Skip to content
CVL COREUnity SDK : Zero-Allocation Client

Public Delegation Broker & Telemetry Controller (Unity SDK)

[SPECIFICATION] Presentation Bridge & Telemetry Controller Invariant

The CVL CORE Presentation Bridge (CVLEngineAPI) & Telemetry Controller govern the client-side integration boundary, thread-decoupled socket transport, and deterministic 30Hz local kinematics sampling within the Unity runtime. Engineered to sustain 0 B/frame of managed heap allocation across a 500-entity unculled hotspot baseline, the SDK encapsulates background TCP stream marshaling, transient uint16 NetID resolution, and fixed-step coordinate quantization behind strongly typed C# lifecycle delegates.


[SEC 01.0] Executive Architecture & Subsystem Topology

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

To ensure the core client runtime remains independent of project-specific presentation logic, UI overlays, or camera rigs, the Unity package enforces strict physical and logical segregation alongside deterministic script execution ordering.

[ISOLATION] Two-Folder Physical Segregation & The Delete Test Rule
Section titled “[ISOLATION] Two-Folder Physical Segregation & The Delete Test Rule”

The Unity integration is partitioned into two physically isolated root directories:

  1. Core SDK Partition (Assets/CVL_CORE_SDK/): Encapsulated strictly inside the CVLCore.SDK namespace. Houses the public delegation broker (CVLEngineAPI.cs), background network transport (CVLNetworkManager.cs), wire contract headers (ProtocolConstants.cs), local kinematics controller (CVLPlayerController.cs), snapshot interpolation identity (CVLNetworkIdentity.cs), screen-space UI pooling (CVLScreenSpaceUIManager.cs), metabolic profiler (CVLClientProfilerReport.cs), and Editor validation tooling (CVLSetupWizard.cs, CVLPrefabValidator.cs).
  2. Demo Environment Partition (Assets/CVL_Demo_Environment/): Houses optional reference presentation scripts (DemoEnvironmentBridge.cs, CVLDemoHUD.cs, EntityNameplate.cs, and SpectatorCamera.cs).
  3. The Delete Test Invariant: Deleting the Assets/CVL_Demo_Environment/ directory in its entirety must leave Assets/CVL_CORE_SDK/ compiling and functioning with zero missing references or compilation errors.
[ORDERING] Deterministic Script Execution Order Pipeline
Section titled “[ORDERING] Deterministic Script Execution Order Pipeline”

To eliminate single-frame transform lag between local physics stepping, network ring-buffer ingestion, camera tracking, and UI projection, the SDK enforces explicit [DefaultExecutionOrder] attributes across the Unity player loop:

Execution Order Subsystem Class Operational Responsibility in Frame Lifecycle
-100 CVLPlayerController Samples local input, steps 30Hz fixed-dt character kinematics, and interpolates the child VisualPivot.
0 CVLNetworkManager / CVLNetworkIdentity Drains the 65,536-slot spatial ring buffer, processes time-sliced spawns, and steps 133ms snapshot interpolation.
10 CVLScreenSpaceUIManager Manages the centralized Screen Space - Overlay canvas and pre-warmed sub-canvas nameplate pools.
100 SpectatorCamera Tracks the local player’s smoothed VisualPivot or executes decoupled free-fly camera translation in LateUpdate().
200 EntityNameplate Projects 3D world anchors to 2D screen coordinates with inverse-distance perspective scaling.
1000 CVLClientProfilerReport Brackets the end-of-frame metabolic recording window and audits 0 B/frame managed GC allocations.
[BROKER] Public Event Delegation Broker (CVLEngineAPI)
Section titled “[BROKER] Public Event Delegation Broker (CVLEngineAPI)”

Gameplay scripts never query socket buffers or internal identity dictionaries directly. CVLEngineAPI acts as a static delegation broker that exposes strongly typed lifecycle events (OnEntitySpawned, OnEntityDespawned, OnNetworkStateChanged, OnVitalsUpdated, OnDamageFlashed, OnZoneEventTriggered, OnDynamicGeometryUpdated, OnPingUpdated, OnGameEventReceived).

  • Permanent 16-Byte EID Encapsulation: All public SDK delegates expose strictly the permanent string EID handle (e.g., "P_ALICE"). Ephemeral 16-bit NetID integers (ushort) are resolved internally via O(1) array lookup tables (fastIdentityMap and netIdToEidLookup) prior to event invocation, ensuring server-side NetID recycling never corrupts client targeting or UI references.
  • Domain Reload Hygiene: Decorated with [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)], CVLEngineAPI.ResetState() automatically clears all static delegates and resets latency/input properties prior to scene load, supporting instant Unity Editor Enter-Play-Mode workflows with Domain Reload disabled.

