Citadel — rendering & assets
This page is generated from the project corpus and rewritten on every docs build. Edit the source in corpus/, not here.
Split out of citadel-overview.md on 2026-07-09. Art direction (what it should look like) lives in citadel-art-style.md; this page is the render machinery.
⚠️ Buildings are 3D meshes (2026-07-14). The char-recipe building path is DELETED.
iso-draw.tsand theBUILDING_RECIPESchar bodies no longer exist — everybld/*frame (21 base + the mill's animation frames + the four@litnight companions) is generated by the mesh renderer and injected asMESH_OVERRIDESinto the atlas. Char recipes still author the non-building sprites (villagers, fx). Prose below that describescottage/postMill/fortform builders is historical — kept for the design rationale (why each type has its own silhouette), not as a map of the current tree.
The tint-alpha trap (fixed 2026-08-23)
Citadel authors its flat ground quads by packing opacity into the tint:
packTint(hex, alpha) returns 0xRRGGBBAA. The engine does not render that byte —
tintFloats (webgl2/renderer.ts) takes
RGB from the tint and alpha from the sprite's own alpha field, by design, so exactly one
place controls opacity.
Citadel's isoFlatSprite and quadToSprite were passing alpha: 1, so everything authored
translucent rendered fully opaque: the placement ghost, drag-paint preview, building
footprint shadows, the cluster/selection diamond, the mood glow, night light pools and fire
glow. It shipped that way through both backends — WebGPU discarded tint alpha too.
Why no test caught it: the render tests asserted on tintRgba, the value that never
reaches the GPU. They were green while the pixels were wrong. The fix lifts the tint's alpha
byte onto the sprite (spriteAlphaOf in render/quads.ts, applied in both quad→sprite
helpers; a 0xff tint multiplies by 1, so roads and bridges are untouched), and the new tests
assert the sprite alpha — they fail on the pre-fix code.
The standing rule: a quad's opacity must end up in sprite.alpha. Asserting a tint byte
proves nothing about what renders. Related: the ambient-crowd dim (brief 105) already had to
be a sprite alpha for this reason — that was the clue that went unfollowed.
Owed: a real-browser pass. This changes how several Citadel surfaces look (correctly, per their own comments), and no screenshot has been taken since.
Mesh building renderer (2026-07-14)
The 2D ASCII-recipe approach could not produce recognizable complex buildings reliably — authoring was blind (no visual loop), and a whole wave of forms failed unseen. Buildings were rebuilt from scratch as in-code 3D meshes:
- Model — an indexed triangle mesh (positions + tris + per-face material) under
render/sprites/mesh/, assembled from
parametric primitive generators (box / cylinder / cone / pyramid / gable) plus transforms + merge.
MESH_MODELSmaps each building type to its model. - Rasterizer — a small software rasterizer: dimetric projection matching iso.ts, back-face cull, per-pixel z-buffer, flat-shade each triangle by face normal onto 3 adjacent Apollo ramp steps, then a silhouette/depth-crease outline.
- Wiring — it emits the existing
RasterizedRecipecontract, soatlas.tsdrops the output in as per-name frame overrides (MESH_OVERRIDES). Nothing downstream of the atlas changed. - Emissive materials +
@litnight frames (Phase 3,dfd754d). A material can be marked emissive: the renderer gives it one flat tone for every face orientation instead of quantizing the normal onto the shading ramp. house / bakery / smith / healer carry real window geometry — a dark recessed pane by day, warmlampGlowat night (the smith's hearth also runs hotter,hotEmber). Thebld/<type>@litmodels (mesh/models/lit.ts) are anti-drift by construction: a lit frame calls the SAME day-frame factory and remaps tri materials, so day and night can only differ in which materials emit, never in shape. - Heights follow
BUILDING_HEIGHT_TILES, so tall buildings loom. Shipped in6cc32fb(Phase 1) +d1e7c7c(Phase 2) +dfd754d(Phase 3), browser-approved on a real GPU; specs in the closed rebuild todo + Phase-3 todo.
Load-bearing rules for anyone touching this pipeline
- Override the ANIMATION frames, not just the base. The mill needed
bld/mill@1..7overridden too — a base-frame-only override silently left the spinning mill in the old style, because the renderer cycles the@Nframes. BUILDING_SPRITE_TYPESmust derive fromMESH_MODELS. It (and the atlas) used to derive from the charBUILDING_RECIPES. Deleting those without re-deriving would have made every building silently fall back to a tinted box — no crash, no failing test. Derive the type set from the thing that actually rasterizes, so it can never claim art that doesn't render.- Mesh models must import frame names from the LEAF
recipes/buildings, never the barrel. The barrel (recipes/index.ts) importsMESH_MODELS, so a model reaching back through the barrel closes an import cycle and leavesMESH_MODELSundefined at module-eval time (it bitindustry.ts, which wantedmillFrameName). - Guards must read
MESH_OVERRIDES, not recipes. The silhouette/recipe tests kept passing while grading char art the game no longer drew. Grade the rastersatlas.tsactually bakes.
Rendering & assets
Citadel renders through the engine's single WebGL2 backend (there is no other backend to fall back to, and none is needed — WebGL2 is ~98% supported). If it cannot start, boot shows a message rather than leaving a blank surface. Terrain is baked into
the static layer once, as iso diamonds. At 192×192 the iso world is 6144 px wide, past one texture, so
the engine draws it as 2048 px patches. Each patch bakes only the diamonds that reach its iso rect
(makeTerrainDecorate's region, regionTiles), in the whole-world order, so diamonds that cross a
patch edge come out the same on both sides. Since 2026-11-03 this replaces the re-baking camera window of
briefs 21/22 (decisions.md → Renderer). __citadel.windowState() in dev reports the
layer's patches (staticLayerInfo), and ?textureLimit=4096 in dev behaves as a 4096 px device. Buildings,
villagers and raiders are sprite-batch quads.
Sprites (2026-06-19). Entities are real pixel-art sprites, not flat colored
boxes. The art lives as ASCII PixelRecipes under
client/src/render/sprites/ and is
rasterized + shelf-packed into one in-process atlas at client boot
(createCitadelSpriteAtlas in sprites/atlas.ts) — no committed PNGs, no npm run
build step (unlike Farm Valley's @farm/atlas-recipes → npm run atlas committed-PNG
pipeline, which Citadel can't import: games never import each other). The atlas keeps a
1×1 white px frame that the tinted-box paths still use (ghost, wear, house-cluster
border). The night light-pool glow instead stamps the soft fx/diamond frame on
a GROUND layer below buildings (so emitters like the market glow on the ground, not
as a hard orange box over the sprite — 2026-06-21 fix). Per-type frame mapping +
tinting live in quads.ts:
- Buildings sample
bld/<type>tinted white (recipe colors show); a burning building multiplies its tint toward orange. ~20 building types have art; a type without a recipe falls back to a tinted box (never requests a missing frame). Road/wall/gate keep their pre-existing autotile/inset-box rendering. - Villagers / raiders are grey-ramp silhouettes (
vil/person,raider); the per-instance tint (FSM-state color / red) multiplies into a shaded colored figure, so state still reads at a glance.
The recipe palette (sprites/palette.ts) derives every swatch from an EDG.* constant
via rgbOf, so it's EDG32-clean by construction (a test re-asserts it). Rasterize +
pack are pure (deterministic, headlessly tested); only the canvas/createImageBitmap
step is browser-only. Phase 2 (not done): textured terrain tiles, road/wall autotile
sprites, a gate sprite, MP owner-color differentiation.
Runtime layer scheme + landform/motion pass (2026-07-16, b389832/4bc3a4b). The quad
layer order is now export-pinned in citadel-renderer.ts (tests assert it): roads 5 <
coverage 6 (placement ring + catchment wash — moved from 38 so buildings stay visible on
top of it) < light pools 9 < entities 10 (buildings/villagers/raiders, iso-sorted) <
ambient crowd 15 < no-road pip 39 < ghost 40; baked terrain sits below all of them. Terrain
relief is a hillshade (render/hillshade.ts):
a heightfield derived from terrain KIND (water→stone) + fBm, lit from the NW sun, choosing each
type's LIGHT/DARK DITHER_ACCENTS per slope — elevationFill is retired for landformFill
(open-grass relief is deliberately subtle; tune SLOPE_GAIN/HEIGHT_GAIN). Walker motion uses a
render-delay jitter buffer in entity-interp.ts:
snapshot arrivals jitter 0.2–88ms around the 50ms cadence, so drawing RENDER_DELAY_INTERVALS = 1.5
snapshots behind the newest (unclamped snapshotPhase, Farm's approach) cut hold-then-jump
stepping from ~41% of gaps to ~2%. All render-only; sim byte-untouched.
Visual polish (2026-06-21). Render-only ideas borrowed from tiny-world-builder:
elevation-biased terrain dither, a directional NW-sun building drop-shadow
(LAYER_SHADOW), a deeper-night/stronger-dusk wash, and extra procedural detail in the
sprite generators (roof shingles, wall seams, doorstep, fort ashlar courses). All
render-only, EDG32-clean, sim untouched. See the 2026-06-21 log entry.
TRUE ISOMETRIC — IMPLEMENTED (2026-06-21). Citadel now renders 2:1 dimetric
isometric: diamond terrain, iso projection with a working screenToTile inverse
(placement/ghost pick the right diamond), painter's-order depth sort, iso
road/wall diamonds (fx/diamond frame), and true-iso building sprites
(diamond base + two shaded wall faces + hip roof, sprites/recipes/iso-draw.ts)
at 32-based resolution + 32×32 units. The single source of truth is
render/iso.ts (tileToIso,
isoToTile, isoFootprintBox, isoSpriteDims, isoDepth). Sim + determinism
untouched — iso is a pure render/input/art change; CHECK_DETERMINISM stays
byte-identical. Verified in-browser; 174 client tests + iso-volume guard + EDG32
guard green.
Per-building FORMS + 4× detail + animated mill (2026-06-21). Buildings were all the same hipped iso box ("everything looks like a house"). A first pass added per-type accents; a second pass (this one) rebuilt distinct medieval forms with their own proportions, authored at 4× resolution, with an animated mill.
- Authoring resolution: 32-based (
ISO_ART_SCALE = 1). The renderer sizes a building's quad in world-px viaisoSpriteDims(iso.ts); recipes author atisoArtDims=isoSpriteDims × ISO_ART_SCALE. A pass tried 4×, but the user judged 32 dense enough in practice, so buildings stay native res like units/terrain. TheISO_ART_SCALEknob stays so the authoring math is scale-independent. (This retired the "upscale units/terrain to 4×" follow-up, brief 94.) - Reference restyle (done, brief
95). Per
user reference art (Reiner "Isometric Buildings" + zatoart/xilurus itch packs),
the forms were restyled toward warm terracotta tile roofs (
drawGableRoof: ridge cap + eave-overhang shadow + tile courses), half-timber framing (drawTimberFrame: oak studs + diagonal cross-braces over cream infill), ashlar stone coursing on forts (drawAshlarCourses: staggered blocks, not a per-pixel checkerboard), and small ground-prop plots (isoGroundProps: dirt apron + barrel + sack). EDG32-only (clay/rust/salmon, cream/tan, bark/woodDark, slate/steel). Verified in-game. - Form builders lived in
iso-draw.ts(deleted 2026-07-14 — see the banner at the top of this page; the forms below are the historical design rationale, not current code), mapped per type inbuildings.ts:cottage(half-timbered, steep peaked hip roof, studs+window+door — house / bakery / woodcutter / sawmill / smith / healer),postMill(tall weatherboarded body on a trestle + roundhouse base + 4 sails),openField(tilled furrows + post-and-rail fence + gate + crops + hay bale — farm),marketStalls(red-striped awnings + tables + goods — market),church(nave + bell tower + spire + cross — chapel),warehouse(barn doors + hayloft dormer — storehouse / tradingpost / town-hall),fort(ashlar courses + flat crenellated deck + arrow slits — watchpost / tower / garrison / keep),boxBuilding(mine pithead / quarry pit / well). - Animated mill (render-only). Recipes
bld/mill+bld/mill@1..7are the post-mill with sails rotated through a 90° sweep (4-fold symmetry).millFrameAt(clockMs)(index.ts) picks the frame;buildingQuad(b, clockMs)→pushScene(..., clockMs)→main.tspasses the existingperformance.nowrender clock. No sim/determinism impact (wall-clock pacing, render-only).BUILDING_SPRITE_TYPESexcludes@-suffixed frames so they aren't mistaken for building types;BUILDING_HEIGHT_TILES.millraised to 3 to match the form.
All render-only, EDG32-clean (every char via SWATCH). Guards green: 187 client
tests (incl. mill-frame test + per-type opaque-fraction floors — open farm/market/
mill get a lower floor since they're intentionally sparse), EDG32 palette test,
typecheck. Verified in-browser (gallery harness + the actual game): forms render
distinctly through the real atlas pipeline and the mill's sails turn.
⚠️ Sprite anchor convention (load-bearing). The engine sprite-batch anchors every sprite by its CENTRE (both backends draw
pos ± 0.5·size). The iso helpers iniso.tsreturn top-left rects, so the conversion to a sprite must add half-extents — this happens in exactly two choke points,quadToSpriteandisoFlatSprite. Skipping it shifts every iso sprite up-left by half its size (ghost lands left of the cursor, buildings float off their footprint). RelatedlyisoSpriteDims.heightisroofH + wallH + diaH/2(not fulldiaH) becauseiso-draw.tscentres the ground diamond on the wall-bottom mid-line. (Both fixed 2026-06-21; see log.) Terrain is baked FLAT (elevation 0) — a former 0/1-step relief lift inmakeTerrainDecoratedesynced the ground from the (flat) sprites, roads/bridges, andisoToTilepick, floating bridges off the water grid and opening dark seams; the elevation field now only tints the dither, never offsets geometry. Keep terrain, sprites, network tiles, and the pick all at elevation 0.
Brief:
../todos/2026-06-21-citadel-true-isometric.md
(mostly-done). The old "flat-box anomaly" is CLOSED, not open: the
market/storehouse/bakery flat-render was a host-specific driver artifact on the
Playwright-bundled Chromium — it does not reproduce on a real GPU, and the sprite data proved
byte-identical to a working house. Visual checks need system Chrome (channel:"chrome",
--enable-unsafe-webgpu); WebGPU could not render headless here at all. Cleared 2026-08-18: the WebGL2 migration made headless rendering work, so this is no longer a verification blocker. Iso windowing for the large MP
map is still deferred (and MP itself is deprecated — see
citadel-mp-deprecated.md).
BRIDGES — roads over water (2026-06-21). A road dragged onto a Water tile
auto-converts to a bridge (new building type + production def isBridge, both 1×1)
in placeOne: roads on land stay
roads, the water tiles of the same drag become bridges. A bridge is the only way
to place anything on water — it bypasses the buildable (terrain-walkable) check but
requires the tile to BE water and unoccupied, so bridges cannot overlap (nor
sit on a building/road). It joins roadGrid (so villagerWalkable + road-connectivity
treat it as a road) and a new walkablePred (terrain-buildable OR road tile) keeps
the decked water tile walkable in the rebuilt raider/path grid. Demolish clears
roadGrid before rebuilding so a removed bridge stops reading walkable. Render:
two new textured flat-diamond fx frames — fx/road (cobblestone) and fx/bridge
(railed wooden plank deck) in sprites/recipes/fx.ts;
isoNetworkTiles now emits bridge tiles (and carries each tile's type + optional
frame), and pushNetworks stamps the textured frame white-tinted (walls keep the
solid tinted diamond), with bridges depth-sorted just under roads so a bridge mouth
tucks beneath the road it meets. Determinism untouched (terrain/placement only; the
art is render-only). Guarded by systems/bridges.test.ts (road→bridge on water, road
stays road on land, bridge walkable, no-overlap) + an isoNetworkTiles bridge-frame case.