vpin 0.26.5

Rust library for working with Visual Pinball VPX files
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
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
use super::vertex3d::Vertex3D;
use crate::vpx::gameitem::select::WriteSharedAttributes;

use crate::vpx::expanded::WriteError;
use crate::vpx::math::{dequantize_unsigned, quantize_unsigned};
use crate::vpx::model::Vertex3dNoTex2;

use crate::impl_shared_attributes;
use crate::vpx::obj::VpxFace;
use crate::vpx::{
    biff::{self, BiffRead, BiffReader, BiffWrite},
    color::Color,
};
use bytes::{Buf, BufMut, BytesMut};
use flate2::read::ZlibDecoder;
use log::warn;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::io::{self, Read};

const BYTES_PER_VERTEX: usize = 32;

/// when there are more than 65535 vertices we use 4 bytes per index value
/// TODO make private
pub const MAX_VERTICES_FOR_2_BYTE_INDEX: usize = 65535;

#[derive(Debug, PartialEq)]
#[cfg_attr(test, derive(fake::Dummy))]
pub struct Primitive {
    /// Item name. Stored as CSTRING with null terminator (max 32
    /// bytes including null).
    ///
    /// BIFF tag: `NAME`
    pub name: String,

    /// World-space translation applied last in the world matrix
    /// (`Scale * RT * Translate(position)`).
    ///
    /// BIFF tag: `VPOS`
    pub position: Vertex3D,

    /// Per-axis scale, applied first in the world matrix. For builtin
    /// primitives (`use_3d_mesh = false`) this scales the unit-cube
    /// procedural shape; for loaded meshes it scales mesh-local
    /// coordinates.
    ///
    /// BIFF tag: `VSIZ`
    pub size: Vertex3D,

    /// Rotation + translation array, 9 floats. Indices:
    ///
    /// | Index | Meaning   | BIFF |
    /// |-------|-----------|------|
    /// | 0     | RotX      | RTV0 |
    /// | 1     | RotY      | RTV1 |
    /// | 2     | RotZ      | RTV2 |
    /// | 3     | TraX      | RTV3 |
    /// | 4     | TraY      | RTV4 |
    /// | 5     | TraZ      | RTV5 |
    /// | 6     | ObjRotX   | RTV6 |
    /// | 7     | ObjRotY   | RTV7 |
    /// | 8     | ObjRotZ   | RTV8 |
    ///
    /// VPinball composes them as
    /// `Translate(Tra) * RotZ * RotY * RotX * RotZ(Obj) * RotY(Obj) * RotX(Obj)`
    /// inside the world matrix.
    pub rot_and_tra: [f32; 9],

    /// Diffuse texture name; references an entry in `vpx.images` by
    /// name (case-insensitive). Empty string means "no image".
    ///
    /// BIFF tag: `IMAG`
    pub image: String,

    /// Normal-map texture name; references an entry in `vpx.images`.
    /// `None` for tables saved before normal maps were added.
    ///
    /// BIFF tag: `NRMA`
    pub normal_map: Option<String>,

    /// Polygon side count for the procedural mesh used when
    /// `use_3d_mesh = false`. Ignored when a 3D mesh is loaded.
    /// Vpinball clamps to >= 3 in the editor.
    ///
    /// BIFF tag: `SIDS`
    pub sides: u32,

    /// Material name; references an entry in `vpx.gamedata.materials`
    /// (10.8+) or `vpx.gamedata.materials_old` (legacy MATE chunk).
    /// Empty string means "no material" - vpinball falls back to its
    /// dummy material.
    ///
    /// BIFF tag: `MATR`
    pub material: String,

    /// Side colour shown in the vpinball editor preview only -
    /// runtime rendering uses the material/texture, not this field.
    ///
    /// BIFF tag: `SCOL`
    pub side_color: Color,

    /// Render visibility flag. Not the same as `is_collidable` (a
    /// primitive can be invisible but still collide).
    ///
    /// BIFF tag: `TVIS`
    pub is_visible: bool,

    /// When `true`, emit triangles with both windings so the inside
    /// of the mesh is also textured (useful for cup-shaped objects
    /// where the camera sees the back faces). Doubles the index count
    /// for builtin primitives.
    ///
    /// BIFF tag: `DTXI`
    pub draw_textures_inside: bool,

    /// Whether the script `Hit` event fires when the ball touches
    /// this primitive. Independent of `is_collidable` - a
    /// non-collidable primitive can still be queried for hits via
    /// script.
    ///
    /// BIFF tag: `HTEV`
    pub hit_event: bool,

    /// Velocity threshold (VPU/s) below which collisions don't
    /// trigger the `Hit` event.
    ///
    /// BIFF tag: `THRS`
    pub threshold: f32,

    /// Bounciness, 0..1. Overridden by `physics_material` when
    /// `overwrite_physics = false`.
    ///
    /// BIFF tag: `ELAS`
    pub elasticity: f32,

    /// Velocity-dependent elasticity falloff.
    ///
    /// BIFF tag: `ELFO`
    pub elasticity_falloff: f32,

    /// Surface friction, 0..1.
    ///
    /// BIFF tag: `RFCT`
    pub friction: f32,

    /// Random scatter angle in degrees applied to ball reflection.
    ///
    /// BIFF tag: `RSCT`
    pub scatter: f32,

    /// Wireframe density in the editor preview only; doesn't affect
    /// runtime rendering.
    ///
    /// BIFF tag: `EFUI`
    pub edge_factor_ui: f32,

    /// Collision-detection LOD: fraction of triangles included in the
    /// physics mesh, 0..1. Lower values trade physics fidelity for
    /// performance. `None` for tables saved before vpinball 10.01.
    ///
    /// BIFF tag: `CORF`
    pub collision_reduction_factor: Option<f32>,

    /// Master physics enable. When false, the ball passes through the
    /// primitive even if `is_visible = true`.
    ///
    /// BIFF tag: `CLDR`
    pub is_collidable: bool,

    /// Toy / decoration flag. When `true`, the primitive is purely
    /// visual: vpinball generates no collision mesh (independent of
    /// `is_collidable`).
    ///
    /// BIFF tag: `ISTO`
    pub is_toy: bool,

    /// Switches between the procedural builtin primitive (`false`,
    /// see [`crate::vpx::mesh::builtin_primitive`]) and a 3D mesh
    /// loaded from the M3CX/M3CI chunks.
    ///
    /// BIFF tag: `U3DM`
    pub use_3d_mesh: bool,

    /// When `true`, vpinball pre-bakes this primitive into a static
    /// vertex buffer at table load. Disables animation and per-frame
    /// transform changes.
    ///
    /// BIFF tag: `STRE`
    pub static_rendering: bool,

