ABOUT PORTFOLIO GAMES DEVLOG DOCS TOOLS CONTACT
HOME > DOCS > C / raylib > O(N^2) 브루트포스 충돌을 O(N)으로 가속하는 C 언어 2D 공간 분할 해시 그리드Accelerating O(N^2) Collision Detection to O(N) with a 2D Spatial Hash Grid in C
C / raylib Advanced C99 / raylib

O(N^2) 브루트포스 충돌을 O(N)으로 가속하는 C 언어 2D 공간 분할 해시 그리드Accelerating O(N^2) Collision Detection to O(N) with a 2D Spatial Hash Grid in C

화면을 고정 크기 셀(Cell) 그리드로 분할하고 해시 함수를 통해 인접 셀 내부의 객체끼리만 충돌을 검사하여 다수의 오브젝트를 초당 60프레임으로 처리하는 구조입니다.Partitioning world space into fixed-size grid cells and hashing 2D integer coordinates so only neighboring entities are tested for collision at 60 FPS.

#C #SpatialHashing #Collision #Optimization #DataStructure
핵심 개념물체가 $N$개일 때 이중 루프로 모든 쌍을 전수 검사하면 연산 횟수는 $\frac{N(N-1)}{2}$로 객체 수의 제곱에 비례해 증가합니다. 월드 공간을 고정 크기(예: $64 \times 64$) 셀로 나누고 물체의 좌표 $(x, y)$를 정수 해시 키로 변환해 버킷에 등록하면, 같은 셀 및 인접 셀의 물체들만 검사하므로 평균 시간 복잡도를 $O(N)$ 수준으로 낮출 수 있습니다.
Key ConceptTesting all pairs among $N$ entities with a nested loop requires $\frac{N(N-1)}{2}$ checks, scaling quadratically with entity count. Partitioning world space into fixed-size cells (e.g., $64 \times 64$) and hashing entity coordinates $(x, y)$ into buckets restricts collision checks to entities in the same or adjacent cells, reducing average-case complexity to $O(N)$.

1. 공간 해시 키 계산 및 버킷 구조1. Spatial Hash Key Calculation and Intrusive Bucket Structure

spatial_hash.c
#include <math.h>
#include <stdint.h>

#define CELL_SIZE    64.0f
#define HASH_BUCKETS 1024 // 2의 거듭제곱 버킷 수

typedef struct Entity {
    int id;
    float x, y, radius;
    struct Entity *next_in_bucket; // 침투형(Intrusive) 단일 연결 리스트
} Entity;

static Entity *g_buckets[HASH_BUCKETS];

// 큰 소수를 곱해 공간 군집 충돌을 줄이는 2D 정수 해시 함수
uint32_t HashCell(int cellX, int cellY) {
    uint32_t h = ((uint32_t)cellX * 73856093u) ^ ((uint32_t)cellY * 19349663u);
    return h & (HASH_BUCKETS - 1);
}

void ClearGrid(void) {
    for (int i = 0; i < HASH_BUCKETS; ++i) g_buckets[i] = NULL;
}

void InsertEntity(Entity *e) {
    int cellX = (int)floorf(e->x / CELL_SIZE);
    int cellY = (int)floorf(e->y / CELL_SIZE);
    uint32_t bucket = HashCell(cellX, cellY);

    e->next_in_bucket = g_buckets[bucket];
    g_buckets[bucket] = e;
}
spatial_hash.c
#include <math.h>
#include <stdint.h>

#define CELL_SIZE    64.0f
#define HASH_BUCKETS 1024 // Power-of-two bucket count

typedef struct Entity {
    int id;
    float x, y, radius;
    struct Entity *next_in_bucket; // Intrusive singly linked list pointer
} Entity;

static Entity *g_buckets[HASH_BUCKETS];

// 2D integer hash function using large primes to minimize spatial clustering
uint32_t HashCell(int cellX, int cellY) {
    uint32_t h = ((uint32_t)cellX * 73856093u) ^ ((uint32_t)cellY * 19349663u);
    return h & (HASH_BUCKETS - 1);
}

void ClearGrid(void) {
    for (int i = 0; i < HASH_BUCKETS; ++i) g_buckets[i] = NULL;
}

void InsertEntity(Entity *e) {
    int cellX = (int)floorf(e->x / CELL_SIZE);
    int cellY = (int)floorf(e->y / CELL_SIZE);
    uint32_t bucket = HashCell(cellX, cellY);

    e->next_in_bucket = g_buckets[bucket];
    g_buckets[bucket] = e;
}

2. 실무 적용 및 주의사항2. Practical Considerations and Caveats

  • 셀 경계선에 걸친 객체의 인접 9개 셀 검사: 객체의 중심점만 단일 셀에 등록한 경우, 셀 경계선 근처에 있는 두 객체가 서로 다른 셀(cellX와 cellX + 1)에 속하면서도 반지름이 겹칠 수 있습니다. 따라서 충돌 질의 시에는 자신의 셀을 포함한 주변 $3 \times 3$ (총 9개) 셀 버킷을 순회해야 경계선 누락이 발생하지 않습니다.
  • 음수 좌표에서의 floorf 및 부호 없는 해시 처리: C 언어에서 (int)(-10.0f / 64.0f)는 -1이 아닌 0으로 절사되어 원점 근처 셀의 크기가 두 배로 왜곡됩니다. 반드시 floorf(e->x / CELL_SIZE)를 사용해 음수 방향에서도 균일한 격자를 유지하고, 해시 인덱스는 uint32_t 비트마스크로 음수 나머지를 방지해야 합니다.
  • 최적 셀 크기(CELL_SIZE) 선정 기준: 셀 크기가 너무 작으면 객체가 여러 셀에 걸쳐 오버헤드가 커지고, 너무 크면 한 버킷에 수백 개의 객체가 몰려 $O(N^2)$에 가까워집니다. 일반적으로 가장 흔한 이동 객체 지름의 1.5배~2배 크기로 설정할 때 탐색 효율이 가장 높습니다.
  • Query the $3 \times 3$ Neighboring Cells for Boundary Overlaps: When inserting an entity by its center point alone, two overlapping entities straddling a cell boundary may reside in adjacent cells (cellX and cellX + 1). Always iterate over the $3 \times 3$ neighborhood (9 cells) during collision queries so boundary collisions are not missed.
  • Use floorf and Unsigned Bitmasking for Negative Coordinates: Truncating division (int)(-10.0f / 64.0f) rounds toward zero (0 instead of -1), doubling cell width across the origin. Use floorf(e->x / CELL_SIZE) for uniform cells and mask unsigned uint32_t hashes to avoid negative remainder indices.
  • Choosing CELL_SIZE: Setting CELL_SIZE to roughly 1.5x–2x the diameter of the most common moving entity balances bucket occupancy against multi-cell boundary checks.

공간 해시 그리드는 쿼드트리(Quadtree)처럼 매 프레임 트리를 재구축할 필요 없이, 배열 초기화(ClearGrid)와 침투형 연결 리스트 포인터 연결만으로 수천 개의 동적 객체를 고속으로 분류할 수 있습니다.

Unlike hierarchical quadtrees that require tree rebalancing as objects move, a spatial hash grid with intrusive linked-list pointers resets and rebuilds in a single linear pass each frame.