perf
game/perf 為高頻遊戲主迴圈提供確定性、穩態零分配的效能基礎件:物件池(Pool、Arena、SlicePool)、2D 寬相空間索引(SpatialHash、Quadtree)以及視口精靈裁剪(CullBatch、BatchCuller、Cull)。
import "github.com/nsgo-dev/game/pkg/perf"
確定性物件池(Pool、Arena、SlicePool)
與 sync.Pool 不同,perf 的物件池不會在 GC 期間丟棄快取物件,從而在桌面、移動端和 WebAssembly 上保持穩定的幀耗時:
// 帶重置回撥的指標池:
bullets := perf.NewPool(128, func(b *Bullet) { *b = Bullet{} })
b := bullets.Acquire()
b.X, b.Y = playerX, playerY
bullets.Release(b)
// 快取友好的緊湊陣列 Arena,使用帶代數校驗的 Handle(過期控制代碼安全返回 false):
enemies := perf.NewArena[Enemy](64, nil)
h, e := enemies.Alloc()
e.HP = 100
for handle, item := range enemies.All() {
stepEnemy(handle, item, dt)
}
enemies.Remove(h)
// 可複用的臨時切片池:
scratch := perf.NewSlicePool[uint32](16)
ids := scratch.Acquire(64)
defer scratch.Release(ids)
| 型別 | 適用場景 | 核心方法 |
|---|---|---|
Pool[T] |
需要穩定指標的池化結構體(彈幕、粒子) | Acquire、Release、Prewarm、Active、Free、Cap、Reset |
Arena[T] |
緊湊連續遍歷 + O(1) 交換刪除 + 帶代數 Handle |
Add、Alloc、Get、Has、Remove、Slice、ForEach、All、Reset |
SlicePool[T] |
每幀臨時查詢或排序緩衝區 | Acquire(minCap)、Release(s)、Free、Reset |
2D 空間索引(SpatialHash、Quadtree)
用 O(k) 的區域查詢、點查詢與重疊配對替代 O(n²) 暴力掃描。兩種索引都會複用內部桶/節點,並把結果寫入呼叫方傳入的切片,實現穩態查詢零分配:
grid := perf.NewSpatialHash[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)
})
實體尺寸相近或世界無固定邊界時優先使用 SpatialHash[ID];實體尺寸差異較大或集中在已知世界矩形內時使用 NewQuadtree[ID](worldBounds, maxItems, maxDepth)。兩者均提供 Insert、Update、Remove、Clear、Len、Query 與 QueryPoint。
視口裁剪(CullBatch、BatchCuller、Cull)
在向 core.Drawing 提交繪製命令前先剔除螢幕外的精靈:
var culler perf.BatchCuller
// 在 Canvas.Draw 中:
culler.Draw(spriteBatch, cameraViewBounds, d)
BatchCuller.Draw(batch, view, d)複用內部臨時sprite.Batch,做到每幀零分配;若只需一次性便捷呼叫,可使用perf.CullBatch(batch, view, d)。- 使用
perf.CullSprites(view, src, dst[:0])、perf.SpriteBounds(s)、perf.Intersects(a, b)或泛型perf.Cull(view, items, boundsOf, dst[:0])裁剪任意 2D 世界物件。