diff options
| author | Cliff Click <cliffc@acm.org> | 2026-12-04 14:08:57 -0800 |
|---|---|---|
| committer | Cliff Click <cliffc@acm.org> | 2026-12-04 14:08:57 -0800 |
| commit | fd21b1a62f0fb1a0efd503769b2e5f3a81747af0 (patch) | |
| tree | 76946e265ab2bba775c4124b5b07cb52706a9724 /chapter33/src/main/smp/sys | |
| parent | 7be87ff4db692a392af1c68abe7752a1da55637f (diff) | |
| download | Simple-fd21b1a62f0fb1a0efd503769b2e5f3a81747af0.tar.gz Simple-fd21b1a62f0fb1a0efd503769b2e5f3a81747af0.zip | |
Start chapter 33 again from the green chapter 32 baseline
Copy the completed chapter 32 snapshot into chapter33 and register the new Maven and IDE module. Update chapter paths and introductory documentation; retain the chapter 32 compiler behavior. Preserve the previous memory-management attempt on ch33_wip for selective follow-up changes.
Validation: make -k -j8 tests passes with 819 JUnit test executions, including all four lattice shards and native/library integration. git diff --cached --check passes.
Diffstat (limited to 'chapter33/src/main/smp/sys')
26 files changed, 1782 insertions, 0 deletions
diff --git a/chapter33/src/main/smp/sys/adt.smp b/chapter33/src/main/smp/sys/adt.smp new file mode 100644 index 00000000..a4fe40bf --- /dev/null +++ b/chapter33/src/main/smp/sys/adt.smp @@ -0,0 +1,3 @@ + +// Abstract data types. +val bitset = bitset; diff --git a/chapter33/src/main/smp/sys/adt/bitset.smp b/chapter33/src/main/smp/sys/adt/bitset.smp new file mode 100644 index 00000000..a51a63e1 --- /dev/null +++ b/chapter33/src/main/smp/sys/adt/bitset.smp @@ -0,0 +1,57 @@ + +// A set of non-negative integers, represented one bit per value. +struct bitset { + i64[] !_bits; + + new bitset = { -> + _bits = new i64[1]; + }; + + // Return 0 for missing, non-zero for true + val get = { int bit -> + if( (bit >> 6) >= _bits# ) return false; + i64 mask = 1 << (bit & 63); + return (_bits[bit >> 6] & mask); + }; + + val _grow = { int bit -> + int x = bit >> 6; + int len = _bits#; + if( x < len ) return self; + while( x >= len ) len *= 2; + var bits = new i64[len]; + for( int i = 0; i < _bits#; i++ ) + bits[i] = _bits[i]; + _bits = bits; + return self; + }; + + // Set + val set = { int bit -> + i64 mask = 1 << (bit & 63); + _grow(bit)._bits[bit >> 6] |= mask; + return self; + }; + + // Test and set + val tset = { int bit -> + int idx = bit >> 6; + i64 mask = 1 << (bit & 63); + if( _grow(bit)._bits[idx] & mask ) + return true; // Already set + _bits[idx] |= mask; + return false; // Was false (and now set) + }; + + val clr = { int bit -> + if( (bit >> 6) >= _bits# ) return self; + i64 mask = 1 << (bit & 63); + _bits[bit >> 6] &= (mask ^ -1); + return self; + }; + + val clear = { -> + for( int i = 0; i < _bits#; i++ ) _bits[i] = 0; + return self; + }; +}; diff --git a/chapter33/src/main/smp/sys/ary.smp b/chapter33/src/main/smp/sys/ary.smp new file mode 100644 index 00000000..b94ffa8f --- /dev/null +++ b/chapter33/src/main/smp/sys/ary.smp @@ -0,0 +1,40 @@ + +// Array utilities + +// Geometric growth without wrapping a u32 length. Zero means too large. +val capacity = { u32 current, i64 needed -> + if( needed < 0 || needed > sys.integer.MAX_U32 ) return 0; + if( needed <= current ) return current; + i64 size = current ? current : 1; + while( size < needed ) { + size *= 2; + if( size > sys.integer.MAX_U32 ) size = sys.integer.MAX_U32; + } + u32 result = size; + return result; +}; + +// Copy byte array contents. Copies the shorter of the buffers and len +val copy = { u8[] dst, u32 doff, u8[~] src, u32 soff, u32 len -> + if( doff > dst# || soff > src# ) return dst; + if( len > dst# - doff ) len = dst# - doff; + if( len > src# - soff ) len = src# - soff; + for( u32 i = 0; i < len; i++ ) + dst[i+doff] = src[i+soff]; + return dst; +}; + +// Compare lexigraphically array contents. Compares up to shorter array or +// len. Returns <0 or >0 for first non-matching byte. Returns <0 or >0 for +// the larger array after that, or 0 if both arrays are fully equal. +val cmp = { u8[~] src1, u32 off1, u8[~] src2, u32 off2, u32 len -> + u32 left1 = off1 >= src1# ? 0 : src1# - off1; + u32 left2 = off2 >= src2# ? 0 : src2# - off2; + u32 len1 = len > left1 ? left1 : len; + u32 len2 = len > left2 ? left2 : len; + u32 max = len1 > len2 ? len2 : len1; + for( u32 i = 0; i < max; i++ ) + if( src1[off1+i] != src2[off2+i] ) + return src1[off1+i] - src2[off2+i]; // Bytes determine compare + return len1 - len2; // Length determines compare +}; diff --git a/chapter33/src/main/smp/sys/aryi64.smp b/chapter33/src/main/smp/sys/aryi64.smp new file mode 100644 index 00000000..aba1b459 --- /dev/null +++ b/chapter33/src/main/smp/sys/aryi64.smp @@ -0,0 +1,85 @@ + +// Ary/Vector of i64s +struct aryi64 { + u32 !len = 0; + i64[] !buf; + + new aryi64 = { i64[] b -> + buf = b; + }; + + // Grow as needed + val _grow = { u32 len2 -> + if( len+len2 <= buf# ) return self; + u32 newlen = ary.capacity(buf#,len+len2); + if( !newlen ) libc._exit(1); // Length exceeds the array representation. + i64[] !buf2 = new i64[newlen]; + for( u32 i = 0; i < len; i++ ) + buf2[i] = buf[i]; + buf = buf2; + self; + }; + + // Add an i64 to aryi64 + val add = { i64 c -> + _grow(1).buf[len++] = c; + self; + }; + + val get = { u32 index -> return buf[index]; }; + + // Write the bracketed array-list form to aryu8. + val str = { -> + // TODO: clunky default constructor syntax + var str = new aryu8().add('['); + for( u32 i = 0; i < len; i++ ) + str.num(buf[i]).add(',').add(' '); + if( len ) str.undo(2); + return str.add(']'); + }; + + val swap = { u32 i, u32 j -> + i64 tmp = buf[i]; + buf[i] = buf[j]; + buf[j] = tmp; + self; + }; +}; + + + +// Parse a comma-separated list of numbers, wrapped with square brackets, +// with optional whitespace e.g. "[ -17, 0,99,12456789 ] ". +// parseAryI64 & aryi64.str are bijections modulo whitespace. +// Returns null if the parse failed, without giving a clue as to why. +val parseAryI64 = { u8[~] str -> + !scan !s = new scan(str); + if( !s.match('[') ) return null; + // Array of parsed results + var nums = new aryi64(new i64[1]); + + // Parse a list of numbers + if( s.match(']') ) // Handle the empty list + return nums; + + // Parse number commas "123, " until something else + while( s.x < s.buf# ) { + nums.add(s.number()); + if( s.bad ) return null; + if( !s.match(',') ) + break; + }; + // Close the list + if( !s.match(']') ) return null; + s.skip(); + return s.x == s.buf# ? nums : null; +}; + +val copy = { i64[] dst, u32 doff, i64[~] src, u32 soff, u32 len -> + if( doff > dst# || soff > src# ) return dst; + if( len > dst# - doff ) len = dst# - doff; + if( len > src# - soff ) len = src# - soff; + for( u32 i = 0; i < len; i++ ) + dst[i+doff] = src[i+soff]; + return dst; +}; diff --git a/chapter33/src/main/smp/sys/aryu8.smp b/chapter33/src/main/smp/sys/aryu8.smp new file mode 100644 index 00000000..3f462898 --- /dev/null +++ b/chapter33/src/main/smp/sys/aryu8.smp @@ -0,0 +1,75 @@ + +// Ary/Vector of u8s - a resizable array of bytes. +struct aryu8 { + u32 !len = 0; + u8[] !buf; + + new aryu8 = { -> buf = new u8[1]; }; + + // Grow as needed + val _grow = { u32 len2 -> + if( len+len2 <= buf# ) return self; + u32 newlen = ary.capacity(buf#,len+len2); + if( !newlen ) libc._exit(1); // Length exceeds the array representation. + u8[] !buf2 = new u8[newlen]; + ary.copy(buf2,0,buf,0,len); + buf = buf2; + self; + }; + + val clear = { -> len = 0; self; }; + + // Add a character to aryu8 + val add = { u8 c -> + _grow(1).buf[len++] = c; + self; + }; + + // Add all of a plain array to the aryu8 + val addAry = { u8[~] xs -> + u32 n = xs#; + _grow(n); + ary.copy(buf,len,xs,0,n); + len += n; + self; + }; + + // Remove x bytes from the tail. + val undo = { u32 x -> + len = len >= x ? len-x : 0; + self; + }; + + // Print ASCII number into aryu8 + val num = { i64 x -> + text.integer(self,x,0,0,-1); + self; + }; + + // Write all bytes to fd; return len, or -1 with errno set on failure. + val write = { i32 fd -> + io.writeOff(fd,buf,0,len); + }; +}; + + +// Parse one integer, ignore trailing data; returns 0 with an empty string. +// If you want a more robust parsing, use the `scan` class +val atoi = { u8[~] str -> + u32 x = 0; + while( x < str# && str[x] <= ' ' ) x++; + if( x == str# ) return 0; + bool neg = false; + if( str[x] == '-' ) { neg = true; x++; } + i64 n = 0; + while( x < str# && '0' <= str[x] <= '9' ) + n = n*10 + str[x++]-'0'; + return neg ? -n : n; +}; + +// Zero-terminate a string for libc, reserving one array element for the zero. +{ u8[~] -> u8[] } str0 = { u8[~] str -> + if( str# == sys.integer.MAX_U32 ) libc._exit(1); + // Copy, terminate and return + return new u8[str#+1]{i64 i -> i < str# ? str[i] : '\0'; }; +}; diff --git a/chapter33/src/main/smp/sys/audio.md b/chapter33/src/main/smp/sys/audio.md new file mode 100644 index 00000000..31b5c875 --- /dev/null +++ b/chapter33/src/main/smp/sys/audio.md @@ -0,0 +1,84 @@ +# Optional background audio + +[Chapter 31](../../../../../chapter31/README.md#graphics-and-sound) introduces the library. +The Simple API is implemented in [audio.smp](audio.smp), with the native adapter +in [simple_miniaudio.c](../../c/simple_miniaudio.c). + +`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 `chapter33`: + +```sh +make libs # Once while online +make audio +make run-graphical-tictactoe +``` + +The last command builds both optional backends and runs a tictactoe game with +sounds. 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 + +For direct execution from `chapter33`, configure both backends and launch the +game using your shell. + +PowerShell: + +```powershell +$env:SIMPLE_MINIFB = (Resolve-Path build/release/x86_64_v2_win64/simple_minifb.dll).Path +$env:SIMPLE_MINIAUDIO = (Resolve-Path build/release/x86_64_v2_win64/simple_miniaudio.dll).Path +.\build\examples\x86_64_v2_win64\TicTacToeGraphical.exe +``` + +Command Prompt (`cmd.exe`): + +```bat +set "SIMPLE_MINIFB=%CD%\build\release\x86_64_v2_win64\simple_minifb.dll" +set "SIMPLE_MINIAUDIO=%CD%\build\release\x86_64_v2_win64\simple_miniaudio.dll" +.\build\examples\x86_64_v2_win64\TicTacToeGraphical.exe +``` + +Bash (Cygwin, using the Windows build): + +```bash +export SIMPLE_MINIFB="$PWD/build/release/x86_64_v2_win64/simple_minifb.dll" +export SIMPLE_MINIAUDIO="$PWD/build/release/x86_64_v2_win64/simple_miniaudio.dll" +./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` +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/chapter33/src/main/smp/sys/audio.smp b/chapter33/src/main/smp/sys/audio.smp new file mode 100644 index 00000000..5dbe63a3 --- /dev/null +++ b/chapter33/src/main/smp/sys/audio.smp @@ -0,0 +1,30 @@ +// Optional background audio. All API calls belong on the game/main thread. +// API and launch reference: audio.md beside this file. +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/chapter33/src/main/smp/sys/char.smp b/chapter33/src/main/smp/sys/char.smp new file mode 100644 index 00000000..22ca4213 --- /dev/null +++ b/chapter33/src/main/smp/sys/char.smp @@ -0,0 +1,8 @@ + +val toupper = { u8 c -> + return c >= 'a' && c <= 'z' ? c - ('a' - 'A') : c; +}; + +val tolower = { u8 c -> + return c >= 'A' && c <= 'Z' ? c + ('a' - 'A') : c; +}; diff --git a/chapter33/src/main/smp/sys/draw.smp b/chapter33/src/main/smp/sys/draw.smp new file mode 100644 index 00000000..92bf04b7 --- /dev/null +++ b/chapter33/src/main/smp/sys/draw.smp @@ -0,0 +1,19 @@ +// Software raster drawing. No window or native calls; pixels are packed RGB (0x00RRGGBB). +// API reference: draw/README.md. +u32 BLACK = 0x000000; +u32 WHITE = 0xffffff; +u32 RED = 0xff0000; +u32 GREEN = 0x00ff00; +u32 BLUE = 0x0000ff; + +// Components are clamped to bytes rather than wrapping. +val rgb = { int r, int g, int b -> + r = r < 0 ? 0 : r > 255 ? 255 : r; + g = g < 0 ? 0 : g > 255 ? 255 : g; + b = b < 0 ? 0 : b > 255 ? 255 : b; + u32 color = (r<<16) | (g<<8) | b; + return color; +}; + +val Canvas = Canvas; // Pixel canvas and drawing methods +val Button = Button; // Pointer state and rendering for a rectangular button diff --git a/chapter33/src/main/smp/sys/draw/Button.smp b/chapter33/src/main/smp/sys/draw/Button.smp new file mode 100644 index 00000000..c90ed2d3 --- /dev/null +++ b/chapter33/src/main/smp/sys/draw/Button.smp @@ -0,0 +1,41 @@ +// Feed pointer state once per event-loop iteration. Activate on release inside, +// only after a press that began inside. No native/window dependency. +struct Button { + int x, y, width, height; + u8[~] !label; + bool !enabled = true, !hovered = false, !pressed = false; + bool !_held = false, !_armed = false; + new Button = { int px, int py, int w, int h, u8[~] text -> + x = px; y = py; width = w; height = h; label = text; + }; + val contains = { i64 px, i64 py -> + if( width <= 0 || height <= 0 ) return false; + i64 right = x, bottom = y; right += width; bottom += height; + if( px < x || py < y || px >= right || py >= bottom ) return false; + return true; + }; + val update = { i64 px, i64 py, bool down -> + hovered = false; + if( enabled ) hovered = contains(px,py); + if( !enabled ) _armed = false; + if( down && !_held ) _armed = hovered; + var clicked = false; + if( !down ) if( _held ) if( _armed ) if( hovered ) clicked = true; + if( !down ) _armed = false; + _held = down; + pressed = false; + if( down ) if( _armed ) if( hovered ) pressed = true; + return clicked; + }; + val draw = { !sys.draw.Canvas screen, int scale, u32 foreground, u32 background, u32 active -> + screen.fillRect(x,y,width,height,enabled && (hovered || pressed) ? active : background); + screen.rect(x,y,width,height,2,enabled ? foreground : active); + if( scale > 0 ) { + i64 textWidth = label#; textWidth = (textWidth*4-1)*scale; + if( textWidth <= width-8 && 5*scale <= height-8 ) + screen.text(x+(width-textWidth)/2,y+(height-5*scale)/2+(pressed ? 1 : 0), + label,scale,enabled ? foreground : active); + } + return self; + }; +}; diff --git a/chapter33/src/main/smp/sys/draw/Canvas.smp b/chapter33/src/main/smp/sys/draw/Canvas.smp new file mode 100644 index 00000000..5ec7c9ef --- /dev/null +++ b/chapter33/src/main/smp/sys/draw/Canvas.smp @@ -0,0 +1,201 @@ +struct Canvas { + u32 !width; + u32 !height; + u32[] !pixels; + // Layout coordinates are relative to the constructor's base size. + // A single float scale preserves circles and game geometry on resize. + u32 baseWidth, baseHeight; + f64 scale = 1.0; + int offsetX = 0, offsetY = 0; + + new Canvas = { u32 w, u32 h -> + if( w > sys.integer.MAX_I32 || h > sys.integer.MAX_I32 ) libc._exit(1); + i64 count = w; + count *= h; + if( w <= 0 || h <= 0 || count > sys.integer.MAX_I32 ) libc._exit(1); + width = w; + height = h; + baseWidth = w; + baseHeight = h; + pixels = new u32[count]; + }; + + // Ignore minimized windows. Return true only when a redraw is needed. + val resize = { u32 w, u32 h -> + if( w == 0 || h == 0 || (w == width && h == height) ) return false; + if( w > sys.integer.MAX_I32 || h > sys.integer.MAX_I32 ) libc._exit(1); + i64 count = w; count *= h; + if( count > sys.integer.MAX_I32 ) libc._exit(1); + // Reuse storage while dragging. Geometric growth bounds total allocation + // even in the current runtime, which does not yet collect old arrays. + if( count > pixels# ) { + i64 capacity = pixels#*2; + if( capacity < count ) capacity = count; + if( capacity > sys.integer.MAX_I32 ) capacity = sys.integer.MAX_I32; + pixels = new u32[capacity]; + } + width = w; height = h; + f64 sx = w*1.0/baseWidth, sy = h*1.0/baseHeight; + scale = sx < sy ? sx : sy; + offsetX = (w-baseWidth*scale)/2; + offsetY = (h-baseHeight*scale)/2; + return true; + }; + + // Inverse of the drawing transform. Margins are outside the layout; + // reject them before integer truncation can turn a small negative into 0. + val localX = { int x -> + if( x < offsetX || x >= offsetX+baseWidth*scale ) return -1; + int local = (x-offsetX)/scale; + return local; + }; + val localY = { int y -> + if( y < offsetY || y >= offsetY+baseHeight*scale ) return -1; + int local = (y-offsetY)/scale; + return local; + }; + + val clear = { u32 color -> + i64 count = width; count *= height; + for( int i = 0; i < count; i++ ) pixels[i] = color; + return self; + }; + + val pixel = { i64 x, i64 y, u32 color -> + return fillRect(x,y,1,1,color); + }; + + // Integer coordinates, top-left origin. Rectangle extents are half-open. + val fillRect = { i64 x, i64 y, i64 w, i64 h, u32 color -> + if( w <= 0 || h <= 0 ) return self; + i64 right = offsetX+(x+w)*scale; + i64 bottom = offsetY+(y+h)*scale; + x = offsetX+x*scale; y = offsetY+y*scale; + if( right <= 0 || bottom <= 0 || x >= width || y >= height ) return self; + int x0 = x < 0 ? 0 : x, y0 = y < 0 ? 0 : y; + int x1 = right > width ? width : right, y1 = bottom > height ? height : bottom; + for( int py = y0; py < y1; py++ ) + for( int px = x0; px < x1; px++ ) pixels[py*width+px] = color; + return self; + }; + + // Outline stays inside the rectangle. Wide borders become a filled rect. + val rect = { i64 x, i64 y, i64 w, i64 h, i64 thickness, u32 color -> + if( w <= 0 || h <= 0 || thickness <= 0 ) return self; + if( thickness >= w || thickness >= h || thickness >= w-thickness || thickness >= h-thickness ) + return fillRect(x,y,w,h,color); + fillRect(x,y,w,thickness,color); + fillRect(x,y+h-thickness,w,thickness,color); + fillRect(x,y+thickness,thickness,h-2*thickness,color); + return fillRect(x+w-thickness,y+thickness,thickness,h-2*thickness,color); + }; + + // Integer centers are pixel centers. Circle outlines extend inward. + val fillCircle = { i64 cx, i64 cy, int radius, u32 color -> + return _circle(cx,cy,radius,0,true,color); + }; + val circle = { i64 cx, i64 cy, int radius, int thickness, u32 color -> + return _circle(cx,cy,radius,thickness,false,color); + }; + val _circle = { i64 cx, i64 cy, int radius, int thickness, bool filled, u32 color -> + if( radius < 0 || (!filled && thickness <= 0) ) return self; + cx = offsetX+cx*scale; cy = offsetY+cy*scale; + radius *= scale; + thickness *= scale; + if( !filled && thickness < 1 ) thickness = 1; + i64 left = cx; left -= radius; + i64 top = cy; top -= radius; + i64 right = cx; right += radius; + i64 bottom = cy; bottom += radius; + if( right < 0 || bottom < 0 || left >= width || top >= height ) return self; + int x0 = left < 0 ? 0 : left, y0 = top < 0 ? 0 : top; + int x1 = right >= width ? width-1 : right, y1 = bottom >= height ? height-1 : bottom; + i64 outer2 = radius; + outer2 *= radius; + i64 inner = filled ? -1 : radius-thickness; + for( int py = y0; py <= y1; py++ ) + for( int px = x0; px <= x1; px++ ) { + i64 dx = px; dx -= cx; + i64 dy = py; dy -= cy; + i64 d2 = dx*dx+dy*dy; + if( d2 <= outer2 && (inner <= 0 || d2 > inner*inner) ) pixels[py*width+px] = color; + } + return self; + }; + + // Round caps; a zero-length segment is a dot. Only the clipped bounding + // box is scanned. Floating distances avoid overflowing coordinate squares. + val line = { i64 x0, i64 y0, i64 x1, i64 y1, i64 thickness, u32 color -> + if( thickness <= 0 ) return self; + x0 = offsetX+x0*scale; y0 = offsetY+y0*scale; + x1 = offsetX+x1*scale; y1 = offsetY+y1*scale; + thickness *= scale; + if( thickness < 1 ) thickness = 1; + i64 pad = thickness/2+1; + i64 left = x0 < x1 ? x0 : x1; left -= pad; + i64 top = y0 < y1 ? y0 : y1; top -= pad; + i64 right = x0 > x1 ? x0 : x1; right += pad; + i64 bottom = y0 > y1 ? y0 : y1; bottom += pad; + if( right < 0 || bottom < 0 || left >= width || top >= height ) return self; + int bx0 = left < 0 ? 0 : left, by0 = top < 0 ? 0 : top; + int bx1 = right >= width ? width-1 : right, by1 = bottom >= height ? height-1 : bottom; + for( int py = by0; py <= by1; py++ ) + for( int px = bx0; px <= bx1; px++ ) + if( _onLine(px,py,x0,y0,x1,y1,thickness) ) pixels[py*width+px] = color; + return self; + }; + + // Small 3x5 bitmap font for game labels. Lowercase maps to uppercase. + // Newline returns to x; unsupported characters draw a question mark. + val text = { i64 x, i64 y, u8[~] str, int scale, u32 color -> + if( scale <= 0 ) return self; + i64 px = x, py = y; + for( int i = 0; i < str#; i++ ) { + u8 c = str[i]; + if( c == '\n' ) { px = x; py += 6*scale; continue; } + int bits = _glyph(c); + for( int row = 0; row < 5; row++ ) + for( int col = 0; col < 3; col++ ) + if( (bits >> (14-row*3-col)) & 1 ) + fillRect(px+col*scale,py+row*scale,scale,scale,color); + px += 4*scale; + } + return self; + }; +}; + +// An old-school 3x5 font, ASCII 32..127. Five octal row digits need u16. +// Lowercase uses uppercase shapes; unsupported characters use '?'. +val _glyphs = new u16[~96]{ + 000000,022202,055000,057575,061202,051245,061202,022000, // space..' + 012221,042224,005250,002720,000024,000700,000002,011244, // (../ + 075557,026227,061247,061216,055711,074616,034757,071222, // 0..7 + 075757,075716,002020,002024,012421,007070,042124,061202, // 8..? + 061202,025755,065656,034443,065556,074647,074644,034553, // @..G + 055755,072227,011152,055655,044447,057755,057775,025552, // H..O + 065644,025573,065655,034216,072222,055557,055552,055775, // P..W + 055255,055222,071247,032223,044211,062226,025000,000007, // X.._ + 042000,025755,065656,034443,065556,074647,074644,034553, // `..g + 055755,072227,011152,055655,044447,057755,057775,025552, // h..o + 065644,025573,065655,034216,072222,055557,055552,055775, // p..w + 055255,055222,071247,032423,022222,062126,003600,061202, // x..DEL +}; + +val _glyph = { u8 c -> + return 32 <= c < 128 ? _glyphs[c-32] : 061202; +}; + +// Pixel coverage for a round-ended segment, separate from traversal. +val _onLine = { i64 px, i64 py, i64 x0, i64 y0, i64 x1, i64 y1, i64 thickness -> + f64 dx = x1; dx -= x0; + f64 dy = y1; dy -= y0; + f64 vx = px; vx -= x0; + f64 vy = py; vy -= y0; + f64 length2 = dx*dx+dy*dy; + bool point = x0 == x1 && y0 == y1; + f64 t = point ? 0.0 : (vx*dx+vy*dy)/length2; + t = t < 0 ? 0.0 : t > 1 ? 1.0 : t; + f64 ex = vx-t*dx, ey = vy-t*dy; + f64 half = thickness/2.0; + return ex*ex+ey*ey <= half*half; +}; diff --git a/chapter33/src/main/smp/sys/draw/README.md b/chapter33/src/main/smp/sys/draw/README.md new file mode 100644 index 00000000..778ec741 --- /dev/null +++ b/chapter33/src/main/smp/sys/draw/README.md @@ -0,0 +1,124 @@ +# Drawing in Simple + +[Chapter 31](../../../../../../chapter31/README.md#graphics-and-sound) introduces the library. +The implementation is in [Canvas.smp](Canvas.smp), [Button.smp](Button.smp), +and the [draw module](../draw.smp). + +`sys.draw` draws into an ordinary `u32[]`. It has no native dependencies and +does not open a window. `sys.gfx` presents the resulting pixels using the +optional [MiniFB backend](../gfx.md). + +```simple +val canvas = new sys.draw.Canvas(600,780); +u32 orange = 0xe47b57; +canvas.clear(sys.draw.WHITE); +canvas.fillRect(20,20,180,80,orange); +canvas.rect(20,20,180,80,3,sys.draw.BLACK); +canvas.circle(300,200,48,8,sys.draw.BLUE); +canvas.fillCircle(420,200,20,sys.draw.GREEN); +canvas.line(40,320,250,440,12,orange); +canvas.text(40,500,"YOUR TURN",4,sys.draw.BLACK); +// After sys.gfx.open succeeds: +sys.gfx.presentSize(canvas.pixels,canvas.width,canvas.height); +``` + +## Small raster API + +Coordinates start at the upper left; x increases rightward and y downward. +Drawing methods return the canvas for chaining. Everything is opaque RGB; +there is no blending, antialiasing, transform stack, or native drawing state. +Coordinates accept `i64` so ordinary widened arithmetic can be passed directly. +Circle radii and circle stroke widths are `int`. Use screen-sized coordinates, +extents, and stroke widths. + +| Operation | Behavior | +| --- | --- | +| `rgb(r,g,b)` | Clamp components to 0–255 and pack RGB. `BLACK`, `WHITE`, `RED`, `GREEN`, and `BLUE` are available too. | +| `new Canvas(width,height)` | Allocate a zero-filled pixel array. Dimensions must be positive and their product must fit a signed 32-bit index; invalid sizes exit with status 1. Allocation can still fail for lack of memory. | +| `resize(width,height)` | Fit the original layout into new drawable dimensions; return whether they changed. Ignore zero dimensions. | +| `localX(x)`, `localY(y)` | Convert drawable pixels to base coordinates for input; return -1 in the margins. | +| `clear(color)` | Fill the entire canvas. | +| `pixel(x,y,color)` | Set one pixel; ignore points outside the canvas. | +| `fillRect(x,y,w,h,color)` | Fill a half-open rectangle: x through x+w-1, y through y+h-1. | +| `rect(x,y,w,h,thickness,color)` | Draw an inward outline. A sufficiently wide outline fills the rectangle. | +| `fillCircle(cx,cy,radius,color)` | Fill a circle; radius zero draws its center pixel. | +| `circle(cx,cy,radius,thickness,color)` | Draw an inward circular outline. | +| `line(x0,y0,x1,y1,thickness,color)` | Draw a round-ended segment. A zero-length segment draws a round dot. Thickness is its geometric diameter, sampled at integer pixel centers. | +| `text(x,y,string,scale,color)` | Draw a 3×5 bitmap font, with one column between characters. Upper/lowercase ASCII letters, digits, spaces, and basic punctuation are supported. Newline advances six scaled pixels. Unknown characters use `?`. | + +Shapes clip to the canvas. Nonpositive rectangle extents, stroke widths, or +text scale do nothing; negative circle radii do nothing. Line and circle +coverage scans only the clipped bounding box, which is sufficient for small +turn-based games. This is a starting raster library rather than a fast animated +renderer. The pixel array remains available for direct drawing and inspection. + +The constructor sets the layout's `baseWidth` and `baseHeight`. Resizing uses +`scale = min(width/baseWidth, height/baseHeight)` in floating point and centers +the result with `offsetX` and `offsetY`. Sizes, offsets, glyph cells, and stroke +widths all use this transform; circles stay circular. Positive line and circle +strokes retain at least one drawable pixel. Existing drawing coordinates remain +in base units, while `width`, `height`, and direct pixel indexing use the actual +framebuffer dimensions. `clear` fills the whole framebuffer, including margins. +At very small sizes, details smaller than a pixel naturally disappear. + +Canvas reuses its pixel storage and grows its capacity geometrically when needed. +Only the first `width*height` elements are active; use `gfx.presentSize` after +resizing. This avoids allocating on every drag event, including repeated shrink +and grow cycles. Use `localX`/`localY` before button or game hit tests so drawing +and input share the same scale and centering. + +Packed colors use hexadecimal literals (`0xRRGGBB`); `rgb(r,g,b)` remains handy +for computed components. The font masks use leading-zero octal, with five +digits after the prefix: each digit is one three-pixel row, top to bottom. +For example, `A` is `025755`: rows `010`, `101`, `111`, `101`, `101`. +The font includes all printable ASCII punctuation except `@`, `&`, and `$`, +which use the question-mark fallback. Colons and slashes support clock and date +labels; quotes, brackets, arithmetic signs, and other small symbols fit in 3×5. + +## Button widget + +`new sys.draw.Button(x,y,width,height,label)` creates a rectangular software +button. It owns no window or native resources. Feed pointer coordinates and +the held mouse-button state to `update(x,y,down)` once per event-loop iteration. +It returns true once on release inside, provided the press began inside. +Dragging in from outside does not activate it; releasing outside cancels. + +`hovered` and `pressed` expose visual state. Set `enabled=false` to cancel a +pending press and disable activation; `label` can be changed at any time. +`contains(x,y)` uses half-open bounds. `draw(canvas,scale,foreground,background,active)` +paints the button and centers its 3x5 label when it fits. Colors belong to the +caller. Keyboard shortcuts belong to the application; this small widget has +no focus system. The [clock example](../../../../../docs/examples/Clock.smp) shows mouse activation +and a Space shortcut in the same single-threaded loop. + +## Graphical tic-tac-toe + +From `chapter33`: + +```sh +make run-graphical-tictactoe +``` + +Click an empty square or press **1–9**, numbered left-to-right, top-to-bottom. +You are X; the CPU is O. It wins when possible, blocks your immediate win, +then prefers the center, corners, and edges. The result stays visible with +the winning line highlighted. Press **R** or **Space** to start a new game, +or **Q**/**Escape** to quit. Restart is also available during a game. + +Held buttons and keys do not take repeated turns. Moving the pointer highlights +empty cells. The canvas is redrawn after a move, restart, hover change, or resize; +polling still processes window events and waits between polls. + +`make graphical-tictactoe` builds without opening a window or requiring +MiniFB. Its output is `build/examples/x86_64_v2_win64/TicTacToeGraphical.exe` +on Windows or `build/examples/x86_64_v2_SystemV/TicTacToeGraphical` on Linux. +Backend discovery and explicit overrides follow [the pixel-window instructions](../gfx.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` checks raster pixels and complete game turns +without a display. `make tests_nographics` runs the ordinary suite with +the backend disabled. diff --git a/chapter33/src/main/smp/sys/gfx.md b/chapter33/src/main/smp/sys/gfx.md new file mode 100644 index 00000000..7d54f545 --- /dev/null +++ b/chapter33/src/main/smp/sys/gfx.md @@ -0,0 +1,154 @@ +# Optional graphics + +[Chapter 31](../../../../../chapter31/README.md#graphics-and-sound) introduces the library. +The Simple API is implemented in [gfx.smp](gfx.smp), with the window adapter in +[simple_minifb.c](../../c/simple_minifb.c). + +Simple owns the pixel array and drawing code. [MiniFB](https://github.com/emoon/minifb) +provides a window, input, and pixel presentation. The first interface is +`sys.gfx`: one resizable window, operated on the main thread. The +[Graphics example](../../../../docs/examples/Graphics.smp) draws a color gradient in Simple. +The [drawing library and graphical tic-tac-toe](draw/README.md) build on this pixel +interface. `make run-graphical-tictactoe` builds the optional backend and +opens the game; `make graphical-tictactoe` only builds its executable. +The game run target also builds optional [background audio](audio.md). + +## Default: no graphics dependency + +From `chapter33`, the usual `make release`, `make tests`, and `make tictactoe` +need no MiniFB, graphics headers, OpenGL, CMake, or running display. Nothing +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` runs the entire ordinary suite with +`SIMPLE_MINIFB=off`. This includes the missing-backend tests, which never open +windows. It excludes the interactive `run-graphics` target. + +The runtime contains a small loader using the OS dynamic-library facilities. +It does nothing until `sys.gfx.open`. Without an available backend, `open` +prints a diagnostic to stderr and returns `sys.gfx.ERROR` (-1). Programs can +return a nonzero status or fall back to text; the library does not terminate +the process. Non-graphics programs ignore even a broken graphics configuration. + +## Build the optional backend + +From `chapter33`: + +```sh +make libs # Once while online; fills the persistent lib/ cache. +make graphics graphics-example +make run-graphics +``` + +`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 +wrappers, and upstream example programs are omitted. Native Wayland and macOS +builds are not provided here yet. + +Outputs: + +| Platform | Backend | Example | +| --- | --- | --- | +| Windows | `build/release/x86_64_v2_win64/simple_minifb.dll` | `build/examples/x86_64_v2_win64/Graphics.exe` | +| Linux | `build/release/x86_64_v2_SystemV/libsimple_minifb.so` | `build/examples/x86_64_v2_SystemV/Graphics` | + +`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. +`run-graphics` builds both, sets the backend path, and opens a window. Close it +or release Escape to exit. Passing any argument to the executable makes it +close after five polling iterations, for a quick smoke test. + +To run directly from `chapter33` in PowerShell: + +```powershell +$env:SIMPLE_MINIFB = (Resolve-Path build/release/x86_64_v2_win64/simple_minifb.dll).Path +.\build\examples\x86_64_v2_win64\Graphics.exe +``` + +From Command Prompt (`cmd.exe`): + +```bat +set "SIMPLE_MINIFB=%CD%\build\release\x86_64_v2_win64\simple_minifb.dll" +.\build\examples\x86_64_v2_win64\Graphics.exe +``` + +From Bash (Cygwin, using the Windows build): + +```bash +export SIMPLE_MINIFB="$PWD/build/release/x86_64_v2_win64/simple_minifb.dll" +./build/examples/x86_64_v2_win64/Graphics.exe +``` + +For WSL, from the repository root: + +```sh +wsl -d Ubuntu-24.04 -- bash -lc 'cd chapter33 && make graphics graphics-example CLZDIR=build/classes-linux' +``` + +Inside WSL, set `SIMPLE_MINIFB` to the full path of the Linux `.so`, then run +the Linux example with a working X11 display. For an automated virtual display: + +```sh +SIMPLE_MINIFB="$PWD/build/release/x86_64_v2_SystemV/libsimple_minifb.so" \ + xvfb-run -a build/examples/x86_64_v2_SystemV/Graphics smoke +``` + +With no `SIMPLE_MINIFB` setting, the runtime searches beside the executable, +then its `../../release/<ABI>` and `../release/<ABI>` directories. These cover +the examples and test build layouts regardless of the current directory. +It also checks the current directory, `build/release/<ABI>`, and +`chapter33/build/release/<ABI>` relative to the current directory. Thus built +examples such as `Clock.exe` can be launched directly without configuration. + +`SIMPLE_MINIFB` overrides discovery; an invalid explicit path reports an error +without falling back. `SIMPLE_MINIFB=off` disables graphics for headless tests. +An absent, unloadable, or incompatible backend produces a diagnostic. +A backend that loads but cannot create a window also reports an error cleanly. + +## Initial interface + +| Operation | Meaning | +| --- | --- | +| `open(title,width,height)` | Open one window; returns `OK` or `ERROR`. | +| `present(pixels)` | Present a `u32[~]` of exactly the original `width*height` pixels, packed `0x00RRGGBB`. MiniFB stretches this buffer to the window. | +| `width()`, `height()` | Current drawable dimensions after the last event dispatch; zero when no window exists. | +| `presentSize(pixels,width,height)` | Present the first `width*height` elements of a buffer at an explicit resolution. Dimensions must be positive and fit the array. | +| `poll(wait)` | Process input; `true` waits up to 17ms, waking for input. | +| `wait(timeoutMs)` | Wait for input or timeout, then process events; 0 polls, -1 waits indefinitely. | +| `mouseX()`, `mouseY()` | Current mouse position, origin at upper left. | +| `button(LEFT)`, `key(code)` | Current pressed state; printable keys use uppercase ASCII. | +| `close()` | Release native window and pixel storage; safe to repeat. | + +`present`, `poll`, and `wait` return `OK` (0), `CLOSED` (1, normal close/Escape), or +`ERROR` (-1). Stop polling after either terminal result and call `close`. +The initial input API samples held state; it is not a queue of every transition. + +Waits may return early; values below -1 are errors. Recheck the monotonic +clock after waking. The [time library and animation example](time/README.md) combine +this wait with cooperative timer deadlines. Backend API version 3 adds +resizing and explicit framebuffer dimensions; rebuild older MiniFB adapters +with `make graphics` from the cached sources. + +For drawing at the new resolution, call `canvas.resize(gfx.width(),gfx.height())` +after processing events, redraw when it returns true, and use +`gfx.presentSize(canvas.pixels,canvas.width,canvas.height)`. Explicit buffer +dimensions remain valid if another resize arrives while presenting. Zero-sized +resize notifications are ignored by Canvas so minimizing retains the last layout. +Mouse coordinates are in drawable pixels; convert them with `canvas.localX` +and `canvas.localY` for hit testing in the [base layout](draw/README.md). + +MiniFB retains its last framebuffer for repaint events. The adapter copies the +Simple array into native-owned storage before presenting; it never retains a +Simple heap pointer. Framebuffer allocation, the copy, and window/input calls +are the only native work here. Drawing primitives and the games can be built +in Simple on top of this boundary. diff --git a/chapter33/src/main/smp/sys/gfx.smp b/chapter33/src/main/smp/sys/gfx.smp new file mode 100644 index 00000000..60505ac9 --- /dev/null +++ b/chapter33/src/main/smp/sys/gfx.smp @@ -0,0 +1,61 @@ +// Minimal pixel-window interface; drawing belongs in Simple. +// API and launch reference: gfx.md beside this file. +// One resizable window, main thread only. Pixel format is 0x00RRGGBB. +// open/present/poll return OK, CLOSED (normal user close/Esc), or ERROR. +int OK = 0; +int CLOSED = 1; +int ERROR = -1; +int LEFT = 1; +int ESCAPE = 256; + +{ i64 u32 u32 -> i32 } simple_gfx_open = "C"; +{ i64 u32 -> i32 } simple_gfx_present = "C"; +{ i64 u32 u32 u32 -> i32 } simple_gfx_present_size = "C"; +{ u32 } simple_gfx_width = "C"; +{ u32 } simple_gfx_height = "C"; +{ i32 -> i32 } simple_gfx_poll = "C"; +{ i32 } simple_gfx_mouse_x = "C"; +{ i32 } simple_gfx_mouse_y = "C"; +{ i32 -> i32 } simple_gfx_button = "C"; +{ i32 -> i32 } simple_gfx_key = "C"; +{ i32 } simple_gfx_close = "C"; +{ i64 -> i32 } simple_gfx_wait = "C"; + +// Failure prints a diagnostic to stderr and returns ERROR; callers decide +// whether to exit or fall back to text. No native library is loaded until here. +val open = { u8[~] title, u32 width, u32 height -> + i64 ptr = aryu8.str0(title); + simple_gfx_open(ptr,width,height); +}; + +// Array length must be width*height. The native layer copies for OS repaints; +// it never keeps a pointer into the Simple heap after this call returns. +val present = { u32[~] pixels -> + i64 ptr = pixels; + simple_gfx_present(ptr,pixels#); +}; + +// Drawable size after the last event dispatch; zero when closed. +val width = { -> simple_gfx_width(); }; +val height = { -> simple_gfx_height(); }; +// Explicit dimensions keep a resize arriving during presentation harmless. +val presentSize = { u32[~] pixels, u32 width, u32 height -> + if( width == 0 || height == 0 || width > pixels# || height > pixels# ) return ERROR; + i64 count = width; count *= height; + if( count > pixels# ) return ERROR; + i64 ptr = pixels; + u32 size = count; + simple_gfx_present_size(ptr,size,width,height); +}; + +// wait=true waits up to 17ms, waking early for input to avoid a busy loop. +val poll = { bool wait -> simple_gfx_poll(wait); }; +val mouseX = { -> simple_gfx_mouse_x(); }; +val mouseY = { -> simple_gfx_mouse_y(); }; +val button = { int button -> simple_gfx_button(button); }; +// Printable keys use uppercase ASCII; special keys use MiniFB's key codes. +val key = { int key -> simple_gfx_key(key); }; +val close = { -> simple_gfx_close(); }; +// Wait for input or at most timeout milliseconds; 0 polls, -1 waits indefinitely. +// This blocks the game thread, dispatches window events, and may wake early. +val wait = { i64 timeout_ms -> simple_gfx_wait(timeout_ms); }; diff --git a/chapter33/src/main/smp/sys/integer.smp b/chapter33/src/main/smp/sys/integer.smp new file mode 100644 index 00000000..a839e597 --- /dev/null +++ b/chapter33/src/main/smp/sys/integer.smp @@ -0,0 +1,6 @@ +// Integer bounds. + +i64 MIN_I64 = 1<<63; +i64 MAX_I64 = -(MIN_I64+1); +i32 MAX_I32 = (1<<31)-1; +u32 MAX_U32 = (1<<32)-1; diff --git a/chapter33/src/main/smp/sys/io.smp b/chapter33/src/main/smp/sys/io.smp new file mode 100644 index 00000000..6269cde5 --- /dev/null +++ b/chapter33/src/main/smp/sys/io.smp @@ -0,0 +1,95 @@ + +// Simple I/O Library + +// Write byte array to stdout +val p = { u8[~] str -> write(1,str); }; +val p_noInline = { u8[~] str -> write(1,str); }; +// Write to stderr +val err = { u8[~] str -> write(libc.STDERR,str); }; + + +// Read until EOF, including after short reads. Return an empty array for an +// empty stream, or null on error with errno preserved (partial data discarded). +val read = { i32 fd -> + val chunk = new u8[8*1024]; + i64 ptr = chunk; + val buf = new aryu8(); + while( true ) { + i64 rez = libc.read(fd,ptr,chunk#); + if( rez < 0 ) { + if( libc.errno() == libc.EINTR ) continue; + return null; + } + if( rez == 0 ) break; + if( buf.len+rez > sys.integer.MAX_U32 ) { + libc.set_errno(libc.EOVERFLOW); + return null; + } + u32 count = rez; + buf._grow(count); + ary.copy(buf.buf,buf.len,chunk,0,count); + buf.len += count; + } + val out = new u8[buf.len]; + return ary.copy(out,0,buf.buf,0,buf.len); +}; + +// Write all bytes, returning the count or -1 with errno set. An error can +// follow a successfully written prefix; it does not undo that prefix. +val write = { i32 fd, u8[~] str -> + writeOff(fd,str,0,str#); +}; + +// Write a slice, capping len at the remaining bytes. An offset past the end +// is invalid, including for an empty write. A valid empty slice returns zero. +// Invalid arguments return -1; +val writeOff = { i32 fd, u8[~] str, u32 off, u32 len -> + if( off > str# ) return libc.set_errno(libc.EINVAL); + if( len > str# - off ) len = str# - off; + i64 ptr = str; + ptr += off; + i64 done = 0; + while( done < len ) { + i64 rez = libc.write(fd,ptr+done,len-done); + if( rez < 0 ) { + if( libc.errno() == libc.EINTR ) continue; + return -1; + } + if( rez == 0 ) { + libc.set_errno(libc.EIO); + return -1; + } + done += rez; + } + return done; +}; + +// Return stdin as a u8[]. +val stdin = { -> read(0); }; + +// One byte, without Enter or echo. Restores the previous terminal mode before +// returning. Files/pipes also work. Returns 0..255, or -1 with libc.errno() set +// to libc.EOF or an OS error. Ctrl-C is byte 3; escape/UTF-8 sequences are multiple bytes. +val getch = { -> libc.simple_getch(); }; + +// Create file for writing. Return fd, or -1 and errno has the error code +val create = { u8[~] str -> + i64 ptr = sys.aryu8.str0(str); + i32 perms = 6*64 + 6*8 + 6; // 0666 + return libc.creat(ptr, perms); +}; + +// Open file for reading. Return fd, or -1 and errno has the error code +val open = { u8[~] str -> + i64 ptr = sys.aryu8.str0(str); + return libc.open(ptr, sys.libc.O_RDONLY, 0); +}; + +// Close an open fd. Return 0, or -1 and errno has the error code +val close = { i32 fd -> return libc.close(fd); }; + +// Remove a file. Return 0, or -1 and errno has the error code +val remove = { u8[~] str -> + i64 ptr = sys.aryu8.str0(str); + return libc.unlink(ptr); +}; diff --git a/chapter33/src/main/smp/sys/libc.smp b/chapter33/src/main/smp/sys/libc.smp new file mode 100644 index 00000000..8e417461 --- /dev/null +++ b/chapter33/src/main/smp/sys/libc.smp @@ -0,0 +1,61 @@ + +// libc bindings: +// https://www.man7.org/linux/man-pages/man2/<libc call>.2.html + +// The buffers are i64 addresses of zero-terminated strings. +// i64 buf = aryu8.str0("some_file"); +// buf mode perm-> fd +{ i64 i32 i32 -> i32 } open = "C"; +// buf perm -> fd +{ i64 i32 -> i32 } creat = "C"; + +// fd buf len -> len +{ i32 i64 i64 -> i64 } write = "C"; +// fd buf len -> len +{ i32 i64 i64 -> i64 } read = "C"; +// fd -> err +{ i32 -> i32 } close = "C"; +// path -> err +{ i64 -> i32 } unlink = "C"; + +i32 O_RDONLY = 0; +i32 O_WRONLY = 1; +i32 O_RDWR = 2; +i32 O_CREAT = 512; // 02000 on x86_64-pc-cygwin +i32 O_TRUNC = 1024; // 04000 on x86_64-pc-cygwin + +i32 STDIN = 0; +i32 STDOUT = 1; +i32 STDERR = 2; +i32 EOF = -1; // simple_getch sets errno to EOF on end-of-input. + +// status +{ i32 -> i32 } _exit = "C"; + +// errno is not an ordinary C data symbol; read it through the native runtime. +{ i32 } simple_errno = "C"; +val errno = { -> simple_errno(); }; +{ i32 -> i32 } simple_set_errno = "C"; +// Set errno and return -1, matching the native I/O error convention. +val set_errno = { i32 error -> simple_set_errno(error); }; + +i32 EINTR = "C"; +i32 EIO = "C"; +i32 EINVAL = "C"; +i32 EOVERFLOW = "C"; + +// Read one byte from stdin, without <enter> or echo. Restores the previous +// terminal mode before returning. Files and pipes also work. Returns 0..255, +// or -1 with errno set to EOF or an OS error. Ctrl-C is byte 3; escape/UTF-8 +// sequences are multiple bytes. +{ i32 } simple_getch = "C"; + +// addr len prot flags fd off -> void* +{ i64 i64 i32 i32 i32 i32 -> i64 } mmap = "C"; +// mmap flags +i32 PROT_EXEC = 4; +i32 PROT_READ = 1; +i32 PROT_WRITE = 2; +i32 PROT_NONE = 0; +i32 MAP_PRIVATE = 2; +i32 MAP_ANON = 32; diff --git a/chapter33/src/main/smp/sys/math.smp b/chapter33/src/main/smp/sys/math.smp new file mode 100644 index 00000000..33bb0e5f --- /dev/null +++ b/chapter33/src/main/smp/sys/math.smp @@ -0,0 +1,27 @@ +// Mathematical constants, rounded to the nearest f64 value. +val PI = 3.141592653589793; +val E = 2.718281828459045; + +// Native libm functions, all f64 -> f64. sin/cos take radians; exp is e^x, +// log is the natural logarithm, and sqrt is the nonnegative square root. +// These are ordinary C calls: results and domain/range errors (including +// errno) follow the host libm. They are not folded or treated as pure intrinsics. +// The standard linker already includes -lm. +{ f64 -> f64 } sin = "C"; +{ f64 -> f64 } cos = "C"; +{ f64 -> f64 } exp = "C"; +{ f64 -> f64 } log = "C"; +{ f64 -> f64 } sqrt = "C"; + +// Fixed-semantics C bindings recognized by the compiler's intrinsic inliner. +// See chapter31/README.md, "Math support and intrinsics", for the compiler contract. +// These preserve all 64 bits, including signed zero and NaN payloads. +// They are NOT numeric conversions (ordinary typed assignments still are). +{ f64 -> i64 } simple_f64_bits = "C"; +{ i64 -> f64 } simple_f64_from_bits = "C"; +val f64Bits = simple_f64_bits; +val f64FromBits = simple_f64_from_bits; + + +val max = { f64 x, f64 y -> return x > y ? x : y; }; +val min = { f64 x, f64 y -> return x < y ? x : y; }; diff --git a/chapter33/src/main/smp/sys/rt.smp b/chapter33/src/main/smp/sys/rt.smp new file mode 100644 index 00000000..d62b4def --- /dev/null +++ b/chapter33/src/main/smp/sys/rt.smp @@ -0,0 +1,3 @@ +// Run Time support: "rt" has the same meaning as Java's rt.jar or C's crt.o. +// Native entry helpers are compiled and linked independently of ordinary sys +// imports, so programs without library imports can use the same startup code. diff --git a/chapter33/src/main/smp/sys/rt/simple_args.smp b/chapter33/src/main/smp/sys/rt/simple_args.smp new file mode 100644 index 00000000..6f857d91 --- /dev/null +++ b/chapter33/src/main/smp/sys/rt/simple_args.smp @@ -0,0 +1,24 @@ +// Native startup support, compiled independently and linked with the CRT. +// Raw native addresses stay i64; only the arrays allocated here are Simple objects. +// This startup object is built without sys imports. +u32 _MAX_U32 = (1<<32)-1; +{ i64 i64 -> i64 } simple_argv = "C"; +{ i64 -> i64 } strlen = "C"; +{ i64 i64 i64 -> i64 } memcpy = "C"; + +// Returns a constant argc-length array, filled with not-null constant u8 +// arrays. +val simple_args = { i64 argc, i64 argv -> + if( argc < 0 || argc > _MAX_U32 ) return null; + // Build an initialized + return new u8[][argc] { int i -> + i64 src = simple_argv(argv,i); + i64 len = strlen(src); + if( !(0 < len <= _MAX_U32) ) // If not the u32 range, just use zero-length + len = 0; + val bytes = new u8[len]; + i64 dst = bytes; + memcpy(dst,src,len); // Copy from C memory to Simple memory + return bytes; + }; +}; diff --git a/chapter33/src/main/smp/sys/scan.smp b/chapter33/src/main/smp/sys/scan.smp new file mode 100644 index 00000000..44bedaaa --- /dev/null +++ b/chapter33/src/main/smp/sys/scan.smp @@ -0,0 +1,39 @@ + +// Scanner; a simple string parser. +struct scan { + int !x; // Cursor + bool !bad; // True after a malformed token + u8[~] buf; // Buffer to parse + + new scan = { u8[~] b -> buf = b; }; + + // Skip whitespace + val skip = { -> + while( x < buf# && buf[x] <= ' ' ) + x++; + return self; + }; + + // True if find required character, and skip it; else False. + val match = { u8 c -> + skip(); + if( x >= buf# ) return false; + if( buf[x] != c ) return false; + x++; + return true; + }; + + // Parse a simple number + val number = { -> + skip(); + bool neg = match('-'); + if( x >= buf# || buf[x] < '0' || '9' < buf[x] ) { + bad = true; + return 0; + } + i64 n = 0; + while( x < buf# && '0' <= buf[x] & buf[x] <= '9' ) + n = n*10 + (buf[x++] - '0'); + return neg ? -n : n; + }; +}; diff --git a/chapter33/src/main/smp/sys/text.smp b/chapter33/src/main/smp/sys/text.smp new file mode 100644 index 00000000..77dc2190 --- /dev/null +++ b/chapter33/src/main/smp/sys/text.smp @@ -0,0 +1,100 @@ +// Formatting primitives used directly by interpolation and named converters. +// Keep this module free of interpolation: sys can build itself from source. +// spec's low byte is the format kind; bits 8..12 are flags: - + space # 0. + +val begin = { -> new aryu8(); }; + +val end = { aryu8 b -> + new u8[~b.len]{ i64 i -> b.buf[i]; }; +}; + +val _pad = { !aryu8 b, i64 n, u8 c -> + for( i64 i = 0; i < n; i++ ) b.add(c); + b; +}; + +val string = { !aryu8 b, u8[~] s, i64 spec, i64 width, i64 precision -> + i64 len = s#; + if( precision >= 0 && precision < len ) len = precision; + i64 pad = width-len; + if( !(spec&256) ) _pad(b,pad,' '); + for( i64 i = 0; i < len; i++ ) b.add(s[i]); + if( spec&256 ) _pad(b,pad,' '); + b; +}; + +val integer = { !aryu8 b, i64 value, i64 spec, i64 width, i64 precision -> + i64 kind = spec&255; + if( kind == 'b' ) return string(b,value ? "true" : "false",spec,width,-1); + if( kind == 'c' ) { + if( !(spec&256) ) _pad(b,width-1,' '); + u8 c = value; + b.add(c); + if( spec&256 ) _pad(b,width-1,' '); + return b; + } + bool signed = kind == 0 || kind == 'd' || kind == 'i'; + i64 base = kind == 'o' ? 8 : (kind == 'x' || kind == 'X' ? 16 : 10); + u8[~] alphabet = kind == 'X' ? "0123456789ABCDEF" : "0123456789abcdef"; + val digits = new u8[22]; // Maximum: 22 octal digits for a 64-bit integer. + i64 count = 0, n = value; + // Signed decimal stays nonpositive, including the minimum i64. + if( signed && n > 0 ) n = -n; + if( n == 0 && precision != 0 ) digits[count++] = '0'; + while( n != 0 ) { + i64 q = 0, r = 0; + if( signed ) { q = n/base; r = -(n%base); } + else { + // Unsigned division without a u64 type. Halving first makes + // the dividend nonnegative; the remainder needs at most one fix. + q = ((n>>>1)/base)*2; + r = n-q*base; + if( r >= base ) { q++; r -= base; } + } + digits[count++] = alphabet[r]; + n = q; + } + u8[~] !prefix = ""; + if( signed ) { + if( value < 0 ) prefix = "-"; + else if( spec&512 ) prefix = "+"; + else if( spec&1024 ) prefix = " "; + } else if( (spec&2048) && value != 0 ) { + if( kind == 'x' ) prefix = "0x"; + if( kind == 'X' ) prefix = "0X"; + } + i64 zeros = precision > count ? precision-count : 0; + // Alternate octal always begins with a zero, including precision-zero 0. + if( kind == 'o' && (spec&2048) && zeros == 0 && (count == 0 || digits[count-1] != '0') ) zeros = 1; + i64 pad = width-prefix#-zeros-count; + bool left = (spec&256) != 0; + bool zero = (spec&4096) != 0 && precision < 0 && !left; + if( !left && !zero ) _pad(b,pad,' '); + b.addAry(prefix); + if( zero ) _pad(b,pad,'0'); + _pad(b,zeros,'0'); + while( count > 0 ) b.add(digits[--count]); + if( left ) _pad(b,pad,' '); + b; +}; + +// Only conversion of binary floating-point values is delegated to libc. +// The fixed signature accepts a validated format and returns a byte string. +{ f64 i64 i64 i64 -> u8[~] } simple_text_float = "C"; +val floating = { !aryu8 b, f64 value, i64 spec, i64 width, i64 precision -> + b.addAry(simple_text_float(value,spec,width,precision)); +}; + +// Explicitly named, typed conversions share the same formatting routines. +val int = { i64 x -> end(integer (begin(),x, 0 ,0,-1)); }; +val flt = { f64 x -> end(floating(begin(),x, 0 ,0,-1)); }; +val f32 = { f32 x -> end(floating(begin(),x,'g',0,-1)); }; +val f64 = { f64 x -> end(floating(begin(),x, 0 ,0,-1)); }; +val char = { i64 x -> end(integer (begin(),x,'c',0,-1)); }; +val bool = { bool x -> end(integer (begin(),x,'b',0,-1)); }; +val hex = { i64 x -> end(integer (begin(),x,'x',0,-1)); }; + +// Time selectors occupy spec bits 16..23; padding shares string formatting. +val time = { !aryu8 b, i64 value, i64 spec, i64 width, i64 precision -> + string(b,sys.time.format(value,(spec>>>16)&255),spec,width,-1); +}; diff --git a/chapter33/src/main/smp/sys/time.smp b/chapter33/src/main/smp/sys/time.smp new file mode 100644 index 00000000..27378ffe --- /dev/null +++ b/chapter33/src/main/smp/sys/time.smp @@ -0,0 +1,219 @@ +// Time utilities; get the current time (both nanos and millis), sleep, time zones. +// API, formatting, and timer reference: time/README.md. + +// Instants: bare i64 UTC Unix-epoch milliseconds. Durations: i64 milliseconds. +// Monotonic readings are a separate clock domain, for deadlines/elapsed time. + +val DateTime = DateTime; +val Timers = Timers; +i64 SECOND = 1000; +i64 MINUTE = 60*SECOND; +i64 HOUR = 60*MINUTE; +i64 DAY = 24*HOUR; +i64 NANOS_PER_MS = 1000*1000; + +// Gregorian leap days: every fourth year, except centuries not divisible by 400. +i64 _DAYS_PER_4_YEARS = 4*365+1; +i64 _DAYS_PER_CENTURY = 100*365+100/4-1; +i64 _DAYS_PER_ERA = 4*_DAYS_PER_CENTURY+1; +// Complete years before the Unix epoch and after the last supported date. +i64 _DAYS_BEFORE_EPOCH = 1969*365+1969/4-1969/100+1969/400; +i64 _DAYS_BEFORE_YEAR_10000 = 9999*365+9999/4-9999/100+9999/400; +// The March-based calendar algorithm starts at 0000-03-01, 306 days before 0001-01-01. +i64 _MARCH_EPOCH_DAYS = _DAYS_BEFORE_EPOCH+306; +i64 MIN = -_DAYS_BEFORE_EPOCH*DAY; // 0001-01-01T00:00:00.000Z +i64 MAX = (_DAYS_BEFORE_YEAR_10000-_DAYS_BEFORE_EPOCH)*DAY-1; // 9999-12-31T23:59:59.999Z + +// Access to the underlying LIBC functions +int ISO = 0, CLOCK12 = 1, CLOCK24 = 2, ELAPSED = 3, DATE = 4, CLOCK24_SECONDS = 5; +{ i64 } simple_time_now = "C"; +{ i64 } simple_time_mono = "C"; +{ i64 } simple_time_nano = "C"; +{ i64 i32 -> i32 } simple_time_sleep = "C"; +{ i64 i64 -> i32 } simple_time_local = "C"; +{ i64 i64 u32 -> i32 } simple_time_zone = "C"; +val now = { -> simple_time_now (); }; +val monotonic = { -> simple_time_mono(); }; +val nanoTime = { -> simple_time_nano(); }; +val sleep = { i64 duration_ms -> simple_time_sleep(duration_ms,0); }; +val sleepUntil = { i64 deadline_ms -> simple_time_sleep(deadline_ms,1); }; + +// Signed duration conversions. Overflow returns -1; reverse conversions truncate +// toward zero. An exact duration day is 24 hours, independent of DST. +val _scale = { i64 n, i64 unit -> + if( n > sys.integer.MAX_I64/unit || n < sys.integer.MIN_I64/unit ) return -1; + return n*unit; +}; +val seconds = { i64 n -> _scale(n,SECOND); }; +val minutes = { i64 n -> _scale(n,MINUTE); }; +val hours = { i64 n -> _scale(n,HOUR); }; +val days = { i64 n -> _scale(n,DAY); }; +val toSeconds = { i64 ms -> ms/SECOND; }; +val toMinutes = { i64 ms -> ms/MINUTE; }; +val toHours = { i64 ms -> ms/HOUR; }; +val toDays = { i64 ms -> ms/DAY; }; +val fromNanos = { i64 ns -> ns/NANOS_PER_MS; }; +val toNanos = { i64 ms -> _scale(ms,NANOS_PER_MS); }; + +// Clamp to zero once due, and saturate for widely separated i64 readings. +val remaining = { i64 deadline_ms, i64 current_ms -> + if( deadline_ms <= current_ms ) return 0; + if( current_ms < 0 && deadline_ms > sys.integer.MAX_I64+current_ms ) return sys.integer.MAX_I64; + return deadline_ms-current_ms; +}; + +val leap = { int year -> year%4 == 0 && (year%100 != 0 || year%400 == 0); }; +val monthDays = { int year, int month -> + if( month < 1 || month > 12 ) return 0; + return month == 2 ? (leap(year) ? 29 : 28) : + month == 4 || month == 6 || month == 9 || month == 11 ? 30 : 31; +}; + +// Gregorian civil dates, expressed using 400-year eras; no per-year loops. +val _days = { i64 year, i64 month, i64 day -> + year -= month <= 2 ? 1 : 0; + i64 era = year/400, y = year%400; + i64 mp = month+(month > 2 ? -3 : 9); + return era*_DAYS_PER_ERA+y*365+y/4-y/100+(153*mp+2)/5+day-1-_MARCH_EPOCH_DAYS; +}; + +val valid = { int year, int month, int day, int hour, int minute, int second, int millisecond -> + return year >= 1 && year <= 9999 && month >= 1 && month <= 12 && day >= 1 && day <= monthDays(year,month) && + hour >= 0 && hour <= 23 && minute >= 0 && minute <= 59 && second >= 0 && second <= 59 && + millisecond >= 0 && millisecond <= 999; +}; + +val makeUTC = { int year, int month, int day, int hour, int minute, int second, int millisecond -> + if( !valid(year,month,day,hour,minute,second,millisecond) ) return -1; + return _days(year,month,day)*DAY+hour*HOUR+minute*MINUTE+second*SECOND+millisecond; +}; + +val utc = { i64 instant -> + val d = DateTime.empty(); + if( instant < MIN || instant > MAX ) return d; + i64 day = instant/DAY, rest = instant%DAY; + if( rest < 0 ) { rest += DAY; day--; } + i64 z = day+_MARCH_EPOCH_DAYS, era = z/_DAYS_PER_ERA, doe = z%_DAYS_PER_ERA; + i64 y = (doe-doe/(_DAYS_PER_4_YEARS-1)+doe/_DAYS_PER_CENTURY-doe/(_DAYS_PER_ERA-1))/365; + i64 doy = doe-(365*y+y/4-y/100), mp = (5*doy+2)/153; + d.day = doy-(153*mp+2)/5+1; + d.month = mp+(mp < 10 ? 3 : -9); + d.year = y+era*400+(d.month <= 2 ? 1 : 0); + d.hour = rest/HOUR; d.minute = rest/MINUTE%60; + d.second = rest/SECOND%60; d.millisecond = rest%SECOND; + d.weekday = (day+4)%7; + if( d.weekday < 0 ) d.weekday += 7; + return d; +}; + +val local = { i64 instant -> + val d = DateTime.empty(); + val f = new i64[10]; + i64 ptr = f; + if( simple_time_local(instant,ptr) != 0 ) return d; + d.year = f[0]; d.month = f[1]; d.day = f[2]; + d.hour = f[3]; d.minute = f[4]; d.second = f[5]; d.millisecond = f[6]; + d.weekday = f[7]; d.offsetSeconds = f[8]; d.daylight = f[9] != 0; + return d; +}; + +val zoneName = { i64 instant -> + val bytes = new u8[128]; + i64 ptr = bytes; + int n = simple_time_zone(instant,ptr,bytes#); + if( n < 0 ) return ""; + val b = new aryu8(); + for( int i = 0; i < n; i++ ) b.add(bytes[i]); + return text.end(b); +}; + +val _digits = { !aryu8 b, i64 n, int width -> + text.integer(b,n,'d'|4096,width,-1); +}; + +val _format = { i64 instant, int style, bool localZone -> + val d = localZone ? local(instant) : utc(instant); + if( d.year == 0 || style < 0 || style > 5 || style == 3 ) return "<invalid time>"; + val b = new aryu8(); + if( style == 4 ) { + _digits(b,d.day,2).add('/'); _digits(b,d.month,2).add('/'); _digits(b,d.year%100,2); + } else { + if( style == 0 ) { + _digits(b,d.year,4).add('-'); _digits(b,d.month,2).add('-'); _digits(b,d.day,2).add('T'); + } + int hour = d.hour; + if( style == 1 ) { hour = hour%12; if( hour == 0 ) hour = 12; } + _digits(b,hour,style == 1 ? 1 : 2).add(':'); _digits(b,d.minute,2); + if( style == 0 || style == 5 ) { b.add(':'); _digits(b,d.second,2); } + if( style == 1 ) b.addAry(d.hour < 12 ? "am" : "pm"); + if( style == 0 ) { + b.add('.'); _digits(b,d.millisecond,3); + if( d.offsetSeconds == 0 ) b.add('Z'); + else { + i64 offset = d.offsetSeconds; + b.add(offset < 0 ? '-' : '+'); + if( offset < 0 ) offset = -offset; + _digits(b,offset/3600,2).add(':'); _digits(b,offset/60%60,2); + if( offset%60 != 0 ) { b.add(':'); _digits(b,offset%60,2); } + } + } + } + return text.end(b); +}; + +val elapsed = { i64 ms -> + val b = new aryu8(); + // Nonpositive arithmetic handles the minimum i64 without negating it. + if( ms < 0 ) b.add('-'); else ms = -ms; + _digits(b,-(ms/MINUTE),2).add(':'); + _digits(b,-(ms/SECOND%60),2).add('.'); _digits(b,-(ms%SECOND),3); + return text.end(b); +}; +val format = { i64 instant, int style -> + if( style == ELAPSED ) return elapsed(instant); + return _format(instant,style,false); +}; +val formatLocal = { i64 instant, int style -> + if( style == ELAPSED ) return elapsed(instant); + return _format(instant,style,true); +}; + +val _number = { u8[~] s, i64 at, int count -> + if( at < 0 || count < 1 || at+count > s# ) return -1; + int n = 0; + for( int i = 0; i < count; i++ ) { + int c = s[at+i]; + if( c < '0' || c > '9' ) return -1; + n = n*10+c-'0'; + } + return n; +}; + +// Keep suffix validation separate from calendar construction. +val _parseZone = { u8[~] s, int at, i64 instant -> + if( at < 0 || at >= s# ) return -1; + i64 offset = 0; + if( s[at] == 'Z' ) { if( at+1 != s# ) return -1; } + else { + int sign = s[at] == '+' ? 1 : s[at] == '-' ? -1 : 0; + if( !sign || (s# != at+6 && s# != at+9) || s[at+3] != ':' ) return -1; + int oh = _number(s,at+1,2), om = _number(s,at+4,2), os = 0; + if( s# == at+9 ) { if( s[at+6] != ':' ) return -1; os = _number(s,at+7,2); } + if( oh < 0 || oh > 23 || om < 0 || om > 59 || os < 0 || os > 59 ) return -1; + offset = sign*(oh*HOUR+om*MINUTE+os*SECOND); + } + instant -= offset; + return instant < MIN || instant > MAX ? -1 : instant; +}; + +// Strict ISO absolute instants only. -1 is reserved for failure (and therefore +// cannot distinguish the valid instant one millisecond before Unix epoch). +val parse = { u8[~] s -> + if( s# < 20 || s[4] != '-' || s[7] != '-' || s[10] != 'T' || s[13] != ':' || s[16] != ':' ) return -1; + int y = _number(s, 0,4), m = _number(s, 5,2), d = _number(s, 8,2); + int h = _number(s,11,2), min = _number(s,14,2), sec = _number(s,17,2); + bool fraction = s[19] == '.'; + int ms = fraction ? _number(s,20,3) : 0; + if( !valid(y,m,d,h,min,sec,ms) ) return -1; + return _parseZone(s,fraction ? 23 : 19,makeUTC(y,m,d,h,min,sec,ms)); +}; diff --git a/chapter33/src/main/smp/sys/time/DateTime.smp b/chapter33/src/main/smp/sys/time/DateTime.smp new file mode 100644 index 00000000..53b6688e --- /dev/null +++ b/chapter33/src/main/smp/sys/time/DateTime.smp @@ -0,0 +1,13 @@ +// Calendar view of an instant. Month/day start at 1; weekday is Sunday=0. +// year==0 means out of the supported calendar range (years 1 through 9999). + +// All values default zero/false +struct DateTime { + int year, month, day; + int hour, minute, second, millisecond; + int weekday, offsetSeconds; + bool daylight; +}; + +// Factory in the defining unit, so callers need no forward instance type. +val empty = { -> new DateTime(); }; diff --git a/chapter33/src/main/smp/sys/time/README.md b/chapter33/src/main/smp/sys/time/README.md new file mode 100644 index 00000000..a6966d27 --- /dev/null +++ b/chapter33/src/main/smp/sys/time/README.md @@ -0,0 +1,133 @@ +# Time and single-threaded animation + +[Chapter 31](../../../../../../chapter31/README.md#time-library) introduces the library. +The implementation is in [time.smp](../time.smp), [DateTime.smp](DateTime.smp), +and [Timers.smp](Timers.smp). + +`sys.time` uses bare `i64` values: absolute instants are milliseconds since +the Unix epoch in UTC; durations are milliseconds. Monotonic readings belong +to a separate clock domain. Never subtract a wall-clock reading from a +monotonic deadline. + +## Clocks and waits + +| Call | Result | +| --- | --- | +| `time.now()` | Unix-epoch milliseconds; may jump when the system clock changes. | +| `time.monotonic()` | Monotonic milliseconds for elapsed time and deadlines. | +| `time.nanoTime()` | Monotonic nanoseconds, with the clock's available resolution. | +| `time.sleep(duration_ms)` | Sleep for a nonnegative duration. | +| `time.sleepUntil(deadline_ms)` | Wait for a monotonic millisecond deadline; returns immediately if past. | +| `time.remaining(deadline_ms, current_ms)` | Nonnegative difference, saturating on overflow. | + +Clock errors return `-1`; sleeps return zero on success or `-1` on error, +with `sys.libc.errno()` available. Interrupted sleeps resume rather than +returning early. Wakeup times are approximate, and these calls do not wake a +suspended laptop. Sleeping blocks the one Simple execution thread; use +`gfx.wait` when window input must remain responsive. + +`seconds(n)`, `minutes(n)`, `hours(n)`, and `days(n)` convert signed counts +to milliseconds. `toSeconds(ms)`, `toMinutes(ms)`, `toHours(ms)`, and +`toDays(ms)` truncate toward zero. A duration day is exactly 24 hours, +independent of daylight saving. `toNanos(ms)` and `fromNanos(ns)` convert +between millisecond and nanosecond units. Multiplication overflow returns +`-1`. Constants `SECOND`, `MINUTE`, `HOUR`, and `DAY` are also available, +defined as `1000`, `60*SECOND`, `60*MINUTE`, and `24*HOUR` respectively. +`NANOS_PER_MS` is `1000*1000`. Overflow checks use the shared +`sys.integer.MIN_I64` and `MAX_I64` bounds; `MAX_I32` and `MAX_U32` in that +module also describe the library's array and timer-ID limits. + +## String interpolation + +Time formatting is built into the existing string interpolation syntax: + +| Format | Example | Named style | +| --- | --- | --- | +| `%t(instant)` or `%tF(instant)` | `2026-11-12T00:34:05.123Z` | `time.ISO` | +| `%tr(instant)` | `12:34am` | `time.CLOCK12` | +| `%tR(instant)` | `00:34` | `time.CLOCK24` | +| `%tT(instant)` | `00:34:05` | `time.CLOCK24_SECONDS` | +| `%tD(instant)` | `12/11/26` | `time.DATE` | +| `%tM(duration)` | `02:03.456` | `time.ELAPSED` | + +For example, `"UTC %tR(sys.time.now())"`. Width and left alignment work as +for strings: `%30t(instant)` and `%-30t(instant)`. Precision and numeric flags +are rejected. `%tM` formats a duration, with total minutes rather than wrapping +at an hour; negative durations keep their sign. + +Interpolation uses UTC, making its output stable across machines. +`time.format(instant, style)` is the equivalent library call; +`time.formatLocal(instant, style)` uses the system's local zone. Local ISO +output includes a numeric offset instead of `Z` when nonzero, retaining +offset seconds for historical zones. Invalid calendar values/styles produce +`<invalid time>`. The ISO form retains all millisecond bits within the supported +calendar range; short formats intentionally omit information. + +## Calendar values and absolute parsing + +`time.utc(instant)` and `time.local(instant)` return a `DateTime` with fields +`year`, `month`, `day`, `hour`, `minute`, `second`, `millisecond`, `weekday` +(Sunday = 0), `offsetSeconds` (east of UTC), and `daylight`. A zero year means +conversion failed. `time.zoneName(instant)` returns the local abbreviation or +an empty string on error. Local conversion uses the operating system's zone +rules, including DST at that instant; no time-zone database is downloaded. + +`time.makeUTC(year, month, day, hour, minute, second, millisecond)` validates +and constructs an instant, returning `-1` on invalid fields. `time.valid(...)`, +`time.leap(year)`, and `time.monthDays(year, month)` support calendar checks. +Calendar conversion supports Gregorian years 1 through 9999, bounded by +`time.MIN` and `time.MAX`, and rejects leap seconds. + +`time.parse(text)` accepts strict absolute ISO text: +`YYYY-MM-DDTHH:mm:ss[.SSS]Z` or the same with an explicit `+HH:MM`/`-HH:MM` +offset (optionally with `:SS`). Fractions have exactly three digits. No relative +time parsing, implicit local zone, locale-dependent parsing, or named-zone +conversion is provided. Offsets must have hours 00–23 and minutes/seconds 00–59. +Invalid text or an out-of-range result returns `-1`. By design, this sentinel +is indistinguishable from the valid instant `1969-12-31T23:59:59.999Z`; +formatting and calendar conversion still support that instant. + +## Cooperative timers + +Create `val timers = new sys.time.Timers();` on the game thread: + +Timer IDs are `u32`, with `0` reserved for registration failure or no timer due. +Deadlines, delays, and periods remain `i64` milliseconds; their parameter, +field, and local names end in `_ms` to distinguish them from IDs. + +| Operation | Meaning | +| --- | --- | +| `after(delay_ms)` | Register a one-shot timer; return its positive `u32` ID, or `0`. | +| `every(period_ms)` | Register a repeating timer; period must be positive. Returns a `u32` ID, or `0`. | +| `afterAt(current_ms, delay_ms)`, `everyAt(current_ms, period_ms)` | Supply a monotonic reading explicitly, useful for deterministic tests. | +| `cancel(id)` | Remove a timer; return whether it was present. | +| `nextDeadline()` | Earliest monotonic deadline, or `-1` if empty. | +| `poll(current_ms)` | Return the next due `u32` ID, or `0` if none. | + +Poll repeatedly to drain due timers. Deadlines order delivery, then registration +ID breaks ties. Repeating timers advance from their previous deadline, skipping +missed ticks to the first future deadline rather than drifting or replaying a +backlog. Deadline overflow rejects registration or cancels a repeating timer. +IDs are never reused within a collection; registration fails once all nonzero +`u32` IDs have been issued. +There are no callbacks or timer threads: the caller handles each returned ID. + +`gfx.wait(timeout_ms)` processes events after waiting for input or a timeout: +zero polls, `-1` waits indefinitely, values below `-1` fail. It returns the same +`OK`, `CLOSED`, or `ERROR` statuses as `gfx.poll`, and may wake early. Re-read the +monotonic clock after each wake. This allows one thread to handle timers, +input, simulation, and drawing without busy waiting. + +The [digital and analog clock example](../../../../../docs/examples/Clock.smp) combines these pieces. From +the repository root, with graphics dependencies already cached: + +```sh +make -C chapter33 clock-example # Build without opening a window. +make -C chapter33 run-clock # Build the backend and run. +``` + +Click the button or press Space to switch between green seven-segment digits +and an analog dial with smoothly moving hands. Both display system-local time; +Q/Escape exits. Passing any argument directly to the executable closes it after +ten frames, switching faces halfway through. Hands are computed from the current +time, so delayed frames do not create a simulation catch-up backlog. diff --git a/chapter33/src/main/smp/sys/time/Timers.smp b/chapter33/src/main/smp/sys/time/Timers.smp new file mode 100644 index 00000000..7cca2e9c --- /dev/null +++ b/chapter33/src/main/smp/sys/time/Timers.smp @@ -0,0 +1,80 @@ +// Cooperative timers. poll returns IDs; callbacks never run on another thread. +// IDs are u32; 0 means failure or no timer due. Millisecond values use _ms. + +// The + + +struct Timers { + // Collection of timers (as struct-of-arrays) + u32[] !_ids = new u32[8]; // Which timer id for this slot + i64[] !_due_ms = new i64[8]; // Monotonic deadline in milliseconds + i64[] !_period_ms = new i64[8]; // When does it repeat + // Next available timer ID; 0 means all IDs have been used. + u32 !_next = 1; + + // Add a new timer + { i64 i64 i64 -> u32 } _add = { i64 current_ms, i64 delay_ms, i64 period_ms -> + if( current_ms < 0 || delay_ms < 0 || current_ms > sys.integer.MAX_I64-delay_ms || _next == 0 ) return 0; + // Ugly linear scan for an available slot + int slot = 0; + while( slot < _ids# && _ids[slot] != 0 ) slot++; + // Double size for lots of timers + if( slot == _ids# ) { + if( _ids# > sys.integer.MAX_I32/2 ) return 0; + val ids = new u32[_ids#*2]; + val due_ms = new i64[_ids#*2], periods_ms = new i64[_ids#*2]; + for( int i = 0; i < _ids#; i++ ) { ids[i] = _ids[i]; due_ms[i] = _due_ms[i]; periods_ms[i] = _period_ms[i]; } + _ids = ids; _due_ms = due_ms; _period_ms = periods_ms; + // Retry against the newly published arrays after growing. + return _add(current_ms,delay_ms,period_ms); + } + // Next available timer id + u32 id = _next; + _next = id == sys.integer.MAX_U32 ? 0 : id+1; + _ids[slot] = id; _due_ms[slot] = current_ms+delay_ms; _period_ms[slot] = period_ms; + return id; + }; + + // Explicit-clock versions make game logic and tests deterministic. + { i64 i64 -> u32 } afterAt = { i64 current_ms, i64 delay_ms -> _add(current_ms,delay_ms,0); }; + { i64 i64 -> u32 } everyAt = { i64 current_ms, i64 period_ms -> period_ms <= 0 ? 0 : _add(current_ms,period_ms,period_ms); }; + { i64 -> u32 } after = { i64 delay_ms -> afterAt(time.monotonic(),delay_ms ); }; + { i64 -> u32 } every = { i64 period_ms -> everyAt(time.monotonic(),period_ms); }; + + // Remove a timer + val cancel = { u32 id -> + if( id == 0 ) return false; + for( int i = 0; i < _ids#; i++ ) if( _ids[i] == id ) { _ids[i] = 0; return true; } + return false; + }; + + // Earliest absolute monotonic deadline in milliseconds, or -1 when empty. + val nextDeadline = { -> + i64 next_ms = -1; + // Ugly linear scan again, but short + for( int i = 0; i < _ids#; i++ ) + if( _ids[i] != 0 && (next_ms < 0 || _due_ms[i] < next_ms) ) next_ms = _due_ms[i]; + return next_ms; + }; + + // Next firing timer. + + // Earliest deadline first; equal deadlines use registration order. + // Repeats skip missed ticks and retain their phase, avoiding bursts/drift. + { i64 -> u32 } poll = { i64 current_ms -> + int slot = -1; + for( int i = 0; i < _ids#; i++ ) + if( _ids[i] != 0 && _due_ms[i] <= current_ms && (slot < 0 || _due_ms[i] < _due_ms[slot] || + (_due_ms[i] == _due_ms[slot] && _ids[i] < _ids[slot])) ) slot = i; + if( slot < 0 ) return 0; + u32 id = _ids[slot]; + i64 period_ms = _period_ms[slot]; + if( period_ms == 0 ) _ids[slot] = 0; + else { + i64 steps = (current_ms-_due_ms[slot])/period_ms; + if( steps >= (sys.integer.MAX_I64-_due_ms[slot])/period_ms ) _ids[slot] = 0; + else _due_ms[slot] += (steps+1)*period_ms; + } + return id; + }; +}; |
