gizmo-renderer 0.8.0

A custom ECS and physics engine aimed for realistic simulations.
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
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
use super::decode_obj_vertices_for_async;
use super::error::AssetError;
use gizmo_animation::skeletal::{AnimationClip, Keyframe, SkeletonHierarchy, SkeletonJoint, Track};
use crate::components::{Material, Mesh};
use crate::renderer::Vertex;
use gizmo_math::{Quat, Vec3};
use std::sync::Arc;
use wgpu::util::DeviceExt;

// ============================================================================
//  Public data structures
// ============================================================================

pub struct GltfNodeData {
    pub index: usize,
    pub name: Option<String>,
    /// Index into [`GltfSceneAsset::skeletons`] if this node drives a skin.
    pub skin_index: Option<usize>,
    pub translation: [f32; 3],
    pub rotation: [f32; 4],
    pub scale: [f32; 3],
    /// (mesh, optional material) per glTF primitive on this node.
    pub primitives: Vec<(Mesh, Option<Material>)>,
    pub children: Vec<GltfNodeData>,
}

pub struct GltfSceneAsset {
    pub roots: Vec<GltfNodeData>,
    pub animations: Vec<AnimationClip>,
    pub skeletons: Vec<SkeletonHierarchy>,
}

// ============================================================================
//  AssetManager impls
// ============================================================================

impl super::AssetManager {
    // ── OBJ ──────────────────────────────────────────────────────────────────

