Skip to content
CVL COREEngine

Broadphase Spatial Hashing & 3D Continuous Collision Detection (CCD)

[SPECIFICATION] Broadphase Spatial & 3D CCD Invariant

The Broadphase Spatial Computing Engine governs all authoritative 3D coordinate validation, static and dynamic intersection sweeps, volume trigger overlaps, and high-velocity ballistic raycasting within the CVL CORE Spatial Micro-Kernel. Engineered to resolve a 500-entity unculled hotspot baseline ("Combat Storm" cluster) and high-speed trajectories inside a single-threaded 30Hz (33.3 ms) budget—while scaling seamlessly to 10,000+ proximity-culled entities—the subsystem replaces tree-based spatial structures and floating-point division with power-of-two bit-shifted 1D array indexing, localized 9-cell broadphase neighborhoods, and inline Liang-Barsky 3D Continuous Collision Detection (CCD).


[SEC 01.0] Executive Architecture & Subsystem Topology

Section titled “[SEC 01.0] Executive Architecture & Subsystem Topology”

To achieve deterministic O(1) spatial query complexity regardless of world dimensions or total obstacle count, the Broadphase Spatial Computing Engine enforces power-of-two spatial metrics and zero-allocation geometric structures across the simulation hot path.

[INDEXING] Power-of-Two Bit-Shifted Spatial Indexing
Section titled “[INDEXING] Power-of-Two Bit-Shifted Spatial Indexing”

World zone dimensions (ZONE_SIZE), grid layouts (GRID_COLS, GRID_ROWS), and collision cell dimensions (COLLISION_CELL_SIZE) are strictly locked to powers of two. At engine bootstrap, the spatial subsystem pre-computes immutable bitwise shift exponents using (dimension - 1).bit_length(), replacing runtime floating-point multiplication and division instructions with single-cycle CPU bitwise shifts:

  • Coordinate-to-Cell Conversion: An entity’s 2D horizontal target coordinates (tx, ty) resolve to integer grid coordinates via home_cx = int(tx) >> cell_shift and home_cy = int(ty) >> cell_shift.
  • 1D Contiguous Array Mapping: The 2D cell coordinates flatten directly into a 1D index within the pre-allocated spatial matrix via cell_idx = (home_cy << row_shift) | home_cx.
  • Zero-Allocation Dynamic Grid Clearing: Rather than re-allocating or sweeping the entire world grid each frame, the engine tracks populated dynamic cell indices during the tick and clears only occupied buckets in O(1) time at frame boundaries, completely bypassing garbage collection churn.
[ISOLATION] 9-Cell Broadphase Neighborhood Isolation
Section titled “[ISOLATION] 9-Cell Broadphase Neighborhood Isolation”

Global entity-to-entity loops and full-map obstacle scans are prohibited. Whether evaluating grounded/aerial proxy movement, proximity volume triggers, or ballistic trajectories, intersection mathematics are strictly confined to the entity’s active home cell and its eight immediate surrounding neighbors (3x3 grid, 9 cells total):

  • Constant-Time Scaling: By bounding collision sweeps to range(home_cy - 1, home_cy + 2) and range(home_cx - 1, home_cx + 2), a simulation arena containing 10,000 static obstacles executes the exact same per-entity collision instruction count as an empty arena.
  • Tri-Mode Level Geometry Hydration: Static world geometry (ObstacleAABB bounding volumes) is hydrated into pre-allocated spatial buckets at startup or runtime via three configurable modes (OBSTACLE_MODE):
    1. LOCAL_PROCEDURAL: Compiles deterministic binary map layouts (world_geometry.cvlmap) into a pre-serialized egress cache at boot.
    2. DATABASE: Verifies PostgreSQL connectivity at startup, hydrating persistent entities and baking static obstacle bounding boxes directly into spatial cell buckets prior to opening the network intake gate.
    3. LIVE_STREAM: Initializes a mutable in-memory spatial whiteboard that ingests live OP_MAP_GEOMETRY binary mutation streams from authorized administrative tools, dynamically rebuilding spatial buckets and re-baking the cached Stage 2 wire payload in real time.
