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
// SPDX-FileCopyrightText: 2023 Joshua Goins <josh@redstrate.com>
// SPDX-License-Identifier: GPL-3.0-or-later

#![allow(clippy::unnecessary_fallible_conversions)] // This wrongly trips on binrw code

use std::io::{Cursor, Seek, SeekFrom};
use std::mem::size_of;

use binrw::BinRead;
use binrw::BinReaderExt;
use binrw::{binrw, BinWrite, BinWriterExt};

use crate::common_file_operations::{read_bool_from, write_bool_as};
use crate::model_vertex_declarations::{
    vertex_element_parser, vertex_element_writer, VertexDeclaration, VertexType, VertexUsage,
    VERTEX_ELEMENT_SIZE,
};
use crate::{ByteBuffer, ByteSpan};

pub const NUM_VERTICES: u32 = 17;

#[binrw]
#[derive(Debug, Clone, PartialEq)]
#[brw(little)]
pub struct ModelFileHeader {
    pub version: u32,

    pub stack_size: u32,
    pub runtime_size: u32,

    pub vertex_declaration_count: u16,
    pub material_count: u16,

    pub vertex_offsets: [u32; 3],
    pub index_offsets: [u32; 3],
    pub vertex_buffer_size: [u32; 3],
    pub index_buffer_size: [u32; 3],

    pub lod_count: u8,

    #[br(map = read_bool_from::<u8>)]
    #[bw(map = write_bool_as::<u8>)]
    pub index_buffer_streaming_enabled: bool,
    #[br(map = read_bool_from::<u8>)]
    #[bw(map = write_bool_as::<u8>)]
    #[brw(pad_after = 1)]
    pub has_edge_geometry: bool,
}

#[binrw]
#[brw(repr = u8)]
#[derive(Debug, Clone, PartialEq)]
enum ModelFlags1 {
    DustOcclusionEnabled = 0x80,
    SnowOcclusionEnabled = 0x40,
    RainOcclusionEnabled = 0x20,
    Unknown1 = 0x10,
    LightingReflectionEnabled = 0x08,
    WavingAnimationDisabled = 0x04,
    LightShadowDisabled = 0x02,
    ShadowDisabled = 0x01,
}

#[binrw]
#[brw(repr = u8)]
#[derive(Debug, Clone, PartialEq)]
enum ModelFlags2 {
    None = 0x0,
    Unknown2 = 0x80,
    BgUvScrollEnabled = 0x40,
    EnableForceNonResident = 0x20,
    ExtraLodEnabled = 0x10,
    ShadowMaskEnabled = 0x08,
    ForceLodRangeEnabled = 0x04,
    EdgeGeometryEnabled = 0x02,
    Unknown3 = 0x01,
}

#[binrw]
#[derive(Debug, Clone, PartialEq)]
#[br(import { vertex_declaration_count: u16 })]
#[allow(dead_code)]
pub struct ModelHeader {
    #[br(args(vertex_declaration_count), parse_with = vertex_element_parser)]
    #[bw(write_with = vertex_element_writer)]
    pub vertex_declarations: Vec<VertexDeclaration>,

    #[brw(pad_after = 2)]
    string_count: u16,
    string_size: u32,

    #[br(count = string_size)]
    strings: Vec<u8>,

    radius: f32,

    mesh_count: u16,
    attribute_count: u16,
    submesh_count: u16,
    material_count: u16,
    bone_count: u16,
    bone_table_count: u16,
    shape_count: u16,
    shape_mesh_count: u16,
    shape_value_count: u16,

    lod_count: u8,

    flags1: ModelFlags1,

    element_id_count: u16,
    terrain_shadow_mesh_count: u8,

    flags2: ModelFlags2,

    model_clip_out_of_distance: f32,
    shadow_clip_out_of_distance: f32,

    unknown4: u16,

    terrain_shadow_submesh_count: u16,

    unknown5: u8,

    bg_change_material_index: u8,
    bg_crest_change_material_index: u8,

    unknown6: u8,
    unknown7: u16,
    unknown8: u16,
    #[brw(pad_after = 6)]
    unknown9: u16,
}

#[binrw]
#[derive(Debug, Clone, PartialEq)]
#[allow(dead_code)]
struct MeshLod {
    mesh_index: u16,
    mesh_count: u16,

    model_lod_range: f32,
    texture_lod_range: f32,

    water_mesh_index: u16,
    water_mesh_count: u16,

    shadow_mesh_index: u16,
    shadow_mesh_count: u16,

    terrain_shadow_mesh_count: u16,
    terrain_shadow_mesh_index: u16,

    vertical_fog_mesh_index: u16,
    vertical_fog_mesh_count: u16,

    // unused on win32 according to lumina devs
    edge_geometry_size: u32,
    edge_geometry_data_offset: u32,

    #[brw(pad_after = 4)]
    polygon_count: u32,

    vertex_buffer_size: u32,
    index_buffer_size: u32,
    vertex_data_offset: u32,
    index_data_offset: u32,
}

#[binrw]
#[derive(Debug, Clone, PartialEq)]
#[allow(dead_code)]
struct Mesh {
    #[brw(pad_after = 2)]
    vertex_count: u16,
    index_count: u32,

    material_index: u16,
    submesh_index: u16,
    submesh_count: u16,