[SEC 02.0] Concurrency & State Ownership / Lifecycle

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

The Unity Main Thread is strictly prohibited from executing operating system socket syscalls or blocking NetworkStream.Write() operations. Network I/O is isolated inside two dedicated background threads (ReceiveLoop and EgressLoop) managed by CVLNetworkManager.

Architecture: Thread-Decoupled Unity Client Transport & 30Hz Telemetry Pipeline
+-----------------------------------------------------------------------------------+
| BACKGROUND SOCKET THREADS (CVLNetworkManager) |
| |
| [ReceiveLoop Thread] |
| |-- Non-Blocking NetworkStream.Read() ---> Pre-Allocated Stream Buffer |
| |-- MemoryMarshal.Cast / Read over ReadOnlySpan<byte> (Zero Allocation) |
| |-- (OP_BROADCAST) ---> Skip Local Self-NetID ---> [65,536-Slot Spatial Ring] |
| +-- (Discrete Opcodes / OP_GAME_EVENT) ----------> [mainThreadNetQueue] |
| (ArrayPool<byte>.Shared) |
| [EgressLoop Thread] |
| |-- Waits on AutoResetEvent (10ms) ---> Drains [egressQueue] |
| |-- Returns Rented Buffers to ArrayPool<byte>.Shared.Return() |
| +-- Autonomous 1.0Hz OP_PING (5B) Heartbeat (Disconnects if >= 5 Unreturned) |
+-----------------------------------------|-------------------------------^---------+
| Lock-Free Ring / Queue |
v |
+-------------------------------------------------------------------------+---------+
| UNITY MAIN THREAD (0 B/Frame Hot Path) |
| |
| [-100: CVLPlayerController.Update()] |
| |-- Gate: hasReceivedInitialServerPos == true |
| |-- Clamp telemetryAccumulator <= tickInterval * 3.0f (Anti-Burst) |
| |-- Step 30Hz Fixed-Tick Physics ---> Quantize (*30.0f Pos / *10.0f Aim) ======+
| +-- Smooth Child VisualPivot (Render Framerate + Rollback Offset Decay) |
| |
| [0: CVLNetworkManager.Update()] |
| |-- Drain Spatial Ring Buffer ---> CVLNetworkIdentity.SetNetworkTransform() |
| |-- Time-Sliced Hydration Gate (Max 4 Spawns / 2.5ms Budget per Frame) |
| +-- Resolve ushort NetID -> 16B String EID ---> Invoke CVLEngineAPI Delegates |
+-----------------------------------------------------------------------------------+
[EGRESS] Lazy-Connect Socket Initialization & Background Egress
Section titled “[EGRESS] Lazy-Connect Socket Initialization & Background Egress”

CVLNetworkManager enforces socket-free Awake() and Start() lifecycle methods, deferring TCP descriptor creation until IgniteBootSequence() is explicitly invoked. Once active:

  • Event-Driven Egress Loop (EgressLoop): Waits on an AutoResetEvent (egressSignal.WaitOne(10)), drains outbound byte arrays from egressQueue (ConcurrentQueue<byte[]>), writes exact wire byte lengths (16B for OP_TELEMETRY, 5B for OP_PING, 4B for OP_CLIENT_ACTION), and immediately returns leased buffers to ArrayPool<byte>.Shared.Return().
  • Autonomous 1.0Hz Transport Heartbeat (OP_PING): The background egress thread autonomously dispatches a 5-byte OP_PING envelope every 1,000 ms using a monotonic Stopwatch timestamp. Upon receiving the echoed frame in ReceiveLoop, the socket thread computes wire Round-Trip Time (rttSampleMs) immediately upon read and queues a PingEcho command to smooth CurrentPingMs and CurrentJitterMs via an exponential moving average (0.125f weight). If 5 consecutive pings go unreturned (Interlocked.Increment(ref unreturnedPings) >= 5), the transport triggers an automatic disconnect.
