def TrialCountDownTask(): """Task that count downs to time limit for trial""" # Action for text fading out text_fade = vizact.parallel( vizact.fadeTo(0, time=0.8, interpolate=vizact.easeOut), vizact.sizeTo([1.5, 1.5, 1.0], time=0.8, interpolate=vizact.easeOut)) # Reset time text time_text.clearActions() time_text.alpha(1.0) time_text.color(viz.WHITE) time_text.setScale([1, 1, 1]) time_text.message(str(int(TRIAL_DURATION))) # Countdown from time limit start_time = viz.getFrameTime() last_remain = int(TRIAL_DURATION) while (viz.getFrameTime() - start_time) < TRIAL_DURATION: # Compute remaining whole seconds remain = int( math.ceil(TRIAL_DURATION - (viz.getFrameTime() - start_time))) # Update text if time remaining changed if remain != last_remain: if remain <= 5: time_text.alpha(1.0) time_text.color(viz.RED) time_text.setScale([1] * 3) time_text.runAction(text_fade) viz.playSound('sounds/beep.wav') time_text.message(str(remain)) last_remain = remain # Wait tenth of second yield viztask.waitTime(0.1)
def trialCountDownTask(): """Task that count downs to time limit for trial""" # Action for text fading out text_fade = vizact.parallel( vizact.fadeTo(0,time=0.8,interpolate=vizact.easeOut) ,vizact.sizeTo([.1,.1,.1],time=0.8,interpolate=vizact.easeOut) ) # Reset time text time_text.clearActions() time_text.alpha(1.0) time_text.color(viz.BLACK) time_text.setScale([.05,.05,.05]) time_text.message('REMAINING: ' + str(int(globals_oa.TIME_TO_FIND_IN_SCAVENGER_HUNT)/60)+ ':' + str(int(globals_oa.TIME_TO_FIND_IN_SCAVENGER_HUNT)%60).zfill(2)) # Countdown from time limit start_time = viz.getFrameTime() last_remain = int(globals_oa.TIME_TO_FIND_IN_SCAVENGER_HUNT) while (viz.getFrameTime() - start_time) < globals_oa.TIME_TO_FIND_IN_SCAVENGER_HUNT: # Compute remaining whole seconds remain = int(math.ceil(globals_oa.TIME_TO_FIND_IN_SCAVENGER_HUNT - (viz.getFrameTime() - start_time))) # Update text if time remaining changed if remain != last_remain: if remain <= 5: time_text.alpha(1.0) time_text.color(viz.RED) time_text.setScale([.05]*3) time_text.runAction(text_fade) time_text.message(str(remain/60)+ ':'+str(remain%60).zfill(2)) last_remain = remain # Wait tenth of second yield viztask.waitTime(0.1) print 'OUT OF TIME'
def TrialCountDownTask(): """Task that count downs to time limit for trial""" global revealSelf global manChase # Action for text fading out text_fade = vizact.parallel( vizact.fadeTo(0,time=0.8,interpolate=vizact.easeOut) ,vizact.sizeTo([1.5,1.5,1.0],time=0.8,interpolate=vizact.easeOut) ) # Reset time text time_text.clearActions() time_text.alpha(1.0) time_text.color(viz.WHITE) time_text.setScale([1,1,1]) time_text.message(str(int(TRIAL_DURATION))) # Countdown from time limit start_time = viz.getFrameTime() last_remain = int(TRIAL_DURATION) male2.clearActions() male2.setPosition(2.5,0,7.5) while (viz.getFrameTime() - start_time) < TRIAL_DURATION: if revealSelf: pigeon.clearActions() pos = viz.MainView.getPosition() pigeon.addAction( vizact.walkTo([pos[0], 0, pos[2]]) ) if manChase: male.clearActions() male2.state(2) pos = pigeon.getPosition() male2.addAction( vizact.walkTo([pos[0] - .5, 0, pos[2] - .5])) if male2.getPosition()[2] == (pigeon.getPosition()[2] - .5): #allow for other actions to take place (chase takes precedence) manChase = False male2.state(9) # Compute remaining whole seconds remain = int(math.ceil(TRIAL_DURATION - (viz.getFrameTime() - start_time))) # Update text if time remaining changed if remain != last_remain: if remain <= 5: time_text.alpha(1.0) time_text.color(viz.RED) time_text.setScale([1]*3) time_text.runAction(text_fade) viz.playSound('sounds/beep.wav') time_text.message(str(remain)) last_remain = remain # Wait tenth of second yield viztask.waitTime(0.1)
def getOutput(self): """ Returns a string describing the current state of the experiment, useful for recording. """ # Legend: # ** for 1 var # () for 2 vars # [] for 3 vars # <> for 4 vars # @@ for 16 vars (view and projection matrices) #### Eventflag # 1 ball launched # 3 ball has hit floor # 4 ball has hit paddle # 5 ball has hit back wall # 6 ball has timed out outputString = '* frameTime %f * ' % (viz.getFrameTime()) outputString = outputString + '* inCalibrateBool %f * ' % (self.inCalibrateMode) outputString = outputString + '* eventFlag %f * ' % (self.eventFlag.status) outputString = outputString + '* trialType %s * ' % (self.currentTrial.trialType) viewPos_XYZ = viz.MainView.getPosition() outputString = outputString + '[ viewPos_XYZ %f %f %f ] ' % (viewPos_XYZ[0],viewPos_XYZ[1],viewPos_XYZ[2]) return outputString #%f %d' % (viz.getFrameTime(), self.inCalibrateMode)
def ProximityWork(e): global inTime global cur_dict viewPath.append(viz.MainView.getPosition()) bodies = manager.getActiveTargets(e.sensor) inTime = viz.getFrameTime() print "Body count in sensor", len(bodies) cur_dict.update({"Body_Count": len(bodies)})
def populateNextBufferElement(self): footProperties = SingleBufferEntry( frameTime = viz.getFrameTime(), pos_XYZ = self.mocapFoot.vizNode.getPosition(), ori_XYZW = self.mocapFoot.vizNode.getQuat() ) # write here to file for unfiltered data # Lock the buffer before writing to it, so other threads cannot read from it at the same time. self.lock.acquire() self.footBuffer.append(footProperties) self.lock.release()
def writeToFile(): global analytics global MainViewApproaches global startTime file = open('analytics_file', 'w') file.write("Analytics Data:\n\n") cur_dict = {"Approaches": str(MainViewApproaches)} analytics.append(cur_dict) cur_dict = {} cur_dict = {"Total Time ": (viz.getFrameTime() - startTime)} analytics.append(cur_dict) file.writelines(["%s\n" % dict for dict in analytics])
def writeToFile(): global analytics global MainViewApproaches global startTime file = open('analytics_file', 'w') file.write("Analytics Data:\n\n") cur_dict = {"Approaches": str(MainViewApproaches)} analytics.append(cur_dict) cur_dict = {} cur_dict = {"Total Time ": (viz.getFrameTime()-startTime)} analytics.append(cur_dict) file.writelines(["%s\n" % dict for dict in analytics])
def _continuePlay(self): """plays the path with the given configuration""" if self._path == None: return # Calculate time stepping along animation path. # Set last frame time step = viz.getFrameTime() - self._last_frame_time self._last_frame_time = viz.getFrameTime() # Calculate new time from step and current time time = self._path.getTime() time += self._playback_direction * step * self._playback_speed # handle over stepped duration if time > self._path.getDuration(): loop_mode = self._path.getLoopMode() if loop_mode == viz.LOOP: time = 0 elif loop_mode == viz.SWING: self._playback_direction = -1 time = self._path.getTime() + self._playback_direction * step else: self.stop() return elif time < 0.0: loop_mode = self._path.getLoopMode() if loop_mode == viz.LOOP: time = self._path.getDuration() elif loop_mode == viz.SWING: self._playback_direction = 1 time = self._path.getTime() + self._playback_direction * step else: self.stop() return # set final time self._path.setTime(time);
def ExitProximity(e): """@args vizproximity.ProximityEvent()""" global cur_dict global analytics if (e.target is target): instructions.visible(viz.OFF) time = (viz.getFrameTime() - inTime) print("Time spent in sensor: %.2f seconds" % time) cur_dict.update({"Time": time}) #Analytics analytics.append(cur_dict) cur_dict = {}
def TrialCountDownTask(): """Task that count downs to time limit for trial""" # Action for text fading out text_fade = vizact.parallel( vizact.fadeTo(0,time=0.8,interpolate=vizact.easeOut) ,vizact.sizeTo([1.5,1.5,1.0],time=0.8,interpolate=vizact.easeOut) ) # Reset time text time_text.clearActions() time_text.alpha(1.0) time_text.color(viz.WHITE) time_text.setScale([1,1,1]) time_text.message(str(int(TRIAL_DURATION))) # Countdown from time limit start_time = viz.getFrameTime() last_remain = int(TRIAL_DURATION) while (viz.getFrameTime() - start_time) < TRIAL_DURATION: # Compute remaining whole seconds remain = int(math.ceil(TRIAL_DURATION - (viz.getFrameTime() - start_time))) # Update text if time remaining changed if remain != last_remain: if remain <= 5: time_text.alpha(1.0) time_text.color(viz.RED) time_text.setScale([1]*3) time_text.runAction(text_fade) viz.playSound('sounds/beep.wav') time_text.message(str(remain)) last_remain = remain # Wait tenth of second yield viztask.waitTime(0.1)
def ExitProximity(e): """@args vizproximity.ProximityEvent()""" global cur_dict global analytics if (e.target is target): instructions.visible(viz.OFF) time = (viz.getFrameTime() - inTime) print("Time spent in sensor: %.2f seconds" % time) cur_dict.update({"Time":time}) #Analytics analytics.append(cur_dict) cur_dict = {}
def writeToFile(self): if not self.file: print >> sys.stderr, "No file open to write to" else: leftBuffer = self.leftFoot.getFiltered_InstantaneousFootInfo() rightBuffer = self.rightFoot.getFiltered_InstantaneousFootInfo() leftMocapPos = self.leftFoot.mocapFoot.vizNode.getPosition() rightMocapPos = self.rightFoot.mocapFoot.vizNode.getPosition() #Fastest way to concatenate strings. #You dont want to spend time creating and concatenating strings oneLineOfData = [] oneLineOfData.append('lFPos ') oneLineOfData.append(str(leftMocapPos[0])) oneLineOfData.append(' ') oneLineOfData.append(str(leftMocapPos[1])) oneLineOfData.append(' ') oneLineOfData.append(str(leftMocapPos[2])) oneLineOfData.append(' rFPos ') oneLineOfData.append(str(rightMocapPos[0])) oneLineOfData.append(' ') oneLineOfData.append(str(rightMocapPos[1])) oneLineOfData.append(' ') oneLineOfData.append(str(rightMocapPos[2])) oneLineOfData.append(' leftSpeed ') oneLineOfData.append(str(leftBuffer.speed_MS)) oneLineOfData.append(' rightSpeed ') oneLineOfData.append(str(rightBuffer.speed_MS)) oneLineOfData.append(' leftCollision ') oneLineOfData.append(str(self.flag_leftFootCollision)) oneLineOfData.append(' rightCollision ') oneLineOfData.append(str(self.flag_rightFootCollision)) oneLineOfData.append(' frameTimeW ') oneLineOfData.append(str(viz.getFrameTime())) #If there was a collision in this frame, construct the string and set the collision flags to false again if self.flag_leftFootCollision or self.flag_rightFootCollision : self.flag_leftFootCollision = False self.flag_rightFootCollision = False #Join all the strings, this is where the string is created, so no time spent in concatenating :) finalString = ''.join(oneLineOfData) self.file.write(finalString) self.file.write('\n')
def __init__(self, path = None, playback_speed = 1.0, start = True): # path to play self._path = path # direction of playback (forward = 1 or backward = -1) self._playback_direction = 1 # speed factor for playback (real time = 1.0) self._playback_speed = playback_speed # flag that states if animation path capture is currently stopped self._stop = not start # stores frame time of last update call self._last_frame_time = viz.getFrameTime() # reference to event function called each frame self._on_update = vizact.onupdate(0, self._onUpdate)
def _capture(self): """captures position, rotation and time stamp and appends to recorded""" # record based on elapsed time t = -1 t = viz.getFrameTime() if self._start_time == -1: self._start_time = 0.0 t -= self._start_time pos = self.getPosition() rot = self.getEuler() scale = self.getScale() self._data.append({ "time": t, "position": pos, "rotation": rot, "scale": scale }) self._updatAvgFps()
def main(): moveAvatars() global startTime startTime = viz.getFrameTime()
def calculate_segment_CoM(self): x_TBCoM = {} y_TBCoM = {} z_TBCoM = {} self.test_segment_list = [] for segment in self.body_segments: if segment[0] is 'Pelvis': # for body segment pelvis distal end (hip midpoint) equals the midpoint between r and l hip # get tracker of r and l hip lhip, rhip = trackers[16], trackers[20] # use list comprehension to calculate midpoint (using getPosition for coordinates) self.HIP_MIDPOINT = [ ((a + b / 2)) for a, b in zip(lhip.getPosition(), rhip.getPosition()) ] #print(self.HIP_MIDPOINT) # apply hip midpoint coordinates to sphere self.s.setPosition(self.HIP_MIDPOINT) # get position of prox / dist segment ends prox_pos = self.HIP_CENTER prox_pos = prox_pos.getPosition() dist_pos = self.HIP_MIDPOINT else: # link green/red spheres to prox/dist segment prox = segment[1] dist = segment[2] # get position of prox / dist segment ends prox_pos = prox.getPosition() dist_pos = dist.getPosition() #print(segment, prox_pos, dist_pos) seg = [ segment[0] + '_prox', prox_pos[0], prox_pos[1], prox_pos[2], segment[0] + '_dist', dist_pos[0], dist_pos[1], dist_pos[2] ] #data = map(lambda x: str(x).translate(None, ['[',']']), seg) self.test_segment_list.append(seg) #[segment, dist_pos, prox_pos]) x_prox, y_prox, x_dist, y_dist = prox_pos[0], prox_pos[ 1], dist_pos[0], dist_pos[1] z_prox, z_dist = prox_pos[2], prox_pos[2] segment = segment[0] l_prox, l_dist = self.perc_of_segm_length[segment][ 0], self.perc_of_segm_length[segment][1] # x_COM = x_prox * l_dist + x_dist * l_prox y_COM = y_prox * l_dist + y_dist * l_prox z_COM = z_prox * l_dist + z_dist * l_prox # apply body segment COM to according sphere self.com_spheres[segment].setPosition(x_COM, y_COM, z_COM) self.com_spheres[segment].visible(viz.OFF) segment_fraction = self.perc_of_segm_length[segment][2] x_TBCoM[segment] = (x_COM * segment_fraction) y_TBCoM[segment] = (y_COM * segment_fraction) z_TBCoM[segment] = (z_COM * segment_fraction) X = sum(x_TBCoM.values()) Y = sum(y_TBCoM.values()) Z = sum(z_TBCoM.values()) # apply TBCoM coordinates to TBCoM sphere self.TBCoM_sphere.setPosition(X, Y, Z) self.TBCoM_sphere.visible(viz.OFF) #print(self.TBCoM_sphere.getPosition()[0]) #print(self.TBCoM_sphere.getEuler()) # print out data in console #print(self.test_segment_list) #print(self.exp.TRIAL_NO, self.exp.current_stimulus_name, self.exp.current_stimulus_yaw, self.exp.current_stimulus_roll,self.exp.STATE, # viz.tick(), (viz.tick() - self.exp.TRIAL_START_TIME), viz.getFrameNumber(), viz.getFrameElapsed(), viz.getFrameTime(), [X, Y, Z], tracker_coordinates)#self.segment_coordinates) # temporarily save framewise data into empty list self.TEMP_RV_DATA.append([ self.exp.STATE, self.exp.response, self.exp.keyPressTime, viz.tick(), viz.getFrameNumber(), viz.getFrameElapsed(), viz.getFrameTime() ]) self.TEMP_COM_DATA.append( self.test_segment_list) # self.segment_coordinates self.TEMP_TCBOM.append(['TCBOM', X, Y, Z])
def _checkForCollisions(self): thePhysEnv = self.room.physEnv; if( thePhysEnv.collisionDetected == False ): # No collisions this time! return theFloor = self.room.floor theBackWall = self.room.wall_NegZ theBall = self.currentTrial.ballObj thePaddle = self.room.paddle for idx in range(len(thePhysEnv.collisionList_idx_physNodes)): physNode1 = thePhysEnv.collisionList_idx_physNodes[idx][0] physNode2 = thePhysEnv.collisionList_idx_physNodes[idx][1] # BALL / FLOOR if( theBall > 0 ): if( self.currentTrial.ballHasBouncedOnFloor == False and (physNode1 == theFloor.physNode and physNode2 == theBall.physNode or physNode1 == theBall.physNode and physNode2 == theFloor.physNode )): self.eventFlag.setStatus(3) self.currentTrial.ballHasBouncedOnFloor = True # This is an example of how to get contact information bouncePos_XYZ,normal,depth,geom1,geom2 = thePhysEnv.contactObjects_idx[0].getContactGeomParams() self.currentTrial.ballOnPaddlePos_XYZ = bouncePos_XYZ #print 'Ball has hit the ground.' soundBank.bounce.play() # Compare pre-bounce flight dur with predicted pre-bounce flight dur actualPreBounceFlightDur = float(viz.getFrameTime()) - self.currentTrial.launchTime durationError = self.currentTrial.predictedPreBounceFlightDur - actualPreBounceFlightDur self.currentTrial.flightDurationError = durationError print 'Predicted: ' + str(self.currentTrial.predictedPreBounceFlightDur) print 'Actual : ' + str(actualPreBounceFlightDur) print 'Flight duration error: ' + str(durationError) # BALL / PADDLE if( self.currentTrial.ballHasHitPaddle == False and (physNode1 == thePaddle.physNode and physNode2 == theBall.physNode or physNode1 == theBall.physNode and physNode2 == thePaddle.physNode )): self.eventFlag.setStatus(4) self.currentTrial.ballHasHitPaddle = True soundBank.cowbell.play() # self.ballObj.physNode.setStickUponContact( room.paddle.physNode.geom ) if( theBall.physNode.queryStickyState(thePaddle.physNode) ): theBall.visNode.setParent(thePaddle.visNode) collPoint_XYZ = theBall.physNode.collisionPosLocal_XYZ theBall.visNode.setPosition(collPoint_XYZ) self.currentTrial.ballOnPaddlePosLoc_XYZ = collPoint_XYZ # If you don't set position in this way (on the next frame using vizact.onupdate), # then it doesn't seem to update correctly. # My guess is that this is because the ball's position is updated later on this frame using # visObj.applyPhysToVis() vizact.onupdate(viz.PRIORITY_LINKS,theBall.visNode.setPosition,collPoint_XYZ[0],collPoint_XYZ[1],collPoint_XYZ[2]) if( physNode1 == theBackWall.physNode and physNode2 == theBall.physNode or physNode1 == theBall.physNode and physNode2 == theBackWall.physNode): self.eventFlag.setStatus(5) #print 'Ball has hit the back wall.' #currentTrial.removeBall() soundBank.bounce.play()