acadrust 0.3.2

A pure Rust library for reading and writing CAD files in DXF format (ASCII and Binary) and DWG format (Binary).
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
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
//! COLLADA (.dae) XML parser.
//!
//! Extracts mesh geometries, materials with diffuse colours, and visual-scene
//! transform hierarchies from a COLLADA 1.4 / 1.5 document.

use std::collections::HashMap;
use std::io::BufRead;

use quick_xml::events::Event;
use quick_xml::Reader;

use crate::error::{DxfError, Result};

/// A parsed COLLADA scene.
#[derive(Debug, Clone)]
pub struct ColladaScene {
    /// Geometries keyed by their `id` attribute.
    pub geometries: Vec<ColladaGeometry>,
    /// Materials keyed by their `id` attribute.
    pub materials: HashMap<String, ColladaMaterial>,
    /// Visual-scene nodes (geometry instances with transforms).
    pub nodes: Vec<ColladaNode>,
}

/// A single mesh geometry extracted from `<library_geometries>`.
#[derive(Debug, Clone)]
pub struct ColladaGeometry {
    pub id: String,
    pub name: String,
    pub vertices: Vec<[f64; 3]>,
    /// Each entry is a vector of vertex indices forming a triangle.
    pub triangles: Vec<ColladaPrimitive>,
}

/// A primitive group (triangles or polygons converted to triangles).
#[derive(Debug, Clone)]
pub struct ColladaPrimitive {
    /// Indices into the geometry's vertex array (groups of 3 for triangles).
    pub indices: Vec<usize>,
    /// Number of vertex attributes per index (stride). We only use the
    /// VERTEX/POSITION input, but skip the others.
    pub input_count: usize,
    /// Offset of the VERTEX/POSITION input within each index group.
    pub vertex_offset: usize,
    /// Material symbol binding (references `<bind_material>` in the instance).
    pub material_symbol: String,
}

/// Material with diffuse colour.
#[derive(Debug, Clone)]
pub struct ColladaMaterial {
    pub id: String,
    pub name: String,
    /// Diffuse colour (R, G, B, A) in 0.0–1.0 range.
    pub diffuse: [f32; 4],
}

/// A visual-scene node referencing a geometry with a transform.
#[derive(Debug, Clone)]
pub struct ColladaNode {
    pub name: String,
    /// Geometry URL (e.g. `#geom0`).
    pub geometry_url: String,
    /// Flattened 4×4 column-major transform matrix (identity if none).
    pub transform: [f64; 16],
    /// Material bindings: symbol → material id.
    pub material_bindings: HashMap<String, String>,
}

/// Parse a COLLADA XML document from a buffered reader.
pub fn parse_collada<R: BufRead>(reader: R) -> Result<ColladaScene> {
    let mut xml = Reader::from_reader(reader);
    xml.config_mut().trim_text(true);

    let mut scene = ColladaScene {
        geometries: Vec::new(),
        materials: HashMap::new(),
        nodes: Vec::new(),
    };

    // Effect id → diffuse colour (effects are referenced by materials)
    let mut effects: HashMap<String, [f32; 4]> = HashMap::new();
    // Material id → effect URL
    let mut material_to_effect: HashMap<String, String> = HashMap::new();

    let mut buf = Vec::new();

    loop {
        match xml.read_event_into(&mut buf) {
            Ok(Event::Start(ref e)) => {
                let name = e.name();
                let local = local_name(name.as_ref());
                match local {
                    b"geometry" => {
                        let geom = parse_geometry(&mut xml, &e)?;
                        scene.geometries.push(geom);
                    }
                    b"effect" => {
                        let id = attr_string(&e, b"id");
                        let color = parse_effect(&mut xml)?;
                        if let Some(id) = id {
                            effects.insert(id, color);
                        }
                    }
                    b"material" => {
                        let id = attr_string(&e, b"id");
                        let name = attr_string(&e, b"name")
                            .or_else(|| id.clone())
                            .unwrap_or_default();
                        // Read inner <instance_effect url="#effect_id"/>
                        let effect_url = parse_material_element(&mut xml)?;
                        if let (Some(id), Some(url)) = (id, effect_url) {
                            material_to_effect.insert(id.clone(), url);
                            // Placeholder – colour resolved later
                            scene.materials.insert(
                                id.clone(),
                                ColladaMaterial {
                                    id,
                                    name,
                                    diffuse: [0.8, 0.8, 0.8, 1.0],
                                },
                            );
                        }
                    }
                    b"visual_scene" => {
                        parse_visual_scene(&mut xml, &mut scene.nodes)?;
                    }
                    _ => {}
                }
            }
            Ok(Event::Eof) => break,
            Err(e) => {
                return Err(DxfError::ImportError(format!(
                    "COLLADA XML parse error: {}",
                    e
                )));
            }
            _ => {}
        }
        buf.clear();
    }

    // Resolve material → effect → diffuse colour
    for (mat_id, mat) in &mut scene.materials {
        if let Some(effect_url) = material_to_effect.get(mat_id) {
            let effect_id = effect_url.strip_prefix('#').unwrap_or(effect_url);
            if let Some(color) = effects.get(effect_id) {
                mat.diffuse = *color;
            }
        }
    }

    // If no visual_scene nodes exist, create one node per geometry
    if scene.nodes.is_empty() {
        for geom in &scene.geometries {
            scene.nodes.push(ColladaNode {
                name: geom.name.clone(),
                geometry_url: format!("#{}", geom.id),
                transform: IDENTITY_MATRIX,
                material_bindings: HashMap::new(),
            });
        }
    }

    Ok(scene)
}

const IDENTITY_MATRIX: [f64; 16] = [
    1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
];

// ─── Geometry parsing ────────────────────────────────────────────────────

fn parse_geometry<R: BufRead>(
    xml: &mut Reader<R>,
    start: &quick_xml::events::BytesStart<'_>,
) -> Result<ColladaGeometry> {
    let id = attr_string(start, b"id").unwrap_or_default();
    let name = attr_string(start, b"name")
        .unwrap_or_else(|| id.clone());

    let mut geom = ColladaGeometry {
        id,
        name,
        vertices: Vec::new(),
        triangles: Vec::new(),
    };

    // Source arrays keyed by id (e.g. "mesh-positions-array")
    let mut sources: HashMap<String, Vec<f64>> = HashMap::new();
    // <vertices> element maps its id to a source id
    let mut vertices_source: Option<(String, String)> = None;

    let mut buf = Vec::new();
    let mut depth = 1u32;

    loop {
        match xml.read_event_into(&mut buf) {
            Ok(Event::Start(ref e)) => {
                depth += 1;
                let name = e.name();
                let local = local_name(name.as_ref());
                match local {
                    b"source" => {
                        let src_id = attr_string(e, b"id").unwrap_or_default();
                        let floats = parse_source_floats(xml, &mut depth)?;
                        sources.insert(src_id, floats);
                    }
                    b"vertices" => {
                        let vert_id = attr_string(e, b"id").unwrap_or_default();
                        let source_ref = parse_vertices_element(xml, &mut depth)?;
                        vertices_source = Some((vert_id, source_ref));
                    }
                    b"triangles" | b"polylist" | b"polygons" => {
                        let prim = parse_primitives(xml, local, e, &mut depth)?;
                        geom.triangles.push(prim);
                    }
                    _ => {}
                }
            }
            Ok(Event::Empty(ref _e)) => {
                // Handle self-closing elements like <input ... />
                // These are consumed within their parent parsers
            }
            Ok(Event::End(_)) => {
                depth -= 1;
                if depth == 0 {
                    break;
                }
            }
            Ok(Event::Eof) => break,
            Err(e) => {
                return Err(DxfError::ImportError(format!(
                    "Error parsing geometry: {}",
                    e
                )));
            }
            _ => {}
        }
        buf.clear();
    }

    // Resolve vertex positions
    if let Some((_vert_id, source_ref)) = &vertices_source {
        let source_id = source_ref.strip_prefix('#').unwrap_or(source_ref);
        if let Some(floats) = sources.get(source_id) {
            geom.vertices = floats
                .chunks_exact(3)
                .map(|c| [c[0], c[1], c[2]])
                .collect();
        }
    } else {
        // Fallback: look for a source with "position" in the name
        for (sid, floats) in &sources {
            if sid.to_lowercase().contains("position") {
                geom.vertices = floats
                    .chunks_exact(3)
                    .map(|c| [c[0], c[1], c[2]])
                    .collect();
                break;
            }
        }
    }

    Ok(geom)
}

fn parse_source_floats<R: BufRead>(
    xml: &mut Reader<R>,
    depth: &mut u32,
) -> Result<Vec<f64>> {
    let mut floats = Vec::new();
    let mut buf = Vec::new();
    let entry_depth = *depth;

    loop {
        match xml.read_event_into(&mut buf) {
            Ok(Event::Start(ref e)) => {
                *depth += 1;
                let name = e.name();
                let local = local_name(name.as_ref());
                if local == b"float_array" {
                    // Read text content
                    let text = read_text_content(xml, depth)?;
                    floats = parse_float_list(&text);
                }
            }
            Ok(Event::End(_)) => {
                *depth -= 1;
                if *depth < entry_depth {
                    break;
                }
            }
            Ok(Event::Eof) => break,
            Err(e) => {
                return Err(DxfError::ImportError(format!(
                    "Error parsing source: {}",
                    e
                )));
            }
            _ => {}
        }
        buf.clear();
    }

    Ok(floats)
}

fn parse_vertices_element<R: BufRead>(
    xml: &mut Reader<R>,
    depth: &mut u32,
) -> Result<String> {
    let mut source_ref = String::new();
    let mut buf = Vec::new();
    let entry_depth = *depth;

    loop {
        match xml.read_event_into(&mut buf) {
            Ok(Event::Empty(ref e)) => {
                let name = e.name();
                let local = local_name(name.as_ref());
                if local == b"input" {
                    let semantic = attr_string(e, b"semantic").unwrap_or_default();
                    if semantic == "POSITION" {
                        source_ref = attr_string(e, b"source").unwrap_or_default();
                    }
                }
            }
            Ok(Event::Start(ref e)) => {
                *depth += 1;
                let name = e.name();
                let local = local_name(name.as_ref());
                if local == b"input" {
                    let semantic = attr_string(e, b"semantic").unwrap_or_default();
                    if semantic == "POSITION" {
                        source_ref = attr_string(e, b"source").unwrap_or_default();
                    }
                }
            }
            Ok(Event::End(_)) => {
                *depth -= 1;
                if *depth < entry_depth {
                    break;
                }
            }
            Ok(Event::Eof) => break,
            Err(e) => {
                return Err(DxfError::ImportError(format!(
                    "Error parsing vertices: {}",
                    e
                )));
            }
            _ => {}
        }
        buf.clear();
    }

    Ok(source_ref)
}