    bone_table_index: u16,
    start_index: u32,

    vertex_buffer_offsets: [u32; 3],
    vertex_buffer_strides: [u8; 3],

    vertex_stream_count: u8,
}

#[binrw]
#[derive(Debug, Clone, PartialEq)]
#[allow(dead_code)]
struct Submesh {
    index_offset: u32,
    index_count: u32,

    attribute_index_mask: u32,

    bone_start_index: u16,
    bone_count: u16,
}

#[binrw]
#[derive(Debug, Clone, PartialEq)]
#[allow(dead_code)]
struct BoneTable {
    bone_indices: [u16; 64],

    #[brw(pad_after = 3)]
    bone_count: u8,
}

#[binrw]
#[derive(Debug, Clone, PartialEq)]
#[allow(dead_code)]
struct BoneTableV2 {
    #[br(pad_before = 2)]
    bone_count: u16,

    #[br(count = bone_count)]
    bone_indices: Vec<u16>,

    // align to 4 bytes
    // TODO: use br align_to?
    #[br(if(bone_count % 2 == 0))]
    padding: u16,
}

#[binrw]
#[derive(Debug, Clone, PartialEq)]
#[allow(dead_code)]
struct BoundingBox {
    min: [f32; 4],
    max: [f32; 4],
}

#[binrw]
#[derive(Debug, Clone, PartialEq)]
#[allow(dead_code)]
struct TerrainShadowMesh {
    index_count: u32,
    start_index: u32,
    vertex_buffer_offset: u32,
    vertex_count: u16,
    submesh_index: u16,
    submesh_count: u16,
    vertex_buffer_stride: u8,
    padding: u8,
}

#[binrw]
#[derive(Debug, Clone, PartialEq)]
#[allow(dead_code)]
struct TerrainShadowSubmesh {
    index_offset: u32,
    index_count: u32,
    unknown1: u16,
    unknown2: u16,
}

#[binrw]
#[derive(Debug, Clone, PartialEq)]
#[allow(dead_code)]
struct ShapeStruct {
    string_offset: u32,
    shape_mesh_start_index: [u16; 3],
    shape_mesh_count: [u16; 3],
}

#[binrw]
#[derive(Debug, Clone, PartialEq)]
#[allow(dead_code)]
struct ShapeMesh {
    mesh_index_offset: u32,
    shape_value_count: u32,
    shape_value_offset: u32,
}

#[binrw]
#[derive(Debug, Clone, PartialEq)]
#[allow(dead_code)]
struct ShapeValue {
    base_indices_index: u16,
    replacing_vertex_index: u16,
}

#[binrw]
#[derive(Debug, Clone, PartialEq)]
#[allow(dead_code)]
#[br(import {file_header: &ModelFileHeader})]
#[brw(little)]
struct ModelData {
    #[br(args { vertex_declaration_count: file_header.vertex_declaration_count })]
    header: ModelHeader,

    #[br(count = header.element_id_count)]
    element_ids: Vec<ElementId>,

    #[br(count = 3)]
    lods: Vec<MeshLod>,

    #[br(count = header.mesh_count)]
    meshes: Vec<Mesh>,

    #[br(count = header.attribute_count)]
    attribute_name_offsets: Vec<u32>,

    #[br(count = header.terrain_shadow_mesh_count)]
    terrain_shadow_meshes: Vec<TerrainShadowMesh>,

    #[br(count = header.submesh_count)]
    submeshes: Vec<Submesh>,

    #[br(count = header.terrain_shadow_submesh_count)]
    terrain_shadow_submeshes: Vec<TerrainShadowSubmesh>,

    #[br(count = header.material_count)]
    material_name_offsets: Vec<u32>,

    #[br(count = header.bone_count)]
    bone_name_offsets: Vec<u32>,

    #[br(count = header.bone_table_count)]
    #[br(if(file_header.version <= 0x1000005))]
    bone_tables: Vec<BoneTable>,

    #[br(count = header.bone_table_count)]
    #[br(if(file_header.version >= 0x1000006))]
    bone_tables_v2: Vec<BoneTableV2>,

    #[br(count = header.shape_count)]
    shapes: Vec<ShapeStruct>,

    #[br(count = header.shape_mesh_count)]
    shape_meshes: Vec<ShapeMesh>,

    #[br(count = header.shape_value_count)]
    shape_values: Vec<ShapeValue>,

    // TODO: try to unify these fields?
    #[br(if(file_header.version <= 0x1000005))]
    submesh_bone_map_size: u32,

    // hehe, Dawntrail made this u16 instead of u32. fun?
    #[br(if(file_header.version >= 0x1000006))]
    submesh_bone_map_size_v2: u16,

    #[br(count = if file_header.version >= 0x1000006 { (submesh_bone_map_size_v2 / 2) as u32 } else { submesh_bone_map_size / 2 } )]
    submesh_bone_map: Vec<u16>,

    padding_amount: u8,
    #[br(count = padding_amount)]
    unknown_padding: Vec<u8>,

    // TODO: these are still wrong on Dawntrail!
    bounding_box: BoundingBox,
    model_bounding_box: BoundingBox,
    water_bounding_box: BoundingBox,
    vertical_fog_bounding_box: BoundingBox,

