Пример #1
0
 def __init__(self,
              x=0,
              y=0,
              angle=0,
              scale=4,
              speed=DEFAULT_MAX_SPEED,
              center_offset=0,
              callback=None,
              **kwargs):
     print 'Initializing Joystick.movement'
     global __JOYSTICK_VAR
     frequency = 0.01
     timer_id = 1
     self.motion = __JOYSTICK_VAR = InputHandler(frequency,
                                                 speed * scale / 8,
                                                 **kwargs)
     self.scale = float(scale)
     self.callbacks = {timer_id: self.UpdateLocation}
     self.coords = (x, y, angle)
     self.callback = callback
     self.center_offset = center_offset
     viz.eyeheight(0.0)
     viz.setfov(70, 1)
     viz.mouse(viz.OFF)  # don't want vizard mouse navigation
     viz.callback(viz.TIMER_EVENT, self.TimerCallback)
     viz.starttimer(timer_id, frequency, -1)
	def MoveTo(self,_x,_z,_angle):
		if  self.okMove.acquire(0):
			# reset variables
			self.doRotate=0
			self.x = _x
			self.z = _z
			self.angle = _angle
			if self.angle==0:
				self.z-=self.center_offset
			elif self.angle==90:
				self.x-=self.center_offset
			elif self.angle==180:
				self.z+=self.center_offset
			elif self.angle==270:
				self.x+=self.center_offset
			self.moveDistance = 0
			self.currAngle = 0
			self.currX = self.x
			self.currZ = self.z
			viz.reset(viz.HEAD_POS)
			viz.translate(viz.HEAD_POS, self.x, self.y, self.z)
			viz.reset(viz.BODY_ORI)
			viz.rotate(viz.BODY_ORI, self.angle, 0, 0)
			viz.starttimer(self.NORMALIZE)
			self.callback = None
Пример #3
0
        def start(me):
            def clock(t):
                if t == timer_id:
                    callback()

            viz.callback(viz.TIMER_EVENT, clock)
            viz.starttimer(timer_id, period, viz.FOREVER)
Пример #4
0
def toggleRecording():
	global initialTime
	global isRecording
	global avatarDataRecordingTimerID
	initialTime = time.clock()
	isRecording = ~isRecording
	if(isRecording):
		print "Recording now."
		viz.starttimer(avatarDataRecordingTimerID, RECORDING_FREQUENCY, viz.PERPETUAL )
	else:
		print "Stopped recording."
		viz.killtimer(avatarDataRecordingTimerID)
	return isRecording
def main():

    viz.vsync(viz.ON)
    viz.window.setFullscreenMonitor([2])
    viz.setMultiSample(4)
    viz.MainWindow.clip(0.01, 200)

    viz.go(viz.FULLSCREEN)

    environment = viz.addChild("piazza.osgb")
    environment.setPosition(2.75, 0, -0.75)

    mocap = phasespace.Phasespace()

    head = mocap.get_rigidTracker("hmd")

    # DOES NOT ACCOUNT FOR RIGID BODY OFFSET DURING RESET

    # mocap.track_rigid('Resources/hmd-nvisMount.rb', center_markers=(1,2))
    head.link_pose(viz.MainView)

    # glove = mocap.track_points([8, 9, 10])

    paddle = mocap.track_rigid({17: (0, 0, 1), 19: (0, 0, 0), 20: (1, 0, 0), 22: (0, 1, 0)})

    mocap.start_thread()
    # mocap.start_timer()

    def log_mocap(timer_id):
        # print 'glove#9 pos {0[1]:.2f} {0[1]:.2f} {0[2]:.2f}'.format(*glove.get_marker(9))
        print "head    pos {0[0]:.2f} {0[1]:.2f} {0[2]:.2f}, quat {1[0]:.3f} {1[1]:.3f} {1[2]:.3f} {1[3]:.3f}".format(
            *head.get_pose()
        )
        print "main    " + str(viz.MainView.getPosition())
        # print 'paddle  pos {0[0]:.2f} {0[1]:.2f} {0[2]:.2f}, quat {1[0]:.3f} {1[1]:.3f} {1[2]:.3f} {1[3]:.3f}'.format(*paddle.get_pose())

    viz.callback(viz.TIMER_EVENT, log_mocap)
    viz.starttimer(0, 1, viz.FOREVER)

    def keydown(key):

        if key == "h":
            head.reset()
        if key == "H":
            head.save()
        elif key == "1":

            print "Marker Pos: " + str(mocap.get_MarkerPos(1))

    viz.callback(viz.KEYDOWN_EVENT, keydown)
def main():
    viz.setOption('viz.fullscreen.monitor', 1)
    viz.setOption('viz.window.width', 2 * 640)
    viz.setOption('viz.window.height', 480)
    viz.setMultiSample(4)
    viz.MainWindow.clip(0.01, 500)

    vizconfig.register(nvis.nvisorSX111())

    viz.go(viz.FULLSCREEN)

    piazza = viz.addChild('piazza.osgb')

    mocap = phasespace.Mocap('192.168.1.230')

    head = mocap.track_rigid('Resources/hmd-nvis.rb', center_markers=(0, 5))
    head.link_pose(viz.MainView)

    glove = mocap.track_points([8, 9, 10])

    paddle = mocap.track_rigid({
        17: (0, 0, 1),
        19: (0, 0, 0),
        20: (1, 0, 0),
        22: (0, 1, 0),
    })

    mocap.start_thread()

    #mocap.start_timer()

    def log_mocap(timer_id):
        print 'glove#9 pos {0[1]:.2f} {0[1]:.2f} {0[2]:.2f}'.format(
            *glove.get_marker(9))
        print 'head    pos {0[0]:.2f} {0[1]:.2f} {0[2]:.2f}, quat {1[0]:.3f} {1[1]:.3f} {1[2]:.3f} {1[3]:.3f}'.format(
            *head.get_pose())
        print 'paddle  pos {0[0]:.2f} {0[1]:.2f} {0[2]:.2f}, quat {1[0]:.3f} {1[1]:.3f} {1[2]:.3f} {1[3]:.3f}'.format(
            *paddle.get_pose())

    viz.callback(viz.TIMER_EVENT, log_mocap)
    viz.starttimer(0, 1, viz.FOREVER)

    def keydown(*args):
        head.reset()
        paddle.reset()

    viz.callback(viz.KEYDOWN_EVENT, keydown)