    /// Legacy field for disabling lighting on top surface.
    /// Replaced by `disable_lighting_top` in VPX 10.8.
    ///
    /// BIFF tag: `DILI` (removed in 10.8)
    pub disable_lighting_top_old: Option<f32>,

    /// Controls how much lighting is disabled on the top surface.
    /// Range: 0.0 to 1.0
    /// - 0.0 = full lighting (normal rendering)
    /// - 1.0 = lighting fully disabled (appears darker/unlit)
    ///
    /// BIFF tag: `DILT` (added in 10.8)
    pub disable_lighting_top: Option<f32>,

    /// Controls light transmission through this surface from lights below.
    /// Despite the confusing name "disable_lighting_below", this value controls
    /// how much light from below is BLOCKED, not transmitted.
    ///
    /// Range: 0.0 to 1.0
    /// - 0.0 = light passes through fully (fully transmissive/transparent to light)
    /// - 1.0 = light is fully blocked (opaque, no light transmission)
    ///
    /// VPinball shader uses: `lerp(light_from_below, 0, disable_lighting_below)`
    /// This ADDS light from below to the surface color, it doesn't make it see-through.
    ///
    /// BIFF tag: `DILB` (added in 10.?)
    pub disable_lighting_below: Option<f32>,

    /// Whether this primitive appears in playfield reflections.
    ///
    /// When `true`, the ball is rendered in the reflection pass.
    /// When `false`, the ball won't appear as a reflection on the playfield.
    ///
    /// BIFF tag: `REEN` (was missing in 10.01)
    pub is_reflection_enabled: Option<bool>,

    /// When `true`, render back faces (disable culling). Useful for
    /// thin geometry or open shells.
    ///
    /// BIFF tag: `EBFC`
    pub backfaces_enabled: Option<bool>,

    /// Optional named override for physics properties; references
    /// `vpx.gamedata.materials_old` / `materials`. Empty string or
    /// `None` means "no override".
    ///
    /// BIFF tag: `MAPH`
    pub physics_material: Option<String>,

    /// Switch between the in-place physics fields (`elasticity`,
    /// `friction`, ...) and the named `physics_material` override.
    /// `false` = use in-place values (default); `true` = use the
    /// material's physics.
    ///
    /// BIFF tag: `OVPH`
    pub overwrite_physics: Option<bool>,

    /// Whether to display the texture in the VPinball editor preview.
    /// This does NOT affect runtime rendering - textures are always
    /// rendered if set. Also used on: [`Flasher`], [`Wall`].
    ///
    /// BIFF tag: `DIPT`
    pub display_texture: Option<bool>,

    /// Normal-map orientation flag. `true` = object-space normal map
    /// (matches the +X/+Y/+Z bake direction Blender produces);
    /// `false` = tangent-space (default).
    ///
    /// BIFF tag: `OSNM`
    pub object_space_normal_map: Option<bool>,

    /// Cached axis-aligned bounding box minimum (vpx-internal coords).
    /// VPinball treats the chunk as deprecated and re-derives the AABB
    /// at load time, but it's still written so we round-trip it.
    ///
    /// BIFF tag: `BMIN` (added in 10.8)
    pub min_aa_bound: Option<Vertex3D>,

    /// Cached AABB maximum. See [`Self::min_aa_bound`].
    ///
    /// BIFF tag: `BMAX` (added in 10.8)
    pub max_aa_bound: Option<Vertex3D>,

    /// Source filename of the loaded 3D mesh. Informational only -
    /// the actual geometry lives in the M3CX/M3CI chunks below.
    ///
    /// BIFF tag: `M3DN`
    pub mesh_file_name: Option<String>,

    /// Vertex count of the loaded 3D mesh. Should equal
    /// `compressed_vertices_data` decompressed length / 32 (vertex
    /// stride is 32 bytes).
    ///
    /// BIFF tag: `M3VN`
    pub num_vertices: Option<u32>,

    /// Compressed length of `compressed_vertices_data` in bytes.
    ///
    /// BIFF tag: `M3CY`
    pub compressed_vertices_len: Option<u32>,

    /// Zlib-compressed vertex buffer (positions + UVs + normals,
    /// 32 bytes per vertex after decompression). Use
    /// [`Primitive::read_mesh`] to decode.
    ///
    /// BIFF tag: `M3CX`
    pub compressed_vertices_data: Option<Vec<u8>>,

    /// Triangle index count (3 per face).
    ///
    /// BIFF tag: `M3FN`
    pub num_indices: Option<u32>,

    /// Compressed length of `compressed_indices_data` in bytes.
    ///
    /// BIFF tag: `M3CJ`
    pub compressed_indices_len: Option<u32>,

    /// Zlib-compressed index buffer. Stride is 2 bytes per index
    /// when `num_vertices <= 65535`, otherwise 4 bytes.
    ///
    /// BIFF tag: `M3CI`
    pub compressed_indices_data: Option<Vec<u8>>,

    /// Per-frame compressed lengths for animation sequences. The
    /// outer `Vec` is one entry per frame; matching tags appear
    /// repeated in the BIFF stream.
    ///
    /// BIFF tag: `M3AY` (repeats)
    pub compressed_animation_vertices_len: Option<Vec<u32>>,

    /// Per-frame zlib-compressed vertex buffers for animation. Frame
    /// `n` is at index `n`; positions / normals only (UVs are reused
    /// from the base mesh).
    ///
    /// BIFF tag: `M3AX` (repeats)
    pub compressed_animation_vertices_data: Option<Vec<Vec<u8>>>,

    /// Offset applied when depth-sorting transparent and overlapping
    /// objects. Higher values move the object "further away" in the
    /// sort order, causing it to render behind objects with lower bias.
    /// Also used on: [`Flasher`], [`Ramp`], [`Light`], [`HitTarget`].
    ///
    /// BIFF tag: `PIDB`
    pub depth_bias: f32,

    /// When `true`, additive blend the primitive on top of the scene
    /// (used for self-illuminated effects).
    ///
    /// BIFF tag: `ADDB`
    pub add_blend: Option<bool>,

    /// When `true`, the primitive writes to the depth buffer (default).
    /// Set `false` for transparent overlays that should not occlude
    /// objects behind them.
    ///
    /// BIFF tag: `ZMSK` (added in 10.8)
    pub use_depth_mask: Option<bool>,

    /// Per-primitive transparency multiplier, 0..1. Combines with
    /// the material's opacity.
    ///
    /// BIFF tag: `FALP`
    pub alpha: Option<f32>,

    /// Per-primitive tint, multiplied with the diffuse texture.
    ///
    /// BIFF tag: `COLR`
    pub color: Option<Color>,

