Skip to content
dotsX_JQK_MAT_170627.m 25.3 KiB
Newer Older
Julian Kosciessa's avatar
Julian Kosciessa committed
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
%_______________________________________________________________________
%
% core function for drawing random dots motion on presentation screen
%_______________________________________________________________________
%
function [frames,dotInfo, ExperimentProtocol,ResultMat,DisplayInfo] = dotsX_JQK_MAT_170627(screenInfo,dotInfo,targets,indTrial,ExperimentProtocol,ResultMat,DisplayInfo)
% DOTSX display dots or targets on screen
%
% [frames,rseed,start_time,end_time,response,response_time] = dotsX(screenInfo,dotInfo,targets)
%
% For information on minimum fields of screenInfo and dotInfo arguments, see
% also openExperiment and createDotInfo. The input argument - "targets" is not
% necessary unless showing targets with the dots. Since rex only likes integers, 
% almost everything is in visual degrees * 10.
%
%   dotInfo.numDotField     number of dot patches that will be shown on screen
%   dotInfo.coh             vertical vectors, dots coherence (0...999) for each 
%                           dot patch
%   dotInfo.speed           vertical vectors, dots speed (10th deg/sec) for each 
%                           dot patch
%   dotInfo.dir             vertical vectors, dots direction (degrees) for each 
%                           dot patch
%   dotInfo.dotSize         size of dots in pixels, same for all patches
%   dotInfo.movingDotColor  color of dots in RGB for moving dots, same for all patches
%   dotInfo.randomDotColor  color of dots in RGB for random dots, same for all patches
%   dotInfo.maxDotsPerFrame determined by testing video card
%   dotInfo.apXYD           x, y coordinates, and diameter of aperture(s) in 
%                           visual degrees          
%   dotInfo.maxDotTime      optional to set maximum duration (sec). If not provided, 
%                           dot presentation is terminated only by user response
%   dotInfo.trialtype       1 fixed duration, 2 reaction time
%   dotInfo.keys            a set of keyboard buttons that can terminate the 
%                           presentation of dots (optional)
%   dotInfo.mouse           a set of mouse buttons that can terminate the 
%                           presentation of dots (optional)
%
%   screenInfo.curWindow    window pointer on which to plot dots
%   screenInfo.center       center of the screen in pixels
%   screenInfo.ppd          pixels per visual degree
%   screenInfo.monRefresh   monitor refresh value
%   screenInfo.dontclear    If set to 1, flip will not clear the framebuffer 
%                           after Flip - this allows incremental drawing of 
%                           stimuli. Needs to be zero for dots to be erased.
%   screenInfo.rseed        random # seed, can be empty set[] 
%
%   targets.rects           dimensions for drawOval
%   targets.colors          color of targets
%   targets.show            optional, if only showing certain targets but don't
%                           want to change targets structure (index number of 
%                           targets) to be shown during dots

% DisplayInfo       contains info on which conjunction of dots was
%                   presented where

%
% Algorithm:
%   All calculations take place within a square aperture in which the dots are 
% shown. The dots are constructed in 3 sets that are plotted in sequence.  For 
% each set, the probability that a dot is replotted in motion -- as opposed to 
% randomly replaced -- is given by the dotInfo.coh value. This routine generates 
% a set of dots as an (ndots,2) matrix of locations, and then plots them.  In 
% plotting the next set of dots (e.g., set 2), it prepends the preceding set 
% (e.g., set 1).
%

% created by MKMK July 2006, based on ShadlenDots by MNS, JIG and others
% adapted by JQK 2017

% Structures are not altered in this function, so should not have memory
% problems from matlab creating new structures.

% CURRENTLY THERE IS AN ALMOST ONE SECOND DELAY FROM THE TIME DOTSX IS
% CALLED UNTIL THE DOTS START ON THE SCREEN! THIS IS BECAUSE OF PRIORITY.
% NEED TO EVALUATE WHETHER PRIORITY IS REALLY NECESSARY.

if nargin < 3
    targets = [];
    showtar = [];
else
    if isfield(targets,'show')
        showtar = targets.show;
    else
        showtar = 1:size(targets.rects,1);
    end
end