[PRIMITIVES] Slotted Headless Geometry Primitives
Section titled “[PRIMITIVES] Slotted Headless Geometry Primitives”

The server core strips all external GUI or rendering library dependencies (such as graphical Rect objects) from the simulation runtime. All static obstacles and spatial bounds utilize internal slotted data structures (SpatialRect and StaticObstacle), guaranteeing a zero-dictionary heap footprint and hardware-aligned attribute lookups during 30Hz intersection sweeps.


[SEC 02.0] Concurrency & State Ownership / Lifecycle

Section titled “[SEC 02.0] Concurrency & State Ownership / Lifecycle”

All spatial cell indexing, kinematic anti-cheat validation, slide-vector resolution, and ballistic raycasting execute synchronously on the Main Thread during Phase 1 of the Authoritative Simulation Orchestrator loop. Client engines (Unity/Unreal) hold zero authority over collision resolution or hit detection, operating strictly as visual presentation bridges.

Topology: O(1) 9-Cell Neighborhood Isolation & 3D Slab Raycasting
A) 9-CELL BROADPHASE ISOLATION (3x3 Neighborhood -> 1D Bit-Shifted Matrix)
World Grid (Power-of-Two) 1D Contiguous Spatial Matrix
+-------+-------+-------+-------+-------+ +----------------------------------+
| . | . | . | . | . | | ... (Unvisited Cells Ignored) |
+-------+=======+=======+=======+-------+ +----------------------------------+
| . ‖ [NW] | [N] | [NE] ‖ . | ===> | Row (Y - 1) Bit-Shifted Buckets |
+-------+-------+-------+-------+-------+ +----------------------------------+
| . ‖ [W] | HOME | [E] ‖ . | ===> | Row (Y) Bit-Shifted Buckets |
+-------+-------+-------+-------+-------+ +----------------------------------+
| . ‖ [SW] | [S] | [SE] ‖ . | ===> | Row (Y + 1) Bit-Shifted Buckets |
+-------+=======+=======+=======+-------+ +----------------------------------+
| . | . | . | . | . | | ... (O(1) Constant-Time Lookup) |
+-------+-------+-------+-------+-------+
B) LIANG-BARSKY 3D CONTINUOUS COLLISION DETECTION (Anti-Tunneling Slab Test)
Slab Entry Slab Exit
| |
Origin (T0) | Exact Contact Point | Destination (T1)
o===============*-------------------------+----------------->o
| [ Clamped Impact ] | (Discrete step would
| Zero Tunneling | tunnel past volume)
[PIPELINE] The 5-Stage Bulk Kinematics Pipeline
Section titled “[PIPELINE] The 5-Stage Bulk Kinematics Pipeline”

