Skip to main content

spatialrust_gpu/
gpu_frame.rs

1//! GPU-resident spatial frame ownership and chained execution.
2
3use spatialrust_core::{
4    PointSchema, SpatialError, SpatialResult, SpatialTensor, TransferDirection, TransferStats,
5};
6
7use crate::aoso_staging::runtime_device_key;
8use crate::{
9    reduce_voxel_attributes_aoso_chunks, upload_spatial_tensor_xyz_chunks,
10    AoSoAAttributeAggregation, AoSoAAttributeReduction, GpuAoSoAttributeChunk, GpuAoSoNormals,
11    GpuAoSoRadiusGrid, GpuAoSoXyzBuffer, GpuVoxelSegments, WgpuRuntime,
12};
13
14/// GPU frame capabilities available to downstream algorithms.
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16pub enum GpuFrameCapability {
17    /// Interleaved XYZ positions.
18    Positions,
19    /// Per-point normals and curvature.
20    Normals,
21    /// Interleaved point attributes.
22    Attributes,
23    /// Voxel partition metadata.
24    VoxelSegments,
25    /// Sparse uniform radius grid.
26    RadiusGrid,
27}
28
29/// Transfer and logical-stage receipt for one GPU frame.
30///
31/// Counts point/attribute payload copies and scalar metadata readbacks performed
32/// by frame methods, including construction. Kernel parameter uniforms and
33/// shader storage accesses are excluded. Transfers performed outside frame
34/// methods (for example, uploads before attaching attributes or direct buffer
35/// readbacks) remain the caller's responsibility.
36#[derive(Clone, Debug, Default, PartialEq, Eq)]
37pub struct GpuExecutionReceipt {
38    transfers: TransferStats,
39    stages: Vec<&'static str>,
40}
41
42impl GpuExecutionReceipt {
43    /// Returns the common transfer accounting for this execution.
44    #[must_use]
45    pub const fn transfer_stats(&self) -> TransferStats {
46        self.transfers
47    }
48
49    /// Returns bytes uploaded from host memory.
50    #[must_use]
51    pub const fn host_to_device_bytes(&self) -> u64 {
52        self.transfers.host_to_device_bytes()
53    }
54
55    /// Returns bytes copied between GPU buffers.
56    #[must_use]
57    pub const fn gpu_to_gpu_bytes(&self) -> u64 {
58        self.transfers.device_to_device_bytes()
59    }
60
61    /// Returns payload and scalar metadata bytes read back to host memory.
62    #[must_use]
63    pub const fn device_to_host_bytes(&self) -> u64 {
64        self.transfers.device_to_host_bytes()
65    }
66
67    /// Returns the logical GPU stages recorded by the high-level pipeline.
68    #[must_use]
69    pub fn stages(&self) -> &[&'static str] {
70        &self.stages
71    }
72}
73
74/// Owned GPU-resident point frame with explicit schema and device identity.
75pub struct GpuSpatialFrame {
76    schema: PointSchema,
77    device_key: usize,
78    positions: GpuAoSoXyzBuffer,
79    normals: Option<GpuAoSoNormals>,
80    attributes: Vec<GpuAoSoAttributeChunk>,
81    voxel_segments: Option<GpuVoxelSegments>,
82    radius_grid: Option<GpuAoSoRadiusGrid>,
83    receipt: GpuExecutionReceipt,
84}
85
86impl GpuSpatialFrame {
87    /// Creates a frame owning interleaved positions on `runtime`.
88    pub fn new(
89        runtime: &WgpuRuntime,
90        schema: PointSchema,
91        positions: GpuAoSoXyzBuffer,
92    ) -> SpatialResult<Self> {
93        let device_key = runtime_device_key(runtime);
94        if positions.device_key() != device_key {
95            return Err(SpatialError::InvalidArgument(
96                "position buffer belongs to a different runtime device".to_owned(),
97            ));
98        }
99        Ok(Self {
100            schema,
101            device_key,
102            positions,
103            normals: None,
104            attributes: Vec::new(),
105            voxel_segments: None,
106            radius_grid: None,
107            receipt: GpuExecutionReceipt::default(),
108        })
109    }
110
111    /// Returns the source point schema.
112    #[must_use]
113    pub const fn schema(&self) -> &PointSchema {
114        &self.schema
115    }
116
117    /// Returns the number of source points.
118    #[must_use]
119    pub const fn point_count(&self) -> usize {
120        self.positions.point_count()
121    }
122
123    /// Returns retained interleaved positions.
124    #[must_use]
125    pub const fn positions(&self) -> &GpuAoSoXyzBuffer {
126        &self.positions
127    }
128
129    /// Returns retained normals when attached.
130    #[must_use]
131    pub const fn normals(&self) -> Option<&GpuAoSoNormals> {
132        self.normals.as_ref()
133    }
134
135    /// Returns retained voxel segments when attached.
136    #[must_use]
137    pub const fn voxel_segments(&self) -> Option<&GpuVoxelSegments> {
138        self.voxel_segments.as_ref()
139    }
140
141    /// Returns retained radius grid when attached.
142    #[must_use]
143    pub const fn radius_grid(&self) -> Option<&GpuAoSoRadiusGrid> {
144        self.radius_grid.as_ref()
145    }
146
147    /// Returns execution and transfer accounting.
148    #[must_use]
149    pub const fn receipt(&self) -> &GpuExecutionReceipt {
150        &self.receipt
151    }
152
153    /// Returns whether a capability is currently attached.
154    #[must_use]
155    pub fn has_capability(&self, capability: GpuFrameCapability) -> bool {
156        match capability {
157            GpuFrameCapability::Positions => true,
158            GpuFrameCapability::Normals => self.normals.is_some(),
159            GpuFrameCapability::Attributes => !self.attributes.is_empty(),
160            GpuFrameCapability::VoxelSegments => self.voxel_segments.is_some(),
161            GpuFrameCapability::RadiusGrid => self.radius_grid.is_some(),
162        }
163    }
164
165    /// Verifies that `runtime` owns the frame's buffers.
166    pub fn validate_runtime(&self, runtime: &WgpuRuntime) -> SpatialResult<()> {
167        if self.device_key != runtime_device_key(runtime) {
168            return Err(SpatialError::InvalidArgument(
169                "GPU frame belongs to a different runtime device".to_owned(),
170            ));
171        }
172        Ok(())
173    }
174
175    /// Attaches per-point normal output after validating length and device.
176    pub fn attach_normals(
177        &mut self,
178        runtime: &WgpuRuntime,
179        normals: GpuAoSoNormals,
180    ) -> SpatialResult<()> {
181        self.validate_runtime(runtime)?;
182        if normals.device_key() != self.device_key {
183            return Err(SpatialError::InvalidArgument(
184                "normal buffer belongs to a different runtime device".to_owned(),
185            ));
186        }
187        if normals.point_count() != self.point_count() {
188            return Err(SpatialError::BufferLengthMismatch {
189                expected: self.point_count(),
190                found: normals.point_count(),
191            });
192        }
193        if let Some(previous) = self.normals.replace(normals) {
194            previous.recycle(runtime);
195        }
196        Ok(())
197    }
198
199    /// Attaches voxel segments after validating their source point count.
200    pub fn attach_voxel_segments(&mut self, segments: GpuVoxelSegments) -> SpatialResult<()> {
201        if segments.point_count() as usize != self.point_count() {
202            return Err(SpatialError::BufferLengthMismatch {
203                expected: self.point_count(),
204                found: segments.point_count() as usize,
205            });
206        }
207        self.voxel_segments = Some(segments);
208        Ok(())
209    }
210
211    /// Attaches a sparse radius grid after validating its point count.
212    pub fn attach_radius_grid(&mut self, grid: GpuAoSoRadiusGrid) -> SpatialResult<()> {
213        if grid.segments().point_count() as usize != self.point_count() {
214            return Err(SpatialError::BufferLengthMismatch {
215                expected: self.point_count(),
216                found: grid.segments().point_count() as usize,
217            });
218        }
219        self.radius_grid = Some(grid);
220        Ok(())
221    }
222
223    /// Attaches interleaved attribute chunks after validating total length.
224    pub fn attach_attributes(
225        &mut self,
226        runtime: &WgpuRuntime,
227        attributes: Vec<GpuAoSoAttributeChunk>,
228    ) -> SpatialResult<()> {
229        self.validate_runtime(runtime)?;
230        if attributes.iter().any(|attribute| attribute.device_key() != self.device_key) {
231            return Err(SpatialError::InvalidArgument(
232                "attribute buffer belongs to a different runtime device".to_owned(),
233            ));
234        }
235        let found = attributes.iter().map(GpuAoSoAttributeChunk::point_count).sum();
236        if found != self.point_count() {
237            return Err(SpatialError::BufferLengthMismatch { expected: self.point_count(), found });
238        }
239        for previous in std::mem::replace(&mut self.attributes, attributes) {
240            previous.recycle(runtime);
241        }
242        Ok(())
243    }
244
245    /// Rebuilds the sparse radius grid from retained positions.
246    pub fn rebuild_radius_grid(&mut self, runtime: &WgpuRuntime, radius: f32) -> SpatialResult<()> {
247        self.rebuild_radius_grid_with_profiler(runtime, radius, None)
248    }
249
250    fn rebuild_radius_grid_with_profiler(
251        &mut self,
252        runtime: &WgpuRuntime,
253        radius: f32,
254        profiler: Option<&mut crate::GpuStageProfiler>,
255    ) -> SpatialResult<()> {
256        self.validate_runtime(runtime)?;
257        let grid = crate::aoso_staging::build_radius_grid_aoso_gpu_with_profiler(
258            runtime,
259            &self.positions,
260            radius,
261            profiler,
262        )?;
263        self.receipt
264            .transfers
265            .record(TransferDirection::DeviceToHost, grid.segments().construction_readback_bytes());
266        self.radius_grid = Some(grid);
267        self.receipt.stages.push("radius-grid");
268        Ok(())
269    }
270
271    /// Estimates normals using a cached matching grid or rebuilds it first.
272    pub fn estimate_normals(&mut self, runtime: &WgpuRuntime, radius: f32) -> SpatialResult<()> {
273        self.estimate_normals_with_profiler(runtime, radius, None)
274    }
275
276    fn estimate_normals_with_profiler(
277        &mut self,
278        runtime: &WgpuRuntime,
279        radius: f32,
280        mut profiler: Option<&mut crate::GpuStageProfiler>,
281    ) -> SpatialResult<()> {
282        self.validate_runtime(runtime)?;
283        let matches = self.radius_grid.as_ref().is_some_and(|grid| grid.radius() == radius);
284        if !matches {
285            self.rebuild_radius_grid_with_profiler(runtime, radius, profiler.as_deref_mut())?;
286        }
287        let grid = self.radius_grid.as_ref().ok_or_else(|| {
288            SpatialError::InvalidArgument("radius grid is unavailable".to_owned())
289        })?;
290        let normals = crate::aoso_staging::estimate_normals_radius_grid_aoso_gpu_with_profiler(
291            runtime,
292            &self.positions,
293            grid,
294            profiler,
295        )?;
296        self.attach_normals(runtime, normals)?;
297        self.receipt.stages.push("radius-normals");
298        Ok(())
299    }
300
301    /// Reduces attached interleaved attributes using retained voxel segments.
302    pub fn reduce_attributes(
303        &mut self,
304        runtime: &WgpuRuntime,
305        aggregation: AoSoAAttributeAggregation,
306    ) -> SpatialResult<AoSoAAttributeReduction> {
307        self.validate_runtime(runtime)?;
308        if self.attributes.is_empty() {
309            return Err(SpatialError::InvalidArgument(
310                "GPU frame has no attached attributes".to_owned(),
311            ));
312        }
313        let segments = self.voxel_segments.as_ref().ok_or_else(|| {
314            SpatialError::InvalidArgument("GPU frame has no voxel segments".to_owned())
315        })?;
316        let reduced =
317            reduce_voxel_attributes_aoso_chunks(runtime, &self.attributes, segments, aggregation)?;
318        if !reduced.is_empty() {
319            self.receipt.transfers.record(
320                TransferDirection::DeviceToDevice,
321                self.attributes.iter().map(GpuAoSoAttributeChunk::byte_len).sum(),
322            );
323        }
324        self.receipt.transfers.record(
325            TransferDirection::DeviceToHost,
326            (reduced.len() * reduced.layout().stride_f32() * std::mem::size_of::<f32>()) as u64,
327        );
328        self.receipt.stages.push("attribute-reduce");
329        Ok(reduced)
330    }
331
332    /// Explicitly reads interleaved positions back to CPU memory.
333    pub fn readback_positions(&mut self, runtime: &WgpuRuntime) -> SpatialResult<Vec<[f32; 3]>> {
334        self.validate_runtime(runtime)?;
335        let byte_len = self.positions.point_count() * 3 * std::mem::size_of::<f32>();
336        if byte_len == 0 {
337            return Ok(Vec::new());
338        }
339        let device = runtime.device();
340        let staging = device.create_buffer(&wgpu::BufferDescriptor {
341            label: Some("gpu-frame-position-readback"),
342            size: byte_len as u64,
343            usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
344            mapped_at_creation: false,
345        });
346        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
347            label: Some("gpu-frame-position-readback-encoder"),
348        });
349        encoder.copy_buffer_to_buffer(self.positions.buffer(), 0, &staging, 0, byte_len as u64);
350        runtime.queue().submit(Some(encoder.finish()));
351        let slice = staging.slice(..);
352        let (sender, receiver) = std::sync::mpsc::channel();
353        slice.map_async(wgpu::MapMode::Read, move |result| {
354            let _ = sender.send(result);
355        });
356        device.poll(wgpu::Maintain::Wait);
357        receiver
358            .recv()
359            .map_err(|_| SpatialError::InvalidArgument("failed to receive map result".to_owned()))?
360            .map_err(|error| SpatialError::InvalidArgument(format!("map failed: {error}")))?;
361        let mapped = slice.get_mapped_range();
362        let values: &[f32] = bytemuck::cast_slice(&mapped);
363        let positions = values.chunks_exact(3).map(|p| [p[0], p[1], p[2]]).collect();
364        drop(mapped);
365        staging.unmap();
366        self.receipt.transfers.record(TransferDirection::DeviceToHost, byte_len as u64);
367        Ok(positions)
368    }
369
370    /// Recycles pooled frame buffers after validating the runtime device.
371    pub fn recycle(self, runtime: &WgpuRuntime) -> SpatialResult<()> {
372        self.validate_runtime(runtime)?;
373        self.positions.recycle(runtime);
374        if let Some(normals) = self.normals {
375            normals.recycle(runtime);
376        }
377        for attribute in self.attributes {
378            attribute.recycle(runtime);
379        }
380        Ok(())
381    }
382}
383
384/// Uploads a tensor and chains global voxel partitioning and radius normals.
385///
386/// Retains every source point, without computing or reading back voxel centroids.
387/// A nonempty frame synchronizes two four-byte cell counts during partition/grid
388/// construction; these metadata transfers are included in its receipt. Position
389/// and normal arrays remain on the device until explicitly read back.
390pub fn run_aoso_voxel_normal_frame(
391    runtime: &WgpuRuntime,
392    tensor: &SpatialTensor<'_>,
393    origin: [f32; 3],
394    inv_leaf: f32,
395    normal_radius: f32,
396) -> SpatialResult<GpuSpatialFrame> {
397    run_aoso_voxel_normal_frame_with_profiler(
398        runtime,
399        tensor,
400        origin,
401        inv_leaf,
402        normal_radius,
403        None,
404    )
405}
406
407/// Runs a frame with pass timestamps for both partitions and radius normals.
408///
409/// Query readback requires an explicit profiler collection and is separate
410/// from the frame's transfer receipt. Capacity is checked before any upload.
411#[allow(clippy::too_many_arguments)]
412pub fn run_aoso_voxel_normal_frame_profiled(
413    runtime: &WgpuRuntime,
414    tensor: &SpatialTensor<'_>,
415    origin: [f32; 3],
416    inv_leaf: f32,
417    normal_radius: f32,
418    profiler: &mut crate::GpuStageProfiler,
419) -> SpatialResult<GpuSpatialFrame> {
420    let n = u32::try_from(tensor.len()).map_err(|_| {
421        SpatialError::InvalidArgument("AoSoA positions exceed the GPU point limit".to_owned())
422    })?;
423    let stages = if n == 0 {
424        0
425    } else {
426        // Keys + fused-build radix (or singleton entry build) + boundary
427        // scan + segment writing, for two grids.
428        let scan = crate::kernels::voxel_scan_pass_count(n);
429        2 * (2 + if n > 1 { 72 } else { 1 } + scan) + 1
430    };
431    profiler.validate(runtime, stages)?;
432    let result = run_aoso_voxel_normal_frame_with_profiler(
433        runtime,
434        tensor,
435        origin,
436        inv_leaf,
437        normal_radius,
438        Some(profiler),
439    );
440    profiler.finish_recording(&result);
441    result
442}
443
444pub(crate) fn run_aoso_voxel_normal_frame_with_profiler(
445    runtime: &WgpuRuntime,
446    tensor: &SpatialTensor<'_>,
447    origin: [f32; 3],
448    inv_leaf: f32,
449    normal_radius: f32,
450    mut profiler: Option<&mut crate::GpuStageProfiler>,
451) -> SpatialResult<GpuSpatialFrame> {
452    let chunks = upload_spatial_tensor_xyz_chunks(runtime, tensor)?;
453    let upload_bytes = chunks
454        .iter()
455        .map(|chunk| (chunk.point_count() * 3 * std::mem::size_of::<f32>()) as u64)
456        .sum();
457    let partition = crate::aoso_staging::build_voxel_segments_aoso_chunks_with_profiler(
458        runtime,
459        &chunks,
460        origin,
461        inv_leaf,
462        profiler.as_deref_mut(),
463    );
464    for chunk in chunks {
465        chunk.recycle(runtime);
466    }
467    let (positions, segments) = partition?;
468    let mut frame = GpuSpatialFrame::new(runtime, tensor.schema().clone(), positions)?;
469    frame
470        .receipt
471        .transfers
472        .record(TransferDirection::DeviceToHost, segments.construction_readback_bytes());
473    frame.attach_voxel_segments(segments)?;
474    frame.receipt.transfers.record(TransferDirection::HostToDevice, upload_bytes);
475    frame.receipt.transfers.record(TransferDirection::DeviceToDevice, upload_bytes);
476    frame.receipt.stages = vec!["upload", "voxel-segments"];
477    frame.estimate_normals_with_profiler(runtime, normal_radius, profiler)?;
478    Ok(frame)
479}
480
481#[cfg(test)]
482mod tests {
483    use super::{run_aoso_voxel_normal_frame, GpuFrameCapability};
484    use crate::{
485        build_voxel_segments, upload_spatial_tensor_attribute_chunks, AoSoAAttributeAggregation,
486        WgpuRuntime,
487    };
488    use spatialrust_core::{
489        AoSoAAttributeLayout, PointBuffer, PointBufferSet, PointCloud, PointCloudBuilder,
490        SpatialTensor, StandardSchemas,
491    };
492
493    #[test]
494    fn chained_frame_owns_capabilities_and_tracks_readback() {
495        let mut builder = PointCloudBuilder::xyz();
496        let mut expected = Vec::new();
497        for row in 0..8 {
498            for column in 0..8 {
499                let point = [column as f32 * 0.1, row as f32 * 0.1, 0.0];
500                builder.push_point(point).unwrap();
501                expected.push(point);
502            }
503        }
504        let cloud = builder.build().unwrap();
505        let tensor = SpatialTensor::new(&cloud, 13).unwrap();
506        let runtime = WgpuRuntime::new_headless().expect("wgpu runtime");
507
508        let mut frame =
509            run_aoso_voxel_normal_frame(&runtime, &tensor, [0.0; 3], 4.0, 0.25).unwrap();
510        assert_eq!(frame.point_count(), expected.len());
511        assert!(frame.has_capability(GpuFrameCapability::Positions));
512        assert!(frame.has_capability(GpuFrameCapability::Normals));
513        assert!(frame.has_capability(GpuFrameCapability::VoxelSegments));
514        assert!(frame.has_capability(GpuFrameCapability::RadiusGrid));
515        assert!(!frame.has_capability(GpuFrameCapability::Attributes));
516        assert_eq!(frame.normals().unwrap().point_count(), expected.len());
517        assert_eq!(
518            frame.receipt().stages(),
519            &["upload", "voxel-segments", "radius-grid", "radius-normals"]
520        );
521        assert_eq!(frame.receipt().host_to_device_bytes(), (expected.len() * 3 * 4) as u64);
522        assert_eq!(frame.receipt().gpu_to_gpu_bytes(), (expected.len() * 3 * 4) as u64);
523        // Only the voxel and radius-grid cell counts cross back during construction.
524        assert_eq!(frame.receipt().device_to_host_bytes(), 8);
525        assert!(frame.voxel_segments().unwrap().cell_count() < expected.len() as u32);
526
527        let normals = frame.normals().unwrap().readback(&runtime).unwrap();
528        for normal in normals {
529            assert!(normal.normal[0].abs() < 1e-5);
530            assert!(normal.normal[1].abs() < 1e-5);
531            assert!((normal.normal[2].abs() - 1.0).abs() < 1e-5);
532            assert!(normal.curvature.abs() < 1e-5);
533        }
534
535        let actual = frame.readback_positions(&runtime).unwrap();
536        assert_eq!(actual, expected);
537        assert_eq!(frame.receipt().device_to_host_bytes(), 8 + (expected.len() * 3 * 4) as u64);
538        assert!(frame.reduce_attributes(&runtime, AoSoAAttributeAggregation::Average).is_err());
539        frame.recycle(&runtime).unwrap();
540    }
541
542    #[test]
543    fn frame_partition_preserves_source_points_across_chunk_sizes() {
544        let points = [
545            [1.3, 0.0, 0.0],
546            [-0.4, 0.0, 0.0],
547            [1.1, 0.0, 0.0],
548            [-0.2, 0.0, 0.0],
549            [-1.3, 0.0, 0.0],
550            [2.1, 0.0, 0.0],
551            [1.4, 0.0, 0.0],
552        ];
553        let origin = [-0.5, 0.0, 0.0];
554        let mut builder = PointCloudBuilder::xyz();
555        for point in points {
556            builder.push_point(point).unwrap();
557        }
558        let cloud = builder.build().unwrap();
559        let keys = points.map(|p| ((p[0] - origin[0]).floor() as i64, 0, 0));
560        let expected = build_voxel_segments(&keys);
561        let runtime = WgpuRuntime::new_headless().expect("wgpu runtime");
562        for chunk_size in [1, 2, 64] {
563            let tensor = SpatialTensor::new(&cloud, chunk_size).unwrap();
564            let mut frame =
565                run_aoso_voxel_normal_frame(&runtime, &tensor, origin, 1.0, 0.5).unwrap();
566            assert_eq!(frame.point_count(), points.len());
567            assert_eq!(frame.normals().unwrap().point_count(), points.len());
568            assert_eq!(
569                frame.voxel_segments().unwrap().to_voxel_segments(&runtime).unwrap(),
570                expected
571            );
572            assert_eq!(frame.receipt().device_to_host_bytes(), 8);
573            assert_eq!(frame.readback_positions(&runtime).unwrap(), points);
574            assert_eq!(frame.receipt().host_to_device_bytes(), 7 * 12);
575            assert_eq!(frame.receipt().gpu_to_gpu_bytes(), 7 * 12);
576            assert_eq!(frame.receipt().device_to_host_bytes(), 8 + 7 * 12);
577            frame.recycle(&runtime).unwrap();
578        }
579    }
580
581    #[test]
582    fn empty_frame_has_no_payload_or_metadata_transfers() {
583        let mut buffers = PointBufferSet::new();
584        for field in ["x", "y", "z"] {
585            buffers.insert(field, PointBuffer::F32(Vec::new()));
586        }
587        let cloud =
588            PointCloud::try_from_parts(StandardSchemas::point_xyz(), buffers, Default::default())
589                .unwrap();
590        let tensor = SpatialTensor::new(&cloud, 2).unwrap();
591        let runtime = WgpuRuntime::new_headless().expect("wgpu runtime");
592        let mut frame = run_aoso_voxel_normal_frame(&runtime, &tensor, [0.0; 3], 1.0, 0.5).unwrap();
593        assert_eq!(frame.point_count(), 0);
594        assert_eq!(frame.voxel_segments().unwrap().construction_readback_bytes(), 0);
595        assert_eq!(frame.radius_grid().unwrap().segments().construction_readback_bytes(), 0);
596        frame.estimate_normals(&runtime, 1.0).unwrap();
597        assert!(frame.readback_positions(&runtime).unwrap().is_empty());
598        assert_eq!(frame.receipt().host_to_device_bytes(), 0);
599        assert_eq!(frame.receipt().gpu_to_gpu_bytes(), 0);
600        assert_eq!(frame.receipt().device_to_host_bytes(), 0);
601        frame.recycle(&runtime).unwrap();
602    }
603
604    #[test]
605    fn frame_rejects_a_different_runtime() {
606        let mut builder = PointCloudBuilder::xyz();
607        builder.push_point([0.0, 0.0, 0.0]).unwrap();
608        let cloud = builder.build().unwrap();
609        let tensor = SpatialTensor::new(&cloud, 1).unwrap();
610        let runtime = WgpuRuntime::new_headless().expect("first runtime");
611        let other = WgpuRuntime::new_headless().expect("second runtime");
612        let frame = run_aoso_voxel_normal_frame(&runtime, &tensor, [0.0; 3], 1.0, 1.0).unwrap();
613
614        assert!(frame.validate_runtime(&other).is_err());
615        frame.recycle(&runtime).unwrap();
616    }
617
618    #[test]
619    fn frame_native_normals_and_attributes_replace_safely() {
620        let mut builder = PointCloudBuilder::new(StandardSchemas::point_xyzinormal());
621        for point in [
622            [0.1, 0.0, 0.0, 2.0, 0.0, 0.0, 1.0],
623            [1.1, 0.0, 0.0, 4.0, 0.0, 0.0, 1.0],
624            [1.3, 0.0, 0.0, 8.0, 0.0, 0.0, 1.0],
625            [2.1, 0.0, 0.0, 6.0, 0.0, 0.0, 1.0],
626        ] {
627            builder.push_point(point).unwrap();
628        }
629        let cloud = builder.build().unwrap();
630        let tensor = SpatialTensor::new(&cloud, 2).unwrap();
631        let runtime = WgpuRuntime::new_headless().expect("wgpu runtime");
632        let attributes = upload_spatial_tensor_attribute_chunks(
633            &runtime,
634            &tensor,
635            AoSoAAttributeLayout::XYZ_INTENSITY_NORMALS,
636        )
637        .unwrap();
638        let mut frame = run_aoso_voxel_normal_frame(&runtime, &tensor, [0.0; 3], 1.0, 0.5).unwrap();
639        frame.attach_attributes(&runtime, attributes).unwrap();
640
641        let reduced =
642            frame.reduce_attributes(&runtime, AoSoAAttributeAggregation::Average).unwrap();
643        assert_eq!(reduced.len(), 3);
644        assert_eq!(reduced.as_slice()[10], 6.0);
645        assert!(frame.has_capability(GpuFrameCapability::Attributes));
646        // Attribute uploads took place outside frame methods; reduction copies
647        // the attached records on-device and reads back the reduced records.
648        assert_eq!(frame.receipt().host_to_device_bytes(), 4 * 3 * 4);
649        assert_eq!(frame.receipt().gpu_to_gpu_bytes(), 4 * 3 * 4 + 4 * 7 * 4);
650        assert_eq!(frame.receipt().device_to_host_bytes(), 8 + 3 * 7 * 4);
651
652        frame.estimate_normals(&runtime, 0.5).unwrap();
653        assert_eq!(frame.radius_grid().unwrap().radius(), 0.5);
654        assert_eq!(frame.receipt().device_to_host_bytes(), 8 + 3 * 7 * 4);
655        let before_invalid_radius = frame.receipt().clone();
656        assert!(frame.estimate_normals(&runtime, 0.0).is_err());
657        assert_eq!(frame.receipt(), &before_invalid_radius);
658        frame.estimate_normals(&runtime, 1.0).unwrap();
659        assert_eq!(frame.radius_grid().unwrap().radius(), 1.0);
660        assert_eq!(frame.normals().unwrap().point_count(), 4);
661        assert_eq!(frame.receipt().device_to_host_bytes(), 12 + 3 * 7 * 4);
662        assert!(frame.receipt().stages().ends_with(&[
663            "radius-normals",
664            "radius-grid",
665            "radius-normals",
666        ]));
667        frame.recycle(&runtime).unwrap();
668    }
669}