def main():
    viz.setOption('viz.fullscreen.monitor', 1)
    viz.setOption('viz.window.width', 2 * 640)
    viz.setOption('viz.window.height', 480)
    viz.setMultiSample(4)
    viz.MainWindow.clip(0.01, 500)

    vizconfig.register(nvis.nvisorSX111())

    viz.go(viz.FULLSCREEN)

    piazza = viz.addChild('piazza.osgb')

    mocap = phasespace.Mocap('192.168.1.230')

    head = mocap.track_rigid('Resources/hmd-nvis.rb', center_markers=(0, 5))
    head.link_pose(viz.MainView)

    glove = mocap.track_points([8, 9, 10])

    paddle = mocap.track_rigid({
      17:(0, 0, 1),
      19:(0, 0, 0),
      20:(1, 0, 0),
      22:(0, 1, 0),
    })

    mocap.start_thread()
    #mocap.start_timer()

    def log_mocap(timer_id):
        print 'glove#9 pos {0[1]:.2f} {0[1]:.2f} {0[2]:.2f}'.format(*glove.get_marker(9))
        print 'head    pos {0[0]:.2f} {0[1]:.2f} {0[2]:.2f}, quat {1[0]:.3f} {1[1]:.3f} {1[2]:.3f} {1[3]:.3f}'.format(*head.get_pose())
        print 'paddle  pos {0[0]:.2f} {0[1]:.2f} {0[2]:.2f}, quat {1[0]:.3f} {1[1]:.3f} {1[2]:.3f} {1[3]:.3f}'.format(*paddle.get_pose())

    viz.callback(viz.TIMER_EVENT, log_mocap)
    viz.starttimer(0, 1, viz.FOREVER)

    def keydown(*args):
        head.reset()
        paddle.reset()

    viz.callback(viz.KEYDOWN_EVENT, keydown)
	def PerformTurn(self,callback=None):
		self.callback = callback
		self.moveDistance=0
		self.lastTime = time.time()
		self.currAngle=0
		if 0 == self.angle:
			self.xOffset=0
			self.zOffset=self.center_offset
		if 90 == self.angle:
			self.xOffset=self.center_offset
			self.zOffset=0
		if 180 == self.angle:
			self.xOffset=0
			self.zOffset=-self.center_offset
		if 270 == self.angle:
			self.xOffset=-self.center_offset
			self.zOffset=0
		self.currX=self.x + self.xOffset
		self.currZ=self.z + self.zOffset
		viz.starttimer(self.GO_SPIN)
	def GoBackward(self,callback=None):
		if self.okMove.acquire(0):
			self.backwardmoves+=1
			self.callback = callback
			self.lastTime = time.time()
			self.moveDistance=0
			if 0 == self.angle:
				self.xSpeed=0
				self.zSpeed=-self.BACKWARD_SPEED
			if 90 == self.angle:
				self.xSpeed=-self.BACKWARD_SPEED
				self.zSpeed=0
			if 180== self.angle:
				self.xSpeed = 0
				self.zSpeed=self.BACKWARD_SPEED
			if 270== self.angle:
				self.xSpeed=self.BACKWARD_SPEED
				self.zSpeed=0
			self.currX=self.x
			self.currZ=self.z
			viz.starttimer(self.GO_FORWARD)
			return 1
		else: return 0
Пример #10
0
def __PlayNextSound():
    global SOUND_QUEUE, LAST_INDEX, PLAYING_SOUND, SOUND_FINISHED_CALLBACK

    if PLAYING_SOUND == None:
        # This shouldn't happen
        return

    # Search through the sound queue, starting at the last played sound
    # to find the next sound waiting to be played
    index = PLAYING_SOUND
    while index <= LAST_INDEX and not SOUND_QUEUE.has_key(index):
        index = index + 1

    if index <= LAST_INDEX:
        PLAYING_SOUND = index
        # play the next sound
        viz.playsound(SOUND_QUEUE[index]["filename"])

        # start a timer to tell us when the sound is finished
        viz.starttimer(SOUND_FINISHED_CALLBACK, SOUND_QUEUE[index]["length"])
    else:
        # No sounds were waiting to be played
        PLAYING_SOUND = None
def onAudioEnd(e): 
	global introAudio2
	if e.object is introAudio2 and e.event == viz.MEDIA_END: 
		print 'starting minute timer'
		viz.starttimer(MINUTE_TIMER, 40)
	def reset(self):
		print 'RESET WAS CALLED'
		global timerEnded
		timerEnded = False
		viz.starttimer(TIMER, self.__delay)
		viz.callback(viz.TIMER_EVENT,onTimer)
