diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index e729f7b..976442f 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -61,7 +61,8 @@ jobs: # 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 + # the pinned Strata release library (view.STRATA_VERSION, set in + # adapters/binding_strata_loader.py) 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) @@ -131,6 +132,10 @@ jobs: import pygame import preponderous.graphik as package from preponderous.graphik import Graphik + # grid3d's subpackages and page template ship in the archive too + from preponderous.graphik.grid3d import adapters, ports, web + assert os.path.isfile(web.templatePath()), web.templatePath() + assert "site-packages" in adapters.__file__ and ports.SceneRenderer assert package.__version__ == os.environ["VERSION"], package.__version__ assert "site-packages" in package.__file__, package.__file__ diff --git a/docs/grid3d.md b/docs/grid3d.md index c591a57..760b9ca 100644 --- a/docs/grid3d.md +++ b/docs/grid3d.md @@ -24,7 +24,8 @@ Contents: [Scene data](#scene-data) · [Boards and pieces](#boards-and-pieces) [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) +[The wire format](#the-wire-format) · [Fetching the relay](#fetching-the-relay) · +[How the views are built](#how-the-views-are-built) ## Scene data @@ -262,6 +263,9 @@ if web.touchScreen(): | `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()` | | +| `view.setFullscreen(enabled)`, `view.setTitle(title)` | Desktop fullscreen on or off; the window's title. Each returns `False` when it can't: the loaded Strata lacks the call (0.8.0 has no `strata_set_title`), the view is closed, or (fullscreen) headless | +| `view.strata`, `view.lib`, `view.engine` | The binding, the loaded library and the engine, for calls graphik doesn't wrap. Prefer the view's own methods where there is one | +| `Grid3DView.using(display, width, height, isWindow=True, reducedMotion=False, clock=time.monotonic)` | A view drawing on any display that has the view's ports ([below](#how-the-views-are-built)): for tests and tools | | `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) | @@ -292,7 +296,7 @@ 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` | `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`; `setFullscreen()` and `setTitle()` return `False` (the browser owns its window, the page its title) | | `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 | @@ -306,7 +310,8 @@ the relay next to it ([Fetching the relay](#fetching-the-relay)). | `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` | +| `PlatformRelay(relay=None, page=None)` | The transport to the page's `window.StrataGridRelay` (found through `page`, `PAGE` by default) | +| `PAGE` | Where the page helpers look for the page's objects (a `PageObjects`); a test can put a fake here | | `RecordingRelay(reducedMotion=False, state="ready")` | A transport that keeps what it is sent: for tests, and `wireJson()` for the relay's test page | ```python @@ -397,3 +402,40 @@ kept. Only a release version (`0.9.0`, `1.0.0-rc.1`) is taken for `--strata`. | `tarballName(version)` | The release asset's name | | `RelayFetchError` | Why it couldn't fetch, verify or unpack | | `main(argv=None)` | The command line | + +## How the views are built + +The two views share one core and differ only in what they draw on. Each +part of the outside world they touch sits behind a port (an interface, one +per file in `grid3d/ports/`), implemented by adapters (one per file in +`grid3d/adapters/`), and `view.py` and `web.py` wire the production +adapters in as defaults: + +``` +game -> Grid3DView (view.py) -> ViewState, geometry, scene/board/animate/pick -> ports <- adapters + -> Grid3DWebView (web.py) -> ViewState, wire, events -> ports <- adapters +``` + +| Port | Question it answers | Adapters | +|---|---|---| +| `StrataLoader` | Can Strata run here? Open an engine | `BindingStrataLoader` (`view.STRATA_LOADER`) | +| `SceneRenderer` | Draw this Scene now | `StrataEngine`, `RelayDisplay` | +| `EventSource` | What input came since the last poll? | `StrataEngine`, `RelayDisplay` | +| `Surface` | Resize, snapshot, close | `StrataEngine`, `RelayDisplay` | +| `WindowChrome` | Fullscreen and the window's title | `StrataEngine`, `RelayDisplay` | +| `GridRelay` | Talk to the page's grid relay | `PlatformRelay`, `RecordingRelay` | +| `PageObjects` | Which of the page's JS objects exist? | `PygbagPageObjects` (`web.PAGE`) | + +The model and core (`errors.py`, `geometry.py`, `state.py`, `wire.py`, +`events.py`, and the scene, board, animation, picking, text, button and +touch-key modules) import no adapter and no view; `test_grid3d_architecture.py` +fails if one does, or if a port or adapter file holds more than one class. +Every port has a contract test (`test_grid3d_ports.py`) that its fake and its +production adapters all pass. `grid3d.view` and `grid3d.web` still export +every name they did in 0.5.3. + +To draw on something new (another engine, a recorder), write one adapter +file with the `SceneRenderer`, `EventSource`, `Surface` and `WindowChrome` +calls, add it to `adapters/__init__.py`, and hand it to +`Grid3DView.using(display, ...)`, or, for `open()`, add a `StrataLoader` +that returns it. diff --git a/src/main/python/preponderous/graphik/grid3d/__init__.py b/src/main/python/preponderous/graphik/grid3d/__init__.py index 8563c55..d6e7dbd 100644 --- a/src/main/python/preponderous/graphik/grid3d/__init__.py +++ b/src/main/python/preponderous/graphik/grid3d/__init__.py @@ -16,6 +16,15 @@ The API reference, with an example for each part, is docs/grid3d.md. +How it is built (docs/grid3d.md, "How the views are built"): + + game -> Grid3DView / Grid3DWebView (view.py, web.py: composition roots) + -> ViewState, geometry, wire, events (core) -> ports/ <- adapters/ + +The model and core never import an adapter or a view; each port has one +file, each adapter one file. A new backend is one adapter file plus an entry +in adapters/__init__.py. + Importing this package imports neither Strata nor pygame. """ 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..d4afb57 --- /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, page=None): + if relay is None: + relay = (page or 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..e38c0e7 --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/adapters/relay_display.py @@ -0,0 +1,72 @@ +"""RelayDisplay: the page's grid relay (a GridRelay) as a SceneRenderer, +an EventSource, a Surface and a WindowChrome, 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 setFullscreen(self, enabled): + """False: the page's window is the browser's.""" + return False + + def setTitle(self, title): + """False: the page's title is the page's.""" + return False + + 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..8d640f2 --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/adapters/strata_engine.py @@ -0,0 +1,129 @@ +"""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(" 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/ports/__init__.py b/src/main/python/preponderous/graphik/grid3d/ports/__init__.py new file mode 100644 index 0000000..bbde065 --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/ports/__init__.py @@ -0,0 +1,16 @@ +"""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 +from .window_chrome import WindowChrome + +__all__ = ["EventSource", "GridRelay", "PageObjects", "SceneRenderer", "StrataLoader", "Surface", + "WindowChrome"] 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/main/python/preponderous/graphik/grid3d/ports/window_chrome.py b/src/main/python/preponderous/graphik/grid3d/ports/window_chrome.py new file mode 100644 index 0000000..60dd56e --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/ports/window_chrome.py @@ -0,0 +1,22 @@ +from typing import Protocol, runtime_checkable + + +@runtime_checkable +class WindowChrome(Protocol): + """The window around the drawing: fullscreen and its title. + + setFullscreen(enabled) switches to desktop fullscreen (True) or back; + setTitle(title) names the window. Each returns True when done and False + when this backend can't (a Strata library older than the call, a closed + engine, the browser's page, whose window is the browser's). Never + raises for "can't", except fullscreen on a headless Strata engine, + which the binding refuses with an error, so Grid3DView doesn't ask a + headless one. May block for the window system's round trip. Call from + the thread that owns the window. + """ + + def setFullscreen(self, enabled): + ... + + def setTitle(self, title): + ... 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..b7ff166 100644 --- a/src/main/python/preponderous/graphik/grid3d/view.py +++ b/src/main/python/preponderous/graphik/grid3d/view.py @@ -25,148 +25,59 @@ The board and labels are kept between frames; pieces slide between their cells over one tick (see animate.Animator). + +This module is the desktop view's composition root: Grid3DView keeps what +it shows in a ViewState (state.py) and draws through its ports (ports/), +on the StrataEngine that STRATA_LOADER (BindingStrataLoader) opens. The +binding's own names (loadStrata, STRATA_VERSION, renderItems, labelBytes) +live in adapters/ and are re-exported here. """ -import ctypes -import os -import struct import sys import time -from .animate import Animator -from .pick import cellScreenPosition, pickCell, projectToScreen - -STRATA_VERSION = "0.8.0" -STRATA_PLATFORMS = ("linux", "win32") -INSTALL_HINT = "pip install 'graphik[strata]'" - - -# Strata's StrataRenderItem: int32 kind, float3 position, float3 scale, -# float4 colour (44 bytes) -_RENDER_ITEM = struct.Struct("