    /// Upload an already-decoded OBJ vertex buffer to the GPU and cache it.
    ///
    /// Called by [`AsyncAssetLoader`](crate::async_assets::AsyncAssetLoader)
    /// after decoding completes on a worker thread.
    pub fn install_obj_mesh(
        &mut self,
        device: &wgpu::Device,
        file_path: &str,
        vertices: Vec<Vertex>,
        _aabb: gizmo_math::Aabb,
    ) -> Mesh {
        let vbuf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some(&format!("OBJ VBuf: {file_path}")),
            contents: bytemuck::cast_slice(&vertices),
            usage: wgpu::BufferUsages::VERTEX,
        });
        let mesh = Mesh::new(
            device,
            Arc::new(vbuf),
            &vertices,
            Vec3::ZERO,
            format!("obj:{file_path}"),
        );
        self.mesh_cache.insert(file_path.to_string(), mesh.clone());
        mesh
    }

    /// Load an OBJ file from disk (or return the cached copy).
    pub fn load_obj(&mut self, device: &wgpu::Device, file_path_or_uuid: &str) -> Mesh {
        let file_path = match self.resolve_path_from_meta_source(file_path_or_uuid) {
            Ok(p) => p,
            Err(e) => {
                tracing::error!("[AssetManager] ERROR: {e}");
                return self.loading_placeholder_mesh(device);
            }
        };

        // Prefer UUID as cache key when available.
        let cache_key = self
            .get_uuid(&file_path)
            .map(|id| id.to_string())
            .unwrap_or_else(|| file_path.clone());

        if let Some(cached) = self.mesh_cache.get(&cache_key) {
            return cached.clone();
        }

        let (vertices, aabb) = match decode_obj_vertices_for_async(&file_path) {
            Ok(v) => v,
            Err(e) => {
                tracing::error!("[AssetManager] OBJ load failed: {file_path} — {e}");
                // Return a valid-but-empty mesh so nothing downstream panics.
                let vbuf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
                    label: Some("Fallback VBuf (not found)"),
                    contents: &[],
                    usage: wgpu::BufferUsages::VERTEX,
                });
                return Mesh::empty(Arc::new(vbuf), format!("obj:missing_{file_path}"));
            }
        };

        self.install_obj_mesh(device, &cache_key, vertices, aabb)
    }

    // ── glTF — top-level entry points ────────────────────────────────────────

    /// Load a glTF scene from disk (or embedded data) and upload it to the GPU.
    ///
    /// The returned [`GltfSceneAsset`] is pure CPU/ECS data; a separate scene
    /// builder is responsible for spawning ECS entities from it.
    pub fn load_gltf_scene(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        texture_bind_group_layout: &wgpu::BindGroupLayout,
        default_tbind: Arc<wgpu::BindGroup>,
        path_or_uuid: &str,
    ) -> Result<GltfSceneAsset, AssetError> {
        let file_path = self.resolve_path_from_meta_source(path_or_uuid)?;
        let cache_key = self
            .get_uuid(&file_path)
            .map(|id| id.to_string())
            .unwrap_or_else(|| file_path.clone());

        let import_result = if let Some(data) = self.embedded_assets.get(&file_path) {
            gltf::import_slice(data.as_ref())
        } else {
            gltf::import(&file_path)
        };

        let (document, buffers, images) =
            import_result.map_err(|source| AssetError::GltfImport {
                path: std::path::PathBuf::from(&file_path),
                source,
            })?;
        self.load_gltf_from_import(
            device,
            queue,
            texture_bind_group_layout,
            default_tbind,
            &cache_key,
            document,
            buffers,
            images,
        )
    }

    /// Upload a pre-parsed glTF import to the GPU.
    ///
    /// Split from `load_gltf_scene` so that `gltf::import` (which is
    /// CPU-bound and blocks) can be called off the main thread while GPU
    /// upload happens here on the main thread.
    pub fn load_gltf_from_import(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        texture_bind_group_layout: &wgpu::BindGroupLayout,
        default_tbind: Arc<wgpu::BindGroup>,
        file_path: &str,
        document: gltf::Document,
        buffers: Vec<gltf::buffer::Data>,
        images: Vec<gltf::image::Data>,
    ) -> Result<GltfSceneAsset, AssetError> {
        // ── 1. Textures ───────────────────────────────────────────────────
        // Classify each image by usage so colour maps (base/emissive) are uploaded
        // as sRGB while data maps (normal/MR/AO) stay linear, then upload.
        self.ensure_material_defaults(device, queue);
        let srgb_flags = classify_gltf_image_srgb(&document, images.len());
        let gpu_images = upload_gltf_images(device, queue, file_path, &images, &srgb_flags);

        // ── 2. Materials ──────────────────────────────────────────────────
        let defaults = self
            .material_defaults()
            .expect("material defaults ensured above");
        let gltf_materials = build_gltf_materials(
            device,
            texture_bind_group_layout,
            &document,
            &gpu_images,
            defaults,
            &default_tbind,
        );

        // ── 3. Node tree ──────────────────────────────────────────────────
        let mut roots = Vec::new();
        for scene in document.scenes() {
            for node in scene.nodes() {
                roots.push(self.parse_gltf_node(
                    device,
                    &node,
                    &buffers,
                    &gltf_materials,
                    file_path,
                ));
            }
        }

        // ── 4. Animations ─────────────────────────────────────────────────
        let animations = parse_animations(&document, &buffers);

        // ── 5. Skeletons ──────────────────────────────────────────────────
        // Build a node-index → parent-node-index lookup (used when resolving
        // bone parents and the armature root transform).
        let node_parents: std::collections::HashMap<usize, usize> = document
            .nodes()
            .flat_map(|parent| {
                parent
                    .children()
                    .map(move |child| (child.index(), parent.index()))
            })
            .collect();

        // Build a fast node-index → Node lookup so we avoid O(n) `.nth()`.
        let nodes_by_index: Vec<gltf::Node> = document.nodes().collect();

        let skeletons = parse_skeletons(&document, &buffers, &node_parents, &nodes_by_index);

        Ok(GltfSceneAsset {
            roots,
            animations,
            skeletons,
        })
    }

    // ── glTF — node parsing ───────────────────────────────────────────────────

    fn parse_gltf_node(
        &mut self,
        device: &wgpu::Device,
        node: &gltf::Node,
        buffers: &[gltf::buffer::Data],
        materials: &[Material],
        file_name: &str,
    ) -> GltfNodeData {
        let (translation, rotation, scale) = node.transform().decomposed();

        let mut primitives = Vec::new();

        if let Some(mesh) = node.mesh() {
            for (prim_i, primitive) in mesh.primitives().enumerate() {
                // Only handle triangles — skip lines, points, strips, etc.
                if primitive.mode() != gltf::mesh::Mode::Triangles {
                    tracing::error!(
                        "[GLTF WARN] Skipping non-triangle primitive (mode={:?}) on node '{}'",
                        primitive.mode(),
                        node.name().unwrap_or("<unnamed>"),
                    );
                    continue;
                }

                let reader = primitive.reader(|buf| Some(&buffers[buf.index()]));

                let positions: Vec<[f32; 3]> = reader
                    .read_positions()
                    .map(|it| it.collect())
                    .unwrap_or_default();

                if positions.is_empty() {
                    continue; // nothing to upload
                }

                let supplied_normals: Option<Vec<[f32; 3]>> =
                    reader.read_normals().map(|it| it.collect());

                let supplied_tangents: Option<Vec<[f32; 4]>> =
                    reader.read_tangents().map(|it| it.collect());

                let tex_coords: Vec<[f32; 2]> = reader
                    .read_tex_coords(0)
                    .map(|it| it.into_f32().collect())
                    .unwrap_or_else(|| vec![[0.0, 0.0]; positions.len()]);

                let joints: Option<Vec<[u16; 4]>> =
                    reader.read_joints(0).map(|it| it.into_u16().collect());
                let weights: Option<Vec<[f32; 4]>> =
                    reader.read_weights(0).map(|it| it.into_f32().collect());

                // Expand indexed geometry into a flat vertex list.
                let mut all_vertices: Vec<Vertex> = Vec::new();
                let mut aabb = gizmo_math::Aabb::empty();

                let make_vertex = |idx: usize| -> Vertex {
                    let pos = positions[idx];

                    // Safe access — attribute arrays may be shorter than positions.
                    let normal = supplied_normals
                        .as_ref()
                        .and_then(|n| n.get(idx).copied())
                        .unwrap_or([0.0, 1.0, 0.0]);
                    let uv = tex_coords.get(idx).copied().unwrap_or([0.0, 0.0]);
                    let j = joints
                        .as_ref()
                        .and_then(|js| js.get(idx))
                        .map(|&[a, b, c, d]| [a as u32, b as u32, c as u32, d as u32])
                        .unwrap_or([0; 4]);
                    let w = normalize_skin_weights(
                        weights
                            .as_ref()
                            .and_then(|ws| ws.get(idx))
                            .copied()
                            .unwrap_or([0.0; 4]),
                    );

                    let tangent = if let Some(ref tangents) = supplied_tangents {
                        tangents.get(idx).copied().unwrap_or([1.0, 0.0, 0.0, 1.0])
                    } else {
                        // Calculate a dynamic tangent orthogonal to normal
                        let n = gizmo_math::Vec3::from(normal);
                        let t = if n.x.abs() > 0.9 {
                            gizmo_math::Vec3::new(0.0, 1.0, 0.0).cross(n).normalize()
                        } else {
                            gizmo_math::Vec3::new(1.0, 0.0, 0.0).cross(n).normalize()
                        };
                        [t.x, t.y, t.z, 1.0]
                    };

                    Vertex {
                        position: pos,
                        normal,
                        tex_coords: uv,
                        color: [1.0, 1.0, 1.0],
                        joint_indices: j,
                        joint_weights: w,
                        tangent,
                    }
                };

                if let Some(indices) = reader.read_indices() {
                    // Triangle-list assembly: process indices in groups of 3 and
                    // drop the WHOLE triangle if any index is out of bounds.
                    // (Skipping a single OOB index would shift every later vertex
                    // and corrupt the grouping of all following triangles.)
                    let idx: Vec<u32> = indices.into_u32().collect();
                    for tri in idx.chunks_exact(3) {
                        if tri.iter().any(|&t| (t as usize) >= positions.len()) {
                            continue;
                        }
                        for &t in tri {
                            let i = t as usize;
                            let pos = positions[i];
                            aabb.extend(Vec3::new(pos[0], pos[1], pos[2]));
                            all_vertices.push(make_vertex(i));
                        }
                    }
                } else {
                    for (i, pos) in positions.iter().enumerate() {
                        aabb.extend(Vec3::new(pos[0], pos[1], pos[2]));
                        all_vertices.push(make_vertex(i));
                    }
                }

                // Compute flat normals when the file did not supply any.
                // We only do this for triangle lists (guaranteed above).
                if supplied_normals.is_none() {
                    compute_flat_normals(&mut all_vertices);
                }

                let vbuf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
                    label: Some(&format!("GLTF VBuf: {file_name}_prim{prim_i}")),
                    contents: bytemuck::cast_slice(&all_vertices),
                    usage: wgpu::BufferUsages::VERTEX,
                });

                // Use a deterministic cache key that doesn't depend on Debug formatting.
                let mesh_source = format!(
                    "gltf_mesh_{file_name}_{}_p{prim_i}",
                    node.name().unwrap_or("<unnamed>")
                );
                let mesh_comp = Mesh::new(
                    device,
                    Arc::new(vbuf),
                    &all_vertices,
                    Vec3::ZERO,
                    mesh_source.clone(),
                );
                self.mesh_cache.insert(mesh_source, mesh_comp.clone());

                let mat_opt = primitive
                    .material()
                    .index()
                    .and_then(|idx| materials.get(idx).cloned());

                primitives.push((mesh_comp, mat_opt));
            }
        }

        let children = node
            .children()
            .map(|child| self.parse_gltf_node(device, &child, buffers, materials, file_name))
            .collect();

        GltfNodeData {
            index: node.index(),
            name: node.name().map(str::to_owned),
            skin_index: node.skin().map(|s| s.index()),
            translation,
            rotation,
            scale,
            primitives,
            children,
        }
    }
}

