A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
fix(ecs): a parent link has two halves, and setParent is the only writer of both
yhh4b6fc9177c84
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex ac1b01896..2186aed8b 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1847,13 +1847,14 @@ keyof ThemeColors## CommandsInstance — class @public```-@internal spawnImmediate: (components: SpawnComponentEntry[], entityRef: { entity: Entity; }, name?: string) => void+@internal spawnImmediate: (components: SpawnComponentEntry[], entityRef: { entity: Entity; }, name?: string, parent?: Entity | null) => voiddespawn: (entity: Entity) => CommandsInstanceentity: (entity: Entity) => EntityCommandsflush: () => voidinsertResource: <T>(resource: ResourceDef<T>, value: T) => CommandsInstancequeueInsert: (entity: Entity, component: AnyComponentDef, data: unknown) => voidqueueRemove: (entity: Entity, component: AnyComponentDef) => void+queueSetParent: (entity: Entity, parent: Entity) => voidspawn: (name?: string) => EntityCommandsstatic new (world: World, resources: ResourceStorage): CommandsInstancestatic prototype: CommandsInstance@@ -2592,6 +2593,7 @@ number## EntityCommands — class @public```+childOf: (parent: Entity) => EntityCommandsfinalize: () => voidid: () => Entityinsert: <T extends object>(component: AnyComponentDef, data?: Partial<T> | undefined) => EntityCommandsdiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 7ca5788d8..09ede40c1 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1847,13 +1847,14 @@ keyof ThemeColors## CommandsInstance — class @public```-@internal spawnImmediate: (components: SpawnComponentEntry[], entityRef: { entity: Entity; }, name?: string) => void+@internal spawnImmediate: (components: SpawnComponentEntry[], entityRef: { entity: Entity; }, name?: string, parent?: Entity | null) => voiddespawn: (entity: Entity) => CommandsInstanceentity: (entity: Entity) => EntityCommandsflush: () => voidinsertResource: <T>(resource: ResourceDef<T>, value: T) => CommandsInstancequeueInsert: (entity: Entity, component: AnyComponentDef, data: unknown) => voidqueueRemove: (entity: Entity, component: AnyComponentDef) => void+queueSetParent: (entity: Entity, parent: Entity) => voidspawn: (name?: string) => EntityCommandsstatic new (world: World, resources: ResourceStorage): CommandsInstancestatic prototype: CommandsInstance@@ -2600,6 +2601,7 @@ number## EntityCommands — class @public```+childOf: (parent: Entity) => EntityCommandsfinalize: () => voidid: () => Entityinsert: <T extends object>(component: AnyComponentDef, data?: Partial<T> | undefined) => EntityCommandsdiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 063e040e8..e23866feb 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1842,13 +1842,14 @@ keyof ThemeColors## CommandsInstance — class @public```-@internal spawnImmediate: (components: SpawnComponentEntry[], entityRef: { entity: Entity; }, name?: string) => void+@internal spawnImmediate: (components: SpawnComponentEntry[], entityRef: { entity: Entity; }, name?: string, parent?: Entity | null) => voiddespawn: (entity: Entity) => CommandsInstanceentity: (entity: Entity) => EntityCommandsflush: () => voidinsertResource: <T>(resource: ResourceDef<T>, value: T) => CommandsInstancequeueInsert: (entity: Entity, component: AnyComponentDef, data: unknown) => voidqueueRemove: (entity: Entity, component: AnyComponentDef) => void+queueSetParent: (entity: Entity, parent: Entity) => voidspawn: (name?: string) => EntityCommandsstatic new (world: World, resources: ResourceStorage): CommandsInstancestatic prototype: CommandsInstance@@ -2587,6 +2588,7 @@ number## EntityCommands — class @public```+childOf: (parent: Entity) => EntityCommandsfinalize: () => voidid: () => Entityinsert: <T extends object>(component: AnyComponentDef, data?: Partial<T> | undefined) => EntityCommandsdiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 08bf90754..5697768a3 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1842,13 +1842,14 @@ keyof ThemeColors## CommandsInstance — class @public```-@internal spawnImmediate: (components: SpawnComponentEntry[], entityRef: { entity: Entity; }, name?: string) => void+@internal spawnImmediate: (components: SpawnComponentEntry[], entityRef: { entity: Entity; }, name?: string, parent?: Entity | null) => voiddespawn: (entity: Entity) => CommandsInstanceentity: (entity: Entity) => EntityCommandsflush: () => voidinsertResource: <T>(resource: ResourceDef<T>, value: T) => CommandsInstancequeueInsert: (entity: Entity, component: AnyComponentDef, data: unknown) => voidqueueRemove: (entity: Entity, component: AnyComponentDef) => void+queueSetParent: (entity: Entity, parent: Entity) => voidspawn: (name?: string) => EntityCommandsstatic new (world: World, resources: ResourceStorage): CommandsInstancestatic prototype: CommandsInstance@@ -2587,6 +2588,7 @@ number## EntityCommands — class @public```+childOf: (parent: Entity) => EntityCommandsfinalize: () => voidid: () => Entityinsert: <T extends object>(component: AnyComponentDef, data?: Partial<T> | undefined) => EntityCommandsdiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 434aeca07..856d1e44b 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1842,13 +1842,14 @@ keyof ThemeColors## CommandsInstance — class @public```-@internal spawnImmediate: (components: SpawnComponentEntry[], entityRef: { entity: Entity; }, name?: string) => void+@internal spawnImmediate: (components: SpawnComponentEntry[], entityRef: { entity: Entity; }, name?: string, parent?: Entity | null) => voiddespawn: (entity: Entity) => CommandsInstanceentity: (entity: Entity) => EntityCommandsflush: () => voidinsertResource: <T>(resource: ResourceDef<T>, value: T) => CommandsInstancequeueInsert: (entity: Entity, component: AnyComponentDef, data: unknown) => voidqueueRemove: (entity: Entity, component: AnyComponentDef) => void+queueSetParent: (entity: Entity, parent: Entity) => voidspawn: (name?: string) => EntityCommandsstatic new (world: World, resources: ResourceStorage): CommandsInstancestatic prototype: CommandsInstance@@ -2587,6 +2588,7 @@ number## EntityCommands — class @public```+childOf: (parent: Entity) => EntityCommandsfinalize: () => voidid: () => Entityinsert: <T extends object>(component: AnyComponentDef, data?: Partial<T> | undefined) => EntityCommandsdiff --git a/sdk/src/ecs/commands.ts b/sdk/src/ecs/commands.tsindex a5a6878e0..7b8e2fcb2 100644--- a/sdk/src/ecs/commands.ts+++ b/sdk/src/ecs/commands.ts@@ -67,6 +67,12 @@ interface RemoveCommand {component: AnyComponentDef;}+interface SetParentCommand {+ type: 'set_parent';+ entity: Entity;+ parent: Entity;+}+interface InsertResourceCommand {type: 'insert_resource';resource: ResourceDef<unknown>;@@ -77,6 +83,7 @@ type Command =| DespawnCommand| InsertCommand| RemoveCommand+ | SetParentCommand| InsertResourceCommand;// =============================================================================@@ -96,6 +103,7 @@ export class EntityCommands {private readonly components_: SpawnComponentEntry[] = [];private readonly spawnName_?: string;private isNew_: boolean;+ private parent_: Entity | null = null;constructor(commands: CommandsInstance, entity: Entity | null, name?: string) {this.commands_ = commands;@@ -135,6 +143,20 @@ export class EntityCommands {return this;}+ /**+ * Attach this entity under `parent`. The engine keeps {@link Parent} and+ * {@link Children} in step from here — inserting `Parent` yourself writes+ * only one half of the link.+ */+ childOf(parent: Entity): this {+ if (this.isNew_) {+ this.parent_ = parent;+ } else {+ this.commands_.queueSetParent(this.entityRef_.entity, parent);+ }+ return this;+ }+id(): Entity {if (this.isNew_ && this.entityRef_.entity === 0) {this.finalize();@@ -144,8 +166,9 @@ export class EntityCommands {finalize(): void {if (this.isNew_) {- this.commands_.spawnImmediate(this.components_, this.entityRef_, this.spawnName_);+ this.commands_.spawnImmediate(this.components_, this.entityRef_, this.spawnName_, this.parent_);this.isNew_ = false;+ this.parent_ = null;}}}@@ -204,15 +227,28 @@ export class CommandsInstance {this.pending_.push({ type: 'remove', entity, component });}+ queueSetParent(entity: Entity, parent: Entity): void {+ this.pending_.push({ type: 'set_parent', entity, parent });+ }+/** @internal How EntityCommands applies a deferred spawn — `entityRef` is the* handle it already gave the caller, filled in once the entity exists. */- spawnImmediate(components: SpawnComponentEntry[], entityRef: { entity: Entity }, name?: string): void {+ spawnImmediate(+ components: SpawnComponentEntry[],+ entityRef: { entity: Entity },+ name?: string,+ parent?: Entity | null,+ ): void {const entity = this.world_.spawn(name);entityRef.entity = entity;for (const entry of components) {this.world_.insert(entity, entry.component, entry.data as Record<string, unknown>);}++ if (parent !== null && parent !== undefined) {+ this.world_.setParent(entity, parent);+ }}flush(): void {@@ -257,6 +293,14 @@ export class CommandsInstance {this.world_.remove(cmd.entity, cmd.component);break;+ case 'set_parent':+ if (!this.world_.valid(cmd.entity) || !this.world_.valid(cmd.parent)) {+ log.warn('commands', `childOf skipped: entity ${cmd.entity} or parent ${cmd.parent} is invalid`);+ break;+ }+ this.world_.setParent(cmd.entity, cmd.parent);+ break;+case 'insert_resource':this.resources_.insert(cmd.resource, cmd.value);break;diff --git a/sdk/src/ecs/world.ts b/sdk/src/ecs/world.tsindex 6a183e35b..165171d93 100644--- a/sdk/src/ecs/world.ts+++ b/sdk/src/ecs/world.ts@@ -6,7 +6,7 @@*/import { Entity, entityGeneration, entityIndex, makeEntity, INVALID_ENTITY } from '../types';-import { AnyComponentDef, ComponentDef, ComponentData, BuiltinComponentDef, isBuiltinComponent, getComponentRegistry, getUserComponents, getComponent, Name, Parent, Children } from './component';+import { AnyComponentDef, ComponentDef, ComponentData, BuiltinComponentDef, isBuiltinComponent, getComponentRegistry, getUserComponents, getComponent, Name, Parent, Children, type ParentData, type ChildrenData } from './component';import type { CppRegistry, ESEngineModule } from '../wasm';import { handleWasmError } from '../wasm/wasmError';import { BuiltinBridge, convertFromWasm, convertForWasm, type BridgeConnectOptions, type BuiltinMethods } from './bridge/BuiltinBridge';@@ -266,17 +266,8 @@ export class World {/** Depth-first teardown of `entity` and its descendants (children before parent). */private despawnSubtree_(entity: Entity, cppRegistry: CppRegistry | null): void {- if (cppRegistry && cppRegistry.hasChildren(entity)) {- 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, `despawn(children of ${entity})`); }- for (const child of children) {- if (this.valid(child)) this.despawnSubtree_(child, cppRegistry);- }+ for (const child of this.childEntitiesOf_(entity)) {+ if (this.valid(child)) this.despawnSubtree_(child, cppRegistry);}notifyBridge('onEntityDespawned', entity);@@ -516,9 +507,7 @@ export class World {handleWasmError(e, `setParent(child=${child}, parent=${parent})`);}}- this.queries_.markStructuralChange();- this.queries_.markComponentDirty(Parent._id);- this.queries_.markComponentDirty(Children._id);+ this.trackHierarchyWrite_(child, parent);notifyBridge('onParentChanged', child, parent);}@@ -532,10 +521,70 @@ export class World {handleWasmError(e, `removeParent(entity=${entity})`);}}+ this.trackHierarchyWrite_(entity, null);+ notifyBridge('onParentChanged', entity, null);+ }++ /** `entity`'s children, snapshotted out of the wasm vector that holds them. */+ private childEntitiesOf_(entity: Entity): 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})`); }+ return children;+ }++ // Parent/Children are one relationship with two halves, and setParent is the+ // only writer that keeps both. Writing either as a component lands here.+ private insertHierarchy_(entity: Entity, component: AnyComponentDef, data?: unknown): unknown {+ if (component._id === Parent._id) {+ const parent = (data as Partial<ParentData> | undefined)?.entity;+ if (parent === undefined || parent === INVALID_ENTITY) {+ this.removeParent(entity);+ return { entity: INVALID_ENTITY };+ }+ this.setParent(entity, parent);+ return { entity: parent };+ }+ const listed = (data as Partial<ChildrenData> | undefined)?.entities ?? [];+ for (const child of listed) this.setParent(child as Entity, entity);+ return { entities: [...listed] };+ }++ private isHierarchyComponent_(component: AnyComponentDef): boolean {+ return component._id === Parent._id || component._id === Children._id;+ }++ // The C++ side owns both halves of the link; these are the JS mirrors that+ // has() and the query cache read, so they move with it or the two disagree.+ private trackHierarchyWrite_(child: Entity, parent: Entity | null): void {+ const parents = this.builtin_.getOrCreateEntitySet(Parent._cppName);+ const children = this.builtin_.getOrCreateEntitySet(Children._cppName);++ if (parent === null) {+ if (parents.delete(child)) this.changes_.recordRemoved(Parent, child);+ } else {+ if (!parents.has(child)) {+ parents.add(child);+ this.changes_.recordAdded(Parent, child);+ }+ this.changes_.recordChanged(Parent, child);++ if (!children.has(parent)) {+ children.add(parent);+ this.changes_.recordAdded(Children, parent);+ }+ this.changes_.recordChanged(Children, parent);+ }+this.queries_.markStructuralChange();this.queries_.markComponentDirty(Parent._id);this.queries_.markComponentDirty(Children._id);- notifyBridge('onParentChanged', entity, null);}// =========================================================================@@ -548,6 +597,9 @@ export class World {* replaces it.*/insert<C extends AnyComponentDef>(entity: Entity, component: C, data?: Partial<ComponentData<C>>): ComponentData<C> {+ if (this.isHierarchyComponent_(component)) {+ return this.insertHierarchy_(entity, component, data) as ComponentData<C>;+ }if (isBuiltinComponent(component)) {return this.insertBuiltin_(entity, component, data) as ComponentData<C>;}@@ -559,6 +611,10 @@ export class World {* reads. Insert-or-replace: an entity that lacks the component gets it.*/set<C extends AnyComponentDef>(entity: Entity, component: C, data: ComponentData<C>): void {+ if (this.isHierarchyComponent_(component)) {+ this.insertHierarchy_(entity, component, data);+ return;+ }if (isBuiltinComponent(component)) {// `set` is insert-or-replace: adding a builtin the entity LACKS must run// the full structural bookkeeping (entity set + query dirty + recordAdded),@@ -667,6 +723,15 @@ export class World {);}+ if (component._id === Parent._id) {+ this.removeParent(entity);+ return;+ }+ if (component._id === Children._id) {+ for (const child of this.childEntitiesOf_(entity)) this.removeParent(child);+ return;+ }+if (isBuiltinComponent(component)) {this.builtin_.remove(entity, component);this.changes_.recordRemoved(component, entity);diff --git a/sdk/tests/entity-hierarchy.test.ts b/sdk/tests/entity-hierarchy.test.tsindex b2e59b59e..568f71e67 100644--- a/sdk/tests/entity-hierarchy.test.ts+++ b/sdk/tests/entity-hierarchy.test.ts@@ -9,6 +9,9 @@import { describe, it, expect, beforeAll } from 'vitest';import { World } from '../src/ecs/world';import { Transform, Sprite, Parent, Children } from '../src/ecs/component';+import { CommandsInstance } from '../src/ecs/commands';+import { ResourceStorage } from '../src/ecs/resource';+import type { Entity } from '../src/types';import type { ESEngineModule, CppRegistry } from '../src/wasm';import { loadWasmModule, HAS_WASM } from './helpers/loadWasm';@@ -34,6 +37,165 @@ describe.skipIf(!HAS_WASM)('Entity Hierarchy (WASM integration)', () => {(registry as any).delete();}+ // 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.+ describe('every way of parenting writes both halves', () => {+ const expectLinked = (world: World, registry: CppRegistry, child: Entity, parent: Entity): void => {+ expect(registry.hasParent(child)).toBe(true);+ expect(registry.getParent(child).entity).toBe(parent);+ expect(registry.hasChildren(parent)).toBe(true);+ expect(module.getChildEntities(registry, parent)).toContain(child);++ expect(world.has(child, Parent)).toBe(true);+ expect(world.has(parent, Children)).toBe(true);+ };++ it('world.setParent', () => {+ const { world, registry } = createWorld();+ const parent = world.spawn();+ const child = world.spawn();++ world.setParent(child, parent);++ expectLinked(world, registry, child, parent);+ disposeWorld(world, registry);+ });++ it('world.insert(Parent)', () => {+ const { world, registry } = createWorld();+ const parent = world.spawn();+ const child = world.spawn();++ world.insert(child, Parent, { entity: parent });++ expectLinked(world, registry, child, parent);+ disposeWorld(world, registry);+ });++ it('world.insert(Children)', () => {+ const { world, registry } = createWorld();+ const parent = world.spawn();+ const a = world.spawn();+ const b = world.spawn();++ world.insert(parent, Children, { entities: [a, b] });++ expectLinked(world, registry, a, parent);+ expectLinked(world, registry, b, parent);+ disposeWorld(world, registry);+ });++ it('commands.spawn().childOf()', () => {+ const { world, registry } = createWorld();+ const commands = new CommandsInstance(world, new ResourceStorage());+ const parent = world.spawn();++ const child = commands.spawn('child').childOf(parent).id();+ commands.flush();++ expectLinked(world, registry, child, parent);+ disposeWorld(world, registry);+ });++ it('commands.entity().childOf() defers to the flush', () => {+ const { world, registry } = createWorld();+ const commands = new CommandsInstance(world, new ResourceStorage());+ const parent = world.spawn();+ const child = world.spawn();++ commands.entity(child).childOf(parent);+ expect(registry.hasParent(child)).toBe(false);++ commands.flush();++ expectLinked(world, registry, child, parent);+ disposeWorld(world, registry);+ });++ it('remove(Parent) clears both halves', () => {+ const { world, registry } = createWorld();+ const parent = world.spawn();+ const child = world.spawn();+ world.insert(child, Parent, { entity: parent });++ world.remove(child, Parent);++ expect(registry.hasParent(child)).toBe(false);+ expect(world.has(child, Parent)).toBe(false);+ expect(module.getChildEntities(registry, parent)).not.toContain(child);+ disposeWorld(world, registry);+ });++ it('remove(Children) detaches every child', () => {+ const { world, registry } = createWorld();+ const parent = world.spawn();+ const a = world.spawn();+ const b = world.spawn();+ world.insert(parent, Children, { entities: [a, b] });++ world.remove(parent, Children);++ expect(registry.hasParent(a)).toBe(false);+ expect(registry.hasParent(b)).toBe(false);+ expect(world.has(a, Parent)).toBe(false);+ expect(module.getChildEntities(registry, parent)).toHaveLength(0);+ disposeWorld(world, registry);+ });++ // The end-to-end shape this all exists for: a sprite parented under plain+ // grouping nodes draws where its Transform says, not at the world origin.+ it.each([+ ['childOf', (w: World, child: Entity, parent: Entity) => {+ const commands = new CommandsInstance(w, new ResourceStorage());+ commands.entity(child).childOf(parent);+ commands.flush();+ }],+ ['insert(Parent)', (w: World, child: Entity, parent: Entity) => {+ w.insert(child, Parent, { entity: parent });+ }],+ ['setParent', (w: World, child: Entity, parent: Entity) => {+ w.setParent(child, parent);+ }],+ ])('a grandchild composes its world transform (%s)', (_label, link) => {+ const { world, registry } = createWorld();++ const group = world.spawn('group');+ const layer = world.spawn('layer');+ const tile = world.spawn('tile');+ world.insert(group, Transform, {});+ world.insert(layer, Transform, {});+ world.insert(tile, Transform, { position: { x: 300, y: 200, z: 0 } });++ link(world, layer, group);+ link(world, tile, layer);++ // transforms_updated is memoised per frame on the shared context.+ module.renderer_beginFrame(0);+ module.renderer_updateTransforms(registry);++ const t = world.get(tile, Transform);+ expect(t.worldPosition.x).toBeCloseTo(300);+ expect(t.worldPosition.y).toBeCloseTo(200);++ disposeWorld(world, registry);+ });++ it('reparenting moves the child to the new parent on both sides', () => {+ const { world, registry } = createWorld();+ const first = world.spawn();+ const second = world.spawn();+ const child = world.spawn();++ world.insert(child, Parent, { entity: first });+ world.insert(child, Parent, { entity: second });++ expectLinked(world, registry, child, second);+ expect(module.getChildEntities(registry, first)).not.toContain(child);+ disposeWorld(world, registry);+ });+ });+describe('setParent / getChildEntities', () => {it('should establish parent-child relationship', () => {const { world, registry } = createWorld();diff --git a/sdk/tests/mocks/wasm.ts b/sdk/tests/mocks/wasm.tsindex 54fdfe4d3..a43f890cc 100644--- a/sdk/tests/mocks/wasm.ts+++ b/sdk/tests/mocks/wasm.ts@@ -1,6 +1,7 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport type { ESEngineModule, CppRegistry, CppResourceManager } from '../../src/wasm';+import { INVALID_ENTITY } from '../../src/types';import type { Entity } from '../../src/types';/**@@ -36,10 +37,34 @@ export function createMockModule(): MockModule {entityCount: () => entities.size,- setParent: (_child: Entity, _parent: Entity) => {},+ // Mirrors ecs::setParent: both halves of the link, or neither.+ setParent: (child: Entity, parent: Entity) => {+ const detach = (): void => {+ const current = components.get(child)?.get('Parent') as { entity: Entity } | undefined;+ if (!current) return;+ const siblings = components.get(current.entity)?.get('Children') as { entities: Entity[] } | undefined;+ if (siblings) {+ siblings.entities = siblings.entities.filter((e) => e !== child);+ }+ components.get(child)?.delete('Parent');+ };++ detach();+ if (parent === INVALID_ENTITY || !entities.has(parent)) return;++ components.get(child)?.set('Parent', { entity: parent });+ const kids = components.get(parent)?.get('Children') as { entities: Entity[] } | undefined;+ if (kids) {+ if (!kids.entities.includes(child)) kids.entities.push(child);+ } else {+ components.get(parent)?.set('Children', { entities: [child] });+ }+ },delete: () => {},- removeParent: (_entity: Entity) => {},+ removeParent: (entity: Entity) => {+ baseRegistry.setParent(entity, INVALID_ENTITY);+ },// Legacy names used by some internal code pathscreateEntity: () => {diff --git a/src/esengine/bindings/EditorAPI.generated.cpp b/src/esengine/bindings/EditorAPI.generated.cppindex fbc6d6082..66f384b47 100644--- a/src/esengine/bindings/EditorAPI.generated.cpp+++ b/src/esengine/bindings/EditorAPI.generated.cpp@@ -37,6 +37,7 @@#include "../ecs/components/UIScroll.hpp"#include "../ecs/components/UIVisual.hpp"#include "../ecs/components/Velocity.hpp"+#include "../ecs/TransformSystem.hpp"#include <glm/gtc/quaternion.hpp>using namespace esengine;@@ -611,8 +612,7 @@ bool editor_addComponent(Registry& reg, u32 e, const std::string& name) {if (!reg.has<esengine::ecs::CapsuleCollider>(entity)) reg.emplace<esengine::ecs::CapsuleCollider>(entity);return true;} else if (name == "Children") {- if (!reg.has<esengine::ecs::Children>(entity)) reg.emplace<esengine::ecs::Children>(entity);- return true;+ return false;} else if (name == "CircleCollider") {if (!reg.has<esengine::ecs::CircleCollider>(entity)) reg.emplace<esengine::ecs::CircleCollider>(entity);return true;@@ -632,8 +632,7 @@ bool editor_addComponent(Registry& reg, u32 e, const std::string& name) {if (!reg.has<esengine::ecs::Mesh2D>(entity)) reg.emplace<esengine::ecs::Mesh2D>(entity);return true;} else if (name == "Parent") {- if (!reg.has<esengine::ecs::Parent>(entity)) reg.emplace<esengine::ecs::Parent>(entity);- return true;+ return false;} else if (name == "ParticleEmitter") {if (!reg.has<esengine::ecs::ParticleEmitter>(entity)) reg.emplace<esengine::ecs::ParticleEmitter>(entity);return true;@@ -703,7 +702,11 @@ bool editor_removeComponent(Registry& reg, u32 e, const std::string& name) {} else if (name == "CapsuleCollider") {if (reg.has<esengine::ecs::CapsuleCollider>(entity)) { reg.remove<esengine::ecs::CapsuleCollider>(entity); return true; }} else if (name == "Children") {- if (reg.has<esengine::ecs::Children>(entity)) { reg.remove<esengine::ecs::Children>(entity); return true; }+ if (reg.has<esengine::ecs::Children>(entity)) {+ const auto kids = reg.get<esengine::ecs::Children>(entity).entities;+ for (auto child : kids) esengine::ecs::setParent(reg, child, INVALID_ENTITY);+ return true;+ }} else if (name == "CircleCollider") {if (reg.has<esengine::ecs::CircleCollider>(entity)) { reg.remove<esengine::ecs::CircleCollider>(entity); return true; }} else if (name == "DragonBonesAnimation") {@@ -717,7 +720,7 @@ bool editor_removeComponent(Registry& reg, u32 e, const std::string& name) {} else if (name == "Mesh2D") {if (reg.has<esengine::ecs::Mesh2D>(entity)) { reg.remove<esengine::ecs::Mesh2D>(entity); return true; }} else if (name == "Parent") {- if (reg.has<esengine::ecs::Parent>(entity)) { reg.remove<esengine::ecs::Parent>(entity); return true; }+ if (reg.has<esengine::ecs::Parent>(entity)) { esengine::ecs::setParent(reg, entity, INVALID_ENTITY); return true; }} else if (name == "ParticleEmitter") {if (reg.has<esengine::ecs::ParticleEmitter>(entity)) { reg.remove<esengine::ecs::ParticleEmitter>(entity); return true; }} else if (name == "ParticleForceField") {@@ -1665,10 +1668,8 @@ bool editor_setInt(Registry& reg, u32 e, const std::string& comp, const std::strelse { return false; }return true;} else if (comp == "Parent") {- if (!reg.has<esengine::ecs::Parent>(entity)) return false;- auto& c = reg.get<esengine::ecs::Parent>(entity);- if (field == "entity") { c.entity = static_cast<Entity>(value); }- else { return false; }+ if (field != "entity") return false;+ esengine::ecs::setParent(reg, entity, static_cast<Entity>(value));return true;} else if (comp == "ParticleEmitter") {if (!reg.has<esengine::ecs::ParticleEmitter>(entity)) return false;diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cppindex b76f75c00..b64e7be2b 100644--- a/src/esengine/bindings/WebBindings.generated.cpp+++ b/src/esengine/bindings/WebBindings.generated.cpp@@ -393,17 +393,6 @@ struct ChildrenJS {std::vector<u32> entities;};-void childrenApplyJS(esengine::ecs::Children& c, const ChildrenJS& js) {- c.entities.reserve(js.entities.size());- for (auto v : js.entities) c.entities.push_back(Entity(v));-}--esengine::ecs::Children childrenFromJS(const ChildrenJS& js) {- esengine::ecs::Children c;- childrenApplyJS(c, js);- return c;-}-ChildrenJS childrenToJS(const esengine::ecs::Children& c) {ChildrenJS js;js.entities.reserve(c.entities.size());@@ -491,16 +480,6 @@ struct ParentJS {u32 entity;};-void parentApplyJS(esengine::ecs::Parent& c, const ParentJS& js) {- c.entity = Entity(js.entity);-}--esengine::ecs::Parent parentFromJS(const ParentJS& js) {- esengine::ecs::Parent c;- parentApplyJS(c, js);- return c;-}-ParentJS parentToJS(const esengine::ecs::Parent& c) {ParentJS js;js.entity = static_cast<u32>(c.entity);@@ -1626,16 +1605,17 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {.function("addChildren", optional_override([](Registry& r, u32 e, const ChildrenJS& js) {auto entity = static_cast<Entity>(e);if (!r.valid(entity)) return;- if (auto* existing = r.tryGet<esengine::ecs::Children>(entity)) {- childrenApplyJS(*existing, js);- return;+ for (auto v : js.entities) {+ esengine::ecs::setParent(r, static_cast<Entity>(v), entity);}- r.emplaceOrReplace<esengine::ecs::Children>(entity, childrenFromJS(js));})).function("removeChildren", optional_override([](Registry& r, u32 e) {auto entity = static_cast<Entity>(e);if (!r.valid(entity) || !r.has<esengine::ecs::Children>(entity)) return;- r.remove<esengine::ecs::Children>(entity);+ const auto kids = r.get<esengine::ecs::Children>(entity).entities;+ for (auto child : kids) {+ esengine::ecs::setParent(r, child, INVALID_ENTITY);+ }}))// CircleCollider@@ -1782,16 +1762,12 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {.function("addParent", optional_override([](Registry& r, u32 e, const ParentJS& js) {auto entity = static_cast<Entity>(e);if (!r.valid(entity)) return;- if (auto* existing = r.tryGet<esengine::ecs::Parent>(entity)) {- parentApplyJS(*existing, js);- return;- }- r.emplaceOrReplace<esengine::ecs::Parent>(entity, parentFromJS(js));+ esengine::ecs::setParent(r, entity, static_cast<Entity>(js.entity));})).function("removeParent", optional_override([](Registry& r, u32 e) {auto entity = static_cast<Entity>(e);if (!r.valid(entity) || !r.has<esengine::ecs::Parent>(entity)) return;- r.remove<esengine::ecs::Parent>(entity);+ esengine::ecs::setParent(r, entity, INVALID_ENTITY);}))// ParticleEmitterdiff --git a/tools/eht/data.py b/tools/eht/data.pyindex c31b95687..a196f5e79 100644--- a/tools/eht/data.py+++ b/tools/eht/data.py@@ -1,7 +1,7 @@"""Core data structures shared by parser and generators."""from dataclasses import dataclass, field-from typing import Dict, List, Optional+from typing import Dict, List, Optional, Set@dataclass@@ -34,6 +34,12 @@ class Component:READ_HOOKS: Dict[str, str] = {'Transform': 'ensureDecomposed'}+# Parent and Children are two halves of one relationship: writing either as a plain+# component leaves the other stale, and a tree walk cannot reach past the gap.+# Every binding surface routes their writes through ecs::setParent instead.+HIERARCHY_COMPONENTS: Set[str] = {'Parent', 'Children'}++@dataclassclass Enum:"""An ES_ENUM enum class."""diff --git a/tools/eht/generators/editor_api.py b/tools/eht/generators/editor_api.pyindex af1bbaa9c..76682e6bb 100644--- a/tools/eht/generators/editor_api.py+++ b/tools/eht/generators/editor_api.py@@ -8,7 +8,7 @@ Generates EditorAPI.generated.cpp with:import hashlibfrom typing import List, Set-from ..data import Component, Enum+from ..data import Component, Enum, HIERARCHY_COMPONENTSfrom ..type_system import TypeSystemfrom ..field_utils import get_sub_components, get_editor_type, is_color_field@@ -85,6 +85,7 @@ class EditorAPIGenerator:lines.extend(sorted(headers))lines.extend([+ '#include "../ecs/TransformSystem.hpp"','#include <glm/gtc/quaternion.hpp>','','using namespace esengine;',@@ -214,8 +215,13 @@ class EditorAPIGenerator:cond = 'if' if first else '} else if'first = Falselines.append(f' {cond} (name == "{comp.name}") {{')- lines.append(f' if (!reg.has<{full}>(entity)) reg.emplace<{full}>(entity);')- lines.append(f' return true;')+ if comp.name in HIERARCHY_COMPONENTS:+ # A bare Parent names no one, and TransformSystem skips anything that+ # has one — the link is made by naming a parent, not by adding this.+ lines.append(f' return false;')+ else:+ lines.append(f' if (!reg.has<{full}>(entity)) reg.emplace<{full}>(entity);')+ lines.append(f' return true;')if not first:lines.append(' }')@@ -236,7 +242,16 @@ class EditorAPIGenerator:cond = 'if' if first else '} else if'first = Falselines.append(f' {cond} (name == "{comp.name}") {{')- lines.append(f' if (reg.has<{full}>(entity)) {{ reg.remove<{full}>(entity); return true; }}')+ if comp.name == 'Parent':+ lines.append(f' if (reg.has<{full}>(entity)) {{ esengine::ecs::setParent(reg, entity, INVALID_ENTITY); return true; }}')+ elif comp.name == 'Children':+ lines.append(f' if (reg.has<{full}>(entity)) {{')+ lines.append(f' const auto kids = reg.get<{full}>(entity).entities;')+ lines.append(f' for (auto child : kids) esengine::ecs::setParent(reg, child, INVALID_ENTITY);')+ lines.append(f' return true;')+ lines.append(f' }}')+ else:+ lines.append(f' if (reg.has<{full}>(entity)) {{ reg.remove<{full}>(entity); return true; }}')if not first:lines.append(' }')@@ -456,6 +471,13 @@ class EditorAPIGenerator:cond = 'if' if first_comp else '} else if'first_comp = Falselines.append(f' {cond} (comp == "{comp.name}") {{')++ if comp.name == 'Parent':+ lines.append(' if (field != "entity") return false;')+ lines.append(' esengine::ecs::setParent(reg, entity, static_cast<Entity>(value));')+ lines.append(' return true;')+ continue+lines.append(f' if (!reg.has<{full}>(entity)) return false;')lines.append(f' auto& c = reg.get<{full}>(entity);')diff --git a/tools/eht/generators/embind.py b/tools/eht/generators/embind.pyindex 6f536e645..0ca383f4f 100644--- a/tools/eht/generators/embind.py+++ b/tools/eht/generators/embind.py@@ -1,7 +1,7 @@"""Emscripten embind C++ bindings generator."""from typing import List, Set-from ..data import Component, Enum, READ_HOOKS+from ..data import Component, Enum, HIERARCHY_COMPONENTS, READ_HOOKSfrom ..type_system import TypeSystem@@ -185,6 +185,12 @@ class EmbindGenerator:lines.append('};')lines.append('')+ # A hierarchy component is never written field-wise — setParent owns+ # both halves — so only the read direction is generated for it.+ if comp.name in HIERARCHY_COMPONENTS:+ lines.extend(self._gen_to_js(comp, full, js))+ continue+# Assign onto an existing component rather than build a new one: a# component may carry engine-computed state that no ES_PROPERTY# declares (UIVisual.uiOrder, UINode.computed_size_), and replacing@@ -220,29 +226,7 @@ class EmbindGenerator:lines.append('}')lines.append('')- lines.append(f'{js} {comp.name.lower()}ToJS(const {full}& c) {{')- lines.append(f' {js} js;')- for prop in comp.properties:- if self.types.is_skip(prop.cpp_type):- continue- t = self.types.clean_type(prop.cpp_type)- if self.types.is_handle(prop.cpp_type):- lines.append(f' js.{prop.name} = c.{prop.name}.id();')- elif self.types.is_entity(prop.cpp_type):- lines.append(f' js.{prop.name} = static_cast<u32>(c.{prop.name});')- elif self.types.is_enum(prop.cpp_type):- lines.append(f' js.{prop.name} = static_cast<i32>(c.{prop.name});')- elif t in self.types.VECTOR_TYPES and self.types.VECTOR_TYPES[t][0] == 'u32' and 'Entity' in t:- lines.append(f' js.{prop.name}.reserve(c.{prop.name}.size());')- lines.append(f' for (auto e : c.{prop.name}) js.{prop.name}.push_back(static_cast<u32>(e));')- elif self.types.is_struct_vector(t):- lines.append(f' js.{prop.name} = emscripten::val::array();')- lines.append(f' for (size_t i = 0; i < c.{prop.name}.size(); ++i) js.{prop.name}.set(i, emscripten::val(c.{prop.name}[i]));')- else:- lines.append(f' js.{prop.name} = c.{prop.name};')- lines.append(' return js;')- lines.append('}')- lines.append('')+ lines.extend(self._gen_to_js(comp, full, js))lines.append('EMSCRIPTEN_BINDINGS(esengine_components) {')@@ -302,6 +286,64 @@ class EmbindGenerator:])return lines+ def _gen_to_js(self, comp: Component, full: str, js: str) -> List[str]:+ lines = [+ f'{js} {comp.name.lower()}ToJS(const {full}& c) {{',+ f' {js} js;',+ ]+ for prop in comp.properties:+ if self.types.is_skip(prop.cpp_type):+ continue+ t = self.types.clean_type(prop.cpp_type)+ if self.types.is_handle(prop.cpp_type):+ lines.append(f' js.{prop.name} = c.{prop.name}.id();')+ elif self.types.is_entity(prop.cpp_type):+ lines.append(f' js.{prop.name} = static_cast<u32>(c.{prop.name});')+ elif self.types.is_enum(prop.cpp_type):+ lines.append(f' js.{prop.name} = static_cast<i32>(c.{prop.name});')+ elif t in self.types.VECTOR_TYPES and self.types.VECTOR_TYPES[t][0] == 'u32' and 'Entity' in t:+ lines.append(f' js.{prop.name}.reserve(c.{prop.name}.size());')+ lines.append(f' for (auto e : c.{prop.name}) js.{prop.name}.push_back(static_cast<u32>(e));')+ elif self.types.is_struct_vector(t):+ lines.append(f' js.{prop.name} = emscripten::val::array();')+ lines.append(f' for (size_t i = 0; i < c.{prop.name}.size(); ++i) js.{prop.name}.set(i, emscripten::val(c.{prop.name}[i]));')+ else:+ lines.append(f' js.{prop.name} = c.{prop.name};')+ lines.extend([' return js;', '}', ''])+ return lines++ def _gen_hierarchy_writers(self, name: str, full: str, js: str) -> List[str]:+ if name == 'Parent':+ return [+ f' .function("add{name}", optional_override([](Registry& r, u32 e, const {js}& js) {{',+ ' auto entity = static_cast<Entity>(e);',+ ' if (!r.valid(entity)) return;',+ ' esengine::ecs::setParent(r, entity, static_cast<Entity>(js.entity));',+ ' }))',+ f' .function("remove{name}", optional_override([](Registry& r, u32 e) {{',+ ' auto entity = static_cast<Entity>(e);',+ f' if (!r.valid(entity) || !r.has<{full}>(entity)) return;',+ ' esengine::ecs::setParent(r, entity, INVALID_ENTITY);',+ ' }))',+ ]+ return [+ f' .function("add{name}", optional_override([](Registry& r, u32 e, const {js}& js) {{',+ ' auto entity = static_cast<Entity>(e);',+ ' if (!r.valid(entity)) return;',+ ' for (auto v : js.entities) {',+ ' esengine::ecs::setParent(r, static_cast<Entity>(v), entity);',+ ' }',+ ' }))',+ f' .function("remove{name}", optional_override([](Registry& r, u32 e) {{',+ ' auto entity = static_cast<Entity>(e);',+ f' if (!r.valid(entity) || !r.has<{full}>(entity)) return;',+ f' const auto kids = r.get<{full}>(entity).entities;',+ ' for (auto child : kids) {',+ ' esengine::ecs::setParent(r, child, INVALID_ENTITY);',+ ' }',+ ' }))',+ ]+def _gen_registry(self) -> List[str]:lines = ['// =============================================================================',@@ -339,6 +381,16 @@ class EmbindGenerator:read_hook = READ_HOOKS.get(name)+ if name in HIERARCHY_COMPONENTS:+ lines.append(f' .function("get{name}", optional_override([](Registry& r, u32 e) {{')+ lines.append(f' auto entity = static_cast<Entity>(e);')+ lines.append(f' if (!r.valid(entity) || !r.has<{full}>(entity)) return {js}{{}};')+ lines.append(f' return {to_js}(r.get<{full}>(entity));')+ lines.append(' }))')+ lines.extend(self._gen_hierarchy_writers(name, full, js))+ lines.append('')+ continue+if needs_wrap:lines.append(f' .function("get{name}", optional_override([](Registry& r, u32 e) {{')lines.append(f' auto entity = static_cast<Entity>(e);')