规范为cococs wasm

This commit is contained in:
YHH
2025-06-09 18:00:50 +08:00
parent 757eff2937
commit f6250b6d5b
9 changed files with 459 additions and 1017 deletions

View File

@@ -1,287 +0,0 @@
# Cocos Creator 使用指南
本指南专门针对在 Cocos Creator 3.8+ 中使用 @esengine/ecs-framework。
## 安装
```bash
npm install @esengine/ecs-framework
```
## WASM 支持(可选)
🚀 **WASM 模块已独立发布,需要手动下载和配置**
WASM 模块不再包含在 npm 包中,如需使用请从 [GitHub Release](https://github.com/esengine/ecs-framework/releases) 下载。
- 不使用 WASM框架自动使用 JavaScript 实现,功能完全正常
- 使用 WASM提供查询性能优化需要手动配置
## 基本使用
### 1. 创建 ECS 核心
```typescript
import { Core } from '@esengine/ecs-framework';
// 在Cocos组件中初始化
export class GameManager extends Component {
private core: Core;
onLoad() {
// 创建核心实例
this.core = Core.create(true);
console.log('ECS核心已初始化');
// 可选加载WASM支持需要先下载WASM包
this.loadWasmSupport();
}
private async loadWasmSupport() {
try {
// 1. 导入WASM胶水代码需要将文件放到项目中
const { default: wasmFactory } = await import('./ecs_wasm_core.js');
// 2. 使用Cocos API加载WASM文件需要先导入到资源管理器
const wasmFile = await this.loadWasmOrAsm("wasmFiles", "ecs_wasm_core", "your-wasm-uuid");
// 3. 初始化WASM支持
const { ecsCore } = await import('@esengine/ecs-framework');
const success = await ecsCore.initializeWasm(wasmFactory, wasmFile);
if (success) {
console.log('✅ ECS WASM加速已启用');
} else {
console.log('⚠️ WASM初始化失败使用JavaScript实现');
}
} catch (error) {
console.log('⚠️ WASM不可用使用JavaScript实现:', error);
}
}
}
```
### 2. 创建组件
```typescript
import { Component } from '@esengine/ecs-framework';
// 位置组件
export class Position extends Component {
constructor(public x: number = 0, public y: number = 0) {
super();
}
}
// 速度组件
export class Velocity extends Component {
constructor(public dx: number = 0, public dy: number = 0) {
super();
}
}
// 精灵组件关联Cocos节点
export class SpriteComponent extends Component {
constructor(public node: Node) {
super();
}
}
```
### 3. 创建系统
```typescript
import { EntitySystem, Family } from '@esengine/ecs-framework';
export class MovementSystem extends EntitySystem {
constructor() {
super(Family.all(Position, Velocity).get());
}
public processEntity(entity: Entity, deltaTime: number): void {
const pos = entity.getComponent(Position);
const vel = entity.getComponent(Velocity);
pos.x += vel.dx * deltaTime;
pos.y += vel.dy * deltaTime;
}
}
export class SpriteRenderSystem extends EntitySystem {
constructor() {
super(Family.all(Position, SpriteComponent).get());
}
public processEntity(entity: Entity, deltaTime: number): void {
const pos = entity.getComponent(Position);
const sprite = entity.getComponent(SpriteComponent);
// 同步位置到Cocos节点
sprite.node.setPosition(pos.x, pos.y);
}
}
```
### 4. 创建场景
```typescript
import { Scene } from '@esengine/ecs-framework';
export class GameScene extends Scene {
private movementSystem: MovementSystem;
private spriteRenderSystem: SpriteRenderSystem;
public initialize(): void {
// 添加系统
this.movementSystem = this.addEntityProcessor(new MovementSystem());
this.spriteRenderSystem = this.addEntityProcessor(new SpriteRenderSystem());
// 创建一些实体用于测试
this.createTestEntities();
}
private createTestEntities(): void {
for (let i = 0; i < 10; i++) {
const entity = this.createEntity();
// 添加位置组件
entity.addComponent(new Position(
Math.random() * 800,
Math.random() * 600
));
// 添加速度组件
entity.addComponent(new Velocity(
(Math.random() - 0.5) * 200,
(Math.random() - 0.5) * 200
));
// 创建Cocos节点并添加精灵组件
const node = new Node();
const sprite = node.addComponent(Sprite);
// 设置精灵贴图...
entity.addComponent(new SpriteComponent(node));
}
}
}
```
### 5. 在Cocos组件中集成
```typescript
import { Component, _decorator } from 'cc';
import { Core } from '@esengine/ecs-framework';
const { ccclass } = _decorator;
@ccclass('ECSGameManager')
export class ECSGameManager extends Component {
private core: Core;
private gameScene: GameScene;
onLoad() {
// 初始化ECS核心
this.core = Core.create(true);
// 创建游戏场景
this.gameScene = new GameScene();
Core.scene = this.gameScene;
console.log('ECS系统已启动');
}
update(deltaTime: number) {
// ECS系统会自动处理更新
// Core.emitter 会自动触发 frameUpdated 事件
}
onDestroy() {
// 清理资源
if (this.core) {
// 执行必要的清理
}
}
}
```
## 高级功能
### 事件系统
```typescript
import { EventBus, ECSEventType } from '@esengine/ecs-framework';
// 监听实体创建事件
EventBus.subscribe(ECSEventType.EntityCreated, (data) => {
console.log('实体已创建:', data.entityId);
});
// 发射自定义事件
EventBus.emit('player-scored', { score: 100, playerId: 'player1' });
```
### 性能监控
```typescript
import { PerformanceMonitor } from '@esengine/ecs-framework';
// 获取性能统计
const stats = PerformanceMonitor.instance.getStats();
console.log('系统性能:', stats);
```
### 对象池
```typescript
import { PoolManager } from '@esengine/ecs-framework';
// 获取对象池管理器
const poolManager = PoolManager.getInstance();
// 创建对象池
const bulletPool = poolManager.createPool('bullets', () => new BulletComponent(), 100);
// 获取对象
const bullet = bulletPool.obtain();
// 归还对象
bulletPool.free(bullet);
```
## 性能建议
1. **合理使用Family查询**: 避免过于复杂的组件查询
2. **批量操作**: 使用事件系统进行批量更新
3. **对象池**: 频繁创建/销毁的对象使用对象池
4. **定期清理**: 及时移除不需要的实体和组件
## 注意事项
1. 🔧 **WASM 支持**: 在 Cocos Creator 中自动禁用,使用 JavaScript 实现
2. 🎯 **内存管理**: 注意及时清理不需要的实体,避免内存泄漏
3. 🔄 **更新循环**: ECS 系统会自动集成到 Cocos 的更新循环中
4. 📦 **模块化**: 建议按功能拆分不同的系统和组件
## 故障排除
### 常见问题
**Q: 为什么看到"检测到Cocos Creator环境WASM需要手动配置"的警告?**
A: 这是正常的。框架会自动回退到JavaScript实现功能完全正常。
**Q: 如何确认ECS系统正在运行**
A: 查看控制台输出,应该能看到"ECS核心已初始化"等日志。
**Q: 性能是否受到影响?**
A: JavaScript实现的性能已经很好对于大多数游戏场景足够使用。
## 示例项目
完整的示例项目请参考:[GitHub示例仓库](https://github.com/esengine/ecs-framework/tree/master/examples/cocos)
## 技术支持
如遇问题,请访问:
- [GitHub Issues](https://github.com/esengine/ecs-framework/issues)
- [官方文档](https://github.com/esengine/ecs-framework#readme)

243
scripts/build-cocos.bat Normal file
View File

@@ -0,0 +1,243 @@
@echo off
setlocal enabledelayedexpansion
echo.
echo 🎮 构建 ECS Framework WASM for Cocos Creator
echo ============================================
echo.
:: 设置变量
set "RUST_DIR=src\wasm\rust-ecs-core"
set "OUTPUT_DIR=cocos-pkg"
set "WASM_NAME=ecs_wasm_core"
:: 检查必要工具
echo 🔍 检查构建环境...
where wasm-pack >nul 2>&1
if %errorlevel% neq 0 (
echo ❌ 错误: 未找到 wasm-pack
echo 请运行: cargo install wasm-pack
goto :error
)
where rustc >nul 2>&1
if %errorlevel% neq 0 (
echo ❌ 错误: 未找到 Rust 编译器
echo 请安装 Rust: https://rustup.rs/
goto :error
)
echo ✅ 构建环境检查通过
:: 进入 Rust 项目目录
cd /d "%RUST_DIR%"
if %errorlevel% neq 0 (
echo ❌ 错误: 无法进入目录 %RUST_DIR%
goto :error
)
echo.
echo 📦 开始编译 WASM 模块...
echo 目标环境: Cocos Creator (Web + Native)
echo.
:: 清理之前的构建
if exist "pkg" (
echo 🧹 清理旧的构建文件...
rmdir /s /q "pkg"
)
:: 使用 wasm-pack 构建(针对 web 环境)
echo 🔨 编译 WASM 模块...
wasm-pack build --target web --release --no-typescript --out-dir pkg --out-name %WASM_NAME%
if %errorlevel% neq 0 (
echo ❌ WASM 编译失败
goto :error
)
echo ✅ WASM 编译完成
:: 回到项目根目录
cd ..\..\..
:: 创建输出目录
if not exist "%OUTPUT_DIR%" (
mkdir "%OUTPUT_DIR%"
) else (
echo 🧹 清理输出目录...
del /q "%OUTPUT_DIR%\*.*" 2>nul
)
echo.
echo 📁 处理输出文件...
:: 复制和处理 JavaScript 胶水代码
set "JS_SOURCE=%RUST_DIR%\pkg\%WASM_NAME%.js"
set "TS_TARGET=%OUTPUT_DIR%\%WASM_NAME%.ts"
if exist "%JS_SOURCE%" (
echo ✓ 复制并转换 JS 文件为 TS: %WASM_NAME%.ts
copy "%JS_SOURCE%" "%TS_TARGET%" >nul
) else (
echo ❌ 错误: 未找到生成的 JS 文件
goto :error
)
:: 复制 WASM 文件(原生端用 .bin微信小游戏用 .wasm
set "WASM_SOURCE=%RUST_DIR%\pkg\%WASM_NAME%_bg.wasm"
set "BIN_TARGET=%OUTPUT_DIR%\%WASM_NAME%_bg.bin"
set "WASM_TARGET=%OUTPUT_DIR%\%WASM_NAME%_bg.wasm"
if exist "%WASM_SOURCE%" (
echo ✓ 复制 WASM 文件(原生端): %WASM_NAME%_bg.bin
copy "%WASM_SOURCE%" "%BIN_TARGET%" >nul
echo ✓ 复制 WASM 文件(微信小游戏): %WASM_NAME%_bg.wasm
copy "%WASM_SOURCE%" "%WASM_TARGET%" >nul
) else (
echo ❌ 错误: 未找到生成的 WASM 文件
goto :error
)
:: 复制 TypeScript 类型定义(如果存在)
set "DTS_SOURCE=%RUST_DIR%\pkg\%WASM_NAME%.d.ts"
set "DTS_TARGET=%OUTPUT_DIR%\%WASM_NAME%.d.ts"
set "BG_DTS_SOURCE=%RUST_DIR%\pkg\%WASM_NAME%_bg.wasm.d.ts"
set "BG_DTS_TARGET=%OUTPUT_DIR%\%WASM_NAME%_bg.wasm.d.ts"
if exist "%DTS_SOURCE%" (
echo ✓ 复制类型定义: %WASM_NAME%.d.ts
copy "%DTS_SOURCE%" "%DTS_TARGET%" >nul
)
if exist "%BG_DTS_SOURCE%" (
echo ✓ 复制 WASM 类型定义: %WASM_NAME%_bg.wasm.d.ts
copy "%BG_DTS_SOURCE%" "%BG_DTS_TARGET%" >nul
)
:: 生成 Cocos Creator 使用指南
echo.
echo 📋 生成使用指南...
(
echo # ECS Framework WASM for Cocos Creator
echo.
echo ## 文件说明
echo.
echo - `%WASM_NAME%.ts` - WASM 胶水代码(原 JS 文件重命名)
echo - `%WASM_NAME%_bg.bin` - WASM 二进制文件(原生端使用)
echo - `%WASM_NAME%_bg.wasm` - WASM 二进制文件(微信小游戏使用)
echo - `%WASM_NAME%.d.ts` - TypeScript 类型定义
echo.
echo ## 在 Cocos Creator 中使用
echo.
echo ### 1. 导入文件到项目
echo.
echo 1. 将 `%WASM_NAME%.ts` 放到 assets/scripts/ 目录
echo 2. 将 `%WASM_NAME%_bg.bin` 导入为 BufferAsset原生端
echo 3. 将 `%WASM_NAME%_bg.wasm` 放到微信小游戏构建目录
echo.
echo ### 2. 组件代码示例
echo.
echo ```typescript
echo import { _decorator, Component, BufferAsset } from 'cc';
echo import { initSync } from './%WASM_NAME%';
echo.
echo const { ccclass, property } = _decorator;
echo.
echo @ccclass('WasmLoader'^)
echo export class WasmLoader extends Component {
echo @property(BufferAsset^)
echo wasmAsset!: BufferAsset;
echo.
echo start(^) {
echo this.initWasm(^);
echo }
echo.
echo private async initWasm(^) {
echo try {
echo // 检查平台
echo if (typeof wx !== 'undefined'^) {
echo // 微信小游戏环境
echo initSync("/%WASM_NAME%_bg.wasm"^);
echo } else {
echo // 原生端/浏览器环境
echo const wasmBuffer = this.wasmAsset?.buffer(^);
echo if (wasmBuffer^) {
echo initSync(wasmBuffer^);
echo } else {
echo console.error('WASM 资源未正确加载'^);
echo return;
echo }
echo }
echo
echo console.log('✅ ECS WASM 模块初始化成功'^);
echo
echo // 这里可以开始使用 WASM 导出的函数
echo // 例如: wasmFunction(^);
echo
echo } catch (error^) {
echo console.error('❌ WASM 初始化失败:', error^);
echo console.log('↪️ 将使用 JavaScript 实现'^);
echo }
echo }
echo }
echo ```
echo.
echo ### 3. 微信小游戏配置
echo.
echo 使用 build-templates 自动复制 WASM 文件:
echo.
echo 1. 在项目 build-templates/wechatgame/ 目录下创建构建脚本
echo 2. 构建时会自动复制 %WASM_NAME%_bg.wasm 到发布目录
echo.
echo ## 注意事项
echo.
echo 1. 确保在使用 ECS 系统前初始化 WASM 模块
echo 2. 原生端使用 .bin 文件,微信小游戏使用 .wasm 文件
echo 3. 如果 WASM 初始化失败,框架会自动回退到 JavaScript 实现
echo 4. WASM 主要优化查询性能,对大多数应用场景提升有限
echo.
echo ## 重新构建
echo.
echo 运行 `build-cocos.bat` 重新编译最新的 WASM 模块
) > "%OUTPUT_DIR%\README.md"
:: 显示构建结果
echo.
echo 📊 构建结果:
for %%f in ("%OUTPUT_DIR%\*.*") do (
call :filesize "%%f"
echo %%~nxf: !size! KB
)
echo.
echo ✅ 构建完成!
echo 📦 输出目录: %OUTPUT_DIR%
echo 📋 使用说明: %OUTPUT_DIR%\README.md
echo.
echo 💡 下一步:
echo 1. 将文件导入到 Cocos Creator 项目
echo 2. 参考 README.md 集成到游戏中
echo 3. 对于微信小游戏,使用 build-templates 自动复制 WASM 文件
echo.
goto :end
:filesize
set "file=%~1"
for %%A in ("%file%") do set "bytes=%%~zA"
set /a size=bytes/1024
if %size% lss 1 set size=1
goto :eof
:error
echo.
echo ❌ 构建失败!
echo 请检查错误信息并重试。
echo.
pause
exit /b 1
:end
pause

View File

@@ -2,46 +2,23 @@ const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
console.log('🚀 构建WASM发布包...');
console.log('🚀 构建 WASM 发布包(支持 Cocos Creator...');
async function main() {
try {
// 确保WASM已构建
if (!fs.existsSync('./bin/wasm')) {
console.log('📦 构建WASM...');
execSync('npm run build:wasm', { stdio: 'inherit' });
}
// 构建 Cocos Creator 版本
console.log('🎮 构建 Cocos Creator 版本...');
await buildCocosVersion();
// 创建发布目录
const releaseDir = './wasm-release';
if (fs.existsSync(releaseDir)) {
execSync(`rimraf ${releaseDir}`, { stdio: 'inherit' });
}
fs.mkdirSync(releaseDir);
// 构建通用版本(保持兼容性)
console.log('🌐 构建通用版本...');
await buildUniversalVersion();
// 复制WASM文件
console.log('📁 复制WASM文件...');
const wasmDir = './bin/wasm';
fs.readdirSync(wasmDir).forEach(file => {
if (file !== '.gitignore') {
fs.copyFileSync(
path.join(wasmDir, file),
path.join(releaseDir, file)
);
console.log(`${file}`);
}
});
// 创建使用说明
console.log('📋 生成使用说明...');
generateUsageInstructions(releaseDir);
// 显示结果
showReleaseResults(releaseDir);
console.log('\n✅ WASM发布包构建完成');
console.log(`📦 发布目录: ${releaseDir}`);
console.log('💡 可以将整个目录打包为zip文件上传到GitHub Release');
console.log('\n✅ WASM 发布包构建完成!');
console.log('📦 输出目录:');
console.log(' - cocos-release/ (Cocos Creator 专用包)');
console.log(' - wasm-release/ (通用包)');
console.log('💡 可以将整个目录打包为 zip 文件上传到 GitHub Release');
} catch (error) {
console.error('❌ 构建失败:', error.message);
@@ -49,6 +26,155 @@ async function main() {
}
}
async function buildCocosVersion() {
// 确保 Cocos 版本已构建
if (!fs.existsSync('./cocos-pkg')) {
console.log('📦 构建 Cocos Creator WASM...');
execSync('scripts\\build-cocos.bat', { stdio: 'inherit' });
}
// 创建 Cocos 发布目录
const releaseDir = './cocos-release';
if (fs.existsSync(releaseDir)) {
execSync(`rimraf ${releaseDir}`, { stdio: 'inherit' });
}
fs.mkdirSync(releaseDir);
// 复制 Cocos 包文件
console.log('📁 复制 Cocos Creator 文件...');
const cocosDir = './cocos-pkg';
fs.readdirSync(cocosDir).forEach(file => {
fs.copyFileSync(
path.join(cocosDir, file),
path.join(releaseDir, file)
);
console.log(`${file}`);
});
// 生成 Cocos 包信息
console.log('📋 生成 Cocos Creator 包信息...');
generateCocosPackageInfo(releaseDir);
// 复制 build-templates 示例
generateBuildTemplate(releaseDir);
// 显示结果
showReleaseResults(releaseDir, 'Cocos Creator');
}
async function buildUniversalVersion() {
// 确保通用 WASM 已构建
if (!fs.existsSync('./bin/wasm')) {
console.log('📦 构建通用 WASM...');
execSync('npm run build:wasm', { stdio: 'inherit' });
}
// 创建通用发布目录
const releaseDir = './wasm-release';
if (fs.existsSync(releaseDir)) {
execSync(`rimraf ${releaseDir}`, { stdio: 'inherit' });
}
fs.mkdirSync(releaseDir);
// 复制通用 WASM 文件
console.log('📁 复制通用 WASM 文件...');
const wasmDir = './bin/wasm';
fs.readdirSync(wasmDir).forEach(file => {
if (file !== '.gitignore') {
fs.copyFileSync(
path.join(wasmDir, file),
path.join(releaseDir, file)
);
console.log(`${file}`);
}
});
// 创建使用说明
console.log('📋 生成通用使用说明...');
generateUsageInstructions(releaseDir);
// 显示结果
showReleaseResults(releaseDir, '通用');
}
function generateCocosPackageInfo(releaseDir) {
const packageInfo = {
name: "@esengine/ecs-framework-wasm-cocos",
version: "1.0.0",
description: "ECS Framework WASM 加速模块 - Cocos Creator 专用版",
main: "ecs_wasm_core.ts",
files: [
"ecs_wasm_core.ts",
"ecs_wasm_core_bg.bin",
"ecs_wasm_core_bg.wasm",
"*.d.ts",
"README.md",
"build-templates/"
],
keywords: ["ecs", "wasm", "cocos-creator", "game-engine"],
author: "ESEngine Team",
license: "MIT",
peerDependencies: {
"@esengine/ecs-framework": "^1.0.0"
},
engines: {
"cocos-creator": ">=3.8.0"
}
};
fs.writeFileSync(
path.join(releaseDir, 'package.json'),
JSON.stringify(packageInfo, null, 2)
);
}
function generateBuildTemplate(releaseDir) {
const templateDir = path.join(releaseDir, 'build-templates', 'wechatgame');
fs.mkdirSync(templateDir, { recursive: true });
const buildScript = `/**
* 微信小游戏 build-templates 脚本
* 自动将 WASM 文件复制到发布目录
*
* 使用方法:
* 1. 将此文件复制到项目的 build-templates/wechatgame/ 目录
* 2. 重命名为 build-finish.js
* 3. 构建微信小游戏时会自动执行
*/
const fs = require('fs');
const path = require('path');
function copyWasmFiles(options, callback) {
const { buildPath } = options;
console.log('🎮 复制 ECS WASM 文件到微信小游戏目录...');
// WASM 源文件路径(需要根据实际项目结构调整)
const wasmSourcePath = path.join(__dirname, '../../assets/scripts/ecs_wasm_core_bg.wasm');
const wasmTargetPath = path.join(buildPath, 'ecs_wasm_core_bg.wasm');
try {
if (fs.existsSync(wasmSourcePath)) {
fs.copyFileSync(wasmSourcePath, wasmTargetPath);
console.log('✅ WASM 文件复制成功');
} else {
console.warn('⚠️ WASM 文件不存在,跳过复制');
}
} catch (error) {
console.error('❌ 复制 WASM 文件失败:', error.message);
}
if (callback) callback();
}
module.exports = {
onBuildFinished: copyWasmFiles
};`;
fs.writeFileSync(path.join(templateDir, 'build-finish.js'), buildScript);
}
function generateUsageInstructions(releaseDir) {
const instructions = `# ECS Framework WASM 支持包
@@ -64,29 +190,7 @@ function generateUsageInstructions(releaseDir) {
## 使用方法
### 1. Cocos Creator 3.8+
\`\`\`typescript
import { ecsCore } from '@esengine/ecs-framework';
// 1. 将WASM文件导入到项目资源中
// 2. 导入胶水代码
import('./ecs_wasm_core.js').then(({ default: wasmFactory }) => {
// 3. 使用Cocos API加载WASM文件
this.loadWasmOrAsm("wasmFiles", "ecs_wasm_core", "your-wasm-uuid").then((wasmFile) => {
// 4. 初始化WASM支持
ecsCore.initializeWasm(wasmFactory, wasmFile).then((success) => {
if (success) {
console.log("ECS WASM加速已启用");
} else {
console.log("回退到JavaScript实现");
}
});
});
});
\`\`\`
### 2. 其他环境(浏览器/Node.js
### 1. 其他环境(浏览器/Node.js
\`\`\`typescript
import { ecsCore } from '@esengine/ecs-framework';
@@ -107,12 +211,41 @@ import('./ecs_wasm_core.js').then(({ default: wasmFactory }) => {
});
\`\`\`
### 2. Webpack/Vite 等构建工具
\`\`\`typescript
import { ecsCore } from '@esengine/ecs-framework';
import wasmFactory from './ecs_wasm_core.js';
import wasmUrl from './ecs_wasm_core_bg.wasm?url';
async function initWasm() {
try {
const wasmFile = await fetch(wasmUrl).then(r => r.arrayBuffer());
const success = await ecsCore.initializeWasm(wasmFactory, wasmFile);
if (success) {
console.log("ECS WASM加速已启用");
} else {
console.log("回退到JavaScript实现");
}
} catch (error) {
console.error("WASM初始化失败:", error);
}
}
initWasm();
\`\`\`
## 注意事项
1. 如果不使用此WASM包框架会自动使用JavaScript实现功能完全正常
2. WASM主要提供查询性能优化对于大多数应用场景JavaScript实现已足够
3. 确保在ECS系统初始化之前调用\`initializeWasm\`方法
## Cocos Creator 用户
Cocos Creator 用户请使用专门的 Cocos Creator 包:\`cocos-release/\`
## 技术支持
如遇问题,请访问:
@@ -123,12 +256,33 @@ import('./ecs_wasm_core.js').then(({ default: wasmFactory }) => {
fs.writeFileSync(path.join(releaseDir, 'README.md'), instructions);
}
function showReleaseResults(releaseDir) {
console.log('\n📊 WASM发布包内容:');
function showReleaseResults(releaseDir, packageType = '') {
console.log(`\n📊 ${packageType} WASM 发布包内容:`);
fs.readdirSync(releaseDir).forEach(file => {
const filePath = path.join(releaseDir, file);
const size = fs.statSync(filePath).size;
console.log(` ${file}: ${(size / 1024).toFixed(1)}KB`);
const stats = fs.statSync(filePath);
if (stats.isDirectory()) {
console.log(` 📁 ${file}/`);
// 显示子目录内容
try {
fs.readdirSync(filePath).forEach(subFile => {
const subFilePath = path.join(filePath, subFile);
const subStats = fs.statSync(subFilePath);
if (subStats.isFile()) {
const size = (subStats.size / 1024).toFixed(1);
console.log(` ${subFile}: ${size}KB`);
} else {
console.log(` 📁 ${subFile}/`);
}
});
} catch (e) {
// 忽略读取错误
}
} else {
const size = (stats.size / 1024).toFixed(1);
console.log(` ${file}: ${size}KB`);
}
});
}

View File

@@ -1,68 +0,0 @@
# ECS Framework WASM 支持包
这个包包含了 @esengine/ecs-framework 的 WASM 加速模块。
## 包含文件
- `ecs_wasm_core.js` - WASM胶水代码
- `ecs_wasm_core.d.ts` - TypeScript类型定义
- `ecs_wasm_core_bg.wasm` - WASM二进制文件
- `ecs_wasm_core_bg.wasm.d.ts` - WASM类型定义
- `package.json` - 包信息
## 使用方法
### 1. Cocos Creator 3.8+
```typescript
import { ecsCore } from '@esengine/ecs-framework';
// 1. 将WASM文件导入到项目资源中
// 2. 导入胶水代码
import('./ecs_wasm_core.js').then(({ default: wasmFactory }) => {
// 3. 使用Cocos API加载WASM文件
this.loadWasmOrAsm("wasmFiles", "ecs_wasm_core", "your-wasm-uuid").then((wasmFile) => {
// 4. 初始化WASM支持
ecsCore.initializeWasm(wasmFactory, wasmFile).then((success) => {
if (success) {
console.log("ECS WASM加速已启用");
} else {
console.log("回退到JavaScript实现");
}
});
});
});
```
### 2. 其他环境(浏览器/Node.js
```typescript
import { ecsCore } from '@esengine/ecs-framework';
// 1. 导入胶水代码
import('./ecs_wasm_core.js').then(({ default: wasmFactory }) => {
// 2. 加载WASM文件
fetch('./ecs_wasm_core_bg.wasm').then(response => response.arrayBuffer()).then((wasmFile) => {
// 3. 初始化WASM支持
ecsCore.initializeWasm(wasmFactory, wasmFile).then((success) => {
if (success) {
console.log("ECS WASM加速已启用");
} else {
console.log("回退到JavaScript实现");
}
});
});
});
```
## 注意事项
1. 如果不使用此WASM包框架会自动使用JavaScript实现功能完全正常
2. WASM主要提供查询性能优化对于大多数应用场景JavaScript实现已足够
3. 确保在ECS系统初始化之前调用`initializeWasm`方法
## 技术支持
如遇问题,请访问:
- [GitHub Issues](https://github.com/esengine/ecs-framework/issues)
- [主项目文档](https://github.com/esengine/ecs-framework#readme)

View File

@@ -1,141 +0,0 @@
/* tslint:disable */
/* eslint-disable */
/**
* 创建组件掩码的辅助函数
*/
export function create_component_mask(component_ids: Uint32Array): bigint;
/**
* 检查掩码是否包含指定组件
*/
export function mask_contains_component(mask: bigint, component_id: number): boolean;
/**
* 初始化函数
*/
export function main(): void;
/**
* 高性能ECS核心专注于实体查询和掩码管理
*/
export class EcsCore {
free(): void;
/**
* 创建新的ECS核心
*/
constructor();
/**
* 创建新实体
*/
create_entity(): number;
/**
* 删除实体
*/
destroy_entity(entity_id: number): boolean;
/**
* 更新实体的组件掩码
*/
update_entity_mask(entity_id: number, mask: bigint): void;
/**
* 批量更新实体掩码
*/
batch_update_masks(entity_ids: Uint32Array, masks: BigUint64Array): void;
/**
* 查询实体
*/
query_entities(mask: bigint, max_results: number): number;
/**
* 获取查询结果数量
*/
get_query_result_count(): number;
/**
* 缓存查询实体
*/
query_cached(mask: bigint): number;
/**
* 获取缓存查询结果数量
*/
get_cached_query_count(mask: bigint): number;
/**
* 多组件查询
*/
query_multiple_components(masks: BigUint64Array, max_results: number): number;
/**
* 排除查询
*/
query_with_exclusion(include_mask: bigint, exclude_mask: bigint, max_results: number): number;
/**
* 获取实体的组件掩码
*/
get_entity_mask(entity_id: number): bigint;
/**
* 检查实体是否存在
*/
entity_exists(entity_id: number): boolean;
/**
* 获取实体数量
*/
get_entity_count(): number;
/**
* 获取性能统计信息
*/
get_performance_stats(): Array<any>;
/**
* 清理所有数据
*/
clear(): void;
/**
* 重建查询缓存
*/
rebuild_query_cache(): void;
}
export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module;
export interface InitOutput {
readonly memory: WebAssembly.Memory;
readonly __wbg_ecscore_free: (a: number, b: number) => void;
readonly ecscore_new: () => number;
readonly ecscore_create_entity: (a: number) => number;
readonly ecscore_destroy_entity: (a: number, b: number) => number;
readonly ecscore_update_entity_mask: (a: number, b: number, c: bigint) => void;
readonly ecscore_batch_update_masks: (a: number, b: number, c: number, d: number, e: number) => void;
readonly ecscore_query_entities: (a: number, b: bigint, c: number) => number;
readonly ecscore_get_query_result_count: (a: number) => number;
readonly ecscore_query_cached: (a: number, b: bigint) => number;
readonly ecscore_get_cached_query_count: (a: number, b: bigint) => number;
readonly ecscore_query_multiple_components: (a: number, b: number, c: number, d: number) => number;
readonly ecscore_query_with_exclusion: (a: number, b: bigint, c: bigint, d: number) => number;
readonly ecscore_get_entity_mask: (a: number, b: number) => bigint;
readonly ecscore_entity_exists: (a: number, b: number) => number;
readonly ecscore_get_entity_count: (a: number) => number;
readonly ecscore_get_performance_stats: (a: number) => any;
readonly ecscore_clear: (a: number) => void;
readonly ecscore_rebuild_query_cache: (a: number) => void;
readonly create_component_mask: (a: number, b: number) => bigint;
readonly mask_contains_component: (a: bigint, b: number) => number;
readonly main: () => void;
readonly __wbindgen_exn_store: (a: number) => void;
readonly __externref_table_alloc: () => number;
readonly __wbindgen_export_2: WebAssembly.Table;
readonly __wbindgen_malloc: (a: number, b: number) => number;
readonly __wbindgen_start: () => void;
}
export type SyncInitInput = BufferSource | WebAssembly.Module;
/**
* Instantiates the given `module`, which can either be bytes or
* a precompiled `WebAssembly.Module`.
*
* @param {{ module: SyncInitInput }} module - Passing `SyncInitInput` directly is deprecated.
*
* @returns {InitOutput}
*/
export function initSync(module: { module: SyncInitInput } | SyncInitInput): InitOutput;
/**
* If `module_or_path` is {RequestInfo} or {URL}, makes a request and
* for everything else, calls `WebAssembly.instantiate` directly.
*
* @param {{ module_or_path: InitInput | Promise<InitInput> }} module_or_path - Passing `InitInput` directly is deprecated.
*
* @returns {Promise<InitOutput>}
*/
export default function __wbg_init (module_or_path?: { module_or_path: InitInput | Promise<InitInput> } | InitInput | Promise<InitInput>): Promise<InitOutput>;

View File

@@ -1,415 +0,0 @@
let wasm;
let cachedUint8ArrayMemory0 = null;
function getUint8ArrayMemory0() {
if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
}
return cachedUint8ArrayMemory0;
}
function getArrayU8FromWasm0(ptr, len) {
ptr = ptr >>> 0;
return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);
}
function addToExternrefTable0(obj) {
const idx = wasm.__externref_table_alloc();
wasm.__wbindgen_export_2.set(idx, obj);
return idx;
}
function handleError(f, args) {
try {
return f.apply(this, args);
} catch (e) {
const idx = addToExternrefTable0(e);
wasm.__wbindgen_exn_store(idx);
}
}
const cachedTextDecoder = (typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }) : { decode: () => { throw Error('TextDecoder not available') } } );
if (typeof TextDecoder !== 'undefined') { cachedTextDecoder.decode(); };
function getStringFromWasm0(ptr, len) {
ptr = ptr >>> 0;
return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
}
let cachedUint32ArrayMemory0 = null;
function getUint32ArrayMemory0() {
if (cachedUint32ArrayMemory0 === null || cachedUint32ArrayMemory0.byteLength === 0) {
cachedUint32ArrayMemory0 = new Uint32Array(wasm.memory.buffer);
}
return cachedUint32ArrayMemory0;
}
let WASM_VECTOR_LEN = 0;
function passArray32ToWasm0(arg, malloc) {
const ptr = malloc(arg.length * 4, 4) >>> 0;
getUint32ArrayMemory0().set(arg, ptr / 4);
WASM_VECTOR_LEN = arg.length;
return ptr;
}
let cachedBigUint64ArrayMemory0 = null;
function getBigUint64ArrayMemory0() {
if (cachedBigUint64ArrayMemory0 === null || cachedBigUint64ArrayMemory0.byteLength === 0) {
cachedBigUint64ArrayMemory0 = new BigUint64Array(wasm.memory.buffer);
}
return cachedBigUint64ArrayMemory0;
}
function passArray64ToWasm0(arg, malloc) {
const ptr = malloc(arg.length * 8, 8) >>> 0;
getBigUint64ArrayMemory0().set(arg, ptr / 8);
WASM_VECTOR_LEN = arg.length;
return ptr;
}
/**
* 创建组件掩码的辅助函数
* @param {Uint32Array} component_ids
* @returns {bigint}
*/
export function create_component_mask(component_ids) {
const ptr0 = passArray32ToWasm0(component_ids, wasm.__wbindgen_malloc);
const len0 = WASM_VECTOR_LEN;
const ret = wasm.create_component_mask(ptr0, len0);
return BigInt.asUintN(64, ret);
}
/**
* 检查掩码是否包含指定组件
* @param {bigint} mask
* @param {number} component_id
* @returns {boolean}
*/
export function mask_contains_component(mask, component_id) {
const ret = wasm.mask_contains_component(mask, component_id);
return ret !== 0;
}
/**
* 初始化函数
*/
export function main() {
wasm.main();
}
const EcsCoreFinalization = (typeof FinalizationRegistry === 'undefined')
? { register: () => {}, unregister: () => {} }
: new FinalizationRegistry(ptr => wasm.__wbg_ecscore_free(ptr >>> 0, 1));
/**
* 高性能ECS核心专注于实体查询和掩码管理
*/
export class EcsCore {
__destroy_into_raw() {
const ptr = this.__wbg_ptr;
this.__wbg_ptr = 0;
EcsCoreFinalization.unregister(this);
return ptr;
}
free() {
const ptr = this.__destroy_into_raw();
wasm.__wbg_ecscore_free(ptr, 0);
}
/**
* 创建新的ECS核心
*/
constructor() {
const ret = wasm.ecscore_new();
this.__wbg_ptr = ret >>> 0;
EcsCoreFinalization.register(this, this.__wbg_ptr, this);
return this;
}
/**
* 创建新实体
* @returns {number}
*/
create_entity() {
const ret = wasm.ecscore_create_entity(this.__wbg_ptr);
return ret >>> 0;
}
/**
* 删除实体
* @param {number} entity_id
* @returns {boolean}
*/
destroy_entity(entity_id) {
const ret = wasm.ecscore_destroy_entity(this.__wbg_ptr, entity_id);
return ret !== 0;
}
/**
* 更新实体的组件掩码
* @param {number} entity_id
* @param {bigint} mask
*/
update_entity_mask(entity_id, mask) {
wasm.ecscore_update_entity_mask(this.__wbg_ptr, entity_id, mask);
}
/**
* 批量更新实体掩码
* @param {Uint32Array} entity_ids
* @param {BigUint64Array} masks
*/
batch_update_masks(entity_ids, masks) {
const ptr0 = passArray32ToWasm0(entity_ids, wasm.__wbindgen_malloc);
const len0 = WASM_VECTOR_LEN;
const ptr1 = passArray64ToWasm0(masks, wasm.__wbindgen_malloc);
const len1 = WASM_VECTOR_LEN;
wasm.ecscore_batch_update_masks(this.__wbg_ptr, ptr0, len0, ptr1, len1);
}
/**
* 查询实体
* @param {bigint} mask
* @param {number} max_results
* @returns {number}
*/
query_entities(mask, max_results) {
const ret = wasm.ecscore_query_entities(this.__wbg_ptr, mask, max_results);
return ret >>> 0;
}
/**
* 获取查询结果数量
* @returns {number}
*/
get_query_result_count() {
const ret = wasm.ecscore_get_query_result_count(this.__wbg_ptr);
return ret >>> 0;
}
/**
* 缓存查询实体
* @param {bigint} mask
* @returns {number}
*/
query_cached(mask) {
const ret = wasm.ecscore_query_cached(this.__wbg_ptr, mask);
return ret >>> 0;
}
/**
* 获取缓存查询结果数量
* @param {bigint} mask
* @returns {number}
*/
get_cached_query_count(mask) {
const ret = wasm.ecscore_get_cached_query_count(this.__wbg_ptr, mask);
return ret >>> 0;
}
/**
* 多组件查询
* @param {BigUint64Array} masks
* @param {number} max_results
* @returns {number}
*/
query_multiple_components(masks, max_results) {
const ptr0 = passArray64ToWasm0(masks, wasm.__wbindgen_malloc);
const len0 = WASM_VECTOR_LEN;
const ret = wasm.ecscore_query_multiple_components(this.__wbg_ptr, ptr0, len0, max_results);
return ret >>> 0;
}
/**
* 排除查询
* @param {bigint} include_mask
* @param {bigint} exclude_mask
* @param {number} max_results
* @returns {number}
*/
query_with_exclusion(include_mask, exclude_mask, max_results) {
const ret = wasm.ecscore_query_with_exclusion(this.__wbg_ptr, include_mask, exclude_mask, max_results);
return ret >>> 0;
}
/**
* 获取实体的组件掩码
* @param {number} entity_id
* @returns {bigint}
*/
get_entity_mask(entity_id) {
const ret = wasm.ecscore_get_entity_mask(this.__wbg_ptr, entity_id);
return BigInt.asUintN(64, ret);
}
/**
* 检查实体是否存在
* @param {number} entity_id
* @returns {boolean}
*/
entity_exists(entity_id) {
const ret = wasm.ecscore_entity_exists(this.__wbg_ptr, entity_id);
return ret !== 0;
}
/**
* 获取实体数量
* @returns {number}
*/
get_entity_count() {
const ret = wasm.ecscore_get_entity_count(this.__wbg_ptr);
return ret >>> 0;
}
/**
* 获取性能统计信息
* @returns {Array<any>}
*/
get_performance_stats() {
const ret = wasm.ecscore_get_performance_stats(this.__wbg_ptr);
return ret;
}
/**
* 清理所有数据
*/
clear() {
wasm.ecscore_clear(this.__wbg_ptr);
}
/**
* 重建查询缓存
*/
rebuild_query_cache() {
wasm.ecscore_rebuild_query_cache(this.__wbg_ptr);
}
}
async function __wbg_load(module, imports) {
if (typeof Response === 'function' && module instanceof Response) {
if (typeof WebAssembly.instantiateStreaming === 'function') {
try {
return await WebAssembly.instantiateStreaming(module, imports);
} catch (e) {
if (module.headers.get('Content-Type') != 'application/wasm') {
console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e);
} else {
throw e;
}
}
}
const bytes = await module.arrayBuffer();
return await WebAssembly.instantiate(bytes, imports);
} else {
const instance = await WebAssembly.instantiate(module, imports);
if (instance instanceof WebAssembly.Instance) {
return { instance, module };
} else {
return instance;
}
}
}
function __wbg_get_imports() {
const imports = {};
imports.wbg = {};
imports.wbg.__wbg_getRandomValues_3c9c0d586e575a16 = function() { return handleError(function (arg0, arg1) {
globalThis.crypto.getRandomValues(getArrayU8FromWasm0(arg0, arg1));
}, arguments) };
imports.wbg.__wbg_log_bb5387ff27ac9b37 = function(arg0, arg1) {
console.log(getStringFromWasm0(arg0, arg1));
};
imports.wbg.__wbg_new_78feb108b6472713 = function() {
const ret = new Array();
return ret;
};
imports.wbg.__wbg_push_737cfc8c1432c2c6 = function(arg0, arg1) {
const ret = arg0.push(arg1);
return ret;
};
imports.wbg.__wbindgen_init_externref_table = function() {
const table = wasm.__wbindgen_export_2;
const offset = table.grow(4);
table.set(0, undefined);
table.set(offset + 0, undefined);
table.set(offset + 1, null);
table.set(offset + 2, true);
table.set(offset + 3, false);
;
};
imports.wbg.__wbindgen_number_new = function(arg0) {
const ret = arg0;
return ret;
};
imports.wbg.__wbindgen_throw = function(arg0, arg1) {
throw new Error(getStringFromWasm0(arg0, arg1));
};
return imports;
}
function __wbg_init_memory(imports, memory) {
}
function __wbg_finalize_init(instance, module) {
wasm = instance.exports;
__wbg_init.__wbindgen_wasm_module = module;
cachedBigUint64ArrayMemory0 = null;
cachedUint32ArrayMemory0 = null;
cachedUint8ArrayMemory0 = null;
wasm.__wbindgen_start();
return wasm;
}
function initSync(module) {
if (wasm !== undefined) return wasm;
if (typeof module !== 'undefined') {
if (Object.getPrototypeOf(module) === Object.prototype) {
({module} = module)
} else {
console.warn('using deprecated parameters for `initSync()`; pass a single object instead')
}
}
const imports = __wbg_get_imports();
__wbg_init_memory(imports);
if (!(module instanceof WebAssembly.Module)) {
module = new WebAssembly.Module(module);
}
const instance = new WebAssembly.Instance(module, imports);
return __wbg_finalize_init(instance, module);
}
async function __wbg_init(module_or_path) {
if (wasm !== undefined) return wasm;
if (typeof module_or_path !== 'undefined') {
if (Object.getPrototypeOf(module_or_path) === Object.prototype) {
({module_or_path} = module_or_path)
} else {
console.warn('using deprecated parameters for the initialization function; pass a single object instead')
}
}
if (typeof module_or_path === 'undefined') {
module_or_path = new URL('ecs_wasm_core_bg.wasm', import.meta.url);
}
const imports = __wbg_get_imports();
if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {
module_or_path = fetch(module_or_path);
}
__wbg_init_memory(imports);
const { instance, module } = await __wbg_load(await module_or_path, imports);
return __wbg_finalize_init(instance, module);
}
export { initSync };
export default __wbg_init;

Binary file not shown.

View File

@@ -1,29 +0,0 @@
/* tslint:disable */
/* eslint-disable */
export const memory: WebAssembly.Memory;
export const __wbg_ecscore_free: (a: number, b: number) => void;
export const ecscore_new: () => number;
export const ecscore_create_entity: (a: number) => number;
export const ecscore_destroy_entity: (a: number, b: number) => number;
export const ecscore_update_entity_mask: (a: number, b: number, c: bigint) => void;
export const ecscore_batch_update_masks: (a: number, b: number, c: number, d: number, e: number) => void;
export const ecscore_query_entities: (a: number, b: bigint, c: number) => number;
export const ecscore_get_query_result_count: (a: number) => number;
export const ecscore_query_cached: (a: number, b: bigint) => number;
export const ecscore_get_cached_query_count: (a: number, b: bigint) => number;
export const ecscore_query_multiple_components: (a: number, b: number, c: number, d: number) => number;
export const ecscore_query_with_exclusion: (a: number, b: bigint, c: bigint, d: number) => number;
export const ecscore_get_entity_mask: (a: number, b: number) => bigint;
export const ecscore_entity_exists: (a: number, b: number) => number;
export const ecscore_get_entity_count: (a: number) => number;
export const ecscore_get_performance_stats: (a: number) => any;
export const ecscore_clear: (a: number) => void;
export const ecscore_rebuild_query_cache: (a: number) => void;
export const create_component_mask: (a: number, b: number) => bigint;
export const mask_contains_component: (a: bigint, b: number) => number;
export const main: () => void;
export const __wbindgen_exn_store: (a: number) => void;
export const __externref_table_alloc: () => number;
export const __wbindgen_export_2: WebAssembly.Table;
export const __wbindgen_malloc: (a: number, b: number) => number;
export const __wbindgen_start: () => void;

View File

@@ -1,15 +0,0 @@
{
"name": "ecs-wasm-core",
"type": "module",
"version": "0.1.0",
"files": [
"ecs_wasm_core_bg.wasm",
"ecs_wasm_core.js",
"ecs_wasm_core.d.ts"
],
"main": "ecs_wasm_core.js",
"types": "ecs_wasm_core.d.ts",
"sideEffects": [
"./snippets/*"
]
}