Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
perf(play): photograph the world without a preserved buffer, and batch the scenery
nirholasd0c2d35bc5e8
diff --git a/src/game/economy-ui.js b/src/game/economy-ui.jsindex 3a7d5cfeb..9d1a2c7a9 100644--- a/src/game/economy-ui.js+++ b/src/game/economy-ui.js@@ -57,8 +57,53 @@ export class EconPanel {this.status.setAttribute('data-kind', kind || '');}+ // --- one in-flight intent per panel ---------------------------------------+ //+ // Every trade is priced and applied by the server, which answers each intent+ // with a fresh snapshot. So the honest way to stop a double-click from buying+ // twice is to hold exactly one intent open at a time and wait for that answer:+ // no optimistic balance maths on the client, and no second charge in flight+ // while the first is still unresolved. Subclasses implement `_syncPending()`+ // to re-render their buttons against `this.pending`.++ // Claim the panel's single in-flight slot. Returns false when one is already+ // open (the click is swallowed) or the world is offline (the player is told).+ beginRequest(label, { timeoutMs = 9000, onTimeout } = {}) {+ if (this.pending) return false;+ if (this.net?.status && this.net.status !== 'online') {+ this.setStatus('Reconnecting to the world. Nothing was charged, try again in a moment.', 'err');+ return false;+ }+ this.pending = label;+ this.setStatus(label);+ this._syncPending?.();+ clearTimeout(this._pendingTimer);+ // A dropped reply must not strand the UI mid-trade with a stale balance:+ // clear the guard, say plainly that nothing was charged, and re-read the+ // authoritative profile rather than trusting anything local.+ this._pendingTimer = setTimeout(() => {+ this.pending = null;+ this._syncPending?.();+ this.setStatus('No answer from the world. Nothing was charged. Re-checking your purse…', 'err');+ try { this.net?.requestProfile?.(); } catch { /* offline; the reconnect will resync */ }+ onTimeout?.();+ }, timeoutMs);+ return true;+ }++ // Release the slot once the server has answered (an inv/profile echo, or a+ // notice explaining the refusal). Idempotent.+ endRequest() {+ if (!this.pending) return;+ clearTimeout(this._pendingTimer);+ this._pendingTimer = null;+ this.pending = null;+ this._syncPending?.();+ }+close() {this.overlay.classList.remove('ec-on');+ clearTimeout(this._pendingTimer);for (const u of this._unsubs) { try { u(); } catch { /* ignore */ } }this._unsubs = [];setTimeout(() => this.overlay.remove(), 180);@@ -104,10 +149,14 @@ class StorePanel extends EconPanel {this.card.insertBefore(this.tabs, this.purse);this.track(net.on('store', (msg) => { this.catalog = { sell: msg?.sell || [], buy: msg?.buy || [] }; this._render(); }));- this.track(net.on('profile', (snap) => { this._applyProfile(snap); }));- this.track(net.on('inv', (delta) => { this._applyProfile(delta); }));+ this.track(net.on('profile', (snap) => { this.endRequest(); this._applyProfile(snap); }));+ this.track(net.on('inv', (delta) => { this.endRequest(); this._applyProfile(delta); }));+ // A refused trade (no cash, pack full, not for sale) answers with a notice+ // and no snapshot, so it has to release the in-flight slot too.this.track(net.on('notice', (n) => {- if (n?.kind === 'store' || n?.kind === 'full') this.setStatus(n.text || '', n.kind === 'full' ? 'err' : 'ok');+ if (n?.kind !== 'store' && n?.kind !== 'full') return;+ this.endRequest();+ this.setStatus(n.text || '', n.kind === 'full' ? 'err' : 'ok');}));net.requestStore();@@ -134,6 +183,9 @@ class StorePanel extends EconPanel {if (this.tab === 'buy') this._renderBuy(); else this._renderSell();}+ // Re-render is enough: every button derives its disabled state from `pending`.+ _syncPending() { this._render(); }+_renderBuy() {if (!this.catalog.buy.length) {this.body.appendChild(el('div', { class: 'ec-empty', text: 'Loading the catalog…' }));@@ -149,9 +201,12 @@ class StorePanel extends EconPanel {el('div', { class: 'ec-row-sub', text: `${entry.price} cash` }),]),el('button', {- class: 'ec-row-btn', type: 'button', text: 'Buy', disabled: !afford,+ class: 'ec-row-btn', type: 'button', text: 'Buy', disabled: !afford || !!this.pending,'aria-label': `Buy ${entry.label || entry.item} for ${entry.price} cash`,- onclick: () => { this.setStatus('Buying…'); this.net.storeBuy(entry.item); },+ onclick: () => {+ if (!this.beginRequest('Buying…')) return;+ this.net.storeBuy(entry.item);+ },}),]));}@@ -177,9 +232,12 @@ class StorePanel extends EconPanel {el('div', { class: 'ec-row-sub', text: `${price} cash each · ${price * slot.qty} total` }),]),el('button', {- class: 'ec-row-btn', type: 'button', text: 'Sell all',+ class: 'ec-row-btn', type: 'button', text: 'Sell all', disabled: !!this.pending,'aria-label': `Sell all ${disp?.name || slot.item} for ${price * slot.qty} cash`,- onclick: () => { this.setStatus('Selling…'); this.net.storeSell({ zone: 'inv', i }); },+ onclick: () => {+ if (!this.beginRequest('Selling…')) return;+ this.net.storeSell({ zone: 'inv', i });+ },}),]));}@@ -221,32 +279,41 @@ class BankPanel extends EconPanel {this.depositInput = el('input', { type: 'number', min: '0', step: '1', class: 'ec-bank-input', 'aria-label': 'Amount to deposit', placeholder: '0' });this.withdrawInput = el('input', { type: 'number', min: '0', step: '1', class: 'ec-bank-input', 'aria-label': 'Amount to withdraw', placeholder: '0' });+ this.depositBtn = el('button', { class: 'ec-row-btn', type: 'button', text: 'Deposit', onclick: () => this._deposit() });+ this.withdrawBtn = el('button', { class: 'ec-row-btn ec-secondary', type: 'button', text: 'Withdraw', onclick: () => this._withdraw() });+this.body.appendChild(el('div', { class: 'ec-row-sub', text: 'Deposit — protects cash from a death drop.' }));- this.body.appendChild(el('div', { class: 'ec-bank-amount' }, [- this.depositInput,- el('button', { class: 'ec-row-btn', type: 'button', text: 'Deposit', onclick: () => this._deposit() }),- ]));+ this.body.appendChild(el('div', { class: 'ec-bank-amount' }, [this.depositInput, this.depositBtn]));this.body.appendChild(el('div', { class: 'ec-bank-presets' }, [el('button', { class: 'ec-bank-preset', type: 'button', text: 'Max', onclick: () => { this.depositInput.value = String(this.gold); } }),]));this.body.appendChild(el('div', { class: 'ec-row-sub', text: 'Withdraw — moves banked cash back to your purse.' }));- this.body.appendChild(el('div', { class: 'ec-bank-amount' }, [- this.withdrawInput,- el('button', { class: 'ec-row-btn ec-secondary', type: 'button', text: 'Withdraw', onclick: () => this._withdraw() }),- ]));+ this.body.appendChild(el('div', { class: 'ec-bank-amount' }, [this.withdrawInput, this.withdrawBtn]));this.body.appendChild(el('div', { class: 'ec-bank-presets' }, [el('button', { class: 'ec-bank-preset', type: 'button', text: 'Max', onclick: () => { this.withdrawInput.value = String(this.bankBal); } }),]));- this.track(net.on('profile', (snap) => this._applyProfile(snap)));+ this.track(net.on('profile', (snap) => { this.endRequest(); this._applyProfile(snap); }));+ // A transfer the server clamped to zero (nothing on hand, nothing banked)+ // answers with a notice and no snapshot, so release the slot on it too.this.track(net.on('notice', (n) => {- if (n?.kind === 'bank') this.setStatus(n.text || '', 'ok');+ if (n?.kind !== 'bank') return;+ this.endRequest();+ this.setStatus(n.text || '', 'ok');}));net.requestProfile();}+ // Both transfer buttons ride the panel's single in-flight slot, so a+ // double-tapped Deposit can never send the same amount twice.+ _syncPending() {+ const busy = !!this.pending;+ this.depositBtn.disabled = busy;+ this.withdrawBtn.disabled = busy;+ }+_applyProfile(snap) {if (!snap) return;if (Number.isFinite(snap.gold)) this.gold = snap.gold;diff --git a/src/game/npc/npc.js b/src/game/npc/npc.jsindex a8be8ad57..947fc0681 100644--- a/src/game/npc/npc.js+++ b/src/game/npc/npc.js@@ -14,7 +14,7 @@import { Group, Vector3 } from 'three';import { AnimationManager } from '../../animation-manager.js';-import { resolveAvatarUrl, buildAvatar, CLIP_IDLE, CLIP_WALK } from '../avatar-rig.js';+import { resolveAvatarUrl, buildAvatar, releaseAvatar, CLIP_IDLE, CLIP_WALK } from '../avatar-rig.js';import { playEmoteClip } from '../avatar-rig.js';const BUBBLE_MS = 4600;@@ -64,7 +64,13 @@ export class Npc {// emote library. emote() below lazy-loads any clip on demand.resolveAvatarUrl(def.avatar).then((u) => buildAvatar(this.rig, u, this.anim, { clips: 'locomotion' }))- .then(({ height }) => { if (!this._disposed) this.height = height; })+ .then(({ height }) => {+ // Disposed while the GLB was still downloading: buildAvatar has now+ // added a template clone to a detached rig, so release it here or its+ // shared-template ref never drops and the model stays resident.+ if (this._disposed) { releaseAvatar(this.rig); return; }+ this.height = height;+ }).catch(() => {});}@@ -129,6 +135,10 @@ export class Npc {dispose() {this._disposed = true;+ // Free the shared-template clone's GPU buffers, not just the scene-graph+ // reference. 21 NPCs per world across five world hops is 105 orphaned+ // skinned avatars otherwise — the mobile-OOM profile.+ releaseAvatar(this.rig);this.scene.remove(this.rig);this.label.remove();this.bubble?.remove();diff --git a/src/game/photo-mode.css b/src/game/photo-mode.cssnew file mode 100644index 000000000..9dc4197ad--- /dev/null+++ b/src/game/photo-mode.css@@ -0,0 +1,121 @@+/* Photo mode (/play) — shutter flash + the preview card.+ Loaded with src/game/photo-mode.js, which is imported lazily on the first+ press, so none of this reaches a player who never takes a photo.+ Tokens come from coincommunities.css; the fallbacks keep the sheet readable+ if it ever mounts on a surface that has not loaded them. */++/* ── shutter ──────────────────────────────────────────────────────────────+ A single white frame over the whole viewport. Never mounted at all under+ prefers-reduced-motion (photo-mode.js skips it), so there is no animation+ to disable here. */+.cc-photo-flash {+ position: fixed; inset: 0; z-index: 200; pointer-events: none;+ background: #fff; opacity: 0;+ animation: cc-photo-shutter 260ms ease-out forwards;+}+@keyframes cc-photo-shutter {+ 0% { opacity: 0; }+ 12% { opacity: 0.82; }+ 100% { opacity: 0; }+}++/* ── preview sheet ────────────────────────────────────────────────────────+ A light scrim, not a blackout: the world keeps rendering behind the card and+ the player can still see where they were standing. */+#cc-photo {+ position: fixed; inset: 0; z-index: 130;+ display: grid; place-items: center; padding: 20px;+ background: rgba(4, 4, 5, 0.42);+ -webkit-backdrop-filter: blur(2px); backdrop-filter: blur(2px);+ opacity: 0; transition: opacity 0.2s ease;+}+#cc-photo.cc-on { opacity: 1; }++.cc-photo-card {+ position: relative; width: min(460px, 94vw); max-height: 88vh; overflow: auto;+ background: var(--cc-panel-solid, #0c0c0c);+ border: 1px solid var(--cc-edge, rgba(255, 255, 255, 0.12));+ border-radius: var(--cc-radius, 4px);+ box-shadow: var(--cc-shadow, 0 16px 50px rgba(0, 0, 0, 0.7));+ padding: 20px; color: var(--cc-text, #f5f5f6);+ transform: translateY(24px); transition: transform 0.24s cubic-bezier(0.2, 0.8, 0.3, 1);+}+#cc-photo.cc-on .cc-photo-card { transform: none; }++.cc-photo-close {+ position: absolute; top: 12px; right: 12px; width: 30px; height: 30px;+ display: grid; place-items: center; border-radius: var(--cc-radius-sm, 2px);+ border: 1px solid var(--cc-edge, rgba(255, 255, 255, 0.12));+ background: rgba(255, 255, 255, 0.04);+ color: var(--cc-dim, #8c8c92); cursor: pointer; font-size: 14px; line-height: 1;+ transition: color 0.12s ease, background 0.12s ease, border-color 0.12s ease;+}+.cc-photo-close:hover { color: var(--cc-text, #f5f5f6); border-color: var(--cc-edge-hi, rgba(255, 255, 255, 0.55)); background: rgba(255, 255, 255, 0.1); }+.cc-photo-close:active { background: rgba(255, 255, 255, 0.16); }+.cc-photo-close:focus-visible { outline: none; border-color: var(--cc-edge-hi, rgba(255, 255, 255, 0.55)); box-shadow: 0 0 0 1px var(--cc-edge-hi, rgba(255, 255, 255, 0.55)); }++.cc-photo-kicker {+ display: block; font-size: 11px; letter-spacing: 0.18em; text-transform: uppercase;+ color: var(--cc-dim, #8c8c92);+}+.cc-photo-h { margin: 3px 0 0; font-size: 17px; font-weight: 700; letter-spacing: 0.01em; }+.cc-photo-sub {+ margin: 3px 0 0; font-size: 12.5px; color: var(--cc-dim, #8c8c92);+ font-variant-numeric: tabular-nums;+}++.cc-photo-shot {+ display: block; width: 100%; height: auto; max-height: 46vh; object-fit: contain;+ margin: 14px 0 0; border-radius: var(--cc-radius-sm, 2px);+ border: 1px solid var(--cc-edge, rgba(255, 255, 255, 0.12));+ background: #08080a;+}++.cc-photo-actions { display: flex; gap: 8px; margin-top: 14px; flex-wrap: wrap; }+.cc-photo-btn {+ flex: 1 1 140px; display: inline-flex; align-items: center; justify-content: center; gap: 8px;+ padding: 11px 14px; border-radius: var(--cc-radius, 4px); cursor: pointer;+ border: 1px solid var(--cc-edge, rgba(255, 255, 255, 0.12));+ background: rgba(255, 255, 255, 0.04); color: var(--cc-text, #f5f5f6);+ font: inherit; font-size: 13px; font-weight: 600; text-decoration: none; white-space: nowrap;+ transition: border-color 0.12s ease, background 0.12s ease, transform 0.12s ease, box-shadow 0.12s ease;+}+.cc-photo-btn:hover { border-color: var(--cc-edge-hi, rgba(255, 255, 255, 0.55)); background: rgba(255, 255, 255, 0.09); }+.cc-photo-btn:active { transform: translateY(1px); }+.cc-photo-btn:focus-visible { outline: none; border-color: var(--cc-edge-hi, rgba(255, 255, 255, 0.55)); box-shadow: 0 0 0 1px var(--cc-edge-hi, rgba(255, 255, 255, 0.55)); }+.cc-photo-primary {+ background: var(--cc-accent, #fff); color: var(--cc-ink, #060607); border-color: var(--cc-accent, #fff);+}+.cc-photo-primary:hover { background: #fff; box-shadow: var(--cc-glow, 0 0 14px rgba(255, 255, 255, 0.35)); }+/* Clipboard-less browsers keep the button (so the option is never a mystery)+ but read as unavailable; the click explains itself in the status line. */+.cc-photo-btn[aria-disabled="true"] { color: var(--cc-faint, #5a5a60); cursor: default; }+.cc-photo-btn[aria-disabled="true"]:hover { border-color: var(--cc-edge, rgba(255, 255, 255, 0.12)); background: rgba(255, 255, 255, 0.04); }+.cc-photo-btn[aria-disabled="true"]:active { transform: none; }++.cc-photo-status {+ margin: 10px 0 0; min-height: 16px; font-size: 12px; line-height: 1.45;+ color: var(--cc-dim, #8c8c92);+}+.cc-photo-status[data-kind="ok"] { color: #b8ffce; }+.cc-photo-status[data-kind="warn"] { color: #ffd28a; }++.cc-photo-hint {+ margin: 10px 0 0; font-size: 11.5px; color: var(--cc-faint, #5a5a60);+}+.cc-photo-hint kbd {+ font: inherit; font-size: 10.5px; padding: 1px 5px; border-radius: 3px;+ border: 1px solid var(--cc-edge, rgba(255, 255, 255, 0.12)); background: rgba(255, 255, 255, 0.05);+}++/* Phone: a bottom sheet, so the thumb reaches the actions and more world shows. */+@media (max-width: 560px) {+ #cc-photo { place-items: end center; padding: 12px; }+ .cc-photo-card { width: 100%; padding: 16px; max-height: 82vh; }+ .cc-photo-shot { max-height: 38vh; }+}++@media (prefers-reduced-motion: reduce) {+ #cc-photo, .cc-photo-card, .cc-photo-btn { transition: none; }+ .cc-photo-card { transform: none; }+}diff --git a/src/game/scene-capture.js b/src/game/scene-capture.jsnew file mode 100644index 000000000..141dbc194--- /dev/null+++ b/src/game/scene-capture.js@@ -0,0 +1,83 @@+// One way to photograph a live three.js scene: render it into an offscreen+// target and read the pixels back.+//+// The obvious approach (`renderer.domElement.toDataURL()`) returns a BLACK+// frame on every browser unless the context was created with+// `preserveDrawingBuffer: true`, because the drawing buffer is cleared the+// moment the compositor takes the frame. Flipping that flag on permanently+// costs a full extra buffer copy on EVERY frame for the sake of the rare+// screenshot, so /play does not: it renders one extra frame into a+// WebGLRenderTarget on demand instead. Cost when nobody is taking a photo:+// exactly zero.+//+// Side benefits of reading a render target rather than the canvas: the capture+// is independent of what the compositor happens to be showing this instant, DOM+// chrome (HUD, chat, name tags) is never in the shot because it was never in+// the GL frame, and the caller picks the resolution.+//+// Callers: src/game/photo-mode.js (the share card) and+// src/game/coincommunities.js (`_captureBuildShot`, the build thumbnail).++import { WebGLRenderTarget, Vector2, SRGBColorSpace } from 'three';+import { log } from '../shared/log.js';++const _size = new Vector2();++/**+ * Render one frame of `scene`/`camera` offscreen and return it as a 2D canvas.+ *+ * @param {import('three').WebGLRenderer} renderer+ * @param {import('three').Scene} scene+ * @param {import('three').Camera} camera+ * @param {{ maxWidth?: number, samples?: number }} [opts]+ * maxWidth downscales the target so a 5K display does not produce a 40 MB+ * PNG; the aspect ratio always matches the live view.+ * @returns {{ canvas: HTMLCanvasElement, width: number, height: number } | null}+ * null when the scene cannot be photographed (no renderer, zero-size canvas,+ * lost context). Callers treat null as "tell the player to try again".+ */+export function captureSceneCanvas(renderer, scene, camera, { maxWidth = 2560, samples = 4 } = {}) {+ if (!renderer || !scene || !camera) return null;++ // The drawing buffer, not the CSS box: on a retina display those differ by+ // the pixel ratio and the buffer is the true render resolution.+ renderer.getDrawingBufferSize(_size);+ if (!(_size.x >= 1) || !(_size.y >= 1)) return null;++ const scale = Math.min(1, maxWidth / _size.x);+ const w = Math.max(1, Math.round(_size.x * scale));+ const h = Math.max(1, Math.round(_size.y * scale));++ let target = null;+ const previous = renderer.getRenderTarget();+ try {+ target = new WebGLRenderTarget(w, h, { samples });+ target.texture.colorSpace = SRGBColorSpace;+ renderer.setRenderTarget(target);+ renderer.render(scene, camera);++ const pixels = new Uint8Array(w * h * 4);+ renderer.readRenderTargetPixels(target, 0, 0, w, h, pixels);++ const canvas = document.createElement('canvas');+ canvas.width = w;+ canvas.height = h;+ const ctx = canvas.getContext('2d');+ const image = ctx.createImageData(w, h);+ // WebGL's origin is bottom-left and a canvas's is top-left: copy the rows+ // back to front so the photo is not upside down.+ const stride = w * 4;+ for (let y = 0; y < h; y++) {+ const src = (h - 1 - y) * stride;+ image.data.set(pixels.subarray(src, src + stride), y * stride);+ }+ ctx.putImageData(image, 0, 0);+ return { canvas, width: w, height: h };+ } catch (err) {+ log.warn('[scene-capture] capture failed:', err?.message);+ return null;+ } finally {+ renderer.setRenderTarget(previous);+ target?.dispose();+ }+}diff --git a/src/game/static-batch.js b/src/game/static-batch.jsnew file mode 100644index 000000000..1ced65403--- /dev/null+++ b/src/game/static-batch.js@@ -0,0 +1,124 @@+// Static geometry batcher for the /play world dressing.+//+// The biome builders in world-env.js already share geometry and materials+// across everything they scatter: 46 conifers are 46 Groups drawn from the same+// two buffers, a frontier town's 13 storefronts are ~200 boxes cut from one+// BoxGeometry. Sharing the buffers saves memory but not draw calls, and the+// renderer submitted every one of those meshes individually, twice over once+// the sun's shadow pass ran. In the flagship $THREE town that was the single+// largest per-frame cost in the scene.+//+// Nothing in that dressing ever moves. So instead of adding the built Groups to+// the scene, hand them here: the batcher records each mesh's world matrix,+// buckets by (geometry, material, shadow flags), and emits one InstancedMesh+// per bucket. Same pixels, a fraction of the draw calls.+//+// const batch = createStaticBatcher();+// for (const tree of trees) batch.add(tree); // already positioned/scaled+// batch.flush(root); // one InstancedMesh per bucket+//+// Anything that has to animate individually (the tumbleweeds, the market ring)+// must NOT go through here — add it to the scene the ordinary way.++import { InstancedMesh, Matrix4, StaticDrawUsage } from 'three';++// A single-instance bucket is a plain mesh with extra bookkeeping, so those are+// re-emitted as ordinary meshes. Two is already a win: one draw call instead of+// two, for one Float32Array of 32 numbers.+const MIN_INSTANCES = 2;++export function createStaticBatcher() {+ // key → { geometry, material, castShadow, receiveShadow, renderOrder, matrices[] }+ const buckets = new Map();+ // Meshes that can't be instanced (multi-material) keep their world transform+ // and are re-parented as-is.+ const passthrough = [];+ let sourceMeshes = 0;++ /**+ * Record every mesh under `object` for batching. The object must already+ * carry its final transform; it is never added to the scene itself.+ */+ function add(object) {+ if (!object) return;+ object.updateMatrixWorld(true);+ object.traverse((n) => {+ if (!n.isMesh || n.isInstancedMesh || n.isSkinnedMesh) return;+ sourceMeshes++;+ if (Array.isArray(n.material) || !n.geometry || !n.material) {+ n.matrix.copy(n.matrixWorld);+ n.matrix.decompose(n.position, n.quaternion, n.scale);+ passthrough.push(n);+ return;+ }+ const key = `${n.geometry.uuid}|${n.material.uuid}|${n.castShadow ? 1 : 0}${n.receiveShadow ? 1 : 0}|${n.renderOrder}`;+ let bucket = buckets.get(key);+ if (!bucket) {+ bucket = {+ geometry: n.geometry,+ material: n.material,+ castShadow: n.castShadow,+ receiveShadow: n.receiveShadow,+ renderOrder: n.renderOrder,+ matrices: [],+ };+ buckets.set(key, bucket);+ }+ bucket.matrices.push(n.matrixWorld.clone());+ });+ }++ /**+ * Emit the batched meshes into `root` and reset the batcher. Returns the+ * before/after mesh counts so callers (and the perf audit) can see the win.+ */+ function flush(root) {+ let emitted = 0;+ for (const b of buckets.values()) {+ if (b.matrices.length < MIN_INSTANCES) {+ // Rebuild the lone mesh rather than instancing a crowd of one.+ const m = new InstancedMesh(b.geometry, b.material, 1);+ m.setMatrixAt(0, b.matrices[0]);+ m.instanceMatrix.setUsage(StaticDrawUsage);+ m.castShadow = b.castShadow;+ m.receiveShadow = b.receiveShadow;+ m.renderOrder = b.renderOrder;+ m.computeBoundingSphere();+ root.add(m);+ emitted++;+ continue;+ }+ const mesh = new InstancedMesh(b.geometry, b.material, b.matrices.length);+ for (let i = 0; i < b.matrices.length; i++) mesh.setMatrixAt(i, b.matrices[i]);+ // The dressing never moves, so the driver can keep the buffer on the GPU.+ mesh.instanceMatrix.setUsage(StaticDrawUsage);+ mesh.instanceMatrix.needsUpdate = true;+ mesh.castShadow = b.castShadow;+ mesh.receiveShadow = b.receiveShadow;+ mesh.renderOrder = b.renderOrder;+ // Without this the batch inherits the source geometry's bounds (one+ // tree at the origin) and frustum culling pops the whole treeline out+ // the moment the camera looks away from world centre.+ mesh.computeBoundingSphere();+ root.add(mesh);+ emitted++;+ }+ for (const m of passthrough) { root.add(m); emitted++; }+ const stats = { meshes: sourceMeshes, batches: emitted, saved: Math.max(0, sourceMeshes - emitted) };+ buckets.clear();+ passthrough.length = 0;+ sourceMeshes = 0;+ return stats;+ }++ return { add, flush };+}++/**+ * Free an InstancedMesh's per-instance buffers. Geometry and materials are+ * shared with the builders that own them, so they are left alone; the caller's+ * own dispose sweep handles those.+ */+export function disposeInstanced(root) {+ root.traverse((n) => { if (n.isInstancedMesh) n.dispose(); });+}diff --git a/src/game/vehicles.js b/src/game/vehicles.jsindex 2373916cf..2e9043b7c 100644--- a/src/game/vehicles.js+++ b/src/game/vehicles.js@@ -215,7 +215,6 @@ export class VehicleManager {const push = (1 - d / reach) * Math.min(Math.abs(s.speed), 14) * dt;p.x += (dx / d) * push;p.z += (dz / d) * push;- this._damageHook?.({ id: entry.id, speed: s.speed, victim: 'self' });}}@@ -373,7 +372,12 @@ export class VehicleManager {this._pendingEnter = id;this.net?.sendVEnter(id);clearTimeout(this._pendingTimer);- this._pendingTimer = setTimeout(() => this._clearPending(), ENTER_TIMEOUT_MS);+ // If the grant never arrives, tell the player instead of failing silently;+ // clearing the pending flag lets _updatePrompt re-show the F prompt next tick.+ this._pendingTimer = setTimeout(() => {+ this._clearPending();+ this.ui?.toast?.('Could not reach that vehicle. Try again.', 'warn');+ }, ENTER_TIMEOUT_MS);this.prompt.classList.remove('veh-show');}@@ -382,16 +386,30 @@ export class VehicleManager {clearTimeout(this._pendingTimer);}+ // The server granted us a seat we cannot actually take (physics missing, the+ // vehicle vanished locally, a newer state seated someone else). Hand the seat+ // straight back so the car isn't left occupied for the whole room; the server+ // no-ops the exit if we never actually held the seat.+ _releaseSeat(id, s) {+ this.net?.sendVExit(s+ ? { id, x: s.x, y: s.y, z: s.z, qx: s.qx, qy: s.qy, qz: s.qz, qw: s.qw, speed: 0 }+ : { id, speed: 0 });+ }+_beginDriving(id) {this._clearPending();const entry = this.vehicles.get(id);- if (!entry) return;+ if (!entry) { this._releaseSeat(id, null); return; }if (!this.phys) {+ this._releaseSeat(id, entry.state);this.ui?.toast?.('Vehicles need real-time physics, which failed to load this session.', 'warn');return;}// Another change may have arrived; re-confirm the server seated us.- if (entry.state.driver && entry.state.driver !== this.net?.sessionId) return;+ if (entry.state.driver && entry.state.driver !== this.net?.sessionId) {+ this._releaseSeat(id, entry.state);+ return;+ }const s = entry.state;const yaw = yawFromQuat(s.qx, s.qy, s.qz, s.qw);@@ -457,7 +475,7 @@ export class VehicleManager {// flag CoinCommunities sets on a fresh coin spawn) so the next _stepLocal// re-seeds it there instead of resolving a stale move from the old spot.this.host._physicsActivePrev = false;- if (serverForced && t === null) this.ui?.toast?.('You were removed from the vehicle.', 'warn');+ if (serverForced) this.ui?.toast?.('You were removed from the vehicle.', 'warn');}// ---------------------------------------------------------------- input glue@@ -605,7 +623,8 @@ export class VehicleManager {}dispose() {- if (this._drivingId) this._endDriving(this.vehicle ? this.vehicle.transform() : null, true);+ // Not serverForced: this is our own teardown, not an eviction — no toast.+ if (this._drivingId) this._endDriving(this.vehicle ? this.vehicle.transform() : null, false);clearTimeout(this._pendingTimer);for (const [, entry] of this.vehicles) {entry.collider?.remove();@@ -615,6 +634,7 @@ export class VehicleManager {this.vehicles.clear();this.prompt?.remove();this._hud?.remove();+ document.getElementById('veh-styles')?.remove();// `phys` is CoinCommunities' own shared world — owned and disposed by the// host, not us. Just drop our reference.this.phys = null;diff --git a/src/game/world-env.js b/src/game/world-env.jsindex d49743e9d..01ae5f2f2 100644--- a/src/game/world-env.js+++ b/src/game/world-env.js@@ -23,6 +23,8 @@ import {BoxGeometry, TorusGeometry,GridHelper, CanvasTexture,} from 'three';+import { createStaticBatcher, disposeInstanced } from './static-batch.js';+import { log } from '../shared/log.js';// FNV-1a hash → a stable 32-bit seed from a coin mint (or any string). Identical// input always yields the identical world; no Math.random in the layout path.@@ -437,11 +439,15 @@ function makeProp(kind, geo, mats, rand) {return g;}-// Build the whole frontier town into `root`: a ring of storefronts facing the-// square, a water tower, scattered props, and a couple of tumbleweeds that the-// caller animates. Everything sits OUTSIDE playRadius so it frames the plaza-// without ever blocking a player.-function buildFrontierTown(root, rand, playRadius) {+// Build the whole frontier town: a ring of storefronts facing the square, a+// water tower, scattered props, and a couple of tumbleweeds that the caller+// animates. Everything sits OUTSIDE playRadius so it frames the plaza without+// ever blocking a player.+//+// The static dressing goes into `batch` (one InstancedMesh per shared+// geometry+material instead of ~330 individual boxes and posts); only the+// tumbleweeds, which move every frame, are added to `root` directly.+function buildFrontierTown(root, rand, playRadius, batch) {const between = (a, b) => a + (b - a) * rand();const mats = {wood: [@@ -492,14 +498,14 @@ function buildFrontierTown(root, rand, playRadius) {const shop = makeStorefront(geo, mats, rand, names[i % names.length]);shop.position.set(Math.cos(a) * R, 0, Math.sin(a) * R);shop.rotation.y = Math.atan2(-Math.cos(a), -Math.sin(a)); // facade faces the square- root.add(shop);+ batch.add(shop);}// Water tower off one corner of the square.const ta = 0.9;const tower = makeWaterTower(geo, mats);tower.position.set(Math.cos(ta) * (playRadius + 14), 0, Math.sin(ta) * (playRadius + 14));- root.add(tower);+ batch.add(tower);// Clutter scattered through the band between the boundary and the storefronts.const KINDS = ['barrel', 'crate', 'wheel', 'hitch', 'trough', 'barrel', 'crate'];@@ -509,7 +515,7 @@ function buildFrontierTown(root, rand, playRadius) {const prop = makeProp(KINDS[Math.floor(rand() * KINDS.length)], geo, mats, rand);prop.position.set(Math.cos(a) * R, 0, Math.sin(a) * R);prop.rotation.y = rand() * Math.PI * 2;- root.add(prop);+ batch.add(prop);}// A couple of tumbleweeds drifting the mesa band beyond the town — pure life.@@ -614,6 +620,13 @@ export function createWorldEnvironment(scene, renderer, playRadius = 58, opts =// --- Distant hills -----------------------------------------------------// A ring of broad, low mounds beyond the flora gives the horizon depth,// hazing into the biome's sky seam.+ //+ // Hills, flora and town dressing are all static, all built from a handful of+ // shared geometry+material pairs, and all go through the batcher below: the+ // scene ends up with one InstancedMesh per pair instead of several hundred+ // individually-submitted meshes (each of which also cost a second submission+ // in the sun's shadow pass).+ const batch = createStaticBatcher();const hillGeo = new IcosahedronGeometry(1, 1);const hillMat = new MeshStandardMaterial({ color: cHill, roughness: 1, metalness: 0, flatShading: true });for (let i = 0; i < 14; i++) {@@ -623,7 +636,7 @@ export function createWorldEnvironment(scene, renderer, playRadius = 58, opts =const w = between(45, 80), tall = between(14, 30);h.scale.set(w, tall, w);h.position.set(Math.cos(ang) * dist, tall * 0.18 - tall, Math.sin(ang) * dist);- root.add(h);+ batch.add(h);}// --- Flora -------------------------------------------------------------@@ -655,7 +668,6 @@ export function createWorldEnvironment(scene, renderer, playRadius = 58, opts =sagebrush: makeSagebrush,}[biome.flora] || makeConifer;- const crystals = [];for (let i = 0; i < biome.density; i++) {const ang = rand() * Math.PI * 2;const dist = between(playRadius + 6, playRadius + 60);@@ -664,11 +676,12 @@ export function createWorldEnvironment(scene, renderer, playRadius = 58, opts =plant.position.set(Math.cos(ang) * dist, 0, Math.sin(ang) * dist);plant.scale.multiplyScalar(s);plant.rotation.y = rand() * Math.PI * 2;- root.add(plant);- if (neon) crystals.push(plant);+ batch.add(plant);}// Alien crystals breathe with a faint emissive shimmer — biome-specific life.- if (crystals.length) {+ // The pulse is written on the shared leaf materials, so every batched shard+ // picks it up without the animator touching a single mesh.+ if (neon && biome.density > 0) {animators.push((t) => {const k = 0.45 + Math.sin(t * 0.8) * 0.25;mats.leafA.emissiveIntensity = 0.4 + k * 0.4;@@ -681,7 +694,7 @@ export function createWorldEnvironment(scene, renderer, playRadius = 58, opts =// frontier town's tumbleweeds roll on the shared animator clock, looping a// long chord through the mesa band and spinning as they go.if (biome.town === 'frontier') {- const tumbles = buildFrontierTown(root, rand, playRadius);+ const tumbles = buildFrontierTown(root, rand, playRadius, batch);const SPAN = 90; // length of the roll before it loops backanimators.push((t, dt) => {for (const tw of tumbles) {@@ -693,6 +706,14 @@ export function createWorldEnvironment(scene, renderer, playRadius = 58, opts =});}+ // Everything static has been collected by now: emit the instanced batches.+ // The counts are worth a line in the console because they are the single+ // number that predicts frame cost in a crowded plaza.+ const batchStats = batch.flush(root);+ log.info(+ `[world-env] ${biome.id} dressing: ${batchStats.meshes} meshes batched into ${batchStats.batches} draws`,+ );+// --- Live-market reactivity --------------------------------------------// The boundary ring is the world's heartbeat: a slow breathing pulse is the// baseline, but a trade can kick it to a colour (green on a buy, red on a@@ -757,6 +778,16 @@ export function createWorldEnvironment(scene, renderer, playRadius = 58, opts =scene.background?.dispose?.();scene.background = null;scene.fog = null;+ // Instanced batches hold a per-instance attribute of their own on top+ // of the shared geometry, so they need dispose() as well as the+ // geometry/material sweep below.+ disposeInstanced(root);+ // The sun is a DirectionalLight, not a Mesh, so the traverse below skips+ // it — and its 2048x2048 shadow depth target is one of the largest GPU+ // allocations in the world. Free it explicitly, or every coin-world switch+ // strands another full-size shadow map in VRAM.+ sunLight.shadow?.map?.dispose?.();+ sunLight.dispose?.();root.traverse((n) => {if (n.isMesh || n.isLine) {n.geometry?.dispose?.();