From 731463c65dd538eb6cda5ad7fbde27095c42f22b Mon Sep 17 00:00:00 2001 From: Daniel McCoy Stephenson Date: Fri, 20 Nov 2026 18:30:03 -0700 Subject: [PATCH 01/10] refactor(grid3d): the views' pure halves are moved into model and core modules The parts of view.py and web.py that touch nothing outside Python were moved, nearly verbatim, into their own modules: - errors.py: Unavailable - geometry.py: ViewGeometry, with the sun direction and near/far planes both views send to Strata - wire.py: the grid relay's wire format 1.0 (encoders, decode, readHeader, WireError, limits), byte for byte as before - events.py: the event types, Event, pygameKey and toPygameEvents - state.py: ViewState, the board, pieces, animator and HUD that Grid3DView and Grid3DWebView each kept in their own copy; each view now calls its steps in the order it did before view.py and web.py re-export every name they had, as the same objects, so grid3d.view and grid3d.web import as before. No behaviour was changed. 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/errors.py | 5 + .../preponderous/graphik/grid3d/events.py | 111 ++++ .../preponderous/graphik/grid3d/geometry.py | 63 +++ .../preponderous/graphik/grid3d/state.py | 65 +++ .../preponderous/graphik/grid3d/view.py | 105 +--- .../python/preponderous/graphik/grid3d/web.py | 522 +++--------------- .../preponderous/graphik/grid3d/wire.py | 305 ++++++++++ 7 files changed, 637 insertions(+), 539 deletions(-) create mode 100644 src/main/python/preponderous/graphik/grid3d/errors.py create mode 100644 src/main/python/preponderous/graphik/grid3d/events.py create mode 100644 src/main/python/preponderous/graphik/grid3d/geometry.py create mode 100644 src/main/python/preponderous/graphik/grid3d/state.py create mode 100644 src/main/python/preponderous/graphik/grid3d/wire.py diff --git a/src/main/python/preponderous/graphik/grid3d/errors.py b/src/main/python/preponderous/graphik/grid3d/errors.py new file mode 100644 index 0000000..56d4208 --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/errors.py @@ -0,0 +1,5 @@ +"""Errors a grid3d view raises for a reason a player can act on.""" + + +class Unavailable(Exception): + """The 3D view can't run here. The message says why, in plain words.""" diff --git a/src/main/python/preponderous/graphik/grid3d/events.py b/src/main/python/preponderous/graphik/grid3d/events.py new file mode 100644 index 0000000..624d34c --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/events.py @@ -0,0 +1,111 @@ +"""Input events: Strata's event types, the relay's Event, and pygame +events made from either, so a game's 2D input handling works unchanged in +3D. Pure Python; pygame is passed in, never imported. web.py re-exports +every name. +""" + +from types import SimpleNamespace + +# Strata's event types (strata.h) and the web relay's additions. +EVENT_QUIT, EVENT_KEY_DOWN, EVENT_KEY_UP = 1, 2, 3 +EVENT_MOUSE_MOTION, EVENT_MOUSE_BUTTON_DOWN, EVENT_MOUSE_BUTTON_UP = 4, 5, 6 +EVENT_MOUSE_WHEEL, EVENT_RESIZED, EVENT_TEXT_INPUT = 7, 8, 9 +EVENT_FINGER_DOWN, EVENT_FINGER_UP, EVENT_FINGER_MOTION, EVENT_FINGER_CANCELED = 16, 17, 18, 19 + +# Stands in for the strata module where games read event types from it +# (view.strata.EVENT_QUIT), so the same loop reads desktop and web events. +EVENTS = SimpleNamespace( + EVENT_QUIT=EVENT_QUIT, EVENT_KEY_DOWN=EVENT_KEY_DOWN, EVENT_KEY_UP=EVENT_KEY_UP, + EVENT_MOUSE_MOTION=EVENT_MOUSE_MOTION, EVENT_MOUSE_BUTTON_DOWN=EVENT_MOUSE_BUTTON_DOWN, + EVENT_MOUSE_BUTTON_UP=EVENT_MOUSE_BUTTON_UP, EVENT_MOUSE_WHEEL=EVENT_MOUSE_WHEEL, + EVENT_RESIZED=EVENT_RESIZED, EVENT_TEXT_INPUT=EVENT_TEXT_INPUT, + EVENT_FINGER_DOWN=EVENT_FINGER_DOWN, EVENT_FINGER_UP=EVENT_FINGER_UP, + EVENT_FINGER_MOTION=EVENT_FINGER_MOTION, EVENT_FINGER_CANCELED=EVENT_FINGER_CANCELED, +) + +class Event: + """A Strata-style event (the fields of strata.h's StrataEvent, plus the + web's pointer, id, nx, ny for touch and the browser's key).""" + + __slots__ = ("type", "scancode", "modifiers", "repeat", "button", "width", "height", + "x", "y", "dx", "dy", "text", "pointer", "id", "nx", "ny", "key", "pressure") + + def __init__(self, d): + for name in self.__slots__: + setattr(self, name, d.get(name, "" if name in ("text", "pointer", "key") else 0)) + + def __repr__(self): + return "Event(%s)" % ", ".join( + "%s=%r" % (n, getattr(self, n)) for n in self.__slots__ if getattr(self, n)) + +# -- pygame events, so a game's 2D handlers work in 3D + +# USB HID usage id -> pygame key name (pygame.key.key_code takes these). +_KEY_NAMES = {40: "return", 41: "escape", 42: "backspace", 43: "tab", 44: "space", 45: "-", 46: "=", + 47: "[", 48: "]", 49: "\\", 51: ";", 52: "'", 53: "`", 54: ",", 55: ".", 56: "/", + 74: "home", 75: "page up", 76: "delete", 77: "end", 78: "page down", + 79: "right", 80: "left", 81: "down", 82: "up", + 224: "left ctrl", 225: "left shift", 226: "left alt", 227: "left meta", + 228: "right ctrl", 229: "right shift", 230: "right alt", 231: "right meta"} +_KEY_NAMES.update({4 + i: chr(97 + i) for i in range(26)}) +_KEY_NAMES.update({30 + i: str((i + 1) % 10) for i in range(10)}) +_KEY_NAMES.update({58 + i: "f%d" % (i + 1) for i in range(12)}) +# SDL3 modifier bits; pygame's KMOD_* (SDL2's) use the same bits for these. +_MODS = (0x1, 0x2, 0x40, 0x80, 0x100, 0x200, 0x400, 0x800, 0x1000, 0x2000) + + +def pygameKey(scancode, pygame): + """The pygame key constant for a Strata (USB HID) scancode, or 0.""" + name = _KEY_NAMES.get(scancode) + try: + return pygame.key.key_code(name) if name else 0 + except (ValueError, AttributeError): + return 0 + + +def toPygameEvents(events, pygame, keys=False, pointer=True, fingers=True): + """pygame events for relay (or desktop Strata) events: KEYDOWN, KEYUP and + TEXTINPUT; MOUSEBUTTONDOWN/UP, MOUSEMOTION and MOUSEWHEEL; FINGERDOWN, + FINGERUP and FINGERMOTION (a cancelled finger is a FINGERUP); and + VIDEORESIZE. Keys are off by default: under pygbag, pygame's own SDL + already gets them (it listens on the whole page), so posting them too + would double every key. The pointer is on: the relay's canvas covers + pygame's, so its mouse and touch never reach SDL.""" + out = [] + for e in events: + t = e.type + kind = getattr(e, "pointer", "") or "" + if keys and t in (EVENT_KEY_DOWN, EVENT_KEY_UP): + mod = 0 + for bit in _MODS: + if getattr(e, "modifiers", 0) & bit: + mod |= bit + key = getattr(e, "key", "") or "" + out.append(pygame.event.Event( + pygame.KEYDOWN if t == EVENT_KEY_DOWN else pygame.KEYUP, + key=pygameKey(e.scancode, pygame), scancode=e.scancode, mod=mod, + unicode=key if len(key) == 1 else "")) + elif keys and t == EVENT_TEXT_INPUT: + out.append(pygame.event.Event(pygame.TEXTINPUT, text=e.text)) + elif pointer and t in (EVENT_MOUSE_BUTTON_DOWN, EVENT_MOUSE_BUTTON_UP): + out.append(pygame.event.Event( + pygame.MOUSEBUTTONDOWN if t == EVENT_MOUSE_BUTTON_DOWN else pygame.MOUSEBUTTONUP, + pos=(int(e.x), int(e.y)), button=e.button, touch=kind == "touch")) + elif pointer and t == EVENT_MOUSE_MOTION: + out.append(pygame.event.Event( + pygame.MOUSEMOTION, pos=(int(e.x), int(e.y)), + rel=(int(getattr(e, "dx", 0)), int(getattr(e, "dy", 0))), + buttons=(0, 0, 0), touch=kind == "touch")) + elif pointer and t == EVENT_MOUSE_WHEEL: + out.append(pygame.event.Event(pygame.MOUSEWHEEL, x=e.x, y=e.y, flipped=False)) + elif fingers and t in (EVENT_FINGER_DOWN, EVENT_FINGER_UP, EVENT_FINGER_MOTION, + EVENT_FINGER_CANCELED): + fingerKind = {EVENT_FINGER_DOWN: pygame.FINGERDOWN, + EVENT_FINGER_MOTION: pygame.FINGERMOTION}.get(t, pygame.FINGERUP) + out.append(pygame.event.Event( + fingerKind, x=e.nx, y=e.ny, dx=getattr(e, "dx", 0), dy=getattr(e, "dy", 0), + finger_id=e.id, touch_id=0, pressure=getattr(e, "pressure", 0) or 1.0)) + elif t == EVENT_RESIZED: + out.append(pygame.event.Event(pygame.VIDEORESIZE, size=(e.width, e.height), + w=e.width, h=e.height)) + return out diff --git a/src/main/python/preponderous/graphik/grid3d/geometry.py b/src/main/python/preponderous/graphik/grid3d/geometry.py new file mode 100644 index 0000000..2a2c9ec --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/geometry.py @@ -0,0 +1,63 @@ +"""Where things are on screen for a 3D grid view: insets, the camera that +fits the board between them, picking and projection. Shared by Grid3DView +and Grid3DWebView, with the projection and sun both send to Strata. Pure +Python: no Strata, no pygame. +""" + +from .pick import cellScreenPosition, pickCell, projectToScreen + +# Grid3DView's lighting and projection, sent with every VIEW so the relay +# draws what the desktop draws. +SUN_DIRECTION = (-0.45, 0.85, 0.35) +NEAR_PLANE, FAR_PLANE = 0.3, 200.0 + + +class ViewGeometry: + """Where things are on screen, for a view with `board`, `width` and + `height` (Grid3DView and Grid3DWebView).""" + + # pixels at the top and bottom of the window kept clear of the board + # (setInsets); None for fitCamera's own framing + insets = None + + def setInsets(self, top=None, bottom=None): + """Keeps `top` pixels at the top of the window (a HUD) and `bottom` + at the bottom (a bar of touch keys) clear of the board: the camera + fits the board in the space between. None for both (the default) + frames the board as fitCamera does for the window's shape. Returns + whether anything changed.""" + insets = None if top is None and bottom is None else (top or 0, bottom or 0) + if insets == self.insets: + return False + self.insets = insets + return True + + def insetFractions(self): + """(top, bottom) as fractions of the window's height, or (None, + None) when no insets are set.""" + if self.insets is None or not self.height: + return None, None + top, bottom = self.insets + return top / float(self.height), bottom / float(self.height) + + def camera(self): + """The camera the current board is drawn with at this window size.""" + if self.board is None: + raise RuntimeError("setBoard() must come before the camera") + top, bottom = self.insetFractions() + return self.board.camera(self.width / float(self.height), top=top, bottom=bottom) + + def pickCell(self, x, y): + """The board (column, row) under window pixel (x, y), or None.""" + if self.board is None: + return None + return pickCell(self.camera(), self.board, x, y, self.width, self.height) + + def projectToScreen(self, point): + """Where world point (x, y, z) lands in the window, or None.""" + return projectToScreen(self.camera(), point, self.width, self.height) + + def cellScreenPosition(self, column, row, y=0.0): + """Where the middle of a cell, `y` above the bed, lands in the window.""" + return cellScreenPosition(self.camera(), self.board, column, row, + self.width, self.height, y) diff --git a/src/main/python/preponderous/graphik/grid3d/state.py b/src/main/python/preponderous/graphik/grid3d/state.py new file mode 100644 index 0000000..e95bf99 --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/state.py @@ -0,0 +1,65 @@ +"""What a 3D grid view shows, kept between frames: the board, its tint and +lights, the tick's pieces sliding on an Animator, and the HUD. The half of +Grid3DView and Grid3DWebView that doesn't depend on how they draw: each +view calls these steps in its own order and adds its own drawing. Pure +Python: no Strata, no pygame. +""" + +import time + +from .animate import Animator +from .geometry import ViewGeometry + + +class ViewState(ViewGeometry): + """A view's board, pieces and HUD at a window size, on a clock.""" + + def __init__(self, width, height, reducedMotion=False, clock=time.monotonic): + self.width, self.height = width, height + self.reducedMotion = reducedMotion + self.clock = clock + self.board = None + self.boardTint = None + self.boardLights = [] + self.pieces = [] + self.labels, self.panels = [], [] + self.animator = None + + def placeBoard(self, board, tint=None, lights=()): + """The static part, kept: setBoard's first step.""" + self.board = board + self.boardTint = tint + self.boardLights = list(lights) + + def restartAnimator(self): + """A new Animator for the board, the current pieces on their cells.""" + self.animator = Animator(self.board.cellCenter, reducedMotion=self.reducedMotion) + self.animator.update(self.pieces, self.clock(), 0.0) + + def checkedPieces(self, pieces): + """`pieces` as a list, once the board is set and they all fit on it.""" + if self.board is None: + raise RuntimeError("setBoard() must come before setPieces()") + pieces = list(pieces) + self.board.checkPieces(pieces) + return pieces + + def movePieces(self, pieces, tickSeconds=0.0, snap=False): + """Keeps this tick's (checked) pieces and starts their slides now.""" + self.pieces = pieces + self.animator.update(pieces, self.clock(), tickSeconds, snap=snap) + + def placeLabels(self, labels=(), panels=()): + """Screen text and the panels behind it, kept.""" + self.labels, self.panels = list(labels), list(panels) + + def scene(self, now=None): + """The Scene a frame at `now` would draw (for tests and tools).""" + if self.board is None: + raise RuntimeError("setBoard() must come before drawing") + now = self.clock() if now is None else now + top, bottom = self.insetFractions() + return self.board.scene(self.pieces, positions=self.animator.positions(now), + labels=self.labels, panels=self.panels, lights=self.boardLights, + aspect=self.width / float(self.height), tint=self.boardTint, + top=top, bottom=bottom) diff --git a/src/main/python/preponderous/graphik/grid3d/view.py b/src/main/python/preponderous/graphik/grid3d/view.py index 4b249d1..0d273ff 100644 --- a/src/main/python/preponderous/graphik/grid3d/view.py +++ b/src/main/python/preponderous/graphik/grid3d/view.py @@ -33,8 +33,9 @@ import sys import time -from .animate import Animator -from .pick import cellScreenPosition, pickCell, projectToScreen +from .errors import Unavailable +from .geometry import FAR_PLANE, NEAR_PLANE, SUN_DIRECTION, ViewGeometry # noqa: F401 +from .state import ViewState STRATA_VERSION = "0.8.0" STRATA_PLATFORMS = ("linux", "win32") @@ -74,10 +75,6 @@ def labelBytes(text): 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.""" - - def loadStrata(platform=None): """Import the binding and load libstrata; raise Unavailable if either fails.""" platform = sys.platform if platform is None else platform @@ -100,73 +97,14 @@ def loadStrata(platform=None): raise Unavailable("the Strata library couldn't be loaded: %s" % error) -class ViewGeometry: - """Where things are on screen, for a view with `board`, `width` and - `height` (Grid3DView and Grid3DWebView).""" - - # pixels at the top and bottom of the window kept clear of the board - # (setInsets); None for fitCamera's own framing - insets = None - - def setInsets(self, top=None, bottom=None): - """Keeps `top` pixels at the top of the window (a HUD) and `bottom` - at the bottom (a bar of touch keys) clear of the board: the camera - fits the board in the space between. None for both (the default) - frames the board as fitCamera does for the window's shape. Returns - whether anything changed.""" - insets = None if top is None and bottom is None else (top or 0, bottom or 0) - if insets == self.insets: - return False - self.insets = insets - return True - - def insetFractions(self): - """(top, bottom) as fractions of the window's height, or (None, - None) when no insets are set.""" - if self.insets is None or not self.height: - return None, None - top, bottom = self.insets - return top / float(self.height), bottom / float(self.height) - - def camera(self): - """The camera the current board is drawn with at this window size.""" - if self.board is None: - raise RuntimeError("setBoard() must come before the camera") - top, bottom = self.insetFractions() - return self.board.camera(self.width / float(self.height), top=top, bottom=bottom) - - def pickCell(self, x, y): - """The board (column, row) under window pixel (x, y), or None.""" - if self.board is None: - return None - return pickCell(self.camera(), self.board, x, y, self.width, self.height) - - def projectToScreen(self, point): - """Where world point (x, y, z) lands in the window, or None.""" - return projectToScreen(self.camera(), point, self.width, self.height) - - def cellScreenPosition(self, column, row, y=0.0): - """Where the middle of a cell, `y` above the bed, lands in the window.""" - return cellScreenPosition(self.camera(), self.board, column, row, - self.width, self.height, y) - - -class Grid3DView(ViewGeometry): +class Grid3DView(ViewState): """One Strata engine (a window, or headless for screenshots and tests).""" def __init__(self, strata, lib, engine, width, height, isWindow, reducedMotion=False, clock=time.monotonic): + ViewState.__init__(self, width, height, reducedMotion=reducedMotion, clock=clock) self.strata, self.lib, self.engine = strata, lib, engine - self.width, self.height = width, height self.isWindow = isWindow - self.reducedMotion = reducedMotion - self.clock = clock - self.board = None - self.boardTint = None - self.boardLights = [] - self.pieces = [] - self.labels, self.panels = [], [] - self.animator = None self.EVENT_QUIT = strata.EVENT_QUIT self.EVENT_KEY_DOWN = strata.EVENT_KEY_DOWN self.EVENT_KEY_UP = strata.EVENT_KEY_UP @@ -211,43 +149,18 @@ def open(cls, width=900, height=700, title="graphik", headless=False, def setBoard(self, board, tint=None, lights=()): """The static part: call when the board, its theme or its tint changes.""" - self.board = board - self.boardTint = tint - self.boardLights = list(lights) - self.animator = Animator(board.cellCenter, reducedMotion=self.reducedMotion) - self.animator.update(self.pieces, self.clock(), 0.0) + self.placeBoard(board, tint, lights) + self.restartAnimator() def setPieces(self, pieces, tickSeconds=0.0, snap=False): """The dynamic part: call once per game tick. Pieces slide from where they were drawn to their new cells over `tickSeconds`; `snap=True` (a restart, a new level) puts them all straight on their cells.""" - if self.board is None: - raise RuntimeError("setBoard() must come before setPieces()") - pieces = list(pieces) - self.board.checkPieces(pieces) - self.pieces = pieces - self.animator.update(pieces, self.clock(), tickSeconds, snap=snap) + self.movePieces(self.checkedPieces(pieces), tickSeconds, snap) def setLabels(self, labels=(), panels=()): """Screen text and the panels behind it.""" - self.labels, self.panels = list(labels), list(panels) - - def scene(self, now=None): - """The Scene a frame at `now` would draw (for tests and tools).""" - if self.board is None: - raise RuntimeError("setBoard() must come before drawing") - now = self.clock() if now is None else now - return self.board.scene( - self.pieces, - positions=self.animator.positions(now), - labels=self.labels, - panels=self.panels, - lights=self.boardLights, - aspect=self.width / float(self.height), - tint=self.boardTint, - top=self.insetFractions()[0], - bottom=self.insetFractions()[1], - ) + self.placeLabels(labels, panels) def frame(self, now=None, present=True): """Draw one frame (pieces at their positions for `now`).""" diff --git a/src/main/python/preponderous/graphik/grid3d/web.py b/src/main/python/preponderous/graphik/grid3d/web.py index 827cca2..e2924ed 100644 --- a/src/main/python/preponderous/graphik/grid3d/web.py +++ b/src/main/python/preponderous/graphik/grid3d/web.py @@ -41,80 +41,85 @@ Pure Python (struct, base64, json); pygbag's `platform` only in a browser. """ - import base64 import json -import math import os -import struct import sys import tempfile import time -from types import SimpleNamespace - -from .animate import Animator -from .scene import CLEAR_COLOR, checkLights -from .view import ViewGeometry, Unavailable - -WIRE_MAJOR, WIRE_MINOR = 1, 0 -MAGIC = b"G3" -BOARD, PIECES, HUD, VIEW = 1, 2, 3, 4 -KINDS = (BOARD, PIECES, HUD, VIEW) -WORLD, PIECE, BRIDGE = 0, 1, 2 - -HEADER = struct.Struct("<2sBBBBH") # 8 bytes -SHAPE = 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 _worldShapes(shapes): - """The shapes' records for BOARD in one pass, the relay's checks made on - all of them at once (a board is a few thousand shapes, encoded whenever - the game builds its scene); None when one fails, or has a 3-part colour, - so _shape() finds it and says what is wrong.""" - places = [v for s in shapes for v in (*s.position, *s.scale)] - colors = [v for s in shapes for v in s.color] - if len(colors) != 4 * len(shapes): - return None - # sum() is NaN or infinite when any value is - if places and not (max(map(abs, places)) <= MAX_COORDINATE and math.isfinite(sum(places))): - return None - if colors and not (max(map(abs, colors)) <= _FLOAT_MAX and math.isfinite(sum(colors))): - return None - pack = SHAPE.pack - try: - return [pack(s.kind, WORLD, 0, 0, 0, *s.position, *s.scale, *s.color) for s in shapes] - except struct.error: - return None - - -def encodeBoard(shapes, lights=()): - """BOARD: world shapes and lights.""" - _checkCounts(len(shapes), lights) - out = [header(BOARD), COUNTS.pack(len(shapes), len(lights))] - fast = _worldShapes(shapes) - out += fast if fast is not None else [ - _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] - return b"".join(out) - - -def _labelText(text): - # 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 - - -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: - _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) - _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 - ) - - -def encodePieces(board, pieces, tracks, tickSeconds): - """PIECES for this tick. `tracks` maps a piece id to ((x0, z0), (x1, z1)), - 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. - alone, glow = board.pieceShapes([piece], positions={piece.id: end}) - for s in alone: - x, y, z = s.position - shapes.append(_shape(s.kind, PIECE, i, 0, (x - end[0], y, z - end[1]), s.scale, s.color)) - lights += [_light(PIECE, i, light, end) for light in glow] - # Chain bridges, in pieceShapes' order. Each is drawn with both ends at - # the origin, which gives its size across; the relay spans the anchors. - 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) - - -def readHeader(message): - """(major, minor, kind) of a message, or WireError as the relay would - refuse it: not a relay message, another major version, truncated.""" - if len(message) < 2 or bytes(message[:2]) != MAGIC: - raise WireError(-1) - if len(message) < 3: - raise WireError(-3, "no version") - if message[2] != WIRE_MAJOR: - major = message[2] - minor = message[3] if len(message) > 3 else 0 - raise WireError(-2, "wire format %d.%d; this reads %d.x" % (major, minor, WIRE_MAJOR)) - if len(message) < HEADER.size: - raise WireError(-3, "header") - _, major, minor, kind, _, _ = HEADER.unpack_from(message) - if kind not in KINDS: - raise WireError(-4, "kind %d" % kind) - return major, minor, kind - - -def decode(message): - """A message read back as (kind, contents): for tests and tools, with - the relay's checks (version, kind, counts against the length). A minor - version above 0 may carry fields after the ones 1.0 knows; they are - ignored, as the relay ignores them.""" - _, _, kind = readHeader(message) - body = memoryview(message)[HEADER.size:] - - def take(fmt, offset, count=1): - end = offset + fmt.size * count - if end > len(body): - raise WireError(-3, "kind %d" % kind) - return [fmt.unpack_from(body, offset + fmt.size * i) for i in range(count)], end - - def shape(r): - return {"kind": r[0], "attach": r[1], "a": r[2], "b": r[3], - "position": r[5:8], "scale": r[8:11], "color": r[11:15]} - - def light(r): - return {"attach": r[0], "castShadows": bool(r[1] & 1), "a": r[2], - "position": r[3:6], "color": r[6:9], "radius": r[9], "intensity": r[10]} - - if kind == BOARD: - (counts,), at = take(COUNTS, 0) - shapes, at = take(SHAPE, at, counts[0]) - lights, at = take(LIGHT, at, counts[1]) - return kind, {"shapes": [shape(r) for r in shapes], "lights": [light(r) for r in lights]} - if kind == PIECES: - (head,), at = take(PIECES_HEAD, 0) - anchors, at = take(ANCHOR, at, head[1]) - shapes, at = take(SHAPE, at, head[2]) - lights, at = take(LIGHT, at, head[3]) - return kind, {"tickSeconds": head[0], "anchors": [tuple(a) for a in anchors], - "shapes": [shape(r) for r in shapes], "lights": [light(r) for r in lights]} - if kind == HUD: - (counts,), at = take(COUNTS, 0) - panels, at = take(PANEL, at, counts[0]) - labels = [] - for _ in range(counts[1]): - (r,), at = take(LABEL, at) - length = r[7] - if at + length > len(body): - raise WireError(-3, "label text") - text = bytes(body[at:at + length]).decode("utf-8") - at += length + (-length % 4) - labels.append({"x": r[0], "y": r[1], "pixelSize": r[2], "color": r[3:7], "text": text}) - return kind, {"panels": [{"rect": p[:4], "color": p[4:8]} for p in panels], "labels": labels} - (r,), _ = take(VIEW_BODY, 0) - return kind, {"eye": r[0:3], "target": r[3:6], "fovDegrees": r[6], "near": r[7], "far": r[8], - "clearColor": r[9:13], "sun": r[13:16]} - - # -- transports @@ -545,23 +295,7 @@ def set3D(on, reason=""): # -- the view -class Event: - """A Strata-style event (the fields of strata.h's StrataEvent, plus the - web's pointer, id, nx, ny for touch and the browser's key).""" - - __slots__ = ("type", "scancode", "modifiers", "repeat", "button", "width", "height", - "x", "y", "dx", "dy", "text", "pointer", "id", "nx", "ny", "key", "pressure") - - def __init__(self, d): - for name in self.__slots__: - setattr(self, name, d.get(name, "" if name in ("text", "pointer", "key") else 0)) - - def __repr__(self): - return "Event(%s)" % ", ".join( - "%s=%r" % (n, getattr(self, n)) for n in self.__slots__ if getattr(self, n)) - - -class Grid3DWebView(ViewGeometry): +class Grid3DWebView(ViewState): """Grid3DView's calls (setBoard, setPieces, setLabels, frame, drawScene, pollEvents, resize, close, pickCell), drawn by the page's grid relay.""" @@ -569,18 +303,10 @@ class Grid3DWebView(ViewGeometry): EVENT_QUIT, EVENT_KEY_DOWN, EVENT_KEY_UP, EVENT_RESIZED) def __init__(self, relay, width, height, reducedMotion=False, clock=time.monotonic): + ViewState.__init__(self, width, height, reducedMotion=reducedMotion, clock=clock) self.relay = relay self.strata = EVENTS - self.width, self.height = width, height self.isWindow = True - self.reducedMotion = reducedMotion - self.clock = clock - self.board = None - self.boardTint = None - self.boardLights = [] - self.pieces = [] - self.labels, self.panels = [], [] - self.animator = None self.sent = 0 self.lastSent = {} # kind -> the last message of that kind (drawScene) @@ -619,12 +345,9 @@ def _send(self, message, kind=None): def setBoard(self, board, tint=None, lights=()): """The static part: call when the board, its theme or its tint changes.""" - self.board = board - self.boardTint = tint - self.boardLights = list(lights) + self.placeBoard(board, tint, lights) checkLights(self.boardLights) - self.animator = Animator(board.cellCenter, reducedMotion=self.reducedMotion) - self.animator.update(self.pieces, self.clock(), 0.0) + self.restartAnimator() message = encodeBoard(board.boardShapes(tint), self.boardLights) if self.lastSent.get(BOARD) != message: # the relay has it already self._send(message, BOARD) @@ -633,33 +356,18 @@ def setBoard(self, board, tint=None, lights=()): def setPieces(self, pieces, tickSeconds=0.0, snap=False): """The dynamic part: call once per game tick (see Grid3DView).""" - if self.board is None: - raise RuntimeError("setBoard() must come before setPieces()") - pieces = list(pieces) - self.board.checkPieces(pieces) + pieces = self.checkedPieces(pieces) _, lights = self.board.pieceShapes(pieces) checkLights(self.boardLights + lights) - self.pieces = pieces - self.animator.update(pieces, self.clock(), tickSeconds, snap=snap) + self.movePieces(pieces, tickSeconds, snap) tick = 0.0 if snap else self.animator.tickSeconds self._send(encodePieces(self.board, pieces, self.animator.tracks, tick), PIECES) def setLabels(self, labels=(), panels=()): """Screen text and the panels behind it.""" - self.labels, self.panels = list(labels), list(panels) + self.placeLabels(labels, panels) self._send(encodeHud(self.labels, self.panels), HUD) - def scene(self, now=None): - """The Scene a desktop view would draw at `now` (for tests and tools).""" - if self.board is None: - raise RuntimeError("setBoard() must come before drawing") - now = self.clock() if now is None else now - top, bottom = self.insetFractions() - return self.board.scene(self.pieces, positions=self.animator.positions(now), - labels=self.labels, panels=self.panels, lights=self.boardLights, - aspect=self.width / float(self.height), tint=self.boardTint, - top=top, bottom=bottom) - def frame(self, now=None, present=True): """Nothing to do per frame: the relay draws on the page's own frames.""" @@ -722,75 +430,3 @@ def bridgePairs(pieces): _NO_BOARD = _NoBoard() - -# -- pygame events, so a game's 2D handlers work in 3D - -# USB HID usage id -> pygame key name (pygame.key.key_code takes these). -_KEY_NAMES = {40: "return", 41: "escape", 42: "backspace", 43: "tab", 44: "space", 45: "-", 46: "=", - 47: "[", 48: "]", 49: "\\", 51: ";", 52: "'", 53: "`", 54: ",", 55: ".", 56: "/", - 74: "home", 75: "page up", 76: "delete", 77: "end", 78: "page down", - 79: "right", 80: "left", 81: "down", 82: "up", - 224: "left ctrl", 225: "left shift", 226: "left alt", 227: "left meta", - 228: "right ctrl", 229: "right shift", 230: "right alt", 231: "right meta"} -_KEY_NAMES.update({4 + i: chr(97 + i) for i in range(26)}) -_KEY_NAMES.update({30 + i: str((i + 1) % 10) for i in range(10)}) -_KEY_NAMES.update({58 + i: "f%d" % (i + 1) for i in range(12)}) -# SDL3 modifier bits; pygame's KMOD_* (SDL2's) use the same bits for these. -_MODS = (0x1, 0x2, 0x40, 0x80, 0x100, 0x200, 0x400, 0x800, 0x1000, 0x2000) - - -def pygameKey(scancode, pygame): - """The pygame key constant for a Strata (USB HID) scancode, or 0.""" - name = _KEY_NAMES.get(scancode) - try: - return pygame.key.key_code(name) if name else 0 - except (ValueError, AttributeError): - return 0 - - -def toPygameEvents(events, pygame, keys=False, pointer=True, fingers=True): - """pygame events for relay (or desktop Strata) events: KEYDOWN, KEYUP and - TEXTINPUT; MOUSEBUTTONDOWN/UP, MOUSEMOTION and MOUSEWHEEL; FINGERDOWN, - FINGERUP and FINGERMOTION (a cancelled finger is a FINGERUP); and - VIDEORESIZE. Keys are off by default: under pygbag, pygame's own SDL - already gets them (it listens on the whole page), so posting them too - would double every key. The pointer is on: the relay's canvas covers - pygame's, so its mouse and touch never reach SDL.""" - out = [] - for e in events: - t = e.type - kind = getattr(e, "pointer", "") or "" - if keys and t in (EVENT_KEY_DOWN, EVENT_KEY_UP): - mod = 0 - for bit in _MODS: - if getattr(e, "modifiers", 0) & bit: - mod |= bit - key = getattr(e, "key", "") or "" - out.append(pygame.event.Event( - pygame.KEYDOWN if t == EVENT_KEY_DOWN else pygame.KEYUP, - key=pygameKey(e.scancode, pygame), scancode=e.scancode, mod=mod, - unicode=key if len(key) == 1 else "")) - elif keys and t == EVENT_TEXT_INPUT: - out.append(pygame.event.Event(pygame.TEXTINPUT, text=e.text)) - elif pointer and t in (EVENT_MOUSE_BUTTON_DOWN, EVENT_MOUSE_BUTTON_UP): - out.append(pygame.event.Event( - pygame.MOUSEBUTTONDOWN if t == EVENT_MOUSE_BUTTON_DOWN else pygame.MOUSEBUTTONUP, - pos=(int(e.x), int(e.y)), button=e.button, touch=kind == "touch")) - elif pointer and t == EVENT_MOUSE_MOTION: - out.append(pygame.event.Event( - pygame.MOUSEMOTION, pos=(int(e.x), int(e.y)), - rel=(int(getattr(e, "dx", 0)), int(getattr(e, "dy", 0))), - buttons=(0, 0, 0), touch=kind == "touch")) - elif pointer and t == EVENT_MOUSE_WHEEL: - out.append(pygame.event.Event(pygame.MOUSEWHEEL, x=e.x, y=e.y, flipped=False)) - elif fingers and t in (EVENT_FINGER_DOWN, EVENT_FINGER_UP, EVENT_FINGER_MOTION, - EVENT_FINGER_CANCELED): - fingerKind = {EVENT_FINGER_DOWN: pygame.FINGERDOWN, - EVENT_FINGER_MOTION: pygame.FINGERMOTION}.get(t, pygame.FINGERUP) - out.append(pygame.event.Event( - fingerKind, x=e.nx, y=e.ny, dx=getattr(e, "dx", 0), dy=getattr(e, "dy", 0), - finger_id=e.id, touch_id=0, pressure=getattr(e, "pressure", 0) or 1.0)) - elif t == EVENT_RESIZED: - out.append(pygame.event.Event(pygame.VIDEORESIZE, size=(e.width, e.height), - w=e.width, h=e.height)) - return out diff --git a/src/main/python/preponderous/graphik/grid3d/wire.py b/src/main/python/preponderous/graphik/grid3d/wire.py new file mode 100644 index 0000000..d5f7371 --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/wire.py @@ -0,0 +1,305 @@ +"""The grid relay's wire format: Strata's web/kit/grid-relay/WIRE.md, format 1.0. + +The messages Grid3DWebView sends to the page's relay, as pure functions: +BOARD, PIECES, HUD and VIEW encoders, and decode() / readHeader() with the +relay's own checks, for tests and tools. The encoders are held to golden +bytes (golden/wire-1.0.hex) that Strata's relay tests read with its own +parser. Pure Python (struct, math); web.py re-exports every name. +""" + +import math +import struct + +from .geometry import FAR_PLANE, NEAR_PLANE, SUN_DIRECTION +from .scene import CLEAR_COLOR + +WIRE_MAJOR, WIRE_MINOR = 1, 0 +MAGIC = b"G3" +BOARD, PIECES, HUD, VIEW = 1, 2, 3, 4 +KINDS = (BOARD, PIECES, HUD, VIEW) +WORLD, PIECE, BRIDGE = 0, 1, 2 + +HEADER = struct.Struct("<2sBBBBH") # 8 bytes +SHAPE = 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 _worldShapes(shapes): + """The shapes' records for BOARD in one pass, the relay's checks made on + all of them at once (a board is a few thousand shapes, encoded whenever + the game builds its scene); None when one fails, or has a 3-part colour, + so _shape() finds it and says what is wrong.""" + places = [v for s in shapes for v in (*s.position, *s.scale)] + colors = [v for s in shapes for v in s.color] + if len(colors) != 4 * len(shapes): + return None + # sum() is NaN or infinite when any value is + if places and not (max(map(abs, places)) <= MAX_COORDINATE and math.isfinite(sum(places))): + return None + if colors and not (max(map(abs, colors)) <= _FLOAT_MAX and math.isfinite(sum(colors))): + return None + pack = SHAPE.pack + try: + return [pack(s.kind, WORLD, 0, 0, 0, *s.position, *s.scale, *s.color) for s in shapes] + except struct.error: + return None + + +def encodeBoard(shapes, lights=()): + """BOARD: world shapes and lights.""" + _checkCounts(len(shapes), lights) + out = [header(BOARD), COUNTS.pack(len(shapes), len(lights))] + fast = _worldShapes(shapes) + out += fast if fast is not None else [ + _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] + return b"".join(out) + + +def _labelText(text): + # 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 + + +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: + _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) + _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 + ) + + +def encodePieces(board, pieces, tracks, tickSeconds): + """PIECES for this tick. `tracks` maps a piece id to ((x0, z0), (x1, z1)), + 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. + alone, glow = board.pieceShapes([piece], positions={piece.id: end}) + for s in alone: + x, y, z = s.position + shapes.append(_shape(s.kind, PIECE, i, 0, (x - end[0], y, z - end[1]), s.scale, s.color)) + lights += [_light(PIECE, i, light, end) for light in glow] + # Chain bridges, in pieceShapes' order. Each is drawn with both ends at + # the origin, which gives its size across; the relay spans the anchors. + 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) + + +def readHeader(message): + """(major, minor, kind) of a message, or WireError as the relay would + refuse it: not a relay message, another major version, truncated.""" + if len(message) < 2 or bytes(message[:2]) != MAGIC: + raise WireError(-1) + if len(message) < 3: + raise WireError(-3, "no version") + if message[2] != WIRE_MAJOR: + major = message[2] + minor = message[3] if len(message) > 3 else 0 + raise WireError(-2, "wire format %d.%d; this reads %d.x" % (major, minor, WIRE_MAJOR)) + if len(message) < HEADER.size: + raise WireError(-3, "header") + _, major, minor, kind, _, _ = HEADER.unpack_from(message) + if kind not in KINDS: + raise WireError(-4, "kind %d" % kind) + return major, minor, kind + + +def decode(message): + """A message read back as (kind, contents): for tests and tools, with + the relay's checks (version, kind, counts against the length). A minor + version above 0 may carry fields after the ones 1.0 knows; they are + ignored, as the relay ignores them.""" + _, _, kind = readHeader(message) + body = memoryview(message)[HEADER.size:] + + def take(fmt, offset, count=1): + end = offset + fmt.size * count + if end > len(body): + raise WireError(-3, "kind %d" % kind) + return [fmt.unpack_from(body, offset + fmt.size * i) for i in range(count)], end + + def shape(r): + return {"kind": r[0], "attach": r[1], "a": r[2], "b": r[3], + "position": r[5:8], "scale": r[8:11], "color": r[11:15]} + + def light(r): + return {"attach": r[0], "castShadows": bool(r[1] & 1), "a": r[2], + "position": r[3:6], "color": r[6:9], "radius": r[9], "intensity": r[10]} + + if kind == BOARD: + (counts,), at = take(COUNTS, 0) + shapes, at = take(SHAPE, at, counts[0]) + lights, at = take(LIGHT, at, counts[1]) + return kind, {"shapes": [shape(r) for r in shapes], "lights": [light(r) for r in lights]} + if kind == PIECES: + (head,), at = take(PIECES_HEAD, 0) + anchors, at = take(ANCHOR, at, head[1]) + shapes, at = take(SHAPE, at, head[2]) + lights, at = take(LIGHT, at, head[3]) + return kind, {"tickSeconds": head[0], "anchors": [tuple(a) for a in anchors], + "shapes": [shape(r) for r in shapes], "lights": [light(r) for r in lights]} + if kind == HUD: + (counts,), at = take(COUNTS, 0) + panels, at = take(PANEL, at, counts[0]) + labels = [] + for _ in range(counts[1]): + (r,), at = take(LABEL, at) + length = r[7] + if at + length > len(body): + raise WireError(-3, "label text") + text = bytes(body[at:at + length]).decode("utf-8") + at += length + (-length % 4) + labels.append({"x": r[0], "y": r[1], "pixelSize": r[2], "color": r[3:7], "text": text}) + return kind, {"panels": [{"rect": p[:4], "color": p[4:8]} for p in panels], "labels": labels} + (r,), _ = take(VIEW_BODY, 0) + return kind, {"eye": r[0:3], "target": r[3:6], "fovDegrees": r[6], "near": r[7], "far": r[8], + "clearColor": r[9:13], "sun": r[13:16]} From a72d7ee868c2fb3c83455bf425f5935383c4a5ca Mon Sep 17 00:00:00 2001 From: Daniel McCoy Stephenson Date: Fri, 20 Nov 2026 18:31:24 -0700 Subject: [PATCH 02/10] refactor(grid3d): the views' ports are declared, with fakes and contract tests Six ports were added under grid3d/ports/, one interface per file, each with its contract in its doc comment: - SceneRenderer: draw one complete Scene now - EventSource: the input since the last poll - Surface: resize, savePng, close - StrataLoader: open a Strata engine here, or say why not - GridRelay: the page's grid relay (its own six-call JS API) - PageObjects: the page's JS objects by name test_grid3d_ports.py runs each contract against a fake. The same contracts run against the production adapters once they exist (their cases skip until then). No behaviour was changed. 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/ports/__init__.py | 14 + .../graphik/grid3d/ports/event_source.py | 15 + .../graphik/grid3d/ports/grid_relay.py | 42 +++ .../graphik/grid3d/ports/page_objects.py | 15 + .../graphik/grid3d/ports/scene_renderer.py | 19 ++ .../graphik/grid3d/ports/strata_loader.py | 19 ++ .../graphik/grid3d/ports/surface.py | 23 ++ .../graphik/grid3d/test_grid3d_ports.py | 272 ++++++++++++++++++ 8 files changed, 419 insertions(+) create mode 100644 src/main/python/preponderous/graphik/grid3d/ports/__init__.py create mode 100644 src/main/python/preponderous/graphik/grid3d/ports/event_source.py create mode 100644 src/main/python/preponderous/graphik/grid3d/ports/grid_relay.py create mode 100644 src/main/python/preponderous/graphik/grid3d/ports/page_objects.py create mode 100644 src/main/python/preponderous/graphik/grid3d/ports/scene_renderer.py create mode 100644 src/main/python/preponderous/graphik/grid3d/ports/strata_loader.py create mode 100644 src/main/python/preponderous/graphik/grid3d/ports/surface.py create mode 100644 src/test/python/preponderous/graphik/grid3d/test_grid3d_ports.py diff --git a/src/main/python/preponderous/graphik/grid3d/ports/__init__.py b/src/main/python/preponderous/graphik/grid3d/ports/__init__.py new file mode 100644 index 0000000..699fe82 --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/ports/__init__.py @@ -0,0 +1,14 @@ +"""The ports of grid3d's views: what a view needs from the world, one +interface per file. The views (view.py, web.py) are written against these; +adapters/ holds the implementations. Nothing here imports an adapter or a +view, and nothing here loads Strata, pygame or pygbag. +""" + +from .event_source import EventSource +from .grid_relay import GridRelay +from .page_objects import PageObjects +from .scene_renderer import SceneRenderer +from .strata_loader import StrataLoader +from .surface import Surface + +__all__ = ["EventSource", "GridRelay", "PageObjects", "SceneRenderer", "StrataLoader", "Surface"] diff --git a/src/main/python/preponderous/graphik/grid3d/ports/event_source.py b/src/main/python/preponderous/graphik/grid3d/ports/event_source.py new file mode 100644 index 0000000..f6d8351 --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/ports/event_source.py @@ -0,0 +1,15 @@ +from typing import Protocol, runtime_checkable + + +@runtime_checkable +class EventSource(Protocol): + """The input that has arrived since the last poll. + + Returns a list, oldest first, empty when nothing came; never blocks. + The events keep their backend's shape (the desktop binding's own event + objects; the relay's events.Event): both carry Strata's `type` numbers + and fields, which is what games and events.toPygameEvents read. + """ + + def poll(self): + ... diff --git a/src/main/python/preponderous/graphik/grid3d/ports/grid_relay.py b/src/main/python/preponderous/graphik/grid3d/ports/grid_relay.py new file mode 100644 index 0000000..8ddce2a --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/ports/grid_relay.py @@ -0,0 +1,42 @@ +from typing import Protocol, runtime_checkable + + +@runtime_checkable +class GridRelay(Protocol): + """The page's Strata grid relay (window.StrataGridRelay). + + Its own JS API is the contract, as Strata's web/kit/grid-relay + (WIRE.md, grid-relay.js) defines it, so this port keeps all six calls: + + - request(options) asks for the 3D view with a dict of options + ("canvas", "maxBytes", "title") and returns the relay's state; + - state() is "loading", "ready" or "failed:"; + - send(message) takes one wire.py message (bytes) and returns 0, or the + relay's negative status for a refused one (wire.STATUS); + - poll() returns the events since the last poll as dicts of + events.Event's fields, oldest first; + - reducedMotion() is whether the page asks for reduced motion; + - close() stops the relay drawing. + + None of them block. Expected refusals are values (a state string, a + status); exceptions mean a broken page or bridge. Call from the game's + one thread. + """ + + def request(self, options): + ... + + def state(self): + ... + + def send(self, message): + ... + + def poll(self): + ... + + def reducedMotion(self): + ... + + def close(self): + ... diff --git a/src/main/python/preponderous/graphik/grid3d/ports/page_objects.py b/src/main/python/preponderous/graphik/grid3d/ports/page_objects.py new file mode 100644 index 0000000..101b07f --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/ports/page_objects.py @@ -0,0 +1,15 @@ +from typing import Protocol, runtime_checkable + + +@runtime_checkable +class PageObjects(Protocol): + """The page's JS objects, by name. + + get(name) returns window. (the template's Graphik3D, the relay's + StrataGridRelay), or None when there is no page (not in a browser) or no + such object on it. Never raises, never blocks; asked again on every + call, so a page that loads a script later is seen. + """ + + def get(self, name): + ... diff --git a/src/main/python/preponderous/graphik/grid3d/ports/scene_renderer.py b/src/main/python/preponderous/graphik/grid3d/ports/scene_renderer.py new file mode 100644 index 0000000..b0e1faa --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/ports/scene_renderer.py @@ -0,0 +1,19 @@ +from typing import Protocol, runtime_checkable + + +@runtime_checkable +class SceneRenderer(Protocol): + """Draws one complete Scene now. + + `scene` is a scene.Scene whose limits the caller has already checked + (Scene.checkLimits()); `aspect` is the window's width over its height, + for the camera's projection; `present` shows the frame once drawn (a + backend that draws on its own frames, like the page's relay, may ignore + it). Returns nothing. Raises for what the backend refuses (a + wire.WireError from the relay); an Unavailable never comes from here, + only from opening. May block for one frame's drawing. Not thread-safe: + call from the thread that owns the window. + """ + + def draw(self, scene, aspect, present=True): + ... diff --git a/src/main/python/preponderous/graphik/grid3d/ports/strata_loader.py b/src/main/python/preponderous/graphik/grid3d/ports/strata_loader.py new file mode 100644 index 0000000..0829d92 --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/ports/strata_loader.py @@ -0,0 +1,19 @@ +from typing import Protocol, runtime_checkable + + +@runtime_checkable +class StrataLoader(Protocol): + """Opens a Strata engine here, or says in plain words why it can't. + + open(width, height, title, headless) returns a display that is a + SceneRenderer, an EventSource and a Surface at once, with the sun and + lighting the desktop view draws with already set, and with its + binding's `strata`, `lib` and `engine` showing (games read them). It + raises errors.Unavailable with a reason a player can act on: no library + for this system, the binding not installed, the library not loading, no + window or GPU. May block while the binding downloads its library the + first time. Call from the thread that will draw. + """ + + def open(self, width, height, title, headless): + ... diff --git a/src/main/python/preponderous/graphik/grid3d/ports/surface.py b/src/main/python/preponderous/graphik/grid3d/ports/surface.py new file mode 100644 index 0000000..e11c241 --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/ports/surface.py @@ -0,0 +1,23 @@ +from typing import Protocol, runtime_checkable + + +@runtime_checkable +class Surface(Protocol): + """The drawing surface's own life: its size, a snapshot of it, its end. + + resize(width, height) follows a new window size (the camera is the + view's business, not the surface's). savePng(path) writes the last frame + as a PNG, or raises errors.Unavailable where the backend can't (the + browser, whose page takes its own screenshots). close() ends the + surface; whether a second close() does anything is the backend's (the + desktop engine closes once, the page is told every time). + """ + + def resize(self, width, height): + ... + + def savePng(self, path): + ... + + def close(self): + ... diff --git a/src/test/python/preponderous/graphik/grid3d/test_grid3d_ports.py b/src/test/python/preponderous/graphik/grid3d/test_grid3d_ports.py new file mode 100644 index 0000000..60685a2 --- /dev/null +++ b/src/test/python/preponderous/graphik/grid3d/test_grid3d_ports.py @@ -0,0 +1,272 @@ +"""grid3d's ports: each one's contract, run against a fake and against the +production adapters, so a fake can't drift from what the views really get. + +No GPU, browser or network: the desktop adapters run over the stand-in +binding of test_grid3d_view, the browser ones over a stand-in page. +""" + +import base64 +import json +import sys +import types + +import pytest + +from preponderous.graphik.grid3d import CUBE, Camera, Label, Panel, Scene, Shape, Unavailable +from preponderous.graphik.grid3d import wire +from preponderous.graphik.grid3d.ports import ( + EventSource, + GridRelay, + PageObjects, + SceneRenderer, + StrataLoader, + Surface, +) + +from test_grid3d_view import fakeStrata + + +def aScene(camera=True): + return Scene(shapes=[Shape(CUBE, (0, 0, 0), (1, 1, 1), (1, 1, 1, 1))], + labels=[Label("hi", 2, 2, 8)], panels=[Panel(0, 0, 10, 10)], + camera=Camera((0, 5, 5), (0, 0, 0)) if camera else None) + + +# -- fakes, one per port + + +class FakeDisplay: + """SceneRenderer, EventSource and Surface for a view under test.""" + + def __init__(self, events=()): + self.drawn, self.events, self.sizes = [], list(events), [] + self.closed = 0 + self.strata = self.lib = self.engine = None + + def draw(self, scene, aspect, present=True): + self.drawn.append((scene, aspect, present)) + + def poll(self): + events, self.events = self.events, [] + return events + + def resize(self, width, height): + self.sizes.append((width, height)) + + def savePng(self, path): + raise Unavailable("a fake has no pixels") + + def close(self): + self.closed += 1 + + +class FakeStrataLoader: + def __init__(self, display=None, reason=None): + self.display, self.reason, self.opened = display or FakeDisplay(), reason, [] + + def open(self, width, height, title, headless): + if self.reason is not None: + raise Unavailable(self.reason) + self.opened.append((width, height, title, headless)) + return self.display + + +class FakePage: + def __init__(self, **objects): + self.objects = objects + + def get(self, name): + return self.objects.get(name) + + +# -- the production adapters, over stand-ins + + +def adapters(): + # the adapters arrive in the next step; until then their cases skip + return pytest.importorskip("preponderous.graphik.grid3d.adapters") + + +@pytest.fixture +def strataModule(monkeypatch): + module = fakeStrata() + monkeypatch.setitem(sys.modules, "strata", module) + monkeypatch.setattr(sys, "platform", "linux") + monkeypatch.delenv("STRATA_LIBRARY", raising=False) + monkeypatch.setenv("GALLIUM_DRIVER", "llvmpipe") + monkeypatch.setenv("SDL_VIDEODRIVER", "dummy") + return module + + +class PageRelayStandIn: + """window.StrataGridRelay through pygbag's bridge: strings in and out, + refusing what the relay refuses.""" + + def __init__(self): + self.events, self.status = [], "ready" + + def request(self, options): + json.loads(options) + return self.status + + def state(self): + return self.status + + def send(self, b64): + try: + wire.readHeader(base64.b64decode(b64)) + except wire.WireError as error: + return error.status + return 0 + + def poll(self): + events, self.events = self.events, [] + return json.dumps(events) + + def reducedMotion(self): + return 0 + + def close(self): + self.status = "closed" + + +def productionDisplays(strataModule): + module = adapters() + BindingStrataLoader, RecordingRelay, RelayDisplay = ( + module.BindingStrataLoader, module.RecordingRelay, module.RelayDisplay) + + return [BindingStrataLoader().open(320, 200, "t", headless=True), + RelayDisplay(RecordingRelay())] + + +def displays(request, strataModule): + if request.param == "fake": + return FakeDisplay() + return productionDisplays(strataModule)[["desktop", "web"].index(request.param)] + + +@pytest.fixture(params=["fake", "desktop", "web"]) +def display(request, strataModule): + return displays(request, strataModule) + + +# -- SceneRenderer, EventSource, Surface + + +def test_a_display_is_a_renderer_an_event_source_and_a_surface(display): + assert isinstance(display, SceneRenderer) + assert isinstance(display, EventSource) + assert isinstance(display, Surface) + + +def test_a_renderer_draws_a_checked_scene_with_or_without_a_camera(display): + for scene in (aScene(), aScene(camera=False)): + scene.checkLimits() + assert display.draw(scene, 1.6) is None + assert display.draw(scene, 1.6, present=False) is None + + +def test_an_event_source_hands_each_event_over_once(display): + first = display.poll() + assert isinstance(first, list) + assert display.poll() == [] + + +def test_a_surface_resizes_snapshots_or_refuses_in_words_and_closes(display, tmp_path): + assert display.resize(400, 300) is None + try: + display.savePng(str(tmp_path / "shot.png")) + except Unavailable as reason: + assert str(reason) + assert display.close() is None + + +# -- StrataLoader + + +@pytest.fixture(params=["fake", "binding"]) +def loader(request, strataModule): + if request.param == "fake": + return FakeStrataLoader() + BindingStrataLoader = adapters().BindingStrataLoader + + return BindingStrataLoader() + + +def test_a_loader_opens_a_display_that_shows_its_binding(loader): + assert isinstance(loader, StrataLoader) + opened = loader.open(320, 200, "Game", False) + assert isinstance(opened, SceneRenderer) and isinstance(opened, EventSource) + assert isinstance(opened, Surface) + for name in ("strata", "lib", "engine"): + assert hasattr(opened, name) + + +@pytest.mark.parametrize("which", ["fake", "binding"]) +def test_a_loader_that_cant_open_says_why(which, monkeypatch): + if which == "fake": + loader = FakeStrataLoader(reason="no GPU") + else: + BindingStrataLoader = adapters().BindingStrataLoader + + monkeypatch.setitem(sys.modules, "strata", fakeStrata(engineError=RuntimeError("no GPU"))) + monkeypatch.setattr(sys, "platform", "linux") + monkeypatch.delenv("STRATA_LIBRARY", raising=False) + loader = BindingStrataLoader() + with pytest.raises(Unavailable, match="no GPU"): + loader.open(320, 200, "Game", False) + + +# -- GridRelay + + +@pytest.fixture(params=["recording", "platform"]) +def relay(request): + module = adapters() + PlatformRelay, RecordingRelay = module.PlatformRelay, module.RecordingRelay + + if request.param == "recording": + return RecordingRelay() + return PlatformRelay(PageRelayStandIn()) + + +def test_a_relay_answers_with_its_state_and_takes_messages(relay): + assert isinstance(relay, GridRelay) + state = relay.request({"canvas": "relay", "maxBytes": 10, "title": "t"}) + assert state == relay.state() == "ready" + assert relay.send(wire.encodeHud([Label("x", 0, 0, 8)])) == 0 + assert relay.send(b"nope") == -1 + assert relay.poll() == [] and relay.reducedMotion() is False + assert relay.close() is None + + +# -- PageObjects + + +@pytest.fixture(params=["fake", "pygbag"]) +def page(request, monkeypatch): + marker = types.SimpleNamespace(name="toggle") + monkeypatch.setattr(sys, "platform", "emscripten") + fake = types.ModuleType("platform") + fake.window = types.SimpleNamespace(Graphik3D=marker) + monkeypatch.setitem(sys.modules, "platform", fake) + if request.param == "fake": + return FakePage(Graphik3D=marker), marker + PygbagPageObjects = adapters().PygbagPageObjects + + return PygbagPageObjects(), marker + + +def test_page_objects_are_found_by_name_and_missing_ones_are_none(page): + objects, marker = page + assert isinstance(objects, PageObjects) + assert objects.get("Graphik3D") is marker + assert objects.get("StrataGridRelay") is None + + +def test_outside_a_browser_there_are_no_page_objects(monkeypatch): + PygbagPageObjects = adapters().PygbagPageObjects + + monkeypatch.setattr(sys, "platform", "linux") + assert PygbagPageObjects().get("Graphik3D") is None + assert FakePage().get("Graphik3D") is None From bbef6d490406dc5b77f80be10a7161a4a6c31647 Mon Sep 17 00:00:00 2001 From: Daniel McCoy Stephenson Date: Fri, 20 Nov 2026 18:33:03 -0700 Subject: [PATCH 03/10] refactor(grid3d): the views' I/O is moved into adapters, one per file The code that talks to Strata, the page and pygbag was moved, nearly verbatim, into grid3d/adapters/: - BindingStrataLoader: loadStrata, the pinned STRATA_VERSION, the SDL and Gallium defaults, the engine, its lighting and sun - StrataEngine: drawing a Scene through the binding (renderItems, labelBytes), polling, resize, savePng, close - RelayDisplay: drawing a Scene as relay messages (only what changed), sending, Event polling, the savePng refusal - PlatformRelay, RecordingRelay: the two GridRelays - PygbagPageObjects: window. under pygbag Grid3DView and Grid3DWebView now delegate to them and keep every attribute games and tests read (view.strata, view.lib, view.engine, view.relay, view.sent, view.lastSent), as properties. view.py and web.py re-export every moved name. The port contracts now run against these adapters as well as the fakes. No behaviour was changed. 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/adapters/__init__.py | 22 +++ .../grid3d/adapters/binding_strata_loader.py | 62 +++++++ .../graphik/grid3d/adapters/platform_relay.py | 40 +++++ .../grid3d/adapters/pygbag_page_objects.py | 16 ++ .../grid3d/adapters/recording_relay.py | 44 +++++ .../graphik/grid3d/adapters/relay_display.py | 64 +++++++ .../graphik/grid3d/adapters/strata_engine.py | 110 ++++++++++++ .../preponderous/graphik/grid3d/view.py | 164 ++++-------------- .../python/preponderous/graphik/grid3d/web.py | 143 +++------------ .../graphik/grid3d/test_grid3d_ports.py | 5 +- 10 files changed, 419 insertions(+), 251 deletions(-) create mode 100644 src/main/python/preponderous/graphik/grid3d/adapters/__init__.py create mode 100644 src/main/python/preponderous/graphik/grid3d/adapters/binding_strata_loader.py create mode 100644 src/main/python/preponderous/graphik/grid3d/adapters/platform_relay.py create mode 100644 src/main/python/preponderous/graphik/grid3d/adapters/pygbag_page_objects.py create mode 100644 src/main/python/preponderous/graphik/grid3d/adapters/recording_relay.py create mode 100644 src/main/python/preponderous/graphik/grid3d/adapters/relay_display.py create mode 100644 src/main/python/preponderous/graphik/grid3d/adapters/strata_engine.py diff --git a/src/main/python/preponderous/graphik/grid3d/adapters/__init__.py b/src/main/python/preponderous/graphik/grid3d/adapters/__init__.py new file mode 100644 index 0000000..006e78c --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/adapters/__init__.py @@ -0,0 +1,22 @@ +"""The adapters of grid3d's ports, one implementation per file. + +| Port | Adapters | +|---|---| +| StrataLoader | BindingStrataLoader | +| SceneRenderer, EventSource, Surface | StrataEngine (desktop), RelayDisplay (browser) | +| GridRelay | PlatformRelay (pygbag), RecordingRelay (tests, recordings) | +| PageObjects | PygbagPageObjects | + +Importing this package loads neither Strata, pygame nor pygbag: they are +imported when an adapter is used. +""" + +from .binding_strata_loader import BindingStrataLoader +from .platform_relay import PlatformRelay +from .pygbag_page_objects import PygbagPageObjects +from .recording_relay import RecordingRelay +from .relay_display import RelayDisplay +from .strata_engine import StrataEngine + +__all__ = ["BindingStrataLoader", "PlatformRelay", "PygbagPageObjects", "RecordingRelay", + "RelayDisplay", "StrataEngine"] diff --git a/src/main/python/preponderous/graphik/grid3d/adapters/binding_strata_loader.py b/src/main/python/preponderous/graphik/grid3d/adapters/binding_strata_loader.py new file mode 100644 index 0000000..2c22765 --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/adapters/binding_strata_loader.py @@ -0,0 +1,62 @@ +"""BindingStrataLoader: opens a StrataEngine through the strata-engine +binding (`graphik[strata]`), which loads libstrata: a released build, +downloaded once, checked against its pinned SHA-256 and cached, or the +local build STRATA_LIBRARY points at.""" + +import os +import sys + +from ..errors import Unavailable +from ..geometry import SUN_DIRECTION +from .strata_engine import StrataEngine + +STRATA_VERSION = "0.8.0" +STRATA_PLATFORMS = ("linux", "win32") +INSTALL_HINT = "pip install 'graphik[strata]'" + + +def loadStrata(platform=None): + """Import the binding and load libstrata; raise Unavailable if either fails.""" + platform = sys.platform if platform is None else platform + if platform not in STRATA_PLATFORMS and not os.environ.get("STRATA_LIBRARY"): + raise Unavailable("Strata has no library for this system (%s)" % platform) + # Headless rendering without a GPU driver (CI, WSL) goes through Mesa's + # software rasteriser; harmless where a GPU exists. + os.environ.setdefault("GALLIUM_DRIVER", "llvmpipe") + try: + import strata + except ImportError: + raise Unavailable( + "the strata-engine package isn't installed (%s)" % INSTALL_HINT + ) + try: + if os.environ.get("STRATA_LIBRARY"): + return strata, strata.load() + return strata, strata.load_release(STRATA_VERSION) + except Exception as error: # download failed, checksum mismatch, bad library + raise Unavailable("the Strata library couldn't be loaded: %s" % error) + + +class BindingStrataLoader: + """The desktop's StrataLoader.""" + + def open(self, width, height, title, headless): + if headless and sys.platform.startswith("linux"): + # Linux renders headless through EGL with no window. On Windows the + # headless engine is a hidden SDL window, which the dummy driver + # can't create, so it is only forced here. + os.environ.setdefault("SDL_VIDEODRIVER", "dummy") + strata, lib = loadStrata() + surface = strata.SURFACE_HEADLESS if headless else strata.SURFACE_WINDOW + try: + engine = strata.Engine( + lib, width, height, surface=surface, title=None if headless else title + ) + except Exception as error: # no display, no GPU driver + raise Unavailable("no Strata window could be opened: %s" % error) + lighting = lib.lighting_defaults(strata.LIGHTING_SUN) + lighting.shadow_distance = 40.0 + lighting.fog = 0 + engine.set_lighting(lighting) + engine.set_sun_direction(SUN_DIRECTION) + return StrataEngine(strata, lib, engine) diff --git a/src/main/python/preponderous/graphik/grid3d/adapters/platform_relay.py b/src/main/python/preponderous/graphik/grid3d/adapters/platform_relay.py new file mode 100644 index 0000000..57b5e3c --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/adapters/platform_relay.py @@ -0,0 +1,40 @@ +"""PlatformRelay: the page's grid relay through pygbag's platform.window, +which passes strings, so options go as JSON and messages as base64.""" + +import base64 +import json + +from ..errors import Unavailable +from .pygbag_page_objects import PygbagPageObjects + + +class PlatformRelay: + """The page's window.StrataGridRelay, through pygbag's platform.window.""" + + def __init__(self, relay=None): + if relay is None: + relay = PygbagPageObjects().get("StrataGridRelay") + if relay is None: + raise Unavailable( + "this page has no 3D view (grid-relay.js isn't loaded; on graphik's " + "template it loads once the 3D toggle is on, when wants3D() turns true)" + ) + self.js = relay + + def request(self, options): + return str(self.js.request(json.dumps(options))) + + def state(self): + return str(self.js.state()) + + def send(self, message): + return int(self.js.send(base64.b64encode(message).decode("ascii"))) + + def poll(self): + return json.loads(str(self.js.poll())) + + def reducedMotion(self): + return bool(int(self.js.reducedMotion())) + + def close(self): + self.js.close() diff --git a/src/main/python/preponderous/graphik/grid3d/adapters/pygbag_page_objects.py b/src/main/python/preponderous/graphik/grid3d/adapters/pygbag_page_objects.py new file mode 100644 index 0000000..023685f --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/adapters/pygbag_page_objects.py @@ -0,0 +1,16 @@ +"""PygbagPageObjects: the page's JS objects through pygbag's +platform.window, asked again on every call.""" + +import sys + + +class PygbagPageObjects: + """window. under pygbag, or None (not in a browser, or no such + object on the page).""" + + def get(self, name): + if sys.platform != "emscripten": + return None + import platform # pygbag's, not the standard library's + + return getattr(platform.window, name, None) diff --git a/src/main/python/preponderous/graphik/grid3d/adapters/recording_relay.py b/src/main/python/preponderous/graphik/grid3d/adapters/recording_relay.py new file mode 100644 index 0000000..4f86ca3 --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/adapters/recording_relay.py @@ -0,0 +1,44 @@ +"""RecordingRelay: a GridRelay that keeps what it is sent.""" + +import base64 +import json + +from ..wire import WireError, readHeader + + +class RecordingRelay: + """A relay that keeps what it is sent: for tests, and for recording a + game to play into the relay's test page (index.html?wire=...).""" + + def __init__(self, reducedMotion=False, state="ready"): + self.messages, self.events, self.motion = [], [], reducedMotion + self.status = state + self.closed = False + + def request(self, options): + self.options = options + return self.status + + def state(self): + return self.status + + def send(self, message): + try: + readHeader(message) + except WireError as error: + return error.status + self.messages.append(bytes(message)) + return 0 + + def poll(self): + events, self.events = self.events, [] + return events + + def reducedMotion(self): + return self.motion + + def close(self): + self.closed = True + + def wireJson(self): + return json.dumps([base64.b64encode(m).decode("ascii") for m in self.messages]) diff --git a/src/main/python/preponderous/graphik/grid3d/adapters/relay_display.py b/src/main/python/preponderous/graphik/grid3d/adapters/relay_display.py new file mode 100644 index 0000000..26351d1 --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/adapters/relay_display.py @@ -0,0 +1,64 @@ +"""RelayDisplay: the page's grid relay (a GridRelay) as a SceneRenderer, +an EventSource and a Surface, plus the retained messages Grid3DWebView +sends it (BOARD, PIECES, HUD, VIEW).""" + +from types import SimpleNamespace + +from ..errors import Unavailable +from ..events import Event +from ..wire import BOARD, HUD, PIECES, VIEW, WireError, encodeBoard, encodeHud, encodePieces, encodeView + + +# what encodePieces needs to send "no pieces" for draw() +_NO_BOARD = SimpleNamespace(visible=lambda column, row: False, bridgePairs=lambda pieces: []) + + +class RelayDisplay: + """What a Grid3DWebView draws on: `relay` and what it was sent.""" + + def __init__(self, relay): + self.relay = relay + self.sent = 0 + self.lastSent = {} # kind -> the last message of that kind (draw) + + def send(self, message, kind=None): + """Sends one message; a refusal raises WireError with the relay's + status. `kind` keeps it as the last of its kind, which draw() + compares against.""" + rc = self.relay.send(message) + if rc < 0: + raise WireError(rc, "the grid relay refused a message") + self.sent += 1 + if kind is not None: + self.lastSent[kind] = message + + def draw(self, scene, aspect, present=True): + """A complete Scene, for games that build their own each frame: its + shapes and lights go as the board, its labels and panels as the HUD, + its camera as the view; only what changed since the last frame is + sent. The relay keeps its own aspect and presents on the page's own + frames, so `aspect` and `present` change nothing.""" + messages = [ + (BOARD, encodeBoard(scene.shapes, scene.lights)), + (PIECES, encodePieces(_NO_BOARD, (), {}, 0.0)), + (HUD, encodeHud(scene.labels, scene.panels)), + ] + if scene.camera is not None: + messages.append((VIEW, encodeView(scene.camera, scene.clearColor))) + for kind, message in messages: + if self.lastSent.get(kind) != message: + self.send(message, kind) + + def poll(self): + """Every event since the last poll (Event objects; see events.EVENTS).""" + return [Event(e) for e in self.relay.poll()] + + def resize(self, width, height): + """Nothing to do: the page sizes its own canvas (the view sends the + camera for the new size).""" + + def savePng(self, path): + raise Unavailable("screenshots of the web view are taken by the page (canvas.toBlob)") + + def close(self): + self.relay.close() diff --git a/src/main/python/preponderous/graphik/grid3d/adapters/strata_engine.py b/src/main/python/preponderous/graphik/grid3d/adapters/strata_engine.py new file mode 100644 index 0000000..c758f40 --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/adapters/strata_engine.py @@ -0,0 +1,110 @@ +"""StrataEngine: a desktop Strata engine as a SceneRenderer, an +EventSource and a Surface, through the strata-engine binding (ctypes).""" + +import ctypes +import struct + +from ..geometry import FAR_PLANE, NEAR_PLANE + +# Strata's StrataRenderItem: int32 kind, float3 position, float3 scale, +# float4 colour (44 bytes) +_RENDER_ITEM = struct.Struct("