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
fix(play): find() is a list, and a name nothing is registered under throws
yhh1daceff415a0
diff --git a/desktop/scripts/editor-checks/play-stepping.mjs b/desktop/scripts/editor-checks/play-stepping.mjsindex 123a30af7..d657abc13 100644--- a/desktop/scripts/editor-checks/play-stepping.mjs+++ b/desktop/scripts/editor-checks/play-stepping.mjs@@ -49,6 +49,23 @@ export async function run(ed) {code: 'return resource("Time")', // bare, no window.__estellaPlay prefix}, 60000)) ?? {};+ // `find` is a LIST. Every driver writes `.length` and `[0]` first, so both those+ // and the count have to work on the same value.+ const shape = await ed.json('play_probe', {+ code: 'const s = find("Transform"); return { isArray: Array.isArray(s), length: s.length, total: s.total, first: !!s[0]?.entity };',+ }, 60000);+ check(shape?.isArray === true, `find() is not an array: ${JSON.stringify(shape)}`);+ check(shape?.length > 0 && shape.length === shape.total, `find().length ${shape?.length} vs .total ${shape?.total}`);+ check(shape?.first === true, 'find()[0] carries no entity id');+ // A name nothing is registered under is a TYPO, not an empty world.+ let threw = false;+ try {+ await ed.json('play_probe', { code: 'return find("NoSuchComponent").length' }, 60000);+ } catch {+ threw = true;+ }+ check(threw, 'find("NoSuchComponent") answered instead of throwing — an unchecked caller reads that as "none"');+const before = await clock();if (!check(typeof before.frameCount === 'number', `the probe scope has no bare resource(): ${JSON.stringify(before)}`)) {return check.failures;diff --git a/desktop/shared/toolCatalog.mjs b/desktop/shared/toolCatalog.mjsindex 2df694350..ac33589bb 100644--- a/desktop/shared/toolCatalog.mjs+++ b/desktop/shared/toolCatalog.mjs@@ -470,13 +470,15 @@ export const TOOLS = [description: "The Create-popover catalog: every ready-made entity the editor can spawn (id, label, category). Use an id with create_entity.",schema: obj({}), method: 'listEntityTemplates', args: () => [], root: 'editor' },{ name: 'create_entity', effect: 'undoable',- description: 'Spawn a ready-made entity from a template id (see list_entity_templates) through the same pipeline as the Create menu; returns the new entity id. Optional world position and parent.',+ description: 'Spawn a ready-made entity from a template id (see list_entity_templates) through the same pipeline as the Create menu; returns the new entity id. Optional world position, parent and NAME. '+ + '`name` matters most for a `prefab:<path>` template: without it every instance arrives called whatever the prefab is called, so ten enemies are ten entities you cannot tell apart. '+ + 'It is applied as the entity is built (one undo step) and, on an instance, saves as an ordinary name override — the prefab keeps its own name.',schema: obj({template: { type: 'string' }, parent: { type: ['number', 'null'] },- x: { type: 'number' }, y: { type: 'number' },+ x: { type: 'number' }, y: { type: 'number' }, name: { type: 'string' },}, ['template']),method: 'createEntity',- args: (i) => [i.template, { parent: i.parent ?? null, x: i.x, y: i.y }], root: 'editor' },+ args: (i) => [i.template, { parent: i.parent ?? null, x: i.x, y: i.y, name: i.name }], root: 'editor' },{ name: 'toggle_play',description: 'Enter or leave play mode, AWAITED — it resolves once the game realm is ready (or gone) and answers with its state, so there is nothing to poll afterwards. '+ 'Play runs the game in an isolated realm and never dirties the edit scene. Once in: `step` advances it, `play_input` drives it, `play_probe` reads it, `screenshot` shows it.',@@ -538,7 +540,7 @@ export const TOOLS = [{ name: 'play_probe', effect: 'irreversible',description: "Evaluate JS inside the RUNNING play realm and return the result — the gameplay probe. One expression gives its value; several statements need an explicit `return`. "+ 'These are ALREADY IN SCOPE (no prefix, though `window.__estellaPlay` holds them too): '- + '**`find(NAME)`** — every entity carrying that component, with its live data; '+ + '**`find(NAME)`** — an ARRAY of `{ entity, data }`, one per entity carrying that component (`.length`, `[0]`, `for..of` and `.map` all work; `.total` is the count, `.truncatedAt` is set when a limit cut it short, and returning the array itself serialises as a plain list); '+ '**`get(ENTITY, NAME)`** — one entity\'s component data, or null when it does not have it; '+ '**`set(ENTITY, NAME, PATCH)`** — write fields of one component, for staging the situation you want to watch; '+ '**`resource(NAME)`** — the live value of a resource (a score, a phase — state belonging to no entity); 'diff --git a/desktop/src/playHost.ts b/desktop/src/playHost.tsindex b17fd9c68..f8f27a5a8 100644--- a/desktop/src/playHost.ts+++ b/desktop/src/playHost.ts@@ -28,6 +28,15 @@ type LiveEntity = SceneData['entities'][number];// avoids serializing every entity's component data on every sample.const LIVE_STRUCTURAL = new Set(['Name', 'Parent', 'Children', 'WorldTransform']);+/** Every component name this realm has an instance of — what `find` accepts, and what+ * a mistyped one is answered with. */+function componentNamesOf(app_: App): string[] {+ return app_.world.getAllEntities()+ .flatMap((e) => app_.world.getComponentTypes(e as never))+ .filter((t, i, a) => a.indexOf(t) === i)+ .sort();+}+function inspectableTypes(world: App['world'], entity: number): string[] {return world.getComponentTypes(entity as never).filter((t) => {if (LIVE_STRUCTURAL.has(t)) return false;@@ -305,17 +314,29 @@ async function buildAppAndRun(msg: InitMessage): Promise<void> {find: (name: string, limit = 200) => {const world = app!.world;const def = getComponent(name);+ // THROWN, not returned as `{ error }`: a caller that does not check reads an+ // error object as "no entities have it", which is the same shape a typo in the+ // NAME produces and the opposite of the truth.if (!def) {- return { error: `no component named "${name}" is registered in this realm` };+ throw new Error(+ `no component named "${name}" is registered in this realm `+ + `(componentNames() lists them: ${componentNamesOf(app!).slice(0, 40).join(', ')})`,+ );}- const out: Array<{ entity: number; data: unknown }> = [];+ // An ARRAY of { entity, data }, with `total` / `truncatedAt` hung off it.+ // Every driver so far has written `find('Ball').length` and `[0]` first — the+ // reading a list invites — and spent three or four calls discovering a wrapper+ // object instead. Both readings now work: `.length`, `[0]`, `for..of` and+ // `.map` on the list itself, `.total` when what you want is the count.+ const out = [] as Array<{ entity: number; data: unknown }> & { total?: number; truncatedAt?: number };for (const e of world.getAllEntities()) {const data = world.tryGet(e, def);if (data === null || data === undefined) continue;- if (out.length >= limit) return { total: out.length, truncatedAt: limit, entities: out };+ if (out.length >= limit) { out.truncatedAt = limit; break; }out.push({ entity: e as never as number, data });}- return { total: out.length, entities: out };+ out.total = out.length;+ return out;},/*** ONE entity's component data, honestly — null when it does not have it.@@ -327,7 +348,9 @@ async function buildAppAndRun(msg: InitMessage): Promise<void> {*/get: (entity: number, name: string) => {const def = getComponent(name);- if (!def) return { error: `no component named "${name}" is registered in this realm` };+ if (!def) throw new Error(`no component named "${name}" is registered in this realm`);+ // null = this entity does not have it. A mistyped NAME throws above, so the two+ // are never the same answer.return app!.world.tryGet(entity as never, def) ?? null;},/**@@ -340,10 +363,10 @@ async function buildAppAndRun(msg: InitMessage): Promise<void> {*/set: (entity: number, name: string, patch: Record<string, unknown>) => {const def = getComponent(name);- if (!def) return { error: `no component named "${name}" is registered in this realm` };+ if (!def) throw new Error(`no component named "${name}" is registered in this realm`);const current = app!.world.tryGet(entity as never, def);if (current === null || current === undefined) {- return { error: `entity ${entity} has no ${name}` };+ throw new Error(`entity ${entity} has no ${name}`);}app!.world.insert(entity as never, def, { ...(current as object), ...patch } as never);return app!.world.tryGet(entity as never, def) ?? null;@@ -361,10 +384,7 @@ async function buildAppAndRun(msg: InitMessage): Promise<void> {return { frames, dt, frameCount: time?.frameCount ?? 0, elapsed: time?.elapsed ?? 0 };},/** What `find` can be asked about: the component names this realm knows. */- componentNames: () => app!.world.getAllEntities()- .flatMap((e) => app!.world.getComponentTypes(e as never))- .filter((t, i, a) => a.indexOf(t) === i)- .sort(),+ componentNames: () => componentNamesOf(app!),/*** A resource's live value by name — the other half of "what does the game* think is going on", for state that belongs to no entity (a score, a life