Пример #13
0
def run(CL, tracks, grounds, backgrounds, cave, driver, autofiles, wheel, save_prefix):
	
	DEBUG = False
	
	trialtime = tracks[list(tracks.keys())[0]].trialtime	
	if DEBUG: trialtime = 6
		
	wait_texture = setStage('dusk.png')	
	wait_col = list(np.mean(np.array([viz.BLACK,viz.SKYBLUE]).T, axis = 1))	
	
		
	#add audio files
	manual_audio = 'C:\\VENLAB data\\shared_modules\\textures\\490_200ms.wav'
	viz.playSound(manual_audio, viz.SOUND_PRELOAD)	
	def SingleBeep():
		"""play single beep"""
		viz.playSound(manual_audio)
	"""
	datacolumns = ('autofile_i','bend','maxyr',
	'onsettime','ppid','trialn','block','timestamp_exp','timestamp_trial',
	'world_x','world_z','world_yaw','swa', 
	'yawrate_seconds','turnangle_frames',
	'distance_frames','dt','wheelcorrection', 
	'steeringbias', 'autoflag', 'autofile')
	"""
	"""
			UpdateValues = []
		UpdateValues.append(yawrate)
		UpdateValues.append(turnangle)
		UpdateValues.append(distance)
		UpdateValues.append(dt)
		UpdateValues.append(SteeringWheelValue)
		UpdateValues.append(self.__Wheel_yawrate_adjustment)
	"""
	
	expid, ppid, block = save_prefix.split('_')
	columns = ('ppid','block','world_x','world_z','world_yaw','timestamp_exp','timestamp_trial','maxyr', 'onsettime', 'bend','dn','autoflag','yr_sec','yr_frames','distance_frames','dt','sw_value','wheelcorrection','sw_angle')	
	
	def update(num):		
		
		
		if UPDATE:
			
			trialtimer = viz.tick() - trialstart	
			if DEBUG: txtmode.message(str(onset) +'\n' + str(yr) + '\n' + str(round(trialtimer,2)))
			
			if AUTOFLAG:
				
				#read the corresponding entry on the playback_data
				if trialtimer <= onset:
					i, auto_row = next(playback_iter)
					#print(i, auto_row)
					dir = auto_row.bend							
					new_swa = auto_row.swa * dir * bend #these columns are named slightly differently to the final experiment data
					new_yr = auto_row.yr * dir * bend
					
					#move the wheel.									
					wheel.set_position(new_swa)	#set steering wheel to 							
				else:
					#driver.setAutomation(False)
					new_yr = 0 #off-tangent failure
			
			else:
				new_yr = None					
			
			#update position
			updatevals = driver.UpdateView(new_yr) 
			#return the values used in position update			
				
				
				#retrieve position and orientation
			pos = cave.getPosition()							
			yaw = vizmat.NormAngle(cave.getEuler()[0])			
						
			#record data	
			#columns = ('ppid', 'block','world_x','world_z','world_yaw','timestamp_exp','timestamp_trial','maxyr', 'onsettime', 'bend','dn','autoflag','yr_sec','yr_frames','distance_frames','dt','sw_value','wheelcorrection','sw_angle')	
			output = (ppid, block, pos[0], pos[2], yaw, viz.tick(), trialtimer, yr, onset, bend, dn, int(AUTOFLAG), updatevals[0], updatevals[1],updatevals[2], updatevals[3],updatevals[4],updatevals[5], updatevals[4]*90) #output array			
				
			#print(output)
		
			#self.OutputWriter.loc[self.Current_RowIndex,:] = output #this dataframe is actually just one line. 		
			OutputWriter.writerow(output)  #output to csv. any quicker?
			
	
	#call update every frame
	UPDATE = False
	
	viz.callback(viz.TIMER_EVENT, update)
	viz.starttimer(0,1.0/60.0,viz.FOREVER)
	
		
	txtmode = viz.addText("Mode",parent=viz.SCREEN)	
	#set above skyline so I can easily filter glances to the letter out of the data
	txtmode.setPosition(.05,.52)
	txtmode.fontSize(36)
	txtmode.color(viz.WHITE)	

	if not DEBUG: txtmode.message('A')
		
	print(CL)	
		
	for trial_i, (idx, trial) in enumerate(CL.iterrows()):
		
		#reset key trial variables 
		trialstart = viz.tick()
		AUTOFLAG = True
		driver.setAutomation(AUTOFLAG)
		
		#set up dataframe and csv writer
		OutputFile = io.BytesIO()
		OutputWriter = csv.writer(OutputFile)
		OutputWriter.writerow(columns) #write headers.
		
		bend = int(trial['Bend'])
		yr = trial['maxYR']
		dn = trial['Day/Night']
		onset = trial['OnsetTime']		
		key = str(bend)+'_'+str(yr)+'_' + dn
		#retrieve playback
		playback = autofiles[str(yr)]
		playback_iter = playback.iterrows()
		
		
		
		#only switch on update loop after retrieving parameters
		
		
		#pick track and make visible
		track = tracks[key]
		track.ToggleVisibility(1)
		
		ground = grounds[dn]
		ground.visible(viz.ON)
		
		viz.clearcolor(backgrounds[dn])
		if trial_i == 0:
			yield viztask.waitTime(2)
		else:
			yield viztask.waitTime(.5)
		
		
		#start the trial proper
		UPDATE = True
		
		#run trial
		def PlaybackReached():
			"""checks for playback limit or whether automation has been disengaged"""
			end = False
			#print(viz.tick() - trialstart)
			if (viz.tick() - trialstart) > trialtime: end = True
			return(end)
		
		def CheckDisengage():
			"""checks automation status of driver class """
			end = False
			auto = driver.getAutomation()
			if auto == False:end = True				
			return (end)

		#create viztask functions.
		waitPlayback = viztask.waitTrue( PlaybackReached )
		waitDisengage = viztask.waitTrue( CheckDisengage )
		
		d = yield viztask.waitAny( [ waitPlayback, waitDisengage ] )		

		if d.condition is waitPlayback:
			print ('end of trial reached')
			
		elif d.condition is waitDisengage:
			print ('Automation Disengaged')
			if not DEBUG: txtmode.message('M')
			
			AUTOFLAG = False				
			wheel.FF_on(.2)				
			SingleBeep()
			yield viztask.waitTime(trialtime - (viz.tick()-trialstart))
			
		#END OF STEERING TASK
		
		#reset trial
		track.ToggleVisibility(0)
		ground.visible(viz.OFF)
		driver.reset()
		wait_texture.visible(1)
		viz.clearcolor(wait_col)
		UPDATE = False
		if not DEBUG: txtmode.message('A')
		
		yield viztask.waitTime(.5)
		wait_texture.visible(0)
		UPDATE = True
		
		savename = save_prefix +'_'+str(trial_i)
		SaveData(OutputFile, savename)
	
	
	CloseConnections(wheel)
Пример #14
0
		# 02 05 End Trial: Close out the trial and reset values for next trial
		elif trial_stage == 'endtrial_02_05':
			
			# Clears the target pole
			leader.visible(viz.OFF)

			# End data collection for this trial
			data_collect = False
			
			# save the data of this trial			
			fileName = OUTPUT_DIR + NICKNAME + '_subj' + subject + '_trial' + str(trial_num).zfill(3) + '_' + condition + '.csv'
			with open(fileName, 'a') as file:
				file.write(data_batch)
	
			print 'End Trial ' + str(trial_num)
			
			# When trial_num is greater than TOTAL_TRIALS, end experiment
			if trial_num == TOTAL_TRIALS:
				is_freewalk = True
				goToStage('pretrial_00_01')
				trial_num = 1
			# Returns to Stage 1, resets clock
			else:
				trial_num += 1
				goToStage('pretrial_02_01')

# Restarts the loop, at a rate of 60Hz
viz.callback(viz.TIMER_EVENT,masterLoop)
viz.starttimer(0,1.0/HZ,viz.FOREVER)

viz.MainView.setEuler(0, 90, 0)


def onTimer(num):
    #Use the time ids to identify the timer.
    move_speed = 5

    if viz.MainWindow.isCulled(gplane1):
        print "gplane1 culled"

        gplane1.setPosition(0, 0, texture_z_size * 2,
                            viz.REL_GLOBAL)  #bring to driver pos

    if viz.MainWindow.isCulled(gplane2):
        print "gplane2 culled"

        gplane2.setPosition(0, 0, texture_z_size * 2,
                            viz.REL_GLOBAL)  #bring to driver pos

    if viz.key.isDown(viz.KEY_UP):
        viz.MainView.move([0, 0, move_speed * viz.elapsed()], viz.BODY_ORI)
    elif viz.key.isDown(viz.KEY_DOWN):
        viz.MainView.move([0, 0, move_speed * viz.elapsed()], viz.BODY_ORI)


#Register the timer callback.
viz.callback(viz.TIMER_EVENT, onTimer)
#Start both timers.
#The first will be repeated.
viz.starttimer(0, 1 / 60.0, viz.PERPETUAL)
Пример #16
0
		current_tool = tool_manager.getCurrentTool()
		if isinstance(current_tool, HistogramTool):
			current_tool.SetShader(shader_gradient)
			shader_gradient.ApplyShader( render_volume )

	if obj == transfer_shader_radio:
		print "Transfer shader activated"
		#Apply texture
		shader_transfer.ApplyShader( render_volume )
		render_volume.texture( transfer_function_manager.transfer_texture.getVizardTexture() ,unit = 2)

	if obj == light_placement_button and state == viz.DOWN:
		print 'Toggle light button'
		LIGHT_PLACEMENT_FLAG = not LIGHT_PLACEMENT_FLAG
		
			
def onTransferFunctionUpdate( *args, **kwargs):
	pass
	


Message_V2.messageManager.subscribe( TransferFunction.TransferFunction_Messages.message_transfer_function_update, onTransferFunctionUpdate)