[INGRESS] Zero-Allocation Binary Ingress & The 65,536-Slot Spatial Ring
Section titled “[INGRESS] Zero-Allocation Binary Ingress & The 65,536-Slot Spatial Ring”

Inbound TCP bytes are read into a pre-allocated stream buffer and unpacked without BinaryReader or heap object instantiations:

  • High-Velocity Spatial Fast Path (spatialRingBuffer): When ReceiveLoop encounters OP_BROADCAST, it casts the payload slice via MemoryMarshal and writes unpacked transforms directly into a pre-allocated 65,536-slot lock-free Single-Producer Single-Consumer (SPSC) circular array (KinematicState[65536]).
  • Local Proxy Self-NetID Ingestion Filter: Because the server pre-serializes a single master broadcast buffer per 15Hz tick, the stream includes the client’s own NetID. ReceiveLoop compares each stride against its volatile localNetId and executes an inline continue strictly after advancing the binary read pointer, preventing historical server echoes from rubberbanding the local player while maintaining byte-stream alignment.
  • Pooled Discrete Command Queue (mainThreadNetQueue): Variable-length or discrete packets (OP_BUNDLE, OP_VITALS, OP_GAME_EVENT) rent temporary buffers via ArrayPool<byte>.Shared.Rent() on the socket thread and are guaranteed to be returned to the pool inside a finally block on the Unity Main Thread during ExecuteNetCommand().
  • Managed Zero-Allocation EID Parsing (ParseEID): When extracting 16-byte UTF-8 identity strings from OP_BUNDLE or OP_SET_POS strides, CVLNetworkManager strips trailing null/ASCII whitespace over ReadOnlySpan<byte> and executes a custom SpanEqualsAscii() short-circuit check against netIdToEidLookup. If the cached string already matches the incoming byte span, string allocation (Encoding.UTF8.GetString) is bypassed entirely.

[SEC 03.0] 30Hz Fixed-Step Telemetry Controller & Input Suspension

Section titled “[SEC 03.0] 30Hz Fixed-Step Telemetry Controller & Input Suspension”

To guarantee mathematical parity with the server’s 30Hz (33.3 ms) kinematic validation loop regardless of whether the client monitor is rendering at 30 FPS, 144 FPS, or 240 FPS, CVLPlayerController decouples physical movement stepping from render-frame presentation.

[ACCUMULATOR] Fixed-Step Accumulator & Render-Rate Visual Pivot Smoothing
Section titled “[ACCUMULATOR] Fixed-Step Accumulator & Render-Rate Visual Pivot Smoothing”

Rather than calling CharacterController.Move() with variable Time.deltaTime—which produces non-deterministic floating-point drift and triggers server speedhack strikes during frame hitches—CVLPlayerController.DispatchLocalTelemetryTick() enforces a fixed-step accumulator:

  1. Anti-Flood Accumulator Clamping: At the start of each frame, telemetryAccumulator is incremented by Time.deltaTime and strictly clamped to tickInterval * 3.0f (0.10 seconds max catch-up window). This prevents a temporary client OS freeze or alt-tab stall from unleashing a sudden burst of catch-up movement packets that would trip the server’s reactor flood breaker.
  2. Deterministic 30Hz Physics Stepping: While telemetryAccumulator >= tickInterval (0.0333333f), the controller records prevTickWorldPos, steps CharacterController.Move(moveDirection * tickInterval), derives currentStepSpeed from horizontal displacement, validates all floats against NaN/Infinity, and dispatches a quantized 16-byte OP_TELEMETRY frame (* 30.0f for position, * 10.0f for yaw/pitch/speed).
  3. Sub-Tick Visual Interpolation (VisualPivot): Between 30Hz physics ticks, the child visual mesh hierarchy (VisualPivot) is smoothly interpolated at native monitor refresh rate via Vector3.Lerp(prevTickWorldPos, currTickWorldPos, Mathf.Clamp01(telemetryAccumulator / tickInterval)) + rollbackVisualOffset.
  4. Decoupled Camera Pitch Extraction: Vertical aim pitch bypasses the rigid upright root capsule and reads directly from Camera.main.transform.eulerAngles.x, normalizing and clamping the angle strictly within [-90.0f, 90.0f] prior to 10.0f fixed-point quantization.
