-
Notifications
You must be signed in to change notification settings - Fork 23
/
FPSciApp.cpp
1768 lines (1556 loc) · 65.6 KB
/
FPSciApp.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
/** \file FPSciApp.cpp */
#include "FPSciApp.h"
#include "Dialogs.h"
#include "Logger.h"
#include "Session.h"
#include "PhysicsScene.h"
#include "WaypointManager.h"
#include <chrono>
// Storage for configuration static vars
int TrialConfig::defaultCount;
Array<String> UserSessionStatus::defaultSessionOrder;
bool UserSessionStatus::randomizeDefaults;
StartupConfig FPSciApp::startupConfig;
FPSciApp::FPSciApp(const GApp::Settings& settings) : GApp(settings) {}
/** Initialize the app */
void FPSciApp::onInit() {
// Seed random based on the time
Random::common().reset(uint32(time(0)));
GApp::onInit(); // Initialize the G3D application (one time)
// TODO: Move validateExperiments() to a developer mode GUI button
//startupConfig.validateExperiments();
initExperiment(); // Initialize the experiment
}
void FPSciApp::initExperiment(){
// Load config from files
loadConfigs(startupConfig.experimentList[experimentIdx]);
m_lastSavedUser = *currentUser(); // Copy over the startup user for saves
// Setup the display mode
setSubmitToDisplayMode(
//SubmitToDisplayMode::EXPLICIT);
SubmitToDisplayMode::MINIMIZE_LATENCY);
//SubmitToDisplayMode::BALANCE);
//SubmitToDisplayMode::MAXIMIZE_THROUGHPUT);
// Set the initial simulation timestep to REAL_TIME. The desired timestep is set later.
setFrameDuration(frameDuration(), REAL_TIME);
m_lastOnSimulationRealTime = 0.0;
// Setup/update waypoint manager
if (startupConfig.developerMode && startupConfig.waypointEditorMode) {
waypointManager = WaypointManager::create(this);
}
// Setup the scene
m_loadedScene.name = ""; // Clear scene name here
setScene(PhysicsScene::create(m_ambientOcclusion));
scene()->registerEntitySubclass("PlayerEntity", &PlayerEntity::create); // Register the player entity for creation
scene()->registerEntitySubclass("FlyingEntity", &FlyingEntity::create); // Register the target entity for creation
weapon = Weapon::create(&experimentConfig.weapon, scene(), activeCamera());
weapon->setHitCallback(std::bind(&FPSciApp::hitTarget, this, std::placeholders::_1));
weapon->setMissCallback(std::bind(&FPSciApp::missEvent, this));
// Load models and set the reticle
loadModels();
setReticle(reticleConfig.index);
// Load fonts and images
outputFont = GFont::fromFile(System::findDataFile("arial.fnt"));
hudTextures.set("scoreBannerBackdrop", Texture::fromFile(System::findDataFile("gui/scoreBannerBackdrop.png")));
// Setup the GUI
showRenderingStats = false;
makeGUI();
updateMouseSensitivity(); // Update (apply) mouse sensitivity
const Array<String> sessions = m_userSettingsWindow->updateSessionDropDown(); // Update the session drop down to remove already completed sessions
updateSession(sessions[0], true); // Update session to create results file/start collection
}
void FPSciApp::toggleUserSettingsMenu() {
if (!m_userSettingsWindow->visible()) {
openUserSettingsWindow();
}
else {
closeUserSettingsWindow();
}
// Make sure any change to sensitivity are applied
updateMouseSensitivity();
}
/** Handle the user settings window visibility */
void FPSciApp::openUserSettingsWindow() {
// set focus so buttons properly highlight
moveToCenter(m_userSettingsWindow);
m_userSettingsWindow->setVisible(true);
if (!dialog) { // Don't allow the user menu to hide the mouse when a dialog box is open
setMouseInputMode(MouseInputMode::MOUSE_CURSOR); // Set mouse mode to cursor to allow pointer-based interaction
}
m_widgetManager->setFocusedWidget(m_userSettingsWindow);
}
/** Handle the user settings window visibility */
void FPSciApp::closeUserSettingsWindow() {
// Don't allow window close until a user has been added
if (trialConfig->menu.requireUserAdd && !userAdded) {
return;
}
// If the user could have saved their settings, save on close
if (trialConfig->menu.allowUserSettingsSave) {
saveUserConfig(true);
}
// Don't allow the user menu to hide the mouse when a dialog box is open
if (!dialog) {
// Set mouse mode to FPM to allow steering the view again
setMouseInputMode(MouseInputMode::MOUSE_FPM);
}
m_userSettingsWindow->setVisible(false);
}
void FPSciApp::saveUserConfig(bool onDiff) {
// Check for save on diff, without mismatch
if (onDiff && m_lastSavedUser == *currentUser()) {
return;
}
if (notNull(sess->logger)) {
sess->logger->logUserConfig(*currentUser(), sessConfig->id, sessConfig->player.turnScale);
}
userTable.save(startupConfig.experimentList[experimentIdx].userConfigFilename, startupConfig.jsonAnyOutput);
m_lastSavedUser = *currentUser(); // Copy over this user
logPrintf("User table saved.\n"); // Print message to log
}
void FPSciApp::saveUserStatus(void) {
userStatusTable.save(startupConfig.experimentList[experimentIdx].userStatusFilename, startupConfig.jsonAnyOutput);
logPrintf("User status saved.\n");
}
/** Update the mouse mode/sensitivity */
void FPSciApp::updateMouseSensitivity() {
const shared_ptr<UserConfig> user = currentUser();
// Converting from mouseDPI (dots/in) and sensitivity (cm/turn) into rad/dot which explains cm->in (2.54) and turn->rad (2*PI) factors
// rad/dot = rad/cm * cm/dot = 2PI / (cm/turn) * 2.54 / (dots/in) = (2.54 * 2PI)/ (DPI * cm/360)
const double cmp360 = 36.0 / user->mouseDegPerMm;
const double radiansPerDot = 2.0 * pi() * 2.54 / (cmp360 * user->mouseDPI);
// Control player motion using the experiment config parameter
shared_ptr<PlayerEntity> player = scene()->typedEntity<PlayerEntity>("player");
if (notNull(player)) {
player->m_cameraRadiansPerMouseDot = (float)radiansPerDot;
player->turnScale = currentTurnScale();
}
m_userSettingsWindow->updateCmp360();
}
void FPSciApp::setMouseInputMode(MouseInputMode mode) {
const shared_ptr<FirstPersonManipulator>& fpm = dynamic_pointer_cast<FirstPersonManipulator>(cameraManipulator());
switch (mode) {
case MouseInputMode::MOUSE_CURSOR:
fpm->setMouseMode(FirstPersonManipulator::MOUSE_DIRECT_RIGHT_BUTTON); // Display cursor in right button mode (only holding right mouse rotates view)
break;
case MouseInputMode::MOUSE_DISABLED: // Disabled case uses direct mode, but ignores view changes
case MouseInputMode::MOUSE_FPM: // FPM is "direct mode" wherein view is steered by mouse
fpm->setMouseMode(FirstPersonManipulator::MOUSE_DIRECT);
break;
}
m_mouseInputMode = mode;
}
void FPSciApp::loadConfigs(const ConfigFiles& configs) {
// Load experiment setting from file
experimentConfig = ExperimentConfig::load(configs.experimentConfigFilename, startupConfig.jsonAnyOutput);
experimentConfig.printToLog();
experimentConfig.validate(true);
// Get hash for experimentconfig.Any file
const size_t hash = HashTrait<String>::hashCode(experimentConfig.toAny().unparse()); // Hash the serialized Any (don't consider formatting)
m_expConfigHash = format("%x", hash); // Store the hash as a hex string
logPrintf("Experiment hash: %s\r\n", m_expConfigHash); // Write to log
Array<String> sessionIds;
experimentConfig.getSessionIds(sessionIds);
// Load per user settings from file
userTable = UserTable::load(configs.userConfigFilename, startupConfig.jsonAnyOutput);
userTable.printToLog();
// Load per experiment user settings from file and make sure they are valid
userStatusTable = UserStatusTable::load(configs.userStatusFilename, startupConfig.jsonAnyOutput);
userStatusTable.printToLog();
userStatusTable.validate(sessionIds, userTable.getIds());
// Get info about the system
SystemInfo info = SystemInfo::get();
info.printToLog(); // Print system info to log.txt
// Get system configuration
systemConfig = SystemConfig::load(configs.systemConfigFilename, startupConfig.jsonAnyOutput);
systemConfig.printToLog(); // Print the latency logger config to log.txt
// Load the key binds
keyMap = KeyMapping::load(configs.keymapConfigFilename, startupConfig.jsonAnyOutput);
userInput->setKeyMapping(&keyMap.uiMap);
}
void FPSciApp::loadModels() {
if ((experimentConfig.weapon.renderModel || startupConfig.developerMode) && !experimentConfig.weapon.modelSpec.filename.empty()) {
// Load the model if we (might) need it
weapon->loadModels();
}
// Add all the unqiue targets to this list
Table<String, Any> targetsToBuild;
Table<String, String> explosionsToBuild;
Table<String, float> explosionScales;
for (TargetConfig target : experimentConfig.targets) {
targetsToBuild.set(target.id, target.modelSpec);
explosionsToBuild.set(target.id, target.destroyDecal);
explosionScales.set(target.id, target.destroyDecalScale);
}
// Append reference target model(s)
Any& defaultRefTarget = experimentConfig.targetView.refTargetModelSpec;
for (SessionConfig& sess : experimentConfig.sessions) {
if (sess.targetView.refTargetModelSpec != defaultRefTarget) {
// This is a custom reference target model
String id = sess.id + "_reference";
targetsToBuild.set(id, sess.targetView.refTargetModelSpec);
explosionsToBuild.set(id, "explosion_01.png");
explosionScales.set(id, 1.0);
}
}
// Add default reference
targetsToBuild.set("reference", defaultRefTarget);
explosionsToBuild.set("reference", "explosion_01.png");
explosionScales.set("reference", 1.0);
// Scale the models into the m_targetModel table
for (String id : targetsToBuild.getKeys()) {
// Get the any specs
Any tSpec = targetsToBuild.get(id);
Any explosionSpec = Any::parse(format(
"ArticulatedModel::Specification {\
filename = \"ifs/square.ifs\";\
preprocess = {\
transformGeometry(all(), Matrix4::scale(0.1, 0.1, 0.1));\
setMaterial(all(), UniversalMaterial::Specification{\
lambertian = Texture::Specification {\
filename = \"%s\";\
encoding = Color3(1, 1, 1);\
};\
});\
};\
}", explosionsToBuild.get(id).c_str()));
// Get the bounding box to scale to size rather than arbitrary factor
shared_ptr<ArticulatedModel> size_model = ArticulatedModel::create(ArticulatedModel::Specification(tSpec));
AABox bbox;
size_model->getBoundingBox(bbox);
Vector3 extent = bbox.extent();
logPrintf("%20s bounding box: [%2.2f, %2.2f, %2.2f]\n", id.c_str(), extent[0], extent[1], extent[2]);
const float default_scale = 1.0f / extent[0]; // Setup scale so that default model is 1m across
// Create the target/explosion models for this target
Array<shared_ptr<ArticulatedModel>> tModels, expModels;
for (int i = 0; i <= TARGET_MODEL_SCALE_COUNT; ++i) {
const float scale = pow(1.0f + TARGET_MODEL_ARRAY_SCALING, float(i) - TARGET_MODEL_ARRAY_OFFSET);
tSpec.set("scale", scale * default_scale);
explosionSpec.set("scale", (20.0 * scale * explosionScales.get(id)));
tModels.push(ArticulatedModel::create(tSpec));
expModels.push(ArticulatedModel::create(explosionSpec));
}
targetModels.set(id, tModels);
m_explosionModels.set(id, expModels);
// Create a series of colored materials to choose from for target health
shared_ptr<TargetConfig> tconfig = experimentConfig.getTargetConfigById(id);
materials.remove(id);
materials.set(id, makeMaterials(tconfig));
}
}
Array<shared_ptr<UniversalMaterial>> FPSciApp::makeMaterials(shared_ptr<TargetConfig> tconfig) {
Array<shared_ptr<UniversalMaterial>> targetMaterials;
for (int i = 0; i < matTableSize; i++) {
float complete = (float)i / (matTableSize-1);
Color4 color;
if (notNull(tconfig) && tconfig->colors.length() > 0) {
color = lerpColor(tconfig->colors, complete);
}
else {
color = lerpColor(trialConfig->targetView.healthColors, complete);
}
Color4 gloss;
if (notNull(tconfig) && tconfig->hasGloss) {
gloss = tconfig->gloss;
}
else {
gloss = trialConfig->targetView.gloss;
}
Color4 emissive;
if (notNull(tconfig) && tconfig->emissive.length() > 0) {
emissive = lerpColor(tconfig->emissive, complete);
}
else if(trialConfig->targetView.emissive.length() > 0) {
emissive = lerpColor(trialConfig->targetView.emissive, complete);
}
else {
emissive = color * 0.7f; // Historical behavior fallback for unspecified case
}
UniversalMaterial::Specification materialSpecification;
materialSpecification.setLambertian(Texture::Specification(color));
materialSpecification.setEmissive(Texture::Specification(emissive));
materialSpecification.setGlossy(Texture::Specification(gloss)); // Used to be Color4(0.4f, 0.2f, 0.1f, 0.8f)
targetMaterials.append(UniversalMaterial::create(materialSpecification));
}
return targetMaterials;
}
Color4 FPSciApp::lerpColor(Array<Color4> colors, float a) {
if (colors.length() == 0) {
throw "Cannot interpolate from colors array with length 0!";
}
else if (colors.length() == 1 || a >= 1.0f) {
// a >= 1.0f indicates we should use the first color in the array
// since above 1.0 would imply negative a negative array index
return colors[0];
}
else if (a <= 0.0f) {
// Use only the last color in the array
return colors[colors.length() - 1];
}
else
{
// For 2 or more colors, linearly interpolate between the N colors.
// a comes in the range [0, 1] where
// 0 means to use the last value in colors
// and 1 means to use the first value in colors
// This means that a = 0 maps to colors[colors.length() - 1]
// and a = 1 maps to colors[0]
// We need to flip the direction and scale up to the number of elements in the array
// a will indicate which two entries to interpolate between (left of .), and how much of each to use (right of .)
float interp = (1.0f - a) * (colors.length() - 1);
int idx = int(floor(interp));
interp = interp - float(idx);
Color4 output = colors[idx] * (1.0f - interp) + colors[idx + 1] * interp;
return output;
}
}
void FPSciApp::updateDeveloperControls(const shared_ptr<FpsConfig>& config) {
// Update the waypoint manager
if (notNull(waypointManager)) { waypointManager->updateControls(); }
// Update the player controls
bool visible = false;
Rect2D rect;
if (notNull(m_playerControls)) {
visible = m_playerControls->visible();
rect = m_playerControls->rect();
removeWidget(m_playerControls);
}
m_playerControls = PlayerControls::create(*config, std::bind(&FPSciApp::exportScene, this), theme);
m_playerControls->setVisible(visible);
if (!rect.isEmpty()) m_playerControls->setRect(rect);
addWidget(m_playerControls);
// Update the render controls
visible = false;
rect = Rect2D();
if (notNull(m_renderControls)) {
visible = m_renderControls->visible();
rect = m_renderControls->rect();
removeWidget(m_renderControls);
}
m_renderControls = RenderControls::create(this, *config, renderFPS, numReticles, sceneBrightness, theme, MAX_HISTORY_TIMING_FRAMES);
m_renderControls->setVisible(visible);
if (!rect.isEmpty()) m_renderControls->setRect(rect);
addWidget(m_renderControls);
// Update the weapon controls
visible = false;
rect = Rect2D();
if (notNull(m_weaponControls)) {
visible = m_weaponControls->visible();
rect = m_weaponControls->rect();
removeWidget(m_weaponControls);
}
m_weaponControls = WeaponControls::create(config->weapon, theme);
m_weaponControls->setVisible(visible);
if (!rect.isEmpty()) m_weaponControls->setRect(rect);
addWidget(m_weaponControls);
}
void FPSciApp::makeGUI() {
theme = GuiTheme::fromFile(System::findDataFile("osx-10.7.gtm"));
debugWindow->setVisible(startupConfig.developerMode);
if (startupConfig.developerMode) {
developerWindow->cameraControlWindow->setVisible(startupConfig.developerMode);
developerWindow->videoRecordDialog->setEnabled(true);
developerWindow->videoRecordDialog->setCaptureGui(true);
// Update the scene editor (for new PhysicsScene pointer, initially loaded in GApp)
removeWidget(developerWindow->sceneEditorWindow);
developerWindow->sceneEditorWindow = SceneEditorWindow::create(this, scene(), theme);
developerWindow->sceneEditorWindow->moveTo(developerWindow->cameraControlWindow->rect().x0y1() + Vector2(0, 15));
developerWindow->sceneEditorWindow->setVisible(startupConfig.developerMode);
}
// Open sub-window buttons here (menu-style)
debugPane->removeAllChildren();
debugPane->beginRow(); {
debugPane->addButton("Render Controls [1]", this, &FPSciApp::showRenderControls);
debugPane->addButton("Player Controls [2]", this, &FPSciApp::showPlayerControls);
debugPane->addButton("Weapon Controls [3]", this, &FPSciApp::showWeaponControls);
if(notNull(waypointManager)) debugPane->addButton("Waypoint Manager [4]", waypointManager, &WaypointManager::showWaypointWindow);
}debugPane->endRow();
// Create the user settings window
if (notNull(m_userSettingsWindow)) { removeWidget(m_userSettingsWindow); }
m_userSettingsWindow = UserMenu::create(this, userTable, userStatusTable, sessConfig->menu, theme, Rect2D::xywh(0.0f, 0.0f, 10.0f, 10.0f));
addWidget(m_userSettingsWindow);
openUserSettingsWindow();
// Setup the debug window
debugWindow->pack();
debugWindow->setRect(Rect2D::xywh(0, 0, (float)window()->renderDevice()->viewport().width(), debugWindow->rect().height()));
m_debugMenuHeight = startupConfig.developerMode ? debugWindow->rect().height() : 0.0f;
// Add the control panes here
updateUserMenu = true;
// If we require a new user show the menu on startup regardless of configuration
showUserMenu = experimentConfig.menu.showMenuOnStartup || experimentConfig.menu.requireUserAdd;
updateDeveloperControls(std::make_shared<FpsConfig>((FpsConfig)experimentConfig));
}
void FPSciApp::exportScene() {
CFrame frame = scene()->typedEntity<PlayerEntity>("player")->frame();
logPrintf("Player position is: [%f, %f, %f]\n", frame.translation.x, frame.translation.y, frame.translation.z);
String filename = Scene::sceneNameToFilename(trialConfig->scene.name);
scene()->toAny().save(filename); // Save this w/o JSON format (breaks scene.Any file)
}
void FPSciApp::showPlayerControls() {
m_playerControls->setVisible(true);
}
void FPSciApp::showRenderControls() {
m_renderControls->setVisible(true);
}
void FPSciApp::showWeaponControls() {
m_weaponControls->setVisible(true);
}
void FPSciApp::presentQuestion(Question question) {
if (notNull(dialog)) removeWidget(dialog); // Remove the current dialog widget (if valid)
currentQuestion = question; // Store this for processing key-bound presses
Array<String> options = question.options; // Make a copy of the options (to add key binds if necessary)
if (question.randomOrder) options.randomize();
const Rect2D windowRect = window()->clientRect();
const Point2 size = question.fullscreen ? Point2(windowRect.width(), windowRect.height()) : Point2(400, 200);
switch (question.type) {
case Question::Type::MultipleChoice:
if (question.optionKeys.length() > 0) { // Add key-bound option to the dialog
for (int i = 0; i < options.length(); i++) {
// Find the correct index for this option (order might be randomized)
int keyIdx;
for (keyIdx = 0; keyIdx < question.options.length(); keyIdx++) {
if (options[i] == question.options[keyIdx]) break;
}
options[i] += format(" (%s)", question.optionKeys[keyIdx].toString());
}
}
dialog = SelectionDialog::create(question.prompt, options, theme, question.title, question.showCursor, question.optionsPerRow, size, !question.fullscreen,
question.promptFontSize, question.optionFontSize, question.buttonFontSize);
break;
case Question::Type::Entry:
dialog = TextEntryDialog::create(question.prompt, theme, question.title, false, size, !question.fullscreen, question.promptFontSize, question.buttonFontSize);
break;
case Question::Type::Rating:
if (question.optionKeys.length() > 0) { // Add key-bound option to the dialog
for (int i = 0; i < options.length(); i++) {
// Find the correct index for this option (order might be randomized)
int keyIdx;
for (keyIdx = 0; keyIdx < question.options.length(); keyIdx++) {
if (options[i] == question.options[keyIdx]) break;
}
options[i] += format(" (%s)", question.optionKeys[keyIdx].toString());
}
}
dialog = RatingDialog::create(question.prompt, options, theme, question.title, question.showCursor, size, !question.fullscreen,
question.promptFontSize, question.optionFontSize, question.buttonFontSize);
break;
case Question::Type::DropDown:
dialog = DropDownDialog::create(question.prompt, options, theme, question.title, size, !question.fullscreen, question.promptFontSize, question.buttonFontSize);
break;
default:
throw "Unknown question type!";
break;
}
moveToCenter(dialog);
addWidget(dialog);
setMouseInputMode(question.showCursor ? MouseInputMode::MOUSE_CURSOR : MouseInputMode::MOUSE_DISABLED);
}
void FPSciApp::markSessComplete(String sessId) {
if (notNull(m_pyLogger)) {
m_pyLogger->mergeLogToDb();
}
// Add the session id to completed session array and save the user status table
userStatusTable.addCompletedSession(userStatusTable.currentUser, sessId);
logPrintf("Marked session: %s complete for user %s.\n", sessId, userStatusTable.currentUser);
// Update the session drop-down to remove this session
m_userSettingsWindow->updateSessionDropDown();
}
void FPSciApp::updateFrameParameters(int frameDelay, float frameRate) {
// Apply frame lag
displayLagFrames = frameDelay;
lastSetFrameRate = frameRate;
// Set a maximum *finite* frame rate
float dt = 0;
if (frameRate > 0) dt = 1.0f / frameRate;
else dt = 1.0f / float(window()->settings().refreshRate);
// Update the desired realtime framerate, leaving the simulation timestep as it were (likely REAL_TIME)
setFrameDuration(dt, simStepDuration());
}
void FPSciApp::initPlayer(const shared_ptr<FpsConfig> config, const bool respawn, bool setSpawnPosition) {
shared_ptr<PhysicsScene> pscene = typedScene<PhysicsScene>();
shared_ptr<PlayerEntity> player = scene()->typedEntity<PlayerEntity>("player"); // Get player from the scene
// Update the player camera
const String pcamName = config->scene.playerCamera;
playerCamera = pcamName.empty() ? scene()->defaultCamera() : scene()->typedEntity<Camera>(pcamName);
alwaysAssertM(notNull(playerCamera), format("Scene %s does not contain a camera named \"%s\"!", config->scene.name, pcamName));
setActiveCamera(playerCamera);
// Set gravity and camera field of view
Vector3 grav = experimentConfig.player.gravity;
float FoV = experimentConfig.render.hFoV;
if (notNull(config)) {
grav = config->player.gravity;
FoV = config->render.hFoV;
}
pscene->setGravity(grav);
String respawnHeightSource;
playerCamera->setFieldOfView(FoV * units::degrees(), FOVDirection::HORIZONTAL);
if (!m_sceneHasPlayerEntity) { // Scene doesn't have player entity, copy the player entity frame from the camera
respawnHeightSource = format("\"%s\" camera in scene.Any file", playerCamera->name());
player->setFrame(m_initialCameraFrames[playerCamera->name()]);
setSpawnPosition = true; // Set the player spawn position from the camera
}
else {
respawnHeightSource = "PlayerEntity in scene.Any file";
}
playerCamera->setFrame(player->getCameraFrame());
// For now make the player invisible (prevent issues w/ seeing model from inside)
player->setVisible(false);
// Set the reset height
String resetHeightSource = "scene configuration \"resetHeight\" parameter";
float resetHeight = config->scene.resetHeight;
if (isnan(resetHeight)) {
resetHeightSource = "scene.Any Physics \"minHeight\" field";
resetHeight = pscene->resetHeight();
if (isnan(resetHeight)) {
resetHeightSource = "default value";
resetHeight = -1e6;
}
}
player->setRespawnHeight(resetHeight);
// Update the respawn heading
float spawnHeadingDeg = config->scene.spawnHeadingDeg;
if (isnan(spawnHeadingDeg)) { // No SceneConfig spawn heading specified, get heading from scene.Any player entity heading field
if (setSpawnPosition) { // This is the first spawn in the scene
Point3 view_dir = playerCamera->frame().lookVector();
spawnHeadingDeg = atan2(view_dir.x, -view_dir.z) * 180 / pif();
player->setRespawnHeadingDegrees(spawnHeadingDeg);
}
}
else player->setRespawnHeadingDegrees(spawnHeadingDeg);
// Set player respawn location
float respawnPosHeight = player->respawnPosHeight(); // Report the respawn position height
if (config->scene.spawnPosition.isNaN()) {
if (setSpawnPosition) { // This is the first spawn, copy the respawn position from the scene
player->setRespawnPosition(player->frame().translation);
respawnPosHeight = player->frame().translation.y;
}
}
else { // Respawn position set by scene config
player->setRespawnPosition(config->scene.spawnPosition);
respawnPosHeight = config->scene.spawnPosition.y;
respawnHeightSource = "scene configuration \"spawnPosition\" parameter";
}
if (respawnPosHeight < resetHeight) {
throw format("Invalid respawn height (%f) from %s (< %f specified from %s)!", respawnPosHeight, respawnHeightSource.c_str(), resetHeight, resetHeightSource.c_str());
}
// Set player values from session config
player->moveRate = &config->player.moveRate;
player->moveScale = &config->player.moveScale;
player->axisLock = &config->player.axisLock;
player->jumpVelocity = &config->player.jumpVelocity;
player->jumpInterval = &config->player.jumpInterval;
player->jumpTouch = &config->player.jumpTouch;
player->height = &config->player.height;
player->crouchHeight = &config->player.crouchHeight;
// Respawn player
if (respawn) player->respawn();
updateMouseSensitivity();
// Set initial heading for trial/session reference target (from player spawn heading)
sess->initialHeadingRadians = player->respawnHeadingRadians();
}
void FPSciApp::updateSession(const String& id, const bool forceSceneReload) {
// Check for a valid ID (non-emtpy and
Array<String> ids;
experimentConfig.getSessionIds(ids);
if (!id.empty() && ids.contains(id)) {
// Load the session config specified by the id
sessConfig = experimentConfig.getSessionConfigById(id);
logPrintf("User selected session: %s. Updating now...\n", id.c_str());
m_userSettingsWindow->setSelectedSession(id);
// Create the session based on the loaded config
sess = Session::create(this, sessConfig);
}
else {
// Create an empty session
sessConfig = SessionConfig::create();
sess = Session::create(this);
playerCamera = activeCamera();
}
// Update colored materials to choose from for target health
for (String id : sessConfig->getUniqueTargetIds()) {
shared_ptr<TargetConfig> tconfig = experimentConfig.getTargetConfigById(id);
materials.remove(id);
materials.set(id, makeMaterials(tconfig));
}
// Handle clearing the targets here (clear any remaining targets before loading a new scene)
if (notNull(scene())) sess->clearTargets();
// Update the application w/ the session parameters
updateUserMenu = true;
if (!m_firstSession) showUserMenu = sessConfig->menu.showMenuBetweenSessions;
updateConfigParameters(sessConfig, forceSceneReload, true, false);
// Handle results files
const String resultsDirPath = startupConfig.experimentList[experimentIdx].resultsDirPath;
// Check for need to start latency logging and if so run the logger now
if (!FileSystem::isDirectory(resultsDirPath)) {
FileSystem::createDirectory(resultsDirPath);
}
// Create and check log file name
const String logFileBasename = sessConfig->logger.logToSingleDb ?
experimentConfig.description + "_" + userStatusTable.currentUser + "_" + m_expConfigHash :
id + "_" + userStatusTable.currentUser + "_" + String(FPSciLogger::genFileTimestamp());
const String logFilename = FilePath::makeLegalFilename(logFileBasename);
// This is the specified path and log basename with illegal characters replaced, but not suffix (.db)
const String logPath = resultsDirPath + logFilename;
// Logger only supported at the session-level
if (systemConfig.hasLogger) {
if (!sessConfig->clickToPhoton.enabled) {
logPrintf("WARNING: Using a click-to-photon logger without the click-to-photon region enabled!\n\n");
}
if (m_pyLogger == nullptr) {
m_pyLogger = PythonLogger::create(systemConfig.loggerComPort, systemConfig.hasSync, systemConfig.syncComPort);
}
else {
// Handle running logger if we need to (terminate then merge results)
m_pyLogger->mergeLogToDb();
}
// Run a new logger if we need to (include the mode to run in here...)
m_pyLogger->run(logPath, sessConfig->clickToPhoton.mode);
}
// Initialize the experiment (this creates the results file)
sess->onInit(logPath, experimentConfig.description + "/" + sessConfig->description);
// Don't create a results file for a user w/ no sessions left
if (m_userSettingsWindow->sessionsForSelectedUser() == 0) {
logPrintf("No sessions remaining for selected user.\n");
}
else if (sessConfig->logger.enable) {
logPrintf("Created results file: %s.db\n", logPath.c_str());
}
if (m_firstSession) {
m_firstSession = false;
}
}
void FPSciApp::updateTrial(const shared_ptr<TrialConfig> config, const bool forceSceneReload, const bool respawn) {
trialConfig = config; // Naive way to store trial config pointer for now
updateUserMenu = true;
updateConfigParameters(config, forceSceneReload, respawn);
}
void FPSciApp::updateConfigParameters(const shared_ptr<FpsConfig> config, const bool forceSceneReload, const bool respawn, const bool trialLevel) {
// Update reticle
reticleConfig.index = config->reticle.indexSpecified ? config->reticle.index : currentUser()->reticle.index;
reticleConfig.scale = config->reticle.scaleSpecified ? config->reticle.scale : currentUser()->reticle.scale;
reticleConfig.color = config->reticle.colorSpecified ? config->reticle.color : currentUser()->reticle.color;
reticleConfig.changeTimeS = config->reticle.changeTimeSpecified ? config->reticle.changeTimeS : currentUser()->reticle.changeTimeS;
setReticle(reticleConfig.index);
updateDeveloperControls(config);
// Update the frame rate/delay
updateFrameParameters(config->render.frameDelay, config->render.frameRate);
// Handle buffer setup here
updateShaderBuffers(config);
// Update shader table
m_shaderTable.clear();
if (!config->render.shader3D.empty()) {
m_shaderTable.set(config->render.shader3D, G3D::Shader::getShaderFromPattern(config->render.shader3D));
}
if (!config->render.shader2D.empty()) {
m_shaderTable.set(config->render.shader2D, G3D::Shader::getShaderFromPattern(config->render.shader2D));
}
if (!config->render.shaderComposite.empty()) {
m_shaderTable.set(config->render.shaderComposite, G3D::Shader::getShaderFromPattern(config->render.shaderComposite));
}
// Update shader parameters
m_startTime = System::time();
m_last2DTime = m_startTime;
m_last3DTime = m_startTime;
m_lastCompositeTime = m_startTime;
m_frameNumber = 0;
// Load (session dependent) fonts
hudFont = GFont::fromFile(System::findDataFile(config->hud.hudFont));
m_combatFont = GFont::fromFile(System::findDataFile(config->targetView.combatTextFont));
// Load the experiment scene if we haven't already (target only)
if (trialLevel) { // Only force scenes to load at the trial-level
if (config->scene.name.empty()) {
// No scene specified, load default scene
if (m_loadedScene.name.empty() || forceSceneReload) {
loadScene(m_defaultSceneName); // Note: this calls onGraphics()
m_loadedScene.name = m_defaultSceneName;
}
// Otherwise let the loaded scene persist
}
else if (config->scene != m_loadedScene || forceSceneReload) {
loadScene(config->scene.name);
m_loadedScene = config->scene;
}
initPlayer(config, respawn); // Setup the player within the scene
// Check for play mode specific parameters
if (notNull(weapon)) weapon->clearDecals();
weapon->setConfig(&config->weapon);
weapon->setScene(scene());
weapon->setCamera(activeCamera());
// Update weapon model (if drawn) and sounds
weapon->loadModels();
if(startupConfig.audioEnable) weapon->loadSounds();
if (!config->audio.sceneHitSound.empty()) {
m_sceneHitSound = Sound::create(System::findDataFile(config->audio.sceneHitSound));
// Play silently to pre-load the sound
m_sceneHitSound->play(0.f);
}
if (!config->audio.refTargetHitSound.empty()) {
m_refTargetHitSound = Sound::create(System::findDataFile(config->audio.refTargetHitSound));
// Play silently to pre-load the sound
m_refTargetHitSound->play(0.f);
}
// Load static HUD textures
for (StaticHudElement element : config->hud.staticElements) {
hudTextures.set(element.filename, Texture::fromFile(System::findDataFile(element.filename)));
}
}
}
void FPSciApp::quitRequest() {
// End session logging
if (notNull(sess)) {
sess->endLogging();
}
// Merge Python log into session log (if logging)
if (notNull(m_pyLogger)) {
m_pyLogger->mergeLogToDb(true);
}
setExitCode(0);
}
void FPSciApp::onAfterLoadScene(const Any& any, const String& sceneName) {
// Make sure the scene has a "player" entity
shared_ptr<PlayerEntity> player = scene()->typedEntity<PlayerEntity>("player");
m_sceneHasPlayerEntity = notNull(player);
if (!m_sceneHasPlayerEntity) { // Add a player if one isn't present in the scene
logPrintf("WARNING: Didn't find a \"player\" specified in \"%s\"! Adding one at the origin.", sceneName);
shared_ptr<Entity> newPlayer = PlayerEntity::create("player", scene().get(), CFrame(), nullptr);
scene()->insert(newPlayer);
}
// Build lookup of initial camera positions here
Array<shared_ptr<Camera>> camArray;
scene()->getTypedEntityArray<Camera>(camArray);
for (shared_ptr<Camera> cam : camArray) {
m_initialCameraFrames.set(cam->name(), cam->frame());
}
initPlayer(trialConfig, false, true); // Initialize the player (first time for this scene)
if (weapon) {
weapon->setScene(scene());
weapon->setCamera(playerCamera);
}
}
void FPSciApp::onAI() {
GApp::onAI();
// Add non-simulation game logic and AI code here
}
void FPSciApp::onNetwork() {
GApp::onNetwork();
// Poll net messages here
}
void FPSciApp::onSimulation(RealTime rdt, SimTime sdt, SimTime idt) {
const shared_ptr<PlayerEntity>& player = scene()->typedEntity<PlayerEntity>("player");
// TODO: this should eventually probably use sdt instead of rdt
RealTime currentRealTime;
if (m_lastOnSimulationRealTime == 0) {
m_lastOnSimulationRealTime = System::time(); // Grab the current system time if uninitialized
currentRealTime = m_lastOnSimulationRealTime; // Set this equal to the current system time
}
else {
currentRealTime = m_lastOnSimulationRealTime + rdt; // Increment the time by the current real time delta
}
bool stateCanFire = sess->currentState == PresentationState::trialTask && !m_userSettingsWindow->visible();
// These variables will be used to fire after the various weapon styles populate them below
int numShots = 0;
float damagePerShot = weapon->damagePerShot();
RealTime newLastFireTime = currentRealTime;
if (shootButtonJustPressed && stateCanFire && !weapon->canFire(currentRealTime)) {
// Invalid click since the weapon isn't ready to fire
sess->accumulatePlayerAction(PlayerActionType::FireCooldown);
}
else if (shootButtonJustPressed && !weapon->config()->autoFire && weapon->canFire(currentRealTime) && stateCanFire) {
// Discrete weapon fires a single shot with normal damage at the current time
numShots = 1;
// These copy the above defaults, but are here for clarity
damagePerShot = weapon->damagePerShot();
newLastFireTime = currentRealTime;
}
else if (weapon->config()->autoFire && !weapon->config()->isContinuous() && !shootButtonUp && stateCanFire) {
// Autofire weapon should create shots until currentRealTime with normal damage
if (shootButtonJustPressed) {
// If the button was just pressed, fire one bullet half way through
weapon->setLastFireTime(m_lastOnSimulationRealTime + rdt * 0.5f);
numShots = 1;
}
// Add on bullets until the frame time
int newShots = weapon->numShotsUntil(currentRealTime);
numShots += newShots;
newLastFireTime = weapon->lastFireTime() + (float)(newShots) * weapon->config()->firePeriod;
// This copies the above default, but are here for clarity
damagePerShot = weapon->damagePerShot();
}
else if (weapon->config()->isContinuous() && (!shootButtonUp || shootButtonJustReleased) && stateCanFire) {
// Continuous weapon should have been firing continuously, but since we do sampled simulation
// this approximates continuous fire by releasing a single "megabullet"
// with power that matches the elapsed time at the current
numShots = 1;
// If the button was just pressed, assume the duration should begin half way through
if (shootButtonJustPressed) {
weapon->setLastFireTime(m_lastOnSimulationRealTime + rdt * 0.5f);
}
// If the shoot button just released, assume the fire ended half way through
newLastFireTime = shootButtonJustReleased ? m_lastOnSimulationRealTime + rdt * 0.5f : currentRealTime;
RealTime fireDuration = weapon->fireDurationUntil(newLastFireTime);
damagePerShot = (float)fireDuration * weapon->config()->damagePerSecond;
}
// Auto aim if requested
if (numShots > 0 && trialConfig->aimAssist.snapOnFire && canAutoAim()) {
assistAim(sess->hittableTargets(), sdt);
}
// Actually shoot here
m_currentWeaponDamage = damagePerShot; // pass this to the callback where weapon damage is applied
bool shotFired = false;
for (int shotId = 0; shotId < numShots; shotId++) {
Array<shared_ptr<Entity>> dontHit;
dontHit.append(m_explosions);
dontHit.append(sess->unhittableTargets());
Model::HitInfo info;
float hitDist = finf();
int hitIdx = -1;
shared_ptr<TargetEntity> target = weapon->fire(sess->hittableTargets(), hitIdx, hitDist, info, dontHit, false); // Fire the weapon
if (isNull(target)) // Miss case
{
// Play scene hit sound
if (!weapon->config()->isContinuous() && notNull(m_sceneHitSound)) {
m_sceneHitSound->play(trialConfig->audio.sceneHitSoundVol);
}
}
shotFired = true;
}
if (shotFired) {
weapon->setLastFireTime(newLastFireTime);
}
weapon->playSound(shotFired, shootButtonUp);
// TODO (or NOTTODO): The following can be cleared at the cost of one more level of inheritance.
sess->onSimulation(rdt, sdt, idt);
// These are all we need from GApp::onSimulation() for walk mode
m_widgetManager->onSimulation(rdt, sdt, idt);
if (scene()) { scene()->onSimulation(sdt); }
// make sure mouse sensitivity is set right
if (m_userSettingsWindow->visible()) {
updateMouseSensitivity();
}
// Simulate the projectiles
weapon->simulateProjectiles(sdt, sess->hittableTargets());
// explosion animation
for (int i = 0; i < m_explosions.size(); i++) {
shared_ptr<VisibleEntity> explosion = m_explosions[i];
m_explosionRemainingTimes[i] -= sdt;
if (m_explosionRemainingTimes[i] <= 0) {
scene()->remove(explosion);
m_explosions.fastRemove(i);
m_explosionRemainingTimes.fastRemove(i);
i--;
}
else {
// could update animation here...
}
}
// Move the player
const shared_ptr<PlayerEntity>& p = scene()->typedEntity<PlayerEntity>("player");
if(notNull(p)) playerCamera->setFrame(p->getCameraFrame());
// Handle developer mode features here
if (startupConfig.developerMode) {
// If the debug camera is selected, update it's position from the FPM
if (activeCamera() == m_debugCamera) {
m_debugCamera->setFrame(m_cameraManipulator->frame());
}
// Handle frame rate/delay updates here
if (trialConfig->render.frameRate != lastSetFrameRate || displayLagFrames != trialConfig->render.frameDelay) {
updateFrameParameters(trialConfig->render.frameDelay, trialConfig->render.frameRate);
}
if (notNull(waypointManager) && notNull(p)) {
// Handle highlighting for selected target
waypointManager->updateSelected();
// Handle player motion recording here
waypointManager->updatePlayerPosition(player->getCameraFrame().translation);
}
// Example GUI dynamic layout code. Resize the debugWindow to fill
// the screen horizontally.
debugWindow->setRect(Rect2D::xywh(0.0f, 0.0f, (float)window()->width(), debugWindow->rect().height()));
}