Skip to main content

aetheris_client_wasm/
lib.rs

1//! Aetheris WASM client logic.
2//!
3//! This crate implements the browser-based client for the Aetheris Engine,
4//! using `WebWorkers` for multi-threaded execution and `WebGPU` for rendering.
5
6#![warn(clippy::all, clippy::pedantic)]
7// Required to declare `#[thread_local]` statics on nightly (wasm32 target).
8// This feature gate is only active when compiling for WASM — see the
9// `_TLS_ANCHOR` declaration below.
10#![cfg_attr(
11    all(target_arch = "wasm32", feature = "nightly"),
12    feature(thread_local)
13)]
14
15pub mod auth;
16pub mod shared_world;
17pub mod world_state;
18
19#[cfg(target_arch = "wasm32")]
20pub mod metrics;
21
22#[cfg(test)]
23#[cfg(target_arch = "wasm32")]
24pub mod smoke_test;
25
26/// Protobuf message types generated from `auth.proto` (prost only — no service stubs).
27/// Used by `auth.rs` so it doesn't need the `aetheris-protocol` `grpc` feature,
28/// which would pull in `tonic::transport` and hence `mio` (incompatible with wasm32).
29pub mod auth_proto {
30    #![allow(clippy::must_use_candidate, clippy::doc_markdown)]
31    tonic::include_proto!("aetheris.auth.v1");
32}
33
34#[cfg(target_arch = "wasm32")]
35pub mod transport;
36
37#[cfg(test)]
38pub mod transport_mock;
39
40#[cfg(target_arch = "wasm32")]
41pub mod render;
42
43#[cfg(any(target_arch = "wasm32", test))]
44pub mod render_primitives;
45
46#[cfg(any(target_arch = "wasm32", test))]
47pub mod assets;
48
49#[cfg(target_arch = "wasm32")]
50#[cfg_attr(feature = "nightly", thread_local)]
51static _TLS_ANCHOR: u8 = 0;
52
53use std::sync::atomic::AtomicUsize;
54#[cfg(target_arch = "wasm32")]
55use std::sync::atomic::Ordering;
56
57#[allow(dead_code)]
58static NEXT_WORKER_ID: AtomicUsize = AtomicUsize::new(1);
59
60#[cfg(target_arch = "wasm32")]
61thread_local! {
62    static WORKER_ID: usize = NEXT_WORKER_ID.fetch_add(1, Ordering::Relaxed);
63}
64
65/// Helper to get `performance.now()` in both Window and Worker contexts.
66#[must_use]
67pub fn performance_now() -> f64 {
68    #[cfg(target_arch = "wasm32")]
69    {
70        use wasm_bindgen::JsCast;
71        let global = js_sys::global();
72
73        // Try WorkerGlobalScope first
74        if let Ok(worker) = global.clone().dyn_into::<web_sys::WorkerGlobalScope>() {
75            return worker.performance().map(|p| p.now()).unwrap_or(0.0);
76        }
77
78        // Try Window
79        if let Ok(window) = global.dyn_into::<web_sys::Window>() {
80            return window.performance().map(|p| p.now()).unwrap_or(0.0);
81        }
82
83        // Fallback to Date
84        js_sys::Date::now()
85    }
86    #[cfg(not(target_arch = "wasm32"))]
87    {
88        0.0
89    }
90}
91
92#[allow(dead_code)]
93pub(crate) fn get_worker_id() -> usize {
94    #[cfg(target_arch = "wasm32")]
95    {
96        WORKER_ID.with(|&id| id)
97    }
98    #[cfg(not(target_arch = "wasm32"))]
99    {
100        0
101    }
102}
103
104#[cfg(target_arch = "wasm32")]
105mod wasm_impl {
106    use crate::assets;
107    use crate::metrics::with_collector;
108    use crate::performance_now;
109    use crate::render::RenderState;
110    use crate::shared_world::{MAX_ENTITIES, SabSlot, SharedWorld};
111    use crate::transport::WebTransportBridge;
112    use crate::world_state::ClientWorld;
113    use aetheris_encoder_serde::SerdeEncoder;
114    use aetheris_protocol::events::{NetworkEvent, ReplicationEvent};
115    use aetheris_protocol::traits::{Encoder, GameTransport};
116    use aetheris_protocol::types::{
117        ClientId, ComponentKind, InputCommand, NetworkId, PlayerInputKind,
118    };
119    use wasm_bindgen::prelude::*;
120
121    #[wasm_bindgen]
122    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
123    pub enum ConnectionState {
124        Disconnected,
125        Connecting,
126        InGame,
127        Reconnecting,
128        Failed,
129    }
130
131    /// A snapshot of the world for interpolation.
132    #[derive(Clone)]
133    pub struct SimulationSnapshot {
134        pub tick: u64,
135        pub entities: Vec<SabSlot>,
136    }
137
138    /// Global state held by the WASM instance.
139    #[wasm_bindgen]
140    pub struct AetherisClient {
141        pub(crate) shared_world: SharedWorld,
142        pub(crate) world_state: ClientWorld,
143        pub(crate) render_state: Option<RenderState>,
144        pub(crate) transport: Option<Box<dyn GameTransport>>,
145        pub(crate) worker_id: usize,
146        pub(crate) session_token: Option<String>,
147
148        // Interpolation state (Render Worker only)
149        pub(crate) snapshots: std::collections::VecDeque<SimulationSnapshot>,
150
151        // Network metrics
152        pub(crate) last_rtt_ms: f64,
153        ping_counter: u64,
154
155        reassembler: aetheris_protocol::Reassembler,
156        connection_state: ConnectionState,
157        reconnect_attempts: u32,
158        playground_rotation_enabled: bool,
159        playground_next_network_id: u64,
160        first_playground_tick: bool,
161
162        // Reusable buffer for zero-allocation rendering (Render Worker only)
163        pub(crate) render_buffer: Vec<SabSlot>,
164        pub(crate) asset_registry: assets::AssetRegistry,
165
166        // Input noise reduction
167        last_input_target: Option<NetworkId>,
168        last_input_actions: Vec<PlayerInputKind>,
169
170        pending_clear: bool,
171        last_clear_tick: u64,
172    }
173
174    #[wasm_bindgen]
175    impl AetherisClient {
176        /// Creates a new AetherisClient instance.
177        /// If a pointer is provided, it will use it as the backing storage (shared memory).
178        #[wasm_bindgen(constructor)]
179        pub fn new(shared_world_ptr: Option<u32>) -> Result<AetherisClient, JsValue> {
180            console_error_panic_hook::set_once();
181
182            // tracing_wasm doesn't have a clean try_init for global default.
183            // We use a static atomic to ensure only the first worker sets the global default.
184            use std::sync::atomic::{AtomicBool, Ordering};
185            static LOGGER_INITIALIZED: AtomicBool = AtomicBool::new(false);
186            if !LOGGER_INITIALIZED.swap(true, Ordering::SeqCst) {
187                let config = tracing_wasm::WASMLayerConfigBuilder::new()
188                    .set_max_level(tracing::Level::INFO)
189                    .build();
190                tracing_wasm::set_as_global_default_with_config(config);
191            }
192
193            let shared_world = if let Some(ptr_val) = shared_world_ptr {
194                let ptr = ptr_val as *mut u8;
195
196                // Security: Validate the incoming pointer before use
197                if ptr_val == 0 || !ptr_val.is_multiple_of(8) {
198                    return Err(JsValue::from_str(
199                        "Invalid shared_world_ptr: null or unaligned",
200                    ));
201                }
202
203                // JS-allocated SharedArrayBuffer pointers are not in the Rust registry
204                // (only Rust-owned allocations are registered). The null/alignment checks
205                // above are the only feasible boundary validation for externally-provided
206                // pointers; trusting the caller is required by the SAB contract.
207                unsafe { SharedWorld::from_ptr(ptr) }
208            } else {
209                SharedWorld::new()
210            };
211
212            let global = js_sys::global();
213            let (ua, lang) =
214                if let Ok(worker) = global.clone().dyn_into::<web_sys::WorkerGlobalScope>() {
215                    let n = worker.navigator();
216                    (n.user_agent().ok(), n.language())
217                } else if let Ok(window) = global.dyn_into::<web_sys::Window>() {
218                    let n = window.navigator();
219                    (n.user_agent().ok(), n.language())
220                } else {
221                    (None, None)
222                };
223
224            tracing::info!(
225                "Aetheris Client: Environment [UA: {}, Lang: {}]",
226                ua.as_deref().unwrap_or("Unknown"),
227                lang.as_deref().unwrap_or("Unknown")
228            );
229
230            tracing::info!(
231                "AetherisClient initialized on worker {}",
232                crate::get_worker_id()
233            );
234
235            // M10105 — emit wasm_init lifecycle span
236            with_collector(|c| {
237                c.push_event(
238                    1,
239                    "wasm_client",
240                    "AetherisClient initialized",
241                    "wasm_init",
242                    None,
243                );
244            });
245
246            let mut world_state = ClientWorld::new();
247            world_state.shared_world_ref = Some(shared_world.as_ptr() as usize);
248
249            Ok(Self {
250                shared_world,
251                world_state,
252                render_state: None,
253                transport: None,
254                worker_id: crate::get_worker_id(),
255                session_token: None,
256                snapshots: std::collections::VecDeque::with_capacity(8),
257                last_rtt_ms: 0.0,
258                ping_counter: 0,
259                reassembler: aetheris_protocol::Reassembler::new(),
260                connection_state: ConnectionState::Disconnected,
261                reconnect_attempts: 0,
262                playground_rotation_enabled: false,
263                playground_next_network_id: 1,
264                first_playground_tick: true,
265                render_buffer: Vec::with_capacity(crate::shared_world::MAX_ENTITIES),
266                asset_registry: assets::AssetRegistry::new(),
267                last_input_target: None,
268                last_input_actions: Vec::new(),
269                pending_clear: false,
270                last_clear_tick: 0,
271            })
272        }
273
274        #[wasm_bindgen]
275        pub async fn request_otp(base_url: String, email: String) -> Result<String, String> {
276            crate::auth::request_otp(base_url, email).await
277        }
278
279        #[wasm_bindgen]
280        pub async fn login_with_otp(
281            base_url: String,
282            request_id: String,
283            code: String,
284        ) -> Result<String, String> {
285            crate::auth::login_with_otp(base_url, request_id, code).await
286        }
287
288        #[wasm_bindgen]
289        pub async fn logout(base_url: String, session_token: String) -> Result<(), String> {
290            crate::auth::logout(base_url, session_token).await
291        }
292
293        #[wasm_bindgen(getter)]
294        pub fn connection_state(&self) -> ConnectionState {
295            self.connection_state
296        }
297
298        fn check_worker(&self) {
299            debug_assert_eq!(
300                self.worker_id,
301                crate::get_worker_id(),
302                "AetherisClient accessed from wrong worker! It is pin-bound to its creating thread."
303            );
304        }
305
306        /// Returns the raw pointer to the shared world buffer.
307        pub fn shared_world_ptr(&self) -> u32 {
308            self.shared_world.as_ptr() as u32
309        }
310
311        pub async fn connect(
312            &mut self,
313            url: String,
314            cert_hash: Option<Vec<u8>>,
315        ) -> Result<(), JsValue> {
316            self.check_worker();
317
318            if self.connection_state == ConnectionState::Connecting
319                || self.connection_state == ConnectionState::InGame
320                || self.connection_state == ConnectionState::Reconnecting
321            {
322                return Ok(());
323            }
324
325            // M10105 — emit reconnect_attempt if it looks like one
326            if self.connection_state == ConnectionState::Failed && self.reconnect_attempts > 0 {
327                with_collector(|c| {
328                    c.push_event(
329                        2,
330                        "transport",
331                        "Triggering reconnection",
332                        "reconnect_attempt",
333                        None,
334                    );
335                });
336            }
337
338            self.connection_state = ConnectionState::Connecting;
339            tracing::info!(url = %url, "Connecting to server...");
340
341            let transport_result = WebTransportBridge::connect(&url, cert_hash.as_deref()).await;
342
343            match transport_result {
344                Ok(transport) => {
345                    // Security: Send Auth message immediately after connection
346                    if let Some(token) = &self.session_token {
347                        let encoder = SerdeEncoder::new();
348                        let auth_event = NetworkEvent::Auth {
349                            session_token: token.clone(),
350                        };
351
352                        match encoder.encode_event(&auth_event) {
353                            Ok(data) => {
354                                if let Err(e) = transport.send_reliable(ClientId(0), &data).await {
355                                    self.connection_state = ConnectionState::Failed;
356                                    tracing::error!(error = ?e, "Handshake failed: could not send auth packet");
357                                    return Err(JsValue::from_str(&format!(
358                                        "Failed to send auth packet: {:?}",
359                                        e
360                                    )));
361                                }
362                                tracing::info!("Auth packet sent to server");
363                            }
364                            Err(e) => {
365                                self.connection_state = ConnectionState::Failed;
366                                tracing::error!(error = ?e, "Handshake failed: could not encode auth packet");
367                                return Err(JsValue::from_str("Failed to encode auth packet"));
368                            }
369                        }
370                    } else {
371                        tracing::warn!(
372                            "Connecting without session token! Server will likely discard data."
373                        );
374                    }
375
376                    self.transport = Some(Box::new(transport));
377                    self.connection_state = ConnectionState::InGame;
378                    self.reconnect_attempts = 0;
379                    tracing::info!("WebTransport connection established");
380                    // M10105 — connect_handshake lifecycle span
381                    with_collector(|c| {
382                        c.push_event(
383                            1,
384                            "transport",
385                            &format!("WebTransport connected: {url}"),
386                            "connect_handshake",
387                            None,
388                        );
389                    });
390                    Ok(())
391                }
392                Err(e) => {
393                    self.connection_state = ConnectionState::Failed;
394                    tracing::error!(error = ?e, "Failed to establish WebTransport connection");
395                    // M10105 — connect_handshake_failed lifecycle span (ERROR level)
396                    with_collector(|c| {
397                        c.push_event(
398                            3,
399                            "transport",
400                            &format!("WebTransport failed: {url} — {e:?}"),
401                            "connect_handshake_failed",
402                            None,
403                        );
404                    });
405                    Err(JsValue::from_str(&format!("failed to connect: {e:?}")))
406                }
407            }
408        }
409
410        #[wasm_bindgen]
411        pub async fn reconnect(
412            &mut self,
413            url: String,
414            cert_hash: Option<Vec<u8>>,
415        ) -> Result<(), JsValue> {
416            self.check_worker();
417            self.connection_state = ConnectionState::Reconnecting;
418            self.reconnect_attempts += 1;
419
420            tracing::info!(
421                "Attempting reconnection... (attempt {})",
422                self.reconnect_attempts
423            );
424
425            self.connect(url, cert_hash).await
426        }
427
428        #[wasm_bindgen]
429        pub async fn wasm_load_asset(
430            &mut self,
431            handle: assets::AssetHandle,
432            url: String,
433        ) -> Result<(), JsValue> {
434            self.asset_registry.load_asset(handle, &url).await
435        }
436
437        /// Sets the session token to be used for authentication upon connection.
438        pub fn set_session_token(&mut self, token: String) {
439            self.session_token = Some(token);
440        }
441
442        /// Initializes rendering with a canvas element.
443        /// Accepts either web_sys::HtmlCanvasElement or web_sys::OffscreenCanvas.
444        pub async fn init_renderer(&mut self, canvas: JsValue) -> Result<(), JsValue> {
445            self.check_worker();
446            use wasm_bindgen::JsCast;
447
448            let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
449                backends: wgpu::Backends::BROWSER_WEBGPU | wgpu::Backends::GL,
450                flags: wgpu::InstanceFlags::default(),
451                ..wgpu::InstanceDescriptor::new_without_display_handle()
452            });
453
454            // Handle both HtmlCanvasElement and OffscreenCanvas for Worker support
455            let (surface_target, width, height) =
456                if let Ok(html_canvas) = canvas.clone().dyn_into::<web_sys::HtmlCanvasElement>() {
457                    let width = html_canvas.width();
458                    let height = html_canvas.height();
459                    tracing::info!(
460                        "Initializing renderer on HTMLCanvasElement ({}x{})",
461                        width,
462                        height
463                    );
464                    (wgpu::SurfaceTarget::Canvas(html_canvas), width, height)
465                } else if let Ok(offscreen_canvas) =
466                    canvas.clone().dyn_into::<web_sys::OffscreenCanvas>()
467                {
468                    let width = offscreen_canvas.width();
469                    let height = offscreen_canvas.height();
470                    tracing::info!(
471                        "Initializing renderer on OffscreenCanvas ({}x{})",
472                        width,
473                        height
474                    );
475
476                    // Critical fix for wgpu 0.20+ on WASM workers:
477                    // Ensure the context is initialized with the 'webgpu' id before creating the surface.
478                    let _ = offscreen_canvas.get_context("webgpu").map_err(|e| {
479                        JsValue::from_str(&format!("Failed to get webgpu context: {:?}", e))
480                    })?;
481
482                    (
483                        wgpu::SurfaceTarget::OffscreenCanvas(offscreen_canvas),
484                        width,
485                        height,
486                    )
487                } else {
488                    return Err(JsValue::from_str(
489                        "Aetheris: Provided object is not a valid Canvas or OffscreenCanvas",
490                    ));
491                };
492
493            let surface = instance
494                .create_surface(surface_target)
495                .map_err(|e| JsValue::from_str(&format!("Failed to create surface: {:?}", e)))?;
496
497            let render_state = RenderState::new(&instance, surface, width, height)
498                .await
499                .map_err(|e| JsValue::from_str(&format!("Failed to init renderer: {:?}", e)))?;
500
501            self.render_state = Some(render_state);
502
503            // M10105 — emit render_pipeline_setup lifecycle span
504            with_collector(|c| {
505                c.push_event(
506                    1,
507                    "render_worker",
508                    &format!("Renderer initialized ({}x{})", width, height),
509                    "render_pipeline_setup",
510                    None,
511                );
512            });
513
514            Ok(())
515        }
516
517        #[wasm_bindgen]
518        pub fn resize(&mut self, width: u32, height: u32) {
519            if let Some(state) = &mut self.render_state {
520                state.resize(width, height);
521            }
522        }
523
524        #[cfg(debug_assertions)]
525        #[wasm_bindgen]
526        pub fn set_debug_mode(&mut self, mode: u32) {
527            self.check_worker();
528            if let Some(state) = &mut self.render_state {
529                state.set_debug_mode(match mode {
530                    0 => crate::render::DebugRenderMode::Off,
531                    1 => crate::render::DebugRenderMode::Wireframe,
532                    2 => crate::render::DebugRenderMode::Components,
533                    _ => crate::render::DebugRenderMode::Full,
534                });
535            }
536        }
537
538        #[wasm_bindgen]
539        pub fn set_theme_colors(&mut self, bg_base: &str, text_primary: &str) {
540            self.check_worker();
541            let clear = crate::render::parse_css_color(bg_base);
542            let label = crate::render::parse_css_color(text_primary);
543
544            tracing::info!(
545                "Aetheris Client: Applying theme colors [bg: {} -> {:?}, text: {} -> {:?}]",
546                bg_base,
547                clear,
548                text_primary,
549                label
550            );
551
552            if let Some(state) = &mut self.render_state {
553                state.set_clear_color(clear);
554                #[cfg(debug_assertions)]
555                state.set_label_color([
556                    label.r as f32,
557                    label.g as f32,
558                    label.b as f32,
559                    label.a as f32,
560                ]);
561            }
562        }
563
564        #[cfg(debug_assertions)]
565        #[wasm_bindgen]
566        pub fn cycle_debug_mode(&mut self) {
567            if let Some(state) = &mut self.render_state {
568                state.cycle_debug_mode();
569            }
570        }
571
572        #[cfg(debug_assertions)]
573        #[wasm_bindgen]
574        pub fn toggle_grid(&mut self) {
575            if let Some(state) = &mut self.render_state {
576                state.toggle_grid();
577            }
578        }
579
580        #[wasm_bindgen]
581        pub fn latest_tick(&self) -> u64 {
582            self.world_state.latest_tick
583        }
584
585        #[wasm_bindgen]
586        pub fn playground_apply_input(&mut self, move_x: f32, move_y: f32, actions_mask: u32) {
587            self.check_worker();
588            self.world_state
589                .playground_apply_input(move_x, move_y, actions_mask);
590        }
591
592        /// Simulation tick called by the Network Worker at a fixed rate (e.g. 20Hz).
593        pub async fn tick(&mut self) {
594            self.check_worker();
595            use aetheris_protocol::traits::{Encoder, WorldState};
596
597            let encoder = SerdeEncoder::new();
598
599            // 0. Reconnection Logic
600            // TODO: poll transport.closed() promise and trigger reconnection state machine
601            if let Some(_transport) = &self.transport {}
602
603            // 0.1 Periodic Ping (approx. every 1 second at 60Hz)
604            if let Some(transport) = &mut self.transport {
605                self.ping_counter = self.ping_counter.wrapping_add(1);
606                if self.ping_counter % 60 == 0 {
607                    // Use current time as timestamp (ms)
608                    let now = performance_now();
609                    let tick_u64 = now as u64;
610
611                    if let Ok(data) = encoder.encode_event(&NetworkEvent::Ping {
612                        client_id: ClientId(0), // Client doesn't know its ID yet usually
613                        tick: tick_u64,
614                    }) {
615                        tracing::trace!(tick = tick_u64, "Sending Ping");
616                        let _ = transport.send_unreliable(ClientId(0), &data).await;
617                    }
618                }
619            }
620
621            // 1. Poll Network
622            if let Some(transport) = &mut self.transport {
623                let events = match transport.poll_events().await {
624                    Ok(e) => e,
625                    Err(e) => {
626                        tracing::error!("Transport poll failure: {:?}", e);
627                        return;
628                    }
629                };
630                let mut updates: Vec<(ClientId, aetheris_protocol::events::ComponentUpdate)> =
631                    Vec::new();
632
633                for event in events {
634                    match event {
635                        NetworkEvent::UnreliableMessage { data, client_id }
636                        | NetworkEvent::ReliableMessage { data, client_id } => {
637                            match encoder.decode(&data) {
638                                Ok(update) => {
639                                    // M10105 — Always filter by epoch tick so stale datagrams are
640                                    // rejected even after the reliable ClearWorld ack has lowered
641                                    // pending_clear (unreliable datagrams may overtake the ack).
642                                    if self.last_clear_tick == 0
643                                        || update.tick > self.last_clear_tick
644                                    {
645                                        updates.push((client_id, update));
646                                    } else {
647                                        tracing::debug!(
648                                            network_id = update.network_id.0,
649                                            tick = update.tick,
650                                            last_clear_tick = self.last_clear_tick,
651                                            "Discarding stale update (tick <= last_clear_tick)"
652                                        );
653                                    }
654                                }
655                                Err(_) => {
656                                    // Try to decode as a protocol/wire event instead
657                                    if let Ok(event) = encoder.decode_event(&data) {
658                                        match event {
659                                            aetheris_protocol::events::NetworkEvent::GameEvent {
660                                                event: game_event,
661                                                ..
662                                            } => match &game_event {
663                                                aetheris_protocol::events::GameEvent::AsteroidDepleted {
664                                                    network_id,
665                                                } => {
666                                                    tracing::info!(?network_id, "Asteroid depleted");
667                                                    self.world_state.entities.remove(&network_id);
668
669                                                    for slot in self.world_state.entities.values_mut() {
670                                                        if (slot.flags & 0x04) != 0
671                                                            && slot.mining_target_id == (network_id.0 as u16)
672                                                        {
673                                                            slot.mining_active = 0;
674                                                            slot.mining_target_id = 0;
675                                                            tracing::info!("Cleared local mining target due to depletion");
676                                                        }
677                                                    }
678                                                }
679                                                aetheris_protocol::events::GameEvent::Possession {
680                                                    network_id: _,
681                                                } => {
682                                                    self.world_state.handle_game_event(&game_event);
683                                                }
684                                                aetheris_protocol::events::GameEvent::SystemManifest {
685                                                    manifest,
686                                                } => {
687                                                    tracing::info!(
688                                                        count = manifest.len(),
689                                                        "Received SystemManifest from server"
690                                                    );
691                                                    self.world_state.system_manifest = manifest.clone();
692                                                }
693                                            },
694                                            aetheris_protocol::events::NetworkEvent::ClearWorld {
695                                                ..
696                                            } => {
697                                                tracing::info!(
698                                                    "Server ClearWorld ack received (via ReliableMessage) — gate lowered"
699                                                );
700                                                self.pending_clear = false;
701                                            }
702                                            _ => {}
703                                        }
704                                    } else {
705                                        tracing::warn!(
706                                            "Failed to decode server message as update or wire event"
707                                        );
708                                    }
709                                }
710                            }
711                        }
712                        NetworkEvent::ClientConnected(id) => {
713                            tracing::info!(?id, "Server connected");
714                        }
715                        NetworkEvent::ClientDisconnected(id) => {
716                            tracing::warn!(?id, "Server disconnected");
717                        }
718                        NetworkEvent::Disconnected(_id) => {
719                            tracing::error!("Transport disconnected locally");
720                            self.connection_state = ConnectionState::Disconnected;
721                        }
722                        NetworkEvent::Ping { client_id: _, tick } => {
723                            // Immediately reflect the ping as a pong with same tick
724                            let pong = NetworkEvent::Pong { tick };
725                            if let Ok(data) = encoder.encode_event(&pong) {
726                                let _ = transport.send_reliable(ClientId(0), &data).await;
727                            }
728                        }
729                        NetworkEvent::Pong { tick } => {
730                            // Calculate RTT from our own outgoing pings
731                            let now = performance_now();
732                            let rtt = now - (tick as f64);
733                            self.last_rtt_ms = rtt;
734
735                            with_collector(|c| {
736                                c.update_rtt(rtt);
737                            });
738
739                            #[cfg(feature = "metrics")]
740                            metrics::gauge!("aetheris_client_rtt_ms").set(rtt);
741
742                            tracing::trace!(rtt_ms = rtt, tick, "Received Pong / RTT update");
743                        }
744                        NetworkEvent::Auth { .. } => {
745                            // Client initiated event usually, ignore if received from server
746                            tracing::debug!("Received Auth event from server (unexpected)");
747                        }
748                        NetworkEvent::SessionClosed(id) => {
749                            tracing::warn!(?id, "WebTransport session closed");
750                        }
751                        NetworkEvent::StreamReset(id) => {
752                            tracing::error!(?id, "WebTransport stream reset");
753                        }
754                        NetworkEvent::Fragment {
755                            client_id,
756                            fragment,
757                        } => {
758                            if let Some(data) = self.reassembler.ingest(client_id, fragment) {
759                                if let Ok(update) = encoder.decode(&data) {
760                                    if self.last_clear_tick == 0
761                                        || update.tick > self.last_clear_tick
762                                    {
763                                        updates.push((client_id, update));
764                                    }
765                                }
766                            }
767                        }
768                        NetworkEvent::StressTest { .. } => {
769                            // Client-side, we don't handle incoming stress test events usually,
770                            // they are processed by the server.
771                        }
772                        NetworkEvent::Spawn { .. } => {
773                            // Handled by GameWorker via p_spawn
774                        }
775                        NetworkEvent::ClearWorld { .. } => {
776                            // Reliable ack: guaranteed to arrive after all unreliable
777                            // datagrams sent before it (QUIC ordering).  Lower the gate
778                            // and do a final flush — from this point forward, no stale
779                            // entity updates can arrive.
780                            tracing::info!("Server ClearWorld ack received — gate lowered");
781                            self.pending_clear = false;
782                        }
783                        NetworkEvent::GameEvent {
784                            event: game_event, ..
785                        } => {
786                            // Forward to inner GameEvent logic if needed,
787                            // or just handle the depletion here if it's the only one.
788                            match &game_event {
789                                aetheris_protocol::events::GameEvent::AsteroidDepleted {
790                                    network_id,
791                                } => {
792                                    tracing::info!(
793                                        ?network_id,
794                                        "Asteroid depleted (via GameEvent)"
795                                    );
796                                    // Instant local despawn to hide latency
797                                    self.world_state.entities.remove(&network_id);
798
799                                    // Clear local mining target if it matches the depleted asteroid
800                                    for slot in self.world_state.entities.values_mut() {
801                                        // flags & 0x04 is local player
802                                        if (slot.flags & 0x04) != 0
803                                            && slot.mining_target_id == (network_id.0 as u16)
804                                        {
805                                            slot.mining_active = 0;
806                                            slot.mining_target_id = 0;
807                                            tracing::info!(
808                                                "Cleared local mining target due to depletion"
809                                            );
810                                        }
811                                    }
812                                }
813                                aetheris_protocol::events::GameEvent::SystemManifest {
814                                    manifest,
815                                } => {
816                                    tracing::info!(
817                                        count = manifest.len(),
818                                        "Received SystemManifest from server (via GameEvent)"
819                                    );
820                                    self.world_state.system_manifest = manifest.clone();
821                                }
822                                aetheris_protocol::events::GameEvent::Possession {
823                                    network_id: _,
824                                } => {
825                                    self.world_state.handle_game_event(&game_event);
826                                }
827                            }
828                        }
829                        #[allow(unreachable_patterns)]
830                        _ => {
831                            tracing::debug!("Unhandled outer NetworkEvent variant");
832                        }
833                    }
834                }
835
836                // 2. Apply updates to the Simulation World
837                // Skip while a ClearWorld ack is pending: any updates arriving
838                // now are stale datagrams from before the clear command.
839                if self.pending_clear {
840                    if !updates.is_empty() {
841                        tracing::debug!(
842                            count = updates.len(),
843                            "Discarding updates — pending_clear gate is raised"
844                        );
845                    }
846                } else {
847                    if !updates.is_empty() {
848                        tracing::debug!(count = updates.len(), "Applying server updates to world");
849                    }
850                    self.world_state.apply_updates(&updates);
851                }
852            }
853
854            // 2.5. Client-side rotation animation (local, not replicated by server)
855            if self.playground_rotation_enabled {
856                for slot in self.world_state.entities.values_mut() {
857                    slot.rotation = (slot.rotation + 0.05) % std::f32::consts::TAU;
858                }
859            }
860
861            // Advance local tick every frame so the render worker always sees a new snapshot,
862            // even when the server sends no updates (static entities, client-side animation).
863            self.world_state.latest_tick += 1;
864
865            // M10105 — measure simulation time
866            let sim_start = crate::performance_now();
867
868            // 3. Write Authoritative Snapshot to Shared World for the Render Worker
869            self.flush_to_shared_world(self.world_state.latest_tick);
870
871            let sim_time_ms = crate::performance_now() - sim_start;
872            let count = self.world_state.entities.len() as u32;
873            with_collector(|c| {
874                c.record_sim(sim_time_ms);
875                c.update_entity_count(count);
876            });
877        }
878
879        fn flush_to_shared_world(&mut self, tick: u64) {
880            let entities = &self.world_state.entities;
881            let write_buffer = self.shared_world.get_write_buffer();
882
883            let mut count = 0;
884            for (i, slot) in entities.values().enumerate() {
885                if i >= MAX_ENTITIES {
886                    tracing::warn!("Max entities reached in shared world! Overflow suppressed.");
887                    break;
888                }
889                write_buffer[i] = *slot;
890                count += 1;
891            }
892
893            tracing::debug!(entity_count = count, tick, "Flushed world to SAB");
894            self.shared_world.commit_write(count as u32, tick);
895        }
896
897        #[wasm_bindgen]
898        pub async fn request_system_manifest(&mut self) -> Result<(), JsValue> {
899            self.check_worker();
900
901            if let Some(transport) = &self.transport {
902                let encoder = SerdeEncoder::new();
903                let event = NetworkEvent::RequestSystemManifest {
904                    client_id: ClientId(0),
905                };
906
907                if let Ok(data) = encoder.encode_event(&event) {
908                    transport
909                        .send_reliable(ClientId(0), &data)
910                        .await
911                        .map_err(|e| JsValue::from_str(&format!("{e:?}")))?;
912                    tracing::info!("Sent RequestSystemManifest command to server");
913                }
914            }
915            Ok(())
916        }
917
918        #[wasm_bindgen]
919        pub fn get_system_info(&self) -> Result<JsValue, JsValue> {
920            serde_wasm_bindgen::to_value(&self.world_state.system_manifest)
921                .map_err(|e| JsValue::from_str(&e.to_string()))
922        }
923
924        #[wasm_bindgen]
925        pub fn playground_spawn(&mut self, entity_type: u16, x: f32, y: f32, rotation: f32) {
926            // Security: Prevent overflow in playground mode
927            if self.world_state.entities.len() >= MAX_ENTITIES {
928                tracing::warn!("playground_spawn: MAX_ENTITIES reached, spawn ignored.");
929                return;
930            }
931
932            // Sync ID generator if it's currently at default but world is seeded
933            if self.playground_next_network_id == 1 && !self.world_state.entities.is_empty() {
934                self.playground_next_network_id = self
935                    .world_state
936                    .entities
937                    .keys()
938                    .map(|k| k.0)
939                    .max()
940                    .unwrap_or(0)
941                    + 1;
942            }
943
944            let id = aetheris_protocol::types::NetworkId(self.playground_next_network_id);
945            self.playground_next_network_id += 1;
946            let slot = SabSlot {
947                network_id: id.0,
948                x,
949                y,
950                z: 0.0,
951                rotation,
952                dx: 0.0,
953                dy: 0.0,
954                dz: 0.0,
955                hp: 100,
956                shield: 100,
957                entity_type,
958                flags: 0x01, // ALIVE
959                mining_active: 0,
960                cargo_ore: 0,
961                mining_target_id: 0,
962            };
963            self.world_state.entities.insert(id, slot);
964        }
965
966        #[wasm_bindgen]
967        pub async fn playground_spawn_net(
968            &mut self,
969            entity_type: u16,
970            x: f32,
971            y: f32,
972            rot: f32,
973        ) -> Result<(), JsValue> {
974            self.check_worker();
975
976            if let Some(transport) = &self.transport {
977                let encoder = SerdeEncoder::new();
978                let event = NetworkEvent::Spawn {
979                    client_id: ClientId(0),
980                    entity_type,
981                    x,
982                    y,
983                    rot,
984                };
985
986                if let Ok(data) = encoder.encode_event(&event) {
987                    transport
988                        .send_reliable(ClientId(0), &data)
989                        .await
990                        .map_err(|e| JsValue::from_str(&format!("{e:?}")))?;
991                    tracing::info!(entity_type, x, y, "Sent Spawn command to server");
992                }
993            } else {
994                // Local fallback
995                self.playground_spawn(entity_type, x, y, rot);
996            }
997            Ok(())
998        }
999
1000        #[wasm_bindgen]
1001        pub fn playground_clear(&mut self) {
1002            self.world_state.entities.clear();
1003        }
1004
1005        /// Sends a StartSession command to the server.
1006        /// The server will spawn the session Interceptor and send back a Possession event.
1007        /// Only valid when connected; does nothing in local sandbox mode.
1008        #[wasm_bindgen]
1009        pub async fn start_session_net(&mut self) -> Result<(), JsValue> {
1010            self.check_worker();
1011
1012            if let Some(transport) = &self.transport {
1013                let encoder = SerdeEncoder::new();
1014                let event = NetworkEvent::StartSession {
1015                    client_id: ClientId(0),
1016                };
1017                if let Ok(data) = encoder.encode_event(&event) {
1018                    transport
1019                        .send_reliable(ClientId(0), &data)
1020                        .await
1021                        .map_err(|e| JsValue::from_str(&format!("{e:?}")))?;
1022                    tracing::info!("Sent StartSession command to server");
1023                }
1024            }
1025            Ok(())
1026        }
1027
1028        /// Sends a movement/action input command to the server.
1029        ///
1030        /// The input is encoded as an unreliable component update (Kind 128)
1031        /// and sent to the server for processing in the next tick.
1032        #[wasm_bindgen]
1033        pub async fn send_input(
1034            &mut self,
1035            tick: u64,
1036            move_x: f32,
1037            move_y: f32,
1038            actions_mask: u32,
1039            target_id_arg: Option<u64>,
1040        ) -> Result<(), JsValue> {
1041            self.check_worker();
1042
1043            // 1. Identify the controlled player entity to target the command correctly
1044            let target_id = if let Some(owned_id) = self.world_state.player_network_id {
1045                // If we have an explicit possession ID from the server, use it.
1046                // This is the most reliable method (M1038).
1047                tracing::info!(
1048                    network_id = owned_id.0,
1049                    "[send_input] Using player_network_id for input target"
1050                );
1051                Some(owned_id)
1052            } else {
1053                // Fallback: Identify via replication flags if possession event hasn't arrived yet
1054                let fallback = self
1055                    .world_state
1056                    .entities
1057                    .iter()
1058                    .find(|(_, slot)| (slot.flags & 0x04) != 0)
1059                    .map(|(id, _)| *id);
1060                tracing::trace!(
1061                    fallback_id = ?fallback,
1062                    "[send_input] No player_network_id set - using 0x04 flag fallback"
1063                );
1064                fallback
1065            };
1066
1067            let Some(target_id) = target_id else {
1068                tracing::trace!("[send_input] Input dropped: no controlled entity found");
1069                return Ok(());
1070            };
1071
1072            tracing::info!(
1073                target_id = target_id.0,
1074                move_x,
1075                move_y,
1076                "[send_input] Sending input for entity"
1077            );
1078
1079            // 2. Prepare actions vector
1080            let mut actions = Vec::new();
1081
1082            // Movement action
1083            if move_x.abs() > f32::EPSILON || move_y.abs() > f32::EPSILON {
1084                actions.push(PlayerInputKind::Move {
1085                    x: move_x,
1086                    y: move_y,
1087                });
1088            }
1089
1090            // Bitmask actions (M1020 mapping)
1091            // Bit 0: FirePrimary
1092            if (actions_mask & 0x01) != 0 {
1093                actions.push(PlayerInputKind::FirePrimary);
1094            }
1095            // Bit 1: ToggleMining
1096            if (actions_mask & 0x02) != 0 {
1097                if let Some(id) = target_id_arg {
1098                    actions.push(PlayerInputKind::ToggleMining {
1099                        target: NetworkId(id),
1100                    });
1101                } else {
1102                    tracing::warn!("ToggleMining requested without target_id; dropping action");
1103                }
1104            }
1105
1106            // 3. Noise reduction check
1107            let is_repeated = self.last_input_actions.len() == actions.len()
1108                && self
1109                    .last_input_actions
1110                    .iter()
1111                    .zip(actions.iter())
1112                    .all(|(a, b)| a == b)
1113                && self.last_input_target == Some(target_id);
1114
1115            if move_x.abs() > f32::EPSILON || move_y.abs() > f32::EPSILON || actions_mask != 0 {
1116                if is_repeated {
1117                    tracing::trace!(
1118                        tick,
1119                        move_x,
1120                        move_y,
1121                        actions_mask,
1122                        "Client sending input (repeated)"
1123                    );
1124                } else {
1125                    tracing::info!(tick, move_x, move_y, actions_mask, "Client sending input");
1126                }
1127            }
1128
1129            let transport = self.transport.as_ref().ok_or_else(|| {
1130                JsValue::from_str("Cannot send input: transport not initialized or closed")
1131            })?;
1132
1133            if is_repeated {
1134                tracing::trace!(
1135                    ?target_id,
1136                    x = move_x,
1137                    y = move_y,
1138                    "Sending InputCommand (repeated)"
1139                );
1140            } else {
1141                tracing::info!(?target_id, x = move_x, y = move_y, "Sending InputCommand");
1142            }
1143
1144            // Update last input state
1145            self.last_input_target = Some(target_id);
1146            self.last_input_actions = actions.clone();
1147
1148            let cmd = InputCommand {
1149                tick,
1150                actions,
1151                last_seen_input_tick: None,
1152            }
1153            .clamped();
1154
1155            // 4. Encode as a ComponentUpdate-compatible packet
1156            // We use ComponentKind(128) as the convention for InputCommands.
1157            // The server's TickScheduler will decode this as a standard game update.
1158            let payload = rmp_serde::to_vec(&cmd)
1159                .map_err(|e| JsValue::from_str(&format!("Failed to encode InputCommand: {e:?}")))?;
1160
1161            let update = ReplicationEvent {
1162                network_id: target_id,
1163                component_kind: ComponentKind(128),
1164                payload,
1165                tick,
1166            };
1167
1168            let mut buffer = [0u8; 1024];
1169            let encoder = SerdeEncoder::new();
1170            let len = encoder.encode(&update, &mut buffer).map_err(|e| {
1171                JsValue::from_str(&format!("Failed to encode input replication event: {e:?}"))
1172            })?;
1173
1174            // 3. Send via unreliable datagram
1175            transport
1176                .send_unreliable(ClientId(0), &buffer[..len])
1177                .await
1178                .map_err(|e| {
1179                    JsValue::from_str(&format!("Transport error during send_input: {e:?}"))
1180                })?;
1181
1182            Ok(())
1183        }
1184
1185        #[wasm_bindgen]
1186        pub async fn playground_clear_server(&mut self) -> Result<(), JsValue> {
1187            self.check_worker();
1188
1189            if let Some(transport) = &self.transport {
1190                let encoder = SerdeEncoder::new();
1191                let event = NetworkEvent::ClearWorld {
1192                    client_id: ClientId(0),
1193                };
1194                if let Ok(data) = encoder.encode_event(&event) {
1195                    transport
1196                        .send_reliable(ClientId(0), &data)
1197                        .await
1198                        .map_err(|e| JsValue::from_str(&format!("{e:?}")))?;
1199                    tracing::info!(
1200                        "Sent ClearWorld command to server — suppressing updates until ack"
1201                    );
1202                    // Immediately clear local state and raise the gate.  All incoming
1203                    // entity updates are suppressed until the server's reliable ClearWorld
1204                    // ack arrives, preventing stale in-flight datagrams from re-adding
1205                    // entities that were just despawned on the server.
1206                    self.world_state.entities.clear();
1207                    self.world_state.player_network_id = None;
1208                    self.pending_clear = true;
1209                    self.last_clear_tick = self.world_state.latest_tick;
1210                }
1211            } else {
1212                // No transport, clear immediately (no in-flight datagrams to worry about)
1213                self.world_state.entities.clear();
1214                self.world_state.player_network_id = None;
1215            }
1216            Ok(())
1217        }
1218
1219        #[wasm_bindgen]
1220        pub fn playground_set_rotation_enabled(&mut self, enabled: bool) {
1221            self.playground_rotation_enabled = enabled;
1222            // Note: Rotation toggle is currently local-authoritative in playground_tick,
1223            // but for server-side replication it would need a network event.
1224        }
1225
1226        #[wasm_bindgen]
1227        pub async fn playground_stress_test(
1228            &mut self,
1229            count: u16,
1230            rotate: bool,
1231        ) -> Result<(), JsValue> {
1232            self.check_worker();
1233
1234            if let Some(transport) = &self.transport {
1235                let encoder = SerdeEncoder::new();
1236                let event = NetworkEvent::StressTest {
1237                    client_id: ClientId(0),
1238                    count,
1239                    rotate,
1240                };
1241
1242                if let Ok(data) = encoder.encode_event(&event) {
1243                    transport
1244                        .send_reliable(ClientId(0), &data)
1245                        .await
1246                        .map_err(|e| JsValue::from_str(&format!("{e:?}")))?;
1247                    tracing::info!(count, rotate, "Sent StressTest command to server");
1248                }
1249                self.playground_set_rotation_enabled(rotate);
1250            } else {
1251                // Fallback to local behavior if not connected
1252                self.playground_set_rotation_enabled(rotate);
1253                self.playground_clear();
1254                for _ in 0..count {
1255                    self.playground_spawn(1, 0.0, 0.0, 0.0); // Simple spawn
1256                }
1257            }
1258
1259            Ok(())
1260        }
1261
1262        #[wasm_bindgen]
1263        pub async fn tick_playground(&mut self) {
1264            self.check_worker();
1265
1266            // M10105 — emit tick_playground_loop_start lifecycle span
1267            if self.first_playground_tick {
1268                self.first_playground_tick = false;
1269                with_collector(|c| {
1270                    c.push_event(
1271                        1,
1272                        "wasm_client",
1273                        "Playground simulation loop started",
1274                        "tick_playground_loop_start",
1275                        None,
1276                    );
1277                });
1278            }
1279
1280            // M10105 — measure simulation time
1281            let sim_start = crate::performance_now();
1282            self.world_state.latest_tick += 1;
1283
1284            if self.playground_rotation_enabled {
1285                for slot in self.world_state.entities.values_mut() {
1286                    slot.rotation = (slot.rotation + 0.05) % std::f32::consts::TAU;
1287                }
1288            }
1289
1290            // Sync to shared world
1291            let count = self.world_state.entities.len() as u32;
1292            self.flush_to_shared_world(self.world_state.latest_tick);
1293
1294            let sim_time_ms = crate::performance_now() - sim_start;
1295            with_collector(|c| {
1296                c.record_sim(sim_time_ms);
1297                c.update_entity_count(count);
1298            });
1299        }
1300
1301        /// Render frame called by the Render Worker.
1302        pub fn render(&mut self) -> f64 {
1303            self.check_worker();
1304
1305            let tick = self.shared_world.tick();
1306            let entities = self.shared_world.get_read_buffer();
1307            let bounds = self.shared_world.get_room_bounds();
1308            if let Some(state) = &mut self.render_state {
1309                state.set_room_bounds(bounds);
1310            }
1311
1312            // Periodic diagnostic log for render worker
1313            thread_local! {
1314                static FRAME_COUNT: core::cell::Cell<u64> = core::cell::Cell::new(0);
1315            }
1316            FRAME_COUNT.with(|count| {
1317                let current = count.get();
1318                if current % 300 == 0 {
1319                    tracing::debug!(
1320                        "Aetheris Render Stats: Tick={}, Entities={}, Snapshots={}",
1321                        tick,
1322                        entities.len(),
1323                        self.snapshots.len(),
1324                    );
1325                }
1326                count.set(current + 1);
1327            });
1328
1329            if tick == 0 {
1330                // Background only or placeholder if no simulation is running yet
1331                let mut frame_time_ms = 0.0;
1332                if let Some(state) = &mut self.render_state {
1333                    frame_time_ms = state.render_frame_with_compact_slots(&[]);
1334                    with_collector(|c| {
1335                        // FPS is computed in the worker; we only report duration here.
1336                        // FPS=0 here as it is not authoritative.
1337                        c.record_frame(frame_time_ms, 0.0);
1338                    });
1339                }
1340                return frame_time_ms;
1341            }
1342
1343            // 1. Buffer new snapshots — only push when tick advances
1344            if self.snapshots.is_empty()
1345                || tick > self.snapshots.back().map(|s| s.tick).unwrap_or(0)
1346            {
1347                self.snapshots.push_back(SimulationSnapshot {
1348                    tick,
1349                    entities: entities.to_vec(),
1350                });
1351            }
1352
1353            // 2. Calculate target playback tick.
1354            // Stay 2 ticks behind latest so we always have an (s1, s2) interpolation pair.
1355            // This is rate-independent: works for both the 20 Hz server and the 60 Hz playground.
1356            let mut frame_time_ms = 0.0;
1357            if !self.snapshots.is_empty() {
1358                let latest_tick = self.snapshots.back().unwrap().tick as f32;
1359                let target_tick = latest_tick - 2.0;
1360                frame_time_ms = self.render_at_tick(target_tick);
1361            }
1362
1363            // M10105 — record accurate frame time (from WGPU) + snapshot depth.
1364            let snap_count = self.snapshots.len() as u32;
1365            with_collector(|c| {
1366                // FPS is computed in the worker; we only report duration here.
1367                c.record_frame(frame_time_ms, 0.0);
1368                c.update_snapshot_count(snap_count);
1369            });
1370
1371            frame_time_ms
1372        }
1373
1374        fn render_at_tick(&mut self, target_tick: f32) -> f64 {
1375            if self.snapshots.len() < 2 {
1376                // If we don't have enough snapshots for interpolation,
1377                // we still want to render the background or at least one frame.
1378                if let Some(state) = &mut self.render_state {
1379                    let entities = if !self.snapshots.is_empty() {
1380                        self.snapshots[0].entities.clone()
1381                    } else {
1382                        Vec::new()
1383                    };
1384                    return state.render_frame_with_compact_slots(&entities);
1385                }
1386                return 0.0;
1387            }
1388
1389            // Find snapshots S1, S2 such that S1.tick <= target_tick < S2.tick
1390            let mut s1_idx = 0;
1391            let mut found = false;
1392
1393            for i in 0..self.snapshots.len() - 1 {
1394                if (self.snapshots[i].tick as f32) <= target_tick
1395                    && (self.snapshots[i + 1].tick as f32) > target_tick
1396                {
1397                    s1_idx = i;
1398                    found = true;
1399                    break;
1400                }
1401            }
1402
1403            if !found {
1404                // If we are outside the buffer range, clamp to the nearest edge
1405                if target_tick < self.snapshots[0].tick as f32 {
1406                    s1_idx = 0;
1407                } else {
1408                    s1_idx = self.snapshots.len() - 2;
1409                }
1410            }
1411
1412            let s1 = self.snapshots.get(s1_idx).unwrap();
1413            let s2 = self.snapshots.get(s1_idx + 1).unwrap();
1414
1415            let tick_range = (s2.tick - s1.tick) as f32;
1416            let alpha = if tick_range > 0.0 {
1417                (target_tick - s1.tick as f32) / tick_range
1418            } else {
1419                1.0
1420            }
1421            .clamp(0.0, 1.0);
1422
1423            // Interpolate entities into a reusable buffer to avoid per-frame heap allocations
1424            self.render_buffer.clear();
1425            self.render_buffer.extend_from_slice(&s2.entities);
1426
1427            // Build a lookup map from the previous snapshot for O(1) access per entity.
1428            let prev_map: std::collections::HashMap<u64, &SabSlot> =
1429                s1.entities.iter().map(|e| (e.network_id, e)).collect();
1430
1431            for ent in &mut self.render_buffer {
1432                if let Some(prev) = prev_map.get(&ent.network_id).copied() {
1433                    ent.x = lerp(prev.x, ent.x, alpha);
1434                    ent.y = lerp(prev.y, ent.y, alpha);
1435                    ent.z = lerp(prev.z, ent.z, alpha);
1436                    ent.rotation = lerp_rotation(prev.rotation, ent.rotation, alpha);
1437                }
1438            }
1439
1440            let mut frame_time = 0.0;
1441            if let Some(state) = &mut self.render_state {
1442                frame_time = state.render_frame_with_compact_slots(&self.render_buffer);
1443            }
1444
1445            // 3. Prune old snapshots.
1446            // We keep the oldest one that is still relevant for interpolation (index 0)
1447            // and everything newer. We prune snapshots that are entirely behind our window.
1448            while self.snapshots.len() > 2 && (self.snapshots[0].tick as f32) < target_tick - 1.0 {
1449                self.snapshots.pop_front();
1450            }
1451
1452            // Safety cap: prevent unbounded growth if simulation stops but render continues
1453            while self.snapshots.len() > 16 {
1454                self.snapshots.pop_front();
1455            }
1456
1457            frame_time
1458        }
1459    }
1460
1461    fn lerp(a: f32, b: f32, alpha: f32) -> f32 {
1462        a + (b - a) * alpha
1463    }
1464
1465    fn lerp_rotation(a: f32, b: f32, alpha: f32) -> f32 {
1466        // Simple rotation lerp for Phase 1.
1467        // Handles 2pi wraparound for smooth visuals.
1468        let mut diff = b - a;
1469        while diff < -std::f32::consts::PI {
1470            diff += std::f32::consts::TAU;
1471        }
1472        while diff > std::f32::consts::PI {
1473            diff -= std::f32::consts::TAU;
1474        }
1475        a + diff * alpha
1476    }
1477}