1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
|
/************************************************************************************
Filename : OculusWorldDemo.cpp
Content : First-person view test application for Oculus Rift - Implementation
Created : October 4, 2012
Authors : Michael Antonov, Andrew Reisse, Steve LaValle, Dov Katz
Peter Hoff, Dan Goodman, Bryan Croteau
Copyright : Copyright 2012 Oculus VR, Inc. All Rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************************/
#include "OculusWorldDemo.h"
//-------------------------------------------------------------------------------------
// ***** OculusWorldDemoApp
OculusWorldDemoApp::OculusWorldDemoApp()
: pRender(0),
WindowSize(1280,800),
ScreenNumber(0),
FirstScreenInCycle(0),
LastVisionProcessingTime(0.),
VisionTimesCount(0),
VisionProcessingSum(0.),
VisionProcessingAverage(0.),
Hmd(0),
StartTrackingCaps(0),
UsingDebugHmd(false),
LoadingState(LoadingState_Frame0),
HaveVisionTracking(false),
HavePositionTracker(false),
HaveHMDConnected(false),
HmdStatus(0),
NotificationTimeout(0.0),
// Initial location
DistortionClearBlue(0),
ShiftDown(false),
CtrlDown(false),
HmdSettingsChanged(false),
// Modifiable options.
RendertargetIsSharedByBothEyes(false),
DynamicRezScalingEnabled(false),
EnableSensor(true),
ForceZeroIpd(false),
DesiredPixelDensity(1.0f),
FovSideTanMax(1.0f), // Updated based on Hmd.
TimewarpEnabled(true),
TimewarpNoJitEnabled(false),
TimewarpRenderIntervalInSeconds(0.0f),
FreezeEyeUpdate(false),
FreezeEyeOneFrameRendered(false),
CenterPupilDepthMeters(0.05f),
ForceZeroHeadMovement(false),
VsyncEnabled(true),
MultisampleEnabled(true),
IsLowPersistence(true),
DynamicPrediction(true),
DisplaySleep(false),
PositionTrackingEnabled(true),
PixelLuminanceOverdrive(true),
HqAaDistortion(true),
MirrorToWindow(true),
SupportsSrgb(true),
// Scene state
SceneMode(Scene_World),
GridDisplayMode(GridDisplay_None),
GridMode(Grid_Lens),
TextScreen(Text_None),
BlocksShowType(0),
BlocksCenter(0.0f, 0.0f, 0.0f)
{
FPS = 0.0f;
SecondsPerFrame = 0.0f;
FrameCounter = 0;
TotalFrameCounter = 0;
LastFpsUpdate = 0;
EyeRenderSize[0] = EyeRenderSize[1] = Sizei(0);
DistortionClearBlue = false;
}
OculusWorldDemoApp::~OculusWorldDemoApp()
{
CleanupDrawTextFont();
if (Hmd)
{
ovrHmd_Destroy(Hmd);
Hmd = 0;
}
CollisionModels.ClearAndRelease();
GroundCollisionModels.ClearAndRelease();
ovr_Shutdown();
}
int OculusWorldDemoApp::OnStartup(int argc, const char** argv)
{
// *** Oculus HMD & Sensor Initialization
// Create DeviceManager and first available HMDDevice from it.
// Sensor object is created from the HMD, to ensure that it is on the
// correct device.
ovr_Initialize();
Hmd = ovrHmd_Create(0);
if (!Hmd)
{
Menu.SetPopupMessage("Unable to create HMD: %s", ovrHmd_GetLastError(NULL));
// If we didn't detect an Hmd, create a simulated one for debugging.
Hmd = ovrHmd_CreateDebug(ovrHmd_DK1);
UsingDebugHmd = true;
if (!Hmd)
{ // Failed Hmd creation.
return 1;
}
}
if (Hmd->HmdCaps & ovrHmdCap_ExtendDesktop)
{
WindowSize = Hmd->Resolution;
}
else
{
// In Direct App-rendered mode, we can use smaller window size,
// as it can have its own contents and isn't tied to the buffer.
WindowSize = Sizei(1100, 618);//Sizei(960, 540); avoid rotated output bug.
}
// ***** Setup System Window & rendering.
if (!SetupWindowAndRendering(argc, argv))
{
return 1;
}
NotificationTimeout = ovr_GetTimeInSeconds() + 10.0f;
// Initialize FovSideTanMax, which allows us to change all Fov sides at once - Fov
// starts at default and is clamped to this value.
FovSideTanLimit = FovPort::Max(Hmd->MaxEyeFov[0], Hmd->MaxEyeFov[1]).GetMaxSideTan();
FovSideTanMax = FovPort::Max(Hmd->DefaultEyeFov[0], Hmd->DefaultEyeFov[1]).GetMaxSideTan();
PositionTrackingEnabled = (Hmd->TrackingCaps & ovrTrackingCap_Position) ? true : false;
PixelLuminanceOverdrive = (Hmd->DistortionCaps & ovrDistortionCap_Overdrive) ? true : false;
HqAaDistortion = (Hmd->DistortionCaps & ovrDistortionCap_HqDistortion) ? true : false;
// *** Configure HMD Stereo settings.
CalculateHmdValues();
// Query eye height.
ThePlayer.UserEyeHeight = ovrHmd_GetFloat(Hmd, OVR_KEY_EYE_HEIGHT, ThePlayer.UserEyeHeight);
ThePlayer.BodyPos.y = ThePlayer.UserEyeHeight;
// Center pupil for customization; real game shouldn't need to adjust this.
CenterPupilDepthMeters = ovrHmd_GetFloat(Hmd, "CenterPupilDepth", 0.0f);
ThePlayer.bMotionRelativeToBody = false; // Default to head-steering for DK1
if (UsingDebugHmd)
Menu.SetPopupMessage("NO HMD DETECTED");
else if (!(ovrHmd_GetTrackingState(Hmd, 0.0f).StatusFlags & ovrStatus_HmdConnected))
Menu.SetPopupMessage("NO SENSOR DETECTED");
else if (Hmd->HmdCaps & ovrHmdCap_ExtendDesktop)
Menu.SetPopupMessage("Press F9 for Full-Screen on Rift");
else
Menu.SetPopupMessage("Please put on Rift");
// Give first message 10 sec timeout, add border lines.
Menu.SetPopupTimeout(10.0f, true);
PopulateOptionMenu();
// *** Identify Scene File & Prepare for Loading
InitMainFilePath();
PopulatePreloadScene();
LastUpdate = ovr_GetTimeInSeconds();
return 0;
}
bool OculusWorldDemoApp::SetupWindowAndRendering(int argc, const char** argv)
{
// *** Window creation
void* windowHandle = pPlatform->SetupWindow(WindowSize.w, WindowSize.h);
if(!windowHandle)
return false;
ovrHmd_AttachToWindow( Hmd, windowHandle, NULL, NULL );
// Report relative mouse motion in OnMouseMove
pPlatform->SetMouseMode(Mouse_Relative);
// *** Initialize Rendering
#if defined(OVR_OS_WIN32)
const char* graphics = "d3d11";
#else
const char* graphics = "GL";
#endif
// Select renderer based on command line arguments.
for(int i = 1; i < argc; i++)
{
if(!strcmp(argv[i], "-r") && i < argc - 1)
{
graphics = argv[i + 1];
}
else if(!strcmp(argv[i], "-fs"))
{
RenderParams.Fullscreen = true;
}
}
String title = "Oculus World Demo ";
title += graphics;
if (Hmd->ProductName[0])
{
title += " : ";
title += Hmd->ProductName;
}
pPlatform->SetWindowTitle(title);
// Enable multi-sampling by default.
RenderParams.Display = DisplayId(Hmd->DisplayDeviceName, Hmd->DisplayId);
RenderParams.Multisample = 1;
RenderParams.Resolution = Hmd->Resolution;
if (OVR_strcmp(graphics, "GL") == 0 && !(Hmd->HmdCaps & ovrHmdCap_ExtendDesktop))
SupportsSrgb = false;
//RenderParams.Fullscreen = true;
pRender = pPlatform->SetupGraphics(OVR_DEFAULT_RENDER_DEVICE_SET,
graphics, RenderParams);
if (!pRender)
return false;
return true;
}
// Custom formatter for Timewarp interval message.
static String FormatTimewarp(OptionVar* var)
{
char buff[64];
float timewarpInterval = *var->AsFloat();
OVR_sprintf(buff, sizeof(buff), "%.1fms, %.1ffps",
timewarpInterval * 1000.0f,
( timewarpInterval > 0.000001f ) ? 1.0f / timewarpInterval : 10000.0f);
return String(buff);
}
static String FormatMaxFromSideTan(OptionVar* var)
{
char buff[64];
float degrees = 2.0f * atan(*var->AsFloat()) * (180.0f / MATH_FLOAT_PI);
OVR_sprintf(buff, sizeof(buff), "%.1f Degrees", degrees);
return String(buff);
}
void OculusWorldDemoApp::PopulateOptionMenu()
{
// For shortened function member access.
typedef OculusWorldDemoApp OWD;
// *** Scene Content Sub-Menu
// Test
/*
Menu.AddEnum("Scene Content.EyePoseMode", &FT_EyePoseState).AddShortcutKey(Key_Y).
AddEnumValue("Separate Pose", 0).
AddEnumValue("Same Pose", 1).
AddEnumValue("Same Pose+TW", 2);
*/
// Navigate between scenes.
Menu.AddEnum("Scene Content.Rendered Scene ';'", &SceneMode).AddShortcutKey(Key_Semicolon).
AddEnumValue("World", Scene_World).
AddEnumValue("Cubes", Scene_Cubes).
AddEnumValue("Oculus Cubes", Scene_OculusCubes);
// Animating blocks
Menu.AddEnum("Scene Content.Animated Blocks", &BlocksShowType).
AddShortcutKey(Key_B).SetNotify(this, &OWD::BlockShowChange).
AddEnumValue("None", 0).
AddEnumValue("Horizontal Circle", 1).
AddEnumValue("Vertical Circle", 2).
AddEnumValue("Bouncing Blocks", 3);
// Toggle grid
Menu.AddEnum("Scene Content.Grid Display 'G'", &GridDisplayMode).AddShortcutKey(Key_G).
AddEnumValue("No Grid", GridDisplay_None).
AddEnumValue("Grid Only", GridDisplay_GridOnly).
AddEnumValue("Grid And Scene", GridDisplay_GridAndScene);
Menu.AddEnum("Scene Content.Grid Mode 'H'", &GridMode).AddShortcutKey(Key_H).
AddEnumValue("4-pixel RT-centered", Grid_Rendertarget4).
AddEnumValue("16-pixel RT-centered",Grid_Rendertarget16).
AddEnumValue("Lens-centered grid", Grid_Lens);
// *** Scene Content Sub-Menu
Menu.AddBool( "Render Target.Share RenderTarget", &RendertargetIsSharedByBothEyes).
AddShortcutKey(Key_F8).SetNotify(this, &OWD::HmdSettingChange);
Menu.AddBool( "Render Target.Dynamic Res Scaling", &DynamicRezScalingEnabled).
AddShortcutKey(Key_F8, ShortcutKey::Shift_RequireOn);
Menu.AddBool( "Sensor Toggle 'F6'", &EnableSensor).
AddShortcutKey(Key_F6).
SetNotify(this, &OWD::HmdSensorToggle);
Menu.AddBool( "Render Target.Zero IPD 'F7'", &ForceZeroIpd).
AddShortcutKey(Key_F7).
SetNotify(this, &OWD::HmdSettingChangeFreeRTs);
Menu.AddFloat("Render Target.Max Fov", &FovSideTanMax, 0.2f, FovSideTanLimit, 0.02f,
"%.1f Degrees", 1.0f, &FormatMaxFromSideTan).
SetNotify(this, &OWD::HmdSettingChange).
AddShortcutUpKey(Key_I).AddShortcutDownKey(Key_K);
Menu.AddFloat("Render Target.Pixel Density", &DesiredPixelDensity, 0.5f, 1.5, 0.025f, "%3.2f", 1.0f).
SetNotify(this, &OWD::HmdSettingChange);
Menu.AddEnum( "Render Target.Distortion Clear Color", &DistortionClearBlue).
SetNotify(this, &OWD::DistortionClearColorChange).
AddEnumValue("Black", 0).
AddEnumValue("Blue", 1);
// Timewarp
Menu.AddBool( "Timewarp.TimewarpEnabled 'O'", &TimewarpEnabled).AddShortcutKey(Key_O).
SetNotify(this, &OWD::HmdSettingChange);
Menu.AddBool( "Timewarp.Timewarp No-JIT", &TimewarpNoJitEnabled).SetNotify(this, &OWD::HmdSettingChange);
Menu.AddBool( "Timewarp.FreezeEyeUpdate 'C'", &FreezeEyeUpdate).AddShortcutKey(Key_C);
Menu.AddFloat("Timewarp.RenderIntervalSeconds", &TimewarpRenderIntervalInSeconds,
0.0001f, 1.00f, 0.0001f, "%.1f", 1.0f, &FormatTimewarp).
AddShortcutUpKey(Key_J).AddShortcutDownKey(Key_U);
// First page properties
Menu.AddFloat("User Eye Height", &ThePlayer.UserEyeHeight, 0.2f, 2.5f, 0.02f,
"%4.2f m").SetNotify(this, &OWD::EyeHeightChange).
AddShortcutUpKey(Key_Equal).AddShortcutDownKey(Key_Minus);
Menu.AddFloat("Center Pupil Depth", &CenterPupilDepthMeters, 0.0f, 0.2f, 0.001f,
"%4.3f m").SetNotify(this, &OWD::CenterPupilDepthChange);
Menu.AddBool("Body Relative Motion",&ThePlayer.bMotionRelativeToBody).AddShortcutKey(Key_E);
Menu.AddBool("Zero Head Movement", &ForceZeroHeadMovement) .AddShortcutKey(Key_F7, ShortcutKey::Shift_RequireOn);
Menu.AddBool("VSync 'V'", &VsyncEnabled) .AddShortcutKey(Key_V).SetNotify(this, &OWD::HmdSettingChange);
Menu.AddBool("MultiSample 'F4'", &MultisampleEnabled) .AddShortcutKey(Key_F4).SetNotify(this, &OWD::MultisampleChange);
Menu.AddBool("High Quality Distortion", &HqAaDistortion) .AddShortcutKey(Key_F5).SetNotify(this, &OWD::HmdSettingChange);
Menu.AddTrigger("Recenter HMD pose 'R'").AddShortcutKey(Key_R).SetNotify(this, &OWD::ResetHmdPose);
// Add DK2 options to menu only for that headset.
if (Hmd->TrackingCaps & ovrTrackingCap_Position)
{
Menu.AddBool("Low Persistence 'P'", &IsLowPersistence).
AddShortcutKey(Key_P).SetNotify(this, &OWD::HmdSettingChange);
Menu.AddBool("Dynamic Prediction", &DynamicPrediction).
SetNotify(this, &OWD::HmdSettingChange);
Menu.AddBool("Display Sleep", &DisplaySleep).
AddShortcutKey(Key_Z).SetNotify(this, &OWD::HmdSettingChange);
Menu.AddBool("Positional Tracking 'X'", &PositionTrackingEnabled).
AddShortcutKey(Key_X).SetNotify(this, &OWD::HmdSettingChange);
Menu.AddBool("Pixel Luminance Overdrive", &PixelLuminanceOverdrive).SetNotify(this, &OWD::HmdSettingChange);
}
if (!(Hmd->HmdCaps & ovrHmdCap_ExtendDesktop))
{
Menu.AddBool("Mirror To Window", &MirrorToWindow).
AddShortcutKey(Key_M).SetNotify(this, &OWD::MirrorSettingChange);
}
}
void OculusWorldDemoApp::CalculateHmdValues()
{
// Initialize eye rendering information for ovrHmd_Configure.
// The viewport sizes are re-computed in case RenderTargetSize changed due to HW limitations.
ovrFovPort eyeFov[2];
eyeFov[0] = Hmd->DefaultEyeFov[0];
eyeFov[1] = Hmd->DefaultEyeFov[1];
// Clamp Fov based on our dynamically adjustable FovSideTanMax.
// Most apps should use the default, but reducing Fov does reduce rendering cost.
eyeFov[0] = FovPort::Min(eyeFov[0], FovPort(FovSideTanMax));
eyeFov[1] = FovPort::Min(eyeFov[1], FovPort(FovSideTanMax));
if (ForceZeroIpd)
{
// ForceZeroIpd does three things:
// 1) Sets FOV to maximum symmetrical FOV based on both eyes
// 2) Sets eye ViewAdjust values to 0.0 (effective IPD == 0)
// 3) Uses only the Left texture for rendering.
eyeFov[0] = FovPort::Max(eyeFov[0], eyeFov[1]);
eyeFov[1] = eyeFov[0];
Sizei recommenedTexSize = ovrHmd_GetFovTextureSize(Hmd, ovrEye_Left,
eyeFov[0], DesiredPixelDensity);
Sizei textureSize = EnsureRendertargetAtLeastThisBig(Rendertarget_Left, recommenedTexSize);
EyeRenderSize[0] = Sizei::Min(textureSize, recommenedTexSize);
EyeRenderSize[1] = EyeRenderSize[0];
// Store texture pointers that will be passed for rendering.
EyeTexture[0] = RenderTargets[Rendertarget_Left].Tex;
EyeTexture[0].Header.TextureSize = textureSize;
EyeTexture[0].Header.RenderViewport = Recti(EyeRenderSize[0]);
// Right eye is the same.
EyeTexture[1] = EyeTexture[0];
}
else
{
// Configure Stereo settings. Default pixel density is 1.0f.
Sizei recommenedTex0Size = ovrHmd_GetFovTextureSize(Hmd, ovrEye_Left, eyeFov[0], DesiredPixelDensity);
Sizei recommenedTex1Size = ovrHmd_GetFovTextureSize(Hmd, ovrEye_Right, eyeFov[1], DesiredPixelDensity);
if (RendertargetIsSharedByBothEyes)
{
Sizei rtSize(recommenedTex0Size.w + recommenedTex1Size.w,
Alg::Max(recommenedTex0Size.h, recommenedTex1Size.h));
// Use returned size as the actual RT size may be different due to HW limits.
rtSize = EnsureRendertargetAtLeastThisBig(Rendertarget_BothEyes, rtSize);
// Don't draw more then recommended size; this also ensures that resolution reported
// in the overlay HUD size is updated correctly for FOV/pixel density change.
EyeRenderSize[0] = Sizei::Min(Sizei(rtSize.w/2, rtSize.h), recommenedTex0Size);
EyeRenderSize[1] = Sizei::Min(Sizei(rtSize.w/2, rtSize.h), recommenedTex1Size);
// Store texture pointers that will be passed for rendering.
// Same texture is used, but with different viewports.
EyeTexture[0] = RenderTargets[Rendertarget_BothEyes].Tex;
EyeTexture[0].Header.TextureSize = rtSize;
EyeTexture[0].Header.RenderViewport = Recti(Vector2i(0), EyeRenderSize[0]);
EyeTexture[1] = RenderTargets[Rendertarget_BothEyes].Tex;
EyeTexture[1].Header.TextureSize = rtSize;
EyeTexture[1].Header.RenderViewport = Recti(Vector2i((rtSize.w+1)/2, 0), EyeRenderSize[1]);
}
else
{
Sizei tex0Size = EnsureRendertargetAtLeastThisBig(Rendertarget_Left, recommenedTex0Size);
Sizei tex1Size = EnsureRendertargetAtLeastThisBig(Rendertarget_Right, recommenedTex1Size);
EyeRenderSize[0] = Sizei::Min(tex0Size, recommenedTex0Size);
EyeRenderSize[1] = Sizei::Min(tex1Size, recommenedTex1Size);
// Store texture pointers and viewports that will be passed for rendering.
EyeTexture[0] = RenderTargets[Rendertarget_Left].Tex;
EyeTexture[0].Header.TextureSize = tex0Size;
EyeTexture[0].Header.RenderViewport = Recti(EyeRenderSize[0]);
EyeTexture[1] = RenderTargets[Rendertarget_Right].Tex;
EyeTexture[1].Header.TextureSize = tex1Size;
EyeTexture[1].Header.RenderViewport = Recti(EyeRenderSize[1]);
}
}
// Hmd caps.
unsigned hmdCaps = (VsyncEnabled ? 0 : ovrHmdCap_NoVSync);
if (IsLowPersistence)
hmdCaps |= ovrHmdCap_LowPersistence;
// ovrHmdCap_DynamicPrediction - enables internal latency feedback
if (DynamicPrediction)
hmdCaps |= ovrHmdCap_DynamicPrediction;
// ovrHmdCap_DisplayOff - turns off the display
if (DisplaySleep)
hmdCaps |= ovrHmdCap_DisplayOff;
if (!MirrorToWindow)
hmdCaps |= ovrHmdCap_NoMirrorToWindow;
// If using our driver, display status overlay messages.
if (!(Hmd->HmdCaps & ovrHmdCap_ExtendDesktop) && (NotificationTimeout != 0.0f))
{
GetPlatformCore()->SetNotificationOverlay(0, 28, 8,
"Rendering to the Hmd - Please put on your Rift");
GetPlatformCore()->SetNotificationOverlay(1, 24, -8,
MirrorToWindow ? "'M' - Mirror to Window [On]" : "'M' - Mirror to Window [Off]");
}
ovrHmd_SetEnabledCaps(Hmd, hmdCaps);
ovrRenderAPIConfig config = pRender->Get_ovrRenderAPIConfig();
unsigned distortionCaps = ovrDistortionCap_Chromatic |
ovrDistortionCap_Vignette;
if (SupportsSrgb)
distortionCaps |= ovrDistortionCap_SRGB;
if(PixelLuminanceOverdrive)
distortionCaps |= ovrDistortionCap_Overdrive;
if (TimewarpEnabled)
distortionCaps |= ovrDistortionCap_TimeWarp;
if(TimewarpNoJitEnabled)
distortionCaps |= ovrDistortionCap_ProfileNoTimewarpSpinWaits;
if(HqAaDistortion)
distortionCaps |= ovrDistortionCap_HqDistortion;
if (!ovrHmd_ConfigureRendering( Hmd, &config, distortionCaps,
eyeFov, EyeRenderDesc ))
{
// Fail exit? TBD
return;
}
if (ForceZeroIpd)
{
// Remove IPD adjust
EyeRenderDesc[0].ViewAdjust = Vector3f(0);
EyeRenderDesc[1].ViewAdjust = Vector3f(0);
}
unsigned sensorCaps = ovrTrackingCap_Orientation|ovrTrackingCap_MagYawCorrection;
if (PositionTrackingEnabled)
sensorCaps |= ovrTrackingCap_Position;
if (StartTrackingCaps != sensorCaps)
{
ovrHmd_ConfigureTracking(Hmd, sensorCaps, 0);
StartTrackingCaps = sensorCaps;
}
// Calculate projections
Projection[0] = ovrMatrix4f_Projection(EyeRenderDesc[0].Fov, 0.01f, 10000.0f, true);
Projection[1] = ovrMatrix4f_Projection(EyeRenderDesc[1].Fov, 0.01f, 10000.0f, true);
float orthoDistance = 0.8f; // 2D is 0.8 meter from camera
Vector2f orthoScale0 = Vector2f(1.0f) / Vector2f(EyeRenderDesc[0].PixelsPerTanAngleAtCenter);
Vector2f orthoScale1 = Vector2f(1.0f) / Vector2f(EyeRenderDesc[1].PixelsPerTanAngleAtCenter);
OrthoProjection[0] = ovrMatrix4f_OrthoSubProjection(Projection[0], orthoScale0, orthoDistance,
EyeRenderDesc[0].ViewAdjust.x);
OrthoProjection[1] = ovrMatrix4f_OrthoSubProjection(Projection[1], orthoScale1, orthoDistance,
EyeRenderDesc[1].ViewAdjust.x);
// all done
HmdSettingsChanged = false;
}
// Returns the actual size present.
Sizei OculusWorldDemoApp::EnsureRendertargetAtLeastThisBig(int rtNum, Sizei requestedSize)
{
OVR_ASSERT((rtNum >= 0) && (rtNum < Rendertarget_LAST));
// Texture size that we already have might be big enough.
Sizei newRTSize;
RenderTarget& rt = RenderTargets[rtNum];
if (!rt.pTex)
{
// Hmmm... someone nuked my texture. Rez change or similar. Make sure we reallocate.
rt.Tex.Header.TextureSize = Sizei(0);
newRTSize = requestedSize;
}
else
{
newRTSize = rt.Tex.Header.TextureSize;
}
// %50 linear growth each time is a nice balance between being too greedy
// for a 2D surface and too slow to prevent fragmentation.
while ( newRTSize.w < requestedSize.w )
{
newRTSize.w += newRTSize.w/2;
}
while ( newRTSize.h < requestedSize.h )
{
newRTSize.h += newRTSize.h/2;
}
// Put some sane limits on it. 4k x 4k is fine for most modern video cards.
// Nobody should be messing around with surfaces smaller than 4k pixels these days.
newRTSize = Sizei::Max(Sizei::Min(newRTSize, Sizei(4096)), Sizei(64));
// Does that require actual reallocation?
if (Sizei(rt.Tex.Header.TextureSize) != newRTSize)
{
int format = Texture_RGBA | Texture_RenderTarget | (MultisampleEnabled ? 4 : 1);
if (SupportsSrgb)
format |= Texture_SRGB;
rt.pTex = *pRender->CreateTexture(format, newRTSize.w, newRTSize.h, NULL);
rt.pTex->SetSampleMode(Sample_ClampBorder | Sample_Linear);
// Configure texture for SDK Rendering.
rt.Tex = rt.pTex->Get_ovrTexture();
}
return newRTSize;
}
//-----------------------------------------------------------------------------
// ***** Message Handlers
void OculusWorldDemoApp::OnResize(int width, int height)
{
WindowSize = Sizei(width, height);
HmdSettingsChanged = true;
}
void OculusWorldDemoApp::OnMouseMove(int x, int y, int modifiers)
{
OVR_UNUSED(y);
if(modifiers & Mod_MouseRelative)
{
// Get Delta
int dx = x;
// Apply to rotation. Subtract for right body frame rotation,
// since yaw rotation is positive CCW when looking down on XZ plane.
ThePlayer.BodyYaw -= (Sensitivity * dx) / 360.0f;
}
}
void OculusWorldDemoApp::OnKey(OVR::KeyCode key, int chr, bool down, int modifiers)
{
if (down)
{ // Dismiss Safety warning with any key.
ovrHmd_DismissHSWDisplay(Hmd);
}
if (Menu.OnKey(key, chr, down, modifiers))
return;
// Handle player movement keys.
if (ThePlayer.HandleMoveKey(key, down))
return;
switch(key)
{
case Key_Q:
if (down && (modifiers & Mod_Control))
pPlatform->Exit(0);
break;
case Key_Escape:
// Back to primary windowed
if (!down) ChangeDisplay ( true, false, false );
break;
case Key_F9:
// Cycle through displays, going fullscreen on each one.
if (!down) ChangeDisplay ( false, true, false );
break;
#ifdef OVR_OS_MAC
// F11 is reserved on Mac, F10 doesn't work on Windows
case Key_F10:
#else
case Key_F11:
#endif
if (!down) ChangeDisplay ( false, false, true );
break;
case Key_Space:
if (!down)
{
TextScreen = (enum TextScreen)((TextScreen + 1) % Text_Count);
}
break;
// Distortion correction adjustments
case Key_Backslash:
break;
// Holding down Shift key accelerates adjustment velocity.
case Key_Shift:
ShiftDown = down;
break;
case Key_Control:
CtrlDown = down;
break;
// Reset the camera position in case we get stuck
case Key_T:
if (down)
{
struct {
float x, z;
float YawDegrees;
} Positions[] =
{
// x z Yaw
{ 7.7f, -1.0f, 180.0f }, // The starting position.
{ 10.0f, 10.0f, 90.0f }, // Outside, looking at some trees.
{ 19.26f, 5.43f, 22.0f }, // Outside, looking at the fountain.
};
static int nextPosition = 0;
nextPosition = (nextPosition + 1) % (sizeof(Positions)/sizeof(Positions[0]));
ThePlayer.BodyPos = Vector3f(Positions[nextPosition].x,
ThePlayer.UserEyeHeight, Positions[nextPosition].z);
ThePlayer.BodyYaw = DegreeToRad( Positions[nextPosition].YawDegrees );
}
break;
case Key_Num1:
ThePlayer.BodyPos = Vector3f(-1.85f, 6.0f, -0.52f);
ThePlayer.BodyPos.y += ThePlayer.UserEyeHeight;
ThePlayer.BodyYaw = 3.1415f / 2;
ThePlayer.HandleMovement(0, &CollisionModels, &GroundCollisionModels, ShiftDown);
break;
default:
break;
}
}
//-----------------------------------------------------------------------------
Matrix4f OculusWorldDemoApp::CalculateViewFromPose(const Posef& pose)
{
Posef worldPose = ThePlayer.VirtualWorldTransformfromRealPose(pose);
// Rotate and position View Camera
Vector3f up = worldPose.Rotation.Rotate(UpVector);
Vector3f forward = worldPose.Rotation.Rotate(ForwardVector);
// Transform the position of the center eye in the real world (i.e. sitting in your chair)
// into the frame of the player's virtual body.
// It is important to have head movement in scale with IPD.
// If you shrink one, you should also shrink the other.
// So with zero IPD (i.e. everything at infinity),
// head movement should also be zero.
Vector3f viewPos = ForceZeroHeadMovement ? ThePlayer.BodyPos : worldPose.Translation;
Matrix4f view = Matrix4f::LookAtRH(viewPos, viewPos + forward, up);
return view;
}
void OculusWorldDemoApp::OnIdle()
{
double curtime = ovr_GetTimeInSeconds();
// If running slower than 10fps, clamp. Helps when debugging, because then dt can be minutes!
float dt = Alg::Min<float>(float(curtime - LastUpdate), 0.1f);
LastUpdate = curtime;
Profiler.RecordSample(RenderProfiler::Sample_FrameStart);
if (LoadingState == LoadingState_DoLoad)
{
PopulateScene(MainFilePath.ToCStr());
LoadingState = LoadingState_Finished;
return;
}
if (HmdSettingsChanged)
{
CalculateHmdValues();
}
// Kill overlays in non-mirror mode after timeout.
if ((NotificationTimeout != 0.0) && (curtime > NotificationTimeout))
{
if (MirrorToWindow)
{
GetPlatformCore()->SetNotificationOverlay(0,0,0,0);
GetPlatformCore()->SetNotificationOverlay(1,0,0,0);
}
NotificationTimeout = 0.0;
}
HmdFrameTiming = ovrHmd_BeginFrame(Hmd, 0);
// Update gamepad.
GamepadState gamepadState;
if (GetPlatformCore()->GetGamepadManager()->GetGamepadState(0, &gamepadState))
{
GamepadStateChanged(gamepadState);
}
ovrTrackingState trackState = ovrHmd_GetTrackingState(Hmd, HmdFrameTiming.ScanoutMidpointSeconds);
HmdStatus = trackState.StatusFlags;
// Report vision tracking
bool hadVisionTracking = HaveVisionTracking;
HaveVisionTracking = (trackState.StatusFlags & ovrStatus_PositionTracked) != 0;
if (HaveVisionTracking && !hadVisionTracking)
Menu.SetPopupMessage("Vision Tracking Acquired");
if (!HaveVisionTracking && hadVisionTracking)
Menu.SetPopupMessage("Lost Vision Tracking");
// Report position tracker
bool hadPositionTracker = HavePositionTracker;
HavePositionTracker = (trackState.StatusFlags & ovrStatus_PositionConnected) != 0;
if (HavePositionTracker && !hadPositionTracker)
Menu.SetPopupMessage("Position Tracker Connected");
if (!HavePositionTracker && hadPositionTracker)
Menu.SetPopupMessage("Position Tracker Disconnected");
// Report position tracker
bool hadHMDConnected = HaveHMDConnected;
HaveHMDConnected = (trackState.StatusFlags & ovrStatus_HmdConnected) != 0;
if (HaveHMDConnected && !hadHMDConnected)
Menu.SetPopupMessage("HMD Connected");
if (!HaveHMDConnected && hadHMDConnected)
Menu.SetPopupMessage("HMD Disconnected");
UpdateVisionProcessingTime(trackState);
// Check if any new devices were connected.
ProcessDeviceNotificationQueue();
// FPS count and timing.
UpdateFrameRateCounter(curtime);
// Update pose based on frame!
ThePlayer.HeadPose = trackState.HeadPose.ThePose;
// Movement/rotation with the gamepad.
ThePlayer.BodyYaw -= ThePlayer.GamepadRotate.x * dt;
ThePlayer.HandleMovement(dt, &CollisionModels, &GroundCollisionModels, ShiftDown);
// Record after processing time.
Profiler.RecordSample(RenderProfiler::Sample_AfterGameProcessing);
// Determine if we are rendering this frame. Frame rendering may be
// skipped based on FreezeEyeUpdate and Time-warp timing state.
bool bupdateRenderedView = FrameNeedsRendering(curtime);
if (bupdateRenderedView)
{
// If render texture size is changing, apply dynamic changes to viewport.
ApplyDynamicResolutionScaling();
pRender->BeginScene(PostProcess_None);
if (ForceZeroIpd)
{
// Zero IPD eye rendering: draw into left eye only,
// re-use texture for right eye.
pRender->SetRenderTarget(RenderTargets[Rendertarget_Left].pTex);
pRender->Clear();
EyeRenderPose[0] =
EyeRenderPose[1] = ovrHmd_GetEyePose(Hmd, ovrEye_Left);
View = CalculateViewFromPose(EyeRenderPose[0]);
RenderEyeView(ovrEye_Left);
// Note: Second eye gets texture is (initialized to same value above).
}
else if (RendertargetIsSharedByBothEyes)
{
// Shared render target eye rendering; set up RT once for both eyes.
pRender->SetRenderTarget(RenderTargets[Rendertarget_BothEyes].pTex);
pRender->Clear();
for (int eyeIndex = 0; eyeIndex < ovrEye_Count; eyeIndex++)
{
ovrEyeType eye = Hmd->EyeRenderOrder[eyeIndex];
EyeRenderPose[eye] = ovrHmd_GetEyePose(Hmd, eye);
View = CalculateViewFromPose(EyeRenderPose[eye]);
RenderEyeView(eye);
}
}
else
{
// Separate eye rendering - each eye gets its own render target.
for (int eyeIndex = 0; eyeIndex < ovrEye_Count; eyeIndex++)
{
ovrEyeType eye = Hmd->EyeRenderOrder[eyeIndex];
pRender->SetRenderTarget(
RenderTargets[(eye == 0) ? Rendertarget_Left : Rendertarget_Right].pTex);
pRender->Clear();
EyeRenderPose[eye] = ovrHmd_GetEyePose(Hmd, eye);
View = CalculateViewFromPose(EyeRenderPose[eye]);
RenderEyeView(eye);
}
}
pRender->SetDefaultRenderTarget();
pRender->FinishScene();
}
/*
double t= ovr_GetTimeInSeconds();
while (ovr_GetTimeInSeconds() < (t + 0.017))
{
} */
Profiler.RecordSample(RenderProfiler::Sample_AfterEyeRender);
// TODO: These happen inside ovrHmd_EndFrame; need to hook into it.
//Profiler.RecordSample(RenderProfiler::Sample_BeforeDistortion);
ovrHmd_EndFrame(Hmd, EyeRenderPose, EyeTexture);
Profiler.RecordSample(RenderProfiler::Sample_AfterPresent);
}
// Determine whether this frame needs rendering based on time-warp timing and flags.
bool OculusWorldDemoApp::FrameNeedsRendering(double curtime)
{
static double lastUpdate = 0.0;
double renderInterval = TimewarpRenderIntervalInSeconds;
double timeSinceLast = curtime - lastUpdate;
bool updateRenderedView = true;
if (TimewarpEnabled)
{
if (FreezeEyeUpdate)
{
// Draw one frame after (FreezeEyeUpdate = true) to update message text.
if (FreezeEyeOneFrameRendered)
updateRenderedView = false;
else
FreezeEyeOneFrameRendered = true;
}
else
{
FreezeEyeOneFrameRendered = false;
if ( (timeSinceLast < 0.0) || ((float)timeSinceLast > renderInterval) )
{
// This allows us to do "fractional" speeds, e.g. 45fps rendering on a 60fps display.
lastUpdate += renderInterval;
if ( timeSinceLast > 5.0 )
{
// renderInterval is probably tiny (i.e. "as fast as possible")
lastUpdate = curtime;
}
updateRenderedView = true;
}
else
{
updateRenderedView = false;
}
}
}
return updateRenderedView;
}
void OculusWorldDemoApp::ApplyDynamicResolutionScaling()
{
if (!DynamicRezScalingEnabled)
{
// Restore viewport rectangle in case dynamic res scaling was enabled before.
EyeTexture[0].Header.RenderViewport.Size = EyeRenderSize[0];
EyeTexture[1].Header.RenderViewport.Size = EyeRenderSize[1];
return;
}
// Demonstrate dynamic-resolution rendering.
// This demo is too simple to actually have a framerate that varies that much, so we'll
// just pretend this is trying to cope with highly dynamic rendering load.
float dynamicRezScale = 1.0f;
{
// Hacky stuff to make up a scaling...
// This produces value oscillating as follows: 0 -> 1 -> 0.
static double dynamicRezStartTime = ovr_GetTimeInSeconds();
float dynamicRezPhase = float ( ovr_GetTimeInSeconds() - dynamicRezStartTime );
const float dynamicRezTimeScale = 4.0f;
dynamicRezPhase /= dynamicRezTimeScale;
if ( dynamicRezPhase < 1.0f )
{
dynamicRezScale = dynamicRezPhase;
}
else if ( dynamicRezPhase < 2.0f )
{
dynamicRezScale = 2.0f - dynamicRezPhase;
}
else
{
// Reset it to prevent creep.
dynamicRezStartTime = ovr_GetTimeInSeconds();
dynamicRezScale = 0.0f;
}
// Map oscillation: 0.5 -> 1.0 -> 0.5
dynamicRezScale = dynamicRezScale * 0.5f + 0.5f;
}
Sizei sizeLeft = EyeRenderSize[0];
Sizei sizeRight = EyeRenderSize[1];
// This viewport is used for rendering and passed into ovrHmd_EndEyeRender.
EyeTexture[0].Header.RenderViewport.Size = Sizei(int(sizeLeft.w * dynamicRezScale),
int(sizeLeft.h * dynamicRezScale));
EyeTexture[1].Header.RenderViewport.Size = Sizei(int(sizeRight.w * dynamicRezScale),
int(sizeRight.h * dynamicRezScale));
}
void OculusWorldDemoApp::UpdateFrameRateCounter(double curtime)
{
FrameCounter++;
TotalFrameCounter++;
float secondsSinceLastMeasurement = (float)( curtime - LastFpsUpdate );
if (secondsSinceLastMeasurement >= SecondsOfFpsMeasurement)
{
SecondsPerFrame = (float)( curtime - LastFpsUpdate ) / (float)FrameCounter;
FPS = 1.0f / SecondsPerFrame;
LastFpsUpdate = curtime;
FrameCounter = 0;
}
}
void OculusWorldDemoApp::UpdateVisionProcessingTime(const ovrTrackingState& trackState)
{
// Update LastVisionProcessingTime
if (trackState.LastVisionProcessingTime != LastVisionProcessingTime)
{
LastVisionProcessingTime = trackState.LastVisionProcessingTime;
VisionProcessingSum += LastVisionProcessingTime;
if (VisionTimesCount >= 20)
{
VisionProcessingAverage = VisionProcessingSum / 20.;
VisionProcessingSum = 0.;
VisionTimesCount = 0;
}
else
{
VisionTimesCount++;
}
}
}
void OculusWorldDemoApp::RenderEyeView(ovrEyeType eye)
{
Recti renderViewport = EyeTexture[eye].Header.RenderViewport;
Matrix4f viewAdjust = Matrix4f::Translation(Vector3f(EyeRenderDesc[eye].ViewAdjust));
// *** 3D - Configures Viewport/Projection and Render
pRender->ApplyStereoParams(renderViewport, Projection[eye]);
pRender->SetDepthMode(true, true);
Matrix4f baseTranslate = Matrix4f::Translation(ThePlayer.BodyPos);
Matrix4f baseYaw = Matrix4f::RotationY(ThePlayer.BodyYaw.Get());
if (GridDisplayMode != GridDisplay_GridOnly)
{
if (SceneMode != Scene_OculusCubes)
{
MainScene.Render(pRender, viewAdjust * View);
RenderAnimatedBlocks(eye, ovr_GetTimeInSeconds());
}
if (SceneMode == Scene_Cubes)
{
// Draw scene cubes overlay. Red if position tracked, blue otherwise.
Scene sceneCubes = (HmdStatus & ovrStatus_PositionTracked) ?
RedCubesScene : BlueCubesScene;
sceneCubes.Render(pRender, viewAdjust * View * baseTranslate * baseYaw);
}
else if (SceneMode == Scene_OculusCubes)
{
OculusCubesScene.Render(pRender, viewAdjust * View * baseTranslate * baseYaw);
}
}
if (GridDisplayMode != GridDisplay_None)
{
RenderGrid(eye);
}
// *** 2D Text - Configure Orthographic rendering.
// Render UI in 2D orthographic coordinate system that maps [-1,1] range
// to a readable FOV area centered at your eye and properly adjusted.
pRender->ApplyStereoParams(renderViewport, OrthoProjection[eye]);
pRender->SetDepthMode(false, false);
// We set this scale up in CreateOrthoSubProjection().
float textHeight = 22.0f;
// Display Loading screen-shot in frame 0.
if (LoadingState != LoadingState_Finished)
{
const float scale = textHeight * 25.0f;
Matrix4f view ( scale, 0.0f, 0.0f, 0.0f, scale, 0.0f, 0.0f, 0.0f, scale );
LoadingScene.Render(pRender, view);
String loadMessage = String("Loading ") + MainFilePath;
DrawTextBox(pRender, 0.0f, -textHeight, textHeight, loadMessage.ToCStr(), DrawText_HCenter);
LoadingState = LoadingState_DoLoad;
}
// HUD overlay brought up by spacebar.
RenderTextInfoHud(textHeight);
// Menu brought up by
Menu.Render(pRender);
}
// NOTE - try to keep these in sync with the PDF docs!
static const char* HelpText1 =
"Spacebar \t500 Toggle debug info overlay\n"
"W, S \t500 Move forward, back\n"
"A, D \t500 Strafe left, right\n"
"Mouse move \t500 Look left, right\n"
"Left gamepad stick \t500 Move\n"
"Right gamepad stick \t500 Turn\n"
"T \t500 Reset player position";
static const char* HelpText2 =
"R \t250 Reset sensor orientation\n"
"G \t250 Cycle grid overlay mode\n"
"-, + \t250 Adjust eye height\n"
"Esc \t250 Cancel full-screen\n"
"F4 \t250 Multisampling toggle\n"
"F9 \t250 Hardware full-screen (low latency)\n"
"F11 \t250 Faked full-screen (easier debugging)\n"
"Ctrl+Q \t250 Quit";
void FormatLatencyReading(char* buff, size_t size, float val)
{
if (val < 0.000001f)
OVR_strcpy(buff, size, "N/A ");
else
OVR_sprintf(buff, size, "%4.2fms", val * 1000.0f);
}
void OculusWorldDemoApp::RenderTextInfoHud(float textHeight)
{
// View port & 2D ortho projection must be set before call.
float hmdYaw, hmdPitch, hmdRoll;
switch(TextScreen)
{
case Text_Info:
{
char buf[512];
// Average FOVs.
FovPort leftFov = EyeRenderDesc[0].Fov;
FovPort rightFov = EyeRenderDesc[1].Fov;
// Rendered size changes based on selected options & dynamic rendering.
int pixelSizeWidth = EyeTexture[0].Header.RenderViewport.Size.w +
((!ForceZeroIpd) ?
EyeTexture[1].Header.RenderViewport.Size.w : 0);
int pixelSizeHeight = ( EyeTexture[0].Header.RenderViewport.Size.h +
EyeTexture[1].Header.RenderViewport.Size.h ) / 2;
// No DK2, no message.
char latency2Text[128] = "";
{
//float latency2 = ovrHmd_GetMeasuredLatencyTest2(Hmd) * 1000.0f; // show it in ms
//if (latency2 > 0)
// OVR_sprintf(latency2Text, sizeof(latency2Text), "%.2fms", latency2);
float latencies[3] = { 0.0f, 0.0f, 0.0f };
if (ovrHmd_GetFloatArray(Hmd, "DK2Latency", latencies, 3) == 3)
{
char latencyText0[32], latencyText1[32], latencyText2[32];
FormatLatencyReading(latencyText0, sizeof(latencyText0), latencies[0]);
FormatLatencyReading(latencyText1, sizeof(latencyText1), latencies[1]);
FormatLatencyReading(latencyText2, sizeof(latencyText2), latencies[2]);
OVR_sprintf(latency2Text, sizeof(latency2Text),
" DK2 Latency Ren: %s TWrp: %s\n"
" PostPresent: %s VisionProc: %1.2f ms ",
latencyText0, latencyText1, latencyText2,
(float)VisionProcessingAverage * 1000);
}
}
ThePlayer.HeadPose.Rotation.GetEulerAngles<Axis_Y, Axis_X, Axis_Z>(&hmdYaw, &hmdPitch, &hmdRoll);
OVR_sprintf(buf, sizeof(buf),
" HMD YPR:%4.0f %4.0f %4.0f Player Yaw: %4.0f\n"
" FPS: %.1f ms/frame: %.1f Frame: %03d %d\n"
" Pos: %3.2f, %3.2f, %3.2f HMD: %s\n"
" EyeHeight: %3.2f, IPD: %3.1fmm\n" //", Lens: %s\n"
" FOV %3.1fx%3.1f, Resolution: %ix%i\n"
"%s",
RadToDegree(hmdYaw), RadToDegree(hmdPitch), RadToDegree(hmdRoll),
RadToDegree(ThePlayer.BodyYaw.Get()),
FPS, SecondsPerFrame * 1000.0f, FrameCounter, TotalFrameCounter % 2,
ThePlayer.BodyPos.x, ThePlayer.BodyPos.y, ThePlayer.BodyPos.z,
//GetDebugNameHmdType ( TheHmdRenderInfo.HmdType ),
Hmd->ProductName,
ThePlayer.UserEyeHeight,
ovrHmd_GetFloat(Hmd, OVR_KEY_IPD, 0) * 1000.0f,
//( EyeOffsetFromNoseLeft + EyeOffsetFromNoseRight ) * 1000.0f,
//GetDebugNameEyeCupType ( TheHmdRenderInfo.EyeCups ), // Lens/EyeCup not exposed
(leftFov.GetHorizontalFovDegrees() + rightFov.GetHorizontalFovDegrees()) * 0.5f,
(leftFov.GetVerticalFovDegrees() + rightFov.GetVerticalFovDegrees()) * 0.5f,
pixelSizeWidth, pixelSizeHeight,
latency2Text
);
#if 0 // Enable if interested in texture memory usage stats
size_t texMemInMB = pRender->GetTotalTextureMemoryUsage() / (1024 * 1024); // 1 MB
if (texMemInMB)
{
char gpustat[256];
OVR_sprintf(gpustat, sizeof(gpustat), "\nGPU Tex: %u MB", texMemInMB);
OVR_strcat(buf, sizeof(buf), gpustat);
}
#endif
DrawTextBox(pRender, 0.0f, 0.0f, textHeight, buf, DrawText_Center);
}
break;
case Text_Timing:
Profiler.DrawOverlay(pRender);
break;
case Text_Help1:
DrawTextBox(pRender, 0.0f, 0.0f, textHeight, HelpText1, DrawText_Center);
break;
case Text_Help2:
DrawTextBox(pRender, 0.0f, 0.0f, textHeight, HelpText2, DrawText_Center);
break;
case Text_None:
break;
default:
OVR_ASSERT ( !"Missing text screen" );
break;
}
}
//-----------------------------------------------------------------------------
// ***** Callbacks For Menu changes
// Non-trivial callback go here.
void OculusWorldDemoApp::HmdSensorToggle(OptionVar* var)
{
if (*var->AsBool())
{
EnableSensor = true;
if (!ovrHmd_ConfigureTracking(Hmd, StartTrackingCaps, 0))
{
OVR_ASSERT(false);
}
}
else
{
EnableSensor = false;
ovrHmd_ConfigureTracking(Hmd, 0, 0);
}
}
void OculusWorldDemoApp::HmdSettingChangeFreeRTs(OptionVar*)
{
HmdSettingsChanged = true;
// Cause the RTs to be recreated with the new mode.
for ( int rtNum = 0; rtNum < Rendertarget_LAST; rtNum++ )
RenderTargets[rtNum].pTex = NULL;
}
void OculusWorldDemoApp::MultisampleChange(OptionVar*)
{
HmdSettingChangeFreeRTs();
}
void OculusWorldDemoApp::CenterPupilDepthChange(OptionVar*)
{
ovrHmd_SetFloat(Hmd, "CenterPupilDepth", CenterPupilDepthMeters);
}
void OculusWorldDemoApp::DistortionClearColorChange(OptionVar*)
{
float clearColor[2][4] = { { 0.0f, 0.0f, 0.0f, 0.0f },
{ 0.0f, 0.5f, 1.0f, 0.0f } };
ovrHmd_SetFloatArray(Hmd, "DistortionClearColor",
clearColor[(int)DistortionClearBlue], 4);
}
void OculusWorldDemoApp::ResetHmdPose(OptionVar* /* = 0 */)
{
ovrHmd_RecenterPose(Hmd);
Menu.SetPopupMessage("Sensor Fusion Recenter Pose");
}
//-----------------------------------------------------------------------------
void OculusWorldDemoApp::ProcessDeviceNotificationQueue()
{
// TBD: Process device plug & Unplug
}
//-----------------------------------------------------------------------------
void OculusWorldDemoApp::ChangeDisplay ( bool bBackToWindowed, bool bNextFullscreen,
bool bFullWindowDebugging )
{
// Display mode switching doesn't make sense in App driver mode.
if (!(Hmd->HmdCaps & ovrHmdCap_ExtendDesktop))
return;
// Exactly one should be set...
OVR_ASSERT ( ( bBackToWindowed ? 1 : 0 ) + ( bNextFullscreen ? 1 : 0 ) +
( bFullWindowDebugging ? 1 : 0 ) == 1 );
OVR_UNUSED ( bNextFullscreen );
if ( bFullWindowDebugging )
{
// Slightly hacky. Doesn't actually go fullscreen, just makes a screen-sized wndow.
// This has higher latency than fullscreen, and is not intended for actual use,
// but makes for much nicer debugging on some systems.
RenderParams = pRender->GetParams();
RenderParams.Display = DisplayId(Hmd->DisplayDeviceName, Hmd->DisplayId);
pRender->SetParams(RenderParams);
pPlatform->SetMouseMode(Mouse_Normal);
pPlatform->SetFullscreen(RenderParams, pRender->IsFullscreen() ? Display_Window : Display_FakeFullscreen);
pPlatform->SetMouseMode(Mouse_Relative); // Avoid mode world rotation jump.
// If using an HMD, enable post-process (for distortion) and stereo.
if (RenderParams.IsDisplaySet() && pRender->IsFullscreen())
{
//SetPostProcessingMode ( PostProcess );
}
}
else
{
int screenCount = pPlatform->GetDisplayCount();
int screenNumberToSwitchTo;
if ( bBackToWindowed )
{
screenNumberToSwitchTo = -1;
}
else
{
if (!pRender->IsFullscreen())
{
// Currently windowed.
// Try to find HMD Screen, making it the first screen in the full-screen cycle.
FirstScreenInCycle = 0;
if (!UsingDebugHmd)
{
DisplayId HMD (Hmd->DisplayDeviceName, Hmd->DisplayId);
for (int i = 0; i< screenCount; i++)
{
if (pPlatform->GetDisplay(i) == HMD)
{
FirstScreenInCycle = i;
break;
}
}
}
ScreenNumber = FirstScreenInCycle;
screenNumberToSwitchTo = ScreenNumber;
}
else
{
// Currently fullscreen, so cycle to the next screen.
ScreenNumber++;
if (ScreenNumber == screenCount)
{
ScreenNumber = 0;
}
screenNumberToSwitchTo = ScreenNumber;
if (ScreenNumber == FirstScreenInCycle)
{
// We have cycled through all the fullscreen displays, so go back to windowed mode.
screenNumberToSwitchTo = -1;
}
}
}
// Always restore windowed mode before going to next screen, even if we were already fullscreen.
pPlatform->SetFullscreen(RenderParams, Display_Window);
if ( screenNumberToSwitchTo >= 0 )
{
// Go fullscreen.
RenderParams.Display = pPlatform->GetDisplay(screenNumberToSwitchTo);
pRender->SetParams(RenderParams);
pPlatform->SetFullscreen(RenderParams, Display_Fullscreen);
}
}
// Updates render target pointers & sizes.
HmdSettingChangeFreeRTs();
}
void OculusWorldDemoApp::GamepadStateChanged(const GamepadState& pad)
{
if (pad.Buttons != 0)
{ // Dismiss Safety warning with any key.
ovrHmd_DismissHSWDisplay(Hmd);
}
ThePlayer.GamepadMove = Vector3f(pad.LX * pad.LX * (pad.LX > 0 ? 1 : -1),
0,
pad.LY * pad.LY * (pad.LY > 0 ? -1 : 1));
ThePlayer.GamepadRotate = Vector3f(2 * pad.RX, -2 * pad.RY, 0);
uint32_t gamepadDeltas = (pad.Buttons ^ LastGamepadState.Buttons) & pad.Buttons;
if (gamepadDeltas)
{
Menu.OnGamepad(gamepadDeltas);
}
LastGamepadState = pad;
}
//-------------------------------------------------------------------------------------
OVR_PLATFORM_APP(OculusWorldDemoApp);
|