Compare commits

..

86 Commits

Author SHA1 Message Date
YHH
a801e4f50e Merge pull request #150 from esengine/issue-149-编辑器支持设置字体大小
支持字体设置大小
2025-10-17 23:47:42 +08:00
YHH
a9f9ad9b94 支持字体设置大小 2025-10-17 23:47:04 +08:00
YHH
3cf1dab5b9 Merge pull request #148 from esengine/issue-147-Scene的构造函数不应该由用户传入性能分析器
performancemonitor由内部框架维护
2025-10-17 22:19:53 +08:00
YHH
63165bbbfc performancemonitor由内部框架维护 2025-10-17 22:13:32 +08:00
YHH
61caad2bef Merge pull request #146 from esengine/issue-132-场景序列化系统
更新图标及场景序列化系统
2025-10-17 18:17:56 +08:00
YHH
b826bbc4c7 更新图标及场景序列化系统 2025-10-17 18:13:31 +08:00
YHH
2ce7dad8d8 Merge pull request #131 from esengine/release/editor-v1.0.3
chore(editor): Release v1.0.3
2025-10-16 23:53:37 +08:00
esengine
dff400bf22 chore(editor): bump version to 1.0.3 2025-10-16 15:52:45 +00:00
YHH
27ce902344 配置createUpdaterArtifacts生成sig 2025-10-16 23:38:11 +08:00
YHH
33ee0a04c6 升级tauri-action 2025-10-16 23:20:55 +08:00
YHH
d68f6922f8 Merge pull request #129 from esengine/release/editor-v1.0.1
chore(editor): Release v1.0.1
2025-10-16 23:09:26 +08:00
esengine
f8539d7958 chore(editor): bump version to 1.0.1 2025-10-16 15:08:22 +00:00
YHH
14dc911e0a Merge branch 'master' of https://github.com/esengine/ecs-framework 2025-10-16 22:55:09 +08:00
YHH
deccb6bf84 修复editor再ci上版本冲突问题 2025-10-16 22:54:58 +08:00
YHH
dacbfcae95 Merge pull request #127 from esengine/imgbot
[ImgBot] Optimize images
2025-10-16 22:49:51 +08:00
ImgBotApp
1b69ed17b7 [ImgBot] Optimize images
*Total -- 496.42kb -> 376.40kb (24.18%)

/screenshots/main_screetshot.png -- 179.18kb -> 121.90kb (31.97%)
/screenshots/performance_profiler.png -- 59.99kb -> 41.74kb (30.43%)
/screenshots/port_manager.png -- 22.70kb -> 16.86kb (25.72%)
/screenshots/about.png -- 38.75kb -> 29.00kb (25.17%)
/screenshots/plugin_manager.png -- 38.49kb -> 29.16kb (24.25%)
/packages/editor-app/src-tauri/icons/icon.svg -- 3.52kb -> 2.76kb (21.6%)
/screenshots/settings.png -- 53.78kb -> 44.90kb (16.51%)
/packages/editor-app/src-tauri/icons/icon.png -- 33.45kb -> 29.78kb (10.98%)
/packages/editor-app/src-tauri/icons/512x512.png -- 33.45kb -> 29.78kb (10.98%)
/packages/editor-app/src-tauri/icons/256x256.png -- 13.97kb -> 12.76kb (8.68%)
/packages/editor-app/src-tauri/icons/128x128@2x.png -- 13.97kb -> 12.76kb (8.68%)
/packages/editor-app/src-tauri/icons/128x128.png -- 5.17kb -> 5.03kb (2.89%)

Signed-off-by: ImgBotApp <ImgBotHelp@gmail.com>
2025-10-16 14:45:32 +00:00
YHH
241acc9050 更新文档 2025-10-16 22:45:08 +08:00
YHH
8fa921930c Merge pull request #126 from esengine/issue-125-编辑器热更新
热更新配置
2025-10-16 22:31:26 +08:00
YHH
011e43811a 热更新配置 2025-10-16 22:26:50 +08:00
YHH
9f16debd75 新增rust编译缓存和ts构建缓存 2025-10-16 20:54:33 +08:00
YHH
92c56c439b 移除过时的工作流 2025-10-16 20:50:32 +08:00
YHH
7de6a5af0f v2.2.5 2025-10-16 20:37:16 +08:00
YHH
173a063781 Merge pull request #124 from esengine/issue-122-格式化的标准配置
所有源代码文件使用 LF (Unix 风格)
2025-10-16 20:29:21 +08:00
YHH
e04ac7c909 所有源代码文件使用 LF (Unix 风格)
prettier格式化
eslint代码质量检查
2025-10-16 20:24:45 +08:00
YHH
a6e49e1d47 修复publish-release中release_id错误问题 2025-10-16 20:07:56 +08:00
YHH
f0046c7dc2 新增icons作为编辑器图标 2025-10-16 19:52:17 +08:00
YHH
2a17c47c25 修复ts警告 2025-10-16 18:20:31 +08:00
YHH
8d741bf1b9 Merge pull request #123 from esengine/issue-119-插件化编辑器
Issue 119 插件化编辑器
2025-10-16 17:50:35 +08:00
YHH
c676006632 构建配置 2025-10-16 17:44:57 +08:00
YHH
5bcfd597b9 Merge remote-tracking branch 'remotes/origin/master' into issue-119-插件化编辑器 2025-10-16 17:37:24 +08:00
YHH
3cda3c2238 显示客户端链接的ip:port 2025-10-16 17:33:43 +08:00
YHH
43bdd7e43b 远程读取日志 2025-10-16 17:10:22 +08:00
YHH
1ec7892338 设置界面 2025-10-16 13:07:19 +08:00
YHH
6bcfd48a2f 清理调试日志 2025-10-16 12:21:18 +08:00
YHH
345ef70972 支持color类型 2025-10-16 12:00:17 +08:00
YHH
c876edca0c 调试实体和组件属性 2025-10-16 11:55:41 +08:00
YHH
fcf3def284 收集远端数据再profiler dockpanel上 2025-10-15 23:24:13 +08:00
YHH
6f1a2896dd 性能分析器及端口管理器 2025-10-15 22:30:49 +08:00
YHH
62381f4160 记录上一次操作的面板的size大小持久化 2025-10-15 20:26:40 +08:00
YHH
171805debf 禁用默认右键 2025-10-15 20:23:55 +08:00
YHH
619abcbfbc 插件管理器 2025-10-15 20:10:52 +08:00
YHH
03909924c2 app loading 2025-10-15 18:29:48 +08:00
YHH
f4ea077114 菜单栏 2025-10-15 18:24:13 +08:00
YHH
956ccf9195 2D/3D视口 2025-10-15 18:08:55 +08:00
YHH
e880925e3f 视口视图 2025-10-15 17:28:45 +08:00
YHH
0a860920ad 日志面板 2025-10-15 17:21:59 +08:00
YHH
fb7a1b1282 可动态识别属性 2025-10-15 17:15:05 +08:00
YHH
59970ef7c3 Merge pull request #121 from foxling/fix/parent-child-deserialization-bug
fix: 修复场景反序列化时子实体丢失的问题
2025-10-15 15:55:26 +08:00
LING YE
a7750c2894 fix: 修复场景反序列化时子实体丢失的问题
在场景反序列化过程中,子实体虽然保持了父子引用关系,
但未被添加到 Scene 的实体集合和查询系统中,导致查询时子实体"丢失"。
2025-10-15 15:48:54 +08:00
YHH
b69b81f63a 支持树形资源管理器 2025-10-15 10:08:15 +08:00
YHH
00fc6dfd67 Dock系统,支持Tab和拖放 2025-10-15 09:58:45 +08:00
YHH
82451e9fd3 可拖动调整大小的面板 2025-10-15 09:43:48 +08:00
YHH
d0fcc0e447 项目启动流程和资产浏览器功能 2025-10-15 09:34:44 +08:00
YHH
285279629e 优化加载脚本逻辑 2025-10-15 09:19:30 +08:00
YHH
cbfe09b5e9 组件发现和动态加载系统 2025-10-15 00:40:27 +08:00
YHH
b757c1d06c 项目打开功能 2025-10-15 00:23:19 +08:00
YHH
4550a6146a 组件属性编辑器 2025-10-15 00:15:12 +08:00
YHH
3224bb9696 国际化系统 2025-10-14 23:56:54 +08:00
YHH
3a5e73266e 组件注册与添加 2025-10-14 23:42:06 +08:00
YHH
1cf5641c4c 实体存储和管理服务 2025-10-14 23:31:09 +08:00
YHH
85dad41e60 Tauri 窗口,显示编辑器界面 2025-10-14 23:15:07 +08:00
YHH
bd839cf431 Tauri 编辑器应用框架 2025-10-14 22:53:26 +08:00
YHH
b20b2ae4ce 编辑器核心框架 2025-10-14 22:33:55 +08:00
YHH
cac6aedf78 调试插件 DebugPlugin 2025-10-14 22:12:35 +08:00
YHH
a572c80967 v2.2.4 2025-10-14 21:22:07 +08:00
YHH
a09e8261db Merge pull request #118 from esengine/issue-117-统一组件注册系统,移除ComponentTypeManager重复实现
移除了功能重复的ComponentTypeManager
2025-10-14 18:24:17 +08:00
YHH
62e8ebe926 移除了功能重复的ComponentTypeManager 2025-10-14 18:19:08 +08:00
YHH
96e0a9126f Merge pull request #116 from esengine/issue-94-响应式查询(Reactive_Query_System)/_Event-driven_Query
使用ComponentRegistry来确保与Entity.componentMask使用相同的bitIndex
2025-10-14 17:56:26 +08:00
YHH
4afb195814 Merge remote-tracking branch 'origin/master' into issue-94-响应式查询(Reactive_Query_System)/_Event-driven_Query 2025-10-14 17:51:59 +08:00
YHH
7da5366bca 修复querysystem循环依赖的问题 2025-10-14 17:50:32 +08:00
YHH
d979c38615 使用ComponentRegistry来确保与Entity.componentMask使用相同的bitIndex 2025-10-14 17:34:15 +08:00
YHH
7def06126b Merge pull request #115 from esengine/issue-114-reactive-query_文档
新增实体查询系统文档
2025-10-14 13:39:23 +08:00
YHH
9f600f88b0 新增实体查询系统文档 2025-10-14 13:33:12 +08:00
YHH
e3c4d5f0c0 Merge pull request #105 from esengine/issue-94-响应式查询(Reactive_Query_System)/_Event-driven_Query
响应式查询
2025-10-14 12:29:54 +08:00
YHH
b97f3a8431 移除了 EntitySystem.update() 中的冗余 invalidate() 调用 2025-10-14 12:08:08 +08:00
YHH
3b917a06af 修复响应式查询缓存失效和测试隔离问题 2025-10-14 11:48:04 +08:00
YHH
360106fb92 优化ReactiveQuery: 添加公共API、修复内存泄漏、提升通知性能 2025-10-13 23:55:43 +08:00
YHH
507ed5005f Merge remote-tracking branch 'origin/master' into issue-94-响应式查询(Reactive_Query_System)/_Event-driven_Query 2025-10-13 23:36:12 +08:00
YHH
8bea5d5e68 Merge remote-tracking branch 'origin/master' into issue-94-响应式查询(Reactive_Query_System)/_Event-driven_Query 2025-10-13 23:29:56 +08:00
YHH
99076adb72 Merge pull request #113 from esengine/issue-112-优化_DebugManager_使用_DI_避免依赖问题
使用DI避免依赖问题
2025-10-13 23:21:10 +08:00
YHH
d1a6230b23 新增调试配置服务用于DI 2025-10-13 23:17:10 +08:00
YHH
cfe3916934 使用DI避免依赖问题 2025-10-13 22:56:49 +08:00
YHH
d798995876 Merge pull request #111 from esengine/issue-110-_Inject_装饰器在_Cocos_Creator_环境中不执行
扩展 InjectableMetadata 接口支持属性注入,实现 @InjectProperty 装饰器
2025-10-12 23:44:22 +08:00
YHH
43e6b7bf88 扩展 InjectableMetadata 接口支持属性注入,实现 @InjectProperty 装饰器 2025-10-12 23:39:32 +08:00
YHH
942043f0b0 报告响应式查询的数量而不是传统缓存 2025-10-11 18:44:55 +08:00
YHH
23d81bca35 响应式查询 2025-10-11 18:31:20 +08:00
207 changed files with 31624 additions and 398 deletions

35
.editorconfig Normal file
View File

@@ -0,0 +1,35 @@
# EditorConfig is awesome: https://EditorConfig.org
# top-most EditorConfig file
root = true
# 所有文件的默认设置
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
# TypeScript/JavaScript 文件
[*.{ts,tsx,js,jsx,mjs,cjs}]
indent_style = space
indent_size = 4
# JSON 文件
[*.json]
indent_style = space
indent_size = 2
# YAML 文件
[*.{yml,yaml}]
indent_style = space
indent_size = 2
# Markdown 文件
[*.md]
trim_trailing_whitespace = false
indent_size = 2
# 包管理文件
[{package.json,package-lock.json,tsconfig.json}]
indent_size = 2

45
.eslintrc.json Normal file
View File

@@ -0,0 +1,45 @@
{
"root": true,
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 2020,
"sourceType": "module",
"project": "./tsconfig.json"
},
"plugins": [
"@typescript-eslint"
],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended"
],
"rules": {
"semi": ["error", "always"],
"quotes": ["error", "single", { "avoidEscape": true }],
"indent": ["error", 4, { "SwitchCase": 1 }],
"no-trailing-spaces": "error",
"eol-last": ["error", "always"],
"comma-dangle": ["error", "none"],
"object-curly-spacing": ["error", "always"],
"array-bracket-spacing": ["error", "never"],
"arrow-parens": ["error", "always"],
"no-multiple-empty-lines": ["error", { "max": 2, "maxEOF": 1 }],
"no-console": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/explicit-module-boundary-types": "off",
"@typescript-eslint/no-unused-vars": ["warn", { "argsIgnorePattern": "^_" }],
"@typescript-eslint/no-non-null-assertion": "off"
},
"ignorePatterns": [
"node_modules/",
"dist/",
"bin/",
"build/",
"coverage/",
"thirdparty/",
"examples/lawn-mower-demo/",
"extensions/",
"*.min.js",
"*.d.ts"
]
}

44
.gitattributes vendored Normal file
View File

@@ -0,0 +1,44 @@
# 自动检测文本文件并规范化换行符
* text=auto
# 源代码文件强制使用 LF
*.ts text eol=lf
*.tsx text eol=lf
*.js text eol=lf
*.jsx text eol=lf
*.mjs text eol=lf
*.cjs text eol=lf
*.json text eol=lf
*.md text eol=lf
*.yml text eol=lf
*.yaml text eol=lf
# 配置文件强制使用 LF
.gitignore text eol=lf
.gitattributes text eol=lf
.editorconfig text eol=lf
.prettierrc text eol=lf
.prettierignore text eol=lf
.eslintrc.json text eol=lf
tsconfig.json text eol=lf
# Shell 脚本强制使用 LF
*.sh text eol=lf
# Windows 批处理文件使用 CRLF
*.bat text eol=crlf
*.cmd text eol=crlf
*.ps1 text eol=crlf
# 二进制文件不转换
*.png binary
*.jpg binary
*.jpeg binary
*.gif binary
*.ico binary
*.svg binary
*.woff binary
*.woff2 binary
*.ttf binary
*.eot binary
*.otf binary

151
.github/workflows/release-editor.yml vendored Normal file
View File

