lib3mf 0.1.6

Pure Rust implementation for 3MF (3D Manufacturing Format) parsing and writing
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
//! Material extension parsing
//!
//! This module handles parsing of 3MF Material extension elements including
//! base materials, color groups, textures, composites, and multi-properties.

use crate::Model;
use crate::error::{Error, Result};
use crate::model::*;
use crate::opc::Package;
use quick_xml::Reader;
use std::io::Read;

use super::{parse_attributes, validate_attributes};

/// Parse color from hex string format (#RRGGBB or #RRGGBBAA)
pub(super) fn parse_color(color_str: &str) -> Option<(u8, u8, u8, u8)> {
    let color_str = color_str.trim_start_matches('#');

    if color_str.len() == 6 {
        // #RRGGBB format (assume full opacity)
        let r = u8::from_str_radix(&color_str[0..2], 16).ok()?;
        let g = u8::from_str_radix(&color_str[2..4], 16).ok()?;
        let b = u8::from_str_radix(&color_str[4..6], 16).ok()?;
        Some((r, g, b, 255))
    } else if color_str.len() == 8 {
        // #RRGGBBAA format
        let r = u8::from_str_radix(&color_str[0..2], 16).ok()?;
        let g = u8::from_str_radix(&color_str[2..4], 16).ok()?;
        let b = u8::from_str_radix(&color_str[4..6], 16).ok()?;
        let a = u8::from_str_radix(&color_str[6..8], 16).ok()?;
        Some((r, g, b, a))
    } else {
        None
    }
}

/// Parse material (base) element attributes
/// Base materials within a basematerials group use sequential indices (0, 1, 2, ...)
pub(super) fn parse_base_material<R: std::io::BufRead>(
    reader: &Reader<R>,
    e: &quick_xml::events::BytesStart,
    index: usize,
) -> Result<Material> {
    let attrs = parse_attributes(reader, e)?;

    // Validate only allowed attributes are present
    // Per 3MF Core spec: name, displaycolor
    validate_attributes(&attrs, &["name", "displaycolor"], "base")?;

    // Use the provided index as the material ID
    let mut material = Material::new(index);
    material.name = attrs.get("name").cloned();

    // Parse displaycolor attribute (format: #RRGGBBAA or #RRGGBB)
    if let Some(color_str) = attrs.get("displaycolor")
        && let Some(color) = parse_color(color_str)
    {
        material.color = Some(color);
    }

    Ok(material)
}

/// Parse texture2d element
pub(super) fn parse_texture2d<R: std::io::BufRead>(
    reader: &Reader<R>,
    e: &quick_xml::events::BytesStart,
    resource_parse_order: usize,
) -> Result<Texture2D> {
    let attrs = parse_attributes(reader, e)?;
    let id = attrs
        .get("id")
        .ok_or_else(|| Error::missing_attribute("texture2d", "id"))?
        .parse::<usize>()?;
    let path = attrs
        .get("path")
        .ok_or_else(|| Error::missing_attribute("texture2d", "path"))?
        .to_string();
    let contenttype = attrs
        .get("contenttype")
        .ok_or_else(|| Error::InvalidXml("texture2d missing contenttype attribute".to_string()))?
        .to_string();

    let mut texture = Texture2D::new(id, path, contenttype);
    texture.parse_order = resource_parse_order;

    // Parse optional attributes with spec defaults
    if let Some(tileu_str) = attrs.get("tilestyleu") {
        texture.tilestyleu = match tileu_str.to_lowercase().as_str() {
            "wrap" => TileStyle::Wrap,
            "mirror" => TileStyle::Mirror,
            "clamp" => TileStyle::Clamp,
            "none" => TileStyle::None,
            _ => TileStyle::Wrap,
        };
    }

    if let Some(tilev_str) = attrs.get("tilestylev") {
        texture.tilestylev = match tilev_str.to_lowercase().as_str() {
            "wrap" => TileStyle::Wrap,
            "mirror" => TileStyle::Mirror,
            "clamp" => TileStyle::Clamp,
            "none" => TileStyle::None,
            _ => TileStyle::Wrap,
        };
    }

    if let Some(filter_str) = attrs.get("filter") {
        texture.filter = match filter_str.to_lowercase().as_str() {
            "auto" => FilterMode::Auto,
            "linear" => FilterMode::Linear,
            "nearest" => FilterMode::Nearest,
            _ => FilterMode::Auto,
        };
    }

    Ok(texture)
}

/// Validate texture file paths exist in the 3MF package
pub(super) fn validate_texture_file_paths<R: Read + std::io::Seek>(
    package: &mut Package<R>,
    model: &Model,
) -> Result<()> {
    // Get list of encrypted files to skip validation for them
    let encrypted_files: Vec<String> = model
        .secure_content
        .as_ref()
        .map(|sc| sc.encrypted_files.clone())
        .unwrap_or_default();

    for texture in &model.resources.texture2d_resources {
        // Skip validation for encrypted files (they may not follow standard paths)
        if encrypted_files.contains(&texture.path) {
            continue;
        }

        // Normalize path: remove leading slash if present for lookup
        // The path in the model may start with "/" but the ZIP file paths typically don't
        let normalized_path = texture.path.trim_start_matches('/');

        // Check if file exists in the package
        // Try both with and without leading slash as different 3MF implementations vary
        let file_exists = package.has_file(normalized_path) || package.has_file(&texture.path);

        if !file_exists {
            return Err(Error::InvalidModel(format!(
                "Texture2D resource {}: Path '{}' references a file that does not exist in the 3MF package.\n\
                 Per 3MF Material Extension spec, texture paths must reference valid files in the package.\n\
                 Check that:\n\
                 - The texture file is included in the 3MF package\n\
                 - The path is correct (case-sensitive)\n\
                 - The path format follows 3MF conventions\n\
                 Available files can be checked using ZIP archive tools.",
                texture.id, texture.path
            )));
        }
    }

    Ok(())
}

/// Parse basematerials group start and return initialized group
pub(super) fn parse_basematerials_start<R: std::io::BufRead>(
    reader: &Reader<R>,
    e: &quick_xml::events::BytesStart,
    resource_parse_order: usize,
) -> Result<BaseMaterialGroup> {
    let attrs = parse_attributes(reader, e)?;
    let id = attrs
        .get("id")
        .ok_or_else(|| Error::missing_attribute("basematerials", "id"))?
        .parse::<usize>()?;
    let mut group = BaseMaterialGroup::new(id);
    group.parse_order = resource_parse_order;
    Ok(group)
}

/// Parse base material element and add to group
pub(super) fn parse_base_element<R: std::io::BufRead>(
    reader: &Reader<R>,
    e: &quick_xml::events::BytesStart,
) -> Result<BaseMaterial> {
    let attrs = parse_attributes(reader, e)?;

    // Validate only allowed attributes are present
    // Per 3MF Materials & Properties Extension spec: name, displaycolor
    validate_attributes(&attrs, &["name", "displaycolor"], "base")?;

    let name = attrs.get("name").cloned().unwrap_or_default();

    // Parse displaycolor attribute (format: #RRGGBBAA or #RRGGBB)
    // If displaycolor is missing or invalid, use white as default
    let displaycolor = if let Some(color_str) = attrs.get("displaycolor") {
        parse_color(color_str).unwrap_or((255, 255, 255, 255))
    } else {
        (255, 255, 255, 255)
    };

    Ok(BaseMaterial::new(name, displaycolor))
}

/// Parse colorgroup start and return initialized group
pub(super) fn parse_colorgroup_start<R: std::io::BufRead>(
    reader: &Reader<R>,
    e: &quick_xml::events::BytesStart,
    resource_parse_order: usize,
) -> Result<ColorGroup> {
    let attrs = parse_attributes(reader, e)?;
    let id = attrs
        .get("id")
        .ok_or_else(|| Error::missing_attribute("colorgroup", "id"))?
        .parse::<usize>()?;
    let mut group = ColorGroup::new(id);
    group.parse_order = resource_parse_order;
    Ok(group)
}

