oxigdal-copc 0.1.4

Pure Rust COPC (Cloud Optimized Point Cloud) reader for OxiGDAL - LAS/LAZ format with spatial index
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
//! LAS point record binary deserialization.
//!
//! Supports point data record formats 0-3 (LAS 1.0-1.3 legacy) and 6-8
//! (LAS 1.4 extended).  Each format has a fixed-size base record plus optional
//! trailing fields (GPS time, RGB colour, NIR).
//!
//! Reference: ASPRS LAS Specification 1.4 R15, Tables 6-22.

use crate::error::CopcError;
use crate::point::Point3D;

/// Shared base fields extracted from a point record by `parse_legacy_base` /
/// `parse_extended_base`.
///
/// Tuple order: `(return_number, number_of_returns, classification,
/// scan_angle_rank, user_data, point_source_id, gps_time, rgb_offset)`.
type BaseFields = (u8, u8, u8, i8, u8, u16, Option<f64>, Option<usize>);

/// Minimum record sizes per point data format ID.
///
/// | Format | Base | GPS time | RGB | NIR | Total |
/// |--------|------|----------|-----|-----|-------|
/// | 0      | 20   |          |     |     | 20    |
/// | 1      | 20   | 8        |     |     | 28    |
/// | 2      | 20   |          | 6   |     | 26    |
/// | 3      | 20   | 8        | 6   |     | 34    |
/// | 6      | 30   | (incl)   |     |     | 30    |
/// | 7      | 30   | (incl)   | 6   |     | 36    |
/// | 8      | 30   | (incl)   | 6   | 2   | 38    |
pub fn min_record_size(format_id: u8) -> Result<usize, CopcError> {
    match format_id {
        0 => Ok(20),
        1 => Ok(28),
        2 => Ok(26),
        3 => Ok(34),
        6 => Ok(30),
        7 => Ok(36),
        8 => Ok(38),
        other => Err(CopcError::InvalidFormat(format!(
            "Unsupported point data format ID: {other}"
        ))),
    }
}

/// Returns `true` when the format uses the extended 30-byte base (formats 6-10).
#[inline]
fn is_extended_format(format_id: u8) -> bool {
    format_id >= 6
}

/// Deserialize a single point record from `record` using the given format,
/// scale factors and offsets.
///
/// # Parameters
/// - `record` -- raw bytes of a single point record (length >= `min_record_size(format_id)`)
/// - `format_id` -- LAS point data record format (0, 1, 2, 3, 6, 7, 8)
/// - `scale` -- `[scale_x, scale_y, scale_z]` from the LAS header
/// - `offset` -- `[offset_x, offset_y, offset_z]` from the LAS header
///
/// # Errors
/// Returns [`CopcError::InvalidFormat`] when `record` is too short or the
/// format ID is unsupported.
pub fn deserialize_point(
    record: &[u8],
    format_id: u8,
    scale: [f64; 3],
    offset: [f64; 3],
) -> Result<Point3D, CopcError> {
    let min_size = min_record_size(format_id)?;
    if record.len() < min_size {
        return Err(CopcError::InvalidFormat(format!(
            "Point record too short for format {format_id}: {} bytes (need >= {min_size})",
            record.len()
        )));
    }

    // X/Y/Z raw i32 LE at bytes 0-11 (same for all formats).
    let raw_x = i32::from_le_bytes([record[0], record[1], record[2], record[3]]);
    let raw_y = i32::from_le_bytes([record[4], record[5], record[6], record[7]]);
    let raw_z = i32::from_le_bytes([record[8], record[9], record[10], record[11]]);

    let x = raw_x as f64 * scale[0] + offset[0];
    let y = raw_y as f64 * scale[1] + offset[1];
    let z = raw_z as f64 * scale[2] + offset[2];

    // Intensity at bytes 12-13 (u16 LE) -- same for all formats.
    let intensity = u16::from_le_bytes([record[12], record[13]]);

    let (
        return_number,
        number_of_returns,
        classification,
        scan_angle_rank,
        user_data,
        point_source_id,
        gps_time,
        rgb_offset,
    ) = if is_extended_format(format_id) {
        parse_extended_base(record, format_id)?
    } else {
        parse_legacy_base(record, format_id)?
    };

    // Parse optional RGB fields based on format and the computed rgb_offset.
    let (red, green, blue) = if let Some(rgb_off) = rgb_offset {
        if record.len() >= rgb_off + 6 {
            let r = u16::from_le_bytes([record[rgb_off], record[rgb_off + 1]]);
            let g = u16::from_le_bytes([record[rgb_off + 2], record[rgb_off + 3]]);
            let b = u16::from_le_bytes([record[rgb_off + 4], record[rgb_off + 5]]);
            (Some(r), Some(g), Some(b))
        } else {
            (None, None, None)
        }
    } else {
        (None, None, None)
    };

    Ok(Point3D {
        x,
        y,
        z,
        intensity,
        return_number,
        number_of_returns,
        classification,
        scan_angle_rank,
        user_data,
        point_source_id,
        gps_time,
        red,
        green,
        blue,
    })
}

