-
Notifications
You must be signed in to change notification settings - Fork 23
/
Session.cpp
1284 lines (1163 loc) · 51.9 KB
/
Session.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
/***************************************************************************
# Copyright (c) 2015, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of NVIDIA CORPORATION nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***************************************************************************/
#include "Session.h"
#include "FPSciApp.h"
#include "Logger.h"
#include "TargetEntity.h"
#include "PlayerEntity.h"
#include "Dialogs.h"
#include "Weapon.h"
#include "FPSciAnyTableReader.h"
TrialConfig::TrialConfig(const Any& any) : FpsConfig(any, defaultConfig()) {
int settingsVersion = 1;
FPSciAnyTableReader reader(any);
reader.getIfPresent("settingsVersion", settingsVersion);
switch (settingsVersion) {
case 1:
reader.getIfPresent("id", id);
if (!reader.getIfPresent("targetIds", targetIds)) {
if (reader.getIfPresent("ids", targetIds)) {
logPrintf("WARNING: Trial-level target IDs should be specified using \"targetIds\", the \"ids\" parameter is depricated!\n");
}
else throw "The \"targetIds\" field must be provided for each set of trials!";
}
if (!reader.getIfPresent("count", count)) {
count = defaultCount;
}
if (count < 1) {
throw format("Trial count < 1 not allowed! (%d count for trial with targets: %s)", count, Any(targetIds).unparse());
}
break;
default:
debugPrintf("Settings version '%d' not recognized in SessionConfig.\n", settingsVersion);
break;
}
}
Any TrialConfig::toAny(const bool forceAll) const {
Any a = FpsConfig::toAny(forceAll);
a["id"] = id;
a["targetIds"] = targetIds;
a["count"] = count;
return a;
}
TaskConfig::TaskConfig(const Any& any) {
FPSciAnyTableReader reader(any);
reader.get("id", id, "Tasks must be provided w/ an \"id\" field!");
reader.get("trialOrders", trialOrders, "Tasks must be provided w/ trial orders!");
reader.getIfPresent("count", count);
reader.getIfPresent("questions", questions);
// Get the list of options from the final multiple choice question
Array<String> options;
for (int i = 0; i < questions.size(); i++) {
// Use options from the final multiple choice question
if (questions[i].type == Question::Type::MultipleChoice) {
questionIdx = i;
options = questions[i].options;
}
}
// Check that each trial order has a valid correctAnswer (if specified)
for (TrialOrder& order : trialOrders) {
if (!order.correctAnswer.empty()) {
if (options.size() == 0) {
throw format("Task \"%s\" specifies a \"correctAnswer\" but no multiple choice questions are specified!", id);
}
// This order has a specified correct answer
if (!options.contains(order.correctAnswer)) {
throw format("The specfied \"correctAnswer\" (\"%s\") for task \"%s\" is not a valid option for the final multiple choice question in this task!", order.correctAnswer, id);
}
}
}
}
Any TaskConfig::toAny(const bool forceAll) const {
TaskConfig def;
Any a(Any::TABLE);
a["id"] = id;
a["trialOrders"] = trialOrders;
if (forceAll || def.count != count) a["count"] = count;
if (forceAll || questions.length() > 0) a["questions"] = questions;
return a;
}
SessionConfig::SessionConfig(const Any& any) : FpsConfig(any, defaultConfig()) {
TrialConfig::defaultCount = timing.defaultTrialCount;
FPSciAnyTableReader reader(any);
Set<String> uniqueIds;
switch (settingsVersion) {
case 1:
TrialConfig::defaultConfig() = (FpsConfig)(*this); // Setup the default configuration for trials here
// Unique session info
reader.get("id", id, "An \"id\" field must be provided for each session!");
reader.getIfPresent("description", description);
reader.getIfPresent("closeOnComplete", closeOnComplete);
reader.getIfPresent("randomizeTrialOrder", randomizeTaskOrder);
reader.getIfPresent("randomizeTaskOrder", randomizeTaskOrder);
reader.getIfPresent("weightByCount", weightByCount);
reader.getIfPresent("blockCount", blockCount);
reader.get("trials", trials, format("Issues in the (required) \"trials\" array for session: \"%s\"", id));
for (int i = 0; i < trials.length(); i++) {
if (trials[i].id.empty()) { // Look for trials without an id
trials[i].id = String(std::to_string(i)); // Autoname w/ index
}
uniqueIds.insert(trials[i].id);
if (uniqueIds.size() != i + 1) {
logPrintf("ERROR: Duplicate trial ID \"%s\" found (trials without IDs are assigned an ID equal to their index in the trials array)!\n", trials[i].id);
}
}
if (uniqueIds.size() != trials.size()) {
throw "Duplicate trial IDs found in experiment config. Check log.txt for details!";
}
reader.getIfPresent("tasks", tasks);
break;
default:
debugPrintf("Settings version '%d' not recognized in SessionConfig.\n", settingsVersion);
break;
}
}
Any SessionConfig::toAny(const bool forceAll) const {
// Get the base any config
Any a = FpsConfig::toAny(forceAll);
SessionConfig def;
// Update w/ the session-specific fields
a["id"] = id;
a["description"] = description;
if (forceAll || def.closeOnComplete != closeOnComplete) a["closeOnComplete"] = closeOnComplete;
if (forceAll || def.randomizeTaskOrder != randomizeTaskOrder) a["randomizeTaskOrder"] = randomizeTaskOrder;
if (forceAll || def.weightByCount != weightByCount) a["weightByCount"] = weightByCount;
if (forceAll || def.blockCount != blockCount) a["blockCount"] = blockCount;
a["trials"] = trials;
if (forceAll || tasks.length() > 0) a["tasks"] = tasks;
return a;
}
float SessionConfig::getTrialOrdersPerBlock(void) const {
float count = 0.f;
if (tasks.length() == 0) {
for (const TrialConfig& tc : trials) {
if (tc.count < 0) { return finf(); }
else { count += tc.count; }
}
}
else {
for (const TaskConfig& tc : tasks) {
if (tc.count < 0) { return finf(); }
else {
// Total trials are count * length of trial orders
count += tc.count * tc.trialOrders.length();
}
}
}
return count;
}
int SessionConfig::getTrialIndex(const String& id) const {
for (int i = 0; i < trials.length(); i++) {
if (trials[i].id == id) return i; // Return the index of the trial
}
return -1; // Return invalid index if not found
}
Array<String> SessionConfig::getUniqueTargetIds() const {
Array<String> targetIds;
for (TrialConfig trial : trials) {
for (String id : trial.targetIds) {
if (!targetIds.contains(id)) { targetIds.append(id); }
}
}
return targetIds;
}
Session::Session(FPSciApp* app, shared_ptr<SessionConfig> config) : m_app(app), m_sessConfig(config), m_weapon(app->weapon) {
m_hasSession = notNull(m_sessConfig);
}
Session::Session(FPSciApp* app) : m_app(app), m_weapon(app->weapon) {
m_hasSession = false;
}
const RealTime Session::targetFrameTime()
{
const RealTime defaultFrameTime = 1.0 / m_app->window()->settings().refreshRate;
if (!m_hasSession) return defaultFrameTime;
uint arraySize = m_trialConfig->render.frameTimeArray.size();
if (arraySize > 0) {
if ((m_trialConfig->render.frameTimeMode == "taskonly" || m_trialConfig->render.frameTimeMode == "restartwithtask") && currentState != PresentationState::trialTask) {
// We are in a frame time mode which specifies only to change frame time during the task
return 1.0f / m_trialConfig->render.frameRate;
}
if (m_trialConfig->render.frameTimeRandomize) {
return m_trialConfig->render.frameTimeArray.randomElement();
}
else {
RealTime targetTime = m_trialConfig->render.frameTimeArray[m_frameTimeIdx % arraySize];
m_frameTimeIdx += 1;
m_frameTimeIdx %= arraySize;
return targetTime;
}
}
// The below matches the functionality in FPSciApp::updateParameters()
if (m_trialConfig->render.frameRate > 0) {
return 1.0f / m_trialConfig->render.frameRate;
}
return defaultFrameTime;
}
bool Session::nextTrial() {
// Do we need to create a new task?
if(m_taskTrials.length() == 0) {
// Build an array of unrun tasks in this block
Array<Array<int>> unrunTaskIdxs;
for (int i = 0; i < m_remainingTasks.size(); i++) {
for (int j = 0; j < m_remainingTasks[i].size(); j++) {
if (m_remainingTasks[i][j] > 0 || m_remainingTasks[i][j] == -1) {
if (m_sessConfig->randomizeTaskOrder && m_sessConfig->weightByCount) {
// Weight by remaining count of this trial type
for (int k = 0; k < m_remainingTasks[i][j]; k++) {
unrunTaskIdxs.append(Array<int>(i,j)); // Add proportional to the # of times this task needs to be run
}
}
else {
// Add a single instance for each trial that is unrun (don't weight by remaining count)
unrunTaskIdxs.append(Array<int>(i,j));
}
}
}
}
if (unrunTaskIdxs.size() == 0) return false; // If there are no remaining tasks return
// Pick the new task and trial order index
int idx = 0;
// Are we randomizing task order (or randomizing trial order when trials are treated as tasks)?
if (m_sessConfig->randomizeTaskOrder) {
idx = Random::common().integer(0, unrunTaskIdxs.size() - 1); // Pick a random trial from within the array
}
m_currTaskIdx = unrunTaskIdxs[idx][0];
m_currOrderIdx = unrunTaskIdxs[idx][1];
m_completedTaskTrials.clear();
// Populate the task trial and completed task trials array
Array<String> trialIds;
String taskId;
if (m_sessConfig->tasks.size() == 0) {
// There are no tasks in this session, we need to create this task based on a single trial
trialIds = Array<String>(m_sessConfig->trials[m_currTaskIdx].id);
taskId = m_sessConfig->trials[m_currTaskIdx].id;
}
else {
trialIds = m_sessConfig->tasks[m_currTaskIdx].trialOrders[m_currOrderIdx].order;
taskId = m_sessConfig->tasks[m_currTaskIdx].id;
}
for (const String& trialId : trialIds) {
m_taskTrials.insert(0, m_sessConfig->getTrialIndex(trialId)); // Insert trial at the front of the task trials
m_completedTaskTrials.set(trialId, 0);
}
// Add task to tasks table in database
logger->addTask(m_sessConfig->id, m_currBlock-1, taskId, getTaskCount(m_currTaskIdx), trialIds);
}
// Select the next trial from this task (pop trial from back of task trails)
m_currTrialIdx = m_taskTrials.pop();
// Get and update the trial configuration
m_trialConfig = TrialConfig::createShared<TrialConfig>(m_sessConfig->trials[m_currTrialIdx]);
// Respawn player for first trial in session (override session-level spawn position)
m_app->updateTrial(m_trialConfig, false, m_firstTrial);
if (m_firstTrial) m_firstTrial = false;
else {
m_app->showUserMenu = false; // Override showing the user menu after the first trial in the session
}
// Update session fields (if changed) from trial
m_player = m_app->scene()->typedEntity<PlayerEntity>("player");
m_scene = m_app->scene().get();
m_camera = m_app->activeCamera();
// Produce (potentially random in range) pretrial duration
if (isNaN(m_trialConfig->timing.pretrialDurationLambda)) m_pretrialDuration = m_trialConfig->timing.pretrialDuration;
else m_pretrialDuration = drawTruncatedExp(m_trialConfig->timing.pretrialDurationLambda, m_trialConfig->timing.pretrialDurationRange[0], m_trialConfig->timing.pretrialDurationRange[1]);
return true; // Successfully loaded the new trial
}
int Session::getTaskCount(const int currTaskIdx) const {
int idx = 0;
for (int trialOrderCount : m_completedTasks[currTaskIdx]) {
idx += trialOrderCount;
}
return idx;
}
bool Session::blockComplete() const {
for (Array<int> trialOrders : m_remainingTasks) {
for (int remaining : trialOrders) {
if (remaining != 0) return false; // If any trials still need to be run block isn't complete
}
}
return true; // Block is complete
}
bool Session::nextBlock(bool init) {
if (m_sessConfig->tasks.size() == 0) { // If there are no tasks make each trial its own task
for (int i = 0; i < m_targetConfigs.size(); i++) { // There is 1 trial per task, and 1 set of targets specified per trial in the target configs array
if (init) { // If this is the first block in the session
m_completedTasks.append(Array<int>(0));
m_remainingTasks.append(Array<int>(m_sessConfig->trials[i].count));
}
else { // Update for a new block in the session
m_completedTasks[i][0] = 0;
m_remainingTasks[i][0] += m_trialConfig->count; // Add another set of trials of this type
}
}
}
else {
for (int i = 0; i < m_sessConfig->tasks.size(); i++) {
if (init) {
m_completedTasks.append(Array<int>()); // Initialize task-level completed trial orders array
m_remainingTasks.append(Array<int>()); // Initialize task-level remaining trial orders array
}
for (int j = 0; j < m_sessConfig->tasks[i].trialOrders.size(); j++) {
if (init) {
m_completedTasks[i].append(0); // Zero completed count
m_remainingTasks[i].append(m_sessConfig->tasks[i].count); // Append to complete count
}
else {
m_completedTasks[i][j] = 0;
m_remainingTasks[i][j] += m_sessConfig->tasks[i].count;
}
}
}
}
return nextTrial();
}
void Session::onInit(String filename, String description) {
// Initialize presentation states
currentState = PresentationState::initial;
if (m_sessConfig) {
m_feedbackMessage = formatFeedback(m_sessConfig->targetView.showRefTarget ? m_sessConfig->feedback.initialWithRef: m_sessConfig->feedback.initialNoRef);
}
// Get the player from the app
m_player = m_app->scene()->typedEntity<PlayerEntity>("player");
m_scene = m_app->scene().get();
m_camera = m_app->activeCamera();
m_targetModels = &(m_app->targetModels);
// Check for valid session
if (m_hasSession) {
if (m_sessConfig->logger.enable) {
UserConfig user = *m_app->currentUser();
// Setup the logger and create results file
logger = FPSciLogger::create(filename + ".db", user.id,
m_app->startupConfig.experimentList[m_app->experimentIdx].experimentConfigFilename,
m_sessConfig, description);
logger->logTargetTypes(m_app->experimentConfig.getSessionTargets(m_sessConfig->id)); // Log target info at start of session
logger->logUserConfig(user, m_sessConfig->id, m_sessConfig->player.turnScale); // Log user info at start of session
m_dbFilename = filename;
}
runSessionCommands("start"); // Run start of session commands
// Iterate over the sessions here and add a config for each
m_targetConfigs = m_app->experimentConfig.getTargetsByTrial(m_sessConfig->id);
nextBlock(true);
}
else { // Invalid session, move to displaying message
currentState = PresentationState::sessionFeedback;
}
}
void Session::randomizePosition(const shared_ptr<TargetEntity>& target) const {
static const Point3 initialSpawnPos = m_camera->frame().translation;
const int trialIdx = m_sessConfig->getTrialIndex(m_trialConfig->id);
shared_ptr<TargetConfig> config = m_targetConfigs[trialIdx][target->paramIdx()];
const bool isWorldSpace = config->destSpace == "world";
Point3 loc;
if (isWorldSpace) {
loc = config->spawnBounds.randomInteriorPoint(); // Set a random position in the bounds
target->resetMotionParams(); // Reset the target motion behavior
}
else {
const float rot_pitch = (config->symmetricEccV ? randSign() : 1) * Random::common().uniform(config->eccV[0], config->eccV[1]);
const float rot_yaw = (config->symmetricEccH ? randSign() : 1) * Random::common().uniform(config->eccH[0], config->eccH[1]);
const CFrame f = CFrame::fromXYZYPRDegrees(initialSpawnPos.x, initialSpawnPos.y, initialSpawnPos.z, - 180.0f/(float)pi()*initialHeadingRadians - rot_yaw, rot_pitch, 0.0f);
loc = f.pointToWorldSpace(Point3(0, 0, -m_targetDistance));
}
target->setFrame(loc);
}
void Session::initTargetAnimation(const bool task) {
// initialize target location based on the initial displacement values
// Not reference: we don't want it to change after the first call.
const Point3 initialSpawnPos = m_player->getCameraFrame().translation;
// In task state, spawn a test target. Otherwise spawn a target at straight ahead.
if (task) {
if (m_trialConfig->targetView.previewWithRef && m_trialConfig->targetView.showRefTarget) {
// Activate the preview targets
for (shared_ptr<TargetEntity> target : m_targetArray) {
target->setCanHit(true);
m_app->updateTargetColor(target);
m_hittableTargets.append(target);
}
}
else {
spawnTrialTargets(initialSpawnPos); // Spawn all the targets normally
m_weapon->drawsDecals = true; // Enable drawing decals
}
}
else { // State is feedback and we are spawning a reference target
CFrame f = CFrame::fromXYZYPRRadians(initialSpawnPos.x, initialSpawnPos.y, initialSpawnPos.z, -initialHeadingRadians, 0.0f, 0.0f);
// Spawn the reference target
auto t = spawnReferenceTarget(
f.pointToWorldSpace(Point3(0, 0, -m_targetDistance)),
initialSpawnPos,
m_trialConfig->targetView.refTargetSize,
m_trialConfig->targetView.refTargetColor
);
m_hittableTargets.append(t);
m_lastRefTargetPos = t->frame().translation; // Save last spawned reference target position
if (m_trialConfig->targetView.previewWithRef) {
spawnTrialTargets(initialSpawnPos, true); // Spawn all the targets in preview mode
}
// Set weapon decal state to match configuration for reference targets
m_weapon->drawsDecals = m_trialConfig->targetView.showRefDecals;
// Clear target logOnChange management
m_lastLogTargetLoc.clear();
}
// Reset number of destroyed targets (in the trial)
m_destroyedTargets = 0;
// Reset shot and hit counters (in the trial)
m_weapon->reload();
m_trialShotsHit = 0;
}
void Session::spawnTrialTargets(Point3 initialSpawnPos, bool previewMode) {
// Iterate through the targets
for (int i = 0; i < m_targetConfigs[m_currTrialIdx].size(); i++) {
const Color3 previewColor = m_trialConfig->targetView.previewColor;
shared_ptr<TargetConfig> target = m_targetConfigs[m_currTrialIdx][i];
const String name = format("%s_%d_%d_%d_%s_%d", m_sessConfig->id, m_currTaskIdx, m_currOrderIdx, m_completedTasks[m_currTaskIdx][m_currOrderIdx], target->id, i);
const float spawn_eccV = (target->symmetricEccV ? randSign() : 1) * Random::common().uniform(target->eccV[0], target->eccV[1]);
const float spawn_eccH = (target->symmetricEccH ? randSign() : 1) * Random::common().uniform(target->eccH[0], target->eccH[1]);
const float targetSize = G3D::Random().common().uniform(target->size[0], target->size[1]);
bool isWorldSpace = target->destSpace == "world";
// Log the target if desired
if (m_sessConfig->logger.enable) {
const String spawnTime = FPSciLogger::genUniqueTimestamp();
logger->addTarget(name, target, spawnTime, targetSize, Point2(spawn_eccH, spawn_eccV));
}
CFrame f = CFrame::fromXYZYPRDegrees(initialSpawnPos.x, initialSpawnPos.y, initialSpawnPos.z, -initialHeadingRadians * 180.0f / pif() - spawn_eccH, spawn_eccV, 0.0f);
// Check for case w/ destination array
shared_ptr<TargetEntity> t;
if (target->destinations.size() > 0) {
Point3 offset = isWorldSpace ? Point3(0.f, 0.f, 0.f) : f.pointToWorldSpace(Point3(0, 0, -m_targetDistance));
t = spawnDestTarget(target, offset, previewColor, i, name);
}
// Otherwise check if this is a jumping target
else if (target->jumpEnabled) {
Point3 offset = isWorldSpace ? target->spawnBounds.randomInteriorPoint() : f.pointToWorldSpace(Point3(0, 0, -m_targetDistance));
t = spawnJumpingTarget(target, offset, initialSpawnPos, previewColor, m_targetDistance, i, name);
}
else {
Point3 offset = isWorldSpace ? target->spawnBounds.randomInteriorPoint() : f.pointToWorldSpace(Point3(0, 0, -m_targetDistance));
t = spawnFlyingTarget(target, offset, initialSpawnPos, previewColor, i, name);
}
if (!previewMode) m_app->updateTargetColor(t); // If this isn't a preview target update its color now
// Set whether the target can be hit based on whether we are in preview mode
t->setCanHit(!previewMode);
previewMode ? m_unhittableTargets.append(t) : m_hittableTargets.append(t);
}
}
void Session::processResponse() {
m_taskExecutionTime = m_timer.getTime(); // Get time to copmplete the task
const int totalTargets = totalTrialTargets();
recordTrialResponse(m_destroyedTargets, totalTargets); // Record the trial response into the database
// Update completed/remaining task state
if (m_taskTrials.size() == 0) { // Task is complete update tracking
m_completedTasks[m_currTaskIdx][m_currOrderIdx] += 1; // Mark task trial order as completed
if (m_remainingTasks[m_currTaskIdx][m_currOrderIdx] > 0) { // Remove task trial order from remaining
m_remainingTasks[m_currTaskIdx][m_currOrderIdx] -= 1;
}
}
m_completedTaskTrials[m_trialConfig->id] += 1; // Incrememnt count of this trial type in task
// This update is only used for completed trials
if (notNull(logger)) {
// Get completed task and trial count
int completeTrials = 0;
int completeTasks = 0;
for (int i = 0; i < m_completedTasks.length(); i++) {
for (int count : m_completedTasks[i]) {
completeTrials += count;
}
bool taskComplete = true;
for (int remaining : m_remainingTasks[i]) {
if (remaining > 0) {
taskComplete = false;
break;
}
}
if (taskComplete) { completeTasks += 1; }
}
// Update session entry in database
logger->updateSessionEntry(m_currBlock > m_sessConfig->blockCount, completeTasks, completeTrials);
}
// Check for whether all targets have been destroyed
if (m_destroyedTargets == totalTargets) {
m_totalRemainingTime += (double(m_trialConfig->timing.maxTrialDuration) - m_taskExecutionTime);
m_feedbackMessage = formatFeedback(m_trialConfig->feedback.trialSuccess);
m_totalTrialSuccesses += 1;
}
else {
m_feedbackMessage = formatFeedback(m_trialConfig->feedback.trialFailure);
}
}
void Session::updatePresentationState() {
// This updates presentation state and also deals with data collection when each trial ends.
PresentationState newState;
int remainingTargets = m_hittableTargets.size();
float stateElapsedTime = m_timer.getTime();
newState = currentState;
if (currentState == PresentationState::initial)
{
if (m_trialConfig->player.stillBetweenTrials) {
m_player->setMoveEnable(false);
}
if (!(m_app->shootButtonUp && m_trialConfig->timing.clickToStart)) {
newState = PresentationState::referenceTarget;
}
}
else if (currentState == PresentationState::referenceTarget) {
// State for showing the trial reference target
if (remainingTargets == 0) {
newState = PresentationState::pretrial;
m_feedbackMessage = "";
}
}
else if (currentState == PresentationState::pretrial)
{
if (stateElapsedTime > m_pretrialDuration)
{
newState = PresentationState::trialTask;
if (m_trialConfig->player.stillBetweenTrials) {
m_player->setMoveEnable(true);
}
closeTrialProcesses(); // End previous process (if running)
runTrialCommands("start"); // Run start of trial commands
}
}
else if (currentState == PresentationState::trialTask)
{
if ((stateElapsedTime > m_trialConfig->timing.maxTrialDuration) || (remainingTargets <= 0) || (m_weapon->remainingAmmo() == 0))
{
m_taskEndTime = FPSciLogger::genUniqueTimestamp();
processResponse();
clearTargets(); // clear all remaining targets
newState = PresentationState::trialFeedback;
if (m_trialConfig->player.stillBetweenTrials) {
m_player->setMoveEnable(false);
}
if (m_trialConfig->player.resetPositionPerTrial) {
m_player->respawn();
}
closeTrialProcesses(); // Stop start of trial processes
runTrialCommands("end"); // Run the end of trial processes
// Reset weapon cooldown
m_weapon->resetCooldown();
if (m_weapon->config()->clearTrialMissDecals) { // Clear weapon's decals if specified
m_weapon->clearDecals(false);
}
}
}
else if (currentState == PresentationState::trialFeedback)
{
if (stateElapsedTime > m_trialConfig->timing.trialFeedbackDuration) {
bool allAnswered = presentQuestions(m_trialConfig->questionArray); // Present any trial-level questions
if (allAnswered) {
m_currQuestionIdx = -1; // Reset the question index
m_feedbackMessage = ""; // Clear the feedback message
if (m_taskTrials.length() == 0) newState = PresentationState::taskQuestions; // Move forward to providing task-level feedback
else { // Individual trial complete, go back to reference target
logger->updateTaskEntry(m_sessConfig->tasks[m_currTaskIdx].trialOrders[m_currOrderIdx].order.size() - m_taskTrials.size(), false);
nextTrial();
newState = PresentationState::referenceTarget;
}
}
}
}
else if (currentState == PresentationState::taskQuestions) {
bool allAnswered = true;
if (m_sessConfig->tasks.size() > 0) {
// Only ask questions if a task is specified (otherwise trial-level questions have already been presented)
allAnswered = presentQuestions(m_sessConfig->tasks[m_currTaskIdx].questions);
}
if (allAnswered) {
m_currQuestionIdx = -1; // Reset the question index
if (m_sessConfig->tasks.size() > 0) {
const int qIdx = m_sessConfig->tasks[m_currTaskIdx].questionIdx;
bool success = true; // Assume success (for case with no questions)
if (qIdx >= 0 && !m_sessConfig->tasks[m_currTaskIdx].trialOrders[m_currOrderIdx].correctAnswer.empty()) {
// Update the success value if a valid question was asked and correctAnswer was given
success = m_sessConfig->tasks[m_currTaskIdx].questions[qIdx].result == m_sessConfig->tasks[m_currTaskIdx].trialOrders[m_currOrderIdx].correctAnswer;
}
if (success) m_feedbackMessage = formatFeedback(m_sessConfig->feedback.taskSuccess);
else m_feedbackMessage = formatFeedback(m_sessConfig->feedback.taskFailure);
}
newState = PresentationState::taskFeedback;
}
}
else if (currentState == PresentationState::taskFeedback) {
if (stateElapsedTime > m_sessConfig->timing.taskFeedbackDuration) {
m_feedbackMessage = "";
int completeTrials = 1; // Assume 1 completed trial (if we don't have specified tasks)
if (m_sessConfig->tasks.size() > 0) completeTrials = m_sessConfig->tasks[m_currTaskIdx].trialOrders[m_currOrderIdx].order.size() - m_taskTrials.size();
logger->updateTaskEntry(completeTrials, true);
if (blockComplete()) {
m_currBlock++;
if (m_currBlock > m_sessConfig->blockCount) { // End of session (all blocks complete)
newState = PresentationState::sessionFeedback;
}
else { // Block is complete but session isn't
m_feedbackMessage = formatFeedback(m_sessConfig->feedback.blockComplete);
nextBlock();
newState = PresentationState::initial;
}
}
else { // Individual trial complete, go back to reference target
m_feedbackMessage = ""; // Clear the feedback message
nextTrial();
newState = PresentationState::referenceTarget;
}
}
}
else if (currentState == PresentationState::sessionFeedback) {
if (m_hasSession) {
if (stateElapsedTime > m_sessConfig->timing.sessionFeedbackDuration && (!m_sessConfig->timing.sessionFeedbackRequireClick || !m_app->shootButtonUp)) {
bool allAnswered = presentQuestions(m_sessConfig->questionArray); // Ask session-level questions
if (allAnswered) { // Present questions until done here
// Write final session timestamp to log
if (notNull(logger) && m_sessConfig->logger.enable) {
int completeTrials = 0;
int completeTasks = 0;
for (int i = 0; i < m_completedTasks.length(); i++) {
for (int count : m_completedTasks[i]) {
completeTrials += count;
}
bool taskComplete = true;
for (int remaining : m_remainingTasks[i]) {
if (remaining > 0) {
taskComplete = false;
break;
}
}
if (taskComplete) { completeTasks += 1; }
}
logger->updateSessionEntry(m_currBlock > m_sessConfig->blockCount, completeTasks, completeTrials); // Update session entry in database
}
if (m_sessConfig->logger.enable) {
endLogging();
}
m_app->markSessComplete(m_sessConfig->id); // Add this session to user's completed sessions
m_feedbackMessage = formatFeedback(m_sessConfig->feedback.sessComplete); // Update the feedback message
m_currQuestionIdx = -1;
newState = PresentationState::complete;
// Save current user config and status
m_app->saveUserConfig(true);
closeSessionProcesses(); // Close the process we started at session start (if there is one)
runSessionCommands("end"); // Launch processes for the end of the session
Array<String> remaining = m_app->updateSessionDropDown();
if (remaining.size() == 0) {
m_feedbackMessage = formatFeedback(m_sessConfig->feedback.allSessComplete); // Update the feedback message
moveOn = false;
if (m_app->experimentConfig.closeOnComplete || m_sessConfig->closeOnComplete) {
m_app->quitRequest();
}
}
else {
m_feedbackMessage = formatFeedback(m_sessConfig->feedback.sessComplete); // Update the feedback message
if (m_sessConfig->closeOnComplete) {
m_app->quitRequest();
}
moveOn = true; // Check for session complete (signal start of next session)
}
if (m_app->experimentConfig.closeOnComplete) {
m_app->quitRequest();
}
}
}
}
else {
// Go ahead and move to the complete state since there aren't any valid sessions
newState = PresentationState::complete;
m_feedbackMessage = formatFeedback(m_app->experimentConfig.feedback.allSessComplete);
moveOn = false;
if (m_app->experimentConfig.closeOnComplete) { // This is the case that is used for experiment config closeOnComplete!
m_app->quitRequest();
}
}
}
else {
newState = currentState;
}
if (currentState != newState)
{ // handle state transition.
m_timer.startTimer();
if (newState == PresentationState::referenceTarget) {
if (!m_trialConfig->targetView.showRefTarget) {
newState = PresentationState::pretrial; // If we don't want to show reference targets skip this step
}
else initTargetAnimation(false); // Spawn the reference (and also preview if requested) target(s)
}
if (newState == PresentationState::pretrial) {
// Clear weapon miss decals (if requested)
if (m_trialConfig->targetView.clearDecalsWithRef) {
m_weapon->clearDecals();
}
}
else if (newState == PresentationState::trialTask) {
if (m_sessConfig->render.frameTimeMode == "restartwithtask") {
m_frameTimeIdx = 0; // Reset the frame time index with the task if requested
}
// Test for aiming in valid region before spawning task targets
if (m_trialConfig->timing.maxPretrialAimDisplacement >= 0) {
Vector3 aim = m_camera->frame().lookVector().unit();
Vector3 ref = (m_lastRefTargetPos - m_camera->frame().translation).unit();
// Get the view displacement as the arccos of view/reference direction dot product (should never exceed 180 deg)
float viewDisplacement = 180 / pif() * acosf(aim.dot(ref));
if (viewDisplacement > m_trialConfig->timing.maxPretrialAimDisplacement) {
clearTargets(); // Clear targets (in case preview targets are being shown)
m_feedbackMessage = formatFeedback(m_trialConfig->feedback.aimInvalid);
newState = PresentationState::trialFeedback; // Jump to feedback state w/ error message
}
}
m_taskStartTime = FPSciLogger::genUniqueTimestamp();
initTargetAnimation(true); // Spawn task targets (or convert from previews)
}
currentState = newState;
}
}
void Session::onSimulation(RealTime rdt, SimTime sdt, SimTime idt) {
// 1. Update presentation state and send task performance to psychophysics library.
updatePresentationState();
// 2. Record target trajectories, view direction trajectories, and mouse motion.
accumulateTrajectories();
accumulateFrameInfo(rdt, sdt, idt);
}
bool Session::presentQuestions(Array<Question>& questions) {
if (questions.size() > 0 && m_currQuestionIdx < questions.size()) {
// Initialize if needed
if (m_currQuestionIdx == -1) {
m_currQuestionIdx = 0;
m_app->presentQuestion(questions[m_currQuestionIdx]);
}
// Manage answered quesions
else if (!m_app->dialog->visible()) { // Check for whether dialog is closed (otherwise we are waiting for input)
if (m_app->dialog->complete) { // Has this dialog box been completed? (or was it closed without an answer?)
questions[m_currQuestionIdx].result = m_app->dialog->result; // Store response w/ question
if (m_sessConfig->logger.enable) { // Log the question and its answer
if (currentState == PresentationState::trialFeedback) {
// End of trial question, log trial id and index
logger->addQuestion(questions[m_currQuestionIdx], m_sessConfig->id, m_app->dialog, m_sessConfig->tasks[m_currTaskIdx].id, m_lastTaskIndex, m_trialConfig->id, m_completedTaskTrials[m_trialConfig->id]-1);
}
else if (currentState == PresentationState::taskQuestions) {
// End of task question, log task id (no trial info)
logger->addQuestion(questions[m_currQuestionIdx], m_sessConfig->id, m_app->dialog, m_sessConfig->tasks[m_currTaskIdx].id, m_lastTaskIndex);
}
else { // End of session question, don't need to log a task/trial id/index
logger->addQuestion(questions[m_currQuestionIdx], m_sessConfig->id, m_app->dialog);
}
}
m_currQuestionIdx++; // Move to the next question
if (m_currQuestionIdx < questions.size()) { // Double check we have a next question before launching the next question
m_app->presentQuestion(questions[m_currQuestionIdx]); // Present the next question (if there is one)
}
else { // All questions complete
m_app->dialog.reset(); // Null the dialog pointer when all questions complete
m_app->setMouseInputMode(FPSciApp::MouseInputMode::MOUSE_FPM); // Go back to first-person mouse
return true;
}
}
else { // Dialog closed w/o a response (re-present the question)
m_app->presentQuestion(questions[m_currQuestionIdx]); // Relaunch the same dialog (this wasn't completed)
}
}
return false;
}
else return true;
}
void Session::recordTrialResponse(int destroyedTargets, int totalTargets) {
if (!m_sessConfig->logger.enable) return; // Skip this if the logger is disabled
if (m_trialConfig->logger.logTrialResponse) {
String taskId;
if (m_sessConfig->tasks.size() == 0) taskId = m_trialConfig->id;
else taskId = m_sessConfig->tasks[m_currTaskIdx].id;
// Get the (unique) index for this run of the task
m_lastTaskIndex = getTaskCount(m_currTaskIdx);
// Trials table. Record trial start time, end time, and task completion time.
FPSciLogger::TrialValues trialValues = {
"'" + m_sessConfig->id + "'",
format("'Block %d'", m_currBlock),
"'" + taskId + "'",
String(std::to_string(m_lastTaskIndex)),
"'" + m_trialConfig->id + "'",
String(std::to_string(m_completedTasks[m_currTaskIdx][m_currOrderIdx])),
"'" + m_taskStartTime + "'",
"'" + m_taskEndTime + "'",
String(std::to_string(m_pretrialDuration)),
String(std::to_string(m_taskExecutionTime)),
String(std::to_string(destroyedTargets)),
String(std::to_string(totalTargets))
};
logger->addTrialParamValues(trialValues, m_trialConfig);
logger->logTrial(trialValues);
}
}
void Session::accumulateTrajectories() {
if (notNull(logger) && m_trialConfig->logger.logTargetTrajectories) {
for (shared_ptr<TargetEntity> target : m_targetArray) {
if (!target->isLogged()) continue;
String name = target->name();
Point3 pos = target->frame().translation;
TargetLocation location = TargetLocation(FPSciLogger::getFileTime(), name, currentState, pos);
if (m_trialConfig->logger.logOnChange) {
// Check for target in logged position table
if (m_lastLogTargetLoc.containsKey(name) && location.noChangeFrom(m_lastLogTargetLoc[name])) {
continue; // Duplicates last logged position/state (don't log)
}
}
//// below for 2D direction calculation (azimuth and elevation)
//Point3 t = targetPosition.direction();
//float az = atan2(-t.z, -t.x) * 180 / pif();
//float el = atan2(t.y, sqrtf(t.x * t.x + t.z * t.z)) * 180 / pif();
logger->logTargetLocation(location);
m_lastLogTargetLoc.set(name, location); // Update the last logged location
}
}
// recording view direction trajectories
accumulatePlayerAction(PlayerActionType::Aim);
}
void Session::accumulatePlayerAction(PlayerActionType action, String targetName) {
// Count hits (in task state) here
if (currentState == PresentationState::trialTask) {
if (action == PlayerActionType::Miss) {
m_totalShots += 1;
m_accuracy = (float) m_totalShotsHit / (float) m_totalShots * 100.f;
}
if ((action == PlayerActionType::Hit || action == PlayerActionType::Destroy)) {
m_trialShotsHit++;
// Update scoring parameters
m_totalShotsHit++;
m_totalShots += 1;
m_accuracy = (float) m_totalShotsHit / (float) m_totalShots * 100.f;
if (action == PlayerActionType::Destroy) m_totalTargetsDestroyed += 1;
}
}
static PlayerAction lastPA;
if (notNull(logger) && m_trialConfig->logger.logPlayerActions) {
BEGIN_PROFILER_EVENT("accumulatePlayerAction");
// recording target trajectories
Point2 dir = getViewDirection();
Point3 loc = getPlayerLocation();
PlayerAction pa = PlayerAction(FPSciLogger::getFileTime(), dir, loc, currentState, action, targetName);
// Check for log only on change condition
if (m_trialConfig->logger.logOnChange && pa.noChangeFrom(lastPA)) {
return; // Early exit for (would be) duplicate log entry
}
logger->logPlayerAction(pa);
lastPA = pa; // Update last logged values
END_PROFILER_EVENT();
}
}
void Session::accumulateFrameInfo(RealTime t, float sdt, float idt) {
if (notNull(logger) && m_trialConfig->logger.logFrameInfo) {
logger->logFrameInfo(FrameInfo(FPSciLogger::getFileTime(), sdt));
}
}
bool Session::inTask() {
return currentState == PresentationState::trialTask;
}
float Session::getElapsedTrialTime() {
return m_timer.getTime();
}
float Session::getRemainingTrialTime() {
if (isNull(m_trialConfig)) return 10.0;
return m_trialConfig->timing.maxTrialDuration - m_timer.getTime();
}
float Session::getProgress() {
if (notNull(m_sessConfig)) {
// Get progress across tasks
float remainingTrialOrders = 0.f;
for (Array<int> trialOrderCounts : m_remainingTasks) {
for (int orderCount : trialOrderCounts) {
if (orderCount < 0) return 0.f; // Infinite trials, never make any progress
remainingTrialOrders += (float)orderCount;
}
}
// Get progress in current task
int completedTrialsInOrder = 0;
int totalTrialsInOrder = 1; // If there aren't tasks specified there is always 1 trial in this order (single order/trial task)
if(m_sessConfig->tasks.size() > 0) totalTrialsInOrder = m_sessConfig->tasks[m_currTaskIdx].trialOrders[m_currOrderIdx].order.length();
for (const String& trialId : m_completedTaskTrials.getKeys()) {
completedTrialsInOrder += m_completedTaskTrials[trialId];
}
float currTaskProgress = (float) completedTrialsInOrder / (float) totalTrialsInOrder;
// Start by getting task-level progress (based on m_remainingTrialOrders)
float overallProgress = 1.f - (remainingTrialOrders / m_sessConfig->getTrialOrdersPerBlock());
// Special case to avoid "double counting" completed tasks (if incomplete add progress in the current task, if complete it has been counted)
if (currTaskProgress < 1) overallProgress += currTaskProgress / m_sessConfig->getTrialOrdersPerBlock();
return overallProgress;
}
return fnan();
}
double Session::getScore() {
if (isNull(m_trialConfig)) return 0;
double score = 0;