oxideav-obj 0.0.3

Pure-Rust Wavefront OBJ + MTL 3D mesh codec — implements oxideav-mesh3d's Decoder/Encoder traits
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
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
//! Wavefront MTL (material library) ASCII parser + serialiser.
//!
//! The grammar mirrors OBJ's: line-oriented, whitespace-separated,
//! `#` introduces a comment to end of line. Each `newmtl <name>`
//! opens a fresh material; subsequent lines populate the material's
//! parameters until the next `newmtl` or end of file.
//!
//! This crate maps the Phong-Blinn vocabulary onto the glTF
//! metallic-roughness model in [`Material`], preserving the original
//! field values in [`Material::extras`] so a re-serialise reproduces
//! the input. The Wavefront-PBR extension (`Pr`, `Pm`, `Pc`, `Ps`,
//! `map_Pr`, `map_Pm`) lands directly in the corresponding PBR slots.

use oxideav_mesh3d::{AlphaMode, Error, ImageData, Material, Result, Sampler, Texture, TextureRef};

// ---------------------------------------------------------------------------
// Parsing
// ---------------------------------------------------------------------------

/// Pending texture references from the parser. We can't allocate a
/// `TextureRef` at parse time because that needs a `TextureId` (only
/// known once textures land in the [`Scene3D`](oxideav_mesh3d::Scene3D)).
/// The OBJ→Scene3D path bridges this in
/// [`merge_materials_into_scene`].
#[derive(Debug, Default, Clone)]
struct PendingTextures {
    base_color: Option<String>,
    normal: Option<String>,
    metallic_roughness: Option<String>,
    emissive: Option<String>,
}

/// Parsed material plus its yet-to-be-resolved texture URIs.
#[derive(Debug, Clone)]
struct ParsedMaterial {
    material: Material,
    pending: PendingTextures,
}

/// Parse an MTL document.
///
/// Returns one [`Material`] per `newmtl` block. Texture references
/// are resolved lazily by [`merge_materials_into_scene`] (used by the
/// OBJ decoder) — direct callers get materials with `*_texture` slots
/// wired to fresh textures stored in the same returned vector via
/// the `extras["mtl:pending_textures"]` side-channel; consumers
/// integrating with a real `Scene3D` should use [`parse_mtl_with_scene`]
/// instead.
pub fn parse_mtl(text: &str) -> Result<Vec<Material>> {
    let parsed = parse_mtl_internal(text)?;
    let mut out: Vec<Material> = Vec::with_capacity(parsed.len());
    for pm in parsed {
        let mut mat = pm.material;
        // Stash pending texture URIs in extras so a downstream pass
        // can hoist them into a Scene3D's texture pool. Direct callers
        // who want the URIs without a Scene3D can pull them from here.
        let mut pending_obj = serde_json::Map::new();
        if let Some(p) = pm.pending.base_color {
            pending_obj.insert("base_color".into(), serde_json::Value::String(p));
        }
        if let Some(p) = pm.pending.normal {
            pending_obj.insert("normal".into(), serde_json::Value::String(p));
        }
        if let Some(p) = pm.pending.metallic_roughness {
            pending_obj.insert("metallic_roughness".into(), serde_json::Value::String(p));
        }
        if let Some(p) = pm.pending.emissive {
            pending_obj.insert("emissive".into(), serde_json::Value::String(p));
        }
        if !pending_obj.is_empty() {
            mat.extras.insert(
                "mtl:pending_textures".to_string(),
                serde_json::Value::Object(pending_obj),
            );
        }
        out.push(mat);
    }
    Ok(out)
}

/// Hoist pending texture URIs into the supplied scene as
/// [`Texture`]s and bind the result on each material via
/// [`TextureRef`]. Materials are also added to the scene; returns the
/// `MaterialId` for each input material in declaration order.
///
/// Provided as a convenience for `obj.rs` and direct MTL-decoder
/// callers; symmetrical with the OBJ→Scene3D pipeline so reload of an
/// MTL standalone produces the same in-scene structure as a full OBJ
/// decode would.
pub fn merge_materials_into_scene(
    scene: &mut oxideav_mesh3d::Scene3D,
    materials: Vec<Material>,
) -> Vec<oxideav_mesh3d::MaterialId> {
    let mut ids = Vec::with_capacity(materials.len());
    for mut mat in materials {
        // Resolve any `mtl:pending_textures` field into real Textures.
        let pending = mat.extras.remove("mtl:pending_textures");
        if let Some(serde_json::Value::Object(obj)) = pending {
            for (slot, val) in obj {
                let serde_json::Value::String(uri) = val else {
                    continue;
                };
                let tex = Texture {
                    name: Some(uri.clone()),
                    image: ImageData::External {
                        uri: uri.clone(),
                        mime: None,
                    },
                    sampler: Sampler::default_sampler(),
                };
                let tex_id = scene.add_texture(tex);
                let tex_ref = TextureRef::new(tex_id);
                match slot.as_str() {
                    "base_color" => mat.base_color_texture = Some(tex_ref),
                    "normal" => mat.normal_texture = Some(tex_ref),
                    "metallic_roughness" => mat.metallic_roughness_texture = Some(tex_ref),
                    "emissive" => mat.emissive_texture = Some(tex_ref),
                    _ => {}
                }
            }
        }
        ids.push(scene.add_material(mat));
    }
    ids
}

