-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSMITE.m
More file actions
2426 lines (2254 loc) · 130 KB
/
SMITE.m
File metadata and controls
2426 lines (2254 loc) · 130 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
% SMITE is a toolbox providing convenient access to eye tracking
% functionality using SMI eye trackers
%
% SMITE can be found at https://github.com/dcnieho/SMITE. Check there for
% the latest version.
% When using SMITE, please cite the following paper:
% Niehorster, D.C., & Nyström, M., (2019). SMITE: A toolbox for creating
% Psychtoolbox and Psychopy experiments with SMI eye trackers.
% doi: 10.3758/s13428-019-01226-0.
classdef SMITE < handle
properties (Access = protected, Hidden = true)
% dll and mex files
iView;
sampEvtBuffers;
% state
isInitialized = false;
usingFTGLTextRenderer;
keyState;
shiftKey;
mouseState;
needsCheckAveraging = false; % for systems that do not support setting averaging of eye data
isRecording = false;
% settings and external info
settings;
scrInfo;
% eye-tracker info
caps; % will be populated with info about capabilities of the connected eye-tracker
end
properties (SetAccess=private)
systemInfo;
geom;
calibrateHistory;
end
% computed properties (so not actual properties)
properties (Dependent, SetAccess = private)
rawSMI; % get naked iViewXAPI instance
rawBuffers; % get naked SMIbuffer instance
end
methods
function obj = SMITE(settingsOrETName)
% deal with inputs
if ischar(settingsOrETName)
% only eye-tracker name provided, load defaults for this
% tracker
obj.setOptions(obj.getDefaults(settingsOrETName));
else
obj.setOptions(settingsOrETName);
end
end
function delete(obj)
obj.deInit();
end
function out = setDummyMode(obj)
assert(nargout==1,'SMITE: you must use the output argument of setDummyMode, like: SMIhandle = SMIhandle.setDummyMode(), or SMIhandle = setDummyMode(SMIhandle)')
out = SMITEDummyMode(obj);
end
function out = get.rawSMI(obj)
out = obj.iView;
end
function out = get.rawBuffers(obj)
out = obj.sampEvtBuffers;
end
function out = getOptions(obj)
if ~obj.isInitialized
% return all settings
out = obj.settings;
else
% only the subset that can be changed "live"
opts = obj.getAllowedOptions();
for p=1:size(opts,1)
out.(opts{p,1}).(opts{p,2}) = obj.settings.(opts{p,1}).(opts{p,2});
end
end
end
function setOptions(obj,settings)
if obj.isInitialized
% only a subset of settings is allowed. Hardcode here, and
% copy over if exist. Ignore all others silently
allowed = obj.getAllowedOptions();
for p=1:size(allowed,1)
if isfield(settings,allowed{p,1}) && isfield(settings.(allowed{p,1}),allowed{p,2})
obj.settings.(allowed{p,1}).(allowed{p,2}) = settings.(allowed{p,1}).(allowed{p,2});
end
end
else
% get what fields there should be. Error if user added or
% removed
defaults = obj.getDefaults(settings.tracker);
expected = getStructFields(defaults);
input = getStructFields(settings);
qMissing = ~ismember(expected,input);
qAdded = ~ismember(input,expected);
if any(qMissing)
params = sprintf('\n settings.%s',expected{qMissing});
error('SMITE: For the %s tracker, the following settings are expected, but were not provided by you:%s\nAdd these to your settings input.',settings.tracker,params);
end
if any(qAdded)
params = sprintf('\n settings.%s',input{qAdded});
error('SMITE: For the %s tracker, the following settings are not expected, but were provided by you:%s\nRemove these from your settings input.',settings.tracker,params);
end
% input is fine, just copy it over
obj.settings = settings;
end
%%% process settings
% setup colors
obj.settings.cal.bgColor = color2RGBA(obj.settings.cal.bgColor);
obj.settings.cal.fixBackColor = color2RGBA(obj.settings.cal.fixBackColor);
obj.settings.cal.fixFrontColor = color2RGBA(obj.settings.cal.fixFrontColor);
obj.settings.setup.basicRefColor = color2RGBA(obj.settings.setup.basicRefColor);
obj.settings.setup.basicHeadEdgeColor = color2RGBA(obj.settings.setup.basicHeadEdgeColor);
obj.settings.setup.basicHeadFillColor = color2RGBA(obj.settings.setup.basicHeadFillColor);
obj.settings.setup.basicEyeColor = color2RGBA(obj.settings.setup.basicEyeColor);
obj.settings.setup.basicPupilColor = color2RGBA(obj.settings.setup.basicPupilColor);
obj.settings.setup.basicCrossClr = color2RGBA(obj.settings.setup.basicCrossClr);
obj.settings.setup.valAccuracyTextColor = color2RGBA(obj.settings.setup.valAccuracyTextColor);
end
function out = init(obj)
% get capabilities for the connected eye-tracker
obj.setCapabilities();
% Load in plugin (SMI dll)
obj.iView = iViewXAPI();
% Load in our callback buffer mex (tell it if online data has
% eyes swapped)
obj.sampEvtBuffers = SMIbuffer(obj.caps.mayNeedEyeFlip && obj.settings.doFlipEye);
% For reasons unclear to me, a brief wait here improved
% stability on some of the testing systems.
pause(0.1);
% Create logger file, if wanted
if obj.settings.logLevel
ret = obj.iView.setLogger(obj.settings.logLevel, obj.settings.logFileName);
obj.processError(ret,sprintf('SMITE: Logger at "%s" could not be opened',obj.settings.logFileName));
end
% Connect to server
obj.iView.disconnect(); % disconnect first, found this necessary as API otherwise apparently does not recognize it when eye tracker server crashed or closed by hand while connected. Well, calling 'iV_IsConnected' twice seems to work...
if obj.settings.start.removeTempDataFile && ~obj.isTwoComputerSetup()
% remove temp idf file on this computer (file or even
% folder may not exist, no worries because then no problem)
% NB: we don't support one computer setup for old RED
% officially, so i'm not deleting anything from that temp
% folder here (its also likely to contain a lot of
% different files instead of just the temp file for the
% current unfinished recording, so blanket deletion is
% perhaps unsafe)
[~,~]=system('del /F /S /Q /A "C:\ProgramData\SMI\iView X\temp\*.idf"'); % RED-m location
[~,~]=system('del /F /S /Q /A "C:\ProgramData\SMI\TempRemoteRecordings\*.idf"'); % RED NG location
end
ret = obj.iView.start(obj.settings.etApp); % returns 1 when starting app, 4 if its already running
qStarting = ret==1;
% connect
ret = obj.connect();
if qStarting && ret~=1
% in case eye tracker server is starting, give it some time
% before trying to connect, don't hammer it unnecessarily
obj.iView.setConnectionTimeout(1); % "timeout for how long iV_Connect tries to connect to iView eye tracking server." Try short, try often, so we don't wait unnecessarily long
count = 1;
while count < 30 && ret~=1
ret = obj.connect();
count = count+1;
end
end
switch ret
case 1
% connected, we're good. nothing to do here
case 104
error('SMITE: Could not establish connection. Check if Eye Tracker application is running (error 104: %s)',SMIErrCode2String(ret));
case 105
error('SMITE: Could not establish connection. Check the communication ports (error 105: %s)',SMIErrCode2String(ret));
case 123
error('SMITE: Could not establish connection. Another process is blocking the communication ports (error 123: %s)',SMIErrCode2String(ret));
case 201
error('SMITE: Could not establish connection. Check if Eye Tracker is installed and running (error 201: %s)',SMIErrCode2String(ret));
otherwise
obj.processError(ret,'SMITE: Could not establish connection');
end
% check this is the device the user specified
if obj.caps.deviceName
% if possible, use this interface as it is most precise
% (RED-m and RED250mobile are both 'REDm' in the return of
% getSystemInfo)
[~,trackerName] = obj.iView.getDeviceName;
assert(strcmp(trackerName(1:min(end,length(obj.settings.tracker))),obj.settings.tracker),'SMITE: Connected tracker is a "%s", not the "%s" you specified',trackerName,obj.settings.tracker)
else
% this is a old RED or a HiSpeed, check using ETDevice in
% getSystemInfo if it is the device specified by the user
[~,sysInfo] = obj.iView.getSystemInfo();
qErr = false;
switch obj.settings.tracker
case 'HiSpeed'
qErr = ~strcmp(sysInfo.iV_ETDevice,'HiSpeed');
case 'RED'
qErr = ~strcmp(sysInfo.iV_ETDevice,'RED');
end
assert(~qErr,'SMITE: Connected tracker is a "%s", not the "%s" you specified',sysInfo.iV_ETDevice,obj.settings.tracker)
end
% deal with device geometry
if obj.caps.setREDGeometry
% setup device geometry
ret = obj.iView.selectREDGeometry(obj.settings.setup.geomProfile);
obj.processError(ret,sprintf('SMITE: Error selecting geometry profile "%s"',obj.settings.setup.geomProfile));
end
if obj.caps.hasREDGeometry
% get info about the setup
[~,obj.geom] = obj.iView.getCurrentREDGeometry();
obj.geom.setupName = char(obj.geom.setupName(obj.geom.setupName~=0));
out.geom = obj.geom;
if strcmp(obj.settings.tracker,'RED')
% check correct geometry is set in iViewX (NB:
% technically, if iViewX is set to standalone mode,
% selectREDGeometry() would work to select the profile.
% but since that requires the user to set it up
% correctly manually anyway, we gain nothing by
% supporting that here).
assert(strcmpi(obj.geom.redGeometry,obj.settings.setup.geomMode),'SMITE: incorrect RED Operation Mode selected in iViewX. Got "%s", expected "%s"',obj.geom.redGeometry, obj.settings.setup.geomMode)
switch obj.geom.redGeometry
case 'monitorIntegrated'
assert(obj.geom.monitorSize==obj.settings.setup.monitorSize,'SMITE: incorrect monitor size selected in iViewX for monitorIntegrated RED Operation Mode. Got "%d", expected "%d"',obj.geom.monitorSize, obj.settings.setup.monitorSize)
case 'standalone'
assert(strcmpi(obj.geom.setupName,obj.settings.setup.geomProfile), 'SMITE: incorrect profile selected in iViewX for standalone RED Operation Mode. Got "%s", expected "%s"' ,obj.geom.setupName, obj.settings.setup.geomProfile)
assert(obj.geom.stimX ==obj.settings.setup.scrWidth, 'SMITE: incorrect screen width selected in iViewX for standalone profile "%s" in RED Operation Mode. Got "%d", expected "%d"',obj.geom.setupName, obj.geom.stimX , obj.settings.setup.scrWidth)
assert(obj.geom.stimY ==obj.settings.setup.scrHeight, 'SMITE: incorrect screen height selected in iViewX for standalone profile "%s" in RED Operation Mode. Got "%d", expected "%d"',obj.geom.setupName, obj.geom.stimY , obj.settings.setup.scrHeight)
assert(obj.geom.stimHeightOverFloor==obj.settings.setup.scrDistToFloor, 'SMITE: incorrect distance floor to screen selected in iViewX for standalone profile "%s" in RED Operation Mode. Got "%d", expected "%d"',obj.geom.setupName, obj.geom.stimHeightOverFloor, obj.settings.setup.scrDistToFloor)
assert(obj.geom.redHeightOverFloor ==obj.settings.setup.REDDistToFloor, 'SMITE: incorrect distance floor to RED selected in iViewX for standalone profile "%s" in RED Operation Mode. Got "%d", expected "%d"',obj.geom.setupName, obj.geom.redHeightOverFloor , obj.settings.setup.REDDistToFloor)
assert(obj.geom.redStimDist ==obj.settings.setup.REDDistToScreen, 'SMITE: incorrect distance RED to screen in iViewX for standalone profile "%s" in RED Operation Mode. Got "%d", expected "%d"',obj.geom.setupName, obj.geom.redStimDist , obj.settings.setup.REDDistToScreen)
assert(obj.geom.redInclAngle ==obj.settings.setup.REDInclAngle, 'SMITE: incorrect RED inclination angle selected in iViewX for standalone profile "%s" in RED Operation Mode. Got "%d", expected "%d"',obj.geom.setupName, obj.geom.redInclAngle , obj.settings.setup.REDInclAngle)
end
end
end
% if supported, set tracker to operate at requested tracking frequency
if obj.caps.setSpeedMode
% NB: I found this command to be unstable at best, so i'm
% not checking the return value. Below we're checking if
% we're at the right tracking frequency anyway
ret = obj.iView.setSpeedMode(obj.settings.freq);
obj.processError(ret,sprintf('SMITE: Error setting tracker sampling frequency to "%d"',obj.settings.freq));
end
% get info about the system
[~,obj.systemInfo] = obj.iView.getSystemInfo();
if obj.caps.serialNumber
[~,obj.systemInfo.Serial] = obj.iView.getSerialNumber();
end
out.systemInfo = obj.systemInfo;
% check tracker is operating at requested tracking frequency
assert(obj.systemInfo.samplerate == obj.settings.freq,'SMITE: Tracker not running at requested sampling rate (%d Hz), but at %d Hz',obj.settings.freq,obj.systemInfo.samplerate);
% setup track mode
if obj.caps.setTrackingMode
ret = obj.iView.setTrackingParameter(['ET_PARAM_' obj.settings.trackEye], ['ET_PARAM_' obj.settings.trackMode], 1);
obj.processError(ret,'SMITE: Error selecting tracking mode');
elseif isfield(obj.settings,'trackEye')
% get sample to check if recording monocular (and if so
% which eye) or binocular
a = obj.getSample();
qHaveLeft = a.leftEye .gazeX ~= -1;
qHaveRight = a.rightEye.gazeX ~= -1;
if qHaveLeft && qHaveRight
eye = 'both eyes';
elseif qHaveLeft
eye = 'only the left eye';
elseif qHaveRight
eye = 'only the right eye';
end
switch obj.settings.trackEye
case 'EYE_BOTH'
assert( qHaveLeft && qHaveRight,'SMITE: you requested recording from both eyes, but data from %s is available. Change eye-tracker settings in iView, or settings.trackEye',eye);
case 'EYE_LEFT'
assert( qHaveLeft && ~qHaveRight,'SMITE: you requested recording from the left eye, but data from %s is available. Change eye-tracker settings in iView, or settings.trackEye',eye);
case 'EYE_RIGHT'
assert(~qHaveLeft && qHaveRight,'SMITE: you requested recording from the right eye, but data from %s is available. Change eye-tracker settings in iView, or settings.trackEye',eye);
otherwise
error('settings.trackEye ''%s'' not understood, possible values: ''EYE_BOTH'', ''EYE_LEFT'', or ''EYE_RIGHT''', obj.settings.trackEye);
end
end
% switch off averaging filter so we get separate data for each eye
if isfield(obj.settings,'doAverageEyes')
if obj.caps.configureFilter
ret = obj.iView.configureFilter('Average', 'Set', int32(obj.settings.doAverageEyes));
obj.processError(ret,'SMITE: Error configuring averaging filter');
else
obj.needsCheckAveraging = true;
end
end
% prevents CPU from entering power saving mode according to
% docs
if obj.caps.enableHighPerfMode
obj.iView.enableProcessorHighPerformanceMode();
end
% mark as inited
obj.isInitialized = true;
end
function out = calibrate(obj,wpnt,qClearIDFfileBuffer)
% this function does all setup, draws the interface, etc
% this and the functions called by this function are the only
% part of this toolbox that depend on PsychToolbox
% by default don't clear recording buffer. You DO NOT want to do
% that when recalibrating, e.g. in the middle of the trial, or at
% second attempt
if nargin<2
qClearIDFfileBuffer = false;
end
%%% 1: set up calibration
% get info about screen
obj.scrInfo.resolution = Screen('Rect',wpnt); obj.scrInfo.resolution(1:2) = [];
obj.scrInfo.center = obj.scrInfo.resolution/2;
[osf,odf,ocm] = Screen('BlendFunction', wpnt, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
% see what text renderer to use
obj.usingFTGLTextRenderer = ~~exist('libptbdrawtext_ftgl64.dll','file'); % check if we're on a Windows platform with the high quality text renderer present (was never supported for 32bit PTB, so check only for 64bit)
if ~obj.usingFTGLTextRenderer
assert(isfield(obj.settings.text,'lineCentOff'),'SMITE: PTB''s TextRenderer changed between calls to getDefaults and the SMITE constructor. If you force the legacy text renderer by calling ''''Screen(''Preference'', ''TextRenderer'',0)'''' (not recommended) make sure you do so before you call SMITE.getDefaults(), as it has different settings than the recommended TextRenderer number 1')
end
% init key, mouse state
[~,~,obj.keyState] = KbCheck();
obj.shiftKey = KbName('shift');
[~,~,obj.mouseState] = GetMouse();
% to be safe, disable SMI calibration keys when possible
% NB: manual says only for NG trackers, but seems to help
% implementation act correctly on the RED-m as well...
obj.iView.setUseCalibrationKeys(0);
% set background color
Screen('FillRect', wpnt, obj.settings.cal.bgColor); % NB: fullscreen fillrect sets new clear color in PTB
% SMI calibration setup
CalibrationData = SMIStructEnum.Calibration;
assert(ismember(obj.settings.cal.nPoint,obj.caps.nCalibrationPoints),'SMITE: You asked for %d calibration points, but the ''%s'' tracker only supports %sor %d calibration points',obj.settings.cal.nPoint,obj.settings.tracker,sprintf('%d, ',obj.caps.nCalibrationPoints(1:end-1)),obj.caps.nCalibrationPoints(end));
CalibrationData.method = obj.settings.cal.nPoint;
CalibrationData.autoAccept = int32(obj.settings.cal.autoPace);
CalibrationData.displayDevice = max(0,Screen('WindowScreenNumber', wpnt)-1);
% Setup calibration look. Necessary in all cases so that
% validate image looks similar to calibration stimuli
CalibrationData.foregroundBrightness = obj.settings.cal.fixBackColor(1);
CalibrationData.backgroundBrightness = obj.settings.cal.bgColor(1);
CalibrationData.targetSize = max(10,round(obj.settings.cal.fixBackSize/2)); % 10 is the minimum size. Ignored for validation image...
ret = obj.iView.setupCalibration(CalibrationData);
obj.processError(ret,'SMITE: Error setting up calibration');
% reset calibration points in case someone else changed them
% previously
obj.iView.resetCalibrationPoints();
% get where the calibration points are
pCalibrationPoint = SMIStructEnum.CalibrationPoint;
out.calibrationPoints = struct('X',zeros(1,obj.settings.cal.nPoint),'Y',zeros(1,obj.settings.cal.nPoint));
for p=1:obj.settings.cal.nPoint
obj.iView.getCalibrationPoint(p, pCalibrationPoint);
out.calibrationPoints.X(p) = pCalibrationPoint.positionX;
out.calibrationPoints.Y(p) = pCalibrationPoint.positionY;
end
% if requested by user, place the calibration points elsewhere
if ~isempty(obj.settings.cal.rangeX) || ~isempty(obj.settings.cal.rangeY)
if isempty(obj.settings.cal.rangeX)
obj.settings.cal.rangeX = obj.scrInfo.resolution(1);
end
if isempty(obj.settings.cal.rangeY)
obj.settings.cal.rangeY = obj.scrInfo.resolution(2);
end
% center and normalize calibration points, so we can scale
% and move them
scrMid = obj.scrInfo.resolution/2;
pointsX = (out.calibrationPoints.X-scrMid(1))./obj.scrInfo.resolution(1);
pointsY = (out.calibrationPoints.Y-scrMid(2))./obj.scrInfo.resolution(2);
% now rescale and offset
pointsX = round(pointsX.*obj.settings.cal.rangeX + scrMid(1) + obj.settings.cal.offsetX);
pointsY = round(pointsY.*obj.settings.cal.rangeY + scrMid(2) + obj.settings.cal.offsetY);
% check we do not end up off screen
if any(pointsX<0 | pointsX>obj.scrInfo.resolution(1))
warning('SMITE: setup in settings.cal.rangeX and settings.cal.offsetX leads to some of the calibration points being placed offscreen')
end
if any(pointsY<0 | pointsY>obj.scrInfo.resolution(2))
warning('SMITE: setup in settings.cal.rangeY and settings.cal.offsetY leads to some of the calibration points being placed offscreen')
end
% apply
for p=1:obj.settings.cal.nPoint
ret = obj.iView.changeCalibrationPoint(p, pointsX(p) , pointsY(p));
obj.processError(ret,sprintf('SMITE: Error setting calibration point %d to (%d,%d)',p, pointsX(p) , pointsY(p)));
end
% store to output
out.calibrationPoints.X = pointsX;
out.calibrationPoints.Y = pointsY;
end
%%% 2: enter the screens, from setup to validation results
kCal = 0;
% The below is a big loop that will run possibly multiple
% calibration until exiting because skipped or a calibration is
% selected by user.
% there are three start modes:
% 0. skip head positioning, go straight to calibration
% 1. start with simple head positioning interface
% 2. start with advanced head positioning interface
startScreen = obj.settings.setup.startScreen;
while true
qGoToValidationViewer = false;
kCal = kCal+1;
if startScreen>0
%%% 2a: show head positioning screen
status = obj.showHeadPositioning(wpnt,out,startScreen);
switch status
case 1
% all good, continue
case 2
% skip setup
break;
case -3
% go to validation viewer screen
qGoToValidationViewer = true;
case -4
% full stop
error('SMITE: run ended from SMI calibration routine')
otherwise
error('SMITE: status %d not implemented',status);
end
end
%%% 2b: calibrate and validate
if ~qGoToValidationViewer
[out.attempt{kCal}.calStatus,temp] = obj.DoCalAndVal(wpnt,qClearIDFfileBuffer,kCal);
warning('off','catstruct:DuplicatesFound') % field already exists but is empty, will be overwritten with the output from the function here
out.attempt{kCal} = catstruct(out.attempt{kCal},temp);
% qClearbuffer should now become false even if it was true,
% as buffer has been cleared in calibration lines above
qClearIDFfileBuffer = false;
% check returned action state
switch out.attempt{kCal}.calStatus
case 1
% all good, continue
case 2
% skip setup
break;
case -1
% restart calibration
startScreen = 0;
continue;
case -2
% go to setup
startScreen = max(1,startScreen);
continue;
case -4
% full stop
error('SMITE: run ended from SMI calibration routine')
otherwise
error('SMITE: status %d not implemented',out.attempt{kCal}.calStatus);
end
% check calibration status to be sure we're calibrated
[~,out.attempt{kCal}.calStatusSMI] = obj.iView.getCalibrationStatus();
if ~strcmp(out.attempt{kCal}.calStatusSMI,'calibrationValid')
% retry calibration
startScreen = max(1,startScreen);
continue;
end
% store calibration so user can select which one they want
obj.iView.saveCalibration(num2str(kCal));
end
%%% 2c: show calibration results
% get info about accuracy of calibration
[~,out.attempt{kCal}.validateAccuracy] = obj.iView.getAccuracy([], 0);
% dump validation accuracy info to idf file
obj.startRecording();
valMsg = sprintf('VALIDATION %d quality: LX %.3f, LY %.3f, RX %.3f, RY %.3f',kCal,out.attempt{kCal}.validateAccuracy.deviationLX,out.attempt{kCal}.validateAccuracy.deviationLY,out.attempt{kCal}.validateAccuracy.deviationRX,out.attempt{kCal}.validateAccuracy.deviationRY);
fprintf('%s\n',valMsg);
obj.sendMessage(valMsg);
obj.stopRecording();
% get validation image
[~,out.attempt{kCal}.validateImage] = obj.iView.getAccuracyImage();
% show validation result and ask to continue
[out.attempt{kCal}.valResultAccept,out.attempt{kCal}.calSelection] = obj.showValidationResult(wpnt,out.attempt,kCal);
switch out.attempt{kCal}.valResultAccept
case 1
% all good, we're done
break;
case 2
% skip setup
break;
case -1
% restart calibration
startScreen = 0;
continue;
case -2
% go to setup
startScreen = max(1,startScreen);
continue;
case -4
% full stop
error('SMITE: run ended from SMI calibration routine')
otherwise
error('SMITE: status %d not implemented',out.attempt{kCal}.valResultAccept);
end
end
% clean up
Screen('Flip',wpnt);
Screen('BlendFunction', wpnt, osf,odf,ocm);
% log to idf file which calibration was selected
if isfield(out,'attempt') && isfield(out.attempt{kCal},'calSelection')
obj.startRecording();
obj.sendMessage(sprintf('Selected calibration %d',out.attempt{kCal}.calSelection));
obj.stopRecording();
end
% store calibration info in calibration history, for later
% retrieval if wanted
if isempty(obj.calibrateHistory)
obj.calibrateHistory{1} = out;
else
obj.calibrateHistory{end+1} = out;
end
end
function startRecording(obj,qClearIDFfileBuffer)
% by default do not clear recording buffer. For SMI, by the time
% user calls startRecording, we already have data recorded during
% calibration and validation in the buffer
if nargin<2 || isempty(qClearIDFfileBuffer)
qClearIDFfileBuffer = false;
end
obj.iView.stopRecording(); % make sure we're not already recording when we startRecording(), or we get an error. Ignore error return code here
if qClearIDFfileBuffer
obj.iView.clearRecordingBuffer();
end
ret = obj.iView.startRecording();
obj.processError(ret,'SMITE: Error starting recording');
obj.isRecording = true;
end
function startBuffer(obj,varargin)
ret = obj.sampEvtBuffers.startSampleBuffering(varargin{:});
obj.processError(ret,'SMITE: Error starting sample buffer');
end
function data = consumeBufferData(obj,varargin)
% optional input argument firstN: how many samples to consume
% from start. Default: all
data = obj.sampEvtBuffers.consumeSamples(varargin{:});
end
function data = peekBufferData(obj,varargin)
% optional input argument lastN: how many samples to peek from
% end. Default: 1. To get all, ask for -1 samples
data = obj.sampEvtBuffers.peekSamples(varargin{:});
end
function sample = getLatestSample(obj)
% returns empty when sample not gotten successfully
[sample,ret] = obj.getSample();
if ret~=1
sample = [];
end
end
function stopBuffer(obj,doClearBuffer)
if nargin<2 || isempty(doClearBuffer)
doClearBuffer = false;
end
obj.sampEvtBuffers.stopSampleBuffering(doClearBuffer);
end
function stopRecording(obj)
if obj.isRecording
ret = obj.iView.stopRecording();
obj.processError(ret,'SMITE: Error stopping recording');
obj.isRecording = false;
end
end
function out = isConnected(obj)
out = obj.iView.isConnected();
end
function sendMessage(obj,str)
% using
% calllib('obj.iViewXAPI','iV_SendImageMessage','msg_string')
% directly here to save overhead (not sure if this overhead is
% significant, but better be safe than sorry)
% consider using that directly in your code for best timing
% ret = obj.iView.sendImageMessage(str);
if ~obj.isRecording
% messages are only stored when in recording mode, so no
% need to pass them on here when not recording. On some
% systems (e.g. RED250mobile) sending messages when not
% recording is an error, so this check is important
warning('SMITE::sendMessage: you attempted to send a message to file while not in recording mode. This will not work: your message would either silently be dropped or cause an error depending on the eye tracker model')
return;
end
ret = calllib('iViewXAPI','iV_SendImageMessage',str);
obj.processError(ret,'SMITE: Error sending message to data file');
if obj.settings.debugMode
fprintf('%s\n',str);
end
end
function setBegazeTrialImage(obj,filename)
[path,~,ext] = fileparts(filename);
% 1. there must not be a path
assert(isempty(path),'SMITE: SMI BeGaze trial image/video must not contain a path to be usable by BeGaze')
% 2. check extention is one of the supported ones
assert(ismember(ext,{'.png','.jpg','.jpeg','.bmp','.avi'}),'SMITE: SMI BeGaze trial image/video must have one of the following extensions: .png, .jpg, .jpeg, .bmp or .avi')
% ok, send
obj.sendMessage(filename);
end
function setBegazeKeyPress(obj,string)
% can use this to send any string into BeGaze event stream (do
% not know length limit). I advise to keep this short
% special format to achieve this
string = sprintf('UE-keypress %s',string);
% ok, send
obj.sendMessage(string);
end
function setBegazeMouseClick(obj,which,x,y)
assert(ismember(which,{'left','right'}),'SMITE: SMI BeGaze mouse press must be for ''left'' or ''right'' mouse button')
% special format to achieve this
string = sprintf('UE-mouseclick %s x=%d y=%d',which,x,y);
% ok, send
obj.sendMessage(string);
end
function startEyeImageRecording(obj,filename, format, duration)
% NB: does NOT work on NG eye-trackers (RED250mobile, RED-n)
% if using two computer setup, save location is on remote
% computer, if not a full path is given, it is relative to
% iView install directory on that computer. If single computer
% setup, relative paths are relative to the current working
% directory when this function is called
% duration is in ms. If provided, images for the recording
% duration are buffered and written to disk afterwards, so no
% images will be lost. If empty, images are recorded directly
% to disk (and lost if disk can't keep up).
% get filename and path
[path,file,~] = fileparts(filename);
if isempty(regexp(path,'^\w:', 'once')) && ~obj.isTwoComputerSetup()
% single computer setup and no drive letter in provided
% path. Interpret path as relative to cd
path = fullfile(cd,path);
end
% check format
if ischar(format)
format = find(strcmpi(format,{'jpg','bmp','xvid','huffyuv','alpary','xmp4'}));
assert(~isempty(format),'SMITE: if eyeimage format provided as string, should be one of ''jpg'',''bmp'',''xvid'',''huffyuv'',''alpary'',''xmp4''');
format = format-1;
end
assert(isnumeric(format) && format>=0 && format<=5,'SMITE eyeimage format should be between 0 and 5 (inclusive)')
% send command
if isempty(duration)
obj.rawSMI.sendCommand(sprintf('ET_EVB %d "%s" "%s"\n',format,file,path));
else
obj.rawSMI.sendCommand(sprintf('ET_EVB %d "%s" "%s" %d\n',format,file,path,duration));
end
end
function stopEyeImageRecording(obj)
% if no duration specified when calling recordEyeImages, call
% this function to stop eye image recording
obj.rawSMI.sendCommand('ET_EVE\n');
end
function saveData(obj,filename, user, description, doAppendVersion)
% 1. get filename and path
[path,file,ext] = fileparts(filename);
assert(~isempty(path),'SMITE: saveData: filename should contain a path (consider using ''fullfile(cd,%s)'')',filename);
% eat .idf off filename, preserve any other extension user may
% have provided
if ~isempty(ext) && ~strcmpi(ext,'.idf')
file = [file ext];
end
% add versioning info to file name, if wanted and if already
% exists
if nargin>=5 && doAppendVersion
% see what files we have in data folder with the same name
f = dir(path);
f = f(~[f.isdir]);
f = regexp({f.name},['^' regexptranslate('escape',file) '(_\d+)?\.idf$'],'tokens');
% see if any. if so, see what number to append
f = [f{:}];
if ~isempty(f)
% files with this subject name exist
f=cellfun(@(x) sscanf(x,'_%d'),[f{:}],'uni',false);
f=sort([f{:}]);
if isempty(f)
file = [file '_1'];
else
file = [file '_' num2str(max(f)+1)];
end
end
end
% now make sure file ends with .idf
file = [file '.idf'];
% set defaults
if nargin<3 || isempty(user)
user = file;
end
if nargin<4 || isempty(description)
description = '';
end
% construct full filename
filename = fullfile(path,file);
if obj.isTwoComputerSetup() && obj.settings.save.allowFileTransfer
% Two computer setup: file gets saved on eye-tracker
% computer (do so with without path info and allowing
% overwrite). Transfer the file using the
% FileTransferServer running on the remote machine. NB:
% this seems to only work when iView is running on the
% remote machine.
% 1: connect to file transfer server
% 1a: request FileTransferServer.exe's version (always
% happens when experiment center is just started)
con = pnet('tcpconnect',obj.settings.connectInfo{1},9050);
pnet(con,'setreadtimeout',0.1);
pnet(con,'write',uint8(4));
data = '';
while isempty(data)
data = pnet(con,'read',2^20,'uint8');
end
fprintf('FileTransferServer.exe version: %s\n',char(data(6:end))); % first 5 bytes are a response header
pnet(con,'close'); % copy exact order of events, perhaps important
% 1b: ask what the data folder is
con = pnet('tcpconnect',obj.settings.connectInfo{1},9050);
pnet(con,'setreadtimeout',0.1);
pnet(con,'write',uint8(0));
allDat = '';
tries = 0;
while tries<5
data = pnet(con,'read',2^20,'uint8');
if isempty(data)
tries = tries+1;
end
allDat = [allDat data]; %#ok<AGROW>
end
remotePath = allDat(6:end); % skip first 5 bits, they are a response header
% 2: now save file on remote computer with path indicated
% by remote computer. Overwrite if exists
remoteFile = fullfile(remotePath,[file(1:3) '-eye_data.idf']); % nearly hardcode remote file name. Only very specific file names are transferred by the remote endpoint
ret = obj.iView.saveData(remoteFile, description, user, 1); % 1: always overwrite existing file with same name on the remote computer
obj.processError(ret,'SMITE: Error saving data');
fprintf('file stored on the remote (eye-tracker) computer as ''%s''\n',remoteFile);
% now that data is savely stored remotely, check that we
% would not be overwriting a file locally
assert(~exist(filename,'file'),'SMITE: error saving data because local file already exists. File stored on the remote (eye-tracker) computer as ''%s''\n',remoteFile);
% 3a: now request remote file to be transferred
pnet(con,'write', [uint8([1 50 0 0 0]) uint8(remoteFile)]);
% 3b: receive file: read from socket until exhausted
allDat = '';
tries = 0;
pnet(con,'setreadtimeout',0.5);
while tries<10
data = pnet(con,'read',2^20,'uint8');
if isempty(data)
tries = tries+1;
else
tries = 0;
end
allDat = [allDat data]; %#ok<AGROW>
end
pnet(con,'close');
% 4: now save file locally (we already checked above that
% the file does not exist, so overwriting should not happen
% here)
assert(~isempty(allDat),'SMITE: remote file could not be received. File stored on the remote (eye-tracker) computer as ''%s''\n',remoteFile);
fid=fopen(filename,'w');
fwrite(fid,allDat(6:end)); % skip first 5 bits, they are a response header
fclose(fid);
else
ret = obj.iView.saveData(filename, description, user, 0); % 0: never overwrite existing file with same name
obj.processError(ret,'SMITE: Error saving data');
end
end
function out = deInit(obj,qQuit)
if isempty(obj.iView)
% init was never called, nothing to do here
return;
end
obj.iView.disconnect();
% also, read log, return contents as output and delete
fid = fopen(obj.settings.logFileName, 'r');
if fid~=-1
out = fread(fid, inf, '*char').';
fclose(fid);
else
out = '';
end
% somehow, matlab maintains a handle to the log file, even after
% fclose all and unloading the SMI library. Somehow a dangling
% handle from smi, would be my guess (note that calling iV_Quit did
% not fix it).
% delete(smiSetup.logFileName);
if nargin>1 && qQuit
obj.iView.quit();
end
% mark as deinited
obj.isInitialized = false;
obj.isRecording = false;
end
end
% helpers
methods (Static)
function settings = getDefaults(tracker)
settings.tracker = tracker;
% which app to iV_Start()
switch tracker
case {'HiSpeed','RED'}
settings.etApp = 'iViewX';
case 'RED-m'
settings.etApp = 'iViewXOEM';
case {'RED250mobile','REDn Scientific','REDn Professional'}
settings.etApp = 'iViewNG';
otherwise
error('SMITE: tracker "%s" not known/supported.\nSupported are: HiSpeed, RED500, RED250, RED120, RED60, RED-m, RED250mobile, REDn.\nNB: correct capitalization in the name is important.',tracker);
end
% connection info
switch tracker
case {'RED-m','RED250mobile','REDn Scientific','REDn Professional'}
% likely one-computer setup, connectLocal() should
% work, so default is:
settings.connectInfo = {};
% NB: for RED NG trackers, it is also supported to
% supply only the remote endpoint, like:
% settings.connectInfo = {'ipETComputer',4444};
case {'HiSpeed','RED'}
% template IPs, default ports
settings.connectInfo = {'ipETComputer',4444,'ipThis',5555};
end
% default tracking settings per eye-tracker
% settings (only provided if supported):
% - trackEye: 'EYE_LEFT', 'EYE_RIGHT', or
% 'EYE_BOTH'
% - trackMode: 'MONOCULAR', 'BINOCULAR',
% 'SMARTBINOCULAR', or
% 'SMARTTRACKING'
% - doAverageEyes true/false.
% - freq: eye-tracker dependent. Only for NG
% trackers can it actually be set
% - cal.nPoint: 0, 1, 2, 5, 9 or 13 calibration
% points are possible (0 is not
% implemented in SMITE)
switch tracker
case 'HiSpeed'
settings.trackEye = 'EYE_LEFT';
settings.cal.nPoint = 5;
settings.doAverageEyes = false;
settings.setup.eyeImageSize = [160 640]; % 160x224 for monocular at 1250 and 500
settings.freq = 1250;
case 'RED'
settings.cal.nPoint = 5;
settings.doAverageEyes = false;
settings.setup.headBox = [40 20]; % at 70 cm. Doesn't matter what distance, is just for getting aspect ratio
settings.setup.eyeImageSize = [160 496]; % NB: at 500Hz, its [80 344]
settings.freq = 250;
settings.doFlipEye = false;
case 'RED-m'
settings.trackEye = 'EYE_BOTH';
settings.trackMode = 'SMARTBINOCULAR';
settings.freq = 120;
settings.cal.nPoint = 5;
settings.doAverageEyes = true;
settings.setup.headBox = [31 21]; % at 60 cm. Doesn't matter what distance, is just for getting aspect ratio
settings.setup.eyeImageSize = [220 496];
case 'RED250mobile'
settings.trackEye = 'EYE_BOTH';
settings.trackMode = 'SMARTBINOCULAR';
settings.freq = 250;
settings.cal.nPoint = 5;
settings.doAverageEyes = true;
settings.setup.headBox = [32 21]; % at 60 cm. Doesn't matter what distance, is just for getting aspect ratio
settings.setup.eyeImageSize = [160 496];
case {'REDn Scientific','REDn Professional'}
settings.trackEye = 'EYE_BOTH';
settings.trackMode = 'SMARTBINOCULAR';
settings.freq = 60;
settings.cal.nPoint = 5;
settings.doAverageEyes = true;
settings.setup.headBox = [50 30]; % at 65 cm. Doesn't matter what distance, is just for getting aspect ratio
settings.setup.eyeImageSize = [240 300];
end
% some settings only for remotes
switch tracker
case 'RED'
settings.setup.viewingDist = 65;
settings.setup.geomMode = 'monitorIntegrated'; % monitorIntegrated or standalone
% only when in monitorIntegrated mode:
settings.setup.monitorSize = 22;
% only when in standalone mode:
settings.setup.geomProfile = 'profileName';
settings.setup.scrWidth = 0;
settings.setup.scrHeight = 0;
settings.setup.scrDistToFloor = 0;
settings.setup.REDDistToFloor = 0;
settings.setup.REDDistToScreen = 0;
settings.setup.REDInclAngle = 0;
case 'RED-m'
settings.setup.viewingDist = 65;
settings.setup.geomProfile = 'Desktop 22in Monitor';
case 'RED250mobile'
settings.setup.viewingDist = 65;
settings.setup.geomProfile = 'Default Profile';
case {'REDn Scientific','REDn Professional'}
settings.setup.viewingDist = 65;
settings.setup.geomProfile = 'Default Profile'; % TODO, is it the correct name?
end
% the rest here are general defaults. Many are hard to set...
settings.start.removeTempDataFile = true; % when calling iV_Start, iView always complains with a popup if there is some unsaved recorded data in iView's temp location. The popup can really mess with visual timing of PTB, so its best to remove it. Not relevant for a two computer setup
settings.save.allowFileTransfer = true; % if true, will attempt transfer of idf file to experiment computer when on two computer setup. if false, will just save on host computer
settings.setup.startScreen = 1; % 0: skip head positioning, go straight to calibration; 1: start with simple head positioning interface; 2: start with advanced head positioning interface
settings.setup.basicRefColor = [0 0 255]; % basic head position visualization: color of reference circle
settings.setup.basicHeadEdgeColor = [255 255 0]; % basic head position visualization: color of egde of disk representing head
settings.setup.basicHeadFillColor = [255 255 0]; % basic head position visualization: color of fill of disk representing head
settings.setup.basicHeadFillOpacity = .3; % basic head position visualization: opacity of disk representing head
settings.setup.basicShowYaw = false; % basic head position visualization: show yaw of head?
settings.setup.basicShowEyes = true; % basic head position visualization: show eyes?
settings.setup.basicEyeColor = [255 255 255]; % basic head position visualization: color of eyes in head
settings.setup.basicShowPupils = true; % basic head position visualization: show pupils?
settings.setup.basicPupilColor = [0 0 0]; % basic head position visualization: color of pupils in eye
settings.setup.basicCrossClr = [255 0 0]; % basic head position visualization: color of cross in head denoting untracked eye
settings.setup.valAccuracyTextColor = [0 0 0]; % color of text displaying accuracy number on validation feedback screen
settings.cal.autoPace = 1; % 0: manually confirm each calibration point. 1: only manually confirm the first point, the rest will be autoaccepted. 2: all calibration points will be auto-accepted
settings.cal.bgColor = 127;
settings.cal.fixBackSize = 20;
settings.cal.fixFrontSize = 5;
settings.cal.fixBackColor = 0;
settings.cal.fixFrontColor = 255;
settings.cal.drawFunction = [];
settings.cal.rangeX = []; % horizontal extent of calibration area, defaults to whole screen (when empty)
settings.cal.rangeY = []; % vertical extent of calibration area, defaults to whole screen (when empty)
settings.cal.offsetX = 0; % location of left of calibration area in pixels, defaults to calibration area that is centered on the screen (0). negative is leftward, positive rightward offset
settings.cal.offsetY = 0; % location of top of calibration area in pixels, defaults to calibration area that is centered on the screen (0). negative is upward, positive downward offset
settings.logFileName = 'iView_log.txt';
settings.text.font = 'Consolas';
settings.text.style = 0; % can OR together, 0=normal,1=bold,2=italic,4=underline,8=outline,32=condense,64=extend.
settings.text.wrapAt = 62;
settings.text.vSpacing = 1;
if ~exist('libptbdrawtext_ftgl64.dll','file') % if old text renderer, we have different defaults and an extra settings
settings.text.size = 20;
settings.text.lineCentOff = 3; % amount (pixels) to move single line text down so that it is visually centered on requested coordinate
else
settings.text.size = 24;
end
settings.string.simplePositionInstruction = 'Position yourself such that the two circles overlap.\nDistance: %.0f cm';
settings.debugMode = false; % for use together with PTB's PsychDebugWindowConfiguration. e.g. does not hide cursor
% SDK log Level: