From f0a6c6757a795b8e186de0076836a87acef59fa7 Mon Sep 17 00:00:00 2001 From: Cliff Click Date: Sun, 15 Nov 2026 11:20:40 -0800 Subject: Graphics now allow resize Reorganize docs. Fix bugs X86 LOad+cmp scheduling. Math intrinsics --- chapter31/src/main/c/simple_crt.c | 10 ++ chapter31/src/main/c/simple_graphics.c | 8 +- chapter31/src/main/c/simple_graphics.h | 5 +- chapter31/src/main/c/simple_minifb.c | 39 +++++- .../simple/codegen/GlobalCodeMotion.java | 10 +- .../seaofnodes/simple/codegen/ListScheduler.java | 2 +- .../com/seaofnodes/simple/codegen/RegAlloc.java | 12 +- .../java/com/seaofnodes/simple/node/ModFNode.java | 49 +++++++ .../java/com/seaofnodes/simple/node/ModNode.java | 16 +++ .../main/java/com/seaofnodes/simple/node/Node.java | 3 +- .../seaofnodes/simple/node/cpus/arm/ModARM.java | 29 ++++ .../com/seaofnodes/simple/node/cpus/arm/arm.java | 3 +- .../seaofnodes/simple/node/cpus/riscv/DivRISC.java | 17 ++- .../seaofnodes/simple/node/cpus/riscv/riscv.java | 1 + .../simple/node/cpus/x86_64_v2/CmpX86.java | 7 + .../simple/node/cpus/x86_64_v2/DivX86.java | 36 ++++- .../simple/node/cpus/x86_64_v2/x86_64_v2.java | 28 +++- .../com/seaofnodes/simple/parser/Construction.java | 3 +- .../com/seaofnodes/simple/parser/Expressions.java | 4 +- .../java/com/seaofnodes/simple/parser/Lexer.java | 4 +- chapter31/src/main/smp/sys.smp | 2 +- chapter31/src/main/smp/sys/audio.md | 84 +++++++++++ chapter31/src/main/smp/sys/audio.smp | 1 + chapter31/src/main/smp/sys/draw.smp | 1 + chapter31/src/main/smp/sys/draw/Canvas.smp | 68 +++++++-- chapter31/src/main/smp/sys/draw/README.md | 124 +++++++++++++++++ chapter31/src/main/smp/sys/gfx.md | 154 +++++++++++++++++++++ chapter31/src/main/smp/sys/gfx.smp | 19 ++- chapter31/src/main/smp/sys/math.smp | 12 ++ chapter31/src/main/smp/sys/text.smp | 2 +- chapter31/src/main/smp/sys/time.smp | 26 ++-- chapter31/src/main/smp/sys/time/README.md | 133 ++++++++++++++++++ 32 files changed, 855 insertions(+), 57 deletions(-) create mode 100644 chapter31/src/main/java/com/seaofnodes/simple/node/ModFNode.java create mode 100644 chapter31/src/main/java/com/seaofnodes/simple/node/ModNode.java create mode 100644 chapter31/src/main/java/com/seaofnodes/simple/node/cpus/arm/ModARM.java create mode 100644 chapter31/src/main/smp/sys/audio.md create mode 100644 chapter31/src/main/smp/sys/draw/README.md create mode 100644 chapter31/src/main/smp/sys/gfx.md create mode 100644 chapter31/src/main/smp/sys/time/README.md (limited to 'chapter31/src/main') diff --git a/chapter31/src/main/c/simple_crt.c b/chapter31/src/main/c/simple_crt.c index 39708629..e50042c2 100644 --- a/chapter31/src/main/c/simple_crt.c +++ b/chapter31/src/main/c/simple_crt.c @@ -3,6 +3,7 @@ #include #include #include +#include #include #include @@ -19,6 +20,15 @@ double simple_f64_from_bits(int64_t bits) { return value; } +// Floating remainder's machine instruction uses this memory-preserving helper. +double simple_f64_mod(double x, double y) { + // fmod can set errno for NaN-producing inputs; arithmetic leaves it alone. + int saved_errno = errno; + double result = fmod(x, y); + errno = saved_errno; + return result; +} + // errno may be thread-local or a macro calling a platform accessor. int32_t simple_errno(void) { return errno; } int32_t simple_set_errno(int32_t error) { errno = error; return -1; } diff --git a/chapter31/src/main/c/simple_graphics.c b/chapter31/src/main/c/simple_graphics.c index 40d66ba9..a35c28a6 100644 --- a/chapter31/src/main/c/simple_graphics.c +++ b/chapter31/src/main/c/simple_graphics.c @@ -74,7 +74,8 @@ static int load_graphics(void) { if (!candidate || candidate->version != SIMPLE_GRAPHICS_VERSION || !candidate->open || !candidate->present || !candidate->poll || !candidate->mouse_x || !candidate->mouse_y || !candidate->button || - !candidate->key || !candidate->close || !candidate->wait) { + !candidate->key || !candidate->close || !candidate->wait || + !candidate->width || !candidate->height || !candidate->present_size) { fprintf(stderr, "Simple graphics: incompatible MiniFB backend '%s'. Rebuild with make graphics.\n", path); dlclose(library); library = NULL; @@ -93,6 +94,11 @@ int32_t simple_gfx_open(const char *title, uint32_t width, uint32_t height) { int32_t simple_gfx_present(const uint32_t *pixels, uint32_t count) { return api ? api->present(pixels, count) : -1; } +int32_t simple_gfx_present_size(const uint32_t *pixels, uint32_t count, uint32_t width, uint32_t height) { + return api ? api->present_size(pixels, count, width, height) : -1; +} +uint32_t simple_gfx_width(void) { return api ? api->width() : 0; } +uint32_t simple_gfx_height(void) { return api ? api->height() : 0; } int32_t simple_gfx_poll(int32_t wait) { return api ? api->poll(wait) : -1; } int32_t simple_gfx_mouse_x(void) { return api ? api->mouse_x() : 0; } int32_t simple_gfx_mouse_y(void) { return api ? api->mouse_y() : 0; } diff --git a/chapter31/src/main/c/simple_graphics.h b/chapter31/src/main/c/simple_graphics.h index 370256be..d19cac46 100644 --- a/chapter31/src/main/c/simple_graphics.h +++ b/chapter31/src/main/c/simple_graphics.h @@ -15,6 +15,9 @@ struct simple_graphics_api { int32_t (*key)(int32_t); void (*close)(void); int32_t (*wait)(int64_t); + uint32_t (*width)(void); + uint32_t (*height)(void); + int32_t (*present_size)(const uint32_t *, uint32_t, uint32_t, uint32_t); }; -#define SIMPLE_GRAPHICS_VERSION 2 +#define SIMPLE_GRAPHICS_VERSION 3 #endif diff --git a/chapter31/src/main/c/simple_minifb.c b/chapter31/src/main/c/simple_minifb.c index 2117f0d2..86f110c3 100644 --- a/chapter31/src/main/c/simple_minifb.c +++ b/chapter31/src/main/c/simple_minifb.c @@ -14,11 +14,19 @@ #include "x11/WindowData_X11.h" #endif -// One fixed-size window for now. No Simple pointer survives a native call: +// One resizable window. No Simple pointer survives a native call: // MiniFB retains its last draw buffer for OS repaint events, so copy it here. static struct mfb_window *window; static uint32_t *frame; static uint32_t width, height; +static size_t capacity; + +static uint32_t window_width(void) { return window ? mfb_get_window_width(window) : 0; } +static uint32_t window_height(void) { return window ? mfb_get_window_height(window) : 0; } + +static void resize_window(struct mfb_window *w, int x, int y) { + if (x > 0 && y > 0) mfb_set_viewport(w, 0, 0, (unsigned)x, (unsigned)y); +} // The C-only build never installs the upstream C++ callback wrappers. void release_cpp_stub(struct mfb_window *unused) { (void)unused; } @@ -31,6 +39,7 @@ static void close_window(void) { } free(frame); frame = NULL; + capacity = 0; } static int32_t open_window(const char *title, uint32_t w, uint32_t h) { @@ -44,7 +53,8 @@ static int32_t open_window(const char *title, uint32_t w, uint32_t h) { fprintf(stderr, "Simple graphics: cannot allocate the display buffer.\n"); return -1; } - window = mfb_open(title, w, h); + capacity = (size_t)w * h; + window = mfb_open_ex(title, w, h, MFB_WF_RESIZABLE); if (!window) { fprintf(stderr, "Simple graphics: MiniFB could not open a window (is a graphical display available?).\n"); close_window(); @@ -52,6 +62,7 @@ static int32_t open_window(const char *title, uint32_t w, uint32_t h) { } width = w; height = h; + mfb_set_resize_callback(window, resize_window); return 0; } @@ -67,14 +78,29 @@ static int32_t status(mfb_update_state state) { return -1; } -static int32_t present(const uint32_t *pixels, uint32_t count) { +static int32_t present_size(const uint32_t *pixels, uint32_t count, uint32_t w, uint32_t h) { if (!window) return 1; - if (!pixels || count != (uint64_t)width * height) { + if (!pixels || !w || !h || w > UINT32_MAX / 4 || + count != (uint64_t)w * h || (uint64_t)w * h > SIZE_MAX / 4) { fprintf(stderr, "Simple graphics: pixel array length must equal width * height.\n"); return -1; } + if (count > capacity) { + uint32_t *larger = realloc(frame, (size_t)count * sizeof(*frame)); + if (!larger) { + fprintf(stderr, "Simple graphics: cannot resize the display buffer.\n"); + return -1; + } + frame = larger; + capacity = count; + } memcpy(frame, pixels, (size_t)count * sizeof(*frame)); - return status(mfb_update_ex(window, frame, width, height)); + return status(mfb_update_ex(window, frame, w, h)); +} + +// Compatibility for clients drawing at their original resolution. +static int32_t present(const uint32_t *pixels, uint32_t count) { + return present_size(pixels, count, width, height); } static int32_t wait_events(int64_t timeout) { @@ -109,7 +135,8 @@ static int32_t key(int32_t k) { static const struct simple_graphics_api api = { SIMPLE_GRAPHICS_VERSION, open_window, present, poll_events, - mouse_x, mouse_y, button, key, close_window, wait_events + mouse_x, mouse_y, button, key, close_window, wait_events, + window_width, window_height, present_size }; #ifdef _WIN32 __declspec(dllexport) diff --git a/chapter31/src/main/java/com/seaofnodes/simple/codegen/GlobalCodeMotion.java b/chapter31/src/main/java/com/seaofnodes/simple/codegen/GlobalCodeMotion.java index 86cb2e98..83c0677d 100644 --- a/chapter31/src/main/java/com/seaofnodes/simple/codegen/GlobalCodeMotion.java +++ b/chapter31/src/main/java/com/seaofnodes/simple/codegen/GlobalCodeMotion.java @@ -141,10 +141,11 @@ public abstract class GlobalCodeMotion { if( def!=null && !(def instanceof PhiNode) ) _schedEarly(def,code,start); - // An existing edge 0 already supplies control (or a Phi/Proj binding). - if( n.in(0)==null ) { + // A memory op's control is a lower bound, not a complete early schedule: + // instruction selection may have folded in an operand defined later. + if( n.in(0)==null || n instanceof MemOpNode ) { // Schedule at deepest input - CFGNode early = start; // Maximally early, lowest idepth + CFGNode early = n.in(0) instanceof CFGNode ctrl ? ctrl : start; for( int i=1; i early.idepth() ) early = n.in(i).cfg0(); // Latest/deepest input @@ -251,6 +252,9 @@ public abstract class GlobalCodeMotion { if( use != null ) lca = use_block(n,use, late).domLCA(lca,null); + assert lca!=null && early.dominates(lca,null) : + "Early schedule must dominate uses of "+n.getClass().getSimpleName()+"#"+n._nid; + // Loads may need anti-dependencies, raising their LCA if( n instanceof MemOpNode load && load._isLoad ) lca = find_anti_dep(lca,load,early,late,anti, antideps); diff --git a/chapter31/src/main/java/com/seaofnodes/simple/codegen/ListScheduler.java b/chapter31/src/main/java/com/seaofnodes/simple/codegen/ListScheduler.java index c3b603e5..f90d8d4e 100644 --- a/chapter31/src/main/java/com/seaofnodes/simple/codegen/ListScheduler.java +++ b/chapter31/src/main/java/com/seaofnodes/simple/codegen/ListScheduler.java @@ -49,7 +49,7 @@ public abstract class ListScheduler { else computeSingleRDef(bb,n); - if( n instanceof NewNode || n instanceof CallNode ) + if( n instanceof NewNode || n instanceof CallNode || n instanceof ModFNode ) bb.fun()._hasCalls = true; return this; } diff --git a/chapter31/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java b/chapter31/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java index 1b335c50..303fd355 100644 --- a/chapter31/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java +++ b/chapter31/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java @@ -184,6 +184,7 @@ public class RegAlloc { if( bb instanceof CallEndMach cend ) cend.cacheRegs(_code); for( Node n : bb._outputs ) if( n instanceof NewNode nnn ) nnn.cacheRegs(_code); + else if( n instanceof ModFNode mod ) mod.cacheRegs(_code); } // Expensive assert: useful when chasing cross-function allocator edges. //assert verifyFunctionLocalEdges(); @@ -680,7 +681,14 @@ public class RegAlloc { if( cfg==def.cfg0() && def.nOuts()==1 && !singleReg ) return; } - makeSplit(def,kind,round,lrg,umask).insertBefore(n, i); + // If isolating a loop Phi's uses did not relieve pressure, cloning its + // constant input again cannot help: it still forces the Phi into a GPR. + // A real transfer on this retry lets the Phi live on the stack. + Node split = n instanceof PhiNode phi && phi.region() instanceof LoopNode && + lrg._machUse instanceof SplitNode prior && prior._round X86.call(enc); + case "arm" -> enc.add4(Arm64.b(Arm64.OP_CALL,0)); + case "riscv" -> { + enc.add4(RiscV.u_type(RiscV.OP_AUIPC,riscv.T0,0)); + enc.add4(RiscV.i_type(RiscV.OP_JALR,riscv.RPC,0,riscv.T0,0)); + } + default -> throw new IllegalStateException(machine().name()); + } + } + @Override public void asm(CodeGen code, SB sb) { + sb.p(code.reg(this)).p(" = ").p(code.reg(in(1))).p(" % ").p(code.reg(in(2))); + } + @Override public String comment() { return "call simple_f64_mod"; } +} diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/ModNode.java b/chapter31/src/main/java/com/seaofnodes/simple/node/ModNode.java new file mode 100644 index 00000000..7c1a9238 --- /dev/null +++ b/chapter31/src/main/java/com/seaofnodes/simple/node/ModNode.java @@ -0,0 +1,16 @@ +package com.seaofnodes.simple.node; + +import com.seaofnodes.simple.type.TypeInteger; + +public class ModNode extends ArithNode { + public ModNode(Node lhs, Node rhs) { super(null,lhs,rhs); } + public ModNode(Node lhs, Node rhs, byte mode) { super(null,lhs,rhs,mode); } + @Override public Tag serialTag() { return Tag.Mod; } + @Override public String op() { return "%"; } + @Override boolean allowFloat() { return true; } + + @Override long doOp(long x, long y) { return y==0 ? 0 : x%y; } + @Override double doOp(double x, double y) { return x%y; } + @Override TypeInteger doOp(TypeInteger x, TypeInteger y) { return TypeInteger.BOT; } + @Override Node copy(Node lhs, Node rhs) { return new ModNode(lhs,rhs,_mode); } +} diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/Node.java b/chapter31/src/main/java/com/seaofnodes/simple/node/Node.java index d4c0794c..ad4f47e0 100644 --- a/chapter31/src/main/java/com/seaofnodes/simple/node/Node.java +++ b/chapter31/src/main/java/com/seaofnodes/simple/node/Node.java @@ -77,7 +77,7 @@ public abstract class Node extends BaseNode implements Cloneable { New,Never,Not,Or,Parm,Phi,Proj,PtrToInt, ReadOnly,Return,Region,RoundF32, Sar,Shl,Shr,Start,StartCU,StopCU,Stop,Store,Sub, - ToInteger,ToFloat,XCtrl,Xor,F64Bits,F64FromBits; + ToInteger,ToFloat,XCtrl,Xor,F64Bits,F64FromBits,Mod; public static final Tag[] VALS = values(); public Node make( BAOS bais, String[] strs, Type[] types, GlobalBits fileAliases, GlobalBits aliases ) { return switch(this) { @@ -117,6 +117,7 @@ public abstract class Node extends BaseNode implements Cloneable { case Call -> CallNode.make(bais,strs); case CallEnd-> CallEndNode.make(bais ,types); case CLInit -> new CLInitNode(bais,strs); + case Mod -> new ModNode(null,null,(byte)bais.packed1()); case CProj -> CProjNode.make(bais,strs); case Con -> ConstantNode.make(bais ,types); case Escape-> EscapeNode.make(bais ,types); diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/arm/ModARM.java b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/arm/ModARM.java new file mode 100644 index 00000000..bd29ba3f --- /dev/null +++ b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/arm/ModARM.java @@ -0,0 +1,29 @@ +package com.seaofnodes.simple.node.cpus.arm; + +import com.seaofnodes.isa.Arm64; +import com.seaofnodes.simple.codegen.*; +import com.seaofnodes.simple.node.*; +import com.seaofnodes.simple.util.SB; + +public class ModARM extends MachConcreteNode implements MachNode { + private static final RegMask REGS=new RegMask(arm.WR_BITS & ~(1L< new CProjNode(c); case ConstantNode con-> con(con); case DivNode div -> div.mode()==2 ? new DivFARM(div) : new DivARM(div); + case ModNode mod -> mod.mode()==2 ? new ModFNode(mod) : new ModARM(mod); case EscapeNode esc -> new EscapeNode(esc); case FunNode fun -> new FunARM(fun); case FunPtrNode fptr -> fptr(fptr); diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/DivRISC.java b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/DivRISC.java index 515ffa47..691979ec 100644 --- a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/DivRISC.java +++ b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/DivRISC.java @@ -1,17 +1,26 @@ package com.seaofnodes.simple.node.cpus.riscv; +import com.seaofnodes.isa.RiscV; import com.seaofnodes.simple.util.SB; import com.seaofnodes.simple.codegen.*; import com.seaofnodes.simple.node.*; public class DivRISC extends MachConcreteNode implements MachNode{ - public DivRISC(Node div) {super(div);} - @Override public String op() { return "div"; } + private final boolean _mod; + public DivRISC(Node div) {super(div); _mod=div instanceof ModNode;} + @Override public String op() { return _mod ? "mod" : "div"; } @Override public RegMask regmap(int i) { return riscv.RMASK; } @Override public RegMask outregmap() { return riscv.WMASK; } - @Override public void encoding( Encoding enc ) { riscv.r_type(enc,this,4,1); } + @Override public void encoding( Encoding enc ) { + // RISC-V returns -1 for DIV by zero, and the dividend for REM by zero. + // Both ideal operations instead return zero. + enc.add4(RiscV.b_type(RiscV.OP_BRANCH,1,enc.reg(in(2)),(short)riscv.ZERO,12)); + enc.add4(RiscV.i_type(RiscV.OP_IMM,enc.reg(this),0,riscv.ZERO,0)); + enc.add4(RiscV.j_type(RiscV.OP_JAL,riscv.ZERO,8)); + riscv.r_type(enc,this,_mod ? 6 : 4,1); + } @Override public void asm(CodeGen code, SB sb) { - sb.p(code.reg(this)).p(" = ").p(code.reg(in(1))).p(" / ").p(code.reg(in(2))); + sb.p(code.reg(this)).p(" = ").p(code.reg(in(1))).p(_mod ? " % " : " / ").p(code.reg(in(2))); } } diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/riscv.java b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/riscv.java index 976d1a52..70585732 100644 --- a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/riscv.java +++ b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/riscv/riscv.java @@ -222,6 +222,7 @@ public class riscv extends Machine { case CProjNode c -> new CProjNode(c); case ConstantNode con -> con(con); case DivNode div -> div.mode()==2 ? new DivFRISC(div) : new DivRISC(div); + case ModNode mod -> mod.mode()==2 ? new ModFNode(mod) : new DivRISC(mod); case EscapeNode esc -> new EscapeNode(esc); case FunNode fun -> new FunRISC(fun); case FunPtrNode fptr -> fptr(fptr); diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/CmpX86.java b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/CmpX86.java index 7faea17b..f8e652df 100644 --- a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/CmpX86.java +++ b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/CmpX86.java @@ -7,6 +7,12 @@ import com.seaofnodes.simple.util.SB; public class CmpX86 extends MachConcreteNode implements MachNode { CmpX86( Node add ) { super(add); } + private CmpX86(CmpX86 cmp) { + super((Node)null); + addDef(null); + addDef(cmp.in(1)); + addDef(cmp.in(2)); + } @Override public String op() { return "cmp"; } @Override public RegMask regmap(int i) { return x86_64_v2.RMASK; } @Override public RegMask outregmap() { return x86_64_v2.FLAGS_MASK; } @@ -16,6 +22,7 @@ public class CmpX86 extends MachConcreteNode implements MachNode { // compared to some normal registers - and those normal registers might not // be spilling! @Override public boolean isClone() { return true; } + @Override public Node copy() { return new CmpX86(this); } @Override public void encoding( Encoding enc ) { X86.reg(enc,0x3B,enc.reg(in(1)),enc.reg(in(2))); diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/DivX86.java b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/DivX86.java index 9f375a80..7607913f 100644 --- a/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/DivX86.java +++ b/chapter31/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/DivX86.java @@ -6,20 +6,42 @@ import com.seaofnodes.simple.node.*; import com.seaofnodes.simple.util.SB; public class DivX86 extends MachConcreteNode implements MachNode { - DivX86( Node div ) { super(div); } - @Override public String op() { return "div"; } + private final boolean _mod; + DivX86( Node div ) { super(div); _mod=div instanceof ModNode; } + @Override public String op() { return _mod ? "mod" : "div"; } @Override public RegMask regmap(int i) { return (i==1) ? x86_64_v2.RAX_MASK : x86_64_v2.DIV_MASK; } - @Override public RegMask outregmap() { return x86_64_v2.RAX_MASK; } - @Override public RegMask killmap() { return x86_64_v2.RDX_MASK; } + @Override public RegMask outregmap() { return _mod ? x86_64_v2.RDX_MASK : x86_64_v2.RAX_MASK; } + @Override public RegMask killmap() { + return new RegMask((1L<<(_mod ? x86_64_v2.RAX : x86_64_v2.RDX)) | (1L< new GuardMach(guard); case ConstantNode con -> con(con); case DivNode div -> div.mode()==2 ? new DivFX86(div) : new DivX86(div); + case ModNode mod -> mod.mode()==2 ? new ModFNode(mod) : new DivX86(mod); case EscapeNode esc -> new EscapeNode(esc); case FunNode fun -> new FunX86(fun); case FunPtrNode fptr -> fptr(fptr); @@ -354,7 +357,7 @@ public class x86_64_v2 extends Machine { return new AddFX86(add); Node lhs = add.in(1); Node rhs = add.in(2); - if( lhs instanceof LoadNode ld && ld.nOuts() == 1 && ld.declaredType().log_size() >= 3) + if( lhs instanceof LoadNode ld && ld.declaredType().log_size() >= 3 && canFoldLoad(ld,rhs) ) return new AddMemX86(add, address(ld), ld.ptr(), idx, off, scale, 0, rhs); // Attempt a full LEA-style break down. // Returns one of AddX86, AddIX86, LeaX86, or LHS @@ -430,11 +433,11 @@ public class x86_64_v2 extends Machine { // Since cmp does not record a BOP, SetX/Jmp need to know if the CMP is swapped. // Vs memory - if( lhs instanceof LoadNode ld && ld.nOuts() == 1 && rhs._type.isa(ld.declaredType()) ) + if( lhs instanceof LoadNode ld && rhs._type.isa(ld.declaredType()) && canFoldLoad(ld,rhs) ) return new CmpMemX86(bool, address(ld), ld.ptr(), idx, off, scale, imm(rhs), val, false); // Operands swap in the encoding directly, no need for Set/Jmp to swap `bop` - if( rhs instanceof LoadNode ld && ld.nOuts() == 1 && lhs._type.isa(ld.declaredType()) && + if( rhs instanceof LoadNode ld && lhs._type.isa(ld.declaredType()) && canFoldLoad(ld,lhs) && (!(lhs instanceof ConstantNode con && con._con instanceof TypeInteger ti && imm32(ti.value())) || bool.op()=="==" || bool.op()=="!=") ) return new CmpMemX86(bool, address(ld), ld.ptr(), idx, off, scale, imm(lhs), val, true ); @@ -451,6 +454,25 @@ public class x86_64_v2 extends Machine { return new CmpX86(bool); } + // The other operand must not depend on a writer which must follow this + // load. Fusing them would move the read across that write (or form a + // scheduling cycle). Control dependencies count too, including calls. + private static boolean canFoldLoad(LoadNode load, Node value) { + if( load.nOuts()!=1 ) return false; + Ary writers=load.antiDeps(new Ary<>(Node.class)); + if( writers.isEmpty() ) return true; + var seen=new IdentityHashMap(); + Ary work=new Ary<>(Node.class); + work.push(value); + while( !work.isEmpty() ) { + Node n=work.pop(); + if( seen.put(n,Boolean.TRUE)!=null ) continue; + if( writers.find(n)!=-1 ) return false; + for( Node def : n._inputs ) if( def!=null ) work.push(def); + } + return true; + } + private Node con( ConstantNode con ) { if( !con._con.isConstant() ) return ConstantNode.raw(con); // Default unknown caller inputs diff --git a/chapter31/src/main/java/com/seaofnodes/simple/parser/Construction.java b/chapter31/src/main/java/com/seaofnodes/simple/parser/Construction.java index 6dec8ac1..7797cae4 100644 --- a/chapter31/src/main/java/com/seaofnodes/simple/parser/Construction.java +++ b/chapter31/src/main/java/com/seaofnodes/simple/parser/Construction.java @@ -56,7 +56,8 @@ import com.seaofnodes.simple.util.Ary; * binding denotes the allocator. Private-memory Parms therefore need no * fictitious external default or constructor-specific transfer function. * InitView and Construct are erased by the existing TypeCheck walk. There is - * no extra construction pass; see docs/construction-groups.md. + * no extra construction pass; see chapter29/docs/construction-groups.md + * from the repository root, and chapter29/README.md for the introduction. */ final class Construction { private final Parser P; diff --git a/chapter31/src/main/java/com/seaofnodes/simple/parser/Expressions.java b/chapter31/src/main/java/com/seaofnodes/simple/parser/Expressions.java index 6486aba8..ffc96f57 100644 --- a/chapter31/src/main/java/com/seaofnodes/simple/parser/Expressions.java +++ b/chapter31/src/main/java/com/seaofnodes/simple/parser/Expressions.java @@ -233,7 +233,7 @@ final class Expressions { * Parse an multiplicativeExpr expression * *
-     *     multiplicativeExpr : unaryExpr (('*' | '/') unaryExpr)*
+     *     multiplicativeExpr : unaryExpr (('*' | '/' | '%') unaryExpr)*
      * 