[SUSPENSION] Input Suspension (IsInputSuspended) & Spectator Camera Rig
Section titled “[SUSPENSION] Input Suspension (IsInputSuspended) & Spectator Camera Rig”

The server enforces a strict 10.0-second FLATLINE_TIMEOUT transport silence threshold refreshed by OP_TELEMETRY and OP_PING. If a client script disables CVLPlayerController when opening an inventory screen, focusing a chat input field, boarding a vehicle (ParentNetID > 0), or toggling a free-fly camera, the telemetry stream stops and the server evicts the player after 10.0 seconds (REASON_TIMEOUT = 0x01).

To prevent flatline evictions during non-walking states, the SDK provides CVLEngineAPI.IsInputSuspended:

  • Preserving the 30Hz Heartbeat: Setting CVLEngineAPI.IsInputSuspended = true zeroes local WASD movement vectors and mouse look translation inside CVLPlayerController while keeping the 30Hz fixed-step OP_TELEMETRY dispatch loop running uninterrupted in the background.
  • Decoupled Spectator Camera (SpectatorCamera.cs): Executing at [DefaultExecutionOrder(100)], SpectatorCamera hydrates world boundary limits ([mapMinX, mapMaxX], [mapMinZ, mapMaxZ], [minAltitude, maxAltitude]) directly from CVLEngineConfig and binds its follow anchor to CVLPlayerController.VisualPivot. Pressing the C key toggles isFlyingMode, automatically setting CVLEngineAPI.IsInputSuspended = isFlyingMode so the operator can fly the detached camera across the map while their grounded avatar maintains its 30Hz keepalive stream.

[SEC 04.0] Architectural Invariants & Guardrails

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

Client integrations must adhere to strict pooling, subscription, and prefab grounding invariants to preserve 0 B/frame garbage collection stability and deterministic server synchronization.

[GUARDRAIL] Prefab Grounding & Decoupled Physics Terrain Alignment
Section titled “[GUARDRAIL] Prefab Grounding & Decoupled Physics Terrain Alignment”

To ensure visual feet anchors match the server’s authoritative Z-elevation baseline without PhysX depenetration jitter, player and proxy prefabs must enforce canonical hierarchy dimensions:

  • Root & CharacterController Geometry: The root prefab transform pivot must sit flush at ground level (Y = 0.0m), carrying a root CharacterController configured with Center = (0.0, 1.0, 0.0), Height = 2.0m, and Radius = 0.5m.
  • Skin-Width Visual Compensation: Standard capsule visual meshes attached under VisualPivot apply a local position offset of (0.0, 1.08, 0.0) to compensate for Unity’s 0.08m CharacterController skin width, while custom foot-pivoted FBX characters use (0.0, 0.0, 0.0).
  • Inverted Z-Axis Terrain Alignment: Within a standard 512m x 512m zone, the invisible physics BoxCollider terrain floor is centered at (256.0, -0.5, 744.0) with scale (512.0, 1.0, 512.0), paired with an uncollided visual Unity Plane scaled to (51.2, 1.0, 51.2) at (256.0, 0.0, 744.0).
[GUARDRAIL] Mandatory Delegate Subscription Hygiene & Pool Preservation
Section titled “[GUARDRAIL] Mandatory Delegate Subscription Hygiene & Pool Preservation”

Because CVLEngineAPI events are static, any MonoBehaviour subscribing in OnEnable() must explicitly unsubscribe in OnDisable(). Failing to unsubscribe retains references to destroyed scene objects and causes MissingReferenceException faults across scene transitions. Furthermore, when OnEntityDespawned fires upon receipt of OP_REMOVE, CVLNetworkManager automatically returns the proxy GameObject to its pre-warmed PrefabCatalog Stack<GameObject> pool; client scripts must never invoke GameObject.Destroy() on network proxies.