/// Parse fields from legacy base record (formats 0-5, 20-byte base).
///
/// Returns `(return_number, number_of_returns, classification, scan_angle_rank,
///           user_data, point_source_id, gps_time, rgb_offset)`.
fn parse_legacy_base(record: &[u8], format_id: u8) -> Result<BaseFields, CopcError> {
    // Byte 14: bits 0-2 = return_number, bits 3-5 = number_of_returns
    let packed = record[14];
    let return_number = packed & 0x07;
    let number_of_returns = (packed >> 3) & 0x07;

    // Byte 15: classification
    let classification = record[15];

    // Byte 16: scan angle rank (i8)
    let scan_angle_rank = record[16] as i8;

    // Byte 17: user data
    let user_data = record[17];

    // Bytes 18-19: point source ID (u16 LE)
    let point_source_id = u16::from_le_bytes([record[18], record[19]]);

    // GPS time and RGB depend on format
    let (gps_time, rgb_offset) = match format_id {
        0 => (None, None),
        1 => {
            // GPS time at byte 20
            let gps = read_f64_le(record, 20)?;
            (Some(gps), None)
        }
        2 => {
            // RGB at byte 20
            (None, Some(20))
        }
        3 => {
            // GPS time at byte 20, RGB at byte 28
            let gps = read_f64_le(record, 20)?;
            (Some(gps), Some(28))
        }
        _ => {
            return Err(CopcError::InvalidFormat(format!(
                "Unsupported legacy format: {format_id}"
            )));
        }
    };

    Ok((
        return_number,
        number_of_returns,
        classification,
        scan_angle_rank,
        user_data,
        point_source_id,
        gps_time,
        rgb_offset,
    ))
}

/// Parse fields from extended base record (formats 6-10, 30-byte base).
///
/// Returns `(return_number, number_of_returns, classification, scan_angle_rank,
///           user_data, point_source_id, gps_time, rgb_offset)`.
fn parse_extended_base(record: &[u8], format_id: u8) -> Result<BaseFields, CopcError> {
    // Byte 14: bits 0-3 = return_number, bits 4-7 = number_of_returns
    let packed = record[14];
    let return_number = packed & 0x0F;
    let number_of_returns = (packed >> 4) & 0x0F;

    // Byte 16: classification
    let classification = record[16];

    // Byte 17: user data
    let user_data = record[17];

    // Bytes 18-19: scan angle (i16 LE), multiply by 0.006 to get degrees
    let raw_angle = i16::from_le_bytes([record[18], record[19]]);
    let angle_degrees = raw_angle as f64 * 0.006;
    // Clamp to i8 range for compatibility with Point3D.scan_angle_rank
    let clamped = angle_degrees.round().clamp(-128.0, 127.0) as i8;

    // Bytes 20-21: point source ID (u16 LE)
    let point_source_id = u16::from_le_bytes([record[20], record[21]]);

    // Bytes 22-29: GPS time (f64 LE) -- always present in formats 6+
    let gps_time = read_f64_le(record, 22)?;

    // RGB offset depends on format
    let rgb_offset = match format_id {
        6 => None,         // No RGB
        7 | 8 => Some(30), // RGB at byte 30 (NIR at 36 for format 8, but Point3D has no NIR field)
        _ => {
            return Err(CopcError::InvalidFormat(format!(
                "Unsupported extended format: {format_id}"
            )));
        }
    };

    Ok((
        return_number,
        number_of_returns,
        classification,
        clamped,
        user_data,
        point_source_id,
        Some(gps_time),
        rgb_offset,
    ))
}