/// Parse color element
pub(super) fn parse_color_element<R: std::io::BufRead>(
    reader: &Reader<R>,
    e: &quick_xml::events::BytesStart,
    colorgroup_id: usize,
) -> Result<(u8, u8, u8, u8)> {
    let attrs = parse_attributes(reader, e)?;
    let color_str = attrs
        .get("color")
        .ok_or_else(|| Error::missing_attribute("color", "color"))?;

    parse_color(color_str).ok_or_else(|| {
        Error::InvalidXml(format!(
            "Invalid color format '{}' in colorgroup {}.\n\
             Colors must be in format #RRGGBB or #RRGGBBAA where each component is a hexadecimal value (0-9, A-F).\n\
             Examples: #FF0000 (red), #00FF0080 (semi-transparent green)",
            color_str, colorgroup_id
        ))
    })
}

/// Parse texture2dgroup start and return initialized group
pub(super) fn parse_texture2dgroup_start<R: std::io::BufRead>(
    reader: &Reader<R>,
    e: &quick_xml::events::BytesStart,
    resource_parse_order: usize,
) -> Result<Texture2DGroup> {
    let attrs = parse_attributes(reader, e)?;
    let id = attrs
        .get("id")
        .ok_or_else(|| Error::missing_attribute("texture2dgroup", "id"))?
        .parse::<usize>()?;
    let texid = attrs
        .get("texid")
        .ok_or_else(|| Error::missing_attribute("texture2dgroup", "texid"))?
        .parse::<usize>()?;
    let mut group = Texture2DGroup::new(id, texid);
    group.parse_order = resource_parse_order;
    Ok(group)
}

/// Parse tex2coord element
pub(super) fn parse_tex2coord<R: std::io::BufRead>(
    reader: &Reader<R>,
    e: &quick_xml::events::BytesStart,
) -> Result<Tex2Coord> {
    let attrs = parse_attributes(reader, e)?;
    let u = attrs
        .get("u")
        .ok_or_else(|| Error::missing_attribute("tex2coord", "u"))?
        .parse::<f32>()?;
    let v = attrs
        .get("v")
        .ok_or_else(|| Error::missing_attribute("tex2coord", "v"))?
        .parse::<f32>()?;
    Ok(Tex2Coord::new(u, v))
}

/// Parse compositematerials start and return initialized group
pub(super) fn parse_compositematerials_start<R: std::io::BufRead>(
    reader: &Reader<R>,
    e: &quick_xml::events::BytesStart,
    resource_parse_order: usize,
) -> Result<CompositeMaterials> {
    let attrs = parse_attributes(reader, e)?;
    let id = attrs
        .get("id")
        .ok_or_else(|| Error::InvalidXml("compositematerials missing id attribute".to_string()))?
        .parse::<usize>()?;
    let matid = attrs
        .get("matid")
        .ok_or_else(|| Error::InvalidXml("compositematerials missing matid attribute".to_string()))?
        .parse::<usize>()?;
    let matindices_str = attrs.get("matindices").ok_or_else(|| {
        Error::InvalidXml("compositematerials missing matindices attribute".to_string())
    })?;
    let matindices: Vec<usize> = matindices_str
        .split_whitespace()
        .map(|s| {
            s.parse::<usize>().map_err(|_| {
                Error::InvalidXml(format!(
                    "compositematerials matindices contains invalid value '{}'",
                    s
                ))
            })
        })
        .collect::<Result<Vec<usize>>>()?;

    // Validate we parsed at least one index
    if matindices.is_empty() {
        return Err(Error::InvalidXml(
            "compositematerials matindices must contain at least one valid index".to_string(),
        ));
    }

    let mut group = CompositeMaterials::new(id, matid, matindices);
    group.parse_order = resource_parse_order;
    Ok(group)
}

/// Parse composite element
pub(super) fn parse_composite<R: std::io::BufRead>(
    reader: &Reader<R>,
    e: &quick_xml::events::BytesStart,
) -> Result<Composite> {
    let attrs = parse_attributes(reader, e)?;
    let values_str = attrs
        .get("values")
        .ok_or_else(|| Error::InvalidXml("composite missing values attribute".to_string()))?;
    let values: Vec<f32> = values_str
        .split_whitespace()
        .map(|s| {
            s.parse::<f32>().map_err(|_| {
                Error::InvalidXml(format!("composite values contains invalid number '{}'", s))
            })
        })
        .collect::<Result<Vec<f32>>>()?;

    // Validate we parsed at least one value
    if values.is_empty() {
        return Err(Error::InvalidXml(
            "composite values must contain at least one valid number".to_string(),
        ));
    }

    Ok(Composite::new(values))
}

/// Parse multiproperties start and return initialized group
pub(super) fn parse_multiproperties_start<R: std::io::BufRead>(
    reader: &Reader<R>,
    e: &quick_xml::events::BytesStart,
    resource_parse_order: usize,
) -> Result<MultiProperties> {
    let attrs = parse_attributes(reader, e)?;
    let id = attrs
        .get("id")
        .ok_or_else(|| Error::InvalidXml("multiproperties missing id attribute".to_string()))?
        .parse::<usize>()?;
    let pids_str = attrs
        .get("pids")
        .ok_or_else(|| Error::InvalidXml("multiproperties missing pids attribute".to_string()))?;
    let pids: Vec<usize> = pids_str
        .split_whitespace()
        .map(|s| {
            s.parse::<usize>().map_err(|_| {
                Error::InvalidXml(format!(
                    "multiproperties pids contains invalid value '{}'",
                    s
                ))
            })
        })
        .collect::<Result<Vec<usize>>>()?;

    // Validate we parsed at least one property ID
    if pids.is_empty() {
        return Err(Error::InvalidXml(
            "multiproperties pids must contain at least one valid ID".to_string(),
        ));
    }

    let mut multi = MultiProperties::new(id, pids);
    multi.parse_order = resource_parse_order;

    // Parse optional blendmethods
    if let Some(blend_str) = attrs.get("blendmethods") {
        multi.blendmethods = blend_str
            .split_whitespace()
            .filter_map(|s| match s.to_lowercase().as_str() {
                "mix" => Some(BlendMethod::Mix),
                "multiply" => Some(BlendMethod::Multiply),
                _ => None,
            })
            .collect();
    }

    Ok(multi)
}

/// Parse multi element
pub(super) fn parse_multi<R: std::io::BufRead>(
    reader: &Reader<R>,
    e: &quick_xml::events::BytesStart,
) -> Result<Multi> {
    let attrs = parse_attributes(reader, e)?;
    let pindices_str = attrs
        .get("pindices")
        .ok_or_else(|| Error::InvalidXml("multi missing pindices attribute".to_string()))?;
    let pindices: Vec<usize> = if pindices_str.trim().is_empty() {
        Vec::new()
    } else {
        pindices_str
            .split_whitespace()
            .map(|s| {
                s.parse::<usize>().map_err(|_| {
                    Error::InvalidXml(format!("multi pindices contains invalid value '{}'", s))
                })
            })
            .collect::<Result<Vec<usize>>>()?
    };

    Ok(Multi::new(pindices))
}

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

    #[test]
    fn test_parse_color() {
        // Test #RRGGBB format
        assert_eq!(parse_color("#FF0000"), Some((255, 0, 0, 255)));
        assert_eq!(parse_color("#00FF00"), Some((0, 255, 0, 255)));
        assert_eq!(parse_color("#0000FF"), Some((0, 0, 255, 255)));

        // Test #RRGGBBAA format
        assert_eq!(parse_color("#FF000080"), Some((255, 0, 0, 128)));
        assert_eq!(parse_color("#00FF00FF"), Some((0, 255, 0, 255)));

        // Test invalid formats
        assert_eq!(parse_color("#FF"), None);
        assert_eq!(parse_color("FF0000"), Some((255, 0, 0, 255)));
    }

    #[test]
    fn test_parse_color_black_white() {
        assert_eq!(parse_color("#000000"), Some((0, 0, 0, 255)));
        assert_eq!(parse_color("#FFFFFF"), Some((255, 255, 255, 255)));
    }

    #[test]
    fn test_parse_color_zero_alpha() {
        assert_eq!(parse_color("#FF000000"), Some((255, 0, 0, 0)));
    }

    #[test]
    fn test_parse_base_materials_via_xml() {
        let xml = r##"<?xml version="1.0" encoding="UTF-8"?>
<model unit="millimeter" xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02">
  <resources>
    <basematerials id="1">
      <base name="Red" displaycolor="#FF0000"/>
      <base name="Green" displaycolor="#00FF00"/>
      <base name="Transparent" displaycolor="#FFFFFF00"/>
    </basematerials>
    <object id="2" pid="1" pindex="0">
      <mesh>
        <vertices>
          <vertex x="0" y="0" z="0"/>
          <vertex x="1" y="0" z="0"/>
          <vertex x="0" y="1" z="0"/>
        </vertices>
        <triangles>
          <triangle v1="0" v2="1" v3="2"/>
        </triangles>
      </mesh>
    </object>
  </resources>
  <build>
    <item objectid="2"/>
  </build>
</model>"##;
        let model = parse_model_xml(xml).unwrap();
        let group = &model.resources.base_material_groups[0];
        assert_eq!(group.materials.len(), 3);
        assert_eq!(group.materials[0].displaycolor, (255, 0, 0, 255));
        assert_eq!(group.materials[1].displaycolor, (0, 255, 0, 255));
        // Transparent - alpha = 0
        assert_eq!(group.materials[2].displaycolor.3, 0);
    }

    #[test]
    fn test_parse_texture2d_via_xml() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<model unit="millimeter" xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02"
  xmlns:m="http://schemas.microsoft.com/3dmanufacturing/material/2015/02">
  <resources>
    <texture2d id="1" path="/3D/Textures/tex.png" contenttype="image/png"
      tilestyleu="wrap" tilestylev="mirror" filter="linear"/>
    <object id="2">
      <mesh>
        <vertices>
          <vertex x="0" y="0" z="0"/>
          <vertex x="1" y="0" z="0"/>
          <vertex x="0" y="1" z="0"/>
        </vertices>
        <triangles>
          <triangle v1="0" v2="1" v3="2"/>
        </triangles>
      </mesh>
    </object>
  </resources>
  <build>
    <item objectid="2"/>
  </build>