    #[br(count = header.bone_count)]
    bone_bounding_boxes: Vec<BoundingBox>,
}

#[binrw]
#[derive(Debug, Clone, PartialEq)]
#[allow(dead_code)]
struct ElementId {
    element_id: u32,
    parent_bone_name: u32,
    translate: [f32; 3],
    rotate: [f32; 3],
}

#[derive(Clone, Copy, PartialEq)]
#[repr(C)]
pub struct Vertex {
    pub position: [f32; 3],
    pub uv0: [f32; 2],
    pub uv1: [f32; 2],
    pub normal: [f32; 3],
    pub bitangent: [f32; 4],
    //pub bitangent1: [f32; 4], // TODO: need to figure out what the heck this could be
    pub color: [f32; 4],

    pub bone_weight: [f32; 4],
    pub bone_id: [u8; 4],
}

impl Default for Vertex {
    fn default() -> Self {
        Self {
            position: [0.0; 3],
            uv0: [0.0; 2],
            uv1: [0.0; 2],
            normal: [0.0; 3],
            bitangent: [0.0; 4],
            color: [0.0; 4],
            bone_weight: [0.0; 4],
            bone_id: [0u8; 4],
        }
    }
}

#[derive(Clone, Copy)]
#[repr(C)]
pub struct NewShapeValue {
    pub base_index: u32,
    pub replacing_vertex: Vertex,
}

#[derive(Clone, Copy)]
#[repr(C)]
pub struct SubMesh {
    submesh_index: usize,
    pub index_count: u32,
    pub index_offset: u32,
}

#[derive(Clone)]
pub struct Shape {
    pub name: String,
    pub morphed_vertices: Vec<Vertex>,
}

/// Corresponds to a "Mesh" in an LOD
#[derive(Clone)]
pub struct Part {
    mesh_index: u16,
    pub vertices: Vec<Vertex>,
    pub indices: Vec<u16>,
    pub material_index: u16,
    pub submeshes: Vec<SubMesh>,
    pub shapes: Vec<Shape>,
}

#[derive(Clone)]
pub struct Lod {
    pub parts: Vec<Part>,
}

#[derive(Clone)]
pub struct MDL {
    file_header: ModelFileHeader,
    model_data: ModelData,

    pub lods: Vec<Lod>,
    pub affected_bone_names: Vec<String>,
    pub material_names: Vec<String>,
}