/// One-shot parse + scene-hoist for direct MTL-decoder callers.
pub fn parse_mtl_with_scene(text: &str) -> Result<oxideav_mesh3d::Scene3D> {
    let mut scene = oxideav_mesh3d::Scene3D::new();
    let materials = parse_mtl(text)?;
    let _ = merge_materials_into_scene(&mut scene, materials);
    Ok(scene)
}

fn parse_mtl_internal(text: &str) -> Result<Vec<ParsedMaterial>> {
    let mut out: Vec<ParsedMaterial> = Vec::new();
    let mut current: Option<ParsedMaterial> = None;

    fn strip_comment(line: &str) -> &str {
        match line.find('#') {
            Some(idx) => &line[..idx],
            None => line,
        }
    }

    for raw_line in text.split('\n') {
        let line = raw_line.strip_suffix('\r').unwrap_or(raw_line);
        let line = strip_comment(line).trim();
        if line.is_empty() {
            continue;
        }
        let mut tokens = line.split_whitespace();
        let Some(keyword) = tokens.next() else {
            continue;
        };

        match keyword {
            "newmtl" => {
                if let Some(prev) = current.take() {
                    out.push(prev);
                }
                let name: String = tokens.collect::<Vec<_>>().join(" ");
                let mut mat = Material::new();
                // Spec primer says fallback to metallic=0/roughness=0.5 when
                // PBR fields aren't present.
                mat.metallic = 0.0;
                mat.roughness = 0.5;
                mat.name = Some(name);
                current = Some(ParsedMaterial {
                    material: mat,
                    pending: PendingTextures::default(),
                });
            }
            other => {
                let Some(pm) = current.as_mut() else {
                    return Err(Error::invalid(format!(
                        "MTL: {other:?} appears before any newmtl directive"
                    )));
                };
                apply_directive(other, &mut tokens, pm)?;
            }
        }
    }

    if let Some(last) = current.take() {
        out.push(last);
    }
    Ok(out)
}

fn parse_floats<'a, I: Iterator<Item = &'a str>>(tokens: I, keyword: &str) -> Result<Vec<f32>> {
    tokens
        .map(str::parse::<f32>)
        .collect::<std::result::Result<Vec<_>, _>>()
        .map_err(|e| Error::invalid(format!("MTL {keyword}: bad float ({e})")))
}