During every 30Hz tick, after the orchestrator drains one de-jittered telemetry frame per active entity into the Contiguous State Substrate, the Broadphase Spatial Computing Engine executes a five-stage validation pass:

  • Stage 1 (Bitwise Cell Hashing & Modifier Reset): Computes the entity’s 2D grid coordinates and 1D spatial bucket index via single-cycle bitwise shifts. Transient per-tick environmental modifiers (such as climbable volume flags or velocity dampeners) are reset to baseline so actors exiting special volumes immediately revert to standard physics rules.
  • Stage 2 (Dynamic Cell Migration & Volume Trigger Overlaps): Updates dynamic spatial buckets only when an entity crosses a cell boundary. For interactive human operators (ROLE_OPERATOR_HUMAN = 4), the engine scans the 9-cell neighborhood for ROLE_VOLUME_TRIGGER (Role 11) volumes; detecting a spatial overlap within a 3.0m bounding radius dynamically unlocks vertical elevation movement and applies configured velocity scaling (enabling ladders, elevators, or hazard zones without false-positive anti-cheat strikes).
  • Stage 3 (Role-Aware Kinematics & 9-Cell Collision Sweep): Evaluates decoupled 2D horizontal displacement and 1D vertical elevation against role-specific ceilings (MAX_GROUNDED_SPEED with MAX_JUMP_HEIGHT = 5.0m for grounded proxies; MAX_FLYING_SPEED with MAX_FLIGHT_CEILING for ROLE_MOBILE_AERIAL = 7). Validated moves sweep the 9-cell neighborhood against static obstacles (COLLISION_MODE = "ENVIRONMENT_ONLY") or both static obstacles and dynamic peers (COLLISION_MODE = "FULL"), computing smooth axial slide responses upon contact.
  • Stage 4 (Branchless World Boundary Clamping): Clamps resolved horizontal coordinates branchlessly within the configured world dimensions ([0.0, WORLD_WIDTH] and [0.0, WORLD_HEIGHT]).
  • Stage 5 (Macro-Zone Boundary Hysteresis): Evaluates macro-zone coordinates via pre-computed bitwise shift exponents. When an entity crosses a macro-zone boundary beyond the configured hysteresis margin (32.0m), the server updates the active zone index, increments the modulo-4 generation epoch, and dispatches an authoritative 32-byte OP_SET_POS re-anchoring frame.
[INVARIANT] Hierarchical Vehicle Bypass & Rollback Parity
Section titled “[INVARIANT] Hierarchical Vehicle Bypass & Rollback Parity”

Entities mounted to a parent vehicle (parent_net_id != 0 on ROLE_MOBILE_GROUNDED = 6 or ROLE_MOBILE_AERIAL = 7) explicitly bypass individual anti-cheat velocity checks and static obstacle sweeps during Stage 3, inheriting spatial authority and macro-zone generation epochs directly from the host vehicle’s 64-byte memory slot. Conversely, if an unmounted entity violates kinematic speed ceilings or attempts to clip through static geometry, the engine executes an Authoritative Rollback: both the 64-byte memory matrix slice and the cached entity coordinate attributes (x, y, z) are atomically restored to the last confirmed legal transform prior to dispatching an OP_SET_POS correction.


[SEC 03.0] 3D Continuous Collision Detection & Geometry Extrusion

Section titled “[SEC 03.0] 3D Continuous Collision Detection & Geometry Extrusion”

Standard discrete-step collision checks fail when high-velocity objects (such as ballistic projectiles or high-speed autonomous drones) travel distances greater than a target’s bounding thickness within a single 33.3 ms frame (“tunneling”). CVL CORE eliminates tunneling via inline 3D ray-box Continuous Collision Detection.

[ALGORITHM] Liang-Barsky 3D Ray-Box Slab Intersection (ROLE_PROJECTILE_BALLISTIC)
Section titled “[ALGORITHM] Liang-Barsky 3D Ray-Box Slab Intersection (ROLE_PROJECTILE_BALLISTIC)”

Server-spawned ballistic entities (ROLE_PROJECTILE_BALLISTIC = 9) iterate in a dedicated contiguous projectile list isolated from standard character physics. On every 30Hz tick (proj_dt = 0.03333333333333333), the engine advances velocity under gravity (vz = vz - (gravity * proj_dt)) and evaluates a continuous 3D ray segment from origin (p0x, p0y, p0z) to destination (p1x, p1y, p1z) across the 9-cell broadphase neighborhood:

Algorithm: Conceptual 9-Cell Liang-Barsky 3D Ray-Box CCD Sweep
// 1. Step 30Hz Ballistic Trajectory (dt = 0.03333333333333333s)
vz -= gravity * projDt;
Vector3 displacement = new Vector3(vx * projDt, vy * projDt, vz * projDt);
Vector3 p1 = p0 + displacement;
// Pre-compute reciprocal ray scalars once outside the 9-cell loop
Vector3 invDir = new Vector3(1.0f / displacement.x, 1.0f / displacement.y, 1.0f / displacement.z);
float closestContact = 1.0f;
// 2. Sweep 9-Cell Broadphase Neighborhood (3x3 Grid around Home Cell)
for (int cy = homeCy - 1; cy <= homeCy + 1; cy++)
{
for (int cx = homeCx - 1; cx <= homeCx + 1; cx++)
{
int bucketIdx = (cy << rowShift) | cx;
// A) Evaluate Static Obstacle AABB Slabs in Bucket
// B) Evaluate Dynamic Entity Vulnerability Volumes (1.0m x 1.0m x 2.0m)
// (Exclude firing source NetID, Role 9 projectiles, and Role 2 observers)
if (TryIntersectRayAABB(p0, invDir, targetBounds, out float tEntry) && tEntry < closestContact)
{
closestContact = Mathf.Max(0.0f, tEntry);
}
}
}
// 3. Exact Surface Clamping & Authoritative Impact Dispatch
if (closestContact < 1.0f)
{
Vector3 impactPoint = p0 + (displacement * closestContact);
DispatchAuthoritativeImpact(impactPoint); // OP_FLASH_DAMAGE (0x07) + OP_REMOVE (0x05)
}
  • Exact Surface Contact & Immediate Reclamation: When an intersection is confirmed against either a static wall or a dynamic entity vulnerability volume (1.0m x 1.0m x 2.0m), the projectile clamps to the exact normalized impact fraction closest_t. If a dynamic target is struck, the server applies the signed health delta, marks vitals dirty (is_vitals_dirty = True), broadcasts a 4-byte OP_FLASH_DAMAGE stride, and immediately evicts the projectile via OP_REMOVE carrying REASON_PROJECTILE_EXPIRE (0x06). Projectiles exceeding PROJECTILE_MAX_TTL without contact self-evict automatically.
[EXTRUSION] Client Stage 2 Geometry Ingestion & 3D Extrusion (OP_MAP_GEOMETRY)
Section titled “[EXTRUSION] Client Stage 2 Geometry Ingestion & 3D Extrusion (OP_MAP_GEOMETRY)”

During Stage 2 connection admission (or live administrative map streaming), the server transmits static obstacle arrays via OP_MAP_GEOMETRY (5-byte header followed by 20-byte ObstacleAABB strides containing sX, sY, width, length, and typeId). The CVL CORE Presentation Bridge transforms these 2D server footprints into 3D extruded collision volumes in client coordinate space before returning the CHR\n acknowledgment:

Assets/CVL_CORE_SDK/Network/MapGeometryExtruder.cs
using UnityEngine;
using CVLCore.SDK;
namespace CVLCore.Client
{
public sealed class DynamicGeometrySubscriber : MonoBehaviour
{
private void OnEnable()
{
// Subscribes to Stage 2 / LIVE_STREAM OP_MAP_GEOMETRY hydration completion.
// Raw 20-byte ObstacleAABB wire strides and 3D coordinate swizzling are
// processed internally by CVLNetworkManager prior to firing this event.
CVLEngineAPI.OnDynamicGeometryUpdated += HandleGeometryHydrated;
}
private void OnDisable()
{
CVLEngineAPI.OnDynamicGeometryUpdated -= HandleGeometryHydrated;
}
private void HandleGeometryHydrated(int activeObstacleCount)
{
Debug.Log($"[CVL CLIENT] Extruded {activeObstacleCount} static 3D AABB volumes.");
}
}
}

[SEC 04.0] Architectural Invariants & Guardrails

Section titled “[SEC 04.0] Architectural Invariants & Guardrails”

Deterministic spatial hashing and zero-jitter client collision presentation rely on strict mathematical and structural invariants across both the server configuration schema and client prefab definitions.

[GUARDRAIL] Monomorphic Floating-Point Type Stability
Section titled “[GUARDRAIL] Monomorphic Floating-Point Type Stability”

Within the 30Hz bulk kinematics and 3D CCD routines, all local variables, coordinate boundaries, and velocity scalars strictly enforce monomorphic floating-point stability (explicitly initializing as 0.0, 1.0, 0.03333333333333333 rather than integer literals). Preventing mixed-mode integer/float reassignments ensures runtime micro-op JIT optimizers never de-optimize hot-path spatial loops back to generic type-checking instructions.