viz.callback( viz.TIMER_EVENT, onUpdate )
viz.callback( viz.SLIDER_EVENT, onSlider )
viz.callback( viz.BUTTON_EVENT, onButton )
viz.callback( viz.MOUSE_MOVE_EVENT, onMouseMove )
viz.callback( viz.MOUSEDOWN_EVENT, onMouseDown )
viz.starttimer( 0, 1.0, viz.PERPETUAL )
Пример #17
0
        def start(me):
            def clock(t):
                if t == timer_id: callback()

            viz.callback(viz.TIMER_EVENT, clock)
            viz.starttimer(timer_id, period, viz.FOREVER)
Пример #18
0
	def loadModel(self, hbf):

		"""
		Alle Uhrzeiger im Modell hier referenzieren
		Reihenfolge muss mit updateTime übereinstimmen
		"""
		uhr1 = [
			hbf.getChild('SekundenzeigerVorn'),
			hbf.getChild('SekundenzeigerHinten'),
			hbf.getChild('MinutenzeigerVorn'),
			hbf.getChild('MinutenzeigerHinten'),
			hbf.getChild('StundenzeigerVorn'),
			hbf.getChild('StundenzeigerHinten')]

		uhr2 = [
			hbf.getChild('SekundenzeigerVorn.001'),
			hbf.getChild('SekundenzeigerHinten.001'),
			hbf.getChild('MinutenzeigerVorn.001'),
			hbf.getChild('MinutenzeigerHinten.001'),
			hbf.getChild('StundenzeigerVorn.001'),
			hbf.getChild('StundenzeigerHinten.001')]

		uhr3 = [
			hbf.getChild('SekundenzeigerVorn.002'),
			hbf.getChild('SekundenzeigerHinten.002'),
			hbf.getChild('MinutenzeigerVorn.002'),
			hbf.getChild('MinutenzeigerHinten.002'),
			hbf.getChild('StundenzeigerVorn.002'),
			hbf.getChild('StundenzeigerHinten.002')]

		uhr4 = [
			hbf.getChild('SekundenzeigerVorn.003'),
			hbf.getChild('SekundenzeigerHinten.003'),
			hbf.getChild('MinutenzeigerVorn.003'),
			hbf.getChild('MinutenzeigerHinten.003'),
			hbf.getChild('StundenzeigerVorn.003'),
			hbf.getChild('StundenzeigerHinten.003')]

		uhr5 = [
			hbf.getChild('SekundenzeigerVorn.004'),
			hbf.getChild('SekundenzeigerHinten.004'),
			hbf.getChild('MinutenzeigerVorn.004'),
			hbf.getChild('MinutenzeigerHinten.004'),
			hbf.getChild('StundenzeigerVorn.004'),
			hbf.getChild('StundenzeigerHinten.004')]

		uhr6 = [
			hbf.getChild('SekundenzeigerVorn.005'),
			hbf.getChild('SekundenzeigerHinten.005'),
			hbf.getChild('MinutenzeigerVorn.005'),
			hbf.getChild('MinutenzeigerHinten.005'),
			hbf.getChild('StundenzeigerVorn.005'),
			hbf.getChild('StundenzeigerHinten.005')]

		uhr7 = [
			hbf.getChild('SekundenzeigerVorn.006'),
			hbf.getChild('SekundenzeigerHinten.006'),
			hbf.getChild('MinutenzeigerVorn.006'),
			hbf.getChild('MinutenzeigerHinten.006'),
			hbf.getChild('StundenzeigerVorn.006'),
			hbf.getChild('StundenzeigerHinten.006')]

		uhr8 = [
			hbf.getChild('MinutenzeigerVorn.007'),
			hbf.getChild('MinutenzeigerHinten.007'),
			hbf.getChild('SekundenzeigerVorn.007'),
			hbf.getChild('SekundenzeigerHinten.007'),
			hbf.getChild('StundenzeigerVorn.007'),
			hbf.getChild('StundenzeigerHinten.007')]

		uhr9 = [
			hbf.getChild('SekundenzeigerVorn.008'),
			hbf.getChild('SekundenzeigerHinten.008'),
			hbf.getChild('MinutenzeigerVorn.008'),
			hbf.getChild('MinutenzeigerHinten.008'),
			hbf.getChild('StundenzeigerVorn.008'),
			hbf.getChild('StundenzeigerHinten.008')]

		uhr10 = [
			hbf.getChild('SekundenzeigerVorn.009'),
			hbf.getChild('SekundenzeigerHinten.009'),
			hbf.getChild('MinutenzeigerVorn.009'),
			hbf.getChild('MinutenzeigerHinten.009'),
			hbf.getChild('StundenzeigerVorn.009'),
			hbf.getChild('StundenzeigerHinten.009')]

		uhr11 = [
			hbf.getChild('SekundenzeigerVorn.010'),
			hbf.getChild('SekundenzeigerHinten.010'),
			hbf.getChild('MinutenzeigerVorn.010'),
			hbf.getChild('MinutenzeigerHinten.010'),
			hbf.getChild('StundenzeigerVorn.010'),
			hbf.getChild('StundenzeigerHinten.010')]

		self.uhren = [uhr1,uhr2,uhr3,uhr4,uhr5,uhr6,uhr7,uhr8,uhr9,uhr10,uhr11]

		viz.callback(viz.TIMER_EVENT, self.onTimer)
		viz.starttimer(1, 1, viz.PERPETUAL)
    print('Running Visualization Code ...\n\n\n')
    print('Attach View to Head = ', room.attachViewPortToHead)
    print('Save Images for RL = ', room.saveImagesForRL)
    print('Save Images for Data Set = ', room.saveImagesForDataSet)
    print('Ball Disappears = ', room.includeBlankDuration, '\n')
    if (room.attachViewPortToHead == False):
        #sets where the camera view is located
        #viz.MainView.setPosition([-0.46132529973983765, 1.8138036012649536, -1.4800882935523987])
        viz.MainView.setPosition(
            [0.27629128098487854, 1.9876298904418945, -3.3362717628479004])
        viz.MainView.setEuler([-18.816675186157227, 0.0, 0.0])
        #viz.MainView.setPosition([-1.8827998638153076, 2.381239414215088, 0.05993637815117836])
        #sets the angle at which the camera view is pointed
        viz.MainView.setEuler(3.1846203804016113, -0.0, 0.0)
    #lEyeOffsetMatrix = np.array([[1, 0, 0, -0.03],[0, 1, 0, 0], [0, 0, 1, 0],[0, 0, 0, 1]], dtype = float)
    #lEyeRotationMatrix = np.eye(4, dtype = float);
    #counter = 1
    #FrameNumber = TrialStartIndex[0] - 100;
    #FrameNumber = 1;
    #SetRotationAngle(1.6);
    #if the timer goes off go to the onTimer function
    value = np.array(room.rawDataFrame.viewPos.values[0])
    value = value + np.array([0.4, -1.4, 0])
    #print('First Value',value)
    room.male.setPosition(value[0], value[1],
                          value[2])  # - np.array([0,-1.5,0]))

    viz.callback(viz.KEYDOWN_EVENT, keyDown)
    viz.callback(viz.TIMER_EVENT, onTimer)
    viz.starttimer(1, TimeInterval, viz.FOREVER)