</model>"#;
        let model = parse_model_xml(xml).unwrap();
        assert_eq!(model.resources.texture2d_resources.len(), 1);
        let tex = &model.resources.texture2d_resources[0];
        assert_eq!(tex.id, 1);
        assert_eq!(tex.path, "/3D/Textures/tex.png");
        assert_eq!(tex.contenttype, "image/png");
    }

    #[test]
    fn test_parse_texture2d_missing_id_rejected() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<model unit="millimeter" xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02">
  <resources>
    <texture2d path="/3D/Textures/tex.png" contenttype="image/png"/>
    <object id="1">
      <mesh>
        <vertices>
          <vertex x="0" y="0" z="0"/>
          <vertex x="1" y="0" z="0"/>
          <vertex x="0" y="1" z="0"/>
        </vertices>
        <triangles>
          <triangle v1="0" v2="1" v3="2"/>
        </triangles>
      </mesh>
    </object>
  </resources>
  <build>
    <item objectid="1"/>
  </build>
</model>"#;
        let result = parse_model_xml(xml);
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_texture2dgroup_with_tex2coords() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<model unit="millimeter" xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02"
  xmlns:m="http://schemas.microsoft.com/3dmanufacturing/material/2015/02">
  <resources>
    <texture2d id="1" path="/3D/Textures/tex.png" contenttype="image/png"/>
    <texture2dgroup id="2" texid="1">
      <tex2coord u="0.0" v="0.0"/>
      <tex2coord u="1.0" v="0.0"/>
      <tex2coord u="0.5" v="1.0"/>
    </texture2dgroup>
    <object id="3" pid="2" pindex="0">
      <mesh>
        <vertices>
          <vertex x="0" y="0" z="0"/>
          <vertex x="1" y="0" z="0"/>
          <vertex x="0" y="1" z="0"/>
        </vertices>
        <triangles>
          <triangle v1="0" v2="1" v3="2" p1="0" p2="1" p3="2"/>
        </triangles>
      </mesh>
    </object>
  </resources>
  <build>
    <item objectid="3"/>
  </build>