    /// Optional lightmap texture name; references an entry in
    /// `vpx.images`.
    ///
    /// BIFF tag: `LMAP` (added in 10.8)
    pub light_map: Option<String>,

    /// Name of a reflection probe defined in the table; see
    /// `vpx.gamedata.reflection_probes`.
    ///
    /// BIFF tag: `REFL` (added in 10.8)
    pub reflection_probe: Option<String>,

    /// Reflection probe contribution, 0..1.
    ///
    /// BIFF tag: `RSTR` (added in 10.8)
    pub reflection_strength: Option<f32>,

    /// Name of a refraction probe defined in the table.
    ///
    /// BIFF tag: `REFR` (added in 10.8)
    pub refraction_probe: Option<String>,

    /// Effective refraction thickness in VPU; controls how much the
    /// background is offset behind the primitive.
    ///
    /// BIFF tag: `RTHI` (added in 10.8)
    pub refraction_thickness: Option<f32>,

    // these are shared between all items
    pub is_locked: bool,
    pub editor_layer: Option<u32>,
    pub editor_layer_name: Option<String>,
    // default "Layer_{editor_layer + 1}"
    pub editor_layer_visibility: Option<bool>,

    /// Added in 10.8.1
    pub part_group_name: Option<String>,
}
impl_shared_attributes!(Primitive);

impl Default for Primitive {
    fn default() -> Self {
        Self {
            position: Default::default(),
            size: Vertex3D::new(100.0, 100.0, 100.0),
            rot_and_tra: [0.0; 9],
            image: Default::default(),
            normal_map: None,
            sides: 4,
            name: Default::default(),
            material: Default::default(),
            side_color: Color::BLACK,
            is_visible: true,
            draw_textures_inside: false,
            hit_event: true,
            threshold: 2.0,
            elasticity: 0.3,
            elasticity_falloff: 0.5,
            friction: 0.3,
            scatter: 0.0,
            edge_factor_ui: 0.25,
            collision_reduction_factor: None,
            is_collidable: true,
            is_toy: false,
            use_3d_mesh: false,
            static_rendering: false,
            disable_lighting_top_old: None,
            disable_lighting_top: None,
            disable_lighting_below: None,
            is_reflection_enabled: None,
            backfaces_enabled: None,
            physics_material: None,
            overwrite_physics: None,
            display_texture: None,
            object_space_normal_map: None,
            min_aa_bound: None,
            max_aa_bound: None,
            mesh_file_name: None,
            num_vertices: None,
            compressed_vertices_len: None,
            compressed_vertices_data: None,
            num_indices: None,
            compressed_indices_len: None,
            compressed_indices_data: None,
            compressed_animation_vertices_len: None,
            compressed_animation_vertices_data: None,
            depth_bias: 0.0,
            add_blend: None,
            use_depth_mask: None,
            alpha: None,
            color: None,
            light_map: None,
            reflection_probe: None,
            reflection_strength: None,
            refraction_probe: None,
            refraction_thickness: None,
            is_locked: false,
            editor_layer: None,
            editor_layer_name: None,
            editor_layer_visibility: None,
            part_group_name: None,
        }
    }
}

#[derive(Serialize, Deserialize)]
struct PrimitiveJson {
    position: Vertex3D,
    size: Vertex3D,
    rot_and_tra: [f32; 9],
    image: String,
    normal_map: Option<String>,
    sides: u32,
    name: String,
    material: String,
    side_color: Color,
    is_visible: bool,
    draw_textures_inside: bool,
    hit_event: bool,
    threshold: f32,
    elasticity: f32,
    elasticity_falloff: f32,
    friction: f32,
    scatter: f32,
    edge_factor_ui: f32,
    collision_reduction_factor: Option<f32>,
    is_collidable: bool,
    is_toy: bool,
    use_3d_mesh: bool,
    static_rendering: bool,
    disable_lighting_top_old: Option<f32>,
    disable_lighting_top: Option<f32>,
    disable_lighting_below: Option<f32>,
    is_reflection_enabled: Option<bool>,
    backfaces_enabled: Option<bool>,
    physics_material: Option<String>,
    overwrite_physics: Option<bool>,
    display_texture: Option<bool>,
    object_space_normal_map: Option<bool>,
    min_aa_bound: Option<Vertex3D>,
    max_aa_bound: Option<Vertex3D>,
    mesh_file_name: Option<String>,
    depth_bias: f32,
    add_blend: Option<bool>,
    use_depth_mask: Option<bool>,
    alpha: Option<f32>,
    color: Option<Color>,
    light_map: Option<String>,
    reflection_probe: Option<String>,
    reflection_strength: Option<f32>,
    refraction_probe: Option<String>,
    refraction_thickness: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    part_group_name: Option<String>,
}

/// A wrapper for a vertex that includes both the original encoded data and the decoded vertex.
///
/// We have found tables with NaN values in the normals.
/// And there are multiple values that give a NaN when decoded.
/// So we keep the original encoded data for fidelity.
///
/// TODO only keep this data around if we know we had NaNs in the source data
#[derive(Debug, Clone, PartialEq)]
pub struct VertexWrapper {
    pub vpx_encoded_vertex: [u8; 32],
    pub vertex: Vertex3dNoTex2,
}
impl VertexWrapper {
    pub fn new(vpx_encoded_vertex: [u8; 32], vertex: Vertex3dNoTex2) -> Self {
        Self {
            vpx_encoded_vertex,
            vertex,
        }
    }
}

pub struct ReadMesh {
    pub vertices: Vec<VertexWrapper>,
    pub indices: Vec<VpxFace>,
}

impl Primitive {
    pub fn read_mesh(&self) -> Result<Option<ReadMesh>, WriteError> {
        if let Some(vertices_data) = &self.compressed_vertices_data {
            if let Some(indices_data) = &self.compressed_indices_data {
                let raw_vertices = decompress_mesh_data(vertices_data)?;
                let indices = decompress_mesh_data(indices_data)?;
                let calculated_num_vertices = raw_vertices.len() / BYTES_PER_VERTEX;
                assert_eq!(
                    calculated_num_vertices,
                    self.num_vertices.unwrap_or(0) as usize,
                    "Vertices count mismatch"
                );

                let calculated_num_indices =
                    if calculated_num_vertices > MAX_VERTICES_FOR_2_BYTE_INDEX {
                        indices.len() / 4
                    } else {
                        indices.len() / 2
                    };
                assert_eq!(
                    calculated_num_indices,
                    self.num_indices.unwrap_or(0) as usize,
                    "Indices count mismatch"
                );
                let num_vertices = raw_vertices.len() / 32;
                let bytes_per_index: u8 = if num_vertices > MAX_VERTICES_FOR_2_BYTE_INDEX {
                    4
                } else {
                    2
                };

                let vertices = raw_vertices_to_vertices(raw_vertices, num_vertices);

                let indices = raw_indices_to_indices(indices, bytes_per_index);

                Ok(Some(ReadMesh { vertices, indices }))
            } else {
                Err(WriteError::Io(io::Error::new(
                    io::ErrorKind::NotFound,
                    format!("Primitive {} has vertices but no indices", self.name),
                )))
            }
        } else {
            Ok(None)
        }
    }

    /// Check if this primitive is the playfield mesh.
    ///
    /// VPinball identifies the playfield purely by name — there is no explicit
    /// flag or field. Any primitive named `"playfield_mesh"` (case-insensitive)
    /// is treated as the playfield and has the table-level
    /// [`GameData::image`] and [`GameData::playfield_material`] applied
    /// automatically at render time.
    ///
    /// From VPinball `primitive.h`:
    /// ```cpp
    /// bool IsPlayfield() const { return _wcsicmp(m_wzName, L"playfield_mesh") == 0; }
    /// ```
    pub fn is_playfield(&self) -> bool {
        self.name.eq_ignore_ascii_case("playfield_mesh")
    }
}

impl PrimitiveJson {
    pub fn from_primitive(primitive: &Primitive) -> Self {
        Self {
            position: primitive.position,
            size: primitive.size,
            rot_and_tra: primitive.rot_and_tra,
            image: primitive.image.clone(),
            normal_map: primitive.normal_map.clone(),
            sides: primitive.sides,
            name: primitive.name.clone(),
            material: primitive.material.clone(),
            side_color: primitive.side_color,
            is_visible: primitive.is_visible,
            draw_textures_inside: primitive.draw_textures_inside,
            hit_event: primitive.hit_event,
            threshold: primitive.threshold,
            elasticity: primitive.elasticity,
            elasticity_falloff: primitive.elasticity_falloff,
            friction: primitive.friction,
            scatter: primitive.scatter,
            edge_factor_ui: primitive.edge_factor_ui,
            collision_reduction_factor: primitive.collision_reduction_factor,
            is_collidable: primitive.is_collidable,
            is_toy: primitive.is_toy,
            use_3d_mesh: primitive.use_3d_mesh,
            static_rendering: primitive.static_rendering,
            disable_lighting_top_old: primitive.disable_lighting_top_old,
            disable_lighting_top: primitive.disable_lighting_top,
            disable_lighting_below: primitive.disable_lighting_below,
            is_reflection_enabled: primitive.is_reflection_enabled,
            backfaces_enabled: primitive.backfaces_enabled,
            physics_material: primitive.physics_material.clone(),
            overwrite_physics: primitive.overwrite_physics,
            display_texture: primitive.display_texture,
            object_space_normal_map: primitive.object_space_normal_map,
            min_aa_bound: primitive.min_aa_bound,
            max_aa_bound: primitive.max_aa_bound,
            mesh_file_name: primitive.mesh_file_name.clone(),
            // num_vertices: primitive.num_vertices,
            // compressed_vertices: primitive.compressed_vertices_len,
            //compressed_vertices_data: primitive.m3cx.clone(),
            // num_indices: primitive.num_indices,
            // compressed_indices: primitive.compressed_indices_len,
            // compressed_indices_Data: primitive.m3ci.clone(),
            // compressed_animation_vertices: primitive.compressed_animation_vertices_len.clone(),
            // compressed_animation_vertices_data: primitive
            //     .compressed_animation_vertices_data
            //     .clone(),
            depth_bias: primitive.depth_bias,
            add_blend: primitive.add_blend,
            use_depth_mask: primitive.use_depth_mask,
            alpha: primitive.alpha,
            color: primitive.color,
            light_map: primitive.light_map.clone(),
            reflection_probe: primitive.reflection_probe.clone(),
            reflection_strength: primitive.reflection_strength,
            refraction_probe: primitive.refraction_probe.clone(),
            refraction_thickness: primitive.refraction_thickness,
            part_group_name: primitive.part_group_name.clone(),
        }
    }
    pub fn to_primitive(&self) -> Primitive {
        Primitive {
            position: self.position,
            size: self.size,
            rot_and_tra: self.rot_and_tra,
            image: self.image.clone(),
            normal_map: self.normal_map.clone(),
            sides: self.sides,
            name: self.name.clone(),
            material: self.material.clone(),
            side_color: self.side_color,
            is_visible: self.is_visible,
            draw_textures_inside: self.draw_textures_inside,
            hit_event: self.hit_event,
            threshold: self.threshold,
            elasticity: self.elasticity,
            elasticity_falloff: self.elasticity_falloff,
            friction: self.friction,
            scatter: self.scatter,
            edge_factor_ui: self.edge_factor_ui,
            collision_reduction_factor: self.collision_reduction_factor,
            is_collidable: self.is_collidable,
            is_toy: self.is_toy,
            use_3d_mesh: self.use_3d_mesh,
            static_rendering: self.static_rendering,
            disable_lighting_top_old: self.disable_lighting_top_old,
            disable_lighting_top: self.disable_lighting_top,
            disable_lighting_below: self.disable_lighting_below,
            is_reflection_enabled: self.is_reflection_enabled,
            backfaces_enabled: self.backfaces_enabled,
            physics_material: self.physics_material.clone(),
            overwrite_physics: self.overwrite_physics,
            display_texture: self.display_texture,
            object_space_normal_map: self.object_space_normal_map,
            min_aa_bound: self.min_aa_bound,
            max_aa_bound: self.max_aa_bound,
            mesh_file_name: self.mesh_file_name.clone(),
            num_vertices: None,                       //self.num_vertices,
            compressed_vertices_len: None,            //self.compressed_vertices,
            compressed_vertices_data: None,           //self.m3cx.clone(),
            num_indices: None,                        //self.num_indices,
            compressed_indices_len: None,             //self.compressed_indices,
            compressed_indices_data: None,            //self.m3ci.clone(),
            compressed_animation_vertices_len: None,  //self.compressed_animation_vertices.clone(),
            compressed_animation_vertices_data: None, //self.compressed_animation_vertices_data.clone(),
            depth_bias: self.depth_bias,
            add_blend: self.add_blend,
            use_depth_mask: self.use_depth_mask,
            alpha: self.alpha,
            color: self.color,
            light_map: self.light_map.clone(),
            reflection_probe: self.reflection_probe.clone(),
            reflection_strength: self.reflection_strength,
            refraction_probe: self.refraction_probe.clone(),
            refraction_thickness: self.refraction_thickness,
            // this is populated from a different file
            is_locked: false,
            // this is populated from a different file
            editor_layer: None,
            // this is populated from a different file
            editor_layer_name: None,
            // this is populated from a different file
            editor_layer_visibility: None,
            part_group_name: self.part_group_name.clone(),
        }
    }
}

impl Serialize for Primitive {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        PrimitiveJson::from_primitive(self).serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for Primitive {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let json = PrimitiveJson::deserialize(deserializer)?;
        Ok(json.to_primitive())
    }
}

impl BiffRead for Primitive {
    fn biff_read(reader: &mut BiffReader<'_>) -> Primitive {
        let mut compressed_animation_vertices: Option<Vec<u32>> = None;
        let mut m3ax: Option<Vec<Vec<u8>>> = None;
        let mut primitive = Primitive::default();

        loop {
            reader.next(biff::WARN);
            if reader.is_eof() {
                break;
            }
            let tag = reader.tag();
            let tag_str = tag.as_str();
            //println!("tag: {}", tag_str);
            match tag_str {
                // TOTAN4K had this
                // https://github.com/freezy/VisualPinball.Engine/blob/ec1e9765cd4832c134e889d6e6d03320bc404bd5/VisualPinball.Engine/VPT/Primitive/PrimitiveData.cs#L64
                // Unknown tag M3AY for vpxtool::vpx::gameitem::primitive::Primitive
                // Unknown tag M3AY for vpxtool::vpx::gameitem::primitive::Primitive
                // Unknown tag M3AY for vpxtool::vpx::gameitem::primitive::Primitive
                "VPOS" => {
                    primitive.position = Vertex3D::biff_read(reader);
                }
                "VSIZ" => {
                    primitive.size = Vertex3D::biff_read(reader);
                }
                "RTV0" => {
                    primitive.rot_and_tra[0] = reader.get_f32();
                }
                "RTV1" => {
                    primitive.rot_and_tra[1] = reader.get_f32();
                }
                "RTV2" => {
                    primitive.rot_and_tra[2] = reader.get_f32();
                }
                "RTV3" => {
                    primitive.rot_and_tra[3] = reader.get_f32();
                }
                "RTV4" => {
                    primitive.rot_and_tra[4] = reader.get_f32();
                }
                "RTV5" => {
                    primitive.rot_and_tra[5] = reader.get_f32();
                }
                "RTV6" => {
                    primitive.rot_and_tra[6] = reader.get_f32();
                }
                "RTV7" => {
                    primitive.rot_and_tra[7] = reader.get_f32();
                }
                "RTV8" => {
                    primitive.rot_and_tra[8] = reader.get_f32();
                }
                "IMAG" => {
                    primitive.image = reader.get_string();
                }
                "NRMA" => {
                    primitive.normal_map = Some(reader.get_string());
                }
                "SIDS" => {
                    primitive.sides = reader.get_u32();
                }
                "NAME" => {
                    primitive.name = reader.get_wide_string();
                }
                "MATR" => {
                    primitive.material = reader.get_string();
                }
                "SCOL" => {
                    primitive.side_color = Color::biff_read(reader);
                }
                "TVIS" => {
                    primitive.is_visible = reader.get_bool();
                }
                "DTXI" => {
                    primitive.draw_textures_inside = reader.get_bool();
                }
                "HTEV" => {
                    primitive.hit_event = reader.get_bool();
                }
                "THRS" => {
                    primitive.threshold = reader.get_f32();
                }
                "ELAS" => {
                    primitive.elasticity = reader.get_f32();
                }
                "ELFO" => {
                    primitive.elasticity_falloff = reader.get_f32();
                }
                "RFCT" => {
                    primitive.friction = reader.get_f32();
                }
                "RSCT" => {
                    primitive.scatter = reader.get_f32();
                }
                "EFUI" => {
                    primitive.edge_factor_ui = reader.get_f32();
                }
                "CORF" => {
                    primitive.collision_reduction_factor = Some(reader.get_f32());
                }
                "CLDR" => {
                    primitive.is_collidable = reader.get_bool();
                }
                "ISTO" => {
                    primitive.is_toy = reader.get_bool();
                }
                "U3DM" => {
                    primitive.use_3d_mesh = reader.get_bool();
                }
                "STRE" => {
                    primitive.static_rendering = reader.get_bool();
                }
                "DILI" => {
                    // vpinball reads this to DILT, but we keep it as we stick to pure IO
                    primitive.disable_lighting_top_old =
                        Some(dequantize_unsigned::<8>(reader.get_u32()));
                }
                "DILT" => {
                    primitive.disable_lighting_top = Some(reader.get_f32());
                }
                "DILB" => {
                    primitive.disable_lighting_below = Some(reader.get_f32());
                }
                "REEN" => {
                    primitive.is_reflection_enabled = Some(reader.get_bool());
                }
                "EBFC" => {
                    primitive.backfaces_enabled = Some(reader.get_bool());
                }
                "MAPH" => {
                    primitive.physics_material = Some(reader.get_string());
                }
                "OVPH" => {
                    primitive.overwrite_physics = Some(reader.get_bool());
                }
                "DIPT" => {
                    primitive.display_texture = Some(reader.get_bool());
                }
                "OSNM" => {
                    primitive.object_space_normal_map = Some(reader.get_bool());
                }
                "BMIN" => {
                    primitive.min_aa_bound = Some(Vertex3D::read_unpadded(reader));
                }
                "BMAX" => {
                    primitive.max_aa_bound = Some(Vertex3D::read_unpadded(reader));
                }
                "M3DN" => {
                    primitive.mesh_file_name = Some(reader.get_string());
                }
                "M3VN" => {
                    primitive.num_vertices = Some(reader.get_u32());
                }
                "M3CY" => {
                    primitive.compressed_vertices_len = Some(reader.get_u32());
                }

                // [BiffVertices("M3DX", SkipWrite = true)]
                // [BiffVertices("M3CX", IsCompressed = true, Pos = 42)]
                // [BiffIndices("M3DI", SkipWrite = true)]
                // [BiffIndices("M3CI", IsCompressed = true, Pos = 45)]
                // [BiffAnimation("M3AX", IsCompressed = true, Pos = 47 )]
                // public Mesh Mesh = new Mesh();
                "M3CX" => {
                    primitive.compressed_vertices_data = Some(reader.get_record_data(false));
                }
                "M3FN" => {
                    primitive.num_indices = Some(reader.get_u32());
                }
                "M3CJ" => {
                    primitive.compressed_indices_len = Some(reader.get_u32());
                }
                "M3CI" => {
                    primitive.compressed_indices_data = Some(reader.get_record_data(false));
                }
                "M3AY" => {
                    match compressed_animation_vertices {
                        Some(ref mut m3ay) => {
                            m3ay.push(reader.get_u32());
                        }
                        None => compressed_animation_vertices = Some(vec![reader.get_u32()]),
                    };
                }
                "M3AX" => {
                    match m3ax {
                        Some(ref mut m3ax) => {
                            m3ax.push(reader.get_record_data(false));
                        }
                        None => {
                            m3ax = Some(vec![reader.get_record_data(false)]);
                        }
                    };
                }
                "PIDB" => {
                    primitive.depth_bias = reader.get_f32();
                }
                "ADDB" => {
                    primitive.add_blend = Some(reader.get_bool());
                }
                "ZMSK" => {
                    primitive.use_depth_mask = Some(reader.get_bool());
                }
                "FALP" => {
                    primitive.alpha = Some(reader.get_f32());
                }
                "COLR" => {
                    primitive.color = Some(Color::biff_read(reader));
                }
                "LMAP" => {
                    primitive.light_map = Some(reader.get_string());
                }
                "REFL" => {
                    primitive.reflection_probe = Some(reader.get_string());
                }
                "RSTR" => {
                    primitive.reflection_strength = Some(reader.get_f32());
                }
                "REFR" => {
                    primitive.refraction_probe = Some(reader.get_string());
                }
                "RTHI" => {
                    primitive.refraction_thickness = Some(reader.get_f32());
                }
                _ => {
                    if !primitive.read_shared_attribute(tag_str, reader) {
                        warn!(
                            "Unknown tag {} for {}",
                            tag_str,
                            std::any::type_name::<Self>()
                        );
                        reader.skip_tag();
                    }
                }
            }
        }

        primitive.compressed_animation_vertices_len = compressed_animation_vertices;
        primitive.compressed_animation_vertices_data = m3ax;
        primitive
    }
}

impl BiffWrite for Primitive {
    fn biff_write(&self, writer: &mut biff::BiffWriter) {
        writer.write_tagged("VPOS", &self.position);
        writer.write_tagged("VSIZ", &self.size);
        writer.write_tagged_f32("RTV0", self.rot_and_tra[0]);
        writer.write_tagged_f32("RTV1", self.rot_and_tra[1]);
        writer.write_tagged_f32("RTV2", self.rot_and_tra[2]);
        writer.write_tagged_f32("RTV3", self.rot_and_tra[3]);
        writer.write_tagged_f32("RTV4", self.rot_and_tra[4]);
        writer.write_tagged_f32("RTV5", self.rot_and_tra[5]);
        writer.write_tagged_f32("RTV6", self.rot_and_tra[6]);
        writer.write_tagged_f32("RTV7", self.rot_and_tra[7]);
        writer.write_tagged_f32("RTV8", self.rot_and_tra[8]);
        writer.write_tagged_string("IMAG", &self.image);
        if let Some(normal_map) = &self.normal_map {
            writer.write_tagged_string("NRMA", normal_map);
        }
        writer.write_tagged_u32("SIDS", self.sides);
        writer.write_tagged_wide_string("NAME", &self.name);
        writer.write_tagged_string("MATR", &self.material);
        writer.write_tagged_with("SCOL", &self.side_color, Color::biff_write);
        writer.write_tagged_bool("TVIS", self.is_visible);
        writer.write_tagged_bool("DTXI", self.draw_textures_inside);
        writer.write_tagged_bool("HTEV", self.hit_event);
        writer.write_tagged_f32("THRS", self.threshold);
        writer.write_tagged_f32("ELAS", self.elasticity);
        writer.write_tagged_f32("ELFO", self.elasticity_falloff);
        writer.write_tagged_f32("RFCT", self.friction);
        writer.write_tagged_f32("RSCT", self.scatter);
        writer.write_tagged_f32("EFUI", self.edge_factor_ui);
        if let Some(collision_reduction_factor) = self.collision_reduction_factor {
            writer.write_tagged_f32("CORF", collision_reduction_factor);
        }
        writer.write_tagged_bool("CLDR", self.is_collidable);
        writer.write_tagged_bool("ISTO", self.is_toy);
        writer.write_tagged_bool("U3DM", self.use_3d_mesh);
        writer.write_tagged_bool("STRE", self.static_rendering);
        if let Some(disable_lighting_top_old) = self.disable_lighting_top_old {
            writer.write_tagged_u32("DILI", quantize_unsigned::<8>(disable_lighting_top_old));
        }
        if let Some(disable_lighting_top) = self.disable_lighting_top {
            writer.write_tagged_f32("DILT", disable_lighting_top);
        }
        if let Some(disable_lighting_below) = self.disable_lighting_below {
            writer.write_tagged_f32("DILB", disable_lighting_below);
        }
        if let Some(is_reflection_enabled) = self.is_reflection_enabled {
            writer.write_tagged_bool("REEN", is_reflection_enabled);
        }
        if let Some(backfaces_enabled) = self.backfaces_enabled {
            writer.write_tagged_bool("EBFC", backfaces_enabled);
        }
        if let Some(physics_material) = &self.physics_material {
            writer.write_tagged_string("MAPH", physics_material);
        }
        if let Some(overwrite_physics) = self.overwrite_physics {
            writer.write_tagged_bool("OVPH", overwrite_physics);
        }
        if let Some(display_texture) = self.display_texture {
            writer.write_tagged_bool("DIPT", display_texture);
        }
        if let Some(object_space_normal_map) = self.object_space_normal_map {
            writer.write_tagged_bool("OSNM", object_space_normal_map);
        }

        if let Some(min_aa_bound) = &self.min_aa_bound {
            writer.write_tagged_unpadded_vector(
                "BMIN",
                min_aa_bound.x,
                min_aa_bound.y,
                min_aa_bound.z,
            );
        }
        if let Some(max_aa_bound) = &self.max_aa_bound {
            writer.write_tagged_unpadded_vector(
                "BMAX",
                max_aa_bound.x,
                max_aa_bound.y,
                max_aa_bound.z,
            );
        }
        if let Some(mesh_file_name) = &self.mesh_file_name {
            writer.write_tagged_string("M3DN", mesh_file_name);
        }
        if let Some(num_vertices) = &self.num_vertices {
            writer.write_tagged_u32("M3VN", *num_vertices);
        }
        if let Some(compressed_vertices) = &self.compressed_vertices_len {
            writer.write_tagged_u32("M3CY", *compressed_vertices);
        }
        if let Some(m3cx) = &self.compressed_vertices_data {
            writer.write_tagged_data("M3CX", m3cx);
        }
        if let Some(num_indices) = &self.num_indices {
            writer.write_tagged_u32("M3FN", *num_indices);
        }
        if let Some(compressed_indices) = &self.compressed_indices_len {
            writer.write_tagged_u32("M3CJ", *compressed_indices);
        }
        if let Some(m3ci) = &self.compressed_indices_data {
            writer.write_tagged_data("M3CI", m3ci);
        }

        // these should come in pairs
        // TODO rework in a better way
        // if both are present, write them in pairs
        if let (Some(m3ays), Some(m3axs)) = (
            &self.compressed_animation_vertices_len,
            &self.compressed_animation_vertices_data,
        ) {
            for (m3ay, m3ax) in m3ays.iter().zip(m3axs.iter()) {
                writer.write_tagged_u32("M3AY", *m3ay);
                writer.write_tagged_data("M3AX", m3ax);
            }
        }

        writer.write_tagged_f32("PIDB", self.depth_bias);

        if let Some(add_blend) = self.add_blend {
            writer.write_tagged_bool("ADDB", add_blend);
        }
        if let Some(use_depth_mask) = self.use_depth_mask {
            writer.write_tagged_bool("ZMSK", use_depth_mask);
        }
        if let Some(alpha) = self.alpha {
            writer.write_tagged_f32("FALP", alpha);
        }
        if let Some(color) = &self.color {
            writer.write_tagged_with("COLR", color, Color::biff_write);
        }
        if let Some(light_map) = &self.light_map {
            writer.write_tagged_string("LMAP", light_map);
        }
        if let Some(reflection_probe) = &self.reflection_probe {
            writer.write_tagged_string("REFL", reflection_probe);
        }
        if let Some(reflection_strength) = &self.reflection_strength {
            writer.write_tagged_f32("RSTR", *reflection_strength);
        }
        if let Some(refraction_probe) = &self.refraction_probe {
            writer.write_tagged_string("REFR", refraction_probe);
        }
        if let Some(refraction_thickness) = &self.refraction_thickness {
            writer.write_tagged_f32("RTHI", *refraction_thickness);
        }

        self.write_shared_attributes(writer);

        writer.close(true);
    }
}

