Beispiel #1
0
    def __del__(self):

        print viz.getFrameNumber()

        # Remove physical component
        self.phys_node.remove()

        # Stop updating visNode
        if self.update_action:
            self.update_action.remove()

        # Remove visual component
        self.vis_node.remove()
Beispiel #2
0
 def __del__(self):
     
     print viz.getFrameNumber()
     
     # Remove physical component
     self.physNode.remove()
     
     # Stop updating visNode
     if( self.updateAction ):
         self.updateAction.remove()
         
     # Remove visual component
     self.visNode.remove()
    def handle_request(self, request):
        """@args vizhtml.VizardHTTPRequestHandler()"""
        #viz.clearcolor(viz.SKYBLUE)
        #viz.addChild('ground_grass.osgb')
        #viz.MainView.setPosition([0,1.8,-10])
        #carousel = viz.addChild('carousel.wrl')
        #carousel.addAction(vizact.spin(0,1,0,20))

        print request.log_request

        # If request is for a resource (e.g. image), then let vizhtml handle it
        if request.resource_path:
            return

        # If form was submitted, put message back into page
        if request.form_event:
            message = cgi.escape(request.form_event.message, True)
            if message == 'doorBath':
                doorbath()

        else:
            message = ''

        # Send html code with dynamic content
        # Envía el código HTML especificado en el navegador.
        request.send_html_code(
            code.format(frame=viz.getFrameNumber(), message=message))
Beispiel #4
0
	def _resetEventFlag(self):
		
		#This should run before timers, eyeTrackingCal.  Called using <vizact>.onupdate
		if( self.lastFrameUpdated == viz.getFrameNumber() ):
			print 'Did not reset! Status already set to ' + str(self.status)
		else:
			self.status = 0; # 0 Means nothing is happening
Beispiel #5
0
	def setStatus(self,status,overWriteBool = False):
		
		if( self.lastFrameUpdated != viz.getFrameNumber() ):
			
			#print 'Setting status to' + str(status)
			
			self.status = status
			self.lastFrameUpdated = viz.getFrameNumber()
			
		elif( overWriteBool is True and self.lastFrameUpdated == viz.getFrameNumber() ):
			
			#print 'Overwrite from status ' + str(self.status) + ' to ' + str(status)
			
			self.status = status
			self.lastFrameUpdated = viz.getFrameNumber()
		
			
		elif( self.lastFrameUpdated == viz.getFrameNumber() ):
			
			#print 'Stopped attempt to overwrite status of ' + str(self.status) + ' with ' + str(status) + ' [overWriteBool=False]'
			pass
Beispiel #6
0
	def __init__(self):
		
		################################################################
		##  Eventflag
		
		# 1 ball launched
		# 2 * not used * 
		# 3 ball has hit floor
		# 4 ball has hit paddle
		# 5 ball has hit back wall
		# 6 trial end
		# 7 block end
		
		viz.EventClass.__init__(self)
		
		self.status = 0
		self.lastFrameUpdated = viz.getFrameNumber()
		self.currentValue = 0
		
		# On every frame, self.eventFlag should be set to 0
		# This should happen first, before any timer object has the chance to overwrite it!
		vizact.onupdate(viz.PRIORITY_FIRST_UPDATE,self._resetEventFlag)
    def UpdateView(self, YR_input=None):
        #elapsedTime = viz.elapsed()

        elapsedTime = viz.getFrameElapsed()

        if elapsedTime > .02:
            print("viz.tick: ", viz.tick())
            print("frame number: ", viz.getFrameNumber())
            print("elapsedTime:", elapsedTime)

        yawrate = 0.0
        turnangle = 0.0
        distance = 0.0

        dt = elapsedTime
        #dt = 1.0/60.0 #not sure why but it's perceptually smoother with a constant. This shouldn't be the case.

        #Get steering wheel and gas position
        data = joy.getPosition()
        SteeringWheelValue = data[0]  # on scale from -1 to 1.
        gas = data[1]

        #keep heading up to date.
        ori = self.__view.getEuler()
        self.__heading = ori[0]

        if viz.key.isDown(viz.KEY_UP):
            gas = -5
        elif viz.key.isDown(viz.KEY_DOWN):
            gas = 5
        if viz.key.isDown(viz.KEY_LEFT
                          ):  #rudimentary control with the left/right arrows.
            data[0] = -1
        elif viz.key.isDown(viz.KEY_RIGHT):
            data[0] = 1

