Skip to main content

qualia_core_db/render/gpu/
water.rs

1//! Persistent HMC water geometry and depth-owned transparent rendering.
2
3use super::{depth_stencil_state_read_only, PortalGpu};
4use crate::gpu_context::{global_vram_ledger, VramReservation, VramResourceClass};
5use crate::render::gpu::uniform_belt::UniformBelt;
6use crate::shaders::viewport::WATER_WGSL;
7use bytemuck::{Pod, Zeroable};
8use etalon::util::DeviceExt;
9
10pub(super) const MAX_WATER_VERTICES: usize = 1_048_576;
11pub(super) const MAX_WATER_INDICES: usize = 3_145_728;
12
13/// Water quality tiers are deliberately numeric because the value crosses the
14/// existing uniform ABI without adding another bind group or per-frame resource.
15pub(super) const WATER_QUALITY_LOWER: u32 = 0;
16pub(super) const WATER_QUALITY_BALANCED: u32 = 1;
17pub(super) const WATER_QUALITY_CINEMATIC: u32 = 2;
18
19#[repr(C)]
20#[derive(Clone, Copy, Pod, Zeroable)]
21struct WaterUniform {
22    colour_alpha: [f32; 4],
23    wave: [f32; 4],
24    quality: [f32; 4], // tier, reflection, foam, shore response
25    viewport: [f32; 4],
26}
27
28#[repr(C)]
29#[derive(Clone, Copy, Pod, Zeroable)]
30struct WaterVertex {
31    position: [f32; 3],
32    uv: [f32; 2],
33    shore_distance: f32,
34    shore_scale: f32,
35}
36
37pub(super) struct WaterGpu {
38    pipeline: etalon::RenderPipeline,
39    pipeline_hdr: Option<etalon::RenderPipeline>,
40    uniform_buf: etalon::Buffer,
41    uniform_bind: etalon::BindGroup,
42    uniform: WaterUniform,
43    vertex_buf: Option<etalon::Buffer>,
44    index_buf: Option<etalon::Buffer>,
45    index_count: u32,
46    geometry_key: Option<u64>,
47    geometry_bytes: u64,
48    geometry_generation: u64,
49    shoreline_edges: u32,
50    shoreline_evaluations: u64,
51    shoreline_working_bytes: u64,
52    _geometry_reservation: Option<VramReservation<'static>>,
53}
54
55fn geometry_key(positions: &[[f32; 3]], indices: &[u32]) -> u64 {
56    // FNV-1a is sufficient for the cache key: the upload path still validates
57    // every element, and a collision only costs a harmless skipped rebuild.
58    let mut key = 0xcbf29ce484222325u64;
59    for byte in bytemuck::cast_slice::<[f32; 3], u8>(positions)
60        .iter()
61        .chain(bytemuck::cast_slice::<u32, u8>(indices).iter())
62    {
63        key ^= u64::from(*byte);
64        key = key.wrapping_mul(0x100000001b3);
65    }
66    key ^ ((positions.len() as u64) << 32) ^ indices.len() as u64
67}
68
69fn geometry_admission(
70    positions: &[[f32; 3]],
71    indices: &[u32],
72    max_bytes: u64,
73) -> Result<(u64, u64), String> {
74    if positions.is_empty() || indices.is_empty() {
75        return Ok((0, 0));
76    }
77    if positions.len() > MAX_WATER_VERTICES
78        || indices.len() > MAX_WATER_INDICES
79        || indices.len() % 3 != 0
80        || indices
81            .iter()
82            .any(|&index| index as usize >= positions.len())
83        || positions
84            .iter()
85            .any(|position| position.iter().any(|value| !value.is_finite()))
86    {
87        return Err("HMC water geometry exceeds bounded or finite-input contract".into());
88    }
89    let bytes = (positions.len() as u64)
90        .checked_mul(std::mem::size_of::<WaterVertex>() as u64)
91        .and_then(|value| {
92            value
93                .checked_add((indices.len() as u64).checked_mul(std::mem::size_of::<u32>() as u64)?)
94        })
95        .ok_or_else(|| "HMC water geometry byte size overflow".to_string())?;
96    if bytes > max_bytes {
97        return Err(format!(
98            "HMC water geometry exceeds admission budget: {bytes} > {max_bytes} bytes"
99        ));
100    }
101    // Include caller geometry, shoreline scratch/attributes and packed GPU
102    // vertices in the cold upload pass, before allocating any of them.
103    let working = positions.len() as u64 * 56 + indices.len() as u64 * 12;
104    if working > 42 * 1024 * 1024 {
105        return Err("water upload pass exceeds 42 MiB execution budget".into());
106    }
107    Ok((bytes, geometry_key(positions, indices)))
108}
109
110fn colour_target(format: etalon::TextureFormat) -> etalon::ColorTargetState {
111    etalon::ColorTargetState {
112        format,
113        blend: Some(etalon::BlendState {
114            color: etalon::BlendComponent {
115                src_factor: etalon::BlendFactor::SrcAlpha,
116                dst_factor: etalon::BlendFactor::OneMinusSrcAlpha,
117                operation: etalon::BlendOperation::Add,
118            },
119            alpha: etalon::BlendComponent {
120                src_factor: etalon::BlendFactor::One,
121                dst_factor: etalon::BlendFactor::OneMinusSrcAlpha,
122                operation: etalon::BlendOperation::Add,
123            },
124        }),
125        write_mask: etalon::ColorWrites::ALL,
126    }
127}
128
129impl WaterGpu {
130    /// Creates with the given state.
131    pub(super) fn new(
132        device: &etalon::Device,
133        mesh_frame_layout: &etalon::BindGroupLayout,
134        mesh_model_layout: &etalon::BindGroupLayout,
135        format: etalon::TextureFormat,
136        hdr_supported: bool,
137    ) -> Self {
138        let uniform = WaterUniform {
139            colour_alpha: [0.08, 0.34, 0.52, 0.72],
140            wave: [0.0, 0.025, 2.0, 0.08],
141            quality: [WATER_QUALITY_BALANCED as f32, 0.35, 0.60, 0.70],
142            viewport: [1.0, 1.0, 0.0005, 0.0],
143        };
144        let uniform_buf = device.create_buffer_init(&etalon::util::BufferInitDescriptor {
145            label: Some("qualia-water-frame-uniform"),
146            contents: bytemuck::bytes_of(&uniform),
147            usage: etalon::BufferUsages::UNIFORM | etalon::BufferUsages::COPY_DST,
148        });
149        let layout = device.create_bind_group_layout(&etalon::BindGroupLayoutDescriptor {
150            label: Some("qualia-water-uniform-layout"),
151            entries: &[etalon::BindGroupLayoutEntry {
152                binding: 0,
153                visibility: etalon::ShaderStages::VERTEX_FRAGMENT,
154                ty: etalon::BindingType::Buffer {
155                    ty: etalon::BufferBindingType::Uniform,
156                    has_dynamic_offset: false,
157                    min_binding_size: std::num::NonZeroU64::new(
158                        std::mem::size_of::<WaterUniform>() as u64,
159                    ),
160                },
161                count: None,
162            }],
163        });
164        let shader = device.create_shader_module(etalon::ShaderModuleDescriptor {
165            label: Some("qualia-water"),
166            source: etalon::ShaderSource::Wgsl(WATER_WGSL.into()),
167        });
168        let uniform_bind = device.create_bind_group(&etalon::BindGroupDescriptor {
169            label: Some("qualia-water-uniform-bind"),
170            layout: &layout,
171            entries: &[etalon::BindGroupEntry {
172                binding: 0,
173                resource: uniform_buf.as_entire_binding(),
174            }],
175        });
176        let pipeline_layout = device.create_pipeline_layout(&etalon::PipelineLayoutDescriptor {
177            label: Some("qualia-water-pipeline-layout"),
178            bind_group_layouts: &[
179                Some(mesh_frame_layout),
180                Some(mesh_model_layout),
181                Some(&layout),
182            ],
183            immediate_size: 0,
184        });
185        let vertex_layout = etalon::VertexBufferLayout {
186            array_stride: std::mem::size_of::<WaterVertex>() as u64,
187            step_mode: etalon::VertexStepMode::Vertex,
188            attributes: &[
189                etalon::VertexAttribute {
190                    format: etalon::VertexFormat::Float32x3,
191                    offset: 0,
192                    shader_location: 0,
193                },
194                etalon::VertexAttribute {
195                    format: etalon::VertexFormat::Float32x2,
196                    offset: 12,
197                    shader_location: 1,
198                },
199                etalon::VertexAttribute {
200                    format: etalon::VertexFormat::Float32x2,
201                    offset: 20,
202                    shader_location: 2,
203                },
204            ],
205        };
206        let pipeline = |target_format| {
207            device.create_render_pipeline(&etalon::RenderPipelineDescriptor {
208                label: Some("qualia-water-pipeline"),
209                layout: Some(&pipeline_layout),
210                vertex: etalon::VertexState {
211                    module: &shader,
212                    entry_point: Some("vertex_main"),
213                    compilation_options: Default::default(),
214                    buffers: &[Some(vertex_layout.clone())],
215                },
216                fragment: Some(etalon::FragmentState {
217                    module: &shader,
218                    entry_point: Some("fragment_main"),
219                    compilation_options: Default::default(),
220                    targets: &[Some(colour_target(target_format))],
221                }),
222                primitive: etalon::PrimitiveState {
223                    topology: etalon::PrimitiveTopology::TriangleList,
224                    cull_mode: None,
225                    ..Default::default()
226                },
227                depth_stencil: Some(depth_stencil_state_read_only()),
228                multisample: etalon::MultisampleState::default(),
229                multiview_mask: None,
230                cache: None,
231            })
232        };
233        let pipeline_hdr = hdr_supported.then(|| pipeline(etalon::TextureFormat::Rgba16Float));
234        Self {
235            pipeline: pipeline(format),
236            pipeline_hdr,
237            uniform_buf,
238            uniform_bind,
239            uniform,
240            vertex_buf: None,
241            index_buf: None,
242            index_count: 0,
243            geometry_key: None,
244            geometry_bytes: 0,
245            geometry_generation: 0,
246            shoreline_edges: 0,
247            shoreline_evaluations: 0,
248            shoreline_working_bytes: 0,
249            _geometry_reservation: None,
250        }
251    }
252
253    /// Sets `viewport`.
254    pub(super) fn set_viewport(&mut self, width: u32, height: u32) {
255        self.uniform.viewport[0] = width.max(1) as f32;
256        self.uniform.viewport[1] = height.max(1) as f32;
257    }
258
259    /// `true` when `geometry` present.
260    pub(super) fn has_geometry(&self) -> bool {
261        self.index_count > 0
262    }
263
264    /// Sets `time`.
265    pub(super) fn set_time(&mut self, time: f32) {
266        self.uniform.wave[0] = time;
267    }
268
269    /// Writes `uniform`.
270    pub(super) fn write_uniform(
271        &self,
272        belt: &mut UniformBelt,
273        encoder: &mut etalon::CommandEncoder,
274    ) {
275        belt.write_and_unmap(bytemuck::bytes_of(&self.uniform));
276        belt.record_copy(encoder, &self.uniform_buf, 0);
277        // The caller advances the shared belt after this copy, keeping all
278        // frame-owned writes in one preallocated ring.
279    }
280
281    /// `replace_geometry`.
282    pub(super) fn replace_geometry(
283        &mut self,
284        device: &etalon::Device,
285        positions: &[[f32; 3]],
286        indices: &[u32],
287    ) -> Result<(), String> {
288        self.replace_geometry_with_budget(device, positions, indices, u64::MAX)
289    }
290
291    /// `replace_geometry_with_budget`.
292    pub(super) fn replace_geometry_with_budget(
293        &mut self,
294        device: &etalon::Device,
295        positions: &[[f32; 3]],
296        indices: &[u32],
297        max_bytes: u64,
298    ) -> Result<(), String> {
299        if positions.is_empty() || indices.is_empty() {
300            self.clear_geometry();
301            return Ok(());
302        }
303        let (bytes, key) = geometry_admission(positions, indices, max_bytes)?;
304        if self.geometry_key == Some(key)
305            && self.index_count == u32::try_from(indices.len()).unwrap_or(u32::MAX)
306        {
307            return Ok(());
308        }
309        let mut min = [f32::INFINITY; 2];
310        let mut max = [f32::NEG_INFINITY; 2];
311        for position in positions {
312            min[0] = min[0].min(position[0]);
313            min[1] = min[1].min(position[2]);
314            max[0] = max[0].max(position[0]);
315            max[1] = max[1].max(position[2]);
316        }
317        let span = [
318            (max[0] - min[0]).max(f32::EPSILON),
319            (max[1] - min[1]).max(f32::EPSILON),
320        ];
321        let mut shore = vec![0.0; positions.len()];
322        let mut edges = vec![0; indices.len() + positions.len()];
323        let mut shore_scale = vec![0.0; positions.len()];
324        use crate::render::water_surface::{
325            shore_distance_accelerated_into, shore_topology_into, spatial_working_bytes,
326            ShoreSpatialScratch,
327        };
328        use etalon_render::water_surface::{Aabb, BvhNode, Point3};
329        let topology = shore_topology_into(positions, indices, &mut edges)
330            .map_err(|error| format!("water shoreline topology: {error:?}"))?;
331        let boundary = topology.boundary_edges();
332        let node_capacity = boundary * 2 - 1;
333        let working = positions.len() as u64 * 56
334            + indices.len() as u64 * 12
335            + spatial_working_bytes(boundary)
336                .ok_or_else(|| "water spatial budget overflow".to_owned())? as u64;
337        if working > 42 * 1024 * 1024 {
338            return Err("water spatial upload pass exceeds 42 MiB".into());
339        }
340        let zero = Aabb::new(Point3::new(0.0, 0.0, 0.0), Point3::new(0.0, 0.0, 0.0));
341        let mut bounds = vec![zero; boundary];
342        let mut nodes = vec![BvhNode::default(); node_capacity];
343        let mut order = vec![0; boundary];
344        let mut morton = vec![0; boundary];
345        let mut sorting = vec![0; boundary];
346        let mut components = vec![0; node_capacity];
347        let shoreline = shore_distance_accelerated_into(
348            positions,
349            &topology,
350            &mut shore,
351            &mut shore_scale,
352            ShoreSpatialScratch {
353                bounds: &mut bounds,
354                nodes: &mut nodes,
355                primitive_order: &mut order,
356                morton: &mut morton,
357                sort_order: &mut sorting,
358                node_components: &mut components,
359            },
360        )
361        .map_err(|error| format!("water spatial shoreline: {error:?}"))?;
362        let vertices: Vec<WaterVertex> = positions
363            .iter()
364            .zip(shore.iter().zip(&shore_scale))
365            .map(|(position, (shore, shore_scale))| WaterVertex {
366                position: *position,
367                uv: [
368                    (position[0] - min[0]) / span[0],
369                    (position[2] - min[1]) / span[1],
370                ],
371                shore_distance: *shore,
372                shore_scale: *shore_scale,
373            })
374            .collect();
375        let reservation = global_vram_ledger()
376            .try_reserve_graphics(VramResourceClass::Geometry, bytes)
377            .map_err(|error| format!("HMC water geometry admission failed: {error}"))?;
378        let vertex_buf = device.create_buffer_init(&etalon::util::BufferInitDescriptor {
379            label: Some("qualia-water-vertices"),
380            contents: bytemuck::cast_slice(&vertices),
381            usage: etalon::BufferUsages::VERTEX,
382        });
383        let index_buf = device.create_buffer_init(&etalon::util::BufferInitDescriptor {
384            label: Some("qualia-water-indices"),
385            contents: bytemuck::cast_slice(indices),
386            usage: etalon::BufferUsages::INDEX,
387        });
388        self.vertex_buf = Some(vertex_buf);
389        self.uniform.wave[3] = (shoreline.max_distance * 0.22).clamp(0.0001, 0.008);
390        self.uniform.viewport[3] = shoreline.max_distance;
391        self.index_buf = Some(index_buf);
392        self.index_count =
393            u32::try_from(indices.len()).map_err(|_| "water index count overflow")?;
394        self.geometry_key = Some(key);
395        self.geometry_bytes = bytes;
396        self.shoreline_edges = shoreline.boundary_edges as u32;
397        self.shoreline_evaluations = shoreline.segment_evaluations;
398        self.shoreline_working_bytes = working;
399        self.geometry_generation = self.geometry_generation.wrapping_add(1);
400        self._geometry_reservation = Some(reservation);
401        Ok(())
402    }
403
404    fn clear_geometry(&mut self) {
405        self.vertex_buf = None;
406        self.index_buf = None;
407        self.index_count = 0;
408        self.geometry_key = None;
409        self.geometry_bytes = 0;
410        self.shoreline_edges = 0;
411        self.shoreline_evaluations = 0;
412        self.shoreline_working_bytes = 0;
413        self.geometry_generation = self.geometry_generation.wrapping_add(1);
414        self._geometry_reservation = None;
415    }
416
417    /// `record`.
418    pub(super) fn record<'a>(
419        &'a self,
420        pass: &mut etalon::RenderPass<'a>,
421        mesh_frame_bind: &'a etalon::BindGroup,
422        mesh_model_bind: &'a etalon::BindGroup,
423        hdr: bool,
424    ) {
425        let (Some(vertex_buf), Some(index_buf)) =
426            (self.vertex_buf.as_ref(), self.index_buf.as_ref())
427        else {
428            return;
429        };
430        pass.set_pipeline(if hdr {
431            self.pipeline_hdr.as_ref().unwrap_or(&self.pipeline)
432        } else {
433            &self.pipeline
434        });
435        pass.set_bind_group(0, mesh_frame_bind, &[]);
436        pass.set_bind_group(1, mesh_model_bind, &[]);
437        pass.set_bind_group(2, &self.uniform_bind, &[]);
438        pass.set_vertex_buffer(0, vertex_buf.slice(..));
439        pass.set_index_buffer(index_buf.slice(..), etalon::IndexFormat::Uint32);
440        pass.draw_indexed(0..self.index_count, 0, 0..1);
441    }
442}
443
444impl PortalGpu {
445    /// Uploads water mesh buffers.
446    pub fn upload_water_geometry(
447        &mut self,
448        positions: &[[f32; 3]],
449        indices: &[u32],
450    ) -> Result<(), String> {
451        self.water
452            .replace_geometry(&self.device, positions, indices)
453    }
454
455    /// Upload persistent water geometry with an explicit admission ceiling.
456    /// The previous geometry remains live if validation or budget admission fails.
457    pub fn upload_water_geometry_with_budget(
458        &mut self,
459        positions: &[[f32; 3]],
460        indices: &[u32],
461        max_bytes: u64,
462    ) -> Result<(), String> {
463        self.water
464            .replace_geometry_with_budget(&self.device, positions, indices, max_bytes)
465    }
466
467    /// Drops water geometry.
468    pub fn clear_water_geometry(&mut self) {
469        let _ = self.water.replace_geometry(&self.device, &[], &[]);
470    }
471
472    /// Sets the water surface parameters.
473    pub fn set_water_surface(
474        &mut self,
475        colour: [f32; 3],
476        alpha: f32,
477        wave_amplitude: f32,
478        wave_frequency: f32,
479    ) {
480        self.water.uniform.colour_alpha = [
481            if colour[0].is_finite() {
482                colour[0].max(0.0)
483            } else {
484                0.0
485            },
486            if colour[1].is_finite() {
487                colour[1].max(0.0)
488            } else {
489                0.0
490            },
491            if colour[2].is_finite() {
492                colour[2].max(0.0)
493            } else {
494                0.0
495            },
496            if alpha.is_finite() {
497                alpha.clamp(0.0, 1.0)
498            } else {
499                0.0
500            },
501        ];
502        self.water.uniform.wave[1] = if wave_amplitude.is_finite() {
503            wave_amplitude.max(0.0)
504        } else {
505            0.0
506        };
507        self.water.uniform.wave[2] = if wave_frequency.is_finite() {
508            wave_frequency.max(0.0)
509        } else {
510            0.0
511        };
512    }
513
514    /// Select bounded water shading without allocating or rebuilding resources.
515    pub fn set_water_quality(&mut self, tier: u32) {
516        let (tier, reflection, foam, shore) = match tier {
517            WATER_QUALITY_CINEMATIC => (WATER_QUALITY_CINEMATIC, 0.55, 0.85, 1.0),
518            WATER_QUALITY_BALANCED => (WATER_QUALITY_BALANCED, 0.35, 0.60, 0.70),
519            _ => (WATER_QUALITY_LOWER, 0.0, 0.25, 0.35),
520        };
521        self.water.uniform.quality = [tier as f32, reflection, foam, shore];
522    }
523
524    #[allow(dead_code)]
525    /// `PortalGpu::water_geometry_state`.
526    pub fn water_geometry_state(&self) -> (u64, u64, u32) {
527        (
528            self.water.geometry_generation,
529            self.water.geometry_bytes,
530            self.water.index_count / 3,
531        )
532    }
533    /// Shoreline state `(count, lo, hi)`.
534    pub fn water_shoreline_state(&self) -> (u32, u64, u64) {
535        (
536            self.water.shoreline_edges,
537            self.water.shoreline_evaluations,
538            self.water.shoreline_working_bytes,
539        )
540    }
541}
542
543#[cfg(test)]
544mod tests {
545    use super::{geometry_admission, geometry_key, WATER_QUALITY_BALANCED, WATER_QUALITY_LOWER};
546
547    #[test]
548    fn finite_geometry_is_admitted_and_keyed_deterministically() {
549        let positions = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]];
550        let indices = [0, 1, 2];
551        let (bytes, key) = geometry_admission(&positions, &indices, 1024).unwrap();
552        assert_eq!(
553            bytes,
554            3 * std::mem::size_of::<super::WaterVertex>() as u64 + 12
555        );
556        assert_eq!(key, geometry_key(&positions, &indices));
557    }
558
559    #[test]
560    fn invalid_geometry_fails_before_gpu_admission() {
561        let positions = [[0.0, f32::NAN, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]];
562        assert!(geometry_admission(&positions, &[0, 1, 2], 1024).is_err());
563        assert!(geometry_admission(&[[0.0, 0.0, 0.0]], &[0, 1, 0], 1024).is_err());
564    }
565
566    #[test]
567    fn quality_tier_values_remain_explicit_lower_and_balanced() {
568        assert_eq!(WATER_QUALITY_LOWER, 0);
569        assert_eq!(WATER_QUALITY_BALANCED, 1);
570    }
571}