fn apply_directive(
    keyword: &str,
    tokens: &mut std::str::SplitWhitespace<'_>,
    pm: &mut ParsedMaterial,
) -> Result<()> {
    let mat = &mut pm.material;
    match keyword {
        "Ka" => {
            let v = parse_floats(tokens.by_ref(), keyword)?;
            if v.len() < 3 {
                return Err(Error::invalid(format!(
                    "Ka: needs 3 floats, got {}",
                    v.len()
                )));
            }
            mat.extras
                .insert("mtl:Ka".to_string(), serde_json::json!([v[0], v[1], v[2]]));
        }
        "Kd" => {
            let v = parse_floats(tokens.by_ref(), keyword)?;
            if v.len() < 3 {
                return Err(Error::invalid(format!(
                    "Kd: needs 3 floats, got {}",
                    v.len()
                )));
            }
            // Preserve the alpha channel that may have been set by an
            // earlier `d` line so the assignment ordering matches the
            // file (`d` typically follows `Kd`, but defensive).
            let alpha = mat.base_color[3];
            mat.base_color = [v[0], v[1], v[2], alpha];
        }
        "Ks" => {
            let v = parse_floats(tokens.by_ref(), keyword)?;
            if v.len() < 3 {
                return Err(Error::invalid(format!(
                    "Ks: needs 3 floats, got {}",
                    v.len()
                )));
            }
            mat.extras
                .insert("mtl:Ks".to_string(), serde_json::json!([v[0], v[1], v[2]]));
        }
        "Ke" => {
            let v = parse_floats(tokens.by_ref(), keyword)?;
            if v.len() < 3 {
                return Err(Error::invalid(format!(
                    "Ke: needs 3 floats, got {}",
                    v.len()
                )));
            }
            mat.emissive_factor = [v[0], v[1], v[2]];
        }
        "Tf" => {
            // Transmission filter. Spec §"Tf r g b" lists three mutually
            // exclusive forms:
            //
            //   Tf r g b               — RGB triple (g/b default to r)
            //   Tf spectral file.rfl factor    — spectral .rfl curve
            //   Tf xyz x y z           — CIEXYZ tristimulus (y/z default to x)
            //
            // The RGB form lands in `extras["mtl:Tf"]` as an
            // `[r,g,b]` array (the round-1 behaviour); the alt forms
            // land under sibling keys so a re-emit reproduces the
            // operator's chosen spelling. PBR transmission is its
            // own KHR extension on the glTF side, so we don't model
            // any of the variants as a first-class `Material` field.
            //
            // The first token discriminates: `spectral` / `xyz` /
            // anything-else (treated as a numeric `r`).
            let toks: Vec<&str> = tokens.collect();
            if toks.is_empty() {
                return Err(Error::invalid("Tf: needs at least 1 argument"));
            }
            match toks[0] {
                "spectral" => {
                    if toks.len() < 2 {
                        return Err(Error::invalid("Tf spectral: missing file.rfl"));
                    }
                    let file = toks[1].to_string();
                    let factor: f32 = if let Some(f) = toks.get(2) {
                        f.parse()
                            .map_err(|e| Error::invalid(format!("Tf spectral: bad factor ({e})")))?
                    } else {
                        1.0
                    };
                    mat.extras.insert(
                        "mtl:Tf:spectral".to_string(),
                        serde_json::json!({ "file": file, "factor": factor }),
                    );
                }
                "xyz" => {
                    let v: Vec<f32> = toks[1..]
                        .iter()
                        .map(|s| s.parse::<f32>())
                        .collect::<std::result::Result<Vec<_>, _>>()
                        .map_err(|e| Error::invalid(format!("Tf xyz: bad float ({e})")))?;
                    if v.is_empty() {
                        return Err(Error::invalid("Tf xyz: needs at least 1 float"));
                    }
                    let x = v[0];
                    let y = v.get(1).copied().unwrap_or(x);
                    let z = v.get(2).copied().unwrap_or(x);
                    mat.extras
                        .insert("mtl:Tf:xyz".to_string(), serde_json::json!([x, y, z]));
                }
                _ => {
                    // Plain RGB form. Per MTL spec §"Tf r g b", g and
                    // b default to r when omitted; we eagerly
                    // normalise to a 3-tuple so the round-trip emits
                    // a canonical line.
                    let v: Vec<f32> = toks
                        .iter()
                        .map(|s| s.parse::<f32>())
                        .collect::<std::result::Result<Vec<_>, _>>()
                        .map_err(|e| Error::invalid(format!("Tf: bad float ({e})")))?;
                    let r = v[0];
                    let g = v.get(1).copied().unwrap_or(r);
                    let b = v.get(2).copied().unwrap_or(r);
                    mat.extras
                        .insert("mtl:Tf".to_string(), serde_json::json!([r, g, b]));
                }
            }
        }
        "sharpness" => {
            // Reflection-map sharpness; spec range 0..1000, default 60.
            let v: f32 = tokens
                .next()
                .ok_or_else(|| Error::invalid("sharpness: missing value"))?
                .parse()
                .map_err(|e| Error::invalid(format!("sharpness: bad float ({e})")))?;
            mat.extras
                .insert("mtl:sharpness".to_string(), serde_json::json!(v));
        }
        "Ns" => {
            let v: f32 = tokens
                .next()
                .ok_or_else(|| Error::invalid("Ns: missing value"))?
                .parse()
                .map_err(|e| Error::invalid(format!("Ns: bad float ({e})")))?;
            mat.extras
                .insert("mtl:Ns".to_string(), serde_json::json!(v));
        }
        "Ni" => {
            let v: f32 = tokens
                .next()
                .ok_or_else(|| Error::invalid("Ni: missing value"))?
                .parse()
                .map_err(|e| Error::invalid(format!("Ni: bad float ({e})")))?;
            mat.extras
                .insert("mtl:Ni".to_string(), serde_json::json!(v));
        }
        "d" => {
            // The first non-flag token is the dissolve value. The
            // optional `-halo` flag (per spec §"d -halo factor")
            // makes the dissolve orientation-dependent — surface it
            // via extras so the round-trip emits the same form.
            let mut halo = false;
            let mut value: Option<f32> = None;
            for tok in tokens.by_ref() {
                if tok == "-halo" {
                    halo = true;
                    continue;
                }
                value = Some(
                    tok.parse()
                        .map_err(|e| Error::invalid(format!("d: bad float ({e})")))?,
                );
                break;
            }
            let v = value.ok_or_else(|| Error::invalid("d: missing value"))?;
            mat.base_color[3] = v;
            if v < 1.0 {
                mat.alpha_mode = AlphaMode::Blend;
            }
            if halo {
                mat.extras
                    .insert("mtl:d_halo_factor".to_string(), serde_json::json!(v));
            }
        }
        "Tr" => {
            // Tr = 1 - d (Wavefront alternate dissolve form).
            let v: f32 = tokens
                .next()
                .ok_or_else(|| Error::invalid("Tr: missing value"))?
                .parse()
                .map_err(|e| Error::invalid(format!("Tr: bad float ({e})")))?;
            let d = 1.0 - v;
            mat.base_color[3] = d;
            if d < 1.0 {
                mat.alpha_mode = AlphaMode::Blend;
            }
        }
        "illum" => {
            let v: i32 = tokens
                .next()
                .ok_or_else(|| Error::invalid("illum: missing value"))?
                .parse()
                .map_err(|e| Error::invalid(format!("illum: bad integer ({e})")))?;
            mat.extras
                .insert("mtl:illum".to_string(), serde_json::json!(v));
        }
        "Pr" => {
            let v: f32 = tokens
                .next()
                .ok_or_else(|| Error::invalid("Pr: missing value"))?
                .parse()
                .map_err(|e| Error::invalid(format!("Pr: bad float ({e})")))?;
            mat.roughness = v;
        }
        "Pm" => {
            let v: f32 = tokens
                .next()
                .ok_or_else(|| Error::invalid("Pm: missing value"))?
                .parse()
                .map_err(|e| Error::invalid(format!("Pm: bad float ({e})")))?;
            mat.metallic = v;
        }
        "Pc" => {
            let v: f32 = tokens
                .next()
                .ok_or_else(|| Error::invalid("Pc: missing value"))?
                .parse()
                .map_err(|e| Error::invalid(format!("Pc: bad float ({e})")))?;
            mat.extras
                .insert("mtl:Pc".to_string(), serde_json::json!(v));
        }
        "Pcr" => {
            let v: f32 = tokens
                .next()
                .ok_or_else(|| Error::invalid("Pcr: missing value"))?
                .parse()
                .map_err(|e| Error::invalid(format!("Pcr: bad float ({e})")))?;
            mat.extras
                .insert("mtl:Pcr".to_string(), serde_json::json!(v));
        }
        "Ps" => {
            let v: f32 = tokens
                .next()
                .ok_or_else(|| Error::invalid("Ps: missing value"))?
                .parse()
                .map_err(|e| Error::invalid(format!("Ps: bad float ({e})")))?;
            mat.extras
                .insert("mtl:Ps".to_string(), serde_json::json!(v));
        }
        "aniso" | "anisor" => {
            let v: f32 = tokens
                .next()
                .ok_or_else(|| Error::invalid(format!("{keyword}: missing value")))?
                .parse()
                .map_err(|e| Error::invalid(format!("{keyword}: bad float ({e})")))?;
            mat.extras
                .insert(format!("mtl:{keyword}"), serde_json::json!(v));
        }
        "map_Kd" => {
            pm.pending.base_color = Some(parse_map_with_options(keyword, tokens, &mut mat.extras));
        }
        "map_Bump" | "map_bump" | "bump" | "norm" => {
            pm.pending.normal = Some(parse_map_with_options(keyword, tokens, &mut mat.extras));
        }
        "map_Ke" => {
            pm.pending.emissive = Some(parse_map_with_options(keyword, tokens, &mut mat.extras));
        }
        "map_Pr" | "map_Pm" => {
            // Either of the two PBR maps lands in metallic_roughness — the
            // glTF channel-packing convention is B = metallic, G = roughness.
            // We can't fuse two file references into one packed texture
            // without decoding pixels, so the last-seen wins; the other
            // is stashed in extras for round-trip.
            let s = parse_map_with_options(keyword, tokens, &mut mat.extras);
            if let Some(prev) = pm.pending.metallic_roughness.replace(s.clone()) {
                mat.extras.insert(
                    "mtl:displaced_pbr_map".to_string(),
                    serde_json::Value::String(prev),
                );
            }
            mat.extras
                .insert(format!("mtl:{keyword}"), serde_json::Value::String(s));
        }
        "refl" | "map_refl" => {
            // Reflection-map statements per spec §"Reflection Map" come
            // in three discriminated forms via the `-type` flag:
            //
            //   refl -type sphere -options -args filename
            //   refl -type cube_top|cube_bottom|cube_front|cube_back|cube_left|cube_right ... filename
            //
            // (plus the legacy bare-`refl filename` form which we
            // preserve under `mtl:refl` as before).
            //
            // Cube faces span SIX separate `refl` lines that together
            // describe one cubemap; bundle them into a single
            // `mtl:refl:cube` object keyed by face name so consumers
            // see one cubemap declaration rather than six unrelated
            // textures. Sphere lands as `mtl:refl:sphere = filename`.
            //
            // Per-line option flags (`-blendu`, `-mm`, …) attached to
            // a typed reflection-map line live next to the filename in
            // a `{file, options: [...]}` object so the round-trip is
            // bit-stable.
            let toks: Vec<&str> = tokens.collect();
            let mut iter = toks.iter().copied().peekable();
            // Pull a `-type <kind>` flag out of the option stream when
            // it is the first option; bare-refl with no `-type` falls
            // through to the legacy single-string form.
            let mut refl_kind: Option<&'static str> = None;
            if iter.peek() == Some(&"-type") {
                let _ = iter.next();
                if let Some(kind) = iter.next() {
                    refl_kind = match kind {
                        "sphere" => Some("sphere"),
                        "cube_top" => Some("cube_top"),
                        "cube_bottom" => Some("cube_bottom"),
                        "cube_front" => Some("cube_front"),
                        "cube_back" => Some("cube_back"),
                        "cube_left" => Some("cube_left"),
                        "cube_right" => Some("cube_right"),
                        // Spec also lists the legacy `cube_side` keyword
                        // as an alias-shape; surface it verbatim.
                        "cube_side" => Some("cube_side"),
                        _ => None,
                    };
                    if refl_kind.is_none() {
                        // Unknown -type kind — preserve verbatim via
                        // the legacy single-string slot below.
                    }
                }
            }
            // Re-collect the remaining tokens into a SplitWhitespace-
            // shaped helper so `map_options_and_filename` can work over
            // them without regressing the existing API.
            let remaining: Vec<&str> = iter.collect();
            let joined = remaining.join(" ");
            let mut split = joined.split_whitespace();
            let (opts, filename) = map_options_and_filename(&mut split);

            match refl_kind {
                Some(face) if face != "sphere" && face != "cube_side" => {
                    // Cube face — fold into the per-material cubemap
                    // bundle. Each face is a `{file, options}` object;
                    // missing options arrays are omitted.
                    let mut entry = serde_json::Map::new();
                    entry.insert(
                        "file".to_string(),
                        serde_json::Value::String(filename.clone()),
                    );
                    if !opts.is_empty() {
                        entry.insert(
                            "options".to_string(),
                            serde_json::Value::Array(
                                opts.iter()
                                    .map(|s| serde_json::Value::String(s.clone()))
                                    .collect(),
                            ),
                        );
                    }
                    let cube_key = "mtl:refl:cube".to_string();
                    let cube_obj = match mat.extras.remove(&cube_key) {
                        Some(serde_json::Value::Object(map)) => map,
                        _ => serde_json::Map::new(),
                    };
                    let mut cube_obj = cube_obj;
                    cube_obj.insert(face.to_string(), serde_json::Value::Object(entry));
                    mat.extras
                        .insert(cube_key, serde_json::Value::Object(cube_obj));
                }
                Some("sphere") => {
                    let mut entry = serde_json::Map::new();
                    entry.insert(
                        "file".to_string(),
                        serde_json::Value::String(filename.clone()),
                    );
                    if !opts.is_empty() {
                        entry.insert(
                            "options".to_string(),
                            serde_json::Value::Array(
                                opts.iter()
                                    .map(|s| serde_json::Value::String(s.clone()))
                                    .collect(),
                            ),
                        );
                    }
                    mat.extras.insert(
                        "mtl:refl:sphere".to_string(),
                        serde_json::Value::Object(entry),
                    );
                }
                _ => {
                    // Bare `refl filename` (legacy) or unknown -type
                    // kind — preserve via the original single-string
                    // slot used in r3.
                    if !opts.is_empty() {
                        mat.extras.insert(
                            format!("mtl:{keyword}:options"),
                            serde_json::Value::Array(
                                opts.into_iter().map(serde_json::Value::String).collect(),
                            ),
                        );
                    }
                    mat.extras.insert(
                        format!("mtl:{keyword}"),
                        serde_json::Value::String(filename),
                    );
                }
            }
        }
        "map_Ka" | "map_Ks" | "map_Ns" | "map_d" | "disp" | "map_disp" | "decal" | "map_decal" => {
            // Less-PBR-friendly maps preserved in extras for round-trip.
            // Both the bare (`disp`, `decal`) and `map_*` variants are
            // accepted; the original spelling is kept as the extras key
            // so the encoder re-emits the same form.
            let s = parse_map_with_options(keyword, tokens, &mut mat.extras);
            mat.extras
                .insert(format!("mtl:{keyword}"), serde_json::Value::String(s));
        }
        // Unknown directives are silently skipped (lenient-loader convention).
        _ => {}
    }
    Ok(())
}

/// Split a `map_*` token stream into `(options, filename)`.
///
/// `map_Kd -blendu off -clamp on -mm 0 1 path/to/diffuse.png`
/// returns `(["-blendu off", "-clamp on", "-mm 0 1"], "path/to/diffuse.png")`.
///
/// Each leading `-flag` token consumes a known number of arguments
/// per the MTL spec ("Options for texture map statements", Bourke
/// mirror line 540 onwards). Once a token that is neither a flag nor
/// a flag argument is encountered, the rest of the line is treated
/// as the filename (joined with single spaces so paths with embedded
/// whitespace round-trip).
fn map_options_and_filename(tokens: &mut std::str::SplitWhitespace<'_>) -> (Vec<String>, String) {
    let toks: Vec<&str> = tokens.collect();
    let mut opts: Vec<String> = Vec::new();
    let mut i = 0;
    while i < toks.len() {
        let t = toks[i];
        // Only `-letter…` is a flag; bare integers / negative numbers
        // for paths starting with `-` would also start with `-`,
        // but the second char is the discriminator (alphabetic ⇒ flag).
        let is_flag = t.starts_with('-')
            && t.len() > 1
            && t.chars().nth(1).is_some_and(|c| c.is_ascii_alphabetic());
        if !is_flag {
            break;
        }
        let arg_count = flag_arg_count(t);
        if arg_count == 0 {
            // Unknown flag — preserve verbatim and hope the next token
            // is the filename. Bumps the index by 1.
            opts.push(t.to_string());
            i += 1;
            continue;
        }
        // Make sure we have enough remaining tokens; if not, the file
        // name was truncated mid-flag and we surface the original
        // tail verbatim so the user sees the malformed input.
        let end = (i + 1 + arg_count).min(toks.len());
        let chunk: Vec<&str> = toks[i..end].to_vec();
        opts.push(chunk.join(" "));
        i = end;
    }
    let filename = toks[i..].join(" ");
    (opts, filename)
}