impl MDL {
    pub fn from_existing(buffer: ByteSpan) -> Option<MDL> {
        let mut cursor = Cursor::new(buffer);
        let model_file_header = ModelFileHeader::read(&mut cursor).ok()?;

        let model = ModelData::read_args(
            &mut cursor,
            binrw::args! { file_header: &model_file_header },
        )
        .ok()?;

        let mut affected_bone_names = vec![];

        for offset in &model.bone_name_offsets {
            let mut offset = *offset;
            let mut string = String::new();

            let mut next_char = model.header.strings[offset as usize] as char;
            while next_char != '\0' {
                string.push(next_char);
                offset += 1;
                next_char = model.header.strings[offset as usize] as char;
            }

            affected_bone_names.push(string);
        }

        let mut material_names = vec![];

        for offset in &model.material_name_offsets {
            let mut offset = *offset;
            let mut string = String::new();

            let mut next_char = model.header.strings[offset as usize] as char;
            while next_char != '\0' {
                string.push(next_char);
                offset += 1;
                next_char = model.header.strings[offset as usize] as char;
            }

            material_names.push(string);
        }

        let mut lods = vec![];

        for i in 0..model.header.lod_count {
            let mut parts = vec![];

            for j in model.lods[i as usize].mesh_index
                ..model.lods[i as usize].mesh_index + model.lods[i as usize].mesh_count
            {
                let declaration = &model.header.vertex_declarations[j as usize];
                let vertex_count = model.meshes[j as usize].vertex_count;
                let material_index = model.meshes[j as usize].material_index;

                let mut vertices: Vec<Vertex> = vec![Vertex::default(); vertex_count as usize];

                for k in 0..vertex_count {
                    for element in &declaration.elements {
                        cursor
                            .seek(SeekFrom::Start(
                                (model.lods[i as usize].vertex_data_offset
                                    + model.meshes[j as usize].vertex_buffer_offsets
                                        [element.stream as usize]
                                    + element.offset as u32
                                    + model.meshes[j as usize].vertex_buffer_strides
                                        [element.stream as usize]
                                        as u32
                                        * k as u32) as u64,
                            ))
                            .ok()?;

                        match element.vertex_usage {
                            VertexUsage::Position => match element.vertex_type {
                                VertexType::Single4 => {
                                    vertices[k as usize].position.clone_from_slice(
                                        &MDL::read_single4(&mut cursor).unwrap()[0..3],
                                    );
                                }
                                VertexType::Half4 => {
                                    vertices[k as usize].position.clone_from_slice(
                                        &MDL::read_half4(&mut cursor).unwrap()[0..3],
                                    );
                                }
                                VertexType::Single3 => {
                                    vertices[k as usize].position =
                                        MDL::read_single3(&mut cursor).unwrap();
                                }
                                _ => {
                                    panic!(
                                        "Unexpected vertex type for position: {:#?}",
                                        element.vertex_type
                                    );
                                }
                            },
                            VertexUsage::BlendWeights => match element.vertex_type {
                                VertexType::ByteFloat4 => {
                                    vertices[k as usize].bone_weight =
                                        MDL::read_byte_float4(&mut cursor).unwrap();
                                }
                                VertexType::Byte4 => {
                                    let bytes = MDL::read_byte4(&mut cursor).unwrap();
                                    vertices[k as usize].bone_weight = [
                                        f32::from(bytes[0]),
                                        f32::from(bytes[1]),
                                        f32::from(bytes[2]),
                                        f32::from(bytes[3]),
                                    ];
                                }
                                VertexType::UnsignedShort4 => {
                                    let bytes = MDL::read_unsigned_short4(&mut cursor).unwrap();
                                    vertices[k as usize].bone_weight = [
                                        f32::from(bytes[0]),
                                        f32::from(bytes[1]),
                                        f32::from(bytes[2]),
                                        f32::from(bytes[3]),
                                    ];
                                }
                                _ => {
                                    panic!(
                                        "Unexpected vertex type for blendweight: {:#?}",
                                        element.vertex_type
                                    );
                                }
                            },
                            VertexUsage::BlendIndices => match element.vertex_type {
                                VertexType::Byte4 => {
                                    vertices[k as usize].bone_id =
                                        MDL::read_byte4(&mut cursor).unwrap();
                                }
                                VertexType::UnsignedShort4 => {
                                    let shorts = MDL::read_unsigned_short4(&mut cursor).unwrap();
                                    vertices[k as usize].bone_id = [
                                        shorts[0] as u8,
                                        shorts[1] as u8,
                                        shorts[2] as u8,
                                        shorts[3] as u8,
                                    ];
                                }
                                _ => {
                                    panic!(
                                        "Unexpected vertex type for blendindice: {:#?}",
                                        element.vertex_type
                                    );
                                }
                            },
                            VertexUsage::Normal => match element.vertex_type {
                                VertexType::Half4 => {
                                    vertices[k as usize].normal.clone_from_slice(
                                        &MDL::read_half4(&mut cursor).unwrap()[0..3],
                                    );
                                }
                                VertexType::Single3 => {
                                    vertices[k as usize].normal =
                                        MDL::read_single3(&mut cursor).unwrap();
                                }
                                _ => {
                                    panic!(
                                        "Unexpected vertex type for normal: {:#?}",
                                        element.vertex_type
                                    );
                                }
                            },
                            VertexUsage::UV => match element.vertex_type {
                                VertexType::ByteFloat4 => {
                                    let combined = MDL::read_byte_float4(&mut cursor).unwrap();

                                    vertices[k as usize].uv0.clone_from_slice(&combined[0..2]);
                                    vertices[k as usize].uv1.clone_from_slice(&combined[2..4]);
                                }
                                VertexType::Half4 => {
                                    let combined = MDL::read_half4(&mut cursor).unwrap();

                                    vertices[k as usize].uv0.clone_from_slice(&combined[0..2]);
                                    vertices[k as usize].uv1.clone_from_slice(&combined[2..4]);
                                }
                                VertexType::Single4 => {
                                    let combined = MDL::read_single4(&mut cursor).unwrap();

                                    vertices[k as usize].uv0.clone_from_slice(&combined[0..2]);
                                    vertices[k as usize].uv1.clone_from_slice(&combined[2..4]);
                                }
                                VertexType::Half2 => {
                                    let combined = MDL::read_half2(&mut cursor).unwrap();

                                    vertices[k as usize].uv0.clone_from_slice(&combined[0..2]);
                                }
                                _ => {
                                    panic!(
                                        "Unexpected vertex type for uv: {:#?}",
                                        element.vertex_type
                                    );
                                }
                            },
                            VertexUsage::BiTangent => match element.vertex_type {
                                VertexType::ByteFloat4 => {
                                    vertices[k as usize].bitangent =
                                        MDL::read_tangent(&mut cursor).unwrap();
                                }
                                _ => {
                                    panic!(
                                        "Unexpected vertex type for bitangent: {:#?}",
                                        element.vertex_type
                                    );
                                }
                            },
                            VertexUsage::Tangent => {
                                match element.vertex_type {
                                    // Used for... terrain..?
                                    VertexType::ByteFloat4 => {}
                                    _ => {
                                        panic!(
                                            "Unexpected vertex type for tangent: {:#?}",
                                            element.vertex_type
                                        );
                                    }
                                }
                            }
                            VertexUsage::Color => match element.vertex_type {
                                VertexType::ByteFloat4 => {
                                    vertices[k as usize].color =
                                        MDL::read_byte_float4(&mut cursor).unwrap();
                                }
                                _ => {
                                    panic!(
                                        "Unexpected vertex type for color: {:#?}",
                                        element.vertex_type
                                    );
                                }
                            },
                        }
                    }
                }

                cursor
                    .seek(SeekFrom::Start(
                        (model_file_header.index_offsets[i as usize]
                            + (model.meshes[j as usize].start_index * size_of::<u16>() as u32))
                            as u64,
                    ))
                    .ok()?;

                // TODO: optimize!
                let mut indices: Vec<u16> =
                    Vec::with_capacity(model.meshes[j as usize].index_count as usize);
                for _ in 0..model.meshes[j as usize].index_count {
                    indices.push(cursor.read_le::<u16>().ok()?);
                }

                let mut submeshes: Vec<SubMesh> =
                    Vec::with_capacity(model.meshes[j as usize].submesh_count as usize);
                for i in 0..model.meshes[j as usize].submesh_count {
                    submeshes.push(SubMesh {
                        submesh_index: model.meshes[j as usize].submesh_index as usize + i as usize,
                        index_count: model.submeshes
                            [model.meshes[j as usize].submesh_index as usize + i as usize]
                            .index_count,
                        index_offset: model.submeshes
                            [model.meshes[j as usize].submesh_index as usize + i as usize]
                            .index_offset,
                    });
                }

                let mut shapes = vec![];

                for shape in &model.shapes {
                    // Adapted from https://github.com/xivdev/Penumbra/blob/master/Penumbra/Import/Models/Export/MeshExporter.cs
                    let affected_shape_mesh: Vec<&ShapeMesh> = model
                        .shape_meshes
                        .iter()
                        .skip(shape.shape_mesh_start_index[i as usize] as usize)
                        .take(shape.shape_mesh_count[i as usize] as usize)
                        .filter(|shape_mesh| {
                            shape_mesh.mesh_index_offset == model.meshes[j as usize].start_index
                        })
                        .collect();

                    let shape_values: Vec<&ShapeValue> = affected_shape_mesh
                        .iter()
                        .flat_map(|shape_mesh| {
                            model
                                .shape_values
                                .iter()
                                .skip(shape_mesh.shape_value_offset as usize)
                                .take(shape_mesh.shape_value_count as usize)
                        })
                        .filter(|shape_value| {
                            shape_value.base_indices_index
                                >= model.meshes[j as usize].start_index as u16
                                && shape_value.base_indices_index
                                    < (model.meshes[j as usize].start_index
                                        + model.meshes[j as usize].index_count)
                                        as u16
                        })
                        .collect();

                    let mut morphed_vertices = vec![Vertex::default(); vertices.len()];

                    if !shape_values.is_empty() {
                        for shape_value in shape_values {
                            let old_vertex =
                                vertices[indices[shape_value.base_indices_index as usize] as usize];
                            let new_vertex = vertices[shape_value.replacing_vertex_index
                                as usize];
                            let vertex = &mut morphed_vertices
                                [indices[shape_value.base_indices_index as usize] as usize];

                            vertex.position[0] = new_vertex.position[0] - old_vertex.position[0];
                            vertex.position[1] = new_vertex.position[1] - old_vertex.position[1];
                            vertex.position[2] = new_vertex.position[2] - old_vertex.position[2];
                        }

                        let mut offset = shape.string_offset;
                        let mut string = String::new();

                        let mut next_char = model.header.strings[offset as usize] as char;
                        while next_char != '\0' {
                            string.push(next_char);
                            offset += 1;
                            next_char = model.header.strings[offset as usize] as char;
                        }

                        shapes.push(Shape {
                            name: string,
                            morphed_vertices,
                        });
                    }
                }

                parts.push(Part {
                    mesh_index: j,
                    vertices,
                    indices,
                    material_index,
                    submeshes,
                    shapes,
                });
            }

            lods.push(Lod { parts });
        }

        Some(MDL {
            file_header: model_file_header,
            model_data: model,
            lods,
            affected_bone_names,
            material_names,
        })
    }

