spatial
game/spatial 無需逐個檢測即可找出某個區域附近或視口內的 2D 物件:2D 寬相空間索引(Hash、Quadtree)以及視口精靈裁剪(CullBatch、BatchCuller、Cull),預熱後零分配。物件池見 mempool。
import "github.com/nsgo-dev/game/pkg/spatial"
2D 空間索引(Hash、Quadtree)
用 O(k) 的區域查詢、點查詢與重疊配對替代 O(n²) 暴力掃描。兩種索引都會複用內部桶/節點,並把結果寫入呼叫方傳入的切片,實現穩態查詢零分配:
grid := spatial.NewHash[uint32](64) // 單元格尺寸通常設為常見實體尺寸的 1~2 倍
grid.Insert(id, entityBounds)
grid.Update(id, movedBounds)
// 複用切片進行零分配區域查詢:
hits = grid.Query(cameraView, hits[:0])
// 去重後的寬相重疊實體對:
grid.QueryPairs(func(a, b uint32) {
resolveNarrowPhase(a, b)
})
實體尺寸相近或世界無固定邊界時優先使用 Hash[ID];實體尺寸差異較大或集中在已知世界矩形內時使用 NewQuadtree[ID](worldBounds, maxItems, maxDepth)。兩者均提供 Insert、Update、Remove、Clear、Len、Query 與 QueryPoint。
視口裁剪(CullBatch、BatchCuller、Cull)
在向 core.Drawing 提交繪製命令前先剔除螢幕外的精靈:
var culler spatial.BatchCuller
// 在 Canvas.Draw 中:
culler.Draw(spriteBatch, cameraViewBounds, d)
BatchCuller.Draw(batch, view, d)複用內部臨時sprite.Batch,做到每幀零分配;若只需一次性便捷呼叫,可使用spatial.CullBatch(batch, view, d)。- 使用
spatial.CullSprites(view, src, dst[:0])、spatial.SpriteBounds(s)、spatial.Intersects(a, b)或泛型spatial.Cull(view, items, boundsOf, dst[:0])裁剪任意 2D 世界物件。
圓形查詢
Hash.QueryCircle 和 Quadtree.QueryCircle 會按各自確定性的遍歷順序,把包圍盒與圓相交的實體追加到結果中。跨幀複用輸出切片:
hits = grid.QueryCircle(playerPos, 96, hits[:0])
寬相階段先訪問圓的包圍單元格或象限,再檢查每個實體包圍盒上距離圓心最近的點。負數、非有限或空圓會原樣返回輸出切片。
最近鄰查詢
Hash 和 Quadtree 按查詢點到各實體包圍盒最近點的距離查詢。Nearest 返回 ID、以點為單位的距離,以及是否找到匹配項。KNearest 按距離順序追加最多 k 個 ID。過濾函式可以為 nil,表示接受所有 ID。距離上限 maxDist 包含邊界。0 只查找接觸查詢點的實體,正無窮表示無距離限制。
target, distance, ok := grid.Nearest(playerPos, 96, isEnemy)
allies = grid.KNearest(playerPos, 4, 64, isAlly, allies[:0])
距離相同時按較早的插入順序優先。更新實體保留其順序,刪除後重新插入會獲得新的順序。複用輸出緩衝區可在預熱後做到查詢零分配。過濾函式執行期間須避免訪問正在查詢的索引。