feat(spatial): 空间查询和索引系统 (#324)
* feat(spatial): 添加空间查询包 - ISpatialQuery: 空间查询接口 - findInRadius, findInRect, findNearest, findKNearest - raycast, raycastFirst - IBounds, IRaycastHit, SpatialFilter 类型 - ISpatialIndex: 空间索引接口 - insert, remove, update, clear, getAll - GridSpatialIndex: 网格空间索引实现 - 基于均匀网格的空间划分 - 支持所有 ISpatialQuery 操作 - 工具函数 - createBounds, isPointInBounds, boundsIntersect - distanceSquared, distance * feat(spatial): 添加空间查询蓝图节点 - 添加 FindInRadius/FindInRect/FindNearest/FindKNearest 节点 - 添加 Raycast/RaycastFirst 射线检测节点 - 每个节点包含模板和执行器 - 使用 menuPath: ['Spatial', ...] 组织节点菜单
This commit is contained in:
23
packages/spatial/module.json
Normal file
23
packages/spatial/module.json
Normal file
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"id": "spatial",
|
||||
"name": "@esengine/spatial",
|
||||
"globalKey": "spatial",
|
||||
"displayName": "Spatial Query",
|
||||
"description": "空间查询和索引系统 | Spatial query and indexing system",
|
||||
"version": "1.0.0",
|
||||
"category": "Core",
|
||||
"icon": "Grid",
|
||||
"tags": ["spatial", "query", "quadtree", "grid"],
|
||||
"isCore": false,
|
||||
"defaultEnabled": true,
|
||||
"isEngineModule": true,
|
||||
"canContainContent": false,
|
||||
"platforms": ["web", "desktop", "server"],
|
||||
"dependencies": ["core", "math"],
|
||||
"exports": {
|
||||
"components": [],
|
||||
"systems": ["SpatialIndexSystem"]
|
||||
},
|
||||
"outputPath": "dist/index.js",
|
||||
"pluginExport": "SpatialPlugin"
|
||||
}
|
||||
41
packages/spatial/package.json
Normal file
41
packages/spatial/package.json
Normal file
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"name": "@esengine/spatial",
|
||||
"version": "1.0.0",
|
||||
"description": "Spatial query and indexing system for ECS Framework / ECS 框架的空间查询和索引系统",
|
||||
"type": "module",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"import": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"module.json"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsup",
|
||||
"build:watch": "tsup --watch",
|
||||
"type-check": "tsc --noEmit",
|
||||
"clean": "rimraf dist"
|
||||
},
|
||||
"dependencies": {
|
||||
"tslib": "^2.8.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@esengine/ecs-framework": "workspace:*",
|
||||
"@esengine/ecs-framework-math": "workspace:*",
|
||||
"@esengine/blueprint": "workspace:*",
|
||||
"@esengine/build-config": "workspace:*",
|
||||
"@types/node": "^20.19.17",
|
||||
"rimraf": "^5.0.0",
|
||||
"tsup": "^8.0.0",
|
||||
"typescript": "^5.8.3"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
}
|
||||
}
|
||||
396
packages/spatial/src/GridSpatialIndex.ts
Normal file
396
packages/spatial/src/GridSpatialIndex.ts
Normal 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 });
|
||||
}
|
||||
331
packages/spatial/src/ISpatialQuery.ts
Normal file
331
packages/spatial/src/ISpatialQuery.ts
Normal 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));
|
||||
}
|
||||
68
packages/spatial/src/index.ts
Normal file
68
packages/spatial/src/index.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* @zh @esengine/spatial - 空间查询和索引系统
|
||||
* @en @esengine/spatial - Spatial Query and Indexing System
|
||||
*
|
||||
* @zh 提供空间查询能力,支持范围查询、最近邻查询和射线检测
|
||||
* @en Provides spatial query capabilities including range queries, nearest neighbor queries, and raycasting
|
||||
*/
|
||||
|
||||
// =============================================================================
|
||||
// 接口和类型 | 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';
|
||||
|
||||
// =============================================================================
|
||||
// 服务令牌 | Service Tokens
|
||||
// =============================================================================
|
||||
|
||||
export { SpatialIndexToken, SpatialQueryToken } from './tokens';
|
||||
|
||||
// =============================================================================
|
||||
// 蓝图节点 | Blueprint Nodes
|
||||
// =============================================================================
|
||||
|
||||
export {
|
||||
// Templates
|
||||
FindInRadiusTemplate,
|
||||
FindInRectTemplate,
|
||||
FindNearestTemplate,
|
||||
FindKNearestTemplate,
|
||||
RaycastTemplate,
|
||||
RaycastFirstTemplate,
|
||||
// Executors
|
||||
FindInRadiusExecutor,
|
||||
FindInRectExecutor,
|
||||
FindNearestExecutor,
|
||||
FindKNearestExecutor,
|
||||
RaycastExecutor,
|
||||
RaycastFirstExecutor,
|
||||
// Collection
|
||||
SpatialQueryNodeDefinitions
|
||||
} from './nodes';
|
||||
556
packages/spatial/src/nodes/SpatialQueryNodes.ts
Normal file
556
packages/spatial/src/nodes/SpatialQueryNodes.ts
Normal 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() }
|
||||
];
|
||||
23
packages/spatial/src/nodes/index.ts
Normal file
23
packages/spatial/src/nodes/index.ts
Normal 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';
|
||||
25
packages/spatial/src/tokens.ts
Normal file
25
packages/spatial/src/tokens.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* @zh 空间查询服务令牌
|
||||
* @en Spatial Query Service Tokens
|
||||
*/
|
||||
|
||||
import { createServiceToken } from '@esengine/ecs-framework';
|
||||
import type { ISpatialIndex, ISpatialQuery } from './ISpatialQuery';
|
||||
|
||||
/**
|
||||
* @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');
|
||||
22
packages/spatial/tsconfig.build.json
Normal file
22
packages/spatial/tsconfig.build.json
Normal file
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"module": "ES2020",
|
||||
"moduleResolution": "bundler",
|
||||
"lib": ["ES2020", "DOM"],
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"resolveJsonModule": true,
|
||||
"experimentalDecorators": true,
|
||||
"emitDecoratorMetadata": true
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
14
packages/spatial/tsconfig.json
Normal file
14
packages/spatial/tsconfig.json
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src"
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist"],
|
||||
"references": [
|
||||
{ "path": "../core" },
|
||||
{ "path": "../blueprint" }
|
||||
]
|
||||
}
|
||||
15
packages/spatial/tsup.config.ts
Normal file
15
packages/spatial/tsup.config.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { defineConfig } from 'tsup';
|
||||
|
||||
export default defineConfig({
|
||||
entry: ['src/index.ts'],
|
||||
format: ['esm'],
|
||||
dts: true,
|
||||
sourcemap: true,
|
||||
clean: true,
|
||||
external: [
|
||||
'@esengine/ecs-framework',
|
||||
'@esengine/ecs-framework-math',
|
||||
'@esengine/blueprint'
|
||||
],
|
||||
tsconfig: 'tsconfig.build.json'
|
||||
});
|
||||
31
pnpm-lock.yaml
generated
31
pnpm-lock.yaml
generated
@@ -1719,6 +1719,37 @@ importers:
|
||||
specifier: ^5.0.8
|
||||
version: 5.0.8(@types/react@18.3.27)(react@18.3.1)(use-sync-external-store@1.6.0(react@18.3.1))
|
||||
|
||||
packages/spatial:
|
||||
dependencies:
|
||||
tslib:
|
||||
specifier: ^2.8.1
|
||||
version: 2.8.1
|
||||
devDependencies:
|
||||
'@esengine/blueprint':
|
||||
specifier: workspace:*
|
||||
version: link:../blueprint
|
||||
'@esengine/build-config':
|
||||
specifier: workspace:*
|
||||
version: link:../build-config
|
||||
'@esengine/ecs-framework':
|
||||
specifier: workspace:*
|
||||
version: link:../core
|
||||
'@esengine/ecs-framework-math':
|
||||
specifier: workspace:*
|
||||
version: link:../math
|
||||
'@types/node':
|
||||
specifier: ^20.19.17
|
||||
version: 20.19.25
|
||||
rimraf:
|
||||
specifier: ^5.0.0
|
||||
version: 5.0.10
|
||||
tsup:
|
||||
specifier: ^8.0.0
|
||||
version: 8.5.1(@microsoft/api-extractor@7.55.1(@types/node@20.19.25))(@swc/core@1.15.3)(jiti@2.6.1)(postcss@8.5.6)(tsx@4.21.0)(typescript@5.9.3)(yaml@2.8.1)
|
||||
typescript:
|
||||
specifier: ^5.8.3
|
||||
version: 5.9.3
|
||||
|
||||
packages/sprite:
|
||||
devDependencies:
|
||||
'@esengine/asset-system':
|
||||
|
||||
151
scripts/typedoc-plugin-bilingual.mjs
Normal file
151
scripts/typedoc-plugin-bilingual.mjs
Normal file
@@ -0,0 +1,151 @@
|
||||
/**
|
||||
* TypeDoc Plugin for Bilingual Documentation
|
||||
* TypeDoc 双语文档插件
|
||||
*
|
||||
* Supports @zh and @en tags for bilingual documentation generation.
|
||||
* 支持 @zh 和 @en 标签来生成双语文档。
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* /**
|
||||
* * @zh 组件基类,所有组件都应继承此类
|
||||
* * @en Base class for all components
|
||||
* *\/
|
||||
* export class Component { }
|
||||
* ```
|
||||
*/
|
||||
|
||||
import { Application, Converter, ReflectionKind, Comment, CommentTag } from 'typedoc';
|
||||
|
||||
/**
|
||||
* @zh TypeDoc 双语插件入口
|
||||
* @en TypeDoc bilingual plugin entry
|
||||
* @param {Application} app - TypeDoc 应用实例 | TypeDoc application instance
|
||||
*/
|
||||
export function load(app) {
|
||||
// 注册自定义标签 | Register custom tags
|
||||
app.options.addReader({
|
||||
name: 'bilingual-tags',
|
||||
order: 0,
|
||||
supportsPackages: false,
|
||||
read(container) {
|
||||
// 添加 @zh 和 @en 作为已知标签
|
||||
// Add @zh and @en as known tags
|
||||
const knownTags = container.getValue('blockTags') || [];
|
||||
if (!knownTags.includes('@zh')) {
|
||||
knownTags.push('@zh');
|
||||
}
|
||||
if (!knownTags.includes('@en')) {
|
||||
knownTags.push('@en');
|
||||
}
|
||||
container.setValue('blockTags', knownTags);
|
||||
}
|
||||
});
|
||||
|
||||
// 监听解析完成事件 | Listen for conversion completion
|
||||
app.converter.on(Converter.EVENT_RESOLVE_BEGIN, (context) => {
|
||||
processReflections(context.project);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @zh 处理所有反射对象的注释
|
||||
* @en Process comments for all reflections
|
||||
* @param {import('typedoc').ProjectReflection} project
|
||||
*/
|
||||
function processReflections(project) {
|
||||
for (const reflection of project.getReflectionsByKind(ReflectionKind.All)) {
|
||||
if (reflection.comment) {
|
||||
processBilingualComment(reflection.comment);
|
||||
}
|
||||
|
||||
// 处理签名注释 | Process signature comments
|
||||
if ('signatures' in reflection && reflection.signatures) {
|
||||
for (const sig of reflection.signatures) {
|
||||
if (sig.comment) {
|
||||
processBilingualComment(sig.comment);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @zh 处理单个注释的双语标签
|
||||
* @en Process bilingual tags in a single comment
|
||||
* @param {Comment} comment
|
||||
*/
|
||||
function processBilingualComment(comment) {
|
||||
const zhTags = comment.blockTags?.filter(tag => tag.tag === '@zh') || [];
|
||||
const enTags = comment.blockTags?.filter(tag => tag.tag === '@en') || [];
|
||||
|
||||
if (zhTags.length === 0 && enTags.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 构建双语摘要 | Build bilingual summary
|
||||
const parts = [];
|
||||
|
||||
// 添加中文部分 | Add Chinese part
|
||||
if (zhTags.length > 0) {
|
||||
const zhText = zhTags.map(tag => tagContentToString(tag)).join('\n');
|
||||
parts.push(zhText);
|
||||
}
|
||||
|
||||
// 添加英文部分 | Add English part
|
||||
if (enTags.length > 0) {
|
||||
const enText = enTags.map(tag => tagContentToString(tag)).join('\n');
|
||||
if (parts.length > 0) {
|
||||
parts.push(''); // 空行分隔 | Empty line separator
|
||||
}
|
||||
parts.push(enText);
|
||||
}
|
||||
|
||||
// 如果有双语内容,更新摘要 | Update summary if bilingual content exists
|
||||
if (parts.length > 0) {
|
||||
// 保留原有摘要(如果不是来自 @zh/@en)| Keep original summary if not from @zh/@en
|
||||
const originalSummary = comment.summary?.map(part => {
|
||||
if (typeof part === 'string') return part;
|
||||
if (part.kind === 'text') return part.text;
|
||||
return '';
|
||||
}).join('') || '';
|
||||
|
||||
// 如果原有摘要不是空的且不是重复的,保留它
|
||||
// Keep original summary if not empty and not duplicate
|
||||
const bilingualText = parts.join('\n');
|
||||
if (originalSummary && !bilingualText.includes(originalSummary.trim())) {
|
||||
comment.summary = [
|
||||
{ kind: 'text', text: originalSummary + '\n\n' + bilingualText }
|
||||
];
|
||||
} else {
|
||||
comment.summary = [
|
||||
{ kind: 'text', text: bilingualText }
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
// 移除已处理的 @zh/@en 标签,避免重复显示
|
||||
// Remove processed @zh/@en tags to avoid duplicate display
|
||||
comment.blockTags = comment.blockTags?.filter(
|
||||
tag => tag.tag !== '@zh' && tag.tag !== '@en'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @zh 将标签内容转换为字符串
|
||||
* @en Convert tag content to string
|
||||
* @param {CommentTag} tag
|
||||
* @returns {string}
|
||||
*/
|
||||
function tagContentToString(tag) {
|
||||
if (!tag.content) return '';
|
||||
|
||||
return tag.content.map(part => {
|
||||
if (typeof part === 'string') return part;
|
||||
if (part.kind === 'text') return part.text;
|
||||
if (part.kind === 'code') return '`' + part.text + '`';
|
||||
return '';
|
||||
}).join('');
|
||||
}
|
||||
|
||||
export default { load };
|
||||
Reference in New Issue
Block a user