Skip to main content

geolith_tiles_builder/splat/
ply.rs

1//! Binary PLY reader for 3D Gaussian Splatting point clouds.
2//!
3//! Reads the vertex layout emitted by the INRIA reference trainer, gsplat and
4//! Nerfstudio `splatfacto`: position, optional normals, `f_dc_*` spherical
5//! harmonic DC terms, `f_rest_*` higher-order coefficients, `opacity`,
6//! `scale_*` and `rot_*`.
7//!
8//! Values are kept in their stored (raw) form. `opacity` is a logit and
9//! `scale_*` are natural logs; converting them is the encoder's job because
10//! SPZ quantises the log-scale directly.
11
12use std::fs::File;
13use std::io::{BufRead, BufReader, Read};
14use std::path::Path;
15
16use geolith::error::{GeolithError, Result};
17
18/// Number of `f_rest_*` coefficients per colour channel for each SH degree.
19const SH_REST_PER_CHANNEL: [usize; 4] = [0, 3, 8, 15];
20
21/// Scalar property types permitted in a 3DGS PLY vertex element.
22#[non_exhaustive]
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24enum ScalarType {
25    /// IEEE-754 single precision.
26    Float32,
27    /// IEEE-754 double precision.
28    Float64,
29    /// Signed 8-bit.
30    Int8,
31    /// Unsigned 8-bit.
32    Uint8,
33    /// Signed 16-bit.
34    Int16,
35    /// Unsigned 16-bit.
36    Uint16,
37    /// Signed 32-bit.
38    Int32,
39    /// Unsigned 32-bit.
40    Uint32,
41}
42
43impl ScalarType {
44    /// Parse a PLY type token.
45    fn parse(token: &str) -> Option<Self> {
46        match token {
47            "float" | "float32" => Some(Self::Float32),
48            "double" | "float64" => Some(Self::Float64),
49            "char" | "int8" => Some(Self::Int8),
50            "uchar" | "uint8" => Some(Self::Uint8),
51            "short" | "int16" => Some(Self::Int16),
52            "ushort" | "uint16" => Some(Self::Uint16),
53            "int" | "int32" => Some(Self::Int32),
54            "uint" | "uint32" => Some(Self::Uint32),
55            _ => None,
56        }
57    }
58
59    /// Encoded width in bytes.
60    const fn size(self) -> usize {
61        match self {
62            Self::Int8 | Self::Uint8 => 1,
63            Self::Int16 | Self::Uint16 => 2,
64            Self::Float32 | Self::Int32 | Self::Uint32 => 4,
65            Self::Float64 => 8,
66        }
67    }
68
69    /// Decode one little-endian value to `f32`.
70    fn read_le(self, bytes: &[u8]) -> f32 {
71        match self {
72            Self::Float32 => f32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]),
73            Self::Float64 => f64::from_le_bytes([
74                bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
75            ]) as f32,
76            Self::Int8 => f32::from(bytes[0] as i8),
77            Self::Uint8 => f32::from(bytes[0]),
78            Self::Int16 => f32::from(i16::from_le_bytes([bytes[0], bytes[1]])),
79            Self::Uint16 => f32::from(u16::from_le_bytes([bytes[0], bytes[1]])),
80            Self::Int32 => i32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) as f32,
81            Self::Uint32 => u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) as f32,
82        }
83    }
84}
85
86/// One scalar property inside the vertex element.
87#[derive(Debug, Clone)]
88struct Property {
89    /// Property name as written in the header.
90    name: String,
91    /// Encoded scalar type.
92    ty: ScalarType,
93    /// Byte offset within a vertex record.
94    offset: usize,
95}
96
97/// Parsed PLY header for a 3DGS vertex element.
98#[derive(Debug, Clone)]
99struct PlyHeader {
100    /// Number of vertices.
101    count: usize,
102    /// Byte length of one vertex record.
103    stride: usize,
104    /// Scalar properties in declaration order.
105    properties: Vec<Property>,
106    /// Declared scene vertical axis from a `comment Vertical axis` line.
107    vertical_axis: Option<[f32; 3]>,
108}
109
110impl PlyHeader {
111    /// Look up a property by name.
112    fn find(&self, name: &str) -> Option<&Property> {
113        self.properties.iter().find(|p| p.name == name)
114    }
115
116    /// Look up a property by name or fail.
117    fn require(&self, name: &str) -> Result<&Property> {
118        self.find(name).ok_or_else(|| {
119            GeolithError::Ply(format!("PLY vertex element is missing property '{name}'"))
120        })
121    }
122}
123
124/// A 3D Gaussian Splatting point cloud in raw (stored) units.
125#[derive(Debug, Clone, Default)]
126pub struct SplatCloud {
127    /// Positions as `[x, y, z]` triples.
128    pub positions: Vec<[f32; 3]>,
129    /// Spherical harmonic DC terms as `[r, g, b]` triples.
130    pub colors: Vec<[f32; 3]>,
131    /// Opacity logits, one per splat.
132    pub opacities: Vec<f32>,
133    /// Natural-log scales as `[sx, sy, sz]` triples.
134    pub scales: Vec<[f32; 3]>,
135    /// Rotation quaternions as `[w, x, y, z]`, matching the PLY `rot_*` order.
136    pub rotations: Vec<[f32; 4]>,
137    /// Higher-order SH coefficients, `sh_degree` dependent, channel-major per splat.
138    pub sh: Vec<f32>,
139    /// Spherical harmonic degree present in `sh` (0 through 3).
140    pub sh_degree: u8,
141    /// Declared scene vertical axis from the PLY `comment Vertical axis` line.
142    ///
143    /// Trainers such as brush export the scene in their own reference frame
144    /// and state which way is up in the header. `None` when the PLY has no
145    /// such comment (the standard 3DGS convention, where up is `-Z`).
146    pub vertical_axis: Option<[f32; 3]>,
147}
148
149impl SplatCloud {
150    /// Number of splats in the cloud.
151    #[must_use]
152    pub const fn len(&self) -> usize {
153        self.positions.len()
154    }
155
156    /// Whether the cloud has no splats.
157    #[must_use]
158    pub const fn is_empty(&self) -> bool {
159        self.positions.is_empty()
160    }
161
162    /// Coefficients per colour channel implied by [`Self::sh_degree`].
163    #[must_use]
164    pub const fn sh_rest_per_channel(&self) -> usize {
165        SH_REST_PER_CHANNEL[self.sh_degree as usize]
166    }
167
168    /// Axis-aligned bounds as `(min, max)`, or `None` when empty.
169    #[must_use]
170    pub fn bounds(&self) -> Option<([f32; 3], [f32; 3])> {
171        let mut min = [f32::INFINITY; 3];
172        let mut max = [f32::NEG_INFINITY; 3];
173        for position in &self.positions {
174            for axis in 0..3 {
175                min[axis] = min[axis].min(position[axis]);
176                max[axis] = max[axis].max(position[axis]);
177            }
178        }
179        (!self.positions.is_empty()).then_some((min, max))
180    }
181
182    /// Drop splats outside the central per-axis percentile band.
183    ///
184    /// Inward-facing captures hallucinate a far-field shell of splats around
185    /// the real subject; trimming `percent` from both ends of each axis keeps
186    /// the capture hull. `0.0` keeps every splat.
187    ///
188    /// # Errors
189    ///
190    /// Returns [`GeolithError::SplatTiles`] when `percent` is negative or at
191    /// least 50, which would discard the entire cloud.
192    pub fn crop_percentile(&self, percent: f64) -> Result<Self> {
193        if !(0.0..50.0).contains(&percent) {
194            return Err(GeolithError::SplatTiles(format!(
195                "crop percentile must be in [0, 50), got {percent}"
196            )));
197        }
198        if percent == 0.0 || self.is_empty() {
199            return self.subset(&(0..self.len() as u32).collect::<Vec<_>>());
200        }
201
202        let mut low = [0.0_f32; 3];
203        let mut high = [0.0_f32; 3];
204        let mut sorted = Vec::with_capacity(self.len());
205        for axis in 0..3 {
206            sorted.clear();
207            sorted.extend(self.positions.iter().map(|p| p[axis]));
208            sorted.sort_unstable_by(f32::total_cmp);
209            let cut = ((self.len() as f64) * percent / 100.0).floor() as usize;
210            let cut = cut.min(self.len().saturating_sub(1) / 2);
211            low[axis] = sorted[cut];
212            high[axis] = sorted[self.len() - 1 - cut];
213        }
214
215        let kept: Vec<u32> = self
216            .positions
217            .iter()
218            .enumerate()
219            .filter(|(_, p)| (0..3).all(|axis| p[axis] >= low[axis] && p[axis] <= high[axis]))
220            .map(|(index, _)| index as u32)
221            .collect();
222
223        self.subset(&kept)
224    }
225
226    /// Drop splats whose distance from the cloud centroid exceeds `percent` of
227    /// the radial distance distribution.
228    ///
229    /// Aerial captures hallucinate a roughly spherical shell of low-quality
230    /// splats around the subject that per-axis percentile cropping misses;
231    /// trimming the far end of the radial distance distribution removes it.
232    /// `0.0` keeps every splat.
233    ///
234    /// # Errors
235    ///
236    /// Returns [`GeolithError::SplatTiles`] when `percent` is negative or at
237    /// least 50, which would discard the entire cloud.
238    pub fn crop_radial_percentile(&self, percent: f64) -> Result<Self> {
239        if !(0.0..50.0).contains(&percent) {
240            return Err(GeolithError::SplatTiles(format!(
241                "radial crop percentile must be in [0, 50), got {percent}"
242            )));
243        }
244        if percent == 0.0 || self.is_empty() {
245            return self.subset(&(0..self.len() as u32).collect::<Vec<_>>());
246        }
247
248        let mut centroid = [0.0_f64; 3];
249        for position in &self.positions {
250            centroid[0] += f64::from(position[0]);
251            centroid[1] += f64::from(position[1]);
252            centroid[2] += f64::from(position[2]);
253        }
254        let n = self.len() as f64;
255        centroid[0] /= n;
256        centroid[1] /= n;
257        centroid[2] /= n;
258
259        // Squared distances, compared as computed: taking a square root for
260        // the threshold and squaring it again can land an ulp below the
261        // threshold point's own squared distance and drop that point too.
262        let squared: Vec<f64> = self
263            .positions
264            .iter()
265            .map(|p| {
266                let dx = f64::from(p[0]) - centroid[0];
267                let dy = f64::from(p[1]) - centroid[1];
268                let dz = f64::from(p[2]) - centroid[2];
269                dx * dx + dy * dy + dz * dz
270            })
271            .collect();
272        let mut sorted = squared.clone();
273        sorted.sort_unstable_by(f64::total_cmp);
274
275        let cut = ((self.len() as f64) * percent / 100.0).floor() as usize;
276        let cut = cut.min(self.len().saturating_sub(1));
277        // `cut` points are removed: the threshold is the largest distance
278        // among the surviving `len - cut` points.
279        let keep = self.len() - cut;
280        let max_sq = sorted[keep - 1];
281
282        let kept: Vec<u32> = squared
283            .iter()
284            .enumerate()
285            .filter(|(_, d)| **d <= max_sq)
286            .map(|(index, _)| index as u32)
287            .collect();
288
289        self.subset(&kept)
290    }
291
292    /// Uniformly scale the scene by `factor`.
293    ///
294    /// Positions multiply by the factor and the natural-log splat scales
295    /// shift by `ln(factor)`, so each splat's footprint shrinks or grows with
296    /// the scene instead of smearing.
297    pub fn rescale(&mut self, factor: f32) {
298        if factor == 1.0 {
299            return;
300        }
301        let log_shift = factor.ln();
302        for position in &mut self.positions {
303            for component in position {
304                *component *= factor;
305            }
306        }
307        for scale in &mut self.scales {
308            for axis in scale {
309                *axis += log_shift;
310            }
311        }
312    }
313
314    /// Apply the gsplat coverage boost: `opacity_logit += ln(boost)` and
315    /// `log_scale -= 0.5 * ln(boost)`.
316    ///
317    /// Trainers that run without a coverage boost leave splats dim and
318    /// large; the same capture trained with `--coverage-boost-scale N`
319    /// brightens each splat N-fold while shrinking its footprint by √N, so
320    /// the rendered image keeps its luminance but regains sharpness.
321    /// `boost <= 1.0` is a no-op.
322    pub fn coverage_boost(&mut self, boost: f32) {
323        if boost <= 1.0 || self.is_empty() {
324            return;
325        }
326        let log_boost = boost.ln();
327        for opacity in &mut self.opacities {
328            *opacity += log_boost;
329        }
330        for scale in &mut self.scales {
331            for axis in scale {
332                *axis -= 0.5 * log_boost;
333            }
334        }
335    }
336
337    /// Rotate the whole scene so the declared [`Self::vertical_axis`] points
338    /// along `-Z`, the convention the tileset pipeline expects.
339    ///
340    /// Positions and per-splat rotation quaternions are rotated by the
341    /// shortest-arc rotation that maps the declared up vector onto `-Z`.
342    /// Scales and SH coefficients are untouched: they live in the splat's
343    /// local frame, which rotates along with the quaternion.
344    ///
345    /// No-op when the cloud has no declared axis, or the declared axis is
346    /// already `-Z` within a small tolerance.
347    pub fn orient_to_negative_z(&mut self) {
348        let Some(declared) = self.vertical_axis else {
349            return;
350        };
351        let target = [0.0_f32, 0.0, -1.0];
352        if declared == target {
353            return;
354        }
355
356        // Shortest-arc rotation from `declared` onto `target` about the
357        // perpendicular axis; handle the exactly-opposite case explicitly.
358        let mut axis = [
359            declared[1] * target[2] - declared[2] * target[1],
360            declared[2] * target[0] - declared[0] * target[2],
361            declared[0] * target[1] - declared[1] * target[0],
362        ];
363        let axis_norm = (axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2]).sqrt();
364        if axis_norm < 1e-6 {
365            axis = [1.0, 0.0, 0.0];
366        } else {
367            for component in &mut axis {
368                *component /= axis_norm;
369            }
370        }
371        let dot = (declared[0] * target[0] + declared[1] * target[1] + declared[2] * target[2])
372            .clamp(-1.0, 1.0);
373        let angle = dot.acos();
374        let (sin_half, cos_half) = (angle / 2.0).sin_cos();
375        let q = [
376            cos_half,
377            axis[0] * sin_half,
378            axis[1] * sin_half,
379            axis[2] * sin_half,
380        ];
381
382        let rotate = |v: [f32; 3]| -> [f32; 3] {
383            let (w, x, y, z) = (q[0], q[1], q[2], q[3]);
384            let (vx, vy, vz) = (v[0], v[1], v[2]);
385            let t = [
386                2.0 * (y * vz - z * vy),
387                2.0 * (z * vx - x * vz),
388                2.0 * (x * vy - y * vx),
389            ];
390            [
391                vx + w * t[0] + (y * t[2] - z * t[1]),
392                vy + w * t[1] + (z * t[0] - x * t[2]),
393                vz + w * t[2] + (x * t[1] - y * t[0]),
394            ]
395        };
396
397        let mul_quat = |a: [f32; 4], b: [f32; 4]| -> [f32; 4] {
398            let (aw, ax, ay, az) = (a[0], a[1], a[2], a[3]);
399            let (bw, bx, by, bz) = (b[0], b[1], b[2], b[3]);
400            [
401                aw * bw - ax * bx - ay * by - az * bz,
402                aw * bx + ax * bw + ay * bz - az * by,
403                aw * by - ax * bz + ay * bw + az * bx,
404                aw * bz + ax * by - ay * bx + az * bw,
405            ]
406        };
407
408        for position in &mut self.positions {
409            *position = rotate(*position);
410        }
411        for rotation in &mut self.rotations {
412            *rotation = mul_quat(q, *rotation);
413        }
414        self.vertical_axis = None;
415    }
416
417    /// Build a cloud holding only the splats at `indices`.
418    ///
419    /// # Errors
420    ///
421    /// Returns [`GeolithError::Ply`] when an index is out of range.
422    pub fn subset(&self, indices: &[u32]) -> Result<Self> {
423        let rest = self.sh_rest_per_channel() * 3;
424        let mut out = Self {
425            positions: Vec::with_capacity(indices.len()),
426            colors: Vec::with_capacity(indices.len()),
427            opacities: Vec::with_capacity(indices.len()),
428            scales: Vec::with_capacity(indices.len()),
429            rotations: Vec::with_capacity(indices.len()),
430            sh: Vec::with_capacity(indices.len() * rest),
431            sh_degree: self.sh_degree,
432            vertical_axis: self.vertical_axis,
433        };
434
435        for &index in indices {
436            let i = index as usize;
437            if i >= self.positions.len() {
438                return Err(GeolithError::Ply(format!(
439                    "splat index {i} out of range for cloud of {} splats",
440                    self.positions.len()
441                )));
442            }
443            out.positions.push(self.positions[i]);
444            out.colors.push(self.colors[i]);
445            out.opacities.push(self.opacities[i]);
446            out.scales.push(self.scales[i]);
447            out.rotations.push(self.rotations[i]);
448            if rest > 0 {
449                out.sh.extend_from_slice(&self.sh[i * rest..(i + 1) * rest]);
450            }
451        }
452
453        Ok(out)
454    }
455}
456
457/// Read a binary little-endian 3DGS PLY file.
458///
459/// # Errors
460///
461/// Returns [`GeolithError::Ply`] when the header is malformed, the format is
462/// not `binary_little_endian`, required properties are absent, or the vertex
463/// payload is truncated.
464pub fn read_splat_ply(path: &Path) -> Result<SplatCloud> {
465    let mut file = File::open(path)?;
466    let header = parse_header(&mut file, path)?;
467
468    let mut buffer = Vec::with_capacity(header.count * header.stride);
469    file.read_to_end(&mut buffer)?;
470
471    let expected = header.count * header.stride;
472    if buffer.len() < expected {
473        return Err(GeolithError::Ply(format!(
474            "{}: truncated vertex data — expected {expected} bytes, found {}",
475            path.display(),
476            buffer.len()
477        )));
478    }
479
480    let mut cloud = decode_vertices(&header, &buffer)?;
481    cloud.orient_to_negative_z();
482    Ok(cloud)
483}
484
485/// Parse the ASCII header and leave the reader positioned at the payload.
486fn parse_header(file: &mut File, path: &Path) -> Result<PlyHeader> {
487    let mut reader = BufReader::new(file.try_clone()?);
488    let mut consumed = 0_usize;
489    let mut line = String::new();
490
491    reader.read_line(&mut line)?;
492    consumed += line.len();
493    if line.trim() != "ply" {
494        return Err(GeolithError::Ply(format!(
495            "{}: not a PLY file (missing 'ply' magic)",
496            path.display()
497        )));
498    }
499
500    let mut count = None;
501    let mut properties: Vec<Property> = Vec::new();
502    let mut offset = 0_usize;
503    let mut in_vertex_element = false;
504    let mut saw_format = false;
505    let mut vertical_axis: Option<[f32; 3]> = None;
506
507    loop {
508        line.clear();
509        let read = reader.read_line(&mut line)?;
510        if read == 0 {
511            return Err(GeolithError::Ply(format!(
512                "{}: header ended before 'end_header'",
513                path.display()
514            )));
515        }
516        consumed += read;
517        let trimmed = line.trim();
518        let tokens: Vec<&str> = trimmed.split_whitespace().collect();
519
520        match tokens.as_slice() {
521            ["format", encoding, ..] => {
522                saw_format = true;
523                if *encoding != "binary_little_endian" {
524                    return Err(GeolithError::Ply(format!(
525                        "{}: unsupported PLY format '{encoding}' — \
526                         only binary_little_endian is supported",
527                        path.display()
528                    )));
529                }
530            }
531            ["element", name, n] => {
532                in_vertex_element = *name == "vertex";
533                if in_vertex_element {
534                    count = Some(n.parse::<usize>().map_err(|e| {
535                        GeolithError::Ply(format!(
536                            "{}: bad vertex count '{n}': {e}",
537                            path.display()
538                        ))
539                    })?);
540                }
541            }
542            ["property", "list", ..] => {
543                if in_vertex_element {
544                    return Err(GeolithError::Ply(format!(
545                        "{}: list properties are not supported in the vertex element",
546                        path.display()
547                    )));
548                }
549            }
550            ["property", ty, name] => {
551                if in_vertex_element {
552                    let scalar = ScalarType::parse(ty).ok_or_else(|| {
553                        GeolithError::Ply(format!(
554                            "{}: unsupported property type '{ty}' for '{name}'",
555                            path.display()
556                        ))
557                    })?;
558                    properties.push(Property {
559                        name: (*name).to_owned(),
560                        ty: scalar,
561                        offset,
562                    });
563                    offset += scalar.size();
564                }
565            }
566            ["end_header"] => break,
567            ["comment", rest @ ..] => {
568                if let Some(axis) = parse_vertical_axis_comment(rest) {
569                    vertical_axis = Some(axis);
570                }
571            }
572            _ => {}
573        }
574    }
575
576    if !saw_format {
577        return Err(GeolithError::Ply(format!(
578            "{}: header has no format line",
579            path.display()
580        )));
581    }
582
583    let count = count.ok_or_else(|| {
584        GeolithError::Ply(format!("{}: no 'vertex' element declared", path.display()))
585    })?;
586
587    use std::io::Seek as _;
588    file.seek(std::io::SeekFrom::Start(consumed as u64))?;
589
590    Ok(PlyHeader {
591        count,
592        stride: offset,
593        properties,
594        vertical_axis,
595    })
596}
597
598/// Parse a `comment Vertical axis: x y z` PLY header line.
599///
600/// Brush-style trainers export the scene in their own reference frame and
601/// declare the direction of gravity as a unit vector. Returns `None` for
602/// any other comment line.
603fn parse_vertical_axis_comment(rest: &[&str]) -> Option<[f32; 3]> {
604    let ["Vertical", "axis:", x, y, z] = rest else {
605        return None;
606    };
607    let x = x.parse::<f32>().ok()?;
608    let y = y.parse::<f32>().ok()?;
609    let z = z.parse::<f32>().ok()?;
610    let norm = (x * x + y * y + z * z).sqrt();
611    if norm < f32::EPSILON || !norm.is_finite() {
612        return None;
613    }
614    Some([x / norm, y / norm, z / norm])
615}
616
617/// Decode the vertex payload into a [`SplatCloud`].
618fn decode_vertices(header: &PlyHeader, buffer: &[u8]) -> Result<SplatCloud> {
619    let x = header.require("x")?;
620    let y = header.require("y")?;
621    let z = header.require("z")?;
622    let opacity = header.require("opacity")?;
623    let f_dc: Vec<&Property> = (0..3)
624        .map(|i| header.require(&format!("f_dc_{i}")))
625        .collect::<Result<_>>()?;
626    let scale: Vec<&Property> = (0..3)
627        .map(|i| header.require(&format!("scale_{i}")))
628        .collect::<Result<_>>()?;
629    let rot: Vec<&Property> = (0..4)
630        .map(|i| header.require(&format!("rot_{i}")))
631        .collect::<Result<_>>()?;
632
633    let rest_count = (0..)
634        .take_while(|i| header.find(&format!("f_rest_{i}")).is_some())
635        .count();
636    let sh_degree = sh_degree_from_rest_count(rest_count)?;
637    let rest_per_channel = SH_REST_PER_CHANNEL[sh_degree as usize];
638
639    let rest: Vec<&Property> = (0..rest_per_channel * 3)
640        .map(|i| header.require(&format!("f_rest_{i}")))
641        .collect::<Result<_>>()?;
642
643    let n = header.count;
644    let mut cloud = SplatCloud {
645        positions: Vec::with_capacity(n),
646        colors: Vec::with_capacity(n),
647        opacities: Vec::with_capacity(n),
648        scales: Vec::with_capacity(n),
649        rotations: Vec::with_capacity(n),
650        sh: Vec::with_capacity(n * rest.len()),
651        sh_degree,
652        vertical_axis: header.vertical_axis,
653    };
654
655    let read = |record: &[u8], p: &Property| p.ty.read_le(&record[p.offset..]);
656
657    for record in buffer.chunks_exact(header.stride).take(n) {
658        cloud
659            .positions
660            .push([read(record, x), read(record, y), read(record, z)]);
661        cloud.colors.push([
662            read(record, f_dc[0]),
663            read(record, f_dc[1]),
664            read(record, f_dc[2]),
665        ]);
666        cloud.opacities.push(read(record, opacity));
667        cloud.scales.push([
668            read(record, scale[0]),
669            read(record, scale[1]),
670            read(record, scale[2]),
671        ]);
672        cloud.rotations.push([
673            read(record, rot[0]),
674            read(record, rot[1]),
675            read(record, rot[2]),
676            read(record, rot[3]),
677        ]);
678        for property in &rest {
679            cloud.sh.push(read(record, property));
680        }
681    }
682
683    Ok(cloud)
684}
685
686/// Map an `f_rest_*` property count to its spherical harmonic degree.
687///
688/// The trainers store `3 * coefficients_per_channel` rest values, so the
689/// valid totals are 0, 9, 24 and 45 for degrees 0 through 3.
690fn sh_degree_from_rest_count(rest_count: usize) -> Result<u8> {
691    if !rest_count.is_multiple_of(3) {
692        return Err(GeolithError::Ply(format!(
693            "f_rest_* count {rest_count} is not a multiple of 3"
694        )));
695    }
696    let per_channel = rest_count / 3;
697    SH_REST_PER_CHANNEL
698        .iter()
699        .position(|&c| c == per_channel)
700        .map(|degree| degree as u8)
701        .ok_or_else(|| {
702            GeolithError::Ply(format!(
703                "f_rest_* count {rest_count} maps to no SH degree \
704                 (expected 0, 9, 24 or 45)"
705            ))
706        })
707}
708
709#[cfg(test)]
710mod tests {
711    use super::*;
712    use std::io::Write as _;
713
714    fn write_ply(
715        properties: &[&str],
716        vertices: &[Vec<f32>],
717        format: &str,
718    ) -> tempfile::NamedTempFile {
719        let mut file = tempfile::NamedTempFile::new().expect("temp file");
720        let mut header = String::from("ply\n");
721        header.push_str(&format!("format {format} 1.0\n"));
722        header.push_str(&format!("element vertex {}\n", vertices.len()));
723        for property in properties {
724            header.push_str(&format!("property float {property}\n"));
725        }
726        header.push_str("end_header\n");
727        file.write_all(header.as_bytes()).expect("write header");
728        for vertex in vertices {
729            for value in vertex {
730                file.write_all(&value.to_le_bytes()).expect("write value");
731            }
732        }
733        file.flush().expect("flush");
734        file
735    }
736
737    fn minimal_properties() -> Vec<&'static str> {
738        vec![
739            "x", "y", "z", "f_dc_0", "f_dc_1", "f_dc_2", "opacity", "scale_0", "scale_1",
740            "scale_2", "rot_0", "rot_1", "rot_2", "rot_3",
741        ]
742    }
743
744    fn minimal_vertex(x: f32) -> Vec<f32> {
745        vec![
746            x, 2.0, 3.0, 0.5, 0.6, 0.7, 1.2, -2.0, -2.1, -2.2, 1.0, 0.0, 0.0, 0.0,
747        ]
748    }
749
750    #[test]
751    fn reads_degree_zero_cloud() {
752        let file = write_ply(
753            &minimal_properties(),
754            &[minimal_vertex(1.0), minimal_vertex(4.0)],
755            "binary_little_endian",
756        );
757        let cloud = read_splat_ply(file.path()).expect("valid ply");
758
759        assert_eq!(cloud.len(), 2);
760        assert!(!cloud.is_empty());
761        assert_eq!(cloud.sh_degree, 0);
762        assert_eq!(cloud.sh_rest_per_channel(), 0);
763        assert_eq!(cloud.positions[0], [1.0, 2.0, 3.0]);
764        assert_eq!(cloud.positions[1], [4.0, 2.0, 3.0]);
765        assert_eq!(cloud.colors[0], [0.5, 0.6, 0.7]);
766        assert_eq!(cloud.opacities[0], 1.2);
767        assert_eq!(cloud.scales[0], [-2.0, -2.1, -2.2]);
768        assert_eq!(
769            cloud.rotations[0],
770            [1.0, 0.0, 0.0, 0.0],
771            "rot_0..3 is stored w,x,y,z"
772        );
773        assert!(cloud.sh.is_empty());
774    }
775
776    #[test]
777    fn reads_degree_one_cloud_with_rest_coefficients() {
778        let mut properties = minimal_properties();
779        for i in 0..9 {
780            properties.push(Box::leak(format!("f_rest_{i}").into_boxed_str()));
781        }
782        let mut vertex = minimal_vertex(1.0);
783        vertex.extend((0..9).map(|i| i as f32 * 0.1));
784
785        let file = write_ply(&properties, &[vertex], "binary_little_endian");
786        let cloud = read_splat_ply(file.path()).expect("valid ply");
787
788        assert_eq!(cloud.sh_degree, 1);
789        assert_eq!(cloud.sh_rest_per_channel(), 3);
790        assert_eq!(cloud.sh.len(), 9);
791        assert!((cloud.sh[8] - 0.8).abs() < 1e-6);
792    }
793
794    #[test]
795    fn skips_unrelated_properties_via_offsets() {
796        let mut properties = vec!["x", "y", "z", "nx", "ny", "nz"];
797        properties.extend([
798            "f_dc_0", "f_dc_1", "f_dc_2", "opacity", "scale_0", "scale_1", "scale_2", "rot_0",
799            "rot_1", "rot_2", "rot_3",
800        ]);
801        let vertex = vec![
802            1.0, 2.0, 3.0, 9.0, 9.0, 9.0, 0.5, 0.6, 0.7, 1.2, -2.0, -2.1, -2.2, 1.0, 0.0, 0.0, 0.0,
803        ];
804
805        let file = write_ply(&properties, &[vertex], "binary_little_endian");
806        let cloud = read_splat_ply(file.path()).expect("valid ply");
807
808        assert_eq!(
809            cloud.positions[0],
810            [1.0, 2.0, 3.0],
811            "normals must not shift the decoded fields"
812        );
813        assert_eq!(cloud.colors[0], [0.5, 0.6, 0.7]);
814    }
815
816    #[test]
817    fn rejects_ascii_format() {
818        let file = write_ply(&minimal_properties(), &[minimal_vertex(1.0)], "ascii");
819        let err = read_splat_ply(file.path()).expect_err("ascii is unsupported");
820        assert!(matches!(err, GeolithError::Ply(_)));
821    }
822
823    #[test]
824    fn rejects_missing_required_property() {
825        let properties: Vec<&str> = minimal_properties()
826            .into_iter()
827            .filter(|p| *p != "opacity")
828            .collect();
829        let vertex = vec![
830            1.0, 2.0, 3.0, 0.5, 0.6, 0.7, -2.0, -2.1, -2.2, 1.0, 0.0, 0.0, 0.0,
831        ];
832        let file = write_ply(&properties, &[vertex], "binary_little_endian");
833
834        let err = read_splat_ply(file.path()).expect_err("opacity is required");
835        assert!(
836            format!("{err}").contains("opacity"),
837            "error names the missing property: {err}"
838        );
839    }
840
841    #[test]
842    fn rejects_truncated_payload() {
843        let file = write_ply(
844            &minimal_properties(),
845            &[minimal_vertex(1.0)],
846            "binary_little_endian",
847        );
848        let mut bytes = std::fs::read(file.path()).expect("read");
849        bytes.truncate(bytes.len() - 8);
850        std::fs::write(file.path(), &bytes).expect("truncate");
851
852        let err = read_splat_ply(file.path()).expect_err("truncated payload");
853        assert!(format!("{err}").contains("truncated"), "{err}");
854    }
855
856    #[test]
857    fn rejects_non_ply_file() {
858        let mut file = tempfile::NamedTempFile::new().expect("temp");
859        file.write_all(b"not a ply\n").expect("write");
860        file.flush().expect("flush");
861        let err = read_splat_ply(file.path()).expect_err("bad magic");
862        assert!(format!("{err}").contains("ply"), "{err}");
863    }
864
865    #[test]
866    fn sh_degree_mapping_matches_trainer_layouts() {
867        assert_eq!(sh_degree_from_rest_count(0).expect("degree 0"), 0);
868        assert_eq!(sh_degree_from_rest_count(9).expect("degree 1"), 1);
869        assert_eq!(sh_degree_from_rest_count(24).expect("degree 2"), 2);
870        assert_eq!(sh_degree_from_rest_count(45).expect("degree 3"), 3);
871    }
872
873    #[test]
874    fn sh_degree_rejects_invalid_counts() {
875        assert!(sh_degree_from_rest_count(7).is_err(), "not a multiple of 3");
876        assert!(sh_degree_from_rest_count(12).is_err(), "no matching degree");
877    }
878
879    #[test]
880    fn scalar_types_report_their_widths() {
881        assert_eq!(ScalarType::parse("float").expect("float").size(), 4);
882        assert_eq!(ScalarType::parse("double").expect("double").size(), 8);
883        assert_eq!(ScalarType::parse("uchar").expect("uchar").size(), 1);
884        assert_eq!(ScalarType::parse("ushort").expect("ushort").size(), 2);
885        assert_eq!(ScalarType::parse("int").expect("int").size(), 4);
886        assert!(ScalarType::parse("quadruple").is_none());
887    }
888
889    #[test]
890    fn scalar_types_decode_little_endian() {
891        assert!((ScalarType::Float32.read_le(&1.5_f32.to_le_bytes()) - 1.5).abs() < 1e-9);
892        assert!((ScalarType::Float64.read_le(&2.5_f64.to_le_bytes()) - 2.5).abs() < 1e-9);
893        assert!((ScalarType::Uint8.read_le(&[255]) - 255.0).abs() < 1e-9);
894        assert!((ScalarType::Int8.read_le(&[0xFF]) + 1.0).abs() < 1e-9);
895        assert!((ScalarType::Int16.read_le(&(-2_i16).to_le_bytes()) + 2.0).abs() < 1e-9);
896        assert!((ScalarType::Uint16.read_le(&7_u16.to_le_bytes()) - 7.0).abs() < 1e-9);
897        assert!((ScalarType::Int32.read_le(&(-9_i32).to_le_bytes()) + 9.0).abs() < 1e-9);
898        assert!((ScalarType::Uint32.read_le(&11_u32.to_le_bytes()) - 11.0).abs() < 1e-9);
899    }
900
901    #[test]
902    fn bounds_span_every_splat() {
903        let file = write_ply(
904            &minimal_properties(),
905            &[minimal_vertex(-5.0), minimal_vertex(7.0)],
906            "binary_little_endian",
907        );
908        let cloud = read_splat_ply(file.path()).expect("valid ply");
909        let (min, max) = cloud.bounds().expect("non-empty");
910        assert_eq!(min[0], -5.0);
911        assert_eq!(max[0], 7.0);
912    }
913
914    #[test]
915    fn bounds_is_none_for_empty_cloud() {
916        assert!(SplatCloud::default().bounds().is_none());
917        assert!(SplatCloud::default().is_empty());
918    }
919
920    #[test]
921    fn subset_selects_requested_splats_with_sh() {
922        let mut properties = minimal_properties();
923        for i in 0..9 {
924            properties.push(Box::leak(format!("f_rest_{i}").into_boxed_str()));
925        }
926        let mut first = minimal_vertex(1.0);
927        first.extend(std::iter::repeat_n(1.0_f32, 9));
928        let mut second = minimal_vertex(2.0);
929        second.extend(std::iter::repeat_n(2.0_f32, 9));
930
931        let file = write_ply(&properties, &[first, second], "binary_little_endian");
932        let cloud = read_splat_ply(file.path()).expect("valid ply");
933
934        let subset = cloud.subset(&[1]).expect("valid index");
935        assert_eq!(subset.len(), 1);
936        assert_eq!(subset.positions[0][0], 2.0);
937        assert_eq!(subset.sh.len(), 9);
938        assert!(subset.sh.iter().all(|v| (*v - 2.0).abs() < 1e-6));
939        assert_eq!(subset.sh_degree, cloud.sh_degree);
940    }
941
942    #[test]
943    fn subset_rejects_out_of_range_index() {
944        let file = write_ply(
945            &minimal_properties(),
946            &[minimal_vertex(1.0)],
947            "binary_little_endian",
948        );
949        let cloud = read_splat_ply(file.path()).expect("valid ply");
950        assert!(cloud.subset(&[5]).is_err());
951    }
952
953    #[test]
954    fn header_records_the_payload_offset() {
955        let file = write_ply(
956            &minimal_properties(),
957            &[minimal_vertex(1.0)],
958            "binary_little_endian",
959        );
960        let mut handle = File::open(file.path()).expect("open");
961        let header = parse_header(&mut handle, file.path()).expect("header");
962        assert_eq!(header.count, 1);
963        assert_eq!(header.stride, 14 * 4);
964    }
965
966    fn write_raw_header(header: &str) -> tempfile::NamedTempFile {
967        let mut file = tempfile::NamedTempFile::new().expect("temp file");
968        file.write_all(header.as_bytes()).expect("write header");
969        file.flush().expect("flush");
970        file
971    }
972
973    #[test]
974    fn scalar_type_aliases_all_resolve() {
975        for (alias, expected) in [
976            ("float32", ScalarType::Float32),
977            ("float64", ScalarType::Float64),
978            ("char", ScalarType::Int8),
979            ("int8", ScalarType::Int8),
980            ("uint8", ScalarType::Uint8),
981            ("short", ScalarType::Int16),
982            ("int16", ScalarType::Int16),
983            ("uint16", ScalarType::Uint16),
984            ("int32", ScalarType::Int32),
985            ("uint", ScalarType::Uint32),
986            ("uint32", ScalarType::Uint32),
987        ] {
988            assert_eq!(
989                ScalarType::parse(alias),
990                Some(expected),
991                "'{alias}' must resolve"
992            );
993        }
994    }
995
996    #[test]
997    fn rejects_a_header_without_end_header() {
998        let file = write_raw_header("ply\nformat binary_little_endian 1.0\nelement vertex 1\n");
999        let err = read_splat_ply(file.path()).expect_err("header never terminates");
1000        assert!(format!("{err}").contains("end_header"), "{err}");
1001    }
1002
1003    #[test]
1004    fn rejects_a_header_without_a_format_line() {
1005        let file = write_raw_header("ply\nelement vertex 0\nend_header\n");
1006        let err = read_splat_ply(file.path()).expect_err("no format declaration");
1007        assert!(format!("{err}").contains("no format line"), "{err}");
1008    }
1009
1010    #[test]
1011    fn rejects_a_header_without_a_vertex_element() {
1012        let file =
1013            write_raw_header("ply\nformat binary_little_endian 1.0\nelement face 0\nend_header\n");
1014        let err = read_splat_ply(file.path()).expect_err("no vertex element");
1015        assert!(format!("{err}").contains("no 'vertex' element"), "{err}");
1016    }
1017
1018    #[test]
1019    fn rejects_an_unparseable_vertex_count() {
1020        let file = write_raw_header(
1021            "ply\nformat binary_little_endian 1.0\nelement vertex many\nend_header\n",
1022        );
1023        let err = read_splat_ply(file.path()).expect_err("bad count");
1024        assert!(format!("{err}").contains("bad vertex count"), "{err}");
1025    }
1026
1027    #[test]
1028    fn rejects_list_properties_inside_the_vertex_element() {
1029        let file = write_raw_header(
1030            "ply\nformat binary_little_endian 1.0\nelement vertex 1\n\
1031             property list uchar int vertex_indices\nend_header\n",
1032        );
1033        let err = read_splat_ply(file.path()).expect_err("list property");
1034        assert!(format!("{err}").contains("list properties"), "{err}");
1035    }
1036
1037    #[test]
1038    fn allows_list_properties_outside_the_vertex_element() {
1039        let file = write_raw_header(
1040            "ply\nformat binary_little_endian 1.0\nelement face 0\n\
1041             property list uchar int vertex_indices\nelement vertex 0\n\
1042             property float x\nproperty float y\nproperty float z\n\
1043             property float f_dc_0\nproperty float f_dc_1\nproperty float f_dc_2\n\
1044             property float opacity\nproperty float scale_0\nproperty float scale_1\n\
1045             property float scale_2\nproperty float rot_0\nproperty float rot_1\n\
1046             property float rot_2\nproperty float rot_3\nend_header\n",
1047        );
1048        let cloud = read_splat_ply(file.path()).expect("face lists are ignored");
1049        assert!(cloud.is_empty(), "the vertex element declares no splats");
1050    }
1051
1052    #[test]
1053    fn rejects_an_unsupported_property_type() {
1054        let file = write_raw_header(
1055            "ply\nformat binary_little_endian 1.0\nelement vertex 1\n\
1056             property quadruple x\nend_header\n",
1057        );
1058        let err = read_splat_ply(file.path()).expect_err("unknown scalar type");
1059        assert!(
1060            format!("{err}").contains("unsupported property type"),
1061            "{err}"
1062        );
1063    }
1064
1065    #[test]
1066    fn ignores_properties_declared_outside_the_vertex_element() {
1067        let mut properties = minimal_properties();
1068        properties.push("f_rest_0");
1069        properties.push("f_rest_1");
1070        properties.push("f_rest_2");
1071        properties.push("f_rest_3");
1072        properties.push("f_rest_4");
1073        properties.push("f_rest_5");
1074        properties.push("f_rest_6");
1075        properties.push("f_rest_7");
1076        properties.push("f_rest_8");
1077
1078        let mut vertex = minimal_vertex(1.0);
1079        vertex.extend(std::iter::repeat_n(0.25_f32, 9));
1080
1081        let mut header = String::from("ply\nformat binary_little_endian 1.0\n");
1082        header.push_str("element vertex 1\n");
1083        for property in &properties {
1084            header.push_str(&format!("property float {property}\n"));
1085        }
1086        header.push_str("element face 2\nproperty float unused\nend_header\n");
1087
1088        let mut file = tempfile::NamedTempFile::new().expect("temp file");
1089        file.write_all(header.as_bytes()).expect("header");
1090        for value in &vertex {
1091            file.write_all(&value.to_le_bytes()).expect("vertex");
1092        }
1093        file.flush().expect("flush");
1094
1095        let cloud = read_splat_ply(file.path()).expect("trailing element is ignored");
1096        assert_eq!(cloud.len(), 1);
1097        assert_eq!(
1098            cloud.sh.len(),
1099            9,
1100            "the face element's property must not join the vertex stride"
1101        );
1102    }
1103
1104    #[test]
1105    fn rejects_a_non_multiple_of_three_rest_count() {
1106        let mut properties = minimal_properties();
1107        for i in 0..4 {
1108            properties.push(Box::leak(format!("f_rest_{i}").into_boxed_str()));
1109        }
1110        let mut vertex = minimal_vertex(1.0);
1111        vertex.extend(std::iter::repeat_n(0.1_f32, 4));
1112
1113        let file = write_ply(&properties, &[vertex], "binary_little_endian");
1114        let err = read_splat_ply(file.path()).expect_err("4 rest values is not a valid layout");
1115        assert!(format!("{err}").contains("not a multiple of 3"), "{err}");
1116    }
1117
1118    #[test]
1119    fn rejects_a_rest_count_with_no_matching_degree() {
1120        let mut properties = minimal_properties();
1121        for i in 0..12 {
1122            properties.push(Box::leak(format!("f_rest_{i}").into_boxed_str()));
1123        }
1124        let mut vertex = minimal_vertex(1.0);
1125        vertex.extend(std::iter::repeat_n(0.1_f32, 12));
1126
1127        let file = write_ply(&properties, &[vertex], "binary_little_endian");
1128        let err = read_splat_ply(file.path()).expect_err("12 maps to no SH degree");
1129        assert!(format!("{err}").contains("no SH degree"), "{err}");
1130    }
1131
1132    #[test]
1133    fn reads_degree_two_and_degree_three_clouds() {
1134        for (rest, expected_degree) in [(24_usize, 2_u8), (45, 3)] {
1135            let mut properties = minimal_properties();
1136            for i in 0..rest {
1137                properties.push(Box::leak(format!("f_rest_{i}").into_boxed_str()));
1138            }
1139            let mut vertex = minimal_vertex(1.0);
1140            vertex.extend((0..rest).map(|i| i as f32 * 0.01));
1141
1142            let file = write_ply(&properties, &[vertex], "binary_little_endian");
1143            let cloud = read_splat_ply(file.path()).expect("valid ply");
1144            assert_eq!(cloud.sh_degree, expected_degree);
1145            assert_eq!(cloud.sh.len(), rest);
1146        }
1147    }
1148
1149    #[test]
1150    fn reads_mixed_width_properties_via_their_declared_types() {
1151        let mut file = tempfile::NamedTempFile::new().expect("temp file");
1152        let header = "ply\nformat binary_little_endian 1.0\nelement vertex 1\n\
1153             property double x\nproperty float y\nproperty float z\n\
1154             property float f_dc_0\nproperty float f_dc_1\nproperty float f_dc_2\n\
1155             property float opacity\nproperty float scale_0\nproperty float scale_1\n\
1156             property float scale_2\nproperty float rot_0\nproperty float rot_1\n\
1157             property float rot_2\nproperty float rot_3\nend_header\n";
1158        file.write_all(header.as_bytes()).expect("header");
1159        file.write_all(&7.5_f64.to_le_bytes()).expect("x as double");
1160        for value in [
1161            2.0_f32, 3.0, 0.5, 0.6, 0.7, 1.2, -2.0, -2.1, -2.2, 1.0, 0.0, 0.0, 0.0,
1162        ] {
1163            file.write_all(&value.to_le_bytes()).expect("value");
1164        }
1165        file.flush().expect("flush");
1166
1167        let cloud = read_splat_ply(file.path()).expect("mixed widths decode");
1168        assert!(
1169            (cloud.positions[0][0] - 7.5).abs() < 1e-6,
1170            "the f64 x is read at its own width"
1171        );
1172        assert!((cloud.positions[0][1] - 2.0).abs() < 1e-6);
1173    }
1174
1175    #[test]
1176    fn crop_percentile_removes_the_outlier_shell() {
1177        let mut cloud = SplatCloud {
1178            sh_degree: 0,
1179            ..SplatCloud::default()
1180        };
1181        for i in 0..100 {
1182            cloud.positions.push([i as f32 * 0.01, 0.0, 0.0]);
1183            cloud.colors.push([0.1, 0.2, 0.3]);
1184            cloud.opacities.push(1.0);
1185            cloud.scales.push([-3.0; 3]);
1186            cloud.rotations.push([1.0, 0.0, 0.0, 0.0]);
1187        }
1188        cloud.positions[0] = [-1000.0, 0.0, 0.0];
1189        cloud.positions[99] = [1000.0, 0.0, 0.0];
1190
1191        let cropped = cloud.crop_percentile(2.0).expect("valid percentile");
1192        assert!(
1193            cropped.len() < cloud.len(),
1194            "the hallucinated far-field splats are dropped"
1195        );
1196        let (min, max) = cropped.bounds().expect("non-empty");
1197        assert!(min[0] > -1000.0 && max[0] < 1000.0, "outliers excluded");
1198    }
1199
1200    #[test]
1201    fn crop_percentile_zero_keeps_every_splat() {
1202        let file = write_ply(
1203            &minimal_properties(),
1204            &[minimal_vertex(1.0), minimal_vertex(2.0)],
1205            "binary_little_endian",
1206        );
1207        let cloud = read_splat_ply(file.path()).expect("valid ply");
1208        let cropped = cloud.crop_percentile(0.0).expect("no-op crop");
1209        assert_eq!(cropped.len(), cloud.len());
1210    }
1211
1212    #[test]
1213    fn crop_percentile_rejects_a_degenerate_fraction() {
1214        let cloud = SplatCloud::default();
1215        assert!(
1216            cloud.crop_percentile(50.0).is_err(),
1217            "50% from both ends leaves nothing"
1218        );
1219        assert!(cloud.crop_percentile(-1.0).is_err());
1220    }
1221
1222    #[test]
1223    fn crop_radial_percentile_zero_keeps_every_splat() {
1224        let cloud = build_radial_cloud();
1225        let cropped = cloud.crop_radial_percentile(0.0).expect("no-op crop");
1226        assert_eq!(cropped.len(), cloud.len());
1227    }
1228
1229    #[test]
1230    fn crop_radial_percentile_drops_the_outer_shell() {
1231        let cloud = build_radial_cloud();
1232        let cropped = cloud.crop_radial_percentile(1.0).expect("radial crop");
1233        assert_eq!(cropped.len(), cloud.len() - 1, "one far outlier removed");
1234    }
1235
1236    #[test]
1237    fn crop_radial_percentile_rejects_a_degenerate_fraction() {
1238        let cloud = SplatCloud::default();
1239        assert!(cloud.crop_radial_percentile(50.0).is_err());
1240        assert!(cloud.crop_radial_percentile(-1.0).is_err());
1241    }
1242
1243    fn build_radial_cloud() -> SplatCloud {
1244        let mut cloud = SplatCloud {
1245            positions: Vec::with_capacity(101),
1246            ..SplatCloud::default()
1247        };
1248        // 100 splats clustered near the origin.
1249        for i in 0..100 {
1250            let theta = (i as f32) * 0.0628318;
1251            cloud.positions.push([theta.cos(), theta.sin(), 0.0]);
1252            cloud.colors.push([0.5, 0.6, 0.7]);
1253            cloud.opacities.push(1.0);
1254            cloud.scales.push([-3.0; 3]);
1255            cloud.rotations.push([1.0, 0.0, 0.0, 0.0]);
1256        }
1257        // One splat far from the centroid: the radial crop must remove it.
1258        cloud.positions.push([100.0, 100.0, 100.0]);
1259        cloud.colors.push([0.5, 0.6, 0.7]);
1260        cloud.opacities.push(1.0);
1261        cloud.scales.push([-3.0; 3]);
1262        cloud.rotations.push([1.0, 0.0, 0.0, 0.0]);
1263        cloud
1264    }
1265
1266    #[test]
1267    fn rescale_scales_positions_and_log_scales_together() {
1268        let file = write_ply(
1269            &minimal_properties(),
1270            &[minimal_vertex(2.0)],
1271            "binary_little_endian",
1272        );
1273        let mut cloud = read_splat_ply(file.path()).expect("valid ply");
1274        let original_scale = cloud.scales[0][0];
1275
1276        cloud.rescale(0.5);
1277
1278        assert!(
1279            (cloud.positions[0][0] - 1.0).abs() < 1e-6,
1280            "positions halve"
1281        );
1282        assert!(
1283            (cloud.scales[0][0] - (original_scale + 0.5_f32.ln())).abs() < 1e-6,
1284            "log-scales shift by ln(factor) so splat footprints shrink with the scene"
1285        );
1286    }
1287
1288    #[test]
1289    fn rescale_by_one_is_identity() {
1290        let file = write_ply(
1291            &minimal_properties(),
1292            &[minimal_vertex(3.0)],
1293            "binary_little_endian",
1294        );
1295        let mut cloud = read_splat_ply(file.path()).expect("valid ply");
1296        let before = (cloud.positions[0], cloud.scales[0]);
1297        cloud.rescale(1.0);
1298        assert_eq!(before, (cloud.positions[0], cloud.scales[0]));
1299    }
1300
1301    #[test]
1302    fn coverage_boost_shifts_logits_and_shrinks_log_scales() {
1303        let file = write_ply(
1304            &minimal_properties(),
1305            &[minimal_vertex(1.0)],
1306            "binary_little_endian",
1307        );
1308        let mut cloud = read_splat_ply(file.path()).expect("valid ply");
1309        let logit_before = cloud.opacities[0];
1310        let scale_before = cloud.scales[0];
1311
1312        cloud.coverage_boost(8.0);
1313
1314        let expected = 8.0_f32.ln();
1315        assert!(
1316            (cloud.opacities[0] - (logit_before + expected)).abs() < 1e-5,
1317            "logits shift by ln(boost)"
1318        );
1319        for (got, want) in cloud.scales[0].iter().zip(scale_before) {
1320            assert!(
1321                (got - (want - 0.5 * expected)).abs() < 1e-5,
1322                "log-scales shrink by half ln(boost)"
1323            );
1324        }
1325    }
1326
1327    #[test]
1328    fn coverage_boost_at_or_below_one_is_identity() {
1329        let file = write_ply(
1330            &minimal_properties(),
1331            &[minimal_vertex(1.0)],
1332            "binary_little_endian",
1333        );
1334        let mut cloud = read_splat_ply(file.path()).expect("valid ply");
1335        let before = (cloud.opacities[0], cloud.scales[0]);
1336        cloud.coverage_boost(1.0);
1337        assert_eq!(before, (cloud.opacities[0], cloud.scales[0]));
1338        cloud.coverage_boost(0.0);
1339        assert_eq!(before, (cloud.opacities[0], cloud.scales[0]));
1340    }
1341
1342    #[test]
1343    fn subset_of_an_empty_index_list_is_empty() {
1344        let file = write_ply(
1345            &minimal_properties(),
1346            &[minimal_vertex(1.0)],
1347            "binary_little_endian",
1348        );
1349        let cloud = read_splat_ply(file.path()).expect("valid ply");
1350        let subset = cloud.subset(&[]).expect("empty selection is valid");
1351        assert!(subset.is_empty());
1352        assert_eq!(subset.sh_degree, cloud.sh_degree);
1353    }
1354
1355    #[test]
1356    fn parses_vertical_axis_comment() {
1357        assert_eq!(
1358            parse_vertical_axis_comment(&["Vertical", "axis:", "0", "0", "-1"]),
1359            Some([0.0, 0.0, -1.0])
1360        );
1361        let parsed = parse_vertical_axis_comment(&[
1362            "Vertical",
1363            "axis:",
1364            "-0.07945679",
1365            "-0.9641912",
1366            "-0.25302535",
1367        ])
1368        .expect("axis parsed");
1369        for (got, want) in parsed.iter().zip([-0.07945679, -0.9641912, -0.25302535]) {
1370            assert!((got - want).abs() < 1e-6, "axis component {got} != {want}");
1371        }
1372        // Non-axis comments are ignored.
1373        assert_eq!(
1374            parse_vertical_axis_comment(&["Exported", "from", "Brush"]),
1375            None
1376        );
1377        assert_eq!(
1378            parse_vertical_axis_comment(&["Vertical", "axis:", "not", "a", "number"]),
1379            None
1380        );
1381        // A zero-length vector is rejected.
1382        assert_eq!(
1383            parse_vertical_axis_comment(&["Vertical", "axis:", "0", "0", "0"]),
1384            None
1385        );
1386    }
1387
1388    #[test]
1389    fn reads_vertical_axis_from_ply_header() {
1390        let mut file = tempfile::NamedTempFile::new().expect("temp file");
1391        let mut header = String::from("ply\nformat binary_little_endian 1.0\n");
1392        header.push_str("comment Exported from Brush\n");
1393        header.push_str("comment Vertical axis: -0.07945679 -0.9641912 -0.25302535\n");
1394        header.push_str("comment SH degree: 3\n");
1395        header.push_str(&format!("element vertex {}\n", 1));
1396        for property in minimal_properties() {
1397            header.push_str(&format!("property float {property}\n"));
1398        }
1399        header.push_str("end_header\n");
1400        file.write_all(header.as_bytes()).expect("write header");
1401        for value in minimal_vertex(1.0) {
1402            file.write_all(&value.to_le_bytes()).expect("write value");
1403        }
1404        file.flush().expect("flush");
1405
1406        let cloud = read_splat_ply(file.path()).expect("valid ply");
1407        assert!(
1408            cloud.vertical_axis.is_none(),
1409            "axis consumed after orientation"
1410        );
1411    }
1412
1413    #[test]
1414    fn orients_declared_up_to_negative_z() {
1415        // A cloud whose declared up is +Y (like brush's -Y convention rotated).
1416        let mut cloud = SplatCloud {
1417            positions: vec![[0.0, 10.0, 0.0], [0.0, 0.0, 0.0]],
1418            colors: vec![[0.5, 0.6, 0.7]; 2],
1419            opacities: vec![1.0; 2],
1420            scales: vec![[-2.0; 3]; 2],
1421            rotations: vec![[1.0, 0.0, 0.0, 0.0]; 2],
1422            sh: vec![],
1423            sh_degree: 0,
1424            vertical_axis: Some([0.0, 1.0, 0.0]),
1425        };
1426        cloud.orient_to_negative_z();
1427        // +Y up → -Z up: the point above the origin should land on -Z.
1428        assert!(
1429            (cloud.positions[0][2] + 10.0).abs() < 1e-5,
1430            "expected point at -Z, got {:?}",
1431            cloud.positions[0]
1432        );
1433        assert!((cloud.positions[0][0]).abs() < 1e-5);
1434        assert!((cloud.positions[0][1]).abs() < 1e-5);
1435        // The rotation quaternion is a 90° rotation about X.
1436        let q = cloud.rotations[0];
1437        assert!(
1438            (q[0].abs() - 2.0_f32.sqrt() / 2.0).abs() < 1e-5,
1439            "q = {q:?}"
1440        );
1441        assert!(
1442            (q[1].abs() - 2.0_f32.sqrt() / 2.0).abs() < 1e-5,
1443            "q = {q:?}"
1444        );
1445    }
1446
1447    #[test]
1448    fn orientation_is_noop_without_declared_axis() {
1449        let mut cloud = SplatCloud::default();
1450        cloud.positions.push([1.0, 2.0, 3.0]);
1451        cloud.rotations.push([1.0, 0.0, 0.0, 0.0]);
1452        cloud.orient_to_negative_z();
1453        assert_eq!(cloud.positions[0], [1.0, 2.0, 3.0]);
1454    }
1455
1456    #[test]
1457    fn orientation_is_noop_when_already_negative_z() {
1458        let mut cloud = SplatCloud {
1459            vertical_axis: Some([0.0, 0.0, -1.0]),
1460            positions: vec![[1.0, 2.0, 3.0]],
1461            ..SplatCloud::default()
1462        };
1463        cloud.orient_to_negative_z();
1464        assert_eq!(cloud.positions[0], [1.0, 2.0, 3.0]);
1465    }
1466
1467    #[test]
1468    fn orientation_preserves_distances_and_unit_quaternions() {
1469        let mut cloud = SplatCloud {
1470            vertical_axis: Some([0.0, 1.0, 0.0]),
1471            positions: vec![[0.0, 0.0, 0.0], [3.0, 4.0, 0.0], [-1.0, 2.0, -5.0]],
1472            rotations: vec![
1473                [1.0, 0.0, 0.0, 0.0],
1474                [0.5, 0.5, 0.5, 0.5],
1475                [0.5, -0.5, 0.5, 0.5],
1476            ],
1477            ..SplatCloud::default()
1478        };
1479        let before = cloud.positions[1];
1480        cloud.orient_to_negative_z();
1481        // Distance from origin is preserved under a rigid rotation.
1482        let after = cloud.positions[1];
1483        let before_norm =
1484            (before[0] * before[0] + before[1] * before[1] + before[2] * before[2]).sqrt();
1485        let after_norm = (after[0] * after[0] + after[1] * after[1] + after[2] * after[2]).sqrt();
1486        assert!((before_norm - after_norm).abs() < 1e-4);
1487        for q in &cloud.rotations {
1488            let norm = (q[0] * q[0] + q[1] * q[1] + q[2] * q[2] + q[3] * q[3]).sqrt();
1489            assert!((norm - 1.0).abs() < 1e-4, "quaternion not unit: {q:?}");
1490        }
1491    }
1492}