Unity / C#
Advanced
Unity 2021.3+ / Unity 6
인벤토리 및 타일 배치 검사를 위한 64비트 비트마스크(Bitmask) 연산64-Bit Bitmask Operations for Grid Inventory and Tile Placement
다차원 배열 2중 루프 순회를 단일 ulong 비트 연산(AND, OR, Shift)으로 치환하여 O(1) 복잡도로 오버랩과 경계를 검사하는 그리드 최적화 기법.A grid optimization technique that replaces nested 2D array loops with single ulong bitwise operations (AND, OR, Shift) for O(1) overlap and boundary checks.
#Unity #C# #Bitmask #Optimization #Inventory
핵심 개념타일 기반 인벤토리에서 8×8 슬롯의 점유 상태를
bool[8,8] 배열로 검사하면 마우스 드래그 프레임마다 2중 반복문이 실행됩니다. 이를 하나의 ulong(64비트 부호 없는 정수)으로 압축하면 단일 비트 AND(&) 연산으로 충돌 여부를 O(1)에 판정할 수 있습니다.Core ConceptChecking slot occupancy in an 8×8 tile-based inventory using a
bool[8,8] array requires nested loops on every mouse drag frame. Packing the grid state into a single ulong (64-bit unsigned integer) enables collision checks in O(1) time using a single bitwise AND (&) operation.1. 비트마스크 그리드 배치 엔진1. Bitmask Grid Placement Engine
public class BitmaskInventoryGrid
{
private ulong _occupiedMask = 0UL; // 8x8 = 64개 슬롯
// x, y 좌표를 0~63 비트 인덱스로 변환
private static int ToBitIndex(int x, int y) => y * 8 + x;
/// <summary>
/// 아이템 모양 마스크를 (targetX, targetY)에 배치 가능한지 O(1) 검사합니다.
/// </summary>
public bool CanPlace(ulong itemMask, int targetX, int targetY, int itemWidth, int itemHeight)
{
// 1. 그리드 경계 검사
if (targetX < 0 || targetY < 0 || targetX + itemWidth > 8 || targetY + itemHeight > 8)
return false;
// 2. 비트 시프트로 위치 이동
int shift = ToBitIndex(targetX, targetY);
ulong shiftedItemMask = itemMask << shift;
// 3. 중복 점유 검사 (AND 연산 결과가 0이어야 빈 자리)
return (_occupiedMask & shiftedItemMask) == 0UL;
}
/// <summary>
/// 아이템을 그리드에 배치하고 마스크를 갱신합니다.
/// </summary>
public void Place(ulong itemMask, int targetX, int targetY)
{
int shift = ToBitIndex(targetX, targetY);
_occupiedMask |= (itemMask << shift);
}
/// <summary>
/// 아이템을 그리드에서 제거합니다.
/// </summary>
public void Remove(ulong itemMask, int targetX, int targetY)
{
int shift = ToBitIndex(targetX, targetY);
_occupiedMask &= ~(itemMask << shift);
}
}
public class BitmaskInventoryGrid
{
private ulong _occupiedMask = 0UL; // 8x8 = 64 slots
// Convert (x, y) coordinates to a bit index from 0 to 63
private static int ToBitIndex(int x, int y) => y * 8 + x;
/// <summary>
/// Checks in O(1) time whether the item shape mask can be placed at (targetX, targetY).
/// </summary>
public bool CanPlace(ulong itemMask, int targetX, int targetY, int itemWidth, int itemHeight)
{
// 1. Check grid boundaries
if (targetX < 0 || targetY < 0 || targetX + itemWidth > 8 || targetY + itemHeight > 8)
return false;
// 2. Shift mask to target position
int shift = ToBitIndex(targetX, targetY);
ulong shiftedItemMask = itemMask << shift;
// 3. Check overlap (result must be 0 for unoccupied slots)
return (_occupiedMask & shiftedItemMask) == 0UL;
}
/// <summary>
/// Places the item on the grid and updates the occupancy mask.
/// </summary>
public void Place(ulong itemMask, int targetX, int targetY)
{
int shift = ToBitIndex(targetX, targetY);
_occupiedMask |= (itemMask << shift);
}
/// <summary>
/// Removes the item from the grid.
/// </summary>
public void Remove(ulong itemMask, int targetX, int targetY)
{
int shift = ToBitIndex(targetX, targetY);
_occupiedMask &= ~(itemMask << shift);
}
}
2. 아이템 비트마스크 정의 예시2. Item Bitmask Definition Examples
public static class ItemShapePresets
{
// 2x2 정사각형 아이템
// Row 0: 1 1 0 0 0 0 0 0 (0b00000011)
// Row 1: 1 1 0 0 0 0 0 0 (0b00000011 << 8)
public const ulong Shape2x2 = 0x0303UL;
// 1x3 세로 긴 막대 아이템
// Row 0: 1, Row 1: 1, Row 2: 1
public const ulong Shape1x3 = 0x010101UL;
// L자형 아이템 (2x3)
public const ulong ShapeL = 0x010103UL;
}
public static class ItemShapePresets
{
// 2x2 square item
// Row 0: 1 1 0 0 0 0 0 0 (0b00000011)
// Row 1: 1 1 0 0 0 0 0 0 (0b00000011 << 8)
public const ulong Shape2x2 = 0x0303UL;
// 1x3 vertical bar item
// Row 0: 1, Row 1: 1, Row 2: 1
public const ulong Shape1x3 = 0x010101UL;
// L-shaped item (2x3)
public const ulong ShapeL = 0x010103UL;
}
3. 실무 적용 및 주의사항3. Practical Considerations
- 행 경계 래핑(Row Wrapping) 주의: 비트 시프트만 수행할 경우 오른쪽 끝 슬롯을 넘어선 비트가 다음 행의 첫 번째 비트로 넘어갈 수 있으므로, 반드시
targetX + itemWidth <= 8경계 검사를 먼저 수행해야 합니다. - 64슬롯 초과 그리드 확장: 인벤토리 크기가 8×8(64칸)을 초과하는 경우에는
ulong[]배열이나UInt128구조체를 활용하여 동일한 비트 연산 원리를 확장할 수 있습니다. - 아이템 회전 프리셋 분리: 90도 회전 기능을 지원할 때는 런타임에 비트를 재계산하기보다, 회전 각도별 프리셋 마스크와 가로·세로 크기를 미리 정의해 두고 참조를 교체하는 방식이 효율적입니다.
- Prevent Row Wrapping: Bit-shifting alone can cause bits exceeding the right edge of a row to wrap into the first column of the next row, so always validate
targetX + itemWidth <= 8before shifting. - Scaling Beyond 64 Slots: When the inventory size exceeds 8×8 (64 slots), you can apply the same bitwise logic using a
ulong[]array or theUInt128struct. - Predefine Rotated Masks: To support 90-degree item rotation, predefine rotated bitmask presets and dimensions rather than recalculating bit positions at runtime.
비트마스크 기반 그리드 검사는 반복문 오버헤드와 추가 메모리 할당 없이 즉각적인 배치 판정을 수행하므로, 드래그 앤 드롭 인벤토리나 타일 기반 건설 시스템에서 유용하게 활용할 수 있습니다.
Bitmask-based grid validation evaluates placement without loop overhead or heap allocations, making it well suited for drag-and-drop inventories and tile placement systems.