Compare commits

..

21 Commits

Author SHA1 Message Date
github-actions[bot]
1e31e9101b chore: release packages (#351)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-12-26 22:32:12 +08:00
yhh
d66c18041e fix(spatial): 修复 GridAOI 可见性更新问题
- 修复 addObserver 时现有观察者无法检测到新实体的问题
- 修复实体远距离移动时观察者可见性未正确更新的问题
- 重构 demos 抽取公共测试工具
2025-12-26 22:23:03 +08:00
yhh
881ffad3bc feat(tools): 添加 CLI 模块管理命令和文档验证 demos
- CLI 新增 list/add/remove 命令管理项目模块
- 创建 demos 包验证模块文档正确性
- 包含 Timer/FSM/Pathfinding/Procgen/Spatial 5个模块的完整测试
2025-12-26 22:09:01 +08:00
YHH
4a16e30794 docs(modules): 添加框架模块文档 (#350)
* docs(modules): 添加框架模块文档

添加以下模块的完整文档:
- FSM (状态机): 状态定义、转换条件、优先级、事件监听
- Timer (定时器): 定时器调度、冷却系统、服务令牌
- Spatial (空间索引): GridSpatialIndex、AOI 兴趣区域管理
- Pathfinding (寻路): A* 算法、网格地图、导航网格、路径平滑
- Procgen (程序化生成): 噪声函数、种子随机数、加权随机

所有文档均基于实际源码 API 编写,包含:
- 快速开始示例
- 完整 API 参考
- 实际使用案例
- 蓝图节点说明
- 最佳实践建议

* docs(modules): 添加 Blueprint 模块文档和所有模块英文版

新增中文文档:
- Blueprint (蓝图可视化脚本): VM、自定义节点、组合系统、触发器

新增英文文档 (docs/en/modules/):
- FSM: State machine API, transitions, ECS integration
- Timer: Timers, cooldowns, service tokens
- Spatial: Grid spatial index, AOI management
- Pathfinding: A*, grid map, NavMesh, path smoothing
- Procgen: Noise functions, seeded random, weighted random
- Blueprint: Visual scripting, custom nodes, composition

所有文档均基于实际源码 API 编写。
2025-12-26 20:02:21 +08:00
YHH
76691cc198 docs: 重构文档结构,添加独立模块区域 (#349)
* docs: 重构文档结构,添加独立模块区域

- 新增 /modules/ 目录用于功能模块文档
- 移动 behavior-tree 从 /guide/ 到 /modules/
- 添加模块总览页面
- 更新导航栏添加"模块"入口
- 更新侧边栏:模块区域独立侧边栏
- 更新 i18n 配置支持新模块

* style(docs): 提高文字对比度
2025-12-26 19:15:08 +08:00
github-actions[bot]
27b9e174eb chore: release packages (#348)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-12-26 18:16:57 +08:00
YHH
ede440d277 chore: changeset for framework package configs (#347)
* chore: add changeset for framework package configs

* fix(docs): 修复 VitePress 配置中的包路径
2025-12-26 18:13:12 +08:00
YHH
5cb83f0743 fix(framework): 补充包配置 peerDeps/repository/keywords (#346)
* fix(framework): 补充 peerDependencies, repository 和 keywords 配置

- fsm: 添加 peerDeps, repository, keywords
- timer: 添加 peerDeps, repository, keywords
- spatial: 添加 peerDeps, repository, keywords
- procgen: 添加 peerDeps, repository, keywords
- pathfinding: 移除重复的 dependencies,添加 repository, keywords

* chore: update pnpm-lock.yaml
2025-12-26 18:05:37 +08:00
yhh
7cbf92b8c7 fix(docs): 修复 tsconfig.json 中的 references 路径 2025-12-26 17:49:40 +08:00
YHH
a049bbe2f5 fix: add private:true to packages not meant for npm (#345)
* fix(ci): run on all PRs with conditional skip

- Remove paths filter from pull_request trigger
- Add check-changes job to detect code changes
- Skip full CI if no code files changed
- Satisfies branch protection while avoiding unnecessary builds

* fix: add private:true to packages not meant for npm

Prevents changesets from trying to publish internal packages:
- engine/* (8 packages)
- rendering/* (8 packages)
- physics/* (2 packages)
- streaming/* (1 package)
- tools/sdk, tools/worker-generator
2025-12-26 17:45:00 +08:00
github-actions[bot]
ec72df7af5 chore: release packages (#343)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: YHH <359807859@qq.com>
2025-12-26 17:18:01 +08:00
YHH
9327c1cef5 fix(ci): run on all PRs with conditional skip (#344)
- Remove paths filter from pull_request trigger
- Add check-changes job to detect code changes
- Skip full CI if no code files changed
- Satisfies branch protection while avoiding unnecessary builds
2025-12-26 17:15:02 +08:00
YHH
da5bf2116a fix(changesets): remove network-protocols and build-config from ignore (#342)
* fix(changesets): remove network-protocols and build-config from ignore

These packages are dependencies of non-ignored packages:
- @esengine/network depends on @esengine/network-protocols
- Multiple packages depend on @esengine/build-config (private, won't publish)

* fix(ci): add .changeset to CI trigger paths
2025-12-26 17:05:41 +08:00
YHH
67e97f89c6 fix(ci): update typedoc path and add workflow_dispatch (#341)
* fix: update Laya examples, add CLI docs, fix changesets workflow

- Update Laya examples to use Laya 3.x Script pattern (@regClass)
- Add CLI tool quick start section to README (npx @esengine/cli init)
- Fix changesets workflow to only build framework packages
- Remove unnecessary Rust/WASM build steps from changesets workflow
- Remove redundant 'pnpm build' from changeset:publish script

* docs: add CLI documentation and update Laya examples

- Add CLI quick start section to getting-started.md (zh/en)
- Update Laya examples to use Laya 3.x Script pattern

* fix(ci): update typedoc path and add workflow_dispatch

- Fix typedoc entry point: packages/core -> packages/framework/core
- Add workflow_dispatch to release-changesets for manual triggering
- Add deeper package paths to trigger on nested packages
2025-12-26 16:52:29 +08:00
YHH
31fd34b221 fix: update Laya examples, add CLI docs, fix changesets workflow (#340)
* fix: update Laya examples, add CLI docs, fix changesets workflow

- Update Laya examples to use Laya 3.x Script pattern (@regClass)
- Add CLI tool quick start section to README (npx @esengine/cli init)
- Fix changesets workflow to only build framework packages
- Remove unnecessary Rust/WASM build steps from changesets workflow
- Remove redundant 'pnpm build' from changeset:publish script

* docs: add CLI documentation and update Laya examples

- Add CLI quick start section to getting-started.md (zh/en)
- Update Laya examples to use Laya 3.x Script pattern
2025-12-26 16:37:37 +08:00
YHH
c4f7a13b74 feat(cli): add CLI tool for adding ECS framework to existing projects (#339)
* feat(cli): add CLI tool for adding ECS framework to existing projects

- Support Cocos Creator 2.x/3.x, LayaAir 3.x, and Node.js platforms
- Auto-detect project type based on directory structure
- Generate ECSManager with full configuration (debug, remote debug, WebSocket URL)
- Auto-install dependencies with npm/yarn/pnpm detection
- Platform-specific decorators and lifecycle methods

* chore: add changeset for @esengine/cli

* fix(ci): fix YAML syntax error in ai-issue-helper workflow

* fix(cli): resolve file system race conditions (CodeQL)

* chore(ci): remove unused and broken workflows

* fix(ci): fix YAML encoding in release.yml
2025-12-26 16:18:59 +08:00
YHH
155411e743 refactor: reorganize package structure and decouple framework packages (#338)
* refactor: reorganize package structure and decouple framework packages

## Package Structure Reorganization
- Reorganized 55 packages into categorized subdirectories:
  - packages/framework/ - Generic framework (Laya/Cocos compatible)
  - packages/engine/ - ESEngine core modules
  - packages/rendering/ - Rendering modules (WASM dependent)
  - packages/physics/ - Physics modules
  - packages/streaming/ - World streaming
  - packages/network-ext/ - Network extensions
  - packages/editor/ - Editor framework and plugins
  - packages/rust/ - Rust WASM engine
  - packages/tools/ - Build tools and SDK

## Framework Package Decoupling
- Decoupled behavior-tree and blueprint packages from ESEngine dependencies
- Created abstracted interfaces (IBTAssetManager, IBehaviorTreeAssetContent)
- ESEngine-specific code moved to esengine/ subpath exports
- Framework packages now usable with Cocos/Laya without ESEngine

## CI Configuration
- Updated CI to only type-check and lint framework packages
- Added type-check:framework and lint:framework scripts

## Breaking Changes
- Package import paths changed due to directory reorganization
- ESEngine integrations now use subpath imports (e.g., '@esengine/behavior-tree/esengine')

* fix: update es-engine file path after directory reorganization

* docs: update README to focus on framework over engine

* ci: only build framework packages, remove Rust/WASM dependencies

* fix: remove esengine subpath from behavior-tree and blueprint builds

ESEngine integration code will only be available in full engine builds.
Framework packages are now purely engine-agnostic.

* fix: move network-protocols to framework, build both in CI

* fix: update workflow paths from packages/core to packages/framework/core

* fix: exclude esengine folder from type-check in behavior-tree and blueprint

* fix: update network tsconfig references to new paths

* fix: add test:ci:framework to only test framework packages in CI

* fix: only build core and math npm packages in CI

* fix: exclude test files from CodeQL and fix string escaping security issue
2025-12-26 14:50:35 +08:00
YHH
a84ff902e4 fix: 修复 changesets 验证错误 (#337)
- 简化 ignore 配置,只保留 editor-app
- 设置内部包为 private: true
  - build-config, engine, ecs-engine-bindgen
  - editor-core, editor-runtime
  - 所有 *-editor 插件包

这样 changesets 可以正常工作,private 包不会被发布
2025-12-26 09:06:52 +08:00
YHH
54038e3250 feat: 配置 changesets 版本管理和自动发布 (#336)
- 安装 @changesets/cli 和 @changesets/changelog-github
- 配置 .changeset/config.json
- 添加 npm scripts
- 创建 release-changesets.yml GitHub Action
2025-12-25 23:07:44 +08:00
yhh
5544fca002 docs: update changelog for v2.4.2 2025-12-25 20:42:15 +08:00
yhh
88b5ffc0a7 fix(ci): don't mark npm package releases as latest 2025-12-25 20:37:50 +08:00
2039 changed files with 15010 additions and 13936 deletions

8
.changeset/README.md Normal file
View File

@@ -0,0 +1,8 @@
# Changesets
Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works
with multi-package repos, or single-package repos to help you version and publish your code. You can
find the full documentation for it [in our repository](https://github.com/changesets/changesets)
We have a quick list of common questions to get you started engaging with this project in
[our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md)

58
.changeset/config.json Normal file
View File

@@ -0,0 +1,58 @@
{
"$schema": "https://unpkg.com/@changesets/config@3.1.2/schema.json",
"changelog": [
"@changesets/changelog-github",
{ "repo": "esengine/esengine" }
],
"commit": false,
"fixed": [],
"linked": [
["@esengine/ecs-framework", "@esengine/ecs-framework-math"]
],
"access": "public",
"baseBranch": "master",
"updateInternalDependencies": "patch",
"ignore": [
"@esengine/engine-core",
"@esengine/runtime-core",
"@esengine/asset-system",
"@esengine/material-system",
"@esengine/ecs-engine-bindgen",
"@esengine/script-runtime",
"@esengine/platform-common",
"@esengine/platform-web",
"@esengine/platform-wechat",
"@esengine/sprite",
"@esengine/camera",
"@esengine/particle",
"@esengine/tilemap",
"@esengine/mesh-3d",
"@esengine/effect",
"@esengine/audio",
"@esengine/fairygui",
"@esengine/physics-rapier2d",
"@esengine/rapier2d",
"@esengine/world-streaming",
"@esengine/network-server",
"@esengine/editor-core",
"@esengine/editor-runtime",
"@esengine/editor-app",
"@esengine/sprite-editor",
"@esengine/camera-editor",
"@esengine/particle-editor",
"@esengine/tilemap-editor",
"@esengine/mesh-3d-editor",
"@esengine/fairygui-editor",
"@esengine/physics-rapier2d-editor",
"@esengine/behavior-tree-editor",
"@esengine/blueprint-editor",
"@esengine/asset-system-editor",
"@esengine/material-editor",
"@esengine/shader-editor",
"@esengine/world-streaming-editor",
"@esengine/node-editor",
"@esengine/sdk",
"@esengine/worker-generator",
"@esengine/engine"
]
}

View File

@@ -6,3 +6,8 @@ paths-ignore:
- "**/node_modules"
- "**/dist"
- "**/bin"
- "**/tests"
- "**/*.test.ts"
- "**/*.spec.ts"
- "**/test"
- "**/__tests__"

32
.github/labeler.yml vendored
View File

@@ -1,32 +0,0 @@
# 自动标签配置
# 根据 issue/PR 内容自动打标签
'bug':
- '/(bug|错误|崩溃|crash|error|exception|问题)/i'
'enhancement':
- '/(feature|功能|enhancement|improve|优化|建议)/i'
'documentation':
- '/(doc|文档|readme|guide|tutorial|教程)/i'
'question':
- '/(question|疑问|how to|如何|怎么)/i'
'performance':
- '/(performance|性能|slow|慢|lag|卡顿|optimize)/i'
'core':
- '/(@esengine\/ecs-framework|packages\/core|core package)/i'
'editor':
- '/(editor|编辑器|tauri)/i'
'network':
- '/(network|网络|multiplayer|多人)/i'
'help wanted':
- '/(help wanted|需要帮助|求助)/i'
'good first issue':
- '/(good first issue|新手友好|beginner)/i'

View File

@@ -1,73 +0,0 @@
name: AI Batch Analyze Issues
on:
workflow_dispatch:
inputs:
mode:
description: '分析模式'
required: true
type: choice
options:
- 'recent' # 最近 10 个 issue
- 'open' # 所有打开的 issue
- 'all' # 所有 issue慎用
default: 'recent'
permissions:
issues: write
contents: read
jobs:
analyze:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20.x'
- name: Install GitHub CLI
run: |
gh --version || (curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | sudo dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | sudo tee /etc/apt/sources.list.d/github-cli.list > /dev/null
sudo apt update
sudo apt install gh)
- name: Batch Analyze Issues
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
MODE="${{ github.event.inputs.mode }}"
# 获取 issue 列表
if [ "$MODE" = "recent" ]; then
echo "📊 分析最近 10 个 issue..."
ISSUES=$(gh issue list --limit 10 --json number --jq '.[].number')
elif [ "$MODE" = "open" ]; then
echo "📊 分析所有打开的 issue..."
ISSUES=$(gh issue list --state open --json number --jq '.[].number')
else
echo "📊 分析所有 issue这可能需要很长时间..."
ISSUES=$(gh issue list --state all --limit 100 --json number --jq '.[].number')
fi
# 为每个 issue 添加 AI 分析评论
for issue_num in $ISSUES; do
echo "🤖 分析 Issue #$issue_num..."
# 获取 issue 内容
ISSUE_BODY=$(gh issue view $issue_num --json body --jq '.body')
ISSUE_TITLE=$(gh issue view $issue_num --json title --jq '.title')
# 添加触发评论
gh issue comment $issue_num --body "@ai-helper 请帮我分析这个 issue" || true
# 避免 API 限制
sleep 2
done
echo "✅ 批量分析完成!"
echo "查看结果https://github.com/${{ github.repository }}/issues"

View File

@@ -1,61 +0,0 @@
name: AI Helper Tip
# 对所有新创建的 issue 自动回复 AI 助手使用说明(新老用户都适用)
on:
issues:
types: [opened]
permissions:
issues: write
jobs:
tip:
runs-on: ubuntu-latest
steps:
- name: Post AI Helper Usage Tip
uses: actions/github-script@v7
with:
script: |
const message = [
"## 🤖 AI 助手可用 | AI Helper Available",
"",
"**中文说明:**",
"",
"本项目配备了 AI 智能助手,可以帮助你快速获得解答!",
"",
"**使用方法:** 在评论中提及 `@ai-helper`AI 会自动搜索项目代码并提供解决方案。",
"",
"**示例:**",
"```",
"@ai-helper 如何创建一个新的 System",
"@ai-helper 这个报错是什么原因?",
"```",
"",
"---",
"",
"**English:**",
"",
"This project has an AI assistant to help you get answers quickly!",
"",
"**How to use:** Mention `@ai-helper` in a comment, and AI will automatically search the codebase and provide solutions.",
"",
"**Examples:**",
"```",
"@ai-helper How do I create a new System?",
"@ai-helper What causes this error?",
"```",
"",
"---",
"",
"💡 *AI 助手基于代码库提供建议,复杂问题建议等待维护者回复*",
"💡 *AI suggestions are based on the codebase. For complex issues, please wait for maintainer responses*"
].join('\n');
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: message
});
console.log('✅ AI helper tip posted successfully');

View File

@@ -1,85 +0,0 @@
name: AI Issue Helper
on:
issue_comment:
types: [created]
permissions:
issues: write
contents: read
models: read
jobs:
ai-helper:
runs-on: ubuntu-latest
# 只在真实用户提到 @ai-helper 时触发,忽略机器人评论
if: |
contains(github.event.comment.body, '@ai-helper') &&
github.event.comment.user.type != 'Bot'
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: Get Issue Details
id: issue
uses: actions/github-script@v7
with:
script: |
const issue = await github.rest.issues.get({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number
});
// 限制长度,避免超过 token 限制
const maxLength = 1000;
const truncate = (str, max) => {
if (!str) return '';
return str.length > max ? str.substring(0, max) + '...[内容过长已截断]' : str;
};
core.exportVariable('ISSUE_TITLE', truncate(issue.data.title || '', 200));
core.exportVariable('ISSUE_BODY', truncate(issue.data.body || '', maxLength));
core.exportVariable('COMMENT_BODY', truncate(context.payload.comment.body || '', 500));
core.exportVariable('ISSUE_NUMBER', context.issue.number);
- name: Create Prompt
id: prompt
run: |
cat > prompt.txt << 'PROMPT_EOF'
Issue #${{ env.ISSUE_NUMBER }}
标题: ${{ env.ISSUE_TITLE }}
内容: ${{ env.ISSUE_BODY }}
评论: ${{ env.COMMENT_BODY }}
请搜索项目代码并提供解决方案。
PROMPT_EOF
- name: AI Analysis
uses: actions/ai-inference@v1
id: ai
with:
model: 'gpt-4o'
enable-github-mcp: true
max-tokens: 1500
system-prompt: |
你是 ECS Framework (TypeScript ECS 框架) 的 AI 助手。
主要代码在 packages/core/src。
搜索相关代码后,用中文简洁回答问题,包含问题分析、解决方案和代码引用。
prompt-file: prompt.txt
- name: Post AI Response
env:
AI_RESPONSE: ${{ steps.ai.outputs.response }}
uses: actions/github-script@v7
with:
script: |
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: process.env.AI_RESPONSE
});

View File

@@ -1,56 +0,0 @@
name: AI Issue Moderator
on:
issues:
types: [opened]
issue_comment:
types: [created]
permissions:
issues: write
contents: read
models: read
jobs:
moderate:
runs-on: ubuntu-latest
steps:
- name: Check Content
uses: actions/ai-inference@v1
id: check
with:
model: 'gpt-4o-mini'
system-prompt: |
你是一个内容审查助手。
检查内容是否包含:
1. 垃圾信息或广告
2. 恶意或攻击性内容
3. 与项目完全无关的内容
只返回 "SPAM" 或 "OK",不要其他内容。
prompt: |
标题:${{ github.event.issue.title || github.event.comment.body }}
内容:
${{ github.event.issue.body || github.event.comment.body }}
- name: Mark as Spam
if: contains(steps.check.outputs.response, 'SPAM')
uses: actions/github-script@v7
with:
script: |
// 添加 spam 标签
github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
labels: ['spam']
});
// 添加评论
github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: '🤖 这个内容被 AI 检测为可能的垃圾内容。如果这是误判,请联系维护者。\n\n🤖 This content was detected as potential spam by AI. If this is a false positive, please contact the maintainers.'
});

View File

@@ -1,160 +0,0 @@
name: Batch Label Issues
on:
workflow_dispatch:
inputs:
mode:
description: '标签模式'
required: true
type: choice
options:
- 'recent' # 最近 20 个 issue
- 'open' # 所有打开的 issue
- 'unlabeled' # 只处理没有标签的 issue
- 'all' # 所有 issue慎用
default: 'recent'
skip_labeled:
description: '跳过已有标签的 issue'
required: false
type: boolean
default: true
permissions:
issues: write
contents: read
jobs:
batch-label:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20.x'
- name: Batch Label Issues
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
MODE="${{ github.event.inputs.mode }}"
SKIP_LABELED="${{ github.event.inputs.skip_labeled }}"
echo "📊 开始批量打标签..."
echo "模式: $MODE"
echo "跳过已标签: $SKIP_LABELED"
# 获取 issue 列表
if [ "$MODE" = "recent" ]; then
echo "📋 获取最近 20 个 issue..."
ISSUES=$(gh issue list --limit 20 --json number,labels,title,body --jq '.[] | {number, labels: [.labels[].name], title, body}')
elif [ "$MODE" = "open" ]; then
echo "📋 获取所有打开的 issue..."
ISSUES=$(gh issue list --state open --json number,labels,title,body --jq '.[] | {number, labels: [.labels[].name], title, body}')
elif [ "$MODE" = "unlabeled" ]; then
echo "📋 获取没有标签的 issue..."
ISSUES=$(gh issue list --state all --json number,labels,title,body --jq '.[] | select(.labels | length == 0) | {number, labels: [.labels[].name], title, body}')
else
echo "📋 获取所有 issue限制 100 个)..."
ISSUES=$(gh issue list --state all --limit 100 --json number,labels,title,body --jq '.[] | {number, labels: [.labels[].name], title, body}')
fi
# 临时文件
echo "$ISSUES" > /tmp/issues.json
# 处理每个 issue
cat /tmp/issues.json | jq -c '.' | while read -r issue; do
ISSUE_NUM=$(echo "$issue" | jq -r '.number')
EXISTING_LABELS=$(echo "$issue" | jq -r '.labels | join(",")')
TITLE=$(echo "$issue" | jq -r '.title')
BODY=$(echo "$issue" | jq -r '.body')
echo ""
echo "🔍 处理 Issue #$ISSUE_NUM: $TITLE"
echo " 现有标签: $EXISTING_LABELS"
# 跳过已有标签的 issue
if [ "$SKIP_LABELED" = "true" ] && [ ! -z "$EXISTING_LABELS" ]; then
echo " ⏭️ 跳过(已有标签)"
continue
fi
# 分析内容并打标签
LABELS_TO_ADD=""
# 检测 bug
if echo "$TITLE $BODY" | grep -iE "(bug|错误|崩溃|crash|error|exception|问题|fix)" > /dev/null; then
LABELS_TO_ADD="$LABELS_TO_ADD bug"
echo " 🐛 检测到: bug"
fi
# 检测 feature request
if echo "$TITLE $BODY" | grep -iE "(feature|功能|enhancement|improve|优化|建议|新增|添加|add)" > /dev/null; then
LABELS_TO_ADD="$LABELS_TO_ADD enhancement"
echo " ✨ 检测到: enhancement"
fi
# 检测 question
if echo "$TITLE $BODY" | grep -iE "(question|疑问|how to|如何|怎么|为什么|why|咨询|\?|)" > /dev/null; then
LABELS_TO_ADD="$LABELS_TO_ADD question"
echo " ❓ 检测到: question"
fi
# 检测 documentation
if echo "$TITLE $BODY" | grep -iE "(doc|文档|readme|guide|tutorial|教程|说明)" > /dev/null; then
LABELS_TO_ADD="$LABELS_TO_ADD documentation"
echo " 📖 检测到: documentation"
fi
# 检测 performance
if echo "$TITLE $BODY" | grep -iE "(performance|性能|slow|慢|lag|卡顿|optimize|优化)" > /dev/null; then
LABELS_TO_ADD="$LABELS_TO_ADD performance"
echo " ⚡ 检测到: performance"
fi
# 检测 core
if echo "$TITLE $BODY" | grep -iE "(@esengine/ecs-framework|packages/core|core package|核心包)" > /dev/null; then
LABELS_TO_ADD="$LABELS_TO_ADD core"
echo " 🎯 检测到: core"
fi
# 检测 editor
if echo "$TITLE $BODY" | grep -iE "(editor|编辑器|tauri)" > /dev/null; then
LABELS_TO_ADD="$LABELS_TO_ADD editor"
echo " 🎨 检测到: editor"
fi
# 检测 network
if echo "$TITLE $BODY" | grep -iE "(network|网络|multiplayer|多人|同步)" > /dev/null; then
LABELS_TO_ADD="$LABELS_TO_ADD network"
echo " 🌐 检测到: network"
fi
# 检测 help wanted
if echo "$TITLE $BODY" | grep -iE "(help wanted|需要帮助|求助)" > /dev/null; then
LABELS_TO_ADD="$LABELS_TO_ADD help wanted"
echo " 🆘 检测到: help wanted"
fi
# 添加标签
if [ ! -z "$LABELS_TO_ADD" ]; then
echo " ✅ 添加标签: $LABELS_TO_ADD"
for label in $LABELS_TO_ADD; do
gh issue edit $ISSUE_NUM --add-label "$label" 2>&1 | grep -v "already exists" || true
done
echo " 💬 添加说明评论..."
gh issue comment $ISSUE_NUM --body $'🤖 自动标签系统检测到此 issue 并添加了相关标签。如有误判,请告知维护者。\n\n🤖 Auto-labeling system detected and labeled this issue. Please let maintainers know if this is incorrect.' || true
else
echo " 未检测到明确类型"
fi
# 避免 API 限制
sleep 1
done
echo ""
echo "✅ 批量标签完成!"
echo "查看结果: https://github.com/${{ github.repository }}/issues"

View File

@@ -13,17 +13,31 @@ on:
- '.github/workflows/ci.yml'
pull_request:
branches: [ master, main, develop ]
paths:
- 'packages/**'
- 'package.json'
- 'pnpm-lock.yaml'
- 'tsconfig.json'
- 'turbo.json'
- 'jest.config.*'
- '.github/workflows/ci.yml'
# Run on all PRs to satisfy branch protection, but skip build if no code changes
jobs:
# Check if we need to run the full CI
check-changes:
runs-on: ubuntu-latest
outputs:
should-run: ${{ steps.filter.outputs.code }}
steps:
- uses: actions/checkout@v4
- uses: dorny/paths-filter@v3
id: filter
with:
filters: |
code:
- 'packages/**'
- 'package.json'
- 'pnpm-lock.yaml'
- 'tsconfig.json'
- 'turbo.json'
- 'jest.config.*'
ci:
needs: check-changes
if: needs.check-changes.outputs.should-run == 'true'
runs-on: ubuntu-latest
env:
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
@@ -42,57 +56,35 @@ jobs:
node-version: '20.x'
cache: 'pnpm'
- name: Install Rust stable
uses: dtolnay/rust-toolchain@stable
with:
targets: wasm32-unknown-unknown
# 缓存 Rust 编译结果
- name: Cache Rust dependencies
uses: Swatinem/rust-cache@v2
with:
workspaces: packages/engine
cache-on-failure: true
# 缓存 wasm-pack
- name: Cache wasm-pack
uses: actions/cache@v4
with:
path: ~/.cargo/bin/wasm-pack
key: wasm-pack-${{ runner.os }}
- name: Install wasm-pack
run: |
if ! command -v wasm-pack &> /dev/null; then
cargo install wasm-pack
fi
- name: Install dependencies
run: pnpm install --no-frozen-lockfile
# 构建所有包 (使用 Turborepo Remote Cache)
- name: Build all packages
run: pnpm run build
- name: Copy WASM files to ecs-engine-bindgen
# 构建 framework 包 (可独立发布的通用库,无外部依赖)
- name: Build framework packages
run: |
mkdir -p packages/ecs-engine-bindgen/src/wasm
cp packages/engine/pkg/es_engine.js packages/ecs-engine-bindgen/src/wasm/
cp packages/engine/pkg/es_engine.d.ts packages/ecs-engine-bindgen/src/wasm/
cp packages/engine/pkg/es_engine_bg.wasm packages/ecs-engine-bindgen/src/wasm/
cp packages/engine/pkg/es_engine_bg.wasm.d.ts packages/ecs-engine-bindgen/src/wasm/
pnpm --filter @esengine/ecs-framework build
pnpm --filter @esengine/ecs-framework-math build
pnpm --filter @esengine/behavior-tree build
pnpm --filter @esengine/blueprint build
pnpm --filter @esengine/fsm build
pnpm --filter @esengine/timer build
pnpm --filter @esengine/spatial build
pnpm --filter @esengine/procgen build
pnpm --filter @esengine/pathfinding build
pnpm --filter @esengine/network-protocols build
pnpm --filter @esengine/network build
# 类型检查
- name: Type check
run: pnpm run type-check
# 类型检查 (仅 framework 包)
- name: Type check (framework packages)
run: pnpm run type-check:framework
# Lint 检查
- name: Lint check
run: pnpm run lint
# Lint 检查 (仅 framework 包)
- name: Lint check (framework packages)
run: pnpm run lint:framework
# 测试
# 测试 (仅 framework 包)
- name: Run tests with coverage
run: pnpm run test:ci
run: pnpm run test:ci:framework
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v4
@@ -103,9 +95,11 @@ jobs:
name: codecov-umbrella
fail_ci_if_error: false
# 构建 npm 包
# 构建 npm 包 (core 和 math)
- name: Build npm packages
run: pnpm run build:npm
run: |
pnpm run build:npm:core
pnpm run build:npm:math
# 上传构建产物
- name: Upload build artifacts
@@ -113,6 +107,6 @@ jobs:
with:
name: build-artifacts
path: |
packages/*/dist/
packages/*/bin/
packages/framework/**/dist/
packages/framework/**/bin/
retention-days: 7

