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).
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.
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:
tx, ty) resolve to integer grid coordinates via home_cx = int(tx) >> cell_shift and home_cy = int(ty) >> cell_shift.cell_idx = (home_cy << row_shift) | home_cx.O(1) time at frame boundaries, completely bypassing garbage collection churn.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):
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.ObstacleAABB bounding volumes) is hydrated into pre-allocated spatial buckets at startup or runtime via three configurable modes (OBSTACLE_MODE):
LOCAL_PROCEDURAL: Compiles deterministic binary map layouts (world_geometry.cvlmap) into a pre-serialized egress cache at boot.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.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.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.
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.
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)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:
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).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.[0.0, WORLD_WIDTH] and [0.0, WORLD_HEIGHT]).OP_SET_POS re-anchoring frame.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.
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.
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:
// 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 loopVector3 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 Dispatchif (closestContact < 1.0f){ Vector3 impactPoint = p0 + (displacement * closestContact); DispatchAuthoritativeImpact(impactPoint); // OP_FLASH_DAMAGE (0x07) + OP_REMOVE (0x05)}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.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:
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."); } }}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.
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.
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.
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):
<= 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.>= 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.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:
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.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.
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.
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.
cvlcore_engine_config.json)All spatial dimensions and role-aware kinematic limits are validated at startup with zero implicit fallback defaults:
{ "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}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):
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."); }}OP_MAP_GEOMETRY, OP_SET_POS, and OP_FLASH_DAMAGE alongside Y/Z coordinate swizzling rules, see Authoritative Binary Wire Protocol & Master Opcodes.ZONE_SIZE, COLLISION_CELL_SIZE, and static obstacle baking directly inside Unity, see Setup Wizard & Server Config Hydration.