curWindow = screenInfo.curWindow;
white = [255 255 255];

%% other initializiation

if isfield(dotInfo,'movingDotColor')
  movingDotColor = dotInfo.movingDotColor;
else
  movingDotColor = white;
end

if isfield(dotInfo,'randomDotColor')
  randomDotColor = dotInfo.randomDotColor;
else
  randomDotColor = white;
end

% set new random seed at each iteration and retain seed
rng(sum(100*clock), 'twister');
[dotInfo.curSeed{indTrial}] = rng;

% Query the frame duration
ifi = Screen('GetFlipInterval', curWindow);

% In order to find out if using keypress or mouse, all trials should have spacekey
% for abort, unless its a demo. Spacekey means end experiment after this trial - 
% sends abort message to experiment.

keys = [];
abort = [];
if isfield(dotInfo, 'keyLeft')
    keys = [dotInfo.keyLeft dotInfo.keyRight];
elseif isfield(dotInfo, 'keySpace')
    abort = nan;
end

if isfield(targets,'select')
    h = targets.select(:,1);
    k = targets.select(:,2);
    r = targets.select(:,3);
end

% Create the aperture square
%apRect = floor(createTRect(dotInfo.apXYD, screenInfo));

apD = dotInfo.apXYD(:,3); % diameter of aperture
center = repmat(screenInfo.center,size(dotInfo.apXYD(:,1)));

% Change x,y coordinates to pixels (y is inverted - pos on bottom, neg. on top)
center = [center(:,1) + dotInfo.apXYD(:,1)/10*screenInfo.ppd center(:,2) - ...
    dotInfo.apXYD(:,2)/10*screenInfo.ppd]; % where you want the center of the aperture
center(:,3) = dotInfo.apXYD(:,3)/2/10*screenInfo.ppd; % add diameter
d_ppd = floor(apD/10 * screenInfo.ppd);	% size of aperture in pixels
dotSize = dotInfo.dotSize; % probably better to leave this in pixels, but not sure

% ndots is the number of dots shown per video frame. Dots will be placed in a 
% square of the size of aperture.
% - Size of aperture = Apd*Apd/100  sq deg
% - Number of dots per video frame = 16.7 dots per sq deg/sec,
% When rounding up, do not exceed the number of dots that can be plotted in a 
% video frame (dotInfo.maxDotsPerFrame). maxDotsPerFrame was originally in 
% setupScreen as a field in screenInfo, but makes more sense in createDotInfo as 
% a field in dotInfo.
ndots = min(dotInfo.maxDotsPerFrame, ...
    ceil(16.7 * apD .* apD * 0.01 / screenInfo.monRefresh));

%% MAT definition

% 170627: For each feature, the dissociation may differ based on difficulty
% of the stimulus.

for indFeature = 1:4
    dotInfo.MAT.ndotsH(1,indFeature) = dotInfo.MAT.(['percAtt', num2str(indFeature), 'H']) * ndots;
    dotInfo.MAT.ndotsL(1,indFeature) = dotInfo.MAT.(['percAtt', num2str(indFeature), 'L']) * ndots;
    % The following is just a sanity check and should not cause problems in
    % the current setup.
    if dotInfo.MAT.ndotsL(1,indFeature) > dotInfo.MAT.ndotsH(1,indFeature)
        disp('Warning: Check percentages for the likelihood. The second percentage appears to be larger than the first.');
    end
end

% get the a priori defined higher probability option for each feature
curChoices = dotInfo.HighProbChoice(:,indTrial);
curChoices(isnan(curChoices)) = 1; % only necessary if we test a single condition

% encode info on currently active parameters for each feature
for indAtt = 1:4
    atts.(dotInfo.MAT.attNames{indAtt}) = [];
    atts.(dotInfo.MAT.attNames{indAtt})(1,1) = dotInfo.MAT.(dotInfo.MAT.attNames{indAtt})(curChoices(indAtt));
    atts.(dotInfo.MAT.attNames{indAtt})(1,2) = dotInfo.MAT.(dotInfo.MAT.attNames{indAtt})(3-curChoices(indAtt));
    atts.(dotInfo.MAT.attNames{indAtt})(2,1) = curChoices(indAtt);
    atts.(dotInfo.MAT.attNames{indAtt})(2,2) = 3-curChoices(indAtt);