    pub fn replace_vertices(
        &mut self,
        lod_index: usize,
        part_index: usize,
        vertices: &[Vertex],
        indices: &[u16],
        submeshes: &[SubMesh],
    ) {
        let part = &mut self.lods[lod_index].parts[part_index];

        part.vertices = Vec::from(vertices);
        part.indices = Vec::from(indices);

        for (i, submesh) in part.submeshes.iter().enumerate() {
            if i < submeshes.len() {
                self.model_data.submeshes[submesh.submesh_index].index_offset =
                    submeshes[i].index_offset;
                self.model_data.submeshes[submesh.submesh_index].index_count =
                    submeshes[i].index_count;
            }
        }

        // Update vertex count in header
        self.model_data.meshes[part.mesh_index as usize].vertex_count = part.vertices.len() as u16;
        self.model_data.meshes[part.mesh_index as usize].index_count = part.indices.len() as u32;

        self.update_headers();
    }

    pub fn remove_shape_meshes(&mut self) {
        self.model_data.shape_meshes.clear();
        self.model_data.shape_values.clear();

        for lod in 0..3 {
            for shape in &mut self.model_data.shapes {
                shape.shape_mesh_count[lod] = 0;
                shape.shape_mesh_start_index[lod] = 0;
            }
        }

        self.update_headers();
    }

