《游戏编辑器技术原理与架构》2.1 模块注册与依赖拓扑

编辑器不是一坨可执行文件,是一堆互相声明的模块。本节从一张模块注册表开始:每个模块声明依赖谁,用 Kahn 算法把模块排成可启动的线性顺序,依赖环被检出并返回环成员,仍被依赖的模块不允许卸载;6 条用例本机真跑,对照 Unreal 的 Build.cs 依赖声明与 Unity 的 asmdef 程序集引用。

2.1 模块注册与依赖拓扑

第一章把「编辑态 / 运行态」这条横轴定好了。现在看编辑器自己的骨架:一个工业级编辑器由几十上百个模块拼成——文档系统、资产数据库、视口、Inspector、快捷键、撤销栈……它们谁也不能独占进程,而必须在一个内核里按顺序起来、按顺序关。

难点不在「怎么把代码拆成模块」,而在顺序。资产数据库要先于内容浏览器启动;撤销栈要先于所有会写文档的面板启动;谁先谁后不该靠「注册顺序」或「想起来谁」,而该从依赖声明里算出来。本节做一个最小的 ModuleRegistry:模块声明依赖、拓扑排序得到启动顺序、环被检出、卸载有安全边界——然后用 6 条用例钉住这些行为。

本章与站内既有内容的分工

第 2 章是整个系列的内核起点;站内此前没有模块系统篇章,helio 卷三的第 8 章骨架也没有做插件化。

主题站内既有内容本节做什么
模块系统站内无模块注册、依赖拓扑、环检出、卸载边界
文档模型与脏标记helio 8.2 文档模型与脏标记文档系统会是这个内核里的一个模块(第 7 章深入)
插件化内核站内无本节的注册表是第 4 卷扩展框架的地基

一张注册表,三条规则

ModuleRegistry 做的事,是把模块世界简化成三件能断言的事:

  1. 注册:每个模块用一个 ModuleDef 声明自己,deps 列出它依赖的模块 id。重复 id 被拒绝——内核里模块身份必须唯一。
  2. 排序:buildOrder() 用 Kahn 算法把整张依赖图拍平成线性启动顺序,被依赖者在前。有环时返回 null,并把参与环的模块记进 cycleNodes()——不是「报错拉倒」,而是把嫌疑名单交出来。
  3. 卸载:unregister(id) 只有当没有其它模块依赖它时才允许。这是热装卸(下一节)的安全边界:你敢卸一个,别让它的依赖者悬空。

Kahn 算法的直觉一句话:不断找「当前还没有被依赖(入度为 0)」的模块先启动,启动后把它从图上划掉、解除它对别人的牵制,再重复。环的本质是永远找不到入度为 0 的点,剩下的就是环成员。

对标 Unreal 与 Unity 的依赖声明

Unreal 在 Build.cs 声明构建依赖,通过 .uproject 或 .uplugin 指定模块加载阶段。同一阶段内的加载顺序不保证确定。若启动回调需要另一个模块先就绪,官方文档建议显式调用 LoadModule 或 LoadModuleChecked。Unreal Engine Modules

Unity 的 asmdef 引用描述程序集之间的编译依赖。helio 的 ModuleDef.deps 则描述会话内的启动先后,Kahn 排序直接服务于启动计划。

可运行产物:6 条用例钉住注册与排序

下面 src/module-registry.ts 层级 L1,完整可编译,命令 node --test test/02-1-module-registry-dependency.test.ts:

// file: src/module-registry.ts
// tier: L1
// verify: node --test test/02-1-module-registry-dependency.test.ts
//
// 插件化内核(第二章):模块注册与依赖拓扑。
// ModuleRegistry 维护一张模块表,每个模块声明它依赖谁;buildOrder 用
// Kahn 算法把模块排成可启动的线性顺序,遇到依赖环则检出并返回环成员。
// 卸载规则:仍被其它模块依赖的模块不允许卸载——这是热装卸的安全边界。

