embedded-3dgfx 0.3.0

3D graphics rendering for embedded systems (fork of embedded-gfx by Kezii)
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
#![no_std]
#[cfg(feature = "std")]
extern crate std;
use camera::Camera;
use embedded_graphics_core::pixelcolor::Rgb565;
use embedded_graphics_core::pixelcolor::RgbColor;
use mesh::K3dMesh;
use mesh::RenderMode;
use nalgebra::Matrix4;
use nalgebra::Point2;
use nalgebra::Point3;
use nalgebra::Vector3;

// ComplexField provides sqrt() for f32 in no_std via libm
// It appears "unused" in tests because tests use std, but it's required for no_std builds
#[allow(unused_imports)]
use nalgebra::ComplexField;

pub mod animation;
pub mod billboard;
pub mod bridge;
pub mod camera;
pub mod command_buffer;
pub mod config;
pub mod display_backend;
pub mod draw;
pub mod error;
pub mod fixed_math;
pub mod hardware_profile;
pub mod hud;
pub mod lut;
pub mod mesh;
#[cfg(feature = "std")]
pub mod painters;
#[cfg(feature = "perfcounter")]
pub mod perfcounter;
pub mod physics;
pub mod renderer;
pub mod scene_format;
pub mod scene_stream;
pub mod skeleton;
pub mod softbody;
pub mod swapchain;
pub mod telemetry;
pub mod texture;
pub mod tilebin;
pub mod transform_anim;
pub mod tween;

// Re-export framebuffer types from external crate for user convenience
pub use embedded_graphics_framebuf::{
    FrameBuf,
    backends::{DMACapableFrameBufferBackend, EndianCorrectedBuffer, EndianCorrection},
};

#[cfg(feature = "aa")]
pub use draw::ReadPixel;

pub use bridge::{
    AsEgPoint, AsNalgebraPoint, draw_to, eg_to_nalgebra, nalgebra_to_eg, render_drawable_to_buffer,
};
pub use renderer::{DirtyRegion, FrameCtx};
pub use tilebin::{TileBinStats, TileConfig};
pub use transform_anim::{AnimationPlayer, SampledTransform, TransformKeyframe, TransformTrack};
pub use tween::{Easing, Tween, Tween3, apply_easing, lerp, lerp3, scale_rgb565};

#[derive(Debug, Clone)]
pub enum DrawPrimitive {
    ColoredPoint(Point2<i32>, Rgb565),
    Line([Point2<i32>; 2], Rgb565),
    ColoredTriangle([Point2<i32>; 3], Rgb565),
    ColoredTriangleWithDepth {
        points: [Point2<i32>; 3],
        depths: [f32; 3],
        color: Rgb565,
    },
    GouraudTriangle {
        points: [Point2<i32>; 3],
        colors: [Rgb565; 3],
    },
    GouraudTriangleWithDepth {
        points: [Point2<i32>; 3],
        depths: [f32; 3],
        colors: [Rgb565; 3],
    },
    TexturedTriangle {
        points: [Point2<i32>; 3],
        uvs: [[f32; 2]; 3],
        texture_id: u32,
    },
    TexturedTriangleWithDepth {
        points: [Point2<i32>; 3],
        depths: [f32; 3],
        ws: [f32; 3],
        uvs: [[f32; 2]; 3],
        texture_id: u32,
    },
}

pub struct K3dengine {
    pub camera: Camera,
    width: u16,
    height: u16,
    caps: Option<crate::config::ProfileCaps>,
    quality_tier: crate::config::QualityTier,
    material_profile: crate::config::MaterialProfile,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BudgetFallbackOutcome {
    pub used_fallback: bool,
    pub primary_budget_error: Option<crate::error::BudgetKind>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DegradationOutcome {
    pub used_degradation: bool,
    pub steps_applied: usize,
    pub dropped_meshes: usize,
    pub final_quality_tier: crate::config::QualityTier,
    pub primary_budget_error: Option<crate::error::BudgetKind>,
}

impl K3dengine {
    pub fn new(width: u16, height: u16) -> K3dengine {
        K3dengine {
            camera: Camera::new(width as f32 / height as f32),
            width,
            height,
            caps: None,
            quality_tier: crate::config::QualityTier::Balanced,
            material_profile: crate::config::MaterialProfile::Lambert,
        }
    }

    pub fn set_caps(&mut self, caps: crate::config::ProfileCaps) {
        self.caps = Some(caps);
        self.apply_render_defaults(crate::config::render_defaults_for_profile(caps));
    }

    pub fn clear_caps(&mut self) {
        self.caps = None;
    }

    pub fn set_quality_tier(&mut self, tier: crate::config::QualityTier) {
        self.quality_tier = tier;
    }

    pub fn set_material_profile(&mut self, profile: crate::config::MaterialProfile) {
        self.material_profile = profile;
    }

    pub fn apply_render_defaults(&mut self, defaults: crate::config::RenderDefaults) {
        self.quality_tier = defaults.quality_tier;
        self.material_profile = defaults.material_profile;
    }

    fn resolve_render_mode(&self, mode: &RenderMode) -> RenderMode {
        use crate::config::{MaterialProfile, QualityTier};
        match self.quality_tier {
            QualityTier::Fastest => match mode {
                RenderMode::BlinnPhong { .. }
                | RenderMode::GouraudLightDir(_)
                | RenderMode::SolidLightDir(_) => RenderMode::Solid,
                _ => mode.clone(),
            },
            QualityTier::Balanced => match (self.material_profile, mode) {
                (MaterialProfile::Unlit, RenderMode::BlinnPhong { .. })
                | (MaterialProfile::Unlit, RenderMode::GouraudLightDir(_))
                | (MaterialProfile::Unlit, RenderMode::SolidLightDir(_)) => RenderMode::Solid,
                (MaterialProfile::Lambert, RenderMode::BlinnPhong { light_dir, .. }) => {
                    RenderMode::SolidLightDir(light_dir.clone())
                }
                _ => mode.clone(),
            },
            QualityTier::Quality => match (self.material_profile, mode) {
                (MaterialProfile::Unlit, RenderMode::BlinnPhong { .. })
                | (MaterialProfile::Unlit, RenderMode::GouraudLightDir(_))
                | (MaterialProfile::Unlit, RenderMode::SolidLightDir(_)) => RenderMode::Solid,
                (MaterialProfile::Lambert, RenderMode::BlinnPhong { light_dir, .. }) => {
                    RenderMode::SolidLightDir(light_dir.clone())
                }
                _ => mode.clone(),
            },
        }
    }

    /// Fast frustum culling check using bounding sphere.
    /// Returns true if the mesh should be culled (not rendered).
    #[inline]
    fn should_cull_mesh(&self, mesh: &K3dMesh) -> bool {
        // Get mesh position in world space
        let mesh_pos = mesh.get_position();

        // Compute distance from camera to mesh center
        let to_mesh = mesh_pos - self.camera.position;
        let distance = to_mesh.norm(); // Uses libm sqrt via nalgebra

        // Get squared bounding radius and compute radius
        // This is only called once per mesh, not in the inner loop
        let radius_sq = mesh.compute_bounding_radius_sq();
        let radius = radius_sq.sqrt(); // Uses libm sqrt (one call per mesh is acceptable)

        // Far plane culling: mesh sphere is entirely beyond far plane
        if distance - radius > self.camera.far {
            return true;
        }

        // Near plane culling: mesh sphere is entirely before near plane
        if distance + radius < self.camera.near {
            return true;
        }

        // Passed culling tests - render the mesh
        false
    }

    #[inline(always)]
    fn transform_point(&self, point: &[f32; 3], model_matrix: Matrix4<f32>) -> Option<Point3<i32>> {
        #[cfg(feature = "fixed-transform")]
        {
            return self.transform_point_fixed(point, model_matrix);
        }
        #[cfg(not(feature = "fixed-transform"))]
        {
            let point = nalgebra::Vector4::new(point[0], point[1], point[2], 1.0);
            let point = model_matrix * point;

            if point.w < 0.0 {
                return None;
            }
            if point.z < self.camera.near || point.z > self.camera.far {
                return None;
            }

            let point = Point3::from_homogeneous(point)?;

            let x = ((1.0 + point.x) * 0.5 * self.width as f32) as i32;
            let y = ((1.0 - point.y) * 0.5 * self.height as f32) as i32;

            if x < 0 || x >= self.width as i32 || y < 0 || y >= self.height as i32 {
                return None;
            }

            Some(Point3::new(
                x,
                y,
                (point.z * (self.camera.far - self.camera.near) + self.camera.near) as i32,
            ))
        }
    }

    #[cfg(feature = "fixed-transform")]
    #[inline(always)]
    fn transform_point_fixed(
        &self,
        point: &[f32; 3],
        model_matrix: Matrix4<f32>,
    ) -> Option<Point3<i32>> {
        use crate::fixed_math::{div_fp, from_fp, to_fp};

        let point = nalgebra::Vector4::new(point[0], point[1], point[2], 1.0);
        let point = model_matrix * point;

        if point.w <= 0.0 {
            return None;
        }

        let x_fp = div_fp(to_fp(point.x), to_fp(point.w))?;
        let y_fp = div_fp(to_fp(point.y), to_fp(point.w))?;
        let z_ndc = from_fp(div_fp(to_fp(point.z), to_fp(point.w))?);
        if z_ndc < self.camera.near || z_ndc > self.camera.far {
            return None;
        }

        let x = ((1.0 + from_fp(x_fp)) * 0.5 * self.width as f32) as i32;
        let y = ((1.0 - from_fp(y_fp)) * 0.5 * self.height as f32) as i32;

        if x < 0 || x >= self.width as i32 || y < 0 || y >= self.height as i32 {
            return None;
        }

        Some(Point3::new(
            x,
            y,
            (z_ndc * (self.camera.far - self.camera.near) + self.camera.near) as i32,
        ))
    }

    #[inline(always)]
    pub fn transform_points<const N: usize>(
        &self,
        indices: &[usize; N],
        vertices: &[[f32; 3]],
        model_matrix: Matrix4<f32>,
    ) -> Option<[Point3<i32>; N]> {
        let mut ret = [Point3::new(0, 0, 0); N];

        for i in 0..N {
            ret[i] = self.transform_point(&vertices[indices[i]], model_matrix)?;
        }

        Some(ret)
    }

    /// Like `transform_point` but also returns the clip-space W for perspective-correct interpolation.
    /// Returns (screen_point, w_clip). w_clip is the clip-space W before perspective division.
    fn transform_point_with_w(
        &self,
        point: &[f32; 3],
        model_matrix: Matrix4<f32>,
    ) -> Option<(Point3<i32>, f32)> {
        let v = nalgebra::Vector4::new(point[0], point[1], point[2], 1.0);
        let clip = model_matrix * v;
        if clip.w <= 0.0 {
            return None;
        }
        let ndc_x = clip.x / clip.w;
        let ndc_y = clip.y / clip.w;
        let ndc_z = clip.z / clip.w;
        if ndc_z < self.camera.near || ndc_z > self.camera.far {
            return None;
        }
        let x = ((1.0 + ndc_x) * 0.5 * self.width as f32) as i32;
        let y = ((1.0 - ndc_y) * 0.5 * self.height as f32) as i32;
        if x < 0 || x >= self.width as i32 || y < 0 || y >= self.height as i32 {
            return None;
        }
        let z = (ndc_z * (self.camera.far - self.camera.near) + self.camera.near) as i32;
        Some((Point3::new(x, y, z), clip.w))
    }

    /// Like `transform_points` but also returns clip-space W values for perspective-correct UV.
    #[inline(always)]
    pub fn transform_points_with_w<const N: usize>(
        &self,
        indices: &[usize; N],
        vertices: &[[f32; 3]],
        model_matrix: Matrix4<f32>,
    ) -> Option<([Point3<i32>; N], [f32; N])> {
        let mut pts = [Point3::new(0, 0, 0); N];
        let mut ws = [1.0f32; N];
        for i in 0..N {
            let (p, w) = self.transform_point_with_w(&vertices[indices[i]], model_matrix)?;
            pts[i] = p;
            ws[i] = w;
        }
        Some((pts, ws))
    }

    fn render<'a, MS, F>(&self, meshes: MS, mut callback: F)
    where
        MS: IntoIterator<Item = &'a K3dMesh<'a>>,
        F: FnMut(DrawPrimitive),
    {
        for mesh in meshes {
            if mesh.geometry.vertices.is_empty() {
                continue;
            }

            // Frustum culling: Skip meshes that are completely outside the view frustum
            // This can improve performance by 50-90% by avoiding transformation and rendering
            // of off-screen objects
            if self.should_cull_mesh(mesh) {
                continue;
            }

            // LOD Selection: Choose geometry based on distance from camera
            let mesh_pos = mesh.get_position();
            let distance = (mesh_pos - self.camera.position).norm();
            let geometry = mesh.select_lod(distance);

            let transform_matrix = self.camera.vp_matrix * mesh.model_matrix;

            let render_mode = self.resolve_render_mode(&mesh.render_mode);
            match render_mode {
                RenderMode::Points => {
                    let screen_space_points = geometry
                        .vertices
                        .iter()
                        .filter_map(|v| self.transform_point(v, transform_matrix));

                    if geometry.colors.len() == geometry.vertices.len() {
                        for (point, color) in screen_space_points.zip(geometry.colors) {
                            callback(DrawPrimitive::ColoredPoint(point.xy(), *color));
                        }
                    } else {
                        for point in screen_space_points {
                            callback(DrawPrimitive::ColoredPoint(point.xy(), mesh.color));
                        }
                    }
                }

                RenderMode::Lines if !geometry.lines.is_empty() => {
                    for line in geometry.lines {
                        if let Some([p1, p2]) =
                            self.transform_points(line, geometry.vertices, transform_matrix)
                        {
                            callback(DrawPrimitive::Line([p1.xy(), p2.xy()], mesh.color));
                        }
                    }
                }

                RenderMode::Lines if !geometry.faces.is_empty() => {
                    for face in geometry.faces {
                        if let Some([p1, p2, p3]) =
                            self.transform_points(face, geometry.vertices, transform_matrix)
                        {
                            callback(DrawPrimitive::Line([p1.xy(), p2.xy()], mesh.color));
                            callback(DrawPrimitive::Line([p2.xy(), p3.xy()], mesh.color));
                            callback(DrawPrimitive::Line([p3.xy(), p1.xy()], mesh.color));
                        }
                    }
                }

                RenderMode::Lines => {}

                RenderMode::SolidLightDir(direction) => {
                    // Pre-compute lighting constants (once per mesh, not per face)
                    // This optimization reduces redundant calculations in the inner loop
                    let color_as_float = Vector3::new(
                        mesh.color.r() as f32 / 32.0,
                        mesh.color.g() as f32 / 64.0,
                        mesh.color.b() as f32 / 32.0,
                    );

                    // Pre-compute ambient lighting term
                    let ambient_color = color_as_float * 0.1;

                    // Pre-compute adjusted light direction
                    // Negate only Z component of direction to fix front/back while keeping left/right
                    let adjusted_dir = Vector3::new(direction.x, direction.y, -direction.z);

                    for (face, normal) in geometry.faces.iter().zip(geometry.normals.iter()) {
                        //Backface culling
                        let normal = Vector3::new(normal[0], normal[1], normal[2]);

                        let transformed_normal = mesh.model_matrix.transform_vector(&normal);

                        // Backface culling: cull faces pointing away from camera
                        // This improves performance by ~50% (don't render back faces)
                        // Z-buffer handles depth ordering, but culling avoids wasted work
                        if self.camera.get_direction().dot(&transformed_normal) < 0.0 {
                            continue;
                        }

                        if let Some([p1, p2, p3]) =
                            self.transform_points(face, geometry.vertices, transform_matrix)
                        {
                            // Calculate lighting intensity
                            let intensity = transformed_normal.dot(&adjusted_dir).max(0.0);

                            // Compute final color using pre-computed constants
                            let final_color = color_as_float * intensity + ambient_color;

                            let final_color = Vector3::new(
                                final_color.x.clamp(0.0, 1.0),
                                final_color.y.clamp(0.0, 1.0),
                                final_color.z.clamp(0.0, 1.0),
                            );

                            let color = Rgb565::new(
                                (final_color.x * 31.0) as u8,
                                (final_color.y * 63.0) as u8,
                                (final_color.z * 31.0) as u8,
                            );
                            callback(DrawPrimitive::ColoredTriangleWithDepth {
                                points: [p1.xy(), p2.xy(), p3.xy()],
                                depths: [p1.z as f32, p2.z as f32, p3.z as f32],
                                color,
                            });
                        }
                    }
                }

                RenderMode::GouraudLightDir(direction) => {
                    let color_as_float = Vector3::new(
                        mesh.color.r() as f32 / 32.0,
                        mesh.color.g() as f32 / 64.0,
                        mesh.color.b() as f32 / 32.0,
                    );
                    let ambient_color = color_as_float * 0.1;
                    let adjusted_dir = Vector3::new(direction.x, direction.y, -direction.z);

                    for (face, face_normal) in geometry.faces.iter().zip(geometry.normals.iter()) {
                        let fn_vec = Vector3::new(face_normal[0], face_normal[1], face_normal[2]);
                        let transformed_fn = mesh.model_matrix.transform_vector(&fn_vec);

                        if self.camera.get_direction().dot(&transformed_fn) < 0.0 {
                            continue;
                        }

                        if let Some([p1, p2, p3]) =
                            self.transform_points(face, geometry.vertices, transform_matrix)
                        {
                            // Compute per-vertex colors
                            let vertex_colors: [Rgb565; 3] = core::array::from_fn(|k| {
                                let vn = if !geometry.vertex_normals.is_empty() {
                                    let vn_arr = geometry.vertex_normals[face[k]];
                                    let vn_vec = Vector3::new(vn_arr[0], vn_arr[1], vn_arr[2]);
                                    mesh.model_matrix.transform_vector(&vn_vec)
                                } else {
                                    transformed_fn
                                };

                                let intensity = vn.dot(&adjusted_dir).max(0.0);
                                let c = color_as_float * intensity + ambient_color;
                                Rgb565::new(
                                    (c.x.clamp(0.0, 1.0) * 31.0) as u8,
                                    (c.y.clamp(0.0, 1.0) * 63.0) as u8,
                                    (c.z.clamp(0.0, 1.0) * 31.0) as u8,
                                )
                            });

                            callback(DrawPrimitive::GouraudTriangleWithDepth {
                                points: [p1.xy(), p2.xy(), p3.xy()],
                                depths: [p1.z as f32, p2.z as f32, p3.z as f32],
                                colors: vertex_colors,
                            });
                        }
                    }
                }

                RenderMode::BlinnPhong {
                    light_dir,
                    specular_intensity,
                    shininess,
                } => {
                    // Pre-compute lighting constants (once per mesh, not per face)
                    let color_as_float = Vector3::new(
                        mesh.color.r() as f32 / 32.0,
                        mesh.color.g() as f32 / 64.0,
                        mesh.color.b() as f32 / 32.0,
                    );

                    // Pre-compute ambient lighting term
                    let ambient_color = color_as_float * 0.1;

                    // Pre-compute adjusted light direction
                    // Negate only Z component of direction to fix front/back while keeping left/right
                    let adjusted_light_dir = Vector3::new(light_dir.x, light_dir.y, -light_dir.z);

                    // Normalize light direction
                    let light_dir_normalized = adjusted_light_dir.normalize();

                    for (face, normal) in geometry.faces.iter().zip(geometry.normals.iter()) {
                        //Backface culling
                        let normal = Vector3::new(normal[0], normal[1], normal[2]);
                        let transformed_normal = mesh.model_matrix.transform_vector(&normal);
                        let normalized_normal = transformed_normal.normalize();

                        // Backface culling: cull faces pointing away from camera
                        if self.camera.get_direction().dot(&normalized_normal) < 0.0 {
                            continue;
                        }

                        if let Some([p1, p2, p3]) =
                            self.transform_points(face, geometry.vertices, transform_matrix)
                        {
                            // Calculate face center in world space for view direction
                            let v0 = geometry.vertices[face[0]];
                            let v1 = geometry.vertices[face[1]];
                            let v2 = geometry.vertices[face[2]];
                            let face_center = Point3::new(
                                (v0[0] + v1[0] + v2[0]) / 3.0,
                                (v0[1] + v1[1] + v2[1]) / 3.0,
                                (v0[2] + v1[2] + v2[2]) / 3.0,
                            );
                            let face_center_world = mesh.model_matrix.transform_point(&face_center);

                            // View direction: from face to camera
                            let view_dir = (self.camera.position - face_center_world).normalize();

                            // Blinn-Phong half vector: H = normalize(L + V)
                            let half_vector = (light_dir_normalized + view_dir).normalize();

                            // Diffuse term: N·L
                            let diffuse_intensity =
                                normalized_normal.dot(&light_dir_normalized).max(0.0);

                            // Specular term: (N·H)^shininess
                            let specular_term =
                                normalized_normal.dot(&half_vector).max(0.0).powf(shininess);

                            // Compute final color: ambient + diffuse + specular
                            let diffuse_color = color_as_float * diffuse_intensity;
                            let specular_color =
                                Vector3::new(1.0, 1.0, 1.0) * specular_term * specular_intensity;
                            let final_color = ambient_color + diffuse_color + specular_color;

                            let final_color = Vector3::new(
                                final_color.x.clamp(0.0, 1.0),
                                final_color.y.clamp(0.0, 1.0),
                                final_color.z.clamp(0.0, 1.0),
                            );

                            let color = Rgb565::new(
                                (final_color.x * 31.0) as u8,
                                (final_color.y * 63.0) as u8,
                                (final_color.z * 31.0) as u8,
                            );
                            callback(DrawPrimitive::ColoredTriangleWithDepth {
                                points: [p1.xy(), p2.xy(), p3.xy()],
                                depths: [p1.z as f32, p2.z as f32, p3.z as f32],
                                color,
                            });
                        }
                    }
                }

                RenderMode::Solid => {
                    if geometry.normals.is_empty() {
                        for face in geometry.faces.iter() {
                            if let Some([p1, p2, p3]) =
                                self.transform_points(face, geometry.vertices, transform_matrix)
                            {
                                callback(DrawPrimitive::ColoredTriangleWithDepth {
                                    points: [p1.xy(), p2.xy(), p3.xy()],
                                    depths: [p1.z as f32, p2.z as f32, p3.z as f32],
                                    color: mesh.color,
                                });
                            }
                        }
                    } else {
                        for (face, normal) in geometry.faces.iter().zip(geometry.normals) {
                            //Backface culling
                            let normal = Vector3::new(normal[0], normal[1], normal[2]);

                            let transformed_normal = mesh.model_matrix.transform_vector(&normal);

                            // Backface culling: cull faces pointing away from camera
                            if self.camera.get_direction().dot(&transformed_normal) < 0.0 {
                                continue;
                            }

                            if let Some([p1, p2, p3]) =
                                self.transform_points(face, geometry.vertices, transform_matrix)
                            {
                                callback(DrawPrimitive::ColoredTriangleWithDepth {
                                    points: [p1.xy(), p2.xy(), p3.xy()],
                                    depths: [p1.z as f32, p2.z as f32, p3.z as f32],
                                    color: mesh.color,
                                });
                            }
                        }
                    }
                }

                RenderMode::SectorBright(brightness) => {
                    // Scale mesh color by brightness factor (Doom-style sector lighting)
                    let factor = brightness as f32 / 255.0;
                    let scaled_r = (mesh.color.r() as f32 * factor) as u8;
                    let scaled_g = (mesh.color.g() as f32 * factor) as u8;
                    let scaled_b = (mesh.color.b() as f32 * factor) as u8;
                    let scaled_color = Rgb565::new(scaled_r, scaled_g, scaled_b);

                    if geometry.normals.is_empty() {
                        for face in geometry.faces.iter() {
                            if let Some([p1, p2, p3]) =
                                self.transform_points(face, geometry.vertices, transform_matrix)
                            {
                                callback(DrawPrimitive::ColoredTriangleWithDepth {
                                    points: [p1.xy(), p2.xy(), p3.xy()],
                                    depths: [p1.z as f32, p2.z as f32, p3.z as f32],
                                    color: scaled_color,
                                });
                            }
                        }
                    } else {
                        for (face, normal) in geometry.faces.iter().zip(geometry.normals) {
                            // Backface culling
                            let normal = Vector3::new(normal[0], normal[1], normal[2]);
                            let transformed_normal = mesh.model_matrix.transform_vector(&normal);

                            if self.camera.get_direction().dot(&transformed_normal) < 0.0 {
                                continue;
                            }

                            if let Some([p1, p2, p3]) =
                                self.transform_points(face, geometry.vertices, transform_matrix)
                            {
                                callback(DrawPrimitive::ColoredTriangleWithDepth {
                                    points: [p1.xy(), p2.xy(), p3.xy()],
                                    depths: [p1.z as f32, p2.z as f32, p3.z as f32],
                                    color: scaled_color,
                                });
                            }
                        }
                    }
                }
            }
        }
    }

    pub fn record<'a, MS, const MAX: usize>(
        &self,
        meshes: MS,
        commands: &mut crate::command_buffer::CommandBuffer<MAX>,
        telemetry: Option<&mut crate::telemetry::RecordTelemetry>,
    ) -> Result<(), crate::error::RenderError>
    where
        MS: IntoIterator<Item = &'a K3dMesh<'a>>,
    {
        self.record_impl(meshes, commands, telemetry)
    }

    fn record_impl<'a, MS, const MAX: usize>(
        &self,
        meshes: MS,
        commands: &mut crate::command_buffer::CommandBuffer<MAX>,
        telemetry: Option<&mut crate::telemetry::RecordTelemetry>,
    ) -> Result<(), crate::error::RenderError>
    where
        MS: IntoIterator<Item = &'a K3dMesh<'a>>,
    {
        use crate::command_buffer::RenderCommand;
        use crate::error::{BudgetKind, RenderError};

        commands.clear();
        commands.push(RenderCommand::ClearDepth(u32::MAX))?;
        if let Some(caps) = self.caps {
            caps.validate_framebuffer(self.width as usize, self.height as usize)?;
        }

        let mut first_error = None;
        let mut visible_meshes = 0usize;
        let mut used_texture_ids: heapless::Vec<u32, 64> = heapless::Vec::new();
        let mut meshes_total = 0usize;

        for mesh in meshes {
            meshes_total += 1;
            if mesh.geometry.vertices.is_empty() {
                continue;
            }
            if self.should_cull_mesh(mesh) {
                continue;
            }

            let distance = (mesh.get_position() - self.camera.position).norm();
            let geometry = mesh.select_lod(distance);

            if let Some(caps) = self.caps {
                visible_meshes += 1;
                if visible_meshes > caps.max_meshes_per_frame {
                    return Err(RenderError::OutOfBudget(BudgetKind::MeshesPerFrame {
                        attempted: visible_meshes,
                        max: caps.max_meshes_per_frame,
                    }));
                }

                if geometry.vertices.len() > caps.max_vertices_per_mesh {
                    return Err(RenderError::OutOfBudget(BudgetKind::VerticesPerMesh {
                        attempted: geometry.vertices.len(),
                        max: caps.max_vertices_per_mesh,
                    }));
                }

                if geometry.faces.len() > caps.max_triangles_per_mesh {
                    return Err(RenderError::OutOfBudget(BudgetKind::TrianglesPerMesh {
                        attempted: geometry.faces.len(),
                        max: caps.max_triangles_per_mesh,
                    }));
                }

                if let Some(texture_id) = geometry.texture_id
                    && !used_texture_ids.iter().any(|id| *id == texture_id)
                {
                    let attempted = used_texture_ids.len() + 1;
                    if attempted > caps.max_textures {
                        return Err(RenderError::OutOfBudget(BudgetKind::Textures {
                            attempted,
                            max: caps.max_textures,
                        }));
                    }

                    if used_texture_ids.push(texture_id).is_err() {
                        return Err(RenderError::OutOfBudget(BudgetKind::Textures {
                            attempted,
                            max: caps.max_textures,
                        }));
                    }
                }
            }

            self.render(core::iter::once(mesh), |primitive| {
                if first_error.is_none()
                    && let Err(e) = commands.push(RenderCommand::Draw(primitive))
                {
                    first_error = Some(e);
                }
            });
            if let Some(err) = first_error {
                return Err(err);
            }
        }

        if let Some(t) = telemetry {
            t.meshes_total = meshes_total;
            t.meshes_visible = visible_meshes;
            t.unique_textures = used_texture_ids.len();
            t.draw_commands = commands
                .iter()
                .filter(|cmd| matches!(cmd, RenderCommand::Draw(_)))
                .count();
            t.fallback_used = false;
            t.degradation_steps_applied = 0;
            t.dropped_meshes = 0;
        }

        Ok(())
    }

