A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(residency): prepared means every obligation is paid, not just the assets
esengine17d93f155350
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 35759bedc..794b42b6f 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -7338,6 +7338,7 @@ name: stringonPhase: ((phase: string, ms: number) => void) | undefinedpath: string | undefinedprepare: (() => Promise<void>) | undefined+readyRenderPrograms: (() => Promise<RenderReadiness>) | undefinedsetup: ((ctx: SceneContext) => void | Promise<void>) | undefinedsystems: { schedule: Schedule; system: SystemDef; }[] | undefined```@@ -7430,6 +7431,7 @@ load: (name: string, onProgress?: SceneLoadProgressCallback) => Promise<SceneConloadAdditive: (name: string, onProgress?: SceneLoadProgressCallback) => Promise<SceneContext>pause: (name: string) => voidprepare: (name: string) => Promise<void>+readyRenderPrograms: (name: string) => Promise<RenderReadiness>register: (config: SceneConfig) => voidreload: (options?: TransitionOptions) => Promise<void>reset: () => void@@ -10236,6 +10238,7 @@ prefetchMisses: numberprefetchRequests: numberprepareCount: numberpreparedCells: string[]+preparedWithRenderClaim: string[]residentCells: string[]sourceCount: numberstreamed: boolean@@ -10249,6 +10252,7 @@ discardPrepared: (name: string) => numberisLoaded: (name: string) => booleanloadAdditive: (name: string) => Promise<unknown>prepare: (name: string) => Promise<void>+readyRenderPrograms: ((name: string) => Promise<RenderReadiness>) | undefinedregister: (config: SceneConfig) => voidunload: (name: string, options?: { keepPersistent?: boolean; }) => Promise<void>```@@ -10260,6 +10264,7 @@ delivery: () => Record<string, CellDelivery>loadManifest: (manifest: WorldManifest, sceneConfig?: (cell: WorldCell) => SceneConfig) => voidmanifest: WorldManifest | nullrecordPhase: (name: string, phase: string, ms: number) => void+renderReadinessOf: (name: string) => RenderReadinessStamp | nullresidencyOf: (name: string) => CellResidencystatus: () => WorldStreamerStatusupdate: (sources: readonly ResidencySource[]) => voiddiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex f7dd585cd..be37b7284 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -7531,6 +7531,7 @@ name: stringonPhase: ((phase: string, ms: number) => void) | undefinedpath: string | undefinedprepare: (() => Promise<void>) | undefined+readyRenderPrograms: (() => Promise<RenderReadiness>) | undefinedsetup: ((ctx: SceneContext) => void | Promise<void>) | undefinedsystems: { schedule: Schedule; system: SystemDef; }[] | undefined```@@ -7623,6 +7624,7 @@ load: (name: string, onProgress?: SceneLoadProgressCallback) => Promise<SceneConloadAdditive: (name: string, onProgress?: SceneLoadProgressCallback) => Promise<SceneContext>pause: (name: string) => voidprepare: (name: string) => Promise<void>+readyRenderPrograms: (name: string) => Promise<RenderReadiness>register: (config: SceneConfig) => voidreload: (options?: TransitionOptions) => Promise<void>reset: () => void@@ -10429,6 +10431,7 @@ prefetchMisses: numberprefetchRequests: numberprepareCount: numberpreparedCells: string[]+preparedWithRenderClaim: string[]residentCells: string[]sourceCount: numberstreamed: boolean@@ -10442,6 +10445,7 @@ discardPrepared: (name: string) => numberisLoaded: (name: string) => booleanloadAdditive: (name: string) => Promise<unknown>prepare: (name: string) => Promise<void>+readyRenderPrograms: ((name: string) => Promise<RenderReadiness>) | undefinedregister: (config: SceneConfig) => voidunload: (name: string, options?: { keepPersistent?: boolean; }) => Promise<void>```@@ -10453,6 +10457,7 @@ delivery: () => Record<string, CellDelivery>loadManifest: (manifest: WorldManifest, sceneConfig?: (cell: WorldCell) => SceneConfig) => voidmanifest: WorldManifest | nullrecordPhase: (name: string, phase: string, ms: number) => void+renderReadinessOf: (name: string) => RenderReadinessStamp | nullresidencyOf: (name: string) => CellResidencystatus: () => WorldStreamerStatusupdate: (sources: readonly ResidencySource[]) => voiddiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 72dd5a0a9..ba6480d10 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -7333,6 +7333,7 @@ name: stringonPhase: ((phase: string, ms: number) => void) | undefinedpath: string | undefinedprepare: (() => Promise<void>) | undefined+readyRenderPrograms: (() => Promise<RenderReadiness>) | undefinedsetup: ((ctx: SceneContext) => void | Promise<void>) | undefinedsystems: { schedule: Schedule; system: SystemDef; }[] | undefined```@@ -7425,6 +7426,7 @@ load: (name: string, onProgress?: SceneLoadProgressCallback) => Promise<SceneConloadAdditive: (name: string, onProgress?: SceneLoadProgressCallback) => Promise<SceneContext>pause: (name: string) => voidprepare: (name: string) => Promise<void>+readyRenderPrograms: (name: string) => Promise<RenderReadiness>register: (config: SceneConfig) => voidreload: (options?: TransitionOptions) => Promise<void>reset: () => void@@ -10231,6 +10233,7 @@ prefetchMisses: numberprefetchRequests: numberprepareCount: numberpreparedCells: string[]+preparedWithRenderClaim: string[]residentCells: string[]sourceCount: numberstreamed: boolean@@ -10244,6 +10247,7 @@ discardPrepared: (name: string) => numberisLoaded: (name: string) => booleanloadAdditive: (name: string) => Promise<unknown>prepare: (name: string) => Promise<void>+readyRenderPrograms: ((name: string) => Promise<RenderReadiness>) | undefinedregister: (config: SceneConfig) => voidunload: (name: string, options?: { keepPersistent?: boolean; }) => Promise<void>```@@ -10255,6 +10259,7 @@ delivery: () => Record<string, CellDelivery>loadManifest: (manifest: WorldManifest, sceneConfig?: (cell: WorldCell) => SceneConfig) => voidmanifest: WorldManifest | nullrecordPhase: (name: string, phase: string, ms: number) => void+renderReadinessOf: (name: string) => RenderReadinessStamp | nullresidencyOf: (name: string) => CellResidencystatus: () => WorldStreamerStatusupdate: (sources: readonly ResidencySource[]) => voiddiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 3e4948b94..cbbd42046 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -7579,6 +7579,7 @@ name: stringonPhase: ((phase: string, ms: number) => void) | undefinedpath: string | undefinedprepare: (() => Promise<void>) | undefined+readyRenderPrograms: (() => Promise<RenderReadiness>) | undefinedsetup: ((ctx: SceneContext) => void | Promise<void>) | undefinedsystems: { schedule: Schedule; system: SystemDef; }[] | undefined```@@ -7671,6 +7672,7 @@ load: (name: string, onProgress?: SceneLoadProgressCallback) => Promise<SceneConloadAdditive: (name: string, onProgress?: SceneLoadProgressCallback) => Promise<SceneContext>pause: (name: string) => voidprepare: (name: string) => Promise<void>+readyRenderPrograms: (name: string) => Promise<RenderReadiness>register: (config: SceneConfig) => voidreload: (options?: TransitionOptions) => Promise<void>reset: () => void@@ -10483,6 +10485,7 @@ prefetchMisses: numberprefetchRequests: numberprepareCount: numberpreparedCells: string[]+preparedWithRenderClaim: string[]residentCells: string[]sourceCount: numberstreamed: boolean@@ -10496,6 +10499,7 @@ discardPrepared: (name: string) => numberisLoaded: (name: string) => booleanloadAdditive: (name: string) => Promise<unknown>prepare: (name: string) => Promise<void>+readyRenderPrograms: ((name: string) => Promise<RenderReadiness>) | undefinedregister: (config: SceneConfig) => voidunload: (name: string, options?: { keepPersistent?: boolean; }) => Promise<void>```@@ -10507,6 +10511,7 @@ delivery: () => Record<string, CellDelivery>loadManifest: (manifest: WorldManifest, sceneConfig?: (cell: WorldCell) => SceneConfig) => voidmanifest: WorldManifest | nullrecordPhase: (name: string, phase: string, ms: number) => void+renderReadinessOf: (name: string) => RenderReadinessStamp | nullresidencyOf: (name: string) => CellResidencystatus: () => WorldStreamerStatusupdate: (sources: readonly ResidencySource[]) => voiddiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 7dbb05bd1..24e97aba8 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -7340,6 +7340,7 @@ name: stringonPhase: ((phase: string, ms: number) => void) | undefinedpath: string | undefinedprepare: (() => Promise<void>) | undefined+readyRenderPrograms: (() => Promise<RenderReadiness>) | undefinedsetup: ((ctx: SceneContext) => void | Promise<void>) | undefinedsystems: { schedule: Schedule; system: SystemDef; }[] | undefined```@@ -7432,6 +7433,7 @@ load: (name: string, onProgress?: SceneLoadProgressCallback) => Promise<SceneConloadAdditive: (name: string, onProgress?: SceneLoadProgressCallback) => Promise<SceneContext>pause: (name: string) => voidprepare: (name: string) => Promise<void>+readyRenderPrograms: (name: string) => Promise<RenderReadiness>register: (config: SceneConfig) => voidreload: (options?: TransitionOptions) => Promise<void>reset: () => void@@ -10259,6 +10261,7 @@ prefetchMisses: numberprefetchRequests: numberprepareCount: numberpreparedCells: string[]+preparedWithRenderClaim: string[]residentCells: string[]sourceCount: numberstreamed: boolean@@ -10272,6 +10275,7 @@ discardPrepared: (name: string) => numberisLoaded: (name: string) => booleanloadAdditive: (name: string) => Promise<unknown>prepare: (name: string) => Promise<void>+readyRenderPrograms: ((name: string) => Promise<RenderReadiness>) | undefinedregister: (config: SceneConfig) => voidunload: (name: string, options?: { keepPersistent?: boolean; }) => Promise<void>```@@ -10283,6 +10287,7 @@ delivery: () => Record<string, CellDelivery>loadManifest: (manifest: WorldManifest, sceneConfig?: (cell: WorldCell) => SceneConfig) => voidmanifest: WorldManifest | nullrecordPhase: (name: string, phase: string, ms: number) => void+renderReadinessOf: (name: string) => RenderReadinessStamp | nullresidencyOf: (name: string) => CellResidencystatus: () => WorldStreamerStatusupdate: (sources: readonly ResidencySource[]) => voiddiff --git a/sdk/src/render/meshProgramReadiness.ts b/sdk/src/render/meshProgramReadiness.tsnew file mode 100644index 000000000..6d160c100--- /dev/null+++ b/sdk/src/render/meshProgramReadiness.ts@@ -0,0 +1,80 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Readying the mesh programs a decoded scene document requires.+ *+ * The document is the only source available at preparation: a cell is prepared+ * precisely when it has no entities, so the requirements have to come from what+ * it says rather than from what it spawned.+ */+import type { SceneData } from '../scene/scene';+import type { ESEngineModule } from '../wasm';+import { withScratch } from '../wasm/wasmScratch';+import type { RenderReadiness } from './renderReadiness';++/** Words per renderable in, and words of readiness result out. */+const ROW_WORDS = 5;+const RESULT_WORDS = 11;++interface DocEntity {+ components?: Array<{ type: string; data: Record<string, unknown> }>;+}++/**+ * The five words per renderable the engine reads: mesh handle, lit, normal-map+ * handle, joint count, material id.+ *+ * Asset references must already be resolved to handles: a path string here+ * reads as handle 0 and describes a requirement nothing has.+ */+export function meshDocumentRows(doc: SceneData): number[] {+ const rows: number[] = [];+ for (const entity of doc.entities as DocEntity[]) {+ const parts = entity.components;+ const renderer = parts?.find((c) => c.type === 'MeshRenderer');+ if (!renderer) continue;+ const skin = parts?.find((c) => c.type === 'MeshSkin');+ rows.push(+ Number(renderer.data.mesh) || 0,+ renderer.data.lit ? 1 : 0,+ Number(renderer.data.normalMap) || 0,+ (skin?.data.joints as unknown[] | undefined)?.length ?? 0,+ Number(renderer.data.material) || 0,+ );+ }+ return rows;+}++/**+ * Make the mesh programs `doc` requires ready, and answer with the claim.+ *+ * Not applicable where the engine does not carry the entry: a headless host owes+ * nothing rather than being handed an invented claim. A null stamp is a debt —+ * something moved underneath the readying, and it can be attempted again.+ */+export function readyMeshPrograms(module: ESEngineModule | null,+ doc: SceneData): RenderReadiness {+ if (!module?.engine_prepareMeshPrograms) return { applicable: false };+ const rows = meshDocumentRows(doc);+ // Nothing to draw is still an answer: the claim covers an empty requirement+ // set, so a cell of pure logic is prepared rather than perpetually owing.+ const m = module as unknown as {+ _malloc(n: number): number; _free(p: number): void; HEAPU32: Uint32Array;+ engine_prepareMeshPrograms(rowsPtr: number, count: number, outPtr: number): void;+ };+ return withScratch(module, (alloc) => {+ const rowsPtr = alloc(Math.max(rows.length, 1) * 4);+ const outPtr = alloc(RESULT_WORDS * 4);+ if (rows.length > 0) m.HEAPU32.set(rows, rowsPtr >> 2);+ m.engine_prepareMeshPrograms(rowsPtr, rows.length / ROW_WORDS, outPtr);+ const o = m.HEAPU32.subarray(outPtr >> 2, (outPtr >> 2) + RESULT_WORDS);+ if (o[0] !== 1) return { applicable: true, stamp: null };+ return {+ applicable: true,+ stamp: {+ digestLo: o[5], digestHi: o[6],+ programEpoch: o[7] + o[8] * 0x100000000,+ },+ };+ });+}diff --git a/sdk/src/render/renderReadiness.ts b/sdk/src/render/renderReadiness.tsnew file mode 100644index 000000000..73d5ea374--- /dev/null+++ b/sdk/src/render/renderReadiness.ts@@ -0,0 +1,45 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file What it means for content to have its render programs ready.+ *+ * Publishing content whose shaders are not built pays for them in the first+ * frame that shows it. A preparation that readies assets and not programs is a+ * promise half kept; this is the other half's shape.+ */++/**+ * A claim that some content's render programs are ready.+ *+ * Two facts, never one: the digest says WHICH programs, so a claim cannot cover+ * content it was not made about, and the epoch says those programs still exist.+ * The device generation guards the act of claiming, not the claim.+ *+ * @experimental+ */+export interface RenderReadinessStamp {+ /** The requirement digest in two halves — 64 bits do not survive a JS number. */+ digestLo: number;+ digestHi: number;+ /** The program epoch the digest holds under. */+ programEpoch: number;+}++/**+ * The outcome of trying to ready some content's render programs.+ *+ * `applicable: false` is the honest answer where there is no renderer, and must+ * never be spelled as a claim that succeeded. `stamp: null` is a debt: it can be+ * attempted again, and until one succeeds nothing is ready.+ *+ * @experimental+ */+export type RenderReadiness =+ | { applicable: false }+ | { applicable: true; stamp: RenderReadinessStamp | null };++/** Whether two claims describe the same requirements under the same epoch. */+export function sameReadiness(a: RenderReadinessStamp, b: RenderReadinessStamp): boolean {+ return a.digestLo === b.digestLo && a.digestHi === b.digestHi+ && a.programEpoch === b.programEpoch;+}diff --git a/sdk/src/residency/WorldStreamer.ts b/sdk/src/residency/WorldStreamer.tsindex e9978967a..996bfc752 100644--- a/sdk/src/residency/WorldStreamer.ts+++ b/sdk/src/residency/WorldStreamer.ts@@ -19,6 +19,7 @@import { desiredResidency, type ResidencySource, type WorldCell, type WorldManifest } from './cells';import type { SceneConfig } from '../scene/sceneManager';+import type { RenderReadiness, RenderReadinessStamp } from '../render/renderReadiness';import { defineResource } from '../ecs/resource';import { log } from '../util/logger';@@ -43,6 +44,12 @@ export type CellResidency =export interface WorldStreamHost {register(config: SceneConfig): void;prepare(name: string): Promise<void>;+ /**+ * Make the render programs a prepared cell requires ready. Absent on a host+ * that predates the obligation, which reads as not applicable — the same+ * answer a headless one gives, and never a claim that succeeded.+ */+ readyRenderPrograms?(name: string): Promise<RenderReadiness>;discardPrepared(name: string): number;loadAdditive(name: string): Promise<unknown>;unload(name: string, options?: { keepPersistent?: boolean }): Promise<void>;@@ -87,6 +94,17 @@ export interface WorldStreamerStatus {interface CellState {cell: WorldCell;residency: CellResidency;+ /**+ * The obligations preparation owes before this cell may be called prepared.+ * Held here and only READ by the state machine: what a cell's programs are+ * is the renderer's question, and a streamer deriving it would be a second+ * author of the answer.+ */+ assetsReady: boolean;+ /** The claim, once one has been made. Null while it is still owed. */+ renderReadiness: RenderReadinessStamp | null;+ /** Whether a readying attempt is in flight, so a retry does not stack. */+ readinessInFlight: boolean;/** What the last reconciliation asked for; the async completions re-read it. */desired: boolean;/** Whether any source is close enough to speculate about it. */@@ -164,6 +182,7 @@ export class WorldStreamer {this.host_.register(sceneConfig?.(cell) ?? { name: cell.name, path: cell.path });this.cells_.set(cell.name, {cell, residency: 'unloaded', desired: false, speculated: false,+ assetsReady: false, renderReadiness: null, readinessInFlight: false,phases: {}, issuedAt: 0, delivery: 0,demandedAt: 0, preparedAt: 0, publishedAt: 0,prepareMs: 0, publishMs: 0, demandToResidentMs: 0, dwellMs: 0, outcome: '',@@ -179,6 +198,19 @@ export class WorldStreamer {return this.cells_.get(name)?.residency ?? 'unloaded';}+ /**+ * The render-program claim a cell holds, or null when it holds none.+ *+ * A cell on a host with no renderer holds NONE — the obligation did not+ * apply, which is a different fact from a claim that succeeded and must stay+ * distinguishable from one. Publication reads this to re-check freshness.+ *+ * @experimental+ */+ renderReadinessOf(name: string): RenderReadinessStamp | null {+ return this.cells_.get(name)?.renderReadiness ?? null;+ }+/*** Where a cell's load spent its time.*@@ -325,8 +357,16 @@ export class WorldStreamer {private step_(name: string): void {const state = this.cells_.get(name);if (!state) return;- if (state.residency === 'preparing' || state.residency === 'publishing'- || state.residency === 'unloading') return;+ if (state.residency === 'preparing') {+ // Assets are in and only the program obligation is left. Retried+ // here, because a claim refused once (a device that rebuilt mid-+ // readying) costs one more attempt rather than the whole preparation.+ if (state.assetsReady && !state.readinessInFlight) {+ this.settleReadiness_(name, state);+ }+ return;+ }+ if (state.residency === 'publishing' || state.residency === 'unloading') return;if (state.residency === 'unloaded' && (state.desired || state.speculated)) {this.beginPrepare_(name, state);} else if (state.residency === 'prepared' && state.desired) {@@ -337,6 +377,8 @@ export class WorldStreamer {// happens to be ready.this.cancelledRefs_ += this.host_.discardPrepared(name);state.residency = 'unloaded';+ state.assetsReady = false;+ state.renderReadiness = null;this.cancelCount_++;} else if (state.residency === 'resident' && !state.desired) {this.beginUnload_(name, state);@@ -359,23 +401,67 @@ export class WorldStreamer {state.outcome = '';state.dwellMs = 0;}+ state.assetsReady = false;+ state.renderReadiness = null;Promise.resolve(this.host_.prepare(name)).then(() => {- state.residency = 'prepared';- state.preparedAt = performance.now();- state.prepareMs = state.preparedAt - state.issuedAt;- // What finished was begun against a world that has moved. Whether- // this cell is still wanted — or wanted now when it was not — is- // asked again here rather than assumed from when it started.- this.step_(name);+ // One obligation of two. `prepared` is not the end of the assets+ // arriving, it is the end of everything publication requires.+ state.assetsReady = true;+ this.settleReadiness_(name, state);},(err) => {state.residency = 'unloaded';+ state.assetsReady = false;log.error('residency', `cell "${name}" did not prepare`, err);},);}+ /**+ * Pay the render-program obligation, or leave it owed.+ *+ * A debt rather than an event: a claim that could not be made leaves the cell+ * in `preparing` with its assets intact, and the next progression tries+ * again. Dropping it would strip a preparation that had almost finished.+ */+ private settleReadiness_(name: string, state: CellState): void {+ const ready = this.host_.readyRenderPrograms;+ if (!ready) { this.markPrepared_(name, state); return; }++ state.readinessInFlight = true;+ Promise.resolve(ready.call(this.host_, name)).then(+ (outcome) => {+ state.readinessInFlight = false;+ // Not applicable is an answer, not a claim: a host with no+ // renderer has nothing to ready and owes nothing.+ if (!outcome.applicable) { this.markPrepared_(name, state); return; }+ if (!outcome.stamp) {+ log.warn('residency',+ `cell "${name}" readied no render programs; still owed`);+ return;+ }+ state.renderReadiness = outcome.stamp;+ this.markPrepared_(name, state);+ },+ (err) => {+ state.readinessInFlight = false;+ log.error('residency', `cell "${name}" could not ready its programs`, err);+ },+ );+ }++ /** Every obligation is satisfied: only now is the cell prepared. */+ private markPrepared_(name: string, state: CellState): void {+ state.residency = 'prepared';+ state.preparedAt = performance.now();+ state.prepareMs = state.preparedAt - state.issuedAt;+ // What finished was begun against a world that has moved. Whether this+ // cell is still wanted — or wanted now when it was not — is asked again+ // here rather than assumed from when it started.+ this.step_(name);+ }+private beginLoad_(name: string, state: CellState): void {state.residency = 'publishing';state.publishedAt = performance.now();diff --git a/sdk/src/residency/report.ts b/sdk/src/residency/report.tsindex f3a410c10..4adcfe21b 100644--- a/sdk/src/residency/report.ts+++ b/sdk/src/residency/report.ts@@ -32,6 +32,9 @@ export interface WorldResidencyReport {residentCells: string[];/** Ready, owning assets, and holding nothing the world can see. */preparedCells: string[];+ /** Of those, the ones holding a render-program claim. A prepared cell with+ * none was readied by a host that has no renderer to ready. */+ preparedWithRenderClaim: string[];loadingCells: string[];unloadingCells: string[];loadCount: number;@@ -75,6 +78,7 @@ export interface WorldResidencyReport {const EMPTY: WorldResidencyReport = {streamed: false, cellCount: 0, sourceCount: 0,desiredCells: [], prefetchCells: [], residentCells: [], preparedCells: [],+ preparedWithRenderClaim: [],loadingCells: [], unloadingCells: [],loadCount: 0, unloadCount: 0, prepareCount: 0, cancelCount: 0,prefetchRequests: 0, cancelledRefs: 0,@@ -131,6 +135,8 @@ export function worldResidencyReport(app: App): WorldResidencyReport {prefetchCells: status.prefetchCells,residentCells: status.residentCells,preparedCells: status.preparedCells,+ preparedWithRenderClaim:+ status.preparedCells.filter((c) => streamer.renderReadinessOf(c) !== null),loadingCells: status.loadingCells,unloadingCells: status.unloadingCells,loadCount: status.loadCount,diff --git a/sdk/src/runtime/runtimeLoader.ts b/sdk/src/runtime/runtimeLoader.tsindex 833dfce1b..1f2ae8381 100644--- a/sdk/src/runtime/runtimeLoader.ts+++ b/sdk/src/runtime/runtimeLoader.ts@@ -29,6 +29,8 @@ import { transcoderFromModule, type BasisWasmModule } from '../asset/basisTranscimport type { BasisTranscoder } from '../asset/compressed';import type { TextureImportSettings } from '../asset/loaders/TextureLoader';import { SceneManager, type SceneConfig } from '../scene/sceneManager';+import { readyMeshPrograms } from '../render/meshProgramReadiness';+import type { RenderReadiness } from '../render/renderReadiness';import { WorldStreaming } from '../residency/WorldStreamer';import { persistentEntityRows } from '../residency/identity';import type { WorldManifest } from '../residency/cells';@@ -684,6 +686,13 @@ export function createRuntimeSceneConfig(async prepare() {if (prepared === null) prepared = await readied();},+ // The second obligation. It runs on what `prepare` decoded, so the mesh+ // references are already handles; readying from an unprepared scene would+ // describe requirements for geometry nothing has acquired.+ async readyRenderPrograms() {+ if (prepared === null) return { applicable: false } as RenderReadiness;+ return readyMeshPrograms(options.module, prepared.sceneData);+ },discardPrepared() {// Speculation is not authority: what nobody asked for is given back,// receipts included, rather than published because it was ready.diff --git a/sdk/src/scene/sceneManager.ts b/sdk/src/scene/sceneManager.tsindex 48cd48417..d4fef4f98 100644--- a/sdk/src/scene/sceneManager.ts+++ b/sdk/src/scene/sceneManager.ts@@ -14,6 +14,7 @@ import { assetBindingsOf, readLiveAssetBinding } from '../asset/liveAssetBindingimport { leaseBoundAs, slotLeaseNamed } from '../asset/liveAssetRebind';import type { SystemDef } from '../ecs/system';import { Material } from '../render/material';+import type { RenderReadiness } from '../render/renderReadiness';import type { DrawCallback } from '../render/customDraw';import { Schedule } from '../ecs/system';import { loadSceneWithAssets } from './scene';@@ -66,6 +67,12 @@ export interface SceneConfig {prepare?: () => Promise<void>;/** Throw away what `prepare` readied, answering how many receipts came back. */discardPrepared?: () => number;+ /**+ * Ready the render programs this scene's content requires, from what+ * `prepare` decoded. Absent means the obligation does not apply here, which+ * is how a headless host satisfies it — never by inventing a claim.+ */+ readyRenderPrograms?: () => Promise<RenderReadiness>;}/**@@ -414,6 +421,17 @@ export class SceneManagerState {await this.configs_.get(name)?.prepare?.();}+ /**+ * Make the render programs `name`'s prepared content requires ready.+ * @returns Not applicable where the scene declares no readying or is already+ * up; otherwise the claim, or null when one could not be made.+ */+ async readyRenderPrograms(name: string): Promise<RenderReadiness> {+ if (this.scenes_.has(name)) return { applicable: false };+ const ready = this.configs_.get(name)?.readyRenderPrograms;+ return ready ? ready() : { applicable: false };+ }+/*** Give back what {@link prepare} readied, answering how many acquisitions* came back with it. Zero for a scene that readied nothing.diff --git a/sdk/tests/world-residency.test.ts b/sdk/tests/world-residency.test.tsindex a5f5c2a71..67f07eaf2 100644--- a/sdk/tests/world-residency.test.ts+++ b/sdk/tests/world-residency.test.ts@@ -10,6 +10,7 @@ import {desiredResidency, distanceToCell, type WorldCell, type ResidencySource,} from '../src/residency/cells';import { WorldStreamer, type WorldStreamHost } from '../src/residency/WorldStreamer';+import type { RenderReadiness } from '../src/render/renderReadiness';import type { WorldManifest } from '../src/residency/cells';import { World } from '../src/ecs/world';import { Health, applyDamage } from '../src/gameplay/Health';@@ -126,7 +127,12 @@ describe('desiredResidency', () => {});});-function recordingHost() {+/**+ * A host with a renderer that always readies. `readiness` steers what the+ * readying answers, so a criterion can put a cell in front of every outcome the+ * obligation has — a claim, a debt, and no renderer at all.+ */+function recordingHost(readiness?: () => RenderReadiness) {const loaded = new Set<string>();const readied = new Set<string>();const calls: string[] = [];@@ -140,6 +146,12 @@ function recordingHost() {if (!deferred) { settle(); return Promise.resolve(); }return new Promise((resolve) => pending.push(() => { settle(); resolve(); }));},+ ...(readiness ? {+ readyRenderPrograms(name: string): Promise<RenderReadiness> {+ calls.push(`ready:${name}`);+ return Promise.resolve(readiness());+ },+ } : {}),discardPrepared(name) {calls.push(`discard:${name}`);// Two receipts per readied cell, so "gave them back" is a number and@@ -171,6 +183,96 @@ const manifest = (...cells: WorldCell[]): WorldManifest =>({ version: 1, scene: 'main', cellSize: 100, persistentRefs: [], cells });describe('WorldStreamer', () => {+ // `prepared` means every obligation publication has is satisfied — not that+ // the assets arrived. A cell whose programs are not ready is one whose first+ // visible frame pays for them, which is the frame a player is looking at.+ describe('the render-program obligation gates prepared', () => {+ const claim: RenderReadiness =+ { applicable: true, stamp: { digestLo: 7, digestHi: 0, programEpoch: 3 } };+ // Speculated, never demanded: the cell stays where preparation leaves it+ // instead of being published the instant it is ready, which is what makes+ // `prepared` observable at all.+ const nearby = () => source(250, 50, 10, 20, 200);++ it('a cell with a valid claim is prepared', async () => {+ const { host } = recordingHost(() => claim);+ const s = new WorldStreamer(host);+ s.loadManifest(manifest(cell(0, 0)));+ s.update([nearby()]);+ await flush();+ expect(s.residencyOf('c_0_0')).toBe('prepared');+ expect(s.renderReadinessOf('c_0_0'))+ .toEqual({ digestLo: 7, digestHi: 0, programEpoch: 3 });+ });++ it('a cell whose readying made NO claim is not prepared, whatever its assets did',+ async () => {+ const { host, readied } = recordingHost(() => ({ applicable: true, stamp: null }));+ const s = new WorldStreamer(host);+ s.loadManifest(manifest(cell(0, 0)));+ s.update([nearby()]);+ await flush();+ // The assets are in — this is precisely the state the old contract+ // called prepared, and publishing from it is the defect.+ expect(readied.has('c_0_0')).toBe(true);+ expect(s.residencyOf('c_0_0')).not.toBe('prepared');+ expect(s.residencyOf('c_0_0')).toBe('preparing');+ });++ it('an unpaid claim is a debt the next progression retries', async () => {+ let answer: RenderReadiness = { applicable: true, stamp: null };+ const { host, calls } = recordingHost(() => answer);+ const s = new WorldStreamer(host);+ s.loadManifest(manifest(cell(0, 0)));+ s.update([nearby()]);+ await flush();+ expect(s.residencyOf('c_0_0')).toBe('preparing');++ // The device settled, or whatever refused the claim stopped. The+ // preparation must continue rather than start over.+ answer = claim;+ s.update([nearby()]);+ await flush();+ expect(s.residencyOf('c_0_0')).toBe('prepared');+ expect(calls.filter((c) => c === 'prepare:c_0_0')).toHaveLength(1);+ expect(calls.filter((c) => c === 'ready:c_0_0')).toHaveLength(2);+ });++ it('a readying that throws leaves the debt, not a prepared cell', async () => {+ const { host } = recordingHost(() => { throw new Error('device went away'); });+ const s = new WorldStreamer(host);+ s.loadManifest(manifest(cell(0, 0)));+ s.update([nearby()]);+ await flush();+ expect(s.residencyOf('c_0_0')).toBe('preparing');+ });++ it('a host with no renderer satisfies the obligation by not having it', async () => {+ const { host, calls } = recordingHost(() => ({ applicable: false }));+ const s = new WorldStreamer(host);+ s.loadManifest(manifest(cell(0, 0)));+ s.update([nearby()]);+ await flush();+ expect(s.residencyOf('c_0_0')).toBe('prepared');+ expect(calls).toContain('ready:c_0_0');+ // Not applicable holds NO claim. An empty stamp would be a claim+ // about nothing, and publication would later re-check it against the+ // live renderer as if a renderer had made it.+ expect(s.renderReadinessOf('c_0_0')).toBeNull();+ });++ it('a host that predates the obligation is not held to it', async () => {+ const { host, calls } = recordingHost();+ const s = new WorldStreamer(host);+ s.loadManifest(manifest(cell(0, 0)));+ s.update([nearby()]);+ await flush();+ expect(s.residencyOf('c_0_0')).toBe('prepared');+ expect(calls.some((c) => c.startsWith('ready:'))).toBe(false);+ expect(s.renderReadinessOf('c_0_0')).toBeNull();+ });+ });+it('registers every cell as a scene the game itself never names', async () => {const { host, calls } = recordingHost();new WorldStreamer(host).loadManifest(manifest(cell(0, 0), cell(1, 0)));diff --git a/tools/verify-world-residency.mjs b/tools/verify-world-residency.mjsindex 0df4e6dea..8ff2b9161 100644--- a/tools/verify-world-residency.mjs+++ b/tools/verify-world-residency.mjs@@ -134,6 +134,14 @@ function main() {&& !initial.streaming.residentCells.includes(B),'places the player may soon want are readied without being brought in',`prepared ${JSON.stringify(initial.streaming.preparedCells)}`);+ // Assets are half of what publication needs. A cell readied without its+ // shader programs pays for them in the first frame that shows it, which is+ // the frame this whole feature exists to make cheap.+ claim(initial.streaming.preparedWithRenderClaim.includes(B)+ && initial.streaming.preparedWithRenderClaim.includes(C),+ 'and their render programs are ready too, not just their assets',+ `claims ${JSON.stringify(initial.streaming.preparedWithRenderClaim)}`+ + ` of prepared ${JSON.stringify(initial.streaming.preparedCells)}`);claim(initial.at.Enemy === undefined && initial.at.Wall === undefined&& initial.streaming.hunters === 0 && initial.streaming.navAgents === 0&& entities(initial, B) === undefined,