    pub fn add_shape_mesh(
        &mut self,
        lod_index: usize,
        shape_index: usize,
        shape_mesh_index: usize,
        part_index: usize,
        shape_values: &[NewShapeValue],
    ) {
        let part = &mut self.lods[lod_index].parts[part_index];

        // TODO: this is assuming they are added in order
        if shape_mesh_index == 0 {
            self.model_data.shapes[shape_index].shape_mesh_start_index[lod_index] =
                self.model_data.shape_meshes.len() as u16;
        }

        self.model_data.shape_meshes.push(ShapeMesh {
            mesh_index_offset: self.model_data.meshes[part.mesh_index as usize].start_index,
            shape_value_count: shape_values.len() as u32,
            shape_value_offset: self.model_data.shape_values.len() as u32,
        });

        for shape_value in shape_values {
            part.vertices.push(shape_value.replacing_vertex);

            self.model_data.shape_values.push(ShapeValue {
                base_indices_index: self.model_data.meshes[part.mesh_index as usize].start_index
                    as u16
                    + shape_value.base_index as u16,
                replacing_vertex_index: self.model_data.meshes[part.mesh_index as usize].start_index
                    as u16
                    + (part.vertices.len() - 1) as u16,
            })
        }

        self.model_data.shapes[shape_index].shape_mesh_count[lod_index] += 1;

        self.update_headers();
    }

    pub(crate) fn update_headers(&mut self) {
        // update values
        for i in 0..self.file_header.lod_count {
            let mut vertex_offset = 0;

            for j in self.model_data.lods[i as usize].mesh_index
                ..self.model_data.lods[i as usize].mesh_index
                    + self.model_data.lods[i as usize].mesh_count
            {
                let mesh = &mut self.model_data.meshes[j as usize];

                mesh.start_index =
                    self.model_data.submeshes[mesh.submesh_index as usize].index_offset;

                for i in 0..mesh.vertex_stream_count as usize {
                    mesh.vertex_buffer_offsets[i] = vertex_offset;
                    vertex_offset +=
                        mesh.vertex_count as u32 * mesh.vertex_buffer_strides[i] as u32;
                }
            }
        }

        for lod in &mut self.model_data.lods {
            let mut total_vertex_buffer_size = 0;
            let mut total_index_buffer_size = 0;

            // still slightly off?
            for j in lod.mesh_index..lod.mesh_index + lod.mesh_count {
                let vertex_count = self.model_data.meshes[j as usize].vertex_count;
                let index_count = self.model_data.meshes[j as usize].index_count;

                let mut total_vertex_stride: u32 = 0;
                for i in 0..self.model_data.meshes[j as usize].vertex_stream_count as usize {
                    total_vertex_stride +=
                        self.model_data.meshes[j as usize].vertex_buffer_strides[i] as u32;
                }

                total_vertex_buffer_size += vertex_count as u32 * total_vertex_stride;
                total_index_buffer_size += index_count * size_of::<u16>() as u32;
            }

            // TODO: this can definitely be written better
            let mut index_padding = total_index_buffer_size % 16;
            if index_padding == 0 {
                index_padding = 16;
            } else {
                index_padding = 16 - index_padding;
            }

            lod.vertex_buffer_size = total_vertex_buffer_size;
            lod.index_buffer_size = total_index_buffer_size.wrapping_add(index_padding);
        }

        // update lod values
        self.file_header.stack_size = self.file_header.calculate_stack_size();
        self.file_header.runtime_size = self.model_data.calculate_runtime_size();

        let data_offset = self.file_header.runtime_size
            + size_of::<ModelFileHeader>() as u32
            + self.file_header.stack_size;

        let mut overall_offset: u32 = 0;

        for lod in &mut self.model_data.lods {
            // vertex
            lod.vertex_data_offset = data_offset + overall_offset;
            overall_offset += lod.vertex_buffer_size;

            // index
            lod.index_data_offset = data_offset + overall_offset;
            overall_offset += lod.index_buffer_size;

            // edge, but unused?
            //lod.edge_geometry_data_offset = data_offset + overall_offset;
            //overall_offset += lod.edge_geometry_size;

            lod.edge_geometry_data_offset = lod.index_data_offset;
        }

        for i in 0..self.lods.len() {
            self.file_header.vertex_buffer_size[i] = self.model_data.lods[i].vertex_buffer_size;
        }

        for i in 0..self.lods.len() {
            self.file_header.vertex_offsets[i] = self.model_data.lods[i].vertex_data_offset;
        }

        for i in 0..self.lods.len() {
            self.file_header.index_buffer_size[i] = self.model_data.lods[i].index_buffer_size;
        }

        for i in 0..self.lods.len() {
            self.file_header.index_offsets[i] = self.model_data.lods[i].index_data_offset;
        }

        self.model_data.header.shape_count = self.model_data.shapes.len() as u16;
        self.model_data.header.shape_mesh_count = self.model_data.shape_meshes.len() as u16;
        self.model_data.header.shape_value_count = self.model_data.shape_values.len() as u16;
    }

