This document explains how the engine works inside, for people who want to change it. It does not
cover why the system is shaped this way (see DESIGN.md) or the spec format itself (see
SPEC.md). Figures and motion models get a short section here; the full reference is
figures.md. The web runtimes get a short section too; their references are
runtime.md (<pixel-sprite>) and stage.md (<pixel-stage>).
Every mechanism below cites the file and function that implements it. If the code and this document disagree, the code is right. Please fix the document in the same change.
Contents
Section titled “Contents”- Pipeline
- Module map
- Spec resolution: extends and figures
- Validation, compilation and lint
- Animation internals
- Rendering internals
- Output: sheets, bundles, export, runtime
- Invariants
- How to extend
- Testing
1. Pipeline
Section titled “1. Pipeline”flowchart TD
A["spec JSON (may have extends / figure)"] --> B["resolveExtends<br/>extend.js"]
B --> C["resolveFigure → expandFigure<br/>figure.js"]
C -->|"bones → parts<br/>motions → generateMotion (motion.js)<br/>→ oversampled tracks"| D["plain spec"]
D --> E["validate<br/>spec.js"]
E -->|"errors"| X["{path, message} list<br/>(CLI / studio show it)"]
E --> F["compile<br/>spec.js"]
F --> L["checkBounds<br/>lint.js (warnings)"]
F --> G["renderFrame(compiled, {res, anim, frame, style})<br/>render.js"]
subgraph per frame
G --> H["samplePose<br/>animate.js: tracks, reach (rig.js solveReach),<br/>+ followOffsets"]
H --> I["worldMatrices<br/>rig.js (pixel-snapped offsets)"]
I --> J["rasterize: SDF test at each pixel centre<br/>shapes.js"]
J --> K["shade: ramp, light, texture, shine, dither,<br/>contact shadow → inner lines → outline"]
end
K --> M["frame {w, h, rgba, ids, materials}"]
M --> N["renderAnimation / renderSheet<br/>render.js"]
N --> O["buildBundle<br/>bundle.js (PNG via host encoder,<br/>+ skins, bakePoints, ground, states)"]
O --> P["<pixel-sprite><br/>@pixel-studio/runtime"]
P --> S["<pixel-stage> / <pixel-actor><br/>@pixel-studio/runtime/stage"]
N --> R["exportSheet<br/>export.js (Aseprite JSON for Phaser / PixiJS)"]
M --> Q["contactSheet (image.js) / frameToAscii (ascii.js)"]The same steps as text:
spec ──resolveSpec──▶ plain spec ──validate──▶ {errors, warnings} │ (no errors) ▼ compile ──▶ compiled {size, materials, parts, animations, style, points, ground, skins, states} │ for each animation × frame × resolution: ▼ resolveStyle(compiled, res, overrides) ──▶ style (lod preset < spec.style < overrides) samplePose(compiled, anim, f) ──▶ Map(partId → {x, y, rot, sx, sy, show}) worldMatrices(parts, pose, snap) ──▶ Map(partId → affine matrix), visibility raster pass (one SDF sample per pixel) ──▶ hitPart / hitShape / local point per pixel shade pass ──▶ rgba + material ids inner-line pass, outline pass ──▶ final frame ▼ renderSheet ──▶ buildBundle ──▶ JSON {format, size, ground, animations, points?, skins?, states?, variants[{res, image, skin?}]} ──▶ <pixel-sprite> ──▶ <pixel-stage> └─▶ exportSheet ──▶ sheet + Aseprite JSON (frames, frameTags, slices) ──▶ Phaser / PixiJSEach stage passes plain data to the next. Nothing downstream of resolveSpec knows that figures,
motions or variants exist. (Skins are the exception that proves the rule: compile turns each skin
into a whole compiled character of its own, so the renderer still sees only plain compiled specs.) By the time validate runs, a goose dressed on the goose figure with a
walk motion is ordinary parts and keyframe arrays.
2. Module map
Section titled “2. Module map”src/core/ (the engine; isomorphic, zero dependencies)
Section titled “src/core/ (the engine; isomorphic, zero dependencies)”| File | Responsibility | Main exports |
|---|---|---|
index.js |
Public API barrel (@pixel-studio/core). Hosts should import from here. It exports no live registries: shapeTypes(), textures(), motionModels(), leggedModels() return frozen copies. |
the pipeline (resolveSpec, validate, compile, render, buildBundle, exportSheet, …), plug-ins, constants |
internal.js |
Building blocks for tools (@pixel-studio/core/internal): the CLI, studio and tests import them; no compatibility promise. |
createImage, blit, bakePoints, samplePose, samplePoseAt, sampleValue, frameTime, followOffsets, worldMatrices, solveReach, overflowForPose, resolveExtends, mergeVariant, expandFigure, paletteOf, buildMixes |
extend.js |
Variants: merge a spec onto its extends base (points and skins by name), then call resolveFigure. |
resolveExtends, mergeVariant, resolveSpec |
figure.js |
Expand figure: bones become parts, motions become tracks (author tracks layered on top), model events become frame numbers, and the figure’s foot line (ground) and attachment points are fitted. views add the same character seen from other angles (idle@front, turn@front, …). |
resolveFigure, expandFigure |
motion.js |
Motion models (gait, idle, pose, hop, jump, climb, fall, sit) that generate per-sample track arrays with planted feet, plus speed/speedY/wall and timed events. |
generateMotion, MOTION_MODELS, LEGGED_MODELS, OVERSAMPLE |
spec.js |
Structural validation (JSON paths, did-you-mean; validateStates for the state machine) and compilation into the renderer’s structure, skins included. |
validate, compile, TRACK_PROPS, skinSpec (not re-exported from index.js) |
shapes.js |
Signed distance functions and compileShape (sdf, thickness R, bbox). |
SHAPE_TYPES, compileShape, sdEllipse, sdRoundRect, sdCapsule, sdPolygon |
animate.js |
Track sampling, pose composition, follow-through springs. | sampleValue, frameTime, samplePose, samplePoseAt, followOffsets |
rig.js |
2D affine maths, world matrices, CCD reach solver, bounds sampling. | worldMatrices, solveReach, ccd, overflowForPose, invert, apply, angleOf, localMatrix, mul |
lint.js |
Checks that need poses: parts leaving the canvas, reach targets missed. | checkBounds |
render.js |
Style resolution, rasterizer, pixel-art shader, animation and sheet rendering, per-animation playback metadata. | renderFrame, renderAnimation, renderSheet, animationMeta, resolveStyle, lodForRes, DETAIL_PRESETS, DETAIL_NAMES, MAX_RES |
color.js |
Hex parsing, HSV/HSL conversion, hue-shifted ramps, darken. |
buildRamp, baseIndex, parseHex, toHex, darken |
textures.js |
Procedural textures sampled in part-local pixel space. | TEXTURES, sampleTexture, hash2 |
image.js |
RGBA image helpers and the contact sheet used by preview. |
contactSheet, createImage, blit, checker (not re-exported from index.js) |
ascii.js |
A frame as text (one letter per material, # outline, . empty). |
frameToAscii |
bundle.js |
Render one sheet per resolution (and per skin, stored as a colour swap + overlay of the default sheet when smaller) and package them for the runtime with size, ground, baked points and states; optionally without some views. |
buildBundle, bakePoints, skinDelta, keepViews, BUNDLE_FORMAT ('pixel-sprite/1') |
export.js |
One sheet plus Aseprite “hash” JSON for game engines (Phaser, PixiJS): frames, tags, slices for points, Pixel Studio extras. | exportSheet |
mix.js |
Transition clips (mixes): a few frames that interpolate the pose from the end of one animation to the start of another, added to the compiled animations as "from>to". |
buildMixes |
plugins.js |
Extension points: register shapes, textures and motion models; they join the built-in tables so validation and pixel brief treat them like built-ins. Read-only snapshots of those tables. |
registerShape, registerTexture, registerMotion, registeredPlugins, usePlugin, shapeTypes, textures, motionModels, leggedModels |
png.js |
PNG bytes for any host (zlib injected): indexed (PLTE + tRNS, 1–8 bits) up to 256 colours, else RGBA8 with per-row filters. | pngBytes, paletteOf |
Everything else
Section titled “Everything else”| File | Responsibility | Main exports / entry |
|---|---|---|
src/node/png.js |
pngBytes with node:zlib deflate level 9. Node-only. |
encodePNG(w, h, rgba) → Buffer |
packages/runtime/src/pixel-sprite.js |
<pixel-sprite> web component: loads a bundle, picks a variant (and skin), plays frames from the sheet, fires baked events, runs the bundle’s state machine, and exports the shared frame clock. Does not import the engine. |
PixelSprite, clock, pickVariant, deviceScale, checkBundle, StateMachine, parseCondition, BurstDetector, BUNDLE_FORMAT |
packages/runtime/src/pixel-stage.js |
<pixel-stage> and <pixel-actor>: characters that roam a page, standing on, jumping between, climbing and hiding behind opted-in elements. Imports only clock from pixel-sprite.js. |
PixelStage, PixelActor, World, checkScene, runScene, jumpArc, cells |
bin/pixel.mjs |
CLI: validate, preview, ascii, render, export, bundle, resolve, where, figures, brief. Loads files, calls resolveSpec, then the core. |
pixel bin (see package.json) |
scripts/build-demo.mjs |
Builds demo/assets/*.bundle.json from examples/*.json at 16/32/64 px, writes a 64 px poster of each (demo/assets/*.poster.png) and a 32 px exportSheet sheet for goose-root, copies both runtimes (pixel-sprite.js, pixel-stage.js), and with --previews writes previews/*.png. |
npm run build:demo, npm run previews |
demo/index.html, demo/flock.html, demo/stage.html, demo/runner.html |
Demo pages: sprites on a site (including a state machine and skins section), the goose flock, <pixel-stage> characters roaming a page, and a tiny runner game played by the fox. |
pages |
scripts/serve.mjs |
Zero-dependency static server for the repo root (studio and demo), port PORT or 5173. |
npm run studio |
studio/app.js |
Studio UI: editor → resolveSpec → validate → compile → checkBounds → render (current view, LOD strip at 16/24/32/48/64 px, sheet), rig overlay, export with a canvas PNG encoder. |
browser module |
studio/agent.js |
Agent tab: calls the Anthropic SDK from the browser (loaded lazily from esm.sh), validation-repair loop, contact-sheet critique. | initAgent, extractSpec |
studio/goose.html |
Goose workbench: resolves {extends: <goose>, …features} in the page, renders frames on demand with renderFrame, hides parts/shapes on a copy of the compiled spec (bones stay), exports a variant spec and checks it builds. Features live in studio/goose-features.json. |
page |
studio/figures.html |
Figure viewer: inline module that draws each figure’s skeleton with samplePoseAt + followOffsets (smooth time, trails, onion skin). |
page |
studio/index.html, studio/studio.css |
Studio markup and styles. | — |
3. Spec resolution: extends and figures
Section titled “3. Spec resolution: extends and figures”resolveSpec(spec, {loadRef, loadFigure, warn}) in extend.js is the single entry point for
turning an authored file into a plain spec. It runs two steps in a fixed order:
-
resolveExtendsfollows theextendschain recursively, up to depth 8. It raises"chain is too deep (cycle?)"after that. Each level callsmergeVariant(resolvedBase, variant). Merge rules:- materials merge per field, and
nullremoves; - parts are patched by
id:remove: trueremoves the part and its descendants,addShapesappends, other fields replace, and unknown ids are appended; materialMapre-points shape materials, including the variant’s own shapes;- materials that the base used but the variant no longer uses are dropped;
- animations merge per track property, and
nullremoves; - tracks and reach constraints that refer to removed parts are dropped;
pointsandskinsmerge by name, andnullremoves one;stylemerges.
Errors carry
e.errors = [{path:'$', message}], the same shape as validation errors. - materials merge per field, and
-
resolveFigure(figure.js) loads the figure by name throughloadFigureand callsexpandFigure. Because extends runs first, a variant of a figure-based spec (for exampleexamples/goose-root.jsonextendsgoose-base.json, which uses"figure": "goose") patches the unexpanded dressing, and the figure is expanded once at the end.
Loaders are injected by the host, which keeps the core free of I/O. The CLI resolves extends paths
relative to the referring file (bin/pixel.mjs, loadSpec). The studio and build-demo.mjs
resolve them inside examples/. All three read figures from figures/<name>.json.
Figures and motion (brief)
Section titled “Figures and motion (brief)”expandFigure(spec, figure, fit, warn) in figure.js:
- Bones become parts. Each bone
{id, parent, from, to, z, side, follow}becomes a part withpivot = from,tip = to,z = bone.z ?? indexandshapes: [].side: "far"addsshade: -0.3. Bones are first fitted byfit.scale,fit.offsetandfit.origin(default: bottom centre of the canvas), and patched byfit.bones. - Dressing. A spec part whose
idmatches a bone is merged into that bone part. A part withbone: "x"becomes a child of bonex, withpivot = fromandz = bone.z + 0.5. Any other part is appended as is. A spec with nopartsgets a stick figure: capsules ofr1.4 with materialbone, joint circles ofr2.4 (1.8 at leaf tips) with materialjoint, andstyle.outline: 'dark'. - Motions become tracks. For each animation with
motion, the preset parameters (figure.motions[name]) are merged with the animation’s own fields.generateMotion(motion.js) is then called with the expanded parts,figure.rigand the author’stracksasinput. It simulates the motion twice (the first pass warm-starts the IK so the loop closes) and recordsMsamples per track.M = frames × OVERSAMPLEwhen looping and(frames − 1) × OVERSAMPLE + 1for one-shots, withOVERSAMPLE = 4. Values are rounded to 0.01. A track whose samples are all equal collapses to a number. Foot misses over 0.3 units are reported throughwarn. - Layering.
layerTracksresamples the author’s tracks at the sameMpoints and combines them with the generated ones:x,yandrotadd,sxandsymultiply,showreplaces. Rootx/y/rottracks are not layered a second time, becausegenerateMotionalready applied them before solving the legs (so feet stay planted under author body motion). - Gait and hop animations get
speed, in units per second. The page moves the sprite at this speed so planted feet do not slide. Climb animations getspeedY(units per second upward) andwall(the x of the wall the feet hold). - Events.
generateMotionreports events in normalized timeu:footstepper leg (data: {leg}) forgaitandclimb,takeoff/landforhop,launch/landforjump.expandFigureturnsuinto the first frame at or after it (ceil(u·frames) mod frameslooping,ceil(u·(frames − 1))one-shot), appends the author’sevents, and sorts by frame."events": falsedrops the model’s events.holdsis copied through. - Ground and points. Unless the spec sets
ground,expandFiguretakes the figure’sground(fitted), elsegroundOf: the lowest toe of the rig’s legs, else the shadow bone’s line, else the root bone. Figurepointson existing bones are fitted and merged under the spec’s ownpoints. - Rig roles.
rootis always required; the models inLEGGED_MODELS(gait,pose,jump,climb,sit) also needlegs. Optional roles:neck,head,arms,tail,wings(flapped infall,climbandjump),shadow,view.
Generated tracks are keyframe arrays with M entries. With linear interpolation (section 5), frame
f lands exactly on sample f × OVERSAMPLE. The extra samples only matter where time is sampled
between frames: the follow-through simulation and the studio’s smooth figure view. After expansion
the output is a plain spec. validate rejects any leftover figure or motion key with a message
that says to resolve it first.
4. Validation, compilation and lint
Section titled “4. Validation, compilation and lint”validate(spec) (spec.js)
Section titled “validate(spec) (spec.js)”validate returns {errors: [{path, message}], warnings: [{path, message}]}. Paths are JSONPath-like
strings built while walking the spec, for example $.parts[3].shapes[0].material or
$.animations.walk.tracks.legL.rot. Errors block compilation. Warnings never do.
- Did-you-mean.
didYouMean(word, options)returns the option with the smallest Levenshtein distance, provided that distance is below 3. It is appended to errors for unknown shape types, textures, materials, parents, track parts, track properties and reach chain ids. - Unknown keys produce warnings, not errors, through
unknownKeys(obj, kind, ...)against theKNOWNtable. Every object kind (top level, material, part, shape, animation, follow, reach, style, wave, keys) has an entry there. - Structural checks:
- hex colours, and
shinein 0..1; - unique part ids, unknown parents, and parent cycles;
- per-type required shape fields (
SHAPE_REQUIRED), and polygons with at least 3 points; opmust beaddorcut; cuts need no material;profileindome|flat|none;framesis an integer 1..64, andfpsis in 1..60;- track values must be a number, a non-empty number array,
{keys}or{wave}(isTrackValue); style.outlineinnone|dark|selective.
- hex colours, and
- Bones without shapes. A part with a
tipmay haveshapes: []. - Off-canvas warning.
compileShapeis run on each shape and its bbox is checked againstsize, before part transforms. This only happens while no errors have been found yet. - Unused material warnings.
- Reach (
validateReach): the chain ids must exist, every chain id must beendor one of its ancestors,tipmust be a point,targetmust be a pair of track values,aimneeds at least one chain part besidesend, andlimitsmust be{id: [min, max]}for chain members only. - Animation extras:
speedYandwallare numbers;eventsare{frame, name, data?}with an integerframeinside the animation;holdskeys are frame indices and values are in (0, 16]. - Points: each names an existing part, and
atis[x, y],"pivot", or"tip"(bones only). - Ground: a number in
0..size[1]. - Skins: each is an object with only
parts,materials,materialMapandstyle(SKIN_KEYS). When the spec has no other errors yet,skinSpec(spec, patch)(the spec withoutskinsandstates, merged with the patch bymergeVariant) is validated, and its errors are re-reported under$.skins.<name>. - States (
validateStates):nodesis non-empty and every node’sanimexists;thenis a node or"previous";randomfidgets name existing animations;initialand transitionfrom/toare nodes (frommay be"*");whenconditions parse (name,!name,name op literal, joined by&&orand) and name declared inputs; inputs start as a number, boolean, word or"trigger"; a node’srateis a speed in (0, 4] or the name of an input; a transition’satis a string ("now","end","sync"or an event name); interactions useon: click|enter|leave|burst|calmandfire/setdeclared inputs. Unknownstateskeys warn. - Mixes:
mixesis an object; each key is"from>to"naming two different existing animations; each value is an object withframesa whole number 1..8,easelinearorsmooth, andfpsin 1..60.
ease names, wave shape names, and the types of style values and of material.tones /
textureScale / textureStrength are validated too. Not validated: event data (any JSON value),
the timing fields of states random fidgets (every, weight), and a non-array states.interactions
(ignored).
compile(spec) (spec.js)
Section titled “compile(spec) (spec.js)”compile calls validate and throws Error('invalid spec: ...') with .errors if there are any.
Otherwise it normalizes the spec:
- Materials become
{color, texture, textureScale: 1, textureStrength: 0.35, shine: 0, flat, outline: true, tones}. A bare hex string"#rrggbb"is accepted as a material. - Parts become
{id, index, parent, pivot (default: canvas centre), z (default: array index), tip, follow, base: {x, y, rot, sx, sy, show}, shade, shapes}. - Follow.
compileFollowturnsfollow: ninto{freq: 3, damping: 0.3, amount: n, max: 40}. - Shapes are
compileShape(s)(sdf,R,bbox) plusop,material,minDetail(1),maxDetail(3),profile(dome) andshade(0). - Animations become
{name, frames, fps: 8, loop: true, tracks, reach: [], speed: 0, speedY: 0, wall: null, events: [], holds: null}. Events are sorted by frame;holdskeys become numbers. - No animations. A spec without animations gets
still(1 frame, 1 fps). - Points become
{part, at}with"tip"and"pivot"replaced by the part’s rest-pose point. groundandstatesare copied (nullwhen absent).- Skins. Each skin is compiled recursively,
compile(skinSpec(spec, patch)), into a full compiled character with the same animations;compiled.skinsmaps names to them (nullwithout skins).
checkBounds(compiled, {margin = 0.5}) (lint.js)
Section titled “checkBounds(compiled, {margin = 0.5}) (lint.js)”checkBounds samples every frame of every animation with samplePose, so tracks, reach and
follow-through are all included. For each frame:
- Overflow.
overflowForPose(rig.js) transforms each visible part’s edge samples into world units and records how far they go past each canvas edge.samplesForproduces the edge samples: bbox points on a 0.75-unit grid with-1.5 < sdf ≤ 0, cached per compiled shape in aWeakMap. Overflows larger thanmarginare aggregated per part and edge. The warning lists the frame ranges, for example"head" goes 8.2 units past the right edge in frames 2–7. - Reach. Any reach constraint whose
pose.reachMissis above 1 unit gets a warning that names the chain and suggests what to relax.
Bounds warnings use the same {path, message} shape as validation warnings, plus anim, part,
edge, frames and amount. The CLI (compileOrExit, validate) and the studio (rebuild) print
them next to validation output.
5. Animation internals
Section titled “5. Animation internals”Track values (animate.js, sampleValue)
Section titled “Track values (animate.js, sampleValue)”sampleValue(v, t, loop, isStep, defaultOffset) takes normalized time t ∈ [0, 1) (or [0, 1] for
one-shots):
| Form | Evaluation |
|---|---|
3 |
constant |
[a, b, c, ...] |
interp(keys, t, loop, 'linear') |
{keys, ease} |
interp with linear, smooth (smoothstep f²(3−2f)) or step. Any other string behaves as linear. |
{wave, phase, cycles, offset, shape} |
offset + wave × w(x) with x = (t × cycles + phase) % 1. w is sin (default), tri (same phase as sin), square (+1 for the first half), or `bounce = − |
interp spreads keys evenly over the cycle:
- Looping: the span is
n, so the last key interpolates back to the first.[0, 10]reaches 10 att = 0.5and is back to 5 att = 0.75. - One-shot: the span is
n − 1, so the last key is reached att = 1and held.
show is always stepped. Arrays and keys use step, and a wave becomes 1 when its value is ≥ 0.
sx/sy waves use defaultOffset = 1, so {"wave": 0.06} oscillates over 0.94..1.06. Numbers and
arrays on sx/sy are absolute factors.
Time mapping (frameTime)
Section titled “Time mapping (frameTime)”loop: t = f / frames (frame 0 and the virtual frame `frames` coincide → seamless)one-shot: t = f / (frames − 1) (first and last frames hit t = 0 and t = 1 exactly)frames ≤ 1: t = 0renderFrame wraps the frame index with frame % frames. loop defaults to true in compile.
The runtime decides what happens after the last frame (section 7).
Pose composition (samplePoseAt)
Section titled “Pose composition (samplePoseAt)”For each part, the base transform from compile is combined with the sampled track values. A missing
track leaves the base unchanged:
x = base.x + track.x rot = base.rot + track.roty = base.y + track.y sx = base.sx × track.sx sy = base.sy × track.syshow = (track.show ?? base.show) ≥ 0.5The local matrix is built by localMatrix(pivot, t) in rig.js:
local = T(pivot + (x, y)) · R(rot) · S(sx, sy) · T(−pivot)world = world(parent) · local (worldMatrices, parents resolved recursively)visible = show && visible(parent)Pivots and offsets are in rest-pose canvas units. Rotation is in degrees, clockwise on screen
(y points down). The pivot is both the rotation origin and the scale origin. Matrices are
[a, b, c, d, e, f] with x' = a·x + c·y + e and y' = b·x + d·y + f. invert clamps the
determinant to 1e-9, so a zero scale does not produce NaNs.
Reach constraints: CCD IK (rig.js)
Section titled “Reach constraints: CCD IK (rig.js)”After the tracks are applied, samplePoseAt solves each anim.reach[i] in order. The constraint’s
target and aim are themselves track values, sampled at t.
-
solveReach(parts, pose, r, target, aim)runsccdstarting from the current (track) rotations. If the tip still misses by more than 0.05 units, it restarts from four perturbed seeds (chain[0]/chain[1]rotated by ±60° or ±120°) and keeps the best result. CCD can settle in a local minimum, for example a joint bent the wrong way, and the restarts get it out. It returns the remaining distance, which is stored inpose.reachMiss[i]. -
ccd(parts, pose, r, target, aim, iters = 32)runs up to 32 passes and stops early under 0.05 units. Each pass visits the joints from the end of the chain back to the root. For each joint it:- recomputes world matrices;
- if
aimis set, sets the end part’s local rotation so its world angle equalsaim; - rotates the joint by the wrapped angle between “pivot → tip” and “pivot → target”.
With
aim, the end part is not one of the solved joints.limitsclamp the localrotto[min, max]as absolute values, which include the base rotation.
ccd is also used by motion.js for necks, heads and legs that are not two-bone. Two-bone legs use
the exact law-of-cosines solver twoBone. Front-view legs use frontLeg, which foreshortens with
sy.
Cost: each CCD step recomputes every part’s world matrix twice, and reach runs inside
samplePoseAt, which the follow-through simulation calls once per substep.
Follow-through (animate.js, followOffsets)
Section titled “Follow-through (animate.js, followOffsets)”A part with follow is a damped angular spring that hangs from its pivot. samplePose adds the
spring angle to the part’s rot after tracks and reach:
pose.get(id).rot += followOffsets(compiled, anim).get(id)[f % frames]samplePoseAt alone, as the studio figure viewer uses it, has no follow-through.
followOffsets(compiled, anim) simulates once per animation and caches the result in a
WeakMap keyed by the compiled animation object:
-
Spring.
k = (2π·freq)²andc = 2·damping·2π·freq, sodampingis the damping ratio (1 = critically damped). -
Driving forces. Each substep poses the rig at that time, with the current spring angles of all followers included, so chains of followers interact. It then computes world matrices and takes, for each follower:
- the linear acceleration of its pivot
a, by second finite differences over the last three substeps. This becomes a torque around the pivot using the lever armrto the part’s centre of mass:(r × −a) / max(4, |r|²), converted to degrees.centerOfcomputes the centre of mass as the area-weighted centre of the shape bboxes, or the bone midpoint, or the pivot. - the angular acceleration of its parent
α, which the part resists (−α).
The sum is multiplied by
amount. The spring is integrated with semi-implicit Euler, and the angle is clamped to±max, with the velocity toward the limit zeroed. - the linear acceleration of its pivot
-
Substeps. There are
SUBSTEPS = 8per frame.dt = 1 / (8 · fps). Generated motions have 4 samples per frame, which the 8 substeps interpolate linearly. -
Warm-up. Looping animations run 4 passes over the cycle and record the last, so the spring has settled into its periodic state and the loop is seamless. One-shots run one pass from rest.
-
Recording. Every 8th substep the angle is recorded per frame, rounded to 0.01°.
-
No followers or fewer than 2 frames gives
null(cached too).
6. Rendering internals
Section titled “6. Rendering internals”All of this is in render.js unless noted otherwise.
Style resolution (resolveStyle)
Section titled “Style resolution (resolveStyle)”The style is built from these layers, with later layers winning:
defaults { light: −45, elevation: 50, outlineColor: '#1b1424', snap: true, hueShift: 1, ambient: 0.15, curvature: 0.8, flip: false } < DETAIL_PRESETS[lod] < spec.style (null / undefined / '' values ignored) < overrides (CLI flags, studio knobs; same filtering)lod = overrides.lod || lodForRes(res)resolveStyle throws a readable error for a lod other than 1, 2 or 3 and for overrides that break
the style rules (for example tones outside 2..6). renderAnimation refuses a res outside
1..MAX_RES (512).
Detail tiers
Section titled “Detail tiers”lodForRes(res) returns 1 for res ≤ 20, 2 for res ≤ 40, and 3 otherwise.
DETAIL_NAMES = {1: 'icon', 2: 'sprite', 3: 'portrait'}.
| Key | lod 1 | lod 2 | lod 3 |
|---|---|---|---|
tones |
2 | 3 | 5 |
texture |
0 | 0.6 | 1 |
dither |
false | false | true |
outline |
dark |
selective |
selective |
innerLines |
false | false | true |
contactShadow |
false | true | true |
ambientBoost |
0.25 | 0 | 0 |
A shape is drawn only when minDetail ≤ lod ≤ maxDetail (defaults 1 and 3). Parts whose shapes are
all gated out, and bones with no shapes, are skipped entirely.
Coordinate system and pixel grid
Section titled “Coordinate system and pixel grid”- Size. The canvas is
sizeunits (default[100, 100]). For a requestedres, the frame isH = round(res)pixels tall andW = round(res × width / height)wide, withscale = H / heightpixels per unit.resis the frame height. - Sampling. Pixel
(px, py)samples the world point((px + 0.5) / scale, (py + 0.5) / scale), its centre. There is no supersampling or anti-aliasing: each pixel takes one binary sample.flipmirrors the sampling (px → W − 1 − px) and negates the x gradient, so the light stays on the same screen side. - Pixel snapping. When
st.snapis on,worldMatricesgets anadjusthook that runssnapUnitson each part’sxandyoffset before building its matrix. An offset under 0.35 px becomes 0. Anything larger rounds to whole pixels, with a minimum of 1 px. Rotation and scale are not snapped, and the effect accumulates through the hierarchy, because each part’s local offset is snapped on its own.
Rasterization: SDF per pixel
Section titled “Rasterization: SDF per pixel”compileShape (shapes.js) returns, for each shape:
sdf(x, y): signed distance in part-local units, negative inside.rectis a rounded box (r,rot),ellipse/circlean ellipse (withrot),capsulea segment with radiir→r2, andpolygonan even-odd polygon distance, minusrwhen rounding is set.R: the thickness, the largest inner distance. For an ellipse that ismin(rx, ry), for a rectmin(w, h)/2, for a capsulemax(r1, r2). For a polygon it is estimated on a 13×13 grid over the bbox. The minimum is 0.01.bboxin local units.
For each pixel, renderFrame walks the visible parts in draw order, sorted by z then by array
index. It maps the pixel centre into each part’s local space with the inverse world matrix. Then:
- A shape is skipped early when the local point is outside its bbox padded by
R + 0.75/scale. - Thin-feature preservation. A shape thinner than a pixel is inflated just enough to claim the
nearest pixel centre. The hit threshold is
thr = reach − RwhenR < reach, otherwise 0.reachis half a pixel (0.5/scale) for elongated shapes, so lines stay 1 px wide. For “dots”, whose bbox is under 3 px in both directions,reachis0.75/scale, a little over the half-diagonal. - Inside a part, shapes are tested in array order. An
addshape withsdf ≤ thrbecomes the hit. Acutshape clears the part’s hit so far. Later shapes override earlier ones, and a cut only erases shapes of its own part that come before it. - Across parts, a later (front) part that hits overwrites earlier ones, like a painter’s algorithm. The pixel records the part, the winning shape, and the local point.
Material unions. Before rasterizing, every part groups its non-cut shapes by material into a
surface. Its sdf is the minimum of the member SDFs and its R is the largest member R.
Lighting uses the surface, not the individual shape, so overlapping shapes of one material read as
one lit volume without seams. The hit test itself still uses individual shapes.
Shading model
Section titled “Shading model”For a hit pixel with material mat, the shader does the following:
- Ramp.
ramp = buildRamp(mat.color, tones = mat.tones ?? st.tones, {hueShift}), memoized in the module-levelrampCache. The base colour sits atbi = baseIndex(tones), which is 1 for 2 or 3 tones, 2 for 4 or 5, and 3 for 6. flatmaterials skip everything below and use the base tone. This is for eyes and emissive details.- Normal.
(gx, gy): the normalized gradient of the surface SDF, by central differences in world space witheps = 0.35 px.u: depth inside the surface,clamp(−sdf / R, 0, 1). It is 0 at the edge and 1 at the thickest point.rho: tilt toward the edge, chosen by the shape’sprofile:dome:1 − u;flat: tilted only in the outer 30% ((1 − u/0.3) × 0.6);none: 0.
- Then
rho = min(rho × curvature, 0.85)andn = (gx·rho, gy·rho, √(1 − rho²)).
- Light.
L = (sin az·cos el, −cos az·cos el, sin el), whereaz = light(0 = from the top, negative = from the left) andel = elevation. The diffuse term isdiff = max(0, n·L). It is remapped around the flat-facing valueflatB = L.z:v = (diff − flatB)/(1 − flatB)above it and(diff − flatB)/flatBbelow it, sov ∈ [−1, 1]and a surface facing the viewer getsv = 0. - Offsets.
v += ambient + ambientBoost + part.shade + shape.shade. - Contact shadow (when
contactShadowis on). The pixel one step toward the light is checked:(sign(round(L.x·1.4)), sign(round(L.y·1.4))), which is up-left for the default light. If a part with strictly higherzcovers that pixel, and its material is neitherflatnoroutline: false, thenv −= 0.7. Eyes and glints do not cast shadows. - Tone index.
f = bi + v·biforv < 0, otherwisebi + v·(tones − 1 − bi).v = −1maps to the darkest tone andv = +1to the lightest. - Texture (when
mat.textureandst.texture > 0).f += sampleTexture(name, floor(localX·scale), floor(localY·scale), textureScale) × textureStrength × st.texture × 1.3. The coordinates are part-local pixels at the current resolution, so the texture moves with the limb and its feature size is in pixels. - Shine (when
mat.shine > 0). Blinn-Phong with half vectornormalize(L + (0, 0, 1))and exponent 40. Whenspec × (0.5 + shine) > 0.55, the pixel takes the top tone. - Dither. When
ditheris on and the fractional part offis in (0.3, 0.7), a 4×4 Bayer threshold, indexed by the part-local pixel coordinate (so the pattern also sticks to the part), picks floor or ceil. Otherwisefis rounded. The result is clamped to[0, tones − 1].
ids[i] stores the material index. It is −1 for empty pixels and −2 for outline pixels.
frameToAscii and the tests use it.
Hue-shifted ramps (color.js, buildRamp)
Section titled “Hue-shifted ramps (color.js, buildRamp)”Ramps are built in HSV around the base colour:
| Hue | Saturation | Value | |
|---|---|---|---|
Shadows, t = (bi − i)/bi |
drifts toward 250° (blue-violet) by 0.2·t·hueShift of the arc, capped at 60° of arc (≤ 12° at hueShift: 1) |
+0.14·t·(1 − s) |
×(1 − 0.42·t) |
Highlights, t = (i − bi)/(n − 1 − bi) |
drifts toward 55° (yellow) by 0.14·t·hueShift, capped at 50° of arc |
×(1 − 0.35·t) |
+(1 − v)·0.65·t |
Greys (s < 0.08) are handled differently. Their shadows take hue 250 with saturation capped at
0.18, and their highlights keep their hue.
darken(rgb, amount) uses the same cool drift. It adds 0.1 saturation and scales the value by
1 − amount. An invalid hex renders magenta ([255, 0, 255]).
Textures (textures.js)
Section titled “Textures (textures.js)”sampleTexture(name, x, y, s) takes integer local pixel coordinates and a scale
s = max(1, round(textureScale)), and returns a brightness offset of roughly ±1. The textures are:
noise: hash per cell;fur: vertical streaks per column plus a variation alongyevery3s;scales: offset rows of cells3s + 1wide;stripes: horizontal bands every2s;checker;cloth: diagonal threads;bricks:6s × 3swith mortar lines;spots: one jittered spot per6scell;metal: horizontal brushed bands.
Randomness comes from hash2, an integer hash, so it is deterministic.
Inner lines and outline
Section titled “Inner lines and outline”Both passes run after shading.
-
Inner lines (when
innerLinesis on). A pixel gets one when a 4-neighbour belongs to a different part with strictly higherz, and both materials are non-flatwithoutlinenotfalse. The pixel is repainted withdarken(ramp[0], 0.15)of its own material, so the back part gets the line. -
Outline (unless
outline: 'none'). Each empty pixel that has a 4-neighbour covered by a material withoutlinenotfalsebecomes an outline pixel. The neighbours are checked in the order up, left, right, down, and the first match is the source. Outline pixels haveids = −2.dark: usesstyle.outlineColor.selective: usesdarken(sourceRamp[0], 0.45), tinted by the neighbouring material.
The outline sits outside the silhouette, so it grows the sprite by 1 px. That is why SPEC.md asks for margin around the character.
7. Output: sheets, bundles, export, runtime
Section titled “7. Output: sheets, bundles, export, runtime”renderAnimation(compiled, name, res, overrides)resolves the style once and renders every frame.renderSheet(compiled, res, overrides, names)puts one row per animation and one column per frame. Width is the maximum frame count, and unused cells stay transparent. It returnsmeta = {res, lod, frameW, frameH, animations: {name: {row, ...animationMeta(anim)}}}.animationMeta(anim)(render.js) is the playback description shared by sheets, bundles and the CLI’srenderJSON:frames,fps,loop, plusspeed,speedY,wall,mix({from, to}, on transition clips) andeventswhen set, anddurations(ms per frame,1000/fps × hold) only when the animation hasholds.buildBundle(compiled, {resolutions = [16, 32, 64], overrides, encode, views, deltas = true})(bundle.js) first drops the views not listed inviews(keepViews: animations namedx@view), then sorts the resolutions ascending and renders a sheet per resolution. It encodes each sheet with the host-suppliedencode(w, h, rgba):encodePNG→ data URL in Node,pngByteswithCompressionStreamin the studio. Each skin incompiled.skinsgets the same resolutions again, appended as variants taggedskin.skinDelta(base, skin)tries to express a skin sheet asrecolor(each default colour → the skin colour it most often becomes) plus anoverlayof the pixels still different; it gives up (null) if the skin makes an opaque pixel transparent. The delta is used when its encoded size is below the full sheet’s. It returns{format: 'pixel-sprite/1', name, size, ground, animations, skins?, states?, points?, skinPoints?, variants: [{res, lod, frameW, frameH, image, skin?}]}.groundiscompiled.ground, orgroundFromPixels: the bottom of the lowest opaque row of the first frame of the largest sheet, in units.pointscomes frombakePoints(compiled), which poses every frame withsamplePose+worldMatricesand records[x, y, rotDeg]per point, animation and frame, in units (so one table serves every variant). Each skin’s points are baked too; a skin whose table differs from the default one (it moves the parts points ride on) gets it underskinPoints.<skin>.exportSheet(compiled, res, {image, overrides})(export.js) renders one sheet and writes Aseprite “hash” JSON: frames keyed by running index ("0","1", …; what Phaser’screateFromAsepriteexpects) with per-frameduration,meta.frameTagsper animation (repeat: "1"on non-looping ones), a PixiJSanimationsmap, one 1×1 slice per point with a key per frame (frombakePoints, converted to frame pixels), andmeta.pixelStudiowithsize,ground(falling back togroundFromPixels, likebuildBundle) and per-animationfps,loop,speed,speedY,wall,events. It returns{width, height, rgba, json}; the CLI’sexportcommand encodes and writes the two files.<pixel-sprite>(@pixel-studio/runtime,src/pixel-sprite.js) does not import the engine; it reads only the bundle. Full reference: runtime.md.- Skins. The
skinattribute filtersvariantsto those with thatskin(none = the default look; an unknown skin falls back to the default look) before choosing one. - Variant choice.
pickVariantscores each variant by the integer scalek = round(size / frameH). Among variants withk ≥ 2that land within 20% ofsize, the highestreswins. Otherwise the closest fit wins, preferringk ≥ 2. - Drawing.
deviceScaleturns the CSS scalekinto whole device pixels per sprite pixel,m = round(k × devicePixelRatio). The canvas backing store isframe × mand its CSS sizeframe × m / dpr; each frame is drawn withdrawImagefrom(frame × frameW, row × frameH)with smoothing off, so pixels are even at fractional DPRs. Draws happen only when the frame changes. - Animation clock. One exported
clockdrives all sprites and page code with onedtcapped at 100 ms. It requests the next frame before running subscribers and isolates each intry/catch. - Loading. One load path per element guarded by a token, so overlapping
srcchanges cannot race; the bundle, variant and sheet are committed together. Bundles are cached per URL (failures evicted), validated withcheckBundle, and sheets are decoded once per variant (ImageBitmap). The host box is reserved fromsizebefore load; light-DOM children are the fallback untilstatus="ready"(mirrored to the legacystateattribute until 0.2.0-alpha), and again onpixel-error. - Page observers. One
IntersectionObserverfor all sprites, a live reduced-motion listener, and a device-pixel-ratio listener that re-lays-out every sprite. - Playback.
- Each frame shows for
1000 / fpsms, or for its entry indurations(scaled when thefpsattribute overrides the rate). - Looping animations wrap.
- Non-looping animations stop on their last frame and fire
pixel-end. play(name, {once: true})(used byclick-anim) firespixel-endand then returns to the hover or base animation.- Events. Entering a frame that has baked
eventsfirespixel-event({anim, frame, name, data}), also for frames skipped while catching up after a slow frame.
- Each frame shows for
- Page geometry.
el.point(name, {relative})scales the bakedpointsof the current frame to client (or box-relative) px, mirrored withflip;el.groundOffsetis the foot line in CSS px from the top of the box;el.pxPerSecond()/el.pxPerSecondY()turnspeed/speedYinto CSS px per second;el.hitTest(x, y)reads the sheet pixel under a client point on one shared 1×1 probe canvas (never the display canvas) and treats unreadable cross-origin sheets as a hit. - State machine. If the bundle has
states(and the element does not havestates="off"), aStateMachine(DOM-free, conditions parsed byparseCondition) picks the animations: inputs viael.set(name, value)andel.fire(trigger), transitionsatnow,end,sync(keep the phase) or an event name,thennodes and random fidgets;el.stateNodeand apixel-statechangeevent report it. Itsinteractions(click,enter,leave) replacehover-anim/click-anim. - Pausing. Sprites pause while off-screen (
IntersectionObserver), whenpausedis set, or underprefers-reduced-motion. Off-screen or under reduced motion, a one-shot or non-looping animation still ends on time: a timer for its full duration firespixel-end, so code waiting for it never hangs. - Events. Every event goes through one
emit()helper:pixel-<name>, bubbling and composed. Until 0.2.0-alpha is out it also fires the pre-0.2 name with its old options (LEGACY_EVENTS). - Node. A
Baseclass guard lets Node importpickVariant,StateMachineand the other helpers for tests.
- Skins. The
<pixel-stage>(@pixel-studio/runtime/stage,src/pixel-stage.js) puts<pixel-actor>characters (each wraps a<pixel-sprite>withstates="off") on the page. Full reference: stage.md.- World.
Worldreads the boxes ofdata-pixel-surface|climbable|perch|hide|occluder|avoidelements in one batch, only when marked dirty (ResizeObserver,MutationObserver,resize,load,transitionend,animationend,document.fonts.ready, orworld.invalidate()), and builds platforms from surface tops plus a document floor. - Planning. An actor routes to a target with a cheapest-path search over platforms linked by
drops, jumps and climbs (cost = px walked + a cost per action). Behaviours:
wander,sit,hide,climb,jumpand idling. Jumps followjumpArc, timed to the animation’slaunch→landevents; climbs move atpxPerSecondY; feet stand ongroundOffset. - Occlusion. Occluders and hiding spots are cut out of the actor with an even-odd
clip-path;cellssplits overlapping holes into disjoint rectangles first. - Events. Actor and stage events go through the file’s own
emit()(pixel-tap,pixel-activity, …, plus the legacy names for one alpha). The inner sprite runs withburst="off"andstates="off", and its events are stopped at the actor’s shadow root, so listeners on the actor hear each thing once. Scenes keep short names ("waitFor": "tap");sceneEventNamemaps them to thepixel-events on actors and the stage. - Input and accessibility. Tapping or clicking an actor’s opaque pixels (
hitTest) shoos it and swallows that click; a pause button (state kept inlocalStorage) stops all actors; underprefers-reduced-motionthey stand still.
- World.
8. Invariants
Section titled “8. Invariants”Keep these true, and treat any change that breaks one as a design change. The verification column records what was checked for this document.
| Invariant | What it means | Verified |
|---|---|---|
| Zero dependencies | package.json has no dependencies or devDependencies. Node code uses only node: built-ins. |
Yes. No dependency fields and no node_modules. The one exception is opt-in: studio/agent.js loads @anthropic-ai/sdk from esm.sh at runtime, and only when the Agent tab is used. |
| Isomorphic core | src/core/*.js uses only language built-ins: no DOM, no Node APIs, no I/O, no globals. Hosts inject loaders (resolveSpec) and encoders (buildBundle). |
Yes. A grep of src/core for document, window, process, require(, node:, fs, fetch, Buffer, globalThis, performance, Date and console. finds nothing, and every import in src/core is relative (./). |
| Determinism | The same spec and settings give the same pixels on every run and host. | Yes. There is no Math.random. Textures use hash2. Rendering examples/fox.json twice at 32 px gave identical SHA-1 hashes, and engine.test.mjs asserts identical RGBA for two renders. The caches (rampCache, followCache, edgeSamples) memoize pure functions of their keys. |
| Everything reduces to a plain spec | extends, figure and motion are resolved before validate. Generated motion is ordinary keyframe arrays. The renderer, lint, CLI where, and the studio rig overlay see only parts and tracks. |
Yes. validate errors on any remaining figure or motion. pixel resolve prints the plain spec. |
| Validation never throws, compile never renders invalid specs | validate returns lists. compile throws one error carrying .errors, and so do resolveExtends and resolveFigure, so every host shows {path, message} the same way. |
Yes for structure. Some value types are not validated and can crash rendering (issues below). |
| Geometry is never resampled as a bitmap | Every frame and resolution rasterizes the SDFs again. Rotation and scale go through matrices. | Yes (renderFrame). |
Detail-dependent behaviour lives in DETAIL_PRESETS and minDetail/maxDetail |
The renderer branches on style keys, not on res, so every tier can be overridden. |
Yes. The only res-dependent lookup is lodForRes. |
| Textures and dither are in part-local space | They move with parts instead of swimming. | Yes (render.js, using hitLX/hitLY). |
| Runtime is independent of the engine | pixel-sprite.js reads bundles only; pixel-stage.js imports only pixel-sprite.js. demo/assets/ holds copies of both. |
Yes. Neither runtime imports src/core, and both copies are byte-identical today. build-demo.mjs refreshes them. |
Known issues
Section titled “Known issues”These are open. (Issues found while writing the docs that have since been fixed are not listed: negative
wave phases, unvalidated style/material/track values, CLI argument handling, renderFrame/renderSheet/
buildBundle misuse errors.)
- Dead code.
hitD(render.js, written but never read) andtoneIdx(render.js, same);rgbToHsl/hslToRgb(color.js) are exported but unused. - Unbounded cache.
rampCache(render.js) is a module-levelMapwith no eviction. It grows with every distinct colour, tones and hueShift combination, for example while a colour is edited live in the studio. - CLI
extendspaths.bin/pixel.mjskeys resolvedextendspaths by the reference string, so two different files named by the same relative string at different depths of a chain would resolve against the wrong directory. - Inline figures are not fitted.
resolveFigureignoresscale,offsetandbonespatches whenfigureis an inline object rather than a name.
9. How to extend
Section titled “9. How to extend”Without touching the engine: plug-ins. src/core/plugins.js exposes registerShape, registerTexture and
registerMotion. Registered names join SHAPE_TYPES / SHAPE_REQUIRED / SHAPE_KEYS, TEXTURES, and MOTION_MODELS
(and LEGGED_MODELS), the engine’s private tables (the public API only hands out frozen copies), so validation, did-you-mean warnings and pixel brief treat them like built-ins; compileShape,
sampleTexture and generateMotion fall back to the registered functions (customShapes, customTextures,
customMotions). Plug-in motions return per-sample tracks, normalized and checked by pluginMotion in motion.js. The CLI
loads plug-in modules with --plugin (usePlugin); examples/plugins/extras.mjs is a working example, tested in
test/plugins.test.mjs (in its own process, since registries are global). Bundles stay data-only, so the runtime is
unaffected. The recipes below are for changing the engine itself.
In every recipe, run npm test and then render something with node bin/pixel.mjs preview <spec>
to look at the result. Rendering changes are visual; the tests only catch structure and regressions.
Add a shape type
Section titled “Add a shape type”src/core/shapes.js: add the name toSHAPE_TYPESand acaseincompileShapethat returnssdf(negative inside, part-local units),R(thickness: largest inner distance, used for lighting depth and thin-feature preservation) andbbox(it must contain the shape; it drives early-out, lint edge sampling andcenterOf). Export the raw SDF function if it is useful on its own.src/core/spec.js: add required fields toSHAPE_REQUIRED, new field names toKNOWN.shape, and any extra checks inside thepart.shapes.forEachblock invalidate.docs/SPEC.md, section “Shapes”.- Tests in
test/engine.test.mjs: an SDF sign/distance assertion (like'SDFs: sign and distance') and a render assertion that the shape’s material appears inrenderFrame(...).ids.
Add a texture
Section titled “Add a texture”src/core/textures.js: add the name toTEXTURESand acaseinsampleTexture(name, x, y, s). It receives integer part-local pixel coordinates and an integer scales ≥ 1, and returns roughly −1..1 (the shader multiplies bytextureStrength × style.texture × 1.3). Usehash2for randomness, neverMath.random.- Validation picks up
TEXTURESautomatically, including did-you-mean. - Update the texture lists in
docs/SPEC.mdandREADME.md. - Test: render a material with the texture at lod 3 and assert that more than one tone appears, and that two renders are identical.
Add a material property
Section titled “Add a material property”src/core/spec.js: add toKNOWN.material, validate the value in the materials loop ofvalidate, and give it a default incompile(thematerials[name] = {...}object).src/core/render.js: read it frommatin the shading loop ofrenderFrame, or in the inner-line or outline passes.extend.jsmerges material fields generically, so nothing is needed there.docs/SPEC.md, section “Materials”. Add a test intest/engine.test.mjs.
A new style key follows the same path: KNOWN.style in spec.js, a default in resolveStyle
or a per-tier value in DETAIL_PRESETS, consumed in renderFrame, and documented in the SPEC.md
style table. Validate its type in validate (next to the other style checks) so it cannot reach the renderer as NaN.
Add a track property
Section titled “Add a track property”Track properties are transform channels, so several places must agree:
src/core/spec.js: add toTRACK_PROPSandKNOWN.part(the rest value), and add the rest value tobaseincompile.src/core/animate.jssamplePoseAt: decide how it composes with the base (add or multiply), and itsdefaultOffsetfor waves.src/core/rig.jslocalMatrix(andworldMatricesif it affects visibility or the hierarchy). If it should snap to pixels, update theadjustcallback inrenderFrame.src/core/figure.js: add the rest value tomotionParts[].base, and choose add, multiply or replace inlayerTracks. If motion models should generate it, changerecinmotion.js.- Tests:
'track values: ...'style unit tests plus a render orworldMatricesassertion (seetest/rig.test.mjs).
Add a motion model
Section titled “Add a motion model”-
src/core/motion.js: add the name toMOTION_MODELSand implement it insidegenerateMotion. The function is one loop overMsamples. Per sample it does the following, so a new model usually changes the feet, the root placement or the limbs and reuses the rest:- compute foot targets (
feet); - place the root (
place); - lower the hips if a leg cannot reach;
- stabilize the head (
ccd); - solve the legs (
twoBone,frontLegorccd); - set arms, tail and shadow;
- record the pose relative to the base.
Note that
poseis currently aliased toidle. If the page should react to moments in the motion, push{u, name, data?}ontoevents;expandFigureconverts them to frames. - compute foot targets (
-
If the model needs
rig.legs, add it toLEGGED_MODELSinmotion.js;expandFigurechecksrootfor every model andlegsfor those. -
Add presets with
"model": "<name>"to themotionsof the relevantfigures/*.json, and document the parameters in figures.md. -
Tests in
test/figure.test.mjs. The first test already asserts that every figure’s motions expand with no warnings, no foot-miss notes and no bounds warnings. Add a model-specific test in the style of'hop: ...'or'gait: planted feet ...', which measures toe positions withworldMatrices.
Add a figure
Section titled “Add a figure”Add figures/<name>.json with name, size, bones, rig and motions (format in
figures.md). test/figure.test.mjs iterates over the directory, so the new figure is
tested automatically for clean expansion, validation, foot placement and bounds. The CLI’s figures
command and bare-name preview also read the directory. studio/figures.html has a hard-coded
FIGURES list; add the name there.
Add a CLI command
Section titled “Add a CLI command”bin/pixel.mjs: add acaseto theswitch (cmd). UseloadSpec(path)(resolvesextendsandfigure),compileOrExit(spec)(prints warnings, exits 1 on errors, prints bounds warnings),overridesFrom(args)for the shared render flags, andencodePNGfor images.compileOrExitalso applies--skin(every command exceptbundle).- Document it in the header comment block. The default case prints every line that starts with
//at column 0 as the help text. - Mention it in
README.mdand the “Agent workflow” section ofdocs/SPEC.mdif agents should use it. There are no CLI tests today. If you add one, spawnnode bin/pixel.mjswithnode:child_processfrom a newtest/cli.test.mjs.
10. Testing
Section titled “10. Testing”npm test # node --test test/*.test.mjs (Node ≥ 20, no dependencies)The test suite uses node:test and node:assert/strict. The engine tests import from
src/core/index.js (and src/core/internal.js for building blocks) and build small specs inline. blob() in engine.test.mjs and arm() in
rig.test.mjs are the helpers.
| File | Covers |
|---|---|
test/engine.test.mjs |
SDF signs and distances. Validation paths, did-you-mean, parent cycles, bad tracks, and unknown-key warnings. LOD selection and overrides. Ramp ordering with the base colour kept. Track sampling (keys, waves, steps). Render determinism, size and outline. Thin features at 16 px. Pixel-snapped motion. minDetail gating. cut scoped to its own part. Sheet layout. PNG round-trip through inflateSync. Bundle variants. sx/sy waves around 1. |
test/rig.test.mjs |
Reach: the tip hits a per-frame target, aim fixes the end orientation, limits are respected, validation messages. Bounds warnings with frames and edges. extends: material merge, part patch/add/remove with descendants, animation merge, materialMap, chained resolveExtends. |
test/figure.test.mjs |
Every figure expands cleanly: no errors, no warnings, no motion notes, no bounds warnings. Gait feet move backward at exactly speed. pose keeps feet planted. Dressing and bone layers ride their bones, and tracks layer on the motion. Figure errors point at paths. Follow-through lags during the gait and stays still at rest. Every example resolves and validates. Front view: planted feet, foreshortening. Hop: gravity arc, volume-preserving squash, shadow shrink. Events: footsteps at touchdowns, hop takeoff/land, jump launch/land, author events. Climb: feet planted on the wall at speedY. Ground line from the figure, fitted and overridable. Points baked per frame, with validation messages. Holds become durations; bundles carry ground, size, events, points, speedY. Variants merge points by name. States validated against animations and inputs; skins compile as patched characters. exportSheet: Aseprite frames and tags, PixiJS map, slices, extras. |
test/runtime.test.mjs |
pickVariant: integer scale ≥ 2, most detail within 20%, closest fit otherwise. The shared clock (a throwing subscriber cannot stop it; dt clamp and reset), checkBundle errors, deviceScale at fractional DPRs. jumpArc lands on time at the apex height; cells splits overlapping cut-outs into disjoint cells. parseCondition and StateMachine (inputs, sync, waiting for footstep, triggers, then: "previous", random fidgets). |
test/plugins.test.mjs |
Plug-ins, in their own file because registrations are process-wide: a registered shape, texture and motion validate, render and animate like built-ins; registration errors are clear. |
test/references.test.mjs |
The reference registry (references/, checked by scripts/references.mjs): every source is cited and every logged value matches, references/CREDITS.md is up to date with sources.json, and the checks catch bad licences, drifted values, unknown sources and measurement files that do not say who, when and how. |
test/browser/runtime.html |
24 in-browser checks of <pixel-sprite> (open it on real devices; passes in Chromium and the iOS 18.1 Safari simulator): single load on upgrade, reserved box, errors and reload(), races, shared sheets, device-pixel scaling, decorative alt, touch and mouse input, one-shots, the clock, footstep events, holds, point() with flip, groundOffset, hitTest(), the state machine, skins, transition clips, rage clicks. Run in Firefox and WebKit with scripts/browser-check.mjs. |
Not covered by tests: the CLI, the studio, the <pixel-stage> / <pixel-actor> elements beyond
jumpArc and cells (try demo/stage.html), <pixel-sprite> beyond the Node helpers except in the
manual browser page, individual textures, dither, innerLines, contactShadow, shine, and the issues listed in
section 8.