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 Mut row kept past the loop stays live until the system returns
yhh56d38f273cc6
diff --git a/sdk/src/ecs/query.ts b/sdk/src/ecs/query.tsindex ebeae03ae..99ce15822 100644--- a/sdk/src/ecs/query.ts+++ b/sdk/src/ecs/query.ts@@ -401,6 +401,12 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Quprivate readonly allRequired_: AnyComponentDef[];private readonly result_: unknown[];private readonly mutData_: Array<{ component: AnyComponentDef; data: Record<string, unknown> }>;+ /**+ * Mut rows the iterator handed out and the caller may still be holding:+ * entity, which Mut slot, and the very object it was given. Written once more+ * when the system returns — see {@link settleKeptRows}.+ */+ private kept_: Array<{ entity: Entity; slot: number; data: Record<string, unknown> }> = [];private readonly cacheKey_: string;// Static cache-dependency ids (required + with + without + filter deps),// precomputed like cacheKey_ so per-call query iteration allocates no array.@@ -598,6 +604,42 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Qu}}+ /**+ * @internal Write the Mut rows this query's iterator handed out once more,+ * now that the system has returned. Called by the runner, before the+ * system's Commands flush.+ *+ * The iterator's rows are the ones a caller may KEEP, and keeping them is+ * how a system edits after the loop: collect, sort, then change the nearest.+ * A script component's row is its stored object, so that edit already landed;+ * an engine-backed one (Transform, Sprite) is a copy written back as the loop+ * advanced, and an edit made after that was silently dropped. Until the+ * system returns a kept row stays live. The lent rows of {@link forEach} are+ * not tracked and cost nothing here.+ */+ settleKeptRows(): void {+ const kept = this.kept_;+ if (kept.length === 0) return;+ const world = this.world_;+ const mutData = this.mutData_;+ const mutSetters = this.mutSetters_;+ const mutIsBuiltin = this.mutIsBuiltin_;+ try {+ for (const { entity, slot, data } of kept) {+ if (!world.valid(entity)) continue;+ const component = mutData[slot].component;+ if (mutIsBuiltin[slot]) {+ const setter = mutSetters[slot];+ if (setter) setter(entity, data);+ else world.set(entity, component, data);+ }+ world.markChanged(entity, component);+ }+ } finally {+ kept.length = 0;+ }+ }+/*** Rows the caller may keep: a fresh array per entity, and for an* engine-backed component a fresh value rather than the shared fill target.@@ -616,6 +658,7 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Quconst world = this.world_;const getters = this.gettersRetained_;const self = this;+ const kept = this.kept_;let idx = 0;let prevEntity: Entity | null = null;@@ -678,7 +721,9 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Quif (hasMut) {for (let i = 0; i < mutCount; i++) {- mutData[i].data = row[_mutIndices[i] + 1] as Record<string, unknown>;+ const data = row[_mutIndices[i] + 1] as Record<string, unknown>;+ mutData[i].data = data;+ kept.push({ entity, slot: i, data });}prevEntity = entity;}diff --git a/sdk/src/ecs/system.ts b/sdk/src/ecs/system.tsindex f6c0d6b5e..26a228371 100644--- a/sdk/src/ecs/system.ts+++ b/sdk/src/ecs/system.ts@@ -597,6 +597,12 @@ export class SystemRunner {}private flushSystem_(system: SystemDef, args: unknown[], t0: number): void {+ // Kept Mut rows first: the edits a system made to rows it held past the+ // loop belong to the entities as they stood, before its Commands despawn+ // or restructure any of them.+ for (let i = 0; i < args.length; i++) {+ if (args[i] instanceof QueryInstance) (args[i] as QueryInstance<readonly QueryArg[]>).settleKeptRows();+ }for (let i = 0; i < args.length; i++) {if (args[i] instanceof CommandsInstance) {(args[i] as CommandsInstance).flush();diff --git a/sdk/tests/query-kept-mut-rows.test.ts b/sdk/tests/query-kept-mut-rows.test.tsnew file mode 100644index 000000000..3b0c42082--- /dev/null+++ b/sdk/tests/query-kept-mut-rows.test.ts@@ -0,0 +1,39 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * A Mut row the iterator handed out stays live until the system returns: collect+ * the rows, decide, then edit the chosen one. An engine-backed component's row is+ * a copy, and an edit made after the loop had moved on was silently dropped.+ */+import { describe, it, expect } from 'vitest';+import { World } from '../src/ecs/world';+import { Query, QueryInstance, Mut } from '../src/ecs/query';+import { Transform, type TransformData } from '../src/ecs/component';+import { createMockModule } from './mocks/wasm';++function transformAt(x: number): TransformData {+ return {+ position: { x, y: 0, z: 0 }, rotation: { w: 1, x: 0, y: 0, z: 0 }, scale: { x: 1, y: 1, z: 1 },+ worldPosition: { x, y: 0, z: 0 }, worldRotation: { w: 1, x: 0, y: 0, z: 0 }, worldScale: { x: 1, y: 1, z: 1 },+ } as TransformData;+}++describe('kept Mut rows', () => {+ it('an edit made after the loop reaches the engine once the system returns', () => {+ const mod = createMockModule();+ const world = new World();+ world.connectCpp(mod.getRegistry(), mod);+ const near = world.spawn(); world.insert(near, Transform, transformAt(1));+ const far = world.spawn(); world.insert(far, Transform, transformAt(9));++ const query = new QueryInstance(world, Query(Mut(Transform)), -1);+ const rows = [...query];+ rows.sort((a, b) => a[1].position.x - b[1].position.x);+ rows[0][1].position.y = 42; // after the loop: the row has been written back already+ expect(world.get(near, Transform).position.y).toBe(0);++ query.settleKeptRows(); // what the runner does when the system returns+ expect(world.get(near, Transform).position.y).toBe(42);+ expect(world.get(far, Transform).position.y).toBe(0);+ });+});