Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 38 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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.4.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.

Expand Down
7 changes: 7 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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.8.0#subdirectory=bindings/python",
]

[project.urls]
Homepage = "https://github.com/Stephenson-Software/graphik"
Expand Down
2 changes: 1 addition & 1 deletion src/main/python/preponderous/graphik/_version.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "0.3.0"
__version__ = "0.4.0"
46 changes: 46 additions & 0 deletions src/main/python/preponderous/graphik/grid3d/__init__.py
Original file line number Diff line number Diff line change
@@ -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",
]
80 changes: 80 additions & 0 deletions src/main/python/preponderous/graphik/grid3d/animate.py
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading