draco-core 1.0.3

Pure Rust core encoder and decoder for Draco geometry compression
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
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
use crate::compression_config::EncodedGeometryType;
use crate::corner_table::CornerTable;
#[cfg(feature = "point_cloud_decode")]
use crate::decoder_buffer::DecoderBuffer;
#[cfg(feature = "point_cloud_decode")]
use crate::draco_types::DataType;
#[cfg(feature = "point_cloud_decode")]
use crate::geometry_attribute::{GeometryAttributeType, PointAttribute};
#[cfg(feature = "point_cloud_decode")]
use crate::geometry_indices::PointIndex;
#[cfg(feature = "point_cloud_decode")]
use crate::kd_tree_attributes_decoder::KdTreeAttributesDecoder;
use crate::mesh::Mesh;
use crate::point_cloud::PointCloud;
#[cfg(feature = "point_cloud_decode")]
use crate::sequential_integer_attribute_decoder::SequentialIntegerAttributeDecoder;
#[cfg(feature = "point_cloud_decode")]
use crate::status::{DracoError, Status};

#[cfg(feature = "point_cloud_decode")]
use crate::attribute_octahedron_transform::AttributeOctahedronTransform;
#[cfg(feature = "point_cloud_decode")]
use crate::attribute_quantization_transform::AttributeQuantizationTransform;
#[cfg(feature = "point_cloud_decode")]
use crate::attribute_transform::AttributeTransform;
#[cfg(feature = "point_cloud_decode")]
use crate::version::{version_at_least, VERSION_FLAGS_INTRODUCED};

/// Internal geometry context used by attribute decoders.
pub trait GeometryDecoder {
    /// Returns point-cloud geometry when available.
    fn point_cloud(&self) -> Option<&PointCloud>;
    /// Returns mesh geometry when available.
    fn mesh(&self) -> Option<&Mesh>;
    /// Returns mesh corner-table topology when available.
    fn corner_table(&self) -> Option<&CornerTable>;
    /// Returns the encoded geometry type.
    fn get_geometry_type(&self) -> EncodedGeometryType;
    /// Returns the attribute encoding method for an attribute id, if known.
    fn get_attribute_encoding_method(&self, _att_id: i32) -> Option<i32> {
        None
    }
}

/// Decoder for Draco point cloud bitstreams.
///
/// `PointCloudDecoder` reads a point-cloud `.drc` bitstream and reconstructs a
/// [`PointCloud`] with its attributes and metadata. Both
/// KD-tree and sequential attribute encodings are supported (the actual decode
/// requires the `point_cloud_decode` feature).
///
/// A round trip is shown on the `PointCloudEncoder` type docs.
pub struct PointCloudDecoder {
    geometry_type: EncodedGeometryType,
    #[cfg(feature = "point_cloud_decode")]
    method: u8,
    #[cfg(feature = "point_cloud_decode")]
    flags: u16,
    #[cfg(feature = "point_cloud_decode")]
    version_major: u8,
    #[cfg(feature = "point_cloud_decode")]
    version_minor: u8,
}

impl GeometryDecoder for PointCloudDecoder {
    fn point_cloud(&self) -> Option<&PointCloud> {
        None // PointCloudDecoder constructs PointCloud, doesn't hold it?
             // Actually decode takes &mut PointCloud.
             // So we can't return it here easily unless we store it.
             // But GeometryDecoder is usually passed to attribute decoders.
             // Attribute decoders take PointCloud as argument.
    }

    fn mesh(&self) -> Option<&Mesh> {
        None
    }

    fn corner_table(&self) -> Option<&CornerTable> {
        None
    }

    fn get_geometry_type(&self) -> EncodedGeometryType {
        self.geometry_type
    }
}

impl Default for PointCloudDecoder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(feature = "point_cloud_decode")]
fn make_point_ids(num_points: usize) -> Result<Vec<PointIndex>, DracoError> {
    let mut point_ids = Vec::new();
    point_ids
        .try_reserve_exact(num_points)
        .map_err(|_| DracoError::DracoError("Failed to allocate point ids".to_string()))?;
    for i in 0..num_points {
        point_ids.push(PointIndex(i as u32));
    }
    Ok(point_ids)
}

