《游戏编辑器技术原理与架构》12.1 编辑器 WebAssembly 化

WebAssembly 模块声明自己需要哪些导入函数、导出哪些函数、占多少页内存。加载器只做四件事:导入必须全部由宿主提供、内存总量不超预算、同模块不重复加载、卸载时把内存还回去。真实的实例化交给运行时,这四件事不变。本节从零实现并真跑 6 条用例,对标 Unity / Unreal / Godot / Cocos Creator 的编辑器 WASM 化。

12.1 编辑器 WebAssembly 化

WebAssembly 模块声明自己需要哪些导入函数、导出哪些函数、占多少页内存。加载器只做四件事:导入必须全部由宿主提供、内存总量不超预算、同模块不重复加载、卸载时把内存还回去。真实的实例化交给运行时,这四件事不变。

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

主题站内既有内容本节做什么
编辑器内核《架构内核》内核是 TypeScript 实现;本节讨论把计算密集部分搬进 WASM
扩展框架本卷 1.11.1 管扩展清单;本节管 WASM 模块的加载契约
全卷脉络本卷目录本节是云编辑器章的第一块

从零实现:编辑器 WebAssembly 化

加载前先核对导入:声明的每个导入名都必须在宿主对象里是函数。内存预算按页累计,超过剩余页数直接拒绝。实例表以模块名为键,重复加载报错。调用导出时先确认模块已加载且导出名在声明列表里,再交给宿主函数;没有对应宿主函数时返回调用描述,便于测试。

实现与交付边界

WasmLoader 检查模块声明中的导入名称并记录内存页配额。示例卸载归还的是账面配额,真正实例化由 WebAssembly 宿主完成。游戏 Web 导出和浏览器编辑器是两个交付目标。

可运行产物:6 条用例

下面是 src/wasm-loader.ts,层级 L1,完整可编译。运行命令 node --test test/12-1-editor-wasm.test.ts:

// file: src/wasm-loader.ts
// tier: L1
// verify: node --test test/12-1-editor-wasm.test.ts
//
// 卷四(第十二章):云编辑器与 WebAssembly——编辑器 WASM 化。
// WebAssembly 模块声明自己需要哪些导入函数、导出哪些函数、占多少页内存。
// 加载器只做四件事:导入必须全部由宿主提供、内存总量不超预算、同模块不
// 重复加载、卸载时把内存还回去。真实的实例化交给运行时,这四件事不变。

export interface WasmModuleDecl {
  name: string;
  imports: string[];
  exports: string[];
  memoryPages: number;
}

export interface WasmInstance {
  module: WasmModuleDecl;
  host: Record<string, (...args: unknown[]) => unknown>;
}

const PAGE_BYTES = 65536;

export class WasmLoader {
  #instances = new Map<string, WasmInstance>();
  #budgetPages: number;
  #usedPages = 0;

  constructor(budgetPages: number) {
    if (budgetPages <= 0) throw new Error('内存预算必须为正');
    this.#budgetPages = budgetPages;
  }

  load(decl: WasmModuleDecl, host: Record<string, (...args: unknown[]) => unknown>): void {
    if (this.#instances.has(decl.name)) {
      throw new Error(`模块 ${decl.name} 已加载`);
    }
    const missing = decl.imports.filter((name) => typeof host[name] !== 'function');
    if (missing.length > 0) {
      throw new Error(`缺少导入函数:${missing.join(', ')}`);
    }
    if (this.#usedPages + decl.memoryPages > this.#budgetPages) {
      throw new Error(`内存超出预算:需要 ${decl.memoryPages} 页,剩余 ${this.remainingPages()} 页`);
    }
    this.#instances.set(decl.name, { module: { ...decl }, host });
    this.#usedPages += decl.memoryPages;
  }

