diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 2c5e67a..e729f7b 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -55,6 +55,40 @@ jobs: SDL_AUDIODRIVER: dummy run: python -m pytest + grid3d-render: + # The rest of the suite runs without Strata, so its render tests (a board + # drawn headless and compared with golden/board-4x3.png, a frame mid-tick) + # skip there. This job installs the strata extra and draws them for real, + # headless through EGL on Mesa's llvmpipe (no GPU, no display), and + # GRAPHIK_REQUIRE_STRATA turns a skip into a failure. The binding fetches + # the pinned Strata release library (view.STRATA_VERSION) from GitHub and + # checks its SHA-256. The browser backend has no render here: Strata's own + # CI draws the grid relay in Chromium against desktop stills. + name: grid3d render (Strata, llvmpipe) + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - name: Install Mesa (EGL, llvmpipe) + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends libegl1 libegl-mesa0 libgl1-mesa-dri libgles2 + + - name: Install package with test and strata dependencies + run: python -m pip install --upgrade pip && python -m pip install -e ".[test,strata]" + + - name: grid3d tests, rendering included + env: + SDL_VIDEODRIVER: dummy + SDL_AUDIODRIVER: dummy + GALLIUM_DRIVER: llvmpipe + GRAPHIK_REQUIRE_STRATA: "1" + run: python -m pytest -rs src/test/python/preponderous/graphik/grid3d + archive-install: # Consumers install graphik from a release tag's source archive, e.g. # graphik @ https://github.com/Stephenson-Software/graphik/archive/refs/tags/v0.3.0.zip diff --git a/README.md b/README.md index e017835..9a28b67 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.5.2.zip" +pip install "graphik @ https://github.com/Stephenson-Software/graphik/archive/refs/tags/v0.5.3.zip" ``` In a `requirements.txt`, use the same line without the quotes. See [RELEASING.md](RELEASING.md) for how releases are cut. @@ -95,7 +95,7 @@ and runs on Linux and Windows desktops, and in the browser under pygbag (see [In the browser](#in-the-browser)): ```bash -pip install "graphik[strata] @ https://github.com/Stephenson-Software/graphik/archive/refs/tags/v0.5.2.zip" +pip install "graphik[strata] @ https://github.com/Stephenson-Software/graphik/archive/refs/tags/v0.5.3.zip" ``` ```python @@ -122,6 +122,8 @@ else: - Everything except `Grid3DView.open` is plain Python, so scene code can be unit-tested without a GPU. Importing `grid3d` loads neither Strata nor pygame. - `PieceStyle.extras(piece, x, z, baseY)` returns shapes placed relative to the piece: x and z measured from the given `(x, z)`, so moving the piece moves them all the same way. The browser backend sends them as offsets from the piece and relies on this. +Every public class and function, with an example for each part, is in the [grid3d API reference](docs/grid3d.md). + ### Helpers for a game's 3D view So that games stop hand-building the same pieces: @@ -129,7 +131,7 @@ So that games stop hand-building the same pieces: - **Picking.** `view.pickCell(x, y)` (or `pickCell(camera, board, x, y, width, height)`) gives the `(column, row)` under a pointer, or `None`; the whole cell counts, gaps between tiles included. `projectToScreen(camera, point, width, height)` and `cellScreenPosition(camera, board, column, row, width, height, y)` go the other way, for aiming a tap at a piece or putting a note beside a tile. They use the same look-at and perspective the view asks Strata for. - **Text.** Strata's built-in font is an 8 x 8 bitmap font in which every character is exactly `pixelSize` wide. `measureText(text, pixelSize)`, `fitText(text, width, pixelSize)` (cut with `...`), `wrapText(text, maxWidth, pixelSize)` (greedy word wrap) and `centredLabel(text, x, y, pixelSize, color, rise=0.5)` build on that. - **Screen buttons.** `Button(x, y, width, height, text, color, textColor, pixelSize, function)` draws a panel and a centred label (`button.draw(pointer)`), hit-tests with `drawButton`'s edges (`contains`, `click`), and lifts under the pointer as `drawButton` does (`hoverColor`). Colours are 0-255, as for `drawButton`; `padding` widens a button whose label doesn't fit. -- **2D screens under a 3D view.** `ScreenRecorder` stands in for `Graphik`: a game's 2D screens draw into it as usual (`drawText`, `drawRectangle`, `drawButton`), the 3D view shows what they drew, and `recorder.click(pos)` runs the 2D button's own function. +- **2D screens under a 3D view.** `ScreenRecorder` stands in for `Graphik`: a game's 2D screens draw into it as usual (`drawText`, `drawRectangle`, `drawButton`, `drawImage`; `beginFrame`, `endFrame`, `getVersion` and the colour constants are there too), the 3D view shows what they drew, and `recorder.click(pos)` runs the 2D button's own function. - **Bigger boards.** `GridBoard(columns, rows, theme, tiles=..., mergeTiles=True, viewport=...)`: `tiles` maps a cell to its own `Tile(color, raised)`; `mergeTiles` draws each row's neighbouring tiles that look the same as one box (a 64 x 64 board of one colour is 64 boxes, not 4096); `viewport=Viewport.around(column, row, reach)` draws only a window of the board, framed and fitted as if it were the whole board, with pieces and picking still in whole-board cells. - **Hover.** `board.scene(..., highlight=(column, row))` lays a thin slab in `Theme.highlight` on the tile under the pointer. - **Chains.** `board.bridgePairs(pieces)` names the joined pieces and `board.bridgeShape(a, b, aAt, bAt)` draws one bridge. @@ -142,9 +144,10 @@ Under [pygbag](https://pypi.org/project/pygbag/) (`sys.platform == "emscripten"` - `view.ready` turns true once the page has loaded the 3D view; `view.failure()` says why it couldn't. `open()` raises `Unavailable` on a page without the relay. - `view.pollEvents()` returns Strata-style events (keys with desktop Strata's scancodes, mouse, wheel, resize, and `FINGER_*` for touch), and `grid3d.web.toPygameEvents(events, pygame)` turns them into pygame events, so a game's 2D input code runs unchanged. It converts desktop Strata events too. -- The page: build with `pygbag --template ...`, a copy of pygbag 0.9.3's default template with the relay's canvas and a **2D/3D** button. The relay has to be served with the game (a browser can't fetch GitHub release assets cross-origin): `python -m preponderous.graphik.grid3d.relay --strata 0.9.0 --dest ` downloads Strata's `strata--wasm32-emscripten.tar.gz`, checks it against the release's `SHA256SUMS` and copies its prebuilt `kit/grid-relay/dist/` next to the page, leaving files already there (pygbag's `index.html`) alone. +- The page: build with `pygbag --template ...`, a copy of pygbag 0.9.3's default template with the relay's canvas and a **2D/3D** button. The relay has to be served with the game (a browser can't fetch GitHub release assets cross-origin): `python -m preponderous.graphik.grid3d.relay --strata 0.9.0 --dest ` downloads Strata's `strata--wasm32-emscripten.tar.gz`, checks it against the release's `SHA256SUMS` and copies its prebuilt `kit/grid-relay/dist/` next to the page, leaving files already there (pygbag's `index.html`) alone; `--replace` replaces an earlier relay's files (never `index.html`) when moving to a newer Strata. - Since 0.5.1 the page starts in **3D**, as a desktop `Grid3DView` game does: the relay's scripts and engine load at once, alongside pygbag, and the 2D canvas stays on screen until the 3D view is drawing the game. If 3D can't start (no WebGL 2, a file missing, too big, the engine failed), the 2D view stays, the button reads *3D unavailable* and a note under it says why in plain words. Which view a page starts in: `?view=2d` or `?view=3d` in the address (for testing and sharing; not remembered), else the player's last choice on the button (kept in `localStorage`; a stored 2D wins over the default), else the game's default, which `templatePath(defaultView="2d")` makes 2D. A page that starts in 2D downloads nothing of the 3D view (not even the relay's three small scripts) until the button is pressed. `grid3d.web.wants3D()` tells the game 3D is on and the relay's scripts are in, so `Grid3DWebView.open()` can begin, and `set3D(False, reason)` turns it off. -- The button sits in the page's top right corner. `grid3d.web.buttonArea()` gives its `(x, y, width, height)` in CSS pixels, the units of the web view's labels and panels, so a HUD can keep text out from under it (`None` outside a browser). The page never scrolls (`overflow: hidden`), so a phone's browser can't widen it to fit pygbag's 50000-pixel measuring element and push the button off screen, and its one viewport tag sets `width=device-width` (pygbag 0.9.3's default page has a second one that overrides it). Strata's own loading and failure overlay is hidden, so it never covers the 2D game. +- **Too slow: back to 2D.** Since 0.5.3, when the 3D view stays slow once the game is drawing in it, the page goes back to 2D and the note says why in plain words ("this device draws the 3D view too slowly"). Strata's kit first gives up pixel density (down to 1) and then its quality tier; only once it has nothing left to give up, and the drawing itself stays slow for 5 seconds, does the page switch: second by second, the typical frame (the median time between the page's frames) is over 66 ms, the relay's own drawing (its `stats()` `cpuMs`) is at least a quarter of it, and the kit's own average frame (`frameMs`) is over 66 ms too. A game that stops the page now and then (building and sending a board in Python) makes a few long gaps, not a slow typical frame, and a game that is slow every frame while the drawing is cheap wouldn't be helped by 2D, so neither switches. Counting starts 3 seconds after the game's first message to the 3D view, so pygbag's boot and the first shader compile aren't counted, and stops while the tab is hidden. The switch isn't remembered as the player's choice: the button still offers 3D, and once the player chooses 3D again the page leaves it alone until it is reloaded. `?slow=0` in the address turns the switch off (for testing on a machine that draws in software). `Graphik3D.slowed()` in the page says it happened, and `Graphik3D.speed()` gives the last second's readings. +- The button sits in the page's top right corner. Since 0.5.3 it is a switch with both views on it, *2D* and *3D*, the one on show lit, so it reads as a choice rather than as a status; to a screen reader it is a toggle named "3D view" (`aria-pressed` while 3D is on), and it is at least 44 CSS pixels each way. `grid3d.web.buttonArea()` gives its `(x, y, width, height)` in CSS pixels, the units of the web view's labels and panels, so a HUD can keep text out from under it (`None` outside a browser). The page never scrolls (`overflow: hidden`), so a phone's browser can't widen it to fit pygbag's 50000-pixel measuring element and push the button off screen, and its one viewport tag sets `width=device-width` (pygbag 0.9.3's default page has a second one that overrides it). Strata's own loading and failure overlay is hidden, so it never covers the 2D game. In a game's `browser.yml`, where graphik is installed into `src/` for pygbag: diff --git a/docs/grid3d.md b/docs/grid3d.md new file mode 100644 index 0000000..c591a57 --- /dev/null +++ b/docs/grid3d.md @@ -0,0 +1,399 @@ +# grid3d API reference + +`preponderous.graphik.grid3d` draws a grid game's board in 3D with +[Strata](https://github.com/Preponderous-Software/strata). This page lists +every public name, grouped by what a game does with it, with a short example +for each group. The README's [3D grid view](../README.md#3d-grid-view-optional) +section is the tour; this is the reference. + +Conventions used throughout: + +- **World axes.** x runs along the columns, z along the rows (row 0 is the far + edge, away from a camera south of the board), y is up. One cell is one world + unit and a board is centred on the origin. +- **Colours.** Scene colours are 0-1 floats, `(r, g, b)` or `(r, g, b, a)`. + The 2D stand-ins in `ui.py` (`Button`, `ScreenRecorder`) take 0-255 + colours, as `Graphik` does. +- **Screen units.** Labels, panels and pointers are in window pixels from the + top-left (CSS pixels in a browser). +- **No GPU needed** for anything except `Grid3DView.open()`. Importing + `grid3d` loads neither Strata nor pygame. + +Contents: [Scene data](#scene-data) · [Boards and pieces](#boards-and-pieces) · +[Animation](#animation) · [Picking and projection](#picking-and-projection) · +[Text](#text) · [Buttons and 2D screens](#buttons-and-2d-screens) · +[Touch keys](#touch-keys) · +[The desktop view](#the-desktop-view) · [The browser view](#the-browser-view) · +[The wire format](#the-wire-format) · [Fetching the relay](#fetching-the-relay) + +## Scene data + +`scene.py`: a frame as plain data. + +| Name | What it is | +|---|---| +| `CUBE`, `CAPSULE`, `CYLINDER`, `SPHERE` | Shape kinds 0-3, Strata's `STRATA_PRIMITIVE_*` | +| `Shape(kind, position, scale, color)` | An axis-aligned primitive; `scale` is its size along x, y, z | +| `Label(text, x, y, pixelSize, color=TEXT_COLOR)` | Screen text; `(x, y)` is the top-left of its first glyph | +| `Panel(x, y, width, height, color=(0, 0, 0, 0.6))` | A filled screen rectangle, drawn under every label | +| `Light(position, color, radius, intensity, castShadows=False)` | A point light. Strata takes a radius over 0 and no negative colour or intensity | +| `Camera(eye, target, fovDegrees=42.0)` | A right-handed look-at with +y up and a vertical field of view. It can't look straight up or down, or at its own eye | +| `Scene(shapes, labels, panels, lights, camera, clearColor)` | Everything one frame draws; `scene.checkLimits()` raises `SceneLimitError` | +| `SceneLimitError` | A `ValueError`: over `MAX_POINT_LIGHTS` (32) lights, over `MAX_SHADOWED_POINT_LIGHTS` (4) shadow casters, or an unknown shape kind | +| `TEXT_COLOR`, `DIM_TEXT_COLOR`, `CLEAR_COLOR` | Default colours | +| `rgb255(color)` | A 0-255 colour as 0-1 `(r, g, b)` | +| `rgba(color, alpha=1.0)` | `(r, g, b)` as `(r, g, b, alpha)` | +| `shade(color, factor)` | r, g and b scaled by `factor`, clamped to 0-1 | +| `fitText(text, width, pixelSize, margin=18)` | Text cut with `...` to fit `width` pixels (also in [Text](#text)) | + +```python +from preponderous.graphik.grid3d import CUBE, Camera, Label, Light, Scene, Shape, rgb255, rgba + +scene = Scene(camera=Camera(eye=(0, 8, 6), target=(0, 0, 0))) +scene.shapes.append(Shape(CUBE, (0, 0.25, 0), (1, 0.5, 1), rgba(rgb255((200, 60, 40))))) +scene.lights.append(Light((0, 2, 0), (1.0, 0.9, 0.7), radius=4.0, intensity=1.5)) +scene.labels.append(Label("Hello", 16, 16, 24)) +scene.checkLimits() +``` + +## Boards and pieces + +`board.py`: what is on each cell, and how it looks. + +| Name | What it is | +|---|---| +| `PieceStyle(kind, color, height, size, lift, glow, tones, extras)` | How one kind of piece looks. `glow=(radius, intensity)` adds a light above it; `tones=(odd, even)` shades a chain's links alternately; `extras(piece, x, z, baseY)` returns more `Shape`s placed relative to the piece | +| `Piece(id, column, row, style, scale, color, chain, link, facing, interpolate)` | Something on a cell. Keep `id` stable from tick to tick so it slides; `chain` and consecutive `link`s join orthogonal neighbours with a bridge; `interpolate=False` jumps | +| `Theme(tile, alternate, tileHeight, tileGap, frame, frameWidth, pieces, bridgeAcross, bridgeHeight, bridgeShade, highlight)` | The board's look; `pieces` maps a style name to a `PieceStyle`. `theme.style(name)` raises a `KeyError` naming the known styles | +| `Tile(color, raised=0.0)` | One cell's own tile (`GridBoard`'s `tiles`) | +| `Viewport(column, row, columns, rows)` | A window of a board; `Viewport.around(column, row, reach)` is the square around a cell; `contains(column, row)` | +| `GridBoard(columns, rows, theme=None, tiles=None, mergeTiles=False, viewport=None)` | A board drawn with a theme (below) | +| `cellCenter(column, row, columns, rows)` | World `(x, z)` of a cell's middle on a whole board | +| `fitCamera(columns, rows, aspect=1.0, fovDegrees=42.0, top=None, bottom=None)` | A camera south of the board that fits it in the window. A portrait window (aspect below 1) gets a steeper camera and a board that fills its width; between 0.8 and 1 the two framings blend. `top` and `bottom` are fractions of the window's height kept clear of the board (a HUD, a bar of touch keys) | +| `BED_TOP` | y of the tiles' top face (0.0); pieces stand on it | + +`GridBoard` methods: + +| Method | Returns | +|---|---| +| `scene(pieces, positions, labels, panels, lights, aspect, tint, clearColor, highlight, highlightColor, top, bottom)` | A complete `Scene`, lights checked; `highlight=(column, row)` lays a slab on that tile | +| `boardShapes(tint=None, tintAmount=0.55)` | The tiles and frame; `tint` blends every tile towards a colour | +| `pieceShapes(pieces, positions=None)` | `(shapes, lights)` for the pieces, at `positions` (id to world `(x, z)`) or on their cells | +| `highlightShapes(cell, color=None)` | The hover slab for one visible cell, or `[]` | +| `bridgePairs(pieces)`, `bridgeShape(a, b, aAt, bAt)` | The joined pairs of a chain in drawing order, and one bridge between two positions | +| `checkPieces(pieces)` | Raises `ValueError` (off the board, a duplicate id) or `KeyError` (unknown style) | +| `camera(aspect=1.0, top=None, bottom=None)` | `fitCamera` for what is on show | +| `cellCenter(column, row)`, `cellAt(x, z)` | Cell to world and back; `cellAt` is half-open (west and north edges in, east and south out) and `None` off the shown cells | +| `contains(column, row)`, `visible(column, row)` | On the board; on the board and in the viewport | +| `shownSize()`, `shownOrigin()` | The viewport's (or board's) size and top-left cell | +| `tileAt(column, row)`, `tileRaise(column, row)` | The `Tile` drawn on a cell (or `None` for a bare cell) and its raise | + +```python +from preponderous.graphik.grid3d import SPHERE, CUBE, GridBoard, Piece, PieceStyle, Shape, Theme, Tile + +def eyes(piece, x, z, baseY): # placed from (x, z): they move with the piece + return [Shape(SPHERE, (x + 0.2, baseY + 0.4, z - 0.3), (0.1, 0.1, 0.1), (1, 1, 1, 1))] + +theme = Theme(pieces={ + "head": PieceStyle(SPHERE, (0.2, 0.8, 0.3), extras=eyes), + "body": PieceStyle(CUBE, (0.1, 0.6, 0.2), tones=(0.9, 1.0)), +}) +board = GridBoard(14, 10, theme, tiles={(3, 3): Tile((0.2, 0.4, 0.8), raised=0.05)}, mergeTiles=True) +snake = [Piece("s0", 5, 5, "head", chain="s", link=0), Piece("s1", 5, 6, "body", chain="s", link=1)] +scene = board.scene(snake, aspect=900 / 700, highlight=(5, 4)) +``` + +## Animation + +`animate.py`. + +| Name | What it is | +|---|---| +| `Animator(cellCenter, reducedMotion=False, maxSlideCells=1.5)` | Slides each piece from where it was drawn to its new cell over one tick | +| `animator.update(pieces, now, tickSeconds, snap=False)` | Takes a tick's pieces at monotonic time `now`. A piece jumps when it is new, opted out, moved more than `maxSlideCells` (a diagonal step is 2), under reduced motion, or when `snap` is set. A tick of 0 or less (or NaN) places every piece at once | +| `animator.positions(now)` | id to world `(x, z)` at `now`; a time before the tick began gives its start | +| `animator.settled(now)` | True once every piece is on its cell | +| `animator.tracks` | id to `((x0, z0), (x1, z1))`, what the browser view sends | +| `interpolatePosition(start, end, alpha)` | `(x, z)` a fraction of the way, `alpha` clamped to 0-1 | + +```python +import time +from preponderous.graphik.grid3d import Animator, GridBoard, Piece + +board = GridBoard(8, 8) +animator = Animator(board.cellCenter) +animator.update([Piece(1, 0, 0, "pawn")], time.monotonic(), 0.15) +animator.update([Piece(1, 1, 0, "pawn")], time.monotonic(), 0.15) # next tick +x, z = animator.positions(time.monotonic())[1] # somewhere between +``` + +## Picking and projection + +`pick.py`: the same look-at and perspective the views ask Strata for. + +| Name | Returns | +|---|---| +| `pickCell(camera, board, x, y, width, height)` | The `(column, row)` under window pixel `(x, y)`, gaps between tiles included, or `None` (off the board, out of the viewport, above the horizon, or `x`/`y` is `None`) | +| `pickPoint(camera, x, y, width, height, planeY=BED_TOP)` | World `(x, z)` where that pixel's ray meets the plane, or `None` | +| `screenRay(camera, x, y, width, height)` | The ray's direction (not normalised) | +| `projectToScreen(camera, point, width, height)` | Window `(x, y)` of a world point, or `None` behind the camera | +| `cellScreenPosition(camera, board, column, row, width, height, y=BED_TOP)` | Where a cell's middle lands, `y` above the bed | + +A camera looking straight up or down, or with its eye on its target, raises +`ValueError`: Strata's look-at has no answer for those either, so tilt such a +camera a little. The views have the same calls bound to their own camera and +window: `view.camera()`, `view.pickCell(x, y)`, `view.projectToScreen(point)`, +`view.cellScreenPosition(column, row, y=0.0)`. + +```python +from preponderous.graphik.grid3d import GridBoard, cellScreenPosition, pickCell + +board = GridBoard(8, 8) +camera = board.camera(900 / 700) +cell = pickCell(camera, board, 450, 400, 900, 700) # what was tapped +note = cellScreenPosition(camera, board, 2, 3, 900, 700) # where to put a note +``` + +## Text + +`text.py`: Strata's built-in font is 8 x 8 and monospaced: every character +is one `pixelSize`-wide cell. A character outside printable ASCII (an +accented letter, an emoji) is drawn as one `?`, still one cell, so text is +measured in characters, not bytes. A NUL draws nothing on either backend. + +| Name | Returns | +|---|---| +| `measureText(text, pixelSize)` | The widest line's width in pixels | +| `fitText(text, width, pixelSize, margin=18)` | `text`, cut with `...` to fit | +| `wrapText(text, maxWidth, pixelSize)` | Lines, greedily word-wrapped; a word too long for a line stays whole on its own | +| `centredLabel(text, x, y, pixelSize, color=TEXT_COLOR, rise=0.5)` | A `Label` centred on `x`; `rise` places it on `y` (0.5 centres its cells, 0 puts its top there) | + +```python +from preponderous.graphik.grid3d import centredLabel, wrapText + +lines = wrapText("Eat the gems; avoid your own tail.", 300, 16) +labels = [centredLabel(line, 450, 200 + 20 * i, 16) for i, line in enumerate(lines)] +``` + +## Buttons and 2D screens + +`ui.py`: menus over a 3D view that behave like `Graphik`'s. Colours are 0-255. + +| Name | What it is | +|---|---| +| `Button(x, y, width, height, text, color, textColor, pixelSize=16, function=None, alpha=1.0, padding=None, rise=0.5)` | A screen button: `draw(pointer)` gives `(Panel, Label)` with the hover lift; `contains(position)` uses `drawButton`'s edges (left/top in, right/bottom out); `click(position)` runs `function`; `rect()` is the drawn box (widened by `padding` to fit its label) | +| `drawButtons(buttons, pointer=None)` | `([Label], [Panel])` for several buttons | +| `hoverColor(color)` | `drawButton`'s hover lift: light colours darken by 25, the rest lighten by 35 | +| `ScreenRecorder(width=800, height=600)` | Stands in for `Graphik` so a game's 2D screens run unchanged under a 3D view (below) | +| `RecordedText`, `RecordedRect`, `RecordedButton`, `RecordedImage` | What the recorder keeps for `drawText`, `drawRectangle`, `drawButton` and `drawImage` | +| `RecordedDisplay` | The recorder's `getGameDisplay()`: `get_size()`, `get_width()`, `get_height()`, `fill()` | + +`ScreenRecorder` answers every public call and colour constant `Graphik` +has: `drawText`, `drawRectangle`, `drawButton`, `drawImage` (recorded), +`beginFrame` and `endFrame` (nothing to do: the 3D view sends a press to +`click()` itself, once), `getGameDisplay`, `getVersion`, and `black`, +`white`, `red`, `green`, `blue`. Then `items` is the frame's calls in order, +`texts()`, `buttons()` and `images()` pick them out, `click(position)` runs +the first recorded button under `position`, and `reset()` starts the next +frame, `resize(width, height)` follows the window. + +```python +from preponderous.graphik.grid3d import Button, ScreenRecorder, drawButtons + +play = Button(350, 300, 200, 48, "Play", color=(40, 120, 60), textColor=(255, 255, 255), + pixelSize=20, function=lambda: print("play"), padding=12) +labels, panels = drawButtons([play], pointer=(400, 320)) +play.click((400, 320)) + +recorder = ScreenRecorder(900, 700) +mainMenu.draw(recorder) # a 2D screen that normally draws with Graphik +recorder.click((400, 320)) # runs that screen's own button function +``` + +## Touch keys + +`touchkeys.py`: a bar of on-screen keys along the bottom of a touch screen, +drawn alike in 2D (with `Graphik`) and 3D (as HUD panels and labels) from one +layout and one hit test. Sizes are CSS pixels; `scale` is a surface's CSS +pixels per pixel (1 for the web view). + +| Name | What it is | +|---|---| +| `TouchKey(label, key)` | One key: its label and the key it presses, by pygame's name (`"p"`, `"space"`, `"up"`, `"escape"`) | +| `TouchKeys(keys, minTarget=44, gap=6, margin=8, pixelSize=11, padding=6, portraitRows=3, landscapeRows=1, ...)` | The bar: rows of equal buttons, each at least `minTarget` each way. When the keys don't all fit, the last button is *More* (*Back* on the last page) | +| `keys.setKeys(keys)` | Changes the keys on offer (back to the first page) | +| `keys.layout(width, height, scale=1.0)` | The `KeySlot`s as laid out | +| `keys.bandHeight(width, height, scale=1.0)` | How much of the screen the bar takes, for `view.setInsets(bottom=...)` | +| `keys.below(width, height, pageWidth, pageHeight)` | The band a 2D game adds under its board, and the canvas's scale once the browser fits it to the page | +| `keys.press(position, width, height, pygame, scale=1.0)` | Posts the key's `KEYDOWN` and `KEYUP` (marked `touchKey=True`) and returns the `TouchKey`, `MORE` for More/Back, or `None` off the bar | +| `keys.draw(graphik, width, height, scale=1.0, pointer=None)` | Draws the bar in 2D | +| `keys.overlay(width, height, pointer=None)` | `(labels, panels)` for the 3D view's HUD | +| `keys.buttons(width, height)`, `keys.slotAt(position, width, height, scale=1.0)`, `TouchKeys.keyEvents(key, pygame)` | The bar as `Button`s (CSS pixels); the `KeySlot` under a point; the `KEYDOWN`/`KEYUP` pair a key posts | +| `KeySlot` | A laid-out button: `x`, `y`, `width`, `height`, `label`, `key`, `contains(position)` | +| `MIN_TARGET`, `MORE` | 44 (CSS pixels), and what `press()` returns for More | + +```python +from preponderous.graphik.grid3d import TouchKey, TouchKeys +from preponderous.graphik.grid3d import web + +keys = TouchKeys([TouchKey("Pause", "space"), TouchKey("Shop", "p")]) +if web.touchScreen(): + view.setInsets(top=40, bottom=keys.bandHeight(390, 844)) + labels, panels = keys.overlay(390, 844) # add to the HUD + # on a tap: + if keys.press(position, 390, 844, pygame) is None: + handle(position) # not on the bar: the game's +``` + +## The desktop view + +`view.py`. Linux and Windows x64; anywhere else `open()` raises +`Unavailable`. + +| Name | What it is | +|---|---| +| `Grid3DView.open(width=900, height=700, title="graphik", headless=False, reducedMotion=False, clock=time.monotonic)` | A window, or a headless surface for tests and screenshots. Under pygbag it returns a `Grid3DWebView` instead | +| `view.setBoard(board, tint=None, lights=())` | The static part, when the board, theme or tint changes | +| `view.setPieces(pieces, tickSeconds=0.0, snap=False)` | Once per game tick | +| `view.setLabels(labels=(), panels=())` | When the HUD changes | +| `view.setInsets(top=None, bottom=None)` | Pixels at the top (a HUD) and bottom (touch keys) kept clear of the board; the camera, picking and `cellScreenPosition` follow. Returns whether anything changed | +| `view.frame(now=None, present=True)` | Draws one frame (pieces where they are at `now`) | +| `view.scene(now=None)` | The `Scene` that frame would draw | +| `view.drawScene(scene, present=True)` | Draws a `Scene` a game built itself | +| `view.pollEvents()` | Every pending Strata event (`view.EVENT_QUIT`, `EVENT_KEY_DOWN`, `EVENT_KEY_UP`, `EVENT_RESIZED`, ...) | +| `view.resize(width, height)`, `view.savePng(path)`, `view.close()` | | +| `Unavailable` | Why 3D can't run here, in words a player can act on | +| `STRATA_VERSION` | The Strata release the binding loads (`STRATA_LIBRARY` points at a local build instead) | + +```python +from preponderous.graphik.grid3d import Grid3DView, Unavailable + +try: + view = Grid3DView.open(900, 700, "My game") +except Unavailable as reason: + view = None # keep the 2D view, and say why +if view: + view.setBoard(board) + while running: + for event in view.pollEvents(): + if event.type == view.EVENT_QUIT: + running = False + if tick(): + view.setPieces(pieces(), tickSeconds=0.15) + view.frame() + view.close() +``` + +## The browser view + +`web.py`: under pygbag, the page's Strata grid relay draws what a desktop +view would. Build the page with `pygbag --template ` and copy +the relay next to it ([Fetching the relay](#fetching-the-relay)). + +| Name | What it is | +|---|---| +| `Grid3DWebView` | `Grid3DView`'s calls (`setBoard`, `setPieces`, `setLabels`, `frame`, `scene`, `drawScene`, `pollEvents`, `resize`, `close`, picking) drawn by the relay. `frame()` does nothing: the page slides pieces itself. `drawScene()` sends only what changed. `savePng()` raises `Unavailable` | +| `Grid3DWebView.open(width, height, title, relay=None, maxBytes=4000000, reducedMotion=None, clock, canvas="relay")` | Asks the page for its 3D view; raises `Unavailable` when there is none or it failed | +| `view.ready`, `view.failure()` | Loaded yet; why it couldn't load | +| `templatePath(defaultView="3d")` | The pygbag page template, starting in 3D (or 2D) unless `?view=` or the player's last choice says otherwise | +| `wants3D()` | The page's 2D/3D button is on and the relay's scripts are in: time to `open()` | +| `set3D(on, reason="")` | Turns the button on or off; off with a reason marks 3D unavailable | +| `buttonArea()` | The button's `(x, y, width, height)` in CSS pixels, for keeping HUD text clear, or `None` | +| `touchScreen()` | The page is on a touch screen (a coarse pointer, or a touch seen; `?touch=1`/`?touch=0` overrides; `GRAPHIK_TOUCH=1` outside a browser): time to show `TouchKeys` | +| `parseArea(text)` | `"x,y,width,height"` as a tuple, or `None` | +| `pageObject(name)` | `window.` under pygbag, or `None` | +| `toPygameEvents(events, pygame, keys=False, pointer=True, fingers=True)` | Relay (or desktop Strata) events as pygame events, so 2D input code runs unchanged. Keys are off by default: pygbag's SDL already gets them | +| `pygameKey(scancode, pygame)` | The pygame key for a USB HID scancode, or 0 | +| `Event` | A relay event: `type`, `scancode`, `modifiers`, `repeat`, `button`, `width`, `height`, `x`, `y`, `dx`, `dy`, `text`, `pointer`, `id`, `nx`, `ny`, `key`, `pressure` | +| `EVENTS`, `EVENT_*` | Event type numbers, Strata's and the web's `FINGER_*` | +| `PlatformRelay(relay=None)` | The transport to the page's `window.StrataGridRelay` | +| `RecordingRelay(reducedMotion=False, state="ready")` | A transport that keeps what it is sent: for tests, and `wireJson()` for the relay's test page | + +```python +from preponderous.graphik.grid3d import Grid3DView, Unavailable +from preponderous.graphik.grid3d import web + +view = None +def follow(): # call once per frame + global view + if web.wants3D() and view is None: + try: + view = Grid3DView.open(900, 700, "My game") # a Grid3DWebView here + view.setBoard(board) + except Unavailable as reason: + web.set3D(False, str(reason)) + elif not web.wants3D() and view is not None: + view.close() + view = None + if view is not None: + for event in web.toPygameEvents(view.pollEvents(), pygame): + handle(event) # the game's own 2D handler +``` + +The page goes back to 2D by itself, with the reason on screen, when 3D can't +start or when its drawing stays too slow once the game draws in it (for 5 +seconds the typical frame and the kit's average frame are over 66 ms and the +relay's own drawing at least a quarter of the typical frame, with Strata's kit at its lowest tier and pixel density 1; +the game's own pauses don't count); the +latter is not remembered, the button brings 3D back, and `?slow=0` in the +address turns it off. + +The button is a switch showing both views, *2D* and *3D*, with the one on +show lit: a toggle named "3D view", `aria-pressed` while 3D is on, at least +44 CSS pixels each way. `buttonArea()` measures it as drawn. + +## The wire format + +The messages `Grid3DWebView` sends, as functions: Strata's +`web/kit/grid-relay/WIRE.md` is the specification (format 1.0). + +| Name | What it is | +|---|---| +| `encodeBoard(shapes, lights=())`, `encodePieces(board, pieces, tracks, tickSeconds)`, `encodeHud(labels=(), panels=())`, `encodeView(camera, clearColor, sun, near, far)` | One message each. They raise `WireError` for anything the relay would refuse, with the relay's status: counts over its limits (-6), and a non-finite number, a coordinate past ±10⁶, a light with no radius or a negative colour or intensity, a HUD colour with a negative part or alpha over 1, or a camera with its eye on its target (-5) | +| `decode(message)` | `(kind, contents)`, with the relay's checks: for tests and tools | +| `readHeader(message)` | `(major, minor, kind)`, or `WireError` as the relay says it | +| `header(kind)` | The 8-byte header | +| `WireError` | A `ValueError` with the relay's `status` (`STATUS` maps it to words) | +| `WIRE_MAJOR`, `WIRE_MINOR`, `MAGIC`, `BOARD`, `PIECES`, `HUD`, `VIEW`, `WORLD`, `PIECE`, `BRIDGE` | Format constants | +| `MAX_SHAPES`, `MAX_ANCHORS`, `MAX_LIGHTS`, `MAX_SHADOWED_LIGHTS`, `MAX_HUD_ITEMS`, `MAX_COORDINATE` | The relay's limits | +| `SUN_DIRECTION`, `NEAR_PLANE`, `FAR_PLANE` | The desktop view's, sent with every view | + +The encoder is held to golden bytes +(`src/test/python/preponderous/graphik/grid3d/golden/wire-1.0.hex`) that +Strata's relay tests read with its own parser, so the two sides can't drift +apart unnoticed. + +```python +from preponderous.graphik.grid3d import Label +from preponderous.graphik.grid3d import web + +message = web.encodeHud([Label("Score 3", 12, 8, 16)]) +kind, hud = web.decode(message) +assert kind == web.HUD and hud["labels"][0]["text"] == "Score 3" +``` + +## Fetching the relay + +`relay.py`, run after `pygbag --build`: + +```bash +python -m preponderous.graphik.grid3d.relay --strata 0.9.0 --dest build/web [--replace] +``` + +It downloads `strata--wasm32-emscripten.tar.gz` and the release's +`SHA256SUMS`, checks the tarball's SHA-256 (refusing a missing, malformed or +contradictory line), checks every member under `kit/grid-relay/dist/` before +writing anything (no links or devices, nothing outside `--dest`, even through +a link inside it, under 64 MB in all) and copies them next to the page. Files +already there are kept; with `--replace` the relay's own files are replaced +(after moving to a newer Strata) and only `index.html`, the game's page, is +kept. Only a release version (`0.9.0`, `1.0.0-rc.1`) is taken for `--strata`. + +| Name | What it is | +|---|---| +| `fetchRelay(version, dest, base=RELEASES, download=None, replace=False)` | The whole fetch; returns `(copied, skipped)` | +| `extractDist(data, dest, prefix=DIST, replace=False)` | Unpacks a tarball's relay folder | +| `verify(data, sums, name)`, `expectedDigest(sums, name)` | The checksum check | +| `tarballName(version)` | The release asset's name | +| `RelayFetchError` | Why it couldn't fetch, verify or unpack | +| `main(argv=None)` | The command line | diff --git a/src/main/python/preponderous/graphik/_version.py b/src/main/python/preponderous/graphik/_version.py index 7225152..43a1e95 100644 --- a/src/main/python/preponderous/graphik/_version.py +++ b/src/main/python/preponderous/graphik/_version.py @@ -1 +1 @@ -__version__ = "0.5.2" +__version__ = "0.5.3" diff --git a/src/main/python/preponderous/graphik/grid3d/__init__.py b/src/main/python/preponderous/graphik/grid3d/__init__.py index 83aa2b8..8563c55 100644 --- a/src/main/python/preponderous/graphik/grid3d/__init__.py +++ b/src/main/python/preponderous/graphik/grid3d/__init__.py @@ -14,6 +14,8 @@ stand-in for running 2D screens under a 3D view (ui.py), and a bar of on-screen keys for touch screens, drawn alike in 2D and 3D (touchkeys.py). +The API reference, with an example for each part, is docs/grid3d.md. + Importing this package imports neither Strata nor pygame. """ @@ -57,6 +59,7 @@ Button, RecordedButton, RecordedDisplay, + RecordedImage, RecordedRect, RecordedText, ScreenRecorder, @@ -76,7 +79,7 @@ "Camera", "Label", "Light", "Panel", "Scene", "SceneLimitError", "Shape", "fitText", "rgb255", "rgba", "shade", "centredLabel", "measureText", "wrapText", - "Button", "RecordedButton", "RecordedDisplay", "RecordedRect", "RecordedText", + "Button", "RecordedButton", "RecordedDisplay", "RecordedImage", "RecordedRect", "RecordedText", "ScreenRecorder", "drawButtons", "hoverColor", "MIN_TARGET", "MORE", "KeySlot", "TouchKey", "TouchKeys", "STRATA_VERSION", "Grid3DView", "Unavailable", diff --git a/src/main/python/preponderous/graphik/grid3d/pick.py b/src/main/python/preponderous/graphik/grid3d/pick.py index b4a1402..3510d0b 100644 --- a/src/main/python/preponderous/graphik/grid3d/pick.py +++ b/src/main/python/preponderous/graphik/grid3d/pick.py @@ -34,9 +34,19 @@ def _unit(a): def cameraBasis(camera): - """(forward, right, up) unit vectors of a Camera.""" - forward = _unit(_sub(camera.target, camera.eye)) - right = _unit(_cross(forward, (0.0, 1.0, 0.0))) + """(forward, right, up) unit vectors of a Camera. ValueError for a + camera that looks nowhere (its eye on its target) or straight up or + down: Strata's look-at, with +y up, has no right or up for those either, + so they draw nothing on the desktop; tilt the camera a little instead.""" + view = _sub(camera.target, camera.eye) + if _dot(view, view) == 0.0: + raise ValueError("the camera's eye is on its target, so it looks nowhere") + forward = _unit(view) + side = _cross(forward, (0.0, 1.0, 0.0)) + if _dot(side, side) < 1e-12: + raise ValueError("the camera looks straight %s; tilt it a little (Strata's look-at " + "has +y up)" % ("down" if forward[1] < 0 else "up")) + right = _unit(side) return forward, right, _cross(right, forward) diff --git a/src/main/python/preponderous/graphik/grid3d/relay.py b/src/main/python/preponderous/graphik/grid3d/relay.py index 80eee58..3819f0a 100644 --- a/src/main/python/preponderous/graphik/grid3d/relay.py +++ b/src/main/python/preponderous/graphik/grid3d/relay.py @@ -13,8 +13,10 @@ against it, and copies kit/grid-relay/dist/ into `--dest`, next to the page pygbag built from grid3d's template (web.templatePath()). Files that already exist there (pygbag's own index.html, say) are left alone, so the -relay's test page never replaces the game's. Nothing of the relay is -downloaded by a player until the page's 3D toggle asks for it. +relay's test page never replaces the game's; with --replace (after moving to +a newer Strata into a folder an older relay was copied to) the relay's own +files are replaced, and only index.html is still kept. Nothing of the relay +is downloaded by a player until the page's 3D toggle asks for it. Standard library only. """ @@ -24,6 +26,7 @@ import io import os import posixpath +import re import shutil import sys import tarfile @@ -31,6 +34,13 @@ RELEASES = "https://github.com/Preponderous-Software/strata/releases/download" DIST = "kit/grid-relay/dist/" +# A Strata release version as its tags spell them (0.9.0, 1.0.0-rc.1): it goes +# into the download URL, so nothing else is taken. +VERSION = re.compile(r"^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$") +# Never replaced, even with replace=True: the game's own page. +KEEP = ("index.html",) +# The relay's dist/ is about 1.5 MB; anything far bigger is not a relay. +MAX_DIST_BYTES = 64 * 1000 * 1000 class RelayFetchError(Exception): @@ -38,6 +48,8 @@ class RelayFetchError(Exception): def tarballName(version): + if not VERSION.match(str(version)): + raise RelayFetchError("%r is not a Strata release version (like 0.9.0)" % (version,)) return "strata-%s-wasm32-emscripten.tar.gz" % version @@ -48,12 +60,21 @@ def _download(url): def expectedDigest(sums, name): - """The SHA-256 a SHA256SUMS text gives for `name`.""" + """The SHA-256 a SHA256SUMS text gives for `name`: refused when it has + none, more than one that disagree, or one that isn't a SHA-256.""" + found = set() for line in sums.splitlines(): parts = line.strip().split() if len(parts) == 2 and parts[1].lstrip("*").split("/")[-1] == name: - return parts[0].lower() - raise RelayFetchError("SHA256SUMS has no line for %s" % name) + found.add(parts[0].lower()) + if not found: + raise RelayFetchError("SHA256SUMS has no line for %s" % name) + if len(found) > 1: + raise RelayFetchError("SHA256SUMS has different digests for %s" % name) + digest = found.pop() + if not re.match(r"^[0-9a-f]{64}$", digest): + raise RelayFetchError("SHA256SUMS's digest for %s isn't a SHA-256: %r" % (name, digest)) + return digest def verify(data, sums, name): @@ -63,14 +84,16 @@ def verify(data, sums, name): raise RelayFetchError("%s's SHA-256 is %s, SHA256SUMS says %s" % (name, digest, expected)) -def extractDist(data, dest, prefix=DIST): +def extractDist(data, dest, prefix=DIST, replace=False): """Copy the tarball's `prefix` tree into `dest`; returns (copied, - skipped) relative paths. Existing files are skipped, and members that - aren't plain files and directories, or would land outside `dest`, are - refused.""" - copied, skipped = [], [] + skipped) relative paths. Existing files are skipped (with `replace`, only + index.html is), and members that aren't plain files and directories, or + would land outside `dest`, are refused. Every member is checked before + anything is written, so a refused tarball leaves `dest` as it was.""" dest = os.path.abspath(dest) + realDest = os.path.realpath(dest) with tarfile.open(fileobj=io.BytesIO(data), mode="r:gz") as archive: + plan, total = [], 0 for member in archive.getmembers(): name = member.name[2:] if member.name.startswith("./") else member.name if prefix in name + "/" and (".." in name.split("/") or name.startswith("/")): @@ -86,26 +109,38 @@ def extractDist(data, dest, prefix=DIST): if relative.startswith("../") or os.path.isabs(relative) or "/../" in "/" + relative: raise RelayFetchError("refusing %s: outside the relay's folder" % member.name) target = os.path.abspath(os.path.join(dest, relative)) - if not target.startswith(dest + os.sep): + # resolved too, so a folder in `dest` that is a link elsewhere + # can't carry a file out of it + if not target.startswith(dest + os.sep) or not os.path.realpath(target).startswith(realDest + os.sep): raise RelayFetchError("refusing %s: outside %s" % (member.name, dest)) + if not member.isdir() and not member.isfile(): + raise RelayFetchError("refusing %s: not a plain file" % member.name) + total += member.size + if total > MAX_DIST_BYTES: + raise RelayFetchError("refusing the tarball: over %d MB under %s" + % (MAX_DIST_BYTES // 1000000, prefix)) + plan.append((member, relative, target)) + if not plan or all(member.isdir() for member, _, _ in plan): + raise RelayFetchError("the tarball has nothing under %s" % prefix) + copied, skipped = [], [] + for member, relative, target in plan: if member.isdir(): os.makedirs(target, exist_ok=True) continue - if not member.isfile(): - raise RelayFetchError("refusing %s: not a plain file" % member.name) - if os.path.exists(target): + if os.path.lexists(target) and (not replace or relative in KEEP + or not os.path.isfile(target) or os.path.islink(target)): + # with replace, only a plain file is written over: never a + # link (which could point anywhere) or a folder skipped.append(relative) continue os.makedirs(os.path.dirname(target), exist_ok=True) with archive.extractfile(member) as source, open(target, "wb") as out: shutil.copyfileobj(source, out) copied.append(relative) - if not copied and not skipped: - raise RelayFetchError("the tarball has nothing under %s" % prefix) return copied, skipped -def fetchRelay(version, dest, base=RELEASES, download=None): +def fetchRelay(version, dest, base=RELEASES, download=None, replace=False): """Download, verify and unpack Strata `version`'s grid relay into `dest`. Returns (copied, skipped).""" download = download or _download @@ -118,7 +153,7 @@ def fetchRelay(version, dest, base=RELEASES, download=None): raise RelayFetchError("couldn't download Strata %s's release: %s" % (version, error)) verify(data, sums, name) os.makedirs(dest, exist_ok=True) - return extractDist(data, dest) + return extractDist(data, dest, replace=replace) def main(argv=None): @@ -127,16 +162,20 @@ def main(argv=None): description="Copy Strata's prebuilt grid relay next to a pygbag build.") parser.add_argument("--strata", required=True, help="Strata release version, e.g. 0.9.0") parser.add_argument("--dest", required=True, help="the pygbag output folder (build/web)") + parser.add_argument("--replace", action="store_true", + help="replace relay files already in --dest (never index.html)") parser.add_argument("--base", default=RELEASES, help=argparse.SUPPRESS) args = parser.parse_args(argv) try: - copied, skipped = fetchRelay(args.strata, args.dest, args.base) + copied, skipped = fetchRelay(args.strata, args.dest, args.base, replace=args.replace) except RelayFetchError as error: print("grid relay: %s" % error, file=sys.stderr) return 1 print("grid relay: Strata %s, %d files copied to %s" % (args.strata, len(copied), args.dest)) for path in skipped: print("grid relay: kept the existing %s" % path) + if any(path not in KEEP for path in skipped): + print("grid relay: files of an earlier relay were kept; --replace replaces them", file=sys.stderr) return 0 diff --git a/src/main/python/preponderous/graphik/grid3d/templates/pygbag.tmpl b/src/main/python/preponderous/graphik/grid3d/templates/pygbag.tmpl index 8a40f05..538e109 100644 --- a/src/main/python/preponderous/graphik/grid3d/templates/pygbag.tmpl +++ b/src/main/python/preponderous/graphik/grid3d/templates/pygbag.tmpl @@ -429,7 +429,6 @@ frameborder="1" -