summaryrefslogtreecommitdiff
path: root/chapter31
diff options
context:
space:
mode:
authorCliff Click <cliffc@acm.org>2026-11-12 13:16:00 -0800
committerCliff Click <cliffc@acm.org>2026-11-12 13:52:46 -0800
commit467338ee01565234762db8077c067df42c3b40a8 (patch)
tree42c44a77da87c4811b1eb7611d0952dc2c55e022 /chapter31
parent0720fd8ed0aa92248622a9f3c3ebd522b002fd91 (diff)
downloadSimple-467338ee01565234762db8077c067df42c3b40a8.tar.gz
Simple-467338ee01565234762db8077c067df42c3b40a8.zip
Add audio, overhaul makefiles
Adds simple audio support to Simple Overhaul makefiles; remove common boilerplate; make them more uniform
Diffstat (limited to 'chapter31')
-rw-r--r--chapter31/Makefile185
-rw-r--r--chapter31/README.md8
-rw-r--r--chapter31/audio.mk31
-rw-r--r--chapter31/docs/audio.md62
-rw-r--r--chapter31/docs/drawing.md3
-rw-r--r--chapter31/docs/examples/README.md1
-rw-r--r--chapter31/docs/examples/TicTacToeGraphical.smp15
-rw-r--r--chapter31/docs/graphics.md13
-rw-r--r--chapter31/graphics.mk20
-rw-r--r--chapter31/src/main/c/simple_audio.c40
-rw-r--r--chapter31/src/main/c/simple_audio.h16
-rw-r--r--chapter31/src/main/c/simple_miniaudio.c123
-rw-r--r--chapter31/src/main/smp/sys.smp1
-rw-r--r--chapter31/src/main/smp/sys/audio.smp29
-rw-r--r--chapter31/src/test/c/audio_test.c48
-rw-r--r--chapter31/src/test/java/com/seaofnodes/simple/AudioTest.java94
-rw-r--r--chapter31/src/test/java/com/seaofnodes/simple/Chapter25Test.java2
-rw-r--r--chapter31/src/test/java/com/seaofnodes/simple/DrawTest.java3
-rw-r--r--chapter31/src/test/java/com/seaofnodes/simple/StreamIOTest.java1
-rw-r--r--chapter31/src/test/java/com/seaofnodes/simple/TestC.java1
20 files changed, 516 insertions, 180 deletions
diff --git a/chapter31/Makefile b/chapter31/Makefile
index 10717b55..e685b205 100644
--- a/chapter31/Makefile
+++ b/chapter31/Makefile
@@ -1,75 +1,10 @@
-#
-# Makefile expects to run at the project root, and not nested inside anywhere
-#
-# cd $DESK/Simple/chapterXX; make
-#
-#
-# first time only - this is the only thing that hits the Interwebs
-#
-# make lib
-#
-# any time you want to nuke everything from space:
-#
-# make clean tags
-#
-# run the tests
-#
-# make tests
-# make test CLASS=Chapter25Test METHOD=testHelloWorldNoInline
+# Build from this chapter directory; make libs/init prepares the offline cache.
+USE_ISA := 1
+CUSTOM_TESTS := 1
+CUSTOM_RELEASE := 1
+DEFAULT_TARGETS := release tests
+include $(firstword $(wildcard ../build-support/java.mk build-support/java.mk))
-#######################################################
-#
-# Boilerplate because make syntax isn't the best
-#
-
-# Use bash for recipes
-SHELL := /bin/bash
-
-# Remove target on error (no broken leftover files)
-.DELETE_ON_ERROR:
-
-# Keep partial builds but not partial recipes; keeping them speeds up the next `make`
-.NOTINTERMEDIATE:
-
-# for printing variable values
-# usage: make print-VARIABLE
-# > VARIABLE = value_of_variable
-print-% : ; @echo $* = $($*)
-
-# literal space
-space := $() $()
-
-# Decide OS-specific questions
-# jar-file seperator
-ifeq ($(OS),Windows_NT)
- SEP = ;
-else
- SEP = :
-endif
-# Find a reasonable ctags.
-CTAGS = $(shell which ctags)
-# Hack for MacOS: /usr/bin/ctags is unfriendly, so look for ctags from brew
-ifeq ($(UNAME),Darwin)
- CTAGS = $(shell brew list ctags 2> /dev/null | grep bin/ctags)
-endif
-
-# Fun Args to javac. Mostly limit to java8 source definitions, and fairly
-# aggressive lint warnings.
-JAVAC_ARGS = -g
-
-# Source code
-SIMPLE := com/seaofnodes/simple
-SRC := src/main/java
-TST := src/test/java
-CLZDIR:= build/classes
-main_javas := $(wildcard $(SRC)/$(SIMPLE)/*java $(SRC)/$(SIMPLE)/*/*java $(SRC)/$(SIMPLE)/node/cpus/*/*java)
-test_javas := $(wildcard $(TST)/$(SIMPLE)/*java $(TST)/$(SIMPLE)/*/*java)
-simple_driver := $(TST)/$(SIMPLE)/Simple.java
-main_classes := $(patsubst $(SRC)/%java,$(CLZDIR)/main/%class,$(main_javas))
-include $(firstword $(wildcard ../graph/graph.mk graph/graph.mk))
-include $(firstword $(wildcard ../print/print.mk print/print.mk))
-include $(firstword $(wildcard ../isa/isa.mk isa/isa.mk))
-test_classes := $(patsubst $(TST)/%java,$(CLZDIR)/test/%class,$(test_javas))
# These tests do not rely on the stdlib
test_alone := com.seaofnodes.simple.BrainFuckTest com.seaofnodes.simple.MergeSortTest com.seaofnodes.simple.TypeTest
test_raw_nums0 := 01 02 03 04 05 06 07 08 09 10 12 13 14Float 14 15 16 17a 17b 18 19 20 21
@@ -89,59 +24,6 @@ test_cp2 := $(filter-out $(test_raw1) ,$(test_cp1))
test_cp3 := $(filter-out $(test_alone),$(test_cp2))
test_cp4 := $(filter-out com.seaofnodes.simple.Chapter25Test,$(test_cp3))
test_cp := $(filter-out $(test_sys) ,$(test_cp4))
-# All the classes to compile
-classes = $(main_classes) $(test_classes)
-# All the libraries
-libs = $(wildcard lib/*jar)
-jars = $(subst $(space),$(SEP),$(libs))
-
-
-default_targets := TAGS release tests
-# Optionally add ctags to the default target if a reasonable one was found.
-ifneq ($(CTAGS),)
-default_targets += tags
-endif
-
-default: $(default_targets)
-
-.PHONY: build
-build: $(CLZDIR)/main/.mtag
-
-#######################################################
-# Compile Java as a whole source set. javac tracks Java dependencies
-# internally, so compiling only the directly out-of-date .java files can leave
-# stale dependent .class files behind.
-$(CLZDIR)/main/.mtag: $(main_javas)
- @[ -d $(CLZDIR)/main ] || mkdir -p $(CLZDIR)/main
- @# This crap is really just "javac", but with a beautiful error message.
- @# The very very long list of java files is suppressed and counted.
- @# The required output "Note: blah blah deprecated blah" is suppressed.
- $(file > .argsM.txt, $(main_javas))
- @echo "compiling main " `wc -w < .argsM.txt` " files"
- @if ! javac $(JAVAC_ARGS) -cp "$(CLZDIR)/main$(SEP)$(jars)" -sourcepath $(SRC) -d $(CLZDIR)/main @.argsM.txt >& .out.txt ; then \
- cat .out.txt ; \
- exit 1; \
- fi
- @rm -rf .out.txt
- @touch $(CLZDIR)/main/.mtag
- @rm -f .argsM.txt
-
-
-#######################################################
-
-$(CLZDIR)/test/.ttag: $(test_javas) $(isa_test_javas) $(CLZDIR)/main/.mtag
- @[ -d $(CLZDIR)/test ] || mkdir -p $(CLZDIR)/test
- $(file > .argsT.txt, $(test_javas) $(isa_test_javas))
- @echo "compiling test " `wc -w < .argsT.txt` " files"
- @if ! javac $(JAVAC_ARGS) -cp "$(CLZDIR)/test$(SEP)$(CLZDIR)/main$(SEP)$(jars)" -sourcepath $(TST) -d $(CLZDIR)/test @.argsT.txt >& .out.txt ; then \
- cat .out.txt ; \
- exit 1; \
- fi
- @rm -rf .out.txt
- @touch $(CLZDIR)/test/.ttag
- @rm -f .argsT.txt
-
-#######################################################
# Default Simple .o target is build/objs which is where all the test .o's get
# dumped. The default sys search needs to NOT include all the dumped test
@@ -156,6 +38,7 @@ TEST_SYS:= $(OBJS)/lib_$(CPU_ABI)/sys.o
RELEASE_SYS:= $(RELEASE)/$(CPU_ABI)/sys.o
RELEASE_CRT:= $(RELEASE)/$(CPU_ABI)/simple_crt.o
RELEASE_GRAPHICS:= $(RELEASE)/$(CPU_ABI)/simple_graphics.o
+RELEASE_AUDIO:= $(RELEASE)/$(CPU_ABI)/simple_audio.o
RELEASE_ARGS:= $(RELEASE)/$(CPU_ABI)/simple_args.o
C_CALL_CONV:= $(if $(filter win64,$(CALL_CONV)),ms_abi,sysv_abi)
GAME_DIR:= build/examples/$(CPU_ABI)
@@ -184,7 +67,7 @@ $(RELEASE_ARGS): src/main/smp/sys/rt/simple_args.smp $(CLZDIR)/main/.mtag $(simp
@echo "simping " $@
@$(JVM) com.seaofnodes.simple.Simple --cpu $(CPU_PORT) --abi $(CALL_CONV) --norun -o $@ $<
-$(RELEASE_CRT): src/main/c/simple_crt.c $(RELEASE_ARGS) $(RELEASE_GRAPHICS) Makefile
+$(RELEASE_CRT): src/main/c/simple_crt.c $(RELEASE_ARGS) $(RELEASE_GRAPHICS) $(RELEASE_AUDIO) Makefile
@echo "compiling " $@
@[ -d $(dir $@) ] || mkdir -p $(dir $@)
@gcc -c -O2 -DCALL_CONV=$(C_CALL_CONV) -o $@ $<
@@ -196,14 +79,18 @@ $(RELEASE_GRAPHICS): src/main/c/simple_graphics.c src/main/c/simple_graphics.h M
# Optional native graphics backend. Nothing in the default build depends on it.
include graphics.mk
+include audio.mk
+
+$(RELEASE_AUDIO): src/main/c/simple_audio.c src/main/c/simple_audio.h Makefile
+ @mkdir -p $(dir $@)
+ @gcc -c -O2 -Wall -Wextra -o $@ $<
.PHONY: tests_nographics
tests_nographics:
- @SIMPLE_MINIFB=off $(MAKE) tests
+ @SIMPLE_MINIFB=off SIMPLE_MINIAUDIO=off $(MAKE) tests
#######################################################
# Base launch line for JVM tests
-JVM=nice java -ea -cp "$(CLZDIR)/main${SEP}${jars}${SEP}$(CLZDIR)/test"
# Tests that do NOT need sys.smp
tests_raw0: $(CLZDIR)/main/.mtag $(CLZDIR)/test/.ttag $(RELEASE_CRT)
@@ -216,14 +103,14 @@ tests_raw1: $(CLZDIR)/main/.mtag $(CLZDIR)/test/.ttag $(RELEASE_CRT)
@[ -d $(OBJS) ] || mkdir -p $(OBJS)
@$(JVM) org.junit.runner.JUnitCore $(test_raw1)
-# Larger standalone tests, still JUnits, still no sys.smp
-tests_alone: $(CLZDIR)/main/.mtag $(CLZDIR)/test/.ttag $(RELEASE_CRT) $(RELEASE_SYS)
+# Larger regressions, including BrainFuck's standard-library buffer variant.
+tests_alone: $(main_classes) $(test_classes) $(RELEASE_SYS) $(RELEASE_CRT)
@echo "testing " $(test_alone)
@[ -d $(OBJS) ] || mkdir -p $(OBJS)
@$(JVM) org.junit.runner.JUnitCore $(test_alone)
# Tests that DO need sys.smp
-tests_sys: $(CLZDIR)/main/.mtag $(CLZDIR)/test/.ttag $(TEST_SYS) $(RELEASE_CRT)
+tests_sys: $(main_classes) $(test_classes) $(RELEASE_SYS) $(RELEASE_CRT)
@echo "testing " $(test_sys)
@[ -d $(OBJS) ] || mkdir -p $(OBJS)
@$(JVM) org.junit.runner.JUnitCore $(test_sys)
@@ -232,13 +119,9 @@ tests_sys: $(CLZDIR)/main/.mtag $(CLZDIR)/test/.ttag $(TEST_SYS) $(RELEASE_CRT)
CLASS ?= Chapter25Test
METHOD ?=
.PHONY: test
-test: $(CLZDIR)/main/.mtag $(CLZDIR)/test/.ttag $(TEST_SYS) $(RELEASE_SYS) $(RELEASE_CRT)
+test: $(main_classes) $(test_classes) $(RELEASE_SYS) $(RELEASE_CRT)
@$(JVM) com.seaofnodes.simple.TestRunner "$(CLASS)" "$(METHOD)"
-fuzzer: $(CLZDIR)/main/.mtag $(CLZDIR)/test/.ttag
- @echo "fuzzing "
- @$(JVM) org.junit.runner.JUnitCore com.seaofnodes.simple.FuzzerWrap
-
tests: $(CLZDIR)/main/.mtag $(CLZDIR)/test/.ttag tests_raw0 tests_raw1 tests_alone tests_sys fuzzer
@echo "All tests"
@[ -d $(OBJS) ] || mkdir -p $(OBJS)
@@ -256,35 +139,7 @@ build/release/Simple.jar: $(CLZDIR)/main/.mtag $(CLZDIR)/test/.ttag
@jar cfm $@ build/release/MANIFEST.MF -C $(CLZDIR)/main . -C $(CLZDIR)/test . -C $(SRC)/$(SIMPLE) . -C $(TST)/$(SIMPLE) .
-#######################################################
-.PHONY: clean
-clean:
- rm -rf build
- rm -f TAGS
- (find . -name "*~" -exec rm {} \; 2>/dev/null; exit 0)
-
-# Download libs from maven
-lib: lib/junit-4.12.jar lib/hamcrest-core-1.3.jar
-
-# Jars
-lib/junit-4.12.jar:
- @[ -d lib ] || mkdir -p lib
- @(cd lib; wget https://repo1.maven.org/maven2/junit/junit/4.12/junit-4.12.jar)
-
-lib/hamcrest-core-1.3.jar:
- @[ -d lib ] || mkdir -p lib
- @(cd lib; wget https://repo1.maven.org/maven2/org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3.jar)
-
-# Build emacs tags (part of a tasty emacs ide experience)
-.PHONY: tags
-tags: TAGS
-
-TAGS: $(main_javas) $(test_javas)
- @rm -f TAGS
- @$(CTAGS) -e --recurse=yes --fields=+fksaiS $(SRC) $(TST)
-
-# Frozen earlier allocation cohorts, followed by Chapter 25's native tests.
-spill-stats: $(CLZDIR)/test/.ttag $(TEST_SYS) $(RELEASE_SYS) $(RELEASE_CRT)
- @$(JVM) com.seaofnodes.simple.SpillStats
.PHONY: spill-stats
+spill-stats: $(test_classes) $(TEST_SYS) $(RELEASE_SYS) $(RELEASE_CRT)
+ @$(JVM) com.seaofnodes.simple.SpillStats
diff --git a/chapter31/README.md b/chapter31/README.md
index 6b7d9eb7..65c8d787 100644
--- a/chapter31/README.md
+++ b/chapter31/README.md
@@ -12,16 +12,22 @@ The [drawing library](docs/drawing.md) provides a pixel canvas, colors,
rectangles, circles, thick lines, and bitmap labels. The
[graphical tic-tac-toe game](docs/examples/TicTacToeGraphical.smp) uses it for
mouse/keyboard play against the terminal game's CPU strategy.
+The optional [audio library](docs/audio.md) adds soft move sounds and rising
+or falling win/loss cues, played in the background by miniaudio.
Hexadecimal colors (`0xe47b57`) and leading-zero octal font masks (`025755`)
are supported by this chapter's integer literal syntax.
```sh
+make -C chapter31 libs CTAGS= # Once while online (also: init or lib).
make -C chapter31 run-graphical-tictactoe CTAGS=
```
-This explicitly builds the optional backend and opens a window. Use
+This explicitly builds the optional graphics/audio backends and opens a window. Use
`graphical-tictactoe` instead to build the executable without starting it or
requiring MiniFB.
+Dependencies stay cached under `chapter31/lib`, including across `make clean`.
+Only explicit `libs`/`init`/`lib` setup targets access the internet; other
+targets use local files and fail promptly if something needs downloading.
The default build and test suite need no graphics dependencies. See
[optional graphics](docs/graphics.md) for building MiniFB, running the pixel
diff --git a/chapter31/audio.mk b/chapter31/audio.mk
new file mode 100644
index 00000000..4aeeec20
--- /dev/null
+++ b/chapter31/audio.mk
@@ -0,0 +1,31 @@
+# Optional miniaudio, independent of the default build and MiniFB.
+MINIAUDIO_REV := 0.11.23
+MINIAUDIO_SRC := lib/miniaudio-$(MINIAUDIO_REV)
+MINIAUDIO_HEADER := $(MINIAUDIO_SRC)/miniaudio.h
+ifeq ($(OS),Windows_NT)
+ AUDIO_CC := x86_64-w64-mingw32-gcc
+ AUDIO_LIB := $(RELEASE)/$(CPU_ABI)/simple_miniaudio.dll
+ AUDIO_FLAGS := -D_WIN32_WINNT=0x0601
+ AUDIO_LIBS := -lm
+else
+ AUDIO_CC := gcc
+ AUDIO_LIB := $(RELEASE)/$(CPU_ABI)/libsimple_miniaudio.so
+ AUDIO_FLAGS := -fPIC
+ AUDIO_LIBS := -lpthread -lm -ldl
+endif
+.PHONY: audio
+audio: $(AUDIO_LIB)
+.PHONY: test-audio
+test-audio: $(MINIAUDIO_HEADER)
+ @mkdir -p build/objs
+ @$(AUDIO_CC) -O2 -Wall -Wextra $(AUDIO_FLAGS) -I$(MINIAUDIO_SRC) src/test/c/audio_test.c $(AUDIO_LIBS) -o build/objs/audio_test$(if $(filter Windows_NT,$(OS)),.exe,)
+ @build/objs/audio_test$(if $(filter Windows_NT,$(OS)),.exe,)
+lib libs init: $(MINIAUDIO_HEADER)
+
+$(MINIAUDIO_HEADER):
+ @$(call download-library,https://raw.githubusercontent.com/mackron/miniaudio/$(MINIAUDIO_REV)/miniaudio.h)
+$(AUDIO_LIB): $(MINIAUDIO_HEADER) src/main/c/simple_miniaudio.c src/main/c/simple_audio.h audio.mk
+ @echo "building " $@
+ @mkdir -p $(dir $@)
+ @$(AUDIO_CC) -shared -O2 -Wall -Wextra $(AUDIO_FLAGS) -I$(MINIAUDIO_SRC) src/main/c/simple_miniaudio.c $(AUDIO_LIBS) -o $@
+ @sed -n '/^This software is available as a choice of the following licenses/,$$p' $(MINIAUDIO_HEADER) > $(dir $@)miniaudio-LICENSE
diff --git a/chapter31/docs/audio.md b/chapter31/docs/audio.md
new file mode 100644
index 00000000..30817012
--- /dev/null
+++ b/chapter31/docs/audio.md
@@ -0,0 +1,62 @@
+# Optional background audio
+
+`sys.audio` uses [miniaudio](https://github.com/mackron/miniaudio) through an
+optional native C backend. Playback runs on its own thread; the game keeps
+processing input and drawing. No Python, CMake, codec packages, or sound files
+are needed. Default builds/tests never download miniaudio or open a device.
+
+From `chapter31`:
+
+```sh
+make libs CTAGS= # Once while online, or use make init.
+make audio CTAGS=
+make run-graphical-tictactoe CTAGS=
+```
+
+The last command builds both optional backends and runs the game. Accepted
+moves get a quiet 70ms sine boop. A player win gets a 480ms rising C-E-G
+celebration; a CPU win reverses the notes. Invalid input and occupied squares
+are silent. Replay stops any previous cue. Win/loss cues replace the ordinary
+move boop; draws use the ordinary boop.
+
+For direct execution in PowerShell, alongside `SIMPLE_MINIFB`:
+
+```powershell
+$env:SIMPLE_MINIAUDIO = (Resolve-Path build/release/x86_64_v2_win64/simple_miniaudio.dll).Path
+.\build\examples\x86_64_v2_win64\TicTacToeGraphical.exe
+```
+
+Linux uses `libsimple_miniaudio.so` in the corresponding release directory.
+`SIMPLE_MINIAUDIO` must name the full backend path. Unset it or set it to `off`
+for silent play. An unavailable audio device returns `ERROR` and the game
+continues. Audio and graphics can be configured independently.
+
+| Operation | Meaning |
+| --- | --- |
+| `open()` | Open output and generate built-in sounds; `OK` (0) or `ERROR` (-1). Repeated open is safe. |
+| `boop()`, `win()`, `lose()` | Play a built-in cue; same as `play(BOOP/WIN/LOSE)`. |
+| `load(samples)` | Copy `i16[~]` mono PCM at `RATE` (48000Hz); return handle or `ERROR`. |
+| `play(handle)` | Start/restart, replacing the current sound. Return `OK` or `ERROR`. |
+| `stop()` | Stop playback; safe before open/after close. |
+| `playing()` | Whether samples remain to submit; final device buffering may remain. |
+| `close()` | Join the audio thread and free device/buffers; safe to repeat. |
+
+All calls belong on the main/game thread. Load custom sounds at startup:
+there are 28 custom slots, each up to ten seconds, retained until close.
+Custom handles must be reloaded after close/reopen. Signed samples range
+from -32768 to 32767; quiet effects should use much smaller amplitudes.
+Native code copies the array and never retains a Simple heap pointer or calls
+Simple from the audio thread. Playback itself neither allocates nor waits for
+the sound duration. This first interface plays one sound at a time.
+
+`audio.mk` pins miniaudio 0.11.23, cached under `lib/miniaudio-0.11.23/` by
+`make libs` (or `init`; `lib` remains a setup alias). Only these explicit setup
+targets can download dependencies. All builds, runs, and tests use local
+copies, surviving `make clean`; missing cache entries fail promptly with setup
+instructions. Windows uses the existing MinGW-w64 compiler;
+Linux uses GCC and system pthread/math/dl libraries. No audio development
+headers need installing. The upstream header includes its public-domain and
+MIT-0 license options, copied beside the backend as `miniaudio-LICENSE`.
+`make test-audio CTAGS=` builds the backend checks from the local cache
+and runs a real audio thread with miniaudio's silent null
+device; normal tests exercise the loader and game without hardware.
diff --git a/chapter31/docs/drawing.md b/chapter31/docs/drawing.md
index d9d7e624..3fec1f12 100644
--- a/chapter31/docs/drawing.md
+++ b/chapter31/docs/drawing.md
@@ -76,6 +76,9 @@ The explicit backend path follows [the pixel-window instructions](graphics.md).
Passing any argument performs a five-poll, self-closing smoke test.
The original `make tictactoe` still builds the terminal game.
+The graphical game also uses optional [background audio](audio.md): a soft
+boop for accepted moves, rising tones for a player win, and falling tones for
+a CPU win. Bad input is silent. The run target builds/configures both backends.
`make test CLASS=DrawTest CTAGS=` checks raster pixels and complete game turns
without a display. `make tests_nographics CTAGS=` runs the ordinary suite with
the backend disabled.
diff --git a/chapter31/docs/examples/README.md b/chapter31/docs/examples/README.md
index db95487e..a1d81be2 100644
--- a/chapter31/docs/examples/README.md
+++ b/chapter31/docs/examples/README.md
@@ -8,6 +8,7 @@ The [graphical tic-tac-toe](TicTacToeGraphical.smp) uses the Simple
[drawing library](../drawing.md). Run it with
`make run-graphical-tictactoe CTAGS=`; click a cell or press 1–9, R/Space to
replay, and Q/Escape to quit. The terminal game below remains available.
+Optional [background audio](../audio.md) supplies soft move and win/loss cues.
From `chapter31`, build the tic-tac-toe executable (without starting it):
diff --git a/chapter31/docs/examples/TicTacToeGraphical.smp b/chapter31/docs/examples/TicTacToeGraphical.smp
index 7daf6710..b4f8bcf4 100644
--- a/chapter31/docs/examples/TicTacToeGraphical.smp
+++ b/chapter31/docs/examples/TicTacToeGraphical.smp
@@ -7,6 +7,7 @@ val main = { u8[~][] args ->
val board = new u8[9];
_reset(board);
if( sys.gfx.open("Simple tic-tac-toe",screen.width,screen.height) != sys.gfx.OK ) return 1;
+ sys.audio.open(); // Audio is optional; failure leaves the game silent.
_draw(screen,board,-1);
int result = sys.gfx.present(screen.pixels);
bool mouseHeld = false, keyHeld = false, replayHeld = false;
@@ -20,7 +21,7 @@ val main = { u8[~][] args ->
int square = _square(sys.gfx.mouseX(),sys.gfx.mouseY());
bool dirty = square!=hover;
hover = square;
- if( replay && !replayHeld ) { _reset(board); dirty=true; }
+ if( replay && !replayHeld ) { sys.audio.stop(); _reset(board); dirty=true; }
bool digit = false;
int choice = down && !mouseHeld ? square : -1;
for( int i=0; i<9; i++ ) {
@@ -30,7 +31,10 @@ val main = { u8[~][] args ->
if( !keyHeld ) choice=i;
}
}
- if( !(replay && !replayHeld) && _move(board,choice) ) dirty=true;
+ if( !(replay && !replayHeld) && _move(board,choice) ) {
+ sys.audio.play(_sound(board));
+ dirty=true;
+ }
mouseHeld = down;
keyHeld = digit;
replayHeld = replay;
@@ -40,10 +44,17 @@ val main = { u8[~][] args ->
}
if( args#>1 && ++frames==5 ) break;
}
+ sys.audio.close();
sys.gfx.close();
return result==sys.gfx.ERROR ? 1 : 0;
};
+// Called only for an accepted move; invalid input never requests a sound.
+val _sound = { u8[~] board ->
+ int winner = _winner(board);
+ return winner=='X' ? sys.audio.WIN : winner=='O' ? sys.audio.LOSE : sys.audio.BOOP;
+};
+
val _reset = { u8[] board ->
for( int i=0; i<9; i++ ) board[i]=' ';
};
diff --git a/chapter31/docs/graphics.md b/chapter31/docs/graphics.md
index fb3972ee..2394a401 100644
--- a/chapter31/docs/graphics.md
+++ b/chapter31/docs/graphics.md
@@ -7,12 +7,14 @@ provides a window, input, and pixel presentation. The first interface is
The [drawing library and graphical tic-tac-toe](drawing.md) build on this pixel
interface. `make run-graphical-tictactoe CTAGS=` builds the optional backend and
opens the game; `make graphical-tictactoe CTAGS=` only builds its executable.
+The game run target also builds optional [background audio](audio.md).
## Default: no graphics dependency
From `chapter31`, the usual `make release`, `make tests`, and `make tictactoe`
need no MiniFB, graphics headers, OpenGL, CMake, or running display. Nothing
-downloads MiniFB unless you explicitly request `make graphics`.
+downloads dependencies unless you explicitly request `make libs` or `make init`
+(`make lib` remains a setup alias). Build and run targets never use the network.
`make tests_nographics CTAGS=` runs the entire ordinary suite with
`SIMPLE_MINIFB=off`. This includes the missing-backend tests, which never open
@@ -29,12 +31,14 @@ the process. Non-graphics programs ignore even a broken graphics configuration.
From `chapter31`:
```sh
+make libs CTAGS= # Once while online; fills the persistent lib/ cache.
make graphics graphics-example CTAGS=
make run-graphics CTAGS=
```
-`graphics` downloads the revision pinned in [graphics.mk](../graphics.mk) into
-ignored `build/deps/minifb` and builds only its C framebuffer backend. Windows
+`libs` downloads the revision pinned in [graphics.mk](../graphics.mk) into
+ignored `lib/minifb-<revision>.tar.gz` and extracts it under `lib/`.
+`graphics` builds only its C framebuffer backend from these local sources. Windows
uses the MinGW-w64 GCC compiler (`x86_64-w64-mingw32-gcc`) and GDI; the rest of
Simple still uses the existing Cygwin GCC. Linux uses GCC and X11 (`libx11-dev`
on Ubuntu), including XWayland on a Wayland desktop. OpenGL, the C++ callback
@@ -50,6 +54,9 @@ Outputs:
`MiniFB-LICENSE` is copied alongside the backend; include it when distributing
the library. MiniFB sources remain outside the tracked Simple sources.
+The cache survives `make clean`. Editing a makefile or rebuilding a backend
+does not fetch or check GitHub. Missing dependencies fail promptly with
+instructions to run `make libs` while online.
`graphics-example` alone builds the executable without requiring MiniFB. It
also demonstrates the diagnostic and exit status 1 when graphics is absent.
diff --git a/chapter31/graphics.mk b/chapter31/graphics.mk
index 719c5fcd..9ede649d 100644
--- a/chapter31/graphics.mk
+++ b/chapter31/graphics.mk
@@ -1,7 +1,8 @@
# Optional MiniFB build, pinned independently of Simple's default build.
# A C-only GDI/X11 subset: no OpenGL, C++ wrapper, examples, or CMake required.
MINIFB_REV := f92be8e966f194004853c10196e704f4510f58d4
-MINIFB_SRC := build/deps/minifb
+MINIFB_SRC := lib/minifb-$(MINIFB_REV)
+MINIFB_ARCHIVE := lib/minifb-$(MINIFB_REV).tar.gz
MINIFB_STAMP := $(MINIFB_SRC)/.simple-$(MINIFB_REV)
MINIFB_COMMON := MiniFB_common MiniFB_cpu_x86 MiniFB_internal MiniFB_stretch \
MiniFB_stretch_sse2 MiniFB_stretch_avx2 MiniFB_stretch_neon MiniFB_timer MiniFB_utf8
@@ -29,15 +30,18 @@ graphical-tictactoe: $(GRAPHICAL_TICTACTOE)
$(GRAPHICAL_TICTACTOE): docs/examples/TicTacToeGraphical.smp $(CLZDIR)/test/.ttag $(RELEASE_SYS) $(RELEASE_CRT) graphics.mk
@$(JVM) com.seaofnodes.simple.Simple --link --cpu $(CPU_PORT) --abi $(CALL_CONV) -L $(dir $(RELEASE_SYS)) -o $(GAME_DIR)/TicTacToeGraphical.o $<
-run-graphical-tictactoe: graphics graphical-tictactoe
- SIMPLE_MINIFB="$(abspath $(GRAPHICS_LIB))" $(GRAPHICAL_TICTACTOE)
+run-graphical-tictactoe: graphics audio graphical-tictactoe
+ SIMPLE_MINIFB="$(abspath $(GRAPHICS_LIB))" SIMPLE_MINIAUDIO="$(abspath $(AUDIO_LIB))" $(GRAPHICAL_TICTACTOE)
graphics: $(GRAPHICS_LIB)
-$(MINIFB_STAMP): graphics.mk
- @mkdir -p $(dir $(MINIFB_SRC))
- @test -d $(MINIFB_SRC)/.git || git clone --no-checkout https://github.com/emoon/minifb.git $(MINIFB_SRC)
- @git -C $(MINIFB_SRC) fetch --depth 1 origin $(MINIFB_REV)
- @git -C $(MINIFB_SRC) checkout --detach $(MINIFB_REV)
+lib libs init: $(MINIFB_STAMP)
+
+$(MINIFB_ARCHIVE):
+ @$(call download-library,https://codeload.github.com/emoon/minifb/tar.gz/$(MINIFB_REV))
+
+$(MINIFB_STAMP): $(MINIFB_ARCHIVE)
+ @mkdir -p $(MINIFB_SRC)
+ @tar -xzf $< --strip-components=1 -C $(MINIFB_SRC)
@touch $@
$(GRAPHICS_LIB): $(MINIFB_STAMP) src/main/c/simple_minifb.c src/main/c/simple_graphics.h graphics.mk
diff --git a/chapter31/src/main/c/simple_audio.c b/chapter31/src/main/c/simple_audio.c
new file mode 100644
index 00000000..b8ed62de
--- /dev/null
+++ b/chapter31/src/main/c/simple_audio.c
@@ -0,0 +1,40 @@
+#include "simple_audio.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <dlfcn.h>
+
+static const struct simple_audio_api *api;
+static void *library;
+
+int32_t simple_audio_open(void) {
+ const char *path = getenv("SIMPLE_MINIAUDIO");
+ if (path && strcmp(path,"off")==0) return -1;
+ if (!api) {
+ if (!path || !*path) return -1; // Optional: games may run silently.
+ library = dlopen(path,RTLD_NOW | RTLD_LOCAL);
+ if (!library) {
+ fprintf(stderr,"Simple audio: cannot load backend '%s': %s\n",path,dlerror());
+ return -1;
+ }
+ const struct simple_audio_api *(*get_api)(void) =
+ (const struct simple_audio_api *(*)(void))dlsym(library,"simple_miniaudio_api");
+ const struct simple_audio_api *candidate = get_api ? get_api() : NULL;
+ if (!candidate || candidate->version!=SIMPLE_AUDIO_VERSION || !candidate->open ||
+ !candidate->load || !candidate->play || !candidate->stop ||
+ !candidate->playing || !candidate->close) {
+ fprintf(stderr,"Simple audio: incompatible backend; rebuild with make audio.\n");
+ dlclose(library);
+ library=NULL;
+ return -1;
+ }
+ api=candidate;
+ atexit(api->close);
+ }
+ return api->open();
+}
+int32_t simple_audio_load(const int16_t *samples, uint32_t count) { return api ? api->load(samples,count) : -1; }
+int32_t simple_audio_play(int32_t sound) { return api ? api->play(sound) : -1; }
+int32_t simple_audio_stop(void) { return api ? api->stop() : 0; }
+int32_t simple_audio_playing(void) { return api ? api->playing() : 0; }
+int32_t simple_audio_close(void) { if (api) api->close(); return 0; }
diff --git a/chapter31/src/main/c/simple_audio.h b/chapter31/src/main/c/simple_audio.h
new file mode 100644
index 00000000..77cce530
--- /dev/null
+++ b/chapter31/src/main/c/simple_audio.h
@@ -0,0 +1,16 @@
+#ifndef SIMPLE_AUDIO_H
+#define SIMPLE_AUDIO_H
+#include <stdint.h>
+
+// Main-thread API. Samples are copied; no Simple heap pointer is retained.
+struct simple_audio_api {
+ int32_t version;
+ int32_t (*open)(void);
+ int32_t (*load)(const int16_t *, uint32_t);
+ int32_t (*play)(int32_t);
+ int32_t (*stop)(void);
+ int32_t (*playing)(void);
+ void (*close)(void);
+};
+#define SIMPLE_AUDIO_VERSION 1
+#endif
diff --git a/chapter31/src/main/c/simple_miniaudio.c b/chapter31/src/main/c/simple_miniaudio.c
new file mode 100644
index 00000000..03dbadd7
--- /dev/null
+++ b/chapter31/src/main/c/simple_miniaudio.c
@@ -0,0 +1,123 @@
+#include "simple_audio.h"
+#define MA_NO_DECODING
+#define MA_NO_ENCODING
+#define MA_NO_RESOURCE_MANAGER
+#define MA_NO_NODE_GRAPH
+#define MA_NO_ENGINE
+#define MINIAUDIO_IMPLEMENTATION
+#include <miniaudio.h>
+#include <math.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+
+#define RATE 48000
+#define SLOTS 32
+static ma_device device;
+static ma_mutex mutex;
+static int opened, active;
+static uint32_t cursor;
+static struct { int16_t *pcm; uint32_t count; } sounds[SLOTS];
+
+// Only native-owned immutable PCM is read on the audio thread. The lock covers
+// a bounded copy, never allocation, synthesis, device calls, or Simple code.
+static void output(ma_device *unused, void *out, const void *in, ma_uint32 frames) {
+ (void)unused; (void)in;
+ memset(out,0,frames*sizeof(int16_t));
+ ma_mutex_lock(&mutex);
+ if (active) {
+ uint32_t count=sounds[active].count-cursor;
+ if (count>frames) count=frames;
+ memcpy(out,sounds[active].pcm+cursor,count*sizeof(int16_t));
+ cursor+=count;
+ if (cursor==sounds[active].count) active=0;
+ }
+ ma_mutex_unlock(&mutex);
+}
+static int32_t load(const int16_t *pcm, uint32_t count) {
+ if (!opened || !pcm || !count || count>RATE*10) return -1;
+ int slot;
+ for (slot=4; slot<SLOTS && sounds[slot].pcm; ++slot) {}
+ if (slot==SLOTS) return -1;
+ int16_t *copy=malloc(count*sizeof(*copy));
+ if (!copy) return -1;
+ memcpy(copy,pcm,count*sizeof(*copy));
+ ma_mutex_lock(&mutex);
+ sounds[slot].pcm=copy; sounds[slot].count=count;
+ ma_mutex_unlock(&mutex);
+ return slot;
+}
+static int32_t play(int32_t sound) {
+ if (!opened || sound<=0 || sound>=SLOTS || !sounds[sound].pcm) return -1;
+ ma_mutex_lock(&mutex);
+ active=sound; cursor=0;
+ ma_mutex_unlock(&mutex);
+ return 0;
+}
+static int32_t stop(void) {
+ if (opened) { ma_mutex_lock(&mutex); active=0; ma_mutex_unlock(&mutex); }
+ return 0;
+}
+static int32_t playing(void) {
+ if (!opened) return 0;
+ ma_mutex_lock(&mutex);
+ int result=active!=0;
+ ma_mutex_unlock(&mutex);
+ return result;
+}
+static void close_audio(void) {
+ if (!opened) return;
+ ma_device_uninit(&device); // Joins callback before freeing buffers/mutex.
+ ma_mutex_uninit(&mutex);
+ for (int i=1;i<SLOTS;++i) {
+ free(sounds[i].pcm); sounds[i].pcm=NULL; sounds[i].count=0;
+ }
+ opened=0; active=0; cursor=0;
+}
+static int tone(int slot, int descending) {
+ uint32_t note=slot==1 ? RATE*7/100 : RATE*16/100;
+ int notes=slot==1 ? 1 : 3;
+ sounds[slot].count=note*notes;
+ sounds[slot].pcm=calloc(note*notes,sizeof(int16_t));
+ if (!sounds[slot].pcm) return -1;
+ const double pitches[3]={523.251,659.255,783.991};
+ for (int n=0;n<notes;++n) {
+ double hz=slot==1 ? 440.0 : pitches[descending ? 2-n : n];
+ for (uint32_t i=0;i<note;++i) {
+ double t=(double)i/note;
+ double envelope=sin(3.141592653589793*t);
+ sounds[slot].pcm[n*note+i]=(int16_t)(3200*envelope*envelope*sin(6.283185307179586*hz*i/RATE));
+ }
+ }
+ return 0;
+}
+static int32_t open_audio(void) {
+ if (opened) return 0;
+ if (ma_mutex_init(&mutex)!=MA_SUCCESS) return -1;
+ ma_device_config config=ma_device_config_init(ma_device_type_playback);
+ config.playback.format=ma_format_s16;
+ config.playback.channels=1;
+ config.sampleRate=RATE;
+ config.dataCallback=output;
+#ifdef SIMPLE_AUDIO_TEST_NULL
+ ma_backend backend=ma_backend_null;
+ ma_result result=ma_device_init_ex(&backend,1,NULL,&config,&device);
+#else
+ ma_result result=ma_device_init(NULL,&config,&device);
+#endif
+ if (result!=MA_SUCCESS) {
+ ma_mutex_uninit(&mutex);
+ fprintf(stderr,"Simple audio: no playback device (%d); continuing silently.\n",result);
+ return -1;
+ }
+ opened=1;
+ if (tone(1,0) || tone(2,0) || tone(3,1) || ma_device_start(&device)!=MA_SUCCESS) {
+ close_audio(); return -1;
+ }
+ return 0;
+}
+static const struct simple_audio_api api={SIMPLE_AUDIO_VERSION,open_audio,load,play,stop,playing,close_audio};
+#ifdef _WIN32
+__declspec(dllexport)
+#endif
+const struct simple_audio_api *simple_miniaudio_api(void) { return &api; }
diff --git a/chapter31/src/main/smp/sys.smp b/chapter31/src/main/smp/sys.smp
index 3ef19099..40a4b955 100644
--- a/chapter31/src/main/smp/sys.smp
+++ b/chapter31/src/main/smp/sys.smp
@@ -2,6 +2,7 @@
// top-level default standard library import
val adt = adt; // Abstract Data Types
+val audio = audio; // Optional background sound (miniaudio)
val ary = ary; // Array utilities
val aryi64 = aryi64; // Variable sized array of i64
val aryu8 = aryu8; // Variable sized array of u8
diff --git a/chapter31/src/main/smp/sys/audio.smp b/chapter31/src/main/smp/sys/audio.smp
new file mode 100644
index 00000000..89e6dfa9
--- /dev/null
+++ b/chapter31/src/main/smp/sys/audio.smp
@@ -0,0 +1,29 @@
+// Optional background audio. All API calls belong on the game/main thread.
+int OK = 0;
+int ERROR = -1;
+int BOOP = 1;
+int WIN = 2;
+int LOSE = 3;
+int RATE = 48000;
+{ i32 } simple_audio_open = "C";
+{ i64 u32 -> i32 } simple_audio_load = "C";
+{ i32 -> i32 } simple_audio_play = "C";
+{ i32 } simple_audio_stop = "C";
+{ i32 } simple_audio_playing = "C";
+{ i32 } simple_audio_close = "C";
+// Missing/disabled backend returns ERROR quietly; the game may remain silent.
+val open = { -> simple_audio_open(); };
+// Mono signed 16-bit PCM at RATE, up to ten seconds. Copies into native memory.
+// Load at startup: up to 28 custom handles, valid until close, then reload.
+val load = { i16[~] samples ->
+ i64 ptr = samples;
+ simple_audio_load(ptr,samples#);
+};
+// Starts/restarts immediately, replacing the previous sound; never waits for it.
+val play = { int sound -> simple_audio_play(sound); };
+val boop = { -> simple_audio_play(BOOP); };
+val win = { -> simple_audio_play(WIN); };
+val lose = { -> simple_audio_play(LOSE); };
+val stop = { -> simple_audio_stop(); };
+val playing = { -> simple_audio_playing(); };
+val close = { -> simple_audio_close(); };
diff --git a/chapter31/src/test/c/audio_test.c b/chapter31/src/test/c/audio_test.c
new file mode 100644
index 00000000..f82504c3
--- /dev/null
+++ b/chapter31/src/test/c/audio_test.c
@@ -0,0 +1,48 @@
+// Explicit optional integration checks: real miniaudio thread, silent device.
+#define SIMPLE_AUDIO_TEST_NULL
+#include "../../main/c/simple_miniaudio.c"
+#include <assert.h>
+
+int main(void) {
+ assert(api.play(1)==-1 && api.playing()==0);
+ assert(api.stop()==0);
+ api.close();
+ for (int pass=0;pass<2;++pass) {
+ assert(api.open()==0 && api.open()==0);
+ assert(api.load(NULL,1)==-1);
+ int16_t pcm[RATE]={0};
+ assert(api.load(pcm,0)==-1 && api.load(pcm,RATE*10+1)==-1);
+ int sound=api.load(pcm,RATE);
+ assert(sound==4);
+ pcm[0]=12345;
+ assert(sounds[sound].pcm[0]==0);
+ assert(api.play(-1)==-1 && api.play(0)==-1 && api.play(SLOTS)==-1);
+ assert(api.play(sound)==0 && api.playing());
+ // A one-second sound returns while playback is still in progress.
+ assert(api.stop()==0 && !api.playing());
+ for (int cue=1;cue<=3;++cue) {
+ assert(api.play(cue)==0);
+ int elapsed=0;
+ while (api.playing() && elapsed<2000) { ma_sleep(10); elapsed+=10; }
+ assert(!api.playing());
+ }
+ for (int i=5;i<SLOTS;++i) assert(api.load(pcm,1)==i);
+ assert(api.load(pcm,1)==-1);
+ assert(api.play(sound)==0);
+ api.close(); // Join during playback, then reopen next pass.
+ api.close();
+ assert(api.play(sound)==-1 && !api.playing());
+ }
+ // The loss cue reverses exactly the same three softly enveloped notes.
+ assert(tone(1,0)==0 && tone(2,0)==0 && tone(3,1)==0);
+ uint32_t note=RATE*16/100;
+ for (int n=0;n<3;++n)
+ assert(memcmp(sounds[2].pcm+n*note,sounds[3].pcm+(2-n)*note,note*sizeof(int16_t))==0);
+ for (int i=1;i<=3;++i) {
+ assert(sounds[i].pcm[0]==0);
+ for (uint32_t j=0;j<sounds[i].count;++j) assert(abs(sounds[i].pcm[j])<=3200);
+ free(sounds[i].pcm); sounds[i].pcm=NULL;
+ }
+ puts("audio native checks passed");
+ return 0;
+}
diff --git a/chapter31/src/test/java/com/seaofnodes/simple/AudioTest.java b/chapter31/src/test/java/com/seaofnodes/simple/AudioTest.java
new file mode 100644
index 00000000..db8542d0
--- /dev/null
+++ b/chapter31/src/test/java/com/seaofnodes/simple/AudioTest.java
@@ -0,0 +1,94 @@
+package com.seaofnodes.simple;
+
+import com.seaofnodes.simple.util.Ary;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.charset.StandardCharsets;
+import java.util.concurrent.TimeUnit;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+// Loader and Simple/C ABI checks: no miniaudio download or audio device.
+public class AudioTest {
+ private static String missing, playback;
+
+ @BeforeClass public static void compilePrograms() throws Exception {
+ var paths=new Ary<>(new String[]{TestC.RELEASE_SYS_DIR});
+ missing=TestC.compile("""
+ val main = { ->
+ if( sys.audio.open()!=sys.audio.ERROR ) return 1;
+ if( sys.audio.boop()!=sys.audio.ERROR || sys.audio.playing() ) return 2;
+ sys.audio.stop(); sys.audio.close(); sys.audio.close();
+ sys.io.p("silent fallback\\n");
+ return 0;
+ };
+ ""","audio_missing",paths,TestC.CALL_CONVENTION,null,null,-1);
+ playback=TestC.compile("""
+ val main = { ->
+ if( sys.audio.open()!=sys.audio.OK ) return 1;
+ val pcm = new i16[3];
+ pcm[0]=-32768; pcm[1]=123; pcm[2]=32767;
+ int sound = sys.audio.load(pcm);
+ if( sound!=4 || sys.audio.play(sound)!=0 || !sys.audio.playing() ) return 2;
+ if( sys.audio.boop()!=0 || sys.audio.win()!=0 || sys.audio.lose()!=0 ) return 3;
+ sys.audio.stop();
+ if( sys.audio.playing() ) return 4;
+ sys.audio.close();
+ return 0;
+ };
+ ""","audio_playback",paths,TestC.CALL_CONVENTION,null,null,-1);
+ }
+
+ private static String run(String exe, String backend) throws Exception {
+ ProcessBuilder pb=new ProcessBuilder(exe).redirectErrorStream(true);
+ if( backend==null ) pb.environment().remove("SIMPLE_MINIAUDIO");
+ else pb.environment().put("SIMPLE_MINIAUDIO",backend);
+ Process child=pb.start();
+ try {
+ assertTrue("audio program timed out",child.waitFor(10,TimeUnit.SECONDS));
+ String out=new String(child.getInputStream().readAllBytes(),StandardCharsets.UTF_8);
+ assertEquals(out,0,child.exitValue());
+ return out;
+ } finally { if( child.isAlive() ) child.destroyForcibly(); }
+ }
+
+ @Test public void silentFallback() throws Exception {
+ assertEquals("silent fallback\n",run(missing,null));
+ assertEquals("silent fallback\n",run(missing,"off"));
+ assertTrue(run(missing,"no-such-miniaudio-backend").contains("cannot load backend"));
+ }
+
+ @Test public void nativeBoundary() throws Exception {
+ Path source=Path.of("build/objs/audio_stub.c");
+ Path library=Path.of("build/objs/audio_stub"+(TestC.OS.startsWith("Windows") ? ".dll" : ".so"));
+ Files.writeString(source,"""
+ #include "simple_audio.h"
+ static int active;
+ static int32_t open_audio(void) { return 0; }
+ static int32_t load(const int16_t *p, uint32_t n) {
+ return n==3 && p[0]==-32768 && p[1]==123 && p[2]==32767 ? 4 : -1;
+ }
+ static int32_t play(int32_t cue) { active=1; return cue>=1 && cue<=4 ? 0 : -1; }
+ static int32_t stop(void) { active=0; return 0; }
+ static int32_t playing(void) { return active; }
+ static void close_audio(void) { active=0; }
+ static const struct simple_audio_api api={1,open_audio,load,play,stop,playing,close_audio};
+ const struct simple_audio_api *simple_miniaudio_api(void) { return &api; }
+ """);
+ TestC.exec(30,"gcc","-shared","-fPIC","-Isrc/main/c",source.toString(),"-o",library.toString());
+ assertEquals("",run(playback,library.toAbsolutePath().toString()));
+ }
+
+ @Test public void incompatibleBackend() throws Exception {
+ Path source=Path.of("build/objs/audio_bad.c");
+ Path library=Path.of("build/objs/audio_bad"+(TestC.OS.startsWith("Windows") ? ".dll" : ".so"));
+ Files.writeString(source,"""
+ #include "simple_audio.h"
+ static const struct simple_audio_api api={999};
+ const struct simple_audio_api *simple_miniaudio_api(void) { return &api; }
+ """);
+ TestC.exec(30,"gcc","-shared","-fPIC","-Isrc/main/c",source.toString(),"-o",library.toString());
+ assertTrue(run(missing,library.toAbsolutePath().toString()).contains("incompatible backend"));
+ }
+}
diff --git a/chapter31/src/test/java/com/seaofnodes/simple/Chapter25Test.java b/chapter31/src/test/java/com/seaofnodes/simple/Chapter25Test.java
index 3b71bd2a..7f2b4a77 100644
--- a/chapter31/src/test/java/com/seaofnodes/simple/Chapter25Test.java
+++ b/chapter31/src/test/java/com/seaofnodes/simple/Chapter25Test.java
@@ -477,7 +477,7 @@ public class Chapter25Test {
// Software drawing and the optional native graphics interface.
assertArrayEquals(new String[]{"sys/adt", "sys/ary",
- "sys/aryi64", "sys/aryu8", "sys/char", "sys/draw", "sys/gfx", "sys/io", "sys/libc", "sys/rt", "sys/scan", "sys/text"},sys_elf._deps);
+ "sys/aryi64", "sys/aryu8", "sys/audio", "sys/char", "sys/draw", "sys/gfx", "sys/io", "sys/libc", "sys/rt", "sys/scan", "sys/text"},sys_elf._deps);
assertArrayEquals(new String[]{"sys"},sys_elf._units);
assertSame("class:sys" ,sys_elf._clz._name);
}
diff --git a/chapter31/src/test/java/com/seaofnodes/simple/DrawTest.java b/chapter31/src/test/java/com/seaofnodes/simple/DrawTest.java
index b3e8edd0..6eb261f1 100644
--- a/chapter31/src/test/java/com/seaofnodes/simple/DrawTest.java
+++ b/chapter31/src/test/java/com/seaofnodes/simple/DrawTest.java
@@ -75,12 +75,14 @@ public class DrawTest {
_reset(board);
if( _square(48,168)!=0 || _square(551,671)!=8 || _square(552,400)!=-1 || _square(100,167)!=-1 ) return 1;
if( !_move(board,4) || board[4]!='X' || board[0]!='O' ) return 2;
+ if( _sound(board)!=sys.audio.BOOP ) return 10;
if( _move(board,4) || _move(board,0) || _move(board,-1) || _move(board,9) ) return 3;
val moves = "1879";
_reset(board);
for( int i=0; i<moves#; i++ )
if( !_move(board,moves[i]-'1') ) return 4;
if( _winner(board)!='X' || _move(board,1) ) return 5;
+ if( _sound(board)!=sys.audio.WIN ) return 11;
val screen = new sys.draw.Canvas(600,780);
_draw(screen,board,-1);
if( screen.pixels[252*600+132]==screen.pixels[0] ) return 6;
@@ -91,6 +93,7 @@ public class DrawTest {
_reset(board);
_move(board,0); _move(board,1); _move(board,3);
if( _winner(board)!='O' ) return 8;
+ if( _sound(board)!=sys.audio.LOSE ) return 12;
_draw(screen,board,-1);
_reset(board);
if( _finished(board) ) return 9;
diff --git a/chapter31/src/test/java/com/seaofnodes/simple/StreamIOTest.java b/chapter31/src/test/java/com/seaofnodes/simple/StreamIOTest.java
index 2aa2e3da..e47cd929 100644
--- a/chapter31/src/test/java/com/seaofnodes/simple/StreamIOTest.java
+++ b/chapter31/src/test/java/com/seaofnodes/simple/StreamIOTest.java
@@ -132,6 +132,7 @@ public class StreamIOTest extends TestC {
gcc.add(runtimeObject("simple_crt"));
gcc.add(runtimeObject("simple_args"));
gcc.add(runtimeObject("simple_graphics"));
+ gcc.add(runtimeObject("simple_audio"));
if( !OS.startsWith("Windows") ) gcc.add("-ldl");
gcc.addAll(new String[]{"-lm","-o",exe});
exec(TEST_TIMEOUT_SECONDS,gcc.asAry());
diff --git a/chapter31/src/test/java/com/seaofnodes/simple/TestC.java b/chapter31/src/test/java/com/seaofnodes/simple/TestC.java
index 73795111..741ee13b 100644
--- a/chapter31/src/test/java/com/seaofnodes/simple/TestC.java
+++ b/chapter31/src/test/java/com/seaofnodes/simple/TestC.java
@@ -192,6 +192,7 @@ public abstract class TestC {
params.addAll(objects);
// The loader has no MiniFB dependency and opens nothing until gfx.open.
params.add(runtimeObject("simple_graphics"));
+ params.add(runtimeObject("simple_audio"));
if( !OS.startsWith("Windows") ) params.add("-ldl");
// Standalone Simple programs export `simple_main`; the small C
// runtime owns native main and calls the Simple argument converter