/// Number of arguments that follow a known `map_*` option flag, per
/// the MTL spec. Unknown flags return 0 → the parser preserves the
/// flag literally and treats the next token as the filename.
fn flag_arg_count(flag: &str) -> usize {
    match flag {
        "-blendu" | "-blendv" | "-cc" | "-clamp" => 1, // on | off
        "-bm" | "-boost" | "-texres" => 1,             // single float / int
        "-imfchan" | "-type" => 1,                     // single char / keyword
        "-mm" => 2,                                    // base gain
        // `-o`, `-s`, `-t` are documented as `u [v] [w]` — variable
        // arity. We greedily consume up to three numeric tokens after
        // the flag in `consume_uvw`, but the static count is 3 so
        // well-formed inputs round-trip cleanly. If a path follows
        // earlier than expected (e.g. `-o 1 path.png`), the path
        // accidentally absorbs the missing v / w; users who need that
        // edge case can supply explicit zeros.
        "-o" | "-s" | "-t" => 3,
        _ => 0,
    }
}

/// Parse a `map_*`-style keyword: split into (options, filename),
/// stash the options in `extras["mtl:<keyword>:options"]`, and return
/// the bare filename for caller-side TextureRef wiring.
fn parse_map_with_options(
    keyword: &str,
    tokens: &mut std::str::SplitWhitespace<'_>,
    extras: &mut std::collections::HashMap<String, serde_json::Value>,
) -> String {
    let (opts, filename) = map_options_and_filename(tokens);
    if !opts.is_empty() {
        extras.insert(
            format!("mtl:{keyword}:options"),
            serde_json::Value::Array(opts.into_iter().map(serde_json::Value::String).collect()),
        );
    }
    filename
}

