Debug tooling
JSON snapshots for agents, the canvas overlay drawn with pixi-silk, and SpinMetrics timings.
A reel set draws to a canvas, and a canvas keeps its secrets. When a reel lands one cell off, or a tease feels too short, or a symbol pokes out of its mask on one device, the picture tells you something is wrong but not what the engine thinks is happening. Worse, two of the people who most need to know cannot see the canvas at all: a CI runner asserting on a headless spin, and an AI agent working through a console. A QA tester has the opposite problem. They can see the picture but have no way to read the engine's state without opening the source.
So the debug tooling comes in two halves, built for those two audiences. The first is data only. debugSnapshot() returns plain JSON with no PixiJS types and no cycles, debugGrid() returns an ASCII table, and enableDebug() puts both on window so anyone with a console can type __PIXI_REELS_DEBUG.log() and read the board. That half lives in the main entry and was the first debug tool the library had (ADR 006). The second half draws: an overlay that paints what the engine knows, cells, buffers, axes, phases, a timeline, straight onto the canvas for a human to look at. It lives in a separate subpath, pixi-reels/debug, because it depends on a renderer (ADR 022, docs/adr/022-debug-subpath-on-pixi-silk.md), and the main entry must never pull one in. The debugging guide shows both in use; this page is how they are built.
Who needs which half
It is worth being concrete about the two audiences, because they shape every design choice below. An AI agent driving a browser, or a Playwright test, cannot interpret pixels reliably and should not try. What it needs is a question it can ask and an answer it can compare: "what is in cell (2, 1) right now?", "is reel 4 still spinning?", "in what order did the reels land?". Plain JSON answers those directly, survives JSON.stringify for a log line, and can be diffed between a good run and a bad one. That is why the snapshot has no PixiJS objects in it: a Sprite in the output would make it circular and useless the moment it left the page. The library's own browser suite asserts through this global rather than through screenshots, for the same reason.
A QA person or a developer has the opposite need. They are already looking at the game, and what they lack is the engine's version of the picture laid over the real one: where the mask edge actually is, which cells the engine thinks are visible, which way each reel is travelling, how long the tease on reel 5 really lasted compared with reel 4. A painted overlay answers in a glance what would take minutes of reading numbers, and the timeline panel turns "it felt wrong" into "reel 3 stopped 120 ms late". The two halves agree by construction: the overlay and describe() compute from the same helpers, so a tester and an agent looking at the same spin see the same facts.
Two halves
Figures 1 and 2 show the two halves side by side. Both only read from the ReelSet: its events through the wildcard listener onAny, and its geometry through getCellBounds, getCellQuad, the reels, the pins and the viewport. In figure 1 the dashed "reads" edge is the only connection between the debug global and the set; everything under it is a transformation of what it read.
Figure 2 is the drawing half. debugOverlay() is the entry point; it owns twelve drawn layers and leans on three helpers: SpinMetrics for timing (it creates one, or borrows the one you pass), DebugPlaque for the two text panels, and a pair of small drawing utilities for dashed rounded rectangles and paylines.
The main-entry tools
The snapshot is the heart of the data half, so here is its shape. Think of it as "everything a test would want to assert on, at one instant", with the visible grid pulled out as a convenience because that is what most assertions compare.
| DebugSnapshot field | Meaning |
|---|---|
| timestamp, isSpinning, currentSpeed, availableSpeeds, spotlightActive | When it was taken and the set-level flags: is anything moving, which speed profile is active, which are registered, is a spotlight up. |
| reelCount, visibleCells: number[] | How many reels, and how many cells each one shows. One entry per reel (a breaking change since v0.3), because jagged and MultiWays boards differ per reel. |
| reels: DebugReelSnapshot[] | Per reel: index, speed, isStopping, orientation, direction, allSymbols as { cell, symbolId, main }[] and visibleSymbols. main is the rounded position along the travel axis; it used to be a hard-coded y, which read 0 on horizontal sets. |
| grid: string[][] | The visible board, reel-major, from reelSet.getVisibleGrid(). Cells covered by a big symbol show the anchor's id. |
enableDebug(reelSet, key?) is how a page exposes that snapshot to the outside. It installs a small object on window.__PIXI_REELS_DEBUG and, so that pages with several sets can address each one, also under __PIXI_REELS_DEBUG_INSTANCES[key]; the key defaults to reelset_<n> and the bare global always points at the most recently enabled set. Enabling also starts a SpinMetrics recorder for that set (one per set, kept in a WeakMap so a second call reuses it) without a ticker, so rounds are recorded from that moment on but speed is not sampled. These are the global's methods.
| __PIXI_REELS_DEBUG | Returns |
|---|---|
| snapshot() | debugSnapshot(reelSet): the JSON above. |
| grid() | debugGrid(reelSet): an ASCII box table with 8-character columns, blank cells for jagged reels, and '(empty grid)' for an empty set. |
| log() | Prints the spinning flag, the speed and the grid to the console and returns the snapshot. |
| trace() | Logs every set-bus event through onAny and returns a function that stops the trace. |
| metrics() | SpinMetrics.snapshot(): the rounds recorded since enableDebug() was called. |
| startRecording(), stopRecording() | The frame recorder, below. |
The frame recorder
Sometimes one snapshot is not enough and you want the story of a spin: what the board looked like at each landing. The recorder does that without you writing listeners. startRecording(reelSet, tag, { maxFrames }) captures a snapshot on spin:start, spin:reelLanded, spin:allLanded and spin:complete, each wrapped as { tag, trigger, snapshot }, and detaches itself when the set is destroyed. getFrames(tag?) hands back a copy, filtered by tag if you give one; stopRecording(reelSet) and clearFrames() complete the set. Two things to know: calling startRecording twice on one set replaces the first recorder, and the buffer is a single process-wide rolling log capped at 1000 frames (DEFAULT_MAX_FRAMES), so maxFrames changes that cap for everyone, not per session.
The overlay
debugOverlay(reelSet, options) in debug/debugOverlay.ts returns a handle and starts drawing. What it draws is organised as twelve layers you can switch on and off independently, listed in the table below in draw order. The first six are geometry (where the mask, cells, buffers, wrap lines, travel axes and feed edges are); the next three follow symbols (their real bounds, big-symbol blocks, pin overlays); the last three are text panels (a per-reel HUD, a metrics plaque and a timeline). The "makes visible" column is the reason each layer exists.
Three terms from the motion pages, in case you arrived here first. The pitch is the distance from one cell to the next along the travel axis. The wrap lines (thresholds) are the two positions where a symbol that scrolls past is moved to the other end of the strip. The feed edge is the end of the strip where new symbols enter; it is derived from the reel's direction and must agree with the axis arrow, which is why both are drawn.
| Layer | Colour | Draws | Makes visible |
|---|---|---|---|
| mask | red | A 2px box around the viewport mask, plus dashed green per-reel maskRects. | What the viewport clips; whether the strategy is shared or per reel. |
| cells | cyan | Every visible cell from getCellBounds, or the trapezoid from getCellQuad on a curved reel, each with a "reel,cell" chip. | Cell geometry and indexing (visibleCells per reel). |
| buffers | amber, dashed, alpha 0.6 | The bufferStart and bufferEnd cells, following the drum curve. | Buffer indexing: which off-screen slots exist. |
| thresholds | red, dashed | The two wrap lines at main = -(bufferStart + 1) × pitch and (visibleCells + bufferEnd) × pitch. | L7 periodicity and L9 boundedness of the motion contract. |
| axis | green | One arrow per reel from 20% to 80% of the span, pointing by polarity; reversed reels point backwards. | Travel direction per reel. |
| feed | sky | A bar at the feed edge, derived from polarity. It must agree with the axis arrow. | L14, the feed edge: where new symbols enter. |
| bounds | pink | World getBounds() of every visible symbol, mapped to local space. | Spine or sprite overrun past the cell. |
| blocks | yellow | Big-symbol getBlockBounds, drawn once at the anchor. | Block geometry and anchoring. |
| pins | purple | The pin cell outline plus a green diagonal cross on the overlay. | A cross off its cell means movePin and the overlay disagree. |
| hud | plaque | A DebugPlaque in the mask top-left: one row per reel, r<i> VF feed=... spd=... <phase> cells=..., with a phase swatch and a |speedNormalized| meter. | Live per-reel state without a console. |
| metrics | plaque, 232px | A fixed-width plaque below the mask: title ROUND n profile live|skipped|done [boosted]; rows time (first stop), land order (max gap), tease per reel, skip (mode, reels, partial, @t, ×count or queued), swaps and events, fps/pins/spotlight, wins/chains. Placeholder rows before the first round keep its height fixed. | The SpinMetrics round as text. |
| timeline | panel | Below the mask: a legend of phases seen, a time grid (niceStep), one lane per reel (7px lanes, 4px gaps) with phase spans, an amber tease underline, a speed polyline clamped to 1.25 and downsampled to about a point per pixel, a tick at stoppingAt and a dot at landedAt, dashed skip lines (slam red, quicken yellow) and a live cursor. Minimum span 500 ms. | Stagger, tease and skip timing per reel. |
The options are few. layers is a list of layer names or 'all' (the default). live (default false) makes the symbol-following layers redraw every frame rather than on events; when live, ticker is the clock to redraw on, defaulting to Ticker.shared, and you should pass the set's own ticker or a FakeTicker to stay in lock-step. metrics lets you hand in a SpinMetrics you own; without one the overlay records its own from now on, sampling speed on the live ticker, and destroys it with itself.
Figure 3 shows when things are redrawn, which matters for cost. The geometry layers only change when the board changes shape, so they are cleared and redrawn together on redraw(), setLayers() and the geometry events. The six on the right are the ones that move: when live they follow the ticker; when not live, the three panels follow every set event and the three symbol layers wait for an explicit redraw().
The handle you get back has setLayers(), redraw(), describe(), metrics, destroy() and isDestroyed. Layers you switch off are cleared and hidden, and the overlay destroys itself when the set emits destroyed, so there is nothing to clean up in the common case. describe() is the bridge back to the data half: it returns a DebugOverlaySnapshot { layers, reels, round } where each reel entry carries its orientation, direction, feedEdge, a signed axisArrow { fromMain, toMain }, feedMain, thresholds { start, end }, visibleCells and current phase. The drawing code and describe() share the same helpers (_arrowMains, _feedMain), so the picture and the numbers cannot disagree. A reel's phase is tracked from its phase:enter and phase:exit events because there is no reel.phase accessor to read. Nudge draws pink; the other phase colours come from PHASE_CARD_COLORS in symbols/PhaseCardSymbol.ts, so the overlay matches the phase-card demo symbols.
Where it sits: the root container is added to the ReelSet at zIndex 1_000_000 with eventMode 'none', so it never intercepts a pointer, and it is labelled OVERLAY_LABEL = 'pixi-reels:debugOverlay'; each layer is labelled pixi-reels:debugOverlay:<layer> and z-ordered by its index times 10. The metrics and timeline panels sit side by side when the mask leaves at least TIMELINE_MIN_WIDTH = 200 px beside the 232 px metrics plaque, otherwise they stack, with a PANEL_GAP of 8. Both panels are outside the mask, which means they enlarge the reel set's bounds: re-fit your camera after enabling them, or the board will look as if it jumped.
DebugPlaque
The HUD and metrics panels are both a DebugPlaque: rows of monospace Text on a SilkGraphics plate, in DEBUG_FONT ("Fira Code" with fallbacks). One design choice makes it cheap enough to update every frame and deterministic in headless tests: its size is computed from character count times MONO_ADVANCE = 0.6em, not by measuring rendered text. The API is small: update(opts) merges options, setRows() replaces the rows, a text getter and setter make it a drop-in for a plain Text, and plateWidth and plateHeight report its size. After destroy() later writes are ignored. The options are below.
| DebugPlaque option | Default / meaning |
|---|---|
| title, rows, text | rows are strings or { text, color, swatch, meter 0-1, meterColor }; text is a drop-in for a Text |
| fontSize, color, fill, fillAlpha | 11, 0xe7e5e4, 0x0b0e14, 0.84 |
| radius | fontSize × 0.7, or 'pill' |
| padding, anchor, align, minWidth, maxWidth | maxWidth enables word wrap |
| reserveRows, shadow, accent | shadow defaults to true; hitArea and boundsArea exclude it |
Two small helpers round out the subpath. roundRectPath(g, x, y, w, h, radius = 0) traces a rounded rectangle as a closed path with quadratic corners, which exists only because pixi-silk 0.1 cannot dash a rect or roundRect stroke; the radius is clamped to half the width and height, and since strokes are centred on the line you inset by half the stroke width. ADR 022 says it goes once silk dashes rect strokes itself. WinLines draws a payline through one cell per reel, or a payway joining every winning cell to every winning cell on the next reel, at the cell centres from getCellBounds(); it reads the cells at draw time, so a board that grew is drawn where it is now.
SpinMetrics
SpinMetrics is the stopwatch behind the metrics plaque and the timeline, and it is also what metrics() on the global returns. It is purely event-driven: it attaches an onAny listener to the set bus and to every reel bus, stamps the time whenever something happens, and costs nothing between spins. It follows reels:added and reels:removed so an expanding board keeps being measured, and destroys itself on destroyed.
Its unit of record is the round: everything from one spin:start to the next. Because a cascade refill emits spin:start too, every refill stage is its own round, which is usually what you want when you are timing a tumble. Figure 4 is one reel's lane in one round. The coloured spans are the reel's phases, the marks along the top and bottom are the instants the metrics stamp, and all of them are in milliseconds since the round opened. Speed samples ride along the lane at about 30 Hz when a ticker is available.
The two tables are what a round records, per reel and for the set as a whole. The per-reel part is what the timeline draws; the set part is what the metrics plaque prints.
| Per reel | Meaning |
|---|---|
| phases[] { phase, start, end | null } | Every phase the reel entered, with its span; end is null while the phase is open. |
| stoppingAt, landingAt, landedAt | When the controller asked it to stop, when it reached its result frame, when it came to rest. |
| tease { start, end, order, total } | The anticipation span and where this reel sat in the tease sequence. |
| symbolSwaps | How many times a cell took a new symbol during the round. |
| speed | A flat [t0, v0, t1, v1, ...] array of samples, only when a ticker was given. |
| Per round | Meaning |
|---|---|
| index, spin, startedAt, profile | The round number, whether a spin() opened it (false for a nudge before any spin), when, and the speed profile in force. |
| allStartedAt, allLandedAt, completeAt, duration | The set-level marks and the total. |
| wasSkipped, skips[] { at, mode, reels, partial, completedAt }, queuedSkipAt, boosted | Every skip press and what it freed. wasSkipped is set at skip:requested, because an aborted spin never reaches spin:complete; skip:completed closes the oldest open mark with the same reels. |
| landOrder, events, cascadeChains, wins, lastActivityAt | The order the reels landed, an event count, cascade and win bookkeeping, and the last time anything happened (round events extend it after a round settles). |
An event that arrives with no round open opens one with spin: false, which is how a nudge before any spin still gets measured. The options are now (default performance.now), history (20 rounds kept; clear() empties them but keeps the counter), ticker (enables speed sampling) and sampleMs (33); MAX_SAMPLES caps speed at 1800 samples per reel per round, about 30 seconds. The getters are current, rounds, isActive (a reel has an open phase, or a spin round has not completed while the set is spinning), length (a live clock while active, else lastActivityAt) and totals { rounds, skipped, averageDuration | null }, where rounds counts every round ever opened and the other two are over the kept window. snapshot() returns a deep JSON copy as SpinMetricsSnapshot { rounds, totals }. Like the debug snapshot, it is not semver-protected.
Notices
The library sometimes needs to tell a developer something they should act on: a buffer that had to be clamped, a mask that cannot be rounded, a phase chain that threw and was recovered by a slam. All of that goes through one channel, utils/notify.ts, rather than scattered console.warn calls, so you can turn it down, listen to it, or route it somewhere. A notice is { kind, code, message, detail }, and the code is a stable string you can grep for.
The level, 'silent' | 'error' | 'warn' | 'info', ranked 0 to 3, gates console output only; it defaults to 'info' because the messages it replaced were unconditional, and setLogLevel() and getLogLevel() change and read it. onNotice(listener) returns an unsubscribe and hears every notice regardless of level, even at 'silent', which is how a test asserts that a warning fired without cluttering its output. noticeWarnOnce deduplicates by code in a process-wide set and skips the listeners on repeats too; resetNoticesForTest() clears both the set and the listeners. Output goes through console[kind] so devtools filtering and stack traces keep working: a styled badge in a browser, [pixi-reels] kind(code) message in Node. Notices are for things a developer should act on, never for per-frame state. This is every code the library raises today, and where.
| Kind | Code | Raised in |
|---|---|---|
| error | phase-chain-threw | spin/SpinController.ts; the engine slams to recover |
| error | refill-threw | SpinController.ts refill |
| error | pin-hook-threw | core/ReelSet.ts movePin hooks |
| warn | destroy-rejected | ReelSet.ts destroySymbols |
| warn | anticipation-cells-unreachable | SpinController.ts; a final curve leg at speed 0 |
| warn | hw-coin-<anim>-failed | board/HoldAndWinBoard.ts |
| warnOnce | buffer-clamped | core/ReelSetBuilder.ts |
| warnOnce | mask-rounded-touching | core/maskStrategies.ts |
| warnOnce | mask-silhouette-disjoint | core/maskStrategies.ts |
| warnOnce | shared-mask-jagged | ReelSet.ts _setColumn |
| warnOnce | quicken-cascade | SpinController.ts; a quicken press in cascade mode becomes a slam |
| warnOnce | anticipation-curve-cascade | SpinController.ts |
| warnOnce | wide-block-misaligned | SpinController.ts |
| warnOnce | anticipation-drive-budget | spin/phases/AnticipationPhase.ts |
| warnOnce | profile-step-<phase>-<name> | spin/phases/ReelPhase.ts; an unknown step in a speed profile section |
| info | mask-auto-shared | ReelSetBuilder.ts; an unmask symbol with a cross gap picked SharedRectMaskStrategy |
| info | warp-skips-unmask | ReelSetBuilder.ts |
Tickers, disposal and gsap
Three pieces of plumbing underpin everything above, and they are the first things to check when a debug tool, or the game, misbehaves: how objects clean up, which gsap instance the engine is tweening on, and who is driving gsap's clock.
Disposable is { destroy(): void; readonly isDestroyed }. Any class that subscribes to tickers, creates display objects or holds references implements it. The original library's main leak was ticker.add without a matching remove, so no class may call ticker.add() directly: it goes through TickerRef, which keeps its own callback list, ignores add after destroy, only removes callbacks it tracks, and on an idempotent destroy() removes every tracked callback. ReelSet.destroy() cascades through every subsystem; SpinMetrics and the overlay both use TickerRef.
With symlinked workspaces (vite with a linked package, pnpm, esbuild chains) the library's gsap import and yours can resolve to different module instances, each with its own root timeline; the engine's tweens then sit on a timeline nobody drives and stall at progress 0. ReelSetBuilder.gsap(myGsap) hands the engine your instance. It is held per reel set (carried down through ReelConfig.gsap), so composed stages can use different instances. DEFAULT_GSAP is the instance resolved when the library loaded.
driveGsapWithTicker(ticker, instance = DEFAULT_GSAP) → dispose removes gsap.updateRoot from gsap's own ticker and calls it from a Pixi ticker callback with ticker.lastTime / 1000. Why: gsap's requestAnimationFrame loop is throttled or frozen in hidden tabs and iframes (casino lobbies) while the Pixi ticker keeps going, so easing and bounces would freeze mid-flight. Call it once per app, with the same instance you gave the builder; driving from two sources runs animations at double speed. The disposer is idempotent and re-adds updateRoot.
Where this lives
debug.tsdebugSnapshot, debugGrid, the frame recorder, enableDebug (main entry)index.tsthe pixi-reels/debug barrel: debugOverlay, OVERLAY_LABEL, DebugPlaque, DEBUG_FONT, WinLines, roundRectPath, SpinMetricsdebugOverlay.ts,SpinMetrics.ts,DebugPlaque.ts,roundRectPath.ts,WinLines.ts
notify.tslog levels, onNotice, noticeError/Warn/WarnOnce/InfoDisposable.ts,TickerRef.ts,gsap.ts,gsapTicker.tsdocs/adr/004-disposable-tickerref.md,006-debug-mode.md,022-debug-subpath-on-pixi-silk.md