#		#Compute drag
#		drag = self.__speed / 300.0
        self.__dir = 1
        if (YR_input is not None) and (
                self.__automation == True
        ):  #provides the opportunity to pass a yaw rate to the driver.
            yawrate = YR_input

            Wheel_yawrate = self.__dir * SteeringWheelValue * 35.0  #max wheel lock is 35degrees per s yawrate

            self.__Wheel_yawrate_adjustment = yawrate - Wheel_yawrate  #correction for any offset between virtual yawrate and yawrate as specified by the steering wheel angle.
        else:
            yawrate = self.__dir * SteeringWheelValue * 35.0  #max wheel lock is 35degrees per s yawrate

            #add adjustment for smooth take-over.
            yawrate += self.__Wheel_yawrate_adjustment

        turnangle = yawrate * dt
        self.__heading += turnangle

        self.__pause = self.__pause + 1
        #Update the viewpoint
        if self.__pause > 0:

            distance = self.__speed * dt

            #posnew = (0,0,self.__speed)
            posnew = (0, 0, distance)
            eulernew = (self.__heading, 0, 0)

            self.__view.setPosition(posnew, viz.REL_LOCAL)
            self.__view.setEuler(eulernew)

        else:
            self.__heading = 0.0
            self.__dir = 1.0
            turnangle = 0.0

        #return the values used in position update
        UpdateValues = []
        UpdateValues.append(yawrate)
        UpdateValues.append(turnangle)
        UpdateValues.append(distance)
        UpdateValues.append(dt)
        UpdateValues.append(SteeringWheelValue)
        UpdateValues.append(self.__Wheel_yawrate_adjustment)

        return (UpdateValues)
def myKeyboard( key):
	global t , trialstartframe, trialType, feetScaledFlag, Piazza, stripe2, lFoot, rFoot
	global affTrials, distTrials, trials, footSize, numTrials, canStep, DataEntry, verbalEst
	global subjectno, ToRecord_YN, Estimate, FootH_Offset, Swapped, Tracker_Offset, paused
	global lFootTracker, rFootTracker, LFootLink, RFootLink, rFoot, lFoot, Tracker2FootEdge
	global lFootModel, rFootModel, InputString, EH_Flag
	
	if DataEntry == False:
		
		if key == '`':
			DataEntry = True
		if key == 'n':
			ToRecord_YN = "FALSE"
		if key == 'y':
			ToRecord_YN = "TRUE"
		# Starts the next trial
		if key == 'p':
			BlockDisplayOFF()
		if key ==  ' ':
			if trialType == 0: # AFFORDANCE
				out.write(str(subjectno) + ',' + str(t) + ',' +	str(trials[t][1]) + ',' + 'AFFORDANCE' + ',' + str(trials[t][0]) + ',' + str(ToRecord_YN) +'\n') 
				#('\nSubject Number,Trial Index,Gap Width,Trial Type,Rotation,Can Step,Distance,Height Perception,Height Change %')
				out.flush()
				os.fsync(out) 
				ToRecord_YN = None
				
				if t < len(affTrials) - 1:
					CrosshairDisplay(2)
					t += 1
					doTrial( trials[t][0] , trials[t][1] )
					print t
					print trials[t]
					trialstartframe =  viz.getFrameNumber()
				else: # Finished AFFORDANCE
					t += 1 # Increment so that the scene that is loaded after the message box is the first DISTANCE trial/next trial
					trialType = 1 # DISTANCE
	
					numTrials = 12 # Number of trials in each foot size for the DISTANCE judgments
					canStep = -1 # No longer used for remaining trials
					
					# Take break before beginning DISTANCE judgments
					BlockDisplay("DISTANCE")
					# Load the first DISTANCE trial
					doTrial (trials[t][0] , trials[t][1])
					print t
					print trials[t]
					
			else: # DISTANCE (trialType == 1) or EYE HEIGHT (trialType == 2) 
				if t < len(trials) - 1:
					CrosshairDisplay(3)
					out.write(str(subjectno) + ',' + str(t) + ',' +	str(trials[t][1]) + ',' + 'DISTANCE' + ',' + str(trials[t][0]) + ',' + "N/A" + ',' + InputString +'\n') 
					#('\nSubject Number,Trial Index,Trial Type,Rotation,Can Step,Distance,Height Perception,Height Change %')
					out.flush()
					os.fsync(out) 
					InputString = ""
					InputText2D.message(InputString)
					
					t += 1