View File

@@ -1,146 +0,0 @@
name: Cleanup Old Dependabot PRs
# 手动触发的 workflow用于清理堆积的 Dependabot PR
on:
workflow_dispatch:
inputs:
days_old:
description: '关闭多少天前创建的 PR默认 7 天)'
required: false
default: '7'
dry_run:
description: '试运行模式true=仅显示,不关闭)'
required: false
default: 'true'
type: choice
options:
- 'true'
- 'false'
jobs:
cleanup:
runs-on: ubuntu-latest
permissions:
pull-requests: write
issues: write
steps:
- name: Checkout
uses: actions/checkout@v4
- name: List and Close Old Dependabot PRs
uses: actions/github-script@v7
with:
script: |
const daysOld = parseInt('${{ github.event.inputs.days_old }}') || 7;
const dryRun = '${{ github.event.inputs.dry_run }}' === 'true';
const cutoffDate = new Date();
cutoffDate.setDate(cutoffDate.getDate() - daysOld);
console.log(`🔍 查找超过 ${daysOld} 天的 Dependabot PR...`);
console.log(`📅 截止日期: ${cutoffDate.toISOString()}`);
console.log(`🏃 模式: ${dryRun ? '试运行(不会实际关闭)' : '实际执行'}`);
console.log('---');
// 获取所有 Dependabot PR
const { data: pulls } = await github.rest.pulls.list({
owner: context.repo.owner,
repo: context.repo.repo,
state: 'open',
per_page: 100
});
const dependabotPRs = pulls.filter(pr =>
pr.user.login === 'dependabot[bot]' &&
new Date(pr.created_at) < cutoffDate
);
console.log(`📊 找到 ${dependabotPRs.length} 个符合条件的 Dependabot PR`);
console.log('');
if (dependabotPRs.length === 0) {
console.log('✅ 没有需要清理的 PR');
return;
}
// 按类型分组
const byType = {
dev: [],
prod: [],
actions: [],
other: []
};
for (const pr of dependabotPRs) {
const title = pr.title.toLowerCase();
const labels = pr.labels.map(l => l.name);
let type = 'other';
if (title.includes('dev-dependencies') || title.includes('development')) {
type = 'dev';
} else if (title.includes('production-dependencies')) {
type = 'prod';
} else if (labels.includes('github-actions')) {
type = 'actions';
}
byType[type].push(pr);
}
console.log('📋 PR 分类统计:');
console.log(` 🔧 开发依赖: ${byType.dev.length} 个`);
console.log(` 📦 生产依赖: ${byType.prod.length} 个`);
console.log(` ⚙️ GitHub Actions: ${byType.actions.length} 个`);
console.log(` ❓ 其他: ${byType.other.length} 个`);
console.log('');
// 处理每个 PR
for (const pr of dependabotPRs) {
const age = Math.floor((Date.now() - new Date(pr.created_at)) / (1000 * 60 * 60 * 24));
console.log(`${dryRun ? '🔍' : '🗑️ '} #${pr.number}: ${pr.title}`);
console.log(` 创建时间: ${pr.created_at} (${age} 天前)`);
console.log(` 链接: ${pr.html_url}`);
if (!dryRun) {
await github.rest.pulls.update({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: pr.number,
state: 'closed'
});
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: pr.number,
body: `🤖 **自动关闭旧的 Dependabot PR**
此 PR 已超过 ${daysOld} 天未合并,已被自动关闭以清理积压。
📌 **下一步:**
- Dependabot 已配置为月度运行,届时会创建新的分组更新
- 新的 Mergify 规则会智能处理不同类型的依赖更新
- 开发依赖和 GitHub Actions 会自动合并(即使 CI 失败)
- 生产依赖需要 CI 通过才会自动合并
如果需要立即应用此更新,请手动更新依赖。
---
*此操作由仓库维护者手动触发的清理工作流执行*`
});
console.log(' ✅ 已关闭并添加说明');
} else {
console.log(' 试运行模式 - 未执行操作');
}
console.log('');
}
console.log('---');
if (dryRun) {
console.log(`✨ 试运行完成!共发现 ${dependabotPRs.length} 个待清理的 PR`);
console.log('💡 要实际执行清理,请将 dry_run 参数设为 false 重新运行');
} else {
console.log(`✅ 清理完成!已关闭 ${dependabotPRs.length} 个 Dependabot PR`);
}

View File

@@ -28,7 +28,7 @@ jobs:
- name: Run tests with coverage
run: |
cd packages/core
cd packages/framework/core
pnpm run test:coverage
- name: Upload coverage to Codecov
@@ -36,7 +36,7 @@ jobs:
continue-on-error: true
with:
token: ${{ secrets.CODECOV_TOKEN }}
files: ./packages/core/coverage/coverage-final.json
files: ./packages/framework/core/coverage/coverage-final.json
flags: core
name: core-coverage
fail_ci_if_error: false
@@ -46,4 +46,4 @@ jobs:
uses: actions/upload-artifact@v4
with:
name: coverage-report
path: packages/core/coverage/
path: packages/framework/core/coverage/

View File

@@ -1,23 +0,0 @@
name: Issue Labeler
on:
issues:
types: [opened, edited]
permissions:
issues: write
contents: read
jobs:
label:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Label Issues
uses: github/issue-labeler@v3.4
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
configuration-path: .github/labeler.yml
enable-versioned-regex: 1

View File

@@ -1,28 +0,0 @@
name: Issue Translator
on:
issue_comment:
types: [created]
issues:
types: [opened]
permissions:
issues: write
jobs:
translate:
runs-on: ubuntu-latest
steps:
- name: Translate Issues
uses: tomsun28/issues-translate-action@v2.7
with:
IS_MODIFY_TITLE: false
# 设置为 true 会修改标题false 只在评论中添加翻译
CUSTOM_BOT_NOTE: |
<details>
<summary>🌏 Translation / 翻译</summary>
Bot detected the issue body's language is not English, translate it automatically.
机器人检测到 issue 内容非英文,自动翻译。
</details>

View File

@@ -0,0 +1,70 @@
name: Release (Changesets)
on:
push:
branches:
- master
paths:
- '.changeset/**'
- 'packages/*/package.json'
- 'packages/*/*/package.json'
- 'packages/*/*/*/package.json'
workflow_dispatch:
concurrency: ${{ github.workflow }}-${{ github.ref }}
jobs:
release:
name: Release
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
id-token: write
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install pnpm
uses: pnpm/action-setup@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 20
registry-url: 'https://registry.npmjs.org'
cache: 'pnpm'
- name: Install dependencies
run: pnpm install
- name: Build framework packages
run: |
# Only build packages managed by Changesets (not in ignore list)
pnpm --filter "@esengine/ecs-framework" build
pnpm --filter "@esengine/ecs-framework-math" build
pnpm --filter "@esengine/behavior-tree" build
pnpm --filter "@esengine/blueprint" build
pnpm --filter "@esengine/fsm" build
pnpm --filter "@esengine/timer" build
pnpm --filter "@esengine/spatial" build
pnpm --filter "@esengine/procgen" build
pnpm --filter "@esengine/pathfinding" build
pnpm --filter "@esengine/network-protocols" build
pnpm --filter "@esengine/network" build
pnpm --filter "@esengine/cli" build
- name: Create Release Pull Request or Publish
id: changesets
uses: changesets/action@v1
with:
version: pnpm changeset:version
publish: pnpm changeset:publish
title: 'chore: release packages'
commit: 'chore: release packages'
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

View File