/// Deserialize multiple point records from a contiguous byte buffer.
///
/// # Parameters
/// - `data` -- raw bytes containing `count` point records packed end-to-end
/// - `count` -- number of point records to read
/// - `record_length` -- byte size of each record (may be larger than `min_record_size`)
/// - `format_id` -- LAS point data record format
/// - `scale` -- `[scale_x, scale_y, scale_z]`
/// - `offset` -- `[offset_x, offset_y, offset_z]`
///
/// # Errors
/// Returns [`CopcError::InvalidFormat`] when the data is too short or a record
/// is malformed.
pub fn deserialize_points(
    data: &[u8],
    count: usize,
    record_length: usize,
    format_id: u8,
    scale: [f64; 3],
    offset: [f64; 3],
) -> Result<Vec<Point3D>, CopcError> {
    let needed = count.checked_mul(record_length).ok_or_else(|| {
        CopcError::InvalidFormat("Point count * record length overflows usize".into())
    })?;
    if data.len() < needed {
        return Err(CopcError::InvalidFormat(format!(
            "Point data too short: {} bytes (need {needed} for {count} records of {record_length} bytes)",
            data.len()
        )));
    }

    let mut points = Vec::with_capacity(count);
    for i in 0..count {
        let start = i * record_length;
        let end = start + record_length;
        let record = &data[start..end];
        let point = deserialize_point(record, format_id, scale, offset)?;
        points.push(point);
    }
    Ok(points)
}