// ============================================================================
//  Free helpers — image conversion
// ============================================================================

/// Convert any glTF image format to RGBA8, always producing `width * height * 4` bytes.
fn convert_image_to_rgba8(image: &gltf::image::Data, idx: usize, file_path: &str) -> Vec<u8> {
    let (w, h) = (image.width as usize, image.height as usize);
    let pixel_count = w * h;

    match image.format {
        gltf::image::Format::R8G8B8A8 => {
            // Already in the right format — clone and return.
            // Guard against truncated data so write_texture can't panic.
            let expected = pixel_count * 4;
            if image.pixels.len() >= expected {
                image.pixels[..expected].to_vec()
            } else {
                // Pad with opaque black.
                let mut out = image.pixels.clone();
                out.resize(expected, 255);
                out
            }
        }

        gltf::image::Format::R8G8B8 => {
            // Drop the boundary check: chunks_exact only yields complete 3-byte chunks,
            // silently ignoring a trailing 1 or 2 bytes. A trailing partial pixel is
            // a malformed file; padding it to opaque black is the safest recovery.
            let mut out = Vec::with_capacity(pixel_count * 4);
            for chunk in image.pixels.chunks_exact(3) {
                out.extend_from_slice(&[chunk[0], chunk[1], chunk[2], 255]);
            }
            // Pad if the source was shorter than expected.
            out.resize(pixel_count * 4, 255);
            out
        }

        gltf::image::Format::R8G8 => {
            // glTF R8G8 = two independent channels (Red, Green) — NOT luminance+alpha.
            // Map R→R, G→G, B=0, A=opaque. (Previously broadcast R into RGB and put
            // G into alpha, losing the green channel.)
            let mut out = Vec::with_capacity(pixel_count * 4);
            for chunk in image.pixels.chunks_exact(2) {
                out.extend_from_slice(&[chunk[0], chunk[1], 0, 255]);
            }
            out.resize(pixel_count * 4, 255);
            out
        }

        gltf::image::Format::R8 => {
            // Single-channel luminance: replicate to RGB, full alpha.
            let mut out = Vec::with_capacity(pixel_count * 4);
            for &lum in &image.pixels {
                out.extend_from_slice(&[lum, lum, lum, 255]);
            }
            out.resize(pixel_count * 4, 255);
            out
        }

        unknown => {
            tracing::error!(
                "[GLTF WARN] Unknown pixel format {unknown:?} on image {idx} in '{file_path}'. \
                 Falling back to RGBA8 with clamped copy."
            );
            let expected = pixel_count * 4;
            // Opaque black canvas — copy whatever bytes we have.
            let mut out = vec![0u8; expected];
            // Set alpha channel of every pixel to 255 (opaque).
            for px in 0..pixel_count {
                out[px * 4 + 3] = 255;
            }
            let copy_len = image.pixels.len().min(expected);
            out[..copy_len].copy_from_slice(&image.pixels[..copy_len]);
            out
        }
    }
}

// ============================================================================
//  Free helpers — flat normal generation
// ============================================================================

/// Compute per-triangle flat normals and assign them to each vertex in the
/// triangle.  Vertices must already be in expanded (non-indexed) form and the
/// primitive mode must be `Triangles` (guaranteed by the caller).
/// glTF joint weights must form a partition of unity (sum = 1.0): the skinning
/// shader computes `Σ wᵢ·Mᵢ` WITHOUT renormalizing (shader.wgsl). Exporters and
/// quantized `KHR_mesh_quantization` weights frequently emit sums slightly ≠ 1
/// (e.g. 0.998), which scales the skin matrix and distorts the mesh. Normalize
/// whenever there is any weight; leave an all-zero weight (a non-skinned vertex)
/// untouched so the shader's `sum > 0` guard correctly keeps it unskinned.
fn normalize_skin_weights(w: [f32; 4]) -> [f32; 4] {
    let sum = w[0] + w[1] + w[2] + w[3];
    if sum > 1e-5 {
        [w[0] / sum, w[1] / sum, w[2] / sum, w[3] / sum]
    } else {
        w
    }
}

fn compute_flat_normals(vertices: &mut [Vertex]) {
    for tri in vertices.chunks_exact_mut(3) {
        let v0 = Vec3::from(tri[0].position);
        let v1 = Vec3::from(tri[1].position);
        let v2 = Vec3::from(tri[2].position);

        let edge1 = v1 - v0;
        let edge2 = v2 - v0;
        let cross = edge1.cross(edge2);

        let normal = if cross.length_squared() > 1e-10 {
            cross.normalize()
        } else {
            Vec3::Y // degenerate triangle → point up
        };

        let n = [normal.x, normal.y, normal.z];
        tri[0].normal = n;
        tri[1].normal = n;
        tri[2].normal = n;
    }
}

// ============================================================================
//  Free helpers — material building
// ============================================================================

/// A GPU-resident glTF image.  Holds the [`wgpu::Texture`] alongside its view so
/// the texture outlives every material bind group that references the view.
struct GpuImage {
    // Kept alive so views remain valid; not read directly.
    #[allow(dead_code)]
    texture: wgpu::Texture,
    view: wgpu::TextureView,
}

/// Decide, per image index, whether it must be uploaded as sRGB.
///
/// Base-colour and emissive textures are colour data (sRGB); normal,
/// metallic-roughness and occlusion textures are linear data and must NOT be
/// gamma-decoded.  An image used as a colour map anywhere wins the sRGB vote.
fn classify_gltf_image_srgb(document: &gltf::Document, num_images: usize) -> Vec<bool> {
    let mut is_srgb = vec![false; num_images];
    let mut mark = |idx: usize| {
        if idx < is_srgb.len() {
            is_srgb[idx] = true;
        }
    };
    for material in document.materials() {
        let pbr = material.pbr_metallic_roughness();
        if let Some(ti) = pbr.base_color_texture() {
            mark(ti.texture().source().index());
        }
        if let Some(ti) = material.emissive_texture() {
            mark(ti.texture().source().index());
        }
    }
    is_srgb
}

/// Upload every glTF image to the GPU with the correct colour space, returning
/// index-aligned [`GpuImage`]s.
fn upload_gltf_images(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    file_path: &str,
    images: &[gltf::image::Data],
    srgb_flags: &[bool],
) -> Vec<GpuImage> {
    let mut out = Vec::with_capacity(images.len());

    for (i, image) in images.iter().enumerate() {
        let (width, height) = (image.width, image.height);
        let rgba: Vec<u8> = convert_image_to_rgba8(image, i, file_path);

        let texture_size = wgpu::Extent3d {
            width,
            height,
            depth_or_array_layers: 1,
        };

        let format = if srgb_flags.get(i).copied().unwrap_or(true) {
            wgpu::TextureFormat::Rgba8UnormSrgb
        } else {
            wgpu::TextureFormat::Rgba8Unorm
        };

        let texture = device.create_texture(&wgpu::TextureDescriptor {
            size: texture_size,
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format,
            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
            label: Some(&format!("{file_path}_tex_{i}")),
            view_formats: &[],
        });

        queue.write_texture(
            wgpu::TexelCopyTextureInfo {
                texture: &texture,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            &rgba,
            wgpu::TexelCopyBufferLayout {
                offset: 0,
                bytes_per_row: Some(4 * width),
                rows_per_image: Some(height),
            },
            texture_size,
        );

        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
        out.push(GpuImage { texture, view });
    }

    out
}

/// glTF sampler settings resolved to wgpu enums. Hashable so identical
/// configurations across materials share a single `wgpu::Sampler`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
struct SamplerKey {
    wrap_u: wgpu::AddressMode,
    wrap_v: wgpu::AddressMode,
    mag: wgpu::FilterMode,
    min: wgpu::FilterMode,
}

impl SamplerKey {
    /// glTF default when a texture references no sampler: repeat + linear.
    const DEFAULT: SamplerKey = SamplerKey {
        wrap_u: wgpu::AddressMode::Repeat,
        wrap_v: wgpu::AddressMode::Repeat,
        mag: wgpu::FilterMode::Linear,
        min: wgpu::FilterMode::Linear,
    };

    fn from_gltf(s: &gltf::texture::Sampler) -> SamplerKey {
        SamplerKey {
            wrap_u: wrap_to_wgpu(s.wrap_s()),
            wrap_v: wrap_to_wgpu(s.wrap_t()),
            mag: mag_to_wgpu(s.mag_filter()),
            min: min_to_wgpu(s.min_filter()),
        }
    }
}

fn wrap_to_wgpu(m: gltf::texture::WrappingMode) -> wgpu::AddressMode {
    use gltf::texture::WrappingMode;
    match m {
        WrappingMode::ClampToEdge => wgpu::AddressMode::ClampToEdge,
        WrappingMode::MirroredRepeat => wgpu::AddressMode::MirrorRepeat,
        WrappingMode::Repeat => wgpu::AddressMode::Repeat,
    }
}

fn mag_to_wgpu(f: Option<gltf::texture::MagFilter>) -> wgpu::FilterMode {
    match f {
        Some(gltf::texture::MagFilter::Nearest) => wgpu::FilterMode::Nearest,
        _ => wgpu::FilterMode::Linear,
    }
}

fn min_to_wgpu(f: Option<gltf::texture::MinFilter>) -> wgpu::FilterMode {
    use gltf::texture::MinFilter;
    match f {
        Some(MinFilter::Nearest)
        | Some(MinFilter::NearestMipmapNearest)
        | Some(MinFilter::NearestMipmapLinear) => wgpu::FilterMode::Nearest,
        _ => wgpu::FilterMode::Linear,
    }
}

fn create_gltf_sampler(device: &wgpu::Device, key: SamplerKey) -> wgpu::Sampler {
    device.create_sampler(&wgpu::SamplerDescriptor {
        label: Some("gltf_material_sampler"),
        address_mode_u: key.wrap_u,
        address_mode_v: key.wrap_v,
        address_mode_w: wgpu::AddressMode::Repeat,
        mag_filter: key.mag,
        min_filter: key.min,
        mipmap_filter: wgpu::MipmapFilterMode::Nearest, // single mip level
        ..Default::default()
    })
}

/// Resolve which sampler configuration a material's maps should use.
///
/// The material bind group carries a single shared sampler (the g-buffer samples
/// every map through one `s_diffuse`), so we honour the sampler of the first
/// defined map in priority order (base → normal → MR → emissive → AO). Real
/// glTF exporters assign one sampler per material, so this matches the asset; a
/// material whose maps reference *divergent* samplers (rare) uses the first.
fn material_sampler_key(material: &gltf::Material) -> SamplerKey {
    let pbr = material.pbr_metallic_roughness();
    let tex = pbr
        .base_color_texture()
        .map(|t| t.texture())
        .or_else(|| material.normal_texture().map(|t| t.texture()))
        .or_else(|| pbr.metallic_roughness_texture().map(|t| t.texture()))
        .or_else(|| material.emissive_texture().map(|t| t.texture()))
        .or_else(|| material.occlusion_texture().map(|t| t.texture()));
    match tex {
        Some(t) => SamplerKey::from_gltf(&t.sampler()),
        None => SamplerKey::DEFAULT,
    }
}

/// Apply `KHR_materials_emissive_strength` to the emissive factor.
///
/// The extension multiplies the emissive colour by a scalar (default 1.0) to
/// express HDR glow. The g-buffer stores emissive additively (LDR approximation),
/// so strengths > 1 brighten emission up to the render-target range; full unlit
/// HDR bloom still needs a dedicated emissive target (tracked in the ROADMAP).
fn emissive_with_strength(factor: [f32; 3], strength: Option<f32>) -> [f32; 3] {
    let s = strength.unwrap_or(1.0);
    [factor[0] * s, factor[1] * s, factor[2] * s]
}

/// Resolve the `KHR_texture_transform` (UV offset / rotation / scale) for a
/// material, from its base-colour texture (identity when absent).
///
/// The g-buffer applies a single UV transform per material to every map, so we
/// take the base-colour map's transform — real assets that tile/offset a
/// material apply the same transform across its maps. A per-map transform on a
/// non-base map, or a `texCoord` set override, is not represented (single UV
/// channel); such rare cases fall back to the base-colour transform.
fn material_uv_transform(material: &gltf::Material) -> crate::gpu_types::UvTransform {
    match material
        .pbr_metallic_roughness()
        .base_color_texture()
        .and_then(|ti| ti.texture_transform())
    {
        Some(tt) => crate::gpu_types::UvTransform {
            offset: tt.offset(),
            rotation: tt.rotation(),
            scale: tt.scale(),
        },
        None => crate::gpu_types::UvTransform::default(),
    }
}

fn build_gltf_materials(
    device: &wgpu::Device,
    layout: &wgpu::BindGroupLayout,
    document: &gltf::Document,
    gpu_images: &[GpuImage],
    defaults: &crate::asset::MaterialDefaults,
    default_tbind: &Arc<wgpu::BindGroup>,
) -> Vec<Material> {
    // One wgpu sampler per distinct glTF sampler configuration used by the
    // document's materials — honours wrap + filter settings instead of forcing
    // repeat/linear. Identical configurations are shared via the cache key.
    let mut sampler_cache: std::collections::HashMap<SamplerKey, wgpu::Sampler> =
        std::collections::HashMap::new();
    for material in document.materials() {
        let key = material_sampler_key(&material);
        sampler_cache
            .entry(key)
            .or_insert_with(|| create_gltf_sampler(device, key));
    }
    // Textureless materials still need *a* sampler for their bind group.
    sampler_cache
        .entry(SamplerKey::DEFAULT)
        .or_insert_with(|| create_gltf_sampler(device, SamplerKey::DEFAULT));

    document
        .materials()
        .map(|material| {
            let pbr = material.pbr_metallic_roughness();
            let base_color = pbr.base_color_factor();

            // Shared sampler honouring this material's glTF wrap/filter settings.
            let mat_sampler = &sampler_cache[&material_sampler_key(&material)];

            // Resolve each map's image view (or the neutral default).
            let base_view = pbr
                .base_color_texture()
                .and_then(|ti| gpu_images.get(ti.texture().source().index()))
                .map(|img| &img.view)
                .unwrap_or(&defaults.white_view);
            let normal_view = material
                .normal_texture()
                .and_then(|nt| gpu_images.get(nt.texture().source().index()))
                .map(|img| &img.view)
                .unwrap_or(&defaults.flat_normal_view);
            let mr_view = pbr
                .metallic_roughness_texture()
                .and_then(|ti| gpu_images.get(ti.texture().source().index()))
                .map(|img| &img.view)
                .unwrap_or(&defaults.white_view);
            let emissive_view = material
                .emissive_texture()
                .and_then(|ti| gpu_images.get(ti.texture().source().index()))
                .map(|img| &img.view)
                .unwrap_or(&defaults.white_view);
            let ao_view = material
                .occlusion_texture()
                .and_then(|ot| gpu_images.get(ot.texture().source().index()))
                .map(|img| &img.view)
                .unwrap_or(&defaults.white_view);

            let has_base = pbr.base_color_texture().is_some();
            let has_any_map = has_base
                || material.normal_texture().is_some()
                || pbr.metallic_roughness_texture().is_some()
                || material.emissive_texture().is_some()
                || material.occlusion_texture().is_some();

            // Per-material scalar params (glTF factors that modulate the maps).
            // KHR_materials_emissive_strength scales the emissive factor for HDR
            // glow; folded into the factor here (LDR-additive in the g-buffer).
            let emissive =
                emissive_with_strength(material.emissive_factor(), material.emissive_strength());
            let normal_scale = material.normal_texture().map(|nt| nt.scale()).unwrap_or(1.0);
            let occlusion_strength = material
                .occlusion_texture()
                .map(|ot| ot.strength())
                .unwrap_or(1.0);
            let uv_transform = material_uv_transform(&material);
            let params = crate::gpu_types::MaterialParams::new(
                emissive,
                normal_scale,
                occlusion_strength,
                uv_transform,
            );
            let is_default_params = emissive == [0.0, 0.0, 0.0]
                && normal_scale == 1.0
                && occlusion_strength == 1.0
                && uv_transform.is_identity();

            // Fast path: no textures and neutral params → reuse the shared white
            // fallback bind group. Otherwise assemble a dedicated one.
            let bind_group = if !has_any_map && is_default_params {
                default_tbind.clone()
            } else {
                let params_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
                    label: Some(&format!(
                        "gltf_material_params_{}",
                        material.index().unwrap_or(usize::MAX)
                    )),
                    contents: bytemuck::cast_slice(&[params]),
                    usage: wgpu::BufferUsages::UNIFORM,
                });
                super::AssetManager::assemble_material_bind_group(
                    device,
                    layout,
                    base_view,
                    mat_sampler,
                    normal_view,
                    mr_view,
                    emissive_view,
                    ao_view,
                    &params_buffer,
                    &format!("gltf_material_{}", material.index().unwrap_or(usize::MAX)),
                )
            };

            let mut mat = Material::new(bind_group);
            if has_base {
                mat.texture_source = Some(format!(
                    "gltf_tex_base_{}",
                    material.index().unwrap_or(usize::MAX)
                ));
            }

            let mat_name = material.name().unwrap_or("").to_lowercase();
            let is_glass = mat_name.contains("glass");

            let alpha = if is_glass {
                0.25 // Glass bulb should be translucent and glowing!
            } else if material.alpha_mode() == gltf::material::AlphaMode::Opaque {
                1.0
            } else {
                base_color[3]
            };

            tracing::debug!("GLTF LOAD MAT: name={:?}, alpha_mode={:?}, alpha_factor={}, base_color={:?}, double_sided={}",
                material.name(), material.alpha_mode(), alpha, base_color, material.double_sided());

            mat.albedo = gizmo_math::Vec4::new(base_color[0], base_color[1], base_color[2], alpha);
            mat.metallic = pbr.metallic_factor();
            mat.roughness = pbr.roughness_factor();

            mat.is_transparent = material.alpha_mode() != gltf::material::AlphaMode::Opaque || alpha < 0.99 || is_glass;
            mat.is_double_sided = material.double_sided();

            mat
        })
        .collect()
}