[GUARDRAIL] Decoupled Horizontal and Vertical Validation
Section titled “[GUARDRAIL] Decoupled Horizontal and Vertical Validation”

Anti-cheat displacement math explicitly decouples 2D horizontal distance squared (DynamicMaxDistSq = (max_speed * speed_modifier * tolerance * dt)^2) from 1D vertical Z-axis displacement. Grounded entities (ROLE_OPERATOR_HUMAN = 4, ROLE_MOBILE_GROUNDED = 6) are evaluated against MAX_JUMP_HEIGHT (5.0m) on upward movement while downward gravitational falls (tz < z) bypass jump strikes; aerial entities (ROLE_MOBILE_AERIAL = 7) bypass jump checks entirely and clamp elevation against MAX_FLIGHT_CEILING.

[GUARDRAIL] Broadphase Cell Size Bounds & Culling Balance
Section titled “[GUARDRAIL] Broadphase Cell Size Bounds & Culling Balance”

The spatial partition dimension (COLLISION_CELL_SIZE) must be a power of two strictly bounded between 4.0m and 64.0m, and must never be smaller than the largest entity bounding radius (enforced by a fail-fast GUI lock in CVLSetupWizard):

  • Upper Bound (<= 64.0m — Preventing Culling Dilution): Configuring cell dimensions larger than 64.0m packs excessive entities and static obstacles into single buckets, degrading O(1) neighborhood lookups back into expensive brute-force proximity scans.
  • Lower Bound (>= 4.0m — Preventing Grid Migration Thrashing): Configuring cell dimensions smaller than 4.0m causes high-frequency boundary crossings, saturating the CPU with dynamic array un-binning and re-binning operations on every 30Hz tick.
[GUARDRAIL] Client PhysX Isolation & Pooled Projectile Presentation
Section titled “[GUARDRAIL] Client PhysX Isolation & Pooled Projectile Presentation”

Because the server holds sole authority over collision sweeps and 3D ray-box hit detection, client visual proxies and pooled ballistic projectiles (ROLE_PROJECTILE_BALLISTIC = 9) must remain completely decoupled from local physics solver competition:

  • Ghost Authority & PhysX Sync Isolation: Remote entity proxies and projectile prefabs must omit solid Collider, Rigidbody, and CharacterController components, and client code must gate Physics.SyncTransforms() strictly behind isLocalPlayer == true rollback checks. Running active physics components or global PhysX flushes on remote proxies stalls the Unity Main Thread and disrupts the 133ms snapshot interpolation timeline during multi-entity spawn bursts.
  • Pooled Projectile Trail Reset: Ballistic projectiles are leased and returned through pre-warmed PrefabCatalog object pools (OP_BUNDLE / OP_SET_POS to OP_REMOVE). Any attached TrailRenderer or ParticleSystem must enable Clear on Enable or invoke .Clear() inside OnEnable() so recycled projectiles do not draw visual streaks from their prior impact coordinate back to the new firing origin.