Пример #20
0
	def execute_actions (self, actList):
		# check if this is a valid list and if it contains at least one action
		try:
			if len(actList) > 0:
				print self._name.getMessage(), "executing...", actList
				ex = True
			else:
				ex = False
		except:
			ex = False
			pass
		
		if not ex: return
		#action list
		for action in actList:
			#get a list timer delay(s) (contained inside brackets, e.g. [10,20])
			if '[' in action:
				action, delay = self.parse_action(action)
			########## ENGINE ACTIONS ##############
			if action == 'turning_valve_on':
				self._factory.factory.addAction(vizact.call(self._factory.engine.E_openValve, 3))
			elif action == 'turning_valve_off':
				self._factory.factory.addAction(vizact.call(self._factory.engine.E_closeValve, 3))
			elif action == 'starting_engine':
				self._factory.factory.addAction(vizact.waittime(3))	#wait for valve animation
				self._factory.factory.addAction(vizact.call(self._factory.StartFactory))
			elif action == 'stopping_engine':
				self._factory.StopFactory()
			########## BOILER ACTIONS ##############
			elif action == 'loading_boiler':
				self._factory.boiler.OpenCloseHatch(True)
				self._factory.factory.addAction(vizact.waittime(2))
				self._factory.factory.addAction(vizact.call(self._factory.boiler.CoalAction, 1))
				#self._factory.factory.addAction(vizact.waittime(1))
				#self._factory.factory.addAction(vizact.call(self._factory.boiler.CoalAction, 2))
			elif action == 'starting_timer':
				viz.starttimer(10, delay[0], 0)	#timer for the first warning
				viz.starttimer(15, delay[1], 0)	#timer for the second warning
				viz.starttimer(20, delay[2], 0)	#timer for stopping factory
			elif action == 'stopping_timer':
				viz.killtimer(10)
				viz.killtimer(15)
				viz.killtimer(20)
			elif 'pressure' in action:
				#get the pressure and send it as an argument to the machine specified by the first word
				machine = action.partition('_')[0]
				pressure = action.rpartition('_')[2][:-3]	#get psi or rpm value
				exec('self._factory.'+machine+'.ChangePressure('+pressure+','+str(delay[0])+')')
			elif action == 'lighting_furnace':	#coals appear inside furnace and light up
				self._factory.boiler.CoalAction(2)
				self._factory.factory.addAction(vizact.waittime(2))
				self._factory.factory.addAction(vizact.call(self._factory.boiler.OpenCloseHatch, False))
			elif action == 'dying_away_fire':	#fire dies away and coals are wasted
				self._factory.boiler.CoalAction(3)
			elif action == 'renewing_fire':	#fire dies away and coals are wasted
				self._factory.boiler.CoalAction(4)
			elif action == 'exhausting_fire':	#fire dies away and coals are wasted
				self._factory.boiler.CoalAction(5)
				viz.starttimer(5, 5, 0)	#timer for waiting fire die out, before sending anim-finished
				
			########## MILL ACTIONS ##############
			elif 'loading_mill' in action:	#has * at the end
				if '*' in action:	#don't let the second player (no *) execute the animation again
					LR = action[-2:-1]
					viz.starttimer(ord(LR), 5, 0)	#timer while loading the olives -> anim-finished
					mill = 'mill'+ LR
					sackID = action[-3:-1]
					exec('self._factory.'+mill+'.SackAnim(\"'+sackID+'\")')
			elif 'starting_crash' in action:
				LR = action[-1:]
				mill = 'mill'+ LR
				exec('self._factory.'+mill+'.OlivesToPaste()')
			elif 'pouring_paste' in action:
				LR = action[-1:]
				mill = 'mill'+ LR
				viz.starttimer(ord(LR), 5, 0)	#timer while pouring the paste -> anim-finished
				exec('self._factory.'+mill+'.PasteInTank()')
			elif 'wasting_paste' in action:
				LR = action[-1:]
				mill = 'mill'+ LR
				viz.starttimer(ord(LR), delay[0], 0)	#timer while wasting the paste -> anim-finished
				exec('self._factory.'+mill+'.Damage(True)')
				exec('self._factory.'+mill+'.WastePaste()')
			elif 'transferring_tank' in action:
				if '*' in action:	#don't let the second player (no *) execute the action again
					LR = action[-2:-1]
					mill = 'mill'+ LR
					viz.starttimer(ord(LR), 10, 0)	#timer while transferring the tank -> anim-finshed
					exec('self._factory.'+mill+'.MoveTank()')
			elif 'finishing_transfer' in action:
				LR = action[-1:]
				mill = 'mill'+ LR
				viz.starttimer(ord(LR), 4, 0)	#timer while big tank fills up -> anim-finshed
			elif 'replenishing_sacks' in action:
				LR = action[-1:]
				mill = 'mill'+ LR
				exec('self._factory.'+mill+'.ReplenishSacks()')
			elif 'resetting_mill' in action:
				LR = action[-1:]
				mill = 'mill'+ LR
				exec('self._factory.'+mill+'.ResetMill()')
			elif 'timerM' in action:
				LR = action[-1:]
				action = action.replace(LR, '')	#delete the last character
				timerTag = action.partition('_')[2]
				timerCode = action.partition('_')[0][-1:]	#1=set timer, 0=kill timer
				#e.g., (1,5) -> set timer id=77 (76+1) or id=83 (82+1) for 5 secs
				#wasted is called with thick and hot and needs to expire later
				timers = {'dilute':1, 'thick':2, 'ready':3, 'hot':4, 'wasted':5}
				if int(timerCode) == 1:
					viz.starttimer(ord(LR)+timers[timerTag], delay[0], 0)
				else:
					viz.killtimer(ord(LR)+timers[timerTag])
					
			########## LOADER ACTIONS ##############
			elif action == 'serving_mat':
				self._factory.loader.MatOnTable()
			elif 'getting_pulp' in action:
				amount = delay[0]*.5
				self._factory.loader.PulpInTank(amount)
			elif action == 'scooping_pulp':
				self._CanFull(True)	# sent to player holding can
			elif 'filling_mat' in action:
				if '*' in action:	#don't let the second player (no *) execute the action again
					self._factory.loader.FillMat()
				if self._selected == 'canful':	#the one holding the can should...
					self._CanFull(False)	#empty the can being held
			elif action == 'picking_mat':
				if self.AddToToolbox('mat'):	#prevents picking the mat when inventory full
					viz.starttimer(200+self._player, .1, 0)	#send mat-picked event from this player
					self._feedback = 'picked'	#avoids displaying the 'undefined' message
					self.SelectTool('mat')		#select the mat from the toolbox
					self.HoldObject('mat')		#sets the mat as the holding object (cursor)
					self._factory.loader.PickMat()
			elif action == 'mat_as_tool':
				matObj = self._factory.loader.components['mat']
				self._factory.AddMatAsTool('matP', matObj)
				
			######## PRESS ACTIONS ###############
			elif 'loading_press' in action:
				LR = action[-1:]
				press = 'press'+ LR
				matsLoaded = eval('self._factory.'+press+'.LoadMat()')
				matsFull = delay[0]	#delay->number of mats to load before full
				if matsLoaded == matsFull:
					viz.starttimer(ord(LR)+501, 2, 0)	#timer for filling up press	
			elif action == 'dropping_mat':
				self.DropObject(putBack=False, matOnTray=True)
			elif 'fillingup_press' in action:
				LR = action[-1:]					#L:76, R:82
				press = 'press'+ LR
				exec('self._factory.'+press+'.FillUp()')
			elif 'starting_press' in action:	# called from the pump
				LR = action[-1:]
				viz.starttimer(ord(LR)+502, 1, 0)	#timer for staring press
			elif 'finishing_press' in action:	# called from the pump
				LR = action[-1:]
				viz.starttimer(ord(LR)+503, 1, 0)	#timer for finishing press
			elif 'pumping_oil_press' in action:	# called from the oil pump
				LR = action[-1:]
				viz.starttimer(ord(LR)+505, 1, 0)	#timer for emptying the oil tanks
			elif 'resetting_press' in action:	# called from the pump
				LR = action[-1:]
				viz.starttimer(ord(LR)+504, 1, 0)	#timer for releasing press
			elif 'releasing_press' in action:	# used as delay to send the 'anim-finished' event
				LR = action[-1:]
				press = 'press'+ LR
				viz.starttimer(ord(LR)+500, 10, 0)	#waiting to send anim-finished
				exec('self._factory.'+press+'.Releasing(10)')
			elif 'pressing_press' in action:
				LR = action[-1:]
				press = 'press'+ LR
				exec('self._factory.'+press+'.Pressing()')
			elif 'removing_mats' in action:
				LR = action[-1:]
				press = 'press'+ LR
				exec('self._factory.'+press+'.RestoreMats()')
			elif 'damaging_press' in action:
				LR = action[-1:]
				press = 'press'+ LR
				viz.starttimer(ord(LR)+500, delay[0], 0)	#waiting to send anim-finished
				exec('self._factory.'+press+'.Damage(True)')
			elif 'emptying_oil' in action:
				LR = action[-1:]
				press = 'press'+ LR
				exec('self._factory.'+press+'.PumpOil()')
				
			######## PUMP ACTIONS ###############
			elif 'starting_pump' in action:
				LR = action[-1:]
				pump = 'pump'+ LR
				func = 'self._factory.'+pump+'.ChangeGuide, 1'
				exec('self._factory.factory.addAction(vizact.call('+func+'))')
				func = 'self._factory.'+pump+'.StopCrazy'
				exec('self._factory.factory.addAction(vizact.call('+func+'))')
				func = 'self._factory.'+pump+'.SetMotion'
				exec('self._factory.factory.addAction(vizact.call('+func+'))')
			elif 'stopping_pump' in action:
				LR = action[-1:]
				pump = 'pump'+ LR
				func = 'self._factory.'+pump+'.ChangeGuide, -1'
				exec('self._factory.factory.addAction(vizact.call('+func+'))')
				func = 'self._factory.'+pump+'.StartCrazy'
				exec('self._factory.factory.addAction(vizact.call('+func+'))')
				func = 'self._factory.'+pump+'.EndMotion'
				exec('self._factory.factory.addAction(vizact.call('+func+'))')
			elif 'opening_bypass' in action:
				LR = action[-1:]
				pump = 'pump'+ LR
				exec('self._factory.'+pump+'.TurnValve(1)')
			elif 'closing_bypass' in action:
				LR = action[-1:]
				pump = 'pump'+ LR
				exec('self._factory.'+pump+'.TurnValve(-1)')
			elif 'lifting_bar' in action:
				LR = action[-1:]
				pump = 'pump'+ LR
				exec('self._factory.'+pump+'.LiftBar(True)')
			elif 'dropping_bar' in action:
				LR = action[-1:]
				pump = 'pump'+ LR
				exec('self._factory.'+pump+'.LiftBar(False)')
			elif 'damaging_pump' in action:
				LR = action[-1:]
				pump = 'pump'+ LR
				viz.starttimer(ord(LR)+100, delay[0], 0)
			elif 'timerP' in action:
				LR = action[-1:]
				action = action.replace(LR, '')	#delete the last character
				timerTag = action.partition('_')[2]
				timerCode = action.partition('_')[0][-1:]	#1=set timer, 0=kill timer
				#e.g., (101,20) -> set timer id=177 (76+101) or id=184 (82+102) for 20 secs
				#safe+done=60 (the duration of the pressing animation)
				#10, 60, 30 secs should be also set in the pump's ChangePressure function 
				timers = {'good':101, 'safe':102, 'done':103, 'high':104, 'max':105}
				if int(timerCode) == 1:
					viz.starttimer(ord(LR)+timers[timerTag], delay[0], 0)
				else:
					viz.killtimer(ord(LR)+timers[timerTag])
					
			######## OIL PUMP ACTIONS ###############
			elif action == 'start_pumping':
				self._factory.oilPump.ChangeGuide(1)
			elif action == 'stop_pumping':
				self._factory.oilPump.ChangeGuide(-1)
			elif action == 'filling_lavals':
				self._factory.oilPump.OilPourInLavals(1)
			elif action == 'emptying_tanks':
				self._factory.oilPump.OilPourInLavals(0)
			elif 'timerO' in action:
				timerTag = action.partition('_')[2]
				timerCode = action.partition('_')[0][-1:]	#1=set timer, 0=kill timer
				timers = {'tanks':(701,5), 'lavals':(702,10)}
				if int(timerCode) == 1:
					viz.starttimer(timers[timerTag][0], timers[timerTag][1], 0)
				else:
					viz.killtimer(timers[timerTag][0])

			######## LAVAL ACTIONS ###############
			elif action == 'detaching_laval_belt':
				self._factory.lavalR.DetachBelt()
			elif 'attaching_belt' in action:	#has * at the end
				if '*' in action:	#execute the action only the first time (second no *)
					print "ATTACHING BELTTTTTTTTTTT by", self._name.getMessage()
					self._factory.lavalR.AttachBelt()
				if self._selected == 'belt':#the one holding the belt should...	
					self.DropObject(False)	#drop it without putting in back in place
			elif 'starting_laval' in action:
				LR = action[-1:]
				laval = 'laval'+ LR
				exec('self._factory.'+laval+'.ChangeGuide(1)')
			elif 'stopping_laval' in action:
				LR = action[-1:]
				laval = 'laval'+ LR
				exec('self._factory.'+laval+'.ChangeGuide(-1)')
			elif 'starting_separation' in action:
				LR = action[-1:]
				laval = 'laval'+ LR
				exec('self._factory.'+laval+'.StartSeparation(1)')
			elif 'stopping_separation' in action:
				LR = action[-1:]
				laval = 'laval'+ LR
				exec('self._factory.'+laval+'.StartSeparation(0)')
			elif 'transferring_pitcher' in action:
				if '*' in action:	#don't let the second player execute the animation again
					LR = action[-2:-1]
					laval = 'laval'+ LR
					viz.starttimer(400+ord(LR), 7, 0)	#timer while transferring the pitcher -> anim-finshed
					exec('self._factory.'+laval+'.MovePitcher('+str(delay[0])+')')
			elif 'damaging_laval' in action:
				LR = action[-1:]
				laval = 'laval'+ LR
				viz.starttimer(ord(LR)+400, delay[0], 0)	#waiting to send anim-finished
				exec('self._factory.'+laval+'.Damage(True)')
			elif 'timerL' in action:
				LR = action[-1:]
				action = action.replace(LR, '')	#delete the last character
				timerTag = action.partition('_')[2]
				timerCode = action.partition('_')[0][-1:]	#1=set timer, 0=kill timer
				#e.g., (401,10) -> set timer id=477 (76+401) or id=484 (82+402) for 10 secs
				#10, 30, 30 secs should be also set in the laval's ChangePressure function 
				timers = {'start':401, 'done':402, 'critical':403, 'max':404}
				if int(timerCode) == 1:
					viz.starttimer(ord(LR)+timers[timerTag], delay[0], 0)
				else:
					viz.killtimer(ord(LR)+timers[timerTag])
			
			######## SCALE ACTIONS ###############
			elif action == 'pitcher_on_scale':	#called from the lavals
				viz.starttimer(801, 1, 0)
			elif action == 'weighing_pitcher':	#increase counter by delay[1] lbs in delay[0] secs
				self._factory.scale.WeighPitcher(delay[0], delay[1], delay[2])
			elif 'timerS' in action:
				viz.starttimer(802, delay[0], 0)
			elif action == 'finishing_production':
				viz.starttimer(803, delay[0], 0)
			elif action == 'finishing_game':
				self._mapWin.GameFinish(delay[0])
			elif action == 'save_data':
				viz.starttimer(2000, 0, 0)
			
			####### WATER PIPE ACTIONS [PRACTICE] ######
			elif 'detaching_pipe' in action:
				self._factory.waterPipe.DetachPipe()
			elif 'attaching_pipe' in action:
				if '*' in action:
					self._factory.waterPipe.AttachPipe()
				if self._selected == 'pipe':#the one holding the pipe should...	
					self.DropObject(False)	#drop it without putting in back in place
			elif action == 'opening_valve':
				self._factory.waterPipe.OpenValve(2)
			elif action == 'closing_valve':
				self._factory.waterPipe.CloseValve(2)
				viz.starttimer(1000, 10, 0)
			elif action == 'damaging_pipe':
				viz.starttimer(1000, delay[0], 0)
				self._factory.waterPipe.Damage(True)
			elif action == 'resetting_pipe':
				self.AddToWorld('pipe')
			elif 'timerW' in action:
				timerTag = action.partition('_')[2]
				timerCode = action.partition('_')[0][-1:]	#1=set timer, 0=kill timer
				timers = {'done':1001, 'high':1002, 'max':1003}
				if int(timerCode) == 1:
					viz.starttimer(timers[timerTag], delay[0], 0)
				else:
					viz.killtimer(timers[timerTag])
			
			####### WHEEL BARROW ACTIONS [PRACTICE] ######
			elif 'moving_barrow' in action:
				if '*' in action:
					self._factory.wheelBarrow.MoveBarrow()
			elif action == 'reset_delay':
				viz.starttimer(1010, delay[0], 0)
			elif action == 'resetting_barrow':
				self._factory.wheelBarrow.ResetBarrow()
			
			# CHECK IF IN 1P CONDITION AND REMOVE SECOND PLAYER DEMAND
			elif 'enable1P' in action:
				otherAct = action.partition('_')[2]
				self.EnablePlayer1ForMultiInput(otherAct)
				
			# REMOVING SMOKE FROM MACHINERY
			elif 'removing_smoke' in action:
				mach = action.rpartition('_')[2]
				exec('self._factory.'+mach+'.Damage(False)')
				
			# ALERTS ON MACHINERY
			elif 'error' in action:
				mach = action.partition('_')[2]
				machPos = self._factory.machines[mach].object.getPosition()
				errorCode = action.partition('_')[0][-1:]	#1=error on, 0=error off
				self._mapWin.ShowErrorOnMap(mach, machPos, int(errorCode))
				#check if any of the players is near a machine and update their alert panels
				for p in self.PLAYERS.values():
					p.CheckForAlertNearMachine(mach, int(errorCode))
			
			# SCORE KEEPING
			elif 'score' in action:
				print "Points:", delay[0]
				self._mapWin.UpdateScore(delay[0])
			elif action == 'revealing_total_counter':
				self._mapWin.ShowTotalScore()
			elif action == 'increasing_total':
				self._mapWin.IncreaseOilTotal(delay[0], delay[1])
Пример #21
0
def translate():
    viz.callback(viz.TIMER_EVENT, transport_vhil.onTimerMoveDown)
    viz.starttimer(transport_vhil.moveDownWithTimerFunc, 0, 100)
Пример #22
0
		# save the oculus orientation for next frame
		ovrEulerOld = ovrEuler

	
	if DATA_COLLECT:
		# write data to buffer		
		data = OVRTracker.getEuler() + ISTracker.getEuler() + virtual.getEuler()
		strData = [str(round(t,4)) for t in data+[time]]
		strData = ','.join(strData)+'\n'
		dataBuffer = dataBuffer + strData
		

		# write buffer to file
		if frame % 450 == 0:
			fileName = OUTPUT_DIR + 'sensorfusion' + timeID + '.csv'
			file = open(fileName, 'a')
			file.write(dataBuffer)
			dataBuffer = ''
			file.close()
			print(data)


# Restarts the loop, at a rate of 90 Hz
viz.callback(viz.TIMER_EVENT,masterLoop)
viz.starttimer(0,1.0/90,viz.FOREVER)





    FrameNumber = FrameNumber + 1 
        #time.sleep(1)


if __name__ == '__main__':
    
    global lEyeOffsetMatrix, lEyeRotationMatrix;
    global FrameNumber, counter, TrialStartIndex, TrialEndIndex;
    global nearW,nearH;
    
    nearH = 1.2497;
    nearW = 1.5622;
    viz.setMultiSample(4)
    viz.fov(60)
    viz.go()
    ExtractDataFromMatFile('RawMat_exp_data-2014-10-10-11-35.mat');
    CreateTheRoom()
    CreateVisualObjects()
    #sets where the camera view is located
    viz.MainView.setPosition([-0.95528644323349, 1.6438825130462646, -0.6167752742767334])
    #sets the angle at which the camera view is pointed
    viz.MainView.setEuler(10.763678550720215, -0.0, 0.0)
    lEyeOffsetMatrix = np.array([[1, 0, 0, -0.03],[0, 1, 0, 0], [0, 0, 1, 0],[0, 0, 0, 1]], dtype = float)
    lEyeRotationMatrix = np.eye(4, dtype = float);
    counter = 1
    FrameNumber = TrialStartIndex[0] - 100;
    SetRotationAngle(1.6);
    #if the timer goes off go to the onTimer function
    viz.callback(viz.TIMER_EVENT,onTimer)
    viz.starttimer(1, .077, viz.FOREVER)