    pub fn write_to_buffer(&self) -> Option<ByteBuffer> {
        let mut buffer = ByteBuffer::new();

        {
            let mut cursor = Cursor::new(&mut buffer);

            // write file header
            self.file_header.write(&mut cursor).ok()?;

            self.model_data.write(&mut cursor).ok()?;

            for (l, lod) in self.lods.iter().enumerate() {
                for part in lod.parts.iter() {
                    let declaration =
                        &self.model_data.header.vertex_declarations[part.mesh_index as usize];

                    for (k, vert) in part.vertices.iter().enumerate() {
                        for element in &declaration.elements {
                            cursor
                                .seek(SeekFrom::Start(
                                    (self.model_data.lods[l].vertex_data_offset
                                        + self.model_data.meshes[part.mesh_index as usize]
                                            .vertex_buffer_offsets
                                            [element.stream as usize]
                                        + element.offset as u32
                                        + self.model_data.meshes[part.mesh_index as usize]
                                            .vertex_buffer_strides
                                            [element.stream as usize]
                                            as u32
                                            * k as u32) as u64,
                                ))
                                .ok()?;

                            match element.vertex_usage {
                                VertexUsage::Position => match element.vertex_type {
                                    VertexType::Half4 => {
                                        MDL::write_half4(
                                            &mut cursor,
                                            &MDL::pad_slice(&vert.position, 1.0),
                                        )
                                        .ok()?;
                                    }
                                    VertexType::Single3 => {
                                        MDL::write_single3(&mut cursor, &vert.position).ok()?;
                                    }
                                    _ => {
                                        panic!(
                                            "Unexpected vertex type for position: {:#?}",
                                            element.vertex_type
                                        );
                                    }
                                },
                                VertexUsage::BlendWeights => match element.vertex_type {
                                    VertexType::ByteFloat4 => {
                                        MDL::write_byte_float4(&mut cursor, &vert.bone_weight)
                                            .ok()?;
                                    }
                                    _ => {
                                        panic!(
                                            "Unexpected vertex type for blendweight: {:#?}",
                                            element.vertex_type
                                        );
                                    }
                                },
                                VertexUsage::BlendIndices => match element.vertex_type {
                                    VertexType::Byte4 => {
                                        MDL::write_byte4(&mut cursor, &vert.bone_id).ok()?;
                                    }
                                    _ => {
                                        panic!(
                                            "Unexpected vertex type for blendindice: {:#?}",
                                            element.vertex_type
                                        );
                                    }
                                },
                                VertexUsage::Normal => match element.vertex_type {
                                    VertexType::Half4 => {
                                        MDL::write_half4(
                                            &mut cursor,
                                            &MDL::pad_slice(&vert.normal, 0.0),
                                        )
                                        .ok()?;
                                    }
                                    VertexType::Single3 => {
                                        MDL::write_single3(&mut cursor, &vert.normal).ok()?;
                                    }
                                    _ => {
                                        panic!(
                                            "Unexpected vertex type for normal: {:#?}",
                                            element.vertex_type
                                        );
                                    }
                                },
                                VertexUsage::UV => match element.vertex_type {
                                    VertexType::Half4 => {
                                        let combined =
                                            [vert.uv0[0], vert.uv0[1], vert.uv1[0], vert.uv1[1]];

                                        MDL::write_half4(&mut cursor, &combined).ok()?;
                                    }
                                    VertexType::Single4 => {
                                        let combined =
                                            [vert.uv0[0], vert.uv0[1], vert.uv1[0], vert.uv1[1]];

                                        MDL::write_single4(&mut cursor, &combined).ok()?;
                                    }
                                    _ => {
                                        panic!(
                                            "Unexpected vertex type for uv: {:#?}",
                                            element.vertex_type
                                        );
                                    }
                                },
                                VertexUsage::BiTangent => match element.vertex_type {
                                    VertexType::ByteFloat4 => {
                                        MDL::write_tangent(&mut cursor, &vert.bitangent).ok()?;
                                    }
                                    _ => {
                                        panic!(
                                            "Unexpected vertex type for bitangent: {:#?}",
                                            element.vertex_type
                                        );
                                    }
                                },
                                VertexUsage::Tangent => {
                                    #[allow(clippy::match_single_binding)] // TODO
                                    match element.vertex_type {
                                        /*VertexType::ByteFloat4 => {
                                            MDL::write_tangent(&mut cursor, &vert.binormal).ok()?;
                                        }*/
                                        _ => {
                                            panic!(
                                                "Unexpected vertex type for tangent: {:#?}",
                                                element.vertex_type
                                            );
                                        }
                                    }
                                }
                                VertexUsage::Color => match element.vertex_type {
                                    VertexType::ByteFloat4 => {
                                        MDL::write_byte_float4(&mut cursor, &vert.color).ok()?;
                                    }
                                    _ => {
                                        panic!(
                                            "Unexpected vertex type for color: {:#?}",
                                            element.vertex_type
                                        );
                                    }
                                },
                            }
                        }
                    }

                    cursor
                        .seek(SeekFrom::Start(
                            (self.file_header.index_offsets[l]
                                + (self.model_data.meshes[part.mesh_index as usize].start_index
                                    * size_of::<u16>() as u32)) as u64,
                        ))
                        .ok()?;

                    cursor.write_le(&part.indices).ok()?;
                }
            }
        }

        Some(buffer)
    }
}

impl ModelFileHeader {
    pub fn calculate_stack_size(&self) -> u32 {
        // From https://github.com/Ottermandias/Penumbra.GameData/blob/44021b93e6901c84b739bbf4d1c6350f4486cdbf/Files/MdlFile.cs#L11
        self.vertex_declaration_count as u32 * NUM_VERTICES * VERTEX_ELEMENT_SIZE as u32
    }
}

