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    // The count comes from the header, which the file does not vouch for:
469    // multiply without wrapping, and ask for no buffer the file could not fill.
470    let expected = header.count.checked_mul(header.stride).ok_or_else(|| {
471        GeolithError::Ply(format!(
472            "{}: {} vertices of {} bytes do not fit in memory",
473            path.display(),
474            header.count,
475            header.stride
476        ))
477    })?;
478    let file_len = usize::try_from(file.metadata()?.len()).unwrap_or(usize::MAX);
479    if expected > file_len {
480        return Err(GeolithError::Ply(format!(
481            "{}: truncated vertex data — expected {expected} bytes, the file has {file_len}",
482            path.display(),
483        )));
484    }
485    let mut buffer = Vec::with_capacity(expected);
486    file.read_to_end(&mut buffer)?;
487    if buffer.len() < expected {
488        return Err(GeolithError::Ply(format!(
489            "{}: truncated vertex data — expected {expected} bytes, found {}",
490            path.display(),
491            buffer.len()
492        )));
493    }
494
495    let mut cloud = decode_vertices(&header, &buffer)?;
496    cloud.orient_to_negative_z();
497    Ok(cloud)
498}
499
500/// Parse the ASCII header and leave the reader positioned at the payload.
501fn parse_header(file: &mut File, path: &Path) -> Result<PlyHeader> {
502    let mut reader = BufReader::new(file.try_clone()?);
503    let mut consumed = 0_usize;
504    let mut line = String::new();
505
506    reader.read_line(&mut line)?;
507    consumed += line.len();
508    if line.trim() != "ply" {
509        return Err(GeolithError::Ply(format!(
510            "{}: not a PLY file (missing 'ply' magic)",
511            path.display()
512        )));
513    }
514
515    let mut count = None;
516    let mut properties: Vec<Property> = Vec::new();
517    let mut offset = 0_usize;
518    let mut in_vertex_element = false;
519    let mut saw_format = false;
520    let mut vertical_axis: Option<[f32; 3]> = None;
521
522    loop {
523        line.clear();
524        let read = reader.read_line(&mut line)?;
525        if read == 0 {
526            return Err(GeolithError::Ply(format!(
527                "{}: header ended before 'end_header'",
528                path.display()
529            )));
530        }
531        consumed += read;
532        let trimmed = line.trim();
533        let tokens: Vec<&str> = trimmed.split_whitespace().collect();
534
535        match tokens.as_slice() {
536            ["format", encoding, ..] => {
537                saw_format = true;
538                if *encoding != "binary_little_endian" {
539                    return Err(GeolithError::Ply(format!(
540                        "{}: unsupported PLY format '{encoding}' — \
541                         only binary_little_endian is supported",
542                        path.display()
543                    )));
544                }
545            }
546            ["element", name, n] => {
547                in_vertex_element = *name == "vertex";
548                if in_vertex_element {
549                    count = Some(n.parse::<usize>().map_err(|e| {
550                        GeolithError::Ply(format!(
551                            "{}: bad vertex count '{n}': {e}",
552                            path.display()
553                        ))
554                    })?);
555                }
556            }
557            ["property", "list", ..] => {
558                if in_vertex_element {
559                    return Err(GeolithError::Ply(format!(
560                        "{}: list properties are not supported in the vertex element",
561                        path.display()
562                    )));
563                }
564            }
565            ["property", ty, name] => {
566                if in_vertex_element {
567                    let scalar = ScalarType::parse(ty).ok_or_else(|| {
568                        GeolithError::Ply(format!(
569                            "{}: unsupported property type '{ty}' for '{name}'",
570                            path.display()
571                        ))
572                    })?;
573                    properties.push(Property {
574                        name: (*name).to_owned(),
575                        ty: scalar,
576                        offset,
577                    });
578                    offset += scalar.size();
579                }
580            }
581            ["end_header"] => break,
582            ["comment", rest @ ..] => {
583                if let Some(axis) = parse_vertical_axis_comment(rest) {
584                    vertical_axis = Some(axis);
585                }
586            }
587            _ => {}
588        }
589    }
590
591    if !saw_format {
592        return Err(GeolithError::Ply(format!(
593            "{}: header has no format line",
594            path.display()
595        )));
596    }
597
598    let count = count.ok_or_else(|| {
599        GeolithError::Ply(format!("{}: no 'vertex' element declared", path.display()))
600    })?;
601
602    use std::io::Seek as _;
603    file.seek(std::io::SeekFrom::Start(consumed as u64))?;
604
605    Ok(PlyHeader {
606        count,
607        stride: offset,
608        properties,
609        vertical_axis,
610    })
611}
612
613/// Parse a `comment Vertical axis: x y z` PLY header line.
614///
615/// Brush-style trainers export the scene in their own reference frame and
616/// declare the direction of gravity as a unit vector. Returns `None` for
617/// any other comment line.
618fn parse_vertical_axis_comment(rest: &[&str]) -> Option<[f32; 3]> {
619    let ["Vertical", "axis:", x, y, z] = rest else {
620        return None;
621    };
622    let x = x.parse::<f32>().ok()?;
623    let y = y.parse::<f32>().ok()?;
624    let z = z.parse::<f32>().ok()?;
625    let norm = (x * x + y * y + z * z).sqrt();
626    if norm < f32::EPSILON || !norm.is_finite() {
627        return None;
628    }
629    Some([x / norm, y / norm, z / norm])
630}
631
632/// Decode the vertex payload into a [`SplatCloud`].
633fn decode_vertices(header: &PlyHeader, buffer: &[u8]) -> Result<SplatCloud> {
634    let x = header.require("x")?;
635    let y = header.require("y")?;
636    let z = header.require("z")?;
637    let opacity = header.require("opacity")?;
638    let f_dc: Vec<&Property> = (0..3)
639        .map(|i| header.require(&format!("f_dc_{i}")))
640        .collect::<Result<_>>()?;
641    let scale: Vec<&Property> = (0..3)
642        .map(|i| header.require(&format!("scale_{i}")))
643        .collect::<Result<_>>()?;
644    let rot: Vec<&Property> = (0..4)
645        .map(|i| header.require(&format!("rot_{i}")))
646        .collect::<Result<_>>()?;
647
648    let rest_count = (0..)
649        .take_while(|i| header.find(&format!("f_rest_{i}")).is_some())
650        .count();
651    let sh_degree = sh_degree_from_rest_count(rest_count)?;
652    let rest_per_channel = SH_REST_PER_CHANNEL[sh_degree as usize];
653
654    let rest: Vec<&Property> = (0..rest_per_channel * 3)
655        .map(|i| header.require(&format!("f_rest_{i}")))
656        .collect::<Result<_>>()?;
657
658    let n = header.count;
659    let mut cloud = SplatCloud {
660        positions: Vec::with_capacity(n),
661        colors: Vec::with_capacity(n),
662        opacities: Vec::with_capacity(n),
663        scales: Vec::with_capacity(n),
664        rotations: Vec::with_capacity(n),
665        sh: Vec::with_capacity(n * rest.len()),
666        sh_degree,
667        vertical_axis: header.vertical_axis,
668    };
669
670    let read = |record: &[u8], p: &Property| p.ty.read_le(&record[p.offset..]);
671
672    for record in buffer.chunks_exact(header.stride).take(n) {
673        cloud
674            .positions
675            .push([read(record, x), read(record, y), read(record, z)]);
676        cloud.colors.push([
677            read(record, f_dc[0]),
678            read(record, f_dc[1]),
679            read(record, f_dc[2]),
680        ]);
681        cloud.opacities.push(read(record, opacity));
682        cloud.scales.push([
683            read(record, scale[0]),
684            read(record, scale[1]),
685            read(record, scale[2]),
686        ]);
687        cloud.rotations.push([
688            read(record, rot[0]),
689            read(record, rot[1]),
690            read(record, rot[2]),
691            read(record, rot[3]),
692        ]);
693        for property in &rest {
694            cloud.sh.push(read(record, property));
695        }
696    }
697
698    Ok(cloud)
699}
700
701/// Map an `f_rest_*` property count to its spherical harmonic degree.
702///
703/// The trainers store `3 * coefficients_per_channel` rest values, so the
704/// valid totals are 0, 9, 24 and 45 for degrees 0 through 3.
705fn sh_degree_from_rest_count(rest_count: usize) -> Result<u8> {
706    if !rest_count.is_multiple_of(3) {
707        return Err(GeolithError::Ply(format!(
708            "f_rest_* count {rest_count} is not a multiple of 3"
709        )));
710    }
711    let per_channel = rest_count / 3;
712    SH_REST_PER_CHANNEL
713        .iter()
714        .position(|&c| c == per_channel)
715        .map(|degree| degree as u8)
716        .ok_or_else(|| {
717            GeolithError::Ply(format!(
718                "f_rest_* count {rest_count} maps to no SH degree \
719                 (expected 0, 9, 24 or 45)"
720            ))
721        })
722}
723
724#[cfg(test)]
725mod tests {
726    use super::*;
727    use std::io::Write as _;
728
729    fn write_ply(
730        properties: &[&str],
731        vertices: &[Vec<f32>],
732        format: &str,
733    ) -> tempfile::NamedTempFile {
734        let mut file = tempfile::NamedTempFile::new().expect("temp file");
735        let mut header = String::from("ply\n");
736        header.push_str(&format!("format {format} 1.0\n"));
737        header.push_str(&format!("element vertex {}\n", vertices.len()));
738        for property in properties {
739            header.push_str(&format!("property float {property}\n"));
740        }
741        header.push_str("end_header\n");
742        file.write_all(header.as_bytes()).expect("write header");
743        for vertex in vertices {
744            for value in vertex {
745                file.write_all(&value.to_le_bytes()).expect("write value");
746            }
747        }
748        file.flush().expect("flush");
749        file
750    }
751
752    fn minimal_properties() -> Vec<&'static str> {
753        vec![
754            "x", "y", "z", "f_dc_0", "f_dc_1", "f_dc_2", "opacity", "scale_0", "scale_1",
755            "scale_2", "rot_0", "rot_1", "rot_2", "rot_3",
756        ]
757    }
758
759    fn minimal_vertex(x: f32) -> Vec<f32> {
760        vec![
761            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,
762        ]
763    }
764
765    #[test]
766    fn reads_degree_zero_cloud() {
767        let file = write_ply(
768            &minimal_properties(),
769            &[minimal_vertex(1.0), minimal_vertex(4.0)],
770            "binary_little_endian",
771        );
772        let cloud = read_splat_ply(file.path()).expect("valid ply");
773
774        assert_eq!(cloud.len(), 2);
775        assert!(!cloud.is_empty());
776        assert_eq!(cloud.sh_degree, 0);
777        assert_eq!(cloud.sh_rest_per_channel(), 0);
778        assert_eq!(cloud.positions[0], [1.0, 2.0, 3.0]);
779        assert_eq!(cloud.positions[1], [4.0, 2.0, 3.0]);
780        assert_eq!(cloud.colors[0], [0.5, 0.6, 0.7]);
781        assert_eq!(cloud.opacities[0], 1.2);
782        assert_eq!(cloud.scales[0], [-2.0, -2.1, -2.2]);
783        assert_eq!(
784            cloud.rotations[0],
785            [1.0, 0.0, 0.0, 0.0],
786            "rot_0..3 is stored w,x,y,z"
787        );
788        assert!(cloud.sh.is_empty());
789    }
790
791    #[test]
792    fn reads_degree_one_cloud_with_rest_coefficients() {
793        let mut properties = minimal_properties();
794        for i in 0..9 {
795            properties.push(Box::leak(format!("f_rest_{i}").into_boxed_str()));
796        }
797        let mut vertex = minimal_vertex(1.0);
798        vertex.extend((0..9).map(|i| i as f32 * 0.1));
799
800        let file = write_ply(&properties, &[vertex], "binary_little_endian");
801        let cloud = read_splat_ply(file.path()).expect("valid ply");
802
803        assert_eq!(cloud.sh_degree, 1);
804        assert_eq!(cloud.sh_rest_per_channel(), 3);
805        assert_eq!(cloud.sh.len(), 9);
806        assert!((cloud.sh[8] - 0.8).abs() < 1e-6);
807    }
808
809    #[test]
810    fn skips_unrelated_properties_via_offsets() {
811        let mut properties = vec!["x", "y", "z", "nx", "ny", "nz"];
812        properties.extend([
813            "f_dc_0", "f_dc_1", "f_dc_2", "opacity", "scale_0", "scale_1", "scale_2", "rot_0",
814            "rot_1", "rot_2", "rot_3",
815        ]);
816        let vertex = vec![
817            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,
818        ];
819
820        let file = write_ply(&properties, &[vertex], "binary_little_endian");
821        let cloud = read_splat_ply(file.path()).expect("valid ply");
822
823        assert_eq!(
824            cloud.positions[0],
825            [1.0, 2.0, 3.0],
826            "normals must not shift the decoded fields"
827        );
828        assert_eq!(cloud.colors[0], [0.5, 0.6, 0.7]);
829    }
830
831    #[test]
832    fn rejects_ascii_format() {
833        let file = write_ply(&minimal_properties(), &[minimal_vertex(1.0)], "ascii");
834        let err = read_splat_ply(file.path()).expect_err("ascii is unsupported");
835        assert!(matches!(err, GeolithError::Ply(_)));
836    }
837
838    #[test]
839    fn rejects_missing_required_property() {
840        let properties: Vec<&str> = minimal_properties()
841            .into_iter()
842            .filter(|p| *p != "opacity")
843            .collect();
844        let vertex = vec![
845            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,
846        ];
847        let file = write_ply(&properties, &[vertex], "binary_little_endian");
848
849        let err = read_splat_ply(file.path()).expect_err("opacity is required");
850        assert!(
851            format!("{err}").contains("opacity"),
852            "error names the missing property: {err}"
853        );
854    }
855
856    #[test]
857    fn rejects_truncated_payload() {
858        let file = write_ply(
859            &minimal_properties(),
860            &[minimal_vertex(1.0)],
861            "binary_little_endian",
862        );
863        let mut bytes = std::fs::read(file.path()).expect("read");
864        bytes.truncate(bytes.len() - 8);
865        std::fs::write(file.path(), &bytes).expect("truncate");
866
867        let err = read_splat_ply(file.path()).expect_err("truncated payload");
868        assert!(format!("{err}").contains("truncated"), "{err}");
869    }
870
871    #[test]
872    fn rejects_non_ply_file() {
873        let mut file = tempfile::NamedTempFile::new().expect("temp");
874        file.write_all(b"not a ply\n").expect("write");
875        file.flush().expect("flush");
876        let err = read_splat_ply(file.path()).expect_err("bad magic");
877        assert!(format!("{err}").contains("ply"), "{err}");
878    }
879
880    #[test]
881    fn sh_degree_mapping_matches_trainer_layouts() {
882        assert_eq!(sh_degree_from_rest_count(0).expect("degree 0"), 0);
883        assert_eq!(sh_degree_from_rest_count(9).expect("degree 1"), 1);
884        assert_eq!(sh_degree_from_rest_count(24).expect("degree 2"), 2);
885        assert_eq!(sh_degree_from_rest_count(45).expect("degree 3"), 3);
886    }
887
888    #[test]
889    fn sh_degree_rejects_invalid_counts() {
890        assert!(sh_degree_from_rest_count(7).is_err(), "not a multiple of 3");
891        assert!(sh_degree_from_rest_count(12).is_err(), "no matching degree");
892    }
893
894    #[test]
895    fn scalar_types_report_their_widths() {
896        assert_eq!(ScalarType::parse("float").expect("float").size(), 4);
897        assert_eq!(ScalarType::parse("double").expect("double").size(), 8);
898        assert_eq!(ScalarType::parse("uchar").expect("uchar").size(), 1);
899        assert_eq!(ScalarType::parse("ushort").expect("ushort").size(), 2);
900        assert_eq!(ScalarType::parse("int").expect("int").size(), 4);
901        assert!(ScalarType::parse("quadruple").is_none());
902    }
903
904    #[test]
905    fn scalar_types_decode_little_endian() {
906        assert!((ScalarType::Float32.read_le(&1.5_f32.to_le_bytes()) - 1.5).abs() < 1e-9);
907        assert!((ScalarType::Float64.read_le(&2.5_f64.to_le_bytes()) - 2.5).abs() < 1e-9);
908        assert!((ScalarType::Uint8.read_le(&[255]) - 255.0).abs() < 1e-9);
909        assert!((ScalarType::Int8.read_le(&[0xFF]) + 1.0).abs() < 1e-9);
910        assert!((ScalarType::Int16.read_le(&(-2_i16).to_le_bytes()) + 2.0).abs() < 1e-9);
911        assert!((ScalarType::Uint16.read_le(&7_u16.to_le_bytes()) - 7.0).abs() < 1e-9);
912        assert!((ScalarType::Int32.read_le(&(-9_i32).to_le_bytes()) + 9.0).abs() < 1e-9);
913        assert!((ScalarType::Uint32.read_le(&11_u32.to_le_bytes()) - 11.0).abs() < 1e-9);
914    }
915
916    #[test]
917    fn bounds_span_every_splat() {
918        let file = write_ply(
919            &minimal_properties(),
920            &[minimal_vertex(-5.0), minimal_vertex(7.0)],
921            "binary_little_endian",
922        );
923        let cloud = read_splat_ply(file.path()).expect("valid ply");
924        let (min, max) = cloud.bounds().expect("non-empty");
925        assert_eq!(min[0], -5.0);
926        assert_eq!(max[0], 7.0);
927    }
928
929    #[test]
930    fn bounds_is_none_for_empty_cloud() {
931        assert!(SplatCloud::default().bounds().is_none());
932        assert!(SplatCloud::default().is_empty());
933    }
934
935    #[test]
936    fn subset_selects_requested_splats_with_sh() {
937        let mut properties = minimal_properties();
938        for i in 0..9 {
939            properties.push(Box::leak(format!("f_rest_{i}").into_boxed_str()));
940        }
941        let mut first = minimal_vertex(1.0);
942        first.extend(std::iter::repeat_n(1.0_f32, 9));
943        let mut second = minimal_vertex(2.0);
944        second.extend(std::iter::repeat_n(2.0_f32, 9));
945
946        let file = write_ply(&properties, &[first, second], "binary_little_endian");
947        let cloud = read_splat_ply(file.path()).expect("valid ply");
948
949        let subset = cloud.subset(&[1]).expect("valid index");
950        assert_eq!(subset.len(), 1);
951        assert_eq!(subset.positions[0][0], 2.0);
952        assert_eq!(subset.sh.len(), 9);
953        assert!(subset.sh.iter().all(|v| (*v - 2.0).abs() < 1e-6));
954        assert_eq!(subset.sh_degree, cloud.sh_degree);
955    }
956
957    #[test]
958    fn subset_rejects_out_of_range_index() {
959        let file = write_ply(
960            &minimal_properties(),
961            &[minimal_vertex(1.0)],
962            "binary_little_endian",
963        );
964        let cloud = read_splat_ply(file.path()).expect("valid ply");
965        assert!(cloud.subset(&[5]).is_err());
966    }
967
968    #[test]
969    fn header_records_the_payload_offset() {
970        let file = write_ply(
971            &minimal_properties(),
972            &[minimal_vertex(1.0)],
973            "binary_little_endian",
974        );
975        let mut handle = File::open(file.path()).expect("open");
976        let header = parse_header(&mut handle, file.path()).expect("header");
977        assert_eq!(header.count, 1);
978        assert_eq!(header.stride, 14 * 4);
979    }
980
981    fn write_raw_header(header: &str) -> tempfile::NamedTempFile {
982        let mut file = tempfile::NamedTempFile::new().expect("temp file");
983        file.write_all(header.as_bytes()).expect("write header");
984        file.flush().expect("flush");
985        file
986    }
987
988    #[test]
989    fn scalar_type_aliases_all_resolve() {
990        for (alias, expected) in [
991            ("float32", ScalarType::Float32),
992            ("float64", ScalarType::Float64),
993            ("char", ScalarType::Int8),
994            ("int8", ScalarType::Int8),
995            ("uint8", ScalarType::Uint8),
996            ("short", ScalarType::Int16),
997            ("int16", ScalarType::Int16),
998            ("uint16", ScalarType::Uint16),
999            ("int32", ScalarType::Int32),
1000            ("uint", ScalarType::Uint32),
1001            ("uint32", ScalarType::Uint32),
1002        ] {
1003            assert_eq!(
1004                ScalarType::parse(alias),
1005                Some(expected),
1006                "'{alias}' must resolve"
1007            );
1008        }
1009    }
1010
1011    #[test]
1012    fn rejects_a_header_without_end_header() {
1013        let file = write_raw_header("ply\nformat binary_little_endian 1.0\nelement vertex 1\n");
1014        let err = read_splat_ply(file.path()).expect_err("header never terminates");
1015        assert!(format!("{err}").contains("end_header"), "{err}");
1016    }
1017
1018    #[test]
1019    fn rejects_a_header_without_a_format_line() {
1020        let file = write_raw_header("ply\nelement vertex 0\nend_header\n");
1021        let err = read_splat_ply(file.path()).expect_err("no format declaration");
1022        assert!(format!("{err}").contains("no format line"), "{err}");
1023    }
1024
1025    #[test]
1026    fn rejects_a_header_without_a_vertex_element() {
1027        let file =
1028            write_raw_header("ply\nformat binary_little_endian 1.0\nelement face 0\nend_header\n");
1029        let err = read_splat_ply(file.path()).expect_err("no vertex element");
1030        assert!(format!("{err}").contains("no 'vertex' element"), "{err}");
1031    }
1032
1033    #[test]
1034    fn rejects_an_unparseable_vertex_count() {
1035        let file = write_raw_header(
1036            "ply\nformat binary_little_endian 1.0\nelement vertex many\nend_header\n",
1037        );
1038        let err = read_splat_ply(file.path()).expect_err("bad count");
1039        assert!(format!("{err}").contains("bad vertex count"), "{err}");
1040    }
1041
1042    #[test]
1043    fn rejects_list_properties_inside_the_vertex_element() {
1044        let file = write_raw_header(
1045            "ply\nformat binary_little_endian 1.0\nelement vertex 1\n\
1046             property list uchar int vertex_indices\nend_header\n",
1047        );
1048        let err = read_splat_ply(file.path()).expect_err("list property");
1049        assert!(format!("{err}").contains("list properties"), "{err}");
1050    }
1051
1052    #[test]
1053    fn allows_list_properties_outside_the_vertex_element() {
1054        let file = write_raw_header(
1055            "ply\nformat binary_little_endian 1.0\nelement face 0\n\
1056             property list uchar int vertex_indices\nelement vertex 0\n\
1057             property float x\nproperty float y\nproperty float z\n\
1058             property float f_dc_0\nproperty float f_dc_1\nproperty float f_dc_2\n\
1059             property float opacity\nproperty float scale_0\nproperty float scale_1\n\
1060             property float scale_2\nproperty float rot_0\nproperty float rot_1\n\
1061             property float rot_2\nproperty float rot_3\nend_header\n",
1062        );
1063        let cloud = read_splat_ply(file.path()).expect("face lists are ignored");
1064        assert!(cloud.is_empty(), "the vertex element declares no splats");
1065    }
1066
1067    #[test]
1068    fn rejects_an_unsupported_property_type() {
1069        let file = write_raw_header(
1070            "ply\nformat binary_little_endian 1.0\nelement vertex 1\n\
1071             property quadruple x\nend_header\n",
1072        );
1073        let err = read_splat_ply(file.path()).expect_err("unknown scalar type");
1074        assert!(
1075            format!("{err}").contains("unsupported property type"),
1076            "{err}"
1077        );
1078    }
1079
1080    #[test]
1081    fn ignores_properties_declared_outside_the_vertex_element() {
1082        let mut properties = minimal_properties();
1083        properties.push("f_rest_0");
1084        properties.push("f_rest_1");
1085        properties.push("f_rest_2");
1086        properties.push("f_rest_3");
1087        properties.push("f_rest_4");
1088        properties.push("f_rest_5");
1089        properties.push("f_rest_6");
1090        properties.push("f_rest_7");
1091        properties.push("f_rest_8");
1092
1093        let mut vertex = minimal_vertex(1.0);
1094        vertex.extend(std::iter::repeat_n(0.25_f32, 9));
1095
1096        let mut header = String::from("ply\nformat binary_little_endian 1.0\n");
1097        header.push_str("element vertex 1\n");
1098        for property in &properties {
1099            header.push_str(&format!("property float {property}\n"));
1100        }
1101        header.push_str("element face 2\nproperty float unused\nend_header\n");
1102
1103        let mut file = tempfile::NamedTempFile::new().expect("temp file");
1104        file.write_all(header.as_bytes()).expect("header");
1105        for value in &vertex {
1106            file.write_all(&value.to_le_bytes()).expect("vertex");
1107        }
1108        file.flush().expect("flush");
1109
1110        let cloud = read_splat_ply(file.path()).expect("trailing element is ignored");
1111        assert_eq!(cloud.len(), 1);
1112        assert_eq!(
1113            cloud.sh.len(),
1114            9,
1115            "the face element's property must not join the vertex stride"
1116        );
1117    }
1118
1119    #[test]
1120    fn rejects_a_non_multiple_of_three_rest_count() {
1121        let mut properties = minimal_properties();
1122        for i in 0..4 {
1123            properties.push(Box::leak(format!("f_rest_{i}").into_boxed_str()));
1124        }
1125        let mut vertex = minimal_vertex(1.0);
1126        vertex.extend(std::iter::repeat_n(0.1_f32, 4));
1127
1128        let file = write_ply(&properties, &[vertex], "binary_little_endian");
1129        let err = read_splat_ply(file.path()).expect_err("4 rest values is not a valid layout");
1130        assert!(format!("{err}").contains("not a multiple of 3"), "{err}");
1131    }
1132
1133    #[test]
1134    fn rejects_a_rest_count_with_no_matching_degree() {
1135        let mut properties = minimal_properties();
1136        for i in 0..12 {
1137            properties.push(Box::leak(format!("f_rest_{i}").into_boxed_str()));
1138        }
1139        let mut vertex = minimal_vertex(1.0);
1140        vertex.extend(std::iter::repeat_n(0.1_f32, 12));
1141
1142        let file = write_ply(&properties, &[vertex], "binary_little_endian");
1143        let err = read_splat_ply(file.path()).expect_err("12 maps to no SH degree");
1144        assert!(format!("{err}").contains("no SH degree"), "{err}");
1145    }
1146
1147    #[test]
1148    fn reads_degree_two_and_degree_three_clouds() {
1149        for (rest, expected_degree) in [(24_usize, 2_u8), (45, 3)] {
1150            let mut properties = minimal_properties();
1151            for i in 0..rest {
1152                properties.push(Box::leak(format!("f_rest_{i}").into_boxed_str()));
1153            }
1154            let mut vertex = minimal_vertex(1.0);
1155            vertex.extend((0..rest).map(|i| i as f32 * 0.01));
1156
1157            let file = write_ply(&properties, &[vertex], "binary_little_endian");
1158            let cloud = read_splat_ply(file.path()).expect("valid ply");
1159            assert_eq!(cloud.sh_degree, expected_degree);
1160            assert_eq!(cloud.sh.len(), rest);
1161        }
1162    }
1163
1164    #[test]
1165    fn reads_mixed_width_properties_via_their_declared_types() {
1166        let mut file = tempfile::NamedTempFile::new().expect("temp file");
1167        let header = "ply\nformat binary_little_endian 1.0\nelement vertex 1\n\
1168             property double x\nproperty float y\nproperty float z\n\
1169             property float f_dc_0\nproperty float f_dc_1\nproperty float f_dc_2\n\
1170             property float opacity\nproperty float scale_0\nproperty float scale_1\n\
1171             property float scale_2\nproperty float rot_0\nproperty float rot_1\n\
1172             property float rot_2\nproperty float rot_3\nend_header\n";
1173        file.write_all(header.as_bytes()).expect("header");
1174        file.write_all(&7.5_f64.to_le_bytes()).expect("x as double");
1175        for value in [
1176            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,
1177        ] {
1178            file.write_all(&value.to_le_bytes()).expect("value");
1179        }
1180        file.flush().expect("flush");
1181
1182        let cloud = read_splat_ply(file.path()).expect("mixed widths decode");
1183        assert!(
1184            (cloud.positions[0][0] - 7.5).abs() < 1e-6,
1185            "the f64 x is read at its own width"
1186        );
1187        assert!((cloud.positions[0][1] - 2.0).abs() < 1e-6);
1188    }
1189
1190    #[test]
1191    fn crop_percentile_removes_the_outlier_shell() {
1192        let mut cloud = SplatCloud {
1193            sh_degree: 0,
1194            ..SplatCloud::default()
1195        };
1196        for i in 0..100 {
1197            cloud.positions.push([i as f32 * 0.01, 0.0, 0.0]);
1198            cloud.colors.push([0.1, 0.2, 0.3]);
1199            cloud.opacities.push(1.0);
1200            cloud.scales.push([-3.0; 3]);
1201            cloud.rotations.push([1.0, 0.0, 0.0, 0.0]);
1202        }
1203        cloud.positions[0] = [-1000.0, 0.0, 0.0];
1204        cloud.positions[99] = [1000.0, 0.0, 0.0];
1205
1206        let cropped = cloud.crop_percentile(2.0).expect("valid percentile");
1207        assert!(
1208            cropped.len() < cloud.len(),
1209            "the hallucinated far-field splats are dropped"
1210        );
1211        let (min, max) = cropped.bounds().expect("non-empty");
1212        assert!(min[0] > -1000.0 && max[0] < 1000.0, "outliers excluded");
1213    }
1214
1215    #[test]
1216    fn crop_percentile_zero_keeps_every_splat() {
1217        let file = write_ply(
1218            &minimal_properties(),
1219            &[minimal_vertex(1.0), minimal_vertex(2.0)],
1220            "binary_little_endian",
1221        );
1222        let cloud = read_splat_ply(file.path()).expect("valid ply");
1223        let cropped = cloud.crop_percentile(0.0).expect("no-op crop");
1224        assert_eq!(cropped.len(), cloud.len());
1225    }
1226
1227    #[test]
1228    fn crop_percentile_rejects_a_degenerate_fraction() {
1229        let cloud = SplatCloud::default();
1230        assert!(
1231            cloud.crop_percentile(50.0).is_err(),
1232            "50% from both ends leaves nothing"
1233        );
1234        assert!(cloud.crop_percentile(-1.0).is_err());
1235    }
1236
1237    #[test]
1238    fn crop_radial_percentile_zero_keeps_every_splat() {
1239        let cloud = build_radial_cloud();
1240        let cropped = cloud.crop_radial_percentile(0.0).expect("no-op crop");
1241        assert_eq!(cropped.len(), cloud.len());
1242    }
1243
1244    #[test]
1245    fn crop_radial_percentile_drops_the_outer_shell() {
1246        let cloud = build_radial_cloud();
1247        let cropped = cloud.crop_radial_percentile(1.0).expect("radial crop");
1248        assert_eq!(cropped.len(), cloud.len() - 1, "one far outlier removed");
1249    }
1250
1251    #[test]
1252    fn crop_radial_percentile_rejects_a_degenerate_fraction() {
1253        let cloud = SplatCloud::default();
1254        assert!(cloud.crop_radial_percentile(50.0).is_err());
1255        assert!(cloud.crop_radial_percentile(-1.0).is_err());
1256    }
1257
1258    fn build_radial_cloud() -> SplatCloud {
1259        let mut cloud = SplatCloud {
1260            positions: Vec::with_capacity(101),
1261            ..SplatCloud::default()
1262        };
1263        // 100 splats clustered near the origin.
1264        for i in 0..100 {
1265            let theta = (i as f32) * 0.0628318;
1266            cloud.positions.push([theta.cos(), theta.sin(), 0.0]);
1267            cloud.colors.push([0.5, 0.6, 0.7]);
1268            cloud.opacities.push(1.0);
1269            cloud.scales.push([-3.0; 3]);
1270            cloud.rotations.push([1.0, 0.0, 0.0, 0.0]);
1271        }
1272        // One splat far from the centroid: the radial crop must remove it.
1273        cloud.positions.push([100.0, 100.0, 100.0]);
1274        cloud.colors.push([0.5, 0.6, 0.7]);
1275        cloud.opacities.push(1.0);
1276        cloud.scales.push([-3.0; 3]);
1277        cloud.rotations.push([1.0, 0.0, 0.0, 0.0]);
1278        cloud
1279    }
1280
1281    #[test]
1282    fn rescale_scales_positions_and_log_scales_together() {
1283        let file = write_ply(
1284            &minimal_properties(),
1285            &[minimal_vertex(2.0)],
1286            "binary_little_endian",
1287        );
1288        let mut cloud = read_splat_ply(file.path()).expect("valid ply");
1289        let original_scale = cloud.scales[0][0];
1290
1291        cloud.rescale(0.5);
1292
1293        assert!(
1294            (cloud.positions[0][0] - 1.0).abs() < 1e-6,
1295            "positions halve"
1296        );
1297        assert!(
1298            (cloud.scales[0][0] - (original_scale + 0.5_f32.ln())).abs() < 1e-6,
1299            "log-scales shift by ln(factor) so splat footprints shrink with the scene"
1300        );
1301    }
1302
1303    #[test]
1304    fn rescale_by_one_is_identity() {
1305        let file = write_ply(
1306            &minimal_properties(),
1307            &[minimal_vertex(3.0)],
1308            "binary_little_endian",
1309        );
1310        let mut cloud = read_splat_ply(file.path()).expect("valid ply");
1311        let before = (cloud.positions[0], cloud.scales[0]);
1312        cloud.rescale(1.0);
1313        assert_eq!(before, (cloud.positions[0], cloud.scales[0]));
1314    }
1315
1316    #[test]
1317    fn coverage_boost_shifts_logits_and_shrinks_log_scales() {
1318        let file = write_ply(
1319            &minimal_properties(),
1320            &[minimal_vertex(1.0)],
1321            "binary_little_endian",
1322        );
1323        let mut cloud = read_splat_ply(file.path()).expect("valid ply");
1324        let logit_before = cloud.opacities[0];
1325        let scale_before = cloud.scales[0];
1326
1327        cloud.coverage_boost(8.0);
1328
1329        let expected = 8.0_f32.ln();
1330        assert!(
1331            (cloud.opacities[0] - (logit_before + expected)).abs() < 1e-5,
1332            "logits shift by ln(boost)"
1333        );
1334        for (got, want) in cloud.scales[0].iter().zip(scale_before) {
1335            assert!(
1336                (got - (want - 0.5 * expected)).abs() < 1e-5,
1337                "log-scales shrink by half ln(boost)"
1338            );
1339        }
1340    }
1341
1342    #[test]
1343    fn coverage_boost_at_or_below_one_is_identity() {
1344        let file = write_ply(
1345            &minimal_properties(),
1346            &[minimal_vertex(1.0)],
1347            "binary_little_endian",
1348        );
1349        let mut cloud = read_splat_ply(file.path()).expect("valid ply");
1350        let before = (cloud.opacities[0], cloud.scales[0]);
1351        cloud.coverage_boost(1.0);
1352        assert_eq!(before, (cloud.opacities[0], cloud.scales[0]));
1353        cloud.coverage_boost(0.0);
1354        assert_eq!(before, (cloud.opacities[0], cloud.scales[0]));
1355    }
1356
1357    #[test]
1358    fn subset_of_an_empty_index_list_is_empty() {
1359        let file = write_ply(
1360            &minimal_properties(),
1361            &[minimal_vertex(1.0)],
1362            "binary_little_endian",
1363        );
1364        let cloud = read_splat_ply(file.path()).expect("valid ply");
1365        let subset = cloud.subset(&[]).expect("empty selection is valid");
1366        assert!(subset.is_empty());
1367        assert_eq!(subset.sh_degree, cloud.sh_degree);
1368    }
1369
1370    #[test]
1371    fn parses_vertical_axis_comment() {
1372        assert_eq!(
1373            parse_vertical_axis_comment(&["Vertical", "axis:", "0", "0", "-1"]),
1374            Some([0.0, 0.0, -1.0])
1375        );
1376        let parsed = parse_vertical_axis_comment(&[
1377            "Vertical",
1378            "axis:",
1379            "-0.07945679",
1380            "-0.9641912",
1381            "-0.25302535",
1382        ])
1383        .expect("axis parsed");
1384        for (got, want) in parsed.iter().zip([-0.07945679, -0.9641912, -0.25302535]) {
1385            assert!((got - want).abs() < 1e-6, "axis component {got} != {want}");
1386        }
1387        // Non-axis comments are ignored.
1388        assert_eq!(
1389            parse_vertical_axis_comment(&["Exported", "from", "Brush"]),
1390            None
1391        );
1392        assert_eq!(
1393            parse_vertical_axis_comment(&["Vertical", "axis:", "not", "a", "number"]),
1394            None
1395        );
1396        // A zero-length vector is rejected.
1397        assert_eq!(
1398            parse_vertical_axis_comment(&["Vertical", "axis:", "0", "0", "0"]),
1399            None
1400        );
1401    }
1402
1403    #[test]
1404    fn reads_vertical_axis_from_ply_header() {
1405        let mut file = tempfile::NamedTempFile::new().expect("temp file");
1406        let mut header = String::from("ply\nformat binary_little_endian 1.0\n");
1407        header.push_str("comment Exported from Brush\n");
1408        header.push_str("comment Vertical axis: -0.07945679 -0.9641912 -0.25302535\n");
1409        header.push_str("comment SH degree: 3\n");
1410        header.push_str(&format!("element vertex {}\n", 1));
1411        for property in minimal_properties() {
1412            header.push_str(&format!("property float {property}\n"));
1413        }
1414        header.push_str("end_header\n");
1415        file.write_all(header.as_bytes()).expect("write header");
1416        for value in minimal_vertex(1.0) {
1417            file.write_all(&value.to_le_bytes()).expect("write value");
1418        }
1419        file.flush().expect("flush");
1420
1421        let cloud = read_splat_ply(file.path()).expect("valid ply");
1422        assert!(
1423            cloud.vertical_axis.is_none(),
1424            "axis consumed after orientation"
1425        );
1426    }
1427
1428    #[test]
1429    fn orients_declared_up_to_negative_z() {
1430        // A cloud whose declared up is +Y (like brush's -Y convention rotated).
1431        let mut cloud = SplatCloud {
1432            positions: vec![[0.0, 10.0, 0.0], [0.0, 0.0, 0.0]],
1433            colors: vec![[0.5, 0.6, 0.7]; 2],
1434            opacities: vec![1.0; 2],
1435            scales: vec![[-2.0; 3]; 2],
1436            rotations: vec![[1.0, 0.0, 0.0, 0.0]; 2],
1437            sh: vec![],
1438            sh_degree: 0,
1439            vertical_axis: Some([0.0, 1.0, 0.0]),
1440        };
1441        cloud.orient_to_negative_z();
1442        // +Y up → -Z up: the point above the origin should land on -Z.
1443        assert!(
1444            (cloud.positions[0][2] + 10.0).abs() < 1e-5,
1445            "expected point at -Z, got {:?}",
1446            cloud.positions[0]
1447        );
1448        assert!((cloud.positions[0][0]).abs() < 1e-5);
1449        assert!((cloud.positions[0][1]).abs() < 1e-5);
1450        // The rotation quaternion is a 90° rotation about X.
1451        let q = cloud.rotations[0];
1452        assert!(
1453            (q[0].abs() - 2.0_f32.sqrt() / 2.0).abs() < 1e-5,
1454            "q = {q:?}"
1455        );
1456        assert!(
1457            (q[1].abs() - 2.0_f32.sqrt() / 2.0).abs() < 1e-5,
1458            "q = {q:?}"
1459        );
1460    }
1461
1462    #[test]
1463    fn orientation_is_noop_without_declared_axis() {
1464        let mut cloud = SplatCloud::default();
1465        cloud.positions.push([1.0, 2.0, 3.0]);
1466        cloud.rotations.push([1.0, 0.0, 0.0, 0.0]);
1467        cloud.orient_to_negative_z();
1468        assert_eq!(cloud.positions[0], [1.0, 2.0, 3.0]);
1469    }
1470
1471    #[test]
1472    fn orientation_is_noop_when_already_negative_z() {
1473        let mut cloud = SplatCloud {
1474            vertical_axis: Some([0.0, 0.0, -1.0]),
1475            positions: vec![[1.0, 2.0, 3.0]],
1476            ..SplatCloud::default()
1477        };
1478        cloud.orient_to_negative_z();
1479        assert_eq!(cloud.positions[0], [1.0, 2.0, 3.0]);
1480    }
1481
1482    #[test]
1483    fn orientation_preserves_distances_and_unit_quaternions() {
1484        let mut cloud = SplatCloud {
1485            vertical_axis: Some([0.0, 1.0, 0.0]),
1486            positions: vec![[0.0, 0.0, 0.0], [3.0, 4.0, 0.0], [-1.0, 2.0, -5.0]],
1487            rotations: vec![
1488                [1.0, 0.0, 0.0, 0.0],
1489                [0.5, 0.5, 0.5, 0.5],
1490                [0.5, -0.5, 0.5, 0.5],
1491            ],
1492            ..SplatCloud::default()
1493        };
1494        let before = cloud.positions[1];
1495        cloud.orient_to_negative_z();
1496        // Distance from origin is preserved under a rigid rotation.
1497        let after = cloud.positions[1];
1498        let before_norm =
1499            (before[0] * before[0] + before[1] * before[1] + before[2] * before[2]).sqrt();
1500        let after_norm = (after[0] * after[0] + after[1] * after[1] + after[2] * after[2]).sqrt();
1501        assert!((before_norm - after_norm).abs() < 1e-4);
1502        for q in &cloud.rotations {
1503            let norm = (q[0] * q[0] + q[1] * q[1] + q[2] * q[2] + q[3] * q[3]).sqrt();
1504            assert!((norm - 1.0).abs() < 1e-4, "quaternion not unit: {q:?}");
1505        }
1506    }
1507
1508    /// A header that claims more vertices than the address space holds. The
1509    /// size sum used to overflow (a panic, or a wrapped buffer size in a
1510    /// release build) before the payload length was looked at.
1511    #[test]
1512    fn a_vertex_count_that_overflows_is_an_error_not_a_panic() {
1513        let file = write_ply(&minimal_properties(), &[], "binary_little_endian");
1514        let text = std::fs::read_to_string(file.path()).expect("header");
1515        std::fs::write(
1516            file.path(),
1517            text.replace(
1518                "element vertex 0",
1519                &format!("element vertex {}", usize::MAX),
1520            ),
1521        )
1522        .expect("rewrite");
1523        let err = read_splat_ply(file.path()).expect_err("an impossible count");
1524        assert!(matches!(err, GeolithError::Ply(_)), "{err}");
1525    }
1526
1527    /// A count that fits but is far above the file: refused before any
1528    /// buffer of that size is asked for.
1529    #[test]
1530    fn a_vertex_count_far_above_the_file_is_truncated_data() {
1531        let file = write_ply(
1532            &minimal_properties(),
1533            &[minimal_vertex(1.0)],
1534            "binary_little_endian",
1535        );
1536        let bytes = std::fs::read(file.path()).expect("file");
1537        let from = b"element vertex 1\n";
1538        let at = bytes
1539            .windows(from.len())
1540            .position(|w| w == from)
1541            .expect("count line");
1542        let mut rewritten = bytes[..at].to_vec();
1543        rewritten.extend_from_slice(b"element vertex 4000000000000\n");
1544        rewritten.extend_from_slice(&bytes[at + from.len()..]);
1545        std::fs::write(file.path(), rewritten).expect("rewrite");
1546        let err = read_splat_ply(file.path()).expect_err("count above the file");
1547        assert!(err.to_string().contains("truncated"), "{err}");
1548    }
1549}