Пример #24
0
	global grab
	#print 'analog getData', analog.getData()
	#add the analog data to a list so that interactions can be made
	leap = analog.getData()
	#if a hand is present (stops movement when hand is taken away)
	if leap[98] > 0.3:
		#if gesture is a fist (grab)
		if leap[96] >= 0.5:
			if grab is None:
			#grab the object
				grab = viz.grab(view, h)
		elif leap[96] < 0.5:
			if grab is not None:
				grab.remove()
				grab = None
		if leap[2] < -40:
			view.move([0,0,MOVE_SPEED*viz.elapsed()],viz.BODY_ORI)
		if leap[2] > 40:
			view.move([0,0,-MOVE_SPEED*viz.elapsed()],viz.BODY_ORI)
		if leap[0] < -40:
			view.setEuler([-TURN_SPEED*viz.elapsed(),0,0],viz.BODY_ORI,viz.REL_PARENT)
		if leap[0] > 40:
			view.setEuler([TURN_SPEED*viz.elapsed(),0,0],viz.BODY_ORI,viz.REL_PARENT)
	
	
#the main runtime loop for the program
viz.starttimer( 0, 1, viz.FOREVER )

#timer called at an update rate, meaning for 0 it will be called every frame, calling the function onTimer
vizact.ontimer(0, update)
	def MovementTimer(self,num):
		self.newTime = time.time()
		deltaTime = (self.newTime-self.lastTime)/(1./60.)
		self.lastTime = self.newTime
		if num == self.GO_FORWARD:
			# going forward 
			xDistance=self.xSpeed * deltaTime
			zDistance=self.zSpeed * deltaTime
			self.currZ = self.currZ + zDistance
			self.currX = self.currX + xDistance
			self.moveDistance=self.moveDistance+(((xDistance)**2+(zDistance)**2)**0.5)
			# move camera forward
			viz.reset(viz.HEAD_POS)
			viz.translate(viz.HEAD_POS, self.currX, self.currY, self.currZ)
			if  self.moveDistance < self.scale:
				# keep moving forward
				viz.starttimer(self.GO_FORWARD)
			else:
				# done moving forward, normalize current position
				if self.zSpeed>0:
					self.z=self.z+self.scale
				elif self.zSpeed<0:
					self.z=self.z-self.scale
				elif self.zSpeed==0:
					self.z=self.z

				if self.xSpeed>0:
					self.x=self.x+self.scale
				elif self.xSpeed<0:
					self.x=self.x-self.scale
				elif self.xSpeed==0:
					self.x=self.x
					
				viz.reset(viz.HEAD_POS)
				viz.translate(viz.HEAD_POS, self.x, self.y, self.z)
				viz.starttimer(self.NORMALIZE)
		elif num == self.MISSKEY :
			print 'Misskey??????????????????'
		elif num == self.GO_SPIN:
			# do rotation
			if abs(self.currAngle) < 90:
				self.currAngle = self.currAngle + self.turnSpeed * deltaTime
				if abs(self.currAngle) < 90:
					viz.reset(viz.BODY_ORI)
					viz.rotate(viz.BODY_ORI, self.angle+self.currAngle, 0, 0)
					
					# Lazy Susan rotation:
					#   math's sin/cos use radians, so must convert from degrees.
					#   Also, math's angles are offset from viz's by 90 degrees, so use sin for x, cos for z
					radians = (self.angle+self.currAngle)*math.pi/180.0
					xoff = -math.sin(radians)*self.center_offset+self.xOffset
					zoff = -math.cos(radians)*self.center_offset+self.zOffset
					viz.reset(viz.HEAD_POS)
					viz.translate(viz.HEAD_POS, self.x+xoff, self.y, self.z+zoff)
					
				# keep rotating
				viz.starttimer(self.GO_SPIN)
			else:
				# done rotating, normalize angle
				self.angle+=self.currAngle
				self.angle=int(round(self.angle/90.0)*90) #Round to the nearest 90 degrees
				self.angle=self.angle%360
				viz.reset(viz.BODY_ORI)
				viz.rotate(viz.BODY_ORI, self.angle, 0, 0)

				if self.angle==0:
					self.x=self.currX
					self.z=self.currZ-self.center_offset
				elif self.angle==90:
					self.x=self.currX-self.center_offset
					self.z=self.currZ
				elif self.angle==180:
					self.x=self.currX
					self.z=self.currZ+self.center_offset
				elif self.angle==270:
					self.x=self.currX+self.center_offset
					self.z=self.currZ
				
				viz.reset(viz.HEAD_POS)
				viz.translate(viz.HEAD_POS, self.x, self.y, self.z)
				
				viz.starttimer(self.NORMALIZE)
		elif num == self.NORMALIZE:
			self.currAngle = 0
			self.currX = self.x
			self.currZ = self.z
			self.okMove.release()
			if self.callback:
				self.callback()
			self.callback = None
		else:
			# call handler for some other timer event
			for (key,func) in self.EVENTS:
				if num == key:
					func()