  call(moduleName: string, exportName: string, args: unknown[] = []): unknown {
    const instance = this.#instances.get(moduleName);
    if (!instance) throw new Error(`模块 ${moduleName} 未加载`);
    if (!instance.module.exports.includes(exportName)) {
      throw new Error(`模块 ${moduleName} 没有导出 ${exportName}`);
    }
    const fn = instance.host[`${moduleName}.${exportName}`];
    if (typeof fn === 'function') return fn(...args);
    return { module: moduleName, exportName, args };
  }

  unload(moduleName: string): boolean {
    const instance = this.#instances.get(moduleName);
    if (!instance) return false;
    this.#usedPages -= instance.module.memoryPages;
    this.#instances.delete(moduleName);
    return true;
  }

  remainingPages(): number {
    return this.#budgetPages - this.#usedPages;
  }

  usedBytes(): number {
    return this.#usedPages * PAGE_BYTES;
  }

  names(): string[] {
    return [...this.#instances.keys()];
  }
}

把导入与导出写成声明,而不是运行时反射,是为了在加载前就能失败:缺一个导入函数,加载阶段报错比运行到一半崩溃容易排查得多。内存按页预算,与 WebAssembly 的内存模型一致,避免再做一层单位换算。

下面是 test/12-1-editor-wasm.test.ts,层级 L1:

// file: test/12-1-editor-wasm.test.ts
// tier: L1
// verify: node --test test/12-1-editor-wasm.test.ts
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { WasmLoader } from '../src/wasm-loader.ts';

const decl = {
  name: 'mesh-codec',
  imports: ['log'],
  exports: ['decode'],
  memoryPages: 4,
};

test('导入齐全时加载成功', () => {
  const l = new WasmLoader(16);
  l.load(decl, { log: () => {} });
  assert.deepEqual(l.names(), ['mesh-codec']);
  assert.equal(l.usedBytes(), 4 * 65536);
});

test('缺少导入函数时拒绝加载', () => {
  const l = new WasmLoader(16);
  assert.throws(() => l.load(decl, {}), /缺少导入函数:log/);
  assert.deepEqual(l.names(), []);
});

test('内存超预算时拒绝加载', () => {
  const l = new WasmLoader(3);
  assert.throws(() => l.load(decl, { log: () => {} }), /内存超出预算/);
  assert.equal(l.remainingPages(), 3);
});

test('调用导出走宿主函数', () => {
  const l = new WasmLoader(16);
  l.load(decl, {
    log: () => {},
    'mesh-codec.decode': (bytes: unknown) => `decoded:${String(bytes)}`,
  });
  assert.equal(l.call('mesh-codec', 'decode', ['abc']), 'decoded:abc');
});

test('未导出的函数与未加载模块报错', () => {
  const l = new WasmLoader(16);
  l.load(decl, { log: () => {} });
  assert.throws(() => l.call('mesh-codec', 'encode'), /没有导出 encode/);
  assert.throws(() => l.call('ghost', 'decode'), /未加载/);
  assert.throws(() => l.load(decl, { log: () => {} }), /已加载/);
});

test('卸载释放内存', () => {
  const l = new WasmLoader(8);
  l.load(decl, { log: () => {} });
  assert.equal(l.remainingPages(), 4);
  assert.equal(l.unload('mesh-codec'), true);
  assert.equal(l.unload('mesh-codec'), false);
  assert.equal(l.remainingPages(), 8);
  assert.deepEqual(l.names(), []);
});

本机实测(Node v26.5.0,node --test test/12-1-editor-wasm.test.ts):tests 6 · pass 6 · fail 0,耗时约 40 ms。

前两条钉加载与缺导入;第三条钉内存预算;第四条钉导出调用;后两条钉未导出与卸载归还。

小结

  • WASM 模块的契约:导入、导出、内存页数。
  • 导入在加载前校验,缺函数直接拒绝。
  • 内存按页累计,超预算不加载。
  • 卸载归还内存,模块名不可重复加载。

阅读导航:上一节:11.3 协作模式与权限 · 下一节:12.2 远程桌面与云端构建 。

继续阅读

探索更多技术文章

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

全部文章 返回首页

「books」更多文章

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