</model>"#;
        let model = parse_model_xml(xml).unwrap();
        assert_eq!(model.resources.texture2d_groups.len(), 1);
        let group = &model.resources.texture2d_groups[0];
        assert_eq!(group.tex2coords.len(), 3);
        assert_eq!(group.tex2coords[0].u, 0.0);
        assert_eq!(group.tex2coords[1].u, 1.0);
    }

    #[test]
    fn test_parse_compositematerials_via_xml() {
        let xml = r##"<?xml version="1.0" encoding="UTF-8"?>
<model unit="millimeter" xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02"
  xmlns:m="http://schemas.microsoft.com/3dmanufacturing/material/2015/02">
  <resources>
    <basematerials id="1">
      <base name="Red" displaycolor="#FF0000"/>
      <base name="Blue" displaycolor="#0000FF"/>
    </basematerials>
    <compositematerials id="2" matid="1" matindices="0 1">
      <composite values="0.5 0.5"/>
      <composite values="0.8 0.2"/>
    </compositematerials>
    <object id="3" pid="2" pindex="0">
      <mesh>
        <vertices>
          <vertex x="0" y="0" z="0"/>
          <vertex x="1" y="0" z="0"/>
          <vertex x="0" y="1" z="0"/>
        </vertices>
        <triangles>
          <triangle v1="0" v2="1" v3="2"/>
        </triangles>
      </mesh>
    </object>
  </resources>
  <build>
    <item objectid="3"/>
  </build>
</model>"##;
        let model = parse_model_xml(xml).unwrap();
        assert_eq!(model.resources.composite_materials.len(), 1);
        assert_eq!(model.resources.composite_materials[0].composites.len(), 2);
    }

    #[test]
    fn test_parse_multiproperties_via_xml() {
        let xml = r##"<?xml version="1.0" encoding="UTF-8"?>
<model unit="millimeter" xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02"
  xmlns:m="http://schemas.microsoft.com/3dmanufacturing/material/2015/02">
  <resources>
    <basematerials id="1">
      <base name="Red" displaycolor="#FF0000"/>
      <base name="Blue" displaycolor="#0000FF"/>
    </basematerials>
    <colorgroup id="2">
      <color color="#FF0000"/>
      <color color="#00FF00"/>
    </colorgroup>
    <multiproperties id="3" pids="1 2" blendmethods="mix">
      <multi pindices="0 0"/>
      <multi pindices="1 1"/>
    </multiproperties>
    <object id="4" pid="3" pindex="0">
      <mesh>
        <vertices>
          <vertex x="0" y="0" z="0"/>
          <vertex x="1" y="0" z="0"/>
          <vertex x="0" y="1" z="0"/>
        </vertices>
        <triangles>
          <triangle v1="0" v2="1" v3="2"/>
        </triangles>
      </mesh>
    </object>
  </resources>
  <build>
    <item objectid="4"/>
  </build>
</model>"##;
        let model = parse_model_xml(xml).unwrap();
        assert_eq!(model.resources.multi_properties.len(), 1);
        assert_eq!(model.resources.multi_properties[0].multis.len(), 2);
    }

    #[test]
    fn test_parse_tilestyles() {
        // Test all tilestyle values
        for (u_style, v_style) in &[
            ("wrap", "wrap"),
            ("mirror", "clamp"),
            ("clamp", "none"),
            ("none", "mirror"),
        ] {
            let xml = format!(
                r#"<?xml version="1.0" encoding="UTF-8"?>
<model unit="millimeter" xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02">
  <resources>
    <texture2d id="1" path="/3D/t.png" contenttype="image/png"
      tilestyleu="{u}" tilestylev="{v}"/>
    <object id="2">
      <mesh>
        <vertices>
          <vertex x="0" y="0" z="0"/>
          <vertex x="1" y="0" z="0"/>
          <vertex x="0" y="1" z="0"/>
        </vertices>
        <triangles>
          <triangle v1="0" v2="1" v3="2"/>
        </triangles>
      </mesh>
    </object>
  </resources>
  <build><item objectid="2"/></build>
</model>"#,
                u = u_style,
                v = v_style
            );
            assert!(
                parse_model_xml(&xml).is_ok(),
                "Failed for tilestyleu={}, tilestylev={}",
                u_style,
                v_style
            );
        }
    }
}