Files
shooter-demo/client-cocos/assets/scripts/Utils/WasmLoaderExample.ts

128 lines
4.4 KiB
TypeScript
Raw Normal View History

2025-11-28 18:10:10 +08:00
/**
* WasmLoader 使
*
* 使 WasmLoader WASM
*/
import { wasmLoader } from './WasmLoader';
// 假设我们有一个 WASM 工厂函数(需要从 JS 胶水代码中导入)
// import wasmFactory from '../path/to/your-wasm-module.js';
export class WasmLoaderExample {
/**
* 示例1: 加载简单的 WASM
*/
async loadSimpleWasmExample(wasmFactory: any) {
try {
// 首先需要初始化加载器(通常在应用启动时执行一次)
wasmLoader.initialize();
// 假设你有一个 WASM 工厂函数
// const wasmFactory = (await import('../wasm/pinball_physics.js')).default;
// 加载 WASM 模块
const instance = await wasmLoader.loadSimpleWasm(
wasmFactory, // WASM 工厂函数
'pinball_physics.wasm', // WASM 文件名
'44cacb3c-e901-455d-b3e1-1c38a69718e1', // 编辑器中的 UUID可选
'wasmFiles' // Bundle 名称(可选)
);
// 现在可以使用 WASM 模块的函数
console.log('WASM 模块加载成功:', instance);
return instance;
} catch (error) {
console.error('WASM 加载失败:', error);
throw error;
}
}
/**
* 示例2: 加载支持 ASM 退 WASM
*/
async loadWasmWithFallbackExample(wasmFactory: any, asmFactory: any) {
try {
wasmLoader.initialize();
// 假设你有 WASM 和 ASM 工厂函数
// const wasmFactory = (await import('../wasm/pinball_physics.js')).default;
// const asmFactory = (await import('../wasm/pinball_physics.asm.js')).default;
const result = await wasmLoader.loadWasmWithAsmFallback(
wasmFactory, // WASM 工厂函数
asmFactory, // ASM 工厂函数
'pinball_physics.wasm', // WASM 文件名
'pinball_physics.asm.mem', // ASM 内存文件名
'44cacb3c-e901-455d-b3e1-1c38a69718e1', // WASM UUID
'3400003e-dc3c-43c1-8757-3e082429125a', // ASM UUID
'wasmFiles' // Bundle 名称
);
console.log('模块加载成功,使用的是:', result.isWasm ? 'WASM' : 'ASM');
console.log('模块实例:', result.instance);
return result;
} catch (error) {
console.error('模块加载失败:', error);
throw error;
}
}
/**
* 示例3: 检查平台支持情况
*/
checkPlatformSupport() {
const isWasmSupported = wasmLoader.isWasmSupported();
const strategy = wasmLoader.getRecommendedStrategy();
console.log('WASM 支持:', isWasmSupported);
console.log('推荐策略:', strategy);
return { isWasmSupported, strategy };
}
/**
* 示例4: 高级用法 -
*/
async loadCustomWasm(wasmFactory: any, asmFactory: any) {
try {
wasmLoader.initialize();
// 使用完整配置
const result = await wasmLoader.loadWasmModule({
fileName: 'pinball_physics.wasm',
bundleName: 'wasmFiles',
editorUuid: '44cacb3c-e901-455d-b3e1-1c38a69718e1',
supportAsm: true,
asmFileName: 'pinball_physics.asm.mem',
asmEditorUuid: '3400003e-dc3c-43c1-8757-3e082429125a',
wasmFactory: wasmFactory,
asmFactory: asmFactory
});
return result;
} catch (error) {
console.error('自定义 WASM 加载失败:', error);
throw error;
}
}
}
/**
* 使:
*
* 1. WASM JS
* 2. .wasm
* 3. .wasm UUID
* 4. JS
* 5. wasmLoader WASM
*
* :
* - UUID
* - Bundle
* - iOS WASM ASM 退
* - 使 initialize()
*/