// ---------------------------------------------------------------------------
// Serialisation
// ---------------------------------------------------------------------------

/// Serialise a slice of materials to MTL format.
///
/// Texture references are emitted via the `External { uri, .. }`
/// variant — the URI is written verbatim. Embedded / Source textures
/// are skipped (no on-disk path to point at); a one-line comment
/// identifies the gap so the file is round-trip-able under the same
/// invariants as the decoder.
pub fn serialize_mtl(materials: &[Material], textures: &[Texture]) -> Result<Vec<u8>> {
    use std::fmt::Write;
    let mut out = String::new();
    writeln!(out, "# MTL generated by oxideav-obj").unwrap();

    for (i, mat) in materials.iter().enumerate() {
        let name = mat.name.clone().unwrap_or_else(|| format!("material_{i}"));
        writeln!(out, "newmtl {name}").unwrap();

        if let Some(serde_json::Value::Array(v)) = mat.extras.get("mtl:Ka") {
            if let [a, b, c] = v.as_slice() {
                writeln!(
                    out,
                    "Ka {} {} {}",
                    fmt_f(a.as_f64().unwrap_or(0.0) as f32),
                    fmt_f(b.as_f64().unwrap_or(0.0) as f32),
                    fmt_f(c.as_f64().unwrap_or(0.0) as f32)
                )
                .unwrap();
            }
        }
        // Always emit Kd (it's the canonical glTF base color → MTL Phong diffuse).
        writeln!(
            out,
            "Kd {} {} {}",
            fmt_f(mat.base_color[0]),
            fmt_f(mat.base_color[1]),
            fmt_f(mat.base_color[2])
        )
        .unwrap();
        if let Some(serde_json::Value::Array(v)) = mat.extras.get("mtl:Ks") {
            if let [a, b, c] = v.as_slice() {
                writeln!(
                    out,
                    "Ks {} {} {}",
                    fmt_f(a.as_f64().unwrap_or(0.0) as f32),
                    fmt_f(b.as_f64().unwrap_or(0.0) as f32),
                    fmt_f(c.as_f64().unwrap_or(0.0) as f32)
                )
                .unwrap();
            }
        }
        if mat.emissive_factor != [0.0, 0.0, 0.0] {
            writeln!(
                out,
                "Ke {} {} {}",
                fmt_f(mat.emissive_factor[0]),
                fmt_f(mat.emissive_factor[1]),
                fmt_f(mat.emissive_factor[2])
            )
            .unwrap();
        }
        if let Some(v) = mat.extras.get("mtl:Ns").and_then(|v| v.as_f64()) {
            writeln!(out, "Ns {}", fmt_f(v as f32)).unwrap();
        }
        if let Some(v) = mat.extras.get("mtl:Ni").and_then(|v| v.as_f64()) {
            writeln!(out, "Ni {}", fmt_f(v as f32)).unwrap();
        }
        // Tf transmission filter — one of three mutually exclusive
        // forms per spec §"Tf". Only the first present extras key is
        // emitted (per the spec's mutual-exclusion clause).
        if let Some(serde_json::Value::Array(v)) = mat.extras.get("mtl:Tf") {
            if let [a, b, c] = v.as_slice() {
                writeln!(
                    out,
                    "Tf {} {} {}",
                    fmt_f(a.as_f64().unwrap_or(0.0) as f32),
                    fmt_f(b.as_f64().unwrap_or(0.0) as f32),
                    fmt_f(c.as_f64().unwrap_or(0.0) as f32)
                )
                .unwrap();
            }
        } else if let Some(serde_json::Value::Object(o)) = mat.extras.get("mtl:Tf:spectral") {
            // `Tf spectral file.rfl factor` — `factor` defaults to 1.0
            // and is omitted from the emit when it equals the default,
            // so the round-trip matches the most common operator-written
            // form.
            let file = o.get("file").and_then(|v| v.as_str()).unwrap_or("");
            let factor = o.get("factor").and_then(|v| v.as_f64()).unwrap_or(1.0) as f32;
            if (factor - 1.0).abs() < f32::EPSILON {
                writeln!(out, "Tf spectral {file}").unwrap();
            } else {
                writeln!(out, "Tf spectral {file} {}", fmt_f(factor)).unwrap();
            }
        } else if let Some(serde_json::Value::Array(v)) = mat.extras.get("mtl:Tf:xyz") {
            if let [a, b, c] = v.as_slice() {
                writeln!(
                    out,
                    "Tf xyz {} {} {}",
                    fmt_f(a.as_f64().unwrap_or(0.0) as f32),
                    fmt_f(b.as_f64().unwrap_or(0.0) as f32),
                    fmt_f(c.as_f64().unwrap_or(0.0) as f32)
                )
                .unwrap();
            }
        }
        // sharpness — scalar, MTL spec §"sharpness value".
        if let Some(v) = mat.extras.get("mtl:sharpness").and_then(|v| v.as_f64()) {
            writeln!(out, "sharpness {}", fmt_f(v as f32)).unwrap();
        }
        if mat.base_color[3] < 1.0 || matches!(mat.alpha_mode, AlphaMode::Blend) {
            // Emit `d -halo <factor>` when the parser captured a halo
            // dissolve, otherwise the canonical `d <value>` form.
            if mat.extras.contains_key("mtl:d_halo_factor") {
                writeln!(out, "d -halo {}", fmt_f(mat.base_color[3])).unwrap();
            } else {
                writeln!(out, "d {}", fmt_f(mat.base_color[3])).unwrap();
            }
        }
        if let Some(v) = mat.extras.get("mtl:illum").and_then(|v| v.as_i64()) {
            writeln!(out, "illum {v}").unwrap();
        }
        // PBR fields — only emit when the user actually carries PBR values.
        // The mesh3d default is metallic=1.0 / roughness=1.0; our parser
        // resets those to 0 / 0.5 when constructing from MTL, so any
        // non-default value is taken to indicate "PBR is in use".
        let pbr_in_use = mat.metallic != 0.0
            || (mat.roughness - 0.5).abs() > f32::EPSILON
            || mat.metallic_roughness_texture.is_some()
            || mat.extras.contains_key("mtl:Pc")
            || mat.extras.contains_key("mtl:Ps");
        if pbr_in_use {
            writeln!(out, "Pr {}", fmt_f(mat.roughness)).unwrap();
            writeln!(out, "Pm {}", fmt_f(mat.metallic)).unwrap();
        }
        if let Some(v) = mat.extras.get("mtl:Pc").and_then(|v| v.as_f64()) {
            writeln!(out, "Pc {}", fmt_f(v as f32)).unwrap();
        }
        if let Some(v) = mat.extras.get("mtl:Ps").and_then(|v| v.as_f64()) {
            writeln!(out, "Ps {}", fmt_f(v as f32)).unwrap();
        }

        // Texture references — splice any saved `-flag value` option
        // chunks back ahead of the filename so the round-trip emits
        // `map_Kd -clamp on path.png` instead of just `map_Kd path.png`.
        write_tex_ref(
            &mut out,
            "map_Kd",
            mat.base_color_texture,
            textures,
            &mat.extras,
        );
        write_tex_ref(
            &mut out,
            "map_Bump",
            mat.normal_texture,
            textures,
            &mat.extras,
        );
        write_tex_ref(
            &mut out,
            "map_Pr",
            mat.metallic_roughness_texture,
            textures,
            &mat.extras,
        );
        write_tex_ref(
            &mut out,
            "map_Ke",
            mat.emissive_texture,
            textures,
            &mat.extras,
        );

        // Typed reflection-map sets per spec §"Reflection Map":
        // `refl -type sphere file` and the six `refl -type cube_*`
        // faces. Each face emits as its own line; option flags
        // captured per-face are spliced ahead of the filename.
        if let Some(serde_json::Value::Object(o)) = mat.extras.get("mtl:refl:sphere") {
            let file = o.get("file").and_then(|v| v.as_str()).unwrap_or("");
            let opts: Vec<&str> = o
                .get("options")
                .and_then(|v| v.as_array())
                .map(|a| a.iter().filter_map(|s| s.as_str()).collect())
                .unwrap_or_default();
            if opts.is_empty() {
                writeln!(out, "refl -type sphere {file}").unwrap();
            } else {
                writeln!(out, "refl -type sphere {} {file}", opts.join(" ")).unwrap();
            }
        }
        if let Some(serde_json::Value::Object(faces)) = mat.extras.get("mtl:refl:cube") {
            // Fixed face order — keeps the round-trip diff stable
            // regardless of HashMap insertion order.
            for face in [
                "cube_top",
                "cube_bottom",
                "cube_front",
                "cube_back",
                "cube_left",
                "cube_right",
                "cube_side",
            ] {
                let Some(serde_json::Value::Object(entry)) = faces.get(face) else {
                    continue;
                };
                let file = entry.get("file").and_then(|v| v.as_str()).unwrap_or("");
                let opts: Vec<&str> = entry
                    .get("options")
                    .and_then(|v| v.as_array())
                    .map(|a| a.iter().filter_map(|s| s.as_str()).collect())
                    .unwrap_or_default();
                if opts.is_empty() {
                    writeln!(out, "refl -type {face} {file}").unwrap();
                } else {
                    writeln!(out, "refl -type {face} {} {file}", opts.join(" ")).unwrap();
                }
            }
        }

        // Pass-through extras — `mtl:*` keys we didn't consume above.
        for (k, v) in &mat.extras {
            if !k.starts_with("mtl:") {
                continue;
            }
            // Skip the keys we already printed above.
            match k.as_str() {
                "mtl:Ka"
                | "mtl:Ks"
                | "mtl:Ns"
                | "mtl:Ni"
                | "mtl:illum"
                | "mtl:Pc"
                | "mtl:Ps"
                | "mtl:Tf"
                | "mtl:Tf:spectral"
                | "mtl:Tf:xyz"
                | "mtl:sharpness"
                | "mtl:displaced_pbr_map"
                | "mtl:d_halo_factor"
                | "mtl:refl:sphere"
                | "mtl:refl:cube" => continue,
                _ => {}
            }
            // `mtl:<map>:options` chunks are spliced inline by
            // write_tex_ref / the bare-`disp`-etc pass-through; skip
            // them here so they don't double-emit as a standalone line.
            if k.ends_with(":options") {
                continue;
            }
            // Only emit string-valued passthrough keys (textures we didn't model);
            // numeric ones we don't consume just stay as side-channel metadata.
            if let Some(s) = v.as_str() {
                let kw = k.strip_prefix("mtl:").unwrap_or(k.as_str());
                // Splice options ahead of the filename for keys that
                // have an associated `:options` companion (disp /
                // decal / refl / map_Ka / map_Ks / map_Ns / map_d).
                let opts_key = format!("mtl:{kw}:options");
                if let Some(serde_json::Value::Array(opts)) = mat.extras.get(&opts_key) {
                    let parts: Vec<&str> = opts.iter().filter_map(|o| o.as_str()).collect();
                    writeln!(out, "{kw} {} {s}", parts.join(" ")).unwrap();
                } else {
                    writeln!(out, "{kw} {s}").unwrap();
                }
            }
        }

        out.push('\n');
    }

    Ok(out.into_bytes())
}

