| 58 | * @en Uses uniform grid for spatial partitioning, suitable for evenly distributed objects |
| 59 | */ |
| 60 | export class GridSpatialIndex<T> implements ISpatialIndex<T> { |
| 61 | private readonly _cellSize: number; |
| 62 | private readonly _cells: Map<string, Set<GridItem<T>>> = new Map(); |
| 63 | private readonly _itemMap: Map<T, GridItem<T>> = new Map(); |
| 64 | |
| 65 | constructor(config: GridSpatialIndexConfig) { |
| 66 | this._cellSize = config.cellSize; |
| 67 | } |
| 68 | |
| 69 | // ========================================================================= |
| 70 | // ISpatialIndex 实现 | ISpatialIndex Implementation |
| 71 | // ========================================================================= |
| 72 | |
| 73 | get count(): number { |
| 74 | return this._itemMap.size; |
| 75 | } |
| 76 | |
| 77 | /** |
| 78 | * @zh 插入对象 |
| 79 | * @en Insert object |
| 80 | */ |
| 81 | insert(item: T, position: IVector2): void { |
| 82 | if (this._itemMap.has(item)) { |
| 83 | this.update(item, position); |
| 84 | return; |
| 85 | } |
| 86 | |
| 87 | const cellKey = this._getCellKey(position); |
| 88 | const gridItem: GridItem<T> = { item, position: { x: position.x, y: position.y }, cellKey }; |
| 89 | |
| 90 | this._itemMap.set(item, gridItem); |
| 91 | this._addToCell(cellKey, gridItem); |
| 92 | } |
| 93 | |
| 94 | /** |
| 95 | * @zh 移除对象 |
| 96 | * @en Remove object |
| 97 | */ |
| 98 | remove(item: T): boolean { |
| 99 | const gridItem = this._itemMap.get(item); |
| 100 | if (!gridItem) { |
| 101 | return false; |
| 102 | } |
| 103 | |
| 104 | this._removeFromCell(gridItem.cellKey, gridItem); |
| 105 | this._itemMap.delete(item); |
| 106 | return true; |
| 107 | } |
| 108 | |
| 109 | /** |
| 110 | * @zh 更新对象位置 |
| 111 | * @en Update object position |
| 112 | */ |
| 113 | update(item: T, newPosition: IVector2): boolean { |
| 114 | const gridItem = this._itemMap.get(item); |
| 115 | if (!gridItem) { |
| 116 | return false; |
| 117 | } |
nothing calls this directly
no outgoing calls
no test coverage detected