Compare commits

...

25 Commits

Author SHA1 Message Date
github-actions[bot]
cc6f12d470 chore: release packages (#405)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-12-31 10:11:24 +08:00
YHH
902c0a1074 chore: add changeset for HTTP file routing (#404) 2025-12-31 10:06:40 +08:00
yhh
d3e489aad3 feat(server): add HTTP file-based routing support
- Add file-based HTTP routing with httpDir and httpPrefix config options
- Create defineHttp<TBody>() helper for type-safe route definitions
- Support dynamic routes with [param].ts file naming convention
- Add CORS support for cross-origin requests
- Allow merging file routes with inline http config
- RPC server now supports attaching to existing HTTP server via server option
- Add comprehensive documentation for HTTP routing
2025-12-31 09:53:12 +08:00
yhh
12051d987f docs(network): add custom authentication provider documentation
- Add IAuthProvider interface documentation
- Add database password authentication example
- Add OAuth/third-party authentication example
- Add API Key authentication example
- Add guide for using and combining multiple providers
2025-12-30 22:46:40 +08:00
yhh
b38fe5ebf4 docs(editor): improve editor-app build documentation and add build:rapier2d script
- Add `pnpm build:rapier2d` command to automate Rapier2D WASM build process
- Fix gen-src.mjs path to correctly locate thirdparty/rapier.js
- Update init.ts to work with new wasm-pack web target (auto-initialization)
- Fix behavior-tree-editor build config for asset-system dependency
- Update README_CN.md and README.md with simplified build instructions
2025-12-30 22:33:06 +08:00
yhh
f01ce1e320 chore: update lawn-mower-demo submodule (airstrike sync fix) 2025-12-30 21:21:51 +08:00
github-actions[bot]
094133a71a chore: release packages (#403)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-12-30 20:55:04 +08:00
YHH
3e5b7783be fix(ecs): resolve ESM require is not defined error (#402)
- Add RuntimeConfig module as standalone runtime environment storage
- Core.runtimeEnvironment and Scene.runtimeEnvironment now read from RuntimeConfig
- Remove require() call in Scene.ts to fix Node.js ESM compatibility

Fixes ReferenceError: require is not defined when using scene.isServer in ESM environment
2025-12-30 20:52:29 +08:00
github-actions[bot]
ebcb4d00a8 chore: release packages (#401)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-12-30 20:35:23 +08:00
YHH
d2af9caae9 feat(behavior-tree): add pure BehaviorTreePlugin for Cocos/Laya integration (#400)
- Add BehaviorTreePlugin class that only depends on @esengine/ecs-framework
- Implement IPlugin interface with install(), uninstall(), setupScene() methods
- Remove esengine/ subdirectory that incorrectly depended on engine-core
- Update package documentation with correct usage examples
2025-12-30 20:31:52 +08:00
yhh
bb696c6a60 chore: update lawn-mower-demo submodule to 2.7.0 2025-12-30 18:56:44 +08:00
github-actions[bot]
ffd35a71cd chore: release packages (#399)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-12-30 18:08:38 +08:00
YHH
1f3a76aabe feat(ecs): 添加运行时环境区分机制 | add runtime environment detection (#398)
- Core 新增静态属性 runtimeEnvironment,支持 'server' | 'client' | 'standalone'
- Core 新增 isServer / isClient 静态只读属性
- ICoreConfig 新增 runtimeEnvironment 配置项
- Scene 新增 isServer / isClient 只读属性(默认从 Core 继承,可通过 config 覆盖)
- 新增 @ServerOnly() / @ClientOnly() / @NotServer() / @NotClient() 方法装饰器
- 更新中英文文档

用于网络游戏中区分服务端权威逻辑和客户端逻辑
2025-12-30 17:56:06 +08:00
github-actions[bot]
ddc7d1f726 chore: release packages (#397)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-12-30 16:59:49 +08:00
YHH
04b08f3f07 fix(ecs): add entity field to COMPONENT_ADDED event (#396)
Fix missing entity field in COMPONENT_ADDED event payload that caused
ECSRoom's @NetworkEntity auto-broadcast to fail with 'Cannot read
properties of undefined'
2025-12-30 16:57:11 +08:00
yhh
d9969d0b08 Merge branch 'master' of https://github.com/esengine/esengine 2025-12-30 16:23:54 +08:00
YHH
bdbbf8a80a feat(ecs): 添加 @NetworkEntity 装饰器,支持自动广播实体生成/销毁 (#395)
* docs: add editor-app README with setup instructions

* docs: add separate EN/CN editor setup guides

* feat(ecs): add @NetworkEntity decorator for auto spawn/despawn broadcasting

- Add @NetworkEntity decorator to mark components for automatic network broadcasting
- ECSRoom now auto-broadcasts spawn on component:added event
- ECSRoom now auto-broadcasts despawn on entity:destroyed event
- Entity.destroy() emits entity:destroyed event via ECSEventType
- Entity active state changes emit ENTITY_ENABLED/ENTITY_DISABLED events
- Add enableAutoNetworkEntity config option to ECSRoom (default true)
- Update documentation for both Chinese and English
2025-12-30 16:19:01 +08:00
yhh
1368473c71 Merge remote master 2025-12-30 12:29:24 +08:00
YHH
b28169b186 fix(editor): fix build errors and refactor behavior-tree architecture (#394)
* docs: add editor-app README with setup instructions

* docs: add separate EN/CN editor setup guides

* fix(editor): fix build errors and refactor behavior-tree architecture

- Fix fairygui-editor tsconfig extends path and add missing tsconfig.build.json
- Refactor behavior-tree-editor to not depend on asset-system in runtime
  - Create local BehaviorTreeRuntimeModule for pure runtime logic
  - Move asset loader registration to editor module install()
  - Add BehaviorTreeLoader for asset system integration
- Fix rapier2d WASM loader to not pass arguments to init()
- Add WASM base64 loader config to rapier2d tsup.config
- Update README documentation and simplify setup steps
2025-12-30 11:13:26 +08:00
yhh
e2598b2292 docs: add separate EN/CN editor setup guides 2025-12-30 10:02:53 +08:00
yhh
2e3889abed docs: add editor-app README with setup instructions 2025-12-30 09:54:41 +08:00
github-actions[bot]
d21caa974e chore: release packages (#393)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-12-30 09:41:17 +08:00
YHH
a08a84b7db fix(sync): use GlobalComponentRegistry for network sync decoding (#392)
- Decoder.ts now uses GlobalComponentRegistry.getComponentType() instead of local registry
- @sync decorator uses getComponentTypeName() to get @ECSComponent decorator name
- @ECSComponent decorator updates SYNC_METADATA.typeId when defined
- Removed deprecated registerSyncComponent/autoRegisterSyncComponent functions
- Updated ComponentSync.ts in network package to use GlobalComponentRegistry
- Updated tests to use correct @ECSComponent type names

This ensures that components decorated with @ECSComponent are automatically
available for network sync decoding without any manual registration.
2025-12-30 09:39:17 +08:00
github-actions[bot]
449bd420a6 chore: release packages (#391)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-12-29 21:10:36 +08:00
YHH
1f297ac769 feat(ecs): ECS 网络状态同步系统 | add ECS network state synchronization (#390)
## @esengine/ecs-framework

新增 @sync 装饰器和二进制编解码器,支持基于 Component 的网络状态同步:

- `sync` 装饰器标记需要同步的字段
- `ChangeTracker` 组件变更追踪
- 二进制编解码器 (BinaryWriter/BinaryReader)
- `encodeSnapshot`/`decodeSnapshot` 批量编解码
- `encodeSpawn`/`decodeSpawn` 实体生成编解码
- `encodeDespawn`/`processDespawn` 实体销毁编解码

将以下方法标记为 @internal,用户应通过 Core.update() 驱动更新:
- Scene.update()
- SceneManager.update()
- WorldManager.updateAll()

## @esengine/network

- 新增 ComponentSyncSystem 基于 @sync 自动同步组件状态
- 将 ecs-framework 从 devDependencies 移到 peerDependencies

## @esengine/server

新增 ECSRoom,带有 ECS World 支持的房间基类:

- 每个 ECSRoom 在 Core.worldManager 中创建独立的 World
- Core.update() 统一更新 Time 和所有 World
- onTick() 只处理状态同步逻辑
- 自动创建/销毁玩家实体
- 增量状态广播
2025-12-29 21:08:34 +08:00
113 changed files with 9820 additions and 904 deletions

View File

@@ -228,6 +228,7 @@ If you want a complete engine solution with rendering:
A visual editor built with Tauri for scene management:
- Download from [Releases](https://github.com/esengine/esengine/releases)
- [Build from source](./packages/editor/editor-app/README.md)
- Supports behavior tree editing, tilemap painting, visual scripting
## Project Structure
@@ -281,6 +282,7 @@ pnpm test
- [ECS Framework Guide](./packages/framework/core/README.md)
- [Behavior Tree Guide](./packages/framework/behavior-tree/README.md)
- [Editor Setup Guide](./packages/editor/editor-app/README.md) ([中文](./packages/editor/editor-app/README_CN.md))
- [API Reference](https://esengine.cn/api/README)
## Community

View File

@@ -228,6 +228,7 @@ npm install @esengine/world-streaming # 世界流送
基于 Tauri 构建的可视化编辑器:
- 从 [Releases](https://github.com/esengine/esengine/releases) 下载
- [从源码构建](./packages/editor/editor-app/README.md)
- 支持行为树编辑、Tilemap 绘制、可视化脚本
## 项目结构
@@ -281,6 +282,7 @@ pnpm test
- [ECS 框架指南](./packages/framework/core/README.md)
- [行为树指南](./packages/framework/behavior-tree/README.md)
- [编辑器启动指南](./packages/editor/editor-app/README_CN.md) ([English](./packages/editor/editor-app/README.md))
- [API 参考](https://esengine.cn/api/README)
## 社区

View File

@@ -71,6 +71,55 @@ class ConfiguredScene extends Scene {
}
```
## Runtime Environment
For networked games, you can configure the runtime environment to distinguish between server and client logic.
### Global Configuration (Recommended)
Set the runtime environment once at the Core level - all Scenes will inherit this setting:
```typescript
import { Core } from '@esengine/ecs-framework';
// Method 1: Set in Core.create()
Core.create({ runtimeEnvironment: 'server' });
// Method 2: Set static property directly
Core.runtimeEnvironment = 'server';
```
### Per-Scene Override
Individual scenes can override the global setting:
```typescript
const clientScene = new Scene({ runtimeEnvironment: 'client' });
```
### Environment Types
| Environment | Use Case |
|-------------|----------|
| `'standalone'` | Single-player games (default) |
| `'server'` | Game server, authoritative logic |
| `'client'` | Game client, rendering/input |
### Checking Environment in Systems
```typescript
class CollectibleSpawnSystem extends EntitySystem {
private checkCollections(): void {
// Skip on client - only server handles authoritative logic
if (!this.scene.isServer) return;
// Server-authoritative spawn logic...
}
}
```
See [System Runtime Decorators](/en/guide/system/index#runtime-environment-decorators) for decorator-based approach.
### Running a Scene
```typescript

View File

@@ -160,6 +160,53 @@ scene.addSystem(new SystemA()); // addOrder = 0, executes first
scene.addSystem(new SystemB()); // addOrder = 1, executes second
```
## Runtime Environment Decorators
For networked games, you can use decorators to control which environment a system method runs in.
### Available Decorators
| Decorator | Effect |
|-----------|--------|
| `@ServerOnly()` | Method only executes on server |
| `@ClientOnly()` | Method only executes on client |
| `@NotServer()` | Method skipped on server |
| `@NotClient()` | Method skipped on client |
### Usage Example
```typescript
import { EntitySystem, ServerOnly, ClientOnly } from '@esengine/ecs-framework';
class GameSystem extends EntitySystem {
@ServerOnly()
private spawnEnemies(): void {
// Only runs on server - authoritative spawn logic
}
@ClientOnly()
private playEffects(): void {
// Only runs on client - visual effects
}
}
```
### Simple Conditional Check
For simple cases, a direct check is often clearer than decorators:
```typescript
class CollectibleSystem extends EntitySystem {
private checkCollections(): void {
if (!this.scene.isServer) return; // Skip on client
// Server-authoritative logic...
}
}
```
See [Scene Runtime Environment](/en/guide/scene/index#runtime-environment) for configuration details.
## Next Steps
- [System Types](/en/guide/system/types) - Learn about different system base classes

View File

@@ -92,6 +92,355 @@ const token = jwtProvider.sign({
const payload = jwtProvider.decode(token)
```
### Custom Provider
You can create custom authentication providers by implementing the `IAuthProvider` interface to integrate with any authentication system (OAuth, LDAP, custom database auth, etc.).
#### IAuthProvider Interface
```typescript
interface IAuthProvider<TUser = unknown, TCredentials = unknown> {
/** Provider name */
readonly name: string;
/** Verify credentials */
verify(credentials: TCredentials): Promise<AuthResult<TUser>>;
/** Refresh token (optional) */
refresh?(token: string): Promise<AuthResult<TUser>>;
/** Revoke token (optional) */
revoke?(token: string): Promise<boolean>;
}
interface AuthResult<TUser> {
success: boolean;
user?: TUser;
error?: string;
errorCode?: AuthErrorCode;
token?: string;
expiresAt?: number;
}
type AuthErrorCode =
| 'INVALID_CREDENTIALS'
| 'EXPIRED_TOKEN'
| 'INVALID_TOKEN'
| 'USER_NOT_FOUND'
| 'ACCOUNT_DISABLED'
| 'RATE_LIMITED'
| 'INSUFFICIENT_PERMISSIONS';
```
#### Custom Provider Examples
**Example 1: Database Password Authentication**
```typescript
import type { IAuthProvider, AuthResult } from '@esengine/server/auth'
interface User {
id: string
username: string
roles: string[]
}
interface PasswordCredentials {
username: string
password: string
}
class DatabaseAuthProvider implements IAuthProvider<User, PasswordCredentials> {
readonly name = 'database'
async verify(credentials: PasswordCredentials): Promise<AuthResult<User>> {
const { username, password } = credentials
// Query user from database
const user = await db.users.findByUsername(username)
if (!user) {
return {
success: false,
error: 'User not found',
errorCode: 'USER_NOT_FOUND'
}
}
// Verify password (using bcrypt or similar)
const isValid = await bcrypt.compare(password, user.passwordHash)
if (!isValid) {
return {
success: false,
error: 'Invalid password',
errorCode: 'INVALID_CREDENTIALS'
}
}
// Check account status
if (user.disabled) {
return {
success: false,
error: 'Account is disabled',
errorCode: 'ACCOUNT_DISABLED'
}
}
return {
success: true,
user: {
id: user.id,
username: user.username,
roles: user.roles
}
}
}
}
```
**Example 2: OAuth/Third-party Authentication**
```typescript
import type { IAuthProvider, AuthResult } from '@esengine/server/auth'
interface OAuthUser {
id: string
email: string
name: string
provider: string
roles: string[]
}
interface OAuthCredentials {
provider: 'google' | 'github' | 'discord'
accessToken: string
}
class OAuthProvider implements IAuthProvider<OAuthUser, OAuthCredentials> {
readonly name = 'oauth'
async verify(credentials: OAuthCredentials): Promise<AuthResult<OAuthUser>> {
const { provider, accessToken } = credentials
try {
// Verify token with provider
const profile = await this.fetchUserProfile(provider, accessToken)
// Find or create local user
let user = await db.users.findByOAuth(provider, profile.id)
if (!user) {
user = await db.users.create({
oauthProvider: provider,
oauthId: profile.id,
email: profile.email,
name: profile.name,
roles: ['player']
})
}
return {
success: true,
user: {
id: user.id,
email: user.email,
name: user.name,
provider,
roles: user.roles
}
}
} catch (error) {
return {
success: false,
error: 'OAuth verification failed',
errorCode: 'INVALID_TOKEN'
}
}
}
private async fetchUserProfile(provider: string, token: string) {
switch (provider) {
case 'google':
return fetch('https://www.googleapis.com/oauth2/v2/userinfo', {
headers: { Authorization: `Bearer ${token}` }
}).then(r => r.json())
case 'github':
return fetch('https://api.github.com/user', {
headers: { Authorization: `Bearer ${token}` }
}).then(r => r.json())
// Other providers...
default:
throw new Error(`Unsupported provider: ${provider}`)
}
}
}
```
**Example 3: API Key Authentication**
```typescript
import type { IAuthProvider, AuthResult } from '@esengine/server/auth'
interface ApiUser {
id: string
name: string
roles: string[]
rateLimit: number
}
class ApiKeyAuthProvider implements IAuthProvider<ApiUser, string> {
readonly name = 'api-key'
private revokedKeys = new Set<string>()
async verify(apiKey: string): Promise<AuthResult<ApiUser>> {
if (!apiKey || !apiKey.startsWith('sk_')) {
return {
success: false,
error: 'Invalid API Key format',
errorCode: 'INVALID_TOKEN'
}
}
if (this.revokedKeys.has(apiKey)) {
return {
success: false,
error: 'API Key has been revoked',
errorCode: 'INVALID_TOKEN'
}
}
// Query API Key from database
const keyData = await db.apiKeys.findByKey(apiKey)
if (!keyData) {
return {
success: false,
error: 'API Key not found',
errorCode: 'INVALID_CREDENTIALS'
}
}
// Check expiration
if (keyData.expiresAt && keyData.expiresAt < Date.now()) {
return {
success: false,
error: 'API Key has expired',
errorCode: 'EXPIRED_TOKEN'
}
}
return {
success: true,
user: {
id: keyData.userId,
name: keyData.name,
roles: keyData.roles,
rateLimit: keyData.rateLimit
},
expiresAt: keyData.expiresAt
}
}
async revoke(apiKey: string): Promise<boolean> {
this.revokedKeys.add(apiKey)
await db.apiKeys.revoke(apiKey)
return true
}
}
```
#### Using Custom Providers
```typescript
import { createServer } from '@esengine/server'
import { withAuth } from '@esengine/server/auth'
// Create custom provider
const dbAuthProvider = new DatabaseAuthProvider()
// Or use OAuth provider
const oauthProvider = new OAuthProvider()
// Use custom provider
const server = withAuth(await createServer({ port: 3000 }), {
provider: dbAuthProvider, // or oauthProvider
// Extract credentials from WebSocket connection request
extractCredentials: (req) => {
const url = new URL(req.url, 'http://localhost')
// For database auth: get from query params
const username = url.searchParams.get('username')
const password = url.searchParams.get('password')
if (username && password) {
return { username, password }
}
// For OAuth: get from token param
const provider = url.searchParams.get('provider')
const accessToken = url.searchParams.get('access_token')
if (provider && accessToken) {
return { provider, accessToken }
}
// For API Key: get from header
const apiKey = req.headers['x-api-key']
if (apiKey) {
return apiKey as string
}
return null
},
onAuthFailure: (conn, error) => {
console.log(`Auth failed: ${error.errorCode} - ${error.error}`)
}
})
await server.start()
```
#### Combining Multiple Providers
You can create a composite provider to support multiple authentication methods:
```typescript
import type { IAuthProvider, AuthResult } from '@esengine/server/auth'
interface MultiAuthCredentials {
type: 'jwt' | 'oauth' | 'apikey' | 'password'
data: unknown
}
class MultiAuthProvider implements IAuthProvider<User, MultiAuthCredentials> {
readonly name = 'multi'
constructor(
private jwtProvider: JwtAuthProvider<User>,
private oauthProvider: OAuthProvider,
private apiKeyProvider: ApiKeyAuthProvider,
private dbProvider: DatabaseAuthProvider
) {}
async verify(credentials: MultiAuthCredentials): Promise<AuthResult<User>> {
switch (credentials.type) {
case 'jwt':
return this.jwtProvider.verify(credentials.data as string)
case 'oauth':
return this.oauthProvider.verify(credentials.data as OAuthCredentials)
case 'apikey':
return this.apiKeyProvider.verify(credentials.data as string)
case 'password':
return this.dbProvider.verify(credentials.data as PasswordCredentials)
default:
return {
success: false,
error: 'Unsupported authentication type',
errorCode: 'INVALID_CREDENTIALS'
}
}
}
}
```
### Session Provider
Use server-side sessions for stateful authentication:

View File

@@ -79,10 +79,140 @@ await server.start()
| `tickRate` | `number` | `20` | Global tick rate (Hz) |
| `apiDir` | `string` | `'src/api'` | API handlers directory |
| `msgDir` | `string` | `'src/msg'` | Message handlers directory |
| `httpDir` | `string` | `'src/http'` | HTTP routes directory |
| `httpPrefix` | `string` | `'/api'` | HTTP routes prefix |
| `cors` | `boolean \| CorsOptions` | - | CORS configuration |
| `onStart` | `(port) => void` | - | Start callback |
| `onConnect` | `(conn) => void` | - | Connection callback |
| `onDisconnect` | `(conn) => void` | - | Disconnect callback |
## HTTP Routing
Supports HTTP API sharing the same port with WebSocket, ideal for login, registration, and similar scenarios.
### File-based Routing
Create route files in the `httpDir` directory, automatically mapped to HTTP endpoints:
```
src/http/
├── login.ts → POST /api/login
├── register.ts → POST /api/register
├── health.ts → GET /api/health (set method: 'GET')
└── users/
└── [id].ts → POST /api/users/:id (dynamic route)
```
### Define Routes
Use `defineHttp` to define type-safe route handlers:
```typescript
// src/http/login.ts
import { defineHttp } from '@esengine/server'
interface LoginBody {
username: string
password: string
}
export default defineHttp<LoginBody>({
method: 'POST', // Default POST, options: GET/PUT/DELETE/PATCH
handler(req, res) {
const { username, password } = req.body
// Validate credentials...
if (!isValid(username, password)) {
res.error(401, 'Invalid credentials')
return
}
// Generate token...
res.json({ token: '...', userId: '...' })
}
})
```
### Request Object (HttpRequest)
```typescript
interface HttpRequest {
raw: IncomingMessage // Node.js raw request
method: string // Request method
path: string // Request path
query: Record<string, string> // Query parameters
headers: Record<string, string | string[] | undefined>
body: unknown // Parsed JSON body
ip: string // Client IP
}
```
### Response Object (HttpResponse)
```typescript
interface HttpResponse {
raw: ServerResponse // Node.js raw response
status(code: number): HttpResponse // Set status code (chainable)
header(name: string, value: string): HttpResponse // Set header (chainable)
json(data: unknown): void // Send JSON
text(data: string): void // Send text
error(code: number, message: string): void // Send error
}
```
### Usage Example
```typescript
// Complete login server example
import { createServer, defineHttp } from '@esengine/server'
import { createJwtAuthProvider, withAuth } from '@esengine/server/auth'
const jwtProvider = createJwtAuthProvider({
secret: process.env.JWT_SECRET!,
expiresIn: 3600 * 24,
})
const server = await createServer({
port: 8080,
httpDir: 'src/http',
httpPrefix: '/api',
cors: true,
})
// Wrap with auth (WebSocket connections validate token)
const authServer = withAuth(server, {
provider: jwtProvider,
extractCredentials: (req) => {
const url = new URL(req.url, 'http://localhost')
return url.searchParams.get('token')
},
})
await authServer.start()
// HTTP: http://localhost:8080/api/*
// WebSocket: ws://localhost:8080?token=xxx
```
### Inline Routes
Routes can also be defined directly in configuration (merged with file routes, inline takes priority):
```typescript
const server = await createServer({
port: 8080,
http: {
'/health': {
GET: (req, res) => res.json({ status: 'ok' }),
},
'/webhook': async (req, res) => {
// Accepts all methods
await handleWebhook(req.body)
res.json({ received: true })
},
},
})
```
## Room System
Room is the base class for game rooms, managing players and game state.
@@ -311,6 +441,93 @@ client.send('RoomMessage', {
})
```
## ECSRoom
`ECSRoom` is a room base class with ECS World support, suitable for games that need ECS architecture.
### Server Startup
```typescript
import { Core } from '@esengine/ecs-framework';
import { createServer } from '@esengine/server';
import { GameRoom } from './rooms/GameRoom.js';
// Initialize Core
Core.create();
// Global game loop
setInterval(() => Core.update(1/60), 16);
// Create server
const server = await createServer({ port: 3000 });
server.define('game', GameRoom);
await server.start();
```
### Define ECSRoom
```typescript
import { ECSRoom, Player } from '@esengine/server/ecs';
import { Component, ECSComponent, sync } from '@esengine/ecs-framework';
// Define sync component
@ECSComponent('Player')
class PlayerComponent extends Component {
@sync("string") name: string = "";
@sync("uint16") score: number = 0;
@sync("float32") x: number = 0;
@sync("float32") y: number = 0;
}
// Define room
class GameRoom extends ECSRoom {
onCreate() {
this.addSystem(new MovementSystem());
}
onJoin(player: Player) {
const entity = this.createPlayerEntity(player.id);
const comp = entity.addComponent(new PlayerComponent());
comp.name = player.id;
}
}
```
### ECSRoom API
```typescript
abstract class ECSRoom<TState, TPlayerData> extends Room<TState, TPlayerData> {
protected readonly world: World; // ECS World
protected readonly scene: Scene; // Main scene
// Scene management
protected addSystem(system: EntitySystem): void;
protected createEntity(name?: string): Entity;
protected createPlayerEntity(playerId: string, name?: string): Entity;
protected getPlayerEntity(playerId: string): Entity | undefined;
protected destroyPlayerEntity(playerId: string): void;
// State sync
protected sendFullState(player: Player): void;
protected broadcastSpawn(entity: Entity, prefabType?: string): void;
protected broadcastDelta(): void;
}
```
### @sync Decorator
Mark component fields that need network synchronization:
| Type | Description | Bytes |
|------|-------------|-------|
| `"boolean"` | Boolean | 1 |
| `"int8"` / `"uint8"` | 8-bit integer | 1 |
| `"int16"` / `"uint16"` | 16-bit integer | 2 |
| `"int32"` / `"uint32"` | 32-bit integer | 4 |
| `"float32"` | 32-bit float | 4 |
| `"float64"` | 64-bit float | 8 |
| `"string"` | String | Variable |
## Best Practices
1. **Set Appropriate Tick Rate**

View File

@@ -1,8 +1,176 @@
---
title: "State Sync"
description: "Interpolation, prediction and snapshot buffers"
description: "Component sync, interpolation, prediction and snapshot buffers"
---
## @NetworkEntity Decorator
The `@NetworkEntity` decorator marks components for automatic spawn/despawn broadcasting. When an entity containing this component is created or destroyed, ECSRoom automatically broadcasts the corresponding message to all clients.
### Basic Usage
```typescript
import { Component, ECSComponent, sync, NetworkEntity } from '@esengine/ecs-framework';
@ECSComponent('Enemy')
@NetworkEntity('Enemy')
class EnemyComponent extends Component {
@sync('float32') x: number = 0;
@sync('float32') y: number = 0;
@sync('uint16') health: number = 100;
}
```
When adding this component to an entity, ECSRoom automatically broadcasts the spawn message:
```typescript
// Server-side
const entity = scene.createEntity('Enemy');
entity.addComponent(new EnemyComponent()); // Auto-broadcasts spawn
// Destroying auto-broadcasts despawn
entity.destroy(); // Auto-broadcasts despawn
```
### Configuration Options
```typescript
@NetworkEntity('Bullet', {
autoSpawn: true, // Auto-broadcast spawn (default true)
autoDespawn: false // Disable auto-broadcast despawn
})
class BulletComponent extends Component { }
```
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `autoSpawn` | `boolean` | `true` | Auto-broadcast spawn when component is added |
| `autoDespawn` | `boolean` | `true` | Auto-broadcast despawn when entity is destroyed |
### Initialization Order
When using `@NetworkEntity`, initialize data **before** adding the component:
```typescript
// ✅ Correct: Initialize first, then add
const comp = new PlayerComponent();
comp.playerId = player.id;
comp.x = 100;
comp.y = 200;
entity.addComponent(comp); // Data is correct at spawn
// ❌ Wrong: Add first, then initialize
const comp = entity.addComponent(new PlayerComponent());
comp.playerId = player.id; // Data has default values at spawn
```
### Simplified GameRoom
With `@NetworkEntity`, GameRoom becomes much cleaner:
```typescript
// No manual callbacks needed
class GameRoom extends ECSRoom {
private setupSystems(): void {
// Enemy spawn system (auto-broadcasts spawn)
this.addSystem(new EnemySpawnSystem());
// Enemy AI system
const enemyAI = new EnemyAISystem();
enemyAI.onDeath((enemy) => {
enemy.destroy(); // Auto-broadcasts despawn
});
this.addSystem(enemyAI);
}
}
```
### ECSRoom Configuration
You can disable the auto network entity feature in ECSRoom:
```typescript
class GameRoom extends ECSRoom {
constructor() {
super({
enableAutoNetworkEntity: false // Disable auto-broadcasting
});
}
}
```
## Component Sync System
ECS component state synchronization based on `@sync` decorator.
### Define Sync Component
```typescript
import { Component, ECSComponent, sync } from '@esengine/ecs-framework';
@ECSComponent('Player')
class PlayerComponent extends Component {
@sync("string") name: string = "";
@sync("uint16") score: number = 0;
@sync("float32") x: number = 0;
@sync("float32") y: number = 0;
// Fields without @sync won't be synced
localData: any;
}
```
### Server-side Encoding
```typescript
import { ComponentSyncSystem } from '@esengine/network';
const syncSystem = new ComponentSyncSystem({}, true);
scene.addSystem(syncSystem);
// Encode all entities (initial connection)
const fullData = syncSystem.encodeAllEntities(true);
sendToClient(fullData);
// Encode delta (only send changes)
const deltaData = syncSystem.encodeDelta();
if (deltaData) {
broadcast(deltaData);
}
```
### Client-side Decoding
```typescript
const syncSystem = new ComponentSyncSystem();
scene.addSystem(syncSystem);
// Register component types
syncSystem.registerComponent(PlayerComponent);
// Listen for sync events
syncSystem.addSyncListener((event) => {
if (event.type === 'entitySpawned') {
console.log('New entity:', event.entityId);
}
});
// Apply state
syncSystem.applySnapshot(data);
```
### Sync Types
| Type | Description | Bytes |
|------|-------------|-------|
| `"boolean"` | Boolean | 1 |
| `"int8"` / `"uint8"` | 8-bit integer | 1 |
| `"int16"` / `"uint16"` | 16-bit integer | 2 |
| `"int32"` / `"uint32"` | 32-bit integer | 4 |
| `"float32"` | 32-bit float | 4 |
| `"float64"` | 64-bit float | 8 |
| `"string"` | String | Variable |
## Snapshot Buffer
Stores server state snapshots for interpolation:

View File

@@ -71,6 +71,55 @@ class ConfiguredScene extends Scene {
}
```
## 运行时环境
对于网络游戏,你可以配置运行时环境来区分服务端和客户端逻辑。
### 全局配置(推荐)
在 Core 层级设置一次运行时环境,所有场景都会继承此设置:
```typescript
import { Core } from '@esengine/ecs-framework';
// 方式1在 Core.create() 中设置
Core.create({ runtimeEnvironment: 'server' });
// 方式2直接设置静态属性
Core.runtimeEnvironment = 'server';
```
### 单个场景覆盖
个别场景可以覆盖全局设置:
```typescript
const clientScene = new Scene({ runtimeEnvironment: 'client' });
```
### 环境类型
| 环境 | 使用场景 |
|------|----------|
| `'standalone'` | 单机游戏(默认) |
| `'server'` | 游戏服务器,权威逻辑 |
| `'client'` | 游戏客户端,渲染/输入 |
### 在系统中检查环境
```typescript
class CollectibleSpawnSystem extends EntitySystem {
private checkCollections(): void {
// 客户端跳过 - 只有服务端处理权威逻辑
if (!this.scene.isServer) return;
// 服务端权威生成逻辑...
}
}
```
参见 [系统运行时装饰器](/guide/system/index#运行时环境装饰器) 了解基于装饰器的方式。
### 运行场景
```typescript

View File

@@ -160,6 +160,53 @@ scene.addSystem(new SystemA()); // addOrder = 0先执行
scene.addSystem(new SystemB()); // addOrder = 1后执行
```
## 运行时环境装饰器
对于网络游戏,你可以使用装饰器来控制系统方法在哪个环境下执行。
### 可用装饰器
| 装饰器 | 效果 |
|--------|------|
| `@ServerOnly()` | 方法仅在服务端执行 |
| `@ClientOnly()` | 方法仅在客户端执行 |
| `@NotServer()` | 方法在服务端跳过 |
| `@NotClient()` | 方法在客户端跳过 |
### 使用示例
```typescript
import { EntitySystem, ServerOnly, ClientOnly } from '@esengine/ecs-framework';
class GameSystem extends EntitySystem {
@ServerOnly()
private spawnEnemies(): void {
// 仅在服务端运行 - 权威生成逻辑
}
@ClientOnly()
private playEffects(): void {
// 仅在客户端运行 - 视觉效果
}
}
```
### 简单条件检查
对于简单场景,直接检查通常比装饰器更清晰:
```typescript
class CollectibleSystem extends EntitySystem {
private checkCollections(): void {
if (!this.scene.isServer) return; // 客户端跳过
// 服务端权威逻辑...
}
}
```
参见 [场景运行时环境](/guide/scene/index#运行时环境) 了解配置详情。
## 下一步
- [系统类型](/guide/system/types) - 了解不同类型的系统基类

View File

@@ -92,6 +92,355 @@ const token = jwtProvider.sign({
const payload = jwtProvider.decode(token)
```
### 自定义提供者
你可以通过实现 `IAuthProvider` 接口来创建自定义认证提供者,以集成任何认证系统(如 OAuth、LDAP、自定义数据库认证等
#### IAuthProvider 接口
```typescript
interface IAuthProvider<TUser = unknown, TCredentials = unknown> {
/** 提供者名称 */
readonly name: string;
/** 验证凭证 */
verify(credentials: TCredentials): Promise<AuthResult<TUser>>;
/** 刷新令牌(可选) */
refresh?(token: string): Promise<AuthResult<TUser>>;
/** 撤销令牌(可选) */
revoke?(token: string): Promise<boolean>;
}
interface AuthResult<TUser> {
success: boolean;
user?: TUser;
error?: string;
errorCode?: AuthErrorCode;
token?: string;
expiresAt?: number;
}
type AuthErrorCode =
| 'INVALID_CREDENTIALS'
| 'EXPIRED_TOKEN'
| 'INVALID_TOKEN'
| 'USER_NOT_FOUND'
| 'ACCOUNT_DISABLED'
| 'RATE_LIMITED'
| 'INSUFFICIENT_PERMISSIONS';
```
#### 自定义提供者示例
**示例 1数据库密码认证**
```typescript
import type { IAuthProvider, AuthResult } from '@esengine/server/auth'
interface User {
id: string
username: string
roles: string[]
}
interface PasswordCredentials {
username: string
password: string
}
class DatabaseAuthProvider implements IAuthProvider<User, PasswordCredentials> {
readonly name = 'database'
async verify(credentials: PasswordCredentials): Promise<AuthResult<User>> {
const { username, password } = credentials
// 从数据库查询用户
const user = await db.users.findByUsername(username)
if (!user) {
return {
success: false,
error: '用户不存在',
errorCode: 'USER_NOT_FOUND'
}
}
// 验证密码(使用 bcrypt 等库)
const isValid = await bcrypt.compare(password, user.passwordHash)
if (!isValid) {
return {
success: false,
error: '密码错误',
errorCode: 'INVALID_CREDENTIALS'
}
}
// 检查账号状态
if (user.disabled) {
return {
success: false,
error: '账号已禁用',
errorCode: 'ACCOUNT_DISABLED'
}
}
return {
success: true,
user: {
id: user.id,
username: user.username,
roles: user.roles
}
}
}
}
```
**示例 2OAuth/第三方认证**
```typescript
import type { IAuthProvider, AuthResult } from '@esengine/server/auth'
interface OAuthUser {
id: string
email: string
name: string
provider: string
roles: string[]
}
interface OAuthCredentials {
provider: 'google' | 'github' | 'discord'
accessToken: string
}
class OAuthProvider implements IAuthProvider<OAuthUser, OAuthCredentials> {
readonly name = 'oauth'
async verify(credentials: OAuthCredentials): Promise<AuthResult<OAuthUser>> {
const { provider, accessToken } = credentials
try {
// 根据提供商验证 token
const profile = await this.fetchUserProfile(provider, accessToken)
// 查找或创建本地用户
let user = await db.users.findByOAuth(provider, profile.id)
if (!user) {
user = await db.users.create({
oauthProvider: provider,
oauthId: profile.id,
email: profile.email,
name: profile.name,
roles: ['player']
})
}
return {
success: true,
user: {
id: user.id,
email: user.email,
name: user.name,
provider,
roles: user.roles
}
}
} catch (error) {
return {
success: false,
error: 'OAuth 验证失败',
errorCode: 'INVALID_TOKEN'
}
}
}
private async fetchUserProfile(provider: string, token: string) {
switch (provider) {
case 'google':
return fetch('https://www.googleapis.com/oauth2/v2/userinfo', {
headers: { Authorization: `Bearer ${token}` }
}).then(r => r.json())
case 'github':
return fetch('https://api.github.com/user', {
headers: { Authorization: `Bearer ${token}` }
}).then(r => r.json())
// 其他提供商...
default:
throw new Error(`不支持的提供商: ${provider}`)
}
}
}
```
**示例 3API Key 认证**
```typescript
import type { IAuthProvider, AuthResult } from '@esengine/server/auth'
interface ApiUser {
id: string
name: string
roles: string[]
rateLimit: number
}
class ApiKeyAuthProvider implements IAuthProvider<ApiUser, string> {
readonly name = 'api-key'
private revokedKeys = new Set<string>()
async verify(apiKey: string): Promise<AuthResult<ApiUser>> {
if (!apiKey || !apiKey.startsWith('sk_')) {
return {
success: false,
error: 'API Key 格式无效',
errorCode: 'INVALID_TOKEN'
}
}
if (this.revokedKeys.has(apiKey)) {
return {
success: false,
error: 'API Key 已被撤销',
errorCode: 'INVALID_TOKEN'
}
}
// 从数据库查询 API Key
const keyData = await db.apiKeys.findByKey(apiKey)
if (!keyData) {
return {
success: false,
error: 'API Key 不存在',
errorCode: 'INVALID_CREDENTIALS'
}
}
// 检查过期
if (keyData.expiresAt && keyData.expiresAt < Date.now()) {
return {
success: false,
error: 'API Key 已过期',
errorCode: 'EXPIRED_TOKEN'
}
}
return {
success: true,
user: {
id: keyData.userId,
name: keyData.name,
roles: keyData.roles,
rateLimit: keyData.rateLimit
},
expiresAt: keyData.expiresAt
}
}
async revoke(apiKey: string): Promise<boolean> {
this.revokedKeys.add(apiKey)
await db.apiKeys.revoke(apiKey)
return true
}
}
```
#### 使用自定义提供者
```typescript
import { createServer } from '@esengine/server'
import { withAuth } from '@esengine/server/auth'
// 创建自定义提供者
const dbAuthProvider = new DatabaseAuthProvider()
// 或使用 OAuth 提供者
const oauthProvider = new OAuthProvider()
// 使用自定义提供者
const server = withAuth(await createServer({ port: 3000 }), {
provider: dbAuthProvider, // 或 oauthProvider
// 从 WebSocket 连接请求中提取凭证
extractCredentials: (req) => {
const url = new URL(req.url, 'http://localhost')
// 对于数据库认证:从查询参数获取
const username = url.searchParams.get('username')
const password = url.searchParams.get('password')
if (username && password) {
return { username, password }
}
// 对于 OAuth从 token 参数获取
const provider = url.searchParams.get('provider')
const accessToken = url.searchParams.get('access_token')
if (provider && accessToken) {
return { provider, accessToken }
}
// 对于 API Key从请求头获取
const apiKey = req.headers['x-api-key']
if (apiKey) {
return apiKey as string
}
return null
},
onAuthFailure: (conn, error) => {
console.log(`认证失败: ${error.errorCode} - ${error.error}`)
}
})
await server.start()
```
#### 组合多个提供者
你可以创建一个复合提供者来支持多种认证方式:
```typescript
import type { IAuthProvider, AuthResult } from '@esengine/server/auth'
interface MultiAuthCredentials {
type: 'jwt' | 'oauth' | 'apikey' | 'password'
data: unknown
}
class MultiAuthProvider implements IAuthProvider<User, MultiAuthCredentials> {
readonly name = 'multi'
constructor(
private jwtProvider: JwtAuthProvider<User>,
private oauthProvider: OAuthProvider,
private apiKeyProvider: ApiKeyAuthProvider,
private dbProvider: DatabaseAuthProvider
) {}
async verify(credentials: MultiAuthCredentials): Promise<AuthResult<User>> {
switch (credentials.type) {
case 'jwt':
return this.jwtProvider.verify(credentials.data as string)
case 'oauth':
return this.oauthProvider.verify(credentials.data as OAuthCredentials)
case 'apikey':
return this.apiKeyProvider.verify(credentials.data as string)
case 'password':
return this.dbProvider.verify(credentials.data as PasswordCredentials)
default:
return {
success: false,
error: '不支持的认证类型',
errorCode: 'INVALID_CREDENTIALS'
}
}
}
}
```
### Session 提供者
使用服务端会话实现有状态认证:

View File

@@ -79,10 +79,140 @@ await server.start()
| `tickRate` | `number` | `20` | 全局 Tick 频率 (Hz) |
| `apiDir` | `string` | `'src/api'` | API 处理器目录 |
| `msgDir` | `string` | `'src/msg'` | 消息处理器目录 |
| `httpDir` | `string` | `'src/http'` | HTTP 路由目录 |
| `httpPrefix` | `string` | `'/api'` | HTTP 路由前缀 |
| `cors` | `boolean \| CorsOptions` | - | CORS 配置 |
| `onStart` | `(port) => void` | - | 启动回调 |
| `onConnect` | `(conn) => void` | - | 连接回调 |
| `onDisconnect` | `(conn) => void` | - | 断开回调 |
## HTTP 路由
支持 HTTP API 与 WebSocket 共用端口,适用于登录、注册等场景。
### 文件路由
`httpDir` 目录下创建路由文件,自动映射为 HTTP 端点:
```
src/http/
├── login.ts → POST /api/login
├── register.ts → POST /api/register
├── health.ts → GET /api/health (需设置 method: 'GET')
└── users/
└── [id].ts → POST /api/users/:id (动态路由)
```
### 定义路由
使用 `defineHttp` 定义类型安全的路由处理器:
```typescript
// src/http/login.ts
import { defineHttp } from '@esengine/server'
interface LoginBody {
username: string
password: string
}
export default defineHttp<LoginBody>({
method: 'POST', // 默认 POST可选 GET/PUT/DELETE/PATCH
handler(req, res) {
const { username, password } = req.body
// 验证凭证...
if (!isValid(username, password)) {
res.error(401, 'Invalid credentials')
return
}
// 生成 token...
res.json({ token: '...', userId: '...' })
}
})
```
### 请求对象 (HttpRequest)
```typescript
interface HttpRequest {
raw: IncomingMessage // Node.js 原始请求
method: string // 请求方法
path: string // 请求路径
query: Record<string, string> // 查询参数
headers: Record<string, string | string[] | undefined>
body: unknown // 解析后的 JSON 请求体
ip: string // 客户端 IP
}
```
### 响应对象 (HttpResponse)
```typescript
interface HttpResponse {
raw: ServerResponse // Node.js 原始响应
status(code: number): HttpResponse // 设置状态码(链式)
header(name: string, value: string): HttpResponse // 设置头(链式)
json(data: unknown): void // 发送 JSON
text(data: string): void // 发送文本
error(code: number, message: string): void // 发送错误
}
```
### 使用示例
```typescript
// 完整的登录服务器示例
import { createServer, defineHttp } from '@esengine/server'
import { createJwtAuthProvider, withAuth } from '@esengine/server/auth'
const jwtProvider = createJwtAuthProvider({
secret: process.env.JWT_SECRET!,
expiresIn: 3600 * 24,
})
const server = await createServer({
port: 8080,
httpDir: 'src/http',
httpPrefix: '/api',
cors: true,
})
// 包装认证WebSocket 连接验证 token
const authServer = withAuth(server, {
provider: jwtProvider,
extractCredentials: (req) => {
const url = new URL(req.url, 'http://localhost')
return url.searchParams.get('token')
},
})
await authServer.start()
// HTTP: http://localhost:8080/api/*
// WebSocket: ws://localhost:8080?token=xxx
```
### 内联路由
也可以直接在配置中定义路由(与文件路由合并,内联优先):
```typescript
const server = await createServer({
port: 8080,
http: {
'/health': {
GET: (req, res) => res.json({ status: 'ok' }),
},
'/webhook': async (req, res) => {
// 接受所有方法
await handleWebhook(req.body)
res.json({ received: true })
},
},
})
```
## Room 系统
Room 是游戏房间的基类,管理玩家和游戏状态。
@@ -311,6 +441,93 @@ client.send('RoomMessage', {
})
```
## ECSRoom
`ECSRoom` 是带有 ECS World 支持的房间基类,适用于需要 ECS 架构的游戏。
### 服务端启动
```typescript
import { Core } from '@esengine/ecs-framework';
import { createServer } from '@esengine/server';
import { GameRoom } from './rooms/GameRoom.js';
// 初始化 Core
Core.create();
// 全局游戏循环
setInterval(() => Core.update(1/60), 16);
// 创建服务器
const server = await createServer({ port: 3000 });
server.define('game', GameRoom);
await server.start();
```
### 定义 ECSRoom
```typescript
import { ECSRoom, Player } from '@esengine/server/ecs';
import { Component, ECSComponent, sync } from '@esengine/ecs-framework';
// 定义同步组件
@ECSComponent('Player')
class PlayerComponent extends Component {
@sync("string") name: string = "";
@sync("uint16") score: number = 0;
@sync("float32") x: number = 0;
@sync("float32") y: number = 0;
}
// 定义房间
class GameRoom extends ECSRoom {
onCreate() {
this.addSystem(new MovementSystem());
}
onJoin(player: Player) {
const entity = this.createPlayerEntity(player.id);
const comp = entity.addComponent(new PlayerComponent());
comp.name = player.id;
}
}
```
### ECSRoom API
```typescript
abstract class ECSRoom<TState, TPlayerData> extends Room<TState, TPlayerData> {
protected readonly world: World; // ECS World
protected readonly scene: Scene; // 主场景
// 场景管理
protected addSystem(system: EntitySystem): void;
protected createEntity(name?: string): Entity;
protected createPlayerEntity(playerId: string, name?: string): Entity;
protected getPlayerEntity(playerId: string): Entity | undefined;
protected destroyPlayerEntity(playerId: string): void;
// 状态同步
protected sendFullState(player: Player): void;
protected broadcastSpawn(entity: Entity, prefabType?: string): void;
protected broadcastDelta(): void;
}
```
### @sync 装饰器
标记需要网络同步的组件字段:
| 类型 | 描述 | 字节数 |
|------|------|--------|
| `"boolean"` | 布尔值 | 1 |
| `"int8"` / `"uint8"` | 8位整数 | 1 |
| `"int16"` / `"uint16"` | 16位整数 | 2 |
| `"int32"` / `"uint32"` | 32位整数 | 4 |
| `"float32"` | 32位浮点 | 4 |
| `"float64"` | 64位浮点 | 8 |
| `"string"` | 字符串 | 变长 |
## 最佳实践
1. **合理设置 Tick 频率**

View File

@@ -1,8 +1,176 @@
---
title: "状态同步"
description: "插值、预测和快照缓冲区"
description: "组件同步、插值、预测和快照缓冲区"
---
## @NetworkEntity 装饰器
`@NetworkEntity` 装饰器用于标记需要自动广播生成/销毁的组件。当包含此组件的实体被创建或销毁时ECSRoom 会自动广播相应的消息给所有客户端。
### 基本用法
```typescript
import { Component, ECSComponent, sync, NetworkEntity } from '@esengine/ecs-framework';
@ECSComponent('Enemy')
@NetworkEntity('Enemy')
class EnemyComponent extends Component {
@sync('float32') x: number = 0;
@sync('float32') y: number = 0;
@sync('uint16') health: number = 100;
}
```
当添加此组件到实体时ECSRoom 会自动广播 spawn 消息:
```typescript
// 服务端
const entity = scene.createEntity('Enemy');
entity.addComponent(new EnemyComponent()); // 自动广播 spawn
// 销毁时自动广播 despawn
entity.destroy(); // 自动广播 despawn
```
### 配置选项
```typescript
@NetworkEntity('Bullet', {
autoSpawn: true, // 自动广播生成(默认 true
autoDespawn: false // 禁用自动广播销毁
})
class BulletComponent extends Component { }
```
| 选项 | 类型 | 默认值 | 描述 |
|------|------|--------|------|
| `autoSpawn` | `boolean` | `true` | 添加组件时自动广播 spawn |
| `autoDespawn` | `boolean` | `true` | 销毁实体时自动广播 despawn |
### 初始化顺序
使用 `@NetworkEntity` 时,应在添加组件**之前**初始化数据:
```typescript
// ✅ 正确:先初始化,再添加
const comp = new PlayerComponent();
comp.playerId = player.id;
comp.x = 100;
comp.y = 200;
entity.addComponent(comp); // spawn 时数据已正确
// ❌ 错误:先添加,再初始化
const comp = entity.addComponent(new PlayerComponent());
comp.playerId = player.id; // spawn 时数据是默认值
```
### 简化 GameRoom
使用 `@NetworkEntity`GameRoom 变得更加简洁:
```typescript
// 无需手动回调
class GameRoom extends ECSRoom {
private setupSystems(): void {
// 敌人生成系统(自动广播 spawn
this.addSystem(new EnemySpawnSystem());
// 敌人 AI 系统
const enemyAI = new EnemyAISystem();
enemyAI.onDeath((enemy) => {
enemy.destroy(); // 自动广播 despawn
});
this.addSystem(enemyAI);
}
}
```
### ECSRoom 配置
可以在 ECSRoom 中禁用自动网络实体功能:
```typescript
class GameRoom extends ECSRoom {
constructor() {
super({
enableAutoNetworkEntity: false // 禁用自动广播
});
}
}
```
## 组件同步系统
基于 `@sync` 装饰器的 ECS 组件状态同步。
### 定义同步组件
```typescript
import { Component, ECSComponent, sync } from '@esengine/ecs-framework';
@ECSComponent('Player')
class PlayerComponent extends Component {
@sync("string") name: string = "";
@sync("uint16") score: number = 0;
@sync("float32") x: number = 0;
@sync("float32") y: number = 0;
// 不带 @sync 的字段不会同步
localData: any;
}
```
### 服务端编码
```typescript
import { ComponentSyncSystem } from '@esengine/network';
const syncSystem = new ComponentSyncSystem({}, true);
scene.addSystem(syncSystem);
// 编码所有实体(首次连接)
const fullData = syncSystem.encodeAllEntities(true);
sendToClient(fullData);
// 编码增量(只发送变更)
const deltaData = syncSystem.encodeDelta();
if (deltaData) {
broadcast(deltaData);
}
```
### 客户端解码
```typescript
const syncSystem = new ComponentSyncSystem();
scene.addSystem(syncSystem);
// 注册组件类型
syncSystem.registerComponent(PlayerComponent);
// 监听同步事件
syncSystem.addSyncListener((event) => {
if (event.type === 'entitySpawned') {
console.log('New entity:', event.entityId);
}
});
// 应用状态
syncSystem.applySnapshot(data);
```
### 同步类型
| 类型 | 描述 | 字节数 |
|------|------|--------|
| `"boolean"` | 布尔值 | 1 |
| `"int8"` / `"uint8"` | 8位整数 | 1 |
| `"int16"` / `"uint16"` | 16位整数 | 2 |
| `"int32"` / `"uint32"` | 32位整数 | 4 |
| `"float32"` | 32位浮点 | 4 |
| `"float64"` | 64位浮点 | 8 |
| `"string"` | 字符串 | 变长 |
## 快照缓冲区
用于存储服务器状态快照并进行插值:

View File

@@ -74,6 +74,7 @@
"lint:fix": "turbo run lint:fix",
"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",
"build:rapier2d": "node scripts/build-rapier2d.mjs",
"copy-modules": "node scripts/copy-engine-modules.mjs"
},
"author": "yhh",

View File

@@ -0,0 +1,132 @@
# ESEngine Editor
A cross-platform desktop visual editor built with Tauri 2.x + React 18.
## Prerequisites
Before running the editor, ensure you have the following installed:
- **Node.js** >= 18.x
- **pnpm** >= 10.x
- **Rust** >= 1.70 (for Tauri and WASM builds)
- **wasm-pack** (for building Rapier2D physics engine)
- **Platform-specific dependencies**:
- **Windows**: Microsoft Visual Studio C++ Build Tools
- **macOS**: Xcode Command Line Tools (`xcode-select --install`)
- **Linux**: See [Tauri prerequisites](https://tauri.app/v1/guides/getting-started/prerequisites)
### Installing wasm-pack
```bash
# Using cargo
cargo install wasm-pack
# Or using the official installer script (Linux/macOS)
curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh
```
## Quick Start
### 1. Clone and Install
```bash
git clone https://github.com/esengine/esengine.git
cd esengine
pnpm install
```
### 2. Build Rapier2D WASM
The editor depends on Rapier2D physics engine WASM artifacts. First-time setup only requires one command:
```bash
pnpm build:rapier2d
```
This command automatically:
1. Prepares the Rust project
2. Builds WASM
3. Copies artifacts to `packages/physics/rapier2d/pkg`
4. Generates TypeScript source code
> **Note**: Requires Rust and wasm-pack to be installed.
### 3. Build Editor
From the project root:
```bash
pnpm build:editor
```
### 4. Run Editor
```bash
cd packages/editor/editor-app
pnpm tauri:dev
```
## Available Scripts
| Script | Description |
|--------|-------------|
| `pnpm build:rapier2d` | Build Rapier2D WASM (required for first-time setup) |
| `pnpm build:editor` | Build editor and all dependencies |
| `pnpm tauri:dev` | Run editor in development mode with hot-reload |
| `pnpm tauri:build` | Build production application |
| `pnpm build:sdk` | Build editor-runtime SDK |
## Project Structure
```
editor-app/
├── src/ # React application source
│ ├── components/ # UI components
│ ├── panels/ # Editor panels
│ └── services/ # Core services
├── src-tauri/ # Tauri (Rust) backend
├── public/ # Static assets
└── scripts/ # Build scripts
```
## Troubleshooting
### Rapier2D WASM Build Failed
**Error**: `Could not resolve "../pkg/rapier_wasm2d"`
**Cause**: Missing Rapier2D WASM artifacts.
**Solution**:
1. Ensure `wasm-pack` is installed: `cargo install wasm-pack`
2. Run `pnpm build:rapier2d`
3. Verify `packages/physics/rapier2d/pkg/` directory exists and contains `rapier_wasm2d_bg.wasm` file
### Build Errors
```bash
pnpm clean
pnpm install
pnpm build:editor
```
### Rust/Tauri Errors
```bash
rustup update
```
### Windows Users Building WASM
The `pnpm build:rapier2d` script works directly on Windows. If you encounter issues:
1. Use Git Bash or WSL
2. Or download pre-built WASM artifacts from [Releases](https://github.com/esengine/esengine/releases)
## Documentation
- [ESEngine Documentation](https://esengine.cn/)
- [Tauri Documentation](https://tauri.app/)
## License
MIT License

View File

@@ -0,0 +1,132 @@
# ESEngine 编辑器
基于 Tauri 2.x + React 18 构建的跨平台桌面可视化编辑器。
## 环境要求
运行编辑器前,请确保已安装以下环境:
- **Node.js** >= 18.x
- **pnpm** >= 10.x
- **Rust** >= 1.70 (Tauri 和 WASM 构建需要)
- **wasm-pack** (构建 Rapier2D 物理引擎需要)
- **平台相关依赖**
- **Windows**: Microsoft Visual Studio C++ Build Tools
- **macOS**: Xcode Command Line Tools (`xcode-select --install`)
- **Linux**: 参考 [Tauri 环境配置](https://tauri.app/v1/guides/getting-started/prerequisites)
### 安装 wasm-pack
```bash
# 使用 cargo 安装
cargo install wasm-pack
# 或使用官方安装脚本 (Linux/macOS)
curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh
```
## 快速开始
### 1. 克隆并安装
```bash
git clone https://github.com/esengine/esengine.git
cd esengine
pnpm install
```
### 2. 构建 Rapier2D WASM
编辑器依赖 Rapier2D 物理引擎的 WASM 产物。首次构建只需执行一条命令:
```bash
pnpm build:rapier2d
```
该命令会自动完成以下步骤:
1. 准备 Rust 项目
2. 构建 WASM
3. 复制产物到 `packages/physics/rapier2d/pkg`
4. 生成 TypeScript 源码
> **注意**:需要已安装 Rust 和 wasm-pack。
### 3. 构建编辑器
在项目根目录执行:
```bash
pnpm build:editor
```
### 4. 启动编辑器
```bash
cd packages/editor/editor-app
pnpm tauri:dev
```
## 可用脚本
| 脚本 | 说明 |
|------|------|
| `pnpm build:rapier2d` | 构建 Rapier2D WASM首次构建必须执行|
| `pnpm build:editor` | 构建编辑器及所有依赖 |
| `pnpm tauri:dev` | 开发模式运行编辑器(支持热重载)|
| `pnpm tauri:build` | 构建生产版本应用 |
| `pnpm build:sdk` | 构建 editor-runtime SDK |
## 项目结构
```
editor-app/
├── src/ # React 应用源码
│ ├── components/ # UI 组件
│ ├── panels/ # 编辑器面板
│ └── services/ # 核心服务
├── src-tauri/ # Tauri (Rust) 后端
├── public/ # 静态资源
└── scripts/ # 构建脚本
```
## 常见问题
### Rapier2D WASM 构建失败
**错误**: `Could not resolve "../pkg/rapier_wasm2d"`
**原因**: 缺少 Rapier2D 的 WASM 产物。
**解决方案**:
1. 确保已安装 `wasm-pack``cargo install wasm-pack`
2. 执行 `pnpm build:rapier2d`
3. 确认 `packages/physics/rapier2d/pkg/` 目录存在且包含 `rapier_wasm2d_bg.wasm` 文件
### 构建错误
```bash
pnpm clean
pnpm install
pnpm build:editor
```
### Rust/Tauri 错误
```bash
rustup update
```
### Windows 用户构建 WASM
`pnpm build:rapier2d` 脚本在 Windows 上可以直接运行。如果遇到问题:
1. 使用 Git Bash 或 WSL
2. 或从 [Releases](https://github.com/esengine/esengine/releases) 下载预编译的 WASM 产物
## 文档
- [ESEngine 文档](https://esengine.cn/)
- [Tauri 文档](https://tauri.app/)
## 许可证
MIT License

View File

@@ -9,7 +9,7 @@
"build": "npm run build:sdk && tsc && vite build",
"build:watch": "vite build --watch",
"tauri": "tauri",
"copy-modules": "node ../../scripts/copy-engine-modules.mjs",
"copy-modules": "node ../../../scripts/copy-engine-modules.mjs",
"tauri:dev": "npm run build:sdk && npm run copy-modules && tauri dev",
"bundle:runtime": "node scripts/bundle-runtime.mjs",
"tauri:build": "npm run build:sdk && npm run copy-modules && npm run bundle:runtime && tauri build",

File diff suppressed because it is too large Load Diff

View File

@@ -10,16 +10,16 @@ name = "ecs_editor_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
tauri-build = { version = "2.0", features = [] }
tauri-build = { version = "2", features = [] }
[dependencies]
tauri = { version = "2.0", features = ["protocol-asset"] }
tauri-plugin-shell = "2.0"
tauri-plugin-dialog = "2.0"
tauri-plugin-fs = "2.0"
tauri = { version = "2", features = ["protocol-asset"] }
tauri-plugin-shell = "2"
tauri-plugin-dialog = "2"
tauri-plugin-fs = "2"
tauri-plugin-updater = "2"
tauri-plugin-http = "2.0"
tauri-plugin-cli = "2.0"
tauri-plugin-http = "2"
tauri-plugin-cli = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
glob = "0.3"

View File

@@ -30,6 +30,7 @@
"devDependencies": {
"@esengine/ecs-framework": "workspace:*",
"@esengine/engine-core": "workspace:*",
"@esengine/asset-system": "workspace:*",
"@esengine/editor-core": "workspace:*",
"@esengine/editor-runtime": "workspace:*",
"@esengine/node-editor": "workspace:*",

View File

@@ -0,0 +1,45 @@
/**
* @zh ESEngine 行为树运行时模块
* @en ESEngine Behavior Tree Runtime Module
*
* @zh 纯运行时模块,不依赖 asset-system。资产加载由编辑器在 install 时注册。
* @en Pure runtime module, no asset-system dependency. Asset loading is registered by editor during install.
*/
import type { IScene, ServiceContainer, IComponentRegistry } from '@esengine/ecs-framework';
import type { IRuntimeModule, SystemContext } from '@esengine/engine-core';
import {
BehaviorTreeRuntimeComponent,
BehaviorTreeExecutionSystem,
BehaviorTreeAssetManager,
GlobalBlackboardService,
BehaviorTreeSystemToken
} from '@esengine/behavior-tree';
export class BehaviorTreeRuntimeModule implements IRuntimeModule {
registerComponents(registry: IComponentRegistry): void {
registry.register(BehaviorTreeRuntimeComponent);
}
registerServices(services: ServiceContainer): void {
if (!services.isRegistered(GlobalBlackboardService)) {
services.registerSingleton(GlobalBlackboardService);
}
if (!services.isRegistered(BehaviorTreeAssetManager)) {
services.registerSingleton(BehaviorTreeAssetManager);
}
}
createSystems(scene: IScene, context: SystemContext): void {
const ecsServices = (context as { ecsServices?: ServiceContainer }).ecsServices;
const behaviorTreeSystem = new BehaviorTreeExecutionSystem(ecsServices);
if (context.isEditor) {
behaviorTreeSystem.enabled = false;
}
scene.addSystem(behaviorTreeSystem);
context.services.register(BehaviorTreeSystemToken, behaviorTreeSystem);
}
}

View File

@@ -30,8 +30,11 @@ import {
LocaleService,
} from '@esengine/editor-runtime';
// Runtime imports from @esengine/behavior-tree package
import { BehaviorTreeRuntimeComponent, BehaviorTreeRuntimeModule } from '@esengine/behavior-tree';
// Runtime imports
import { BehaviorTreeRuntimeComponent, BehaviorTreeAssetType } from '@esengine/behavior-tree';
import { AssetManagerToken } from '@esengine/asset-system';
import { BehaviorTreeRuntimeModule } from './BehaviorTreeRuntimeModule';
import { BehaviorTreeLoader } from './runtime/BehaviorTreeLoader';
// Editor components and services
import { BehaviorTreeService } from './services/BehaviorTreeService';
@@ -71,6 +74,10 @@ export class BehaviorTreeEditorModule implements IEditorModuleLoader {
// 设置插件上下文
PluginContext.setServices(services);
// 注册行为树资产加载器到 AssetManager
// Register behavior tree asset loader to AssetManager
this.registerAssetLoader();
// 注册服务
this.registerServices(services);
@@ -92,6 +99,22 @@ export class BehaviorTreeEditorModule implements IEditorModuleLoader {
logger.info('BehaviorTree editor module installed');
}
/**
* 注册行为树资产加载器
* Register behavior tree asset loader
*/
private registerAssetLoader(): void {
try {
const assetManager = PluginAPI.resolve(AssetManagerToken);
if (assetManager) {
assetManager.registerLoader(BehaviorTreeAssetType, new BehaviorTreeLoader());
logger.info('BehaviorTree asset loader registered');
}
} catch (error) {
logger.warn('Failed to register asset loader:', error);
}
}
private registerAssetCreationMappings(services: ServiceContainer): void {
try {
const fileActionRegistry = services.resolve<FileActionRegistry>(IFileActionRegistry);
@@ -376,7 +399,7 @@ export const BehaviorTreePlugin: IEditorPlugin = {
editorModule: new BehaviorTreeEditorModule(),
};
export { BehaviorTreeRuntimeModule };
// BehaviorTreeRuntimeModule is internal, not re-exported
// Re-exports for editor functionality
export { PluginContext } from './PluginContext';

View File

@@ -0,0 +1,61 @@
/**
* @zh ESEngine 资产加载器
* @en ESEngine asset loader
* @internal
*/
import { Core } from '@esengine/ecs-framework';
import {
BehaviorTreeAssetManager,
EditorToBehaviorTreeDataConverter,
BehaviorTreeAssetType,
type BehaviorTreeData
} from '@esengine/behavior-tree';
/**
* @zh 行为树资产接口
* @en Behavior tree asset interface
* @internal
*/
export interface IBehaviorTreeAsset {
data: BehaviorTreeData;
path: string;
}
/**
* @zh 行为树加载器
* @en Behavior tree loader implementing IAssetLoader interface
* @internal
*/
export class BehaviorTreeLoader {
readonly supportedType = BehaviorTreeAssetType;
readonly supportedExtensions = ['.btree'];
readonly contentType = 'text' as const;
async parse(content: { text?: string }, context: { metadata: { path: string } }): Promise<IBehaviorTreeAsset> {
if (!content.text) {
throw new Error('Behavior tree content is empty');
}
const treeData = EditorToBehaviorTreeDataConverter.fromEditorJSON(content.text);
const assetPath = context.metadata.path;
treeData.id = assetPath;
const btAssetManager = Core.services.tryResolve(BehaviorTreeAssetManager);
if (btAssetManager) {
btAssetManager.loadAsset(treeData);
}
return {
data: treeData,
path: assetPath
};
}
dispose(asset: IBehaviorTreeAsset): void {
const btAssetManager = Core.services.tryResolve(BehaviorTreeAssetManager);
if (btAssetManager && asset.data) {
btAssetManager.unloadAsset(asset.data.id);
}
}
}

View File

@@ -1,23 +1,18 @@
{
"extends": "../../../../tsconfig.base.json",
"compilerOptions": {
"target": "ES2020",
"module": "ES2020",
"moduleResolution": "bundler",
"lib": ["ES2020", "DOM"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"composite": false,
"declaration": true,
"declarationMap": true,
"outDir": "./dist",
"rootDir": "./src",
"jsx": "react-jsx",
"resolveJsonModule": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true
"skipLibCheck": true,
"moduleResolution": "bundler",
"paths": {
"@esengine/asset-system": ["../../../engine/asset-system/src"]
}
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
"exclude": ["node_modules", "dist", "**/*.test.ts"]
}

View File

@@ -2,6 +2,7 @@ import { defineConfig } from 'tsup';
import { editorOnlyPreset } from '../../../tools/build-config/src/presets/plugin-tsup';
export default defineConfig({
...editorOnlyPreset(),
tsconfig: 'tsconfig.build.json'
...editorOnlyPreset({}),
tsconfig: 'tsconfig.build.json',
noExternal: ['@esengine/asset-system']
});

View File

@@ -0,0 +1,13 @@
{
"extends": "../../../../tsconfig.base.json",
"compilerOptions": {
"composite": false,
"declaration": true,
"declarationMap": true,
"outDir": "./dist",
"rootDir": "./src",
"jsx": "react-jsx"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "**/*.test.ts"]
}

View File

@@ -1,6 +1,7 @@
{
"extends": "../build-config/tsconfig.json",
"extends": "../../../../tsconfig.base.json",
"compilerOptions": {
"composite": true,
"outDir": "./dist",
"rootDir": "./src",
"jsx": "react-jsx",

View File

@@ -5,6 +5,7 @@ export default defineConfig({
format: ['esm'],
dts: true,
clean: true,
tsconfig: 'tsconfig.build.json',
external: [
'react',
'react-dom',

View File

@@ -1,5 +1,72 @@
# @esengine/behavior-tree
## 4.1.1
### Patch Changes
- Updated dependencies [[`3e5b778`](https://github.com/esengine/esengine/commit/3e5b7783beec08e247f7525184935401923ecde8)]:
- @esengine/ecs-framework@2.7.1
## 4.1.0
### Minor Changes
- [#400](https://github.com/esengine/esengine/pull/400) [`d2af9ca`](https://github.com/esengine/esengine/commit/d2af9caae9d5620c5f690272ab80dc246e9b7e10) Thanks [@esengine](https://github.com/esengine)! - feat(behavior-tree): add pure BehaviorTreePlugin class for Cocos/Laya integration
- Added `BehaviorTreePlugin` class that only depends on `@esengine/ecs-framework`
- Implements `IPlugin` interface with `install()`, `uninstall()`, and `setupScene()` methods
- Removed `esengine/` subdirectory that incorrectly depended on `@esengine/engine-core`
- Updated package documentation with correct usage examples
Usage:
```typescript
import { Core, Scene } from '@esengine/ecs-framework';
import { BehaviorTreePlugin, BehaviorTreeBuilder, BehaviorTreeStarter } from '@esengine/behavior-tree';
Core.create();
const plugin = new BehaviorTreePlugin();
await Core.installPlugin(plugin);
const scene = new Scene();
plugin.setupScene(scene);
Core.setScene(scene);
```
## 4.0.0
### Patch Changes
- Updated dependencies [[`1f3a76a`](https://github.com/esengine/esengine/commit/1f3a76aabea2d3eb8a5eb8b73e29127da57e2028)]:
- @esengine/ecs-framework@2.7.0
## 3.0.1
### Patch Changes
- Updated dependencies [[`04b08f3`](https://github.com/esengine/esengine/commit/04b08f3f073d69beb8f4be399c774bea0acb612e)]:
- @esengine/ecs-framework@2.6.1
## 3.0.0
### Patch Changes
- Updated dependencies []:
- @esengine/ecs-framework@2.6.0
## 2.0.1
### Patch Changes
- Updated dependencies [[`a08a84b`](https://github.com/esengine/esengine/commit/a08a84b7db28e1140cbc637d442552747ad81c76)]:
- @esengine/ecs-framework@2.5.1
## 2.0.0
### Patch Changes
- Updated dependencies [[`1f297ac`](https://github.com/esengine/esengine/commit/1f297ac769e37700f72fb4425639af7090898256)]:
- @esengine/ecs-framework@2.5.0
## 1.0.3
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "@esengine/behavior-tree",
"version": "1.0.3",
"version": "4.1.1",
"description": "ECS-based AI behavior tree system - works with any ECS framework (ESEngine, Cocos, Laya, etc.)",
"main": "dist/index.js",
"module": "dist/index.js",

View File

@@ -0,0 +1,118 @@
import type { Core, ServiceContainer, IPlugin, IScene } from '@esengine/ecs-framework';
import { BehaviorTreeExecutionSystem } from './execution/BehaviorTreeExecutionSystem';
import { BehaviorTreeAssetManager } from './execution/BehaviorTreeAssetManager';
import { GlobalBlackboardService } from './Services/GlobalBlackboardService';
/**
* @zh 行为树插件
* @en Behavior Tree Plugin
*
* @zh 为 ECS 框架提供行为树支持的插件。
* 可与任何基于 @esengine/ecs-framework 的引擎集成Cocos、Laya、Node.js 等)。
*
* @en Plugin that provides behavior tree support for ECS framework.
* Can be integrated with any engine based on @esengine/ecs-framework (Cocos, Laya, Node.js, etc.).
*
* @example
* ```typescript
* import { Core, Scene } from '@esengine/ecs-framework';
* import { BehaviorTreePlugin, BehaviorTreeBuilder, BehaviorTreeStarter } from '@esengine/behavior-tree';
*
* // Initialize
* Core.create();
* const plugin = new BehaviorTreePlugin();
* await Core.installPlugin(plugin);
*
* // Setup scene
* const scene = new Scene();
* plugin.setupScene(scene);
* Core.setScene(scene);
*
* // Create and start behavior tree
* const tree = BehaviorTreeBuilder.create('MyAI')
* .selector('Root')
* .log('Hello from behavior tree!')
* .end()
* .build();
*
* const entity = scene.createEntity('AIEntity');
* BehaviorTreeStarter.start(entity, tree);
* ```
*/
export class BehaviorTreePlugin implements IPlugin {
/**
* @zh 插件名称
* @en Plugin name
*/
readonly name = '@esengine/behavior-tree';
/**
* @zh 插件版本
* @en Plugin version
*/
readonly version = '1.0.0';
/**
* @zh 插件依赖
* @en Plugin dependencies
*/
readonly dependencies: readonly string[] = [];
private _services: ServiceContainer | null = null;
/**
* @zh 安装插件
* @en Install plugin
*
* @param _core - Core 实例
* @param services - 服务容器
*/
install(_core: Core, services: ServiceContainer): void {
this._services = services;
// Register services
if (!services.isRegistered(GlobalBlackboardService)) {
services.registerSingleton(GlobalBlackboardService);
}
if (!services.isRegistered(BehaviorTreeAssetManager)) {
services.registerSingleton(BehaviorTreeAssetManager);
}
}
/**
* @zh 卸载插件
* @en Uninstall plugin
*/
uninstall(): void {
if (this._services) {
const assetManager = this._services.tryResolve(BehaviorTreeAssetManager);
if (assetManager) {
assetManager.dispose();
}
const blackboardService = this._services.tryResolve(GlobalBlackboardService);
if (blackboardService) {
blackboardService.dispose();
}
}
this._services = null;
}
/**
* @zh 设置场景,添加行为树执行系统
* @en Setup scene, add behavior tree execution system
*
* @param scene - 要设置的场景
*
* @example
* ```typescript
* const scene = new Scene();
* plugin.setupScene(scene);
* Core.setScene(scene);
* ```
*/
setupScene(scene: IScene): void {
const system = new BehaviorTreeExecutionSystem(this._services ?? undefined);
scene.addSystem(system);
}
}

View File

@@ -1,82 +0,0 @@
/**
* @zh ESEngine 资产加载器
* @en ESEngine asset loader
*
* @zh 实现 IAssetLoader 接口,用于通过 AssetManager 加载行为树文件。
* 此文件仅在使用 ESEngine 时需要。
*
* @en Implements IAssetLoader interface for loading behavior tree files via AssetManager.
* This file is only needed when using ESEngine.
*/
import type {
IAssetLoader,
IAssetParseContext,
IAssetContent,
AssetContentType
} from '@esengine/asset-system';
import { Core } from '@esengine/ecs-framework';
import { BehaviorTreeData } from '../execution/BehaviorTreeData';
import { BehaviorTreeAssetManager } from '../execution/BehaviorTreeAssetManager';
import { EditorToBehaviorTreeDataConverter } from '../Serialization/EditorToBehaviorTreeDataConverter';
import { BehaviorTreeAssetType } from '../constants';
/**
* @zh 行为树资产接口
* @en Behavior tree asset interface
*/
export interface IBehaviorTreeAsset {
/** @zh 行为树数据 @en Behavior tree data */
data: BehaviorTreeData;
/** @zh 文件路径 @en File path */
path: string;
}
/**
* @zh 行为树加载器
* @en Behavior tree loader implementing IAssetLoader interface
*/
export class BehaviorTreeLoader implements IAssetLoader<IBehaviorTreeAsset> {
readonly supportedType = BehaviorTreeAssetType;
readonly supportedExtensions = ['.btree'];
readonly contentType: AssetContentType = 'text';
/**
* @zh 从内容解析行为树资产
* @en Parse behavior tree asset from content
*/
async parse(content: IAssetContent, context: IAssetParseContext): Promise<IBehaviorTreeAsset> {
if (!content.text) {
throw new Error('Behavior tree content is empty');
}
// Convert to runtime data
const treeData = EditorToBehaviorTreeDataConverter.fromEditorJSON(content.text);
// Use file path as ID
const assetPath = context.metadata.path;
treeData.id = assetPath;
// Also register to BehaviorTreeAssetManager for legacy code
const btAssetManager = Core.services.tryResolve(BehaviorTreeAssetManager);
if (btAssetManager) {
btAssetManager.loadAsset(treeData);
}
return {
data: treeData,
path: assetPath
};
}
/**
* @zh 释放资产
* @en Dispose asset
*/
dispose(asset: IBehaviorTreeAsset): void {
const btAssetManager = Core.services.tryResolve(BehaviorTreeAssetManager);
if (btAssetManager && asset.data) {
btAssetManager.unloadAsset(asset.data.id);
}
}
}

View File

@@ -1,93 +0,0 @@
/**
* @zh ESEngine 集成模块
* @en ESEngine integration module
*
* @zh 此文件包含与 ESEngine 引擎核心集成的代码。
* 使用 Cocos/Laya 等其他引擎时不需要此文件。
*
* @en This file contains code for integrating with ESEngine engine-core.
* Not needed when using other engines like Cocos/Laya.
*/
import type { IScene, ServiceContainer, IComponentRegistry } from '@esengine/ecs-framework';
import type { IRuntimeModule, IRuntimePlugin, ModuleManifest, SystemContext } from '@esengine/engine-core';
import { AssetManagerToken } from '@esengine/asset-system';
import { BehaviorTreeRuntimeComponent } from '../execution/BehaviorTreeRuntimeComponent';
import { BehaviorTreeExecutionSystem } from '../execution/BehaviorTreeExecutionSystem';
import { BehaviorTreeAssetManager } from '../execution/BehaviorTreeAssetManager';
import { GlobalBlackboardService } from '../Services/GlobalBlackboardService';
import { BehaviorTreeLoader } from './BehaviorTreeLoader';
import { BehaviorTreeAssetType } from '../constants';
import { BehaviorTreeSystemToken } from '../tokens';
// Re-export tokens for ESEngine users
export { BehaviorTreeSystemToken } from '../tokens';
class BehaviorTreeRuntimeModule implements IRuntimeModule {
private _loaderRegistered = false;
registerComponents(registry: IComponentRegistry): void {
registry.register(BehaviorTreeRuntimeComponent);
}
registerServices(services: ServiceContainer): void {
if (!services.isRegistered(GlobalBlackboardService)) {
services.registerSingleton(GlobalBlackboardService);
}
if (!services.isRegistered(BehaviorTreeAssetManager)) {
services.registerSingleton(BehaviorTreeAssetManager);
}
}
createSystems(scene: IScene, context: SystemContext): void {
// Get dependencies from service registry
const assetManager = context.services.get(AssetManagerToken);
if (!this._loaderRegistered && assetManager) {
assetManager.registerLoader(BehaviorTreeAssetType, new BehaviorTreeLoader());
this._loaderRegistered = true;
}
// Use ECS service container from context.services
const ecsServices = (context as { ecsServices?: ServiceContainer }).ecsServices;
const behaviorTreeSystem = new BehaviorTreeExecutionSystem(ecsServices);
if (assetManager) {
behaviorTreeSystem.setAssetManager(assetManager);
}
if (context.isEditor) {
behaviorTreeSystem.enabled = false;
}
scene.addSystem(behaviorTreeSystem);
// Register service to service registry
context.services.register(BehaviorTreeSystemToken, behaviorTreeSystem);
}
}
const manifest: ModuleManifest = {
id: 'behavior-tree',
name: '@esengine/behavior-tree',
displayName: 'Behavior Tree',
version: '1.0.0',
description: 'AI behavior tree system',
category: 'AI',
icon: 'GitBranch',
isCore: false,
defaultEnabled: false,
isEngineModule: true,
canContainContent: true,
dependencies: ['core'],
exports: { components: ['BehaviorTreeComponent'] },
editorPackage: '@esengine/behavior-tree-editor'
};
export const BehaviorTreePlugin: IRuntimePlugin = {
manifest,
runtimeModule: new BehaviorTreeRuntimeModule()
};
export { BehaviorTreeRuntimeModule };

View File

@@ -1,39 +0,0 @@
/**
* @zh ESEngine 集成入口
* @en ESEngine integration entry point
*
* @zh 此模块包含与 ESEngine 引擎核心集成所需的所有代码。
* 使用 Cocos/Laya 等其他引擎时,只需导入主模块即可。
*
* @en This module contains all code required for ESEngine engine-core integration.
* When using other engines like Cocos/Laya, just import the main module.
*
* @example ESEngine 使用方式 / ESEngine usage:
* ```typescript
* import { BehaviorTreePlugin } from '@esengine/behavior-tree/esengine';
*
* // Register with ESEngine plugin system
* engine.registerPlugin(BehaviorTreePlugin);
* ```
*
* @example Cocos/Laya 使用方式 / Cocos/Laya usage:
* ```typescript
* import {
* BehaviorTreeAssetManager,
* BehaviorTreeExecutionSystem
* } from '@esengine/behavior-tree';
*
* // Load behavior tree from JSON
* const assetManager = new BehaviorTreeAssetManager();
* assetManager.loadFromEditorJSON(jsonContent);
*
* // Add system to your ECS world
* world.addSystem(new BehaviorTreeExecutionSystem());
* ```
*/
// Runtime module and plugin
export { BehaviorTreeRuntimeModule, BehaviorTreePlugin, BehaviorTreeSystemToken } from './BehaviorTreeRuntimeModule';
// Asset loader for ESEngine asset-system
export { BehaviorTreeLoader, type IBehaviorTreeAsset } from './BehaviorTreeLoader';

View File

@@ -4,32 +4,44 @@
* @zh AI 行为树系统,支持运行时执行和可视化编辑
* @en AI Behavior Tree System with runtime execution and visual editor support
*
* @zh 此包是通用的行为树实现,可以与任何 ECS 框架配合使用。
* 对于 ESEngine 集成,请从 '@esengine/behavior-tree/esengine' 导入插件
* @zh 此包是通用的行为树实现,可以与任何基于 @esengine/ecs-framework 的引擎集成
* Cocos Creator、LayaAir、Node.js 等)
*
* @en This package is a generic behavior tree implementation that works with any ECS framework.
* For ESEngine integration, import the plugin from '@esengine/behavior-tree/esengine'.
* @en This package is a generic behavior tree implementation that works with any engine
* based on @esengine/ecs-framework (Cocos Creator, LayaAir, Node.js, etc.).
*
* @example Cocos/Laya/通用 ECS 使用方式:
* @example
* ```typescript
* import { Core, Scene } from '@esengine/ecs-framework';
* import {
* BehaviorTreeAssetManager,
* BehaviorTreeExecutionSystem,
* BehaviorTreeRuntimeComponent
* BehaviorTreePlugin,
* BehaviorTreeBuilder,
* BehaviorTreeStarter
* } from '@esengine/behavior-tree';
*
* // 1. Register service
* Core.services.registerSingleton(BehaviorTreeAssetManager);
* // 1. Initialize Core and install plugin
* Core.create();
* const plugin = new BehaviorTreePlugin();
* await Core.installPlugin(plugin);
*
* // 2. Load behavior tree from JSON
* const assetManager = Core.services.resolve(BehaviorTreeAssetManager);
* assetManager.loadFromEditorJSON(jsonContent);
* // 2. Create scene and setup behavior tree system
* const scene = new Scene();
* plugin.setupScene(scene);
* Core.setScene(scene);
*
* // 3. Add component to entity
* entity.addComponent(new BehaviorTreeRuntimeComponent());
* // 3. Build behavior tree
* const tree = BehaviorTreeBuilder.create('MyAI')
* .selector('Root')
* .log('Hello!')
* .end()
* .build();
*
* // 4. Add system to scene
* scene.addSystem(new BehaviorTreeExecutionSystem());
* // 4. Start behavior tree on entity
* const entity = scene.createEntity('AIEntity');
* BehaviorTreeStarter.start(entity, tree);
*
* // 5. Run game loop
* setInterval(() => Core.update(0.016), 16);
* ```
*
* @packageDocumentation
@@ -65,3 +77,6 @@ export { BlackboardTypes } from './Blackboard/BlackboardTypes';
// Service tokens (using ecs-framework's createServiceToken, not engine-core)
export { BehaviorTreeSystemToken } from './tokens';
// Plugin
export { BehaviorTreePlugin } from './BehaviorTreePlugin';

View File

@@ -1,5 +1,47 @@
# @esengine/blueprint
## 4.0.1
### Patch Changes
- Updated dependencies [[`3e5b778`](https://github.com/esengine/esengine/commit/3e5b7783beec08e247f7525184935401923ecde8)]:
- @esengine/ecs-framework@2.7.1
## 4.0.0
### Patch Changes
- Updated dependencies [[`1f3a76a`](https://github.com/esengine/esengine/commit/1f3a76aabea2d3eb8a5eb8b73e29127da57e2028)]:
- @esengine/ecs-framework@2.7.0
## 3.0.1
### Patch Changes
- Updated dependencies [[`04b08f3`](https://github.com/esengine/esengine/commit/04b08f3f073d69beb8f4be399c774bea0acb612e)]:
- @esengine/ecs-framework@2.6.1
## 3.0.0
### Patch Changes
- Updated dependencies []:
- @esengine/ecs-framework@2.6.0
## 2.0.1
### Patch Changes
- Updated dependencies [[`a08a84b`](https://github.com/esengine/esengine/commit/a08a84b7db28e1140cbc637d442552747ad81c76)]:
- @esengine/ecs-framework@2.5.1
## 2.0.0
### Patch Changes
- Updated dependencies [[`1f297ac`](https://github.com/esengine/esengine/commit/1f297ac769e37700f72fb4425639af7090898256)]:
- @esengine/ecs-framework@2.5.0
## 1.0.2
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "@esengine/blueprint",
"version": "1.0.2",
"version": "4.0.1",
"description": "Visual scripting system - works with any ECS framework (ESEngine, Cocos, Laya, etc.)",
"main": "dist/index.js",
"module": "dist/index.js",

View File

@@ -1,5 +1,217 @@
# @esengine/ecs-framework
## 2.7.1
### Patch Changes
- [#402](https://github.com/esengine/esengine/pull/402) [`3e5b778`](https://github.com/esengine/esengine/commit/3e5b7783beec08e247f7525184935401923ecde8) Thanks [@esengine](https://github.com/esengine)! - fix(ecs): 修复 ESM 环境下 require 不存在的问题
- 新增 `RuntimeConfig` 模块,作为运行时环境配置的独立存储
- `Core.runtimeEnvironment``Scene.runtimeEnvironment` 现在都从 `RuntimeConfig` 读取
- 移除 `Scene.ts` 中的 `require()` 调用,解决 Node.js ESM 环境下的兼容性问题
此修复解决了在 Node.js ESM 环境(如游戏服务端)中使用 `scene.isServer` 时报错 `ReferenceError: require is not defined` 的问题。
## 2.7.0
### Minor Changes
- [#398](https://github.com/esengine/esengine/pull/398) [`1f3a76a`](https://github.com/esengine/esengine/commit/1f3a76aabea2d3eb8a5eb8b73e29127da57e2028) Thanks [@esengine](https://github.com/esengine)! - feat(ecs): 添加运行时环境区分机制 | add runtime environment detection
新增功能:
- `Core` 新增静态属性 `runtimeEnvironment`,支持 `'server' | 'client' | 'standalone'`
- `Core` 新增 `isServer` / `isClient` 静态只读属性
- `ICoreConfig` 新增 `runtimeEnvironment` 配置项
- `Scene` 新增 `isServer` / `isClient` 只读属性(默认从 Core 继承,可通过 config 覆盖)
- 新增 `@ServerOnly()` / `@ClientOnly()` / `@NotServer()` / `@NotClient()` 方法装饰器
用于网络游戏中区分服务端权威逻辑和客户端逻辑:
```typescript
// 方式1: 全局设置(推荐)
Core.create({ runtimeEnvironment: 'server' });
// 或直接设置静态属性
Core.runtimeEnvironment = 'server';
// 所有场景自动继承
const scene = new Scene();
console.log(scene.isServer); // true
// 方式2: 单个场景覆盖(可选)
const clientScene = new Scene({ runtimeEnvironment: 'client' });
// 在系统中检查环境
class CollectibleSpawnSystem extends EntitySystem {
private checkCollections(): void {
if (!this.scene.isServer) return; // 客户端跳过
// ... 服务端权威逻辑
}
}
```
## 2.6.1
### Patch Changes
- [#396](https://github.com/esengine/esengine/pull/396) [`04b08f3`](https://github.com/esengine/esengine/commit/04b08f3f073d69beb8f4be399c774bea0acb612e) Thanks [@esengine](https://github.com/esengine)! - fix(ecs): COMPONENT_ADDED 事件添加 entity 字段
修复 `ECSEventType.COMPONENT_ADDED` 事件缺少 `entity` 字段的问题,导致 ECSRoom 的 `@NetworkEntity` 自动广播功能报错。
## 2.6.0
### Minor Changes
- feat(ecs): 添加 @NetworkEntity 装饰器,支持自动广播实体生成/销毁
### 新功能
**@NetworkEntity 装饰器**
- 标记组件为网络实体,自动广播 spawn/despawn 消息
- 支持 `autoSpawn` 和 `autoDespawn` 配置选项
- 通过事件系统(`ECSEventType.COMPONENT_ADDED` / `ECSEventType.ENTITY_DESTROYED`)实现
**ECSRoom 增强**
- 新增 `enableAutoNetworkEntity` 配置选项(默认启用)
- 自动监听组件添加和实体销毁事件
- 简化 GameRoom 实现,无需手动回调
### 改进
**Entity 事件**
- `Entity.destroy()` 现在发出 `entity:destroyed` 事件
- `Entity.active` 变化时发出 `entity:enabled` / `entity:disabled` 事件
- 使用 `ECSEventType` 常量替代硬编码字符串
### 使用示例
```typescript
import { Component, ECSComponent, sync, NetworkEntity } from '@esengine/ecs-framework';
@ECSComponent('Enemy')
@NetworkEntity('Enemy')
class EnemyComponent extends Component {
@sync('float32') x: number = 0;
@sync('float32') y: number = 0;
}
// 服务端
const entity = scene.createEntity('Enemy');
entity.addComponent(new EnemyComponent()); // 自动广播 spawn
entity.destroy(); // 自动广播 despawn
```
## 2.5.1
### Patch Changes
- [#392](https://github.com/esengine/esengine/pull/392) [`a08a84b`](https://github.com/esengine/esengine/commit/a08a84b7db28e1140cbc637d442552747ad81c76) Thanks [@esengine](https://github.com/esengine)! - fix(sync): Decoder 现在使用 GlobalComponentRegistry 查找组件 | Decoder now uses GlobalComponentRegistry for component lookup
**问题 | Problem:**
1. `Decoder.ts` 有自己独立的 `componentRegistry` Map与 `GlobalComponentRegistry` 完全分离。这导致通过 `@ECSComponent` 装饰器注册的组件在网络反序列化时找不到,产生 "Unknown component type" 错误。
2. `@sync` 装饰器使用 `constructor.name` 作为 `typeId`,而不是 `@ECSComponent` 装饰器指定的名称,导致编码和解码使用不同的类型 ID。
3. `Decoder.ts` had its own local `componentRegistry` Map that was completely separate from `GlobalComponentRegistry`. This caused components registered via `@ECSComponent` decorator to not be found during network deserialization, resulting in "Unknown component type" errors.
4. `@sync` decorator used `constructor.name` as `typeId` instead of the name specified by `@ECSComponent` decorator, causing encoding and decoding to use different type IDs.
**修改 | Changes:**
- 从 Decoder.ts 中移除本地 `componentRegistry`
- 更新 `decodeEntity` 和 `decodeSpawn` 使用 `GlobalComponentRegistry.getComponentType()`
- 移除已废弃的 `registerSyncComponent` 和 `autoRegisterSyncComponent` 函数
- 更新 `@sync` 装饰器使用 `getComponentTypeName()` 获取组件类型名称
- 更新 `@ECSComponent` 装饰器同步更新 `SYNC_METADATA.typeId`
- Removed local `componentRegistry` from Decoder.ts
- Updated `decodeEntity` and `decodeSpawn` to use `GlobalComponentRegistry.getComponentType()`
- Removed deprecated `registerSyncComponent` and `autoRegisterSyncComponent` functions
- Updated `@sync` decorator to use `getComponentTypeName()` for component type name
- Updated `@ECSComponent` decorator to sync update `SYNC_METADATA.typeId`
现在使用 `@ECSComponent` 装饰器的组件会自动可用于网络同步解码,无需手动注册。
Now `@ECSComponent` decorated components are automatically available for network sync decoding without any manual registration.
## 2.5.0
### Minor Changes
- [#390](https://github.com/esengine/esengine/pull/390) [`1f297ac`](https://github.com/esengine/esengine/commit/1f297ac769e37700f72fb4425639af7090898256) Thanks [@esengine](https://github.com/esengine)! - feat: ECS 网络状态同步系统
## @esengine/ecs-framework
新增 `@sync` 装饰器和二进制编解码器,支持基于 Component 的网络状态同步:
```typescript
import { Component, ECSComponent, sync } from '@esengine/ecs-framework';
@ECSComponent('Player')
class PlayerComponent extends Component {
@sync('string') name: string = '';
@sync('uint16') score: number = 0;
@sync('float32') x: number = 0;
@sync('float32') y: number = 0;
}
```
### 新增导出
- `sync` - 标记需要同步的字段装饰器
- `SyncType` - 支持的同步类型
- `SyncOperation` - 同步操作类型FULL/DELTA/SPAWN/DESPAWN
- `encodeSnapshot` / `decodeSnapshot` - 批量编解码
- `encodeSpawn` / `decodeSpawn` - 实体生成编解码
- `encodeDespawn` / `processDespawn` - 实体销毁编解码
- `ChangeTracker` - 字段级变更追踪
- `initChangeTracker` / `clearChanges` / `hasChanges` - 变更追踪工具函数
### 内部方法标记
将以下方法标记为 `@internal`,用户应通过 `Core.update()` 驱动更新:
- `Scene.update()`
- `SceneManager.update()`
- `WorldManager.updateAll()`
## @esengine/network
新增 `ComponentSyncSystem`,基于 `@sync` 装饰器自动同步组件状态:
```typescript
import { ComponentSyncSystem } from '@esengine/network';
// 服务端:编码状态
const data = syncSystem.encodeAllEntities(false);
// 客户端:解码状态
syncSystem.applySnapshot(data);
```
### 修复
- 将 `@esengine/ecs-framework` 从 devDependencies 移到 peerDependencies
## @esengine/server
新增 `ECSRoom`,带有 ECS World 支持的房间基类:
```typescript
import { ECSRoom } from '@esengine/server/ecs';
// 服务端启动
Core.create();
setInterval(() => Core.update(1 / 60), 16);
// 定义房间
class GameRoom extends ECSRoom {
onCreate() {
this.addSystem(new PhysicsSystem());
}
onJoin(player: Player) {
const entity = this.createPlayerEntity(player.id);
entity.addComponent(new PlayerComponent());
}
}
```
### 设计
- 每个 `ECSRoom` 在 `Core.worldManager` 中创建独立的 World
- `Core.update()` 统一更新 Time 和所有 World
- `onTick()` 只处理状态同步逻辑
## 2.4.4
### Patch Changes

View File

@@ -1,16 +1,18 @@
{
"name": "@esengine/ecs-framework",
"version": "2.4.4",
"version": "2.7.1",
"description": "用于Laya、Cocos Creator等JavaScript游戏引擎的高性能ECS框架",
"main": "dist/index.cjs",
"module": "dist/index.mjs",
"types": "dist/index.d.ts",
"unpkg": "dist/index.umd.js",
"sideEffects": false,
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
"require": "./dist/index.cjs",
"source": "./src/index.ts"
}
},
"files": [
@@ -50,23 +52,24 @@
"@babel/plugin-transform-nullish-coalescing-operator": "^7.27.1",
"@babel/plugin-transform-optional-chaining": "^7.27.1",
"@babel/preset-env": "^7.28.3",
"@eslint/js": "^9.37.0",
"@jest/globals": "^29.7.0",
"@rollup/plugin-babel": "^6.0.4",
"@rollup/plugin-commonjs": "^28.0.3",
"@rollup/plugin-node-resolve": "^16.0.1",
"@rollup/plugin-terser": "^0.4.4",
"@jest/globals": "^29.7.0",
"@types/jest": "^29.5.14",
"@types/node": "^20.19.17",
"@eslint/js": "^9.37.0",
"eslint": "^9.37.0",
"typescript-eslint": "^8.46.1",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"rimraf": "^5.0.0",
"rollup": "^4.42.0",
"rollup-plugin-dts": "^6.2.1",
"rollup-plugin-sourcemaps": "^0.6.3",
"ts-jest": "^29.4.0",
"typescript": "^5.8.3"
"typescript": "^5.8.3",
"typescript-eslint": "^8.46.1"
},
"publishConfig": {
"access": "public",

View File

@@ -5,7 +5,7 @@ import { Time } from './Utils/Time';
import { PerformanceMonitor } from './Utils/PerformanceMonitor';
import { PoolManager } from './Utils/Pool/PoolManager';
import { DebugManager } from './Utils/Debug';
import { ICoreConfig, IECSDebugConfig } from './Types';
import { ICoreConfig, IECSDebugConfig, RuntimeEnvironment } from './Types';
import { createLogger } from './Utils/Logger';
import { SceneManager } from './ECS/SceneManager';
import { IScene } from './ECS/IScene';
@@ -16,6 +16,7 @@ import { IPlugin } from './Core/Plugin';
import { WorldManager } from './ECS/WorldManager';
import { DebugConfigService } from './Utils/Debug/DebugConfigService';
import { createInstance } from './Core/DI/Decorators';
import { RuntimeConfig } from './RuntimeConfig';
/**
* @zh 游戏引擎核心类
@@ -63,6 +64,53 @@ export class Core {
*/
public static paused = false;
/**
* @zh 运行时环境
* @en Runtime environment
*
* @zh 全局运行时环境设置。所有 Scene 默认继承此值。
* 服务端框架(如 @esengine/server应在启动时设置为 'server'。
* 客户端应用应设置为 'client'。
* 单机游戏使用默认值 'standalone'。
*
* @en Global runtime environment setting. All Scenes inherit this value by default.
* Server frameworks (like @esengine/server) should set this to 'server' at startup.
* Client apps should set this to 'client'.
* Standalone games use the default 'standalone'.
*
* @example
* ```typescript
* // @zh 服务端启动时设置 | @en Set at server startup
* Core.runtimeEnvironment = 'server';
*
* // @zh 或在 Core.create 时配置 | @en Or configure in Core.create
* Core.create({ runtimeEnvironment: 'server' });
* ```
*/
public static get runtimeEnvironment(): RuntimeEnvironment {
return RuntimeConfig.runtimeEnvironment;
}
public static set runtimeEnvironment(value: RuntimeEnvironment) {
RuntimeConfig.runtimeEnvironment = value;
}
/**
* @zh 是否在服务端运行
* @en Whether running on server
*/
public static get isServer(): boolean {
return RuntimeConfig.isServer;
}
/**
* @zh 是否在客户端运行
* @en Whether running on client
*/
public static get isClient(): boolean {
return RuntimeConfig.isClient;
}
/**
* @zh 全局核心实例可能为null表示Core尚未初始化或已被销毁
* @en Global core instance, null means Core is not initialized or destroyed
@@ -133,6 +181,11 @@ export class Core {
this._config = { debug: true, ...config };
this._serviceContainer = new ServiceContainer();
// 设置全局运行时环境
if (config.runtimeEnvironment) {
Core.runtimeEnvironment = config.runtimeEnvironment;
}
this._timerManager = new TimerManager();
this._serviceContainer.registerInstance(TimerManager, this._timerManager);

View File

@@ -10,10 +10,16 @@ import { Int32 } from './Core/SoAStorage';
* @en Components in ECS architecture should be pure data containers.
* All game logic should be implemented in EntitySystem, not inside components.
*
* @zh **重要:所有 Component 子类都必须使用 @ECSComponent 装饰器!**
* @zh 该装饰器用于注册组件类型名称,是序列化、网络同步等功能正常工作的前提。
* @en **IMPORTANT: All Component subclasses MUST use the @ECSComponent decorator!**
* @en This decorator registers the component type name, which is required for serialization, network sync, etc.
*
* @example
* @zh 推荐做法:纯数据组件
* @en Recommended: Pure data component
* @zh 正确做法:使用 @ECSComponent 装饰器
* @en Correct: Use @ECSComponent decorator
* ```typescript
* @ECSComponent('HealthComponent')
* class HealthComponent extends Component {
* public health: number = 100;
* public maxHealth: number = 100;

View File

@@ -0,0 +1,188 @@
/**
* @zh 运行时环境装饰器
* @en Runtime Environment Decorators
*
* @zh 提供 @ServerOnly 和 @ClientOnly 装饰器,用于标记只在特定环境执行的方法
* @en Provides @ServerOnly and @ClientOnly decorators to mark methods that only execute in specific environments
*/
import type { EntitySystem } from '../Systems/EntitySystem';
/**
* @zh 服务端专用方法装饰器
* @en Server-only method decorator
*
* @zh 被装饰的方法只会在服务端环境执行scene.isServer === true
* 在客户端或单机模式下,方法调用会被静默跳过。
*
* @en Decorated methods only execute in server environment (scene.isServer === true).
* In client or standalone mode, method calls are silently skipped.
*
* @example
* ```typescript
* class CollectibleSpawnSystem extends EntitySystem {
* @ServerOnly()
* private checkCollections(players: readonly Entity[]): void {
* // 只在服务端执行收集检测
* // Only check collections on server
* for (const entity of this.scene.entities.buffer) {
* // ...
* }
* }
* }
* ```
*/
export function ServerOnly(): MethodDecorator {
return function <T>(
_target: object,
_propertyKey: string | symbol,
descriptor: TypedPropertyDescriptor<T>
): TypedPropertyDescriptor<T> | void {
const originalMethod = descriptor.value as unknown as (...args: unknown[]) => unknown;
if (typeof originalMethod !== 'function') {
throw new Error(`@ServerOnly can only be applied to methods, not ${typeof originalMethod}`);
}
descriptor.value = function (this: EntitySystem, ...args: unknown[]): unknown {
if (!this.scene?.isServer) {
return undefined;
}
return originalMethod.apply(this, args);
} as unknown as T;
return descriptor;
};
}
/**
* @zh 客户端专用方法装饰器
* @en Client-only method decorator
*
* @zh 被装饰的方法只会在客户端环境执行scene.isClient === true
* 在服务端或单机模式下,方法调用会被静默跳过。
*
* @en Decorated methods only execute in client environment (scene.isClient === true).
* In server or standalone mode, method calls are silently skipped.
*
* @example
* ```typescript
* class RenderSystem extends EntitySystem {
* @ClientOnly()
* private updateVisuals(): void {
* // 只在客户端执行渲染逻辑
* // Only update visuals on client
* }
* }
* ```
*/
export function ClientOnly(): MethodDecorator {
return function <T>(
_target: object,
_propertyKey: string | symbol,
descriptor: TypedPropertyDescriptor<T>
): TypedPropertyDescriptor<T> | void {
const originalMethod = descriptor.value as unknown as (...args: unknown[]) => unknown;
if (typeof originalMethod !== 'function') {
throw new Error(`@ClientOnly can only be applied to methods, not ${typeof originalMethod}`);
}
descriptor.value = function (this: EntitySystem, ...args: unknown[]): unknown {
if (!this.scene?.isClient) {
return undefined;
}
return originalMethod.apply(this, args);
} as unknown as T;
return descriptor;
};
}
/**
* @zh 非客户端环境方法装饰器
* @en Non-client method decorator
*
* @zh 被装饰的方法在服务端和单机模式下执行,但不在客户端执行。
* 用于需要在服务端和单机都运行,但客户端跳过的逻辑。
*
* @en Decorated methods execute in server and standalone mode, but not on client.
* Used for logic that should run on server and standalone, but skip on client.
*
* @example
* ```typescript
* class SpawnSystem extends EntitySystem {
* @NotClient()
* private spawnEntities(): void {
* // 服务端和单机模式执行,客户端跳过
* // Execute on server and standalone, skip on client
* }
* }
* ```
*/
export function NotClient(): MethodDecorator {
return function <T>(
_target: object,
_propertyKey: string | symbol,
descriptor: TypedPropertyDescriptor<T>
): TypedPropertyDescriptor<T> | void {
const originalMethod = descriptor.value as unknown as (...args: unknown[]) => unknown;
if (typeof originalMethod !== 'function') {
throw new Error(`@NotClient can only be applied to methods, not ${typeof originalMethod}`);
}
descriptor.value = function (this: EntitySystem, ...args: unknown[]): unknown {
if (this.scene?.isClient) {
return undefined;
}
return originalMethod.apply(this, args);
} as unknown as T;
return descriptor;
};
}
/**
* @zh 非服务端环境方法装饰器
* @en Non-server method decorator
*
* @zh 被装饰的方法在客户端和单机模式下执行,但不在服务端执行。
* 用于需要在客户端和单机都运行,但服务端跳过的逻辑(如渲染、音效)。
*
* @en Decorated methods execute in client and standalone mode, but not on server.
* Used for logic that should run on client and standalone, but skip on server (like rendering, audio).
*
* @example
* ```typescript
* class AudioSystem extends EntitySystem {
* @NotServer()
* private playSound(): void {
* // 客户端和单机模式执行,服务端跳过
* // Execute on client and standalone, skip on server
* }
* }
* ```
*/
export function NotServer(): MethodDecorator {
return function <T>(
_target: object,
_propertyKey: string | symbol,
descriptor: TypedPropertyDescriptor<T>
): TypedPropertyDescriptor<T> | void {
const originalMethod = descriptor.value as unknown as (...args: unknown[]) => unknown;
if (typeof originalMethod !== 'function') {
throw new Error(`@NotServer can only be applied to methods, not ${typeof originalMethod}`);
}
descriptor.value = function (this: EntitySystem, ...args: unknown[]): unknown {
if (this.scene?.isServer) {
return undefined;
}
return originalMethod.apply(this, args);
} as unknown as T;
return descriptor;
};
}

View File

@@ -19,6 +19,7 @@ import {
type ComponentEditorOptions,
type ComponentType
} from '../Core/ComponentStorage/ComponentTypeUtils';
import { SYNC_METADATA, type SyncMetadata } from '../Sync/types';
/**
* 存储系统类型名称的Symbol键
@@ -138,6 +139,14 @@ export function ECSComponent(typeName: string, options?: ComponentOptions) {
metadata[COMPONENT_EDITOR_OPTIONS] = options.editor;
}
// 更新 @sync 装饰器创建的 SYNC_METADATA.typeId如果存在
// Update SYNC_METADATA.typeId created by @sync decorator (if exists)
// Property decorators execute before class decorators, so @sync may have used constructor.name
const syncMeta = (target as any)[SYNC_METADATA] as SyncMetadata | undefined;
if (syncMeta) {
syncMeta.typeId = typeName;
}
// 自动注册到全局 ComponentRegistry使组件可以通过名称查找
// Auto-register to GlobalComponentRegistry, enabling lookup by name
GlobalComponentRegistry.register(target);

View File

@@ -82,3 +82,14 @@ export {
hasSchedulingMetadata,
SCHEDULING_METADATA
} from './SystemScheduling';
// ============================================================================
// Runtime Environment Decorators
// 运行时环境装饰器
// ============================================================================
export {
ServerOnly,
ClientOnly,
NotServer,
NotClient
} from './RuntimeEnvironment';

View File

@@ -7,14 +7,7 @@ import { getComponentInstanceTypeName, getComponentTypeName } from './Decorators
import { generateGUID } from '../Utils/GUID';
import type { IScene } from './IScene';
import { EntityHandle, NULL_HANDLE } from './Core/EntityHandle';
/**
* @zh 组件活跃状态变化接口
* @en Interface for component active state change
*/
interface IActiveChangeable {
onActiveChanged(): void;
}
import { ECSEventType } from './CoreEvents';
/**
* @zh 比较两个实体的优先级
@@ -482,9 +475,10 @@ export class Entity {
}
if (this.scene.eventSystem) {
this.scene.eventSystem.emitSync('component:added', {
this.scene.eventSystem.emitSync(ECSEventType.COMPONENT_ADDED, {
timestamp: Date.now(),
source: 'Entity',
entity: this,
entityId: this.id,
entityName: this.name,
entityTag: this.tag?.toString(),
@@ -639,7 +633,7 @@ export class Entity {
component.entityId = null;
if (this.scene?.eventSystem) {
this.scene.eventSystem.emitSync('component:removed', {
this.scene.eventSystem.emitSync(ECSEventType.COMPONENT_REMOVED, {
timestamp: Date.now(),
source: 'Entity',
entityId: this.id,
@@ -770,19 +764,23 @@ export class Entity {
}
/**
* 活跃状态改变时的回调
* @zh 活跃状态改变时的回调
* @en Callback when active state changes
*
* @zh 通过事件系统发出 ENTITY_ENABLED 或 ENTITY_DISABLED 事件,
* 组件可以通过监听这些事件来响应实体状态变化。
* @en Emits ENTITY_ENABLED or ENTITY_DISABLED event through the event system.
* Components can listen to these events to respond to entity state changes.
*/
private onActiveChanged(): void {
for (const component of this.components) {
if ('onActiveChanged' in component && typeof component.onActiveChanged === 'function') {
(component as IActiveChangeable).onActiveChanged();
}
}
if (this.scene?.eventSystem) {
const eventType = this._active
? ECSEventType.ENTITY_ENABLED
: ECSEventType.ENTITY_DISABLED;
if (this.scene && this.scene.eventSystem) {
this.scene.eventSystem.emitSync('entity:activeChanged', {
this.scene.eventSystem.emitSync(eventType, {
entity: this,
active: this._active
scene: this.scene,
});
}
}
@@ -801,6 +799,15 @@ export class Entity {
this._isDestroyed = true;
// 在清理之前发出销毁事件(组件仍然可访问)
if (this.scene?.eventSystem) {
this.scene.eventSystem.emitSync(ECSEventType.ENTITY_DESTROYED, {
entity: this,
entityId: this.id,
scene: this.scene,
});
}
if (this.scene && this.scene.referenceTracker) {
this.scene.referenceTracker.clearReferencesTo(this.id);
this.scene.referenceTracker.unregisterEntityScene(this.id);

View File

@@ -12,6 +12,10 @@ import type { ServiceContainer, ServiceType } from '../Core/ServiceContainer';
import type { TypedQueryBuilder } from './Core/Query/TypedQuery';
import type { SceneSerializationOptions, SceneDeserializationOptions } from './Serialization/SceneSerializer';
import type { IncrementalSnapshot, IncrementalSerializationOptions } from './Serialization/IncrementalSerializer';
import type { RuntimeEnvironment } from '../Types';
// Re-export for convenience
export type { RuntimeEnvironment };
/**
* 场景接口定义
@@ -113,6 +117,27 @@ export type IScene = {
*/
isEditorMode: boolean;
/**
* @zh 运行时环境
* @en Runtime environment
*
* @zh 标识场景运行在服务端、客户端还是单机模式
* @en Indicates whether scene runs on server, client, or standalone mode
*/
readonly runtimeEnvironment: RuntimeEnvironment;
/**
* @zh 是否在服务端运行
* @en Whether running on server
*/
readonly isServer: boolean;
/**
* @zh 是否在客户端运行
* @en Whether running on client
*/
readonly isClient: boolean;
/**
* 获取系统列表
*/
@@ -395,4 +420,18 @@ export type ISceneConfig = {
* @default 10
*/
maxSystemErrorCount?: number;
/**
* @zh 运行时环境
* @en Runtime environment
*
* @zh 用于区分场景运行在服务端、客户端还是单机模式。
* 配合 @ServerOnly / @ClientOnly 装饰器使用,可以让系统方法只在特定环境执行。
*
* @en Used to distinguish whether scene runs on server, client, or standalone mode.
* Works with @ServerOnly / @ClientOnly decorators to make system methods execute only in specific environments.
*
* @default 'standalone'
*/
runtimeEnvironment?: RuntimeEnvironment;
}

View File

@@ -12,7 +12,8 @@ import type { IComponentRegistry } from './Core/ComponentStorage';
import { QuerySystem } from './Core/QuerySystem';
import { TypeSafeEventSystem } from './Core/EventSystem';
import { ReferenceTracker } from './Core/ReferenceTracker';
import { IScene, ISceneConfig } from './IScene';
import { IScene, ISceneConfig, RuntimeEnvironment } from './IScene';
import { RuntimeConfig } from '../RuntimeConfig';
import { getComponentInstanceTypeName, getSystemInstanceTypeName, getSystemMetadata, getSystemInstanceMetadata } from './Decorators';
import { TypedQueryBuilder } from './Core/Query/TypedQuery';
import {
@@ -180,6 +181,45 @@ export class Scene implements IScene {
*/
public isEditorMode: boolean = false;
/**
* @zh 场景级别的运行时环境覆盖
* @en Scene-level runtime environment override
*
* @zh 如果未设置,则从 Core.runtimeEnvironment 读取
* @en If not set, reads from Core.runtimeEnvironment
*/
private _runtimeEnvironmentOverride: RuntimeEnvironment | undefined;
/**
* @zh 获取运行时环境
* @en Get runtime environment
*
* @zh 优先返回场景级别设置,否则返回 Core 全局设置
* @en Returns scene-level setting if set, otherwise returns Core global setting
*/
public get runtimeEnvironment(): RuntimeEnvironment {
if (this._runtimeEnvironmentOverride) {
return this._runtimeEnvironmentOverride;
}
return RuntimeConfig.runtimeEnvironment;
}
/**
* @zh 是否在服务端运行
* @en Whether running on server
*/
public get isServer(): boolean {
return this.runtimeEnvironment === 'server';
}
/**
* @zh 是否在客户端运行
* @en Whether running on client
*/
public get isClient(): boolean {
return this.runtimeEnvironment === 'client';
}
/**
* 延迟的组件生命周期回调队列
*
@@ -398,6 +438,11 @@ export class Scene implements IScene {
this._logger = createLogger('Scene');
this._maxErrorCount = config?.maxSystemErrorCount ?? 10;
// 只有显式指定时才覆盖,否则从 Core 读取
if (config?.runtimeEnvironment) {
this._runtimeEnvironmentOverride = config.runtimeEnvironment;
}
if (config?.name) {
this.name = config.name;
}
@@ -508,7 +553,9 @@ export class Scene implements IScene {
}
/**
* 更新场景
* @zh 更新场景
* @en Update scene
* @internal 由 SceneManager 或 World 调用,用户不应直接调用
*/
public update() {
this.epochManager.increment();

View File

@@ -240,18 +240,9 @@ export class SceneManager implements IService {
}
/**
* 更新场景
*
* 应该在每帧的游戏循环中调用
* 会自动处理延迟场景切换。
*
* @example
* ```typescript
* function gameLoop(deltaTime: number) {
* Core.update(deltaTime);
* sceneManager.update(); // 每帧调用
* }
* ```
* @zh 更新场景
* @en Update scene
* @internal 由 Core.update() 调用,用户不应直接调用
*/
public update(): void {
// 处理延迟场景切换

View File

@@ -0,0 +1,125 @@
/**
* @zh 组件变更追踪器
* @en Component change tracker
*
* @zh 用于追踪 @sync 标记字段的变更,支持增量同步
* @en Tracks changes to @sync marked fields for delta synchronization
*/
export class ChangeTracker {
/**
* @zh 脏字段索引集合
* @en Set of dirty field indices
*/
private _dirtyFields: Set<number> = new Set();
/**
* @zh 是否有任何变更
* @en Whether there are any changes
*/
private _hasChanges: boolean = false;
/**
* @zh 上次同步的时间戳
* @en Last sync timestamp
*/
private _lastSyncTime: number = 0;
/**
* @zh 标记字段为脏
* @en Mark field as dirty
*
* @param fieldIndex - @zh 字段索引 @en Field index
*/
public setDirty(fieldIndex: number): void {
this._dirtyFields.add(fieldIndex);
this._hasChanges = true;
}
/**
* @zh 检查是否有变更
* @en Check if there are any changes
*/
public hasChanges(): boolean {
return this._hasChanges;
}
/**
* @zh 检查特定字段是否脏
* @en Check if a specific field is dirty
*
* @param fieldIndex - @zh 字段索引 @en Field index
*/
public isDirty(fieldIndex: number): boolean {
return this._dirtyFields.has(fieldIndex);
}
/**
* @zh 获取所有脏字段索引
* @en Get all dirty field indices
*/
public getDirtyFields(): number[] {
return Array.from(this._dirtyFields);
}
/**
* @zh 获取脏字段数量
* @en Get number of dirty fields
*/
public getDirtyCount(): number {
return this._dirtyFields.size;
}
/**
* @zh 清除所有变更标记
* @en Clear all change marks
*/
public clear(): void {
this._dirtyFields.clear();
this._hasChanges = false;
this._lastSyncTime = Date.now();
}
/**
* @zh 清除特定字段的变更标记
* @en Clear change mark for a specific field
*
* @param fieldIndex - @zh 字段索引 @en Field index
*/
public clearField(fieldIndex: number): void {
this._dirtyFields.delete(fieldIndex);
if (this._dirtyFields.size === 0) {
this._hasChanges = false;
}
}
/**
* @zh 获取上次同步时间
* @en Get last sync time
*/
public get lastSyncTime(): number {
return this._lastSyncTime;
}
/**
* @zh 标记所有字段为脏(用于首次同步)
* @en Mark all fields as dirty (for initial sync)
*
* @param fieldCount - @zh 字段数量 @en Field count
*/
public markAllDirty(fieldCount: number): void {
for (let i = 0; i < fieldCount; i++) {
this._dirtyFields.add(i);
}
this._hasChanges = fieldCount > 0;
}
/**
* @zh 重置追踪器
* @en Reset tracker
*/
public reset(): void {
this._dirtyFields.clear();
this._hasChanges = false;
this._lastSyncTime = 0;
}
}

View File

@@ -0,0 +1,147 @@
/**
* @zh 网络实体装饰器
* @en Network entity decorator
*
* @zh 提供 @NetworkEntity 装饰器,用于标记需要自动广播生成/销毁的组件
* @en Provides @NetworkEntity decorator to mark components for automatic spawn/despawn broadcasting
*/
/**
* @zh 网络实体元数据的 Symbol 键
* @en Symbol key for network entity metadata
*/
export const NETWORK_ENTITY_METADATA = Symbol('NetworkEntityMetadata');
/**
* @zh 网络实体元数据
* @en Network entity metadata
*/
export interface NetworkEntityMetadata {
/**
* @zh 预制体类型名称(用于客户端重建实体)
* @en Prefab type name (used by client to reconstruct entity)
*/
prefabType: string;
/**
* @zh 是否自动广播生成
* @en Whether to auto-broadcast spawn
* @default true
*/
autoSpawn: boolean;
/**
* @zh 是否自动广播销毁
* @en Whether to auto-broadcast despawn
* @default true
*/
autoDespawn: boolean;
}
/**
* @zh 网络实体装饰器配置选项
* @en Network entity decorator options
*/
export interface NetworkEntityOptions {
/**
* @zh 是否自动广播生成
* @en Whether to auto-broadcast spawn
* @default true
*/
autoSpawn?: boolean;
/**
* @zh 是否自动广播销毁
* @en Whether to auto-broadcast despawn
* @default true
*/
autoDespawn?: boolean;
}
/**
* @zh 网络实体装饰器
* @en Network entity decorator
*
* @zh 标记组件类为网络实体。当包含此组件的实体被创建或销毁时,
* ECSRoom 会自动广播相应的 spawn/despawn 消息给所有客户端。
* @en Marks a component class as a network entity. When an entity containing
* this component is created or destroyed, ECSRoom will automatically broadcast
* the corresponding spawn/despawn messages to all clients.
*
* @param prefabType - @zh 预制体类型名称 @en Prefab type name
* @param options - @zh 可选配置 @en Optional configuration
*
* @example
* ```typescript
* import { Component, ECSComponent, NetworkEntity, sync } from '@esengine/ecs-framework';
*
* @ECSComponent('Enemy')
* @NetworkEntity('Enemy')
* class EnemyComponent extends Component {
* @sync('float32') x: number = 0;
* @sync('float32') y: number = 0;
* @sync('uint16') health: number = 100;
* }
*
* // 当添加此组件到实体时ECSRoom 会自动广播 spawn
* const enemy = scene.createEntity('Enemy');
* enemy.addComponent(new EnemyComponent()); // 自动广播给所有客户端
*
* // 当实体销毁时,自动广播 despawn
* enemy.destroy(); // 自动广播给所有客户端
* ```
*
* @example
* ```typescript
* // 只自动广播生成,销毁由手动控制
* @ECSComponent('Bullet')
* @NetworkEntity('Bullet', { autoDespawn: false })
* class BulletComponent extends Component {
* @sync('float32') x: number = 0;
* @sync('float32') y: number = 0;
* }
* ```
*/
export function NetworkEntity(prefabType: string, options?: NetworkEntityOptions) {
return function <T extends new (...args: any[]) => any>(target: T): T {
const metadata: NetworkEntityMetadata = {
prefabType,
autoSpawn: options?.autoSpawn ?? true,
autoDespawn: options?.autoDespawn ?? true,
};
(target as any)[NETWORK_ENTITY_METADATA] = metadata;
return target;
};
}
/**
* @zh 获取组件类的网络实体元数据
* @en Get network entity metadata for a component class
*
* @param componentClass - @zh 组件类或组件实例 @en Component class or instance
* @returns @zh 网络实体元数据,如果不存在则返回 null @en Network entity metadata, or null if not exists
*/
export function getNetworkEntityMetadata(componentClass: any): NetworkEntityMetadata | null {
if (!componentClass) {
return null;
}
const constructor = typeof componentClass === 'function'
? componentClass
: componentClass.constructor;
return constructor[NETWORK_ENTITY_METADATA] || null;
}
/**
* @zh 检查组件是否标记为网络实体
* @en Check if a component is marked as a network entity
*
* @param component - @zh 组件类或组件实例 @en Component class or instance
* @returns @zh 如果是网络实体返回 true @en Returns true if is a network entity
*/
export function isNetworkEntity(component: any): boolean {
return getNetworkEntityMetadata(component) !== null;
}

View File

@@ -0,0 +1,219 @@
/**
* @zh 网络同步装饰器
* @en Network synchronization decorators
*
* @zh 提供 @sync 装饰器,用于标记需要网络同步的 Component 字段
* @en Provides @sync decorator to mark Component fields for network synchronization
*/
import type { SyncType, SyncFieldMetadata, SyncMetadata } from './types';
import { SYNC_METADATA, CHANGE_TRACKER } from './types';
import { ChangeTracker } from './ChangeTracker';
import { getComponentTypeName } from '../Core/ComponentStorage/ComponentTypeUtils';
/**
* @zh 获取或创建组件的同步元数据
* @en Get or create sync metadata for a component class
*
* @param target - @zh 组件类的原型 @en Component class prototype
* @returns @zh 同步元数据 @en Sync metadata
*/
function getOrCreateSyncMetadata(target: any): SyncMetadata {
const constructor = target.constructor;
// Check if has own metadata (not inherited)
const hasOwnMetadata = Object.prototype.hasOwnProperty.call(constructor, SYNC_METADATA);
if (hasOwnMetadata) {
return constructor[SYNC_METADATA];
}
// Check for inherited metadata
const inheritedMetadata: SyncMetadata | undefined = constructor[SYNC_METADATA];
// Create new metadata (copy from inherited if exists)
// Use getComponentTypeName to get @ECSComponent decorator name, or fall back to constructor.name
const metadata: SyncMetadata = {
typeId: getComponentTypeName(constructor),
fields: inheritedMetadata ? [...inheritedMetadata.fields] : [],
fieldIndexMap: inheritedMetadata ? new Map(inheritedMetadata.fieldIndexMap) : new Map()
};
constructor[SYNC_METADATA] = metadata;
return metadata;
}
/**
* @zh 同步字段装饰器
* @en Sync field decorator
*
* @zh 标记 Component 字段为可网络同步。被标记的字段会自动追踪变更,
* 并在值修改时触发变更追踪器。
* @en Marks a Component field for network synchronization. Marked fields
* automatically track changes and trigger the change tracker on modification.
*
* @param type - @zh 字段的同步类型 @en Sync type of the field
*
* @example
* ```typescript
* import { Component, ECSComponent } from '@esengine/ecs-framework';
* import { sync } from '@esengine/ecs-framework';
*
* @ECSComponent('Player')
* class PlayerComponent extends Component {
* @sync("string") name: string = "";
* @sync("uint16") score: number = 0;
* @sync("float32") x: number = 0;
* @sync("float32") y: number = 0;
*
* // 不带 @sync 的字段不会同步
* // Fields without @sync will not be synchronized
* localData: any;
* }
* ```
*/
export function sync(type: SyncType) {
return function (target: any, propertyKey: string) {
const metadata = getOrCreateSyncMetadata(target);
// Assign field index (auto-increment based on field count)
const fieldIndex = metadata.fields.length;
// Create field metadata
const fieldMeta: SyncFieldMetadata = {
index: fieldIndex,
name: propertyKey,
type: type
};
// Register field
metadata.fields.push(fieldMeta);
metadata.fieldIndexMap.set(propertyKey, fieldIndex);
// Store original property key for getter/setter
const privateKey = `_sync_${propertyKey}`;
// Define getter/setter to intercept value changes
Object.defineProperty(target, propertyKey, {
get() {
return this[privateKey];
},
set(value: any) {
const oldValue = this[privateKey];
if (oldValue !== value) {
this[privateKey] = value;
// Trigger change tracker if exists
const tracker = this[CHANGE_TRACKER] as ChangeTracker | undefined;
if (tracker) {
tracker.setDirty(fieldIndex);
}
}
},
enumerable: true,
configurable: true
});
};
}
/**
* @zh 获取组件类的同步元数据
* @en Get sync metadata for a component class
*
* @param componentClass - @zh 组件类或组件实例 @en Component class or instance
* @returns @zh 同步元数据,如果不存在则返回 null @en Sync metadata, or null if not exists
*/
export function getSyncMetadata(componentClass: any): SyncMetadata | null {
if (!componentClass) {
return null;
}
const constructor = typeof componentClass === 'function'
? componentClass
: componentClass.constructor;
return constructor[SYNC_METADATA] || null;
}
/**
* @zh 检查组件是否有同步字段
* @en Check if a component has sync fields
*
* @param component - @zh 组件类或组件实例 @en Component class or instance
* @returns @zh 如果有同步字段返回 true @en Returns true if has sync fields
*/
export function hasSyncFields(component: any): boolean {
const metadata = getSyncMetadata(component);
return metadata !== null && metadata.fields.length > 0;
}
/**
* @zh 获取组件实例的变更追踪器
* @en Get change tracker of a component instance
*
* @param component - @zh 组件实例 @en Component instance
* @returns @zh 变更追踪器,如果不存在则返回 null @en Change tracker, or null if not exists
*/
export function getChangeTracker(component: any): ChangeTracker | null {
if (!component) {
return null;
}
return component[CHANGE_TRACKER] || null;
}
/**
* @zh 为组件实例初始化变更追踪器
* @en Initialize change tracker for a component instance
*
* @zh 这个函数应该在组件首次添加到实体时调用。
* 它会创建变更追踪器并标记所有字段为脏(用于首次同步)。
* @en This function should be called when a component is first added to an entity.
* It creates the change tracker and marks all fields as dirty (for initial sync).
*
* @param component - @zh 组件实例 @en Component instance
* @returns @zh 变更追踪器 @en Change tracker
*/
export function initChangeTracker(component: any): ChangeTracker {
const metadata = getSyncMetadata(component);
if (!metadata) {
throw new Error('Component does not have sync metadata. Use @sync decorator on fields.');
}
let tracker = component[CHANGE_TRACKER] as ChangeTracker | undefined;
if (!tracker) {
tracker = new ChangeTracker();
component[CHANGE_TRACKER] = tracker;
}
// Mark all fields as dirty for initial sync
tracker.markAllDirty(metadata.fields.length);
return tracker;
}
/**
* @zh 清除组件实例的变更标记
* @en Clear change marks for a component instance
*
* @zh 通常在同步完成后调用,清除所有脏标记
* @en Usually called after sync is complete, clears all dirty marks
*
* @param component - @zh 组件实例 @en Component instance
*/
export function clearChanges(component: any): void {
const tracker = getChangeTracker(component);
if (tracker) {
tracker.clear();
}
}
/**
* @zh 检查组件是否有变更
* @en Check if a component has changes
*
* @param component - @zh 组件实例 @en Component instance
* @returns @zh 如果有变更返回 true @en Returns true if has changes
*/
export function hasChanges(component: any): boolean {
const tracker = getChangeTracker(component);
return tracker ? tracker.hasChanges() : false;
}

View File

@@ -0,0 +1,285 @@
/**
* @zh 二进制读取器
* @en Binary Reader
*
* @zh 提供高效的二进制数据读取功能
* @en Provides efficient binary data reading
*/
import { decodeVarint } from './varint';
/**
* @zh 文本解码器(使用浏览器原生 API
* @en Text decoder (using browser native API)
*/
const textDecoder = typeof TextDecoder !== 'undefined' ? new TextDecoder() : null;
/**
* @zh 二进制读取器
* @en Binary reader for decoding data
*/
export class BinaryReader {
/**
* @zh 数据缓冲区
* @en Data buffer
*/
private _buffer: Uint8Array;
/**
* @zh DataView 用于读取数值
* @en DataView for reading numbers
*/
private _view: DataView;
/**
* @zh 当前读取位置
* @en Current read position
*/
private _offset: number = 0;
/**
* @zh 创建二进制读取器
* @en Create binary reader
*
* @param buffer - @zh 要读取的数据 @en Data to read
*/
constructor(buffer: Uint8Array) {
this._buffer = buffer;
this._view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
}
/**
* @zh 获取当前读取位置
* @en Get current read position
*/
public get offset(): number {
return this._offset;
}
/**
* @zh 设置读取位置
* @en Set read position
*/
public set offset(value: number) {
this._offset = value;
}
/**
* @zh 获取剩余可读字节数
* @en Get remaining readable bytes
*/
public get remaining(): number {
return this._buffer.length - this._offset;
}
/**
* @zh 检查是否有更多数据可读
* @en Check if there's more data to read
*/
public hasMore(): boolean {
return this._offset < this._buffer.length;
}
/**
* @zh 读取单个字节
* @en Read single byte
*/
public readUint8(): number {
this.checkBounds(1);
return this._buffer[this._offset++]!;
}
/**
* @zh 读取有符号字节
* @en Read signed byte
*/
public readInt8(): number {
this.checkBounds(1);
return this._view.getInt8(this._offset++);
}
/**
* @zh 读取布尔值
* @en Read boolean
*/
public readBoolean(): boolean {
return this.readUint8() !== 0;
}
/**
* @zh 读取 16 位无符号整数(小端序)
* @en Read 16-bit unsigned integer (little-endian)
*/
public readUint16(): number {
this.checkBounds(2);
const value = this._view.getUint16(this._offset, true);
this._offset += 2;
return value;
}
/**
* @zh 读取 16 位有符号整数(小端序)
* @en Read 16-bit signed integer (little-endian)
*/
public readInt16(): number {
this.checkBounds(2);
const value = this._view.getInt16(this._offset, true);
this._offset += 2;
return value;
}
/**
* @zh 读取 32 位无符号整数(小端序)
* @en Read 32-bit unsigned integer (little-endian)
*/
public readUint32(): number {
this.checkBounds(4);
const value = this._view.getUint32(this._offset, true);
this._offset += 4;
return value;
}
/**
* @zh 读取 32 位有符号整数(小端序)
* @en Read 32-bit signed integer (little-endian)
*/
public readInt32(): number {
this.checkBounds(4);
const value = this._view.getInt32(this._offset, true);
this._offset += 4;
return value;
}
/**
* @zh 读取 32 位浮点数(小端序)
* @en Read 32-bit float (little-endian)
*/
public readFloat32(): number {
this.checkBounds(4);
const value = this._view.getFloat32(this._offset, true);
this._offset += 4;
return value;
}
/**
* @zh 读取 64 位浮点数(小端序)
* @en Read 64-bit float (little-endian)
*/
public readFloat64(): number {
this.checkBounds(8);
const value = this._view.getFloat64(this._offset, true);
this._offset += 8;
return value;
}
/**
* @zh 读取变长整数
* @en Read variable-length integer
*/
public readVarint(): number {
const [value, newOffset] = decodeVarint(this._buffer, this._offset);
this._offset = newOffset;
return value;
}
/**
* @zh 读取字符串UTF-8 编码,带长度前缀)
* @en Read string (UTF-8 encoded with length prefix)
*/
public readString(): string {
const length = this.readVarint();
this.checkBounds(length);
const bytes = this._buffer.subarray(this._offset, this._offset + length);
this._offset += length;
if (textDecoder) {
return textDecoder.decode(bytes);
} else {
return this.utf8BytesToString(bytes);
}
}
/**
* @zh 读取原始字节
* @en Read raw bytes
*
* @param length - @zh 要读取的字节数 @en Number of bytes to read
*/
public readBytes(length: number): Uint8Array {
this.checkBounds(length);
const bytes = this._buffer.slice(this._offset, this._offset + length);
this._offset += length;
return bytes;
}
/**
* @zh 查看下一个字节但不移动读取位置
* @en Peek next byte without advancing read position
*/
public peekUint8(): number {
this.checkBounds(1);
return this._buffer[this._offset]!;
}
/**
* @zh 跳过指定字节数
* @en Skip specified number of bytes
*/
public skip(count: number): void {
this.checkBounds(count);
this._offset += count;
}
/**
* @zh 检查边界
* @en Check bounds
*/
private checkBounds(size: number): void {
if (this._offset + size > this._buffer.length) {
throw new Error(`BinaryReader: buffer overflow (offset=${this._offset}, size=${size}, bufferLength=${this._buffer.length})`);
}
}
/**
* @zh UTF-8 字节转字符串(后备方案)
* @en UTF-8 bytes to string (fallback)
*/
private utf8BytesToString(bytes: Uint8Array): string {
let result = '';
let i = 0;
while (i < bytes.length) {
let charCode: number;
const byte1 = bytes[i++]!;
if (byte1 < 0x80) {
charCode = byte1;
} else if (byte1 < 0xE0) {
const byte2 = bytes[i++]!;
charCode = ((byte1 & 0x1F) << 6) | (byte2 & 0x3F);
} else if (byte1 < 0xF0) {
const byte2 = bytes[i++]!;
const byte3 = bytes[i++]!;
charCode = ((byte1 & 0x0F) << 12) | ((byte2 & 0x3F) << 6) | (byte3 & 0x3F);
} else {
const byte2 = bytes[i++]!;
const byte3 = bytes[i++]!;
const byte4 = bytes[i++]!;
charCode = ((byte1 & 0x07) << 18) | ((byte2 & 0x3F) << 12) |
((byte3 & 0x3F) << 6) | (byte4 & 0x3F);
// Convert to surrogate pair
if (charCode > 0xFFFF) {
charCode -= 0x10000;
result += String.fromCharCode(0xD800 + (charCode >> 10));
charCode = 0xDC00 + (charCode & 0x3FF);
}
}
result += String.fromCharCode(charCode);
}
return result;
}
}

View File

@@ -0,0 +1,257 @@
/**
* @zh 二进制写入器
* @en Binary Writer
*
* @zh 提供高效的二进制数据写入功能,支持自动扩容
* @en Provides efficient binary data writing with auto-expansion
*/
import { encodeVarint, varintSize } from './varint';
/**
* @zh 文本编码器(使用浏览器原生 API
* @en Text encoder (using browser native API)
*/
const textEncoder = typeof TextEncoder !== 'undefined' ? new TextEncoder() : null;
/**
* @zh 二进制写入器
* @en Binary writer for encoding data
*/
export class BinaryWriter {
/**
* @zh 内部缓冲区
* @en Internal buffer
*/
private _buffer: Uint8Array;
/**
* @zh DataView 用于写入数值
* @en DataView for writing numbers
*/
private _view: DataView;
/**
* @zh 当前写入位置
* @en Current write position
*/
private _offset: number = 0;
/**
* @zh 创建二进制写入器
* @en Create binary writer
*
* @param initialCapacity - @zh 初始容量 @en Initial capacity
*/
constructor(initialCapacity: number = 256) {
this._buffer = new Uint8Array(initialCapacity);
this._view = new DataView(this._buffer.buffer);
}
/**
* @zh 获取当前写入位置
* @en Get current write position
*/
public get offset(): number {
return this._offset;
}
/**
* @zh 获取写入的数据
* @en Get written data
*
* @returns @zh 包含写入数据的 Uint8Array @en Uint8Array containing written data
*/
public toUint8Array(): Uint8Array {
return this._buffer.slice(0, this._offset);
}
/**
* @zh 重置写入器(清空数据但保留缓冲区)
* @en Reset writer (clear data but keep buffer)
*/
public reset(): void {
this._offset = 0;
}
/**
* @zh 确保有足够空间
* @en Ensure enough space
*
* @param size - @zh 需要的额外字节数 @en Extra bytes needed
*/
private ensureCapacity(size: number): void {
const required = this._offset + size;
if (required > this._buffer.length) {
// Double the buffer size or use required size, whichever is larger
const newSize = Math.max(this._buffer.length * 2, required);
const newBuffer = new Uint8Array(newSize);
newBuffer.set(this._buffer);
this._buffer = newBuffer;
this._view = new DataView(this._buffer.buffer);
}
}
/**
* @zh 写入单个字节
* @en Write single byte
*/
public writeUint8(value: number): void {
this.ensureCapacity(1);
this._buffer[this._offset++] = value;
}
/**
* @zh 写入有符号字节
* @en Write signed byte
*/
public writeInt8(value: number): void {
this.ensureCapacity(1);
this._view.setInt8(this._offset++, value);
}
/**
* @zh 写入布尔值
* @en Write boolean
*/
public writeBoolean(value: boolean): void {
this.writeUint8(value ? 1 : 0);
}
/**
* @zh 写入 16 位无符号整数(小端序)
* @en Write 16-bit unsigned integer (little-endian)
*/
public writeUint16(value: number): void {
this.ensureCapacity(2);
this._view.setUint16(this._offset, value, true);
this._offset += 2;
}
/**
* @zh 写入 16 位有符号整数(小端序)
* @en Write 16-bit signed integer (little-endian)
*/
public writeInt16(value: number): void {
this.ensureCapacity(2);
this._view.setInt16(this._offset, value, true);
this._offset += 2;
}
/**
* @zh 写入 32 位无符号整数(小端序)
* @en Write 32-bit unsigned integer (little-endian)
*/
public writeUint32(value: number): void {
this.ensureCapacity(4);
this._view.setUint32(this._offset, value, true);
this._offset += 4;
}
/**
* @zh 写入 32 位有符号整数(小端序)
* @en Write 32-bit signed integer (little-endian)
*/
public writeInt32(value: number): void {
this.ensureCapacity(4);
this._view.setInt32(this._offset, value, true);
this._offset += 4;
}
/**
* @zh 写入 32 位浮点数(小端序)
* @en Write 32-bit float (little-endian)
*/
public writeFloat32(value: number): void {
this.ensureCapacity(4);
this._view.setFloat32(this._offset, value, true);
this._offset += 4;
}
/**
* @zh 写入 64 位浮点数(小端序)
* @en Write 64-bit float (little-endian)
*/
public writeFloat64(value: number): void {
this.ensureCapacity(8);
this._view.setFloat64(this._offset, value, true);
this._offset += 8;
}
/**
* @zh 写入变长整数
* @en Write variable-length integer
*/
public writeVarint(value: number): void {
this.ensureCapacity(varintSize(value));
this._offset = encodeVarint(value, this._buffer, this._offset);
}
/**
* @zh 写入字符串UTF-8 编码,带长度前缀)
* @en Write string (UTF-8 encoded with length prefix)
*/
public writeString(value: string): void {
if (textEncoder) {
const encoded = textEncoder.encode(value);
this.writeVarint(encoded.length);
this.ensureCapacity(encoded.length);
this._buffer.set(encoded, this._offset);
this._offset += encoded.length;
} else {
// Fallback for environments without TextEncoder
const bytes = this.stringToUtf8Bytes(value);
this.writeVarint(bytes.length);
this.ensureCapacity(bytes.length);
this._buffer.set(bytes, this._offset);
this._offset += bytes.length;
}
}
/**
* @zh 写入原始字节
* @en Write raw bytes
*/
public writeBytes(data: Uint8Array): void {
this.ensureCapacity(data.length);
this._buffer.set(data, this._offset);
this._offset += data.length;
}
/**
* @zh 字符串转 UTF-8 字节(后备方案)
* @en String to UTF-8 bytes (fallback)
*/
private stringToUtf8Bytes(str: string): Uint8Array {
const bytes: number[] = [];
for (let i = 0; i < str.length; i++) {
let charCode = str.charCodeAt(i);
// Handle surrogate pairs
if (charCode >= 0xD800 && charCode <= 0xDBFF && i + 1 < str.length) {
const next = str.charCodeAt(i + 1);
if (next >= 0xDC00 && next <= 0xDFFF) {
charCode = 0x10000 + ((charCode - 0xD800) << 10) + (next - 0xDC00);
i++;
}
}
if (charCode < 0x80) {
bytes.push(charCode);
} else if (charCode < 0x800) {
bytes.push(0xC0 | (charCode >> 6));
bytes.push(0x80 | (charCode & 0x3F));
} else if (charCode < 0x10000) {
bytes.push(0xE0 | (charCode >> 12));
bytes.push(0x80 | ((charCode >> 6) & 0x3F));
bytes.push(0x80 | (charCode & 0x3F));
} else {
bytes.push(0xF0 | (charCode >> 18));
bytes.push(0x80 | ((charCode >> 12) & 0x3F));
bytes.push(0x80 | ((charCode >> 6) & 0x3F));
bytes.push(0x80 | (charCode & 0x3F));
}
}
return new Uint8Array(bytes);
}
}

View File

@@ -0,0 +1,372 @@
/**
* @zh 组件状态解码器
* @en Component state decoder
*
* @zh 从二进制格式解码并应用到 ECS Component
* @en Decodes binary format and applies to ECS Components
*/
import type { Entity } from '../../Entity';
import type { Component } from '../../Component';
import type { Scene } from '../../Scene';
import type { SyncType, SyncMetadata } from '../types';
import { SyncOperation, SYNC_METADATA } from '../types';
import { BinaryReader } from './BinaryReader';
import { GlobalComponentRegistry } from '../../Core/ComponentStorage/ComponentRegistry';
/**
* @zh 解码字段值
* @en Decode field value
*/
function decodeFieldValue(reader: BinaryReader, type: SyncType): any {
switch (type) {
case 'boolean':
return reader.readBoolean();
case 'int8':
return reader.readInt8();
case 'uint8':
return reader.readUint8();
case 'int16':
return reader.readInt16();
case 'uint16':
return reader.readUint16();
case 'int32':
return reader.readInt32();
case 'uint32':
return reader.readUint32();
case 'float32':
return reader.readFloat32();
case 'float64':
return reader.readFloat64();
case 'string':
return reader.readString();
}
}
/**
* @zh 解码并应用组件数据
* @en Decode and apply component data
*
* @param component - @zh 组件实例 @en Component instance
* @param metadata - @zh 组件同步元数据 @en Component sync metadata
* @param reader - @zh 二进制读取器 @en Binary reader
*/
export function decodeComponent(
component: Component,
metadata: SyncMetadata,
reader: BinaryReader
): void {
const fieldCount = reader.readVarint();
for (let i = 0; i < fieldCount; i++) {
const fieldIndex = reader.readUint8();
const field = metadata.fields[fieldIndex];
if (field) {
const value = decodeFieldValue(reader, field.type);
// Directly set the private backing field to avoid triggering change tracking
(component as any)[`_sync_${field.name}`] = value;
} else {
// Unknown field, skip based on type info in metadata
console.warn(`Unknown sync field index: ${fieldIndex}`);
}
}
}
/**
* @zh 解码实体快照结果
* @en Decode entity snapshot result
*/
export interface DecodeEntityResult {
/**
* @zh 实体 ID
* @en Entity ID
*/
entityId: number;
/**
* @zh 是否为新实体
* @en Whether it's a new entity
*/
isNew: boolean;
/**
* @zh 解码的组件类型列表
* @en List of decoded component types
*/
componentTypes: string[];
}
/**
* @zh 解码并应用实体数据
* @en Decode and apply entity data
*
* @param scene - @zh 场景 @en Scene
* @param reader - @zh 二进制读取器 @en Binary reader
* @param entityMap - @zh 实体 ID 映射(可选)@en Entity ID mapping (optional)
* @returns @zh 解码结果 @en Decode result
*/
export function decodeEntity(
scene: Scene,
reader: BinaryReader,
entityMap?: Map<number, Entity>
): DecodeEntityResult {
const entityId = reader.readUint32();
const componentCount = reader.readVarint();
const componentTypes: string[] = [];
// Find or create entity
let entity: Entity | null | undefined = entityMap?.get(entityId);
let isNew = false;
if (!entity) {
entity = scene.findEntityById(entityId);
}
if (!entity) {
// Entity doesn't exist, create it
entity = scene.createEntity(`entity_${entityId}`);
isNew = true;
entityMap?.set(entityId, entity);
}
for (let i = 0; i < componentCount; i++) {
const typeId = reader.readString();
componentTypes.push(typeId);
// Find component class from GlobalComponentRegistry
const componentClass = GlobalComponentRegistry.getComponentType(typeId) as (new () => Component) | null;
if (!componentClass) {
console.warn(`Unknown component type: ${typeId}`);
// Skip component data - we need to read it to advance the reader
const fieldCount = reader.readVarint();
for (let j = 0; j < fieldCount; j++) {
reader.readUint8(); // fieldIndex
// We can't skip properly without knowing the type, so this is a problem
// For now, log error and break
console.error(`Cannot skip unknown component type: ${typeId}`);
break;
}
continue;
}
const metadata: SyncMetadata | undefined = (componentClass as any)[SYNC_METADATA];
if (!metadata) {
console.warn(`Component ${typeId} has no sync metadata`);
continue;
}
// Find or add component
let component = entity.getComponent(componentClass);
if (!component) {
component = entity.addComponent(new componentClass());
}
// Decode component data
decodeComponent(component, metadata, reader);
}
return { entityId, isNew, componentTypes };
}
/**
* @zh 解码快照结果
* @en Decode snapshot result
*/
export interface DecodeSnapshotResult {
/**
* @zh 操作类型
* @en Operation type
*/
operation: SyncOperation;
/**
* @zh 解码的实体列表
* @en List of decoded entities
*/
entities: DecodeEntityResult[];
}
/**
* @zh 解码状态快照
* @en Decode state snapshot
*
* @param scene - @zh 场景 @en Scene
* @param data - @zh 二进制数据 @en Binary data
* @param entityMap - @zh 实体 ID 映射(可选)@en Entity ID mapping (optional)
* @returns @zh 解码结果 @en Decode result
*/
export function decodeSnapshot(
scene: Scene,
data: Uint8Array,
entityMap?: Map<number, Entity>
): DecodeSnapshotResult {
const reader = new BinaryReader(data);
const operation = reader.readUint8() as SyncOperation;
const entityCount = reader.readVarint();
const entities: DecodeEntityResult[] = [];
const map = entityMap || new Map<number, Entity>();
for (let i = 0; i < entityCount; i++) {
const result = decodeEntity(scene, reader, map);
entities.push(result);
}
return { operation, entities };
}
/**
* @zh 解码生成消息结果
* @en Decode spawn message result
*/
export interface DecodeSpawnResult {
/**
* @zh 实体
* @en Entity
*/
entity: Entity;
/**
* @zh 预制体类型
* @en Prefab type
*/
prefabType: string;
/**
* @zh 解码的组件类型列表
* @en List of decoded component types
*/
componentTypes: string[];
}
/**
* @zh 解码实体生成消息
* @en Decode entity spawn message
*
* @param scene - @zh 场景 @en Scene
* @param data - @zh 二进制数据 @en Binary data
* @param entityMap - @zh 实体 ID 映射(可选)@en Entity ID mapping (optional)
* @returns @zh 解码结果,如果不是 SPAWN 消息则返回 null @en Decode result, or null if not a SPAWN message
*/
export function decodeSpawn(
scene: Scene,
data: Uint8Array,
entityMap?: Map<number, Entity>
): DecodeSpawnResult | null {
const reader = new BinaryReader(data);
const operation = reader.readUint8();
if (operation !== SyncOperation.SPAWN) {
return null;
}
const entityId = reader.readUint32();
const prefabType = reader.readString();
const componentCount = reader.readVarint();
const componentTypes: string[] = [];
// Create entity
const entity = scene.createEntity(`entity_${entityId}`);
entityMap?.set(entityId, entity);
for (let i = 0; i < componentCount; i++) {
const typeId = reader.readString();
componentTypes.push(typeId);
const componentClass = GlobalComponentRegistry.getComponentType(typeId) as (new () => Component) | null;
if (!componentClass) {
console.warn(`Unknown component type: ${typeId}`);
// Try to skip
const fieldCount = reader.readVarint();
for (let j = 0; j < fieldCount; j++) {
reader.readUint8();
}
continue;
}
const metadata: SyncMetadata | undefined = (componentClass as any)[SYNC_METADATA];
if (!metadata) {
continue;
}
const component = entity.addComponent(new (componentClass as new () => Component)());
decodeComponent(component, metadata, reader);
}
return { entity, prefabType, componentTypes };
}
/**
* @zh 解码销毁消息结果
* @en Decode despawn message result
*/
export interface DecodeDespawnResult {
/**
* @zh 销毁的实体 ID 列表
* @en List of despawned entity IDs
*/
entityIds: number[];
}
/**
* @zh 解码实体销毁消息
* @en Decode entity despawn message
*
* @param data - @zh 二进制数据 @en Binary data
* @returns @zh 解码结果,如果不是 DESPAWN 消息则返回 null @en Decode result, or null if not a DESPAWN message
*/
export function decodeDespawn(data: Uint8Array): DecodeDespawnResult | null {
const reader = new BinaryReader(data);
const operation = reader.readUint8();
if (operation !== SyncOperation.DESPAWN) {
return null;
}
const entityIds: number[] = [];
// Check if it's a single entity or batch
if (reader.remaining === 4) {
// Single entity
entityIds.push(reader.readUint32());
} else {
// Batch
const count = reader.readVarint();
for (let i = 0; i < count; i++) {
entityIds.push(reader.readUint32());
}
}
return { entityIds };
}
/**
* @zh 处理销毁消息(从场景中移除实体)
* @en Process despawn message (remove entities from scene)
*
* @param scene - @zh 场景 @en Scene
* @param data - @zh 二进制数据 @en Binary data
* @param entityMap - @zh 实体 ID 映射(可选)@en Entity ID mapping (optional)
* @returns @zh 移除的实体 ID 列表 @en List of removed entity IDs
*/
export function processDespawn(
scene: Scene,
data: Uint8Array,
entityMap?: Map<number, Entity>
): number[] {
const result = decodeDespawn(data);
if (!result) {
return [];
}
for (const entityId of result.entityIds) {
const entity = entityMap?.get(entityId) || scene.findEntityById(entityId);
if (entity) {
entity.destroy();
entityMap?.delete(entityId);
}
}
return result.entityIds;
}

View File

@@ -0,0 +1,291 @@
/**
* @zh 组件状态编码器
* @en Component state encoder
*
* @zh 将 ECS Component 的 @sync 字段编码为二进制格式
* @en Encodes @sync fields of ECS Components to binary format
*/
import type { Entity } from '../../Entity';
import type { Component } from '../../Component';
import type { SyncType, SyncMetadata } from '../types';
import { SyncOperation, SYNC_METADATA, CHANGE_TRACKER } from '../types';
import type { ChangeTracker } from '../ChangeTracker';
import { BinaryWriter } from './BinaryWriter';
/**
* @zh 编码单个字段值
* @en Encode a single field value
*/
function encodeFieldValue(writer: BinaryWriter, value: any, type: SyncType): void {
switch (type) {
case 'boolean':
writer.writeBoolean(value);
break;
case 'int8':
writer.writeInt8(value);
break;
case 'uint8':
writer.writeUint8(value);
break;
case 'int16':
writer.writeInt16(value);
break;
case 'uint16':
writer.writeUint16(value);
break;
case 'int32':
writer.writeInt32(value);
break;
case 'uint32':
writer.writeUint32(value);
break;
case 'float32':
writer.writeFloat32(value);
break;
case 'float64':
writer.writeFloat64(value);
break;
case 'string':
writer.writeString(value ?? '');
break;
}
}
/**
* @zh 编码组件的完整状态
* @en Encode full state of a component
*
* @zh 格式: [fieldCount: varint] ([fieldIndex: uint8] [value])...
* @en Format: [fieldCount: varint] ([fieldIndex: uint8] [value])...
*
* @param component - @zh 组件实例 @en Component instance
* @param metadata - @zh 组件同步元数据 @en Component sync metadata
* @param writer - @zh 二进制写入器 @en Binary writer
*/
export function encodeComponentFull(
component: Component,
metadata: SyncMetadata,
writer: BinaryWriter
): void {
const fields = metadata.fields;
writer.writeVarint(fields.length);
for (const field of fields) {
writer.writeUint8(field.index);
const value = (component as any)[field.name];
encodeFieldValue(writer, value, field.type);
}
}
/**
* @zh 编码组件的增量状态(只编码脏字段)
* @en Encode delta state of a component (only dirty fields)
*
* @zh 格式: [dirtyCount: varint] ([fieldIndex: uint8] [value])...
* @en Format: [dirtyCount: varint] ([fieldIndex: uint8] [value])...
*
* @param component - @zh 组件实例 @en Component instance
* @param metadata - @zh 组件同步元数据 @en Component sync metadata
* @param tracker - @zh 变更追踪器 @en Change tracker
* @param writer - @zh 二进制写入器 @en Binary writer
* @returns @zh 是否有数据编码 @en Whether any data was encoded
*/
export function encodeComponentDelta(
component: Component,
metadata: SyncMetadata,
tracker: ChangeTracker,
writer: BinaryWriter
): boolean {
if (!tracker.hasChanges()) {
return false;
}
const dirtyFields = tracker.getDirtyFields();
writer.writeVarint(dirtyFields.length);
for (const fieldIndex of dirtyFields) {
const field = metadata.fields[fieldIndex];
if (field) {
writer.writeUint8(field.index);
const value = (component as any)[field.name];
encodeFieldValue(writer, value, field.type);
}
}
return dirtyFields.length > 0;
}
/**
* @zh 编码实体的所有同步组件
* @en Encode all sync components of an entity
*
* @zh 格式:
* [entityId: uint32]
* [componentCount: varint]
* ([typeIdLength: varint] [typeId: string] [componentData])...
*
* @en Format:
* [entityId: uint32]
* [componentCount: varint]
* ([typeIdLength: varint] [typeId: string] [componentData])...
*
* @param entity - @zh 实体 @en Entity
* @param writer - @zh 二进制写入器 @en Binary writer
* @param deltaOnly - @zh 只编码增量 @en Only encode delta
* @returns @zh 编码的组件数量 @en Number of components encoded
*/
export function encodeEntity(
entity: Entity,
writer: BinaryWriter,
deltaOnly: boolean = false
): number {
writer.writeUint32(entity.id);
const components = entity.components;
const syncComponents: Array<{
component: Component;
metadata: SyncMetadata;
tracker: ChangeTracker | undefined;
}> = [];
// Collect components with sync metadata
for (const component of components) {
const constructor = component.constructor as any;
const metadata: SyncMetadata | undefined = constructor[SYNC_METADATA];
if (metadata && metadata.fields.length > 0) {
const tracker = (component as any)[CHANGE_TRACKER] as ChangeTracker | undefined;
// For delta encoding, only include components with changes
if (deltaOnly && tracker && !tracker.hasChanges()) {
continue;
}
syncComponents.push({ component, metadata, tracker });
}
}
writer.writeVarint(syncComponents.length);
for (const { component, metadata, tracker } of syncComponents) {
// Write component type ID
writer.writeString(metadata.typeId);
if (deltaOnly && tracker) {
encodeComponentDelta(component, metadata, tracker, writer);
} else {
encodeComponentFull(component, metadata, writer);
}
}
return syncComponents.length;
}
/**
* @zh 编码状态快照(多个实体)
* @en Encode state snapshot (multiple entities)
*
* @zh 格式:
* [operation: uint8] (FULL=0, DELTA=1, SPAWN=2, DESPAWN=3)
* [entityCount: varint]
* (entityData)...
*
* @en Format:
* [operation: uint8] (FULL=0, DELTA=1, SPAWN=2, DESPAWN=3)
* [entityCount: varint]
* (entityData)...
*
* @param entities - @zh 要编码的实体数组 @en Entities to encode
* @param operation - @zh 同步操作类型 @en Sync operation type
* @returns @zh 编码后的二进制数据 @en Encoded binary data
*/
export function encodeSnapshot(
entities: Entity[],
operation: SyncOperation = SyncOperation.FULL
): Uint8Array {
const writer = new BinaryWriter(1024);
writer.writeUint8(operation);
writer.writeVarint(entities.length);
const deltaOnly = operation === SyncOperation.DELTA;
for (const entity of entities) {
encodeEntity(entity, writer, deltaOnly);
}
return writer.toUint8Array();
}
/**
* @zh 编码实体生成消息
* @en Encode entity spawn message
*
* @param entity - @zh 生成的实体 @en Spawned entity
* @param prefabType - @zh 预制体类型(可选)@en Prefab type (optional)
* @returns @zh 编码后的二进制数据 @en Encoded binary data
*/
export function encodeSpawn(entity: Entity, prefabType?: string): Uint8Array {
const writer = new BinaryWriter(256);
writer.writeUint8(SyncOperation.SPAWN);
writer.writeUint32(entity.id);
writer.writeString(prefabType || '');
// Encode all sync components for initial state
const components = entity.components;
const syncComponents: Array<{ component: Component; metadata: SyncMetadata }> = [];
for (const component of components) {
const constructor = component.constructor as any;
const metadata: SyncMetadata | undefined = constructor[SYNC_METADATA];
if (metadata && metadata.fields.length > 0) {
syncComponents.push({ component, metadata });
}
}
writer.writeVarint(syncComponents.length);
for (const { component, metadata } of syncComponents) {
writer.writeString(metadata.typeId);
encodeComponentFull(component, metadata, writer);
}
return writer.toUint8Array();
}
/**
* @zh 编码实体销毁消息
* @en Encode entity despawn message
*
* @param entityId - @zh 销毁的实体 ID @en Despawned entity ID
* @returns @zh 编码后的二进制数据 @en Encoded binary data
*/
export function encodeDespawn(entityId: number): Uint8Array {
const writer = new BinaryWriter(8);
writer.writeUint8(SyncOperation.DESPAWN);
writer.writeUint32(entityId);
return writer.toUint8Array();
}
/**
* @zh 编码批量实体销毁消息
* @en Encode batch entity despawn message
*
* @param entityIds - @zh 销毁的实体 ID 数组 @en Despawned entity IDs
* @returns @zh 编码后的二进制数据 @en Encoded binary data
*/
export function encodeDespawnBatch(entityIds: number[]): Uint8Array {
const writer = new BinaryWriter(8 + entityIds.length * 4);
writer.writeUint8(SyncOperation.DESPAWN);
writer.writeVarint(entityIds.length);
for (const id of entityIds) {
writer.writeUint32(id);
}
return writer.toUint8Array();
}

View File

@@ -0,0 +1,50 @@
/**
* @zh 二进制编解码模块
* @en Binary encoding/decoding module
*
* @zh 提供 ECS Component 状态的二进制序列化和反序列化功能
* @en Provides binary serialization and deserialization for ECS Component state
*/
// Variable-length integer encoding
export {
varintSize,
encodeVarint,
decodeVarint,
zigzagEncode,
zigzagDecode,
encodeSignedVarint,
decodeSignedVarint
} from './varint';
// Binary writer/reader
export { BinaryWriter } from './BinaryWriter';
export { BinaryReader } from './BinaryReader';
// Encoder
export {
encodeComponentFull,
encodeComponentDelta,
encodeEntity,
encodeSnapshot,
encodeSpawn,
encodeDespawn,
encodeDespawnBatch
} from './Encoder';
// Decoder
export {
decodeComponent,
decodeEntity,
decodeSnapshot,
decodeSpawn,
decodeDespawn,
processDespawn
} from './Decoder';
export type {
DecodeEntityResult,
DecodeSnapshotResult,
DecodeSpawnResult,
DecodeDespawnResult
} from './Decoder';

View File

@@ -0,0 +1,137 @@
/**
* @zh 变长整数编解码
* @en Variable-length integer encoding/decoding
*
* @zh 使用 LEB128 编码方式,可变长度编码正整数。
* 小数值使用更少字节,大数值使用更多字节。
* @en Uses LEB128 encoding for variable-length integer encoding.
* Small values use fewer bytes, large values use more bytes.
*
* | 值范围 | 字节数 |
* |--------|--------|
* | 0-127 | 1 |
* | 128-16383 | 2 |
* | 16384-2097151 | 3 |
* | 2097152-268435455 | 4 |
* | 268435456+ | 5 |
*/
/**
* @zh 计算变长整数所需的字节数
* @en Calculate bytes needed for a varint
*
* @param value - @zh 整数值 @en Integer value
* @returns @zh 所需字节数 @en Bytes needed
*/
export function varintSize(value: number): number {
if (value < 0) {
throw new Error('Varint only supports non-negative integers');
}
if (value < 128) return 1;
if (value < 16384) return 2;
if (value < 2097152) return 3;
if (value < 268435456) return 4;
return 5;
}
/**
* @zh 编码变长整数到字节数组
* @en Encode varint to byte array
*
* @param value - @zh 要编码的整数 @en Integer to encode
* @param buffer - @zh 目标缓冲区 @en Target buffer
* @param offset - @zh 写入偏移 @en Write offset
* @returns @zh 写入后的新偏移 @en New offset after writing
*/
export function encodeVarint(value: number, buffer: Uint8Array, offset: number): number {
if (value < 0) {
throw new Error('Varint only supports non-negative integers');
}
while (value >= 0x80) {
buffer[offset++] = (value & 0x7F) | 0x80;
value >>>= 7;
}
buffer[offset++] = value;
return offset;
}
/**
* @zh 从字节数组解码变长整数
* @en Decode varint from byte array
*
* @param buffer - @zh 源缓冲区 @en Source buffer
* @param offset - @zh 读取偏移 @en Read offset
* @returns @zh [解码值, 新偏移] @en [decoded value, new offset]
*/
export function decodeVarint(buffer: Uint8Array, offset: number): [number, number] {
let result = 0;
let shift = 0;
let byte: number;
do {
if (offset >= buffer.length) {
throw new Error('Varint decode: buffer overflow');
}
byte = buffer[offset++]!;
result |= (byte & 0x7F) << shift;
shift += 7;
} while (byte >= 0x80);
return [result, offset];
}
/**
* @zh 编码有符号整数ZigZag 编码)
* @en Encode signed integer (ZigZag encoding)
*
* @zh ZigZag 编码将有符号整数映射到无符号整数:
* 0 → 0, -1 → 1, 1 → 2, -2 → 3, 2 → 4, ...
* 这样小的负数也能用较少字节表示。
* @en ZigZag encoding maps signed integers to unsigned:
* 0 → 0, -1 → 1, 1 → 2, -2 → 3, 2 → 4, ...
* This allows small negative numbers to use fewer bytes.
*
* @param value - @zh 有符号整数 @en Signed integer
* @returns @zh ZigZag 编码后的值 @en ZigZag encoded value
*/
export function zigzagEncode(value: number): number {
return (value << 1) ^ (value >> 31);
}
/**
* @zh 解码有符号整数ZigZag 解码)
* @en Decode signed integer (ZigZag decoding)
*
* @param value - @zh ZigZag 编码的值 @en ZigZag encoded value
* @returns @zh 原始有符号整数 @en Original signed integer
*/
export function zigzagDecode(value: number): number {
return (value >>> 1) ^ -(value & 1);
}
/**
* @zh 编码有符号变长整数
* @en Encode signed varint
*
* @param value - @zh 有符号整数 @en Signed integer
* @param buffer - @zh 目标缓冲区 @en Target buffer
* @param offset - @zh 写入偏移 @en Write offset
* @returns @zh 写入后的新偏移 @en New offset after writing
*/
export function encodeSignedVarint(value: number, buffer: Uint8Array, offset: number): number {
return encodeVarint(zigzagEncode(value), buffer, offset);
}
/**
* @zh 解码有符号变长整数
* @en Decode signed varint
*
* @param buffer - @zh 源缓冲区 @en Source buffer
* @param offset - @zh 读取偏移 @en Read offset
* @returns @zh [解码值, 新偏移] @en [decoded value, new offset]
*/
export function decodeSignedVarint(buffer: Uint8Array, offset: number): [number, number] {
const [encoded, newOffset] = decodeVarint(buffer, offset);
return [zigzagDecode(encoded), newOffset];
}

View File

@@ -0,0 +1,65 @@
/**
* @zh ECS 网络同步模块
* @en ECS Network Synchronization Module
*
* @zh 提供基于 ECS Component 的网络状态同步功能:
* - @sync 装饰器:标记需要同步的字段
* - ChangeTracker追踪字段级变更
* - 二进制编解码器:高效的网络序列化
*
* @en Provides network state synchronization based on ECS Components:
* - @sync decorator: Mark fields for synchronization
* - ChangeTracker: Track field-level changes
* - Binary encoder/decoder: Efficient network serialization
*
* @example
* ```typescript
* import { Component, ECSComponent, sync } from '@esengine/ecs-framework';
*
* @ECSComponent('Player')
* class PlayerComponent extends Component {
* @sync("string") name: string = "";
* @sync("uint16") score: number = 0;
* @sync("float32") x: number = 0;
* @sync("float32") y: number = 0;
* }
* ```
*/
// Types
export {
SyncType,
SyncFieldMetadata,
SyncMetadata,
SyncOperation,
TYPE_SIZES,
SYNC_METADATA,
CHANGE_TRACKER
} from './types';
// Change Tracker
export { ChangeTracker } from './ChangeTracker';
// Decorators
export {
sync,
getSyncMetadata,
hasSyncFields,
getChangeTracker,
initChangeTracker,
clearChanges,
hasChanges
} from './decorators';
// Network Entity Decorator
export {
NetworkEntity,
getNetworkEntityMetadata,
isNetworkEntity,
NETWORK_ENTITY_METADATA,
type NetworkEntityMetadata,
type NetworkEntityOptions
} from './NetworkEntityDecorator';
// Encoding
export * from './encoding';

View File

@@ -0,0 +1,127 @@
/**
* @zh 网络同步类型定义
* @en Network synchronization type definitions
*/
/**
* @zh 支持的同步数据类型
* @en Supported sync data types
*/
export type SyncType =
| 'boolean'
| 'int8'
| 'uint8'
| 'int16'
| 'uint16'
| 'int32'
| 'uint32'
| 'float32'
| 'float64'
| 'string';
/**
* @zh 同步字段元数据
* @en Sync field metadata
*/
export interface SyncFieldMetadata {
/**
* @zh 字段索引(用于二进制编码)
* @en Field index (for binary encoding)
*/
index: number;
/**
* @zh 字段名称
* @en Field name
*/
name: string;
/**
* @zh 字段类型
* @en Field type
*/
type: SyncType;
}
/**
* @zh 组件同步元数据
* @en Component sync metadata
*/
export interface SyncMetadata {
/**
* @zh 组件类型 ID
* @en Component type ID
*/
typeId: string;
/**
* @zh 同步字段列表(按索引排序)
* @en Sync fields list (sorted by index)
*/
fields: SyncFieldMetadata[];
/**
* @zh 字段名到索引的映射
* @en Field name to index mapping
*/
fieldIndexMap: Map<string, number>;
}
/**
* @zh 同步操作类型
* @en Sync operation type
*/
export enum SyncOperation {
/**
* @zh 完整快照
* @en Full snapshot
*/
FULL = 0,
/**
* @zh 增量更新
* @en Delta update
*/
DELTA = 1,
/**
* @zh 实体生成
* @en Entity spawn
*/
SPAWN = 2,
/**
* @zh 实体销毁
* @en Entity despawn
*/
DESPAWN = 3,
}
/**
* @zh 各类型的字节大小
* @en Byte size for each type
*/
export const TYPE_SIZES: Record<SyncType, number> = {
boolean: 1,
int8: 1,
uint8: 1,
int16: 2,
uint16: 2,
int32: 4,
uint32: 4,
float32: 4,
float64: 8,
string: -1, // 动态长度 | dynamic length
};
/**
* @zh 同步元数据的 Symbol 键
* @en Symbol key for sync metadata
*/
export const SYNC_METADATA = Symbol('SyncMetadata');
/**
* @zh 变更追踪器的 Symbol 键
* @en Symbol key for change tracker
*/
export const CHANGE_TRACKER = Symbol('ChangeTracker');

View File

@@ -317,9 +317,7 @@ export class WorldManager implements IService {
/**
* @zh 更新所有活跃的World
* @en Update all active Worlds
*
* @zh 应该在每帧的游戏循环中调用
* @en Should be called in each frame of game loop
* @internal 由 Core.update() 调用,用户不应直接调用
*/
public updateAll(): void {
if (!this._isRunning) return;

View File

@@ -7,7 +7,7 @@ export * from './Utils';
export * from './Decorators';
export * from './Components';
export { Scene } from './Scene';
export type { IScene, ISceneFactory, ISceneConfig } from './IScene';
export type { IScene, ISceneFactory, ISceneConfig, RuntimeEnvironment } from './IScene';
export { SceneManager } from './SceneManager';
export { World } from './World';
export type { IWorldConfig } from './World';
@@ -57,3 +57,6 @@ export { EpochManager } from './Core/EpochManager';
// Compiled Query
export { CompiledQuery } from './Core/Query/CompiledQuery';
export type { InstanceTypes } from './Core/Query/CompiledQuery';
// Network Synchronization
export * from './Sync';

View File

@@ -0,0 +1,50 @@
import type { RuntimeEnvironment } from './Types';
/**
* @zh 全局运行时配置
* @en Global runtime configuration
*
* @zh 独立模块,避免 Core 和 Scene 之间的循环依赖
* @en Standalone module to avoid circular dependency between Core and Scene
*/
class RuntimeConfigClass {
private _runtimeEnvironment: RuntimeEnvironment = 'standalone';
/**
* @zh 获取运行时环境
* @en Get runtime environment
*/
get runtimeEnvironment(): RuntimeEnvironment {
return this._runtimeEnvironment;
}
/**
* @zh 设置运行时环境
* @en Set runtime environment
*/
set runtimeEnvironment(value: RuntimeEnvironment) {
this._runtimeEnvironment = value;
}
/**
* @zh 是否在服务端运行
* @en Whether running on server
*/
get isServer(): boolean {
return this._runtimeEnvironment === 'server';
}
/**
* @zh 是否在客户端运行
* @en Whether running on client
*/
get isClient(): boolean {
return this._runtimeEnvironment === 'client';
}
}
/**
* @zh 全局运行时配置单例
* @en Global runtime configuration singleton
*/
export const RuntimeConfig = new RuntimeConfigClass();

View File

@@ -267,6 +267,12 @@ export type IECSDebugConfig = {
};
}
/**
* @zh 运行时环境类型
* @en Runtime environment type
*/
export type RuntimeEnvironment = 'server' | 'client' | 'standalone';
/**
* Core配置接口
*/
@@ -277,6 +283,16 @@ export type ICoreConfig = {
debugConfig?: IECSDebugConfig;
/** WorldManager配置 */
worldManagerConfig?: IWorldManagerConfig;
/**
* @zh 运行时环境
* @en Runtime environment
*
* @zh 设置后所有 Scene 默认继承此环境。服务端框架应设置为 'server',客户端应用设置为 'client'。
* @en All Scenes inherit this environment by default. Server frameworks should set 'server', client apps should set 'client'.
*
* @default 'standalone'
*/
runtimeEnvironment?: RuntimeEnvironment;
}
/**

View File

@@ -5,6 +5,7 @@
// 核心模块
export { Core } from './Core';
export { RuntimeConfig } from './RuntimeConfig';
export { ServiceContainer, ServiceLifetime } from './Core/ServiceContainer';
export type { IService, ServiceType, ServiceIdentifier } from './Core/ServiceContainer';

View File

@@ -0,0 +1,172 @@
import { ChangeTracker } from '../../../src/ECS/Sync/ChangeTracker';
describe('ChangeTracker - 变更追踪器测试', () => {
let tracker: ChangeTracker;
beforeEach(() => {
tracker = new ChangeTracker();
});
describe('基本功能', () => {
test('初始状态应该没有变更', () => {
expect(tracker.hasChanges()).toBe(false);
expect(tracker.getDirtyCount()).toBe(0);
expect(tracker.getDirtyFields()).toEqual([]);
});
test('setDirty 应该标记字段为脏', () => {
tracker.setDirty(0);
expect(tracker.hasChanges()).toBe(true);
expect(tracker.isDirty(0)).toBe(true);
expect(tracker.getDirtyCount()).toBe(1);
expect(tracker.getDirtyFields()).toEqual([0]);
});
test('多次 setDirty 同一字段应该只记录一次', () => {
tracker.setDirty(0);
tracker.setDirty(0);
tracker.setDirty(0);
expect(tracker.getDirtyCount()).toBe(1);
expect(tracker.getDirtyFields()).toEqual([0]);
});
test('setDirty 不同字段应该都被记录', () => {
tracker.setDirty(0);
tracker.setDirty(1);
tracker.setDirty(2);
expect(tracker.getDirtyCount()).toBe(3);
expect(tracker.getDirtyFields().sort()).toEqual([0, 1, 2]);
});
});
describe('isDirty 方法', () => {
test('未标记的字段应该返回 false', () => {
expect(tracker.isDirty(0)).toBe(false);
expect(tracker.isDirty(5)).toBe(false);
});
test('已标记的字段应该返回 true', () => {
tracker.setDirty(3);
expect(tracker.isDirty(3)).toBe(true);
expect(tracker.isDirty(0)).toBe(false);
});
});
describe('clear 方法', () => {
test('clear 应该清除所有变更', () => {
tracker.setDirty(0);
tracker.setDirty(1);
tracker.setDirty(2);
expect(tracker.hasChanges()).toBe(true);
tracker.clear();
expect(tracker.hasChanges()).toBe(false);
expect(tracker.getDirtyCount()).toBe(0);
expect(tracker.getDirtyFields()).toEqual([]);
});
test('clear 应该更新 lastSyncTime', () => {
const before = tracker.lastSyncTime;
tracker.setDirty(0);
tracker.clear();
expect(tracker.lastSyncTime).toBeGreaterThan(0);
});
});
describe('clearField 方法', () => {
test('clearField 应该只清除指定字段', () => {
tracker.setDirty(0);
tracker.setDirty(1);
tracker.setDirty(2);
tracker.clearField(1);
expect(tracker.isDirty(0)).toBe(true);
expect(tracker.isDirty(1)).toBe(false);
expect(tracker.isDirty(2)).toBe(true);
expect(tracker.getDirtyCount()).toBe(2);
});
test('清除最后一个字段应该使 hasChanges 返回 false', () => {
tracker.setDirty(0);
expect(tracker.hasChanges()).toBe(true);
tracker.clearField(0);
expect(tracker.hasChanges()).toBe(false);
});
});
describe('markAllDirty 方法', () => {
test('markAllDirty 应该标记所有字段', () => {
tracker.markAllDirty(5);
expect(tracker.hasChanges()).toBe(true);
expect(tracker.getDirtyCount()).toBe(5);
expect(tracker.getDirtyFields().sort()).toEqual([0, 1, 2, 3, 4]);
});
test('markAllDirty(0) 应该没有变更', () => {
tracker.markAllDirty(0);
expect(tracker.hasChanges()).toBe(false);
expect(tracker.getDirtyCount()).toBe(0);
});
test('markAllDirty 用于首次同步', () => {
tracker.markAllDirty(3);
expect(tracker.isDirty(0)).toBe(true);
expect(tracker.isDirty(1)).toBe(true);
expect(tracker.isDirty(2)).toBe(true);
expect(tracker.isDirty(3)).toBe(false);
});
});
describe('reset 方法', () => {
test('reset 应该重置所有状态', () => {
tracker.setDirty(0);
tracker.setDirty(1);
tracker.clear();
tracker.reset();
expect(tracker.hasChanges()).toBe(false);
expect(tracker.getDirtyCount()).toBe(0);
expect(tracker.lastSyncTime).toBe(0);
});
});
describe('边界情况', () => {
test('大量字段标记应该正常工作', () => {
const fieldCount = 1000;
for (let i = 0; i < fieldCount; i++) {
tracker.setDirty(i);
}
expect(tracker.getDirtyCount()).toBe(fieldCount);
expect(tracker.hasChanges()).toBe(true);
});
test('交替设置和清除应该正常工作', () => {
tracker.setDirty(0);
tracker.setDirty(1);
tracker.clearField(0);
tracker.setDirty(2);
tracker.clearField(1);
expect(tracker.isDirty(0)).toBe(false);
expect(tracker.isDirty(1)).toBe(false);
expect(tracker.isDirty(2)).toBe(true);
expect(tracker.getDirtyCount()).toBe(1);
});
});
});

View File

@@ -0,0 +1,327 @@
import { Component } from '../../../src/ECS/Component';
import { ECSComponent } from '../../../src/ECS/Decorators';
import { Scene } from '../../../src/ECS/Scene';
import {
sync,
getSyncMetadata,
hasSyncFields,
getChangeTracker,
initChangeTracker,
clearChanges,
hasChanges
} from '../../../src/ECS/Sync/decorators';
import { SYNC_METADATA, CHANGE_TRACKER } from '../../../src/ECS/Sync/types';
@ECSComponent('SyncTest_PlayerComponent')
class PlayerComponent extends Component {
@sync("string") name: string = "";
@sync("uint16") score: number = 0;
@sync("float32") x: number = 0;
@sync("float32") y: number = 0;
localData: string = "not synced";
}
@ECSComponent('SyncTest_SimpleComponent')
class SimpleComponent extends Component {
@sync("boolean") active: boolean = true;
@sync("int32") value: number = 100;
}
@ECSComponent('SyncTest_NoSyncComponent')
class NoSyncComponent extends Component {
localValue: number = 0;
}
@ECSComponent('SyncTest_AllTypesComponent')
class AllTypesComponent extends Component {
@sync("boolean") boolField: boolean = false;
@sync("int8") int8Field: number = 0;
@sync("uint8") uint8Field: number = 0;
@sync("int16") int16Field: number = 0;
@sync("uint16") uint16Field: number = 0;
@sync("int32") int32Field: number = 0;
@sync("uint32") uint32Field: number = 0;
@sync("float32") float32Field: number = 0;
@sync("float64") float64Field: number = 0;
@sync("string") stringField: string = "";
}
describe('@sync 装饰器测试', () => {
describe('getSyncMetadata', () => {
test('应该返回带 @sync 字段的组件元数据', () => {
const metadata = getSyncMetadata(PlayerComponent);
expect(metadata).not.toBeNull();
expect(metadata!.typeId).toBe('SyncTest_PlayerComponent');
expect(metadata!.fields.length).toBe(4);
});
test('应该正确记录字段信息', () => {
const metadata = getSyncMetadata(PlayerComponent);
const nameField = metadata!.fields.find(f => f.name === 'name');
expect(nameField).toBeDefined();
expect(nameField!.type).toBe('string');
expect(nameField!.index).toBe(0);
const scoreField = metadata!.fields.find(f => f.name === 'score');
expect(scoreField).toBeDefined();
expect(scoreField!.type).toBe('uint16');
const xField = metadata!.fields.find(f => f.name === 'x');
expect(xField).toBeDefined();
expect(xField!.type).toBe('float32');
});
test('没有 @sync 字段的组件应该返回 null', () => {
const metadata = getSyncMetadata(NoSyncComponent);
expect(metadata).toBeNull();
});
test('可以从实例获取元数据', () => {
const component = new PlayerComponent();
const metadata = getSyncMetadata(component);
expect(metadata).not.toBeNull();
expect(metadata!.fields.length).toBe(4);
});
test('fieldIndexMap 应该正确映射字段名到索引', () => {
const metadata = getSyncMetadata(PlayerComponent);
expect(metadata!.fieldIndexMap.get('name')).toBe(0);
expect(metadata!.fieldIndexMap.get('score')).toBe(1);
expect(metadata!.fieldIndexMap.get('x')).toBe(2);
expect(metadata!.fieldIndexMap.get('y')).toBe(3);
});
});
describe('hasSyncFields', () => {
test('有 @sync 字段应该返回 true', () => {
expect(hasSyncFields(PlayerComponent)).toBe(true);
expect(hasSyncFields(new PlayerComponent())).toBe(true);
});
test('没有 @sync 字段应该返回 false', () => {
expect(hasSyncFields(NoSyncComponent)).toBe(false);
expect(hasSyncFields(new NoSyncComponent())).toBe(false);
});
});
describe('支持所有同步类型', () => {
test('AllTypesComponent 应该有所有类型的字段', () => {
const metadata = getSyncMetadata(AllTypesComponent);
expect(metadata).not.toBeNull();
expect(metadata!.fields.length).toBe(10);
const types = metadata!.fields.map(f => f.type);
expect(types).toContain('boolean');
expect(types).toContain('int8');
expect(types).toContain('uint8');
expect(types).toContain('int16');
expect(types).toContain('uint16');
expect(types).toContain('int32');
expect(types).toContain('uint32');
expect(types).toContain('float32');
expect(types).toContain('float64');
expect(types).toContain('string');
});
});
describe('字段值拦截', () => {
test('修改 @sync 字段应该触发变更追踪', () => {
const component = new PlayerComponent();
initChangeTracker(component);
const tracker = getChangeTracker(component);
expect(tracker).not.toBeNull();
tracker!.clear();
component.name = "TestPlayer";
expect(tracker!.hasChanges()).toBe(true);
expect(tracker!.isDirty(0)).toBe(true);
});
test('设置相同值不应该触发变更', () => {
const component = new PlayerComponent();
component.name = "Test";
initChangeTracker(component);
const tracker = getChangeTracker(component);
tracker!.clear();
component.name = "Test";
expect(tracker!.hasChanges()).toBe(false);
});
test('修改非 @sync 字段不应该触发变更', () => {
const component = new PlayerComponent();
initChangeTracker(component);
const tracker = getChangeTracker(component);
tracker!.clear();
component.localData = "new value";
expect(tracker!.hasChanges()).toBe(false);
});
test('多个字段变更应该都被追踪', () => {
const component = new PlayerComponent();
initChangeTracker(component);
const tracker = getChangeTracker(component);
tracker!.clear();
component.name = "NewName";
component.score = 100;
component.x = 1.5;
expect(tracker!.getDirtyCount()).toBe(3);
expect(tracker!.isDirty(0)).toBe(true);
expect(tracker!.isDirty(1)).toBe(true);
expect(tracker!.isDirty(2)).toBe(true);
expect(tracker!.isDirty(3)).toBe(false);
});
});
describe('initChangeTracker', () => {
test('应该创建变更追踪器', () => {
const component = new PlayerComponent();
expect(getChangeTracker(component)).toBeNull();
initChangeTracker(component);
expect(getChangeTracker(component)).not.toBeNull();
});
test('应该标记所有字段为脏(用于首次同步)', () => {
const component = new PlayerComponent();
initChangeTracker(component);
const tracker = getChangeTracker(component);
expect(tracker!.hasChanges()).toBe(true);
expect(tracker!.getDirtyCount()).toBe(4);
});
test('对没有 @sync 字段的组件应该抛出错误', () => {
const component = new NoSyncComponent();
expect(() => {
initChangeTracker(component);
}).toThrow();
});
test('重复初始化应该重新标记所有字段', () => {
const component = new PlayerComponent();
initChangeTracker(component);
const tracker = getChangeTracker(component);
tracker!.clear();
expect(tracker!.hasChanges()).toBe(false);
initChangeTracker(component);
expect(tracker!.hasChanges()).toBe(true);
expect(tracker!.getDirtyCount()).toBe(4);
});
});
describe('clearChanges', () => {
test('应该清除所有变更标记', () => {
const component = new PlayerComponent();
initChangeTracker(component);
expect(hasChanges(component)).toBe(true);
clearChanges(component);
expect(hasChanges(component)).toBe(false);
});
test('对没有追踪器的组件应该安全执行', () => {
const component = new PlayerComponent();
expect(() => {
clearChanges(component);
}).not.toThrow();
});
});
describe('hasChanges', () => {
test('初始化后应该有变更', () => {
const component = new PlayerComponent();
initChangeTracker(component);
expect(hasChanges(component)).toBe(true);
});
test('清除后应该没有变更', () => {
const component = new PlayerComponent();
initChangeTracker(component);
clearChanges(component);
expect(hasChanges(component)).toBe(false);
});
test('修改字段后应该有变更', () => {
const component = new PlayerComponent();
initChangeTracker(component);
clearChanges(component);
component.score = 999;
expect(hasChanges(component)).toBe(true);
});
test('没有追踪器应该返回 false', () => {
const component = new PlayerComponent();
expect(hasChanges(component)).toBe(false);
});
});
describe('与实体集成', () => {
let scene: Scene;
beforeEach(() => {
scene = new Scene();
});
test('添加到实体的组件应该能正常工作', () => {
const entity = scene.createEntity('TestEntity');
const component = new PlayerComponent();
entity.addComponent(component);
initChangeTracker(component);
component.name = "EntityPlayer";
component.x = 100;
const tracker = getChangeTracker(component);
expect(tracker!.hasChanges()).toBe(true);
});
test('从实体获取的组件应该保持追踪状态', () => {
const entity = scene.createEntity('TestEntity');
const component = new PlayerComponent();
entity.addComponent(component);
initChangeTracker(component);
clearChanges(component);
const retrieved = entity.getComponent(PlayerComponent);
retrieved!.score = 50;
expect(hasChanges(component)).toBe(true);
expect(hasChanges(retrieved!)).toBe(true);
});
});
});

View File

@@ -0,0 +1,530 @@
import { BinaryWriter } from '../../../src/ECS/Sync/encoding/BinaryWriter';
import { BinaryReader } from '../../../src/ECS/Sync/encoding/BinaryReader';
import { Component } from '../../../src/ECS/Component';
import { ECSComponent } from '../../../src/ECS/Decorators';
import { Scene } from '../../../src/ECS/Scene';
import { sync, initChangeTracker, clearChanges } from '../../../src/ECS/Sync/decorators';
import {
encodeSnapshot,
encodeSpawn,
encodeDespawn,
encodeDespawnBatch
} from '../../../src/ECS/Sync/encoding/Encoder';
import {
decodeSnapshot,
decodeSpawn,
processDespawn
} from '../../../src/ECS/Sync/encoding/Decoder';
import { SyncOperation } from '../../../src/ECS/Sync/types';
@ECSComponent('EncodingTest_PlayerComponent')
class PlayerComponent extends Component {
@sync("string") name: string = "";
@sync("uint16") score: number = 0;
@sync("float32") x: number = 0;
@sync("float32") y: number = 0;
}
@ECSComponent('EncodingTest_AllTypesComponent')
class AllTypesComponent extends Component {
@sync("boolean") boolField: boolean = false;
@sync("int8") int8Field: number = 0;
@sync("uint8") uint8Field: number = 0;
@sync("int16") int16Field: number = 0;
@sync("uint16") uint16Field: number = 0;
@sync("int32") int32Field: number = 0;
@sync("uint32") uint32Field: number = 0;
@sync("float32") float32Field: number = 0;
@sync("float64") float64Field: number = 0;
@sync("string") stringField: string = "";
}
describe('BinaryWriter/BinaryReader - 二进制读写器测试', () => {
describe('基本数值类型', () => {
test('writeUint8/readUint8', () => {
const writer = new BinaryWriter();
writer.writeUint8(0);
writer.writeUint8(127);
writer.writeUint8(255);
const reader = new BinaryReader(writer.toUint8Array());
expect(reader.readUint8()).toBe(0);
expect(reader.readUint8()).toBe(127);
expect(reader.readUint8()).toBe(255);
});
test('writeInt8/readInt8', () => {
const writer = new BinaryWriter();
writer.writeInt8(-128);
writer.writeInt8(0);
writer.writeInt8(127);
const reader = new BinaryReader(writer.toUint8Array());
expect(reader.readInt8()).toBe(-128);
expect(reader.readInt8()).toBe(0);
expect(reader.readInt8()).toBe(127);
});
test('writeBoolean/readBoolean', () => {
const writer = new BinaryWriter();
writer.writeBoolean(true);
writer.writeBoolean(false);
const reader = new BinaryReader(writer.toUint8Array());
expect(reader.readBoolean()).toBe(true);
expect(reader.readBoolean()).toBe(false);
});
test('writeUint16/readUint16', () => {
const writer = new BinaryWriter();
writer.writeUint16(0);
writer.writeUint16(32767);
writer.writeUint16(65535);
const reader = new BinaryReader(writer.toUint8Array());
expect(reader.readUint16()).toBe(0);
expect(reader.readUint16()).toBe(32767);
expect(reader.readUint16()).toBe(65535);
});
test('writeInt16/readInt16', () => {
const writer = new BinaryWriter();
writer.writeInt16(-32768);
writer.writeInt16(0);
writer.writeInt16(32767);
const reader = new BinaryReader(writer.toUint8Array());
expect(reader.readInt16()).toBe(-32768);
expect(reader.readInt16()).toBe(0);
expect(reader.readInt16()).toBe(32767);
});
test('writeUint32/readUint32', () => {
const writer = new BinaryWriter();
writer.writeUint32(0);
writer.writeUint32(2147483647);
writer.writeUint32(4294967295);
const reader = new BinaryReader(writer.toUint8Array());
expect(reader.readUint32()).toBe(0);
expect(reader.readUint32()).toBe(2147483647);
expect(reader.readUint32()).toBe(4294967295);
});
test('writeInt32/readInt32', () => {
const writer = new BinaryWriter();
writer.writeInt32(-2147483648);
writer.writeInt32(0);
writer.writeInt32(2147483647);
const reader = new BinaryReader(writer.toUint8Array());
expect(reader.readInt32()).toBe(-2147483648);
expect(reader.readInt32()).toBe(0);
expect(reader.readInt32()).toBe(2147483647);
});
test('writeFloat32/readFloat32', () => {
const writer = new BinaryWriter();
writer.writeFloat32(0);
writer.writeFloat32(3.14);
writer.writeFloat32(-100.5);
const reader = new BinaryReader(writer.toUint8Array());
expect(reader.readFloat32()).toBe(0);
expect(reader.readFloat32()).toBeCloseTo(3.14, 5);
expect(reader.readFloat32()).toBeCloseTo(-100.5, 5);
});
test('writeFloat64/readFloat64', () => {
const writer = new BinaryWriter();
writer.writeFloat64(0);
writer.writeFloat64(Math.PI);
writer.writeFloat64(-1e100);
const reader = new BinaryReader(writer.toUint8Array());
expect(reader.readFloat64()).toBe(0);
expect(reader.readFloat64()).toBe(Math.PI);
expect(reader.readFloat64()).toBe(-1e100);
});
});
describe('变长整数 (Varint)', () => {
test('小值 (1字节)', () => {
const writer = new BinaryWriter();
writer.writeVarint(0);
writer.writeVarint(127);
const reader = new BinaryReader(writer.toUint8Array());
expect(reader.readVarint()).toBe(0);
expect(reader.readVarint()).toBe(127);
});
test('中等值 (2字节)', () => {
const writer = new BinaryWriter();
writer.writeVarint(128);
writer.writeVarint(16383);
const reader = new BinaryReader(writer.toUint8Array());
expect(reader.readVarint()).toBe(128);
expect(reader.readVarint()).toBe(16383);
});
test('大值 (多字节)', () => {
const writer = new BinaryWriter();
writer.writeVarint(16384);
writer.writeVarint(1000000);
writer.writeVarint(2147483647);
const reader = new BinaryReader(writer.toUint8Array());
expect(reader.readVarint()).toBe(16384);
expect(reader.readVarint()).toBe(1000000);
expect(reader.readVarint()).toBe(2147483647);
});
});
describe('字符串', () => {
test('空字符串', () => {
const writer = new BinaryWriter();
writer.writeString("");
const reader = new BinaryReader(writer.toUint8Array());
expect(reader.readString()).toBe("");
});
test('ASCII 字符串', () => {
const writer = new BinaryWriter();
writer.writeString("Hello, World!");
const reader = new BinaryReader(writer.toUint8Array());
expect(reader.readString()).toBe("Hello, World!");
});
test('Unicode 字符串', () => {
const writer = new BinaryWriter();
writer.writeString("你好世界");
writer.writeString("日本語テスト");
writer.writeString("emoji: 🎮🎯");
const reader = new BinaryReader(writer.toUint8Array());
expect(reader.readString()).toBe("你好世界");
expect(reader.readString()).toBe("日本語テスト");
expect(reader.readString()).toBe("emoji: 🎮🎯");
});
test('混合字符串', () => {
const writer = new BinaryWriter();
writer.writeString("Player_玩家_プレイヤー");
const reader = new BinaryReader(writer.toUint8Array());
expect(reader.readString()).toBe("Player_玩家_プレイヤー");
});
});
describe('字节数组', () => {
test('writeBytes/readBytes', () => {
const writer = new BinaryWriter();
const data = new Uint8Array([1, 2, 3, 4, 5]);
writer.writeBytes(data);
const reader = new BinaryReader(writer.toUint8Array());
const result = reader.readBytes(5);
expect(Array.from(result)).toEqual([1, 2, 3, 4, 5]);
});
});
describe('BinaryReader 辅助方法', () => {
test('remaining 应该返回剩余字节数', () => {
const writer = new BinaryWriter();
writer.writeUint32(100);
writer.writeUint32(200);
const reader = new BinaryReader(writer.toUint8Array());
expect(reader.remaining).toBe(8);
reader.readUint32();
expect(reader.remaining).toBe(4);
});
test('hasMore 应该正确判断', () => {
const writer = new BinaryWriter();
writer.writeUint8(1);
const reader = new BinaryReader(writer.toUint8Array());
expect(reader.hasMore()).toBe(true);
reader.readUint8();
expect(reader.hasMore()).toBe(false);
});
test('peekUint8 不应该移动读取位置', () => {
const writer = new BinaryWriter();
writer.writeUint8(42);
writer.writeUint8(99);
const reader = new BinaryReader(writer.toUint8Array());
expect(reader.peekUint8()).toBe(42);
expect(reader.peekUint8()).toBe(42);
expect(reader.offset).toBe(0);
});
test('skip 应该跳过指定字节', () => {
const writer = new BinaryWriter();
writer.writeUint8(1);
writer.writeUint8(2);
writer.writeUint8(3);
const reader = new BinaryReader(writer.toUint8Array());
reader.skip(2);
expect(reader.readUint8()).toBe(3);
});
test('读取超出范围应该抛出错误', () => {
const reader = new BinaryReader(new Uint8Array([1, 2]));
expect(() => reader.readUint32()).toThrow();
});
});
describe('BinaryWriter 自动扩容', () => {
test('应该自动扩容', () => {
const writer = new BinaryWriter(4);
for (let i = 0; i < 100; i++) {
writer.writeUint32(i);
}
expect(writer.offset).toBe(400);
const reader = new BinaryReader(writer.toUint8Array());
for (let i = 0; i < 100; i++) {
expect(reader.readUint32()).toBe(i);
}
});
test('reset 应该清空数据但保留缓冲区', () => {
const writer = new BinaryWriter();
writer.writeUint32(100);
writer.writeUint32(200);
expect(writer.offset).toBe(8);
writer.reset();
expect(writer.offset).toBe(0);
expect(writer.toUint8Array().length).toBe(0);
});
});
});
describe('Encoder/Decoder - 实体编解码测试', () => {
let scene: Scene;
// Components are auto-registered via @ECSComponent decorator
beforeEach(() => {
scene = new Scene();
});
describe('encodeSnapshot/decodeSnapshot', () => {
test('应该编码和解码单个实体', () => {
const entity = scene.createEntity('Player1');
const comp = entity.addComponent(new PlayerComponent());
comp.name = "TestPlayer";
comp.score = 100;
comp.x = 10.5;
comp.y = 20.5;
initChangeTracker(comp);
const data = encodeSnapshot([entity], SyncOperation.FULL);
const targetScene = new Scene();
const result = decodeSnapshot(targetScene, data);
expect(result.operation).toBe(SyncOperation.FULL);
expect(result.entities.length).toBe(1);
expect(result.entities[0].isNew).toBe(true);
const decodedEntity = targetScene.entities.buffer[0];
expect(decodedEntity).toBeDefined();
const decodedComp = decodedEntity!.getComponent(PlayerComponent);
expect(decodedComp).not.toBeNull();
expect(decodedComp!.name).toBe("TestPlayer");
expect(decodedComp!.score).toBe(100);
expect(decodedComp!.x).toBeCloseTo(10.5, 5);
expect(decodedComp!.y).toBeCloseTo(20.5, 5);
});
test('应该编码和解码多个实体', () => {
const entity1 = scene.createEntity('Player1');
const comp1 = entity1.addComponent(new PlayerComponent());
comp1.name = "Player1";
comp1.score = 50;
initChangeTracker(comp1);
const entity2 = scene.createEntity('Player2');
const comp2 = entity2.addComponent(new PlayerComponent());
comp2.name = "Player2";
comp2.score = 100;
initChangeTracker(comp2);
const data = encodeSnapshot([entity1, entity2], SyncOperation.FULL);
const targetScene = new Scene();
const result = decodeSnapshot(targetScene, data);
expect(result.entities.length).toBe(2);
});
test('DELTA 操作应该只编码变更的字段', () => {
const entity = scene.createEntity('Player1');
const comp = entity.addComponent(new PlayerComponent());
comp.name = "TestPlayer";
comp.score = 0;
initChangeTracker(comp);
clearChanges(comp);
comp.score = 200;
const deltaData = encodeSnapshot([entity], SyncOperation.DELTA);
expect(deltaData[0]).toBe(SyncOperation.DELTA);
expect(deltaData.length).toBeLessThan(50);
});
});
describe('encodeSpawn/decodeSpawn', () => {
test('应该编码和解码实体生成', () => {
const entity = scene.createEntity('SpawnedEntity');
const comp = entity.addComponent(new PlayerComponent());
comp.name = "SpawnedPlayer";
comp.score = 50;
comp.x = 100;
comp.y = 200;
initChangeTracker(comp);
const data = encodeSpawn(entity, 'Player');
const targetScene = new Scene();
const result = decodeSpawn(targetScene, data);
expect(result).not.toBeNull();
expect(result!.prefabType).toBe('Player');
expect(result!.componentTypes).toContain('EncodingTest_PlayerComponent');
const decodedComp = result!.entity.getComponent(PlayerComponent);
expect(decodedComp!.name).toBe("SpawnedPlayer");
expect(decodedComp!.score).toBe(50);
});
test('没有 prefabType 应该也能工作', () => {
const entity = scene.createEntity('Entity');
const comp = entity.addComponent(new PlayerComponent());
initChangeTracker(comp);
const data = encodeSpawn(entity);
const targetScene = new Scene();
const result = decodeSpawn(targetScene, data);
expect(result!.prefabType).toBe('');
});
});
describe('encodeDespawn/processDespawn', () => {
test('应该编码和处理单个实体销毁', () => {
const targetScene = new Scene();
const entity = targetScene.createEntity('ToBeDestroyed');
const entityId = entity.id;
const data = encodeDespawn(entityId);
expect(data[0]).toBe(SyncOperation.DESPAWN);
const removedIds = processDespawn(targetScene, data);
expect(removedIds).toContain(entityId);
});
test('应该编码和处理批量实体销毁', () => {
const targetScene = new Scene();
const entity1 = targetScene.createEntity('Entity1');
const entity2 = targetScene.createEntity('Entity2');
const entity3 = targetScene.createEntity('Entity3');
const data = encodeDespawnBatch([entity1.id, entity2.id, entity3.id]);
expect(data[0]).toBe(SyncOperation.DESPAWN);
const removedIds = processDespawn(targetScene, data);
expect(removedIds.length).toBe(3);
expect(removedIds).toContain(entity1.id);
expect(removedIds).toContain(entity2.id);
expect(removedIds).toContain(entity3.id);
});
});
describe('所有同步类型编解码', () => {
test('应该正确编解码所有类型', () => {
const entity = scene.createEntity('AllTypes');
const comp = entity.addComponent(new AllTypesComponent());
comp.boolField = true;
comp.int8Field = -100;
comp.uint8Field = 200;
comp.int16Field = -30000;
comp.uint16Field = 60000;
comp.int32Field = -2000000000;
comp.uint32Field = 4000000000;
comp.float32Field = 3.14159;
comp.float64Field = Math.PI;
comp.stringField = "测试字符串";
initChangeTracker(comp);
const data = encodeSnapshot([entity], SyncOperation.FULL);
const targetScene = new Scene();
decodeSnapshot(targetScene, data);
const decodedEntity = targetScene.entities.buffer[0];
const decodedComp = decodedEntity!.getComponent(AllTypesComponent);
expect(decodedComp!.boolField).toBe(true);
expect(decodedComp!.int8Field).toBe(-100);
expect(decodedComp!.uint8Field).toBe(200);
expect(decodedComp!.int16Field).toBe(-30000);
expect(decodedComp!.uint16Field).toBe(60000);
expect(decodedComp!.int32Field).toBe(-2000000000);
expect(decodedComp!.uint32Field).toBe(4000000000);
expect(decodedComp!.float32Field).toBeCloseTo(3.14159, 4);
expect(decodedComp!.float64Field).toBe(Math.PI);
expect(decodedComp!.stringField).toBe("测试字符串");
});
});
describe('边界情况', () => {
test('空实体列表应该能编码', () => {
const data = encodeSnapshot([], SyncOperation.FULL);
const targetScene = new Scene();
const result = decodeSnapshot(targetScene, data);
expect(result.entities.length).toBe(0);
});
test('entityMap 应该正确跟踪实体', () => {
const entity = scene.createEntity('Tracked');
const comp = entity.addComponent(new PlayerComponent());
comp.name = "TrackedPlayer";
initChangeTracker(comp);
const data = encodeSnapshot([entity], SyncOperation.FULL);
const targetScene = new Scene();
const entityMap = new Map();
decodeSnapshot(targetScene, data, entityMap);
expect(entityMap.size).toBe(1);
});
});
});

View File

@@ -1,5 +1,53 @@
# @esengine/fsm
## 4.0.1
### Patch Changes
- Updated dependencies [[`3e5b778`](https://github.com/esengine/esengine/commit/3e5b7783beec08e247f7525184935401923ecde8)]:
- @esengine/ecs-framework@2.7.1
- @esengine/blueprint@4.0.1
## 4.0.0
### Patch Changes
- Updated dependencies [[`1f3a76a`](https://github.com/esengine/esengine/commit/1f3a76aabea2d3eb8a5eb8b73e29127da57e2028)]:
- @esengine/ecs-framework@2.7.0
- @esengine/blueprint@4.0.0
## 3.0.1
### Patch Changes
- Updated dependencies [[`04b08f3`](https://github.com/esengine/esengine/commit/04b08f3f073d69beb8f4be399c774bea0acb612e)]:
- @esengine/ecs-framework@2.6.1
- @esengine/blueprint@3.0.1
## 3.0.0
### Patch Changes
- Updated dependencies []:
- @esengine/ecs-framework@2.6.0
- @esengine/blueprint@3.0.0
## 2.0.1
### Patch Changes
- Updated dependencies [[`a08a84b`](https://github.com/esengine/esengine/commit/a08a84b7db28e1140cbc637d442552747ad81c76)]:
- @esengine/ecs-framework@2.5.1
- @esengine/blueprint@2.0.1
## 2.0.0
### Patch Changes
- Updated dependencies [[`1f297ac`](https://github.com/esengine/esengine/commit/1f297ac769e37700f72fb4425639af7090898256)]:
- @esengine/ecs-framework@2.5.0
- @esengine/blueprint@2.0.0
## 1.0.3
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "@esengine/fsm",
"version": "1.0.3",
"version": "4.0.1",
"description": "Finite State Machine for ECS Framework / ECS 框架的有限状态机",
"type": "module",
"main": "./dist/index.js",

View File

@@ -1,5 +1,150 @@
# @esengine/network
## 5.0.3
### Patch Changes
- Updated dependencies [[`902c0a1`](https://github.com/esengine/esengine/commit/902c0a10749f80bd8f499b44154646379d359704)]:
- @esengine/rpc@1.1.3
## 5.0.2
### Patch Changes
- Updated dependencies []:
- @esengine/rpc@1.1.2
## 5.0.1
### Patch Changes
- Updated dependencies [[`3e5b778`](https://github.com/esengine/esengine/commit/3e5b7783beec08e247f7525184935401923ecde8)]:
- @esengine/ecs-framework@2.7.1
- @esengine/blueprint@4.0.1
## 5.0.0
### Patch Changes
- Updated dependencies [[`1f3a76a`](https://github.com/esengine/esengine/commit/1f3a76aabea2d3eb8a5eb8b73e29127da57e2028)]:
- @esengine/ecs-framework@2.7.0
- @esengine/blueprint@4.0.0
## 4.0.1
### Patch Changes
- Updated dependencies [[`04b08f3`](https://github.com/esengine/esengine/commit/04b08f3f073d69beb8f4be399c774bea0acb612e)]:
- @esengine/ecs-framework@2.6.1
- @esengine/blueprint@3.0.1
## 4.0.0
### Patch Changes
- Updated dependencies []:
- @esengine/ecs-framework@2.6.0
- @esengine/blueprint@3.0.0
## 3.0.1
### Patch Changes
- Updated dependencies [[`a08a84b`](https://github.com/esengine/esengine/commit/a08a84b7db28e1140cbc637d442552747ad81c76)]:
- @esengine/ecs-framework@2.5.1
- @esengine/blueprint@2.0.1
## 3.0.0
### Minor Changes
- [#390](https://github.com/esengine/esengine/pull/390) [`1f297ac`](https://github.com/esengine/esengine/commit/1f297ac769e37700f72fb4425639af7090898256) Thanks [@esengine](https://github.com/esengine)! - feat: ECS 网络状态同步系统
## @esengine/ecs-framework
新增 `@sync` 装饰器和二进制编解码器,支持基于 Component 的网络状态同步:
```typescript
import { Component, ECSComponent, sync } from '@esengine/ecs-framework';
@ECSComponent('Player')
class PlayerComponent extends Component {
@sync('string') name: string = '';
@sync('uint16') score: number = 0;
@sync('float32') x: number = 0;
@sync('float32') y: number = 0;
}
```
### 新增导出
- `sync` - 标记需要同步的字段装饰器
- `SyncType` - 支持的同步类型
- `SyncOperation` - 同步操作类型FULL/DELTA/SPAWN/DESPAWN
- `encodeSnapshot` / `decodeSnapshot` - 批量编解码
- `encodeSpawn` / `decodeSpawn` - 实体生成编解码
- `encodeDespawn` / `processDespawn` - 实体销毁编解码
- `ChangeTracker` - 字段级变更追踪
- `initChangeTracker` / `clearChanges` / `hasChanges` - 变更追踪工具函数
### 内部方法标记
将以下方法标记为 `@internal`,用户应通过 `Core.update()` 驱动更新:
- `Scene.update()`
- `SceneManager.update()`
- `WorldManager.updateAll()`
## @esengine/network
新增 `ComponentSyncSystem`,基于 `@sync` 装饰器自动同步组件状态:
```typescript
import { ComponentSyncSystem } from '@esengine/network';
// 服务端:编码状态
const data = syncSystem.encodeAllEntities(false);
// 客户端:解码状态
syncSystem.applySnapshot(data);
```
### 修复
- 将 `@esengine/ecs-framework` 从 devDependencies 移到 peerDependencies
## @esengine/server
新增 `ECSRoom`,带有 ECS World 支持的房间基类:
```typescript
import { ECSRoom } from '@esengine/server/ecs';
// 服务端启动
Core.create();
setInterval(() => Core.update(1 / 60), 16);
// 定义房间
class GameRoom extends ECSRoom {
onCreate() {
this.addSystem(new PhysicsSystem());
}
onJoin(player: Player) {
const entity = this.createPlayerEntity(player.id);
entity.addComponent(new PlayerComponent());
}
}
```
### 设计
- 每个 `ECSRoom` 在 `Core.worldManager` 中创建独立的 World
- `Core.update()` 统一更新 Time 和所有 World
- `onTick()` 只处理状态同步逻辑
### Patch Changes
- Updated dependencies [[`1f297ac`](https://github.com/esengine/esengine/commit/1f297ac769e37700f72fb4425639af7090898256)]:
- @esengine/ecs-framework@2.5.0
- @esengine/blueprint@2.0.0
## 2.2.0
### Minor Changes

View File

@@ -1,6 +1,6 @@
{
"name": "@esengine/network",
"version": "2.2.0",
"version": "5.0.3",
"description": "Network synchronization for multiplayer games",
"esengine": {
"plugin": true,
@@ -30,6 +30,15 @@
"dependencies": {
"@esengine/rpc": "workspace:*"
},
"peerDependencies": {
"@esengine/ecs-framework": "workspace:*",
"@esengine/blueprint": "workspace:*"
},
"peerDependenciesMeta": {
"@esengine/blueprint": {
"optional": true
}
},
"devDependencies": {
"@esengine/blueprint": "workspace:*",
"@esengine/ecs-framework": "workspace:*",

View File

@@ -133,6 +133,11 @@ export type {
EntityDeltaState,
DeltaSyncData,
DeltaCompressionConfig,
// Component sync types
ComponentSyncEventType,
ComponentSyncEvent,
ComponentSyncEventListener,
ComponentSyncConfig,
} from './sync'
export {
@@ -150,6 +155,9 @@ export {
DeltaFlags,
StateDeltaCompressor,
createStateDeltaCompressor,
// Component sync
ComponentSyncSystem,
createComponentSyncSystem,
} from './sync'
// ============================================================================

View File

@@ -0,0 +1,408 @@
/**
* @zh 组件同步系统
* @en Component Sync System
*
* @zh 基于 @sync 装饰器的组件状态同步,与 ecs-framework 的 Sync 模块集成
* @en Component state synchronization based on @sync decorator, integrated with ecs-framework Sync module
*/
import {
EntitySystem,
Matcher,
type Entity,
// Sync types
SyncOperation,
SYNC_METADATA,
CHANGE_TRACKER,
type SyncMetadata,
type ChangeTracker,
// Encoding
encodeSnapshot,
encodeSpawn,
encodeDespawn,
decodeSnapshot,
decodeSpawn,
processDespawn,
GlobalComponentRegistry,
type DecodeSnapshotResult,
type DecodeSpawnResult,
} from '@esengine/ecs-framework';
import { NetworkIdentity } from '../components/NetworkIdentity';
// =============================================================================
// Types | 类型定义
// =============================================================================
/**
* @zh 组件同步事件类型
* @en Component sync event type
*/
export type ComponentSyncEventType =
| 'entitySpawned'
| 'entityDespawned'
| 'stateUpdated';
/**
* @zh 组件同步事件
* @en Component sync event
*/
export interface ComponentSyncEvent {
type: ComponentSyncEventType;
entityId: number;
prefabType?: string;
}
/**
* @zh 组件同步事件监听器
* @en Component sync event listener
*/
export type ComponentSyncEventListener = (event: ComponentSyncEvent) => void;
/**
* @zh 组件同步配置
* @en Component sync configuration
*/
export interface ComponentSyncConfig {
/**
* @zh 是否启用增量同步
* @en Whether to enable delta sync
*/
enableDeltaSync: boolean;
/**
* @zh 同步间隔(毫秒)
* @en Sync interval in milliseconds
*/
syncInterval: number;
}
const DEFAULT_CONFIG: ComponentSyncConfig = {
enableDeltaSync: true,
syncInterval: 50, // 20 Hz
};
// =============================================================================
// ComponentSyncSystem | 组件同步系统
// =============================================================================
/**
* @zh 组件同步系统
* @en Component sync system
*
* @zh 基于 @sync 装饰器自动同步组件状态
* @en Automatically syncs component state based on @sync decorator
*
* @example
* ```typescript
* // Server-side: broadcast state
* const syncSystem = scene.getSystem(ComponentSyncSystem);
* const data = syncSystem.encodeAllEntities(false); // delta
* broadcast(data);
*
* // Client-side: receive state
* const syncSystem = scene.getSystem(ComponentSyncSystem);
* syncSystem.applySnapshot(data);
* ```
*/
export class ComponentSyncSystem extends EntitySystem {
private readonly _config: ComponentSyncConfig;
private readonly _syncEntityMap: Map<number, Entity> = new Map();
private readonly _syncListeners: Set<ComponentSyncEventListener> = new Set();
private _lastSyncTime: number = 0;
private _isServer: boolean = false;
constructor(config?: Partial<ComponentSyncConfig>, isServer: boolean = false) {
super(Matcher.all(NetworkIdentity));
this._config = { ...DEFAULT_CONFIG, ...config };
this._isServer = isServer;
}
/**
* @zh 设置是否为服务端模式
* @en Set whether in server mode
*/
public set isServer(value: boolean) {
this._isServer = value;
}
/**
* @zh 获取是否为服务端模式
* @en Get whether in server mode
*/
public get isServer(): boolean {
return this._isServer;
}
/**
* @zh 获取配置
* @en Get configuration
*/
public get config(): Readonly<ComponentSyncConfig> {
return this._config;
}
/**
* @zh 添加同步事件监听器
* @en Add sync event listener
*/
public addSyncListener(listener: ComponentSyncEventListener): void {
this._syncListeners.add(listener);
}
/**
* @zh 移除同步事件监听器
* @en Remove sync event listener
*/
public removeSyncListener(listener: ComponentSyncEventListener): void {
this._syncListeners.delete(listener);
}
/**
* @zh 注册同步组件类型
* @en Register sync component type
*
* @zh 客户端需要调用此方法注册所有需要同步的组件类型
* @en Client needs to call this to register all component types to be synced
*/
public registerComponent<T extends new () => any>(componentClass: T): void {
GlobalComponentRegistry.register(componentClass as any);
}
// =========================================================================
// Server-side: Encoding | 服务端:编码
// =========================================================================
/**
* @zh 编码所有实体状态
* @en Encode all entities state
*
* @param fullSync - @zh 是否完整同步(首次连接时使用)@en Whether to do full sync (for initial connection)
* @returns @zh 编码后的二进制数据 @en Encoded binary data
*/
public encodeAllEntities(fullSync: boolean = false): Uint8Array {
const entities = this.getMatchingEntities();
const operation = fullSync ? SyncOperation.FULL : SyncOperation.DELTA;
const data = encodeSnapshot(entities, operation);
// Clear change trackers after encoding delta
if (!fullSync) {
this._clearChangeTrackers(entities);
}
return data;
}
/**
* @zh 编码有变更的实体
* @en Encode entities with changes
*
* @returns @zh 编码后的二进制数据,如果没有变更返回 null @en Encoded binary data, or null if no changes
*/
public encodeDelta(): Uint8Array | null {
const entities = this.getMatchingEntities();
const changedEntities = entities.filter(entity => this._hasChanges(entity));
if (changedEntities.length === 0) {
return null;
}
const data = encodeSnapshot(changedEntities, SyncOperation.DELTA);
this._clearChangeTrackers(changedEntities);
return data;
}
/**
* @zh 编码实体生成消息
* @en Encode entity spawn message
*/
public encodeSpawn(entity: Entity, prefabType?: string): Uint8Array {
return encodeSpawn(entity, prefabType);
}
/**
* @zh 编码实体销毁消息
* @en Encode entity despawn message
*/
public encodeDespawn(entityId: number): Uint8Array {
return encodeDespawn(entityId);
}
// =========================================================================
// Client-side: Decoding | 客户端:解码
// =========================================================================
/**
* @zh 应用状态快照
* @en Apply state snapshot
*
* @param data - @zh 二进制数据 @en Binary data
* @returns @zh 解码结果 @en Decode result
*/
public applySnapshot(data: Uint8Array): DecodeSnapshotResult {
if (!this.scene) {
throw new Error('ComponentSyncSystem not attached to a scene');
}
const result = decodeSnapshot(this.scene, data, this._syncEntityMap);
// Emit events
for (const entityResult of result.entities) {
if (entityResult.isNew) {
this._emitEvent({
type: 'entitySpawned',
entityId: entityResult.entityId,
});
} else {
this._emitEvent({
type: 'stateUpdated',
entityId: entityResult.entityId,
});
}
}
return result;
}
/**
* @zh 应用实体生成消息
* @en Apply entity spawn message
*
* @param data - @zh 二进制数据 @en Binary data
* @returns @zh 解码结果,如果不是 SPAWN 消息返回 null @en Decode result, or null if not a SPAWN message
*/
public applySpawn(data: Uint8Array): DecodeSpawnResult | null {
if (!this.scene) {
throw new Error('ComponentSyncSystem not attached to a scene');
}
const result = decodeSpawn(this.scene, data, this._syncEntityMap);
if (result) {
this._emitEvent({
type: 'entitySpawned',
entityId: result.entity.id,
prefabType: result.prefabType,
});
}
return result;
}
/**
* @zh 应用实体销毁消息
* @en Apply entity despawn message
*
* @param data - @zh 二进制数据 @en Binary data
* @returns @zh 销毁的实体 ID 列表 @en List of despawned entity IDs
*/
public applyDespawn(data: Uint8Array): number[] {
if (!this.scene) {
throw new Error('ComponentSyncSystem not attached to a scene');
}
const entityIds = processDespawn(this.scene, data, this._syncEntityMap);
for (const entityId of entityIds) {
this._emitEvent({
type: 'entityDespawned',
entityId,
});
}
return entityIds;
}
// =========================================================================
// Entity Management | 实体管理
// =========================================================================
/**
* @zh 通过网络 ID 获取实体
* @en Get entity by network ID
*/
public getEntityById(entityId: number): Entity | undefined {
return this._syncEntityMap.get(entityId);
}
/**
* @zh 获取所有匹配的实体
* @en Get all matching entities
*/
public getMatchingEntities(): Entity[] {
return this.entities.slice();
}
// =========================================================================
// Internal | 内部方法
// =========================================================================
protected override process(entities: readonly Entity[]): void {
// Server mode: auto-sync at interval
if (this._isServer && this._config.enableDeltaSync) {
const now = Date.now();
if (now - this._lastSyncTime >= this._config.syncInterval) {
// Note: actual broadcast should be done by the user
// This just updates the sync time
this._lastSyncTime = now;
}
}
// Update entity ID map
for (const entity of entities) {
const identity = entity.getComponent(NetworkIdentity);
if (identity) {
this._syncEntityMap.set(entity.id, entity);
}
}
}
private _hasChanges(entity: Entity): boolean {
for (const component of entity.components) {
const tracker = (component as any)[CHANGE_TRACKER] as ChangeTracker | undefined;
if (tracker?.hasChanges()) {
return true;
}
}
return false;
}
private _clearChangeTrackers(entities: Entity[]): void {
for (const entity of entities) {
for (const component of entity.components) {
const tracker = (component as any)[CHANGE_TRACKER] as ChangeTracker | undefined;
if (tracker) {
tracker.clear();
}
}
}
}
private _emitEvent(event: ComponentSyncEvent): void {
for (const listener of this._syncListeners) {
try {
listener(event);
} catch (error) {
console.error('ComponentSyncSystem: event listener error:', error);
}
}
}
protected override onDestroy(): void {
this._syncEntityMap.clear();
this._syncListeners.clear();
}
}
/**
* @zh 创建组件同步系统
* @en Create component sync system
*/
export function createComponentSyncSystem(
config?: Partial<ComponentSyncConfig>,
isServer: boolean = false
): ComponentSyncSystem {
return new ComponentSyncSystem(config, isServer);
}

View File

@@ -62,3 +62,19 @@ export {
StateDeltaCompressor,
createStateDeltaCompressor
} from './StateDelta';
// =============================================================================
// 组件同步 | Component Sync (@sync decorator based)
// =============================================================================
export type {
ComponentSyncEventType,
ComponentSyncEvent,
ComponentSyncEventListener,
ComponentSyncConfig
} from './ComponentSync';
export {
ComponentSyncSystem,
createComponentSyncSystem
} from './ComponentSync';

View File

@@ -1,5 +1,53 @@
# @esengine/pathfinding
## 4.0.1
### Patch Changes
- Updated dependencies [[`3e5b778`](https://github.com/esengine/esengine/commit/3e5b7783beec08e247f7525184935401923ecde8)]:
- @esengine/ecs-framework@2.7.1
- @esengine/blueprint@4.0.1
## 4.0.0
### Patch Changes
- Updated dependencies [[`1f3a76a`](https://github.com/esengine/esengine/commit/1f3a76aabea2d3eb8a5eb8b73e29127da57e2028)]:
- @esengine/ecs-framework@2.7.0
- @esengine/blueprint@4.0.0
## 3.0.1
### Patch Changes
- Updated dependencies [[`04b08f3`](https://github.com/esengine/esengine/commit/04b08f3f073d69beb8f4be399c774bea0acb612e)]:
- @esengine/ecs-framework@2.6.1
- @esengine/blueprint@3.0.1
## 3.0.0
### Patch Changes
- Updated dependencies []:
- @esengine/ecs-framework@2.6.0
- @esengine/blueprint@3.0.0
## 2.0.1
### Patch Changes
- Updated dependencies [[`a08a84b`](https://github.com/esengine/esengine/commit/a08a84b7db28e1140cbc637d442552747ad81c76)]:
- @esengine/ecs-framework@2.5.1
- @esengine/blueprint@2.0.1
## 2.0.0
### Patch Changes
- Updated dependencies [[`1f297ac`](https://github.com/esengine/esengine/commit/1f297ac769e37700f72fb4425639af7090898256)]:
- @esengine/ecs-framework@2.5.0
- @esengine/blueprint@2.0.0
## 1.0.4
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "@esengine/pathfinding",
"version": "1.1.0",
"version": "4.0.1",
"description": "寻路系统 | Pathfinding System - A*, Grid, NavMesh",
"type": "module",
"main": "./dist/index.js",

View File

@@ -1,5 +1,53 @@
# @esengine/procgen
## 4.0.1
### Patch Changes
- Updated dependencies [[`3e5b778`](https://github.com/esengine/esengine/commit/3e5b7783beec08e247f7525184935401923ecde8)]:
- @esengine/ecs-framework@2.7.1
- @esengine/blueprint@4.0.1
## 4.0.0
### Patch Changes
- Updated dependencies [[`1f3a76a`](https://github.com/esengine/esengine/commit/1f3a76aabea2d3eb8a5eb8b73e29127da57e2028)]:
- @esengine/ecs-framework@2.7.0
- @esengine/blueprint@4.0.0
## 3.0.1
### Patch Changes
- Updated dependencies [[`04b08f3`](https://github.com/esengine/esengine/commit/04b08f3f073d69beb8f4be399c774bea0acb612e)]:
- @esengine/ecs-framework@2.6.1
- @esengine/blueprint@3.0.1
## 3.0.0
### Patch Changes
- Updated dependencies []:
- @esengine/ecs-framework@2.6.0
- @esengine/blueprint@3.0.0
## 2.0.1
### Patch Changes
- Updated dependencies [[`a08a84b`](https://github.com/esengine/esengine/commit/a08a84b7db28e1140cbc637d442552747ad81c76)]:
- @esengine/ecs-framework@2.5.1
- @esengine/blueprint@2.0.1
## 2.0.0
### Patch Changes
- Updated dependencies [[`1f297ac`](https://github.com/esengine/esengine/commit/1f297ac769e37700f72fb4425639af7090898256)]:
- @esengine/ecs-framework@2.5.0
- @esengine/blueprint@2.0.0
## 1.0.3
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "@esengine/procgen",
"version": "1.0.3",
"version": "4.0.1",
"description": "Procedural generation tools for ECS Framework / ECS 框架的程序化生成工具",
"type": "module",
"main": "./dist/index.js",

View File

@@ -1,5 +1,93 @@
# @esengine/rpc
## 1.1.3
### Patch Changes
- [#404](https://github.com/esengine/esengine/pull/404) [`902c0a1`](https://github.com/esengine/esengine/commit/902c0a10749f80bd8f499b44154646379d359704) Thanks [@esengine](https://github.com/esengine)! - feat(server): add HTTP file-based routing support / 添加 HTTP 文件路由支持
New feature that allows organizing HTTP routes in separate files, similar to API and message handlers.
新功能:支持将 HTTP 路由组织在独立文件中,类似于 API 和消息处理器的文件路由方式。
```typescript
// src/http/login.ts
import { defineHttp } from '@esengine/server';
export default defineHttp<{ username: string; password: string }>({
method: 'POST',
handler(req, res) {
const { username, password } = req.body;
res.json({ token: '...', userId: '...' });
}
});
```
Server configuration / 服务器配置:
```typescript
const server = await createServer({
port: 8080,
httpDir: 'src/http', // HTTP routes directory / HTTP 路由目录
httpPrefix: '/api', // Route prefix / 路由前缀
cors: true
});
```
File naming convention / 文件命名规则:
- `login.ts` → POST /api/login
- `users/profile.ts` → POST /api/users/profile
- `users/[id].ts` → POST /api/users/:id (dynamic routes / 动态路由)
- Set `method: 'GET'` in defineHttp for GET requests / 在 defineHttp 中设置 `method: 'GET'` 以处理 GET 请求
Also includes / 还包括:
- `defineHttp<TBody>()` helper for type-safe route definitions / 类型安全的路由定义辅助函数
- Support for merging file routes with inline `http` config / 支持文件路由与内联 `http` 配置合并
- RPC server supports attaching to existing HTTP server via `server` option / RPC 服务器支持通过 `server` 选项附加到现有 HTTP 服务器
## 1.1.2
### Patch Changes
- feat(server): add HTTP file-based routing support
New feature that allows organizing HTTP routes in separate files, similar to API and message handlers:
```typescript
// src/http/login.ts
import { defineHttp } from '@esengine/server';
export default defineHttp<{ username: string; password: string }>({
method: 'POST',
handler(req, res) {
const { username, password } = req.body;
// ... authentication logic
res.json({ token: '...', userId: '...' });
}
});
```
Server configuration:
```typescript
const server = await createServer({
port: 8080,
httpDir: 'src/http', // HTTP routes directory
httpPrefix: '/api', // Route prefix
cors: true
});
```
File naming convention:
- `login.ts` → POST /api/login
- `users/profile.ts` → POST /api/users/profile
- `users/[id].ts` → POST /api/users/:id (dynamic routes)
- Set `method: 'GET'` in defineHttp for GET requests
Also includes:
- `defineHttp<TBody>()` helper function for type-safe route definitions
- Support for merging file routes with inline `http` config
- RPC server now supports attaching to existing HTTP server via `server` option
## 1.1.1
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "@esengine/rpc",
"version": "1.1.1",
"version": "1.1.3",
"description": "Elegant type-safe RPC library for ESEngine",
"type": "module",
"main": "./dist/index.js",

View File

@@ -4,6 +4,7 @@
*/
import { WebSocketServer, WebSocket } from 'ws'
import type { Server as HttpServer } from 'node:http'
import type {
ProtocolDef,
ApiNames,
@@ -66,10 +67,19 @@ type MsgHandlers<P extends ProtocolDef, TConnData> = {
*/
export interface ServeOptions<P extends ProtocolDef, TConnData = unknown> {
/**
* @zh 监听端口
* @en Listen port
* @zh 监听端口(与 server 二选一)
* @en Listen port (mutually exclusive with server)
*/
port: number
port?: number
/**
* @zh 已有的 HTTP 服务器(与 port 二选一)
* @en Existing HTTP server (mutually exclusive with port)
*
* @zh 使用此选项可以在同一端口同时支持 HTTP 和 WebSocket
* @en Use this option to support both HTTP and WebSocket on the same port
*/
server?: HttpServer
/**
* @zh API 处理器
@@ -280,7 +290,16 @@ export function serve<P extends ProtocolDef, TConnData = unknown>(
async start() {
return new Promise((resolve) => {
wss = new WebSocketServer({ port: options.port })
// 根据配置创建 WebSocketServer
if (options.server) {
// 附加到已有的 HTTP 服务器
wss = new WebSocketServer({ server: options.server })
} else if (options.port) {
// 独立创建
wss = new WebSocketServer({ port: options.port })
} else {
throw new Error('Either port or server must be provided')
}
wss.on('connection', async (ws, req) => {
const id = String(++connIdCounter)
@@ -318,10 +337,16 @@ export function serve<P extends ProtocolDef, TConnData = unknown>(
await options.onConnect?.(conn)
})
wss.on('listening', () => {
options.onStart?.(options.port)
// 如果使用已有的 HTTP 服务器WebSocketServer 不会触发 listening 事件
if (options.server) {
options.onStart?.(0) // 端口由 HTTP 服务器管理
resolve()
})
} else {
wss.on('listening', () => {
options.onStart?.(options.port!)
resolve()
})
}
})
},

View File

@@ -1,5 +1,248 @@
# @esengine/server
## 4.2.0
### Minor Changes
- [#404](https://github.com/esengine/esengine/pull/404) [`902c0a1`](https://github.com/esengine/esengine/commit/902c0a10749f80bd8f499b44154646379d359704) Thanks [@esengine](https://github.com/esengine)! - feat(server): add HTTP file-based routing support / 添加 HTTP 文件路由支持
New feature that allows organizing HTTP routes in separate files, similar to API and message handlers.
新功能:支持将 HTTP 路由组织在独立文件中,类似于 API 和消息处理器的文件路由方式。
```typescript
// src/http/login.ts
import { defineHttp } from '@esengine/server';
export default defineHttp<{ username: string; password: string }>({
method: 'POST',
handler(req, res) {
const { username, password } = req.body;
res.json({ token: '...', userId: '...' });
}
});
```
Server configuration / 服务器配置:
```typescript
const server = await createServer({
port: 8080,
httpDir: 'src/http', // HTTP routes directory / HTTP 路由目录
httpPrefix: '/api', // Route prefix / 路由前缀
cors: true
});
```
File naming convention / 文件命名规则:
- `login.ts` → POST /api/login
- `users/profile.ts` → POST /api/users/profile
- `users/[id].ts` → POST /api/users/:id (dynamic routes / 动态路由)
- Set `method: 'GET'` in defineHttp for GET requests / 在 defineHttp 中设置 `method: 'GET'` 以处理 GET 请求
Also includes / 还包括:
- `defineHttp<TBody>()` helper for type-safe route definitions / 类型安全的路由定义辅助函数
- Support for merging file routes with inline `http` config / 支持文件路由与内联 `http` 配置合并
- RPC server supports attaching to existing HTTP server via `server` option / RPC 服务器支持通过 `server` 选项附加到现有 HTTP 服务器
### Patch Changes
- Updated dependencies [[`902c0a1`](https://github.com/esengine/esengine/commit/902c0a10749f80bd8f499b44154646379d359704)]:
- @esengine/rpc@1.1.3
## 4.1.0
### Minor Changes
- feat(server): add HTTP file-based routing support
New feature that allows organizing HTTP routes in separate files, similar to API and message handlers:
```typescript
// src/http/login.ts
import { defineHttp } from '@esengine/server';
export default defineHttp<{ username: string; password: string }>({
method: 'POST',
handler(req, res) {
const { username, password } = req.body;
// ... authentication logic
res.json({ token: '...', userId: '...' });
}
});
```
Server configuration:
```typescript
const server = await createServer({
port: 8080,
httpDir: 'src/http', // HTTP routes directory
httpPrefix: '/api', // Route prefix
cors: true
});
```
File naming convention:
- `login.ts` → POST /api/login
- `users/profile.ts` → POST /api/users/profile
- `users/[id].ts` → POST /api/users/:id (dynamic routes)
- Set `method: 'GET'` in defineHttp for GET requests
Also includes:
- `defineHttp<TBody>()` helper function for type-safe route definitions
- Support for merging file routes with inline `http` config
- RPC server now supports attaching to existing HTTP server via `server` option
### Patch Changes
- Updated dependencies []:
- @esengine/rpc@1.1.2
## 4.0.0
### Patch Changes
- Updated dependencies [[`1f3a76a`](https://github.com/esengine/esengine/commit/1f3a76aabea2d3eb8a5eb8b73e29127da57e2028)]:
- @esengine/ecs-framework@2.7.0
## 3.0.0
### Minor Changes
- feat(ecs): 添加 @NetworkEntity 装饰器,支持自动广播实体生成/销毁
### 新功能
**@NetworkEntity 装饰器**
- 标记组件为网络实体,自动广播 spawn/despawn 消息
- 支持 `autoSpawn` 和 `autoDespawn` 配置选项
- 通过事件系统(`ECSEventType.COMPONENT_ADDED` / `ECSEventType.ENTITY_DESTROYED`)实现
**ECSRoom 增强**
- 新增 `enableAutoNetworkEntity` 配置选项(默认启用)
- 自动监听组件添加和实体销毁事件
- 简化 GameRoom 实现,无需手动回调
### 改进
**Entity 事件**
- `Entity.destroy()` 现在发出 `entity:destroyed` 事件
- `Entity.active` 变化时发出 `entity:enabled` / `entity:disabled` 事件
- 使用 `ECSEventType` 常量替代硬编码字符串
### 使用示例
```typescript
import { Component, ECSComponent, sync, NetworkEntity } from '@esengine/ecs-framework';
@ECSComponent('Enemy')
@NetworkEntity('Enemy')
class EnemyComponent extends Component {
@sync('float32') x: number = 0;
@sync('float32') y: number = 0;
}
// 服务端
const entity = scene.createEntity('Enemy');
entity.addComponent(new EnemyComponent()); // 自动广播 spawn
entity.destroy(); // 自动广播 despawn
```
### Patch Changes
- Updated dependencies []:
- @esengine/ecs-framework@2.6.0
## 2.0.0
### Minor Changes
- [#390](https://github.com/esengine/esengine/pull/390) [`1f297ac`](https://github.com/esengine/esengine/commit/1f297ac769e37700f72fb4425639af7090898256) Thanks [@esengine](https://github.com/esengine)! - feat: ECS 网络状态同步系统
## @esengine/ecs-framework
新增 `@sync` 装饰器和二进制编解码器,支持基于 Component 的网络状态同步:
```typescript
import { Component, ECSComponent, sync } from '@esengine/ecs-framework';
@ECSComponent('Player')
class PlayerComponent extends Component {
@sync('string') name: string = '';
@sync('uint16') score: number = 0;
@sync('float32') x: number = 0;
@sync('float32') y: number = 0;
}
```
### 新增导出
- `sync` - 标记需要同步的字段装饰器
- `SyncType` - 支持的同步类型
- `SyncOperation` - 同步操作类型FULL/DELTA/SPAWN/DESPAWN
- `encodeSnapshot` / `decodeSnapshot` - 批量编解码
- `encodeSpawn` / `decodeSpawn` - 实体生成编解码
- `encodeDespawn` / `processDespawn` - 实体销毁编解码
- `ChangeTracker` - 字段级变更追踪
- `initChangeTracker` / `clearChanges` / `hasChanges` - 变更追踪工具函数
### 内部方法标记
将以下方法标记为 `@internal`,用户应通过 `Core.update()` 驱动更新:
- `Scene.update()`
- `SceneManager.update()`
- `WorldManager.updateAll()`
## @esengine/network
新增 `ComponentSyncSystem`,基于 `@sync` 装饰器自动同步组件状态:
```typescript
import { ComponentSyncSystem } from '@esengine/network';
// 服务端:编码状态
const data = syncSystem.encodeAllEntities(false);
// 客户端:解码状态
syncSystem.applySnapshot(data);
```
### 修复
- 将 `@esengine/ecs-framework` 从 devDependencies 移到 peerDependencies
## @esengine/server
新增 `ECSRoom`,带有 ECS World 支持的房间基类:
```typescript
import { ECSRoom } from '@esengine/server/ecs';
// 服务端启动
Core.create();
setInterval(() => Core.update(1 / 60), 16);
// 定义房间
class GameRoom extends ECSRoom {
onCreate() {
this.addSystem(new PhysicsSystem());
}
onJoin(player: Player) {
const entity = this.createPlayerEntity(player.id);
entity.addComponent(new PlayerComponent());
}
}
```
### 设计
- 每个 `ECSRoom` 在 `Core.worldManager` 中创建独立的 World
- `Core.update()` 统一更新 Time 和所有 World
- `onTick()` 只处理状态同步逻辑
### Patch Changes
- Updated dependencies [[`1f297ac`](https://github.com/esengine/esengine/commit/1f297ac769e37700f72fb4425639af7090898256)]:
- @esengine/ecs-framework@2.5.0
## 1.3.0
### Minor Changes

View File

@@ -1,6 +1,6 @@
{
"name": "@esengine/server",
"version": "1.3.0",
"version": "4.2.0",
"description": "Game server framework for ESEngine with file-based routing",
"type": "module",
"main": "./dist/index.js",
@@ -26,6 +26,10 @@
"./testing": {
"import": "./dist/testing/index.js",
"types": "./dist/testing/index.d.ts"
},
"./ecs": {
"import": "./dist/ecs/index.js",
"types": "./dist/ecs/index.d.ts"
}
},
"files": [
@@ -46,14 +50,19 @@
},
"peerDependencies": {
"ws": ">=8.0.0",
"jsonwebtoken": ">=9.0.0"
"jsonwebtoken": ">=9.0.0",
"@esengine/ecs-framework": ">=2.7.1"
},
"peerDependenciesMeta": {
"jsonwebtoken": {
"optional": true
},
"@esengine/ecs-framework": {
"optional": true
}
},
"devDependencies": {
"@esengine/ecs-framework": "workspace:*",
"@types/jsonwebtoken": "^9.0.0",
"@types/node": "^20.0.0",
"@types/ws": "^8.5.13",

View File

@@ -4,6 +4,7 @@
*/
import * as path from 'node:path'
import { createServer as createHttpServer, type Server as HttpServer } from 'node:http'
import { serve, type RpcServer } from '@esengine/rpc/server'
import { rpc } from '@esengine/rpc'
import type {
@@ -14,18 +15,23 @@ import type {
MsgContext,
LoadedApiHandler,
LoadedMsgHandler,
LoadedHttpHandler,
} from '../types/index.js'
import { loadApiHandlers, loadMsgHandlers } from '../router/loader.js'
import type { HttpRoutes, HttpHandler } from '../http/types.js'
import { loadApiHandlers, loadMsgHandlers, loadHttpHandlers } from '../router/loader.js'
import { RoomManager, type RoomClass, type Room } from '../room/index.js'
import { createHttpRouter } from '../http/router.js'
/**
* @zh 默认配置
* @en Default configuration
*/
const DEFAULT_CONFIG: Required<Omit<ServerConfig, 'onStart' | 'onConnect' | 'onDisconnect'>> = {
const DEFAULT_CONFIG: Required<Omit<ServerConfig, 'onStart' | 'onConnect' | 'onDisconnect' | 'http' | 'cors' | 'httpDir' | 'httpPrefix'>> & { httpDir: string; httpPrefix: string } = {
port: 3000,
apiDir: 'src/api',
msgDir: 'src/msg',
httpDir: 'src/http',
httpPrefix: '/api',
tickRate: 20,
}
@@ -56,12 +62,53 @@ export async function createServer(config: ServerConfig = {}): Promise<GameServe
const apiHandlers = await loadApiHandlers(path.resolve(cwd, opts.apiDir))
const msgHandlers = await loadMsgHandlers(path.resolve(cwd, opts.msgDir))
// 加载 HTTP 文件路由
const httpDir = config.httpDir ?? opts.httpDir
const httpPrefix = config.httpPrefix ?? opts.httpPrefix
const httpHandlers = await loadHttpHandlers(path.resolve(cwd, httpDir), httpPrefix)
if (apiHandlers.length > 0) {
console.log(`[Server] Loaded ${apiHandlers.length} API handlers`)
}
if (msgHandlers.length > 0) {
console.log(`[Server] Loaded ${msgHandlers.length} message handlers`)
}
if (httpHandlers.length > 0) {
console.log(`[Server] Loaded ${httpHandlers.length} HTTP handlers`)
}
// 合并 HTTP 路由(文件路由 + 内联路由)
const mergedHttpRoutes: HttpRoutes = {}
// 先添加文件路由
for (const handler of httpHandlers) {
const existingRoute = mergedHttpRoutes[handler.route]
if (existingRoute && typeof existingRoute !== 'function') {
(existingRoute as Record<string, HttpHandler>)[handler.method] = handler.definition.handler
} else {
mergedHttpRoutes[handler.route] = {
[handler.method]: handler.definition.handler,
}
}
}
// 再添加内联路由(覆盖文件路由)
if (config.http) {
for (const [route, handlerOrMethods] of Object.entries(config.http)) {
if (typeof handlerOrMethods === 'function') {
mergedHttpRoutes[route] = handlerOrMethods
} else {
const existing = mergedHttpRoutes[route]
if (existing && typeof existing !== 'function') {
Object.assign(existing, handlerOrMethods)
} else {
mergedHttpRoutes[route] = handlerOrMethods
}
}
}
}
const hasHttpRoutes = Object.keys(mergedHttpRoutes).length > 0
// 动态构建协议
const apiDefs: Record<string, ReturnType<typeof rpc.api>> = {
@@ -90,6 +137,7 @@ export async function createServer(config: ServerConfig = {}): Promise<GameServe
let currentTick = 0
let tickInterval: ReturnType<typeof setInterval> | null = null
let rpcServer: RpcServer<typeof protocol, Record<string, unknown>> | null = null
let httpServer: HttpServer | null = null
// 房间管理器(立即初始化,以便 define() 可在 start() 前调用)
const roomManager = new RoomManager((conn, type, data) => {
@@ -200,26 +248,68 @@ export async function createServer(config: ServerConfig = {}): Promise<GameServe
}
}
rpcServer = serve(protocol, {
port: opts.port,
createConnData: () => ({}),
onStart: (p) => {
console.log(`[Server] Started on ws://localhost:${p}`)
opts.onStart?.(p)
},
onConnect: async (conn) => {
await config.onConnect?.(conn as ServerConnection)
},
onDisconnect: async (conn) => {
// 玩家断线时自动离开房间
await roomManager?.leave(conn.id, 'disconnected')
await config.onDisconnect?.(conn as ServerConnection)
},
api: apiHandlersObj as any,
msg: msgHandlersObj as any,
})
// 如果有 HTTP 路由,创建 HTTP 服务器
if (hasHttpRoutes) {
const httpRouter = createHttpRouter(mergedHttpRoutes, config.cors ?? true)
await rpcServer.start()
httpServer = createHttpServer(async (req, res) => {
// 先尝试 HTTP 路由
const handled = await httpRouter(req, res)
if (!handled) {
// 未匹配的请求返回 404
res.statusCode = 404
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify({ error: 'Not Found' }))
}
})
// 使用 HTTP 服务器创建 RPC
rpcServer = serve(protocol, {
server: httpServer,
createConnData: () => ({}),
onStart: () => {
console.log(`[Server] Started on http://localhost:${opts.port}`)
opts.onStart?.(opts.port)
},
onConnect: async (conn) => {
await config.onConnect?.(conn as ServerConnection)
},
onDisconnect: async (conn) => {
await roomManager?.leave(conn.id, 'disconnected')
await config.onDisconnect?.(conn as ServerConnection)
},
api: apiHandlersObj as any,
msg: msgHandlersObj as any,
})
await rpcServer.start()
// 启动 HTTP 服务器
await new Promise<void>((resolve) => {
httpServer!.listen(opts.port, () => resolve())
})
} else {
// 仅 WebSocket 模式
rpcServer = serve(protocol, {
port: opts.port,
createConnData: () => ({}),
onStart: (p) => {
console.log(`[Server] Started on ws://localhost:${p}`)
opts.onStart?.(p)
},
onConnect: async (conn) => {
await config.onConnect?.(conn as ServerConnection)
},
onDisconnect: async (conn) => {
await roomManager?.leave(conn.id, 'disconnected')
await config.onDisconnect?.(conn as ServerConnection)
},
api: apiHandlersObj as any,
msg: msgHandlersObj as any,
})
await rpcServer.start()
}
// 启动 tick 循环
if (opts.tickRate > 0) {
@@ -238,6 +328,15 @@ export async function createServer(config: ServerConfig = {}): Promise<GameServe
await rpcServer.stop()
rpcServer = null
}
if (httpServer) {
await new Promise<void>((resolve, reject) => {
httpServer!.close((err) => {
if (err) reject(err)
else resolve()
})
})
httpServer = null
}
},
broadcast(name, data) {

View File

@@ -0,0 +1,348 @@
/**
* @zh ECSRoom 集成测试
* @en ECSRoom integration tests
*/
import { describe, it, expect, beforeEach, afterEach, beforeAll, afterAll } from 'vitest'
import {
Core,
Component,
ECSComponent,
sync,
initChangeTracker,
getSyncMetadata,
registerSyncComponent,
} from '@esengine/ecs-framework'
import { createTestEnv, type TestEnvironment, wait } from '../testing/TestServer.js'
import { ECSRoom } from './ECSRoom.js'
import type { Player } from '../room/Player.js'
import { onMessage } from '../room/decorators.js'
// ============================================================================
// Test Components | 测试组件
// ============================================================================
@ECSComponent('ECSRoomTest_PlayerComponent')
class PlayerComponent extends Component {
@sync('string') name: string = ''
@sync('uint16') score: number = 0
@sync('float32') x: number = 0
@sync('float32') y: number = 0
}
@ECSComponent('ECSRoomTest_HealthComponent')
class HealthComponent extends Component {
@sync('int32') current: number = 100
@sync('int32') max: number = 100
}
// ============================================================================
// Test Room | 测试房间
// ============================================================================
interface TestRoomState {
gameStarted: boolean
}
interface TestPlayerData {
nickname: string
}
class TestECSRoom extends ECSRoom<TestRoomState, TestPlayerData> {
state: TestRoomState = {
gameStarted: false,
}
onCreate(): void {
// 可以在这里添加系统
}
onJoin(player: Player<TestPlayerData>): void {
const entity = this.createPlayerEntity(player.id)
const comp = entity.addComponent(new PlayerComponent())
comp.name = player.data.nickname || `Player_${player.id.slice(-4)}`
comp.x = Math.random() * 100
comp.y = Math.random() * 100
this.broadcast('PlayerJoined', {
playerId: player.id,
name: comp.name,
})
}
async onLeave(player: Player<TestPlayerData>, reason?: string): Promise<void> {
await super.onLeave(player, reason)
this.broadcast('PlayerLeft', { playerId: player.id })
}
@onMessage('Move')
handleMove(data: { x: number; y: number }, player: Player<TestPlayerData>): void {
const entity = this.getPlayerEntity(player.id)
if (entity) {
const comp = entity.getComponent(PlayerComponent)
if (comp) {
comp.x = data.x
comp.y = data.y
}
}
}
@onMessage('AddScore')
handleAddScore(data: { amount: number }, player: Player<TestPlayerData>): void {
const entity = this.getPlayerEntity(player.id)
if (entity) {
const comp = entity.getComponent(PlayerComponent)
if (comp) {
comp.score += data.amount
}
}
}
@onMessage('Ping')
handlePing(_data: unknown, player: Player<TestPlayerData>): void {
player.send('Pong', { timestamp: Date.now() })
}
getWorld() {
return this.world
}
getScene() {
return this.scene
}
getPlayerEntityCount(): number {
return this.scene.entities.buffer.length
}
}
// ============================================================================
// Test Suites | 测试套件
// ============================================================================
describe('ECSRoom Integration Tests', () => {
let env: TestEnvironment
beforeAll(() => {
Core.create()
registerSyncComponent('ECSRoomTest_PlayerComponent', PlayerComponent)
registerSyncComponent('ECSRoomTest_HealthComponent', HealthComponent)
})
afterAll(() => {
Core.destroy()
})
beforeEach(async () => {
env = await createTestEnv({ tickRate: 20 })
})
afterEach(async () => {
await env.cleanup()
})
// ========================================================================
// Room Creation | 房间创建
// ========================================================================
describe('Room Creation', () => {
it('should create ECSRoom with World and Scene', async () => {
env.server.define('ecs-test', TestECSRoom)
const client = await env.createClient()
await client.joinRoom('ecs-test')
expect(client.roomId).toBeDefined()
})
it('should have World managed by Core.worldManager', async () => {
env.server.define('ecs-test', TestECSRoom)
const client = await env.createClient()
await client.joinRoom('ecs-test')
// 验证 World 正常创建(通过消息通信验证)
const pongPromise = client.waitForRoomMessage<{ timestamp: number }>('Pong')
client.sendToRoom('Ping', {})
const pong = await pongPromise
expect(pong.timestamp).toBeGreaterThan(0)
})
})
// ========================================================================
// Player Entity Management | 玩家实体管理
// ========================================================================
describe('Player Entity Management', () => {
it('should create player entity on join', async () => {
env.server.define('ecs-test', TestECSRoom)
const client1 = await env.createClient()
const { roomId } = await client1.joinRoom('ecs-test')
// 等待第二个玩家加入时收到广播
const joinPromise = client1.waitForRoomMessage<{ playerId: string; name: string }>(
'PlayerJoined'
)
const client2 = await env.createClient()
await client2.joinRoomById(roomId)
const joinMsg = await joinPromise
expect(joinMsg.playerId).toBe(client2.playerId)
expect(joinMsg.name).toContain('Player_')
})
it('should destroy player entity on leave', async () => {
env.server.define('ecs-test', TestECSRoom)
const client1 = await env.createClient()
const { roomId } = await client1.joinRoom('ecs-test')
const client2 = await env.createClient()
await client2.joinRoomById(roomId)
const leavePromise = client1.waitForRoomMessage<{ playerId: string }>('PlayerLeft')
await client2.leaveRoom()
const leaveMsg = await leavePromise
expect(leaveMsg.playerId).toBeDefined()
})
})
// ========================================================================
// Component Sync | 组件同步
// ========================================================================
describe('Component State Updates', () => {
it('should update component via message handler', async () => {
env.server.define('ecs-test', TestECSRoom)
const client = await env.createClient()
await client.joinRoom('ecs-test')
client.sendToRoom('Move', { x: 100, y: 200 })
// 等待处理
await wait(50)
// 验证 Ping/Pong 仍能工作(房间仍活跃)
const pongPromise = client.waitForRoomMessage<{ timestamp: number }>('Pong')
client.sendToRoom('Ping', {})
const pong = await pongPromise
expect(pong.timestamp).toBeGreaterThan(0)
})
it('should handle AddScore message', async () => {
env.server.define('ecs-test', TestECSRoom)
const client = await env.createClient()
await client.joinRoom('ecs-test')
client.sendToRoom('AddScore', { amount: 50 })
client.sendToRoom('AddScore', { amount: 25 })
await wait(50)
// 确认房间仍然活跃
const pongPromise = client.waitForRoomMessage<{ timestamp: number }>('Pong')
client.sendToRoom('Ping', {})
await pongPromise
})
})
// ========================================================================
// Sync Broadcast | 同步广播
// ========================================================================
describe('State Sync Broadcast', () => {
it('should receive $sync messages when enabled', async () => {
env.server.define('ecs-test', TestECSRoom)
const client = await env.createClient()
await client.joinRoom('ecs-test')
// 触发状态变更
client.sendToRoom('Move', { x: 50, y: 75 })
// 等待 tick 处理
await wait(200)
// 检查是否收到 $sync 消息
const hasSync = client.hasReceivedMessage('RoomMessage')
expect(hasSync).toBe(true)
})
})
// ========================================================================
// Multi-player Sync | 多玩家同步
// ========================================================================
describe('Multi-player Scenarios', () => {
it('should handle multiple players in same room', async () => {
env.server.define('ecs-test', TestECSRoom)
const client1 = await env.createClient()
const { roomId } = await client1.joinRoom('ecs-test')
const client2 = await env.createClient()
const joinPromise = client1.waitForRoomMessage<{ playerId: string }>('PlayerJoined')
await client2.joinRoomById(roomId)
const joinMsg = await joinPromise
expect(joinMsg.playerId).toBe(client2.playerId)
})
it('should broadcast to all players on state change', async () => {
env.server.define('ecs-test', TestECSRoom)
const client1 = await env.createClient()
const { roomId } = await client1.joinRoom('ecs-test')
const client2 = await env.createClient()
// client1 等待收到 client2 加入的广播
const joinPromise = client1.waitForRoomMessage<{ playerId: string }>('PlayerJoined')
await client2.joinRoomById(roomId)
const joinMsg = await joinPromise
expect(joinMsg.playerId).toBe(client2.playerId)
// 验证每个客户端都能独立通信
const pong1Promise = client1.waitForRoomMessage<{ timestamp: number }>('Pong')
client1.sendToRoom('Ping', {})
const pong1 = await pong1Promise
expect(pong1.timestamp).toBeGreaterThan(0)
const pong2Promise = client2.waitForRoomMessage<{ timestamp: number }>('Pong')
client2.sendToRoom('Ping', {})
const pong2 = await pong2Promise
expect(pong2.timestamp).toBeGreaterThan(0)
})
})
// ========================================================================
// Cleanup | 清理
// ========================================================================
describe('Room Cleanup', () => {
it('should cleanup World on dispose', async () => {
env.server.define('ecs-test', TestECSRoom)
const client = await env.createClient()
await client.joinRoom('ecs-test')
await client.leaveRoom()
// 等待自动销毁
await wait(100)
// 房间应该已销毁
expect(client.roomId).toBeNull()
})
})
})

View File

@@ -0,0 +1,405 @@
/**
* @zh ECS 房间基类
* @en ECS Room base class
*/
import {
Core,
Scene,
World,
Entity,
EntitySystem,
type Component,
// Sync
SyncOperation,
SYNC_METADATA,
CHANGE_TRACKER,
type SyncMetadata,
type ChangeTracker,
encodeSnapshot,
encodeSpawn,
encodeDespawn,
initChangeTracker,
// Network Entity
NETWORK_ENTITY_METADATA,
type NetworkEntityMetadata,
// Events
ECSEventType,
} from '@esengine/ecs-framework';
import { Room, type RoomOptions } from '../room/Room.js';
import type { Player } from '../room/Player.js';
// =============================================================================
// Types | 类型定义
// =============================================================================
/**
* @zh ECS 房间配置
* @en ECS room configuration
*/
export interface ECSRoomConfig {
/**
* @zh 状态同步间隔(毫秒)
* @en State sync interval in milliseconds
*/
syncInterval: number;
/**
* @zh 是否启用增量同步
* @en Whether to enable delta sync
*/
enableDeltaSync: boolean;
/**
* @zh 是否启用自动网络实体广播(基于 @NetworkEntity 装饰器)
* @en Whether to enable automatic network entity broadcasting (based on @NetworkEntity decorator)
* @default true
*/
enableAutoNetworkEntity: boolean;
}
const DEFAULT_ECS_CONFIG: ECSRoomConfig = {
syncInterval: 50, // 20 Hz
enableDeltaSync: true,
enableAutoNetworkEntity: true,
};
/**
* @zh 网络实体标识组件
* @en Network entity identity component
*/
const NETWORK_ENTITY_OWNER = Symbol('NetworkEntityOwner');
// =============================================================================
// ECSRoom | ECS 房间
// =============================================================================
/**
* @zh ECS 房间基类,带有 ECS World 支持和自动状态同步
* @en ECS Room base class with ECS World support and automatic state synchronization
*
* @example
* ```typescript
* // 服务端启动
* Core.create();
* setInterval(() => Core.update(1/60), 16);
*
* // 定义房间
* class GameRoom extends ECSRoom {
* onCreate() {
* this.addSystem(new PhysicsSystem());
* }
*
* onJoin(player: Player) {
* const entity = this.createPlayerEntity(player.id);
* entity.addComponent(new PlayerComponent());
* }
* }
* ```
*/
export abstract class ECSRoom<TState = any, TPlayerData = Record<string, unknown>> extends Room<TState, TPlayerData> {
/**
* @zh ECS World由 Core.worldManager 管理)
* @en ECS World (managed by Core.worldManager)
*/
protected readonly world: World;
/**
* @zh World 在 WorldManager 中的 ID
* @en World ID in WorldManager
*/
protected readonly worldId: string;
/**
* @zh 房间的主场景
* @en Room's main scene
*/
protected readonly scene: Scene;
/**
* @zh ECS 配置
* @en ECS configuration
*/
protected readonly ecsConfig: ECSRoomConfig;
/**
* @zh 玩家 ID 到实体的映射
* @en Player ID to Entity mapping
*/
private readonly _playerEntities: Map<string, Entity> = new Map();
/**
* @zh 网络实体映射(实体 ID -> prefabType
* @en Network entity mapping (entity ID -> prefabType)
*/
private readonly _networkEntities: Map<number, string> = new Map();
/**
* @zh 上次同步时间
* @en Last sync time
*/
private _lastSyncTime: number = 0;
constructor(ecsConfig?: Partial<ECSRoomConfig>) {
super();
this.ecsConfig = { ...DEFAULT_ECS_CONFIG, ...ecsConfig };
this.worldId = `room_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
this.world = Core.worldManager.createWorld(this.worldId);
this.scene = this.world.createScene('game');
this.world.setSceneActive('game', true);
this.world.start();
// 设置自动网络实体广播
if (this.ecsConfig.enableAutoNetworkEntity) {
this._setupAutoNetworkEntity();
}
}
/**
* @zh 设置自动网络实体广播
* @en Setup automatic network entity broadcasting
*/
private _setupAutoNetworkEntity(): void {
// 监听组件添加事件,自动广播 spawn
this.scene.eventSystem.on(ECSEventType.COMPONENT_ADDED, (event: any) => {
const { entity, component } = event;
const metadata: NetworkEntityMetadata | undefined =
(component.constructor as any)[NETWORK_ENTITY_METADATA];
if (metadata?.autoSpawn) {
// 避免重复广播同一实体
if (!this._networkEntities.has(entity.id)) {
this._networkEntities.set(entity.id, metadata.prefabType);
this.broadcastSpawn(entity, metadata.prefabType);
}
}
// 记录需要自动 despawn 的实体
if (metadata?.autoDespawn && !this._networkEntities.has(entity.id)) {
this._networkEntities.set(entity.id, metadata.prefabType);
}
});
// 监听实体销毁事件,自动广播 despawn
this.scene.eventSystem.on(ECSEventType.ENTITY_DESTROYED, (event: any) => {
const { entityId } = event;
if (this._networkEntities.has(entityId)) {
const despawnData = encodeDespawn(entityId);
this.broadcastBinary(despawnData);
this._networkEntities.delete(entityId);
}
});
}
// =========================================================================
// Scene Management | 场景管理
// =========================================================================
/**
* @zh 添加系统到场景
* @en Add system to scene
*/
protected addSystem(system: EntitySystem): void {
this.scene.addSystem(system);
}
/**
* @zh 创建实体
* @en Create entity
*/
protected createEntity(name?: string): Entity {
return this.scene.createEntity(name ?? `entity_${Date.now()}`);
}
/**
* @zh 为玩家创建实体
* @en Create entity for player
*
* @param playerId - @zh 玩家 ID @en Player ID
* @param name - @zh 实体名称 @en Entity name
* @returns @zh 创建的实体 @en Created entity
*/
protected createPlayerEntity(playerId: string, name?: string): Entity {
const entityName = name ?? `player_${playerId}`;
const entity = this.scene.createEntity(entityName);
(entity as any)[NETWORK_ENTITY_OWNER] = playerId;
this._playerEntities.set(playerId, entity);
return entity;
}
/**
* @zh 获取玩家的实体
* @en Get player's entity
*/
protected getPlayerEntity(playerId: string): Entity | undefined {
return this._playerEntities.get(playerId);
}
/**
* @zh 销毁玩家的实体
* @en Destroy player's entity
*/
protected destroyPlayerEntity(playerId: string): void {
const entity = this._playerEntities.get(playerId);
if (entity) {
const despawnData = encodeDespawn(entity.id);
this.broadcastBinary(despawnData);
entity.destroy();
this._playerEntities.delete(playerId);
}
}
// =========================================================================
// State Sync | 状态同步
// =========================================================================
/**
* @zh 广播二进制数据
* @en Broadcast binary data
*/
protected broadcastBinary(data: Uint8Array): void {
for (const player of this.players) {
this.sendBinary(player, data);
}
}
/**
* @zh 发送二进制数据给指定玩家
* @en Send binary data to specific player
*/
protected sendBinary(player: Player<TPlayerData>, data: Uint8Array): void {
player.send('$sync', { data: Array.from(data) });
}
/**
* @zh 发送完整状态给玩家(用于玩家刚加入时)
* @en Send full state to player (for when player just joined)
*/
protected sendFullState(player: Player<TPlayerData>): void {
const entities = this._getSyncEntities();
if (entities.length === 0) return;
for (const entity of entities) {
this._initComponentTrackers(entity);
}
const data = encodeSnapshot(entities, SyncOperation.FULL);
this.sendBinary(player, data);
}
/**
* @zh 广播实体生成
* @en Broadcast entity spawn
*/
protected broadcastSpawn(entity: Entity, prefabType?: string): void {
this._initComponentTrackers(entity);
const data = encodeSpawn(entity, prefabType);
this.broadcastBinary(data);
}
/**
* @zh 广播增量状态更新
* @en Broadcast delta state update
*/
protected broadcastDelta(): void {
const entities = this._getSyncEntities();
const changedEntities = entities.filter(entity => this._hasChanges(entity));
if (changedEntities.length === 0) return;
const data = encodeSnapshot(changedEntities, SyncOperation.DELTA);
this.broadcastBinary(data);
this._clearChangeTrackers(changedEntities);
}
// =========================================================================
// Lifecycle Overrides | 生命周期重载
// =========================================================================
/**
* @zh 游戏循环,处理状态同步
* @en Game tick, handles state sync
*/
override onTick(_dt: number): void {
if (this.ecsConfig.enableDeltaSync) {
const now = Date.now();
if (now - this._lastSyncTime >= this.ecsConfig.syncInterval) {
this._lastSyncTime = now;
this.broadcastDelta();
}
}
}
/**
* @zh 玩家离开时自动销毁其实体
* @en Auto destroy player entity when leaving
*/
override async onLeave(player: Player<TPlayerData>, reason?: string): Promise<void> {
this.destroyPlayerEntity(player.id);
}
/**
* @zh 房间销毁时从 WorldManager 移除 World
* @en Remove World from WorldManager when room is disposed
*/
override onDispose(): void {
this._playerEntities.clear();
Core.worldManager.removeWorld(this.worldId);
}
// =========================================================================
// Internal | 内部方法
// =========================================================================
private _getSyncEntities(): Entity[] {
const entities: Entity[] = [];
for (const entity of this.scene.entities.buffer) {
if (this._hasSyncComponents(entity)) {
entities.push(entity);
}
}
return entities;
}
private _hasSyncComponents(entity: Entity): boolean {
for (const component of entity.components) {
const metadata: SyncMetadata | undefined = (component.constructor as any)[SYNC_METADATA];
if (metadata && metadata.fields.length > 0) {
return true;
}
}
return false;
}
private _hasChanges(entity: Entity): boolean {
for (const component of entity.components) {
const tracker = (component as any)[CHANGE_TRACKER] as ChangeTracker | undefined;
if (tracker?.hasChanges()) {
return true;
}
}
return false;
}
private _initComponentTrackers(entity: Entity): void {
for (const component of entity.components) {
const metadata: SyncMetadata | undefined = (component.constructor as any)[SYNC_METADATA];
if (metadata && metadata.fields.length > 0) {
initChangeTracker(component);
}
}
}
private _clearChangeTrackers(entities: Entity[]): void {
for (const entity of entities) {
for (const component of entity.components) {
const tracker = (component as any)[CHANGE_TRACKER] as ChangeTracker | undefined;
if (tracker) {
tracker.clear();
}
}
}
}
}

View File

@@ -0,0 +1,62 @@
/**
* @zh @esengine/server ECS 集成模块
* @en @esengine/server ECS integration module
*
* @zh 提供带 ECS World 的房间类,支持基于 @sync 装饰器的自动状态同步
* @en Provides Room class with ECS World, supports automatic state sync based on @sync decorator
*
* @example
* ```typescript
* import { ECSRoom } from '@esengine/server/ecs';
* import { Component, ECSComponent, sync } from '@esengine/ecs-framework';
*
* @ECSComponent('Player')
* class PlayerComponent extends Component {
* @sync("string") name: string = "";
* @sync("uint16") score: number = 0;
* }
*
* class GameRoom extends ECSRoom {
* onCreate() {
* this.addSystem(new MovementSystem());
* }
*
* onJoin(player: Player) {
* const entity = this.createPlayerEntity(player.id);
* entity.addComponent(new PlayerComponent());
* }
* }
* ```
*/
export { ECSRoom } from './ECSRoom.js';
export type { ECSRoomConfig } from './ECSRoom.js';
// Re-export Player for convenience
export { Player, type IPlayer } from '../room/Player.js';
// Re-export commonly used ECS types for convenience
export type {
Entity,
Component,
EntitySystem,
Scene,
World,
} from '@esengine/ecs-framework';
// Re-export sync types
export {
sync,
getSyncMetadata,
hasSyncFields,
initChangeTracker,
clearChanges,
hasChanges,
SyncOperation,
type SyncType,
type SyncFieldMetadata,
type SyncMetadata,
} from '@esengine/ecs-framework';
// Re-export room decorators
export { onMessage } from '../room/decorators.js';

View File

@@ -1,9 +1,9 @@
/**
* @zh API 和消息定义助手
* @en API and message definition helpers
* @zh API、消息和 HTTP 定义助手
* @en API, message, and HTTP definition helpers
*/
import type { ApiDefinition, MsgDefinition } from '../types/index.js'
import type { ApiDefinition, MsgDefinition, HttpDefinition } from '../types/index.js'
/**
* @zh 定义 API 处理器
@@ -49,3 +49,33 @@ export function defineMsg<TMsg, TData = Record<string, unknown>>(
): MsgDefinition<TMsg, TData> {
return definition
}
/**
* @zh 定义 HTTP 路由处理器
* @en Define HTTP route handler
*
* @example
* ```typescript
* // src/http/login.ts
* import { defineHttp } from '@esengine/server'
*
* interface LoginBody {
* username: string
* password: string
* }
*
* export default defineHttp<LoginBody>({
* method: 'POST',
* handler(req, res) {
* const { username, password } = req.body
* // ... validate credentials
* res.json({ token: '...', userId: '...' })
* }
* })
* ```
*/
export function defineHttp<TBody = unknown>(
definition: HttpDefinition<TBody>
): HttpDefinition<TBody> {
return definition
}

View File

@@ -0,0 +1,7 @@
/**
* @zh HTTP 模块导出
* @en HTTP module exports
*/
export * from './types.js';
export { createHttpRouter } from './router.js';

View File

@@ -0,0 +1,263 @@
/**
* @zh HTTP 路由器
* @en HTTP Router
*
* @zh 简洁的 HTTP 路由实现,支持与 WebSocket 共用端口
* @en Simple HTTP router implementation, supports sharing port with WebSocket
*/
import type { IncomingMessage, ServerResponse } from 'node:http';
import type {
HttpRequest,
HttpResponse,
HttpHandler,
HttpRoutes,
CorsOptions,
} from './types.js';
/**
* @zh 创建 HTTP 请求对象
* @en Create HTTP request object
*/
async function createRequest(req: IncomingMessage): Promise<HttpRequest> {
const url = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`);
// 解析查询参数
const query: Record<string, string> = {};
url.searchParams.forEach((value, key) => {
query[key] = value;
});
// 解析请求体
let body: unknown = null;
if (req.method === 'POST' || req.method === 'PUT' || req.method === 'PATCH') {
body = await parseBody(req);
}
// 获取客户端 IP
const ip =
(req.headers['x-forwarded-for'] as string)?.split(',')[0]?.trim() ||
req.socket?.remoteAddress ||
'unknown';
return {
raw: req,
method: req.method ?? 'GET',
path: url.pathname,
query,
headers: req.headers as Record<string, string | string[] | undefined>,
body,
ip,
};
}
/**
* @zh 解析请求体
* @en Parse request body
*/
function parseBody(req: IncomingMessage): Promise<unknown> {
return new Promise((resolve) => {
const chunks: Buffer[] = [];
req.on('data', (chunk: Buffer) => {
chunks.push(chunk);
});
req.on('end', () => {
const rawBody = Buffer.concat(chunks).toString('utf-8');
if (!rawBody) {
resolve(null);
return;
}
const contentType = req.headers['content-type'] ?? '';
if (contentType.includes('application/json')) {
try {
resolve(JSON.parse(rawBody));
} catch {
resolve(rawBody);
}
} else if (contentType.includes('application/x-www-form-urlencoded')) {
const params = new URLSearchParams(rawBody);
const result: Record<string, string> = {};
params.forEach((value, key) => {
result[key] = value;
});
resolve(result);
} else {
resolve(rawBody);
}
});
req.on('error', () => {
resolve(null);
});
});
}
/**
* @zh 创建 HTTP 响应对象
* @en Create HTTP response object
*/
function createResponse(res: ServerResponse): HttpResponse {
let statusCode = 200;
const response: HttpResponse = {
raw: res,
status(code: number) {
statusCode = code;
return response;
},
header(name: string, value: string) {
res.setHeader(name, value);
return response;
},
json(data: unknown) {
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.statusCode = statusCode;
res.end(JSON.stringify(data));
},
text(data: string) {
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.statusCode = statusCode;
res.end(data);
},
error(code: number, message: string) {
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.statusCode = code;
res.end(JSON.stringify({ error: message }));
},
};
return response;
}
/**
* @zh 应用 CORS 头
* @en Apply CORS headers
*/
function applyCors(res: ServerResponse, req: IncomingMessage, cors: CorsOptions): void {
const origin = req.headers.origin;
// 处理 origin
if (cors.origin === true || cors.origin === '*') {
res.setHeader('Access-Control-Allow-Origin', origin ?? '*');
} else if (typeof cors.origin === 'string') {
res.setHeader('Access-Control-Allow-Origin', cors.origin);
} else if (Array.isArray(cors.origin) && origin && cors.origin.includes(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
}
// 允许的方法
if (cors.methods) {
res.setHeader('Access-Control-Allow-Methods', cors.methods.join(', '));
} else {
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
}
// 允许的头
if (cors.allowedHeaders) {
res.setHeader('Access-Control-Allow-Headers', cors.allowedHeaders.join(', '));
} else {
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
}
// 凭证
if (cors.credentials) {
res.setHeader('Access-Control-Allow-Credentials', 'true');
}
// 缓存
if (cors.maxAge) {
res.setHeader('Access-Control-Max-Age', String(cors.maxAge));
}
}
/**
* @zh 创建 HTTP 路由器
* @en Create HTTP router
*/
export function createHttpRouter(routes: HttpRoutes, cors?: CorsOptions | boolean) {
// 解析路由
const parsedRoutes: Array<{
method: string;
path: string;
handler: HttpHandler;
}> = [];
for (const [path, handlerOrMethods] of Object.entries(routes)) {
if (typeof handlerOrMethods === 'function') {
// 简单形式:路径 -> 处理器(接受所有方法)
parsedRoutes.push({ method: '*', path, handler: handlerOrMethods });
} else {
// 对象形式:路径 -> { GET, POST, ... }
for (const [method, handler] of Object.entries(handlerOrMethods)) {
if (handler !== undefined) {
parsedRoutes.push({ method, path, handler });
}
}
}
}
// 默认 CORS 配置
const corsOptions: CorsOptions | null =
cors === true
? { origin: true, credentials: true }
: cors === false
? null
: cors ?? null;
/**
* @zh 处理 HTTP 请求
* @en Handle HTTP request
*/
return async function handleRequest(
req: IncomingMessage,
res: ServerResponse
): Promise<boolean> {
const url = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`);
const path = url.pathname;
const method = req.method ?? 'GET';
// 应用 CORS
if (corsOptions) {
applyCors(res, req, corsOptions);
// 处理预检请求
if (method === 'OPTIONS') {
res.statusCode = 204;
res.end();
return true;
}
}
// 查找匹配的路由
const route = parsedRoutes.find(
(r) => r.path === path && (r.method === '*' || r.method === method)
);
if (!route) {
return false; // 未找到路由,让其他处理器处理
}
try {
const httpReq = await createRequest(req);
const httpRes = createResponse(res);
await route.handler(httpReq, httpRes);
return true;
} catch (error) {
console.error('[HTTP] Route handler error:', error);
res.statusCode = 500;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ error: 'Internal Server Error' }));
return true;
}
};
}

View File

@@ -0,0 +1,161 @@
/**
* @zh HTTP 路由类型定义
* @en HTTP router type definitions
*/
import type { IncomingMessage, ServerResponse } from 'node:http';
/**
* @zh HTTP 请求上下文
* @en HTTP request context
*/
export interface HttpRequest {
/**
* @zh 原始请求对象
* @en Raw request object
*/
raw: IncomingMessage;
/**
* @zh 请求方法
* @en Request method
*/
method: string;
/**
* @zh 请求路径
* @en Request path
*/
path: string;
/**
* @zh 查询参数
* @en Query parameters
*/
query: Record<string, string>;
/**
* @zh 请求头
* @en Request headers
*/
headers: Record<string, string | string[] | undefined>;
/**
* @zh 解析后的 JSON 请求体
* @en Parsed JSON body
*/
body: unknown;
/**
* @zh 客户端 IP
* @en Client IP
*/
ip: string;
}
/**
* @zh HTTP 响应工具
* @en HTTP response utilities
*/
export interface HttpResponse {
/**
* @zh 原始响应对象
* @en Raw response object
*/
raw: ServerResponse;
/**
* @zh 设置状态码
* @en Set status code
*/
status(code: number): HttpResponse;
/**
* @zh 设置响应头
* @en Set response header
*/
header(name: string, value: string): HttpResponse;
/**
* @zh 发送 JSON 响应
* @en Send JSON response
*/
json(data: unknown): void;
/**
* @zh 发送文本响应
* @en Send text response
*/
text(data: string): void;
/**
* @zh 发送错误响应
* @en Send error response
*/
error(code: number, message: string): void;
}
/**
* @zh HTTP 路由处理器
* @en HTTP route handler
*/
export type HttpHandler = (req: HttpRequest, res: HttpResponse) => void | Promise<void>;
/**
* @zh HTTP 路由定义
* @en HTTP route definition
*/
export interface HttpRoute {
method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS' | '*';
path: string;
handler: HttpHandler;
}
/**
* @zh HTTP 路由配置
* @en HTTP routes configuration
*/
export type HttpRoutes = Record<string, HttpHandler | {
GET?: HttpHandler;
POST?: HttpHandler;
PUT?: HttpHandler;
DELETE?: HttpHandler;
PATCH?: HttpHandler;
OPTIONS?: HttpHandler;
}>;
/**
* @zh CORS 配置
* @en CORS configuration
*/
export interface CorsOptions {
/**
* @zh 允许的来源
* @en Allowed origins
*/
origin?: string | string[] | boolean;
/**
* @zh 允许的方法
* @en Allowed methods
*/
methods?: string[];
/**
* @zh 允许的请求头
* @en Allowed headers
*/
allowedHeaders?: string[];
/**
* @zh 是否允许携带凭证
* @en Allow credentials
*/
credentials?: boolean;
/**
* @zh 预检请求缓存时间(秒)
* @en Preflight cache max age
*/
maxAge?: number;
}

View File

@@ -30,7 +30,7 @@
export { createServer } from './core/server.js'
// Helpers
export { defineApi, defineMsg } from './helpers/define.js'
export { defineApi, defineMsg, defineHttp } from './helpers/define.js'
// Room System
export { Room, type RoomOptions } from './room/Room.js'
@@ -46,7 +46,19 @@ export type {
MsgContext,
ApiDefinition,
MsgDefinition,
HttpDefinition,
HttpMethod,
} from './types/index.js'
// HTTP
export { createHttpRouter } from './http/router.js'
export type {
HttpRequest,
HttpResponse,
HttpHandler,
HttpRoutes,
CorsOptions,
} from './http/types.js'
// Re-export useful types from @esengine/rpc
export { RpcError, ErrorCode } from '@esengine/rpc'

View File

@@ -6,7 +6,15 @@
import * as fs from 'node:fs'
import * as path from 'node:path'
import { pathToFileURL } from 'node:url'
import type { ApiDefinition, MsgDefinition, LoadedApiHandler, LoadedMsgHandler } from '../types/index.js'
import type {
ApiDefinition,
MsgDefinition,
HttpDefinition,
LoadedApiHandler,
LoadedMsgHandler,
LoadedHttpHandler,
HttpMethod,
} from '../types/index.js'
/**
* @zh 将文件名转换为 API/消息名称
@@ -110,3 +118,106 @@ export async function loadMsgHandlers(msgDir: string): Promise<LoadedMsgHandler[
return handlers
}
/**
* @zh 递归扫描目录获取所有处理器文件
* @en Recursively scan directory for all handler files
*/
function scanDirectoryRecursive(dir: string, baseDir: string = dir): Array<{ filePath: string; relativePath: string }> {
if (!fs.existsSync(dir)) {
return []
}
const files: Array<{ filePath: string; relativePath: string }> = []
const entries = fs.readdirSync(dir, { withFileTypes: true })
for (const entry of entries) {
const fullPath = path.join(dir, entry.name)
if (entry.isDirectory()) {
files.push(...scanDirectoryRecursive(fullPath, baseDir))
} else if (entry.isFile() && /\.(ts|js|mts|mjs)$/.test(entry.name)) {
if (entry.name.startsWith('_') || entry.name.startsWith('index.')) {
continue
}
const relativePath = path.relative(baseDir, fullPath)
files.push({ filePath: fullPath, relativePath })
}
}
return files
}
/**
* @zh 将文件路径转换为路由路径
* @en Convert file path to route path
*
* @example
* 'login.ts' -> '/login'
* 'users/profile.ts' -> '/users/profile'
* 'users/[id].ts' -> '/users/:id'
*/
function filePathToRoute(relativePath: string, prefix: string): string {
let route = relativePath
.replace(/\.(ts|js|mts|mjs)$/, '')
.replace(/\\/g, '/')
.replace(/\[([^\]]+)\]/g, ':$1')
if (!route.startsWith('/')) {
route = '/' + route
}
const fullRoute = prefix.endsWith('/')
? prefix.slice(0, -1) + route
: prefix + route
return fullRoute
}
/**
* @zh 加载 HTTP 路由处理器
* @en Load HTTP route handlers
*
* @example
* ```typescript
* // Directory structure:
* // src/http/
* // login.ts -> POST /api/login
* // register.ts -> POST /api/register
* // users/
* // [id].ts -> GET /api/users/:id
*
* const handlers = await loadHttpHandlers('src/http', '/api')
* ```
*/
export async function loadHttpHandlers(
httpDir: string,
prefix: string = '/api'
): Promise<LoadedHttpHandler[]> {
const files = scanDirectoryRecursive(httpDir)
const handlers: LoadedHttpHandler[] = []
for (const { filePath, relativePath } of files) {
try {
const fileUrl = pathToFileURL(filePath).href
const module = await import(fileUrl)
const definition = module.default as HttpDefinition<unknown>
if (definition && typeof definition.handler === 'function') {
const route = filePathToRoute(relativePath, prefix)
const method: HttpMethod = definition.method ?? 'POST'
handlers.push({
route,
method,
path: filePath,
definition,
})
}
} catch (err) {
console.warn(`[Server] Failed to load HTTP handler: ${filePath}`, err)
}
}
return handlers
}

View File

@@ -4,6 +4,7 @@
*/
import type { Connection, ProtocolDef } from '@esengine/rpc'
import type { HttpRoutes, CorsOptions, HttpRequest, HttpResponse } from '../http/types.js'
// ============================================================================
// Server Config
@@ -35,6 +36,29 @@ export interface ServerConfig {
*/
msgDir?: string
/**
* @zh HTTP 路由目录路径
* @en HTTP routes directory path
* @default 'src/http'
*
* @zh 文件命名规则:
* - `login.ts` → POST /api/login
* - `users/[id].ts` → /api/users/:id
* - `health.ts` (method: 'GET') → GET /api/health
* @en File naming convention:
* - `login.ts` → POST /api/login
* - `users/[id].ts` → /api/users/:id
* - `health.ts` (method: 'GET') → GET /api/health
*/
httpDir?: string
/**
* @zh HTTP 路由前缀
* @en HTTP routes prefix
* @default '/api'
*/
httpPrefix?: string
/**
* @zh 游戏 Tick 速率 (每秒)
* @en Game tick rate (per second)
@@ -42,6 +66,19 @@ export interface ServerConfig {
*/
tickRate?: number
/**
* @zh HTTP 路由配置(内联定义,与 httpDir 文件路由合并)
* @en HTTP routes configuration (inline definition, merged with httpDir file routes)
*/
http?: HttpRoutes
/**
* @zh CORS 配置
* @en CORS configuration
* @default true
*/
cors?: CorsOptions | boolean
/**
* @zh 服务器启动回调
* @en Server start callback
@@ -232,3 +269,80 @@ export interface LoadedMsgHandler {
path: string
definition: MsgDefinition<any, any>
}
// ============================================================================
// HTTP Definition
// ============================================================================
/**
* @zh HTTP 请求方法
* @en HTTP request method
*/
export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'
/**
* @zh HTTP 定义选项
* @en HTTP definition options
*
* @example
* ```typescript
* // src/http/login.ts
* import { defineHttp } from '@esengine/server'
*
* export default defineHttp({
* method: 'POST',
* handler: async (req, res) => {
* const { username, password } = req.body
* // ... authentication logic
* res.json({ token: '...', userId: '...' })
* }
* })
* ```
*/
export interface HttpDefinition<TBody = unknown> {
/**
* @zh 请求方法
* @en Request method
* @default 'POST'
*/
method?: HttpMethod
/**
* @zh 处理函数
* @en Handler function
*/
handler: (
req: HttpRequest & { body: TBody },
res: HttpResponse
) => void | Promise<void>
}
/**
* @zh 已加载的 HTTP 处理器
* @en Loaded HTTP handler
*/
export interface LoadedHttpHandler {
/**
* @zh 路由路径(如 /api/login
* @en Route path (e.g., /api/login)
*/
route: string
/**
* @zh 请求方法
* @en Request method
*/
method: HttpMethod
/**
* @zh 源文件路径
* @en Source file path
*/
path: string
/**
* @zh 处理器定义
* @en Handler definition
*/
definition: HttpDefinition<any>
}

View File

@@ -1,4 +1,4 @@
import { defineConfig } from 'tsup'
import { defineConfig } from 'tsup';
export default defineConfig({
entry: [
@@ -6,12 +6,13 @@ export default defineConfig({
'src/auth/index.ts',
'src/auth/testing/index.ts',
'src/ratelimit/index.ts',
'src/testing/index.ts'
'src/testing/index.ts',
'src/ecs/index.ts',
],
format: ['esm'],
dts: true,
clean: true,
sourcemap: true,
external: ['ws', 'jsonwebtoken', '@esengine/rpc', '@esengine/rpc/codec'],
external: ['ws', 'jsonwebtoken', '@esengine/rpc', '@esengine/rpc/codec', '@esengine/ecs-framework'],
treeshake: true,
})
});

View File

@@ -1,5 +1,53 @@
# @esengine/spatial
## 4.0.1
### Patch Changes
- Updated dependencies [[`3e5b778`](https://github.com/esengine/esengine/commit/3e5b7783beec08e247f7525184935401923ecde8)]:
- @esengine/ecs-framework@2.7.1
- @esengine/blueprint@4.0.1
## 4.0.0
### Patch Changes
- Updated dependencies [[`1f3a76a`](https://github.com/esengine/esengine/commit/1f3a76aabea2d3eb8a5eb8b73e29127da57e2028)]:
- @esengine/ecs-framework@2.7.0
- @esengine/blueprint@4.0.0
## 3.0.1
### Patch Changes
- Updated dependencies [[`04b08f3`](https://github.com/esengine/esengine/commit/04b08f3f073d69beb8f4be399c774bea0acb612e)]:
- @esengine/ecs-framework@2.6.1
- @esengine/blueprint@3.0.1
## 3.0.0
### Patch Changes
- Updated dependencies []:
- @esengine/ecs-framework@2.6.0
- @esengine/blueprint@3.0.0
## 2.0.1
### Patch Changes
- Updated dependencies [[`a08a84b`](https://github.com/esengine/esengine/commit/a08a84b7db28e1140cbc637d442552747ad81c76)]:
- @esengine/ecs-framework@2.5.1
- @esengine/blueprint@2.0.1
## 2.0.0
### Patch Changes
- Updated dependencies [[`1f297ac`](https://github.com/esengine/esengine/commit/1f297ac769e37700f72fb4425639af7090898256)]:
- @esengine/ecs-framework@2.5.0
- @esengine/blueprint@2.0.0
## 1.0.4
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "@esengine/spatial",
"version": "1.0.4",
"version": "4.0.1",
"description": "Spatial query and indexing system for ECS Framework / ECS 框架的空间查询和索引系统",
"type": "module",
"main": "./dist/index.js",

View File

@@ -1,5 +1,53 @@
# @esengine/timer
## 4.0.1
### Patch Changes
- Updated dependencies [[`3e5b778`](https://github.com/esengine/esengine/commit/3e5b7783beec08e247f7525184935401923ecde8)]:
- @esengine/ecs-framework@2.7.1
- @esengine/blueprint@4.0.1
## 4.0.0
### Patch Changes
- Updated dependencies [[`1f3a76a`](https://github.com/esengine/esengine/commit/1f3a76aabea2d3eb8a5eb8b73e29127da57e2028)]:
- @esengine/ecs-framework@2.7.0
- @esengine/blueprint@4.0.0
## 3.0.1
### Patch Changes
- Updated dependencies [[`04b08f3`](https://github.com/esengine/esengine/commit/04b08f3f073d69beb8f4be399c774bea0acb612e)]:
- @esengine/ecs-framework@2.6.1
- @esengine/blueprint@3.0.1
## 3.0.0
### Patch Changes
- Updated dependencies []:
- @esengine/ecs-framework@2.6.0
- @esengine/blueprint@3.0.0
## 2.0.1
### Patch Changes
- Updated dependencies [[`a08a84b`](https://github.com/esengine/esengine/commit/a08a84b7db28e1140cbc637d442552747ad81c76)]:
- @esengine/ecs-framework@2.5.1
- @esengine/blueprint@2.0.1
## 2.0.0
### Patch Changes
- Updated dependencies [[`1f297ac`](https://github.com/esengine/esengine/commit/1f297ac769e37700f72fb4425639af7090898256)]:
- @esengine/ecs-framework@2.5.0
- @esengine/blueprint@2.0.0
## 1.0.3
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "@esengine/timer",
"version": "1.0.3",
"version": "4.0.1",
"description": "Timer and cooldown system for ECS Framework / ECS 框架的定时器和冷却系统",
"type": "module",
"main": "./dist/index.js",

View File

@@ -1,5 +1,40 @@
# @esengine/transaction
## 2.0.7
### Patch Changes
- Updated dependencies [[`902c0a1`](https://github.com/esengine/esengine/commit/902c0a10749f80bd8f499b44154646379d359704)]:
- @esengine/server@4.2.0
## 2.0.6
### Patch Changes
- Updated dependencies []:
- @esengine/server@4.1.0
## 2.0.5
### Patch Changes
- Updated dependencies []:
- @esengine/server@4.0.0
## 2.0.4
### Patch Changes
- Updated dependencies []:
- @esengine/server@3.0.0
## 2.0.3
### Patch Changes
- Updated dependencies [[`1f297ac`](https://github.com/esengine/esengine/commit/1f297ac769e37700f72fb4425639af7090898256)]:
- @esengine/server@2.0.0
## 2.0.2
### Patch Changes

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