fn read_vertex_index_from_vpx(bytes_per_index: u8, buff: &mut BytesMut) -> i64 {
    if bytes_per_index == 2 {
        buff.get_u16_le() as i64
    } else {
        buff.get_u32_le() as i64
    }
}

/// Decompress mesh data (vertices or indices) using zlib compression.
pub(crate) fn decompress_mesh_data(compressed_data: &[u8]) -> io::Result<Vec<u8>> {
    let mut decoder = ZlibDecoder::new(compressed_data);
    let mut decompressed_data = Vec::new();
    decoder.read_to_end(&mut decompressed_data)?;
    Ok(decompressed_data)
}

/// Compress mesh data (vertices or indices) using zlib compression.
pub(crate) fn compress_mesh_data(data: &[u8]) -> io::Result<Vec<u8>> {
    use flate2::Compression;
    use flate2::write::ZlibEncoder;
    use std::io::Write;

    // before 10.6.1, compression was always LZW
    // "abuses the VP-Image-LZW compressor"
    // see https://github.com/vpinball/vpinball/commit/09f5510d676cd6b204350dfc4a93b9bf93284c56

    // Pre-allocate buffer with estimated compressed size (typically ~50-70% of original)
    let estimated_size = (data.len() * 7) / 10;
    let output = Vec::with_capacity(estimated_size);

    // The best compression level is too slow for large meshes, so we use a default level
    let compression_level = Compression::default();

    let mut encoder = ZlibEncoder::new(output, compression_level);
    encoder.write_all(data)?;
    encoder.finish()
}

fn raw_vertices_to_vertices(raw_vertices: Vec<u8>, num_vertices: usize) -> Vec<VertexWrapper> {
    let mut vertices = Vec::with_capacity(num_vertices);
    let mut buff = BytesMut::from(raw_vertices.as_slice());
    for _ in 0..num_vertices {
        let vertex = read_vertex(&mut buff);
        vertices.push(vertex);
    }
    vertices
}

fn raw_indices_to_indices(vpx_encoded_indices: Vec<u8>, bytes_per_index: u8) -> Vec<VpxFace> {
    let mut buff = BytesMut::from(vpx_encoded_indices.as_slice());
    let num_indices = vpx_encoded_indices.len() / bytes_per_index as usize;
    let mut indices: Vec<VpxFace> = Vec::with_capacity(num_indices);
    for _ in 0..num_indices / 3 {
        // Looks like the indices are in reverse order
        let v1 = read_vertex_index_from_vpx(bytes_per_index, &mut buff);
        let v2 = read_vertex_index_from_vpx(bytes_per_index, &mut buff);
        let v3 = read_vertex_index_from_vpx(bytes_per_index, &mut buff);
        indices.push(VpxFace::new(v1, v2, v3));
    }
    indices
}

fn read_vertex(buffer: &mut BytesMut) -> VertexWrapper {
    let mut bytes = [0; 32];
    buffer.copy_to_slice(&mut bytes);
    let mut vertex_buff = BytesMut::from(bytes.as_ref());

    let x = vertex_buff.get_f32_le();
    let y = vertex_buff.get_f32_le();
    let z = vertex_buff.get_f32_le();
    // normals
    let nx = vertex_buff.get_f32_le();
    let ny = vertex_buff.get_f32_le();
    let nz = vertex_buff.get_f32_le();
    // texture coordinates
    let tu = vertex_buff.get_f32_le();
    let tv = vertex_buff.get_f32_le();
    let v3d = Vertex3dNoTex2 {
        x,
        y,
        z,
        nx,
        ny,
        nz,
        tu,
        tv,
    };
    VertexWrapper {
        vpx_encoded_vertex: bytes,
        vertex: v3d,
    }
}

/// Animation frame vertex data
/// this is combined with the primary mesh face and texture data.
///
/// This struct is used for serializing and deserializing in the vpinball C++ code
#[derive(Debug, Clone, Copy)]
pub struct VertData {
    pub x: f32,
    pub y: f32,
    pub z: f32,
    pub nx: f32,
    pub ny: f32,
    pub nz: f32,
}
impl VertData {
    pub const SERIALIZED_SIZE: usize = 24;
}

pub(crate) fn read_vpx_animation_frame(
    compressed_frame: &[u8],
    compressed_length: &u32,
) -> Result<Vec<VertData>, WriteError> {
    if compressed_frame.len() != *compressed_length as usize {
        return Err(WriteError::Io(io::Error::new(
            io::ErrorKind::InvalidData,
            format!(
                "Animation frame compressed length does not match: {} != {}",
                compressed_frame.len(),
                compressed_length
            ),
        )));
    }
    let decompressed_frame = decompress_mesh_data(compressed_frame)?;
    let frame_data_len = decompressed_frame.len() / VertData::SERIALIZED_SIZE;
    let mut buff = BytesMut::from(decompressed_frame.as_slice());
    let mut vertices: Vec<VertData> = Vec::with_capacity(frame_data_len);
    for _ in 0..frame_data_len {
        let vertex = read_animation_vertex_data(&mut buff);
        vertices.push(vertex);
    }
    Ok(vertices)
}