* @return a multiply expression {@link Node}, never {@code null} */ @@ -242,6 +242,7 @@ final class Expressions { while( true ) { if( P.match("*") ) lhs = new MulNode(lhs,null); else if( P.match("/") ) lhs = new DivNode(lhs,null); + else if( P.match("%") ) lhs = new ModNode(lhs,null); else break; lhs.setDef(2,parseUnary()); lhs = P.peep(lhs); @@ -341,6 +342,7 @@ final class Expressions { case '-' -> new SubNode(lhs,rhs); case '*' -> new MulNode(lhs,rhs); case '/' -> new DivNode(lhs,rhs); + case '%' -> new ModNode(lhs,rhs); case '|' -> new OrNode(null,lhs,rhs); case '&' -> new AndNode(null,lhs,rhs); case '^' -> new XorNode(P.loc(),lhs,rhs); diff --git a/chapter31/src/main/java/com/seaofnodes/simple/parser/Lexer.java b/chapter31/src/main/java/com/seaofnodes/simple/parser/Lexer.java index 62dd054e..8633f2be 100644 --- a/chapter31/src/main/java/com/seaofnodes/simple/parser/Lexer.java +++ b/chapter31/src/main/java/com/seaofnodes/simple/parser/Lexer.java @@ -325,7 +325,7 @@ public class Lexer { // private boolean isPunctuation(char ch) { - return "=;[]<>()+-/*&|^".indexOf(ch) != -1; + return "=;[]<>()+-/*%&|^".indexOf(ch) != -1; } private String parsePunctuation() { @@ -350,7 +350,7 @@ public class Lexer { if( match(">>=" ) ) return SAR; if( _position+2 >= _input.length ) return 0; char ch0 = (char)_input[_position]; - if( "+-/*&|^".indexOf(ch0) == -1 ) return 0; + if( "+-/*%&|^".indexOf(ch0) == -1 ) return 0; char ch1 = (char)_input[_position+1]; if( ch1 == '=' ) { _position += 2; return ch0; } if( isIdLetter((char)_input[_position+2]) ) return 0; diff --git a/chapter31/src/main/smp/sys.smp b/chapter31/src/main/smp/sys.smp index 3fb8d94b..58896f33 100644 --- a/chapter31/src/main/smp/sys.smp +++ b/chapter31/src/main/smp/sys.smp @@ -8,7 +8,7 @@ val aryi64 = aryi64; // Variable sized array of i64 val aryu8 = aryu8; // Variable sized array of u8 val char = char; // Character utilities val integer = integer; // Integer bounds -val math = math; // Floating-point representation primitives +val math = math; // Math functions, constants, and float representations val io = io; // IO library val gfx = gfx; // Optional pixel window (MiniFB) val draw = draw; // Software raster drawing in Simple diff --git a/chapter31/src/main/smp/sys/audio.md b/chapter31/src/main/smp/sys/audio.md new file mode 100644 index 00000000..bb2ad77c --- /dev/null +++ b/chapter31/src/main/smp/sys/audio.md @@ -0,0 +1,84 @@ +# Optional background audio + +[Chapter 31](../../../../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 `chapter31`: + +```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 `chapter31`, 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/chapter31/src/main/smp/sys/audio.smp b/chapter31/src/main/smp/sys/audio.smp index 89e6dfa9..5dbe63a3 100644 --- a/chapter31/src/main/smp/sys/audio.smp +++ b/chapter31/src/main/smp/sys/audio.smp @@ -1,4 +1,5 @@ // 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; diff --git a/chapter31/src/main/smp/sys/draw.smp b/chapter31/src/main/smp/sys/draw.smp index 2a8b6117..92bf04b7 100644 --- a/chapter31/src/main/smp/sys/draw.smp +++ b/chapter31/src/main/smp/sys/draw.smp @@ -1,4 +1,5 @@ // 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; diff --git a/chapter31/src/main/smp/sys/draw/Canvas.smp b/chapter31/src/main/smp/sys/draw/Canvas.smp index 9ba3514a..5ec7c9ef 100644 --- a/chapter31/src/main/smp/sys/draw/Canvas.smp +++ b/chapter31/src/main/smp/sys/draw/Canvas.smp @@ -1,32 +1,76 @@ struct Canvas { - u32 width; - u32 height; - u32[] pixels; + 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 -> - for( int i = 0; i < pixels#; i++ ) pixels[i] = 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 -> - if( 0 <= x < width && 0 <= y < height ) pixels[y*width+x] = color; - return self; + 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 = x; right += w; - i64 bottom = y; bottom += h; + 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; @@ -55,6 +99,10 @@ struct Canvas { }; 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; @@ -79,6 +127,10 @@ struct Canvas { // 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; diff --git a/chapter31/src/main/smp/sys/draw/README.md b/chapter31/src/main/smp/sys/draw/README.md new file mode 100644 index 00000000..7d3bf6c8 --- /dev/null +++ b/chapter31/src/main/smp/sys/draw/README.md @@ -0,0 +1,124 @@ +# Drawing in Simple + +[Chapter 31](../../../../../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 `chapter31`: + +```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/chapter31/src/main/smp/sys/gfx.md b/chapter31/src/main/smp/sys/gfx.md new file mode 100644 index 00000000..931d985f --- /dev/null +++ b/chapter31/src/main/smp/sys/gfx.md @@ -0,0 +1,154 @@ +# Optional graphics + +[Chapter 31](../../../../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 `chapter31`, 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 `chapter31`: + +```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-.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 `chapter31` 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 chapter31 && 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/` and `../release/` directories. These cover +the examples and test build layouts regardless of the current directory. +It also checks the current directory, `build/release/`, and +`chapter31/build/release/` 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/chapter31/src/main/smp/sys/gfx.smp b/chapter31/src/main/smp/sys/gfx.smp index ae203bd1..60505ac9 100644 --- a/chapter31/src/main/smp/sys/gfx.smp +++ b/chapter31/src/main/smp/sys/gfx.smp @@ -1,5 +1,6 @@ // Minimal pixel-window interface; drawing belongs in Simple. -// One fixed-size window, main thread only. Pixel format is 0x00RRGGBB. +// 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; @@ -9,6 +10,9 @@ 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"; @@ -31,6 +35,19 @@ val present = { u32[~] 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(); }; diff --git a/chapter31/src/main/smp/sys/math.smp b/chapter31/src/main/smp/sys/math.smp index a5e1887c..33bb0e5f 100644 --- a/chapter31/src/main/smp/sys/math.smp +++ b/chapter31/src/main/smp/sys/math.smp @@ -2,7 +2,19 @@ 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"; diff --git a/chapter31/src/main/smp/sys/text.smp b/chapter31/src/main/smp/sys/text.smp index 43698f22..77dc2190 100644 --- a/chapter31/src/main/smp/sys/text.smp +++ b/chapter31/src/main/smp/sys/text.smp @@ -43,7 +43,7 @@ val integer = { !aryu8 b, i64 value, i64 spec, i64 width, i64 precision -> if( n == 0 && precision != 0 ) digits[count++] = '0'; while( n != 0 ) { i64 q = 0, r = 0; - if( signed ) { q = n/base; r = q*base-n; } + 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. diff --git a/chapter31/src/main/smp/sys/time.smp b/chapter31/src/main/smp/sys/time.smp index a3e9b3a2..27378ffe 100644 --- a/chapter31/src/main/smp/sys/time.smp +++ b/chapter31/src/main/smp/sys/time.smp @@ -1,4 +1,5 @@ // 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. @@ -61,8 +62,7 @@ val remaining = { i64 deadline_ms, i64 current_ms -> return deadline_ms-current_ms; }; -val _mod = { i64 n, i64 unit -> n-n/unit*unit; }; -val leap = { int year -> _mod(year,4) == 0 && (_mod(year,100) != 0 || _mod(year,400) == 0); }; +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) : @@ -72,7 +72,7 @@ val monthDays = { int year, int month -> // 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-era*400; + 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; }; @@ -91,17 +91,17 @@ val makeUTC = { int year, int month, int day, int hour, int minute, int second, val utc = { i64 instant -> val d = DateTime.empty(); if( instant < MIN || instant > MAX ) return d; - i64 day = instant/DAY, rest = _mod(instant,DAY); + 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-era*_DAYS_PER_ERA; + 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 = _mod(rest/MINUTE,60); - d.second = _mod(rest/SECOND,60); d.millisecond = _mod(rest,SECOND); - d.weekday = _mod(day+4,7); + 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; }; @@ -136,13 +136,13 @@ val _format = { i64 instant, int style, bool localZone -> if( d.year == 0 || style < 0 || style > 5 || style == 3 ) return ""; val b = new aryu8(); if( style == 4 ) { - _digits(b,d.day,2).add('/'); _digits(b,d.month,2).add('/'); _digits(b,_mod(d.year,100),2); + _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 = _mod(hour,12); if( hour == 0 ) hour = 12; } + 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"); @@ -153,8 +153,8 @@ val _format = { i64 instant, int style, bool localZone -> i64 offset = d.offsetSeconds; b.add(offset < 0 ? '-' : '+'); if( offset < 0 ) offset = -offset; - _digits(b,offset/3600,2).add(':'); _digits(b,_mod(offset/60,60),2); - if( _mod(offset,60) != 0 ) { b.add(':'); _digits(b,_mod(offset,60),2); } + _digits(b,offset/3600,2).add(':'); _digits(b,offset/60%60,2); + if( offset%60 != 0 ) { b.add(':'); _digits(b,offset%60,2); } } } } @@ -166,7 +166,7 @@ val elapsed = { i64 ms -> // 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,-_mod(ms/SECOND,60),2).add('.'); _digits(b,-_mod(ms,SECOND),3); + _digits(b,-(ms/SECOND%60),2).add('.'); _digits(b,-(ms%SECOND),3); return text.end(b); }; val format = { i64 instant, int style -> diff --git a/chapter31/src/main/smp/sys/time/README.md b/chapter31/src/main/smp/sys/time/README.md new file mode 100644 index 00000000..baa920cb --- /dev/null +++ b/chapter31/src/main/smp/sys/time/README.md @@ -0,0 +1,133 @@ +# Time and single-threaded animation + +[Chapter 31](../../../../../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 +``. 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 chapter31 clock-example # Build without opening a window. +make -C chapter31 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. -- cgit v1.2.3