// ============================================================================
//  Free helpers — animation parsing
// ============================================================================

/// Build a keyframe list from a glTF channel's raw outputs, preserving cubic tangents.
///
/// For `CUBICSPLINE` the raw output stores three entries per sample —
/// `[inTangent, value, outTangent]` — so we pick the value (offset 1) and keep both
/// tangents so the sampler can do true cubic-Hermite instead of downgrading to linear.
/// For Linear/Step there is one entry per sample and no tangents.
fn build_keyframes<V, T>(
    times: &[f32],
    vals: &[V],
    cubic: bool,
    conv: impl Fn(&V) -> T,
) -> Vec<Keyframe<T>> {
    let (stride, off) = if cubic { (3usize, 1usize) } else { (1usize, 0usize) };
    times
        .iter()
        .enumerate()
        .filter_map(|(i, &t)| {
            let base = i * stride;
            let value = conv(vals.get(base + off)?);
            if cubic {
                match (vals.get(base), vals.get(base + 2)) {
                    (Some(a), Some(b)) => {
                        Some(Keyframe::with_tangents(t, value, conv(a), conv(b)))
                    }
                    // Malformed cubic block → keep the value, sampler falls back to lerp.
                    _ => Some(Keyframe::new(t, value)),
                }
            } else {
                Some(Keyframe::new(t, value))
            }
        })
        .collect()
}