// TODO: From Xande, need to be cleaned up :)
impl ModelData {
    pub fn calculate_runtime_size(&self) -> u32 {
        2   //StringCount
        + 2 // Unknown
        + 4 //StringSize
        + self.header.string_size
        + 56 //ModelHeader
        + (self.element_ids.len() as u32 * 32)
        + (3 * 60) // 3 Lods
        //+ ( /*file.ModelHeader.ExtraLodEnabled ? 40*/ 0 )
        + self.meshes.len() as u32 * 36
        + self.attribute_name_offsets.len() as u32 * size_of::<u32>() as u32
        + self.header.terrain_shadow_mesh_count as u32 * 20
        + self.header.submesh_count as u32 * 16
        + self.header.terrain_shadow_submesh_count as u32 * 10
        + self.material_name_offsets.len() as u32 * size_of::<u32>() as u32
        + self.bone_name_offsets.len() as u32 * size_of::<u32>() as u32
        + self.bone_tables.len() as u32 * 132
        + self.header.shape_count as u32 * 16
        + self.header.shape_mesh_count as u32 * 12
        + self.header.shape_value_count as u32 * 4
        + 4 // SubmeshBoneMapSize
        + self.submesh_bone_map.len() as u32 * 2
        + self.padding_amount as u32 + 1          // PaddingAmount and Padding
        + (4 * 32) // 4 BoundingBoxes
        + (self.header.bone_count as u32 * 32)
    }
}

#[cfg(test)]
mod tests {
    use std::fs::read;
    use std::mem::size_of;
    use std::path::PathBuf;

    use crate::model_vertex_declarations::VERTEX_ELEMENT_SIZE;

    use super::*;

    #[test]
    fn test_file_header_size() {
        assert_eq!(0x44, size_of::<ModelFileHeader>());
    }

    #[test]
    fn test_vertex_element_size() {
        assert_eq!(8, VERTEX_ELEMENT_SIZE);
    }

    #[test]
    fn test_stack_size() {
        let example_header = ModelFileHeader {
            version: 0,
            stack_size: 0,
            runtime_size: 0,
            vertex_declaration_count: 6,
            material_count: 0,
            vertex_offsets: [0; 3],
            index_offsets: [0; 3],
            vertex_buffer_size: [0; 3],
            index_buffer_size: [0; 3],
            lod_count: 0,
            index_buffer_streaming_enabled: false,
            has_edge_geometry: false,
        };

        assert_eq!(816, example_header.calculate_stack_size());

        let example_header2 = ModelFileHeader {
            version: 0,
            stack_size: 0,
            runtime_size: 0,
            vertex_declaration_count: 2,
            material_count: 0,
            vertex_offsets: [0; 3],
            index_offsets: [0; 3],
            vertex_buffer_size: [0; 3],
            index_buffer_size: [0; 3],
            lod_count: 0,
            index_buffer_streaming_enabled: false,
            has_edge_geometry: false,
        };

        assert_eq!(272, example_header2.calculate_stack_size());
    }

    #[test]
    fn test_update_headers() {
        let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        d.push("resources/tests");
        d.push("c0201e0038_top_zeroed.mdl");

        let mut mdl = MDL::from_existing(&read(d).unwrap()).unwrap();
        let old_mdl = mdl.clone();

        mdl.update_headers();

        // There should be no changes
        assert_eq!(mdl.file_header, old_mdl.file_header);
        assert_eq!(mdl.model_data, old_mdl.model_data);
    }

    #[test]
    fn test_update_vertices() {
        let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        d.push("resources/tests");
        d.push("c0201e0038_top_zeroed.mdl");

        let mut mdl = MDL::from_existing(&read(d).unwrap()).unwrap();
        let old_mdl = mdl.clone();

        for l in 0..old_mdl.lods.len() {
            for p in 0..old_mdl.lods[l].parts.len() {
                mdl.replace_vertices(
                    l,
                    p,
                    &old_mdl.lods[l].parts[p].vertices,
                    &old_mdl.lods[l].parts[p].indices,
                    &old_mdl.lods[l].parts[p].submeshes,
                );
            }
        }

        // There should be no changes
        assert_eq!(mdl.file_header, old_mdl.file_header);
        assert_eq!(mdl.model_data, old_mdl.model_data);
    }

    #[test]
    fn test_parsing() {
        let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        d.push("resources/tests");
        d.push("c0201e0038_top_zeroed.mdl");

        let mdl = MDL::from_existing(&read(d).unwrap()).unwrap();

        // file header
        assert_eq!(mdl.file_header.version, 16777221);
        assert_eq!(mdl.file_header.stack_size, 816);
        assert_eq!(
            mdl.file_header.stack_size,
            mdl.file_header.calculate_stack_size()
        );
        assert_eq!(mdl.file_header.runtime_size, 12544);
        assert_eq!(
            mdl.file_header.runtime_size,
            mdl.model_data.calculate_runtime_size()
        );
        assert_eq!(mdl.file_header.vertex_declaration_count, 6);
        assert_eq!(mdl.file_header.material_count, 2);
        assert_eq!(mdl.file_header.lod_count, 3);
        assert_eq!(mdl.file_header.index_buffer_streaming_enabled, false);
        assert_eq!(mdl.file_header.has_edge_geometry, false);

        // model header
        assert_eq!(mdl.model_data.header.radius, 1.5340779);
    }

    #[test]
    fn test_invalid() {
        let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        d.push("resources/tests");
        d.push("random");

        // Feeding it invalid data should not panic
        MDL::from_existing(&read(d).unwrap());
    }
}