refactor: reorganize package structure and decouple framework packages (#338)

* refactor: reorganize package structure and decouple framework packages

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

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

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

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

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

* docs: update README to focus on framework over engine

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

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

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

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

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

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

* fix: update network tsconfig references to new paths

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

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

* fix: exclude test files from CodeQL and fix string escaping security issue
This commit is contained in:
YHH
2025-12-26 14:50:35 +08:00
committed by GitHub
parent a84ff902e4
commit 155411e743
1936 changed files with 4147 additions and 11578 deletions

View File

@@ -0,0 +1,396 @@
/**
* @zh 网格空间索引
* @en Grid Spatial Index
*
* @zh 基于均匀网格的空间索引实现
* @en Uniform grid based spatial index implementation
*/
import type { IVector2 } from '@esengine/ecs-framework-math';
import type {
ISpatialIndex,
IBounds,
IRaycastHit,
SpatialFilter
} from './ISpatialQuery';
import {
createBoundsFromCircle,
boundsIntersectsCircle,
distanceSquared,
distance
} from './ISpatialQuery';
// =============================================================================
// 网格项 | Grid Item
// =============================================================================
/**
* @zh 网格中的项
* @en Item in grid
*/
interface GridItem<T> {
item: T;
position: IVector2;
cellKey: string;
}
// =============================================================================
// 网格空间索引 | Grid Spatial Index
// =============================================================================
/**
* @zh 网格空间索引配置
* @en Grid spatial index configuration
*/
export interface GridSpatialIndexConfig {
/**
* @zh 网格单元格大小
* @en Grid cell size
*/
cellSize: number;
}
/**
* @zh 网格空间索引实现
* @en Grid spatial index implementation
*
* @zh 使用均匀网格进行空间划分,适合对象分布均匀的场景
* @en Uses uniform grid for spatial partitioning, suitable for evenly distributed objects
*/
export class GridSpatialIndex<T> implements ISpatialIndex<T> {
private readonly _cellSize: number;
private readonly _cells: Map<string, Set<GridItem<T>>> = new Map();
private readonly _itemMap: Map<T, GridItem<T>> = new Map();
constructor(config: GridSpatialIndexConfig) {
this._cellSize = config.cellSize;
}
// =========================================================================
// ISpatialIndex 实现 | ISpatialIndex Implementation
// =========================================================================
get count(): number {
return this._itemMap.size;
}
/**
* @zh 插入对象
* @en Insert object
*/
insert(item: T, position: IVector2): void {
if (this._itemMap.has(item)) {
this.update(item, position);
return;
}
const cellKey = this._getCellKey(position);
const gridItem: GridItem<T> = { item, position: { x: position.x, y: position.y }, cellKey };
this._itemMap.set(item, gridItem);
this._addToCell(cellKey, gridItem);
}
/**
* @zh 移除对象
* @en Remove object
*/
remove(item: T): boolean {
const gridItem = this._itemMap.get(item);
if (!gridItem) {
return false;
}
this._removeFromCell(gridItem.cellKey, gridItem);
this._itemMap.delete(item);
return true;
}
/**
* @zh 更新对象位置
* @en Update object position
*/
update(item: T, newPosition: IVector2): boolean {
const gridItem = this._itemMap.get(item);
if (!gridItem) {
return false;
}
const newCellKey = this._getCellKey(newPosition);
if (newCellKey !== gridItem.cellKey) {
this._removeFromCell(gridItem.cellKey, gridItem);
gridItem.cellKey = newCellKey;
this._addToCell(newCellKey, gridItem);
}
gridItem.position = { x: newPosition.x, y: newPosition.y };
return true;
}
/**
* @zh 清空索引
* @en Clear index
*/
clear(): void {
this._cells.clear();
this._itemMap.clear();
}
/**
* @zh 获取所有对象
* @en Get all objects
*/
getAll(): T[] {
return Array.from(this._itemMap.keys());
}
// =========================================================================
// ISpatialQuery 实现 | ISpatialQuery Implementation
// =========================================================================
/**
* @zh 查找半径内的所有对象
* @en Find all objects within radius
*/
findInRadius(center: IVector2, radius: number, filter?: SpatialFilter<T>): T[] {
const results: T[] = [];
const radiusSq = radius * radius;
const bounds = createBoundsFromCircle(center, radius);
this._forEachInBounds(bounds, (gridItem) => {
const distSq = distanceSquared(center, gridItem.position);
if (distSq <= radiusSq) {
if (!filter || filter(gridItem.item)) {
results.push(gridItem.item);
}
}
});
return results;
}
/**
* @zh 查找矩形区域内的所有对象
* @en Find all objects within rectangle
*/
findInRect(bounds: IBounds, filter?: SpatialFilter<T>): T[] {
const results: T[] = [];
this._forEachInBounds(bounds, (gridItem) => {
const pos = gridItem.position;
if (pos.x >= bounds.minX && pos.x <= bounds.maxX &&
pos.y >= bounds.minY && pos.y <= bounds.maxY) {
if (!filter || filter(gridItem.item)) {
results.push(gridItem.item);
}
}
});
return results;
}
/**
* @zh 查找最近的对象
* @en Find nearest object
*/
findNearest(center: IVector2, maxDistance?: number, filter?: SpatialFilter<T>): T | null {
let nearest: T | null = null;
let nearestDistSq = maxDistance !== undefined ? maxDistance * maxDistance : Infinity;
const searchRadius = maxDistance ?? this._cellSize * 10;
const bounds = createBoundsFromCircle(center, searchRadius);
this._forEachInBounds(bounds, (gridItem) => {
const distSq = distanceSquared(center, gridItem.position);
if (distSq < nearestDistSq) {
if (!filter || filter(gridItem.item)) {
nearest = gridItem.item;
nearestDistSq = distSq;
}
}
});
return nearest;
}
/**
* @zh 查找最近的 K 个对象
* @en Find K nearest objects
*/
findKNearest(center: IVector2, k: number, maxDistance?: number, filter?: SpatialFilter<T>): T[] {
if (k <= 0) return [];
const candidates: Array<{ item: T; distSq: number }> = [];
const maxDistSq = maxDistance !== undefined ? maxDistance * maxDistance : Infinity;
const searchRadius = maxDistance ?? this._cellSize * 10;
const bounds = createBoundsFromCircle(center, searchRadius);
this._forEachInBounds(bounds, (gridItem) => {
const distSq = distanceSquared(center, gridItem.position);
if (distSq <= maxDistSq) {
if (!filter || filter(gridItem.item)) {
candidates.push({ item: gridItem.item, distSq });
}
}
});
candidates.sort((a, b) => a.distSq - b.distSq);
return candidates.slice(0, k).map(c => c.item);
}
/**
* @zh 射线检测
* @en Raycast
*/
raycast(origin: IVector2, direction: IVector2, maxDistance: number, filter?: SpatialFilter<T>): IRaycastHit<T>[] {
const hits: IRaycastHit<T>[] = [];
const rayBounds = this._getRayBounds(origin, direction, maxDistance);
this._forEachInBounds(rayBounds, (gridItem) => {
const hit = this._rayIntersectsPoint(origin, direction, gridItem.position, maxDistance);
if (hit && hit.distance <= maxDistance) {
if (!filter || filter(gridItem.item)) {
hits.push({
target: gridItem.item,
point: hit.point,
normal: hit.normal,
distance: hit.distance
});
}
}
});
hits.sort((a, b) => a.distance - b.distance);
return hits;
}
/**
* @zh 射线检测(仅返回第一个命中)
* @en Raycast (return first hit only)
*/
raycastFirst(origin: IVector2, direction: IVector2, maxDistance: number, filter?: SpatialFilter<T>): IRaycastHit<T> | null {
const hits = this.raycast(origin, direction, maxDistance, filter);
return hits.length > 0 ? hits[0] : null;
}
// =========================================================================
// 私有方法 | Private Methods
// =========================================================================
private _getCellKey(position: IVector2): string {
const cellX = Math.floor(position.x / this._cellSize);
const cellY = Math.floor(position.y / this._cellSize);
return `${cellX},${cellY}`;
}
private _getCellCoords(position: IVector2): { x: number; y: number } {
return {
x: Math.floor(position.x / this._cellSize),
y: Math.floor(position.y / this._cellSize)
};
}
private _addToCell(cellKey: string, gridItem: GridItem<T>): void {
let cell = this._cells.get(cellKey);
if (!cell) {
cell = new Set();
this._cells.set(cellKey, cell);
}
cell.add(gridItem);
}
private _removeFromCell(cellKey: string, gridItem: GridItem<T>): void {
const cell = this._cells.get(cellKey);
if (cell) {
cell.delete(gridItem);
if (cell.size === 0) {
this._cells.delete(cellKey);
}
}
}
private _forEachInBounds(bounds: IBounds, callback: (item: GridItem<T>) => void): void {
const minCell = this._getCellCoords({ x: bounds.minX, y: bounds.minY });
const maxCell = this._getCellCoords({ x: bounds.maxX, y: bounds.maxY });
for (let x = minCell.x; x <= maxCell.x; x++) {
for (let y = minCell.y; y <= maxCell.y; y++) {
const cell = this._cells.get(`${x},${y}`);
if (cell) {
for (const gridItem of cell) {
callback(gridItem);
}
}
}
}
}
private _getRayBounds(origin: IVector2, direction: IVector2, maxDistance: number): IBounds {
const endX = origin.x + direction.x * maxDistance;
const endY = origin.y + direction.y * maxDistance;
return {
minX: Math.min(origin.x, endX),
minY: Math.min(origin.y, endY),
maxX: Math.max(origin.x, endX),
maxY: Math.max(origin.y, endY)
};
}
private _rayIntersectsPoint(
origin: IVector2,
direction: IVector2,
point: IVector2,
_maxDistance: number,
hitRadius: number = 0.5
): { point: IVector2; normal: IVector2; distance: number } | null {
const toPoint = { x: point.x - origin.x, y: point.y - origin.y };
const projection = toPoint.x * direction.x + toPoint.y * direction.y;
if (projection < 0) {
return null;
}
const closestX = origin.x + direction.x * projection;
const closestY = origin.y + direction.y * projection;
const distToLine = Math.sqrt(
(point.x - closestX) * (point.x - closestX) +
(point.y - closestY) * (point.y - closestY)
);
if (distToLine <= hitRadius) {
const hitDist = projection - Math.sqrt(hitRadius * hitRadius - distToLine * distToLine);
if (hitDist >= 0) {
const hitPoint = {
x: origin.x + direction.x * hitDist,
y: origin.y + direction.y * hitDist
};
const normal = {
x: hitPoint.x - point.x,
y: hitPoint.y - point.y
};
const normalLen = Math.sqrt(normal.x * normal.x + normal.y * normal.y);
if (normalLen > 0) {
normal.x /= normalLen;
normal.y /= normalLen;
}
return { point: hitPoint, normal, distance: hitDist };
}
}
return null;
}
}
// =============================================================================
// 工厂函数 | Factory Functions
// =============================================================================
/**
* @zh 创建网格空间索引
* @en Create grid spatial index
*/
export function createGridSpatialIndex<T>(cellSize: number = 100): GridSpatialIndex<T> {
return new GridSpatialIndex<T>({ cellSize });
}

View File

@@ -0,0 +1,331 @@
/**
* @zh 空间查询接口
* @en Spatial Query Interface
*
* @zh 提供空间查询的核心抽象
* @en Provides core abstractions for spatial queries
*/
import type { IVector2 } from '@esengine/ecs-framework-math';
// =============================================================================
// 基础类型 | Basic Types
// =============================================================================
/**
* @zh 空间边界框
* @en Spatial bounding box
*/
export interface IBounds {
/**
* @zh 最小 X 坐标
* @en Minimum X coordinate
*/
readonly minX: number;
/**
* @zh 最小 Y 坐标
* @en Minimum Y coordinate
*/
readonly minY: number;
/**
* @zh 最大 X 坐标
* @en Maximum X coordinate
*/
readonly maxX: number;
/**
* @zh 最大 Y 坐标
* @en Maximum Y coordinate
*/
readonly maxY: number;
}
/**
* @zh 可定位对象接口
* @en Positionable object interface
*/
export interface IPositionable {
/**
* @zh 获取对象位置
* @en Get object position
*/
readonly position: IVector2;
}
/**
* @zh 可定位且有边界的对象接口
* @en Positionable object with bounds interface
*/
export interface IBoundable extends IPositionable {
/**
* @zh 获取对象边界
* @en Get object bounds
*/
readonly bounds: IBounds;
}
/**
* @zh 射线检测结果
* @en Raycast hit result
*/
export interface IRaycastHit<T> {
/**
* @zh 命中的对象
* @en Hit object
*/
readonly target: T;
/**
* @zh 命中点
* @en Hit point
*/
readonly point: IVector2;
/**
* @zh 命中点的法线
* @en Normal at hit point
*/
readonly normal: IVector2;
/**
* @zh 距离射线起点的距离
* @en Distance from ray origin
*/
readonly distance: number;
}
/**
* @zh 过滤器函数类型
* @en Filter function type
*/
export type SpatialFilter<T> = (item: T) => boolean;
// =============================================================================
// 空间查询接口 | Spatial Query Interface
// =============================================================================
/**
* @zh 空间查询接口
* @en Spatial query interface
*
* @zh 提供空间查询能力,支持范围查询、最近邻查询和射线检测
* @en Provides spatial query capabilities including range queries, nearest neighbor queries, and raycasting
*/
export interface ISpatialQuery<T> {
/**
* @zh 查找半径内的所有对象
* @en Find all objects within radius
*
* @param center - @zh 中心点 @en Center point
* @param radius - @zh 半径 @en Radius
* @param filter - @zh 过滤函数 @en Filter function
* @returns @zh 半径内的对象数组 @en Array of objects within radius
*/
findInRadius(center: IVector2, radius: number, filter?: SpatialFilter<T>): T[];
/**
* @zh 查找矩形区域内的所有对象
* @en Find all objects within rectangle
*
* @param bounds - @zh 边界框 @en Bounding box
* @param filter - @zh 过滤函数 @en Filter function
* @returns @zh 区域内的对象数组 @en Array of objects within bounds
*/
findInRect(bounds: IBounds, filter?: SpatialFilter<T>): T[];
/**
* @zh 查找最近的对象
* @en Find nearest object
*
* @param center - @zh 查询中心点 @en Query center point
* @param maxDistance - @zh 最大搜索距离 @en Maximum search distance
* @param filter - @zh 过滤函数 @en Filter function
* @returns @zh 最近的对象,没有则返回 null @en Nearest object or null
*/
findNearest(center: IVector2, maxDistance?: number, filter?: SpatialFilter<T>): T | null;
/**
* @zh 查找最近的 K 个对象
* @en Find K nearest objects
*
* @param center - @zh 查询中心点 @en Query center point
* @param k - @zh 返回的对象数量 @en Number of objects to return
* @param maxDistance - @zh 最大搜索距离 @en Maximum search distance
* @param filter - @zh 过滤函数 @en Filter function
* @returns @zh 最近的 K 个对象数组 @en Array of K nearest objects
*/
findKNearest(center: IVector2, k: number, maxDistance?: number, filter?: SpatialFilter<T>): T[];
/**
* @zh 射线检测
* @en Raycast
*
* @param origin - @zh 射线起点 @en Ray origin
* @param direction - @zh 射线方向(应归一化)@en Ray direction (should be normalized)
* @param maxDistance - @zh 最大检测距离 @en Maximum detection distance
* @param filter - @zh 过滤函数 @en Filter function
* @returns @zh 命中结果数组,按距离排序 @en Array of hit results sorted by distance
*/
raycast(origin: IVector2, direction: IVector2, maxDistance: number, filter?: SpatialFilter<T>): IRaycastHit<T>[];
/**
* @zh 射线检测(仅返回第一个命中)
* @en Raycast (return first hit only)
*
* @param origin - @zh 射线起点 @en Ray origin
* @param direction - @zh 射线方向(应归一化)@en Ray direction (should be normalized)
* @param maxDistance - @zh 最大检测距离 @en Maximum detection distance
* @param filter - @zh 过滤函数 @en Filter function
* @returns @zh 第一个命中结果,没有则返回 null @en First hit result or null
*/
raycastFirst(origin: IVector2, direction: IVector2, maxDistance: number, filter?: SpatialFilter<T>): IRaycastHit<T> | null;
}
// =============================================================================
// 空间索引接口 | Spatial Index Interface
// =============================================================================
/**
* @zh 空间索引接口
* @en Spatial index interface
*
* @zh 提供空间索引的管理能力
* @en Provides spatial index management capabilities
*/
export interface ISpatialIndex<T> extends ISpatialQuery<T> {
/**
* @zh 插入对象
* @en Insert object
*
* @param item - @zh 要插入的对象 @en Object to insert
* @param position - @zh 对象位置 @en Object position
*/
insert(item: T, position: IVector2): void;
/**
* @zh 移除对象
* @en Remove object
*
* @param item - @zh 要移除的对象 @en Object to remove
* @returns @zh 是否成功移除 @en Whether removal was successful
*/
remove(item: T): boolean;
/**
* @zh 更新对象位置
* @en Update object position
*
* @param item - @zh 要更新的对象 @en Object to update
* @param newPosition - @zh 新位置 @en New position
* @returns @zh 是否成功更新 @en Whether update was successful
*/
update(item: T, newPosition: IVector2): boolean;
/**
* @zh 清空索引
* @en Clear index
*/
clear(): void;
/**
* @zh 获取索引中的对象数量
* @en Get number of objects in index
*/
readonly count: number;
/**
* @zh 获取所有对象
* @en Get all objects
*/
getAll(): T[];
}
// =============================================================================
// 工具函数 | Utility Functions
// =============================================================================
/**
* @zh 创建边界框
* @en Create bounding box
*/
export function createBounds(minX: number, minY: number, maxX: number, maxY: number): IBounds {
return { minX, minY, maxX, maxY };
}
/**
* @zh 从中心点和尺寸创建边界框
* @en Create bounding box from center and size
*/
export function createBoundsFromCenter(center: IVector2, width: number, height: number): IBounds {
const halfWidth = width / 2;
const halfHeight = height / 2;
return {
minX: center.x - halfWidth,
minY: center.y - halfHeight,
maxX: center.x + halfWidth,
maxY: center.y + halfHeight
};
}
/**
* @zh 从圆形创建边界框
* @en Create bounding box from circle
*/
export function createBoundsFromCircle(center: IVector2, radius: number): IBounds {
return {
minX: center.x - radius,
minY: center.y - radius,
maxX: center.x + radius,
maxY: center.y + radius
};
}
/**
* @zh 检查点是否在边界框内
* @en Check if point is inside bounds
*/
export function isPointInBounds(point: IVector2, bounds: IBounds): boolean {
return point.x >= bounds.minX && point.x <= bounds.maxX &&
point.y >= bounds.minY && point.y <= bounds.maxY;
}
/**
* @zh 检查两个边界框是否相交
* @en Check if two bounding boxes intersect
*/
export function boundsIntersect(a: IBounds, b: IBounds): boolean {
return a.minX <= b.maxX && a.maxX >= b.minX &&
a.minY <= b.maxY && a.maxY >= b.minY;
}
/**
* @zh 检查边界框是否与圆形相交
* @en Check if bounds intersects with circle
*/
export function boundsIntersectsCircle(bounds: IBounds, center: IVector2, radius: number): boolean {
const closestX = Math.max(bounds.minX, Math.min(center.x, bounds.maxX));
const closestY = Math.max(bounds.minY, Math.min(center.y, bounds.maxY));
const distanceX = center.x - closestX;
const distanceY = center.y - closestY;
return (distanceX * distanceX + distanceY * distanceY) <= (radius * radius);
}
/**
* @zh 计算两点之间的距离平方
* @en Calculate squared distance between two points
*/
export function distanceSquared(a: IVector2, b: IVector2): number {
const dx = a.x - b.x;
const dy = a.y - b.y;
return dx * dx + dy * dy;
}
/**
* @zh 计算两点之间的距离
* @en Calculate distance between two points
*/
export function distance(a: IVector2, b: IVector2): number {
return Math.sqrt(distanceSquared(a, b));
}

View File

@@ -0,0 +1,328 @@
/**
* @zh AOI 蓝图节点
* @en AOI Blueprint Nodes
*
* @zh 提供 AOI 功能的蓝图节点
* @en Provides blueprint nodes for AOI functionality
*/
import type { BlueprintNodeTemplate, BlueprintNode, INodeExecutor, ExecutionResult } from '@esengine/blueprint';
import type { IAOIManager } from './IAOI';
// =============================================================================
// 执行上下文接口 | Execution Context Interface
// =============================================================================
/**
* @zh AOI 上下文
* @en AOI context
*/
interface AOIContext {
aoiManager: IAOIManager<unknown>;
entity: unknown;
evaluateInput(nodeId: string, pinName: string, defaultValue?: unknown): unknown;
setOutputs(nodeId: string, outputs: Record<string, unknown>): void;
}
// =============================================================================
// GetEntitiesInView 节点 | GetEntitiesInView Node
// =============================================================================
/**
* @zh GetEntitiesInView 节点模板
* @en GetEntitiesInView node template
*/
export const GetEntitiesInViewTemplate: BlueprintNodeTemplate = {
type: 'GetEntitiesInView',
title: 'Get Entities In View',
category: 'entity',
description: 'Get all entities within view range / 获取视野范围内的所有实体',
keywords: ['aoi', 'view', 'entities', 'visible'],
menuPath: ['AOI', 'Get Entities In View'],
isPure: true,
inputs: [
{
name: 'observer',
displayName: 'Observer',
type: 'object'
}
],
outputs: [
{
name: 'entities',
displayName: 'Entities',
type: 'array'
},
{
name: 'count',
displayName: 'Count',
type: 'int'
}
],
color: '#9c27b0'
};
/**
* @zh GetEntitiesInView 节点执行器
* @en GetEntitiesInView node executor
*/
export class GetEntitiesInViewExecutor implements INodeExecutor {
execute(node: BlueprintNode, context: unknown): ExecutionResult {
const ctx = context as AOIContext;
const observer = ctx.evaluateInput(node.id, 'observer', ctx.entity);
const entities = ctx.aoiManager?.getEntitiesInView(observer) ?? [];
return {
outputs: {
entities,
count: entities.length
}
};
}
}
// =============================================================================
// GetObserversOf 节点 | GetObserversOf Node
// =============================================================================
/**
* @zh GetObserversOf 节点模板
* @en GetObserversOf node template
*/
export const GetObserversOfTemplate: BlueprintNodeTemplate = {
type: 'GetObserversOf',
title: 'Get Observers Of',
category: 'entity',
description: 'Get all observers who can see the entity / 获取能看到该实体的所有观察者',
keywords: ['aoi', 'observers', 'watchers', 'visible'],
menuPath: ['AOI', 'Get Observers Of'],
isPure: true,
inputs: [
{
name: 'target',
displayName: 'Target',
type: 'object'
}
],
outputs: [
{
name: 'observers',
displayName: 'Observers',
type: 'array'
},
{
name: 'count',
displayName: 'Count',
type: 'int'
}
],
color: '#9c27b0'
};
/**
* @zh GetObserversOf 节点执行器
* @en GetObserversOf node executor
*/
export class GetObserversOfExecutor implements INodeExecutor {
execute(node: BlueprintNode, context: unknown): ExecutionResult {
const ctx = context as AOIContext;
const target = ctx.evaluateInput(node.id, 'target', ctx.entity);
const observers = ctx.aoiManager?.getObserversOf(target) ?? [];
return {
outputs: {
observers,
count: observers.length
}
};
}
}
// =============================================================================
// CanSee 节点 | CanSee Node
// =============================================================================
/**
* @zh CanSee 节点模板
* @en CanSee node template
*/
export const CanSeeTemplate: BlueprintNodeTemplate = {
type: 'CanSee',
title: 'Can See',
category: 'entity',
description: 'Check if observer can see target / 检查观察者是否能看到目标',
keywords: ['aoi', 'visibility', 'can', 'see', 'check'],
menuPath: ['AOI', 'Can See'],
isPure: true,
inputs: [
{
name: 'observer',
displayName: 'Observer',
type: 'object'
},
{
name: 'target',
displayName: 'Target',
type: 'object'
}
],
outputs: [
{
name: 'canSee',
displayName: 'Can See',
type: 'bool'
}
],
color: '#9c27b0'
};
/**
* @zh CanSee 节点执行器
* @en CanSee node executor
*/
export class CanSeeExecutor implements INodeExecutor {
execute(node: BlueprintNode, context: unknown): ExecutionResult {
const ctx = context as AOIContext;
const observer = ctx.evaluateInput(node.id, 'observer', ctx.entity);
const target = ctx.evaluateInput(node.id, 'target', null);
const canSee = ctx.aoiManager?.canSee(observer, target) ?? false;
return {
outputs: {
canSee
}
};
}
}
// =============================================================================
// OnEntityEnterView 事件节点 | OnEntityEnterView Event Node
// =============================================================================
/**
* @zh OnEntityEnterView 事件节点模板
* @en OnEntityEnterView event node template
*/
export const OnEntityEnterViewTemplate: BlueprintNodeTemplate = {
type: 'EventEntityEnterView',
title: 'On Entity Enter View',
category: 'event',
description: 'Triggered when an entity enters view / 当实体进入视野时触发',
keywords: ['aoi', 'event', 'enter', 'view', 'visible'],
menuPath: ['AOI', 'Events', 'On Entity Enter View'],
color: '#e91e63',
inputs: [],
outputs: [
{
name: 'exec',
displayName: '',
type: 'exec'
},
{
name: 'entity',
displayName: 'Entity',
type: 'object'
},
{
name: 'positionX',
displayName: 'Position X',
type: 'float'
},
{
name: 'positionY',
displayName: 'Position Y',
type: 'float'
}
]
};
/**
* @zh OnEntityEnterView 事件执行器
* @en OnEntityEnterView event executor
*/
export class OnEntityEnterViewExecutor implements INodeExecutor {
execute(_node: BlueprintNode, _context: unknown): ExecutionResult {
// Event nodes don't execute directly, they are triggered by the runtime
return { nextExec: 'exec' };
}
}
// =============================================================================
// OnEntityExitView 事件节点 | OnEntityExitView Event Node
// =============================================================================
/**
* @zh OnEntityExitView 事件节点模板
* @en OnEntityExitView event node template
*/
export const OnEntityExitViewTemplate: BlueprintNodeTemplate = {
type: 'EventEntityExitView',
title: 'On Entity Exit View',
category: 'event',
description: 'Triggered when an entity exits view / 当实体离开视野时触发',
keywords: ['aoi', 'event', 'exit', 'view', 'invisible'],
menuPath: ['AOI', 'Events', 'On Entity Exit View'],
color: '#e91e63',
inputs: [],
outputs: [
{
name: 'exec',
displayName: '',
type: 'exec'
},
{
name: 'entity',
displayName: 'Entity',
type: 'object'
},
{
name: 'positionX',
displayName: 'Position X',
type: 'float'
},
{
name: 'positionY',
displayName: 'Position Y',
type: 'float'
}
]
};
/**
* @zh OnEntityExitView 事件执行器
* @en OnEntityExitView event executor
*/
export class OnEntityExitViewExecutor implements INodeExecutor {
execute(_node: BlueprintNode, _context: unknown): ExecutionResult {
// Event nodes don't execute directly, they are triggered by the runtime
return { nextExec: 'exec' };
}
}
// =============================================================================
// 节点定义集合 | Node Definition Collection
// =============================================================================
/**
* @zh AOI 节点定义集合
* @en AOI node definition collection
*/
export const AOINodeDefinitions = {
templates: [
GetEntitiesInViewTemplate,
GetObserversOfTemplate,
CanSeeTemplate,
OnEntityEnterViewTemplate,
OnEntityExitViewTemplate
],
executors: new Map<string, INodeExecutor>([
['GetEntitiesInView', new GetEntitiesInViewExecutor()],
['GetObserversOf', new GetObserversOfExecutor()],
['CanSee', new CanSeeExecutor()],
['EventEntityEnterView', new OnEntityEnterViewExecutor()],
['EventEntityExitView', new OnEntityExitViewExecutor()]
])
};

View File

@@ -0,0 +1,490 @@
/**
* @zh 网格 AOI 实现
* @en Grid AOI Implementation
*
* @zh 基于均匀网格的兴趣区域管理实现
* @en Uniform grid based area of interest management implementation
*/
import type { IVector2 } from '@esengine/ecs-framework-math';
import type {
IAOIManager,
IAOIObserverConfig,
IAOIEvent,
AOIEventListener
} from './IAOI';
import { distanceSquared } from '../ISpatialQuery';
// =============================================================================
// 内部类型 | Internal Types
// =============================================================================
/**
* @zh AOI 观察者数据
* @en AOI observer data
*/
interface AOIObserverData<T> {
entity: T;
position: IVector2;
viewRange: number;
viewRangeSq: number;
observable: boolean;
cellKey: string;
/** @zh 当前可见的实体集合 @en Currently visible entities */
visibleEntities: Set<T>;
/** @zh 实体特定的监听器 @en Entity-specific listeners */
listeners: Set<AOIEventListener<T>>;
}
// =============================================================================
// 网格 AOI 配置 | Grid AOI Configuration
// =============================================================================
/**
* @zh 网格 AOI 配置
* @en Grid AOI configuration
*/
export interface GridAOIConfig {
/**
* @zh 网格单元格大小(建议设置为平均视野范围的 1-2 倍)
* @en Grid cell size (recommended 1-2x average view range)
*/
cellSize: number;
}
// =============================================================================
// 网格 AOI 实现 | Grid AOI Implementation
// =============================================================================
/**
* @zh 网格 AOI 实现
* @en Grid AOI implementation
*
* @zh 使用均匀网格进行空间划分,高效管理大量实体的兴趣区域
* @en Uses uniform grid for spatial partitioning, efficiently managing AOI for many entities
*/
export class GridAOI<T> implements IAOIManager<T> {
private readonly _cellSize: number;
private readonly _cells: Map<string, Set<AOIObserverData<T>>> = new Map();
private readonly _observers: Map<T, AOIObserverData<T>> = new Map();
private readonly _globalListeners: Set<AOIEventListener<T>> = new Set();
constructor(config: GridAOIConfig) {
this._cellSize = config.cellSize;
}
// =========================================================================
// IAOIManager 实现 | IAOIManager Implementation
// =========================================================================
get count(): number {
return this._observers.size;
}
/**
* @zh 添加观察者
* @en Add observer
*/
addObserver(entity: T, position: IVector2, config: IAOIObserverConfig): void {
if (this._observers.has(entity)) {
this.updatePosition(entity, position);
this.updateViewRange(entity, config.viewRange);
return;
}
const cellKey = this._getCellKey(position);
const data: AOIObserverData<T> = {
entity,
position: { x: position.x, y: position.y },
viewRange: config.viewRange,
viewRangeSq: config.viewRange * config.viewRange,
observable: config.observable !== false,
cellKey,
visibleEntities: new Set(),
listeners: new Set()
};
this._observers.set(entity, data);
this._addToCell(cellKey, data);
// Initial visibility check
this._updateVisibility(data);
}
/**
* @zh 移除观察者
* @en Remove observer
*/
removeObserver(entity: T): boolean {
const data = this._observers.get(entity);
if (!data) {
return false;
}
// Notify all observers who were watching this entity
if (data.observable) {
for (const [, otherData] of this._observers) {
if (otherData !== data && otherData.visibleEntities.has(entity)) {
otherData.visibleEntities.delete(entity);
this._emitEvent({
type: 'exit',
observer: otherData.entity,
target: entity,
position: data.position
}, otherData);
}
}
}
// Notify this entity about all entities it was watching
for (const visible of data.visibleEntities) {
const visibleData = this._observers.get(visible);
if (visibleData) {
this._emitEvent({
type: 'exit',
observer: entity,
target: visible,
position: visibleData.position
}, data);
}
}
this._removeFromCell(data.cellKey, data);
this._observers.delete(entity);
return true;
}
/**
* @zh 更新观察者位置
* @en Update observer position
*/
updatePosition(entity: T, newPosition: IVector2): boolean {
const data = this._observers.get(entity);
if (!data) {
return false;
}
const newCellKey = this._getCellKey(newPosition);
// Update cell if changed
if (newCellKey !== data.cellKey) {
this._removeFromCell(data.cellKey, data);
data.cellKey = newCellKey;
this._addToCell(newCellKey, data);
}
data.position = { x: newPosition.x, y: newPosition.y };
// Update visibility for this observer
this._updateVisibility(data);
// Update visibility for others who might now see/unsee this entity
if (data.observable) {
this._updateObserversOfEntity(data);
}
return true;
}
/**
* @zh 更新观察者视野范围
* @en Update observer view range
*/
updateViewRange(entity: T, newRange: number): boolean {
const data = this._observers.get(entity);
if (!data) {
return false;
}
data.viewRange = newRange;
data.viewRangeSq = newRange * newRange;
// Recalculate visibility
this._updateVisibility(data);
return true;
}
/**
* @zh 获取实体视野内的所有对象
* @en Get all objects within entity's view
*/
getEntitiesInView(entity: T): T[] {
const data = this._observers.get(entity);
if (!data) {
return [];
}
return Array.from(data.visibleEntities);
}
/**
* @zh 获取能看到指定实体的所有观察者
* @en Get all observers who can see the specified entity
*/
getObserversOf(entity: T): T[] {
const data = this._observers.get(entity);
if (!data || !data.observable) {
return [];
}
const observers: T[] = [];
for (const [, otherData] of this._observers) {
if (otherData !== data && otherData.visibleEntities.has(entity)) {
observers.push(otherData.entity);
}
}
return observers;
}
/**
* @zh 检查观察者是否能看到目标
* @en Check if observer can see target
*/
canSee(observer: T, target: T): boolean {
const data = this._observers.get(observer);
if (!data) {
return false;
}
return data.visibleEntities.has(target);
}
/**
* @zh 添加全局事件监听器
* @en Add global event listener
*/
addListener(listener: AOIEventListener<T>): void {
this._globalListeners.add(listener);
}
/**
* @zh 移除全局事件监听器
* @en Remove global event listener
*/
removeListener(listener: AOIEventListener<T>): void {
this._globalListeners.delete(listener);
}
/**
* @zh 为特定观察者添加事件监听器
* @en Add event listener for specific observer
*/
addEntityListener(entity: T, listener: AOIEventListener<T>): void {
const data = this._observers.get(entity);
if (data) {
data.listeners.add(listener);
}
}
/**
* @zh 移除特定观察者的事件监听器
* @en Remove event listener for specific observer
*/
removeEntityListener(entity: T, listener: AOIEventListener<T>): void {
const data = this._observers.get(entity);
if (data) {
data.listeners.delete(listener);
}
}
/**
* @zh 清空所有观察者
* @en Clear all observers
*/
clear(): void {
this._cells.clear();
this._observers.clear();
}
// =========================================================================
// 私有方法 | Private Methods
// =========================================================================
private _getCellKey(position: IVector2): string {
const cellX = Math.floor(position.x / this._cellSize);
const cellY = Math.floor(position.y / this._cellSize);
return `${cellX},${cellY}`;
}
private _getCellCoords(position: IVector2): { x: number; y: number } {
return {
x: Math.floor(position.x / this._cellSize),
y: Math.floor(position.y / this._cellSize)
};
}
private _addToCell(cellKey: string, data: AOIObserverData<T>): void {
let cell = this._cells.get(cellKey);
if (!cell) {
cell = new Set();
this._cells.set(cellKey, cell);
}
cell.add(data);
}
private _removeFromCell(cellKey: string, data: AOIObserverData<T>): void {
const cell = this._cells.get(cellKey);
if (cell) {
cell.delete(data);
if (cell.size === 0) {
this._cells.delete(cellKey);
}
}
}
/**
* @zh 更新观察者的可见实体列表
* @en Update observer's visible entities list
*/
private _updateVisibility(data: AOIObserverData<T>): void {
const newVisible = new Set<T>();
// Calculate search radius in cells
const cellRadius = Math.ceil(data.viewRange / this._cellSize);
const centerCell = this._getCellCoords(data.position);
// Check all cells within range
for (let dx = -cellRadius; dx <= cellRadius; dx++) {
for (let dy = -cellRadius; dy <= cellRadius; dy++) {
const cellKey = `${centerCell.x + dx},${centerCell.y + dy}`;
const cell = this._cells.get(cellKey);
if (!cell) continue;
for (const otherData of cell) {
if (otherData === data) continue;
if (!otherData.observable) continue;
const distSq = distanceSquared(data.position, otherData.position);
if (distSq <= data.viewRangeSq) {
newVisible.add(otherData.entity);
}
}
}
}
// Find entities that entered view
for (const entity of newVisible) {
if (!data.visibleEntities.has(entity)) {
const targetData = this._observers.get(entity);
if (targetData) {
this._emitEvent({
type: 'enter',
observer: data.entity,
target: entity,
position: targetData.position
}, data);
}
}
}
// Find entities that exited view
for (const entity of data.visibleEntities) {
if (!newVisible.has(entity)) {
const targetData = this._observers.get(entity);
const position = targetData?.position ?? { x: 0, y: 0 };
this._emitEvent({
type: 'exit',
observer: data.entity,
target: entity,
position
}, data);
}
}
data.visibleEntities = newVisible;
}
/**
* @zh 更新其他观察者对于某个实体的可见性
* @en Update other observers' visibility of an entity
*/
private _updateObserversOfEntity(movedData: AOIObserverData<T>): void {
const cellRadius = Math.ceil(this._getMaxViewRange() / this._cellSize) + 1;
const centerCell = this._getCellCoords(movedData.position);
for (let dx = -cellRadius; dx <= cellRadius; dx++) {
for (let dy = -cellRadius; dy <= cellRadius; dy++) {
const cellKey = `${centerCell.x + dx},${centerCell.y + dy}`;
const cell = this._cells.get(cellKey);
if (!cell) continue;
for (const otherData of cell) {
if (otherData === movedData) continue;
const distSq = distanceSquared(otherData.position, movedData.position);
const wasVisible = otherData.visibleEntities.has(movedData.entity);
const isVisible = distSq <= otherData.viewRangeSq;
if (isVisible && !wasVisible) {
otherData.visibleEntities.add(movedData.entity);
this._emitEvent({
type: 'enter',
observer: otherData.entity,
target: movedData.entity,
position: movedData.position
}, otherData);
} else if (!isVisible && wasVisible) {
otherData.visibleEntities.delete(movedData.entity);
this._emitEvent({
type: 'exit',
observer: otherData.entity,
target: movedData.entity,
position: movedData.position
}, otherData);
}
}
}
}
}
/**
* @zh 获取最大视野范围(用于优化搜索)
* @en Get maximum view range (for search optimization)
*/
private _getMaxViewRange(): number {
let max = 0;
for (const [, data] of this._observers) {
if (data.viewRange > max) {
max = data.viewRange;
}
}
return max;
}
/**
* @zh 发送事件
* @en Emit event
*/
private _emitEvent(event: IAOIEvent<T>, observerData: AOIObserverData<T>): void {
// Entity-specific listeners
for (const listener of observerData.listeners) {
try {
listener(event);
} catch (e) {
console.error('AOI entity listener error:', e);
}
}
// Global listeners
for (const listener of this._globalListeners) {
try {
listener(event);
} catch (e) {
console.error('AOI global listener error:', e);
}
}
}
}
// =============================================================================
// 工厂函数 | Factory Functions
// =============================================================================
/**
* @zh 创建网格 AOI 管理器
* @en Create grid AOI manager
*
* @param cellSize - @zh 网格单元格大小 @en Grid cell size
*/
export function createGridAOI<T>(cellSize: number = 100): GridAOI<T> {
return new GridAOI<T>({ cellSize });
}

View File

@@ -0,0 +1,205 @@
/**
* @zh AOI (Area of Interest) 兴趣区域接口
* @en AOI (Area of Interest) Interface
*
* @zh 提供 MMO 游戏中的兴趣区域管理能力
* @en Provides area of interest management for MMO games
*/
import type { IVector2 } from '@esengine/ecs-framework-math';
// =============================================================================
// AOI 事件类型 | AOI Event Types
// =============================================================================
/**
* @zh AOI 事件类型
* @en AOI event type
*/
export type AOIEventType = 'enter' | 'exit' | 'update';
/**
* @zh AOI 事件
* @en AOI event
*/
export interface IAOIEvent<T> {
/**
* @zh 事件类型
* @en Event type
*/
readonly type: AOIEventType;
/**
* @zh 观察者(谁看到了变化)
* @en Observer (who saw the change)
*/
readonly observer: T;
/**
* @zh 目标(发生变化的对象)
* @en Target (the object that changed)
*/
readonly target: T;
/**
* @zh 目标位置
* @en Target position
*/
readonly position: IVector2;
}
/**
* @zh AOI 事件监听器
* @en AOI event listener
*/
export type AOIEventListener<T> = (event: IAOIEvent<T>) => void;
// =============================================================================
// AOI 观察者接口 | AOI Observer Interface
// =============================================================================
/**
* @zh AOI 观察者配置
* @en AOI observer configuration
*/
export interface IAOIObserverConfig {
/**
* @zh 视野范围
* @en View range
*/
viewRange: number;
/**
* @zh 是否是可被观察的对象(默认 true
* @en Whether this observer can be observed by others (default true)
*/
observable?: boolean;
}
// =============================================================================
// AOI 管理器接口 | AOI Manager Interface
// =============================================================================
/**
* @zh AOI 管理器接口
* @en AOI manager interface
*
* @zh 管理兴趣区域,追踪对象的进入/离开事件
* @en Manages areas of interest, tracking enter/exit events for objects
*
* @typeParam T - @zh 被管理对象的类型 @en Type of managed objects
*/
export interface IAOIManager<T> {
/**
* @zh 添加观察者
* @en Add observer
*
* @param entity - @zh 实体对象 @en Entity object
* @param position - @zh 初始位置 @en Initial position
* @param config - @zh 观察者配置 @en Observer configuration
*/
addObserver(entity: T, position: IVector2, config: IAOIObserverConfig): void;
/**
* @zh 移除观察者
* @en Remove observer
*
* @param entity - @zh 实体对象 @en Entity object
* @returns @zh 是否成功移除 @en Whether removal was successful
*/
removeObserver(entity: T): boolean;
/**
* @zh 更新观察者位置
* @en Update observer position
*
* @param entity - @zh 实体对象 @en Entity object
* @param newPosition - @zh 新位置 @en New position
* @returns @zh 是否成功更新 @en Whether update was successful
*/
updatePosition(entity: T, newPosition: IVector2): boolean;
/**
* @zh 更新观察者视野范围
* @en Update observer view range
*
* @param entity - @zh 实体对象 @en Entity object
* @param newRange - @zh 新视野范围 @en New view range
* @returns @zh 是否成功更新 @en Whether update was successful
*/
updateViewRange(entity: T, newRange: number): boolean;
/**
* @zh 获取实体视野内的所有对象
* @en Get all objects within entity's view
*
* @param entity - @zh 观察者实体 @en Observer entity
* @returns @zh 视野内的对象数组 @en Array of objects within view
*/
getEntitiesInView(entity: T): T[];
/**
* @zh 获取能看到指定实体的所有观察者
* @en Get all observers who can see the specified entity
*
* @param entity - @zh 目标实体 @en Target entity
* @returns @zh 能看到目标的观察者数组 @en Array of observers who can see target
*/
getObserversOf(entity: T): T[];
/**
* @zh 检查观察者是否能看到目标
* @en Check if observer can see target
*
* @param observer - @zh 观察者 @en Observer
* @param target - @zh 目标 @en Target
* @returns @zh 是否在视野内 @en Whether target is in view
*/
canSee(observer: T, target: T): boolean;
/**
* @zh 添加事件监听器
* @en Add event listener
*
* @param listener - @zh 监听器函数 @en Listener function
*/
addListener(listener: AOIEventListener<T>): void;
/**
* @zh 移除事件监听器
* @en Remove event listener
*
* @param listener - @zh 监听器函数 @en Listener function
*/
removeListener(listener: AOIEventListener<T>): void;
/**
* @zh 为特定观察者添加事件监听器
* @en Add event listener for specific observer
*
* @param entity - @zh 观察者实体 @en Observer entity
* @param listener - @zh 监听器函数 @en Listener function
*/
addEntityListener(entity: T, listener: AOIEventListener<T>): void;
/**
* @zh 移除特定观察者的事件监听器
* @en Remove event listener for specific observer
*
* @param entity - @zh 观察者实体 @en Observer entity
* @param listener - @zh 监听器函数 @en Listener function
*/
removeEntityListener(entity: T, listener: AOIEventListener<T>): void;
/**
* @zh 清空所有观察者
* @en Clear all observers
*/
clear(): void;
/**
* @zh 获取观察者数量
* @en Get observer count
*/
readonly count: number;
}

View File

@@ -0,0 +1,15 @@
/**
* @zh AOI (Area of Interest) 兴趣区域模块
* @en AOI (Area of Interest) Module
*/
export type {
AOIEventType,
IAOIEvent,
AOIEventListener,
IAOIObserverConfig,
IAOIManager
} from './IAOI';
export type { GridAOIConfig } from './GridAOI';
export { GridAOI, createGridAOI } from './GridAOI';

View File

@@ -0,0 +1,100 @@
/**
* @zh @esengine/spatial - 空间查询和索引系统
* @en @esengine/spatial - Spatial Query and Indexing System
*
* @zh 提供空间查询能力,支持范围查询、最近邻查询、射线检测和 AOI 兴趣区域管理
* @en Provides spatial query capabilities including range queries, nearest neighbor queries, raycasting, and AOI management
*/
// =============================================================================
// 接口和类型 | Interfaces and Types
// =============================================================================
export type {
IBounds,
IPositionable,
IBoundable,
IRaycastHit,
SpatialFilter,
ISpatialQuery,
ISpatialIndex
} from './ISpatialQuery';
export {
createBounds,
createBoundsFromCenter,
createBoundsFromCircle,
isPointInBounds,
boundsIntersect,
boundsIntersectsCircle,
distanceSquared,
distance
} from './ISpatialQuery';
// =============================================================================
// 实现 | Implementations
// =============================================================================
export type { GridSpatialIndexConfig } from './GridSpatialIndex';
export { GridSpatialIndex, createGridSpatialIndex } from './GridSpatialIndex';
// =============================================================================
// AOI 兴趣区域 | AOI (Area of Interest)
// =============================================================================
export type {
AOIEventType,
IAOIEvent,
AOIEventListener,
IAOIObserverConfig,
IAOIManager
} from './aoi';
export type { GridAOIConfig } from './aoi';
export { GridAOI, createGridAOI } from './aoi';
// =============================================================================
// 服务令牌 | Service Tokens
// =============================================================================
export { SpatialIndexToken, SpatialQueryToken, AOIManagerToken } from './tokens';
// =============================================================================
// 蓝图节点 | Blueprint Nodes
// =============================================================================
export {
// Spatial Query Templates
FindInRadiusTemplate,
FindInRectTemplate,
FindNearestTemplate,
FindKNearestTemplate,
RaycastTemplate,
RaycastFirstTemplate,
// Spatial Query Executors
FindInRadiusExecutor,
FindInRectExecutor,
FindNearestExecutor,
FindKNearestExecutor,
RaycastExecutor,
RaycastFirstExecutor,
// Collection
SpatialQueryNodeDefinitions
} from './nodes';
export {
// AOI Templates
GetEntitiesInViewTemplate,
GetObserversOfTemplate,
CanSeeTemplate,
OnEntityEnterViewTemplate,
OnEntityExitViewTemplate,
// AOI Executors
GetEntitiesInViewExecutor,
GetObserversOfExecutor,
CanSeeExecutor,
OnEntityEnterViewExecutor,
OnEntityExitViewExecutor,
// Collection
AOINodeDefinitions
} from './aoi/AOINodes';

View File

@@ -0,0 +1,556 @@
/**
* @zh 空间查询蓝图节点
* @en Spatial Query Blueprint Nodes
*
* @zh 提供空间查询功能的蓝图节点
* @en Provides blueprint nodes for spatial query functionality
*/
import type { BlueprintNodeTemplate, BlueprintNode, INodeExecutor, ExecutionResult } from '@esengine/blueprint';
import type { ISpatialQuery, IBounds } from '../ISpatialQuery';
// =============================================================================
// 执行上下文接口 | Execution Context Interface
// =============================================================================
/**
* @zh 空间查询上下文
* @en Spatial query context
*/
interface SpatialContext {
spatialQuery: ISpatialQuery<unknown>;
evaluateInput(nodeId: string, pinName: string, defaultValue?: unknown): unknown;
setOutputs(nodeId: string, outputs: Record<string, unknown>): void;
}
// =============================================================================
// FindInRadius 节点 | FindInRadius Node
// =============================================================================
/**
* @zh FindInRadius 节点模板
* @en FindInRadius node template
*/
export const FindInRadiusTemplate: BlueprintNodeTemplate = {
type: 'FindInRadius',
title: 'Find In Radius',
category: 'entity',
description: 'Find all objects within radius / 查找半径内的所有对象',
keywords: ['spatial', 'find', 'radius', 'range', 'query'],
menuPath: ['Spatial', 'Find In Radius'],
isPure: true,
inputs: [
{
name: 'centerX',
displayName: 'Center X',
type: 'float',
defaultValue: 0
},
{
name: 'centerY',
displayName: 'Center Y',
type: 'float',
defaultValue: 0
},
{
name: 'radius',
displayName: 'Radius',
type: 'float',
defaultValue: 100
}
],
outputs: [
{
name: 'results',
displayName: 'Results',
type: 'array'
},
{
name: 'count',
displayName: 'Count',
type: 'int'
}
],
color: '#4a9eff'
};
/**
* @zh FindInRadius 节点执行器
* @en FindInRadius node executor
*/
export class FindInRadiusExecutor implements INodeExecutor {
execute(node: BlueprintNode, context: unknown): ExecutionResult {
const ctx = context as SpatialContext;
const centerX = ctx.evaluateInput(node.id, 'centerX', 0) as number;
const centerY = ctx.evaluateInput(node.id, 'centerY', 0) as number;
const radius = ctx.evaluateInput(node.id, 'radius', 100) as number;
const results = ctx.spatialQuery?.findInRadius({ x: centerX, y: centerY }, radius) ?? [];
return {
outputs: {
results,
count: results.length
}
};
}
}
// =============================================================================
// FindInRect 节点 | FindInRect Node
// =============================================================================
/**
* @zh FindInRect 节点模板
* @en FindInRect node template
*/
export const FindInRectTemplate: BlueprintNodeTemplate = {
type: 'FindInRect',
title: 'Find In Rect',
category: 'entity',
description: 'Find all objects within rectangle / 查找矩形区域内的所有对象',
keywords: ['spatial', 'find', 'rect', 'rectangle', 'area', 'query'],
menuPath: ['Spatial', 'Find In Rect'],
isPure: true,
inputs: [
{
name: 'minX',
displayName: 'Min X',
type: 'float',
defaultValue: 0
},
{
name: 'minY',
displayName: 'Min Y',
type: 'float',
defaultValue: 0
},
{
name: 'maxX',
displayName: 'Max X',
type: 'float',
defaultValue: 100
},
{
name: 'maxY',
displayName: 'Max Y',
type: 'float',
defaultValue: 100
}
],
outputs: [
{
name: 'results',
displayName: 'Results',
type: 'array'
},
{
name: 'count',
displayName: 'Count',
type: 'int'
}
],
color: '#4a9eff'
};
/**
* @zh FindInRect 节点执行器
* @en FindInRect node executor
*/
export class FindInRectExecutor implements INodeExecutor {
execute(node: BlueprintNode, context: unknown): ExecutionResult {
const ctx = context as SpatialContext;
const minX = ctx.evaluateInput(node.id, 'minX', 0) as number;
const minY = ctx.evaluateInput(node.id, 'minY', 0) as number;
const maxX = ctx.evaluateInput(node.id, 'maxX', 100) as number;
const maxY = ctx.evaluateInput(node.id, 'maxY', 100) as number;
const bounds: IBounds = { minX, minY, maxX, maxY };
const results = ctx.spatialQuery?.findInRect(bounds) ?? [];
return {
outputs: {
results,
count: results.length
}
};
}
}
// =============================================================================
// FindNearest 节点 | FindNearest Node
// =============================================================================
/**
* @zh FindNearest 节点模板
* @en FindNearest node template
*/
export const FindNearestTemplate: BlueprintNodeTemplate = {
type: 'FindNearest',
title: 'Find Nearest',
category: 'entity',
description: 'Find nearest object to a point / 查找距离点最近的对象',
keywords: ['spatial', 'find', 'nearest', 'closest', 'query'],
menuPath: ['Spatial', 'Find Nearest'],
isPure: true,
inputs: [
{
name: 'centerX',
displayName: 'Center X',
type: 'float',
defaultValue: 0
},
{
name: 'centerY',
displayName: 'Center Y',
type: 'float',
defaultValue: 0
},
{
name: 'maxDistance',
displayName: 'Max Distance',
type: 'float',
defaultValue: 1000
}
],
outputs: [
{
name: 'result',
displayName: 'Result',
type: 'any'
},
{
name: 'found',
displayName: 'Found',
type: 'bool'
}
],
color: '#4a9eff'
};
/**
* @zh FindNearest 节点执行器
* @en FindNearest node executor
*/
export class FindNearestExecutor implements INodeExecutor {
execute(node: BlueprintNode, context: unknown): ExecutionResult {
const ctx = context as SpatialContext;
const centerX = ctx.evaluateInput(node.id, 'centerX', 0) as number;
const centerY = ctx.evaluateInput(node.id, 'centerY', 0) as number;
const maxDistance = ctx.evaluateInput(node.id, 'maxDistance', 1000) as number;
const result = ctx.spatialQuery?.findNearest({ x: centerX, y: centerY }, maxDistance) ?? null;
return {
outputs: {
result,
found: result !== null
}
};
}
}
// =============================================================================
// FindKNearest 节点 | FindKNearest Node
// =============================================================================
/**
* @zh FindKNearest 节点模板
* @en FindKNearest node template
*/
export const FindKNearestTemplate: BlueprintNodeTemplate = {
type: 'FindKNearest',
title: 'Find K Nearest',
category: 'entity',
description: 'Find K nearest objects to a point / 查找距离点最近的 K 个对象',
keywords: ['spatial', 'find', 'nearest', 'k', 'query'],
menuPath: ['Spatial', 'Find K Nearest'],
isPure: true,
inputs: [
{
name: 'centerX',
displayName: 'Center X',
type: 'float',
defaultValue: 0
},
{
name: 'centerY',
displayName: 'Center Y',
type: 'float',
defaultValue: 0
},
{
name: 'k',
displayName: 'K',
type: 'int',
defaultValue: 5
},
{
name: 'maxDistance',
displayName: 'Max Distance',
type: 'float',
defaultValue: 1000
}
],
outputs: [
{
name: 'results',
displayName: 'Results',
type: 'array'
},
{
name: 'count',
displayName: 'Count',
type: 'int'
}
],
color: '#4a9eff'
};
/**
* @zh FindKNearest 节点执行器
* @en FindKNearest node executor
*/
export class FindKNearestExecutor implements INodeExecutor {
execute(node: BlueprintNode, context: unknown): ExecutionResult {
const ctx = context as SpatialContext;
const centerX = ctx.evaluateInput(node.id, 'centerX', 0) as number;
const centerY = ctx.evaluateInput(node.id, 'centerY', 0) as number;
const k = ctx.evaluateInput(node.id, 'k', 5) as number;
const maxDistance = ctx.evaluateInput(node.id, 'maxDistance', 1000) as number;
const results = ctx.spatialQuery?.findKNearest({ x: centerX, y: centerY }, k, maxDistance) ?? [];
return {
outputs: {
results,
count: results.length
}
};
}
}
// =============================================================================
// Raycast 节点 | Raycast Node
// =============================================================================
/**
* @zh Raycast 节点模板
* @en Raycast node template
*/
export const RaycastTemplate: BlueprintNodeTemplate = {
type: 'Raycast',
title: 'Raycast',
category: 'entity',
description: 'Cast a ray and get all hits / 发射射线并获取所有命中',
keywords: ['spatial', 'raycast', 'ray', 'hit', 'query'],
menuPath: ['Spatial', 'Raycast'],
isPure: true,
inputs: [
{
name: 'originX',
displayName: 'Origin X',
type: 'float',
defaultValue: 0
},
{
name: 'originY',
displayName: 'Origin Y',
type: 'float',
defaultValue: 0
},
{
name: 'directionX',
displayName: 'Direction X',
type: 'float',
defaultValue: 1
},
{
name: 'directionY',
displayName: 'Direction Y',
type: 'float',
defaultValue: 0
},
{
name: 'maxDistance',
displayName: 'Max Distance',
type: 'float',
defaultValue: 1000
}
],
outputs: [
{
name: 'hits',
displayName: 'Hits',
type: 'array'
},
{
name: 'hitCount',
displayName: 'Hit Count',
type: 'int'
},
{
name: 'hasHit',
displayName: 'Has Hit',
type: 'bool'
}
],
color: '#4a9eff'
};
/**
* @zh Raycast 节点执行器
* @en Raycast node executor
*/
export class RaycastExecutor implements INodeExecutor {
execute(node: BlueprintNode, context: unknown): ExecutionResult {
const ctx = context as SpatialContext;
const originX = ctx.evaluateInput(node.id, 'originX', 0) as number;
const originY = ctx.evaluateInput(node.id, 'originY', 0) as number;
const directionX = ctx.evaluateInput(node.id, 'directionX', 1) as number;
const directionY = ctx.evaluateInput(node.id, 'directionY', 0) as number;
const maxDistance = ctx.evaluateInput(node.id, 'maxDistance', 1000) as number;
const hits = ctx.spatialQuery?.raycast(
{ x: originX, y: originY },
{ x: directionX, y: directionY },
maxDistance
) ?? [];
return {
outputs: {
hits,
hitCount: hits.length,
hasHit: hits.length > 0
}
};
}
}
/**
* @zh RaycastFirst 节点模板
* @en RaycastFirst node template
*/
export const RaycastFirstTemplate: BlueprintNodeTemplate = {
type: 'RaycastFirst',
title: 'Raycast First',
category: 'entity',
description: 'Cast a ray and get first hit / 发射射线并获取第一个命中',
keywords: ['spatial', 'raycast', 'ray', 'first', 'hit', 'query'],
menuPath: ['Spatial', 'Raycast First'],
isPure: true,
inputs: [
{
name: 'originX',
displayName: 'Origin X',
type: 'float',
defaultValue: 0
},
{
name: 'originY',
displayName: 'Origin Y',
type: 'float',
defaultValue: 0
},
{
name: 'directionX',
displayName: 'Direction X',
type: 'float',
defaultValue: 1
},
{
name: 'directionY',
displayName: 'Direction Y',
type: 'float',
defaultValue: 0
},
{
name: 'maxDistance',
displayName: 'Max Distance',
type: 'float',
defaultValue: 1000
}
],
outputs: [
{
name: 'hit',
displayName: 'Hit',
type: 'object'
},
{
name: 'target',
displayName: 'Target',
type: 'any'
},
{
name: 'hitPointX',
displayName: 'Hit Point X',
type: 'float'
},
{
name: 'hitPointY',
displayName: 'Hit Point Y',
type: 'float'
},
{
name: 'distance',
displayName: 'Distance',
type: 'float'
},
{
name: 'hasHit',
displayName: 'Has Hit',
type: 'bool'
}
],
color: '#4a9eff'
};
/**
* @zh RaycastFirst 节点执行器
* @en RaycastFirst node executor
*/
export class RaycastFirstExecutor implements INodeExecutor {
execute(node: BlueprintNode, context: unknown): ExecutionResult {
const ctx = context as SpatialContext;
const originX = ctx.evaluateInput(node.id, 'originX', 0) as number;
const originY = ctx.evaluateInput(node.id, 'originY', 0) as number;
const directionX = ctx.evaluateInput(node.id, 'directionX', 1) as number;
const directionY = ctx.evaluateInput(node.id, 'directionY', 0) as number;
const maxDistance = ctx.evaluateInput(node.id, 'maxDistance', 1000) as number;
const hit = ctx.spatialQuery?.raycastFirst(
{ x: originX, y: originY },
{ x: directionX, y: directionY },
maxDistance
) ?? null;
return {
outputs: {
hit,
target: hit?.target ?? null,
hitPointX: hit?.point.x ?? 0,
hitPointY: hit?.point.y ?? 0,
distance: hit?.distance ?? 0,
hasHit: hit !== null
}
};
}
}
// =============================================================================
// 节点定义集合 | Node Definition Collection
// =============================================================================
/**
* @zh 空间查询节点定义
* @en Spatial query node definitions
*/
export const SpatialQueryNodeDefinitions = [
{ template: FindInRadiusTemplate, executor: new FindInRadiusExecutor() },
{ template: FindInRectTemplate, executor: new FindInRectExecutor() },
{ template: FindNearestTemplate, executor: new FindNearestExecutor() },
{ template: FindKNearestTemplate, executor: new FindKNearestExecutor() },
{ template: RaycastTemplate, executor: new RaycastExecutor() },
{ template: RaycastFirstTemplate, executor: new RaycastFirstExecutor() }
];

View File

@@ -0,0 +1,23 @@
/**
* @zh 空间查询蓝图节点导出
* @en Spatial Query Blueprint Nodes Export
*/
export {
// Templates
FindInRadiusTemplate,
FindInRectTemplate,
FindNearestTemplate,
FindKNearestTemplate,
RaycastTemplate,
RaycastFirstTemplate,
// Executors
FindInRadiusExecutor,
FindInRectExecutor,
FindNearestExecutor,
FindKNearestExecutor,
RaycastExecutor,
RaycastFirstExecutor,
// Collection
SpatialQueryNodeDefinitions
} from './SpatialQueryNodes';

View File

@@ -0,0 +1,35 @@
/**
* @zh 空间查询服务令牌
* @en Spatial Query Service Tokens
*/
import { createServiceToken } from '@esengine/ecs-framework';
import type { ISpatialIndex, ISpatialQuery } from './ISpatialQuery';
import type { IAOIManager } from './aoi/IAOI';
/**
* @zh 空间索引服务令牌
* @en Spatial index service token
*
* @zh 用于注入空间索引服务
* @en Used for injecting spatial index service
*/
export const SpatialIndexToken = createServiceToken<ISpatialIndex<unknown>>('spatialIndex');
/**
* @zh 空间查询服务令牌
* @en Spatial query service token
*
* @zh 用于注入空间查询服务(只读)
* @en Used for injecting spatial query service (read-only)
*/
export const SpatialQueryToken = createServiceToken<ISpatialQuery<unknown>>('spatialQuery');
/**
* @zh AOI 管理器服务令牌
* @en AOI manager service token
*
* @zh 用于注入 AOI 兴趣区域管理服务
* @en Used for injecting AOI (Area of Interest) manager service
*/
export const AOIManagerToken = createServiceToken<IAOIManager<unknown>>('aoiManager');