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
feat(ecs): world.update, and no write the tracker cannot see
esengine7333d3afca2a
diff --git a/docs/MUTATION_CONTRACT.md b/docs/MUTATION_CONTRACT.mdindex 907066d7e..4ea15eacd 100644--- a/docs/MUTATION_CONTRACT.md+++ b/docs/MUTATION_CONTRACT.md@@ -114,6 +114,34 @@ shadow scan 看得见,ChangeTracker 看不见。** 只要还有一条这样的同一目录下 `layout.ts` 正在用 `world.anyChangedSince(UINode, ...)` 决定要不要重算布局——同一个 tracker,一边被当权威,一边被绕过。+## 3.5 PR6c.3:`world.update` 与静默写归零++裁定已执行第一步。新增 `world.update(entity, Component, draft => {…})`,它是「读出来、改一个字段、+其余保留」的唯一写入口:++- **脚本组件零拷贝**——draft 就是存储里那个对象,编辑后 `recordChanged`;+- **引擎组件**读投影、编辑、经 `set` 写回(hierarchy 也走它),不发明第三套机制;+- **无条件报告**:不做深比较。假阳性让消费者多看一眼,而按比较决定会在它读不懂的值上变哑;+- **`edit` 抛异常不回滚**:脚本组件上已经写进去的就是写进去了,所以在异常逃逸前先报告——+ 一个没人听见的半写正是这条路要消灭的东西;+- draft 是**借用**的,不许留存。++43 处静默写已清到 **0**,其中:++| 位置 | 处数 | 做法 |+|---|---|---|+| `text-input-plugin.ts` | 15 | 7 处改 `update`;8 处 `ti.dirty = true` **直接删** |+| `drag.ts` | 12 | 全部改 `update` |+| `sdk/tests/*` | 13 | 改走合法路径;三个假 World 补上 `update`(假实现落后于真实现正是它骗人的方式)|+| `combat.ts` | 3 | 伤害结算改 `update` |++`TextInputData.dirty` 全仓零读者,是变更观测缺位时长出来的私有 dirty 机制化石。写入已删,+字段本身标 `@deprecated` 留到下一个 MINOR——顶层未知字段在反序列化时是**错误**,+立刻删字段会让存量场景加载失败。++`mutation-census` 已升级成门禁(`--gate`,注册为 `silent-writes`):**静默写恒为 0**。+它对扫不到的 root(未检出的编辑器子模块)明说而不是静默缩小语料。+## 4. 待裁定普查给出的结论是明确的:**`get`/`tryGet`/裸 `Query` 必须收成只读**,而且必须是diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.jsonindex 8c6d9ac45..e4577fe0a 100644--- a/docs/astro/src/data/components.generated.json+++ b/docs/astro/src/data/components.generated.json@@ -4009,11 +4009,6 @@"type": "number","default": "0"},- {- "key": "dirty",- "type": "boolean",- "default": "true"- },{"key": "textAlign","type": "enum",diff --git a/examples/celestial-heights/src/systems/combat.ts b/examples/celestial-heights/src/systems/combat.tsindex 1ca7f557d..2e9f71f36 100644--- a/examples/celestial-heights/src/systems/combat.ts+++ b/examples/celestial-heights/src/systems/combat.ts@@ -50,12 +50,16 @@ export const damageSystem = defineSystem(if (!world.has(blow.target, Health)) continue;const health = world.get(blow.target, Health);if (health.invulnerable > 0 || health.current <= 0) continue;- health.current -= blow.amount;- health.invulnerable = health.invulnerability;- if (health.current <= 0) {- health.current = 0;- died.send({ entity: blow.target, isPlayer: world.has(blow.target, Player) });- }+ let killed = false;+ world.update(blow.target, Health, (h) => {+ h.current -= blow.amount;+ h.invulnerable = h.invulnerability;+ if (h.current <= 0) {+ h.current = 0;+ killed = true;+ }+ });+ if (killed) died.send({ entity: blow.target, isPlayer: world.has(blow.target, Player) });}},{ name: 'DamageSystem' },diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 4d2ff4e0f..dd6007fc1 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -8089,7 +8089,6 @@ ComponentDef<TextInputData>backgroundColor: Colorcolor: ColorcursorPos: number-dirty: booleanfocused: booleanfont: numberfontFamily: string@@ -9548,6 +9547,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+update: <C extends AnyComponentDef>(entity: Entity, component: C, edit: (draft: ComponentData<C>) => void) => voidvalid: (entity: Entity) => booleanstatic new (): Worldstatic prototype: Worlddiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 36b0803ca..9f4948c6d 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -8282,7 +8282,6 @@ ComponentDef<TextInputData>backgroundColor: Colorcolor: ColorcursorPos: number-dirty: booleanfocused: booleanfont: numberfontFamily: string@@ -9741,6 +9740,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+update: <C extends AnyComponentDef>(entity: Entity, component: C, edit: (draft: ComponentData<C>) => void) => voidvalid: (entity: Entity) => booleanstatic new (): Worldstatic prototype: Worlddiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 5c16bdee3..cdf9af7cc 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -8084,7 +8084,6 @@ ComponentDef<TextInputData>backgroundColor: Colorcolor: ColorcursorPos: number-dirty: booleanfocused: booleanfont: numberfontFamily: string@@ -9543,6 +9542,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+update: <C extends AnyComponentDef>(entity: Entity, component: C, edit: (draft: ComponentData<C>) => void) => voidvalid: (entity: Entity) => booleanstatic new (): Worldstatic prototype: Worlddiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 45e615048..c84c22335 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -8330,7 +8330,6 @@ ComponentDef<TextInputData>backgroundColor: Colorcolor: ColorcursorPos: number-dirty: booleanfocused: booleanfont: numberfontFamily: string@@ -9795,6 +9794,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+update: <C extends AnyComponentDef>(entity: Entity, component: C, edit: (draft: ComponentData<C>) => void) => voidvalid: (entity: Entity) => booleanstatic new (): Worldstatic prototype: Worlddiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 5d8037b00..e6d50228a 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -8091,7 +8091,6 @@ ComponentDef<TextInputData>backgroundColor: Colorcolor: ColorcursorPos: number-dirty: booleanfocused: booleanfont: numberfontFamily: string@@ -9571,6 +9570,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+update: <C extends AnyComponentDef>(entity: Entity, component: C, edit: (draft: ComponentData<C>) => void) => voidvalid: (entity: Entity) => booleanstatic new (): Worldstatic prototype: Worlddiff --git a/sdk/src/ecs/world.ts b/sdk/src/ecs/world.tsindex 3946409e1..bb5356f25 100644--- a/sdk/src/ecs/world.ts+++ b/sdk/src/ecs/world.ts@@ -702,10 +702,54 @@ export class World {}/**- * The component's value. Asking for one the entity does not have is a- * programming error, not a case to handle — use {@link tryGet} where absence- * is expected. Engine-backed components answer a fresh object each call;- * writing to it does not store anything, {@link set} does.+ * Edit a component in place and report the change — the write path for+ * "read it, adjust a field, keep the rest". The draft is BORROWED for the+ * call, and for a script component it IS the stored object, so nothing may+ * keep it. Reporting is unconditional; a false positive costs one look.+ *+ * @throws if `entity` does not carry `component`.+ */+ update<C extends AnyComponentDef>(+ entity: Entity,+ component: C,+ edit: (draft: ComponentData<C>) => void,+ ): void {+ if (!this.has(entity, component)) {+ throw new Error(+ `update(${component._name}, entity=${entity}): the entity does not carry it. `+ + 'Use insert() or set() to add a component.'+ );+ }+ if (isBuiltinComponent(component)) {+ // A projection, so the write-back is what stores it; `set` owns that+ // for every builtin shape, hierarchy included, and records the change.+ const draft = this.builtin_.get(entity, component) as ComponentData<C>;+ try {+ edit(draft);+ } finally {+ this.set(entity, component, draft);+ }+ return;+ }+ const draft = this.scripts_.get(entity, component as ComponentDef<any>) as ComponentData<C>;+ try {+ edit(draft);+ } finally {+ // A throwing `edit` has already written to the live object, so the+ // change is reported before the error escapes.+ this.changes_.recordChanged(component, entity);+ if ((component as ComponentDef<any>)._id === Name._id) {+ this.names_.update(entity, (draft as { value: string }).value);+ }+ notifyBridge('onComponentChanged', entity, component._name);+ }+ }++ /**+ * The component's value, to READ. Writing to the result is deprecated: it+ * stores nothing for an engine-backed component and changes a script one+ * with nothing observing it — use {@link update}, {@link set} or `Mut()`.+ * Asking for a component the entity lacks throws; {@link tryGet} allows it.*/get<C extends AnyComponentDef>(entity: Entity, component: C): ComponentData<C> {if (isBuiltinComponent(component)) {@@ -726,7 +770,9 @@ export class World {return this.scripts_.has(entity, component as ComponentDef<any>);}- /** {@link get}, answering null instead of throwing when the component is absent. */+ /** {@link get}, answering null instead of throwing when the component is+ * absent. Reading only, on the same terms — writing to the result is+ * deprecated; {@link update} is the edit. */tryGet<C extends AnyComponentDef>(entity: Entity, component: C): ComponentData<C> | null {if (isBuiltinComponent(component)) {if (!this.builtin_.hasCpp) return null;diff --git a/sdk/src/ui/input/drag.ts b/sdk/src/ui/input/drag.tsindex ac97fb92e..4bbe5dece 100644--- a/sdk/src/ui/input/drag.ts+++ b/sdk/src/ui/input/drag.ts@@ -128,21 +128,21 @@ export class DragPlugin implements Plugin {if (!world.has(bestEntity, DragState)) {world.insert(bestEntity, DragState);}- const dragState = world.get(bestEntity, DragState) as DragStateData;const wt = world.get(bestEntity, Transform) as TransformData;- dragState.startWorldPos = { x: wt.worldPosition.x, y: wt.worldPosition.y };- dragState.currentWorldPos = { x: wt.worldPosition.x, y: wt.worldPosition.y };- dragState.pointerStartWorld = { x: worldMouse.x, y: worldMouse.y };- dragState.deltaWorld = { x: 0, y: 0 };- dragState.totalDeltaWorld = { x: 0, y: 0 };- dragState.isDragging = false;+ world.update(bestEntity, DragState, (d) => {+ d.startWorldPos = { x: wt.worldPosition.x, y: wt.worldPosition.y };+ d.currentWorldPos = { x: wt.worldPosition.x, y: wt.worldPosition.y };+ d.pointerStartWorld = { x: worldMouse.x, y: worldMouse.y };+ d.deltaWorld = { x: 0, y: 0 };+ d.totalDeltaWorld = { x: 0, y: 0 };+ d.isDragging = false;+ });}}if (pendingEntity !== null && !input.isMouseButtonDown(0)) {if (world.valid(pendingEntity) && world.has(pendingEntity, DragState)) {- const dragState = world.get(pendingEntity, DragState) as DragStateData;- dragState.isDragging = false;+ world.update(pendingEntity, DragState, (d) => { d.isDragging = false; });}pendingEntity = null;}@@ -162,8 +162,7 @@ export class DragPlugin implements Plugin {activeEntity = pendingEntity;pendingEntity = null;- const dragState = world.get(activeEntity, DragState) as DragStateData;- dragState.isDragging = true;+ world.update(activeEntity, DragState, (d) => { d.isDragging = true; });events.emit(activeEntity, 'drag_start');}}@@ -189,12 +188,14 @@ export class DragPlugin implements Plugin {const prevX = dragState.currentWorldPos.x;const prevY = dragState.currentWorldPos.y;- dragState.deltaWorld = { x: newWorldX - prevX, y: newWorldY - prevY };- dragState.currentWorldPos = { x: newWorldX, y: newWorldY };- dragState.totalDeltaWorld = {- x: newWorldX - dragState.startWorldPos.x,- y: newWorldY - dragState.startWorldPos.y,- };+ world.update(activeEntity, DragState, (d) => {+ d.deltaWorld = { x: newWorldX - prevX, y: newWorldY - prevY };+ d.currentWorldPos = { x: newWorldX, y: newWorldY };+ d.totalDeltaWorld = {+ x: newWorldX - d.startWorldPos.x,+ y: newWorldY - d.startWorldPos.y,+ };+ });if (world.has(activeEntity, UINode)) {// Nudge the CSS-box absolute insets (the layout input), so@@ -214,16 +215,16 @@ export class DragPlugin implements Plugin {world, activeEntity,dragState.deltaWorld.x, dragState.deltaWorld.y);- const lt = world.get(activeEntity, Transform) as TransformData;- lt.position.x += localDelta.x;- lt.position.y += localDelta.y;- world.insert(activeEntity, Transform, lt);+ world.update(activeEntity, Transform, (t) => {+ t.position.x += localDelta.x;+ t.position.y += localDelta.y;+ });}events.emit(activeEntity, 'drag_move');if (input.isMouseButtonReleased(0)) {- dragState.isDragging = false;+ world.update(activeEntity, DragState, (d) => { d.isDragging = false; });events.emit(activeEntity, 'drag_end');activeEntity = null;}diff --git a/sdk/src/ui/text/text-input-plugin.ts b/sdk/src/ui/text/text-input-plugin.tsindex f12da326f..e115cb3ff 100644--- a/sdk/src/ui/text/text-input-plugin.ts+++ b/sdk/src/ui/text/text-input-plugin.ts@@ -117,10 +117,8 @@ export class TextInputPlugin implements Plugin {case 'composition':// The preedit sits in the surface's value with the caret after// it, and the render loop reads that live — so nothing is copied- // here. This keeps the caret solid and the field dirty while the- // composition moves, and commits it when it ends.+ // here, and the commit at the end is what writes the field.composing = event.composing;- if (focused !== null) (world.get(focused, TextInput) as TextInputData).dirty = true;if (!event.composing && focused !== null) syncFromEditor();resetCursorBlink();break;@@ -135,9 +133,7 @@ export class TextInputPlugin implements Plugin {break;case 'blur':if (focused !== null) {- const ti = world.get(focused, TextInput) as TextInputData;- ti.focused = false;- ti.dirty = true;+ world.update(focused, TextInput, (ti) => { ti.focused = false; });(app.getResource(FocusManager) as FocusManagerState).blur();// The manager only holds "who has focus"; the entity holds// it too. Clearing one and not the other leaves a control@@ -176,13 +172,14 @@ export class TextInputPlugin implements Plugin {editor!.write({ ...state, value: val, selectionStart: val.length, selectionEnd: val.length });}- if (val !== ti.value) {- ti.value = val;- const events = app.getResource(UIEvents) as UIEventQueue;- events.emit(focused, 'change');+ const valueChanged = val !== ti.value;+ world.update(focused, TextInput, (d) => {+ d.value = val;+ d.cursorPos = Math.min(state.selectionStart, val.length);+ });+ if (valueChanged) {+ (app.getResource(UIEvents) as UIEventQueue).emit(focused, 'change');}- ti.cursorPos = Math.min(state.selectionStart, val.length);- ti.dirty = true;resetCursorBlink();}@@ -245,8 +242,7 @@ export class TextInputPlugin implements Plugin {const ti = world.get(entity, TextInput) as TextInputData;if (ti.readOnly) return;- ti.focused = true;- ti.dirty = true;+ world.update(entity, TextInput, (d) => { d.focused = true; });editor!.focus({ value: ti.value, selectionStart: ti.cursorPos, selectionEnd: ti.cursorPos, backward: false },@@ -258,9 +254,7 @@ export class TextInputPlugin implements Plugin {function blurCurrent(): void {const focused = getFocusedTextInput();if (focused !== null) {- const ti = world.get(focused, TextInput) as TextInputData;- ti.focused = false;- ti.dirty = true;+ world.update(focused, TextInput, (ti) => { ti.focused = false; });}const fm = app.getResource(FocusManager) as FocusManagerState;fm.blur();@@ -326,9 +320,7 @@ export class TextInputPlugin implements Plugin {// the surface on its way in.if (prevFocusedTextInput !== null && prevFocusedTextInput !== currentFocused&& world.valid(prevFocusedTextInput) && world.has(prevFocusedTextInput, TextInput)) {- const ti = world.get(prevFocusedTextInput, TextInput) as TextInputData;- ti.focused = false;- ti.dirty = true;+ world.update(prevFocusedTextInput, TextInput, (ti) => { ti.focused = false; });editor.blur();}@@ -349,9 +341,7 @@ export class TextInputPlugin implements Plugin {const idx = caretIndexFromPointer(currentFocused);if (idx !== null) {editor.write({ ...editor.read(), selectionStart: idx, selectionEnd: idx, backward: false });- const ti = world.get(currentFocused, TextInput) as TextInputData;- ti.cursorPos = idx;- ti.dirty = true;+ world.update(currentFocused, TextInput, (ti) => { ti.cursorPos = idx; });resetCursorBlink();}}@@ -414,7 +404,9 @@ export class TextInputPlugin implements Plugin {? fieldSelection(state.selectionStart, state.selectionEnd, state.backward, len): { lo: 0, hi: 0, caret: Math.max(0, Math.min(ti.cursorPos, len)), hasRange: false };// Keep the component caret in step so a blur/refocus restores it.- if (editing && ti.cursorPos !== sel.caret) ti.cursorPos = sel.caret;+ if (editing && ti.cursorPos !== sel.caret) {+ world.update(entity, TextInput, (d) => { d.cursorPos = sel.caret; });+ }const disp = textFieldDisplay(val, ti.password, ti.placeholder, PASSWORD_CHAR);const atlas = ensureMeasure().atlas;diff --git a/sdk/src/ui/text/text-input.ts b/sdk/src/ui/text/text-input.tsindex 59e75bcf4..641ab79f7 100644--- a/sdk/src/ui/text/text-input.ts+++ b/sdk/src/ui/text/text-input.ts@@ -23,7 +23,6 @@ export interface TextInputData {readOnly: boolean;focused: boolean;cursorPos: number;- dirty: boolean;/** Where the value sits in the field: Left, Center or Right. A single line* keeps the alignment only while it fits — past that the field scrolls to* follow the caret, as a left-aligned one always has. */@@ -49,7 +48,6 @@ export const TextInput = defineComponent<TextInputData>('TextInput', {readOnly: false,focused: false,cursorPos: 0,- dirty: true,textAlign: TextAlign.Left,renderMode: TextRenderMode.Auto,}, {diff --git a/sdk/src/ui/widgets/prefabs/TextInput.esprefab b/sdk/src/ui/widgets/prefabs/TextInput.esprefabindex 62c18385e..66ef83172 100644--- a/sdk/src/ui/widgets/prefabs/TextInput.esprefab+++ b/sdk/src/ui/widgets/prefabs/TextInput.esprefab@@ -165,7 +165,6 @@"readOnly": false,"focused": false,"cursorPos": 0,- "dirty": true,"renderMode": 0}},diff --git a/sdk/src/ui/widgets/prefabs/generated.ts b/sdk/src/ui/widgets/prefabs/generated.tsindex b65340318..360aec813 100644--- a/sdk/src/ui/widgets/prefabs/generated.ts+++ b/sdk/src/ui/widgets/prefabs/generated.ts@@ -1883,7 +1883,6 @@ export const BUILTIN_UI_PREFABS: Record<string, PrefabData> = {"readOnly": false,"focused": false,"cursorPos": 0,- "dirty": true,"renderMode": 0}},diff --git a/sdk/src/ui/widgets/text-input.ts b/sdk/src/ui/widgets/text-input.tsindex 92fcfe200..bf77a3bf7 100644--- a/sdk/src/ui/widgets/text-input.ts+++ b/sdk/src/ui/widgets/text-input.ts@@ -88,7 +88,6 @@ export function createTextInput(opts: TextInputOptions): TextInputHandle {readOnly: opts.readOnly ?? false,focused: false,cursorPos: (opts.value ?? '').length,- dirty: true,renderMode: opts.renderMode ?? TextRenderMode.Auto,});markThemed(world, entity, {@@ -114,12 +113,11 @@ export function createTextInput(opts: TextInputOptions): TextInputHandle {entity,getValue: () => (world.get(entity, TextInput) as TextInputData).value,setValue: (value: string) => {- const ti = world.get(entity, TextInput) as TextInputData;- if (ti.value === value) return;- ti.value = value;- ti.cursorPos = Math.min(ti.cursorPos, value.length);- ti.dirty = true;- world.insert(entity, TextInput, ti);+ if ((world.get(entity, TextInput) as TextInputData).value === value) return;+ world.update(entity, TextInput, (ti) => {+ ti.value = value;+ ti.cursorPos = Math.min(ti.cursorPos, value.length);+ });},dispose: () => {offChange?.();diff --git a/sdk/tests/animator-substate.test.ts b/sdk/tests/animator-substate.test.tsindex 95cbe706b..c95b33020 100644--- a/sdk/tests/animator-substate.test.ts+++ b/sdk/tests/animator-substate.test.ts@@ -139,6 +139,7 @@ function makeWorld() {insert(e: number, c: unknown, data: unknown) { mapOf(c).set(e, data); },get(e: number, c: unknown) { return mapOf(c).get(e); },has(e: number, c: unknown) { return mapOf(c).has(e); },+ update(e: number, c: unknown, edit: (d: unknown) => void) { edit(mapOf(c).get(e)); },getEntitiesWithComponents(comps: unknown[]) {const [first, ...rest] = comps;return [...mapOf(first).keys()].filter((e) => rest.every((c) => mapOf(c).has(e)));@@ -183,8 +184,7 @@ describe('AnimatorControllerAPI.update — nested machine', () => {ctrl.setTrigger(E, 'attack');ctrl.update(world); // → Combat/Swing (swing clip applied, loop:false)// Simulate the swing clip finishing so its exit-time edge can fire.- const sp = world.get(E, SpriteAnimator) as SpriteAnimatorData;- sp.playing = false;+ world.update(E, SpriteAnimator, (sp: SpriteAnimatorData) => { sp.playing = false; });ctrl.update(world);expect(animPath(world)).toBe('Combat/Recover');expect(clip(world)).toBe('recover');diff --git a/sdk/tests/physics3d-ecs.test.ts b/sdk/tests/physics3d-ecs.test.tsindex 5d8bbd134..cd7603d9a 100644--- a/sdk/tests/physics3d-ecs.test.ts+++ b/sdk/tests/physics3d-ecs.test.ts@@ -144,6 +144,13 @@ function fakeWorld() {store.get(e)?.set(def, value as Record<string, unknown>);},has(e: Entity, def: unknown): boolean { return store.get(e)?.has(def) ?? false; },+ // Modelled, not stubbed: the real one edits the stored value in place and+ // reports it. A fake missing a write path sends its tests down another.+ update<T>(e: Entity, def: unknown, edit: (draft: T) => void): void {+ const value = store.get(e)?.get(def);+ if (!value) throw new Error('update: the entity does not carry it.');+ edit(value as T);+ },valid(e: Entity): boolean { return store.has(e); },queryEntities(defs: unknown[]): Entity[] {return [...store.entries()]@@ -210,7 +217,7 @@ describe('the 3D world and the ECS', () => {it('sends the solver metres, not world units', () => {const e = spawn({ x: 300, y: 150, z: 0 });world.insert(e, SphereCollider3D);- (world.get(e, SphereCollider3D) as { radius: number }).radius = 50;+ world.update(e, SphereCollider3D, (c) => { (c as { radius: number }).radius = 50; });stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG);@@ -375,7 +382,7 @@ describe('the 3D world and the ECS', () => {it('sends the continuous-collision choice to the world', () => {const e = spawn();world.insert(e, SphereCollider3D);- (world.get(e, RigidBody3D) as { continuousCollision: boolean }).continuousCollision = true;+ world.update(e, RigidBody3D, (b) => { (b as { continuousCollision: boolean }).continuousCollision = true; });stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG);@@ -388,7 +395,7 @@ describe('the 3D world and the ECS', () => {it('sends a body\u2019s layer to the world', () => {const e = spawn();world.insert(e, SphereCollider3D);- (world.get(e, RigidBody3D) as { layer: number }).layer = 5;+ world.update(e, RigidBody3D, (b) => { (b as { layer: number }).layer = 5; });stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG);@@ -401,7 +408,7 @@ describe('the 3D world and the ECS', () => {it('leaves a disabled body out of the world', () => {const e = spawn();world.insert(e, BoxCollider3D);- (world.get(e, RigidBody3D) as { enabled: boolean }).enabled = false;+ world.update(e, RigidBody3D, (b) => { (b as { enabled: boolean }).enabled = false; });stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG);expect(bodies.size).toBe(0);@@ -440,8 +447,9 @@ describe('the 3D world and the ECS', () => {const [a, b] = pair();// A quarter turn about Z: +x becomes +y, and so does the hinge axis.const half = Math.PI / 4;- const t = world.get(a, Transform) as TransformData;- t.worldRotation = { x: 0, y: 0, z: Math.sin(half), w: Math.cos(half) };+ world.update(a, Transform, (t) => {+ (t as TransformData).worldRotation = { x: 0, y: 0, z: Math.sin(half), w: Math.cos(half) };+ });world.insert(a, HingeJoint3D, {connectedEntity: b, anchor: { x: 100, y: 0, z: 0 }, axis: { x: 1, y: 0, z: 0 },});diff --git a/sdk/tests/query.test.ts b/sdk/tests/query.test.tsindex 63c59ed4e..01d88d1df 100644--- a/sdk/tests/query.test.ts+++ b/sdk/tests/query.test.ts@@ -137,8 +137,7 @@ describe('Query System', () => {new QueryInstance(world, query).forEach(() => {});- const pos = world.get(e1, Position);- pos.x = 999;+ world.update(e1, Position, (pos) => { pos.x = 999; });let count = 0;new QueryInstance(world, query).forEach(() => { count++; });diff --git a/sdk/tests/scene.test.ts b/sdk/tests/scene.test.tsindex 5a28f69ec..d623e7fcc 100644--- a/sdk/tests/scene.test.ts+++ b/sdk/tests/scene.test.ts@@ -70,10 +70,11 @@ describe('Scene', () => {const snapshot = serializeEntityComponents(world, e);const snap = snapshot.find((c) => c.type === 'SerStats')!.data as { hp: number; tags: string[] };- // Mutate the LIVE component — a detached snapshot must not change.- const live = world.get(e, Stats) as { hp: number; tags: string[] };- live.hp = 99;- live.tags.push('b');+ // Change the component — a detached snapshot must not follow.+ world.update(e, Stats, (live) => {+ (live as { hp: number }).hp = 99;+ (live as { tags: string[] }).tags.push('b');+ });expect(snap.hp).toBe(10);expect(snap.tags).toEqual(['a']);diff --git a/sdk/tests/ui-controller-gear.test.ts b/sdk/tests/ui-controller-gear.test.tsindex 2f50201aa..ff6af2f26 100644--- a/sdk/tests/ui-controller-gear.test.ts+++ b/sdk/tests/ui-controller-gear.test.ts@@ -52,6 +52,7 @@ function makeMockWorld() {get: (e: Entity, c: AnyComponentDef) => storeFor(c).get(e),insert: (e: Entity, c: AnyComponentDef, d: unknown) => { storeFor(c).set(e, d); },set: (e: Entity, c: AnyComponentDef, d: unknown) => { storeFor(c).set(e, d); },+ update: (e: Entity, c: AnyComponentDef, edit: (d: unknown) => void) => { edit(storeFor(c).get(e)); },remove: (e: Entity, c: AnyComponentDef) => storeFor(c).delete(e),getEntitiesWithComponents: (required: AnyComponentDef[]) => {const out: Entity[] = [];@@ -216,7 +217,7 @@ describe('GearApplySystem — snap', () => {expect((world.get(e, UIVisual) as UIVisualData).color).toEqual({ r: 1, g: 0, b: 0, a: 1 });setControllerPage(world as never, e, 'tab', 'b'); // page 'b' unauthored for this gear- (world.get(e, UIVisual) as UIVisualData).color = { r: 0.3, g: 0.3, b: 0.3, a: 1 };+ world.update(e, UIVisual, (v) => { (v as UIVisualData).color = { r: 0.3, g: 0.3, b: 0.3, a: 1 }; });runSystem(sys, 1 / 60);expect((world.get(e, UIVisual) as UIVisualData).color).toEqual({ r: 0.3, g: 0.3, b: 0.3, a: 1 });});diff --git a/sdk/tests/world-update.test.ts b/sdk/tests/world-update.test.tsnew file mode 100644index 000000000..63fa5444f--- /dev/null+++ b/sdk/tests/world-update.test.ts@@ -0,0 +1,101 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file `world.update` — the contract, including the parts that look wrong.+ *+ * Reporting unconditionally and not rolling back on a throw are deliberate:+ * both trade a cheap false positive for the one failure this path exists to+ * remove, a change nothing observes.+ */+import { describe, it, expect, beforeAll } from 'vitest';+import { App } from '../src/app/app';+import { World } from '../src/ecs/world';+import { defineComponent, Name, Transform } from '../src/ecs/component';+import type { ESEngineModule, CppRegistry } from '../src/wasm';+import { loadWasmModule, HAS_WASM } from './helpers/loadWasm';++const Flat = defineComponent('WuFlat', { v: 0, w: 0 });+const Nested = defineComponent('WuNested', { inner: { x: 0 }, tag: 'a' });++/** A world, an entity carrying `component`, and the tick to ask changes since. */+function fixture<T>(component: Parameters<World['insert']>[1], initial: T) {+ const world = new World();+ world.enableChangeTracking(component);+ const entity = world.spawn();+ world.insert(entity, component, initial as never);+ world.advanceTick();+ return { world, entity, since: world.getWorldTick() - 1 };+}++const observed = (f: ReturnType<typeof fixture>, c: Parameters<World['insert']>[1]) =>+ f.world.isChangedSince(f.entity, c, f.since);++describe('world.update', () => {+ it('edits a script component in place and reports it', () => {+ const f = fixture(Flat, { v: 1, w: 1 });+ f.world.update(f.entity, Flat, (d) => { d.v = 5; });+ expect(f.world.get(f.entity, Flat).v).toBe(5);+ expect(observed(f, Flat)).toBe(true);+ });++ it('reaches a nested field', () => {+ const f = fixture(Nested, { inner: { x: 1 }, tag: 'a' });+ f.world.update(f.entity, Nested, (d) => { d.inner.x = 5; });+ expect(f.world.get(f.entity, Nested).inner.x).toBe(5);+ expect(observed(f, Nested)).toBe(true);+ });++ it('reports even when the callback writes nothing', () => {+ const f = fixture(Flat, { v: 1, w: 1 });+ f.world.update(f.entity, Flat, () => { /* reads only */ });+ expect(observed(f, Flat)).toBe(true);+ });++ it('keeps what a throwing callback wrote, and still reports it', () => {+ const f = fixture(Flat, { v: 1, w: 1 });+ expect(() => f.world.update(f.entity, Flat, (d) => {+ d.v = 9;+ throw new Error('boom');+ })).toThrow('boom');+ expect(f.world.get(f.entity, Flat).v).toBe(9);+ expect(observed(f, Flat)).toBe(true);+ });++ it('refuses an entity that does not carry the component', () => {+ const world = new World();+ const entity = world.spawn();+ expect(() => world.update(entity, Flat, () => { /* never runs */ }))+ .toThrow('does not carry it');+ });++ it('keeps the name index in step', () => {+ const world = new World();+ const entity = world.spawn();+ world.insert(entity, Name, { value: 'before' });+ world.update(entity, Name, (d) => { d.value = 'after'; });+ expect(world.findEntityByName('after')).toBe(entity);+ expect(world.findEntityByName('before')).toBe(null);+ });+});++describe.skipIf(!HAS_WASM)('world.update on engine-backed components', () => {+ let module: ESEngineModule;+ beforeAll(async () => { module = await loadWasmModule(); });++ it('stores a projection edit and reports it', () => {+ const app = App.new();+ app.connectCpp(new module.Registry() as unknown as CppRegistry, module);+ const world = app.world;+ world.enableChangeTracking(Transform);+ const entity = world.spawn();+ world.insert(entity, Transform, { position: { x: 1, y: 0, z: 0 } });+ world.advanceTick();+ const since = world.getWorldTick() - 1;++ world.update(entity, Transform, (d) => { d.position.x = 42; });++ expect(world.get(entity, Transform).position.x).toBe(42);+ expect(world.isChangedSince(entity, Transform, since)).toBe(true);+ world.disconnectCpp();+ });+});diff --git a/sdk/tests/world.test.ts b/sdk/tests/world.test.tsindex 044243823..20531b7ed 100644--- a/sdk/tests/world.test.ts+++ b/sdk/tests/world.test.ts@@ -266,29 +266,30 @@ describe('World', () => {});});- describe('component data mutations', () => {- it('should allow mutating component data', () => {+ // The supported edit is `update`. Writing to a `get` result does still stick+ // for a script component, but nothing observes it.+ describe('component data updates', () => {+ it('stores what the edit wrote', () => {const entity = world.spawn();world.insert(entity, Position, { x: 0, y: 0 });- const pos = world.get(entity, Position);- pos.x = 100;- pos.y = 200;+ world.update(entity, Position, (pos) => {+ pos.x = 100;+ pos.y = 200;+ });const updated = world.get(entity, Position);expect(updated.x).toBe(100);expect(updated.y).toBe(200);});- it('should reflect mutations immediately', () => {+ it('is visible to the next read', () => {const entity = world.spawn();world.insert(entity, Health, { value: 100 });- const hp1 = world.get(entity, Health);- hp1.value -= 25;+ world.update(entity, Health, (hp) => { hp.value -= 25; });- const hp2 = world.get(entity, Health);- expect(hp2.value).toBe(75);+ expect(world.get(entity, Health).value).toBe(75);});});diff --git a/tools/gates.mjs b/tools/gates.mjsindex 8ae77ed10..cb5775262 100644--- a/tools/gates.mjs+++ b/tools/gates.mjs@@ -182,6 +182,7 @@ export const GATES = [{ id: 'path-sandbox', run: 'node tools/check-path-sandbox.mjs' },{ id: 'key-codes', run: 'node tools/check-key-codes.mjs' },{ id: 'comment-style', run: 'node tools/check-comment-style.mjs' },+ { id: 'silent-writes', run: 'node tools/mutation-census.mjs --gate' },{id: 'cpp-tests',run: 'node tools/check-cpp-tests.mjs',diff --git a/tools/lib/apiSnapshot.mjs b/tools/lib/apiSnapshot.mjsindex 732a17574..fba4ffcfc 100644--- a/tools/lib/apiSnapshot.mjs+++ b/tools/lib/apiSnapshot.mjs@@ -61,6 +61,21 @@ export function isAdditiveMembers(before, after) {return added.length > 0 && added.every((line) => /:\s.*\|\s*undefined$/.test(line));}+/**+ * A class that kept every member it had and gained more. Nobody implements a+ * class from outside, so a new member breaks no caller — unlike an interface,+ * where a required member is a demand on every implementor.+ */+export function isAddedClassMembers(before, after) {+ const was = before.split('\n').filter(Boolean);+ const now = new Set(after.split('\n').filter(Boolean));+ if (was.some((line) => !now.has(line))) return false;+ // Set against Set: a body may repeat a line, and comparing a deduplicated+ // size to a raw length reads an addition as no change.+ const wasSet = new Set(was);+ return [...now].some((line) => !wasSet.has(line));+}+/*** A function that kept every parameter it had and gained OPTIONAL ones at the* end: every call written against the old signature still compiles and means@@ -153,6 +168,9 @@ export function baselineFindings(was, now) {} else if (before.kind === 'function'&& isAddedOptionalParam(promisedBody(before.body), promisedBody(after.body))) {notes.push(`${name} — @public function gained an optional parameter`);+ } else if (before.kind === 'class'+ && isAddedClassMembers(promisedBody(before.body), promisedBody(after.body))) {+ notes.push(`${name} — @public class gained a member`);} else {failures.push(`${name} — @public signature changed`);}diff --git a/tools/mutation-census.mjs b/tools/mutation-census.mjsindex 038b8db5a..04ab10610 100644--- a/tools/mutation-census.mjs+++ b/tools/mutation-census.mjs@@ -18,12 +18,16 @@* result, because a census whose limits are unstated reads as an all-clear.** node tools/mutation-census.mjs+ * node tools/mutation-census.mjs --gate # no silent write may exist* node tools/mutation-census.mjs --json* node tools/mutation-census.mjs --self-test # calibrate on known-positive source*- * Exit codes: 0 the census ran, 2 a declared root could not be read (an- * unchecked-out editor submodule scans as zero findings, which is a false- * all-clear, not a clean repo).+ * Exit codes without `--gate`: 0 the census ran, 2 a declared root could not be+ * read (an unchecked-out editor submodule scans as zero findings, which is a+ * false all-clear, not a clean repo). With `--gate`: 0 no silent write in what+ * was scanned, 1 there is one. A gate NAMES the roots it could not read rather+ * than refusing to answer for the rest — the corpus it judged is stated, and a+ * silent write anywhere in it fails.*/import { readFileSync, existsSync } from 'node:fs';import path from 'node:path';@@ -35,6 +39,7 @@ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');const ts = createRequire(path.join(ROOT, 'sdk', '/'))('typescript');const JSON_OUT = process.argv.includes('--json');const SELF_TEST = process.argv.includes('--self-test');+const GATE = process.argv.includes('--gate');/** Where a game or the engine could write through a read handle. */const ROOTS = ['sdk/src', 'sdk/tests', 'examples', 'desktop/src'];@@ -407,7 +412,7 @@ const byRoot = (rel) => ROOTS.find((r) => rel.startsWith(r + '/')) ?? rel;if (JSON_OUT) {console.log(JSON.stringify({ scanned: sources.length, findings, skippedRoots, missing }, null, 2));-} else {+} else if (!GATE) {console.log('');console.log(` ${sources.length} files scanned across ${declaredRoots.join(', ')}`);if (skippedRoots.length) console.log(` NOT scanned (no checkout): ${skippedRoots.join(', ')}`);@@ -444,4 +449,18 @@ if (JSON_OUT) {console.log('');}+if (GATE) {+ const silent = writes.filter((f) => f.storedBack === false);+ const unread = [...skippedRoots, ...missing];+ if (silent.length) {+ console.error(`mutation-census: ${silent.length} silent write(s) — the value changes and`+ + ' nothing observes it. Use world.update, world.set, or Mut().\n');+ for (const f of silent) console.error(` ${f.file}:${f.line} ${f.code}`);+ process.exit(1);+ }+ console.log(`mutation-census: ${sources.length} files, no silent writes`+ + (unread.length ? ` (NOT read: ${unread.join(', ')})` : ''));+ process.exit(0);+}+process.exit(skippedRoots.length || missing.length ? 2 : 0);diff --git a/tools/tests/api-baseline.test.ts b/tools/tests/api-baseline.test.tsindex 01bdc9e80..c0b638334 100644--- a/tools/tests/api-baseline.test.ts+++ b/tools/tests/api-baseline.test.ts@@ -140,6 +140,53 @@ describe('an interface that gains an optional member', () => {});});+/**+ * Nobody implements a class from outside, so a class that GAINS a member breaks+ * no caller — unlike an interface, where a required member is a demand on every+ * implementor. Losing or changing one is still a broken promise.+ */+describe('a @public class that gained a member', () => {+ const body = (...members: string[]) => members.join('\n');+ const was = sig('World — class @public', body(+ 'get: (e: Entity, c: Def) => Data',+ 'set: (e: Entity, c: Def, d: Data) => void',+ ));+ const changed = (b: string) =>+ baselineFindings(snapshot(was), snapshot(sig('World — class @public', b)));++ it('is a note, not a broken promise', () => {+ const { failures, notes } = changed(body(+ 'get: (e: Entity, c: Def) => Data',+ 'set: (e: Entity, c: Def, d: Data) => void',+ 'update: (e: Entity, c: Def, edit: (d: Data) => void) => void',+ ));+ expect(failures).toEqual([]);+ expect(notes.join(' ')).toMatch(/class gained a member/);+ });++ it('is still broken when a member is REMOVED', () => {+ expect(changed(body('get: (e: Entity, c: Def) => Data')).failures)+ .toEqual(['World — @public signature changed']);+ });++ it('is still broken when a member CHANGED while another was added', () => {+ expect(changed(body(+ 'get: (e: Entity, c: Def, extra: number) => Data',+ 'set: (e: Entity, c: Def, d: Data) => void',+ 'update: (e: Entity, c: Def, edit: (d: Data) => void) => void',+ )).failures).toEqual(['World — @public signature changed']);+ });++ it('does not fire for an interface, where a required member is a demand', () => {+ const iface = sig('Shape — interface @public', body('a: number'));+ const { failures } = baselineFindings(+ snapshot(iface),+ snapshot(sig('Shape — interface @public', body('a: number', 'b: string'))),+ );+ expect(failures).toEqual(['Shape — @public signature changed']);+ });+});+/*** A trailing OPTIONAL parameter breaks no call that was written, which is the* whole of what @public promises. Every other edit to a signature does break