end

%% prepare checkerboard

% white = 255;
% black = 0;
% grey = 0; % note that background is also black
% % Query the frame duration
% ifi = Screen('GetFlipInterval', curWindow);
% % Screen resolution in Y
% screenYpix = screenInfo.screenRect(4)-200;
% % Number of white/black circle pairs
% rcycles = 8;
% % Number of white/black angular segment pairs (integer)
% tcycles = 26;
% % Now we make our checkerboard pattern
% xylim = 2 * pi * rcycles;
% xylim_small = 1 * pi * rcycles;
% [x, y] = meshgrid(-xylim: 2 * xylim / (screenYpix - 1): xylim,...
%     -xylim: 2 * xylim / (screenYpix - 1): xylim);
% at = atan2(y, x);
% checks = ((1 + sign(sin(at * tcycles) + eps)...
%     .* sign(sin(sqrt(x.^2 + y.^2)))) / 2) * (white - black) + black;
% circle = x.^2 + y.^2 <= xylim^2 & x.^2 + y.^2 >= xylim_small^2;
% checks = circle .* checks + grey * ~circle;
% % % Now we make this into a PTB texture
% % radialCheckerboardTexture(1)  = Screen('MakeTexture', curWindow, checkerContrast.*checks);
% % radialCheckerboardTexture(2)  = Screen('MakeTexture', curWindow, 1 - checkerContrast.*checks);
% % set starting texture cue
% textureCue = [1 2];
% brightPixels = find(checks == 255);
% darkPixels = find(checks ~= 255 & circle == 1);
% 
% determine update frequency of the two contents

% checkFlipTimeSecs = 1/dotInfo.Hz_BG;
% checkFlipTimeFrames = round(checkFlipTimeSecs / ifi);
frameCounter = 0;
cbframeCounter = 0;
cbFlip = 1;

RDMFlipTimeSecs = 1/dotInfo.Hz_RDM;
RDMFlipTimeFrames = round(RDMFlipTimeSecs / ifi);

%% get display size (for BG dots)

sizeX = screenInfo.screenRect(3);
sizeY = screenInfo.screenRect(4);

dontclear = screenInfo.dontclear;

% The main loop
frames = 0;
priorityLevel = MaxPriority(curWindow,'KbCheck');
Priority(priorityLevel);

% Make sure the fixation still on
for i = showtar
    Screen('FillOval',screenInfo.curWindow,targets.colors(i,:),targets.rects(i,:));
end

Screen('DrawingFinished',curWindow,dontclear);

%% get starting parameters

%currentSegment = 1;
%coh = dotInfo.coh{indCond}(currentSegment)./1000;
%direction = dotInfo.dir{indCond}(currentSegment);
%time = dotInfo.presTime{indCond}(currentSegment);
%Contrast = dotInfo.Contrast(indTrial);

% % Create checkerboard textures according to contrast
% checks1 = checks;        
% checks1(brightPixels) = 255.*Contrast;
% checks2 = checks;
% checks2(brightPixels) = 0;
% checks2(darkPixels) = 255.*Contrast;
% radialCheckerboardTexture(1)  = Screen('MakeTexture', curWindow, checks1);
% radialCheckerboardTexture(2)  = Screen('MakeTexture', curWindow, checks2);

% How dots are presented: 1st group of dots are shown in the first frame, a 2nd 
% group are shown in the second frame, a 3rd group shown in the third frame.
% Then in the next (4th) frame, some percentage of the dots from the 1st frame 
% are replotted according to the speed/direction and coherence. Similarly, the 
% same is done for the 2nd group, etc.

% initialize dot fields
for df = 1 : dotInfo.numDotField
    ss{df} = rand(ndots(df)*3, 2); % array of dot positions raw [x,y]
    % Divide dots into three sets
    Ls{df} = cumsum(ones(ndots(df),3)) + repmat([0 ndots(df) ndots(df)*2], ... 
        ndots(df), 1);
    loopi(df) = 1; % loops through the three sets of dots
end

%% PRESENT CUE

