Skip to content

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.

fix(ecs): cmds.spawn(...).id() inside a query reserves the id instead of throwing

yhhf9b652bb4e4d
diff --git a/sdk/src/ecs/commands.ts b/sdk/src/ecs/commands.ts
index 1735e9107..8a0a4a9a8 100644
--- a/sdk/src/ecs/commands.ts
+++ b/sdk/src/ecs/commands.ts
@@ -101,7 +101,9 @@ type Command =
/**
* One entity's share of a {@link CommandsInstance}: chain `insert`/`remove` and
* let the queue apply them. Asking {@link EntityCommands.id} for a spawn's
- * entity materialises it early, because an id has to exist to be answered.
+ * entity materialises it early, because an id has to exist to be answered —
+ * except inside a running query, where the id is reserved and the spawn still
+ * lands at the flush.
*
* @public
*/
@@ -177,7 +179,11 @@ export class EntityCommands {
id(): Entity {
if (this.isNew_ && this.entityRef_.entity === 0) {
- this.finalize();
+ // Inside a running query the spawn cannot happen yet, but its identity
+ // can: reserve it, and let the flush spawn into it. Outside one the
+ // spawn lands now, as it always has.
+ if (this.commands_.isWorldIterating()) this.entityRef_.entity = this.commands_.reserveEntity();
+ else this.finalize();
}
return this.entityRef_.entity;
}
@@ -259,6 +265,16 @@ export class CommandsInstance {
this.pending_.push({ type: 'set_parent', entity, parent });
}
+ /** @internal Whether the world is inside a query walk, where a spawn must wait. */
+ isWorldIterating(): boolean {
+ return this.world_.isIterating();
+ }
+
+ /** @internal An identity for a spawn that will be applied at flush. */
+ reserveEntity(): Entity {
+ return this.world_.reserveEntity();
+ }
+
/** @internal How EntityCommands applies a deferred spawn — `entityRef` is the
* handle it already gave the caller, filled in once the entity exists. */
spawnImmediate(
@@ -267,7 +283,10 @@ export class CommandsInstance {
name?: string,
parent?: Entity | null,
): void {
- const entity = this.world_.spawn(name);
+ // A reserved id (see EntityCommands.id) is spawned into, not replaced.
+ let entity = entityRef.entity;
+ if (entity !== 0 && this.world_.valid(entity)) this.world_.commitReservedSpawn(entity, name);
+ else entity = this.world_.spawn(name);
entityRef.entity = entity;
for (const entry of components) {
diff --git a/sdk/src/ecs/world.ts b/sdk/src/ecs/world.ts
index 7ce002bcc..9ffa51b37 100644
--- a/sdk/src/ecs/world.ts
+++ b/sdk/src/ecs/world.ts
@@ -268,7 +268,31 @@ export class World {
'Use Commands to defer entity creation until after iteration completes.'
);
}
+ const entity = this.allocateEntity_();
+ this.commitSpawn_(entity, name);
+ return entity;
+ }
+
+ /**
+ * @internal An identity for a spawn {@link Commands} will apply later — what
+ * `cmds.spawn(...).id()` answers while a query is running. Allowed mid-iteration
+ * because it touches no component storage: a bare id is in no query. The spawn
+ * itself (name, components, spawn callbacks) happens at
+ * {@link commitReservedSpawn}, when the commands flush.
+ */
+ reserveEntity(): Entity {
+ if (this.speculation_) {
+ throw new Error('Cannot reserve an entity inside a speculation.');
+ }
+ return this.allocateEntity_();
+ }
+ /** @internal Finish a spawn begun by {@link reserveEntity}. */
+ commitReservedSpawn(entity: Entity, name?: string): void {
+ this.commitSpawn_(entity, name);
+ }
+
+ private allocateEntity_(): Entity {
let entity: Entity;
const cppRegistry = this.builtin_.getCppRegistry();
@@ -299,6 +323,10 @@ export class World {
}
this.entities_.set(entity, generation);
this.indexGeneration_.set(entityIndex(entity), entityGeneration(entity));
+ return entity;
+ }
+
+ private commitSpawn_(entity: Entity, name?: string): void {
this.queries_.markStructuralChange();
if (name !== undefined) {
@@ -310,8 +338,6 @@ export class World {
}
notifyBridge('onEntitySpawned', entity, name);
-
- return entity;
}
/**
diff --git a/sdk/tests/commands-spawn-in-query.test.ts b/sdk/tests/commands-spawn-in-query.test.ts
new file mode 100644
index 000000000..ccf28d768
--- /dev/null
+++ b/sdk/tests/commands-spawn-in-query.test.ts
@@ -0,0 +1,40 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * `cmds.spawn(...).id()` inside a query loop: the id is reserved on the spot and
+ * the spawn lands when the commands flush, instead of throwing "Cannot spawn
+ * entity during query iteration".
+ */
+import { describe, it, expect } from 'vitest';
+import { App } from '../src/app/app';
+import { defineSystem } from '../src/ecs/system';
+import { Query } from '../src/ecs/query';
+import { Commands } from '../src/ecs/commands';
+import { defineComponent } from '../src/ecs/component';
+import type { Entity } from '../src/types';
+
+describe('Commands.spawn().id() during a query', () => {
+ it('reserves the id and spawns into it at flush', async () => {
+ const Source = defineComponent('SpawnInQuerySource', { n: 0 });
+ const Child = defineComponent('SpawnInQueryChild', { of: 0 });
+ const app = App.new();
+ const a = app.world.spawn(); app.world.insert(a, Source, { n: 1 });
+ const b = app.world.spawn(); app.world.insert(b, Source, { n: 2 });
+ const made: Entity[] = [];
+ app.addSystem(defineSystem([Query(Source), Commands()], (q, cmds) => {
+ for (const [entity] of q) {
+ const id = cmds.spawn('child').insert(Child, { of: entity as number }).id();
+ expect(id).not.toBe(0);
+ made.push(id);
+ }
+ }, { name: 'SpawnInQuery' }));
+ await app.tick(1 / 60);
+ expect(made).toHaveLength(2);
+ expect(new Set(made).size).toBe(2);
+ for (const id of made) {
+ expect(app.world.valid(id)).toBe(true);
+ expect(app.world.has(id, Child)).toBe(true);
+ }
+ expect(made.map((id) => app.world.get(id, Child).of).sort()).toEqual([a, b].map(Number).sort());
+ });
+});
diff --git a/sdk/tests/commands.test.ts b/sdk/tests/commands.test.ts
index 022d9b587..07c5a8844 100644
--- a/sdk/tests/commands.test.ts
+++ b/sdk/tests/commands.test.ts
@@ -17,6 +17,7 @@ function createMockWorld() {
const components = new Map<Entity, Map<string, any>>();
const world = {
+ isIterating: () => false,
spawn: vi.fn((name?: string) => {
const entity = nextId++ as Entity;
validEntities.add(entity);