    pub fn record_with_fallback<'a, MS, FS, const MAX: usize>(
        &self,
        primary: MS,
        fallback: FS,
        commands: &mut crate::command_buffer::CommandBuffer<MAX>,
        telemetry: Option<&mut crate::telemetry::RecordTelemetry>,
    ) -> Result<BudgetFallbackOutcome, crate::error::RenderError>
    where
        MS: IntoIterator<Item = &'a K3dMesh<'a>>,
        FS: IntoIterator<Item = &'a K3dMesh<'a>>,
    {
        use crate::error::RenderError;

        let mut local_telemetry = crate::telemetry::RecordTelemetry::default();
        match self.record_impl(primary, commands, Some(&mut local_telemetry)) {
            Ok(()) => {
                if let Some(t) = telemetry {
                    *t = local_telemetry;
                    t.fallback_used = false;
                }
                Ok(BudgetFallbackOutcome {
                    used_fallback: false,
                    primary_budget_error: None,
                })
            }
            Err(RenderError::OutOfBudget(kind)) => {
                let mut fallback_telemetry = crate::telemetry::RecordTelemetry::default();
                self.record_impl(fallback, commands, Some(&mut fallback_telemetry))?;
                if let Some(t) = telemetry {
                    *t = fallback_telemetry;
                    t.fallback_used = true;
                }
                Ok(BudgetFallbackOutcome {
                    used_fallback: true,
                    primary_budget_error: Some(kind),
                })
            }
            Err(e) => Err(e),
        }
    }

    fn downgraded_quality_tier(tier: crate::config::QualityTier) -> crate::config::QualityTier {
        use crate::config::QualityTier;
        match tier {
            QualityTier::Quality => QualityTier::Balanced,
            QualityTier::Balanced => QualityTier::Fastest,
            QualityTier::Fastest => QualityTier::Fastest,
        }
    }

    pub fn record_with_degradation<'a, const MAX: usize>(
        &mut self,
        meshes: &[&'a K3dMesh<'a>],
        commands: &mut crate::command_buffer::CommandBuffer<MAX>,
        policy: crate::config::DegradationPolicy<'_>,
        telemetry: Option<&mut crate::telemetry::RecordTelemetry>,
    ) -> Result<DegradationOutcome, crate::error::RenderError> {
        use crate::config::DegradationStep;
        use crate::error::RenderError;

        let original_quality = self.quality_tier;
        let mut active_quality = self.quality_tier;

        let mut outcome = DegradationOutcome {
            used_degradation: false,
            steps_applied: 0,
            dropped_meshes: 0,
            final_quality_tier: active_quality,
            primary_budget_error: None,
        };

        let mut local_telemetry = crate::telemetry::RecordTelemetry::default();
        match self.record_impl(meshes.iter().copied(), commands, Some(&mut local_telemetry)) {
            Ok(()) => {
                if let Some(t) = telemetry {
                    *t = local_telemetry;
                }
                return Ok(outcome);
            }
            Err(RenderError::OutOfBudget(kind)) => {
                outcome.primary_budget_error = Some(kind);
            }
            Err(e) => return Err(e),
        }

        for step in policy.steps {
            outcome.used_degradation = true;
            outcome.steps_applied += 1;

            let mut selected: heapless::Vec<&K3dMesh<'_>, 512> = heapless::Vec::new();
            match *step {
                DegradationStep::RaisePriorityFloor(min_priority) => {
                    for mesh in meshes {
                        if mesh.priority >= min_priority {
                            let _ = selected.push(*mesh);
                        } else {
                            outcome.dropped_meshes += 1;
                        }
                    }
                }
                DegradationStep::MeshDecimationStride(stride) => {
                    if stride == 0 {
                        self.quality_tier = original_quality;
                        return Err(RenderError::InvalidInput(
                            "mesh decimation stride must be >= 1",
                        ));
                    }
                    for (idx, mesh) in meshes.iter().enumerate() {
                        if idx % stride == 0 {
                            let _ = selected.push(*mesh);
                        } else {
                            outcome.dropped_meshes += 1;
                        }
                    }
                }
                DegradationStep::DowngradeQuality => {
                    active_quality = Self::downgraded_quality_tier(active_quality);
                    self.quality_tier = active_quality;
                    for mesh in meshes {
                        let _ = selected.push(*mesh);
                    }
                }
            }

            if selected.is_empty() {
                continue;
            }

            let mut step_telemetry = crate::telemetry::RecordTelemetry::default();
            let attempt = self.record_impl(
                selected.iter().copied(),
                commands,
                Some(&mut step_telemetry),
            );

            if let Ok(()) = attempt {
                outcome.final_quality_tier = self.quality_tier;
                if let Some(t) = telemetry {
                    *t = step_telemetry;
                    t.fallback_used = true;
                    t.degradation_steps_applied = outcome.steps_applied;
                    t.dropped_meshes = outcome.dropped_meshes;
                }
                self.quality_tier = original_quality;
                return Ok(outcome);
            }
        }

        self.quality_tier = original_quality;
        Err(crate::error::RenderError::Recoverable {
            fault: crate::error::RuntimeFaultKind::Budget(outcome.primary_budget_error.unwrap_or(
                crate::error::BudgetKind::DrawPrimitives {
                    attempted: commands.len(),
                    max: MAX,
                },
            )),
            action: crate::error::RecoveryAction::SkipFrame,
        })
    }

    pub fn execute<D, const MAX: usize>(
        &self,
        fb: &mut D,
        frame: &mut crate::renderer::FrameCtx<'_>,
        commands: &crate::command_buffer::CommandBuffer<MAX>,
        telemetry: Option<&mut crate::telemetry::ExecuteTelemetry>,
    ) -> Result<Option<crate::renderer::DirtyRegion>, crate::error::RenderError>
    where
        D: embedded_graphics_core::draw_target::DrawTarget<Color = Rgb565>
            + embedded_graphics_core::prelude::OriginDimensions,
        <D as embedded_graphics_core::draw_target::DrawTarget>::Error: core::fmt::Debug,
    {
        if let Some(t) = telemetry {
            t.commands_total = commands.len();
            t.draw_commands = commands
                .iter()
                .filter(|cmd| matches!(cmd, crate::command_buffer::RenderCommand::Draw(_)))
                .count();
            t.clear_color_commands = commands
                .iter()
                .filter(|cmd| matches!(cmd, crate::command_buffer::RenderCommand::ClearColor(_)))
                .count();
            t.clear_depth_commands = commands
                .iter()
                .filter(|cmd| matches!(cmd, crate::command_buffer::RenderCommand::ClearDepth(_)))
                .count();
        }
        crate::renderer::execute_commands_with_dirty_region(fb, frame, commands)
    }

    pub fn execute_tiled<D, const MAX: usize, const BIN_CAP: usize>(
        &self,
        fb: &mut D,
        frame: &mut crate::renderer::FrameCtx<'_>,
        commands: &crate::command_buffer::CommandBuffer<MAX>,
        tile: crate::tilebin::TileConfig,
    ) -> Result<crate::tilebin::TileBinStats, crate::error::RenderError>
    where
        D: embedded_graphics_core::draw_target::DrawTarget<Color = Rgb565>
            + embedded_graphics_core::prelude::OriginDimensions,
        <D as embedded_graphics_core::draw_target::DrawTarget>::Error: core::fmt::Debug,
    {
        crate::renderer::execute_commands_tiled::<D, MAX, BIN_CAP>(fb, frame, commands, tile)
    }
}