#					if (t != len(affTrials)) and (t-len(affTrials))%numTrials == 0:
#						viz.message("")
#						print 'hit third break'
#						currSizeIndex = 1 # Set foot size index to second foot size
					doTrial( trials[t][0] , trials[t][1] )
					print t
					print trials[t]
					trialstartframe =  viz.getFrameNumber()
				else: # Finished DISTANCE
					if(EH_Flag == False):
						out.write(str(subjectno) + ',' + str(t) + ',' +	str(trials[t][1]) + ',' + 'DISTANCE' + ',' + str(trials[t][0]) + ',' + "N/A" + ',' + InputString +'\n')
						EH_Flag = True
					else:
						out.write(str(subjectno) + ',' + str(t+1) + ',' +	"N/A" + ',' + 'HEIGHT ESTIM' + ',' + str(trials[t][0]) + ',' + "N/A" + ',' + "N/A" + ',' + InputString +'\n')
					trialType = 2 # EYE HEIGHT
					paused = True
					InputString = ""
					InputText2D.message(InputString)
					BlockDisplay("EYE HEIGHT")
					
		# Precautionary inclusion, these keys should be VERY circumstantially used
		# Go back one trial
		if key == viz.KEY_LEFT:
			t -= 2
			myKeyboard(' ')
		# Going forward one trial would be equivalent to pressing the spacebar so that key == ' '
			
		
		# Use this key for updating scale of the shoes to reflect the base shoe size/dimensions
		if key == 'u' and feetScaledFlag < 0:
			print ("Scaling Feet")
			# The shoes will now be scaled properly
			feetScaledFlag = 1
			
			TempList = rFoot.getScale()
			TempList = [TempList[0]*Multi,TempList[1]*Multi,TempList[2]*Multi]
			rFoot.setScale(TempList)
			TempList = lFoot.getScale()
			TempList = [TempList[0]*Multi,TempList[1]*Multi,TempList[2]*Multi]
			lFoot.setScale(TempList)
			SetShoes()
			del TempList
			
			# Make the shoes visible to the user
			rFoot.visible(viz.ON)
			lFoot.visible(viz.ON)
			
			RotAngle = math.degrees(math.asin(Tracker_Offset/Tracker2FootEdge))
			print("RotAngle: " + str(RotAngle))
			rFootModel.setAxisAngle([1,0,0,RotAngle])
			lFootModel.setAxisAngle([1,0,0,RotAngle])
			
			# Schedule a task so that the data is recorded every FRAME_DELAY seconds
			viztask.schedule(printTarget)
			
			print ("Scaling Feet Done")
		
		# Show noisy blank screen
		if key == 'b':
			CrosshairDisplay(2)
		
		if key == '1':
			Tracker_Offset = viz.input('Tracker offset from center to ground (in CM)' , value='0')
			Tracker_Offset = Tracker_Offset * .01
			LFootLink.remove()
			RFootLink.remove()
			RFootLink = viz.link(Tracking[0], rFoot, offset=(0,-Tracker_Offset,0, viz.REL_PARENT))
			LFootLink = viz.link(Tracking[1], lFoot, offset=(0,-Tracker_Offset,0, viz.REL_PARENT))
			
			if(Tracker_Offset/Tracker2FootEdge > 1 or Tracker_Offset/Tracker2FootEdge < 0):
				CalcErrorFlag = True
			
			while(CalcErrorFlag):
				Tracker_Offset = viz.input('Tracker offset from center to ground (in CM)' , value='0')
				Tracker_Offset = Tracker_Offset * .01
				Tracker2FootEdge = viz.input('distance from tracker center to the ground in front of the participants foot (in CM)' , value='0')
				Tracker2FootEdge = Tracker2FootEdge * .01
				if(Tracker_Offset/Tracker2FootEdge > 1 or Tracker_Offset/Tracker2FootEdge < 0):
					pass
				else:
					CalcErrorFlag = False
					
			RotAngle = math.degrees(math.asin(Tracker_Offset/Tracker2FootEdge))
			print("RotAngle: " + str(RotAngle))
			rFootModel.setAxisAngle([1,0,0,RotAngle])
			lFootModel.setAxisAngle([1,0,0,RotAngle])
	
		if key == '2':
			Tracker2FootEdge = viz.input('distance from tracker center to the ground in front of the participants foot (in CM)' , value='0')
			Tracker2FootEdge = Tracker2FootEdge * .01

			if(Tracker_Offset/Tracker2FootEdge > 1 or Tracker_Offset/Tracker2FootEdge < 0):
				CalcErrorFlag = True
			
			while(CalcErrorFlag):
				Tracker_Offset = viz.input('Tracker offset from center to ground (in CM)' , value='0')
				Tracker_Offset = Tracker_Offset * .01
				Tracker2FootEdge = viz.input('distance from tracker center to the ground in front of the participants foot (in CM)' , value='0')
				Tracker2FootEdge = Tracker2FootEdge * .01
				if(Tracker_Offset/Tracker2FootEdge > 1 or Tracker_Offset/Tracker2FootEdge < 0):
					pass
				else:
					CalcErrorFlag = False
	
			RotAngle = math.degrees(math.asin(Tracker_Offset/Tracker2FootEdge))
			print("RotAngle: " + str(RotAngle))
			rFootModel.setAxisAngle([1,0,0,RotAngle])
			lFootModel.setAxisAngle([1,0,0,RotAngle])

	elif DataEntry == True:
		
		if key == '`' or key == viz.KEY_RETURN:
			DataEntry = False
		elif key == viz.KEY_BACKSPACE:
			InputString = InputString[:-1]
		else:
			InputString = InputString + key
		InputText2D.message(InputString)
		
		
	if key == viz.KEY_F6:
		LFootLink.remove()
		RFootLink.remove()
		if Swapped == False:
			Swapped = True
			RFootLink = viz.link(Tracking[1], rFoot, offset=(0,-Tracker_Offset,0, viz.REL_PARENT))###FIX
			LFootLink = viz.link(Tracking[0], lFoot, offset=(0,-Tracker_Offset,0, viz.REL_PARENT))
			
		elif Swapped == True:
			Swapped = False
			RFootLink = viz.link(Tracking[0], rFoot, offset=(0,-Tracker_Offset,0, viz.REL_PARENT))###FIX
			LFootLink = viz.link(Tracking[1], lFoot, offset=(0,-Tracker_Offset,0, viz.REL_PARENT))
			

	if key == viz.KEY_ESCAPE:
		out.flush()
		out2.flush()
		os.fsync(out)
		os.fsync(out2) 
		out.close()
		out2.close()
		viz.quit()
Beispiel #9
0
    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])