fn parse_animations(
    document: &gltf::Document,
    buffers: &[gltf::buffer::Data],
) -> Vec<AnimationClip> {
    document
        .animations()
        .map(|anim| {
            let mut translations = Vec::new();
            let mut rotations = Vec::new();
            let mut scales = Vec::new();

            for channel in anim.channels() {
                let target_node = channel.target().node().index();
                let target_node_name = channel.target().node().name().map(str::to_owned);
                let reader = channel.reader(|b| Some(&buffers[b.index()]));

                let times: Vec<f32> = match reader.read_inputs() {
                    Some(it) => it.collect(),
                    None => continue,
                };

                let interp = match channel.sampler().interpolation() {
                    gltf::animation::Interpolation::Step => {
                        gizmo_animation::skeletal::InterpolationMode::Step
                    }
                    gltf::animation::Interpolation::CubicSpline => {
                        gizmo_animation::skeletal::InterpolationMode::CubicSpline
                    }
                    _ => gizmo_animation::skeletal::InterpolationMode::Linear,
                };

                let outputs = match reader.read_outputs() {
                    Some(o) => o,
                    None => continue,
                };

                match outputs {
                    gltf::animation::util::ReadOutputs::Translations(tr) => {
                        let vals: Vec<[f32; 3]> = tr.collect();
                        let cubic = matches!(interp, gizmo_animation::skeletal::InterpolationMode::CubicSpline);
                        let keyframes = build_keyframes(&times, &vals, cubic, |v| Vec3::new(v[0], v[1], v[2]));
                        translations.push(Track {
                            target_node,
                            target_node_name: target_node_name.clone(),
                            interpolation: interp,
                            keyframes,
                        });
                    }
                    gltf::animation::util::ReadOutputs::Rotations(rt) => {
                        let vals: Vec<[f32; 4]> = rt.into_f32().collect();
                        let cubic = matches!(interp, gizmo_animation::skeletal::InterpolationMode::CubicSpline);
                        let keyframes = build_keyframes(&times, &vals, cubic, |v| Quat::from_xyzw(v[0], v[1], v[2], v[3]));
                        rotations.push(Track {
                            target_node,
                            target_node_name: target_node_name.clone(),
                            interpolation: interp,
                            keyframes,
                        });
                    }
                    gltf::animation::util::ReadOutputs::Scales(sc) => {
                        let vals: Vec<[f32; 3]> = sc.collect();
                        let cubic = matches!(interp, gizmo_animation::skeletal::InterpolationMode::CubicSpline);
                        let keyframes = build_keyframes(&times, &vals, cubic, |v| Vec3::new(v[0], v[1], v[2]));
                        scales.push(Track {
                            target_node,
                            target_node_name,
                            interpolation: interp,
                            keyframes,
                        });
                    }
                    _ => {} // Morph targets and other outputs are intentionally ignored.
                }
            }

            // Duration = time of the last keyframe across all tracks.
            let d_tr = translations
                .iter()
                .filter_map(|t| t.keyframes.last().map(|k| k.time))
                .fold(0.0f32, f32::max);
            let d_rot = rotations
                .iter()
                .filter_map(|t| t.keyframes.last().map(|k| k.time))
                .fold(0.0f32, f32::max);
            let d_scl = scales
                .iter()
                .filter_map(|t| t.keyframes.last().map(|k| k.time))
                .fold(0.0f32, f32::max);
            let duration = d_tr.max(d_rot).max(d_scl);

            AnimationClip {
                name: anim.name().unwrap_or("unnamed").to_string(),
                duration,
                translations,
                rotations,
                scales,
            }
        })
        .collect()
}

// ============================================================================
//  Free helpers — skeleton parsing
// ============================================================================