fn write_tex_ref(
    out: &mut String,
    keyword: &str,
    ref_: Option<TextureRef>,
    textures: &[Texture],
    extras: &std::collections::HashMap<String, serde_json::Value>,
) {
    use std::fmt::Write;
    let Some(r) = ref_ else { return };
    let Some(tex) = textures.get(r.texture.0 as usize) else {
        return;
    };
    if let ImageData::External { uri, .. } = &tex.image {
        // Splice any saved option flags ahead of the filename. The
        // options key uses the canonical map keyword (e.g. `map_Bump`)
        // even when the user originally wrote `bump` / `map_bump` /
        // `norm` — those alias keywords store options under whatever
        // spelling the user used, so try both.
        let opts_key = format!("mtl:{keyword}:options");
        let alt_keys: &[&str] = match keyword {
            "map_Bump" => &[
                "mtl:map_bump:options",
                "mtl:bump:options",
                "mtl:norm:options",
            ],
            _ => &[],
        };
        let opts = extras
            .get(&opts_key)
            .or_else(|| alt_keys.iter().find_map(|k| extras.get(*k)));
        if let Some(serde_json::Value::Array(arr)) = opts {
            let parts: Vec<&str> = arr.iter().filter_map(|o| o.as_str()).collect();
            if parts.is_empty() {
                writeln!(out, "{keyword} {uri}").unwrap();
            } else {
                writeln!(out, "{keyword} {} {uri}", parts.join(" ")).unwrap();
            }
        } else {
            writeln!(out, "{keyword} {uri}").unwrap();
        }
    }
}

