-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathScene.cpp
More file actions
1447 lines (1344 loc) · 67.2 KB
/
Scene.cpp
File metadata and controls
1447 lines (1344 loc) · 67.2 KB
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
#include "Scene.hpp"
#include "TrigLUT.hpp"
#include "Renderer.hpp"
#include "JetConfig.hpp"
#include <cstring> // For memset
#include <algorithm> // For std::min, std::max
#include <cmath> // For std::sqrt (per-object distance fade)
namespace Renderer {
#if LIGHTING
// Diffuse-only Lambert shading, evaluated in whatever frame N and L
// share (object-local for the precompute path below). Matches the
// diffuse branch of Renderer.cpp's jetShadeBrightness when
// specularCoef == 0: 12-bit reduce, clamp, square-falloff, scale by
// lightIntensity, scale by diffuseCoef, clamp.
//
// The specular branch is intentionally absent — this helper is only
// used for objects whose materials are ALL non-specular, which is the
// exact precondition for skipping the view-space normal transform.
// Inlining the specular branch here would mean its `N.z < 0` test
// would be reading an object-local component instead of view-space Z
// and give wrong results.
static inline uint16_t sceneLambertDiffuse(const Vector3& N, const Vector3& L,
uint16_t lightIntensity,
uint8_t diffuseCoef)
{
if (lightIntensity > 255) lightIntensity = 255;
int64_t lit = Vector3::dotProduct(N, L);
if (lit <= 0) return 0;
uint32_t lambert = (uint32_t)(lit >> 12);
if (lambert > 255) lambert = 255;
lambert = (lambert * lambert + 128) >> 8; // squared falloff
lambert = (lambert * lightIntensity) >> 8;
uint32_t diffuseTerm = (lambert * diffuseCoef) >> 8;
if (diffuseTerm > 255) diffuseTerm = 255;
return (uint16_t)diffuseTerm;
}
#endif
// Returns true if the object's AABB is entirely outside the view frustum.
bool Scene::cullObject(Object* obj,
int32_t camCosX, int32_t camSinX,
int32_t camCosY, int32_t camSinY,
int32_t camCosZ, int32_t camSinZ) const {
if (obj->isBillboard) return false; // keep billboards simple for now
Vector3 camPos(camera->position);
Vector3 objPos(obj->position);
const Vector3& bMin = obj->boundingBoxMin;
const Vector3& bMax = obj->boundingBoxMax;
int outLeft = 0, outRight = 0, outTop = 0, outBottom = 0, outNear = 0, outFar = 0;
float fovFactor = camera->fovFactor;
int32_t nearPlane = camera->nearPlane;
int32_t farPlane = camera->farPlane;
int32_t objCosX = lookupCosI(obj->rotation.x), objSinX = lookupSinI(obj->rotation.x);
int32_t objCosY = lookupCosI(obj->rotation.y), objSinY = lookupSinI(obj->rotation.y);
int32_t objCosZ = lookupCosI(obj->rotation.z), objSinZ = lookupSinI(obj->rotation.z);
for (int i = 0; i < 8; ++i) {
Vector3 p(
(i & 1) ? bMax.x : bMin.x,
(i & 2) ? bMax.y : bMin.y,
(i & 4) ? bMax.z : bMin.z);
// Object rotation (X, Y, Z) — same order as renderObject
p.assign(p.x,
(p.y * objCosX - p.z * objSinX) / FIXED_POINT_SCALE,
(p.y * objSinX + p.z * objCosX) / FIXED_POINT_SCALE);
p.assign((p.x * objCosY + p.z * objSinY) / FIXED_POINT_SCALE,
p.y,
(-p.x * objSinY + p.z * objCosY) / FIXED_POINT_SCALE);
p.assign((p.x * objCosZ - p.y * objSinZ) / FIXED_POINT_SCALE,
(p.x * objSinZ + p.y * objCosZ) / FIXED_POINT_SCALE,
p.z);
// Translation
p.add(objPos);
p.add(camPos.inverse());
// Camera rotation (Y, X, Z)
Vector3 r;
r.assign((p.x * camCosY + p.z * camSinY) / FIXED_POINT_SCALE,
p.y,
(-p.x * camSinY + p.z * camCosY) / FIXED_POINT_SCALE); p = r;
r.assign(p.x,
(p.y * camCosX - p.z * camSinX) / FIXED_POINT_SCALE,
(p.y * camSinX + p.z * camCosX) / FIXED_POINT_SCALE); p = r;
r.assign((p.x * camCosZ - p.y * camSinZ) / FIXED_POINT_SCALE,
(p.x * camSinZ + p.y * camCosZ) / FIXED_POINT_SCALE,
p.z); p = r;
if (p.z < nearPlane) { outNear++; continue; }
if (p.z > farPlane) { outFar++; continue; }
if (p.z <= 0) { outNear++; continue; }
const float invZ = fovFactor / (float)p.z;
int32_t sx = (int32_t)(p.x * invZ) + screenWidth / 2;
int32_t sy = screenHeight / 2 - (int32_t)(p.y * invZ);
if (sx < 0) outLeft++;
if (sx > screenWidth) outRight++;
if (sy < 0) outTop++;
if (sy > screenHeight) outBottom++;
}
return (outNear == 8 || outFar == 8 ||
outLeft == 8 || outRight == 8 ||
outTop == 8 || outBottom == 8);
}
Scene::Scene(uint16_t* framebuffer, uint16_t* zBuffer, int screenWidth, int screenHeight)
: camera(nullptr), directionalLight(nullptr), ambientLight(nullptr),
framebuffer(framebuffer), zBuffer(zBuffer), screenWidth(screenWidth), screenHeight(screenHeight), scanlinesUpdated(nullptr) {
initializeTrigTables();
renderer = new Rasterizer(framebuffer, screenWidth, screenHeight, zBuffer);
postFX = new PostFX(screenWidth, screenHeight);
}
Scene::~Scene() {
if (renderer) {
delete renderer;
renderer = nullptr;
}
if (postFX) {
delete postFX;
postFX = nullptr;
}
}
void Scene::setFramebuffer(uint16_t *newBuffer) {
framebuffer = newBuffer;
renderer->setFramebuffer(newBuffer);
}
void Scene::resize(uint16_t* newFramebuffer, uint16_t* newZBuffer,
int newWidth, int newHeight) {
framebuffer = newFramebuffer;
zBuffer = newZBuffer;
screenWidth = newWidth;
screenHeight = newHeight;
if (renderer) {
renderer->resize(newFramebuffer, newZBuffer, newWidth, newHeight);
}
// PostFX caches its own dimensions and (when enabled) owns scratch
// buffers sized to them. Easiest correct thing is to rebuild it.
if (postFX) {
delete postFX;
postFX = new PostFX(newWidth, newHeight);
}
}
void Scene::addObject(Object* obj) {
objects.push_back(obj);
}
void Scene::addPointLight(PointLight* light) {
pointLights.push_back(light);
}
void Scene::setCamera(Camera* cam) {
camera = cam;
renderer->camera = cam;
}
void Scene::setDirectionalLight(DirectionalLight* light) {
directionalLight = light;
}
void Scene::setAmbientLight(AmbientLight* light) {
ambientLight = light;
}
#if MAX_PICK_QUERIES > 0
void Scene::setPickQueries(const PickQuery* queries, int count) {
if (count < 0) count = 0;
if (count > MAX_PICK_QUERIES) count = MAX_PICK_QUERIES;
pickQueryCount = count;
for (int i = 0; i < count; ++i) {
pickQueries[i] = queries[i];
}
// Slots beyond `count` keep their previous contents but are ignored
// by the rasterizer (it loops 0..pickQueryCount). We don't bother
// zeroing them.
}
#endif
void Scene::reconstructCheckerboard() {
// For each pixel that was NOT rendered this frame (opposite parity),
// approximate it as a 3-tap average of its own previous-frame value and
// its two freshly-rendered horizontal neighbours. The old value provides
// temporal stability; the fresh neighbours provide spatial accuracy.
// At the left/right edges the missing neighbour is omitted (2-tap).
// This is a separate pass over the completed framebuffer so that painter's
// algorithm overdraw doesn't cause repeated averaging of the gap pixel.
const int cbParity = renderEvenLines ? 0 : 1;
for (int y = 0; y < screenHeight; ++y) {
uint16_t* row = framebuffer + y * screenWidth;
for (int x = 0; x < screenWidth; ++x) {
if (((x ^ y) & 1) == cbParity) continue; // freshly rendered — skip
const uint16_t old = row[x];
if (x == 0) {
// 2-tap: old + right
const uint16_t r = row[x + 1];
row[x] = (uint16_t)(
((((old >> 11) & 0x1F) + ((r >> 11) & 0x1F)) >> 1 << 11) |
((((old >> 5) & 0x3F) + ((r >> 5) & 0x3F)) >> 1 << 5) |
(((old & 0x1F) + ( r & 0x1F)) >> 1));
} else if (x == screenWidth - 1) {
// 2-tap: left + old
const uint16_t l = row[x - 1];
row[x] = (uint16_t)(
((((l >> 11) & 0x1F) + ((old >> 11) & 0x1F)) >> 1 << 11) |
((((l >> 5) & 0x3F) + ((old >> 5) & 0x3F)) >> 1 << 5) |
((( l & 0x1F) + ( old & 0x1F)) >> 1));
} else {
// 3-tap: left + old + right
const uint16_t l = row[x - 1];
const uint16_t r = row[x + 1];
row[x] = (uint16_t)(
((((l >> 11) & 0x1F) + ((old >> 11) & 0x1F) + ((r >> 11) & 0x1F)) / 3 << 11) |
((((l >> 5) & 0x3F) + ((old >> 5) & 0x3F) + ((r >> 5) & 0x3F)) / 3 << 5) |
((( l & 0x1F) + ( old & 0x1F) + ( r & 0x1F)) / 3));
}
}
}
}
#if defined(CONFIG_IDF_TARGET_ESP32S3)
// clearBuffers() row fill using 128-bit EE.VST.128.XP stores (4 × uint32
// per instruction). dest must be 16-byte aligned; n32 need not be a
// multiple of 4 — trailing elements are handled with scalar stores.
static void jet_fill_u32x16(uint32_t* dest, uint32_t val, int n32) {
const int n16 = n32 >> 2;
if (n16 > 0) {
__asm__ volatile (
"ee.movi.32.q q0, %[v], 0\n\t"
"ee.movi.32.q q0, %[v], 1\n\t"
"ee.movi.32.q q0, %[v], 2\n\t"
"ee.movi.32.q q0, %[v], 3\n\t"
: : [v] "r"(val)
);
// EE.VST.128.XP takes the post-increment stride as a register,
// not a bare immediate: as += stride_reg after each 128-bit store.
const int stride = 16;
for (int i = 0; i < n16; i++) {
__asm__ volatile (
"ee.vst.128.xp q0, %[p], %[s]\n\t"
: [p] "+r"(dest) : [s] "r"(stride) : "memory"
);
}
}
for (int r = n32 & 3; r-- > 0; ) *dest++ = val;
}
#endif
void PERF_CRITICAL Scene::clearBuffers() {
//cast the framebuffer to a 32-bit pointer
uint32_t* framebuffer32 = (uint32_t*)framebuffer;
// Wireframe mode forces a solid black background regardless of the
// configured backcolor / gradient so the outlines pop. We detour the
// gradient and backcolor for the duration of this clear and restore
// them on the way out so the host-visible state is unchanged.
uint16_t* savedGradient = backgroundGradientColors;
uint16_t savedBack = backcolor;
const bool wireClear = (renderer && renderer->wireframeMode);
if (wireClear) {
backgroundGradientColors = nullptr;
backcolor = 0;
}
if (clearRenderBuffer) {
if (renderer->checkerboardMode) {
// Checkerboard clear: only wipe current-parity pixels. Opposite-parity
// pixels keep last frame's values; when CHECKERBOARD_RECONSTRUCTION
// is enabled the rasterizer fills them in-situ as it renders each
// current-parity pixel.
const int cbParity = renderEvenLines ? 0 : 1;
for (int y = 0; y < screenHeight; ++y) {
#if DEBUG_OVERDRAW
const uint16_t lineColor = 0;
#else
const uint16_t lineColor = backgroundGradientColors
? backgroundGradientColors[y] : backcolor;
#endif
uint16_t* row = framebuffer + y * screenWidth;
for (int x = 0; x < screenWidth; ++x) {
if (((x ^ y) & 1) == cbParity) {
row[x] = lineColor;
}
}
}
#if Z_BUFFERING
memset(zBuffer, 0xFF, (size_t)screenWidth * screenHeight * sizeof(uint16_t));
#endif
} else if (renderer->interlacedMode) {
for (int y = (int)renderEvenLines; y < screenHeight; y += 2) {
#if DEBUG_OVERDRAW
uint16_t lineColor = 0;
uint32_t lineColor32 = 0;
#else
uint16_t lineColor = backgroundGradientColors ? backgroundGradientColors[y] : backcolor;
uint32_t lineColor32 = (lineColor << 16) | lineColor;
#endif
#if HALF_WIDTH_BUFFERS
const int divisor = 4;
#else
const int divisor = 2;
#endif
#if FIELD_BUFFERS
// Field-buffer layout: packed half-height. Row index = y>>1.
uint32_t* lineStart = framebuffer32 + (y >> 1) * (screenWidth / divisor);
#else
uint32_t* lineStart = framebuffer32 + y * (screenWidth / divisor);
#endif
#if defined(CONFIG_IDF_TARGET_ESP32S3)
jet_fill_u32x16(lineStart, lineColor32, screenWidth / divisor);
#else
for (int x = 0; x < screenWidth / divisor; x++) {
lineStart[x] = lineColor32;
}
#endif
#if Z_BUFFERING
#if HALF_WIDTH_BUFFERS
memset(zBuffer + (y / 2) * (screenWidth / 2), 0xFF, (screenWidth / 2) * sizeof(uint16_t));
#else
memset(zBuffer + y * screenWidth, 0xFF, screenWidth * sizeof(uint16_t));
#endif
#endif
}
} else {
// Non-interlaced clear: fill every row. Honour the per-row
// background gradient if one is set; otherwise fall back to
// a solid backcolor. Note that `memset(fb, backcolor, ...)` is
// wrong for a 16-bit backcolor because memset writes bytes —
// we'd get backcolor's low byte duplicated. Pack two pixels per
// 32-bit store and walk rows so the gradient (if any) actually
// shows up.
#if HALF_WIDTH_BUFFERS
const int rowPixels = screenWidth / 2;
const int rowCount = screenHeight / 2;
#else
const int rowPixels = screenWidth;
const int rowCount = screenHeight;
#endif
const int row32 = rowPixels / 2; // pairs of pixels per row
// Respect yBandMin/yBandMax so the clear only touches the rows
// assigned to this band (critical for virtual-base-pointer band
// rendering where the buffer only covers [yBandMin, yBandMax)).
const int yClearStart = renderer ? renderer->yBandMin : 0;
const int yClearEnd = renderer ? std::min(renderer->yBandMax, rowCount) : rowCount;
for (int y = yClearStart; y < yClearEnd; ++y) {
#if DEBUG_OVERDRAW
const uint16_t lineColor = 0;
#else
// Source row in the gradient table maps 1:1 with the
// logical screen row (`screenHeight`). When the back buffer
// is half-height (HALF_WIDTH_BUFFERS implies a y/2-style
// layout in some configs), index by `y` directly because
// rowCount already accounts for the halving.
const uint16_t lineColor = backgroundGradientColors
? backgroundGradientColors[y * (screenHeight / rowCount)]
: backcolor;
#endif
const uint32_t lineColor32 = ((uint32_t)lineColor << 16) | lineColor;
uint32_t* lineStart = framebuffer32 + y * row32;
#if defined(CONFIG_IDF_TARGET_ESP32S3)
jet_fill_u32x16(lineStart, lineColor32, row32);
#else
for (int x = 0; x < row32; ++x) lineStart[x] = lineColor32;
#endif
}
#if Z_BUFFERING
// Z-buffer stride matches the rasterizer's depth-buffer layout
// (see ZBUFFER_STRIDE in Renderer.hpp): half-width when
// HALF_WIDTH_BUFFERS is on, per-pixel otherwise. Height is the
// full screen height regardless.
#if HALF_WIDTH_BUFFERS
memset(zBuffer, 0xFF, (size_t)(screenWidth / 2) * screenHeight * sizeof(uint16_t));
#else
memset(zBuffer, 0xFF, (size_t)screenWidth * screenHeight * sizeof(uint16_t));
#endif
#endif
}
}
//memset(scanlinesUpdated, 0, screenHeight * sizeof(bool));
// Restore the host-visible background state regardless of whether we
// detoured it for the wireframe-mode clear above.
if (wireClear) {
backgroundGradientColors = savedGradient;
backcolor = savedBack;
}
}
void Scene::prepareFrame() {
if (!camera) return;
// renderEvenLines drives the frame-parity selection used by both interlaced
// and checkerboard modes. In interlaced mode it selects which rows to draw;
// in checkerboard mode it selects which (x+y) pixel parity to draw. When
// neither mode is active we force it to false so drawTriangle's
// `yStart = interlacedMode ? (minY + renderEvenLines) : minY` never shifts
// the first scanline by a stray ±1.
renderEvenLines = (renderer->interlacedMode || renderer->checkerboardMode)
? (frameCounter % 2 == 0)
: false;
clearBuffers();
#if MAX_PICK_QUERIES > 0
// Reset pick results for this frame and hand the arrays to the
// rasterizer. With FIELD_BUFFERS the rasterizer only writes one
// parity of rows per frame, so a query landing on the "off" parity
// would never be tested by drawTriangle's per-row pick loop. Snap
// the y to a row this frame's field actually covers so the host's
// requested pixel still produces a hit on roughly the right
// location (off by one row at most). The snapped y is what gets
// stored in PickResult.y so the caller can render their cursor on
// the same row the renderer inspected.
for (int i = 0; i < pickQueryCount; ++i) {
pickResults[i] = PickResult{};
#if FIELD_BUFFERS
if (renderer->interlacedMode && pickQueries[i].y >= 0) {
const int desiredParity = renderEvenLines ? 0 : 1;
int sy = pickQueries[i].y;
if ((sy & 1) != desiredParity) {
// Prefer nudging up; clamp to a valid row at the bottom.
if (sy + 1 < screenHeight) sy += 1; else if (sy > 0) sy -= 1;
}
pickQueries[i].y = (int16_t)sy;
}
#endif
}
renderer->pickQueries = pickQueries;
renderer->pickResults = pickResults;
renderer->pickQueryCount = pickQueryCount;
#endif
#if LIGHTING
if (directionalLight) directionalLight->updateViewSpaceDirection(camera);
#endif
int32_t camCosX, camSinX, camCosY, camSinY, camCosZ, camSinZ;
camera->getRotationMatrix(camCosX, camSinX, camCosY, camSinY, camCosZ, camSinZ);
renderQueue.clear();
int drawnObjs = 0;
for (auto obj : objects) {
if (!obj->enabled) continue;
// 1) Quick sphere far-cull before the expensive 8-corner AABB test.
// distSq to the object centre is computed unconditionally so it
// is also available for the fade ramps and LOD pick below,
// replacing the old lazy-compute block. The conservative sphere
// radius used is the object's longest bounding-box dimension
// (always >= the true bounding-sphere radius — never drops a
// visible object).
uint8_t objAlpha = 255;
const int32_t _ocx = (obj->position.x + obj->centreVolume.x) - camera->position.x;
const int32_t _ocy = (obj->position.y + obj->centreVolume.y) - camera->position.y;
const int32_t _ocz = (obj->position.z + obj->centreVolume.z) - camera->position.z;
int64_t distSq = (int64_t)_ocx*_ocx + (int64_t)_ocy*_ocy + (int64_t)_ocz*_ocz;
int32_t dist = -1;
{
const int32_t maxExtent = std::max({
obj->boundingBoxMax.x - obj->boundingBoxMin.x,
obj->boundingBoxMax.y - obj->boundingBoxMin.y,
obj->boundingBoxMax.z - obj->boundingBoxMin.z});
const int64_t farCutoff = static_cast<int64_t>(camera->farPlane) + maxExtent;
if (distSq > farCutoff * farCutoff) continue;
}
// 2) Object-level AABB frustum cull (all 8 corners; full rotation).
if (cullObject(obj, camCosX, camSinX, camCosY, camSinY, camCosZ, camSinZ))
continue;
// 3) Per-object distance fade (two ramps, multiplied):
// - fadeFar > 0: close=opaque, far=invisible (decor fade-out).
// - appearFar > 0: close=invisible, far=opaque (LOD impostor
// that pops in at distance).
// Both can be combined on the same object if you want a
// visibility "band" — opaque only between two distances.
// fadeFar==0 / appearFar==0 disable the respective ramp.
// Distance is measured in world space from the camera to the
// object's centre (position + centreVolume). Beyond fadeFar
// OR closer than appearNear the object is skipped entirely
// (no transform, no per-tri work), so this is a real perf
// win not just a visual fade.
// distSq is always valid here (computed above for the sphere pre-cull).
if (obj->fadeFar > 0 || obj->appearFar > 0) {
if (obj->fadeFar > 0) {
const int64_t farSq = (int64_t)obj->fadeFar * obj->fadeFar;
if (distSq >= farSq) continue; // fully past fade-out — skip
const int64_t nearSq = (int64_t)obj->fadeNear * obj->fadeNear;
if (distSq > nearSq && obj->fadeFar > obj->fadeNear) {
if (dist < 0) dist = (int32_t)std::sqrt((double)distSq);
const int32_t span = obj->fadeFar - obj->fadeNear;
const int32_t over = dist - obj->fadeNear;
int32_t a = 255 - (over * 255) / span;
if (a < 0) a = 0;
if (a > 255) a = 255;
objAlpha = (uint8_t)((objAlpha * a) / 255);
}
}
// Appear-in ramp (LOD impostor).
if (obj->appearFar > 0) {
const int64_t nearSq = (int64_t)obj->appearNear * obj->appearNear;
if (distSq <= nearSq) continue; // still too close — skip
const int64_t farSq = (int64_t)obj->appearFar * obj->appearFar;
if (distSq < farSq && obj->appearFar > obj->appearNear) {
if (dist < 0) dist = (int32_t)std::sqrt((double)distSq);
const int32_t span = obj->appearFar - obj->appearNear;
const int32_t over = dist - obj->appearNear;
int32_t a = (over * 255) / span;
if (a < 0) a = 0;
if (a > 255) a = 255;
objAlpha = (uint8_t)((objAlpha * a) / 255);
}
// distSq >= farSq: fully appeared, multiplier already 255.
}
if (objAlpha == 0) continue;
}
// 1c) Global LOD pick. The head Object IS LOD 0; entries in
// obj->lodMeshes are LOD 1, 2, ... in order. Beyond the last
// available LOD: cull (default) or clamp (`lodPersist`).
// The picked Object* contributes ONLY mesh data; the head's
// transform / flags / AABB / fade ramps still drive the draw.
Object* meshSource = obj;
if (lodScale > 0) {
if (dist < 0 && distSq >= 0) dist = (int32_t)std::sqrt((double)distSq);
int32_t level = (dist < 0 ? 0 : dist / lodScale);
level += (int32_t)lodBias + (int32_t)obj->lodBias;
if (level < 0) level = 0;
const int availableLODs = (int)obj->lodMeshes.size();
if (level == 0) {
meshSource = obj;
} else if (level <= availableLODs) {
Object* candidate = obj->lodMeshes[level - 1];
meshSource = candidate ? candidate : obj;
} else if (obj->lodPersist) {
if (availableLODs > 0) {
Object* candidate = obj->lodMeshes[availableLODs - 1];
meshSource = candidate ? candidate : obj;
}
// else: no LOD chain at all, draw the head as-is.
} else {
continue; // ran out of LODs and not persisting → cull.
}
}
// 2) Transform + project + per-triangle cull, push into renderQueue
renderObject(obj, camCosX, camSinX, camCosY, camSinY, camCosZ, camSinZ, objAlpha, meshSource);
++drawnObjs;
}
lastFrameDrawnObjects = drawnObjs;
lastFrameDrawnTriangles = static_cast<int>(renderQueue.size());
// 3) Global painter's sort. Three bands:
// 0. noWriteZBuffer — drawn first, so later geometry paints over
// them (e.g. skyboxes).
// 1. Normal — main scene, back-to-front by effective Z.
// 2. ignoreZBuffer — drawn last, unconditionally on top.
//
// Within the normal band, the sort key is `avgZ - zBias * zBiasScale`.
// Bigger zBias pulls a triangle toward the camera in the sort, so it
// draws later than coplanar geometry without that bias. The scale has
// to be large enough to beat within-triangle avgZ variation on
// typical world-scale geometry (~hundreds of units) so decals reliably
// win coplanar fights, but not so large that a biased decal draws
// *over* geometry that's genuinely much closer (where avgZ differences
// are thousands). Tune if the scale of the world changes significantly.
constexpr int32_t zBiasScale = 256;
// Bucket sort: O(N) vs O(N log N) for std::sort. Separates the three
// draw bands with one linear pass, then counting-sorts the normal band
// by depth in K=64 buckets (farther triangles first). Within a bucket
// (~Z_RANGE/64 depth units) relative order is preserved (stable).
{
const int N = static_cast<int>(renderQueue.size());
if (N > 1) {
const int32_t nearZ = camera->nearPlane;
const int32_t farZ = camera->farPlane;
const int32_t zRange = (farZ > nearZ) ? (farZ - nearZ) : 1;
constexpr int K = 64;
int counts[K] = {};
int band0N = 0, band2N = 0;
// Pass 1: classify bands; histogram the normal band by depth.
for (const auto& t : renderQueue) {
if (t.noWriteZBuffer) { band0N++; continue; }
if (t.ignoreZBuffer) { band2N++; continue; }
const int32_t key = t.avgZ - static_cast<int32_t>(t.zBias) * zBiasScale;
int b = static_cast<int>((static_cast<int64_t>(key - nearZ) * K) / zRange);
if (b < 0) b = 0; else if (b >= K) b = K - 1;
++counts[b];
}
// Prefix sums — output bucket K-1 first (farthest first).
int pos[K];
pos[K - 1] = band0N;
for (int i = K - 2; i >= 0; --i) pos[i] = pos[i + 1] + counts[i + 1];
// Pass 2: scatter into reused static output buffer.
static std::vector<RenderTri> sortBuffer;
sortBuffer.resize(N);
int b0 = 0;
int b2 = band0N + (N - band0N - band2N);
for (const auto& t : renderQueue) {
if (t.noWriteZBuffer) { sortBuffer[b0++] = t; continue; }
if (t.ignoreZBuffer) { sortBuffer[b2++] = t; continue; }
const int32_t key = t.avgZ - static_cast<int32_t>(t.zBias) * zBiasScale;
int b = static_cast<int>((static_cast<int64_t>(key - nearZ) * K) / zRange);
if (b < 0) b = 0; else if (b >= K) b = K - 1;
sortBuffer[pos[b]++] = t;
}
renderQueue.swap(sortBuffer);
}
}
} // end prepareFrame()
void Scene::clearBand(int yMin, int yMax) {
if (!renderer) return;
renderer->yBandMin = yMin;
renderer->yBandMax = yMax;
clearBuffers();
}
void Scene::rasterizeBand(int yMin, int yMax) {
// Create a thread-local copy of the rasteriser so each band worker has
// its own yBandMin/yBandMax. Only framebuffer/zbuffer ptrs are shared;
// writes go to non-overlapping y regions so there is no write race.
Rasterizer bandRast = *renderer;
bandRast.yBandMin = yMin;
bandRast.yBandMax = yMax;
// 4) Flush. Count triangles that actually entered the rasterizer
// (drawTriangle returned true). Triangles dropped by per-tri checks
// inside drawTriangle (alpha=0, zero-area, near/far Z, degenerate
// denom) return false and don't count toward the rasterized total.
int rasterized = 0;
for (const auto& t : renderQueue) {
#if MAX_PICK_QUERIES > 0
bandRast.currentPickObject = t.sourceObject;
bandRast.currentPickTriangleIndex = t.sourceTriangleIndex;
#endif
if (bandRast.drawTriangle(t.v1, t.v2, t.v3, t.material,
directionalLight, ambientLight,
renderEvenLines,
t.ignoreZBuffer, t.noWriteZBuffer,
(int)t.zBias, t.objAlpha,
t.brightnessPrecomputed)) {
++rasterized;
}
}
lastFrameRasterizedTriangles = rasterized;
}
void Scene::render() {
if (!camera) return;
prepareFrame();
rasterizeBand(0, screenHeight);
// Checkerboard reconstruction: fill in opposite-parity pixels from the
// freshly-rendered current-parity neighbours so PostFX sees a fully-populated
// buffer. Done as a separate pass after all triangles are drawn so that
// painter's algorithm overdraw cannot cause repeated averaging.
#if defined(CHECKERBOARD_RECONSTRUCTION) && CHECKERBOARD_RECONSTRUCTION
if (renderer->checkerboardMode) {
reconstructCheckerboard();
}
#endif
#if POSTFX_ANTIALIASING
postFX->applyFXAA(framebuffer);
#endif
#if POSTFX_BLOOM
postFX->applyBloom(framebuffer);
#endif
#if POSTFX_CRT
postFX->applyCRT(framebuffer);
#endif
#if POSTFX_PIXELATE
postFX->applyPixelate(framebuffer);
#endif
#if POSTFX_CHROMATIC
postFX->applyChromatic(framebuffer);
#endif
#if POSTFX_MOTION_BLUR
postFX->applyMotionBlur(framebuffer);
#endif
drawSprites();
frameCounter++;
}
void Scene::addSprite(Sprite2D* sprite) {
if (sprite) sprites.push_back(sprite);
}
// ---------------------------------------------------------------------------
// drawSprites — called at end of render(), after PostFX, before frameCounter++
// ---------------------------------------------------------------------------
// Blends each registered Sprite2D onto the framebuffer in zOrder sequence.
// Two paths:
// textured — iterate source rows, colour-key skip, optional alpha blend
// solid — span fill with material->color, optional alpha blend
//
// Alpha compositing uses a fast 5-bit RGB565 lerp:
// out = src + ((dst - src) * inv_alpha >> 5)
// which is exact at 0 and 255 and has ≤1 LSB error at mid values.
// ---------------------------------------------------------------------------
void Scene::drawSprites() {
// On HALF_WIDTH_BUFFERS builds, sprites are composited at full output
// resolution during Display::pushFrame() scanout instead — writing them
// into the half-width framebuffer here would halve their horizontal
// resolution and use the wrong stride.
#if HALF_WIDTH_BUFFERS
return;
#else
if (sprites.empty()) return;
// Sort by zOrder each frame (list is typically tiny — insertion sort
// territory, but std::stable_sort keeps it simple and correct).
std::stable_sort(sprites.begin(), sprites.end(),
[](const Sprite2D* a, const Sprite2D* b){ return a->zOrder < b->zOrder; });
for (Sprite2D* sp : sprites) {
if (!sp || !sp->enabled || !sp->material) continue;
const uint8_t matAlpha = sp->material->alpha;
// Combined alpha: 0 = invisible, 255 = opaque.
const int combined = ((int)sp->alpha * (int)matAlpha) / 255;
if (combined == 0) continue;
const Texture* tex = sp->material->diffuseMap;
const bool opaque = (combined == 255);
// Clip dest rect to framebuffer bounds.
const int srcW = tex ? tex->width : sp->width;
const int srcH = tex ? tex->height : sp->height;
if (srcW <= 0 || srcH <= 0) continue;
const int dstW = srcW * sp->scale;
const int dstH = srcH * sp->scale;
const int x0 = sp->x, y0 = sp->y;
const int x1 = x0 + dstW, y1 = y0 + dstH;
// Clipped dest rect
const int dx0 = (x0 < 0) ? 0 : x0;
const int dy0 = (y0 < 0) ? 0 : y0;
const int dx1 = (x1 > screenWidth) ? screenWidth : x1;
const int dy1 = (y1 > screenHeight) ? screenHeight : y1;
if (dx0 >= dx1 || dy0 >= dy1) continue;
// Source start offsets for the unscaled (scale==1) path.
const int sx0 = dx0 - x0;
const int sy0 = dy0 - y0;
if (tex && sp->scale > 1) {
// ---- Nearest-neighbour upscale textured blit (scale > 1) ---------
// fp8 step: advances source coord by (1/scale) per output pixel.
const int xStep = (srcW << 8) / dstW;
const int yStep = (srcH << 8) / dstH;
const bool colorKey = tex->hasAlpha;
const uint16_t keyColor = tex->alphaColor;
const uint16_t* src = tex->data;
int sf_y = (dy0 - y0) * yStep;
for (int dy = dy0; dy < dy1; ++dy, sf_y += yStep) {
const int sy = sf_y >> 8; // nearest-neighbour: integer texel
uint16_t* dstRow = framebuffer + dy * screenWidth + dx0;
int sf_x = (dx0 - x0) * xStep;
const int w = dx1 - dx0;
for (int i = 0; i < w; ++i, sf_x += xStep) {
const int sx = sf_x >> 8;
const uint16_t s = src[sy * srcW + sx];
if (colorKey && s == keyColor) continue;
const int sr = (s >> 11) & 0x1F;
const int sg = (s >> 5) & 0x3F;
const int sb = s & 0x1F;
if (sp->blendMode == BlendMode::BLEND_ADD) {
const uint16_t d = dstRow[i];
int ar=((d>>11)&0x1F)+sr; if(ar>0x1F)ar=0x1F;
int ag=((d>>5) &0x3F)+sg; if(ag>0x3F)ag=0x3F;
int ab=(d &0x1F)+sb; if(ab>0x1F)ab=0x1F;
dstRow[i]=(uint16_t)((ar<<11)|(ag<<5)|ab);
} else if (combined == 255) {
dstRow[i]=(uint16_t)((sr<<11)|(sg<<5)|sb);
} else {
const uint16_t d = dstRow[i];
const int inv=255-combined;
const int dr=(d>>11)&0x1F,dg=(d>>5)&0x3F,db=d&0x1F;
dstRow[i]=(uint16_t)(
(((sr*combined+dr*inv)/255)<<11)|
(((sg*combined+dg*inv)/255)<<5)|
((sb*combined+db*inv)/255));
}
}
}
} else if (tex) {
// ---- Textured sprite blit ----------------------------------------
const bool colorKey = tex->hasAlpha;
const uint16_t keyColor = tex->alphaColor;
const uint16_t* src = tex->data;
if (sp->blendMode == BlendMode::BLEND_ADD) {
// Saturating additive: dst = clamp(dst + src). No alpha scaling.
for (int dy = dy0; dy < dy1; ++dy) {
const int sy = sy0 + (dy - dy0);
const uint16_t* srcRow = src + sy * tex->width + sx0;
uint16_t* dstRow = framebuffer + dy * screenWidth + dx0;
const int w = dx1 - dx0;
for (int i = 0; i < w; ++i) {
const uint16_t s = srcRow[i];
if (colorKey && s == keyColor) continue;
const uint16_t d = dstRow[i];
const int sr = (s >> 11) & 0x1F;
const int sg = (s >> 5) & 0x3F;
const int sb = s & 0x1F;
int ar = ((d >> 11) & 0x1F) + sr; if (ar > 0x1F) ar = 0x1F;
int ag = ((d >> 5) & 0x3F) + sg; if (ag > 0x3F) ag = 0x3F;
int ab = ( d & 0x1F) + sb; if (ab > 0x1F) ab = 0x1F;
dstRow[i] = (uint16_t)((ar << 11) | (ag << 5) | ab);
}
}
} else {
for (int dy = dy0; dy < dy1; ++dy) {
const int sy = sy0 + (dy - dy0);
const uint16_t* srcRow = src + sy * tex->width + sx0;
uint16_t* dstRow = framebuffer + dy * screenWidth + dx0;
const int w = dx1 - dx0;
if (opaque) {
if (colorKey) {
for (int i = 0; i < w; ++i) {
if (srcRow[i] != keyColor) dstRow[i] = srcRow[i];
}
} else {
for (int i = 0; i < w; ++i) dstRow[i] = srcRow[i];
}
} else {
// 5-bit lerp: decompose RGB565 into R5/G6/B5 channels,
// lerp each independently, repack.
const int inv = 255 - combined;
for (int i = 0; i < w; ++i) {
const uint16_t s = srcRow[i];
if (colorKey && s == keyColor) continue;
const uint16_t d = dstRow[i];
const int sr = (s >> 11) & 0x1F;
const int sg = (s >> 5) & 0x3F;
const int sb = s & 0x1F;
const int dr = (d >> 11) & 0x1F;
const int dg = (d >> 5) & 0x3F;
const int db = d & 0x1F;
const int or_ = (sr * combined + dr * inv) / 255;
const int og = (sg * combined + dg * inv) / 255;
const int ob = (sb * combined + db * inv) / 255;
dstRow[i] = (uint16_t)((or_ << 11) | (og << 5) | ob);
}
}
}
}
} else {
// ---- Solid rectangle fill ----------------------------------------
const uint16_t col = sp->material->color;
if (sp->blendMode == BlendMode::BLEND_ADD) {
// Additive: add colour directly, no alpha scaling.
const int acr = (col >> 11) & 0x1F;
const int acg = (col >> 5) & 0x3F;
const int acb = col & 0x1F;
for (int dy = dy0; dy < dy1; ++dy) {
uint16_t* row = framebuffer + dy * screenWidth + dx0;
const int w = dx1 - dx0;
for (int i = 0; i < w; ++i) {
const uint16_t d = row[i];
int ar = ((d >> 11) & 0x1F) + acr; if (ar > 0x1F) ar = 0x1F;
int ag = ((d >> 5) & 0x3F) + acg; if (ag > 0x3F) ag = 0x3F;
int ab = ( d & 0x1F) + acb; if (ab > 0x1F) ab = 0x1F;
row[i] = (uint16_t)((ar << 11) | (ag << 5) | ab);
}
}
} else {
if (opaque) {
for (int dy = dy0; dy < dy1; ++dy) {
uint16_t* row = framebuffer + dy * screenWidth + dx0;
const int w = dx1 - dx0;
for (int i = 0; i < w; ++i) row[i] = col;
}
} else {
const int inv = 255 - combined;
const int cr = (col >> 11) & 0x1F;
const int cg = (col >> 5) & 0x3F;
const int cb = col & 0x1F;
for (int dy = dy0; dy < dy1; ++dy) {
uint16_t* row = framebuffer + dy * screenWidth + dx0;
const int w = dx1 - dx0;
for (int i = 0; i < w; ++i) {
const uint16_t d = row[i];
const int dr = (d >> 11) & 0x1F;
const int dg = (d >> 5) & 0x3F;
const int db = d & 0x1F;
const int or_ = (cr * combined + dr * inv) / 255;
const int og = (cg * combined + dg * inv) / 255;
const int ob = (cb * combined + db * inv) / 255;
row[i] = (uint16_t)((or_ << 11) | (og << 5) | ob);
}
}
}
}
}
}
#endif // !HALF_WIDTH_BUFFERS
}
void Scene::getStatistics(int& objectCount, int& triangleCount, int& vertexCount) {
objectCount = static_cast<int>(objects.size());
triangleCount = 0;
vertexCount = 0;
for (const auto& obj : objects) {
if (!obj->enabled) continue;
triangleCount += static_cast<int>(obj->triangles.size());
vertexCount += static_cast<int>(obj->vertices.size());
}
}
void PERF_CRITICAL Scene::renderObject(Object* obj,
int32_t camCosX, int32_t camSinX,
int32_t camCosY, int32_t camSinY,
int32_t camCosZ, int32_t camSinZ,
uint8_t objAlpha,
Object* meshSource) {
// meshSource decouples "which mesh do we rasterise" from "where / how
// does the object live in the world". Defaults to obj itself, so the
// non-LOD path is unchanged. When the global LOD system picks a
// reduced-detail mesh, that Object* is passed in here while obj keeps
// ownership of the transform, flags, AABB and fade state.
if (!meshSource) meshSource = obj;
// Reusable scratch buffers — kept across calls so we don't pay for a
// heap alloc + copy per object per frame. Renderer is single-threaded
// (one render task), so plain static is fine here.
static std::vector<Object::Vertex> transformedVertices;
static std::vector<Vector3> camSpacePos;
transformedVertices.assign(meshSource->vertices.begin(), meshSource->vertices.end());
// Parallel array of camera-space positions (pre-projection). Needed so
// triangles straddling the near plane can be clipped geometrically —
// otherwise a single vertex slipping behind the near plane would force
// the whole triangle to be discarded, leaving a visible hole in the
// world right under the camera.
camSpacePos.clear();
camSpacePos.reserve(transformedVertices.size());
Vector3 camPos(camera->position);
#if FLOAT_CAMERA_ANGLES
Vector3_f camRotF(camera->rotation);
#endif
Vector3 objPos(obj->position);
float fovFactor = camera->fovFactor;
bool isBillboard = obj->isBillboard;
CullingMode cullingMode = obj->cullingMode;
bool ignoreZBuffer = obj->ignoreZBuffer;
bool noWriteZBuffer = obj->noWriteZBuffer;
// Hoist object rotation trig out of the per-vertex loop — these are
// constant for every vertex on the object. Also short-circuit the entire
// rotation block when the object has zero rotation (true for most static
// scenery), saving 12 mul + 6 div + 9 add per vertex.
const bool objHasRotation = !isBillboard &&
(obj->rotation.x != 0 || obj->rotation.y != 0 || obj->rotation.z != 0);
// Composed object rotation matrix (Rz * Ry * Rx, since the previous
// per-vertex code applied X→Y→Z). Storing all 9 entries at
// FIXED_POINT_SCALE scale lets the per-vertex transform collapse from
// three cascaded rotations (12 muls + 12 div per vertex) into a single
// 3×3 mat-vec (9 muls + 3 div), with the same again saved on the
// normal when LIGHTING is on. The trig product entries are pre-divided
// by FIXED_POINT_SCALE so the entire matrix lives at one consistent
// scale.
int32_t objM00=FIXED_POINT_SCALE, objM01=0, objM02=0;
int32_t objM10=0, objM11=FIXED_POINT_SCALE, objM12=0;
int32_t objM20=0, objM21=0, objM22=FIXED_POINT_SCALE;
// Float counterparts pre-divided by FIXED_POINT_SCALE. Per-vertex mat-vecs
// use hardware-FPU fmul-add instead of int64_t multiply+shift. Defaults
// are identity; vertex loop guards on objHasRotation so they're never
// consumed when false.
float fObjM00=1.0f, fObjM01=0.0f, fObjM02=0.0f;
float fObjM10=0.0f, fObjM11=1.0f, fObjM12=0.0f;
float fObjM20=0.0f, fObjM21=0.0f, fObjM22=1.0f;
if (objHasRotation) {
const int32_t cx = lookupCosI(obj->rotation.x);
const int32_t sx = lookupSinI(obj->rotation.x);
const int32_t cy = lookupCosI(obj->rotation.y);
const int32_t sy = lookupSinI(obj->rotation.y);
const int32_t cz = lookupCosI(obj->rotation.z);
const int32_t sz = lookupSinI(obj->rotation.z);
// K = Ry * Rx (at FPS scale; trig-product entries divided once).