@@ -0,0 +1,151 @@
name: Release Editor App
on:
push:
tags:
- 'editor-v*'
workflow_dispatch:
inputs:
version:
description: 'Release version (e.g., 1.0.0)'
required: true
default: '1.0.0'
jobs:
build-tauri:
strategy:
fail-fast: false
matrix:
include:
- platform: windows-latest
target: x86_64-pc-windows-msvc
arch: x64
- platform: macos-latest
target: x86_64-apple-darwin
arch: x64
- platform: macos-latest
target: aarch64-apple-darwin
arch: arm64
runs-on: ${{ matrix.platform }}
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20.x'
cache: 'npm'
- name: Install Rust stable
uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.target }}
- name: Rust cache
uses: Swatinem/rust-cache@v2
with:
workspaces: packages/editor-app/src-tauri
cache-on-failure: true
- name: Install dependencies (Ubuntu)
if: matrix.platform == 'ubuntu-latest'
run: |
sudo apt-get update
sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.0-dev libappindicator3-dev librsvg2-dev patchelf
- name: Install frontend dependencies
run: npm ci
- name: Update version in config files (for manual trigger)
if: github.event_name == 'workflow_dispatch'
run: |
cd packages/editor-app
# 临时更新版本号用于构建(不提交到仓库)
npm version ${{ github.event.inputs.version }} --no-git-tag-version
node scripts/sync-version.js
- name: Cache TypeScript build
uses: actions/cache@v4
with:
path: |
packages/core/bin
packages/editor-core/dist
key: ${{ runner.os }}-ts-build-${{ hashFiles('packages/core/src/**', 'packages/editor-core/src/**') }}
restore-keys: |
${{ runner.os }}-ts-build-
- name: Build core package
run: npm run build:core
- name: Build editor-core package
run: |
cd packages/editor-core
npm run build
- name: Build Tauri app
uses: tauri-apps/tauri-action@v0.5
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
with:
projectPath: packages/editor-app
tagName: ${{ github.event_name == 'workflow_dispatch' && format('editor-v{0}', github.event.inputs.version) || github.ref_name }}
releaseName: 'ECS Editor v${{ github.event.inputs.version || github.ref_name }}'
releaseBody: 'See the assets to download this version and install.'
releaseDraft: false
prerelease: false
includeUpdaterJson: true
updaterJsonKeepUniversal: false
args: ${{ matrix.platform == 'macos-latest' && format('--target {0}', matrix.target) || '' }}
# 构建成功后,创建 PR 更新版本号
update-version-pr:
needs: build-tauri
if: github.event_name == 'workflow_dispatch' && success()
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20.x'
- name: Update version files
run: |
cd packages/editor-app
npm version ${{ github.event.inputs.version }} --no-git-tag-version
node scripts/sync-version.js
- name: Create Pull Request
uses: peter-evans/create-pull-request@v6
with:
token: ${{ secrets.GITHUB_TOKEN }}
commit-message: "chore(editor): bump version to ${{ github.event.inputs.version }}"
branch: release/editor-v${{ github.event.inputs.version }}
delete-branch: true
title: "chore(editor): Release v${{ github.event.inputs.version }}"
body: |
## 🚀 Release v${{ github.event.inputs.version }}
This PR updates the editor version after successful release build.
### Changes
- ✅ Updated `packages/editor-app/package.json` → `${{ github.event.inputs.version }}`
- ✅ Updated `packages/editor-app/src-tauri/tauri.conf.json` → `${{ github.event.inputs.version }}`
### Release
- 📦 [GitHub Release](https://github.com/${{ github.repository }}/releases/tag/editor-v${{ github.event.inputs.version }})
---
*This PR was automatically created by the release workflow.*
labels: |
release
editor
automated pr

9
.gitignore vendored
View File

@@ -69,3 +69,12 @@ docs/.vitepress/dist/
/demo/.idea/
/demo/.vscode/
/demo_wxgame/
# Tauri 构建产物
**/src-tauri/target/
**/src-tauri/WixTools/
**/src-tauri/gen/
# Tauri 捆绑输出
**/src-tauri/target/release/bundle/
**/src-tauri/target/debug/bundle/

49
.prettierignore Normal file
View File

@@ -0,0 +1,49 @@
# 依赖和构建输出
node_modules/
dist/
bin/
build/
coverage/
*.min.js
*.min.css
# 编译输出
**/*.d.ts
tsconfig.tsbuildinfo
# 日志
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# 第三方库
thirdparty/
examples/lawn-mower-demo/
extensions/
# 文档生成
docs/.vitepress/cache/
docs/.vitepress/dist/
docs/api/
# 临时文件
*.tmp
*.bak
*.swp
*~
# 系统文件
.DS_Store
Thumbs.db
# 编辑器
.vscode/
.idea/
# 其他
*.backup
CHANGELOG.md
LICENSE
README.md

14
.prettierrc Normal file
View File

@@ -0,0 +1,14 @@
{
"semi": true,
"singleQuote": true,
"tabWidth": 4,
"useTabs": false,
"trailingComma": "none",
"printWidth": 120,
"arrowParens": "always",
"endOfLine": "lf",
"bracketSpacing": true,
"quoteProps": "as-needed",
"jsxSingleQuote": false,
"proseWrap": "preserve"
}

View File

@@ -95,11 +95,47 @@ function gameLoop(deltaTime: number) {
支持主流游戏引擎和 Web 平台:
- **Cocos Creator** - 内置引擎集成支持,提供[专用调试插件](https://store.cocos.com/app/detail/7823)
- **Laya 引擎** - 完整的生命周期管理
- **Cocos Creator**
- **Laya 引擎**
- **原生 Web** - 浏览器环境直接运行
- **小游戏平台** - 微信、支付宝等小游戏
## ECS Framework Editor
跨平台桌面编辑器,提供可视化开发和调试工具。
### 主要功能
- **场景管理** - 可视化场景层级和实体管理
- **组件检视** - 实时查看和编辑实体组件
- **性能分析** - 内置 Profiler 监控系统性能
- **插件系统** - 可扩展的插件架构
- **远程调试** - 连接运行中的游戏进行实时调试
- **自动更新** - 支持热更新,自动获取最新版本
### 下载
[![Latest Release](https://img.shields.io/github/v/release/esengine/ecs-framework?label=下载最新版本&style=for-the-badge)](https://github.com/esengine/ecs-framework/releases/latest)
支持 Windows、macOS (Intel & Apple Silicon)
### 截图
<img src="screenshots/main_screetshot.png" alt="ECS Framework Editor" width="800">
<details>
<summary>查看更多截图</summary>
**性能分析器**
<img src="screenshots/performance_profiler.png" alt="Performance Profiler" width="600">
**插件管理**
<img src="screenshots/plugin_manager.png" alt="Plugin Manager" width="600">
**设置界面**
<img src="screenshots/settings.png" alt="Settings" width="600">
</details>
## 示例项目

View File

@@ -66,6 +66,7 @@ export default defineConfig({
items: [
{ text: '实体类 (Entity)', link: '/guide/entity' },
{ text: '组件系统 (Component)', link: '/guide/component' },
{ text: '实体查询系统', link: '/guide/entity-query' },
{
text: '系统架构 (System)',
link: '/guide/system',

501
docs/guide/entity-query.md Normal file
View File

@@ -0,0 +1,501 @@
# 实体查询系统
实体查询是 ECS 架构的核心功能之一。本指南将介绍如何使用 Matcher 和 QuerySystem 来查询和筛选实体。
## 核心概念
### Matcher - 查询条件描述符
Matcher 是一个链式 API,用于描述实体查询条件。它本身不执行查询,而是作为条件传递给 EntitySystem 或 QuerySystem。
### QuerySystem - 查询执行引擎
QuerySystem 负责实际执行查询,内部使用响应式查询机制自动优化性能。
## 在 EntitySystem 中使用 Matcher
这是最常见的使用方式。EntitySystem 通过 Matcher 自动筛选和处理符合条件的实体。
### 基础用法
```typescript
import { EntitySystem, Matcher, Entity, Component } from '@esengine/ecs-framework';
class PositionComponent extends Component {
public x: number = 0;
public y: number = 0;
}
class VelocityComponent extends Component {
public vx: number = 0;
public vy: number = 0;
}
class MovementSystem extends EntitySystem {
constructor() {
// 方式1: 使用 Matcher.empty().all()
super(Matcher.empty().all(PositionComponent, VelocityComponent));
// 方式2: 直接使用 Matcher.all() (等价)
// super(Matcher.all(PositionComponent, VelocityComponent));
}
protected process(entities: readonly Entity[]): void {
for (const entity of entities) {
const pos = entity.getComponent(PositionComponent)!;
const vel = entity.getComponent(VelocityComponent)!;
pos.x += vel.vx;
pos.y += vel.vy;
}
}
}
// 添加到场景
scene.addEntityProcessor(new MovementSystem());
```
### Matcher 链式 API
#### all() - 必须包含所有组件
```typescript
class HealthSystem extends EntitySystem {
constructor() {
// 实体必须同时拥有 Health 和 Position 组件
super(Matcher.empty().all(HealthComponent, PositionComponent));
}
protected process(entities: readonly Entity[]): void {
// 只处理同时拥有两个组件的实体
}
}
```
#### any() - 至少包含一个组件
```typescript
class DamageableSystem extends EntitySystem {
constructor() {
// 实体至少拥有 Health 或 Shield 其中之一
super(Matcher.any(HealthComponent, ShieldComponent));
}
protected process(entities: readonly Entity[]): void {
// 处理拥有生命值或护盾的实体
}
}
```
#### none() - 不能包含指定组件
```typescript
class AliveEntitySystem extends EntitySystem {
constructor() {
// 实体不能拥有 DeadTag 组件
super(Matcher.all(HealthComponent).none(DeadTag));
}
protected process(entities: readonly Entity[]): void {
// 只处理活着的实体
}
}
```
#### 组合条件
```typescript
class CombatSystem extends EntitySystem {
constructor() {
super(
Matcher.empty()
.all(PositionComponent, HealthComponent) // 必须有位置和生命
.any(WeaponComponent, MagicComponent) // 至少有武器或魔法
.none(DeadTag, FrozenTag) // 不能是死亡或冰冻状态
);
}
protected process(entities: readonly Entity[]): void {
// 处理可以战斗的活着的实体
}
}
```
### 按标签查询
```typescript
class PlayerSystem extends EntitySystem {
constructor() {
// 查询特定标签的实体
super(Matcher.empty().withTag(Tags.PLAYER));
}
protected process(entities: readonly Entity[]): void {
// 只处理玩家实体
}
}
```
### 按名称查询
```typescript
class BossSystem extends EntitySystem {
constructor() {
// 查询特定名称的实体
super(Matcher.empty().withName('Boss'));
}
protected process(entities: readonly Entity[]): void {
// 只处理名为 'Boss' 的实体
}
}
```
## 直接使用 QuerySystem
如果不需要创建系统,可以直接使用 Scene 的 querySystem 进行查询。
### 基础查询方法
```typescript
// 获取场景的查询系统
const querySystem = scene.querySystem;
// 查询拥有所有指定组件的实体
const result1 = querySystem.queryAll(PositionComponent, VelocityComponent);
console.log(`找到 ${result1.count} 个移动实体`);
console.log(`查询耗时: ${result1.executionTime.toFixed(2)}ms`);
// 查询拥有任意指定组件的实体
const result2 = querySystem.queryAny(WeaponComponent, MagicComponent);
console.log(`找到 ${result2.count} 个战斗单位`);
// 查询不包含指定组件的实体
const result3 = querySystem.queryNone(DeadTag);
console.log(`找到 ${result3.count} 个活着的实体`);
```
### 按标签查询
```typescript
const playerResult = querySystem.queryByTag(Tags.PLAYER);
for (const player of playerResult.entities) {
console.log('玩家:', player.name);
}
```
### 按名称查询
```typescript
const bossResult = querySystem.queryByName('Boss');
if (bossResult.count > 0) {
const boss = bossResult.entities[0];
console.log('找到Boss:', boss);
}
```
### 按单个组件查询
```typescript
const healthResult = querySystem.queryByComponent(HealthComponent);
console.log(`${healthResult.count} 个实体拥有生命值`);
```
## 性能优化
### 自动缓存
QuerySystem 内部使用响应式查询自动缓存结果,相同的查询条件会直接使用缓存:
```typescript
// 第一次查询,执行实际查询
const result1 = querySystem.queryAll(PositionComponent);
console.log('fromCache:', result1.fromCache); // false
// 第二次相同查询,使用缓存
const result2 = querySystem.queryAll(PositionComponent);
console.log('fromCache:', result2.fromCache); // true
```
### 实体变化自动更新
当实体添加/移除组件时,查询缓存会自动更新:
```typescript
// 查询拥有武器的实体
const before = querySystem.queryAll(WeaponComponent);
console.log('之前:', before.count); // 假设为 5
// 给实体添加武器
const enemy = scene.createEntity('Enemy');
enemy.addComponent(new WeaponComponent());
// 再次查询,自动包含新实体
const after = querySystem.queryAll(WeaponComponent);
console.log('之后:', after.count); // 现在是 6
```
### 查询性能统计
```typescript
const stats = querySystem.getStats();
console.log('总查询次数:', stats.queryStats.totalQueries);
console.log('缓存命中率:', stats.queryStats.cacheHitRate);
console.log('缓存大小:', stats.cacheStats.size);
```
## 实际应用场景
### 场景1: 物理系统
```typescript
class PhysicsSystem extends EntitySystem {
constructor() {
super(Matcher.empty().all(TransformComponent, RigidbodyComponent));
}
protected process(entities: readonly Entity[]): void {
for (const entity of entities) {
const transform = entity.getComponent(TransformComponent)!;
const rigidbody = entity.getComponent(RigidbodyComponent)!;
// 应用重力
rigidbody.velocity.y -= 9.8 * Time.deltaTime;
// 更新位置
transform.position.x += rigidbody.velocity.x * Time.deltaTime;
transform.position.y += rigidbody.velocity.y * Time.deltaTime;
}
}
}
```
### 场景2: 渲染系统
```typescript
class RenderSystem extends EntitySystem {
constructor() {
super(
Matcher.empty()
.all(TransformComponent, SpriteComponent)
.none(InvisibleTag) // 排除不可见实体
);
}
protected process(entities: readonly Entity[]): void {
// 按 z-order 排序
const sorted = entities.slice().sort((a, b) => {
const zA = a.getComponent(TransformComponent)!.z;
const zB = b.getComponent(TransformComponent)!.z;
return zA - zB;
});
// 渲染实体
for (const entity of sorted) {
const transform = entity.getComponent(TransformComponent)!;
const sprite = entity.getComponent(SpriteComponent)!;
renderer.drawSprite(sprite.texture, transform.position);
}
}
}
```
### 场景3: 碰撞检测
```typescript
class CollisionSystem extends EntitySystem {
constructor() {
super(Matcher.empty().all(TransformComponent, ColliderComponent));
}
protected process(entities: readonly Entity[]): void {
// 简单的 O(n²) 碰撞检测
for (let i = 0; i < entities.length; i++) {
for (let j = i + 1; j < entities.length; j++) {
this.checkCollision(entities[i], entities[j]);
}
}
}
private checkCollision(a: Entity, b: Entity): void {
const transA = a.getComponent(TransformComponent)!;
const transB = b.getComponent(TransformComponent)!;
const colliderA = a.getComponent(ColliderComponent)!;
const colliderB = b.getComponent(ColliderComponent)!;
if (this.isOverlapping(transA, colliderA, transB, colliderB)) {
// 触发碰撞事件
scene.eventSystem.emit('collision', { entityA: a, entityB: b });
}
}
private isOverlapping(...args: any[]): boolean {
// 碰撞检测逻辑
return false;
}
}
```
### 场景4: 一次性查询
```typescript
// 在系统外部执行一次性查询
class GameManager {
private scene: Scene;
public countEnemies(): number {
const result = this.scene.querySystem.queryByTag(Tags.ENEMY);
return result.count;
}
public findNearestEnemy(playerPos: Vector2): Entity | null {
const enemies = this.scene.querySystem.queryByTag(Tags.ENEMY);
let nearest: Entity | null = null;
let minDistance = Infinity;
for (const enemy of enemies.entities) {
const transform = enemy.getComponent(TransformComponent);
if (!transform) continue;
const distance = Vector2.distance(playerPos, transform.position);
if (distance < minDistance) {
minDistance = distance;
nearest = enemy;
}
}
return nearest;
}
}
```
## 最佳实践
### 1. 优先使用 EntitySystem
```typescript
// 推荐: 使用 EntitySystem
class GoodSystem extends EntitySystem {
constructor() {
super(Matcher.empty().all(HealthComponent));
}
protected process(entities: readonly Entity[]): void {
// 自动获得符合条件的实体,每帧自动更新
}
}
// 不推荐: 在 update 中手动查询
class BadSystem extends EntitySystem {
constructor() {
super(Matcher.empty());
}
protected process(entities: readonly Entity[]): void {
// 每帧手动查询,浪费性能
const result = this.scene!.querySystem.queryAll(HealthComponent);
for (const entity of result.entities) {
// ...
}
}
}
```
### 2. 合理使用 none() 排除条件
```typescript
// 排除已死亡的敌人
class EnemyAISystem extends EntitySystem {
constructor() {
super(
Matcher.empty()
.all(EnemyTag, AIComponent)
.none(DeadTag) // 不处理死亡的敌人
);
}
}
```
### 3. 使用标签优化查询
```typescript
// 不好: 查询所有实体再过滤
const allEntities = scene.querySystem.getAllEntities();
const players = allEntities.filter(e => e.hasComponent(PlayerTag));
// 好: 直接按标签查询
const players = scene.querySystem.queryByTag(Tags.PLAYER).entities;
```
### 4. 避免过于复杂的查询条件
```typescript
// 不推荐: 过于复杂
super(
Matcher.empty()
.all(A, B, C, D)
.any(E, F, G)
.none(H, I, J)
);
// 推荐: 拆分成多个简单系统
class SystemAB extends EntitySystem {
constructor() {
super(Matcher.empty().all(A, B));
}
}
class SystemCD extends EntitySystem {
constructor() {
super(Matcher.empty().all(C, D));
}
}
```
## 注意事项
### 1. 查询结果是只读的
```typescript
const result = querySystem.queryAll(PositionComponent);
// 不要修改返回的数组
result.entities.push(someEntity); // 错误!
// 如果需要修改,先复制
const mutableArray = [...result.entities];
mutableArray.push(someEntity); // 正确
```
### 2. 组件添加/移除后的查询时机
```typescript
// 创建实体并添加组件
const entity = scene.createEntity('Player');
entity.addComponent(new PositionComponent());
// 立即查询可能获取到新实体
const result = scene.querySystem.queryAll(PositionComponent);
// result.entities 包含新创建的实体
```
### 3. Matcher 是不可变的
```typescript
const matcher = Matcher.empty().all(PositionComponent);
// 链式调用返回新的 Matcher 实例
const matcher2 = matcher.any(VelocityComponent);
// matcher 本身不变
console.log(matcher === matcher2); // false
```
## 相关 API
- [Matcher](../api/classes/Matcher.md) - 查询条件描述符 API 参考
- [QuerySystem](../api/classes/QuerySystem.md) - 查询系统 API 参考
- [EntitySystem](../api/classes/EntitySystem.md) - 实体系统 API 参考
- [Entity](../api/classes/Entity.md) - 实体 API 参考

2702
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -55,7 +55,11 @@
"docs:api": "typedoc",
"docs:api:watch": "typedoc --watch",
"update:worker-demo": "npm run build:core && cd examples/worker-system-demo && npm run build && cd ../.. && npm run copy:worker-demo",
"copy:worker-demo": "node scripts/update-worker-demo.js"
"copy:worker-demo": "node scripts/update-worker-demo.js",
"format": "prettier --write \"packages/**/src/**/*.{ts,tsx,js,jsx}\"",
"format:check": "prettier --check \"packages/**/src/**/*.{ts,tsx,js,jsx}\"",
"lint": "eslint \"packages/**/src/**/*.{ts,tsx,js,jsx}\"",
"lint:fix": "eslint \"packages/**/src/**/*.{ts,tsx,js,jsx}\" --fix"
},
"author": "yhh",
"license": "MIT",
@@ -66,9 +70,13 @@
"@rollup/plugin-terser": "^0.4.4",
"@types/jest": "^29.5.14",
"@types/node": "^20.19.0",
"@typescript-eslint/eslint-plugin": "^8.46.1",
"@typescript-eslint/parser": "^8.46.1",
"eslint": "^9.37.0",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"lerna": "^8.1.8",
"prettier": "^3.6.2",
"rimraf": "^5.0.0",
"rollup": "^4.42.0",
"rollup-plugin-dts": "^6.2.1",

View File