/// Result of a ray cast against triangle geometry.
#[derive(Debug, Clone, Copy)]
pub struct MeshRayCastHit {
    /// Distance along the ray to the hit point
    pub distance: f32,
    /// Hit point in world space
    pub point: Vector3<f32>,
    /// Face normal (from cross product of edges, not per-vertex normals)
    pub normal: Vector3<f32>,
    /// Index of the triangle face that was hit
    pub face_index: usize,
    /// Barycentric-interpolated UV at the hit point (or [0.0, 0.0] if no UVs present)
    pub uv: [f32; 2],
}

/// Ray-cast against triangle geometry using Möller–Trumbore intersection.
///
/// `ray_origin` and `ray_dir` are in world space. `model_matrix` transforms mesh
/// vertices to world space. Returns the closest hit within `max_distance`, or `None`.
pub fn mesh_ray_cast(
    ray_origin: Vector3<f32>,
    ray_dir: Vector3<f32>,
    geometry: &mesh::Geometry<'_>,
    model_matrix: &Matrix4<f32>,
    max_distance: f32,
) -> Option<MeshRayCastHit> {
    let mut nearest: Option<MeshRayCastHit> = None;
    let mut min_dist = max_distance;

    for (face_index, face) in geometry.faces.iter().enumerate() {
        let raw_v0 = geometry.vertices[face[0]];
        let raw_v1 = geometry.vertices[face[1]];
        let raw_v2 = geometry.vertices[face[2]];

        // Transform vertices to world space
        let v0 = model_matrix
            .transform_point(&Point3::new(raw_v0[0], raw_v0[1], raw_v0[2]))
            .coords;
        let v1 = model_matrix
            .transform_point(&Point3::new(raw_v1[0], raw_v1[1], raw_v1[2]))
            .coords;
        let v2 = model_matrix
            .transform_point(&Point3::new(raw_v2[0], raw_v2[1], raw_v2[2]))
            .coords;

        // Möller–Trumbore
        let edge1 = v1 - v0;
        let edge2 = v2 - v0;
        let h = ray_dir.cross(&edge2);
        let det = edge1.dot(&h);

        // Parallel ray: skip
        if det.abs() < 1e-6 {
            continue;
        }

        let inv_det = 1.0 / det;
        let s = ray_origin - v0;
        let bary_u = inv_det * s.dot(&h);
        if bary_u < 0.0 || bary_u > 1.0 {
            continue;
        }

        let q = s.cross(&edge1);
        let bary_v = inv_det * ray_dir.dot(&q);
        if bary_v < 0.0 || bary_u + bary_v > 1.0 {
            continue;
        }

        let t = inv_det * edge2.dot(&q);
        if t <= 0.0 || t >= min_dist {
            continue;
        }

        // Face normal from edge cross product
        let normal = edge1.cross(&edge2).normalize();

        // Barycentric weights: w0 = 1 - u - v, w1 = u, w2 = v
        let bary_w = 1.0 - bary_u - bary_v;

        // Interpolate UV if available
        let uv = if geometry.uvs.len() > face[0]
            && geometry.uvs.len() > face[1]
            && geometry.uvs.len() > face[2]
        {
            let uv0 = geometry.uvs[face[0]];
            let uv1 = geometry.uvs[face[1]];
            let uv2 = geometry.uvs[face[2]];
            [
                bary_w * uv0[0] + bary_u * uv1[0] + bary_v * uv2[0],
                bary_w * uv0[1] + bary_u * uv1[1] + bary_v * uv2[1],
            ]
        } else {
            [0.0, 0.0]
        };

        let point = ray_origin + ray_dir * t;
        min_dist = t;
        nearest = Some(MeshRayCastHit {
            distance: t,
            point,
            normal,
            face_index,
            uv,
        });
    }

    nearest
}

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

    #[test]
    fn test_engine_creation() {
        let engine = K3dengine::new(640, 480);
        assert_eq!(engine.width, 640);
        assert_eq!(engine.height, 480);
        assert!((engine.camera.get_aspect_ratio() - 640.0 / 480.0).abs() < 0.001);
    }

    #[test]
    fn test_transform_point_basic() {
        let engine = K3dengine::new(640, 480);
        // Use camera's VP matrix directly
        let transform_matrix = engine.camera.vp_matrix;

        // Point in front of default camera, within view frustum
        // Default camera is at origin looking at origin, so we need a point in front
        let point = [0.0, 0.0, -5.0];
        let result = engine.transform_point(&point, transform_matrix);

        if let Some(transformed) = result {
            // Should be within screen bounds
            assert!(transformed.x >= 0 && transformed.x < 640);
            assert!(transformed.y >= 0 && transformed.y < 480);
        }
        // If None, the point was culled which is also valid behavior
    }

    #[test]
    fn test_transform_point_clamps_out_of_bounds() {
        let engine = K3dengine::new(640, 480);
        let model_matrix = nalgebra::Matrix4::identity();

        // Point way outside the viewport should be clamped/rejected
        let point = [100.0, 100.0, -5.0];
        let result = engine.transform_point(&point, model_matrix);
        // Should return None because coordinates are clamped out
        assert!(result.is_none());
    }

    #[test]
    fn test_transform_point_behind_camera() {
        let engine = K3dengine::new(640, 480);
        let transform_matrix = engine.camera.vp_matrix;

        // Point with positive z (behind default camera orientation)
        let point = [0.0, 0.0, 1.0];
        let _result = engine.transform_point(&point, transform_matrix);
        // Point behind camera or outside frustum should return None
        // (actual behavior depends on camera setup and projection)
        // This test just verifies the function doesn't panic
    }

    #[test]
    fn test_transform_point_near_plane_clipping() {
        let engine = K3dengine::new(640, 480);
        let model_matrix = nalgebra::Matrix4::identity();

        // Point too close to camera (before near plane)
        let point = [0.0, 0.0, -0.01];
        let result = engine.transform_point(&point, model_matrix);
        assert!(result.is_none());
    }

    #[test]
    fn test_transform_point_far_plane_clipping() {
        let engine = K3dengine::new(640, 480);
        let model_matrix = nalgebra::Matrix4::identity();

        // Point too far from camera (beyond far plane)
        let point = [0.0, 0.0, -1000.0];
        let result = engine.transform_point(&point, model_matrix);
        assert!(result.is_none());
    }

    #[test]
    fn test_transform_points_array() {
        let engine = K3dengine::new(640, 480);
        let transform_matrix = engine.camera.vp_matrix;

        let vertices = [[0.0, 0.0, -5.0], [0.1, 0.0, -5.0], [0.0, 0.1, -5.0]];
        let indices = [0, 1, 2];

        let result = engine.transform_points(&indices, &vertices, transform_matrix);

        // If transform succeeds, verify we get 3 points
        if let Some(points) = result {
            assert_eq!(points.len(), 3);
        }
        // If None, one or more points were culled which is valid
    }

    #[test]
    fn test_render_empty_faces_mesh() {
        let engine = K3dengine::new(640, 480);
        let vertices = [[0.0, 0.0, -5.0]]; // At least one vertex required
        let geometry = mesh::Geometry {
            vertices: &vertices,
            faces: &[],
            colors: &[],
            lines: &[],
            normals: &[],
            vertex_normals: &[],
            uvs: &[],
            texture_id: None,
        };
        let mesh = mesh::K3dMesh::new(geometry);

        let mut callback_count = 0;
        engine.render(std::iter::once(&mesh), |_| {
            callback_count += 1;
        });

        // Mesh with no faces/lines should trigger one point callback (default is Points mode)
        assert!(callback_count > 0);
    }

    #[test]
    fn test_render_points_mode() {
        let engine = K3dengine::new(640, 480);

        let vertices = [[0.0, 0.0, -5.0], [0.5, 0.0, -5.0]];

        let geometry = mesh::Geometry {
            vertices: &vertices,
            faces: &[],
            colors: &[],
            lines: &[],
            normals: &[],
            vertex_normals: &[],
            uvs: &[],
            texture_id: None,
        };

        let mut mesh = mesh::K3dMesh::new(geometry);
        mesh.set_render_mode(mesh::RenderMode::Points);

        let mut primitives = std::vec::Vec::new();
        engine.render(std::iter::once(&mesh), |prim| {
            primitives.push(prim);
        });

        // Should render points
        assert!(primitives.len() > 0);
        for prim in primitives {
            assert!(matches!(prim, DrawPrimitive::ColoredPoint(_, _)));
        }
    }

    #[test]
    fn test_render_lines_mode_with_faces() {
        let engine = K3dengine::new(640, 480);

        let vertices = [[0.0, 0.0, -5.0], [0.5, 0.0, -5.0], [0.0, 0.5, -5.0]];

        let faces = [[0, 1, 2]];

        let geometry = mesh::Geometry {
            vertices: &vertices,
            faces: &faces,
            colors: &[],
            lines: &[],
            normals: &[],
            vertex_normals: &[],
            uvs: &[],
            texture_id: None,
        };

        let mut mesh = mesh::K3dMesh::new(geometry);
        mesh.set_render_mode(mesh::RenderMode::Lines);

        let mut primitives = std::vec::Vec::new();
        engine.render(std::iter::once(&mesh), |prim| {
            primitives.push(prim);
        });

        // Should render 3 lines (edges of triangle)
        assert_eq!(primitives.len(), 3);
        for prim in primitives {
            assert!(matches!(prim, DrawPrimitive::Line(_, _)));
        }
    }

    #[test]
    fn test_render_gouraud_light_dir() {
        let mut engine = K3dengine::new(640, 480);
        engine.camera.set_position(Point3::new(0.0, 0.0, -10.0));
        engine.camera.set_target(Point3::new(0.0, 0.0, 0.0));

        let vertices = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]];
        let faces = [[0, 1, 2]];
        let normals = [[0.0, 0.0, -1.0]]; // face normal pointing toward camera
        let vertex_normals = [[0.0, 0.0, -1.0], [0.0, 0.0, -1.0], [0.0, 0.0, -1.0]];

        let geometry = mesh::Geometry {
            vertices: &vertices,
            faces: &faces,
            colors: &[],
            lines: &[],
            normals: &normals,
            vertex_normals: &vertex_normals,
            uvs: &[],
            texture_id: None,
        };

        let mut mesh = mesh::K3dMesh::new(geometry);
        mesh.set_render_mode(mesh::RenderMode::GouraudLightDir(Vector3::new(
            0.0, 0.0, 1.0,
        )));

        let mut primitives = std::vec::Vec::new();
        engine.render(std::iter::once(&mesh), |prim| {
            primitives.push(prim);
        });

        // Should emit GouraudTriangleWithDepth primitives
        assert!(!primitives.is_empty());
        for prim in &primitives {
            assert!(matches!(
                prim,
                DrawPrimitive::GouraudTriangleWithDepth { .. }
            ));
        }
    }
}