fn parse_skeletons(
    document: &gltf::Document,
    buffers: &[gltf::buffer::Data],
    node_parents: &std::collections::HashMap<usize, usize>,
    nodes_by_index: &[gltf::Node],
) -> Vec<SkeletonHierarchy> {
    document
        .skins()
        .map(|skin| {
            let reader = skin.reader(|b| Some(&buffers[b.index()]));

            let identity_mat = [
                [1.0, 0., 0., 0.],
                [0., 1., 0., 0.],
                [0., 0., 1., 0.],
                [0., 0., 0., 1.],
            ];
            let ibm: Vec<[[f32; 4]; 4]> = reader
                .read_inverse_bind_matrices()
                .map(|v| v.collect())
                .unwrap_or_else(|| vec![identity_mat; skin.joints().count()]);

            // Map node_index → bone_index for O(1) parent lookups.
            let node_to_bone: std::collections::HashMap<usize, usize> = skin
                .joints()
                .enumerate()
                .map(|(bone_idx, node)| (node.index(), bone_idx))
                .collect();

            let joints: Vec<SkeletonJoint> = skin
                .joints()
                .enumerate()
                .map(|(bone_idx, joint_node)| {
                    // Fall back to IDENTITY when the glTF file has fewer
                    // inverse_bind_matrices than joints (malformed/truncated data),
                    // rather than panicking on an out-of-bounds index.
                    let inverse_bind_matrix = ibm
                        .get(bone_idx)
                        .map(gizmo_math::Mat4::from_cols_array_2d)
                        .unwrap_or(gizmo_math::Mat4::IDENTITY);

                    let parent_index = node_parents
                        .get(&joint_node.index())
                        .and_then(|p| node_to_bone.get(p).copied());

                    let (t, r, s) = joint_node.transform().decomposed();
                    let bind_translation = Vec3::new(t[0], t[1], t[2]);
                    let bind_rotation = Quat::from_array(r);
                    let bind_scale = Vec3::new(s[0], s[1], s[2]);

                    let local_bind_transform = gizmo_math::Mat4::from_translation(bind_translation)
                        * gizmo_math::Mat4::from_quat(bind_rotation)
                        * gizmo_math::Mat4::from_scale(bind_scale);

                    SkeletonJoint {
                        name: joint_node.name().unwrap_or("bone").to_string(),
                        node_index: joint_node.index(),
                        inverse_bind_matrix,
                        parent_index,
                        local_bind_transform,
                        bind_translation,
                        bind_rotation,
                        bind_scale,
                    }
                })
                .collect();

            // Compute the combined transform of all non-joint ancestor nodes
            // (the "armature" transform).  `calculate_global_matrices` relies
            // on this so that joint matrices are identity in the bind pose.
            //
            // We use `nodes_by_index` for O(1) node lookup instead of O(n) `.nth()`.
            let root_transform =
                compute_armature_root_transform(&skin, node_parents, &node_to_bone, nodes_by_index);

            SkeletonHierarchy {
                joints,
                root_transform,
            }
        })
        .collect()
}

