Skip to main content

webizen_render/
volumetric.rs

1//! SDK facade over QualiaDB's canonical wgpu 29 volumetric renderer.
2//!
3//! This is the native bridge used by desktop/studio embedders. It deliberately delegates the
4//! projection, depth, standpoint, bloom, picking, tensor ABI, and shared-device ownership to
5//! `qualia-core-db`; this crate only adapts the serde scene contract.
6
7use crate::scene_contract::{RenderScene, ScenePoint};
8use qualia_core_db::render::gpu::PortalGpu;
9use qualia_core_db::render::telemetry::SystemTelemetry as CoreTelemetry;
10use qualia_core_db::render::texture_stream_policy::TextureStreamBudget;
11use qualia_core_db::tensor::buffer_export::{write_tensor_buffer, TensorBufferHeader};
12use qualia_core_db::tensor::Tensor10D;
13
14pub use crate::volumetric_hmc::{
15    HmcTextureResidencyRequest, HmcTextureStreamApplyRequest, HmcTextureStreamPlan,
16    HmcTextureStreamRequest,
17};
18
19/// Result of best-effort HMC texture admission. Missing or budget-deferred interpretations bind
20/// the renderer's typed fallback texture; they do not prevent the `.10d` mesh from loading.
21#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
22pub struct HmcTextureAdmissionReport {
23    pub requested_interpretations: usize,
24    pub resident_interpretations: usize,
25    pub deferred_interpretations: usize,
26    pub admitted_mips: usize,
27    pub deferred_mips: usize,
28    pub admitted_upload_bytes: u64,
29    pub deferred_upload_bytes: u64,
30    /// KTX2/Basis-like inputs refused by the validated decoder capability set rather than
31    /// silently transcoded. Budget and decode failures are reported separately as deferrals.
32    pub capability_refusals: usize,
33}
34
35/// Cross-platform volumetric renderer SDK. Native instances render offscreen on the same physical
36/// wgpu device as QualiaDB inference and expose caller-buffered RGBA8 readback.
37pub struct VolumetricRenderer {
38    pub(crate) inner: PortalGpu,
39    pub(crate) texture_stream_state: Option<crate::volumetric_hmc::HmcTextureStreamState>,
40}
41
42impl VolumetricRenderer {
43    /// Create a volumetric renderer from an existing `PortalGpu` instance.
44    pub fn from_portal_gpu(inner: PortalGpu) -> Self {
45        Self {
46            inner,
47            texture_stream_state: None,
48        }
49    }
50
51    /// Create a volumetric renderer targeting a browser HTML canvas element.
52    #[cfg(target_arch = "wasm32")]
53    pub async fn from_canvas(
54        canvas: web_sys::HtmlCanvasElement,
55        particle_cap: usize,
56    ) -> Result<Self, String> {
57        Ok(Self {
58            inner: PortalGpu::try_new_async(&canvas, particle_cap).await?,
59            texture_stream_state: None,
60        })
61    }
62
63    /// New offscreen renderer.
64    #[cfg(not(target_arch = "wasm32"))]
65    pub fn new_offscreen(width: u32, height: u32, particle_cap: usize) -> Result<Self, String> {
66        Ok(Self {
67            inner: PortalGpu::new_offscreen(width, height, particle_cap)?,
68            texture_stream_state: None,
69        })
70    }
71
72    /// Create a **surface** renderer that draws directly to a window's GPU swapchain.
73    ///
74    /// This is the native desktop path — no PNG round-trip, no webview `<img>`.
75    /// The surface is created from a raw window handle (HWND on Windows).
76    /// Call `render()` to draw a frame; the swapchain present is automatic.
77    #[cfg(not(target_arch = "wasm32"))]
78    pub fn new_surface(
79        hwnd: isize,
80        width: u32,
81        height: u32,
82        particle_cap: usize,
83    ) -> Result<Self, String> {
84        Ok(Self {
85            inner: PortalGpu::new_surface(hwnd, width, height, particle_cap)?,
86            texture_stream_state: None,
87        })
88    }
89
90    /// Uploads a tensor buffer.
91    pub fn upload_tensor_buffer(&mut self, bytes: &[u8]) -> Result<u32, String> {
92        self.inner.upload_tensor_buffer(bytes)
93    }
94
95    /// Load one `.10d` scene asset and its digest-verified HMC texture dependencies.
96    /// Texture decode and GPU residency remain cold, bounded asset-boundary work.
97    pub fn load_hmc_asset(
98        &mut self,
99        hmc_bytes: &[u8],
100        asset_key: &str,
101    ) -> Result<(u32, u32, f32), String> {
102        let (loaded, _) = self.load_hmc_asset_with_texture_budget(
103            hmc_bytes,
104            asset_key,
105            TextureStreamBudget {
106                max_resident_bytes: u64::MAX,
107                max_upload_bytes: u64::MAX,
108            },
109        )?;
110        Ok(loaded)
111    }
112
113    /// Load an HMC `.10d` asset while admitting texture mips according to view footprint
114    /// and streaming budgets. For KTX2 resources with stored coarse levels, the authored
115    /// mip is decoded directly without decompressing level zero or performing CPU filtering.
116    pub fn load_hmc_asset_with_texture_request(
117        &mut self,
118        hmc_bytes: &[u8],
119        asset_key: &str,
120        request: HmcTextureStreamRequest,
121    ) -> Result<((u32, u32, f32), HmcTextureAdmissionReport), String> {
122        crate::volumetric_hmc::load_hmc_asset_with_texture_request(
123            self, hmc_bytes, asset_key, request,
124        )
125    }
126
127    /// Load an HMC `.10d` asset while admitting only the highest-priority coarse-to-fine texture
128    /// mip prefix that fits the supplied per-load budgets. A texture admitted at mip `m` is
129    /// physically allocated from that mip's dimensions, with its remaining coarser chain generated
130    /// on the GPU. Deferred interpretations use typed fallback maps for this scene load.
131    ///
132    /// These budgets govern incremental HMC residency; they are separate from the 42 MiB semantic
133    /// Sentinel and from graphics reservations owned by earlier scene loads. This API does not
134    /// evict or refine textures already bound into existing material groups.
135    pub fn load_hmc_asset_with_texture_budget(
136        &mut self,
137        hmc_bytes: &[u8],
138        asset_key: &str,
139        budget: TextureStreamBudget,
140    ) -> Result<((u32, u32, f32), HmcTextureAdmissionReport), String> {
141        self.load_hmc_asset_with_texture_request(
142            hmc_bytes,
143            asset_key,
144            HmcTextureStreamRequest {
145                budget,
146                projected_width: 0,
147                projected_height: 0,
148            },
149        )
150    }
151
152    /// Plan a bounded working-set transition for the active HMC asset. The request list is the
153    /// complete set of interpretations that should remain resident; omitted entries are evicted.
154    pub fn request_texture_stream(
155        &self,
156        request: HmcTextureStreamApplyRequest<'_>,
157    ) -> Result<HmcTextureStreamPlan, String> {
158        crate::volumetric_hmc::request_texture_stream(self, request)
159    }
160
161    /// Apply a previously generated texture plan. A stale generation is rejected before any GPU
162    /// mutation; successful refinement/eviction rebuilds the active material bind groups.
163    pub fn apply_texture_stream(&mut self, plan: HmcTextureStreamPlan) -> Result<(), String> {
164        crate::volumetric_hmc::apply_texture_stream(self, plan)
165    }
166
167    /// Load a verified HMC mesh as the renderer-owned water surface. The
168    /// surface uses shared scene depth and remains outside semantic picking.
169    pub fn load_hmc_water_asset(
170        &mut self,
171        hmc_bytes: &[u8],
172        asset_key: &str,
173    ) -> Result<(u32, u32), String> {
174        crate::volumetric_hmc::load_hmc_water_asset(self, hmc_bytes, asset_key)
175    }
176
177    /// Uploads a mesh.
178    pub fn upload_mesh(&mut self, positions: &[[f32; 3]], indices: &[u32]) -> u32 {
179        self.inner.upload_mesh(positions, indices)
180    }
181
182    /// Upload a `.10d` QuantizedMesh section (QualiaDB's compact native
183    /// geometry format — u16-quantized vertices within the mesh's bounding
184    /// box, u16/u32 triangle indices).
185    ///
186    /// Decode/allocation occurs once at this explicit asset boundary; the
187    /// resulting vertex/index buffers use the normal zero-copy GPU draw path.
188    pub fn upload_10d_mesh(&mut self, bytes: &[u8]) -> Result<u32, String> {
189        let mesh =
190            qualia_core_db::container_10d::decode_mesh_section(bytes).map_err(|e| e.to_string())?;
191        let mut indices = Vec::with_capacity(mesh.triangles.len() * 3);
192        for triangle in &mesh.triangles {
193            indices.extend_from_slice(triangle);
194        }
195        Ok(self.inner.upload_mesh(&mesh.positions, &indices))
196    }
197
198    /// Uploads a colored mesh.
199    pub fn upload_mesh_colored(
200        &mut self,
201        positions: &[[f32; 3]],
202        colors: &[[f32; 4]],
203        indices: &[u32],
204    ) -> u32 {
205        self.inner.upload_mesh_colored(positions, colors, indices)
206    }
207
208    /// Sets camera.
209    pub fn set_camera(&mut self, yaw: f32, pitch: f32, zoom: f32) {
210        self.inner.set_camera(yaw, pitch, zoom);
211    }
212
213    /// Toggle the bounded portable directional shadow pass. When its VRAM reservation is refused,
214    /// the renderer keeps the unshadowed material path available.
215    pub fn set_sun_shadows_enabled(&mut self, enabled: bool) {
216        self.inner.set_shadows_enabled(enabled);
217    }
218
219    /// Sun-shadow resolution.
220    pub fn sun_shadow_resolution(&self) -> Option<u32> {
221        self.inner.shadow_resolution()
222    }
223
224    /// Enable the optional half-resolution depth/normal ambient-visibility pass when budget permits.
225    pub fn set_screen_space_ao_enabled(&mut self, enabled: bool) {
226        self.inner.set_screen_space_ao_enabled(enabled);
227    }
228
229    /// Set the world-space AO radius, indirect visibility strength, and normal-offset bias.
230    pub fn set_screen_space_ao(&mut self, radius: f32, strength: f32, bias: f32) {
231        self.inner.set_screen_space_ao(radius, strength, bias);
232    }
233
234    /// Sets screen-space-ao-sample-count.
235    pub fn set_screen_space_ao_sample_count(&mut self, samples: u32) {
236        self.inner.set_screen_space_ao_sample_count(samples);
237    }
238
239    /// `true` when SSAO is available.
240    pub fn screen_space_ao_available(&self) -> bool {
241        self.inner.screen_space_ao_available()
242    }
243
244    /// SSAO resolution.
245    pub fn screen_space_ao_resolution(&self) -> Option<(u32, u32)> {
246        self.inner.screen_space_ao_resolution()
247    }
248
249    /// Renders.
250    pub fn render(
251        &mut self,
252        time_seconds: f32,
253        telemetry: &crate::telemetry::SystemTelemetry,
254    ) -> Result<(), String> {
255        self.inner.render(time_seconds, &core_telemetry(telemetry))
256    }
257
258    /// Render a frame of `scene` into the active surface or offscreen target.
259    ///
260    /// Converts scene nodes to Tensor10D instances, compiles faces/edges into a colored mesh,
261    /// updates the camera orientation and distance, and executes the render pass.
262    pub fn render_scene_frame(
263        &mut self,
264        scene: &RenderScene,
265        width: u32,
266        height: u32,
267        time_seconds: f32,
268        telemetry: &crate::telemetry::SystemTelemetry,
269    ) -> Result<(), String> {
270        let tensors: Vec<Tensor10D> = scene.nodes.iter().map(node_tensor).collect();
271        if !tensors.is_empty() {
272            let mut bytes = vec![0u8; TensorBufferHeader::total_bytes(tensors.len())];
273            write_tensor_buffer(&tensors, &mut bytes).map_err(str::to_owned)?;
274            self.upload_tensor_buffer(&bytes)?;
275        }
276
277        let (positions, colors, indices) = scene_mesh(scene, width, height);
278        if !indices.is_empty() {
279            self.upload_mesh_colored(&positions, &colors, &indices);
280        }
281
282        let eye = scene.camera.position;
283        let target = scene.camera.target;
284        let dx = (eye[0] - target[0]) as f32;
285        let dy = (eye[1] - target[1]) as f32;
286        let dz = (eye[2] - target[2]) as f32;
287        let distance = (dx * dx + dy * dy + dz * dz).sqrt();
288        if distance.is_finite() && (0.35..=48.0).contains(&distance) {
289            self.set_camera(dx.atan2(dz), (dy / distance).asin(), distance);
290        }
291
292        self.render(time_seconds, telemetry)
293    }
294
295    /// Required RGBA8 bytes.
296    #[cfg(not(target_arch = "wasm32"))]
297    pub fn required_rgba8_bytes(&self) -> usize {
298        self.inner.required_rgba8_bytes()
299    }
300
301    /// Reads rgba8-into.
302    #[cfg(not(target_arch = "wasm32"))]
303    pub fn read_rgba8_into(&self, out: &mut [u8]) -> Result<usize, String> {
304        self.inner.read_rgba8_into(out)
305    }
306
307    /// Resizes.
308    pub fn resize(&mut self, width: u32, height: u32) {
309        if let Err(error) = self.inner.resize(width, height) {
310            log::warn!("volumetric renderer resize retained previous targets: {error}");
311        }
312    }
313
314    /// P9.3 — Queue an integer pick at pixel `(x, y)`. The result is available
315    /// after the next `render()` call via `poll_pick_readback()`.
316    pub fn queue_pick(&mut self, x: f32, y: f32) {
317        self.inner.queue_pick(x, y);
318    }
319
320    /// P9.3 — Poll for a completed GPU pick readback. Returns `Some(node_index)`
321    /// if the picking pass has completed, or `None` if still pending.
322    pub fn poll_pick_readback(&mut self) -> Option<u32> {
323        self.inner.poll_pick_readback()
324    }
325
326    /// Legacy planar CPU picker retained for callers using the Canvas2D
327    /// projection. The camera-aware WebGPU-equivalent oracle is exposed by
328    /// [`Self::cpu_pick_node_at_camera`].
329    pub fn cpu_pick_node_at(
330        tensor: &[u8],
331        canvas_w: f64,
332        canvas_h: f64,
333        pick_x: f64,
334        pick_y: f64,
335        yaw: f32,
336        standpoint: &qualia_core_db::render::telemetry::ObserverStandpoint,
337    ) -> Option<u32> {
338        qualia_core_db::render::navigation::cpu_pick_node_at(
339            tensor, canvas_w, canvas_h, pick_x, pick_y, yaw, standpoint,
340        )
341    }
342
343    /// CPU oracle for the Tensor10D WebGPU picking pass. Uses the same camera,
344    /// frame time, observer/PGA transform, clip range, pixel footprint and
345    /// depth ordering as the GPU projector.
346    pub fn cpu_pick_node_at_camera(
347        tensor: &[u8],
348        canvas_w: u32,
349        canvas_h: u32,
350        pick_x: f64,
351        pick_y: f64,
352        frame_time: f32,
353        camera: qualia_core_db::render::camera::CameraState,
354        standpoint: &qualia_core_db::render::telemetry::ObserverStandpoint,
355    ) -> Option<u32> {
356        qualia_core_db::render::navigation::cpu_pick_node_at_camera(
357            tensor, canvas_w, canvas_h, pick_x, pick_y, frame_time, camera, standpoint,
358        )
359    }
360
361    #[cfg(target_arch = "wasm32")]
362    /// P9.3 — Load a full `.10d` container asset (not just a mesh section).
363    /// Parses the section table, extracts the QuantizedMesh, uploads it to the
364    /// GPU, and returns `(vertex_count, triangle_count, provenance_mu)`.
365    ///
366    /// D3: when Tensor10DNodes are present, vertices are coloured by nearest-node
367    /// σ via `sigma_to_display_rgb` (vision recon / EMF paint fuel).
368    pub fn load_10d_asset(&mut self, bytes: &[u8]) -> Result<(u32, u32, f32), String> {
369        use qualia_core_db::container_10d::{
370            self, header::Container10dHeader, node_section::parse_node_header,
371        };
372        use qualia_core_db::render::spectral::sigma_to_display_rgb;
373        use qualia_core_db::tensor::Tensor10D;
374
375        let mut bytes_mut = bytes.to_vec();
376        let header =
377            Container10dHeader::parse(&bytes_mut).map_err(|e| format!("10d header: {e}"))?;
378        container_10d::verify_whole_file_crc32c(&mut bytes_mut)
379            .map_err(|e| format!("10d CRC: {e}"))?;
380        let descs = container_10d::parse_section_table(&bytes_mut, &header)
381            .map_err(|e| format!("10d section table: {e}"))?;
382
383        let mut mesh = None;
384        let mut material_payload = None;
385        let mut texture_coordinates_payload = None;
386        let mut provenance_mu: f32 = 0.0;
387        let mut nodes: Vec<Tensor10D> = Vec::new();
388
389        for desc in descs.iter() {
390            let st = container_10d::SectionType::from_u8(desc.section_type)
391                .ok_or_else(|| format!("10d: unknown section type {}", desc.section_type))?;
392            let off = desc.byte_offset as usize;
393            let len = desc.byte_length as usize;
394            let payload = &bytes_mut[off..off + len];
395
396            match st {
397                container_10d::SectionType::QuantizedMesh => {
398                    mesh = Some(
399                        container_10d::decode_mesh_section(payload)
400                            .map_err(|e| format!("10d mesh decode: {e}"))?,
401                    );
402                }
403                container_10d::SectionType::Tensor10DNodes => {
404                    if let Ok((nh, _)) = parse_node_header(payload) {
405                        let count = nh.node_count as usize;
406                        for i in 0..count {
407                            if let Ok(t) = container_10d::read_node(payload, i) {
408                                if i == 0 {
409                                    provenance_mu = t.mu;
410                                }
411                                nodes.push(t);
412                            }
413                        }
414                    } else if let Ok(t) = container_10d::read_node(payload, 0) {
415                        provenance_mu = t.mu;
416                        nodes.push(t);
417                    }
418                }
419                container_10d::SectionType::Materials => {
420                    material_payload = Some(payload);
421                }
422                container_10d::SectionType::TextureCoordinates => {
423                    texture_coordinates_payload = Some(payload);
424                }
425                _ => {}
426            }
427        }
428
429        let mesh = mesh.ok_or_else(|| "10d: no mesh section".to_string())?;
430        let tri_count = mesh.triangles.len() as u32;
431        let vert_count = mesh.positions.len() as u32;
432        let texture_coordinates_0 = if let Some(payload) = texture_coordinates_payload {
433            let mut coordinates = vec![[0.0f32; 2]; mesh.positions.len()];
434            let count = container_10d::decode_texture_coordinates_into(
435                payload,
436                mesh.positions.len(),
437                &mut coordinates,
438            )
439            .map_err(|error| format!("10d UV01 decode: {error}"))?;
440            if count != mesh.positions.len() {
441                return Err("10d UV01 vertex count does not match mesh".to_string());
442            }
443            Some(coordinates)
444        } else {
445            None
446        };
447
448        let mut indices = Vec::with_capacity(mesh.triangles.len() * 3);
449        for triangle in &mesh.triangles {
450            indices.extend_from_slice(triangle);
451        }
452
453        let colors: Vec<[f32; 4]> = if nodes.is_empty() {
454            Vec::new()
455        } else {
456            // Colour vertices by nearest node σ as an explicit observer projection. MAT1's
457            // multiplyVertexColor flag controls whether that projection tints the surface.
458            mesh.positions
459                .iter()
460                .map(|p| {
461                    let mut best = 0usize;
462                    let mut best_d = f32::INFINITY;
463                    for (i, n) in nodes.iter().enumerate() {
464                        let dx = p[0] - n.x;
465                        let dy = p[1] - n.y;
466                        let dz = p[2] - n.z;
467                        let d = dx * dx + dy * dy + dz * dz;
468                        if d < best_d {
469                            best_d = d;
470                            best = i;
471                        }
472                    }
473                    let (r, g, b) = sigma_to_display_rgb(nodes[best].sigma);
474                    [r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0, 1.0]
475                })
476                .collect()
477        };
478
479        if let Some(payload) = material_payload {
480            let (material_count, range_count) = container_10d::material_section_counts(payload)
481                .map_err(|error| format!("10d MAT1 header: {error}"))?;
482            if range_count > qualia_core_db::render::gpu::MAX_GPU_MATERIAL_DRAWS {
483                return Err("10d MAT1 draw count exceeds the active renderer cap".to_string());
484            }
485            let mut materials =
486                vec![container_10d::MaterialRecord::legacy_default(); material_count];
487            let mut ranges = vec![
488                container_10d::SubmeshRange {
489                    first_index: 0,
490                    index_count: 3,
491                    material_id: materials.first().map(|material| material.id).unwrap_or(1),
492                    semantic_id: 0,
493                };
494                range_count
495            ];
496            let index_count = u32::try_from(indices.len())
497                .map_err(|_| "10d mesh index count exceeds u32".to_string())?;
498            container_10d::decode_material_section_into(
499                payload,
500                index_count,
501                &mut materials,
502                &mut ranges,
503            )
504            .map_err(|error| format!("10d MAT1 decode: {error}"))?;
505            self.inner
506                .upload_mesh_colored_with_frames_and_materials_and_uv0(
507                    &mesh.positions,
508                    &colors,
509                    None,
510                    None,
511                    texture_coordinates_0.as_deref(),
512                    &indices,
513                    &materials,
514                    &ranges,
515                )
516                .map_err(|error| format!("10d MAT1 GPU upload: {error}"))?;
517        } else if let Some(coordinates) = texture_coordinates_0.as_deref() {
518            let material = container_10d::MaterialRecord::legacy_default();
519            let range = container_10d::SubmeshRange {
520                first_index: 0,
521                index_count: u32::try_from(indices.len())
522                    .map_err(|_| "10d mesh index count exceeds u32".to_string())?,
523                material_id: material.id,
524                semantic_id: 0,
525            };
526            self.inner
527                .upload_mesh_colored_with_frames_and_materials_and_uv0(
528                    &mesh.positions,
529                    &colors,
530                    None,
531                    None,
532                    Some(coordinates),
533                    &indices,
534                    &[material],
535                    &[range],
536                )
537                .map_err(|error| format!("10d UV0 GPU upload: {error}"))?;
538        } else if colors.is_empty() {
539            self.inner.upload_mesh(&mesh.positions, &indices);
540        } else {
541            self.inner
542                .upload_mesh_colored(&mesh.positions, &colors, &indices);
543        }
544
545        Ok((vert_count, tri_count, provenance_mu))
546    }
547
548    #[cfg(not(target_arch = "wasm32"))]
549    /// Native shared decode/upload path with the legacy Core compatibility profile.
550    pub fn load_10d_asset(&mut self, bytes: &[u8]) -> Result<(u32, u32, f32), String> {
551        self.load_10d_compat_asset(bytes)
552    }
553    /// P9.3 — Colour-by-field: map a scalar field value to a deterministic RGB
554    /// colour. The mapping is a simple linear interpolation across a fixed
555    /// colour ramp, ensuring the same field value produces the same colour on
556    /// both CPU and GPU paths.
557    pub fn colour_by_field(value: f32, min: f32, max: f32) -> [f32; 3] {
558        let t = if (max - min).abs() < f32::EPSILON {
559            0.5
560        } else {
561            ((value - min) / (max - min)).clamp(0.0, 1.0)
562        };
563        // 5-stop ramp: blue → cyan → green → yellow → red
564        let stops: [(f32, [f32; 3]); 5] = [
565            (0.00, [0.0, 0.0, 1.0]),
566            (0.25, [0.0, 1.0, 1.0]),
567            (0.50, [0.0, 1.0, 0.0]),
568            (0.75, [1.0, 1.0, 0.0]),
569            (1.00, [1.0, 0.0, 0.0]),
570        ];
571        for i in 0..4 {
572            if t <= stops[i + 1].0 {
573                let local = (t - stops[i].0) / (stops[i + 1].0 - stops[i].0);
574                let local = local.clamp(0.0, 1.0);
575                return [
576                    stops[i].1[0] + (stops[i + 1].1[0] - stops[i].1[0]) * local,
577                    stops[i].1[1] + (stops[i + 1].1[1] - stops[i].1[1]) * local,
578                    stops[i].1[2] + (stops[i + 1].1[2] - stops[i].1[2]) * local,
579                ];
580            }
581        }
582        stops[4].1
583    }
584
585    /// P9.3 — Temporal-scrub: filter tensor nodes to those within the
586    /// `[t_slice - t_window/2, t_slice + t_window/2]` time window. Returns
587    /// the indices of nodes in the window, byte-identical to a linear-scan
588    /// oracle.
589    pub fn temporal_scrub(tensor: &[u8], t_slice: f32, t_window: f32) -> Result<Vec<u32>, String> {
590        let count = qualia_core_db::tensor::buffer_export::tensor_node_count(tensor)
591            .map_err(|e| e.to_string())?;
592        let half = t_window * 0.5;
593        let lo = t_slice - half;
594        let hi = t_slice + half;
595        let mut result = Vec::new();
596        for i in 0..count {
597            let t = qualia_core_db::tensor::buffer_export::read_tensor_at(tensor, i)
598                .map_err(|e| e.to_string())?;
599            if t.t >= lo && t.t <= hi {
600                result.push(i as u32);
601            }
602        }
603        Ok(result)
604    }
605}
606
607/// Render the neutral SDK scene through the canonical depth-buffered projector and mesh pipeline.
608///
609/// Nodes become Tensor10D projector instances. Faces and edges become a triangulated depth-tested
610/// mesh. Conversion allocates only on this cold serde/IPC boundary; the renderer draw/readback path
611/// remains caller-buffered.
612#[cfg(not(target_arch = "wasm32"))]
613pub fn render_scene_rgba8_into(
614    scene: &RenderScene,
615    width: u32,
616    height: u32,
617    time_seconds: f32,
618    telemetry: &crate::telemetry::SystemTelemetry,
619    out: &mut [u8],
620) -> Result<usize, String> {
621    let mut renderer = VolumetricRenderer::new_offscreen(width, height, 50_000)?;
622    renderer.render_scene_frame(scene, width, height, time_seconds, telemetry)?;
623    renderer.read_rgba8_into(out)
624}
625
626/// PNG convenience bridge for native webviews. The render itself still uses caller-buffered core
627/// APIs; allocation here belongs to the explicit image-codec boundary.
628#[cfg(not(target_arch = "wasm32"))]
629pub fn render_scene_png(
630    scene: &RenderScene,
631    width: u32,
632    height: u32,
633    time_seconds: f32,
634    telemetry: &crate::telemetry::SystemTelemetry,
635) -> Result<Vec<u8>, String> {
636    use image::ImageEncoder;
637
638    let mut rgba = vec![0u8; width.max(1) as usize * height.max(1) as usize * 4];
639    render_scene_rgba8_into(
640        scene,
641        width.max(1),
642        height.max(1),
643        time_seconds,
644        telemetry,
645        &mut rgba,
646    )?;
647    let mut png = Vec::new();
648    image::codecs::png::PngEncoder::new(&mut png)
649        .write_image(
650            &rgba,
651            width.max(1),
652            height.max(1),
653            image::ExtendedColorType::Rgba8,
654        )
655        .map_err(|e| format!("PNG encode failed: {e}"))?;
656    Ok(png)
657}
658
659fn node_tensor(node: &crate::scene_contract::SceneNode) -> Tensor10D {
660    let t = node.tensor;
661    let tensor_has_position = t.x != 0.0 || t.y != 0.0 || t.z != 0.0;
662    let [x, y, z] = if tensor_has_position {
663        [t.x as f32, t.y as f32, t.z as f32]
664    } else {
665        scene_point_world(node.position)
666    };
667    Tensor10D::new(
668        t.q as f32,
669        t.v as f32,
670        t.w as f32,
671        x,
672        y,
673        z,
674        if t.t == 0.0 {
675            node.version as f32
676        } else {
677            t.t as f32
678        },
679        (t.alpha * node.alpha).clamp(0.0, 1.0) as f32,
680        t.mu as f32,
681        t.sigma as f32,
682    )
683}
684
685fn scene_mesh(
686    scene: &RenderScene,
687    width: u32,
688    height: u32,
689) -> (Vec<[f32; 3]>, Vec<[f32; 4]>, Vec<u32>) {
690    let mut positions = Vec::new();
691    let mut colors = Vec::new();
692    let mut indices = Vec::new();
693
694    for face in &scene.faces {
695        if face.vertices.len() < 3 {
696            continue;
697        }
698        let base = positions.len() as u32;
699        positions.extend(face.vertices.iter().copied().map(scene_point_world));
700        colors.extend(
701            std::iter::repeat(css_color_linear(&face.color, face.alpha)).take(face.vertices.len()),
702        );
703        for i in 1..face.vertices.len() - 1 {
704            indices.extend_from_slice(&[base, base + i as u32, base + i as u32 + 1]);
705        }
706    }
707
708    for edge in &scene.edges {
709        let from = scene_point_world(edge.from);
710        let to = scene_point_world(edge.to);
711        let dx = to[0] - from[0];
712        let dy = to[1] - from[1];
713        let length = (dx * dx + dy * dy).sqrt();
714        if length <= f32::EPSILON {
715            continue;
716        }
717        let pixel_scale = 2.0 / width.max(height).max(1) as f32;
718        let half = edge.width.max(1.0) as f32 * pixel_scale * 0.5;
719        let ox = -dy / length * half;
720        let oy = dx / length * half;
721        let base = positions.len() as u32;
722        positions.extend_from_slice(&[
723            [from[0] + ox, from[1] + oy, from[2]],
724            [from[0] - ox, from[1] - oy, from[2]],
725            [to[0] - ox, to[1] - oy, to[2]],
726            [to[0] + ox, to[1] + oy, to[2]],
727        ]);
728        colors.extend_from_slice(&[css_color_linear(&edge.color, edge.alpha); 4]);
729        indices.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]);
730    }
731
732    (positions, colors, indices)
733}
734
735#[inline]
736fn scene_point_world(point: ScenePoint) -> [f32; 3] {
737    [
738        (point.x as f32 - 0.5) * 2.0,
739        (0.5 - point.y as f32) * 2.0,
740        point.z as f32,
741    ]
742}
743
744fn css_color_linear(color: &str, alpha: f64) -> [f32; 4] {
745    let hex = color.strip_prefix('#').unwrap_or("");
746    let (r, g, b) = match hex.len() {
747        6 => (
748            u8::from_str_radix(&hex[0..2], 16).unwrap_or(128),
749            u8::from_str_radix(&hex[2..4], 16).unwrap_or(153),
750            u8::from_str_radix(&hex[4..6], 16).unwrap_or(209),
751        ),
752        3 => (
753            u8::from_str_radix(&hex[0..1], 16).unwrap_or(8) * 17,
754            u8::from_str_radix(&hex[1..2], 16).unwrap_or(9) * 17,
755            u8::from_str_radix(&hex[2..3], 16).unwrap_or(12) * 17,
756        ),
757        _ => (128, 153, 209),
758    };
759    let decode = |value: u8| {
760        let s = value as f32 / 255.0;
761        if s <= 0.04045 {
762            s / 12.92
763        } else {
764            ((s + 0.055) / 1.055).powf(2.4)
765        }
766    };
767    [
768        decode(r),
769        decode(g),
770        decode(b),
771        alpha.clamp(0.0, 1.0) as f32,
772    ]
773}
774
775fn core_telemetry(value: &crate::telemetry::SystemTelemetry) -> CoreTelemetry {
776    CoreTelemetry {
777        memory_pressure: value.memory_pressure,
778        network_ripple: value.network_ripple,
779        baking_crystallization: value.baking_crystallization,
780        logic_flashes: value.logic_flashes,
781        llm_heat: value.llm_heat,
782        quantum_activity: value.quantum_activity,
783        spectral_shift: value.spectral_shift,
784        temporal_pulse: value.temporal_pulse,
785        epistemic_density: value.epistemic_density,
786        manifold_pressure: value.manifold_pressure,
787        _padding: value._padding,
788    }
789}
790
791#[cfg(all(test, not(target_arch = "wasm32")))]
792#[path = "volumetric_tests.rs"]
793mod tests;