Repository navigation
Expand file tree
/
Copy pathview.cpp
More file actions
2748 lines (2344 loc) · 113 KB
/
Copy pathview.cpp
File metadata and controls
2748 lines (2344 loc) · 113 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
/* ================================================================================================
* File: view.cpp
* Brief: View/3D frame rendering: the world geometry pass behind PS2_RenderFrame.
*
* RenderFrame walks the world BSP for the refdef's camera: MarkLeaves stamps the nodes reachable
* from the current PVS cluster, RecursiveWorldNode descends the tree front-to-back culling
* against the view frustum and threads every visible opaque surface onto its texture's draw
* chain, and DrawTextureChains gathers each chain through an rs::TriangleStream - one batch per
* texture. Translucent surfaces are routed aside and drawn back-to-front at the end of the frame
* by RenderAlphaSurfaces, and sky surfaces aside to sky.cpp.
*
* Camera mapping: Quake is Z-up with AngleVectors giving forward/right/up; those
* feed math::LookAt directly (its right = cross(up, -forward) lands on Quake's
* own right vector) and PerspectiveProjection's Y-flip puts +up up on screen, so
* no axis juggling is needed between the engine and the GS.
*
* This source code is released under the GNU GPL v2 license.
* ================================================================================================ */
#include "ps2/renderer/view.h"
#include "ps2/qwords.h"
#include "ps2/renderer/profile.h"
#include "ps2/renderer/md2.h"
#include "ps2/renderer/sky.h"
#include "ps2/renderer/texture.h"
#include "ps2/renderer/model.h"
#include "ps2/renderer/lightmap.h"
#include "ps2/renderer/render_system.h"
#include "ps2/renderer/cmd_buffer.h"
#include "ps2/renderer/vu1.h"
#include "ps2/renderer/gs.h"
#include "ps2/renderer/gamma.h" // the palette as it shows (beam and particle colours)
#include <cmath>
#include <cstring>
namespace ps2::view {
namespace {
// ------------------------------------------------------------------------------------------------
// Cvars / common constants
// ------------------------------------------------------------------------------------------------
// Depth range for the world projection (ref_gl's values).
constexpr float kZNear = 4.0f;
constexpr float kZFar = 4096.0f;
// The view weapon gets its own, much closer near plane. Its models sit at the
// view origin with the stock and hands reaching back past it, so at kZNear a
// good part of the gun straddles the near plane - and the VU rejects straddling
// triangles whole rather than cutting them, which would punch holes in it. The
// weapon's depth is remapped into a fixed slice of the z-buffer regardless of
// the projection (rs::DrawFlags::DepthHack), so a near plane this close costs
// it no precision it can use: the gun still spans thousands of z values inside
// its slice.
constexpr float kZNearWeapon = 0.25f;
// Vertex colour for the not-yet-lit world: GS modulate 128 = texels unchanged.
// The loader bakes this same value into the vertices of every surface it cannot
// give a luxel chroma to, so the two must not drift apart.
constexpr u32 kFullBright = mod::kFullBrightColor;
// Render view cvars:
static const cvar_t * s_skipWorld = nullptr;
static const cvar_t * s_skipAlphaSurfaces = nullptr;
static const cvar_t * s_skipBrushModels = nullptr;
static const cvar_t * s_skipSprites = nullptr;
static const cvar_t * s_skipEntities = nullptr;
static const cvar_t * s_skipParticles = nullptr;
static const cvar_t * s_particles = nullptr;
static const cvar_t * s_forceNullModels = nullptr;
static const cvar_t * s_skipWeaponModel = nullptr;
static const cvar_t * s_dynamicLightmaps = nullptr;
static const cvar_t * s_dlightScale = nullptr;
static const cvar_t * s_lightmaps = nullptr;
static const cvar_t * s_lightmapOnly = nullptr;
static const cvar_t * s_lightmapColor = nullptr;
static const cvar_t * s_lightmapModulate = nullptr;
static const cvar_t * s_polyblend = nullptr;
// Not ours to read: SetLightLevel writes the sampled light level back into it
// every frame for the game code (hence non-const). Registered by the client
// (cl_main.c), which forwards it to the server in each usercmd.
static cvar_t * s_lightLevel = nullptr;
// ps2_mip_filter picks the filtering of the walls and model skins by name, as ref_gl's
// gl_texturemode did: nearest, bilinear or trilinear. Non-const to clear its 'modified' flag,
// which is what gets a new name parsed - once, not every frame. ps2_mip_bias shifts the mip
// levels the walls sample, in levels; positive is blurrier. See SetUpTextureSampling.
static cvar_t * s_mipFilter = nullptr;
static const cvar_t * s_mipBias = nullptr;
static gs::MipFilter s_mipFilterMode = gs::MipFilter::Bilinear;
// ------------------------------------------------------------------------------------------------
// Frame state
// ------------------------------------------------------------------------------------------------
// Game time of the frame, in seconds; drives the water warp animation.
static float s_frameTime = 0.0f;
// Frame counters used to mark drawable surfaces:
static int s_frameCount = 0; // Bumped per RenderFrame; stamps surfaces marked for draw.
static int s_visFrameCount = 0; // Bumped when the PVS changes; stamps reachable nodes.
// Quake 2 view clusters; BeginRegistration() resets them for a new map.
constexpr int kInvalidCluster = -1;
static int s_viewCluster = kInvalidCluster;
static int s_viewCluster2 = kInvalidCluster;
static int s_oldViewCluster = kInvalidCluster;
static int s_oldViewCluster2 = kInvalidCluster;
// Scene camera basis for the frame (Quake coordinates, from AngleVectors).
static vec3_t s_forwardVec = {};
static vec3_t s_rightVec = {};
static vec3_t s_upVec = {};
// World-to-clip transform for the frame (world geometry draws in world space).
static math::Mat4 s_viewProjMatrix = {};
// The same transform with the view weapon's closer near plane (kZNearWeapon).
static math::Mat4 s_weaponViewProjMatrix = {};
// View frustum side planes (left, right, bottom, top) for bounding-box culling.
static cplane_t s_frustum[4] = {};
// For each frustum plane, which of a bounding box's six minmaxs values (mins xyz, then maxs xyz)
// make the corner farthest along the plane normal, and which the nearest - the pair of corners
// BoxOnPlaneSide picks by the plane's sign bits, picked once a frame here instead. The far corner
// behind the plane puts the whole box behind it; the near one in front puts the whole box in front.
struct FrustumPlaneCorners
{
u8 farCorner[3];
u8 nearCorner[3];
};
static FrustumPlaneCorners s_frustumCorners[4] = {};
// All four frustum planes still to be tested, which is where the world walk starts.
constexpr int kAllFrustumPlanes = 0xF;
// The same four planes packed for VU0; rebuilt with them by SetUpFrustum.
static math::Mat4 s_frustumMatrix = {};
// Wall texture animation frame (viewDef.time * 2, as in ref_gl).
static int s_textureAnimFrame = 0;
// Textures that received surfaces this frame; DrawTextureChains draws and
// resets exactly these. One entry per live texture is the true ceiling, so it
// tracks the cache's own capacity.
constexpr int kMaxChainTextures = static_cast<int>(tex::kMaxTextures);
static const tex::Texture * s_chainTextures[kMaxChainTextures];
static int s_chainTextureCount = 0;
// Surfaces with transparency (glass, water, lava, slime), collected while
// walking the BSP and while drawing brush model entities, then drawn last by
// RenderAlphaSurfaces over the finished opaque scene.
//
// Recorded here rather than threaded through ModelSurface::textureChain like
// the opaque chains because a brush model's surfaces have to remember the
// entity transform they were collected under. ref_gl loses it - its
// R_DrawAlphaSurfaces reloads the world matrix, so a moving submodel's water
// draws back at the map's rest position - and the records cost little.
struct AlphaSurface
{
const mod::ModelSurface * surf;
const tex::Texture * texture; // Resolved on collection: the animation frame is the entity's.
const math::Mat4 * mvp; // &s_viewProjMatrix, or into s_alphaEntityMatrices below.
};
constexpr int kMaxAlphaSurfaces = 1024;
static AlphaSurface s_alphaSurfaces[kMaxAlphaSurfaces];
static int s_alphaSurfaceCount = 0;
// One transform per brush model entity that contributed a translucent surface;
// DrawBrushModelEntity's own is a local, long gone by the time the alpha pass
// runs. MAX_ENTITIES is the hard ceiling on contributors, so it cannot overflow.
static math::Mat4 s_alphaEntityMatrices[MAX_ENTITIES];
static int s_alphaEntityMatrixCount = 0;
// Triangle gather buffer: texture chains append here and flush through
// rs::DrawTriangles when full (see rs::TriangleStream). The vertices live in the frame
// chain, so an instance is 8 bytes and rides in the draw state rather than
// sitting in .bss - which also means a pass cannot gather under one state and
// flush under another by forgetting which static it shared.
constexpr int kBatchMaxVerts = 3 * 768; // 768 whole triangles per batch
// One rs::TriangleStream per pass, at kBatchMaxVerts.
// Performance counters for the frame, reset by RenderFrame and read through
// GetStats() by the ps2_show_drawstats overlay.
#if PS2_QUAKE_PROFILE
static DrawStats s_drawStats = {};
#endif // PS2_QUAKE_PROFILE
// ------------------------------------------------------------------------------------------------
// Translucent surface collection
// ------------------------------------------------------------------------------------------------
// Defers one translucent surface to the RenderAlphaSurfaces pass at the end of
// the frame, remembering the texture (the animation frame is the caller's) and
// the transform it draws under.
void PushAlphaSurface(const mod::ModelSurface & surf, const tex::Texture & texture, const math::Mat4 & mvp)
{
PS2_AssertMsg(s_alphaSurfaceCount < kMaxAlphaSurfaces, "Out of alpha surface slots!");
if (s_alphaSurfaceCount == kMaxAlphaSurfaces)
{
Com_DPrintf("Out of alpha surface slots!\n");
return; // Fail and drop the overflow surface on no-asserts build.
}
AlphaSurface & entry = s_alphaSurfaces[s_alphaSurfaceCount++];
entry.surf = &surf;
entry.texture = &texture;
entry.mvp = &mvp;
PS2_PROFILE_ONLY(++s_drawStats.surfacesAlpha);
}
// Parks a brush model entity's transform where the deferred pass can still
// reach it. One slot per contributing entity - callers hold on to the returned
// pointer for the rest of their surfaces. Null only if the table is full.
const math::Mat4 * StoreAlphaEntityMatrix(const math::Mat4 & mvp)
{
PS2_AssertMsg(s_alphaEntityMatrixCount < MAX_ENTITIES, "Out of alpha entity matrix slots!");
if (s_alphaEntityMatrixCount == MAX_ENTITIES)
{
Com_DPrintf("Out of alpha entity matrix slots!\n");
return nullptr;
}
math::Mat4 & slot = s_alphaEntityMatrices[s_alphaEntityMatrixCount++];
slot = mvp;
return &slot;
}
// ------------------------------------------------------------------------------------------------
// Frame setup: camera matrices and frustum
// ------------------------------------------------------------------------------------------------
Q_ALWAYS_INLINE int SignBitsForPlane(const cplane_t & plane)
{
// Sign bits are used for fast box-on-plane-side tests.
int bits = 0;
for (int i = 0; i < 3; ++i)
{
if (plane.normal[i] < 0.0f)
{
bits |= (1 << i);
}
}
return bits;
}
// The frame's texture filtering and the constant that picks the walls' mip levels.
//
// A wall texel spans one world unit - 2085 of the 2118 walls are powers of two, and nearly every
// texinfo is unscaled - and at view depth w a world unit covers f / w pixels, where
// f = (screen height / 2) * cot(fovY / 2) is the projection's focal length in pixels (see
// PerspectiveProjection; 320 at 640x448 and fov 90). So texels shrink to a pixel at w = f, and
// the level that keeps them about a pixel wide is log2(w / f): with the GS measuring log2(1/Q)
// and Q = 1/w, that makes K = -log2(f). The GS goes by depth alone, not by how slanted the
// surface is, so a floor seen at a grazing angle gets a sharper level than its texel density on
// screen calls for; ps2_mip_bias is the knob for that.
void SetUpTextureSampling(const refdef_t & viewDef)
{
if (s_mipFilter->modified)
{
s_mipFilter->modified = false;
static const char * const kFilterNames[] = { "nearest", "bilinear", "trilinear" };
int filter = -1;
for (int i = 0; i < ArrayLength(kFilterNames); ++i)
{
if (Q_stricmp(s_mipFilter->string, kFilterNames[i]) == 0)
{
filter = i;
}
}
if (filter >= 0)
{
s_mipFilterMode = static_cast<gs::MipFilter>(filter);
}
else
{
const char * const current = kFilterNames[static_cast<int>(s_mipFilterMode)];
Com_Printf("ps2_mip_filter: '%s' is not nearest, bilinear or trilinear; keeping %s.\n",
s_mipFilter->string, current);
Cvar_Set(s_mipFilter->name, current);
s_mipFilter->modified = false;
}
}
const float halfFovY = math::DegToRad(viewDef.fov_y) * 0.5f;
const float focalPixels = 0.5f * static_cast<float>(gs::Height()) * math::Cosf(halfFovY) / math::Sinf(halfFovY);
const float lodK = s_mipBias->value - std::log2(focalPixels);
// TEX1.K is signed fixed point with four fraction bits, in 12 bits.
int lodK16 = static_cast<int>((lodK * 16.0f) + ((lodK < 0.0f) ? -0.5f : 0.5f));
lodK16 = (lodK16 < -2048) ? -2048 : ((lodK16 > 2047) ? 2047 : lodK16);
rs::SetTextureSampling({ s_mipFilterMode, lodK16 });
}
// Builds the four frustum side planes by rotating the view direction around
// the up/right axes by half the FOV (ref_gl's R_SetFrustum construction).
void SetUpFrustum(const refdef_t & viewDef)
{
RotatePointAroundVector(s_frustum[0].normal, s_upVec, s_forwardVec, -(90.0f - viewDef.fov_x * 0.5f));
RotatePointAroundVector(s_frustum[1].normal, s_upVec, s_forwardVec, (90.0f - viewDef.fov_x * 0.5f));
RotatePointAroundVector(s_frustum[2].normal, s_rightVec, s_forwardVec, (90.0f - viewDef.fov_y * 0.5f));
RotatePointAroundVector(s_frustum[3].normal, s_rightVec, s_forwardVec, -(90.0f - viewDef.fov_y * 0.5f));
for (int p = 0; p < 4; ++p)
{
cplane_t & plane = s_frustum[p];
plane.type = PLANE_ANYZ;
plane.dist = DotProduct(viewDef.vieworg, plane.normal);
plane.signbits = static_cast<byte>(SignBitsForPlane(plane));
// A negative normal component takes the far corner from mins, as BoxOnPlaneSide's
// sign bits do.
for (int axis = 0; axis < 3; ++axis)
{
const bool negative = (plane.normal[axis] < 0.0f);
s_frustumCorners[p].farCorner[axis] = static_cast<u8>(negative ? axis : axis + 3);
s_frustumCorners[p].nearCorner[axis] = static_cast<u8>(negative ? axis + 3 : axis);
}
}
// The same four planes as a transform, so a point's distance to all of them
// comes out of one VU0 pass instead of four scalar dot products: column p
// holds plane p's normal with -dist in the translation row, which makes
// component p of (point * this) exactly dot(point, n[p]) - dist[p].
s_frustumMatrix = {{
{ s_frustum[0].normal[0], s_frustum[1].normal[0], s_frustum[2].normal[0], s_frustum[3].normal[0] },
{ s_frustum[0].normal[1], s_frustum[1].normal[1], s_frustum[2].normal[1], s_frustum[3].normal[1] },
{ s_frustum[0].normal[2], s_frustum[1].normal[2], s_frustum[2].normal[2], s_frustum[3].normal[2] },
{ -s_frustum[0].dist, -s_frustum[1].dist, -s_frustum[2].dist, -s_frustum[3].dist },
}};
}
// True when dynamic lights are drawn as per-vertex point lights on VU1.
Q_ALWAYS_INLINE bool VuDynamicLightsEnabled()
{
return s_dynamicLightmaps->value == 2.0f;
}
// Hands the frame's dynamic lights to VU1 (mode 2 only).
//
// The microprogram evaluates four at once and attenuates per vertex, so lights
// need no assignment to batches - one far from a surface simply contributes
// nothing through the same max(). That means the only choice to make here is
// which four matter most when the client sends more, which it rarely does:
// MAX_DLIGHTS is 32 but a busy firefight runs two or three.
//
// Selection is by intensity, largest first. Quake 2's dlight intensity is the
// radius in world units, so the brightest light is also the one reaching
// furthest, which makes it the right one to keep.
void SetUpDynamicLights(const refdef_t & viewDef)
{
if (!VuDynamicLightsEnabled())
{
rs::SetDynamicLights(nullptr, 0);
return;
}
vu1::DynamicLight chosen[vu1::kMaxDynamicLights];
int count = 0;
const float scale = s_dlightScale->value;
const int numDlights = viewDef.num_dlights;
for (int i = 0; i < numDlights; ++i)
{
const dlight_t & dl = viewDef.dlights[i];
if (dl.intensity <= 0.0f)
{
continue; // The client emits "dark lights" this path cannot express.
}
// Insertion sort into a four-deep list, weakest dropped off the end.
int slot = count;
while (slot > 0 && chosen[slot - 1].radius < dl.intensity)
{
if (slot < vu1::kMaxDynamicLights)
{
chosen[slot] = chosen[slot - 1];
}
--slot;
}
if (slot < vu1::kMaxDynamicLights)
{
chosen[slot] = {
{ dl.origin[0], dl.origin[1], dl.origin[2] },
{ dl.color[0] * scale, dl.color[1] * scale, dl.color[2] * scale },
dl.intensity
};
if (count < vu1::kMaxDynamicLights)
{
++count;
}
}
}
rs::SetDynamicLights(chosen, count);
}
// Extracts the six planes bounding the VU1 clip volume from a view-projection.
//
// Tests a box ('minmaxs': mins xyz, then maxs xyz) against the frustum planes still set in
// 'clipFlags'. Returns -1 when it is entirely behind one of them, and otherwise the planes its
// contents still have to be tested against: a plane the box is entirely in front of is cleared,
// since nothing inside the box can be behind it either. That is what makes the world walk cheap -
// once a node is fully inside a plane, nothing beneath it tests that plane again, which is the
// software renderer's R_RecursiveWorldNode clipflags.
//
// The same corners, sums and comparisons as BOX_ON_PLANE_SIDE, so the same boxes go: the frustum
// planes are never axial, which sent every one of those to an out-of-line BoxOnPlaneSide.
Q_ALWAYS_INLINE int CullBoxToFrustum(const float * const minmaxs, int clipFlags)
{
for (int p = 0; p < 4; ++p)
{
if ((clipFlags & (1 << p)) == 0)
{
continue;
}
const cplane_t & plane = s_frustum[p];
const FrustumPlaneCorners & corners = s_frustumCorners[p];
const float farDist = plane.normal[0] * minmaxs[corners.farCorner[0]]
+ plane.normal[1] * minmaxs[corners.farCorner[1]]
+ plane.normal[2] * minmaxs[corners.farCorner[2]];
if (farDist < plane.dist)
{
PS2_PROFILE_ONLY(++s_drawStats.boxesCulled);
return -1;
}
const float nearDist = plane.normal[0] * minmaxs[corners.nearCorner[0]]
+ plane.normal[1] * minmaxs[corners.nearCorner[1]]
+ plane.normal[2] * minmaxs[corners.nearCorner[2]];
if (nearDist >= plane.dist)
{
clipFlags &= ~(1 << p);
}
}
return clipFlags;
}
// True when the box is completely outside the frustum and must not draw.
Q_ALWAYS_INLINE bool ShouldCullBBox(const float * const mins, const float * const maxs)
{
const float minmaxs[6] = { mins[0], mins[1], mins[2], maxs[0], maxs[1], maxs[2] };
return CullBoxToFrustum(minmaxs, kAllFrustumPlanes) < 0;
}
void SetupFrame(const refdef_t & viewDef)
{
PS2_Assert(viewDef.width > 0 && viewDef.height > 0);
lm::BeginFrame();
PS2_PROFILE_ONLY(s_drawStats = {});
s_alphaSurfaceCount = 0;
s_alphaEntityMatrixCount = 0;
++s_frameCount;
// Animated walls flip frames at 2 Hz of game time (as in ref_gl).
s_frameTime = viewDef.time;
s_textureAnimFrame = static_cast<int>(viewDef.time * 2.0f);
// Turbulent surfaces animate on the VU (the warp block of textured_triangles.vusl), so the frame's two animation
// terms go over once here rather than being folded into every vertex.
//
// The phase travels in turns and pre-wrapped, which keeps it precise however long the session
// has run - ref_gl hands its table a raw, ever-growing 'time' and leans on the integer mask to
// bring it back. SURF_FLOWING's drift is a whole 64-texel tile every two seconds; the batches
// that take it are the ones flagged rs::DrawFlags::WarpFlowing.
const float warpTurns = s_frameTime * (1.0f / (2.0f * math::kPI));
const float halfTime = s_frameTime * 0.5f;
rs::SetWarpAnimation(warpTurns - std::floor(warpTurns), -64.0f * (halfTime - std::floor(halfTime)));
SetUpTextureSampling(viewDef);
// Camera basis vectors from the view angles.
math::AngleVectors(viewDef.viewangles, s_forwardVec, s_rightVec, s_upVec);
const math::Vec3 eye = { viewDef.vieworg[0], viewDef.vieworg[1], viewDef.vieworg[2] };
const math::Vec3 target = { eye.x + s_forwardVec[0], eye.y + s_forwardVec[1], eye.z + s_forwardVec[2] };
const math::Vec3 up = { s_upVec[0], s_upVec[1], s_upVec[2] };
const float fovY = math::DegToRad(viewDef.fov_y);
const float aspect = static_cast<float>(viewDef.width) / static_cast<float>(viewDef.height);
const float screenW = static_cast<float>(gs::Width());
const float screenH = static_cast<float>(gs::Height());
const math::Mat4 view = math::LookAt(eye, target, up);
const math::Mat4 proj = math::PerspectiveProjection(fovY, aspect, screenW, screenH, kZNear, kZFar);
s_viewProjMatrix = view * proj;
// The view weapon's variant differs only in the near plane, so it shares
// the camera and every screen mapping; nothing else may use it.
const math::Mat4 weaponProj = math::PerspectiveProjection(fovY, aspect, screenW, screenH, kZNearWeapon, kZFar);
s_weaponViewProjMatrix = view * weaponProj;
SetUpFrustum(viewDef);
SetUpDynamicLights(viewDef);
}
// ------------------------------------------------------------------------------------------------
// PVS / visibility
// ------------------------------------------------------------------------------------------------
const mod::ModelLeaf * FindLeafNodeForPoint(const float * point, const mod::ModelInstance & model)
{
PS2_AssertMsg(model.Brush().nodes != nullptr, "World model has no nodes!");
const mod::ModelNode * node = model.Brush().nodes;
for (;;)
{
if (node->contents != -1)
{
return reinterpret_cast<const mod::ModelLeaf *>(node);
}
const cplane_t * const plane = node->plane;
const float d = DotProduct(point, plane->normal) - plane->dist;
node = (d > 0.0f) ? node->children[0] : node->children[1];
}
}
// Returns the decompressed PVS row for 'cluster'.
//
// Defers to CM_ClusterPVS rather than keeping a copy of the VISIBILITY lump in the world hunk -
// the collision model already holds it, and its decoder clamps a zero-run to the row length
// instead of running off the end.
//
// The row lives in a shared buffer that the next call overwrites, so don't hold
// on to it (MarkLeaves copies it into a temp before asking for the second one).
Q_ALWAYS_INLINE const u8 * GetClusterPVS(const int cluster)
{
PS2_Assert(cluster != kInvalidCluster); // MarkLeaves handles that case itself.
return CM_ClusterPVS(cluster);
}
// Finds the clusters the camera sees from this frame. Two clusters when near a
// solid water surface, so crossing it doesn't draw wrong (checked by sampling a
// second leaf 16 units above/below the eye).
void SetUpViewClusters(const refdef_t & viewDef, const mod::ModelInstance & world)
{
const mod::ModelLeaf * leaf = FindLeafNodeForPoint(viewDef.vieworg, world);
s_oldViewCluster = s_viewCluster;
s_oldViewCluster2 = s_viewCluster2;
s_viewCluster = s_viewCluster2 = leaf->cluster;
vec3_t temp;
VectorCopy(viewDef.vieworg, temp);
temp[2] += (leaf->contents == 0) ? -16.0f : 16.0f;
leaf = FindLeafNodeForPoint(temp, world);
if (!(leaf->contents & CONTENTS_SOLID) && (leaf->cluster != s_viewCluster2))
{
s_viewCluster2 = leaf->cluster;
}
}
// Stamps the leafs in the current clusters' PVS - and the node chains above
// them - with the new vis frame count. Skipped entirely while the camera stays
// in the same cluster(s), which is the common case.
void MarkLeaves(const mod::ModelInstance & world)
{
PS2_PROFILE_SCOPED_EVENT(prof_evt::MarkLeaves);
if (s_oldViewCluster == s_viewCluster &&
s_oldViewCluster2 == s_viewCluster2 &&
s_viewCluster != kInvalidCluster)
{
return; // Same clusters as the previous frame; marks still valid.
}
++s_visFrameCount;
s_oldViewCluster = s_viewCluster;
s_oldViewCluster2 = s_viewCluster2;
if (s_viewCluster == kInvalidCluster || !CM_HasVisibility())
{
// Outside the map or no PVS data: mark everything visible.
for (int i = 0; i < world.Brush().numLeafs; ++i)
{
world.Brush().leafs[i].visFrame = s_visFrameCount;
}
for (int i = 0; i < world.Brush().numNodes; ++i)
{
world.Brush().nodes[i].visFrame = s_visFrameCount;
}
return;
}
const u8 * vis = GetClusterPVS(s_viewCluster);
// Scratch for the two-cluster PVS union used when the camera straddles a solid
// water boundary. The single-cluster row comes from CM_ClusterPVS, which owns its
// own buffer - this only exists because combining two clusters needs the first row
// kept while the second is decompressed over it.
alignas(16) u8 fatPvs[MAX_MAP_LEAFS / 8];
// May have to combine two clusters because of solid water boundaries:
if (s_viewCluster2 != s_viewCluster)
{
// Copy the first row out before asking for the second: CM_ClusterPVS
// decompresses both into the same buffer.
std::memcpy(fatPvs, vis, static_cast<size_t>((world.Brush().numLeafs + 7) / 8));
vis = GetClusterPVS(s_viewCluster2);
// Both buffers are 16-byte aligned, so OR them a word at a time.
u32 * fat = static_cast<u32 *>(static_cast<void *>(fatPvs));
const u32 * add = static_cast<const u32 *>(static_cast<const void *>(vis));
const int words = (world.Brush().numLeafs + 31) / 32;
for (int i = 0; i < words; ++i)
{
fat[i] |= add[i];
}
vis = fatPvs;
}
mod::ModelLeaf * leaf = world.Brush().leafs;
for (int i = 0; i < world.Brush().numLeafs; ++i, ++leaf)
{
const int cluster = leaf->cluster;
if (cluster == kInvalidCluster)
{
continue;
}
if (vis[cluster >> 3] & (1 << (cluster & 7)))
{
auto * node = reinterpret_cast<mod::ModelNode *>(leaf);
do
{
if (node->visFrame == s_visFrameCount)
{
break; // This branch is already marked up to the root.
}
node->visFrame = s_visFrameCount;
node = node->parent;
} while (node != nullptr);
}
}
}
// ------------------------------------------------------------------------------------------------
// World BSP walk and texture chains
// ------------------------------------------------------------------------------------------------
// Returns the texture a surface draws with, following the animation chain for
// animated walls (torches, screens). Never null: the model loader substitutes
// the debug checkerboard for missing wall textures. World surfaces step the
// chain on game time; brush model entities step it on entity.frame instead,
// which is how the game scripts a door or button changing its own texture.
const tex::Texture * TextureAnimation(const mod::ModelTexInfo * texInfo, int animFrame)
{
PS2_Assert(texInfo != nullptr && texInfo->texture != nullptr);
if (texInfo->next == nullptr)
{
return texInfo->texture; // Not animated.
}
int c = animFrame % texInfo->numFrames;
while (c-- > 0)
{
texInfo = texInfo->next;
}
return texInfo->texture;
}
// Recursively marks and chains the visible world surfaces: walks the BSP
// front-to-back, culling nodes against the PVS marks and the view frustum,
// and threads each drawable surface onto its texture's chain so the next
// DrawTextureChains() call renders what was collected here.
void RecursiveWorldNode(const refdef_t & viewDef, const mod::ModelInstance & world, mod::ModelNode * node,
int clipFlags)
{
if (node->contents == CONTENTS_SOLID)
{
return;
}
if (node->visFrame != s_visFrameCount)
{
return; // Not reachable from the current PVS cluster.
}
// Only the planes the parent was not already entirely inside.
if (clipFlags != 0)
{
clipFlags = CullBoxToFrustum(node->minmaxs, clipFlags);
if (clipFlags < 0)
{
return; // Entirely outside the view frustum.
}
}
PS2_PROFILE_ONLY(++s_drawStats.nodesWalked);
// Leaf: stamp its surfaces as drawable this frame.
if (node->contents != -1)
{
auto * leaf = reinterpret_cast<mod::ModelLeaf *>(node);
// Check for door-connected areas:
if (viewDef.areabits != nullptr)
{
if (!(viewDef.areabits[leaf->area >> 3] & (1 << (leaf->area & 7))))
{
return; // Not visible.
}
}
mod::ModelSurface ** mark = leaf->firstMarkSurface;
for (int i = 0; i < leaf->numMarkSurfaces; ++i, ++mark)
{
(*mark)->visFrame = s_frameCount;
}
return;
}
// Decision node: find which side of its plane the camera is on.
float dot;
const cplane_t * const plane = node->plane;
switch (plane->type)
{
case PLANE_X:
dot = viewDef.vieworg[0] - plane->dist;
break;
case PLANE_Y:
dot = viewDef.vieworg[1] - plane->dist;
break;
case PLANE_Z:
dot = viewDef.vieworg[2] - plane->dist;
break;
default:
dot = DotProduct(viewDef.vieworg, plane->normal) - plane->dist;
break;
}
const int side = (dot >= 0.0f) ? 0 : 1;
const bool cameraOnBack = (side == 1);
// Recurse down the camera side first (front-to-back order)...
RecursiveWorldNode(viewDef, world, node->children[side], clipFlags);
// ...then chain this node's surfaces that face the camera...
mod::ModelSurface * surf = world.Brush().surfaces + node->firstSurface;
for (int i = 0; i < node->numSurfaces; ++i, ++surf)
{
if (surf->visFrame != s_frameCount)
{
continue; // Not in a visible leaf.
}
if (HasFlag(surf->flags, mod::SurfaceFlags::PlaneBack) != cameraOnBack)
{
continue; // Facing away from the camera.
}
const int texFlags = surf->texInfo->flags;
if (texFlags & SURF_SKY)
{
// Never drawn: a sky surface is a hole, and all it contributes is
// which part of the skybox the player can see through it.
sky::AddSurface(*surf, viewDef.vieworg);
continue;
}
if (texFlags & (SURF_TRANS33 | SURF_TRANS66 | SURF_WARP))
{
// Translucent or turbulent: deferred to the back-to-front pass at
// the end of the frame. World geometry draws in world space, so
// the plain view-projection is transform enough.
PushAlphaSurface(*surf, *TextureAnimation(surf->texInfo, s_textureAnimFrame), s_viewProjMatrix);
continue;
}
// Opaque: thread onto its texture's draw chain.
PS2_PROFILE_ONLY(++s_drawStats.surfaces);
const tex::Texture * texture = TextureAnimation(surf->texInfo, s_textureAnimFrame);
if (texture->textureChain == nullptr)
{
// First surface for this texture this frame; remember the chain.
PS2_AssertMsg(s_chainTextureCount < kMaxChainTextures, "Out of texture chain slots!");
s_chainTextures[s_chainTextureCount++] = texture;
}
surf->textureChain = texture->textureChain;
texture->textureChain = surf;
// Rebuild the surface's luxels if its lighting moved since they were
// baked, and thread it onto its atlas's chain for the lightmap pass.
// Here rather than at draw time because this walk reaches each visible
// surface exactly once, so the rebuild cannot be done twice over.
if (surf->lightmapTextureNum != mod::kNotLightmapped)
{
lm::ChainSurface(*surf, viewDef, s_frameCount);
}
}
// ...and finally recurse down the far side.
RecursiveWorldNode(viewDef, world, node->children[side ^ 1], clipFlags);
}
// ------------------------------------------------------------------------------------------------
// Triangle gathering and submission
// ------------------------------------------------------------------------------------------------
// Everything the gather path needs beyond the geometry itself. The world pass
// draws untransformed, fullbright and opaque; a brush model entity carries its
// own model-view-projection and may blend, so the same clipper and scratch
// buffer serve both.
struct SurfaceDrawState
{
// What the gather appends to. Scoped to the pass that built this state: two
// streams holding claimed command buffer spans at once is not a thing the
// buffer can represent (see rs::TriangleStream).
rs::TriangleStream * stream = nullptr;
// Draws with this; the world's is the plain view-projection. Kept here as
// well as on the stream because ApplyDrawState is what hands it over.
const math::Mat4 * mvp = nullptr;
// Packed vertex colour (GS modulate: 128 = unchanged, alpha 0x80 = 1.0).
u32 rgba = 0;
// Batch flags, i.e. whether the submission blends.
rs::DrawFlags flags = rs::DrawFlags::None;
// Gouraud alpha: take each vertex's alpha from its own corner's st.z
// (0..1) instead of from 'rgba', whose RGB is still used for all three
// corners. The gather path is otherwise flat-shaded - one colour per
// batch - and this is the cheapest way out of that, since st is already
// a whole quadword the clipper interpolates and .z was spare.
bool vertexAlpha = false;
// Feed the gather the vertices' lightmap UVs instead of their diffuse
// ones - the second pass over the same geometry that modulates in the
// lightmap. Defaulted because only that one pass wants it; every other
// draw leaves it alone.
bool lightmapUVs = false;
// Tint the surface being gathered by the luxel chroma its vertices carry
// (PolyVertex::rgba), rather than leaving the vertex colour flat.
// Set per surface by the diffuse passes: the lightmap pass can only deliver
// a luxel's intensity, so its colour rides the vertex colour the GS
// modulates the wall texture by instead. Mutually exclusive with
// vertexAlpha, which owns that colour's alpha byte.
bool lightmapTint = false;
// The loader's PolyVertex is exactly what this pass wants in the batch, so
// GatherPolyTriangles can hand the model's own memory to the DMA instead of
// rebuilding a vertex per corner. True whenever the pass draws with the colour
// the bake put there - which is every shipping path; the debug views that
// override it (ps2_lightmap_only, ps2_lightmap_color 0) and translucent brush
// models, which carry the entity's alpha rather than the surface's, fall back
// to BuildPolyVertexCache.
bool bakedVertices = false;
};
// ------------------------------------------------------------------------------------------------
// Triangle gathering through the clipper
//
// Sprites, beams, null models and the dlight flares build their corners here
// and hand them to GatherTriangle, which turns them into batch vertices. VU1
// cuts whatever straddles; nothing on this path meets the EE clipper any more.
// ------------------------------------------------------------------------------------------------
struct GatherCorner
{
math::Vec3 position;
math::Vec3 st;
};
// Scales one 0-255 colour channel by a 0..1 factor, rounded so a factor of 1
// leaves it exactly where it was.
// Applies a vertex's cached luxel chroma (lm::CacheSurfaceVertexColors) to a
// batch colour. The cache holds what a fullbright batch wants, which is the
// overwhelmingly common case and needs nothing further.
//
// The rest - the lightmap-only debug view, and translucent brush models at their
// flat quarter alpha - rescale it with integer maths rather than falling back to
// re-sampling the atlas: the cached channel is the chroma times 128, so
// (base * cached) >> 7 recovers base times chroma, with no float conversions and
// no 128 KB mirror read.
Q_ALWAYS_INLINE u32 ApplyCachedLightmapColor(const u32 base, const u32 cached)
{
if (base == kFullBright)
{
return cached;
}
const auto channel = [](const u32 b, const u32 c) -> u32
{
const u32 scaled = ((b * c) + 64u) >> 7;
return (scaled > 255u) ? 255u : scaled;
};
return channel( base & 0xFFu, cached & 0xFFu)
| (channel((base >> 8) & 0xFFu, (cached >> 8) & 0xFFu) << 8)
| (channel((base >> 16) & 0xFFu, (cached >> 16) & 0xFFu) << 16)
| (base & 0xFF000000u); // The batch keeps its own alpha.
}
// Swaps the batch colour's alpha for this vertex's own, clamped onto the GS's
// 0..0x80 = 0..1.0 alpha scale.
Q_ALWAYS_INLINE u32 WithVertexAlpha(u32 rgba, float alpha)
{
const float scaled = alpha * 128.0f;
const u32 packed = (scaled >= 128.0f) ? 128u
: (scaled <= 0.0f) ? 0u
: static_cast<u32>(scaled);
return (rgba & 0x00FFFFFFu) | (packed << 24);
}
// One triangle from the gathers that are not surfaces - sprites, beams, null
// models and the dlight flares - straight into the batch. VU1 cuts it.
//
// The corners arrive carrying a position and UVs, and for the flares an alpha
// per vertex in st.z, which is the one thing the batch colour cannot express;
// it folds into rgba here, which is where the clipper's extra lanes used to go.
// The two free lanes DrawVertex keeps for the world's second UV set are zeroed:
// no microprogram reads them, the translation row being scaled by a hardwired
// 1.0 and Q synthesised from the divide.
Q_ALWAYS_INLINE void GatherTriangle(const GatherCorner (&corners)[3], const SurfaceDrawState & state)
{
state.stream->BeginVerts(3);
vu1::DrawVertex * __restrict const dst = state.stream->PushTriangle();
for (int i = 0; i < 3; ++i)
{
const GatherCorner & src = corners[i];
dst[i].position = src.position;
dst[i].rgba = state.vertexAlpha ? WithVertexAlpha(state.rgba, src.st.z) : state.rgba;
dst[i].s = src.st.x;
dst[i].t = src.st.y;
dst[i].lightmap_s = 0.0f;
dst[i].lightmap_t = 0.0f;
}
}
// Hands the pass's transform, flags and texture to its stream, which flushes whatever it gathered
// under the outgoing set first. Everything submitted from here draws with these.
Q_ALWAYS_INLINE void ApplyDrawState(const SurfaceDrawState & state, const tex::Texture & texture)
{
state.stream->SetTransform(*state.mvp);
state.stream->SetDrawFlags(state.flags);
state.stream->SetTexture(texture);
}
// Every vertex the polygon being gathered can emit, already in the form the
// batch wants. Filled by GatherPolyTriangles, and bounded by
// mod::kTriangulationMaxVerts as it is. File level rather than a local because
// 128 entries is 4 KB of stack, and gathers never interleave - the same
// single-caller-at-a-time discipline the sky path's clip::Scratch relies on.
static mod::PolyVertex s_polyVertexCache[mod::kTriangulationMaxVerts];
// Fills s_polyVertexCache with the polygon's vertices as the batch wants them.
//
// Every read of the draw state is hoisted into a local first. They look loop
// invariant, but the build stores through a mod::PolyVertex while the state
// arrives by reference, and the renderer builds with -fno-strict-aliasing - so
// left in place the compiler must assume each store could have changed them and
// reload all four every single time round.
Q_ALWAYS_INLINE void BuildPolyVertexCache(const mod::ModelPoly & poly, const SurfaceDrawState & state)
{
const mod::PolyVertex * const verts = poly.vertexes;
const bool tinted = state.lightmapTint;
const bool lightmapUVs = state.lightmapUVs;
const u32 baseRgba = state.rgba;
// The untinted colour is the same for every vertex of every polygon: this
// path leaves the alpha lane zero, so the alpha branch reads a
// constant 0.0f here. Fold it once rather than per vertex.
const u32 flatRgba = (!tinted && state.vertexAlpha) ? WithVertexAlpha(baseRgba, 0.0f) : baseRgba;
const int numVerts = poly.numVerts;
for (int v = 0; v < numVerts; ++v)
{
const mod::PolyVertex & src = verts[v];
mod::PolyVertex & dst = s_polyVertexCache[v];
dst.position = src.position;
// The chroma comes off the vertex rather than out of the atlas: it was
// sampled once when the luxels were baked. See PolyVertex::rgba.
dst.rgba = tinted ? ApplyCachedLightmapColor(baseRgba, src.rgba) : flatRgba;
dst.s = lightmapUVs ? src.lightmap_s : src.s;
dst.t = lightmapUVs ? src.lightmap_t : src.t;
// The lightmap lanes are left as they fall: nothing downstream reads them.
}
}