fn read_animation_vertex_data(buffer: &mut BytesMut) -> VertData {
    let x = buffer.get_f32_le();
    let y = buffer.get_f32_le();
    let z = buffer.get_f32_le();
    let nx = buffer.get_f32_le();
    let ny = buffer.get_f32_le();
    let nz = buffer.get_f32_le();
    VertData {
        x,
        y,
        z,
        nx,
        ny,
        nz,
    }
}

pub(crate) fn write_animation_vertex_data(buff: &mut BytesMut, vertex: &VertData) {
    buff.put_f32_le(vertex.x);
    buff.put_f32_le(vertex.y);
    buff.put_f32_le(vertex.z);
    buff.put_f32_le(vertex.nx);
    buff.put_f32_le(vertex.ny);
    buff.put_f32_le(vertex.nz);
}

#[cfg(test)]
mod tests {
    use crate::vpx::biff::BiffWriter;
    use fake::{Fake, Faker};

    use super::*;
    use crate::vpx::gameitem::tests::RandomOption;
    use pretty_assertions::assert_eq;
    use rand::RngExt;

    #[test]
    fn test_write_read() {
        let mut rng = rand::rng();
        let primitive: Primitive = Primitive {
            position: Vertex3D::new(1.0, 2.0, 3.0),
            size: Vertex3D::new(4.0, 5.0, 6.0),
            rot_and_tra: [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9],
            image: "image".to_string(),
            normal_map: Some("normal_map".to_string()),
            sides: 1,
            name: "name".to_string(),
            material: "material".to_string(),
            side_color: Faker.fake(),
            is_visible: rng.random(),
            // random bool
            draw_textures_inside: rng.random(),
            hit_event: rng.random(),
            threshold: 1.0,
            elasticity: 2.0,
            elasticity_falloff: 3.0,
            friction: 4.0,
            scatter: 5.0,
            edge_factor_ui: 6.0,
            collision_reduction_factor: Some(7.0),
            is_collidable: rng.random(),
            is_toy: rng.random(),
            use_3d_mesh: rng.random(),
            static_rendering: rng.random(),
            // we need a value that is supported when quantized to 8 bits, since the old `DILI` tag uses 8-bit quantization.
            disable_lighting_top_old: Some(1.0),
            disable_lighting_top: Some(rng.random()),
            disable_lighting_below: rng.random_option(),
            is_reflection_enabled: rng.random_option(),
            backfaces_enabled: rng.random_option(),
            physics_material: Some("physics_material".to_string()),
            overwrite_physics: rng.random_option(),
            display_texture: rng.random_option(),
            object_space_normal_map: rng.random_option(),
            min_aa_bound: Some(Vertex3D::new(-1.5, -2.5, -3.5)),
            max_aa_bound: Some(Vertex3D::new(1.5, 2.5, 3.5)),
            mesh_file_name: Some("mesh_file_name".to_string()),
            num_vertices: Some(8),
            compressed_vertices_len: Some(9),
            compressed_vertices_data: Some(vec![1, 2, 3, 4, 5, 6, 7, 8, 9]),
            num_indices: Some(10),
            compressed_indices_len: Some(11),
            compressed_indices_data: Some(vec![2, 3, 4, 5, 6, 7, 8, 9, 10]),
            compressed_animation_vertices_len: Some(vec![9, 8]),
            compressed_animation_vertices_data: Some(vec![
                vec![4, 5, 6, 7, 8, 9, 10, 11, 12],
                vec![5, 6, 7, 8, 9, 10, 11, 12],
            ]),
            depth_bias: 12.0,
            add_blend: rng.random_option(),
            use_depth_mask: rng.random_option(),
            alpha: Some(13.0),
            color: Faker.fake(),
            light_map: Some("light_map".to_string()),
            reflection_probe: Some("reflection_probe".to_string()),
            reflection_strength: Some(14.0),
            refraction_probe: Some("refraction_probe".to_string()),
            refraction_thickness: Some(15.0),
            is_locked: rng.random(),
            editor_layer: Some(17),
            editor_layer_name: Some("editor_layer_name".to_string()),
            editor_layer_visibility: rng.random_option(),
            part_group_name: Some("part_group_name".to_string()),
        };
        let mut writer = BiffWriter::new();
        Primitive::biff_write(&primitive, &mut writer);
        let primitive_read = Primitive::biff_read(&mut BiffReader::new(writer.get_data()));
        assert_eq!(primitive, primitive_read);
    }

    #[test]
    fn test_compress_decompress_mesh_data() {
        // Test with small data
        let original_small = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
        let compressed_small = compress_mesh_data(&original_small).unwrap();
        let decompressed_small = decompress_mesh_data(&compressed_small).unwrap();
        assert_eq!(original_small, decompressed_small);
        // Compression should make it larger for tiny data due to headers
        assert!(compressed_small.len() > original_small.len());

        // Test with larger data (simulating vertex data: 100 vertices * 32 bytes)
        let original_large: Vec<u8> = (0..3200).map(|i| (i % 256) as u8).collect();
        let compressed_large = compress_mesh_data(&original_large).unwrap();
        let decompressed_large = decompress_mesh_data(&compressed_large).unwrap();
        assert_eq!(original_large, decompressed_large);
        // Compression should reduce size for larger repetitive data
        assert!(compressed_large.len() < original_large.len());

        // Test with very large data (>10MB) to verify adaptive compression level
        let original_huge: Vec<u8> = vec![42; 11_000_000]; // 11MB of same byte
        let compressed_huge = compress_mesh_data(&original_huge).unwrap();
        let decompressed_huge = decompress_mesh_data(&compressed_huge).unwrap();
        assert_eq!(original_huge, decompressed_huge);
        // Should compress extremely well due to repetition
        assert!(compressed_huge.len() < 100_000); // Should be much smaller than 11MB
    }

    #[test]
    fn test_compress_mesh_data_empty() {
        let original = vec![];
        let compressed = compress_mesh_data(&original).unwrap();
        let decompressed = decompress_mesh_data(&compressed).unwrap();
        assert_eq!(original, decompressed);
    }

    #[test]
    fn test_compress_mesh_data_random_like() {
        // Test with pseudo-random data (harder to compress)
        let original: Vec<u8> = (0..1000).map(|i| ((i * 7 + 13) % 256) as u8).collect();
        let compressed = compress_mesh_data(&original).unwrap();
        let decompressed = decompress_mesh_data(&compressed).unwrap();
        assert_eq!(original, decompressed);
    }
}