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 engine activity, asset ownership and material rendering
yhh2b35c77ae2b7
diff --git a/native/host/bindings/AotBindings.cpp b/native/host/bindings/AotBindings.cppindex cd568dd1e..3f69338ef 100644--- a/native/host/bindings/AotBindings.cpp+++ b/native/host/bindings/AotBindings.cpp@@ -39,6 +39,7 @@#include "esengine/aot/EngineDigest.generated.h"#include <cstdio>+#include <charconv>#include <deque>#include <string>#include <unordered_map>@@ -63,7 +64,6 @@ struct AotState {/** The fallback list, rebuilt per run for a system that cannot narrow.* Kept so a frame that needs it allocates none. */std::vector<std::uint32_t> candidates;- bool installed = false;};AotState& state() {@@ -117,7 +117,8 @@ void* resourceAt(const char* name) {// — the calls —/** es_aot_install(path) -> system count, or -1 with the reason logged. */-JSValue js_install(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {+JSValue installModule(JSContext* ctx, int argc, JSValueConst* argv,+ std::optional<std::uint64_t> expectedContract = std::nullopt) {if (argc < 1) return JS_NewInt32(ctx, -1);const char* path = JS_ToCString(ctx, argv[0]);if (path == nullptr) return JS_NewInt32(ctx, -1);@@ -131,13 +132,40 @@ JSValue js_install(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {AotState& s = state();std::string why;const bool ok = s.dispatcher.install(open, aot::abiHash(ES_ENGINE_ABI_DIGEST),- componentAt, resourceAt, &why, candidatesFor);+ componentAt, resourceAt, &why, candidatesFor, expectedContract);+ if (ok) {+ // Bound resolvers hold slot addresses: invalidate their contents without+ // freeing slots. The new SDK owner reports only its own rows/resources.+ for (auto& span : s.scriptSpans) span = {};+ s.resources.clear();+ s.candidates.clear();+ }if (!ok) ESHOST_LOGE("[aot] %s: %s", path, why.c_str());JS_FreeCString(ctx, path);- s.installed = ok;return JS_NewInt32(ctx, ok ? static_cast<int>(s.dispatcher.count()) : -1);}+JSValue js_install(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {+ return installModule(ctx, argc, argv);+}++/** Validate the sidecar against the candidate before replacing the live module. */+JSValue js_installChecked(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {+ if (argc < 2) return JS_ThrowTypeError(ctx, "es_aot_install_checked requires a module and contract");+ const char* text = JS_ToCString(ctx, argv[1]);+ if (!text) return JS_EXCEPTION;+ std::uint64_t expected = 0;+ const std::size_t length = std::strlen(text);+ bool valid = length == 0;+ if (length == 16) {+ const auto parsed = std::from_chars(text, text + length, expected, 16);+ valid = parsed.ec == std::errc{} && parsed.ptr == text + length;+ }+ JS_FreeCString(ctx, text);+ if (!valid) return JS_ThrowTypeError(ctx, "module contract must be empty or 16 hex digits");+ return installModule(ctx, argc, argv, expected);+}+/** es_aot_index(name) -> the index the scheduler keeps, or -1. */JSValue js_index(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {if (argc < 1) return JS_NewInt32(ctx, -1);@@ -247,7 +275,9 @@ JSValue js_run(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {std::uint32_t i = 0;JS_ToUint32(ctx, &i, argv[0]);AotState& s = state();- if (!s.installed) return JS_NewInt32(ctx, -1);+ // The dispatcher owns installed state. A failed replacement retains its+ // old systems; an independent flag would disable that preserved module.+ if (i >= s.dispatcher.count()) return JS_NewInt32(ctx, -1);aot::WorldStamp world;double scriptEpoch = 0.0;@@ -278,7 +308,6 @@ JSValue js_reset(JSContext* ctx, JSValueConst, int, JSValueConst*) {s.scriptByName.clear();s.scriptSpans.clear();s.resources.clear();- s.installed = false;return JS_UNDEFINED;}@@ -289,6 +318,7 @@ void registerAotBindings(HostState& h, JSValue global) {JS_SetPropertyStr(h.js, global, name, JS_NewCFunction(h.js, impl, name, arity));};fn("es_aot_install", js_install, 1);+ fn("es_aot_install_checked", js_installChecked, 2);fn("es_aot_index", js_index, 1);fn("es_aot_bound", js_bound, 1);fn("es_aot_contract", js_contract, 0);diff --git a/native/host/bindings/EcsBindings.cpp b/native/host/bindings/EcsBindings.cppindex 0718b9e71..03009479e 100644--- a/native/host/bindings/EcsBindings.cpp+++ b/native/host/bindings/EcsBindings.cpp@@ -48,9 +48,33 @@ JSValue js_destroyEntity(JSContext* ctx, JSValueConst, int, JSValueConst* argv)return JS_UNDEFINED;}JSValue js_setParent(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {- ecs::setParent(*host().registry, esn_entity(ctx, argv[0]), esn_entity(ctx, argv[1]));+ return JS_NewBool(ctx, ecs::setParent(*host().registry, esn_entity(ctx, argv[0]), esn_entity(ctx, argv[1])));+}+JSValue js_reserveDestruction(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {+ return JS_NewBool(ctx, host().registry->reserveDestruction(esn_entity(ctx, argv[0])));+}+JSValue js_releaseDestruction(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {+ host().registry->releaseDestruction(esn_entity(ctx, argv[0]));return JS_UNDEFINED;}+JSValue js_destructionPending(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {+ return JS_NewBool(ctx, host().registry->destructionPending(esn_entity(ctx, argv[0])));+}+JSValue js_setEntityEnabled(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {+ return JS_NewBool(ctx, host().registry->setEntityEnabled(esn_entity(ctx, argv[0]), JS_ToBool(ctx, argv[1]) != 0));+}+JSValue js_isEntityActive(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {+ return JS_NewBool(ctx, host().registry->isEntityActive(esn_entity(ctx, argv[0])));+}+JSValue js_isEntityEnabled(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {+ return JS_NewBool(ctx, host().registry->isEntityEnabled(esn_entity(ctx, argv[0])));+}+JSValue js_hasInactiveEntities(JSContext* ctx, JSValueConst, int, JSValueConst*) {+ return JS_NewBool(ctx, host().registry->hasInactiveEntities());+}+JSValue js_activityEpoch(JSContext* ctx, JSValueConst, int, JSValueConst*) {+ return JS_NewUint32(ctx, host().registry->activityEpoch());+}JSValue js_hasParent(JSContext* ctx, JSValueConst, int, JSValueConst* argv) {return JS_NewBool(ctx, host().registry->has<ecs::Parent>(esn_entity(ctx, argv[0])));}@@ -168,6 +192,14 @@ void registerEcsBindings(HostState& h, JSValue global) {bindGlobal(h, global, "es_createEntity", js_createEntity, 0);bindGlobal(h, global, "es_destroyEntity", js_destroyEntity, 1);bindGlobal(h, global, "es_setParent", js_setParent, 2);+ bindGlobal(h, global, "es_reserveDestruction", js_reserveDestruction, 1);+ bindGlobal(h, global, "es_releaseDestruction", js_releaseDestruction, 1);+ bindGlobal(h, global, "es_destructionPending", js_destructionPending, 1);+ bindGlobal(h, global, "es_setEntityEnabled", js_setEntityEnabled, 2);+ bindGlobal(h, global, "es_isEntityActive", js_isEntityActive, 1);+ bindGlobal(h, global, "es_isEntityEnabled", js_isEntityEnabled, 1);+ bindGlobal(h, global, "es_hasInactiveEntities", js_hasInactiveEntities, 0);+ bindGlobal(h, global, "es_activityEpoch", js_activityEpoch, 0);bindGlobal(h, global, "es_hasParent", js_hasParent, 1);bindGlobal(h, global, "es_getParent", js_getParent, 1);bindGlobal(h, global, "es_removeParent", js_removeParent, 1);diff --git a/native/host/bindings/RenderBindings.cpp b/native/host/bindings/RenderBindings.cppindex 9dd01d596..5bfc8441a 100644--- a/native/host/bindings/RenderBindings.cpp+++ b/native/host/bindings/RenderBindings.cpp@@ -158,7 +158,7 @@ JSValue js_registry_getCameraEntities(JSContext* ctx, JSValueConst, int, JSValueif (!hostAlive() || !host().registry) return arr;auto& registry = *host().registry;uint32_t n = 0;- for (auto entity : registry.view<ecs::Camera, ecs::Transform>()) {+ for (auto entity : registry.activeView<ecs::Camera, ecs::Transform>()) {if (registry.get<ecs::Camera>(entity).isActive) {JS_SetPropertyUint32(ctx, arr, n++, JS_NewInt32(ctx, (int32_t)entity.id()));}diff --git a/sdk/etc/dragonbones.api.md b/sdk/etc/dragonbones.api.mdindex dbe6e7df8..852ebe973 100644--- a/sdk/etc/dragonbones.api.md+++ b/sdk/etc/dragonbones.api.md@@ -53,8 +53,8 @@ setEnabled: (entity: Entity, enabled: boolean) => voidsetEntityProps: (entity: Entity, props: Partial<Pick<EntityInfo, "skeletonScale" | "flipX" | "flipY" | "layer" | "playing">> & { timeScale?: number; color?: { r: number; g: number; b: number; a: number; }; }) => voidsetTimeScale: (entity: Entity, scale: number) => voidstop: (entity: Entity, animation?: string) => void-submitMeshes: (core: SkeletalSubmitCore, registry: unknown, materialOf?: SkeletalMaterialOf) => void-updateAnimations: (dt: number) => void+submitMeshes: (core: SkeletalSubmitCore, registry: unknown, materialOf?: SkeletalMaterialOf, isActive?: (entity: Entity) => boolean) => void+updateAnimations: (dt: number, isActive?: (entity: Entity) => boolean) => voidstatic new (controller: DragonBonesModuleController): DragonBonesManagerstatic prototype: DragonBonesManager```diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex e8e9ce04a..173a33f5d 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -733,7 +733,7 @@ writers: readonly { slot: number; event: string; fields: readonly string[]; }[]## App — class @experimental```@internal addBundleSystems: (entries: ReadonlyArray<{ schedule: number; system: SystemDef | SystemSet; }>) => App-@internal connectCpp: (cppRegistry: CppRegistry, module?: ESEngineModule, options?: BridgeConnectOptions) => App+@internal connectCpp: (cppRegistry: CppRegistry, module?: ESEngineModule, options?: BridgeConnectOptions & { ownedRegistry?: boolean; }) => App@internal wasmModule: ESEngineModule | nulladdEvent: <T>(event: EventDef<T>) => AppaddPlugin: (plugin: Plugin) => App@@ -882,6 +882,7 @@ version: string## AssetLease — interface @experimental```+@internal failedDependencies: readonly string[] | undefinedgeneration: numberkey: stringrelease: () => void@@ -972,6 +973,7 @@ ResourceDef<AssetsClass>@internal dependentsOfSource: (ref: string) => AssetIdentity[]@internal entityScopes: EntityAssetScopes@internal handleBoundTypes: () => string[]+@internal preparePrefab: (ref: string, overrides?: readonly PrefabOverride[]) => Promise<PreparedPrefab>@internal publishedRegistryAssets: <T>(type: string) => T[]@internal releaseTextureLease: (lease: AssetRefLease<number>) => void@internal releaseTyped: (type: string, ref: string) => void@@ -1050,6 +1052,7 @@ setRemoteRoot: (url: string | undefined) => voidsetTextureImportSettingsResolver: (resolver: TextureImportSettingsResolver | null) => voidtextureFormatReport: () => TextureFormatReporttexturesAwaitingReupload: () => { handle: number; content: TextureContent; path: string; }[]+trackSceneAssetReferences: (scene: SceneData, entities: ReadonlyMap<number, number>) => voidupdateStatus: () => UpdateStatusstatic create: (options: AssetsOptions) => AssetsClassstatic new (options: AssetsOptions): AssetsClass@@ -1058,6 +1061,7 @@ static prototype: AssetsClass## AsyncCache — class @experimental```+@internal failures: () => Generator<[string, Error]>@internal sizes: () => { cached: number; pending: number; failed: number; }clear: () => voidclearAll: () => void@@ -4966,7 +4970,7 @@ static prototype: MaskReach## Material — const @experimental```-{ createShader(vertexSrc: string, fragmentSrc: string): ShaderHandle; releaseShader(shader: ShaderHandle): void; create(options: MaterialOptions): MaterialHandle; compileShader(esshaderSource: string, features?: string[]): ShaderHandle; getSwitch(material: MaterialHandle, name: string): boolean; setSwitch(material: MaterialHandle, name: string, on: boolean): void; get(material: MaterialHandle): MaterialData | undefined; setUniform(material: MaterialHandle, name: string, value: UniformValue): void; getUniform(material: MaterialHandle, name: string): UniformValue | undefined; setBlendMode(material: MaterialHandle, mode: BlendMode): void; getBlendMode(material: MaterialHandle): BlendMode; setDepthTest(material: MaterialHandle, enabled: boolean): void; setDepthWrite(material: MaterialHandle, enabled: boolean): void; setDepthBias(material: MaterialHandle, units: number): void; setCull(material: MaterialHandle, cull: CullMode): void; getShader(material: MaterialHandle): ShaderHandle; release(material: MaterialHandle): void; isValid(material: MaterialHandle): boolean; renderPreview(material: MaterialHandle, w: number, h: number): Promise<ImageData | null>; releaseAll(): void; createFromAsset(data: MaterialAssetData, shaderHandle: ShaderHandle, parentHandle?: MaterialHandle): MaterialHandle; createInstance(source: MaterialHandle): MaterialHandle; toAssetData(material: MaterialHandle, shaderPath: string, parentPath?: string): MaterialAssetData | null; getUniforms(material: MaterialHandle): Map<string, UniformValue>; tex(textureId: number, slot?: number): TextureRef; }+{ createShader(vertexSrc: string, fragmentSrc: string): ShaderHandle; releaseShader(shader: ShaderHandle): void; create(options: MaterialOptions): MaterialHandle; compileShader(esshaderSource: string, features?: string[]): ShaderHandle; getSwitch(material: MaterialHandle, name: string): boolean; setSwitch(material: MaterialHandle, name: string, on: boolean): void; get(material: MaterialHandle): MaterialData | undefined; getRenderState(material: MaterialHandle): Omit<ResolvedMaterial, "uniforms"> | null; applyState(material: MaterialHandle, state: Omit<MaterialOptions, "shader">): void; setUniform(material: MaterialHandle, name: string, value: UniformValue): void; getUniform(material: MaterialHandle, name: string): UniformValue | undefined; setBlendMode(material: MaterialHandle, mode: BlendMode): void; getBlendMode(material: MaterialHandle): BlendMode; setDepthTest(material: MaterialHandle, enabled: boolean): void; setDepthWrite(material: MaterialHandle, enabled: boolean): void; setDepthBias(material: MaterialHandle, units: number): void; setCull(material: MaterialHandle, cull: CullMode): void; getShader(material: MaterialHandle): ShaderHandle; release(material: MaterialHandle): void; isValid(material: MaterialHandle): boolean; renderPreview(material: MaterialHandle, w: number, h: number): Promise<ImageData | null>; releaseAll(): void; createFromAsset(data: MaterialAssetData, shaderHandle: ShaderHandle, parentHandle?: MaterialHandle): MaterialHandle; createInstance(source: MaterialHandle): MaterialHandle; toAssetData(material: MaterialHandle, shaderPath: string, parentPath?: string): MaterialAssetData | null; getUniforms(material: MaterialHandle): Map<string, UniformValue>; tex(textureId: number, slot?: number): TextureRef; }```## MaterialAssetData — interface @experimental@@ -7741,6 +7745,7 @@ indexCount: numberindices: Uint8Array<ArrayBufferLike>layer: number | undefinedmaterialId: number | undefined+premultipliedColor: boolean | undefinedtextureId: numbertransform: Float32Array<ArrayBufferLike>vertexCount: number@@ -9794,10 +9799,12 @@ tabIndex: number | undefined@internal getWorldVersion: () => number@internal getWrittenEntitiesSince: (component: AnyComponentDef, sinceTick: number) => Entity[]@internal hasCpp: boolean+@internal hasPortableScriptAssetRefs: (component: AnyComponentDef) => boolean@internal invalidateTransformComposition: () => void@internal isAddedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean@internal isChangeTracked: (component: AnyComponentDef) => boolean@internal isChangedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean+@internal isDestructionPending: (entity: Entity) => boolean@internal isIterating: () => boolean@internal layoutEpoch: () => number | null@internal markChanged: (entity: Entity, component: AnyComponentDef) => void@@ -9809,6 +9816,7 @@ tabIndex: number | undefined@internal registerRemovedReaderFrom: (component: AnyComponentDef, retainFromTick: number) => number@internal registerTopologyReaderFrom: (component: AnyComponentDef, retainFromTick: number) => number@internal registerWriteReaderFrom: (component: AnyComponentDef, retainFromTick: number) => number+@internal releaseScriptPools: () => void@internal removedReaderCount: (component: AnyComponentDef) => number@internal resetIterationDepth: () => void@internal resetQueryCacheStats: () => void@@ -9826,7 +9834,7 @@ tabIndex: number | undefined@internal takeCompositionChanges: () => void@internal topologyReaderCount: (component: AnyComponentDef) => number@internal transformEpoch: () => number-@internal useScriptPoolMemory: (memory: PoolMemory) => void+@internal useScriptPoolMemory: (memory: PoolMemory, validateOnly?: boolean) => void@internal writeReaderCount: (component: AnyComponentDef) => numberdespawn: (entity: Entity) => voidentityCount: () => number@@ -9837,6 +9845,7 @@ getComponentTypes: (entity: Entity) => string[]getEntitiesWithComponents: (components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[]) => readonly Entity[]has: (entity: Entity, component: AnyComponentDef) => booleaninsert: <C extends AnyComponentDef>(entity: Entity, component: C, data?: Partial<ComponentData<C>>) => ComponentData<C>+isEntityActive: (entity: Entity) => booleanisStale: (entity: Entity) => booleanonDespawn: (callback: (entity: Entity) => void) => () => voidonSpawn: (callback: (entity: Entity) => void) => () => void@@ -9846,6 +9855,7 @@ set: <C extends AnyComponentDef>(entity: Entity, component: C, data: ComponentDasetParent: (child: Entity, parent: Entity) => voidspawn: (name?: string) => EntitytryGet: <C extends AnyComponentDef>(entity: Entity, component: C) => ComponentData<C> | null+trySetParent: (child: Entity, parent: Entity) => booleanupdate: <C extends AnyComponentDef>(entity: Entity, component: C, edit: (draft: ComponentData<C>) => void) => voidvalid: (entity: Entity) => booleanstatic new (): World@@ -11448,7 +11458,7 @@ InputRouter## inspectableTypes — function @experimental```-(world: World, entity: number): string[]+(world: World, entity: number, includeTransient?: boolean): string[]```## installEditorGrid — function @experimentaldiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex d983f0ed0..e93457eeb 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -733,7 +733,7 @@ writers: readonly { slot: number; event: string; fields: readonly string[]; }[]## App — class @experimental```@internal addBundleSystems: (entries: ReadonlyArray<{ schedule: number; system: SystemDef | SystemSet; }>) => App-@internal connectCpp: (cppRegistry: CppRegistry, module?: ESEngineModule, options?: BridgeConnectOptions) => App+@internal connectCpp: (cppRegistry: CppRegistry, module?: ESEngineModule, options?: BridgeConnectOptions & { ownedRegistry?: boolean; }) => App@internal wasmModule: ESEngineModule | nulladdEvent: <T>(event: EventDef<T>) => AppaddPlugin: (plugin: Plugin) => App@@ -882,6 +882,7 @@ version: string## AssetLease — interface @experimental```+@internal failedDependencies: readonly string[] | undefinedgeneration: numberkey: stringrelease: () => void@@ -972,6 +973,7 @@ ResourceDef<AssetsClass>@internal dependentsOfSource: (ref: string) => AssetIdentity[]@internal entityScopes: EntityAssetScopes@internal handleBoundTypes: () => string[]+@internal preparePrefab: (ref: string, overrides?: readonly PrefabOverride[]) => Promise<PreparedPrefab>@internal publishedRegistryAssets: <T>(type: string) => T[]@internal releaseTextureLease: (lease: AssetRefLease<number>) => void@internal releaseTyped: (type: string, ref: string) => void@@ -1050,6 +1052,7 @@ setRemoteRoot: (url: string | undefined) => voidsetTextureImportSettingsResolver: (resolver: TextureImportSettingsResolver | null) => voidtextureFormatReport: () => TextureFormatReporttexturesAwaitingReupload: () => { handle: number; content: TextureContent; path: string; }[]+trackSceneAssetReferences: (scene: SceneData, entities: ReadonlyMap<number, number>) => voidupdateStatus: () => UpdateStatusstatic create: (options: AssetsOptions) => AssetsClassstatic new (options: AssetsOptions): AssetsClass@@ -1058,6 +1061,7 @@ static prototype: AssetsClass## AsyncCache — class @experimental```+@internal failures: () => Generator<[string, Error]>@internal sizes: () => { cached: number; pending: number; failed: number; }clear: () => voidclearAll: () => void@@ -4974,7 +4978,7 @@ static prototype: MaskReach## Material — const @experimental```-{ createShader(vertexSrc: string, fragmentSrc: string): ShaderHandle; releaseShader(shader: ShaderHandle): void; create(options: MaterialOptions): MaterialHandle; compileShader(esshaderSource: string, features?: string[]): ShaderHandle; getSwitch(material: MaterialHandle, name: string): boolean; setSwitch(material: MaterialHandle, name: string, on: boolean): void; get(material: MaterialHandle): MaterialData | undefined; setUniform(material: MaterialHandle, name: string, value: UniformValue): void; getUniform(material: MaterialHandle, name: string): UniformValue | undefined; setBlendMode(material: MaterialHandle, mode: BlendMode): void; getBlendMode(material: MaterialHandle): BlendMode; setDepthTest(material: MaterialHandle, enabled: boolean): void; setDepthWrite(material: MaterialHandle, enabled: boolean): void; setDepthBias(material: MaterialHandle, units: number): void; setCull(material: MaterialHandle, cull: CullMode): void; getShader(material: MaterialHandle): ShaderHandle; release(material: MaterialHandle): void; isValid(material: MaterialHandle): boolean; renderPreview(material: MaterialHandle, w: number, h: number): Promise<ImageData | null>; releaseAll(): void; createFromAsset(data: MaterialAssetData, shaderHandle: ShaderHandle, parentHandle?: MaterialHandle): MaterialHandle; createInstance(source: MaterialHandle): MaterialHandle; toAssetData(material: MaterialHandle, shaderPath: string, parentPath?: string): MaterialAssetData | null; getUniforms(material: MaterialHandle): Map<string, UniformValue>; tex(textureId: number, slot?: number): TextureRef; }+{ createShader(vertexSrc: string, fragmentSrc: string): ShaderHandle; releaseShader(shader: ShaderHandle): void; create(options: MaterialOptions): MaterialHandle; compileShader(esshaderSource: string, features?: string[]): ShaderHandle; getSwitch(material: MaterialHandle, name: string): boolean; setSwitch(material: MaterialHandle, name: string, on: boolean): void; get(material: MaterialHandle): MaterialData | undefined; getRenderState(material: MaterialHandle): Omit<ResolvedMaterial, "uniforms"> | null; applyState(material: MaterialHandle, state: Omit<MaterialOptions, "shader">): void; setUniform(material: MaterialHandle, name: string, value: UniformValue): void; getUniform(material: MaterialHandle, name: string): UniformValue | undefined; setBlendMode(material: MaterialHandle, mode: BlendMode): void; getBlendMode(material: MaterialHandle): BlendMode; setDepthTest(material: MaterialHandle, enabled: boolean): void; setDepthWrite(material: MaterialHandle, enabled: boolean): void; setDepthBias(material: MaterialHandle, units: number): void; setCull(material: MaterialHandle, cull: CullMode): void; getShader(material: MaterialHandle): ShaderHandle; release(material: MaterialHandle): void; isValid(material: MaterialHandle): boolean; renderPreview(material: MaterialHandle, w: number, h: number): Promise<ImageData | null>; releaseAll(): void; createFromAsset(data: MaterialAssetData, shaderHandle: ShaderHandle, parentHandle?: MaterialHandle): MaterialHandle; createInstance(source: MaterialHandle): MaterialHandle; toAssetData(material: MaterialHandle, shaderPath: string, parentPath?: string): MaterialAssetData | null; getUniforms(material: MaterialHandle): Map<string, UniformValue>; tex(textureId: number, slot?: number): TextureRef; }```## MaterialAssetData — interface @experimental@@ -7942,6 +7946,7 @@ indexCount: numberindices: Uint8Array<ArrayBufferLike>layer: number | undefinedmaterialId: number | undefined+premultipliedColor: boolean | undefinedtextureId: numbertransform: Float32Array<ArrayBufferLike>vertexCount: number@@ -9995,10 +10000,12 @@ tabIndex: number | undefined@internal getWorldVersion: () => number@internal getWrittenEntitiesSince: (component: AnyComponentDef, sinceTick: number) => Entity[]@internal hasCpp: boolean+@internal hasPortableScriptAssetRefs: (component: AnyComponentDef) => boolean@internal invalidateTransformComposition: () => void@internal isAddedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean@internal isChangeTracked: (component: AnyComponentDef) => boolean@internal isChangedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean+@internal isDestructionPending: (entity: Entity) => boolean@internal isIterating: () => boolean@internal layoutEpoch: () => number | null@internal markChanged: (entity: Entity, component: AnyComponentDef) => void@@ -10010,6 +10017,7 @@ tabIndex: number | undefined@internal registerRemovedReaderFrom: (component: AnyComponentDef, retainFromTick: number) => number@internal registerTopologyReaderFrom: (component: AnyComponentDef, retainFromTick: number) => number@internal registerWriteReaderFrom: (component: AnyComponentDef, retainFromTick: number) => number+@internal releaseScriptPools: () => void@internal removedReaderCount: (component: AnyComponentDef) => number@internal resetIterationDepth: () => void@internal resetQueryCacheStats: () => void@@ -10027,7 +10035,7 @@ tabIndex: number | undefined@internal takeCompositionChanges: () => void@internal topologyReaderCount: (component: AnyComponentDef) => number@internal transformEpoch: () => number-@internal useScriptPoolMemory: (memory: PoolMemory) => void+@internal useScriptPoolMemory: (memory: PoolMemory, validateOnly?: boolean) => void@internal writeReaderCount: (component: AnyComponentDef) => numberdespawn: (entity: Entity) => voidentityCount: () => number@@ -10038,6 +10046,7 @@ getComponentTypes: (entity: Entity) => string[]getEntitiesWithComponents: (components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[]) => readonly Entity[]has: (entity: Entity, component: AnyComponentDef) => booleaninsert: <C extends AnyComponentDef>(entity: Entity, component: C, data?: Partial<ComponentData<C>>) => ComponentData<C>+isEntityActive: (entity: Entity) => booleanisStale: (entity: Entity) => booleanonDespawn: (callback: (entity: Entity) => void) => () => voidonSpawn: (callback: (entity: Entity) => void) => () => void@@ -10047,6 +10056,7 @@ set: <C extends AnyComponentDef>(entity: Entity, component: C, data: ComponentDasetParent: (child: Entity, parent: Entity) => voidspawn: (name?: string) => EntitytryGet: <C extends AnyComponentDef>(entity: Entity, component: C) => ComponentData<C> | null+trySetParent: (child: Entity, parent: Entity) => booleanupdate: <C extends AnyComponentDef>(entity: Entity, component: C, edit: (draft: ComponentData<C>) => void) => voidvalid: (entity: Entity) => booleanstatic new (): World@@ -11694,7 +11704,7 @@ InputRouter## inspectableTypes — function @experimental```-(world: World, entity: number): string[]+(world: World, entity: number, includeTransient?: boolean): string[]```## installEditorGrid — function @experimentaldiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 463665f1c..a10f0ceb9 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -728,7 +728,7 @@ writers: readonly { slot: number; event: string; fields: readonly string[]; }[]## App — class @experimental```@internal addBundleSystems: (entries: ReadonlyArray<{ schedule: number; system: SystemDef | SystemSet; }>) => App-@internal connectCpp: (cppRegistry: CppRegistry, module?: ESEngineModule, options?: BridgeConnectOptions) => App+@internal connectCpp: (cppRegistry: CppRegistry, module?: ESEngineModule, options?: BridgeConnectOptions & { ownedRegistry?: boolean; }) => App@internal wasmModule: ESEngineModule | nulladdEvent: <T>(event: EventDef<T>) => AppaddPlugin: (plugin: Plugin) => App@@ -877,6 +877,7 @@ version: string## AssetLease — interface @experimental```+@internal failedDependencies: readonly string[] | undefinedgeneration: numberkey: stringrelease: () => void@@ -967,6 +968,7 @@ ResourceDef<AssetsClass>@internal dependentsOfSource: (ref: string) => AssetIdentity[]@internal entityScopes: EntityAssetScopes@internal handleBoundTypes: () => string[]+@internal preparePrefab: (ref: string, overrides?: readonly PrefabOverride[]) => Promise<PreparedPrefab>@internal publishedRegistryAssets: <T>(type: string) => T[]@internal releaseTextureLease: (lease: AssetRefLease<number>) => void@internal releaseTyped: (type: string, ref: string) => void@@ -1045,6 +1047,7 @@ setRemoteRoot: (url: string | undefined) => voidsetTextureImportSettingsResolver: (resolver: TextureImportSettingsResolver | null) => voidtextureFormatReport: () => TextureFormatReporttexturesAwaitingReupload: () => { handle: number; content: TextureContent; path: string; }[]+trackSceneAssetReferences: (scene: SceneData, entities: ReadonlyMap<number, number>) => voidupdateStatus: () => UpdateStatusstatic create: (options: AssetsOptions) => AssetsClassstatic new (options: AssetsOptions): AssetsClass@@ -1053,6 +1056,7 @@ static prototype: AssetsClass## AsyncCache — class @experimental```+@internal failures: () => Generator<[string, Error]>@internal sizes: () => { cached: number; pending: number; failed: number; }clear: () => voidclearAll: () => void@@ -4961,7 +4965,7 @@ static prototype: MaskReach## Material — const @experimental```-{ createShader(vertexSrc: string, fragmentSrc: string): ShaderHandle; releaseShader(shader: ShaderHandle): void; create(options: MaterialOptions): MaterialHandle; compileShader(esshaderSource: string, features?: string[]): ShaderHandle; getSwitch(material: MaterialHandle, name: string): boolean; setSwitch(material: MaterialHandle, name: string, on: boolean): void; get(material: MaterialHandle): MaterialData | undefined; setUniform(material: MaterialHandle, name: string, value: UniformValue): void; getUniform(material: MaterialHandle, name: string): UniformValue | undefined; setBlendMode(material: MaterialHandle, mode: BlendMode): void; getBlendMode(material: MaterialHandle): BlendMode; setDepthTest(material: MaterialHandle, enabled: boolean): void; setDepthWrite(material: MaterialHandle, enabled: boolean): void; setDepthBias(material: MaterialHandle, units: number): void; setCull(material: MaterialHandle, cull: CullMode): void; getShader(material: MaterialHandle): ShaderHandle; release(material: MaterialHandle): void; isValid(material: MaterialHandle): boolean; renderPreview(material: MaterialHandle, w: number, h: number): Promise<ImageData | null>; releaseAll(): void; createFromAsset(data: MaterialAssetData, shaderHandle: ShaderHandle, parentHandle?: MaterialHandle): MaterialHandle; createInstance(source: MaterialHandle): MaterialHandle; toAssetData(material: MaterialHandle, shaderPath: string, parentPath?: string): MaterialAssetData | null; getUniforms(material: MaterialHandle): Map<string, UniformValue>; tex(textureId: number, slot?: number): TextureRef; }+{ createShader(vertexSrc: string, fragmentSrc: string): ShaderHandle; releaseShader(shader: ShaderHandle): void; create(options: MaterialOptions): MaterialHandle; compileShader(esshaderSource: string, features?: string[]): ShaderHandle; getSwitch(material: MaterialHandle, name: string): boolean; setSwitch(material: MaterialHandle, name: string, on: boolean): void; get(material: MaterialHandle): MaterialData | undefined; getRenderState(material: MaterialHandle): Omit<ResolvedMaterial, "uniforms"> | null; applyState(material: MaterialHandle, state: Omit<MaterialOptions, "shader">): void; setUniform(material: MaterialHandle, name: string, value: UniformValue): void; getUniform(material: MaterialHandle, name: string): UniformValue | undefined; setBlendMode(material: MaterialHandle, mode: BlendMode): void; getBlendMode(material: MaterialHandle): BlendMode; setDepthTest(material: MaterialHandle, enabled: boolean): void; setDepthWrite(material: MaterialHandle, enabled: boolean): void; setDepthBias(material: MaterialHandle, units: number): void; setCull(material: MaterialHandle, cull: CullMode): void; getShader(material: MaterialHandle): ShaderHandle; release(material: MaterialHandle): void; isValid(material: MaterialHandle): boolean; renderPreview(material: MaterialHandle, w: number, h: number): Promise<ImageData | null>; releaseAll(): void; createFromAsset(data: MaterialAssetData, shaderHandle: ShaderHandle, parentHandle?: MaterialHandle): MaterialHandle; createInstance(source: MaterialHandle): MaterialHandle; toAssetData(material: MaterialHandle, shaderPath: string, parentPath?: string): MaterialAssetData | null; getUniforms(material: MaterialHandle): Map<string, UniformValue>; tex(textureId: number, slot?: number): TextureRef; }```## MaterialAssetData — interface @experimental@@ -7736,6 +7740,7 @@ indexCount: numberindices: Uint8Array<ArrayBufferLike>layer: number | undefinedmaterialId: number | undefined+premultipliedColor: boolean | undefinedtextureId: numbertransform: Float32Array<ArrayBufferLike>vertexCount: number@@ -9789,10 +9794,12 @@ tabIndex: number | undefined@internal getWorldVersion: () => number@internal getWrittenEntitiesSince: (component: AnyComponentDef, sinceTick: number) => Entity[]@internal hasCpp: boolean+@internal hasPortableScriptAssetRefs: (component: AnyComponentDef) => boolean@internal invalidateTransformComposition: () => void@internal isAddedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean@internal isChangeTracked: (component: AnyComponentDef) => boolean@internal isChangedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean+@internal isDestructionPending: (entity: Entity) => boolean@internal isIterating: () => boolean@internal layoutEpoch: () => number | null@internal markChanged: (entity: Entity, component: AnyComponentDef) => void@@ -9804,6 +9811,7 @@ tabIndex: number | undefined@internal registerRemovedReaderFrom: (component: AnyComponentDef, retainFromTick: number) => number@internal registerTopologyReaderFrom: (component: AnyComponentDef, retainFromTick: number) => number@internal registerWriteReaderFrom: (component: AnyComponentDef, retainFromTick: number) => number+@internal releaseScriptPools: () => void@internal removedReaderCount: (component: AnyComponentDef) => number@internal resetIterationDepth: () => void@internal resetQueryCacheStats: () => void@@ -9821,7 +9829,7 @@ tabIndex: number | undefined@internal takeCompositionChanges: () => void@internal topologyReaderCount: (component: AnyComponentDef) => number@internal transformEpoch: () => number-@internal useScriptPoolMemory: (memory: PoolMemory) => void+@internal useScriptPoolMemory: (memory: PoolMemory, validateOnly?: boolean) => void@internal writeReaderCount: (component: AnyComponentDef) => numberdespawn: (entity: Entity) => voidentityCount: () => number@@ -9832,6 +9840,7 @@ getComponentTypes: (entity: Entity) => string[]getEntitiesWithComponents: (components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[]) => readonly Entity[]has: (entity: Entity, component: AnyComponentDef) => booleaninsert: <C extends AnyComponentDef>(entity: Entity, component: C, data?: Partial<ComponentData<C>>) => ComponentData<C>+isEntityActive: (entity: Entity) => booleanisStale: (entity: Entity) => booleanonDespawn: (callback: (entity: Entity) => void) => () => voidonSpawn: (callback: (entity: Entity) => void) => () => void@@ -9841,6 +9850,7 @@ set: <C extends AnyComponentDef>(entity: Entity, component: C, data: ComponentDasetParent: (child: Entity, parent: Entity) => voidspawn: (name?: string) => EntitytryGet: <C extends AnyComponentDef>(entity: Entity, component: C) => ComponentData<C> | null+trySetParent: (child: Entity, parent: Entity) => booleanupdate: <C extends AnyComponentDef>(entity: Entity, component: C, edit: (draft: ComponentData<C>) => void) => voidvalid: (entity: Entity) => booleanstatic new (): World@@ -11443,7 +11453,7 @@ InputRouter## inspectableTypes — function @experimental```-(world: World, entity: number): string[]+(world: World, entity: number, includeTransient?: boolean): string[]```## installEditorGrid — function @experimentaldiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 02add0c88..4b4575fb5 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -728,7 +728,7 @@ writers: readonly { slot: number; event: string; fields: readonly string[]; }[]## App — class @experimental```@internal addBundleSystems: (entries: ReadonlyArray<{ schedule: number; system: SystemDef | SystemSet; }>) => App-@internal connectCpp: (cppRegistry: CppRegistry, module?: ESEngineModule, options?: BridgeConnectOptions) => App+@internal connectCpp: (cppRegistry: CppRegistry, module?: ESEngineModule, options?: BridgeConnectOptions & { ownedRegistry?: boolean; }) => App@internal wasmModule: ESEngineModule | nulladdEvent: <T>(event: EventDef<T>) => AppaddPlugin: (plugin: Plugin) => App@@ -877,6 +877,7 @@ version: string## AssetLease — interface @experimental```+@internal failedDependencies: readonly string[] | undefinedgeneration: numberkey: stringrelease: () => void@@ -967,6 +968,7 @@ ResourceDef<AssetsClass>@internal dependentsOfSource: (ref: string) => AssetIdentity[]@internal entityScopes: EntityAssetScopes@internal handleBoundTypes: () => string[]+@internal preparePrefab: (ref: string, overrides?: readonly PrefabOverride[]) => Promise<PreparedPrefab>@internal publishedRegistryAssets: <T>(type: string) => T[]@internal releaseTextureLease: (lease: AssetRefLease<number>) => void@internal releaseTyped: (type: string, ref: string) => void@@ -1045,6 +1047,7 @@ setRemoteRoot: (url: string | undefined) => voidsetTextureImportSettingsResolver: (resolver: TextureImportSettingsResolver | null) => voidtextureFormatReport: () => TextureFormatReporttexturesAwaitingReupload: () => { handle: number; content: TextureContent; path: string; }[]+trackSceneAssetReferences: (scene: SceneData, entities: ReadonlyMap<number, number>) => voidupdateStatus: () => UpdateStatusstatic create: (options: AssetsOptions) => AssetsClassstatic new (options: AssetsOptions): AssetsClass@@ -1053,6 +1056,7 @@ static prototype: AssetsClass## AsyncCache — class @experimental```+@internal failures: () => Generator<[string, Error]>@internal sizes: () => { cached: number; pending: number; failed: number; }clear: () => voidclearAll: () => void@@ -4961,7 +4965,7 @@ static prototype: MaskReach## Material — const @experimental```-{ createShader(vertexSrc: string, fragmentSrc: string): ShaderHandle; releaseShader(shader: ShaderHandle): void; create(options: MaterialOptions): MaterialHandle; compileShader(esshaderSource: string, features?: string[]): ShaderHandle; getSwitch(material: MaterialHandle, name: string): boolean; setSwitch(material: MaterialHandle, name: string, on: boolean): void; get(material: MaterialHandle): MaterialData | undefined; setUniform(material: MaterialHandle, name: string, value: UniformValue): void; getUniform(material: MaterialHandle, name: string): UniformValue | undefined; setBlendMode(material: MaterialHandle, mode: BlendMode): void; getBlendMode(material: MaterialHandle): BlendMode; setDepthTest(material: MaterialHandle, enabled: boolean): void; setDepthWrite(material: MaterialHandle, enabled: boolean): void; setDepthBias(material: MaterialHandle, units: number): void; setCull(material: MaterialHandle, cull: CullMode): void; getShader(material: MaterialHandle): ShaderHandle; release(material: MaterialHandle): void; isValid(material: MaterialHandle): boolean; renderPreview(material: MaterialHandle, w: number, h: number): Promise<ImageData | null>; releaseAll(): void; createFromAsset(data: MaterialAssetData, shaderHandle: ShaderHandle, parentHandle?: MaterialHandle): MaterialHandle; createInstance(source: MaterialHandle): MaterialHandle; toAssetData(material: MaterialHandle, shaderPath: string, parentPath?: string): MaterialAssetData | null; getUniforms(material: MaterialHandle): Map<string, UniformValue>; tex(textureId: number, slot?: number): TextureRef; }+{ createShader(vertexSrc: string, fragmentSrc: string): ShaderHandle; releaseShader(shader: ShaderHandle): void; create(options: MaterialOptions): MaterialHandle; compileShader(esshaderSource: string, features?: string[]): ShaderHandle; getSwitch(material: MaterialHandle, name: string): boolean; setSwitch(material: MaterialHandle, name: string, on: boolean): void; get(material: MaterialHandle): MaterialData | undefined; getRenderState(material: MaterialHandle): Omit<ResolvedMaterial, "uniforms"> | null; applyState(material: MaterialHandle, state: Omit<MaterialOptions, "shader">): void; setUniform(material: MaterialHandle, name: string, value: UniformValue): void; getUniform(material: MaterialHandle, name: string): UniformValue | undefined; setBlendMode(material: MaterialHandle, mode: BlendMode): void; getBlendMode(material: MaterialHandle): BlendMode; setDepthTest(material: MaterialHandle, enabled: boolean): void; setDepthWrite(material: MaterialHandle, enabled: boolean): void; setDepthBias(material: MaterialHandle, units: number): void; setCull(material: MaterialHandle, cull: CullMode): void; getShader(material: MaterialHandle): ShaderHandle; release(material: MaterialHandle): void; isValid(material: MaterialHandle): boolean; renderPreview(material: MaterialHandle, w: number, h: number): Promise<ImageData | null>; releaseAll(): void; createFromAsset(data: MaterialAssetData, shaderHandle: ShaderHandle, parentHandle?: MaterialHandle): MaterialHandle; createInstance(source: MaterialHandle): MaterialHandle; toAssetData(material: MaterialHandle, shaderPath: string, parentPath?: string): MaterialAssetData | null; getUniforms(material: MaterialHandle): Map<string, UniformValue>; tex(textureId: number, slot?: number): TextureRef; }```## MaterialAssetData — interface @experimental@@ -8009,6 +8013,7 @@ indexCount: numberindices: Uint8Array<ArrayBufferLike>layer: number | undefinedmaterialId: number | undefined+premultipliedColor: boolean | undefinedtextureId: numbertransform: Float32Array<ArrayBufferLike>vertexCount: number@@ -10068,10 +10073,12 @@ tabIndex: number | undefined@internal getWorldVersion: () => number@internal getWrittenEntitiesSince: (component: AnyComponentDef, sinceTick: number) => Entity[]@internal hasCpp: boolean+@internal hasPortableScriptAssetRefs: (component: AnyComponentDef) => boolean@internal invalidateTransformComposition: () => void@internal isAddedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean@internal isChangeTracked: (component: AnyComponentDef) => boolean@internal isChangedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean+@internal isDestructionPending: (entity: Entity) => boolean@internal isIterating: () => boolean@internal layoutEpoch: () => number | null@internal markChanged: (entity: Entity, component: AnyComponentDef) => void@@ -10083,6 +10090,7 @@ tabIndex: number | undefined@internal registerRemovedReaderFrom: (component: AnyComponentDef, retainFromTick: number) => number@internal registerTopologyReaderFrom: (component: AnyComponentDef, retainFromTick: number) => number@internal registerWriteReaderFrom: (component: AnyComponentDef, retainFromTick: number) => number+@internal releaseScriptPools: () => void@internal removedReaderCount: (component: AnyComponentDef) => number@internal resetIterationDepth: () => void@internal resetQueryCacheStats: () => void@@ -10100,7 +10108,7 @@ tabIndex: number | undefined@internal takeCompositionChanges: () => void@internal topologyReaderCount: (component: AnyComponentDef) => number@internal transformEpoch: () => number-@internal useScriptPoolMemory: (memory: PoolMemory) => void+@internal useScriptPoolMemory: (memory: PoolMemory, validateOnly?: boolean) => void@internal writeReaderCount: (component: AnyComponentDef) => numberdespawn: (entity: Entity) => voidentityCount: () => number@@ -10111,6 +10119,7 @@ getComponentTypes: (entity: Entity) => string[]getEntitiesWithComponents: (components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[]) => readonly Entity[]has: (entity: Entity, component: AnyComponentDef) => booleaninsert: <C extends AnyComponentDef>(entity: Entity, component: C, data?: Partial<ComponentData<C>>) => ComponentData<C>+isEntityActive: (entity: Entity) => booleanisStale: (entity: Entity) => booleanonDespawn: (callback: (entity: Entity) => void) => () => voidonSpawn: (callback: (entity: Entity) => void) => () => void@@ -10120,6 +10129,7 @@ set: <C extends AnyComponentDef>(entity: Entity, component: C, data: ComponentDasetParent: (child: Entity, parent: Entity) => voidspawn: (name?: string) => EntitytryGet: <C extends AnyComponentDef>(entity: Entity, component: C) => ComponentData<C> | null+trySetParent: (child: Entity, parent: Entity) => booleanupdate: <C extends AnyComponentDef>(entity: Entity, component: C, edit: (draft: ComponentData<C>) => void) => voidvalid: (entity: Entity) => booleanstatic new (): World@@ -11732,7 +11742,7 @@ InputRouter## inspectableTypes — function @experimental```-(world: World, entity: number): string[]+(world: World, entity: number, includeTransient?: boolean): string[]```## installEditorGrid — function @experimentaldiff --git a/sdk/etc/spine.api.md b/sdk/etc/spine.api.mdindex 6839f691c..ecf182a94 100644--- a/sdk/etc/spine.api.md+++ b/sdk/etc/spine.api.md@@ -177,7 +177,7 @@ entities: number```boundEntities: () => Iterable<Entity>clipBudget: (entity: Entity) => SpineClipBudget | null-collectAllEvents: () => { entity: Entity; raw: RawSpineEvent; }[]+collectAllEvents: (isActive?: (entity: Entity) => boolean) => { entity: Entity; raw: RawSpineEvent; }[]diagnostics: () => SpineSceneDiagnosticsdispose: () => voidenableEvents: (entity: Entity) => void@@ -208,8 +208,8 @@ setSkin: (entity: Entity, skin: string) => voidsetSlotColor: (entity: Entity, slotName: string, r: number, g: number, b: number, a: number) => booleansetTrackAlpha: (entity: Entity, track: number, alpha: number) => voidsetTransformConstraintMix: (entity: Entity, name: string, mix: TransformMixData) => boolean-submitMeshes: (registry: CppRegistry, materialOf?: SkeletalMaterialOf) => void-updateAnimations: (dt: number) => void+submitMeshes: (registry: CppRegistry, materialOf?: SkeletalMaterialOf, isActive?: (entity: Entity) => boolean) => void+updateAnimations: (dt: number, isActive?: (entity: Entity) => boolean) => voidstatic detectVersion: (data: Uint8Array) => SpineVersion | nullstatic detectVersionJson: (json: string) => SpineVersion | nullstatic new (coreModule: NonNullable<EngineApi>, moduleFactories: Map<SpineVersion, SpineModuleFactory>): SpineManager@@ -320,12 +320,12 @@ requiresContinuousWorldPose: boolean## SpineRuntime — class @experimental```clipBudget: (entity: Entity) => SpineClipBudget | null-collectAllEvents: () => { entity: Entity; raw: RawSpineEvent; }[]+collectAllEvents: (isActive?: (entity: Entity) => boolean) => { entity: Entity; raw: RawSpineEvent; }[]dispose: () => voidenableEvents: (entity: Entity) => voidensurePose: (entity: Entity) => booleanentityCount: number-extractAndSubmitMeshes: (core: NonNullable<EngineApi>, registry: CppRegistry, materialOf?: SkeletalMaterialOf) => void+extractAndSubmitMeshes: (core: NonNullable<EngineApi>, registry: CppRegistry, materialOf?: SkeletalMaterialOf, isActive?: (entity: Entity) => boolean) => voidgetAnimations: (entity: Entity) => string[]getBounds: (entity: Entity) => { x: number; y: number; width: number; height: number; } | nullgetPathConstraintMix: (entity: Entity, name: string) => PathMixData | null@@ -353,7 +353,7 @@ setSkin: (entity: Entity, skin: string) => voidsetSlotColor: (entity: Entity, slotName: string, r: number, g: number, b: number, a: number) => booleansetTrackAlpha: (entity: Entity, track: number, alpha: number) => voidsetTransformConstraintMix: (entity: Entity, name: string, mix: TransformMixData) => boolean-updateAll: (dt: number) => void+updateAll: (dt: number, isActive?: (entity: Entity) => boolean) => voidversion: SpineVersionwindows: () => { pose: SpineTimeWindow; readback: SpineTimeWindow; total: SpineTimeWindow; }worldPoseDebt: () => numberdiff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.mdindex 8f1f0c601..593216089 100644--- a/sdk/etc/wasm.api.md+++ b/sdk/etc/wasm.api.md@@ -13,6 +13,7 @@ shutdown: () => void## CppRegistry — interface @experimental```+activityEpoch: (() => number) | undefinedaddBitmapText: (entity: Entity, component: BitmapText) => voidaddBoxCollider2D: (entity: Entity, component: BoxCollider2D) => voidaddBoxCollider3D: (entity: Entity, component: BoxCollider3D) => void@@ -63,6 +64,7 @@ addVelocity: (entity: Entity, component: Velocity) => voidcreate: () => Entitydelete: () => voiddestroy: (entity: Entity) => void+destructionPending: ((entity: Entity) => boolean) | undefinedentityCount: () => numbergetBitmapText: (entity: Entity) => BitmapTextgetBoxCollider2D: (entity: Entity) => BoxCollider2D@@ -125,6 +127,7 @@ hasConvexCollider3D: (entity: Entity) => booleanhasDraggable: (entity: Entity) => booleanhasDragonBonesAnimation: (entity: Entity) => booleanhasFlexContainer: (entity: Entity) => boolean+hasInactiveEntities: (() => boolean) | undefinedhasInteractable: (entity: Entity) => booleanhasLODGroup: (entity: Entity) => booleanhasLight: (entity: Entity) => boolean@@ -158,7 +161,10 @@ hasUINode: (entity: Entity) => booleanhasUIScroll: (entity: Entity) => booleanhasUIVisual: (entity: Entity) => booleanhasVelocity: (entity: Entity) => boolean+isEntityActive: ((entity: Entity) => boolean) | undefined+isEntityEnabled: ((entity: Entity) => boolean) | undefinedlayoutEpoch: (() => number) | undefined+releaseDestruction: ((entity: Entity) => void) | undefinedremoveBitmapText: (entity: Entity) => voidremoveBoxCollider2D: (entity: Entity) => voidremoveBoxCollider3D: (entity: Entity) => void@@ -206,7 +212,9 @@ removeUINode: (entity: Entity) => voidremoveUIScroll: (entity: Entity) => voidremoveUIVisual: (entity: Entity) => voidremoveVelocity: (entity: Entity) => void-setParent: (child: Entity, parent: Entity) => void+reserveDestruction: ((entity: Entity) => boolean) | undefined+setEntityEnabled: ((entity: Entity, enabled: boolean) => boolean) | undefined+setParent: (child: Entity, parent: Entity) => boolean | voidvalid: (entity: Entity) => boolean```@@ -331,7 +339,7 @@ getUINodeHiddenInTree: ((registry: CppRegistry, entity: number) => boolean) | ungetVelocityPtr: (registry: CppRegistry, entity: number) => numbergl_checkErrors: (context: string) => numbergl_enableErrorCheck: (enabled: boolean) => void-initRenderer: () => void+initRenderer: () => booleaninitRendererWebGPU: (canvasSelector: string, width: number, height: number, readback: boolean, preferBGRA: boolean) => booleaninitRendererWithContext: (contextHandle: number) => booleanmaterial_compileEsshader: (source: string, featuresCsv: string) => number@@ -474,7 +482,9 @@ renderer_snapshotMatchesCapture: () => booleanrenderer_submitAll: (registry: CppRegistry, vpX: number, vpY: number, vpW: number, vpH: number) => voidrenderer_submitScreenOverlay: ((registry: CppRegistry) => void) | undefinedrenderer_submitSkeletalBatchByEntity: ((registry: CppRegistry, verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, blendMode: number, entity: number, skelScale: number, flipX: boolean, flipY: boolean, layer: number, depth: number, materialId: number) => void) | undefined+renderer_submitSkeletalBatchByEntityEx: ((registry: CppRegistry, verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, blendMode: number, entity: number, skelScale: number, flipX: boolean, flipY: boolean, layer: number, depth: number, materialId: number, premultipliedColor: boolean) => void) | undefinedrenderer_submitSkeletalPreviewBatch: (preview: number, verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, blendMode: number, transformPtr: number, layer: number, depth: number, materialId: number) => number+renderer_submitSkeletalPreviewBatchEx: (preview: number, verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, blendMode: number, transformPtr: number, layer: number, depth: number, materialId: number, premultipliedColor: boolean) => numberrenderer_submitTextBatch: ((verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, transformPtr: number, entity: number, layer: number, depth: number, sdf: number, cullBit: number) => void) | undefinedrenderer_takeFrameCapture: ((handle: number, dest: number, destSize: number) => boolean) | undefinedrenderer_updateTransforms: (registry: CppRegistry) => voiddiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 0eb7c6ac8..eaa2d115f 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -728,7 +728,7 @@ writers: readonly { slot: number; event: string; fields: readonly string[]; }[]## App — class @experimental```@internal addBundleSystems: (entries: ReadonlyArray<{ schedule: number; system: SystemDef | SystemSet; }>) => App-@internal connectCpp: (cppRegistry: CppRegistry, module?: ESEngineModule, options?: BridgeConnectOptions) => App+@internal connectCpp: (cppRegistry: CppRegistry, module?: ESEngineModule, options?: BridgeConnectOptions & { ownedRegistry?: boolean; }) => App@internal wasmModule: ESEngineModule | nulladdEvent: <T>(event: EventDef<T>) => AppaddPlugin: (plugin: Plugin) => App@@ -877,6 +877,7 @@ version: string## AssetLease — interface @experimental```+@internal failedDependencies: readonly string[] | undefinedgeneration: numberkey: stringrelease: () => void@@ -967,6 +968,7 @@ ResourceDef<AssetsClass>@internal dependentsOfSource: (ref: string) => AssetIdentity[]@internal entityScopes: EntityAssetScopes@internal handleBoundTypes: () => string[]+@internal preparePrefab: (ref: string, overrides?: readonly PrefabOverride[]) => Promise<PreparedPrefab>@internal publishedRegistryAssets: <T>(type: string) => T[]@internal releaseTextureLease: (lease: AssetRefLease<number>) => void@internal releaseTyped: (type: string, ref: string) => void@@ -1045,6 +1047,7 @@ setRemoteRoot: (url: string | undefined) => voidsetTextureImportSettingsResolver: (resolver: TextureImportSettingsResolver | null) => voidtextureFormatReport: () => TextureFormatReporttexturesAwaitingReupload: () => { handle: number; content: TextureContent; path: string; }[]+trackSceneAssetReferences: (scene: SceneData, entities: ReadonlyMap<number, number>) => voidupdateStatus: () => UpdateStatusstatic create: (options: AssetsOptions) => AssetsClassstatic new (options: AssetsOptions): AssetsClass@@ -1053,6 +1056,7 @@ static prototype: AssetsClass## AsyncCache — class @experimental```+@internal failures: () => Generator<[string, Error]>@internal sizes: () => { cached: number; pending: number; failed: number; }clear: () => voidclearAll: () => void@@ -4968,7 +4972,7 @@ static prototype: MaskReach## Material — const @experimental```-{ createShader(vertexSrc: string, fragmentSrc: string): ShaderHandle; releaseShader(shader: ShaderHandle): void; create(options: MaterialOptions): MaterialHandle; compileShader(esshaderSource: string, features?: string[]): ShaderHandle; getSwitch(material: MaterialHandle, name: string): boolean; setSwitch(material: MaterialHandle, name: string, on: boolean): void; get(material: MaterialHandle): MaterialData | undefined; setUniform(material: MaterialHandle, name: string, value: UniformValue): void; getUniform(material: MaterialHandle, name: string): UniformValue | undefined; setBlendMode(material: MaterialHandle, mode: BlendMode): void; getBlendMode(material: MaterialHandle): BlendMode; setDepthTest(material: MaterialHandle, enabled: boolean): void; setDepthWrite(material: MaterialHandle, enabled: boolean): void; setDepthBias(material: MaterialHandle, units: number): void; setCull(material: MaterialHandle, cull: CullMode): void; getShader(material: MaterialHandle): ShaderHandle; release(material: MaterialHandle): void; isValid(material: MaterialHandle): boolean; renderPreview(material: MaterialHandle, w: number, h: number): Promise<ImageData | null>; releaseAll(): void; createFromAsset(data: MaterialAssetData, shaderHandle: ShaderHandle, parentHandle?: MaterialHandle): MaterialHandle; createInstance(source: MaterialHandle): MaterialHandle; toAssetData(material: MaterialHandle, shaderPath: string, parentPath?: string): MaterialAssetData | null; getUniforms(material: MaterialHandle): Map<string, UniformValue>; tex(textureId: number, slot?: number): TextureRef; }+{ createShader(vertexSrc: string, fragmentSrc: string): ShaderHandle; releaseShader(shader: ShaderHandle): void; create(options: MaterialOptions): MaterialHandle; compileShader(esshaderSource: string, features?: string[]): ShaderHandle; getSwitch(material: MaterialHandle, name: string): boolean; setSwitch(material: MaterialHandle, name: string, on: boolean): void; get(material: MaterialHandle): MaterialData | undefined; getRenderState(material: MaterialHandle): Omit<ResolvedMaterial, "uniforms"> | null; applyState(material: MaterialHandle, state: Omit<MaterialOptions, "shader">): void; setUniform(material: MaterialHandle, name: string, value: UniformValue): void; getUniform(material: MaterialHandle, name: string): UniformValue | undefined; setBlendMode(material: MaterialHandle, mode: BlendMode): void; getBlendMode(material: MaterialHandle): BlendMode; setDepthTest(material: MaterialHandle, enabled: boolean): void; setDepthWrite(material: MaterialHandle, enabled: boolean): void; setDepthBias(material: MaterialHandle, units: number): void; setCull(material: MaterialHandle, cull: CullMode): void; getShader(material: MaterialHandle): ShaderHandle; release(material: MaterialHandle): void; isValid(material: MaterialHandle): boolean; renderPreview(material: MaterialHandle, w: number, h: number): Promise<ImageData | null>; releaseAll(): void; createFromAsset(data: MaterialAssetData, shaderHandle: ShaderHandle, parentHandle?: MaterialHandle): MaterialHandle; createInstance(source: MaterialHandle): MaterialHandle; toAssetData(material: MaterialHandle, shaderPath: string, parentPath?: string): MaterialAssetData | null; getUniforms(material: MaterialHandle): Map<string, UniformValue>; tex(textureId: number, slot?: number): TextureRef; }```## MaterialAssetData — interface @experimental@@ -7743,6 +7747,7 @@ indexCount: numberindices: Uint8Array<ArrayBufferLike>layer: number | undefinedmaterialId: number | undefined+premultipliedColor: boolean | undefinedtextureId: numbertransform: Float32Array<ArrayBufferLike>vertexCount: number@@ -9820,10 +9825,12 @@ tabIndex: number | undefined@internal getWorldVersion: () => number@internal getWrittenEntitiesSince: (component: AnyComponentDef, sinceTick: number) => Entity[]@internal hasCpp: boolean+@internal hasPortableScriptAssetRefs: (component: AnyComponentDef) => boolean@internal invalidateTransformComposition: () => void@internal isAddedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean@internal isChangeTracked: (component: AnyComponentDef) => boolean@internal isChangedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean+@internal isDestructionPending: (entity: Entity) => boolean@internal isIterating: () => boolean@internal layoutEpoch: () => number | null@internal markChanged: (entity: Entity, component: AnyComponentDef) => void@@ -9835,6 +9842,7 @@ tabIndex: number | undefined@internal registerRemovedReaderFrom: (component: AnyComponentDef, retainFromTick: number) => number@internal registerTopologyReaderFrom: (component: AnyComponentDef, retainFromTick: number) => number@internal registerWriteReaderFrom: (component: AnyComponentDef, retainFromTick: number) => number+@internal releaseScriptPools: () => void@internal removedReaderCount: (component: AnyComponentDef) => number@internal resetIterationDepth: () => void@internal resetQueryCacheStats: () => void@@ -9852,7 +9860,7 @@ tabIndex: number | undefined@internal takeCompositionChanges: () => void@internal topologyReaderCount: (component: AnyComponentDef) => number@internal transformEpoch: () => number-@internal useScriptPoolMemory: (memory: PoolMemory) => void+@internal useScriptPoolMemory: (memory: PoolMemory, validateOnly?: boolean) => void@internal writeReaderCount: (component: AnyComponentDef) => numberdespawn: (entity: Entity) => voidentityCount: () => number@@ -9863,6 +9871,7 @@ getComponentTypes: (entity: Entity) => string[]getEntitiesWithComponents: (components: AnyComponentDef[], withFilters?: AnyComponentDef[], withoutFilters?: AnyComponentDef[]) => readonly Entity[]has: (entity: Entity, component: AnyComponentDef) => booleaninsert: <C extends AnyComponentDef>(entity: Entity, component: C, data?: Partial<ComponentData<C>>) => ComponentData<C>+isEntityActive: (entity: Entity) => booleanisStale: (entity: Entity) => booleanonDespawn: (callback: (entity: Entity) => void) => () => voidonSpawn: (callback: (entity: Entity) => void) => () => void@@ -9872,6 +9881,7 @@ set: <C extends AnyComponentDef>(entity: Entity, component: C, data: ComponentDasetParent: (child: Entity, parent: Entity) => voidspawn: (name?: string) => EntitytryGet: <C extends AnyComponentDef>(entity: Entity, component: C) => ComponentData<C> | null+trySetParent: (child: Entity, parent: Entity) => booleanupdate: <C extends AnyComponentDef>(entity: Entity, component: C, edit: (draft: ComponentData<C>) => void) => voidvalid: (entity: Entity) => booleanstatic new (): World@@ -11484,7 +11494,7 @@ InputRouter## inspectableTypes — function @experimental```-(world: World, entity: number): string[]+(world: World, entity: number, includeTransient?: boolean): string[]```## installEditorGrid — function @experimentaldiff --git a/sdk/src/app/app.ts b/sdk/src/app/app.tsindex bb01bb9a8..67d316f8c 100644--- a/sdk/src/app/app.ts+++ b/sdk/src/app/app.ts@@ -11,7 +11,7 @@ import type { QualityConfig } from '../render/quality';import { Schedule, SystemDef, SystemRunner, SystemSet, mergeOrderingEdges, rescopeSystem, type RunCondition } from '../ecs/system';import { builtinResource, declaredResource, ResourceStorage, Time, TimeData, type ResourceDef } from '../ecs/resource';import { Speculation, SpeculationInstance } from '../ecs/speculation';-import { installAot, prepareAot, type AotHost } from '../ecs/aot/installAot';+import { prepareAot, type AotHost } from '../ecs/aot/installAot';import { installNativeAot, nativeAotBindings } from '../ecs/aot/installNativeAot';import { createNativeHeap } from '../ecs/bridge/nativeHeap';import type { AotManifest } from '../ecs/aot/AotSystems';@@ -71,6 +71,8 @@ export interface Plugin {profileDomain?: string;build(app: App): void;finish?(app: App): void;+ /** Releases acquired resources on quit or a failed build; must tolerate a+ * partially completed build. */cleanup?(app?: App): void;}@@ -169,8 +171,10 @@ export class App {private nextCapFrameAt_ = 0;private module_: ESEngineModule | null = null;+ private ownedCppRegistry_: CppRegistry | null = null;private pipeline_: RenderPipeline | null = null;private spineInitPromise_?: Promise<unknown>;+ private compiledInstallTail_: Promise<void> = Promise.resolve();private readonly installed_plugins_: Plugin[] = [];private readonly installedPluginSet_ = new Set<Plugin>();private readonly installedPluginNames_ = new Set<string>();@@ -181,6 +185,8 @@ export class App {private buildingPlugin_: string | null = null;/** The cost domain of that plugin, which is its name unless it declared one. */private buildingDomain_: string | null = null;+ /** Registration undo actions for the current build; nested builds own theirs. */+ private buildRollback_: Array<() => void> | null = null;private addingBundleSystems_ = false;// The realm's acquirer for optional native modules (physics, spine). Set once// at app creation; physics/spine self-gate off it. Null in headless/test apps.@@ -257,6 +263,7 @@ export class App {}addPlugin(plugin: Plugin): this {+ if (this.quitting_) throw new Error('Cannot install plugins while App.quit is running');if (this.installedPluginSet_.has(plugin)) return this;if (plugin.dependencies) {for (const dep of plugin.dependencies) {@@ -288,6 +295,10 @@ export class App {}const prevBuilding = this.buildingPlugin_;const prevDomain = this.buildingDomain_;+ const prevRollback = this.buildRollback_;+ const rollback: Array<() => void> = [];+ const buildEpoch = this.quitEpoch_;+ this.buildRollback_ = rollback;this.buildingPlugin_ = plugin.name ?? null;this.buildingDomain_ = plugin.profileDomain ?? plugin.name ?? null;try {@@ -297,22 +308,43 @@ export class App {if (plugin.name && this.subsystems_.phaseOf(plugin.name) === 'registered') {this.subsystems_.transition(plugin.name, 'ready');}+ // A child installed inside this build remains provisional until the+ // enclosing build commits. Pre-existing plugins never reach here.+ prevRollback?.push(() => this.rollbackPluginBuild_(plugin, rollback, buildEpoch,+ 'Enclosing plugin build failed'));} catch (e) {- this.installedPluginSet_.delete(plugin);- this.installed_plugins_.pop();- if (plugin.name) {- this.installedPluginNames_.delete(plugin.name);- // Keep the errored (now-uninstalled) entry so the failure stays visible.- this.subsystems_.markError(plugin.name, e instanceof Error ? e.message : String(e));- }+ this.buildRollback_ = null;+ this.rollbackPluginBuild_(plugin, rollback, buildEpoch, e instanceof Error ? e.message : String(e));throw e;} finally {this.buildingPlugin_ = prevBuilding;this.buildingDomain_ = prevDomain;+ this.buildRollback_ = prevRollback;}return this;}+ private rollbackPluginBuild_(plugin: Plugin, rollback: Array<() => void>, epoch: number, reason: string): void {+ this.installedPluginSet_.delete(plugin);+ const index = this.installed_plugins_.indexOf(plugin);+ if (index >= 0) this.installed_plugins_.splice(index, 1);+ if (plugin.name) {+ if (!this.installed_plugins_.some(p => p.name === plugin.name)) this.installedPluginNames_.delete(plugin.name);+ this.subsystems_.markError(plugin.name, reason);+ }+ // Child resources are released before their parent's, matching quit.+ // Withdraw systems even if resource cleanup throws.+ for (let i = rollback.length - 1; i >= 0 && this.quitEpoch_ === epoch; i--) {+ try { rollback[i](); } catch (rollbackError) {+ log.error('app', 'Failed plugin registration rollback error', rollbackError);+ }+ }+ // Already removed above: a cleanup that quits cannot clean this twice.+ try { if (index >= 0) plugin.cleanup?.(this); } catch (cleanupError) {+ log.error('app', 'Failed plugin build cleanup error', cleanupError);+ }+ }+addEvent<T>(event: EventDef<T>): this {this.eventRegistry_.register(event);return this;@@ -368,9 +400,7 @@ export class App {): this {const name = system._name || `System_${++this.systemCounter_}`;const scoped = rescopeSystem(system, name);- this.templateToRuntime_.set(system._id, scoped._id);-- this.scheduleBucket_(schedule, name).push({+ this.registerSystemEntry_(schedule, system._id, {system: scoped,runBefore: mergeOrderingEdges(system._runBefore, options?.runBefore),runAfter: mergeOrderingEdges(system._runAfter, options?.runAfter),@@ -384,6 +414,26 @@ export class App {return this;}+ private registerSystemEntry_(schedule: Schedule, templateId: symbol, entry: SystemEntry): void {+ const bucket = this.scheduleBucket_(schedule, entry.system._name);+ const previous = this.templateToRuntime_.get(templateId);+ this.templateToRuntime_.set(templateId, entry.system._id);+ bucket.push(entry);+ this.buildRollback_?.push(() => {+ const live = this.systems_.get(schedule);+ const index = live?.indexOf(entry) ?? -1;+ if (index >= 0) live!.splice(index, 1);+ this.sortedSystemsCache_.delete(schedule);+ this.dependencyCache_.delete(schedule);+ this.runner_?.evict(entry.system._id);+ // A successful nested plugin may have registered the same template.+ if (this.templateToRuntime_.get(templateId) === entry.system._id) {+ if (previous === undefined) this.templateToRuntime_.delete(templateId);+ else this.templateToRuntime_.set(templateId, previous);+ }+ });+ }+addSystem(system: SystemDef): this {return this.addSystemToSchedule(Schedule.Update, system);}@@ -514,9 +564,7 @@ export class App {// Use the scoped system name the App would generate so ordering// lookups match. Mirrors addSystemToSchedule's naming path.const scoped = rescopeSystem(sys, name);- this.templateToRuntime_.set(sys._id, scoped._id);-- this.scheduleBucket_(schedule, name).push({+ this.registerSystemEntry_(schedule, sys._id, {system: scoped,runBefore: mergedRunBefore,runAfter: mergedRunAfter,@@ -529,7 +577,13 @@ export class App {this.dependencyCache_.delete(schedule);const existing = this.setMembership_.get(set._name);- this.setMembership_.set(set._name, existing ? [...existing, ...members] : members);+ const membership = existing ? [...existing, ...members] : members;+ this.setMembership_.set(set._name, membership);+ this.buildRollback_?.push(() => {+ if (this.setMembership_.get(set._name) !== membership) return;+ if (existing) this.setMembership_.set(set._name, existing);+ else this.setMembership_.delete(set._name);+ });return this;}@@ -565,15 +619,34 @@ export class App {* Bind the app to an engine core. Part of the embedding contract, which is* `esengine/wasm` — a host builds the module and calls this; a game is* handed an App that is already connected.+ * `ownedRegistry` transfers a newly constructed instance to this App after+ * the connection guards pass; failed verification releases it too. Omit+ * it for a registry whose lifetime belongs to the embedding host.** @internal*/connectCpp(cppRegistry: CppRegistry,module?: ESEngineModule,- options?: BridgeConnectOptions,+ options?: BridgeConnectOptions & { ownedRegistry?: boolean },): this {- this.world_.connectCpp(cppRegistry, module, options);+ if (this.quitting_) throw new Error('Cannot connect a registry while App.quit is releasing it');+ if (this.ownedCppRegistry_ && this.ownedCppRegistry_ !== cppRegistry) {+ throw new Error('Quit the App before replacing its owned registry');+ }+ // Factories transfer their newly constructed embind instance here.+ // External connections borrow by default. A failed connection must+ // release the transferred instance, preserving the original diagnostic.+ try { this.world_.connectCpp(cppRegistry, module, options); }+ catch (error) {+ if (options?.ownedRegistry && this.ownedCppRegistry_ !== cppRegistry) {+ this.world_.disconnectCpp();+ try { cppRegistry.delete(); }+ catch (releaseError) { log.warn('app', 'Failed registry connection release error', releaseError); }+ }+ throw error;+ }+ if (options?.ownedRegistry) this.ownedCppRegistry_ = cppRegistry;if (module) {this.module_ = module;@@ -638,42 +711,81 @@ export class App {readonly manifest: AotManifest;readonly wasm: BufferSource;}): Promise<void> {- this.ensureTime_();- this.aot_ = await prepareAot({- world: this.world_,- host: opts.host,- manifest: opts.manifest,- wasm: opts.wasm,- resourceFields: (name) => {- const def = builtinResource(name) ?? this.resources_.getByName(name) ?? declaredResource(name);- if (def === undefined) return undefined;- const value = this.resources_.get(def);- return typeof value === 'object' && value !== null ? Object.keys(value) : [];- },- // A manifest carries event NAMES; the registry answers for the ones- // some system has asked for a reader or a writer of.- events: (name) => {- // Through the DEFINITION, so the bus exists whether or not an- // interpreted system has asked for one yet: a twin sending into- // a bus nobody had made would drop its payloads and say nothing.- const def = eventNamed(name);- if (def === undefined) return undefined;- const bus = this.eventRegistry_.getBus(def);- return { read: () => bus.getReadBuffer(), send: (payload) => bus.send(payload) };- },- resources: (name) => {- // The engine's own by name, and the PROJECT's through the- // storage's own name registry — a compiled system reads either.- const def = builtinResource(name) ?? this.resources_.getByName(name) ?? declaredResource(name);- // `get`, not `has` then `get`: a slot holding a materialised- // default is what an INTERPRETED system reads, and a twin has to- // see the same world or the two stop being the same program.- return def === undefined- ? undefined- : this.resources_.get(def) as Readonly<Record<string, unknown>>;- },- });- this.runner_?.useAot(this.aot_);+ const installation = this.reserveCompiledInstall_();+ await installation.ready;+ try {+ const epoch = installation.epoch;+ this.checkCompiledInstallEpoch_(epoch);+ this.ensureTime_();+ const runtime = await prepareAot({+ world: this.world_,+ host: opts.host,+ manifest: opts.manifest,+ wasm: opts.wasm,+ beforeCommit: () => this.checkCompiledInstallEpoch_(epoch),+ resourceFields: (name) => {+ const def = builtinResource(name) ?? this.resources_.getByName(name) ?? declaredResource(name);+ if (def === undefined) return undefined;+ const value = this.resources_.get(def);+ return typeof value === 'object' && value !== null ? Object.keys(value) : [];+ },+ // A manifest carries event NAMES; the registry answers for the ones+ // some system has asked for a reader or a writer of.+ events: (name) => {+ // Through the DEFINITION, so the bus exists whether or not an+ // interpreted system has asked for one yet: a twin sending into+ // a bus nobody had made would drop its payloads and say nothing.+ const def = eventNamed(name);+ if (def === undefined) return undefined;+ const bus = this.eventRegistry_.getBus(def);+ return { read: () => bus.getReadBuffer(), send: (payload) => bus.send(payload) };+ },+ resources: (name) => {+ // The engine's own by name, and the PROJECT's through the+ // storage's own name registry — a compiled system reads either.+ const def = builtinResource(name) ?? this.resources_.getByName(name) ?? declaredResource(name);+ // `get`, not `has` then `get`: a slot holding a materialised+ // default is what an INTERPRETED system reads, and a twin has to+ // see the same world or the two stop being the same program.+ return def === undefined+ ? undefined+ : this.resources_.get(def) as Readonly<Record<string, unknown>>;+ },+ });+ if (epoch !== this.quitEpoch_) {+ runtime.dispose?.();+ throw new Error('Compiled systems installation was cancelled by App.quit');+ }+ this.commitCompiledRuntime_(runtime, epoch);+ } finally {+ installation.done();+ }+ }++ private reserveCompiledInstall_(): { ready: Promise<void>; done(): void; epoch: number } {+ const ready = this.compiledInstallTail_;+ let done!: () => void;+ this.compiledInstallTail_ = new Promise<void>(resolve => { done = resolve; });+ return { ready, done, epoch: this.quitEpoch_ };+ }++ private checkCompiledInstallEpoch_(epoch: number): void {+ if (this.quitting_ || epoch !== this.quitEpoch_) {+ throw new Error('Compiled systems installation was cancelled by App.quit');+ }+ }++ private commitCompiledRuntime_(runtime: AotRuntime, epoch: number): void {+ const previous = this.aot_;+ try { this.runner_?.useAot(runtime); }+ catch (error) {+ try { this.runner_?.useAot(previous); } catch (restoreError) { log.warn('app', 'Compiled dispatch restore error', restoreError); }+ try { runtime.dispose?.(); } catch (releaseError) { log.warn('app', 'Compiled installation cleanup error', releaseError); }+ throw error;+ }+ this.aot_ = runtime;+ try { previous?.dispose?.(); } catch (releaseError) { log.warn('app', 'Compiled runtime replacement cleanup error', releaseError); }+ this.checkCompiledInstallEpoch_(epoch);}/**@@ -949,42 +1061,57 @@ export class App {async installCompiledSystems(source: string | BufferSource, manifest: AotManifest,): Promise<number> {- // Which road is a fact about the HOST, not about the caller: a host- // that loads a library packs the rows itself, and an address there is a- // pointer nothing here can hold.- const native = this.installNative_(source, manifest);- if (native !== null) return native;- const wasm = source;- const module = this.module_;- if (!module) {- throw new Error('installCompiledSystems: this App has no engine module, and a compiled '- + 'system reads the memory of one');- }- const memory = module.wasmMemory;- if (!memory) {- throw new Error('installCompiledSystems: this engine artifact does not export '- + "'wasmMemory', so there is no memory for the module to import — rebuild the engine");+ const installation = this.reserveCompiledInstall_();+ await installation.ready;+ try {+ const epoch = installation.epoch;+ this.checkCompiledInstallEpoch_(epoch);+ // Which road is a fact about the HOST, not about the caller: a host+ // that loads a library packs the rows itself, and an address there is a+ // pointer nothing here can hold.+ const native = this.installNative_(source, manifest);+ if (native !== null) return native;+ const wasm = source;+ const module = this.module_;+ if (!module) {+ throw new Error('installCompiledSystems: this App has no engine module, and a compiled '+ + 'system reads the memory of one');+ }+ const memory = module.wasmMemory;+ if (!memory) {+ throw new Error('installCompiledSystems: this engine artifact does not export '+ + "'wasmMemory', so there is no memory for the module to import — rebuild the engine");+ }+ // Read through to the module rather than captured: emscripten REPLACES+ // the heap view when the heap grows, and a snapshot taken here would be+ // detached by the first allocation that grows it.+ const host: AotHost = {+ allocatorIdentity: module,+ memory,+ _malloc: (size: number) => module._malloc(size),+ _free: (ptr: number) => module._free(ptr),+ get HEAPU8(): Uint8Array { return module.HEAPU8; },+ };+ this.ensureTime_();+ const runtime = await prepareAot({+ world: this.world_,+ host,+ manifest,+ wasm,+ beforeCommit: () => this.checkCompiledInstallEpoch_(epoch),+ resources: (name: string) => this.getResourceByName(name) as+ Readonly<Record<string, unknown>> | undefined,+ });+ if (epoch !== this.quitEpoch_) {+ runtime.dispose?.();+ throw new Error('Compiled systems installation was cancelled by App.quit');+ }+ this.ensureRunner_();+ this.commitCompiledRuntime_(runtime, epoch);+ return runtime.systems.size;+ } finally {+ installation.done();}- // Read through to the module rather than captured: emscripten REPLACES- // the heap view when the heap grows, and a snapshot taken here would be- // detached by the first allocation that grows it.- const host: AotHost = {- memory,- _malloc: (size: number) => module._malloc(size),- _free: (ptr: number) => module._free(ptr),- get HEAPU8(): Uint8Array { return module.HEAPU8; },- };- this.ensureTime_();- this.aot_ = await installAot({- world: this.world_,- runner: this.ensureRunner_(),- host,- manifest,- wasm,- resources: (name: string) => this.getResourceByName(name) as- Readonly<Record<string, unknown>> | undefined,- });- return this.aot_.systems.size;}/**@@ -998,7 +1125,8 @@ export class App {const heap = createNativeHeap();if (bindings === null || heap === null) return null;this.ensureTime_();- this.aot_ = installNativeAot({+ const epoch = this.quitEpoch_;+ const runtime = installNativeAot({world: this.world_,runner: this.ensureRunner_(),modulePath: module,@@ -1008,7 +1136,14 @@ export class App {resources: (name: string) => this.getResourceByName(name) asReadonly<Record<string, unknown>> | undefined,});- return this.aot_?.systems.size ?? 0;+ if (runtime === null) return 0;+ if (epoch !== this.quitEpoch_) {+ runtime.dispose?.();+ this.runner_?.useAot(this.aot_);+ throw new Error('Compiled systems installation was cancelled by App.quit');+ }+ this.commitCompiledRuntime_(runtime, epoch);+ return runtime.systems.size;}// =========================================================================@@ -1135,7 +1270,18 @@ export class App {if (this.running_ && version === this.loopVersion_) this.queueLoopFrame_();};+ private quitting_ = false;+ private quitEpoch_ = 0;+quit(options?: { keepRenderer?: boolean }): void {+ if (this.quitting_) return;+ this.quitting_ = true;+ this.quitEpoch_++;+ try { this.quit_(options); }+ finally { this.quitting_ = false; }+ }++ private quit_(options?: { keepRenderer?: boolean }): void {this.invalidateLoop_();this.running_ = false;@@ -1151,7 +1297,18 @@ export class App {for (const entity of this.world_.getAllEntities()) {try { this.world_.despawn(entity); } catch (e) { log.warn('app', 'Shutdown despawn error', e); }}+ const aot = this.aot_;+ this.aot_ = null;+ this.runner_?.useAot(null);+ try { aot?.dispose?.(); }+ catch (e) { log.warn('app', 'Shutdown compiled-runtime release error', e); }+ try { this.world_.releaseScriptPools(); }+ catch (e) { log.warn('app', 'Shutdown script-pool release error', e); }this.world_.disconnectCpp();+ const ownedRegistry = this.ownedCppRegistry_;+ this.ownedCppRegistry_ = null;+ try { ownedRegistry?.delete(); }+ catch (e) { log.warn('app', 'Shutdown registry release error', e); }for (const [, entries] of this.systems_) {entries.length = 0;@@ -1756,79 +1913,89 @@ export function createWebApp(module: ESEngineModule, options?: WebAppOptions): Aif (options?.sideModules) app.setSideModules(options.sideModules);const cppRegistry = new module.Registry() as unknown as CppRegistry;- app.connectCpp(cppRegistry, module, { strict: true });-- // BEFORE renderer init: shader compilation reads the color-space global.- // Always applied (realm reloads must reset a prior session's mode too).- setLinearColorSpace(options?.colorSpace === 'linear');- module.renderer_setColorSpace?.(options?.colorSpace === 'linear' ? 1 : 0);- if (options?.randomSeed !== undefined) module.engine_setRandomSeed?.(options.randomSeed >>> 0);-- const surface: RenderSurfaceSource = options?.renderSurface ?? { kind: 'default' };- switch (surface.kind) {- case 'webgpu': {- const size = options?.getViewportSize?.() ?? { width: 800, height: 600 };- // The canvas' own preference: configuring anything else makes the- // browser copy the whole frame on every present.- const preferBGRA = (navigator as unknown as {- gpu?: { getPreferredCanvasFormat?(): string };- }).gpu?.getPreferredCanvasFormat?.() === 'bgra8unorm';- if (!module.initRendererWebGPU(- surface.canvasSelector ?? '#canvas', size.width, size.height,- surface.readback === true, preferBGRA)) {- throw new Error(- 'WebGPU renderer initialization failed — the module needs a ' +- 'preinitializedWebGPUDevice and a WebGPU-enabled engine build.');+ try {+ app.connectCpp(cppRegistry, module, { strict: true, ownedRegistry: true });++ // BEFORE renderer init: shader compilation reads the color-space global.+ // Always applied (realm reloads must reset a prior session's mode too).+ setLinearColorSpace(options?.colorSpace === 'linear');+ module.renderer_setColorSpace?.(options?.colorSpace === 'linear' ? 1 : 0);+ if (options?.randomSeed !== undefined) module.engine_setRandomSeed?.(options.randomSeed >>> 0);++ const surface: RenderSurfaceSource = options?.renderSurface ?? { kind: 'default' };+ switch (surface.kind) {+ case 'webgpu': {+ const size = options?.getViewportSize?.() ?? { width: 800, height: 600 };+ // The canvas' own preference: configuring anything else makes the+ // browser copy the whole frame on every present.+ const preferBGRA = (navigator as unknown as {+ gpu?: { getPreferredCanvasFormat?(): string };+ }).gpu?.getPreferredCanvasFormat?.() === 'bgra8unorm';+ if (!module.initRendererWebGPU(+ surface.canvasSelector ?? '#canvas', size.width, size.height,+ surface.readback === true, preferBGRA)) {+ throw new Error(+ 'WebGPU renderer initialization failed — the module needs a ' ++ 'preinitializedWebGPUDevice and a WebGPU-enabled engine build.');+ }+ watchWebGPUDeviceLoss(module);+ break;}- watchWebGPUDeviceLoss(module);- break;+ case 'gl-context':+ if (!module.initRendererWithContext(surface.handle)) {+ throw new Error(`WebGL2 renderer initialization failed for context ${surface.handle}.`);+ }+ break;+ case 'default':+ if (!module.initRenderer()) {+ throw new Error('WebGL2 renderer initialization failed for the default canvas.');+ }+ break;+ }+ surfaces.set(app, { graphics: graphicsPathFor(surface), size: options?.getViewportSize ?? null });+ // Always applied (not only when set): the renderer outlives the App on realm+ // reloads, so a fresh App must reset a prior session's y-sort state too.+ module.renderer_setYSortLayers?.((options?.ySortLayers ?? 0) >>> 0);+ module.renderer_setDepthLayers?.((options?.depthLayers ?? 0) >>> 0);+ // After the renderer, not with the colour space above it: the post-process+ // pipeline is created by the renderer, and a curve declared before it exists+ // reaches nothing.+ module.postprocess_setOutputTransform?.(outputTransformCode(options?.outputTransform));+ module.postprocess_setMsaaSamples?.((options?.msaaSamples ?? 4) >>> 0);++ app.addPlugin(corePlugin);+ app.setPipeline(new RenderPipeline());+ app.insertResource(UICameraInfo, { ...DEFAULT_UI_CAMERA_INFO });+ app.insertResource(ScreenLayout, { ...ScreenLayout._default });+ app.insertResource(ScreenOverlay, defaultScreenOverlay());+ app.addPlugin(cameraPlugin(options?.getViewportSize));+ app.addPlugin(assetPlugin);+ app.addPlugin(prefabsPlugin);+ app.addPlugin(inputPlugin);+ app.addPlugin(sceneManagerPlugin);+ if (options?.plugins) {+ app.addPlugins(options.plugins);}- case 'gl-context':- module.initRendererWithContext(surface.handle);- break;- case 'default':- module.initRenderer();- break;- }- surfaces.set(app, { graphics: graphicsPathFor(surface), size: options?.getViewportSize ?? null });- // Always applied (not only when set): the renderer outlives the App on realm- // reloads, so a fresh App must reset a prior session's y-sort state too.- module.renderer_setYSortLayers?.((options?.ySortLayers ?? 0) >>> 0);- module.renderer_setDepthLayers?.((options?.depthLayers ?? 0) >>> 0);- // After the renderer, not with the colour space above it: the post-process- // pipeline is created by the renderer, and a curve declared before it exists- // reaches nothing.- module.postprocess_setOutputTransform?.(outputTransformCode(options?.outputTransform));- module.postprocess_setMsaaSamples?.((options?.msaaSamples ?? 4) >>> 0);-- app.addPlugin(corePlugin);- app.setPipeline(new RenderPipeline());- app.insertResource(UICameraInfo, { ...DEFAULT_UI_CAMERA_INFO });- app.insertResource(ScreenLayout, { ...ScreenLayout._default });- app.insertResource(ScreenOverlay, defaultScreenOverlay());- app.addPlugin(cameraPlugin(options?.getViewportSize));- app.addPlugin(assetPlugin);- app.addPlugin(prefabsPlugin);- app.addPlugin(inputPlugin);- app.addPlugin(sceneManagerPlugin);- if (options?.plugins) {- app.addPlugins(options.plugins);- }-- // Project camera fit: only install the resource when the project opts in (a real- // scaleMode). Absent ⇒ CameraPlugin.resolveFitSource sees no resource and keeps- // the legacy Canvas-or-raw fit, so an unconfigured game is byte-for-byte unchanged.- // Either opt-in installs it. The render policy does not need a camera fit —- // it takes the camera's world height whatever produced it — and gating one on- // the other made a project that wanted only the policy get neither.- if (options?.screenFit- && (options.screenFit.scaleMode > SCREEN_FIT_OFF- || (options.screenFit.renderPolicy ?? RenderResolution.Surface) !== RenderResolution.Surface)) {- app.insertResource(ScreenScaling, { ...options.screenFit });- }-- if (options?.quality) installQuality(app, options.quality, options.msaaSamples ?? 4);- return app;++ // Project camera fit: only install the resource when the project opts in (a real+ // scaleMode). Absent ⇒ CameraPlugin.resolveFitSource sees no resource and keeps+ // the legacy Canvas-or-raw fit, so an unconfigured game is byte-for-byte unchanged.+ // Either opt-in installs it. The render policy does not need a camera fit —+ // it takes the camera's world height whatever produced it — and gating one on+ // the other made a project that wanted only the policy get neither.+ if (options?.screenFit+ && (options.screenFit.scaleMode > SCREEN_FIT_OFF+ || (options.screenFit.renderPolicy ?? RenderResolution.Surface) !== RenderResolution.Surface)) {+ app.insertResource(ScreenScaling, { ...options.screenFit });+ }++ if (options?.quality) installQuality(app, options.quality, options.msaaSamples ?? 4);+ return app;+ } catch (error) {+ try { app.quit({ keepRenderer: true }); }+ catch (releaseError) { log.warn('app', 'Failed web App construction cleanup error', releaseError); }+ throw error;+ }}/**diff --git a/sdk/src/asset/AssetLease.ts b/sdk/src/asset/AssetLease.tsindex bf000dbae..e9fc962fe 100644--- a/sdk/src/asset/AssetLease.ts+++ b/sdk/src/asset/AssetLease.ts@@ -10,12 +10,18 @@* same path live at the same time.*/+import { disposeAll } from '../util/disposeAll';++const releaseLease = (lease: AssetLease): void => lease.release();+/** One acquisition, and the right to end it. */export interface AssetLease<T = unknown> {readonly key: string;/** Ledger-minted, so two eras never merge even if their values compare equal. */readonly generation: number;readonly value: T;+ /** @internal Unavailable dependencies of the preparation held by this receipt. */+ readonly failedDependencies?: readonly string[];/** Give this one acquisition back. Calling twice is a no-op, not a double free. */release(): void;/**@@ -44,11 +50,14 @@ export class AssetScope {return lease;}- /** Hand back everything, in reverse acquisition order. */+ /** Hand back the current batch in reverse order, attempting all releases.+ * A failure is reported after cleanup; acquisitions made by cleanup belong+ * to the next batch. */releaseAll(): void {- // Reverse: a dependent acquired after what it depends on goes first.- for (let i = this.leases_.length - 1; i >= 0; i--) this.leases_[i].release();+ const leases = this.leases_;this.leases_ = [];+ // Detach before callbacks: a reentrant release cannot spend this batch.+ disposeAll(leases, releaseLease, true);}/**diff --git a/sdk/src/asset/AssetPlugin.ts b/sdk/src/asset/AssetPlugin.tsindex e361d154d..97a63b385 100644--- a/sdk/src/asset/AssetPlugin.ts+++ b/sdk/src/asset/AssetPlugin.ts@@ -7,7 +7,7 @@ import { DeviceStatus, getDeviceStatus } from '../render/renderer';import { Assets as AssetsClass } from './Assets';import { HttpBackend } from './Backend';import { basisTranscoderFor } from './basisWorkers';-import { AssetRefCounter } from './AssetRefCounter';+import { bindAssetReferenceTracking } from './assetReferenceTracking';import { Audio, type AudioAPI } from '../audio/Audio';import { SpriteAnimation, type SpriteAnimationAPI } from '../animation/SpriteAnimator';import { Localization, type LocalizationAPI } from '../i18n/Localization';@@ -64,16 +64,15 @@ export class AssetPlugin implements Plugin {// which the realm sets before any asset load.assets.getTextureLoader().setTranscoderProvider(() => basisTranscoderFor(app.sideModules));- // Install the ref counter so resolveSceneAssetPaths records who- // uses what, and wire it to world despawns so entries don't+ // Install the ref counter so scene spawning records live World IDs,+ // and wire it to world despawns so entries don't// outlive their entities. Tools / debug UI read it via// `assets.getRefCounter()`.- const counter = new AssetRefCounter();- assets.setRefCounter(counter);- app.world.onDespawn((entity) => counter.removeAllRefsForEntity(entity));+ bindAssetReferenceTracking(app.world, assets,+ () => app.hasResource(Assets) ? app.getResource(Assets) : null);app.insertResource(Assets, assets);- this.driveDeviceRecovery_(app, assets);+ this.driveDeviceRecovery_(app);}/**@@ -82,7 +81,7 @@ export class AssetPlugin implements Plugin {* lost its GPU stayed lost. Timed off UNSCALED delta — a paused game still* has to come back — and backed off, since each attempt re-fetches content.*/- private driveDeviceRecovery_(app: App, assets: AssetsClass): void {+ private driveDeviceRecovery_(app: App): void {let inFlight = false;let waited = 0;let backoff = 0;@@ -105,7 +104,19 @@ export class AssetPlugin implements Plugin {waited = 0;inFlight = true;const lostFor = downtime;- void assets.recoverFromDeviceLoss()+ // A runtime replaces the default HTTP-backed resource with its own+ // decoder. Never recover the instance captured during plugin build.+ const recoverCurrent = async (): Promise<boolean> => {+ let assets = app.hasResource(Assets) ? app.getResource(Assets) : null;+ while (assets) {+ const whole = await assets.recoverFromDeviceLoss();+ const current = app.hasResource(Assets) ? app.getResource(Assets) : null;+ if (current === assets) return whole;+ assets = current;+ }+ return false;+ };+ void recoverCurrent().then((whole) => {if (whole) {log.info('asset', `Device recovered after ${lostFor.toFixed(1)}s`);diff --git a/sdk/src/asset/AssetRefCounter.ts b/sdk/src/asset/AssetRefCounter.tsindex c5d404fb9..fe83aaca4 100644--- a/sdk/src/asset/AssetRefCounter.ts+++ b/sdk/src/asset/AssetRefCounter.ts@@ -13,6 +13,8 @@ export interface AssetRefInfo {class RefMap {private refs_ = new Map<string, Set<number>>();+ private pathsByEntity_ = new Map<number, Set<string>>();+ private rows_ = 0;add(path: string, entity: number): void {let refs = this.refs_.get(path);@@ -20,14 +22,22 @@ class RefMap {refs = new Set();this.refs_.set(path, refs);}+ if (refs.has(entity)) return;refs.add(entity);+ let paths = this.pathsByEntity_.get(entity);+ if (!paths) this.pathsByEntity_.set(entity, paths = new Set());+ paths.add(path);+ this.rows_++;}remove(path: string, entity: number): void {const refs = this.refs_.get(path);- if (refs) {- refs.delete(entity);+ if (refs?.delete(entity)) {+ this.rows_--;if (refs.size === 0) this.refs_.delete(path);+ const paths = this.pathsByEntity_.get(entity);+ paths?.delete(path);+ if (paths?.size === 0) this.pathsByEntity_.delete(entity);}}@@ -48,8 +58,12 @@ class RefMap {}removeEntity(entity: number): void {- for (const [path, refs] of this.refs_) {- refs.delete(entity);+ const paths = this.pathsByEntity_.get(entity);+ if (!paths) return;+ this.pathsByEntity_.delete(entity);+ for (const path of paths) {+ const refs = this.refs_.get(path)!;+ if (refs.delete(entity)) this.rows_--;if (refs.size === 0) this.refs_.delete(path);}}@@ -57,12 +71,10 @@ class RefMap {get size(): number { return this.refs_.size; }get rows(): number {- let n = 0;- for (const refs of this.refs_.values()) n += refs.size;- return n;+ return this.rows_;}- clear(): void { this.refs_.clear(); }+ clear(): void { this.refs_.clear(); this.pathsByEntity_.clear(); this.rows_ = 0; }}export class AssetRefCounter {diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.tsindex e878bcf18..c3178ade5 100644--- a/sdk/src/asset/Assets.ts+++ b/sdk/src/asset/Assets.ts@@ -25,11 +25,13 @@ import { optionalAssetLoaders } from './optionalLoaders';import { AssetScope, type AssetLease } from './AssetLease';import { EntityAssetScopes } from './entityAssetScopes';import { RegistryAssetSlots, type RegistryAssetKind } from './registryAssets';-import { DependencyRecorder, isInvalidatable, rebuildPlan, type AssetIdentity,+import { DependencyRecorder, PreparationFailure, preparationFailureReason, isInvalidatable, rebuildPlan, type AssetIdentity,type DependencyReceipt, type Preparation, type PreparedLoad } from './dependencies';import { SpineAssetLoader } from './loaders/SpineAssetLoader';-import { spinePairKey } from '../spine/prepareSpine';+import { spinePairKey } from './spinePairKey';import { MaterialAssetLoader } from './loaders/MaterialAssetLoader';+import { MaterialShaderAssetLoader } from './loaders/MaterialShaderAssetLoader';+import { isBuiltinAssetRef } from './documentRef';import { MeshAssetLoader, type MeshResult } from './loaders/MeshAssetLoader';import { nativeEngineApi, type EngineApi } from '../ecs/bridge/engineApi';import { isBuiltinMeshRef } from './builtinMeshes';@@ -42,7 +44,8 @@ import { TimelineAssetLoader } from './loaders/TimelineAssetLoader';import { PrefabAssetLoader } from './loaders/PrefabAssetLoader';import { AnimatorControllerAssetLoader } from './loaders/AnimatorControllerAssetLoader';import { AvatarAssetLoader } from './loaders/AvatarAssetLoader';-import { preparePrefab, type PreparedPrefab } from '../prefab/preparedPrefab';+import { preparePrefabFromSource, type PreparedPrefab } from '../prefab/preparedPrefab';+import type { PrefabOverride } from '../prefab';import { LocaleAssetLoader } from './loaders/LocaleAssetLoader';import { JsonAssetLoader } from './loaders/JsonAssetLoader';import { getComponentDefaults } from '../ecs/component';@@ -54,6 +57,7 @@ import { SceneHandle, type ReleaseCallback } from './SceneHandle';import { UUID_REF_PREFIX } from './AssetRegistry';import type { AssetRefCounter } from './AssetRefCounter';import { log } from '../util/logger';+import { disposeAll } from '../util/disposeAll';import { recoverDevice, getDeviceStatus, DeviceStatus } from '../render/renderer';/**@@ -336,6 +340,8 @@ export interface SceneAssetResult {* and an invalidate mid-load left the receipt of the era we really got.*/scope: AssetScope;+ /** @internal Projection of successful acquisitions; their scope/era remains the owner. */+ acquisitions?: readonly { readonly type: string; readonly path: string; readonly lease: AssetLease }[];missing: MissingAsset[];/** Per asset type: how many loaded, the sum of their load times and the* slowest one, in ms. Loads overlap, so the sums exceed the wall time. */@@ -413,9 +419,6 @@ export class Assets {private textureImportResolver_: TextureImportSettingsResolver | null = null;private spineLoader_: SpineAssetLoader;- /** Prefabs flattened and resolved for one-frame spawning, by resolved path. */- private preparedPrefabs_ = new Map<string, { holders: number; prepared: PreparedPrefab }>();-private textureCache_ = new AsyncCache<TextureResult>((result) => {// A texture whose load finished after its getOrLoad timed out has no// owner; release its GL handle so it doesn't leak VRAM.@@ -431,6 +434,14 @@ export class Assets {* resumes. Delivering that handle is a use-after-free; the load fails instead.*/private resetEpoch_ = 0;+ private releasing_ = false;+ private preparations_ = new Set<DependencyRecorder>();++ private assertLoading_(epoch = this.resetEpoch_): void {+ if (this.releasing_ || epoch !== this.resetEpoch_) {+ throw new Error('Assets were released while loading; this request has no owner. Load it again.');+ }+ }/** Handles already disowned in this epoch, so N callers sharing one load* drop its single C++ reference once between them, not N times. */private abandoned_ = new Set<number>();@@ -638,6 +649,7 @@ export class Assets {private async acquireTextureVariant_(ref: string, flip: boolean,): Promise<{ result: TextureResult; lease: AssetRefLease<number> }> {+ this.assertLoading_();const path = this.resolveLoadPath_(ref);const cacheKey = this.textureCacheKey_(path, flip);const settings = this.textureImportResolver_?.(ref);@@ -742,7 +754,7 @@ export class Assets {return null;}- /** Record a handle→path pair for {@link pathForHandle} (dropped on invalidate/releaseAll). */+ /** Record a handle→path pair, dropped on invalidation or final release. */private recordHandlePath_(kind: string, handle: number, path: string): void {if (handle !== 0) this.handleToPath_.set(`${kind}:${handle}`, path);}@@ -759,6 +771,11 @@ export class Assets {* names the pair and not the skeleton's path.*/async acquireSpine(skeletonRef: string, atlasRef?: string): Promise<AssetLease<SpineResult>> {+ try { return await this.acquireSpineLease_(skeletonRef, atlasRef); }+ catch (error) { throw preparationFailureReason(error); }+ }++ private async acquireSpineLease_(skeletonRef: string, atlasRef?: string): Promise<AssetLease<SpineResult>> {const skeleton = this.resolveLoadPath_(skeletonRef);const atlas = this.spineAtlasOf_(skeleton, atlasRef);const key = spinePairKey(skeleton, atlas);@@ -1417,6 +1434,15 @@ export class Assets {sceneData: SceneData,onProgress?: (loaded: number, total: number) => void,options?: { readonly maxConcurrent?: number; readonly skipSpine?: boolean },+ ): Promise<SceneAssetResult> {+ return this.preloadSceneAssets_(sceneData, onProgress, options);+ }++ private async preloadSceneAssets_(+ sceneData: SceneData,+ onProgress?: (loaded: number, total: number) => void,+ options?: { readonly maxConcurrent?: number; readonly skipSpine?: boolean },+ recorder?: DependencyRecorder,): Promise<SceneAssetResult> {const missing: MissingAsset[] = [];const discovered = discoverSceneAssets(sceneData, (ref) => this.resolveRef(ref));@@ -1460,10 +1486,12 @@ export class Assets {const probeVolumeHandles = new Map<string, number>();const releaseCallbacks: ReleaseCallback[] = [];const scope = new AssetScope();+ const acquisitions: { type: string; path: string; lease: AssetLease }[] = [];let loadedCount = 0;const recordFailure = (path: string, label: string, err: unknown): void => {+ recorder?.failed(path, err);missing.push({ref: path,type: label,@@ -1502,7 +1530,11 @@ export class Assets {for (const path of paths) {tasks.push(() =>timedLoad(label, () => acquire(path)).then(lease => {- scope.add(lease);+ // A baked asset's era owns these acquisitions. An ordinary+ // scene owns them through the returned scope instead.+ if (recorder) recorder.own(path, lease, label);+ else scope.add(lease);+ acquisitions.push({ type: label, path, lease });releaseCallbacks.push(() => lease.release());if (handles) {handles.set(path, (lease.value as { handle?: number } | null)?.handle ?? 0);@@ -1528,14 +1560,14 @@ export class Assets {'texture',textureHandles,);- pushAcquire(materialPaths, p => this.acquireTyped<MaterialResult>('material', p),+ pushAcquire(materialPaths, p => this.acquireTypedLease_<MaterialResult>('material', p),'material', materialHandles);- pushAcquire(fontPaths, p => this.acquireTyped<FontResult>('font', p), 'font', fontHandles);- pushAcquire(meshPaths, p => this.acquireTyped<{ handle: number }>('mesh', p),+ pushAcquire(fontPaths, p => this.acquireTypedLease_<FontResult>('font', p), 'font', fontHandles);+ pushAcquire(meshPaths, p => this.acquireTypedLease_<{ handle: number }>('mesh', p),'mesh', meshHandles);- pushAcquire(environmentPaths, p => this.acquireTyped<{ handle: number }>('environment', p),+ pushAcquire(environmentPaths, p => this.acquireTypedLease_<{ handle: number }>('environment', p),'environment', environmentHandles);- pushAcquire(probeVolumePaths, p => this.acquireTyped<{ handle: number }>('probeVolume', p),+ pushAcquire(probeVolumePaths, p => this.acquireTypedLease_<{ handle: number }>('probeVolume', p),'probeVolume', probeVolumeHandles);// A pair, so not `pushAcquire` (which keys by one path); the receipt is// the scene's exactly as every other one is. The runtime scene loader@@ -1543,8 +1575,10 @@ export class Assets {if (!options?.skipSpine) {for (const pair of spinePairs) {tasks.push(() =>- this.acquireSpine(pair.skeleton, pair.atlas).then((lease) => {- scope.add(lease);+ this.acquireSpineLease_(pair.skeleton, pair.atlas).then((lease) => {+ if (recorder) recorder.own(spinePairKey(pair.skeleton, pair.atlas), lease, 'spine');+ else scope.add(lease);+ acquisitions.push({ type: 'spine', path: spinePairKey(pair.skeleton, pair.atlas), lease });releaseCallbacks.push(() => lease.release());}).catch(e => {log.warn('asset', `Failed to load spine: ${pair.skeleton}`, e);@@ -1553,19 +1587,19 @@ export class Assets {);}}- pushAcquire(animClipPaths, p => this.acquireAnimClip_(p), 'anim-clip');- pushAcquire(tilemapPaths, p => this.acquireTyped('tilemap', p), 'tilemap');- pushAcquire(tilesetPaths, p => this.acquireTyped('tileset', p), 'tileset');- pushAcquire(timelinePaths, p => this.acquireTyped('timeline', p), 'timeline');- pushAcquire(audioPaths, p => this.acquireTyped('audio', p), 'audio');+ pushAcquire(animClipPaths, p => this.acquireTypedLease_('anim-clip', p), 'anim-clip');+ pushAcquire(tilemapPaths, p => this.acquireTypedLease_('tilemap', p), 'tilemap');+ pushAcquire(tilesetPaths, p => this.acquireTypedLease_('tileset', p), 'tileset');+ pushAcquire(timelinePaths, p => this.acquireTypedLease_('timeline', p), 'timeline');+ pushAcquire(audioPaths, p => this.acquireTypedLease_('audio', p), 'audio');// FSM/BT loaders register the parsed definition into the shared AI store// under the asset path, so a StateMachineAgent/BehaviorTreeAgent whose// fsm/bt is that path resolves once the scene finishes preloading.- pushAcquire(fsmPaths, p => this.acquireTyped('statemachine', p), 'statemachine');- pushAcquire(btPaths, p => this.acquireTyped('behaviortree', p), 'behaviortree');- pushAcquire(graphPaths, p => this.acquireTyped('scriptgraph', p), 'scriptgraph');- pushAcquire(animatorPaths, p => this.acquireTyped('animatorcontroller', p), 'animatorcontroller');- pushAcquire(avatarPaths, p => this.acquireTyped('avatar', p), 'avatar');+ pushAcquire(fsmPaths, p => this.acquireTypedLease_('statemachine', p), 'statemachine');+ pushAcquire(btPaths, p => this.acquireTypedLease_('behaviortree', p), 'behaviortree');+ pushAcquire(graphPaths, p => this.acquireTypedLease_('scriptgraph', p), 'scriptgraph');+ pushAcquire(animatorPaths, p => this.acquireTypedLease_('animatorcontroller', p), 'animatorcontroller');+ pushAcquire(avatarPaths, p => this.acquireTypedLease_('avatar', p), 'avatar');const totalCount = tasks.length;onProgress?.(0, totalCount);@@ -1588,13 +1622,12 @@ export class Assets {warnFailedLoads(missing.filter((m) => m.reason === 'load-failed'));return { textureHandles, materialHandles, fontHandles, meshHandles, environmentHandles,- probeVolumeHandles, releaseCallbacks, scope, missing, timings, wallMs };+ probeVolumeHandles, releaseCallbacks, scope, acquisitions, missing, timings, wallMs };}resolveSceneAssetPaths(sceneData: SceneData, result: SceneAssetResult): void {const { textureHandles, materialHandles, fontHandles, meshHandles,environmentHandles, probeVolumeHandles } = result;- const counter = this.refCounter_;for (const entity of sceneData.entities) {// Prefab-instance entries carry no inline components (a prefab ref +@@ -1623,7 +1656,7 @@ export class Assets {case 'texture': {const handle = textureHandles.get(path) ?? 0;comp.data[field] = handle;- if (counter && handle) counter.addTextureRef(path, entity.id);+ this.recordHandlePath_('texture', handle, path);// Ref spelling first (per-frame keys); the resolved// path for packed frames is the shared page.const atlasInfo = this.catalog.getAtlasFrame(ref) ?? this.catalog.getAtlasFrame(path);@@ -1654,13 +1687,13 @@ export class Assets {case 'material': {const handle = materialHandles.get(path) ?? 0;comp.data[field] = handle;- if (counter && handle) counter.addMaterialRef(path, entity.id);+ this.recordHandlePath_('material', handle, path);break;}case 'font': {const handle = fontHandles.get(path) ?? 0;comp.data[field] = handle;- if (counter && handle) counter.addFontRef(path, entity.id);+ this.recordHandlePath_('font', handle, path);break;}case 'mesh': {@@ -1681,6 +1714,28 @@ export class Assets {}}+ /** Record scene users only after source IDs have been mapped to live World entities.+ * Resolution is preparation; source IDs cannot be removed by World.onDespawn. */+ trackSceneAssetReferences(scene: SceneData, entities: ReadonlyMap<number, number>): void {+ const counter = this.refCounter_;+ if (!counter) return;+ for (const source of scene.entities) {+ const entity = entities.get(source.id);+ if (entity === undefined || !Array.isArray(source.components)) continue;+ for (const comp of source.components) {+ for (const { field, type } of getComponentAssetFieldDescriptors(comp.type)) {+ const handle = comp.data[field];+ if (typeof handle !== 'number' || !handle) continue;+ const path = this.pathForHandle(type, handle);+ if (path === null) continue;+ if (type === 'texture') counter.addTextureRef(path, entity);+ else if (type === 'material') counter.addMaterialRef(path, entity);+ else if (type === 'font') counter.addFontRef(path, entity);+ }+ }+ }+ }+// =========================================================================// Acquire — the same loads, but handing back an ownership receipt// =========================================================================@@ -1699,7 +1754,16 @@ export class Assets {/** {@link acquireTexture} for everything that goes through a typed loader. */async acquireTyped<T>(type: string, ref: string): Promise<AssetLease<T>> {+ try { return await this.acquireTypedLease_<T>(type, ref); }+ catch (error) { throw preparationFailureReason(error); }+ }++ private async acquireTypedLease_<T>(type: string, ref: string): Promise<AssetLease<T>> {+ const epoch = this.resetEpoch_;+ this.assertLoading_(epoch);const slot = await this.acquireSlot_<T>(type, ref);+ try { this.assertLoading_(epoch); }+ catch (error) { slot?.release(); throw error; }if (slot) return slot;const { value, lease } = await this.acquireTyped_<T>(type, ref);return this.typedLease_(type, lease, value);@@ -1775,6 +1839,7 @@ export class Assets {): AssetLease<T> {return {key: lease.key, generation: lease.generation, value,+ failedDependencies: lease.value.failedDependencies,release: () => this.releaseTypedLease(type, lease),retain: () => {const child = this.genericRefs_.retain(lease);@@ -1812,12 +1877,13 @@ export class Assets {private disposeTexture_(key: string, handle: number): void {// The pool decides what that means — free immediately (no budget), or// retain as an evictable cache entry that the next load revives by key.- requireResourceManager().releaseTexture(handle);evictTextureDimensions(handle);+ this.handleToPath_.delete(`texture:${handle}`);// Only when it is still the cached value: a superseded handle left the// cache when its generation ended, and the entry there now belongs to a// generation with holders of its own.if (this.textureCache_.get(key)?.handle === handle) this.textureCache_.delete(key);+ requireResourceManager().releaseTexture(handle);}releaseFont(ref: string): void {@@ -1910,9 +1976,9 @@ export class Assets {/** The last reference to a typed asset is gone: hand it to its loader. */private disposeGeneric_(type: string, path: string, era: PreparedLoad<unknown>): void {- this.retire_(type, era);const cache = this.genericCache_.get(type);if (cache && cache.get(path) === era) cache.delete(path);+ this.retire_(type, era);}/** End one handle-bound era: its loader destroys what it made, then what its@@ -1921,11 +1987,12 @@ export class Assets {private retire_(type: string, era: PreparedLoad<unknown>): void {if (this.retired_.has(era)) return;this.retired_.add(era);- try {- this.loaders_.get(type)?.unload?.(era.value);- } finally {- era.dependencies.releaseAll();- }+ const handle = (era.value as { handle?: unknown } | null)?.handle;+ if (typeof handle === 'number') this.handleToPath_.delete(`${type}:${handle}`);+ disposeAll([+ () => this.loaders_.get(type)?.unload?.(era.value),+ () => era.dependencies.releaseAll(),+ ], dispose => dispose());}/**@@ -1952,6 +2019,16 @@ export class Assets {*/invalidate(ref: string): boolean {const plan = this.rebuildPlan_(ref);+ // A failed preparation has no live era, but its canonical cooldown+ // rejection still records why it failed. Clear it before rebuilding+ // holders reached by the restored source, rather than reusing failure.+ const source = this.assetIdentity_(ref);+ for (const cache of this.genericCache_.values()) {+ for (const [key, error] of cache.failures()) {+ if (error instanceof PreparationFailure+ && error.sources.some(path => this.assetIdentity_(path) === source)) cache.invalidate(key);+ }+ }const { hit, rebuilt } = this.invalidateSource_(ref);if (plan.length > 0) this.track_(rebuilt.then(() => this.rebuildAssetGraph_(plan)));return hit;@@ -2211,40 +2288,58 @@ export class Assets {return this.entityScopes_;}+ /** @internal A standalone bake uses the same acquisition transaction as a graph recipe. */+ async preparePrefab(ref: string, overrides: readonly PrefabOverride[] = []): Promise<PreparedPrefab> {+ const epoch = this.resetEpoch_;+ try {+ const era = await this.prepared_(ctx => this.bakePrefab_(this.resolveLoadPath_(ref),+ ctx as LoadContext & { recorder: DependencyRecorder }, overrides));+ if (epoch !== this.resetEpoch_) {+ era.dependencies.releaseAll();+ throw new Error(`Assets were released while "${ref}" was preparing; it has no owner. Load it again.`);+ }+ return { ...era, ref, release: () => era.dependencies.releaseAll() };+ } catch (error) { throw preparationFailureReason(error); }+ }+releaseAll(): void {- // Through the normal door first, so what the app owned is disposed the- // way any other owner's is rather than by the wholesale drain below.- this.appScope_.releaseAll();- this.registrySlots_.releaseAll();- const rm = requireResourceManager();+ if (this.releasing_) return;+ this.releasing_ = true;+ // Pending loads lose ownership even if a user-provided unload throws.this.resetEpoch_++;this.abandoned_.clear();- const seen = new Set<number>();- for (const info of this.textureCache_.values()) {- seen.add(info.handle);- rm.releaseTexture(info.handle);- evictTextureDimensions(info.handle);- }- this.textureCache_.clearAll();- // Superseded generations are not in the cache and would otherwise- // survive a releaseAll that claims to have let go of everything.- for (const { value } of this.textureRefs_.drain()) {- if (seen.has(value)) continue;- seen.add(value);- rm.releaseTexture(value);- evictTextureDimensions(value);- }-- this.materialLoader_?.releaseAll();-- for (const cache of this.genericCache_.values()) {- cache.clearAll();- }- this.genericCache_.clear();- for (const { key, value } of this.genericRefs_.drain()) {- this.retire_(key.slice(0, key.indexOf(':')), value);+ try {+ disposeAll([+ () => {+ const pending = [...this.preparations_];+ this.preparations_.clear();+ disposeAll(pending, recorder => recorder.rollback());+ },+ // Normal receipts first, then every remaining generation.+ () => this.appScope_.releaseAll(),+ () => this.registrySlots_.releaseAll(),+ () => {+ const handles = new Set<number>();+ for (const info of this.textureCache_.values()) handles.add(info.handle);+ this.textureCache_.clearAll();+ for (const { value } of this.textureRefs_.drain()) handles.add(value);+ const rm = requireResourceManager();+ disposeAll([...handles], handle => {+ evictTextureDimensions(handle);+ rm.releaseTexture(handle);+ });+ },+ () => {+ for (const cache of this.genericCache_.values()) cache.clearAll();+ this.genericCache_.clear();+ const generations = this.genericRefs_.drain();+ disposeAll(generations, ({ key, value }) => this.retire_(key.slice(0, key.indexOf(':')), value));+ },+ ], dispose => dispose());+ } finally {+ this.handleToPath_.clear();+ this.releasing_ = false;}- this.handleToPath_.clear();}// =========================================================================@@ -2276,13 +2371,11 @@ export class Assets {}/**- * Attach an AssetRefCounter. When set, resolveSceneAssetPaths records- * which entity references which texture/material/font path as it- * hands out handles. Paired with `world.onDespawn(e =>- * counter.removeAllRefsForEntity(e))` — which AssetPlugin installs- * — this gives editor tools visibility into "who's holding X" and- * "does anything still need this asset?". Optional; null means no- * tracking (default, zero overhead).+ * Attach optional usage monitoring. Scene publication records runtime+ * entity IDs through trackSceneAssetReferences; the shared World binding+ * removes them on despawn and follows the active asset resource. Plugin+ * and runtime factories install it; manually created Assets default to+ * no tracking until a counter is attached.*/setRefCounter(counter: AssetRefCounter): void {this.refCounter_ = counter;@@ -2299,7 +2392,7 @@ export class Assets {* unchanged — legacy path-only scenes keep working.*/resolveRef(ref: string): string | null {- if (isBuiltinMeshRef(ref)) return ref;+ if (isBuiltinAssetRef(ref)) return ref;if (this.assetRefResolver_) return this.assetRefResolver_(ref);return ref;}@@ -2332,7 +2425,7 @@ export class Assets {// Built-in geometry names code, not a file. Every realm's resolver turns a// non-URL ref into one (the play realm prefixes an origin), so a ref that// has nothing to resolve has to say so before resolution, not after.- if (isBuiltinMeshRef(ref)) return ref;+ if (isBuiltinAssetRef(ref)) return ref;// A `remote`-group asset (per the active addressable manifest) resolves to// its CDN url — so a scene @uuid ref to a remote asset loads from, and// hot-updates with, the CDN, not just loadGroup'd DLC assets. Gated on a@@ -2384,13 +2477,11 @@ export class Assets {// Private// =========================================================================- private materialLoader_: MaterialAssetLoader | null = null;-private registerBuiltinLoaders(): void {this.register(this.textureLoader_);this.register(this.spineLoader_);- this.materialLoader_ = new MaterialAssetLoader();- this.register(this.materialLoader_);+ this.register(new MaterialShaderAssetLoader());+ this.register(new MaterialAssetLoader());this.register(new FontAssetLoader());// The engine core however it is embedded: the module on the web, the host's// bindings on a device. Taking only the module made these two web-only by@@ -2405,6 +2496,13 @@ export class Assets {this.register(new AnimClipAssetLoader());this.register(new TimelineAssetLoader());this.register(new PrefabAssetLoader());+ // A recipe is bound to an exact era, just like a resolved material.+ // Use the same pending cache, generation ledger and dependency graph.+ this.register<PreparedPrefab>({+ type: 'prepared-prefab', extensions: [],+ load: (path, context) => this.bakePrefab_(path, context as LoadContext & { recorder: DependencyRecorder }),+ unload: (prepared) => prepared.release(),+ });this.register(new AnimatorControllerAssetLoader());this.register(new AvatarAssetLoader());this.register(new LocaleAssetLoader());@@ -2420,7 +2518,8 @@ export class Assets {}private async loadTyped<T>(type: string, ref: string): Promise<T> {- return (await this.acquireTyped_<T>(type, ref)).value;+ try { return (await this.acquireTyped_<T>(type, ref)).value; }+ catch (error) { throw preparationFailureReason(error); }}private async acquireTyped_<T>(@@ -2447,6 +2546,7 @@ export class Assets {private async acquirePrepared_<T>(type: string, key: string, ref: string, prepare: (ctx: LoadContext) => Promise<T>,): Promise<{ value: T; lease: AssetRefLease<PreparedLoad<unknown>> }> {+ this.assertLoading_();const epoch = this.resetEpoch_;const era = await this.genericCacheFor_(type).getOrLoad(key, () =>this.prepared_(async (ctx) => ({ value: await prepare(ctx) as unknown })),@@ -2574,8 +2674,24 @@ export class Assets {for (const era of this.registrySlots_.eras()) {yield { type: era.type, path: era.key, edges: era.edges };}+ const seen = new Set<PreparedLoad<unknown>>();for (const [type, cache] of this.genericCache_) {- for (const [path, era] of cache.entries()) yield { type, path, edges: era.edges };+ for (const [path, era] of cache.entries()) {+ seen.add(era);+ yield { type, path, edges: era.edges };+ }+ }+ // Invalidating removes residency, not ownership. A failed refresh can+ // keep an outgoing recipe in a graph; its nested dependencies must still+ // lead back to that graph when their sources recover.+ for (const [key, generations] of this.genericRefs_.entries()) {+ const split = key.indexOf(':');+ const type = key.slice(0, split), path = key.slice(split + 1);+ for (const { value: era } of generations) {+ if (seen.has(era)) continue;+ seen.add(era);+ yield { type, path, edges: era.edges };+ }}}@@ -2608,40 +2724,21 @@ export class Assets {};}- /**- * A prepared prefab as a lease: one preparation per ref per realm, released- * when the last holder lets go. Shared, because two graphs spawning the same- * prefab want the same flattened copy — preparing it twice would load its- * textures twice and leave two scopes to release.- */- private async preparePrefabLease_(ref: string): Promise<AssetLease<PreparedPrefab>> {- const key = `prepared-prefab:${this.resolveLoadPath_(ref)}`;- let entry = this.preparedPrefabs_.get(key);- if (!entry) {- entry = { holders: 0, prepared: await preparePrefab(this, ref) };- this.preparedPrefabs_.set(key, entry);- }- const held = entry;- const receipt = (): AssetLease<PreparedPrefab> => {- held.holders++;- let released = false;- return {- key,- generation: 0,- value: held.prepared,- release: () => {- if (released) return;- released = true;- if (--held.holders > 0) return;- this.preparedPrefabs_.delete(key);- held.prepared.release();- },- // A second receipt for the same preparation — the splitting owner- // stays bound to this one, which is the point of splitting.- retain: () => receipt(),- };- };- return receipt();+ /** A generation-bound recipe through the ordinary typed-asset door. */+ private preparePrefabLease_(ref: string): Promise<AssetLease<PreparedPrefab>> {+ return this.acquireTypedLease_<PreparedPrefab>('prepared-prefab', ref);+ }++ private bakePrefab_(path: string, ctx: LoadContext & { recorder: DependencyRecorder },+ overrides: readonly PrefabOverride[] = []): Promise<PreparedPrefab> {+ return preparePrefabFromSource({+ loadPrefab: async (ref) => (await ctx.acquireAsset<PrefabResult>('prefab', ref)).value,+ preloadSceneAssets: scene => this.preloadSceneAssets_(scene, undefined, undefined, ctx.recorder),+ resolveSceneAssetPaths: (scene, result) => this.resolveSceneAssetPaths(scene, result),+ trackSceneAssetReferences: (scene, entities) => this.trackSceneAssetReferences(scene, entities),+ resolveRef: ref => this.resolveRef(ref),+ entityScopes: this.entityScopes,+ }, path, overrides);}/**@@ -2653,35 +2750,61 @@ export class Assets {private async prepared_<T extends object>(work: (ctx: LoadContext) => Promise<T>,): Promise<T & Preparation> {+ this.assertLoading_();const recorder = new DependencyRecorder();+ this.preparations_.add(recorder);try {return recorder.commit(await work(this.recordingContext_(recorder)));} catch (e) {- recorder.rollback();- throw e;- }+ throw recorder.abort(e);+ } finally { this.preparations_.delete(recorder); }}/** The load context one preparation sees: every door that takes something* reports it, and the plain readers stay plain. */- private recordingContext_(recorder: DependencyRecorder): LoadContext {+ private recordingContext_(recorder: DependencyRecorder): LoadContext & { recorder: DependencyRecorder } {const base = this.getLoadContext_();+ const epoch = this.resetEpoch_;+ const attempt = async <T>(ref: string, work: () => Promise<T>): Promise<T> => {+ try { this.assertLoading_(epoch); return await work(); }+ catch (error) { recorder.failed(ref, error); throw preparationFailureReason(error); }+ };+ const read = async <T>(ref: string, work: () => Promise<T>): Promise<T> => {+ const result = await attempt(ref, work);+ this.assertLoading_(epoch);+ return result;+ };+ const take = async <T>(ref: string, work: () => Promise<AssetLease<T>>, type?: string): Promise<AssetLease<T>> => {+ // Own first: if teardown crossed this await, rollback must still+ // return the receipt before the obsolete loader sees its value.+ const lease = recorder.own(ref, await attempt(ref, work), type);+ this.assertLoading_(epoch);+ return lease;+ };return {...base,+ recorder,+ loadText: path => read(path, () => base.loadText(path)),+ loadBinary: path => read(path, () => base.loadBinary(path)),+ loadTexture: (path, flipY) => read(path, () => base.loadTexture(path, flipY)),+ decodePixels: path => read(path, () => base.decodePixels!(path)),acquireTexture: async (path, flipY) =>- recorder.own(path, await base.acquireTexture(path, flipY), 'texture'),- acquireAsset: async (type, ref) => recorder.own(ref, await base.acquireAsset(type, ref), type),- preparePrefab: async (ref) => recorder.own(ref, await this.preparePrefabLease_(ref), 'prefab'),+ take(path, () => base.acquireTexture(path, flipY), 'texture'),+ acquireAsset: async (type, ref) => take(ref, () => this.acquireTypedLease_(type, ref), type),+ preparePrefab: async (ref) => take(ref, () => this.preparePrefabLease_(ref), 'prepared-prefab'),createOwnedTexture: async (width, height, pixels, flipY) => {+ this.assertLoading_(epoch);const lease = await base.createOwnedTexture!(width, height, pixels, flipY);- return recorder.own(`composed:${lease.value.handle}`, lease);+ recorder.own(`composed:${lease.value.handle}`, lease);+ this.assertLoading_(epoch);+ return lease;},readSource: async (ref) => {// The edge records what was ASKED for; where the build put// those bytes is this door's business, as it is for a texture.// A loader resolving first records an identity nothing names.recorder.read(ref);- return base.loadText(this.catalog.getBuildPath(ref));+ return read(ref, () => base.loadText(this.catalog.getBuildPath(ref)));},};}diff --git a/sdk/src/asset/AsyncCache.ts b/sdk/src/asset/AsyncCache.tsindex d1860544f..212897e02 100644--- a/sdk/src/asset/AsyncCache.ts+++ b/sdk/src/asset/AsyncCache.ts@@ -2,6 +2,7 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport { RuntimeConfig } from '../defaults';import { log } from '../util/logger';+import { preparationFailureReason } from './dependencies';interface PendingEntry<T> {promise: Promise<T>;@@ -27,6 +28,16 @@ export class AsyncCache<T> {*/constructor(private dispose_?: (value: T) => void) {}+ /** Current cooldown rejections; expired records retain no failure metadata. */+ /** @internal Failed preparation provenance for source invalidation. */+ *failures(): Generator<[string, Error]> {+ const now = Date.now();+ for (const [key, failure] of this.failed_) {+ if (failure.expiry <= now) { this.failed_.delete(key); continue; }+ yield [key, failure.error];+ }+ }+async getOrLoad(key: string, loader: () => Promise<T>, timeout = RuntimeConfig.assetLoadTimeout): Promise<T> {const cached = this.cache_.get(key);if (cached !== undefined) {@@ -66,20 +77,24 @@ export class AsyncCache<T> {() => { /* loader rejected — nothing to release */ },);- const result = await Promise.race([- loaderPromise,- new Promise<never>((_, reject) => {- timer = setTimeout(() => {- timedOut = true;- entry.aborted = true;- reject(new Error(`AsyncCache timeout: ${key} (${timeout}ms)`));- }, timeout);- }),- ]);-- // Loader won the race: cancel the deadline so it can't abort after- // the fact, then cache (unless invalidate() aborted it in-flight).- clearTimeout(timer);+ let result: T;+ try {+ result = await Promise.race([+ loaderPromise,+ new Promise<never>((_, reject) => {+ timer = setTimeout(() => {+ timedOut = true;+ entry.aborted = true;+ reject(new Error(`AsyncCache timeout: ${key} (${timeout}ms)`));+ }, timeout);+ }),+ ]);+ } finally {+ // Rejection also settles the race and no longer needs a deadline.+ clearTimeout(timer);+ }++ // Cache unless invalidate() aborted this request in-flight.if (!entry.aborted) this.cache_.set(key, result);this.clearPendingIfCurrent_(key, entry);return result;@@ -96,7 +111,7 @@ export class AsyncCache<T> {const current = this.pending_.get(key) === entry;if (current) {this.pending_.delete(key);- if (err instanceof Error) {+ if (err instanceof Error && preparationFailureReason(err) instanceof Error) {this.failed_.set(key, { error: err, expiry: Date.now() + RuntimeConfig.assetFailureCooldown });}}diff --git a/sdk/src/asset/SceneHandle.ts b/sdk/src/asset/SceneHandle.tsindex 11fb2d36c..36e8a1b0b 100644--- a/sdk/src/asset/SceneHandle.ts+++ b/sdk/src/asset/SceneHandle.ts@@ -1,6 +1,9 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport type { Entity } from '../types';+import { disposeAll } from '../util/disposeAll';++const releaseCallback = (callback: ReleaseCallback): void => callback();export type ReleaseCallback = () => void;@@ -21,9 +24,8 @@ export class SceneHandle {release(): void {if (this.released_) return;this.released_ = true;- for (const cb of this.releaseCallbacks_) {- cb();- }+ const callbacks = this.releaseCallbacks_;this.releaseCallbacks_ = [];+ disposeAll(callbacks, releaseCallback);}}diff --git a/sdk/src/asset/assetReferenceTracking.ts b/sdk/src/asset/assetReferenceTracking.tsnew file mode 100644index 000000000..cd54fe0ab--- /dev/null+++ b/sdk/src/asset/assetReferenceTracking.ts@@ -0,0 +1,17 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import type { World } from '../ecs/world';+import type { Assets } from './Assets';+import { AssetRefCounter } from './AssetRefCounter';++const subscribed = new WeakSet<World>();++/** One World observer, resolving its current asset resource at notification time. */+export function bindAssetReferenceTracking(+ world: World, assets: Assets, current: () => Assets | null | undefined,+): void {+ if (!assets.getRefCounter()) assets.setRefCounter(new AssetRefCounter());+ if (subscribed.has(world)) return;+ subscribed.add(world);+ world.onDespawn(entity => current()?.getRefCounter()?.removeAllRefsForEntity(entity));+}diff --git a/sdk/src/asset/dependencies.ts b/sdk/src/asset/dependencies.tsindex 91298bee0..9609d254e 100644--- a/sdk/src/asset/dependencies.ts+++ b/sdk/src/asset/dependencies.ts@@ -69,6 +69,9 @@ export interface Preparation {readonly dependencies: AssetScope;/** Every edge it produced, owned and source alike. */readonly edges: readonly DependencyReceipt[];+ /** An optional dependency was unavailable; initial degraded loads may run,+ * but a refresh must not replace a working era with one missing it. */+ readonly failedDependencies?: readonly string[];}/**@@ -142,6 +145,20 @@ export function rebuildPlan(*/export type PreparedLoad<T> = Preparation & { readonly value: T };+/** Internal rejection transport. Its sources belong to this preparation, not+ * to an Error object that several concurrent loaders may reuse. Public doors+ * rethrow the original reason, including primitive rejection values. */+export class PreparationFailure extends Error {+ constructor(readonly reason: unknown, readonly sources: readonly string[]) {+ super(reason instanceof Error ? reason.message : String(reason));+ }+ override toString(): string { return String(this.reason); }+}++export function preparationFailureReason(error: unknown): unknown {+ return error instanceof PreparationFailure ? error.reason : error;+}+/*** The recorder behind one preparation: everything it acquires lands here, so* neither the era's ownership nor the graph's edges depend on a loader@@ -155,6 +172,7 @@ export type PreparedLoad<T> = Preparation & { readonly value: T };export class DependencyRecorder {private readonly edges_: DependencyReceipt[] = [];private readonly acquired_ = new AssetScope();+ private readonly failed_ = new Set<string>();private state_: 'open' | 'committed' | 'rolled-back' = 'open';/** A runtime resource this preparation now holds. */@@ -162,6 +180,9 @@ export class DependencyRecorder {if (this.state_ !== 'open') return this.late_(lease);this.acquired_.add(lease);this.edges_.push(type === undefined ? { kind: 'owned', path } : { kind: 'owned', type, path });+ // The acquisition succeeded, but may hold a degraded preparation. Its+ // owned edge carries causality; its readiness must reach this owner too.+ for (const path of lease.failedDependencies ?? []) this.failed_.add(path);return lease;}@@ -171,6 +192,15 @@ export class DependencyRecorder {this.edges_.push({ kind: 'source', path });}+ failed(path: string, error?: unknown): void {+ if (this.state_ !== 'open') return;+ this.read(path);+ this.failed_.add(path);+ if (error instanceof PreparationFailure) {+ for (const source of error.sources) this.read(source);+ }+ }+/*** The preparation produced `value`: what it took is what that value owns.*@@ -180,14 +210,25 @@ export class DependencyRecorder {*/commit<T extends object>(value: T): T & Preparation {this.state_ = 'committed';- return { ...value, dependencies: this.acquired_, edges: this.edges_ };+ return { ...value, dependencies: this.acquired_, edges: this.edges_, failedDependencies: [...this.failed_] };}/** The preparation produced nothing, so it may keep nothing. */rollback(): void {this.state_ = 'rolled-back';- this.acquired_.releaseAll();- this.edges_.length = 0;+ try { this.acquired_.releaseAll(); } finally { this.edges_.length = 0; }+ }++ /** Roll back ownership while transporting the reads that caused failure. */+ abort(error: unknown): PreparationFailure {+ const sources = new Set(this.edges_.filter(isInvalidatable).map(edge => edge.path));+ const reason = preparationFailureReason(error);+ if (error instanceof PreparationFailure) for (const source of error.sources) {+ sources.add(source);+ }+ try { this.rollback(); }+ catch (cleanupError) { log.warn('asset', 'Preparation rollback cleanup failed', cleanupError); }+ return new PreparationFailure(reason, [...sources]);}/**diff --git a/sdk/src/asset/entityAssetScopes.ts b/sdk/src/asset/entityAssetScopes.tsindex 69794ec30..8d0ac6698 100644--- a/sdk/src/asset/entityAssetScopes.ts+++ b/sdk/src/asset/entityAssetScopes.ts@@ -18,9 +18,7 @@ import type { World } from '../ecs/world';import { AssetScope } from './AssetLease';export class EntityAssetScopes {- private scopes_ = new Map<Entity, AssetScope>();- private world_: World | null = null;- private unbind_: (() => void) | null = null;+ private worlds_ = new Map<World, { scopes: Map<Entity, AssetScope>; unbind: () => void }>();/*** The scope this entity owns, created on first use.@@ -30,34 +28,55 @@ export class EntityAssetScopes {* here — before any scope exists there is nothing that could be missed.*/ensure(world: World, entity: Entity): AssetScope {- this.bind_(world);- let scope = this.scopes_.get(entity);+ if (!world.valid(entity) || world.isDestructionPending(entity)) {+ throw new Error(`Cannot own resources for entity ${entity}: destroyed or pending destruction`);+ }+ const scopes = this.bind_(world);+ let scope = scopes.get(entity);if (!scope) {scope = new AssetScope();- this.scopes_.set(entity, scope);+ scopes.set(entity, scope);}return scope;}/** What this entity owns, or null when it owns nothing of its own. */- scopeFor(entity: Entity): AssetScope | null {- return this.scopes_.get(entity) ?? null;+ scopeFor(entity: Entity, world?: World): AssetScope | null {+ if (world) return this.worlds_.get(world)?.scopes.get(entity) ?? null;+ let found: AssetScope | null = null;+ for (const { scopes } of this.worlds_.values()) {+ const scope = scopes.get(entity);+ if (!scope) continue;+ // An id alone cannot distinguish entities in different worlds.+ if (found) return null;+ found = scope;+ }+ return found;}/** Live per-entity scopes. Diagnostics and the resource census. */get size(): number {- return this.scopes_.size;+ let total = 0;+ for (const { scopes } of this.worlds_.values()) total += scopes.size;+ return total;}- private bind_(world: World): void {- if (this.world_ === world) return;- this.unbind_?.();- this.world_ = world;- this.unbind_ = world.onDespawn((entity) => {- const scope = this.scopes_.get(entity);+ private bind_(world: World): Map<Entity, AssetScope> {+ const existing = this.worlds_.get(world);+ if (existing) return existing.scopes;+ const entry = { scopes: new Map<Entity, AssetScope>(), unbind: () => {} };+ this.worlds_.set(world, entry);+ entry.unbind = world.onDespawn((entity) => {+ const scope = entry.scopes.get(entity);if (!scope) return;- this.scopes_.delete(entity);- scope.releaseAll();+ entry.scopes.delete(entity);+ try { scope.releaseAll(); } finally {+ if (!entry.scopes.size && this.worlds_.get(world) === entry) {+ this.worlds_.delete(world);+ entry.unbind();+ }+ }});+ return entry.scopes;}}diff --git a/sdk/src/asset/loaders/MaterialAssetLoader.ts b/sdk/src/asset/loaders/MaterialAssetLoader.tsindex 325be397c..4f3d0ca32 100644--- a/sdk/src/asset/loaders/MaterialAssetLoader.ts+++ b/sdk/src/asset/loaders/MaterialAssetLoader.ts@@ -1,19 +1,16 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport type { AssetLoader, LoadContext, MaterialResult } from '../AssetLoader';-import { BUILTIN_REF_PREFIX, isBuiltinAssetRef, resolveDocumentRef } from '../documentRef';-import type { MaterialAssetData, ShaderHandle } from '../../render/material';+import { isBuiltinAssetRef, resolveDocumentRef } from '../documentRef';+import type { MaterialAssetData } from '../../render/material';import { Material } from '../../render/material';-import { builtinShaderTemplate } from '../../render/builtinShaders';-import { AsyncCache } from '../AsyncCache';+import type { MaterialShaderSource } from './MaterialShaderAssetLoader';import { log } from '../../util/logger';export class MaterialAssetLoader implements AssetLoader<MaterialResult> {readonly type = 'material';readonly extensions = ['.esmaterial'];- private shaderCache_ = new AsyncCache<ShaderHandle>();-async load(path: string, ctx: LoadContext): Promise<MaterialResult> {const buildPath = ctx.catalog.getBuildPath(path);const text = await ctx.loadText(buildPath);@@ -36,7 +33,9 @@ export class MaterialAssetLoader implements AssetLoader<MaterialResult> {// Enabled static switches select the shader permutation (compiled once per switch-set).const features = enabledSwitches(data.switches);- const shaderHandle = await this.loadShader(path, data.shader, features, ctx);+ const shaderPath = isBuiltinAssetRef(data.shader) ? data.shader : resolveDocumentRef(path, data.shader);+ const source = await ctx.acquireAsset<MaterialShaderSource>('material-shader', shaderPath);+ const shaderHandle = source.value.compile(features);const handle = Material.createFromAsset(data, shaderHandle);await this.applyTextureProps(handle, data, path, ctx);@@ -70,42 +69,6 @@ export class MaterialAssetLoader implements AssetLoader<MaterialResult> {Material.release(asset.handle);}- releaseAll(): void {- this.shaderCache_.clearAll();- }-- // Compile a material's shader ref — either a `builtin:<id>` stock template (from its in-code- // source, no file) or a path to a project `.esshader` resolved relative to the material. One- // compiled program per (resolved key, enabled-switch set) — distinct switch sets are distinct- // permutations, so the cache key folds the sorted features in.- private async loadShader(matPath: string, ref: string, features: string[], ctx: LoadContext): Promise<ShaderHandle> {- const isBuiltin = isBuiltinAssetRef(ref);- const key = isBuiltin ? ref : resolveDocumentRef(matPath, ref);- const cacheKey = features.length ? `${key}#${features.join('|')}` : key;- const cached = this.shaderCache_.get(cacheKey);- if (cached !== undefined) return cached;-- return this.shaderCache_.getOrLoad(cacheKey, async () => {- let content: string;- if (isBuiltin) {- const template = builtinShaderTemplate(ref.slice(BUILTIN_REF_PREFIX.length));- if (!template) {- throw new Error(`Unknown built-in shader: ${ref}`);- }- content = template.source;- } else {- content = await ctx.loadText(ctx.catalog.getBuildPath(key));- }- // Compile through ShaderParser (engine-side): assembles the stages + the enabled- // switch permutation, generates the std140 MaterialConstants block from #pragma param,- // and registers the layout so the material's parameters reach the GPU.- const handle = Material.compileShader(content, features);- if (!handle) {- throw new Error(`Failed to compile material shader: ${key}`);- }- return handle;- });- }}// The enabled static switches, sorted for a stable permutation cache key.diff --git a/sdk/src/asset/loaders/MaterialShaderAssetLoader.ts b/sdk/src/asset/loaders/MaterialShaderAssetLoader.tsnew file mode 100644index 000000000..85ea01347--- /dev/null+++ b/sdk/src/asset/loaders/MaterialShaderAssetLoader.ts@@ -0,0 +1,48 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import type { AssetLoader, LoadContext } from '../AssetLoader';+import { BUILTIN_REF_PREFIX, isBuiltinAssetRef } from '../documentRef';+import { builtinShaderTemplate } from '../../render/builtinShaders';+import { Material, type ShaderHandle } from '../../render/material';+import { disposeAll } from '../../util/disposeAll';++/** One source era owns every permutation compiled from those exact bytes. */+export class MaterialShaderSource {+ private programs_ = new Map<string, ShaderHandle>();+ constructor(private readonly path_: string, private readonly source_: string) {}++ compile(features: string[]): ShaderHandle {+ const key = JSON.stringify(features);+ const cached = this.programs_.get(key);+ if (cached !== undefined) return cached;+ const handle = Material.compileShader(this.source_, features);+ if (!handle) throw new Error(`Failed to compile material shader: ${this.path_}`);+ this.programs_.set(key, handle);+ return handle;+ }++ release(): void {+ const handles = [...this.programs_.values()];+ this.programs_.clear();+ disposeAll(handles, handle => Material.releaseShader(handle));+ }+}++export class MaterialShaderAssetLoader implements AssetLoader<MaterialShaderSource> {+ readonly type = 'material-shader';+ readonly extensions = ['.esshader'];++ async load(path: string, ctx: LoadContext): Promise<MaterialShaderSource> {+ let source: string;+ if (isBuiltinAssetRef(path)) {+ const template = builtinShaderTemplate(path.slice(BUILTIN_REF_PREFIX.length));+ if (!template) throw new Error(`Unknown built-in shader: ${path}`);+ source = template.source;+ } else {+ source = ctx.readSource ? await ctx.readSource(path) : await ctx.loadText(ctx.catalog.getBuildPath(path));+ }+ return new MaterialShaderSource(path, source);+ }++ unload(source: MaterialShaderSource): void { source.release(); }+}diff --git a/sdk/src/asset/registryAssets.ts b/sdk/src/asset/registryAssets.tsindex 487ce5650..95a09ab74 100644--- a/sdk/src/asset/registryAssets.ts+++ b/sdk/src/asset/registryAssets.ts@@ -24,6 +24,9 @@*/import type { AssetLease } from './AssetLease';import type { DependencyReceipt, Preparation } from './dependencies';+import { disposeAll } from '../util/disposeAll';++const releaseEra = (era: Preparation | null): void => era?.dependencies.releaseAll();/** What one preparation PRODUCED. What it took is recorded for it — see* dependencies.ts — so an era cannot describe a dependency it does not have. */@@ -136,6 +139,10 @@ export class RegistryAssetSlots {if (!slot?.era) return false;const ticket = ++slot.refresh;const era = await kind.prepare(slot.key);+ if (era.failedDependencies?.length) {+ era.dependencies.releaseAll();+ throw new Error(`Cannot refresh "${name}": dependencies did not load: ${era.failedDependencies.join(', ')}`);+ }// Two things can have happened while this prepared: a newer refresh// started, or the last holder let go. Publishing either way puts an era// where nothing will ever release it.@@ -197,12 +204,14 @@ export class RegistryAssetSlots {/** Give up every slot. For a wholesale teardown. */releaseAll(): void {+ const eras: Array<Preparation | null> = [];for (const slot of new Set(this.byName_.values())) {- slot.era?.dependencies.releaseAll();+ eras.push(slot.era);slot.era = null;slot.refs = 0;}this.byName_.clear();+ disposeAll(eras, releaseEra);}/** Drop one claim on the slot `name` resolves to, without its receipt. The@@ -221,6 +230,7 @@ export class RegistryAssetSlots {key: slot.key,generation: slot.id,value: slot.era!.value,+ get failedDependencies() { return slot.era?.failedDependencies; },names: slot.names,release: () => {if (spent) return;@@ -235,10 +245,12 @@ export class RegistryAssetSlots {}private drop_(slot: Slot<unknown>): void {+ if (slot.refs === 0) return; // A wholesale release already retired it.if (--slot.refs > 0) return;- slot.era?.dependencies.releaseAll();+ const era = slot.era;slot.era = null;this.forget_(slot);+ releaseEra(era);}private slotFor_(type: string, key: string): Slot<unknown> {diff --git a/sdk/src/asset/spinePairKey.ts b/sdk/src/asset/spinePairKey.tsnew file mode 100644index 000000000..2120f96b4--- /dev/null+++ b/sdk/src/asset/spinePairKey.ts@@ -0,0 +1,7 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team++/** The identity of a Spine asset: its skeleton and atlas references together. */+export function spinePairKey(skeleton: string, atlas: string): string {+ return `${skeleton}:${atlas}`;+}diff --git a/sdk/src/camera/CameraPlugin.ts b/sdk/src/camera/CameraPlugin.tsindex 772edd01b..109188606 100644--- a/sdk/src/camera/CameraPlugin.ts+++ b/sdk/src/camera/CameraPlugin.ts@@ -265,10 +265,9 @@ function readCameraPOV(}/**- * Build the renderer-facing CameraInfo from a POV. `canvas` (when given) applies- * the design-resolution ortho scaling for scene cameras; pass null to use the raw- * orthoSize (the editor view does this, for predictable zoom). Rotation is applied- * here via invertViewZ.+ * Apply design-resolution ortho scaling only to full-screen scene cameras.+ * Sub-viewport and texture cameras keep their authored zoom; null `canvas`+ * preserves raw orthoSize for editor views. Rotation uses invertViewZ.*/export function buildCameraInfo(pov: CameraPOV,@@ -278,6 +277,11 @@ export function buildCameraInfo(pool: CameraInfo[],index: number,): CameraInfo {+ // Projection and pixel snapping must use the same surface the render pass+ // uses; a portrait target on a landscape window otherwise stretches the view.+ const target = pov.renderTarget ? renderTargetSize(pov.renderTarget) : null;+ width = target?.width ?? width;+ height = target?.height ?? height;const aspect = (pov.viewport.z * width) / (pov.viewport.w * height);let projection: Float32Array;let halfW = 0;@@ -285,7 +289,7 @@ export function buildCameraInfo(if (pov.projection === ProjectionType.Orthographic) {halfH = pov.orthoSize;- if (canvas) {+ if (canvas && (pov.renderTarget ?? 0) === 0 && isFullFrame(pov.viewport)) {const baseOrthoSize = canvas.designResolution.y / 2;const designAspect = canvas.designResolution.x / canvas.designResolution.y;halfH = computeEffectiveOrthoSize(@@ -624,6 +628,12 @@ function sameMatrix(a: Float32Array, b: Float32Array): boolean {return true;}+// Texture passes run first, but only a screen camera can describe where a+// pointer lands or what the composited screen was drawn through.+function primaryScreenCamera(cameras: CameraInfo[]): CameraInfo | null {+ return cameras.find(cam => cam.renderTarget === 0) ?? null;+}+function syncUICameraInfo(app: App,module: ESEngineModule | null,@@ -638,8 +648,8 @@ function syncUICameraInfo(}publishScreenLayout(app, module, cppRegistry, width, height);const uiCam = app.getResource(UICameraInfo);- if (cameras.length > 0) {- const cam = cameras[0];+ const cam = primaryScreenCamera(cameras);+ if (cam) {uiCam.viewProjection.set(cam.viewProjection);// In the same statement group as the write it names: a revision published// apart from the matrix is a reader's chance to see one without the other.@@ -704,9 +714,14 @@ function publishScreenOverlay(// statement about layers rather than about geometry, so it survives the// screen leaving the cameras' passes.let mask = 0;- for (const cam of cameras) mask |= cam.cullingMask ?? 0xFFFFFFFF;- overlay.layerMask = (cameras.length > 0 ? mask : 0xFFFFFFFF) >>> 0;- const primary = cameras[0];+ let hasScreenCamera = false;+ for (const cam of cameras) {+ if (cam.renderTarget !== 0) continue;+ hasScreenCamera = true;+ mask |= cam.cullingMask ?? 0xFFFFFFFF;+ }+ overlay.layerMask = (hasScreenCamera ? mask : 0xFFFFFFFF) >>> 0;+ const primary = primaryScreenCamera(cameras);if (uiCam.valid && primary?.entity === EDITOR_VIEW_ENTITY) {overlay.projection.set(uiCam.viewProjection);@@ -904,7 +919,7 @@ export function cameraPlugin(// The frame is drawn; say which camera drew it. After the// submit, so nothing can publish a commit for a picture that// then failed to render.- commitCamera(app, cameras.length > 0 ? cameras[0] : null, app.getResource(UICameraInfo));+ commitCamera(app, primaryScreenCamera(cameras), app.getResource(UICameraInfo));},};@@ -943,9 +958,14 @@ export function renderCameraFrame(app: App, width: number, height: number, entitpipeline.beginFrame(elapsed);try {Renderer.updateTransforms({ _cpp: registry });+ // An authored-camera preview ignores director selection (so an inactive+ // camera can be inspected), but uses the same project fit as gameplay.const cameras = entity === undefined? resolveCameras(app, module, registry, width, height, app.world, undefined, [], elapsed, false)- : collectCameras(module, registry, width, height, app.world).filter(c => c.entity === entity);+ : collectCameraPOVs(module, registry, width, height, app.world)+ .filter(pov => pov.entity === entity)+ .map((pov, i) => buildCameraInfo(pov, width, height,+ resolveFitSource(app, findCanvasData(module, registry, app.world)), [], i));if (!cameras.length) return false;const canvasEntity = canvasEntityOf(module, registry);const clearColor = canvasEntity >= 0 ? registry.getCanvas(canvasEntity).backgroundColor : undefined;diff --git a/sdk/src/document/diagnostics.ts b/sdk/src/document/diagnostics.tsindex 4d79d996c..a811e0a22 100644--- a/sdk/src/document/diagnostics.ts+++ b/sdk/src/document/diagnostics.ts@@ -54,6 +54,18 @@ export interface DocumentNode {/** Whether a document names its entities by string or by number, for messages. */const quote = (id: DocumentEntityId): string => (typeof id === 'string' ? `"${id}"` : String(id));+/** @internal Index wide immutable link lists once; tiny lists need no index. */+export function createChildLookup<Id extends DocumentEntityId>(): (children: readonly Id[], id: Id) => boolean {+ let indexes: Map<readonly Id[], ReadonlySet<Id>> | undefined;+ return (children, id) => {+ if (children.length <= 8) return children.includes(id);+ indexes ??= new Map();+ let index = indexes.get(children);+ if (!index) { index = new Set(children); indexes.set(children, index); }+ return index.has(id);+ };+}+/*** Ids are unique, and no entity carries the same component twice. A repeated id* is the finding nothing downstream can work around: a loader keying by id keeps@@ -96,13 +108,14 @@ export function checkDocumentTopology(byId: ReadonlyMap<DocumentEntityId, DocumentNode>,push: DiagnosticSink,): void {+ const hasChild = createChildLookup<DocumentEntityId>();for (const node of nodes) {if (node.parent !== null) {const parent = byId.get(node.parent);if (!parent) {push('missing-parent', 'error',`entity ${quote(node.id)} parent ${quote(node.parent)} does not exist`, node.id);- } else if (!parent.children.includes(node.id)) {+ } else if (!hasChild(parent.children, node.id)) {push('inconsistent-topology', 'error',`entity ${quote(node.id)} claims parent ${quote(node.parent)} but that parent's children omit it`, node.id);}@@ -132,24 +145,25 @@ export function checkParentCycle(const WHITE = 0, GRAY = 1, BLACK = 2;const color = new Map<DocumentEntityId, number>();for (const node of nodes) color.set(node.id, WHITE);- let reported = false;-- const visit = (id: DocumentEntityId, path: DocumentEntityId[]): void => {- if (reported) return;- const c = color.get(id);- if (c === BLACK) return;- if (c === GRAY) {- const cycle = path.slice(path.indexOf(id)).concat(id).map(String).join(' → ');- push('parent-cycle', 'error', `parent cycle detected: ${cycle}`, id);- reported = true;- return;+ // A document has at most one parent per node. Walk each unvisited chain+ // iteratively: no call-stack ceiling and no copying the ancestor path at+ // every depth. Each link is examined once, regardless of serialized order.+ for (const node of nodes) {+ if (color.get(node.id) === BLACK) continue;+ const path: DocumentEntityId[] = [];+ let id: DocumentEntityId | null = node.id;+ while (id !== null && byId.has(id) && color.get(id) !== BLACK) {+ if (color.get(id) === GRAY) {+ const cycle = path.slice(path.indexOf(id)).concat(id).map(String).join(' → ');+ push('parent-cycle', 'error', `parent cycle detected: ${cycle}`, id);+ return;+ }+ color.set(id, GRAY);+ path.push(id);+ id = byId.get(id)!.parent;}- color.set(id, GRAY);- const node = byId.get(id);- if (node && node.parent !== null && byId.has(node.parent)) visit(node.parent, [...path, id]);- color.set(id, BLACK);- };- for (const node of nodes) visit(node.id, []);+ for (const visited of path) color.set(visited, BLACK);+ }}/**diff --git a/sdk/src/dragonbones/DragonBonesManager.ts b/sdk/src/dragonbones/DragonBonesManager.tsindex 593f21d04..d66181094 100644--- a/sdk/src/dragonbones/DragonBonesManager.ts+++ b/sdk/src/dragonbones/DragonBonesManager.ts@@ -57,6 +57,7 @@ export class DragonBonesManager {private readonly entities_ = new Map<Entity, EntityInfo>();private readonly disabled_ = new Set<Entity>();private readonly skeletons_ = new Map<string, { handle: number; refcount: number }>();+ private readonly unkeyedSkeletons_ = new Map<number, number>();constructor(controller: DragonBonesModuleController) {this.controller_ = controller;@@ -83,6 +84,7 @@ export class DragonBonesManager {return -1;}if (assetKey !== undefined) this.skeletons_.set(assetKey, { handle, refcount: 0 });+ else this.unkeyedSkeletons_.set(handle, 0);return handle;}@@ -97,18 +99,21 @@ export class DragonBonesManager {// — Entities —————————————————————————————————————————————————————————————- /** Attach an armature to `entity`. Replaces whatever it had. */+ /** Replace an armature only after its new instance and ownership are valid. */addEntity(entity: Entity, skeletonHandle: number, options: DragonBonesEntityOptions): boolean {- this.removeEntity(entity);-+ const previous = this.entities_.get(entity);+ const shared = options.assetKey === undefined ? undefined : this.skeletons_.get(options.assetKey);+ if (options.assetKey !== undefined && (!shared || shared.handle !== skeletonHandle)) return false;+ if (options.assetKey === undefined && [...this.skeletons_.values()].some(s => s.handle === skeletonHandle)) return false;+ if (previous?.skeletonHandle === skeletonHandle && previous.assetKey !== options.assetKey) return false;const instanceId = this.controller_.createInstance(skeletonHandle, options.armature);if (instanceId < 0) return false;-- if (options.assetKey !== undefined) {- const shared = this.skeletons_.get(options.assetKey);- if (shared) shared.refcount++;+ if (shared) shared.refcount++;+ else this.unkeyedSkeletons_.set(skeletonHandle, (this.unkeyedSkeletons_.get(skeletonHandle) ?? 0) + 1);+ if (previous) {+ this.controller_.destroyInstance(previous.instanceId);+ this.releaseSkeleton_(previous);}-const info: EntityInfo = {skeletonHandle,instanceId,@@ -220,9 +225,10 @@ export class DragonBonesManager {// — Frame ————————————————————————————————————————————————————————————————- updateAnimations(dt: number): void {+ /** Freeze inactive entities without changing their manual enable state. */+ updateAnimations(dt: number, isActive?: (entity: Entity) => boolean): void {for (const [entity, info] of this.entities_) {- if (this.disabled_.has(entity)) continue;+ if (this.disabled_.has(entity) || (isActive && !isActive(entity))) continue;// Paused armatures fall through to submitMeshes, which still draws the// pose they are holding.if (!info.playing) continue;@@ -230,9 +236,10 @@ export class DragonBonesManager {}}- submitMeshes(core: SkeletalSubmitCore, registry: unknown, materialOf?: SkeletalMaterialOf): void {+ /** Skip extraction for entities the activity predicate excludes. */+ submitMeshes(core: SkeletalSubmitCore, registry: unknown, materialOf?: SkeletalMaterialOf, isActive?: (entity: Entity) => boolean): void {for (const [entity, info] of this.entities_) {- if (this.disabled_.has(entity)) continue;+ if (this.disabled_.has(entity) || (isActive && !isActive(entity))) continue;// False means the core cannot take geometry at all, so asking again for// the next entity would only repeat the same check.const accepted = submitEntityMeshes(core, registry, entity, info, cb =>@@ -251,15 +258,22 @@ export class DragonBonesManager {for (const shared of this.skeletons_.values()) {this.controller_.unloadSkeleton(shared.handle);}+ for (const handle of this.unkeyedSkeletons_.keys()) this.controller_.unloadSkeleton(handle);this.entities_.clear();this.disabled_.clear();this.skeletons_.clear();+ this.unkeyedSkeletons_.clear();}/** One reference gone; a shared skeleton unloads when the last one does. */private releaseSkeleton_(info: EntityInfo): void {if (info.assetKey === undefined) {- this.controller_.unloadSkeleton(info.skeletonHandle);+ const refs = (this.unkeyedSkeletons_.get(info.skeletonHandle) ?? 1) - 1;+ if (refs > 0) this.unkeyedSkeletons_.set(info.skeletonHandle, refs);+ else {+ this.controller_.unloadSkeleton(info.skeletonHandle);+ this.unkeyedSkeletons_.delete(info.skeletonHandle);+ }return;}const shared = this.skeletons_.get(info.assetKey);diff --git a/sdk/src/dragonbones/DragonBonesPlugin.ts b/sdk/src/dragonbones/DragonBonesPlugin.tsindex af74b80fa..9e8b8e9ef 100644--- a/sdk/src/dragonbones/DragonBonesPlugin.ts+++ b/sdk/src/dragonbones/DragonBonesPlugin.ts@@ -85,6 +85,7 @@ export class DragonBonesPlugin implements Plugin {build(app: App): void {this.app_ = app;+ const isActive = (e: Entity) => app.world.isEntityActive(e);app.insertResource(DragonBones, this.manager_);this.despawnUnsub_ = app.world.onDespawn((entity: Entity) => {@@ -99,7 +100,7 @@ export class DragonBonesPlugin implements Plugin {const core = engineApi(app);app.pipeline?.addPreFlushCallback(registry => {if (core) this.manager_?.submitMeshes(core, registry._cpp, (e) =>- (app.world.tryGet(e, DragonBonesAnimation)?.material as number | undefined) ?? 0);+ (app.world.tryGet(e, DragonBonesAnimation)?.material as number | undefined) ?? 0, isActive);});}@@ -114,8 +115,8 @@ export class DragonBonesPlugin implements Plugin {const time = app.getResource(Time);const manager = this.manager_;if (!manager) return;- this.enableMirror_.sync(app.world, manager);- manager.updateAnimations(time?.delta ?? 0);+ this.enableMirror_.sync(app.world, manager, isActive);+ manager.updateAnimations(time?.delta ?? 0, isActive);},};// PreUpdate, like Spine: poses have to be current before anything thatdiff --git a/sdk/src/ecs/ScriptPool.ts b/sdk/src/ecs/ScriptPool.tsindex 62091c9f6..9d5780e85 100644--- a/sdk/src/ecs/ScriptPool.ts+++ b/sdk/src/ecs/ScriptPool.ts@@ -22,6 +22,7 @@*/import { entityIndex, type Entity } from '../types';+import { disposeAll } from '../util/disposeAll';/** What a pooled field holds. Booleans are 0/1 in the slot, `true`/`false` out. */export type PoolKind = 'number' | 'boolean';@@ -48,6 +49,9 @@ export interface PoolBlock {* and unreachable is what rows exist to stop being.*/export interface PoolMemory {+ /** Stable allocator ownership, not merely a buffer. Compatible wrappers may+ * reuse existing rows without moving them to a different allocation domain. */+ readonly allocatorIdentity?: object;alloc(bytes: number): PoolBlock;release(block: PoolBlock): void;/**@@ -58,6 +62,16 @@ export interface PoolMemory {current?(block: PoolBlock): ArrayBufferLike;}+interface PoolAssetRefs {+ fields(): readonly { readonly field: string }[];+ addressChanged(): void;+}++interface PoolView {+ readonly value: Record<string, unknown>;+ detach(): void;+}+/** Storage on the JS heap: right for native, useless to a wasm module. */export const HEAP_MEMORY: PoolMemory = {alloc: (bytes) => ({ buffer: new ArrayBuffer(bytes), byteOffset: 0, byteLength: bytes }),@@ -116,14 +130,44 @@ export class ScriptPool {private owners_: Uint32Array;private capacity_: number;private readonly slotOf_ = new Map<Entity, number>();- private readonly views_ = new Map<Entity, Record<string, unknown>>();+ private readonly views_ = new Map<Entity, PoolView>();private readonly free_: number[] = [];private next_ = 0;+ // Portable asset references have no numeric ABI representation yet. Keep+ // them beside the row until resolved, without giving compiled code an+ // address that would silently reinterpret a string as zero.+ private refs_: Map<number, Map<number, string>> | undefined;+ private disposed_ = false;++ get disposed(): boolean { return this.disposed_; }++ dispose(): void {+ if (this.disposed_) return;+ this.disposed_ = true;+ const views = [...this.views_.values()];+ const blocks = [this.rows_, this.sparseBlock_, this.ownersBlock_];+ disposeAll([+ () => this.rebuild_(),+ () => disposeAll(views, view => view.detach()),+ () => {+ this.slotOf_.clear();this.views_.clear();this.refs_?.clear();+ this.free_.length = 0;this.next_ = 0;+ this.slots_ = EMPTY_F64;this.sparse_ = EMPTY_U32;this.owners_ = EMPTY_U32;+ this.rows_ = this.sparseBlock_ = this.ownersBlock_ = EMPTY_BLOCK;+ },+ () => disposeAll(blocks, block => this.memory_.release(block)),+ ], action => action());+ }++ private assertOpen_(): void {+ if (this.disposed_) throw new Error('ScriptPool is disposed');+ }constructor(fields: readonly PoolField[],capacity = 64,private readonly memory_: PoolMemory = HEAP_MEMORY,+ private readonly assetRefs_?: PoolAssetRefs,) {this.fields = fields;this.stride = fields.length * POOL_SLOT_BYTES;@@ -131,15 +175,22 @@ export class ScriptPool {// BOTH allocations before EITHER view. The second can grow the heap, and// a grown heap detaches a view built after the first — which is a bug// this constructor had, and the reason every view is built in one place.- this.rows_ = memory_.alloc(this.capacity_ * this.stride);- this.sparseBlock_ = memory_.alloc(this.capacity_ * 4);- this.sparseLen_ = this.capacity_;- this.ownersBlock_ = memory_.alloc(this.capacity_ * 4);- this.slots_ = EMPTY_F64;- this.sparse_ = EMPTY_U32;- this.owners_ = EMPTY_U32;- this.rebuild_();- this.owners_.fill(POOL_NO_OWNER);+ const allocated: PoolBlock[] = [];+ try {+ this.rows_ = memory_.alloc(this.capacity_ * this.stride);allocated.push(this.rows_);+ this.sparseBlock_ = memory_.alloc(this.capacity_ * 4);allocated.push(this.sparseBlock_);+ this.sparseLen_ = this.capacity_;+ this.ownersBlock_ = memory_.alloc(this.capacity_ * 4);allocated.push(this.ownersBlock_);+ this.slots_ = EMPTY_F64;+ this.sparse_ = EMPTY_U32;+ this.owners_ = EMPTY_U32;+ this.rebuild_();+ this.owners_.fill(POOL_NO_OWNER);+ } catch (error) {+ // Preserve the allocation/view failure even if cleanup also fails.+ try { disposeAll(allocated, block => memory_.release(block)); } catch {}+ throw error;+ }}/**@@ -153,11 +204,12 @@ export class ScriptPool {rows: number; stride: number; sparse: number; sparseCount: number;owners: number; ownerCount: number;} {+ this.assertOpen_();return {rows: this.rows_.byteOffset,stride: this.stride,sparse: this.sparseBlock_.byteOffset,- sparseCount: this.sparse_.length,+ sparseCount: this.sparseLen_,owners: this.ownersBlock_.byteOffset,// The high-water mark, not the size: slots are reused rather than// compacted, so the used prefix has holes and stopping at `size`@@ -166,8 +218,10 @@ export class ScriptPool {};}- /** The sparse table itself, for a host that reads it in this address space. */+ /** The current sparse view. Retrieve it again after pool or heap growth;+ * a held typed array cannot follow replacement or detached memory. */get sparseTable(): Uint32Array {+ this.ensureCurrent_();return this.sparse_;}@@ -178,6 +232,7 @@ export class ScriptPool {* per-entity views read `slots_` on access and need no rebuild.*/refresh(): void {+ this.assertOpen_();this.rebuild_();}@@ -197,9 +252,18 @@ export class ScriptPool {return this.memory_.current?.(block) ?? block.buffer;}- /** The rows themselves. Its byteOffset moves when the pool grows, so an- * address taken from `address` is valid only until the next `put`. */+ private ensureCurrent_(): void {+ // Foreign allocations (resources, compiled scratch, engine assets) can+ // grow the shared WASM heap without passing through ScriptStorage.+ // Live row allocations are never empty; zero means their view detached.+ if (this.slots_.length === 0 && !this.disposed_) this.rebuild_();+ }++ /** The current row view. Retrieve it again after pool or heap growth.+ * Pool growth moves row addresses; foreign heap growth detaches views+ * while allocation addresses stay unchanged. */get buffer(): Float64Array {+ this.ensureCurrent_();return this.slots_;}@@ -207,6 +271,10 @@ export class ScriptPool {return this.slotOf_.size;}+ get hasPortableAssetRefs(): boolean {+ return (this.refs_?.size ?? 0) > 0;+ }+/** Byte offset of `entity`'s row inside `buffer`. */baseOf(entity: Entity): number | undefined {const slot = this.slotOf_.get(entity);@@ -220,8 +288,10 @@ export class ScriptPool {* the next growth, which a one-call lifetime requires anyway.*/address(entity: Entity): number | undefined {- const base = this.baseOf(entity);- return base === undefined ? undefined : this.slots_.byteOffset + base;+ const slot = this.slotOf_.get(entity);+ if (slot === undefined || this.refs_?.has(slot)) return undefined;+ // Addresses belong to allocations, not detachable typed-array views.+ return this.rows_.byteOffset + slot * this.stride;}has(entity: Entity): boolean {@@ -230,7 +300,7 @@ export class ScriptPool {/** The live view, or undefined when the entity does not carry this. */get(entity: Entity): Record<string, unknown> | undefined {- return this.views_.get(entity);+ return this.views_.get(entity)?.value;}/**@@ -240,6 +310,8 @@ export class ScriptPool {*/put(entity: Entity, defaults: Record<string, unknown>, data?: Record<string, unknown>):{ view: Record<string, unknown>; isNew: boolean } {+ this.assertOpen_();+ this.ensureCurrent_();let slot = this.slotOf_.get(entity);const isNew = slot === undefined;if (slot === undefined) {@@ -254,14 +326,20 @@ export class ScriptPool {this.writeAll_(slot, defaults);}if (data) this.writeSome_(slot, data);- return { view: this.views_.get(entity)!, isNew };+ return { view: this.views_.get(entity)!.value, isNew };}delete(entity: Entity): boolean {const slot = this.slotOf_.get(entity);if (slot === undefined) return false;+ // A retained component becomes an ordinary detached value, matching+ // object storage. It must never alias the next owner of this slot.+ const buffer = this.memory_.current?.(this.rows_) ?? this.rows_.buffer;+ if (this.slots_.buffer !== buffer) this.rebuild_();+ this.views_.get(entity)!.detach();this.slotOf_.delete(entity);this.views_.delete(entity);+ this.refs_?.delete(slot);this.mark_(entity, POOL_ABSENT);this.owners_[slot] = POOL_NO_OWNER;this.free_.push(slot);@@ -294,7 +372,14 @@ export class ScriptPool {// The owner table is indexed by SLOT, so it grows with the rows and on// the same schedule — allocated here so one growth is one pair of// allocations, and the views below are built once over both.- const ownerBlock = this.memory_.alloc(want * 4);+ let ownerBlock: PoolBlock;+ try { ownerBlock = this.memory_.alloc(want * 4); }+ catch (error) {+ try { this.memory_.release(block); } catch {}+ // The successful allocation may have detached every old heap view.+ try { this.rebuild_(); } catch {}+ throw error;+ }// Before reading the old rows, not after: allocating may have grown the// heap, and a grown heap detaches the view this is about to copy FROM.this.rebuild_();@@ -311,14 +396,10 @@ export class ScriptPool {this.slots_ = wider;this.ownersBlock_ = ownerBlock;this.owners_ = widerOwners;- this.memory_.release(old);- this.memory_.release(oldOwners);+ disposeAll([old, oldOwners], block => this.memory_.release(block));// Views hold a slot index, not a reference into the old array, so they// survive this. An ADDRESS taken before it does not, which is why// `address` says so.- for (const [entity, slot] of this.slotOf_) {- this.views_.set(entity, this.makeView_(slot));- }}/** The sparse table is indexed by ENTITY INDEX, which the world hands out@@ -341,7 +422,7 @@ export class ScriptPool {private writeAll_(slot: number, from: Record<string, unknown>): void {const base = slot * this.fields.length;this.fields.forEach((f, i) => {- this.slots_[base + i] = toSlot(from[f.name]);+ this.writeValue_(slot, i, base + i, from[f.name]);});}@@ -349,32 +430,80 @@ export class ScriptPool {const base = slot * this.fields.length;this.fields.forEach((f, i) => {const v = from[f.name];- if (v !== undefined) this.slots_[base + i] = toSlot(v);+ if (v !== undefined) this.writeValue_(slot, i, base + i, v);});}+ private writeValue_(slot: number, index: number, at: number, value: unknown): void {+ this.ensureCurrent_();+ if (typeof value === 'string' && this.fields[index].kind === 'number'+ && this.assetRefs_?.fields().some(f => f.field === this.fields[index].name)) {+ this.refs_ ??= new Map();+ let refs = this.refs_.get(slot);+ if (!refs) {+ this.refs_.set(slot, refs = new Map());+ this.assetRefs_.addressChanged();+ }+ refs.set(index, value);+ this.slots_[at] = 0;+ return;+ }+ const refs = this.refs_?.get(slot);+ if (refs?.delete(index) && refs.size === 0) {+ this.refs_!.delete(slot);+ this.assetRefs_?.addressChanged();+ }+ this.slots_[at] = toSlot(value);+ }+/** One object per entity, with an accessor per field onto its row. */- private makeView_(slot: number): Record<string, unknown> {+ private makeView_(slot: number): PoolView {const base = slot * this.fields.length;const view: Record<string, unknown> = {};+ let owner: ScriptPool | undefined = this;+ let detached: unknown[] | undefined;this.fields.forEach((f, i) => {const at = base + i;Object.defineProperty(view, f.name, {enumerable: true,configurable: true,get: f.kind === 'boolean'- ? (): boolean => this.slots_[at] !== 0- : (): number => this.slots_[at]!,- set: (v: unknown): void => { this.slots_[at] = toSlot(v); },+ ? (): unknown => {+ if (!owner) return detached![i];+ if (owner.slots_.length === 0) owner.rebuild_();+ return owner.slots_[at] !== 0;+ }+ : (): unknown => {+ if (!owner) return detached![i];+ if (owner.slots_.length === 0) owner.rebuild_();+ return owner.refs_?.get(slot)?.get(i) ?? owner.slots_[at]!;+ },+ set: (v: unknown): void => {+ if (owner) owner.writeValue_(slot, i, at, v);+ else detached![i] = v;+ },});});- return view;+ return {+ value: view,+ detach() {+ const pool = owner;+ if (!pool) return;+ // Snapshot canonical columns, without invoking authored getters+ // or redefining properties on sealed/frozen component objects.+ detached = pool.fields.map((f, i) => f.kind === 'boolean'+ ? pool.slots_[base + i] !== 0+ : pool.refs_?.get(slot)?.get(i) ?? pool.slots_[base + i]!);+ owner = undefined;+ },+ };}}/** Placeholders, so the constructor can allocate before it views. */const EMPTY_F64 = new Float64Array(0);const EMPTY_U32 = new Uint32Array(0);+const EMPTY_BLOCK: PoolBlock = { buffer: new ArrayBuffer(0), byteOffset: 0, byteLength: 0 };/** A slot holds a number; a boolean is the 0/1 the ABI stores it as. */function toSlot(v: unknown): number {diff --git a/sdk/src/ecs/ScriptStorage.ts b/sdk/src/ecs/ScriptStorage.tsindex 3d5daad54..73841e2e3 100644--- a/sdk/src/ecs/ScriptStorage.ts+++ b/sdk/src/ecs/ScriptStorage.ts@@ -7,10 +7,11 @@import { Entity } from '../types';import { ComponentDef } from './component';-import { validateComponentData, formatValidationErrors, assetFieldNames } from '../util/validation';+import { validateComponentData, formatValidationErrors } from '../util/validation';import { log } from '../util/logger';import { reorderMapByRank, type RankOf } from './entityOrder';import { ScriptPool, poolShape, HEAP_MEMORY, type PoolMemory } from './ScriptPool';+import { disposeAll } from '../util/disposeAll';export interface InsertResult<T> {value: T;@@ -28,6 +29,17 @@ export class ScriptStorage {*/private pools_ = new Map<symbol, ScriptPool>();private poolMemory_: PoolMemory = HEAP_MEMORY;+ private releasingPools_ = false;++ releasePools(): void {+ if (this.releasingPools_) return;+ this.releasingPools_ = true;+ const pools = [...this.pools_.values()];+ this.pools_.clear();this.notPooled_.clear();this.poolMemory_ = HEAP_MEMORY;+ this.layoutEpoch_++;+ try { disposeAll(pools, pool => pool.dispose()); }+ finally { this.releasingPools_ = false; }+ }/*** @internal Where pools allocate from. A wasm runtime installs one backed by@@ -46,11 +58,13 @@ export class ScriptStorage {private layoutEpoch_ = 0;- usePoolMemory(memory: PoolMemory): void {+ usePoolMemory(memory: PoolMemory, validateOnly = false): void {if (this.pools_.size > 0) {+ if (memory === this.poolMemory_ || (memory.allocatorIdentity !== undefined+ && memory.allocatorIdentity === this.poolMemory_.allocatorIdentity)) return;throw new Error('ScriptPool memory must be chosen before the first pooled component');}- this.poolMemory_ = memory;+ if (!validateOnly) this.poolMemory_ = memory;}/** @internal The rows behind `component`, or undefined if it has none. */@@ -58,6 +72,10 @@ export class ScriptStorage {return this.pools_.get(id);}+ hasPortableAssetRefs(id: symbol): boolean {+ return this.pools_.get(id)?.hasPortableAssetRefs ?? false;+ }+/*** @internal Re-view every pool. A wasm heap grows for one pool and detaches* the views of all of them, so this is a set operation and not a per-pool@@ -73,12 +91,16 @@ export class ScriptStorage {* repeated per insert.*/private pool_(component: ComponentDef<any>): ScriptPool | null {+ if (this.releasingPools_) throw new Error('Script pools are being released');const held = this.pools_.get(component._id);if (held) return held;if (this.notPooled_.has(component._id)) return null;const fields = poolShape(component._default);if (!fields) { this.notPooled_.add(component._id); return null; }- const pool = new ScriptPool(fields, 64, this.poolMemory_);+ const pool = new ScriptPool(fields, 64, this.poolMemory_, {+ fields: () => component.assetFields,+ addressChanged: () => { this.layoutEpoch_++; },+ });this.pools_.set(component._id, pool);// Creating one may have grown the heap every OTHER pool also lives in.this.refreshPools();@@ -90,7 +112,7 @@ export class ScriptStorage {insert<T>(entity: Entity, component: ComponentDef<T>, data?: unknown): InsertResult<T> {let filtered: Partial<T> | undefined;if (data !== null && data !== undefined && typeof data === 'object') {- const clean: Record<string, unknown> = {};+ const clean: Record<string, unknown> = Object.create(null);for (const [k, v] of Object.entries(data as Record<string, unknown>)) {if (v !== undefined) {clean[k] = v;@@ -100,7 +122,7 @@ export class ScriptStorage {component._name,component._default as Record<string, unknown>,clean,- assetFieldNames(component)+ component.assetFields);if (errors.length > 0) {throw new Error(formatValidationErrors(component._name, errors));@@ -180,7 +202,7 @@ export class ScriptStorage {component._name,component._default as Record<string, unknown>,data as Record<string, unknown>,- assetFieldNames(component)+ component.assetFields);if (errors.length > 0) {log.warn('ecs', formatValidationErrors(component._name, errors));diff --git a/sdk/src/ecs/WasmPoolMemory.ts b/sdk/src/ecs/WasmPoolMemory.tsindex 8b277dc30..c3f1dcf48 100644--- a/sdk/src/ecs/WasmPoolMemory.ts+++ b/sdk/src/ecs/WasmPoolMemory.ts@@ -22,6 +22,7 @@ import type { PoolBlock, PoolMemory } from './ScriptPool';/** What this needs of the engine module: an allocator and its heap. */export interface WasmHeap {+ readonly allocatorIdentity?: object;_malloc(size: number): number;_free(ptr: number): void;/** The live view. Emscripten replaces this object when the heap grows. */@@ -33,7 +34,10 @@ export interface WasmHeap {* a pool's `span()` directly usable by compiled code.*/export class WasmPoolMemory implements PoolMemory {- constructor(private readonly heap: WasmHeap) {}+ readonly allocatorIdentity: object;+ constructor(private readonly heap: WasmHeap) {+ this.allocatorIdentity = heap.allocatorIdentity ?? heap;+ }alloc(bytes: number): PoolBlock {// Eight-aligned because a row's fields are f64 and an unaligned typeddiff --git a/sdk/src/ecs/aot/AotContext.ts b/sdk/src/ecs/aot/AotContext.tsindex cf2259965..6c4102888 100644--- a/sdk/src/ecs/aot/AotContext.ts+++ b/sdk/src/ecs/aot/AotContext.ts@@ -39,6 +39,7 @@ export interface AotCommand {*/export class AotContext {private block: PoolBlock | null = null;+ private disposed = false;private words: Uint32Array = EMPTY;private cmdCap: number;/** f64 slots a call may append across every writer it declared. */@@ -51,9 +52,11 @@ export class AotContext {/** Hand the block back; the arena is dead after this. */dispose(): void {- if (this.block) this.memory.release(this.block);+ this.disposed = true;+ const block = this.block;this.block = null;this.words = EMPTY;+ if (block) this.memory.release(block);}/**@@ -71,6 +74,7 @@ export class AotContext {counts: Uint32Array,resources: readonly number[],): number {+ if (this.disposed) throw new Error('AotContext is disposed');const queryCount = counts.length;const need = SYSCTX_WORDS+ queryCount * QUERYROWS_WORDSdiff --git a/sdk/src/ecs/aot/AotDispatch.ts b/sdk/src/ecs/aot/AotDispatch.tsindex 6c39c4e5f..b0aca5016 100644--- a/sdk/src/ecs/aot/AotDispatch.ts+++ b/sdk/src/ecs/aot/AotDispatch.ts@@ -123,7 +123,10 @@ export class AotDispatch {run(twin: AotTwin): boolean {const plan = this.planFor_(twin);- this.packRows_(plan, this.world.layoutEpoch());+ if (!this.packRows_(plan, this.world.layoutEpoch())) {+ if (plan.reads) this.runtime.addresses.releasePayloads();+ return false;+ }const resources = plan.resources.map((r) => this.runtime.addresses.resourceAt(r.name) ?? 0);const writers = twin.decl.writers ?? [];@@ -167,10 +170,10 @@ export class AotDispatch {/*** Every row of every query, written into one block.*- * A row whose components cannot all answer is not written: an address of zero- * is a real address, and the compiled code would read somebody else's bytes.+ * Every matching row must be addressable. If one is not, the interpreter+ * runs the whole system; skipping it would silently lose authored work.*/- private packRows_(plan: Plan, epoch: number | null): void {+ private packRows_(plan: Plan, epoch: number | null): boolean {// The whole table or none of it: one query's rows moving says nothing// about another's, but a repack is a walk of both and this way there is// one condition to reason about rather than one per query.@@ -187,7 +190,8 @@ export class AotDispatch {lists.push(entities);if (entities !== plan.packedFrom[k]) reuse = false;}- if (reuse) return;+ if (reuse) return true;+ plan.packedAt = null;let at = 0;for (let k = 0; k < plan.queries.length; k++) {@@ -225,7 +229,7 @@ export class AotDispatch {if (address === undefined) { whole = false; break; }rows[write + 1 + c] = address;}- if (!whole) continue;+ if (!whole) return false;rows[write] = entity as unknown as number;n++;}@@ -234,6 +238,7 @@ export class AotDispatch {}plan.rowWords = at;plan.packedAt = epoch;+ return true;}/**diff --git a/sdk/src/ecs/aot/AotEvents.ts b/sdk/src/ecs/aot/AotEvents.tsindex b3c9433d7..f832a412d 100644--- a/sdk/src/ecs/aot/AotEvents.ts+++ b/sdk/src/ecs/aot/AotEvents.ts@@ -13,6 +13,8 @@* the object is rebuilt from that field list before it goes on the bus.*/import { POOL_SLOT_BYTES, type PoolBlock, type PoolMemory } from '../ScriptPool';+import { disposeAll } from '../../util/disposeAll';+import { hasOwn, setOwn } from '../../util/ownProperties';/** What the runtime knows about an event by NAME; a manifest carries names. */export interface EventBusAccess {@@ -24,6 +26,12 @@ export interface EventBusAccess {export class AotEvents {private readonly blocks: PoolBlock[] = [];+ private disposed = false;++ dispose(): void {+ this.disposed = true;+ this.release();+ }constructor(private readonly memory: PoolMemory, private readonly bus: EventBusAccess) {}@@ -33,6 +41,7 @@ export class AotEvents {* end of the call — the same lifetime the row array has.*/rowsFor(event: string, fields: readonly string[]): (readonly number[])[] {+ if (this.disposed) throw new Error('AotEvents is disposed');const payloads = this.bus(event)?.read() ?? [];const rows: number[][] = [];for (const payload of payloads) {@@ -48,6 +57,7 @@ export class AotEvents {/** Rebuild one payload from the fields the code wrote, and put it on the bus. */send(event: string, fields: readonly string[], values: readonly number[]): void {+ if (this.disposed) throw new Error('AotEvents is disposed');const target = this.bus(event);if (!target) return;const payload: Record<string, unknown> = {};@@ -57,8 +67,8 @@ export class AotEvents {/** Give the per-call blocks back; they are only valid inside one call. */release(): void {- for (const block of this.blocks) this.memory.release(block);- this.blocks.length = 0;+ const blocks = this.blocks.splice(0);+ disposeAll(blocks, block => this.memory.release(block));}}@@ -66,7 +76,7 @@ export class AotEvents {function numberAt(payload: unknown, path: string): number {let at: unknown = payload;for (const part of path.split('.')) {- if (at === null || typeof at !== 'object') return 0;+ if (at === null || typeof at !== 'object' || !hasOwn(at, part)) return 0;at = (at as Record<string, unknown>)[part];}return typeof at === 'boolean' ? (at ? 1 : 0) : (typeof at === 'number' ? at : 0);@@ -77,8 +87,8 @@ function assignAt(payload: Record<string, unknown>, path: string, value: number)const parts = path.split('.');let at = payload;for (const part of parts.slice(0, -1)) {- if (typeof at[part] !== 'object' || at[part] === null) at[part] = {};+ if (!hasOwn(at, part) || typeof at[part] !== 'object' || at[part] === null) setOwn(at, part, {});at = at[part] as Record<string, unknown>;}- at[parts[parts.length - 1]!] = value;+ setOwn(at, parts[parts.length - 1]!, value);}diff --git a/sdk/src/ecs/aot/AotResources.ts b/sdk/src/ecs/aot/AotResources.tsindex 75b4b381d..cea1ca1b4 100644--- a/sdk/src/ecs/aot/AotResources.ts+++ b/sdk/src/ecs/aot/AotResources.ts@@ -20,6 +20,7 @@*/import { POOL_SLOT_BYTES, type PoolBlock, type PoolMemory } from '../ScriptPool';+import { disposeAll } from '../../util/disposeAll';import {resourceBitSource, resourceBlockBytes, resourceLayout, type ResourceMember,} from '../resourceShapes';@@ -35,6 +36,7 @@ export type ResourceReader = (name: string) => Readonly<Record<string, unknown>>export class AotResources {private readonly blocks = new Map<string, PoolBlock>();private readonly views = new Map<string, Uint8Array>();+ private disposed = false;constructor(private readonly memory: PoolMemory,@@ -69,6 +71,7 @@ export class AotResources {* undefined when the resource has no layout or the world has no value.*/addressOf(name: string): number | undefined {+ if (this.disposed) throw new Error('AotResources is disposed');const layout = this.layoutOf(name);if (!layout) return undefined;const value = this.read(name);@@ -146,8 +149,10 @@ export class AotResources {}dispose(): void {- for (const block of this.blocks.values()) this.memory.release(block);+ this.disposed = true;+ const blocks = [...this.blocks.values()];this.blocks.clear();this.views.clear();+ disposeAll(blocks, block => this.memory.release(block));}}diff --git a/sdk/src/ecs/aot/AotRuntime.ts b/sdk/src/ecs/aot/AotRuntime.tsindex ed7511abd..e93b7a0fd 100644--- a/sdk/src/ecs/aot/AotRuntime.ts+++ b/sdk/src/ecs/aot/AotRuntime.ts@@ -65,6 +65,8 @@ export interface AotDispatcher {* the editor and dev builds need no flag and take no branch worth measuring.*/export interface AotRuntime {+ /** Retire dispatch and release its owned arenas/mirrors. Idempotent. */+ dispose?(): void;readonly systems: AotSystems;readonly addresses: AotAddresses;readonly ctx: AotContext;diff --git a/sdk/src/ecs/aot/installAot.ts b/sdk/src/ecs/aot/installAot.tsindex 01d8d9bb1..986df6f2b 100644--- a/sdk/src/ecs/aot/installAot.ts+++ b/sdk/src/ecs/aot/installAot.ts@@ -34,6 +34,7 @@ import type { AotAddresses, AotRuntime } from './AotRuntime';import { AotDispatch } from './AotDispatch';import { missingCapabilities, whyInterpreted, WEB_AOT } from './executorCapabilities';import { log } from '../../util/logger';+import { disposeAll } from '../../util/disposeAll';/*** The engine module a compiled system shares memory with. The Memory OBJECT,@@ -68,9 +69,9 @@ export interface InstallAotOptions {/*** Install the twins. Throws if the module disagrees with this engine or this- * project, and the message says which. Call it BEFORE the world has any pooled- * component: the rows must be in the memory the module reads, and moving them- * afterwards would leave half of them behind — so it refuses instead.+ * project, and the message says which. Select the allocation domain before the+ * world's first pooled component. Replacement may reuse that allocator; moving+ * existing rows to another domain would leave addresses behind, so it refuses.*/export async function installAot(opts: InstallAotOptions): Promise<AotRuntime> {const runtime = await prepareAot(opts);@@ -96,9 +97,11 @@ function moduleContractOf(exports: Readonly<Record<string, unknown>>): string |return half((hi as () => number)()) + half((lo as () => number)());}-export async function prepareAot(opts: Omit<InstallAotOptions, 'runner'>): Promise<AotRuntime> {+export async function prepareAot(opts: Omit<InstallAotOptions, 'runner'> & {+ /** Owner cancellation gate before selecting the world's allocation domain. */+ readonly beforeCommit?: () => void;+}): Promise<AotRuntime> {const memory = new WasmPoolMemory(opts.host);- opts.world.useScriptPoolMemory(memory);const { instance } = await platformInstantiateWasm(wasmSource(opts.wasm), { env: { memory: opts.host.memory } });@@ -125,15 +128,27 @@ export async function prepareAot(opts: Omit<InstallAotOptions, 'runner'>): PromimoduleContract: moduleContractOf(exports),});+ opts.beforeCommit?.();+ opts.world.useScriptPoolMemory(memory);+ const resources = new AotResources(memory, opts.resources, declaredLayouts(opts.manifest));+ const events = new AotEvents(memory, opts.events ?? (() => undefined));+ const ctx = new AotContext(memory);+ let disposed = false;const runtime: AotRuntime = {+ dispose() {+ if (disposed) return;+ disposed = true;+ disposeAll([() => events.dispose(), () => resources.dispose(), () => ctx.dispose()], action => action());+ },systems,- addresses: worldAddresses(- new AotResources(memory, opts.resources, declaredLayouts(opts.manifest)),- new AotEvents(memory, opts.events ?? (() => undefined))),- ctx: new AotContext(memory),+ addresses: worldAddresses(resources, events),+ ctx,// This module shares the engine's memory, so the rows go there and the// call takes their address.- dispatcherFor: (world) => new AotDispatch(world, runtime),+ dispatcherFor: (world) => {+ const dispatch = new AotDispatch(world, runtime);+ return { run: twin => !disposed && dispatch.run(twin) };+ },};return runtime;}diff --git a/sdk/src/ecs/aot/installNativeAot.ts b/sdk/src/ecs/aot/installNativeAot.tsindex cea4432ef..cac497de0 100644--- a/sdk/src/ecs/aot/installNativeAot.ts+++ b/sdk/src/ecs/aot/installNativeAot.ts@@ -18,7 +18,7 @@* handshake is checked here too, at the width a loading host runs at.*/-import { getComponent, type AnyComponentDef } from '../component';+import { getComponent, isBuiltinComponent, type AnyComponentDef } from '../component';import { log } from '../../util/logger';import type { World } from '../world';import type { SystemRunner } from '../system';@@ -28,13 +28,18 @@ import { AotSystems, type AotManifest, type AotSystemDecl, type AotTwin } from 'import { AotResources, type ResourceReader } from './AotResources';import type { AotDispatcher, AotRuntime } from './AotRuntime';import { missingCapabilities, whyInterpreted, NATIVE_AOT } from './executorCapabilities';+import { disposeAll } from '../../util/disposeAll';/** `sizeof(es_addr_t)` where a loaded library runs. */const NATIVE_ADDRESS_BYTES = 8;/** The `es_aot_*` surface, as one object so a test can stand in for the host. */export interface NativeAotBindings {+ /** Shared native dispatcher ownership across freshly created wrappers. */+ readonly runtimeIdentity?: object;install(path: string): number;+ /** Candidate contract validation before the live module is replaced. */+ installChecked?(path: string, expectedContract: string): number;index(name: string): number;bound(index: number): boolean;scriptRows(name: string, sparseOffset: number, sparseCount: number,@@ -48,6 +53,8 @@ export interface NativeAotBindings {contract?(): string;}+const nativeOwners = new WeakMap<object, { retire(): void }>();+export interface InstallNativeAotOptions {readonly world: World;readonly runner: SystemRunner;@@ -89,6 +96,7 @@ export function nativeAotBindings(const fn = (name: string): ((...args: never[]) => unknown) | null =>(typeof scope[name] === 'function' ? scope[name] as (...args: never[]) => unknown : null);const install = fn('es_aot_install');+ const checked = fn('es_aot_install_checked');const run = fn('es_aot_run');if (install === null || run === null) return null;const call = <T>(name: string, fallback: T) => (...args: unknown[]): T => {@@ -96,7 +104,10 @@ export function nativeAotBindings(return f === null ? fallback : (f as (...a: unknown[]) => T)(...args);};return {+ runtimeIdentity: install,install: (path) => (install as (p: string) => number)(path),+ ...(checked === null ? {} : { installChecked: (path: string, expected: string) =>+ (checked as (p: string, e: string) => number)(path, expected) }),index: call<number>('es_aot_index', -1),bound: call<boolean>('es_aot_bound', false),scriptRows: call<boolean>('es_aot_script_rows', false),@@ -116,31 +127,6 @@ export function installNativeAot(opts: InstallNativeAotOptions): AotRuntime | nuconst bindings = opts.bindings ?? nativeAotBindings();if (bindings === null) return null;- // Before the first pooled component exists: a pool cannot move to other- // memory once it has rows, and the host addresses only this heap.- const memory = new WasmPoolMemory(opts.heap);- opts.world.useScriptPoolMemory(memory);-- const count = bindings.install(opts.modulePath);- if (count < 0) return null;-- // The index the scheduler keeps. Whether the host can BIND one is settled at- // the first run instead: a script pool does not exist until an entity has- // that component, and until then the interpreter keeps the system.- const byName = new Map<string, number>();- for (const decl of opts.manifest.systems) {- const missing = missingCapabilities(decl, NATIVE_AOT);- if (missing.length > 0) {- log.info('runtime', whyInterpreted(decl.name, missing));- continue;- }- const at = bindings.index(decl.name);- if (at >= 0) byName.set(decl.name, at);- }-- // The handshake at the loading width, over the WHOLE manifest — that is- // what the module is. The exports throw because the host holds the function- // pointers here, so a twin's `call` reaching one is a bug, loudly.const systems = new AotSystems();const exports: Record<string, unknown> = {};for (const decl of opts.manifest.systems) {@@ -148,48 +134,116 @@ export function installNativeAot(opts: InstallNativeAotOptions): AotRuntime | nuthrow new Error(`AOT: ${decl.name} is the host's to call, not this runtime's`);};}- // The artifact is the host's to read here, so the pairing comes back from- // it rather than off an export this side can reach.- const paired = bindings.contract?.() ?? '';- systems.install(opts.manifest, exports, (name) => getComponent(name), {- addressBytes: NATIVE_ADDRESS_BYTES,- runs: (name) => byName.has(name),- moduleContract: paired === '' ? null : paired,- // From the RUNTIME's own copy. The default answers "no fields" for every- // resource, so this road's handshake could not see a project resource at- // all and the mirror was laid out from the manifest alone.- resourceFields: (name) => {- const value = opts.resources?.(name);- return value === undefined ? undefined : Object.keys(value);- },+ const resourceFields = (name: string) => {+ const value = opts.resources?.(name);+ return value === undefined ? undefined : Object.keys(value);+ };+ // Reject runtime shape/ABI mismatches before the host changes its module.+ systems.install(opts.manifest, exports, getComponent, {+ addressBytes: NATIVE_ADDRESS_BYTES, runs: () => false, resourceFields,});- // Every script component any twin names, so one epoch change re-reports all- // of them rather than whichever twin happened to run first.- const pooled = new Set<string>();- for (const decl of opts.manifest.systems) {- for (const query of decl.queries) for (const arg of query) pooled.add(arg.comp);- }- // The resources, mirrored into the same heap the pools use. A resource has no- // address of its own until something writes one down, and doing that per call- // is what the contract promises — the address is good for one call.- const resources = new AotResources(memory, opts.resources ?? (() => undefined),- declaredResourceLayouts(opts.manifest));+ // Before the first pooled component exists: a pool cannot move to other+ // memory once it has rows, and the host addresses only this heap.+ const memory = new WasmPoolMemory(opts.heap);+ opts.world.useScriptPoolMemory(memory, true);- const runtime: AotRuntime = {- systems,- // Absent on this road: nothing here resolves an address, because nothing- // here can hold one. Present in the type so the wasm road cannot omit it.- addresses: {- componentNamed: (name: string) => getComponent(name),- resourceAt: () => undefined,- } as unknown as AotRuntime['addresses'],- ctx: null as unknown as AotRuntime['ctx'],- dispatcherFor: (world) =>- new NativeAotDispatch(world, bindings, byName, pooled, resources, systems),- };- opts.runner.useAot(runtime);- return runtime;+ const count = bindings.installChecked+ ? bindings.installChecked(opts.modulePath, opts.manifest.moduleContract ?? '')+ : bindings.install(opts.modulePath);+ if (count < 0) return null;++ const identity = bindings.runtimeIdentity ?? bindings;+ const previous = nativeOwners.get(identity);+ const lease = { retire: () => {} };+ nativeOwners.set(identity, lease);+ const ownsHost = () => nativeOwners.get(identity) === lease;+ try { previous?.retire(); }+ catch (error) { log.warn('runtime', 'Native compiled runtime retirement error', error); }++ try {+ opts.world.useScriptPoolMemory(memory);++ // The index the scheduler keeps. Whether the host can BIND one is settled at+ // the first run instead: a script pool does not exist until an entity has+ // that component, and until then the interpreter keeps the system.+ const byName = new Map<string, number>();+ for (const decl of opts.manifest.systems) {+ const missing = missingCapabilities(decl, NATIVE_AOT);+ if (missing.length > 0) {+ log.info('runtime', whyInterpreted(decl.name, missing));+ continue;+ }+ const at = bindings.index(decl.name);+ if (at >= 0) byName.set(decl.name, at);+ }++ // The handshake at the loading width, over the WHOLE manifest — that is+ // what the module is. The exports throw because the host holds the function+ // pointers here, so a twin's `call` reaching one is a bug, loudly.+ // The artifact is the host's to read here, so the pairing comes back from+ // it rather than off an export this side can reach.+ const paired = bindings.contract?.() ?? '';+ systems.install(opts.manifest, exports, (name) => getComponent(name), {+ addressBytes: NATIVE_ADDRESS_BYTES,+ runs: (name) => byName.has(name),+ moduleContract: paired === '' ? null : paired,+ // From the RUNTIME's own copy. The default answers "no fields" for every+ // resource, so this road's handshake could not see a project resource at+ // all and the mirror was laid out from the manifest alone.+ resourceFields,+ });++ // Every script component any twin names, so one epoch change re-reports all+ // of them rather than whichever twin happened to run first.+ const pooled = new Set<string>();+ for (const decl of opts.manifest.systems) {+ for (const query of decl.queries) for (const arg of query) pooled.add(arg.comp);+ }+ // The resources, mirrored into the same heap the pools use. A resource has no+ // address of its own until something writes one down, and doing that per call+ // is what the contract promises — the address is good for one call.+ const resources = new AotResources(memory, opts.resources ?? (() => undefined),+ declaredResourceLayouts(opts.manifest));++ let disposed = false;+ const runtime: AotRuntime = {+ dispose() {+ if (disposed) return;+ disposed = true;+ systems.clear();+ const current = ownsHost();+ if (current) nativeOwners.delete(identity);+ disposeAll([() => { if (current) bindings.reset(); }, () => resources.dispose()], action => action());+ },+ systems,+ // Absent on this road: nothing here resolves an address, because nothing+ // here can hold one. Present in the type so the wasm road cannot omit it.+ addresses: {+ componentNamed: (name: string) => getComponent(name),+ resourceAt: () => undefined,+ } as unknown as AotRuntime['addresses'],+ ctx: null as unknown as AotRuntime['ctx'],+ dispatcherFor: (world) => {+ const dispatch = new NativeAotDispatch(world, bindings, byName, pooled, resources, systems);+ return { run: twin => !disposed && dispatch.run(twin) };+ },+ };+ lease.retire = () => runtime.dispose?.();+ if (!ownsHost()) {+ runtime.dispose?.();+ throw new Error('Native compiled installation was superseded during preparation');+ }+ opts.runner.useAot(runtime);+ return runtime;+ } catch (error) {+ try { lease.retire(); } catch (releaseError) { log.warn('runtime', 'Native compiled cleanup error', releaseError); }+ if (ownsHost()) {+ nativeOwners.delete(identity);+ try { bindings.reset(); } catch (resetError) { log.warn('runtime', 'Native compiled reset error', resetError); }+ }+ throw error;+ }}/**@@ -207,6 +261,11 @@ class NativeAotDispatch implements AotDispatcher {private reportedAt_: number | null | undefined = undefined;/** Systems the host has taken at least once, so it is said once. */private readonly running_ = new Set<string>();+ private readonly assetQueries_ = new Map<AotTwin, {+ comps: AnyComponentDef[];+ scripts: AnyComponentDef[];+ addresses: ((entity: Entity) => number | undefined)[];+ }[]>();constructor(private readonly world: World,@@ -220,6 +279,27 @@ class NativeAotDispatch implements AotDispatcher {run(twin: AotTwin): boolean {const at = this.indexByName.get(twin.decl.name);if (at === undefined) return false;+ // A portable reference lives beside its numeric pool until resolved.+ // The host only sees numeric memory, so never let it run a partial+ // query while the interpreter can still see the authored string.+ let queries = this.assetQueries_.get(twin);+ if (!queries) {+ queries = twin.decl.queries.map(query => {+ const comps = query.map(arg => getComponent(arg.comp))+ .filter((def): def is AnyComponentDef => def !== undefined);+ const scripts = comps.filter(def => !isBuiltinComponent(def));+ return { comps, scripts, addresses: scripts.map(def => this.world.addressResolver(def)) };+ });+ this.assetQueries_.set(twin, queries);+ }+ for (const query of queries) {+ if (!query.scripts.some(def => this.world.hasPortableScriptAssetRefs(def))) continue;+ for (const entity of this.world.queryEntities(query.comps)) {+ for (let i = 0; i < query.scripts.length; i++) {+ if (query.addresses[i](entity) === undefined) return false;+ }+ }+ }this.reportPools_();this.reportResources_(twin);// The epoch goes with the call: the host keeps last frame's row table@@ -275,8 +355,12 @@ class NativeAotDispatch implements AotDispatcher {this.reportedAt_ = epoch;for (const name of this.pooled) {const def = getComponent(name);- const span = def === undefined ? undefined : this.world.scriptSpanOf(def);- if (span === undefined) continue;+ if (def === undefined || isBuiltinComponent(def)) continue;+ const span = this.world.scriptSpanOf(def);+ if (span === undefined) {+ this.bindings.scriptRows(name, 0, 0, 0, 0, SPARSE_INDEX_MASK, 0, 0);+ continue;+ }this.bindings.scriptRows(name, span.sparse, span.sparseCount,span.rows, span.stride, SPARSE_INDEX_MASK, span.owners, span.ownerCount);}diff --git a/sdk/src/ecs/bridge/BuiltinBridge.ts b/sdk/src/ecs/bridge/BuiltinBridge.tsindex 47e1bab4e..8cc58d3fe 100644--- a/sdk/src/ecs/bridge/BuiltinBridge.ts+++ b/sdk/src/ecs/bridge/BuiltinBridge.ts@@ -9,11 +9,12 @@ import { Entity } from '../../types';import { mergeIntoDefaults } from '../component';import type { BuiltinComponentDef } from '../component';import type { CppRegistry, ESEngineModule } from '../../wasm';-import { validateComponentData, formatValidationErrors, assetFieldNames } from '../../util/validation';+import { validateComponentData, formatValidationErrors } from '../../util/validation';import { handleWasmError } from '../../wasm/wasmError';import { installAbortGuard, throwIfModuleAborted, isModuleAborted, WasmModuleAborted } from '../../wasm/moduleHealth';import { COMPONENT_META, ABI_LAYOUT_HASH } from '../component.generated';import { PTR_ACCESSORS } from './ptrAccessors.generated';+import { hasOwn } from '../../util/ownProperties';import { reorderSetByRank, type RankOf } from '../entityOrder';import {type MemoryProvider, type ComponentHeap,@@ -812,7 +813,7 @@ export class BuiltinBridge {if (data !== null && data !== undefined && typeof data === 'object') {for (const [k, v] of Object.entries(data as Record<string, unknown>)) {if (v === undefined) continue;- if (!(k in defaults)) continue;+ if (!hasOwn(defaults, k)) continue;filtered[k] = v;}@@ -820,7 +821,7 @@ export class BuiltinBridge {component._name,defaults,filtered,- assetFieldNames(component)+ component.assetFields);if (errors.length > 0) {throw new Error(formatValidationErrors(component._name, errors));diff --git a/sdk/src/ecs/bridge/memoryProvider.ts b/sdk/src/ecs/bridge/memoryProvider.tsindex ec7d6bf6a..4850dd3b4 100644--- a/sdk/src/ecs/bridge/memoryProvider.ts+++ b/sdk/src/ecs/bridge/memoryProvider.ts@@ -14,9 +14,9 @@// component (the host's generated `es_<Component>_buffer(entity)` binding),// viewed as F32/U32/U8, with offset 0.//-// Same generated accessors, same POD layout (wasm32/arm64 layout-identical, per-// the EHT ABI hash), two memory backends — this is the seam that lets the real-// SDK component API run unchanged on both.+// The native host exposes a buffer only when its compiler proves all accessed+// offsets agree with wasm32 and the component is trivially copyable. Otherwise+// resolution returns null and BuiltinBridge uses generated member bindings.import type { Entity } from '../../types';import type { CppRegistry, ESEngineModule } from '../../wasm';@@ -126,8 +126,9 @@ export class NativeMemoryProvider implements MemoryProvider {return (entity: Entity, out: ComponentHeap): boolean => {const buf = bufFn(entity);if (!buf) return false;- out.f32 = new Float32Array(buf);- out.u32 = new Uint32Array(buf);+ const words = Math.floor(buf.byteLength / 4);+ out.f32 = new Float32Array(buf, 0, words);+ out.u32 = new Uint32Array(buf, 0, words);out.u8 = new Uint8Array(buf);out.ptr = 0;return true;diff --git a/sdk/src/ecs/bridge/nativeBindings.ts b/sdk/src/ecs/bridge/nativeBindings.tsindex 8d9fb5a6e..8e0385d63 100644--- a/sdk/src/ecs/bridge/nativeBindings.ts+++ b/sdk/src/ecs/bridge/nativeBindings.ts@@ -47,6 +47,22 @@ export const REGISTRY_BINDINGS = {ensureComposed: 'es_transformEnsureComposed',} as const;+/** Optional shared destruction ownership for current native hosts. */+export const DESTRUCTION_BINDINGS = {+ reserveDestruction: 'es_reserveDestruction',+ releaseDestruction: 'es_releaseDestruction',+ destructionPending: 'es_destructionPending',+} as const;++/** Effective entity activity, available on hosts implementing the shared core. */+export const ACTIVITY_BINDINGS = {+ setEntityEnabled: 'es_setEntityEnabled',+ isEntityActive: 'es_isEntityActive',+ isEntityEnabled: 'es_isEntityEnabled',+ hasInactiveEntities: 'es_hasInactiveEntities',+ activityEpoch: 'es_activityEpoch',+} as const;+/*** The composition's change REPORT, which not every host has to answer: a core* that does not leaves consumers rebuilding rather than updating, so these arediff --git a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts b/sdk/src/ecs/bridge/nativeEngineApi.generated.tsindex c101eac0f..3a0eddca6 100644--- a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts+++ b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts@@ -198,7 +198,9 @@ export interface NativeEngineApi {renderer_submitAll?(registry: unknown, vpX: number, vpY: number, vpW: number, vpH: number): void;renderer_submitScreenOverlay?(registry: unknown): void;renderer_submitSkeletalBatchByEntity?(registry: unknown, verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, blendMode: number, entity: number, skelScale: number, flipX: boolean, flipY: boolean, layer: number, depth: number, materialId: number): void;+ renderer_submitSkeletalBatchByEntityEx?(registry: unknown, verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, blendMode: number, entity: number, skelScale: number, flipX: boolean, flipY: boolean, layer: number, depth: number, materialId: number, premultipliedColor: boolean): void;renderer_submitSkeletalPreviewBatch?(preview: number, verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, blendMode: number, transformPtr: number, layer: number, depth: number, materialId: number): number;+ renderer_submitSkeletalPreviewBatchEx?(preview: number, verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, blendMode: number, transformPtr: number, layer: number, depth: number, materialId: number, premultipliedColor: boolean): number;renderer_submitTextBatch?(verticesPtr: number, vertexCount: number, indicesPtr: number, indexCount: number, textureId: number, transformPtr: number, entity: number, layer: number, depth: number, sdf: number, cullBit: number): void;renderer_takeFrameCapture?(handle: number, dest: number, destSize: number): boolean;renderer_updateTransforms?(registry: unknown): void;@@ -478,7 +480,9 @@ export function createNativeEngineApi(bind('renderer_submitAll', 'es_renderer_submitAll', true);bind('renderer_submitScreenOverlay', 'es_renderer_submitScreenOverlay', true);bind('renderer_submitSkeletalBatchByEntity', 'es_renderer_submitSkeletalBatchByEntity', true);+ bind('renderer_submitSkeletalBatchByEntityEx', 'es_renderer_submitSkeletalBatchByEntityEx', true);bind('renderer_submitSkeletalPreviewBatch', 'es_renderer_submitSkeletalPreviewBatch', false);+ bind('renderer_submitSkeletalPreviewBatchEx', 'es_renderer_submitSkeletalPreviewBatchEx', false);bind('renderer_submitTextBatch', 'es_renderer_submitTextBatch', false);bind('renderer_takeFrameCapture', 'es_renderer_takeFrameCapture', false);bind('renderer_updateTransforms', 'es_renderer_updateTransforms', true);diff --git a/sdk/src/ecs/bridge/nativeHeap.ts b/sdk/src/ecs/bridge/nativeHeap.tsindex 85b17293b..9265f3270 100644--- a/sdk/src/ecs/bridge/nativeHeap.ts+++ b/sdk/src/ecs/bridge/nativeHeap.ts@@ -23,6 +23,7 @@/** The heap members a subsystem module interface asks for. */export interface NativeHeap {+ readonly allocatorIdentity: object;HEAPU8: Uint8Array;HEAPU16: Uint16Array;HEAPU32: Uint32Array;@@ -40,6 +41,10 @@ export const HEAP_BINDINGS = {free: 'es_free',} as const;+const allocationDomains = new WeakMap<object, {+ buffer: ArrayBuffer; malloc: unknown; free: unknown; identity: object;+}>();+/** Whether this host bound the heap at all. A core that marshals nothing may not. */export function hasHeapBindings(scope: Record<string, unknown>): boolean {return typeof scope[HEAP_BINDINGS.heap] === 'function'@@ -60,7 +65,13 @@ export function createNativeHeap(if (!buffer) return null;const malloc = scope[HEAP_BINDINGS.malloc] as (bytes: number) => number;const free = scope[HEAP_BINDINGS.free] as (offset: number) => void;+ let domain = allocationDomains.get(scope);+ if (!domain || domain.buffer !== buffer || domain.malloc !== malloc || domain.free !== free) {+ domain = { buffer, malloc, free, identity: {} };+ allocationDomains.set(scope, domain);+ }return {+ allocatorIdentity: domain.identity,HEAPU8: new Uint8Array(buffer),HEAPU16: new Uint16Array(buffer),HEAPU32: new Uint32Array(buffer),diff --git a/sdk/src/ecs/bridge/nativeRegistry.ts b/sdk/src/ecs/bridge/nativeRegistry.tsindex 3724d0c8c..2eb714869 100644--- a/sdk/src/ecs/bridge/nativeRegistry.ts+++ b/sdk/src/ecs/bridge/nativeRegistry.ts@@ -6,10 +6,10 @@// consumes (add<Name> / get<Name> / has<Name> / remove<Name> per component), so// the real SDK component API runs on the native core unchanged.//-// It is composed, not a second marshaller: field IO reuses the generated-// ptrAccessors (the one marshalling path, proven on device) over the host's-// zero-copy es_<Component>_buffer binding; lifecycle reuses the generated-// es_<Component>_has / _remove bindings. The only shape bridge is color naming —+// The host exposes a zero-copy buffer only for trivially copyable components+// whose actual compiler offsets match the generated wasm32 accessors. Other+// components cross through generated C++ member getters/setters, preserving+// native string/vector ownership and layout. The color shape bridge remains —// embind marshals colors as {x,y,z,w}, ptrAccessors as {r,g,b,a} — handled by the// same convertForWasm/convertFromWasm the web methods path uses, keyed off// COMPONENT_META.colorFields.@@ -17,7 +17,7 @@import type { CppRegistry } from '../../wasm';import type { Entity } from '../../types';import { PTR_ACCESSORS } from './ptrAccessors.generated';-import { REGISTRY_BINDINGS, SCENE_QUERY_BINDINGS } from './nativeBindings';+import { REGISTRY_BINDINGS, SCENE_QUERY_BINDINGS, ACTIVITY_BINDINGS, DESTRUCTION_BINDINGS } from './nativeBindings';import { COMPONENT_META } from '../component.generated';import { convertForWasm, convertFromWasm } from './BuiltinBridge';@@ -88,6 +88,14 @@ export function createNativeRegistry(scope: Record<string, unknown> = globalThis as unknown as Record<string, unknown>,): CppRegistry {const reg: Record<string, unknown> = {};+ for (const [method, binding] of Object.entries(ACTIVITY_BINDINGS)) {+ if (typeof scope[binding] === 'function') reg[method] = (...args: unknown[]) => hostCall(scope, binding, args);+ }+ if (Object.values(DESTRUCTION_BINDINGS).every(binding => typeof scope[binding] === 'function')) {+ for (const [method, binding] of Object.entries(DESTRUCTION_BINDINGS)) {+ reg[method] = (entity: Entity) => hostCall(scope, binding, [entity]);+ }+ }// Entity lifecycle + hierarchy — the base Registry surface World drives (spawn,// despawn, parent/child). These are not per-component; the host binds them by@@ -99,8 +107,8 @@ export function createNativeRegistry(// re-resolve it every frame, silently.reg.layoutEpoch = (): number => hostCall(scope, REGISTRY_BINDINGS.layoutEpoch, []) as number;reg.hasParent = (e: Entity): boolean => !!hostCall(scope, REGISTRY_BINDINGS.hasParent, [e]);- reg.setParent = (child: Entity, parent: Entity): void => {- hostCall(scope, REGISTRY_BINDINGS.setParent, [child, parent]);+ reg.setParent = (child: Entity, parent: Entity): boolean | void => {+ return hostCall(scope, REGISTRY_BINDINGS.setParent, [child, parent]) as boolean | void;};reg.removeParent = (e: Entity): void => { hostCall(scope, REGISTRY_BINDINGS.removeParent, [e]); };reg.hasChildren = (e: Entity): boolean => !!hostCall(scope, REGISTRY_BINDINGS.hasChildren, [e]);@@ -172,6 +180,35 @@ export function createNativeRegistry(reg.delete = (): void => {};+ // A native std::string/std::vector (and even POD with different alignment)+ // cannot be addressed with wasm32 offsets. The host deliberately withholds+ // its buffer; use actual C++ members instead. Lists retain their own bindings.+ for (const [cppName, meta] of Object.entries(COMPONENT_META)) {+ if (cppName === 'Parent' || cppName === 'Children' || cppName === 'MeshSkin') continue;+ if (typeof scope[`es_${cppName}_buffer`] === 'function') continue;+ const get = scope[`es_get_${cppName}`] as ((e: Entity) => Record<string, unknown>) | undefined;+ const set = scope[`es_set_${cppName}`] as ((e: Entity, data: unknown) => void) | undefined;+ const has = scope[`es_${cppName}_has`] as HasFn | undefined;+ const remove = scope[`es_${cppName}_remove`] as RemoveFn | undefined;+ if (typeof get !== 'function' || typeof set !== 'function'+ || typeof has !== 'function' || typeof remove !== 'function') continue;+ const fields = [...new Set([...(meta.listFields ?? []), ...(meta.numberListFields ?? [])])];+ reg[`add${cppName}`] = (e: Entity, data: Record<string, unknown>): void => {+ set(e, data);+ for (const field of fields) {+ if (field in data) hostCall(scope, `es_${cppName}_${field}_set`, [e, data[field]]);+ }+ };+ reg[`get${cppName}`] = (e: Entity): Record<string, unknown> => {+ const out = has(e) ? get(e) : {};+ for (const field of fields) out[field] = has(e)+ ? hostCall(scope, `es_${cppName}_${field}_get`, [e]) : [];+ return out;+ };+ reg[`has${cppName}`] = has;+ reg[`remove${cppName}`] = remove;+ }+// The scene queries the wasm module answers as module-level functions. There is// no module here, so the registry answers them — the camera plugin asks the// registry first and falls through to the module on web (see canvasEntityOf).diff --git a/sdk/src/ecs/component.ts b/sdk/src/ecs/component.tsindex 956170247..3b6fa4583 100644--- a/sdk/src/ecs/component.ts+++ b/sdk/src/ecs/component.ts@@ -7,6 +7,7 @@import { Entity, Vec2, Vec3, Color, Quat } from '../types';import { deepClone } from '../util/deepClone';+import { hasOwn, setOwn } from '../util/ownProperties';import { COMPONENT_META, type AssetFieldMeta, type SkeletalFieldMeta } from './component.generated';export type { AssetFieldMeta, SkeletalFieldMeta };// C++-backed component data shapes, generated from the ES_COMPONENT structs (single@@ -259,11 +260,18 @@ export function mergeIntoDefaults<T extends object>(defaults: T, data?: Partial<if (!data) return out as T;for (const [k, v] of Object.entries(data as Record<string, unknown>)) {if (v === undefined) continue;- const base = out[k];+ const base = hasOwn(out, k) ? out[k] : undefined;const nest = base !== null && typeof base === 'object' && !Array.isArray(base)&& v !== null && typeof v === 'object' && !Array.isArray(v);- if (nest) Object.assign(base as object, v);- else out[k] = v;+ // The default's nested record was already copied above. Reuse that+ // instance on ordinary patches; __proto__ needs spread's own-data write+ // so it cannot invoke the inherited prototype setter.+ const merged = nest+ ? hasOwn(v as object, '__proto__')+ ? { ...(base as object), ...(v as object) }+ : Object.assign(base as object, v)+ : v;+ setOwn(out, k, merged);}return out as T;}@@ -273,7 +281,7 @@ function classifyKeys(obj: object): { flatKeys: string[]; objectKeys: string[];const objectKeys: string[] = [];const arrayKeys: string[] = [];let hasNested = false;- for (const key in obj) {+ for (const key of Object.keys(obj)) {const val = (obj as Record<string, unknown>)[key];if (val !== null && typeof val === 'object') {hasNested = true;@@ -343,14 +351,14 @@ function createComponentDef<T extends object>(// drift class this metadata exists to kill, so it fails loud (same spirit as// EHT rejecting a malformed known annotation).for (const f of metadata?.replicatedFields ?? []) {- if (!(f in defaultsRec)) {+ if (!hasOwn(defaultsRec, f)) {throw new Error(`Component "${name}": replicatedFields names unknown field "${f}"`);}}// Same reason, and the same check EHT makes for a builtin: a renderableField// that names nothing would read as "draws nothing" and quietly stay visible.const renderableField = metadata?.renderableField;- if (renderableField !== undefined && typeof defaultsRec[renderableField] !== 'boolean') {+ if (renderableField !== undefined && (!hasOwn(defaultsRec, renderableField) || typeof defaultsRec[renderableField] !== 'boolean')) {throw new Error(`Component "${name}": renderableField "${renderableField}" is not a boolean field of its defaults`,);diff --git a/sdk/src/ecs/entityUtils.ts b/sdk/src/ecs/entityUtils.tsindex 79085e216..2a403e7d2 100644--- a/sdk/src/ecs/entityUtils.ts+++ b/sdk/src/ecs/entityUtils.ts@@ -78,12 +78,13 @@ export function setEntityActive(world: World, entity: Entity, active: boolean):} else if (!world.has(entity, Disabled)) {world.insert(entity, Disabled, {});}+ world.getCppRegistry()?.setEntityEnabled?.(entity, active);}/** Whether this entity ITSELF is switched on. An ancestor's switch takes it out* of every query without changing this — see {@link setEntityActive}. */export function isEntityActive(world: World, entity: Entity): boolean {- return !world.has(entity, Disabled);+ return world.valid(entity) && (world.getCppRegistry()?.isEntityEnabled?.(entity) ?? !world.has(entity, Disabled));}/**diff --git a/sdk/src/ecs/world.ts b/sdk/src/ecs/world.tsindex b202a9e9b..0c212d304 100644--- a/sdk/src/ecs/world.ts+++ b/sdk/src/ecs/world.ts@@ -20,6 +20,7 @@ import { rankByOrder, reorderMapByRank } from './entityOrder';import { worldEngineApi } from './bridge/engineApi';import { withScratch } from '../wasm/wasmScratch';import { log } from '../util/logger';+import { hasOwn } from '../util/ownProperties';import { getDefaultContext, type EditorBridge } from './context';/** The slice of a core {@link World.applyEntityOrder} needs: the entry point plus@@ -160,6 +161,7 @@ export class World {/** @see inactiveEntities_ */private inactive_: { set: Set<Entity> } | null = null;private inactiveVersion_ = -1;+ private coreActivityEpoch_ = -1;private entities_ = new Map<Entity, number>();private indexGeneration_ = new Map<number, number>(); // index -> current generation (for isStale detection)private iterationDepth_ = 0;@@ -168,6 +170,7 @@ export class World {private nextGeneration_ = 0;private spawnCallbacks_: Array<(entity: Entity) => void> = [];private despawnCallbacks_: Array<(entity: Entity) => void> = [];+ private despawning_: Set<Entity> | null = null;/** @internal */get builtin(): BuiltinBridge {@@ -188,12 +191,17 @@ export class World {): void {this.addressOf_.clear();this.builtin_.connect(cppRegistry, module, options);+ for (const e of this.scripts_.getStorageById(Disabled._id)?.keys() ?? []) cppRegistry.setEntityEnabled?.(e, false);+ this.coreActivityEpoch_ = cppRegistry.activityEpoch?.() ?? -1;+ this.queries_.markComponentDirty(Disabled._id);}/** @internal */disconnectCpp(): void {this.addressOf_.clear();this.builtin_.disconnect();+ this.coreActivityEpoch_ = -1;+ this.queries_.markComponentDirty(Disabled._id);}/** @internal Whether an engine core is bound — false in a pure-JS world. */@@ -296,24 +304,58 @@ export class World {'Use Commands to defer entity destruction until after iteration completes.');}- if (!this.valid(entity)) return; // already gone (e.g. despawned as part of a subtree)-- // Unlink from the parent (setParent-to-INVALID clears both sides), then- // tear down the whole subtree so no children are left orphaned + rendering.+ if (!this.valid(entity) || this.despawning_?.has(entity)) return;const cppRegistry = this.builtin_.getCppRegistry();- if (cppRegistry && cppRegistry.hasParent(entity)) {- try { cppRegistry.setParent(entity, INVALID_ENTITY); }- catch (e) { handleWasmError(e, `despawn(detach ${entity})`); }- }+ if (cppRegistry?.destructionPending?.(entity)) return;this.despawnSubtree_(entity, cppRegistry);}/** Depth-first teardown of `entity` and its descendants (children before parent). */private despawnSubtree_(entity: Entity, cppRegistry: CppRegistry | null): void {- for (const child of this.childEntitiesOf_(entity)) {- if (this.valid(child)) this.despawnSubtree_(child, cppRegistry);+ const reserved = this.despawning_ ??= new Set<Entity>();+ const owned: Entity[] = [], nativeOwned: Entity[] = [], postorder: Entity[] = [];+ const stack: Array<{ entity: Entity; children: Entity[] | null; next: number }> = [+ { entity, children: null, next: 0 },+ ];+ try {+ // Reserve the whole subtree before callbacks run. It cannot escape+ // through reparenting, receive new children, or be torn down twice+ // by a re-entrant callback. Snapshot each child list just once.+ while (stack.length) {+ const frame = stack[stack.length - 1];+ if (frame.children === null) {+ if (!this.valid(frame.entity) || reserved.has(frame.entity)+ || cppRegistry?.destructionPending?.(frame.entity)) { stack.pop(); continue; }+ reserved.add(frame.entity); owned.push(frame.entity);+ frame.children = this.childEntitiesOf_(frame.entity, true);+ }+ if (frame.next < frame.children.length) {+ stack.push({ entity: frame.children[frame.next++], children: null, next: 0 });+ } else {+ postorder.push(frame.entity); stack.pop();+ }+ }+ if (cppRegistry && cppRegistry.hasParent(entity)) {+ try { cppRegistry.setParent(entity, INVALID_ENTITY); }+ catch (e) { handleWasmError(e, `despawn(detach ${entity})`); }+ }+ // Detach before taking native ownership: setParent also rejects+ // reserved entities. The same core guard then protects raw registry+ // calls and native teardown invoked from an SDK callback.+ if (cppRegistry?.reserveDestruction && cppRegistry.releaseDestruction) {+ for (const current of owned) {+ if (cppRegistry.reserveDestruction(current)) nativeOwned.push(current);+ }+ }+ for (const current of postorder) if (this.valid(current)) this.despawnOne_(current, cppRegistry);+ } finally {+ for (const current of nativeOwned) cppRegistry!.releaseDestruction!(current);+ for (const current of owned) reserved.delete(current);+ if (reserved.size === 0) this.despawning_ = null;}+ }+ private despawnOne_(entity: Entity, cppRegistry: CppRegistry | null): void {notifyBridge('onEntityDespawned', entity);for (const cb of this.despawnCallbacks_) {@@ -374,10 +416,12 @@ export class World {* per-entity side table is cleaned up from.*/onDespawn(callback: (entity: Entity) => void): () => void {- this.despawnCallbacks_.push(callback);+ // Copy on subscription changes, so self-unsubscription during a+ // notification cannot skip the next observer. Dispatch allocates nothing.+ this.despawnCallbacks_ = [...this.despawnCallbacks_, callback];return () => {const idx = this.despawnCallbacks_.indexOf(callback);- if (idx !== -1) this.despawnCallbacks_.splice(idx, 1);+ if (idx !== -1) this.despawnCallbacks_ = this.despawnCallbacks_.filter((_, i) => i !== idx);};}@@ -387,6 +431,18 @@ export class World {return this.entities_.has(entity);}+ /** @internal True throughout subtree teardown, including queued ancestors. */+ isDestructionPending(entity: Entity): boolean {+ return !!this.despawning_?.has(entity)+ || !!this.builtin_.getCppRegistry()?.destructionPending?.(entity);+ }++ /** Effective activity, including ancestors; unlike valid(), an inactive+ * entity remains available for inspection, cleanup and serialization. */+ isEntityActive(entity: Entity): boolean {+ return this.valid(entity) && !this.inactiveEntities_()?.has(entity);+ }+/*** True if `entity` refers to a slot that has been recycled — its index is* currently live, but held by a *different* generation. Useful for@@ -436,6 +492,7 @@ export class World {/** @internal Structural version the query cache invalidates against. */getWorldVersion(): number {+ this.syncActivityEpoch_();return this.queries_.structuralVersion;}@@ -570,27 +627,43 @@ export class World {}}- /**- * Make `child` a child of `parent`. This is the side to write — the engine- * keeps {@link Parent} and {@link Children} in step from here, and a transform- * composes against whatever this names.- */+ /** Keep {@link Parent} and {@link Children} consistent when reparenting. */setParent(child: Entity, parent: Entity): void {+ this.trySetParent(child, parent);+ }++ /** Reject invalid relationships without changing hierarchy or notifications. */+ trySetParent(child: Entity, parent: Entity): boolean {+ if (parent === (0xFFFFFFFF as Entity)) parent = INVALID_ENTITY;+ if (this.despawning_?.has(child) || this.despawning_?.has(parent)) return false;+ if (!this.valid(child) || (parent !== INVALID_ENTITY && !this.valid(parent))) return false;const cppRegistry = this.builtin_.getCppRegistry();if (cppRegistry) {try {- cppRegistry.setParent(child, parent);+ const previous = cppRegistry.hasParent(child) ? cppRegistry.getParent(child).entity : INVALID_ENTITY;+ if (previous === parent) {+ return !cppRegistry.destructionPending?.(child) && !cppRegistry.destructionPending?.(parent);+ }+ // New cores return acceptance. A legacy void host remains+ // compatible; only an explicit rejection prevents bookkeeping.+ if (cppRegistry.setParent(child, parent) === false) return false;} catch (e) {handleWasmError(e, `setParent(child=${child}, parent=${parent})`);+ return false;}}- this.trackHierarchyWrite_(child, parent);- notifyBridge('onParentChanged', child, parent);+ const linkedParent = parent === INVALID_ENTITY ? null : parent;+ this.trackHierarchyWrite_(child, linkedParent);+ notifyBridge('onParentChanged', child, linkedParent);+ return true;}/** Detach `entity` from its parent, leaving its own children attached to it. */removeParent(entity: Entity): void {+ if (this.despawning_?.has(entity)) return;+ if (!this.valid(entity)) return;const cppRegistry = this.builtin_.getCppRegistry();+ if (cppRegistry?.destructionPending?.(entity)) return;if (cppRegistry) {try {cppRegistry.removeParent(entity);@@ -603,16 +676,23 @@ export class World {}/** `entity`'s children, snapshotted out of the wasm vector that holds them. */- private childEntitiesOf_(entity: Entity): Entity[] {+ private childEntitiesOf_(entity: Entity, strict = false): Entity[] {const cppRegistry = this.builtin_.getCppRegistry();if (!cppRegistry || !cppRegistry.hasChildren(entity)) return [];const children: Entity[] = [];try {// Snapshot then free the wasm VectorEntity (it leaks if left alive).const vec = cppRegistry.getChildren(entity).entities;- for (let i = 0; i < vec.size(); i++) children.push(vec.get(i) as Entity);- vec.delete();- } catch (e) { handleWasmError(e, `getChildren(entity=${entity})`); }+ try {+ const count = vec.size();+ for (let i = 0; i < count; i++) children.push(vec.get(i) as Entity);+ } finally { vec.delete(); }+ } catch (e) {+ handleWasmError(e, `getChildren(entity=${entity})`);+ // A partial snapshot is unsafe for deletion: it would remove the+ // parent while leaving unread children alive with dangling links.+ if (strict) throw e;+ }return children;}@@ -626,11 +706,11 @@ export class World {return { entity: INVALID_ENTITY };}this.setParent(entity, parent);- return { entity: parent };+ return this.has(entity, Parent) ? this.get(entity, Parent) : { entity: INVALID_ENTITY };}const listed = (data as Partial<ChildrenData> | undefined)?.entities ?? [];for (const child of listed) this.setParent(child as Entity, entity);- return { entities: [...listed] };+ return { entities: this.builtin_.hasCpp ? this.childEntitiesOf_(entity) : [...listed] };}private isHierarchyComponent_(component: AnyComponentDef): boolean {@@ -715,7 +795,7 @@ export class World {const raw = data as Record<string, unknown>;let wasmData = raw;for (const k of Object.keys(raw)) {- if (!(k in defaults)) {+ if (!hasOwn(defaults, k)) {if (wasmData === raw) wasmData = { ...raw };delete wasmData[k];}@@ -918,6 +998,7 @@ export class World {this.names_.remove(entity);}this.scripts_.remove(entity, component);+ if (component._id === Disabled._id) this.builtin_.getCppRegistry()?.setEntityEnabled?.(entity, true);this.changes_.recordRemoved(component, entity);this.queries_.markComponentDirty(component._id);this.queries_.markStructuralChange();@@ -1043,6 +1124,10 @@ export class World {* when the tag or the hierarchy moves; free when nothing is switched off.*/private inactiveEntities_(): { has(entity: Entity): boolean } | null {+ const core = this.builtin_.getCppRegistry();+ if (core?.isEntityActive && core.hasInactiveEntities) {+ return core.hasInactiveEntities() ? { has: e => !core.isEntityActive!(e) } : null;+ }const storage = this.scripts_.getStorageById(Disabled._id);if (!storage || storage.size === 0) return null;// One version covers both halves: a re-parent in a world that has anything@@ -1121,13 +1206,7 @@ export class World {filter?: QueryFilter,precomputedDepIds?: symbol[],): readonly Entity[] {- if (- components.length === 0 && withFilters.length === 0 &&- withoutFilters.length === 0 && !filter- ) {- return this.getAllEntities();- }-+ this.syncActivityEpoch_();const cacheKey = precomputedKey ?? computeQueryCacheKey(components, withFilters, withoutFilters);// The dep-id set is static per query; QueryInstance precomputes it (incl.// filter deps) so cache-hit iteration allocates nothing here.@@ -1373,12 +1452,22 @@ export class World {* here whether or not the fast pointer setter moved the bytes.*/private recordComponentWrite_(entity: Entity, component: AnyComponentDef): void {+ if (component._id === Disabled._id) this.builtin_.getCppRegistry()?.setEntityEnabled?.(entity, false);if (COMPOSITION_INPUTS.has(component._name)) {this.builtin_.invalidateTransformComposition();}this.changes_.recordChanged(component, entity);}+ private syncActivityEpoch_(): void {+ const epoch = this.builtin_.getCppRegistry()?.activityEpoch?.();+ if (epoch === undefined || epoch === this.coreActivityEpoch_) return;+ if (this.coreActivityEpoch_ === -1) { this.coreActivityEpoch_ = epoch; return; }+ this.coreActivityEpoch_ = epoch;+ this.queries_.markComponentDirty(Disabled._id);+ this.queries_.markStructuralChange();+ }+/** @internal Say composed world transforms are stale, for a producer that* wrote the bytes without going through the mutation seam. */invalidateTransformComposition(): void {@@ -1454,8 +1543,8 @@ export class World {* installs linear memory here BEFORE any component is added, because* compiled code cannot reach a JS-heap array.*/- useScriptPoolMemory(memory: PoolMemory): void {- this.scripts_.usePoolMemory(memory);+ useScriptPoolMemory(memory: PoolMemory, validateOnly = false): void {+ this.scripts_.usePoolMemory(memory, validateOnly);}/**@@ -1506,6 +1595,17 @@ export class World {return this.scripts_.poolFor(component._id as symbol)?.span();}+ /** @internal Whether script rows still carry a portable asset reference. */+ hasPortableScriptAssetRefs(component: AnyComponentDef): boolean {+ return this.scripts_.hasPortableAssetRefs(component._id as symbol);+ }++ /** @internal Release script memory after its application stops using it. */+ releaseScriptPools(): void {+ this.addressOf_.clear();+ this.scripts_.releasePools();+ }+/*** @internal The same answer as a function, for a caller with a whole column* to walk: the lookup above is per entity, and a loop that pays it per row is@@ -1538,6 +1638,7 @@ const NO_ADDRESS = (): undefined => undefined;function scriptAddress(scripts: ScriptStorage, id: symbol): (entity: Entity) => number | undefined {let pool: ScriptPool | undefined;return (entity: Entity) => {+ if (pool?.disposed) pool = undefined;pool ??= scripts.poolFor(id);return pool?.address(entity);};diff --git a/sdk/src/physics/PhysicsSystem.ts b/sdk/src/physics/PhysicsSystem.tsindex 686239e3c..c0f196f4b 100644--- a/sdk/src/physics/PhysicsSystem.ts+++ b/sdk/src/physics/PhysicsSystem.ts@@ -847,9 +847,19 @@ export function registerPhysics2DSystem(else kinematicEntities.delete(entity);}- // Bodies whose entity left the query without firing onDespawn.+ // Activity filtering removes descendants from the query too.+ // Freeze those bodies in place so reactivation keeps velocity,+ // shapes and joints; only component removal destroys the body.for (const entity of trackedEntities) {if (!currentEntities.has(entity)) {+ if (world.has(entity, RigidBody2D) && world.has(entity, Transform)) {+ const cached = cachedProps.get(entity)!;+ if (cached.enabled) {+ module._physics_setBodyEnabled(entity, 0);+ cached.enabled = false;+ }+ continue;+ }module._physics_destroyBody(entity);trackedEntities.delete(entity);cachedProps.delete(entity);@@ -882,6 +892,7 @@ export function registerPhysics2DSystem(// velocity is what carries/pushes resting dynamic bodies (a plain// teleport reports zero velocity, so platforms wouldn't move riders).for (const entity of kinematicEntities) {+ if (!cachedProps.get(entity)?.enabled) continue;const wt = world.get(entity, Transform) as TransformData;module._physics_setBodyTargetTransform(entity,diff --git a/sdk/src/prefab.ts b/sdk/src/prefab.tsindex b95b67d84..cd3b250cd 100644--- a/sdk/src/prefab.ts+++ b/sdk/src/prefab.ts@@ -3,7 +3,7 @@import type { World } from './ecs/world';import type { Entity } from './types';import type { Assets } from './asset/Assets';-import { loadSceneWithAssets, SCENE_FORMAT_VERSION, type SceneData } from './scene/scene';+import { loadOwnedSceneWithAssets, SCENE_FORMAT_VERSION, type SceneData } from './scene/scene';import {flattenPrefab,preloadNestedPrefabs,@@ -108,7 +108,7 @@ export async function instantiatePrefab(})),};- const entityMap = await loadSceneWithAssets(world, sceneData, {+ const entityMap = await loadOwnedSceneWithAssets(world, sceneData, {assets: options?.assets,assetBaseUrl: options?.assetBaseUrl,});diff --git a/sdk/src/prefab/clone.ts b/sdk/src/prefab/clone.tsindex 51bb9f1ad..81aaf056c 100644--- a/sdk/src/prefab/clone.ts+++ b/sdk/src/prefab/clone.ts@@ -1,18 +1,19 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport type { ComponentData } from './types';+import { cloneJsonValue } from '../util/cloneJsonValue';export function cloneComponents(components: ComponentData[]): ComponentData[] {return components.map(c => ({type: c.type,- data: JSON.parse(JSON.stringify(c.data)),+ data: cloneJsonValue(c.data),}));}export function cloneComponentData(data: Record<string, unknown>): Record<string, unknown> {- return JSON.parse(JSON.stringify(data));+ return cloneJsonValue(data);}export function cloneMetadata(metadata: Record<string, unknown>): Record<string, unknown> {- return JSON.parse(JSON.stringify(metadata));+ return cloneJsonValue(metadata);}diff --git a/sdk/src/prefab/diff.ts b/sdk/src/prefab/diff.tsindex 112673ba7..65e898b11 100644--- a/sdk/src/prefab/diff.ts+++ b/sdk/src/prefab/diff.ts@@ -9,6 +9,7 @@ import type {} from './types';import { getComponent } from '../ecs/component';import { mapEntityRefField } from './entityRef';+import { hasOwn } from '../util/ownProperties';/*** An entity-typed field on an instance holds a numeric runtime id; the source@@ -214,8 +215,8 @@ function diffMetadata(const keys = new Set<string>([...Object.keys(src), ...Object.keys(inst)]);for (const key of keys) {if (ignored.has(key)) continue;- const inSrc = key in src;- const inInst = key in inst;+ const inSrc = hasOwn(src, key);+ const inInst = hasOwn(inst, key);if (inInst && !inSrc) {out.push({ prefabEntityId: entityId, type: 'metadata_set', metadataKey: key, value: inst[key] });} else if (!inInst && inSrc) {@@ -311,7 +312,7 @@ function deepEqual(a: unknown, b: unknown, eps = 0): boolean {const ak = Object.keys(ao);const bk = Object.keys(bo);if (ak.length !== bk.length) return false;- for (const k of ak) if (!deepEqual(ao[k], bo[k], eps)) return false;+ for (const k of ak) if (!hasOwn(bo, k) || !deepEqual(ao[k], bo[k], eps)) return false;return true;}diff --git a/sdk/src/prefab/flatten.ts b/sdk/src/prefab/flatten.tsindex 1ab65ef2c..d000f8da4 100644--- a/sdk/src/prefab/flatten.ts+++ b/sdk/src/prefab/flatten.ts@@ -13,6 +13,7 @@ import { PREFAB_ADDRESS_SEP } from './types';import { cloneComponents, cloneMetadata } from './clone';import { remapComponentEntityRefs } from './entityRef';import { applyOverrides, bucketOverridesByEntity } from './override';+import { createChildLookup, checkParentCycle } from '../document/diagnostics';const MAX_PREFAB_NESTING_DEPTH = 10;@@ -135,9 +136,8 @@ export function flattenPrefab(parent: isRoot? null: (pe.parent !== null ? idMapping.get(pe.parent) ?? null : null),- children: pe.children- .map(c => idMapping.get(c))- .filter((c): c is number => c !== undefined),+ // Filled after every nested slot has an allocated runtime id.+ children: [],components: cloneComponents(pe.components),visible: pe.visible,...(pe.metadata ? { metadata: cloneMetadata(pe.metadata) } : {}),@@ -165,29 +165,25 @@ export function flattenPrefab();}- // Second pass: heal top-level parent/child links now that idMapping is- // complete. A nested SLOT's runtime id is only known after its own flatten, so- // an entity parented to a slot that appears LATER in a non-tree-ordered- // `entities` array resolved to null (and dropped from the slot's children) in- // the loop above. Re-resolve every top-level link so flatten is order-independent;- // for a tree-ordered file every link already matches and this is a no-op.+ // Resolve authored links only after nested slots have ids. Preserve the+ // children order the author serialized, including slots that were flattened+ // later; entity-array order is not sibling order.const byRuntimeId = new Map(result.map((e) => [e.id, e]));for (const pe of prefab.entities) {- if (pe.prefabEntityId === prefab.rootEntityId) continue;const childId = idMapping.get(pe.prefabEntityId);if (childId === undefined) continue;const entity = byRuntimeId.get(childId);if (!entity) continue;- const wantParent = pe.parent !== null ? (idMapping.get(pe.parent) ?? null) : null;- if (entity.parent === wantParent) continue;- if (entity.parent != null) {- const old = byRuntimeId.get(entity.parent);- if (old) old.children = old.children.filter((c) => c !== childId);- }- entity.parent = wantParent;- if (wantParent != null) {- const np = byRuntimeId.get(wantParent);- if (np && !np.children.includes(childId)) np.children.push(childId);+ entity.parent = pe.prefabEntityId === prefab.rootEntityId ? null+ : (pe.parent !== null ? idMapping.get(pe.parent) ?? null : null);+ const authored = pe.children.map(c => idMapping.get(c)).filter((c): c is number => c !== undefined);+ if (!pe.nestedPrefab) {+ entity.children = authored;+ } else if (authored.length) {+ // A mounted root keeps its own subtree, then children authored on+ // the mounting slot. They share the same final parent.+ const present = new Set(entity.children);+ for (const id of authored) if (!present.has(id)) { present.add(id); entity.children.push(id); }}}@@ -288,13 +284,11 @@ function mergeVariantEntities(base: PrefabData, variant: PrefabData): PrefabData);}- const baseById = new Map<PrefabEntityId, PrefabEntityData>();- for (const e of base.entities) baseById.set(e.prefabEntityId, e);-const merged: PrefabEntityData[] = base.entities.map(e => ({ ...e }));const mergedById = new Map<PrefabEntityId, PrefabEntityData>();for (const e of merged) mergedById.set(e.prefabEntityId, e);+ const mergedIndex = new Map(merged.map((e, i) => [e.prefabEntityId, i]));const variantEntities = variant.entities ?? [];for (const ve of variantEntities) {const existing = mergedById.get(ve.prefabEntityId);@@ -311,7 +305,7 @@ function mergeVariantEntities(base: PrefabData, variant: PrefabData): PrefabData})),...(ve.metadata ? { metadata: { ...ve.metadata } } : {}),};- const idx = merged.indexOf(existing);+ const idx = mergedIndex.get(ve.prefabEntityId)!;merged[idx] = replaced;mergedById.set(ve.prefabEntityId, replaced);continue;@@ -334,6 +328,7 @@ function mergeVariantEntities(base: PrefabData, variant: PrefabData): PrefabData})),...(ve.metadata ? { metadata: { ...ve.metadata } } : {}),};+ mergedIndex.set(ve.prefabEntityId, merged.length);merged.push(added);mergedById.set(ve.prefabEntityId, added);}@@ -341,6 +336,7 @@ function mergeVariantEntities(base: PrefabData, variant: PrefabData): PrefabData// Pass 2: link added entities into their parents' children lists,// and validate referential integrity.const baseIds = new Set(base.entities.map(e => e.prefabEntityId));+ const extendedChildren = new Map<PrefabEntityId, Set<PrefabEntityId>>();for (const ve of variantEntities) {const isNew = !baseIds.has(ve.prefabEntityId);if (!isNew) continue;@@ -351,8 +347,15 @@ function mergeVariantEntities(base: PrefabData, variant: PrefabData): PrefabData`"${ve.parent!}" not found in base or other variant additions.`,);}- if (!parent.children.includes(ve.prefabEntityId)) {- parent.children = [...parent.children, ve.prefabEntityId];+ let children = extendedChildren.get(parent.prefabEntityId);+ if (!children) {+ children = new Set(parent.children);+ parent.children = [...parent.children]; // one owned copy, never mutate the base+ extendedChildren.set(parent.prefabEntityId, children);+ }+ if (!children.has(ve.prefabEntityId)) {+ children.add(ve.prefabEntityId);+ parent.children.push(ve.prefabEntityId);}}@@ -372,6 +375,7 @@ function mergeVariantEntities(base: PrefabData, variant: PrefabData): PrefabDatafunction validateParentChildConsistency(prefab: PrefabData): void {const byId = new Map<PrefabEntityId, PrefabEntityData>();for (const e of prefab.entities) byId.set(e.prefabEntityId, e);+ const hasChild = createChildLookup<PrefabEntityId>();for (const e of prefab.entities) {// The address separator is reserved so flatten can compose `slot/localId`@@ -391,7 +395,7 @@ function validateParentChildConsistency(prefab: PrefabData): void {`"${e.parent}" does not exist.`,);}- if (!parent.children.includes(e.prefabEntityId)) {+ if (!hasChild(parent.children, e.prefabEntityId)) {throw new Error(`Prefab "${prefab.name}" inconsistent topology: entity ` +`"${e.prefabEntityId}" claims parent "${e.parent}" but the ` +@@ -420,29 +424,9 @@ function validateParentChildConsistency(prefab: PrefabData): void {}function detectCycle(entities: PrefabEntityData[], prefabName: string): void {- const byId = new Map<PrefabEntityId, PrefabEntityData>();- for (const e of entities) byId.set(e.prefabEntityId, e);- const WHITE = 0, GRAY = 1, BLACK = 2;- const color = new Map<PrefabEntityId, number>();- for (const e of entities) color.set(e.prefabEntityId, WHITE);-- const visit = (id: PrefabEntityId, path: PrefabEntityId[]): void => {- const c = color.get(id);- if (c === BLACK) return;- if (c === GRAY) {- const cycleStart = path.indexOf(id);- const cycle = path.slice(cycleStart).concat(id);- throw new Error(- `Prefab "${prefabName}" parent cycle detected: ${cycle.join(' → ')}`,- );- }- color.set(id, GRAY);- const entity = byId.get(id);- if (entity?.parent !== null && entity?.parent !== undefined) {- visit(entity.parent, [...path, id]);- }- color.set(id, BLACK);- };-- for (const e of entities) visit(e.prefabEntityId, []);+ const nodes = entities.map(e => ({ id: e.prefabEntityId, parent: e.parent,+ children: e.children, components: e.components }));+ checkParentCycle(nodes, new Map(nodes.map(e => [e.id, e])), (_code, _severity, message) => {+ throw new Error(`Prefab "${prefabName}" ${message}`);+ });}diff --git a/sdk/src/prefab/override.ts b/sdk/src/prefab/override.tsindex 69febeb12..f366f6da3 100644--- a/sdk/src/prefab/override.ts+++ b/sdk/src/prefab/override.ts@@ -7,6 +7,7 @@ import type {PrefabOverride,} from './types';import { cloneComponentData } from './clone';+import { setOwn } from '../util/ownProperties';/*** The fields {@link applyOverrides} reads/writes. Both `ProcessedEntity` (a@@ -53,7 +54,7 @@ export function applyOverrides(if (override.componentType && override.propertyName !== undefined) {const comp = entity.components.find(c => c.type === override.componentType);if (comp) {- comp.data[override.propertyName] = override.value;+ setOwn(comp.data, override.propertyName, cloneComponentData({ value: override.value }).value);}}break;@@ -104,7 +105,7 @@ export function applyOverrides(case 'metadata_set':if (typeof override.metadataKey === 'string') {if (!entity.metadata) entity.metadata = {};- entity.metadata[override.metadataKey] = override.value;+ setOwn(entity.metadata, override.metadataKey, cloneComponentData({ value: override.value }).value);}break;case 'metadata_removed':diff --git a/sdk/src/prefab/preparedAssetOwnership.ts b/sdk/src/prefab/preparedAssetOwnership.tsnew file mode 100644index 000000000..eac84bc8b--- /dev/null+++ b/sdk/src/prefab/preparedAssetOwnership.ts@@ -0,0 +1,80 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { AssetScope, type AssetLease } from '../asset/AssetLease';+import type { SceneAssetResult } from '../asset/Assets';+import { discoverSceneAssets, type RefResolver } from '../asset/discoverAssets';+import type { EntityAssetScopes } from '../asset/entityAssetScopes';+import type { World } from '../ecs/world';+import type { Entity } from '../types';+import type { SceneData } from '../scene/scene';+import { spinePairKey } from '../asset/spinePairKey';++/** Resources retained before a spawn; attachment transfers them to entity scopes. */+export interface PreparedSpawnOwnership {+ attach(world: World, entities: ReadonlyMap<number, Entity>): void;+ release(): void;+}++/** Project successful acquisitions onto immutable authored entities once, at bake time. */+export function prepareSpawnOwnership(+ scene: SceneData, result: SceneAssetResult, owners: EntityAssetScopes | undefined,+ resolveRef?: RefResolver,+): (() => PreparedSpawnOwnership) | undefined {+ if (!owners || !result.acquisitions?.length) return undefined;+ const index = new Map<string, Map<string, AssetLease>>();+ for (const { type, path, lease } of result.acquisitions) {+ let paths = index.get(type);+ if (!paths) index.set(type, paths = new Map());+ paths.set(path, lease);+ }+ const sources = new Map<number, readonly AssetLease[]>();+ for (const entity of scene.entities) {+ const refs = discoverSceneAssets({ ...scene, entities: [entity] }, resolveRef);+ const selected = new Set<AssetLease>();+ // Ref-bound loaders acquire the authored name; handle-bound loaders use+ // the resolved path. Both are spellings of an actual acquisition.+ for (const buckets of [refs.byType, refs.rawByType]) {+ for (const [type, paths] of buckets) {+ const acquired = index.get(type === 'bitmap-font' ? 'font' : type);+ for (const path of paths) {+ const lease = acquired?.get(path);+ if (lease) selected.add(lease);+ }+ }+ }+ for (const pair of refs.spines) {+ const lease = index.get('spine')?.get(spinePairKey(pair.skeleton, pair.atlas));+ if (lease) selected.add(lease);+ }+ if (selected.size) sources.set(entity.id, [...selected]);+ }+ if (!sources.size) return undefined;+ return () => {+ const retained = new Map<number, AssetScope>();+ const release = (): void => {+ for (const scope of retained.values()) scope.releaseAll();+ retained.clear();+ };+ try {+ for (const [id, leases] of sources) {+ const scope = new AssetScope(); retained.set(id, scope);+ for (const source of leases) {+ const lease = source.retain();+ if (!lease) throw new Error(`Cannot spawn retired prefab: resource "${source.key}" was released`);+ scope.add(lease);+ }+ }+ } catch (error) { release(); throw error; }+ return {+ attach(world, entities) {+ for (const [id, scope] of retained) {+ const entity = entities.get(id);+ if (entity !== undefined && world.valid(entity)) owners.ensure(world, entity).absorb(scope);+ }+ // Unspawned entities release their receipts; absorbed scopes are empty.+ release();+ },+ release,+ };+ };+}diff --git a/sdk/src/prefab/preparedPrefab.ts b/sdk/src/prefab/preparedPrefab.tsindex fe72bdd49..feb0ef37d 100644--- a/sdk/src/prefab/preparedPrefab.ts+++ b/sdk/src/prefab/preparedPrefab.ts@@ -26,7 +26,8 @@ import type { Entity } from '../types';import type { Assets } from '../asset/Assets';import { loadSceneData, SCENE_FORMAT_VERSION, type SceneData } from '../scene/scene';import { Transform } from '../ecs/component';-import { flattenPrefab, migratePrefabData, type FlattenContext, type PrefabData, type PrefabOverride } from './index';+import { prepareSpawnOwnership, type PreparedSpawnOwnership } from './preparedAssetOwnership';+import { flattenPrefab, migratePrefabData, preloadNestedPrefabs, type FlattenContext, type PrefabData, type PrefabOverride } from './index';/*** A prefab with its loading done: the flattened entities, their asset handles@@ -43,6 +44,10 @@ export interface PreparedPrefab {readonly missing: readonly string[];/** Give back everything the preparation took. */release(): void;+ /** @internal Retain exact resource generations before creating a spawned copy. */+ retainSpawnAssets?(): PreparedSpawnOwnership;+ /** @internal Record references against this copy's runtime IDs after spawning. */+ trackSpawnReferences?(entities: ReadonlyMap<number, number>): void;}/**@@ -55,6 +60,17 @@ export async function preparePrefab(assets: Assets,ref: string,overrides: readonly PrefabOverride[] = [],+): Promise<PreparedPrefab> {+ if (typeof assets.preparePrefab === 'function') return assets.preparePrefab(ref, overrides);+ return preparePrefabFromSource(assets, ref, overrides);+}++/** @internal The shared bake, with acquisition supplied by its owning era. */+export async function preparePrefabFromSource(+ assets: Pick<Assets, 'loadPrefab' | 'preloadSceneAssets' | 'resolveSceneAssetPaths'>+ & Partial<Pick<Assets, 'entityScopes' | 'resolveRef' | 'trackSceneAssetReferences'>>,+ ref: string,+ overrides: readonly PrefabOverride[] = [],): Promise<PreparedPrefab> {const loaded = await assets.loadPrefab(ref);const normalized = migratePrefabData(loaded.data as PrefabData).data;@@ -62,7 +78,8 @@ export async function preparePrefab(// Nested prefabs first: flattening reads them synchronously, so they have to// be in the cache before it runs.const cache = new Map<string, PrefabData>();- await collectNested(assets, normalized, cache);+ await preloadNestedPrefabs(normalized, async (path) =>+ migratePrefabData((await assets.loadPrefab(path)).data as PrefabData).data, cache);let nextId = 0;const ctx: FlattenContext = {@@ -84,6 +101,7 @@ export async function preparePrefab(// The same preload the scene runs, on the same shape — so a prefab spawned// from here and one placed in a scene get the same handles for the same refs.const result = await assets.preloadSceneAssets(scene);+ const retainSpawnAssets = prepareSpawnOwnership(scene, result, assets.entityScopes, assets.resolveRef?.bind(assets));assets.resolveSceneAssetPaths(scene, result);return {@@ -92,34 +110,11 @@ export async function preparePrefab(rootId,missing: result.missing.map((m) => m.ref),release: () => result.scope.releaseAll(),+ retainSpawnAssets,+ trackSpawnReferences: entities => assets.trackSceneAssetReferences?.(scene, entities),};}-/** Load every prefab nested inside `prefab`, into `cache`, depth first. */-async function collectNested(- assets: Assets, prefab: PrefabData, cache: Map<string, PrefabData>,-): Promise<void> {- for (const path of nestedRefs(prefab)) {- if (cache.has(path)) continue;- // Reserve before awaiting: a prefab that nests itself would otherwise- // recurse until the stack gave out.- cache.set(path, { entities: [], root: '' } as unknown as PrefabData);- const nested = migratePrefabData((await assets.loadPrefab(path)).data as PrefabData).data;- cache.set(path, nested);- await collectNested(assets, nested, cache);- }-}--/** The prefab paths one prefab's entities nest, in document order. */-function nestedRefs(prefab: PrefabData): string[] {- const out: string[] = [];- for (const entity of prefab.entities ?? []) {- const ref = (entity as { prefab?: { path?: string } }).prefab?.path;- if (typeof ref === 'string' && ref) out.push(ref);- }- return out;-}-export interface SpawnPreparedOptions {parent?: Entity;/** Where the root lands. Absent leaves the prefab's own transform. */@@ -137,14 +132,23 @@ export function spawnPrepared(): { root: Entity; entities: Map<number, Entity> } {// `loadSceneData` migrates, and migration deep-clones — so the prepared// scene is never mutated and one preparation spawns any number of copies.- const entities = loadSceneData(world, prepared.scene);- const root = entities.get(prepared.rootId)!;- if (options?.parent !== undefined) world.setParent(root, options.parent);- if (options?.position) {- // Transform is C++-backed, so the read is a copy: change it and hand it back.- const transform = world.get(root, Transform);- transform.position = { ...transform.position, ...options.position };- world.set(root, Transform, transform);- }- return { root, entities };+ const ownership = prepared.retainSpawnAssets?.();+ let entities: Map<number, Entity> | undefined;+ try {+ entities = loadSceneData(world, prepared.scene);+ ownership?.attach(world, entities);+ prepared.trackSpawnReferences?.(entities);+ const root = entities.get(prepared.rootId)!;+ if (options?.parent !== undefined) world.setParent(root, options.parent);+ if (options?.position) {+ // Transform is C++-backed, so the read is a copy: change it and hand it back.+ const transform = world.get(root, Transform);+ transform.position = { ...transform.position, ...options.position };+ world.set(root, Transform, transform);+ }+ return { root, entities };+ } catch (error) {+ if (entities) for (const entity of entities.values()) if (world.valid(entity)) world.despawn(entity);+ throw error;+ } finally { ownership?.release(); }}diff --git a/sdk/src/prefab/validate.ts b/sdk/src/prefab/validate.tsindex a7ba200e6..bcb4c2158 100644--- a/sdk/src/prefab/validate.ts+++ b/sdk/src/prefab/validate.ts@@ -251,8 +251,8 @@ export function validatePrefab(if (byId.has(prefab.rootEntityId)) {const reachable = new Set<PrefabEntityId>();const queue: PrefabEntityId[] = [prefab.rootEntityId];- while (queue.length > 0) {- const cur = queue.shift()!;+ for (let head = 0; head < queue.length; head++) {+ const cur = queue[head];if (reachable.has(cur)) continue;reachable.add(cur);for (const c of byId.get(cur)?.children ?? []) if (byId.has(c)) queue.push(c);diff --git a/sdk/src/render/assetPreview.ts b/sdk/src/render/assetPreview.tsindex 30a5c1c7c..8f951c1f2 100644--- a/sdk/src/render/assetPreview.ts+++ b/sdk/src/render/assetPreview.ts@@ -30,7 +30,19 @@ export function previewCore(m: unknown): PreviewCore | null {* readback rides the engine's async seam: immediate on GL, resolved when the* staging-buffer map lands on WebGPU — one awaited call either way.*/-export async function drawPreview(m: PreviewCore, draw: () => void): Promise<ImageData | null> {+const previewTails = new WeakMap<PreviewCore, Promise<void>>();++export function drawPreview(m: PreviewCore, draw: () => void): Promise<ImageData | null> {+ // Draw, poll and copy own one shared buffer as a single operation. Even a+ // ready GL readback yields at await, so a second draw must wait for the copy.+ const result = (previewTails.get(m) ?? Promise.resolve()).then(() => readPreview(m, draw));+ const tail = result.then(() => {}, () => {});+ previewTails.set(m, tail);+ void tail.then(() => { if (previewTails.get(m) === tail) previewTails.delete(m); });+ return result;+}++async function readPreview(m: PreviewCore, draw: () => void): Promise<ImageData | null> {draw();if (await awaitReadback(() => m.renderer_pollPreviewReadback()) !== READBACK_READY) return null;const size = m.renderer_getPreviewSize();diff --git a/sdk/src/render/draw.ts b/sdk/src/render/draw.tsindex c9de3c296..3457bee4f 100644--- a/sdk/src/render/draw.ts+++ b/sdk/src/render/draw.ts@@ -461,24 +461,21 @@ export const Draw: DrawAPI = {// False means the shader has no #pragma-param layout — legacy stream below.if (m.draw_meshWithMaterial(geometry, material)) return;- Draw.setBlendMode(matData.blendMode);- Draw.setDepthTest(matData.depthTest);+ const state = Material.getRenderState(material);+ if (!state) return;+ Draw.setBlendMode(state.blendMode);+ Draw.setDepthTest(state.depthTest);if (transform) m.HEAPF32.set(transform, transformPtr / 4);else m.HEAPF32.set(IDENTITY_TRANSFORM, transformPtr / 4);- if (matData.uniforms.size === 0) {- m.draw_mesh(geometry, matData.shader, transformPtr);- return;- }-let idx: number;if (!matData.dirty_ && matData.cachedBuffer_) {idx = matData.cachedIdx_;} else {idx = 0;let autoTextureSlot = 0;- for (const [name, value] of matData.uniforms) {+ for (const [name, value] of Material.getUniforms(material)) {if (idx > UNIFORMS_BUFFER_SIZE - 6) {log.warn('draw', 'Uniform buffer overflow, some uniforms will be ignored');break;@@ -518,12 +515,12 @@ export const Draw: DrawAPI = {}if (idx === 0) {- m.draw_mesh(geometry, matData.shader, transformPtr);+ m.draw_mesh(geometry, state.shader, transformPtr);return;}m.HEAPF32.set(matData.cachedBuffer_!.subarray(0, idx), uniformsPtr / 4);- m.draw_meshWithUniforms(geometry, matData.shader, transformPtr, uniformsPtr, idx);+ m.draw_meshWithUniforms(geometry, state.shader, transformPtr, uniformsPtr, idx);} catch (e) {handleWasmError(e, `Draw.drawMeshWithMaterial(geometry=${geometry}, material=${material})`);}diff --git a/sdk/src/render/material.ts b/sdk/src/render/material.tsindex 45dc0b836..b0c123c88 100644--- a/sdk/src/render/material.ts+++ b/sdk/src/render/material.ts@@ -26,6 +26,7 @@ export type MaterialHandle = number;export interface TextureRef {__textureRef: true;+ /** ResourceManager texture handle, resolved to a device texture at draw time. */textureId: number;slot?: number;}@@ -271,23 +272,24 @@ interface ResolvedMaterial {depthBias: number;uniforms: Map<string, UniformValue>;}+const NO_UNIFORMS = new Map<string, UniformValue>();// Flatten an instance chain to its effective material: the parent's values with this// material's overrides applied (uniforms by key, render state by `overrides`). Defensive// against a missing parent (e.g. a released base) — falls back to the material's own values.-function resolveMaterial(handle: MaterialHandle): ResolvedMaterial | null {+function resolveMaterial(handle: MaterialHandle, includeUniforms = true): ResolvedMaterial | null {const data = materials.get(handle);if (!data) return null;- const parent = data.parent !== undefined ? resolveMaterial(data.parent) : null;+ const parent = data.parent !== undefined ? resolveMaterial(data.parent, includeUniforms) : null;if (!parent) {return {shader: data.shader, blendMode: data.blendMode, depthTest: data.depthTest,depthWrite: data.depthWrite, cull: data.cull, depthBias: data.depthBias,- uniforms: new Map(data.uniforms),+ uniforms: includeUniforms ? new Map(data.uniforms) : NO_UNIFORMS,};}const uniforms = parent.uniforms; // fresh map from the recursive call- for (const [k, v] of data.uniforms) uniforms.set(k, v); // instance overrides win+ if (includeUniforms) for (const [k, v] of data.uniforms) uniforms.set(k, v); // instance overrides winreturn {shader: parent.shader, // instances inherit the shaderblendMode: data.overrides.has('blendMode') ? data.blendMode : parent.blendMode,@@ -301,16 +303,23 @@ function resolveMaterial(handle: MaterialHandle): ResolvedMaterial | null {// Push a material's flattened state to the engine, then re-flush every instance of it — so a// base edit propagates to non-overriding children. The single push point for create + edits.-function flushMaterial(handle: MaterialHandle): void {+function flushMaterial(handle: MaterialHandle, previous?: ReadonlyMap<MaterialHandle, ResolvedMaterial>): void {const resolved = resolveMaterial(handle);if (resolved && module) {+ // define preserves existing constants and texture bindings. A deleted value+ // must return to the shader default, including in inheriting descendants.+ const old = previous?.get(handle);+ if (old && [...old.uniforms.keys()].some(name => !resolved.uniforms.has(name)))+ module.material_undefine(handle);module.material_define(handle, resolved.shader, resolved.blendMode,materialFlags(resolved.depthTest, resolved.depthWrite, resolved.cull),resolved.depthBias);for (const [name, value] of resolved.uniforms) pushUniform(handle, name, value);}+ const data = materials.get(handle);+ if (data) data.dirty_ = true;const kids = childrenOf.get(handle);- if (kids) for (const child of kids) flushMaterial(child);+ if (kids) for (const child of kids) flushMaterial(child, previous);}// Convert a .esmaterial `properties` map (JSON numbers / colors / vectors) into typed@@ -431,6 +440,49 @@ export const Material = {return materials.get(material);},+ /** Effective shader/render state without allocating or cloning uniform maps. */+ getRenderState(material: MaterialHandle): Omit<ResolvedMaterial, 'uniforms'> | null {+ const resolved = resolveMaterial(material, false);+ if (!resolved) return null;+ const { uniforms: _, ...state } = resolved;+ return state;+ },++ /**+ * Replace the complete local parameter/render-state snapshot and flush once.+ * Missing fields restore base defaults or remove an instance override, so+ * future parent edits keep propagating. Shader and parent ownership stay with+ * the asset loader; this operation never re-acquires a different generation.+ */+ applyState(material: MaterialHandle, state: Omit<MaterialOptions, 'shader'>): void {+ const data = materials.get(material);+ if (!data) return;+ const previous = new Map<MaterialHandle, ResolvedMaterial>();+ const collect = (handle: MaterialHandle): void => {+ if (previous.has(handle)) return;+ const resolved = resolveMaterial(handle);+ if (resolved) previous.set(handle, resolved);+ for (const child of childrenOf.get(handle) ?? []) collect(child);+ };+ collect(material);+ data.uniforms.clear();+ for (const [name, value] of Object.entries(state.uniforms ?? {})) {+ warnUndeclared(shaderOf(material), name); data.uniforms.set(name, value);+ }+ data.blendMode = state.blendMode ?? BlendMode.Normal;+ data.depthTest = state.depthTest ?? false;+ data.depthWrite = state.depthWrite ?? true;+ data.cull = state.cull ?? CullMode.None;+ data.depthBias = Math.round(state.depthBias ?? 0);+ data.switches = { ...state.switches };+ data.overrides.clear();+ if (data.parent !== undefined) {+ for (const key of ['blendMode', 'depthTest', 'depthWrite', 'cull', 'depthBias'] as const)+ if (state[key] !== undefined) data.overrides.add(key);+ }+ flushMaterial(material, previous);+ },+/*** Sets a uniform value on a material.* @param material Material handle@@ -478,7 +530,7 @@ export const Material = {* @returns Blend mode*/getBlendMode(material: MaterialHandle): BlendMode {- return resolveMaterial(material)?.blendMode ?? BlendMode.Normal;+ return resolveMaterial(material, false)?.blendMode ?? BlendMode.Normal;},/**@@ -535,7 +587,7 @@ export const Material = {* @returns Shader handle*/getShader(material: MaterialHandle): ShaderHandle {- return resolveMaterial(material)?.shader ?? 0;+ return resolveMaterial(material, false)?.shader ?? 0;},/**diff --git a/sdk/src/render/skeletalPreview.ts b/sdk/src/render/skeletalPreview.tsindex bdf9d6016..1099f1b8e 100644--- a/sdk/src/render/skeletalPreview.ts+++ b/sdk/src/render/skeletalPreview.ts@@ -23,7 +23,8 @@ export type SkeletalPreviewCore = Pick<ESEngineModule,| 'renderer_renderSkeletalPreview' | 'renderer_pollSkeletalPreview'| 'renderer_getSkeletalPreviewPtr' | 'renderer_getSkeletalPreviewSize'| 'renderer_getSkeletalPreviewWidth' | 'renderer_getSkeletalPreviewHeight'- | 'renderer_destroySkeletalPreview' | '_malloc' | '_free' | 'HEAPU8'>;+ | 'renderer_destroySkeletalPreview' | '_malloc' | '_free' | 'HEAPU8'>+ & Partial<Pick<ESEngineModule, 'renderer_submitSkeletalPreviewBatchEx'>>;/** The connected core, when it answers the skeletal-preview surface. */export function skeletalPreviewCore(m: unknown): SkeletalPreviewCore | null {@@ -40,6 +41,7 @@ export interface SkeletalPreviewBatch {indexCount: number;textureId: number;blendMode: number;+ premultipliedColor?: boolean;/** Column-major 4×4, as the renderer takes a model matrix. */transform: Float32Array;materialId?: number;@@ -86,10 +88,14 @@ export class SkeletalPreview {core.HEAPU8.set(batch.vertices, vp);core.HEAPU8.set(batch.indices, ip);core.HEAPU8.set(new Uint8Array(batch.transform.buffer, batch.transform.byteOffset, 16 * 4), tp);- return core.renderer_submitSkeletalPreviewBatch(- this.id, vp, batch.vertexCount, ip, batch.indexCount,- batch.textureId, batch.blendMode, tp,- batch.layer ?? 0, batch.depth ?? 0, batch.materialId ?? 0) !== 0;+ return (core.renderer_submitSkeletalPreviewBatchEx+ ? core.renderer_submitSkeletalPreviewBatchEx(this.id,+ vp, batch.vertexCount, ip, batch.indexCount, batch.textureId, batch.blendMode, tp,+ batch.layer ?? 0, batch.depth ?? 0, batch.materialId ?? 0,+ batch.premultipliedColor ?? (batch.blendMode === 4 || batch.blendMode === 5))+ : core.renderer_submitSkeletalPreviewBatch(this.id,+ vp, batch.vertexCount, ip, batch.indexCount, batch.textureId, batch.blendMode, tp,+ batch.layer ?? 0, batch.depth ?? 0, batch.materialId ?? 0)) !== 0;});}diff --git a/sdk/src/runtime/runtimeLoader.ts b/sdk/src/runtime/runtimeLoader.tsindex 9abe4a756..a477d1f28 100644--- a/sdk/src/runtime/runtimeLoader.ts+++ b/sdk/src/runtime/runtimeLoader.ts@@ -23,6 +23,7 @@ import { applyAudioProjectConfig, type AudioProjectConfig } from '../audio/Audioimport type { App } from '../app/app';import { Assets as AssetsClass } from '../asset/Assets';import { Assets as AssetsResource } from '../asset/AssetPlugin';+import { bindAssetReferenceTracking } from '../asset/assetReferenceTracking';import { basisTranscoderFor } from '../asset/basisWorkers';import type { BasisTranscoder } from '../asset/compressed';import type { TextureImportSettings } from '../asset/loaders/TextureLoader';@@ -92,9 +93,8 @@ const runtimeImportSettings = new WeakMap<AssetsClass, Record<string, TextureImp* the addressable manifest survive scene switches — `Assets.loadGroup` keeps* working after the first scene, and re-entering a scene revives resident* textures instead of re-decoding. The first scene load's `source` wins; one- * App is expected to keep one asset source for its lifetime. No ref counter /- * catalog is attached (parity with the old runtime loader, which tracked- * neither and applied no atlas-frame indirection).+ * App is expected to keep one asset source for its lifetime. Reference tracking+ * shares the same World observer as AssetPlugin, including native runtimes.*/function ensureRuntimeAssets(app: App, module: ESEngineModule | null, source: RuntimeAssetSource, catalog?: Catalog,@@ -134,6 +134,9 @@ function ensureRuntimeAssets();runtimeImportSettings.set(assets, settings);+ bindAssetReferenceTracking(app.world, assets,+ () => app.hasResource(AssetsResource) ? app.getResource(AssetsResource) : null);+app.insertResource(AssetsResource, assets);return assets;}@@ -605,6 +608,7 @@ export async function publishRuntimeScene(const entityMap = await timed('spawn',() => loadSceneData(app.world, sceneData, options.externalEntities, onPhase));+ app.getResource(AssetsResource).trackSceneAssetReferences(sceneData, entityMap);// Which document row each entity came from, when someone is keeping track// (an editor inspecting its own running game). No-op otherwise.mark('origins', () => recordSceneOrigins(app, entityMap));diff --git a/sdk/src/runtime/webAppFactory.ts b/sdk/src/runtime/webAppFactory.tsindex 0fd612235..e8446f45d 100644--- a/sdk/src/runtime/webAppFactory.ts+++ b/sdk/src/runtime/webAppFactory.ts@@ -2,6 +2,7 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport { App, createWebApp as _createWebApp, type Plugin, type WebAppOptions } from '../app/app';import type { CppRegistry, ESEngineModule } from '../wasm';+import { log } from '../util/logger';import { assetPlugin } from '../asset';import { prefabsPlugin } from '../prefab/prefabServer';import { sceneManagerPlugin } from '../scene/scenePlugin';@@ -71,18 +72,24 @@ export function createHeadlessApp(module: ESEngineModule, options?: HeadlessAppOconst app = App.new();if (options?.sideModules) app.setSideModules(options.sideModules);const cppRegistry = new module.Registry() as unknown as CppRegistry;- app.connectCpp(cppRegistry, module, { strict: true });+ try {+ app.connectCpp(cppRegistry, module, { strict: true, ownedRegistry: true });- // No corePlugin: it wires the render facades (ResourceManager, draw,- // material, post-process) that only exist after initRenderer().- app.addPlugin(assetPlugin);- app.addPlugin(prefabsPlugin);- app.addPlugin(sceneManagerPlugin);- // A server steps what the client steps: the optional subsystems an entry- // installed run here too.- app.addPlugins(inBuildOrder([...headlessBasePlugins(), ...entryPlugins()]));- if (options?.plugins) app.addPlugins(options.plugins);- return app;+ // No corePlugin: it wires the render facades (ResourceManager, draw,+ // material, post-process) that only exist after initRenderer().+ app.addPlugin(assetPlugin);+ app.addPlugin(prefabsPlugin);+ app.addPlugin(sceneManagerPlugin);+ // A server steps what the client steps: the optional subsystems an entry+ // installed run here too.+ app.addPlugins(inBuildOrder([...headlessBasePlugins(), ...entryPlugins()]));+ if (options?.plugins) app.addPlugins(options.plugins);+ return app;+ } catch (error) {+ try { app.quit({ keepRenderer: true }); }+ catch (releaseError) { log.warn('app', 'Failed headless App construction cleanup error', releaseError); }+ throw error;+ }}/**diff --git a/sdk/src/runtime/worldSnapshot.ts b/sdk/src/runtime/worldSnapshot.tsindex 7e8045b2d..70136baa8 100644--- a/sdk/src/runtime/worldSnapshot.ts+++ b/sdk/src/runtime/worldSnapshot.ts@@ -48,13 +48,13 @@ export interface WorldSnapshotOptions {assetPath?: (path: string) => string | null;}-/** The component types an inspector shows for @p entity: not the tree's own- * structure, and never per-frame transient state. */-export function inspectableTypes(world: World, entity: number): string[] {+/** Authoring inspection omits transient state; runtime diagnostics may request+ * it explicitly. The tree's own structural fields remain separate. */+export function inspectableTypes(world: World, entity: number, includeTransient = false): string[] {return world.getComponentTypes(entity as never).filter((t) => {if (STRUCTURAL.has(t)) return false;const def = getComponent(t);- return !!def && !def.transient;+ return !!def && (includeTransient || !def.transient);});}diff --git a/sdk/src/scene/scene.ts b/sdk/src/scene/scene.tsindex b77cc2d43..d952ae1ff 100644--- a/sdk/src/scene/scene.ts+++ b/sdk/src/scene/scene.ts@@ -14,7 +14,7 @@ import { getComponent, Name, Camera, RuntimeOnly } from '../ecs/component';import { deepClone } from '../util/deepClone';import { discoverSceneAssets } from '../asset/discoverAssets';import { requireResourceManager } from '../wasm/resourceManager';-import { validateComponentData, formatValidationErrors, assetFieldNames } from '../util/validation';+import { validateComponentData, formatValidationErrors } from '../util/validation';import { log } from '../util/logger';import { ESTELLA_SCENE_GENERATOR } from '../util/provenance';import {@@ -413,6 +413,13 @@ export { RENAMED_COMPONENT_TYPES } from './legacyComponents';* loading never mutates the caller's object (snapshots can be reloaded).*/export function migrateSceneData(raw: SceneData): SceneMigrationResult {+ const fromVersion = checkSceneFormat(raw);+ // Public inputs remain caller-owned. Internal builders can hand over their+ // fresh private records to the same normalization without copying them twice.+ return migrateOwnedSceneData(JSON.parse(JSON.stringify(raw)) as SceneData, fromVersion);+}++function checkSceneFormat(raw: SceneData): number {if (!raw || typeof raw !== 'object' || !Array.isArray(raw.entities)) {throw new Error('Scene data must have an "entities" array');}@@ -424,10 +431,10 @@ export function migrateSceneData(raw: SceneData): SceneMigrationResult {);}- // Scene data is plain JSON — JSON clone is safe on every platform and frees- // the migrations/loader below to mutate without touching the caller's input.- const data: SceneData = JSON.parse(JSON.stringify(raw)) as SceneData;+ return fromVersion;+}+function migrateOwnedSceneData(data: SceneData, fromVersion = checkSceneFormat(data)): SceneMigrationResult {let migrated = false;const retired = new Set<string>();for (const entity of data.entities) {@@ -486,23 +493,22 @@ function spawnAndLoadEntities(checkLoadable(sceneData);if (onPhase) onPhase('spawn.validate', since());const entityMap = new Map<number, Entity>();-- for (const entityData of sceneData.entities) {- if (entityData.visible === false) continue;- // A prefab-instance entry reaching here means the synchronous path was- // used on an unexpanded prefab scene — it has no spawnable components.- // Skip it (loadSceneWithAssets is the supported prefab-scene path).- if (isPrefabEntry(entityData)) {- log.warn('scene', 'Prefab-instance entry skipped in synchronous load; use loadSceneWithAssets to load prefab scenes');- continue;+ try {+ for (const entityData of sceneData.entities) {+ if (entityData.visible === false) continue;+ // A prefab-instance entry reaching here means the synchronous path was+ // used on an unexpanded prefab scene — it has no spawnable components.+ // Skip it (loadSceneWithAssets is the supported prefab-scene path).+ if (isPrefabEntry(entityData)) {+ log.warn('scene', 'Prefab-instance entry skipped in synchronous load; use loadSceneWithAssets to load prefab scenes');+ continue;+ }+ const entity = world.spawn();+ entityMap.set(entityData.id, entity);+ world.insert(entity, Name, { value: entityData.name });}- const entity = world.spawn();- entityMap.set(entityData.id, entity);- world.insert(entity, Name, { value: entityData.name });- }- if (onPhase) onPhase('spawn.entities', since());+ if (onPhase) onPhase('spawn.entities', since());- try {// By component TYPE, because "component writes" is a rename of the total// and not an answer: which writes reach a subsystem, and which are field// validation, is the difference between a mechanism and a number.@@ -581,12 +587,7 @@ export async function loadSceneWithAssets(sceneData: SceneData,options?: SceneLoadOptions): Promise<Map<number, Entity>> {- const onPhase = options?.onPhase;- const timed = async <T>(phase: string, run: () => Promise<T> | T): Promise<T> => {- if (!onPhase) return run();- const began = performance.now();- try { return await run(); } finally { onPhase(phase, performance.now() - began); }- };+ const timed = scenePhaseRunner(options?.onPhase);// Expand prefab-instance entries first (via the same flattenPrefab core the// editor uses) so migration + asset resolution + spawn all operate on plain// entities — this is how a saved prefab scene achieves play == ship. The@@ -607,6 +608,36 @@ export async function loadSceneWithAssets(// Migrate up-front to a private copy; asset resolution + spawn all operate// on it, so the caller's SceneData is never mutated.const { data } = migrateSceneData(scene);+ return loadSceneAssetsAndSpawn(world, data, options, timed);+}++/**+ * Consume fresh private scene records from an internal builder. The builder must+ * have copied every mutable component and override value before handing them+ * over. Validation, migrations, asset resolution and spawning are shared with+ * the public scene loader; only its caller-protection copy is already paid.+ * @internal+ */+export async function loadOwnedSceneWithAssets(+ world: World, scene: SceneData, options?: SceneLoadOptions,+): Promise<Map<number, Entity>> {+ const timed = scenePhaseRunner(options?.onPhase);+ const { data } = migrateOwnedSceneData(scene);+ return loadSceneAssetsAndSpawn(world, data, options, timed);+}++function scenePhaseRunner(onPhase?: ScenePhaseSink) {+ return async <T>(phase: string, run: () => Promise<T> | T): Promise<T> => {+ if (!onPhase) return run();+ const began = performance.now();+ try { return await run(); } finally { onPhase(phase, performance.now() - began); }+ };+}++async function loadSceneAssetsAndSpawn(+ world: World, data: SceneData, options: SceneLoadOptions | undefined,+ timed: <T>(phase: string, run: () => Promise<T> | T) => Promise<T>,+): Promise<Map<number, Entity>> {if (options?.assets) {const assets = options.assets;const result = await timed('assets', () => assets.preloadSceneAssets(data, options.onProgress));@@ -628,7 +659,9 @@ export async function loadSceneWithAssets(}}}- return timed('spawn', () => spawnAndLoadEntities(world, data, options?.externalEntities, onPhase));+ const entities = timed('spawn', () => spawnAndLoadEntities(world, data, options?.externalEntities, options?.onPhase));+ options?.assets?.trackSceneAssetReferences(data, entities);+ return entities;}function applyTextureMetadata(sceneData: SceneData, textureHandles: Map<string, number>): void {@@ -670,7 +703,7 @@ export function loadComponent(world: World, entity: Entity, compData: SceneCompo// Asset-ref fields validate leniently: their serialized string ref and runtime// numeric handle are both legal (a Tiled-imported Tilemap's `source: 0` == "none").const context = entityName ? ` (entity "${entityName}")` : '';- const errors = validateComponentData(compData.type, comp._default as Record<string, unknown>, compData.data, assetFieldNames(comp));+ const errors = validateComponentData(compData.type, comp._default as Record<string, unknown>, compData.data, comp.assetFields);if (errors.length > 0) {// Salvage, not sacrifice: deserialized data is the one input the strict// storage validators must not veto wholesale — drop the invalid fields sodiff --git a/sdk/src/scene/sceneManager.ts b/sdk/src/scene/sceneManager.tsindex d4fef4f98..3ae0d3794 100644--- a/sdk/src/scene/sceneManager.ts+++ b/sdk/src/scene/sceneManager.ts@@ -960,7 +960,7 @@ export const SceneManager = defineResource<SceneManagerState>(* working the rule out for itself hands its replacement to the app instead.*/export function assetScopeForEntity(app: App, assets: AssetsData, entity: Entity): AssetScope {- const own = assets.entityScopes.scopeFor(entity);+ const own = assets.entityScopes.scopeFor(entity, app.world);if (own) return own;const owner = app.world.tryGet(entity, SceneOwner);const scene = owner?.scene && app.hasResource(SceneManager)diff --git a/sdk/src/skeletal/enableSync.ts b/sdk/src/skeletal/enableSync.tsindex 27ea8f635..a562a6ffa 100644--- a/sdk/src/skeletal/enableSync.ts+++ b/sdk/src/skeletal/enableSync.ts@@ -57,10 +57,12 @@ export class SkeletalEnableMirror {constructor(private readonly component_: AnyComponentDef) {}- sync(world: SkeletalEnableWorld, target: SkeletalEnableTarget): void {+ sync(world: SkeletalEnableWorld, target: SkeletalEnableTarget, isActive?: (entity: Entity) => boolean): void {let bound = 0;for (const entity of target.boundEntities()) {bound++;+ // Read new bindings once; inactive ones catch up before they resume.+ if (this.mirrored_.has(entity) && isActive && !isActive(entity)) continue;const data = world.tryGet(entity, this.component_) as { enabled?: boolean } | null;// No component (an entity bound by something other than a scene —// a test, a tool) has no flag to obey, so it is left alone.diff --git a/sdk/src/skeletal/meshBatches.ts b/sdk/src/skeletal/meshBatches.tsindex 1e004646e..cd31070c2 100644--- a/sdk/src/skeletal/meshBatches.ts+++ b/sdk/src/skeletal/meshBatches.ts@@ -29,6 +29,7 @@ export interface SkeletalHeap {/** The four readback entry points, however a module spells them. */export interface MeshBatchSource {getMeshBatchCount(instanceId: number): number;+ getMeshBatchColorPremultiplied?(instanceId: number, batchIndex: number): number;getMeshBatchVertexCount(instanceId: number, batchIndex: number): number;getMeshBatchIndexCount(instanceId: number, batchIndex: number): number;getMeshBatchData(@@ -40,7 +41,7 @@ export interface MeshBatchSource {export type MeshBatchVisitor = (vertBytes: Uint8Array, indexBytes: Uint8Array,vertexCount: number, indexCount: number,- textureId: number, blendMode: number,+ textureId: number, blendMode: number, premultipliedColor?: boolean,) => void;/** Interleaved x,y,u,v,r,g,b,a — the layout every skeletal module writes. */@@ -90,12 +91,17 @@ export function forEachMeshBatch(probe.bytes.scratchAllocated += vertByteLen + idxByteLen;probe.bytes.wasmRead += vertByteLen + idxByteLen;}+ const blendMode = heap.HEAPU32[blendPtr >> 2];+ const premultipliedColor = api.getMeshBatchColorPremultiplied+ ? api.getMeshBatchColorPremultiplied(instanceId, i) !== 0+ : blendMode === 4 || blendMode === 5;+ if (probe && api.getMeshBatchColorPremultiplied) probe.abi.batchColor++;cb(new Uint8Array(heap.HEAPU8.buffer, vertPtr, vertByteLen),new Uint8Array(heap.HEAPU8.buffer, idxPtr, idxByteLen),vertexCount, indexCount,heap.HEAPU32[texIdPtr >> 2],- heap.HEAPU32[blendPtr >> 2],+ blendMode, premultipliedColor,);});}diff --git a/sdk/src/skeletal/submitMeshes.ts b/sdk/src/skeletal/submitMeshes.tsindex 15a787353..f652cb603 100644--- a/sdk/src/skeletal/submitMeshes.ts+++ b/sdk/src/skeletal/submitMeshes.ts@@ -45,6 +45,14 @@ export interface SkeletalSubmitCore {entity: number, skeletonScale: number, flipX: boolean, flipY: boolean,layer: number, depth: number, materialId: number,): void;+ renderer_submitSkeletalBatchByEntityEx?(+ registry: unknown,+ verticesPtr: number, vertexCount: number,+ indicesPtr: number, indexCount: number,+ textureId: number, blendMode: number,+ entity: number, skeletonScale: number, flipX: boolean, flipY: boolean,+ layer: number, depth: number, materialId: number, premultipliedColor: boolean,+ ): void;_malloc?(size: number): number;_free?(ptr: number): void;HEAPU8?: Uint8Array;@@ -68,14 +76,15 @@ export function submitEntityMeshes(materialOf?: SkeletalMaterialOf,probe?: SkeletalProbe,): boolean {- const submit = core.renderer_submitSkeletalBatchByEntity;+ const submitEx = core.renderer_submitSkeletalBatchByEntityEx;+ const submit = submitEx ?? core.renderer_submitSkeletalBatchByEntity;const heap = core.HEAPU8;if (!submit || !heap || !core._malloc || !core._free) return false;const allocator = { _malloc: core._malloc, _free: core._free };const materialId = materialOf?.(entity) ?? 0;withScratch(allocator, alloc => {- walk((vertBytes, idxBytes, vertexCount, indexCount, textureId, blendMode) => {+ walk((vertBytes, idxBytes, vertexCount, indexCount, textureId, blendMode, premultipliedColor) => {const dstVert = alloc(vertBytes.byteLength);const dstIdx = alloc(idxBytes.byteLength);heap.set(vertBytes, dstVert);@@ -84,9 +93,12 @@ export function submitEntityMeshes(probe.abi.submit++;probe.bytes.coreWrite += vertBytes.byteLength + idxBytes.byteLength;}- submit.call(core, registry,- dstVert, vertexCount, dstIdx, indexCount,- textureId, blendMode, entity as number,+ if (submitEx) submitEx.call(core, registry,+ dstVert, vertexCount, dstIdx, indexCount, textureId, blendMode, entity as number,+ props.skeletonScale, props.flipX, props.flipY, props.layer, 0, materialId,+ premultipliedColor ?? (blendMode === 4 || blendMode === 5));+ else core.renderer_submitSkeletalBatchByEntity!.call(core, registry,+ dstVert, vertexCount, dstIdx, indexCount, textureId, blendMode, entity as number,props.skeletonScale, props.flipX, props.flipY, props.layer, 0, materialId);});});diff --git a/sdk/src/spine/SpineController.ts b/sdk/src/spine/SpineController.tsindex 8e58679a9..5d5423add 100644--- a/sdk/src/spine/SpineController.ts+++ b/sdk/src/spine/SpineController.ts@@ -366,17 +366,18 @@ export class SpineModuleController {const EVENT_STRIDE = 4;const bufferPtr = this.api_.getEventBuffer();const f32 = this.raw_.HEAPF32;+ const i32 = this.raw_.HEAPU32;const base = bufferPtr >> 2;const events: RawSpineEvent[] = [];for (let i = 0; i < count; i++) {const offset = base + i * EVENT_STRIDE;- const typeNum = f32[offset];+ const typeNum = i32[offset] | 0;events.push({type: typeNum,- track: f32[offset + 1],+ track: i32[offset + 1] | 0,floatValue: f32[offset + 2],- intValue: f32[offset + 3],+ intValue: i32[offset + 3] | 0,animationName: this.api_.getEventAnimationName(i),eventName: typeNum === 5 ? this.api_.getEventName(i) : '',stringValue: typeNum === 5 ? this.api_.getEventStringValue(i) : '',diff --git a/sdk/src/spine/SpineManager.ts b/sdk/src/spine/SpineManager.tsindex be90bbfbc..c848d65ee 100644--- a/sdk/src/spine/SpineManager.ts+++ b/sdk/src/spine/SpineManager.ts@@ -48,6 +48,7 @@ export class SpineManager {* runtime can only see its own entities, so one handed an entity another is* posing cannot retire the binding it replaces. */private bindings_: Map<Entity, SpineRuntime> = new Map();+ private readonly disabledEntities_ = new Set<Entity>();/** So a runtime loaded after `observe(true)` reports too. */private observing_ = false;@@ -107,18 +108,21 @@ export class SpineManager {// submitted every frame and no despawn ever reaches it.if (previous && previous !== runtime) previous.removeEntity(entity);this.bindings_.set(entity, runtime);+ runtime.setEnabled(entity, !this.disabledEntities_.has(entity));return version;}- updateAnimations(dt: number): void {+ /** Freeze inactive entities without changing their manual enable state. */+ updateAnimations(dt: number, isActive?: (entity: Entity) => boolean): void {for (const runtime of this.runtimes_.values()) {- runtime.updateAll(dt);+ runtime.updateAll(dt, isActive);}}- submitMeshes(registry: CppRegistry, materialOf?: SkeletalMaterialOf): void {+ /** Skip extraction for entities the activity predicate excludes. */+ submitMeshes(registry: CppRegistry, materialOf?: SkeletalMaterialOf, isActive?: (entity: Entity) => boolean): void {for (const runtime of this.runtimes_.values()) {- runtime.extractAndSubmitMeshes(this.coreModule_, registry, materialOf);+ runtime.extractAndSubmitMeshes(this.coreModule_, registry, materialOf, isActive);}}@@ -131,6 +135,7 @@ export class SpineManager {removeEntity(entity: Entity): void {this.bindings_.get(entity)?.removeEntity(entity);this.bindings_.delete(entity);+ this.disabledEntities_.delete(entity);}/**@@ -145,6 +150,7 @@ export class SpineManager {this.runtimes_.clear();this.loadingRuntimes_.clear();this.bindings_.clear();+ this.disabledEntities_.clear();}getEntityVersion(entity: Entity): SpineVersion | undefined {@@ -306,7 +312,10 @@ export class SpineManager {*/setEnabled(entity: Entity, enabled: boolean): void {const backend = this.runtimeOf_(entity);- if (backend) backend.setEnabled(entity, enabled);+ if (!backend) return;+ if (enabled) this.disabledEntities_.delete(entity);+ else this.disabledEntities_.add(entity);+ backend.setEnabled(entity, enabled);}enableEvents(entity: Entity): void {@@ -314,10 +323,10 @@ export class SpineManager {if (backend) backend.enableEvents(entity);}- collectAllEvents(): { entity: Entity; raw: RawSpineEvent }[] {+ collectAllEvents(isActive?: (entity: Entity) => boolean): { entity: Entity; raw: RawSpineEvent }[] {const result: { entity: Entity; raw: RawSpineEvent }[] = [];for (const backend of this.runtimes_.values()) {- const events = backend.collectAllEvents();+ const events = backend.collectAllEvents(isActive);for (const evt of events) {result.push(evt);}diff --git a/sdk/src/spine/SpineModuleLoader.ts b/sdk/src/spine/SpineModuleLoader.tsindex 188d7fb20..1e7f85cfb 100644--- a/sdk/src/spine/SpineModuleLoader.ts+++ b/sdk/src/spine/SpineModuleLoader.ts@@ -34,6 +34,7 @@ export interface SpineWasmModule {_spine_getBounds(instanceId: number, outXPtr: number, outYPtr: number, outWPtr: number, outHPtr: number): void;_spine_getSkeletonBounds(skeletonHandle: number, outXPtr: number, outYPtr: number, outWPtr: number, outHPtr: number): number;+ _spine_getMeshBatchColorPremultiplied?(instanceId: number, batchIndex: number): number;_spine_getMeshBatchCount(instanceId: number): number;_spine_getMeshBatchVertexCount(instanceId: number, batchIndex: number): number;_spine_getMeshBatchIndexCount(instanceId: number, batchIndex: number): number;@@ -120,6 +121,7 @@ export interface SpineWrappedAPI {/** The skeleton's authored extent — answerable without an instance or a pose. */getSkeletonBounds(skeletonHandle: number, outXPtr: number, outYPtr: number, outWPtr: number, outHPtr: number): number;getMeshBatchCount(instanceId: number): number;+ getMeshBatchColorPremultiplied?(instanceId: number, batchIndex: number): number;getMeshBatchVertexCount(instanceId: number, batchIndex: number): number;getMeshBatchIndexCount(instanceId: number, batchIndex: number): number;getMeshBatchData(instanceId: number, batchIndex: number,@@ -195,6 +197,8 @@ export function wrapSpineModule(raw: SpineWasmModule): SpineWrappedAPI {getBoneRotation: cw('spine_getBoneRotation', 'number', ['number', 'string']) as SpineWrappedAPI['getBoneRotation'],getBounds: cw('spine_getBounds', null, ['number', 'number', 'number', 'number', 'number']) as SpineWrappedAPI['getBounds'],getSkeletonBounds: cw('spine_getSkeletonBounds', 'number', ['number', 'number', 'number', 'number', 'number']) as SpineWrappedAPI['getSkeletonBounds'],+ getMeshBatchColorPremultiplied: typeof (raw as unknown as Record<string, unknown>)._spine_getMeshBatchColorPremultiplied === 'function'+ ? cw('spine_getMeshBatchColorPremultiplied', 'number', ['number', 'number']) as SpineWrappedAPI['getMeshBatchColorPremultiplied'] : undefined,getMeshBatchCount: cw('spine_getMeshBatchCount', 'number', ['number']) as SpineWrappedAPI['getMeshBatchCount'],getMeshBatchVertexCount: cw('spine_getMeshBatchVertexCount', 'number', ['number', 'number']) as SpineWrappedAPI['getMeshBatchVertexCount'],getMeshBatchIndexCount: cw('spine_getMeshBatchIndexCount', 'number', ['number', 'number']) as SpineWrappedAPI['getMeshBatchIndexCount'],diff --git a/sdk/src/spine/SpinePlugin.ts b/sdk/src/spine/SpinePlugin.tsindex f2867a85c..34d1db4af 100644--- a/sdk/src/spine/SpinePlugin.ts+++ b/sdk/src/spine/SpinePlugin.ts@@ -95,14 +95,16 @@ export class SpinePlugin implements Plugin {private wireSubmit_(app: App): void {if (this.submitWired_) return;this.submitWired_ = true;+ const isActive = (e: Entity) => app.world.isEntityActive(e);app.pipeline?.addPreFlushCallback((registry) => {this.spineManager_?.submitMeshes(registry._cpp, (e: Entity) =>- (app.world.tryGet(e, SpineAnimation)?.material as number | undefined) ?? 0);+ (app.world.tryGet(e, SpineAnimation)?.material as number | undefined) ?? 0, isActive);});}build(app: App): void {this.app_ = app;+ const isActive = (e: Entity) => app.world.isEntityActive(e);// The core the mesh batches are submitted through: the wasm module on the// web, the native host's bindings on a device.const coreModule = engineApi(app);@@ -142,10 +144,10 @@ export class SpinePlugin implements Plugin {const time = app.getResource(Time);const manager = this.spineManager_;if (manager) {- this.enableMirror_.sync(app.world, manager);- manager.updateAnimations(time.delta);+ this.enableMirror_.sync(app.world, manager, isActive);+ manager.updateAnimations(time.delta, isActive);}- this.collectAndPublishEvents_(app);+ this.collectAndPublishEvents_(app, isActive);},};@@ -185,11 +187,11 @@ export class SpinePlugin implements Plugin {this.submitWired_ = false; // a fresh build (new pipeline) re-registers the submit}- private collectAndPublishEvents_(app: App): void {+ private collectAndPublishEvents_(app: App, isActive: (entity: Entity) => boolean): void {const events: SpineEvent[] = [];if (this.spineManager_) {- for (const { entity, raw } of this.spineManager_.collectAllEvents()) {+ for (const { entity, raw } of this.spineManager_.collectAllEvents(isActive)) {const type = SPINE_TYPE_MAP[raw.type];if (type === null || type === undefined) continue;const evt: SpineEvent = {diff --git a/sdk/src/spine/SpineRuntime.ts b/sdk/src/spine/SpineRuntime.tsindex ea4a7bf90..e65d03931 100644--- a/sdk/src/spine/SpineRuntime.ts+++ b/sdk/src/spine/SpineRuntime.ts@@ -132,7 +132,9 @@ export class SpineRuntime {// Only now: the old instance and its claim on the era it was posing.// Re-binding to the SAME era claimed it again above, so the skeleton is// never unloaded and re-parsed underneath an entity that stays on it.+ const disabled = this.disabledEntities_.has(entity);this.removeEntity(entity);+ if (disabled) this.disabledEntities_.add(entity);this.entities_.set(entity, {skelHandle: claimed, instanceId, era: era.id,skeletonScale: 1, flipX: false, flipY: false, layer: 0, timeScale: 1, playing: true,@@ -324,9 +326,10 @@ export class SpineRuntime {if (info) this.controller_.enableEvents(info.instanceId);}- collectAllEvents(): { entity: Entity; raw: RawSpineEvent }[] {+ collectAllEvents(isActive?: (entity: Entity) => boolean): { entity: Entity; raw: RawSpineEvent }[] {const result: { entity: Entity; raw: RawSpineEvent }[] = [];for (const [entity, info] of this.entities_) {+ if (this.disabledEntities_.has(entity) || (isActive && !isActive(entity))) continue;const events = this.controller_.collectEvents(info.instanceId);for (const raw of events) {result.push({ entity, raw });@@ -529,7 +532,7 @@ export class SpineRuntime {info.logicalRevision++;}- updateAll(dt: number): void {+ updateAll(dt: number, isActive?: (entity: Entity) => boolean): void {const m = this.metrics_;if (m) {// The frame that ends HERE is the only place its readback is whole:@@ -546,7 +549,7 @@ export class SpineRuntime {for (const [entity, info] of this.entities_) {// Disabled means out of the frame entirely, so it costs no posing// either — the same meaning the DragonBones manager gives it.- if (this.disabledEntities_.has(entity)) continue;+ if (this.disabledEntities_.has(entity) || (isActive && !isActive(entity))) continue;// playing=false freezes the pose (skip advance, still submitted);// timeScale scales the advance (update() takes an arbitrary dt).if (info.playing) {@@ -572,11 +575,11 @@ export class SpineRuntime {* batches cross through its heap, which is wasm linear memory on the web and the* host arena on a device. */extractAndSubmitMeshes(core: NonNullable<EngineApi>, registry: CppRegistry,- materialOf?: SkeletalMaterialOf): void {+ materialOf?: SkeletalMaterialOf, isActive?: (entity: Entity) => boolean): void {const m = this.metrics_;const started = m ? performance.now() : 0;for (const [entity, info] of this.entities_) {- if (this.disabledEntities_.has(entity)) continue;+ if (this.disabledEntities_.has(entity) || (isActive && !isActive(entity))) continue;// Only a NO from the renderer, about an extent somebody certified,// removes work. Unknown is not a no: an entity whose extent nobody// promised has unknown visibility and is drawn.diff --git a/sdk/src/spine/prepareSpine.ts b/sdk/src/spine/prepareSpine.tsindex dde3c5854..357e51d77 100644--- a/sdk/src/spine/prepareSpine.ts+++ b/sdk/src/spine/prepareSpine.ts@@ -21,6 +21,8 @@* is decided once, here.*/import { requireResourceManager } from '../wasm/resourceManager';+import { spinePairKey } from '../asset/spinePairKey';+export { spinePairKey } from '../asset/spinePairKey';import type { AssetLease } from '../asset/AssetLease';import { parseSpineAtlasPages } from './atlasPages';import { log } from '../util/logger';@@ -120,11 +122,6 @@ export function spineEraOf(};}-/** The identity of a spine asset in one realm: the pair, in one string. */-export function spinePairKey(skeleton: string, atlas: string): string {- return `${skeleton}:${atlas}`;-}-/*** Prepare one spine pair. A page that fails to load is left out with a warning* rather than failing the asset: a skeleton missing one page still poses, anddiff --git a/sdk/src/spine/spineMetrics.ts b/sdk/src/spine/spineMetrics.tsindex 541394611..4d3ed28ea 100644--- a/sdk/src/spine/spineMetrics.ts+++ b/sdk/src/spine/spineMetrics.ts@@ -63,6 +63,7 @@ export interface SpineAbiCounts {vertexCount: number;indexCount: number;batchData: number;+ batchColor: number;malloc: number;free: number;submit: number;@@ -115,7 +116,7 @@ export interface SpineFrameMetrics {export function newSpineFrameMetrics(): SpineFrameMetrics {return {frame: 0, entities: 0, residencies: 0, meshBatches: 0, vertices: 0, indices: 0,- abi: { pose: 0, world: 0, batchCount: 0, vertexCount: 0, indexCount: 0, batchData: 0, malloc: 0, free: 0, submit: 0 },+ abi: { pose: 0, world: 0, batchCount: 0, vertexCount: 0, indexCount: 0, batchData: 0, batchColor: 0, malloc: 0, free: 0, submit: 0 },pose: { logicalUpdates: 0, worldMaterializations: 0, worldAlreadyCurrent: 0, meshExtractions: 0, renderCulled: 0 },bytes: { wasmRead: 0, coreWrite: 0, scratchAllocated: 0 },time: { pose: 0, readback: 0, total: 0 },@@ -127,7 +128,7 @@ export function beginSpineFrame(m: SpineFrameMetrics): void {m.frame++;m.entities = 0; m.residencies = 0; m.meshBatches = 0; m.vertices = 0; m.indices = 0;m.abi.pose = 0; m.abi.world = 0; m.abi.batchCount = 0; m.abi.vertexCount = 0; m.abi.indexCount = 0;- m.abi.batchData = 0; m.abi.malloc = 0; m.abi.free = 0; m.abi.submit = 0;+ m.abi.batchData = 0; m.abi.batchColor = 0; m.abi.malloc = 0; m.abi.free = 0; m.abi.submit = 0;m.bytes.wasmRead = 0; m.bytes.coreWrite = 0; m.bytes.scratchAllocated = 0;m.pose.logicalUpdates = 0; m.pose.worldMaterializations = 0;m.pose.worldAlreadyCurrent = 0; m.pose.meshExtractions = 0; m.pose.renderCulled = 0;diff --git a/sdk/src/spine/spineSceneDiagnostics.ts b/sdk/src/spine/spineSceneDiagnostics.tsindex 4455ac3ef..f6a41719a 100644--- a/sdk/src/spine/spineSceneDiagnostics.ts+++ b/sdk/src/spine/spineSceneDiagnostics.ts@@ -201,7 +201,7 @@ export function spineSceneDiagnostics(const geometry = { meshBatches: 0, vertices: 0, indices: 0 };const abi: SpineAbiCounts = {pose: 0, world: 0, batchCount: 0, vertexCount: 0, indexCount: 0,- batchData: 0, malloc: 0, free: 0, submit: 0,+ batchData: 0, batchColor: 0, malloc: 0, free: 0, submit: 0,};const bytes: SpineByteCounts = { wasmRead: 0, coreWrite: 0, scratchAllocated: 0 };const time = { pose: 0, readback: 0, total: 0 };diff --git a/sdk/src/ui/input/interaction.ts b/sdk/src/ui/input/interaction.tsindex 81ba70eb4..57e0620d8 100644--- a/sdk/src/ui/input/interaction.ts+++ b/sdk/src/ui/input/interaction.ts@@ -55,6 +55,7 @@ export class UIInteractionPlugin implements Plugin {build(app: App): void {registerComponent('Interactable', Interactable);+ registerComponent('UIInteraction', UIInteraction);const world = app.world;const engine = engineApi(app);@@ -70,12 +71,17 @@ export class UIInteractionPlugin implements Plugin {/** Where each pointer last hit, so a settled pointer skips the raycast. */const lastHit = new Map<number, { x: number; y: number; entity: Entity | null }>();let lastLayoutGen = -1;+ let lastWorldVersion = -1;+ let lastTick = -1;+ world.enableChangeTracking(Interactable);+ const eligible = (entity: Entity): boolean => world.isEntityActive(entity)+ && (!world.has(entity, Interactable) || world.get(entity, Interactable).enabled);// During the host's release event, from what the last frame saw: the// control this pointer pressed, if it is still the one under it.const releaseInGesture = (pointer: number): void => {const held = book.releasing(pointer, lastHit.get(pointer)?.entity ?? null);- if (held === null || !world.valid(held)) return;+ if (held === null || !eligible(held)) return;if (world.has(held, Interactable) && !(world.get(held, Interactable) as InteractableData).enabled) return;fireGestureClick(world, held);};@@ -103,13 +109,18 @@ export class UIInteractionPlugin implements Plugin {// Either domain is enough to be pointing AT something: a scene// with no camera still has a screen, and a HUD on it is still// clickable.- if (!camera.valid && !overlay.active) { input.pointerOverUI = false; return; }-const dpr = platformDevicePixelRatio();const surfaceH = overlay.active ? overlay.surfaceH : camera.screenH;const pointers = uiPointersOf(input);const layoutChanged = layoutGen.generation !== lastLayoutGen;lastLayoutGen = layoutGen.generation;+ const worldVersion = world.getWorldVersion();+ // A write between frames may carry the previous frame's tick;+ // overlap one tick so stationary pointers see enable/disable.+ const worldChanged = worldVersion !== lastWorldVersion+ || world.anyChangedSince(Interactable, lastTick - 1);+ lastWorldVersion = worldVersion;+ lastTick = world.getWorldTick();// The single-pointer resources every other consumer reads are the// PRIMARY pointer's: the mouse, or the oldest finger on the glass.@@ -117,6 +128,7 @@ export class UIInteractionPlugin implements Plugin {let overUI = false;const hit = (pointer: UiPointerSample): Entity | null => {+ if (!camera.valid && !overlay.active) return null;const glX = pointer.x * dpr;const glY = surfaceH - pointer.y * dpr;// The pointer, once per domain. Neither is derived from the@@ -136,8 +148,9 @@ export class UIInteractionPlugin implements Plugin {const settled = cached !== undefined&& cached.x === layoutPointer.x && cached.y === layoutPointer.y;let entity: Entity | null;- if (settled && !layoutChanged && !edge) {- entity = cached.entity !== null && world.valid(cached.entity) ? cached.entity : null;+ if (settled && !layoutChanged && !worldChanged && !edge+ && (cached.entity === null || eligible(cached.entity))) {+ entity = cached.entity;} else {// With no camera there is no world ray: inverting a projection// never written yields NaN, which answers "no" by accident.@@ -145,6 +158,7 @@ export class UIInteractionPlugin implements Plugin {const screenRay = overlay.active ? uiLayoutRay(overlay, glX, glY) : undefined;const worldRay = camera.valid ? uiPointerRay(camera, glX, glY) : screenRay!;entity = uiHitTestWorld(world, worldRay, screenRay);+ if (entity !== null && !eligible(entity)) entity = null;lastHit.set(pointer.id, { x: layoutPointer.x, y: layoutPointer.y, entity });}if (entity !== null) overUI = true;@@ -152,7 +166,9 @@ export class UIInteractionPlugin implements Plugin {};const wasPressed = new Set(book.pressed);- for (const event of book.step(pointers, hit, (e) => world.valid(e))) {+ const wasHovered = new Set(book.hovered);+ for (const event of book.step(pointers, hit,+ e => eligible(e) && (camera.valid || overlay.active))) {switch (event.kind) {case 'hoverEnter':ensureComponent(world, event.entity, UIInteraction);@@ -183,14 +199,15 @@ export class UIInteractionPlugin implements Plugin {// any pointer is over or holding it, false once none is.const hovered = book.hovered;const pressed = book.pressed;- const touched = new Set<Entity>([...interactionEntities, ...hovered, ...pressed, ...wasPressed]);+ const touched = new Set<Entity>([...interactionEntities, ...hovered, ...pressed, ...wasPressed, ...wasHovered]);for (const entity of touched) {if (!world.valid(entity) || !world.has(entity, UIInteraction)) continue;const data = world.get(entity, UIInteraction) as UIInteractionData;const isHovered = hovered.has(entity);const isPressed = pressed.has(entity);- const justPressed = data.justPressed || (isPressed && !wasPressed.has(entity));- const justReleased = data.justReleased || (!isPressed && wasPressed.has(entity));+ const active = eligible(entity) && (camera.valid || overlay.active);+ const justPressed = active && (data.justPressed || (isPressed && !wasPressed.has(entity)));+ const justReleased = active && (data.justReleased || (!isPressed && wasPressed.has(entity)));if (data.hovered === isHovered && data.pressed === isPressed&& data.justPressed === justPressed && data.justReleased === justReleased) continue;data.hovered = isHovered;diff --git a/sdk/src/util/cloneJsonValue.ts b/sdk/src/util/cloneJsonValue.tsnew file mode 100644index 000000000..852458dbd--- /dev/null+++ b/sdk/src/util/cloneJsonValue.ts@@ -0,0 +1,43 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { setOwn } from './ownProperties';++/** Copy authored JSON data without serializing ordinary records to text first.+ * Exotic values keep JSON's conversion rules, including toJSON's property key. */+export function cloneJsonValue<T>(value: T): T {+ const ancestors = new Set<object>();+ const clone = (value: unknown, key: string, root = false, depth = 0): unknown => {+ if (value === null || typeof value === 'string' || typeof value === 'boolean') return value;+ if (typeof value === 'number') return Number.isFinite(value) ? (value === 0 ? 0 : value) : null;+ if (value === undefined || typeof value === 'function' || typeof value === 'symbol') return undefined;+ const fallback = (): unknown => root+ ? JSON.parse(JSON.stringify(value))+ : JSON.parse(JSON.stringify({ [key]: value }))[key];+ if (typeof value !== 'object') return fallback(); // BigInt keeps JSON's rejection.+ // Let the native serializer handle deep documents rather than spend a+ // larger JS call stack on a tree JSON itself can still represent.+ if (depth >= 64) return fallback();+ const proto = Object.getPrototypeOf(value);+ const array = Array.isArray(value);+ if ('toJSON' in value || (proto !== Object.prototype && proto !== null && !(array && proto === Array.prototype))) return fallback();+ if (ancestors.has(value)) return fallback(); // Preserve the circular-data error.+ ancestors.add(value);+ try {+ if (array) {+ const length = value.length;+ const result = new Array(length);+ for (let i = 0; i < length; i++) result[i] = clone(value[i], String(i), false, depth + 1) ?? null;+ return result;+ }+ const result: Record<string, unknown> = {};+ for (const name of Object.keys(value)) {+ const next = clone((value as Record<string, unknown>)[name], name, false, depth + 1);+ if (next === undefined) continue;+ setOwn(result, name, next);+ }+ return result;+ } finally { ancestors.delete(value); }+ };+ if (value === undefined || typeof value === 'function' || typeof value === 'symbol') return JSON.parse(JSON.stringify(value)) as T;+ return clone(value, '', true) as T;+}diff --git a/sdk/src/util/deepClone.ts b/sdk/src/util/deepClone.tsindex d12a96f51..6befb78f3 100644--- a/sdk/src/util/deepClone.ts+++ b/sdk/src/util/deepClone.ts@@ -5,6 +5,8 @@* @brief Structural deep clone for plain data (objects, arrays, primitives)*/+import { setOwn } from './ownProperties';+/*** Recursively clone plain objects and arrays; primitives AND class instances* (Map, Date, a custom class with methods, …) pass through by reference.@@ -30,8 +32,8 @@ export function deepClone<T>(value: T): T {return value;}const result: Record<string, unknown> = {};- for (const key in value) {- result[key] = deepClone((value as Record<string, unknown>)[key]);+ for (const key of Object.keys(value)) {+ setOwn(result, key, deepClone((value as Record<string, unknown>)[key]));}return result as T;}diff --git a/sdk/src/util/disposeAll.ts b/sdk/src/util/disposeAll.tsnew file mode 100644index 000000000..609b1856f--- /dev/null+++ b/sdk/src/util/disposeAll.ts@@ -0,0 +1,11 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/** Dispose a detached batch completely; report its first failure unchanged. */+export function disposeAll<T>(items: readonly T[], dispose: (item: T) => void, reverse = false): void {+ let failed = false, reason: unknown;+ for (let n = 0; n < items.length; n++) {+ try { dispose(items[reverse ? items.length - 1 - n : n]); }+ catch (error) { if (!failed) { failed = true; reason = error; } }+ }+ if (failed) throw reason;+}diff --git a/sdk/src/util/ownProperties.ts b/sdk/src/util/ownProperties.tsnew file mode 100644index 000000000..ab5dfc353--- /dev/null+++ b/sdk/src/util/ownProperties.ts@@ -0,0 +1,13 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/** ES-compatible own-field lookup for schema records, including null prototypes. */+export function hasOwn(value: object, key: PropertyKey): boolean {+ return Object.prototype.hasOwnProperty.call(value, key);+}++/** Write a data member on a fresh record without invoking __proto__'s setter. */+export function setOwn(value: Record<string, unknown>, key: string, data: unknown): void {+ if (key === '__proto__') {+ Object.defineProperty(value, key, { value: data, enumerable: true, writable: true, configurable: true });+ } else value[key] = data;+}diff --git a/sdk/src/util/validation.ts b/sdk/src/util/validation.tsindex 47b2f8d55..ad315d651 100644--- a/sdk/src/util/validation.ts+++ b/sdk/src/util/validation.ts@@ -5,6 +5,10 @@* @brief Component data validation utilities*/+import { hasOwn } from './ownProperties';++type AssetFields = ReadonlySet<string> | readonly { readonly field: string }[];+export type ValidationError = {field: string;expected: string;@@ -16,7 +20,7 @@ export function validateComponentData(componentName: string,defaults: Record<string, unknown>,data: Record<string, unknown>,- assetFields?: ReadonlySet<string>+ assetFields?: AssetFields): ValidationError[] {const errors: ValidationError[] = [];validateInto(errors, defaults, data, assetFields, '');@@ -27,13 +31,16 @@ function validateInto(errors: ValidationError[],defaults: Record<string, unknown>,data: Record<string, unknown>,- assetFields: ReadonlySet<string> | undefined,+ assetFields: AssetFields | undefined,prefix: string): void {- for (const [field, value] of Object.entries(data)) {- if (field.startsWith('_')) continue;+ // Validation walks nested records on both scene load and component writes.+ // Keys avoid allocating a [key, value] tuple for every field at every depth.+ for (const field of Object.keys(data)) {+ const value = data[field];+ if (field.startsWith('_') && field !== '__proto__') continue;const path = prefix ? `${prefix}.${field}` : field;- if (!(field in defaults)) {+ if (!hasOwn(defaults, field)) {// Unknown members are an error only at the TOP level (a stray key names// a field that will silently never apply). Nested objects legally carry// extra keys — e.g. colors read back from wasm keep ghost x/y/z/w@@ -64,7 +71,7 @@ function validateInto(// are top-level fields; the rule never applies at depth.)if (!prefix &&- assetFields?.has(field) &&+ isAssetField(assetFields, field) &&((expectedType === 'string' && actualType === 'number') ||(expectedType === 'number' && actualType === 'string'))) {@@ -94,6 +101,15 @@ function validateInto(}}+function isAssetField(fields: AssetFields | undefined, name: string): boolean {+ if (!fields) return false;+ if ('has' in fields) return fields.has(name);+ // Component metadata is already a small list. Read it only on a type+ // mismatch, without allocating a Set per write or caching mutable metadata.+ for (const entry of fields) if (entry.field === name) return true;+ return false;+}+/** A component's asset-ref field names — pass to {@link validateComponentData} so* those fields validate leniently: a portable string ref ("@uuid:…"/"") and a* numeric runtime handle (0) both denote the same asset (or its absence). */diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.tsindex 28156514c..e11fe1c31 100644--- a/sdk/src/wasm.ts+++ b/sdk/src/wasm.ts@@ -35,6 +35,10 @@ export interface CppRegistry extends GeneratedRegistry {* registry itself. The web module answers the same question as a free* function; absent on a core built before either existed. */layoutEpoch?(): number;+ /** Shared subtree teardown ownership; optional for older hosts. */+ reserveDestruction?(entity: Entity): boolean;+ releaseDestruction?(entity: Entity): void;+ destructionPending?(entity: Entity): boolean;[key: string]: Function | undefined;}@@ -221,7 +225,7 @@ export interface ESEngineModule {FS: EmscriptenFS;- initRenderer(): void;+ initRenderer(): boolean;initRendererWithContext(contextHandle: number): boolean;/*** Boot on the WebGPU backend. The host must acquire a GPUDevice and pass it@@ -408,6 +412,14 @@ export interface ESEngineModule {entity: number, skelScale: number, flipX: boolean, flipY: boolean,layer: number, depth: number, materialId: number): void;+ renderer_submitSkeletalBatchByEntityEx?(+ registry: CppRegistry,+ verticesPtr: number, vertexCount: number,+ indicesPtr: number, indexCount: number,+ textureId: number, blendMode: number,+ entity: number, skelScale: number, flipX: boolean, flipY: boolean,+ layer: number, depth: number, materialId: number, premultipliedColor: boolean+ ): void;/*** Submit pre-laid-out glyph quads. Vertex format x,y,u,v,r,g,b,a; `sdf` (1/0)* selects the SDF variant vs the plain textured batch (device bitmap atlas).@@ -706,6 +718,10 @@ export interface ESEngineModule {preview: number, verticesPtr: number, vertexCount: number,indicesPtr: number, indexCount: number, textureId: number, blendMode: number,transformPtr: number, layer: number, depth: number, materialId: number): number;+ renderer_submitSkeletalPreviewBatchEx(+ preview: number, verticesPtr: number, vertexCount: number,+ indicesPtr: number, indexCount: number, textureId: number, blendMode: number,+ transformPtr: number, layer: number, depth: number, materialId: number, premultipliedColor: boolean): number;renderer_renderSkeletalPreview(preview: number, viewProjectionPtr: number): number;renderer_pollSkeletalPreview(preview: number): number;renderer_getSkeletalPreviewPtr(preview: number): number;diff --git a/sdk/src/wasm/wasm.generated.ts b/sdk/src/wasm/wasm.generated.tsindex dbb6092f7..2c42087cb 100644--- a/sdk/src/wasm/wasm.generated.ts+++ b/sdk/src/wasm/wasm.generated.ts@@ -1128,7 +1128,12 @@ export interface Registry {removeVelocity(entity: Entity): void;// Hierarchy Utilities- setParent(child: Entity, parent: Entity): void;+ setEntityEnabled?(entity: Entity, enabled: boolean): boolean;+ isEntityActive?(entity: Entity): boolean;+ isEntityEnabled?(entity: Entity): boolean;+ hasInactiveEntities?(): boolean;+ activityEpoch?(): number;+ setParent(child: Entity, parent: Entity): boolean | void;}// Modulediff --git a/sdk/tests/AsyncCache.test.ts b/sdk/tests/AsyncCache.test.tsindex a2f4fe213..49679a7b2 100644--- a/sdk/tests/AsyncCache.test.ts+++ b/sdk/tests/AsyncCache.test.ts@@ -10,6 +10,15 @@ describe('AsyncCache', () => {cache = new AsyncCache<string>();});+ it('clears its deadline when a loader rejects before timeout', async () => {+ vi.useFakeTimers();+ try {+ const error = new Error('load failed');+ await expect(cache.getOrLoad('deadline', async () => { throw error; }, 10000)).rejects.toBe(error);+ expect(vi.getTimerCount()).toBe(0);+ } finally { vi.useRealTimers(); }+ });+describe('basic caching', () => {it('should cache successful results', async () => {const loader = vi.fn().mockResolvedValue('value');diff --git a/sdk/tests/aot-app.test.ts b/sdk/tests/aot-app.test.tsindex 4ab00800a..65cada70a 100644--- a/sdk/tests/aot-app.test.ts+++ b/sdk/tests/aot-app.test.ts@@ -10,6 +10,8 @@* install is split, and this is the gate on the halves meeting.*/import { describe, it, expect } from 'vitest';+import { setPlatform } from '../src/platform/base';+import type { PlatformAdapter } from '../src/platform/types';import { bootMockApp } from './helpers/mockApp';import {buildAotModule, buildFadeModule, eventManifest, fadeManifest, fadeTaggedManifest,@@ -27,6 +29,7 @@ import { defineSystem, Schedule } from '../src/ecs/system';import { Query, Mut } from '../src/ecs/query';import type { AnyComponentDef } from '../src/ecs/component';import type { Entity } from '../src/types';+import { projectShapeDigest } from '../src/ecs/aot/abiDigest';const EMCC = emccPath();const N = 8;@@ -59,6 +62,46 @@ const alphas = (app: ReturnType<typeof bootMockApp>['app'], Fade: AnyComponentDees.map((e) => (app.world.get(e, Fade) as { alpha: number }).alpha);describe('an App told to run its compiled twins', () => {+ it.skipIf(!EMCC)('compiled scratch and foreign heap growth preserve held script views and cached query rows',async()=>{+ class GrowingEngine extends FakeEngine {+ grow():void {this.memory.grow(1);this.HEAPU8=new Uint8Array(this.memory.buffer);}+ override _malloc(size:number):number {this.grow();return super._malloc(size);}+ }+ const {app,Fade}=fadeApp(),host=new GrowingEngine();+ await app.useCompiledSystems({host,manifest:fadeManifest(),wasm:new Uint8Array(buildFadeModule(EMCC!)).buffer});+ const entities=seed(app,Fade),held=app.world.get(entities[0]!,Fade) as {alpha:number;step:number};+ const address=app.world.addressResolver(Fade),before=address(entities[0]!);+ try {+ await app.tick(1/60);expect(held.alpha).toBeCloseTo(0.09);expect(app.compiledSystems.calls).toBe(1);+ host.grow();expect(address(entities[0]!)).toBe(before);+ held.alpha=0.5;await app.tick(1/60);expect(held.alpha).toBeCloseTo(0.49);+ expect(app.compiledSystems.calls).toBe(2);expect(host.staticsIntact()).toBe(true);+ }finally{app.quit({keepRenderer:true});}+ });++ it.skipIf(!EMCC)('quit frees both script rows and the real compiled call arena',async()=>{+ const live=new Set<number>();+ class TrackedEngine extends FakeEngine {+ override _malloc(size:number):number {const at=super._malloc(size);live.add(at);return at;}+ override _free(at?:number):void {expect(live.delete(at!)).toBe(true);}+ }+ const {app,Fade}=fadeApp(),host=new TrackedEngine();+ await app.useCompiledSystems({host,manifest:fadeManifest(),wasm:new Uint8Array(buildFadeModule(EMCC!)).buffer});+ seed(app,Fade);await app.tick(1/60);expect(live.size).toBeGreaterThan(3);+ app.quit({keepRenderer:true});expect(live.size).toBe(0);app.quit({keepRenderer:true});expect(live.size).toBe(0);+ expect(host.staticsIntact()).toBe(true);+ });+ it.skipIf(!EMCC)('a module finishing after quit cannot resurrect compiled dispatch',async()=>{+ const {app}=fadeApp();let begin!:()=>void,resume!:()=>void;+ const started=new Promise<void>(resolve=>{begin=resolve;}),gate=new Promise<void>(resolve=>{resume=resolve;});+ setPlatform({instantiateWasm:async(source:ArrayBuffer,imports:WebAssembly.Imports)=>{begin();await gate;return WebAssembly.instantiate(source,imports);}} as unknown as PlatformAdapter);+ try{+ const pending=app.useCompiledSystems({host:new FakeEngine(),manifest:fadeManifest(),wasm:new Uint8Array(buildFadeModule(EMCC!)).buffer}).catch(error=>error);+ await started;app.quit({keepRenderer:true});resume();+ const failure=await pending;expect(failure).toBeInstanceOf(Error);expect(failure.message).toMatch(/cancelled by App.quit/);expect(app.compiledSystemCount).toBe(0);+ expect(app.compiledSystems.calls).toBe(0);+ }finally{resume();useBytesPlatform();}+ });it('reports whether this gate could run at all', () => {if (!EMCC) console.warn('[aot-app] NO EMSDK — the App-level install did NOT run.');});@@ -246,6 +289,23 @@ describe('an App told to run its compiled twins', () => {expect(seen).toEqual(entities.map((_, i) => (i + 1) * 0.1));});+ it.skipIf(!EMCC)('compiled event delivery preserves nested prototype-named payload fields',async()=>{+ const wasm=buildAotModule(EMCC!,EVENT_C,'es_sys_Emit'),{app}=bootMockApp();+ const Fade=defineComponent('Fade',{alpha:1,step:0.1}) as AnyComponentDef;+ const name='OwnAotPayload',fields=['__proto__.amount'],event=defineEvent(name,JSON.parse('{"__proto__":{"amount":0}}'));+ const base=eventManifest('Emit'),manifest={...base,projectShapes:projectShapeDigest([{name:'Fade',fields:['alpha','step']},{name,fields}]),systems:[{...base.systems[0]!,writers:[{slot:0,event:name,fields}]}]};+ const seen:unknown[]=[],original=Object.getOwnPropertyDescriptor(Object.prototype,'amount');+ app.addSystemToSchedule(Schedule.Update,defineSystem([Query(Fade),EventWriter(event)],()=>{throw Error('compiled twin was not used');},{name:'Emit'}));+ app.addSystemToSchedule(Schedule.Update,defineSystem([EventReader(event)],hits=>{for(const hit of hits)seen.push(hit);},{name:'WatchOwnPayload'}));+ try {+ await app.useCompiledSystems({host:new FakeEngine(),manifest,wasm:new Uint8Array(wasm).buffer});seed(app,Fade);+ await app.tick(1/60);await app.tick(1/60);+ expect(seen).toHaveLength(N);expect(app.compiledSystems.calls).toBe(2);+ expect(JSON.stringify(seen[0])).toBe('{"__proto__":{"amount":0.1}}');+ expect(Object.getOwnPropertyDescriptor(Object.prototype,'amount')).toEqual(original);+ }finally{app.quit({keepRenderer:true});if(original)Object.defineProperty(Object.prototype,'amount',original);else delete (Object.prototype as Record<string,unknown>).amount;}+ });+it.skipIf(!EMCC)("reads a resource the PROJECT declared, at the layout the build derived", async () => {const wasm = buildAotModule(EMCC!, USER_RES_C, 'es_sys_Tally');const { app } = bootMockApp();diff --git a/sdk/tests/aot-dispatch.test.ts b/sdk/tests/aot-dispatch.test.tsindex 2e9f08cd2..b2125e94f 100644--- a/sdk/tests/aot-dispatch.test.ts+++ b/sdk/tests/aot-dispatch.test.ts@@ -115,6 +115,29 @@ function snapshot(world: World, Decay: AnyComponentDef, entities: readonly Entit}describe('the scheduler and its compiled twin', () => {+ it.skipIf(!EMCC)('portable asset refs run through the interpreter until every row is addressable',async()=>{+ const b=makeWorld(),heap=new FakeEngine(),memory=new WasmPoolMemory(heap);+ b.world.useScriptPoolMemory(memory);+ Object.defineProperty(b.Decay,'assetFields',{value:[{field:'remaining',type:'texture'}]});+ const first=b.world.spawn(),second=b.world.spawn();+ b.world.insert(first,b.Decay,{remaining:1,rate:0.1});+ b.world.insert(second,b.Decay,{remaining:'@uuid:pending',rate:0.1} as never);+ const instance=await WebAssembly.instantiate(new WebAssembly.Module(buildModule() as unknown as BufferSource),{env:{memory:heap.memory}});+ const exports=instance.exports as unknown as Record<string,unknown>;+ (exports['_initialize'] as (()=>void)|undefined)?.();+ const systems=new AotSystems();systems.install({engineAbi:ENGINE,projectShapes:SHAPES,systems:[{name:'Decay',symbol:'es_sys_Decay',queries:[[{comp:'Decay',mut:true}]],resources:[]}]},exports,name=>name==='Decay'?b.Decay:undefined);+ const runtime:AotRuntime={systems,addresses:{componentNamed:name=>name==='Decay'?b.Decay:undefined,resourceAt:()=>undefined,resourceWriteBack:()=>{},payloadRows:()=>[],sendEvent:()=>{},releasePayloads:()=>{}},ctx:new AotContext(memory),dispatcherFor:w=>new AotDispatch(w,runtime)};+ b.runner.useAot(runtime);+ const seen:unknown[]=[];+ const system=defineSystem([Query(Mut(b.Decay))],query=>{for(const [,data] of query as Iterable<[Entity,{remaining:unknown}]>)seen.push(data.remaining);},{name:'Decay'});+ b.runner.run(system);expect(seen).toEqual([1,'@uuid:pending']);expect(systems.calls).toBe(0);+ b.world.set(second,b.Decay,{remaining:1,rate:0.1});b.runner.run(system);+ expect(systems.calls).toBe(1);expect((b.world.get(first,b.Decay) as {remaining:number}).remaining).toBeCloseTo(0.9);+ // A cached row table must become invalid when a live view gains a ref.+ (b.world.get(first,b.Decay) as {remaining:unknown}).remaining='@uuid:later';b.runner.run(system);+ expect(systems.calls).toBe(1);expect(seen.slice(2)).toEqual(['@uuid:later',0.9]);+ expect(heap.staticsIntact()).toBe(true);+ });it('reports whether this gate could run at all', () => {if (EMCC) console.log('[aot-dispatch] the twin ran under the real runner');else console.warn('[aot-dispatch] NO EMSDK — the dispatch did NOT run (pnpm emsdk:setup).');diff --git a/sdk/tests/aot-event-own-fields.test.ts b/sdk/tests/aot-event-own-fields.test.tsnew file mode 100644index 000000000..cf8e7a656--- /dev/null+++ b/sdk/tests/aot-event-own-fields.test.ts@@ -0,0 +1,44 @@+import {afterEach,describe,it,expect,vi} from 'vitest';+import {AotEvents} from '../src/ecs/aot/AotEvents';+import type {PoolMemory} from '../src/ecs/ScriptPool';+const originalValue=Object.getOwnPropertyDescriptor(Object.prototype,'value');+afterEach(()=>{+ if(originalValue)Object.defineProperty(Object.prototype,'value',originalValue);+ else delete (Object.prototype as Record<string,unknown>).value;+});++function fixture(payloads:unknown[]=[]){+ const buffer=new ArrayBuffer(4096);let offset=8;+ const memory:PoolMemory={alloc(bytes){const at=offset;offset+=bytes;return{buffer,byteOffset:at,byteLength:bytes};},release(){}};+ const send=vi.fn(),events=new AotEvents(memory,()=>({read:()=>payloads,send}));+ return{buffer,send,events};+}+describe('compiled event own fields',()=>{+ it('preserves explicit prototype-named scalar fields as data',()=>{+ const {events,send}=fixture();events.send('Probe',['__proto__','constructor','toString'],[3,4,5]);+ const payload=send.mock.calls[0]![0];+ expect(Object.getPrototypeOf(payload)).toBe(Object.prototype);+ expect(JSON.stringify(payload)).toBe('{"__proto__":3,"constructor":4,"toString":5}');+ });+ it('creates nested own prototype fields without changing global prototypes',()=>{+ const key='__estellaAotEventOwnFieldProbe',prototype=Object.prototype as Record<string,unknown>;+ expect(Object.hasOwn(prototype,key)).toBe(false);+ try {+ const {events,send}=fixture();events.send('Probe',['__proto__.'+key,'nested.__proto__.value'],[7,9]);+ expect(Object.hasOwn(prototype,key)).toBe(false);+ expect(JSON.stringify(send.mock.calls[0]![0])).toBe('{"__proto__":{"'+key+'":7},"nested":{"__proto__":{"value":9}}}');+ }finally{delete prototype[key];delete prototype.value;}+ });+ it('round trips own nested fields and booleans through compiled rows',()=>{+ const payload=JSON.parse('{"__proto__":{"value":7},"nested":{"constructor":true}}');+ const {events,buffer,send}=fixture([payload]);+ const fields=['__proto__.value','nested.constructor'],rows=events.rowsFor('Probe',fields),values=[...new Float64Array(buffer,rows[0]![1],2)];+ expect(values).toEqual([7,1]);events.send('Probe',fields,values);+ expect(JSON.stringify(send.mock.calls[0]![0])).toBe('{"__proto__":{"value":7},"nested":{"constructor":1}}');events.release();+ });+ it('reads inherited values as absent without invoking inherited getters',()=>{+ const inherited=vi.fn(()=>13),base=Object.create(null);Object.defineProperty(base,'value',{get:inherited});+ const {events,buffer}=fixture([Object.create(base)]),rows=events.rowsFor('Probe',['value']);+ expect(new Float64Array(buffer,rows[0]![1],1)[0]).toBe(0);expect(inherited).not.toHaveBeenCalled();events.release();+ });+});diff --git a/sdk/tests/aot-native-install.test.ts b/sdk/tests/aot-native-install.test.tsindex 521b8802c..9887ffb43 100644--- a/sdk/tests/aot-native-install.test.ts+++ b/sdk/tests/aot-native-install.test.ts@@ -161,6 +161,32 @@ function eventFixture() {}describe('installing compiled systems on a host that loads a library', () => {+ it('a retired runtime refuses saved and runner-owned native dispatchers',()=>{+ const f=fixture(['DriftSystem']),entity=f.world.spawn();f.world.insert(entity,f.Drift,{x:7});+ let interpreted=0;const system=defineSystem([Query(Mut(f.Drift))],()=>{interpreted++;},{name:'DriftSystem'});+ const dispatcher=f.runtime!.dispatcherFor(f.world),twin=f.runtime!.systems.get('DriftSystem');+ f.runner.run(system);expect(f.calls).toEqual([0]);f.runtime!.dispose?.();f.runtime!.dispose?.();+ f.runner.run(system);expect(interpreted).toBe(1);expect(f.calls).toEqual([0]);+ if(twin)expect(dispatcher.run(twin)).toBe(false);+ });+ it('interprets every matching row with a portable asset ref, then resumes compiled',()=>{+ const f=fixture(['DriftSystem']);+ const fields=[{field:'x',type:'texture'}];+ Object.defineProperty(f.Drift,'assetFields',{value:fields});+ const first=f.world.spawn(),second=f.world.spawn();+ f.world.insert(first,f.Drift,{x:7});f.world.insert(second,f.Drift,{x:'@uuid:unresolved'} as never);+ const seen:unknown[]=[];+ const system=defineSystem([Query(Mut(f.Drift))],query=>{+ for(const [,data] of query)seen.push(data.x);+ },{name:'DriftSystem'});+ f.runner.run(system);expect(seen).toEqual([7,'@uuid:unresolved']);expect(f.calls).toEqual([]);+ f.world.set(second,f.Drift,{x:9});f.runner.run(system);+ expect(f.calls).toEqual([0]);expect(seen).toEqual([7,'@uuid:unresolved']);+ f.world.set(first,f.Drift,{x:'@uuid:later'} as never);f.runner.run(system);+ expect(f.calls).toEqual([0]);expect(seen.slice(2)).toEqual(['@uuid:later',9]);+ fields.length=0;f.runner.run(system);+ expect(f.calls).toEqual([0]);expect(seen.slice(4)).toEqual(['@uuid:later',9]);+ });it('a system the host cannot run is interpreted that frame, not skipped', () => {const f = fixture(['DriftSystem']);const Drift = f.Drift;diff --git a/sdk/tests/aot-replacement.test.ts b/sdk/tests/aot-replacement.test.tsnew file mode 100644index 000000000..bb1da1e5c--- /dev/null+++ b/sdk/tests/aot-replacement.test.ts@@ -0,0 +1,116 @@+import {afterEach,describe,it,expect,vi} from 'vitest';+import {App} from '../src/app/app';+import {defineComponent} from '../src/ecs/component';+import {defineSystem} from '../src/ecs/system';+import {Query,Mut} from '../src/ecs/query';+import {setPlatform} from '../src/platform/base';+import type {PlatformAdapter} from '../src/platform/types';+import {FakeEngine} from './fakeEngine';+import {buildFadeModule,fadeManifest,useBytesPlatform} from './helpers/aotFade';+import {emccPath} from '../../build-tools/utils/emscripten.js';+import {createMockModule} from './mocks/wasm';++const EMCC=emccPath();useBytesPlatform();afterEach(useBytesPlatform);+class TrackedEngine extends FakeEngine {+ readonly live=new Set<number>();+ override _malloc(size:number):number {const at=super._malloc(size);this.live.add(at);return at;}+ override _free(at?:number):void {expect(this.live.delete(at!)).toBe(true);}+}+function fixture(){+ const app=App.new(),host=new TrackedEngine(),Fade=defineComponent('Fade',{alpha:1,step:0.1});+ app.addSystem(defineSystem([Query(Mut(Fade))],q=>{for(const [,row] of q)row.alpha-=row.step;},{name:'Fade'}));+ const wasm=new Uint8Array(buildFadeModule(EMCC!)).buffer;+ return{app,host,Fade,opts:{host,manifest:fadeManifest(),wasm}};+}+describe.skipIf(!EMCC)('compiled runtime replacement ownership',()=>{+ it('retires old arenas on every replacement and releases all ownership on quit',async()=>{+ const f=fixture();+ try {+ for(let round=0;round<4;round++){+ await f.app.useCompiledSystems(f.opts);+ expect(f.host.live.size).toBe(0);+ await f.app.tick(1/60);expect(f.host.live.size).toBeGreaterThan(0);+ }+ }finally{f.app.quit({keepRenderer:true});}+ expect(f.host.live.size).toBe(0);+ });+ it('preserves pooled rows, held views and addresses when the allocator is unchanged',async()=>{+ const f=fixture();await f.app.useCompiledSystems(f.opts);+ const entity=f.app.world.spawn();f.app.world.insert(entity,f.Fade,{alpha:1,step:0.1});+ const held=f.app.world.get(entity,f.Fade),address=f.app.world.addressResolver(f.Fade)(entity);+ try{+ await f.app.tick(1/60);const live=f.host.live.size;+ await f.app.useCompiledSystems(f.opts);await f.app.tick(1/60);+ expect(held.alpha).toBeCloseTo(0.8);expect(f.app.world.get(entity,f.Fade)).toBe(held);+ expect(f.app.world.addressResolver(f.Fade)(entity)).toBe(address);expect(f.host.live.size).toBe(live);+ }finally{f.app.quit({keepRenderer:true});}expect(f.host.live.size).toBe(0);+ });+ it('rejects moving existing rows to a different allocator and retains the active runtime',async()=>{+ const f=fixture();await f.app.useCompiledSystems(f.opts);+ const entity=f.app.world.spawn();f.app.world.insert(entity,f.Fade,{alpha:1,step:0.1});+ try{+ await expect(f.app.useCompiledSystems({...f.opts,host:new TrackedEngine()})).rejects.toThrow(/before the first pooled component/);+ await f.app.tick(1/60);expect(f.app.world.get(entity,f.Fade).alpha).toBeCloseTo(0.9);expect(f.app.compiledSystems.calls).toBe(1);+ }finally{f.app.quit({keepRenderer:true});}expect(f.host.live.size).toBe(0);+ });+ it('serializes asynchronous installations and keeps the old runtime active until commit',async()=>{+ const f=fixture(),gates:Array<()=>void>=[],entered:Array<()=>void>=[];+ const firstEntered=new Promise<void>(r=>entered.push(r)),secondEntered=new Promise<void>(r=>entered.push(r));let calls=0;+ setPlatform({instantiateWasm:async(source:ArrayBuffer,imports:WebAssembly.Imports)=>{+ const n=calls++;entered[n]?.();await new Promise<void>(r=>gates[n]=r);return WebAssembly.instantiate(source,imports);+ }} as unknown as PlatformAdapter);+ const first=f.app.useCompiledSystems({...f.opts,manifest:{...f.opts.manifest,systems:[{...f.opts.manifest.systems[0]!,name:'First'}]}});+ const second=f.app.useCompiledSystems({...f.opts,manifest:{...f.opts.manifest,systems:[{...f.opts.manifest.systems[0]!,name:'Second'}]}});+ try {+ await firstEntered;expect(calls).toBe(1);gates[0]!();await first;await secondEntered;+ expect(f.app.compiledSystems.installed).toEqual(['First']);gates[1]!();await second;+ expect(f.app.compiledSystems.installed).toEqual(['Second']);expect(calls).toBe(2);+ }finally{gates.forEach(r=>r());f.app.quit({keepRenderer:true});}+ });+ it('cancels current and queued installs on quit without changing the retired world allocator',async()=>{+ const f=fixture();let begin!:()=>void,resume!:()=>void,calls=0;+ const started=new Promise<void>(r=>begin=r),gate=new Promise<void>(r=>resume=r);+ setPlatform({instantiateWasm:async(source:ArrayBuffer,imports:WebAssembly.Imports)=>{calls++;begin();await gate;return WebAssembly.instantiate(source,imports);}} as unknown as PlatformAdapter);+ const first=f.app.useCompiledSystems(f.opts).catch(e=>e),second=f.app.useCompiledSystems(f.opts).catch(e=>e);+ await started;f.app.quit({keepRenderer:true});resume();+ expect((await first).message).toMatch(/cancelled by App.quit/);expect((await second).message).toMatch(/cancelled by App.quit/);+ expect(calls).toBe(1);expect(f.app.compiledSystemCount).toBe(0);expect(f.host.live.size).toBe(0);+ const entity=f.app.world.spawn();f.app.world.insert(entity,f.Fade,{alpha:1,step:0.1});+ expect(f.host.live.size).toBe(0);f.app.quit({keepRenderer:true});+ });+ it('keeps the previous allocator after a refused module before rows exist',async()=>{+ const f=fixture();await f.app.useCompiledSystems(f.opts);const other=new TrackedEngine();+ try{+ await expect(f.app.useCompiledSystems({...f.opts,host:other,wasm:new Uint8Array([0]).buffer})).rejects.toThrow();+ const entity=f.app.world.spawn();f.app.world.insert(entity,f.Fade,{alpha:1,step:0.1});await f.app.tick(1/60);+ expect(f.app.world.get(entity,f.Fade).alpha).toBeCloseTo(0.9);expect(other.live.size).toBe(0);+ }finally{f.app.quit({keepRenderer:true});}expect(f.host.live.size).toBe(0);+ });+ it('shares allocator identity across the public module installation wrappers',async()=>{+ const f=fixture(),module=createMockModule();+ Object.assign(module,{wasmMemory:f.host.memory,_malloc:(n:number)=>f.host._malloc(n),_free:(at:number)=>f.host._free(at)});+ Object.defineProperty(module,'HEAPU8',{get:()=>f.host.HEAPU8});f.app.connectCpp(module.getRegistry(),module);+ try{+ expect(await f.app.installCompiledSystems(f.opts.wasm,f.opts.manifest)).toBe(1);+ const entity=f.app.world.spawn();f.app.world.insert(entity,f.Fade,{alpha:1,step:0.1});await f.app.tick(1/60);+ expect(await f.app.installCompiledSystems(f.opts.wasm,f.opts.manifest)).toBe(1);await f.app.tick(1/60);+ expect(f.app.world.get(entity,f.Fade).alpha).toBeCloseTo(0.8);+ }finally{f.app.quit({keepRenderer:true});}expect(f.host.live.size).toBe(0);+ });+ it('retains the new runtime if retiring the old arena reports an error',async()=>{+ const f=fixture(),warn=vi.spyOn(console,'warn').mockImplementation(()=>{});let thrown=false;+ const free=f.host._free.bind(f.host);f.host._free=at=>{free(at);if(!thrown){thrown=true;throw Error('retirement failed');}};+ try{+ await f.app.useCompiledSystems(f.opts);await f.app.tick(1/60);+ await f.app.useCompiledSystems(f.opts);expect(f.host.live.size).toBe(0);+ await f.app.tick(1/60);expect(f.app.compiledSystems.calls).toBe(1);+ }finally{f.app.quit({keepRenderer:true});warn.mockRestore();}expect(f.host.live.size).toBe(0);+ });+ it('cannot resurrect dispatch when old retirement reenters quit',async()=>{+ const f=fixture();await f.app.useCompiledSystems(f.opts);await f.app.tick(1/60);+ const free=f.host._free.bind(f.host);let quit=false;+ f.host._free=at=>{free(at);if(!quit){quit=true;f.app.quit({keepRenderer:true});}};+ await expect(f.app.useCompiledSystems(f.opts)).rejects.toThrow(/cancelled by App.quit/);+ expect(f.app.compiledSystemCount).toBe(0);expect(f.host.live.size).toBe(0);+ });+});diff --git a/sdk/tests/asset-cleanup-failure.test.ts b/sdk/tests/asset-cleanup-failure.test.tsnew file mode 100644index 000000000..b0e0d7f43--- /dev/null+++ b/sdk/tests/asset-cleanup-failure.test.ts@@ -0,0 +1,122 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect, vi } from 'vitest';+import { AssetScope, type AssetLease } from '../src/asset/AssetLease';+import { RegistryAssetSlots, type RegistryAssetKind } from '../src/asset/registryAssets';+import { Assets } from '../src/asset/Assets';+import type { Backend } from '../src/asset/Backend';+import { DependencyRecorder, PreparationFailure } from '../src/asset/dependencies';++vi.mock('../src/wasm/resourceManager', () => ({+ requireResourceManager: () => ({ releaseTexture: vi.fn() }),+ getResourceManager: () => null,+ evictTextureDimensions: vi.fn(),+}));++const lease = (release: () => void): AssetLease => ({ key: 'probe', generation: 1, value: null, release, retain: () => null });++describe('asset teardown survives user cleanup failures', () => {+ it.each([new Error('unload failed'), undefined, 'primitive failure'])('a scope returns every receipt and preserves the first thrown reason: %s', error => {+ const scope = new AssetScope(), events: string[] = [];+ scope.add(lease(() => { events.push('first'); }));+ scope.add(lease(() => { events.push('second'); throw error; }));+ scope.add(lease(() => { events.push('last'); }));+ let thrown = false, reason: unknown;+ try { scope.releaseAll(); } catch (e) { thrown = true; reason = e; }+ expect(thrown).toBe(true); expect(reason).toBe(error);+ expect(events).toEqual(['last', 'second', 'first']); expect(scope.size).toBe(0);+ scope.releaseAll(); expect(events).toHaveLength(3);+ });++ it('a cleanup can reenter the same scope without releasing receipts twice', () => {+ const scope = new AssetScope(), events: string[] = []; let entered = false;+ scope.add(lease(() => { events.push('first'); }));+ scope.add(lease(() => { events.push('last'); if (!entered) { entered = true; scope.releaseAll(); } }));+ expect(() => scope.releaseAll()).not.toThrow(); expect(events).toEqual(['last', 'first']);+ expect(scope.size).toBe(0);+ });++ it('a new acquisition during cleanup is owned by the next scope batch', () => {+ const scope = new AssetScope(), next = vi.fn();+ scope.add(lease(() => scope.add(lease(next))));+ scope.releaseAll(); expect(scope.size).toBe(1); expect(next).not.toHaveBeenCalled();+ scope.releaseAll(); expect(next).toHaveBeenCalledTimes(1); expect(scope.size).toBe(0);+ });++ it('a preparation keeps the load failure and its source after rollback cleanup also fails', () => {+ const recorder = new DependencyRecorder(), error = new Error('source missing'), released = vi.fn();+ recorder.read('missing.source');+ recorder.own('good', lease(released));+ recorder.own('bad', lease(() => { throw new Error('rollback cleanup failed'); }));+ const failure = recorder.abort(error);+ expect(failure).toBeInstanceOf(PreparationFailure); expect(failure.reason).toBe(error);+ expect(failure.sources).toContain('missing.source'); expect(released).toHaveBeenCalledOnce();+ });++ it('a value unload failure remains the reported reason if its dependencies also fail', async () => {+ const first = new Error('value unload failed'), second = new Error('dependency unload failed');+ const assets = assetsFor(() => { throw first; });+ assets.register({ type: 'parent', extensions: ['.parent'],+ load: async (_path, ctx) => { await ctx.acquireAsset('probe', 'a.probe'); return {}; }, unload: () => { throw second; } });+ const owner = await assets.acquireTyped('parent', 'a.parent');+ expect(() => owner.release()).toThrow(second);+ expect(assets.sizes()).toMatchObject({ refRows: 0, genericCached: 0 });+ });++ function kindFor(release: (path: string) => void): RegistryAssetKind<string> {+ return { prepare: async path => {+ const dependencies = new AssetScope(); dependencies.add(lease(() => release(path)));+ return { published: path, value: path, dependencies, edges: [] };+ } };+ }++ it('the last slot receipt unpublishes every alias even when a dependency unload throws', async () => {+ const slots = new RegistryAssetSlots(), error = new Error('bad dependency');+ const owner = await slots.acquire(kindFor(() => { throw error; }), 'probe', 'a', ['alias']);+ expect(() => owner.release()).toThrow(error);+ expect(slots.size).toBe(0); expect(slots.published('probe', 'alias')).toBeUndefined();+ expect(owner.retain()).toBeNull(); expect(() => owner.release()).not.toThrow();+ });++ it('a retiring slot cannot be retained from its own dependency cleanup', async () => {+ const slots = new RegistryAssetSlots(); let retained: AssetLease | null | undefined;+ const owner = await slots.acquire(kindFor(() => { retained = owner.retain(); }), 'probe', 'a', []);+ owner.release(); expect(retained).toBeNull(); expect(slots.size).toBe(0);+ });++ it('wholesale slot cleanup retires all names before callbacks and attempts all dependencies', async () => {+ const slots = new RegistryAssetSlots(), calls: string[] = [], error = new Error('bad first slot');+ const kind = kindFor(path => { calls.push(path); expect(slots.size).toBe(0); if (path === 'a') throw error; });+ const a = await slots.acquire(kind, 'probe', 'a', ['alias-a']);+ const b = await slots.acquire(kind, 'probe', 'b', ['alias-b']);+ expect(() => slots.releaseAll()).toThrow(error); expect(calls).toEqual(['a', 'b']);+ expect(slots.size).toBe(0); expect(a.retain()).toBeNull(); expect(b.retain()).toBeNull();+ expect(() => { a.release(); b.release(); slots.releaseAll(); }).not.toThrow();+ expect(calls).toHaveLength(2);+ });++ function assetsFor(unload: (value: { path: string }) => void) {+ const assets = Assets.create({ module: null, backend: { fetchBinary: async () => new ArrayBuffer(0), fetchText: async () => '{}', resolveUrl: p => p } as Backend });+ assets.register({ type: 'probe', extensions: ['.probe'], load: async path => ({ path }), unload });+ return assets;+ }++ it('a failed generic unload evicts the retired cache entry before a later acquisition', async () => {+ const error = new Error('bad unload'), unloaded: object[] = [];+ const assets = assetsFor(value => { unloaded.push(value); if (unloaded.length === 1) throw error; });+ const first = await assets.acquireTyped('probe', 'a.probe');+ expect(() => first.release()).toThrow(error);+ const second = await assets.acquireTyped('probe', 'a.probe');+ expect(second.value).not.toBe(first.value); second.release(); expect(unloaded).toHaveLength(2);+ expect(assets.sizes()).toMatchObject({ refRows: 0, genericCached: 0 });+ });++ it('wholesale Assets cleanup attempts all owned values despite the first unload failure', async () => {+ const calls: string[] = [], error = new Error('bad unload');+ const assets = assetsFor(value => { calls.push(value.path); if (value.path === 'a.probe') throw error; });+ const a = await assets.acquireTyped('probe', 'a.probe'), b = await assets.acquireTyped('probe', 'b.probe');+ expect(() => assets.releaseAll()).toThrow(error); expect(calls).toEqual(['a.probe', 'b.probe']);+ expect(assets.sizes()).toMatchObject({ refRows: 0, genericCached: 0, registrySlots: 0 });+ expect(() => { a.release(); b.release(); assets.releaseAll(); }).not.toThrow(); expect(calls).toHaveLength(2);+ });+});diff --git a/sdk/tests/asset-dependencies.test.ts b/sdk/tests/asset-dependencies.test.tsindex 5a500352b..e37a76124 100644--- a/sdk/tests/asset-dependencies.test.ts+++ b/sdk/tests/asset-dependencies.test.ts@@ -10,11 +10,20 @@* difference is the whole point — `owned` is a runtime resource the era* holds, `source` is content that decided what the era became.*/-import { describe, it, expect, vi, beforeEach } from 'vitest';+import { describe, it, expect, vi, beforeEach, beforeAll } from 'vitest';import { Assets } from '../src/asset/Assets';import { Catalog } from '../src/asset/Catalog';import type { Backend } from '../src/asset/Backend';import type { LoadContext } from '../src/asset/AssetLoader';+import { seedEngineComponents } from '../src/ecs/component';+import { ScriptGraphAssetLoader } from '../src/asset/loaders/ScriptGraphAssetLoader';+import type { CompiledScriptGraph } from '../src/logic/ScriptGraphRunner';+import '../src/logic';+import { World } from '../src/ecs/world';+import { Sprite } from '../src/ecs/component';+import { spawnPrepared, preparePrefab } from '../src/prefab/preparedPrefab';+import { loadWasmModule } from './helpers/loadWasm';+import type { ESEngineModule, CppRegistry } from '../src/wasm';// The tilemap loaders come with the subsystem now, not with the asset// registry: a package without tilemaps does not carry a tilemap parser.@@ -79,6 +88,7 @@ const materialFake = vi.hoisted(() => {setUniform: vi.fn(),tex: vi.fn((handle: number) => ({ kind: 'tex', handle })),compileShader: vi.fn(() => 7),+ releaseShader: vi.fn(),release: vi.fn((h: number) => { live.delete(h); }),},};@@ -132,6 +142,205 @@ function realm(docs: Record<string, string>): Assets {return assets;}+describe('spawned prefab entities own their resource generations', () => {+ let core: ESEngineModule;+ beforeAll(async () => { core = await loadWasmModule(); });+ beforeEach(() => { pool = createPoolFake(); materialFake.reset(); seedEngineComponents(); });+ function spawnedRealm(children = false) {+ const registry = new core.Registry(), world = new World(); world.connectCpp(registry as unknown as CppRegistry, core);+ const sprite = (id: string, parent: string | null) => ({ prefabEntityId: id, name: id, parent,+ children: id === 'root' && children ? ['child'] : [], visible: true,+ components: [{ type: 'Transform', data: {} }, { type: 'Sprite', data: { texture: id + '.png' } }] });+ const assets = realm({ 'root.esprefab': JSON.stringify({ version: '2', name: 'Owned sprites', rootEntityId: 'root',+ entities: [sprite('root', null), ...(children ? [sprite('child', 'root')] : [])] }),+ 'a.esgraph': JSON.stringify({ version: '1.0', name: 'Owner graph', nodes: [+ { id: 'spawn', kind: 'entity.spawn', literals: { prefab: 'root.esprefab' } },+ ], edges: [] }) }); assets.register(new ScriptGraphAssetLoader());+ const recipe = () => assets.resolveRegistryAsset<CompiledScriptGraph>('scriptgraph', 'a.esgraph')!.prefabs.get('root.esprefab')!;+ const dispose = () => { for (const e of world.getAllEntities()) if (world.valid(e)) world.despawn(e);+ assets.releaseAll(); world.disconnectCpp(); registry.delete(); };+ return { assets, world, recipe, dispose };+ }+ it('holds a sprite texture after its graph retires and releases it on despawn', async () => {+ const { assets, world, recipe, dispose } = spawnedRealm();+ try { const owner = await assets.acquireTyped('scriptgraph', 'a.esgraph');+ const { root } = spawnPrepared(world, recipe()); owner.release();+ expect(world.valid(root)).toBe(true); expect(world.get(root, Sprite).texture).toBeGreaterThan(0);+ expect(pool.liveTextures()).toBe(1); expect(assets.entityScopes.size).toBe(1);+ world.despawn(root); expect(pool.liveTextures()).toBe(0); expect(assets.entityScopes.size).toBe(0);+ expect(assets.sizes()).toMatchObject({ refRows: 0, registrySlots: 0, genericCached: 0 });+ } finally { dispose(); }+ });+ it.each([false, true])('standalone preparation releases raw sources and preserves its spawned resource (overrides: %s)', async (override) => {+ const { assets, world, dispose } = spawnedRealm();+ try { const prepared = await preparePrefab(assets, 'root.esprefab', override ? [{ prefabEntityId: 'root', type: 'property',+ componentType: 'Transform', propertyName: 'position', value: { x: 19, y: 0, z: 0 } }] : []);+ const { root } = spawnPrepared(world, prepared); prepared.release();+ expect(pool.liveTextures()).toBe(1); expect(assets.sizes()).toMatchObject({ refRows: 1, genericCached: 0 });+ world.despawn(root); expect(pool.liveTextures()).toBe(0);+ expect(assets.sizes()).toMatchObject({ refRows: 0, registrySlots: 0, genericCached: 0 });+ } finally { dispose(); }+ });+ it('a detached child owns only its texture after the parent and graph retire', async () => {+ const { assets, world, recipe, dispose } = spawnedRealm(true);+ try { const owner = await assets.acquireTyped('scriptgraph', 'a.esgraph'); const instance = spawnPrepared(world, recipe());+ const child = [...instance.entities.values()].find(e => e !== instance.root)!;+ world.removeParent(child); owner.release(); world.despawn(instance.root);+ expect(world.valid(child)).toBe(true); expect(pool.liveTextures()).toBe(1);+ expect(assets.entityScopes.size).toBe(1);+ world.despawn(child); expect(pool.liveTextures()).toBe(0); expect(assets.entityScopes.size).toBe(0);+ } finally { dispose(); }+ });+ it('keeps old and new texture generations independently through graph refresh', async () => {+ const { assets, world, recipe, dispose } = spawnedRealm();+ try { const owner = await assets.acquireTyped('scriptgraph', 'a.esgraph'); const old = spawnPrepared(world, recipe()).root;+ assets.invalidate('root.png'); await assets.assetGraphSettled(); const fresh = spawnPrepared(world, recipe()).root;+ expect(world.get(old, Sprite).texture).not.toBe(world.get(fresh, Sprite).texture);+ owner.release(); expect(pool.liveTextures()).toBe(2);+ world.despawn(old); expect(pool.liveTextures()).toBe(1);+ world.despawn(fresh); expect(pool.liveTextures()).toBe(0); expect(assets.entityScopes.size).toBe(0);+ } finally { dispose(); }+ });+ it('refuses a retired recipe before creating entities when its resource generation is gone', async () => {+ const { assets, world, recipe, dispose } = spawnedRealm();+ try { const owner = await assets.acquireTyped('scriptgraph', 'a.esgraph'); const stale = recipe(); owner.release();+ expect(() => spawnPrepared(world, stale)).toThrow(/retired|released/i);+ expect(world.entityCount()).toBe(0); expect(assets.entityScopes.size).toBe(0); expect(pool.liveTextures()).toBe(0);+ } finally { dispose(); }+ });+ it('a thousand copies share one texture while every copy has an independent lifetime', async () => {+ const { assets, world, recipe, dispose } = spawnedRealm();+ try { const owner = await assets.acquireTyped('scriptgraph', 'a.esgraph'), prepared = recipe();+ const roots = Array.from({ length: 1000 }, () => spawnPrepared(world, prepared).root); owner.release();+ expect(pool.createTexture.mock.calls.length + pool.createTextureFromBytes.mock.calls.length).toBe(1);+ expect(pool.liveTextures()).toBe(1);+ expect(assets.entityScopes.size).toBe(1000);+ for (const root of roots.slice(0, -1)) world.despawn(root);+ expect(pool.liveTextures()).toBe(1); expect(assets.entityScopes.size).toBe(1);+ world.despawn(roots.at(-1)!); expect(pool.liveTextures()).toBe(0); expect(assets.entityScopes.size).toBe(0);+ expect(assets.sizes()).toMatchObject({ refRows: 0, registrySlots: 0, genericCached: 0 });+ } finally { dispose(); }+ });+ it('the same recipe can give equal entity ids in two worlds independent scopes', async () => {+ const { assets, world, recipe, dispose } = spawnedRealm();+ const secondRegistry = new core.Registry(), second = new World(); second.connectCpp(secondRegistry as unknown as CppRegistry, core);+ try { const owner = await assets.acquireTyped('scriptgraph', 'a.esgraph'), prepared = recipe();+ const a = spawnPrepared(world, prepared).root, b = spawnPrepared(second, prepared).root;+ expect(a).toBe(b); owner.release(); expect(assets.entityScopes.size).toBe(2);+ world.despawn(a); expect(pool.liveTextures()).toBe(1); expect(assets.entityScopes.size).toBe(1);+ second.despawn(b); expect(pool.liveTextures()).toBe(0); expect(assets.entityScopes.size).toBe(0);+ } finally { for (const e of second.getAllEntities()) if (second.valid(e)) second.despawn(e);+ second.disconnectCpp(); secondRegistry.delete(); dispose(); }+ });+ it('rolls back earlier retains before spawning when a later resource generation is gone', async () => {+ const { assets, world, recipe, dispose } = spawnedRealm(true);+ try { const owner = await assets.acquireTyped('scriptgraph', 'a.esgraph'), prepared = recipe();+ const keepOne = await assets.acquireTexture('root.png'); owner.release();+ expect(pool.liveTextures()).toBe(1);+ expect(() => spawnPrepared(world, prepared)).toThrow(/retired|released/i);+ expect(world.entityCount()).toBe(0); expect(assets.entityScopes.size).toBe(0);+ keepOne.release(); expect(pool.liveTextures()).toBe(0); expect(assets.sizes().refRows).toBe(0);+ } finally { dispose(); }+ });+ it('rolls back entities and retained assets when the initial Name write fails', async () => {+ const { assets, world, recipe, dispose } = spawnedRealm();+ try { const owner = await assets.acquireTyped('scriptgraph', 'a.esgraph'), prepared = recipe();+ const fault = vi.spyOn(world, 'insert').mockImplementationOnce(() => { throw new Error('Name write failed'); });+ expect(() => spawnPrepared(world, prepared)).toThrow('Name write failed'); fault.mockRestore();+ expect(world.entityCount()).toBe(0); expect(assets.entityScopes.size).toBe(0);+ owner.release(); expect(pool.liveTextures()).toBe(0); expect(assets.sizes().refRows).toBe(0);+ } finally { dispose(); }+ });+ it('does not confuse material and texture resources with the same numeric handle', async () => {+ const { assets, world, recipe, dispose } = spawnedRealm(true);+ const fetchText = assets.backend.fetchText;+ assets.backend.fetchText = async url => {+ if (!url.endsWith('root.esprefab')) return fetchText.call(assets.backend, url);+ return JSON.stringify({ version: '2', name: 'Handle collision', rootEntityId: 'root', entities: [+ { prefabEntityId: 'root', name: 'Material', parent: null, children: ['child'], visible: true,+ components: [{ type: 'Transform', data: {} }, { type: 'Sprite', data: { material: 'skin.esmaterial' } }] },+ { prefabEntityId: 'child', name: 'Texture', parent: 'root', children: [], visible: true,+ components: [{ type: 'Transform', data: {} }, { type: 'Sprite', data: { texture: 'child.png' } }] },+ ] });+ };+ const unload = vi.fn(); assets.register({ type: 'material', extensions: ['.esmaterial'],+ load: async () => ({ handle: 1, shaderHandle: 0 }), unload });+ try { const owner = await assets.acquireTyped('scriptgraph', 'a.esgraph'), instance = spawnPrepared(world, recipe());+ const child = [...instance.entities.values()].find(e => e !== instance.root)!;+ expect(world.get(instance.root, Sprite).material).toBe(world.get(child, Sprite).texture);+ world.removeParent(child); owner.release(); world.despawn(instance.root);+ expect(unload).toHaveBeenCalledTimes(1); expect(pool.liveTextures()).toBe(1);+ world.despawn(child); expect(pool.liveTextures()).toBe(0); expect(assets.entityScopes.size).toBe(0);+ } finally { dispose(); }+ });+});++describe('partial resource preparation through prefab graphs', () => {+ beforeEach(() => { pool = createPoolFake(); materialFake.reset(); seedEngineComponents(); });+ function prefabGraph(data: Record<string, unknown>, type = 'Sprite') {+ const docs = { 'root.esprefab': JSON.stringify({ version: '2', name: 'Resources', rootEntityId: 'root', entities: [+ { prefabEntityId: 'root', name: 'Resources', parent: null, children: [], visible: true,+ components: [{ type: 'Transform', data: {} }, { type, data }] },+ ] }), 'a.esgraph': JSON.stringify({ version: '1.0', name: 'Resource graph', nodes: [+ { id: 'spawn', kind: 'entity.spawn', literals: { prefab: 'root.esprefab' } },+ ], edges: [] }), 'skin.esmaterial': MATERIAL };+ const assets = realm(docs); assets.register(new ScriptGraphAssetLoader());+ const graph = () => assets.resolveRegistryAsset<CompiledScriptGraph>('scriptgraph', 'a.esgraph')!;+ return { assets, graph };+ }++ it.each(['texture', 'material'] as const)('keeps the usable graph and its resource generation when a %s refresh partially fails', async (kind) => {+ const { assets, graph } = prefabGraph(kind === 'texture' ? { texture: 'wall.png' } : { material: 'skin.esmaterial' });+ let missing = false;+ assets.getTextureLoader().setPixelDecoder(async () => {+ if (missing) throw new Error('wall image missing');+ return { width: 4, height: 4, pixels: new Uint8Array(64) };+ });+ try {+ const lease = await assets.acquireTyped('scriptgraph', 'a.esgraph');+ const before = graph(), recipe = before.prefabs.get('root.esprefab')!;+ expect(pool.liveTextures()).toBe(1);+ missing = true; assets.invalidate('wall.png'); await assets.assetGraphSettled();+ expect(graph()).toBe(before);+ expect(graph().prefabs.get('root.esprefab')).toBe(recipe);+ expect(pool.liveTextures()).toBe(1);+ if (kind === 'material') expect(materialFake.live.size).toBe(1);+ missing = false; assets.invalidate('wall.png'); await assets.assetGraphSettled();+ expect(graph()).not.toBe(before);+ expect(graph().prefabs.get('root.esprefab')).not.toBe(recipe);+ expect(pool.liveTextures()).toBe(1);+ lease.release();+ expect(pool.liveTextures()).toBe(0); expect(materialFake.live.size).toBe(0);+ expect(assets.sizes()).toMatchObject({ refRows: 0, registrySlots: 0, genericCached: 0 });+ } finally { assets.releaseAll(); }+ });++ it('recovers an initially degraded prefab when the indirect source of a failed font appears', async () => {+ const { assets, graph } = prefabGraph({ font: 'face.font' }, 'BitmapText');+ const reason = new Error('font metrics missing'); let missing = true;+ const fetchText = assets.backend.fetchText;+ assets.backend.fetchText = async url => {+ if (url.endsWith('metrics.json') && missing) throw reason;+ return fetchText.call(assets.backend, url);+ };+ assets.register({ type: 'font', extensions: ['.font'], load: async (_path, ctx) => {+ await ctx.readSource!('metrics.json'); return { handle: 17 };+ }, unload: vi.fn() });+ try {+ const lease = await assets.acquireTyped('scriptgraph', 'a.esgraph');+ const recipe = graph().prefabs.get('root.esprefab')!;+ expect(recipe.missing).toContain('face.font');+ expect(assets.dependentsOfSource('metrics.json').length).toBeGreaterThan(0);+ missing = false; assets.invalidate('metrics.json'); await assets.assetGraphSettled();+ const after = graph().prefabs.get('root.esprefab')!;+ expect(after).not.toBe(recipe); expect(after.missing).toEqual([]);+ expect(after.scene.entities[0].components.find(c => c.type === 'BitmapText')!.data.font).toBe(17);+ lease.release();+ expect(assets.sizes()).toMatchObject({ refRows: 0, registrySlots: 0, genericCached: 0 });+ } finally { assets.releaseAll(); }+ });+});+describe('an edge comes from the acquisition that made it', () => {beforeEach(() => { pool = createPoolFake(); });diff --git a/sdk/tests/asset-handle-path.test.ts b/sdk/tests/asset-handle-path.test.tsindex 5f6fb059c..e72d82c36 100644--- a/sdk/tests/asset-handle-path.test.ts+++ b/sdk/tests/asset-handle-path.test.ts@@ -53,6 +53,18 @@ function createAssets(): Assets {}describe('Assets.pathForHandle', () => {+ it('forgets a handle only after its final receipt is released', async () => {+ const assets = createAssets();+ assets.register({ type: 'material', extensions: ['.esmaterial'],+ load: async () => ({ handle: 42, shaderHandle: 7 }), unload: () => {} } as never);+ const first = await assets.acquireTyped('material', 'assets/shared.esmaterial');+ const second = await assets.acquireTyped('material', 'assets/shared.esmaterial');+ first.release();+ expect(assets.pathForHandle('material', 42)).toBe('assets/shared.esmaterial');+ second.release();+ expect(assets.pathForHandle('material', 42)).toBeNull();+ expect(assets.sizes().handlePaths).toBe(0);+ });it('records handle→path on a typed load and resolves it back', async () => {const assets = createAssets();assets.register({diff --git a/sdk/tests/asset-preview-concurrency.test.ts b/sdk/tests/asset-preview-concurrency.test.tsnew file mode 100644index 000000000..0ca9b56a1--- /dev/null+++ b/sdk/tests/asset-preview-concurrency.test.ts@@ -0,0 +1,35 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { afterEach, describe, expect, it, vi } from 'vitest';+import { drawPreview, type PreviewCore } from '../src/render/assetPreview';+afterEach(() => vi.unstubAllGlobals());+const core = () => ({ HEAPU8: new Uint8Array(4), renderer_pollPreviewReadback: () => 1,+ renderer_getPreviewSize: () => 4, renderer_getPreviewWidth: () => 1,+ renderer_getPreviewHeight: () => 1, renderer_getPreviewPtr: () => 0 } as unknown as PreviewCore);+const imageData = () => vi.stubGlobal('ImageData', class {+ constructor(public data: Uint8ClampedArray, public width: number, public height: number) {}+});+describe('shared preview readback ownership', () => {+ it('copies each result before a concurrent request overwrites the core buffer', async () => {+ imageData(); const m = core();+ const images = await Promise.all([11, 22, 33].map(value => drawPreview(m, () => m.HEAPU8.fill(value))));+ expect(images.map(image => image!.data[0])).toEqual([11, 22, 33]);+ });+ it('does not poison subsequent requests after a draw throws', async () => {+ imageData(); const m = core();+ const bad = drawPreview(m, () => { throw Error('draw rejected'); });+ const next = drawPreview(m, () => m.HEAPU8.fill(44));+ await expect(bad).rejects.toThrow('draw rejected');+ expect((await next)!.data[0]).toBe(44);+ });+ it('allows another core to finish while the first core still owes a readback', async () => {+ imageData(); const first = core(), second = core(); let ready = false;+ first.renderer_pollPreviewReadback = () => ready ? 1 : 0;+ const pending = drawPreview(first, () => first.HEAPU8.fill(55));+ try {+ const image = await Promise.race([drawPreview(second, () => second.HEAPU8.fill(66)),+ new Promise<never>((_, reject) => setTimeout(() => reject(Error('independent core blocked')), 100))]);+ expect(image!.data[0]).toBe(66);+ } finally { ready = true; await pending; }+ });+});diff --git a/sdk/tests/asset-ref-counter.test.ts b/sdk/tests/asset-ref-counter.test.tsindex 5b16b835d..c78efc250 100644--- a/sdk/tests/asset-ref-counter.test.ts+++ b/sdk/tests/asset-ref-counter.test.ts@@ -4,6 +4,25 @@ import { describe, it, expect, beforeEach } from 'vitest';import { AssetRefCounter } from '../src/asset/AssetRefCounter';describe('AssetRefCounter', () => {+ it('keeps bidirectional usage consistent through duplicate, partial and entity-wide removal', () => {+ const counter = new AssetRefCounter();+ counter.addTextureRef('shared', 1); counter.addTextureRef('shared', 2);+ counter.addTextureRef('own', 1); counter.addTextureRef('own', 1);+ counter.addFontRef('font', 1); counter.addMaterialRef('material', 2);+ expect(counter.getTotalRefRows()).toBe(5);+ counter.removeTextureRef('own', 1);+ counter.removeTextureRef('own', 1);+ expect(counter.getTotalRefRows()).toBe(4);+ counter.removeAllRefsForEntity(1);+ expect(counter.getTextureRefs('shared')).toEqual([2]);+ expect(counter.getFontRefs('font')).toEqual([]);+ expect(counter.getTotalRefRows()).toBe(2);+ counter.clear(); counter.removeAllRefsForEntity(2);+ counter.addTextureRef('fresh', 2);+ expect(counter.getTotalRefRows()).toBe(1);+ counter.removeAllRefsForEntity(2);+ expect(counter.getTotalRefRows()).toBe(0);+ });let counter: AssetRefCounter;beforeEach(() => {diff --git a/sdk/tests/asset-refcounter-integration.test.ts b/sdk/tests/asset-refcounter-integration.test.tsindex 6de84bc09..80186b5fc 100644--- a/sdk/tests/asset-refcounter-integration.test.ts+++ b/sdk/tests/asset-refcounter-integration.test.ts@@ -1,8 +1,8 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/**- * Verifies that Assets.resolveSceneAssetPaths populates an attached- * AssetRefCounter so tools can answer "which entities hold this asset?".+ * Resolution prepares handles; tracking after spawning records runtime IDs so+ * tools can answer "which live entities hold this asset?" and despawn cleans up.** We only exercise the bookkeeping path — no WASM, no real loader.* resolveSceneAssetPaths takes a SceneAssetResult whose handle maps we@@ -17,6 +17,8 @@ import type { Backend } from '../src/asset/Backend';import type { SceneData } from '../src/scene/scene';import type { SceneAssetResult } from '../src/asset/Assets';import { AssetScope } from '../src/asset/AssetLease';+import { World } from '../src/ecs/world';+import { loadSceneData } from '../src/scene/scene';vi.mock('../src/wasm/resourceManager', () => ({requireResourceManager: () => ({ releaseTexture: vi.fn() }),@@ -85,6 +87,23 @@ beforeEach(() => {});describe('Assets.resolveSceneAssetPaths → AssetRefCounter', () => {+ it('records runtime IDs after spawning and removes the rows when those entities despawn', () => {+ const assets = makeAssets(), counter = new AssetRefCounter(), world = new World();+ assets.setRefCounter(counter);+ world.spawn(); world.spawn();+ world.onDespawn(entity => counter.removeAllRefsForEntity(entity));+ const scene = sceneWith(7, { texture: 'assets/player.png' }), result = emptyResult();+ result.textureHandles.set('assets/player.png', 42);+ assets.resolveSceneAssetPaths(scene, result);+ expect(counter.getTotalRefRows()).toBe(0);+ const entities = loadSceneData(world, scene);+ const entity = entities.get(7)!;+ expect(entity).not.toBe(7);+ assets.trackSceneAssetReferences(scene, entities);+ expect(counter.getTextureRefs('assets/player.png')).toEqual([entity]);+ world.despawn(entity);+ expect(counter.getTotalRefRows()).toBe(0);+ });it('records texture refs against the entity id when a handle resolves', () => {const assets = makeAssets();const counter = new AssetRefCounter();@@ -95,6 +114,7 @@ describe('Assets.resolveSceneAssetPaths → AssetRefCounter', () => {result.textureHandles.set('assets/player.png', 42);assets.resolveSceneAssetPaths(scene, result);+ assets.trackSceneAssetReferences(scene, new Map(scene.entities.map(e => [e.id, e.id])));expect(counter.getTextureRefCount('assets/player.png')).toBe(1);expect(counter.getTextureRefs('assets/player.png')).toEqual([7]);@@ -111,6 +131,7 @@ describe('Assets.resolveSceneAssetPaths → AssetRefCounter', () => {result.textureHandles.set('assets/missing.png', 0);assets.resolveSceneAssetPaths(scene, result);+ assets.trackSceneAssetReferences(scene, new Map(scene.entities.map(e => [e.id, e.id])));expect(counter.getTextureRefCount('assets/missing.png')).toBe(0);});@@ -142,6 +163,7 @@ describe('Assets.resolveSceneAssetPaths → AssetRefCounter', () => {result.fontHandles.set('font.fnt', 30);assets.resolveSceneAssetPaths(scene, result);+ assets.trackSceneAssetReferences(scene, new Map(scene.entities.map(e => [e.id, e.id])));expect(counter.getTextureRefCount('a.png')).toBe(1);expect(counter.getMaterialRefCount('a.mat')).toBe(1);diff --git a/sdk/tests/asset-resource-binding.test.ts b/sdk/tests/asset-resource-binding.test.tsnew file mode 100644index 000000000..8feaac56b--- /dev/null+++ b/sdk/tests/asset-resource-binding.test.ts@@ -0,0 +1,69 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, expect, it, vi } from 'vitest';+import { World } from '../src/ecs/world';+import { Assets as AssetsClass } from '../src/asset/Assets';+import { AssetPlugin, Assets } from '../src/asset/AssetPlugin';+import { bindAssetReferenceTracking } from '../src/asset/assetReferenceTracking';+import { Time } from '../src/ecs/resource';+import type { App } from '../src/app/app';+import type { SystemDef } from '../src/ecs/system';+import type { Backend } from '../src/asset/Backend';+const gpu = vi.hoisted(() => ({ status: 1 }));+vi.mock('../src/render/renderer', async importOriginal => ({+ ...await importOriginal<typeof import('../src/render/renderer')>(),+ getDeviceStatus: () => gpu.status,+}));+const makeAssets = () => AssetsClass.create({ backend: {} as Backend, module: null });+const settle = async () => { for (let i = 0; i < 12; i++) await Promise.resolve(); };++describe('current asset resource binding', () => {+ it('keeps one World callback across resource replacements and targets the active counter', () => {+ const world = new World(), first = makeAssets();+ let current = first;+ for (let i = 0; i < 100; i++) {+ current = makeAssets();+ bindAssetReferenceTracking(world, current, () => current);+ const entity = world.spawn();+ current.getRefCounter()!.addTextureRef('active.png', entity);+ world.despawn(entity);+ expect(current.getRefCounter()!.getTotalRefRows()).toBe(0);+ }+ expect(world.getStorageSizes().despawnCallbacks).toBe(1);+ });++ function pluginHost() {+ const resources = new Map<unknown, unknown>([[Time, { unscaledDelta: 1 }]]);+ const systems: SystemDef[] = [];+ const app = { world: new World(), wasmModule: {},+ hasResource: (key: unknown) => resources.has(key),+ getResource: (key: unknown) => resources.get(key),+ insertResource: (key: unknown, value: unknown) => resources.set(key, value),+ addSystemToSchedule: (_schedule: unknown, system: SystemDef) => systems.push(system),+ } as unknown as App;+ new AssetPlugin().build(app);+ return { app, tick: () => systems[0]._fn() };+ }++ it('recovers through the replacement decoder rather than the plugin build instance', async () => {+ const { app, tick } = pluginHost();+ const old = vi.spyOn(app.getResource(Assets), 'recoverFromDeviceLoss').mockResolvedValue(true);+ const current = makeAssets(), recover = vi.spyOn(current, 'recoverFromDeviceLoss').mockResolvedValue(true);+ app.insertResource(Assets, current);+ tick(); await settle();+ expect(recover).toHaveBeenCalledTimes(1);+ expect(old).not.toHaveBeenCalled();+ });++ it('recovers the new resource when it replaces an in-flight recovery owner', async () => {+ const { app, tick } = pluginHost();+ let finish!: (whole: boolean) => void;+ vi.spyOn(app.getResource(Assets), 'recoverFromDeviceLoss')+ .mockImplementation(() => new Promise(resolve => { finish = resolve; }));+ tick();+ const current = makeAssets(), recover = vi.spyOn(current, 'recoverFromDeviceLoss').mockResolvedValue(true);+ app.insertResource(Assets, current);+ finish(true); await settle();+ expect(recover).toHaveBeenCalledTimes(1);+ });+});diff --git a/sdk/tests/asset-teardown-loading.test.ts b/sdk/tests/asset-teardown-loading.test.tsnew file mode 100644index 000000000..8a9bf1460--- /dev/null+++ b/sdk/tests/asset-teardown-loading.test.ts@@ -0,0 +1,102 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect, vi } from 'vitest';+import { Assets } from '../src/asset/Assets';+import type { Backend } from '../src/asset/Backend';++const {releaseTexture} = vi.hoisted(() => ({ releaseTexture: vi.fn() }));+vi.mock('../src/wasm/resourceManager', () => ({+ requireResourceManager: () => ({ releaseTexture }),+ getResourceManager: () => null, evictTextureDimensions: vi.fn(),+}));+const deferred = <T>() => {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>(r => { resolve = r; });+ return { promise, resolve };+};+const make = (fetchText: Backend['fetchText'] = async () => '{}') => Assets.create({+ module: null, backend: { fetchText, fetchBinary: async () => new ArrayBuffer(0), resolveUrl: p => p } as Backend,+});++describe('loading across wholesale asset teardown', () => {+ it('immediately returns a composed texture held by a stalled preparation', async () => {+ const pending = deferred<string>(), entered = deferred<void>();+ const assets = make(async () => { entered.resolve(); return pending.promise; });+ releaseTexture.mockClear();+ vi.spyOn(assets.getTextureLoader(), 'loadFromPixels').mockResolvedValue({ handle: 42, width: 2, height: 2 });+ assets.register({ type: 'probe', extensions: [], load: async (_, ctx) => {+ await ctx.createOwnedTexture!(2, 2, new Uint8Array(16), false);+ await ctx.loadText('stalled'); return {};+ }, unload: vi.fn() });+ const request = assets.acquireTyped('probe', 'probe').then(() => null, e => e);+ await entered.promise; assets.releaseAll();+ expect(releaseTexture).toHaveBeenCalledTimes(1); expect(releaseTexture).toHaveBeenCalledWith(42);+ pending.resolve('{}'); expect(await request).toBeInstanceOf(Error);+ expect(releaseTexture).toHaveBeenCalledTimes(1);+ });+ it('rejects a new acquisition started by an unload before executing its loader', async () => {+ const assets = make(), nested = vi.fn(async () => ({ handle: 99 }));+ let request: Promise<unknown> | undefined;+ assets.register({ type: 'child', extensions: [], load: nested, unload: vi.fn() });+ assets.register({ type: 'parent', extensions: [], load: async () => ({}), unload: () => {+ assets.releaseAll(); // A nested release must not reopen the loading door.+ request = assets.acquireTyped('child', 'child').then(() => 'unexpected success', e => e);+ } });+ await assets.acquireTyped('parent', 'parent');+ assets.releaseAll();+ expect(await request).toBeInstanceOf(Error); expect(nested).not.toHaveBeenCalled();+ expect(assets.sizes()).toMatchObject({ refRows: 0, genericCached: 0 });+ const next = await assets.acquireTyped('child', 'child');+ next.release(); expect(nested).toHaveBeenCalledTimes(1);+ });++ it('does not start a fallback typed loader if releaseAll occurs during slot lookup', async () => {+ const assets = make(), load = vi.fn(async () => ({}));+ assets.register({ type: 'probe', extensions: [], load, unload: vi.fn() });+ const request = assets.acquireTyped('probe', 'probe').then(() => null, e => e);+ assets.releaseAll(); expect(await request).toBeInstanceOf(Error);+ expect(load).not.toHaveBeenCalled(); expect(assets.sizes().refRows).toBe(0);+ });++ it('stops a stale source read before the loader can create a resource', async () => {+ const pending = deferred<string>(), entered = deferred<void>();+ const assets = make(async () => { entered.resolve(); return pending.promise; }), create = vi.fn();+ assets.register({ type: 'probe', extensions: [], load: async (_, ctx) => {+ await ctx.loadText('source'); create(); return {};+ }, unload: vi.fn() });+ const request = assets.acquireTyped('probe', 'probe').then(() => null, e => e);+ await entered.promise; assets.releaseAll(); pending.resolve('{}');+ expect(await request).toBeInstanceOf(Error); expect(create).not.toHaveBeenCalled();+ expect(assets.sizes()).toMatchObject({ refRows: 0, genericCached: 0 });+ });++ it('an old loader resuming after teardown cannot acquire dependencies in the new epoch', async () => {+ const pending = deferred<void>(), entered = deferred<void>(), child = vi.fn(async () => ({}));+ const assets = make(); assets.register({ type: 'child', extensions: [], load: child, unload: vi.fn() });+ assets.register({ type: 'parent', extensions: [], load: async (_, ctx) => {+ entered.resolve(); await pending.promise; await ctx.acquireAsset('child', 'child'); return {};+ }, unload: vi.fn() });+ const request = assets.acquireTyped('parent', 'parent').then(() => null, e => e);+ await entered.promise; assets.releaseAll(); pending.resolve();+ expect(await request).toBeInstanceOf(Error); expect(child).not.toHaveBeenCalled();+ expect(assets.sizes()).toMatchObject({ refRows: 0, genericCached: 0 });+ });++ it('rejects a stale binary before resource creation and allows a fresh request immediately', async () => {+ const pending = deferred<ArrayBuffer>(), entered = deferred<void>(), create = vi.fn();+ const assets = make(); let first = true;+ assets.backend.fetchBinary = async () => {+ if (first) { first = false; entered.resolve(); return pending.promise; }+ return new ArrayBuffer(2);+ };+ assets.register({ type: 'probe', extensions: [], load: async (_, ctx) => {+ await ctx.loadBinary('source'); create(); return {};+ }, unload: vi.fn() });+ const old = assets.acquireTyped('probe', 'probe').then(() => null, e => e);+ await entered.promise; assets.releaseAll();+ const next = await assets.acquireTyped('probe', 'probe');+ pending.resolve(new ArrayBuffer(1)); expect(await old).toBeInstanceOf(Error);+ expect(create).toHaveBeenCalledTimes(1); expect(assets.sizes().refRows).toBe(1);+ next.release(); expect(assets.sizes()).toMatchObject({ refRows: 0, genericCached: 0 });+ });+});diff --git a/sdk/tests/camera-commit.test.ts b/sdk/tests/camera-commit.test.tsindex 82e60207e..557c5d284 100644--- a/sdk/tests/camera-commit.test.ts+++ b/sdk/tests/camera-commit.test.ts@@ -17,6 +17,7 @@ import type { PlatformAdapter } from '../src/platform/types';import { cameraPlugin } from '../src/camera/CameraPlugin';import { CameraCommit, onCameraCommitChanged } from '../src/camera/CameraCommit';import { UICameraInfo } from '../src/ui/core/ui-camera-info';+import { ScreenOverlay, defaultScreenOverlay } from '../src/ui/core/screen-overlay';import { RenderPipeline } from '../src/render/renderPipeline';import { setRendererBackend, type RendererBackend } from '../src/render/renderer';import { defineSystem, Schedule } from '../src/ecs/system';@@ -85,6 +86,31 @@ describe('the camera a frame was drawn with', () => {expect(Array.from(commit.viewProjection)).toEqual(Array.from(drawnWith!));});+ it('an offscreen camera cannot take over screen picking, commits or HUD layers', async () => {+ const { app, cam } = bootWithCamera();+ const registry = app.world.getCppRegistry() as unknown as Record<string, unknown> & CppRegistry;+ app.insertResource(ScreenOverlay, defaultScreenOverlay());+ app.world.update(cam, Camera, data => { data.cullingMask = 1; });+ const offscreen = app.world.spawn('texture camera');+ app.world.insert(offscreen, Transform, {+ position: { x: 1000, y: 0, z: 0 }, worldPosition: { x: 1000, y: 0, z: 0 },+ });+ app.world.insert(offscreen, Camera, { isActive: true, renderTarget: 7, cullingMask: 2, orthoSize: 50 });+ registry.getCameraEntities = () => [cam, offscreen];+ expect(registry.getCamera(cam).cullingMask).toBe(1);+ expect(registry.getCamera(offscreen).renderTarget).toBe(7);+ await app.tick(1 / 60);+ const ui = app.getResource(UICameraInfo);+ expect(ui.viewProjection[12]).toBeCloseTo(0);+ expect(app.getResource(CameraCommit).viewProjection[12]).toBeCloseTo(0);+ expect(app.getResource(ScreenOverlay).layerMask).toBe(1);+ registry.getCameraEntities = () => [offscreen];+ await app.tick(1 / 60);+ expect(app.getResource(UICameraInfo).valid).toBe(false);+ expect(app.getResource(CameraCommit).valid).toBe(false);+ expect(app.getResource(ScreenOverlay).layerMask).toBe(0xFFFFFFFF);+ });+it('is a copy, so a later write cannot move it under a reader', async () => {const { app } = bootWithCamera();await app.tick(1 / 60);diff --git a/sdk/tests/camera-pov.test.ts b/sdk/tests/camera-pov.test.tsindex 59015d721..585175ac3 100644--- a/sdk/tests/camera-pov.test.ts+++ b/sdk/tests/camera-pov.test.ts@@ -5,11 +5,13 @@* (buildCameraInfo), including the newly-honored camera rotation. The POV* is the decoupling point a camera director will blend over (Phase C).*/-import { describe, it, expect } from 'vitest';+import { describe, it, expect, vi } from 'vitest';import {buildCameraInfo, cameraFrustumCorners, snapToPixelGrid, type CameraPOV,} from '../src/camera/CameraPlugin';import { ProjectionType, ClearFlags } from '../src/ecs/component';+import { RenderTexture } from '../src/render/renderTexture';+import { Renderer } from '../src/render/renderer';function ndc(vp: Float32Array, x: number, y: number) {return { x: vp[0] * x + vp[4] * y + vp[12], y: vp[1] * x + vp[5] * y + vp[13] };@@ -35,6 +37,41 @@ const pov = (over: Partial<CameraPOV>): CameraPOV => ({});describe('camera POV → view-projection', () => {+ it('uses the target aspect and pixel grid for a portrait texture on a landscape screen', () => {+ const create = vi.spyOn(Renderer, 'createRenderTarget').mockReturnValue(7);+ const texture = vi.spyOn(Renderer, 'getTargetTexture').mockReturnValue(0);+ const release = vi.spyOn(Renderer, 'releaseRenderTarget').mockImplementation(() => {});+ const rt = RenderTexture.create({ width: 200, height: 400 });+ let released = false;+ try {+ const cam = buildCameraInfo(pov({ renderTarget: rt._handle, orthoSize: 100, x: 0.3, pixelPerfect: true }), 800, 600, null, [], 0);+ expect(cam.halfW).toBe(50);+ expect(cam.cameraX).toBe(0.5); // 200 world units / 400 target pixels+ const corner = ndc(cam.viewProjection, 50.5, 100);+ expect(corner.x).toBeCloseTo(1);+ expect(corner.y).toBeCloseTo(1);+ RenderTexture.release(rt);+ released = true;+ const fallback = buildCameraInfo(pov({ renderTarget: rt._handle, orthoSize: 100 }), 800, 600, null, [], 0);+ expect(fallback.halfW).toBeCloseTo(100 * 800 / 600);+ } finally {+ if (!released) RenderTexture.release(rt);+ create.mockRestore(); texture.mockRestore(); release.mockRestore();+ }+ });++ it.each([+ { viewport: { x: 0.75, y: 0.75, z: 0.25, w: 0.25 } },+ { renderTarget: 7 },+ ])('keeps independent camera zoom under a screen fit (%j)', (over) => {+ const fit = { designResolution: { x: 1920, y: 1080 }, scaleMode: 1, matchWidthOrHeight: 0.5 };+ const cam = buildCameraInfo(pov({ orthoSize: 100, ...over }), 800, 600, fit, [], 0);+ expect(cam.halfH).toBe(100);+ expect(ndc(cam.viewProjection, 0, 100).y).toBeCloseTo(1);+ const main = buildCameraInfo(pov({ orthoSize: 100 }), 800, 600, fit, [], 0);+ expect(main.halfH).toBe(540);+ });+it('rotation 0 keeps the old translation-only view (center → clip origin)', () => {const cam = buildCameraInfo(pov({ x: 100, y: 50 }), 800, 600, null, [], 0);const c = ndc(cam.viewProjection, 100, 50);diff --git a/sdk/tests/camera-render-order.test.ts b/sdk/tests/camera-render-order.test.tsindex 57e1add4f..7ff721962 100644--- a/sdk/tests/camera-render-order.test.ts+++ b/sdk/tests/camera-render-order.test.ts@@ -22,6 +22,7 @@ import { Camera, Transform, ProjectionType } from '../src/ecs/component';import { Query, Mut } from '../src/ecs/query';import type { Entity } from '../src/types';import type { CppRegistry } from '../src/wasm';+import { ScreenScaling } from '../src/camera/ScreenScaling';/** Where a world point lands in clip space under a view-projection. */const ndcX = (vp: Float32Array, x: number, y: number): number =>@@ -103,6 +104,26 @@ describe('render order: transforms resolve before cameras are read', () => {expect(calls.at(-1)).toBe('endFrame');});+ it('a selected camera preview uses the project fit just as a game frame does', async () => {+ const { app, module } = bootMockApp();+ const registry = module.getRegistry() as unknown as Record<string, unknown> & CppRegistry;+ const cam = app.world.spawn('camera') as Entity;+ app.world.insert(cam, Transform, {});+ app.world.insert(cam, Camera, { isActive: true, projectionType: ProjectionType.Orthographic, orthoSize: 180 });+ registry.getCameraEntities = () => [cam];+ registry.getCanvasEntities = () => [];+ app.setPipeline(new RenderPipeline());+ setRendererBackend(fakeBackend(registry, [cam]));+ app.addPlugin(cameraPlugin(() => ({ width: 800, height: 600 })));+ app.insertResource(ScreenScaling, { designWidth: 800, designHeight: 600, scaleMode: 1, matchWidthOrHeight: 0.5 });+ await app.tick(1 / 60);+ const gameProjection = Array.from(lastViewProjection!);+ expect(ndcX(lastViewProjection!, 400, 0)).toBeCloseTo(1);+ app.world.update(cam, Camera, data => { data.isActive = false; });+ expect(renderCameraFrame(app, 800, 600, cam)).toBe(true);+ expect(Array.from(lastViewProjection!)).toEqual(gameProjection);+ });+it('keeps updates alive without drawing a covered surface and resumes rendering', async () => {const { app, module } = bootMockApp();const registry = module.getRegistry() as unknown as Record<string, unknown> & CppRegistry;diff --git a/sdk/tests/clone-json-value.test.ts b/sdk/tests/clone-json-value.test.tsnew file mode 100644index 000000000..2e18a6ab3--- /dev/null+++ b/sdk/tests/clone-json-value.test.ts@@ -0,0 +1,50 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import {describe,it,expect} from 'vitest';+import {cloneJsonValue} from '../src/util/cloneJsonValue';++describe('authored JSON copy',()=>{+ it('copies nested records and arrays without aliases, including repeated references',()=>{+ const child={axis:[1,2]},source={left:child,right:child};+ const copy=cloneJsonValue(source);expect(copy).toEqual(JSON.parse(JSON.stringify(source)));+ copy.left.axis[0]=9;expect(source.left.axis[0]).toBe(1);expect(copy.right.axis[0]).toBe(1);+ });+ it('preserves JSON omission, array holes, nonfinite numbers and signed zero rules',()=>{+ const source={undefined,fn:()=>1,symbol:Symbol(),array:[,undefined,()=>1,Symbol(),NaN,Infinity,-0],n:NaN};+ expect(cloneJsonValue(source)).toEqual(JSON.parse(JSON.stringify(source)));+ expect(Object.is(cloneJsonValue(source).array[6],-0)).toBe(false);+ });+ it('keeps dates, boxed values and key-dependent toJSON conversion',()=>{+ const keyed={toJSON(key:string){return key;}};+ const source={date:new Date('2020-01-01'),number:new Number(3),map:new Map(),item:keyed,array:[keyed,keyed]};+ expect(cloneJsonValue(source)).toEqual(JSON.parse(JSON.stringify(source)));+ expect(cloneJsonValue(keyed)).toBe('');+ });+ it('does not interpret authored __proto__ as a prototype setter',()=>{+ const source=JSON.parse('{"__proto__":{"unsafe":1},"constructor":{"x":2}}');+ const copy=cloneJsonValue(source);expect(copy).toEqual(source);+ expect(Object.getPrototypeOf(copy)).toBe(Object.prototype);expect(({} as any).unsafe).toBeUndefined();+ });+ it('rejects cycles and BigInt instead of sharing unrepresentable values',()=>{+ const source:any={};source.self=source;+ expect(()=>cloneJsonValue(source)).toThrow(TypeError);expect(()=>cloneJsonValue({n:1n})).toThrow(TypeError);+ });+ it('rejects an unrepresentable root but omits a nested toJSON result of undefined',()=>{+ const missing={toJSON:()=>undefined};+ expect(()=>cloneJsonValue(missing)).toThrow(SyntaxError);+ expect(cloneJsonValue({missing,array:[missing]})).toEqual({array:[null]});+ });+ it('omits inherited enumerable fields and preserves null-prototype data',()=>{+ const source=Object.assign(Object.create(null),{a:1});+ expect(cloneJsonValue(source)).toEqual(JSON.parse(JSON.stringify(source)));+ expect(cloneJsonValue(Object.create({inherited:1}))).toEqual({});+ });+ it('copies deep JSON documents without exhausting the JS recursion stack',()=>{+ let source:any={leaf:1};for(let i=0;i<2500;i++)source={next:source};+ expect(JSON.stringify(cloneJsonValue(source))).toBe(JSON.stringify(source));+ });+ it('captures array length before reading index getters, as JSON does',()=>{+ const make=()=>{const values=[1];Object.defineProperty(values,0,{get:()=>{values.push(2);return 1;}});return values;};+ expect(cloneJsonValue(make())).toEqual(JSON.parse(JSON.stringify(make())));+ });+});diff --git a/sdk/tests/component-asset-validation.test.ts b/sdk/tests/component-asset-validation.test.tsnew file mode 100644index 000000000..2c6104e60--- /dev/null+++ b/sdk/tests/component-asset-validation.test.ts@@ -0,0 +1,79 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import {describe,it,expect,vi} from 'vitest';+import {validateComponentData,assetFieldNames} from '../src/util/validation';+import {defineComponent,Sprite} from '../src/ecs/component';+import {World} from '../src/ecs/world';+import {BuiltinBridge} from '../src/ecs/bridge/BuiltinBridge';+import type {CppRegistry} from '../src/wasm';++describe('component asset validation reads current metadata',()=>{+ it('list and Set metadata preserve the same type errors and asset exceptions',()=>{+ const fields=[{field:'texture'}],defaults={texture:0,count:0,nested:{texture:0}};+ const data={texture:'@uuid:texture',count:'bad',nested:{texture:'bad'}};+ const listErrors=validateComponentData('Probe',defaults,data,fields);+ expect(listErrors.map(e=>e.field)).toEqual(['count','nested.texture']);+ expect(listErrors).toEqual(validateComponentData('Probe',defaults,data,new Set(['texture'])));+ expect(assetFieldNames({assetFields:fields})).toEqual(new Set(['texture']));+ });+ it('metadata edits take effect without changing the component identity',()=>{+ const fields=[{field:'texture',type:'texture' as const}],comp=defineComponent('CurrentAssetMetadataProbe',{texture:0,other:0},{assetFields:fields});+ const w=new World(),entity=w.spawn();+ w.insert(entity,comp,{texture:'@uuid:texture'} as never);+ fields[0].field='other';+ expect(()=>w.insert(entity,comp,{texture:'@uuid:texture'} as never)).toThrow(/texture/);+ w.insert(entity,comp,{other:'@uuid:other'} as never);+ expect(w.get(entity,comp).other).toBe('@uuid:other');+ fields.length=0;+ expect(()=>w.insert(entity,comp,{other:'@uuid:other'} as never)).toThrow(/other/);+ });+ it('builtin asset strings stay legal while unrelated strings are rejected',()=>{+ const addSprite=vi.fn(),bridge=new BuiltinBridge();+ bridge.connect({hasSprite:()=>false,addSprite,getSprite:()=>({}),removeSprite:()=>{}} as unknown as CppRegistry);+ bridge.insert(1 as never,Sprite,{texture:'@uuid:texture'} as never);+ expect(addSprite.mock.calls[0][1].texture).toBe('@uuid:texture');+ expect(()=>bridge.insert(1 as never,Sprite,{layer:'bad'} as never)).toThrow(/layer/);+ expect(addSprite).toHaveBeenCalledTimes(1);+ });+ it('metadata array replacement immediately updates strict script insertion',()=>{+ const comp=defineComponent('ReplacedAssetMetadataProbe',{source:0},{assetFields:[]}),w=new World(),entity=w.spawn();+ expect(()=>w.insert(entity,comp,{source:'@uuid:source'} as never)).toThrow(/source/);+ Object.defineProperty(comp,'assetFields',{value:[{field:'source',type:'texture'}],configurable:true});+ w.insert(entity,comp,{source:'@uuid:source'} as never);+ expect(w.get(entity,comp).source).toBe('@uuid:source');+ });+ it('only string/number asset mismatches are exempt',()=>{+ const fields=[{field:'texture'}];+ expect(validateComponentData('Probe',{texture:0},{texture:false},fields).map(e=>e.field)).toEqual(['texture']);+ expect(validateComponentData('Probe',{texture:0},{texture:{}},fields).map(e=>e.field)).toEqual(['texture']);+ expect(validateComponentData('Probe',{texture:''},{texture:7},fields)).toEqual([]);+ });+ it('pooled asset references survive live writes, growth, delete and slot reuse',()=>{+ const comp=defineComponent('PooledAssetReferenceProbe',{texture:0,count:0},{assetFields:[{field:'texture',type:'texture'}]}),w=new World();+ const entity=w.spawn();w.insert(entity,comp,{texture:'@uuid:first',count:7} as never);+ const view=w.get(entity,comp),address=w.addressResolver(comp),epoch=w.scriptLayoutEpoch();+ expect(view.texture).toBe('@uuid:first');expect(address(entity)).toBeUndefined();+ (view as unknown as {texture:unknown}).texture=11;+ expect(address(entity)).toBeDefined();expect(w.scriptLayoutEpoch()).toBeGreaterThan(epoch);+ (view as unknown as {texture:unknown}).texture='@uuid:second';+ expect(address(entity)).toBeUndefined();+ for(let i=0;i<70;i++)w.insert(w.spawn(),comp,{texture:i,count:i});+ expect(view.texture).toBe('@uuid:second');expect(view.count).toBe(7);+ w.despawn(entity);const next=w.spawn();w.insert(next,comp,{texture:13,count:3});+ expect(w.get(next,comp).texture).toBe(13);expect(address(next)).toBeDefined();+ });+ it('adding asset metadata to an existing numeric pool preserves later references',()=>{+ const fields:{field:string;type:'texture'}[]=[],comp=defineComponent('PooledLateAssetMetadataProbe',{texture:0},{assetFields:fields}),w=new World(),entity=w.spawn();+ w.insert(entity,comp,{texture:5});const at=w.addressResolver(comp);expect(at(entity)).toBeDefined();+ fields.push({field:'texture',type:'texture'});w.set(entity,comp,{texture:'@uuid:late'} as never);+ expect(w.get(entity,comp).texture).toBe('@uuid:late');expect(at(entity)).toBeUndefined();+ w.set(entity,comp,{texture:9});expect(w.get(entity,comp).texture).toBe(9);expect(at(entity)).toBeDefined();+ });+ it('a row becomes addressable only after all portable refs resolve',()=>{+ const comp=defineComponent('PooledMultipleAssetReferences',{first:0,second:0},{assetFields:[{field:'first',type:'texture'},{field:'second',type:'texture'}]}),w=new World(),entity=w.spawn();+ w.insert(entity,comp,{first:'@uuid:first',second:'@uuid:second'} as never);+ const data=w.get(entity,comp) as unknown as {first:unknown;second:unknown},address=w.addressResolver(comp);+ data.first=5;expect(address(entity)).toBeUndefined();expect(data.second).toBe('@uuid:second');+ data.second=7;expect(address(entity)).toBeDefined();+ });+});diff --git a/sdk/tests/component-own-fields.test.ts b/sdk/tests/component-own-fields.test.tsnew file mode 100644index 000000000..7102e8495--- /dev/null+++ b/sdk/tests/component-own-fields.test.ts@@ -0,0 +1,94 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import {describe,it,expect,vi} from 'vitest';+import {defineComponent,mergeIntoDefaults,Sprite} from '../src/ecs/component';+import {validateComponentData} from '../src/util/validation';+import {World} from '../src/ecs/world';+import {BuiltinBridge} from '../src/ecs/bridge/BuiltinBridge';+import type {CppRegistry} from '../src/wasm';+import {applyOverrides} from '../src/prefab/override';+import {diffEntities} from '../src/prefab/diff';+import {deepClone} from '../src/util/deepClone';++describe('component schemas and own authored fields',()=>{+ it('default/resource deep copying keeps __proto__ as independent data',()=>{+ const source=JSON.parse('{"__proto__":{"flag":1},"nested":{"values":[1,2]}}');+ const copy=deepClone(source);+ expect(Object.getPrototypeOf(copy)).toBe(Object.prototype);+ expect(Object.prototype.hasOwnProperty.call(copy,'__proto__')).toBe(true);+ copy.__proto__.flag=9;expect(source.__proto__.flag).toBe(1);+ });+ it('a root __proto__ remains data without changing shared object prototypes',()=>{+ const key='__estellaOwnFieldsAudit';+ const patch=JSON.parse('{"__proto__":{"__estellaOwnFieldsAudit":7}}');+ try{+ const result=mergeIntoDefaults({position:{x:0,y:0}},patch);+ expect(Object.prototype.hasOwnProperty.call(Object.prototype,key)).toBe(false);+ expect(Object.getPrototypeOf(result)).toBe(Object.prototype);+ expect(Object.prototype.hasOwnProperty.call(result,'__proto__')).toBe(true);+ }finally{Reflect.deleteProperty(Object.prototype,key);}+ });+ it('a nested __proto__ stays an own field and never becomes the vector prototype',()=>{+ const result=mergeIntoDefaults({position:{x:0,y:0}},JSON.parse('{"position":{"__proto__":{"probe":7},"x":3}}'));+ expect(Object.getPrototypeOf(result.position)).toBe(Object.prototype);+ expect(Object.prototype.hasOwnProperty.call(result.position,'__proto__')).toBe(true);+ expect(result.position.x).toBe(3);expect(result.position.y).toBe(0);+ });+ it('inherited Object members cannot masquerade as declared schema fields',()=>{+ const data={constructor:Object,toString:Object.prototype.toString};+ expect(validateComponentData('Probe',{count:0},data).map(e=>e.field)).toEqual(['constructor','toString']);+ expect(validateComponentData('Probe',{count:0},JSON.parse('{"__proto__":{"flag":1}}')).map(e=>e.field)).toEqual(['__proto__']);+ });+ it('replicated fields cannot name inherited defaults',()=>{+ expect(()=>defineComponent('OwnFieldReplicationProbe',{count:0},{replicatedFields:['constructor']})).toThrow(/unknown field/);+ });+ it('renderable metadata cannot name an inherited boolean',()=>{+ const defaults=Object.assign(Object.create({ghost:true}),{count:0});+ expect(()=>defineComponent('OwnFieldRenderableProbe',defaults,{renderableField:'ghost'})).toThrow(/not a boolean field/);+ });+ it('property and metadata overrides write __proto__ as authored data',()=>{+ const entity={prefabEntityId:'root',name:'root',visible:true,components:[{type:'Probe',data:{}}],metadata:{}};+ applyOverrides(entity,[{prefabEntityId:'root',type:'property',componentType:'Probe',propertyName:'__proto__',value:{probe:1}},{prefabEntityId:'root',type:'metadata_set',metadataKey:'__proto__',value:{probe:2}}]);+ for(const value of [entity.components[0].data,entity.metadata]){+ expect(Object.getPrototypeOf(value)).toBe(Object.prototype);expect(Object.prototype.hasOwnProperty.call(value,'__proto__')).toBe(true);+ }+ });+ it('metadata removal does not mistake inherited constructor for an instance value',()=>{+ const baseline={prefabEntityId:'root',name:'root',visible:true,components:[],metadata:{constructor:3}};+ const instance={prefabEntityId:'root',id:0,name:'root',parent:null,children:[],visible:true,components:[],metadata:{}};+ expect(diffEntities([baseline],[instance]).overrides).toContainEqual({prefabEntityId:'root',type:'metadata_removed',metadataKey:'constructor'});+ });+ it('prefab diff compares own key sets instead of matching an inherited __proto__',()=>{+ const baseline={prefabEntityId:'root',name:'root',visible:true,components:[{type:'Probe',data:{payload:JSON.parse('{"__proto__":{}}')}}]};+ const instance={prefabEntityId:'root',id:0,name:'root',parent:null,children:[],visible:true,components:[{type:'Probe',data:{payload:{other:{}}}}]};+ expect(diffEntities([baseline],[instance]).overrides).toContainEqual({prefabEntityId:'root',type:'property',componentType:'Probe',propertyName:'payload',value:{other:{}}});+ });+ it('nested merging preserves own enumerable symbols and defaults without aliases',()=>{+ const symbol=Symbol('probe'),defaults={vector:{x:0,y:0}},patch={vector:{x:2,[symbol]:3}};+ const merged=mergeIntoDefaults<{vector:{x:number;y?:number}}>(defaults,patch);+ expect((merged.vector as any)[symbol]).toBe(3);expect(merged.vector).toMatchObject({x:2,y:0});+ merged.vector.y=9;expect(defaults.vector.y).toBe(0);+ });+ it('script insertion validates __proto__ instead of losing it during filtering',()=>{+ const comp=defineComponent('OwnFieldScriptProbe',{count:0}),world=new World(),entity=world.spawn();+ expect(()=>world.insert(entity,comp,JSON.parse('{"__proto__":{"flag":1},"count":2}'))).toThrow(/__proto__/);+ expect(world.has(entity,comp)).toBe(false);+ });+ it('builtin filtering keeps only fields owned by its declared defaults',()=>{+ const addSprite=vi.fn(),bridge=new BuiltinBridge();+ bridge.connect({hasSprite:()=>false,addSprite,getSprite:()=>({}),removeSprite:()=>{}} as unknown as CppRegistry);+ bridge.insert(1 as never,Sprite,{constructor:Object} as never);+ const payload=addSprite.mock.calls[0][1];+ expect(Object.prototype.hasOwnProperty.call(payload,'constructor')).toBe(false);+ });+ it('explicit own constructor and __proto__ fields remain usable and type checked',()=>{+ const defaults=JSON.parse('{"constructor":0,"__proto__":{"x":0}}');+ const comp=defineComponent('OwnFieldExplicitProbe',defaults,{replicatedFields:['constructor']});+ const world=new World(),entity=world.spawn();+ world.insert(entity,comp,JSON.parse('{"constructor":3,"__proto__":{"x":4}}'));+ const data=world.get(entity,comp);+ expect(data.constructor).toBe(3);expect(Object.prototype.hasOwnProperty.call(data,'__proto__')).toBe(true);+ expect(data.__proto__.x).toBe(4);expect(Object.getPrototypeOf(data)).toBe(Object.prototype);+ expect(validateComponentData('Probe',defaults,JSON.parse('{"__proto__":{"x":"wrong"}}')).map(e=>e.field)).toEqual(['__proto__.x']);+ });+});diff --git a/sdk/tests/disabled-entities.test.ts b/sdk/tests/disabled-entities.test.tsindex 0e2a004e8..16d1a5c7d 100644--- a/sdk/tests/disabled-entities.test.ts+++ b/sdk/tests/disabled-entities.test.ts@@ -30,6 +30,39 @@ function worldWith(n: number): { world: World; entities: Entity[] } {}describe('a disabled entity', () => {+ it('filters component-free queries while retaining raw management access', () => {+ const { world, entities } = worldWith(2);+ setEntityActive(world, entities[0]!, false);+ expect(world.queryEntities([])).toEqual([entities[1]]);+ expect(world.getAllEntities()).toEqual(entities);+ setEntityActive(world, entities[0]!, true);+ expect(world.queryEntities([])).toEqual(entities);+ });++ it('observes core activity changes after a query cache hit', () => {+ const { world, entities } = worldWith(2);+ const disabled = new Set<Entity>();+ let epoch = 0;+ const core = {+ setEntityEnabled: (e: Entity, enabled: boolean) => {+ if (enabled) disabled.delete(e); else disabled.add(e);+ ++epoch; return true;+ },+ isEntityActive: (e: Entity) => !disabled.has(e),+ isEntityEnabled: (e: Entity) => !disabled.has(e),+ hasInactiveEntities: () => disabled.size > 0,+ activityEpoch: () => epoch,+ };+ world.connectCpp(core as never);+ expect(world.queryEntities([Health])).toEqual(entities);+ core.setEntityEnabled(entities[0]!, false);+ expect(world.queryEntities([Health])).toEqual([entities[1]]);+ expect(isEntityActive(world, entities[0]!)).toBe(false);+ setEntityActive(world, entities[0]!, true);+ expect(world.queryEntities([Health])).toEqual(entities);+ setEntityActive(world, entities[1]!, false);+ expect(core.isEntityActive(entities[1]!)).toBe(false);+ });it('is not answered by a query', () => {const { world, entities } = worldWith(3);expect(world.getEntitiesWithComponents([Health])).toHaveLength(3);diff --git a/sdk/tests/dragonbones-manager.integration.test.ts b/sdk/tests/dragonbones-manager.integration.test.tsindex 6a8ef41ed..b02ccbeba 100644--- a/sdk/tests/dragonbones-manager.integration.test.ts+++ b/sdk/tests/dragonbones-manager.integration.test.ts@@ -104,8 +104,10 @@ describe.skipIf(!HAS_ASSETS)('DragonBonesManager', () => {manager = fresh();const handle = load(manager, 'dragonboy');manager.setAtlasTexture(handle, 3);- manager.addEntity(e(1), handle, { armature: 'Dragon', assetKey: 'dragonboy' });- manager.addEntity(e(1), handle, { armature: 'Dragon', assetKey: 'dragonboy' });+ expect(manager.addEntity(e(1), handle, { armature: 'Dragon', assetKey: 'dragonboy' })).toBe(true);+ expect(manager.addEntity(e(1), handle, { armature: 'Dragon', assetKey: 'dragonboy' })).toBe(true);+ expect(manager.hasInstance(e(1))).toBe(true);+ expect(manager.play(e(1), 'walk')).toBe(true);// One entity, one instance — and the shared skeleton survives, which it// would not if the replace released a reference it never took.@@ -126,4 +128,84 @@ describe.skipIf(!HAS_ASSETS)('DragonBonesManager', () => {// and the second must not free a handle the first already did.expect(() => manager.dispose()).not.toThrow();});++ it('keeps the previous instance and its enable state when a replacement fails', () => {+ manager = fresh();+ const handle = load(manager, 'dragonboy');+ manager.setAtlasTexture(handle, 3);+ expect(manager.addEntity(e(1), handle, { armature: 'Dragon', assetKey: 'dragonboy', animation: 'walk' })).toBe(true);+ manager.updateAnimations(1 / 60);+ manager.setEnabled(e(1), false);+ const bounds = manager.getBounds(e(1));+ expect(manager.addEntity(e(1), handle, { armature: 'Nope', assetKey: 'dragonboy' })).toBe(false);+ expect(manager.hasInstance(e(1))).toBe(true);+ expect(manager.getArmatures(handle)).toEqual(['Dragon']);+ for (let i = 0; i < 20; i++) manager.updateAnimations(1 / 60);+ expect(manager.getBounds(e(1))).toEqual(bounds);+ manager.setEnabled(e(1), true); manager.updateAnimations(1 / 60);+ expect(manager.getBounds(e(1))).not.toEqual(bounds);+ manager.dispose();+ });++ it('transfers an unkeyed skeleton to the replacement before releasing the last owner', () => {+ manager = fresh();+ const handle = load(manager);+ expect(manager.addEntity(e(1), handle, { armature: 'Dragon' })).toBe(true);+ expect(manager.addEntity(e(1), handle, { armature: 'Dragon' })).toBe(true);+ expect(manager.play(e(1), 'walk')).toBe(true);+ manager.removeEntity(e(1));+ expect(manager.getArmatures(handle)).toEqual([]);+ manager.dispose();+ });++ it('rejects inconsistent keyed ownership before replacing an instance', () => {+ manager = fresh();+ const handle = load(manager, 'dragonboy');+ const other = load(manager, 'other');+ expect(manager.addEntity(e(1), handle, { armature: 'Dragon', assetKey: 'dragonboy' })).toBe(true);+ expect(manager.addEntity(e(1), other, { armature: 'Dragon', assetKey: 'dragonboy' })).toBe(false);+ expect(manager.addEntity(e(1), handle, { armature: 'Dragon', assetKey: 'missing' })).toBe(false);+ expect(manager.addEntity(e(1), handle, { armature: 'Dragon' })).toBe(false);+ expect(manager.hasInstance(e(1))).toBe(true);+ expect(manager.play(e(1), 'walk')).toBe(true);+ manager.dispose();+ });++ it('keeps manual disable when a replacement succeeds', () => {+ manager = fresh();+ const handle = load(manager, 'dragonboy'); manager.setAtlasTexture(handle, 3);+ try {+ expect(manager.addEntity(e(1), handle, { armature: 'Dragon', assetKey: 'dragonboy', animation: 'walk' })).toBe(true);+ manager.setEnabled(e(1), false);+ expect(manager.addEntity(e(1), handle, { armature: 'Dragon', assetKey: 'dragonboy', animation: 'walk' })).toBe(true);+ const frozen = manager.getBounds(e(1));+ for (let i = 0; i < 20; i++) manager.updateAnimations(1 / 60);+ expect(manager.getBounds(e(1))).toEqual(frozen);+ manager.setEnabled(e(1), true); manager.updateAnimations(1 / 60);+ expect(manager.getBounds(e(1))).not.toEqual(frozen);+ } finally { manager.dispose(); }+ });++ it('releases unkeyed skeletons on dispose, including one never attached', () => {+ manager = fresh();+ const attached = load(manager);+ const unused = load(manager);+ expect(manager.addEntity(e(1), attached, { armature: 'Dragon' })).toBe(true);+ manager.dispose();+ expect(manager.getArmatures(attached)).toEqual([]);+ expect(manager.getArmatures(unused)).toEqual([]);+ });++ it('keeps an unkeyed handle alive while another attached entity holds it', () => {+ manager = fresh();+ const handle = load(manager);+ expect(manager.addEntity(e(1), handle, { armature: 'Dragon' })).toBe(true);+ expect(manager.addEntity(e(2), handle, { armature: 'Dragon' })).toBe(true);+ manager.removeEntity(e(1));+ expect(manager.getArmatures(handle)).toEqual(['Dragon']);+ expect(manager.play(e(2), 'walk')).toBe(true);+ manager.removeEntity(e(2));+ expect(manager.getArmatures(handle)).toEqual([]);+ manager.dispose();+ });});diff --git a/sdk/tests/draw-material-inheritance.test.ts b/sdk/tests/draw-material-inheritance.test.tsnew file mode 100644index 000000000..fc110ad5c--- /dev/null+++ b/sdk/tests/draw-material-inheritance.test.ts@@ -0,0 +1,39 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import{afterEach,beforeEach,describe,expect,it,vi}from'vitest';+import{Draw,initDrawAPI,shutdownDrawAPI}from'../src/render/draw';+import{Material,initMaterialAPI,shutdownMaterialAPI}from'../src/render/material';+import{BlendMode}from'../src/render/blend';+import type{ESEngineModule}from'../src/wasm';+describe('legacy Draw with real material instances',()=>{+ let core:ReturnType<typeof makeCore>;+ function makeCore(){let address=128;return{HEAPF32:new Float32Array(4096),_malloc:(bytes:number)=>{const p=address;address+=bytes;return p;},_free:vi.fn(),+ material_define:vi.fn(),material_setUniform:vi.fn(),material_setTexture:vi.fn(),material_undefine:vi.fn(),material_compileEsshader:()=>1,+ draw_meshWithMaterial:vi.fn(()=>false),draw_mesh:vi.fn(),draw_meshWithUniforms:vi.fn(),draw_setBlendMode:vi.fn(),draw_setDepthTest:vi.fn()};}+ beforeEach(()=>{core=makeCore();initMaterialAPI(core as never);initDrawAPI(core as unknown as ESEngineModule);});+ afterEach(()=>{shutdownDrawAPI();shutdownMaterialAPI();});+ const stream=()=>{const call=core.draw_meshWithUniforms.mock.calls.at(-1)!;return Array.from(core.HEAPF32.subarray(call[3]/4,call[3]/4+call[4]));};+ it('inherits parent uniforms and state without writing local overrides',()=>{+ const parent=Material.create({shader:7,blendMode:BlendMode.Additive,depthTest:true,uniforms:{u_color:{x:1,y:0,z:0,w:1}}});+ const child=Material.createInstance(parent);Draw.drawMeshWithMaterial(1,child);+ expect(core.draw_meshWithUniforms).toHaveBeenCalled();+ expect(stream()).toEqual([4,1,1,0,0,1]);+ expect(core.draw_setBlendMode).toHaveBeenCalledWith(BlendMode.Additive);+ expect(core.draw_setDepthTest).toHaveBeenCalledWith(true);+ expect(Material.get(child)!.uniforms.size).toBe(0);+ });+ it('updates cached inheritance after parent edits and resets, preserving child overrides',()=>{+ const parent=Material.create({shader:7,uniforms:{u_color:{x:1,y:0,z:0,w:1}}}),child=Material.createInstance(parent);+ Draw.drawMeshWithMaterial(1,child);Material.setUniform(parent,'u_color',{x:0,y:1,z:0,w:1});+ Draw.drawMeshWithMaterial(1,child);expect(stream()).toEqual([4,1,0,1,0,1]);+ Material.setUniform(child,'u_color',{x:0,y:0,z:1,w:1});Draw.drawMeshWithMaterial(1,child);+ expect(stream()).toEqual([4,1,0,0,1,1]);Material.applyState(child,{});Draw.drawMeshWithMaterial(1,child);+ expect(stream()).toEqual([4,1,0,1,0,1]);+ });+ it('inherits texture refs and reuses the encoded stream on warm draws',()=>{+ const parent=Material.create({shader:7,uniforms:{u_texture0:Material.tex(42,2)}}),child=Material.createInstance(parent);+ const read=vi.spyOn(Material,'getUniforms');Draw.drawMeshWithMaterial(1,child);+ expect(stream()).toEqual([10,14,2,42]);const cached=Material.get(child)!.cachedBuffer_;+ Draw.drawMeshWithMaterial(1,child);expect(Material.get(child)!.cachedBuffer_).toBe(cached);expect(read).toHaveBeenCalledTimes(1);read.mockRestore();+ });+});diff --git a/sdk/tests/draw.test.ts b/sdk/tests/draw.test.tsindex cc1dced81..2edc3cafa 100644--- a/sdk/tests/draw.test.ts+++ b/sdk/tests/draw.test.ts@@ -5,6 +5,8 @@ vi.mock('../src/render/material', () => {return {Material: {get: vi.fn((id: number) => materials.get(id)),+ getRenderState: vi.fn((id: number) => materials.get(id)),+ getUniforms: vi.fn((id: number) => materials.get(id)?.uniforms ?? new Map()),_materials: materials,},isTextureRef: vi.fn(diff --git a/sdk/tests/entity-hierarchy.test.ts b/sdk/tests/entity-hierarchy.test.tsindex ff5791c6b..0be3c8207 100644--- a/sdk/tests/entity-hierarchy.test.ts+++ b/sdk/tests/entity-hierarchy.test.ts@@ -8,7 +8,8 @@*/import { describe, it, expect, beforeAll } from 'vitest';import { World } from '../src/ecs/world';-import { Transform, Sprite, Parent, Children } from '../src/ecs/component';+import { Transform, Sprite, Parent, Children, Disabled, Canvas, Camera } from '../src/ecs/component';+import { setEntityActive, isEntityActive } from '../src/ecs/entityUtils';import { CommandsInstance } from '../src/ecs/commands';import { ResourceStorage } from '../src/ecs/resource';import type { Entity } from '../src/types';@@ -37,6 +38,116 @@ describe.skipIf(!HAS_WASM)('Entity Hierarchy (WASM integration)', () => {(registry as any).delete();}+ it('shares effective activity between WASM, SDK queries and reparenting', () => {+ const { world, registry } = createWorld();+ try {+ const parent = world.spawn(), child = world.spawn(), other = world.spawn();+ world.insert(child, Sprite, {});+ world.setParent(child, parent);+ expect(world.queryEntities([Sprite])).toEqual([child]);+ setEntityActive(world, parent, false);+ expect(registry.isEntityActive!(child)).toBe(false);+ expect(isEntityActive(world, child)).toBe(true);+ expect(world.queryEntities([Sprite])).toEqual([]);+ world.setParent(child, other);+ expect(world.queryEntities([Sprite])).toEqual([child]);+ registry.setEntityEnabled!(other, false);+ expect(world.queryEntities([Sprite])).toEqual([]);+ registry.setEntityEnabled!(other, true);+ expect(world.queryEntities([Sprite])).toEqual([child]);+ world.insert(child, Disabled, {});+ setEntityActive(world, parent, true);+ expect(registry.isEntityActive!(child)).toBe(false);+ world.remove(child, Disabled);+ expect(registry.isEntityActive!(child)).toBe(true);+ } finally { disposeWorld(world, registry); }+ });++ it('enumerates only active cameras and Canvases in the core selectors', () => {+ const { world, registry } = createWorld();+ try {+ const root = world.spawn(), child = world.spawn();+ world.insert(child, Transform, {});+ world.insert(child, Camera, { isActive: true });+ world.insert(child, Canvas, {});+ world.setParent(child, root);+ expect(module.registry_getCanvasEntity(registry)).toBe(child);+ expect(module.registry_getCameraEntities(registry)).toEqual([child]);+ setEntityActive(world, root, false);+ expect(module.registry_getCanvasEntity(registry)).toBe(-1);+ expect(module.registry_getCanvasEntities!(registry)).toEqual([]);+ expect(module.registry_getCameraEntities(registry)).toEqual([]);+ setEntityActive(world, root, true);+ expect(module.registry_getCanvasEntities!(registry)).toEqual([child]);+ expect(module.registry_getCameraEntities(registry)).toEqual([child]);+ } finally { disposeWorld(world, registry); }+ });++ describe('rejected parenting is atomic', () => {+ it('insert(Parent) returns the retained relationship after rejection', () => {+ const { world, registry } = createWorld();+ const parent = world.spawn();+ const child = world.spawn();+ world.setParent(child, parent);+ expect(world.insert(child, Parent, { entity: child }).entity).toBe(parent);+ expect(module.getChildEntities(registry, parent)).toEqual([child]);+ disposeWorld(world, registry);+ });++ it.each(['self', 'descendant', 'destroyed target'] as const)('%s preserves both sides and SDK caches', (reason) => {+ const { world, registry } = createWorld();+ const parent = world.spawn();+ const child = world.spawn();+ const descendant = world.spawn();+ const stale = world.spawn();+ world.setParent(child, parent);+ world.setParent(descendant, child);+ world.despawn(stale);+ const target = reason === 'self' ? child : reason === 'descendant' ? descendant : stale;+ const before = module.getChildEntities(registry, parent);+ const version = world.getWorldVersion();+ expect(world.trySetParent(child, target)).toBe(false);+ expect(registry.getParent(child).entity).toBe(parent);+ expect(module.getChildEntities(registry, parent)).toEqual(before);+ expect(world.get(child, Parent).entity).toBe(parent);+ expect(world.getWorldVersion()).toBe(version);+ disposeWorld(world, registry);+ });++ it('rejects a stale child without adding it to a live parent', () => {+ const { world, registry } = createWorld();+ const parent = world.spawn();+ const stale = world.spawn();+ world.despawn(stale);+ registry.setParent(stale, parent);+ expect(module.getChildEntities(registry, parent)).toEqual([]);+ disposeWorld(world, registry);+ });++ it('repeating the same parent preserves sibling order', () => {+ const { world, registry } = createWorld();+ const parent = world.spawn();+ const a = world.spawn();+ const b = world.spawn();+ world.setParent(a, parent);+ world.setParent(b, parent);+ registry.setParent(a, parent);+ expect(module.getChildEntities(registry, parent)).toEqual([a, b]);+ disposeWorld(world, registry);+ });++ it.each([0, 0xFFFFFFFF])('detaches with null sentinel %s', (sentinel) => {+ const { world, registry } = createWorld();+ const parent = world.spawn();+ const child = world.spawn();+ world.setParent(child, parent);+ expect(registry.setParent(child, sentinel as Entity)).toBe(true);+ expect(registry.hasParent(child)).toBe(false);+ expect(module.getChildEntities(registry, parent)).toEqual([]);+ disposeWorld(world, registry);+ });+ });+// Parent and Children are two halves of one link. Every way of writing it has// to leave both halves — and their JS mirrors, which has()/queries read —// agreeing, or a subtree becomes unreachable to every tree walk there is.diff --git a/sdk/tests/entity-visibility.test.ts b/sdk/tests/entity-visibility.test.tsindex c2aa5fa3b..d95cdceed 100644--- a/sdk/tests/entity-visibility.test.ts+++ b/sdk/tests/entity-visibility.test.ts@@ -20,6 +20,7 @@ describe('Entity visibility helpers', () => {// One entity, no tree: switching off walks the subtree, and an// entity with no Children is where that walk stops.valid: () => true,+ getCppRegistry: () => null,has: (_e: number, comp: any) => components.has(key(comp)),get: (_e: number, comp: any) => components.get(key(comp)),set: (_e: number, comp: any, data: any) => {diff --git a/sdk/tests/hierarchy-teardown-wasm.test.ts b/sdk/tests/hierarchy-teardown-wasm.test.tsnew file mode 100644index 000000000..f57e31e9d--- /dev/null+++ b/sdk/tests/hierarchy-teardown-wasm.test.ts@@ -0,0 +1,246 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { beforeAll, describe, expect, it, vi } from 'vitest';+import { World } from '../src/ecs/world';+import { Parent, Children } from '../src/ecs/component';+import { EntityAssetScopes } from '../src/asset/entityAssetScopes';+import type { CppRegistry, ESEngineModule } from '../src/wasm';+import type { Entity } from '../src/types';+import { HAS_WASM, loadWasmModule } from './helpers/loadWasm';++describe.skipIf(!HAS_WASM)('subtree teardown through real WASM', () => {+ let engine: ESEngineModule;+ beforeAll(async () => { engine = await loadWasmModule(); });+ function realm() {+ const registry = new engine.Registry() as unknown as CppRegistry;+ const world = new World(); world.connectCpp(registry, engine);+ const dispose = () => {+ for (const e of [...world.getAllEntities()].reverse()) if (world.valid(e)) world.despawn(e);+ world.disconnectCpp(); (registry as unknown as { delete(): void }).delete();+ };+ return { world, registry, dispose };+ }++ it('deletes a 10,000-level root and releases every entity scope in postorder', () => {+ const { world, dispose } = realm();+ const scopes = new EntityAssetScopes(), events: Entity[] = [], released = new Set<Entity>();+ const ids: Entity[] = [];+ try {+ for (let i = 0; i < 10000; i++) {+ const e = world.spawn(); ids.push(e);+ if (i) world.setParent(e, ids[i - 1]);+ scopes.ensure(world, e).add({ key: `entity:${e}`, generation: 1, value: e,+ release: () => { released.add(e); }, retain: () => null });+ }+ world.onDespawn(e => events.push(e));+ world.despawn(ids[0]);+ expect(world.entityCount()).toBe(0);+ expect(scopes.size).toBe(0);+ expect(released.size).toBe(10000);+ expect(events).toEqual([...ids].reverse());+ } finally { dispose(); }+ });++ it('reads a snapshot length once and releases its native vector', () => {+ const { world, registry, dispose } = realm();+ const original = registry.getChildren;+ try {+ const root = world.spawn(), a = world.spawn(), b = world.spawn();+ world.setParent(a, root); world.setParent(b, root);+ const size = vi.fn(() => 2), release = vi.fn();+ registry.getChildren = () => ({ entities: { size, get: (i: number) => [a, b][i], delete: release } }) as never;+ world.despawn(root);+ expect(size).toHaveBeenCalledTimes(1);+ expect(release).toHaveBeenCalledTimes(1);+ expect(world.entityCount()).toBe(0);+ } finally { registry.getChildren = original; dispose(); }+ });++ it('releases all entity receipts after an unload throws and still notifies later observers', () => {+ const { world, dispose } = realm(), scopes = new EntityAssetScopes();+ try {+ const entity = world.spawn(), released = vi.fn(), observed = vi.fn();+ const scope = scopes.ensure(world, entity);+ scope.add({ key: 'good', generation: 1, value: null, release: released, retain: () => null });+ scope.add({ key: 'bad', generation: 1, value: null, release: () => { throw new Error('bad unload'); }, retain: () => null });+ world.onDespawn(observed); world.despawn(entity);+ expect(released).toHaveBeenCalledOnce(); expect(observed).toHaveBeenCalledWith(entity);+ expect(world.entityCount()).toBe(0); expect(scopes.size).toBe(0);+ expect(scope.size).toBe(0);+ } finally { dispose(); }+ });++ it('rejects acquiring an entity scope while that entity or a queued ancestor is dying', () => {+ const { world, dispose } = realm(), scopes = new EntityAssetScopes();+ try {+ const root = world.spawn(), child = world.spawn(); world.setParent(child, root);+ const rejected: boolean[] = [];+ world.onDespawn(entity => {+ for (const candidate of [entity, root]) {+ try { scopes.ensure(world, candidate); rejected.push(false); } catch { rejected.push(true); }+ }+ });+ world.despawn(root); expect(rejected).toEqual([true, true, true, true]);+ expect(scopes.size).toBe(0); expect(world.entityCount()).toBe(0);+ expect(() => scopes.ensure(world, root)).toThrow(/destroyed|destruction/);+ } finally { dispose(); }+ });++ it('releases a failing native snapshot and aborts teardown before notifications or link changes', () => {+ const { world, registry, dispose } = realm();+ const original = registry.getChildren;+ try {+ const root = world.spawn(), a = world.spawn(), b = world.spawn();+ world.setParent(a, root); world.setParent(b, root);+ const release = vi.fn(), events: Entity[] = [], error = new Error('child snapshot failed');+ registry.getChildren = () => ({ entities: { size: () => 2,+ get: (i: number) => { if (i) throw error; return a; }, delete: release } }) as never;+ world.onDespawn(e => events.push(e));+ expect(() => world.despawn(root)).toThrow(error);+ expect(release).toHaveBeenCalledTimes(1);+ expect(events).toEqual([]);+ expect(world.entityCount()).toBe(3);+ expect(registry.getParent(a).entity).toBe(root);+ expect(registry.getParent(b).entity).toBe(root);+ expect(registry.destructionPending!(root)).toBe(false);+ const survivor = world.spawn();+ expect(world.trySetParent(root, survivor)).toBe(true);+ } finally { registry.getChildren = original; dispose(); }+ });++ it('does not emit duplicate callbacks when a callback deletes its own entity or ancestor', () => {+ const { world, dispose } = realm();+ try {+ const root = world.spawn(), child = world.spawn(); world.setParent(child, root);+ const events: Entity[] = [];+ world.onDespawn(e => { events.push(e); if (events.length < 4) { world.despawn(e); world.despawn(root); } });+ world.despawn(root);+ expect(events).toEqual([child, root]);+ expect(world.entityCount()).toBe(0);+ } finally { dispose(); }+ });++ it('joins a queued sibling deletion requested by a child callback', () => {+ const { world, dispose } = realm();+ try {+ const root = world.spawn(), a = world.spawn(), b = world.spawn();+ world.setParent(a, root); world.setParent(b, root);+ const events: Entity[] = [];+ world.onDespawn(e => { events.push(e); if (e === a) world.despawn(b); });+ world.despawn(root);+ expect(events).toEqual([a, b, root]);+ expect(world.entityCount()).toBe(0);+ } finally { dispose(); }+ });++ it('rejects attaching a new child to an ancestor currently being torn down', () => {+ const { world, dispose } = realm();+ try {+ const root = world.spawn(), child = world.spawn(); world.setParent(child, root);+ let created: Entity | undefined, accepted: boolean | undefined;+ world.onDespawn(e => { if (e === child) { created = world.spawn(); accepted = world.trySetParent(created, root); } });+ world.despawn(root);+ expect(accepted).toBe(false);+ expect(world.valid(created!)).toBe(true);+ expect(world.has(created!, Parent)).toBe(false);+ expect(world.entityCount()).toBe(1);+ } finally { dispose(); }+ });++ it('rejects moving a dying entity into a surviving parent from its callback', () => {+ const { world, dispose } = realm();+ try {+ const root = world.spawn(), child = world.spawn(), survivor = world.spawn();+ world.setParent(child, root);+ let accepted: boolean | undefined;+ world.onDespawn(e => { if (e === child) accepted = world.trySetParent(e, survivor); });+ world.despawn(root);+ expect(accepted).toBe(false);+ expect(world.entityCount()).toBe(1);+ expect(world.has(survivor, Children)).toBe(false);+ } finally { dispose(); }+ });++ it('shares teardown ownership with raw native hierarchy calls and releases reused slots', () => {+ const { world, registry, dispose } = realm();+ try {+ const root = world.spawn(), child = world.spawn(), survivor = world.spawn();+ world.setParent(child, root);+ const accepted: unknown[] = [], pending: boolean[] = [];+ world.onDespawn(e => {+ if (e !== child) return;+ pending.push(registry.destructionPending!(root), registry.destructionPending!(child));+ accepted.push(registry.setParent(child, survivor));+ const fresh = world.spawn();+ accepted.push(registry.setParent(fresh, root));+ });+ world.despawn(root);+ expect(pending).toEqual([true, true]);+ expect(accepted).toEqual([false, false]);+ expect(registry.destructionPending!(root)).toBe(false);+ expect(registry.destructionPending!(child)).toBe(false);+ const next = world.spawn();+ expect(registry.setParent(next, survivor)).toBe(true);+ expect(registry.hasChildren(survivor)).toBe(true);+ } finally { dispose(); }+ });++ it('does not release a new native reservation when a child slot is reused during its root callback', () => {+ const { world, registry, dispose } = realm();+ let fresh: Entity | undefined;+ try {+ const root = world.spawn(), child = world.spawn(); world.setParent(child, root);+ let reserved: boolean | undefined;+ world.onDespawn(e => { if (e === root) { fresh = world.spawn(); reserved = registry.reserveDestruction!(fresh); } });+ world.despawn(root);+ expect(reserved).toBe(true);+ expect(world.valid(fresh!)).toBe(true);+ expect(registry.destructionPending!(fresh!)).toBe(true);+ expect(registry.destructionPending!(child)).toBe(false);+ registry.releaseDestruction!(fresh!);+ world.despawn(fresh!);+ expect(world.entityCount()).toBe(0);+ } finally { if (fresh !== undefined) registry.releaseDestruction!(fresh); dispose(); }+ });++ it('keeps SDK hierarchy bookkeeping unchanged while a native owner holds the entity', () => {+ const { world, registry, dispose } = realm();+ let child: Entity | undefined;+ try {+ const root = world.spawn(); child = world.spawn(); world.setParent(child, root);+ expect(registry.reserveDestruction!(child)).toBe(true);+ world.removeParent(child);+ const state = { nativeParent: registry.getParent(child).entity,+ sdkHasParent: world.has(child, Parent),+ queried: world.getEntitiesWithComponents([Parent]).includes(child),+ accepted: world.trySetParent(child, root) };+ expect(state).toEqual({ nativeParent: root, sdkHasParent: true, queried: true, accepted: false });+ registry.releaseDestruction!(child);+ world.removeParent(child);+ expect(world.has(child, Parent)).toBe(false);+ expect(registry.hasParent(child)).toBe(false);+ } finally { if (child !== undefined) registry.releaseDestruction!(child); dispose(); }+ });++ it('also protects queued descendants and hierarchy component writes', () => {+ const { world, dispose } = realm();+ try {+ const root = world.spawn(), a = world.spawn(), b = world.spawn(), survivor = world.spawn();+ world.setParent(a, root); world.setParent(b, root);+ const parents: Entity[] = [];+ world.onDespawn(e => {+ if (e !== a) return;+ world.set(b, Parent, { entity: survivor });+ parents.push(world.get(b, Parent).entity);+ world.insert(survivor, Children, { entities: [b] });+ parents.push(world.get(b, Parent).entity);+ });+ world.despawn(root);+ expect(parents).toEqual([root, root]);+ expect(world.entityCount()).toBe(1);+ expect(world.has(survivor, Children)).toBe(false);+ const next = world.spawn();+ expect(world.trySetParent(next, survivor)).toBe(true);+ } finally { dispose(); }+ });+});diff --git a/sdk/tests/hot-update-rebind.test.ts b/sdk/tests/hot-update-rebind.test.tsindex 04c62c667..d464136f9 100644--- a/sdk/tests/hot-update-rebind.test.ts+++ b/sdk/tests/hot-update-rebind.test.ts@@ -89,6 +89,7 @@ const materialFake = vi.hoisted(() => {setUniform: vi.fn(),tex: vi.fn((handle: number) => ({ kind: 'tex', handle })),compileShader: vi.fn(() => 7),+ releaseShader: vi.fn(),release: vi.fn(),},};diff --git a/sdk/tests/material-asset-loader.test.ts b/sdk/tests/material-asset-loader.test.tsindex 207db4a4d..383ccb9ab 100644--- a/sdk/tests/material-asset-loader.test.ts+++ b/sdk/tests/material-asset-loader.test.ts@@ -8,28 +8,39 @@ vi.mock('../src/render/material', () => ({setUniform: vi.fn(),tex: vi.fn((handle: number) => ({ kind: 'tex', handle })),compileShader: vi.fn().mockReturnValue(7),+ releaseShader: vi.fn(),release: vi.fn(),},}));import { MaterialAssetLoader } from '../src/asset/loaders/MaterialAssetLoader';+import { MaterialShaderAssetLoader } from '../src/asset/loaders/MaterialShaderAssetLoader';import { Material } from '../src/render/material';import type { LoadContext } from '../src/asset/AssetLoader';const MAT_PATH = 'assets/materials/foo.esmaterial';const TEX_REF = 'missing.png';+function withShaderSource(ctx: LoadContext): LoadContext {+ const loader = new MaterialShaderAssetLoader();+ ctx.acquireAsset = vi.fn(async (_type: string, path: string) => {+ const value = await loader.load(path, ctx);+ return { key: path, generation: 1, value, release: () => loader.unload(value), retain: () => null };+ }) as LoadContext['acquireAsset'];+ return ctx;+}+function makeCtx(): LoadContext {const materialJson = JSON.stringify({type: 'material',shader: 'fx.esshader',properties: { mainTex: TEX_REF },});- return {+ return withShaderSource({catalog: { getBuildPath: (p: string) => p },loadText: vi.fn(async (p: string) => (p.endsWith('.esmaterial') ? materialJson : '// shader src')),acquireTexture: vi.fn().mockRejectedValue(new Error('404 not found')),- } as unknown as LoadContext;+ } as unknown as LoadContext);}describe('MaterialAssetLoader texture failure', () => {@@ -87,7 +98,7 @@ describe('MaterialAssetLoader ownership on unload', () => {return lease;}),} as unknown as LoadContext;- return { ctx, released };+ return { ctx: withShaderSource(ctx), released };}it('destroys what it made and gives back nothing it acquired', async () => {@@ -114,12 +125,12 @@ describe('MaterialAssetLoader built-in shader ref', () => {function ctxFor(shader: string): LoadContext {const materialJson = JSON.stringify({ type: 'material', shader, properties: {} });- return {+ return withShaderSource({catalog: { getBuildPath: (p: string) => p },// Only the material is ever read — a built-in shader has no file.loadText: vi.fn(async () => materialJson),loadTexture: vi.fn(),- } as unknown as LoadContext;+ } as unknown as LoadContext);}it('compiles a `builtin:<id>` shader from its in-code template, reading no shader file', async () => {diff --git a/sdk/tests/material-shader-ownership.test.ts b/sdk/tests/material-shader-ownership.test.tsnew file mode 100644index 000000000..f2a2022ab--- /dev/null+++ b/sdk/tests/material-shader-ownership.test.ts@@ -0,0 +1,123 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { Assets } from '../src/asset/Assets';+import type { MaterialResult } from '../src/asset/AssetLoader';+import { ScriptGraphAssetLoader } from '../src/asset/loaders/ScriptGraphAssetLoader';+import type { CompiledScriptGraph } from '../src/logic/ScriptGraphRunner';+import { seedEngineComponents } from '../src/ecs/component';+import '../src/logic';++const gpu = vi.hoisted(() => ({ next: 1, live: new Set<number>(), compiled: [] as Array<{ source: string; features: string[] }>, released: [] as number[] }));+vi.mock('../src/wasm/resourceManager', () => ({ requireResourceManager: () => ({}), getResourceManager: () => null }));+vi.mock('../src/render/material', () => ({ Material: {+ compileShader: vi.fn((source: string, features: string[]) => {+ gpu.compiled.push({ source, features: [...features] });+ if (source === 'invalid') return 0;+ const handle = gpu.next++; gpu.live.add(handle); return handle;+ }),+ releaseShader: vi.fn((handle: number) => { gpu.live.delete(handle); gpu.released.push(handle); }),+ createFromAsset: vi.fn(() => gpu.next++), release: vi.fn(), setUniform: vi.fn(), tex: vi.fn(),+} }));++function realm() {+ const docs: Record<string, string> = { 'fx.esshader': 'original', 'other.esshader': 'other' };+ const material = (shader: string, switches = {}) => JSON.stringify({ type: 'material', shader, properties: {}, switches });+ docs['a.esmaterial'] = material('fx.esshader'); docs['b.esmaterial'] = material('fx.esshader');+ docs['variant.esmaterial'] = material('fx.esshader', { GLOW: true }); docs['other.esmaterial'] = material('other.esshader');+ const fetchText = vi.fn(async (path: string) => { const value = docs[path]; if (value === undefined) throw new Error('missing ' + path); return value; });+ const assets = Assets.create({ module: null, backend: { resolveUrl: p => p, fetchText, fetchBinary: async () => new ArrayBuffer(0) } });+ const acquire = (ref: string) => assets.acquireTyped<MaterialResult>('material', ref);+ return { docs, assets, acquire, fetchText, material };+}++describe('material shaders use the asset ownership and source graph', () => {+ beforeEach(() => { gpu.next = 1; gpu.live.clear(); gpu.compiled.length = 0; gpu.released.length = 0; vi.clearAllMocks(); });++ it('shared materials retain one compiled program until their final receipt retires', async () => {+ const { assets, acquire } = realm(); const a = await acquire('a.esmaterial'), b = await acquire('b.esmaterial');+ expect(a.value.shaderHandle).toBe(b.value.shaderHandle); expect(gpu.compiled).toHaveLength(1);+ a.release(); expect(gpu.live.size).toBe(1); b.release(); expect(gpu.live.size).toBe(0);+ expect(gpu.released).toHaveLength(1); expect(assets.sizes().refRows).toBe(0);+ });++ it('the shared shader remains owned by every material, including a cache-hit preparation', async () => {+ const { assets, acquire } = realm(); const a = await acquire('a.esmaterial'), b = await acquire('b.esmaterial');+ for (const ref of ['a.esmaterial', 'b.esmaterial']) expect(assets.dependenciesOf('material', ref))+ .toContainEqual({ kind: 'owned', type: 'material-shader', path: 'fx.esshader' });+ a.release(); b.release();+ });++ it('shader edits compile a new era while held old materials keep their exact program', async () => {+ const { assets, docs, acquire } = realm(); const old = await acquire('a.esmaterial');+ docs['fx.esshader'] = 'changed'; assets.invalidate('fx.esshader'); await assets.assetGraphSettled();+ const fresh = await acquire('a.esmaterial'); expect(fresh.value.shaderHandle).not.toBe(old.value.shaderHandle);+ expect(gpu.compiled.at(-1)?.source).toBe('changed'); expect(gpu.live.size).toBe(2);+ old.release(); expect(gpu.live.has(fresh.value.shaderHandle)).toBe(true); expect(gpu.live.size).toBe(1);+ fresh.release(); expect(gpu.live.size).toBe(0);+ });++ it('one source read feeds distinct switch permutations and retires all programs with that source era', async () => {+ const { acquire, fetchText } = realm(); const a = await acquire('a.esmaterial'), b = await acquire('variant.esmaterial');+ expect(a.value.shaderHandle).not.toBe(b.value.shaderHandle); expect(gpu.compiled.map(c => c.features)).toEqual([[], ['GLOW']]);+ expect(fetchText.mock.calls.filter(([path]) => path === 'fx.esshader')).toHaveLength(1);+ a.release(); expect(gpu.live.size).toBe(2); b.release(); expect(gpu.live.size).toBe(0);+ });++ it('restoring missing shader source clears the material failure cooldown immediately', async () => {+ const { assets, docs, acquire } = realm(); delete docs['fx.esshader'];+ await expect(acquire('a.esmaterial')).rejects.toThrow(/missing/);+ docs['fx.esshader'] = 'restored'; assets.invalidate('fx.esshader');+ const owner = await acquire('a.esmaterial'); expect(gpu.compiled.at(-1)?.source).toBe('restored'); owner.release();+ expect(gpu.live.size).toBe(0);+ });++ it('restoring a failed compilation clears the material failure cooldown immediately', async () => {+ const { assets, docs, acquire } = realm(); docs['fx.esshader'] = 'invalid';+ await expect(acquire('a.esmaterial')).rejects.toThrow(/compile/);+ docs['fx.esshader'] = 'fixed'; assets.invalidate('fx.esshader');+ const owner = await acquire('a.esmaterial'); expect(gpu.compiled.at(-1)?.source).toBe('fixed'); owner.release();+ expect(gpu.live.size).toBe(0);+ });++ it('shader invalidation leaves another source and its compiled program untouched', async () => {+ const { assets, docs, acquire } = realm(); const a = await acquire('a.esmaterial'), b = await acquire('other.esmaterial');+ docs['fx.esshader'] = 'changed'; assets.invalidate('fx.esshader'); await assets.assetGraphSettled();+ const fresh = await acquire('a.esmaterial'); expect(gpu.compiled.filter(c => c.source === 'other')).toHaveLength(1);+ expect(fresh.value.shaderHandle).not.toBe(a.value.shaderHandle); expect(gpu.live.has(b.value.shaderHandle)).toBe(true);+ a.release(); b.release(); fresh.release(); expect(gpu.live.size).toBe(0);+ });++ it('builtin shader code has the same lease lifecycle and bypasses file ref resolvers', async () => {+ const { assets, docs, acquire, material, fetchText } = realm();+ docs['a.esmaterial'] = material('builtin:sprite-unlit');+ assets.setAssetRefResolver(ref => ref.startsWith('builtin:') ? 'wrong/' + ref : ref);+ const owner = await acquire('a.esmaterial'); expect(fetchText.mock.calls.map(([path]) => path)).toEqual(['a.esmaterial']);+ expect(gpu.compiled[0].source).toContain('#pragma shader "Sprite Unlit"'); owner.release(); expect(gpu.live.size).toBe(0);+ });++ it('wholesale release returns every shader generation and old receipts cannot free them twice', async () => {+ const { assets, acquire } = realm(); const a = await acquire('a.esmaterial'), b = await acquire('variant.esmaterial');+ assets.releaseAll(); expect(gpu.live.size).toBe(0); expect(gpu.released).toHaveLength(2);+ a.release(); b.release(); expect(gpu.released).toHaveLength(2); expect(assets.sizes().refRows).toBe(0);+ });++ it('failed shader refresh preserves a held spawn graph, and a source repair replaces it', async () => {+ seedEngineComponents();+ const { assets, docs } = realm(); assets.register(new ScriptGraphAssetLoader());+ docs['root.esprefab'] = JSON.stringify({ version: '2', name: 'shader sprite', rootEntityId: 'root',+ entities: [{ prefabEntityId: 'root', name: 'root', parent: null, children: [], visible: true,+ components: [{ type: 'Transform', data: {} }, { type: 'Sprite', data: { material: 'a.esmaterial' } }] }] });+ docs['spawn.esgraph'] = JSON.stringify({ version: '1.0', name: 'held graph',+ nodes: [{ id: 'spawn', kind: 'entity.spawn', literals: { prefab: 'root.esprefab' } }], edges: [] });+ const owner = await assets.acquireTyped('scriptgraph', 'spawn.esgraph');+ const graph = () => assets.resolveRegistryAsset<CompiledScriptGraph>('scriptgraph', 'spawn.esgraph')!;+ const old = graph(), oldShader = [...gpu.live][0];+ docs['fx.esshader'] = 'invalid'; assets.invalidate('fx.esshader'); await assets.assetGraphSettled();+ expect(graph()).toBe(old); expect(gpu.live.has(oldShader)).toBe(true);+ docs['fx.esshader'] = 'fixed'; assets.invalidate('fx.esshader'); await assets.assetGraphSettled();+ expect(graph()).not.toBe(old); expect(gpu.compiled.at(-1)?.source).toBe('fixed');+ expect(gpu.live.has(oldShader)).toBe(false); expect(gpu.live.size).toBe(1);+ owner.release(); expect(gpu.live.size).toBe(0); expect(assets.sizes().refRows).toBe(0);+ });+});diff --git a/sdk/tests/material.test.ts b/sdk/tests/material.test.tsindex d106f6809..1d701d874 100644--- a/sdk/tests/material.test.ts+++ b/sdk/tests/material.test.ts@@ -69,6 +69,39 @@ describe('Material API', () => {shutdownResourceManager();});+ describe('complete material state projection', () => {+ it('removes local overrides and keeps inheriting subsequent parent changes', () => {+ const parent = Material.create({shader:1,uniforms:{u_value:3},blendMode:BlendMode.Additive});+ const child = Material.createInstance(parent);+ Material.applyState(child,{uniforms:{u_value:9},blendMode:BlendMode.Multiply});+ Material.applyState(child,{});+ expect(Material.getUniform(child,'u_value')).toBe(3);+ expect(Material.getBlendMode(child)).toBe(BlendMode.Additive);+ expect(Material.get(child)!.uniforms.size).toBe(0);+ expect(Material.get(child)!.overrides.size).toBe(0);+ Material.setUniform(parent,'u_value',7);+ expect(Material.getUniform(child,'u_value')).toBe(7);+ });+ it('clears removed GPU values only where no inherited override replaces them', () => {+ const parent = Material.create({shader:1,uniforms:{u_value:3}});+ const inheriting = Material.createInstance(parent), overriding = Material.createInstance(parent);+ Material.setUniform(overriding,'u_value',9);mock.material_undefine.mockClear();+ Material.applyState(parent,{});+ expect(mock.material_undefine.mock.calls.map(call=>call[0])).toEqual([parent,inheriting]);+ expect(Material.getUniform(overriding,'u_value')).toBe(9);+ expect(Material.getUniform(inheriting,'u_value')).toBeUndefined();+ });+ it('flushes one complete snapshot per affected material instead of once per field', () => {+ const parent=Material.create({shader:1}),child=Material.createInstance(parent);+ mock.material_define.mockClear();mock.material_setUniform.mockClear();+ const uniforms=Object.fromEntries(Array.from({length:8},(_,i)=>[`p${i}`,i]));+ Material.applyState(parent,{uniforms,blendMode:BlendMode.Additive,depthTest:true,depthWrite:false,cull:CullMode.Back,depthBias:2});+ expect(mock.material_define).toHaveBeenCalledTimes(2);+ expect(mock.material_setUniform).toHaveBeenCalledTimes(16);+ expect(mock.material_define).toHaveBeenCalledWith(child,1,BlendMode.Additive,flags(true,false,CullMode.Back),2);+ });+ });+// =========================================================================// shutdownMaterialAPI// =========================================================================diff --git a/sdk/tests/mocks/wasm.ts b/sdk/tests/mocks/wasm.tsindex 8f3b80cab..cb9259bd4 100644--- a/sdk/tests/mocks/wasm.ts+++ b/sdk/tests/mocks/wasm.ts@@ -138,7 +138,15 @@ export function createMockModule(): MockModule {const name = prop.slice(3);return (entity: Entity) => {const data = components.get(entity)?.get(name);- return data ? JSON.parse(JSON.stringify(data)) : undefined;+ if (!data) return undefined;+ const copy = JSON.parse(JSON.stringify(data));+ if (name === 'Children') {+ const children = copy.entities as Entity[];+ // Match the owning vector returned by the actual core.+ // This mock stores JS arrays, so deletion has no heap work.+ copy.entities = { size: () => children.length, get: (i: number) => children[i], delete: () => {} };+ }+ return copy;};}if (prop.startsWith('has') && prop !== 'hasComponent') {diff --git a/sdk/tests/native-aot-ownership.test.ts b/sdk/tests/native-aot-ownership.test.tsnew file mode 100644index 000000000..3363c7b7f--- /dev/null+++ b/sdk/tests/native-aot-ownership.test.ts@@ -0,0 +1,111 @@+import {describe,it,expect,vi,afterEach} from 'vitest';+import {App} from '../src/app/app';+import {World} from '../src/ecs/world';+import {ResourceStorage,defineResource} from '../src/ecs/resource';+import {defineComponent} from '../src/ecs/component';+import {SystemRunner,defineSystem} from '../src/ecs/system';+import {Query,Mut} from '../src/ecs/query';+import {createNativeHeap} from '../src/ecs/bridge/nativeHeap';+import {installNativeAot,nativeAotBindings} from '../src/ecs/aot/installNativeAot';+import {engineAbiDigest,projectShapeDigest} from '../src/ecs/aot/abiDigest';+import type {AotManifest} from '../src/ecs/aot/AotSystems';+import type {ResourceReader} from '../src/ecs/aot/AotResources';+afterEach(()=>vi.unstubAllGlobals());++function fixture(){+ const Drift=defineComponent('NativeLeaseDrift',{x:0}),world=new World(),runner=new SystemRunner(world,new ResourceStorage());+ const buffer=new ArrayBuffer(1<<20),live=new Set<number>(),resourceOffsets=new Map<string,number>();let next=8,resets=0,installs=0,calls=0,reject=false,contract='';+ const scope:Record<string,unknown>={es_heap:()=>buffer,es_malloc:(n:number)=>{const p=next;next+=(n+7)&~7;live.add(p);return p;},es_free:(p:number)=>{expect(live.delete(p)).toBe(true);},+ es_aot_install:()=>{installs++;return reject?-1:1;},es_aot_index:()=>0,es_aot_bound:()=>true,es_aot_script_rows:()=>true,es_aot_resource:(name:string,offset:number)=>{resourceOffsets.set(name,offset);return true;},+ es_aot_run:()=>{calls++;const p=resourceOffsets.get('NativeLeaseScore');if(p!==undefined){const view=new DataView(buffer);view.setFloat64(p,view.getFloat64(p,true)+1,true);}return 0;},es_aot_reset:()=>{resets++;resourceOffsets.clear();},es_aot_contract:()=>contract};+ const manifest:AotManifest={engineAbi:engineAbiDigest(8),projectShapes:projectShapeDigest([{name:'NativeLeaseDrift',fields:['x']}]),systems:[{name:'NativeLeaseMove',symbol:'es_sys_Move',commands:false,queries:[[{comp:'NativeLeaseDrift',mut:true}]],resources:[]}]};+ const system=defineSystem([Query(Mut(Drift))],q=>{for(const [,row]of q)row.x++;},{name:'NativeLeaseMove'});+ const install=(w=world,r=runner,m=manifest,resources?:ResourceReader)=>installNativeAot({world:w,runner:r,modulePath:'module.dll',manifest:m,heap:createNativeHeap(scope)!,bindings:nativeAotBindings(scope)!,resources});+ return{Drift,world,runner,manifest,system,install,scope,live,setReject:(v:boolean)=>reject=v,setContract:(v:string)=>contract=v,counts:()=>({resets,installs,calls})};+}+describe('native compiled runtime ownership',()=>{+ it('reuses the allocation domain with existing pooled rows and retires old dispatch',()=>{+ const f=fixture(),first=f.install()!,twin=first.systems.get('NativeLeaseMove')!;const entity=f.world.spawn();f.world.insert(entity,f.Drift,{x:7});const held=f.world.get(entity,f.Drift),address=f.world.addressResolver(f.Drift)(entity);+ const second=f.install()!;first.dispose?.();expect(f.counts().resets).toBe(0);+ expect(first.dispatcherFor!(f.world).run(twin)).toBe(false);+ f.runner.run(f.system);expect(f.counts().calls).toBe(1);expect(f.world.get(entity,f.Drift)).toBe(held);expect(f.world.addressResolver(f.Drift)(entity)).toBe(address);+ second.dispose?.();second.dispose?.();f.world.releaseScriptPools();expect(f.counts().resets).toBe(1);expect(f.live.size).toBe(0);+ });+ it('revokes an older world when fresh wrappers install into the same native host',()=>{+ const f=fixture(),first=f.install()!,twin=first.systems.get('NativeLeaseMove')!,dispatch=first.dispatcherFor!(f.world);+ const other=new World(),runner=new SystemRunner(other,new ResourceStorage()),second=f.install(other,runner)!;+ expect(dispatch.run(twin)).toBe(false);expect(first.systems.size).toBe(0);first.dispose?.();expect(f.counts().resets).toBe(0);+ runner.run(f.system);expect(f.counts().calls).toBe(1);second.dispose?.();f.world.releaseScriptPools();other.releaseScriptPools();expect(f.counts().resets).toBe(1);+ });+ it('validates a refused manifest before changing the native host',()=>{+ const f=fixture(),first=f.install()!;f.setReject(false);+ expect(()=>f.install(f.world,f.runner,{...f.manifest,engineAbi:'bad'})).toThrow(/built for engine/);+ expect(f.counts().installs).toBe(1);f.runner.run(f.system);expect(f.counts().calls).toBe(1);first.dispose?.();f.world.releaseScriptPools();+ });+ it('preserves the active lease when the host refuses to load a replacement',()=>{+ const f=fixture(),first=f.install()!;f.setReject(true);expect(f.install()).toBeNull();+ f.runner.run(f.system);expect(f.counts().calls).toBe(1);expect(f.counts().resets).toBe(0);first.dispose?.();f.world.releaseScriptPools();expect(f.counts().resets).toBe(1);+ });+ it('does not select a different allocation domain when the candidate cannot load',()=>{+ const f=fixture(),first=f.install()!,otherLive=new Set<number>();let next=8;f.setReject(true);+ const heap={HEAPU8:new Uint8Array(1<<20),_malloc:(n:number)=>{const p=next;next+=(n+7)&~7;otherLive.add(p);return p;},_free:(p:number)=>{otherLive.delete(p);}};+ expect(installNativeAot({world:f.world,runner:f.runner,modulePath:'missing.dll',manifest:f.manifest,heap,bindings:nativeAotBindings(f.scope)!})).toBeNull();+ const entity=f.world.spawn();f.world.insert(entity,f.Drift,{x:7});expect(otherLive.size).toBe(0);expect(f.live.size).toBeGreaterThan(0);+ first.dispose?.();f.world.releaseScriptPools();expect(f.live.size).toBe(0);+ });+ it('reports an absent script pool after switching to a world with no rows',()=>{+ const f=fixture(),reported:Array<{name:string;rows:number}>=[];+ f.scope.es_aot_script_rows=(name:string,_sparse:number,_count:number,rows:number)=>{reported.push({name,rows});return true;};+ const first=f.install()!,entity=f.world.spawn();f.world.insert(entity,f.Drift,{x:7});f.runner.run(f.system);expect(reported.at(-1)!.rows).toBeGreaterThan(0);+ const other=new World(),runner=new SystemRunner(other,new ResourceStorage()),second=f.install(other,runner)!;runner.run(f.system);+ expect(reported.at(-1)).toEqual({name:'NativeLeaseDrift',rows:0});first.dispose?.();second.dispose?.();f.world.releaseScriptPools();other.releaseScriptPools();+ });+ it('cannot call new native code through old indices after legacy pairing refusal',()=>{+ const f=fixture(),first=f.install()!,dispatch=first.dispatcherFor!(f.world),twin=first.systems.get('NativeLeaseMove')!;f.setContract('aaaabbbbccccdddd');+ expect(()=>f.install()).toThrow(/different builds/);expect(dispatch.run(twin)).toBe(false);expect(first.systems.size).toBe(0);expect(f.counts().resets).toBe(1);+ f.runner.run(f.system);expect(f.counts().calls).toBe(0);first.dispose?.();f.world.releaseScriptPools();expect(f.counts().resets).toBe(1);+ });+ it('uses checked candidate installation to preserve the active lease on sidecar mismatch',()=>{+ const f=fixture(),contract='aaaabbbbccccdddd';f.setContract(contract);+ const checked=vi.fn((path:string,expected:string)=>expected===contract?(f.scope.es_aot_install as (p:string)=>number)(path):-1);+ f.scope.es_aot_install_checked=checked;+ const manifest={...f.manifest,moduleContract:contract},first=f.install(f.world,f.runner,manifest)!;+ expect(f.install(f.world,f.runner,{...manifest,moduleContract:'0123456789abcdef'})).toBeNull();+ expect(f.install()).toBeNull();expect(checked.mock.calls.map(c=>c[1])).toEqual([contract,'0123456789abcdef','']);+ f.runner.run(f.system);expect(f.counts().calls).toBe(1);expect(first.systems.size).toBe(1);expect(f.counts().resets).toBe(0);+ first.dispose?.();f.world.releaseScriptPools();expect(f.counts().resets).toBe(1);+ });+ it('retires mirrored resources on repeated installations without resetting the successor',()=>{+ const f=fixture(),score={value:0};+ const manifest={...f.manifest,projectShapes:projectShapeDigest([{name:'NativeLeaseDrift',fields:['x']},{name:'NativeLeaseScore',fields:['value']}]),systems:[{...f.manifest.systems[0]!,resources:[{name:'NativeLeaseScore',mut:true,fields:['value']}]}]};+ let runtime;for(let i=0;i<16;i++){+ runtime=f.install(f.world,f.runner,manifest,name=>name==='NativeLeaseScore'?score:undefined)!;+ expect(f.live.size).toBe(0);f.runner.run(f.system);expect(score.value).toBe(i+1);expect(f.live.size).toBe(1);expect(f.counts().resets).toBe(0);+ }+ runtime!.dispose?.();f.world.releaseScriptPools();expect(f.live.size).toBe(0);expect(f.counts().resets).toBe(1);+ });+ it('keeps App ownership after a refused host load and replaces live rows on success',async()=>{+ const f=fixture();for(const [key,value]of Object.entries(f.scope))vi.stubGlobal(key,value);+ const app=App.new();app.addSystem(f.system);+ try{+ expect(await app.installCompiledSystems('first.dll',f.manifest)).toBe(1);+ const entity=app.world.spawn();app.world.insert(entity,f.Drift,{x:7});await app.tick(1/60);+ f.setReject(true);expect(await app.installCompiledSystems('missing.dll',f.manifest)).toBe(0);+ expect(app.compiledSystemCount).toBe(1);await app.tick(1/60);expect(f.counts().calls).toBe(2);+ f.setReject(false);expect(await app.installCompiledSystems('next.dll',f.manifest)).toBe(1);await app.tick(1/60);expect(f.counts().calls).toBe(3);expect(f.counts().resets).toBe(0);+ }finally{app.quit({keepRenderer:true});}+ expect(f.live.size).toBe(0);expect(f.counts().resets).toBe(1);+ });+ it('cannot resurrect App dispatch when retiring native resources reenters quit',async()=>{+ const f=fixture(),app=App.new(),Score=defineResource({value:0},'NativeLeaseScore');let quit=false;+ const free=f.scope.es_free as (p:number)=>void;f.scope.es_free=(p:number)=>{free(p);if(!quit){quit=true;app.quit({keepRenderer:true});}};+ for(const [key,value]of Object.entries(f.scope))vi.stubGlobal(key,value);+ app.insertResource(Score,{value:0});app.addSystem(f.system);+ const manifest={...f.manifest,projectShapes:projectShapeDigest([{name:'NativeLeaseDrift',fields:['x']},{name:'NativeLeaseScore',fields:['value']}]),systems:[{...f.manifest.systems[0]!,resources:[{name:'NativeLeaseScore',mut:true,fields:['value']}]}]};+ try{+ await app.installCompiledSystems('first.dll',manifest);await app.tick(1/60);expect(f.live.size).toBe(1);+ await expect(app.installCompiledSystems('next.dll',manifest)).rejects.toThrow(/cancelled by App.quit/);+ expect(app.compiledSystemCount).toBe(0);expect(f.live.size).toBe(0);expect(f.counts().resets).toBe(1);+ }finally{app.quit({keepRenderer:true});}+ });+});diff --git a/sdk/tests/native-heap.test.ts b/sdk/tests/native-heap.test.tsindex e29af3392..c3d0db8e9 100644--- a/sdk/tests/native-heap.test.ts+++ b/sdk/tests/native-heap.test.ts@@ -29,6 +29,24 @@ function mockHost(bytes = 1024): Record<string, unknown> {}describe('createNativeHeap', () => {+ it('keeps allocator ownership across fresh wrappers of one host', () => {+ const host = mockHost();+ expect(createNativeHeap(host)!.allocatorIdentity).toBe(createNativeHeap(host)!.allocatorIdentity);+ });++ it('changes allocator ownership when allocation callbacks change over the same buffer', () => {+ const host = mockHost(), before = createNativeHeap(host)!;+ host[HEAP_BINDINGS.free] = () => {};+ const after = createNativeHeap(host)!;+ expect(after.HEAPU8.buffer).toBe(before.HEAPU8.buffer);+ expect(after.allocatorIdentity).not.toBe(before.allocatorIdentity);+ });++ it('changes ownership when the host arena changes', () => {+ const host = mockHost(), before = createNativeHeap(host)!;+ host[HEAP_BINDINGS.heap] = () => new ArrayBuffer(1024);+ expect(createNativeHeap(host)!.allocatorIdentity).not.toBe(before.allocatorIdentity);+ });it('is absent until the host binds all three globals', () => {expect(hasHeapBindings({})).toBe(false);expect(createNativeHeap({})).toBeNull();diff --git a/sdk/tests/native-registry.test.ts b/sdk/tests/native-registry.test.tsindex 80ba47f8f..46d26e63d 100644--- a/sdk/tests/native-registry.test.ts+++ b/sdk/tests/native-registry.test.ts@@ -36,6 +36,97 @@ function mockNativeScope(byteSize = 256): Record<string, unknown> {}describe('createNativeRegistry', () => {+ it('resolves a three-byte native component without constructing misaligned word views', () => {+ const buffer = new ArrayBuffer(3);+ const resolve = new NativeMemoryProvider({ es_Interactable_buffer: () => buffer })+ .resolveComponentHeap('Interactable')!;+ const heap = {} as Parameters<typeof resolve>[1];+ expect(resolve(1 as never, heap)).toBe(true);+ expect(heap.f32.length).toBe(0);+ expect(heap.u32.length).toBe(0);+ expect(heap.u8.length).toBe(3);+ });+ it('round-trips native owned strings and scalars without wasm-offset access', () => {+ const components = new Map<number, Record<string, unknown>>();+ const scope = {+ es_set_SpineAnimation: (e: number, data: Record<string, unknown>) => {+ components.set(e, { ...components.get(e), ...structuredClone(data) });+ },+ es_get_SpineAnimation: (e: number) => structuredClone(components.get(e)!),+ es_SpineAnimation_has: (e: number) => components.has(e),+ es_SpineAnimation_remove: (e: number) => components.delete(e),+ };+ const reg = createNativeRegistry(scope) as unknown as Record<string, Function>;+ expect(new NativeMemoryProvider(scope).resolveComponentHeap('SpineAnimation')).toBeNull();+ expect(reg.getSpineAnimation(1)).toEqual({});+ expect(components.size).toBe(0);+ const data = { skeletonPath: 'assets/骨骼.json', atlasPath: 'long/path/'.repeat(8),+ skin: 'default', animation: 'walk', timeScale: 0.5, enabled: true,+ color: { x: 0.25, y: 0.5, z: 0.75, w: 1 } };+ reg.addSpineAnimation(1, data);+ reg.addSpineAnimation(1, { timeScale: 2, animation: 'run' });+ const got = reg.getSpineAnimation(1);+ expect(got).toEqual({ ...data, timeScale: 2, animation: 'run' });+ got.skeletonPath = 'changed';+ expect(reg.getSpineAnimation(1).skeletonPath).toBe(data.skeletonPath);+ reg.removeSpineAnimation(1);+ expect(reg.hasSpineAnimation(1)).toBe(false);+ });++ it('keeps fields following a native vector and preserves lists on scalar updates', () => {+ let component: Record<string, unknown> | undefined;+ let path: unknown[] = [];+ const reg = createNativeRegistry({+ es_set_ShadowCaster2D: (_e: number, data: Record<string, unknown>) => {+ component = { ...component, ...data };+ },+ es_get_ShadowCaster2D: () => ({ size: component?.size, enabled: component?.enabled }),+ es_ShadowCaster2D_has: () => !!component,+ es_ShadowCaster2D_remove: () => { component = undefined; },+ es_ShadowCaster2D_path_set: (_e: number, value: unknown[]) => { path = structuredClone(value); },+ es_ShadowCaster2D_path_get: () => structuredClone(path),+ }) as unknown as Record<string, Function>;+ reg.addShadowCaster2D(1, { size: { x: 32, y: 48 }, enabled: true,+ path: [{ x: 1, y: 2 }, { x: 3, y: 4 }] });+ reg.addShadowCaster2D(1, { enabled: false });+ expect(reg.getShadowCaster2D(1)).toEqual({ size: { x: 32, y: 48 }, enabled: false,+ path: [{ x: 1, y: 2 }, { x: 3, y: 4 }] });+ });+ it('forwards shared destruction ownership only when the complete host contract exists', () => {+ const pending = new Set<number>();+ const reg = createNativeRegistry({+ es_reserveDestruction: (e: number) => { if (pending.has(e)) return false; pending.add(e); return true; },+ es_releaseDestruction: (e: number) => { pending.delete(e); },+ es_destructionPending: (e: number) => pending.has(e),+ });+ expect(reg.reserveDestruction!(1 as never)).toBe(true);+ expect(reg.reserveDestruction!(1 as never)).toBe(false);+ expect(reg.destructionPending!(1 as never)).toBe(true);+ reg.releaseDestruction!(1 as never);+ expect(reg.destructionPending!(1 as never)).toBe(false);+ expect(createNativeRegistry({}).reserveDestruction).toBeUndefined();+ expect(createNativeRegistry({ es_reserveDestruction: () => true }).reserveDestruction).toBeUndefined();+ });+ it('forwards the optional shared activity contract and preserves legacy hosts', () => {+ let enabled = true;+ const reg = createNativeRegistry({+ es_setEntityEnabled: (_e: number, value: boolean) => { enabled = value; return true; },+ es_isEntityEnabled: () => enabled,+ es_isEntityActive: () => enabled,+ es_hasInactiveEntities: () => !enabled,+ es_activityEpoch: () => 7,+ });+ expect(reg.setEntityEnabled!(1 as never, false)).toBe(true);+ expect(reg.isEntityEnabled!(1 as never)).toBe(false);+ expect(reg.isEntityActive!(1 as never)).toBe(false);+ expect(reg.hasInactiveEntities!()).toBe(true);+ expect(reg.activityEpoch!()).toBe(7);+ expect(createNativeRegistry({}).isEntityActive).toBeUndefined();+ });+ it.each([true, false])('forwards native hierarchy acceptance %s', (accepted) => {+ const reg = createNativeRegistry({ es_setParent: () => accepted });+ expect(reg.setParent(1 as never, 2 as never)).toBe(accepted);+ });it('round-trips a component through add / has / get / remove (embind shape)', () => {const reg = createNativeRegistry(mockNativeScope()) as unknown as Record<string, Function>;diff --git a/sdk/tests/physics-activity-wasm.test.ts b/sdk/tests/physics-activity-wasm.test.tsnew file mode 100644index 000000000..d4c78a04a--- /dev/null+++ b/sdk/tests/physics-activity-wasm.test.ts@@ -0,0 +1,76 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { beforeAll, describe, expect, it } from 'vitest';+import { App } from '../src/app/app';+import { Transform, Disabled } from '../src/ecs/component';+import { AppContext, setDefaultContext } from '../src/ecs/context';+import { RigidBody2D, BoxCollider2D } from '../src/physics/PhysicsComponents';+import { Physics2DPlugin } from '../src/physics/Physics2DPlugin';+import { Physics2DRuntime } from '../src/physics/Physics2DRuntime';+import type { PhysicsWasmModule } from '../src/physics/PhysicsModuleLoader';+import type { CppRegistry, ESEngineModule } from '../src/wasm';+import { HAS_WASM, hasSideModule, loadSideModule, loadWasmModule } from './helpers/loadWasm';++describe.skipIf(!HAS_WASM || !hasSideModule('physics'))('real Box2D hierarchy activity', () => {+ let engine: ESEngineModule;+ beforeAll(async () => { engine = await loadWasmModule(); });++ it.each(['authored', 'native', 'body'] as const)('freezes and resumes a child without losing velocity (%s)', async (path) => {+ setDefaultContext(new AppContext());+ const registry = new engine.Registry() as unknown as CppRegistry;+ const app = App.new(); app.connectCpp(registry, engine);+ const physics = await loadSideModule<PhysicsWasmModule>('physics');+ const plugin = new Physics2DPlugin('', { gravity: { x: 0, y: 0 } }, async () => physics);+ plugin.build(app);+ try {+ await app.getResource(Physics2DRuntime).initPromise;+ const world = app.world;+ const parent = world.spawn('parent');+ world.insert(parent, Transform, { position: { x: 100, y: 0, z: 0 } });+ const child = world.spawn('body');+ world.insert(child, Transform, { position: { x: 5, y: 0, z: 0 } });+ world.insert(child, RigidBody2D, { bodyType: 2 });+ world.insert(child, BoxCollider2D, {});+ world.setParent(child, parent);+ await app.stepFrames(1, 1 / 30);+ expect(physics._physics_hasBody(child)).toBe(1);+ physics._physics_setLinearVelocity(child, 2, 0);+ physics._physics_setAngularVelocity(child, 0.5);+ await app.stepFrames(3, 1 / 30);+ const position = () => world.get(child, Transform).position.x;+ const before = position();+ const enable = (active: boolean) => {+ if (path === 'body') world.update(child, RigidBody2D, rb => { rb.enabled = active; });+ else if (path === 'native') registry.setEntityEnabled!(parent, active);+ else if (active) world.remove(parent, Disabled);+ else world.insert(parent, Disabled, {});+ };+ enable(false);+ await app.stepFrames(3, 1 / 30);+ expect(position()).toBeCloseTo(before, 4);+ expect(physics._physics_hasBody(child), 'inactive bodies keep their simulation state').toBe(1);+ expect(physics._physics_getInterpolatedCount()).toBe(0);+ const pausedVelocity = physics._physics_getLinearVelocity(child);+ expect(physics.HEAPF32[pausedVelocity >> 2]).toBeCloseTo(2);+ expect(physics._physics_getAngularVelocity(child)).toBeCloseTo(0.5);+ // Edits while paused become the resumed state, including after a+ // repeated disable (which must not overwrite the stored velocity).+ physics._physics_setLinearVelocity(child, 3, 0);+ physics._physics_setAngularVelocity(child, 0.75);+ physics._physics_setBodyEnabled(child, 0);+ enable(true);+ await app.stepFrames(3, 1 / 30);+ expect(position()).toBeGreaterThan(before + 1);+ const ptr = physics._physics_getLinearVelocity(child);+ expect(physics.HEAPF32[ptr >> 2]).toBeCloseTo(3);+ expect(physics._physics_getAngularVelocity(child)).toBeCloseTo(0.75);+ enable(false);+ await app.stepFrames(1, 1 / 30);+ world.remove(child, RigidBody2D);+ await app.stepFrames(1, 1 / 30);+ expect(physics._physics_hasBody(child)).toBe(0);+ } finally {+ plugin.cleanup(); app.world.disconnectCpp(); (registry as any).delete();+ }+ });+});diff --git a/sdk/tests/plugin-build-failure.test.ts b/sdk/tests/plugin-build-failure.test.tsnew file mode 100644index 000000000..324211a21--- /dev/null+++ b/sdk/tests/plugin-build-failure.test.ts@@ -0,0 +1,79 @@+import {describe,it,expect,vi} from 'vitest';+import {App,type Plugin} from '../src/app/app';+import {defineSystem,defineSystemSet,Schedule} from '../src/ecs/system';++describe('failed plugin build ownership',()=>{+ it('cleans partial resources once while retaining the original failure',()=>{+ const app=App.new(),failure=new Error('build failed'),release=vi.fn();+ const plugin={build(){throw failure;},cleanup:release};+ expect(()=>app.addPlugin(plugin)).toThrow(failure);+ expect(release).toHaveBeenCalledTimes(1);expect(release).toHaveBeenCalledWith(app);+ app.quit({keepRenderer:true});expect(release).toHaveBeenCalledTimes(1);+ });+ it('unwinds newly installed children before their failed parent',()=>{+ const app=App.new(),parentCleanup=vi.fn(),childCleanup=vi.fn();+ const child:Plugin={name:'child',build(){},cleanup:childCleanup};+ const parent:Plugin={name:'parent',build(a){a.addPlugin(child);throw Error('parent failed');},cleanup:parentCleanup};+ expect(()=>app.addPlugin(parent)).toThrow('parent failed');+ expect(childCleanup).toHaveBeenCalledTimes(1);+ expect(childCleanup.mock.invocationCallOrder[0]).toBeLessThan(parentCleanup.mock.invocationCallOrder[0]);+ app.quit({keepRenderer:true});+ expect(parentCleanup).toHaveBeenCalledTimes(1);expect(childCleanup).toHaveBeenCalledTimes(1);+ });+ it('withdraws direct and grouped systems across schedules before the next tick',async()=>{+ const app=App.new(),failed=vi.fn(),live=vi.fn();+ app.addSystem(defineSystem([],live));await app.tick(1/60);live.mockClear();+ expect(()=>app.addPlugin({build(a){+ a.addSystem(defineSystem([],failed));+ a.addSystemSetToSchedule(Schedule.Last,defineSystemSet('failed-set',{systems:[defineSystem([],failed)]}));+ throw Error('failed');+ }})).toThrow('failed');+ await app.tick(1/60);expect(failed).not.toHaveBeenCalled();expect(live).toHaveBeenCalledTimes(1);+ app.quit({keepRenderer:true});+ });+ it('restores an existing template registration so removeSystem still removes it',async()=>{+ const app=App.new(),run=vi.fn(),template=defineSystem([],run);app.addSystem(template);+ expect(()=>app.addPlugin({build(a){a.addSystem(template);a.addSystem(template);throw Error('failed');}})).toThrow('failed');+ expect(app.removeSystem(template._id)).toBe(true);await app.tick(1/60);expect(run).not.toHaveBeenCalled();app.quit({keepRenderer:true});+ });+ it('unwinds nested systems that share the parent template',async()=>{+ const app=App.new(),run=vi.fn(),system=defineSystem([],run),child={build(a:App){a.addSystem(system);}};+ expect(()=>app.addPlugin({build(a){a.addSystem(system);a.addPlugin(child);a.addSystem(system);throw Error('failed');}})).toThrow('failed');+ await app.tick(1/60);expect(run).not.toHaveBeenCalled();+ expect(app.removeSystem(system._id)).toBe(false);app.quit({keepRenderer:true});+ });+ it('continues registration rollback when cleanup throws',async()=>{+ const app=App.new(),failure=new Error('original'),run=vi.fn(),warn=vi.spyOn(console,'error').mockImplementation(()=>{});+ try {expect(()=>app.addPlugin({build(a){a.addSystem(defineSystem([],run));throw failure;},cleanup(){throw Error('cleanup');}})).toThrow(failure);+ await app.tick(1/60);expect(run).not.toHaveBeenCalled();}+ finally{warn.mockRestore();app.quit({keepRenderer:true});}+ });+ it('can retry the same instance without stale systems or double cleanup',async()=>{+ const app=App.new(),run=vi.fn(),cleanup=vi.fn();let first=true;+ const plugin={build(a:App){a.addSystem(defineSystem([],run));if(first){first=false;throw Error('first');}},cleanup};+ expect(()=>app.addPlugin(plugin)).toThrow('first');app.addPlugin(plugin);await app.tick(1/60);+ expect(run).toHaveBeenCalledTimes(1);app.quit({keepRenderer:true});expect(cleanup).toHaveBeenCalledTimes(2);+ });+ it('does not clean a failed parent twice when its cleanup calls quit',()=>{+ const app=App.new(),cleanup=vi.fn((a?:App)=>a!.quit({keepRenderer:true}));+ expect(()=>app.addPlugin({build(){throw Error('failed');},cleanup})).toThrow('failed');+ expect(cleanup).toHaveBeenCalledTimes(1);app.quit({keepRenderer:true});expect(cleanup).toHaveBeenCalledTimes(1);+ });+ it('does not double-clean when build quits before throwing',()=>{+ const app=App.new(),cleanup=vi.fn();+ expect(()=>app.addPlugin({build(a){a.quit({keepRenderer:true});throw Error('failed');},cleanup})).toThrow('failed');+ expect(cleanup).toHaveBeenCalledTimes(1);+ });+ it('rejects new plugin installation during shutdown',()=>{+ const app=App.new(),build=vi.fn();+ app.addPlugin({build(){},cleanup(a){expect(()=>a!.addPlugin({build})).toThrow(/while App.quit/);}});+ app.quit({keepRenderer:true});expect(build).not.toHaveBeenCalled();+ });+ it('preserves plugins installed before the failed enclosing build',async()=>{+ const app=App.new(),run=vi.fn(),cleanup=vi.fn(),child={build(a:App){a.addSystem(defineSystem([],run));},cleanup};+ app.addPlugin(child);+ expect(()=>app.addPlugin({build(a){a.addPlugin(child);throw Error('failed');}})).toThrow('failed');+ expect(cleanup).not.toHaveBeenCalled();await app.tick(1/60);expect(run).toHaveBeenCalledTimes(1);+ app.quit({keepRenderer:true});expect(cleanup).toHaveBeenCalledTimes(1);+ });+});diff --git a/sdk/tests/prefab-hierarchy-scale.test.ts b/sdk/tests/prefab-hierarchy-scale.test.tsnew file mode 100644index 000000000..ce2489653--- /dev/null+++ b/sdk/tests/prefab-hierarchy-scale.test.ts@@ -0,0 +1,91 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect } from 'vitest';+import { flattenPrefab, validatePrefab, type PrefabData, type PrefabEntityData } from '../src/prefab/index';++const entity = (id: string, parent: string | null, children: string[] = []): PrefabEntityData => ({+ prefabEntityId: id, name: id, parent, children, visible: true, components: [],+});+function wide(n: number): PrefabData {+ return { version: '2', name: 'wide', rootEntityId: 'root', entities: [+ entity('root', null, Array.from({ length: n }, (_, i) => `c${i}`)),+ ...Array.from({ length: n }, (_, i) => entity(`c${i}`, 'root')),+ ] };+}+function flatten(p: PrefabData, base?: PrefabData) {+ let next = 0;+ return flattenPrefab(p, [], { allocateId: () => next++, visited: new Set(), loadPrefab: () => base ?? null });+}+function reverseChain(n: number): PrefabData {+ return { version: '2', name: 'deep', rootEntityId: '0', entities: Array.from({ length: n }, (_, i) =>+ entity(String(i), i ? String(i - 1) : null, i + 1 < n ? [String(i + 1)] : [])).reverse() };+}++describe('hierarchy authoring remains bounded by nodes and links', () => {+ for (const operation of ['flatten', 'validate'] as const) {+ it(`${operation} reads a wide authored children list linearly`, () => {+ const p = wide(1024); let reads = 0;+ p.entities[0].children = new Proxy(p.entities[0].children, {+ get(target, property, receiver) {+ if (typeof property === 'string' && /^\d+$/.test(property)) reads++;+ return Reflect.get(target, property, receiver);+ },+ });+ if (operation === 'flatten') expect(flatten(p).entities).toHaveLength(1025);+ else expect(validatePrefab(p)).toEqual([]);+ // Count authored link reads, not wall time: a membership scan per+ // child must fail even on a fast machine, while legitimate passes fit.+ expect(reads).toBeLessThan(1024 * 12);+ });+ }++ it('validates a reversed 10,000-level hierarchy without a JS call-stack limit', () => {+ expect(validatePrefab(reverseChain(10000))).toEqual([]);+ });++ it('merges a reversed deep variant with stable links and unmodified sources', () => {+ const base = reverseChain(10000), original = JSON.stringify(base);+ const variant: PrefabData = { version: '2', name: 'deep-variant', rootEntityId: '0', basePrefab: 'base', entities: [] };+ const result = flatten(variant, base);+ expect(result.entities).toHaveLength(10000);+ expect(result.entities.find(e => e.id === result.rootId)!.children).toHaveLength(1);+ expect(JSON.stringify(base)).toBe(original);+ });++ it('reports a cycle at the end of a long reversed chain rather than throwing RangeError', () => {+ const p = reverseChain(10000);+ p.entities.find(e => e.prefabEntityId === '0')!.parent = '1';+ expect(validatePrefab(p).filter(d => d.code === 'parent-cycle')).toHaveLength(1);+ });++ it('appends and replaces wide variant entries without changing base children or ordering', () => {+ const base = wide(1024), original = JSON.stringify(base);+ const replacements = base.entities.slice(1).map(e => ({ ...e, name: `updated-${e.name}` }));+ const additions = Array.from({ length: 1024 }, (_, i) => entity(`extra${i}`, 'root'));+ const variant: PrefabData = { version: '2', name: 'wide-variant', rootEntityId: 'root', basePrefab: 'base', entities: [...replacements, ...additions] };+ const result = flatten(variant, base);+ expect(result.entities).toHaveLength(2049);+ expect(result.entities.find(e => e.id === result.rootId)!.children).toHaveLength(2048);+ expect(result.entities.slice(1, 1025).every(e => e.name.startsWith('updated-'))).toBe(true);+ expect(JSON.stringify(base)).toBe(original);+ });++ it('keeps authored sibling order when nested slots appear in a different entity-array order', () => {+ const p: PrefabData = { version: '2', name: 'slots', rootEntityId: 'root', entities: [+ entity('root', null, ['right', 'left']),+ { ...entity('left', 'root', ['extra']), nestedPrefab: { prefabPath: 'leaf', overrides: [] } },+ { ...entity('right', 'root'), nestedPrefab: { prefabPath: 'leaf', overrides: [] } },+ entity('extra', 'left'),+ ] };+ const leaf: PrefabData = { version: '2', name: 'leaf', rootEntityId: '0', entities: [+ entity('0', null, ['1']), entity('1', '0'),+ ] };+ const original = JSON.stringify({ p, leaf });+ const result = flatten(p, leaf);+ const byId = new Map(result.entities.map(e => [e.prefabEntityId, e]));+ expect(byId.get('root')!.children).toEqual([byId.get('right/0')!.id, byId.get('left/0')!.id]);+ expect(byId.get('left/0')!.children).toEqual([byId.get('left/1')!.id, byId.get('extra')!.id]);+ expect(byId.get('extra')!.parent).toBe(byId.get('left/0')!.id);+ expect(JSON.stringify({ p, leaf })).toBe(original);+ });+});diff --git a/sdk/tests/prefab-owned-data.test.ts b/sdk/tests/prefab-owned-data.test.tsnew file mode 100644index 000000000..56afefd3c--- /dev/null+++ b/sdk/tests/prefab-owned-data.test.ts@@ -0,0 +1,62 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { beforeAll, describe, expect, it } from 'vitest';+import { World } from '../src/ecs/world';+import { defineComponent, Transform } from '../src/ecs/component';+import { instantiatePrefab, type PrefabData, type PrefabOverride } from '../src/prefab';+import { flattenPrefab } from '../src/prefab/flatten';+import { HAS_WASM, loadWasmModule } from './helpers/loadWasm';+import type { CppRegistry, ESEngineModule } from '../src/wasm';++const Payload = defineComponent('PrefabOwnedPayload', { payload: { values: [0] }, target: 0 },+ { entityFields: ['target'] });+const source = (): PrefabData => ({ version: '2', name: 'owned', rootEntityId: 'root', entities: [+ { prefabEntityId: 'root', name: 'root', parent: null, children: ['child'], visible: true,+ components: [{ type: 'PrefabOwnedPayload', data: {} }] },+ { prefabEntityId: 'child', name: 'child', parent: 'root', children: [], visible: true,+ components: [{ type: 'Transform', data: {} }] },+] });++describe('flattened prefab owns all mutable override values', () => {+ it('isolates property and metadata objects across flatten calls and the caller', () => {+ const prefab = source();+ const payload = { values: [1, 2] };+ const marker = { values: ['source'] };+ const overrides: PrefabOverride[] = [+ { type: 'property', prefabEntityId: 'root', componentType: 'PrefabOwnedPayload', propertyName: 'payload', value: payload },+ { type: 'metadata_set', prefabEntityId: 'root', metadataKey: 'marker', value: marker },+ ];+ const flatten = () => { let next = 0; return flattenPrefab(prefab, overrides, { allocateId: () => next++, loadPrefab: () => null }); };+ const first = flatten(); const second = flatten();+ (first.entities[0].components[0].data.payload as typeof payload).values.push(9);+ (first.entities[0].metadata!.marker as typeof marker).values.push('changed');+ expect(second.entities[0].components[0].data.payload).toEqual({ values: [1, 2] });+ expect(second.entities[0].metadata!.marker).toEqual({ values: ['source'] });+ expect(payload.values).toEqual([1, 2]); expect(marker.values).toEqual(['source']);+ });+});++describe.skipIf(!HAS_WASM)('owned prefab records retain scene-loader behavior', () => {+ let engine: ESEngineModule;+ beforeAll(async () => { engine = await loadWasmModule(); });+ it('remaps entity overrides, upgrades added legacy components and preserves source data', async () => {+ const world = new World(); world.connectCpp(new engine.Registry() as unknown as CppRegistry, engine);+ const prefab = source(); const payload = { values: [3, 4] };+ const overrides: PrefabOverride[] = [+ { type: 'property', prefabEntityId: 'root', componentType: Payload._name, propertyName: 'target', value: 'child' },+ { type: 'property', prefabEntityId: 'root', componentType: Payload._name, propertyName: 'payload', value: payload },+ { type: 'component_added', prefabEntityId: 'root', componentData: { type: 'LocalTransform', data: { position: { x: 7, y: 8, z: 0 } } } },+ ];+ const original = JSON.stringify({ prefab, overrides });+ try {+ const first = await instantiatePrefab(world, prefab, { overrides });+ const second = await instantiatePrefab(world, prefab, { overrides });+ expect(world.get(first.root, Payload).target).toBe(first.entities.get(1));+ expect(world.get(second.root, Payload).target).toBe(second.entities.get(1));+ expect(world.get(first.root, Transform).position.x).toBe(7);+ world.get(first.root, Payload).payload.values.push(12);+ expect(world.get(second.root, Payload).payload.values).toEqual([3, 4]);+ expect(JSON.stringify({ prefab, overrides })).toBe(original);+ } finally { for (const e of world.getAllEntities()) if (world.valid(e)) world.despawn(e); }+ });+});diff --git a/sdk/tests/prefab.test.ts b/sdk/tests/prefab.test.tsindex 317c4e252..2f0f22f7a 100644--- a/sdk/tests/prefab.test.ts+++ b/sdk/tests/prefab.test.ts@@ -10,15 +10,15 @@ vi.mock('../src/scene/scene', async (importOriginal) => {const actual = await importOriginal<typeof import('../src/scene/scene')>();return {...actual,- loadSceneWithAssets: vi.fn(),+ loadOwnedSceneWithAssets: vi.fn(),};});import { instantiatePrefab } from '../src/prefab';-import { loadSceneWithAssets } from '../src/scene/scene';+import { loadOwnedSceneWithAssets } from '../src/scene/scene';import { defineComponent } from '../src/ecs/component';-const mockLoadScene = vi.mocked(loadSceneWithAssets);+const mockLoadScene = vi.mocked(loadOwnedSceneWithAssets);function createMockWorld(): World {const parentMap = new Map<Entity, Entity>();diff --git a/sdk/tests/prepared-prefab-lifetime.test.ts b/sdk/tests/prepared-prefab-lifetime.test.tsnew file mode 100644index 000000000..db193f7fa--- /dev/null+++ b/sdk/tests/prepared-prefab-lifetime.test.ts@@ -0,0 +1,202 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect, vi } from 'vitest';+import { Assets } from '../src/asset/Assets';+import { Catalog } from '../src/asset/Catalog';+import { seedEngineComponents, defineComponent } from '../src/ecs/component';+import { ScriptGraphAssetLoader } from '../src/asset/loaders/ScriptGraphAssetLoader';+import type { CompiledScriptGraph } from '../src/logic/ScriptGraphRunner';+import type { Backend } from '../src/asset/Backend';+import type { PrefabData } from '../src/prefab';+import '../src/logic';++vi.mock('../src/wasm/resourceManager', () => ({+ requireResourceManager: () => ({}), getResourceManager: () => null,+ evictTextureDimensions: vi.fn(),+}));++const REF = 'root.esprefab';+const leaf = (name: string): PrefabData => ({ version: '2', name, rootEntityId: 'root', entities: [+ { prefabEntityId: 'root', name, parent: null, children: [], visible: true,+ components: [{ type: 'Transform', data: {} }] },+] });+function realm(root: PrefabData = leaf('before')) {+ seedEngineComponents();+ const docs = new Map<string, string>([[REF, JSON.stringify(root)], ['child.esprefab', JSON.stringify(leaf('child-before'))]]);+ const assets = Assets.create({ catalog: Catalog.empty(), module: null as never, backend: {+ resolveUrl: (p: string) => p,+ fetchText: async (p: string) => {+ if (p.endsWith('.esgraph')) return JSON.stringify({ version: '1.0', name: p,+ nodes: [{ id: 'spawn', kind: 'entity.spawn', literals: { prefab: REF } }], edges: [] });+ const text = docs.get(p); if (!text) throw new Error(`Missing ${p}`); return text;+ }, fetchBinary: async () => new ArrayBuffer(0),+ } as Backend });+ assets.register(new ScriptGraphAssetLoader());+ const graph = (ref: string) => assets.resolveRegistryAsset<CompiledScriptGraph>('scriptgraph', ref)!;+ return { assets, docs, graph };+}++describe('prepared prefab ownership through the real Assets and graph loaders', () => {+ it.each(['nested', 'base', 'deep-nested'] as const)('recovers an initially missing %s source without reloading its held graph', async (kind) => {+ const nested = (name: string, path: string) => {+ const root = leaf(name); root.entities[0].children = ['slot'];+ root.entities.push({ prefabEntityId: 'slot', name: 'slot', parent: 'root', children: [], visible: true,+ components: [], nestedPrefab: { prefabPath: path, overrides: [] } });+ return root;+ };+ const root = kind === 'base' ? { ...leaf('variant'), entities: [], basePrefab: 'child.esprefab' }+ : nested('parent', 'child.esprefab');+ const { assets, docs, graph } = realm(root);+ const missing = kind === 'deep-nested' ? 'grandchild.esprefab' : 'child.esprefab';+ if (kind === 'deep-nested') docs.set('child.esprefab', JSON.stringify(nested('middle', missing)));+ docs.delete(missing);+ try {+ const lease = await assets.acquireTyped('scriptgraph', 'a.esgraph');+ expect(graph('a.esgraph').prefabs.size).toBe(0);+ docs.set(missing, JSON.stringify(leaf('restored')));+ assets.invalidate(missing); await assets.assetGraphSettled();+ expect(graph('a.esgraph').prefabs.get(REF)?.scene.entities.some(e => e.name === 'restored')).toBe(true);+ expect(assets.dependenciesOf('scriptgraph', 'a.esgraph').some(e => e.kind === 'owned' && e.type === 'prepared-prefab')).toBe(true);+ lease.release();+ expect(assets.sizes()).toMatchObject({ refRows: 0, registrySlots: 0, genericCached: 0 });+ } finally { assets.releaseAll(); }+ });++ it('coalesces concurrent preparations shared by independent graphs', async () => {+ const { assets, graph } = realm();+ try {+ const leases = await Promise.all(['a.esgraph', 'b.esgraph'].map(p => assets.acquireTyped('scriptgraph', p)));+ expect(graph('a.esgraph').prefabs.get(REF)).toBe(graph('b.esgraph').prefabs.get(REF));+ leases[0].release();+ const third = await assets.acquireTyped('scriptgraph', 'c.esgraph');+ expect(graph('c.esgraph').prefabs.get(REF)).toBe(graph('b.esgraph').prefabs.get(REF));+ third.release(); leases[1].release();+ } finally { assets.releaseAll(); }+ });++ it.each([new Error('shared failure'), 'primitive failure'])('preserves rejection identity and separates concurrent failed preparations (%s)', async (reason) => {+ const nested = (path: string) => {+ const root = leaf(path); root.entities[0].children = ['slot'];+ root.entities.push({ prefabEntityId: 'slot', name: 'slot', parent: 'root', children: [], visible: true,+ components: [], nestedPrefab: { prefabPath: path, overrides: [] } });+ return root;+ };+ const { assets, docs, graph } = realm(nested('one.esprefab'));+ docs.set('other.esprefab', JSON.stringify(nested('two.esprefab')));+ const original = assets.backend.fetchText;+ assets.backend.fetchText = async (path) => {+ if (path.endsWith('.esgraph')) return JSON.stringify({ version: '1.0', name: path,+ nodes: [{ id: 'spawn', kind: 'entity.spawn', literals: { prefab: path === 'a.esgraph' ? REF : 'other.esprefab' } }], edges: [] });+ if ((path === 'one.esprefab' || path === 'two.esprefab') && !docs.has(path)) throw reason;+ return original(path);+ };+ try {+ const leases = await Promise.all(['a.esgraph', 'b.esgraph'].map(path => assets.acquireTyped('scriptgraph', path)));+ expect(assets.dependenciesOf('scriptgraph', 'a.esgraph').some(e => e.path === 'two.esprefab')).toBe(false);+ expect(assets.dependenciesOf('scriptgraph', 'b.esgraph').some(e => e.path === 'one.esprefab')).toBe(false);+ await expect(assets.acquireTyped('prepared-prefab', REF)).rejects.toBe(reason);+ await expect(assets.loadPrefab('one.esprefab')).rejects.toBe(reason);+ docs.set('one.esprefab', JSON.stringify(leaf('one-restored')));+ assets.invalidate('one.esprefab'); await assets.assetGraphSettled();+ expect(graph('a.esgraph').prefabs.get(REF)?.scene.entities.some(e => e.name === 'one-restored')).toBe(true);+ expect(graph('b.esgraph').prefabs.size).toBe(0);+ docs.set('two.esprefab', JSON.stringify(leaf('two-restored')));+ assets.invalidate('two.esprefab'); await assets.assetGraphSettled();+ expect(graph('b.esgraph').prefabs.get('other.esprefab')?.scene.entities.some(e => e.name === 'two-restored')).toBe(true);+ for (const lease of leases) lease.release();+ expect(assets.sizes()).toMatchObject({ refRows: 0, registrySlots: 0, genericCached: 0 });+ } finally { assets.releaseAll(); }+ });++ it('rebuilds a held graph from new top-level source without mutating the retired recipe', async () => {+ const { assets, docs, graph } = realm();+ try {+ const lease = await assets.acquireTyped('scriptgraph', 'a.esgraph');+ const before = graph('a.esgraph').prefabs.get(REF)!;+ docs.set(REF, JSON.stringify(leaf('after')));+ assets.invalidate(REF); await assets.assetGraphSettled();+ const after = graph('a.esgraph').prefabs.get(REF)!;+ expect(after.scene.entities[0].name).toBe('after');+ expect(after).not.toBe(before);+ expect(before.scene.entities[0].name).toBe('before');+ lease.release();+ } finally { assets.releaseAll(); }+ });++ it('propagates a nested source update through the prepared recipe to its held graph', async () => {+ const root = leaf('parent'); root.entities[0].children = ['slot'];+ root.entities.push({ prefabEntityId: 'slot', name: 'slot', parent: 'root', children: [], visible: true,+ components: [], nestedPrefab: { prefabPath: 'child.esprefab', overrides: [] } });+ const { assets, docs, graph } = realm(root);+ try {+ const lease = await assets.acquireTyped('scriptgraph', 'a.esgraph');+ expect(graph('a.esgraph').prefabs.get(REF)!.scene.entities.some(e => e.name === 'child-before')).toBe(true);+ docs.set('child.esprefab', JSON.stringify(leaf('child-after')));+ assets.invalidate('child.esprefab'); await assets.assetGraphSettled();+ expect(graph('a.esgraph').prefabs.get(REF)!.scene.entities.some(e => e.name === 'child-after')).toBe(true);+ const usable = graph('a.esgraph');+ docs.set('child.esprefab', '{broken');+ assets.invalidate('child.esprefab'); await assets.assetGraphSettled();+ expect(graph('a.esgraph')).toBe(usable);+ docs.set('child.esprefab', JSON.stringify(leaf('child-recovered')));+ assets.invalidate('child.esprefab'); await assets.assetGraphSettled();+ expect(graph('a.esgraph').prefabs.get(REF)!.scene.entities.some(e => e.name === 'child-recovered')).toBe(true);+ lease.release();+ } finally { assets.releaseAll(); }+ });++ it('holds resolved resource generations until their last recipe owner retires', async () => {+ defineComponent('PrefabMeshProbe', { mesh: 0 }, { assetFields: [{ field: 'mesh', type: 'mesh' }] });+ const root = leaf('with-resource');+ root.entities[0].components.push({ type: 'PrefabMeshProbe', data: { mesh: 'shape.esmesh' } });+ const { assets, graph } = realm(root);+ let next = 1;+ const live = new Set<number>();+ const unload = vi.fn(({ handle }: { handle: number }) => { expect(live.delete(handle)).toBe(true); });+ assets.register({ type: 'mesh', extensions: ['.esmesh'], load: async () => {+ const handle = next++; live.add(handle); return { handle };+ }, unload });+ try {+ const leases = await Promise.all(['a.esgraph', 'b.esgraph'].map(p => assets.acquireTyped('scriptgraph', p)));+ const before = graph('a.esgraph').prefabs.get(REF)!;+ expect(live.size).toBe(1);+ const beforeHandle = before.scene.entities[0].components.find(c => c.type === 'PrefabMeshProbe')!.data.mesh;+ assets.invalidate('shape.esmesh'); await assets.assetGraphSettled();+ const after = graph('a.esgraph').prefabs.get(REF)!;+ expect(after.scene.entities[0].components.find(c => c.type === 'PrefabMeshProbe')!.data.mesh).not.toBe(beforeHandle);+ expect(graph('b.esgraph').prefabs.get(REF)).toBe(after);+ expect(live.size).toBe(1);+ expect(unload).toHaveBeenCalledTimes(1);+ leases[0].release(); expect(live.size).toBe(1);+ leases[1].release(); expect(live.size).toBe(0);+ expect(unload).toHaveBeenCalledTimes(2);+ expect(assets.sizes()).toMatchObject({ refRows: 0, registrySlots: 0, genericCached: 0 });+ } finally { assets.releaseAll(); }+ });++ it('keeps an old held graph usable when changed source fails to prepare', async () => {+ const { assets, docs, graph } = realm();+ try {+ const lease = await assets.acquireTyped('scriptgraph', 'a.esgraph');+ const before = graph('a.esgraph').prefabs.get(REF)!;+ docs.set(REF, '{broken'); assets.invalidate(REF); await assets.assetGraphSettled();+ expect(graph('a.esgraph').prefabs.get(REF)).toBe(before);+ docs.set(REF, JSON.stringify(leaf('recovered')));+ assets.invalidate(REF); await assets.assetGraphSettled();+ expect(graph('a.esgraph').prefabs.get(REF)!.scene.entities[0].name).toBe('recovered');+ lease.release();+ } finally { assets.releaseAll(); }+ });++ it('retries an initially missing prefab after its source becomes available', async () => {+ const { assets, docs, graph } = realm(); docs.delete(REF);+ try {+ const lease = await assets.acquireTyped('scriptgraph', 'a.esgraph');+ expect(graph('a.esgraph').prefabs.size).toBe(0);+ docs.set(REF, JSON.stringify(leaf('now-present')));+ assets.invalidate(REF); await assets.assetGraphSettled();+ expect(graph('a.esgraph').prefabs.get(REF)!.scene.entities[0].name).toBe('now-present');+ lease.release();+ } finally { assets.releaseAll(); }+ });+});diff --git a/sdk/tests/prepared-prefab.test.ts b/sdk/tests/prepared-prefab.test.tsnew file mode 100644index 000000000..056216bdb--- /dev/null+++ b/sdk/tests/prepared-prefab.test.ts@@ -0,0 +1,90 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { beforeAll, describe, expect, it, vi } from 'vitest';+import { World } from '../src/ecs/world';+import { Transform, Parent } from '../src/ecs/component';+import { preparePrefab, spawnPrepared } from '../src/prefab/preparedPrefab';+import { instantiatePrefab, type PrefabData } from '../src/prefab';+import type { Assets } from '../src/asset/Assets';+import { HAS_WASM, loadWasmModule } from './helpers/loadWasm';+import type { ESEngineModule, CppRegistry } from '../src/wasm';++const leaf = (name: string): PrefabData => ({ version: '2', name, rootEntityId: 'root', entities: [+ { prefabEntityId: 'root', name, parent: null, children: [], visible: true,+ components: [{ type: 'Transform', data: { position: { x: 2, y: 3, z: 0 } } }] },+] });+function assetsFor(prefabs: Record<string, PrefabData>) {+ const release = vi.fn();+ const assets = {+ loadPrefab: vi.fn(async (ref: string) => ({ data: prefabs[ref] })),+ preloadSceneAssets: vi.fn(async () => ({ missing: [], scope: { releaseAll: release } })),+ resolveSceneAssetPaths: vi.fn(),+ trackSceneAssetReferences: vi.fn(),+ };+ return { assets: assets as unknown as Assets, load: assets.loadPrefab, release };+}++describe.skipIf(!HAS_WASM)('prepared prefabs use the same dependency graph as async instantiation', () => {+ let engine: ESEngineModule;+ beforeAll(async () => { engine = await loadWasmModule(); });+ const world = () => {+ const w = new World(); w.connectCpp(new engine.Registry() as unknown as CppRegistry, engine); return w;+ };++ it('preloads a nested prefab mounted in two slots once, then spawns independent copies', async () => {+ const child = leaf('child');+ const root = leaf('parent'); root.entities[0].children = ['left', 'right'];+ for (const id of ['left', 'right']) root.entities.push({ prefabEntityId: id, name: id,+ parent: 'root', children: [], visible: true, components: [],+ nestedPrefab: { prefabPath: 'child', overrides: [] } });+ const original = JSON.stringify({ root, child });+ const { assets, load, release } = assetsFor({ root, child });+ const prepared = await preparePrefab(assets, 'root');+ expect(assets.trackSceneAssetReferences).not.toHaveBeenCalled();+ expect(prepared.scene.entities.find(e => e.id === prepared.rootId)!.children).toHaveLength(2);+ expect(load.mock.calls.map(c => c[0])).toEqual(['root', 'child']);+ const w = world();+ try {+ const first = spawnPrepared(w, prepared);+ const second = spawnPrepared(w, prepared, { position: { x: 90, y: 80 } });+ expect(assets.trackSceneAssetReferences).toHaveBeenCalledTimes(2);+ expect(vi.mocked(assets.trackSceneAssetReferences).mock.calls[0][1]).toBe(first.entities);+ expect(vi.mocked(assets.trackSceneAssetReferences).mock.calls[1][1]).toBe(second.entities);+ expect(first.entities.size).toBe(3);+ for (const e of first.entities.values()) if (e !== first.root) expect(w.get(e, Parent).entity).toBe(first.root);+ expect(w.get(first.root, Transform).position.x).toBe(2);+ expect(w.get(second.root, Transform).position.x).toBe(90);+ expect(JSON.stringify({ root, child })).toBe(original);+ expect(load).toHaveBeenCalledTimes(2);+ } finally { for (const e of w.getAllEntities()) if (w.valid(e)) w.despawn(e); prepared.release(); }+ expect(release).toHaveBeenCalledOnce();+ });++ it('preloads a variant base and its nested dependencies and matches async spawn', async () => {+ const child = leaf('child');+ const base = leaf('base'); base.entities[0].children = ['slot'];+ base.entities.push({ prefabEntityId: 'slot', name: 'slot', parent: 'root', children: [],+ visible: true, components: [], nestedPrefab: { prefabPath: 'child', overrides: [] } });+ const variant: PrefabData = { ...leaf('variant'), entities: [], basePrefab: 'base',+ overrides: [{ prefabEntityId: 'root', type: 'property', componentType: 'Transform',+ propertyName: 'position', value: { x: 10, y: 20, z: 0 } }] };+ const { assets, load } = assetsFor({ variant, base, child });+ const prepared = await preparePrefab(assets, 'variant');+ expect(load.mock.calls.map(c => c[0])).toEqual(['variant', 'base', 'child']);+ const w = world();+ try {+ const first = spawnPrepared(w, prepared);+ const asyncCopy = await instantiatePrefab(w, variant, { assets });+ expect(first.entities.size).toBe(asyncCopy.entities.size);+ expect(w.get(first.root, Transform).position).toEqual(w.get(asyncCopy.root, Transform).position);+ expect(w.get(first.root, Transform).position.x).toBe(10);+ } finally { for (const e of w.getAllEntities()) if (w.valid(e)) w.despawn(e); prepared.release(); }+ });++ it('refuses a nested cycle before publishing a prepared value', async () => {+ const root = leaf('root'); root.entities[0].nestedPrefab = { prefabPath: 'root', overrides: [] };+ const { assets, load } = assetsFor({ root });+ await expect(preparePrefab(assets, 'root')).rejects.toThrow(/Circular reference/);+ expect(load.mock.calls.length).toBeLessThanOrEqual(2);+ });+});diff --git a/sdk/tests/registry-ownership.test.ts b/sdk/tests/registry-ownership.test.tsnew file mode 100644index 000000000..849a8ab37--- /dev/null+++ b/sdk/tests/registry-ownership.test.ts@@ -0,0 +1,92 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import {describe,it,expect,vi,beforeEach} from 'vitest';+import {App,createWebApp} from '../src/app/app';+import {createHeadlessApp} from '../src/runtime/webAppFactory';+import {AppContext,setDefaultContext} from '../src/ecs/context';+import {createMockModule} from './mocks/wasm';+import {setPlatform} from '../src/platform/base';+import {nodeAdapter} from '../src/platform/node';++// Ownership tests isolate graphics bootstrap; actual editor runs exercise it.+vi.mock('../src/app/corePlugin',async importOriginal=>({...await importOriginal<typeof import('../src/app/corePlugin')>(),corePlugin:{build(){}}}));+beforeEach(()=>{setDefaultContext(new AppContext());setPlatform(nodeAdapter);});++function fixture(){+ const module=createMockModule(),registry=module.getRegistry();+ const release=vi.fn(),shutdown=vi.fn();registry.delete=release;+ Object.assign(module,{Registry:function(){return registry;},initRenderer:vi.fn(()=>true),shutdownRenderer:shutdown});+ return{module,registry,release,shutdown};+}++describe('App registry ownership',()=>{+ it.each([['web',createWebApp],['headless',createHeadlessApp]] as const)('%s factory deletes its own registry once even when preserving the renderer',(_name,factory)=>{+ const f=fixture(),app=factory(f.module);+ f.release.mockImplementation(()=>expect(app.world.hasCpp).toBe(false));+ app.world.spawn();app.quit({keepRenderer:true});app.quit({keepRenderer:true});+ expect(f.release).toHaveBeenCalledTimes(1);expect(f.shutdown).not.toHaveBeenCalled();expect(app.world.entityCount()).toBe(0);+ });++ it.each([['web',createWebApp],['headless',createHeadlessApp]] as const)('%s factory releases ownership when plugin construction throws',(_name,factory)=>{+ const f=fixture(),cleanup=vi.fn(),failure=new Error('plugin build failed');+ expect(()=>factory(f.module,{plugins:[{build(){},cleanup},{build(){throw failure;}}]})).toThrow(failure);+ expect(cleanup).toHaveBeenCalledTimes(1);expect(f.release).toHaveBeenCalledTimes(1);expect(f.shutdown).not.toHaveBeenCalled();+ });++ it.each([['web',createWebApp],['headless',createHeadlessApp]] as const)('%s factory releases a registry rejected by strict binding verification',(_name,factory)=>{+ const f=fixture();Object.assign(f.registry,{addSprite:undefined});+ expect(()=>factory(f.module)).toThrow(/Sprite/);expect(f.release).toHaveBeenCalledTimes(1);+ });++ it('web initialization failure releases the registry and retains the original renderer error',()=>{+ const f=fixture(),failure=new Error('renderer failed');Object.assign(f.module,{initRenderer(){throw failure;}});+ expect(()=>createWebApp(f.module)).toThrow(failure);expect(f.release).toHaveBeenCalledTimes(1);+ });++ it.each(['default','gl-context','glx'] as const)('%s renderer refusal aborts before project plugins and releases only its registry',kind=>{+ const f=fixture(),build=vi.fn();+ Object.assign(f.module,{initRenderer:vi.fn(()=>false),initRendererWithContext:vi.fn(()=>false)});+ const renderSurface=kind==='default'?{kind:'default' as const}:{kind:'gl-context' as const,handle:73,glx:kind==='glx'};+ expect(()=>createWebApp(f.module,{renderSurface,plugins:[{build}]})).toThrow(/WebGL2 renderer initialization failed/);+ expect(build).not.toHaveBeenCalled();expect(f.release).toHaveBeenCalledTimes(1);+ expect(f.shutdown).not.toHaveBeenCalled();+ if(kind!=='default')expect(f.module.initRendererWithContext).toHaveBeenCalledWith(73);+ });++ it.each(['default','gl-context','glx'] as const)('%s successful renderer initializes plugins and preserves the shared renderer on quit',kind=>{+ const f=fixture(),build=vi.fn();+ Object.assign(f.module,{initRendererWithContext:vi.fn(()=>true)});+ const renderSurface=kind==='default'?{kind:'default' as const}:{kind:'gl-context' as const,handle:73,glx:kind==='glx'};+ const app=createWebApp(f.module,{renderSurface,plugins:[{build}]});+ expect(build).toHaveBeenCalledTimes(1);app.quit({keepRenderer:true});+ expect(f.release).toHaveBeenCalledTimes(1);expect(f.shutdown).not.toHaveBeenCalled();+ });++ it('a failed verification retains its diagnostic even when registry deletion throws',()=>{+ const f=fixture(),warn=vi.spyOn(console,'warn').mockImplementation(()=>{});Object.assign(f.registry,{addSprite:undefined});f.release.mockImplementation(()=>{throw Error('destructor failure');});+ try{expect(()=>createHeadlessApp(f.module)).toThrow(/Sprite/);expect(f.release).toHaveBeenCalledTimes(1);}+ finally{warn.mockRestore();}+ });++ it('an external borrowed registry survives quit and can connect to another App',()=>{+ const f=fixture(),app=App.new();app.connectCpp(f.registry,f.module);app.world.spawn();app.quit({keepRenderer:true});+ expect(f.release).not.toHaveBeenCalled();const next=App.new();next.connectCpp(f.registry,f.module);+ expect(next.world.valid(next.world.spawn())).toBe(true);next.quit({keepRenderer:true});expect(f.release).not.toHaveBeenCalled();+ });++ it('owned registry disposal is reentrant, attempted once, and cannot reconnect during quit',()=>{+ const f=fixture(),app=App.new(),warn=vi.spyOn(console,'warn').mockImplementation(()=>{});+ app.connectCpp(f.registry,f.module,{ownedRegistry:true});+ f.release.mockImplementation(()=>{expect(app.world.hasCpp).toBe(false);app.quit({keepRenderer:true});expect(()=>app.connectCpp(f.registry,f.module)).toThrow(/while App.quit/);throw Error('destructor failure');});+ try{app.quit({keepRenderer:true});app.quit({keepRenderer:true});expect(f.release).toHaveBeenCalledTimes(1);expect(app.world.hasCpp).toBe(false);}+ finally{warn.mockRestore();}+ });++ it('replacing a live owned registry is rejected before touching either instance',()=>{+ const f=fixture(),other=fixture(),app=App.new();app.connectCpp(f.registry,f.module,{ownedRegistry:true});+ expect(()=>app.connectCpp(other.registry,other.module)).toThrow(/before replacing/);+ expect(app.world.getCppRegistry()).toBe(f.registry);expect(f.release).not.toHaveBeenCalled();expect(other.release).not.toHaveBeenCalled();+ app.quit({keepRenderer:true});app.connectCpp(other.registry,other.module,{ownedRegistry:true});app.quit({keepRenderer:true});+ expect(f.release).toHaveBeenCalledTimes(1);expect(other.release).toHaveBeenCalledTimes(1);+ });+});diff --git a/sdk/tests/runtime-assets-persistence.test.ts b/sdk/tests/runtime-assets-persistence.test.tsindex 3cda57909..8f1202fb7 100644--- a/sdk/tests/runtime-assets-persistence.test.ts+++ b/sdk/tests/runtime-assets-persistence.test.ts@@ -73,9 +73,11 @@ describe('per-App runtime Assets persistence', () => {await loadScene(app, makeScene('a'));const first = app.getResource(AssetsResource);expect(first).not.toBe(pluginAssets);+ expect(first.getRefCounter()).not.toBeNull();await loadScene(app, makeScene('b'));expect(app.getResource(AssetsResource)).toBe(first);+ expect(app.world.getStorageSizes().despawnCallbacks).toBe(1);});it('keeps the addressable manifest across scene loads (loadGroup stays armed)', async () => {diff --git a/sdk/tests/scene-handle.test.ts b/sdk/tests/scene-handle.test.tsindex 51cf28585..475b2e21d 100644--- a/sdk/tests/scene-handle.test.ts+++ b/sdk/tests/scene-handle.test.ts@@ -35,4 +35,12 @@ describe('SceneHandle', () => {const handle = new SceneHandle([1], []);expect(handle.isReleased).toBe(false);});++ it('attempts every callback after one throws, and never retries a released scene', () => {+ const error = new Error('scene cleanup failed'), other = vi.fn();+ const handle = new SceneHandle([], [() => { throw error; }, other]);+ expect(() => handle.release()).toThrow(error);+ expect(other).toHaveBeenCalledOnce(); expect(handle.isReleased).toBe(true);+ expect(() => handle.release()).not.toThrow(); expect(other).toHaveBeenCalledOnce();+ });});diff --git a/sdk/tests/scene-prefab.test.ts b/sdk/tests/scene-prefab.test.tsindex 09ce6198b..0c1afc810 100644--- a/sdk/tests/scene-prefab.test.ts+++ b/sdk/tests/scene-prefab.test.ts@@ -97,6 +97,7 @@ function mockAssets(prefabs: Record<string, PrefabData | null>) {releaseCallbacks: [],}),resolveSceneAssetPaths: vi.fn(),+ trackSceneAssetReferences: vi.fn(),loadPrefab: vi.fn(async (ref: string) => ({ data: prefabs[ref] ?? null })),// eslint-disable-next-line @typescript-eslint/no-explicit-any} as any;diff --git a/sdk/tests/scene.test.ts b/sdk/tests/scene.test.tsindex d623e7fcc..34373c790 100644--- a/sdk/tests/scene.test.ts+++ b/sdk/tests/scene.test.ts@@ -686,6 +686,7 @@ describe('Scene', () => {return {preloadSceneAssets,resolveSceneAssetPaths,+ trackSceneAssetReferences: vi.fn(),} as any;}diff --git a/sdk/tests/script-pool-lifetime.test.ts b/sdk/tests/script-pool-lifetime.test.tsnew file mode 100644index 000000000..592ed430a--- /dev/null+++ b/sdk/tests/script-pool-lifetime.test.ts@@ -0,0 +1,82 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import {describe,it,expect,vi} from 'vitest';+import {App} from '../src/app/app';+import {defineComponent} from '../src/ecs/component';+import {ScriptPool, type PoolBlock, type PoolMemory} from '../src/ecs/ScriptPool';+import {AotContext} from '../src/ecs/aot/AotContext';+import {AotResources} from '../src/ecs/aot/AotResources';+import {AotEvents} from '../src/ecs/aot/AotEvents';++function memory(){+ const live=new Set<PoolBlock>();+ const provider:PoolMemory={alloc(bytes){const block={buffer:new ArrayBuffer(bytes),byteOffset:0,byteLength:bytes};live.add(block);return block;},release(block){if(!live.delete(block))throw Error('duplicate release');}};+ return{live,provider};+}++describe('script pool lifetime',()=>{+ it('frozen held views do not prevent entity removal or pool release',()=>{+ const m=memory(),app=App.new(),comp=defineComponent('FrozenPoolViewProbe',{value:0});+ app.world.useScriptPoolMemory(m.provider);const entity=app.world.spawn();app.world.insert(entity,comp,{value:7});+ const held=Object.freeze(app.world.get(entity,comp));app.quit({keepRenderer:true});+ expect(app.world.entityCount()).toBe(0);expect(m.live.size).toBe(0);expect(held.value).toBe(7);+ });+ it('retired AOT arenas, resources and event payloads cannot allocate again',()=>{+ const m=memory(),context=new AotContext(m.provider),resources=new AotResources(m.provider,()=>({value:7}),new Map([['Probe',['value']]])),events=new AotEvents(m.provider,()=>({read:()=>[{value:7}],send:()=>{}}));+ resources.addressOf('Probe');events.rowsFor('Probe',['value']);+ context.build(new Uint32Array(),0,new Uint32Array(),new Uint32Array(),[]);+ expect(m.live.size).toBe(3);context.dispose();resources.dispose();events.dispose();expect(m.live.size).toBe(0);+ expect(()=>resources.addressOf('Probe')).toThrow(/disposed/);expect(()=>events.rowsFor('Probe',['value'])).toThrow(/disposed/);+ expect(()=>context.build(new Uint32Array(),0,new Uint32Array(),new Uint32Array(),[])).toThrow(/disposed/);expect(m.live.size).toBe(0);+ });+ it('quit releases current row, sparse and owner blocks after growth',()=>{+ const m=memory(),app=App.new(),comp=defineComponent('QuitPoolProbe',{value:0});+ app.world.useScriptPoolMemory(m.provider);+ for(let i=0;i<70;i++)app.world.insert(app.world.spawn(),comp,{value:i});+ expect(m.live.size).toBe(3);app.quit({keepRenderer:true});expect(m.live.size).toBe(0);+ app.quit({keepRenderer:true});expect(m.live.size).toBe(0);+ });+ it('a deleted row view cannot mutate the next entity that reuses its slot',()=>{+ const pool=new ScriptPool([{name:'value',kind:'number'}],1);+ const old=pool.put(1 as never,{value:0},{value:7}).view;+ pool.put(3 as never,{value:0},{value:4});+ expect(pool.get(1 as never)).toBe(old);+ pool.delete(1 as never);const next=pool.put(2 as never,{value:0},{value:9}).view;+ old.value=100;expect(next.value).toBe(9);expect(old.value).toBe(100);+ });+ it('disposing a pool detaches held views and refuses reuse of freed storage',()=>{+ const m=memory(),pool=new ScriptPool([{name:'value',kind:'number'}],1,m.provider);+ const view=pool.put(1 as never,{value:0},{value:7}).view;+ pool.dispose();expect(m.live.size).toBe(0);expect(view.value).toBe(7);+ view.value=99;expect(view.value).toBe(99);expect(pool.address(1 as never)).toBeUndefined();+ expect(()=>pool.put(2 as never,{value:0})).toThrow(/disposed/);+ expect(()=>pool.span()).toThrow(/disposed/);pool.dispose();expect(m.live.size).toBe(0);+ });+ it.each([2,3])('rolls back partial construction when allocation %i fails',failAt=>{+ const m=memory(),alloc=m.provider.alloc;let calls=0;+ m.provider.alloc=bytes=>{if(++calls===failAt)throw Error('OOM');return alloc(bytes);};+ expect(()=>new ScriptPool([{name:'value',kind:'number'}],1,m.provider)).toThrow('OOM');expect(m.live.size).toBe(0);+ });+ it('failed growth gives back its partial block and leaves existing rows usable',()=>{+ const m=memory(),pool=new ScriptPool([{name:'value',kind:'number'}],1,m.provider);+ const view=pool.put(0 as never,{value:0},{value:7}).view,alloc=m.provider.alloc;let calls=0;+ m.provider.alloc=bytes=>{if(++calls===2)throw Error('OOM');return alloc(bytes);};+ expect(()=>pool.put(1 as never,{value:0},{value:9})).toThrow('OOM');expect(m.live.size).toBe(3);expect(view.value).toBe(7);+ m.provider.alloc=alloc;expect(pool.put(1 as never,{value:0},{value:9}).view.value).toBe(9);pool.dispose();expect(m.live.size).toBe(0);+ });+ it('an address resolver follows a newly created pool after quit',()=>{+ const m=memory(),app=App.new(),comp=defineComponent('ResetPoolAddressProbe',{value:0});+ app.world.useScriptPoolMemory(m.provider);const first=app.world.spawn();app.world.insert(first,comp,{value:7});+ const address=app.world.addressResolver(comp);expect(address(first)).toBeDefined();app.quit({keepRenderer:true});expect(address(first)).toBeUndefined();+ app.world.useScriptPoolMemory(m.provider);const next=app.world.spawn();app.world.insert(next,comp,{value:9});+ expect(address(next)).toBeDefined();app.quit({keepRenderer:true});expect(m.live.size).toBe(0);+ });+ it('quit survives reentrant and throwing frees while releasing every block once',()=>{+ const warn=vi.spyOn(console,'warn').mockImplementation(()=>{}),m=memory(),app=App.new(),comp=defineComponent('QuitFreeFailureProbe',{value:0});+ app.world.useScriptPoolMemory(m.provider);app.world.insert(app.world.spawn(),comp,{value:7});+ const release=m.provider.release;let calls=0;+ m.provider.release=block=>{release(block);app.quit({keepRenderer:true});if(++calls===1)throw Error('release failure');};+ try{app.quit({keepRenderer:true});expect(calls).toBe(3);expect(m.live.size).toBe(0);app.quit({keepRenderer:true});expect(calls).toBe(3);}+ finally{warn.mockRestore();}+ });+});diff --git a/sdk/tests/skeletal-activity-scale.test.ts b/sdk/tests/skeletal-activity-scale.test.tsnew file mode 100644index 000000000..1b1f0870d--- /dev/null+++ b/sdk/tests/skeletal-activity-scale.test.ts@@ -0,0 +1,82 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/** @brief Measure 1000 resident skeletons and check inactive frames cross no event ABI. */+import { describe, it, expect } from 'vitest';+import { readFileSync, writeFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { App } from '../src/app/app';+import { AppContext, setDefaultContext } from '../src/ecs/context';+import { Transform, SpineAnimation } from '../src/ecs/component';+import { SkeletalEnableMirror } from '../src/skeletal/enableSync';+import { SpineManager } from '../src/spine/SpineManager';+import type { SpineWasmModule } from '../src/spine/SpineModuleLoader';+import type { SpineEraBinding } from '../src/spine/prepareSpine';+import type { CppRegistry } from '../src/wasm';+import { HAS_WASM, hasSideModule, loadSideModule, loadWasmModule } from './helpers/loadWasm';++describe.skipIf(!HAS_WASM || !hasSideModule('spine38'))('resident skeletal activity costs', () => {+ it('retains 1000 instances while stopping event ABI polling for an inactive hierarchy', async () => {+ setDefaultContext(new AppContext());+ const engine = await loadWasmModule();+ const registry = new engine.Registry() as unknown as CppRegistry;+ const app = App.new(); app.connectCpp(registry, engine);+ const world = app.world;+ const raw = await loadSideModule<SpineWasmModule>('spine38');+ const cwrap = raw.cwrap.bind(raw);+ let polls = 0;+ raw.cwrap = (name, result, args) => {+ const fn = cwrap(name, result, args);+ return name === 'spine_getEventCount' ? (...values) => { polls++; return fn(...values); } : fn;+ };+ const manager = new SpineManager(engine, new Map([['3.8', async () => raw]]));+ const root = world.spawn(); world.insert(root, Transform, {});+ const fixture = resolve(__dirname, '../benchmarks/fixtures/spine/spineboy-38');+ const era: SpineEraBinding = {+ id: 'scale-spineboy', culling: { kind: 'unknown' },+ pair: { skeleton: 'spineboy.skel', atlas: 'spineboy.atlas' },+ value: {+ skelData: new Uint8Array(readFileSync(resolve(fixture, 'spineboy-pro.skel'))),+ atlasText: readFileSync(resolve(fixture, 'spineboy.atlas'), 'utf8'), isBinary: true,+ textures: new Map([['spineboy.png', { glId: 3, w: 1024, h: 1024 }]]),+ }, retain: () => ({ release: () => {} }),+ };+ try {+ for (let i = 0; i < 1000; i++) {+ const entity = world.spawn(); world.insert(entity, Transform, {});+ world.setParent(entity, root); world.insert(entity, SpineAnimation, {});+ expect(await manager.loadEntity(entity, era, registry)).toBe('3.8');+ manager.setAnimation(entity, 'walk', true);+ }+ const mirror = new SkeletalEnableMirror(SpineAnimation);+ const isActive = (e: Parameters<typeof world.isEntityActive>[0]) => world.isEntityActive(e);+ const frame = () => {+ const a = performance.now(); mirror.sync(world, manager, isActive);+ const b = performance.now(); manager.updateAnimations(1 / 60, isActive);+ const c = performance.now(); manager.collectAllEvents(isActive);+ const d = performance.now(); return [b - a, c - b, d - c, d - a];+ };+ const measure = () => {+ for (let i = 0; i < 3; i++) frame();+ polls = 0;+ const samples = Array.from({ length: 11 }, frame);+ const stageNames = ['enableMirror', 'pose', 'events', 'total'];+ return { pollsPerFrame: polls / 11, stages: Object.fromEntries(stageNames.map((name, i) => {+ const values = samples.map(v => v[i]).sort((a, b) => a - b);+ return [name, { minMs: values[0], medianMs: values[5] }];+ })) };+ };+ const active = measure();+ registry.setEntityEnabled!(root, false);+ const inactive = measure();+ registry.setEntityEnabled!(root, true);+ const resumed = measure();+ const report = { entities: 1000, gpuMeasured: false, active, inactive, resumed };+ const phase = process.env.ES_SKELETAL_AUDIT_PHASE;+ if (phase === 'before' || phase === 'after') writeFileSync(resolve(__dirname, `../../output/engine-audit-2026-10-11/skeletal-scale-${phase}.json`), JSON.stringify(report, null, 2));+ expect([...manager.boundEntities()]).toHaveLength(1000);+ expect(active.pollsPerFrame).toBe(1000);+ expect(inactive.pollsPerFrame).toBe(0);+ expect(resumed.pollsPerFrame).toBe(1000);+ } finally { manager.dispose(); registry.delete(); }+ }, 120_000);+});diff --git a/sdk/tests/skeletal-activity-wasm.test.ts b/sdk/tests/skeletal-activity-wasm.test.tsnew file mode 100644index 000000000..64fff1af4--- /dev/null+++ b/sdk/tests/skeletal-activity-wasm.test.ts@@ -0,0 +1,100 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/** @brief Skeletal side modules obey hierarchy activity without losing their instances. */+import { beforeAll, describe, expect, it } from 'vitest';+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { App } from '../src/app/app';+import { AppContext, setDefaultContext } from '../src/ecs/context';+import { Disabled, Transform, SpineAnimation, DragonBonesAnimation } from '../src/ecs/component';+import { SpineManager } from '../src/spine/SpineManager';+import { SpinePlugin, SpineEvents } from '../src/spine/SpinePlugin';+import type { SpineWasmModule } from '../src/spine/SpineModuleLoader';+import { DragonBonesManager } from '../src/dragonbones/DragonBonesManager';+import { DragonBonesPlugin } from '../src/dragonbones/DragonBonesPlugin';+import { DragonBonesModuleController } from '../src/dragonbones/DragonBonesController';+import { wrapDragonBonesModule, type DragonBonesWasmModule } from '../src/dragonbones/DragonBonesModuleLoader';+import type { CppRegistry, ESEngineModule } from '../src/wasm';+import type { RenderPipeline } from '../src/render/renderPipeline';+import { HAS_WASM, hasSideModule, loadSideModule, loadWasmModule } from './helpers/loadWasm';++describe.skipIf(!HAS_WASM || !hasSideModule('spine38') || !hasSideModule('dragonbones'))('real skeletal hierarchy activity', () => {+ let engine: ESEngineModule;+ beforeAll(async () => { engine = await loadWasmModule(); });++ it.each(['spine-authored', 'spine-native', 'dragonbones-authored', 'dragonbones-native'])('%s freezes updates and mesh extraction independently of manual enable', async (scenario) => {+ setDefaultContext(new AppContext());+ const registry = new engine.Registry() as unknown as CppRegistry;+ let submissions = 0;+ const core = Object.create(engine) as ESEngineModule;+ core.renderer_submitSkeletalBatchByEntity = () => { submissions++; };+ core.renderer_submitSkeletalBatchByEntityEx = core.renderer_submitSkeletalBatchByEntity;+ const app = App.new(); app.connectCpp(registry, core);+ const callbacks: Array<(r: { _cpp: CppRegistry }) => void> = [];+ app.setPipeline({ addPreFlushCallback: (cb: (r: { _cpp: CppRegistry }) => void) => callbacks.push(cb) } as unknown as RenderPipeline);+ const world = app.world;+ const parent = world.spawn('parent'); world.insert(parent, Transform, {});+ const child = world.spawn('skeleton'); world.insert(child, Transform, {}); world.setParent(child, parent);+ let manager: SpineManager | DragonBonesManager;+ let cleanup: () => void;+ if (scenario.startsWith('spine')) {+ const raw = await loadSideModule<SpineWasmModule>('spine38');+ manager = new SpineManager(core, new Map([['3.8', async () => raw]]));+ const plugin = new SpinePlugin(manager); plugin.build(app); cleanup = () => plugin.cleanup();+ world.insert(child, SpineAnimation, {});+ const assets = resolve(__dirname, '../benchmarks/fixtures/spine/spineboy-38');+ expect(await manager.loadEntity(child, {+ id: 'activity-spineboy', culling: { kind: 'unknown' },+ pair: { skeleton: 'spineboy.skel', atlas: 'spineboy.atlas' },+ value: {+ skelData: new Uint8Array(readFileSync(resolve(assets, 'spineboy-pro.skel'))),+ atlasText: readFileSync(resolve(assets, 'spineboy.atlas'), 'utf8'), isBinary: true,+ textures: new Map([['spineboy.png', { glId: 3, w: 1024, h: 1024 }]]),+ }, retain: () => ({ release: () => {} }),+ }, registry)).toBe('3.8');+ manager.setAnimation(child, 'walk', true);+ } else {+ const raw = await loadSideModule<DragonBonesWasmModule>('dragonbones');+ manager = new DragonBonesManager(new DragonBonesModuleController(raw, wrapDragonBonesModule(raw)));+ const plugin = new DragonBonesPlugin(manager); plugin.build(app); cleanup = () => plugin.cleanup();+ world.insert(child, DragonBonesAnimation, {});+ const assets = resolve(__dirname, 'assets/dragonbones');+ const handle = manager.loadSkeleton(new Uint8Array(readFileSync(resolve(assets, 'DragonBoy_ske.json'))), readFileSync(resolve(assets, 'DragonBoy_tex.json'), 'utf8'), 'activity-dragon');+ manager.setAtlasTexture(handle, 3);+ expect(manager.addEntity(child, handle, { armature: 'Dragon', animation: 'walk', assetKey: 'activity-dragon' })).toBe(true);+ }+ try {+ const frame = async () => { await app.tick(1 / 60); for (const cb of callbacks) cb({ _cpp: registry }); };+ const enable = (on: boolean) => {+ if (scenario.endsWith('native')) registry.setEntityEnabled!(parent, on);+ else if (on) world.remove(parent, Disabled);+ else world.insert(parent, Disabled, {});+ };+ await frame(); expect(submissions).toBeGreaterThan(0);+ const frozen = manager.getBounds(child); expect(frozen).not.toBeNull();+ enable(false); expect(world.isEntityActive(child)).toBe(false);+ submissions = 0;+ for (let i = 0; i < 20; i++) await frame();+ expect(manager.getBounds(child), 'inactive hierarchy advanced the pose').toEqual(frozen);+ expect(submissions, 'inactive hierarchy extracted meshes').toBe(0);+ expect([...manager.boundEntities()]).toContain(child);+ enable(true); await frame();+ expect(submissions).toBeGreaterThan(0);+ expect(manager.getBounds(child)).not.toEqual(frozen);+ manager.setEnabled(child, false);+ const manualFrozen = manager.getBounds(child);+ enable(false); await frame(); enable(true); submissions = 0;+ for (let i = 0; i < 5; i++) await frame();+ expect(manager.getBounds(child), 'hierarchy resume overwrote manual disable').toEqual(manualFrozen);+ expect(submissions).toBe(0);+ manager.setEnabled(child, true); await frame(); expect(submissions).toBeGreaterThan(0);+ if (manager instanceof SpineManager) {+ manager.enableEvents(child); enable(false);+ manager.setAnimation(child, 'walk', true); await frame();+ expect(app.getResource(SpineEvents).events).toEqual([]);+ enable(true); await frame();+ expect(app.getResource(SpineEvents).events.some(e => e.entity === child && e.type === 'start')).toBe(true);+ }+ } finally { cleanup!(); registry.delete(); }+ });+});diff --git a/sdk/tests/skeletal-enable-sync.test.ts b/sdk/tests/skeletal-enable-sync.test.tsindex b2712683e..4542e31be 100644--- a/sdk/tests/skeletal-enable-sync.test.ts+++ b/sdk/tests/skeletal-enable-sync.test.ts@@ -35,6 +35,22 @@ function fakeManager(entities: number[]) {}describe('SkeletalEnableMirror', () => {+ it('reads new inactive bindings once and catches up before resuming', () => {+ const mirror = new SkeletalEnableMirror(SpineAnimation);+ const manager = fakeManager([1]);+ let enabled = false;+ let reads = 0;+ const world = { tryGet: () => { reads++; return { enabled } as never; } };+ mirror.sync(world, manager, () => false);+ expect(manager.pushed).toEqual([[1, false]]);+ enabled = true;+ mirror.sync(world, manager, () => false);+ expect(reads).toBe(1);+ mirror.sync(world, manager, () => true);+ expect(reads).toBe(2);+ expect(manager.pushed).toEqual([[1, false], [1, true]]);+ });+it('pushes the field on the first sync an entity appears in', () => {const m = new SkeletalEnableMirror(SpineAnimation);const mgr = fakeManager([1, 2]);diff --git a/sdk/tests/skeletal-preview-color.test.ts b/sdk/tests/skeletal-preview-color.test.tsnew file mode 100644index 000000000..916b8c12e--- /dev/null+++ b/sdk/tests/skeletal-preview-color.test.ts@@ -0,0 +1,27 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, expect, it, vi } from 'vitest';+import { SkeletalPreview } from '../src/render/skeletalPreview';++describe('skeletal preview color source', () => {+ it.each([2, 3])('preserves PMA color for blend %s without guessing from blend', blendMode => {+ let next = 64;+ const legacy = vi.fn(() => 1);+ const submit = vi.fn(() => 1);+ const core = {+ HEAPU8: new Uint8Array(4096),+ _malloc: (size: number) => { const p = next; next += size; return p; },+ _free: vi.fn(),+ renderer_createSkeletalPreview: () => 9,+ renderer_submitSkeletalPreviewBatch: legacy,+ renderer_submitSkeletalPreviewBatchEx: submit,+ };+ const preview = SkeletalPreview.create(core, 128, 128)!;+ expect(preview.submit({ vertices: new Uint8Array(96), indices: new Uint8Array(6),+ vertexCount: 3, indexCount: 3, textureId: 7, blendMode,+ transform: new Float32Array(16), premultipliedColor: true })).toBe(true);+ expect(submit).toHaveBeenCalledOnce();+ expect(submit.mock.calls[0].at(-1)).toBe(true);+ expect(legacy).not.toHaveBeenCalled();+ });+});diff --git a/sdk/tests/skeletal-submit.test.ts b/sdk/tests/skeletal-submit.test.tsindex 1904a4287..db7acf5e6 100644--- a/sdk/tests/skeletal-submit.test.ts+++ b/sdk/tests/skeletal-submit.test.ts@@ -36,6 +36,19 @@ const oneBatch = (cb: (v: Uint8Array, i: Uint8Array, vc: number, ic: number, tex};describe('handing a posed skeleton to the engine', () => {+ it.each([2, 3])('carries PMA color independently of blend mode %s', blend => {+ const { core } = mockCore();+ const submit = vi.fn();+ core.renderer_submitSkeletalBatchByEntityEx = submit;+ submitEntityMeshes(core, {}, 5 as Entity, PROPS, cb => {+ cb(new Uint8Array(64), new Uint8Array(6), 2, 3, 7, blend, true);+ });+ expect(submit).toHaveBeenCalledOnce();+ expect(submit.mock.calls[0].at(-1)).toBe(true);+ expect(submit.mock.calls[0][6]).toBe(blend);+ expect(core.renderer_submitSkeletalBatchByEntity).not.toHaveBeenCalled();+ });+it('submits no material when the caller names none', () => {const { core, submits } = mockCore();expect(submitEntityMeshes(core, {}, 5 as Entity, PROPS, oneBatch)).toBe(true);diff --git a/sdk/tests/spine-abi-cost.test.ts b/sdk/tests/spine-abi-cost.test.tsindex 722a2b934..358a35f3a 100644--- a/sdk/tests/spine-abi-cost.test.ts+++ b/sdk/tests/spine-abi-cost.test.ts@@ -203,11 +203,11 @@ describe.skipIf(!HAS_ASSETS)('what a spine entity costs per frame', () => {runtime.dispose();});- it('reading a pose back is 2 + 3 per batch, per entity, per frame', () => {+ it('reading a pose back includes a color-source query per batch', () => {// The pose itself is two more, which this counts but does not attribute// to the readback: they are the frame's other half.// The number a batch ABI would change: today the walk asks how many- // batches, then three questions per batch, and allocates twice per batch+ // batches, then four questions per batch, and allocates twice per batch// — all of it per entity.const { module, crossings } = counting(module38);const runtime = new SpineRuntime('3.8', module);@@ -227,12 +227,13 @@ describe.skipIf(!HAS_ASSETS)('what a spine entity costs per frame', () => {expect(c.get('spine_getMeshBatchVertexCount')).toBe(batches);expect(c.get('spine_getMeshBatchIndexCount')).toBe(batches);expect(c.get('spine_getMeshBatchData')).toBe(batches);+ expect(c.get('spine_getMeshBatchColorPremultiplied')).toBe(batches);// Two allocations per batch (vertices + indices) plus the meta pair.expect(c.get('_malloc')).toBe(1 + batches * 2);- // The formula, for the wall: 5 fixed + 7 per batch, per entity, per+ // The formula, for the wall: 5 fixed + 8 per batch, per entity, per// frame. It was 4 while a pose was one call. A batch ABI is a change to// THIS; so was splitting the pose, deliberately.- expect(crossings.total()).toBe(5 + 7 * batches);+ expect(crossings.total()).toBe(5 + 8 * batches);runtime.dispose();});diff --git a/sdk/tests/spine-events-wasm.test.ts b/sdk/tests/spine-events-wasm.test.tsnew file mode 100644index 000000000..1813c801d--- /dev/null+++ b/sdk/tests/spine-events-wasm.test.ts@@ -0,0 +1,54 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect } from 'vitest';+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { WASM_DIR, hasSideModule } from './helpers/loadWasm';+import { SpineModuleController } from '../src/spine/SpineController';+import { wrapSpineModule, type SpineWasmModule } from '../src/spine/SpineModuleLoader';++for (const version of ['2.1', '3.8', '4.1', '4.2', '4.3']) {+ const moduleName = 'spine' + version.replace('.', '');+ describe.skipIf(!hasSideModule(moduleName))('Spine ' + version + ' event ownership', () => {+ it('retains separate queues across updates, decodes packed integers, and unloads safely', async () => {+ const factory = (await import(resolve(WASM_DIR, moduleName + '.js'))).default;+ const raw: SpineWasmModule = await factory({ wasmBinary: readFileSync(resolve(WASM_DIR, moduleName + '.wasm')) });+ const controller = new SpineModuleController(raw, wrapSpineModule(raw));+ const root = resolve(__dirname, '../../third_party/spine-runtimes-' + version);+ const dir = version === '2.1' ? resolve(root, 'spine-c/data') : resolve(root, 'examples/spineboy/export');+ const json = JSON.parse(readFileSync(resolve(dir, version === '2.1' ? 'spineboy.json' : 'spineboy-pro.json'), 'utf8'));+ json.events = { ...json.events, audit: { int: -7, float: 0.125, string: 'marker' } };+ json.animations.walk.events = [{ time: 0.05, name: 'audit' }];+ const handle = controller.loadSkeleton(new TextEncoder().encode(JSON.stringify(json)), readFileSync(resolve(dir, 'spineboy.atlas'), 'utf8'), false);+ expect(handle).toBeGreaterThan(0);+ const a = controller.createInstance(handle);+ const b = controller.createInstance(handle);+ try {+ controller.enableEvents(a);+ controller.enableEvents(b);+ expect(controller.play(a, 'walk', false, 2)).toBe(true);+ expect(controller.play(b, 'run', false, 1)).toBe(true);+ controller.update(a, 0.1);+ controller.update(b, 0.1);+ const aEvents = controller.collectEvents(a);+ const bEvents = controller.collectEvents(b);+ expect(aEvents).toContainEqual(expect.objectContaining({ type: 0, track: 2, animationName: 'walk' }));+ expect(aEvents).toContainEqual(expect.objectContaining({ type: 5, track: 2, intValue: -7, floatValue: 0.125, eventName: 'audit', stringValue: 'marker' }));+ expect(bEvents).toContainEqual(expect.objectContaining({ type: 0, track: 1, animationName: 'run' }));+ expect(bEvents.every(event => event.animationName === 'run')).toBe(true);+ expect(controller.collectEvents(a)).toEqual([]);+ controller.update(a, 10);+ controller.update(b, 10);+ expect(controller.collectEvents(a)).toContainEqual(expect.objectContaining({ type: 3, track: 2, animationName: 'walk' }));+ controller.destroyInstance(a);+ expect(controller.collectEvents(b)).toContainEqual(expect.objectContaining({ type: 3, track: 1, animationName: 'run' }));+ controller.unloadSkeleton(handle);+ expect(controller.collectEvents(b)).toEqual([]);+ } finally {+ controller.destroyInstance(a);+ controller.destroyInstance(b);+ controller.unloadSkeleton(handle);+ }+ }, 30_000);+ });+}diff --git a/sdk/tests/spine-pma-color-wasm.test.ts b/sdk/tests/spine-pma-color-wasm.test.tsnew file mode 100644index 000000000..97d7cc2d5--- /dev/null+++ b/sdk/tests/spine-pma-color-wasm.test.ts@@ -0,0 +1,37 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect, beforeAll } from 'vitest';+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { WASM_DIR, hasSideModule } from './helpers/loadWasm';+import { SpineModuleController } from '../src/spine/SpineController';+import { wrapSpineModule } from '../src/spine/SpineModuleLoader';++describe.skipIf(!hasSideModule('spine42'))('PMA tint source survives every Spine blend mode', () => {+ let controller: SpineModuleController;+ const dir = resolve(__dirname, '../../third_party/spine-runtimes-4.2/examples/spineboy/export');+ beforeAll(async () => {+ const factory = (await import(resolve(WASM_DIR, 'spine42.js'))).default;+ const raw = await factory({ wasmBinary: readFileSync(resolve(WASM_DIR, 'spine42.wasm')) });+ controller = new SpineModuleController(raw, wrapSpineModule(raw));+ });+ it.each(['normal', 'additive', 'multiply', 'screen'])('reports straight and PMA color for %s', mode => {+ const index = ['normal', 'additive', 'multiply', 'screen'].indexOf(mode);+ for (const pma of [false, true]) {+ const json = JSON.parse(readFileSync(resolve(dir, 'spineboy-pro.json'), 'utf8'));+ for (const slot of json.slots) slot.blend = mode;+ const atlas = readFileSync(resolve(dir, pma ? 'spineboy-pma.atlas' : 'spineboy.atlas'), 'utf8');+ const skeleton = controller.loadSkeleton(JSON.stringify(json), atlas, false);+ expect(skeleton).toBeGreaterThan(0);+ const instance = controller.createInstance(skeleton);+ try {+ controller.setAtlasPageTexture(skeleton, 0, 7, 1024, 256);+ controller.update(instance, 0);+ const states: Array<[number, boolean | undefined]> = [];+ controller.forEachMeshBatch(instance, (_v, _i, _vc, _ic, _tex, blend, premultiplied) => states.push([blend, premultiplied]));+ expect(states.length).toBeGreaterThan(0);+ expect(states.every(([blend, premultiplied]) => blend === (pma && index < 2 ? index + 4 : index) && premultiplied === pma)).toBe(true);+ } finally { controller.destroyInstance(instance); controller.unloadSkeleton(skeleton); }+ }+ });+});diff --git a/sdk/tests/spine-runtime-binding.test.ts b/sdk/tests/spine-runtime-binding.test.tsindex b9bc22c67..ddbcc163a 100644--- a/sdk/tests/spine-runtime-binding.test.ts+++ b/sdk/tests/spine-runtime-binding.test.ts@@ -44,6 +44,23 @@ async function bind(}describe('one entity is posed by at most one runtime', () => {+ it.each(['4.1', '4.2'])('keeps manual disable when rebinding to %s', async (version) => {+ const { manager } = managerWithVersions();+ const entity = 7 as Entity;+ try {+ manager.observe(true);+ await bind(manager, entity, '4.1', 'hero#1');+ manager.updateAnimations(1 / 60);+ expect(manager.diagnostics().pose.logicalUpdates).toBe(1);+ manager.setEnabled(entity, false);+ await bind(manager, entity, version, 'hero#2');+ manager.updateAnimations(1 / 60);+ expect(manager.diagnostics().pose.logicalUpdates).toBe(0);+ manager.setEnabled(entity, true);+ manager.updateAnimations(1 / 60);+ expect(manager.diagnostics().pose.logicalUpdates).toBe(1);+ } finally { manager.dispose(); }+ });it('moving to another spine version leaves nothing behind in the old one', async () => {// The runtime it moves TO can only remove its own entities, and the one// it came from is never told: what stays there is posed and submitteddiff --git a/sdk/tests/spine-scene-diagnostics.test.ts b/sdk/tests/spine-scene-diagnostics.test.tsindex ed4e1a9fa..0a05b769a 100644--- a/sdk/tests/spine-scene-diagnostics.test.ts+++ b/sdk/tests/spine-scene-diagnostics.test.ts@@ -338,7 +338,7 @@ describe('what a frame moved, not only what it decided', () => {expect(d.bytes).toEqual({ wasmRead: 3000, coreWrite: 6000, scratchAllocated: 9000 });expect(d.abi).toEqual({pose: 6, world: 9, batchCount: 18, vertexCount: 21, indexCount: 24,- batchData: 12, malloc: 27, free: 33, submit: 15,+ batchData: 12, batchColor: 0, malloc: 27, free: 33, submit: 15,});expect(d.frame, 'the newest frame any runtime reached').toBe(2);expect(d.runtimes.map(t => t.total.last)).toEqual([1, 2]);diff --git a/sdk/tests/ui-quick-click-focus.test.ts b/sdk/tests/ui-quick-click-focus.test.tsindex fba6067e5..1dc019d3c 100644--- a/sdk/tests/ui-quick-click-focus.test.ts+++ b/sdk/tests/ui-quick-click-focus.test.ts@@ -12,6 +12,11 @@ import { Focusable, FocusManager } from '../src/ui/input/focusable';import { focusPlugin } from '../src/ui/input/focus';import { uiInteractionPlugin } from '../src/ui/input/interaction';import { UIEvents } from '../src/ui/core/events';+import { setEntityActive } from '../src/ecs/entityUtils';+import { inputRouter } from '../src/input/inputRouter';+import { onGestureClick } from '../src/ui/input/gestureClick';+import { getComponent } from '../src/ecs/component';+import { inspectableTypes } from '../src/runtime/worldSnapshot';const hit = vi.hoisted(() => ({ entity: null as number | null }));vi.mock('../src/ui/util/ui-pick', () => ({screenToUiWorld: () => ({ x: 0, y: 0 }), screenToUiLayout: () => ({ x: 0, y: 0 }),@@ -19,6 +24,64 @@ vi.mock('../src/ui/util/ui-pick', () => ({}));describe('quick pointer focus through real interaction projection', () => {+ it.each(['control', 'surface'])('clears capture when the %s is switched off', async (reason) => {+ const { app } = bootMockApp(); const input = new InputState();+ const overlay = { active: true, surfaceH: 600 } as any;+ app.insertResource(Input, input);+ app.insertResource(UICameraInfo, { valid: false } as any);+ app.insertResource(ScreenOverlay, overlay);+ app.insertResource(UILayoutGeneration, { generation: 0 });+ uiInteractionPlugin.build(app); flushPendingRegistrations(app);+ expect(getComponent('UIInteraction')).toBe(UIInteraction);+ const entity = app.world.spawn();+ app.world.insert(entity, Interactable, { enabled: true }); hit.entity = entity;+ input.noteMouseDown(0); await app.tick(1 / 60); input.clearFrameState();+ expect(app.world.get(entity, UIInteraction).pressed).toBe(true);+ expect(inspectableTypes(app.world, entity)).not.toContain('UIInteraction');+ expect(inspectableTypes(app.world, entity, true)).toContain('UIInteraction');+ if (reason === 'control') app.world.update(entity, Interactable, data => { data.enabled = false; });+ else overlay.active = false;+ await app.tick(1 / 60);+ expect(app.world.get(entity, UIInteraction)).toMatchObject({ hovered: false, pressed: false, justPressed: false, justReleased: false });+ expect(input.pointerOverUI).toBe(false);+ if (reason === 'control') app.world.update(entity, Interactable, data => { data.enabled = true; });+ else overlay.active = true;+ await app.tick(1 / 60);+ expect(app.world.get(entity, UIInteraction)).toMatchObject({ hovered: true, pressed: false });+ });+ it('cancels disabled parent capture and focus, and re-hits a stationary pointer on restore', async () => {+ const { app } = bootMockApp();+ const input = new InputState();+ app.insertResource(Input, input);+ app.insertResource(UICameraInfo, { valid: false } as any);+ app.insertResource(ScreenOverlay, { active: true, surfaceH: 600 } as any);+ app.insertResource(UILayoutGeneration, { generation: 0 });+ uiInteractionPlugin.build(app); focusPlugin.build(app); flushPendingRegistrations(app);+ const parent = app.world.spawn(), entity = app.world.spawn();+ app.world.setParent(entity, parent);+ app.world.insert(entity, Interactable, { enabled: true });+ app.world.insert(entity, Focusable, {});+ hit.entity = entity;+ const gesture = vi.fn(); onGestureClick(app.world, entity, gesture);+ const clicked = vi.fn(); app.getResource(UIEvents).on(entity, 'click', clicked);+ input.noteMouseDown(0); await app.tick(1 / 60); input.clearFrameState();+ expect(app.world.get(entity, UIInteraction)).toMatchObject({ hovered: true, pressed: true });+ expect(app.getResource(FocusManager).focusedEntity).toBe(entity);+ setEntityActive(app.world, parent, false);+ // The host's release can run before another frame observes the switch.+ inputRouter.dispatchPointerUp(0); expect(gesture).not.toHaveBeenCalled();+ await app.tick(1 / 60);+ expect(app.world.get(entity, UIInteraction)).toMatchObject({ hovered: false, pressed: false, justPressed: false, justReleased: false });+ expect(app.getResource(FocusManager).focusedEntity).toBeNull();+ expect(app.world.get(entity, Focusable).isFocused).toBe(false);+ expect(input.pointerOverUI).toBe(false);+ setEntityActive(app.world, parent, true);+ await app.tick(1 / 60);+ expect(app.world.get(entity, UIInteraction)).toMatchObject({ hovered: true, pressed: false });+ input.noteMouseUp(0); await app.tick(1 / 60);+ expect(clicked).not.toHaveBeenCalled();+ expect(gesture).not.toHaveBeenCalled();+ });it('preserves press/release edges when the whole click ends before a frame', async () => {const { app } = bootMockApp();const input = new InputState();diff --git a/sdk/tests/ui-text-submit.test.ts b/sdk/tests/ui-text-submit.test.tsindex 16cc9c3ea..7c73f519b 100644--- a/sdk/tests/ui-text-submit.test.ts+++ b/sdk/tests/ui-text-submit.test.ts@@ -24,10 +24,10 @@ describe.skipIf(!HAS_WASM)('REARCH_GUI P1.3a: text batch submit binding', () =>it('the TS wrapper no-ops safely without a render frame (guards, no throw)', async () => {const { submitTextBatch } = await import('../src/ui/text/submit');- const verts = new Float32Array(4 * 8); // one quad+ const verts = new Float32Array(4 * 9); // one quad, including SDF biasconst idx = new Uint16Array([0, 1, 2, 0, 2, 3]);const xform = new Float32Array(16); xform[0] = xform[5] = xform[10] = xform[15] = 1;// No active render frame headless → binding guards (g_renderFrame null) → no draw, no throw.- expect(() => submitTextBatch(module, verts, idx, 1, xform, 0, 0, 0)).not.toThrow();+ expect(() => submitTextBatch(module, verts, idx, 1, xform, 0, 0, 0, false)).not.toThrow();});});diff --git a/sdk/tests/wasm-pool-memory.test.ts b/sdk/tests/wasm-pool-memory.test.tsindex fae0bde80..bd4892d6f 100644--- a/sdk/tests/wasm-pool-memory.test.ts+++ b/sdk/tests/wasm-pool-memory.test.ts@@ -63,6 +63,43 @@ class FakeModule implements WasmHeap {}describe('rows on the engine heap', () => {+ it('held numeric and boolean fields remain live after foreign heap growth without refresh', () => {+ const mod = new FakeModule(), pool = new ScriptPool(poolShape(DEFAULTS)!, 4, new WasmPoolMemory(mod));+ const held = pool.put(e(1), DEFAULTS, {speed: 7, enabled: false}).view;+ mod.grow();+ expect(held['speed']).toBe(7);expect(held['enabled']).toBe(false);+ mod.grow();held['speed'] = 42;held['enabled'] = true;+ const heap = new Float64Array(mod.memory.buffer), address = pool.address(e(1))!;+ expect(heap[address / 8]).toBe(42);expect(heap[address / 8 + 3]).toBe(1);+ pool.dispose();+ });++ it('compiled addresses and sparse spans survive foreign growth before any component read', () => {+ const mod = new FakeModule(), pool = new ScriptPool(poolShape(DEFAULTS)!, 4, new WasmPoolMemory(mod));+ pool.put(e(1), DEFAULTS, {speed: 7});const address = pool.address(e(1)), span = pool.span();+ mod.grow();+ expect(pool.address(e(1))).toBe(address);expect(pool.span()).toEqual(span);+ expect(pool.sparseTable[entityIndex(e(1))]).toBe(1);expect(pool.buffer[0]).toBe(7);+ pool.dispose();+ });++ it('existing writes and new rows work after foreign growth without needing pool expansion', () => {+ const mod = new FakeModule(), pool = new ScriptPool(poolShape(DEFAULTS)!, 4, new WasmPoolMemory(mod));+ pool.put(e(1), DEFAULTS, {speed: 7});mod.grow();+ pool.put(e(1), DEFAULTS, {speed: 42});pool.put(e(2), DEFAULTS, {speed: 9});+ expect(pool.get(e(1))!['speed']).toBe(42);expect(pool.get(e(2))!['speed']).toBe(9);+ expect(pool.sparseTable[entityIndex(e(2))]).toBe(2);pool.dispose();+ });++ it('one pool allocating on the same heap cannot detach another pool view', () => {+ const mod = new FakeModule(1, true), memory = new WasmPoolMemory(mod);+ const first = new ScriptPool(poolShape(DEFAULTS)!, 4, memory), held = first.put(e(1), DEFAULTS, {speed: 7}).view;+ const second = new ScriptPool(poolShape(DEFAULTS)!, 4, memory);+ expect(held['speed']).toBe(7);held['speed'] = 42;+ expect(new Float64Array(mod.memory.buffer)[first.address(e(1))! / 8]).toBe(42);+ first.dispose();second.dispose();+ });+it('allocates at a wasm address, and an address is that address', () => {const mod = new FakeModule();const pool = new ScriptPool(poolShape(DEFAULTS)!, 4, new WasmPoolMemory(mod));diff --git a/sdk/tests/world-transform-authority.test.ts b/sdk/tests/world-transform-authority.test.tsindex 3d4f7c1c8..052a9d5c3 100644--- a/sdk/tests/world-transform-authority.test.ts+++ b/sdk/tests/world-transform-authority.test.ts@@ -17,6 +17,22 @@ describe.skipIf(!HAS_WASM)('world transform authority', () => {let module: ESEngineModule;beforeAll(async () => { module = await loadWasmModule(); });+ it('composes a legal hierarchy beyond the former 256-level cutoff', () => {+ const registry = new module.Registry() as unknown as CppRegistry;+ const app = App.new(); app.connectCpp(registry, module);+ const world = app.world;+ let parent: ReturnType<typeof world.spawn> | undefined;+ for (let i = 0; i < 600; ++i) {+ const child = world.spawn();+ world.insert(child, Transform, { position: { x: 1, y: 0, z: 0 } });+ if (parent !== undefined) world.setParent(child, parent);+ parent = child;+ }+ world.ensureTransformsComposed();+ expect(world.get(parent!, Transform).worldPosition.x).toBe(600);+ world.disconnectCpp(); (registry as any).delete();+ });+/** A parent at 100 and a child 5 to its right, on a server with no renderer. */function parented() {const app = App.new();diff --git a/src/esengine/animation/TweenSystem.cpp b/src/esengine/animation/TweenSystem.cppindex bca37edf2..a9b0effb4 100644--- a/src/esengine/animation/TweenSystem.cpp+++ b/src/esengine/animation/TweenSystem.cpp@@ -31,6 +31,8 @@ void TweenSystem::update(ecs::Registry& registry, f32 deltaTime) {}continue;}+ if (!registry.isEntityActive(entity) || !registry.isEntityActive(tween.target_entity)) continue;+ f32 tweenDelta = deltaTime;if (tween.delay > 0.0f) {tween.delay -= deltaTime;@@ -44,11 +46,11 @@ void TweenSystem::update(ecs::Registry& registry, f32 deltaTime) {applyValue(registry, tween, tween.from_value);continue;}- deltaTime = -tween.delay;+ tweenDelta = -tween.delay;tween.delay = 0.0f;}- tween.elapsed += deltaTime;+ tween.elapsed += tweenDelta;f32 rawT = (tween.duration > 0.0f)? glm::clamp(tween.elapsed / tween.duration, 0.0f, 1.0f): 1.0f;diff --git a/src/esengine/aot/AotDispatcher.hpp b/src/esengine/aot/AotDispatcher.hppindex e439329d3..463fa402d 100644--- a/src/esengine/aot/AotDispatcher.hpp+++ b/src/esengine/aot/AotDispatcher.hpp@@ -27,8 +27,10 @@#pragma once#include <cstdint>+#include <optional>#include <span>#include <string>+#include <utility>#include <vector>#include "esengine/aot/AotHost.hpp"@@ -47,17 +49,32 @@ public:*/bool install(const char* path, std::uint64_t expected,const ComponentLookup& components, const ResourceLookup& resources,- std::string* why = nullptr, const CandidateLookup& candidates = {}) {- reset();- if (!module_.open(path, expected, why)) return false;- components_ = components;- resources_ = resources;- candidates_ = candidates;- for (const EsSystemDecl& decl : module_.systems()) {- names_.push_back(decl.name != nullptr ? decl.name : "");- bound_.push_back(::esengine::aot::bind(decl, components, resources, candidates));+ std::string* why = nullptr, const CandidateLookup& candidates = {},+ std::optional<std::uint64_t> expectedContract = std::nullopt) {+ // Prepare a complete replacement before touching the live module. The+ // staged owner closes its library on refusal or a lookup/allocation throw.+ Dispatcher next;+ if (!next.module_.open(path, expected, why)) return false;+ if (expectedContract && next.module_.contract() != 0 && next.module_.contract() != *expectedContract) {+ if (why) *why = "module and manifest are from different builds";+ return false;}- arenas_ = std::vector<CallArena>(bound_.size());+ next.components_ = components;+ next.resources_ = resources;+ next.candidates_ = candidates;+ for (const EsSystemDecl& decl : next.module_.systems()) {+ next.names_.push_back(decl.name != nullptr ? decl.name : "");+ next.bound_.push_back(::esengine::aot::bind(decl, next.components_, next.resources_, next.candidates_));+ }+ next.arenas_ = std::vector<CallArena>(next.bound_.size());+ // These swaps cannot throw; next now owns and retires the old runtime.+ std::swap(module_, next.module_);+ names_.swap(next.names_);+ bound_.swap(next.bound_);+ arenas_.swap(next.arenas_);+ components_.swap(next.components_);+ resources_.swap(next.resources_);+ candidates_.swap(next.candidates_);return true;}@@ -113,7 +130,10 @@ public:bound_[i] = ::esengine::aot::bind(module_.systems()[i], components_, resources_, candidates_);}if (bound_[i].fn == nullptr) return {};- return runBound(bound_[i], candidates, resources, arenas_[i], world);+ bool runnable = false;+ const auto commands = runBound(bound_[i], candidates, resources, arenas_[i], world, &runnable);+ if (!runnable) bound_[i].fn = nullptr;+ return commands;}/** Entities that system's last {@link run} covered. See CallArena. */diff --git a/src/esengine/aot/AotHost.hpp b/src/esengine/aot/AotHost.hppindex fb4d0bf21..510754a6a 100644--- a/src/esengine/aot/AotHost.hpp+++ b/src/esengine/aot/AotHost.hpp@@ -116,6 +116,9 @@ inline bool narrows(std::span<const QuerySpec> queries) {return true;}+struct BoundSystem;+using ResourceLookup = std::function<void*(const char*)>;+/*** The scratch a call needs. Held by the caller so the vectors keep their* capacity between frames; every `run` overwrites it and nothing survives.@@ -144,9 +147,14 @@ private:friend std::span<const EsCmd> run(SystemFn, std::span<const std::uint32_t>,std::span<const QuerySpec>, std::span<void* const>,CallArena&, WorldStamp);+ friend std::span<const EsCmd> runBound(const BoundSystem&, std::span<const std::uint32_t>,+ const ResourceLookup&, CallArena&, WorldStamp, bool*);std::vector<es_addr_t> rows_;std::vector<EsQueryRows> queries_;std::vector<es_addr_t> resources_;+ std::vector<void*> resourcePointers_;+ std::vector<std::size_t> starts_;+ std::vector<std::uint32_t> counts_;std::vector<EsCmd> cmds_;std::uint32_t count_ = 0;std::uint32_t walked_ = 0;@@ -215,8 +223,10 @@ inline std::span<const EsCmd> run(SystemFn fn,// Offsets first, addresses after: one vector holding every query's rows// moves under the first query's pointer as the second grows, and the ctx// has to point at something that will still be there during the call.- std::vector<std::size_t> starts(queries.size());- std::vector<std::uint32_t> counts(queries.size(), 0);+ auto& starts = arena.starts_;+ auto& counts = arena.counts_;+ starts.resize(queries.size());+ counts.assign(queries.size(), 0);for (std::size_t q = 0; q < queries.size(); ++q) {starts[q] = arena.rows_.size();const auto& comps = queries[q].comps;@@ -338,7 +348,6 @@ inline CandidatesOf fromMovingOwners(const RowSpan* slot) {* what the artifact carries — it cannot know this host's type ids.*/using ComponentLookup = std::function<ComponentAt(const char*)>;-using ResourceLookup = std::function<void*(const char*)>;/*** The third question, and the only optional one: who holds that component.@@ -396,11 +405,18 @@ inline std::span<const EsCmd> runBound(const BoundSystem& bound,std::span<const std::uint32_t> fallback,const ResourceLookup& resources,CallArena& arena,- WorldStamp world = {}) {+ WorldStamp world = {}, bool* runnable = nullptr) {+ if (runnable) *runnable = false;if (bound.fn == nullptr) return {};- std::vector<void*> addresses;+ auto& addresses = arena.resourcePointers_;+ addresses.clear();addresses.reserve(bound.resourceNames.size());- for (const char* name : bound.resourceNames) addresses.push_back(resources(name));+ for (const char* name : bound.resourceNames) {+ void* address = resources(name);+ if (address == nullptr) return {};+ addresses.push_back(address);+ }+ if (runnable) *runnable = true;return run(bound.fn, fallback, bound.queries, addresses, arena, world);}diff --git a/src/esengine/aot/AotModule.hpp b/src/esengine/aot/AotModule.hppindex 070c651b8..76acc1183 100644--- a/src/esengine/aot/AotModule.hpp+++ b/src/esengine/aot/AotModule.hpp@@ -57,26 +57,27 @@ public:* another engine.*/bool open(const char* path, std::uint64_t expected, std::string* why = nullptr) {- close();const auto fail = [why](const char* msg) { if (why != nullptr) *why = msg; return false; };- handle_ = core::openLibrary(path);- if (handle_ == nullptr) return fail("the platform could not load it");+ Module next;+ next.handle_ = core::openLibrary(path);+ if (next.handle_ == nullptr) return fail("the platform could not load it");- const auto* hash = static_cast<const std::uint64_t*>(core::librarySymbol(handle_, "es_abi_hash"));- const auto* count = static_cast<const std::uint32_t*>(core::librarySymbol(handle_, "es_system_count"));- const auto* decls = static_cast<const EsSystemDecl*>(core::librarySymbol(handle_, "es_systems"));+ const auto* hash = static_cast<const std::uint64_t*>(core::librarySymbol(next.handle_, "es_abi_hash"));+ const auto* count = static_cast<const std::uint32_t*>(core::librarySymbol(next.handle_, "es_system_count"));+ const auto* decls = static_cast<const EsSystemDecl*>(core::librarySymbol(next.handle_, "es_systems"));if (hash == nullptr || count == nullptr || decls == nullptr) {- close();// A wasm module is built WITHOUT the declaration table on purpose;// handing one to a linking host lands exactly here.return fail("it carries no declaration table — built for a host that shares memory?");}if (*hash != expected) {- close();return fail("it was built against a different engine or address width");}- systems_ = std::span<const EsSystemDecl>(decls, *count);- contract_ = readContract_();+ next.systems_ = std::span<const EsSystemDecl>(decls, *count);+ next.contract_ = next.readContract_();+ // The candidate owns its handle until every check passed. Failed loads+ // leave this owner's declarations and their library alive.+ *this = std::move(next);return true;}diff --git a/src/esengine/bindings/EngineState.hpp b/src/esengine/bindings/EngineState.hppindex 2552ded1b..cf9991b0f 100644--- a/src/esengine/bindings/EngineState.hpp+++ b/src/esengine/bindings/EngineState.hpp@@ -9,6 +9,7 @@ namespace esengine {struct EngineState {int webgl_context = 0;+ bool owns_webgl_context = false;bool initialized = false;bool immediate_draw_active = false;// Off by default: glGetError is a SYNCHRONOUS round-trip to the GPU process,diff --git a/src/esengine/bindings/GeometryBindings.cpp b/src/esengine/bindings/GeometryBindings.cppindex af9bfc162..b6def786c 100644--- a/src/esengine/bindings/GeometryBindings.cpp+++ b/src/esengine/bindings/GeometryBindings.cpp@@ -287,7 +287,11 @@ void draw_meshWithUniforms(u32 geometryHandle, u32 shaderHandle, uintptr_t transcase 10: {i32 slot = static_cast<i32>(uniforms[idx++]);u32 textureId = static_cast<u32>(uniforms[idx++]);- g_device->bindTexture(static_cast<u32>(slot), TextureHandle{textureId});+ // Material.tex carries a resource identity, just like the reflected+ // material store. Resolve at draw time so device re-uploads behind+ // the same resource handle do not leave cached streams stale.+ const Texture* texture = g_resourceManager->getTexture(resource::TextureHandle{textureId});+ g_device->bindTexture(static_cast<u32>(slot), texture ? texture->handle() : TextureHandle::Invalid);shader->setUniform(name, slot);break;}diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cppindex 29fdc5d64..1f0259bf5 100644--- a/src/esengine/bindings/RendererBindings.cpp+++ b/src/esengine/bindings/RendererBindings.cpp@@ -18,6 +18,7 @@#include "../renderer/frame/RenderStage.hpp"#include "../renderer/draw/ImmediateDraw.hpp"#include "../renderer/draw/CustomGeometry.hpp"+#include "../renderer/draw/TextVertexFormat.hpp"#include "../resource/ResourceManager.hpp"#include "../ecs/Registry.hpp"#include "../ecs/TransformSystem.hpp"@@ -95,10 +96,21 @@ void renderer_submitSkeletalBatchByEntity(u32 textureId, i32 blendMode,u32 entity, f32 skelScale, bool flipX, bool flipY,i32 layer, f32 depth, u32 materialId+) {+ renderer_submitSkeletalBatchByEntityEx(registry, verticesPtr, vertexCount, indicesPtr, indexCount, textureId, blendMode, entity, skelScale, flipX, flipY, layer, depth, materialId, blendMode == 4 || blendMode == 5);+}++void renderer_submitSkeletalBatchByEntityEx(+ ecs::Registry& registry,+ uintptr_t verticesPtr, i32 vertexCount,+ uintptr_t indicesPtr, i32 indexCount,+ u32 textureId, i32 blendMode,+ u32 entity, f32 skelScale, bool flipX, bool flipY,+ i32 layer, f32 depth, u32 materialId, bool premultipliedColor) {if (!g_initialized || !g_renderFrame) return;const Entity ent = Entity::fromRaw(entity);- if (!registry.has<ecs::Transform>(ent)) return;+ if (!registry.isEntityActive(ent) || !registry.has<ecs::Transform>(ent)) return;auto& t = registry.get<ecs::Transform>(ent);t.ensureDecomposed();@@ -120,7 +132,7 @@ void renderer_submitSkeletalBatchByEntity(if (!vertices || !indices) return;g_renderFrame->submitSkeletalBatch(vertices, vertexCount, indices, indexCount,- textureId, blendMode, &model[0][0], ent, layer, depth, materialId);+ textureId, blendMode, &model[0][0], ent, layer, depth, materialId, premultipliedColor);}/**@@ -169,8 +181,7 @@ void renderer_submitTextBatch() {if (!g_initialized || !g_renderFrame) return;if (vertexCount < 0 || indexCount < 0) return;- // Text vertex format is x,y,u,v,r,g,b,a (8 floats per vertex).- auto* vertices = boundarySpan<f32>(verticesPtr, static_cast<u64>(vertexCount) * 8, "renderer_submitTextBatch.vertices");+ auto* vertices = boundarySpan<f32>(verticesPtr, static_cast<u64>(vertexCount) * TEXT_VERTEX_FLOATS, "renderer_submitTextBatch.vertices");auto* indices = boundarySpan<u16>(indicesPtr, static_cast<u64>(indexCount), "renderer_submitTextBatch.indices");auto* transform = boundarySpan<f32>(transformPtr, 16, "renderer_submitTextBatch.transform");if (!vertices || !indices || !transform) return;@@ -1145,7 +1156,7 @@ u32 gl_checkErrors(const std::string& context) {}i32 registry_getCanvasEntity(ecs::Registry& registry) {- auto view = registry.view<ecs::Canvas>();+ auto view = registry.activeView<ecs::Canvas>();for (auto entity : view) {return static_cast<i32>(entity.id());}@@ -1157,7 +1168,7 @@ i32 registry_getCanvasEntity(ecs::Registry& registry) {// membership (SceneOwner) is an SDK component the engine cannot see, which is why// this reports rather than decides — the camera query has the same shape.emscripten::val registry_getCanvasEntities(ecs::Registry& registry) {- auto view = registry.view<ecs::Canvas>();+ auto view = registry.activeView<ecs::Canvas>();auto result = emscripten::val::array();u32 idx = 0;for (auto entity : view) {@@ -1169,7 +1180,7 @@ emscripten::val registry_getCanvasEntities(ecs::Registry& registry) {#ifdef __EMSCRIPTEN__emscripten::val registry_getCameraEntities(ecs::Registry& registry) {- auto cameraView = registry.view<ecs::Camera, ecs::Transform>();+ auto cameraView = registry.activeView<ecs::Camera, ecs::Transform>();auto result = emscripten::val::array();u32 idx = 0;for (auto entity : cameraView) {@@ -1398,6 +1409,16 @@ i32 renderer_submitSkeletalPreviewBatch(uintptr_t indicesPtr, i32 indexCount,u32 textureId, i32 blendMode, uintptr_t transformPtr,i32 layer, f32 depth, u32 materialId+) {+ return renderer_submitSkeletalPreviewBatchEx(preview, verticesPtr, vertexCount, indicesPtr, indexCount, textureId, blendMode, transformPtr, layer, depth, materialId, blendMode == 4 || blendMode == 5);+}++i32 renderer_submitSkeletalPreviewBatchEx(+ u32 preview,+ uintptr_t verticesPtr, i32 vertexCount,+ uintptr_t indicesPtr, i32 indexCount,+ u32 textureId, i32 blendMode, uintptr_t transformPtr,+ i32 layer, f32 depth, u32 materialId, bool premultipliedColor) {if (!g_renderFrame || vertexCount < 0 || indexCount < 0) return 0;// Skeletal vertex format is x,y,u,v,r,g,b,a (8 floats per vertex).@@ -1410,7 +1431,7 @@ i32 renderer_submitSkeletalPreviewBatch(if (!vertices || !indices || !transform) return 0;return g_renderFrame->submitSkeletalPreviewBatch(preview, vertices, vertexCount, indices, indexCount,- textureId, blendMode, transform, layer, depth, materialId) ? 1 : 0;+ textureId, blendMode, transform, layer, depth, materialId, premultipliedColor) ? 1 : 0;}i32 renderer_renderSkeletalPreview(u32 preview, uintptr_t viewProjectionPtr) {diff --git a/src/esengine/bindings/RendererBindings.hpp b/src/esengine/bindings/RendererBindings.hppindex 7caf64b02..5d178df5d 100644--- a/src/esengine/bindings/RendererBindings.hpp+++ b/src/esengine/bindings/RendererBindings.hpp@@ -60,6 +60,14 @@ void renderer_submitSkeletalBatchByEntity(u32 entity, f32 skelScale, bool flipX, bool flipY,i32 layer, f32 depth, u32 materialId);+void renderer_submitSkeletalBatchByEntityEx(+ ecs::Registry& registry,+ uintptr_t verticesPtr, i32 vertexCount,+ uintptr_t indicesPtr, i32 indexCount,+ u32 textureId, i32 blendMode,+ u32 entity, f32 skelScale, bool flipX, bool flipY,+ i32 layer, f32 depth, u32 materialId, bool premultipliedColor+);void renderer_submitTextBatch(uintptr_t verticesPtr, i32 vertexCount,uintptr_t indicesPtr, i32 indexCount,@@ -279,6 +287,12 @@ i32 renderer_submitSkeletalPreviewBatch(uintptr_t indicesPtr, i32 indexCount,u32 textureId, i32 blendMode, uintptr_t transformPtr,i32 layer, f32 depth, u32 materialId);+i32 renderer_submitSkeletalPreviewBatchEx(+ u32 preview,+ uintptr_t verticesPtr, i32 vertexCount,+ uintptr_t indicesPtr, i32 indexCount,+ u32 textureId, i32 blendMode, uintptr_t transformPtr,+ i32 layer, f32 depth, u32 materialId, bool premultipliedColor);i32 renderer_renderSkeletalPreview(u32 preview, uintptr_t viewProjectionPtr);i32 renderer_pollSkeletalPreview(u32 preview);uintptr_t renderer_getSkeletalPreviewPtr(u32 preview);diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cppindex 3d10118ff..e0e417271 100644--- a/src/esengine/bindings/WebBindings.generated.cpp+++ b/src/esengine/bindings/WebBindings.generated.cpp@@ -2066,6 +2066,15 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {.function("valid", optional_override([](Registry& r, u32 e) {return r.valid(static_cast<Entity>(e));}))+ .function("reserveDestruction", optional_override([](Registry& r, u32 e) {+ return r.reserveDestruction(static_cast<Entity>(e));+ }))+ .function("releaseDestruction", optional_override([](Registry& r, u32 e) {+ r.releaseDestruction(static_cast<Entity>(e));+ }))+ .function("destructionPending", optional_override([](Registry& r, u32 e) {+ return r.destructionPending(static_cast<Entity>(e));+ })).function("entityCount", &Registry::entityCount)// BitmapText@@ -3133,8 +3142,13 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {}))// Hierarchy Utilities+ .function("setEntityEnabled", optional_override([](Registry& r, u32 e, bool enabled) { return r.setEntityEnabled(static_cast<Entity>(e), enabled); }))+ .function("isEntityActive", optional_override([](Registry& r, u32 e) { return r.isEntityActive(static_cast<Entity>(e)); }))+ .function("isEntityEnabled", optional_override([](Registry& r, u32 e) { return r.isEntityEnabled(static_cast<Entity>(e)); }))+ .function("hasInactiveEntities", &Registry::hasInactiveEntities)+ .function("activityEpoch", &Registry::activityEpoch).function("setParent", optional_override([](Registry& r, u32 child, u32 parent) {- esengine::ecs::setParent(r, static_cast<Entity>(child), static_cast<Entity>(parent));+ return esengine::ecs::setParent(r, static_cast<Entity>(child), static_cast<Entity>(parent));}));diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cppindex 2176c551a..1bd1d8e72 100644--- a/src/esengine/bindings/WebSDKEntry.cpp+++ b/src/esengine/bindings/WebSDKEntry.cpp@@ -186,7 +186,12 @@ bool initRendererInternal(const char* canvasSelector) {ES_LOG_INFO("Estella runtime provenance {}", kEstellaBuildProvenance);g_activeContext = &legacyCtx().context();- return g_activeContext->init(static_cast<int>(webglCtx));+ if (!g_activeContext->init(static_cast<int>(webglCtx), true)) {+ // This path creates the context; an externally supplied handle is borrowed.+ emscripten_webgl_destroy_context(webglCtx);+ return false;+ }+ return true;}// The WebGPU mirror of initRendererInternal — the same platform boundary,@@ -231,8 +236,8 @@ bool initRendererWebGPU(const std::string& canvasSelector, u32 width, u32 height#endif}-void initRenderer() {- initRendererInternal("#canvas");+bool initRenderer() {+ return initRendererInternal("#canvas");}bool initRendererWithContext(int contextHandle) {@@ -519,6 +524,7 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {// Every skeletal runtime is a side module; this is the one door their posed// geometry comes through, so it belongs to neither of their build flags.emscripten::function("renderer_submitSkeletalBatchByEntity", &esengine::renderer_submitSkeletalBatchByEntity);+ emscripten::function("renderer_submitSkeletalBatchByEntityEx", &esengine::renderer_submitSkeletalBatchByEntityEx);emscripten::function("renderer_entityVisibleToCamera", &esengine::renderer_entityVisibleToCamera);emscripten::function("renderer_submitTextBatch", &esengine::renderer_submitTextBatch);emscripten::function("meshRenderer_setGeometry", &esengine::meshRenderer_setGeometry);@@ -789,6 +795,7 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {// and no begin/end pair, so two of them cannot reach each other.emscripten::function("renderer_createSkeletalPreview", &esengine::renderer_createSkeletalPreview);emscripten::function("renderer_submitSkeletalPreviewBatch", &esengine::renderer_submitSkeletalPreviewBatch);+ emscripten::function("renderer_submitSkeletalPreviewBatchEx", &esengine::renderer_submitSkeletalPreviewBatchEx);emscripten::function("renderer_renderSkeletalPreview", &esengine::renderer_renderSkeletalPreview);emscripten::function("renderer_pollSkeletalPreview", &esengine::renderer_pollSkeletalPreview);emscripten::function("renderer_getSkeletalPreviewPtr", &esengine::renderer_getSkeletalPreviewPtr);diff --git a/src/esengine/bindings/modules/physics/PhysicsContext.hpp b/src/esengine/bindings/modules/physics/PhysicsContext.hppindex 141256fb3..e627bbeec 100644--- a/src/esengine/bindings/modules/physics/PhysicsContext.hpp+++ b/src/esengine/bindings/modules/physics/PhysicsContext.hpp@@ -35,6 +35,13 @@ struct PhysicsContext {std::unordered_map<uint32_t, b2JointId> entityToJoint;std::vector<uint32_t> dynamicBodyEntities;+ // Box2D discards solver velocity when a body moves to the disabled set.+ struct PausedMotion {+ b2Vec2 linearVelocity;+ float angularVelocity;+ };+ std::unordered_map<uint32_t, PausedMotion> pausedMotion;+// One-way (one-sided) platforms: entity -> solid-side normal in physics space// (normalized). Read by the pre-solve callback to cancel contacts that approach// from the pass-through side. Empty map = zero pre-solve overhead.@@ -72,6 +79,7 @@ struct PhysicsContext {entityToBody.clear();entityToShapes.clear();entityToJoint.clear();+ pausedMotion.clear();oneWayNormals.clear();mouseBodyId = b2_nullBodyId;mouseJointId = b2_nullJointId;diff --git a/src/esengine/bindings/modules/physics/PhysicsModuleEntry.cpp b/src/esengine/bindings/modules/physics/PhysicsModuleEntry.cppindex 0eca3bf92..5fcd11893 100644--- a/src/esengine/bindings/modules/physics/PhysicsModuleEntry.cpp+++ b/src/esengine/bindings/modules/physics/PhysicsModuleEntry.cpp@@ -172,6 +172,7 @@ void physics_destroyBody(uint32_t entityId) {b2DestroyBody(it->second);}g_ctx.entityToBody.erase(it);+ g_ctx.pausedMotion.erase(entityId);g_ctx.entityToShapes.erase(entityId);auto dit = std::find(g_ctx.dynamicBodyEntities.begin(), g_ctx.dynamicBodyEntities.end(), entityId);if (dit != g_ctx.dynamicBodyEntities.end()) {@@ -193,8 +194,19 @@ void physics_setBodyEnabled(uint32_t entityId, int enabled) {b2BodyId body = findValidBody(entityId);if (!b2Body_IsValid(body)) return;if (enabled) {+ if (b2Body_IsEnabled(body)) return;b2Body_Enable(body);+ auto it = g_ctx.pausedMotion.find(entityId);+ if (it != g_ctx.pausedMotion.end()) {+ b2Body_SetLinearVelocity(body, it->second.linearVelocity);+ b2Body_SetAngularVelocity(body, it->second.angularVelocity);+ g_ctx.pausedMotion.erase(it);+ }} else {+ if (!b2Body_IsEnabled(body)) return;+ g_ctx.pausedMotion[entityId] = {+ b2Body_GetLinearVelocity(body), b2Body_GetAngularVelocity(body)+ };b2Body_Disable(body);}}@@ -280,7 +292,8 @@ int physics_getJointCount() {EMSCRIPTEN_KEEPALIVEint physics_getTrackingRows() {return static_cast<int>(g_ctx.entityToShapes.size() + g_ctx.oneWayNormals.size()- + g_ctx.posePrevIndex.size() + g_ctx.dynamicBodyEntities.size());+ + g_ctx.posePrevIndex.size() + g_ctx.dynamicBodyEntities.size()+ + g_ctx.pausedMotion.size());}EMSCRIPTEN_KEEPALIVE@@ -575,6 +588,11 @@ void physics_applyImpulse(uint32_t entityId, float impulseX, float impulseY) {EMSCRIPTEN_KEEPALIVEvoid physics_setLinearVelocity(uint32_t entityId, float vx, float vy) {+ auto paused = g_ctx.pausedMotion.find(entityId);+ if (paused != g_ctx.pausedMotion.end()) {+ paused->second.linearVelocity = {vx, vy};+ return;+ }auto it = g_ctx.entityToBody.find(entityId);if (it == g_ctx.entityToBody.end()) return;if (!b2Body_IsValid(it->second)) return;@@ -596,7 +614,9 @@ uintptr_t physics_getLinearVelocity(uint32_t entityId) {return reinterpret_cast<uintptr_t>(g_ctx.velocityBuffer);}- b2Vec2 v = b2Body_GetLinearVelocity(it->second);+ auto paused = g_ctx.pausedMotion.find(entityId);+ b2Vec2 v = paused != g_ctx.pausedMotion.end()+ ? paused->second.linearVelocity : b2Body_GetLinearVelocity(it->second);g_ctx.velocityBuffer[0] = v.x;g_ctx.velocityBuffer[1] = v.y;return reinterpret_cast<uintptr_t>(g_ctx.velocityBuffer);@@ -627,6 +647,11 @@ uintptr_t physics_getGravity() {EMSCRIPTEN_KEEPALIVEvoid physics_setAngularVelocity(uint32_t entityId, float omega) {+ auto paused = g_ctx.pausedMotion.find(entityId);+ if (paused != g_ctx.pausedMotion.end()) {+ paused->second.angularVelocity = omega;+ return;+ }auto it = g_ctx.entityToBody.find(entityId);if (it == g_ctx.entityToBody.end()) return;if (!b2Body_IsValid(it->second)) return;@@ -635,6 +660,8 @@ void physics_setAngularVelocity(uint32_t entityId, float omega) {EMSCRIPTEN_KEEPALIVEfloat physics_getAngularVelocity(uint32_t entityId) {+ auto paused = g_ctx.pausedMotion.find(entityId);+ if (paused != g_ctx.pausedMotion.end()) return paused->second.angularVelocity;auto it = g_ctx.entityToBody.find(entityId);if (it == g_ctx.entityToBody.end()) return 0;if (!b2Body_IsValid(it->second)) return 0;diff --git a/src/esengine/bindings/modules/spine/SkeletalModule.hpp b/src/esengine/bindings/modules/spine/SkeletalModule.hppindex f1450c14a..7455de123 100644--- a/src/esengine/bindings/modules/spine/SkeletalModule.hpp+++ b/src/esengine/bindings/modules/spine/SkeletalModule.hpp@@ -80,11 +80,13 @@ struct MeshBatch {Buffer<std::uint16_t> indices;std::uint32_t texture = 0;int blendMode = 0;+ bool premultipliedColor = false;};/// Where a runtime pours the triangles it posed.struct TriangleSink {virtual ~TriangleSink() = default;+ virtual void setPremultipliedColor(bool) {}virtual void emit(const float* positions, const float* uvs, int vertexCount,const std::uint16_t* indices, int indexCount,std::uint32_t texture, int blendMode, const float rgba[4]) = 0;@@ -112,13 +114,14 @@ public:/// Starts a batch in this state, in the next slot's storage. The reference/// is good until the next `open`, which may move every slot.- MeshBatch& open(std::uint32_t texture, int blendMode) {+ MeshBatch& open(std::uint32_t texture, int blendMode, bool premultipliedColor = false) {if (active_ == slots_.size()) slots_.emplace_back();MeshBatch& fresh = slots_[active_++];fresh.vertices.clear();fresh.indices.clear();fresh.texture = texture;fresh.blendMode = blendMode;+ fresh.premultipliedColor = premultipliedColor;return fresh;}@@ -160,6 +163,7 @@ private:class BatchCollector final : public TriangleSink {public:explicit BatchCollector(BatchList& into) : batches_(into) {}+ void setPremultipliedColor(bool value) override { premultipliedColor_ = value; }void emit(const float* positions, const float* uvs, int vertexCount,const std::uint16_t* indices, int indexCount,@@ -192,16 +196,18 @@ private:MeshBatch& batchFor(std::uint32_t texture, int blendMode, int incomingVertices) {if (batches_.size() > 0) {MeshBatch& open = batches_.back();- const bool sameState = texture == open.texture && blendMode == open.blendMode;+ const bool sameState = texture == open.texture && blendMode == open.blendMode+ && premultipliedColor_ == open.premultipliedColor;const bool fits =open.vertices.size() / VERTEX_FLOATS + static_cast<std::size_t>(incomingVertices)<= MAX_BATCH_VERTICES;if (sameState && fits) return open;}- return batches_.open(texture, blendMode);+ return batches_.open(texture, blendMode, premultipliedColor_);}BatchList& batches_;+ bool premultipliedColor_ = false;};/**diff --git a/src/esengine/bindings/modules/spine/SpineBindings.hpp b/src/esengine/bindings/modules/spine/SpineBindings.hppindex 4ffd790b8..3b0618497 100644--- a/src/esengine/bindings/modules/spine/SpineBindings.hpp+++ b/src/esengine/bindings/modules/spine/SpineBindings.hpp@@ -49,6 +49,7 @@ int spine_getBonePosition(int instanceId, const char* bone, uintptr_t outXPtr, ufloat spine_getBoneRotation(int instanceId, const char* bone);void spine_getBounds(int instanceId, uintptr_t outXPtr, uintptr_t outYPtr, uintptr_t outWPtr, uintptr_t outHPtr);int spine_getMeshBatchCount(int instanceId);+int spine_getMeshBatchColorPremultiplied(int instanceId, int batchIndex);int spine_getMeshBatchVertexCount(int instanceId, int batchIndex);int spine_getMeshBatchIndexCount(int instanceId, int batchIndex);void spine_getMeshBatchData(int instanceId, int batchIndex, uintptr_t outVerticesPtr, uintptr_t outIndicesPtr, uintptr_t outTextureIdPtr, uintptr_t outBlendModePtr);@@ -57,6 +58,7 @@ void spine_setDefaultMix(int skeletonHandle, float duration);void spine_setMixDuration(int skeletonHandle, const char* fromAnim, const char* toAnim, float duration);void spine_setTrackAlpha(int instanceId, int track, float alpha);void spine_enableEvents(int instanceId);+// Selects this instance for the buffer, string getters, and clear call below.int spine_getEventCount(int instanceId);// @heapreturn spine_eventBufferBytes()uintptr_t spine_getEventBuffer();diff --git a/src/esengine/bindings/modules/spine/SpineModuleEntry.cpp b/src/esengine/bindings/modules/spine/SpineModuleEntry.cppindex 5af23b31b..76e1cb1da 100644--- a/src/esengine/bindings/modules/spine/SpineModuleEntry.cpp+++ b/src/esengine/bindings/modules/spine/SpineModuleEntry.cpp@@ -54,6 +54,7 @@ using es::spine::TransformMix;struct LiveInstance {InstancePtr instance;int skeletonHandle = -1;+ es::skeletal::EventBuffer events;};struct Context {@@ -62,7 +63,22 @@ struct Context {es::skeletal::BatchList batches;es::skeletal::StringBuffer strings;- es::skeletal::EventBuffer events;+ std::unordered_map<const void*, int> eventOwners;+ int selectedEventInstance = -1;++ es::skeletal::EventBuffer* selectedEvents() {+ auto* live = instances.find(selectedEventInstance);+ return live ? &live->events : nullptr;+ }++ void forgetEvents(const LiveInstance& live) {+ const auto source = es::spine::eventSource(live.instance.get());+ auto owner = eventOwners.find(source);+ if (owner != eventOwners.end()) {+ if (selectedEventInstance == owner->second) selectedEventInstance = -1;+ eventOwners.erase(owner);+ }+ }/// Clip-region processing, on by default: a debug and perf knob, so a scene/// with no clip regions can skip the machinery and a clipped one can be@@ -71,6 +87,13 @@ struct Context {std::string lastError;+ ~Context() {+ // Instance destruction can emit events; stop routing before releasing it.+ eventOwners.clear();+ instances.clear();+ skeletons.clear();+ }+es::spine::Instance* instanceOf(int id) {auto* live = instances.find(id);return live ? live->instance.get() : nullptr;@@ -86,7 +109,11 @@ Context g_ctx;/// Queues one event for the SDK to drain after the update that produced it.void collectEvent(const Event& event) {- g_ctx.events.push(static_cast<int>(event.kind), event.track, event.floatValue, event.intValue,+ auto owner = g_ctx.eventOwners.find(event.source);+ if (owner == g_ctx.eventOwners.end()) return;+ auto* live = g_ctx.instances.find(owner->second);+ if (!live) return;+ live->events.push(static_cast<int>(event.kind), event.track, event.floatValue, event.intValue,es::skeletal::EventStrings{event.animation, event.name, event.stringValue});}@@ -147,7 +174,11 @@ void spine_unloadSkeleton(int handle) {if (!g_ctx.skeletons.find(handle)) return;// Instances hold the skeleton's data; they go first.- g_ctx.instances.eraseIf([handle](const LiveInstance& live) { return live.skeletonHandle == handle; });+ g_ctx.instances.eraseIf([handle](const LiveInstance& live) {+ if (live.skeletonHandle != handle) return false;+ g_ctx.forgetEvents(live);+ return true;+ });g_ctx.skeletons.erase(handle);}@@ -179,12 +210,14 @@ int spine_createInstance(int skeletonHandle) {es::spine::Instance* created = es::spine::createInstance(skeleton);if (!created) return -1;- const int id = g_ctx.instances.add(LiveInstance{InstancePtr(created), skeletonHandle});+ const int id = g_ctx.instances.add(LiveInstance{InstancePtr(created), skeletonHandle, {}});+ g_ctx.eventOwners.emplace(es::spine::eventSource(created), id);return id;}EMSCRIPTEN_KEEPALIVEvoid spine_destroyInstance(int instanceId) {+ if (auto* live = g_ctx.instances.find(instanceId)) g_ctx.forgetEvents(*live);g_ctx.instances.erase(instanceId);}@@ -220,7 +253,6 @@ void spine_update(int instanceId, float dt) {if (!instance) return;// The composition lives in the runtime beside the two halves, so there is// one definition of what a whole frame is rather than one here as well.- g_ctx.events.clear();es::spine::update(instance, dt);}@@ -234,7 +266,6 @@ EMSCRIPTEN_KEEPALIVEvoid spine_advanceAndApply(int instanceId, float dt) {auto* instance = g_ctx.instanceOf(instanceId);if (!instance) return;- g_ctx.events.clear();es::spine::advanceAndApply(instance, dt);}@@ -501,6 +532,13 @@ void spine_probe_storage(std::uint32_t* out) {out[3] = static_cast<std::uint32_t>(held.indices);}+EMSCRIPTEN_KEEPALIVE+int spine_getMeshBatchColorPremultiplied(int instanceId, int batchIndex) {+ (void)instanceId;+ if (batchIndex < 0 || static_cast<std::size_t>(batchIndex) >= g_ctx.batches.size()) return 0;+ return g_ctx.batches[batchIndex].premultipliedColor ? 1 : 0;+}+EMSCRIPTEN_KEEPALIVEint spine_getMeshBatchCount(int instanceId) {extractBatches(instanceId);@@ -576,23 +614,26 @@ void spine_enableEvents(int instanceId) {EMSCRIPTEN_KEEPALIVEint spine_getEventCount(int instanceId) {- (void)instanceId;- return g_ctx.events.count();+ g_ctx.selectedEventInstance = instanceId;+ auto* events = g_ctx.selectedEvents();+ return events ? events->count() : 0;}EMSCRIPTEN_KEEPALIVEuintptr_t spine_getEventBuffer() {- return reinterpret_cast<uintptr_t>(g_ctx.events.values());+ auto* events = g_ctx.selectedEvents();+ return events ? reinterpret_cast<uintptr_t>(events->values()) : 0;}EMSCRIPTEN_KEEPALIVEvoid spine_clearEvents() {- g_ctx.events.clear();+ if (auto* events = g_ctx.selectedEvents()) events->clear();}EMSCRIPTEN_KEEPALIVEconst char* spine_getEventAnimationName(int index) {- const auto* record = g_ctx.events.strings(index);+ auto* events = g_ctx.selectedEvents();+ const auto* record = events ? events->strings(index) : nullptr;if (!record) return "";const char* name = record->animationName;return name ? name : "";@@ -600,7 +641,8 @@ const char* spine_getEventAnimationName(int index) {EMSCRIPTEN_KEEPALIVEconst char* spine_getEventName(int index) {- const auto* record = g_ctx.events.strings(index);+ auto* events = g_ctx.selectedEvents();+ const auto* record = events ? events->strings(index) : nullptr;if (!record) return "";const char* name = record->eventName;return name ? name : "";@@ -608,7 +650,8 @@ const char* spine_getEventName(int index) {EMSCRIPTEN_KEEPALIVEconst char* spine_getEventStringValue(int index) {- const auto* record = g_ctx.events.strings(index);+ auto* events = g_ctx.selectedEvents();+ const auto* record = events ? events->strings(index) : nullptr;if (!record) return "";const char* value = record->stringValue;return value ? value : "";@@ -733,7 +776,8 @@ int spine_runtimeVersion() {// assuming the stride — see `@heapreturn` in SpineBindings.hpp.EMSCRIPTEN_KEEPALIVEsize_t spine_eventBufferBytes() {- return g_ctx.events.byteLength();+ auto* events = g_ctx.selectedEvents();+ return events ? events->byteLength() : 0;}} // extern "C"diff --git a/src/esengine/bindings/modules/spine/SpineRuntime.hpp b/src/esengine/bindings/modules/spine/SpineRuntime.hppindex 9ee8127aa..0c975ef26 100644--- a/src/esengine/bindings/modules/spine/SpineRuntime.hpp+++ b/src/esengine/bindings/modules/spine/SpineRuntime.hpp@@ -90,6 +90,7 @@ enum class EventKind {};struct Event {+ const void* source = nullptr;EventKind kind = EventKind::Event;int track = 0;float floatValue = 0.0f;@@ -103,6 +104,8 @@ struct Event {/// The module is a singleton, so its collector is process-wide rather than per instance.using EventSink = void (*)(const Event&);+const void* eventSource(Instance* instance);+/*** Where a backend pours the triangles it posed. The sink batches: it decides when* a texture or blend change starts a new batch and when one has filled up, so thatdiff --git a/src/esengine/bindings/modules/spine/SpineRuntime21.cpp b/src/esengine/bindings/modules/spine/SpineRuntime21.cppindex a704f6fa8..6a2eee9da 100644--- a/src/esengine/bindings/modules/spine/SpineRuntime21.cpp+++ b/src/esengine/bindings/modules/spine/SpineRuntime21.cpp@@ -226,6 +226,7 @@ void eventListener(spAnimationState* state, int trackIndex, spEventType type,if (!g_eventSink) return;Event out;+ out.source = state;out.kind = kindOf(type);out.track = trackIndex;@@ -404,6 +405,10 @@ void setEventSink(EventSink sink) {g_eventSink = sink;}+const void* eventSource(Instance* instance) {+ return instance ? instance->state : nullptr;+}+void enableEvents(Instance* instance) {if (instance) instance->state->listener = eventListener;}diff --git a/src/esengine/bindings/modules/spine/SpineRuntimeC.cpp b/src/esengine/bindings/modules/spine/SpineRuntimeC.cppindex f4db1609a..600a1faea 100644--- a/src/esengine/bindings/modules/spine/SpineRuntimeC.cpp+++ b/src/esengine/bindings/modules/spine/SpineRuntimeC.cpp@@ -160,6 +160,7 @@ void eventListener(spAnimationState* state, spEventType type, spTrackEntry* entrif (!g_eventSink) return;Event out;+ out.source = state;out.kind = static_cast<EventKind>(static_cast<int>(type));out.track = entry ? entry->trackIndex : 0;out.animation = (entry && entry->animation) ? entry->animation->name : nullptr;@@ -424,6 +425,10 @@ void setEventSink(EventSink sink) {g_eventSink = sink;}+const void* eventSource(Instance* instance) {+ return instance ? instance->state : nullptr;+}+void enableEvents(Instance* instance) {if (instance) instance->state->listener = eventListener;}@@ -1055,6 +1060,7 @@ void renderImpl(Instance* instance, TriangleSink& sink, bool clipping, ProbeCounskeletonColor.b * slotColor.b * attachmentColor.b,skeletonColor.a * slotColor.a * attachmentColor.a,};+ sink.setPremultipliedColor(pma);premultiplyTint(rgba, pma);if constexpr (COUNT) counts->verticesGenerated += 4;@@ -1088,6 +1094,7 @@ void renderImpl(Instance* instance, TriangleSink& sink, bool clipping, ProbeCounskeletonColor.b * slotColor.b * attachmentColor.b,skeletonColor.a * slotColor.a * attachmentColor.a,};+ sink.setPremultipliedColor(pma);premultiplyTint(rgba, pma);if constexpr (COUNT) counts->verticesGenerated += length / 2;diff --git a/src/esengine/bindings/modules/spine/SpineRuntimeCpp.cpp b/src/esengine/bindings/modules/spine/SpineRuntimeCpp.cppindex f1bb6b308..e8c33c178 100644--- a/src/esengine/bindings/modules/spine/SpineRuntimeCpp.cpp+++ b/src/esengine/bindings/modules/spine/SpineRuntimeCpp.cpp@@ -327,6 +327,7 @@ void eventListener(sp::AnimationState* state, sp::EventType type,if (!g_eventSink) return;Event out;+ out.source = state;out.kind = kindOf(type);out.track = entry ? static_cast<int>(entry->getTrackIndex()) : 0;if (entry) out.animation = cstr(entry->getAnimation().getName());@@ -341,6 +342,10 @@ void eventListener(sp::AnimationState* state, sp::EventType type,} // namespace+const void* eventSource(Instance* instance) {+ return instance ? instance->state : nullptr;+}+void enableEvents(Instance* instance) {if (instance) instance->state->setListener(eventListener);}@@ -552,6 +557,7 @@ void render(Instance* instance, TriangleSink& sink, bool clipping) {// backend also reads (SpineRuntime.hpp): the blend code gains a twin for// two of the four modes, and the tint carries its alpha for ALL of them.const bool pma = instance->owner->isPremultiplied(command->texture);+ sink.setPremultipliedColor(pma);premultiplyTint(rgba, pma);sink.emit(command->positions, command->uvs, command->numVertices,diff --git a/src/esengine/core/EstellaContext.cpp b/src/esengine/core/EstellaContext.cppindex 8d0f1a978..3d754d279 100644--- a/src/esengine/core/EstellaContext.cpp+++ b/src/esengine/core/EstellaContext.cpp@@ -85,13 +85,15 @@ EstellaContext::~EstellaContext() {// backend. A native build has no WebGL — it enters through init(Unique<GfxDevice>)// with an injected WebGPUDevice instead, so this overload compiles out entirely.bool EstellaContext::init(int webglContextHandle) {+ return init(webglContextHandle, false);+}++bool EstellaContext::init(int webglContextHandle, bool ownsContext) {if (state_.initialized) {ES_LOG_WARN("EstellaContext already initialized");return true;}- state_.webgl_context = webglContextHandle;-EMSCRIPTEN_RESULT result = emscripten_webgl_make_context_current(static_cast<EMSCRIPTEN_WEBGL_CONTEXT_HANDLE>(webglContextHandle));if (result != EMSCRIPTEN_RESULT_SUCCESS) {@@ -99,6 +101,9 @@ bool EstellaContext::init(int webglContextHandle) {return false;}+ state_.webgl_context = webglContextHandle;+ state_.owns_webgl_context = ownsContext;+initSubsystems(makeUnique<GLDevice>());return true;}@@ -243,20 +248,31 @@ void EstellaContext::initSubsystems(Unique<GfxDevice> gfxDevice) {void EstellaContext::shutdown() {if (!state_.initialized) return;+#ifdef ES_PLATFORM_WEB+ const auto webglCtx = static_cast<EMSCRIPTEN_WEBGL_CONTEXT_HANDLE>(state_.webgl_context);+ const bool ownsWebglContext = state_.owns_webgl_context;+ const auto previousContext = emscripten_webgl_get_current_context();+ // GL object deletion uses the current context, including subsystem destructors.+ // Another engine instance may have made its own context current since our init.+ if (webglCtx > 0 && previousContext != webglCtx) {+ emscripten_webgl_make_context_current(webglCtx);+ }+#endif+if (auto* rf = tryGet<RenderFrame>()) rf->shutdown();if (auto* id = tryGet<ImmediateDraw>()) id->shutdown();if (auto* rc = tryGet<RenderContext>()) rc->shutdown();if (auto* rm = tryGet<resource::ResourceManager>()) rm->shutdown();- int webglCtx = state_.webgl_context;-services_.clear();state_ = EngineState{};#ifdef ES_PLATFORM_WEB- if (webglCtx > 0) {- emscripten_webgl_destroy_context(- static_cast<EMSCRIPTEN_WEBGL_CONTEXT_HANDLE>(webglCtx));+ if (webglCtx > 0 && ownsWebglContext) {+ emscripten_webgl_destroy_context(webglCtx);+ }+ if (webglCtx > 0 && previousContext != webglCtx) {+ emscripten_webgl_make_context_current(previousContext);}#endifdiff --git a/src/esengine/core/EstellaContext.hpp b/src/esengine/core/EstellaContext.hppindex 433b1d1d2..75f229b4a 100644--- a/src/esengine/core/EstellaContext.hpp+++ b/src/esengine/core/EstellaContext.hpp@@ -34,9 +34,13 @@ public:* @return True on success* @details Convenience for the GL backend: makes the context current and* delegates to init(UniquePtr<GfxDevice>) with a GLDevice.+ * Borrows the handle; its owner must keep it registered until shutdown.*/bool init(int webglContextHandle);+ /** Adopt a WebGL handle only when its creator explicitly transfers ownership. */+ bool init(int webglContextHandle, bool ownsContext);+/*** @brief Initialize with an injected render backend.* @param device A ready-to-use GfxDevice (e.g. a WebGPUDevice whose surfacediff --git a/src/esengine/data/shaders/batch.esshader b/src/esengine/data/shaders/batch.esshaderindex 24b647da8..d5ca363f5 100644--- a/src/esengine/data/shaders/batch.esshader+++ b/src/esengine/data/shaders/batch.esshader@@ -17,6 +17,9 @@// they keep an unconditional (early-Z friendly) fragment path.#pragma feature ALPHA_CLIP+// The vertex tint arrives straight; multiply coverage after color conversion.+#pragma feature PREMULTIPLIED_COLOR+#pragma vertexlayout(location = 0) in vec3 a_position;layout(location = 1) in vec4 a_color;@@ -89,6 +92,9 @@ void main() {#elsevec4 tint = v_color;#endif+#ifdef PREMULTIPLIED_COLOR+ tint.rgb *= tint.a;+#endif#ifdef SDF// The glyph atlas stores a signed distance in the alpha channel (RGB = 1).// Distance ÷ fwidth = screen px from the edge; the ±0.5px clamp is exactly@@ -200,9 +206,12 @@ struct VSOut {else if (idx == 6) { texColor = textureSampleLevel(t6, s6, v.v_texCoord, 0.0); }else { texColor = textureSampleLevel(t7, s7, v.v_texCoord, 0.0); }#ifdef ES_LINEAR- let tint = vec4f(srgbToLinear(v.v_color.rgb), v.v_color.a);+ var tint = vec4f(srgbToLinear(v.v_color.rgb), v.v_color.a);#else- let tint = v.v_color;+ var tint = v.v_color;+#endif+#ifdef PREMULTIPLIED_COLOR+ tint = vec4f(tint.rgb * tint.a, tint.a);#endif#ifdef SDF// Same coverage math as the GLSL stage; fwidth here is in uniform controldiff --git a/src/esengine/ecs/ActiveView.hpp b/src/esengine/ecs/ActiveView.hppnew file mode 100644index 000000000..9296e8fe6--- /dev/null+++ b/src/esengine/ecs/ActiveView.hpp@@ -0,0 +1,58 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+#pragma once+#include "Entity.hpp"+#include <tuple>+#include <type_traits>+#include <utility>++namespace esengine::ecs {++// Storage views stay unfiltered for inspection, serialization and hierarchy+// maintenance. Simulation/render consumers explicitly ask for an active view.+template<class V, class R>+class ActiveView {+public:+ class Iterator {+ public:+ Iterator(typename V::Iterator at, typename V::Iterator end, R* registry)+ : at_(at), end_(end), registry_(registry) { skip(); }+ Entity operator*() const { return *at_; }+ Iterator& operator++() { ++at_; skip(); return *this; }+ bool operator!=(const Iterator& other) const { return at_ != other.at_; }+ bool operator==(const Iterator& other) const { return at_ == other.at_; }+ private:+ void skip() { while (at_ != end_ && !registry_->isEntityActive(*at_)) ++at_; }+ typename V::Iterator at_, end_;+ R* registry_;+ };+ ActiveView(V view, R& registry) : view_(std::move(view)), registry_(®istry) {}+ Iterator begin() const { return {view_.begin(), view_.end(), registry_}; }+ Iterator end() const { return {view_.end(), view_.end(), registry_}; }+ template<class T> T& get(Entity e) { return view_.template get<T>(e); }+ decltype(auto) get(Entity e) { return view_.get(e); }+ bool empty() const { return begin() == end(); }+ usize sizeHint() const { return view_.sizeHint(); }+ template<class F> void each(F&& f) {+ view_.each([&](Entity e, auto&... data) {+ if (!registry_->isEntityActive(e)) return;+ invoke(f, e, data...);+ });+ }+ template<class F> void eachLive(F&& f) {+ view_.eachLive([&](Entity e, auto&... data) {+ if (!registry_->isEntityActive(e)) return;+ invoke(f, e, data...);+ });+ }+private:+ template<class F, class... Data>+ static void invoke(F& f, Entity e, Data&... data) {+ if constexpr (std::is_invocable_v<F&, Entity, Data&...>) f(e, data...);+ else if constexpr (std::is_invocable_v<F&, Data&...>) f(data...);+ else f(e);+ }+ V view_;+ R* registry_;+};+} // namespace esengine::ecsdiff --git a/src/esengine/ecs/Registry.hpp b/src/esengine/ecs/Registry.hppindex 43c9b3a81..9e8b852cd 100644--- a/src/esengine/ecs/Registry.hpp+++ b/src/esengine/ecs/Registry.hpp@@ -26,6 +26,8 @@#include "Entity.hpp"#include "SparseSet.hpp"#include "View.hpp"+#include "ActiveView.hpp"+#include "components/Hierarchy.hpp"#include "../events/Sink.hpp"// Standard library@@ -89,6 +91,36 @@ public:*/u64 instanceId() const { return instance_id_; }+ // Local authoring state is distinct from effective activity. Disabling a+ // parent never overwrites a child's own switch. All engine consumers share+ // this derived answer, including JS queries through the registry binding.+ bool setEntityEnabled(Entity e, bool enabled) {+ if (!valid(e)) return false;+ const u8 off = enabled ? 0 : 1;+ if (disabled_[e.index()] == off) return true;+ disabled_[e.index()] = off;+ if (off) ++disabled_count_; else --disabled_count_;+ ++activity_epoch_;+ return true;+ }+ bool isEntityEnabled(Entity e) const {+ return valid(e) && disabled_[e.index()] == 0;+ }++ bool isEntityActive(Entity e) const {+ if (!valid(e)) return false;+ if (disabled_count_ == 0) return true;+ ensureActivity();+ return inactive_[e.index()] == 0;+ }+ bool hasInactiveEntities() const { return disabled_count_ != 0; }+ u32 activityEpoch() const { return activity_epoch_; }+ void invalidateActivityHierarchy() { if (disabled_count_) ++activity_epoch_; }++ template<class... C> auto activeView() {+ return ActiveView<View<C...>, Registry>(view<C...>(), *this);+ }+// =========================================================================// Entity Management// =========================================================================@@ -151,6 +183,27 @@ public:return activateIndex(index);}+ /** Internal subtree ownership. Components remain readable for callbacks,+ * but a pending entity cannot receive links or be reserved a second time. */+ bool reserveDestruction(Entity entity) {+ if (!valid(entity) || destruction_pending_[entity.index()]) return false;+ destruction_pending_[entity.index()] = 1;+ return true;+ }+ void releaseDestruction(Entity entity) {+ const u32 index = entity.index();+ // An old owner's finalizer can run after this slot was recycled and+ // reserved by a new owner. Only its original generation may clear it.+ if (index < destruction_pending_.size() && generations_[index] == entity.generation()) {+ destruction_pending_[index] = 0;+ }+ }+ bool destructionPending(Entity entity) const {+ const u32 index = entity.index();+ return index < destruction_pending_.size() && destruction_pending_[index]+ && generations_[index] == entity.generation();+ }+/*** @brief Destroys an entity and removes all its components* @param entity The entity to destroy@@ -168,6 +221,9 @@ public:// runs twice: entity_count_ underflows and idx is pushed onto recycled_// twice, later aliasing two distinct entities to the same index.entityValid_[idx] = false;+ const bool hadDisabled = disabled_count_ != 0;+ if (disabled_[idx]) { disabled_[idx] = 0; --disabled_count_; }+ if (hadDisabled) ++activity_epoch_;// Signal handles re-entrant connect/disconnect during publish; its RAII// Connection (via Sink::connect) keeps subscriber lifetimes safe in both@@ -271,6 +327,7 @@ public:auto& pool = assurePool<T>();auto& result = pool.emplace(entity, std::forward<Args>(args)...);component_masks_[entity.index()].set(componentTypeId<T>());+ if constexpr (std::is_same_v<T, Parent> || std::is_same_v<T, Children>) invalidateActivityHierarchy();return result;}@@ -292,10 +349,12 @@ public:if (pool.contains(entity)) {auto& comp = pool.get(entity);comp = T(std::forward<Args>(args)...);+ if constexpr (std::is_same_v<T, Parent> || std::is_same_v<T, Children>) invalidateActivityHierarchy();return comp;}auto& result = pool.emplace(entity, std::forward<Args>(args)...);component_masks_[entity.index()].set(componentTypeId<T>());+ if constexpr (std::is_same_v<T, Parent> || std::is_same_v<T, Children>) invalidateActivityHierarchy();return result;}@@ -311,6 +370,7 @@ public:auto* pool = getPool<T>();if (pool) {pool->remove(entity);+ if constexpr (std::is_same_v<T, Parent> || std::is_same_v<T, Children>) invalidateActivityHierarchy();const u32 idx = entity.index();if (idx < component_masks_.size()) {component_masks_[idx].clear(componentTypeId<T>());@@ -463,6 +523,11 @@ public:}}entityValid_.clear();+ disabled_.clear();+ inactive_.clear();+ activity_state_.clear();+ disabled_count_ = 0;+ ++activity_epoch_;generations_.clear();component_masks_.clear();while (!recycled_.empty()) recycled_.pop();@@ -703,10 +768,15 @@ private:}if (index >= entityValid_.size()) {entityValid_.resize(index + 1, false);+ disabled_.resize(index + 1, 0);+ destruction_pending_.resize(index + 1, 0);generations_.resize(index + 1, 0);component_masks_.resize(index + 1);}entityValid_[index] = true;+ disabled_[index] = 0;+ destruction_pending_[index] = 0;+ invalidateActivityHierarchy();generations_[index] = (generations_[index] + 1) & Entity::GEN_MASK;if (generations_[index] == 0) generations_[index] = 1;component_masks_[index].reset();@@ -719,6 +789,42 @@ private:// =========================================================================std::vector<u8> entityValid_;+ std::vector<u8> disabled_;+ usize disabled_count_ = 0;+ u32 activity_epoch_ = 1;+ mutable u32 resolved_activity_epoch_ = 0;+ mutable std::vector<u8> inactive_, activity_state_;+ mutable std::vector<u32> activity_path_;++ void ensureActivity() const {+ if (resolved_activity_epoch_ == activity_epoch_) return;+ inactive_.assign(entityValid_.size(), 0);+ activity_state_.assign(entityValid_.size(), 0);+ const auto* parents = getPool<Parent>();+ // Each entity is resolved once, iteratively: deep chains do not recurse+ // or repeatedly walk their ancestors. O(entities + parent links).+ for (usize start = 0; start < entityValid_.size(); ++start) {+ if (!entityValid_[start] || activity_state_[start] == 2) continue;+ activity_path_.clear();+ u32 at = static_cast<u32>(start);+ bool off = false;+ for (;;) {+ if (activity_state_[at] == 2) { off = inactive_[at] != 0; break; }+ if (activity_state_[at] == 1) { off = true; break; }+ activity_state_[at] = 1;+ activity_path_.push_back(at);+ if (disabled_[at]) { off = true; break; }+ const auto* parent = parents ? parents->tryGet(Entity::make(at, generations_[at])) : nullptr;+ if (!parent || !valid(parent->entity)) break;+ at = parent->entity.index();+ }+ for (u32 index : activity_path_) {+ inactive_[index] = off ? 1 : 0;+ activity_state_[index] = 2;+ }+ }+ resolved_activity_epoch_ = activity_epoch_;+ }std::vector<u32> generations_;std::vector<ComponentMask> component_masks_;std::queue<u32> recycled_; ///< Recycled entity indices@@ -733,6 +839,10 @@ private:std::vector<Unique<SparseSetBase>> pools_;Signal<void(Entity)> on_destroy_signal_;+ // Indexed by the canonical entity slot/generation. Grow during activation,+ // never allocate one hash node per teardown or a whole-world array on the+ // first deletion. Recycled slots start unreserved.+ std::vector<u8> destruction_pending_;};} // namespace esengine::ecsdiff --git a/src/esengine/ecs/TransformSystem.hpp b/src/esengine/ecs/TransformSystem.hppindex 904ad561a..c559e6392 100644--- a/src/esengine/ecs/TransformSystem.hpp+++ b/src/esengine/ecs/TransformSystem.hpp@@ -45,8 +45,6 @@ inline void invalidateTransformComposition() { transformMutationEpoch()++; }class TransformSystem : public System {public:- static constexpr u32 MAX_HIERARCHY_DEPTH = 256;-TransformSystem() {setPriority(-100);}@@ -137,6 +135,25 @@ private:u32 visited_ = 0;u32 serial_ = 0;bool overflowed_ = false;+ struct TraversalTask {+ Entity entity;+ const glm::mat4* parentMatrix;+ bool parentDirty;+ };+ std::vector<TraversalTask> pending_;+ std::vector<u32> traversal_stamps_;+ u32 traversal_stamp_ = 0;+ bool have_dirty_ = false;+ bool have_static_ = false;+ bool have_children_ = false;++ bool visitOnce(Entity entity) {+ const auto index = entity.index();+ if (index >= traversal_stamps_.size()) traversal_stamps_.resize(index + 1, 0);+ if (traversal_stamps_[index] == traversal_stamp_) return false;+ traversal_stamps_[index] = traversal_stamp_;+ return true;+ }/*** @brief One composition, whoever asked for it@@ -146,6 +163,10 @@ private:* past a set nobody collected.*/void compose(Registry& registry) {+ if (++traversal_stamp_ == 0) {+ std::fill(traversal_stamps_.begin(), traversal_stamps_.end(), 0);+ ++traversal_stamp_;+ }visited_ = 0;if (tracking_ && !overflowed_) changedOut_ = &changed_;updateDirtyTransforms(registry);@@ -161,31 +182,31 @@ private:void updateDirtyTransforms(Registry& registry) {dirty_to_clear_.clear();+ have_dirty_ = !registry.entitiesWith<TransformDirty>().empty();+ have_static_ = !registry.entitiesWith<TransformStatic>().empty();+ have_children_ = !registry.entitiesWith<Children>().empty();+ const bool haveParents = !registry.entitiesWith<Parent>().empty();// eachLive (no per-frame snapshot copy of the entity list): the callback// only reads/writes Transform fields and defers TransformDirty removal to// dirty_to_clear_, so it never structurally mutates the Transform pool.- registry.eachLive<Transform>([®istry, this](Entity entity, Transform& transform) {- if (!registry.has<Parent>(entity)) {- bool isStatic = registry.has<TransformStatic>(entity);- bool isDirty = registry.has<TransformDirty>(entity);+ registry.eachLive<Transform>([®istry, this, haveParents](Entity entity, Transform& transform) {+ if (!haveParents || !registry.has<Parent>(entity)) {+ bool isStatic = have_static_ && registry.has<TransformStatic>(entity);+ bool isDirty = have_dirty_ && registry.has<TransformDirty>(entity);if (isStatic && !isDirty) {auto* children = registry.tryGet<Children>(entity);if (children) {+ visitOnce(entity);for (Entity child : children->entities) {- if (registry.valid(child)) {- auto* childTransform = registry.tryGet<Transform>(child);- if (childTransform) {- updateEntityTransform(registry, child, *childTransform, transform.cachedMatrix_, false, 1);- }- }+ updateEntityTransform(registry, child, transform.cachedMatrix_, false);}}return;}- updateRootTransform(registry, entity, transform);+ updateRootTransform(registry, entity, transform, isDirty);}});@@ -196,7 +217,7 @@ private:}}- void updateRootTransform(Registry& registry, Entity entity, Transform& transform) {+ void updateRootTransform(Registry& registry, Entity entity, Transform& transform, bool localDirty) {if (changedOut_) {++visited_;if (!transform.decomposed_@@ -211,10 +232,11 @@ private:transform.worldScale = transform.scale;transform.decomposed_ = true;- if (registry.has<TransformDirty>(entity)) {+ if (localDirty) {dirty_to_clear_.push_back(entity);}+ if (!have_children_) return;auto* children = registry.tryGet<Children>(entity);if (!children || children->entities.empty()) {// A root's cachedMatrix_ is only read to transform its children, and@@ -224,74 +246,61 @@ private:}transform.cachedMatrix_ = math::compose(transform.worldPosition, transform.worldRotation, transform.worldScale);+ visitOnce(entity);for (Entity child : children->entities) {- if (registry.valid(child)) {- auto* childTransform = registry.tryGet<Transform>(child);- if (childTransform) {- updateEntityTransform(registry, child, *childTransform, transform.cachedMatrix_, true, 1);- }- }+ updateEntityTransform(registry, child, transform.cachedMatrix_, true);}}void updateEntityTransform(Registry& registry, Entity entity,- Transform& transform,- const glm::mat4& parentWorldMatrix,- bool parentDirty, u32 depth) {- if (depth >= MAX_HIERARCHY_DEPTH) {- return;- }-- bool isDirty = parentDirty || registry.has<TransformDirty>(entity);-- if (registry.has<TransformStatic>(entity) && !isDirty) {- auto* children = registry.tryGet<Children>(entity);- if (children) {- for (Entity child : children->entities) {- if (registry.valid(child)) {- auto* childTransform = registry.tryGet<Transform>(child);- if (childTransform) {- updateEntityTransform(registry, child, *childTransform, transform.cachedMatrix_, false, depth + 1);- }+ const glm::mat4& parentWorldMatrix, bool parentDirty) {+ pending_.clear();+ TraversalTask task{entity, &parentWorldMatrix, parentDirty};+ // Explicit DFS preserves child order without a depth limit or call-stack+ // growth. Per-composition stamps bound corrupt duplicate/cyclic links.+ for (;;) {+ auto* transform = registry.tryGet<Transform>(task.entity);+ if (transform && visitOnce(task.entity)) {+ const bool localDirty = have_dirty_ && registry.has<TransformDirty>(task.entity);+ const bool dirty = task.parentDirty || localDirty;+ const bool keepStatic = have_static_ && registry.has<TransformStatic>(task.entity) && !dirty;+ if (!keepStatic) {+ const auto matrix = *task.parentMatrix * math::compose(transform->position, transform->rotation, transform->scale);+ if (changedOut_) {+ ++visited_;+ if (matrix != transform->cachedMatrix_) changedOut_->push_back(task.entity);}+ transform->cachedMatrix_ = matrix;+ transform->decomposed_ = false;+ if (localDirty) dirty_to_clear_.push_back(task.entity);}- }- return;- }-- glm::mat4 localMatrix = math::compose(transform.position, transform.rotation, transform.scale);- glm::mat4 worldMatrix = parentWorldMatrix * localMatrix;-- if (changedOut_) {- ++visited_;- // `decomposed_` is not part of the output: a READ flips it (the ptr- // accessor decomposes on the way out), so testing it here reports- // every child anyone looked at as having moved.- if (worldMatrix != transform.cachedMatrix_) changedOut_->push_back(entity);- }- transform.cachedMatrix_ = worldMatrix;- transform.decomposed_ = false;-- if (isDirty && !parentDirty) {- dirty_to_clear_.push_back(entity);- }-- auto* children = registry.tryGet<Children>(entity);- if (children) {- for (Entity child : children->entities) {- if (registry.valid(child)) {- auto* childTransform = registry.tryGet<Transform>(child);- if (childTransform) {- updateEntityTransform(registry, child, *childTransform, worldMatrix, isDirty, depth + 1);+ if (auto* children = registry.tryGet<Children>(task.entity)) {+ const auto& list = children->entities;+ // Descend directly into the first child. Only siblings need a+ // stack entry; long chains do no push/pop work per node.+ for (usize i = list.size(); i > 1; --i) {+ // Transform storage is stable throughout composition; borrow+ // its cache rather than copying a matrix into every task.+ pending_.push_back({list[i - 1], &transform->cachedMatrix_, keepStatic ? false : dirty});+ }+ if (!list.empty()) {+ task = {list[0], &transform->cachedMatrix_, keepStatic ? false : dirty};+ continue;}}}+ if (pending_.empty()) break;+ task = pending_.back();+ pending_.pop_back();}}};inline bool isDescendantOf(Registry& registry, Entity entity, Entity ancestor) {+ usize remaining = registry.entityCount();while (registry.has<Parent>(entity)) {+ // Corrupt/deserialized cycles must not hang a hierarchy edit.+ if (remaining-- == 0) return true;Entity parent = registry.get<Parent>(entity).entity;if (parent == ancestor) return true;if (!registry.valid(parent)) break;@@ -300,7 +309,20 @@ inline bool isDescendantOf(Registry& registry, Entity entity, Entity ancestor) {return false;}-inline void setParent(Registry& registry, Entity child, Entity newParent) {+inline bool setParent(Registry& registry, Entity child, Entity newParent) {+ // SDK/scene documents use 0 for no entity; C++ uses UINT32_MAX. Index 0+ // is never allocated, so both null representations mean detachment.+ if (newParent.id() == 0) newParent = INVALID_ENTITY;+ if (registry.destructionPending(child) || registry.destructionPending(newParent)) return false;+ // Validate the entire proposed link BEFORE touching either half of the old+ // one. A rejected edit is a transaction with no observable changes.+ if (!registry.valid(child)) return false;+ if (newParent != INVALID_ENTITY &&+ (!registry.valid(newParent) || child == newParent || isDescendantOf(registry, newParent, child))) {+ return false;+ }+ const auto* current = registry.tryGet<Parent>(child);+ if ((current ? current->entity : INVALID_ENTITY) == newParent) return true;if (registry.has<Parent>(child)) {Entity oldParent = registry.get<Parent>(child).entity;if (registry.valid(oldParent) && registry.has<Children>(oldParent)) {@@ -319,10 +341,6 @@ inline void setParent(Registry& registry, Entity child, Entity newParent) {}if (newParent != INVALID_ENTITY && registry.valid(newParent)) {- if (child == newParent || isDescendantOf(registry, newParent, child)) {- return;- }-if (registry.has<Parent>(child)) {registry.get<Parent>(child).entity = newParent;} else {@@ -333,6 +351,12 @@ inline void setParent(Registry& registry, Entity child, Entity newParent) {registry.emplace<Children>(newParent);}auto& newChildren = registry.get<Children>(newParent).entities;+ // A childless root does not build a matrix. Its first child makes that+ // cache live, even when the parent has since been marked static.+ if (newChildren.empty() && registry.has<TransformStatic>(newParent)+ && !registry.has<TransformDirty>(newParent)) {+ registry.emplace<TransformDirty>(newParent);+ }if (std::find(newChildren.begin(), newChildren.end(), child) == newChildren.end()) {newChildren.push_back(child);}@@ -352,6 +376,8 @@ inline void setParent(Registry& registry, Entity child, Entity newParent) {registry.emplace<TransformDirty>(child);}invalidateTransformComposition();+ registry.invalidateActivityHierarchy();+ return true;}/**@@ -399,29 +425,47 @@ inline Entity getRoot(Registry& registry, Entity entity) {}inline void destroyWithChildren(Registry& registry, Entity entity) {- if (registry.has<Children>(entity)) {- auto children = registry.get<Children>(entity).entities;- for (Entity child : children) {- if (registry.valid(child)) {- destroyWithChildren(registry, child);- }+ if (!registry.valid(entity) || registry.destructionPending(entity)) return;+ std::vector<Entity> owned, postorder;+ struct Reservations {+ Registry& registry;+ std::vector<Entity>& owned;+ ~Reservations() { for (Entity e : owned) registry.releaseDestruction(e); }+ } reservations{registry, owned};+ struct Frame { Entity entity; std::vector<Entity> children; usize next = 0; };+ std::vector<Frame> stack;+ const auto enter = [&](Entity e) {+ if (!registry.valid(e) || registry.destructionPending(e)) return;+ owned.push_back(e);+ if (!registry.reserveDestruction(e)) { owned.pop_back(); return; }+ auto children = registry.has<Children>(e) ? registry.get<Children>(e).entities : std::vector<Entity>{};+ stack.push_back({e, std::move(children), 0});+ };+ enter(entity);+ // Reserve once and preserve child-list postorder. A corrupt back-edge or+ // re-entrant subtree call joins an existing owner instead of recursing.+ while (!stack.empty()) {+ auto& frame = stack.back();+ if (frame.next < frame.children.size()) {+ const Entity child = frame.children[frame.next++];+ enter(child);+ } else {+ postorder.push_back(frame.entity);+ stack.pop_back();}}-- if (registry.has<Parent>(entity)) {- Entity parent = registry.get<Parent>(entity).entity;- if (registry.valid(parent) && registry.has<Children>(parent)) {- auto& parentChildren = registry.get<Children>(parent);- auto& vec = parentChildren.entities;- auto it = std::find(vec.begin(), vec.end(), entity);- if (it != vec.end()) {- *it = vec.back();- vec.pop_back();+ for (Entity e : postorder) {+ if (!registry.valid(e)) continue;+ if (registry.has<Parent>(e)) {+ const Entity parent = registry.get<Parent>(e).entity;+ if (registry.valid(parent) && registry.has<Children>(parent)) {+ auto& children = registry.get<Children>(parent).entities;+ const auto it = std::find(children.begin(), children.end(), e);+ if (it != children.end()) { *it = children.back(); children.pop_back(); }}}+ registry.destroy(e);}-- registry.destroy(entity);}} // namespace esengine::ecsdiff --git a/src/esengine/particle/ParticleSystem.cpp b/src/esengine/particle/ParticleSystem.cppindex 686dbc975..96412f23e 100644--- a/src/esengine/particle/ParticleSystem.cpp+++ b/src/esengine/particle/ParticleSystem.cpp@@ -32,7 +32,7 @@ void ParticleSystem::update(ecs::Registry& registry, f32 dt) {// Flatten the active force fields once so the per-particle loop touches no// components. Fields are world objects, applied to world-space particles.force_fields_.clear();- auto ffView = registry.view<ecs::Transform, ecs::ParticleForceField>();+ auto ffView = registry.activeView<ecs::Transform, ecs::ParticleForceField>();for (auto ffEntity : ffView) {const auto& ff = ffView.get<ecs::ParticleForceField>(ffEntity);if (!ff.enabled || ff.strength == 0.0f) continue;@@ -51,7 +51,7 @@ void ParticleSystem::update(ecs::Registry& registry, f32 dt) {force_fields_.push_back(inst);}- auto view = registry.view<ecs::Transform, ecs::ParticleEmitter>();+ auto view = registry.activeView<ecs::Transform, ecs::ParticleEmitter>();for (auto entity : view) {const auto& emitter = view.get<ecs::ParticleEmitter>(entity);const auto& transform = view.get<ecs::Transform>(entity);diff --git a/src/esengine/renderer/draw/TextVertexFormat.hpp b/src/esengine/renderer/draw/TextVertexFormat.hppnew file mode 100644index 000000000..05183cbe7--- /dev/null+++ b/src/esengine/renderer/draw/TextVertexFormat.hpp@@ -0,0 +1,13 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+#pragma once++#include "../../core/Types.hpp"++namespace esengine {++// JS/native text submission: x, y, u, v, r, g, b, a, sdfBias.+// The boundary validator and the renderer must consume the same stride.+inline constexpr i32 TEXT_VERTEX_FLOATS = 9;++} // namespace esenginediff --git a/src/esengine/renderer/frame/RenderContext.cpp b/src/esengine/renderer/frame/RenderContext.cppindex 3d9ee6681..1737ec2bd 100644--- a/src/esengine/renderer/frame/RenderContext.cpp+++ b/src/esengine/renderer/frame/RenderContext.cpp@@ -74,8 +74,17 @@ void RenderContext::shutdown() {device_.deleteBuffer(timeUbo_);timeUbo_ = BufferHandle::Invalid;}+ if (drawParamsFallback_ != BufferHandle::Invalid) {+ device_.deleteBuffer(drawParamsFallback_);+ drawParamsFallback_ = BufferHandle::Invalid;+ }+ skinBlocks_.shutdown();+ morphBlocks_.shutdown();+ probeBlocks_.shutdown();+ instanceBlocks_.shutdown();materials_.clear(); // free per-material UBOs while the device is still valid+ materials_.setResourceManager(nullptr);lights_.free(); // free the lighting UBO while the device is still validdevice_.shutdown();diff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cppindex 1dbd80db3..a5243d29b 100644--- a/src/esengine/renderer/frame/RenderFrame.cpp+++ b/src/esengine/renderer/frame/RenderFrame.cpp@@ -758,7 +758,7 @@ void RenderFrame::renderSurface(ecs::Registry& registry, const glm::mat4& viewPrsubmitSkeletalBatch(batch.vertices.data(), static_cast<i32>(batch.vertices.size() / 8),batch.indices.data(), static_cast<i32>(batch.indices.size()),batch.textureId, batch.blendMode, &batch.transform[0][0],- batch.entity, batch.layer, batch.depth, batch.materialId);+ batch.entity, batch.layer, batch.depth, batch.materialId, batch.premultipliedColor);}draw_list_.finalize(pool_);@@ -814,7 +814,7 @@ bool RenderFrame::submitSkeletalPreviewBatch(const f32* vertices, i32 vertexCount,const u16* indices, i32 indexCount,u32 textureId, i32 blendMode, const f32* transform16,- i32 layer, f32 depth, u32 materialId+ i32 layer, f32 depth, u32 materialId, bool premultipliedColor) {auto* preview = skeletalPreview(id);if (!preview || !vertices || !indices || vertexCount < 0 || indexCount < 0) return false;@@ -825,6 +825,7 @@ bool RenderFrame::submitSkeletalPreviewBatch(batch.indices.assign(indices, indices + static_cast<usize>(indexCount));batch.textureId = textureId;batch.blendMode = blendMode;+ batch.premultipliedColor = premultipliedColor;if (transform16) std::memcpy(&batch.transform[0][0], transform16, sizeof(f32) * 16);batch.entity = preview->entity;batch.layer = layer;@@ -1013,7 +1014,7 @@ bool hasEnclosingGroup(ecs::Registry& registry, Entity entity) {void RenderFrame::buildSortingGroups(ecs::Registry& registry) {draw_list_.clearSortingGroups();- auto groups = registry.view<ecs::SortingGroup>();+ auto groups = registry.activeView<ecs::SortingGroup>();for (auto entity : groups) {const auto& group = groups.get(entity);if (!group.enabled) continue;@@ -1034,7 +1035,7 @@ void RenderFrame::buildSpriteMasks(ecs::Registry& registry) {std::vector<ResolvedMask>& masks = sprite_mask_scratch_;masks.clear();- auto maskView = registry.view<ecs::SpriteMask>();+ auto maskView = registry.activeView<ecs::SpriteMask>();for (auto entity : maskView) {const auto& mask = maskView.get(entity);if (!mask.enabled) continue;@@ -1072,7 +1073,7 @@ void RenderFrame::buildSpriteMasks(ecs::Registry& registry) {clip_state_.setStencilMask(mask_entities_scratch_[slot].id(), masks[slot].ref);}- auto spriteView = registry.view<ecs::Sprite>();+ auto spriteView = registry.activeView<ecs::Sprite>();for (auto entity : spriteView) {const auto& sprite = spriteView.get(entity);if (sprite.maskInteraction == 0 || !sprite.enabled) continue;@@ -1128,7 +1129,7 @@ void RenderFrame::collectProbes(ecs::Registry& registry) {ProbeStore& probes = context_.probes();probes.clear();- auto view = registry.view<ecs::LightProbeVolume>();+ auto view = registry.activeView<ecs::LightProbeVolume>();for (auto entity : view) {const auto& volume = view.get(entity);if (!volume.enabled) continue;@@ -1154,7 +1155,7 @@ void RenderFrame::collectProbes(ecs::Registry& registry) {*/void RenderFrame::collectOccluders(ecs::Registry& registry) {occlusion_.begin(view_projection_);- auto view = registry.view<ecs::Occluder>();+ auto view = registry.activeView<ecs::Occluder>();for (auto entity : view) {const auto& occluder = view.get(entity);if (!occluder.enabled) continue;@@ -1182,7 +1183,7 @@ void RenderFrame::collectReflections(ecs::Registry& registry) {ReflectionStore& store = context_.reflections();store.clear();- auto view = registry.view<ecs::ReflectionProbe>();+ auto view = registry.activeView<ecs::ReflectionProbe>();for (auto entity : view) {const auto& probe = view.get(entity);if (!probe.enabled || !probe.reflection.isValid()) continue;@@ -1238,7 +1239,7 @@ void RenderFrame::collectLights(ecs::Registry& registry) {// The frame's environment is decided before any light is: a directional light// following its sun needs it, and whether one does decides which irradiance// the environment lights with — so the answer cannot depend on registry order.- auto view = registry.view<ecs::Light>();+ auto view = registry.activeView<ecs::Light>();Entity skyLight{};const Environment* sky = nullptr;glm::vec3 skyScale(0.0f);@@ -1450,7 +1451,7 @@ bool RenderFrame::collectEnvironment(const ecs::Light& light, const glm::vec3& s/// shadow map covers, and what a face is tested against before it gathers. Each mesh/// contributes the box MeshPlugin culls it by, so a frustum missing this misses all.bool RenderFrame::meshWorldBounds(ecs::Registry& registry, glm::vec3& outMin, glm::vec3& outMax) {- auto meshes = registry.view<ecs::Transform, ecs::MeshRenderer>();+ auto meshes = registry.activeView<ecs::Transform, ecs::MeshRenderer>();bool any = false;for (auto entity : meshes) {const auto& mesh = meshes.get<ecs::MeshRenderer>(entity);@@ -2094,6 +2095,17 @@ u32 RenderFrame::initBatchShader() {return batchProgram({});}+u32 RenderFrame::premultipliedBatchProgram() {+ if (!premultiplied_batch_handle_) {+ const std::vector<std::string> features{"PREMULTIPLIED_COLOR"};+ batchProgram(features);+ premultiplied_batch_handle_ = &batch_variants_.at(resource::ShaderParser::variantKey(features));+ }+ // Map values survive rehash; the device may replace the program behind them.+ Shader* shader = resource_manager_.getShader(*premultiplied_batch_handle_);+ return shader ? shader->getProgramId() : 0;+}+u32 RenderFrame::batchProgram(const std::vector<std::string>& features) {const std::string key = resource::ShaderParser::variantKey(features);auto it = batch_variants_.find(key);diff --git a/src/esengine/renderer/frame/RenderFrame.hpp b/src/esengine/renderer/frame/RenderFrame.hppindex 7df2aea30..d9fd39975 100644--- a/src/esengine/renderer/frame/RenderFrame.hpp+++ b/src/esengine/renderer/frame/RenderFrame.hpp@@ -235,6 +235,7 @@ public:std::vector<u16> indices;u32 textureId = 0;i32 blendMode = 0;+ bool premultipliedColor = false;glm::mat4 transform{1.0f};Entity entity{};i32 layer = 0;@@ -253,7 +254,7 @@ public:const u16* indices, i32 indexCount,u32 textureId, i32 blendMode,const f32* transform16,- Entity entity, i32 layer, f32 depth, u32 materialId = 0+ Entity entity, i32 layer, f32 depth, u32 materialId = 0, bool premultipliedColor = false);void setStage(RenderStage stage) { current_stage_ = stage; }@@ -401,7 +402,7 @@ public:const f32* vertices, i32 vertexCount,const u16* indices, i32 indexCount,u32 textureId, i32 blendMode, const f32* transform16,- i32 layer, f32 depth, u32 materialId);+ i32 layer, f32 depth, u32 materialId, bool premultipliedColor = false);/*** Draw everything handed to @p id, and start its readback. CONSUMES the@@ -460,6 +461,7 @@ public:* as the default, so quads of any variant share the batch vertex format.*/u32 batchProgram(const std::vector<std::string>& features);+ u32 premultipliedBatchProgram();static constexpr u32 STAGE_COUNT = 4;@@ -569,6 +571,7 @@ private:/// Variant key -> the shader HANDLE. Not the program id: rebuilding the/// device changes every id, and the handle is what stays true across it.std::unordered_map<std::string, resource::ShaderHandle> batch_variants_;+ const resource::ShaderHandle* premultiplied_batch_handle_ = nullptr;TransientBufferPool pool_;DrawList draw_list_;bool linear_color_ = false;diff --git a/src/esengine/renderer/frame/RenderFrameMask.cpp b/src/esengine/renderer/frame/RenderFrameMask.cppindex e082b4123..bccea7e23 100644--- a/src/esengine/renderer/frame/RenderFrameMask.cpp+++ b/src/esengine/renderer/frame/RenderFrameMask.cpp@@ -202,7 +202,7 @@ void RenderFrame::processMasks(ecs::Registry& registry, const glm::mat4& projectclearAllClipRects();clearAllStencilMasks();- auto maskView = registry.view<ecs::UIMask>();+ auto maskView = registry.activeView<ecs::UIMask>();std::vector<Entity>& scissorMasks = mask_scissor_scratch_;std::vector<Entity>& stencilMasks = mask_stencil_scratch_;std::unordered_set<u32>& maskSet = mask_set_scratch_;diff --git a/src/esengine/renderer/frame/RenderFrameShadow2D.cpp b/src/esengine/renderer/frame/RenderFrameShadow2D.cppindex 2284c3f23..385fd5057 100644--- a/src/esengine/renderer/frame/RenderFrameShadow2D.cpp+++ b/src/esengine/renderer/frame/RenderFrameShadow2D.cpp@@ -53,7 +53,7 @@ void RenderFrame::collectShadow2D(ecs::Registry& registry) {shadow_2d_texture_id_ = 0;context_.lights().setMask2DRect(glm::vec4(0.0f));- auto casters = registry.view<ecs::Transform, ecs::ShadowCaster2D>();+ auto casters = registry.activeView<ecs::Transform, ecs::ShadowCaster2D>();for (auto entity : casters) {const auto& caster = casters.get<ecs::ShadowCaster2D>(entity);if (!caster.enabled) continue;@@ -375,7 +375,7 @@ void RenderFrame::collectShape2D(ecs::Registry& registry) {shape_2d_texture_id_ = 0;const LightConstants& lights = context_.lights().data();- auto view = registry.view<ecs::Transform, ecs::Light>();+ auto view = registry.activeView<ecs::Transform, ecs::Light>();for (auto entity : view) {if (shape_2d_lights_.size() >= MAX_SHAPE_2D_LIGHTS) break;const auto& light = view.get<ecs::Light>(entity);diff --git a/src/esengine/renderer/frame/RenderFrameSubmit.cpp b/src/esengine/renderer/frame/RenderFrameSubmit.cppindex c1283ce75..7b5baf9be 100644--- a/src/esengine/renderer/frame/RenderFrameSubmit.cpp+++ b/src/esengine/renderer/frame/RenderFrameSubmit.cpp@@ -3,6 +3,7 @@#include "./RenderFrame.hpp"#include "../draw/BatchBuilder.hpp"#include "../draw/BatchVertex.hpp"+#include "../draw/TextVertexFormat.hpp"#include "./RenderContext.hpp"#include <glm/gtc/type_ptr.hpp>@@ -48,7 +49,6 @@ void RenderFrame::submitTextBatch() {if (vertexCount <= 0 || indexCount <= 0) return;- constexpr i32 FLOATS_PER_VERTEX = 9; // x, y, u, v, r, g, b, a, sdfBiasglm::mat4 model = glm::make_mat4(transform16);u32 vBytes = static_cast<u32>(vertexCount) * sizeof(BatchVertex);@@ -56,7 +56,7 @@ void RenderFrame::submitTextBatch(auto* dst = reinterpret_cast<BatchVertex*>(pool_.vertexData(LayoutId::Batch) + vOff);for (i32 i = 0; i < vertexCount; ++i) {- const f32* v = vertices + i * FLOATS_PER_VERTEX;+ const f32* v = vertices + i * TEXT_VERTEX_FLOATS;glm::vec4 worldPos = model * glm::vec4(v[0], v[1], 0.0f, 1.0f);u32 pc = packColor(glm::vec4(v[4], v[5], v[6], v[7]));// texIndex is assigned at merge time; sdfBias rides in from the layout,@@ -85,7 +85,7 @@ void RenderFrame::submitSkeletalBatch(const u16* indices, i32 indexCount,u32 textureId, i32 blendMode,const f32* transform16,- Entity entity, i32 layer, f32 depth, u32 materialId+ Entity entity, i32 layer, f32 depth, u32 materialId, bool premultipliedColor) {if (vertexCount <= 0 || indexCount <= 0) return;@@ -93,6 +93,9 @@ void RenderFrame::submitSkeletalBatch(glm::mat4 model = glm::make_mat4(transform16);BlendMode blend = static_cast<BlendMode>(std::clamp(blendMode, 0, 5));+ const MaterialRecord* material = materialId != 0 ? context_.materials().find(materialId) : nullptr;+ const bool builtinColor = !material || material->shader == 0;+// Format the transformed vertices in place — a complex skeleton can carry many// vertices, so we avoid staging them into a temporary before the pool copy.u32 vBytes = static_cast<u32>(vertexCount) * sizeof(BatchVertex);@@ -102,14 +105,22 @@ void RenderFrame::submitSkeletalBatch(for (i32 i = 0; i < vertexCount; ++i) {const f32* v = vertices + i * FLOATS_PER_VERTEX;glm::vec4 worldPos = model * glm::vec4(v[0], v[1], 0.0f, 1.0f);- u32 pc = packColor(glm::vec4(v[4], v[5], v[6], v[7]));+ glm::vec4 color(v[4], v[5], v[6], v[7]);+ if (premultipliedColor && builtinColor) {+ // Recover straight color before 8-bit packing and the shader EOTF.+ color = color.a > 0.0f ? glm::vec4(glm::vec3(color) / color.a, color.a)+ : glm::vec4(0.0f);+ }+ u32 pc = packColor(color);dst[i] = { {worldPos.x, worldPos.y, worldPos.z}, pc, {v[2], v[3]} };}+ const u32 defaultShader = !builtinColor ? material->shader+ : premultipliedColor ? premultipliedBatchProgram() : batch_shader_id_;BatchDrawKey key{.stage = current_stage_,.layer = layer,- .shaderId = batch_shader_id_,+ .shaderId = defaultShader,.blend = blend,.textureId = textureId,.depth = depth,@@ -120,8 +131,8 @@ void RenderFrame::submitSkeletalBatch(// handle nothing registered falls back to the batch shader rather than// binding a program that was never built.if (materialId != 0) {- if (const MaterialRecord* m = context_.materials().find(materialId)) {- key.shaderId = (m->shader != 0) ? m->shader : batch_shader_id_;+ if (const MaterialRecord* m = material) {+ key.shaderId = (m->shader != 0) ? m->shader : defaultShader;key.blend = m->blend;key.materialId = materialId;key.depthTest = m->depthTest;diff --git a/src/esengine/renderer/plugins/MeshPlugin.cpp b/src/esengine/renderer/plugins/MeshPlugin.cppindex 0d5478ece..4a2f5f673 100644--- a/src/esengine/renderer/plugins/MeshPlugin.cpp+++ b/src/esengine/renderer/plugins/MeshPlugin.cpp@@ -470,7 +470,7 @@ void MeshPlugin::collect(RenderCollectContext& collect_ctx) {auto& buffers = collect_ctx.buffer_pool;auto& draw_list = collect_ctx.draw_list;auto& ctx = collect_ctx.frame_context;- auto meshView = registry.view<ecs::Transform, ecs::MeshRenderer>();+ auto meshView = registry.activeView<ecs::Transform, ecs::MeshRenderer>();// Read once: the phase is the same for every mesh this collect walks.const bool shadowDepth = ctx.purpose == RenderPurpose::ShadowDepth;diff --git a/src/esengine/renderer/plugins/ParticlePlugin.cpp b/src/esengine/renderer/plugins/ParticlePlugin.cppindex 542c4998d..f65b7e9d7 100644--- a/src/esengine/renderer/plugins/ParticlePlugin.cpp+++ b/src/esengine/renderer/plugins/ParticlePlugin.cpp@@ -73,7 +73,7 @@ void ParticlePlugin::collect(RenderCollectContext& collect_ctx) {auto& ctx = collect_ctx.frame_context;if (!particle_system_ || particle_shader_id_ == 0) return;- auto emitterView = registry.view<ecs::Transform, ecs::ParticleEmitter>();+ auto emitterView = registry.activeView<ecs::Transform, ecs::ParticleEmitter>();for (auto entity : emitterView) {if (!collect_ctx.accepts(entity)) continue;diff --git a/src/esengine/renderer/plugins/ShapePlugin.cpp b/src/esengine/renderer/plugins/ShapePlugin.cppindex 49eb40e63..fa6c1f0a8 100644--- a/src/esengine/renderer/plugins/ShapePlugin.cpp+++ b/src/esengine/renderer/plugins/ShapePlugin.cpp@@ -43,7 +43,7 @@ void ShapePlugin::collect(RenderCollectContext& collect_ctx) {auto& buffers = collect_ctx.buffer_pool;auto& draw_list = collect_ctx.draw_list;auto& ctx = collect_ctx.frame_context;- auto shapeView = registry.view<ecs::Transform, ecs::ShapeRenderer>();+ auto shapeView = registry.activeView<ecs::Transform, ecs::ShapeRenderer>();for (auto entity : shapeView) {const auto& shape = shapeView.get<ecs::ShapeRenderer>(entity);diff --git a/src/esengine/renderer/plugins/SpritePlugin.cpp b/src/esengine/renderer/plugins/SpritePlugin.cppindex f78f01f61..2053e47fa 100644--- a/src/esengine/renderer/plugins/SpritePlugin.cpp+++ b/src/esengine/renderer/plugins/SpritePlugin.cpp@@ -21,7 +21,7 @@ void SpritePlugin::collect(RenderCollectContext& collect_ctx) {auto& buffers = collect_ctx.buffer_pool;auto& draw_list = collect_ctx.draw_list;auto& ctx = collect_ctx.frame_context;- auto spriteView = registry.view<ecs::Transform, ecs::Sprite>();+ auto spriteView = registry.activeView<ecs::Transform, ecs::Sprite>();u32 litProgram = 0;diff --git a/src/esengine/renderer/plugins/TextPlugin.cpp b/src/esengine/renderer/plugins/TextPlugin.cppindex bbbb0b61e..ebbb025a1 100644--- a/src/esengine/renderer/plugins/TextPlugin.cpp+++ b/src/esengine/renderer/plugins/TextPlugin.cpp@@ -123,7 +123,7 @@ void TextPlugin::collect(RenderCollectContext& collect_ctx) {auto& buffers = collect_ctx.buffer_pool;auto& draw_list = collect_ctx.draw_list;auto& ctx = collect_ctx.frame_context;- auto textView = registry.view<ecs::Transform, ecs::BitmapText>();+ auto textView = registry.activeView<ecs::Transform, ecs::BitmapText>();for (auto entity : textView) {const auto& bt = textView.get<ecs::BitmapText>(entity);diff --git a/src/esengine/renderer/plugins/TilemapRenderPlugin.cpp b/src/esengine/renderer/plugins/TilemapRenderPlugin.cppindex ef207d100..b30577466 100644--- a/src/esengine/renderer/plugins/TilemapRenderPlugin.cpp+++ b/src/esengine/renderer/plugins/TilemapRenderPlugin.cpp@@ -160,6 +160,7 @@ void TilemapRenderPlugin::collect(RenderCollectContext& collect_ctx) {const CameraView& cam = collect_ctx.camera;for (const auto& [entity, layer] : layers) {+ if (registry.valid(entity) && !registry.isEntityActive(entity)) continue;// The TilemapLayer component is the single source of a layer's visual// metadata — the renderer reads it live each frame (so animated// tint/opacity need no sync). Every scene-driven layer has one (Tileddiff --git a/src/esengine/renderer/plugins/TrailPlugin.cpp b/src/esengine/renderer/plugins/TrailPlugin.cppindex 17e0f72b8..28f968232 100644--- a/src/esengine/renderer/plugins/TrailPlugin.cpp+++ b/src/esengine/renderer/plugins/TrailPlugin.cpp@@ -27,7 +27,7 @@ void TrailPlugin::collect(RenderCollectContext& collect_ctx) {const f32 now = trail_system_->now();- auto view = registry.view<ecs::Transform, ecs::TrailRenderer>();+ auto view = registry.activeView<ecs::Transform, ecs::TrailRenderer>();for (auto entity : view) {const auto& trail = view.get<ecs::TrailRenderer>(entity);if (!trail.enabled) continue;diff --git a/src/esengine/renderer/plugins/UIElementPlugin.cpp b/src/esengine/renderer/plugins/UIElementPlugin.cppindex 0e4333dd8..1a57a1867 100644--- a/src/esengine/renderer/plugins/UIElementPlugin.cpp+++ b/src/esengine/renderer/plugins/UIElementPlugin.cpp@@ -50,7 +50,7 @@ void UIElementPlugin::collect(RenderCollectContext& collect_ctx) {auto& buffers = collect_ctx.buffer_pool;auto& draw_list = collect_ctx.draw_list;auto& ctx = collect_ctx.frame_context;- auto uiView = registry.view<ecs::Transform, ecs::UIVisual>();+ auto uiView = registry.activeView<ecs::Transform, ecs::UIVisual>();for (auto entity : uiView) {if (!collect_ctx.accepts(entity)) continue;diff --git a/src/esengine/renderer/rhi/GLDevice.cpp b/src/esengine/renderer/rhi/GLDevice.cppindex 7f2f04700..935811cd3 100644--- a/src/esengine/renderer/rhi/GLDevice.cpp+++ b/src/esengine/renderer/rhi/GLDevice.cpp@@ -389,6 +389,13 @@ void GLDevice::resetStateCache() {}void GLDevice::shutdown() {+ // Timer queries belong to the device; the frame timer only keeps their ids.+ for (u32& query : query_names_) {+ if (query) glDeleteQueries(1, &query);+ query = 0;+ }+ query_names_.clear();+ readbacks_.clear();ES_LOG_INFO("GLDevice shutdown");}diff --git a/src/esengine/renderer/rhi/PerDrawBlocks.hpp b/src/esengine/renderer/rhi/PerDrawBlocks.hppindex 553c95dfd..170740e53 100644--- a/src/esengine/renderer/rhi/PerDrawBlocks.hpp+++ b/src/esengine/renderer/rhi/PerDrawBlocks.hpp@@ -36,6 +36,7 @@ public:/** @brief Claims the pool for blocks of @p blockSize bytes, plus the zero one. */void init(GfxDevice& device, u32 blockSize) {+ shutdown();device_ = &device;blockSize_ = blockSize;pageBytes_ = std::max(PAGE_BYTES, alignUp(blockSize));@@ -48,6 +49,20 @@ public:GfxContent::retained(), zeros.data());}+ /** @brief Releases every page and the zero block while the device is alive. */+ void shutdown() {+ if (!device_) return;+ for (const Page& page : pages_) {+ if (page.buffer != BufferHandle::Invalid) device_->deleteBuffer(page.buffer);+ }+ if (zero_ != BufferHandle::Invalid) device_->deleteBuffer(zero_);+ pages_.clear();+ zero_ = BufferHandle::Invalid;+ device_ = nullptr;+ blockSize_ = pageBytes_ = cursor_ = used_ = 0;+ page_ = 0;+ }+/** @brief Hands every range back. Called once per FRAME — see the file note. */void beginFrame() {page_ = 0;diff --git a/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp b/src/esengine/renderer/rhi/ShaderEmbeds.generated.hppindex a876dc2fe..e8b228226 100644--- a/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp+++ b/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp@@ -21,6 +21,9 @@ inline constexpr const char* BATCH = R"esshader(#pragma shader "Batch"#pragma feature ALPHA_CLIP++#pragma feature PREMULTIPLIED_COLOR+#pragma vertexlayout(location = 0) in vec3 a_position;layout(location = 1) in vec4 a_color;@@ -93,6 +96,9 @@ void main() {#elsevec4 tint = v_color;#endif+#ifdef PREMULTIPLIED_COLOR+ tint.rgb *= tint.a;+#endif#ifdef SDF@@ -204,9 +210,12 @@ struct VSOut {else if (idx == 6) { texColor = textureSampleLevel(t6, s6, v.v_texCoord, 0.0); }else { texColor = textureSampleLevel(t7, s7, v.v_texCoord, 0.0); }#ifdef ES_LINEAR- let tint = vec4f(srgbToLinear(v.v_color.rgb), v.v_color.a);+ var tint = vec4f(srgbToLinear(v.v_color.rgb), v.v_color.a);#else- let tint = v.v_color;+ var tint = v.v_color;+#endif+#ifdef PREMULTIPLIED_COLOR+ tint = vec4f(tint.rgb * tint.a, tint.a);#endif#ifdef SDFdiff --git a/src/esengine/renderer/store/MaterialStore.cpp b/src/esengine/renderer/store/MaterialStore.cppindex 63161fdf5..e8038a477 100644--- a/src/esengine/renderer/store/MaterialStore.cpp+++ b/src/esengine/renderer/store/MaterialStore.cpp@@ -17,6 +17,31 @@namespace esengine {+MaterialStore::~MaterialStore() {+ clear();+ if (resources_) resources_->clearShaderRetiredCallback(this);+}++void MaterialStore::setResourceManager(resource::ResourceManager* resources) {+ if (resources_ == resources) return;+ if (resources_) { clear(); resources_->clearShaderRetiredCallback(this); }+ resources_ = resources;+ if (resources_) resources_->setShaderRetiredCallback(this, [](void* owner, resource::ShaderHandle shader) {+ static_cast<MaterialStore*>(owner)->forgetShader(shader);+ });+}++void MaterialStore::forgetShader(resource::ShaderHandle shader) {+ layouts_.erase(shader.id());+ sources_.erase(shader.id());+ auto found = mesh_programs_.find(shader.id());+ if (found == mesh_programs_.end()) return;+ auto variants = std::move(found->second);+ mesh_programs_.erase(found);+ // Detach before returning handles: their retirement can notify this store again.+ if (resources_) for (const auto& [shape, handle] : variants) resources_->releaseShader(handle);+}+void MaterialStore::undefine(u32 materialId) {auto it = materials_.find(materialId);if (it == materials_.end()) return;@@ -32,6 +57,11 @@ void MaterialStore::clear() {}materials_.clear();layouts_.clear();+ sources_.clear();+ auto variants = std::move(mesh_programs_);+ mesh_programs_.clear();+ if (resources_) for (const auto& [source, programs] : variants)+ for (const auto& [shape, handle] : programs) resources_->releaseShader(handle);}u32 MaterialStore::meshProgram(u32 materialId, resource::ResourceManager& resources,@@ -67,14 +97,16 @@ u32 MaterialStore::variantProgram(u32 materialId, resource::ResourceManager& resconst char* what) const {const MaterialRecord* rec = find(materialId);if (!rec || !rec->shaderRef.isValid()) return 0;- const u64 key = static_cast<u64>(rec->shaderRef.id()) | shape;-- auto cached = mesh_programs_.find(key);- if (cached != mesh_programs_.end()) return cached->second;+ auto& variants = mesh_programs_[rec->shaderRef.id()];+ auto cached = variants.find(shape);+ if (cached != variants.end()) {+ const Shader* shader = resources.getShader(cached->second);+ return shader ? shader->getProgramId() : 0;+ }auto src = sources_.find(rec->shaderRef.id());if (src == sources_.end()) {- mesh_programs_[key] = 0;+ variants[shape] = {};return 0;}@@ -95,7 +127,7 @@ u32 MaterialStore::variantProgram(u32 materialId, resource::ResourceManager& resif (!parsed.vertexIsCanonical) {ES_LOG_WARN("MaterialStore: material {} writes its own vertex stage, so it cannot draw ""{} (only a shader on the engine's vertex stage can)", materialId, what);- mesh_programs_[key] = 0;+ variants[shape] = {};return 0;}// A full WGSL vertex twin is a translation of the BATCH vertex stage, frozen@@ -106,13 +138,13 @@ u32 MaterialStore::variantProgram(u32 materialId, resource::ResourceManager& res&& fullVertex != parsed.wgslStageFull.end() && fullVertex->second) {ES_LOG_WARN("MaterialStore: material {} carries a generated WGSL vertex stage, so it ""cannot draw {} — regenerate its twin", materialId, what);- mesh_programs_[key] = 0;+ variants[shape] = {};return 0;}if (!parsed.valid || vert.empty() || frag.empty()) {ES_LOG_WARN("MaterialStore: no {} variant for material {} ({})",what, materialId, parsed.valid ? "stage assembly failed" : parsed.errorMessage);- mesh_programs_[key] = 0;+ variants[shape] = {};return 0;}@@ -120,14 +152,15 @@ u32 MaterialStore::variantProgram(u32 materialId, resource::ResourceManager& resresources.preferredShaderLanguage());Shader* shader = resources.getShader(handle);if (!shader || !shader->isValid()) {- mesh_programs_[key] = 0;+ resources.releaseShader(handle);+ variants[shape] = {};return 0;}seedSamplers(*shader, parsed);// No layout of its own: uniforms pack through the material's shaderRef, and// this variant declares the same params, so its handle is never looked up.const u32 program = shader->getProgramId();- mesh_programs_[key] = program;+ variants[shape] = handle;return program;}diff --git a/src/esengine/renderer/store/MaterialStore.hpp b/src/esengine/renderer/store/MaterialStore.hppindex 7f68eb537..41ca78edd 100644--- a/src/esengine/renderer/store/MaterialStore.hpp+++ b/src/esengine/renderer/store/MaterialStore.hpp@@ -141,11 +141,16 @@ struct MaterialRecord {*/class MaterialStore {public:+ MaterialStore() = default;+ ~MaterialStore();+ MaterialStore(const MaterialStore&) = delete;+ MaterialStore& operator=(const MaterialStore&) = delete;/// The render path uses this device to create/upload/delete per-material UBOs.void setDevice(GfxDevice* device) { device_ = device; }/// Resolves texture handles at bind time; without one, texture params bind nothing.- void setResourceManager(resource::ResourceManager* resources) { resources_ = resources; }+ void setResourceManager(resource::ResourceManager* resources);+ void forgetShader(resource::ShaderHandle shader);/// The context's built-in fallbacks.void setBuiltinDefaults(TextureHandle white, TextureHandle black, TextureHandle flatNormal) {@@ -315,12 +320,18 @@ private:/// (Handle, vertex source) → the program compiled for it (0 = tried and/// failed). Mutable because compiling it is memoization: the collect path/// asks a read-only store, and the answer is the same every time.- mutable std::unordered_map<u64, u32> mesh_programs_;+ // Indexed first by source shader: retirement touches only its own variants.+ // Handles resolve to the current device program, including after recovery.+ mutable std::unordered_map<u32, std::unordered_map<u64, resource::ShaderHandle>> mesh_programs_;public:/** @brief How many material program variants have been built. A prewarm counts* what it caused by the difference, rather than by asking again. */- u32 builtVariantCount() const { return static_cast<u32>(mesh_programs_.size()); }+ u32 builtVariantCount() const {+ u32 count = 0;+ for (const auto& [shader, variants] : mesh_programs_) count += static_cast<u32>(variants.size());+ return count;+ }private:diff --git a/src/esengine/resource/ResourceManager.cpp b/src/esengine/resource/ResourceManager.cppindex b02785622..8f49a7eb1 100644--- a/src/esengine/resource/ResourceManager.cpp+++ b/src/esengine/resource/ResourceManager.cpp@@ -67,8 +67,14 @@ void ResourceManager::shutdown() {guidToTexture_.clear();textureMetadata_.clear();fonts_.clear();+ std::vector<ShaderHandle> retiredShaders;+ shaders_.forEachAlive([&](ShaderHandle handle, const Shader&) { retiredShaders.push_back(handle); });shaders_.clear();+ if (shaderRetiredCallback_) for (ShaderHandle handle : retiredShaders) shaderRetiredCallback_(shaderRetiredOwner_, handle);textures_.clear();+ std::vector<MeshHandle> retiredMeshes;+ meshes_.forEachAlive([&](MeshHandle handle, const Mesh&) { retiredMeshes.push_back(handle); });+ for (MeshHandle handle : retiredMeshes) releaseMesh(handle);vertexBuffers_.clear();indexBuffers_.clear();@@ -181,7 +187,9 @@ const Shader* ResourceManager::getShader(ShaderHandle handle) const {void ResourceManager::releaseShader(ShaderHandle handle) {if (handle.isValid()) {+ const bool final = shaders_.getRefCount(handle) == 1;shaders_.release(handle.id());+ if (final && shaderRetiredCallback_) shaderRetiredCallback_(shaderRetiredOwner_, handle);}}@@ -599,11 +607,13 @@ bool ResourceManager::realizeMesh(Mesh& mesh, ConstSpan<u8> vertexBytes, ConstSp|| ib->handle() == BufferHandle::Invalid || layoutHandle == VertexLayoutHandle::Invalid) {releaseVertexBuffer(vertices);releaseIndexBuffer(indices_handle);+ device_->deleteVertexLayout(layoutHandle);return false;}releaseVertexBuffer(previousVertices);releaseIndexBuffer(previousIndices);+ device_->deleteVertexLayout(mesh.layout);mesh.vertices = vertices;mesh.indices = indices_handle;@@ -765,8 +775,8 @@ std::vector<MeshHandle> ResourceManager::meshesAwaitingRematerialization() constvoid ResourceManager::releaseMesh(MeshHandle handle) {Mesh* mesh = meshes_.get(handle);if (!mesh) return;- // The buffers are the mesh's own, so they go with it; the layout is not, since- // createVertexLayout caches by description and other meshes share the result.+ // The RHI creates a distinct layout for each realization, owned by this mesh.+ if (device_) device_->deleteVertexLayout(mesh->layout);releaseVertexBuffer(mesh->vertices);releaseIndexBuffer(mesh->indices);// The delta texture IS the mesh's own — nothing shares it, unlike the layout.diff --git a/src/esengine/resource/ResourceManager.hpp b/src/esengine/resource/ResourceManager.hppindex 8d9e7baf4..3e6924a95 100644--- a/src/esengine/resource/ResourceManager.hpp+++ b/src/esengine/resource/ResourceManager.hpp@@ -218,6 +218,15 @@ public:*/void releaseShader(ShaderHandle handle);+ /// One renderer owns shader-derived metadata. Notify after final pool retirement.+ using ShaderRetiredCallback = void (*)(void*, ShaderHandle);+ void setShaderRetiredCallback(void* owner, ShaderRetiredCallback callback) {+ shaderRetiredOwner_ = owner; shaderRetiredCallback_ = callback;+ }+ void clearShaderRetiredCallback(void* owner) {+ if (shaderRetiredOwner_ == owner) { shaderRetiredOwner_ = nullptr; shaderRetiredCallback_ = nullptr; }+ }+/*** @brief Gets the current reference count for a shader* @param handle The shader handle@@ -695,6 +704,8 @@ public:LoaderRegistry& getLoaderRegistry() { return loaderRegistry_; }private:+ void* shaderRetiredOwner_ = nullptr;+ ShaderRetiredCallback shaderRetiredCallback_ = nullptr;ResourcePool<Shader> shaders_;ResourcePool<Texture> textures_;ResourcePool<VertexBuffer> vertexBuffers_;diff --git a/src/esengine/trail/TrailSystem.cpp b/src/esengine/trail/TrailSystem.cppindex ff05f5830..f55d3f99e 100644--- a/src/esengine/trail/TrailSystem.cpp+++ b/src/esengine/trail/TrailSystem.cpp@@ -13,7 +13,7 @@ void TrailSystem::update(ecs::Registry& registry, f32 dt) {time_ += dt;- auto view = registry.view<ecs::Transform, ecs::TrailRenderer>();+ auto view = registry.activeView<ecs::Transform, ecs::TrailRenderer>();for (auto entity : view) {const auto& trail = view.get<ecs::TrailRenderer>(entity);// Frozen (disabled) trails keep their history so re-enabling resumes thediff --git a/src/esengine/ui/UISystem.cpp b/src/esengine/ui/UISystem.cppindex 3bce5e819..c25d38c4e 100644--- a/src/esengine/ui/UISystem.cpp+++ b/src/esengine/ui/UISystem.cpp@@ -38,6 +38,7 @@ void UISystem::hitTestUpdate(Registry& registry, const PickRay& worldRay, constfor (i32 i = static_cast<i32>(nodes.size()) - 1; i >= 0; i--) {Entity entity = nodes[i].entity;+ if (!registry.isEntityActive(entity)) continue;auto* interactable = registry.tryGet<Interactable>(entity);if (!interactable || !interactable->enabled || !interactable->raycastTarget) continue;@@ -122,6 +123,7 @@ void UISystem::hitWorldContent(Registry& registry, const PickRay& ray,registry.eachLive<Sprite, Interactable>([&](Entity entity, Sprite& sprite, Interactable& interactable) {+ if (!registry.isEntityActive(entity)) return;if (!interactable.enabled || !interactable.raycastTarget) return;// The layout tree owns anything with a UINode; this pass is for the rest.if (registry.has<UINode>(entity)) return;@@ -146,6 +148,7 @@ void UISystem::hitWorldContent(Registry& registry, const PickRay& ray,registry.eachLive<MeshRenderer, Interactable>([&](Entity entity, MeshRenderer& mesh, Interactable& interactable) {+ if (!registry.isEntityActive(entity)) return;if (!interactable.enabled || !interactable.raycastTarget) return;if (!mesh.enabled) return;if (registry.has<UINode>(entity)) return;@@ -191,6 +194,7 @@ u32 UISystem::pickAll(Registry& registry, f32 worldX, f32 worldY) {for (i32 i = static_cast<i32>(nodes.size()) - 1; i >= 0; i--) {Entity entity = nodes[i].entity;+ if (!registry.isEntityActive(entity)) continue;if (!registry.has<Transform>(entity)) continue;auto* node = registry.tryGet<UINode>(entity);diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txtindex 6c317d1a2..8e3f80951 100644--- a/tests/CMakeLists.txt+++ b/tests/CMakeLists.txt@@ -4,6 +4,51 @@include_directories(${CMAKE_SOURCE_DIR}/third_party/doctest)# ECS tests+add_executable(test_skeletal_batch_color renderer/test_skeletal_batch_color.cpp)+target_include_directories(test_skeletal_batch_color PRIVATE ${CMAKE_SOURCE_DIR}/src)+add_test(NAME test_skeletal_batch_color COMMAND test_skeletal_batch_color)++add_executable(test_transform_traversal+ ecs/test_transform_traversal.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/core/Log.cpp+)+target_include_directories(test_transform_traversal PRIVATE+ ${CMAKE_SOURCE_DIR}/src+ ${CMAKE_SOURCE_DIR}/third_party/glm+)+add_test(NAME test_transform_traversal COMMAND test_transform_traversal)++add_executable(test_tween_activity+ ecs/test_tween_activity.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/animation/TweenSystem.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/core/Log.cpp+)+target_include_directories(test_tween_activity PRIVATE+ ${CMAKE_SOURCE_DIR}/src+ ${CMAKE_SOURCE_DIR}/third_party/glm+)+add_test(NAME test_tween_activity COMMAND test_tween_activity)++add_executable(test_entity_activity+ ecs/test_entity_activity.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/core/Log.cpp+)+target_include_directories(test_entity_activity PRIVATE+ ${CMAKE_SOURCE_DIR}/src+ ${CMAKE_SOURCE_DIR}/third_party/glm+)+add_test(NAME test_entity_activity COMMAND test_entity_activity)++add_executable(test_hierarchy_links+ ecs/test_hierarchy_links.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/core/Log.cpp+)+target_include_directories(test_hierarchy_links PRIVATE+ ${CMAKE_SOURCE_DIR}/src+ ${CMAKE_SOURCE_DIR}/third_party/glm+)+add_test(NAME test_hierarchy_links COMMAND test_hierarchy_links)+add_executable(test_ecsecs/test_registry.cpp)@@ -323,6 +368,20 @@ target_include_directories(test_texture_cache PRIVATE)add_test(NAME test_texture_cache COMMAND test_texture_cache)+# The real resource pool and material store against the same device boundary.+get_target_property(ES_TEXTURE_CACHE_SOURCES test_texture_cache SOURCES)+list(REMOVE_ITEM ES_TEXTURE_CACHE_SOURCES resource/test_texture_cache.cpp)+add_executable(test_material_shader_lifetime+ resource/test_material_shader_lifetime.cpp+ ${ES_TEXTURE_CACHE_SOURCES}+ ${CMAKE_SOURCE_DIR}/src/esengine/renderer/store/MaterialStore.cpp+)+target_include_directories(test_material_shader_lifetime PRIVATE+ ${CMAKE_SOURCE_DIR}/src ${CMAKE_SOURCE_DIR}/tests+ ${CMAKE_SOURCE_DIR}/third_party/glm ${CMAKE_SOURCE_DIR}/third_party/stb+)+add_test(NAME test_material_shader_lifetime COMMAND test_material_shader_lifetime)+# Persistent mesh identity across a device generation. Same shape as the texture# cache harness: the REAL ResourceManager.cpp against MockGfxDevice, so what it# asserts is the engine's invalidation and not a model of it.diff --git a/tests/aot/test_aot_host.cpp b/tests/aot/test_aot_host.cppindex f575b0c16..9c808fe5c 100644--- a/tests/aot/test_aot_host.cpp+++ b/tests/aot/test_aot_host.cpp@@ -27,11 +27,37 @@#include <cstddef>#include <cstdint>+#include <cstdlib>+#include <new>#include <cstring>#include <span>+#include <stdexcept>#include <string>#include <vector>+namespace allocation_probe {+thread_local std::size_t* current = nullptr;+struct Scope {+ std::size_t count = 0;+ std::size_t* previous = current;+ Scope() { current = &count; }+ ~Scope() { current = previous; }+};+}++// Count actual ordinary C++ allocations only inside measured call scopes.+// Doctest assertions and fixture construction stay outside those scopes.+void* operator new(std::size_t bytes) {+ if (allocation_probe::current) ++*allocation_probe::current;+ if (void* p = std::malloc(bytes == 0 ? 1 : bytes)) return p;+ throw std::bad_alloc();+}+void* operator new[](std::size_t bytes) { return ::operator new(bytes); }+void operator delete(void* p) noexcept { std::free(p); }+void operator delete[](void* p) noexcept { std::free(p); }+void operator delete(void* p, std::size_t) noexcept { std::free(p); }+void operator delete[](void* p, std::size_t) noexcept { std::free(p); }+#include "esengine/aot/AotHost.hpp"#include "esengine/aot/AotComponents.generated.hpp"#include "esengine/aot/AotModule.hpp"@@ -491,6 +517,135 @@ TEST_CASE("the dispatcher binds once and runs by index") {}}+TEST_CASE("a module owner retains its declarations after a refused replacement") {+ World w = makeWorld();+ World expected = makeWorld();+ aot::Module module;+ std::string why;+ const auto abi = aot::abiHash(ES_EXPECTED_CONTRACT_HASH);+ REQUIRE(module.open(ES_AOT_MODULE_PATH, abi, &why));+ const auto* held = module.find("MoveSystem");+ const auto contract = module.contract();+ SUBCASE("missing library") {+ CHECK_FALSE(module.open("estella-aot-missing-replacement.dll", abi, &why));+ }+ SUBCASE("wrong ABI") {+ CHECK_FALSE(module.open(ES_AOT_MODULE_PATH, abi ^ 1u, &why));+ }+ REQUIRE(module.isOpen());+ REQUIRE(module.find("MoveSystem") == held);+ CHECK(module.contract() == contract);+ aot::CallArena arena;+ aot::runBound(aot::bind(*held, componentsOf(w), resourcesOf(w)), w.entities, resourcesOf(w), arena);+ moveByHand(expected);+ for (std::size_t i = 0; i < w.entities.size(); ++i) {+ const auto* got = w.registry.tryGet<ecs::Transform>(Entity::fromRaw(w.entities[i]));+ const auto* want = expected.registry.tryGet<ecs::Transform>(Entity::fromRaw(expected.entities[i]));+ CHECK(got->position.x == want->position.x);+ CHECK(got->position.y == want->position.y);+ }+}++TEST_CASE("failed module replacement preserves the running dispatcher") {+ World w = makeWorld();+ World expected = makeWorld();+ aot::Dispatcher dispatcher;+ std::string why;+ const auto abi = aot::abiHash(ES_EXPECTED_CONTRACT_HASH);+ REQUIRE(dispatcher.install(ES_AOT_MODULE_PATH, abi, componentsOf(w), resourcesOf(w), &why));+ const auto index = dispatcher.indexOf("MoveSystem");+ const auto contract = dispatcher.contract();+ dispatcher.run(index, w.entities, resourcesOf(w));+ moveByHand(expected);+ SUBCASE("missing replacement library") {+ CHECK_FALSE(dispatcher.install("estella-aot-missing-replacement.dll", abi,+ componentsOf(w), resourcesOf(w), &why));+ CHECK_FALSE(why.empty());+ }+ SUBCASE("replacement with the wrong ABI") {+ CHECK_FALSE(dispatcher.install(ES_AOT_MODULE_PATH, abi ^ 1u,+ componentsOf(w), resourcesOf(w), &why));+ CHECK_FALSE(why.empty());+ }+ SUBCASE("replacement binding throws") {+ const aot::ComponentLookup throws = [](const char*) -> aot::ComponentAt {+ throw std::runtime_error("binding failed");+ };+ CHECK_THROWS_AS(dispatcher.install(ES_AOT_MODULE_PATH, abi, throws, resourcesOf(w), &why), std::runtime_error);+ }+ REQUIRE(dispatcher.count() == 1u);+ CHECK(dispatcher.contract() == contract);+ REQUIRE(dispatcher.boundAt(index));+ CHECK(std::strcmp(dispatcher.nameAt(index), "MoveSystem") == 0);+ dispatcher.run(index, w.entities, resourcesOf(w));+ moveByHand(expected);+ for (std::size_t i = 0; i < w.entities.size(); ++i) {+ const auto* got = w.registry.tryGet<ecs::Transform>(Entity::fromRaw(w.entities[i]));+ const auto* want = expected.registry.tryGet<ecs::Transform>(Entity::fromRaw(expected.entities[i]));+ CHECK(got->position.x == want->position.x);+ CHECK(got->position.y == want->position.y);+ }+}++TEST_CASE("successful replacement commits new bindings after a refused module") {+ World old = makeWorld();+ World next = makeWorld();+ World expected = makeWorld();+ aot::Dispatcher dispatcher;+ std::string why;+ const auto abi = aot::abiHash(ES_EXPECTED_CONTRACT_HASH);+ REQUIRE(dispatcher.install(ES_AOT_MODULE_PATH, abi, componentsOf(old), resourcesOf(old), &why));+ dispatcher.run(dispatcher.indexOf("MoveSystem"), old.entities, resourcesOf(old));+ const auto oldX = old.registry.tryGet<ecs::Transform>(Entity::fromRaw(old.entities[0]))->position.x;+ CHECK_FALSE(dispatcher.install(ES_AOT_MODULE_PATH, abi ^ 1u, componentsOf(next), resourcesOf(next), &why));+ REQUIRE(dispatcher.install(ES_AOT_MODULE_PATH, abi, componentsOf(next), resourcesOf(next), &why));+ dispatcher.run(dispatcher.indexOf("MoveSystem"), next.entities, resourcesOf(next));+ moveByHand(expected);+ for (std::size_t i = 0; i < next.entities.size(); ++i) {+ const auto* got = next.registry.tryGet<ecs::Transform>(Entity::fromRaw(next.entities[i]));+ const auto* want = expected.registry.tryGet<ecs::Transform>(Entity::fromRaw(expected.entities[i]));+ CHECK(got->position.x == want->position.x);+ CHECK(got->position.y == want->position.y);+ }+ CHECK(old.registry.tryGet<ecs::Transform>(Entity::fromRaw(old.entities[0]))->position.x == oldX);+}++TEST_CASE("rejected replacements release their library references") {+#ifdef _WIN32+ REQUIRE(::GetModuleHandleA(ES_AOT_MODULE_PATH) == nullptr);+#endif+ World w = makeWorld();+ World expected = makeWorld();+ {+ aot::Dispatcher dispatcher;+ std::string why;+ const auto abi = aot::abiHash(ES_EXPECTED_CONTRACT_HASH);+ REQUIRE(dispatcher.install(ES_AOT_MODULE_PATH, abi, componentsOf(w), resourcesOf(w), &why));+ const aot::ComponentLookup throws = [](const char*) -> aot::ComponentAt {+ throw std::runtime_error("binding failed");+ };+ for (int attempt = 0; attempt < 256; ++attempt) {+ CHECK_FALSE(dispatcher.install(ES_AOT_MODULE_PATH, abi ^ 1u,+ componentsOf(w), resourcesOf(w), &why));+ CHECK_THROWS_AS(dispatcher.install(ES_AOT_MODULE_PATH, abi, throws,+ resourcesOf(w), &why), std::runtime_error);+ }+ REQUIRE(dispatcher.count() == 1u);+ dispatcher.run(dispatcher.indexOf("MoveSystem"), w.entities, resourcesOf(w));+ moveByHand(expected);+ for (std::size_t i = 0; i < w.entities.size(); ++i) {+ const auto* got = w.registry.tryGet<ecs::Transform>(Entity::fromRaw(w.entities[i]));+ const auto* want = expected.registry.tryGet<ecs::Transform>(Entity::fromRaw(expected.entities[i]));+ CHECK(got->position.x == want->position.x);+ CHECK(got->position.y == want->position.y);+ }+ }+#ifdef _WIN32+ // No loader reference from any rejected candidate may outlive the owner.+ CHECK(::GetModuleHandleA(ES_AOT_MODULE_PATH) == nullptr);+#endif+}+TEST_CASE("a system this host cannot name is left unbound, not refused") {World w = makeWorld();aot::Dispatcher dispatcher;@@ -836,6 +991,151 @@ TEST_CASE("a table packed against a standing world is not packed again") {CHECK(xf(w, w.entities[1])->position.x != afterFirst);}+#ifdef ES_AOT_MODULE_PATH+TEST_CASE("a warmed dispatcher refuses a resource that disappeared and recovers when reported") {+ World w = makeWorld();+ aot::Dispatcher dispatcher;+ std::string why;+ REQUIRE(dispatcher.install(ES_AOT_MODULE_PATH, aot::abiHash(ES_EXPECTED_CONTRACT_HASH), componentsOf(w), resourcesOf(w), &why, candidatesOf(w)));+ const auto index = dispatcher.indexOf("MoveSystem");+ const aot::WorldStamp stamp{w.registry.layoutEpoch(), true};+ dispatcher.run(index, w.everyEntity(), resourcesOf(w), stamp);+ const float held = xf(w, w.entities[1])->position.x;+ const aot::ResourceLookup absent = [](const char*) -> void* { return nullptr; };+ CHECK(dispatcher.run(index, w.everyEntity(), absent, stamp).empty());+ CHECK_FALSE(dispatcher.boundAt(index));+ CHECK(xf(w, w.entities[1])->position.x == held);+ CHECK(dispatcher.run(index, w.everyEntity(), absent, stamp).empty());+ CHECK_FALSE(dispatcher.boundAt(index));+ dispatcher.run(index, w.everyEntity(), resourcesOf(w), stamp);+ CHECK(dispatcher.boundAt(index));+ CHECK(xf(w, w.entities[1])->position.x != held);+}++TEST_CASE("candidate sidecar pairing is refused before replacing a warm dispatcher") {+ World old = makeWorld(), next = makeWorld();+ aot::Dispatcher dispatcher;+ std::string why;+ const auto abi = aot::abiHash(ES_EXPECTED_CONTRACT_HASH);+ REQUIRE(dispatcher.install(ES_AOT_MODULE_PATH, abi, componentsOf(old), resourcesOf(old), &why, candidatesOf(old)));+ const auto contract = dispatcher.contract();+ REQUIRE(contract != 0);+ const auto index = dispatcher.indexOf("MoveSystem");+ const aot::WorldStamp stamp{old.registry.layoutEpoch(), true};+ dispatcher.run(index, old.everyEntity(), resourcesOf(old), stamp);+ const float before = xf(old, old.entities[1])->position.x;+ const float nextBefore = xf(next, next.entities[1])->position.x;+ int binds = 0;+ const aot::ComponentLookup lookup = [&](const char* name) { ++binds; return componentsOf(next)(name); };+ for (const auto wrong : {std::uint64_t{0}, contract ^ std::uint64_t{1}}) {+ CHECK_FALSE(dispatcher.install(ES_AOT_MODULE_PATH, abi, lookup, resourcesOf(next), &why, candidatesOf(next), wrong));+ CHECK(why.find("different builds") != std::string::npos);+ CHECK(dispatcher.contract() == contract);+ CHECK(binds == 0);+ dispatcher.run(index, old.everyEntity(), resourcesOf(old), stamp);+ CHECK(dispatcher.rowsPacked(index) == 0u);+ }+ CHECK(xf(old, old.entities[1])->position.x != before);+ const float held = xf(old, old.entities[1])->position.x;+ REQUIRE(dispatcher.install(ES_AOT_MODULE_PATH, abi, componentsOf(next), resourcesOf(next), &why, candidatesOf(next), contract));+ dispatcher.run(dispatcher.indexOf("MoveSystem"), next.everyEntity(), resourcesOf(next), {next.registry.layoutEpoch(), true});+ CHECK(xf(old, old.entities[1])->position.x == held);+ CHECK(xf(next, next.entities[1])->position.x != nextBefore);+}+#endif++TEST_CASE("warmed compiled calls allocate no scratch even when rows must repack") {+ World w = makeWorld();+ const auto bound = aot::bind(*declOf("MoveSystem"), componentsOf(w), resourcesOf(w), candidatesOf(w));+ const auto resources = resourcesOf(w);+ aot::CallArena arena;+ aot::WorldStamp stamp{w.registry.layoutEpoch(), true};+ SUBCASE("known stable world") {}+ SUBCASE("unknown world stamp") { stamp = {}; }+ for (int i = 0; i < 8; ++i) aot::runBound(bound, {}, resources, arena, stamp);+ std::size_t allocations = 0;+ const float before = xf(w, w.entities[1])->position.x;+ {+ allocation_probe::Scope measured;+ for (int i = 0; i < 256; ++i) aot::runBound(bound, {}, resources, arena, stamp);+ allocations = measured.count;+ }+ CHECK(allocations == 0u);+ CHECK(xf(w, w.entities[1])->position.x != before);+ CHECK(arena.rowsPacked() == (stamp.known ? 0u : w.entities.size()));+}++TEST_CASE("scratch reuse supports changing query counts and fresh resource addresses") {+ World w = makeWorld(), expected = makeWorld();+ const auto single = aot::bind(*declOf("MoveSystem"), componentsOf(w), resourcesOf(w), candidatesOf(w));+ auto multiple = single;+ multiple.queries.push_back(single.queries[0]);+ multiple.resourceNames.push_back("Time");+ TimeRow alternate{1.0 / 120.0};+ bool alternateNow = false;+ std::size_t lookups = 0;+ const aot::ResourceLookup resources = [&](const char*) -> void* { ++lookups; return alternateNow ? &alternate : &w.time; };+ aot::CallArena arena;+ // Warm both shapes without changing the scene used by the oracle.+ const double delta = w.time.delta;+ w.time.delta = 0;+ aot::runBound(multiple, {}, resources, arena);+ aot::runBound(single, {}, resources, arena);+ w.time.delta = delta;+ lookups = 0;+ std::size_t allocations = 0;+ {+ allocation_probe::Scope measured;+ for (int i = 0; i < 256; ++i) {+ alternateNow = (i % 2) == 0;+ aot::runBound(alternateNow ? multiple : single, {}, resources, arena);+ }+ allocations = measured.count;+ }+ CHECK(allocations == 0u);+ CHECK(lookups == 384u);+ CHECK(arena.rowsPacked() == w.entities.size());+ for (int i = 0; i < 256; ++i) {+ expected.time.delta = (i % 2) == 0 ? alternate.delta : delta;+ moveByHand(expected);+ }+ for (std::size_t i = 0; i < w.entities.size(); ++i) {+ CHECK(xf(w, w.entities[i])->position.x == xf(expected, expected.entities[i])->position.x);+ CHECK(xf(w, w.entities[i])->position.y == xf(expected, expected.entities[i])->position.y);+ }+}++#ifdef ES_AOT_MODULE_PATH+TEST_CASE("a warmed actual DLL dispatcher allocates no frame scratch") {+ World w = makeWorld(), expected = makeWorld();+ aot::Dispatcher dispatcher;+ std::string why;+ const auto resources = resourcesOf(w);+ REQUIRE(dispatcher.install(ES_AOT_MODULE_PATH, aot::abiHash(ES_EXPECTED_CONTRACT_HASH), componentsOf(w), resources, &why, candidatesOf(w)));+ const auto index = dispatcher.indexOf("MoveSystem");+ aot::WorldStamp stamp{w.registry.layoutEpoch(), true};+ SUBCASE("cached rows") {}+ SUBCASE("repacked rows") { stamp = {}; }+ const double delta = w.time.delta;+ w.time.delta = 0;+ for (int i = 0; i < 8; ++i) dispatcher.run(index, {}, resources, stamp);+ w.time.delta = delta;+ std::size_t allocations = 0;+ {+ allocation_probe::Scope measured;+ for (int i = 0; i < 256; ++i) dispatcher.run(index, {}, resources, stamp);+ allocations = measured.count;+ }+ CHECK(allocations == 0u);+ CHECK(dispatcher.rowsPacked(index) == (stamp.known ? 0u : w.entities.size()));+ for (int i = 0; i < 256; ++i) moveByHand(expected);+ for (std::size_t i = 0; i < w.entities.size(); ++i) {+ CHECK(xf(w, w.entities[i])->position.x == xf(expected, expected.entities[i])->position.x);+ CHECK(xf(w, w.entities[i])->position.y == xf(expected, expected.entities[i])->position.y);+ }+}+#endif+TEST_CASE("an unknown stamp is never the same world twice") {World w = makeWorld();const aot::BoundSystem bound = aot::bind(*declOf("MoveSystem"), componentsOf(w),diff --git a/tests/bindings/test_boundary_span.cpp b/tests/bindings/test_boundary_span.cppindex 4f8b90fee..b28459198 100644--- a/tests/bindings/test_boundary_span.cpp+++ b/tests/bindings/test_boundary_span.cpp@@ -9,12 +9,33 @@#include <doctest.h>#include "esengine/bindings/BoundarySpan.hpp"+#include "esengine/renderer/draw/TextVertexFormat.hpp"#include <cstdint>#include <vector>using namespace esengine;+TEST_CASE("text vertex boundary includes the SDF bias of the final vertex") {+ constexpr u64 count = 4;+#ifdef __EMSCRIPTEN__+ const auto end = static_cast<uintptr_t>(emscripten_get_heap_size());+ const auto ptr = end - count * TEXT_VERTEX_FLOATS * sizeof(f32);+ CHECK(boundarySpan<f32>(ptr, count * TEXT_VERTEX_FLOATS, "text.complete") != nullptr);+ // Leave room for the old eight-float format, but not the actual nine-float one.+ const auto truncated = end - count * 8 * sizeof(f32);+ CHECK(boundarySpan<f32>(truncated, count * TEXT_VERTEX_FLOATS, "text.truncated") == nullptr);+#else+ std::vector<f32> buffer(count * TEXT_VERTEX_FLOATS);+ const auto ptr = reinterpret_cast<uintptr_t>(buffer.data());+ setBoundaryRegion(ptr, buffer.size() * sizeof(f32));+ CHECK(boundarySpan<f32>(ptr, count * TEXT_VERTEX_FLOATS, "text.complete") != nullptr);+ setBoundaryRegion(ptr, count * 8 * sizeof(f32));+ CHECK(boundarySpan<f32>(ptr, count * TEXT_VERTEX_FLOATS, "text.truncated") == nullptr);+ setBoundaryRegion(0, 0);+#endif+}+TEST_CASE("valid span inside the heap passes through typed") {std::vector<f32> buf(64, 1.5f);auto ptr = reinterpret_cast<uintptr_t>(buf.data());diff --git a/tests/ecs/test_entity_activity.cpp b/tests/ecs/test_entity_activity.cppnew file mode 100644index 000000000..3eccccd74--- /dev/null+++ b/tests/ecs/test_entity_activity.cpp@@ -0,0 +1,82 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN+#include <doctest.h>+#include "esengine/ecs/TransformSystem.hpp"++using namespace esengine;+using namespace esengine::ecs;+struct Sample { int value = 1; };++TEST_CASE("activity is derived without overwriting a child's switch") {+ Registry r;+ const auto root = r.create(), child = r.create(), leaf = r.create();+ setParent(r, child, root); setParent(r, leaf, child);+ r.setEntityEnabled(root, false);+ CHECK_FALSE(r.isEntityActive(leaf));+ r.setEntityEnabled(child, false);+ r.setEntityEnabled(root, true);+ CHECK(r.isEntityActive(root));+ CHECK_FALSE(r.isEntityActive(leaf));+ r.setEntityEnabled(child, true);+ CHECK(r.isEntityActive(leaf));+}+TEST_CASE("reparenting and detachment invalidate the derived closure") {+ Registry r;+ const auto off = r.create(), on = r.create(), child = r.create();+ r.setEntityEnabled(off, false); setParent(r, child, off);+ CHECK_FALSE(r.isEntityActive(child));+ setParent(r, child, on); CHECK(r.isEntityActive(child));+ setParent(r, child, off); CHECK_FALSE(r.isEntityActive(child));+ setParent(r, child, INVALID_ENTITY); CHECK(r.isEntityActive(child));+}+TEST_CASE("active views filter single, multiple, snapshot and live iteration") {+ Registry r;+ const auto on = r.create(), off = r.create();+ for (auto e : {on, off}) { r.emplace<Sample>(e); r.emplace<Transform>(e); }+ r.setEntityEnabled(off, false);+ CHECK(r.view<Sample>().size() == 2);+ int count = 0;+ for (auto e : r.activeView<Sample>()) { CHECK(e == on); ++count; }+ CHECK(count == 1);+ count = 0;+ r.activeView<Sample, Transform>().each([&](Entity e, Sample&, Transform&) { CHECK(e == on); ++count; });+ CHECK(count == 1);+ count = 0;+ r.activeView<Sample>().eachLive([&](Sample&) { ++count; });+ CHECK(count == 1);+ count = 0;+ r.activeView<Sample>().each([&](Sample&) { ++count; });+ r.activeView<Sample>().each([&](Entity e) { CHECK(e == on); ++count; });+ r.activeView<Sample>().eachLive([&](Entity e, Sample&) { CHECK(e == on); ++count; });+ r.activeView<Sample>().eachLive([&](Entity e) { CHECK(e == on); ++count; });+ CHECK(count == 4);+}+TEST_CASE("destruction and clear do not disable a recycled slot") {+ Registry r;+ const auto old = r.create();+ r.setEntityEnabled(old, false); r.destroy(old);+ const auto replacement = r.create();+ CHECK(replacement.index() == old.index());+ CHECK(r.isEntityActive(replacement));+ CHECK_FALSE(r.isEntityActive(old));+ CHECK_FALSE(r.setEntityEnabled(old, false));+ r.setEntityEnabled(replacement, false); r.clear();+ CHECK(r.isEntityActive(r.create()));+}+TEST_CASE("a deep chain resolves iteratively and responds to native component writes") {+ Registry r;+ const auto root = r.create();+ auto last = root;+ for (int i = 0; i < 50000; ++i) { const auto child = r.create(); r.emplace<Parent>(child, last); last = child; }+ r.setEntityEnabled(root, false);+ CHECK_FALSE(r.isEntityActive(last));+ r.remove<Parent>(last); CHECK(r.isEntityActive(last));+ r.emplaceOrReplace<Parent>(last, root); CHECK_FALSE(r.isEntityActive(last));+}+TEST_CASE("unrelated entity churn leaves the all-active epoch stable") {+ Registry r;+ const auto epoch = r.activityEpoch();+ const auto e = r.create(); r.destroy(e);+ CHECK(r.activityEpoch() == epoch);+}diff --git a/tests/ecs/test_hierarchy_links.cpp b/tests/ecs/test_hierarchy_links.cppnew file mode 100644index 000000000..d365cdad1--- /dev/null+++ b/tests/ecs/test_hierarchy_links.cpp@@ -0,0 +1,155 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN+#include <doctest.h>+#include "esengine/ecs/TransformSystem.hpp"++using namespace esengine;+using namespace esengine::ecs;++TEST_CASE("rejected hierarchy edits preserve the existing link") {+ Registry r;+ const auto root = r.create(), child = r.create(), leaf = r.create();+ REQUIRE(setParent(r, child, root));+ REQUIRE(setParent(r, leaf, child));+ const auto epoch = transformMutationEpoch();+ CHECK_FALSE(setParent(r, child, child));+ CHECK_FALSE(setParent(r, child, leaf));+ const auto stale = r.create();+ r.destroy(stale);+ CHECK_FALSE(setParent(r, child, stale));+ CHECK_FALSE(setParent(r, stale, root));+ CHECK(r.get<Parent>(child).entity == root);+ CHECK(r.get<Children>(root).entities == std::vector<Entity>{child});+ CHECK(transformMutationEpoch() == epoch);+}++TEST_CASE("repeated parenting does not reorder siblings or invalidate composition") {+ Registry r;+ const auto root = r.create(), a = r.create(), b = r.create();+ REQUIRE(setParent(r, a, root));+ REQUIRE(setParent(r, b, root));+ const auto epoch = transformMutationEpoch();+ CHECK(setParent(r, a, root));+ CHECK(r.get<Children>(root).entities == std::vector<Entity>{a, b});+ CHECK(transformMutationEpoch() == epoch);+}++TEST_CASE("both wire null representations detach") {+ Registry r;+ const auto root = r.create(), child = r.create();+ for (const Entity sentinel : {Entity::fromRaw(0), INVALID_ENTITY}) {+ REQUIRE(setParent(r, child, root));+ CHECK(setParent(r, child, sentinel));+ CHECK_FALSE(r.has<Parent>(child));+ CHECK(r.get<Children>(root).entities.empty());+ }+}++TEST_CASE("an existing corrupt ancestor cycle is rejected without hanging") {+ Registry r;+ const auto a = r.create(), b = r.create(), child = r.create();+ // Raw native component writes can bypass the hierarchy transaction. The+ // public operation must fail safely even when handed such a damaged tree.+ r.emplace<Parent>(a, b);+ r.emplace<Parent>(b, a);+ CHECK_FALSE(setParent(r, child, a));+ CHECK_FALSE(r.has<Parent>(child));+ CHECK_FALSE(r.has<Children>(a));+}++TEST_CASE("subtree destruction is iterative and children precede their parents") {+ Registry r;+ std::vector<Entity> ids, events;+ constexpr usize count = 20000;+ ids.reserve(count);+ for (usize i = 0; i < count; ++i) {+ const auto e = r.create();+ ids.push_back(e);+ if (i != 0) {+ // A valid chain constructed directly so this test measures teardown,+ // not the separate ancestry checks charged by setParent.+ r.emplace<Parent>(e, ids[i - 1]);+ r.emplace<Children>(ids[i - 1]).entities.push_back(e);+ }+ }+ auto connection = r.onDestroy([&](Entity e) { events.push_back(e); });+ destroyWithChildren(r, ids.front());+ CHECK(r.entityCount() == 0);+ std::reverse(ids.begin(), ids.end());+ CHECK(events == ids);+}++TEST_CASE("subtree callbacks cannot recursively destroy ancestors or attach children to them") {+ Registry r;+ const auto root = r.create(), child = r.create(), survivor = r.create();+ REQUIRE(setParent(r, child, root));+ std::vector<Entity> events;+ auto connection = r.onDestroy([&](Entity e) {+ events.push_back(e);+ if (e == child) {+ destroyWithChildren(r, root);+ CHECK(r.valid(root)); // reserved, still waiting for this child's callbacks+ CHECK_FALSE(setParent(r, survivor, root));+ }+ });+ destroyWithChildren(r, root);+ CHECK(events == std::vector<Entity>{child, root});+ CHECK(r.entityCount() == 1);+ CHECK_FALSE(r.has<Parent>(survivor));+ CHECK(r.valid(survivor));+}++TEST_CASE("a corrupt child back-edge is destroyed once and reservations do not survive teardown") {+ Registry r;+ const auto root = r.create(), child = r.create();+ REQUIRE(setParent(r, child, root));+ r.emplace<Children>(child).entities.push_back(root);+ usize callbacks = 0;+ auto connection = r.onDestroy([&](Entity) { ++callbacks; });+ destroyWithChildren(r, root);+ CHECK(r.entityCount() == 0);+ CHECK(callbacks == 2);+ CHECK_FALSE(r.destructionPending(root));+ CHECK_FALSE(r.destructionPending(child));+ const auto a = r.create(), b = r.create();+ CHECK(setParent(r, b, a));+}++TEST_CASE("an old teardown owner cannot release a new generation's reservation") {+ Registry r;+ const auto old = r.create();+ REQUIRE(r.reserveDestruction(old));+ CHECK_FALSE(r.reserveDestruction(old));+ r.destroy(old);+ const auto fresh = r.create();+ REQUIRE(fresh.index() == old.index());+ REQUIRE(fresh != old);+ REQUIRE(r.reserveDestruction(fresh));+ r.releaseDestruction(old);+ CHECK(r.destructionPending(fresh));+ const auto parent = r.create();+ CHECK_FALSE(setParent(r, fresh, parent));+ r.releaseDestruction(fresh);+ CHECK(setParent(r, fresh, parent));+ CHECK_FALSE(r.reserveDestruction(old));+ CHECK_FALSE(r.reserveDestruction(INVALID_ENTITY));+}++TEST_CASE("subtree finalization preserves a nested reservation in a reused child slot") {+ Registry r;+ const auto root = r.create(), child = r.create();+ REQUIRE(setParent(r, child, root));+ Entity fresh = INVALID_ENTITY;+ auto connection = r.onDestroy([&](Entity e) {+ if (e != root) return;+ fresh = r.create();+ REQUIRE(fresh.index() == child.index());+ CHECK(r.reserveDestruction(fresh));+ });+ destroyWithChildren(r, root);+ CHECK(r.valid(fresh));+ CHECK(r.destructionPending(fresh));+ r.releaseDestruction(fresh);+ CHECK_FALSE(r.destructionPending(fresh));+}diff --git a/tests/ecs/test_transform_traversal.cpp b/tests/ecs/test_transform_traversal.cppnew file mode 100644index 000000000..366ff449f--- /dev/null+++ b/tests/ecs/test_transform_traversal.cpp@@ -0,0 +1,113 @@+#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN+#include <doctest.h>+#include "esengine/ecs/TransformSystem.hpp"+using namespace esengine;+using namespace esengine::ecs;++TEST_CASE("valid deep hierarchies compose every descendant") {+ Registry r; TransformSystem system;+ Entity parent = INVALID_ENTITY, leaf;+ for (int i = 0; i < 50000; ++i) {+ leaf = r.create();+ r.emplace<Transform>(leaf).position.x = 1;+ if (parent != INVALID_ENTITY) {+ r.emplace<Parent>(leaf).entity = parent;+ r.emplace<Children>(parent).entities.push_back(leaf);+ }+ parent = leaf;+ }+ system.ensureComposed(r);+ auto& t = r.get<Transform>(leaf); t.ensureDecomposed();+ CHECK(t.worldPosition.x == doctest::Approx(50000));+}++TEST_CASE("corrupted child links cannot repeat a traversal forever") {+ Registry r; TransformSystem system;+ auto root = r.create(), child = r.create();+ r.emplace<Transform>(root).position.x = 3;+ r.emplace<Transform>(child).position.x = 2;+ setParent(r, child, root);+ r.get<Children>(root).entities.push_back(child);+ r.emplace<Children>(child).entities.push_back(root);+ system.setChangeTracking(true);+ system.ensureComposed(r);+ r.get<Transform>(child).ensureDecomposed();+ CHECK(r.get<Transform>(child).worldPosition.x == doctest::Approx(5));+ CHECK(system.visited() == 2);+}++TEST_CASE("static ancestors preserve cached matrices while dirty descendants update") {+ Registry r; TransformSystem system;+ auto root = r.create(), child = r.create(), leaf = r.create();+ r.emplace<Transform>(root).position.x = 10;+ r.emplace<Transform>(child).position.x = 3;+ r.emplace<Transform>(leaf).position.x = 2;+ setParent(r, child, root); setParent(r, leaf, child);+ system.ensureComposed(r);+ CHECK_FALSE(r.has<TransformDirty>(child));+ CHECK_FALSE(r.has<TransformDirty>(leaf));+ r.emplace<TransformStatic>(root); r.emplace<TransformStatic>(child);+ r.get<Transform>(child).position.x = 7;+ r.emplace<TransformDirty>(child);+ invalidateTransformComposition(); system.ensureComposed(r);+ r.get<Transform>(leaf).ensureDecomposed();+ CHECK(r.get<Transform>(leaf).worldPosition.x == doctest::Approx(19));+ CHECK_FALSE(r.has<TransformDirty>(child));+ const auto serial = system.compositionSerial();+ system.ensureComposed(r); CHECK(system.compositionSerial() == serial);+}++TEST_CASE("traversal stamps are independent across compositions and registries") {+ TransformSystem system;+ for (int i = 0; i < 3; ++i) {+ Registry r;+ auto root = r.create(), child = r.create();+ r.emplace<Transform>(root).position.x = i * 10;+ r.emplace<Transform>(child).position.x = 2;+ setParent(r, child, root);+ system.ensureComposed(r);+ r.get<Transform>(child).ensureDecomposed();+ CHECK(r.get<Transform>(child).worldPosition.x == doctest::Approx(i * 10 + 2));+ r.get<Transform>(root).position.x += 5;+ invalidateTransformComposition(); system.ensureComposed(r);+ r.get<Transform>(child).ensureDecomposed();+ CHECK(r.get<Transform>(child).worldPosition.x == doctest::Approx(i * 10 + 7));+ }+}++TEST_CASE("a static childless root builds its matrix when its first child arrives") {+ Registry r; TransformSystem system;+ auto root = r.create(); r.emplace<Transform>(root).position.x = 10;+ system.ensureComposed(r);+ r.emplace<TransformStatic>(root);+ auto child = r.create(); r.emplace<Transform>(child).position.x = 3;+ setParent(r, child, root);+ system.ensureComposed(r);+ r.get<Transform>(child).ensureDecomposed();+ CHECK(r.get<Transform>(child).worldPosition.x == doctest::Approx(13));+ CHECK_FALSE(r.has<TransformDirty>(root));+ CHECK_FALSE(r.has<TransformDirty>(child));+}++TEST_CASE("siblings retain their own parent matrices during iterative traversal") {+ Registry r; TransformSystem system;+ auto root = r.create();+ r.emplace<Transform>(root).position.x = 10;+ r.get<Transform>(root).scale.x = 2;+ for (int offset : {1, 4}) {+ auto child = r.create(), leaf = r.create();+ r.emplace<Transform>(child).position.x = offset;+ r.emplace<Transform>(leaf).position.x = 3;+ setParent(r, child, root); setParent(r, leaf, child);+ }+ system.setChangeTracking(true);+ system.ensureComposed(r);+ const auto& siblings = r.get<Children>(root).entities;+ auto left = r.get<Children>(siblings[0]).entities[0];+ auto right = r.get<Children>(siblings[1]).entities[0];+ r.get<Transform>(left).ensureDecomposed(); r.get<Transform>(right).ensureDecomposed();+ CHECK(r.get<Transform>(left).worldPosition.x == doctest::Approx(18));+ CHECK(r.get<Transform>(right).worldPosition.x == doctest::Approx(24));+ const std::vector<Entity> expected{root, siblings[0], left, siblings[1], right};+ CHECK(system.pendingChanges() == expected);+}diff --git a/tests/ecs/test_tween_activity.cpp b/tests/ecs/test_tween_activity.cppnew file mode 100644index 000000000..c52eef182--- /dev/null+++ b/tests/ecs/test_tween_activity.cpp@@ -0,0 +1,38 @@+#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN+#include <doctest.h>+#include "esengine/animation/TweenSystem.hpp"+#include "esengine/ecs/components/Transform.hpp"++using namespace esengine;+using namespace esengine::ecs;+using namespace esengine::animation;++TEST_CASE("delay remainder belongs to its own tween") {+ Registry r; TweenSystem s;+ auto a = r.create(), b = r.create();+ r.emplace<Transform>(a); r.emplace<Transform>(b);+ auto delayed = s.createTween(r, a, TweenTarget::PositionX, 0, 10, 1);+ auto immediate = s.createTween(r, b, TweenTarget::PositionX, 0, 10, 1);+ r.get<TweenData>(delayed).delay = 0.05f;+ s.update(r, 0.1f);+ CHECK(r.get<TweenData>(delayed).elapsed == doctest::Approx(0.05));+ CHECK(r.get<TweenData>(immediate).elapsed == doctest::Approx(0.1));+}++TEST_CASE("disabled tweens pause advancement but cancelled tweens are cleaned up") {+ Registry r; TweenSystem s;+ auto target = r.create(); r.emplace<Transform>(target);+ auto tween = s.createTween(r, target, TweenTarget::PositionX, 0, 10, 1);+ r.setEntityEnabled(target, false);+ s.update(r, 0.2f);+ CHECK(r.get<TweenData>(tween).elapsed == 0);+ r.setEntityEnabled(target, true);+ s.update(r, 0.2f);+ CHECK(r.get<TweenData>(tween).elapsed == doctest::Approx(0.2));+ r.setEntityEnabled(tween, false);+ s.update(r, 0.2f);+ CHECK(r.get<TweenData>(tween).elapsed == doctest::Approx(0.2));+ s.cancelAllTweens(r, target);+ s.update(r, 0.2f);+ CHECK_FALSE(r.valid(tween));+}diff --git a/tests/renderer/test_per_draw_blocks.cpp b/tests/renderer/test_per_draw_blocks.cppindex 58485b2dc..d78fe4c5c 100644--- a/tests/renderer/test_per_draw_blocks.cpp+++ b/tests/renderer/test_per_draw_blocks.cpp@@ -71,6 +71,23 @@ int main() {device.lastUniformBuffer != second.back().buffer,"a write the block cannot hold binds the zero block");+ blocks.shutdown();+ CHECK(device.deleteBufferCalls == device.createBufferCalls,+ "shutdown releases all populated pages and the zero block");+ const int deleted = device.deleteBufferCalls;+ blocks.shutdown();+ CHECK(device.deleteBufferCalls == deleted, "shutdown is idempotent");+ CHECK(blocks.stage(bytes.data(), WRITTEN).page == PerDrawBlocks::Range{}.page,+ "a stopped pool cannot stage a draw");+ blocks.init(device, BLOCK);+ blocks.stage(bytes.data(), WRITTEN);+ blocks.init(device, BLOCK);+ CHECK(device.createBufferCalls - device.deleteBufferCalls == 1,+ "reinitialization releases the previous pages and zero block");+ blocks.shutdown();+ CHECK(device.deleteBufferCalls == device.createBufferCalls,+ "a reinitialized pool returns to zero live buffers");+if (g_failures) std::printf("%d failure(s)\n", g_failures);return g_failures ? 1 : 0;}diff --git a/tests/renderer/test_skeletal_batch_color.cpp b/tests/renderer/test_skeletal_batch_color.cppnew file mode 100644index 000000000..14a3d8da6--- /dev/null+++ b/tests/renderer/test_skeletal_batch_color.cpp@@ -0,0 +1,29 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN+#include <doctest.h>+#include "esengine/bindings/modules/spine/SkeletalModule.hpp"++TEST_CASE("PMA color separates batches even when texture and blend match") {+ es::skeletal::BatchList batches;+ es::skeletal::BatchCollector sink(batches);+ const float positions[] = {0, 0, 1, 0, 0, 1};+ const float uvs[] = {0, 0, 1, 0, 0, 1};+ const std::uint16_t indices[] = {0, 1, 2};+ const float color[] = {0.2f, 0.1f, 0.05f, 0.25f};+ for (int blend : {2, 3}) {+ batches.reset();+ for (bool pma : {false, true, true, false}) {+ sink.setPremultipliedColor(pma);+ sink.emit(positions, uvs, 3, indices, 3, 7, blend, color);+ }+ REQUIRE(batches.size() == 3);+ CHECK_FALSE(batches[0].premultipliedColor);+ CHECK(batches[1].premultipliedColor);+ CHECK_FALSE(batches[2].premultipliedColor);+ CHECK(batches[1].vertices.size() == 6 * es::skeletal::VERTEX_FLOATS);+ CHECK(batches[1].indices[3] == 3);+ CHECK(batches[1].vertices[4] == doctest::Approx(color[0]));+ CHECK(batches[1].vertices[7] == doctest::Approx(color[3]));+ }+}diff --git a/tests/resource/test_material_shader_lifetime.cpp b/tests/resource/test_material_shader_lifetime.cppnew file mode 100644index 000000000..0de30d450--- /dev/null+++ b/tests/resource/test_material_shader_lifetime.cpp@@ -0,0 +1,86 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+#include "../renderer/MockGfxDevice.hpp"+#include "esengine/resource/ResourceManager.hpp"+#include "esengine/renderer/store/MaterialStore.hpp"+#include <cstdio>+using namespace esengine;+static int failures = 0;+#define CHECK(c, m) do { if (!(c)) { std::printf("FAIL: %s\n", m); ++failures; } else std::printf("ok: %s\n", m); } while (0)+static const char* source = R"(#pragma shader "Lifetime"+#pragma version 300 es+#pragma domain Unlit+#pragma fragment+precision mediump float;+in vec4 v_color;+out vec4 fragColor;+void main() { fragColor = v_color; }+#pragma end+)";+int main() {+ {+ MockGfxDevice device; resource::ResourceManager rm; rm.init(device);+ MaterialStore store; store.setDevice(&device); store.setResourceManager(&rm);+ auto shader = rm.createShader("vertex", "fragment", false);+ store.registerLayout(shader, {}); store.rememberSource(shader, source, "");+ MaterialRecord record; record.shaderRef = shader; store.define(1, record);+ CHECK(store.meshProgram(1, rm) != 0, "mesh variant compiles");+ CHECK(store.particleProgram(1, rm) != 0, "2D particle variant compiles");+ CHECK(rm.getStats().shaderCount == 3, "base and two variants have real pool ownership");+ rm.releaseShader(shader);+ CHECK(rm.getStats().shaderCount == 0, "final base release also retires both variants");+ CHECK(store.layoutFor(shader) == nullptr, "retired shader layout is gone");+ CHECK(store.builtVariantCount() == 0, "retired shader variant entries are gone");+ store.clear(); rm.shutdown();+ }+ {+ MockGfxDevice device; resource::ResourceManager rm; rm.init(device);+ MaterialStore store; store.setDevice(&device); store.setResourceManager(&rm);+ auto shader = rm.createShader("vertex", "fragment", false);+ store.rememberSource(shader, source, "");+ MaterialRecord record; record.shaderRef = shader; store.define(1, record);+ const auto program = store.particleProgram(1, rm);+ bool shared = true;+ for (int i = 0; i < 10000; ++i) shared &= store.particleProgram(1, rm) == program;+ CHECK(shared, "10000 warm particle lookups share the program");+ store.clear();+ CHECK(rm.getStats().shaderCount == 1, "clear releases owned variants, not caller-owned base");+ CHECK(store.builtVariantCount() == 0, "clear forgets variant cache");+ store.define(1, record);+ CHECK(store.particleProgram(1, rm) == 0, "clear forgets source rather than rebuilding from retired bytes");+ store.clear(); rm.releaseShader(shader); rm.shutdown();+ }+ {+ MockGfxDevice device; resource::ResourceManager rm; rm.init(device);+ MaterialStore store; store.setDevice(&device); store.setResourceManager(&rm);+ auto a = rm.createShader("vertex", "fragment", false);+ auto b = rm.createShader("vertex", "fragment", false);+ for (auto shader : {a, b}) { store.registerLayout(shader, {}); store.rememberSource(shader, source, ""); }+ MaterialRecord record; record.shaderRef = a; store.define(1, record); store.define(2, record);+ record.shaderRef = b; store.define(3, record);+ CHECK(store.particleProgram(1, rm) == store.particleProgram(2, rm), "two materials share one source variant");+ const auto other = store.particleProgram(3, rm);+ CHECK(rm.getStats().shaderCount == 4, "two source eras own two variants");+ rm.releaseShader(a);+ CHECK(rm.getStats().shaderCount == 2, "retiring one source releases only its variant");+ CHECK(store.layoutFor(b) != nullptr && store.particleProgram(3, rm) == other, "another source remains usable");+ rm.shutdown();+ CHECK(store.layoutFor(b) == nullptr && store.builtVariantCount() == 0, "pool shutdown retires remaining metadata and variants");+ }+ {+ MockGfxDevice device; resource::ResourceManager rm; rm.init(device);+ auto shader = rm.createShader("vertex", "fragment", false);+ {+ MaterialStore store; store.setDevice(&device); store.setResourceManager(&rm);+ store.rememberSource(shader, source, "");+ MaterialRecord record; record.shaderRef = shader; store.define(1, record);+ store.particleProgram(1, rm);+ }+ CHECK(rm.getStats().shaderCount == 1, "store destruction releases owned variants but preserves external base");+ rm.releaseShader(shader);+ CHECK(rm.getStats().shaderCount == 0, "retirement after store destruction invokes no dead observer");+ rm.shutdown();+ }+ std::printf("Material shader lifetime: %d failures\n", failures);+ return failures ? 1 : 0;+}diff --git a/tests/resource/test_mesh_recovery.cpp b/tests/resource/test_mesh_recovery.cppindex e8940581d..cc8a5b842 100644--- a/tests/resource/test_mesh_recovery.cpp+++ b/tests/resource/test_mesh_recovery.cpp@@ -58,6 +58,37 @@ bool rematerialize(resource::ResourceManager& rm, resource::MeshHandle h, f32 ex} // namespaceint main() {+ // Layout ownership follows the mesh through replacement, failure and shutdown.+ {+ MockGfxDevice d;+ resource::ResourceManager rm;+ rm.init(d);+ const auto first = makeMesh(rm, MeshRecovery::SourceReplayable);+ const auto second = makeMesh(rm, MeshRecovery::HostOnly);+ const auto oldLayout = rm.getMesh(first)->layout;+ const auto secondLayout = rm.getMesh(second)->layout;+ CHECK(oldLayout != secondLayout, "identical mesh descriptions own distinct layouts");+ CHECK(rematerialize(rm, first, 2.0f), "a mesh can replace its realization");+ CHECK(d.vertexLayoutDesc(oldLayout) == nullptr,+ "replacement releases the previous vertex layout");+ const auto liveLayout = rm.getMesh(first)->layout;+ const int deletedBeforeFailure = d.deleteVertexLayoutCalls;+ d.createBufferSucceeds = false;+ CHECK(!rematerialize(rm, first, 3.0f), "allocation failure refuses a replacement");+ CHECK(d.deleteVertexLayoutCalls == deletedBeforeFailure + 1 &&+ d.vertexLayoutDesc(liveLayout) != nullptr,+ "failed allocation releases its new layout and preserves the live one");+ d.createBufferSucceeds = true;+ rm.releaseMesh(first);+ CHECK(d.vertexLayoutDesc(liveLayout) == nullptr && d.vertexLayoutDesc(secondLayout) != nullptr,+ "releasing one mesh releases only its layout");+ rm.shutdown();+ CHECK(d.vertexLayoutDesc(secondLayout) == nullptr && rm.getMesh(second) == nullptr,+ "shutdown releases remaining meshes and their layouts");+ const int deleted = d.deleteVertexLayoutCalls;+ rm.shutdown();+ CHECK(d.deleteVertexLayoutCalls == deleted, "resource shutdown is idempotent");+ }// --- The identity and its buffers survive; replayable geometry is owed ---{MockGfxDevice d;diff --git a/tools/eht/generators/embind.py b/tools/eht/generators/embind.pyindex 2339ba021..084238cce 100644--- a/tools/eht/generators/embind.py+++ b/tools/eht/generators/embind.py@@ -368,6 +368,15 @@ class EmbindGenerator:' .function("valid", optional_override([](Registry& r, u32 e) {',' return r.valid(static_cast<Entity>(e));',' }))',+ ' .function("reserveDestruction", optional_override([](Registry& r, u32 e) {',+ ' return r.reserveDestruction(static_cast<Entity>(e));',+ ' }))',+ ' .function("releaseDestruction", optional_override([](Registry& r, u32 e) {',+ ' r.releaseDestruction(static_cast<Entity>(e));',+ ' }))',+ ' .function("destructionPending", optional_override([](Registry& r, u32 e) {',+ ' return r.destructionPending(static_cast<Entity>(e));',+ ' }))',' .function("entityCount", &Registry::entityCount)','',]@@ -444,8 +453,13 @@ class EmbindGenerator:lines.extend([' // Hierarchy Utilities',+ ' .function("setEntityEnabled", optional_override([](Registry& r, u32 e, bool enabled) { return r.setEntityEnabled(static_cast<Entity>(e), enabled); }))',+ ' .function("isEntityActive", optional_override([](Registry& r, u32 e) { return r.isEntityActive(static_cast<Entity>(e)); }))',+ ' .function("isEntityEnabled", optional_override([](Registry& r, u32 e) { return r.isEntityEnabled(static_cast<Entity>(e)); }))',+ ' .function("hasInactiveEntities", &Registry::hasInactiveEntities)',+ ' .function("activityEpoch", &Registry::activityEpoch)',' .function("setParent", optional_override([](Registry& r, u32 child, u32 parent) {',- ' esengine::ecs::setParent(r, static_cast<Entity>(child), static_cast<Entity>(parent));',+ ' return esengine::ecs::setParent(r, static_cast<Entity>(child), static_cast<Entity>(parent));',' }))','',])diff --git a/tools/eht/generators/native_bindings.py b/tools/eht/generators/native_bindings.pyindex 04408a110..79ae99f9b 100644--- a/tools/eht/generators/native_bindings.py+++ b/tools/eht/generators/native_bindings.py@@ -1,7 +1,7 @@"""Native (QuickJS) binding generator — the native sibling of the embind generator.-Emits, per ES_COMPONENT, a QuickJS-callable ``es_set_<Component>(entityId, obj)``-that writes the reflected scalar / vec / bool / enum fields, plus an+Emits, per ES_COMPONENT, QuickJS-callable member getters/setters for reflected+strings, scalars, vectors and enums, plus compiler-validated zero-copy buffers and an``esn_register()`` that installs them as script globals. It consumes the SAMEparsed reflection (data.Component) as EmbindGenerator, so the web (embind) andnative (QuickJS) binding surfaces are generated from one source and cannot drift.@@ -13,16 +13,16 @@ for the ``esn_*`` readers, the entity lookup, and the component includes."""from typing import List-from ..data import Component, Enum, READ_HOOKS+from ..data import Component, Enum, READ_HOOKS, WRITE_HOOKSfrom ..type_system import TypeSystem+from .ptr_layout import PtrLayoutGenerator# Numeric primitives written straight through (via a double), by cleaned type._FLOAT = {'f32', 'f64', 'float', 'double'}_INT = {'i8', 'i16', 'i32', 'i64', 'u8', 'u16', 'u32', 'u64','int', 'int8_t', 'int16_t', 'int32_t', 'int64_t','uint8_t', 'uint16_t', 'uint32_t', 'uint64_t', 'size_t', 'char'}-# glm vector arities the reader marshals (float lanes). quat/uvec2 skipped:-# quaternion storage order is fragile to hand-write, uvec2 is unsigned.+# Float vector arities used by list element bindings._GLM_ARITY = {'glm::vec2': 2, 'glm::vec3': 3, 'glm::vec4': 4}@@ -35,16 +35,58 @@ class NativeBindingsGenerator:self.enums = enumsself.types = TypeSystem(enums)self.shim_header = shim_header+ self.layouts = {l['name']: l for l in PtrLayoutGenerator(self.components, enums).layouts}++ def _members(self, ct):+ if ct in self.types.CUSTOM_STRUCTS:+ return [m for m, _ in self.types.CUSTOM_STRUCTS[ct]]+ if ct in self.types.GLM_TYPES:+ return ['x', 'y', 'z', 'w'][:{'glm::vec2': 2, 'glm::uvec2': 2,+ 'glm::vec3': 3}.get(ct, 4)]+ return []++ def _read_field(self, prop):+ ct = self.types.clean_type(prop.cpp_type)+ n = prop.name+ members = self._members(ct)+ if members:+ lines = [' { JSValue v = JS_NewObject(ctx);']+ lines += [f' JS_SetPropertyStr(ctx, v, "{m}", JS_NewFloat64(ctx, c->{n}.{m}));'+ for m in members]+ return lines + [f' JS_SetPropertyStr(ctx, o, "{n}", v); }}']+ if ct == 'std::string':+ value = f'JS_NewStringLen(ctx, c->{n}.data(), c->{n}.size())'+ elif ct == 'bool':+ value = f'JS_NewBool(ctx, c->{n})'+ elif self.types.is_handle(ct):+ value = f'JS_NewFloat64(ctx, c->{n}.id())'+ elif ct == 'Entity':+ value = f'JS_NewFloat64(ctx, static_cast<esengine::u32>(c->{n}))'+ elif ct in _FLOAT | _INT or self.types.is_enum(ct):+ value = f'JS_NewFloat64(ctx, static_cast<double>(c->{n}))'+ else:+ return []+ return [f' JS_SetPropertyStr(ctx, o, "{n}", {value});']def _field(self, prop) -> str:t = prop.cpp_typen = prop.namect = self.types.clean_type(t)- if ct in _GLM_ARITY:- return f' esn_getvec(ctx, o, "{n}", &c.{n}.x, {_GLM_ARITY[ct]});'+ if ct == 'std::string':+ return (f' {{ JSValue v = JS_GetPropertyStr(ctx, o, "{n}"); '+ 'if (!JS_IsUndefined(v)) { size_t len; const char* s = JS_ToCStringLen(ctx, &len, v); '+ f'if (s) {{ c.{n}.assign(s, len); JS_FreeCString(ctx, s); }} }} '+ 'JS_FreeValue(ctx, v); }')+ if self._members(ct):+ lines = [f' {{ JSValue v = JS_GetPropertyStr(ctx, o, "{n}");']+ lines.append(' if (JS_IsObject(v)) {')+ for i, m in enumerate(self._members(ct)):+ lines.append(f' {{ double x; if (esn_getnum(ctx, v, JS_IsArray(v) ? "{i}" : "{m}", &x)) '+ f'c.{n}.{m} = static_cast<decltype(c.{n}.{m})>(x); }}')+ return '\n'.join(lines + [' } JS_FreeValue(ctx, v); }'])if ct == 'bool':return f' {{ int _b; if (esn_getbool(ctx, o, "{n}", &_b)) c.{n} = _b != 0; }}'- if self.types.is_enum(t) or ct in _INT:+ if self.types.is_enum(t) or ct in _INT or ct == 'Entity':return (f' {{ double _v; if (esn_getnum(ctx, o, "{n}", &_v)) 'f'c.{n} = static_cast<decltype(c.{n})>(static_cast<long long>(_v)); }}')if ct in _FLOAT:@@ -142,12 +184,25 @@ class NativeBindingsGenerator:' JSValueConst o = argv[1];',' (void)c; (void)o;']for prop in comp.properties:- out.append(self._field(prop))+ if 'readonly' not in prop.annotations:+ out.append(self._field(prop))+ if comp.name in WRITE_HOOKS:+ out.append(f' {WRITE_HOOKS[comp.name]}')out.append(' return JS_UNDEFINED;')out.append('}')- # Fast path: es_<Component>_buffer(entityId) -> a zero-copy ArrayBuffer over- # the native component, which the shared generated ptrAccessors write. Same- # POD layout as wasm32, so ptrAccessors.generated.ts works unchanged.+ out += [f'static JSValue es_get_{comp.name}(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {{',+ ' JSValue o = JS_NewObject(ctx);',+ ' if (argc < 1) return o;',+ f' auto* c = esn_reg().tryGet<{full}>(esn_entity(ctx, argv[0]));',+ ' if (!c) return o;']+ read_hook = READ_HOOKS.get(comp.name)+ if read_hook:+ out.append(f' c->{read_hook}();')+ for prop in comp.properties:+ out.extend(self._read_field(prop))+ out += [' return o;', '}']+ # The buffer implementation is registered below only if the native+ # compiler proves trivial ownership and the actual wasm accessor offsets.# getOrEmplace so a first write (component add) also creates the component.out.append(f'static JSValue es_{comp.name}_buffer(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {{')out.append(' if (argc < 1) return JS_UNDEFINED;')@@ -182,9 +237,13 @@ class NativeBindingsGenerator:'// Auto-generated by EHT (native_bindings) — DO NOT EDIT.','// Native QuickJS sibling of WebBindings.generated.cpp — one reflection source.',f'#include "{self.shim_header}"',+ '#include <type_traits>',+ '#include <cstddef>','',]components = sorted(self.components, key=lambda c: c.name)+ if any(c.name in WRITE_HOOKS for c in components):+ lines.append('#include "esengine/ecs/TransformSystem.hpp"')# Self-include each bound component's header (relative to src/), so the TU# needs only the shim for the esn_* plumbing — deduped (some components# share a header, e.g. the collider family).@@ -208,8 +267,25 @@ class NativeBindingsGenerator:remove = f'es_{comp.name}_remove'lines.append(f' JS_SetPropertyStr(ctx, global, "{setter}", 'f'JS_NewCFunction(ctx, {setter}, "{setter}", 2));')- lines.append(f' JS_SetPropertyStr(ctx, global, "{buffer}", '- f'JS_NewCFunction(ctx, {buffer}, "{buffer}", 1));')+ getter = f'es_get_{comp.name}'+ lines.append(f' JS_SetPropertyStr(ctx, global, "{getter}", '+ f'JS_NewCFunction(ctx, {getter}, "{getter}", 1));')+ # Expose the raw buffer ONLY when this compiler proves every accessed+ # offset matches wasm32 and no owned string/vector can be overwritten.+ full = f'{comp.namespace}::{comp.name}' if comp.namespace else comp.name+ layout = self.layouts.get(comp.name)+ if layout:+ checks = [f'std::is_standard_layout_v<{full}>',+ f'std::is_trivially_copyable_v<{full}>']+ checks += [f'offsetof({full}, {f["name"]}) == {f["offset"]}'+ for f in layout['fields']]+ for f in layout['fields']:+ checks += [f'offsetof(decltype({full}::{f["name"]}), {m["name"]}) == {m["offset"]}'+ for m in f.get('members', [])]+ lines.append(f' if constexpr ({" && ".join(checks)}) {{')+ lines.append(f' JS_SetPropertyStr(ctx, global, "{buffer}", '+ f'JS_NewCFunction(ctx, {buffer}, "{buffer}", 1));')+ lines.append(' }')lines.append(f' JS_SetPropertyStr(ctx, global, "{has}", 'f'JS_NewCFunction(ctx, {has}, "{has}", 1));')lines.append(f' JS_SetPropertyStr(ctx, global, "{remove}", 'diff --git a/tools/eht/generators/typescript.py b/tools/eht/generators/typescript.pyindex b94041192..55fd23aa5 100644--- a/tools/eht/generators/typescript.py+++ b/tools/eht/generators/typescript.py@@ -109,7 +109,12 @@ class TypeScriptGenerator:lines.extend(['',' // Hierarchy Utilities',- ' setParent(child: Entity, parent: Entity): void;',+ ' setEntityEnabled?(entity: Entity, enabled: boolean): boolean;',+ ' isEntityActive?(entity: Entity): boolean;',+ ' isEntityEnabled?(entity: Entity): boolean;',+ ' hasInactiveEntities?(): boolean;',+ ' activityEpoch?(): number;',+ ' setParent(child: Entity, parent: Entity): boolean | void;',])lines.append('}')lines.append('')diff --git a/tools/eht/test_native_layout.py b/tools/eht/test_native_layout.pynew file mode 100644index 000000000..f21a2ca54--- /dev/null+++ b/tools/eht/test_native_layout.py@@ -0,0 +1,46 @@+"""Native buffers must be compiler-validated; owned fields use member bindings."""+import sys+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent.parent))+from eht.data import Component, Property+from eht.generators.native_bindings import NativeBindingsGenerator+++class NativeLayoutTests(unittest.TestCase):+ def generate(self, properties):+ return NativeBindingsGenerator([+ Component('Fixture', 'esengine::ecs', properties)+ ], []).generate()++ def test_buffer_requires_actual_offsets_and_trivial_ownership(self):+ code = self.generate([Property('text', 'std::string'), Property('speed', 'f32')])+ self.assertIn('std::is_trivially_copyable_v<esengine::ecs::Fixture>', code)+ self.assertIn('std::is_standard_layout_v<esengine::ecs::Fixture>', code)+ self.assertIn('offsetof(esengine::ecs::Fixture, speed) == 12', code)+ self.assertIn('c.text.assign(s, len)', code)+ self.assertIn('JS_NewStringLen(ctx, c->text.data(), c->text.size())', code)+ self.assertIn('es_get_Fixture', code)++ def test_vector_following_scalar_is_guarded_and_members_use_names(self):+ code = self.generate([Property('path', 'std::vector<glm::vec2>'),+ Property('enabled', 'bool'), Property('rotation', 'glm::quat')])+ self.assertIn('offsetof(esengine::ecs::Fixture, enabled) == 12', code)+ self.assertIn('es_Fixture_path_set', code)+ self.assertIn('c.rotation.w', code)+ self.assertIn('JS_IsArray(v) ? "3" : "w"', code)++ def test_member_path_respects_readonly_and_shared_transform_write_hook(self):+ code = NativeBindingsGenerator([Component('Transform', 'esengine::ecs', [+ Property('position', 'glm::vec3'),+ Property('worldPosition', 'glm::vec3', annotations={'readonly': ''}),+ ])], []).generate()+ self.assertIn('c.position.x =', code)+ self.assertNotIn('c.worldPosition.x =', code)+ self.assertIn('c->worldPosition.x', code)+ self.assertIn('esengine::ecs::invalidateTransformComposition();', code)+++if __name__ == '__main__':+ unittest.main()