/// Read an f64 from `data` at byte offset `off` in little-endian order.
#[inline]
fn read_f64_le(data: &[u8], off: usize) -> Result<f64, CopcError> {
    if data.len() < off + 8 {
        return Err(CopcError::InvalidFormat(format!(
            "Cannot read f64 at offset {off}: data too short ({} bytes)",
            data.len()
        )));
    }
    Ok(f64::from_le_bytes([
        data[off],
        data[off + 1],
        data[off + 2],
        data[off + 3],
        data[off + 4],
        data[off + 5],
        data[off + 6],
        data[off + 7],
    ]))
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Build a format-0 point record (20 bytes).
    fn make_format0_record(raw_x: i32, raw_y: i32, raw_z: i32, intensity: u16) -> Vec<u8> {
        let mut rec = vec![0u8; 20];
        rec[0..4].copy_from_slice(&raw_x.to_le_bytes());
        rec[4..8].copy_from_slice(&raw_y.to_le_bytes());
        rec[8..12].copy_from_slice(&raw_z.to_le_bytes());
        rec[12..14].copy_from_slice(&intensity.to_le_bytes());
        // Byte 14: return_number=2 (bits 0-2), number_of_returns=3 (bits 3-5)
        rec[14] = 2 | (3 << 3);
        // Byte 15: classification = 2 (Ground)
        rec[15] = 2;
        // Byte 16: scan_angle_rank = -5
        rec[16] = (-5i8) as u8;
        // Byte 17: user_data = 42
        rec[17] = 42;
        // Bytes 18-19: point_source_id = 7
        rec[18..20].copy_from_slice(&7u16.to_le_bytes());
        rec
    }

    /// Build a format-1 point record (28 bytes = 20 base + 8 GPS).
    fn make_format1_record(raw_x: i32, raw_y: i32, raw_z: i32, gps_time: f64) -> Vec<u8> {
        let mut rec = make_format0_record(raw_x, raw_y, raw_z, 100);
        rec.resize(28, 0);
        rec[20..28].copy_from_slice(&gps_time.to_le_bytes());
        rec
    }

    /// Build a format-2 point record (26 bytes = 20 base + 6 RGB).
    fn make_format2_record(raw_x: i32, raw_y: i32, raw_z: i32, r: u16, g: u16, b: u16) -> Vec<u8> {
        let mut rec = make_format0_record(raw_x, raw_y, raw_z, 200);
        rec.resize(26, 0);
        rec[20..22].copy_from_slice(&r.to_le_bytes());
        rec[22..24].copy_from_slice(&g.to_le_bytes());
        rec[24..26].copy_from_slice(&b.to_le_bytes());
        rec
    }

    /// Build a format-3 point record (34 bytes = 20 base + 8 GPS + 6 RGB).
    fn make_format3_record(
        raw_x: i32,
        raw_y: i32,
        raw_z: i32,
        gps_time: f64,
        r: u16,
        g: u16,
        b: u16,
    ) -> Vec<u8> {
        let mut rec = make_format0_record(raw_x, raw_y, raw_z, 300);
        rec.resize(34, 0);
        rec[20..28].copy_from_slice(&gps_time.to_le_bytes());
        rec[28..30].copy_from_slice(&r.to_le_bytes());
        rec[30..32].copy_from_slice(&g.to_le_bytes());
        rec[32..34].copy_from_slice(&b.to_le_bytes());
        rec
    }

    /// Build a format-6 point record (30 bytes extended base).
    fn make_format6_record(raw_x: i32, raw_y: i32, raw_z: i32, gps_time: f64) -> Vec<u8> {
        let mut rec = vec![0u8; 30];
        rec[0..4].copy_from_slice(&raw_x.to_le_bytes());
        rec[4..8].copy_from_slice(&raw_y.to_le_bytes());
        rec[8..12].copy_from_slice(&raw_z.to_le_bytes());
        rec[12..14].copy_from_slice(&500u16.to_le_bytes()); // intensity
        // Byte 14: return_number=3 (bits 0-3), number_of_returns=5 (bits 4-7)
        rec[14] = 3 | (5 << 4);
        // Byte 15: classification flags
        rec[15] = 0;
        // Byte 16: classification = 6 (Building)
        rec[16] = 6;
        // Byte 17: user_data = 99
        rec[17] = 99;
        // Bytes 18-19: scan angle (i16), e.g. 5000 * 0.006 = 30.0 degrees
        rec[18..20].copy_from_slice(&5000i16.to_le_bytes());
        // Bytes 20-21: point_source_id = 12
        rec[20..22].copy_from_slice(&12u16.to_le_bytes());
        // Bytes 22-29: GPS time
        rec[22..30].copy_from_slice(&gps_time.to_le_bytes());
        rec
    }

    /// Build a format-7 point record (36 bytes = 30 base + 6 RGB).
    fn make_format7_record(
        raw_x: i32,
        raw_y: i32,
        raw_z: i32,
        gps_time: f64,
        r: u16,
        g: u16,
        b: u16,
    ) -> Vec<u8> {
        let mut rec = make_format6_record(raw_x, raw_y, raw_z, gps_time);
        rec.resize(36, 0);
        rec[30..32].copy_from_slice(&r.to_le_bytes());
        rec[32..34].copy_from_slice(&g.to_le_bytes());
        rec[34..36].copy_from_slice(&b.to_le_bytes());
        rec
    }

    /// Build a format-8 point record (38 bytes = 30 base + 6 RGB + 2 NIR).
    fn make_format8_record(
        raw_x: i32,
        raw_y: i32,
        raw_z: i32,
        gps_time: f64,
        r: u16,
        g: u16,
        b: u16,
    ) -> Vec<u8> {
        let mut rec = make_format7_record(raw_x, raw_y, raw_z, gps_time, r, g, b);
        rec.resize(38, 0);
        rec[36..38].copy_from_slice(&1000u16.to_le_bytes()); // NIR
        rec
    }

    // ---- Format 0 ----

    #[test]
    fn test_format0_coordinates() {
        let rec = make_format0_record(1000, 2000, 500, 150);
        let scale = [0.001, 0.001, 0.001];
        let offset = [0.0, 0.0, 0.0];
        let pt = deserialize_point(&rec, 0, scale, offset).expect("format 0 parse");
        assert!((pt.x - 1.0).abs() < 1e-9, "x = 1000 * 0.001 = 1.0");
        assert!((pt.y - 2.0).abs() < 1e-9, "y = 2000 * 0.001 = 2.0");
        assert!((pt.z - 0.5).abs() < 1e-9, "z = 500 * 0.001 = 0.5");
    }

    #[test]
    fn test_format0_with_offset() {
        let rec = make_format0_record(1000, 2000, 500, 150);
        let scale = [0.001, 0.001, 0.001];
        let offset = [100.0, 200.0, 50.0];
        let pt = deserialize_point(&rec, 0, scale, offset).expect("format 0 with offset");
        assert!((pt.x - 101.0).abs() < 1e-9);
        assert!((pt.y - 202.0).abs() < 1e-9);
        assert!((pt.z - 50.5).abs() < 1e-9);
    }

    #[test]
    fn test_format0_intensity() {
        let rec = make_format0_record(0, 0, 0, 150);
        let pt = deserialize_point(&rec, 0, [1.0; 3], [0.0; 3]).expect("format 0");
        assert_eq!(pt.intensity, 150);
    }

    #[test]
    fn test_format0_return_number() {
        let rec = make_format0_record(0, 0, 0, 0);
        let pt = deserialize_point(&rec, 0, [1.0; 3], [0.0; 3]).expect("format 0");
        assert_eq!(pt.return_number, 2);
        assert_eq!(pt.number_of_returns, 3);
    }

    #[test]
    fn test_format0_classification() {
        let rec = make_format0_record(0, 0, 0, 0);
        let pt = deserialize_point(&rec, 0, [1.0; 3], [0.0; 3]).expect("format 0");
        assert_eq!(pt.classification, 2);
    }

    #[test]
    fn test_format0_scan_angle() {
        let rec = make_format0_record(0, 0, 0, 0);
        let pt = deserialize_point(&rec, 0, [1.0; 3], [0.0; 3]).expect("format 0");
        assert_eq!(pt.scan_angle_rank, -5);
    }

    #[test]
    fn test_format0_user_data() {
        let rec = make_format0_record(0, 0, 0, 0);
        let pt = deserialize_point(&rec, 0, [1.0; 3], [0.0; 3]).expect("format 0");
        assert_eq!(pt.user_data, 42);
    }

    #[test]
    fn test_format0_point_source_id() {
        let rec = make_format0_record(0, 0, 0, 0);
        let pt = deserialize_point(&rec, 0, [1.0; 3], [0.0; 3]).expect("format 0");
        assert_eq!(pt.point_source_id, 7);
    }

    #[test]
    fn test_format0_no_gps_no_color() {
        let rec = make_format0_record(0, 0, 0, 0);
        let pt = deserialize_point(&rec, 0, [1.0; 3], [0.0; 3]).expect("format 0");
        assert!(pt.gps_time.is_none());
        assert!(pt.red.is_none());
        assert!(pt.green.is_none());
        assert!(pt.blue.is_none());
    }

    #[test]
    fn test_format0_too_short() {
        let rec = vec![0u8; 19]; // need 20
        assert!(deserialize_point(&rec, 0, [1.0; 3], [0.0; 3]).is_err());
    }

    // ---- Format 1 ----

    #[test]
    fn test_format1_gps_time() {
        let rec = make_format1_record(0, 0, 0, 12345.678);
        let pt = deserialize_point(&rec, 1, [1.0; 3], [0.0; 3]).expect("format 1");
        let gps = pt.gps_time.expect("format 1 should have GPS time");
        assert!((gps - 12345.678).abs() < 1e-6);
    }

    #[test]
    fn test_format1_no_color() {
        let rec = make_format1_record(0, 0, 0, 0.0);
        let pt = deserialize_point(&rec, 1, [1.0; 3], [0.0; 3]).expect("format 1");
        assert!(pt.red.is_none());
    }

    // ---- Format 2 ----

    #[test]
    fn test_format2_rgb() {
        let rec = make_format2_record(0, 0, 0, 255, 128, 64);
        let pt = deserialize_point(&rec, 2, [1.0; 3], [0.0; 3]).expect("format 2");
        assert_eq!(pt.red, Some(255));
        assert_eq!(pt.green, Some(128));
        assert_eq!(pt.blue, Some(64));
    }

    #[test]
    fn test_format2_no_gps() {
        let rec = make_format2_record(0, 0, 0, 0, 0, 0);
        let pt = deserialize_point(&rec, 2, [1.0; 3], [0.0; 3]).expect("format 2");
        assert!(pt.gps_time.is_none());
    }

    // ---- Format 3 ----

    #[test]
    fn test_format3_gps_and_rgb() {
        let rec = make_format3_record(1000, 2000, 3000, 99.9, 1000, 2000, 3000);
        let pt = deserialize_point(&rec, 3, [0.01, 0.01, 0.01], [0.0; 3]).expect("format 3");
        assert!((pt.x - 10.0).abs() < 1e-9);
        let gps = pt.gps_time.expect("format 3 should have GPS");
        assert!((gps - 99.9).abs() < 1e-6);
        assert_eq!(pt.red, Some(1000));
        assert_eq!(pt.green, Some(2000));
        assert_eq!(pt.blue, Some(3000));
    }

    // ---- Format 6 ----

    #[test]
    fn test_format6_extended_base() {
        let rec = make_format6_record(10000, 20000, 5000, 42.5);
        let pt = deserialize_point(&rec, 6, [0.001, 0.001, 0.001], [0.0; 3]).expect("format 6");
        assert!((pt.x - 10.0).abs() < 1e-9);
        assert!((pt.y - 20.0).abs() < 1e-9);
        assert!((pt.z - 5.0).abs() < 1e-9);
        assert_eq!(pt.intensity, 500);
        assert_eq!(pt.return_number, 3);
        assert_eq!(pt.number_of_returns, 5);
        assert_eq!(pt.classification, 6);
        assert_eq!(pt.user_data, 99);
        assert_eq!(pt.point_source_id, 12);
        let gps = pt.gps_time.expect("format 6 always has GPS");
        assert!((gps - 42.5).abs() < 1e-9);
    }

    #[test]
    fn test_format6_scan_angle_conversion() {
        let rec = make_format6_record(0, 0, 0, 0.0);
        // scan angle = 5000 * 0.006 = 30.0 degrees
        let pt = deserialize_point(&rec, 6, [1.0; 3], [0.0; 3]).expect("format 6");
        assert_eq!(pt.scan_angle_rank, 30);
    }

    #[test]
    fn test_format6_scan_angle_negative() {
        let mut rec = make_format6_record(0, 0, 0, 0.0);
        // Set scan angle to -5000 -> -30.0 degrees
        rec[18..20].copy_from_slice(&(-5000i16).to_le_bytes());
        let pt = deserialize_point(&rec, 6, [1.0; 3], [0.0; 3]).expect("format 6 neg angle");
        assert_eq!(pt.scan_angle_rank, -30);
    }

    #[test]
    fn test_format6_scan_angle_clamped() {
        let mut rec = make_format6_record(0, 0, 0, 0.0);
        // Set scan angle to i16::MAX = 32767 -> 32767 * 0.006 = 196.6, clamped to 127
        rec[18..20].copy_from_slice(&i16::MAX.to_le_bytes());
        let pt = deserialize_point(&rec, 6, [1.0; 3], [0.0; 3]).expect("format 6 clamped");
        assert_eq!(pt.scan_angle_rank, 127);
    }

    #[test]
    fn test_format6_no_color() {
        let rec = make_format6_record(0, 0, 0, 0.0);
        let pt = deserialize_point(&rec, 6, [1.0; 3], [0.0; 3]).expect("format 6");
        assert!(pt.red.is_none());
    }

    // ---- Format 7 ----

    #[test]
    fn test_format7_gps_and_rgb() {
        let rec = make_format7_record(1000, 2000, 3000, 77.7, 500, 600, 700);
        let pt = deserialize_point(&rec, 7, [0.001; 3], [0.0; 3]).expect("format 7");
        let gps = pt.gps_time.expect("format 7 always has GPS");
        assert!((gps - 77.7).abs() < 1e-9);
        assert_eq!(pt.red, Some(500));
        assert_eq!(pt.green, Some(600));
        assert_eq!(pt.blue, Some(700));
    }

    // ---- Format 8 ----

    #[test]
    fn test_format8_gps_rgb_nir_ignored() {
        let rec = make_format8_record(0, 0, 0, 55.5, 11, 22, 33);
        let pt = deserialize_point(&rec, 8, [1.0; 3], [0.0; 3]).expect("format 8");
        let gps = pt.gps_time.expect("format 8 always has GPS");
        assert!((gps - 55.5).abs() < 1e-9);
        assert_eq!(pt.red, Some(11));
        assert_eq!(pt.green, Some(22));
        assert_eq!(pt.blue, Some(33));
        // NIR is silently ignored (no field in Point3D)
    }

    // ---- min_record_size ----

    #[test]
    fn test_min_record_size_all_formats() {
        assert_eq!(min_record_size(0).expect("f0"), 20);
        assert_eq!(min_record_size(1).expect("f1"), 28);
        assert_eq!(min_record_size(2).expect("f2"), 26);
        assert_eq!(min_record_size(3).expect("f3"), 34);
        assert_eq!(min_record_size(6).expect("f6"), 30);
        assert_eq!(min_record_size(7).expect("f7"), 36);
        assert_eq!(min_record_size(8).expect("f8"), 38);
    }

    #[test]
    fn test_min_record_size_unsupported() {
        assert!(min_record_size(4).is_err());
        assert!(min_record_size(5).is_err());
        assert!(min_record_size(9).is_err());
        assert!(min_record_size(255).is_err());
    }

    // ---- deserialize_points (batch) ----

    #[test]
    fn test_deserialize_points_batch() {
        let rec1 = make_format0_record(1000, 2000, 3000, 100);
        let rec2 = make_format0_record(4000, 5000, 6000, 200);
        let mut data = rec1;
        data.extend_from_slice(&rec2);
        let pts = deserialize_points(&data, 2, 20, 0, [0.001; 3], [0.0; 3]).expect("batch");
        assert_eq!(pts.len(), 2);
        assert!((pts[0].x - 1.0).abs() < 1e-9);
        assert!((pts[1].x - 4.0).abs() < 1e-9);
    }

    #[test]
    fn test_deserialize_points_batch_too_short() {
        let data = vec![0u8; 30]; // only 30 bytes, not enough for 2 records of 20
        assert!(deserialize_points(&data, 2, 20, 0, [1.0; 3], [0.0; 3]).is_err());
    }

    #[test]
    fn test_deserialize_points_zero_count() {
        let pts = deserialize_points(&[], 0, 20, 0, [1.0; 3], [0.0; 3]).expect("zero");
        assert!(pts.is_empty());
    }

    #[test]
    fn test_format0_negative_coordinates() {
        let rec = make_format0_record(-5000, -10000, -500, 0);
        let pt = deserialize_point(&rec, 0, [0.001; 3], [0.0; 3]).expect("negative coords");
        assert!((pt.x - (-5.0)).abs() < 1e-9);
        assert!((pt.y - (-10.0)).abs() < 1e-9);
        assert!((pt.z - (-0.5)).abs() < 1e-9);
    }

    #[test]
    fn test_unsupported_format_id() {
        let rec = vec![0u8; 50];
        assert!(deserialize_point(&rec, 4, [1.0; 3], [0.0; 3]).is_err());
        assert!(deserialize_point(&rec, 5, [1.0; 3], [0.0; 3]).is_err());
        assert!(deserialize_point(&rec, 10, [1.0; 3], [0.0; 3]).is_err());
    }

    #[test]
    fn test_format6_extended_return_numbers_up_to_15() {
        let mut rec = make_format6_record(0, 0, 0, 0.0);
        // Return number 15, number of returns 15
        rec[14] = 15 | (15 << 4);
        let pt = deserialize_point(&rec, 6, [1.0; 3], [0.0; 3]).expect("format 6 max returns");
        assert_eq!(pt.return_number, 15);
        assert_eq!(pt.number_of_returns, 15);
    }

    #[test]
    fn test_deserialize_points_with_record_length_padding() {
        // Record length 24 but format 0 only needs 20 -- 4 bytes padding
        let mut data = make_format0_record(1000, 0, 0, 0);
        data.extend_from_slice(&[0u8; 4]); // padding
        let mut data2 = make_format0_record(2000, 0, 0, 0);
        data2.extend_from_slice(&[0u8; 4]); // padding
        data.extend_from_slice(&data2);
        let pts =
            deserialize_points(&data, 2, 24, 0, [0.001; 3], [0.0; 3]).expect("padded records");
        assert_eq!(pts.len(), 2);
        assert!((pts[0].x - 1.0).abs() < 1e-9);
        assert!((pts[1].x - 2.0).abs() < 1e-9);
    }
}