if dotInfo.durCue > 0

    if dotInfo.DirAttn(indTrial) == 1
        %Cue = dotInfo.targetAtt(indTrial); % current attribute
        Cue = dotInfo.MAT.attNamesDE{dotInfo.targetAtt(indTrial)};
        %DrawFormattedText(screenInfo.curWindow, Cue, 'center', 'center');
        % instead of text, show exemplars
        CueImg = ['/Volumes/fb-lip/LNDG/Julian/Projects/DYNSAT/C_Paradigm/MAT_V2/img/', dotInfo.MAT.attNames{dotInfo.targetAtt(indTrial)},'?.png'];
        [cueLoad,map,alpha] = imread(CueImg);
        cue2Disp = Screen('MakeTexture',screenInfo.curWindow,cueLoad);
        smallIm = CenterRect([0 0 floor(size(cueLoad,2)/1.5) floor(size(cueLoad,1)/1.5)], screenInfo.screenRect);
        Screen('DrawTexture', screenInfo.curWindow, cue2Disp, [], smallIm); % draw the object 

    elseif dotInfo.DirAttn(indTrial) == 2
    %     Cue = '?';
    %     DrawFormattedText(screenInfo.curWindow, Cue, 'center', 'center');

        CueImg = ['/Volumes/fb-lip/LNDG/Julian/Projects/DYNSAT/C_Paradigm/MAT_V2/img/??.png'];
        [cueLoad,map,alpha] = imread(CueImg);
        cue2Disp = Screen('MakeTexture',screenInfo.curWindow,cueLoad);
        smallIm = CenterRect([0 0 floor(size(cueLoad,2)/1.5) floor(size(cueLoad,1)/1.5)], screenInfo.screenRect);
        Screen('DrawTexture', screenInfo.curWindow, cue2Disp, [], smallIm); % draw the object  

    end
    CueOnset = Screen('Flip', curWindow,0,dontclear);
    ExperimentProtocol = [ExperimentProtocol; {'CueOnset'}, {CueOnset}, {[]}, {[]}, {[]}, {indTrial}]

    while GetSecs()-CueOnset < dotInfo.durCue % wait until cuetime is over
    end
    
end

%% PRESENT MAT STIMULUS

TimeStamping = [];
StartTime = GetSecs();
BlockOnset = StartTime;

ExperimentProtocol = [ExperimentProtocol; {'TrialOnset'}, {StartTime}, {[]}, {[]}, {[]}, {indTrial}]
ExperimentProtocol = [ExperimentProtocol; {'RDMUpdate'}, {StartTime}, {[]}, {[]}, {[]}, {indTrial}]

numOfFlips = 0;