@@ -1,6 +1,6 @@
{
"name": "@esengine/ecs-framework",
"version": "2.2.3",
"version": "2.2.5",
"description": "用于Laya、Cocos Creator等JavaScript游戏引擎的高性能ECS框架",
"main": "bin/index.js",
"types": "bin/index.d.ts",

View File

@@ -13,6 +13,8 @@ import { ServiceContainer } from './Core/ServiceContainer';
import { PluginManager } from './Core/PluginManager';
import { IPlugin } from './Core/Plugin';
import { WorldManager } from './ECS/WorldManager';
import { DebugConfigService } from './Utils/Debug/DebugConfigService';
import { createInstance } from './Core/DI/Decorators';
/**
* 游戏引擎核心类
@@ -178,7 +180,7 @@ export class Core {
this._serviceContainer.registerInstance(PoolManager, this._poolManager);
// 初始化场景管理器
this._sceneManager = new SceneManager();
this._sceneManager = new SceneManager(this._performanceMonitor);
this._serviceContainer.registerInstance(SceneManager, this._sceneManager);
// 设置场景切换回调,通知调试管理器
@@ -202,14 +204,15 @@ export class Core {
// 初始化调试管理器
if (this._config.debugConfig?.enabled) {
// 使用DI容器创建DebugManager前两个参数从容器解析config手动传入
const config = this._config.debugConfig;
this._debugManager = new DebugManager(
this._serviceContainer.resolve(SceneManager),
this._serviceContainer.resolve(PerformanceMonitor),
config
const configService = new DebugConfigService();
configService.setConfig(this._config.debugConfig);
this._serviceContainer.registerInstance(DebugConfigService, configService);
this._serviceContainer.registerSingleton(DebugManager, (c) =>
createInstance(DebugManager, c)
);
this._serviceContainer.registerInstance(DebugManager, this._debugManager);
this._debugManager = this._serviceContainer.resolve(DebugManager);
}
this.initialize();
@@ -476,13 +479,15 @@ export class Core {
if (this._instance._debugManager) {
this._instance._debugManager.updateConfig(config);
} else {
// 使用DI容器创建DebugManager
this._instance._debugManager = new DebugManager(
this._instance._serviceContainer.resolve(SceneManager),
this._instance._serviceContainer.resolve(PerformanceMonitor),
config
const configService = new DebugConfigService();
configService.setConfig(config);
this._instance._serviceContainer.registerInstance(DebugConfigService, configService);
this._instance._serviceContainer.registerSingleton(DebugManager, (c) =>
createInstance(DebugManager, c)
);
this._instance._serviceContainer.registerInstance(DebugManager, this._instance._debugManager);
this._instance._debugManager = this._instance._serviceContainer.resolve(DebugManager);
}
// 更新Core配置
@@ -659,11 +664,6 @@ export class Core {
// 更新额外的 WorldManager
this._worldManager.updateAll();
// 更新调试管理器基于FPS的数据发送
if (this._debugManager) {
this._debugManager.onFrameUpdate(deltaTime);
}
// 结束性能监控
this._performanceMonitor.endMonitoring('Core.update', frameStartTime);
}

View File

@@ -35,6 +35,12 @@ export interface InjectableMetadata {
* 依赖列表
*/
dependencies: Array<ServiceType<any> | string | symbol>;
/**
* 属性注入映射
* key: 属性名, value: 服务类型
*/
properties?: Map<string | symbol, ServiceType<any>>;
}
/**
@@ -77,10 +83,12 @@ export interface UpdatableMetadata {
*/
export function Injectable(): ClassDecorator {
return function <T extends Function>(target: T): T {
// 标记为可注入
const existing = injectableMetadata.get(target);
injectableMetadata.set(target, {
injectable: true,
dependencies: []
dependencies: [],
properties: existing?.properties
});
return target;
@@ -142,20 +150,7 @@ export function Updatable(priority: number = 0): ClassDecorator {
*
* 标记构造函数参数需要注入的服务类型
*
* @param serviceType 服务类型标识符类、字符串或Symbol
*
* @example
* ```typescript
* @Injectable()
* class MySystem extends EntitySystem {
* constructor(
* @Inject(TimeService) private timeService: TimeService,
* @Inject(PhysicsService) private physics: PhysicsService
* ) {
* super();
* }
* }
* ```
* @param serviceType 服务类型标识符
*/
export function Inject(serviceType: ServiceType<any> | string | symbol): ParameterDecorator {
return function (target: Object, propertyKey: string | symbol | undefined, parameterIndex: number) {
@@ -171,6 +166,35 @@ export function Inject(serviceType: ServiceType<any> | string | symbol): Paramet
};
}
/**
* @InjectProperty() 装饰器
*
* 通过属性装饰器注入依赖
*
* 注入时机在构造函数执行后、onInitialize() 调用前完成
*
* @param serviceType 服务类型
*/
export function InjectProperty(serviceType: ServiceType<any>): PropertyDecorator {
return function (target: any, propertyKey: string | symbol) {
let metadata = injectableMetadata.get(target.constructor);
if (!metadata) {
metadata = {
injectable: true,
dependencies: []
};
injectableMetadata.set(target.constructor, metadata);
}
if (!metadata.properties) {
metadata.properties = new Map();
}
metadata.properties.set(propertyKey, serviceType);
};
}
/**
* 检查类是否标记为可注入
*
@@ -252,6 +276,29 @@ export function createInstance<T>(
return new constructor(...dependencies);
}
/**
* 为实例注入属性依赖
*
* @param instance 目标实例
* @param container 服务容器
*/
export function injectProperties<T>(instance: T, container: ServiceContainer): void {
const constructor = (instance as any).constructor;
const metadata = getInjectableMetadata(constructor);
if (!metadata?.properties || metadata.properties.size === 0) {
return;
}
for (const [propertyKey, serviceType] of metadata.properties) {
const service = container.resolve(serviceType);
if (service !== null) {
(instance as any)[propertyKey] = service;
}
}
}
/**
* 检查类是否标记为可更新
*

View File

@@ -7,6 +7,7 @@
export {
Injectable,
Inject,
InjectProperty,
Updatable,
isInjectable,
getInjectableMetadata,
@@ -14,6 +15,7 @@ export {
isUpdatable,
getUpdatableMetadata,
createInstance,
injectProperties,
registerInjectable
} from './Decorators';

View File

@@ -70,8 +70,7 @@ export abstract class Component implements IComponent {
* 这是一个生命周期钩子,用于组件的初始化逻辑。
* 虽然保留此方法,但建议将复杂的初始化逻辑放在 System 中处理。
*/
public onAddedToEntity(): void {
}
public onAddedToEntity(): void {}
/**
* 组件从实体移除时的回调
@@ -82,7 +81,5 @@ export abstract class Component implements IComponent {
* 这是一个生命周期钩子,用于组件的清理逻辑。
* 虽然保留此方法,但建议将复杂的清理逻辑放在 System 中处理。
*/
public onRemovedFromEntity(): void {
}
}
public onRemovedFromEntity(): void {}
}

View File

@@ -1,6 +1,6 @@
import { Entity } from '../Entity';
import { ComponentType } from './ComponentStorage';
import { BitMask64Data, BitMask64Utils, ComponentTypeManager } from "../Utils";
import { ComponentType, ComponentRegistry } from './ComponentStorage';
import { BitMask64Data, BitMask64Utils } from "../Utils";
import { BitMaskHashMap } from "../Utils/BitMaskHashMap";
/**
@@ -266,10 +266,18 @@ export class ArchetypeSystem {
/**
* 生成原型ID
* 使用ComponentRegistry确保与Entity.componentMask使用相同的bitIndex
*/
private generateArchetypeId(componentTypes: ComponentType[]): ArchetypeId {
let entityBits = ComponentTypeManager.instance.getEntityBits(componentTypes);
return entityBits.getValue();
let mask = BitMask64Utils.clone(BitMask64Utils.ZERO);
for (const type of componentTypes) {
if (!ComponentRegistry.isRegistered(type)) {
ComponentRegistry.register(type);
}
const bitMask = ComponentRegistry.getBitMask(type);
BitMask64Utils.orInPlace(mask, bitMask);
}
return mask;
}
/**

View File

@@ -5,40 +5,10 @@ import { BitMask64Utils, BitMask64Data } from '../Utils/BigIntCompatibility';
import { createLogger } from '../../Utils/Logger';
import { getComponentTypeName } from '../Decorators';
import { Archetype, ArchetypeSystem } from './ArchetypeSystem';
import { ComponentTypeManager } from "../Utils";
import { ReactiveQuery, ReactiveQueryConfig } from './ReactiveQuery';
import { QueryCondition, QueryConditionType, QueryResult } from './QueryTypes';
/**
* 查询条件类型
*/
export enum QueryConditionType {
/** 必须包含所有指定组件 */
ALL = 'all',
/** 必须包含任意一个指定组件 */
ANY = 'any',
/** 不能包含任何指定组件 */
NONE = 'none'
}
/**
* 查询条件接口
*/
export interface QueryCondition {
type: QueryConditionType;
componentTypes: ComponentType[];
mask: BitMask64Data;
}
/**
* 实体查询结果接口
*/
export interface QueryResult {
entities: readonly Entity[];
count: number;
/** 查询执行时间(毫秒) */
executionTime: number;
/** 是否来自缓存 */
fromCache: boolean;
}
export { QueryCondition, QueryConditionType, QueryResult };
/**
* 实体索引结构
@@ -124,15 +94,16 @@ export class QuerySystem {
/**
* 设置实体列表并重建索引
*
*
* 当实体集合发生大规模变化时调用此方法。
* 系统将重新构建所有索引以确保查询性能。
*
*
* @param entities 新的实体列表
*/
public setEntities(entities: Entity[]): void {
this.entities = entities;
this.clearQueryCache();
this.clearReactiveQueries();
this.rebuildIndexes();
}
@@ -152,12 +123,14 @@ export class QuerySystem {
this.archetypeSystem.addEntity(entity);
// 通知响应式查询
this.notifyReactiveQueriesEntityAdded(entity);
// 只有在非延迟模式下才立即清理缓存
if (!deferCacheClear) {
this.clearQueryCache();
}
// 更新版本号
this._version++;
}
@@ -235,14 +208,24 @@ export class QuerySystem {
public removeEntity(entity: Entity): void {
const index = this.entities.indexOf(entity);
if (index !== -1) {
const componentTypes: ComponentType[] = [];
for (const component of entity.components) {
componentTypes.push(component.constructor as ComponentType);
}
this.entities.splice(index, 1);
this.removeEntityFromIndexes(entity);
this.archetypeSystem.removeEntity(entity);
if (componentTypes.length > 0) {
this.notifyReactiveQueriesEntityRemoved(entity, componentTypes);
} else {
this.notifyReactiveQueriesEntityRemovedFallback(entity);
}
this.clearQueryCache();
// 更新版本号
this._version++;
}
}
@@ -270,6 +253,9 @@ export class QuerySystem {
// 重新添加实体到索引(基于新的组件状态)
this.addEntityToIndexes(entity);
// 通知响应式查询
this.notifyReactiveQueriesEntityChanged(entity);
// 清理查询缓存,因为实体组件状态已改变
this.clearQueryCache();
@@ -357,13 +343,13 @@ export class QuerySystem {
/**
* 查询包含所有指定组件的实体
*
*
* 返回同时包含所有指定组件类型的实体列表。
* 系统会自动选择最高效的查询策略,包括索引查找和缓存机制
*
* 内部使用响应式查询作为智能缓存,自动跟踪实体变化,性能更优
*
* @param componentTypes 要查询的组件类型列表
* @returns 查询结果,包含匹配的实体和性能信息
*
*
* @example
* ```typescript
* // 查询同时具有位置和速度组件的实体
@@ -375,38 +361,20 @@ export class QuerySystem {
const startTime = performance.now();
this.queryStats.totalQueries++;
// 生成缓存
const cacheKey = this.generateCacheKey('all', componentTypes);
// 使用内部响应式查询作为智能缓存
const reactiveQuery = this.getOrCreateReactiveQuery(QueryConditionType.ALL, componentTypes);
// 检查缓存
const cached = this.getFromCache(cacheKey);
if (cached) {
this.queryStats.cacheHits++;
return {
entities: cached,
count: cached.length,
executionTime: performance.now() - startTime,
fromCache: true
};
}
// 从响应式查询获取结果(永远是最新的)
const entities = reactiveQuery.getEntities();
this.queryStats.archetypeHits++;
const archetypeResult = this.archetypeSystem.queryArchetypes(componentTypes, 'AND');
const entities: Entity[] = [];
for (const archetype of archetypeResult.archetypes) {
for (const entity of archetype.entities) {
entities.push(entity);
}
}
this.addToCache(cacheKey, entities);
// 统计为缓存命中(响应式查询本质上是永不过期的智能缓存)
this.queryStats.cacheHits++;
return {
entities,
count: entities.length,
executionTime: performance.now() - startTime,
fromCache: false
fromCache: true
};
}
@@ -436,13 +404,13 @@ export class QuerySystem {
/**
* 查询包含任意指定组件的实体
*
*
* 返回包含任意一个指定组件类型的实体列表。
* 使用集合合并算法确保高效的查询性能
*
* 内部使用响应式查询作为智能缓存,自动跟踪实体变化,性能更优
*
* @param componentTypes 要查询的组件类型列表
* @returns 查询结果,包含匹配的实体和性能信息
*
*
* @example
* ```typescript
* // 查询具有武器或护甲组件的实体
@@ -454,52 +422,32 @@ export class QuerySystem {
const startTime = performance.now();
this.queryStats.totalQueries++;
const cacheKey = this.generateCacheKey('any', componentTypes);
// 使用内部响应式查询作为智能缓存
const reactiveQuery = this.getOrCreateReactiveQuery(QueryConditionType.ANY, componentTypes);
// 检查缓存
const cached = this.getFromCache(cacheKey);
if (cached) {
this.queryStats.cacheHits++;
return {
entities: cached,
count: cached.length,
executionTime: performance.now() - startTime,
fromCache: true
};
}
// 从响应式查询获取结果(永远是最新的)
const entities = reactiveQuery.getEntities();
this.queryStats.archetypeHits++;
const archetypeResult = this.archetypeSystem.queryArchetypes(componentTypes, 'OR');
const entities = this.acquireResultArray();
for (const archetype of archetypeResult.archetypes) {
for (const entity of archetype.entities) {
entities.push(entity);
}
}
const frozenEntities = [...entities];
this.releaseResultArray(entities);
this.addToCache(cacheKey, frozenEntities);
// 统计为缓存命中(响应式查询本质上是永不过期的智能缓存)
this.queryStats.cacheHits++;
return {
entities: frozenEntities,
count: frozenEntities.length,
entities,
count: entities.length,
executionTime: performance.now() - startTime,
fromCache: false
fromCache: true
};
}
/**
* 查询不包含任何指定组件的实体
*
*
* 返回不包含任何指定组件类型的实体列表。
* 适用于排除特定类型实体的查询场景
*
* 内部使用响应式查询作为智能缓存,自动跟踪实体变化,性能更优
*
* @param componentTypes 要排除的组件类型列表
* @returns 查询结果,包含匹配的实体和性能信息
*
*
* @example
* ```typescript
* // 查询不具有AI和玩家控制组件的实体如静态物体
@@ -511,32 +459,20 @@ export class QuerySystem {
const startTime = performance.now();
this.queryStats.totalQueries++;
const cacheKey = this.generateCacheKey('none', componentTypes);
// 使用内部响应式查询作为智能缓存
const reactiveQuery = this.getOrCreateReactiveQuery(QueryConditionType.NONE, componentTypes);
// 检查缓存
const cached = this.getFromCache(cacheKey);
if (cached) {
this.queryStats.cacheHits++;
return {
entities: cached,
count: cached.length,
executionTime: performance.now() - startTime,
fromCache: true
};
}
// 从响应式查询获取结果(永远是最新的)
const entities = reactiveQuery.getEntities();
const mask = this.createComponentMask(componentTypes);
const entities = this.entities.filter(entity =>
BitMask64Utils.hasNone(entity.componentMask, mask)
);
this.addToCache(cacheKey, entities);
// 统计为缓存命中(响应式查询本质上是永不过期的智能缓存)
this.queryStats.cacheHits++;
return {
entities,
count: entities.length,
executionTime: performance.now() - startTime,
fromCache: false
fromCache: true
};
}
@@ -759,6 +695,20 @@ export class QuerySystem {
this.componentMaskCache.clear();
}
/**
* 清除所有响应式查询
*
* 销毁所有响应式查询实例并清理索引
* 通常在setEntities时调用以确保缓存一致性
*/
private clearReactiveQueries(): void {
for (const query of this._reactiveQueries.values()) {
query.dispose();
}
this._reactiveQueries.clear();
this._reactiveQueriesByComponent.clear();
}
/**
* 高效的缓存键生成
*/
@@ -782,11 +732,111 @@ export class QuerySystem {
/**
* 清理查询缓存
*
*
* 用于外部调用清理缓存,通常在批量操作后使用。
* 注意:此方法也会清理响应式查询缓存
*/
public clearCache(): void {
this.clearQueryCache();
this.clearReactiveQueries();
}
/**
* 创建响应式查询
*
* 响应式查询会自动跟踪实体/组件的变化,并通过事件通知订阅者。
* 适合需要实时响应实体变化的场景(如UI更新、AI系统等)。
*
* @param componentTypes 查询的组件类型列表
* @param config 可选的查询配置
* @returns 响应式查询实例
*
* @example
* ```typescript
* const query = querySystem.createReactiveQuery([Position, Velocity], {
* enableBatchMode: true,
* batchDelay: 16
* });
*
* query.subscribe((change) => {
* if (change.type === ReactiveQueryChangeType.ADDED) {
* console.log('新实体:', change.entity);
* }
* });
* ```
*/
public createReactiveQuery(
componentTypes: ComponentType[],
config?: ReactiveQueryConfig
): ReactiveQuery {
if (!componentTypes || componentTypes.length === 0) {
throw new Error('组件类型列表不能为空');
}
const mask = this.createComponentMask(componentTypes);
const condition: QueryCondition = {
type: QueryConditionType.ALL,
componentTypes,
mask
};
const query = new ReactiveQuery(condition, config);
const initialEntities = this.executeTraditionalQuery(
QueryConditionType.ALL,
componentTypes
);
query.initializeWith(initialEntities);
const cacheKey = this.generateCacheKey('all', componentTypes);
this._reactiveQueries.set(cacheKey, query);
for (const type of componentTypes) {
let queries = this._reactiveQueriesByComponent.get(type);
if (!queries) {
queries = new Set();
this._reactiveQueriesByComponent.set(type, queries);
}
queries.add(query);
}
return query;
}
/**
* 销毁响应式查询
*
* 清理查询占用的资源,包括监听器和实体引用。
* 销毁后的查询不应再被使用。
*
* @param query 要销毁的响应式查询
*
* @example
* ```typescript
* const query = querySystem.createReactiveQuery([Position, Velocity]);
* // ... 使用查询
* querySystem.destroyReactiveQuery(query);
* ```
*/
public destroyReactiveQuery(query: ReactiveQuery): void {
if (!query) {
return;
}
const cacheKey = query.id;
this._reactiveQueries.delete(cacheKey);
for (const type of query.condition.componentTypes) {
const queries = this._reactiveQueriesByComponent.get(type);
if (queries) {
queries.delete(query);
if (queries.size === 0) {
this._reactiveQueriesByComponent.delete(type);
}
}
}
query.dispose();
}
/**
@@ -794,6 +844,7 @@ export class QuerySystem {
*
* 根据组件类型列表生成对应的位掩码。
* 使用缓存避免重复计算。
* 注意:必须使用ComponentRegistry来确保与Entity.componentMask使用相同的bitIndex
*
* @param componentTypes 组件类型列表
* @returns 生成的位掩码
@@ -810,10 +861,20 @@ export class QuerySystem {
return cached;
}
let mask = ComponentTypeManager.instance.getEntityBits(componentTypes);
// 使用ComponentRegistry而不是ComponentTypeManager,确保bitIndex一致
let mask = BitMask64Utils.clone(BitMask64Utils.ZERO);
for (const type of componentTypes) {
// 确保组件已注册
if (!ComponentRegistry.isRegistered(type)) {
ComponentRegistry.register(type);
}
const bitMask = ComponentRegistry.getBitMask(type);
BitMask64Utils.orInPlace(mask, bitMask);
}
// 缓存结果
this.componentMaskCache.set(cacheKey, mask.getValue());
return mask.getValue();
this.componentMaskCache.set(cacheKey, mask);
return mask;
}
/**
@@ -882,7 +943,7 @@ export class QuerySystem {
}))
},
cacheStats: {
size: this.queryCache.size,
size: this._reactiveQueries.size,
hitRate: this.queryStats.totalQueries > 0 ?
(this.queryStats.cacheHits / this.queryStats.totalQueries * 100).toFixed(2) + '%' : '0%'
}
@@ -891,12 +952,230 @@ export class QuerySystem {
/**
* 获取实体所属的原型信息
*
*
* @param entity 要查询的实体
*/
public getEntityArchetype(entity: Entity): Archetype | undefined {
return this.archetypeSystem.getEntityArchetype(entity);
}
// ============================================================
// 响应式查询支持(内部智能缓存)
// ============================================================
/**
* 响应式查询集合(内部使用,作为智能缓存)
* 传统查询API(queryAll/queryAny/queryNone)内部自动使用响应式查询优化性能
*/
private _reactiveQueries: Map<string, ReactiveQuery> = new Map();
/**
* 按组件类型索引的响应式查询
* 用于快速定位哪些查询关心某个组件类型
*/
private _reactiveQueriesByComponent: Map<ComponentType, Set<ReactiveQuery>> = new Map();
/**
* 获取或创建内部响应式查询(作为智能缓存)
*
* @param queryType 查询类型
* @param componentTypes 组件类型列表
* @returns 响应式查询实例
*/
private getOrCreateReactiveQuery(
queryType: QueryConditionType,
componentTypes: ComponentType[]
): ReactiveQuery {
// 生成缓存键(与传统缓存键格式一致)
const cacheKey = this.generateCacheKey(queryType, componentTypes);
// 检查是否已存在响应式查询
let reactiveQuery = this._reactiveQueries.get(cacheKey);
if (!reactiveQuery) {
// 创建查询条件
const mask = this.createComponentMask(componentTypes);
const condition: QueryCondition = {
type: queryType,
componentTypes,
mask
};
// 创建响应式查询(禁用批量模式,保持实时性)
reactiveQuery = new ReactiveQuery(condition, {
enableBatchMode: false,
debug: false
});
// 初始化查询结果(使用传统方式获取初始数据)
const initialEntities = this.executeTraditionalQuery(queryType, componentTypes);
reactiveQuery.initializeWith(initialEntities);
// 注册响应式查询
this._reactiveQueries.set(cacheKey, reactiveQuery);
// 为每个组件类型注册索引
for (const type of componentTypes) {
let queries = this._reactiveQueriesByComponent.get(type);
if (!queries) {
queries = new Set();
this._reactiveQueriesByComponent.set(type, queries);
}
queries.add(reactiveQuery);
}
this._logger.debug(`创建内部响应式查询缓存: ${cacheKey}`);
}
return reactiveQuery;
}
/**
* 执行传统查询(内部使用,用于响应式查询初始化)
*
* @param queryType 查询类型
* @param componentTypes 组件类型列表
* @returns 匹配的实体列表
*/
private executeTraditionalQuery(
queryType: QueryConditionType,
componentTypes: ComponentType[]
): Entity[] {
switch (queryType) {
case QueryConditionType.ALL: {
const archetypeResult = this.archetypeSystem.queryArchetypes(componentTypes, 'AND');
const entities: Entity[] = [];
for (const archetype of archetypeResult.archetypes) {
for (const entity of archetype.entities) {
entities.push(entity);
}
}
return entities;
}
case QueryConditionType.ANY: {
const archetypeResult = this.archetypeSystem.queryArchetypes(componentTypes, 'OR');
const entities: Entity[] = [];
for (const archetype of archetypeResult.archetypes) {
for (const entity of archetype.entities) {
entities.push(entity);
}
}
return entities;
}
case QueryConditionType.NONE: {
const mask = this.createComponentMask(componentTypes);
return this.entities.filter(entity =>
BitMask64Utils.hasNone(entity.componentMask, mask)
);
}
default:
return [];
}
}
/**
* 通知所有响应式查询实体已添加
*
* 使用组件类型索引,只通知关心该实体组件的查询
*
* @param entity 添加的实体
*/
private notifyReactiveQueriesEntityAdded(entity: Entity): void {
if (this._reactiveQueries.size === 0) return;
const notified = new Set<ReactiveQuery>();
for (const component of entity.components) {
const componentType = component.constructor as ComponentType;
const queries = this._reactiveQueriesByComponent.get(componentType);
if (queries) {
for (const query of queries) {
if (!notified.has(query)) {
query.notifyEntityAdded(entity);
notified.add(query);
}
}
}
}
}
/**
* 通知响应式查询实体已移除
*
* 使用组件类型索引,只通知关心该实体组件的查询
*
* @param entity 移除的实体
* @param componentTypes 实体移除前的组件类型列表
*/
private notifyReactiveQueriesEntityRemoved(entity: Entity, componentTypes: ComponentType[]): void {
if (this._reactiveQueries.size === 0) return;
const notified = new Set<ReactiveQuery>();
for (const componentType of componentTypes) {
const queries = this._reactiveQueriesByComponent.get(componentType);
if (queries) {
for (const query of queries) {
if (!notified.has(query)) {
query.notifyEntityRemoved(entity);
notified.add(query);
}
}
}
}
}
/**
* 通知响应式查询实体已移除(后备方案)
*
* 当实体已经清空组件时使用,通知所有查询
*
* @param entity 移除的实体
*/
private notifyReactiveQueriesEntityRemovedFallback(entity: Entity): void {
if (this._reactiveQueries.size === 0) return;
for (const query of this._reactiveQueries.values()) {
query.notifyEntityRemoved(entity);
}
}
/**
* 通知响应式查询实体已变化
*
* 使用混合策略:
* 1. 首先通知关心实体当前组件的查询
* 2. 然后通知所有其他查询(包括那些可能因为组件移除而不再匹配的查询)
*
* @param entity 变化的实体
*/
private notifyReactiveQueriesEntityChanged(entity: Entity): void {
if (this._reactiveQueries.size === 0) {
return;
}
const notified = new Set<ReactiveQuery>();
for (const component of entity.components) {
const componentType = component.constructor as ComponentType;
const queries = this._reactiveQueriesByComponent.get(componentType);
if (queries) {
for (const query of queries) {
if (!notified.has(query)) {
query.notifyEntityChanged(entity);
notified.add(query);
}
}
}
}
for (const query of this._reactiveQueries.values()) {
if (!notified.has(query)) {
query.notifyEntityChanged(entity);
}
}
}
}
/**

View File

@@ -0,0 +1,36 @@
import { ComponentType } from './ComponentStorage';
import { BitMask64Data } from '../Utils/BigIntCompatibility';
import { Entity } from '../Entity';
/**
* 查询条件类型
*/
export enum QueryConditionType {
/** 必须包含所有指定组件 */
ALL = 'all',
/** 必须包含任意一个指定组件 */
ANY = 'any',
/** 不能包含任何指定组件 */
NONE = 'none'
}
/**
* 查询条件接口
*/
export interface QueryCondition {
type: QueryConditionType;
componentTypes: ComponentType[];
mask: BitMask64Data;
}
/**
* 实体查询结果接口
*/
export interface QueryResult {
entities: readonly Entity[];
count: number;
/** 查询执行时间(毫秒) */
executionTime: number;
/** 是否来自缓存 */
fromCache: boolean;
}

View File

@@ -0,0 +1,475 @@
import { Entity } from '../Entity';
import { QueryCondition, QueryConditionType } from './QueryTypes';
import { BitMask64Utils } from '../Utils/BigIntCompatibility';
import { createLogger } from '../../Utils/Logger';
const logger = createLogger('ReactiveQuery');
/**
* 响应式查询变化类型
*/
export enum ReactiveQueryChangeType {
/** 实体添加到查询结果 */
ADDED = 'added',
/** 实体从查询结果移除 */
REMOVED = 'removed',
/** 查询结果批量更新 */
BATCH_UPDATE = 'batch_update'
}
/**
* 响应式查询变化事件
*/
export interface ReactiveQueryChange {
/** 变化类型 */
type: ReactiveQueryChangeType;
/** 变化的实体 */
entity?: Entity;
/** 批量变化的实体 */
entities?: readonly Entity[];
/** 新增的实体列表(仅batch_update时有效) */
added?: readonly Entity[];
/** 移除的实体列表(仅batch_update时有效) */
removed?: readonly Entity[];
}
/**
* 响应式查询监听器
*/
export type ReactiveQueryListener = (change: ReactiveQueryChange) => void;
/**
* 响应式查询配置
*/
export interface ReactiveQueryConfig {
/** 是否启用批量模式(减少通知频率) */
enableBatchMode?: boolean;
/** 批量模式的延迟时间(毫秒) */
batchDelay?: number;
/** 调试模式 */
debug?: boolean;
}
/**
* 响应式查询类
*
* 提供基于事件驱动的实体查询机制,只在实体/组件真正变化时触发通知。
*
* 核心特性:
* - Event-driven: 基于事件的增量更新
* - 精确通知: 只通知真正匹配的变化
* - 性能优化: 避免每帧重复查询
*
* @example
* ```typescript
* // 创建响应式查询
* const query = new ReactiveQuery(querySystem, {
* type: QueryConditionType.ALL,
* componentTypes: [Position, Velocity],
* mask: createMask([Position, Velocity])
* });
*
* // 订阅变化
* query.subscribe((change) => {
* if (change.type === ReactiveQueryChangeType.ADDED) {
* console.log('新实体:', change.entity);
* }
* });
*
* // 获取当前结果
* const entities = query.getEntities();
* ```
*/
export class ReactiveQuery {
/** 当前查询结果 */
private _entities: Entity[] = [];
/** 实体ID集合,用于快速查找 */
private _entityIdSet: Set<number> = new Set();
/** 查询条件 */
private readonly _condition: QueryCondition;
/** 监听器列表 */
private _listeners: ReactiveQueryListener[] = [];
/** 配置 */
private readonly _config: ReactiveQueryConfig;
/** 批量变化缓存 */
private _batchChanges: {
added: Entity[];
removed: Entity[];
timer: ReturnType<typeof setTimeout> | null;
};
/** 查询ID(用于调试) */
private readonly _id: string;
/** 是否已激活 */
private _active: boolean = true;
constructor(condition: QueryCondition, config: ReactiveQueryConfig = {}) {
this._condition = condition;
this._config = {
enableBatchMode: config.enableBatchMode ?? true,
batchDelay: config.batchDelay ?? 16, // 默认一帧
debug: config.debug ?? false
};
this._id = this.generateQueryId();
this._batchChanges = {
added: [],
removed: [],
timer: null
};
if (this._config.debug) {
logger.debug(`创建ReactiveQuery: ${this._id}`);
}
}
/**
* 生成查询ID
*/
private generateQueryId(): string {
const typeStr = this._condition.type;
const componentsStr = this._condition.componentTypes
.map(t => t.name)
.sort()
.join(',');
return `${typeStr}:${componentsStr}`;
}
/**
* 订阅查询变化
*
* @param listener 监听器函数
* @returns 取消订阅的函数
*/
public subscribe(listener: ReactiveQueryListener): () => void {
if (!this._active) {
throw new Error(`Cannot subscribe to disposed ReactiveQuery ${this._id}`);
}
if (typeof listener !== 'function') {
throw new TypeError('Listener must be a function');
}
this._listeners.push(listener);
if (this._config.debug) {
logger.debug(`订阅ReactiveQuery: ${this._id}, 监听器数量: ${this._listeners.length}`);
}
return () => {
const index = this._listeners.indexOf(listener);
if (index !== -1) {
this._listeners.splice(index, 1);
}
};
}
/**
* 取消所有订阅
*/
public unsubscribeAll(): void {
this._listeners.length = 0;
}
/**
* 获取当前查询结果
*/
public getEntities(): readonly Entity[] {
return this._entities;
}
/**
* 获取查询结果数量
*/
public get count(): number {
return this._entities.length;
}
/**
* 检查实体是否匹配查询条件
*
* @param entity 要检查的实体
* @returns 是否匹配
*/
public matches(entity: Entity): boolean {
const entityMask = entity.componentMask;
switch (this._condition.type) {
case QueryConditionType.ALL:
return BitMask64Utils.hasAll(entityMask, this._condition.mask);
case QueryConditionType.ANY:
return BitMask64Utils.hasAny(entityMask, this._condition.mask);
case QueryConditionType.NONE:
return BitMask64Utils.hasNone(entityMask, this._condition.mask);
default:
return false;
}
}
/**
* 通知实体添加
*
* 当Scene中添加实体时调用
*
* @param entity 添加的实体
*/
public notifyEntityAdded(entity: Entity): void {
if (!this._active) return;
// 检查实体是否匹配查询条件
if (!this.matches(entity)) {
return;
}
// 检查是否已存在
if (this._entityIdSet.has(entity.id)) {
return;
}
// 添加到结果集
this._entities.push(entity);
this._entityIdSet.add(entity.id);
// 通知监听器
if (this._config.enableBatchMode) {
this.addToBatch('added', entity);
} else {
this.notifyListeners({
type: ReactiveQueryChangeType.ADDED,
entity
});
}
if (this._config.debug) {
logger.debug(`ReactiveQuery ${this._id}: 实体添加 ${entity.name}(${entity.id})`);
}
}
/**
* 通知实体移除
*
* 当Scene中移除实体时调用
*
* @param entity 移除的实体
*/
public notifyEntityRemoved(entity: Entity): void {
if (!this._active) return;
// 检查是否在结果集中
if (!this._entityIdSet.has(entity.id)) {
return;
}
// 从结果集移除
const index = this._entities.indexOf(entity);
if (index !== -1) {
this._entities.splice(index, 1);
}
this._entityIdSet.delete(entity.id);
// 通知监听器
if (this._config.enableBatchMode) {
this.addToBatch('removed', entity);
} else {
this.notifyListeners({
type: ReactiveQueryChangeType.REMOVED,
entity
});
}
if (this._config.debug) {
logger.debug(`ReactiveQuery ${this._id}: 实体移除 ${entity.name}(${entity.id})`);
}
}
/**
* 通知实体组件变化
*
* 当实体的组件发生变化时调用
*
* @param entity 变化的实体
*/
public notifyEntityChanged(entity: Entity): void {
if (!this._active) return;
const wasMatching = this._entityIdSet.has(entity.id);
const isMatching = this.matches(entity);
if (wasMatching && !isMatching) {
// 实体不再匹配,从结果集移除
this.notifyEntityRemoved(entity);
} else if (!wasMatching && isMatching) {
// 实体现在匹配,添加到结果集
this.notifyEntityAdded(entity);
}
}
/**
* 批量初始化查询结果
*
* @param entities 初始实体列表
*/
public initializeWith(entities: readonly Entity[]): void {
// 清空现有结果
this._entities.length = 0;
this._entityIdSet.clear();
// 筛选匹配的实体
for (const entity of entities) {
if (this.matches(entity)) {
this._entities.push(entity);
this._entityIdSet.add(entity.id);
}
}
if (this._config.debug) {
logger.debug(`ReactiveQuery ${this._id}: 初始化 ${this._entities.length} 个实体`);
}
}
/**
* 添加到批量变化缓存
*/
private addToBatch(type: 'added' | 'removed', entity: Entity): void {
if (type === 'added') {
this._batchChanges.added.push(entity);
} else {
this._batchChanges.removed.push(entity);
}
// 启动批量通知定时器
if (this._batchChanges.timer === null) {
this._batchChanges.timer = setTimeout(() => {
this.flushBatchChanges();
}, this._config.batchDelay);
}
}
/**
* 刷新批量变化
*/
private flushBatchChanges(): void {
if (this._batchChanges.added.length === 0 && this._batchChanges.removed.length === 0) {
this._batchChanges.timer = null;
return;
}
const added = [...this._batchChanges.added];
const removed = [...this._batchChanges.removed];
// 清空缓存
this._batchChanges.added.length = 0;
this._batchChanges.removed.length = 0;
this._batchChanges.timer = null;
// 通知监听器
this.notifyListeners({
type: ReactiveQueryChangeType.BATCH_UPDATE,
added,
removed,
entities: this._entities
});
if (this._config.debug) {
logger.debug(`ReactiveQuery ${this._id}: 批量更新 +${added.length} -${removed.length}`);
}
}
/**
* 通知所有监听器
*/
private notifyListeners(change: ReactiveQueryChange): void {
const listeners = [...this._listeners];
for (const listener of listeners) {
try {
listener(change);
} catch (error) {
logger.error(`ReactiveQuery ${this._id}: 监听器执行出错`, error);
}
}
}
/**
* 暂停响应式查询
*
* 暂停后不再响应实体变化,但可以继续获取当前结果
*/
public pause(): void {
this._active = false;
// 清空批量变化缓存
if (this._batchChanges.timer !== null) {
clearTimeout(this._batchChanges.timer);
this._batchChanges.timer = null;
}
this._batchChanges.added.length = 0;
this._batchChanges.removed.length = 0;
}
/**
* 恢复响应式查询
*/
public resume(): void {
this._active = true;
}
/**
* 销毁响应式查询
*
* 释放所有资源,清空监听器和结果集
*/
public dispose(): void {
if (this._batchChanges.timer !== null) {
clearTimeout(this._batchChanges.timer);
this._batchChanges.timer = null;
}
this._batchChanges.added.length = 0;
this._batchChanges.removed.length = 0;
this._active = false;
this.unsubscribeAll();
this._entities.length = 0;
this._entityIdSet.clear();
if (this._config.debug) {
logger.debug(`ReactiveQuery ${this._id}: 已销毁`);
}
}
/**
* 获取查询条件
*/
public get condition(): QueryCondition {
return this._condition;
}
/**
* 获取查询ID
*/
public get id(): string {
return this._id;
}
/**
* 检查是否激活
*/
public get active(): boolean {
return this._active;
}
/**
* 获取监听器数量
*/
public get listenerCount(): number {
return this._listeners.length;
}
}

View File

@@ -75,7 +75,7 @@ export interface SystemMetadata {
* @ECSSystem('Physics', { updateOrder: 10 })
* class PhysicsSystem extends EntitySystem {
* constructor(@Inject(CollisionSystem) private collision: CollisionSystem) {
* super(Matcher.of(Transform, RigidBody));
* super(Matcher.empty().all(Transform, RigidBody));
* }
* }
* ```

View File

@@ -6,6 +6,7 @@ import { ComponentStorageManager } from './Core/ComponentStorage';
import { QuerySystem } from './Core/QuerySystem';
import { TypeSafeEventSystem } from './Core/EventSystem';
import type { ReferenceTracker } from './Core/ReferenceTracker';
import type { ServiceContainer } from '../Core/ServiceContainer';
/**
* 场景接口定义
@@ -67,6 +68,13 @@ export interface IScene {
*/
readonly referenceTracker: ReferenceTracker;
/**
* 服务容器
*
* 场景级别的依赖注入容器,用于管理服务的生命周期。
*/
readonly services: ServiceContainer;
/**
* 获取系统列表
*/
@@ -171,12 +179,4 @@ export interface ISceneConfig {
* 场景名称
*/
name?: string;
/**
* 性能监控器实例(可选)
*
* 如果不提供Scene会自动从Core.services获取全局PerformanceMonitor。
* 提供此参数可以实现场景级别的独立性能监控。
*/
performanceMonitor?: any;
}

View File

@@ -15,13 +15,13 @@ import { IncrementalSerializer, IncrementalSnapshot, IncrementalSerializationOpt
import { ComponentPoolManager } from './Core/ComponentPool';
import { PerformanceMonitor } from '../Utils/PerformanceMonitor';
import { ServiceContainer, type ServiceType } from '../Core/ServiceContainer';
import { createInstance, isInjectable } from '../Core/DI';
import { createInstance, isInjectable, injectProperties } from '../Core/DI';
import { isUpdatable, getUpdatableMetadata } from '../Core/DI/Decorators';
import { createLogger } from '../Utils/Logger';
/**
* 游戏场景默认实现类
*
*
* 实现IScene接口提供场景的基础功能。
* 推荐使用组合而非继承的方式来构建自定义场景。
*/
@@ -97,11 +97,11 @@ export class Scene implements IScene {
private readonly logger: ReturnType<typeof createLogger>;
/**
* 性能监控器
* 性能监控器缓存
*
* 用于监控场景和系统的性能。可以在构造函数中注入如果不提供则从Core获取。
* 用于监控场景和系统的性能。从 ServiceContainer 获取。
*/
private readonly _performanceMonitor: PerformanceMonitor;
private _performanceMonitor: PerformanceMonitor | null = null;
/**
* 场景是否已开始运行
@@ -182,10 +182,6 @@ export class Scene implements IScene {
this._services = new ServiceContainer();
this.logger = createLogger('Scene');
// 从配置获取 PerformanceMonitor如果未提供则创建一个新实例
// Scene 应该是独立的,不依赖于 Core通过构造函数参数明确依赖关系
this._performanceMonitor = config?.performanceMonitor || new PerformanceMonitor();
if (config?.name) {
this.name = config.name;
}
@@ -201,6 +197,19 @@ export class Scene implements IScene {
}
}
/**
* 获取性能监控器
*
* 从 ServiceContainer 获取,如果未注册则创建默认实例(向后兼容)
*/
private get performanceMonitor(): PerformanceMonitor {
if (!this._performanceMonitor) {
this._performanceMonitor = this._services.tryResolve(PerformanceMonitor)
?? new PerformanceMonitor();
}
return this._performanceMonitor;
}
/**
* 初始化场景
*
@@ -527,7 +536,7 @@ export class Scene implements IScene {
* @Injectable()
* class PhysicsSystem extends EntitySystem {
* constructor(@Inject(CollisionSystem) private collision: CollisionSystem) {
* super(Matcher.of(Transform));
* super(Matcher.empty().all(Transform));
* }
* }
* scene.addEntityProcessor(PhysicsSystem);
@@ -547,7 +556,9 @@ export class Scene implements IScene {
constructor = systemTypeOrInstance;
if (this._services.isRegistered(constructor)) {
return this._services.resolve(constructor) as T;
const existingSystem = this._services.resolve(constructor) as T;
this.logger.debug(`System ${constructor.name} already registered, returning existing instance`);
return existingSystem;
}
if (isInjectable(constructor)) {
@@ -560,13 +571,23 @@ export class Scene implements IScene {
constructor = system.constructor;
if (this._services.isRegistered(constructor)) {
return system;
const existingSystem = this._services.resolve(constructor);
if (existingSystem === system) {
this.logger.debug(`System ${constructor.name} instance already registered, returning it`);
return system;
} else {
this.logger.warn(
`Attempting to register a different instance of ${constructor.name}, ` +
`but type is already registered. Returning existing instance.`
);
return existingSystem as T;
}
}
}
system.scene = this;
system.setPerformanceMonitor(this._performanceMonitor);
system.setPerformanceMonitor(this.performanceMonitor);
const metadata = getSystemMetadata(constructor);
if (metadata?.updateOrder !== undefined) {
@@ -578,8 +599,12 @@ export class Scene implements IScene {
this._services.registerInstance(constructor, system);
injectProperties(system, this._services);
system.initialize();
this.logger.debug(`System ${constructor.name} registered and initialized`);
return system;
}
@@ -597,7 +622,7 @@ export class Scene implements IScene {
* @Injectable()
* @ECSSystem('Collision', { updateOrder: 5 })
* class CollisionSystem extends EntitySystem implements IService {
* constructor() { super(Matcher.of(Collider)); }
* constructor() { super(Matcher.empty().all(Collider)); }
* dispose() {}
* }
*
@@ -605,7 +630,7 @@ export class Scene implements IScene {
* @ECSSystem('Physics', { updateOrder: 10 })
* class PhysicsSystem extends EntitySystem implements IService {
* constructor(@Inject(CollisionSystem) private collision: CollisionSystem) {
* super(Matcher.of(Transform, RigidBody));
* super(Matcher.empty().all(Transform, RigidBody));
* }
* dispose() {}
* }

View File

@@ -4,6 +4,7 @@ import { Time } from '../Utils/Time';
import { createLogger } from '../Utils/Logger';
import type { IService } from '../Core/ServiceContainer';
import { World } from './World';
import { PerformanceMonitor } from '../Utils/PerformanceMonitor';
/**
* 单场景管理器
@@ -73,14 +74,20 @@ export class SceneManager implements IService {
*/
private _onSceneChangedCallback?: () => void;
/**
* 性能监控器(从 Core 注入)
*/
private _performanceMonitor: PerformanceMonitor | null = null;
/**
* 默认场景ID
*/
private static readonly DEFAULT_SCENE_ID = '__main__';
constructor() {
constructor(performanceMonitor?: PerformanceMonitor) {
this._defaultWorld = new World({ name: '__default__' });
this._defaultWorld.start();
this._performanceMonitor = performanceMonitor || null;
}
/**
@@ -111,6 +118,11 @@ export class SceneManager implements IService {
// 移除旧场景
this._defaultWorld.removeAllScenes();
// 注册全局 PerformanceMonitor 到 Scene 的 ServiceContainer
if (this._performanceMonitor) {
scene.services.registerInstance(PerformanceMonitor, this._performanceMonitor);
}
// 通过 World 创建新场景
this._defaultWorld.createScene(SceneManager.DEFAULT_SCENE_ID, scene);
this._defaultWorld.setSceneActive(SceneManager.DEFAULT_SCENE_ID, true);

View File

@@ -275,15 +275,38 @@ export class SceneSerializer {
// 将实体添加到场景
for (const entity of entities) {
scene.addEntity(entity);
scene.addEntity(entity, true);
this.addChildrenRecursively(entity, scene);
}
// 统一清理缓存(批量操作完成后)
scene.querySystem.clearCache();
scene.clearSystemEntityCaches();
// 反序列化场景自定义数据
if (serializedScene.sceneData) {
this.deserializeSceneData(serializedScene.sceneData, scene.sceneData);
}
}
/**
* 递归添加实体的所有子实体到场景
*
* 修复反序列化时子实体丢失的问题:
* EntitySerializer.deserialize会提前设置子实体的scene引用
* 导致Entity.addChild的条件判断(!child.scene)跳过scene.addEntity调用。
* 因此需要在SceneSerializer中统一递归添加所有子实体。
*
* @param entity 父实体
* @param scene 目标场景
*/
private static addChildrenRecursively(entity: Entity, scene: IScene): void {
for (const child of entity.children) {
scene.addEntity(child, true); // 延迟缓存清理
this.addChildrenRecursively(child, scene); // 递归处理子实体的子实体
}
}
/**
* 序列化场景自定义数据
*

View File

@@ -36,7 +36,7 @@ interface EventListenerRecord {
* // 传统方式
* class MovementSystem extends EntitySystem {
* constructor() {
* super(Matcher.of(Transform, Velocity));
* super(Matcher.empty().all(Transform, Velocity));
* }
*
* protected process(entities: readonly Entity[]): void {
@@ -51,7 +51,7 @@ interface EventListenerRecord {
* // 类型安全方式
* class MovementSystem extends EntitySystem<[typeof Transform, typeof Velocity]> {
* constructor() {
* super(Matcher.of(Transform, Velocity));
* super(Matcher.empty().all(Transform, Velocity));
* }
*
* protected process(entities: readonly Entity[]): void {
@@ -555,6 +555,7 @@ export abstract class EntitySystem<
try {
this.onBegin();
// 查询实体并存储到帧缓存中
// 响应式查询会自动维护最新的实体列表updateEntityTracking会在检测到变化时invalidate
this._entityCache.frame = this.queryEntities();
entityCount = this._entityCache.frame.length;

View File

@@ -1,101 +0,0 @@
import { Bits } from './Bits';
import { getComponentTypeName } from '../Decorators';
import { ComponentType } from "../../Types";
/**
* 组件类型管理器
* 负责管理组件类型的注册和ID分配
* 支持无限数量的组件类型(通过自动扩展 BitMask
*/
export class ComponentTypeManager {
private static _instance: ComponentTypeManager;
private _componentTypes = new Map<Function, number>();
private _typeNames = new Map<number, string>();
private _nextTypeId = 0;
/**
* 获取单例实例
*/
public static get instance(): ComponentTypeManager {
if (!ComponentTypeManager._instance) {
ComponentTypeManager._instance = new ComponentTypeManager();
}
return ComponentTypeManager._instance;
}
private constructor() {}
/**
* 获取组件类型的ID
* @param componentType 组件类型构造函数
* @returns 组件类型ID
*/
public getTypeId(componentType: ComponentType): number {
let typeId = this._componentTypes.get(componentType);
if (typeId === undefined) {
typeId = this._nextTypeId++;
this._componentTypes.set(componentType, typeId);
this._typeNames.set(typeId, getComponentTypeName(componentType));
}
return typeId;
}
/**
* 获取组件类型名称
* @param typeId 组件类型ID
* @returns 组件类型名称
*/
public getTypeName(typeId: number): string {
return this._typeNames.get(typeId) || 'Unknown';
}
/**
* 创建包含指定组件类型的Bits对象
* @param componentTypes 组件类型构造函数数组
* @returns Bits对象
*/
public createBits(...componentTypes: ComponentType[]): Bits {
const bits = new Bits();
for (const componentType of componentTypes) {
const typeId = this.getTypeId(componentType);
bits.set(typeId);
}
return bits;
}
/**
* 获取实体的组件位掩码
* @param components 组件数组
* @returns Bits对象
*/
public getEntityBits(components: ComponentType[]): Bits {
const bits = new Bits();
for (const component of components) {
const typeId = this.getTypeId(component);
bits.set(typeId);
}
return bits;
}
/**
* 重置管理器(主要用于测试)
*/
public reset(): void {
this._componentTypes.clear();
this._typeNames.clear();
this._nextTypeId = 0;
}
/**
* 获取已注册的组件类型数量
*/
public get registeredTypeCount(): number {
return this._componentTypes.size;
}
}

View File

@@ -4,7 +4,6 @@ export { EntityProcessorList } from './EntityProcessorList';
export { IdentifierPool } from './IdentifierPool';
export { Matcher } from './Matcher';
export { Bits } from './Bits';
export { ComponentTypeManager } from './ComponentTypeManager';
export { BitMask64Utils, BitMask64Data } from './BigIntCompatibility';
export { SparseSet } from './SparseSet';
export { ComponentSparseSet } from './ComponentSparseSet';

View File

@@ -15,4 +15,6 @@ export * from './Core/Storage';
export * from './Core/StorageDecorators';
export * from './Serialization';
export { ReferenceTracker, getSceneByEntityId } from './Core/ReferenceTracker';
export type { EntityRefRecord } from './Core/ReferenceTracker';
export type { EntityRefRecord } from './Core/ReferenceTracker';
export { ReactiveQuery, ReactiveQueryChangeType } from './Core/ReactiveQuery';
export type { ReactiveQueryChange, ReactiveQueryListener, ReactiveQueryConfig } from './Core/ReactiveQuery';

View File

@@ -0,0 +1,359 @@
import type { Core } from '../Core';
import type { ServiceContainer } from '../Core/ServiceContainer';
import { IPlugin } from '../Core/Plugin';
import { createLogger } from '../Utils/Logger';
import type { Scene } from '../ECS/Scene';
import type { IScene } from '../ECS/IScene';
import type { Entity } from '../ECS/Entity';
import type { Component } from '../ECS/Component';
import type { EntitySystem } from '../ECS/Systems/EntitySystem';
import { WorldManager } from '../ECS/WorldManager';
import { Injectable, Inject } from '../Core/DI/Decorators';
import type { IService } from '../Core/ServiceContainer';
import type { PerformanceData } from '../Utils/PerformanceMonitor';
const logger = createLogger('DebugPlugin');
/**
* ECS 调试插件统计信息
*/
export interface ECSDebugStats {
scenes: SceneDebugInfo[];
totalEntities: number;
totalSystems: number;
timestamp: number;
}
/**
* 场景调试信息
*/
export interface SceneDebugInfo {
name: string;
entityCount: number;
systems: SystemDebugInfo[];
entities: EntityDebugInfo[];
}
/**
* 系统调试信息
*/
export interface SystemDebugInfo {
name: string;
enabled: boolean;
updateOrder: number;
entityCount: number;
performance?: {
avgExecutionTime: number;
maxExecutionTime: number;
totalCalls: number;
};
}
/**
* 实体调试信息
*/
export interface EntityDebugInfo {
id: number;
name: string;
enabled: boolean;
tag: number;
componentCount: number;
components: ComponentDebugInfo[];
}
/**
* 组件调试信息
*/
export interface ComponentDebugInfo {
type: string;
data: any;
}
/**
* ECS 调试插件
*
* 提供运行时调试功能:
* - 实时查看实体和组件信息
* - System 执行统计
* - 性能监控
* - 实体查询
*
* @example
* ```typescript
* const core = Core.create();
* const debugPlugin = new DebugPlugin({ autoStart: true, updateInterval: 1000 });
* await core.pluginManager.install(debugPlugin);
*
* // 获取调试信息
* const stats = debugPlugin.getStats();
* console.log('Total entities:', stats.totalEntities);
*
* // 查询实体
* const entities = debugPlugin.queryEntities({ tag: 1 });
* ```
*/
@Injectable()
export class DebugPlugin implements IPlugin, IService {
readonly name = '@esengine/debug-plugin';
readonly version = '1.0.0';
private worldManager: WorldManager | null = null;
private updateInterval: number;
private updateTimer: any = null;
private autoStart: boolean;
/**
* 创建调试插件实例
*
* @param options - 配置选项
*/
constructor(options?: { autoStart?: boolean; updateInterval?: number }) {
this.autoStart = options?.autoStart ?? false;
this.updateInterval = options?.updateInterval ?? 1000;
}
/**
* 安装插件
*/
async install(core: Core, services: ServiceContainer): Promise<void> {
this.worldManager = services.resolve(WorldManager);
logger.info('ECS Debug Plugin installed');
if (this.autoStart) {
this.start();
}
}
/**
* 卸载插件
*/
async uninstall(): Promise<void> {
this.stop();
this.worldManager = null;
logger.info('ECS Debug Plugin uninstalled');
}
/**
* 实现 IService 接口
*/
public dispose(): void {
this.stop();
this.worldManager = null;
}
/**
* 启动调试监控
*/
public start(): void {
if (this.updateTimer) {
logger.warn('Debug monitoring already started');
return;
}
logger.info('Starting debug monitoring');
this.updateTimer = setInterval(() => {
this.logStats();
}, this.updateInterval);
}
/**
* 停止调试监控
*/
public stop(): void {
if (this.updateTimer) {
clearInterval(this.updateTimer);
this.updateTimer = null;
logger.info('Debug monitoring stopped');
}
}
/**
* 获取当前 ECS 统计信息
*/
public getStats(): ECSDebugStats {
if (!this.worldManager) {
throw new Error('Plugin not installed');
}
const scenes: SceneDebugInfo[] = [];
let totalEntities = 0;
let totalSystems = 0;
const worlds = this.worldManager.getAllWorlds();
for (const world of worlds) {
for (const scene of world.getAllScenes()) {
const sceneInfo = this.getSceneInfo(scene);
scenes.push(sceneInfo);
totalEntities += sceneInfo.entityCount;
totalSystems += sceneInfo.systems.length;
}
}
return {
scenes,
totalEntities,
totalSystems,
timestamp: Date.now()
};
}
/**
* 获取场景调试信息
*/
public getSceneInfo(scene: IScene): SceneDebugInfo {
const entities = scene.entities.buffer;
const systems = scene.systems;
return {
name: scene.name,
entityCount: entities.length,
systems: systems.map(sys => this.getSystemInfo(sys)),
entities: entities.map(entity => this.getEntityInfo(entity))
};
}
/**
* 获取系统调试信息
*/
private getSystemInfo(system: EntitySystem): SystemDebugInfo {
const perfStats = system.getPerformanceStats();
return {
name: system.constructor.name,
enabled: system.enabled,
updateOrder: system.updateOrder,
entityCount: system.entities.length,
performance: perfStats ? {
avgExecutionTime: perfStats.averageTime,
maxExecutionTime: perfStats.maxTime,
totalCalls: perfStats.executionCount
} : undefined
};
}
/**
* 获取实体调试信息
*/
public getEntityInfo(entity: Entity): EntityDebugInfo {
const components = entity.components;
return {
id: entity.id,
name: entity.name,
enabled: entity.enabled,
tag: entity.tag,
componentCount: components.length,
components: components.map(comp => this.getComponentInfo(comp))
};
}
/**
* 获取组件调试信息
*/
private getComponentInfo(component: any): ComponentDebugInfo {
const type = component.constructor.name;
const data: any = {};
for (const key of Object.keys(component)) {
if (!key.startsWith('_')) {
const value = component[key];
if (typeof value !== 'function') {
data[key] = value;
}
}
}
return { type, data };
}
/**
* 查询实体
*
* @param filter - 查询过滤器
*/
public queryEntities(filter: {
sceneId?: string;
tag?: number;
name?: string;
hasComponent?: string;
}): EntityDebugInfo[] {
if (!this.worldManager) {
throw new Error('Plugin not installed');
}
const results: EntityDebugInfo[] = [];
const worlds = this.worldManager.getAllWorlds();
for (const world of worlds) {
for (const scene of world.getAllScenes()) {
if (filter.sceneId && scene.name !== filter.sceneId) {
continue;
}
for (const entity of scene.entities.buffer) {
if (filter.tag !== undefined && entity.tag !== filter.tag) {
continue;
}
if (filter.name && !entity.name.includes(filter.name)) {
continue;
}
if (filter.hasComponent) {
const hasComp = entity.components.some(
c => c.constructor.name === filter.hasComponent
);
if (!hasComp) {
continue;
}
}
results.push(this.getEntityInfo(entity));
}
}
}
return results;
}
/**
* 打印统计信息到日志
*/
private logStats(): void {
const stats = this.getStats();
logger.info('=== ECS Debug Stats ===');
logger.info(`Total Entities: ${stats.totalEntities}`);
logger.info(`Total Systems: ${stats.totalSystems}`);
logger.info(`Scenes: ${stats.scenes.length}`);
for (const scene of stats.scenes) {
logger.info(`\n[Scene: ${scene.name}]`);
logger.info(` Entities: ${scene.entityCount}`);
logger.info(` Systems: ${scene.systems.length}`);
for (const system of scene.systems) {
const perfStr = system.performance
? ` | Avg: ${system.performance.avgExecutionTime.toFixed(2)}ms, Max: ${system.performance.maxExecutionTime.toFixed(2)}ms`
: '';
logger.info(
` - ${system.name} (${system.enabled ? 'enabled' : 'disabled'}) | Entities: ${system.entityCount}${perfStr}`
);
}
}
logger.info('========================\n');
}
/**
* 导出调试数据为 JSON
*/
public exportJSON(): string {
const stats = this.getStats();
return JSON.stringify(stats, null, 2);
}
}

View File

@@ -0,0 +1 @@
export * from './DebugPlugin';

View File

@@ -0,0 +1,45 @@
import { IECSDebugConfig } from '../../Types';
import { Injectable } from '../../Core/DI/Decorators';
import type { IService } from '../../Core/ServiceContainer';
/**
* 调试配置服务
*
* 管理调试系统的配置信息
*/
@Injectable()
export class DebugConfigService implements IService {
private _config: IECSDebugConfig;
constructor() {
this._config = {
enabled: false,
websocketUrl: '',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
}
public setConfig(config: IECSDebugConfig): void {
this._config = config;
}
public getConfig(): IECSDebugConfig {
return this._config;
}
public isEnabled(): boolean {
return this._config.enabled;
}
dispose(): void {
// 清理资源
}
}

View File

@@ -10,17 +10,20 @@ import { ComponentPoolManager } from '../../ECS/Core/ComponentPool';
import { Pool } from '../../Utils/Pool';
import { getComponentInstanceTypeName, getSystemInstanceTypeName } from '../../ECS/Decorators';
import type { IService } from '../../Core/ServiceContainer';
import type { IUpdatable } from '../../Types/IUpdatable';
import { SceneManager } from '../../ECS/SceneManager';
import { PerformanceMonitor } from '../PerformanceMonitor';
import { Injectable, Inject, Updatable } from '../../Core/DI/Decorators';
import { DebugConfigService } from './DebugConfigService';
/**
* 调试管理器
*
* 整合所有调试数据收集器,负责收集和发送调试数据
*
* 通过构造函数接收SceneManager和PerformanceMonitor避免直接依赖Core实例
*/
export class DebugManager implements IService {
@Injectable()
@Updatable()
export class DebugManager implements IService, IUpdatable {
private config: IECSDebugConfig;
private webSocketManager: WebSocketManager;
private entityCollector: EntityDataCollector;
@@ -35,19 +38,20 @@ export class DebugManager implements IService {
private lastSendTime: number = 0;
private sendInterval: number;
private isRunning: boolean = false;
private originalConsole = {
log: console.log.bind(console),
debug: console.debug.bind(console),
info: console.info.bind(console),
warn: console.warn.bind(console),
error: console.error.bind(console)
};
/**
* 构造调试管理器
* @param sceneManager 场景管理器
* @param performanceMonitor 性能监控器
* @param config 调试配置
*/
constructor(
sceneManager: SceneManager,
performanceMonitor: PerformanceMonitor,
config: IECSDebugConfig
@Inject(SceneManager) sceneManager: SceneManager,
@Inject(PerformanceMonitor) performanceMonitor: PerformanceMonitor,
@Inject(DebugConfigService) configService: DebugConfigService
) {
this.config = config;
this.config = configService.getConfig();
this.sceneManager = sceneManager;
this.performanceMonitor = performanceMonitor;
@@ -60,17 +64,20 @@ export class DebugManager implements IService {
// 初始化WebSocket管理器
this.webSocketManager = new WebSocketManager(
config.websocketUrl,
config.autoReconnect !== false
this.config.websocketUrl,
this.config.autoReconnect !== false
);
// 设置消息处理回调
this.webSocketManager.setMessageHandler(this.handleMessage.bind(this));
// 计算发送间隔(基于帧率)
const debugFrameRate = config.debugFrameRate || 30;
const debugFrameRate = this.config.debugFrameRate || 30;
this.sendInterval = 1000 / debugFrameRate;
// 拦截 console 日志
this.interceptConsole();
this.start();
}
@@ -94,6 +101,118 @@ export class DebugManager implements IService {
this.webSocketManager.disconnect();
}
/**
* 拦截 console 日志并转发到编辑器
*/
private interceptConsole(): void {
console.log = (...args: unknown[]) => {
this.sendLog('info', this.formatLogMessage(args));
this.originalConsole.log(...args);
};
console.debug = (...args: unknown[]) => {
this.sendLog('debug', this.formatLogMessage(args));
this.originalConsole.debug(...args);
};
console.info = (...args: unknown[]) => {
this.sendLog('info', this.formatLogMessage(args));
this.originalConsole.info(...args);
};
console.warn = (...args: unknown[]) => {
this.sendLog('warn', this.formatLogMessage(args));
this.originalConsole.warn(...args);
};
console.error = (...args: unknown[]) => {
this.sendLog('error', this.formatLogMessage(args));
this.originalConsole.error(...args);
};
}
/**
* 格式化日志消息
*/
private formatLogMessage(args: unknown[]): string {
return args.map(arg => {
if (typeof arg === 'string') return arg;
if (arg instanceof Error) return `${arg.name}: ${arg.message}`;
if (arg === null) return 'null';
if (arg === undefined) return 'undefined';
if (typeof arg === 'object') {
try {
return this.safeStringify(arg, 6);
} catch {
return Object.prototype.toString.call(arg);
}
}
return String(arg);
}).join(' ');
}
/**
* 安全的 JSON 序列化,支持循环引用和深度限制
*/
private safeStringify(obj: any, maxDepth: number = 6): string {
const seen = new WeakSet();
const stringify = (value: any, depth: number): any => {
if (value === null) return null;
if (value === undefined) return undefined;
if (typeof value !== 'object') return value;
if (depth >= maxDepth) {
return '[Max Depth Reached]';
}
if (seen.has(value)) {
return '[Circular]';
}
seen.add(value);
if (Array.isArray(value)) {
const result = value.map(item => stringify(item, depth + 1));
seen.delete(value);
return result;
}
const result: any = {};
for (const key in value) {
if (Object.prototype.hasOwnProperty.call(value, key)) {
result[key] = stringify(value[key], depth + 1);
}
}
seen.delete(value);
return result;
};
return JSON.stringify(stringify(obj, 0));
}
/**
* 发送日志到编辑器
*/
private sendLog(level: string, message: string): void {
if (!this.webSocketManager.getConnectionStatus()) {
return;
}
try {
this.webSocketManager.send({
type: 'log',
data: {
level,
message,
timestamp: new Date().toISOString()
}
});
} catch (error) {
// 静默失败,避免递归日志
}
}
/**
* 更新配置
*/
@@ -116,16 +235,12 @@ export class DebugManager implements IService {
}
}
/**
* 帧更新回调
*/
public onFrameUpdate(deltaTime: number): void {
public update(deltaTime?: number): void {
if (!this.isRunning || !this.config.enabled) return;
this.frameCounter++;
const currentTime = Date.now();
// 基于配置的帧率发送数据
if (currentTime - this.lastSendTime >= this.sendInterval) {
this.sendDebugData();
this.lastSendTime = currentTime;
@@ -213,7 +328,8 @@ export class DebugManager implements IService {
return;
}
const expandedData = this.entityCollector.expandLazyObject(entityId, componentIndex, propertyPath);
const scene = this.sceneManager.currentScene;
const expandedData = this.entityCollector.expandLazyObject(entityId, componentIndex, propertyPath, scene);
this.webSocketManager.send({
type: 'expand_lazy_object_response',
@@ -245,7 +361,8 @@ export class DebugManager implements IService {
return;
}
const properties = this.entityCollector.getComponentProperties(entityId, componentIndex);
const scene = this.sceneManager.currentScene;
const properties = this.entityCollector.getComponentProperties(entityId, componentIndex, scene);
this.webSocketManager.send({
type: 'get_component_properties_response',
@@ -268,7 +385,8 @@ export class DebugManager implements IService {
try {
const { requestId } = message;
const rawEntityList = this.entityCollector.getRawEntityList();
const scene = this.sceneManager.currentScene;
const rawEntityList = this.entityCollector.getRawEntityList(scene);
this.webSocketManager.send({
type: 'get_raw_entity_list_response',
@@ -300,7 +418,8 @@ export class DebugManager implements IService {
return;
}
const entityDetails = this.entityCollector.getEntityDetails(entityId);
const scene = this.sceneManager.currentScene;
const entityDetails = this.entityCollector.getEntityDetails(entityId, scene);
this.webSocketManager.send({
type: 'get_entity_details_response',
@@ -832,5 +951,12 @@ export class DebugManager implements IService {
*/
public dispose(): void {
this.stop();
// 恢复原始 console 方法
console.log = this.originalConsole.log;
console.debug = this.originalConsole.debug;
console.info = this.originalConsole.info;
console.warn = this.originalConsole.warn;
console.error = this.originalConsole.error;
}
}

View File

@@ -1,7 +1,6 @@
import { IEntityDebugData } from '../../Types';
import { Entity } from '../../ECS/Entity';
import { Component } from '../../ECS/Component';
import { ComponentTypeManager } from '../../ECS/Utils/ComponentTypeManager';
import { getComponentInstanceTypeName, getSystemInstanceTypeName } from '../../ECS/Decorators';
import { IScene } from '../../ECS/IScene';
@@ -264,8 +263,7 @@ export class EntityDataCollector {
componentCount: entity.components?.length || 0,
memory: 0
}))
.sort((a: any, b: any) => b.componentCount - a.componentCount)
.slice(0, 10);
.sort((a: any, b: any) => b.componentCount - a.componentCount);
}
@@ -304,7 +302,7 @@ export class EntityDataCollector {
});
if (archetype.entities) {
archetype.entities.slice(0, 5).forEach((entity: any) => {
archetype.entities.forEach((entity: any) => {
topEntities.push({
id: entity.id.toString(),
name: entity.name || `Entity_${entity.id}`,
@@ -353,7 +351,7 @@ export class EntityDataCollector {
});
if (archetype.entities) {
archetype.entities.slice(0, 5).forEach((entity: any) => {
archetype.entities.forEach((entity: any) => {
topEntities.push({
id: entity.id.toString(),
name: entity.name || `Entity_${entity.id}`,
@@ -722,20 +720,7 @@ export class EntityDataCollector {
properties: Record<string, any>;
}> {
return components.map((component: Component) => {
let typeName = getComponentInstanceTypeName(component);
if (!typeName || typeName === 'Object' || typeName === 'Function') {
try {
const typeManager = ComponentTypeManager.instance;
const componentType = component.constructor as any;
const typeId = typeManager.getTypeId(componentType);
typeName = typeManager.getTypeName(typeId);
} catch (error) {
typeName = 'UnknownComponent';
}
}
// 提取实际的组件属性
const typeName = getComponentInstanceTypeName(component);
const properties: Record<string, any> = {};
try {

View File

@@ -4,4 +4,5 @@ export { PerformanceDataCollector } from './PerformanceDataCollector';
export { ComponentDataCollector } from './ComponentDataCollector';
export { SceneDataCollector } from './SceneDataCollector';
export { WebSocketManager } from './WebSocketManager';
export { DebugManager } from './DebugManager';
export { DebugManager } from './DebugManager';
export { DebugConfigService } from './DebugConfigService';

View File

@@ -13,6 +13,9 @@ export { PluginManager } from './Core/PluginManager';
export { PluginState } from './Core/Plugin';
export type { IPlugin, IPluginMetadata } from './Core/Plugin';
// 内置插件
export * from './Plugins';
// 依赖注入
export {
Injectable,

View File

@@ -0,0 +1,668 @@
import { Core } from '../src/Core';
import { Scene } from '../src/ECS/Scene';
import { DebugManager } from '../src/Utils/Debug/DebugManager';
import { DebugConfigService } from '../src/Utils/Debug/DebugConfigService';
import { IECSDebugConfig } from '../src/Types';
import { createLogger } from '../src/Utils/Logger';
const logger = createLogger('DebugManagerTest');
class TestScene extends Scene {
public initializeCalled = false;
public override initialize(): void {
this.initializeCalled = true;
}
public override begin(): void {
}
public override end(): void {
}
}
describe('DebugManager DI Architecture Tests', () => {
let originalConsoleWarn: typeof console.warn;
let originalConsoleError: typeof console.error;
beforeEach(() => {
(Core as any)._instance = null;
originalConsoleWarn = console.warn;
originalConsoleError = console.error;
console.warn = jest.fn();
console.error = jest.fn();
});
afterEach(() => {
console.warn = originalConsoleWarn;
console.error = originalConsoleError;
if (Core.Instance) {
Core.destroy();
}
});
describe('DebugConfigService - Configuration Service', () => {
test('should create with default configuration', () => {
const configService = new DebugConfigService();
const config = configService.getConfig();
expect(config).toBeDefined();
expect(config.enabled).toBe(false);
expect(config.websocketUrl).toBe('');
expect(config.debugFrameRate).toBe(30);
expect(config.autoReconnect).toBe(true);
expect(config.channels).toBeDefined();
});
test('should set and get configuration', () => {
const configService = new DebugConfigService();
const newConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 60,
autoReconnect: false,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
configService.setConfig(newConfig);
const retrievedConfig = configService.getConfig();
expect(retrievedConfig).toEqual(newConfig);
expect(retrievedConfig.enabled).toBe(true);
expect(retrievedConfig.websocketUrl).toBe('ws://localhost:9229');
expect(retrievedConfig.debugFrameRate).toBe(60);
});
test('should return correct enabled status', () => {
const configService = new DebugConfigService();
expect(configService.isEnabled()).toBe(false);
configService.setConfig({
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
});
expect(configService.isEnabled()).toBe(true);
});
test('should implement dispose method', () => {
const configService = new DebugConfigService();
expect(() => configService.dispose()).not.toThrow();
});
});
describe('DebugManager - DI Initialization', () => {
test('should initialize DebugManager through DI when debug config is enabled', () => {
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
const core = Core.create({
debug: true,
debugConfig: debugConfig
});
expect((core as any)._debugManager).toBeDefined();
expect((core as any)._debugManager).toBeInstanceOf(DebugManager);
});
test('should not create DebugManager when debug config is disabled', () => {
const core = Core.create({
debug: true,
debugConfig: {
enabled: false,
websocketUrl: '',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
}
});
expect((core as any)._debugManager).toBeUndefined();
});
test('should not create DebugManager when no debug config provided', () => {
const core = Core.create({ debug: true });
expect((core as any)._debugManager).toBeUndefined();
});
test('should register DebugConfigService in ServiceContainer', () => {
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
Core.create({
debug: true,
debugConfig: debugConfig
});
const configService = Core.services.resolve(DebugConfigService);
expect(configService).toBeDefined();
expect(configService).toBeInstanceOf(DebugConfigService);
});
test('should inject all dependencies correctly', () => {
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
const core = Core.create({
debug: true,
debugConfig: debugConfig
});
const debugManager = (core as any)._debugManager as DebugManager;
expect(debugManager).toBeDefined();
const sceneManager = (debugManager as any).sceneManager;
const performanceMonitor = (debugManager as any).performanceMonitor;
const config = (debugManager as any).config;
expect(sceneManager).toBeDefined();
expect(performanceMonitor).toBeDefined();
expect(config).toBeDefined();
expect(config.enabled).toBe(true);
expect(config.websocketUrl).toBe('ws://localhost:9229');
});
});
describe('Core.enableDebug - Runtime Activation', () => {
test('should enable debug at runtime', () => {
const core = Core.create({ debug: true });
expect(Core.isDebugEnabled).toBe(false);
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
Core.enableDebug(debugConfig);
expect(Core.isDebugEnabled).toBe(true);
expect((core as any)._debugManager).toBeDefined();
});
test('should create DebugConfigService when enabling debug at runtime', () => {
Core.create({ debug: true });
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
Core.enableDebug(debugConfig);
const configService = Core.services.resolve(DebugConfigService);
expect(configService).toBeDefined();
expect(configService.getConfig()).toEqual(debugConfig);
});
test('should update existing DebugManager config when already enabled', () => {
const initialConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
Core.create({ debug: true, debugConfig: initialConfig });
const updatedConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:8080',
debugFrameRate: 60,
autoReconnect: false,
channels: {
entities: false,
systems: true,
performance: true,
components: false,
scenes: true
}
};
Core.enableDebug(updatedConfig);
expect(Core.isDebugEnabled).toBe(true);
const debugManager = (Core.Instance as any)._debugManager;
expect(debugManager).toBeDefined();
});
test('should show warning when enabling debug without Core instance', () => {
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
Core.enableDebug(debugConfig);
expect(console.warn).toHaveBeenCalledWith(
expect.stringContaining('Core实例未创建请先调用Core.create()')
);
});
});
describe('Core.disableDebug', () => {
test('should disable debug functionality', () => {
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
Core.create({ debug: true, debugConfig: debugConfig });
expect(Core.isDebugEnabled).toBe(true);
Core.disableDebug();
expect(Core.isDebugEnabled).toBe(false);
expect((Core.Instance as any)._debugManager).toBeUndefined();
});
test('should handle disabling when Core instance does not exist', () => {
expect(() => Core.disableDebug()).not.toThrow();
});
test('should handle disabling when debug was never enabled', () => {
Core.create({ debug: true });
expect(() => Core.disableDebug()).not.toThrow();
});
});
describe('DebugManager - Auto Update Integration', () => {
test('should be registered as updatable service', () => {
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
Core.create({ debug: true, debugConfig: debugConfig });
const serviceContainer = (Core.Instance as any)._serviceContainer;
const updatableCount = serviceContainer.getUpdatableCount();
expect(updatableCount).toBeGreaterThan(0);
});
test('should be updated during Core.update cycle', () => {
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
const core = Core.create({ debug: true, debugConfig: debugConfig });
const debugManager = (core as any)._debugManager as DebugManager;
const updateSpy = jest.spyOn(debugManager, 'update');
Core.update(0.016);
expect(updateSpy).toHaveBeenCalledWith(0.016);
});
});
describe('DebugManager - Scene Integration', () => {
test('should respond to scene changes', () => {
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
const core = Core.create({ debug: true, debugConfig: debugConfig });
const debugManager = (core as any)._debugManager as DebugManager;
const sceneChangeSpy = jest.spyOn(debugManager, 'onSceneChanged');
const testScene = new TestScene();
Core.setScene(testScene);
expect(sceneChangeSpy).toHaveBeenCalled();
});
test('should collect debug data from current scene', () => {
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
Core.create({ debug: true, debugConfig: debugConfig });
const testScene = new TestScene();
Core.setScene(testScene);
const debugData = Core.getDebugData();
expect(debugData).toBeDefined();
expect(debugData).toHaveProperty('timestamp');
expect(debugData).toHaveProperty('frameworkVersion');
expect(debugData).toHaveProperty('currentScene');
});
});
describe('DebugManager - Configuration Management', () => {
test('should use correct debug frame rate', () => {
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 60,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
const core = Core.create({ debug: true, debugConfig: debugConfig });
const debugManager = (core as any)._debugManager as DebugManager;
const sendInterval = (debugManager as any).sendInterval;
expect(sendInterval).toBe(1000 / 60);
});
test('should handle channel configuration correctly', () => {
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: false,
performance: false,
components: true,
scenes: false
}
};
Core.create({ debug: true, debugConfig: debugConfig });
const testScene = new TestScene();
Core.setScene(testScene);
const debugData = Core.getDebugData() as any;
expect(debugData.entities).toBeDefined();
expect(debugData.components).toBeDefined();
expect(debugData.systems).toBeUndefined();
expect(debugData.performance).toBeUndefined();
expect(debugData.scenes).toBeUndefined();
});
});
describe('DebugManager - Lifecycle', () => {
test('should start automatically on creation', () => {
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
const core = Core.create({ debug: true, debugConfig: debugConfig });
const debugManager = (core as any)._debugManager as DebugManager;
const isRunning = (debugManager as any).isRunning;
expect(isRunning).toBe(true);
});
test('should stop when disabling debug', () => {
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
Core.create({ debug: true, debugConfig: debugConfig });
const debugManager = (Core.Instance as any)._debugManager as DebugManager;
const stopSpy = jest.spyOn(debugManager, 'stop');
Core.disableDebug();
expect(stopSpy).toHaveBeenCalled();
});
test('should dispose properly on Core.destroy', () => {
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
Core.create({ debug: true, debugConfig: debugConfig });
const debugManager = (Core.Instance as any)._debugManager as DebugManager;
const stopSpy = jest.spyOn(debugManager, 'stop');
Core.destroy();
expect(stopSpy).toHaveBeenCalled();
});
});
describe('DebugManager - Pure DI Architecture Validation', () => {
test('should resolve all dependencies through ServiceContainer', () => {
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
Core.create({ debug: true, debugConfig: debugConfig });
const debugConfigService = Core.services.resolve(DebugConfigService);
expect(debugConfigService).toBeDefined();
const config = debugConfigService.getConfig();
expect(config).toEqual(debugConfig);
});
test('should not have mixed DI patterns', () => {
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
const core = Core.create({ debug: true, debugConfig: debugConfig });
const debugManager = (core as any)._debugManager as DebugManager;
const sceneManager = (debugManager as any).sceneManager;
const performanceMonitor = (debugManager as any).performanceMonitor;
const config = (debugManager as any).config;
expect(sceneManager).toBeDefined();
expect(performanceMonitor).toBeDefined();
expect(config).toBeDefined();
expect(config.enabled).toBe(true);
});
test('should use factory pattern for registration', () => {
const debugConfig: IECSDebugConfig = {
enabled: true,
websocketUrl: 'ws://localhost:9229',
debugFrameRate: 30,
autoReconnect: true,
channels: {
entities: true,
systems: true,
performance: true,
components: true,
scenes: true
}
};
Core.create({ debug: true, debugConfig: debugConfig });
const debugManager1 = (Core.Instance as any)._debugManager;
const debugManager2 = Core.services.resolve(DebugManager);
expect(debugManager1).toBe(debugManager2);
});
});
});

View File

@@ -0,0 +1,94 @@
import { Scene } from '../../../src/ECS/Scene';
import { Entity } from '../../../src/ECS/Entity';
import { Component } from '../../../src/ECS/Component';
import { EntitySystem } from '../../../src/ECS/Systems/EntitySystem';
import { Matcher } from '../../../src/ECS/Utils/Matcher';
import { ComponentRegistry } from '../../../src/ECS/Core/ComponentStorage';
// 简单的测试组件
class HealthComponent extends Component {
public health: number;
constructor(...args: unknown[]) {
super();
const [health = 100] = args as [number?];
this.health = health;
}
}
// 简单的测试系统
class HealthSystem extends EntitySystem {
public onAddedEntities: Entity[] = [];
constructor() {
super(Matcher.empty().all(HealthComponent));
}
protected override onAdded(entity: Entity): void {
console.log('[HealthSystem] onAdded called:', { id: entity.id, name: entity.name });
this.onAddedEntities.push(entity);
}
}
describe('MinimalSystemInit - 最小化系统初始化测试', () => {
let scene: Scene;
beforeEach(() => {
ComponentRegistry.reset();
scene = new Scene();
});
afterEach(() => {
if (scene) {
scene.end();
}
});
test('先创建实体和组件,再添加系统 - 应该触发onAdded', () => {
console.log('\\n=== Test 1: 先创建实体再添加系统 ===');
// 1. 创建实体并添加组件
const entity = scene.createEntity('TestEntity');
entity.addComponent(new HealthComponent(100));
console.log('[Test] Entity created with HealthComponent');
console.log('[Test] ComponentRegistry registered types:', ComponentRegistry.getRegisteredCount());
// 2. 验证QuerySystem能查询到实体
const queryResult = scene.querySystem.queryAll(HealthComponent);
console.log('[Test] QuerySystem result:', { count: queryResult.count });
// 3. 添加系统
const system = new HealthSystem();
console.log('[Test] Adding system to scene...');
scene.addEntityProcessor(system);
console.log('[Test] System added, onAddedEntities.length =', system.onAddedEntities.length);
// 4. 验证
expect(system.onAddedEntities).toHaveLength(1);
});
test('先添加系统,再创建实体和组件 - 应该在update时触发onAdded', () => {
console.log('\\n=== Test 2: 先添加系统再创建实体 ===');
// 1. 先添加系统
const system = new HealthSystem();
scene.addEntityProcessor(system);
console.log('[Test] System added, onAddedEntities.length =', system.onAddedEntities.length);
// 2. 创建实体并添加组件
const entity = scene.createEntity('TestEntity');
entity.addComponent(new HealthComponent(100));
console.log('[Test] Entity created with HealthComponent');
// 3. 调用update触发系统查询
console.log('[Test] Calling scene.update()...');
scene.update();
console.log('[Test] After update, onAddedEntities.length =', system.onAddedEntities.length);
// 4. 验证
expect(system.onAddedEntities).toHaveLength(1);
});
});

View File

@@ -0,0 +1,160 @@
import { Scene } from '../../../src/ECS/Scene';
import { Entity } from '../../../src/ECS/Entity';
import { Component } from '../../../src/ECS/Component';
import { EntitySystem } from '../../../src/ECS/Systems/EntitySystem';
import { Matcher } from '../../../src/ECS/Utils/Matcher';
import { ComponentRegistry } from '../../../src/ECS/Core/ComponentStorage';
// 测试组件
class PositionComponent extends Component {
public x: number;
public y: number;
constructor(...args: unknown[]) {
super();
const [x = 0, y = 0] = args as [number?, number?];
this.x = x;
this.y = y;
}
}
class VelocityComponent extends Component {
public vx: number;
public vy: number;
constructor(...args: unknown[]) {
super();
const [vx = 0, vy = 0] = args as [number?, number?];
this.vx = vx;
this.vy = vy;
}
}
class HealthComponent extends Component {
public health: number;
constructor(...args: unknown[]) {
super();
const [health = 100] = args as [number?];
this.health = health;
}
}
// 测试系统
class MovementSystem extends EntitySystem {
public onAddedEntities: Entity[] = [];
constructor() {
super(Matcher.empty().all(PositionComponent, VelocityComponent));
}
protected override onAdded(entity: Entity): void {
console.log('[MovementSystem] onAdded:', { id: entity.id, name: entity.name });
this.onAddedEntities.push(entity);
}
}
class HealthSystem extends EntitySystem {
public onAddedEntities: Entity[] = [];
constructor() {
super(Matcher.empty().all(HealthComponent));
}
protected override onAdded(entity: Entity): void {
console.log('[HealthSystem] onAdded:', { id: entity.id, name: entity.name });
this.onAddedEntities.push(entity);
}
}
describe('MultiSystemInit - 多系统初始化测试', () => {
let scene: Scene;
beforeEach(() => {
ComponentRegistry.reset();
scene = new Scene();
});
afterEach(() => {
if (scene) {
scene.end();
}
});
test('多个系统同时响应同一实体 - 复现失败场景', () => {
console.log('\\n=== Test: 多个系统同时响应同一实体 ===');
// 1. 创建实体并添加所有组件
const entity = scene.createEntity('Entity');
entity.addComponent(new PositionComponent(0, 0));
entity.addComponent(new VelocityComponent(1, 1));
entity.addComponent(new HealthComponent(100));
console.log('[Test] Entity created with Position, Velocity, Health');
console.log('[Test] ComponentRegistry registered types:', ComponentRegistry.getRegisteredCount());
// 2. 验证QuerySystem能查询到实体
const movementQuery = scene.querySystem.queryAll(PositionComponent, VelocityComponent);
const healthQuery = scene.querySystem.queryAll(HealthComponent);
console.log('[Test] MovementQuery result:', { count: movementQuery.count });
console.log('[Test] HealthQuery result:', { count: healthQuery.count });
// 3. 添加两个系统
console.log('[Test] Adding MovementSystem...');
const movementSystem = new MovementSystem();
scene.addEntityProcessor(movementSystem);
console.log('[Test] MovementSystem added, onAddedEntities.length =', movementSystem.onAddedEntities.length);
console.log('[Test] Adding HealthSystem...');
const healthSystem = new HealthSystem();
scene.addEntityProcessor(healthSystem);
console.log('[Test] HealthSystem added, onAddedEntities.length =', healthSystem.onAddedEntities.length);
// 4. 验证
console.log('[Test] Final check:');
console.log(' MovementSystem.onAddedEntities.length =', movementSystem.onAddedEntities.length);
console.log(' HealthSystem.onAddedEntities.length =', healthSystem.onAddedEntities.length);
expect(movementSystem.onAddedEntities).toHaveLength(1);
expect(healthSystem.onAddedEntities).toHaveLength(1);
});
test('不同系统匹配不同实体 - 复现失败场景', () => {
console.log('\\n=== Test: 不同系统匹配不同实体 ===');
// 1. 创建两个实体
const movingEntity = scene.createEntity('Moving');
movingEntity.addComponent(new PositionComponent(0, 0));
movingEntity.addComponent(new VelocityComponent(1, 1));
const healthEntity = scene.createEntity('Health');
healthEntity.addComponent(new HealthComponent(100));
console.log('[Test] Two entities created');
// 2. 验证QuerySystem
const movementQuery = scene.querySystem.queryAll(PositionComponent, VelocityComponent);
const healthQuery = scene.querySystem.queryAll(HealthComponent);
console.log('[Test] MovementQuery result:', { count: movementQuery.count });
console.log('[Test] HealthQuery result:', { count: healthQuery.count });
// 3. 添加系统
console.log('[Test] Adding systems...');
const movementSystem = new MovementSystem();
const healthSystem = new HealthSystem();
scene.addEntityProcessor(movementSystem);
scene.addEntityProcessor(healthSystem);
console.log('[Test] Systems added');
console.log(' MovementSystem.onAddedEntities.length =', movementSystem.onAddedEntities.length);
console.log(' HealthSystem.onAddedEntities.length =', healthSystem.onAddedEntities.length);
// 4. 验证
expect(movementSystem.onAddedEntities).toHaveLength(1);
expect(movementSystem.onAddedEntities[0]).toBe(movingEntity);
expect(healthSystem.onAddedEntities).toHaveLength(1);
expect(healthSystem.onAddedEntities[0]).toBe(healthEntity);
});
});

View File

@@ -449,22 +449,24 @@ describe('QuerySystem - 查询系统测试', () => {
expect(parseFloat(stats.cacheStats.hitRate)).toBeLessThanOrEqual(100);
});
test('缓存命中率应该在重复查询时提高', () => {
test('缓存命中率应该在重复查询时保持高命中率', () => {
entities[0].addComponent(new PositionComponent(10, 20));
entities[1].addComponent(new PositionComponent(30, 40));
// 第一次查询(缓存未命中)
// 第一次查询(创建响应式查询缓存)
querySystem.queryAll(PositionComponent);
let stats = querySystem.getStats();
const initialHitRate = parseFloat(stats.cacheStats.hitRate);
// 重复查询应该命中缓存
// 重复查询(应该持续命中响应式查询缓存)
for (let i = 0; i < 10; i++) {
querySystem.queryAll(PositionComponent);
}
stats = querySystem.getStats();
expect(parseFloat(stats.cacheStats.hitRate)).toBeGreaterThan(initialHitRate);
// 响应式查询永远100%命中,这是期望的优化效果
expect(parseFloat(stats.cacheStats.hitRate)).toBeGreaterThanOrEqual(initialHitRate);
expect(parseFloat(stats.cacheStats.hitRate)).toBe(100);
});
test('应该能够清理查询缓存', () => {

View File

@@ -3,7 +3,6 @@ import { Entity } from '../../../src/ECS/Entity';
import { Component } from '../../../src/ECS/Component';
import { EntitySystem } from '../../../src/ECS/Systems/EntitySystem';
import { Matcher } from '../../../src/ECS/Utils/Matcher';
import { ComponentTypeManager } from '../../../src/ECS/Utils/ComponentTypeManager';
/**
* System初始化测试套件
@@ -205,11 +204,16 @@ describe('SystemInitialization - 系统初始化测试', () => {
let scene: Scene;
beforeEach(() => {
ComponentTypeManager.instance.reset();
scene = new Scene();
scene.name = 'InitializationTestScene';
});
afterEach(() => {
if (scene) {
scene.end();
}
});
describe('初始化时序', () => {
test('先添加实体再添加系统 - 系统应该正确初始化', () => {
const player = scene.createEntity('Player');

View File

@@ -3,7 +3,7 @@ import { EntitySystem } from '../../src/ECS/Systems/EntitySystem';
import { Entity } from '../../src/ECS/Entity';
import { Component } from '../../src/ECS/Component';
import { Matcher } from '../../src/ECS/Utils/Matcher';
import { Injectable, Inject } from '../../src/Core/DI';
import { Injectable, Inject, InjectProperty } from '../../src/Core/DI';
import { Core } from '../../src/Core';
import type { IService } from '../../src/Core/ServiceContainer';
import { ECSSystem } from '../../src/ECS/Decorators';
@@ -423,4 +423,170 @@ describe('EntitySystem - 依赖注入测试', () => {
expect(transform.y).toBeCloseTo(0.8, 1);
});
});
describe('属性注入 @InjectProperty', () => {
test('应该支持单个属性注入', () => {
@Injectable()
@ECSSystem('Config')
class GameConfig extends EntitySystem implements IService {
public bulletDamage = 10;
constructor() {
super(Matcher.empty());
}
override dispose() {}
}
@Injectable()
@ECSSystem('Combat')
class CombatSystem extends EntitySystem implements IService {
@InjectProperty(GameConfig)
gameConfig!: GameConfig;
constructor() {
super(Matcher.empty().all(Health));
}
protected override onInitialize(): void {
expect(this.gameConfig).toBeInstanceOf(GameConfig);
expect(this.gameConfig.bulletDamage).toBe(10);
}
override dispose() {}
}
scene.addEntityProcessor(GameConfig);
scene.addEntityProcessor(CombatSystem);
});
test('应该支持多个属性注入', () => {
@Injectable()
@ECSSystem('Time')
class TimeService extends EntitySystem implements IService {
public deltaTime = 0.016;
constructor() {
super(Matcher.empty());
}
override dispose() {}
}
@Injectable()
@ECSSystem('Collision')
class CollisionSystem extends EntitySystem implements IService {
public checkCount = 0;
constructor() {
super(Matcher.empty());
}
override dispose() {}
}
@Injectable()
@ECSSystem('Physics')
class PhysicsSystem extends EntitySystem implements IService {
@InjectProperty(TimeService)
time!: TimeService;
@InjectProperty(CollisionSystem)
collision!: CollisionSystem;
constructor() {
super(Matcher.empty());
}
protected override onInitialize(): void {
expect(this.time).toBeInstanceOf(TimeService);
expect(this.collision).toBeInstanceOf(CollisionSystem);
expect(this.time.deltaTime).toBe(0.016);
}
override dispose() {}
}
scene.registerSystems([TimeService, CollisionSystem, PhysicsSystem]);
});
test('属性注入应该在onInitialize之前完成', () => {
@Injectable()
@ECSSystem('Service')
class TestService extends EntitySystem implements IService {
public value = 42;
constructor() {
super(Matcher.empty());
}
override dispose() {}
}
@Injectable()
@ECSSystem('Consumer')
class ConsumerSystem extends EntitySystem implements IService {
@InjectProperty(TestService)
service!: TestService;
private initializeValue = 0;
constructor() {
super(Matcher.empty());
}
protected override onInitialize(): void {
this.initializeValue = this.service.value;
}
public getInitializeValue(): number {
return this.initializeValue;
}
override dispose() {}
}
scene.addEntityProcessor(TestService);
const consumer = scene.addEntityProcessor(ConsumerSystem);
expect(consumer.getInitializeValue()).toBe(42);
});
test('属性注入可以与构造函数注入混合使用', () => {
@Injectable()
@ECSSystem('A')
class ServiceA extends EntitySystem implements IService {
public valueA = 'A';
constructor() {
super(Matcher.empty());
}
override dispose() {}
}
@Injectable()
@ECSSystem('B')
class ServiceB extends EntitySystem implements IService {
public valueB = 'B';
constructor() {
super(Matcher.empty());
}
override dispose() {}
}
@Injectable()
@ECSSystem('Mixed')
class MixedSystem extends EntitySystem implements IService {
@InjectProperty(ServiceB)
serviceB!: ServiceB;
constructor(@Inject(ServiceA) public serviceA: ServiceA) {
super(Matcher.empty());
}
protected override onInitialize(): void {
expect(this.serviceA).toBeInstanceOf(ServiceA);
expect(this.serviceB).toBeInstanceOf(ServiceB);
expect(this.serviceA.valueA).toBe('A');
expect(this.serviceB.valueB).toBe('B');
}
override dispose() {}
}
scene.registerSystems([ServiceA, ServiceB, MixedSystem]);
});
});
});

View File

@@ -589,25 +589,10 @@ describe('Scene - 场景管理系统测试', () => {
});
});
describe('依赖注入优化', () => {
test('应该支持注入自定义PerformanceMonitor', () => {
const mockPerfMonitor = {
startMeasure: jest.fn(),
endMeasure: jest.fn(),
recordSystemData: jest.fn(),
recordEntityCount: jest.fn(),
recordComponentCount: jest.fn(),
update: jest.fn(),
getSystemData: jest.fn(),
getSystemStats: jest.fn(),
resetSystem: jest.fn(),
reset: jest.fn(),
dispose: jest.fn()
};
describe('性能监控', () => {
test('Scene应该自动创建PerformanceMonitor', () => {
const customScene = new Scene({
name: 'CustomScene',
performanceMonitor: mockPerfMonitor as any
name: 'CustomScene'
});
class TestSystem extends EntitySystem {
@@ -619,13 +604,14 @@ describe('Scene - 场景管理系统测试', () => {
const system = new TestSystem();
customScene.addEntityProcessor(system);
expect(mockPerfMonitor).toBeDefined();
expect(customScene).toBeDefined();
customScene.end();
});
test('未提供PerformanceMonitor时应该从Core获取', () => {
const defaultScene = new Scene({ name: 'DefaultScene' });
test('每个Scene应该有独立的PerformanceMonitor', () => {
const scene1 = new Scene({ name: 'Scene1' });
const scene2 = new Scene({ name: 'Scene2' });
class TestSystem extends EntitySystem {
constructor() {
@@ -633,12 +619,14 @@ describe('Scene - 场景管理系统测试', () => {
}
}
const system = new TestSystem();
defaultScene.addEntityProcessor(system);
scene1.addEntityProcessor(new TestSystem());
scene2.addEntityProcessor(new TestSystem());
expect(defaultScene).toBeDefined();
expect(scene1).toBeDefined();
expect(scene2).toBeDefined();
defaultScene.end();
scene1.end();
scene2.end();
});
});
});

View File

@@ -0,0 +1,117 @@
/**
* 父子实体序列化和反序列化测试
*
* 测试场景序列化和反序列化时父子实体关系的正确性
*/
import { Scene } from '../../../src';
describe('父子实体序列化测试', () => {
let scene: Scene;
beforeEach(() => {
scene = new Scene({ name: 'TestScene' });
});
afterEach(() => {
scene.end();
});
test('应该正确反序列化父子实体层次结构', () => {
// 创建父实体
const parent = scene.createEntity('parent');
parent.tag = 100;
// 创建2个子实体
const child1 = scene.createEntity('child1');
child1.tag = 200;
parent.addChild(child1);
const child2 = scene.createEntity('child2');
child2.tag = 200;
parent.addChild(child2);
// 创建1个顶层实体对照组
const topLevel = scene.createEntity('topLevel');
topLevel.tag = 200;
// 验证序列化前的状态
expect(scene.querySystem.queryAll().entities.length).toBe(4);
expect(scene.findEntitiesByTag(100).length).toBe(1);
expect(scene.findEntitiesByTag(200).length).toBe(3);
// 序列化
const serialized = scene.serialize({ format: 'json' });
// 创建新场景并反序列化
const scene2 = new Scene({ name: 'LoadTestScene' });
scene2.deserialize(serialized as string, {
strategy: 'replace',
preserveIds: true,
});
// 验证所有实体都被正确恢复
const allEntities = scene2.querySystem.queryAll().entities;
expect(allEntities.length).toBe(4);
expect(scene2.findEntitiesByTag(100).length).toBe(1);
expect(scene2.findEntitiesByTag(200).length).toBe(3);
// 验证父子关系正确恢复
const restoredParent = scene2.findEntity('parent');
expect(restoredParent).not.toBeNull();
expect(restoredParent!.children.length).toBe(2);
const restoredChild1 = scene2.findEntity('child1');
const restoredChild2 = scene2.findEntity('child2');
expect(restoredChild1).not.toBeNull();
expect(restoredChild2).not.toBeNull();
expect(restoredChild1!.parent).toBe(restoredParent);
expect(restoredChild2!.parent).toBe(restoredParent);
scene2.end();
});
test('应该正确反序列化多层级实体层次结构', () => {
// 创建多层级实体结构grandparent -> parent -> child
const grandparent = scene.createEntity('grandparent');
grandparent.tag = 1;
const parent = scene.createEntity('parent');
parent.tag = 2;
grandparent.addChild(parent);
const child = scene.createEntity('child');
child.tag = 3;
parent.addChild(child);
expect(scene.querySystem.queryAll().entities.length).toBe(3);
// 序列化
const serialized = scene.serialize({ format: 'json' });
// 创建新场景并反序列化
const scene2 = new Scene({ name: 'LoadTestScene' });
scene2.deserialize(serialized as string, {
strategy: 'replace',
preserveIds: true,
});
// 验证多层级结构正确恢复
expect(scene2.querySystem.queryAll().entities.length).toBe(3);
const restoredGrandparent = scene2.findEntity('grandparent');
const restoredParent = scene2.findEntity('parent');
const restoredChild = scene2.findEntity('child');
expect(restoredGrandparent).not.toBeNull();
expect(restoredParent).not.toBeNull();
expect(restoredChild).not.toBeNull();
expect(restoredParent!.parent).toBe(restoredGrandparent);
expect(restoredChild!.parent).toBe(restoredParent);
expect(restoredGrandparent!.children.length).toBe(1);
expect(restoredParent!.children.length).toBe(1);
scene2.end();
});
});

View File

@@ -0,0 +1,352 @@
import { Core } from '../../src/Core';
import { World } from '../../src/ECS/World';
import { Scene } from '../../src/ECS/Scene';
import { Component } from '../../src/ECS/Component';
import { Matcher } from '../../src/ECS/Utils/Matcher';
import { DebugPlugin } from '../../src/Plugins/DebugPlugin';
import { Injectable } from '../../src/Core/DI';
import { ECSSystem } from '../../src/ECS/Decorators';
import { EntitySystem } from '../../src/ECS/Systems/EntitySystem';
class HealthComponent extends Component {
public health: number = 100;
public maxHealth: number = 100;
}
class PositionComponent extends Component {
public x: number = 0;
public y: number = 0;
}
@Injectable()
@ECSSystem('TestSystem', { updateOrder: 10 })
class TestSystem extends EntitySystem {
constructor() {
super(Matcher.empty().all(PositionComponent));
}
protected override process(entities: readonly import('../../src/ECS/Entity').Entity[]): void {
// 模拟处理逻辑
}
}
describe('DebugPlugin', () => {
let core: Core;
let world: World;
let scene: Scene;
let debugPlugin: DebugPlugin;
beforeEach(() => {
core = Core.create({ debug: false });
world = Core.worldManager.createWorld('test-world', { name: 'test-world' });
scene = world.createScene('test-scene');
world.setSceneActive('test-scene', true);
world.start();
debugPlugin = new DebugPlugin({ autoStart: false, updateInterval: 1000 });
});
afterEach(() => {
debugPlugin.stop();
Core.destroy();
});
describe('基本功能', () => {
it('应该能够安装插件', async () => {
await Core.installPlugin(debugPlugin);
expect(Core.isPluginInstalled('@esengine/debug-plugin')).toBe(true);
});
it('应该能够卸载插件', async () => {
await Core.installPlugin(debugPlugin);
await Core.uninstallPlugin('@esengine/debug-plugin');
expect(Core.isPluginInstalled('@esengine/debug-plugin')).toBe(false);
});
it('应该能够获取插件信息', async () => {
await Core.installPlugin(debugPlugin);
const plugin = Core.getPlugin('@esengine/debug-plugin');
expect(plugin).toBeDefined();
expect(plugin?.name).toBe('@esengine/debug-plugin');
expect(plugin?.version).toBe('1.0.0');
});
});
describe('统计信息', () => {
beforeEach(async () => {
await Core.installPlugin(debugPlugin);
});
it('应该能够获取 ECS 统计信息', () => {
const entity1 = scene.createEntity('Entity1');
entity1.addComponent(new PositionComponent());
const entity2 = scene.createEntity('Entity2');
entity2.addComponent(new HealthComponent());
const stats = debugPlugin.getStats();
expect(stats).toBeDefined();
expect(stats.totalEntities).toBe(2);
expect(stats.scenes.length).toBe(1);
expect(stats.scenes[0].name).toBe('test-scene');
expect(stats.scenes[0].entityCount).toBe(2);
});
it('应该能够获取场景信息', () => {
const entity = scene.createEntity('TestEntity');
entity.addComponent(new PositionComponent());
entity.addComponent(new HealthComponent());
scene.registerSystems([TestSystem]);
const sceneInfo = debugPlugin.getSceneInfo(scene);
expect(sceneInfo.name).toBe('test-scene');
expect(sceneInfo.entityCount).toBe(1);
expect(sceneInfo.systems.length).toBeGreaterThan(0);
expect(sceneInfo.entities.length).toBe(1);
});
it('应该能够获取实体详细信息', () => {
const entity = scene.createEntity('PlayerEntity');
entity.tag = 1;
entity.addComponent(new PositionComponent());
entity.addComponent(new HealthComponent());
const entityInfo = debugPlugin.getEntityInfo(entity);
expect(entityInfo.name).toBe('PlayerEntity');
expect(entityInfo.tag).toBe(1);
expect(entityInfo.enabled).toBe(true);
expect(entityInfo.componentCount).toBe(2);
expect(entityInfo.components.length).toBe(2);
const componentTypes = entityInfo.components.map(c => c.type);
expect(componentTypes).toContain('PositionComponent');
expect(componentTypes).toContain('HealthComponent');
});
it('应该能够获取组件数据', () => {
const entity = scene.createEntity('TestEntity');
const position = new PositionComponent();
position.x = 100;
position.y = 200;
entity.addComponent(position);
const entityInfo = debugPlugin.getEntityInfo(entity);
const positionInfo = entityInfo.components.find(c => c.type === 'PositionComponent');
expect(positionInfo).toBeDefined();
expect(positionInfo?.data.x).toBe(100);
expect(positionInfo?.data.y).toBe(200);
});
});
describe('实体查询', () => {
beforeEach(async () => {
await Core.installPlugin(debugPlugin);
const entity1 = scene.createEntity('Player');
entity1.tag = 1;
entity1.addComponent(new PositionComponent());
entity1.addComponent(new HealthComponent());
const entity2 = scene.createEntity('Enemy');
entity2.tag = 2;
entity2.addComponent(new PositionComponent());
const entity3 = scene.createEntity('Item');
entity3.tag = 3;
entity3.addComponent(new HealthComponent());
});
it('应该能够按 tag 查询实体', () => {
const results = debugPlugin.queryEntities({ tag: 1 });
expect(results.length).toBe(1);
expect(results[0].name).toBe('Player');
expect(results[0].tag).toBe(1);
});
it('应该能够按名称查询实体', () => {
const results = debugPlugin.queryEntities({ name: 'Player' });
expect(results.length).toBe(1);
expect(results[0].name).toBe('Player');
});
it('应该能够按组件查询实体', () => {
const results = debugPlugin.queryEntities({ hasComponent: 'PositionComponent' });
expect(results.length).toBe(2);
expect(results.map(r => r.name)).toContain('Player');
expect(results.map(r => r.name)).toContain('Enemy');
});
it('应该能够组合多个过滤条件', () => {
const results = debugPlugin.queryEntities({
tag: 1,
hasComponent: 'HealthComponent'
});
expect(results.length).toBe(1);
expect(results[0].name).toBe('Player');
});
it('应该在没有匹配时返回空数组', () => {
const results = debugPlugin.queryEntities({ tag: 999 });
expect(results.length).toBe(0);
});
});
describe('监控功能', () => {
beforeEach(async () => {
await Core.installPlugin(debugPlugin);
});
it('应该能够启动监控', () => {
debugPlugin.start();
expect(debugPlugin['updateTimer']).not.toBeNull();
});
it('应该能够停止监控', () => {
debugPlugin.start();
debugPlugin.stop();
expect(debugPlugin['updateTimer']).toBeNull();
});
it('应该防止重复启动', () => {
debugPlugin.start();
const timer1 = debugPlugin['updateTimer'];
debugPlugin.start();
const timer2 = debugPlugin['updateTimer'];
expect(timer1).toBe(timer2);
debugPlugin.stop();
});
it('应该支持自动启动', async () => {
await Core.uninstallPlugin('@esengine/debug-plugin');
const autoPlugin = new DebugPlugin({ autoStart: true, updateInterval: 100 });
await Core.installPlugin(autoPlugin);
expect(autoPlugin['updateTimer']).not.toBeNull();
autoPlugin.stop();
});
});
describe('数据导出', () => {
beforeEach(async () => {
await Core.installPlugin(debugPlugin);
});
it('应该能够导出 JSON 格式数据', () => {
const entity = scene.createEntity('TestEntity');
entity.addComponent(new PositionComponent());
const json = debugPlugin.exportJSON();
expect(json).toBeDefined();
expect(typeof json).toBe('string');
const data = JSON.parse(json);
expect(data.totalEntities).toBe(1);
expect(data.scenes).toBeDefined();
expect(data.timestamp).toBeDefined();
});
it('导出的 JSON 应该包含完整的实体信息', () => {
const entity = scene.createEntity('ComplexEntity');
const position = new PositionComponent();
position.x = 50;
position.y = 75;
entity.addComponent(position);
const json = debugPlugin.exportJSON();
const data = JSON.parse(json);
const entityData = data.scenes[0].entities[0];
expect(entityData.name).toBe('ComplexEntity');
expect(entityData.components[0].data.x).toBe(50);
expect(entityData.components[0].data.y).toBe(75);
});
});
describe('性能监控', () => {
beforeEach(async () => {
await Core.installPlugin(debugPlugin);
scene.registerSystems([TestSystem]);
});
it('应该能够获取 System 性能数据', () => {
scene.createEntity('E1').addComponent(new PositionComponent());
scene.createEntity('E2').addComponent(new PositionComponent());
scene.update();
scene.update();
scene.update();
const sceneInfo = debugPlugin.getSceneInfo(scene);
const systemInfo = sceneInfo.systems.find(s => s.name === 'TestSystem');
expect(systemInfo).toBeDefined();
if (systemInfo?.performance) {
expect(systemInfo.performance.totalCalls).toBeGreaterThan(0);
expect(systemInfo.performance.avgExecutionTime).toBeGreaterThanOrEqual(0);
}
});
it('应该记录 System 的实体数量', () => {
scene.createEntity('E1').addComponent(new PositionComponent());
scene.createEntity('E2').addComponent(new PositionComponent());
scene.createEntity('E3').addComponent(new HealthComponent());
const sceneInfo = debugPlugin.getSceneInfo(scene);
const systemInfo = sceneInfo.systems.find(s => s.name === 'TestSystem');
expect(systemInfo).toBeDefined();
expect(systemInfo?.entityCount).toBe(2);
});
});
describe('错误处理', () => {
it('应该在未安装时抛出错误', () => {
expect(() => {
debugPlugin.getStats();
}).toThrow('Plugin not installed');
});
it('应该在未安装时查询实体抛出错误', () => {
expect(() => {
debugPlugin.queryEntities({ tag: 1 });
}).toThrow('Plugin not installed');
});
it('应该处理空场景', async () => {
await Core.installPlugin(debugPlugin);
const stats = debugPlugin.getStats();
expect(stats.totalEntities).toBe(0);
expect(stats.totalSystems).toBe(0);
});
it('应该处理没有 World 的情况', async () => {
Core.destroy();
Core.create({ debug: false });
const tempPlugin = new DebugPlugin();
await Core.installPlugin(tempPlugin);
const stats = tempPlugin.getStats();
expect(stats.totalEntities).toBe(0);
expect(stats.scenes.length).toBe(0);
});
});
});

View File

@@ -0,0 +1,109 @@
import { describe, it, expect, beforeEach } from '@jest/globals';
import { Scene, Entity, Component, EntitySystem, Matcher, ECSComponent } from '../src';
@ECSComponent('TestTransform')
class TestTransform extends Component {
constructor(public x: number = 0, public y: number = 0) {
super();
}
}
@ECSComponent('TestRenderable')
class TestRenderable extends Component {
constructor(public sprite: string = 'default') {
super();
}
}
class TestRenderSystem extends EntitySystem {
public entitiesFound: Entity[] = [];
constructor() {
super(Matcher.all(TestTransform, TestRenderable));
}
protected override process(entities: readonly Entity[]): void {
this.entitiesFound = Array.from(entities);
console.log(`TestRenderSystem.process: 找到 ${entities.length} 个实体`);
}
protected override onAdded(entity: Entity): void {
console.log(`TestRenderSystem.onAdded: 实体 ${entity.name}(${entity.id}) 被添加`);
}
}
describe('响应式查询调试', () => {
let scene: Scene;
let system: TestRenderSystem;
beforeEach(() => {
scene = new Scene();
system = new TestRenderSystem();
scene.addEntityProcessor(system);
scene.begin();
});
it('应该在实体添加组件后能被System发现', () => {
console.log('\n=== 测试开始 ===');
// 1. 创建实体(此时没有组件)
console.log('\n步骤1: 创建实体');
const entity = scene.createEntity('TestEntity');
console.log(`实体已创建: ${entity.name}(${entity.id})`);
console.log(`QuerySystem中的实体数量: ${scene.querySystem.getAllEntities().length}`);
// 2. 添加组件
console.log('\n步骤2: 添加 TestTransform 组件');
entity.addComponent(new TestTransform(100, 200));
console.log(`实体组件数量: ${entity.components.length}`);
console.log('\n步骤3: 添加 TestRenderable 组件');
entity.addComponent(new TestRenderable('test-sprite'));
console.log(`实体组件数量: ${entity.components.length}`);
// 3. 触发系统更新
console.log('\n步骤4: 更新Scene');
scene.update();
// 4. 检查System是否找到了实体
console.log(`\nSystem找到的实体数量: ${system.entitiesFound.length}`);
if (system.entitiesFound.length > 0) {
console.log(`找到的实体: ${system.entitiesFound.map(e => `${e.name}(${e.id})`).join(', ')}`);
}
// 5. 直接查询QuerySystem
console.log('\n步骤5: 直接查询QuerySystem');
const queryResult = scene.querySystem.queryAll(TestTransform, TestRenderable);
console.log(`QuerySystem.queryAll 返回: ${queryResult.entities.length} 个实体`);
console.log('\n=== 测试结束 ===\n');
expect(system.entitiesFound.length).toBe(1);
expect(system.entitiesFound[0]).toBe(entity);
expect(queryResult.entities.length).toBe(1);
expect(queryResult.entities[0]).toBe(entity);
});
it('应该测试响应式查询的内部状态', () => {
console.log('\n=== 响应式查询内部状态测试 ===');
// 创建实体并添加组件
const entity = scene.createEntity('TestEntity');
entity.addComponent(new TestTransform(100, 200));
entity.addComponent(new TestRenderable('test-sprite'));
// 获取QuerySystem的内部状态
const querySystem = scene.querySystem as any;
console.log(`\n响应式查询数量: ${querySystem._reactiveQueries.size}`);
console.log(`组件索引数量: ${querySystem._reactiveQueriesByComponent.size}`);
// 检查响应式查询
for (const [key, query] of querySystem._reactiveQueries) {
console.log(`\n查询: ${key}`);
console.log(` 实体数量: ${(query as any)._entities.length}`);
console.log(` 实体ID集合: ${Array.from((query as any)._entityIdSet).join(', ')}`);
}
console.log('\n=== 测试结束 ===\n');
});
});

View File

@@ -0,0 +1,89 @@
import { describe, it, expect } from '@jest/globals';
import { Scene, Entity, Component, EntitySystem, Matcher, ECSComponent } from '../src';
@ECSComponent('TestTransform')
class TestTransform extends Component {
constructor(public x: number = 0, public y: number = 0) {
super();
}
}
@ECSComponent('TestRenderable')
class TestRenderable extends Component {
constructor(public sprite: string = 'default') {
super();
}
}
class TestRenderSystem extends EntitySystem {
public entitiesFound: Entity[] = [];
constructor() {
super(Matcher.all(TestTransform, TestRenderable));
}
protected override process(entities: readonly Entity[]): void {
this.entitiesFound = Array.from(entities);
console.log(`TestRenderSystem.process: 找到 ${entities.length} 个实体`);
}
protected override onAdded(entity: Entity): void {
console.log(`TestRenderSystem.onAdded: 实体 ${entity.name}(${entity.id}) 被添加`);
}
}
class TestGameScene extends Scene {
private renderSystem: TestRenderSystem | null = null;
public override initialize(): void {
super.initialize();
console.log('\n=== Scene.initialize() 开始 ===');
// 1. 先添加System这是GameScene的做法
console.log('步骤1: 添加RenderSystem');
this.renderSystem = new TestRenderSystem();
this.addEntityProcessor(this.renderSystem);
// 2. 然后创建实体这是GameScene的做法
console.log('\n步骤2: 创建实体');
const entity = this.createEntity('Player');
console.log(`实体已创建: ${entity.name}(${entity.id})`);
console.log('\n步骤3: 添加组件');
entity.addComponent(new TestTransform(100, 200));
entity.addComponent(new TestRenderable('player-sprite'));
console.log(`实体组件数量: ${entity.components.length}`);
console.log('=== Scene.initialize() 结束 ===\n');
}
public getRenderSystem(): TestRenderSystem | null {
return this.renderSystem;
}
}
describe('响应式查询时序测试模拟GameScene', () => {
it('应该在Scene.initialize()中先添加System再创建实体时正常工作', () => {
console.log('\n\n========== 测试开始 ==========');
const scene = new TestGameScene();
console.log('\n调用scene.initialize()');
scene.initialize();
console.log('\n调用Scene.begin()');
scene.begin();
console.log('\n第一次Scene.update()');
scene.update();
const renderSystem = scene.getRenderSystem();
expect(renderSystem).not.toBeNull();
console.log(`\nRenderSystem找到的实体数量: ${renderSystem!.entitiesFound.length}`);
expect(renderSystem!.entitiesFound.length).toBe(1);
console.log('========== 测试结束 ==========\n\n');
});
});

View File

@@ -60,15 +60,15 @@ afterEach(() => {
const { Core } = require('../src/Core');
const { WorldManager } = require('../src/ECS/WorldManager');
// 重置 Core 和 WorldManager 单例
// 销毁 Core 和 WorldManager 单例
if (Core._instance) {
Core.reset();
Core.destroy();
}
if (WorldManager._instance) {
if (WorldManager._instance.destroy) {
WorldManager._instance.destroy();
}
WorldManager.reset();
WorldManager._instance = null;
}
} catch (error) {
// 忽略清理错误

View File

@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ECS Framework Editor</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

View File

@@ -0,0 +1,37 @@
{
"name": "@esengine/editor-app",
"version": "1.0.3",
"description": "ECS Framework Editor Application - Cross-platform desktop editor",
"type": "module",
"private": true,
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview",
"tauri": "tauri",
"tauri:dev": "tauri dev",
"tauri:build": "tauri build",
"version": "node scripts/sync-version.js && git add src-tauri/tauri.conf.json"
},
"dependencies": {
"@esengine/ecs-framework": "file:../core",
"@esengine/editor-core": "file:../editor-core",
"@tauri-apps/api": "^2.2.0",
"@tauri-apps/plugin-dialog": "^2.4.0",
"@tauri-apps/plugin-shell": "^2.0.0",
"json5": "^2.2.3",
"lucide-react": "^0.545.0",
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
"devDependencies": {
"@tauri-apps/cli": "^2.2.0",
"@tauri-apps/plugin-updater": "^2.9.0",
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react": "^4.3.4",
"sharp": "^0.34.4",
"typescript": "^5.8.3",
"vite": "^6.0.7"
}
}

View File

@@ -0,0 +1,33 @@
#!/usr/bin/env node
/**
* 同步 package.json 和 tauri.conf.json 的版本号
* 在 npm version 命令执行后自动运行
*/
import { readFileSync, writeFileSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// 读取 package.json
const packageJsonPath = join(__dirname, '../package.json');
const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf8'));
const newVersion = packageJson.version;
// 读取 tauri.conf.json
const tauriConfigPath = join(__dirname, '../src-tauri/tauri.conf.json');
const tauriConfig = JSON.parse(readFileSync(tauriConfigPath, 'utf8'));
// 更新 tauri.conf.json 的版本号
const oldVersion = tauriConfig.version;
tauriConfig.version = newVersion;
// 写回文件(保持格式)
writeFileSync(tauriConfigPath, JSON.stringify(tauriConfig, null, 2) + '\n', 'utf8');
console.log(`✓ Version synced: ${oldVersion}${newVersion}`);
console.log(` - package.json: ${newVersion}`);
console.log(` - tauri.conf.json: ${newVersion}`);

5787
packages/editor-app/src-tauri/Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,36 @@
[package]
name = "ecs-editor"
version = "1.0.0"
description = "ECS Framework Editor - Cross-platform desktop editor"
authors = ["yhh"]
edition = "2021"
[lib]
name = "ecs_editor_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
tauri-build = { version = "2.0", features = [] }
[dependencies]
tauri = { version = "2.0", features = ["protocol-asset"] }
tauri-plugin-shell = "2.0"
tauri-plugin-dialog = "2.0"
tauri-plugin-updater = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
glob = "0.3"
tokio = { version = "1", features = ["full"] }
tokio-tungstenite = "0.21"
futures-util = "0.3"
chrono = "0.4"
[profile.dev]
incremental = true
[profile.release]
codegen-units = 1
lto = true
opt-level = "s"
panic = "abort"
strip = true

View File

@@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 915 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 888 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" fill="none" viewBox="0 0 512 512"><rect width="512" height="512" fill="#1E1E1E"/><defs><radialGradient id="glow" cx="50%" cy="50%" r="50%"><stop offset="0%" style="stop-color:#569cd6;stop-opacity:.15"/><stop offset="100%" style="stop-color:#569cd6;stop-opacity:0"/></radialGradient><linearGradient id="cubeGrad1" x1="0%" x2="100%" y1="0%" y2="100%"><stop offset="0%" style="stop-color:#569cd6"/><stop offset="100%" style="stop-color:#4a8bc2"/></linearGradient><linearGradient id="cubeGrad2" x1="0%" x2="0%" y1="0%" y2="100%"><stop offset="0%" style="stop-color:#4ec9b0"/><stop offset="100%" style="stop-color:#3da592"/></linearGradient><filter id="shadow"><feGaussianBlur in="SourceAlpha" stdDeviation="4"/><feOffset dx="2" dy="2" result="offsetblur"/><feComponentTransfer><feFuncA slope=".3" type="linear"/></feComponentTransfer><feMerge><feMergeNode/><feMergeNode in="SourceGraphic"/></feMerge></filter></defs><circle cx="256" cy="256" r="200" fill="url(#glow)"/><g filter="url(#shadow)"><path fill="none" stroke="url(#cubeGrad1)" stroke-width="6" d="M 180 140 L 332 140 L 332 292 L 180 292 Z" opacity=".4"/><path fill="rgba(86, 156, 214, 0.08)" stroke="url(#cubeGrad1)" stroke-linecap="round" stroke-linejoin="round" stroke-width="8" d="M 140 180 L 292 180 L 292 332 L 140 332 Z"/><line x1="140" x2="180" y1="180" y2="140" stroke="url(#cubeGrad1)" stroke-linecap="round" stroke-width="6" opacity=".6"/><line x1="292" x2="332" y1="180" y2="140" stroke="url(#cubeGrad1)" stroke-linecap="round" stroke-width="6" opacity=".6"/><line x1="292" x2="332" y1="332" y2="292" stroke="url(#cubeGrad1)" stroke-linecap="round" stroke-width="6" opacity=".6"/><line x1="140" x2="180" y1="332" y2="292" stroke="url(#cubeGrad1)" stroke-linecap="round" stroke-width="6" opacity=".6"/><circle cx="216" cy="216" r="14" fill="#CE9178" opacity=".95"><animate attributeName="opacity" dur="2s" repeatCount="indefinite" values="0.95;1;0.95"/></circle><circle cx="256" cy="256" r="14" fill="#4EC9B0" opacity=".95"><animate attributeName="opacity" begin="0.3s" dur="2s" repeatCount="indefinite" values="0.95;1;0.95"/></circle><circle cx="296" cy="296" r="14" fill="#569CD6" opacity=".95"><animate attributeName="opacity" begin="0.6s" dur="2s" repeatCount="indefinite" values="0.95;1;0.95"/></circle><line x1="216" x2="256" y1="216" y2="256" stroke="#4EC9B0" stroke-linecap="round" stroke-width="2" opacity=".5"/><line x1="256" x2="296" y1="256" y2="296" stroke="#569CD6" stroke-linecap="round" stroke-width="2" opacity=".5"/></g><g stroke="#4EC9B0" stroke-linecap="round" stroke-width="3" opacity=".3"><line x1="130" x2="130" y1="170" y2="190"/><line x1="130" x2="150" y1="170" y2="170"/><line x1="302" x2="302" y1="342" y2="322"/><line x1="302" x2="282" y1="342" y2="342"/></g></svg>

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 512 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 847 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Some files were not shown because too many files have changed in this diff Show More