From efdb569bfb9b41a5020fdcb07de1ec16eabe0d7c Mon Sep 17 00:00:00 2001 From: Daniel McCoy Stephenson Date: Fri, 20 Nov 2026 18:01:29 -0700 Subject: [PATCH 01/11] fix: 3D turned off while loading, then on again, no longer leaves a blank page Strata 0.9.0's grid-relay.js forgets a close() that arrives while its module loads: it finishes "ready" on a hidden canvas, and a later request() returns at once without showing it, so the template hid the 2D canvas with nothing in its place. The template now closes and reopens a relay found ready on a hidden canvas, stops a relay that finishes loading after 2D was chosen, and counts the 3D view as drawing only when its canvas is shown. A Node test drives the template's script against a stand-in for the 0.9.0 relay. drafted by Claude on behalf of Daniel Stephenson Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LYNeuoCqxFpUXrFhxnTg89 --- .../graphik/grid3d/templates/pygbag.tmpl | 20 ++- .../graphik/grid3d/test_grid3d_template_js.py | 133 ++++++++++++++++++ .../graphik/grid3d/test_grid3d_web.py | 4 +- 3 files changed, 152 insertions(+), 5 deletions(-) create mode 100644 src/test/python/preponderous/graphik/grid3d/test_grid3d_template_js.py diff --git a/src/main/python/preponderous/graphik/grid3d/templates/pygbag.tmpl b/src/main/python/preponderous/graphik/grid3d/templates/pygbag.tmpl index 8a40f05..082c249 100644 --- a/src/main/python/preponderous/graphik/grid3d/templates/pygbag.tmpl +++ b/src/main/python/preponderous/graphik/grid3d/templates/pygbag.tmpl @@ -578,7 +578,14 @@ frameborder="1" function start() { // the engine starts loading at once; the game's Grid3DWebView.open() // finds it already loading - window.StrataGridRelay.request(JSON.stringify({canvas: "relay", title: document.title || "the 3D view"})); + const relay = window.StrataGridRelay; + // Strata 0.9.0's relay forgets a close() that came while it loaded: it + // finishes "ready" on a hidden canvas, and request() then returns at once + // without showing it, so 3D would replace 2D with nothing. Closing it + // again first makes request() show it (a newer relay does this itself). + const c = canvas3d(); + if (relay.state() === "ready" && c && c.hidden) relay.close(); + relay.request(JSON.stringify({canvas: "relay", title: document.title || "the 3D view"})); } function set(value, reason) { on = value ? 1 : 0; @@ -608,9 +615,16 @@ frameborder="1" // comes back if 3D fails, so there is always a view on screen. setInterval(function () { const relay = scripts === "ready" ? window.StrataGridRelay : null; - if (!on || !relay) return; + if (!relay) return; const state = relay.state(); - const drawing = state === "ready" && fed; + if (!on) { + // 2D was chosen while the 3D view loaded: once it is in, it stops + // drawing (Strata 0.9.0's relay would draw on, hidden, for nothing) + if (state === "ready") relay.close(); + return; + } + const c = canvas3d(); + const drawing = state === "ready" && fed && !(c && c.hidden); show3d(drawing); if (drawing) show2d(false); else if (state.indexOf("failed:") === 0) fail(state.slice(7)); diff --git a/src/test/python/preponderous/graphik/grid3d/test_grid3d_template_js.py b/src/test/python/preponderous/graphik/grid3d/test_grid3d_template_js.py new file mode 100644 index 0000000..d77f2b6 --- /dev/null +++ b/src/test/python/preponderous/graphik/grid3d/test_grid3d_template_js.py @@ -0,0 +1,133 @@ +"""The pygbag template's 2D/3D switch, run in Node against a stand-in page +and a stand-in grid relay that behaves as Strata 0.9.0's does (the relay a +game copies with relay.py today). Skipped where there is no `node`. + +What the string checks in test_grid3d_web.py can't see: the order things +happen in. A player who turns 3D off while the relay is still loading, then +on again, must get the 3D view (not a blank page with both canvases hidden), +and a relay that finishes loading after 2D was chosen must stop drawing. +""" + +import json +import shutil +import subprocess + +import pytest + +from preponderous.graphik.grid3d import web + +NODE = shutil.which("node") + +HARNESS = r""" +const vm = require("vm"); +const block = require("fs").readFileSync(process.argv[2], "utf8"); +const steps = JSON.parse(process.argv[3]); + +function element(id) { + const listeners = {}; + return { + id, hidden: id === "relay" || id === "graphik3d-note", style: {}, textContent: "", title: "", + attrs: {"data-default-view": "3d"}, + getAttribute(n) { return this.attrs[n] || null; }, setAttribute(n, v) { this.attrs[n] = String(v); }, + addEventListener(t, f) { (listeners[t] = listeners[t] || []).push(f); }, + fire(t) { (listeners[t] || []).forEach((f) => f({})); }, + getBoundingClientRect: () => ({left: 700, top: 8, width: 60, height: 36}), focus() {}, + }; +} +const els = {canvas: element("canvas"), relay: element("relay"), graphik3d: element("graphik3d"), + "graphik3d-note": element("graphik3d-note")}; +els.canvas.style.visibility = "visible"; +let interval = null, pendingScripts = []; + +// Strata 0.9.0's grid-relay.js, as far as the page sees it: close() while +// loading hides the canvas but is forgotten when loading ends, and +// request() on a "ready" relay returns without showing the canvas. +const relay = { + s: "idle", kit: false, running: false, sent: 0, + request() { + if (this.s === "loading" || this.s === "ready") return this.s; + if (this.kit && this.s === "idle") { els.relay.hidden = false; this.s = "ready"; this.running = true; return this.s; } + this.s = "loading"; els.relay.hidden = false; return this.s; + }, + finishLoading() { if (this.s === "loading") { this.kit = true; this.s = "ready"; this.running = true; } }, + state() { return this.s; }, + send() { this.sent++; return 0; }, + close() { this.running = false; els.relay.hidden = true; if (this.s === "ready") this.s = "idle"; }, +}; + +const window = { + location: {search: ""}, WebGL2RenderingContext: function () {}, + localStorage: {getItem: () => null, setItem() {}}, + addEventListener() {}, removeEventListener() {}, +}; +const document = { + getElementById: (id) => els[id] || null, + createElement: () => ({}), + body: {appendChild(tag) { pendingScripts.push(tag); }}, +}; +const context = {window, document, URLSearchParams, JSON, String, Number, Math, + setInterval: (f) => { interval = f; return 1; }, setTimeout: () => 0, clearTimeout() {}}; +vm.runInNewContext(block, context); + +function loadScripts() { // the injected scripts load, one after another + while (pendingScripts.length) { + const tag = pendingScripts.shift(); + if (tag.src === "grid-relay.js") window.StrataGridRelay = relay; + tag.onload(); + } +} +const log = []; +for (const step of steps) { + if (step === "scripts") loadScripts(); + else if (step === "click") els.graphik3d.fire("click"); + else if (step === "loaded") relay.finishLoading(); + else if (step === "send") window.StrataGridRelay.send("AAAA"); + else if (step === "tick") interval(); + log.push({step, state: relay.s, running: relay.running, relayHidden: els.relay.hidden, + relayVisible: els.relay.style.visibility === "visible", twoD: els.canvas.style.visibility, + wanted: window.Graphik3D.wanted()}); +} +console.log(JSON.stringify(log)); +""" + + +def graphikScript(page): + block = page[page.index("graphik grid3d:"):] + start = block.index("", start)] + + +def run(tmp_path, steps): + with open(web.templatePath(), encoding="utf-8") as handle: + script = graphikScript(handle.read()) + (tmp_path / "block.js").write_text(script, encoding="utf-8") + (tmp_path / "harness.js").write_text(HARNESS, encoding="utf-8") + out = subprocess.run([NODE, str(tmp_path / "harness.js"), str(tmp_path / "block.js"), json.dumps(steps)], + capture_output=True, text=True, timeout=60) + assert out.returncode == 0, out.stderr + return json.loads(out.stdout) + + +@pytest.mark.skipif(NODE is None, reason="needs node") +def test_3d_turned_off_while_loading_then_on_again_shows_the_3d_view(tmp_path): + log = run(tmp_path, ["scripts", "click", "loaded", "tick", "click", "send", "tick"]) + last = log[-1] + # the game is drawing in 3D: the relay's canvas is shown, not just "visible" while hidden + assert last["state"] == "ready" and last["running"] + assert last["relayVisible"] and not last["relayHidden"] + assert last["twoD"] == "hidden" + + +@pytest.mark.skipif(NODE is None, reason="needs node") +def test_a_relay_that_finishes_loading_after_2d_was_chosen_stops_drawing(tmp_path): + log = run(tmp_path, ["scripts", "click", "loaded", "tick"]) + last = log[-1] + assert not last["running"] and last["state"] == "idle" + assert last["twoD"] == "visible" and not last["wanted"] + + +@pytest.mark.skipif(NODE is None, reason="needs node") +def test_the_2d_view_stays_until_the_3d_view_is_drawing_the_game(tmp_path): + log = run(tmp_path, ["scripts", "loaded", "tick", "send", "tick"]) + assert log[2]["twoD"] == "visible" # loaded, but nothing sent yet + assert log[4]["twoD"] == "hidden" and log[4]["relayVisible"] and not log[4]["relayHidden"] diff --git a/src/test/python/preponderous/graphik/grid3d/test_grid3d_web.py b/src/test/python/preponderous/graphik/grid3d/test_grid3d_web.py index 255d879..9466034 100644 --- a/src/test/python/preponderous/graphik/grid3d/test_grid3d_web.py +++ b/src/test/python/preponderous/graphik/grid3d/test_grid3d_web.py @@ -513,7 +513,7 @@ def test_the_template_is_package_data_with_the_relay_and_a_3d_toggle(): assert ' page.index("function start(") + assert page.index("relay.request(JSON.stringify(") > page.index("function start(") assert 'state.indexOf("failed:") === 0' in page and "show2d(true)" in page # pygbag's own canvas is still there, and its python block intact assert 'id="canvas"' in page and "asyncio.run( custom_site() )" in page @@ -556,7 +556,7 @@ def test_2d_shows_until_3d_draws_the_game_and_comes_back_with_a_reason(): block = graphikBlock(templatePage()) # the 2D canvas hides only once the game has sent the 3D view something assert "fed = true" in block - assert 'const drawing = state === "ready" && fed;' in block + assert 'const drawing = state === "ready" && fed && !(c && c.hidden);' in block assert "if (drawing) show2d(false);" in block # failures say why, in words, on the page assert 'id="graphik3d-note"' in block and 'role="status"' in block From c7570684075b7c2cd5aa01138157e98ccd70eae0 Mon Sep 17 00:00:00 2001 From: Daniel McCoy Stephenson Date: Fri, 20 Nov 2026 18:01:29 -0700 Subject: [PATCH 02/11] fix: the wire encoders refuse what the relay refuses, where the game made the mistake Counts over the relay's limits, non-finite numbers, coordinates past 1e6, lights with no radius or a negative colour or intensity, HUD colours out of range and a camera whose eye is on its target now raise WireError with the relay's status. A lone surrogate in a label is sent as "?" and a NUL is dropped on both backends; measureText no longer counts NULs. golden/wire-1.0.hex pins one message of each kind, and edge-case tests cover picking, board edges, viewports and the Animator. drafted by Claude on behalf of Daniel Stephenson Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LYNeuoCqxFpUXrFhxnTg89 --- .../preponderous/graphik/grid3d/text.py | 3 +- .../preponderous/graphik/grid3d/view.py | 10 +- .../python/preponderous/graphik/grid3d/web.py | 87 +++++++++++- .../graphik/grid3d/golden/wire-1.0.hex | 7 + .../graphik/grid3d/test_grid3d_wire_checks.py | 90 ++++++++++++ .../graphik/grid3d/test_grid3d_wire_golden.py | 129 ++++++++++++++++++ 6 files changed, 318 insertions(+), 8 deletions(-) create mode 100644 src/test/python/preponderous/graphik/grid3d/golden/wire-1.0.hex create mode 100644 src/test/python/preponderous/graphik/grid3d/test_grid3d_wire_checks.py create mode 100644 src/test/python/preponderous/graphik/grid3d/test_grid3d_wire_golden.py diff --git a/src/main/python/preponderous/graphik/grid3d/text.py b/src/main/python/preponderous/graphik/grid3d/text.py index 14ba333..b854dac 100644 --- a/src/main/python/preponderous/graphik/grid3d/text.py +++ b/src/main/python/preponderous/graphik/grid3d/text.py @@ -16,7 +16,8 @@ def measureText(text, pixelSize): """How wide `text` is drawn at `pixelSize`, in pixels: its longest line's characters times pixelSize.""" - return max(len(line) for line in str(text).split("\n")) * pixelSize + # a NUL draws nothing: both backends drop it (view.labelBytes, web._labelText) + return max(len(line) for line in str(text).replace("\0", "").split("\n")) * pixelSize def wrapText(text, maxWidth, pixelSize): diff --git a/src/main/python/preponderous/graphik/grid3d/view.py b/src/main/python/preponderous/graphik/grid3d/view.py index e4cf2f8..4f01a9e 100644 --- a/src/main/python/preponderous/graphik/grid3d/view.py +++ b/src/main/python/preponderous/graphik/grid3d/view.py @@ -39,6 +39,13 @@ INSTALL_HINT = "pip install 'graphik[strata]'" +def labelBytes(text): + """A label's text as Strata takes it: UTF-8 with no NUL (a C string would + end there; the browser backend drops them too), a lone surrogate as '?' + (what Strata draws for any character outside its font).""" + return str(text).replace("\0", "").encode("utf-8", "replace") + + class Unavailable(Exception): """The 3D view can't run here. The message says why, in plain words.""" @@ -257,8 +264,7 @@ def drawScene(self, scene, present=True): if scene.labels: engine.submit_text( [ - s.Text(l.x, l.y, l.pixelSize, s.TEXT_SHADOW, l.color, - l.text.encode("utf-8")) + s.Text(l.x, l.y, l.pixelSize, s.TEXT_SHADOW, l.color, labelBytes(l.text)) for l in scene.labels ] ) diff --git a/src/main/python/preponderous/graphik/grid3d/web.py b/src/main/python/preponderous/graphik/grid3d/web.py index 2917abd..f320a0b 100644 --- a/src/main/python/preponderous/graphik/grid3d/web.py +++ b/src/main/python/preponderous/graphik/grid3d/web.py @@ -71,6 +71,18 @@ COUNTS = struct.Struct(" 1.0: + raise WireError(-5, "%s %r: the engine takes no negative part and alpha up to 1" % (what, color)) + return color + + +def _checkCounts(shapes=0, lights=(), anchors=0): + if shapes > MAX_SHAPES: + raise WireError(-6, "%d shapes; the relay takes %d" % (shapes, MAX_SHAPES)) + if anchors > MAX_ANCHORS: + raise WireError(-6, "%d pieces; the relay takes %d" % (anchors, MAX_ANCHORS)) + if len(lights) > MAX_LIGHTS: + raise WireError(-6, "%d lights; the relay takes %d" % (len(lights), MAX_LIGHTS)) + if sum(1 for light in lights if light.castShadows) > MAX_SHADOWED_LIGHTS: + raise WireError(-6, "over %d shadow-casting lights" % MAX_SHADOWED_LIGHTS) + + def encodeBoard(shapes, lights=()): """BOARD: world shapes and lights.""" + _checkCounts(len(shapes), lights) out = [header(BOARD), COUNTS.pack(len(shapes), len(lights))] out += [_shape(s.kind, WORLD, 0, 0, s.position, s.scale, s.color) for s in shapes] out += [_light(WORLD, 0, light) for light in lights] @@ -176,7 +231,9 @@ def encodeBoard(shapes, lights=()): def _labelText(text): - data = str(text).replace("\0", "").encode("utf-8") + # a lone surrogate (text read from a file name, say) is sent as "?", which + # is what Strata draws for any character outside its font anyway + data = str(text).replace("\0", "").encode("utf-8", "replace") if len(data) > 65535: data = data[:65535].decode("utf-8", "ignore").encode("utf-8") return data @@ -184,18 +241,31 @@ def _labelText(text): def encodeHud(labels=(), panels=()): """HUD: screen panels (drawn first) and labels, in CSS pixels.""" + if len(panels) > MAX_HUD_ITEMS or len(labels) > MAX_HUD_ITEMS: + raise WireError(-6, "%d panels and %d labels; the relay takes %d of each" + % (len(panels), len(labels), MAX_HUD_ITEMS)) out = [header(HUD), COUNTS.pack(len(panels), len(labels))] for p in panels: - out.append(PANEL.pack(p.x, p.y, p.width, p.height, *_rgba(p.color))) + _finite((p.x, p.y, p.width, p.height), "a panel") + out.append(PANEL.pack(p.x, p.y, p.width, p.height, *_hudColor(p.color, "a panel's colour"))) for label in labels: text = _labelText(label.text) - out.append(LABEL.pack(label.x, label.y, label.pixelSize, *_rgba(label.color), len(text), 0)) + _finite((label.x, label.y, label.pixelSize), "a label") + out.append(LABEL.pack(label.x, label.y, label.pixelSize, *_hudColor(label.color, "a label's colour"), + len(text), 0)) out.append(text + b"\0" * (-len(text) % 4)) return b"".join(out) def encodeView(camera, clearColor=CLEAR_COLOR, sun=SUN_DIRECTION, near=NEAR_PLANE, far=FAR_PLANE): """VIEW: the camera, clear colour and direction to the sun.""" + _within(camera.eye, "the camera's eye") + _within(camera.target, "the camera's target") + _finite(tuple(_rgba(clearColor)) + tuple(sun), "the view") + if tuple(camera.eye) == tuple(camera.target): + raise WireError(-5, "the camera's eye is on its target") + if not (0.0 < camera.fovDegrees < 180.0 and 0.0 < near < far <= _FLOAT_MAX): + raise WireError(-5, "the view needs 0 < fov < 180 and 0 < near < far") return header(VIEW) + VIEW_BODY.pack( *camera.eye, *camera.target, camera.fovDegrees, near, far, *_rgba(clearColor), *sun ) @@ -206,12 +276,14 @@ def encodePieces(board, pieces, tracks, tickSeconds): from an Animator; a piece without one stands still on its cell. With a viewport, only the pieces in it are sent.""" pieces = [p for p in pieces if board.visible(p.column, p.row)] + _checkCounts(anchors=len(pieces)) index = {} anchors, shapes, lights = [], [], [] for i, piece in enumerate(pieces): end = board.cellCenter(piece.column, piece.row) start, end = tracks.get(piece.id, (end, end)) index[piece.id] = i + _within(tuple(start) + tuple(end), "piece %r's slide" % (piece.id,)) anchors.append(ANCHOR.pack(start[0], start[1], end[0], end[1])) # The piece's own shapes and glow, drawn at its end cell and sent as # offsets from it. A lone piece has no bridges; they come below. @@ -225,6 +297,11 @@ def encodePieces(board, pieces, tracks, tickSeconds): for a, b in board.bridgePairs(pieces): s = board.bridgeShape(a, b, (0.0, 0.0), (0.0, 0.0)) shapes.append(_shape(s.kind, BRIDGE, index[a.id], index[b.id], s.position, s.scale, s.color)) + if len(shapes) > MAX_SHAPES or len(lights) > MAX_LIGHTS: + raise WireError(-6, "%d piece shapes and %d piece lights; the relay takes %d and %d" + % (len(shapes), len(lights), MAX_SHAPES, MAX_LIGHTS)) + if not (0.0 <= tickSeconds <= _FLOAT_MAX): + raise WireError(-5, "tickSeconds is %r" % (tickSeconds,)) head = header(PIECES) + PIECES_HEAD.pack(tickSeconds, len(anchors), len(shapes), len(lights)) return head + b"".join(anchors) + b"".join(shapes) + b"".join(lights) diff --git a/src/test/python/preponderous/graphik/grid3d/golden/wire-1.0.hex b/src/test/python/preponderous/graphik/grid3d/golden/wire-1.0.hex new file mode 100644 index 0000000..5fb8503 --- /dev/null +++ b/src/test/python/preponderous/graphik/grid3d/golden/wire-1.0.hex @@ -0,0 +1,7 @@ +# Grid relay wire format 1.0: one message of each kind, encoded by graphik's +# grid3d.web (test_grid3d_wire_golden.py). Strata's relay reads the same bytes +# (tests/unit/grid_relay_wire_1_0.inc). , one message a line. +board 47330100010000000a000000010000000000000000000000000080bfec51b8bd000000bfec51783fec51383eec51783fae47613e5c8fc23e7b142e3e0000803f000000000000000000000000ec51b8bd000000bfec51783fec51383eec51783fec51383e0ad7a33e295c0f3e0000803f00000000000000000000803fec51b8bd000000bfec51783fec51383eec51783fae47613e5c8fc23e7b142e3e0000803f0000000000000000000080bfec51b8bd0000003fec51783fec51383eec51783fec51383e0ad7a33e295c0f3e0000803f000000000000000000000000ec51b8bd0000003fec51783fec51383eec51783fae47613e5c8fc23e7b142e3e0000803f00000000000000000000803fec51b8bd0000003fec51783fec51383eec51783fec51383e0ad7a33e295c0f3e0000803f0000000000000000000000008fc2f5bc666696bfcdcc6c409a99993e3333b33eec51b83eae47613e8fc2f53d0000803f0000000000000000000000008fc2f5bc6666963fcdcc6c409a99993e3333b33eec51b83eae47613e8fc2f53d0000803f00000000000000006666d6bf8fc2f5bc000000003333b33e9a99993e00000040ec51b83eae47613e8fc2f53d0000803f00000000000000006666d63f8fc2f5bc000000003333b33e9a99993e00000040ec51b83eae47613e8fc2f53d0000803f000100000000000000004040000000000000803f6666663fcdcc4c3f0000c0409a99993f +view 473301000400000000000000ee7cbb409eef8340000000009a9999be0ad723be000028429a99993e00004843cdcccc3d8fc2f53d0ad7233e0000803f6666e6be9a99593f3333b33e +pieces 47330100020000000000803e030000000500000001000000000080bf000000bf00000000000000bf000080bf0000003f000000000000003f0000803f0000003f0000803f0000003f0301000000000000000000000000803e00000000cdcc4c3f0000003fcdcc4c3fcdcc4c3ecdcc4c3f9a99993e0000803f03010000000000009a99193e0000003f9a99993e8fc2f53d8fc2f53d8fc2f53d0000803f0000803f0000803f0000803f0001010000000000000000005c8f423e00000000295c0f3f5c8fc23e295c0f3fec51b83d713d0a3fec51383e0000803f0101020000000000000000009a99993e00000000cdcccc3e9a99193fcdcccc3e3333733fcdcc4c3fcdcc4c3e0000803f03020000010000000000000077be1f3e00000000713d0a3f77be9f3e713d0a3f7b14ae3d5c8f023f7b142e3e0000803f01000200000000000000803f000000003333733fcdcc4c3fcdcc4c3e000000400000c03f +hud 47330100030000000100000001000000000080400000804000004843000000420000000000000000000000009a99193f000040410000004100008041ec51783f8fc2753f1f856b3f0000803f1100000053636f7265203320e2809420c3a974c3a9000000 diff --git a/src/test/python/preponderous/graphik/grid3d/test_grid3d_wire_checks.py b/src/test/python/preponderous/graphik/grid3d/test_grid3d_wire_checks.py new file mode 100644 index 0000000..c6c001b --- /dev/null +++ b/src/test/python/preponderous/graphik/grid3d/test_grid3d_wire_checks.py @@ -0,0 +1,90 @@ +"""Text the font can't draw, and the wire encoders refusing what Strata's +grid relay would refuse (WIRE.md, "Errors"), with the relay's status.""" + +import pytest + +from preponderous.graphik.grid3d import ( + CUBE, + Camera, + GridBoard, + Label, + Light, + Panel, + Piece, + PieceStyle, + Shape, + Theme, + measureText, + wrapText, +) +from preponderous.graphik.grid3d import web +from preponderous.graphik.grid3d.view import labelBytes + +# -- text the font can't draw + + +def test_text_is_measured_in_characters_as_strata_draws_them_not_bytes(): + # one '?' a character outside the font, a multi-byte UTF-8 sequence included + assert measureText("été", 10) == 30 + assert measureText("\U0001F40D!", 10) == 20 # an astral-plane snake is one cell + assert measureText("a\0b", 10) == 20 # a NUL draws nothing on either backend + assert wrapText("ééé éé", 40, 10) == ["ééé", "éé"] + + +def test_label_bytes_are_utf8_without_nuls_and_with_lone_surrogates_as_question_marks(): + assert labelBytes("a\0bé") == b"ab\xc3\xa9" + assert labelBytes("x\ud800y") == b"x?y" + assert web._labelText("x\ud800y") == b"x?y" + + +def test_a_very_long_label_is_cut_on_a_character_boundary(): + data = web._labelText("é" * 40000) # 80000 bytes of two-byte characters + assert len(data) <= 65535 + data.decode("utf-8") # no half character at the end + + +# -- the encoders refuse what the relay refuses (WIRE.md, "Errors") + + +def board(): + return GridBoard(3, 3, Theme(pieces={"p": PieceStyle(CUBE, (0.5, 0.5, 0.5), glow=(2.0, 1.0))})) + + +@pytest.mark.parametrize("make,status", [ + (lambda: web.encodeBoard([], [Light((0, 1, 0), (1, 1, 1), 0.0, 1.0)]), -5), # no range + (lambda: web.encodeBoard([], [Light((0, 1, 0), (1, -1, 1), 2.0, 1.0)]), -5), # negative colour + (lambda: web.encodeBoard([], [Light((0, 1, 0), (1, 1, 1), 2.0, -1.0)]), -5), # negative intensity + (lambda: web.encodeBoard([], [Light((0, 1, 0), (1, 1, 1), 2.0, 1.0, True)] * 5), -6), # five shadows + (lambda: web.encodeBoard([], [Light((0, 1, 0), (1, 1, 1), 2.0, 1.0)] * 33), -6), + (lambda: web.encodeBoard([Shape(CUBE, (float("nan"), 0, 0), (1, 1, 1), (1, 1, 1, 1))]), -5), + (lambda: web.encodeBoard([Shape(CUBE, (2e6, 0, 0), (1, 1, 1), (1, 1, 1, 1))]), -5), + (lambda: web.encodeHud([], [Panel(0, 0, 10, 10, (0, 0, 0, 1.5))]), -5), # alpha over 1 + (lambda: web.encodeHud([Label("x", 0, 0, 16, (-0.1, 1, 1, 1))]), -5), + (lambda: web.encodeHud([Label("x", float("inf"), 0, 16)]), -5), + (lambda: web.encodeHud([Label("x", 0, 0, 16)] * 4097), -6), + (lambda: web.encodeView(Camera((1, 2, 3), (1, 2, 3))), -5), + (lambda: web.encodeView(Camera((0, 5, 5), (0, 0, 0), 180.0)), -5), + (lambda: web.encodePieces(board(), [Piece(1, 0, 0, "p")], {}, -0.5), -5), + (lambda: web.encodePieces(board(), [Piece(1, 0, 0, "p")], {1: ((3e6, 0.0), (0.0, 0.0))}, 0.5), -5), +]) +def test_the_encoders_refuse_what_the_relay_would_with_its_status(make, status): + with pytest.raises(web.WireError) as error: + make() + assert error.value.status == status + + +def test_the_relays_limits_are_reached_but_not_passed_by_a_real_board(): + big = GridBoard(64, 64, mergeTiles=False) + message = web.encodeBoard(big.boardShapes(), [Light((0, 3, 0), (1, 1, 1), 5.0, 1.0, True)] * 4) + kind, contents = web.decode(message) + assert len(contents["shapes"]) == 64 * 64 + 4 + + +def test_a_web_view_refuses_a_bad_hud_before_sending_it(): + relay = web.RecordingRelay() + view = web.Grid3DWebView.open(400, 300, relay=relay) + view.setBoard(board()) + sent = len(relay.messages) + with pytest.raises(web.WireError): + view.setLabels([], [Panel(0, 0, 10, 10, (0, 0, 0, 2.0))]) + assert len(relay.messages) == sent diff --git a/src/test/python/preponderous/graphik/grid3d/test_grid3d_wire_golden.py b/src/test/python/preponderous/graphik/grid3d/test_grid3d_wire_golden.py new file mode 100644 index 0000000..33f8539 --- /dev/null +++ b/src/test/python/preponderous/graphik/grid3d/test_grid3d_wire_golden.py @@ -0,0 +1,129 @@ +"""The grid relay's wire format 1.0, held to golden bytes shared with Strata. + +golden/wire-1.0.hex holds one message of each kind, encoded by grid3d.web +from the scene below. Strata's tests/unit/test_grid_relay.cpp reads the same +bytes (tests/unit/grid_relay_wire_1_0.inc, made from this file) with the +relay's own parser, so the encoder here and the reader there are checked +against one fixture: a change to either side that the other doesn't make +fails one of the two suites. + +To rewrite the fixture after a deliberate format change (a new minor, a new +major): GRAPHIK_WRITE_WIRE_GOLDEN=1 python -m pytest -k wire_golden, then +regenerate Strata's .inc from it (its header says how). +""" + +import os + +import pytest + +from preponderous.graphik.grid3d import ( + CAPSULE, + CUBE, + SPHERE, + GridBoard, + Label, + Light, + Panel, + Piece, + PieceStyle, + Shape, + Theme, +) +from preponderous.graphik.grid3d import web + +GOLDEN = os.path.join(os.path.dirname(__file__), "golden", "wire-1.0.hex") +ORDER = ("board", "view", "pieces", "hud") + + +def eyes(piece, x, z, baseY): + return [Shape(SPHERE, (x + 0.15, baseY + 0.5, z + 0.3), (0.12, 0.12, 0.12), (1.0, 1.0, 1.0, 1.0))] + + +THEME = Theme(pieces={ + "head": PieceStyle(SPHERE, (0.2, 0.8, 0.3), height=0.5, size=0.8, extras=eyes), + "body": PieceStyle(CUBE, (0.1, 0.6, 0.2), height=0.4, size=0.7, tones=(0.9, 1.0)), + "gem": PieceStyle(CAPSULE, (0.95, 0.8, 0.2), height=0.6, size=0.4, glow=(2.0, 1.5)), +}) +BOARD = GridBoard(3, 2, THEME) +PIECES = [ + Piece("h", 1, 0, "head", chain="s", link=0), + Piece("b", 1, 1, "body", chain="s", link=1, scale=0.8), + Piece("g", 2, 1, "gem"), +] +# the head and body slide one cell east; the gem stands still +TRACKS = {"h": ((-1.0, -0.5), (0.0, -0.5)), "b": ((-1.0, 0.5), (0.0, 0.5))} + + +def messages(): + return { + "board": web.encodeBoard(BOARD.boardShapes(), + [Light((0.0, 3.0, 0.0), (1.0, 0.9, 0.8), 6.0, 1.2, True)]), + "view": web.encodeView(BOARD.camera(4 / 3.0)), + "pieces": web.encodePieces(BOARD, PIECES, TRACKS, 0.25), + # non-ASCII text: an em dash and two accented letters, 17 bytes of UTF-8 + "hud": web.encodeHud([Label("Score 3 — été", 12.0, 8.0, 16.0)], + [Panel(4.0, 4.0, 200.0, 32.0, (0.0, 0.0, 0.0, 0.6))]), + } + + +def readGolden(): + golden = {} + with open(GOLDEN, encoding="ascii") as handle: + for line in handle: + line = line.strip() + if line and not line.startswith("#"): + name, data = line.split() + golden[name] = bytes.fromhex(data) + return golden + + +def writeGolden(encoded): + with open(GOLDEN, "w", encoding="ascii") as handle: + handle.write("# Grid relay wire format 1.0: one message of each kind, encoded by graphik's\n") + handle.write("# grid3d.web (test_grid3d_wire_golden.py). Strata's relay reads the same bytes\n") + handle.write("# (tests/unit/grid_relay_wire_1_0.inc). , one message a line.\n") + for name in ORDER: + handle.write("%s %s\n" % (name, encoded[name].hex())) + + +def test_the_encoder_writes_the_golden_bytes(): + encoded = messages() + if os.environ.get("GRAPHIK_WRITE_WIRE_GOLDEN"): + writeGolden(encoded) + golden = readGolden() + assert sorted(golden) == sorted(ORDER) + for name in ORDER: + assert encoded[name] == golden[name], "%s differs from golden/wire-1.0.hex" % name + + +def test_the_golden_bytes_read_back_as_the_scene(): + golden = readGolden() + kind, board = web.decode(golden["board"]) + assert kind == web.BOARD + assert len(board["shapes"]) == 6 + 4 # six tiles, four frame sides + assert board["lights"][0]["castShadows"] and board["lights"][0]["radius"] == pytest.approx(6.0) + + kind, view = web.decode(golden["view"]) + assert kind == web.VIEW + camera = BOARD.camera(4 / 3.0) + assert view["eye"] == pytest.approx(camera.eye) + assert view["target"] == pytest.approx(camera.target) + assert view["sun"] == pytest.approx(web.SUN_DIRECTION) + + kind, pieces = web.decode(golden["pieces"]) + assert kind == web.PIECES + assert pieces["tickSeconds"] == 0.25 + assert pieces["anchors"] == [(-1.0, -0.5, 0.0, -0.5), (-1.0, 0.5, 0.0, 0.5), (1.0, 0.5, 1.0, 0.5)] + attach = [(s["attach"], s["a"], s["b"]) for s in pieces["shapes"]] + # head and its eye on anchor 0, the body on 1, the gem on 2, then the bridge from 0 to 1 + assert attach == [(web.PIECE, 0, 0), (web.PIECE, 0, 0), (web.PIECE, 1, 0), (web.PIECE, 2, 0), + (web.BRIDGE, 0, 1)] + assert pieces["shapes"][1]["position"] == pytest.approx((0.15, 0.5, 0.3)) # the eye, from its piece + assert [(l["attach"], l["a"]) for l in pieces["lights"]] == [(web.PIECE, 2)] + + kind, hud = web.decode(golden["hud"]) + assert kind == web.HUD + assert hud["labels"][0]["text"] == "Score 3 — été" + assert hud["panels"][0]["rect"] == (4.0, 4.0, 200.0, 32.0) + # 8 header + 8 counts + 32 panel + 32 label + 17 text bytes padded to 20 + assert len(golden["hud"]) == 100 From 1a9b06859c3115167b88ac76b8fbdfc6520c2c4f Mon Sep 17 00:00:00 2001 From: Daniel McCoy Stephenson Date: Fri, 20 Nov 2026 18:01:29 -0700 Subject: [PATCH 03/11] fix: picking with a straight-up, straight-down or eye-on-target camera raises a ValueError that says so Before, such a camera failed with ZeroDivisionError deep in cameraBasis. drafted by Claude on behalf of Daniel Stephenson Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LYNeuoCqxFpUXrFhxnTg89 --- .../preponderous/graphik/grid3d/pick.py | 16 ++- .../graphik/grid3d/test_grid3d_edges.py | 125 ++++++++++++++++++ 2 files changed, 138 insertions(+), 3 deletions(-) create mode 100644 src/test/python/preponderous/graphik/grid3d/test_grid3d_edges.py diff --git a/src/main/python/preponderous/graphik/grid3d/pick.py b/src/main/python/preponderous/graphik/grid3d/pick.py index b4a1402..3510d0b 100644 --- a/src/main/python/preponderous/graphik/grid3d/pick.py +++ b/src/main/python/preponderous/graphik/grid3d/pick.py @@ -34,9 +34,19 @@ def _unit(a): def cameraBasis(camera): - """(forward, right, up) unit vectors of a Camera.""" - forward = _unit(_sub(camera.target, camera.eye)) - right = _unit(_cross(forward, (0.0, 1.0, 0.0))) + """(forward, right, up) unit vectors of a Camera. ValueError for a + camera that looks nowhere (its eye on its target) or straight up or + down: Strata's look-at, with +y up, has no right or up for those either, + so they draw nothing on the desktop; tilt the camera a little instead.""" + view = _sub(camera.target, camera.eye) + if _dot(view, view) == 0.0: + raise ValueError("the camera's eye is on its target, so it looks nowhere") + forward = _unit(view) + side = _cross(forward, (0.0, 1.0, 0.0)) + if _dot(side, side) < 1e-12: + raise ValueError("the camera looks straight %s; tilt it a little (Strata's look-at " + "has +y up)" % ("down" if forward[1] < 0 else "up")) + right = _unit(side) return forward, right, _cross(right, forward) diff --git a/src/test/python/preponderous/graphik/grid3d/test_grid3d_edges.py b/src/test/python/preponderous/graphik/grid3d/test_grid3d_edges.py new file mode 100644 index 0000000..bcffc0b --- /dev/null +++ b/src/test/python/preponderous/graphik/grid3d/test_grid3d_edges.py @@ -0,0 +1,125 @@ +"""Picking at board edges and from extreme cameras, and Animator timing at +its edges. Pure Python.""" + +import math + +import pytest + +from preponderous.graphik.grid3d import ( + Animator, + Camera, + GridBoard, + Piece, + Viewport, + cellScreenPosition, + pickCell, + pickPoint, + projectToScreen, +) + +W, H = 800, 600 + + +def orbit(yawDegrees, pitchDegrees, distance=12.0, target=(0.0, 0.0, 0.0), fov=42.0): + yaw, pitch = math.radians(yawDegrees), math.radians(pitchDegrees) + eye = (target[0] + distance * math.cos(pitch) * math.sin(yaw), + target[1] + distance * math.sin(pitch), + target[2] + distance * math.cos(pitch) * math.cos(yaw)) + return Camera(eye, target, fov) + + +# -- picking + + +@pytest.mark.parametrize("yaw,pitch", [(0, 55), (90, 30), (200, 75), (315, 12), (45, 89.5), (0, 3)]) +def test_every_cells_inner_corners_pick_that_cell_from_any_camera(yaw, pitch): + board = GridBoard(7, 5) + camera = orbit(yaw, pitch, distance=30.0) + for column in range(7): + for row in range(5): + cx, cz = board.cellCenter(column, row) + for dx in (-0.49, 0.49): + for dz in (-0.49, 0.49): + at = projectToScreen(camera, (cx + dx, 0.0, cz + dz), W, H) + assert at is not None + assert pickCell(camera, board, at[0], at[1], W, H) == (column, row) + + +def test_a_boards_edges_are_half_open_like_its_cells(): + board = GridBoard(4, 3) + assert board.cellAt(-2.0, -1.5) == (0, 0) # the west and north edges are in + assert board.cellAt(1.999, 1.499) == (3, 2) + assert board.cellAt(2.0, 0.0) is None # the east and south edges are out + assert board.cellAt(0.0, 1.5) is None + assert board.cellAt(-2.0001, 0.0) is None + + +def test_a_viewport_picks_only_its_own_cells_even_at_the_boards_edge(): + board = GridBoard(10, 10, viewport=Viewport.around(0, 0, 1)) # reaches off the board + assert board.cellAt(0.0, 0.0) == (0, 0) + assert board.cellAt(-1.0, -1.0) is None # cell (-1, -1): in the window, off the board + + +def test_a_pixel_on_the_horizon_or_with_no_pointer_picks_nothing(): + board = GridBoard(4, 4) + level = Camera((0.0, 0.0, 10.0), (0.0, 0.0, 0.0)) # looking along the plane + assert pickPoint(level, W / 2, H / 2, W, H) is None + assert pickCell(orbit(0, 55), board, None, 10, W, H) is None + + +@pytest.mark.parametrize("camera", [ + Camera((0.0, 10.0, 0.0), (0.0, 0.0, 0.0)), # straight down + Camera((1.0, -5.0, 2.0), (1.0, 5.0, 2.0)), # straight up + Camera((1.0, 2.0, 3.0), (1.0, 2.0, 3.0)), # eye on the target +]) +def test_a_camera_strata_cant_aim_is_refused_in_words(camera): + with pytest.raises(ValueError, match="camera"): + pickCell(camera, GridBoard(3, 3), W / 2, H / 2, W, H) + + +def test_a_cell_behind_the_camera_has_no_screen_position(): + board = GridBoard(9, 9) + inside = Camera((0.0, 0.5, 0.0), (0.0, 0.4, -10.0)) # standing on the board, looking north + assert cellScreenPosition(inside, board, 4, 8, W, H) is None # the south edge, behind + assert cellScreenPosition(inside, board, 4, 0, W, H) is not None + + +# -- Animator + + +def animator(): + board = GridBoard(5, 5) + return Animator(board.cellCenter), board + + +def test_a_tick_of_zero_or_less_or_nan_places_pieces_at_once(): + for tick in (0.0, -1.0, float("nan")): + a, board = animator() + a.update([Piece(1, 0, 0, "x")], 0.0, 0.5) + a.update([Piece(1, 1, 0, "x")], 1.0, tick) + assert a.settled(1.0) + assert a.positions(1.0)[1] == board.cellCenter(1, 0) + + +def test_a_time_before_the_tick_began_is_its_start_not_beyond(): + a, board = animator() + a.update([Piece(1, 0, 0, "x")], 0.0, 0.5) + a.update([Piece(1, 1, 0, "x")], 10.0, 0.5) + assert a.positions(9.0)[1] == board.cellCenter(0, 0) # a clock read before the update + assert a.positions(99.0)[1] == board.cellCenter(1, 0) + + +def test_a_diagonal_step_jumps_and_a_straight_one_slides(): + a, board = animator() + a.update([Piece(1, 2, 2, "x"), Piece(2, 0, 0, "x")], 0.0, 0.5) + a.update([Piece(1, 3, 3, "x"), Piece(2, 1, 0, "x")], 1.0, 0.5) + at = a.positions(1.0) + assert at[1] == board.cellCenter(3, 3) # two cells' worth of travel: over maxSlideCells + assert at[2] == board.cellCenter(0, 0) # one cell: slides from where it was + + +def test_pieces_with_any_hashable_id_are_tracked(): + a, board = animator() + ids = [("snake", 0), "food", 7, frozenset({1})] + a.update([Piece(i, n, 0, "x") for n, i in enumerate(ids)], 0.0, 0.0) + assert set(a.positions(0.0)) == set(ids) From 8e5dafeb07c8f5fe89c6dec26fcaeda7453a088e Mon Sep 17 00:00:00 2001 From: Daniel McCoy Stephenson Date: Fri, 20 Nov 2026 18:01:29 -0700 Subject: [PATCH 04/11] fix: ScreenRecorder answers every public call and constant Graphik has beginFrame and endFrame no longer raise AttributeError, drawImage is recorded (RecordedImage, exported next to 0.5.2's touch-key names), and getVersion and the colour constants are there. A test compares the recorder with Graphik's public names. drafted by Claude on behalf of Daniel Stephenson Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LYNeuoCqxFpUXrFhxnTg89 --- .../preponderous/graphik/grid3d/__init__.py | 3 +- .../python/preponderous/graphik/grid3d/ui.py | 45 ++++++++++++++++++- .../grid3d/test_grid3d_recorder_parity.py | 36 +++++++++++++++ 3 files changed, 81 insertions(+), 3 deletions(-) create mode 100644 src/test/python/preponderous/graphik/grid3d/test_grid3d_recorder_parity.py diff --git a/src/main/python/preponderous/graphik/grid3d/__init__.py b/src/main/python/preponderous/graphik/grid3d/__init__.py index 83aa2b8..c633cf4 100644 --- a/src/main/python/preponderous/graphik/grid3d/__init__.py +++ b/src/main/python/preponderous/graphik/grid3d/__init__.py @@ -57,6 +57,7 @@ Button, RecordedButton, RecordedDisplay, + RecordedImage, RecordedRect, RecordedText, ScreenRecorder, @@ -76,7 +77,7 @@ "Camera", "Label", "Light", "Panel", "Scene", "SceneLimitError", "Shape", "fitText", "rgb255", "rgba", "shade", "centredLabel", "measureText", "wrapText", - "Button", "RecordedButton", "RecordedDisplay", "RecordedRect", "RecordedText", + "Button", "RecordedButton", "RecordedDisplay", "RecordedImage", "RecordedRect", "RecordedText", "ScreenRecorder", "drawButtons", "hoverColor", "MIN_TARGET", "MORE", "KeySlot", "TouchKey", "TouchKeys", "STRATA_VERSION", "Grid3DView", "Unavailable", diff --git a/src/main/python/preponderous/graphik/grid3d/ui.py b/src/main/python/preponderous/graphik/grid3d/ui.py index a34d6c6..463b281 100644 --- a/src/main/python/preponderous/graphik/grid3d/ui.py +++ b/src/main/python/preponderous/graphik/grid3d/ui.py @@ -129,6 +129,18 @@ class RecordedRect: color: Color255 +@dataclass +class RecordedImage: + """A drawImage call. A 3D view has no way to show a picture yet, so it is + kept for a game that wants to draw something in its place.""" + + filePath: str + x: float + y: float + width: float + height: float + + @dataclass class RecordedButton: """A drawButton call, with the function the 2D screen gave it.""" @@ -169,13 +181,36 @@ def fill(self, color): class ScreenRecorder: """Stands in for Graphik: keeps, in order, what a screen draws (drawText, - drawRectangle, drawButton) instead of painting it. `items` is one frame's - worth; reset() starts the next.""" + drawRectangle, drawButton, drawImage) instead of painting it. `items` is + one frame's worth; reset() starts the next. + + It answers every public call Graphik has, so a screen written against + Graphik 0.3.0 and later runs unchanged: beginFrame and endFrame (press-only + clicks) do nothing here, because the 3D view hands a press to click() + itself, once; getVersion is graphik's; the colour constants are Graphik's.""" + + # Graphik's colour constants, so screens that read graphik.red still work + black = (0, 0, 0) + white = (255, 255, 255) + red = (200, 0, 0) + green = (0, 200, 0) + blue = (0, 0, 200) def __init__(self, width=800, height=600): self.gameDisplay = RecordedDisplay(width, height) self.items = [] + def beginFrame(self): + """Graphik.beginFrame: nothing to snapshot, the 3D view sends clicks.""" + + def endFrame(self): + """Graphik.endFrame: nothing to do.""" + + def getVersion(self): + from .._version import __version__ + + return __version__ + def resize(self, width, height): self.gameDisplay.width, self.gameDisplay.height = width, height @@ -197,6 +232,12 @@ def drawButton(self, xpos, ypos, width, height, colorBox, colorText, sizeText, t sizeText, str(text), function) ) + def drawImage(self, filePath, xpos, ypos, width, height): + self.items.append(RecordedImage(str(filePath), xpos, ypos, width, height)) + + def images(self): + return [item for item in self.items if isinstance(item, RecordedImage)] + def buttons(self): return [item for item in self.items if isinstance(item, RecordedButton)] diff --git a/src/test/python/preponderous/graphik/grid3d/test_grid3d_recorder_parity.py b/src/test/python/preponderous/graphik/grid3d/test_grid3d_recorder_parity.py new file mode 100644 index 0000000..d73499c --- /dev/null +++ b/src/test/python/preponderous/graphik/grid3d/test_grid3d_recorder_parity.py @@ -0,0 +1,36 @@ +"""ScreenRecorder answers every call and constant Graphik has, so a 2D +screen written against Graphik 0.3.0 and later runs under a 3D view.""" + +import inspect + +from preponderous.graphik import Graphik, __version__ +from preponderous.graphik.grid3d import ScreenRecorder + +# -- ScreenRecorder stands in for every call Graphik has + + +def test_the_recorder_answers_every_public_call_and_constant_graphik_has(): + public = [name for name, _ in inspect.getmembers(Graphik) if not name.startswith("_")] + missing = [name for name in public if not hasattr(ScreenRecorder, name)] + assert missing == [] + for name in public: + value = getattr(Graphik, name) + if not callable(value): + assert getattr(ScreenRecorder, name) == value, name + + +def test_a_screen_using_press_only_clicks_and_images_runs_under_the_recorder(): + recorder = ScreenRecorder(400, 300) + clicked = [] + + def screen(graphik): # a 2D screen written against Graphik 0.3.0 + graphik.beginFrame() + graphik.drawImage("logo.png", 10, 10, 64, 64) + graphik.drawButton(100, 100, 80, 30, graphik.blue, graphik.white, 20, "Play", lambda: clicked.append(1)) + graphik.endFrame() + + screen(recorder) + assert [type(item).__name__ for item in recorder.items] == ["RecordedImage", "RecordedButton"] + assert recorder.images()[0].filePath == "logo.png" + assert recorder.click((120, 110)) and clicked == [1] + assert recorder.getVersion() == __version__ From c1b76fc78a26350aab1da9db202d2fcd87404147 Mon Sep 17 00:00:00 2001 From: Daniel McCoy Stephenson Date: Fri, 20 Nov 2026 18:01:29 -0700 Subject: [PATCH 05/11] fix: relay.py checks every tarball member before writing and caps what it fetches A refused tarball no longer leaves files behind, a linked folder in --dest cannot carry a file out, the relay folder is capped at 64 MB, --strata takes only a release version, SHA256SUMS lines that disagree or are not SHA-256 are refused, and --replace updates an earlier relay's files (never index.html). drafted by Claude on behalf of Daniel Stephenson Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LYNeuoCqxFpUXrFhxnTg89 --- .../preponderous/graphik/grid3d/relay.py | 77 ++++++++++++++----- .../graphik/grid3d/test_grid3d_relay.py | 73 ++++++++++++++++++ 2 files changed, 131 insertions(+), 19 deletions(-) diff --git a/src/main/python/preponderous/graphik/grid3d/relay.py b/src/main/python/preponderous/graphik/grid3d/relay.py index 80eee58..3819f0a 100644 --- a/src/main/python/preponderous/graphik/grid3d/relay.py +++ b/src/main/python/preponderous/graphik/grid3d/relay.py @@ -13,8 +13,10 @@ against it, and copies kit/grid-relay/dist/ into `--dest`, next to the page pygbag built from grid3d's template (web.templatePath()). Files that already exist there (pygbag's own index.html, say) are left alone, so the -relay's test page never replaces the game's. Nothing of the relay is -downloaded by a player until the page's 3D toggle asks for it. +relay's test page never replaces the game's; with --replace (after moving to +a newer Strata into a folder an older relay was copied to) the relay's own +files are replaced, and only index.html is still kept. Nothing of the relay +is downloaded by a player until the page's 3D toggle asks for it. Standard library only. """ @@ -24,6 +26,7 @@ import io import os import posixpath +import re import shutil import sys import tarfile @@ -31,6 +34,13 @@ RELEASES = "https://github.com/Preponderous-Software/strata/releases/download" DIST = "kit/grid-relay/dist/" +# A Strata release version as its tags spell them (0.9.0, 1.0.0-rc.1): it goes +# into the download URL, so nothing else is taken. +VERSION = re.compile(r"^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$") +# Never replaced, even with replace=True: the game's own page. +KEEP = ("index.html",) +# The relay's dist/ is about 1.5 MB; anything far bigger is not a relay. +MAX_DIST_BYTES = 64 * 1000 * 1000 class RelayFetchError(Exception): @@ -38,6 +48,8 @@ class RelayFetchError(Exception): def tarballName(version): + if not VERSION.match(str(version)): + raise RelayFetchError("%r is not a Strata release version (like 0.9.0)" % (version,)) return "strata-%s-wasm32-emscripten.tar.gz" % version @@ -48,12 +60,21 @@ def _download(url): def expectedDigest(sums, name): - """The SHA-256 a SHA256SUMS text gives for `name`.""" + """The SHA-256 a SHA256SUMS text gives for `name`: refused when it has + none, more than one that disagree, or one that isn't a SHA-256.""" + found = set() for line in sums.splitlines(): parts = line.strip().split() if len(parts) == 2 and parts[1].lstrip("*").split("/")[-1] == name: - return parts[0].lower() - raise RelayFetchError("SHA256SUMS has no line for %s" % name) + found.add(parts[0].lower()) + if not found: + raise RelayFetchError("SHA256SUMS has no line for %s" % name) + if len(found) > 1: + raise RelayFetchError("SHA256SUMS has different digests for %s" % name) + digest = found.pop() + if not re.match(r"^[0-9a-f]{64}$", digest): + raise RelayFetchError("SHA256SUMS's digest for %s isn't a SHA-256: %r" % (name, digest)) + return digest def verify(data, sums, name): @@ -63,14 +84,16 @@ def verify(data, sums, name): raise RelayFetchError("%s's SHA-256 is %s, SHA256SUMS says %s" % (name, digest, expected)) -def extractDist(data, dest, prefix=DIST): +def extractDist(data, dest, prefix=DIST, replace=False): """Copy the tarball's `prefix` tree into `dest`; returns (copied, - skipped) relative paths. Existing files are skipped, and members that - aren't plain files and directories, or would land outside `dest`, are - refused.""" - copied, skipped = [], [] + skipped) relative paths. Existing files are skipped (with `replace`, only + index.html is), and members that aren't plain files and directories, or + would land outside `dest`, are refused. Every member is checked before + anything is written, so a refused tarball leaves `dest` as it was.""" dest = os.path.abspath(dest) + realDest = os.path.realpath(dest) with tarfile.open(fileobj=io.BytesIO(data), mode="r:gz") as archive: + plan, total = [], 0 for member in archive.getmembers(): name = member.name[2:] if member.name.startswith("./") else member.name if prefix in name + "/" and (".." in name.split("/") or name.startswith("/")): @@ -86,26 +109,38 @@ def extractDist(data, dest, prefix=DIST): if relative.startswith("../") or os.path.isabs(relative) or "/../" in "/" + relative: raise RelayFetchError("refusing %s: outside the relay's folder" % member.name) target = os.path.abspath(os.path.join(dest, relative)) - if not target.startswith(dest + os.sep): + # resolved too, so a folder in `dest` that is a link elsewhere + # can't carry a file out of it + if not target.startswith(dest + os.sep) or not os.path.realpath(target).startswith(realDest + os.sep): raise RelayFetchError("refusing %s: outside %s" % (member.name, dest)) + if not member.isdir() and not member.isfile(): + raise RelayFetchError("refusing %s: not a plain file" % member.name) + total += member.size + if total > MAX_DIST_BYTES: + raise RelayFetchError("refusing the tarball: over %d MB under %s" + % (MAX_DIST_BYTES // 1000000, prefix)) + plan.append((member, relative, target)) + if not plan or all(member.isdir() for member, _, _ in plan): + raise RelayFetchError("the tarball has nothing under %s" % prefix) + copied, skipped = [], [] + for member, relative, target in plan: if member.isdir(): os.makedirs(target, exist_ok=True) continue - if not member.isfile(): - raise RelayFetchError("refusing %s: not a plain file" % member.name) - if os.path.exists(target): + if os.path.lexists(target) and (not replace or relative in KEEP + or not os.path.isfile(target) or os.path.islink(target)): + # with replace, only a plain file is written over: never a + # link (which could point anywhere) or a folder skipped.append(relative) continue os.makedirs(os.path.dirname(target), exist_ok=True) with archive.extractfile(member) as source, open(target, "wb") as out: shutil.copyfileobj(source, out) copied.append(relative) - if not copied and not skipped: - raise RelayFetchError("the tarball has nothing under %s" % prefix) return copied, skipped -def fetchRelay(version, dest, base=RELEASES, download=None): +def fetchRelay(version, dest, base=RELEASES, download=None, replace=False): """Download, verify and unpack Strata `version`'s grid relay into `dest`. Returns (copied, skipped).""" download = download or _download @@ -118,7 +153,7 @@ def fetchRelay(version, dest, base=RELEASES, download=None): raise RelayFetchError("couldn't download Strata %s's release: %s" % (version, error)) verify(data, sums, name) os.makedirs(dest, exist_ok=True) - return extractDist(data, dest) + return extractDist(data, dest, replace=replace) def main(argv=None): @@ -127,16 +162,20 @@ def main(argv=None): description="Copy Strata's prebuilt grid relay next to a pygbag build.") parser.add_argument("--strata", required=True, help="Strata release version, e.g. 0.9.0") parser.add_argument("--dest", required=True, help="the pygbag output folder (build/web)") + parser.add_argument("--replace", action="store_true", + help="replace relay files already in --dest (never index.html)") parser.add_argument("--base", default=RELEASES, help=argparse.SUPPRESS) args = parser.parse_args(argv) try: - copied, skipped = fetchRelay(args.strata, args.dest, args.base) + copied, skipped = fetchRelay(args.strata, args.dest, args.base, replace=args.replace) except RelayFetchError as error: print("grid relay: %s" % error, file=sys.stderr) return 1 print("grid relay: Strata %s, %d files copied to %s" % (args.strata, len(copied), args.dest)) for path in skipped: print("grid relay: kept the existing %s" % path) + if any(path not in KEEP for path in skipped): + print("grid relay: files of an earlier relay were kept; --replace replaces them", file=sys.stderr) return 0 diff --git a/src/test/python/preponderous/graphik/grid3d/test_grid3d_relay.py b/src/test/python/preponderous/graphik/grid3d/test_grid3d_relay.py index ef94d76..0b238c9 100644 --- a/src/test/python/preponderous/graphik/grid3d/test_grid3d_relay.py +++ b/src/test/python/preponderous/graphik/grid3d/test_grid3d_relay.py @@ -105,3 +105,76 @@ def offline(url): monkeypatch.setattr(relay, "_download", offline) assert relay.main(["--strata", "0.9.0", "--dest", str(tmp_path)]) == 1 assert "no network" in capsys.readouterr().err + + +# -- hardening + + +def test_a_refused_tarball_writes_nothing(tmp_path): + # the escaping member comes last: nothing before it may have been written + evil = tarball(DIST_FILES, extra=[("x/" + relay.DIST + "../../../../escape.js", b"bad")]) + download, _ = release(evil) + web = tmp_path / "web" + with pytest.raises(relay.RelayFetchError, match="refusing"): + relay.fetchRelay("0.9.0", str(web), download=download) + assert not web.exists() or os.listdir(web) == [] + + +def test_links_and_devices_in_the_relay_folder_are_refused(tmp_path): + for kind in (tarfile.SYMTYPE, tarfile.LNKTYPE, tarfile.CHRTYPE): + buffer = io.BytesIO() + with tarfile.open(fileobj=buffer, mode="w:gz") as archive: + info = tarfile.TarInfo(relay.DIST + "grid-relay.js") + info.type = kind + info.linkname = "/etc/passwd" + archive.addfile(info) + with pytest.raises(relay.RelayFetchError, match="not a plain file"): + relay.extractDist(buffer.getvalue(), str(tmp_path / "web")) + + +def test_a_folder_in_dest_that_links_elsewhere_cant_carry_a_file_out(tmp_path): + elsewhere = tmp_path / "elsewhere" + elsewhere.mkdir() + web = tmp_path / "web" + web.mkdir() + os.symlink(str(elsewhere), str(web / "sub")) + data = tarball({"sub/x.js": b"x"}) + with pytest.raises(relay.RelayFetchError, match="outside"): + relay.extractDist(data, str(web)) + assert os.listdir(elsewhere) == [] + + +def test_an_oversized_relay_folder_is_refused(tmp_path, monkeypatch): + monkeypatch.setattr(relay, "MAX_DIST_BYTES", 10) + with pytest.raises(relay.RelayFetchError, match="over"): + relay.extractDist(tarball(DIST_FILES), str(tmp_path)) + + +def test_replace_updates_an_earlier_relay_but_never_the_games_page(tmp_path, capsys, monkeypatch): + web = tmp_path / "web" + web.mkdir() + (web / "index.html").write_bytes(b"the game") + (web / "grid-relay.js").write_bytes(b"// an older relay") + download, _ = release(tarball(DIST_FILES)) + monkeypatch.setattr(relay, "_download", download) + assert relay.main(["--strata", "0.9.0", "--dest", str(web)]) == 0 + assert (web / "grid-relay.js").read_bytes() == b"// an older relay" + assert "--replace replaces them" in capsys.readouterr().err + assert relay.main(["--strata", "0.9.0", "--dest", str(web), "--replace"]) == 0 + assert (web / "grid-relay.js").read_bytes() == b"// relay" + assert (web / "index.html").read_bytes() == b"the game" + + +@pytest.mark.parametrize("version", ["../../evil", "0.9", "v0.9.0", "0.9.0/../x", "", "0.9.0 "]) +def test_only_a_release_version_goes_into_the_download_url(version): + with pytest.raises(relay.RelayFetchError, match="not a Strata release version"): + relay.fetchRelay(version, "unused", download=lambda url: pytest.fail("downloaded %s" % url)) + + +def test_sha256sums_that_disagree_or_arent_digests_are_refused(): + name = relay.tarballName("0.9.0") + with pytest.raises(relay.RelayFetchError, match="different digests"): + relay.expectedDigest("%s %s\n%s dist/%s\n" % ("a" * 64, name, "b" * 64, name), name) + with pytest.raises(relay.RelayFetchError, match="isn't a SHA-256"): + relay.expectedDigest("abc %s\n" % name, name) + assert relay.expectedDigest("%s *%s\n" % ("A" * 64, name), name) == "a" * 64 From c6e9f2589d73802ebb2b29e60939ff0dc48c50e2 Mon Sep 17 00:00:00 2001 From: Daniel McCoy Stephenson Date: Fri, 20 Nov 2026 18:01:29 -0700 Subject: [PATCH 06/11] ci: a grid3d render job runs the Strata render tests on llvmpipe The job installs the strata extra and Mesa and runs the grid3d tests with GRAPHIK_REQUIRE_STRATA=1, so the golden-image and mid-tick render tests run on every pull request instead of skipping. drafted by Claude on behalf of Daniel Stephenson Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LYNeuoCqxFpUXrFhxnTg89 --- .github/workflows/test.yml | 34 +++++++++++++++++++ .../graphik/grid3d/test_grid3d_view.py | 3 ++ 2 files changed, 37 insertions(+) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 2c5e67a..e729f7b 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -55,6 +55,40 @@ jobs: SDL_AUDIODRIVER: dummy run: python -m pytest + grid3d-render: + # The rest of the suite runs without Strata, so its render tests (a board + # drawn headless and compared with golden/board-4x3.png, a frame mid-tick) + # skip there. This job installs the strata extra and draws them for real, + # headless through EGL on Mesa's llvmpipe (no GPU, no display), and + # GRAPHIK_REQUIRE_STRATA turns a skip into a failure. The binding fetches + # the pinned Strata release library (view.STRATA_VERSION) from GitHub and + # checks its SHA-256. The browser backend has no render here: Strata's own + # CI draws the grid relay in Chromium against desktop stills. + name: grid3d render (Strata, llvmpipe) + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - name: Install Mesa (EGL, llvmpipe) + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends libegl1 libegl-mesa0 libgl1-mesa-dri libgles2 + + - name: Install package with test and strata dependencies + run: python -m pip install --upgrade pip && python -m pip install -e ".[test,strata]" + + - name: grid3d tests, rendering included + env: + SDL_VIDEODRIVER: dummy + SDL_AUDIODRIVER: dummy + GALLIUM_DRIVER: llvmpipe + GRAPHIK_REQUIRE_STRATA: "1" + run: python -m pytest -rs src/test/python/preponderous/graphik/grid3d + archive-install: # Consumers install graphik from a release tag's source archive, e.g. # graphik @ https://github.com/Stephenson-Software/graphik/archive/refs/tags/v0.3.0.zip diff --git a/src/test/python/preponderous/graphik/grid3d/test_grid3d_view.py b/src/test/python/preponderous/graphik/grid3d/test_grid3d_view.py index d4c2567..7911cde 100644 --- a/src/test/python/preponderous/graphik/grid3d/test_grid3d_view.py +++ b/src/test/python/preponderous/graphik/grid3d/test_grid3d_view.py @@ -282,6 +282,9 @@ def openHeadless(width=240, height=180, clock=None): return Grid3DView.open(width, height, headless=True) return Grid3DView.open(width, height, headless=True, clock=clock) except Unavailable as reason: + if os.environ.get("GRAPHIK_REQUIRE_STRATA"): + # CI's grid3d render job: a skip there would hide a broken render + pytest.fail("Strata can't run here, and GRAPHIK_REQUIRE_STRATA is set: %s" % reason) pytest.skip("Strata can't run here: %s" % reason) From 968f5102f5c20d20c19ee8a4bb19d3e6996454ec Mon Sep 17 00:00:00 2001 From: Daniel McCoy Stephenson Date: Fri, 20 Nov 2026 18:01:34 -0700 Subject: [PATCH 07/11] docs: an API reference for grid3d (docs/grid3d.md) Every public class and function is listed, grouped by area, with an example for each group; 0.5.2's portrait framing (fitCamera top and bottom, setInsets), touchScreen() and the touch keys are covered in a Touch keys section. The README and the package docstring link to it. drafted by Claude on behalf of Daniel Stephenson Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LYNeuoCqxFpUXrFhxnTg89 --- README.md | 6 +- docs/grid3d.md | 387 ++++++++++++++++++ .../preponderous/graphik/grid3d/__init__.py | 2 + 3 files changed, 393 insertions(+), 2 deletions(-) create mode 100644 docs/grid3d.md diff --git a/README.md b/README.md index e017835..b31910d 100644 --- a/README.md +++ b/README.md @@ -122,6 +122,8 @@ else: - Everything except `Grid3DView.open` is plain Python, so scene code can be unit-tested without a GPU. Importing `grid3d` loads neither Strata nor pygame. - `PieceStyle.extras(piece, x, z, baseY)` returns shapes placed relative to the piece: x and z measured from the given `(x, z)`, so moving the piece moves them all the same way. The browser backend sends them as offsets from the piece and relies on this. +Every public class and function, with an example for each part, is in the [grid3d API reference](docs/grid3d.md). + ### Helpers for a game's 3D view So that games stop hand-building the same pieces: @@ -129,7 +131,7 @@ So that games stop hand-building the same pieces: - **Picking.** `view.pickCell(x, y)` (or `pickCell(camera, board, x, y, width, height)`) gives the `(column, row)` under a pointer, or `None`; the whole cell counts, gaps between tiles included. `projectToScreen(camera, point, width, height)` and `cellScreenPosition(camera, board, column, row, width, height, y)` go the other way, for aiming a tap at a piece or putting a note beside a tile. They use the same look-at and perspective the view asks Strata for. - **Text.** Strata's built-in font is an 8 x 8 bitmap font in which every character is exactly `pixelSize` wide. `measureText(text, pixelSize)`, `fitText(text, width, pixelSize)` (cut with `...`), `wrapText(text, maxWidth, pixelSize)` (greedy word wrap) and `centredLabel(text, x, y, pixelSize, color, rise=0.5)` build on that. - **Screen buttons.** `Button(x, y, width, height, text, color, textColor, pixelSize, function)` draws a panel and a centred label (`button.draw(pointer)`), hit-tests with `drawButton`'s edges (`contains`, `click`), and lifts under the pointer as `drawButton` does (`hoverColor`). Colours are 0-255, as for `drawButton`; `padding` widens a button whose label doesn't fit. -- **2D screens under a 3D view.** `ScreenRecorder` stands in for `Graphik`: a game's 2D screens draw into it as usual (`drawText`, `drawRectangle`, `drawButton`), the 3D view shows what they drew, and `recorder.click(pos)` runs the 2D button's own function. +- **2D screens under a 3D view.** `ScreenRecorder` stands in for `Graphik`: a game's 2D screens draw into it as usual (`drawText`, `drawRectangle`, `drawButton`, `drawImage`; `beginFrame`, `endFrame`, `getVersion` and the colour constants are there too), the 3D view shows what they drew, and `recorder.click(pos)` runs the 2D button's own function. - **Bigger boards.** `GridBoard(columns, rows, theme, tiles=..., mergeTiles=True, viewport=...)`: `tiles` maps a cell to its own `Tile(color, raised)`; `mergeTiles` draws each row's neighbouring tiles that look the same as one box (a 64 x 64 board of one colour is 64 boxes, not 4096); `viewport=Viewport.around(column, row, reach)` draws only a window of the board, framed and fitted as if it were the whole board, with pieces and picking still in whole-board cells. - **Hover.** `board.scene(..., highlight=(column, row))` lays a thin slab in `Theme.highlight` on the tile under the pointer. - **Chains.** `board.bridgePairs(pieces)` names the joined pieces and `board.bridgeShape(a, b, aAt, bAt)` draws one bridge. @@ -142,7 +144,7 @@ Under [pygbag](https://pypi.org/project/pygbag/) (`sys.platform == "emscripten"` - `view.ready` turns true once the page has loaded the 3D view; `view.failure()` says why it couldn't. `open()` raises `Unavailable` on a page without the relay. - `view.pollEvents()` returns Strata-style events (keys with desktop Strata's scancodes, mouse, wheel, resize, and `FINGER_*` for touch), and `grid3d.web.toPygameEvents(events, pygame)` turns them into pygame events, so a game's 2D input code runs unchanged. It converts desktop Strata events too. -- The page: build with `pygbag --template ...`, a copy of pygbag 0.9.3's default template with the relay's canvas and a **2D/3D** button. The relay has to be served with the game (a browser can't fetch GitHub release assets cross-origin): `python -m preponderous.graphik.grid3d.relay --strata 0.9.0 --dest ` downloads Strata's `strata--wasm32-emscripten.tar.gz`, checks it against the release's `SHA256SUMS` and copies its prebuilt `kit/grid-relay/dist/` next to the page, leaving files already there (pygbag's `index.html`) alone. +- The page: build with `pygbag --template ...`, a copy of pygbag 0.9.3's default template with the relay's canvas and a **2D/3D** button. The relay has to be served with the game (a browser can't fetch GitHub release assets cross-origin): `python -m preponderous.graphik.grid3d.relay --strata 0.9.0 --dest ` downloads Strata's `strata--wasm32-emscripten.tar.gz`, checks it against the release's `SHA256SUMS` and copies its prebuilt `kit/grid-relay/dist/` next to the page, leaving files already there (pygbag's `index.html`) alone; `--replace` replaces an earlier relay's files (never `index.html`) when moving to a newer Strata. - Since 0.5.1 the page starts in **3D**, as a desktop `Grid3DView` game does: the relay's scripts and engine load at once, alongside pygbag, and the 2D canvas stays on screen until the 3D view is drawing the game. If 3D can't start (no WebGL 2, a file missing, too big, the engine failed), the 2D view stays, the button reads *3D unavailable* and a note under it says why in plain words. Which view a page starts in: `?view=2d` or `?view=3d` in the address (for testing and sharing; not remembered), else the player's last choice on the button (kept in `localStorage`; a stored 2D wins over the default), else the game's default, which `templatePath(defaultView="2d")` makes 2D. A page that starts in 2D downloads nothing of the 3D view (not even the relay's three small scripts) until the button is pressed. `grid3d.web.wants3D()` tells the game 3D is on and the relay's scripts are in, so `Grid3DWebView.open()` can begin, and `set3D(False, reason)` turns it off. - The button sits in the page's top right corner. `grid3d.web.buttonArea()` gives its `(x, y, width, height)` in CSS pixels, the units of the web view's labels and panels, so a HUD can keep text out from under it (`None` outside a browser). The page never scrolls (`overflow: hidden`), so a phone's browser can't widen it to fit pygbag's 50000-pixel measuring element and push the button off screen, and its one viewport tag sets `width=device-width` (pygbag 0.9.3's default page has a second one that overrides it). Strata's own loading and failure overlay is hidden, so it never covers the 2D game. diff --git a/docs/grid3d.md b/docs/grid3d.md new file mode 100644 index 0000000..d9b7b95 --- /dev/null +++ b/docs/grid3d.md @@ -0,0 +1,387 @@ +# grid3d API reference + +`preponderous.graphik.grid3d` draws a grid game's board in 3D with +[Strata](https://github.com/Preponderous-Software/strata). This page lists +every public name, grouped by what a game does with it, with a short example +for each group. The README's [3D grid view](../README.md#3d-grid-view-optional) +section is the tour; this is the reference. + +Conventions used throughout: + +- **World axes.** x runs along the columns, z along the rows (row 0 is the far + edge, away from a camera south of the board), y is up. One cell is one world + unit and a board is centred on the origin. +- **Colours.** Scene colours are 0-1 floats, `(r, g, b)` or `(r, g, b, a)`. + The 2D stand-ins in `ui.py` (`Button`, `ScreenRecorder`) take 0-255 + colours, as `Graphik` does. +- **Screen units.** Labels, panels and pointers are in window pixels from the + top-left (CSS pixels in a browser). +- **No GPU needed** for anything except `Grid3DView.open()`. Importing + `grid3d` loads neither Strata nor pygame. + +Contents: [Scene data](#scene-data) · [Boards and pieces](#boards-and-pieces) · +[Animation](#animation) · [Picking and projection](#picking-and-projection) · +[Text](#text) · [Buttons and 2D screens](#buttons-and-2d-screens) · +[Touch keys](#touch-keys) · +[The desktop view](#the-desktop-view) · [The browser view](#the-browser-view) · +[The wire format](#the-wire-format) · [Fetching the relay](#fetching-the-relay) + +## Scene data + +`scene.py`: a frame as plain data. + +| Name | What it is | +|---|---| +| `CUBE`, `CAPSULE`, `CYLINDER`, `SPHERE` | Shape kinds 0-3, Strata's `STRATA_PRIMITIVE_*` | +| `Shape(kind, position, scale, color)` | An axis-aligned primitive; `scale` is its size along x, y, z | +| `Label(text, x, y, pixelSize, color=TEXT_COLOR)` | Screen text; `(x, y)` is the top-left of its first glyph | +| `Panel(x, y, width, height, color=(0, 0, 0, 0.6))` | A filled screen rectangle, drawn under every label | +| `Light(position, color, radius, intensity, castShadows=False)` | A point light. Strata takes a radius over 0 and no negative colour or intensity | +| `Camera(eye, target, fovDegrees=42.0)` | A right-handed look-at with +y up and a vertical field of view. It can't look straight up or down, or at its own eye | +| `Scene(shapes, labels, panels, lights, camera, clearColor)` | Everything one frame draws; `scene.checkLimits()` raises `SceneLimitError` | +| `SceneLimitError` | A `ValueError`: over `MAX_POINT_LIGHTS` (32) lights, over `MAX_SHADOWED_POINT_LIGHTS` (4) shadow casters, or an unknown shape kind | +| `TEXT_COLOR`, `DIM_TEXT_COLOR`, `CLEAR_COLOR` | Default colours | +| `rgb255(color)` | A 0-255 colour as 0-1 `(r, g, b)` | +| `rgba(color, alpha=1.0)` | `(r, g, b)` as `(r, g, b, alpha)` | +| `shade(color, factor)` | r, g and b scaled by `factor`, clamped to 0-1 | +| `fitText(text, width, pixelSize, margin=18)` | Text cut with `...` to fit `width` pixels (also in [Text](#text)) | + +```python +from preponderous.graphik.grid3d import CUBE, Camera, Label, Light, Scene, Shape, rgb255, rgba + +scene = Scene(camera=Camera(eye=(0, 8, 6), target=(0, 0, 0))) +scene.shapes.append(Shape(CUBE, (0, 0.25, 0), (1, 0.5, 1), rgba(rgb255((200, 60, 40))))) +scene.lights.append(Light((0, 2, 0), (1.0, 0.9, 0.7), radius=4.0, intensity=1.5)) +scene.labels.append(Label("Hello", 16, 16, 24)) +scene.checkLimits() +``` + +## Boards and pieces + +`board.py`: what is on each cell, and how it looks. + +| Name | What it is | +|---|---| +| `PieceStyle(kind, color, height, size, lift, glow, tones, extras)` | How one kind of piece looks. `glow=(radius, intensity)` adds a light above it; `tones=(odd, even)` shades a chain's links alternately; `extras(piece, x, z, baseY)` returns more `Shape`s placed relative to the piece | +| `Piece(id, column, row, style, scale, color, chain, link, facing, interpolate)` | Something on a cell. Keep `id` stable from tick to tick so it slides; `chain` and consecutive `link`s join orthogonal neighbours with a bridge; `interpolate=False` jumps | +| `Theme(tile, alternate, tileHeight, tileGap, frame, frameWidth, pieces, bridgeAcross, bridgeHeight, bridgeShade, highlight)` | The board's look; `pieces` maps a style name to a `PieceStyle`. `theme.style(name)` raises a `KeyError` naming the known styles | +| `Tile(color, raised=0.0)` | One cell's own tile (`GridBoard`'s `tiles`) | +| `Viewport(column, row, columns, rows)` | A window of a board; `Viewport.around(column, row, reach)` is the square around a cell; `contains(column, row)` | +| `GridBoard(columns, rows, theme=None, tiles=None, mergeTiles=False, viewport=None)` | A board drawn with a theme (below) | +| `cellCenter(column, row, columns, rows)` | World `(x, z)` of a cell's middle on a whole board | +| `fitCamera(columns, rows, aspect=1.0, fovDegrees=42.0, top=None, bottom=None)` | A camera south of the board that fits it in the window. A portrait window (aspect below 1) gets a steeper camera and a board that fills its width; between 0.8 and 1 the two framings blend. `top` and `bottom` are fractions of the window's height kept clear of the board (a HUD, a bar of touch keys) | +| `BED_TOP` | y of the tiles' top face (0.0); pieces stand on it | + +`GridBoard` methods: + +| Method | Returns | +|---|---| +| `scene(pieces, positions, labels, panels, lights, aspect, tint, clearColor, highlight, highlightColor, top, bottom)` | A complete `Scene`, lights checked; `highlight=(column, row)` lays a slab on that tile | +| `boardShapes(tint=None, tintAmount=0.55)` | The tiles and frame; `tint` blends every tile towards a colour | +| `pieceShapes(pieces, positions=None)` | `(shapes, lights)` for the pieces, at `positions` (id to world `(x, z)`) or on their cells | +| `highlightShapes(cell, color=None)` | The hover slab for one visible cell, or `[]` | +| `bridgePairs(pieces)`, `bridgeShape(a, b, aAt, bAt)` | The joined pairs of a chain in drawing order, and one bridge between two positions | +| `checkPieces(pieces)` | Raises `ValueError` (off the board, a duplicate id) or `KeyError` (unknown style) | +| `camera(aspect=1.0, top=None, bottom=None)` | `fitCamera` for what is on show | +| `cellCenter(column, row)`, `cellAt(x, z)` | Cell to world and back; `cellAt` is half-open (west and north edges in, east and south out) and `None` off the shown cells | +| `contains(column, row)`, `visible(column, row)` | On the board; on the board and in the viewport | +| `shownSize()`, `shownOrigin()` | The viewport's (or board's) size and top-left cell | +| `tileAt(column, row)`, `tileRaise(column, row)` | The `Tile` drawn on a cell (or `None` for a bare cell) and its raise | + +```python +from preponderous.graphik.grid3d import SPHERE, CUBE, GridBoard, Piece, PieceStyle, Shape, Theme, Tile + +def eyes(piece, x, z, baseY): # placed from (x, z): they move with the piece + return [Shape(SPHERE, (x + 0.2, baseY + 0.4, z - 0.3), (0.1, 0.1, 0.1), (1, 1, 1, 1))] + +theme = Theme(pieces={ + "head": PieceStyle(SPHERE, (0.2, 0.8, 0.3), extras=eyes), + "body": PieceStyle(CUBE, (0.1, 0.6, 0.2), tones=(0.9, 1.0)), +}) +board = GridBoard(14, 10, theme, tiles={(3, 3): Tile((0.2, 0.4, 0.8), raised=0.05)}, mergeTiles=True) +snake = [Piece("s0", 5, 5, "head", chain="s", link=0), Piece("s1", 5, 6, "body", chain="s", link=1)] +scene = board.scene(snake, aspect=900 / 700, highlight=(5, 4)) +``` + +## Animation + +`animate.py`. + +| Name | What it is | +|---|---| +| `Animator(cellCenter, reducedMotion=False, maxSlideCells=1.5)` | Slides each piece from where it was drawn to its new cell over one tick | +| `animator.update(pieces, now, tickSeconds, snap=False)` | Takes a tick's pieces at monotonic time `now`. A piece jumps when it is new, opted out, moved more than `maxSlideCells` (a diagonal step is 2), under reduced motion, or when `snap` is set. A tick of 0 or less (or NaN) places every piece at once | +| `animator.positions(now)` | id to world `(x, z)` at `now`; a time before the tick began gives its start | +| `animator.settled(now)` | True once every piece is on its cell | +| `animator.tracks` | id to `((x0, z0), (x1, z1))`, what the browser view sends | +| `interpolatePosition(start, end, alpha)` | `(x, z)` a fraction of the way, `alpha` clamped to 0-1 | + +```python +import time +from preponderous.graphik.grid3d import Animator, GridBoard, Piece + +board = GridBoard(8, 8) +animator = Animator(board.cellCenter) +animator.update([Piece(1, 0, 0, "pawn")], time.monotonic(), 0.15) +animator.update([Piece(1, 1, 0, "pawn")], time.monotonic(), 0.15) # next tick +x, z = animator.positions(time.monotonic())[1] # somewhere between +``` + +## Picking and projection + +`pick.py`: the same look-at and perspective the views ask Strata for. + +| Name | Returns | +|---|---| +| `pickCell(camera, board, x, y, width, height)` | The `(column, row)` under window pixel `(x, y)`, gaps between tiles included, or `None` (off the board, out of the viewport, above the horizon, or `x`/`y` is `None`) | +| `pickPoint(camera, x, y, width, height, planeY=BED_TOP)` | World `(x, z)` where that pixel's ray meets the plane, or `None` | +| `screenRay(camera, x, y, width, height)` | The ray's direction (not normalised) | +| `projectToScreen(camera, point, width, height)` | Window `(x, y)` of a world point, or `None` behind the camera | +| `cellScreenPosition(camera, board, column, row, width, height, y=BED_TOP)` | Where a cell's middle lands, `y` above the bed | + +A camera looking straight up or down, or with its eye on its target, raises +`ValueError`: Strata's look-at has no answer for those either, so tilt such a +camera a little. The views have the same calls bound to their own camera and +window: `view.camera()`, `view.pickCell(x, y)`, `view.projectToScreen(point)`, +`view.cellScreenPosition(column, row, y=0.0)`. + +```python +from preponderous.graphik.grid3d import GridBoard, cellScreenPosition, pickCell + +board = GridBoard(8, 8) +camera = board.camera(900 / 700) +cell = pickCell(camera, board, 450, 400, 900, 700) # what was tapped +note = cellScreenPosition(camera, board, 2, 3, 900, 700) # where to put a note +``` + +## Text + +`text.py`: Strata's built-in font is 8 x 8 and monospaced: every character +is one `pixelSize`-wide cell. A character outside printable ASCII (an +accented letter, an emoji) is drawn as one `?`, still one cell, so text is +measured in characters, not bytes. A NUL draws nothing on either backend. + +| Name | Returns | +|---|---| +| `measureText(text, pixelSize)` | The widest line's width in pixels | +| `fitText(text, width, pixelSize, margin=18)` | `text`, cut with `...` to fit | +| `wrapText(text, maxWidth, pixelSize)` | Lines, greedily word-wrapped; a word too long for a line stays whole on its own | +| `centredLabel(text, x, y, pixelSize, color=TEXT_COLOR, rise=0.5)` | A `Label` centred on `x`; `rise` places it on `y` (0.5 centres its cells, 0 puts its top there) | + +```python +from preponderous.graphik.grid3d import centredLabel, wrapText + +lines = wrapText("Eat the gems; avoid your own tail.", 300, 16) +labels = [centredLabel(line, 450, 200 + 20 * i, 16) for i, line in enumerate(lines)] +``` + +## Buttons and 2D screens + +`ui.py`: menus over a 3D view that behave like `Graphik`'s. Colours are 0-255. + +| Name | What it is | +|---|---| +| `Button(x, y, width, height, text, color, textColor, pixelSize=16, function=None, alpha=1.0, padding=None, rise=0.5)` | A screen button: `draw(pointer)` gives `(Panel, Label)` with the hover lift; `contains(position)` uses `drawButton`'s edges (left/top in, right/bottom out); `click(position)` runs `function`; `rect()` is the drawn box (widened by `padding` to fit its label) | +| `drawButtons(buttons, pointer=None)` | `([Label], [Panel])` for several buttons | +| `hoverColor(color)` | `drawButton`'s hover lift: light colours darken by 25, the rest lighten by 35 | +| `ScreenRecorder(width=800, height=600)` | Stands in for `Graphik` so a game's 2D screens run unchanged under a 3D view (below) | +| `RecordedText`, `RecordedRect`, `RecordedButton`, `RecordedImage` | What the recorder keeps for `drawText`, `drawRectangle`, `drawButton` and `drawImage` | +| `RecordedDisplay` | The recorder's `getGameDisplay()`: `get_size()`, `get_width()`, `get_height()`, `fill()` | + +`ScreenRecorder` answers every public call and colour constant `Graphik` +has: `drawText`, `drawRectangle`, `drawButton`, `drawImage` (recorded), +`beginFrame` and `endFrame` (nothing to do: the 3D view sends a press to +`click()` itself, once), `getGameDisplay`, `getVersion`, and `black`, +`white`, `red`, `green`, `blue`. Then `items` is the frame's calls in order, +`texts()`, `buttons()` and `images()` pick them out, `click(position)` runs +the first recorded button under `position`, and `reset()` starts the next +frame, `resize(width, height)` follows the window. + +```python +from preponderous.graphik.grid3d import Button, ScreenRecorder, drawButtons + +play = Button(350, 300, 200, 48, "Play", color=(40, 120, 60), textColor=(255, 255, 255), + pixelSize=20, function=lambda: print("play"), padding=12) +labels, panels = drawButtons([play], pointer=(400, 320)) +play.click((400, 320)) + +recorder = ScreenRecorder(900, 700) +mainMenu.draw(recorder) # a 2D screen that normally draws with Graphik +recorder.click((400, 320)) # runs that screen's own button function +``` + +## Touch keys + +`touchkeys.py`: a bar of on-screen keys along the bottom of a touch screen, +drawn alike in 2D (with `Graphik`) and 3D (as HUD panels and labels) from one +layout and one hit test. Sizes are CSS pixels; `scale` is a surface's CSS +pixels per pixel (1 for the web view). + +| Name | What it is | +|---|---| +| `TouchKey(label, key)` | One key: its label and the key it presses, by pygame's name (`"p"`, `"space"`, `"up"`, `"escape"`) | +| `TouchKeys(keys, minTarget=44, gap=6, margin=8, pixelSize=11, padding=6, portraitRows=3, landscapeRows=1, ...)` | The bar: rows of equal buttons, each at least `minTarget` each way. When the keys don't all fit, the last button is *More* (*Back* on the last page) | +| `keys.setKeys(keys)` | Changes the keys on offer (back to the first page) | +| `keys.layout(width, height, scale=1.0)` | The `KeySlot`s as laid out | +| `keys.bandHeight(width, height, scale=1.0)` | How much of the screen the bar takes, for `view.setInsets(bottom=...)` | +| `keys.below(width, height, pageWidth, pageHeight)` | The band a 2D game adds under its board, and the canvas's scale once the browser fits it to the page | +| `keys.press(position, width, height, pygame, scale=1.0)` | Posts the key's `KEYDOWN` and `KEYUP` (marked `touchKey=True`) and returns the `TouchKey`, `MORE` for More/Back, or `None` off the bar | +| `keys.draw(graphik, width, height, scale=1.0, pointer=None)` | Draws the bar in 2D | +| `keys.overlay(width, height, pointer=None)` | `(labels, panels)` for the 3D view's HUD | +| `keys.buttons(width, height)`, `keys.slotAt(position, width, height, scale=1.0)`, `TouchKeys.keyEvents(key, pygame)` | The bar as `Button`s (CSS pixels); the `KeySlot` under a point; the `KEYDOWN`/`KEYUP` pair a key posts | +| `KeySlot` | A laid-out button: `x`, `y`, `width`, `height`, `label`, `key`, `contains(position)` | +| `MIN_TARGET`, `MORE` | 44 (CSS pixels), and what `press()` returns for More | + +```python +from preponderous.graphik.grid3d import TouchKey, TouchKeys +from preponderous.graphik.grid3d import web + +keys = TouchKeys([TouchKey("Pause", "space"), TouchKey("Shop", "p")]) +if web.touchScreen(): + view.setInsets(top=40, bottom=keys.bandHeight(390, 844)) + labels, panels = keys.overlay(390, 844) # add to the HUD + # on a tap: + if keys.press(position, 390, 844, pygame) is None: + handle(position) # not on the bar: the game's +``` + +## The desktop view + +`view.py`. Linux and Windows x64; anywhere else `open()` raises +`Unavailable`. + +| Name | What it is | +|---|---| +| `Grid3DView.open(width=900, height=700, title="graphik", headless=False, reducedMotion=False, clock=time.monotonic)` | A window, or a headless surface for tests and screenshots. Under pygbag it returns a `Grid3DWebView` instead | +| `view.setBoard(board, tint=None, lights=())` | The static part, when the board, theme or tint changes | +| `view.setPieces(pieces, tickSeconds=0.0, snap=False)` | Once per game tick | +| `view.setLabels(labels=(), panels=())` | When the HUD changes | +| `view.setInsets(top=None, bottom=None)` | Pixels at the top (a HUD) and bottom (touch keys) kept clear of the board; the camera, picking and `cellScreenPosition` follow. Returns whether anything changed | +| `view.frame(now=None, present=True)` | Draws one frame (pieces where they are at `now`) | +| `view.scene(now=None)` | The `Scene` that frame would draw | +| `view.drawScene(scene, present=True)` | Draws a `Scene` a game built itself | +| `view.pollEvents()` | Every pending Strata event (`view.EVENT_QUIT`, `EVENT_KEY_DOWN`, `EVENT_KEY_UP`, `EVENT_RESIZED`, ...) | +| `view.resize(width, height)`, `view.savePng(path)`, `view.close()` | | +| `Unavailable` | Why 3D can't run here, in words a player can act on | +| `STRATA_VERSION` | The Strata release the binding loads (`STRATA_LIBRARY` points at a local build instead) | + +```python +from preponderous.graphik.grid3d import Grid3DView, Unavailable + +try: + view = Grid3DView.open(900, 700, "My game") +except Unavailable as reason: + view = None # keep the 2D view, and say why +if view: + view.setBoard(board) + while running: + for event in view.pollEvents(): + if event.type == view.EVENT_QUIT: + running = False + if tick(): + view.setPieces(pieces(), tickSeconds=0.15) + view.frame() + view.close() +``` + +## The browser view + +`web.py`: under pygbag, the page's Strata grid relay draws what a desktop +view would. Build the page with `pygbag --template ` and copy +the relay next to it ([Fetching the relay](#fetching-the-relay)). + +| Name | What it is | +|---|---| +| `Grid3DWebView` | `Grid3DView`'s calls (`setBoard`, `setPieces`, `setLabels`, `frame`, `scene`, `drawScene`, `pollEvents`, `resize`, `close`, picking) drawn by the relay. `frame()` does nothing: the page slides pieces itself. `drawScene()` sends only what changed. `savePng()` raises `Unavailable` | +| `Grid3DWebView.open(width, height, title, relay=None, maxBytes=4000000, reducedMotion=None, clock, canvas="relay")` | Asks the page for its 3D view; raises `Unavailable` when there is none or it failed | +| `view.ready`, `view.failure()` | Loaded yet; why it couldn't load | +| `templatePath(defaultView="3d")` | The pygbag page template, starting in 3D (or 2D) unless `?view=` or the player's last choice says otherwise | +| `wants3D()` | The page's 2D/3D button is on and the relay's scripts are in: time to `open()` | +| `set3D(on, reason="")` | Turns the button on or off; off with a reason marks 3D unavailable | +| `buttonArea()` | The button's `(x, y, width, height)` in CSS pixels, for keeping HUD text clear, or `None` | +| `touchScreen()` | The page is on a touch screen (a coarse pointer, or a touch seen; `?touch=1`/`?touch=0` overrides; `GRAPHIK_TOUCH=1` outside a browser): time to show `TouchKeys` | +| `parseArea(text)` | `"x,y,width,height"` as a tuple, or `None` | +| `pageObject(name)` | `window.` under pygbag, or `None` | +| `toPygameEvents(events, pygame, keys=False, pointer=True, fingers=True)` | Relay (or desktop Strata) events as pygame events, so 2D input code runs unchanged. Keys are off by default: pygbag's SDL already gets them | +| `pygameKey(scancode, pygame)` | The pygame key for a USB HID scancode, or 0 | +| `Event` | A relay event: `type`, `scancode`, `modifiers`, `repeat`, `button`, `width`, `height`, `x`, `y`, `dx`, `dy`, `text`, `pointer`, `id`, `nx`, `ny`, `key`, `pressure` | +| `EVENTS`, `EVENT_*` | Event type numbers, Strata's and the web's `FINGER_*` | +| `PlatformRelay(relay=None)` | The transport to the page's `window.StrataGridRelay` | +| `RecordingRelay(reducedMotion=False, state="ready")` | A transport that keeps what it is sent: for tests, and `wireJson()` for the relay's test page | + +```python +from preponderous.graphik.grid3d import Grid3DView, Unavailable +from preponderous.graphik.grid3d import web + +view = None +def follow(): # call once per frame + global view + if web.wants3D() and view is None: + try: + view = Grid3DView.open(900, 700, "My game") # a Grid3DWebView here + view.setBoard(board) + except Unavailable as reason: + web.set3D(False, str(reason)) + elif not web.wants3D() and view is not None: + view.close() + view = None + if view is not None: + for event in web.toPygameEvents(view.pollEvents(), pygame): + handle(event) # the game's own 2D handler +``` + +## The wire format + +The messages `Grid3DWebView` sends, as functions: Strata's +`web/kit/grid-relay/WIRE.md` is the specification (format 1.0). + +| Name | What it is | +|---|---| +| `encodeBoard(shapes, lights=())`, `encodePieces(board, pieces, tracks, tickSeconds)`, `encodeHud(labels=(), panels=())`, `encodeView(camera, clearColor, sun, near, far)` | One message each. They raise `WireError` for anything the relay would refuse, with the relay's status: counts over its limits (-6), and a non-finite number, a coordinate past ±10⁶, a light with no radius or a negative colour or intensity, a HUD colour with a negative part or alpha over 1, or a camera with its eye on its target (-5) | +| `decode(message)` | `(kind, contents)`, with the relay's checks: for tests and tools | +| `readHeader(message)` | `(major, minor, kind)`, or `WireError` as the relay says it | +| `header(kind)` | The 8-byte header | +| `WireError` | A `ValueError` with the relay's `status` (`STATUS` maps it to words) | +| `WIRE_MAJOR`, `WIRE_MINOR`, `MAGIC`, `BOARD`, `PIECES`, `HUD`, `VIEW`, `WORLD`, `PIECE`, `BRIDGE` | Format constants | +| `MAX_SHAPES`, `MAX_ANCHORS`, `MAX_LIGHTS`, `MAX_SHADOWED_LIGHTS`, `MAX_HUD_ITEMS`, `MAX_COORDINATE` | The relay's limits | +| `SUN_DIRECTION`, `NEAR_PLANE`, `FAR_PLANE` | The desktop view's, sent with every view | + +The encoder is held to golden bytes +(`src/test/python/preponderous/graphik/grid3d/golden/wire-1.0.hex`) that +Strata's relay tests read with its own parser, so the two sides can't drift +apart unnoticed. + +```python +from preponderous.graphik.grid3d import Label +from preponderous.graphik.grid3d import web + +message = web.encodeHud([Label("Score 3", 12, 8, 16)]) +kind, hud = web.decode(message) +assert kind == web.HUD and hud["labels"][0]["text"] == "Score 3" +``` + +## Fetching the relay + +`relay.py`, run after `pygbag --build`: + +```bash +python -m preponderous.graphik.grid3d.relay --strata 0.9.0 --dest build/web [--replace] +``` + +It downloads `strata--wasm32-emscripten.tar.gz` and the release's +`SHA256SUMS`, checks the tarball's SHA-256 (refusing a missing, malformed or +contradictory line), checks every member under `kit/grid-relay/dist/` before +writing anything (no links or devices, nothing outside `--dest`, even through +a link inside it, under 64 MB in all) and copies them next to the page. Files +already there are kept; with `--replace` the relay's own files are replaced +(after moving to a newer Strata) and only `index.html`, the game's page, is +kept. Only a release version (`0.9.0`, `1.0.0-rc.1`) is taken for `--strata`. + +| Name | What it is | +|---|---| +| `fetchRelay(version, dest, base=RELEASES, download=None, replace=False)` | The whole fetch; returns `(copied, skipped)` | +| `extractDist(data, dest, prefix=DIST, replace=False)` | Unpacks a tarball's relay folder | +| `verify(data, sums, name)`, `expectedDigest(sums, name)` | The checksum check | +| `tarballName(version)` | The release asset's name | +| `RelayFetchError` | Why it couldn't fetch, verify or unpack | +| `main(argv=None)` | The command line | diff --git a/src/main/python/preponderous/graphik/grid3d/__init__.py b/src/main/python/preponderous/graphik/grid3d/__init__.py index c633cf4..8563c55 100644 --- a/src/main/python/preponderous/graphik/grid3d/__init__.py +++ b/src/main/python/preponderous/graphik/grid3d/__init__.py @@ -14,6 +14,8 @@ stand-in for running 2D screens under a 3D view (ui.py), and a bar of on-screen keys for touch screens, drawn alike in 2D and 3D (touchkeys.py). +The API reference, with an example for each part, is docs/grid3d.md. + Importing this package imports neither Strata nor pygame. """ From 9555436c3048384888fd6607f541fd6bf20d76e9 Mon Sep 17 00:00:00 2001 From: Daniel McCoy Stephenson Date: Fri, 20 Nov 2026 18:01:34 -0700 Subject: [PATCH 08/11] feat: a 3D view whose drawing stays too slow goes back to 2D, saying why The relay's onSlow calls StrataLoader.slow(), which does nothing on graphik's page, and the template's "slow" reason was never used. The page now watches the drawing itself once Strata's kit is at its lowest quality tier and pixel density 1: second by second, the typical frame (the median gap between the page's requestAnimationFrame calls, long stalls cut), the relay's own drawing a frame (its stats' cpuMs) and the kit's own average frame (frameMs). When for 5 seconds the typical frame and the kit's average are over 66 ms and the drawing is at least a quarter of the typical frame, the page goes back to 2D and the note says "Back to 2D: this device draws the 3D view too slowly. Press 3D to try it again." A game that stops the page now and then (building and sending a board in Python), or that is slow every frame while the drawing is cheap, stays in 3D: 2D would not help it. Counting starts 3 seconds after the game's first message to the 3D view (pygbag's boot and the first shader compile are not counted) and stops while the tab is hidden. The switch is not remembered as the player's choice and is not a failure: the button still offers 3D, and once the player chooses 3D again the page leaves it alone until it is reloaded. ?slow=0 in the address turns the switch off (for testing on a machine that draws in software); Graphik3D.slowed() says it happened and Graphik3D.speed() gives the last second's readings. Node tests drive it against a stand-in relay and page frames: slow drawing switches (stalls or not); a stalling game with fast drawing, a slow game with cheap drawing, and a kit reporting fast frames (as browser test harnesses pin it on software GL) don't. drafted by Claude on behalf of Daniel Stephenson Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LYNeuoCqxFpUXrFhxnTg89 --- README.md | 1 + docs/grid3d.md | 8 + .../graphik/grid3d/templates/pygbag.tmpl | 104 +++++++++++- .../graphik/grid3d/test_grid3d_template_js.py | 154 +++++++++++++++++- .../graphik/grid3d/test_grid3d_web.py | 2 +- 5 files changed, 258 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index b31910d..2f7d701 100644 --- a/README.md +++ b/README.md @@ -146,6 +146,7 @@ Under [pygbag](https://pypi.org/project/pygbag/) (`sys.platform == "emscripten"` - `view.pollEvents()` returns Strata-style events (keys with desktop Strata's scancodes, mouse, wheel, resize, and `FINGER_*` for touch), and `grid3d.web.toPygameEvents(events, pygame)` turns them into pygame events, so a game's 2D input code runs unchanged. It converts desktop Strata events too. - The page: build with `pygbag --template ...`, a copy of pygbag 0.9.3's default template with the relay's canvas and a **2D/3D** button. The relay has to be served with the game (a browser can't fetch GitHub release assets cross-origin): `python -m preponderous.graphik.grid3d.relay --strata 0.9.0 --dest ` downloads Strata's `strata--wasm32-emscripten.tar.gz`, checks it against the release's `SHA256SUMS` and copies its prebuilt `kit/grid-relay/dist/` next to the page, leaving files already there (pygbag's `index.html`) alone; `--replace` replaces an earlier relay's files (never `index.html`) when moving to a newer Strata. - Since 0.5.1 the page starts in **3D**, as a desktop `Grid3DView` game does: the relay's scripts and engine load at once, alongside pygbag, and the 2D canvas stays on screen until the 3D view is drawing the game. If 3D can't start (no WebGL 2, a file missing, too big, the engine failed), the 2D view stays, the button reads *3D unavailable* and a note under it says why in plain words. Which view a page starts in: `?view=2d` or `?view=3d` in the address (for testing and sharing; not remembered), else the player's last choice on the button (kept in `localStorage`; a stored 2D wins over the default), else the game's default, which `templatePath(defaultView="2d")` makes 2D. A page that starts in 2D downloads nothing of the 3D view (not even the relay's three small scripts) until the button is pressed. `grid3d.web.wants3D()` tells the game 3D is on and the relay's scripts are in, so `Grid3DWebView.open()` can begin, and `set3D(False, reason)` turns it off. +- **Too slow: back to 2D.** Since 0.5.3, when the 3D view stays slow once the game is drawing in it, the page goes back to 2D and the note says why in plain words ("this device draws the 3D view too slowly"). Strata's kit first gives up pixel density (down to 1) and then its quality tier; only once it has nothing left to give up, and the drawing itself stays slow for 5 seconds, does the page switch: second by second, the typical frame (the median time between the page's frames) is over 66 ms, the relay's own drawing (its `stats()` `cpuMs`) is at least a quarter of it, and the kit's own average frame (`frameMs`) is over 66 ms too. A game that stops the page now and then (building and sending a board in Python) makes a few long gaps, not a slow typical frame, and a game that is slow every frame while the drawing is cheap wouldn't be helped by 2D, so neither switches. Counting starts 3 seconds after the game's first message to the 3D view, so pygbag's boot and the first shader compile aren't counted, and stops while the tab is hidden. The switch isn't remembered as the player's choice: the button still offers 3D, and once the player chooses 3D again the page leaves it alone until it is reloaded. `?slow=0` in the address turns the switch off (for testing on a machine that draws in software). `Graphik3D.slowed()` in the page says it happened, and `Graphik3D.speed()` gives the last second's readings. - The button sits in the page's top right corner. `grid3d.web.buttonArea()` gives its `(x, y, width, height)` in CSS pixels, the units of the web view's labels and panels, so a HUD can keep text out from under it (`None` outside a browser). The page never scrolls (`overflow: hidden`), so a phone's browser can't widen it to fit pygbag's 50000-pixel measuring element and push the button off screen, and its one viewport tag sets `width=device-width` (pygbag 0.9.3's default page has a second one that overrides it). Strata's own loading and failure overlay is hidden, so it never covers the 2D game. In a game's `browser.yml`, where graphik is installed into `src/` for pygbag: diff --git a/docs/grid3d.md b/docs/grid3d.md index d9b7b95..aef910a 100644 --- a/docs/grid3d.md +++ b/docs/grid3d.md @@ -330,6 +330,14 @@ def follow(): # call once per frame handle(event) # the game's own 2D handler ``` +The page goes back to 2D by itself, with the reason on screen, when 3D can't +start or when its drawing stays too slow once the game draws in it (for 5 +seconds the typical frame and the kit's average frame are over 66 ms and the +relay's own drawing at least a quarter of the typical frame, with Strata's kit at its lowest tier and pixel density 1; +the game's own pauses don't count); the +latter is not remembered, the button brings 3D back, and `?slow=0` in the +address turns it off. + ## The wire format The messages `Grid3DWebView` sends, as functions: Strata's diff --git a/src/main/python/preponderous/graphik/grid3d/templates/pygbag.tmpl b/src/main/python/preponderous/graphik/grid3d/templates/pygbag.tmpl index 082c249..4c11a0d 100644 --- a/src/main/python/preponderous/graphik/grid3d/templates/pygbag.tmpl +++ b/src/main/python/preponderous/graphik/grid3d/templates/pygbag.tmpl @@ -444,7 +444,10 @@ frameborder="1" Starting in 3D, the relay's scripts and engine load at once, alongside pygbag. The 2D canvas stays on screen until the 3D view is drawing the game, and comes back, with the reason in plain words, whenever 3D can't - start (no WebGL 2, a file missing, too big, the engine failed). A page + start (no WebGL 2, a file missing, too big, the engine failed), or when + the 3D view stays too slow once the game is drawing in it (see + watchSpeed() below; that switch is not remembered, and the button + brings 3D back). A page starting in 2D fetches nothing of the 3D view until the button is pressed. The relay's files (grid-relay-scene.js and .wasm, strata-loader.js, strata-kit.js, grid-relay.js) go next to this page: @@ -606,11 +609,94 @@ frameborder="1" if (!on) { if (relay && relay.state() !== "idle") relay.close(); fed = false; + fedAt = 0; + stopWatching(); show3d(false); show2d(true); } label(); } + // Too slow: the relay's kit first lowers its pixel density to 1, then its + // quality tier to the lowest; Strata's onSlow then calls a + // StrataLoader.slow() that does nothing on this page. The page goes back + // to 2D, saying why, only when the drawing itself stays slow once the kit + // can go no lower: for SLOW_FOR_MS, every SLOW_WINDOW_MS window has its + // typical frame (the median time between frames, the page's own + // requestAnimationFrame) over SLOW_FRAME_MS, with the relay's own drawing + // (its stats' cpuMs a frame) at least DRAW_SHARE of it, and the kit's own + // average frame (its stats' frameMs) over SLOW_FRAME_MS too. A game that stops + // the page now and then (building and sending a board in Python) makes a + // few long gaps between frames, not a slow typical frame, and a game that + // is slow every frame is not helped by 2D: neither counts. Counting starts + // SLOW_GRACE_MS after the game's first message to the 3D view (pygbag's + // boot, the shaders' first compile and the kit's own steps down are not + // counted), and stops while the tab is hidden. It is not the player's + // choice: it is not remembered, the button brings 3D back, and once the + // player has done that the page leaves 3D alone, however slow, until it + // is reloaded. ?slow=0 in the address turns this off (for testing on a + // machine that draws in software). + const SLOW_FRAME_MS = 66, SLOW_FOR_MS = 5000, SLOW_GRACE_MS = 3000, SLOW_WINDOW_MS = 1000; + const DRAW_SHARE = 0.25, STALL_MS = 250; + let fedAt = 0, slowDropped = false, slowAccepted = false; + let slowWindows = 0, windowStart = 0, sampling = false, lastFrameAt = 0, gaps = []; + let lastWindow = ""; // the last second's readings, for Graphik3D.speed() + try { slowAccepted = new URLSearchParams(window.location.search).get("slow") === "0"; } catch (e) { slowAccepted = false; } + function frameStats(relay) { + if (typeof relay.stats !== "function") return null; + try { return JSON.parse(relay.stats()); } catch (e) { return null; } + } + function sampleFrame(t) { + if (!sampling) return; + if (lastFrameAt) gaps.push(t - lastFrameAt); + lastFrameAt = t; + window.requestAnimationFrame(sampleFrame); + } + function stopWatching() { + sampling = false; + lastFrameAt = 0; + gaps = []; + windowStart = 0; + slowWindows = 0; + } + // One window's verdict: true when the kit is at its lowest and the drawing + // slow, false when not, null when the window was nearly all stall (it + // neither counts nor starts the count again). + function slowWindow(relay) { + const s = frameStats(relay); + if (!(s && s.quality === 0 && typeof s.dpr === "number" && s.dpr <= 1.01)) return false; + const sorted = gaps.slice().sort(function (a, b) { return a - b; }); + if (!sorted.length) return null; + // a stall is a gap far past the window's typical one + const cut = Math.max(STALL_MS, 3 * sorted[sorted.length >> 1]); + const kept = sorted.filter(function (ms) { return ms <= cut; }); + if (kept.length < 3) return null; + const typical = kept[kept.length >> 1]; + lastWindow = JSON.stringify({typical: typical, drawMs: Number(s.cpuMs), frames: sorted.length, stalls: sorted.length - kept.length}); + // the kit's own average (stalls and all) must say slow too: it can only + // be lower than a slow typical frame when the frames aren't slow + return typical > SLOW_FRAME_MS && Number(s.cpuMs) >= DRAW_SHARE * typical + && Number(s.frameMs) > SLOW_FRAME_MS; + } + function watchSpeed(relay, now) { + if (slowAccepted || !fedAt || now - fedAt < SLOW_GRACE_MS || document.hidden + || typeof window.requestAnimationFrame !== "function") { stopWatching(); return; } + if (!sampling) { + sampling = true; + window.requestAnimationFrame(sampleFrame); + } + if (!windowStart || now - windowStart >= SLOW_WINDOW_MS) { + const verdict = windowStart ? slowWindow(relay) : null; + if (verdict !== null) slowWindows = verdict ? slowWindows + 1 : 0; + windowStart = now; + gaps = []; + if (typeof relay.resetStats === "function") relay.resetStats(); + } + if (slowWindows * SLOW_WINDOW_MS < SLOW_FOR_MS) return; + stopWatching(); + slowDropped = true; + set(0); + tell("Back to 2D: " + REASONS.slow + ". Press 3D to try it again."); + } // The 2D canvas hides only once the 3D view is drawing the game, and // comes back if 3D fails, so there is always a view on screen. setInterval(function () { @@ -626,11 +712,17 @@ frameborder="1" const c = canvas3d(); const drawing = state === "ready" && fed && !(c && c.hidden); show3d(drawing); - if (drawing) show2d(false); - else if (state.indexOf("failed:") === 0) fail(state.slice(7)); + if (drawing) { + show2d(false); + const now = Date.now(); + if (!fedAt) fedAt = now; + watchSpeed(relay, now); + } else if (state.indexOf("failed:") === 0) fail(state.slice(7)); }, 150); button.addEventListener("click", function () { if (!broken) { + // 3D chosen again after it was dropped for being slow: the player's call + if (!on && slowDropped) slowAccepted = true; set(on ? 0 : 1); if (!broken) remember(on ? "3d" : "2d"); } @@ -655,6 +747,12 @@ frameborder="1" set: function (value, reason) { set(Number(value), reason || ""); return on; }, toggle: function () { return this.set(on ? 0 : 1); }, unavailable: function () { return broken; }, + // 1 once the page went back to 2D because 3D was too slow (not a + // failure: the button still offers 3D) + slowed: function () { return slowDropped ? 1 : 0; }, + // the slow check's last second ({typical, drawMs, frames, stalls}, JSON, + // "" before the first) and how many slow seconds in a row, for testing + speed: function () { return JSON.stringify({last: lastWindow ? JSON.parse(lastWindow) : null, slowSeconds: slowWindows}); }, // the view the page started in: "2d" or "3d" starting: startingView, // where the button is, in CSS pixels from the viewport's top left diff --git a/src/test/python/preponderous/graphik/grid3d/test_grid3d_template_js.py b/src/test/python/preponderous/graphik/grid3d/test_grid3d_template_js.py index d77f2b6..cf93c49 100644 --- a/src/test/python/preponderous/graphik/grid3d/test_grid3d_template_js.py +++ b/src/test/python/preponderous/graphik/grid3d/test_grid3d_template_js.py @@ -6,6 +6,11 @@ happen in. A player who turns 3D off while the relay is still loading, then on again, must get the 3D view (not a blank page with both canvases hidden), and a relay that finishes loading after 2D was chosen must stop drawing. + +Also here: the switch back to 2D when the 3D view stays too slow (only +once the kit can go no lower, only after the game's first message and a +grace period, never remembered, and not again once the player chose 3D +after it). """ import json @@ -22,6 +27,7 @@ const vm = require("vm"); const block = require("fs").readFileSync(process.argv[2], "utf8"); const steps = JSON.parse(process.argv[3]); +const search = process.argv[4] || ""; function element(id) { const listeners = {}; @@ -35,7 +41,23 @@ }; } const els = {canvas: element("canvas"), relay: element("relay"), graphik3d: element("graphik3d"), - "graphik3d-note": element("graphik3d-note")}; + "graphik3d-note": element("graphik3d-note"), "graphik3d-2d": element("graphik3d-2d"), + "graphik3d-3d": element("graphik3d-3d")}; +let clock = 1000000, stored = null; +// the page's frames: one every `gap` ms, and a stall of `stallMs` (the game's +// Python holding the page) every `stallEvery` ms +const pace = {gap: 16.7, stallEvery: 0, stallMs: 0}; +let rafs = [], lastFrame = clock; +function frames() { + for (;;) { + let next = lastFrame + pace.gap; + if (pace.stallEvery && Math.floor(next / pace.stallEvery) > Math.floor(lastFrame / pace.stallEvery)) next += pace.stallMs; + if (next > clock) return; + lastFrame = next; + const due = rafs; rafs = []; + due.forEach((f) => f(next)); + } +} els.canvas.style.visibility = "visible"; let interval = null, pendingScripts = []; @@ -52,20 +74,27 @@ finishLoading() { if (this.s === "loading") { this.kit = true; this.s = "ready"; this.running = true; } }, state() { return this.s; }, send() { this.sent++; return 0; }, + // what Strata's kit reports: its tier (0 lowest), pixel density, its own + // frame-time average (stalls included), and the relay's drawing a frame + frame: {quality: 2, dpr: 3, dprCap: 2, frameMs: 16, cpuMs: 2}, + stats() { return JSON.stringify(Object.assign({state: this.s}, this.frame)); }, + resets: 0, + resetStats() { this.resets++; }, close() { this.running = false; els.relay.hidden = true; if (this.s === "ready") this.s = "idle"; }, }; const window = { - location: {search: ""}, WebGL2RenderingContext: function () {}, - localStorage: {getItem: () => null, setItem() {}}, + location: {search}, WebGL2RenderingContext: function () {}, + localStorage: {getItem: () => null, setItem(k, v) { stored = v; }}, addEventListener() {}, removeEventListener() {}, + requestAnimationFrame(f) { rafs.push(f); return rafs.length; }, }; const document = { getElementById: (id) => els[id] || null, createElement: () => ({}), body: {appendChild(tag) { pendingScripts.push(tag); }}, }; -const context = {window, document, URLSearchParams, JSON, String, Number, Math, +const context = {window, document, URLSearchParams, JSON, String, Number, Math, Date: {now: () => clock}, setInterval: (f) => { interval = f; return 1; }, setTimeout: () => 0, clearTimeout() {}}; vm.runInNewContext(block, context); @@ -81,11 +110,21 @@ if (step === "scripts") loadScripts(); else if (step === "click") els.graphik3d.fire("click"); else if (step === "loaded") relay.finishLoading(); + else if (step === "fail") relay.s = "failed:engine"; else if (step === "send") window.StrataGridRelay.send("AAAA"); else if (step === "tick") interval(); + else if (step.frame) Object.assign(relay.frame, step.frame); + else if (step.pace) Object.assign(pace, step.pace); + else if (step.wait) { // the page's frames and its 150 ms check, for that long + for (let t = 0; t < step.wait; t += 150) { clock += 150; frames(); interval(); } + } log.push({step, state: relay.s, running: relay.running, relayHidden: els.relay.hidden, relayVisible: els.relay.style.visibility === "visible", twoD: els.canvas.style.visibility, - wanted: window.Graphik3D.wanted()}); + wanted: window.Graphik3D.wanted(), slowed: window.Graphik3D.slowed(), stored, + note: els["graphik3d-note"].hidden ? "" : els["graphik3d-note"].textContent, + view: els.graphik3d.attrs["data-view"], pressed: els.graphik3d.attrs["aria-pressed"], + name: els.graphik3d.attrs["aria-label"], text: els.graphik3d.textContent, + lit: ["2d", "3d"].filter((v) => /graphik3d-current/.test(els["graphik3d-" + v].className || ""))}); } console.log(JSON.stringify(log)); """ @@ -97,12 +136,12 @@ def graphikScript(page): return block[start:block.index("", start)] -def run(tmp_path, steps): +def run(tmp_path, steps, search=""): with open(web.templatePath(), encoding="utf-8") as handle: script = graphikScript(handle.read()) (tmp_path / "block.js").write_text(script, encoding="utf-8") (tmp_path / "harness.js").write_text(HARNESS, encoding="utf-8") - out = subprocess.run([NODE, str(tmp_path / "harness.js"), str(tmp_path / "block.js"), json.dumps(steps)], + out = subprocess.run([NODE, str(tmp_path / "harness.js"), str(tmp_path / "block.js"), json.dumps(steps), search], capture_output=True, text=True, timeout=60) assert out.returncode == 0, out.stderr return json.loads(out.stdout) @@ -131,3 +170,104 @@ def test_the_2d_view_stays_until_the_3d_view_is_drawing_the_game(tmp_path): log = run(tmp_path, ["scripts", "loaded", "tick", "send", "tick"]) assert log[2]["twoD"] == "visible" # loaded, but nothing sent yet assert log[4]["twoD"] == "hidden" and log[4]["relayVisible"] and not log[4]["relayHidden"] + + +# -- too slow: back to 2D + +LOWEST = {"quality": 0, "dpr": 1, "dprCap": 1} +# the kit at its lowest, a frame every 90 ms, 40 of them the relay's drawing +SLOW = {"frame": dict(LOWEST, frameMs=90, cpuMs=40)} +SLOW_PACE = {"pace": {"gap": 90, "stallEvery": 0, "stallMs": 0}} +DRAWING = ["scripts", "loaded", "tick", "send", "tick"] + + +@pytest.mark.skipif(NODE is None, reason="needs node") +def test_3d_that_stays_slow_at_the_lowest_tier_goes_back_to_2d_saying_why(tmp_path): + log = run(tmp_path, DRAWING + [SLOW_PACE, SLOW, {"wait": 3000}, {"wait": 4800}, {"wait": 600}]) + assert log[4]["twoD"] == "hidden" # drawing in 3D + assert not log[-3]["slowed"] and not log[-2]["slowed"] # grace, then not yet 5 s + last = log[-1] + assert last["slowed"] and last["twoD"] == "visible" and not last["relayVisible"] + assert not last["running"] and not last["wanted"] + assert last["note"] == "Back to 2D: this device draws the 3D view too slowly. Press 3D to try it again." + # not a failure: the button still offers 3D, and the switch is not the player's choice + assert last["stored"] is None + + +@pytest.mark.skipif(NODE is None, reason="needs node") +def test_slow_frames_before_the_kit_has_stepped_down_do_not_count(tmp_path): + # the kit still has pixel density or a quality tier to give up + for frame, gap in (({"quality": 1, "dpr": 1, "cpuMs": 150}, 200), ({"quality": 0, "dpr": 2, "cpuMs": 150}, 200), + (dict(LOWEST, cpuMs=40), 50)): + log = run(tmp_path, DRAWING + [{"pace": {"gap": gap}}, {"frame": frame}, {"wait": 20000}]) + assert not log[-1]["slowed"] and log[-1]["twoD"] == "hidden", frame + + +@pytest.mark.skipif(NODE is None, reason="needs node") +def test_nothing_counts_before_the_games_first_message_to_the_3d_view(tmp_path): + # pygbag's boot: the relay is loaded and slow, but the game hasn't drawn + log = run(tmp_path, ["scripts", "loaded", SLOW_PACE, SLOW, "tick", {"wait": 20000}, "send", "tick", + {"wait": 2900}]) + assert not log[-1]["slowed"] and log[-1]["twoD"] == "hidden" + + +@pytest.mark.skipif(NODE is None, reason="needs node") +def test_a_fast_window_starts_the_count_again(tmp_path): + fast = {"pace": {"gap": 30}} + log = run(tmp_path, DRAWING + [SLOW_PACE, SLOW, {"wait": 3000}, {"wait": 4500}, fast, {"wait": 1500}, + SLOW_PACE, {"wait": 4500}]) + assert not log[-1]["slowed"] and log[-1]["twoD"] == "hidden" + + +@pytest.mark.skipif(NODE is None, reason="needs node") +def test_slow_0_in_the_address_turns_the_switch_off(tmp_path): + log = run(tmp_path, DRAWING + [SLOW_PACE, SLOW, {"wait": 30000}], search="?slow=0") + assert not log[-1]["slowed"] and log[-1]["twoD"] == "hidden" and log[-1]["running"] + + +@pytest.mark.skipif(NODE is None, reason="needs node") +def test_after_a_slow_switch_the_player_can_choose_3d_and_keep_it(tmp_path): + log = run(tmp_path, DRAWING + [SLOW_PACE, SLOW, {"wait": 9000}, "click", "send", "tick", {"wait": 30000}]) + last = log[-1] + assert log[-5]["slowed"] # it went back to 2D once + assert last["twoD"] == "hidden" and last["relayVisible"] and last["running"] and last["wanted"] + assert last["stored"] == "3d" # the player's own press is remembered, as ever + + +@pytest.mark.skipif(NODE is None, reason="needs node") +def test_a_game_that_stalls_the_page_while_drawing_is_fast_stays_in_3d(tmp_path): + # Python building and sending a board stops the page for 180-1800 ms now + # and then: the kit's own average says 300 ms, but the relay draws a + # frame in under 3 ms and the typical frame is 16.7 ms + stalls = {"pace": {"gap": 16.7, "stallEvery": 1200, "stallMs": 900}} + log = run(tmp_path, DRAWING + [stalls, {"frame": dict(LOWEST, frameMs=300, cpuMs=2.6)}, {"wait": 40000}]) + assert not log[-1]["slowed"] and log[-1]["twoD"] == "hidden" and log[-1]["running"] + # long stalls between slow frames still don't count as drawing (they're cut) + longStalls = {"pace": {"gap": 16.7, "stallEvery": 2000, "stallMs": 1800}} + log = run(tmp_path, DRAWING + [longStalls, {"frame": dict(LOWEST, frameMs=600, cpuMs=2.8)}, {"wait": 40000}]) + assert not log[-1]["slowed"] + + +@pytest.mark.skipif(NODE is None, reason="needs node") +def test_a_game_slow_every_frame_with_cheap_drawing_stays_in_3d(tmp_path): + # 2D wouldn't help: the relay's drawing is 3 of the 90 ms + log = run(tmp_path, DRAWING + [SLOW_PACE, {"frame": dict(LOWEST, frameMs=90, cpuMs=3)}, {"wait": 40000}]) + assert not log[-1]["slowed"] and log[-1]["twoD"] == "hidden" + + +@pytest.mark.skipif(NODE is None, reason="needs node") +def test_slow_drawing_goes_to_2d_even_with_stalls_between(tmp_path): + pace = {"pace": {"gap": 120, "stallEvery": 2500, "stallMs": 1500}} + log = run(tmp_path, DRAWING + [pace, {"frame": dict(LOWEST, frameMs=400, cpuMs=70)}, {"wait": 20000}]) + assert log[-1]["slowed"] and log[-1]["twoD"] == "visible" + + +@pytest.mark.skipif(NODE is None, reason="needs node") +def test_a_relay_whose_kit_reports_fast_frames_keeps_3d(tmp_path): + # Slow page frames and costly drawing, but the kit's own average says + # 16 ms: the switch needs all three. (Browser test harnesses pin the + # kit's frameMs this way to keep 3D on a machine that draws in software; + # a check that read only the page's frames and cpuMs sent their games to + # 2D mid-run.) + log = run(tmp_path, DRAWING + [SLOW_PACE, {"frame": dict(LOWEST, frameMs=16, cpuMs=300)}, {"wait": 40000}]) + assert not log[-1]["slowed"] and log[-1]["twoD"] == "hidden" and log[-1]["running"] diff --git a/src/test/python/preponderous/graphik/grid3d/test_grid3d_web.py b/src/test/python/preponderous/graphik/grid3d/test_grid3d_web.py index 9466034..1427544 100644 --- a/src/test/python/preponderous/graphik/grid3d/test_grid3d_web.py +++ b/src/test/python/preponderous/graphik/grid3d/test_grid3d_web.py @@ -557,7 +557,7 @@ def test_2d_shows_until_3d_draws_the_game_and_comes_back_with_a_reason(): # the 2D canvas hides only once the game has sent the 3D view something assert "fed = true" in block assert 'const drawing = state === "ready" && fed && !(c && c.hidden);' in block - assert "if (drawing) show2d(false);" in block + assert "if (drawing) {\n show2d(false);" in block # failures say why, in words, on the page assert 'id="graphik3d-note"' in block and 'role="status"' in block assert "No 3D view here: " in block and "The 2D view stays." in block From b82b43bf76cdd411a0f8cc839b28f027b2255dbe Mon Sep 17 00:00:00 2001 From: Daniel McCoy Stephenson Date: Fri, 20 Nov 2026 18:01:34 -0700 Subject: [PATCH 09/11] feat: the 2D/3D button shows both views, the one on show lit The button read "2D" while the 3D view was on, like a status. It is now a switch with both views on it, 2D and 3D, the current one highlighted; to a screen reader it is a toggle named "3D view", aria-pressed while 3D is on ("3D view unavailable" when 3D cannot start), and data-view says what is on show. It is at least 44 CSS pixels each way (it was 36 tall), the note sits below it, and buttonArea() measures it as drawn. A duplicated comment opener in the template was removed. drafted by Claude on behalf of Daniel Stephenson Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LYNeuoCqxFpUXrFhxnTg89 --- README.md | 2 +- docs/grid3d.md | 4 +++ .../graphik/grid3d/templates/pygbag.tmpl | 33 +++++++++++++++---- .../graphik/grid3d/test_grid3d_template_js.py | 26 +++++++++++++-- .../graphik/grid3d/test_grid3d_web.py | 15 +++++++++ 5 files changed, 70 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 2f7d701..5780c2e 100644 --- a/README.md +++ b/README.md @@ -147,7 +147,7 @@ Under [pygbag](https://pypi.org/project/pygbag/) (`sys.platform == "emscripten"` - The page: build with `pygbag --template ...`, a copy of pygbag 0.9.3's default template with the relay's canvas and a **2D/3D** button. The relay has to be served with the game (a browser can't fetch GitHub release assets cross-origin): `python -m preponderous.graphik.grid3d.relay --strata 0.9.0 --dest ` downloads Strata's `strata--wasm32-emscripten.tar.gz`, checks it against the release's `SHA256SUMS` and copies its prebuilt `kit/grid-relay/dist/` next to the page, leaving files already there (pygbag's `index.html`) alone; `--replace` replaces an earlier relay's files (never `index.html`) when moving to a newer Strata. - Since 0.5.1 the page starts in **3D**, as a desktop `Grid3DView` game does: the relay's scripts and engine load at once, alongside pygbag, and the 2D canvas stays on screen until the 3D view is drawing the game. If 3D can't start (no WebGL 2, a file missing, too big, the engine failed), the 2D view stays, the button reads *3D unavailable* and a note under it says why in plain words. Which view a page starts in: `?view=2d` or `?view=3d` in the address (for testing and sharing; not remembered), else the player's last choice on the button (kept in `localStorage`; a stored 2D wins over the default), else the game's default, which `templatePath(defaultView="2d")` makes 2D. A page that starts in 2D downloads nothing of the 3D view (not even the relay's three small scripts) until the button is pressed. `grid3d.web.wants3D()` tells the game 3D is on and the relay's scripts are in, so `Grid3DWebView.open()` can begin, and `set3D(False, reason)` turns it off. - **Too slow: back to 2D.** Since 0.5.3, when the 3D view stays slow once the game is drawing in it, the page goes back to 2D and the note says why in plain words ("this device draws the 3D view too slowly"). Strata's kit first gives up pixel density (down to 1) and then its quality tier; only once it has nothing left to give up, and the drawing itself stays slow for 5 seconds, does the page switch: second by second, the typical frame (the median time between the page's frames) is over 66 ms, the relay's own drawing (its `stats()` `cpuMs`) is at least a quarter of it, and the kit's own average frame (`frameMs`) is over 66 ms too. A game that stops the page now and then (building and sending a board in Python) makes a few long gaps, not a slow typical frame, and a game that is slow every frame while the drawing is cheap wouldn't be helped by 2D, so neither switches. Counting starts 3 seconds after the game's first message to the 3D view, so pygbag's boot and the first shader compile aren't counted, and stops while the tab is hidden. The switch isn't remembered as the player's choice: the button still offers 3D, and once the player chooses 3D again the page leaves it alone until it is reloaded. `?slow=0` in the address turns the switch off (for testing on a machine that draws in software). `Graphik3D.slowed()` in the page says it happened, and `Graphik3D.speed()` gives the last second's readings. -- The button sits in the page's top right corner. `grid3d.web.buttonArea()` gives its `(x, y, width, height)` in CSS pixels, the units of the web view's labels and panels, so a HUD can keep text out from under it (`None` outside a browser). The page never scrolls (`overflow: hidden`), so a phone's browser can't widen it to fit pygbag's 50000-pixel measuring element and push the button off screen, and its one viewport tag sets `width=device-width` (pygbag 0.9.3's default page has a second one that overrides it). Strata's own loading and failure overlay is hidden, so it never covers the 2D game. +- The button sits in the page's top right corner. Since 0.5.3 it is a switch with both views on it, *2D* and *3D*, the one on show lit, so it reads as a choice rather than as a status; to a screen reader it is a toggle named "3D view" (`aria-pressed` while 3D is on), and it is at least 44 CSS pixels each way. `grid3d.web.buttonArea()` gives its `(x, y, width, height)` in CSS pixels, the units of the web view's labels and panels, so a HUD can keep text out from under it (`None` outside a browser). The page never scrolls (`overflow: hidden`), so a phone's browser can't widen it to fit pygbag's 50000-pixel measuring element and push the button off screen, and its one viewport tag sets `width=device-width` (pygbag 0.9.3's default page has a second one that overrides it). Strata's own loading and failure overlay is hidden, so it never covers the 2D game. In a game's `browser.yml`, where graphik is installed into `src/` for pygbag: diff --git a/docs/grid3d.md b/docs/grid3d.md index aef910a..c591a57 100644 --- a/docs/grid3d.md +++ b/docs/grid3d.md @@ -338,6 +338,10 @@ the game's own pauses don't count); the latter is not remembered, the button brings 3D back, and `?slow=0` in the address turns it off. +The button is a switch showing both views, *2D* and *3D*, with the one on +show lit: a toggle named "3D view", `aria-pressed` while 3D is on, at least +44 CSS pixels each way. `buttonArea()` measures it as drawn. + ## The wire format The messages `Grid3DWebView` sends, as functions: Strata's diff --git a/src/main/python/preponderous/graphik/grid3d/templates/pygbag.tmpl b/src/main/python/preponderous/graphik/grid3d/templates/pygbag.tmpl index 4c11a0d..538e109 100644 --- a/src/main/python/preponderous/graphik/grid3d/templates/pygbag.tmpl +++ b/src/main/python/preponderous/graphik/grid3d/templates/pygbag.tmpl @@ -429,7 +429,6 @@ frameborder="1" -