fn parse_primitives<R: BufRead>(
    xml: &mut Reader<R>,
    prim_type: &[u8],
    start: &quick_xml::events::BytesStart<'_>,
    depth: &mut u32,
) -> Result<ColladaPrimitive> {
    let material_symbol = attr_string(start, b"material").unwrap_or_default();
    let _count: usize = attr_string(start, b"count")
        .and_then(|s| s.parse().ok())
        .unwrap_or(0);

    let mut inputs: Vec<(String, usize)> = Vec::new(); // (semantic, offset)
    let mut indices_text = String::new();
    let mut vcount_text = String::new();
    let mut buf = Vec::new();
    let entry_depth = *depth;

    loop {
        match xml.read_event_into(&mut buf) {
            Ok(Event::Empty(ref e)) => {
                let name = e.name();
                let local = local_name(name.as_ref());
                if local == b"input" {
                    let semantic = attr_string(e, b"semantic").unwrap_or_default();
                    let offset: usize = attr_string(e, b"offset")
                        .and_then(|s| s.parse().ok())
                        .unwrap_or(0);
                    inputs.push((semantic, offset));
                }
            }
            Ok(Event::Start(ref e)) => {
                *depth += 1;
                let name = e.name();
                let local = local_name(name.as_ref());
                match local {
                    b"input" => {
                        let semantic = attr_string(e, b"semantic").unwrap_or_default();
                        let offset: usize = attr_string(e, b"offset")
                            .and_then(|s| s.parse().ok())
                            .unwrap_or(0);
                        inputs.push((semantic, offset));
                    }
                    b"p" => {
                        indices_text = read_text_content(xml, depth)?;
                    }
                    b"vcount" => {
                        vcount_text = read_text_content(xml, depth)?;
                    }
                    _ => {}
                }
            }
            Ok(Event::End(_)) => {
                *depth -= 1;
                if *depth < entry_depth {
                    break;
                }
            }
            Ok(Event::Eof) => break,
            Err(e) => {
                return Err(DxfError::ImportError(format!(
                    "Error parsing primitives: {}",
                    e
                )));
            }
            _ => {}
        }
        buf.clear();
    }

    let input_count = if inputs.is_empty() {
        1
    } else {
        inputs.iter().map(|(_, o)| o + 1).max().unwrap_or(1)
    };

    let vertex_offset = inputs
        .iter()
        .find(|(s, _)| s == "VERTEX" || s == "POSITION")
        .map(|(_, o)| *o)
        .unwrap_or(0);

    let all_indices: Vec<usize> = indices_text
        .split_whitespace()
        .filter_map(|s| s.parse::<usize>().ok())
        .collect();

    // For polylist/polygons, convert to triangles via fan triangulation
    let triangle_indices = if prim_type == b"polylist" && !vcount_text.is_empty() {
        let vcounts: Vec<usize> = vcount_text
            .split_whitespace()
            .filter_map(|s| s.parse::<usize>().ok())
            .collect();
        polylist_to_triangles(&all_indices, &vcounts, input_count, vertex_offset)
    } else if prim_type == b"triangles" {
        // Already triangles — just extract vertex indices
        extract_vertex_indices(&all_indices, input_count, vertex_offset)
    } else {
        // polygons — treat each <p> as a polygon, but we only have one <p> here
        // Treat as triangles
        extract_vertex_indices(&all_indices, input_count, vertex_offset)
    };

    Ok(ColladaPrimitive {
        indices: triangle_indices,
        input_count,
        vertex_offset,
        material_symbol,
    })
}

/// Extract just the vertex position indices from interleaved index data.
fn extract_vertex_indices(
    all_indices: &[usize],
    input_count: usize,
    vertex_offset: usize,
) -> Vec<usize> {
    all_indices
        .chunks(input_count)
        .map(|chunk| {
            if vertex_offset < chunk.len() {
                chunk[vertex_offset]
            } else {
                0
            }
        })
        .collect()
}

/// Convert polylist variable-count faces to triangles using fan triangulation.
fn polylist_to_triangles(
    all_indices: &[usize],
    vcounts: &[usize],
    input_count: usize,
    vertex_offset: usize,
) -> Vec<usize> {
    let mut result = Vec::new();
    let mut pos = 0;

    for &vc in vcounts {
        let face_start = pos;
        let face_verts: Vec<usize> = (0..vc)
            .map(|i| {
                let idx = face_start + i * input_count + vertex_offset;
                if idx < all_indices.len() {
                    all_indices[idx]
                } else {
                    0
                }
            })
            .collect();

        // Fan triangulation: (v0, v1, v2), (v0, v2, v3), ...
        if face_verts.len() >= 3 {
            for i in 1..face_verts.len() - 1 {
                result.push(face_verts[0]);
                result.push(face_verts[i]);
                result.push(face_verts[i + 1]);
            }
        }

        pos += vc * input_count;
    }

    result
}

// ─── Effect parsing ──────────────────────────────────────────────────────

fn parse_effect<R: BufRead>(xml: &mut Reader<R>) -> Result<[f32; 4]> {
    let mut diffuse = [0.8f32, 0.8, 0.8, 1.0];
    let mut buf = Vec::new();
    let mut depth = 1u32;
    let mut in_diffuse = false;

    loop {
        match xml.read_event_into(&mut buf) {
            Ok(Event::Start(ref e)) => {
                depth += 1;
                let name = e.name();
                let local = local_name(name.as_ref());
                if local == b"diffuse" {
                    in_diffuse = true;
                }
                if in_diffuse && local == b"color" {
                    let text = read_text_content(xml, &mut depth)?;
                    let vals: Vec<f32> = text
                        .split_whitespace()
                        .filter_map(|s| s.parse::<f32>().ok())
                        .collect();
                    if vals.len() >= 3 {
                        diffuse[0] = vals[0];
                        diffuse[1] = vals[1];
                        diffuse[2] = vals[2];
                        if vals.len() >= 4 {
                            diffuse[3] = vals[3];
                        }
                    }
                    in_diffuse = false;
                }
            }
            Ok(Event::End(_)) => {
                depth -= 1;
                if depth == 0 {
                    break;
                }
                // Reset in_diffuse when leaving <diffuse>
                if in_diffuse {
                    in_diffuse = false;
                }
            }
            Ok(Event::Eof) => break,
            Err(e) => {
                return Err(DxfError::ImportError(format!(
                    "Error parsing effect: {}",
                    e
                )));
            }
            _ => {}
        }
        buf.clear();
    }

    Ok(diffuse)
}

// ─── Material element parsing ────────────────────────────────────────────

fn parse_material_element<R: BufRead>(xml: &mut Reader<R>) -> Result<Option<String>> {
    let mut effect_url = None;
    let mut buf = Vec::new();
    let mut depth = 1u32;

    loop {
        match xml.read_event_into(&mut buf) {
            Ok(Event::Empty(ref e)) => {
                let name = e.name();
                let local = local_name(name.as_ref());
                if local == b"instance_effect" {
                    effect_url = attr_string(e, b"url");
                }
            }
            Ok(Event::Start(ref e)) => {
                depth += 1;
                let name = e.name();
                let local = local_name(name.as_ref());
                if local == b"instance_effect" {
                    effect_url = attr_string(e, b"url");
                }
            }
            Ok(Event::End(_)) => {
                depth -= 1;
                if depth == 0 {
                    break;
                }
            }
            Ok(Event::Eof) => break,
            Err(e) => {
                return Err(DxfError::ImportError(format!(
                    "Error parsing material: {}",
                    e
                )));
            }
            _ => {}
        }
        buf.clear();
    }

    Ok(effect_url)
}

// ─── Visual scene parsing ────────────────────────────────────────────────

fn parse_visual_scene<R: BufRead>(
    xml: &mut Reader<R>,
    nodes: &mut Vec<ColladaNode>,
) -> Result<()> {
    let mut buf = Vec::new();
    let mut depth = 1u32;

    loop {
        match xml.read_event_into(&mut buf) {
            Ok(Event::Start(ref e)) => {
                depth += 1;
                let name = e.name();
                let local = local_name(name.as_ref());
                if local == b"node" {
                    let name = attr_string(e, b"name").unwrap_or_default();
                    let node = parse_node(xml, &name, &mut depth)?;
                    if let Some(n) = node {
                        nodes.push(n);
                    }
                }
            }
            Ok(Event::End(_)) => {
                depth -= 1;
                if depth == 0 {
                    break;
                }
            }
            Ok(Event::Eof) => break,
            Err(e) => {
                return Err(DxfError::ImportError(format!(
                    "Error parsing visual_scene: {}",
                    e
                )));
            }
            _ => {}
        }
        buf.clear();
    }

    Ok(())
}

fn parse_node<R: BufRead>(
    xml: &mut Reader<R>,
    name: &str,
    depth: &mut u32,
) -> Result<Option<ColladaNode>> {
    let mut transform = IDENTITY_MATRIX;
    let mut geometry_url = String::new();
    let mut material_bindings: HashMap<String, String> = HashMap::new();
    let mut buf = Vec::new();

    loop {
        match xml.read_event_into(&mut buf) {
            Ok(Event::Start(ref e)) => {
                *depth += 1;
                let name = e.name();
                let local = local_name(name.as_ref());
                match local {
                    b"matrix" => {
                        let text = read_text_content(xml, depth)?;
                        let vals: Vec<f64> = text
                            .split_whitespace()
                            .filter_map(|s| s.parse::<f64>().ok())
                            .collect();
                        if vals.len() == 16 {
                            // COLLADA matrices are row-major; convert to column-major
                            transform = row_to_col_major(&vals);
                        }
                    }
                    b"instance_geometry" => {
                        geometry_url = attr_string(e, b"url").unwrap_or_default();
                        // Parse bind_material inside
                        parse_instance_geometry_bindings(xml, depth, &mut material_bindings)?;
                    }
                    b"node" => {
                        // Skip nested nodes for now
                        skip_element(xml, depth)?;
                    }
                    _ => {}
                }
            }
            Ok(Event::Empty(ref e)) => {
                let name = e.name();
                let local = local_name(name.as_ref());
                if local == b"instance_geometry" {
                    geometry_url = attr_string(e, b"url").unwrap_or_default();
                }
            }
            Ok(Event::End(_)) => {
                *depth -= 1;
                break;
            }
            Ok(Event::Eof) => break,
            Err(e) => {
                return Err(DxfError::ImportError(format!(
                    "Error parsing node: {}",
                    e
                )));
            }
            _ => {}
        }
        buf.clear();
    }

    if geometry_url.is_empty() {
        Ok(None)
    } else {
        Ok(Some(ColladaNode {
            name: name.to_string(),
            geometry_url,
            transform,
            material_bindings,
        }))
    }
}

fn parse_instance_geometry_bindings<R: BufRead>(
    xml: &mut Reader<R>,
    depth: &mut u32,
    bindings: &mut HashMap<String, String>,
) -> Result<()> {
    let mut buf = Vec::new();

    loop {
        match xml.read_event_into(&mut buf) {
            Ok(Event::Empty(ref e)) => {
                let name = e.name();
                let local = local_name(name.as_ref());
                if local == b"instance_material" {
                    let symbol = attr_string(e, b"symbol").unwrap_or_default();
                    let target = attr_string(e, b"target").unwrap_or_default();
                    let target = target.strip_prefix('#').unwrap_or(&target).to_string();
                    if !symbol.is_empty() {
                        bindings.insert(symbol, target);
                    }
                }
            }
            Ok(Event::Start(ref e)) => {
                *depth += 1;
                let name = e.name();
                let local = local_name(name.as_ref());
                if local == b"instance_material" {
                    let symbol = attr_string(e, b"symbol").unwrap_or_default();
                    let target = attr_string(e, b"target").unwrap_or_default();
                    let target = target.strip_prefix('#').unwrap_or(&target).to_string();
                    if !symbol.is_empty() {
                        bindings.insert(symbol, target);
                    }
                }
            }
            Ok(Event::End(_)) => {
                *depth -= 1;
                break;
            }
            Ok(Event::Eof) => break,
            Err(e) => {
                return Err(DxfError::ImportError(format!(
                    "Error parsing instance bindings: {}",
                    e
                )));
            }
            _ => {}
        }
        buf.clear();
    }

    Ok(())
}

// ─── Helpers ─────────────────────────────────────────────────────────────

fn read_text_content<R: BufRead>(
    xml: &mut Reader<R>,
    depth: &mut u32,
) -> Result<String> {
    let mut text = String::new();
    let mut buf = Vec::new();

    loop {
        match xml.read_event_into(&mut buf) {
            Ok(Event::Text(ref e)) => {
                text.push_str(
                    &e.unescape()
                        .map_err(|er| DxfError::ImportError(format!("XML unescape error: {}", er)))?
                );
            }
            Ok(Event::End(_)) => {
                *depth -= 1;
                break;
            }
            Ok(Event::Eof) => break,
            Err(e) => {
                return Err(DxfError::ImportError(format!("XML read error: {}", e)));
            }
            _ => {}
        }
        buf.clear();
    }

    Ok(text)
}

fn skip_element<R: BufRead>(xml: &mut Reader<R>, depth: &mut u32) -> Result<()> {
    let mut buf = Vec::new();
    loop {
        match xml.read_event_into(&mut buf) {
            Ok(Event::Start(_)) => {
                *depth += 1;
            }
            Ok(Event::End(_)) => {
                *depth -= 1;
                break;
            }
            Ok(Event::Eof) => break,
            Err(e) => {
                return Err(DxfError::ImportError(format!("XML skip error: {}", e)));
            }
            _ => {}
        }
        buf.clear();
    }
    Ok(())
}

fn parse_float_list(text: &str) -> Vec<f64> {
    text.split_whitespace()
        .filter_map(|s| s.parse::<f64>().ok())
        .collect()
}

/// Get the local name (without namespace prefix) of an element.
fn local_name(full: &[u8]) -> &[u8] {
    if let Some(pos) = full.iter().position(|&b| b == b':') {
        &full[pos + 1..]
    } else {
        full
    }
}

/// Read a UTF-8 attribute value from a start element.
fn attr_string(e: &quick_xml::events::BytesStart<'_>, key: &[u8]) -> Option<String> {
    for attr in e.attributes().flatten() {
        if attr.key.as_ref() == key {
            return String::from_utf8(attr.value.to_vec()).ok();
        }
    }
    None
}

/// Convert a row-major 4×4 matrix to column-major.
fn row_to_col_major(row: &[f64]) -> [f64; 16] {
    [
        row[0], row[4], row[8], row[12], row[1], row[5], row[9], row[13], row[2], row[6],
        row[10], row[14], row[3], row[7], row[11], row[15],
    ]
}

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

    const SAMPLE_DAE: &str = r##"<?xml version="1.0" encoding="utf-8"?>
<COLLADA xmlns="http://www.collada.org/2005/11/COLLADASchema" version="1.4.1">
  <library_effects>
    <effect id="effect0">
      <profile_COMMON>
        <technique sid="common">
          <phong>
            <diffuse>
              <color>1.0 0.0 0.0 1.0</color>
            </diffuse>
          </phong>
        </technique>
      </profile_COMMON>
    </effect>
  </library_effects>
  <library_materials>
    <material id="material0" name="RedMat">
      <instance_effect url="#effect0"/>
    </material>
  </library_materials>
  <library_geometries>
    <geometry id="geom0" name="Triangle">
      <mesh>
        <source id="positions">
          <float_array id="positions-array" count="9">
            0 0 0  1 0 0  0 1 0
          </float_array>
          <technique_common>
            <accessor source="#positions-array" count="3" stride="3">
              <param name="X" type="float"/>
              <param name="Y" type="float"/>
              <param name="Z" type="float"/>
            </accessor>
          </technique_common>
        </source>
        <vertices id="verts">
          <input semantic="POSITION" source="#positions"/>
        </vertices>
        <triangles count="1" material="mat_sym">
          <input semantic="VERTEX" source="#verts" offset="0"/>
          <p>0 1 2</p>
        </triangles>
      </mesh>
    </geometry>
  </library_geometries>
  <library_visual_scenes>
    <visual_scene id="Scene" name="Scene">
      <node name="TriNode">
        <instance_geometry url="#geom0">
          <bind_material>
            <technique_common>
              <instance_material symbol="mat_sym" target="#material0"/>
            </technique_common>
          </bind_material>
        </instance_geometry>
      </node>
    </visual_scene>
  </library_visual_scenes>
</COLLADA>"##;

    #[test]
    fn test_parse_sample_dae() {
        let reader = BufReader::new(SAMPLE_DAE.as_bytes());
        let scene = parse_collada(reader).unwrap();

        assert_eq!(scene.geometries.len(), 1);
        assert_eq!(scene.geometries[0].name, "Triangle");
        assert_eq!(scene.geometries[0].vertices.len(), 3);
        assert_eq!(scene.geometries[0].triangles.len(), 1);
        assert_eq!(scene.geometries[0].triangles[0].indices, vec![0, 1, 2]);

        assert_eq!(scene.materials.len(), 1);
        let mat = scene.materials.get("material0").unwrap();
        assert_eq!(mat.name, "RedMat");
        assert!((mat.diffuse[0] - 1.0).abs() < 0.01);
        assert!((mat.diffuse[1] - 0.0).abs() < 0.01);

        assert_eq!(scene.nodes.len(), 1);
        assert_eq!(scene.nodes[0].name, "TriNode");
        assert_eq!(scene.nodes[0].geometry_url, "#geom0");
        assert_eq!(
            scene.nodes[0].material_bindings.get("mat_sym"),
            Some(&"material0".to_string())
        );
    }

    #[test]
    fn test_row_to_col_major() {
        let row = [
            1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0,
            16.0,
        ];
        let col = row_to_col_major(&row);
        // Column 0: row[0], row[4], row[8], row[12]
        assert_eq!(col[0], 1.0);
        assert_eq!(col[1], 5.0);
        assert_eq!(col[2], 9.0);
        assert_eq!(col[3], 13.0);
    }
}