@@ -50,7 +50,7 @@ jobs:
- name: Rust cache
uses: Swatinem/rust-cache@v2
with:
workspaces: packages/editor-app/src-tauri
workspaces: packages/editor/editor-app/src-tauri
cache-on-failure: true
- name: Install dependencies (Ubuntu)
@@ -65,7 +65,7 @@ jobs:
- name: Update version in config files (for manual trigger)
if: github.event_name == 'workflow_dispatch'
run: |
cd packages/editor-app
cd packages/editor/editor-app
node -e "const pkg=require('./package.json'); pkg.version='${{ github.event.inputs.version }}'; require('fs').writeFileSync('./package.json', JSON.stringify(pkg, null, 2)+'\n')"
node scripts/sync-version.js
@@ -80,15 +80,15 @@ jobs:
- name: Copy WASM files to ecs-engine-bindgen
shell: bash
run: |
mkdir -p packages/ecs-engine-bindgen/src/wasm
cp packages/engine/pkg/es_engine.js packages/ecs-engine-bindgen/src/wasm/
cp packages/engine/pkg/es_engine.d.ts packages/ecs-engine-bindgen/src/wasm/
cp packages/engine/pkg/es_engine_bg.wasm packages/ecs-engine-bindgen/src/wasm/
cp packages/engine/pkg/es_engine_bg.wasm.d.ts packages/ecs-engine-bindgen/src/wasm/
mkdir -p packages/engine/ecs-engine-bindgen/src/wasm
cp packages/rust/engine/pkg/es_engine.js packages/engine/ecs-engine-bindgen/src/wasm/
cp packages/rust/engine/pkg/es_engine.d.ts packages/engine/ecs-engine-bindgen/src/wasm/
cp packages/rust/engine/pkg/es_engine_bg.wasm packages/engine/ecs-engine-bindgen/src/wasm/
cp packages/rust/engine/pkg/es_engine_bg.wasm.d.ts packages/engine/ecs-engine-bindgen/src/wasm/
- name: Bundle runtime files for Tauri
run: |
cd packages/editor-app
cd packages/editor/editor-app
node scripts/bundle-runtime.mjs
- name: Build Tauri app
@@ -99,7 +99,7 @@ jobs:
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
projectPath: packages/editor/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.'
@@ -116,8 +116,8 @@ jobs:
with:
name: windows-unsigned
path: |
packages/editor-app/src-tauri/target/release/bundle/nsis/*.exe
packages/editor-app/src-tauri/target/release/bundle/msi/*.msi
packages/editor/editor-app/src-tauri/target/release/bundle/nsis/*.exe
packages/editor/editor-app/src-tauri/target/release/bundle/msi/*.msi
retention-days: 1
# SignPath 代码签名Windows
@@ -221,7 +221,7 @@ jobs:
- name: Update version files
run: |
cd packages/editor-app
cd packages/editor/editor-app
node -e "const pkg=require('./package.json'); pkg.version='${{ github.event.inputs.version }}'; require('fs').writeFileSync('./package.json', JSON.stringify(pkg, null, 2)+'\n')"
node scripts/sync-version.js
@@ -239,8 +239,8 @@ jobs:
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 }}`
- Updated `packages/editor/editor-app/package.json` → `${{ github.event.inputs.version }}`
- Updated `packages/editor/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 }})

View File

@@ -1,7 +1,6 @@
name: Release NPM Packages
on:
# 标签触发:支持 v* 和 {package}-v* 格式
# Tag trigger: supports v* and {package}-v* formats
push:
tags:
@@ -15,12 +14,11 @@ on:
- 'physics-rapier2d-v*'
- 'worker-generator-v*'
# 保留手动触发选项
# Keep manual trigger option
# Manual trigger option
workflow_dispatch:
inputs:
package:
description: '选择要发布的包 | Select package to publish'
description: 'Select package to publish'
required: true
type: choice
options:
@@ -33,7 +31,7 @@ on:
- physics-rapier2d
- worker-generator
version_type:
description: '版本更新类型 | Version bump type'
description: 'Version bump type'
required: true
type: choice
options:
@@ -61,11 +59,10 @@ jobs:
id: parse
run: |
if [ "${{ github.event_name }}" = "push" ]; then
# 从标签解析包名和版本 | Parse package and version from tag
# Parse package and version from tag
TAG="${GITHUB_REF#refs/tags/}"
echo "tag=$TAG" >> $GITHUB_OUTPUT
# 解析格式v1.0.0 或 package-v1.0.0
# Parse format: v1.0.0 or package-v1.0.0
if [[ "$TAG" =~ ^v([0-9]+\.[0-9]+\.[0-9]+.*)$ ]]; then
PACKAGE="core"
@@ -82,10 +79,9 @@ jobs:
echo "package=$PACKAGE" >> $GITHUB_OUTPUT
echo "version=$VERSION" >> $GITHUB_OUTPUT
echo "mode=tag" >> $GITHUB_OUTPUT
echo "📦 Package: $PACKAGE"
echo "📌 Version: $VERSION"
echo "Package: $PACKAGE"
echo "Version: $VERSION"
else
# 手动触发:从 package.json 读取并 bump 版本
# Manual trigger: read from package.json and bump version
PACKAGE="${{ github.event.inputs.package }}"
echo "package=$PACKAGE" >> $GITHUB_OUTPUT
@@ -112,7 +108,6 @@ jobs:
PACKAGE="${{ steps.parse.outputs.package }}"
EXPECTED_VERSION="${{ steps.parse.outputs.version }}"
# 获取 package.json 中的版本
# Get version from package.json
ACTUAL_VERSION=$(node -p "require('./packages/$PACKAGE/package.json').version")
@@ -125,7 +120,7 @@ jobs:
exit 1
fi
echo "Version verified: $EXPECTED_VERSION"
echo "Version verified: $EXPECTED_VERSION"
- name: Bump version (manual mode)
if: steps.parse.outputs.mode == 'manual'
@@ -147,7 +142,7 @@ jobs:
node -e "const fs=require('fs'); const pkg=JSON.parse(fs.readFileSync('package.json')); pkg.version='$NEW_VERSION'; fs.writeFileSync('package.json', JSON.stringify(pkg, null, 2)+'\n')"
echo "version=$NEW_VERSION" >> $GITHUB_OUTPUT
echo "📌 Bumped version: $CURRENT $NEW_VERSION"
echo "Bumped version: $CURRENT -> $NEW_VERSION"
- name: Set final version
id: version
@@ -161,7 +156,7 @@ jobs:
- name: Build core package (if needed)
if: ${{ steps.parse.outputs.package != 'core' && steps.parse.outputs.package != 'node-editor' && steps.parse.outputs.package != 'worker-generator' }}
run: |
cd packages/core
cd packages/framework/core
pnpm run build
- name: Build node-editor package (if needed for blueprint)
@@ -188,17 +183,18 @@ jobs:
with:
tag_name: ${{ steps.parse.outputs.tag }}
name: "${{ steps.parse.outputs.package }} v${{ steps.version.outputs.value }}"
make_latest: false
body: |
## 🚀 @esengine/${{ steps.parse.outputs.package }} v${{ steps.version.outputs.value }}
## @esengine/${{ steps.parse.outputs.package }} v${{ steps.version.outputs.value }}
📦 **NPM**: [@esengine/${{ steps.parse.outputs.package }}@${{ steps.version.outputs.value }}](https://www.npmjs.com/package/@esengine/${{ steps.parse.outputs.package }}/v/${{ steps.version.outputs.value }})
**NPM**: [@esengine/${{ steps.parse.outputs.package }}@${{ steps.version.outputs.value }}](https://www.npmjs.com/package/@esengine/${{ steps.parse.outputs.package }}/v/${{ steps.version.outputs.value }})
```bash
npm install @esengine/${{ steps.parse.outputs.package }}@${{ steps.version.outputs.value }}
```
---
*自动发布 | Auto-released by GitHub Actions*
*Auto-released by GitHub Actions*
generate_release_notes: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
@@ -213,16 +209,16 @@ jobs:
delete-branch: true
title: "chore(${{ steps.parse.outputs.package }}): Release v${{ steps.version.outputs.value }}"
body: |
## 🚀 Release v${{ steps.version.outputs.value }}
## Release v${{ steps.version.outputs.value }}
此 PR 更新 `@esengine/${{ steps.parse.outputs.package }}` 包的版本号
This PR updates `@esengine/${{ steps.parse.outputs.package }}` package version.
### 变更
- ✅ 已发布到 npm: [@esengine/${{ steps.parse.outputs.package }}@${{ steps.version.outputs.value }}](https://www.npmjs.com/package/@esengine/${{ steps.parse.outputs.package }}/v/${{ steps.version.outputs.value }})
- ✅ 更新 `packages/${{ steps.parse.outputs.package }}/package.json` `${{ steps.version.outputs.value }}`
### Changes
- Published to npm: [@esengine/${{ steps.parse.outputs.package }}@${{ steps.version.outputs.value }}](https://www.npmjs.com/package/@esengine/${{ steps.parse.outputs.package }}/v/${{ steps.version.outputs.value }})
- Updated `packages/${{ steps.parse.outputs.package }}/package.json` to `${{ steps.version.outputs.value }}`
---
*此 PR 由发布工作流自动创建*
*This PR was automatically created by the release workflow*
labels: |
release
${{ steps.parse.outputs.package }}

View File

@@ -1,46 +0,0 @@
name: Size Limit
on:
pull_request:
branches:
- master
- main
paths:
- 'packages/core/src/**'
- 'packages/core/package.json'
- '.size-limit.json'
permissions:
contents: read
pull-requests: write
issues: write
jobs:
size:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install pnpm
uses: pnpm/action-setup@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20.x'
cache: 'pnpm'
- name: Install dependencies
run: pnpm install
- name: Build core package
run: |
cd packages/core
pnpm run build:npm
- name: Check bundle size
uses: andresz1/size-limit-action@v1
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
skip_step: install

View File

@@ -1,58 +0,0 @@
name: Welcome
on:
issues:
types: [opened]
pull_request_target:
types: [opened]
permissions:
issues: write
pull-requests: write
jobs:
welcome:
runs-on: ubuntu-latest
steps:
- name: Welcome new contributors
uses: actions/first-interaction@v1.3.0
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
issue-message: |
👋 你好!感谢你提交第一个 issue
我们会尽快查看并回复。同时,建议你:
- 📚 查看[文档](https://esengine.github.io/ecs-framework/)
- 🤖 使用 [AI 文档助手](https://deepwiki.com/esengine/esengine)
- 💬 加入 [QQ 交流群](https://jq.qq.com/?_wv=1027&k=29w1Nud6)
---
👋 Hello! Thanks for opening your first issue!
We'll review it as soon as possible. Meanwhile, you might want to:
- 📚 Check the [documentation](https://esengine.github.io/ecs-framework/)
- 🤖 Use [AI documentation assistant](https://deepwiki.com/esengine/esengine)
pr-message: |
👋 你好!感谢你提交第一个 Pull Request
在我们 Review 之前,请确保:
- ✅ 代码遵循项目规范
- ✅ 通过所有测试
- ✅ 更新了相关文档
- ✅ Commit 遵循 [Conventional Commits](https://www.conventionalcommits.org/) 规范
查看完整的[贡献指南](https://github.com/esengine/esengine/blob/master/CONTRIBUTING.md)。
---
👋 Hello! Thanks for your first Pull Request!
Before we review, please ensure:
- ✅ Code follows project conventions
- ✅ All tests pass
- ✅ Documentation is updated
- ✅ Commits follow [Conventional Commits](https://www.conventionalcommits.org/)
See the full [Contributing Guide](https://github.com/esengine/esengine/blob/master/CONTRIBUTING.md).

312
README.md
View File

@@ -5,7 +5,7 @@
</h1>
<p align="center">
<strong>Cross-platform 2D Game Engine</strong>
<strong>Modular Game Framework for TypeScript</strong>
</p>
<p align="center">
@@ -23,64 +23,58 @@
<p align="center">
<a href="https://esengine.cn/">Documentation</a> ·
<a href="https://esengine.cn/api/README">API Reference</a> ·
<a href="https://github.com/esengine/esengine/releases">Download Editor</a> ·
<a href="./examples/">Examples</a>
</p>
---
> **Just need ECS?** The core ECS framework [`@esengine/ecs-framework`](./packages/core/) can be used standalone with Cocos Creator, Laya, or any JS engine. [View ECS Documentation](./packages/core/README.md)
## What is ESEngine?
## Overview
ESEngine is a collection of **engine-agnostic game development modules** for TypeScript. Use them with Cocos Creator, Laya, Phaser, PixiJS, or any JavaScript game engine.
ESEngine is a cross-platform 2D game engine built from the ground up with modern web technologies. It provides a comprehensive toolset that enables developers to focus on creating games rather than building infrastructure.
Export your games to multiple platforms including web browsers, WeChat Mini Games, and other mini-game platforms from a single codebase.
## Key Features
| Feature | Description |
|---------|-------------|
| **ECS Architecture** | Data-driven Entity-Component-System pattern for flexible and cache-friendly game logic |
| **High-Performance Rendering** | Rust/WebAssembly 2D renderer with automatic sprite batching and WebGL 2.0 backend |
| **Visual Editor** | Cross-platform desktop editor built with Tauri for scene management and asset workflows |
| **Modular Design** | Import only what you need - each feature is a standalone package |
| **Multi-Platform Export** | Deploy to Web, WeChat Mini Games, and more from one codebase |
| **Physics Integration** | 2D physics powered by Rapier with editor visualization |
| **Visual Scripting** | Behavior trees and blueprint system for designers |
## Tech Stack
- **Runtime**: TypeScript, Rust, WebAssembly
- **Renderer**: WebGL 2.0, WGPU (planned)
- **Editor**: Tauri, React, Zustand
- **Physics**: Rapier2D
- **Build**: pnpm, Turborepo, Rollup
## License
ESEngine is **free and open source** under the [MIT License](LICENSE). No royalties, no strings attached.
## Installation
### npm
The core is a high-performance **ECS (Entity-Component-System)** framework, accompanied by optional modules for AI, networking, physics, and more.
```bash
npm install @esengine/ecs-framework
```
### Editor
## Features
Download pre-built binaries from the [Releases](https://github.com/esengine/esengine/releases) page (Windows, macOS).
| Module | Description | Engine Required |
|--------|-------------|:---------------:|
| **ECS Core** | Entity-Component-System framework with reactive queries | No |
| **Behavior Tree** | AI behavior trees with visual editor support | No |
| **Blueprint** | Visual scripting system | No |
| **FSM** | Finite state machine | No |
| **Timer** | Timer and cooldown systems | No |
| **Spatial** | Spatial indexing and queries (QuadTree, Grid) | No |
| **Pathfinding** | A* and navigation mesh pathfinding | No |
| **Network** | Client/server networking with TSRPC | No |
> All framework modules can be used standalone with any rendering engine.
## Quick Start
### Using CLI (Recommended)
The easiest way to add ECS to your existing project:
```bash
# In your project directory
npx @esengine/cli init
```
The CLI automatically detects your project type (Cocos Creator 2.x/3.x, LayaAir 3.x, or Node.js) and generates the necessary integration code.
### Manual Setup
```typescript
import {
Core, Scene, Entity, Component, EntitySystem,
Matcher, Time, ECSComponent, ECSSystem
} from '@esengine/ecs-framework';
// Define components (data only)
@ECSComponent('Position')
class Position extends Component {
x = 0;
@@ -93,6 +87,7 @@ class Velocity extends Component {
dy = 0;
}
// Define system (logic)
@ECSSystem('Movement')
class MovementSystem extends EntitySystem {
constructor() {
@@ -120,7 +115,7 @@ player.addComponent(new Velocity());
Core.setScene(scene);
// Game loop
// Integrate with your game loop
function gameLoop(currentTime: number) {
Core.update(currentTime / 1000);
requestAnimationFrame(gameLoop);
@@ -128,109 +123,132 @@ function gameLoop(currentTime: number) {
requestAnimationFrame(gameLoop);
```
## Packages
## Using with Other Engines
ESEngine is organized as a monorepo with 50+ modular packages. Install only what you need.
ESEngine's framework modules are designed to work alongside your preferred rendering engine:
### Essential
### With Cocos Creator
```bash
npm install @esengine/ecs-framework # Core ECS (can be used standalone)
npm install @esengine/engine-core # Full engine with module system
```typescript
import { Component as CCComponent, _decorator } from 'cc';
import { Core, Scene, Matcher, EntitySystem } from '@esengine/ecs-framework';
import { BehaviorTreeExecutionSystem } from '@esengine/behavior-tree';
const { ccclass } = _decorator;
@ccclass('GameManager')
export class GameManager extends CCComponent {
private ecsScene!: Scene;
start() {
Core.create();
this.ecsScene = new Scene();
// Add ECS systems
this.ecsScene.addSystem(new BehaviorTreeExecutionSystem());
this.ecsScene.addSystem(new MyGameSystem());
Core.setScene(this.ecsScene);
}
update(dt: number) {
Core.update(dt);
}
}
```
### Popular Modules
### With Laya 3.x
```typescript
import { Core, Scene } from '@esengine/ecs-framework';
import { FSMSystem } from '@esengine/fsm';
const { regClass } = Laya;
@regClass()
export class ECSManager extends Laya.Script {
private ecsScene = new Scene();
onAwake(): void {
Core.create();
this.ecsScene.addSystem(new FSMSystem());
Core.setScene(this.ecsScene);
}
onUpdate(): void {
Core.update(Laya.timer.delta / 1000);
}
onDestroy(): void {
Core.destroy();
}
}
```
## Packages
### Framework (Engine-Agnostic)
These packages have **zero rendering dependencies** and work with any engine:
```bash
npm install @esengine/ecs-framework # Core ECS
npm install @esengine/behavior-tree # AI behavior trees
npm install @esengine/blueprint # Visual scripting
npm install @esengine/fsm # State machines
npm install @esengine/timer # Timers & cooldowns
npm install @esengine/spatial # Spatial indexing
npm install @esengine/pathfinding # Pathfinding
npm install @esengine/network # Networking
```
### ESEngine Runtime (Optional)
If you want a complete engine solution with rendering:
| Category | Packages |
|----------|----------|
| **Rendering** | `sprite`, `tilemap`, `particle`, `mesh-3d`, `fairygui` |
| **Core** | `engine-core`, `asset-system`, `material-system` |
| **Rendering** | `sprite`, `tilemap`, `particle`, `camera`, `mesh-3d` |
| **Physics** | `physics-rapier2d` |
| **AI & Logic** | `behavior-tree`, `blueprint` |
| **Network** | `network`, `network-server` |
| **Platform** | `platform-web`, `platform-wechat` |
<details>
<summary><b>View all 50+ packages</b></summary>
### Editor (Optional)
#### Core
- `@esengine/ecs-framework` - ECS framework core
- `@esengine/math` - Vector, matrix utilities
- `@esengine/engine` - Rust/WASM renderer
- `@esengine/engine-core` - Module lifecycle
A visual editor built with Tauri for scene management:
#### Runtime
- `@esengine/sprite` - 2D sprites & animation
- `@esengine/tilemap` - Tile-based maps
- `@esengine/particle` - Particle effects
- `@esengine/physics-rapier2d` - 2D physics
- `@esengine/behavior-tree` - AI behavior trees
- `@esengine/blueprint` - Visual scripting
- `@esengine/camera` - Camera system
- `@esengine/audio` - Audio playback
- `@esengine/fairygui` - FairyGUI integration
- `@esengine/mesh-3d` - 3D mesh (FBX/GLTF/OBJ)
- `@esengine/material-system` - Materials & shaders
- `@esengine/asset-system` - Asset management
- `@esengine/world-streaming` - Large world streaming
- Download from [Releases](https://github.com/esengine/esengine/releases)
- Supports behavior tree editing, tilemap painting, visual scripting
#### Network
- `@esengine/network` - Client (TSRPC)
- `@esengine/network-server` - Server runtime
- `@esengine/network-protocols` - Shared protocols
## Project Structure
#### Editor Extensions
All runtime modules have corresponding `-editor` packages for visual editing.
#### Platform
- `@esengine/platform-common` - Platform abstraction
- `@esengine/platform-web` - Web runtime
- `@esengine/platform-wechat` - WeChat Mini Game
</details>
## Editor
The ESEngine Editor is a cross-platform desktop application built with Tauri and React.
### Features
- Scene hierarchy and entity management
- Component inspector with custom property editors
- Asset browser with drag-and-drop
- Tilemap editor with paint and fill tools
- Behavior tree visual editor
- Blueprint visual scripting
- Material and shader editing
- Built-in performance profiler
- Localization (English, Chinese)
### Screenshot
![ESEngine Editor](screenshots/main_screetshot.png)
## Platform Support
| Platform | Runtime | Editor |
|----------|:-------:|:------:|
| Web Browser | ✓ | - |
| Windows | - | ✓ |
| macOS | - | ✓ |
| WeChat Mini Game | In Progress | - |
| Playable Ads | Planned | - |
| Android | Planned | - |
| iOS | Planned | - |
```
esengine/
├── packages/
│ ├── framework/ # Engine-agnostic modules (NPM publishable)
│ │ ├── core/ # ECS Framework
│ │ ├── math/ # Math utilities
│ │ ├── behavior-tree/ # AI behavior trees
│ │ ├── blueprint/ # Visual scripting
│ │ ├── fsm/ # Finite state machine
│ │ ├── timer/ # Timer system
│ │ ├── spatial/ # Spatial queries
│ │ ├── pathfinding/ # Pathfinding
│ │ ├── procgen/ # Procedural generation
│ │ └── network/ # Networking
│ │
│ ├── engine/ # ESEngine runtime
│ ├── rendering/ # Rendering modules
│ ├── physics/ # Physics modules
│ ├── editor/ # Visual editor
│ └── rust/ # WASM renderer
├── docs/ # Documentation
└── examples/ # Examples
```
## Building from Source
### Prerequisites
- Node.js 18+
- pnpm 10+
- Rust toolchain (for WASM renderer)
- wasm-pack
### Setup
```bash
git clone https://github.com/esengine/esengine.git
cd esengine
@@ -238,54 +256,28 @@ cd esengine
pnpm install
pnpm build
# Optional: Build WASM renderer
pnpm build:wasm
# Type check framework packages
pnpm type-check:framework
# Run tests
pnpm test
```
### Run Editor
```bash
cd packages/editor-app
pnpm tauri:dev
```
### Project Structure
```
esengine/
├── packages/
│ ├── core/ # ECS Framework (@esengine/ecs-framework)
│ ├── math/ # Math library (@esengine/math)
│ ├── engine-core/ # Engine lifecycle management
│ ├── sprite/ # 2D sprite rendering
│ ├── tilemap/ # Tilemap system
│ ├── physics-rapier2d/ # Physics engine
│ ├── behavior-tree/ # AI behavior trees
│ ├── editor-app/ # Desktop editor (Tauri)
│ └── ... # Other modules
├── docs/ # Documentation source
├── examples/ # Example projects
├── scripts/ # Build utilities
└── thirdparty/ # Third-party dependencies
```
> **Looking for ECS source code?** The ECS framework is in `packages/core/`
## Documentation
- [Getting Started](https://esengine.cn/guide/getting-started.html)
- [Architecture Guide](https://esengine.cn/guide/)
- [ECS Framework Guide](./packages/framework/core/README.md)
- [Behavior Tree Guide](./packages/framework/behavior-tree/README.md)
- [API Reference](https://esengine.cn/api/README)
## Community
- [Discord](https://discord.gg/gCAgzXFW) - Chat with the community
- [GitHub Issues](https://github.com/esengine/esengine/issues) - Bug reports and feature requests
- [GitHub Discussions](https://github.com/esengine/esengine/discussions) - Questions and ideas
- [Discord](https://discord.gg/gCAgzXFW) - Chat with the community
## Contributing
Contributions are welcome. Please read the contributing guidelines before submitting a pull request.
Contributions are welcome! Please read our contributing guidelines before submitting a pull request.
1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
@@ -295,10 +287,10 @@ Contributions are welcome. Please read the contributing guidelines before submit
## License
ESEngine is licensed under the [MIT License](LICENSE).
ESEngine is licensed under the [MIT License](LICENSE). Free for personal and commercial use.
---
<p align="center">
Made with ❤️ by the ESEngine team
Made with care by the ESEngine community
</p>

View File

@@ -5,7 +5,7 @@
</h1>
<p align="center">
<strong>跨平台 2D 游戏引擎</strong>
<strong>TypeScript 模块化游戏框架</strong>
</p>
<p align="center">
@@ -23,64 +23,58 @@
<p align="center">
<a href="https://esengine.cn/">文档</a> ·
<a href="https://esengine.cn/api/README">API 参考</a> ·
<a href="https://github.com/esengine/esengine/releases">下载编辑器</a> ·
<a href="./examples/">示例</a>
</p>
---
> **只需要 ECS** 核心 ECS 框架 [`@esengine/ecs-framework`](./packages/core/) 可独立使用,支持 Cocos Creator、Laya 或任何 JS 引擎。[查看 ECS 文档](./packages/core/README_CN.md)
## ESEngine 是什么?
## 概述
ESEngine 是一套**引擎无关的游戏开发模块**,可与 Cocos Creator、Laya、Phaser、PixiJS 等任何 JavaScript 游戏引擎配合使用。
ESEngine 是一款基于现代 Web 技术从零构建的跨平台 2D 游戏引擎。它提供完整的工具集,让开发者专注于游戏创作而非基础设施搭建
一套代码即可导出到 Web 浏览器、微信小游戏等多个平台。
## 核心特性
| 特性 | 描述 |
|-----|------|
| **ECS 架构** | 数据驱动的实体-组件-系统模式,提供灵活且缓存友好的游戏逻辑 |
| **高性能渲染** | Rust/WebAssembly 2D 渲染器,支持自动精灵批处理和 WebGL 2.0 |
| **可视化编辑器** | 基于 Tauri 的跨平台桌面编辑器,支持场景管理和资源工作流 |
| **模块化设计** | 按需引入,每个功能都是独立的包 |
| **多平台导出** | 一套代码部署到 Web、微信小游戏等平台 |
| **物理集成** | 基于 Rapier 的 2D 物理,支持编辑器可视化 |
| **可视化脚本** | 行为树和蓝图系统,适合策划使用 |
## 技术栈
- **运行时**: TypeScript, Rust, WebAssembly
- **渲染器**: WebGL 2.0, WGPU (计划中)
- **编辑器**: Tauri, React, Zustand
- **物理**: Rapier2D
- **构建**: pnpm, Turborepo, Rollup
## 许可证
ESEngine **完全免费开源**,采用 [MIT 协议](LICENSE)。无版税,无附加条件。
## 安装
### npm
核心是一个高性能的 **ECS实体-组件-系统)** 框架,配套 AI、网络、物理等可选模块
```bash
npm install @esengine/ecs-framework
```
### 编辑器
## 功能模块
从 [Releases](https://github.com/esengine/esengine/releases) 页面下载预编译版本(支持 Windows、macOS
| 模块 | 描述 | 需要渲染引擎 |
|------|------|:----------:|
| **ECS 核心** | 实体-组件-系统框架,支持响应式查询 | 否 |
| **行为树** | AI 行为树,支持可视化编辑 | 否 |
| **蓝图** | 可视化脚本系统 | 否 |
| **状态机** | 有限状态机 | 否 |
| **定时器** | 定时器和冷却系统 | 否 |
| **空间索引** | 空间查询(四叉树、网格) | 否 |
| **寻路** | A* 和导航网格寻路 | 否 |
| **网络** | 客户端/服务端网络通信 (TSRPC) | 否 |
> 所有框架模块都可以独立使用,无需依赖特定渲染引擎。
## 快速开始
### 使用 CLI推荐
在现有项目中添加 ECS 的最简单方式:
```bash
# 在项目目录中运行
npx @esengine/cli init
```
CLI 会自动检测项目类型Cocos Creator 2.x/3.x、LayaAir 3.x 或 Node.js并生成相应的集成代码。
### 手动配置
```typescript
import {
Core, Scene, Entity, Component, EntitySystem,
Matcher, Time, ECSComponent, ECSSystem
} from '@esengine/ecs-framework';
// 定义组件(纯数据)
@ECSComponent('Position')
class Position extends Component {
x = 0;
@@ -93,6 +87,7 @@ class Velocity extends Component {
dy = 0;
}
// 定义系统(逻辑)
@ECSSystem('Movement')
class MovementSystem extends EntitySystem {
constructor() {
@@ -120,7 +115,7 @@ player.addComponent(new Velocity());
Core.setScene(scene);
// 游戏循环
// 集成到你的游戏循环
function gameLoop(currentTime: number) {
Core.update(currentTime / 1000);
requestAnimationFrame(gameLoop);
@@ -128,109 +123,132 @@ function gameLoop(currentTime: number) {
requestAnimationFrame(gameLoop);
```
## 模块
## 与其他引擎配合使用
ESEngine 采用 Monorepo 组织,包含 50+ 个模块化包。按需引入即可。
ESEngine 的框架模块设计为可与你喜欢的渲染引擎配合使用:
### 核心安装
### 与 Cocos Creator 配合
```bash
npm install @esengine/ecs-framework # ECS 核心(可独立使用)
npm install @esengine/engine-core # 完整引擎模块系统
```typescript
import { Component as CCComponent, _decorator } from 'cc';
import { Core, Scene, Matcher, EntitySystem } from '@esengine/ecs-framework';
import { BehaviorTreeExecutionSystem } from '@esengine/behavior-tree';
const { ccclass } = _decorator;
@ccclass('GameManager')
export class GameManager extends CCComponent {
private ecsScene!: Scene;
start() {
Core.create();
this.ecsScene = new Scene();
// 添加 ECS 系统
this.ecsScene.addSystem(new BehaviorTreeExecutionSystem());
this.ecsScene.addSystem(new MyGameSystem());
Core.setScene(this.ecsScene);
}
update(dt: number) {
Core.update(dt);
}
}
```
### 常用模块
### 与 Laya 3.x 配合
```typescript
import { Core, Scene } from '@esengine/ecs-framework';
import { FSMSystem } from '@esengine/fsm';
const { regClass } = Laya;
@regClass()
export class ECSManager extends Laya.Script {
private ecsScene = new Scene();
onAwake(): void {
Core.create();
this.ecsScene.addSystem(new FSMSystem());
Core.setScene(this.ecsScene);
}
onUpdate(): void {
Core.update(Laya.timer.delta / 1000);
}
onDestroy(): void {
Core.destroy();
}
}
```
## 包列表
### 框架包(引擎无关)
这些包**零渲染依赖**,可与任何引擎配合使用:
```bash
npm install @esengine/ecs-framework # ECS 核心
npm install @esengine/behavior-tree # AI 行为树
npm install @esengine/blueprint # 可视化脚本
npm install @esengine/fsm # 状态机
npm install @esengine/timer # 定时器和冷却
npm install @esengine/spatial # 空间索引
npm install @esengine/pathfinding # 寻路
npm install @esengine/network # 网络
```
### ESEngine 运行时(可选)
如果你需要完整的引擎解决方案:
| 分类 | 包名 |
|------|------|
| **渲染** | `sprite`, `tilemap`, `particle`, `mesh-3d`, `fairygui` |
| **核心** | `engine-core`, `asset-system`, `material-system` |
| **渲染** | `sprite`, `tilemap`, `particle`, `camera`, `mesh-3d` |
| **物理** | `physics-rapier2d` |
| **AI 逻辑** | `behavior-tree`, `blueprint` |
| **网络** | `network`, `network-server` |
| **平台** | `platform-web`, `platform-wechat` |
<details>
<summary><b>查看全部 50+ 个包</b></summary>
### 编辑器(可选)
#### 核心
- `@esengine/ecs-framework` - ECS 框架核心
- `@esengine/math` - 向量、矩阵工具
- `@esengine/engine` - Rust/WASM 渲染器
- `@esengine/engine-core` - 模块生命周期
基于 Tauri 构建的可视化编辑器:
#### 运行时
- `@esengine/sprite` - 2D 精灵和动画
- `@esengine/tilemap` - 瓦片地图
- `@esengine/particle` - 粒子特效
- `@esengine/physics-rapier2d` - 2D 物理
- `@esengine/behavior-tree` - AI 行为树
- `@esengine/blueprint` - 可视化脚本
- `@esengine/camera` - 相机系统
- `@esengine/audio` - 音频播放
- `@esengine/fairygui` - FairyGUI 集成
- `@esengine/mesh-3d` - 3D 模型 (FBX/GLTF/OBJ)
- `@esengine/material-system` - 材质和着色器
- `@esengine/asset-system` - 资源管理
- `@esengine/world-streaming` - 大世界流式加载
- 从 [Releases](https://github.com/esengine/esengine/releases) 下载
- 支持行为树编辑、Tilemap 绘制、可视化脚本
#### 网络
- `@esengine/network` - 客户端 (TSRPC)
- `@esengine/network-server` - 服务端运行时
- `@esengine/network-protocols` - 共享协议
## 项目结构
#### 编辑器扩展
所有运行时模块都有对应的 `-editor` 包用于可视化编辑。
#### 平台
- `@esengine/platform-common` - 平台抽象层
- `@esengine/platform-web` - Web 运行时
- `@esengine/platform-wechat` - 微信小游戏
</details>
## 编辑器
ESEngine 编辑器是基于 Tauri 和 React 构建的跨平台桌面应用。
### 功能
- 场景层级和实体管理
- 组件检视器,支持自定义属性编辑器
- 资源浏览器,支持拖放
- Tilemap 编辑器,支持绘制和填充工具
- 行为树可视化编辑器
- 蓝图可视化脚本
- 材质和着色器编辑
- 内置性能分析器
- 多语言支持(英文、中文)
### 截图
![ESEngine Editor](screenshots/main_screetshot.png)
## 平台支持
| 平台 | 运行时 | 编辑器 |
|------|:------:|:------:|
| Web 浏览器 | ✓ | - |
| Windows | - | ✓ |
| macOS | - | ✓ |
| 微信小游戏 | 开发中 | - |
| Playable 可玩广告 | 计划中 | - |
| Android | 计划中 | - |
| iOS | 计划中 | - |
```
esengine/
├── packages/
│ ├── framework/ # 引擎无关模块(可发布到 NPM
│ │ ├── core/ # ECS 框架
│ │ ├── math/ # 数学工具
│ │ ├── behavior-tree/ # AI 行为树
│ │ ├── blueprint/ # 可视化脚本
│ │ ├── fsm/ # 有限状态机
│ │ ├── timer/ # 定时器系统
│ │ ├── spatial/ # 空间查询
│ │ ├── pathfinding/ # 寻路
│ │ ├── procgen/ # 程序化生成
│ │ └── network/ # 网络
│ │
│ ├── engine/ # ESEngine 运行时
│ ├── rendering/ # 渲染模块
│ ├── physics/ # 物理模块
│ ├── editor/ # 可视化编辑器
│ └── rust/ # WASM 渲染器
├── docs/ # 文档
└── examples/ # 示例
```
## 从源码构建
### 前置要求
- Node.js 18+
- pnpm 10+
- Rust 工具链(用于 WASM 渲染器)
- wasm-pack
### 安装
```bash
git clone https://github.com/esengine/esengine.git
cd esengine
@@ -238,55 +256,29 @@ cd esengine
pnpm install
pnpm build
# 可选:构建 WASM 渲染器
pnpm build:wasm
# 框架包类型检查
pnpm type-check:framework
# 运行测试
pnpm test
```
### 运行编辑器
```bash
cd packages/editor-app
pnpm tauri:dev
```
### 项目结构
```
esengine/
├── packages/
│ ├── core/ # ECS 框架 (@esengine/ecs-framework)
│ ├── math/ # 数学库 (@esengine/math)
│ ├── engine-core/ # 引擎生命周期管理
│ ├── sprite/ # 2D 精灵渲染
│ ├── tilemap/ # Tilemap 系统
│ ├── physics-rapier2d/ # 物理引擎
│ ├── behavior-tree/ # AI 行为树
│ ├── editor-app/ # 桌面编辑器 (Tauri)
│ └── ... # 其他模块
├── docs/ # 文档源码
├── examples/ # 示例项目
├── scripts/ # 构建工具
└── thirdparty/ # 第三方依赖
```
> **寻找 ECS 源码?** ECS 框架位于 `packages/core/`
## 文档
- [快速入门](https://esengine.cn/guide/getting-started.html)
- [架构指南](https://esengine.cn/guide/)
- [ECS 框架指南](./packages/framework/core/README.md)
- [行为树指南](./packages/framework/behavior-tree/README.md)
- [API 参考](https://esengine.cn/api/README)
## 社区
- [Discord](https://discord.gg/gCAgzXFW) - 国际社区
- [QQ 交流群](https://jq.qq.com/?_wv=1027&k=29w1Nud6) - 中文社区
- [Discord](https://discord.gg/gCAgzXFW) - 国际社区
- [GitHub Issues](https://github.com/esengine/esengine/issues) - Bug 反馈和功能建议
- [GitHub Discussions](https://github.com/esengine/esengine/discussions) - 问题和想法
## 贡献
欢迎贡献代码提交 PR 前请阅读贡献指南。
欢迎贡献代码提交 PR 前请阅读贡献指南。
1. Fork 仓库
2. 创建功能分支 (`git checkout -b feature/amazing-feature`)
@@ -296,10 +288,10 @@ esengine/
## 许可证
ESEngine 基于 [MIT 协议](LICENSE) 开源。
ESEngine 基于 [MIT 协议](LICENSE) 开源,个人和商业使用均免费
---
<p align="center">
由 ESEngine 团队用 ❤️ 打造
由 ESEngine 社区用心打造
</p>

View File

@@ -6,7 +6,7 @@ import { fileURLToPath } from 'url'
const __dirname = dirname(fileURLToPath(import.meta.url))
const corePackageJson = JSON.parse(
readFileSync(join(__dirname, '../../packages/core/package.json'), 'utf-8')
readFileSync(join(__dirname, '../../packages/framework/core/package.json'), 'utf-8')
)
// Import i18n messages
@@ -49,21 +49,6 @@ function createSidebar(t, prefix = '') {
{ text: t.sidebar.persistentEntity, link: `${prefix}/guide/persistent-entity` }
]
},
{
text: t.sidebar.behaviorTree,
link: `${prefix}/guide/behavior-tree/`,
items: [
{ text: t.sidebar.btGettingStarted, link: `${prefix}/guide/behavior-tree/getting-started` },
{ text: t.sidebar.btCoreConcepts, link: `${prefix}/guide/behavior-tree/core-concepts` },
{ text: t.sidebar.btEditorGuide, link: `${prefix}/guide/behavior-tree/editor-guide` },
{ text: t.sidebar.btEditorWorkflow, link: `${prefix}/guide/behavior-tree/editor-workflow` },
{ text: t.sidebar.btCustomActions, link: `${prefix}/guide/behavior-tree/custom-actions` },
{ text: t.sidebar.btCocosIntegration, link: `${prefix}/guide/behavior-tree/cocos-integration` },
{ text: t.sidebar.btLayaIntegration, link: `${prefix}/guide/behavior-tree/laya-integration` },
{ text: t.sidebar.btAdvancedUsage, link: `${prefix}/guide/behavior-tree/advanced-usage` },
{ text: t.sidebar.btBestPractices, link: `${prefix}/guide/behavior-tree/best-practices` }
]
},
{ text: t.sidebar.serialization, link: `${prefix}/guide/serialization` },
{ text: t.sidebar.eventSystem, link: `${prefix}/guide/event-system` },
{ text: t.sidebar.timeAndTimers, link: `${prefix}/guide/time-and-timers` },
@@ -89,6 +74,64 @@ function createSidebar(t, prefix = '') {
]
}
],
// 模块总览侧边栏 | Modules overview sidebar
[`${prefix}/modules/`]: [
{
text: t.sidebar.modulesOverview,
link: `${prefix}/modules/`,
items: [
{
text: t.sidebar.aiModules,
collapsed: false,
items: [
{ text: t.sidebar.behaviorTree, link: `${prefix}/modules/behavior-tree/` },
{ text: t.sidebar.fsm, link: `${prefix}/modules/fsm/` }
]
},
{
text: t.sidebar.gameplayModules,
collapsed: false,
items: [
{ text: t.sidebar.timer, link: `${prefix}/modules/timer/` },
{ text: t.sidebar.spatial, link: `${prefix}/modules/spatial/` },
{ text: t.sidebar.pathfinding, link: `${prefix}/modules/pathfinding/` }
]
},
{
text: t.sidebar.toolModules,
collapsed: false,
items: [
{ text: t.sidebar.blueprint, link: `${prefix}/modules/blueprint/` },
{ text: t.sidebar.procgen, link: `${prefix}/modules/procgen/` }
]
},
{
text: t.sidebar.networkModules,
collapsed: false,
items: [
{ text: t.sidebar.network, link: `${prefix}/modules/network/` }
]
}
]
}
],
// 行为树模块侧边栏 | Behavior tree module sidebar
[`${prefix}/modules/behavior-tree/`]: [
{
text: t.sidebar.behaviorTree,
items: [
{ text: t.sidebar.btGettingStarted, link: `${prefix}/modules/behavior-tree/getting-started` },
{ text: t.sidebar.btCoreConcepts, link: `${prefix}/modules/behavior-tree/core-concepts` },
{ text: t.sidebar.btEditorGuide, link: `${prefix}/modules/behavior-tree/editor-guide` },
{ text: t.sidebar.btEditorWorkflow, link: `${prefix}/modules/behavior-tree/editor-workflow` },
{ text: t.sidebar.btCustomActions, link: `${prefix}/modules/behavior-tree/custom-actions` },
{ text: t.sidebar.btCocosIntegration, link: `${prefix}/modules/behavior-tree/cocos-integration` },
{ text: t.sidebar.btLayaIntegration, link: `${prefix}/modules/behavior-tree/laya-integration` },
{ text: t.sidebar.btAdvancedUsage, link: `${prefix}/modules/behavior-tree/advanced-usage` },
{ text: t.sidebar.btBestPractices, link: `${prefix}/modules/behavior-tree/best-practices` }
]
}
],
[`${prefix}/examples/`]: [
{
text: t.sidebar.examples,
@@ -173,6 +216,7 @@ function createNav(t, prefix = '') {
{ text: t.nav.home, link: `${prefix}/` },
{ text: t.nav.quickStart, link: `${prefix}/guide/getting-started` },
{ text: t.nav.guide, link: `${prefix}/guide/` },
{ text: t.nav.modules, link: `${prefix}/modules/` },
{ text: t.nav.api, link: `${prefix}/api/README` },
{
text: t.nav.examples,

View File

@@ -3,6 +3,7 @@
"home": "Home",
"quickStart": "Quick Start",
"guide": "Guide",
"modules": "Modules",
"api": "API",
"examples": "Examples",
"workerDemo": "Worker System Demo",
@@ -54,7 +55,26 @@
"utilities": "Utilities",
"interfaces": "Interfaces",
"decorators": "Decorators",
"enums": "Enums"
"enums": "Enums",
"modulesOverview": "Modules Overview",
"aiModules": "AI Modules",
"gameplayModules": "Gameplay",
"toolModules": "Tools",
"networkModules": "Network",
"fsm": "State Machine (FSM)",
"fsmOverview": "Overview",
"timer": "Timer System",
"timerOverview": "Overview",
"spatial": "Spatial Index",
"spatialOverview": "Overview",
"pathfinding": "Pathfinding",
"pathfindingOverview": "Overview",
"blueprint": "Visual Scripting",
"blueprintOverview": "Overview",
"procgen": "Procedural Generation",
"procgenOverview": "Overview",
"network": "Network Sync",
"networkOverview": "Overview"
},
"home": {
"title": "ESEngine - High-performance TypeScript ECS Framework",

View File

@@ -3,6 +3,7 @@
"home": "首页",
"quickStart": "快速开始",
"guide": "指南",
"modules": "模块",
"api": "API",
"examples": "示例",
"workerDemo": "Worker系统演示",
@@ -54,7 +55,26 @@
"utilities": "工具类",
"interfaces": "接口",
"decorators": "装饰器",
"enums": "枚举"
"enums": "枚举",
"modulesOverview": "模块总览",
"aiModules": "AI 模块",
"gameplayModules": "游戏逻辑",
"toolModules": "工具模块",
"networkModules": "网络模块",
"fsm": "状态机 (FSM)",
"fsmOverview": "概述",
"timer": "定时器系统",
"timerOverview": "概述",
"spatial": "空间索引",
"spatialOverview": "概述",
"pathfinding": "寻路系统",
"pathfindingOverview": "概述",
"blueprint": "可视化脚本",
"blueprintOverview": "概述",
"procgen": "程序化生成",
"procgenOverview": "概述",
"network": "网络同步",
"networkOverview": "概述"
},
"home": {
"title": "ESEngine - 高性能 TypeScript ECS 框架",

View File

@@ -2,23 +2,24 @@
color-scheme: dark;
--vp-nav-height: 64px;
--es-bg-base: #1e1e1e;
--es-bg-elevated: #252526;
--es-bg-overlay: #2d2d2d;
--es-bg-input: #3c3c3c;
--es-bg-inset: #181818;
--es-bg-base: #1a1a1a;
--es-bg-elevated: #222222;
--es-bg-overlay: #2a2a2a;
--es-bg-input: #333333;
--es-bg-inset: #151515;
--es-bg-hover: #2a2d2e;
--es-bg-active: #37373d;
--es-bg-sidebar: #262626;
--es-bg-card: #2a2a2a;
--es-bg-header: #2d2d2d;
--es-bg-sidebar: #1e1e1e;
--es-bg-card: #242424;
--es-bg-header: #1e1e1e;
--es-text-primary: #cccccc;
--es-text-secondary: #9d9d9d;
--es-text-tertiary: #6a6a6a;
/* 提高文字对比度 | Improve text contrast */
--es-text-primary: #e0e0e0;
--es-text-secondary: #b0b0b0;
--es-text-tertiary: #888888;
--es-text-inverse: #ffffff;
--es-text-muted: #aaaaaa;
--es-text-dim: #6a6a6a;
--es-text-muted: #c0c0c0;
--es-text-dim: #888888;
--es-font-xs: 11px;
--es-font-sm: 12px;

View File