[CHECKLIST // INVARIANTS] SPATIAL PARTITIONING & CLIENT PHYSX GUARDRAILS

1. Power-of-Two Cell Bounds: COLLISION_CELL_SIZE must be a power of two strictly between 4.0m and 64.0m (and >= the largest entity bounding radius).
2. Remote Proxy PhysX Isolation: Zero active Rigidbody or solid Collider components on remote proxies; gate Physics.SyncTransforms() strictly behind isLocalPlayer == true.
3. Pooled Ballistic Projectiles (Role 9): Always invoke TrailRenderer.Clear() inside OnEnable() to prevent pool-recycling trail streaks.


[SEC 05.0] Spatial Configuration Schema & Client Presentation Bridge

Section titled “[SEC 05.0] Spatial Configuration Schema & Client Presentation Bridge”

Infrastructure operators configure spatial grid geometry and kinematic speed envelopes through cvlcore_engine_config.json, while client developers hook into spatial zone transitions, live geometry updates, and CCD impact flashes via CVLEngineAPI.

[CONFIG] Spatial & Kinematic Configuration Schema (cvlcore_engine_config.json)
Section titled “[CONFIG] Spatial & Kinematic Configuration Schema (cvlcore_engine_config.json)”

All spatial dimensions and role-aware kinematic limits are validated at startup with zero implicit fallback defaults:

config/cvlcore_engine_config.json
{
"ENABLE_SPATIAL_LOGIC": true,
"MAP_MODE": "CLUSTER_GRID",
"OBSTACLE_MODE": "LOCAL_PROCEDURAL",
"COLLISION_MODE": "FULL",
"USE_SPATIAL_CULLING": false,
"ZONE_SIZE": 512,
"GRID_COLS": 2,
"GRID_ROWS": 2,
"COLLISION_CELL_SIZE": 16,
"Z_AXIS_BIAS": 100.0,
"MAX_GROUNDED_SPEED": 8.0,
"MAX_FLYING_SPEED": 20.0,
"MAX_JUMP_HEIGHT": 5.0,
"MAX_FLIGHT_CEILING": 250.0,
"PROJECTILE_MAX_TTL": 5.0
}
[IMPLEMENTATION] Client Spatial Events & Pooled Projectile Presentation (CVLEngineAPI.cs)
Section titled “[IMPLEMENTATION] Client Spatial Events & Pooled Projectile Presentation (CVLEngineAPI.cs)”

The following C# integration example demonstrates resetting pooled projectile visual trails on spawn, reacting to authoritative 3D CCD impact flashes (OP_FLASH_DAMAGE), and listening for macro-zone boundary transitions (OP_ZONE_EVENT):

Assets/CVL_CORE_SDK/API/SpatialPresentationBridge.cs
using UnityEngine;
using CVLCore.SDK;
public class SpatialPresentationBridge : MonoBehaviour
{
private void OnEnable()
{
CVLEngineAPI.OnEntitySpawned += HandleEntitySpawned;
CVLEngineAPI.OnDamageFlashed += HandleDamageFlashed;
CVLEngineAPI.OnZoneEventTriggered += HandleZoneTransition;
CVLEngineAPI.OnDynamicGeometryUpdated += HandleDynamicGeometryUpdated;
}
private void OnDisable()
{
CVLEngineAPI.OnEntitySpawned -= HandleEntitySpawned;
CVLEngineAPI.OnDamageFlashed -= HandleDamageFlashed;
CVLEngineAPI.OnZoneEventTriggered -= HandleZoneTransition;
CVLEngineAPI.OnDynamicGeometryUpdated -= HandleDynamicGeometryUpdated;
}
private void HandleEntitySpawned(string eid, GameObject proxy, bool isLocal)
{
// Prevent pooled projectile trail streaking across coordinates on re-lease
if (proxy.TryGetComponent<TrailRenderer>(out var trail))
{
trail.Clear();
}
}
private void HandleDamageFlashed(string targetEid, short signedHealthDelta)
{
// Triggered immediately when server 9-cell 3D Liang-Barsky CCD confirms impact
Debug.Log($"Authoritative CCD Hit on {targetEid}: Delta {signedHealthDelta} HP");
}
private void HandleZoneTransition(string eid, int newZoneId)
{
// Dispatched when an entity crosses a power-of-two macro-zone boundary (+32.0m hysteresis)
Debug.Log($"Entity {eid} transitioned to Macro-Zone {newZoneId}");
}
private void HandleDynamicGeometryUpdated(int totalObstacleCount)
{
// Dispatched when Stage 2 or LIVE_STREAM OP_MAP_GEOMETRY rebuilds static AABBs
Debug.Log($"Spatial Obstacle Matrix Synchronized: {totalObstacleCount} active AABBs.");
}
}
Section titled “[RELATED SPECS] Cross-Category Subsystem Links”