#[cfg(feature = "point_cloud_decode")]
fn validate_num_attributes_in_decoder(
    num_attributes_in_decoder: usize,
    remaining_bytes: usize,
) -> Result<(), DracoError> {
    // Each attribute must have at least type, data type, component count,
    // normalized flag, unique id, and a decoder type byte. Reject impossible
    // counts before reserving vectors from untrusted input.
    const MIN_ATTRIBUTE_BYTES: usize = 6;
    if num_attributes_in_decoder == 0
        || num_attributes_in_decoder > remaining_bytes / MIN_ATTRIBUTE_BYTES
    {
        return Err(DracoError::DracoError(
            "Invalid number of attributes".to_string(),
        ));
    }
    Ok(())
}

#[cfg(feature = "point_cloud_decode")]
fn validate_num_components(num_components: u8) -> Result<(), DracoError> {
    if num_components == 0 {
        return Err(DracoError::DracoError(
            "Invalid attribute component count".to_string(),
        ));
    }
    Ok(())
}

#[cfg(feature = "point_cloud_decode")]
fn decode_raw_attribute_values(
    buffer: &mut DecoderBuffer<'_>,
    attribute: &mut PointAttribute,
    num_points: usize,
) -> Result<(), DracoError> {
    let entry_size = attribute.byte_stride() as usize;
    if entry_size == 0 {
        return Err(DracoError::DracoError(
            "Invalid point cloud attribute entry size".to_string(),
        ));
    }
    let required_size = entry_size.checked_mul(num_points).ok_or_else(|| {
        DracoError::DracoError("Point cloud raw attribute byte count overflow".to_string())
    })?;

    let dst = attribute.buffer_mut().data_mut();
    if dst.len() < required_size {
        return Err(DracoError::DracoError(
            "Point cloud attribute buffer too small".to_string(),
        ));
    }

    for chunk in dst[..required_size].chunks_exact_mut(entry_size) {
        buffer.decode_bytes(chunk).map_err(|_| {
            DracoError::DracoError("Failed to decode raw point cloud attribute values".to_string())
        })?;
    }

    Ok(())
}

impl PointCloudDecoder {
    /// Creates a point cloud decoder with default state.
    pub fn new() -> Self {
        Self {
            geometry_type: EncodedGeometryType::PointCloud,
            #[cfg(feature = "point_cloud_decode")]
            method: 0,
            #[cfg(feature = "point_cloud_decode")]
            flags: 0,
            #[cfg(feature = "point_cloud_decode")]
            version_major: 0,
            #[cfg(feature = "point_cloud_decode")]
            version_minor: 0,
        }
    }

    #[cfg(feature = "point_cloud_decode")]
    /// Decodes a Draco point cloud from `in_buffer` into `out_pc`.
    ///
    /// # Errors
    ///
    /// Returns an error if the header is invalid, the bitstream version is
    /// unsupported, or the encoded attributes are malformed.
    pub fn decode(&mut self, in_buffer: &mut DecoderBuffer, out_pc: &mut PointCloud) -> Status {
        // 1. Decode Header
        self.decode_header(in_buffer)?;

        if version_at_least(
            self.version_major,
            self.version_minor,
            VERSION_FLAGS_INTRODUCED,
        ) && (self.flags & crate::metadata::METADATA_FLAG_MASK) != 0
        {
            let metadata = crate::metadata::GeometryMetadata::decode(in_buffer)
                .map_err(|_| DracoError::DracoError("Failed to decode metadata".to_string()))?;
            out_pc.set_metadata(Some(metadata));
        }

        // 2. Decode Geometry Data
        self.decode_geometry_data(in_buffer, out_pc)
    }

    /// Decode point cloud data when header + metadata have already been parsed.
    /// Used by MeshDecoder to delegate point cloud streams.
    #[cfg(feature = "point_cloud_decode")]
    pub fn decode_after_header(
        &mut self,
        version_major: u8,
        version_minor: u8,
        method: u8,
        buffer: &mut DecoderBuffer,
        out_pc: &mut PointCloud,
    ) -> Status {
        self.version_major = version_major;
        self.version_minor = version_minor;
        self.method = method;
        self.flags = 0;
        self.geometry_type = EncodedGeometryType::PointCloud;
        self.decode_geometry_data(buffer, out_pc)
    }

