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(sdk): Mut() write-back records Changed for builtin components

yhh7c8e5874cc09
diff --git a/sdk/benchmarks/query-mut-writeback.bench.ts b/sdk/benchmarks/query-mut-writeback.bench.ts
new file mode 100644
index 000000000..b0c7d695a
--- /dev/null
+++ b/sdk/benchmarks/query-mut-writeback.bench.ts
@@ -0,0 +1,66 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file query-mut-writeback.bench.ts
+ * @brief Quantify the cost of recording change tracking on the Mut() write-back
+ * hot path for BUILTIN (wasm-backed) components. The fix adds one
+ * world.markChanged() to the builtin-setter branch; recordChanged()
+ * self-gates on trackedComponents_, so with no Changed()/Added() query
+ * listening it is a Set.has() + return. This bench shows the untracked
+ * path stays close to the read-only floor, and the tracked delta (the
+ * Map.set that only runs when someone is actually listening) is small.
+ */
+import { bench, describe } from 'vitest';
+import { World } from '../src/world';
+import { Query, QueryInstance, Mut } from '../src/query';
+import { Transform, type TransformData } from '../src/component';
+import { createMockModule } from '../tests/mocks/wasm';
+
+const N = 5000;
+
+function defaultTransform(): TransformData {
+ return {
+ position: { x: 0, y: 0, z: 0 },
+ rotation: { w: 1, x: 0, y: 0, z: 0 },
+ scale: { x: 1, y: 1, z: 1 },
+ worldPosition: { x: 0, y: 0, z: 0 },
+ worldRotation: { w: 1, x: 0, y: 0, z: 0 },
+ worldScale: { x: 1, y: 1, z: 1 },
+ } as TransformData;
+}
+
+function makeWorld(track: boolean): World {
+ const mod = createMockModule();
+ const world = new World();
+ world.connectCpp(mod.getRegistry(), mod);
+ if (track) world.enableChangeTracking(Transform);
+ for (let i = 0; i < N; i++) {
+ world.insert(world.spawn(), Transform, defaultTransform());
+ }
+ return world;
+}
+
+describe(`Mut() write-back over ${N} builtin components`, () => {
+ const untracked = makeWorld(false);
+ const tracked = makeWorld(true);
+ const readWorld = makeWorld(false);
+
+ const qUntracked = new QueryInstance(untracked, Query(Mut(Transform)), -1);
+ const qTracked = new QueryInstance(tracked, Query(Mut(Transform)), -1);
+ const qReadOnly = new QueryInstance(readWorld, Query(Transform), -1);
+
+ // Floor: iterate + read, no Mut write-back at all.
+ bench('read-only iteration (no write-back)', () => {
+ qReadOnly.forEach(() => { /* read only */ });
+ });
+
+ // Common case: Mut write-back, nobody listening → markChanged is Set.has + return.
+ bench('Mut write-back, component NOT tracked', () => {
+ qUntracked.forEach((_e, t) => { (t as TransformData).position.x += 1; });
+ });
+
+ // Worst case: Mut write-back with a live Changed() listener → records a Map.set.
+ bench('Mut write-back, component tracked', () => {
+ qTracked.forEach((_e, t) => { (t as TransformData).position.x += 1; });
+ });
+});
diff --git a/sdk/src/query.ts b/sdk/src/query.ts
index 192fac606..bdde0c6aa 100644
--- a/sdk/src/query.ts
+++ b/sdk/src/query.ts
@@ -360,6 +360,41 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Qu
return true;
}
+ /**
+ * Write buffered Mut() data back to storage for one entity and record a
+ * Changed tick for each mutated component. This is the single write-back path
+ * shared by the iterator and forEach — keeping the three former copies from
+ * drifting apart.
+ *
+ * Builtin (wasm-backed) components write through a direct ptr / embind setter
+ * that pokes component storage without going through world.set(), so the
+ * change must be recorded here explicitly to keep Changed()/Added() detection
+ * consistent with script components and with world.set(). recordChanged()
+ * self-gates on whether any query is actually tracking the component, so on
+ * the hot path with nothing listening this is a Set.has() + return.
+ */
+ private writeMutBack_(entity: Entity): void {
+ const world = this.world_;
+ if (!world.valid(entity)) return;
+ const mutData = this.mutData_;
+ const mutSetters = this.mutSetters_;
+ const mutIsBuiltin = this.mutIsBuiltin_;
+ for (let i = 0; i < mutData.length; i++) {
+ const mut = mutData[i];
+ if (mutIsBuiltin[i]) {
+ const setter = mutSetters[i];
+ if (setter) {
+ setter(entity, mut.data);
+ world.markChanged(entity, mut.component);
+ } else {
+ world.set(entity, mut.component, mut.data);
+ }
+ } else {
+ world.markChanged(entity, mut.component);
+ }
+ }
+ }
+
[Symbol.iterator](): Iterator<QueryResult<C>> {
const { _mutIndices } = this.descriptor_;
const actualComponents = this.actualComponents_;
@@ -377,7 +412,6 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Qu
const result = this.result_;
const mutData = this.mutData_;
const mutCount = mutData.length;
- const mutSetters = this.mutSetters_;
const world = this.world_;
const getters = this.getters_;
const self = this;
@@ -387,20 +421,7 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Qu
let started = false;
let done = false;
- const mutIsBuiltin = this.mutIsBuiltin_;
- const writeMut = () => {
- if (!world.valid(prevEntity!)) return;
- for (let i = 0; i < mutCount; i++) {
- const mut = mutData[i];
- if (mutIsBuiltin[i]) {
- const setter = mutSetters[i];
- if (setter) setter(prevEntity!, mut.data);
- else world.set(prevEntity!, mut.component, mut.data);
- } else {
- world.markChanged(prevEntity!, mut.component);
- }
- }
- };
+ const writeMut = () => { self.writeMutBack_(prevEntity!); };
const finalize = () => {
if (done) return;
@@ -474,7 +495,6 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Qu
const result = this.result_;
const mutData = this.mutData_;
const mutCount = mutData.length;
- const mutSetters = this.mutSetters_;
const world = this.world_;
const getters = this.getters_;
const actualComponents = this.actualComponents_;
@@ -485,17 +505,8 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Qu
const entity = entities[idx];
if (hasChangeFilters && !this.passesChangeFilters_(entity)) continue;
- if (prevEntity !== null && hasMut && world.valid(prevEntity)) {
- for (let i = 0; i < mutCount; i++) {
- const mut = mutData[i];
- if (this.mutIsBuiltin_[i]) {
- const setter = mutSetters[i];
- if (setter) setter(prevEntity, mut.data);
- else world.set(prevEntity, mut.component, mut.data);
- } else {
- world.markChanged(prevEntity, mut.component);
- }
- }
+ if (prevEntity !== null && hasMut) {
+ this.writeMutBack_(prevEntity);
}
result[0] = entity;
@@ -523,17 +534,8 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Qu
}
}
- if (prevEntity !== null && hasMut && world.valid(prevEntity)) {
- for (let i = 0; i < mutCount; i++) {
- const mut = mutData[i];
- if (this.mutIsBuiltin_[i]) {
- const setter = mutSetters[i];
- if (setter) setter(prevEntity, mut.data);
- else world.set(prevEntity, mut.component, mut.data);
- } else {
- world.markChanged(prevEntity, mut.component);
- }
- }
+ if (prevEntity !== null && hasMut) {
+ this.writeMutBack_(prevEntity);
}
world.endIteration();
}
diff --git a/sdk/tests/query-mut-change-tracking.test.ts b/sdk/tests/query-mut-change-tracking.test.ts
new file mode 100644
index 000000000..1499312d1
--- /dev/null
+++ b/sdk/tests/query-mut-change-tracking.test.ts
@@ -0,0 +1,103 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file query-mut-change-tracking.test.ts
+ * @brief A Mut() write-back to a builtin (wasm-backed) component must record a
+ * Changed tick, exactly like a script-component write or an explicit
+ * world.set(). Previously the builtin write-back path (direct ptr /
+ * embind setter) poked component storage without recording a change, so
+ * a Changed()/Added() query missed mutations made through Mut() — but
+ * ONLY for builtin components with cpp connected, which is the normal
+ * runtime. This is the regression guard for that unified behaviour.
+ */
+import { describe, it, expect } from 'vitest';
+import { World } from '../src/world';
+import { Query, QueryInstance, Mut, Changed } from '../src/query';
+import { Transform, type TransformData } from '../src/component';
+import type { Entity } from '../src/types';
+import { createMockModule } from './mocks/wasm';
+
+function defaultTransform(): TransformData {
+ return {
+ position: { x: 0, y: 0, z: 0 },
+ rotation: { w: 1, x: 0, y: 0, z: 0 },
+ scale: { x: 1, y: 1, z: 1 },
+ worldPosition: { x: 0, y: 0, z: 0 },
+ worldRotation: { w: 1, x: 0, y: 0, z: 0 },
+ worldScale: { x: 1, y: 1, z: 1 },
+ } as TransformData;
+}
+
+/** A World wired to the JS-backed mock module: builtin Transform is cpp-connected
+ * (hasCpp === true), so its Mut write-back goes through the builtin setter path. */
+function connectedWorld(): World {
+ const mod = createMockModule();
+ const world = new World();
+ world.connectCpp(mod.getRegistry(), mod);
+ return world;
+}
+
+/** Spawn one entity with a tracked Transform, then move the change into the past
+ * so a later Changed(sinceTick=0) can only be true if a NEW change is recorded. */
+function seedTrackedEntity(world: World): Entity {
+ world.enableChangeTracking(Transform);
+ const e = world.spawn();
+ world.insert(e, Transform, defaultTransform()); // recordChanged at tick 0
+ world.advanceTick(); // worldTick → 1; insert is now "past"
+ // Baseline: nothing has changed strictly after tick 0 yet.
+ return e;
+}
+
+function changedSince(world: World, sinceTick: number): Entity[] {
+ const seen: Entity[] = [];
+ new QueryInstance(world, Query(Changed(Transform)), sinceTick).forEach((entity) => {
+ seen.push(entity);
+ });
+ return seen;
+}
+
+describe('Mut() write-back records change tracking for builtin components', () => {
+ it('baseline: the entity is NOT reported changed before any Mut write', () => {
+ const world = connectedWorld();
+ const e = seedTrackedEntity(world);
+ // The insert recorded a change at tick 0; "changed strictly after tick 0" is empty.
+ expect(changedSince(world, 0)).not.toContain(e);
+ });
+
+ it('forEach Mut write marks the builtin component Changed', () => {
+ const world = connectedWorld();
+ const e = seedTrackedEntity(world);
+
+ new QueryInstance(world, Query(Mut(Transform)), -1).forEach((_entity, t) => {
+ (t as TransformData).position.x = 5;
+ });
+
+ expect(changedSince(world, 0)).toContain(e);
+ });
+
+ it('for-of (iterator) Mut write marks the builtin component Changed', () => {
+ const world = connectedWorld();
+ const e = seedTrackedEntity(world);
+
+ for (const [, t] of new QueryInstance(world, Query(Mut(Transform)), -1)) {
+ (t as TransformData).position.x = 9;
+ }
+
+ expect(changedSince(world, 0)).toContain(e);
+ });
+
+ it('a Changed() query in a later frame observes a prior-frame Mut write', () => {
+ const world = connectedWorld();
+ const e = seedTrackedEntity(world);
+ const tickBeforeWrite = world.getWorldTick(); // = 1
+
+ // Frame N: mutate through Mut().
+ new QueryInstance(world, Query(Mut(Transform)), -1).forEach((_entity, t) => {
+ (t as TransformData).position.y = 3;
+ });
+
+ // Frame N+1: a system whose lastRunTick is the pre-write tick must see it.
+ world.advanceTick();
+ expect(changedSince(world, tickBeforeWrite - 1)).toContain(e);
+ });
+});