fn fmt_f(x: f32) -> String {
    if x == 0.0 {
        return "0".to_string();
    }
    let s = format!("{x:.6}");
    let trimmed = s.trim_end_matches('0').trim_end_matches('.').to_string();
    if trimmed.is_empty() || trimmed == "-" {
        "0".to_string()
    } else {
        trimmed
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn parses_minimal_phong() {
        let text = "newmtl Red\nKd 1.0 0.0 0.0\nKa 0.1 0.1 0.1\nNs 32\n";
        let mats = parse_mtl(text).unwrap();
        assert_eq!(mats.len(), 1);
        let m = &mats[0];
        assert_eq!(m.name.as_deref(), Some("Red"));
        assert_eq!(m.base_color[0..3], [1.0, 0.0, 0.0]);
        assert_eq!(
            m.extras
                .get("mtl:Ka")
                .and_then(|v| v.as_array())
                .map(|a| a.len()),
            Some(3)
        );
        assert_eq!(m.extras.get("mtl:Ns").and_then(|v| v.as_f64()), Some(32.0));
    }

    #[test]
    fn dissolve_sets_alpha_blend() {
        let mats = parse_mtl("newmtl Glass\nKd 0.5 0.5 0.5\nd 0.4\n").unwrap();
        assert_eq!(mats[0].base_color[3], 0.4);
        assert!(matches!(mats[0].alpha_mode, AlphaMode::Blend));
    }

    #[test]
    fn tr_alternate_dissolve() {
        let mats = parse_mtl("newmtl Glass\nKd 0.5 0.5 0.5\nTr 0.4\n").unwrap();
        // Tr = 1 - d  ⇒  d = 0.6
        assert!((mats[0].base_color[3] - 0.6).abs() < 1e-6);
        assert!(matches!(mats[0].alpha_mode, AlphaMode::Blend));
    }

    #[test]
    fn pbr_extension_lands_in_pbr_slots() {
        let mats =
            parse_mtl("newmtl Steel\nKd 0.7 0.7 0.7\nPr 0.25\nPm 0.95\nPc 0.5\nPs 0.1\n").unwrap();
        let m = &mats[0];
        assert!((m.roughness - 0.25).abs() < 1e-6);
        assert!((m.metallic - 0.95).abs() < 1e-6);
        let pc = m.extras.get("mtl:Pc").and_then(|v| v.as_f64()).unwrap();
        assert!((pc - 0.5).abs() < 1e-6);
        let ps = m.extras.get("mtl:Ps").and_then(|v| v.as_f64()).unwrap();
        assert!((ps - 0.1).abs() < 1e-6);
    }

    #[test]
    fn map_kd_pending_uri_round_trips() {
        let mats = parse_mtl("newmtl Tex\nKd 1 1 1\nmap_Kd diffuse.png\n").unwrap();
        let pending = mats[0].extras.get("mtl:pending_textures").unwrap();
        assert_eq!(pending["base_color"].as_str(), Some("diffuse.png"));
    }
}