    #[cfg(feature = "point_cloud_decode")]
    fn decode_header(&mut self, buffer: &mut DecoderBuffer) -> Status {
        let mut magic = [0u8; 5];
        buffer.decode_bytes(&mut magic)?;
        if &magic != b"DRACO" {
            return Err(DracoError::DracoError("Invalid magic".to_string()));
        }

        self.version_major = buffer.decode_u8()?;
        self.version_minor = buffer.decode_u8()?;
        buffer.set_version(self.version_major, self.version_minor);

        let g_type = buffer.decode_u8()?;
        self.geometry_type = match g_type {
            0 => EncodedGeometryType::PointCloud,
            1 => EncodedGeometryType::TriangularMesh,
            _ => return Err(DracoError::DracoError("Invalid geometry type".to_string())),
        };
        if self.geometry_type != EncodedGeometryType::PointCloud {
            return Err(DracoError::DracoError(
                "PointCloudDecoder cannot decode mesh bitstreams".to_string(),
            ));
        }

        self.method = buffer.decode_u8()?;

        // Flags field is always present in the binary header (C++ reads unconditionally).
        self.flags = buffer
            .decode_u16()
            .map_err(|_| DracoError::DracoError("Failed to decode flags".to_string()))?;

        Ok(())
    }

    #[cfg(feature = "point_cloud_decode")]
    fn decode_geometry_data(&mut self, buffer: &mut DecoderBuffer, pc: &mut PointCloud) -> Status {
        let bitstream_version: u16 =
            crate::version::bitstream_version(self.version_major, self.version_minor);
        // Note: Draco point cloud bitstreams encode the number of points as a
        // fixed-width int32 for both sequential (method=0) and KD-tree
        // (method=1) encodings (see C++ PointCloudSequentialDecoder and
        // PointCloudKdTreeDecoder). It is NOT varint encoded, even for v2.x.
        let num_points: usize = buffer.decode_u32()? as usize;
        // Consistency guard: a Draco point cloud encodes at least one bit per
        // point (no real encoder, including C++ Draco, produces sub-bit-per-point
        // streams), so a point count beyond the remaining bit budget is
        // malformed. This bounds the per-attribute buffers that are sized by
        // num_points and prevents memory amplification from a tiny malformed
        // header, for both the sequential and KD-tree paths. It is a relative
        // input-consistency check, not an artificial geometry cap, and runs once
        // per decode off the hot path.
        if num_points > buffer.remaining_size().saturating_mul(8) {
            return Err(DracoError::DracoError(
                "Point count exceeds remaining bitstream size".to_string(),
            ));
        }
        pc.set_num_points(num_points);

        let num_attributes_decoders = buffer.decode_u8()? as usize;

        if self.method == 1 {
            // KD-tree encoding.
            for _ in 0..num_attributes_decoders {
                let mut att_decoder = KdTreeAttributesDecoder::new(0);
                if !att_decoder.decode_attributes_decoder_data(pc, buffer) {
                    return Err(DracoError::DracoError(
                        "Failed to decode attribute metadata".to_string(),
                    ));
                }
                if !att_decoder.decode_attributes(pc, buffer) {
                    return Err(DracoError::DracoError(
                        "Failed to decode attributes".to_string(),
                    ));
                }
            }
        } else {
            // Sequential encoding.
            struct PendingQuant {
                att_id: i32,
                portable: PointAttribute,
                transform: AttributeQuantizationTransform,
            }

            struct PendingNormal {
                att_id: i32,
                portable: PointAttribute,
                quantization_bits: u8,
            }

            struct AttributeSpec {
                att_type: GeometryAttributeType,
                data_type: DataType,
                num_components: u8,
                normalized: bool,
                unique_id: u32,
            }

            for _ in 0..num_attributes_decoders {
                let num_attributes_in_decoder: usize = if bitstream_version < 0x0200 {
                    buffer.decode_u32()? as usize
                } else {
                    buffer.decode_varint()? as usize
                };
                if num_attributes_in_decoder == 0 {
                    return Err(DracoError::DracoError(
                        "Invalid number of attributes".to_string(),
                    ));
                }
                validate_num_attributes_in_decoder(
                    num_attributes_in_decoder,
                    buffer.remaining_size(),
                )?;

                let mut attribute_specs: Vec<AttributeSpec> =
                    Vec::with_capacity(num_attributes_in_decoder);
                let mut att_ids: Vec<i32> = Vec::with_capacity(num_attributes_in_decoder);
                let mut decoder_types: Vec<u8> = Vec::with_capacity(num_attributes_in_decoder);
                let mut pending_quant: Vec<PendingQuant> = Vec::new();
                let mut pending_normals: Vec<PendingNormal> = Vec::new();

                for _ in 0..num_attributes_in_decoder {
                    let att_type_val = buffer.decode_u8()?;
                    let att_type = GeometryAttributeType::try_from(att_type_val)?;

                    let data_type_val = buffer.decode_u8()?;
                    let data_type = DataType::try_from(data_type_val)?;

                    let num_components = buffer.decode_u8()?;
                    validate_num_components(num_components)?;
                    let normalized = buffer.decode_u8()? != 0;
                    let unique_id: u32 = if bitstream_version < 0x0103 {
                        buffer.decode_u16()? as u32
                    } else {
                        buffer.decode_varint()? as u32
                    };

                    attribute_specs.push(AttributeSpec {
                        att_type,
                        data_type,
                        num_components,
                        normalized,
                        unique_id,
                    });
                }

                for _ in 0..num_attributes_in_decoder {
                    decoder_types.push(buffer.decode_u8()?);
                }

                for (local_i, spec) in attribute_specs.iter().enumerate() {
                    if decoder_types[local_i] == 0 {
                        let entry_size =
                            spec.num_components as usize * spec.data_type.byte_length();
                        let bytes_needed = entry_size.checked_mul(num_points).ok_or_else(|| {
                            DracoError::DracoError(
                                "Raw point cloud attribute byte count overflow".to_string(),
                            )
                        })?;
                        if buffer.remaining_size() < bytes_needed {
                            return Err(DracoError::DracoError(
                                "Not enough data for raw point cloud attribute values".to_string(),
                            ));
                        }
                    }

                    let mut att = PointAttribute::new();
                    att.try_init(
                        spec.att_type,
                        spec.num_components,
                        spec.data_type,
                        spec.normalized,
                        num_points,
                    )?;
                    att.set_unique_id(spec.unique_id);
                    let att_id = pc.add_attribute_preserve_unique_id(att);
                    att_ids.push(att_id);
                }

                let point_ids = if decoder_types.iter().any(|&decoder_type| decoder_type != 0) {
                    Some(make_point_ids(num_points)?)
                } else {
                    None
                };

                for (local_i, &att_id) in att_ids.iter().enumerate() {
                    let decoder_type = decoder_types[local_i];
                    match decoder_type {
                        1 => {
                            let point_ids = point_ids.as_ref().ok_or_else(|| {
                                DracoError::DracoError(
                                    "Point ids missing for integer attribute decoder".to_string(),
                                )
                            })?;
                            let mut att_decoder = SequentialIntegerAttributeDecoder::new();
                            att_decoder.init(self, att_id);
                            if !att_decoder.decode_values(
                                pc, point_ids, buffer, None, None, None, None, None, None,
                            ) {
                                return Err(DracoError::DracoError(
                                    "Failed to decode integer attribute".to_string(),
                                ));
                            }
                        }
                        2 => {
                            let original = pc.try_attribute(att_id)?;
                            let (original_type, original_num_components) =
                                (original.attribute_type(), original.num_components());
                            let mut portable = PointAttribute::default();
                            portable.try_init(
                                original_type,
                                original_num_components,
                                DataType::Uint32,
                                false,
                                num_points,
                            )?;
                            let mut transform = AttributeQuantizationTransform::new();

                            // Legacy compatibility shim: C++ bitstreams with version <= 1.1
                            // store quantization params before integer values in the stream.
                            // v1.2+ (including Rust-generated v1.3) stores them after.
                            let quant_skip_bytes = if bitstream_version < 0x0102 {
                                let saved_pos = buffer.position();
                                let method_byte = buffer.decode_u8().map_err(|_| {
                                    DracoError::DracoError("read pred method".to_string())
                                })?;
                                if method_byte != 0xFF {
                                    let _transform_byte = buffer.decode_u8().map_err(|_| {
                                        DracoError::DracoError("read transform".to_string())
                                    })?;
                                }
                                let original = pc.try_attribute(att_id)?;
                                if !transform.decode_parameters(original, buffer) {
                                    return Err(DracoError::DracoError(
                                        "Failed to decode quantization parameters (v<2.0)"
                                            .to_string(),
                                    ));
                                }
                                let bytes_consumed = buffer.position() - saved_pos;
                                let pred_header_bytes = if method_byte != 0xFF { 2 } else { 1 };
                                let skip = bytes_consumed - pred_header_bytes;
                                buffer
                                    .set_position(saved_pos)
                                    .map_err(|_| DracoError::DracoError("buf reset".to_string()))?;
                                skip
                            } else {
                                0
                            };
                            let mut att_decoder = SequentialIntegerAttributeDecoder::new();
                            att_decoder.init(self, att_id);
                            let mut skip_fn =
                                move |buf: &mut crate::decoder_buffer::DecoderBuffer<'_>| -> bool {
                                    if quant_skip_bytes > 0
                                        && buf.try_advance(quant_skip_bytes).is_err()
                                    {
                                        return false;
                                    }
                                    true
                                };
                            let hook: Option<
                                &mut dyn FnMut(
                                    &mut crate::decoder_buffer::DecoderBuffer<'_>,
                                ) -> bool,
                            > = if quant_skip_bytes > 0 {
                                Some(&mut skip_fn)
                            } else {
                                None
                            };
                            if !att_decoder.decode_values(
                                pc,
                                point_ids.as_ref().ok_or_else(|| {
                                    DracoError::DracoError(
                                        "Point ids missing for quantized attribute decoder"
                                            .to_string(),
                                    )
                                })?,
                                buffer,
                                None,
                                None,
                                None,
                                Some(&mut portable),
                                None,
                                hook,
                            ) {
                                return Err(DracoError::DracoError(
                                    "Failed to decode quantized portable values".to_string(),
                                ));
                            }
                            pending_quant.push(PendingQuant {
                                att_id,
                                portable,
                                transform,
                            });
                        }
                        3 => {
                            let mut portable = PointAttribute::default();
                            portable.try_init(
                                GeometryAttributeType::Generic,
                                2,
                                DataType::Uint32,
                                false,
                                num_points,
                            )?;
                            // Legacy compatibility shim: C++ bitstreams with version <= 1.1
                            // store octahedron quantization bits after the prediction header
                            // but before integer values. v1.2+ stores them after.
                            let mut quant_bits: u8 = 0;
                            let normal_skip_bytes = if bitstream_version < 0x0102 {
                                let saved_pos = buffer.position();
                                let method_byte = buffer.decode_u8().map_err(|_| {
                                    DracoError::DracoError("read pred method".to_string())
                                })?;
                                if method_byte != 0xFF {
                                    let _transform_byte = buffer.decode_u8().map_err(|_| {
                                        DracoError::DracoError("read transform".to_string())
                                    })?;
                                }
                                quant_bits = buffer.decode_u8().map_err(|_| {
                                    DracoError::DracoError("read normal quant_bits".to_string())
                                })?;
                                if !AttributeOctahedronTransform::is_valid_quantization_bits(
                                    quant_bits as i32,
                                ) {
                                    return Err(DracoError::DracoError(
                                        "Invalid normal quantization bits".to_string(),
                                    ));
                                }
                                let bytes_consumed = buffer.position() - saved_pos;
                                let pred_header_bytes = if method_byte != 0xFF { 2 } else { 1 };
                                let skip = bytes_consumed - pred_header_bytes;
                                buffer
                                    .set_position(saved_pos)
                                    .map_err(|_| DracoError::DracoError("buf reset".to_string()))?;
                                skip
                            } else {
                                0
                            };
                            let mut att_decoder = SequentialIntegerAttributeDecoder::new();
                            att_decoder.init(self, att_id);
                            let mut skip_fn =
                                move |buf: &mut crate::decoder_buffer::DecoderBuffer<'_>| -> bool {
                                    if normal_skip_bytes > 0
                                        && buf.try_advance(normal_skip_bytes).is_err()
                                    {
                                        return false;
                                    }
                                    true
                                };
                            let hook: Option<
                                &mut dyn FnMut(
                                    &mut crate::decoder_buffer::DecoderBuffer<'_>,
                                ) -> bool,
                            > = if normal_skip_bytes > 0 {
                                Some(&mut skip_fn)
                            } else {
                                None
                            };
                            if !att_decoder.decode_values(
                                pc,
                                point_ids.as_ref().ok_or_else(|| {
                                    DracoError::DracoError(
                                        "Point ids missing for normal attribute decoder"
                                            .to_string(),
                                    )
                                })?,
                                buffer,
                                None,
                                None,
                                None,
                                Some(&mut portable),
                                None,
                                hook,
                            ) {
                                return Err(DracoError::DracoError(
                                    "Failed to decode normal portable values".to_string(),
                                ));
                            }
                            pending_normals.push(PendingNormal {
                                att_id,
                                portable,
                                quantization_bits: quant_bits,
                            });
                        }
                        0 => {
                            // Generic sequential values (raw), matching C++
                            // SequentialAttributeDecoder::DecodeValues().
                            decode_raw_attribute_values(
                                buffer,
                                pc.try_attribute_mut(att_id)?,
                                num_points,
                            )?;
                        }
                        _ => {
                            return Err(DracoError::DracoError(format!(
                                "Unsupported sequential decoder type: {}",
                                decoder_type
                            )));
                        }
                    }
                }

                for (local_i, &att_id) in att_ids.iter().enumerate() {
                    match decoder_types[local_i] {
                        2 if bitstream_version >= 0x0102 => {
                            let idx = pending_quant
                                .iter()
                                .position(|p| p.att_id == att_id)
                                .ok_or_else(|| {
                                    DracoError::DracoError(
                                        "Missing pending quantized attribute transform".to_string(),
                                    )
                                })?;
                            let original = pc.try_attribute(att_id)?;
                            if !pending_quant[idx]
                                .transform
                                .decode_parameters(original, buffer)
                            {
                                return Err(DracoError::DracoError(
                                    "Failed to decode quantization parameters".to_string(),
                                ));
                            }
                        }
                        3 if bitstream_version >= 0x0102 => {
                            let idx = pending_normals
                                .iter()
                                .position(|p| p.att_id == att_id)
                                .ok_or_else(|| {
                                    DracoError::DracoError(
                                        "Missing pending normal attribute transform".to_string(),
                                    )
                                })?;
                            let quantization_bits = buffer.decode_u8()?;
                            if !AttributeOctahedronTransform::is_valid_quantization_bits(
                                quantization_bits as i32,
                            ) {
                                return Err(DracoError::DracoError(
                                    "Invalid normal quantization bits".to_string(),
                                ));
                            }
                            pending_normals[idx].quantization_bits = quantization_bits;
                        }
                        _ => {}
                    }
                }

                for q in pending_quant {
                    let dst = pc.try_attribute_mut(q.att_id)?;
                    if !q.transform.inverse_transform_attribute(&q.portable, dst) {
                        return Err(DracoError::DracoError(
                            "Failed to dequantize attribute".to_string(),
                        ));
                    }
                }
                for n in pending_normals {
                    let mut oct = AttributeOctahedronTransform::new(-1);
                    if !oct.set_parameters(n.quantization_bits as i32) {
                        return Err(DracoError::DracoError(
                            "Invalid normal quantization bits".to_string(),
                        ));
                    }
                    let dst = pc.try_attribute_mut(n.att_id)?;
                    if !oct.inverse_transform_attribute_with_legacy_octahedron(
                        &n.portable,
                        dst,
                        bitstream_version < 0x0102,
                    ) {
                        return Err(DracoError::DracoError(
                            "Failed to decode normals".to_string(),
                        ));
                    }
                }
            }
        }

        Ok(())
    }

    /// Returns the encoded geometry type handled by this decoder.
    pub fn get_geometry_type(&self) -> EncodedGeometryType {
        self.geometry_type
    }
}

#[cfg(all(test, feature = "point_cloud_decode"))]
mod tests {
    use super::*;

    #[test]
    fn decode_raw_attribute_values_rejects_required_size_overflow() {
        let bytes = [];
        let mut buffer = DecoderBuffer::new(&bytes);
        let mut attribute = PointAttribute::new();
        attribute.init(
            GeometryAttributeType::Generic,
            1,
            DataType::Uint32,
            false,
            1,
        );

        let status = decode_raw_attribute_values(&mut buffer, &mut attribute, usize::MAX);

        assert!(status.is_err());
    }

    #[test]
    fn decode_raw_attribute_values_rejects_truncated_input() {
        let bytes = [1u8, 2, 3];
        let mut buffer = DecoderBuffer::new(&bytes);
        let mut attribute = PointAttribute::new();
        attribute.init(
            GeometryAttributeType::Generic,
            1,
            DataType::Uint32,
            false,
            1,
        );

        let status = decode_raw_attribute_values(&mut buffer, &mut attribute, 1);

        assert!(status.is_err());
    }
}