Пример #26
0
    textFileName = 'exp_data-2015-10-25-22-29'#'exp_data-2015-10-25-18-35'#'exp_data-2015-10-6-20-8'#'exp_data-2015-9-30-14-26'#'exp_data-2015-9-25-20-34'#'exp_data-2015-8-18-18-34'# 'exp_data-2015-4-24-13-34'

    myVisualization = visualization(textFileName)
    myVisualization.extractDataFromMatFile()#'Exp_RawMat_calib_data-2015-5-12-21-45.mat');
    myVisualization.createTheRoom()
    myVisualization.createVisualObjects()
    #sets where the camera view is located
    viz.MainView.setPosition([0.4033511281013489, 1.7814747095108032, -1.921712040901184])
    
    #sets the angle at which the camera view is pointed
    viz.MainView.setEuler([0.251657485961914, -0.0, 0.0])
    #lEyeOffsetMatrix = np.array([[1, 0, 0, -0.03],[0, 1, 0, 0], [0, 0, 1, 0],[0, 0, 0, 1]], dtype = float)
    #lEyeRotationMatrix = np.eye(4, dtype = float);
    counter = 1
    myVisualization.setRotationAngle(5.5);
    #if the timer goes off go to the onTimer function
    viz.callback(viz.TIMER_EVENT,myVisualization.onTimer)
    viz.starttimer(1, TimeInterval, viz.FOREVER)
    # Go fullscreen on monitor 1
    viz.window.setFullscreenMonitor(2)
    vizact.onkeydown('v', myVisualization.updateViewPoint)

    point0 = np.array([4.0,0.0, -5.0])
    point1 = np.array([-8.0,5.0, 0.0])
    line = np.array([0.0,0.0,6.0])
    planeNormal = np.array([0.0,0.0,2.0])
    print 'Test =', findLinePlaneIntersection(point0, line, planeNormal, point1)
    
    vizact.onkeydown('b', viz.window.startRecording, 'test01.avi' ) 
    vizact.onkeydown('e', viz.window.stopRecording )
    myVisualization.male.visible(viz.OFF)