@@ -4,6 +4,36 @@
---
## v2.4.2 (2025-12-25)
### Features
- **IncrementalSerializer 实体过滤**: 增量序列化支持 `entityFilter` 选项 (#335)
- 创建快照时可按条件过滤实体
- 支持按标签、组件类型等自定义过滤逻辑
- 适用于只同步部分实体的场景(如只同步玩家)
```typescript
// 只快照玩家实体
const snapshot = IncrementalSerializer.createSnapshot(scene, {
entityFilter: (entity) => entity.tag === PLAYER_TAG
});
// 只快照有特定组件的实体
const snapshot = IncrementalSerializer.createSnapshot(scene, {
entityFilter: (entity) => entity.hasComponent(PlayerMarker)
});
```
### Refactor
- 优化 `PlatformWorkerPool` 代码规范,提取为独立模块 (#335)
- 优化 `WorkerEntitySystem` 实现,改进代码结构 (#334)
- 代码规范化与依赖清理 (#317)
- 代码结构优化,添加 `GlobalTypes.ts` 统一类型定义 (#316)
---
## v2.4.1 (2025-12-23)
### Bug Fixes

View File

@@ -4,6 +4,36 @@ This document records the version update history of the `@esengine/ecs-framework
---
## v2.4.2 (2025-12-25)
### Features
- **IncrementalSerializer Entity Filter**: Incremental serialization supports `entityFilter` option (#335)
- Filter entities by condition when creating snapshots
- Support custom filter logic by tag, component type, etc.
- Suitable for scenarios that only sync partial entities (e.g., only sync players)
```typescript
// Only snapshot player entities
const snapshot = IncrementalSerializer.createSnapshot(scene, {
entityFilter: (entity) => entity.tag === PLAYER_TAG
});
// Only snapshot entities with specific component
const snapshot = IncrementalSerializer.createSnapshot(scene, {
entityFilter: (entity) => entity.hasComponent(PlayerMarker)
});
```
### Refactor
- Optimize `PlatformWorkerPool` code style, extract as standalone module (#335)
- Optimize `WorkerEntitySystem` implementation, improve code structure (#334)
- Code standardization and dependency cleanup (#317)
- Code structure optimization, add `GlobalTypes.ts` for unified type definitions (#316)
---
## v2.4.1 (2025-12-23)
### Bug Fixes

View File

@@ -4,7 +4,24 @@ This guide will help you get started with ECS Framework, from installation to cr
## Installation
### NPM Installation
### Using CLI (Recommended)
The easiest way to add ECS to your existing project:
```bash
# In your project directory
npx @esengine/cli init
```
The CLI automatically detects your project type (Cocos Creator 2.x/3.x, LayaAir 3.x, or Node.js) and generates the necessary integration code, including:
- `ECSManager` component/script - Manages ECS lifecycle
- Example components and systems - Helps you get started quickly
- Automatic dependency installation
### Manual NPM Installation
If you prefer manual configuration:
```bash
# Using npm
@@ -333,27 +350,39 @@ function gameLoop(deltaTime: number) {
## Game Engine Integration
### Laya Engine Integration
### Laya 3.x Engine Integration
Using `Laya.Script` component to manage ECS lifecycle is recommended:
```typescript
import { Stage } from "laya/display/Stage";
import { Laya } from "Laya";
import { Core } from '@esengine/ecs-framework';
import { Core, Scene } from '@esengine/ecs-framework';
// Initialize Laya
Laya.init(800, 600).then(() => {
// Initialize ECS
Core.create(true);
Core.setScene(new GameScene());
const { regClass } = Laya;
// Start game loop
Laya.timer.frameLoop(1, this, () => {
const deltaTime = Laya.timer.delta / 1000;
Core.update(deltaTime); // Auto-updates global services and scene
});
});
@regClass()
export class ECSManager extends Laya.Script {
private ecsScene = new GameScene();
onAwake(): void {
// Initialize ECS
Core.create({ debug: true });
Core.setScene(this.ecsScene);
}
onUpdate(): void {
// Auto-updates global services and scene
Core.update(Laya.timer.delta / 1000);
}
onDestroy(): void {
// Cleanup resources
Core.destroy();
}
}
```
In Laya IDE, attach the `ECSManager` script to a node in your scene.
### Cocos Creator Integration
```typescript

View File

@@ -0,0 +1,404 @@
# Blueprint Visual Scripting
`@esengine/blueprint` provides a full-featured visual scripting system supporting node-based programming, event-driven execution, and blueprint composition.
## Installation
```bash
npm install @esengine/blueprint
```
## Quick Start
```typescript
import {
createBlueprintSystem,
createBlueprintComponentData,
NodeRegistry,
RegisterNode
} from '@esengine/blueprint';
// Create blueprint system
const blueprintSystem = createBlueprintSystem(scene);
// Load blueprint asset
const blueprint = await loadBlueprintAsset('player.bp');
// Create blueprint component data
const componentData = createBlueprintComponentData();
componentData.blueprintAsset = blueprint;
// Update in game loop
function gameLoop(dt: number) {
blueprintSystem.process(entities, dt);
}
```
## Core Concepts
### Blueprint Asset Structure
Blueprints are saved as `.bp` files:
```typescript
interface BlueprintAsset {
version: number; // Format version
type: 'blueprint'; // Asset type
metadata: BlueprintMetadata; // Metadata
variables: BlueprintVariable[]; // Variable definitions
nodes: BlueprintNode[]; // Node instances
connections: BlueprintConnection[]; // Connections
}
```
### Node Categories
| Category | Description | Color |
|----------|-------------|-------|
| `event` | Event nodes (entry points) | Red |
| `flow` | Flow control | Gray |
| `entity` | Entity operations | Blue |
| `component` | Component access | Cyan |
| `math` | Math operations | Green |
| `logic` | Logic operations | Red |
| `variable` | Variable access | Purple |
| `time` | Time utilities | Cyan |
| `debug` | Debug utilities | Gray |
### Pin Types
Nodes connect through pins:
```typescript
interface BlueprintPinDefinition {
name: string; // Pin name
type: PinDataType; // Data type
direction: 'input' | 'output';
isExec?: boolean; // Execution pin
defaultValue?: unknown;
}
type PinDataType =
| 'exec' // Execution flow
| 'boolean' // Boolean
| 'number' // Number
| 'string' // String
| 'vector2' // 2D vector
| 'vector3' // 3D vector
| 'entity' // Entity reference
| 'component' // Component reference
| 'any'; // Any type
```
### Variable Scopes
```typescript
type VariableScope =
| 'local' // Per execution
| 'instance' // Per entity
| 'global'; // Shared globally
```
## Virtual Machine API
### BlueprintVM
The virtual machine executes blueprint graphs:
```typescript
import { BlueprintVM } from '@esengine/blueprint';
const vm = new BlueprintVM(blueprintAsset, entity, scene);
vm.start(); // Start (triggers BeginPlay)
vm.tick(deltaTime); // Update (triggers Tick)
vm.stop(); // Stop (triggers EndPlay)
vm.pause();
vm.resume();
// Trigger events
vm.triggerEvent('EventCollision', { other: otherEntity });
vm.triggerCustomEvent('OnDamage', { amount: 50 });
// Debug mode
vm.debug = true;
```
### Execution Context
```typescript
interface ExecutionContext {
blueprint: BlueprintAsset;
entity: Entity;
scene: IScene;
deltaTime: number;
time: number;
getInput<T>(nodeId: string, pinName: string): T;
setOutput(nodeId: string, pinName: string, value: unknown): void;
getVariable<T>(name: string): T;
setVariable(name: string, value: unknown): void;
}
```
### Execution Result
```typescript
interface ExecutionResult {
outputs?: Record<string, unknown>; // Output values
nextExec?: string | null; // Next exec pin
delay?: number; // Delay execution (ms)
yield?: boolean; // Pause until next frame
error?: string; // Error message
}
```
## Custom Nodes
### Define Node Template
```typescript
import { BlueprintNodeTemplate } from '@esengine/blueprint';
const MyNodeTemplate: BlueprintNodeTemplate = {
type: 'MyCustomNode',
title: 'My Custom Node',
category: 'custom',
description: 'A custom node example',
keywords: ['custom', 'example'],
inputs: [
{ name: 'exec', type: 'exec', direction: 'input', isExec: true },
{ name: 'value', type: 'number', direction: 'input', defaultValue: 0 }
],
outputs: [
{ name: 'exec', type: 'exec', direction: 'output', isExec: true },
{ name: 'result', type: 'number', direction: 'output' }
]
};
```
### Implement Node Executor
```typescript
import { INodeExecutor, RegisterNode } from '@esengine/blueprint';
@RegisterNode(MyNodeTemplate)
class MyNodeExecutor implements INodeExecutor {
execute(node: BlueprintNode, context: ExecutionContext): ExecutionResult {
const value = context.getInput<number>(node.id, 'value');
const result = value * 2;
return {
outputs: { result },
nextExec: 'exec'
};
}
}
```
### Registration Methods
```typescript
// Method 1: Decorator
@RegisterNode(MyNodeTemplate)
class MyNodeExecutor implements INodeExecutor { ... }
// Method 2: Manual registration
NodeRegistry.instance.register(MyNodeTemplate, new MyNodeExecutor());
```
## Node Registry
```typescript
import { NodeRegistry } from '@esengine/blueprint';
const registry = NodeRegistry.instance;
const allTemplates = registry.getAllTemplates();
const mathNodes = registry.getTemplatesByCategory('math');
const results = registry.searchTemplates('add');
if (registry.has('MyCustomNode')) { ... }
```
## Built-in Nodes
### Event Nodes
| Node | Description |
|------|-------------|
| `EventBeginPlay` | Triggered on blueprint start |
| `EventTick` | Triggered every frame |
| `EventEndPlay` | Triggered on blueprint stop |
| `EventCollision` | Triggered on collision |
| `EventInput` | Triggered on input |
| `EventTimer` | Triggered by timer |
### Time Nodes
| Node | Description |
|------|-------------|
| `Delay` | Delay execution |
| `GetDeltaTime` | Get frame delta |
| `GetTime` | Get total runtime |
### Math Nodes
| Node | Description |
|------|-------------|
| `Add`, `Subtract`, `Multiply`, `Divide` | Basic operations |
| `Abs`, `Clamp`, `Lerp`, `Min`, `Max` | Utility functions |
### Debug Nodes
| Node | Description |
|------|-------------|
| `Print` | Print to console |
## Blueprint Composition
### Blueprint Fragments
Encapsulate reusable logic as fragments:
```typescript
import { createFragment } from '@esengine/blueprint';
const healthFragment = createFragment('HealthSystem', {
inputs: [
{ name: 'damage', type: 'number', internalNodeId: 'input1', internalPinName: 'value' }
],
outputs: [
{ name: 'isDead', type: 'boolean', internalNodeId: 'output1', internalPinName: 'value' }
],
graph: { nodes: [...], connections: [...], variables: [...] }
});
```
### Compose Blueprints
```typescript
import { createComposer, FragmentRegistry } from '@esengine/blueprint';
// Register fragments
FragmentRegistry.instance.register('health', healthFragment);
FragmentRegistry.instance.register('movement', movementFragment);
// Create composer
const composer = createComposer('PlayerBlueprint');
// Add fragments to slots
composer.addFragment(healthFragment, 'slot1', { position: { x: 0, y: 0 } });
composer.addFragment(movementFragment, 'slot2', { position: { x: 400, y: 0 } });
// Connect slots
composer.connect('slot1', 'onDeath', 'slot2', 'disable');
// Validate
const validation = composer.validate();
if (!validation.isValid) {
console.error(validation.errors);
}
// Compile to blueprint
const blueprint = composer.compile();
```
## Trigger System
### Define Trigger Conditions
```typescript
import { TriggerCondition, TriggerDispatcher } from '@esengine/blueprint';
const lowHealthCondition: TriggerCondition = {
type: 'comparison',
left: { type: 'variable', name: 'health' },
operator: '<',
right: { type: 'constant', value: 20 }
};
```
### Use Trigger Dispatcher
```typescript
const dispatcher = new TriggerDispatcher();
dispatcher.register('lowHealth', lowHealthCondition, (context) => {
context.triggerEvent('OnLowHealth');
});
dispatcher.evaluate(context);
```
## ECS Integration
### Using Blueprint System
```typescript
import { createBlueprintSystem } from '@esengine/blueprint';
class GameScene {
private blueprintSystem: BlueprintSystem;
initialize() {
this.blueprintSystem = createBlueprintSystem(this.scene);
}
update(dt: number) {
this.blueprintSystem.process(this.entities, dt);
}
}
```
### Triggering Blueprint Events
```typescript
import { triggerBlueprintEvent, triggerCustomBlueprintEvent } from '@esengine/blueprint';
triggerBlueprintEvent(entity, 'Collision', { other: otherEntity });
triggerCustomBlueprintEvent(entity, 'OnPickup', { item: itemEntity });
```
## Serialization
### Save Blueprint
```typescript
import { validateBlueprintAsset } from '@esengine/blueprint';
function saveBlueprint(blueprint: BlueprintAsset, path: string): void {
if (!validateBlueprintAsset(blueprint)) {
throw new Error('Invalid blueprint structure');
}
const json = JSON.stringify(blueprint, null, 2);
fs.writeFileSync(path, json);
}
```
### Load Blueprint
```typescript
async function loadBlueprint(path: string): Promise<BlueprintAsset> {
const json = await fs.readFile(path, 'utf-8');
const asset = JSON.parse(json);
if (!validateBlueprintAsset(asset)) {
throw new Error('Invalid blueprint file');
}
return asset;
}
```
## Best Practices
1. **Use fragments for reusable logic**
2. **Choose appropriate variable scopes**
- `local`: Temporary calculations
- `instance`: Entity state (e.g., health)
- `global`: Game-wide state
3. **Avoid infinite loops** - VM has max steps per frame (default 1000)
4. **Debug techniques**
- Enable `vm.debug = true` for execution logs
- Use Print nodes for intermediate values
5. **Performance optimization**
- Pure nodes (`isPure: true`) cache outputs
- Avoid heavy computation in Tick

View File

@@ -0,0 +1,316 @@
# State Machine (FSM)
`@esengine/fsm` provides a type-safe finite state machine implementation for characters, AI, or any scenario requiring state management.
## Installation
```bash
npm install @esengine/fsm
```
## Quick Start
```typescript
import { createStateMachine } from '@esengine/fsm';
// Define state types
type PlayerState = 'idle' | 'walk' | 'run' | 'jump';
// Create state machine
const fsm = createStateMachine<PlayerState>('idle');
// Define states with callbacks
fsm.defineState('idle', {
onEnter: (ctx, from) => console.log(`Entered idle from ${from}`),
onExit: (ctx, to) => console.log(`Exiting idle to ${to}`),
onUpdate: (ctx, dt) => { /* Update every frame */ }
});
fsm.defineState('walk', {
onEnter: () => console.log('Started walking')
});
// Manual transition
fsm.transition('walk');
console.log(fsm.current); // 'walk'
```
## Core Concepts
### State Configuration
Each state can be configured with the following callbacks:
```typescript
interface StateConfig<TState, TContext> {
name: TState; // State name
onEnter?: (context: TContext, from: TState | null) => void; // Enter callback
onExit?: (context: TContext, to: TState) => void; // Exit callback
onUpdate?: (context: TContext, deltaTime: number) => void; // Update callback
tags?: string[]; // State tags
metadata?: Record<string, unknown>; // Metadata
}
```
### Transition Conditions
Define conditional state transitions:
```typescript
interface Context {
isMoving: boolean;
isRunning: boolean;
isGrounded: boolean;
}
const fsm = createStateMachine<PlayerState, Context>('idle', {
context: { isMoving: false, isRunning: false, isGrounded: true }
});
// Define transition conditions
fsm.defineTransition('idle', 'walk', (ctx) => ctx.isMoving);
fsm.defineTransition('walk', 'run', (ctx) => ctx.isRunning);
fsm.defineTransition('walk', 'idle', (ctx) => !ctx.isMoving);
// Automatically evaluate and execute matching transitions
fsm.evaluateTransitions();
```
### Transition Priority
When multiple transitions are valid, higher priority executes first:
```typescript
// Higher priority number = higher priority
fsm.defineTransition('idle', 'attack', (ctx) => ctx.isAttacking, 10);
fsm.defineTransition('idle', 'walk', (ctx) => ctx.isMoving, 1);
// If both conditions are met, 'attack' (priority 10) is tried first
```
## API Reference
### createStateMachine
```typescript
function createStateMachine<TState extends string, TContext = unknown>(
initialState: TState,
options?: StateMachineOptions<TContext>
): IStateMachine<TState, TContext>
```
**Parameters:**
- `initialState` - Initial state
- `options.context` - Context object, accessible in callbacks
- `options.maxHistorySize` - Maximum history entries (default 100)
- `options.enableHistory` - Enable history tracking (default true)
### State Machine Properties
| Property | Type | Description |
|----------|------|-------------|
| `current` | `TState` | Current state |
| `previous` | `TState \| null` | Previous state |
| `context` | `TContext` | Context object |
| `isTransitioning` | `boolean` | Whether currently transitioning |
| `currentStateDuration` | `number` | Current state duration (ms) |
### State Machine Methods
#### State Definition
```typescript
// Define state
fsm.defineState('idle', {
onEnter: (ctx, from) => {},
onExit: (ctx, to) => {},
onUpdate: (ctx, dt) => {}
});
// Check if state exists
fsm.hasState('idle'); // true
// Get state configuration
fsm.getStateConfig('idle');
// Get all states
fsm.getStates(); // ['idle', 'walk', ...]
```
#### Transition Operations
```typescript
// Define transition
fsm.defineTransition('idle', 'walk', condition, priority);
// Remove transition
fsm.removeTransition('idle', 'walk');
// Get transitions from state
fsm.getTransitionsFrom('idle');
// Check if transition is possible
fsm.canTransition('walk'); // true/false
// Manual transition
fsm.transition('walk');
// Force transition (ignore conditions)
fsm.transition('walk', true);
// Auto-evaluate transition conditions
fsm.evaluateTransitions();
```
#### Lifecycle
```typescript
// Update state machine (calls current state's onUpdate)
fsm.update(deltaTime);
// Reset state machine
fsm.reset(); // Reset to current state
fsm.reset('idle'); // Reset to specified state
```
#### Event Listeners
```typescript
// Listen to entering specific state
const unsubscribe = fsm.onEnter('walk', (from) => {
console.log(`Entered walk from ${from}`);
});
// Listen to exiting specific state
fsm.onExit('walk', (to) => {
console.log(`Exiting walk to ${to}`);
});
// Listen to any state change
fsm.onChange((event) => {
console.log(`${event.from} -> ${event.to} at ${event.timestamp}`);
});
// Unsubscribe
unsubscribe();
```
#### Debugging
```typescript
// Get state history
const history = fsm.getHistory();
// [{ from: 'idle', to: 'walk', timestamp: 1234567890 }, ...]
// Clear history
fsm.clearHistory();
// Get debug info
const info = fsm.getDebugInfo();
// { current, previous, duration, stateCount, transitionCount, historySize }
```
## Practical Examples
### Character State Machine
```typescript
import { createStateMachine } from '@esengine/fsm';
type CharacterState = 'idle' | 'walk' | 'run' | 'jump' | 'fall' | 'attack';
interface CharacterContext {
velocity: { x: number; y: number };
isGrounded: boolean;
isAttacking: boolean;
speed: number;
}
const characterFSM = createStateMachine<CharacterState, CharacterContext>('idle', {
context: {
velocity: { x: 0, y: 0 },
isGrounded: true,
isAttacking: false,
speed: 0
}
});
// Define states
characterFSM.defineState('idle', {
onEnter: (ctx) => { ctx.speed = 0; }
});
characterFSM.defineState('walk', {
onEnter: (ctx) => { ctx.speed = 100; }
});
characterFSM.defineState('run', {
onEnter: (ctx) => { ctx.speed = 200; }
});
// Define transitions
characterFSM.defineTransition('idle', 'walk', (ctx) => Math.abs(ctx.velocity.x) > 0);
characterFSM.defineTransition('walk', 'idle', (ctx) => ctx.velocity.x === 0);
characterFSM.defineTransition('walk', 'run', (ctx) => Math.abs(ctx.velocity.x) > 150);
// Jump has highest priority
characterFSM.defineTransition('idle', 'jump', (ctx) => !ctx.isGrounded, 10);
characterFSM.defineTransition('walk', 'jump', (ctx) => !ctx.isGrounded, 10);
// Game loop usage
function gameUpdate(dt: number) {
// Update context
characterFSM.context.velocity.x = getInputVelocity();
characterFSM.context.isGrounded = checkGrounded();
// Evaluate transitions
characterFSM.evaluateTransitions();
// Update current state
characterFSM.update(dt);
}
```
### ECS Integration
```typescript
import { Component, EntitySystem, Matcher } from '@esengine/ecs-framework';
import { createStateMachine, type IStateMachine } from '@esengine/fsm';
// State machine component
class FSMComponent extends Component {
fsm: IStateMachine<string>;
constructor(initialState: string) {
super();
this.fsm = createStateMachine(initialState);
}
}
// State machine system
class FSMSystem extends EntitySystem {
constructor() {
super(Matcher.all(FSMComponent));
}
protected processEntity(entity: Entity, dt: number): void {
const fsmComp = entity.getComponent(FSMComponent);
fsmComp.fsm.evaluateTransitions();
fsmComp.fsm.update(dt);
}
}
```
## Blueprint Nodes
The FSM module provides blueprint nodes for visual scripting:
- `GetCurrentState` - Get current state
- `TransitionTo` - Transition to specified state
- `CanTransition` - Check if transition is possible
- `IsInState` - Check if in specified state
- `WasInState` - Check if was ever in specified state
- `GetStateDuration` - Get state duration
- `EvaluateTransitions` - Evaluate transition conditions
- `ResetStateMachine` - Reset state machine

54
docs/en/modules/index.md Normal file
View File

@@ -0,0 +1,54 @@
# Modules
ESEngine provides a rich set of modules that can be imported as needed.
## Module List
### AI Modules
| Module | Package | Description |
|--------|---------|-------------|
| [Behavior Tree](/en/modules/behavior-tree/) | `@esengine/behavior-tree` | AI behavior tree with visual editor |
| [State Machine](/en/modules/fsm/) | `@esengine/fsm` | Finite state machine for character/AI states |
### Gameplay
| Module | Package | Description |
|--------|---------|-------------|
| [Timer](/en/modules/timer/) | `@esengine/timer` | Timer and cooldown system |
| [Spatial](/en/modules/spatial/) | `@esengine/spatial` | Spatial queries, AOI management |
| [Pathfinding](/en/modules/pathfinding/) | `@esengine/pathfinding` | A* pathfinding, NavMesh navigation |
### Tools
| Module | Package | Description |
|--------|---------|-------------|
| [Blueprint](/en/modules/blueprint/) | `@esengine/blueprint` | Visual scripting system |
| [Procgen](/en/modules/procgen/) | `@esengine/procgen` | Noise functions, random utilities |
### Network
| Module | Package | Description |
|--------|---------|-------------|
| [Network](/en/modules/network/) | `@esengine/network` | Multiplayer game networking |
## Installation
All modules can be installed independently:
```bash
# Install a single module
npm install @esengine/behavior-tree
# Or use CLI to add to existing project
npx @esengine/cli add behavior-tree
```
## Platform Compatibility
All modules are pure TypeScript and compatible with:
- Cocos Creator 3.x
- Laya 3.x
- Node.js
- Browser

View File

@@ -0,0 +1,299 @@
# Pathfinding System
`@esengine/pathfinding` provides a complete 2D pathfinding solution including A* algorithm, grid maps, navigation meshes, and path smoothing.
## Installation
```bash
npm install @esengine/pathfinding
```
## Quick Start
### Grid Map Pathfinding
```typescript
import { createGridMap, createAStarPathfinder } from '@esengine/pathfinding';
// Create 20x20 grid
const grid = createGridMap(20, 20);
// Set obstacles
grid.setWalkable(5, 5, false);
grid.setWalkable(5, 6, false);
// Create pathfinder
const pathfinder = createAStarPathfinder(grid);
// Find path
const result = pathfinder.findPath(0, 0, 15, 15);
if (result.found) {
console.log('Path found!');
console.log('Path:', result.path);
console.log('Cost:', result.cost);
}
```
### NavMesh Pathfinding
```typescript
import { createNavMesh } from '@esengine/pathfinding';
const navmesh = createNavMesh();
// Add polygon areas
navmesh.addPolygon([
{ x: 0, y: 0 }, { x: 10, y: 0 },
{ x: 10, y: 10 }, { x: 0, y: 10 }
]);
navmesh.addPolygon([
{ x: 10, y: 0 }, { x: 20, y: 0 },
{ x: 20, y: 10 }, { x: 10, y: 10 }
]);
// Auto-build connections
navmesh.build();
// Find path
const result = navmesh.findPath(1, 1, 18, 8);
```
## Core Concepts
### IPathResult
```typescript
interface IPathResult {
readonly found: boolean; // Path found
readonly path: readonly IPoint[];// Path points
readonly cost: number; // Total cost
readonly nodesSearched: number; // Nodes searched
}
```
### IPathfindingOptions
```typescript
interface IPathfindingOptions {
maxNodes?: number; // Max search nodes (default 10000)
heuristicWeight?: number; // Heuristic weight (>1 faster but may be suboptimal)
allowDiagonal?: boolean; // Allow diagonal movement (default true)
avoidCorners?: boolean; // Avoid corner cutting (default true)
}
```
## Heuristic Functions
| Function | Use Case | Description |
|----------|----------|-------------|
| `manhattanDistance` | 4-directional | Manhattan distance |
| `euclideanDistance` | Any direction | Euclidean distance |
| `chebyshevDistance` | 8-directional | Diagonal cost = 1 |
| `octileDistance` | 8-directional | Diagonal cost = √2 (default) |
## Grid Map API
### createGridMap
```typescript
function createGridMap(
width: number,
height: number,
options?: IGridMapOptions
): GridMap
```
**Options:**
| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `allowDiagonal` | `boolean` | `true` | Allow diagonal movement |
| `diagonalCost` | `number` | `√2` | Diagonal movement cost |
| `avoidCorners` | `boolean` | `true` | Avoid corner cutting |
| `heuristic` | `HeuristicFunction` | `octileDistance` | Heuristic function |
### Map Operations
```typescript
// Check/set walkability
grid.isWalkable(x, y);
grid.setWalkable(x, y, false);
// Set movement cost (e.g., swamp, sand)
grid.setCost(x, y, 2);
// Set rectangle region
grid.setRectWalkable(0, 0, 5, 5, false);
// Load from array (0=walkable, non-0=blocked)
grid.loadFromArray([
[0, 0, 0, 1, 0],
[0, 1, 0, 1, 0]
]);
// Load from string (.=walkable, #=blocked)
grid.loadFromString(`
.....
.#.#.
`);
// Export and reset
console.log(grid.toString());
grid.reset();
```
## A* Pathfinder API
```typescript
const pathfinder = createAStarPathfinder(grid);
const result = pathfinder.findPath(
startX, startY,
endX, endY,
{ maxNodes: 5000, heuristicWeight: 1.5 }
);
// Pathfinder is reusable
pathfinder.findPath(0, 0, 10, 10);
pathfinder.findPath(5, 5, 15, 15);
```
## NavMesh API
```typescript
const navmesh = createNavMesh();
// Add convex polygons
const id1 = navmesh.addPolygon(vertices1);
const id2 = navmesh.addPolygon(vertices2);
// Auto-detect shared edges
navmesh.build();
// Or manually set connections
navmesh.setConnection(id1, id2, {
left: { x: 10, y: 0 },
right: { x: 10, y: 10 }
});
// Query and pathfind
const polygon = navmesh.findPolygonAt(5, 5);
navmesh.isWalkable(5, 5);
const result = navmesh.findPath(1, 1, 18, 8);
```
## Path Smoothing
### Line of Sight Smoothing
Remove unnecessary waypoints:
```typescript
import { createLineOfSightSmoother } from '@esengine/pathfinding';
const smoother = createLineOfSightSmoother();
const smoothedPath = smoother.smooth(result.path, grid);
```
### Curve Smoothing
Catmull-Rom spline:
```typescript
import { createCatmullRomSmoother } from '@esengine/pathfinding';
const smoother = createCatmullRomSmoother(5, 0.5);
const curvedPath = smoother.smooth(result.path, grid);
```
### Combined Smoothing
```typescript
import { createCombinedSmoother } from '@esengine/pathfinding';
const smoother = createCombinedSmoother(5, 0.5);
const finalPath = smoother.smooth(result.path, grid);
```
### Line of Sight Functions
```typescript
import { bresenhamLineOfSight, raycastLineOfSight } from '@esengine/pathfinding';
const hasLOS = bresenhamLineOfSight(x1, y1, x2, y2, grid);
const hasLOS2 = raycastLineOfSight(x1, y1, x2, y2, grid, 0.5);
```
## Practical Examples
### Dynamic Obstacles
```typescript
class DynamicPathfinding {
private grid: GridMap;
private pathfinder: AStarPathfinder;
private dynamicObstacles: Set<string> = new Set();
addDynamicObstacle(x: number, y: number): void {
this.dynamicObstacles.add(`${x},${y}`);
this.grid.setWalkable(x, y, false);
}
removeDynamicObstacle(x: number, y: number): void {
this.dynamicObstacles.delete(`${x},${y}`);
this.grid.setWalkable(x, y, true);
}
}
```
### Terrain Costs
```typescript
const grid = createGridMap(50, 50);
// Normal ground - cost 1 (default)
// Sand - cost 2
for (let y = 10; y < 20; y++) {
for (let x = 0; x < 50; x++) {
grid.setCost(x, y, 2);
}
}
// Swamp - cost 4
for (let y = 30; y < 35; y++) {
for (let x = 20; x < 30; x++) {
grid.setCost(x, y, 4);
}
}
```
## Blueprint Nodes
- `FindPath` - Find path
- `FindPathSmooth` - Find and smooth path
- `IsWalkable` - Check walkability
- `GetPathLength` - Get path point count
- `GetPathDistance` - Get total path distance
- `GetPathPoint` - Get specific path point
- `MoveAlongPath` - Move along path
- `HasLineOfSight` - Check line of sight
## Performance Tips
1. **Limit search range**: `{ maxNodes: 1000 }`
2. **Use heuristic weight**: `{ heuristicWeight: 1.5 }` (faster but may not be optimal)
3. **Reuse pathfinder instances**
4. **Use NavMesh for complex terrain**
5. **Choose appropriate heuristic for movement type**
## Grid vs NavMesh
| Feature | GridMap | NavMesh |
|---------|---------|---------|
| Use Case | Regular tile maps | Complex polygon terrain |
| Memory | Higher (width × height) | Lower (polygon count) |
| Precision | Grid-aligned | Continuous coordinates |
| Dynamic Updates | Easy | Requires rebuild |
| Setup Complexity | Simple | More complex |

View File

@@ -0,0 +1,396 @@
# Procedural Generation (Procgen)
`@esengine/procgen` provides core tools for procedural content generation, including noise functions, seeded random numbers, and various random utilities.
## Installation
```bash
npm install @esengine/procgen
```
## Quick Start
### Noise Generation
```typescript
import { createPerlinNoise, createFBM } from '@esengine/procgen';
// Create Perlin noise
const perlin = createPerlinNoise(12345); // seed
// Sample 2D noise
const value = perlin.noise2D(x * 0.1, y * 0.1);
console.log(value); // [-1, 1]
// Use FBM for more natural results
const fbm = createFBM(perlin, {
octaves: 6,
persistence: 0.5
});
const height = fbm.noise2D(x * 0.01, y * 0.01);
```
### Seeded Random
```typescript
import { createSeededRandom } from '@esengine/procgen';
// Create deterministic random generator
const rng = createSeededRandom(42);
// Same seed always produces same sequence
console.log(rng.next()); // 0.xxx
console.log(rng.nextInt(1, 100)); // 1-100
console.log(rng.nextBool(0.3)); // 30% true
```
### Weighted Random
```typescript
import { createWeightedRandom, createSeededRandom } from '@esengine/procgen';
const rng = createSeededRandom(42);
const loot = createWeightedRandom([
{ value: 'common', weight: 60 },
{ value: 'uncommon', weight: 25 },
{ value: 'rare', weight: 10 },
{ value: 'legendary', weight: 5 }
]);
const drop = loot.pick(rng);
console.log(drop); // Likely 'common'
```
## Noise Functions
### Perlin Noise
Classic gradient noise, output range [-1, 1]:
```typescript
import { createPerlinNoise } from '@esengine/procgen';
const perlin = createPerlinNoise(seed);
const value2D = perlin.noise2D(x, y);
const value3D = perlin.noise3D(x, y, z);
```
### Simplex Noise
Faster than Perlin, less directional bias:
```typescript
import { createSimplexNoise } from '@esengine/procgen';
const simplex = createSimplexNoise(seed);
const value = simplex.noise2D(x, y);
```
### Worley Noise
Cell-based noise for stone, cell textures:
```typescript
import { createWorleyNoise } from '@esengine/procgen';
const worley = createWorleyNoise(seed);
const distance = worley.noise2D(x, y);
```
### FBM (Fractal Brownian Motion)
Layer multiple noise octaves for richer detail:
```typescript
import { createPerlinNoise, createFBM } from '@esengine/procgen';
const baseNoise = createPerlinNoise(seed);
const fbm = createFBM(baseNoise, {
octaves: 6, // Layer count (more = richer detail)
lacunarity: 2.0, // Frequency multiplier
persistence: 0.5, // Amplitude decay
frequency: 1.0, // Initial frequency
amplitude: 1.0 // Initial amplitude
});
// Standard FBM
const value = fbm.noise2D(x, y);
// Ridged FBM (for mountains)
const ridged = fbm.ridged2D(x, y);
// Turbulence
const turb = fbm.turbulence2D(x, y);
// Billowed (for clouds)
const cloud = fbm.billowed2D(x, y);
```
## Seeded Random API
### SeededRandom
Deterministic PRNG based on xorshift128+:
```typescript
import { createSeededRandom } from '@esengine/procgen';
const rng = createSeededRandom(42);
```
### Basic Methods
```typescript
rng.next(); // [0, 1) float
rng.nextInt(1, 10); // [min, max] integer
rng.nextFloat(0, 100); // [min, max) float
rng.nextBool(); // 50%
rng.nextBool(0.3); // 30%
rng.reset(); // Reset to initial state
```
### Distribution Methods
```typescript
// Normal distribution (Gaussian)
rng.nextGaussian(); // mean 0, stdDev 1
rng.nextGaussian(100, 15); // mean 100, stdDev 15
// Exponential distribution
rng.nextExponential(); // λ = 1
rng.nextExponential(0.5); // λ = 0.5
```
### Geometry Methods
```typescript
// Uniform point in circle
const point = rng.nextPointInCircle(50); // { x, y }
// Point on circle edge
const edge = rng.nextPointOnCircle(50); // { x, y }
// Uniform point in sphere
const point3D = rng.nextPointInSphere(50); // { x, y, z }
// Random direction vector
const dir = rng.nextDirection2D(); // { x, y }, length 1
```
## Weighted Random API
### WeightedRandom
Precomputed cumulative weights for efficient selection:
```typescript
import { createWeightedRandom } from '@esengine/procgen';
const selector = createWeightedRandom([
{ value: 'apple', weight: 5 },
{ value: 'banana', weight: 3 },
{ value: 'cherry', weight: 2 }
]);
const result = selector.pick(rng);
const result2 = selector.pickRandom(); // Uses Math.random
console.log(selector.getProbability(0)); // 0.5 (5/10)
console.log(selector.size); // 3
console.log(selector.totalWeight); // 10
```
### Convenience Functions
```typescript
import { weightedPick, weightedPickFromMap } from '@esengine/procgen';
const item = weightedPick([
{ value: 'a', weight: 1 },
{ value: 'b', weight: 2 }
], rng);
const item2 = weightedPickFromMap({
'common': 60,
'rare': 30,
'epic': 10
}, rng);
```
## Shuffle and Sampling
### shuffle / shuffleCopy
Fisher-Yates shuffle:
```typescript
import { shuffle, shuffleCopy } from '@esengine/procgen';
const arr = [1, 2, 3, 4, 5];
shuffle(arr, rng); // In-place
const shuffled = shuffleCopy(arr, rng); // Copy
```
### pickOne
```typescript
import { pickOne } from '@esengine/procgen';
const item = pickOne(['a', 'b', 'c', 'd'], rng);
```
### sample / sampleWithReplacement
```typescript
import { sample, sampleWithReplacement } from '@esengine/procgen';
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const unique = sample(arr, 3, rng); // 3 unique
const withRep = sampleWithReplacement(arr, 5, rng); // 5 with replacement
```
### randomIntegers
```typescript
import { randomIntegers } from '@esengine/procgen';
// 5 unique random integers from 1-100
const nums = randomIntegers(1, 100, 5, rng);
```
### weightedSample
```typescript
import { weightedSample } from '@esengine/procgen';
const items = ['A', 'B', 'C', 'D', 'E'];
const weights = [10, 8, 6, 4, 2];
const selected = weightedSample(items, weights, 3, rng);
```
## Practical Examples
### Procedural Terrain
```typescript
import { createPerlinNoise, createFBM } from '@esengine/procgen';
class TerrainGenerator {
private fbm: FBM;
private moistureFbm: FBM;
constructor(seed: number) {
const heightNoise = createPerlinNoise(seed);
const moistureNoise = createPerlinNoise(seed + 1000);
this.fbm = createFBM(heightNoise, {
octaves: 8,
persistence: 0.5,
frequency: 0.01
});
this.moistureFbm = createFBM(moistureNoise, {
octaves: 4,
persistence: 0.6,
frequency: 0.02
});
}
getHeight(x: number, y: number): number {
let height = this.fbm.noise2D(x, y);
height += this.fbm.ridged2D(x * 0.5, y * 0.5) * 0.3;
return (height + 1) * 0.5; // Normalize to [0, 1]
}
getBiome(x: number, y: number): string {
const height = this.getHeight(x, y);
const moisture = (this.moistureFbm.noise2D(x, y) + 1) * 0.5;
if (height < 0.3) return 'water';
if (height < 0.4) return 'beach';
if (height > 0.8) return 'mountain';
if (moisture < 0.3) return 'desert';
if (moisture > 0.7) return 'forest';
return 'grassland';
}
}
```
### Loot System
```typescript
import { createSeededRandom, createWeightedRandom } from '@esengine/procgen';
class LootSystem {
private rng: SeededRandom;
private raritySelector: WeightedRandom<string>;
constructor(seed: number) {
this.rng = createSeededRandom(seed);
this.raritySelector = createWeightedRandom([
{ value: 'common', weight: 60 },
{ value: 'uncommon', weight: 25 },
{ value: 'rare', weight: 10 },
{ value: 'legendary', weight: 5 }
]);
}
generateLoot(count: number): LootItem[] {
const loot: LootItem[] = [];
for (let i = 0; i < count; i++) {
const rarity = this.raritySelector.pick(this.rng);
// Get item from rarity table...
loot.push(item);
}
return loot;
}
}
```
## Blueprint Nodes
### Noise Nodes
- `SampleNoise2D` - Sample 2D noise
- `SampleFBM` - Sample FBM noise
### Random Nodes
- `SeededRandom` - Generate random float
- `SeededRandomInt` - Generate random integer
- `WeightedPick` - Weighted random selection
- `ShuffleArray` - Shuffle array
- `PickRandom` - Pick random element
- `SampleArray` - Sample from array
- `RandomPointInCircle` - Random point in circle
## Best Practices
1. **Use seeds for reproducibility**
```typescript
const seed = Date.now();
const rng = createSeededRandom(seed);
saveSeed(seed);
```
2. **Precompute weighted selectors**
```typescript
// Good: Create once, use many times
const selector = createWeightedRandom(items);
for (let i = 0; i < 1000; i++) {
selector.pick(rng);
}
```
3. **Choose appropriate noise**
- Perlin: Smooth terrain, clouds
- Simplex: Performance-critical
- Worley: Cell textures, stone
- FBM: Natural multi-detail effects
4. **Tune FBM parameters**
- `octaves`: More = richer detail, higher cost
- `persistence`: 0.5 is common, higher = more high-frequency detail
- `lacunarity`: Usually 2, controls frequency growth

View File

@@ -0,0 +1,322 @@
# Spatial Index System
`@esengine/spatial` provides efficient spatial querying and indexing, including range queries, nearest neighbor queries, raycasting, and AOI (Area of Interest) management.
## Installation
```bash
npm install @esengine/spatial
```
## Quick Start
### Spatial Index
```typescript
import { createGridSpatialIndex } from '@esengine/spatial';
// Create spatial index (cell size 100)
const spatialIndex = createGridSpatialIndex<Entity>(100);
// Insert objects
spatialIndex.insert(player, { x: 100, y: 200 });
spatialIndex.insert(enemy1, { x: 150, y: 250 });
spatialIndex.insert(enemy2, { x: 500, y: 600 });
// Find objects within radius
const nearby = spatialIndex.findInRadius({ x: 100, y: 200 }, 100);
console.log(nearby); // [player, enemy1]
// Find nearest object
const nearest = spatialIndex.findNearest({ x: 100, y: 200 });
console.log(nearest); // enemy1
// Update position
spatialIndex.update(player, { x: 120, y: 220 });
```
### AOI (Area of Interest)
```typescript
import { createGridAOI } from '@esengine/spatial';
// Create AOI manager
const aoi = createGridAOI<Entity>(100);
// Add observers
aoi.addObserver(player, { x: 100, y: 100 }, { viewRange: 200 });
aoi.addObserver(npc, { x: 150, y: 150 }, { viewRange: 150 });
// Listen to enter/exit events
aoi.addListener((event) => {
if (event.type === 'enter') {
console.log(`${event.observer} saw ${event.target}`);
} else if (event.type === 'exit') {
console.log(`${event.target} left ${event.observer}'s view`);
}
});
// Update position (triggers enter/exit events)
aoi.updatePosition(player, { x: 200, y: 200 });
// Get visible entities
const visible = aoi.getEntitiesInView(player);
```
## Core Concepts
### Spatial Index vs AOI
| Feature | SpatialIndex | AOI |
|---------|--------------|-----|
| Purpose | General spatial queries | Entity visibility tracking |
| Events | No event notification | Enter/exit events |
| Direction | One-way query | Two-way tracking |
| Use Cases | Collision, range attacks | MMO sync, NPC AI perception |
### IBounds
```typescript
interface IBounds {
readonly minX: number;
readonly minY: number;
readonly maxX: number;
readonly maxY: number;
}
```
### IRaycastHit
```typescript
interface IRaycastHit<T> {
readonly target: T; // Hit object
readonly point: IVector2; // Hit point
readonly normal: IVector2;// Hit normal
readonly distance: number;// Distance from origin
}
```
## Spatial Index API
### createGridSpatialIndex
```typescript
function createGridSpatialIndex<T>(cellSize?: number): GridSpatialIndex<T>
```
**Choosing cellSize:**
- Too small: High memory, reduced query efficiency
- Too large: Many objects per cell, slow iteration
- Recommended: 1-2x average object spacing
### Management Methods
```typescript
spatialIndex.insert(entity, position);
spatialIndex.remove(entity);
spatialIndex.update(entity, newPosition);
spatialIndex.clear();
```
### Query Methods
#### findInRadius
```typescript
const enemies = spatialIndex.findInRadius(
{ x: 100, y: 200 },
50,
(entity) => entity.type === 'enemy' // Optional filter
);
```
#### findInRect
```typescript
import { createBounds } from '@esengine/spatial';
const bounds = createBounds(0, 0, 200, 200);
const entities = spatialIndex.findInRect(bounds);
```
#### findNearest
```typescript
const nearest = spatialIndex.findNearest(
playerPosition,
500, // maxDistance
(entity) => entity.type === 'enemy'
);
```
#### findKNearest
```typescript
const nearestEnemies = spatialIndex.findKNearest(
playerPosition,
5, // k
500, // maxDistance
(entity) => entity.type === 'enemy'
);
```
#### raycast / raycastFirst
```typescript
const hits = spatialIndex.raycast(origin, direction, maxDistance);
const firstHit = spatialIndex.raycastFirst(origin, direction, maxDistance);
```
## AOI API
### createGridAOI
```typescript
function createGridAOI<T>(cellSize?: number): GridAOI<T>
```
### Observer Management
```typescript
// Add observer
aoi.addObserver(player, position, {
viewRange: 200,
observable: true // Can be seen by others
});
// Remove observer
aoi.removeObserver(player);
// Update position
aoi.updatePosition(player, newPosition);
// Update view range
aoi.updateViewRange(player, 300);
```
### Query Methods
```typescript
// Get entities in observer's view
const visible = aoi.getEntitiesInView(player);
// Get observers who can see entity
const observers = aoi.getObserversOf(monster);
// Check visibility
if (aoi.canSee(player, enemy)) { ... }
```
### Event System
```typescript
// Global event listener
aoi.addListener((event) => {
switch (event.type) {
case 'enter': /* entered view */ break;
case 'exit': /* left view */ break;
}
});
// Entity-specific listener
aoi.addEntityListener(player, (event) => {
if (event.type === 'enter') {
sendToClient(player, 'entity_enter', event.target);
}
});
```
## Utility Functions
### Bounds Creation
```typescript
import {
createBounds,
createBoundsFromCenter,
createBoundsFromCircle
} from '@esengine/spatial';
const bounds1 = createBounds(0, 0, 100, 100);
const bounds2 = createBoundsFromCenter({ x: 50, y: 50 }, 100, 100);
const bounds3 = createBoundsFromCircle({ x: 50, y: 50 }, 50);
```
### Geometry Checks
```typescript
import {
isPointInBounds,
boundsIntersect,
boundsIntersectsCircle,
distance,
distanceSquared
} from '@esengine/spatial';
if (isPointInBounds(point, bounds)) { ... }
if (boundsIntersect(boundsA, boundsB)) { ... }
if (boundsIntersectsCircle(bounds, center, radius)) { ... }
const dist = distance(pointA, pointB);
const distSq = distanceSquared(pointA, pointB); // Faster
```
## Practical Examples
### Range Attack Detection
```typescript
class CombatSystem {
private spatialIndex: ISpatialIndex<Entity>;
dealAreaDamage(center: IVector2, radius: number, damage: number): void {
const targets = this.spatialIndex.findInRadius(
center, radius,
(entity) => entity.hasComponent(HealthComponent)
);
for (const target of targets) {
target.getComponent(HealthComponent).takeDamage(damage);
}
}
}
```
### MMO Sync System
```typescript
class SyncSystem {
private aoi: IAOIManager<Player>;
constructor() {
this.aoi = createGridAOI<Player>(100);
this.aoi.addListener((event) => {
const packet = this.createSyncPacket(event);
this.sendToPlayer(event.observer, packet);
});
}
onPlayerMove(player: Player, newPosition: IVector2): void {
this.aoi.updatePosition(player, newPosition);
}
}
```
## Blueprint Nodes
### Spatial Query Nodes
- `FindInRadius`, `FindInRect`, `FindNearest`, `FindKNearest`
- `Raycast`, `RaycastFirst`
### AOI Nodes
- `GetEntitiesInView`, `GetObserversOf`, `CanSee`
- `OnEntityEnterView`, `OnEntityExitView`
## Service Tokens
```typescript
import { SpatialIndexToken, AOIManagerToken } from '@esengine/spatial';
services.register(SpatialIndexToken, createGridSpatialIndex(100));
services.register(AOIManagerToken, createGridAOI(100));
```

View File

@@ -0,0 +1,352 @@
# Timer System
`@esengine/timer` provides a flexible timer and cooldown system for delayed execution, repeating tasks, skill cooldowns, and more.
## Installation
```bash
npm install @esengine/timer
```
## Quick Start
```typescript
import { createTimerService } from '@esengine/timer';
// Create timer service
const timerService = createTimerService();
// One-time timer (executes after 1 second)
const handle = timerService.schedule('myTimer', 1000, () => {
console.log('Timer fired!');
});
// Repeating timer (every 100ms)
timerService.scheduleRepeating('heartbeat', 100, () => {
console.log('Tick');
});
// Cooldown system (5 second cooldown)
timerService.startCooldown('skill_fireball', 5000);
if (timerService.isCooldownReady('skill_fireball')) {
useFireball();
timerService.startCooldown('skill_fireball', 5000);
}
// Update in game loop
function gameLoop(deltaTime: number) {
timerService.update(deltaTime);
}
```
## Core Concepts
### Timer vs Cooldown
| Feature | Timer | Cooldown |
|---------|-------|----------|
| Purpose | Delayed code execution | Rate limiting |
| Callback | Has callback function | No callback |
| Repeat | Supports repeating | One-time |
| Query | Query remaining time | Query progress/ready status |
### TimerHandle
Handle object returned when scheduling a timer:
```typescript
interface TimerHandle {
readonly id: string; // Timer ID
readonly isValid: boolean; // Whether valid (not cancelled)
cancel(): void; // Cancel timer
}
```
### TimerInfo
Timer information object:
```typescript
interface TimerInfo {
readonly id: string; // Timer ID
readonly remaining: number; // Remaining time (ms)
readonly repeating: boolean; // Whether repeating
readonly interval?: number; // Interval (repeating only)
}
```
### CooldownInfo
Cooldown information object:
```typescript
interface CooldownInfo {
readonly id: string; // Cooldown ID
readonly duration: number; // Total duration (ms)
readonly remaining: number; // Remaining time (ms)
readonly progress: number; // Progress (0-1, 0=started, 1=finished)
readonly isReady: boolean; // Whether ready
}
```
## API Reference
### createTimerService
```typescript
function createTimerService(config?: TimerServiceConfig): ITimerService
```
**Configuration:**
| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `maxTimers` | `number` | `0` | Maximum timer count (0 = unlimited) |
| `maxCooldowns` | `number` | `0` | Maximum cooldown count (0 = unlimited) |
### Timer API
#### schedule
Schedule a one-time timer:
```typescript
const handle = timerService.schedule('explosion', 2000, () => {
createExplosion();
});
// Cancel early
handle.cancel();
```
#### scheduleRepeating
Schedule a repeating timer:
```typescript
// Execute every second
timerService.scheduleRepeating('regen', 1000, () => {
player.hp += 5;
});
// Execute immediately once, then repeat every second
timerService.scheduleRepeating('tick', 1000, () => {
console.log('Tick');
}, true); // immediate = true
```
#### cancel / cancelById
Cancel timers:
```typescript
// Cancel by handle
handle.cancel();
// or
timerService.cancel(handle);
// Cancel by ID
timerService.cancelById('regen');
```
#### hasTimer
Check if timer exists:
```typescript
if (timerService.hasTimer('explosion')) {
console.log('Explosion is pending');
}
```
#### getTimerInfo
Get timer information:
```typescript
const info = timerService.getTimerInfo('explosion');
if (info) {
console.log(`Remaining: ${info.remaining}ms`);
console.log(`Repeating: ${info.repeating}`);
}
```
### Cooldown API
#### startCooldown
Start a cooldown:
```typescript
timerService.startCooldown('skill_fireball', 5000);
```
#### isCooldownReady / isOnCooldown
Check cooldown status:
```typescript
if (timerService.isCooldownReady('skill_fireball')) {
castFireball();
timerService.startCooldown('skill_fireball', 5000);
}
if (timerService.isOnCooldown('skill_fireball')) {
console.log('On cooldown...');
}
```
#### getCooldownProgress / getCooldownRemaining
Get cooldown progress:
```typescript
// Progress 0-1 (0=started, 1=complete)
const progress = timerService.getCooldownProgress('skill_fireball');
console.log(`Progress: ${(progress * 100).toFixed(0)}%`);
// Remaining time (ms)
const remaining = timerService.getCooldownRemaining('skill_fireball');
console.log(`Remaining: ${(remaining / 1000).toFixed(1)}s`);
```
#### getCooldownInfo
Get complete cooldown info:
```typescript
const info = timerService.getCooldownInfo('skill_fireball');
if (info) {
console.log(`Duration: ${info.duration}ms`);
console.log(`Remaining: ${info.remaining}ms`);
console.log(`Progress: ${info.progress}`);
console.log(`Ready: ${info.isReady}`);
}
```
#### resetCooldown / clearAllCooldowns
Reset cooldowns:
```typescript
// Reset single cooldown
timerService.resetCooldown('skill_fireball');
// Clear all cooldowns (e.g., on respawn)
timerService.clearAllCooldowns();
```
### Lifecycle
#### update
Update timer service (call every frame):
```typescript
function gameLoop(deltaTime: number) {
timerService.update(deltaTime); // deltaTime in ms
}
```
#### clear
Clear all timers and cooldowns:
```typescript
timerService.clear();
```
### Debug Properties
```typescript
console.log(timerService.activeTimerCount);
console.log(timerService.activeCooldownCount);
const timerIds = timerService.getActiveTimerIds();
const cooldownIds = timerService.getActiveCooldownIds();
```
## Practical Examples
### Skill Cooldown System
```typescript
import { createTimerService, type ITimerService } from '@esengine/timer';
class SkillSystem {
private timerService: ITimerService;
private skills: Map<string, SkillData> = new Map();
constructor() {
this.timerService = createTimerService();
}
useSkill(skillId: string): boolean {
const skill = this.skills.get(skillId);
if (!skill) return false;
if (!this.timerService.isCooldownReady(skillId)) {
const remaining = this.timerService.getCooldownRemaining(skillId);
console.log(`Skill ${skillId} on cooldown, ${remaining}ms remaining`);
return false;
}
this.executeSkill(skill);
this.timerService.startCooldown(skillId, skill.cooldown);
return true;
}
update(dt: number): void {
this.timerService.update(dt);
}
}
```
### DOT Effects
```typescript
class EffectSystem {
private timerService: ITimerService;
applyDOT(target: Entity, damage: number, duration: number): void {
const dotId = `dot_${target.id}_${Date.now()}`;
let elapsed = 0;
this.timerService.scheduleRepeating(dotId, 1000, () => {
elapsed += 1000;
target.takeDamage(damage);
if (elapsed >= duration) {
this.timerService.cancelById(dotId);
}
});
}
}
```
## Blueprint Nodes
### Cooldown Nodes
- `StartCooldown` - Start cooldown
- `IsCooldownReady` - Check if cooldown is ready
- `GetCooldownProgress` - Get cooldown progress
- `GetCooldownInfo` - Get cooldown info
- `ResetCooldown` - Reset cooldown
### Timer Nodes
- `HasTimer` - Check if timer exists
- `CancelTimer` - Cancel timer
- `GetTimerRemaining` - Get timer remaining time
## Service Token
For dependency injection:
```typescript
import { TimerServiceToken, createTimerService } from '@esengine/timer';
services.register(TimerServiceToken, createTimerService());
const timerService = services.get(TimerServiceToken);
```

View File

@@ -4,7 +4,24 @@
## 安装
### NPM 安装
### 使用 CLI推荐
在现有项目中添加 ECS 的最简单方式:
```bash
# 在项目目录中运行
npx @esengine/cli init
```
CLI 会自动检测项目类型Cocos Creator 2.x/3.x、LayaAir 3.x 或 Node.js并生成相应的集成代码包括
- `ECSManager` 组件/脚本 - 负责 ECS 生命周期管理
- 示例组件和系统 - 帮助快速上手
- 自动安装依赖
### NPM 手动安装
如果你更喜欢手动配置,可以直接安装:
```bash
# 使用 npm
@@ -333,27 +350,39 @@ function gameLoop(deltaTime: number) {
## 与游戏引擎集成
### Laya 引擎集成
### Laya 3.x 引擎集成
推荐使用 `Laya.Script` 组件来管理 ECS 生命周期:
```typescript
import { Stage } from "laya/display/Stage";
import { Laya } from "Laya";
import { Core } from '@esengine/ecs-framework';
import { Core, Scene } from '@esengine/ecs-framework';
// 初始化 Laya
Laya.init(800, 600).then(() => {
// 初始化 ECS
Core.create(true);
Core.setScene(new GameScene());
const { regClass } = Laya;
// 启动游戏循环
Laya.timer.frameLoop(1, this, () => {
const deltaTime = Laya.timer.delta / 1000;
Core.update(deltaTime); // 自动更新全局服务和场景
});
});
@regClass()
export class ECSManager extends Laya.Script {
private ecsScene = new GameScene();
onAwake(): void {
// 初始化 ECS
Core.create({ debug: true });
Core.setScene(this.ecsScene);
}
onUpdate(): void {
// 自动更新全局服务和场景
Core.update(Laya.timer.delta / 1000);
}
onDestroy(): void {
// 清理资源
Core.destroy();
}
}
```
在 Laya IDE 中,将 `ECSManager` 脚本挂载到场景中的节点上即可。
### Cocos Creator 集成
```typescript

View File

@@ -0,0 +1,507 @@
# 蓝图可视化脚本 (Blueprint)
`@esengine/blueprint` 提供了一个功能完整的可视化脚本系统,支持节点式编程、事件驱动和蓝图组合。
## 安装
```bash
npm install @esengine/blueprint
```
## 快速开始
```typescript
import {
createBlueprintSystem,
createBlueprintComponentData,
NodeRegistry,
RegisterNode
} from '@esengine/blueprint';
// 创建蓝图系统
const blueprintSystem = createBlueprintSystem(scene);
// 加载蓝图资产
const blueprint = await loadBlueprintAsset('player.bp');
// 创建蓝图组件数据
const componentData = createBlueprintComponentData();
componentData.blueprintAsset = blueprint;
// 在游戏循环中更新
function gameLoop(dt: number) {
blueprintSystem.process(entities, dt);
}
```
## 核心概念
### 蓝图资产结构
蓝图保存为 `.bp` 文件,包含以下结构:
```typescript
interface BlueprintAsset {
version: number; // 格式版本
type: 'blueprint'; // 资产类型
metadata: BlueprintMetadata; // 元数据
variables: BlueprintVariable[]; // 变量定义
nodes: BlueprintNode[]; // 节点实例
connections: BlueprintConnection[]; // 连接
}
```
### 节点类型
节点按功能分为以下类别:
| 类别 | 说明 | 颜色 |
|------|------|------|
| `event` | 事件节点(入口点) | 红色 |
| `flow` | 流程控制 | 灰色 |
| `entity` | 实体操作 | 蓝色 |
| `component` | 组件访问 | 青色 |
| `math` | 数学运算 | 绿色 |
| `logic` | 逻辑运算 | 红色 |
| `variable` | 变量访问 | 紫色 |
| `time` | 时间工具 | 青色 |
| `debug` | 调试工具 | 灰色 |
### 引脚类型
节点通过引脚连接:
```typescript
interface BlueprintPinDefinition {
name: string; // 引脚名称
type: PinDataType; // 数据类型
direction: 'input' | 'output';
isExec?: boolean; // 是否是执行引脚
defaultValue?: unknown;
}
// 支持的数据类型
type PinDataType =
| 'exec' // 执行流
| 'boolean' // 布尔值
| 'number' // 数字
| 'string' // 字符串
| 'vector2' // 2D 向量
| 'vector3' // 3D 向量
| 'entity' // 实体引用
| 'component' // 组件引用
| 'any'; // 任意类型
```
### 变量作用域
```typescript
type VariableScope =
| 'local' // 每次执行独立
| 'instance' // 每个实体独立
| 'global'; // 全局共享
```
## 虚拟机 API
### BlueprintVM
蓝图虚拟机负责执行蓝图图:
```typescript
import { BlueprintVM } from '@esengine/blueprint';
// 创建 VM
const vm = new BlueprintVM(blueprintAsset, entity, scene);
// 启动(触发 BeginPlay
vm.start();
// 每帧更新(触发 Tick
vm.tick(deltaTime);
// 停止(触发 EndPlay
vm.stop();
// 暂停/恢复
vm.pause();
vm.resume();
// 触发事件
vm.triggerEvent('EventCollision', { other: otherEntity });
vm.triggerCustomEvent('OnDamage', { amount: 50 });
// 调试模式
vm.debug = true;
```
### 执行上下文
```typescript
interface ExecutionContext {
blueprint: BlueprintAsset; // 蓝图资产
entity: Entity; // 当前实体
scene: IScene; // 当前场景
deltaTime: number; // 帧间隔时间
time: number; // 总运行时间
// 获取输入值
getInput<T>(nodeId: string, pinName: string): T;
// 设置输出值
setOutput(nodeId: string, pinName: string, value: unknown): void;
// 变量访问
getVariable<T>(name: string): T;
setVariable(name: string, value: unknown): void;
}
```
### 执行结果
```typescript
interface ExecutionResult {
outputs?: Record<string, unknown>; // 输出值
nextExec?: string | null; // 下一个执行引脚
delay?: number; // 延迟执行(毫秒)
yield?: boolean; // 暂停到下一帧
error?: string; // 错误信息
}
```
## 自定义节点
### 定义节点模板
```typescript
import { BlueprintNodeTemplate } from '@esengine/blueprint';
const MyNodeTemplate: BlueprintNodeTemplate = {
type: 'MyCustomNode',
title: 'My Custom Node',
category: 'custom',
description: 'A custom node example',
keywords: ['custom', 'example'],
inputs: [
{ name: 'exec', type: 'exec', direction: 'input', isExec: true },
{ name: 'value', type: 'number', direction: 'input', defaultValue: 0 }
],
outputs: [
{ name: 'exec', type: 'exec', direction: 'output', isExec: true },
{ name: 'result', type: 'number', direction: 'output' }
]
};
```
### 实现节点执行器
```typescript
import { INodeExecutor, RegisterNode } from '@esengine/blueprint';
@RegisterNode(MyNodeTemplate)
class MyNodeExecutor implements INodeExecutor {
execute(node: BlueprintNode, context: ExecutionContext): ExecutionResult {
// 获取输入
const value = context.getInput<number>(node.id, 'value');
// 执行逻辑
const result = value * 2;
// 返回结果
return {
outputs: { result },
nextExec: 'exec' // 继续执行
};
}
}
```
### 使用装饰器注册
```typescript
// 方式 1: 使用装饰器
@RegisterNode(MyNodeTemplate)
class MyNodeExecutor implements INodeExecutor { ... }
// 方式 2: 手动注册
NodeRegistry.instance.register(MyNodeTemplate, new MyNodeExecutor());
```
## 节点注册表
```typescript
import { NodeRegistry } from '@esengine/blueprint';
// 获取单例
const registry = NodeRegistry.instance;
// 获取所有模板
const allTemplates = registry.getAllTemplates();
// 按类别获取
const mathNodes = registry.getTemplatesByCategory('math');
// 搜索节点
const results = registry.searchTemplates('add');
// 检查是否存在
if (registry.has('MyCustomNode')) { ... }
```
## 内置节点
### 事件节点
| 节点 | 说明 |
|------|------|
| `EventBeginPlay` | 蓝图启动时触发 |
| `EventTick` | 每帧触发 |
| `EventEndPlay` | 蓝图停止时触发 |
| `EventCollision` | 碰撞时触发 |
| `EventInput` | 输入事件触发 |
| `EventTimer` | 定时器触发 |
| `EventMessage` | 自定义消息触发 |
### 时间节点
| 节点 | 说明 |
|------|------|
| `Delay` | 延迟执行 |
| `GetDeltaTime` | 获取帧间隔 |
| `GetTime` | 获取运行时间 |
### 数学节点
| 节点 | 说明 |
|------|------|
| `Add` | 加法 |
| `Subtract` | 减法 |
| `Multiply` | 乘法 |
| `Divide` | 除法 |
| `Abs` | 绝对值 |
| `Clamp` | 限制范围 |
| `Lerp` | 线性插值 |
| `Min` / `Max` | 最小/最大值 |
### 调试节点
| 节点 | 说明 |
|------|------|
| `Print` | 打印到控制台 |
## 蓝图组合
### 蓝图片段
将可复用的逻辑封装为片段:
```typescript
import { createFragment } from '@esengine/blueprint';
const healthFragment = createFragment('HealthSystem', {
inputs: [
{ name: 'damage', type: 'number', internalNodeId: 'input1', internalPinName: 'value' }
],
outputs: [
{ name: 'isDead', type: 'boolean', internalNodeId: 'output1', internalPinName: 'value' }
],
graph: {
nodes: [...],
connections: [...],
variables: [...]
}
});
```
### 组合蓝图
```typescript
import { createComposer, FragmentRegistry } from '@esengine/blueprint';
// 注册片段
FragmentRegistry.instance.register('health', healthFragment);
FragmentRegistry.instance.register('movement', movementFragment);
// 创建组合器
const composer = createComposer('PlayerBlueprint');
// 添加片段到槽位
composer.addFragment(healthFragment, 'slot1', { position: { x: 0, y: 0 } });
composer.addFragment(movementFragment, 'slot2', { position: { x: 400, y: 0 } });
// 连接槽位
composer.connect('slot1', 'onDeath', 'slot2', 'disable');
// 验证
const validation = composer.validate();
if (!validation.isValid) {
console.error(validation.errors);
}
// 编译成蓝图
const blueprint = composer.compile();
```
## 触发器系统
### 定义触发条件
```typescript
import { TriggerCondition, TriggerDispatcher } from '@esengine/blueprint';
const lowHealthCondition: TriggerCondition = {
type: 'comparison',
left: { type: 'variable', name: 'health' },
operator: '<',
right: { type: 'constant', value: 20 }
};
```
### 使用触发器分发器
```typescript
const dispatcher = new TriggerDispatcher();
// 注册触发器
dispatcher.register('lowHealth', lowHealthCondition, (context) => {
context.triggerEvent('OnLowHealth');
});
// 每帧评估
dispatcher.evaluate(context);
```
## 与 ECS 集成
### 使用蓝图系统
```typescript
import { createBlueprintSystem } from '@esengine/blueprint';
class GameScene {
private blueprintSystem: BlueprintSystem;
initialize() {
this.blueprintSystem = createBlueprintSystem(this.scene);
}
update(dt: number) {
// 处理所有带蓝图组件的实体
this.blueprintSystem.process(this.entities, dt);
}
}
```
### 触发蓝图事件
```typescript
import { triggerBlueprintEvent, triggerCustomBlueprintEvent } from '@esengine/blueprint';
// 触发内置事件
triggerBlueprintEvent(entity, 'Collision', { other: otherEntity });
// 触发自定义事件
triggerCustomBlueprintEvent(entity, 'OnPickup', { item: itemEntity });
```
## 实际示例
### 玩家控制蓝图
```typescript
// 定义输入处理节点
const InputMoveTemplate: BlueprintNodeTemplate = {
type: 'InputMove',
title: 'Get Movement Input',
category: 'input',
inputs: [],
outputs: [
{ name: 'direction', type: 'vector2', direction: 'output' }
],
isPure: true
};
@RegisterNode(InputMoveTemplate)
class InputMoveExecutor implements INodeExecutor {
execute(node: BlueprintNode, context: ExecutionContext): ExecutionResult {
const input = context.scene.services.get(InputServiceToken);
const direction = {
x: input.getAxis('horizontal'),
y: input.getAxis('vertical')
};
return { outputs: { direction } };
}
}
```
### 状态切换逻辑
```typescript
// 在蓝图中实现状态机逻辑
const stateBlueprint = createEmptyBlueprint('PlayerState');
// 添加状态变量
stateBlueprint.variables.push({
name: 'currentState',
type: 'string',
defaultValue: 'idle',
scope: 'instance'
});
// 在 Tick 事件中检查状态转换
// ... 通过节点连接实现
```
## 序列化
### 保存蓝图
```typescript
import { validateBlueprintAsset } from '@esengine/blueprint';
function saveBlueprint(blueprint: BlueprintAsset, path: string): void {
if (!validateBlueprintAsset(blueprint)) {
throw new Error('Invalid blueprint structure');
}
const json = JSON.stringify(blueprint, null, 2);
fs.writeFileSync(path, json);
}
```
### 加载蓝图
```typescript
async function loadBlueprint(path: string): Promise<BlueprintAsset> {
const json = await fs.readFile(path, 'utf-8');
const asset = JSON.parse(json);
if (!validateBlueprintAsset(asset)) {
throw new Error('Invalid blueprint file');
}
return asset;
}
```
## 最佳实践
1. **使用片段复用逻辑**
- 将通用逻辑封装为片段
- 通过组合器构建复杂蓝图
2. **合理使用变量作用域**
- `local`: 临时计算结果
- `instance`: 实体状态(如生命值)
- `global`: 游戏全局状态
3. **避免无限循环**
- VM 有每帧最大执行步数限制(默认 1000
- 使用 Delay 节点打断长执行链
4. **调试技巧**
- 启用 `vm.debug = true` 查看执行日志
- 使用 Print 节点输出中间值
5. **性能优化**
- 纯节点(`isPure: true`)的输出会被缓存
- 避免在 Tick 中执行重计算

337
docs/modules/fsm/index.md Normal file
View File

@@ -0,0 +1,337 @@
# 状态机 (FSM)
`@esengine/fsm` 提供了一个类型安全的有限状态机实现用于角色、AI 或任何需要状态管理的场景。
## 安装
```bash
npm install @esengine/fsm
```
## 快速开始
```typescript
import { createStateMachine } from '@esengine/fsm';
// 定义状态类型
type PlayerState = 'idle' | 'walk' | 'run' | 'jump';
// 创建状态机
const fsm = createStateMachine<PlayerState>('idle');
// 定义状态和回调
fsm.defineState('idle', {
onEnter: (ctx, from) => console.log(`${from} 进入 idle`),
onExit: (ctx, to) => console.log(`从 idle 退出到 ${to}`),
onUpdate: (ctx, dt) => { /* 每帧更新 */ }
});
fsm.defineState('walk', {
onEnter: () => console.log('开始行走')
});
// 手动切换状态
fsm.transition('walk');
console.log(fsm.current); // 'walk'
```
## 核心概念
### 状态配置
每个状态可以配置以下回调:
```typescript
interface StateConfig<TState, TContext> {
name: TState; // 状态名称
onEnter?: (context: TContext, from: TState | null) => void; // 进入回调
onExit?: (context: TContext, to: TState) => void; // 退出回调
onUpdate?: (context: TContext, deltaTime: number) => void; // 更新回调
tags?: string[]; // 状态标签
metadata?: Record<string, unknown>; // 元数据
}
```
### 转换条件
可以定义带条件的状态转换:
```typescript
interface Context {
isMoving: boolean;
isRunning: boolean;
isGrounded: boolean;
}
const fsm = createStateMachine<PlayerState, Context>('idle', {
context: { isMoving: false, isRunning: false, isGrounded: true }
});
// 定义转换条件
fsm.defineTransition('idle', 'walk', (ctx) => ctx.isMoving);
fsm.defineTransition('walk', 'run', (ctx) => ctx.isRunning);
fsm.defineTransition('walk', 'idle', (ctx) => !ctx.isMoving);
// 自动评估并执行满足条件的转换
fsm.evaluateTransitions();
```
### 转换优先级
当多个转换条件同时满足时,优先级高的先执行:
```typescript
// 优先级数字越大越优先
fsm.defineTransition('idle', 'attack', (ctx) => ctx.isAttacking, 10);
fsm.defineTransition('idle', 'walk', (ctx) => ctx.isMoving, 1);
// 如果同时满足,会先尝试 attack优先级 10
```
## API 参考
### createStateMachine
```typescript
function createStateMachine<TState extends string, TContext = unknown>(
initialState: TState,
options?: StateMachineOptions<TContext>
): IStateMachine<TState, TContext>
```
**参数:**
- `initialState` - 初始状态
- `options.context` - 上下文对象,在回调中可访问
- `options.maxHistorySize` - 最大历史记录数(默认 100
- `options.enableHistory` - 是否启用历史记录(默认 true
### 状态机属性
| 属性 | 类型 | 描述 |
|------|------|------|
| `current` | `TState` | 当前状态 |
| `previous` | `TState \| null` | 上一个状态 |
| `context` | `TContext` | 上下文对象 |
| `isTransitioning` | `boolean` | 是否正在转换中 |
| `currentStateDuration` | `number` | 当前状态持续时间(毫秒) |
### 状态机方法
#### 状态定义
```typescript
// 定义状态
fsm.defineState('idle', {
onEnter: (ctx, from) => {},
onExit: (ctx, to) => {},
onUpdate: (ctx, dt) => {}
});
// 检查状态是否存在
fsm.hasState('idle'); // true
// 获取状态配置
fsm.getStateConfig('idle');
// 获取所有状态
fsm.getStates(); // ['idle', 'walk', ...]
```
#### 转换操作
```typescript
// 定义转换
fsm.defineTransition('idle', 'walk', condition, priority);
// 移除转换
fsm.removeTransition('idle', 'walk');
// 获取从某状态出发的所有转换
fsm.getTransitionsFrom('idle');
// 检查是否可以转换
fsm.canTransition('walk'); // true/false
// 手动转换
fsm.transition('walk');
// 强制转换(忽略条件)
fsm.transition('walk', true);
// 自动评估转换条件
fsm.evaluateTransitions();
```
#### 生命周期
```typescript
// 更新状态机(调用当前状态的 onUpdate
fsm.update(deltaTime);
// 重置状态机
fsm.reset(); // 重置到当前状态
fsm.reset('idle'); // 重置到指定状态
```
#### 事件监听
```typescript
// 监听进入特定状态
const unsubscribe = fsm.onEnter('walk', (from) => {
console.log(`${from} 进入 walk`);
});
// 监听退出特定状态
fsm.onExit('walk', (to) => {
console.log(`从 walk 退出到 ${to}`);
});
// 监听任意状态变化
fsm.onChange((event) => {
console.log(`${event.from} -> ${event.to} at ${event.timestamp}`);
});
// 取消订阅
unsubscribe();
```
#### 调试
```typescript
// 获取状态历史
const history = fsm.getHistory();
// [{ from: 'idle', to: 'walk', timestamp: 1234567890 }, ...]
// 清除历史
fsm.clearHistory();
// 获取调试信息
const info = fsm.getDebugInfo();
// { current, previous, duration, stateCount, transitionCount, historySize }
```
## 实际示例
### 角色状态机
```typescript
import { createStateMachine } from '@esengine/fsm';
type CharacterState = 'idle' | 'walk' | 'run' | 'jump' | 'fall' | 'attack';
interface CharacterContext {
velocity: { x: number; y: number };
isGrounded: boolean;
isAttacking: boolean;
speed: number;
}
const characterFSM = createStateMachine<CharacterState, CharacterContext>('idle', {
context: {
velocity: { x: 0, y: 0 },
isGrounded: true,
isAttacking: false,
speed: 0
}
});
// 定义状态
characterFSM.defineState('idle', {
onEnter: (ctx) => {
ctx.speed = 0;
},
onUpdate: (ctx, dt) => {
// 播放待机动画
}
});
characterFSM.defineState('walk', {
onEnter: (ctx) => {
ctx.speed = 100;
}
});
characterFSM.defineState('run', {
onEnter: (ctx) => {
ctx.speed = 200;
}
});
characterFSM.defineState('jump', {
onEnter: (ctx) => {
ctx.velocity.y = -300;
ctx.isGrounded = false;
}
});
// 定义转换
characterFSM.defineTransition('idle', 'walk', (ctx) => Math.abs(ctx.velocity.x) > 0);
characterFSM.defineTransition('walk', 'idle', (ctx) => ctx.velocity.x === 0);
characterFSM.defineTransition('walk', 'run', (ctx) => Math.abs(ctx.velocity.x) > 150);
characterFSM.defineTransition('run', 'walk', (ctx) => Math.abs(ctx.velocity.x) <= 150);
// 跳跃有最高优先级
characterFSM.defineTransition('idle', 'jump', (ctx) => !ctx.isGrounded, 10);
characterFSM.defineTransition('walk', 'jump', (ctx) => !ctx.isGrounded, 10);
characterFSM.defineTransition('run', 'jump', (ctx) => !ctx.isGrounded, 10);
characterFSM.defineTransition('jump', 'fall', (ctx) => ctx.velocity.y > 0);
characterFSM.defineTransition('fall', 'idle', (ctx) => ctx.isGrounded);
// 游戏循环中使用
function gameUpdate(dt: number) {
// 更新上下文
characterFSM.context.velocity.x = getInputVelocity();
characterFSM.context.isGrounded = checkGrounded();
// 评估状态转换
characterFSM.evaluateTransitions();
// 更新当前状态
characterFSM.update(dt);
}
```
### 与 ECS 集成
```typescript
import { Component, EntitySystem, Matcher } from '@esengine/ecs-framework';
import { createStateMachine, type IStateMachine } from '@esengine/fsm';
// 状态机组件
class FSMComponent extends Component {
fsm: IStateMachine<string>;
constructor(initialState: string) {
super();
this.fsm = createStateMachine(initialState);
}
}
// 状态机系统
class FSMSystem extends EntitySystem {
constructor() {
super(Matcher.all(FSMComponent));
}
protected processEntity(entity: Entity, dt: number): void {
const fsmComp = entity.getComponent(FSMComponent);
fsmComp.fsm.evaluateTransitions();
fsmComp.fsm.update(dt);
}
}
```
## 蓝图节点
FSM 模块提供了可视化脚本支持的蓝图节点:
- `GetCurrentState` - 获取当前状态
- `TransitionTo` - 转换到指定状态
- `CanTransition` - 检查是否可以转换
- `IsInState` - 检查是否在指定状态
- `WasInState` - 检查是否曾在指定状态
- `GetStateDuration` - 获取状态持续时间
- `EvaluateTransitions` - 评估转换条件
- `ResetStateMachine` - 重置状态机

54
docs/modules/index.md Normal file
View File

@@ -0,0 +1,54 @@
# 功能模块
ESEngine 提供了丰富的功能模块,可以按需引入到你的项目中。
## 模块列表
### AI 模块
| 模块 | 包名 | 描述 |
|------|------|------|
| [行为树](/modules/behavior-tree/) | `@esengine/behavior-tree` | AI 行为树系统,支持可视化编辑 |
| [状态机](/modules/fsm/) | `@esengine/fsm` | 有限状态机,用于角色/AI 状态管理 |
### 游戏逻辑
| 模块 | 包名 | 描述 |
|------|------|------|
| [定时器](/modules/timer/) | `@esengine/timer` | 定时器和冷却系统 |
| [空间索引](/modules/spatial/) | `@esengine/spatial` | 空间查询、AOI 兴趣区域管理 |
| [寻路系统](/modules/pathfinding/) | `@esengine/pathfinding` | A* 寻路、NavMesh 导航网格 |
### 工具模块
| 模块 | 包名 | 描述 |
|------|------|------|
| [可视化脚本](/modules/blueprint/) | `@esengine/blueprint` | 蓝图可视化脚本系统 |
| [程序化生成](/modules/procgen/) | `@esengine/procgen` | 噪声函数、随机工具 |
### 网络模块
| 模块 | 包名 | 描述 |
|------|------|------|
| [网络同步](/modules/network/) | `@esengine/network` | 多人游戏网络同步 |
## 安装
所有模块都可以独立安装:
```bash
# 安装单个模块
npm install @esengine/behavior-tree
# 或使用 CLI 添加到现有项目
npx @esengine/cli add behavior-tree
```
## 平台兼容性
所有功能模块都是纯 TypeScript 实现,兼容:
- Cocos Creator 3.x
- Laya 3.x
- Node.js
- 浏览器

View File

@@ -0,0 +1,502 @@
# 寻路系统 (Pathfinding)
`@esengine/pathfinding` 提供了完整的 2D 寻路解决方案,包括 A* 算法、网格地图、导航网格和路径平滑。
## 安装
```bash
npm install @esengine/pathfinding
```
## 快速开始
### 网格地图寻路
```typescript
import { createGridMap, createAStarPathfinder } from '@esengine/pathfinding';
// 创建 20x20 的网格地图
const grid = createGridMap(20, 20);
// 设置障碍物
grid.setWalkable(5, 5, false);
grid.setWalkable(5, 6, false);
grid.setWalkable(5, 7, false);
// 创建寻路器
const pathfinder = createAStarPathfinder(grid);
// 查找路径
const result = pathfinder.findPath(0, 0, 15, 15);
if (result.found) {
console.log('找到路径!');
console.log('路径点:', result.path);
console.log('总代价:', result.cost);
console.log('搜索节点数:', result.nodesSearched);
}
```
### 导航网格寻路
```typescript
import { createNavMesh } from '@esengine/pathfinding';
// 创建导航网格
const navmesh = createNavMesh();
// 添加多边形区域
navmesh.addPolygon([
{ x: 0, y: 0 }, { x: 10, y: 0 },
{ x: 10, y: 10 }, { x: 0, y: 10 }
]);
navmesh.addPolygon([
{ x: 10, y: 0 }, { x: 20, y: 0 },
{ x: 20, y: 10 }, { x: 10, y: 10 }
]);
// 自动建立连接
navmesh.build();
// 寻路
const result = navmesh.findPath(1, 1, 18, 8);
```
## 核心概念
### IPoint - 坐标点
```typescript
interface IPoint {
readonly x: number;
readonly y: number;
}
```
### IPathResult - 寻路结果
```typescript
interface IPathResult {
readonly found: boolean; // 是否找到路径
readonly path: readonly IPoint[]; // 路径点列表
readonly cost: number; // 路径总代价
readonly nodesSearched: number; // 搜索的节点数
}
```
### IPathfindingOptions - 寻路配置
```typescript
interface IPathfindingOptions {
maxNodes?: number; // 最大搜索节点数(默认 10000
heuristicWeight?: number; // 启发式权重(>1 更快但可能非最优)
allowDiagonal?: boolean; // 是否允许对角移动(默认 true
avoidCorners?: boolean; // 是否避免穿角(默认 true
}
```
## 启发式函数
模块提供了四种启发式函数:
| 函数 | 适用场景 | 说明 |
|------|----------|------|
| `manhattanDistance` | 4方向移动 | 曼哈顿距离,只考虑水平/垂直 |
| `euclideanDistance` | 任意方向 | 欧几里得距离,直线距离 |
| `chebyshevDistance` | 8方向移动 | 切比雪夫距离,对角线代价为 1 |
| `octileDistance` | 8方向移动 | 八角距离,对角线代价为 √2默认 |
```typescript
import { manhattanDistance, octileDistance } from '@esengine/pathfinding';
// 自定义启发式
const grid = createGridMap(20, 20, {
heuristic: manhattanDistance // 使用曼哈顿距离
});
```
## 网格地图 API
### createGridMap
```typescript
function createGridMap(
width: number,
height: number,
options?: IGridMapOptions
): GridMap
```
**配置选项:**
| 属性 | 类型 | 默认值 | 描述 |
|------|------|--------|------|
| `allowDiagonal` | `boolean` | `true` | 允许对角移动 |
| `diagonalCost` | `number` | `√2` | 对角移动代价 |
| `avoidCorners` | `boolean` | `true` | 避免穿角 |
| `heuristic` | `HeuristicFunction` | `octileDistance` | 启发式函数 |
### 地图操作
```typescript
// 检查/设置可通行性
grid.isWalkable(x, y);
grid.setWalkable(x, y, false);
// 设置移动代价(如沼泽、沙地)
grid.setCost(x, y, 2); // 代价为 2默认 1
// 设置矩形区域
grid.setRectWalkable(0, 0, 5, 5, false);
// 从数组加载0=可通行非0=障碍)
grid.loadFromArray([
[0, 0, 0, 1, 0],
[0, 1, 0, 1, 0],
[0, 1, 0, 0, 0]
]);
// 从字符串加载(.=可通行,#=障碍)
grid.loadFromString(`
.....
.#.#.
.#...
`);
// 导出为字符串
console.log(grid.toString());
// 重置所有节点为可通行
grid.reset();
```
### 方向常量
```typescript
import { DIRECTIONS_4, DIRECTIONS_8 } from '@esengine/pathfinding';
// 4方向上下左右
DIRECTIONS_4 // [{ dx: 0, dy: -1 }, { dx: 1, dy: 0 }, ...]
// 8方向含对角线
DIRECTIONS_8 // [{ dx: 0, dy: -1 }, { dx: 1, dy: -1 }, ...]
```
## A* 寻路器 API
### createAStarPathfinder
```typescript
function createAStarPathfinder(map: IPathfindingMap): AStarPathfinder
```
### findPath
```typescript
const result = pathfinder.findPath(
startX, startY,
endX, endY,
{
maxNodes: 5000, // 限制搜索节点数
heuristicWeight: 1.5 // 加速但可能非最优
}
);
```
### 重用寻路器
```typescript
// 寻路器可重用,内部会自动清理状态
pathfinder.findPath(0, 0, 10, 10);
pathfinder.findPath(5, 5, 15, 15);
// 手动清理(可选)
pathfinder.clear();
```
## 导航网格 API
### createNavMesh
```typescript
function createNavMesh(): NavMesh
```
### 构建导航网格
```typescript
const navmesh = createNavMesh();
// 添加凸多边形
const id1 = navmesh.addPolygon([
{ x: 0, y: 0 }, { x: 10, y: 0 },
{ x: 10, y: 10 }, { x: 0, y: 10 }
]);
const id2 = navmesh.addPolygon([
{ x: 10, y: 0 }, { x: 20, y: 0 },
{ x: 20, y: 10 }, { x: 10, y: 10 }
]);
// 方式1自动检测共享边并建立连接
navmesh.build();
// 方式2手动设置连接
navmesh.setConnection(id1, id2, {
left: { x: 10, y: 0 },
right: { x: 10, y: 10 }
});
```
### 查询和寻路
```typescript
// 查找包含点的多边形
const polygon = navmesh.findPolygonAt(5, 5);
// 检查位置是否可通行
navmesh.isWalkable(5, 5);
// 寻路(内部使用漏斗算法优化路径)
const result = navmesh.findPath(1, 1, 18, 8);
```
## 路径平滑 API
### 视线简化
移除不必要的中间点:
```typescript
import { createLineOfSightSmoother } from '@esengine/pathfinding';
const smoother = createLineOfSightSmoother();
const smoothedPath = smoother.smooth(result.path, grid);
// 原路径: [(0,0), (1,1), (2,2), (3,3), (4,4)]
// 简化后: [(0,0), (4,4)]
```
### 曲线平滑
使用 Catmull-Rom 样条曲线:
```typescript
import { createCatmullRomSmoother } from '@esengine/pathfinding';
const smoother = createCatmullRomSmoother(
5, // segments - 每段插值点数
0.5 // tension - 张力 (0-1)
);
const curvedPath = smoother.smooth(result.path, grid);
```
### 组合平滑
先简化再曲线平滑:
```typescript
import { createCombinedSmoother } from '@esengine/pathfinding';
const smoother = createCombinedSmoother(5, 0.5);
const finalPath = smoother.smooth(result.path, grid);
```
### 视线检测函数
```typescript
import { bresenhamLineOfSight, raycastLineOfSight } from '@esengine/pathfinding';
// Bresenham 算法(快速,网格对齐)
const hasLOS = bresenhamLineOfSight(x1, y1, x2, y2, grid);
// 射线投射(精确,支持浮点坐标)
const hasLOS = raycastLineOfSight(x1, y1, x2, y2, grid, 0.5);
```
## 实际示例
### 游戏角色移动
```typescript
class MovementSystem {
private grid: GridMap;
private pathfinder: AStarPathfinder;
private smoother: CombinedSmoother;
constructor(width: number, height: number) {
this.grid = createGridMap(width, height);
this.pathfinder = createAStarPathfinder(this.grid);
this.smoother = createCombinedSmoother();
}
findPath(from: IPoint, to: IPoint): IPoint[] | null {
const result = this.pathfinder.findPath(
from.x, from.y,
to.x, to.y
);
if (!result.found) {
return null;
}
// 平滑路径
return this.smoother.smooth(result.path, this.grid);
}
setObstacle(x: number, y: number): void {
this.grid.setWalkable(x, y, false);
}
setTerrain(x: number, y: number, cost: number): void {
this.grid.setCost(x, y, cost);
}
}
```
### 动态障碍物
```typescript
class DynamicPathfinding {
private grid: GridMap;
private pathfinder: AStarPathfinder;
private dynamicObstacles: Set<string> = new Set();
addDynamicObstacle(x: number, y: number): void {
const key = `${x},${y}`;
if (!this.dynamicObstacles.has(key)) {
this.dynamicObstacles.add(key);
this.grid.setWalkable(x, y, false);
}
}
removeDynamicObstacle(x: number, y: number): void {
const key = `${x},${y}`;
if (this.dynamicObstacles.has(key)) {
this.dynamicObstacles.delete(key);
this.grid.setWalkable(x, y, true);
}
}
findPath(from: IPoint, to: IPoint): IPathResult {
return this.pathfinder.findPath(from.x, from.y, to.x, to.y);
}
}
```
### 不同地形代价
```typescript
// 设置不同地形的移动代价
const grid = createGridMap(50, 50);
// 普通地面 - 代价 1默认
// 沙地 - 代价 2
for (let y = 10; y < 20; y++) {
for (let x = 0; x < 50; x++) {
grid.setCost(x, y, 2);
}
}
// 沼泽 - 代价 4
for (let y = 30; y < 35; y++) {
for (let x = 20; x < 30; x++) {
grid.setCost(x, y, 4);
}
}
// 寻路时会自动考虑地形代价
const result = pathfinder.findPath(0, 0, 49, 49);
```
### 分层寻路
对于大型地图,使用层级化寻路:
```typescript
class HierarchicalPathfinding {
private coarseGrid: GridMap; // 粗粒度网格
private fineGrid: GridMap; // 细粒度网格
private coarsePathfinder: AStarPathfinder;
private finePathfinder: AStarPathfinder;
private cellSize = 10;
findPath(from: IPoint, to: IPoint): IPoint[] {
// 1. 在粗粒度网格上寻路
const coarseFrom = this.toCoarse(from);
const coarseTo = this.toCoarse(to);
const coarseResult = this.coarsePathfinder.findPath(
coarseFrom.x, coarseFrom.y,
coarseTo.x, coarseTo.y
);
if (!coarseResult.found) {
return [];
}
// 2. 在每个粗粒度单元内进行细粒度寻路
const finePath: IPoint[] = [];
// ... 详细实现略
return finePath;
}
private toCoarse(p: IPoint): IPoint {
return {
x: Math.floor(p.x / this.cellSize),
y: Math.floor(p.y / this.cellSize)
};
}
}
```
## 蓝图节点
Pathfinding 模块提供了可视化脚本支持的蓝图节点:
- `FindPath` - 查找路径
- `FindPathSmooth` - 查找并平滑路径
- `IsWalkable` - 检查位置是否可通行
- `GetPathLength` - 获取路径点数
- `GetPathDistance` - 获取路径总距离
- `GetPathPoint` - 获取路径上的指定点
- `MoveAlongPath` - 沿路径移动
- `HasLineOfSight` - 检查视线
## 性能优化
1. **限制搜索范围**
```typescript
pathfinder.findPath(x1, y1, x2, y2, { maxNodes: 1000 });
```
2. **使用启发式权重**
```typescript
// 权重 > 1 会更快但可能不是最优路径
pathfinder.findPath(x1, y1, x2, y2, { heuristicWeight: 1.5 });
```
3. **复用寻路器实例**
```typescript
// 创建一次,多次使用
const pathfinder = createAStarPathfinder(grid);
```
4. **使用导航网格**
- 对于复杂地形NavMesh 比网格寻路更高效
- 多边形数量远少于网格单元格数量
5. **选择合适的启发式**
- 4方向移动用 `manhattanDistance`
- 8方向移动用 `octileDistance`(默认)
## 网格 vs 导航网格
| 特性 | GridMap | NavMesh |
|------|---------|---------|
| 适用场景 | 规则瓦片地图 | 复杂多边形地形 |
| 内存占用 | 较高 (width × height) | 较低 (多边形数) |
| 精度 | 网格对齐 | 连续坐标 |
| 动态修改 | 容易 | 需要重建 |
| 设置复杂度 | 简单 | 较复杂 |

View File

@@ -0,0 +1,557 @@
# 程序化生成 (Procgen)
`@esengine/procgen` 提供了程序化内容生成的核心工具,包括噪声函数、种子随机数和各种随机工具。
## 安装
```bash
npm install @esengine/procgen
```
## 快速开始
### 噪声生成
```typescript
import { createPerlinNoise, createFBM } from '@esengine/procgen';
// 创建 Perlin 噪声
const perlin = createPerlinNoise(12345); // 种子
// 采样 2D 噪声
const value = perlin.noise2D(x * 0.1, y * 0.1);
console.log(value); // [-1, 1]
// 使用 FBM 获得更自然的效果
const fbm = createFBM(perlin, {
octaves: 6,
persistence: 0.5
});
const height = fbm.noise2D(x * 0.01, y * 0.01);
```
### 种子随机数
```typescript
import { createSeededRandom } from '@esengine/procgen';
// 创建确定性随机数生成器
const rng = createSeededRandom(42);
// 相同种子总是产生相同序列
console.log(rng.next()); // 0.xxx
console.log(rng.nextInt(1, 100)); // 1-100
console.log(rng.nextBool(0.3)); // 30% true
```
### 加权随机
```typescript
import { createWeightedRandom, createSeededRandom } from '@esengine/procgen';
const rng = createSeededRandom(42);
// 创建加权选择器
const loot = createWeightedRandom([
{ value: 'common', weight: 60 },
{ value: 'uncommon', weight: 25 },
{ value: 'rare', weight: 10 },
{ value: 'legendary', weight: 5 }
]);
// 随机选择
const drop = loot.pick(rng);
console.log(drop); // 大概率是 'common'
```
## 噪声函数
### Perlin 噪声
经典的梯度噪声,输出范围 [-1, 1]
```typescript
import { createPerlinNoise } from '@esengine/procgen';
const perlin = createPerlinNoise(seed);
// 2D 噪声
const value2D = perlin.noise2D(x, y);
// 3D 噪声
const value3D = perlin.noise3D(x, y, z);
```
### Simplex 噪声
比 Perlin 更快、更少方向性偏差:
```typescript
import { createSimplexNoise } from '@esengine/procgen';
const simplex = createSimplexNoise(seed);
const value = simplex.noise2D(x, y);
```
### Worley 噪声
基于细胞的噪声,适合生成石头、细胞等纹理:
```typescript
import { createWorleyNoise } from '@esengine/procgen';
const worley = createWorleyNoise(seed);
// 返回到最近点的距离
const distance = worley.noise2D(x, y);
```
### FBM (分形布朗运动)
叠加多层噪声创建更丰富的细节:
```typescript
import { createPerlinNoise, createFBM } from '@esengine/procgen';
const baseNoise = createPerlinNoise(seed);
const fbm = createFBM(baseNoise, {
octaves: 6, // 层数(越多细节越丰富)
lacunarity: 2.0, // 频率倍增因子
persistence: 0.5, // 振幅衰减因子
frequency: 1.0, // 初始频率
amplitude: 1.0 // 初始振幅
});
// 标准 FBM
const value = fbm.noise2D(x, y);
// Ridged FBM脊状适合山脉
const ridged = fbm.ridged2D(x, y);
// Turbulence湍流
const turb = fbm.turbulence2D(x, y);
// Billowed膨胀适合云朵
const cloud = fbm.billowed2D(x, y);
```
## 种子随机数 API
### SeededRandom
基于 xorshift128+ 算法的确定性伪随机数生成器:
```typescript
import { createSeededRandom } from '@esengine/procgen';
const rng = createSeededRandom(42);
```
### 基础方法
```typescript
// [0, 1) 浮点数
rng.next();
// [min, max] 整数
rng.nextInt(1, 10);
// [min, max) 浮点数
rng.nextFloat(0, 100);
// 布尔值(可指定概率)
rng.nextBool(); // 50%
rng.nextBool(0.3); // 30%
// 重置到初始状态
rng.reset();
```
### 分布方法
```typescript
// 正态分布(高斯分布)
rng.nextGaussian(); // 均值 0, 标准差 1
rng.nextGaussian(100, 15); // 均值 100, 标准差 15
// 指数分布
rng.nextExponential(); // λ = 1
rng.nextExponential(0.5); // λ = 0.5
```
### 几何方法
```typescript
// 圆内均匀分布的点
const point = rng.nextPointInCircle(50); // { x, y }
// 圆周上的点
const edge = rng.nextPointOnCircle(50); // { x, y }
// 球内均匀分布的点
const point3D = rng.nextPointInSphere(50); // { x, y, z }
// 随机方向向量
const dir = rng.nextDirection2D(); // { x, y },长度为 1
```
## 加权随机 API
### WeightedRandom
预计算累积权重,高效随机选择:
```typescript
import { createWeightedRandom } from '@esengine/procgen';
const selector = createWeightedRandom([
{ value: 'apple', weight: 5 },
{ value: 'banana', weight: 3 },
{ value: 'cherry', weight: 2 }
]);
// 使用种子随机数
const result = selector.pick(rng);
// 使用 Math.random
const result2 = selector.pickRandom();
// 获取概率
console.log(selector.getProbability(0)); // 0.5 (5/10)
console.log(selector.size); // 3
console.log(selector.totalWeight); // 10
```
### 便捷函数
```typescript
import { weightedPick, weightedPickFromMap } from '@esengine/procgen';
// 从数组选择
const item = weightedPick([
{ value: 'a', weight: 1 },
{ value: 'b', weight: 2 }
], rng);
// 从对象选择
const item2 = weightedPickFromMap({
'common': 60,
'rare': 30,
'epic': 10
}, rng);
```
## 洗牌和采样 API
### shuffle / shuffleCopy
Fisher-Yates 洗牌算法:
```typescript
import { shuffle, shuffleCopy } from '@esengine/procgen';
const arr = [1, 2, 3, 4, 5];
// 原地洗牌
shuffle(arr, rng);
// 创建洗牌副本(不修改原数组)
const shuffled = shuffleCopy(arr, rng);
```
### pickOne
随机选择一个元素:
```typescript
import { pickOne } from '@esengine/procgen';
const items = ['a', 'b', 'c', 'd'];
const item = pickOne(items, rng);
```
### sample / sampleWithReplacement
采样:
```typescript
import { sample, sampleWithReplacement } from '@esengine/procgen';
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// 采样 3 个不重复元素
const unique = sample(arr, 3, rng);
// 采样 5 个(可重复)
const withRep = sampleWithReplacement(arr, 5, rng);
```
### randomIntegers
生成范围内的随机整数数组:
```typescript
import { randomIntegers } from '@esengine/procgen';
// 从 1-100 中随机选 5 个不重复的数
const nums = randomIntegers(1, 100, 5, rng);
```
### weightedSample
按权重采样(不重复):
```typescript
import { weightedSample } from '@esengine/procgen';
const items = ['A', 'B', 'C', 'D', 'E'];
const weights = [10, 8, 6, 4, 2];
// 按权重选 3 个
const selected = weightedSample(items, weights, 3, rng);
```
## 实际示例
### 程序化地形生成
```typescript
import { createPerlinNoise, createFBM } from '@esengine/procgen';
class TerrainGenerator {
private fbm: FBM;
private moistureFbm: FBM;
constructor(seed: number) {
const heightNoise = createPerlinNoise(seed);
const moistureNoise = createPerlinNoise(seed + 1000);
this.fbm = createFBM(heightNoise, {
octaves: 8,
persistence: 0.5,
frequency: 0.01
});
this.moistureFbm = createFBM(moistureNoise, {
octaves: 4,
persistence: 0.6,
frequency: 0.02
});
}
getHeight(x: number, y: number): number {
// 基础高度
let height = this.fbm.noise2D(x, y);
// 添加山脉
height += this.fbm.ridged2D(x * 0.5, y * 0.5) * 0.3;
return (height + 1) * 0.5; // 归一化到 [0, 1]
}
getBiome(x: number, y: number): string {
const height = this.getHeight(x, y);
const moisture = (this.moistureFbm.noise2D(x, y) + 1) * 0.5;
if (height < 0.3) return 'water';
if (height < 0.4) return 'beach';
if (height > 0.8) return 'mountain';
if (moisture < 0.3) return 'desert';
if (moisture > 0.7) return 'forest';
return 'grassland';
}
}
```
### 战利品系统
```typescript
import { createSeededRandom, createWeightedRandom, sample } from '@esengine/procgen';
interface LootItem {
id: string;
rarity: string;
}
class LootSystem {
private rng: SeededRandom;
private raritySelector: WeightedRandom<string>;
private lootTables: Map<string, LootItem[]> = new Map();
constructor(seed: number) {
this.rng = createSeededRandom(seed);
this.raritySelector = createWeightedRandom([
{ value: 'common', weight: 60 },
{ value: 'uncommon', weight: 25 },
{ value: 'rare', weight: 10 },
{ value: 'legendary', weight: 5 }
]);
// 初始化战利品表
this.lootTables.set('common', [/* ... */]);
this.lootTables.set('rare', [/* ... */]);
// ...
}
generateLoot(count: number): LootItem[] {
const loot: LootItem[] = [];
for (let i = 0; i < count; i++) {
const rarity = this.raritySelector.pick(this.rng);
const table = this.lootTables.get(rarity)!;
const item = pickOne(table, this.rng);
loot.push(item);
}
return loot;
}
// 保证可重现
setSeed(seed: number): void {
this.rng = createSeededRandom(seed);
}
}
```
### 程序化敌人放置
```typescript
import { createSeededRandom } from '@esengine/procgen';
class EnemySpawner {
private rng: SeededRandom;
constructor(seed: number) {
this.rng = createSeededRandom(seed);
}
spawnEnemiesInArea(
centerX: number,
centerY: number,
radius: number,
count: number
): Array<{ x: number; y: number; type: string }> {
const enemies: Array<{ x: number; y: number; type: string }> = [];
for (let i = 0; i < count; i++) {
// 在圆内生成位置
const pos = this.rng.nextPointInCircle(radius);
// 随机选择敌人类型
const type = this.rng.nextBool(0.2) ? 'elite' : 'normal';
enemies.push({
x: centerX + pos.x,
y: centerY + pos.y,
type
});
}
return enemies;
}
}
```
### 程序化关卡布局
```typescript
import { createSeededRandom, shuffle } from '@esengine/procgen';
interface Room {
x: number;
y: number;
width: number;
height: number;
type: 'start' | 'combat' | 'treasure' | 'boss';
}
class DungeonGenerator {
private rng: SeededRandom;
constructor(seed: number) {
this.rng = createSeededRandom(seed);
}
generate(roomCount: number): Room[] {
const rooms: Room[] = [];
// 生成房间
for (let i = 0; i < roomCount; i++) {
rooms.push({
x: this.rng.nextInt(0, 100),
y: this.rng.nextInt(0, 100),
width: this.rng.nextInt(5, 15),
height: this.rng.nextInt(5, 15),
type: 'combat'
});
}
// 随机分配特殊房间
shuffle(rooms, this.rng);
rooms[0].type = 'start';
rooms[1].type = 'treasure';
rooms[rooms.length - 1].type = 'boss';
return rooms;
}
}
```
## 蓝图节点
Procgen 模块提供了可视化脚本支持的蓝图节点:
### 噪声节点
- `SampleNoise2D` - 采样 2D 噪声
- `SampleFBM` - 采样 FBM 噪声
### 随机节点
- `SeededRandom` - 生成随机浮点数
- `SeededRandomInt` - 生成随机整数
- `WeightedPick` - 加权随机选择
- `ShuffleArray` - 洗牌数组
- `PickRandom` - 随机选择元素
- `SampleArray` - 采样数组
- `RandomPointInCircle` - 圆内随机点
## 最佳实践
1. **使用种子保证可重现性**
```typescript
// 保存种子以便重现相同结果
const seed = Date.now();
const rng = createSeededRandom(seed);
saveSeed(seed);
```
2. **预计算加权选择器**
```typescript
// 好:创建一次,多次使用
const selector = createWeightedRandom(items);
for (let i = 0; i < 1000; i++) {
selector.pick(rng);
}
// 不好:每次都创建
for (let i = 0; i < 1000; i++) {
weightedPick(items, rng);
}
```
3. **选择合适的噪声函数**
- Perlin平滑过渡的地形、云彩
- Simplex性能要求高的场景
- Worley细胞、石头纹理
- FBM需要多层细节的自然效果
4. **调整 FBM 参数**
- `octaves`:越多细节越丰富,但性能开销越大
- `persistence`0.5 是常用值,越大高频细节越明显
- `lacunarity`:通常为 2控制频率增长速度

View File

@@ -0,0 +1,600 @@
# 空间索引系统 (Spatial)
`@esengine/spatial` 提供了高效的空间查询和索引功能,包括范围查询、最近邻查询、射线检测和 AOI兴趣区域管理。
## 安装
```bash
npm install @esengine/spatial
```
## 快速开始
### 空间索引
```typescript
import { createGridSpatialIndex } from '@esengine/spatial';
// 创建空间索引(网格单元格大小为 100
const spatialIndex = createGridSpatialIndex<Entity>(100);
// 插入对象
spatialIndex.insert(player, { x: 100, y: 200 });
spatialIndex.insert(enemy1, { x: 150, y: 250 });
spatialIndex.insert(enemy2, { x: 500, y: 600 });
// 查找半径内的对象
const nearby = spatialIndex.findInRadius({ x: 100, y: 200 }, 100);
console.log(nearby); // [player, enemy1]
// 查找最近的对象
const nearest = spatialIndex.findNearest({ x: 100, y: 200 });
console.log(nearest); // enemy1
// 更新位置
spatialIndex.update(player, { x: 120, y: 220 });
```
### AOI 兴趣区域
```typescript
import { createGridAOI } from '@esengine/spatial';
// 创建 AOI 管理器
const aoi = createGridAOI<Entity>(100);
// 添加观察者(玩家)
aoi.addObserver(player, { x: 100, y: 100 }, { viewRange: 200 });
aoi.addObserver(npc, { x: 150, y: 150 }, { viewRange: 150 });
// 监听进入/离开事件
aoi.addListener((event) => {
if (event.type === 'enter') {
console.log(`${event.observer} 看到了 ${event.target}`);
} else if (event.type === 'exit') {
console.log(`${event.target} 离开了 ${event.observer} 的视野`);
}
});
// 更新位置(会自动触发进入/离开事件)
aoi.updatePosition(player, { x: 200, y: 200 });
// 获取视野内的实体
const visible = aoi.getEntitiesInView(player);
```
## 核心概念
### 空间索引 vs AOI
| 特性 | 空间索引 (SpatialIndex) | AOI (Area of Interest) |
|------|------------------------|------------------------|
| 用途 | 通用空间查询 | 实体可见性追踪 |
| 事件 | 无事件通知 | 进入/离开事件 |
| 方向 | 单向查询 | 双向追踪(谁看到谁) |
| 场景 | 碰撞检测、范围攻击 | MMO 同步、NPC AI 感知 |
### IBounds 边界框
```typescript
interface IBounds {
readonly minX: number;
readonly minY: number;
readonly maxX: number;
readonly maxY: number;
}
```
### IRaycastHit 射线检测结果
```typescript
interface IRaycastHit<T> {
readonly target: T; // 命中的对象
readonly point: IVector2; // 命中点坐标
readonly normal: IVector2; // 命中点法线
readonly distance: number; // 距离射线起点的距离
}
```
## 空间索引 API
### createGridSpatialIndex
```typescript
function createGridSpatialIndex<T>(cellSize?: number): GridSpatialIndex<T>
```
创建基于均匀网格的空间索引。
**参数:**
- `cellSize` - 网格单元格大小(默认 100
**选择合适的 cellSize**
- 太小:内存占用高,查询效率降低
- 太大:单元格内对象过多,遍历耗时
- 建议:设置为对象平均分布间距的 1-2 倍
### 管理方法
#### insert
插入对象到索引:
```typescript
spatialIndex.insert(enemy, { x: 100, y: 200 });
```
#### remove
移除对象:
```typescript
spatialIndex.remove(enemy);
```
#### update
更新对象位置:
```typescript
spatialIndex.update(enemy, { x: 150, y: 250 });
```
#### clear
清空索引:
```typescript
spatialIndex.clear();
```
### 查询方法
#### findInRadius
查找圆形范围内的所有对象:
```typescript
// 查找中心点 (100, 200) 半径 50 内的所有敌人
const enemies = spatialIndex.findInRadius(
{ x: 100, y: 200 },
50,
(entity) => entity.type === 'enemy' // 可选过滤器
);
```
#### findInRect
查找矩形区域内的所有对象:
```typescript
import { createBounds } from '@esengine/spatial';
const bounds = createBounds(0, 0, 200, 200);
const entities = spatialIndex.findInRect(bounds);
```
#### findNearest
查找最近的对象:
```typescript
// 查找最近的敌人(最大搜索距离 500
const nearest = spatialIndex.findNearest(
playerPosition,
500, // maxDistance
(entity) => entity.type === 'enemy'
);
if (nearest) {
attackTarget(nearest);
}
```
#### findKNearest
查找最近的 K 个对象:
```typescript
// 查找最近的 5 个敌人
const nearestEnemies = spatialIndex.findKNearest(
playerPosition,
5, // k
500, // maxDistance
(entity) => entity.type === 'enemy'
);
```
#### raycast
射线检测(返回所有命中):
```typescript
const hits = spatialIndex.raycast(
origin, // 射线起点
direction, // 射线方向(应归一化)
maxDistance, // 最大检测距离
filter // 可选过滤器
);
// hits 按距离排序
for (const hit of hits) {
console.log(`命中 ${hit.target} at ${hit.point}, 距离 ${hit.distance}`);
}
```
#### raycastFirst
射线检测(仅返回第一个命中):
```typescript
const hit = spatialIndex.raycastFirst(origin, direction, 1000);
if (hit) {
dealDamage(hit.target, calculateDamage(hit.distance));
}
```
### 属性
```typescript
// 获取索引中的对象数量
console.log(spatialIndex.count);
// 获取所有对象
const all = spatialIndex.getAll();
```
## AOI 兴趣区域 API
### createGridAOI
```typescript
function createGridAOI<T>(cellSize?: number): GridAOI<T>
```
创建基于网格的 AOI 管理器。
**参数:**
- `cellSize` - 网格单元格大小(建议为平均视野范围的 1-2 倍)
### 观察者管理
#### addObserver
添加观察者:
```typescript
aoi.addObserver(player, position, {
viewRange: 200, // 视野范围
observable: true // 是否可被其他观察者看到(默认 true
});
// NPC 只观察不被观察
aoi.addObserver(camera, position, {
viewRange: 500,
observable: false
});
```
#### removeObserver
移除观察者:
```typescript
aoi.removeObserver(player);
```
#### updatePosition
更新位置(自动触发进入/离开事件):
```typescript
aoi.updatePosition(player, newPosition);
```
#### updateViewRange
更新视野范围:
```typescript
// 获得增益后视野扩大
aoi.updateViewRange(player, 300);
```
### 查询方法
#### getEntitiesInView
获取观察者视野内的所有实体:
```typescript
const visible = aoi.getEntitiesInView(player);
for (const entity of visible) {
updateEntityForPlayer(player, entity);
}
```
#### getObserversOf
获取能看到指定实体的所有观察者:
```typescript
const observers = aoi.getObserversOf(monster);
for (const observer of observers) {
notifyMonsterMoved(observer, monster);
}
```
#### canSee
检查是否可见:
```typescript
if (aoi.canSee(player, enemy)) {
enemy.showHealthBar();
}
```
### 事件系统
#### 全局事件监听
```typescript
aoi.addListener((event) => {
switch (event.type) {
case 'enter':
console.log(`${event.observer} 看到了 ${event.target}`);
break;
case 'exit':
console.log(`${event.target} 离开了 ${event.observer} 的视野`);
break;
}
});
```
#### 实体特定事件监听
```typescript
// 只监听特定玩家的视野事件
aoi.addEntityListener(player, (event) => {
if (event.type === 'enter') {
sendToClient(player, 'entity_enter', event.target);
} else if (event.type === 'exit') {
sendToClient(player, 'entity_exit', event.target);
}
});
```
#### 事件类型
```typescript
interface IAOIEvent<T> {
type: 'enter' | 'exit' | 'update';
observer: T; // 观察者(谁看到了变化)
target: T; // 目标(发生变化的对象)
position: IVector2; // 目标位置
}
```
## 工具函数
### 边界框创建
```typescript
import {
createBounds,
createBoundsFromCenter,
createBoundsFromCircle
} from '@esengine/spatial';
// 从角点创建
const bounds1 = createBounds(0, 0, 100, 100);
// 从中心点和尺寸创建
const bounds2 = createBoundsFromCenter({ x: 50, y: 50 }, 100, 100);
// 从圆形创建(包围盒)
const bounds3 = createBoundsFromCircle({ x: 50, y: 50 }, 50);
```
### 几何检测
```typescript
import {
isPointInBounds,
boundsIntersect,
boundsIntersectsCircle,
distance,
distanceSquared
} from '@esengine/spatial';
// 点在边界内?
if (isPointInBounds(point, bounds)) { ... }
// 两个边界框相交?
if (boundsIntersect(boundsA, boundsB)) { ... }
// 边界框与圆形相交?
if (boundsIntersectsCircle(bounds, center, radius)) { ... }
// 距离计算
const dist = distance(pointA, pointB);
const distSq = distanceSquared(pointA, pointB); // 更快,避免 sqrt
```
## 实际示例
### 范围攻击检测
```typescript
class CombatSystem {
private spatialIndex: ISpatialIndex<Entity>;
dealAreaDamage(center: IVector2, radius: number, damage: number): void {
const targets = this.spatialIndex.findInRadius(
center,
radius,
(entity) => entity.hasComponent(HealthComponent)
);
for (const target of targets) {
const health = target.getComponent(HealthComponent);
health.takeDamage(damage);
}
}
findNearestEnemy(position: IVector2, team: string): Entity | null {
return this.spatialIndex.findNearest(
position,
undefined, // 无距离限制
(entity) => {
const teamComp = entity.getComponent(TeamComponent);
return teamComp && teamComp.team !== team;
}
);
}
}
```
### MMO 同步系统
```typescript
class SyncSystem {
private aoi: IAOIManager<Player>;
constructor() {
this.aoi = createGridAOI<Player>(100);
// 监听进入/离开事件
this.aoi.addListener((event) => {
const packet = this.createSyncPacket(event);
this.sendToPlayer(event.observer, packet);
});
}
onPlayerJoin(player: Player): void {
this.aoi.addObserver(player, player.position, {
viewRange: player.viewRange
});
}
onPlayerMove(player: Player, newPosition: IVector2): void {
this.aoi.updatePosition(player, newPosition);
}
onPlayerLeave(player: Player): void {
this.aoi.removeObserver(player);
}
// 广播给所有能看到某玩家的其他玩家
broadcastToObservers(player: Player, packet: Packet): void {
const observers = this.aoi.getObserversOf(player);
for (const observer of observers) {
this.sendToPlayer(observer, packet);
}
}
}
```
### NPC AI 感知
```typescript
class AIPerceptionSystem {
private aoi: IAOIManager<Entity>;
constructor() {
this.aoi = createGridAOI<Entity>(50);
}
setupNPC(npc: Entity): void {
const perception = npc.getComponent(PerceptionComponent);
this.aoi.addObserver(npc, npc.position, {
viewRange: perception.range
});
// 监听该 NPC 的感知事件
this.aoi.addEntityListener(npc, (event) => {
const ai = npc.getComponent(AIComponent);
if (event.type === 'enter') {
ai.onTargetDetected(event.target);
} else if (event.type === 'exit') {
ai.onTargetLost(event.target);
}
});
}
update(): void {
// 更新所有 NPC 位置
for (const npc of this.npcs) {
this.aoi.updatePosition(npc, npc.position);
}
}
}
```
## 蓝图节点
### 空间查询节点
- `FindInRadius` - 查找半径内的对象
- `FindInRect` - 查找矩形内的对象
- `FindNearest` - 查找最近的对象
- `FindKNearest` - 查找最近的 K 个对象
- `Raycast` - 射线检测
- `RaycastFirst` - 射线检测(仅第一个)
### AOI 节点
- `GetEntitiesInView` - 获取视野内实体
- `GetObserversOf` - 获取观察者
- `CanSee` - 检查可见性
- `OnEntityEnterView` - 进入视野事件
- `OnEntityExitView` - 离开视野事件
## 服务令牌
在依赖注入场景中使用:
```typescript
import {
SpatialIndexToken,
SpatialQueryToken,
AOIManagerToken,
createGridSpatialIndex,
createGridAOI
} from '@esengine/spatial';
// 注册服务
services.register(SpatialIndexToken, createGridSpatialIndex(100));
services.register(AOIManagerToken, createGridAOI(100));
// 获取服务
const spatialIndex = services.get(SpatialIndexToken);
const aoiManager = services.get(AOIManagerToken);
```
## 性能优化
1. **选择合适的 cellSize**
- 太小:内存占用高,单元格数量多
- 太大:单元格内对象多,遍历慢
- 经验法则:对象平均间距的 1-2 倍
2. **使用过滤器减少结果**
```typescript
// 在空间查询阶段就过滤,而不是事后过滤
spatialIndex.findInRadius(center, radius, (e) => e.type === 'enemy');
```
3. **使用 distanceSquared 代替 distance**
```typescript
// 避免 sqrt 计算
if (distanceSquared(a, b) < threshold * threshold) { ... }
```
4. **批量更新优化**
```typescript
// 如果有大量对象同时移动,考虑禁用事件后批量更新
```

479
docs/modules/timer/index.md Normal file
View File

@@ -0,0 +1,479 @@
# 定时器系统 (Timer)
`@esengine/timer` 提供了一个灵活的定时器和冷却系统,用于游戏中的延迟执行、重复任务、技能冷却等场景。
## 安装
```bash
npm install @esengine/timer
```
## 快速开始
```typescript
import { createTimerService } from '@esengine/timer';
// 创建定时器服务
const timerService = createTimerService();
// 一次性定时器1秒后执行
const handle = timerService.schedule('myTimer', 1000, () => {
console.log('Timer fired!');
});
// 重复定时器每100毫秒执行
timerService.scheduleRepeating('heartbeat', 100, () => {
console.log('Tick');
});
// 冷却系统5秒冷却
timerService.startCooldown('skill_fireball', 5000);
if (timerService.isCooldownReady('skill_fireball')) {
// 可以使用技能
useFireball();
timerService.startCooldown('skill_fireball', 5000);
}
// 游戏循环中更新
function gameLoop(deltaTime: number) {
timerService.update(deltaTime);
}
```
## 核心概念
### 定时器 vs 冷却
| 特性 | 定时器 (Timer) | 冷却 (Cooldown) |
|------|---------------|-----------------|
| 用途 | 延迟执行代码 | 限制操作频率 |
| 回调 | 有回调函数 | 无回调函数 |
| 重复 | 支持重复执行 | 一次性 |
| 查询 | 查询剩余时间 | 查询进度/是否就绪 |
### TimerHandle
调度定时器后返回的句柄对象,用于控制定时器:
```typescript
interface TimerHandle {
readonly id: string; // 定时器 ID
readonly isValid: boolean; // 是否有效(未被取消)
cancel(): void; // 取消定时器
}
```
### TimerInfo
定时器信息对象:
```typescript
interface TimerInfo {
readonly id: string; // 定时器 ID
readonly remaining: number; // 剩余时间(毫秒)
readonly repeating: boolean; // 是否重复执行
readonly interval?: number; // 间隔时间(仅重复定时器)
}
```
### CooldownInfo
冷却信息对象:
```typescript
interface CooldownInfo {
readonly id: string; // 冷却 ID
readonly duration: number; // 总持续时间(毫秒)
readonly remaining: number; // 剩余时间(毫秒)
readonly progress: number; // 进度0-10=刚开始1=结束)
readonly isReady: boolean; // 是否已就绪
}
```
## API 参考
### createTimerService
```typescript
function createTimerService(config?: TimerServiceConfig): ITimerService
```
**配置选项:**
| 属性 | 类型 | 默认值 | 描述 |
|------|------|--------|------|
| `maxTimers` | `number` | `0` | 最大定时器数量0 表示无限制) |
| `maxCooldowns` | `number` | `0` | 最大冷却数量0 表示无限制) |
### 定时器 API
#### schedule
调度一次性定时器:
```typescript
const handle = timerService.schedule('explosion', 2000, () => {
createExplosion();
});
// 提前取消
handle.cancel();
```
#### scheduleRepeating
调度重复定时器:
```typescript
// 每秒执行
timerService.scheduleRepeating('regen', 1000, () => {
player.hp += 5;
});
// 立即执行一次,然后每秒重复
timerService.scheduleRepeating('tick', 1000, () => {
console.log('Tick');
}, true); // immediate = true
```
#### cancel / cancelById
取消定时器:
```typescript
// 通过句柄取消
handle.cancel();
// 或
timerService.cancel(handle);
// 通过 ID 取消
timerService.cancelById('regen');
```
#### hasTimer
检查定时器是否存在:
```typescript
if (timerService.hasTimer('explosion')) {
console.log('Explosion is pending');
}
```
#### getTimerInfo
获取定时器信息:
```typescript
const info = timerService.getTimerInfo('explosion');
if (info) {
console.log(`剩余时间: ${info.remaining}ms`);
console.log(`是否重复: ${info.repeating}`);
}
```
### 冷却 API
#### startCooldown
开始冷却:
```typescript
// 5秒冷却
timerService.startCooldown('skill_fireball', 5000);
```
#### isCooldownReady / isOnCooldown
检查冷却状态:
```typescript
if (timerService.isCooldownReady('skill_fireball')) {
// 可以使用技能
castFireball();
timerService.startCooldown('skill_fireball', 5000);
} else {
console.log('技能还在冷却中');
}
// 或使用 isOnCooldown
if (timerService.isOnCooldown('skill_fireball')) {
console.log('冷却中...');
}
```
#### getCooldownProgress / getCooldownRemaining
获取冷却进度:
```typescript
// 进度 0-10=刚开始1=完成)
const progress = timerService.getCooldownProgress('skill_fireball');
console.log(`冷却进度: ${(progress * 100).toFixed(0)}%`);
// 剩余时间(毫秒)
const remaining = timerService.getCooldownRemaining('skill_fireball');
console.log(`剩余时间: ${(remaining / 1000).toFixed(1)}s`);
```
#### getCooldownInfo
获取完整冷却信息:
```typescript
const info = timerService.getCooldownInfo('skill_fireball');
if (info) {
console.log(`总时长: ${info.duration}ms`);
console.log(`剩余: ${info.remaining}ms`);
console.log(`进度: ${info.progress}`);
console.log(`就绪: ${info.isReady}`);
}
```
#### resetCooldown / clearAllCooldowns
重置冷却:
```typescript
// 重置单个冷却
timerService.resetCooldown('skill_fireball');
// 清除所有冷却(例如角色复活时)
timerService.clearAllCooldowns();
```
### 生命周期
#### update
更新定时器服务(需要每帧调用):
```typescript
function gameLoop(deltaTime: number) {
// deltaTime 单位是毫秒
timerService.update(deltaTime);
}
```
#### clear
清除所有定时器和冷却:
```typescript
timerService.clear();
```
### 调试属性
```typescript
// 获取活跃定时器数量
console.log(timerService.activeTimerCount);
// 获取活跃冷却数量
console.log(timerService.activeCooldownCount);
// 获取所有活跃定时器 ID
const timerIds = timerService.getActiveTimerIds();
// 获取所有活跃冷却 ID
const cooldownIds = timerService.getActiveCooldownIds();
```
## 实际示例
### 技能冷却系统
```typescript
import { createTimerService, type ITimerService } from '@esengine/timer';
class SkillSystem {
private timerService: ITimerService;
private skills: Map<string, SkillData> = new Map();
constructor() {
this.timerService = createTimerService();
}
registerSkill(id: string, data: SkillData): void {
this.skills.set(id, data);
}
useSkill(skillId: string): boolean {
const skill = this.skills.get(skillId);
if (!skill) return false;
// 检查冷却
if (!this.timerService.isCooldownReady(skillId)) {
const remaining = this.timerService.getCooldownRemaining(skillId);
console.log(`技能 ${skillId} 冷却中,剩余 ${remaining}ms`);
return false;
}
// 使用技能
this.executeSkill(skill);
// 开始冷却
this.timerService.startCooldown(skillId, skill.cooldown);
return true;
}
getSkillCooldownProgress(skillId: string): number {
return this.timerService.getCooldownProgress(skillId);
}
update(dt: number): void {
this.timerService.update(dt);
}
}
interface SkillData {
cooldown: number;
// ... other properties
}
```
### 延迟和定时效果
```typescript
class EffectSystem {
private timerService: ITimerService;
constructor(timerService: ITimerService) {
this.timerService = timerService;
}
// 延迟爆炸
scheduleExplosion(position: { x: number; y: number }, delay: number): void {
this.timerService.schedule(`explosion_${Date.now()}`, delay, () => {
this.createExplosion(position);
});
}
// DOT 伤害(每秒造成伤害)
applyDOT(target: Entity, damage: number, duration: number): void {
const dotId = `dot_${target.id}_${Date.now()}`;
let elapsed = 0;
this.timerService.scheduleRepeating(dotId, 1000, () => {
elapsed += 1000;
target.takeDamage(damage);
if (elapsed >= duration) {
this.timerService.cancelById(dotId);
}
});
}
// BUFF 效果(持续一段时间)
applyBuff(target: Entity, buffId: string, duration: number): void {
target.addBuff(buffId);
this.timerService.schedule(`buff_expire_${buffId}`, duration, () => {
target.removeBuff(buffId);
});
}
}
```
### 与 ECS 集成
```typescript
import { Component, EntitySystem, Matcher } from '@esengine/ecs-framework';
import { createTimerService, type ITimerService } from '@esengine/timer';
// 定时器组件
class TimerComponent extends Component {
timerService: ITimerService;
constructor() {
super();
this.timerService = createTimerService();
}
}
// 定时器系统
class TimerSystem extends EntitySystem {
constructor() {
super(Matcher.all(TimerComponent));
}
protected processEntity(entity: Entity, dt: number): void {
const timer = entity.getComponent(TimerComponent);
timer.timerService.update(dt);
}
}
// 冷却组件(用于共享冷却)
class CooldownComponent extends Component {
constructor(public timerService: ITimerService) {
super();
}
}
```
## 蓝图节点
Timer 模块提供了可视化脚本支持的蓝图节点:
### 冷却节点
- `StartCooldown` - 开始冷却
- `IsCooldownReady` - 检查冷却是否就绪
- `GetCooldownProgress` - 获取冷却进度
- `GetCooldownInfo` - 获取详细冷却信息
- `ResetCooldown` - 重置冷却
### 定时器节点
- `HasTimer` - 检查定时器是否存在
- `CancelTimer` - 取消定时器
- `GetTimerRemaining` - 获取定时器剩余时间
## 服务令牌
在依赖注入场景中使用:
```typescript
import { TimerServiceToken, createTimerService } from '@esengine/timer';
// 注册服务
services.register(TimerServiceToken, createTimerService());
// 获取服务
const timerService = services.get(TimerServiceToken);
```
## 最佳实践
1. **使用有意义的 ID**:使用描述性的 ID 便于调试和管理
```typescript
// 好
timerService.startCooldown('skill_fireball', 5000);
// 不好
timerService.startCooldown('cd1', 5000);
```
2. **避免重复 ID**:相同 ID 的定时器会覆盖之前的
```typescript
// 使用唯一 ID
const uniqueId = `explosion_${entity.id}_${Date.now()}`;
timerService.schedule(uniqueId, 1000, callback);
```
3. **及时清理**:在适当时机清理不需要的定时器和冷却
```typescript
// 实体销毁时
onDestroy() {
this.timerService.cancelById(this.timerId);
}
```
4. **配置限制**:在生产环境考虑设置最大数量限制
```typescript
const timerService = createTimerService({
maxTimers: 1000,
maxCooldowns: 500
});
```

View File

@@ -5,7 +5,16 @@
"private": true,
"packageManager": "pnpm@10.22.0",
"workspaces": [
"packages/*"
"packages/framework/*",
"packages/engine/*",
"packages/rendering/*",
"packages/physics/*",
"packages/streaming/*",
"packages/network-ext/*",
"packages/editor/*",
"packages/editor/plugins/*",
"packages/rust/*",
"packages/tools/*"
],
"keywords": [
"ecs",
@@ -17,6 +26,9 @@
"egret"
],
"scripts": {
"changeset": "changeset",
"changeset:version": "changeset version",
"changeset:publish": "changeset publish",
"bootstrap": "lerna bootstrap",
"clean": "turbo run clean",
"build": "turbo run build",
@@ -25,23 +37,24 @@
"build:math": "turbo run build --filter=@esengine/ecs-framework-math",
"build:editor": "turbo run build --filter=@esengine/editor-app...",
"build:npm": "turbo run build:npm",
"build:npm:core": "cd packages/core && npm run build:npm",
"build:npm:math": "cd packages/math && npm run build:npm",
"build:npm:core": "cd packages/framework/core && npm run build:npm",
"build:npm:math": "cd packages/framework/math && npm run build:npm",
"test": "turbo run test",
"test:coverage": "turbo run test:coverage",
"test:ci": "turbo run test:ci",
"test:ci:framework": "turbo run test:ci --filter=@esengine/ecs-framework --filter=@esengine/ecs-framework-math --filter=@esengine/behavior-tree --filter=@esengine/blueprint --filter=@esengine/fsm --filter=@esengine/timer --filter=@esengine/spatial --filter=@esengine/procgen --filter=@esengine/pathfinding --filter=@esengine/network-protocols --filter=@esengine/network",
"prepare:publish": "npm run build:npm && node scripts/pre-publish-check.cjs",
"sync:versions": "node scripts/sync-versions.cjs",
"publish:all": "npm run prepare:publish && npm run publish:all:dist",
"publish:all:dist": "npm run publish:core && npm run publish:math",
"publish:core": "cd packages/core && npm run publish:npm",
"publish:core:patch": "cd packages/core && npm run publish:patch",
"publish:math": "cd packages/math && npm run publish:npm",
"publish:math:patch": "cd packages/math && npm run publish:patch",
"publish:core": "cd packages/framework/core && npm run publish:npm",
"publish:core:patch": "cd packages/framework/core && npm run publish:patch",
"publish:math": "cd packages/framework/math && npm run publish:npm",
"publish:math:patch": "cd packages/framework/math && npm run publish:patch",
"publish": "lerna publish",
"version": "lerna version",
"release": "semantic-release",
"release:core": "cd packages/core && semantic-release",
"release:core": "cd packages/framework/core && semantic-release",
"contributors:add": "all-contributors add",
"contributors:generate": "all-contributors generate",
"contributors:check": "all-contributors check",
@@ -55,15 +68,19 @@
"format": "prettier --write \"packages/**/src/**/*.{ts,tsx,js,jsx}\"",
"format:check": "prettier --check \"packages/**/src/**/*.{ts,tsx,js,jsx}\"",
"type-check": "turbo run type-check",
"type-check:framework": "turbo run type-check --filter=@esengine/ecs-framework --filter=@esengine/ecs-framework-math --filter=@esengine/behavior-tree --filter=@esengine/blueprint --filter=@esengine/fsm --filter=@esengine/timer --filter=@esengine/spatial --filter=@esengine/procgen --filter=@esengine/pathfinding --filter=@esengine/network-protocols --filter=@esengine/network",
"lint": "turbo run lint",
"lint:framework": "turbo run lint --filter=@esengine/ecs-framework --filter=@esengine/ecs-framework-math --filter=@esengine/behavior-tree --filter=@esengine/blueprint --filter=@esengine/fsm --filter=@esengine/timer --filter=@esengine/spatial --filter=@esengine/procgen --filter=@esengine/pathfinding --filter=@esengine/network-protocols --filter=@esengine/network",
"lint:fix": "turbo run lint:fix",
"build:wasm": "cd packages/engine && wasm-pack build --dev --out-dir pkg",
"build:wasm:release": "cd packages/engine && wasm-pack build --release --out-dir pkg",
"build:wasm": "cd packages/rust/engine && wasm-pack build --dev --out-dir pkg",
"build:wasm:release": "cd packages/rust/engine && wasm-pack build --release --out-dir pkg",
"copy-modules": "node scripts/copy-engine-modules.mjs"
},
"author": "yhh",
"license": "MIT",
"devDependencies": {
"@changesets/changelog-github": "^0.5.2",
"@changesets/cli": "^2.29.8",
"@commitlint/cli": "^18.6.0",
"@commitlint/config-conventional": "^18.6.0",
"@eslint/js": "^9.39.1",
@@ -121,4 +138,3 @@
"ws": "^8.18.2"
}
}

View File

@@ -1,46 +0,0 @@
{
"name": "@esengine/audio",
"version": "1.0.0",
"description": "ECS-based audio system",
"esengine": {
"plugin": true,
"pluginExport": "AudioPlugin",
"category": "audio",
"isEnginePlugin": true
},
"main": "dist/index.js",
"module": "dist/index.js",
"types": "dist/index.d.ts",
"type": "module",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
}
},
"files": [
"dist"
],
"scripts": {
"build": "tsup",
"build:watch": "tsup --watch",
"type-check": "tsc --noEmit",
"clean": "rimraf dist"
},
"devDependencies": {
"@esengine/ecs-framework": "workspace:*",
"@esengine/engine-core": "workspace:*",
"@esengine/build-config": "workspace:*",
"rimraf": "^5.0.5",
"tsup": "^8.0.0",
"typescript": "^5.3.3"
},
"keywords": [
"ecs",
"audio",
"sound",
"music"
],
"author": "yhh",
"license": "MIT"
}

View File

@@ -1,13 +0,0 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"composite": true,
"outDir": "./dist",
"rootDir": "./src"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"],
"references": [
{ "path": "../core" }
]
}

View File

@@ -1,52 +0,0 @@
{
"name": "@esengine/behavior-tree-editor",
"version": "1.0.0",
"description": "Editor support for @esengine/behavior-tree - visual editor, inspectors, and tools",
"main": "dist/index.js",
"module": "dist/index.js",
"types": "dist/index.d.ts",
"type": "module",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
}
},
"files": [
"dist"
],
"scripts": {
"build": "tsup",
"build:watch": "tsup --watch",
"type-check": "tsc --noEmit",
"clean": "rimraf dist"
},
"dependencies": {
"@esengine/behavior-tree": "workspace:*"
},
"peerDependencies": {
"@esengine/editor-core": "workspace:*"
},
"devDependencies": {
"@esengine/ecs-framework": "workspace:*",
"@esengine/engine-core": "workspace:*",
"@esengine/editor-core": "workspace:*",
"@esengine/editor-runtime": "workspace:*",
"@esengine/node-editor": "workspace:*",
"@esengine/build-config": "workspace:*",
"lucide-react": "^0.545.0",
"react": "^18.3.1",
"zustand": "^5.0.8",
"@types/react": "^18.3.12",
"rimraf": "^5.0.5",
"tsup": "^8.0.0",
"typescript": "^5.3.3"
},
"keywords": [
"ecs",
"behavior-tree",
"editor"
],
"author": "",
"license": "MIT"
}

View File

@@ -1,17 +0,0 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"composite": true,
"outDir": "./dist",
"rootDir": "./src",
"declaration": true,
"jsx": "react-jsx"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"],
"references": [
{ "path": "../core" },
{ "path": "../editor-core" },
{ "path": "../behavior-tree" }
]
}

View File

@@ -1,41 +0,0 @@
/**
* @esengine/behavior-tree
*
* AI Behavior Tree System with runtime execution and visual editor support
* AI 行为树系统,支持运行时执行和可视化编辑
*
* @packageDocumentation
*/
// Constants
export { BehaviorTreeAssetType } from './constants';
// Types
export * from './Types/TaskStatus';
// Execution (runtime core)
export * from './execution';
// Utilities
export * from './BehaviorTreeStarter';
export * from './BehaviorTreeBuilder';
// Serialization
export * from './Serialization/NodeTemplates';
export * from './Serialization/BehaviorTreeAsset';
export * from './Serialization/EditorFormatConverter';
export * from './Serialization/BehaviorTreeAssetSerializer';
export * from './Serialization/EditorToBehaviorTreeDataConverter';
// Services
export * from './Services/GlobalBlackboardService';
// Blackboard types (excluding BlackboardValueType which is already exported from TaskStatus)
export type { BlackboardTypeDefinition } from './Blackboard/BlackboardTypes';
export { BlackboardTypes } from './Blackboard/BlackboardTypes';
// Runtime module and plugin
export { BehaviorTreeRuntimeModule, BehaviorTreePlugin } from './BehaviorTreeRuntimeModule';
// Service tokens | 服务令牌
export { BehaviorTreeSystemToken } from './tokens';

View File

@@ -1,52 +0,0 @@
{
"name": "@esengine/blueprint-editor",
"version": "1.0.0",
"description": "Editor support for @esengine/blueprint - visual scripting editor",
"main": "dist/index.js",
"module": "dist/index.js",
"types": "dist/index.d.ts",
"type": "module",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
}
},
"files": [
"dist"
],
"scripts": {
"build": "tsup",
"build:watch": "tsup --watch",
"type-check": "tsc --noEmit",
"clean": "rimraf dist"
},
"dependencies": {
"@esengine/blueprint": "workspace:*"
},
"peerDependencies": {
"@esengine/editor-core": "workspace:*"
},
"devDependencies": {
"@esengine/ecs-framework": "workspace:*",
"@esengine/engine-core": "workspace:*",
"@esengine/editor-core": "workspace:*",
"@esengine/node-editor": "workspace:*",
"@esengine/build-config": "workspace:*",
"lucide-react": "^0.545.0",
"react": "^18.3.1",
"zustand": "^5.0.8",
"@types/react": "^18.3.12",
"rimraf": "^5.0.5",
"tsup": "^8.0.0",
"typescript": "^5.3.3"
},
"keywords": [
"ecs",
"blueprint",
"editor",
"visual-scripting"
],
"author": "",
"license": "MIT"
}

View File

@@ -1,40 +0,0 @@
/**
* @esengine/blueprint - Visual scripting system for ECS Framework
* 蓝图可视化脚本系统
*/
// Types
export * from './types';
// Runtime
export * from './runtime';
// Triggers
export * from './triggers';
// Composition
export * from './composition';
// Nodes (import to register)
import './nodes';
// Re-export commonly used items
export { NodeRegistry, RegisterNode } from './runtime/NodeRegistry';
export { BlueprintVM } from './runtime/BlueprintVM';
export {
createBlueprintComponentData,
initializeBlueprintVM,
startBlueprint,
stopBlueprint,
tickBlueprint,
cleanupBlueprint
} from './runtime/BlueprintComponent';
export {
createBlueprintSystem,
triggerBlueprintEvent,
triggerCustomBlueprintEvent
} from './runtime/BlueprintSystem';
export { createEmptyBlueprint, validateBlueprintAsset } from './types/blueprint';
// Plugin
export { BlueprintPlugin } from './BlueprintPlugin';

View File

@@ -1,39 +0,0 @@
{
"name": "@esengine/build-config",
"version": "1.0.0",
"description": "Shared build configuration for ES Engine packages",
"type": "module",
"main": "src/index.ts",
"exports": {
".": "./src/index.ts",
"./presets": "./src/presets/index.ts",
"./presets/tsup": "./src/presets/plugin-tsup.ts",
"./plugins": "./src/plugins/index.ts"
},
"scripts": {
"type-check": "tsc --noEmit"
},
"keywords": [
"build",
"tsup",
"config"
],
"author": "yhh",
"license": "MIT",
"devDependencies": {
"@vitejs/plugin-react": "^4.3.4",
"tsup": "^8.0.0",
"typescript": "^5.8.3",
"vite": "^6.3.5",
"vite-plugin-dts": "^4.5.4"
},
"peerDependencies": {
"tsup": "^8.0.0",
"vite": "^6.0.0"
},
"peerDependenciesMeta": {
"vite": {
"optional": true
}
}
}

View File

@@ -1,48 +0,0 @@
{
"name": "@esengine/camera-editor",
"version": "1.0.0",
"description": "Editor components for camera system",
"main": "dist/index.js",
"module": "dist/index.js",
"types": "dist/index.d.ts",
"type": "module",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
}
},
"files": [
"dist"
],
"scripts": {
"build": "tsup",
"build:watch": "tsup --watch",
"type-check": "tsc --noEmit",
"clean": "rimraf dist"
},
"dependencies": {
"@esengine/camera": "workspace:*"
},
"peerDependencies": {
"@esengine/editor-core": "workspace:*"
},
"devDependencies": {
"@esengine/ecs-framework": "workspace:*",
"@esengine/engine-core": "workspace:*",
"@esengine/editor-core": "workspace:*",
"@esengine/build-config": "workspace:*",
"react": "^18.3.1",
"@types/react": "^18.2.0",
"rimraf": "^5.0.5",
"tsup": "^8.0.0",
"typescript": "^5.3.3"
},
"keywords": [
"ecs",
"camera",
"editor"
],
"author": "yhh",
"license": "MIT"
}

View File

@@ -1,16 +0,0 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"composite": true,
"outDir": "./dist",
"rootDir": "./src",
"jsx": "react-jsx"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"],
"references": [
{ "path": "../core" },
{ "path": "../camera" },
{ "path": "../editor-core" }
]
}

View File

@@ -1,48 +0,0 @@
{
"name": "@esengine/camera",
"version": "1.0.0",
"description": "Camera component and systems for 2D/3D rendering",
"esengine": {
"plugin": true,
"pluginExport": "CameraPlugin",
"category": "core",
"isEnginePlugin": true
},
"main": "dist/index.js",
"module": "dist/index.js",
"types": "dist/index.d.ts",
"type": "module",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
}
},
"files": [
"dist"
],
"scripts": {
"build": "tsup",
"build:watch": "tsup --watch",
"type-check": "tsc --noEmit",
"clean": "rimraf dist"
},
"devDependencies": {
"@esengine/ecs-framework": "workspace:*",
"@esengine/ecs-framework-math": "workspace:*",
"@esengine/engine-core": "workspace:*",
"@esengine/build-config": "workspace:*",
"rimraf": "^5.0.5",
"tsup": "^8.0.0",
"typescript": "^5.3.3"
},
"keywords": [
"ecs",
"camera",
"2d",
"3d",
"rendering"
],
"author": "yhh",
"license": "MIT"
}

View File

@@ -1,13 +0,0 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"composite": true,
"outDir": "./dist",
"rootDir": "./src"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"],
"references": [
{ "path": "../core" }
]
}

View File

@@ -1,7 +0,0 @@
import { defineConfig } from 'tsup';
import { runtimeOnlyPreset } from '../build-config/src/presets/plugin-tsup';
export default defineConfig({
...runtimeOnlyPreset(),
tsconfig: 'tsconfig.build.json'
});

View File

@@ -1,62 +0,0 @@
{
"name": "@esengine/ecs-engine-bindgen",
"version": "0.1.0",
"description": "Bridge layer between ECS Framework and Rust Engine | ECS框架与Rust引擎之间的桥接层",
"main": "dist/index.js",
"module": "dist/index.js",
"types": "dist/index.d.ts",
"type": "module",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
}
},
"files": [
"dist"
],
"scripts": {
"build": "tsup",
"build:watch": "tsup --watch",
"clean": "rimraf dist"
},
"repository": {
"type": "git",
"url": "https://github.com/esengine/esengine.git",
"directory": "packages/ecs-engine-bindgen"
},
"keywords": [
"ecs",
"game-engine",
"bridge",
"wasm",
"typescript"
],
"author": "ESEngine Team",
"license": "MIT",
"dependencies": {
"@esengine/ecs-framework": "workspace:*",
"@esengine/ecs-framework-math": "workspace:*",
"@esengine/engine-core": "workspace:*",
"@esengine/asset-system": "workspace:*",
"@esengine/material-system": "workspace:*"
},
"peerDependencies": {
"@esengine/sprite": "workspace:*",
"@esengine/camera": "workspace:*"
},
"peerDependenciesMeta": {
"@esengine/sprite": { "optional": true },
"@esengine/camera": { "optional": true }
},
"optionalDependencies": {
"es-engine": "file:../engine/pkg"
},
"devDependencies": {
"@esengine/sprite": "workspace:*",
"@esengine/camera": "workspace:*",
"tsup": "^8.5.1",
"typescript": "^5.8.0",
"rimraf": "^5.0.0"
}
}

View File

Before

Width:  |  Height:  |  Size: 4.4 KiB

After

Width:  |  Height:  |  Size: 4.4 KiB

View File

Before

Width:  |  Height:  |  Size: 10 KiB

After

Width:  |  Height:  |  Size: 10 KiB

View File

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 13 KiB

View File

Before

Width:  |  Height:  |  Size: 915 B

After

Width:  |  Height:  |  Size: 915 B

View File

Before

Width:  |  Height:  |  Size: 30 KiB

After

Width:  |  Height:  |  Size: 30 KiB

View File

Before

Width:  |  Height:  |  Size: 2.0 KiB

After

Width:  |  Height:  |  Size: 2.0 KiB

View File

Before

Width:  |  Height:  |  Size: 3.7 KiB

After

Width:  |  Height:  |  Size: 3.7 KiB

View File

Before

Width:  |  Height:  |  Size: 5.1 KiB

After

Width:  |  Height:  |  Size: 5.1 KiB

View File

Before

Width:  |  Height:  |  Size: 5.6 KiB

After

Width:  |  Height:  |  Size: 5.6 KiB

View File

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 12 KiB

View File

Before

Width:  |  Height:  |  Size: 888 B

After

Width:  |  Height:  |  Size: 888 B

View File

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 13 KiB

View File

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 1.4 KiB

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