چیست؟
خیلی از سؤالهای بازی مکانیاند: کدام دشمنها داخل این انفجارند، کدام boidها آنقدر نزدیکاند که با هم دسته تشکیل دهند، آهنربا کدام آیتمها را میتواند بکشد؟ جواب سادهلوحانه این است که روی همهٔ اشیا حلقه بزنی و فاصله را اندازه بگیری. برای ۵۰ یونیت مشکلی نیست، اما وقتی ۵٬۰۰۰ یونیت در هر فریم همین سؤال را بپرسند، فاجعه است.
spatial partition دنیا را به ناحیههایی تقسیم میکند و هر شیء را زیر ناحیهای که در آن است ثبت میکند. سادهترین نسخهاش یک grid یکنواخت است: یک Dictionary<Vector2Int, List<Unit>> که کلیدش خانهٔ grid است. هر query محدودهٔ خودش را به بازهای از خانهها تبدیل میکند و فقط اشیای ذخیرهشده در همان خانهها را بررسی میکند.
اشیا باید وقتی به خانهٔ دیگری میروند به grid خبر بدهند، اما این کار ارزان است: یک حذف و یک اضافه، آن هم فقط وقتی از مرز خانه رد میشوند. در عوض، هزینهٔ پیدا کردن همسایهها از O(n) برای هر query به حدود همان چند شیء داخل خانههای اطراف میرسد. Quadtree، octree و BVH نسخههای تطبیقپذیر همین ایدهاند.
کِی به کار میآید؟
وقتی از آن استفاده کن که اشیای زیادی مدام اطرافشان را جستوجو میکنند: هدایت جمعیت، انتخاب هدف در بازیهای RTS، برخورد در بازیهای bullet-hell، ادراک AI و voice chat مجاورتی.
grid یکنواخت وقتی بهترین عملکرد را دارد که اشیا تقریباً یکنواخت پخش شده باشند و اندازهشان نزدیک به هم باشد. برای دنیاهایی که اشیا در آنها بهشدت خوشهای جمع میشوند یا اختلاف اندازه زیاد است، quadtree بهتر خودش را وفق میدهد.
اگر فقط چند ده شیء داری، یا queryهای فیزیک Unity مثل Physics.OverlapSphereNonAlloc همین حالا جواب سؤالت را میدهند، broadphase داخلی موتور احتمالاً کافی است.
دموی تعاملی
دکمهها را بزن و ببین اشیا چطور با هم کار میکنند. کنسول همان چیزی را نشان میدهد که کد C# پایین صفحه لاگ میکند.
کد
using System.Collections.Generic;
using UnityEngine;
namespace Patterns.Optimization.SpatialPartition
{
/// <summary>
/// Spawns wandering units, then every frame finds those within a radius
/// of this object using the grid instead of scanning every unit.
/// </summary>
public class SpatialTester : MonoBehaviour
{
[SerializeField] private Unit unitPrefab;
[SerializeField] private int unitCount = 500;
[SerializeField] private float worldSize = 100f;
[SerializeField] private float cellSize = 10f;
[SerializeField] private float queryRadius = 8f;
private SpatialGrid<Unit> grid;
private readonly List<Unit> results = new();
private void Awake()
{
grid = new SpatialGrid<Unit>(cellSize);
for (int i = 0; i < unitCount; i++)
{
Vector2 p = new(Random.value * worldSize, Random.value * worldSize);
Unit unit = Instantiate(unitPrefab, new Vector3(p.x, 0f, p.y), Quaternion.identity);
unit.Init(grid, worldSize);
}
}
private void Update()
{
Vector2 center = new(transform.position.x, transform.position.z);
int checks = grid.Query(center, queryRadius, results);
foreach (Unit unit in results)
Debug.DrawLine(transform.position, unit.transform.position, Color.cyan);
if (Time.frameCount % 60 == 0)
Debug.Log($"Found {results.Count} with {checks} distance checks (brute force: {unitCount}).");
}
}
}using System.Collections.Generic;
using UnityEngine;
namespace Patterns.Optimization.SpatialPartition
{
/// <summary>
/// A uniform grid that buckets items by cell. Queries only look at the
/// cells overlapping the search circle.
/// </summary>
public class SpatialGrid<T> where T : class, ISpatialItem
{
private readonly float cellSize;
private readonly Dictionary<Vector2Int, List<T>> cells = new();
public SpatialGrid(float cellSize) => this.cellSize = cellSize;
public Vector2Int CellOf(Vector2 position) =>
new(Mathf.FloorToInt(position.x / cellSize), Mathf.FloorToInt(position.y / cellSize));
public void Add(T item, Vector2Int cell)
{
if (!cells.TryGetValue(cell, out var list))
cells[cell] = list = new List<T>();
list.Add(item);
}
public void Remove(T item, Vector2Int cell)
{
if (cells.TryGetValue(cell, out var list))
list.Remove(item);
}
public void Move(T item, Vector2Int from, Vector2Int to)
{
if (from == to) return;
Remove(item, from);
Add(item, to);
}
/// <summary>Fills results; returns how many distance checks ran.</summary>
public int Query(Vector2 center, float radius, List<T> results)
{
results.Clear();
int checks = 0;
float radiusSq = radius * radius;
Vector2Int min = CellOf(center - Vector2.one * radius);
Vector2Int max = CellOf(center + Vector2.one * radius);
for (int x = min.x; x <= max.x; x++)
for (int y = min.y; y <= max.y; y++)
{
if (!cells.TryGetValue(new Vector2Int(x, y), out var list)) continue;
foreach (T item in list)
{
checks++;
if ((item.Position - center).sqrMagnitude <= radiusSq)
results.Add(item);
}
}
return checks;
}
}
/// <summary>Anything the grid can store.</summary>
public interface ISpatialItem
{
Vector2 Position { get; }
}
}using UnityEngine;
namespace Patterns.Optimization.SpatialPartition
{
/// <summary>
/// A wandering unit that keeps the grid informed whenever it crosses
/// into a new cell.
/// </summary>
public class Unit : MonoBehaviour, ISpatialItem
{
[SerializeField] private float speed = 4f;
private SpatialGrid<Unit> grid;
private Vector2Int cell;
private Vector2 velocity;
private float bounds;
public Vector2 Position => new(transform.position.x, transform.position.z);
public void Init(SpatialGrid<Unit> owner, float worldSize)
{
grid = owner;
bounds = worldSize;
velocity = Random.insideUnitCircle.normalized * speed;
cell = grid.CellOf(Position);
grid.Add(this, cell);
}
private void Update()
{
Vector2 p = Position + velocity * Time.deltaTime;
if (p.x < 0f || p.x > bounds) velocity.x = -velocity.x;
if (p.y < 0f || p.y > bounds) velocity.y = -velocity.y;
p = new Vector2(Mathf.Clamp(p.x, 0f, bounds), Mathf.Clamp(p.y, 0f, bounds));
transform.position = new Vector3(p.x, 0f, p.y);
// Re-bucket only when the cell actually changes.
Vector2Int newCell = grid.CellOf(p);
if (newCell != cell)
{
grid.Move(this, cell, newCell);
cell = newCell;
}
}
private void OnDestroy() => grid?.Remove(this, cell);
}
}قبل و بعد از پترن
یک موقعیت واقعی: یونیتهایی که برای پیدا کردن همسایه همهٔ یونیتهای دیگر را چک میکنند. اینجا کد بدون پترن، نسخهٔ بازنویسیشده و diff دقیق بینشان را میبینی.
! مشکل کجاست؟
هر Unit خودش را به لیست static به اسم all اضافه میکند، و FindNearest در هر فریم روی کل این لیست حلقه میزند تا نزدیکترین یونیت داخل senseRadius را پیدا کند.
با ۵۰۰ یونیت یعنی ۲۵۰٬۰۰۰ چک فاصله در هر فریم، که تقریباً همهاش برای یونیتهای آن سر نقشه است. ارتش را دو برابر کن تا هزینه چهار برابر شود؛ این همان دیوار معروف O(n²) است.
✓ چه چیزی عوض شد؟
- لیست static به اسم
allجایش را به یکSpatialGrid<Unit>مشترک داد و یونیت حالاISpatialItemرا پیاده میکند. - متد
Initیونیت را در خانهٔ شروعش ثبت میکند، وUpdateفقط وقتی یونیت وارد خانهٔ تازهای میشودgrid.Moveرا صدا میزند. - متد
FindNearestاولgrid.Queryرا صدا میزند، پس حلقه فقط یونیتهای خانههایی را میبیند که باsenseRadiusهمپوشانی دارند. - خود چک فاصله هیچ تغییری نکرده؛ grid فقط لیستی را که حلقه رویش میچرخد کوچکتر میکند.
using System.Collections.Generic;
using UnityEngine;
namespace Patterns.Optimization.SpatialPartition
{
/// <summary>
/// Without a spatial partition: every unit scans every other unit each
/// frame to find its nearest neighbour. That is O(n²) per frame.
/// </summary>
public class Unit : MonoBehaviour
{
[SerializeField] private float speed = 4f;
[SerializeField] private float senseRadius = 8f;
private static readonly List<Unit> all = new();
private Vector2 velocity;
private float bounds;
public Vector2 Position => new(transform.position.x, transform.position.z);
public Unit Nearest { get; private set; }
public void Init(float worldSize)
{
bounds = worldSize;
velocity = Random.insideUnitCircle.normalized * speed;
all.Add(this);
}
private void Update()
{
Vector2 p = Position + velocity * Time.deltaTime;
if (p.x < 0f || p.x > bounds) velocity.x = -velocity.x;
if (p.y < 0f || p.y > bounds) velocity.y = -velocity.y;
p = new Vector2(Mathf.Clamp(p.x, 0f, bounds), Mathf.Clamp(p.y, 0f, bounds));
transform.position = new Vector3(p.x, 0f, p.y);
Nearest = FindNearest();
}
private Unit FindNearest()
{
Unit best = null;
float bestSq = senseRadius * senseRadius;
foreach (Unit other in all) // every unit, however far away
{
if (other == this) continue;
float sq = (other.Position - Position).sqrMagnitude;
if (sq < bestSq) { bestSq = sq; best = other; }
}
return best;
}
private void OnDestroy() => all.Remove(this);
}
}using System.Collections.Generic;
using UnityEngine;
namespace Patterns.Optimization.SpatialPartition
{
/// <summary>
/// With a spatial partition: each unit lives in a grid cell and only
/// checks the units in the cells around it.
/// </summary>
public class Unit : MonoBehaviour, ISpatialItem
{
[SerializeField] private float speed = 4f;
[SerializeField] private float senseRadius = 8f;
private static readonly List<Unit> nearby = new();
private SpatialGrid<Unit> grid;
private Vector2Int cell;
private Vector2 velocity;
private float bounds;
public Vector2 Position => new(transform.position.x, transform.position.z);
public Unit Nearest { get; private set; }
public void Init(SpatialGrid<Unit> owner, float worldSize)
{
grid = owner;
bounds = worldSize;
velocity = Random.insideUnitCircle.normalized * speed;
cell = grid.CellOf(Position);
grid.Add(this, cell);
}
private void Update()
{
Vector2 p = Position + velocity * Time.deltaTime;
if (p.x < 0f || p.x > bounds) velocity.x = -velocity.x;
if (p.y < 0f || p.y > bounds) velocity.y = -velocity.y;
p = new Vector2(Mathf.Clamp(p.x, 0f, bounds), Mathf.Clamp(p.y, 0f, bounds));
transform.position = new Vector3(p.x, 0f, p.y);
// Re-bucket only when the cell actually changes.
Vector2Int newCell = grid.CellOf(p);
if (newCell != cell)
{
grid.Move(this, cell, newCell);
cell = newCell;
}
Nearest = FindNearest();
}
private Unit FindNearest()
{
Unit best = null;
float bestSq = senseRadius * senseRadius;
grid.Query(Position, senseRadius, nearby);
foreach (Unit other in nearby) // only units in the cells around us
{
if (other == this) continue;
float sq = (other.Position - Position).sqrMagnitude;
if (sq < bestSq) { bestSq = sq; best = other; }
}
return best;
}
private void OnDestroy() => grid?.Remove(this, cell);
}
}مزایا و معایب
+ مزایا
- جستوجوی همسایهها را از بررسی همهچیز به بررسی یک مجموعهٔ کوچک محلی تبدیل میکند.
- پیادهسازی grid یکنواخت خیلی کوتاه است و هزینههایش قابل پیشبینی و cache-friendly است.
- برای دادههای غیرفیزیکی هم کار میکند: blackboardهای AI، منابع صدا، کنار زدن fog-of-war.
− معایب
- اشیا باید همیشه همگام نگه داشته شوند. اگر بهروزرسانی یک یونیت جابهجاشده یادت برود، queryها بیصدا جواب غلط میدهند.
- انتخاب اندازهٔ خانه یک بدهبستان است: خیلی کوچک یعنی هر query به خانههای زیادی سر میزند، خیلی بزرگ یعنی خانهها شلوغ میشوند.
- برای سطلها حافظهٔ اضافه مصرف میکند. اگر هم اشیا در یک خانه تجمع کنند، کارایی دوباره به جستوجوی brute force نزدیک میشود.
چند نکتهٔ کاربردی
- ۰۱اندازهٔ خانه را نزدیک به رایجترین شعاع queryات انتخاب کن؛ آنوقت هر query حداکثر به یک بلوک ۳×۳ از خانهها سر میزند.
- ۰۲یک یونیت را فقط وقتی دوباره دستهبندی کن که مختصات خانهاش واقعاً تغییر کرده باشد. اول
Vector2Intقبلی و جدید را مقایسه کن. - ۰۳بهجای برگرداندن یک لیست تازه، یک
List<T>نتایج را به query پاس بده و دوباره از آن استفاده کن تا مسیر پرتکرار بدون تخصیص حافظه بماند. - ۰۴grid فقط تعداد کاندیداها را کم میکند. روی همین کاندیداها هنوز باید بررسی دقیق فاصله (
sqrMagnitudeدر مقایسه با مربع شعاع) را انجام بدهی. - ۰۵برای هزاران یونیت، بهجای dictionaryای از لیستها، یک grid مبتنی بر آرایهٔ تخت همراه با Burst و Jobs system را در نظر بگیر.