/// Walk the parent chain of the first joint upward until we hit a joint or the
/// root, accumulating the transforms of all non-joint ancestors.
fn compute_armature_root_transform(
    skin: &gltf::Skin,
    node_parents: &std::collections::HashMap<usize, usize>,
    node_to_bone: &std::collections::HashMap<usize, usize>,
    nodes_by_index: &[gltf::Node],
) -> gizmo_math::Mat4 {
    let mut root_transform = gizmo_math::Mat4::IDENTITY;

    let first_joint = match skin.joints().next() {
        Some(j) => j,
        None => return root_transform,
    };

    let mut current_idx = first_joint.index();
    let mut ancestor_transforms: Vec<gizmo_math::Mat4> = Vec::new();

    while let Some(&parent_idx) = node_parents.get(&current_idx) {
        // Stop when we reach another bone — its transform is already baked
        // into the skeleton hierarchy.
        if node_to_bone.contains_key(&parent_idx) {
            break;
        }

        if let Some(parent_node) = nodes_by_index.get(parent_idx) {
            let (t, r, s) = parent_node.transform().decomposed();
            let mat = gizmo_math::Mat4::from_translation(Vec3::new(t[0], t[1], t[2]))
                * gizmo_math::Mat4::from_quat(Quat::from_array(r))
                * gizmo_math::Mat4::from_scale(Vec3::new(s[0], s[1], s[2]));
            ancestor_transforms.push(mat);
        }

        current_idx = parent_idx;
    }

    // Apply transforms from root downward (reverse of collection order).
    for mat in ancestor_transforms.into_iter().rev() {
        root_transform *= mat;
    }

    root_transform
}

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

    fn wsum(w: [f32; 4]) -> f32 {
        w[0] + w[1] + w[2] + w[3]
    }

    #[test]
    fn skin_weights_normalize_to_unity() {
        // Sum < 1 → ölçeklenip 1'e çıkar.
        let w = normalize_skin_weights([0.25, 0.25, 0.0, 0.0]);
        assert!((wsum(w) - 1.0).abs() < 1e-6, "sum={}", wsum(w));
        assert!((w[0] - 0.5).abs() < 1e-6 && (w[1] - 0.5).abs() < 1e-6);

        // Sum > 1 → küçültülüp 1'e iner, oranlar korunur.
        let w = normalize_skin_weights([0.3, 0.3, 0.3, 0.3]);
        assert!((wsum(w) - 1.0).abs() < 1e-6);
        for c in w {
            assert!((c - 0.25).abs() < 1e-6);
        }

        // Zaten 1 → değişmez.
        let w = normalize_skin_weights([0.5, 0.5, 0.0, 0.0]);
        assert!((wsum(w) - 1.0).abs() < 1e-6);
    }

    #[test]
    fn skin_weights_all_zero_preserved() {
        // Skinless vertex: [0,0,0,0] DOKUNULMAZ ki shader'ın `sum > 0` guard'ı
        // onu doğru şekilde unskinned tutsun (yoksa skinless mesh bozulurdu).
        assert_eq!(normalize_skin_weights([0.0; 4]), [0.0; 4]);
    }

    #[test]
    fn skin_weights_arbitrary_sum_to_one() {
        for w in [[0.1, 0.2, 0.3, 0.05], [0.9, 0.05, 0.02, 0.0], [2.0, 1.0, 0.5, 0.5]] {
            let n = normalize_skin_weights(w);
            assert!((wsum(n) - 1.0).abs() < 1e-5, "input {w:?} → {n:?} sum {}", wsum(n));
        }
    }

    #[test]
    fn emissive_strength_scales_factor() {
        // Absent extension → factor unchanged.
        assert_eq!(emissive_with_strength([1.0, 0.5, 0.0], None), [1.0, 0.5, 0.0]);
        // Strength multiplies each channel (HDR glow).
        assert_eq!(emissive_with_strength([1.0, 0.5, 0.25], Some(4.0)), [4.0, 2.0, 1.0]);
        // Zero strength kills emission.
        assert_eq!(emissive_with_strength([1.0, 1.0, 1.0], Some(0.0)), [0.0, 0.0, 0.0]);
    }

    #[test]
    fn sampler_filter_and_wrap_converters() {
        use gltf::texture::{MagFilter, MinFilter, WrappingMode};
        assert_eq!(wrap_to_wgpu(WrappingMode::ClampToEdge), wgpu::AddressMode::ClampToEdge);
        assert_eq!(wrap_to_wgpu(WrappingMode::MirroredRepeat), wgpu::AddressMode::MirrorRepeat);
        assert_eq!(wrap_to_wgpu(WrappingMode::Repeat), wgpu::AddressMode::Repeat);

        assert_eq!(mag_to_wgpu(Some(MagFilter::Nearest)), wgpu::FilterMode::Nearest);
        assert_eq!(mag_to_wgpu(Some(MagFilter::Linear)), wgpu::FilterMode::Linear);
        assert_eq!(mag_to_wgpu(None), wgpu::FilterMode::Linear);

        assert_eq!(min_to_wgpu(Some(MinFilter::Nearest)), wgpu::FilterMode::Nearest);
        assert_eq!(min_to_wgpu(Some(MinFilter::NearestMipmapLinear)), wgpu::FilterMode::Nearest);
        assert_eq!(min_to_wgpu(Some(MinFilter::Linear)), wgpu::FilterMode::Linear);
        assert_eq!(min_to_wgpu(Some(MinFilter::LinearMipmapLinear)), wgpu::FilterMode::Linear);
        assert_eq!(min_to_wgpu(None), wgpu::FilterMode::Linear);
    }

    #[test]
    fn gltf_material_sampler_and_emissive_strength_parsed() {
        // Minimal glTF: a material whose base-colour texture references a sampler
        // with mixed wrap/filter modes, plus KHR_materials_emissive_strength = 4.
        let json = r#"{
          "asset": { "version": "2.0" },
          "extensionsUsed": ["KHR_materials_emissive_strength"],
          "samplers": [
            { "wrapS": 33071, "wrapT": 10497, "magFilter": 9728, "minFilter": 9729 }
          ],
          "images": [ { "uri": "dummy.png" } ],
          "textures": [ { "sampler": 0, "source": 0 } ],
          "materials": [
            {
              "pbrMetallicRoughness": { "baseColorTexture": { "index": 0 } },
              "emissiveFactor": [1.0, 0.5, 0.25],
              "extensions": { "KHR_materials_emissive_strength": { "emissiveStrength": 4.0 } }
            }
          ]
        }"#;
        let doc = gltf::Gltf::from_slice(json.as_bytes()).expect("parse minimal glTF");
        let material = doc.materials().next().expect("one material");

        // Sampler settings honoured (not the old hardcoded repeat/linear).
        let key = material_sampler_key(&material);
        assert_eq!(key.wrap_u, wgpu::AddressMode::ClampToEdge);
        assert_eq!(key.wrap_v, wgpu::AddressMode::Repeat);
        assert_eq!(key.mag, wgpu::FilterMode::Nearest);
        assert_eq!(key.min, wgpu::FilterMode::Linear);

        // KHR_materials_emissive_strength scales the emissive factor.
        assert_eq!(material.emissive_strength(), Some(4.0));
        let emissive =
            emissive_with_strength(material.emissive_factor(), material.emissive_strength());
        assert_eq!(emissive, [4.0, 2.0, 1.0]);
    }

    #[test]
    fn material_without_textures_uses_default_sampler_key() {
        let json = r#"{
          "asset": { "version": "2.0" },
          "materials": [ { "emissiveFactor": [0.0, 0.0, 0.0] } ]
        }"#;
        let doc = gltf::Gltf::from_slice(json.as_bytes()).expect("parse");
        let material = doc.materials().next().expect("one material");
        assert_eq!(material_sampler_key(&material), SamplerKey::DEFAULT);
        // Absent extension → no strength (folds to factor unchanged).
        assert_eq!(material.emissive_strength(), None);
    }

    #[test]
    fn gltf_texture_transform_parsed_and_packed() {
        // KHR_texture_transform on the base-colour texture: offset/rotation/scale.
        let json = r#"{
          "asset": { "version": "2.0" },
          "extensionsUsed": ["KHR_texture_transform"],
          "images": [ { "uri": "dummy.png" } ],
          "samplers": [ {} ],
          "textures": [ { "sampler": 0, "source": 0 } ],
          "materials": [
            {
              "pbrMetallicRoughness": {
                "baseColorTexture": {
                  "index": 0,
                  "extensions": {
                    "KHR_texture_transform": {
                      "offset": [0.1, 0.2],
                      "rotation": 1.5,
                      "scale": [2.0, 3.0]
                    }
                  }
                }
              }
            }
          ]
        }"#;
        let doc = gltf::Gltf::from_slice(json.as_bytes()).expect("parse");
        let material = doc.materials().next().expect("one material");

        let uv = material_uv_transform(&material);
        assert_eq!(uv.offset, [0.1, 0.2]);
        assert!((uv.rotation - 1.5).abs() < 1e-6);
        assert_eq!(uv.scale, [2.0, 3.0]);
        assert!(!uv.is_identity());

        // Packed into MaterialParams in the documented slots:
        // occlusion_uv_rot_offset = [occlusion, rotation, offset.x, offset.y].
        let params = crate::gpu_types::MaterialParams::new([0.0; 3], 1.0, 1.0, uv);
        assert_eq!(params.occlusion_uv_rot_offset, [1.0, 1.5, 0.1, 0.2]);
        assert_eq!(params.uv_scale, [2.0, 3.0, 0.0, 0.0]);
    }

    #[test]
    fn material_without_texture_transform_is_identity() {
        let json = r#"{
          "asset": { "version": "2.0" },
          "images": [ { "uri": "dummy.png" } ],
          "samplers": [ {} ],
          "textures": [ { "sampler": 0, "source": 0 } ],
          "materials": [ { "pbrMetallicRoughness": { "baseColorTexture": { "index": 0 } } } ]
        }"#;
        let doc = gltf::Gltf::from_slice(json.as_bytes()).expect("parse");
        let material = doc.materials().next().expect("one material");
        assert!(material_uv_transform(&material).is_identity());
        // Default MaterialParams carries an identity UV (unit scale, zero offset/rot).
        let d = crate::gpu_types::MaterialParams::default();
        assert_eq!(d.uv_scale, [1.0, 1.0, 0.0, 0.0]);
        assert_eq!(d.occlusion_uv_rot_offset, [1.0, 0.0, 0.0, 0.0]);
    }
}