Skip to main content

qualia_core_db/render/gpu/
mesh_slab.rs

1//! Semantic procedural header adapter and universe admission for canonical slab residency.
2use crate::container_10d::procedural_synthesis::{ProceduralSynthesisHeader, MAGIC_PROC};
3use crate::gpu_context::{global_vram_ledger, VramReservation, VramResourceClass};
4use bytemuck::{Pod, Zeroable};
5pub use etalon_render::mesh_slab::{
6    AssetRepresentationKind, MeshSlabArenaDescriptor, MeshSlabVertex, ResidentAssetEntry,
7    SkinAttrVertex, SlabRange, SlabRangeAllocator, SubmeshSlice, INVALID_HEADER_SLOT,
8    MAX_SLAB_PROC_HEADERS, MAX_SLAB_RESIDENT_ASSETS, REP_KIND_HOLOGRAPHIC_SDF_PROXY,
9    REP_KIND_MESH_BREP, REP_KIND_OCTAHEDRAL_IMPOSTOR, REP_KIND_SGGX_CANOPY, REP_KIND_SURFEL_CLOUD,
10};
11/// 64-byte GPU storage representation of `.10d` `MAGIC_PROC` `ProceduralSynthesisHeader`.
12///
13/// Uses 32-bit words for header fields so WGSL shaders can read it directly without `u64`/`u16`
14/// extension requirements while remaining byte-for-byte compatible with `ProceduralSynthesisHeader`.
15#[repr(C)]
16#[derive(Clone, Copy, Debug, PartialEq, Pod, Zeroable)]
17pub struct ProceduralSynthesisGpu {
18    pub magic_u32: u32,
19    /// Low 16 bits = `version`, high 16 bits = `flags` (`FLAG_CELLULAR_VORONOI`, `FLAG_PGA_MOTOR_DYNAMICS`, etc.).
20    pub version_and_flags: u32,
21    pub seed_lo: u32,
22    pub seed_hi: u32,
23    pub voronoi_frequency: f32,
24    pub voronoi_jitter: f32,
25    pub fillet_blend_radius: f32,
26    pub fillet_threshold: f32,
27    pub allometry_exponent_k: f32,
28    pub allometry_base_b: f32,
29    pub spiral_growth_rate_k: f32,
30    pub spiral_initial_radius_a: f32,
31    pub motor_frequency_hz: f32,
32    pub motor_damping_ratio: f32,
33    pub critical_stress_threshold: f32,
34    pub reserved_f32: f32,
35}
36
37const _: [(); 64] = [(); std::mem::size_of::<ProceduralSynthesisGpu>()];
38
39impl Default for ProceduralSynthesisGpu {
40    fn default() -> Self {
41        bytemuck::Zeroable::zeroed()
42    }
43}
44
45impl ProceduralSynthesisGpu {
46    /// Converts a `.10d` `ProceduralSynthesisHeader` into its 64-byte GPU storage representation.
47    #[inline]
48    pub const fn from_header(header: &ProceduralSynthesisHeader) -> Self {
49        let magic_u32 = u32::from_le_bytes(header.magic);
50        let version_and_flags = (header.version as u32) | ((header.flags as u32) << 16);
51        let seed_lo = header.seed as u32;
52        let seed_hi = (header.seed >> 32) as u32;
53        Self {
54            magic_u32,
55            version_and_flags,
56            seed_lo,
57            seed_hi,
58            voronoi_frequency: header.voronoi_frequency,
59            voronoi_jitter: header.voronoi_jitter,
60            fillet_blend_radius: header.fillet_blend_radius,
61            fillet_threshold: header.fillet_threshold,
62            allometry_exponent_k: header.allometry_exponent_k,
63            allometry_base_b: header.allometry_base_b,
64            spiral_growth_rate_k: header.spiral_growth_rate_k,
65            spiral_initial_radius_a: header.spiral_initial_radius_a,
66            motor_frequency_hz: header.motor_frequency_hz,
67            motor_damping_ratio: header.motor_damping_ratio,
68            critical_stress_threshold: header.critical_stress_threshold,
69            reserved_f32: header.reserved_f32,
70        }
71    }
72
73    /// Reconstructs the CPU `ProceduralSynthesisHeader`.
74    #[inline]
75    pub const fn to_header(self) -> ProceduralSynthesisHeader {
76        ProceduralSynthesisHeader {
77            magic: self.magic_u32.to_le_bytes(),
78            version: (self.version_and_flags & 0xFFFF) as u16,
79            flags: (self.version_and_flags >> 16) as u16,
80            seed: (self.seed_lo as u64) | ((self.seed_hi as u64) << 32),
81            voronoi_frequency: self.voronoi_frequency,
82            voronoi_jitter: self.voronoi_jitter,
83            fillet_blend_radius: self.fillet_blend_radius,
84            fillet_threshold: self.fillet_threshold,
85            allometry_exponent_k: self.allometry_exponent_k,
86            allometry_base_b: self.allometry_base_b,
87            spiral_growth_rate_k: self.spiral_growth_rate_k,
88            spiral_initial_radius_a: self.spiral_initial_radius_a,
89            motor_frequency_hz: self.motor_frequency_hz,
90            motor_damping_ratio: self.motor_damping_ratio,
91            critical_stress_threshold: self.critical_stress_threshold,
92            reserved_f32: self.reserved_f32,
93        }
94    }
95
96    /// Returns the 16-bit `PROC1` synthesis recipe flags.
97    #[inline]
98    pub const fn flags(&self) -> u16 {
99        (self.version_and_flags >> 16) as u16
100    }
101
102    /// Returns `true` when `magic_u32` matches `MAGIC_PROC`.
103    #[inline]
104    pub const fn is_valid(&self) -> bool {
105        let m = self.magic_u32.to_le_bytes();
106        m[0] == MAGIC_PROC[0]
107            && m[1] == MAGIC_PROC[1]
108            && m[2] == MAGIC_PROC[2]
109            && m[3] == MAGIC_PROC[3]
110    }
111}
112
113pub struct MeshSlabArenaGpu(
114    etalon_render::mesh_slab::MeshSlabArenaGpu<VramReservation<'static>, ProceduralSynthesisGpu>,
115);
116impl std::ops::Deref for MeshSlabArenaGpu {
117    type Target = etalon_render::mesh_slab::MeshSlabArenaGpu<
118        VramReservation<'static>,
119        ProceduralSynthesisGpu,
120    >;
121    fn deref(&self) -> &Self::Target {
122        &self.0
123    }
124}
125impl std::ops::DerefMut for MeshSlabArenaGpu {
126    fn deref_mut(&mut self) -> &mut Self::Target {
127        &mut self.0
128    }
129}
130impl MeshSlabArenaGpu {
131    pub fn required_vram_bytes(desc: MeshSlabArenaDescriptor) -> Option<u64> {
132        etalon_render::mesh_slab::MeshSlabArenaGpu::<VramReservation<'static>,ProceduralSynthesisGpu>::required_vram_bytes(desc)
133    }
134    pub fn try_new(device: &etalon::Device, desc: MeshSlabArenaDescriptor) -> Option<Self> {
135        etalon_render::mesh_slab::MeshSlabArenaGpu::try_new(device, desc, |bytes| {
136            global_vram_ledger()
137                .try_reserve_graphics(VramResourceClass::Geometry, bytes)
138                .ok()
139        })
140        .map(Self)
141    }
142    pub fn register_proc_header(
143        &mut self,
144        queue: &etalon::Queue,
145        header: &ProceduralSynthesisHeader,
146    ) -> Option<u16> {
147        self.0
148            .register_proc_header(queue, &ProceduralSynthesisGpu::from_header(header))
149    }
150}
151#[cfg(test)]
152mod tests {
153    use super::*;
154    use crate::container_10d::procedural_synthesis::{
155        FLAG_CELLULAR_VORONOI, FLAG_PGA_MOTOR_DYNAMICS,
156    };
157
158    #[test]
159    fn slab_range_allocator_allocates_aligns_and_coalesces_zero_heap() {
160        let mut alloc = SlabRangeAllocator::<16>::new(1024);
161        assert_eq!(alloc.capacity(), 1024);
162        assert_eq!(alloc.free_remaining(), 1024);
163        assert_eq!(alloc.free_range_count(), 1);
164
165        let a = alloc.allocate(100, 1).expect("alloc a");
166        let b = alloc.allocate(200, 16).expect("alloc b aligned 16");
167        let c = alloc.allocate(50, 1).expect("alloc c");
168        assert_eq!(a, 0);
169        assert_eq!(b % 16, 0);
170        assert!(b >= 100);
171        assert_eq!(c, b + 200);
172
173        // Free out of order and verify bidirectional coalescing restores a single contiguous span
174        assert!(alloc.free(b, 200));
175        assert!(alloc.free(a, 100));
176        assert!(alloc.free(c, 50));
177        assert_eq!(alloc.used(), 0);
178        assert_eq!(alloc.free_remaining(), 1024);
179        assert_eq!(alloc.free_range_count(), 1);
180    }
181
182    #[test]
183    fn procedural_synthesis_gpu_mirrors_header_in_64_bytes() {
184        let header = ProceduralSynthesisHeader {
185            magic: MAGIC_PROC,
186            version: 1,
187            flags: (FLAG_CELLULAR_VORONOI | FLAG_PGA_MOTOR_DYNAMICS) as u16,
188            seed: 0xDEAD_BEEF_CAFE_BABEu64,
189            voronoi_frequency: 24.0,
190            voronoi_jitter: 0.9,
191            fillet_blend_radius: 0.25,
192            fillet_threshold: 0.05,
193            allometry_exponent_k: 1.5,
194            allometry_base_b: 0.8,
195            spiral_growth_rate_k: 0.22,
196            spiral_initial_radius_a: 0.15,
197            motor_frequency_hz: 1.8,
198            motor_damping_ratio: 0.05,
199            critical_stress_threshold: 60.0,
200            reserved_f32: 0.0,
201        };
202        let gpu = ProceduralSynthesisGpu::from_header(&header);
203        assert_eq!(std::mem::size_of::<ProceduralSynthesisGpu>(), 64);
204        assert!(gpu.is_valid());
205        assert_eq!(
206            gpu.flags(),
207            (FLAG_CELLULAR_VORONOI | FLAG_PGA_MOTOR_DYNAMICS) as u16
208        );
209        assert_eq!(gpu.to_header(), header);
210    }
211}