From 6121b30e212559a1c299a0635bcfee745bff72eb Mon Sep 17 00:00:00 2001 From: Daniel McCoy Stephenson Date: Thu, 19 Nov 2026 20:04:11 -0700 Subject: [PATCH 1/2] =?UTF-8?q?feat:=20grid3d=20=E2=80=94=20an=20optional?= =?UTF-8?q?=203D=20grid=20view=20drawn=20by=20Strata?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A new subpackage, preponderous.graphik.grid3d, draws a grid game's board in 3D with Strata: checkered tiles and a frame, pieces standing on cells, and a camera fitted to the board. A game describes the board once (GridBoard and a Theme of PieceStyles), reports its pieces every tick (Piece, with an id that stays the same from tick to tick), and Grid3DView draws them. Pieces slide between cells: Animator moves each piece from where it was drawn to its new cell over one tick, so motion is smooth at any frame rate while the game still steps a whole cell per tick. A piece jumps instead when it is new, opts out (interpolate=False), moves further than a cell (a teleport or wrap-around; the step is measured cell to cell, so a tick that comes before the last slide finished still slides), when reducedMotion is on, or when a tick is a snap (setPieces(..., snap=True), for a restart or a new level). Chained pieces (a snake's body) are bridged where they are orthogonal neighbours. Everything but Grid3DView.open is plain Python and is tested without a GPU; importing grid3d loads neither Strata nor pygame. The Strata binding is the optional `strata` extra, and Grid3DView.open raises Unavailable with a plain reason where Strata can't run (no binding, no library for the system, no window), so a game can keep its 2D view. Linux and Windows desktops only. The README gains a section on the view, with an example. drafted by Claude on behalf of Daniel Stephenson Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LYNeuoCqxFpUXrFhxnTg89 --- README.md | 37 +++ pyproject.toml | 7 + .../preponderous/graphik/grid3d/__init__.py | 46 +++ .../preponderous/graphik/grid3d/animate.py | 80 +++++ .../preponderous/graphik/grid3d/board.py | 286 +++++++++++++++++ .../preponderous/graphik/grid3d/scene.py | 137 ++++++++ .../preponderous/graphik/grid3d/view.py | 223 +++++++++++++ .../graphik/grid3d/golden/board-4x3.png | Bin 0 -> 6384 bytes .../graphik/grid3d/test_grid3d_scene.py | 296 ++++++++++++++++++ .../graphik/grid3d/test_grid3d_view.py | 128 ++++++++ 10 files changed, 1240 insertions(+) create mode 100644 src/main/python/preponderous/graphik/grid3d/__init__.py create mode 100644 src/main/python/preponderous/graphik/grid3d/animate.py create mode 100644 src/main/python/preponderous/graphik/grid3d/board.py create mode 100644 src/main/python/preponderous/graphik/grid3d/scene.py create mode 100644 src/main/python/preponderous/graphik/grid3d/view.py create mode 100644 src/test/python/preponderous/graphik/grid3d/golden/board-4x3.png create mode 100644 src/test/python/preponderous/graphik/grid3d/test_grid3d_scene.py create mode 100644 src/test/python/preponderous/graphik/grid3d/test_grid3d_view.py diff --git a/README.md b/README.md index 4d1a0f0..afbaf57 100644 --- a/README.md +++ b/README.md @@ -84,8 +84,45 @@ Color constants: `Graphik.black`, `Graphik.white`, `Graphik.red`, `Graphik.green An alpha component in a fill color (`(r, g, b, a)`) does not make `drawRectangle` or `drawButton`'s box translucent: on the display the shape is painted opaquely whatever `a` is, and on a surface with per-pixel alpha (`pygame.SRCALPHA`) the color's alpha replaces the pixels' own rather than blending over them. `drawText`'s `color` and `drawButton`'s `colorText` ignore an alpha component altogether: the text is painted as if `a` were 255, on the display and on a per-pixel alpha surface alike (only the antialiased glyph edges blend with what is underneath). +## 3D grid view (optional) + +`preponderous.graphik.grid3d` draws a grid game's board in 3D with +[Strata](https://github.com/Preponderous-Software/strata): tiles, a frame, and +pieces standing on cells that slide smoothly between cells from one game tick +to the next. A game describes its board once and reports what is on each cell +every tick; the look lives in a `Theme`. It needs the optional Strata binding +and runs on Linux and Windows desktops: + +```bash +pip install "graphik[strata] @ https://github.com/Stephenson-Software/graphik/archive/refs/tags/v0.3.0.zip" +``` + +```python +from preponderous.graphik.grid3d import ( + SPHERE, Grid3DView, GridBoard, Label, Piece, PieceStyle, Theme, Unavailable, +) + +theme = Theme(pieces={"pawn": PieceStyle(SPHERE, (0.9, 0.25, 0.2))}) +try: + view = Grid3DView.open(900, 700, "My game") +except Unavailable as reason: + print("No 3D here:", reason) # keep the 2D game +else: + view.setBoard(GridBoard(8, 8, theme)) + view.setPieces([Piece("p1", 3, 4, "pawn")], tickSeconds=0.15) # once per tick + view.setLabels([Label("Score: 0", 18, 16, 24)]) # when it changes + view.frame() # once per frame +``` + +- `Piece(id, column, row, style)`: keep `id` stable so the piece slides; `chain`/`link` join neighbouring pieces (a snake's body); `interpolate=False` makes it jump; `scale`, `color` and `facing` vary one piece. +- `PieceStyle(kind, color, height, size, lift, glow, tones, extras)`: `glow` adds a point light; `extras` draws decorations such as eyes. +- `Grid3DView.open(..., headless=True)` renders off-screen for tests and screenshots (`savePng`); `reducedMotion=True` makes pieces jump instead of slide. +- `Unavailable` says in plain words why 3D can't run (no binding, no library for the system, no window); the game should fall back to its 2D view. +- Everything except `Grid3DView.open` is plain Python, so scene code can be unit-tested without a GPU. Importing `grid3d` loads neither Strata nor pygame. + ## Dependencies - pygame +- optional: `strata-engine` 0.7.0 for the 3D grid view (the `strata` extra) Python 3.9 or newer is required (`requires-python` in [pyproject.toml](pyproject.toml)). The test suite is run against 3.9 through 3.13; see [`.github/workflows/test.yml`](.github/workflows/test.yml) for why 3.13 is the ceiling. diff --git a/pyproject.toml b/pyproject.toml index a65834e..8282181 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -19,6 +19,13 @@ classifiers = [ [project.optional-dependencies] test = ["pytest"] +# The 3D grid view (preponderous.graphik.grid3d) draws with Strata's Python +# binding. It isn't on PyPI, so it is installed from the Strata release tag; +# graphik itself is installed from tag archives too, never from PyPI, so a +# direct reference here is allowed. +strata = [ + "strata-engine @ git+https://github.com/Preponderous-Software/strata@v0.7.0#subdirectory=bindings/python", +] [project.urls] Homepage = "https://github.com/Stephenson-Software/graphik" diff --git a/src/main/python/preponderous/graphik/grid3d/__init__.py b/src/main/python/preponderous/graphik/grid3d/__init__.py new file mode 100644 index 0000000..e472a09 --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/__init__.py @@ -0,0 +1,46 @@ +"""graphik's 3D grid view: a grid game's board drawn in 3D with Strata. + +A game describes its board once (GridBoard + Theme), reports what stands on +each cell every tick (Piece), and a Grid3DView draws it, sliding pieces +between cells. The scene description (scene.py, board.py, animate.py) is pure +Python and needs no GPU; only Grid3DView.open() loads Strata, through the +optional `graphik[strata]` extra. Desktop Linux and Windows only for now. + +Importing this package imports neither Strata nor pygame. +""" + +from .animate import Animator, interpolatePosition +from .board import BED_TOP, GridBoard, Piece, PieceStyle, Theme, cellCenter, fitCamera +from .scene import ( + CAPSULE, + CLEAR_COLOR, + CUBE, + CYLINDER, + DIM_TEXT_COLOR, + MAX_POINT_LIGHTS, + MAX_SHADOWED_POINT_LIGHTS, + SPHERE, + TEXT_COLOR, + Camera, + Label, + Light, + Panel, + Scene, + SceneLimitError, + Shape, + fitText, + rgb255, + rgba, + shade, +) +from .view import STRATA_VERSION, Grid3DView, Unavailable + +__all__ = [ + "Animator", "interpolatePosition", + "BED_TOP", "GridBoard", "Piece", "PieceStyle", "Theme", "cellCenter", "fitCamera", + "CAPSULE", "CLEAR_COLOR", "CUBE", "CYLINDER", "DIM_TEXT_COLOR", + "MAX_POINT_LIGHTS", "MAX_SHADOWED_POINT_LIGHTS", "SPHERE", "TEXT_COLOR", + "Camera", "Label", "Light", "Panel", "Scene", "SceneLimitError", "Shape", + "fitText", "rgb255", "rgba", "shade", + "STRATA_VERSION", "Grid3DView", "Unavailable", +] diff --git a/src/main/python/preponderous/graphik/grid3d/animate.py b/src/main/python/preponderous/graphik/grid3d/animate.py new file mode 100644 index 0000000..75be1c1 --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/animate.py @@ -0,0 +1,80 @@ +"""Smooth piece movement between game ticks. + +A game moves pieces a whole cell per tick; the screen redraws many times in +between. Animator remembers where each piece was drawn and slides it to its +new cell over one tick, so motion is smooth at any frame rate while the game +only reports cell positions. Pure Python: positions are world (x, z) pairs. +""" + + +def lerp(a, b, t): + return a + (b - a) * t + + +def interpolatePosition(start, end, alpha): + """World (x, z) a fraction `alpha` (clamped to 0-1) of the way from start + to end.""" + alpha = 0.0 if alpha < 0.0 else 1.0 if alpha > 1.0 else alpha + return (lerp(start[0], end[0], alpha), lerp(start[1], end[1], alpha)) + + +class Animator: + """Tracks pieces by id and gives each one's position at a given time. + + A piece slides from where it was last drawn to the centre of its new cell + over `tickSeconds`. It jumps instead when it is new, when it opted out + (Piece.interpolate is False), when it moved further than `maxSlideCells` + in one tick (a teleport or wrap-around would otherwise slide across the + board), when reducedMotion is on, or when the whole tick is a snap (a + restart or a new level, where nothing should slide from the old board). + """ + + def __init__(self, cellCenter, reducedMotion=False, maxSlideCells=1.5): + self.cellCenter = cellCenter + self.reducedMotion = reducedMotion + self.maxSlideCells = maxSlideCells + self.tracks = {} # id -> (start, end) + self.startedAt = 0.0 + self.tickSeconds = 0.0 + + def update(self, pieces, now, tickSeconds, snap=False): + """Take this tick's pieces; `now` is a monotonic time in seconds. + `snap=True` puts every piece straight on its cell.""" + current = {} if snap else self.positions(now) + tracks = {} + for piece in pieces: + end = self.cellCenter(piece.column, piece.row) + start = current.get(piece.id) + # how far it moved is measured cell to cell, not from where it is + # drawn: a tick that comes before the last slide finished is + # still a one-cell step, and still slides + previous = self.tracks.get(piece.id, (None, None))[1] + if ( + start is None + or self.reducedMotion + or not piece.interpolate + or abs(end[0] - previous[0]) + abs(end[1] - previous[1]) + > self.maxSlideCells + ): + start = end + tracks[piece.id] = (start, end) + self.tracks = tracks + self.startedAt = now + self.tickSeconds = max(0.0, tickSeconds) + + def alpha(self, now): + if self.tickSeconds <= 0.0: + return 1.0 + return (now - self.startedAt) / self.tickSeconds + + def positions(self, now): + """id -> world (x, z) of every tracked piece at time `now`.""" + alpha = self.alpha(now) + return { + pieceId: interpolatePosition(start, end, alpha) + for pieceId, (start, end) in self.tracks.items() + } + + def settled(self, now): + """True once every piece has reached its cell.""" + return self.alpha(now) >= 1.0 diff --git a/src/main/python/preponderous/graphik/grid3d/board.py b/src/main/python/preponderous/graphik/grid3d/board.py new file mode 100644 index 0000000..736d703 --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/board.py @@ -0,0 +1,286 @@ +"""A grid game's board in 3D: tiles, a frame, pieces standing on cells. + +A game says *what* is on each cell with Piece objects; a Theme says *how* +everything looks (tile colours, frame, one PieceStyle per kind of piece). +GridBoard turns the two into scene shapes and lights, and fits a camera. +Pure Python: no Strata, no pygame. +""" + +from dataclasses import dataclass, field +from typing import Callable, Dict, Hashable, List, Optional, Tuple + +from .scene import ( + CUBE, + SPHERE, + Camera, + Light, + Scene, + Shape, + checkLights, + rgba, + shade, +) + +BED_TOP = 0.0 # y of the tiles' top face; pieces stand on it + + +@dataclass +class PieceStyle: + """How one kind of piece looks. + + kind, color, height (y size) and size (x/z footprint, in cells) make the + piece's main shape, standing on the board with its base `lift` above the + tiles. `glow` adds a point light above it: (radius, intensity). `tones` + (odd, even) shades chained pieces alternately by link, so a long body + reads as segments. `extras` + draws decorations (eyes, a crown): called with (piece, x, z, baseY), it + returns more Shapes, positioned from the piece's current (possibly + interpolated) world position. + """ + + kind: int = CUBE + color: Tuple[float, float, float] = (0.8, 0.8, 0.8) + height: float = 0.5 + size: float = 0.8 + lift: float = 0.0 + glow: Optional[Tuple[float, float]] = None + tones: Optional[Tuple[float, float]] = None + extras: Optional[Callable] = None + + +@dataclass +class Piece: + """Something standing on cell (column, row). + + `id` must stay the same from tick to tick for the same thing, so a view + can animate it from its old cell to its new one. `style` names a + PieceStyle in the Theme. `scale` multiplies the style's footprint and + height (a tapering tail), `color` overrides the style's colour. + + Pieces with the same `chain` and consecutive `link` numbers (a snake's + segments, head first) are joined by a bridge when their cells are + orthogonal neighbours. `facing` is a unit (dx, dz) step for extras that + look somewhere. `interpolate=False` makes the piece jump to its new cell + instead of sliding (teleports, wrap-around). + """ + + id: Hashable + column: int + row: int + style: str + scale: float = 1.0 + color: Optional[Tuple[float, float, float]] = None + chain: Optional[Hashable] = None + link: int = 0 + facing: Tuple[int, int] = (0, 1) + interpolate: bool = True + + +@dataclass +class Theme: + """The look of a board and its pieces. Colours are 0-1 (r, g, b).""" + + tile: Tuple[float, float, float] = (0.22, 0.38, 0.17) + alternate: Optional[Tuple[float, float, float]] = (0.18, 0.32, 0.14) + tileHeight: float = 0.18 + tileGap: float = 0.03 + frame: Optional[Tuple[float, float, float]] = (0.36, 0.22, 0.12) + frameWidth: float = 0.35 + pieces: Dict[str, PieceStyle] = field(default_factory=dict) + # How chained pieces are bridged: footprint across the bridge (a fraction + # of a cell, before the pieces' scale), height as a fraction of the + # pieces' height, and colour shade relative to the piece. + bridgeAcross: float = 0.6 + bridgeHeight: float = 0.8 + bridgeShade: float = 0.85 + + def style(self, name): + try: + return self.pieces[name] + except KeyError: + raise KeyError( + "no PieceStyle named %r in the theme (known: %s)" + % (name, ", ".join(sorted(self.pieces)) or "none") + ) + + +def cellCenter(column, row, columns, rows): + """World (x, z) of the middle of cell (column, row).""" + return (column - (columns - 1) / 2.0, row - (rows - 1) / 2.0) + + +def fitCamera(columns, rows, aspect=1.0, fovDegrees=42.0): + """A camera south of the board, tilted down about 55 degrees, far enough + back that the whole board and its frame fit, aiming a little beyond the + centre so the board sits low in the window and leaves the top rows of the + screen for a HUD. A tall window backs the camera off further.""" + size = max(columns, rows) + 1.0 # the frame adds about half a cell a side + size *= max(1.0, 1.0 / max(aspect, 0.5)) + distance = 0.86 * size + 0.9 + return Camera( + eye=(0.0, 1.35 * distance, 0.95 * distance), + target=(0.0, -0.3, -0.04 * size), + fovDegrees=fovDegrees, + ) + + +class GridBoard: + """A columns x rows board drawn with a Theme.""" + + def __init__(self, columns, rows, theme=None): + if columns < 1 or rows < 1: + raise ValueError("a board needs at least one column and one row") + self.columns = columns + self.rows = rows + self.theme = theme or Theme() + + def cellCenter(self, column, row): + return cellCenter(column, row, self.columns, self.rows) + + def contains(self, column, row): + return 0 <= column < self.columns and 0 <= row < self.rows + + def camera(self, aspect=1.0): + return fitCamera(self.columns, self.rows, aspect) + + # -- the static part + + def boardShapes(self, tint=None, tintAmount=0.55): + """Tiles (checkered when the theme has an alternate colour) and a + frame. `tint` blends every tile towards a colour (a red flash on a + collision).""" + t = self.theme + shapes = [] + edge = 1.0 - t.tileGap + for row in range(self.rows): + for column in range(self.columns): + cx, cz = self.cellCenter(column, row) + color = t.tile + if t.alternate is not None and (column + row) % 2: + color = t.alternate + if tint is not None: + color = tuple( + (1 - tintAmount) * c + tintAmount * k + for c, k in zip(color, tint) + ) + shapes.append( + Shape( + CUBE, + (cx, BED_TOP - t.tileHeight / 2, cz), + (edge, t.tileHeight, edge), + rgba(color), + ) + ) + if t.frame is not None: + halfW, halfD = self.columns / 2.0, self.rows / 2.0 + rim, height = t.frameWidth, t.tileHeight + 0.12 + yMid = BED_TOP - t.tileHeight + height / 2 + frame = rgba(t.frame) + wide = self.columns + 2 * rim + shapes += [ + Shape(CUBE, (0.0, yMid, -halfD - rim / 2), (wide, height, rim), frame), + Shape(CUBE, (0.0, yMid, halfD + rim / 2), (wide, height, rim), frame), + Shape(CUBE, (-halfW - rim / 2, yMid, 0.0), (rim, height, self.rows), frame), + Shape(CUBE, (halfW + rim / 2, yMid, 0.0), (rim, height, self.rows), frame), + ] + return shapes + + # -- the dynamic part + + def checkPieces(self, pieces): + """Raise ValueError for a piece off the board or a duplicate id, and + KeyError for an unknown style.""" + seen = set() + for piece in pieces: + if piece.id in seen: + raise ValueError("two pieces share the id %r" % (piece.id,)) + seen.add(piece.id) + if not self.contains(piece.column, piece.row): + raise ValueError( + "piece %r is off the %dx%d board at (%d, %d)" + % (piece.id, self.columns, self.rows, piece.column, piece.row) + ) + self.theme.style(piece.style) + + def pieceShapes(self, pieces, positions=None): + """Shapes and lights for `pieces`. `positions` maps a piece id to its + world (x, z) for this frame (from an Animator); pieces without one + stand in the middle of their cell.""" + shapes, lights = [], [] + where = {} + for piece in pieces: + x, z = (positions or {}).get(piece.id) or self.cellCenter( + piece.column, piece.row + ) + where[piece.id] = (x, z) + style = self.theme.style(piece.style) + color = piece.color if piece.color is not None else style.color + if style.tones is not None and piece.chain is not None: + color = shade(color, style.tones[0] if piece.link % 2 else style.tones[1]) + size = style.size * piece.scale + height = style.height * (0.75 + 0.25 * piece.scale) + baseY = BED_TOP + style.lift + shapes.append( + Shape( + style.kind, + (x, baseY + height / 2, z), + (size, height, size), + rgba(color), + ) + ) + if style.glow is not None: + radius, intensity = style.glow + lights.append( + Light((x, baseY + height + 0.4, z), tuple(color), radius, intensity) + ) + if style.extras is not None: + shapes.extend(style.extras(piece, x, z, baseY) or []) + shapes.extend(self._bridges(pieces, where)) + return shapes, lights + + def _bridges(self, pieces, where): + t = self.theme + chains = {} + for piece in pieces: + if piece.chain is not None: + chains.setdefault(piece.chain, []).append(piece) + shapes = [] + for members in chains.values(): + members.sort(key=lambda p: p.link) + for a, b in zip(members, members[1:]): + if b.link != a.link + 1: + continue + # only orthogonal neighbours (on their target cells) are joined + if abs(a.column - b.column) + abs(a.row - b.row) != 1: + continue + (ax, az), (bx, bz) = where[a.id], where[b.id] + style = t.style(b.style) + scale = (a.scale + b.scale) / 2 + across = t.bridgeAcross * scale + height = style.height * t.bridgeHeight * (0.75 + 0.25 * scale) + color = b.color if b.color is not None else style.color + shapes.append( + Shape( + SPHERE, + ((ax + bx) / 2, BED_TOP + style.lift + height / 2, (az + bz) / 2), + (max(across, abs(ax - bx)), height, max(across, abs(az - bz))), + rgba(shade(color, t.bridgeShade)), + ) + ) + return shapes + + # -- everything + + def scene(self, pieces=(), positions=None, labels=(), panels=(), lights=(), + aspect=1.0, tint=None, clearColor=None): + """A complete Scene, checked against the engine limits.""" + pieceShapes, pieceLights = self.pieceShapes(pieces, positions) + scene = Scene(camera=self.camera(aspect)) + scene.shapes = self.boardShapes(tint) + pieceShapes + scene.lights = list(lights) + pieceLights + scene.labels = list(labels) + scene.panels = list(panels) + if clearColor is not None: + scene.clearColor = clearColor + checkLights(scene.lights) + return scene diff --git a/src/main/python/preponderous/graphik/grid3d/scene.py b/src/main/python/preponderous/graphik/grid3d/scene.py new file mode 100644 index 0000000..3b129d1 --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/scene.py @@ -0,0 +1,137 @@ +"""A 3D scene as plain data: shapes, screen text and panels, lights, a camera. + +Nothing here imports Strata or pygame, so a game's state-to-scene code can be +built and tested without a GPU. A Grid3DView (view.py) draws a Scene. + +World axes: x runs along a grid's columns, z along its rows (row 0 is the far +edge, away from a camera south of the board), y is up. One cell is one world +unit, and a board is centred on the origin. +""" + +from dataclasses import dataclass, field +from typing import List, Optional, Tuple + +# Shape kinds. The values match Strata's PRIMITIVE_* constants. +CUBE, CAPSULE, CYLINDER, SPHERE = 0, 1, 2, 3 +SHAPE_KINDS = (CUBE, CAPSULE, CYLINDER, SPHERE) + +# Engine limits (strata.h). A Scene over them is rejected with SceneLimitError +# rather than left for the engine to refuse or truncate. +MAX_POINT_LIGHTS = 32 +MAX_SHADOWED_POINT_LIGHTS = 4 + +TEXT_COLOR = (0.97, 0.96, 0.92, 1.0) +DIM_TEXT_COLOR = (0.82, 0.80, 0.74, 1.0) +CLEAR_COLOR = (0.10, 0.12, 0.16, 1.0) + +Color3 = Tuple[float, float, float] +Color4 = Tuple[float, float, float, float] +Vec3 = Tuple[float, float, float] + + +class SceneLimitError(ValueError): + """A scene asks for more than the engine can draw (see MAX_* above).""" + + +@dataclass +class Shape: + """One of Strata's primitives. Strata 0.7.0 can't rotate primitives, so a + shape is axis-aligned; `scale` is its size along x, y and z.""" + + kind: int + position: Vec3 + scale: Vec3 + color: Color4 + + +@dataclass +class Label: + """Screen text: x/y in pixels from the top-left of the window.""" + + text: str + x: float + y: float + pixelSize: float + color: Color4 = TEXT_COLOR + + +@dataclass +class Panel: + """A filled screen rectangle, in pixels from the top-left, drawn under text.""" + + x: float + y: float + width: float + height: float + color: Color4 = (0.0, 0.0, 0.0, 0.6) + + +@dataclass +class Light: + """A point light. At most MAX_SHADOWED_POINT_LIGHTS may cast shadows.""" + + position: Vec3 + color: Color3 + radius: float + intensity: float + castShadows: bool = False + + +@dataclass +class Camera: + eye: Vec3 + target: Vec3 + fovDegrees: float = 42.0 + + +@dataclass +class Scene: + shapes: List[Shape] = field(default_factory=list) + labels: List[Label] = field(default_factory=list) + panels: List[Panel] = field(default_factory=list) + lights: List[Light] = field(default_factory=list) + camera: Optional[Camera] = None + clearColor: Color4 = CLEAR_COLOR + + def checkLimits(self): + """Raise SceneLimitError if the scene is over an engine limit.""" + checkLights(self.lights) + for shape in self.shapes: + if shape.kind not in SHAPE_KINDS: + raise SceneLimitError("unknown shape kind %r" % (shape.kind,)) + + +def checkLights(lights): + if len(lights) > MAX_POINT_LIGHTS: + raise SceneLimitError( + "%d point lights; Strata draws at most %d" + % (len(lights), MAX_POINT_LIGHTS) + ) + shadowed = sum(1 for light in lights if light.castShadows) + if shadowed > MAX_SHADOWED_POINT_LIGHTS: + raise SceneLimitError( + "%d shadow-casting lights; Strata allows at most %d" + % (shadowed, MAX_SHADOWED_POINT_LIGHTS) + ) + + +def rgb255(color): + """A 0-255 (r, g, b[, a]) colour as 0-1 floats (r, g, b).""" + return (color[0] / 255.0, color[1] / 255.0, color[2] / 255.0) + + +def rgba(color, alpha=1.0): + """(r, g, b) as (r, g, b, alpha).""" + return (color[0], color[1], color[2], alpha) + + +def shade(color, factor): + """Scale a 0-1 colour's r, g, b by `factor`, clamped to 0-1.""" + return tuple(max(0.0, min(1.0, c * factor)) for c in color[:3]) + + +def fitText(text, width, pixelSize, margin=18): + """Cut text to what fits across `width` pixels. Strata's built-in font is + monospaced, about one pixel size wide per character.""" + room = max(4, int((width - 2 * margin) / pixelSize)) + return text if len(text) <= room else text[: room - 3] + "..." diff --git a/src/main/python/preponderous/graphik/grid3d/view.py b/src/main/python/preponderous/graphik/grid3d/view.py new file mode 100644 index 0000000..9a5cb58 --- /dev/null +++ b/src/main/python/preponderous/graphik/grid3d/view.py @@ -0,0 +1,223 @@ +"""Grid3DView: draws a GridBoard and its pieces with Strata (desktop). + +The Strata Python binding (`strata-engine`, installed with the +`graphik[strata]` extra) loads libstrata, a native library: a released build +is downloaded once, checked against its pinned SHA-256 and cached, or +STRATA_LIBRARY points at a local build. Strata ships Linux x64 and Windows +x64 libraries, so this view runs there; anywhere else, or when the library +can't load or no window can open, Grid3DView.open() raises Unavailable with a +reason a player can act on, and the game keeps its 2D view. + +Usage, once per game: + + view = Grid3DView.open(900, 700, "My game") # or headless=True + view.setBoard(GridBoard(columns, rows, theme)) # when the board changes + view.setPieces(pieces, tickSeconds) # once per game tick + view.setLabels(labels, panels) # when the HUD changes + view.frame() # once per display frame + view.close() + +The board and labels are kept between frames; pieces slide between their +cells over one tick (see animate.Animator). +""" + +import os +import sys +import time + +from .animate import Animator + +STRATA_VERSION = "0.7.0" +STRATA_PLATFORMS = ("linux", "win32") +INSTALL_HINT = "pip install 'graphik[strata]'" + + +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 + 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 Grid3DView: + """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): + 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 + self.EVENT_RESIZED = strata.EVENT_RESIZED + + @classmethod + def open(cls, width=900, height=700, title="graphik", headless=False, + reducedMotion=False, clock=time.monotonic): + """Open a window (or a headless surface); raise Unavailable if Strata + can't run here.""" + 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) + view = cls(strata, lib, engine, width, height, not headless, + reducedMotion=reducedMotion, clock=clock) + lighting = lib.lighting_defaults(strata.LIGHTING_SUN) + lighting.shadow_distance = 40.0 + lighting.fog = 0 + engine.set_lighting(lighting) + engine.set_sun_direction((-0.45, 0.85, 0.35)) + return view + + # -- what to draw + + 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) + + 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) + + 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, + ) + + def frame(self, now=None, present=True): + """Draw one frame (pieces at their positions for `now`).""" + self.drawScene(self.scene(now), present=present) + + # -- drawing a Scene + + def drawScene(self, scene, present=True): + """Draw a complete Scene, for callers that build their own.""" + scene.checkLimits() + s, engine = self.strata, self.engine + camera = scene.camera + if camera is not None: + engine.set_camera( + self.lib.look_at( + camera.eye, + camera.target, + fov_y_degrees=camera.fovDegrees, + aspect=self.width / float(self.height), + near_plane=0.3, + far_plane=200.0, + ) + ) + lights = [] + for light in scene.lights: + point = s.PointLight() + point.position = light.position + point.color = light.color + point.range = light.radius + point.intensity = light.intensity + point.flags = s.POINT_LIGHT_CAST_SHADOWS if light.castShadows else 0 + lights.append(point) + engine.set_point_lights(lights) + engine.begin_frame(clear_color=scene.clearColor) + engine.submit_primitives( + [s.RenderItem(sh.kind, sh.position, sh.scale, sh.color) for sh in scene.shapes] + ) + if scene.panels: + engine.submit_rects( + [s.Rect(p.x, p.y, p.width, p.height, p.color) for p in scene.panels] + ) + if scene.labels: + engine.submit_text( + [ + s.Text(l.x, l.y, l.pixelSize, s.TEXT_SHADOW, l.color, + l.text.encode("utf-8")) + for l in scene.labels + ] + ) + engine.end_frame() + if present: + engine.present() + + # -- the window + + def pollEvents(self): + """Every pending Strata event (EVENT_QUIT, EVENT_KEY_DOWN, ...).""" + events = [] + while True: + event = self.engine.poll_event() + if event is None: + return events + events.append(event) + + def resize(self, width, height): + self.width, self.height = width, height + self.engine.resize(width, height) + + def savePng(self, path): + """The last frame as a PNG (headless or windowed).""" + self.engine.save_screenshot_png(path) + + def close(self): + if self.engine is not None: + self.engine.close() + self.engine = None diff --git a/src/test/python/preponderous/graphik/grid3d/golden/board-4x3.png b/src/test/python/preponderous/graphik/grid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zq(H#2Zz#oBXwshfa_2 z!PDUyz2pybYwSDNX=uEZ4u1!jY$d z>{K_7C`rFx=CQ_3*A!aHUMK%;jSQNtF;mxMRdi%@I{x08b{Ta2N!b5Gg8L|pdS#cQ z5Uw9Q{U2mo`cq;0DaD^sh=tOM^~yVs%IyE?=KqoGdRYh5tg3=u`=3;o)ASGE9nxDf zXN~Iq3-eE_{=~y!_Cw?7e`xOimaYNtHD`8rulcpcZyEob6GZ;|oM7#kU=1I~z<)Yn zqbu{PiqrekzyFkmmQdQTu-q(s&9DC+n1AzU5XkD&tw)|AxV^HI43L-m4!7GBM#BF9 DH2l;g literal 0 HcmV?d00001 diff --git a/src/test/python/preponderous/graphik/grid3d/test_grid3d_scene.py b/src/test/python/preponderous/graphik/grid3d/test_grid3d_scene.py new file mode 100644 index 0000000..3fa809e --- /dev/null +++ b/src/test/python/preponderous/graphik/grid3d/test_grid3d_scene.py @@ -0,0 +1,296 @@ +"""grid3d's scene description, board, pieces and animation: pure Python, no GPU.""" + +import importlib +import sys + +import pytest + +from preponderous.graphik.grid3d import ( + BED_TOP, + CAPSULE, + CUBE, + MAX_POINT_LIGHTS, + SPHERE, + Animator, + GridBoard, + Light, + Piece, + PieceStyle, + Scene, + SceneLimitError, + Shape, + Theme, + cellCenter, + fitCamera, + interpolatePosition, +) + + +def theme(): + return Theme( + pieces={ + "pawn": PieceStyle(SPHERE, (0.9, 0.2, 0.2), height=0.5, size=0.8), + "gem": PieceStyle(CAPSULE, (0.2, 0.9, 0.9), height=0.7, size=0.4, glow=(2.0, 1.5)), + "body": PieceStyle(SPHERE, (0.4, 0.8, 0.4), height=0.5, size=0.78, tones=(0.92, 0.78)), + } + ) + + +# -- importing + + +def test_importing_grid3d_loads_neither_strata_nor_pygame(): + for name in list(sys.modules): + if name == "strata" or name.startswith("strata.") or name.startswith("preponderous.graphik.grid3d"): + del sys.modules[name] + pygameLoaded = "pygame" in sys.modules + importlib.import_module("preponderous.graphik.grid3d") + assert "strata" not in sys.modules + assert ("pygame" in sys.modules) == pygameLoaded + + +# -- the board + + +def test_cells_are_centred_on_the_origin(): + assert cellCenter(0, 0, 3, 3) == (-1.0, -1.0) + assert cellCenter(1, 1, 3, 3) == (0.0, 0.0) + assert cellCenter(3, 0, 4, 2) == (1.5, -0.5) + + +def test_a_board_has_one_tile_per_cell_plus_a_four_sided_frame(): + board = GridBoard(5, 3, theme()) + shapes = board.boardShapes() + assert len(shapes) == 5 * 3 + 4 + assert all(shape.kind == CUBE for shape in shapes) + + +def test_tiles_are_checkered_and_a_tint_blends_every_tile(): + board = GridBoard(2, 1, theme()) + plain = board.boardShapes() + assert plain[0].color != plain[1].color + tinted = board.boardShapes(tint=(1.0, 0.0, 0.0)) + assert all(t.color[0] > p.color[0] for t, p in zip(tinted[:2], plain[:2])) + + +def test_a_theme_without_frame_or_alternate_draws_plain_tiles_only(): + board = GridBoard(2, 2, Theme(alternate=None, frame=None)) + shapes = board.boardShapes() + assert len(shapes) == 4 + assert len({shape.color for shape in shapes}) == 1 + + +def test_a_board_needs_a_cell(): + with pytest.raises(ValueError): + GridBoard(0, 3) + + +# -- pieces + + +def test_a_piece_stands_on_its_cell(): + board = GridBoard(3, 3, theme()) + shapes, lights = board.pieceShapes([Piece("p", 2, 0, "pawn")]) + (shape,) = shapes + assert (shape.position[0], shape.position[2]) == (1.0, -1.0) + assert shape.position[1] - shape.scale[1] / 2 == pytest.approx(BED_TOP) + assert lights == [] + + +def test_a_glowing_style_adds_a_light_above_the_piece(): + board = GridBoard(3, 3, theme()) + _, lights = board.pieceShapes([Piece("g", 1, 1, "gem")]) + (light,) = lights + assert (light.position[0], light.position[2]) == (0.0, 0.0) + assert light.position[1] > BED_TOP + 0.7 + + +def test_scale_and_colour_override_the_style(): + board = GridBoard(3, 3, theme()) + (shape,), _ = board.pieceShapes([Piece("p", 0, 0, "pawn", scale=0.5, color=(0.1, 0.2, 0.3))]) + assert shape.scale[0] == pytest.approx(0.4) + assert shape.color[:3] == (0.1, 0.2, 0.3) + + +def test_extras_are_drawn_from_the_pieces_current_position(): + def eyes(piece, x, z, baseY): + return [Shape(SPHERE, (x + piece.facing[0] * 0.3, baseY + 0.4, z), (0.2, 0.2, 0.2), (1, 1, 1, 1))] + + t = theme() + t.pieces["head"] = PieceStyle(SPHERE, (0.5, 0.9, 0.5), extras=eyes) + board = GridBoard(3, 3, t) + shapes, _ = board.pieceShapes([Piece("h", 1, 1, "head", facing=(1, 0))], positions={"h": (0.5, 0.0)}) + assert shapes[1].position[0] == pytest.approx(0.8) + + +def test_chained_neighbours_are_bridged_and_gaps_are_not(): + board = GridBoard(5, 1, theme()) + pieces = [ + Piece("a", 0, 0, "body", chain="snake", link=0), + Piece("b", 1, 0, "body", chain="snake", link=1), + Piece("c", 3, 0, "body", chain="snake", link=2), # not next to b + ] + shapes, _ = board.pieceShapes(pieces) + bridges = shapes[3:] + assert len(bridges) == 1 + assert bridges[0].position[0] == pytest.approx(-1.5) # between cells 0 and 1 + assert bridges[0].scale[0] == pytest.approx(1.0) # spans the gap along x + + +def test_chained_pieces_alternate_tones(): + board = GridBoard(3, 1, theme()) + pieces = [Piece(i, i, 0, "body", chain="s", link=i) for i in range(2)] + shapes, _ = board.pieceShapes(pieces) + assert shapes[0].color != shapes[1].color + + +def test_bad_pieces_are_rejected_with_their_id(): + board = GridBoard(3, 3, theme()) + with pytest.raises(ValueError, match="off the 3x3 board"): + board.checkPieces([Piece("x", 3, 0, "pawn")]) + with pytest.raises(ValueError, match="share the id"): + board.checkPieces([Piece("x", 0, 0, "pawn"), Piece("x", 1, 0, "pawn")]) + with pytest.raises(KeyError, match="no PieceStyle named 'ghost'"): + board.checkPieces([Piece("x", 0, 0, "ghost")]) + + +# -- the camera + + +@pytest.mark.parametrize("columns, rows", [(3, 3), (5, 5), (16, 16), (20, 8), (8, 20)]) +def test_the_camera_sees_every_corner_of_the_board(columns, rows): + camera = fitCamera(columns, rows, aspect=900 / 700) + ex, ey, ez = camera.eye + tx, ty, tz = camera.target + forward = (tx - ex, ty - ey, tz - ez) + import math + + norm = math.sqrt(sum(c * c for c in forward)) + forward = tuple(c / norm for c in forward) + half = math.radians(camera.fovDegrees) / 2 + for cx in (-columns / 2 - 0.4, columns / 2 + 0.4): + for cz in (-rows / 2 - 0.4, rows / 2 + 0.4): + to = (cx - ex, 0.0 - ey, cz - ez) + dist = math.sqrt(sum(c * c for c in to)) + cosAngle = sum(a * b for a, b in zip(forward, to)) / dist + # inside the vertical field of view (the horizontal one is wider) + assert math.acos(min(1.0, cosAngle)) < half * 1.35 + + +def test_the_camera_looks_down_from_the_south(): + camera = fitCamera(5, 5) + assert camera.eye[1] > camera.target[1] + assert camera.eye[2] > camera.target[2] + + +# -- limits + + +def test_too_many_lights_are_rejected(): + board = GridBoard(1, 1) + lights = [Light((0, 1, 0), (1, 1, 1), 1, 1)] * (MAX_POINT_LIGHTS + 1) + with pytest.raises(SceneLimitError, match="at most 32"): + board.scene(lights=lights) + + +def test_too_many_shadow_casting_lights_are_rejected(): + lights = [Light((0, 1, 0), (1, 1, 1), 1, 1, castShadows=True)] * 5 + with pytest.raises(SceneLimitError, match="shadow"): + Scene(lights=lights).checkLimits() + + +def test_the_largest_real_board_stays_inside_the_limits(): + # ophidian's level 6: a 16x16 board, a long snake and some pickups + t = theme() + board = GridBoard(16, 16, t) + snake = [Piece(("s", i), i % 16, i // 16, "body", chain="s", link=i) for i in range(60)] + pickups = [Piece(("g", i), i, 10, "gem") for i in range(8)] + scene = board.scene(snake + pickups) + scene.checkLimits() + assert len(scene.lights) == 8 + + +# -- animation + + +def test_interpolation_is_clamped(): + assert interpolatePosition((0, 0), (1, 2), 0.5) == (0.5, 1.0) + assert interpolatePosition((0, 0), (1, 2), -1) == (0, 0) + assert interpolatePosition((0, 0), (1, 2), 3) == (1, 2) + + +def animator(**kwargs): + return Animator(lambda c, r: cellCenter(c, r, 5, 5), **kwargs) + + +def test_a_piece_slides_to_its_new_cell_over_one_tick(): + a = animator() + a.update([Piece("p", 0, 0, "pawn")], now=0.0, tickSeconds=0.2) + a.update([Piece("p", 1, 0, "pawn")], now=0.2, tickSeconds=0.2) + assert a.positions(0.2)["p"] == (-2.0, -2.0) + assert a.positions(0.3)["p"] == pytest.approx((-1.5, -2.0)) + assert a.positions(0.5)["p"] == (-1.0, -2.0) + assert a.settled(0.4) + + +def test_a_new_piece_appears_on_its_cell(): + a = animator() + a.update([Piece("p", 2, 2, "pawn")], now=0.0, tickSeconds=0.2) + assert a.positions(0.0)["p"] == (0.0, 0.0) + + +def test_a_teleport_or_an_opted_out_piece_jumps(): + a = animator() + a.update([Piece("p", 0, 0, "pawn"), Piece("q", 0, 1, "pawn")], now=0.0, tickSeconds=0.2) + a.update( + [Piece("p", 4, 0, "pawn"), Piece("q", 1, 1, "pawn", interpolate=False)], + now=0.2, + tickSeconds=0.2, + ) + positions = a.positions(0.25) + assert positions["p"] == (2.0, -2.0) # wrapped across the board: no slide + assert positions["q"] == (-1.0, -1.0) + + +def test_reduced_motion_snaps_every_piece(): + a = animator(reducedMotion=True) + a.update([Piece("p", 0, 0, "pawn")], now=0.0, tickSeconds=0.2) + a.update([Piece("p", 1, 0, "pawn")], now=0.2, tickSeconds=0.2) + assert a.positions(0.25)["p"] == (-1.0, -2.0) + + +def test_a_slide_interrupted_by_the_next_tick_continues_from_where_it_was_drawn(): + a = animator() + a.update([Piece("p", 0, 0, "pawn")], now=0.0, tickSeconds=0.2) + a.update([Piece("p", 1, 0, "pawn")], now=0.2, tickSeconds=0.2) + a.update([Piece("p", 2, 0, "pawn")], now=0.3, tickSeconds=0.2) # halfway + assert a.positions(0.3)["p"] == pytest.approx((-1.5, -2.0)) + + +def test_removed_pieces_are_forgotten(): + a = animator() + a.update([Piece("p", 0, 0, "pawn")], now=0.0, tickSeconds=0.2) + a.update([], now=0.2, tickSeconds=0.2) + assert a.positions(0.3) == {} + + +def test_a_snapped_tick_puts_every_piece_on_its_cell(): + # a restart or a new level: nothing slides over from the old board + a = animator() + a.update([Piece("p", 0, 0, "pawn")], now=0.0, tickSeconds=0.2) + a.update([Piece("p", 1, 0, "pawn")], now=0.2, tickSeconds=0.2, snap=True) + assert a.positions(0.25)["p"] == (-1.0, -2.0) + a.update([Piece("p", 2, 0, "pawn")], now=0.4, tickSeconds=0.2) + assert a.positions(0.5)["p"] == pytest.approx((-0.5, -2.0)) # slides again + + +def test_a_tick_before_the_last_slide_finished_still_slides_a_one_cell_step(): + # ticks that come back to back (a busy frame, a speed-up): the step is + # measured from cell to cell, so a turn isn't mistaken for a teleport + a = animator() + a.update([Piece("p", 0, 0, "pawn")], now=0.0, tickSeconds=0.2) + a.update([Piece("p", 0, 1, "pawn")], now=0.2, tickSeconds=0.2) + a.update([Piece("p", 1, 1, "pawn")], now=0.2, tickSeconds=0.2) # no time passed + assert a.positions(0.2)["p"] == (-2.0, -2.0) # still drawn where it was + assert a.positions(0.3)["p"] == pytest.approx((-1.5, -1.5)) + assert a.positions(0.4)["p"] == (-1.0, -1.0) diff --git a/src/test/python/preponderous/graphik/grid3d/test_grid3d_view.py b/src/test/python/preponderous/graphik/grid3d/test_grid3d_view.py new file mode 100644 index 0000000..be45a48 --- /dev/null +++ b/src/test/python/preponderous/graphik/grid3d/test_grid3d_view.py @@ -0,0 +1,128 @@ +"""Grid3DView: why it can't start, and a headless render against a golden image. + +The render tests need Strata's Python binding and its library; they skip when +Strata can't load here (Grid3DView.open raises Unavailable). +""" + +import json +import os +import shutil +import subprocess +import sys + +import pytest + +from preponderous.graphik.grid3d import ( + CAPSULE, + SPHERE, + GridBoard, + Grid3DView, + Label, + Piece, + PieceStyle, + Theme, + Unavailable, +) +from preponderous.graphik.grid3d import view as viewModule + +GOLDEN = os.path.join(os.path.dirname(__file__), "golden", "board-4x3.png") + + +# -- why it can't start (no GPU needed) + + +def test_a_system_without_a_strata_library_is_unavailable(monkeypatch): + monkeypatch.delenv("STRATA_LIBRARY", raising=False) + with pytest.raises(Unavailable, match="no library for this system"): + viewModule.loadStrata(platform="darwin") + + +def test_a_missing_binding_says_how_to_install_it(monkeypatch): + monkeypatch.setitem(sys.modules, "strata", None) # makes `import strata` fail + with pytest.raises(Unavailable, match=r"graphik\[strata\]"): + viewModule.loadStrata(platform="linux") + + +# -- rendering (needs Strata) + + +def openHeadless(width=240, height=180, clock=None): + try: + if clock is None: + return Grid3DView.open(width, height, headless=True) + return Grid3DView.open(width, height, headless=True, clock=clock) + except Unavailable as reason: + pytest.skip("Strata can't run here: %s" % reason) + + +def goldenScene(view): + theme = Theme( + pieces={ + "pawn": PieceStyle(SPHERE, (0.9, 0.25, 0.2)), + "gem": PieceStyle(CAPSULE, (0.2, 0.8, 0.95), height=0.7, size=0.4, glow=(2.0, 1.6)), + } + ) + view.setBoard(GridBoard(4, 3, theme)) + view.setPieces([Piece("p", 1, 1, "pawn"), Piece("g", 3, 0, "gem")]) + view.setLabels([Label("grid3d", 8, 8, 14)]) + + +def differingFraction(expected, actual, threshold=12.0): + """Fraction of pixels whose RGB distance exceeds `threshold` (0-255 scale). + Uses strata-imgcmp (STRATA_IMGCMP or on PATH) when available.""" + imgcmp = os.environ.get("STRATA_IMGCMP") or shutil.which("strata-imgcmp") + if imgcmp: + out = subprocess.run( + [imgcmp, expected, actual, "--json", "--threshold", "4"], + capture_output=True, + text=True, + ) + report = json.loads(out.stdout) + for key in ("fraction_over", "fractionOver", "over_fraction"): + if key in report: + return float(report[key]) + if "pixels_over" in report and "pixels" in report: + return report["pixels_over"] / float(report["pixels"]) + import pygame + + a = pygame.image.load(expected) + b = pygame.image.load(actual) + assert a.get_size() == b.get_size() + width, height = a.get_size() + over = 0 + for y in range(height): + for x in range(width): + pa, pb = a.get_at((x, y)), b.get_at((x, y)) + d = ((pa.r - pb.r) ** 2 + (pa.g - pb.g) ** 2 + (pa.b - pb.b) ** 2) ** 0.5 + over += d > threshold + return over / float(width * height) + + +def test_a_board_renders_like_the_golden_image(tmp_path): + view = openHeadless() + try: + goldenScene(view) + view.frame(present=False) + actual = str(tmp_path / "board-4x3.png") + view.savePng(actual) + finally: + view.close() + assert differingFraction(GOLDEN, actual) <= 0.02 + + +def test_a_frame_mid_tick_draws_a_piece_between_its_cells(): + now = [0.0] + view = openHeadless(clock=lambda: now[0]) + try: + theme = Theme(pieces={"pawn": PieceStyle(SPHERE, (0.9, 0.25, 0.2))}) + view.setBoard(GridBoard(4, 3, theme)) + view.setPieces([Piece("p", 0, 1, "pawn")], tickSeconds=0.2) + now[0] = 0.2 + view.setPieces([Piece("p", 1, 1, "pawn")], tickSeconds=0.2) + now[0] = 0.3 + scene = view.scene() + piece = scene.shapes[-1] + assert piece.position[0] == pytest.approx(-1.0) # halfway from -1.5 to -0.5 + view.frame(present=False) # and the engine accepts it + finally: + view.close() From 50edeef23dc22e0fc56e562a368f69f40d77324c Mon Sep 17 00:00:00 2001 From: Daniel McCoy Stephenson Date: Thu, 19 Nov 2026 21:16:08 -0700 Subject: [PATCH 2/2] chore: graphik 0.4.0, grid3d on Strata 0.8.0 The version moves to 0.4.0 and the README's install lines name its tag. grid3d loads Strata 0.8.0, whose window fullscreen lets games offer F11 in their 3D windows, and the strata extra installs the 0.8.0 binding. drafted by Claude on behalf of Daniel Stephenson Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LYNeuoCqxFpUXrFhxnTg89 --- README.md | 4 ++-- pyproject.toml | 2 +- src/main/python/preponderous/graphik/_version.py | 2 +- src/main/python/preponderous/graphik/grid3d/view.py | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index afbaf57..8d3dbde 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ This library assists developers with graphics programming. graphik is released as git tags, not on PyPI. Install a release from its tag's archive (no `git` needed): ```bash -pip install "graphik @ https://github.com/Stephenson-Software/graphik/archive/refs/tags/v0.3.0.zip" +pip install "graphik @ https://github.com/Stephenson-Software/graphik/archive/refs/tags/v0.4.0.zip" ``` In a `requirements.txt`, use the same line without the quotes. See [RELEASING.md](RELEASING.md) for how releases are cut. @@ -94,7 +94,7 @@ every tick; the look lives in a `Theme`. It needs the optional Strata binding and runs on Linux and Windows desktops: ```bash -pip install "graphik[strata] @ https://github.com/Stephenson-Software/graphik/archive/refs/tags/v0.3.0.zip" +pip install "graphik[strata] @ https://github.com/Stephenson-Software/graphik/archive/refs/tags/v0.4.0.zip" ``` ```python diff --git a/pyproject.toml b/pyproject.toml index 8282181..42db9c7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -24,7 +24,7 @@ test = ["pytest"] # graphik itself is installed from tag archives too, never from PyPI, so a # direct reference here is allowed. strata = [ - "strata-engine @ git+https://github.com/Preponderous-Software/strata@v0.7.0#subdirectory=bindings/python", + "strata-engine @ git+https://github.com/Preponderous-Software/strata@v0.8.0#subdirectory=bindings/python", ] [project.urls] diff --git a/src/main/python/preponderous/graphik/_version.py b/src/main/python/preponderous/graphik/_version.py index 493f741..6a9beea 100644 --- a/src/main/python/preponderous/graphik/_version.py +++ b/src/main/python/preponderous/graphik/_version.py @@ -1 +1 @@ -__version__ = "0.3.0" +__version__ = "0.4.0" diff --git a/src/main/python/preponderous/graphik/grid3d/view.py b/src/main/python/preponderous/graphik/grid3d/view.py index 9a5cb58..6cdfe35 100644 --- a/src/main/python/preponderous/graphik/grid3d/view.py +++ b/src/main/python/preponderous/graphik/grid3d/view.py @@ -27,7 +27,7 @@ from .animate import Animator -STRATA_VERSION = "0.7.0" +STRATA_VERSION = "0.8.0" STRATA_PLATFORMS = ("linux", "win32") INSTALL_HINT = "pip install 'graphik[strata]'"