This page is generated from the project corpus and rewritten on every docs build. Edit the source in corpus/, not here.
⚠️ Historical, pre-2026-08-18. The
Canvas2dRendererbackend this page repeatedly names was deleted in the WebGL2-only migration (see decisions.md → Renderer). Its former paths are shown as plain code text, not links, because the files are gone. The CPU rasterizer it shared (compareSprite/drawSprite/createOffscreen) lives on atengine/core/src/render/raster2d.tsand is still load-bearing for texture baking.
Performance & Optimization
Optimization opportunities for the engine, filtered against what the code actually does (verified 2026-06-05). Ordered by impact-for-effort. Generic "best practice" advice that doesn't apply at Farm Valley's scale (~4 farmers + tens of entities) is explicitly called out so it isn't re-litigated.
Determinism guardrail. Any of these is a refactor of how state moves, never what it computes. Prove behavior-preservation with multi-seed
EXPORT=jsondiffs, not justCHECK_DETERMINISM=1(which only proves reproducibility). See architecture.md and the root CLAUDE.md.
Post-migration reading (2026-08-18, WebGL2) — JS side healthy, fps not yet measurable
First numbers after the WebGL2-only migration, Farm via ?profile:
| metric | value | note |
|---|---|---|
ui.flush | 3.49 ms mean / 5.10 p95 | at ui.quads mean 7,272 |
render.endFrame | 7.73 ms mean / 9.60 p95 | |
frame (JS) | 12.09 ms mean / 17.10 p95 | |
worker tick | 1.22 ms mean | sim unaffected |
| fps | 10–19 | not interpretable — see below |
The tint-cache win survived the backend swap. Brief 05's bar was ui.flush ≈ 5 ms at
~2,000 quads; measured 3.49 ms at 7,272 quads — ~3.6× the quads at lower cost. The
brief-118 per-(atlas, frame, rgb) cache lives in the CPU rasterizer
(render/raster2d.ts + ui-draw.ts), which the migration did not touch.
fps from that run is meaningless and must not be compared to the 2026-06-12 baseline.
gpu.renderer read ANGLE (Google, Vulkan 1.3.0 (SwiftShader Device (Subzero)), SwiftShader driver) — headless Chrome, software rasterisation. That is the same trap
documented in the 2026-06-12 banner above. A real-GPU ?profile export is still
required before claiming perf parity (baseline: fps ~99, frame ~5 ms).
Tier 0 — 5 fps regression (in-canvas UI glyph tint) — ✅ RESOLVED 2026-07-15 (brief 118, 4fd48dc)
➡️ Newest banner — read first. Observed 2026-07-15 on real hardware: 5 fps / ~216 ms frame (583 entities) vs the 99 fps baseline below. Regression window: the 2026-07-01 in-canvas UI migration. A new
PROFILE_ENABLED-gatedui.flushsub-timer (+ui.quadscount) insideWebGpuRenderer.endFrameproved the attribution on the affected machine:ui.flushmean 106.0 ms offrame116.6 ms (~91%) at ~1,950 UI quads/frame — every glyph is a tinted quad and ui-draw.tsdrawUIQuadpaid a 5-op Canvas2D composite (multiply→destination-in round-trip) per quad per draw.panels(2.9 ms) andpushSprites(5.6 ms) were noise;_ghostCovered(F3) sat inside the ~1.3 ms endFrame remainder — dismissed.What shipped (F1 only): a per-(atlas, frame, rgb) tint cache in
drawUIQuad— the composite runs once per distinct tinted glyph into a cached canvas (WeakMap keyed by theLoadedAtlasImageobject, so a re-baked atlas self-invalidates; per-atlas map reset at 4,096 entries as a safety valve; alpha stays draw-time, never baked). Same scene, all panels open: fps 3.36 → 57.06,ui.flush106.0 → 5.2 ms,render.endFrame107.4 → 6.1 ms. Citadel benefits for free (same rasterizer). F2 (overlay dirty-skip) was NOT taken — gated on F1 being insufficient, and it wasn't. Numbers: performance-measurements.md 2026-07-15 section.⚠️ Lesson: the per-panel dirty guards never saw this cost —
renderTreere-submits every glyph quad every frame by design, so the cost lands underrender.endFrame, invisible to thepanelssub-timer. When endFrame is hot, split the UI flush out (ui.flushis now permanent) before blaming the GPU submit.
Tier 0 (historical) — Live FPS regression — ✅ RESOLVED 2026-06-12 (not reproducible on real hardware; brief 84)
➡️ Read this banner first. A user-supplied real-GPU
?profileexport (gpu: ANGLE (AMD Radeon …, Direct3D11)— a genuine GPU, not SwiftShader) shows the live WebGPU game at fps 99.2,frameJS 5.0 ms mean / 7.5 ms p95 (render.endFrame2.7/4.4 ms,pushSprites0.93 ms,panels0.51 ms /relmatrix0.028 ms,interp0.06 ms; servertick1.06 ms). The "15–30 fps" was a headless-Chromium-on-SwiftShader (CPU-raster) artifact — exactly the caveat the 2026-06-11 profile flagged. On real hardware there is no GPU-overdraw problem to fix.What shipped (brief 84): (1)
DEFAULT_ZOOM = 2(config.ts) — the camera opens framed-in (kept by user choice); its perf value is now insurance for weak/integrated GPUs + high-DPI, since on a real GPU full-world zoom-1 raster is also fine. (2) A?profileprofile-export button +window.__exportProfile()+DebugOverlay.exportReport()+ a WebGL GPU-identity probe (profile-export.ts) — kept for future render work. Not changed: the uncapped setTimeout render loop (user kept it for input latency, accepting ~40% discarded frames vs a 60 Hz display). Closed without action: GPU-overdraw reduction (no problem on real HW) and sort-on-dirty (the sort never appears in the profile).⚠️ Lesson: never diagnose a raster/GPU regression from a headless SwiftShader profile — its absolute fps is CPU-raster-pessimistic. Require a real-GPU
?profileexport (now one click) before chasing Tier-0 raster work.
Historical (pre-migration, Canvas2D). Everything below this line profiled the Canvas2D renderer on 2026-06-11, before the WebGPU-only migration + the real-GPU reading above. Kept for the suspect-number references (#1–#5) and the relmatrix dirty-guard (which shipped and holds). The bottleneck it names — "canvas raster, not DOM/particles" — was a SwiftShader artifact; treat this whole subsection as superseded by the banner.
Pre-profile reasoning (superseded). The 2026-06-05/06-10 "Measured results" tables show ~60 fps at ~6–10 ms/frame, so 15–30 fps meant a regression after those — suspected the render-side features that landed since (camera smoothing 67, ambient 68, weather particles 74, tab-resync 66); the world is now 160-wide with 21 farmers. All transport/render-only.
Ranked by likelihood × impact-for-effort (each names the file:line so it can be confirmed):
-
0. Re-profile first (gates everything else). Run
npm run dev+?profile(config.tsPROFILE_ENABLED); the DebugOverlay showsframe/interpmean+p95. Confirmframe≫ 16.6 ms and identify whether the cost is DOM (panels), particles, or canvas draw. Per the resource rule, ask the user before any longer perf probe. Capture the before/after number for each fix. -
1.
Relationship matrix rebuilds 441 DOM cells EVERY frame (top suspect).— OBSOLETE 2026-07-09. The in-canvas UI migration (2026-07-01,@engine/ui) deleted every DOM panel:createEl(no longer appears anywhere undergames/farm/client/src/ui/, and relationship-matrix.ts is now a canvas widget that redraws only on trust change. Original finding kept for the reasoning: it had no dirty guard —update()rebuilt the full 21×21<table>(createEl+applyStylesper cell, thenreplaceChildren) on every render frame (~60 Hz), though trust changes at most per-tick (20 Hz) and usually per-day. That's ~28k element creations/sec + full-table relayout. Contrast the panels that already gate: wealth-graph (lastDayDrawnguard, wealth-graph.ts), observer (row reuse), event-feed (node reuse). Fix: cache a trust signature (or gate onclient.tickchange) and early-return when unchanged; ideally reuse cells like the other panels. Highest-leverage single change. -
2. Unbounded weather-particle spawning (brief 74, new). render-loop.ts:279-319 spawns
(viewWidth/TILE) × 2.2rain rects (or× 0.9snow) every frame — at the wide default-zoom viewport (whole 160-tile world) that's a few hundred particles/frame during a storm, with no pool cap. Compounded by particles.ts:93 usingsplice(i,1)(O(n) shift per dead particle → O(n²)-ish churn) and a per-particlearc()/fillRect()draw. Fix: cap total particle count, budget spawns/frame, and swap-with-last +pop()instead ofsplice. -
3. Gate the whole panel-update block on tick change. render-loop.ts:419-431 calls all 9 panel
update()s every frame though their data changes at ≤20 Hz. Even with per-panel guards this re-reads client state 60×/s. Wrap the block inif (client.tick !== lastPanelTick). Cheap, removes a class of future regressions. -
4.
Tier 2 culling now actually bites (was deferred when world was small).— MOSTLY SHIPPED, verified 2026-09-19 against WebGL2. The original finding namedcanvas2d/renderer.ts, a file deleted on 2026-08-18; re-read against the backend that exists, three of its four asks are in:- Dynamic sprites are viewport-culled —
webgl2/renderer.ts:428-439rejects inpush()against a[_cullLeft,_cullRight]×[_cullTop,_cullBottom]box rebuilt per frame from the camera (:413-416) with a 32 pxCULL_MARGIN, testing the sprite's half-extents, not just its origin. - Shadows too —
pushShadowearly-returns on_inView(:441-442). - The static layer is no longer blitted full-frame —
StaticLayerPass.drawtakes aVisibleRectand samples only it (static-layer-pass.ts:189-192). - The per-frame queue realloc is gone too (the Tier 2b item below): the queue is a persistent array reused via
_queueLen(:404, :437-438), not= [].
What survives — and it got more load-bearing, not less:
this._queue.sort(compareSprite)still runs every frame (webgl2/renderer.ts:573). In Canvas2D that sort only fixed draw order. In WebGL2 the sorted queue is then walked to coalesce runs of the sameatlasIdinto one draw group (:575-606) — so the sort now also determines how many GL draw calls a frame costs, which makes sort-on-dirty both a bigger win and a riskier change (a stale order silently fragments batching, it doesn't just mis-layer sprites). Carried forward as its own item below ("Sort only when the set changes"). Nothing here needs a new culling spec: the culling gap this item was filed for is closed. - Dynamic sprites are viewport-culled —
-
5. Ambient layer cost (brief 68).
ambient.update+ambient.pushSpritesrun every frame (render-loop.ts:413-414). New since baseline; profile its sprite count and confirm it's culled toview(it's passedview— verify it uses it).
Likely root cause (pre-profile hypothesis): #1 (DOM thrash, constant cost regardless of weather) + #2 (particle storm, intermittent) together. #1 explains a steady 30 fps; #2 explains drops to 15 during rain/storm/winter. Profile to confirm before committing effort.
✅ PROFILED 2026-06-11 — hypothesis overturned: the bottleneck is canvas raster, not DOM/particles
Profiled live via Playwright ?profile (seed 0xc0ffee, #c0ffee-64-3c → ticksPerDay=60 so weather cycles fast; render loop still runs at 60 Hz). Added dev-only sub-timers in render-loop.ts (weather.spawn, particles.update, pushSprites, ambient, render.endFrame, panels, panels.relmatrix) gated by PROFILE_ENABLED (wall-clock, zero sim/determinism impact) + exposed window.__frameProfile() for a structured readout.
⚠️ Environment caveat. Measured in headless Chromium (WSL2, DPR 1, canvas 1428×590), which rasters the canvas on SwiftShader (CPU) — far slower at raster than a real GPU. So the absolute fps here is pessimistic; trust the relative attribution, and re-read
frame/fps on a real-GPU browser (see "what the user should check").
Measured (mean / p95, ~640-frame window):
| metric | before fix | after relmatrix fix |
|---|---|---|
bare requestAnimationFrame loop | 60.6 fps (16.5 ms, steady) — vsync is healthy, not throttled | — |
| game true render fps (frame-count / wall) | 40.7 fps | ~40 fps (unchanged) |
JS frame work | 7.1–7.8 / ~10–12 ms | 4–7 / 7–12 ms |
panels (all 9) | 3.28 ms | 0.28 ms |
↳ panels.relmatrix | ~3.2 ms (38% of the JS frame) | 0.015 ms |
render.endFrame (canvas draw JS) | 2.5–3.3 ms | 2.4–3.6 ms |
pushSprites / ambient / weather.spawn / interp | 0.27 / 0.01 / 0.01 / 0.09 ms | same |
particles.update | ~0 (no storm landed; rain only) | ~0 |
What this means. A do-nothing rAF hits a rock-steady 60 fps, but the game renders ~40 fps while doing only ~5–7 ms of JS per frame — well under the 16.7 ms budget. The missing ~10 ms is canvas raster + composite that runs after the JS callback and is invisible to the JS profiler; when total (JS + raster) spills past a vsync, the browser halves to 30 fps, so the average bounces 60↔30 ≈ 40. At the default zoom the camera spans the whole 160-tile (2560 px) world (config.ts worldUnitsX = WORLD_WIDTH*TILE, sx≈0.56 → zoomed out), so the viewport cull in renderer.ts push() drops nothing and every frame rasters the full static-layer blit + a bilinear water-pattern fill (two passes, sx<1) + ~470 sprites.
Verdicts on the ranked suspects:
- #1 relationship matrix — REAL waste, FIXED, but not the headless straw. Rebuilt 441 DOM cells every frame = ~3.2 ms JS (38% of the frame) + per-frame table reflow. Shipped a signature-based dirty guard (relationship-matrix.ts
computeSignature/lastSignature, mirrors wealth-graph'slastDayDrawn) → 3.2 ms → 0.015 ms,panels3.28 → 0.28 ms. But true fps did not move (headless is raster-bound, which masks DOM-paint savings). On a real GPU where raster is cheap, this DOM cost is a plausible actual straw — so the fix is worth shipping regardless and the user should re-check fps with it in. - #2 weather particles — NOT the bottleneck (as far as observed). Could not land a storm in the probe window (spring drew sunny/normal/rainy);
particles.updatestayed ~0 andweather.spawn~0.01 ms; fps unchanged across dry→rainy. The code issues (uncapped spawn, O(n)spliceremoval) are real but did not bite at observed levels — deferred, not shipped. - #3 gate panels on tick — moot. Per-panel guards (now incl. relmatrix) already make the whole
panelsblock 0.28 ms; no need to gate the block. - #4 dynamic-sprite culling / sort-on-dirty — this is where the real lever is. Confirmed culling is a no-op at default zoom (whole world in view). The reducible raster cost is the full-world static blit, the two-pass bilinear water fill, and the per-frame whole-queue
compareSpritesort. Untouched — these are bigger changes and headless SwiftShader can't validate them faithfully; needs a real-GPU before/after. - #5 ambient — negligible (0.01 ms JS; its raster is folded into the whole-world cost).
Shipped this round: suspect #1 dirty guard only (safe, correct, zero-risk JS/DOM win). Step 0's dev-only sub-timers + window.__frameProfile are kept (gated by ?profile; the overlay still only prints frame/interp, so use window.__frameProfile() for the full breakdown).
What the user should check (real GPU, disambiguates the remaining cost): open the live game with ?profile, read the overlay fps and frame mean/p95 with the relmatrix fix in. If frame JS is ~5–7 ms but fps is still 15–30 → it's GPU raster (do #4: clamp default zoom / cull / clip the static blit / sort-on-dirty / drop the second water pass at zoom-out). If frame JS is now ≥16 ms → a JS path regressed and we re-profile that. Capture before/after per fix.
Already done — do not redo
- Query iteration is pooled.
for...ofover a query borrows a scratch buffer and returns it; steady-state iteration allocates zero arrays — world.ts:65-97. - Static layer + water pattern baked once, then drawn as one pass per frame — shipped as brief 07's Canvas2D
drawImage, and it survived the WebGL2 migration intact: the CPU bake is stillcreateOffscreen+ sorteddrawSpriteonto an offscreen 2D canvas (webgl2/static-layer-pass.ts), only the presentation changed (onetexImage2Dupload, then an attributelessdrawArrays(TRIANGLE_STRIP, 0, 4)over the visible sub-rect). The textbook "layer caching" win, already shipped. - Message bus uses buffer-swap (
inflight↔deliverable) instead of reallocating — message-bus.ts. - Coastline foam bubbles are viewport-culled — main/render-loop.ts. (The only culling currently in the renderer — see Tier 2.)
- Test-suite runtime tuned (2026-06-10). sim-core runs with
pool: "threads"+isolate: false(vitest.config.ts — module-state safety rationale in the file; verified green under shuffled file order), and the three heaviest live-sim test files (coral-fishing, orchard, tile-features) each drive ONE shared deterministic run inbeforeAlland latch per-milestone observations instead of booting near-identical sims per spec. Full suite ~66s → ~45s wall; sim-core 54s → ~25s solo. Don't re-split the shared runs or re-enable per-file isolation without re-measuring; the floor is now coral-fishing's single ~12k-tick JsPathfinder run (~24s).
Tier 1 — Highest impact
T1.1 The sim→render snapshot boundary
Boundary changed (briefs 57–58, 2026-06-10). The sim no longer runs in an in-browser Web Worker over
postMessage/structured-clone — it runs in the Node server (@farm/server, sim-host.ts) and ships eachRenderSnapshotto the browser asJSON.stringifyover a WebSocket. So the cost is now JSON serialization + network framing, not structured clone, and theSharedArrayBuffer/transfer ideas below no longer apply (there's no shared address space across a socket).
Re-measured 2026-06-10 (post 21-farmer radial reorg + 40→52 world widening) with probe-snapshot-size.ts, seed
0xc0ffee, day 19: the snapshot is now ~143 KB/tick raw JSON — 4× the 36 KB the old table below records. At 20 Hz that is ~2.8 MB/s of stringify (+ permessage-deflate) per viewer (one SimHost per WebSocket). Composition:
section KB % changes… sprites(398: 309 structure + 49 decoration + 21 farmers + 15 crops + 4 npc)104 73% structures/decorations ~daily; only ~40 sprites move per tick wealthSeries(21 farmers × per-day rows, full history re-sent)19.6 14% day boundary only; grows linearly → ~100 KB/tick by day 100 observer10.7 7.5% intra-day (must stay per-tick) relationships+leaderboard+ rest~8 5.5% intra-day Concrete wins, in impact-for-effort order (all transport/snapshot-side, sim untouched; verify each with the fast 3-day/3-seed diff):
Send✅ Done 2026-06-10.wealthSeriesonly on day boundariesRenderSnapshot.wealthSeriesis nowSnapshotWealthSeries[] | null: with a per-runSnapshotSpriteState(the server path) the series is rebuilt + sent only whenrunHistoryRows.lengthchanged (rows only grow at day boundaries;wealthRowsSenttracks the last send); the client caches the last non-null value (SimClient.cachedWealthSeries). Builders without per-run state (tests) keep per-tick behavior. Steady-state snapshot 143 → 123 KB and the unbounded with-day growth is gone. Verified: typecheck, full suite green, 3-seed baseline diff MATCH (sim untouched).Tooltip string churn — cheap half✅ Done 2026-06-10:daysGrowingserializes astoFixed(1)in sprites.ts (was the raw per-tick float, ~17 chars of churn per crop per tick). The bigger fix (descriptions in a separate id-keyed table, sent on change) folds into the brief-72 protocol rework like items 3/4.- Coarse static/dynamic sprite split. 358 of 398 sprites (structures + decorations) change ~daily; ship them as a separate message on change (the static terrain layer already works this way via
buildStaticLayerSprites) and keep only the ~40 moving sprites per tick. ≈70% snapshot reduction without any binary codec.- Omit default-valued sprite fields (
rotation: 0,alpha: 1,action: null,id: null…) from the JSON. ~261 B/sprite today; mostly boilerplate.
Gate before building 3/4: run probe-perf.ts (1→5→10 synthetic viewers, ~3 min, loads the box — needs user sign-off per the resource rule)— GATE ANSWERED 2026-06-10 (user-approved ramp run; full table under "Measured results (2026-06-10)" below). Verdict: deflate already makes the bytes a non-issue on the wire (14× → ~7 KB/snap, ~150 KB/s/viewer) and serialization is small next to the tick — the cost that actually scales is one full sim per WS connection (~8% of a dev core + ~25 MB RSS per viewer; ~80% of one core at 10 viewers, all on one Node thread). So items 3/4 are not worth building as standalone JSON slimming; they fold into the shared-run/lobby protocol rework (briefs/game/done/72), which attacks the per-connection-sim model itself (encode-once broadcast). Items 1–2 remain worth doing regardless (item 1's unbounded growth is real: payload grew 100→126 KB within the probe's first ~3 sim-days).
T1.3 WebSocket transport hardening — TODO (queued 2026-06-10, online-research pass)
The split (briefs 57–58) is new and the WS transport has cheap, high-value wins that don't touch the sim (render/transport-only → determinism untouched; re-verify with the fast 3-day/3-seed diff anyway). Grounded against the actual code:
- Server today (server/src/index.ts):
new WebSocketServer({ port })with nopermessage-deflate, nosetNoDelay. It does drop-stale snapshots onws.bufferedAmount > 1MB(correct for a spectator game) and sendsJSON.stringify(msg). - Client today (sim-client/client.ts): renders one tick (~50ms) behind latest and lerps prev→current with
smoothstep(alpha)— this is textbook snapshot interpolation and is correct, but a 1-tick buffer tolerates zero dropped snapshots before it underruns.
TODOs, in impact-for-effort order:
- Enable
permessage-deflatein theWebSocketServeroptions. ✅ Done 2026-06-10 (server/src/index.ts,perMessageDeflate: { threshold: 1024 }—thresholdskips tiny control frames). ~70–80% size reduction on repetitive JSON at near-zero CPU for 36KB frames. Typecheck clean; transport-only. Verifying the Caddy WS reverse-proxy passes compression through in prod was dropped by decision 2026-06-10 (open-questions round) — if the proxy strips it the app still works, just heavier frames. - Bump render delay 1 tick → 2 ticks (~100ms). ✅ Done 2026-06-10 (open-questions round):
renderDelayMsis now2 * msPerTickin client.ts, comment updated. Decided intentionally: display latency is irrelevant for a spectator game; absorbing a dropped snapshot + TCP retransmit is not. -
setNoDelay(true)on connection. ✅ Done 2026-06-10 (server/src/index.ts — narrowsws._socketsince it's absent from thewspublic types). No-op for today's large JSON frames, but in place ahead of any binary/delta codec (small frames + Nagle + delayed-ACK = ~40ms artificial latency). - Binary/delta wire codec — DEFER (same gate as T1.1(a) / brief-09 #7). Only if
permessage-deflateleaves bytes/sec too high at a real concurrent-viewer target. Quantized binary can reach ~4 bytes/entity (~1.2KB vs 36KB). Don't build speculatively. -
visibilitychangehandling (correctness). rAF pauses when the tab is hidden; on return, the wall-clockalphamath can spike / the snapshot buffer can avalanche. Confirmed absent from the client; briefed 2026-06-10 → briefs/game/done/66-visibilitychange-pause-resync.md (pause + full resync variant).
Explicitly NOT worth it: WebTransport / WebRTC datagrams. For a non-competitive buffered spectator game, TCP head-of-line blocking is absorbed by the interpolation buffer; WebTransport needs HTTP/3 (not in plain ws) + a ~15%-of-users fallback. Premature.
T1.2 Per-frame interpolation allocates on the render thread
getInterpolatedSprites() runs every frame (~60fps, not per tick): new Map() of prev-sprites, .map() a fresh array, spread {...s} per sprite — sim-client/client.ts, main/render-loop.ts. Classic GC-churn.
- Pool the interpolated sprite array + objects; mutate in place across frames.
- Index prev-sprites by id once when the snapshot arrives, not every frame.
- If sprite IDs are dense, replace the
Mapwith a plain indexed array.
Tier 2 — Culling & clipping (classic strategies, currently mostly absent)
Status 2026-09-19: this tier is done except the last bullet. Kept for the reasoning, and because the
last bullet is still open. The static backdrop is drawn each frame but clipped to the visible world
rect — in WebGL2 that is the VisibleRect handed to static-layer-pass.ts's
draw, so zoomed-in frames sample only the on-screen portion of the baked texture. The world grew
160→240 on 2026-06-12 (2.25× the cells); DEFAULT_ZOOM rose 2→3 to keep on-screen tile density, so at
the default zoom the viewport is now smaller than the whole 240×240 world and the clip/cull DO bite. At
the lowest zoom (full-world establishing view) the clip is a no-op and the whole baked texture is sampled
every frame; dynamic sprites and shadows are viewport-culled in push()/pushShadow() (also a no-op only
at full-world zoom). So the classic 2D wins still matter here:
Viewport culling of dynamic sprites/shadows.DONE —push()andpushShadow()test sprite bounds against the camera box + a 32 px margin (webgl2/renderer.ts:419-450).Clip the static-layer blit to the visible source rect.DONE — the pass takes aVisibleRectand samples only it (static-layer-pass.ts:189-192).MOOT under WebGL2 — this was a Canvas2D overdraw trick. The GL path already scissors to the canvas and the wash is a full-screen pass by design; a dirty-rect scheme would fight the passes, not help them.ctx.clip()/ dirty-rectangle redraw.- Sort only when the set changes — the one Tier 2 item still open.
this._queue.sort(compareSprite)runs every frame (webgl2/renderer.ts:573); z-order rarely changes frame-to-frame. Bucket by layer or sort-on-dirty. Read :575-606 first: the sorted queue is walked to coalesce same-atlasIdruns into draw groups, so the sort controls draw-call count as well as layering, and any incremental scheme has to keep atlas runs contiguous — not merely keep z-order correct.
Tier 2b-pre — Sim tick re-verified at 21 farmers (2026-06-10)
A 2-day headless run (2,400 ticks, 21 farmers, default world) completes in ~2s wall including Node startup — the sim tick is still well under 1 ms against the 50 ms budget, so the 2026-06-05 "engine far under budget" conclusion survives the 4× roster growth. A code sweep (2026-06-10) catalogued the remaining per-tick allocation/O(n²) sites for the record — none are worth fixing for throughput at n=21; they only matter as GC pressure if many SimHosts share one Node process (re-evaluate after probe-perf):
- plot-sense.ts — 4 fresh Maps per tick + per-farmer
.slice().sort()of empty plots. - encounter.ts — fresh sorted farmer array + by-region Map + O(n²/2) pair scan per tick.
- rivalry/system.ts
activeAlliances()/activeRivalries()— O(n²) pair scans, called per snapshot tick via the builder. - snapshot-builder/panels.ts
buildRelationshipsData— O(n²) trust matrix per tick (441 cells at n=21). - ap.ts:208 —
[...queue].sort()per ACT farmer per tick.
Tier 2b — Loose per-tick allocations in systems
Small individually, all in the hot path, trivial to fix (the length = 0 reuse pattern already lives in feature-collision.ts):
- crop-growth.ts:55 —
[...world.query("plot")]spreads a fresh array just to sort it. Reuse a persistent scratch array, sort in place. - event-feed/system.ts —
const fresh = []every tick. Reuse a member buffer. Render queue:DONE — the WebGL2 renderer keeps one persistentthis.queue = []each frame_queueand resets_queueLen = 0per frame, trimming the array only when it shrank (webgl2/renderer.ts:404, 437-438, 572).
Tier 3 — Perceived smoothness & game feel — TODO (queued 2026-06-10, online-research pass)
Distinct from raw throughput: the engine is far under budget (table below), so the wins here are about how smooth and polished it feels, not frame time. Canvas2D has ~10× headroom at ~300 sprites — no WebGL/WebGPU needed (a 2025 Phaser case study even found Canvas2D beating WebGL on mid hardware). Grounded against the renderer code:
- Pixel-snap sprite draws (highest-impact feel fix). raster2d.ts:54,57 draws at raw sub-pixel
s.x/s.ystraight from interpolation — the #1 cause of shimmer on slow-moving 16×16 pixel-art sprites. Snap only at draw time ((s.x - cam.x) | 0), never in stored/interpolated state. (imageSmoothingEnabled=falseis already re-asserted per frame atrenderer.ts:271— keep that; it's the correct defensive pattern, the setting is part of saved canvas state.) - Camera smoothing. main/camera.ts calls
setCenter()to snap directly to the focused farmer each frame (only the pan-offset glide-back is eased). A documentary-style spectator camera should lag its target. Add framerate-independent exponential smoothing / a critically-damped spring,halflife ≈ 0.3–0.5sfor a cozy floaty feel:cam.x += (target.x - cam.x) * (1 - Math.exp(-Math.LN2 / halflife * dt)). Single highest-leverage "polish" change. - Floating number popups ("+12 gold") on sells/harvests — easeOutCubic rise + fade. 100% render-side off the existing event feed (sim already emits the events). Cheap, big readability win for a spectator economy game.
- Juice beats (Vlambeer / "Juice It or Lose It"): trauma-based screen shake (
shake = trauma², decaying, tiny 2–4px, positive beats only — lead crossing, festival win, lobster catch); 2–4 frame hitstop on a major event; score-bump (scale 1.0→1.3→1.0 easeOutBack) when a leaderboard number rises. - Ambient idle life: sine-based crop sway / tree-canopy drift / farmer breathing-bob. Pure render, never feeds the sim — for an idle/spectator game this is the main source of life between economic events.
All Tier 3 items are render-only and seed-deterministic by construction (like the day/night wash and ground-noise texture before them) — but still re-verify with the fast determinism diff. These are game-feel briefs, not perf briefs; route through the normal brief/wiki workflow.
Explicitly NOT worth doing at current scale
- Archetype / SoA / column-oriented ECS storage. The ECS uses flat objects with property-based components (world.ts:12-23). The literature's 5–10× cache-locality wins materialize at thousands–millions of entities in tight numeric loops; Farm Valley has ~4 farmers + tens of entities. A rewrite would be high-effort, near-zero-payoff, and would fight the determinism guarantees. Confirmed by profiling 2026-06-05: the full sim tick over ~300 entities is 0.33ms (~0.7% of the 50ms budget) — there is no cache-locality problem to solve. Revisit only if entity counts grow by orders of magnitude.
- Path caching beyond current behavior. The pathfinder is only called on a new travel intent with no active path (travel/system.ts); it is not a per-tick cost. Profiling shows the whole tick (pathfinder included on travel ticks) is sub-millisecond. Not worth caching.
- Packed/SharedArrayBuffer snapshot (P2 #7). Profiling (when this was a Web Worker) showed
snapshot.build= 0.08ms and ~36KB/tick — invisible in the tick/frame budget. The packed-buffer/SAB rewrite would add real complexity for an unmeasurable gain. Doubly moot since the split (briefs 57–58): the boundary is now JSON over a WebSocket, not structured clone, so SAB doesn't even apply — see the T1.1 note above. Deferred indefinitely; revisit only ifsnapshot.bytesor the server tick climb materially (e.g. a 10× entity-count increase), and then via a binary wire codec, not SAB. - The Citadel minimap's last 422 quads (audit-31, closed 2026-09-15 as not worth doing).
audit-02 already cut the minimap from
36,864
fillRects per frame to 422 by rasterizing terrain once and greedy-scanline-merging it into same-colour rects — a 98.9% reduction, shipped ina2b9931. The remaining step, a single baked blit, needsCitadelMinimapto register its bake as an atlas through a renderer. Closed without doing it, and the reason is the measurement, not the cost. 422 quads/frame is already negligible, and the only honest justification for touching a public constructor would be a frame profile from real hardware — which this sandbox cannot produce: it renders WebGL2 through SwiftShader (CPU raster), the exact artifact that produced an entire phantom "FPS regression" chased down in brief 84 (see the Tier 0 historical entry above). Acting on a SwiftShader number would repeat that mistake. Note for whoever reopens this: the spec claimed threading a renderer in was a cross-module contract change. It is not —rendereris already exported from renderer-state.ts:9, the same module minimap-wiring.ts importsisoandcamerafrom. It is an import line and a constructor argument. So if a real-hardware profile ever does show these quads, the fix is cheap — reopen on a number, not on principle.
Measuring & measured results
Split out on 2026-07-09 → performance-measurements.md
(the Profiler harness, ?profile, and the 2026-06-05 / 2026-06-10 measured baselines).
Suggested order of attack
Profile first— ✅ done (see "Measuring" above).T1.2 interpolation pooling + T2b loose allocations + Tier 2 viewport culling/clipping— ✅ done 2026-06-05 (brief 09 P1; behavior-preserving, multi-seedEXPORT=jsonbyte-identical). Sort-on-dirty was partially deferred (live set is tiny after culling). Details: briefs/engine/done/09-perf-optimization.md.T1.1(b) snapshot interim win— ✅ done 2026-06-05 (events double-alloc removed). The brief's "cache observer/leaderboard per day" half was dropped as incorrect: that state changes intra-day (gold/FSM/AP/intention update on arbitrary ticks), so caching it would freeze the live panels.T1.1(a) SharedArrayBuffer/transfer boundary— dead, twice over (2026-06-10): the split removed the shared address space (no SAB across a socket), and the probe-perf ramp showed its successor (a packed wire codec) chases a cost that isn't the bottleneck — see "Measured results (2026-06-10)" and briefs/engine/done/09-perf-optimization.md #7 close-out. The snapshot-payload work that is worth doing lives in T1.1 items 1–2 and briefs/game/done/72.T1.3 WebSocket transport quick-wins— ✅ mostly done 2026-06-10:permessage-deflate+setNoDelay+ render-delay 1→2 ticks shipped;visibilitychangebriefed (game/done/66); Caddy compression verification dropped by decision.- Tier 3 game-feel (queued 2026-06-10) — pixel-snap + camera smoothing briefed (game/done/67), ambient idle life briefed (game/done/68); number popups + juice deferred until those land. Game-feel briefs, not perf.
The AI-drama gap is the bigger product lever, but it is NOT a perf item. Online research (2026-06-10) confirmed the leader-runaway flatness is a well-studied design failure mode (positive-feedback snowball + personality convergence + no cross-agent reaction), fixed by negative-feedback economics (market saturation), hard personality niche-exclusions, and a social-awareness belief layer + persistent "social-practice" trade landmarks. That work is tracked in open-questions.md and briefs/game/done/59-peer-interaction-and-rubber-banding.md — not here.
Sources
External best-practice references consulted (2026-06-05):
- surma.dev — Is postMessage slow? · Chrome — Transferable objects · MDN — SharedArrayBuffer
- web.dev — Static memory with object pools · MDN — Optimizing canvas · Konva — Canvas perf tips
- ecs-faq (Sander Mertens) · ECS deep dive
WS netcode + render-feel references consulted (2026-06-10, online-research pass — Tiers 1.3 & 3):
- Gambetta — Entity Interpolation · Gaffer on Games — Snapshot Interpolation · Valve — Source Multiplayer Networking (the
cl_interp100ms default) - Marc Brooker — It's always TCP_NODELAY · Ably — Can WebTransport replace WebSockets? · MDN — WebSocket.bufferedAmount
- Gaffer on Games — Fix Your Timestep! · marioslab.io — Jitterbugs (sub-pixel jitter) · theorangeduck.com — Spring-Roll-Call (camera springs)
- Jonasson & Purho — Juice It or Lose It (GDC) · Vlambeer — The Art of Screenshake · web.dev — Avoid layout thrashing
- ECS/BDI at small scale (reconfirmed "NOT worth doing"): Run-time perf: sparse-set vs archetype (Eurographics) (10k-entity crossover) · Concurrency in the ECS pattern (arXiv 2508.15264) · Runaway leader / rubber banding (Oakleaf Games) · Behavioral diversity in MARL (arXiv 2412.16244)