Skip to main content

copc_streaming/
header.rs

1//! LAS header + COPC info parsing.
2//!
3//! Uses the `las` crate for standard LAS/VLR parsing.
4//! Only the COPC info VLR (160 bytes) is parsed by us — it's COPC-specific.
5
6use std::io::Cursor;
7
8use byteorder::{LittleEndian, ReadBytesExt};
9use las::raw;
10use laz::LazVlr;
11
12use crate::error::CopcError;
13use crate::types::Aabb;
14
15/// Parsed COPC file header.
16///
17/// LAS-standard fields come from `las::Header`.
18/// COPC-specific fields are in `copc_info`.
19pub struct CopcHeader {
20    pub(crate) las_header: las::Header,
21    pub(crate) copc_info: CopcInfo,
22    pub(crate) laz_vlr: LazVlr,
23    pub(crate) evlr_offset: u64,
24    pub(crate) evlr_count: u32,
25}
26
27impl CopcHeader {
28    /// Full LAS header with transforms, bounds, point format, etc.
29    pub fn las_header(&self) -> &las::Header {
30        &self.las_header
31    }
32
33    /// COPC-specific info (octree center, halfsize, hierarchy location).
34    pub fn copc_info(&self) -> &CopcInfo {
35        &self.copc_info
36    }
37
38    /// LAZ decompression parameters.
39    pub fn laz_vlr(&self) -> &LazVlr {
40        &self.laz_vlr
41    }
42
43    /// File offset where EVLRs start.
44    pub fn evlr_offset(&self) -> u64 {
45        self.evlr_offset
46    }
47
48    /// Number of EVLRs.
49    pub fn evlr_count(&self) -> u32 {
50        self.evlr_count
51    }
52}
53
54/// COPC info VLR payload (160 bytes). This is COPC-specific — not part of the LAS standard.
55#[derive(Debug, Clone)]
56#[non_exhaustive]
57pub struct CopcInfo {
58    /// Centre of the root octree cube `[x, y, z]`.
59    pub center: [f64; 3],
60    /// Half the side length of the root octree cube.
61    pub halfsize: f64,
62    /// Spacing at the finest octree level.
63    pub spacing: f64,
64    /// File offset of the root hierarchy page.
65    pub root_hier_offset: u64,
66    /// Size of the root hierarchy page in bytes.
67    pub root_hier_size: u64,
68    /// Minimum GPS time across all points.
69    pub gpstime_minimum: f64,
70    /// Maximum GPS time across all points.
71    pub gpstime_maximum: f64,
72}
73
74impl CopcInfo {
75    /// Compute the root octree bounding box from center + halfsize.
76    pub fn root_bounds(&self) -> Aabb {
77        Aabb {
78            min: [
79                self.center[0] - self.halfsize,
80                self.center[1] - self.halfsize,
81                self.center[2] - self.halfsize,
82            ],
83            max: [
84                self.center[0] + self.halfsize,
85                self.center[1] + self.halfsize,
86                self.center[2] + self.halfsize,
87            ],
88        }
89    }
90
91    /// Compute the octree level needed for a given point spacing (in the
92    /// same units as the point coordinates, typically meters).
93    ///
94    /// At level 0 the average distance between points equals
95    /// [`CopcInfo::spacing`]. Each deeper level halves the distance. This
96    /// returns the shallowest level where the point spacing is ≤ `resolution`.
97    ///
98    /// For example, if the file's base spacing is 10 m and you request 0.5 m,
99    /// you get level 5 (10 → 5 → 2.5 → 1.25 → 0.625 → 0.3125).
100    ///
101    /// Use the returned level as `max_level` in
102    /// [`CopcStreamingReader::query_points_to_level`](crate::CopcStreamingReader::query_points_to_level)
103    /// or
104    /// [`CopcStreamingReader::load_hierarchy_for_bounds_to_level`](crate::CopcStreamingReader::load_hierarchy_for_bounds_to_level).
105    pub fn level_for_resolution(&self, resolution: f64) -> i32 {
106        if resolution <= 0.0 || self.spacing <= 0.0 {
107            return 0;
108        }
109        (self.spacing / resolution).log2().ceil().max(0.0) as i32
110    }
111
112    fn parse(data: &[u8]) -> Result<Self, CopcError> {
113        if data.len() < 160 {
114            return Err(CopcError::CopcInfoNotFound);
115        }
116        let mut r = Cursor::new(data);
117        let center_x = r.read_f64::<LittleEndian>()?;
118        let center_y = r.read_f64::<LittleEndian>()?;
119        let center_z = r.read_f64::<LittleEndian>()?;
120        let halfsize = r.read_f64::<LittleEndian>()?;
121        let spacing = r.read_f64::<LittleEndian>()?;
122        let root_hier_offset = r.read_u64::<LittleEndian>()?;
123        let root_hier_size = r.read_u64::<LittleEndian>()?;
124        let gpstime_minimum = r.read_f64::<LittleEndian>()?;
125        let gpstime_maximum = r.read_f64::<LittleEndian>()?;
126        Ok(CopcInfo {
127            center: [center_x, center_y, center_z],
128            halfsize,
129            spacing,
130            root_hier_offset,
131            root_hier_size,
132            gpstime_minimum,
133            gpstime_maximum,
134        })
135    }
136}
137
138/// Parse COPC header from a byte buffer.
139///
140/// The buffer must contain the LAS header and all VLRs (typically first ~64KB).
141pub(crate) fn parse_header(data: &[u8]) -> Result<CopcHeader, CopcError> {
142    let mut cursor = Cursor::new(data);
143
144    // Parse the raw LAS header
145    let raw_header = raw::Header::read_from(&mut cursor)?;
146
147    let evlr_offset = raw_header
148        .evlr
149        .as_ref()
150        .map_or(0, |e| e.start_of_first_evlr);
151    let evlr_count = raw_header.evlr.as_ref().map_or(0, |e| e.number_of_evlrs);
152    let number_of_vlrs = raw_header.number_of_variable_length_records;
153    let header_size = raw_header.header_size;
154
155    // Build the high-level header (for transforms, point format, etc.)
156    let mut builder = las::Builder::new(raw_header)?;
157
158    // Seek to VLR start and parse all VLRs
159    cursor.set_position(header_size as u64);
160
161    let mut copc_info = None;
162    let mut laz_vlr = None;
163
164    for _ in 0..number_of_vlrs {
165        let raw_vlr = raw::Vlr::read_from(&mut cursor, false)?;
166        let vlr = las::Vlr::new(raw_vlr);
167
168        match (vlr.user_id.as_str(), vlr.record_id) {
169            ("copc", 1) => {
170                copc_info = Some(CopcInfo::parse(&vlr.data)?);
171            }
172            ("laszip encoded", 22204) => {
173                laz_vlr = Some(LazVlr::read_from(vlr.data.as_slice())?);
174            }
175            _ => {}
176        }
177
178        builder.vlrs.push(vlr);
179    }
180
181    let las_header = builder.into_header()?;
182    let copc_info = copc_info.ok_or(CopcError::CopcInfoNotFound)?;
183    let laz_vlr = laz_vlr.ok_or(CopcError::LazVlrNotFound)?;
184
185    Ok(CopcHeader {
186        las_header,
187        copc_info,
188        laz_vlr,
189        evlr_offset,
190        evlr_count,
191    })
192}
193
194#[cfg(test)]
195mod tests {
196    use super::*;
197
198    #[test]
199    fn test_copc_info_root_bounds() {
200        let info = CopcInfo {
201            center: [100.0, 200.0, 10.0],
202            halfsize: 50.0,
203            spacing: 1.0,
204            root_hier_offset: 0,
205            root_hier_size: 0,
206            gpstime_minimum: 0.0,
207            gpstime_maximum: 0.0,
208        };
209        let b = info.root_bounds();
210        assert_eq!(b.min, [50.0, 150.0, -40.0]);
211        assert_eq!(b.max, [150.0, 250.0, 60.0]);
212    }
213
214    #[test]
215    fn test_level_for_resolution() {
216        let info = CopcInfo {
217            center: [0.0, 0.0, 0.0],
218            halfsize: 500.0,
219            spacing: 10.0,
220            root_hier_offset: 0,
221            root_hier_size: 0,
222            gpstime_minimum: 0.0,
223            gpstime_maximum: 0.0,
224        };
225
226        // spacing=10, resolution=10 → level 0 (no refinement needed)
227        assert_eq!(info.level_for_resolution(10.0), 0);
228        // spacing=10, resolution=5 → level 1 (one halving)
229        assert_eq!(info.level_for_resolution(5.0), 1);
230        // spacing=10, resolution=2.5 → level 2
231        assert_eq!(info.level_for_resolution(2.5), 2);
232        // spacing=10, resolution=1.0 → ceil(log2(10)) = 4
233        assert_eq!(info.level_for_resolution(1.0), 4);
234        // spacing=10, resolution=0.5 → ceil(log2(20)) = 5
235        assert_eq!(info.level_for_resolution(0.5), 5);
236        // resolution larger than spacing → level 0
237        assert_eq!(info.level_for_resolution(20.0), 0);
238        // edge case: zero/negative resolution → level 0
239        assert_eq!(info.level_for_resolution(0.0), 0);
240        assert_eq!(info.level_for_resolution(-1.0), 0);
241    }
242}