% initiate response cue
KbQueueCreate; KbQueueStart;
while GetSecs()-StartTime < dotInfo.durPres % loop while presentation time has not been reached
    

    % On each update, the assignments of the attributes to pixels changes.
    
    % get point cloud according to direction distribution (no incoherence here)
    
    if dotInfo.MAT.coherence ~= 0
        [maxVal,~] = max([dotInfo.MAT.percAtt2H, dotInfo.MAT.percAtt2L]);
    else maxVal = 0;
    end;
        
    for df = 1:dotInfo.numDotField

        % update movement field with current direction
        % dxdy is an N x 2 matrix that gives jumpsize in units on 0..1
        % deg/sec * ap-unit/deg * sec/jump = ap-unit/jump
        dxdy_1{df} = repmat((dotInfo.speed(df)/10) * (10/apD(df)) * ...
        (3/screenInfo.monRefresh) * [cos(pi*atts.direction(1,1)/180.0), ...
        -sin(pi*atts.direction(1,1)/180.0)], ndots(df),1);
    
        dxdy_2{df} = repmat((dotInfo.speed(df)/10) * (10/apD(df)) * ...
        (3/screenInfo.monRefresh) * [cos(pi*atts.direction(1,2)/180.0), ...
        -sin(pi*atts.direction(1,2)/180.0)], ndots(df),1);
        
        % ss is the matrix with 3 sets of dot positions, dots from the last 2 
        %   positions and current dot positions
        % Ls picks out the set (e.g., with 5 dots on the screen at a time, 1:5, 
        %   6:10, or 11:15)
        
        % Lthis has the dot positions from 3 frames ago, which is what is then
        Lthis{df}  = Ls{df}(:,loopi(df));
        
        % Moved in the current loop. This is a matrix of random numbers - starting 
        % positions of dots not moving coherently.
        this_s{df} = ss{df}(Lthis{df},:);
        
        % Update the loop pointer
        loopi(df) = loopi(df)+1;
        
        if loopi(df) == 4
            loopi(df) = 1;
        end
        
        % Compute new locations, how many dots move coherently
        L = rand(ndots(df),1) < maxVal;
        % Offset the selected dots
        this_s{df}(L,:) = bsxfun(@plus,this_s{df}(L,:),dxdy_1{df}(L,:));
        
        if sum(~L) > 0
            if maxVal ~= 0
                this_s{df}(~L,:) = bsxfun(@plus,this_s{df}(~L,:),dxdy_2{df}(~L,:)); % get the opposite direction for the rest
            else 
                this_s{df}(~L,:) = rand(sum(~L),2);	% get new random locations for the rest
            end;
        end
        
        % Check to see if any positions are greater than 1 or less than 0 which 
        % is out of the square aperture, and replace with a dot along one of the
        % edges opposite from the direction of motion.
        N = sum((this_s{df} > 1 | this_s{df} < 0)')' ~= 0;
        
        if sum(N) > 0
            xdir = sin(pi*atts.direction(1,1)/180.0); % Simplify things and just use the primary direction here.
            ydir = cos(pi*atts.direction(1,1)/180.0);
            % Flip a weighted coin to see which edge to put the replaced dots
            if rand < abs(xdir)/(abs(xdir) + abs(ydir))
                this_s{df}(find(N==1),:) = [rand(sum(N),1),(xdir > 0)*ones(sum(N),1)];
            else
                this_s{df}(find(N==1),:) = [(ydir < 0)*ones(sum(N),1),rand(sum(N),1)];
            end
        end
        
        % Convert for plot
        this_x{df} = floor(d_ppd(df) * this_s{df});	% pix/ApUnit
        
        % It assumes that 0 is at the top left, but we want it to be in the 
        % center, so shift the dots up and left, which means adding half of the 
        % aperture size to both the x and y directions.
        dot_show{df} = (this_x{df} - d_ppd(df)/2)';
        
    end
    
    % For each feature, randomly select higher amount of dots in the first
    % cell and lower amount of dots in the second cell. The randomization
    % is conducted before each flip.
    
    % Ordering of features: color, direction, size, luminance
    
    for indFeature = 1:4
        tmp_randChoice = randperm(ndots); % Note that the seed has been saved, so the process should be replicable.
        if indFeature == 2 && maxVal ~= 0 % direction is already set
            randMat{indFeature,indTrial,1} = find(L); % L is always the higher probability
            randMat{indFeature,indTrial,2} = find(~L);
        else 
            randMat{indFeature,indTrial,1} = tmp_randChoice(1:ceil(dotInfo.MAT.ndotsH(1,indFeature))); % round up; might cause slightly more than the requested lower probability
            randMat{indFeature,indTrial,2} = tmp_randChoice(ceil(dotInfo.MAT.ndotsH(1,indFeature))+1:end);
        end
    end
    
    % For displaying, we need to know the dots of conjunction attributes
    % that have to be drawn. These will be encoded in the randMat structure.
    
    combs = allcomb([1,2],[1,2],[1,2],[1,2]); % Note that 1 & 2 refer to the higher/lower prob option here.
    
    for indComb = 1:size(combs,1)
        dotsIdx{indComb} = mintersect(randMat{1,indTrial,combs(indComb,1)},...
            randMat{2,indTrial,combs(indComb,2)},...
            randMat{3,indTrial,combs(indComb,3)},...
            randMat{4,indTrial,combs(indComb,4)});
    end
    
    %% After all computations, flip to draw dots from the previous loop. 
    % For the first call, this doesn't draw anything.
    
    vbl = Screen('Flip', curWindow,0,dontclear);
    
    TimeStamping = [TimeStamping; vbl];
        
    %% update checkerboard
    
%     % Increment the counter
%     frameCounter = frameCounter + 1;
%     cbframeCounter = cbframeCounter + 1;
%     
%     % Reverse the texture cue to show the other polarity if the time is up
%     % measured according to specified frequency
%     
%     if ~mod(cbframeCounter, dotInfo.UpdatesJitter{indCond}(cbFlip))
%         textureCue = fliplr(textureCue);
%         cbFlip = cbFlip + 1;
%         cbframeCounter = 0;
%     end
%     % Draw our texture to the screen
%     Screen('DrawTexture', curWindow, radialCheckerboardTexture(textureCue(1)));

    %% Draw random dots if it's time to update, although nothing is flipped yet    
    
    if ~mod(frameCounter, RDMFlipTimeFrames)
        % Note that dots that fall outside the circle are just dropped.
        % This may screw up the properties of the display.

        % NaN out-of-circle dots                
        xyDis = dot_show{1};
        outCircle = sqrt(xyDis(1,:).^2 + xyDis(2,:).^2) + dotInfo.dotSize/2 > center(df,3);        
        dots2Display = dot_show{1};
        dots2Display(:,outCircle) = NaN;

        Disp.color = cell(size(combs,1),1);
        Disp.dirDots = cell(size(combs,1),1);
        Disp.dotSize = cell(size(combs,1),1);
        Disp.lum = cell(size(combs,1),1);
        for indComb = 1:size(combs,1)
            if numel(dotsIdx{indComb}) > 0
                % referencing: attribute vector(index of higher/lower choice(prob of current comb))
                % combs(indComb, X): for this combination, is feature X higher high or low prob
                % atts.x(2,1): high prob option for feature; atts.X(2,2): low prob option
                Disp.color{indComb,1}   = dotInfo.MAT.color(atts.color(2,combs(indComb, 1)),:);
                Disp.dirDots{indComb,1} = dots2Display(:, dotsIdx{indComb}); % Note that 1 is always the index for the dots of the highest probability direction.
                Disp.dirDots{indComb,1} = Disp.dirDots{indComb,1}(:,~any(isnan(Disp.dirDots{indComb,1}),1)); % remove NaN columns
                Disp.dotSize{indComb,1} = dotInfo.MAT.size(atts.size(2,combs(indComb, 3)));
                Disp.lum{indComb,1}     = dotInfo.MAT.luminance(atts.luminance(2,combs(indComb, 4)));
            end
        end
        
        % Note that the intersection allocation should be saved for subsequent
        % processing as it is unlikely that the dimensions are orthogonal.
        % Therefore, they may constitute relevant intertrial variance in the
        % presentation (e.g. encoding model). Furthermore, the location
        % position can inform the visual sampling process.
        
        numOfFlips = numOfFlips+1;
        DisplayInfo.CombPositionByTrial{1,indTrial}(:,numOfFlips) = Disp.dirDots;
        DisplayInfo.CombSamples(:,indTrial,numOfFlips) = cellfun(@numel, Disp.dirDots);
        
    end
        
    if exist('Disp')
        for indComb = 1:size(combs,1)
            if numel(Disp.dirDots{indComb}) > 0
                Screen('DrawDots',curWindow,Disp.dirDots{indComb},Disp.dotSize{indComb},Disp.lum{indComb}.*Disp.color{indComb},center(df,1:2));
            end
        end
    end

    % Draw targets
    for i = showtar
        Screen('FillOval',screenInfo.curWindow,targets.colors(i,:),targets.rects(i,:));
    end
    
    %% Prepare next dots presentation
    
    % Tell PTB to get ready while doing computations for next dots presentation
    Screen('DrawingFinished',curWindow,dontclear);
    %Screen('BlendFunction', curWindow, GL_ONE, GL_ZERO);
       
    for df = 1 : dotInfo.numDotField
        % Update the dot position array for the next loop
        ss{df}(Lthis{df}, :) = this_s{df};
    end
    
    % Advance to next RDM state if time has passed
%     if GetSecs()-StartTime >= dotInfo.presTime{indCond}(currentSegment)
%         currentSegment = currentSegment + 1;
%         if currentSegment > numel(dotInfo.coh{indCond}) % amount of segments exceeded
%             break;
%         end;
%         %coh = dotInfo.coh{indCond}(currentSegment)./1000;
%         %direction = dotInfo.dir{indCond}(currentSegment);
%         time = dotInfo.presTime{indCond}(currentSegment);
%         StartTime = GetSecs();
%         ExperimentProtocol = [ExperimentProtocol; {'RDMUpdate'}, {StartTime}, {[]}, {[]}, {[]}, {coh}, {direction}, {Contrast}]
%     end;
    
    % User may terminate the dots by pressing certain keyboard keys defined by
    % "keys". Pressing the escape key will exit the experiment
    if not(isempty(keys))
        [exitKeyPressed, ~, keyIsDown, secs, keyCode] = checkKeys(dotInfo);
        if keyIsDown
            % Exit experiment
            if exitKeyPressed
                response{3} = -1;
                return
            end
            % End trial, have response
            if numel(find(keyCode)) == 1 && any(keyCode(keys))
                response{3} = find(keyCode(keys));
                response_time = secs;
            end
        end
    end

end

% Present the last frame of dots
Screen('Flip',curWindow,0,dontclear);

% Erase the last frame of dots, but leave up fixation and targets (if targets 
% are up). Make sure the fixation still on.
showTargets(screenInfo,targets,showtar);

%% QUERY RESPONSE

if dotInfo.durResp ~= 0

    CueImg = ['/Volumes/fb-lip/LNDG/Julian/Projects/DYNSAT/C_Paradigm/MAT_V2/img/', dotInfo.MAT.attNames{dotInfo.targetAtt(indTrial)},'.png'];
    [cueLoad,map,alpha] = imread(CueImg);
    cue2Disp = Screen('MakeTexture',screenInfo.curWindow,cueLoad);
    smallIm = CenterRect([0 0 floor(size(cueLoad,2)/1.5) floor(size(cueLoad,1)/1.5)], screenInfo.screenRect);
    Screen('DrawTexture', screenInfo.curWindow, cue2Disp, [], smallIm); % draw the object 

    % Cue = [dotInfo.MAT.attNamesDE{dotInfo.targetAtt(indTrial)}, '?'];
    % DrawFormattedText(screenInfo.curWindow, Cue, 'center', 'center', [255 255 255]);

    RespOnset = Screen('Flip', curWindow,0,dontclear);
    ExperimentProtocol = [ExperimentProtocol; {'RespOnset'}, {RespOnset}, {[]}, {[]}, {[]}, {indTrial}]

    if dotInfo.HighProbAtt(indTrial) == 1
        correctResp = 80; % response left
    elseif dotInfo.HighProbAtt(indTrial) == 2
        correctResp = 79; % response right
    end

    tmp_response = NaN;
    kp = NaN;
    rt = NaN;
    while GetSecs()-RespOnset < dotInfo.durResp % wait until cuetime is over
        %% check for responses
        [keyIsDown, firstPress, ~, ~, ~] = KbQueueCheck;
        if keyIsDown == 1
            kp = find(firstPress);
            rt = firstPress(kp)-RespOnset; % reference to onset of last interval
            % encode accuracy
            if kp == correctResp
                tmp_response = 1;
                disp('Correct');
            else
                tmp_response = 0;
                disp('Wrong');
            end
            ExperimentProtocol = [ExperimentProtocol; {'Resp'}, {firstPress(kp)}, {rt}, {kp}, {tmp_response}, {indTrial}];

            if dotInfo.feedback == 1
                % show accuracy by textcolor
                if tmp_response == 1
                    DrawFormattedText(screenInfo.curWindow, 'korrekt', 'center', 'center', [0 255 0]);
                elseif tmp_response == 0
                    DrawFormattedText(screenInfo.curWindow, 'falsch', 'center', 'center', [255 0 0]);
                end
                Screen('Flip', curWindow,0,dontclear); clear TextColor;
            end

        end % end of response encode loop
    end
    ResultMat(indTrial,:) = [dotInfo.DirAttn(indTrial), dotInfo.targetAtt(indTrial), rt, tmp_response];
    
end;

%% close

end_time = GetSecs;
Priority(0);