forked from stepmania/stepmania
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRageDisplay.cpp
1132 lines (935 loc) · 28.6 KB
/
RageDisplay.cpp
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 "global.h"
#include "RageDisplay.h"
#include "RageMath.hpp"
#include "RageTimer.h"
#include "RageLog.h"
#include "RageMath.h"
#include "RageUtil.h"
#include "RageFile.h"
#include "RageSurface_Save_BMP.h"
#include "RageSurface_Save_JPEG.h"
#include "RageSurface_Save_PNG.h"
#include "RageSurfaceUtils_Zoom.h"
#include "RageSurface.h"
#include "Preference.h"
#include "LocalizedString.h"
#include "DisplaySpec.h"
#include "arch/ArchHooks/ArchHooks.h"
// Needed for stats (GetPPS)
#include "InputQueue.h"
// This is disabled by default, as the stat is misleading to users.
Preference<bool> show_pps("ShowPPS", false);
using std::vector;
// Statistics stuff
RageTimer g_LastCheckTimer;
int g_iNumVerts;
int g_iFPS, g_iVPF, g_iCFPS;
int RageDisplay::GetFPS() const { return g_iFPS; }
int RageDisplay::GetVPF() const { return g_iVPF; }
int RageDisplay::GetCumFPS() const { return g_iCFPS; }
static int g_iFramesRenderedSinceLastCheck,
g_iFramesRenderedSinceLastReset,
g_iVertsRenderedSinceLastCheck,
g_iNumChecksSinceLastReset;
static RageTimer g_LastFrameEndedAt( RageZeroTimer );
struct Centering
{
Centering( int iTranslateX = 0, int iTranslateY = 0, int iAddWidth = 0, int iAddHeight = 0 ):
m_iTranslateX( iTranslateX ),
m_iTranslateY( iTranslateY ),
m_iAddWidth( iAddWidth ),
m_iAddHeight( iAddHeight ) { }
int m_iTranslateX, m_iTranslateY, m_iAddWidth, m_iAddHeight;
};
static vector<Centering> g_CenteringStack( 1, Centering(0, 0, 0, 0) );
RageDisplay* DISPLAY = nullptr; // global and accessible from anywhere in our program
Preference<bool> LOG_FPS( "LogFPS", true );
Preference<float> g_fFrameLimitPercent( "FrameLimitPercent", 0.0f );
static const char *RagePixelFormatNames[] = {
"RGBA8",
"BGRA8",
"RGBA4",
"RGB5A1",
"RGB5",
"RGB8",
"PAL",
"BGR8",
"A1BGR5",
"X1RGB5",
};
XToString( RagePixelFormat );
/* bNeedReloadTextures is set to true if the device was re-created and we need
* to reload textures. On failure, an error message is returned.
* XXX: the renderer itself should probably be the one to try fallback modes */
static LocalizedString SETVIDEOMODE_FAILED ( "RageDisplay", "SetVideoMode failed:" );
std::string RageDisplay::SetVideoMode( VideoModeParams p, bool &bNeedReloadTextures )
{
std::string err;
vector<std::string> vs;
if( (err = this->TryVideoMode(p,bNeedReloadTextures)) == "" )
{
return "";
}
LOG->Trace( "TryVideoMode failed: %s", err.c_str() );
vs.push_back( err );
// fall back to settings that will most likely work
p.bpp = 16;
if( (err = this->TryVideoMode(p,bNeedReloadTextures)) == "" )
{
return "";
}
vs.push_back( err );
// "Intel(R) 82810E Graphics Controller" won't accept a 16 bpp surface if
// the desktop is 32 bpp, so try 32 bpp as well.
p.bpp = 32;
if( (err = this->TryVideoMode(p,bNeedReloadTextures)) == "" )
{
return "";
}
vs.push_back( err );
// Fall back on a known resolution good rather than 640 x 480.
DisplaySpecs dr;
this->GetDisplaySpecs(dr);
if( dr.empty() )
{
vs.push_back( "No display resolutions" );
return SETVIDEOMODE_FAILED.GetValue() + " " + Rage::join(";",vs);
}
DisplaySpec d = *dr.begin();
// Try to find DisplaySpec corresponding to requested display
for (const auto &candidate: dr)
{
if (candidate.currentMode() != nullptr)
{
d = candidate;
if (candidate.id() == p.sDisplayId)
{
break;
}
}
}
p.sDisplayId = d.id();
const DisplayMode supported = d.currentMode() != nullptr ? *d.currentMode() : *d.supportedModes().begin();
p.width = supported.width;
p.height = supported.height;
p.rate = static_cast<int> (round(supported.refreshRate));
if( (err = this->TryVideoMode(p,bNeedReloadTextures)) == "" )
{
return "";
}
vs.push_back( err );
return SETVIDEOMODE_FAILED.GetValue() + " " + Rage::join(";",vs);
}
void RageDisplay::ProcessStatsOnFlip()
{
g_iFramesRenderedSinceLastCheck++;
g_iFramesRenderedSinceLastReset++;
if( g_LastCheckTimer.PeekDeltaTime() >= 1.0f ) // update stats every 1 sec.
{
float fActualTime = g_LastCheckTimer.GetDeltaTime();
g_iNumChecksSinceLastReset++;
g_iFPS = std::lrint( g_iFramesRenderedSinceLastCheck / fActualTime );
g_iCFPS = g_iFramesRenderedSinceLastReset / g_iNumChecksSinceLastReset;
g_iCFPS = std::lrint( g_iCFPS / fActualTime );
g_iVPF = g_iVertsRenderedSinceLastCheck / g_iFramesRenderedSinceLastCheck;
g_iFramesRenderedSinceLastCheck = g_iVertsRenderedSinceLastCheck = 0;
if( LOG_FPS )
{
std::string sStats = GetStats();
Rage::replace(sStats, "\n", ", " );
LOG->Trace( "%s", sStats.c_str() );
}
}
}
void RageDisplay::ResetStats()
{
g_iFPS = g_iVPF = 0;
g_iFramesRenderedSinceLastCheck = g_iFramesRenderedSinceLastReset = 0;
g_iNumChecksSinceLastReset = 0;
g_iVertsRenderedSinceLastCheck = 0;
g_LastCheckTimer.GetDeltaTime();
}
std::string RageDisplay::GetStats() const
{
std::string s;
// If FPS == 0, we don't have stats yet.
if( !GetFPS() )
s = "-- FPS\n-- av FPS\n-- VPF";
else
s = fmt::sprintf( "%i FPS\n%i av FPS\n%i VPF", GetFPS(), GetCumFPS(), GetVPF() );
s += "\n" + this->GetApiDescription();
if (show_pps)
{
s += "\n";
auto pps = INPUTQUEUE->GetPPS();
for (auto &device : pps)
{
s += fmt::sprintf("%s: %d\n", device.first, device.second);
}
}
return s;
}
bool RageDisplay::BeginFrame()
{
this->SetDefaultRenderStates();
return true;
}
void RageDisplay::EndFrame()
{
ProcessStatsOnFlip();
}
void RageDisplay::BeginConcurrentRendering()
{
this->SetDefaultRenderStates();
}
void RageDisplay::StatsAddVerts( int iNumVertsRendered ) { g_iVertsRenderedSinceLastCheck += iNumVertsRendered; }
/* Draw a line as a quad. GL_LINES with SmoothLines off can draw line
* ends at odd angles--they're forced to axis-alignment regardless of the
* angle of the line. */
void RageDisplay::DrawPolyLine(const Rage::SpriteVertex &p1, const Rage::SpriteVertex &p2, float LineWidth )
{
// soh cah toa strikes strikes again!
float opp = p2.p.x - p1.p.x;
float adj = p2.p.y - p1.p.y;
float hyp = std::pow(opp*opp + adj*adj, 0.5f);
float lsin = opp/hyp;
float lcos = adj/hyp;
Rage::SpriteVertex v[4];
v[0] = v[1] = p1;
v[2] = v[3] = p2;
float ydist = lsin * LineWidth/2;
float xdist = lcos * LineWidth/2;
v[0].p.x += xdist;
v[0].p.y -= ydist;
v[1].p.x -= xdist;
v[1].p.y += ydist;
v[2].p.x -= xdist;
v[2].p.y += ydist;
v[3].p.x += xdist;
v[3].p.y -= ydist;
this->DrawQuad(v);
}
void RageDisplay::DrawLineStripInternal( const Rage::SpriteVertex v[], int iNumVerts, float LineWidth )
{
ASSERT( iNumVerts >= 2 );
/* Draw a line strip with rounded corners using polys. This is used on
* cards that have strange allergic reactions to antialiased points and
* lines. */
for( int i = 0; i < iNumVerts-1; ++i )
DrawPolyLine(v[i], v[i+1], LineWidth);
// Join the lines with circles so we get rounded corners.
for( int i = 0; i < iNumVerts; ++i )
DrawCircle( v[i], LineWidth/2 );
}
void RageDisplay::DrawCircleInternal( const Rage::SpriteVertex &p, float radius )
{
const int subdivisions = 32;
Rage::SpriteVertex v[subdivisions+2];
v[0] = p;
for(int i = 0; i < subdivisions+1; ++i)
{
const float fRotation = float(i) / subdivisions * 2 * Rage::PI;
const float fX = Rage::FastCos(fRotation) * radius;
const float fY = -Rage::FastSin(fRotation) * radius;
v[1+i] = v[0];
v[1+i].p.x += fX;
v[1+i].p.y += fY;
}
this->DrawFan( v, subdivisions+2 );
}
void RageDisplay::SetDefaultRenderStates()
{
SetLighting( false );
SetCullMode( CULL_NONE );
SetZWrite( false );
SetZTestMode( ZTEST_OFF );
SetAlphaTest( true );
SetBlendMode( BLEND_NORMAL );
SetTextureFiltering( TextureUnit_1, true );
SetZBias( 0 );
LoadMenuPerspective( 0, 640, 480, 320, 240 ); // 0 FOV = ortho
}
// Matrix stuff
class MatrixStack
{
vector<Rage::Matrix> stack;
public:
MatrixStack(): stack()
{
stack.resize(1);
LoadIdentity();
}
// Pops the top of the stack.
void Pop()
{
stack.pop_back();
ASSERT( stack.size() > 0 ); // underflow
}
// Pushes the stack by one, duplicating the current matrix.
void Push()
{
stack.push_back( stack.back() );
ASSERT( stack.size() < 100 ); // overflow
}
// Loads identity in the current matrix.
void LoadIdentity()
{
auto &tmp = stack.back();
tmp = Rage::Matrix::GetIdentity();
}
// Loads the given matrix into the current matrix
void LoadMatrix( const Rage::Matrix& m )
{
stack.back() = m;
}
// Right-Multiplies the given matrix to the current matrix.
// (transformation is about the current world origin)
void MultMatrix( const Rage::Matrix& m )
{
RageMatrixMultiply( &stack.back(), &m, &stack.back() );
}
// Left-Multiplies the given matrix to the current matrix
// (transformation is about the local origin of the object)
void MultMatrixLocal( const Rage::Matrix& m )
{
RageMatrixMultiply( &stack.back(), &stack.back(), &m );
}
// Right multiply the current matrix with the computed rotation
// matrix, counterclockwise about the given axis with the given angle.
// (rotation is about the current world origin)
void RotateX( float degrees )
{
Rage::Matrix m;
RageMatrixRotationX( &m, degrees );
MultMatrix( m );
}
void RotateY( float degrees )
{
Rage::Matrix m;
RageMatrixRotationY( &m, degrees );
MultMatrix( m );
}
void RotateZ( float degrees )
{
Rage::Matrix m;
RageMatrixRotationZ( &m, degrees );
MultMatrix( m );
}
// Left multiply the current matrix with the computed rotation
// matrix. All angles are counterclockwise. (rotation is about the
// local origin of the object)
void RotateXLocal( float degrees )
{
Rage::Matrix m;
RageMatrixRotationX( &m, degrees );
MultMatrixLocal( m );
}
void RotateYLocal( float degrees )
{
Rage::Matrix m;
RageMatrixRotationY( &m, degrees );
MultMatrixLocal( m );
}
void RotateZLocal( float degrees )
{
Rage::Matrix m;
RageMatrixRotationZ( &m, degrees );
MultMatrixLocal( m );
}
// Right multiply the current matrix with the computed scale
// matrix. (transformation is about the current world origin)
void Scale( float x, float y, float z )
{
auto m = Rage::Matrix::GetScaling(x, y, z);
MultMatrix( m );
}
// Left multiply the current matrix with the computed scale
// matrix. (transformation is about the local origin of the object)
void ScaleLocal( float x, float y, float z )
{
auto m = Rage::Matrix::GetScaling(x, y, z);
MultMatrixLocal( m );
}
// Right multiply the current matrix with the computed translation
// matrix. (transformation is about the current world origin)
void Translate( float x, float y, float z )
{
auto m = Rage::Matrix::GetTranslation(x, y, z);
MultMatrix( m );
}
// Left multiply the current matrix with the computed translation
// matrix. (transformation is about the local origin of the object)
void TranslateLocal( float x, float y, float z )
{
auto m = Rage::Matrix::GetTranslation(x, y, z);
MultMatrixLocal( m );
}
void SkewX( float fAmount )
{
auto m = Rage::Matrix::GetSkewX(fAmount);
MultMatrixLocal( m );
}
void SkewY( float fAmount )
{
auto m = Rage::Matrix::GetSkewY(fAmount);
MultMatrixLocal( m );
}
// Obtain the current matrix at the top of the stack
const Rage::Matrix* GetTop() const { return &stack.back(); }
void SetTop( const Rage::Matrix &m ) { stack.back() = m; }
};
static Rage::Matrix g_CenteringMatrix;
static MatrixStack g_ProjectionStack;
static MatrixStack g_ViewStack;
static MatrixStack g_WorldStack;
static MatrixStack g_TextureStack;
RageDisplay::RageDisplay()
{
g_CenteringMatrix = Rage::Matrix::GetIdentity();
g_ProjectionStack = MatrixStack();
g_ViewStack = MatrixStack();
g_WorldStack = MatrixStack();
g_TextureStack = MatrixStack();
// Register with Lua.
{
Lua *L = LUA->Get();
lua_pushstring( L, "DISPLAY" );
this->PushSelf( L );
lua_settable( L, LUA_GLOBALSINDEX );
LUA->Release( L );
}
}
RageDisplay::~RageDisplay()
{
// Unregister with Lua.
LUA->UnsetGlobal( "DISPLAY" );
}
const Rage::Matrix* RageDisplay::GetCentering() const
{
return &g_CenteringMatrix;
}
const Rage::Matrix* RageDisplay::GetProjectionTop() const
{
return g_ProjectionStack.GetTop();
}
const Rage::Matrix* RageDisplay::GetViewTop() const
{
return g_ViewStack.GetTop();
}
const Rage::Matrix* RageDisplay::GetWorldTop() const
{
return g_WorldStack.GetTop();
}
const Rage::Matrix* RageDisplay::GetTextureTop() const
{
return g_TextureStack.GetTop();
}
void RageDisplay::PushMatrix()
{
g_WorldStack.Push();
}
void RageDisplay::PopMatrix()
{
g_WorldStack.Pop();
}
void RageDisplay::Translate( float x, float y, float z )
{
g_WorldStack.TranslateLocal(x, y, z);
}
void RageDisplay::TranslateWorld( float x, float y, float z )
{
g_WorldStack.Translate(x, y, z);
}
void RageDisplay::Scale( float x, float y, float z )
{
g_WorldStack.ScaleLocal(x, y, z);
}
void RageDisplay::RotateX( float deg )
{
g_WorldStack.RotateXLocal( deg );
}
void RageDisplay::RotateY( float deg )
{
g_WorldStack.RotateYLocal( deg );
}
void RageDisplay::RotateZ( float deg )
{
g_WorldStack.RotateZLocal( deg );
}
void RageDisplay::SkewX( float fAmount )
{
g_WorldStack.SkewX( fAmount );
}
void RageDisplay::SkewY( float fAmount )
{
g_WorldStack.SkewY( fAmount );
}
void RageDisplay::PostMultMatrix( const Rage::Matrix &m )
{
g_WorldStack.MultMatrix( m );
}
void RageDisplay::PreMultMatrix( const Rage::Matrix &m )
{
g_WorldStack.MultMatrixLocal( m );
}
void RageDisplay::LoadIdentity()
{
g_WorldStack.LoadIdentity();
}
void RageDisplay::TexturePushMatrix()
{
g_TextureStack.Push();
}
void RageDisplay::TexturePopMatrix()
{
g_TextureStack.Pop();
}
void RageDisplay::TextureTranslate( float x, float y )
{
g_TextureStack.TranslateLocal(x, y, 0);
}
void RageDisplay::LoadMenuPerspective( float fovDegrees, float fWidth, float fHeight, float fVanishPointX, float fVanishPointY )
{
// fovDegrees == 0 gives ortho projection.
if( fovDegrees == 0 )
{
float left = 0, right = fWidth, bottom = fHeight, top = 0;
g_ProjectionStack.LoadMatrix( GetOrthoMatrix(left, right, bottom, top, -1000, +1000) );
g_ViewStack.LoadIdentity();
}
else
{
fovDegrees = Rage::clamp( fovDegrees, 0.1f, 179.9f );
float fovRadians = fovDegrees / 180.f * Rage::PI;
float theta = fovRadians/2;
float fDistCameraFromImage = fWidth/2 / std::tan( theta );
fVanishPointX = Rage::scale( fVanishPointX, 0.f, fWidth, fWidth, 0.f );
fVanishPointY = Rage::scale( fVanishPointY, 0.f, fHeight, fHeight, 0.f );
fVanishPointX -= fWidth/2;
fVanishPointY -= fHeight/2;
// It's the caller's responsibility to push first.
g_ProjectionStack.LoadMatrix(
GetFrustumMatrix(
(fVanishPointX-fWidth/2)/fDistCameraFromImage,
(fVanishPointX+fWidth/2)/fDistCameraFromImage,
(fVanishPointY+fHeight/2)/fDistCameraFromImage,
(fVanishPointY-fHeight/2)/fDistCameraFromImage,
1,
fDistCameraFromImage+1000 ) );
g_ViewStack.LoadMatrix(
RageLookAt(
-fVanishPointX+fWidth/2, -fVanishPointY+fHeight/2, fDistCameraFromImage,
-fVanishPointX+fWidth/2, -fVanishPointY+fHeight/2, 0,
0.0f, 1.0f, 0.0f) );
}
}
void RageDisplay::CameraPushMatrix()
{
g_ProjectionStack.Push();
g_ViewStack.Push();
}
void RageDisplay::CameraPopMatrix()
{
g_ProjectionStack.Pop();
g_ViewStack.Pop();
}
/* gluLookAt. The result is pre-multiplied to the matrix (M = L * M) instead of
* post-multiplied. */
void RageDisplay::LoadLookAt( float fFOV, const Rage::Vector3 &Eye, const Rage::Vector3 &At, const Rage::Vector3 &Up )
{
float fAspect = GetActualVideoModeParams().fDisplayAspectRatio;
g_ProjectionStack.LoadMatrix( GetPerspectiveMatrix(fFOV, fAspect, 1, 1000) );
// Flip the Y coordinate, so positive numbers go down.
g_ProjectionStack.Scale( 1, -1, 1 );
g_ViewStack.LoadMatrix( RageLookAt(Eye.x, Eye.y, Eye.z, At.x, At.y, At.z, Up.x, Up.y, Up.z) );
}
Rage::Matrix RageDisplay::GetPerspectiveMatrix(float fovy, float aspect, float zNear, float zFar)
{
float ymax = zNear * std::tan(fovy * Rage::PI / 360.0f);
float ymin = -ymax;
float xmin = ymin * aspect;
float xmax = ymax * aspect;
return GetFrustumMatrix(xmin, xmax, ymin, ymax, zNear, zFar);
}
RageSurface *RageDisplay::CreateSurfaceFromPixfmt( RagePixelFormat pixfmt,
void *pixels, int width, int height, int pitch )
{
const RagePixelFormatDesc *tpf = GetPixelFormatDesc(pixfmt);
RageSurface *surf = CreateSurfaceFrom(
width, height, tpf->bpp,
tpf->masks[0], tpf->masks[1], tpf->masks[2], tpf->masks[3],
(uint8_t *) pixels, pitch );
return surf;
}
RagePixelFormat RageDisplay::FindPixelFormat( int iBPP, unsigned iRmask, unsigned iGmask, unsigned iBmask, unsigned iAmask, bool bRealtime )
{
RagePixelFormatDesc tmp = { iBPP, { iRmask, iGmask, iBmask, iAmask } };
FOREACH_ENUM( RagePixelFormat, iPixFmt )
{
const RagePixelFormatDesc *pf = GetPixelFormatDesc( RagePixelFormat(iPixFmt) );
if( !SupportsTextureFormat(RagePixelFormat(iPixFmt), bRealtime) )
continue;
if( memcmp(pf, &tmp, sizeof(tmp)) )
continue;
return iPixFmt;
}
return RagePixelFormat_Invalid;
}
/* These convert to OpenGL's coordinate system: -1,-1 is the bottom-left,
* +1,+1 is the top-right, and Z goes from -1 (viewer) to +1 (distance).
* It's a little odd, but very well-defined. */
Rage::Matrix RageDisplay::GetOrthoMatrix( float l, float r, float b, float t, float zn, float zf )
{
Rage::Matrix m(
2/(r-l), 0, 0, 0,
0, 2/(t-b), 0, 0,
0, 0, -2/(zf-zn), 0,
-(r+l)/(r-l), -(t+b)/(t-b), -(zf+zn)/(zf-zn), 1 );
return m;
}
Rage::Matrix RageDisplay::GetFrustumMatrix( float l, float r, float b, float t, float zn, float zf )
{
// glFrustum
float A = (r+l) / (r-l);
float B = (t+b) / (t-b);
float C = -1 * (zf+zn) / (zf-zn);
float D = -1 * (2*zf*zn) / (zf-zn);
Rage::Matrix m(
2*zn/(r-l), 0, 0, 0,
0, 2*zn/(t-b), 0, 0,
A, B, C, -1,
0, 0, D, 0 );
return m;
}
void RageDisplay::ResolutionChanged()
{
// The centering matrix depends on the resolution.
UpdateCentering();
}
void RageDisplay::CenteringPushMatrix()
{
g_CenteringStack.push_back( g_CenteringStack.back() );
ASSERT( g_CenteringStack.size() < 100 ); // overflow
}
void RageDisplay::CenteringPopMatrix()
{
g_CenteringStack.pop_back();
ASSERT( g_CenteringStack.size() > 0 ); // underflow
UpdateCentering();
}
void RageDisplay::ChangeCentering( int iTranslateX, int iTranslateY, int iAddWidth, int iAddHeight )
{
g_CenteringStack.back() = Centering( iTranslateX, iTranslateY, iAddWidth, iAddHeight );
UpdateCentering();
}
Rage::Matrix RageDisplay::GetCenteringMatrix( float fTranslateX, float fTranslateY, float fAddWidth, float fAddHeight ) const
{
// in screen space, left edge = -1, right edge = 1, bottom edge = -1. top edge = 1
float fWidth = (float) GetActualVideoModeParams().windowWidth;
float fHeight = (float) GetActualVideoModeParams().windowHeight;
float fPercentShiftX = Rage::scale( fTranslateX, 0.f, fWidth, 0.f, +2.0f );
float fPercentShiftY = Rage::scale( fTranslateY, 0.f, fHeight, 0.f, -2.0f );
float fPercentScaleX = Rage::scale( fAddWidth, 0.f, fWidth, 1.0f, 2.0f );
float fPercentScaleY = Rage::scale( fAddHeight, 0.f, fHeight, 1.0f, 2.0f );
auto m1 = Rage::Matrix::GetTranslation(fPercentShiftX, fPercentShiftY, 0);
auto m2 = Rage::Matrix::GetScaling(fPercentScaleX, fPercentScaleY, 1);
Rage::Matrix mOut;
RageMatrixMultiply( &mOut, &m1, &m2 );
return mOut;
}
void RageDisplay::UpdateCentering()
{
const Centering &p = g_CenteringStack.back();
g_CenteringMatrix = GetCenteringMatrix(
(float) p.m_iTranslateX, (float) p.m_iTranslateY, (float) p.m_iAddWidth, (float) p.m_iAddHeight );
}
bool RageDisplay::SaveScreenshot( std::string sPath, GraphicsFileFormat format )
{
RageTimer timer;
RageSurface *surface = this->CreateScreenshot();
// LOG->Trace( "CreateScreenshot took %f seconds", timer.GetDeltaTime() );
/* Unless we're in lossless, resize the image to 640x480. If we're saving lossy,
* there's no sense in saving 1280x960 screenshots, and we don't want to output
* screenshots in a strange (non-1) sample aspect ratio. */
if( format != SAVE_LOSSLESS && format != SAVE_LOSSLESS_SENSIBLE )
{
// Maintain the DAR.
ASSERT( GetActualVideoModeParams().fDisplayAspectRatio > 0 );
int iHeight = 480;
// This used to be std::lrint. However, std::lrint causes odd resolutions like
// 639x480 (4:3) and 853x480 (16:9). ceilf gives correct values. -aj
int iWidth = static_cast<int>(ceilf( iHeight * GetActualVideoModeParams().fDisplayAspectRatio ));
timer.Touch();
RageSurfaceUtils::Zoom( surface, iWidth, iHeight );
// LOG->Trace( "%ix%i -> %ix%i (%.3f) in %f seconds", surface->w, surface->h, iWidth, iHeight, GetActualVideoModeParams().fDisplayAspectRatio, timer.GetDeltaTime() );
}
RageFile out;
if( !out.Open( sPath, RageFile::WRITE ) )
{
LOG->Trace("Couldn't write %s: %s", sPath.c_str(), out.GetError().c_str() );
Rage::safe_delete( surface );
return false;
}
bool bSuccess = false;
timer.Touch();
std::string strError = "";
switch( format )
{
case SAVE_LOSSLESS:
bSuccess = RageSurfaceUtils::SaveBMP( surface, out );
break;
case SAVE_LOSSLESS_SENSIBLE:
bSuccess = RageSurfaceUtils::SavePNG( surface, out, strError );
break;
case SAVE_LOSSY_LOW_QUAL:
bSuccess = RageSurfaceUtils::SaveJPEG( surface, out, false );
break;
case SAVE_LOSSY_HIGH_QUAL:
bSuccess = RageSurfaceUtils::SaveJPEG( surface, out, true );
break;
DEFAULT_FAIL( format );
}
// LOG->Trace( "Saving Screenshot file took %f seconds.", timer.GetDeltaTime() );
Rage::safe_delete( surface );
if( !bSuccess )
{
LOG->Trace("Couldn't write %s: %s", sPath.c_str(), out.GetError().c_str() );
return false;
}
return true;
}
void RageDisplay::DrawQuads( const Rage::SpriteVertex v[], int iNumVerts )
{
ASSERT( (iNumVerts%4) == 0 );
if(!iNumVerts)
return;
this->DrawQuadsInternal(v,iNumVerts);
StatsAddVerts(iNumVerts);
}
void RageDisplay::DrawQuadStrip( const Rage::SpriteVertex v[], int iNumVerts )
{
ASSERT( (iNumVerts%2) == 0 );
if(iNumVerts < 4)
return;
this->DrawQuadStripInternal(v,iNumVerts);
StatsAddVerts(iNumVerts);
}
void RageDisplay::DrawFan( const Rage::SpriteVertex v[], int iNumVerts )
{
ASSERT( iNumVerts >= 3 );
this->DrawFanInternal(v,iNumVerts);
StatsAddVerts(iNumVerts);
}
void RageDisplay::DrawStrip( const Rage::SpriteVertex v[], int iNumVerts )
{
ASSERT( iNumVerts >= 3 );
this->DrawStripInternal(v,iNumVerts);
StatsAddVerts(iNumVerts);
}
void RageDisplay::DrawTriangles( const Rage::SpriteVertex v[], int iNumVerts )
{
if( iNumVerts == 0 )
return;
ASSERT( iNumVerts >= 3 );
this->DrawTrianglesInternal(v,iNumVerts);
StatsAddVerts(iNumVerts);
}
void RageDisplay::DrawCompiledGeometry( const RageCompiledGeometry *p, int iMeshIndex, const vector<msMesh> &vMeshes )
{
this->DrawCompiledGeometryInternal( p, iMeshIndex );
StatsAddVerts( vMeshes[iMeshIndex].Triangles.size() );
}
void RageDisplay::DrawLineStrip( const Rage::SpriteVertex v[], int iNumVerts, float LineWidth )
{
ASSERT( iNumVerts >= 2 );
this->DrawLineStripInternal( v, iNumVerts, LineWidth );
}
/*
* Draw a strip of:
*
* 0..1..2
* . /.\ .
* ./ . \.
* 3..4..5
* . /.\ .
* ./ . \.
* 6..7..8
*/
void RageDisplay::DrawSymmetricQuadStrip( const Rage::SpriteVertex v[], int iNumVerts )
{
ASSERT( iNumVerts >= 3 );
if( iNumVerts < 6 )
return;
this->DrawSymmetricQuadStripInternal( v, iNumVerts );
StatsAddVerts( iNumVerts );
}
void RageDisplay::DrawCircle( const Rage::SpriteVertex &v, float radius )
{
this->DrawCircleInternal( v, radius );
}
void RageDisplay::FrameLimitBeforeVsync( int iFPS )
{
ASSERT( iFPS != 0 );
using std::max;
int iDelayMicroseconds = 0;
if( g_fFrameLimitPercent.Get() > 0.0f && !g_LastFrameEndedAt.IsZero() )
{
float fFrameTime = g_LastFrameEndedAt.GetDeltaTime();
float fExpectedTime = 1.0f / iFPS;
/* This is typically used to turn some of the delay that would normally
* be waiting for vsync and turn it into a usleep, to make sure we give
* up the CPU. If we overshoot the sleep, then we'll miss the vsync,
* so allow tweaking the amount of time we expect a frame to take.
* Frame limiting is disabled by setting this to 0. */
fExpectedTime *= g_fFrameLimitPercent.Get();
float fExtraTime = fExpectedTime - fFrameTime;
iDelayMicroseconds = int(fExtraTime * 1000000);
}
if( !HOOKS->AppHasFocus() )
iDelayMicroseconds = max( iDelayMicroseconds, 10000 ); // give some time to other processes and threads
#if defined(_WINDOWS)
/* In Windows, always explicitly give up a minimum amount of CPU for other threads. */
iDelayMicroseconds = max( iDelayMicroseconds, 1000 );
#endif
if( iDelayMicroseconds > 0 )
usleep( iDelayMicroseconds );
}
void RageDisplay::FrameLimitAfterVsync()
{
if( g_fFrameLimitPercent.Get() == 0.0f )
return;
g_LastFrameEndedAt.Touch();
}
RageCompiledGeometry::~RageCompiledGeometry()
{
m_bNeedsNormals = false;
}
void RageCompiledGeometry::Set( const vector<msMesh> &vMeshes, bool bNeedsNormals )
{
m_bNeedsNormals = bNeedsNormals;
size_t totalVerts = 0;
size_t totalTriangles = 0;
m_bAnyNeedsTextureMatrixScale = false;
m_vMeshInfo.resize( vMeshes.size() );
for( unsigned i=0; i<vMeshes.size(); i++ )
{
const msMesh& mesh = vMeshes[i];
const vector<Rage::ModelVertex> &Vertices = mesh.Vertices;
const vector<msTriangle> &Triangles = mesh.Triangles;
MeshInfo& meshInfo = m_vMeshInfo[i];
meshInfo.m_bNeedsTextureMatrixScale = false;
meshInfo.iVertexStart = totalVerts;
meshInfo.iVertexCount = Vertices.size();