[CHECKLIST // INVARIANTS] UNITY SDK DELEGATION & TELEMETRY GUARDRAILS

1. Use IsInputSuspended (Never Disable CVLPlayerController): Always lock player movement via CVLEngineAPI.IsInputSuspended = true during UI focus or free-fly camera mode so the 30Hz OP_TELEMETRY heartbeat never flatlines.
2. Advance Read Pointer Before Self-NetID Skip: In binary stream readers, always advance the byte offset pointer before executing if (netId == localNetId) continue;.
3. Zero GameObject.Destroy() on Proxies: Allow CVLNetworkManager to return despawned proxies to the pre-warmed PrefabCatalog pool stack.
4. Strict OnEnable / OnDisable Pairing: Always pair every CVLEngineAPI.On* += ... registration with a matching -= de-registration in OnDisable().


Section titled “[SEC 05.0] Client Gameplay Coordinator & Related Specifications”

The following C# integration pattern demonstrates subscribing to the CVLEngineAPI delegation broker, binding a camera rig to the smoothed VisualPivot on local player spawn, toggling IsInputSuspended during UI overlays, and reading smoothed 1.0Hz ping/jitter telemetry:

[IMPLEMENTATION] Complete Client Broker & Telemetry Integration (CVLEngineAPI.cs)
Section titled “[IMPLEMENTATION] Complete Client Broker & Telemetry Integration (CVLEngineAPI.cs)”
EXAMPLE INTEGRATION : Assets/CVL_CORE_SDK/API/ClientGameplayCoordinator.cs
using System;
using UnityEngine;
using CVLCore.SDK;
public class ClientGameplayCoordinator : MonoBehaviour
{
[SerializeField] private Transform cameraFollowRig;
private GameObject _localPlayerObject;
private void OnEnable()
{
CVLEngineAPI.OnEntitySpawned += HandleEntitySpawned;
CVLEngineAPI.OnEntityDespawned += HandleEntityDespawned;
CVLEngineAPI.OnVitalsUpdated += HandleVitalsUpdated;
CVLEngineAPI.OnPingUpdated += HandlePingUpdated;
CVLEngineAPI.OnGameEventReceived += HandleGameEventReceived;
}
private void OnDisable()
{
CVLEngineAPI.OnEntitySpawned -= HandleEntitySpawned;
CVLEngineAPI.OnEntityDespawned -= HandleEntityDespawned;
CVLEngineAPI.OnVitalsUpdated -= HandleVitalsUpdated;
CVLEngineAPI.OnPingUpdated -= HandlePingUpdated;
CVLEngineAPI.OnGameEventReceived -= HandleGameEventReceived;
}
public void ToggleInventoryOverlay(bool isOpen)
{
// Locks physical WASD/Mouse translation while maintaining the 30Hz OP_TELEMETRY stream
CVLEngineAPI.IsInputSuspended = isOpen;
}
private void HandleEntitySpawned(string eid, GameObject proxy, bool isLocal)
{
if (isLocal)
{
_localPlayerObject = proxy;
// Bind camera rigs strictly to VisualPivot (interpolated at render framerate)
if (proxy.TryGetComponent<CVLPlayerController>(out var controller) && cameraFollowRig != null)
{
cameraFollowRig.SetParent(controller.VisualPivot, worldPositionStays: false);
}
Debug.Log($"Local Operator Hydrated: {eid}");
}
}
private void HandleEntityDespawned(string eid, byte reasonCode)
{
// Do NOT call Destroy(proxy); SDK automatically returns instance to PrefabCatalog pool
if (reasonCode == ProtocolConstants.REASON_TIMEOUT)
{
Debug.LogWarning($"Peer {eid} evicted due to transport flatline (0x01).");
}
}
private void HandleVitalsUpdated(VitalsUpdatePayload vitals)
{
// VitalsUpdatePayload provides pre-resolved permanent EID and TargetEID strings
Debug.Log($"[{vitals.EID}] HP: {vitals.Health} | Shield: {vitals.Shield} | Target: {vitals.TargetEID}");
}
private void HandlePingUpdated(float rttMs, float jitterMs)
{
// Driven by autonomous 1.0Hz background OP_PING loop (0.125f EMA smoothed)
}
private void HandleGameEventReceived(
byte serviceId,
byte subOpcode,
ushort requestId,
byte statusCode,
ReadOnlySpan<byte> payload)
{
// Zero-allocation ReadOnlySpan<byte> slice returned to ArrayPool<byte>.Shared automatically
}
}
Section titled “[RELATED SPECS] Cross-Category Subsystem Links”