export interface ModuleDef {
  id: string;
  /** 依赖的模块 id;拓扑排序保证被依赖者先启动。 */
  deps: string[];
}

export class ModuleRegistry {
  readonly #modules = new Map<string, ModuleDef>();
  #cycleNodes: string[] = [];

  register(def: ModuleDef): boolean {
    if (this.#modules.has(def.id)) return false;
    this.#modules.set(def.id, def);
    return true;
  }

  has(id: string): boolean { return this.#modules.has(id); }
  module(id: string): ModuleDef | undefined { return this.#modules.get(id); }
  size(): number { return this.#modules.size; }

  /** 所有模块 id,按注册序。 */
  ids(): string[] { return [...this.#modules.keys()]; }

  /** 反向依赖:所有直接依赖 id 的模块。 */
  dependentsOf(id: string): string[] {
    const out: string[] = [];
    for (const [mid, def] of this.#modules) {
      if (def.deps.includes(id)) out.push(mid);
    }
    return out;
  }

  /** 卸载一个模块;若有其它模块依赖它则拒绝。返回是否真的卸载了。 */
  unregister(id: string): boolean {
    if (!this.#modules.has(id)) return false;
    if (this.dependentsOf(id).length > 0) return false;
    this.#modules.delete(id);
    return true;
  }

  /** 最近一次 buildOrder 检出的环成员;无环时为空。 */
  cycleNodes(): string[] { return [...this.#cycleNodes]; }

  /**
   * 拓扑排序(Kahn 算法)。无环返回启动顺序(被依赖者在前);
   * 有环返回 null,并把参与环的模块记录进 cycleNodes。
   * 缺失的依赖按忽略处理:不阻塞排序,正文讨论该策略的取舍。
   */
  buildOrder(): string[] | null {
    const indeg = new Map<string, number>();
    const adj = new Map<string, string[]>();
    for (const id of this.#modules.keys()) {
      indeg.set(id, 0);
      adj.set(id, []);
    }
    for (const [, def] of this.#modules) {
      for (const dep of def.deps) {
        if (!this.#modules.has(dep)) continue; // 缺失依赖忽略
        adj.get(dep)!.push(def.id);
        indeg.set(def.id, indeg.get(def.id)! + 1);
      }
    }
    const queue: string[] = [];
    for (const [id, d] of indeg) if (d === 0) queue.push(id);
    const order: string[] = [];
    for (let i = 0; i < queue.length; i++) {
      const id = queue[i];
      order.push(id);
      for (const next of adj.get(id)!) {
        indeg.set(next, indeg.get(next)! - 1);
        if (indeg.get(next) === 0) queue.push(next);
      }
    }
    if (order.length !== this.#modules.size) {
      const remaining = new Set(indeg.keys());
      for (const id of order) remaining.delete(id);
      this.#cycleNodes = [...remaining];
      return null;
    }
    this.#cycleNodes = [];
    return order;
  }
}

有两个实现细节值得说明。一是 Kahn 里 adj.get(dep)!.push(def.id):每条边从「依赖者」指向「被依赖者」,方向跟直觉相反——正因为被依赖者入度低,才先启动。二是缺失依赖按忽略处理:a 声明依赖 missing 而 missing 没注册时,不阻塞排序。这个策略的取舍在正文里讲:它可以掩盖「插件少装了」的失误(好:不崩),也会让你直到运行期才暴露少装(坏:晚)。helio 选「不崩」,第 4 卷扩展框架会给真正的缺失依赖一个明确的诊断日志——这里先保证内核的健壮性。

可运行产物:6 条用例

下面是 test/02-1-module-registry-dependency.test.ts 层级 L1,命令 node --test test/02-1-module-registry-dependency.test.ts:

// file: test/02-1-module-registry-dependency.test.ts
// tier: L1
// verify: node --test test/02-1-module-registry-dependency.test.ts
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { ModuleRegistry } from '../src/module-registry.ts';

test('链式依赖:被依赖者先启动', () => {
  const r = new ModuleRegistry();
  r.register({ id: 'a', deps: [] });
  r.register({ id: 'b', deps: ['a'] });
  r.register({ id: 'c', deps: ['b'] });
  const order = r.buildOrder();
  assert.ok(order);
  assert.deepEqual(order, ['a', 'b', 'c']);
});

test('并行依赖:a 依赖 x/y,x/y 顺序任意但都在 a 前', () => {
  const r = new ModuleRegistry();
  r.register({ id: 'x', deps: [] });
  r.register({ id: 'y', deps: [] });
  r.register({ id: 'a', deps: ['x', 'y'] });
  const order = r.buildOrder();
  assert.ok(order);
  assert.equal(order.length, 3);
  assert.ok(order.indexOf('x') < order.indexOf('a'));
  assert.ok(order.indexOf('y') < order.indexOf('a'));
});

test('环检测:a<->b 时 buildOrder 返回 null 且环成员被检出', () => {
  const r = new ModuleRegistry();
  r.register({ id: 'a', deps: ['b'] });
  r.register({ id: 'b', deps: ['a'] });
  assert.equal(r.buildOrder(), null);
  const cycle = r.cycleNodes();
  assert.ok(cycle.includes('a'));
  assert.ok(cycle.includes('b'));
});

test('卸载被依赖的模块被拒绝,无依赖者可卸载', () => {
  const r = new ModuleRegistry();
  r.register({ id: 'a', deps: [] });
  r.register({ id: 'b', deps: ['a'] });
  assert.equal(r.unregister('a'), false); // b 依赖 a
  assert.equal(r.unregister('b'), true);
  assert.equal(r.unregister('a'), true);
});

test('重复注册被拒绝', () => {
  const r = new ModuleRegistry();
  assert.equal(r.register({ id: 'a', deps: [] }), true);
  assert.equal(r.register({ id: 'a', deps: [] }), false);
});

test('缺失依赖按忽略处理,不阻塞排序', () => {
  const r = new ModuleRegistry();
  r.register({ id: 'a', deps: ['missing'] });
  r.register({ id: 'b', deps: [] });
  const order = r.buildOrder();
  assert.ok(order);
  assert.ok(order.includes('a'));
  assert.ok(order.includes('b'));
});

本机实测(Node v26.5.0,node --test test/02-1-module-registry-dependency.test.ts):tests 6、pass 6、fail 0,耗时约 48 ms。

这 6 条里,第 2 条(并行依赖)最容易被忽略:它断言的是偏序而非全序——x、y 谁先谁后无所谓,但必须都在 a 前面。如果实现偷偷用「注册顺序」代替拓扑排序,这条用例会立刻报警。第 4 条钉死卸载安全边界;第 6 条把「缺失依赖忽略」这个策略选择固化下来,防止将来有人改成「缺依赖就抛异常」。

小结

  • 模块的世界被简化成三件事:注册(身份唯一)、排序(Kahn 拓扑、被依赖者在前)、卸载(无依赖者才允许)。
  • 环是「永远找不到入度为 0 的点」,cycleNodes() 给出嫌疑名单而不是让崩溃汇报。
  • 与 Unreal / Unity 的差异在时机:它们构建期检环,helio 因为运行时加载必须运行时检。
  • 下一节把这张注册表变成能跑起来的内核:init/start 按拓扑序、stop/shutdown 逆序,以及运行期的热装载/卸载。

阅读导航:上一节:1.3 一键 Play 的代价:选型与对标基准 · 下一节:2.2 启动、关闭与热装卸 。

继续阅读

探索更多技术文章

浏览归档,发现更多关于系统设计、工具链和工程实践的内容。

全部文章 返回首页

「books」更多文章

  1. 《大规模分布式计算深入解析·向量数据库与 AI 检索内核》 · 目录与学习路径(45 篇)
  2. 《大规模分布式计算深入解析》15.3 自研向量引擎:可执行骨架与工程缺口
  3. 《大规模分布式计算深入解析》14.1 Milvus:组件架构、段管理与检索链路