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(ecs): a list field reads back as an array on every read path
esengine2e6a00eba515
diff --git a/sdk/src/ecs/bridge/BuiltinBridge.ts b/sdk/src/ecs/bridge/BuiltinBridge.tsindex 23c9cad13..47e1bab4e 100644--- a/sdk/src/ecs/bridge/BuiltinBridge.ts+++ b/sdk/src/ecs/bridge/BuiltinBridge.ts@@ -121,13 +121,6 @@ export function materializeNumberVectors(return made;}-/**- * Snapshot a component's list fields back into JS arrays, freeing the embind- * vectors they came back as.- *- * Read here and not left to the caller: an embind vector is a heap object that- * leaks unless freed, and an array is what everything above this already speaks.- *//*** Which of a builtin's fields hold a list of numbers. Read off the generated* metadata rather than carried on the component definition: that definition is@@ -137,7 +130,12 @@ export function numberListFieldsOf(cppName: string): readonly string[] {return (COMPONENT_META[cppName]?.numberListFields ?? []) as readonly string[];}-export function snapshotNumberVectors(+/**+ * A component's list fields — numbers or entities — as JS arrays, the embind+ * vectors freed; a non-vector field is left as it is. Here and not at the caller:+ * a vector leaks unless freed, and only some emsdk versions make it iterable.+ */+export function snapshotVectors(obj: Record<string, unknown>, fields: readonly string[],): Record<string, unknown> {for (const key of fields) {@@ -151,6 +149,16 @@ export function snapshotNumberVectors(return obj;}+/** A builtin as embind hands it back, made into what the rest of the SDK reads:+ * its lists as arrays (the vectors freed) and its colours converted. */+export function builtinFromWasm(raw: unknown, component: BuiltinComponentDef<any>): unknown {+ return convertFromWasm(+ snapshotVectors(raw as Record<string, unknown>,+ [...numberListFieldsOf(component._cppName), ...component.entityFields]),+ component.colorKeys,+ );+}+// =============================================================================// Pointer-based Field Access// =============================================================================@@ -867,12 +875,7 @@ export class BuiltinBridge {throw new Error('C++ Registry not connected');}try {- const raw = this.getBuiltinMethods(component._cppName).get(entity);- return convertFromWasm(- snapshotNumberVectors(raw as Record<string, unknown>,- numberListFieldsOf(component._cppName)),- component.colorKeys,- ) as T;+ return builtinFromWasm(this.getBuiltinMethods(component._cppName).get(entity), component) as T;} catch (e) {handleWasmError(e, `getBuiltin(${component._name}, entity=${entity})`);return { ...component._default } as T;diff --git a/sdk/src/ecs/world.ts b/sdk/src/ecs/world.tsindex df1c6661e..b202a9e9b 100644--- a/sdk/src/ecs/world.ts+++ b/sdk/src/ecs/world.ts@@ -9,7 +9,7 @@ import { Entity, entityGeneration, entityIndex, makeEntity, INVALID_ENTITY } froimport { AnyComponentDef, ComponentDef, ComponentData, BuiltinComponentDef, isBuiltinComponent, getComponentRegistry, getUserComponents, getComponent, Disabled, Name, Parent, Children, type ParentData, type ChildrenData } from './component';import type { CppRegistry, ESEngineModule } from '../wasm';import { handleWasmError } from '../wasm/wasmError';-import { BuiltinBridge, convertFromWasm, convertForWasm, type BridgeConnectOptions,+import { BuiltinBridge, builtinFromWasm, numberListFieldsOf, convertForWasm, type BridgeConnectOptions,type BuiltinMethods, type CompositionDelta } from './bridge/BuiltinBridge';import { ScriptStorage } from './ScriptStorage';import type { PoolMemory, ScriptPool } from './ScriptPool';@@ -833,10 +833,7 @@ export class World {try {const methods = this.builtin_.getBuiltinMethods(component._cppName);if (!bset && !methods.has(entity)) return null;- return convertFromWasm(- methods.get(entity) as Record<string, unknown>,- component.colorKeys,- ) as ComponentData<C>;+ return builtinFromWasm(methods.get(entity), component) as ComponentData<C>;} catch (e) {handleWasmError(e, `tryGet(${component._name}, entity=${entity})`);return null;@@ -949,11 +946,10 @@ export class World {}const methods = this.builtin_.getBuiltinMethods(component._cppName);- const colorKeys = component.colorKeys;- if (colorKeys.length === 0) {- return (e) => methods.get(e);- }- return (e) => convertFromWasm(methods.get(e) as Record<string, unknown>, colorKeys);+ const plain = component.colorKeys.length === 0 && component.entityFields.length === 0+ && numberListFieldsOf(component._cppName).length === 0;+ if (plain) return (e) => methods.get(e);+ return (e) => builtinFromWasm(methods.get(e), component);}const storage = this.scripts_.getStorageById(component._id);if (!storage) return null;diff --git a/sdk/src/scene/scene.ts b/sdk/src/scene/scene.tsindex cee4f00fc..b77cc2d43 100644--- a/sdk/src/scene/scene.ts+++ b/sdk/src/scene/scene.ts@@ -773,9 +773,7 @@ export function serializeScene(world: World, sceneName = 'scene'): SceneData {}}- // Derive children from the parent map so we don't have to decode the- // Children component (whose `entities` field is a wasm VectorEntity on- // the CPP backend and would leak if iterated without cleanup).+ // Derived from the parent map already built above: one pass, no second read per entity.const childrenOf = new Map<number, number[]>();for (const [child, parent] of parentOf) {let arr = childrenOf.get(parent);diff --git a/sdk/tests/builtin-list-fields-wasm.test.ts b/sdk/tests/builtin-list-fields-wasm.test.tsnew file mode 100644index 000000000..090dc90f5--- /dev/null+++ b/sdk/tests/builtin-list-fields-wasm.test.ts@@ -0,0 +1,41 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file A builtin's list fields read back as arrays on every read path.+ *+ * Embind hands a `std::vector` field back as a heap object. emsdk 5 makes it+ * iterable, 4.0.10 does not, and neither frees it: `tryGet(Children)` returned+ * one, so the animator threw every frame on the WeChat GLX engine and leaked a+ * vector per joint per frame on every other. Requires build/wasm/web.+ */+import { describe, it, expect, beforeAll } from 'vitest';+import { World } from '../src/ecs/world';+import { Children } from '../src/ecs/component';+import type { ESEngineModule, CppRegistry } from '../src/wasm';+import { loadWasmModule, HAS_WASM } from './helpers/loadWasm';++describe.skipIf(!HAS_WASM)('builtin list fields', () => {+ let module: ESEngineModule;+ beforeAll(async () => { module = await loadWasmModule(); });++ it('come back as arrays from get, tryGet and a resolved getter', () => {+ const registry = new module.Registry() as unknown as CppRegistry;+ const world = new World();+ world.connectCpp(registry, module);+ const parent = world.spawn();+ const kids = [world.spawn(), world.spawn()];+ for (const k of kids) world.setParent(k, parent);++ const reads = {+ get: world.get(parent, Children).entities,+ tryGet: world.tryGet(parent, Children)!.entities,+ getter: (world.resolveGetter(Children)!(parent) as { entities: unknown }).entities,+ };+ for (const [path, entities] of Object.entries(reads)) {+ expect(Array.isArray(entities), path).toBe(true);+ expect([...(entities as number[])].sort(), path).toEqual([...kids].sort());+ }+ world.disconnectCpp();+ (registry as unknown as { delete(): void }).delete();+ });+});