移除额外的打包流程

This commit is contained in:
YHH
2025-06-09 18:27:20 +08:00
parent e6ce8995ba
commit e71c49d596
8 changed files with 816 additions and 431 deletions

View File

@@ -1,243 +0,0 @@
@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,22 +2,16 @@ const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
console.log('🚀 构建 WASM 发布包(支持 Cocos Creator...');
console.log('🚀 构建 WASM 发布包...');
async function main() {
try {
// 构建 Cocos Creator 版本
console.log('🎮 构建 Cocos Creator 版本...');
await buildCocosVersion();
// 构建通用版本(保持兼容性)
console.log('🌐 构建通用版本...');
// 构建通用版本
console.log('🌐 构建通用 WASM 版本...');
await buildUniversalVersion();
console.log('\n✅ WASM 发布包构建完成!');
console.log('📦 输出目录:');
console.log(' - cocos-release/ (Cocos Creator 专用包)');
console.log(' - wasm-release/ (通用包)');
console.log('📦 输出目录: wasm-release/');
console.log('💡 可以将整个目录打包为 zip 文件上传到 GitHub Release');
} catch (error) {
@@ -26,41 +20,7 @@ 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 已构建
@@ -69,15 +29,15 @@ async function buildUniversalVersion() {
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 文件...');
// 复制 WASM 文件
console.log('📁 复制 WASM 文件...');
const wasmDir = './bin/wasm';
fs.readdirSync(wasmDir).forEach(file => {
if (file !== '.gitignore') {
@@ -89,36 +49,35 @@ async function buildUniversalVersion() {
}
});
// 生成包信息
console.log('📋 生成包信息...');
generatePackageInfo(releaseDir);
// 创建使用说明
console.log('📋 生成通用使用说明...');
console.log('📋 生成使用说明...');
generateUsageInstructions(releaseDir);
// 显示结果
showReleaseResults(releaseDir, '通用');
showReleaseResults(releaseDir);
}
function generateCocosPackageInfo(releaseDir) {
function generatePackageInfo(releaseDir) {
const packageInfo = {
name: "@esengine/ecs-framework-wasm-cocos",
name: "@esengine/ecs-framework-wasm",
version: "1.0.0",
description: "ECS Framework WASM 加速模块 - Cocos Creator 专用版",
main: "ecs_wasm_core.ts",
description: "ECS Framework WASM 加速模块",
main: "ecs_wasm_core.js",
files: [
"ecs_wasm_core.ts",
"ecs_wasm_core_bg.bin",
"ecs_wasm_core.js",
"ecs_wasm_core_bg.wasm",
"*.d.ts",
"README.md",
"build-templates/"
"README.md"
],
keywords: ["ecs", "wasm", "cocos-creator", "game-engine"],
keywords: ["ecs", "wasm", "game-engine", "performance"],
author: "ESEngine Team",
license: "MIT",
peerDependencies: {
"@esengine/ecs-framework": "^1.0.0"
},
engines: {
"cocos-creator": ">=3.8.0"
}
};
@@ -128,53 +87,6 @@ function generateCocosPackageInfo(releaseDir) {
);
}
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 支持包
@@ -182,108 +94,121 @@ function generateUsageInstructions(releaseDir) {
## 包含文件
- \`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类型定义
- \`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. 其他环境(浏览器/Node.js
### Node.js 环境
\`\`\`typescript
import { ecsCore } from '@esengine/ecs-framework';
\`\`\`javascript
import init, { EcsCore } from './ecs_wasm_core.js';
// 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实现");
}
});
});
});
\`\`\`
### 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);
}
async function useWasm() {
// 初始化 WASM 模块
await init();
// 创建 ECS 核心实例
const ecsCore = new EcsCore();
// 使用 WASM 加速的 ECS 功能
const entity = ecsCore.create_entity();
console.log('创建实体:', entity);
}
initWasm();
useWasm();
\`\`\`
## 注意事项
### 浏览器环境
1. 如果不使用此WASM包框架会自动使用JavaScript实现功能完全正常
2. WASM主要提供查询性能优化对于大多数应用场景JavaScript实现已足够
3. 确保在ECS系统初始化之前调用\`initializeWasm\`方法
\`\`\`html
<!DOCTYPE html>
<html>
<head>
<script type="module">
import init, { EcsCore } from './ecs_wasm_core.js';
async function main() {
await init();
const ecsCore = new EcsCore();
const entity = ecsCore.create_entity();
console.log('Entity created:', entity);
}
main();
</script>
</head>
<body>
<h1>ECS Framework WASM Demo</h1>
</body>
</html>
\`\`\`
## Cocos Creator 用户
### TypeScript 支持
Cocos Creator 用户请使用专门的 Cocos Creator 包:\`cocos-release/\`
确保包含类型定义:
## 技术支持
\`\`\`typescript
import init, { EcsCore } from './ecs_wasm_core.js';
如遇问题,请访问:
- [GitHub Issues](https://github.com/esengine/ecs-framework/issues)
- [主项目文档](https://github.com/esengine/ecs-framework#readme)
async function typedExample(): Promise<void> {
await init();
const ecsCore = new EcsCore();
const entityId: number = ecsCore.create_entity();
// 使用类型安全的 API
const mask = BigInt(0b1010);
ecsCore.update_entity_mask(entityId, mask);
}
\`\`\`
## 性能优势
WASM 模块主要优化以下操作:
- 🚀 实体查询10-100x 性能提升)
- 🔥 组件掩码操作
- ⚡ 批量实体处理
## 兼容性
- **浏览器**: 支持 WebAssembly 的现代浏览器
- **Node.js**: 16.0+ 版本
- **TypeScript**: 4.0+ 版本
## 许可证
MIT License - 详见 LICENSE 文件
`;
fs.writeFileSync(path.join(releaseDir, 'README.md'), instructions);
}
function showReleaseResults(releaseDir, packageType = '') {
console.log(`\n📊 ${packageType} WASM 发布包内容:`);
fs.readdirSync(releaseDir).forEach(file => {
function showReleaseResults(releaseDir) {
const files = fs.readdirSync(releaseDir);
const totalSize = files.reduce((size, file) => {
const filePath = path.join(releaseDir, file);
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`);
}
return size + stats.size;
}, 0);
console.log(`\n📦 发布包内容 (${releaseDir}):`);
files.forEach(file => {
const filePath = path.join(releaseDir, file);
const stats = fs.statSync(filePath);
const sizeKB = (stats.size / 1024).toFixed(1);
console.log(`${file} (${sizeKB} KB)`);
});
console.log(`\n📊 总计 ${files.length} 个文件,大小: ${(totalSize / 1024).toFixed(1)} KB`);
}
main().catch(console.error);
if (require.main === module) {
main();
}
module.exports = { main };

95
wasm-release/README.md Normal file
View File

@@ -0,0 +1,95 @@
# 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` - 包信息
## 使用方法
### Node.js 环境
```javascript
import init, { EcsCore } from './ecs_wasm_core.js';
async function useWasm() {
// 初始化 WASM 模块
await init();
// 创建 ECS 核心实例
const ecsCore = new EcsCore();
// 使用 WASM 加速的 ECS 功能
const entity = ecsCore.create_entity();
console.log('创建实体:', entity);
}
useWasm();
```
### 浏览器环境
```html
<!DOCTYPE html>
<html>
<head>
<script type="module">
import init, { EcsCore } from './ecs_wasm_core.js';
async function main() {
await init();
const ecsCore = new EcsCore();
const entity = ecsCore.create_entity();
console.log('Entity created:', entity);
}
main();
</script>
</head>
<body>
<h1>ECS Framework WASM Demo</h1>
</body>
</html>
```
### TypeScript 支持
确保包含类型定义:
```typescript
import init, { EcsCore } from './ecs_wasm_core.js';
async function typedExample(): Promise<void> {
await init();
const ecsCore = new EcsCore();
const entityId: number = ecsCore.create_entity();
// 使用类型安全的 API
const mask = BigInt(0b1010);
ecsCore.update_entity_mask(entityId, mask);
}
```
## 性能优势
WASM 模块主要优化以下操作:
- 🚀 实体查询10-100x 性能提升)
- 🔥 组件掩码操作
- ⚡ 批量实体处理
## 兼容性
- **浏览器**: 支持 WebAssembly 的现代浏览器
- **Node.js**: 16.0+ 版本
- **TypeScript**: 4.0+ 版本
## 许可证
MIT License - 详见 LICENSE 文件

141
wasm-release/ecs_wasm_core.d.ts vendored Normal file
View File

@@ -0,0 +1,141 @@
/* 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

@@ -0,0 +1,415 @@
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.

29
wasm-release/ecs_wasm_core_bg.wasm.d.ts vendored Normal file
View File

@@ -0,0 +1,29 @@
/* 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;

23
wasm-release/package.json Normal file
View File

@@ -0,0 +1,23 @@
{
"name": "@esengine/ecs-framework-wasm",
"version": "1.0.0",
"description": "ECS Framework WASM 加速模块",
"main": "ecs_wasm_core.js",
"files": [
"ecs_wasm_core.js",
"ecs_wasm_core_bg.wasm",
"*.d.ts",
"README.md"
],
"keywords": [
"ecs",
"wasm",
"game-engine",
"performance"
],
"author": "ESEngine Team",
"license": "MIT",
"peerDependencies": {
"@esengine/ecs-framework": "^1.0.0"
}
}