7.1 场景文档操作 API
文档模型是编辑器的「内存真相」。helio 卷三第 8.2 章的最小文档只有 uid 加三档脏标记——足够演示骨架,但离工业级差着一整套东西:操作怎么收敛、失败怎么表达、改了什么怎么留痕。本节做文档模型深化的第一步:把文档操作收敛成一套完整、可校验、可留痕的 API。
SceneDocument 维护一张节点表,所有改动必须走四个操作:
addNode(id, parent):新增节点。重复 id 拒绝(id 是身份,不允许重复)、父不存在拒绝。removeNode(id):移除节点并级联移除整棵子树,返回移除总数——编辑器中删一个组,组下所有东西跟着删,这是直觉预期。moveNode(id, newParent):移动节点。移动到自身子树被拒绝(否则产生环,文档结构会毁掉)。setProperty(id, field, value):设置属性。只允许已声明字段——ghostField这类未知字段直接拒绝,而不是悄悄写进节点。
本章与站内既有内容的分工
helio 卷三第 8.2 章的最小文档是这套 API 的前身。
| 主题 | 站内既有内容 | 本节做什么 |
|---|---|---|
| 最小文档模型 | 卷三 8.2 文档模型:状态、命令与脏标记 | 只有 uid + 脏标记;本节补完整操作 API |
| 稳定 id | 7.2 稳定 id 与脏传播 | 本节用 string id 占位,下节讲怎么生成 |
| 文档体检 | 7.3 文档不变量校验 | 操作 API 负责改得对,不变量校验负责查得对 |
操作留痕:撤销的入场券
SceneDocument 最容易被忽略的设计是 events():每个操作都写进事件日志。addNode 记 { kind: 'add', id, parent },removeNode 记 { kind: 'remove', id, removed: N },moveNode 记移动前后的父,setProperty 记改的字段。
这不是为了日志而日志——它是第 10 章撤销系统的入场券。撤销的本质是「按操作逆序回放」,没有留痕就没有撤销。现在把每个操作记下来,第 10 章做事务、异步撤销时直接消费这份事件流,不用回头改文档模型。先见之明是架构,事后补是返工。
对标场景操作与撤销入口
Unity 的 Undo.RecordObject 应在对象修改前调用,重挂父节点和销毁对象等操作有各自的 Undo API。Unreal 的 UObject::Modify() 在事务记录启用时将对象纳入事务,也可标记包为脏。Godot 的 EditorUndoRedoManager 管理编辑器撤销历史,可为动作分别登记执行与撤销操作。 Unity Undo.RecordObject
· Unreal UObject::Modify
· Godot EditorUndoRedoManager
helio 用 OpResult 表达预期内的失败,例如目标父节点不存在。调用方应先检查结果再更新界面或登记撤销。返回错误值让调用方能够处理失败,TypeScript 不强制消费该返回值。
可运行产物:6 条用例
下面 src/scene-document.ts 层级 L1,完整可编译,命令 node --test test/07-1-scene-document-operation-api.test.ts:
// file: src/scene-document.ts
// tier: L1
// verify: node --test test/07-1-scene-document-operation-api.test.ts
//
// 文档模型与脏标记深化(第七章):场景文档操作 API。
// helio 卷三第 8.2 章的最小文档只有 uid + 三档脏标记;本节把操作收敛成
// 一套完整、可校验、可留痕的 API:addNode / removeNode(级联)/
// moveNode(拒绝移动到自身子树,防环)/ setProperty(只允许已声明字段)。
// 每个操作返回明确的成功/失败原因,并写进 events() 供撤销与审计。
export interface SceneNode {
/** 稳定 id:跨会话不变(7.2 讲如何生成)。 */
id: string;
name: string;
parent: string | null;
children: string[];
pos: [number, number, number];
}
export type OpResult = { ok: true } | { ok: false; reason: string };
export type OpEvent =
| { kind: 'add'; id: string; parent: string | null }
| { kind: 'remove'; id: string; removed: number }
| { kind: 'move'; id: string; from: string | null; to: string | null }
| { kind: 'set'; id: string; field: string };
const FIELDS = ['name', 'parent', 'children', 'pos'] as const;
export class SceneDocument {
readonly #nodes = new Map<string, SceneNode>();
#events: OpEvent[] = [];
/** 创建一个以 id 为根的新节点(parent 为 null)。 */
addNode(id: string, parent: string | null = null): OpResult {
if (this.#nodes.has(id)) return { ok: false, reason: `duplicate node id: ${id}` };
if (parent !== null && !this.#nodes.has(parent)) return { ok: false, reason: `parent not found: ${parent}` };
const node: SceneNode = { id, name: id, parent, children: [], pos: [0, 0, 0] };
this.#nodes.set(id, node);
if (parent !== null) this.#nodes.get(parent)!.children.push(id);
this.#events.push({ kind: 'add', id, parent });
return { ok: true };
}
/** 移除节点并级联移除子树,返回移除总数。 */
removeNode(id: string): OpResult {
const node = this.#nodes.get(id);
if (!node) return { ok: false, reason: `node not found: ${id}` };
if (node.parent !== null) {
const p = this.#nodes.get(node.parent)!;
p.children = p.children.filter((c) => c !== id);
}
const removed = this.#collectSubtree(id);
for (const dead of removed) this.#nodes.delete(dead);
this.#events.push({ kind: 'remove', id, removed: removed.length });
return { ok: true };
}
/** 移动节点到新父下;移动到自身子树被拒绝(防环)。 */
moveNode(id: string, newParent: string | null): OpResult {
const node = this.#nodes.get(id);
if (!node) return { ok: false, reason: `node not found: ${id}` };
if (newParent !== null && !this.#nodes.has(newParent)) return { ok: false, reason: `parent not found: ${newParent}` };
if (newParent !== null && this.#isDescendant(id, newParent)) return { ok: false, reason: `cannot move node into its own subtree: ${id}` };
const from = node.parent;
if (from !== null) {
const p = this.#nodes.get(from)!;
p.children = p.children.filter((c) => c !== id);
}
node.parent = newParent;
if (newParent !== null) this.#nodes.get(newParent)!.children.push(id);
this.#events.push({ kind: 'move', id, from, to: newParent });
return { ok: true };
}
/** 设置节点属性;未知字段被拒绝。 */
setProperty(id: string, field: string, value: unknown): OpResult {
const node = this.#nodes.get(id);
if (!node) return { ok: false, reason: `node not found: ${id}` };
if (!(FIELDS as readonly string[]).includes(field)) return { ok: false, reason: `unknown field: ${field}` };
(node as unknown as Record<string, unknown>)[field] = value;
this.#events.push({ kind: 'set', id, field });
return { ok: true };
}
node(id: string): SceneNode | undefined { return this.#nodes.get(id); }
size(): number { return this.#nodes.size; }
rootIds(): string[] { return [...this.#nodes.values()].filter((n) => n.parent === null).map((n) => n.id); }
childrenOf(id: string): string[] { return this.#nodes.get(id)?.children ?? []; }
events(): OpEvent[] { return [...this.#events]; }
#collectSubtree(id: string): string[] {
const out: string[] = [];
const walk = (nid: string): void => {
out.push(nid);
const node = this.#nodes.get(nid);
for (const c of node?.children ?? []) walk(c);
};
walk(id);
return out;
}
/** id 是否是 target 的祖先或自身(沿 parent 上溯)。 */
#isDescendant(id: string, target: string): boolean {
let cur: string | null = target;
while (cur !== null) {
if (cur === id) return true;
cur = this.#nodes.get(cur)?.parent ?? null;
}
return false;
}
}
#collectSubtree 用递归把子树节点收进数组再一并删除——removeNode 的级联语义落在这里。#isDescendant 沿 parent 上溯判断目标是不是自己的后代,moveNode 靠它防环:把 a 移到 a1(自己的子节点)底下被拒,因为那等于让 a 成为自己的后代,父子图立刻成环。
可运行产物:6 条用例
下面是 test/07-1-scene-document-operation-api.test.ts 层级 L1,命令 node --test test/07-1-scene-document-operation-api.test.ts:
// file: test/07-1-scene-document-operation-api.test.ts
// tier: L1
// verify: node --test test/07-1-scene-document-operation-api.test.ts
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { SceneDocument } from '../src/scene-document.ts';
test('addNode 创建根节点与子节点', () => {
const doc = new SceneDocument();
assert.deepEqual(doc.addNode('scene'), { ok: true });
assert.deepEqual(doc.addNode('player', 'scene'), { ok: true });
assert.deepEqual(doc.rootIds(), ['scene']);
assert.deepEqual(doc.childrenOf('scene'), ['player']);
assert.equal(doc.node('player')!.parent, 'scene');
});
test('addNode 拒绝重复 id 与悬空父', () => {
const doc = new SceneDocument();
doc.addNode('scene');
assert.deepEqual(doc.addNode('scene'), { ok: false, reason: 'duplicate node id: scene' });
assert.deepEqual(doc.addNode('ghost', 'nobody'), { ok: false, reason: 'parent not found: nobody' });
assert.equal(doc.size(), 1);
});
test('removeNode 级联移除子树', () => {
const doc = new SceneDocument();
doc.addNode('scene');
doc.addNode('group', 'scene');
doc.addNode('a', 'group');
doc.addNode('b', 'group');
assert.deepEqual(doc.removeNode('group'), { ok: true });
assert.equal(doc.size(), 1); // scene 仍在
assert.deepEqual(doc.childrenOf('scene'), []);
assert.equal(doc.node('a'), undefined);
});
test('moveNode 移动节点并更新父子链', () => {
const doc = new SceneDocument();
doc.addNode('scene');
doc.addNode('a', 'scene');
doc.addNode('b', 'scene');
assert.equal(doc.moveNode('a', 'b').ok, true);
assert.deepEqual(doc.childrenOf('scene'), ['b']);
assert.deepEqual(doc.childrenOf('b'), ['a']);
assert.equal(doc.node('a')!.parent, 'b');
});
test('moveNode 拒绝移动到自身子树(防环)', () => {
const doc = new SceneDocument();
doc.addNode('scene');
doc.addNode('a', 'scene');
doc.addNode('a1', 'a');
const r = doc.moveNode('a', 'a1');
assert.deepEqual(r, { ok: false, reason: 'cannot move node into its own subtree: a' });
// 移动自身(parent 为 null)允许但无变化
assert.equal(doc.moveNode('scene', null).ok, true);
});
test('setProperty 只允许已声明字段,操作留痕', () => {
const doc = new SceneDocument();
doc.addNode('scene');
assert.equal(doc.setProperty('scene', 'name', 'Level').ok, true);
assert.equal(doc.setProperty('scene', 'ghostField', 1).ok, false);
assert.equal(doc.node('scene')!.name, 'Level');
const events = doc.events();
assert.deepEqual(events[0], { kind: 'add', id: 'scene', parent: null });
assert.deepEqual(events[1], { kind: 'set', id: 'scene', field: 'name' });
});
本机实测(Node v26.5.0,node --test test/07-1-scene-document-operation-api.test.ts):tests 6、pass 6、fail 0,耗时约 45 ms。
第二条验证两条拒绝纪律(重复 id、悬空父),第三条验证级联移除(a、b 随 group 一起没了),第四条验证移动后父子链双向一致,第五条钉死防环边界——moveNode('a', 'a1') 被拒,而把根移到 null 是合法空操作。第六条同时验证 setProperty 的字段白名单和 events() 留痕:name 改成功且记 set 事件,ghostField 被拒且没有事件。
小结
- 文档操作收敛成四个方法:
add/remove/move/set,每个都返回{ ok, reason },失败必然被处理。 removeNode级联移除子树;moveNode拒绝移入自身子树防环;setProperty只允许已声明字段。events()操作留痕是第 10 章撤销系统的入场券,先见之明,避免事后返工。- 对标各引擎的文档操作:helio 用显式
OpResult表达失败,脚本调用方能拿到原因。 - 下一节解决 id 的来源:稳定 id 与脏传播——确定性生成 id、沿祖先链传播脏标记。
阅读导航:上一节:6.3 多语言脚本类型桥 · 下一节:7.2 稳定 id 与脏传播 。
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。