示例#1
1
	def bindKeys(self):
		self._keyBindings.append(vizact.onkeydown('o', model.proxManager.setDebug, viz.TOGGLE)) #debug shapes
		self._keyBindings.append(vizact.onkeydown(' ', self.grab)) #space select
		self._keyBindings.append(vizact.onkeydown('65421', self.grab)) #numpad enter select
		self._keyBindings.append(vizact.onkeydown(viz.KEY_ALT_R, self.snapCheck))
		self._keyBindings.append(vizact.onkeydown(viz.KEY_ALT_L, self.snapCheck))
		self._keyBindings.append(vizact.onkeyup(' ', self.release))
		self._keyBindings.append(vizact.onkeyup('65421', self.release))
		self._keyBindings.append(vizact.onkeydown('65460', self.viewcube.toggleModes)) # Numpad '4' key
		self._keyBindings.append(vizact.onkeydown(viz.KEY_CONTROL_R, self.solve))
    def setup_mocap(self, motion):
        self.mocap = vrlab.Phasespace('192.168.1.230', postprocess=True)
        self.mocap.start_thread()

        left_finger_id = None
        right_finger_id = None
        if motion == 'suit':
            self.head = self.mocap.track_rigid(6, center_markers=(3, 5))
            self.motion = self.mocap.track_points(range(6, 50))
            left_finger_id = 25
            right_finger_id = 13
        elif motion == 'glove':
            self.head = self.mocap.track_rigid([0, 2, 4, 6, 8, 10], [4, 8])
            self.motion = self.mocap.track_points([38, 40, 42, 44])
            left_finger_id = 44
            right_finger_id = 0
        else:
            assert False, 'unknown motion source "{}"'.format(motion)

        self.head.link_pose(viz.MainView)
        vizact.onkeydown('r', self.head.reset)

        if left_finger_id:
            self.motion.link_marker(left_finger_id, self.left_finger)
        if right_finger_id:
            self.motion.link_marker(right_finger_id, self.right_finger)
示例#3
0
def main():
	global masterTimerG, recordingTimer
	setUp()
	masterTimerG = vizact.ontimer(0, masterTimer)
	#recordingTimer = vizact.ontimer(0, recordCurrentSubjectStatus)
	
	if not KEYBOARD_NAVIGATE:
		addKeyPresses()
	else:
		# Setup keyboard/mouse tracker
		tracker = vizcam.addWalkNavigate(moveScale=10.0)
		tracker.setPosition([0,1.8,0])
		viz.link(tracker,viz.MainView)
		viz.mouse.setVisible(False)
		def printLocation():
			print viz.MainView.getPosition(), viz.MainView.getEuler()
		vizact.onkeydown('p', printLocation)
	
	
	#Add Wiimote support
#	wii = viz.add('wiimote.dle')
#	#Connect to first available wiimote
#	wiimote = wii.addWiimote()
#	wiimote.led = wii.LED_4
#	#Add button functions
#	vizact.onsensordown(wiimote,wii.BUTTON_A,TurnFlyingOn)
#	vizact.onsensordown(wiimote,wii.BUTTON_B,TurnFlyingOff)
#	vizact.onsensordown(wiimote,wii.BUTTON_1,endChildHappy)
#	
	#Hacky bug fix below, I apologize -Mark
	if not FLYING_F and YOKE_F:
		viztask.schedule(fixStartHeliPos) 
示例#4
0
    def __init__(self):

        self.canvas = viz.addGUICanvas(scene=viz.Scene2)
        canvas = self.canvas

        # Compatibility for all display types
        canvas.setCursorSize([25, 25])
        canvas.setCursorPosition([0, 0])

        #init keybindings
        self.keybindings = []
        self.keybindings.append(vizact.onkeydown(viz.KEY_RETURN,
                                                 self.nextMenu))
        self.keybindings.append(vizact.onkeydown(viz.KEY_ESCAPE,
                                                 self.exitGame))

        #init menus
        self.mainMenu = MainMenu(canvas, self)
        self.modeMenu = ModeMenu(canvas, self)
        self.layerMenu = LayerMenu(canvas, self)
        self.loadingScreen = LoadingScreen()
        self.inGameMenu = InGameMenu(canvas, self)

        #stating menu display path
        self.menuOrder = [
            self.mainMenu, self.modeMenu, self.layerMenu, self.inGameMenu
        ]

        self.activeMenu = self.mainMenu
示例#5
0
def togRecording():
	recSound.play()
	if(file != None):
		newthread = viz.director(hf_playback.saveUpdateLoop, avatar, file)
		vizact.onkeydown(viz.KEY_ESCAPE, hf_playback.cleanup, file, newthread)
	touchcube.wakeTouchCubes()
	hf_playback.toggleRecording()
示例#6
0
	def __init__(self):

		self.canvas = viz.addGUICanvas(scene = viz.Scene2)
		canvas = self.canvas
		
		
		# Compatibility for all display types
		canvas.setCursorSize([25,25])
		canvas.setCursorPosition([0,0])
	
		#init keybindings
		self.keybindings = []
		self.keybindings.append(vizact.onkeydown(viz.KEY_RETURN, self.nextMenu))
		self.keybindings.append(vizact.onkeydown(viz.KEY_ESCAPE, self.exitGame))
		
		#init menus
		self.mainMenu		= MainMenu(canvas, self)
		self.modeMenu		= ModeMenu(canvas, self)
		self.layerMenu		= LayerMenu(canvas, self)
		self.loadingScreen 	= LoadingScreen()
		self.inGameMenu		= InGameMenu(canvas, self)
		
		#stating menu display path
		self.menuOrder = [self.mainMenu, self.modeMenu, self.layerMenu, self.inGameMenu]
		
		self.activeMenu = self.mainMenu
示例#7
0
	def __init__(self,use_keyboard = True, desktop_mode = False):
		
		caveapp.CaveApplication.__init__(self,desktop_mode) #call constructor of super class, you have to do this explicitly in Python		
		#self.wand = vizshape.addAxes() #load axis model to represent the wand (WALL FFS!)
		
		# Add skybox
		sky = viz.add(viz.ENVIRONMENT_MAP,'alien/jajalien1.jpg')
		skybox = viz.add('skydome.dlc')
		skybox.texture(sky)
		
		# First light added seems to be ignored....
		# Add lighting
		dummy = viz.addLight()
		light = viz.addLight()
		light.position(0, 0, 0)
		light.color([0.8, 1, 0.8])
		
		self.use_keyboard = use_keyboard #store if we want to use the keyboard
		#self.time = 0.0 #note that to 0.0 is important because it is a double precision floating point number
		
		self.speed = 400.0 #--four-- meters per second
		originTracker = self.cavelib.getOriginTracker()
		#originTracker.setPosition([-100,100,0],viz.REL_LOCAL)
		self.returnToStart()
		self.yaw = 90
		self.startSet=0
		self.joystickpressed=0
		
		vizact.onkeydown(' ', viz.setDebugSound3D, viz.TOGGLE)
示例#8
0
def recordViewAnimation():
    ### replace with your own application setup
    import viz
    import vizcam
    import vizact

    viz.setMultiSample(4)

    viz.go()

    vizcam.WalkNavigate()

    piazza = viz.addChild("piazza.osgb")
    ###

    ### Add this at the bottom
    '''
	 Create an AnimationPathRecorder and link it to any node, which needs to have it's transformation documented.
	 If 'start' is set to True the recording will start automatically, otherwise you need to start manually.
	 you can specify the file name under which the animation will be saved. '.txt' is automatically added.
	'''
    rec = AnimationPathRecorder(start=False)
    viz.link(viz.MainView, rec)

    # toggle path recording and saving finished recording to a file named 'test_animation.txt'
    def toggleRecord(rec):
        if rec.isRunning():
            rec.stop()
            rec.writeToFile("test_animation")
            print "Animation path saved to test_animation.txt"
        else:
            rec.start()
            print "Animation path recording started."

    vizact.onkeydown('r', toggleRecord, rec)
示例#9
0
    def __init__(self, room, size, marker_num, hand='left'):

        VisualObject.__init__(self, room=room, shape='sphere', size=size)

        # remove the sphere and add the baseball glove
        self.vis_node.remove()
        model_path = 'res/glove_{}.OSGB'.format(hand)
        try:
            self.vis_node = viz.addChild(model_path)
        except:
            print 'Hand must be left or right.'

        # setup position and orientation tracking
        glove_tracker = ppt.add_tracker(1)
        isense = viz.add('intersense.dle')
        self.ori_tracker = isense.addTracker(port=0)
        self.ori_tracker.setCompass(0)
        self.ori_tracker.setEnhancement(0)
        self.ori_tracker.resetHeading()
        vizact.onkeydown('i', self.ori_tracker.resetHeading)
        if hand == 'left':
            pre_trans = [0.04, -0.02, 0]
        else:
            pre_trans = [-0.04, -0.02, 0]
        link = ppt.link(tracker=glove_tracker, target=self.vis_node, ori=self.ori_tracker, pre_trans=pre_trans)

        # setup physics object
        # TODO: do we really want this?
        self.toggleUpdatePhysWithVis()
示例#10
0
	def __init__(self):
		#init canvas and create themes for the test panel
		self.canvas = viz.addGUICanvas(align = viz.ALIGN_CENTER_CENTER)
		self.canvas.setPosition(0,0,0)
		viz.mouse.setVisible(False)
		self.name = 'test'
		self._theme = viz.Theme()
		self._theme.borderColor = (0.1,0.1,0.1,1)
		self._theme.backColor = (0.4,0.4,0.4,1)
		self._theme.lightBackColor = (0.6,0.6,0.6,1)
		self._theme.darkBackColor = (0.2,0.2,0.2,1)
		self._theme.highBackColor = (0.2,0.2,0.2,1)
		self._theme.textColor = (1,1,1,1)
		self._theme.highTextColor = (1,1,1,1)
		
		#initialize test panel
		vizdlg.Panel.__init__(self, parent = self.canvas, theme = self._theme, align = viz.ALIGN_CENTER_TOP, fontSize = 15)
		self.visible(viz.OFF)
		self.setScale(*[i*config.menuScale[self.name] for i in [1,1,1]])
		self.alpha(0.6)
		
#		#title
		title = vizdlg.TitleBar('INSTRUCTIONS')
		self.addItem(title, align = viz.ALIGN_CENTER_TOP)
		
		#bones to be snapped. source snapped to target.
		source = 'a'*20
		self.sourceText = viz.addTextbox(parent = self.canvas)
		self.sourceText.setLength(1.5)
		target = 'a'*20
		self.targetText = viz.addTextbox(parent = self.canvas)
		self.targetText.setLength(1.5)
		
		#instructions 
		self.Instruct1 = self.addItem(viz.addText('Snap the: ', parent = self.canvas), align = viz.ALIGN_CENTER_TOP)
		self.sourceCommand = self.addItem(self.sourceText, align = viz.ALIGN_CENTER_TOP)
		self.Instruct2 = self.addItem(viz.addText('To the: ', parent = self.canvas), align = viz.ALIGN_CENTER_TOP)
		self.targetCommand = self.addItem(self.targetText, align = viz.ALIGN_CENTER_TOP)
		
		#render canvas
		
		if config.dispMode == config.DisplayMode.monitor:
			self.canvas.billboard(viz.BILLBOARD_YAXIS)
			self.canvas.setPosition(-2,0,0)
			self.canvas.setBackdrop(viz.ALIGN_CENTER_TOP)
			

		if config.dispMode == config.DisplayMode.oculus:

			bb = self.canvas.getBoundingBox()
			self.canvas.setRenderWorldOverlay([bb.width*1, bb.height*1], fov = bb.height, distance = 0.4)
			self.canvas.setPosition(0,0.05,0)
			self.canvasViewPos = self.canvas.getPosition()
			self.canvas.setEuler(0,15,0)
			self.canvas.setPosition(0, -5, 0)
			self.canvasHidePos = self.canvas.getPosition()
			viztask.schedule(self.updatePanelPos())
			
		vizact.onkeydown(viz.KEY_ESCAPE, self.toggle)
def load(sceneRef=viz.MainScene):
  global SCENE
  SCENE = sceneRef # TODO: Add scene params to all viz.add calls, etc in this module and submodules
  
  #Add audio
  global introAudio
  introAudio = viz.addAudio('Audio/Bus Scene/BusIntroduction.wav')
  global ambientAudio
  ambientAudio = viz.addAudio('Audio/Bus Scene/BusAmbientNoise.wav')
  
  
  #add bus
  BUS_OBJ_SCALE = .0365
  BUS_OSGB_SCALE = 35
  curscale = BUS_OSGB_SCALE
  bus = vizfx.addChild('bus_obj/Bus_Final_Scene1.OSGB', scene=SCENE)
  bus.setScale([curscale]*3)
  #bus.emissive(1,1,1) # Makes it look like daytime

  # add homeless avatars
  global avatars
  avatars = avatarconfig.initAvatars(SCENE)
  
  # create reference to backpack and thief for fading. The .fade attribute = True means that the
  # object should fade if not in view.
  pack_objs = []
  pack = bus.getChild('pack')
  straps = bus.getChild('backpackstraps')
  
  avatars[1].fade = False
  pack.fade = True
  straps.fade = True
  
  pack_objs.append(avatars[1])
  pack_objs.append(pack)
  pack_objs.append(straps)
  
  viz.MainView.getHeadLight().disable()
  
  global controlAvOnKeyPress, controlViewOnKeyPress
  controlAvOnKeyPress = vizact.onkeydown('c', keyboardcontrol.control, avatars[0])
  controlViewOnKeyPress = vizact.onkeydown('v', keyboardcontrol.control, MainView)

  if RIFT:
    creepySeatChanging = CreepySeatChanging.init(avatars[0], pack_objs, introAudio, vfov=VFOV_RIFT, hfov=HFOV_RIFT)
  else:
    creepySeatChanging = CreepySeatChanging.init(avatars[0], pack_objs, introAudio, vfov=VFOV_DEFAULT)
  
  CreepySeatChanging.disable()
  
  #BusLighting.addLighting(SCENE)
  BusLighting.addStreetlights(SCENE)
  global toggleBusLightsOnKeyPress
  toggleBusLightsOnKeyPress = vizact.onkeydown('z', BusLighting.toggleBusLighting)
  
  global dc
  dc = DataCollector(filePrefix='Data/CreepySeatTrackingData_Participant', fileSuffix='.csv')
  dc.addMainviewTracker()
  dc.startCollecting()
 def __init__(self, targetNode):
     self.control(targetNode)
     vizact.ontimer(0, self.UpdateView)
     vizact.onkeydown("t", self.resetPitch)
     vizact.onkeydown("y", self.slower)
     vizact.onkeydown("u", self.faster)
     vizact.onkeydown("o", self.printEuler)
     vizact.onkeydown("p", self.printPos)
示例#13
0
 def __init__(self, targetNode):
   self.control(targetNode)
   vizact.ontimer(0,self.UpdateView)
   vizact.onkeydown('t', self.resetPitch)
   vizact.onkeydown('y', self.slower)
   vizact.onkeydown('u', self.faster)
   vizact.onkeydown('o', self.printEuler)
   vizact.onkeydown('p', self.printPos)
def init():
  vhilGo(rift = RIFT)#, mode=viz.FULLSCREEN)
#  viz.window.setFullscreenMonitor(1) # For Lucas's computer - comment out if you want
  
  keyboardcontrol.control(viz.MainView)
  
  for Scene in SCENE_REFS:
    Scene.load(sceneRef=SCENE_REFS[Scene])
    vizact.onkeydown(SCENE_KEYCHAR[Scene], scheduleSwitchScene, Scene)
    def __init__(self, IDsToSelect):
        self.selectableIDs = IDsToSelect
        self.crosshair, self.crosshairLink = AimCenterScreen.addAimer()
        vizact.onkeydown("m", self.focusCrosshair)

        self.selected = None
        self.timer = vizact.ontimer(0.1, self.focus)

        self.disable()
示例#16
0
def experiment():
    for trialN in range(10):
        if trialN < 9:
            datafile = 'Trial0' + str(trialN + 1) + '.txt'
            respfile = 'RT_Trial0' + str(trialN + 1) + time.strftime(
                "_%d-%b-%y_%H-%M") + '.csv'
        else:
            datafile = 'Trial' + str(trialN + 1) + '.txt'
            respfile = 'RT_Trial' + str(trialN + 1) + time.strftime(
                "_%d-%b-%y_%H-%M") + '.csv'

        colors = []
        with open(datafile, 'rb') as csvfile:
            csvreader = csv.reader(csvfile, delimiter=' ')
            for row in csvreader:
                colors.append(row)
        colors = numpy.asarray(colors, dtype=uInt8)
        # colors = colors[0]

        strobes = Strobes(x, 100)
        leds = LEDs(colors, 0.05, 0.9403)
        vizact.onkeydown('.', leds.recordResp)

        sensor_Target = vizproximity.Sensor(
            vizproximity.RectangleArea([4, 0.1],
                                       center=[0, real_tg_dist[(-1)**trialN]]),
            None)
        manager.addSensor(sensor_Target)

        # Show where the target is and ask them to face to the target
        yield viztask.waitKeyDown('a')
        standBy = viztask.schedule(leds.standby(trialN % 2))
        # Turn of the LED to get the experiment ready to start
        yield viztask.waitKeyDown('s')
        standBy.kill()
        leds.all_off()
        leds.stop()
        monitor_record_Network.send('Start!')
        strobes.StartTask()
        f = viztask.schedule(leds.flashing())
        monitor_record_Network.send('Start!')
        yield vizproximity.waitEnter(
            sensor_Target)  # flash until they enter the target zone
        f.kill()
        # Once reach the target turn off both the LEDs and strobes
        strobes.StopTask()
        strobes.ClearTask()
        leds.all_off()
        leds.stop()
        leds.clear()
        # Save the data into a csv file
        leds.saveAsFile(respfile)
        manager.clearSensors()

    yield viztask.waitTime(10)
    viz.quit()
示例#17
0
    def __init__(self, path, step, radius, bemobil, trackers):
        """
        Fade a visible grid in and out when subjects move close to a boundary wall and back up subsequently.

        To toggle the visibility of the path proximity sensor, use the 'd' button.

        Args:
            path: path along defined points defining the proximity sensor shape. Should be the bounding room shape.
            step: distance between each line building the grid
            radius: distance to the wall at which the proximity sensor should be triggered
            bemobil: if true, then path area will be fixed to [(3, 6.5), (-3, 6.5), (-3, -6.5), (3, -6.5), (3, 6.5)].
            trackers: tracker objects to make as proximity targets. Can take multiple trackers and adds them
                to the proximity manager.
        """

        self.grids = []

        if bemobil:
            self.path = [(3, 6.5), (-3, 6.5), (-3, -6.5), (3, -6.5), (3, 6.5)]
        else:
            path = [(1, 1), (1, 1), (1, 1), (1, 1), (1, 1)]
            # todo create path through parameters provided to the Chaperone constructor (__init__).

        self.grid1 = self.add_grid([13, 3], [0, 0, 0], [3, 1.5, 0], step)
        self.grids.append(self.grid1)

        self.grid2 = self.add_grid([6, 3], [90, 0, 0], [0, 1.5, 6.5], step)
        self.grids.append(self.grid2)

        self.grid3 = self.add_grid([13, 3], [0, 0, 0], [-3, 1.5, 0], step)
        self.grids.append(self.grid3)

        self.grid4 = self.add_grid([6, 3], [90, 0, 0], [0, 1.5, -6.5], step)
        self.grids.append(self.grid4)

        for grid in self.grids:
            grid.addAction(vizact.fadeTo(0, time=3))
            grid.color(viz.GREEN)

        self.path_sensor = self.add_path_sensor(self.path, radius)

        self.path_manager = vizproximity.Manager()
        self.path_manager.addSensor(self.path_sensor)

        if trackers:
            for tracker in trackers:
                self.path_manager.addTarget(tracker)
        else:
            self.path_manager.addTarget(viz.MainView)

        self.path_manager.setDebug(viz.ON)
        vizact.onkeydown('d', self.path_manager.setDebug, viz.TOGGLE)

        self.path_manager.onEnter(self.path_sensor, self.enter_grid,
                                  self.grids)
        self.path_manager.onExit(self.path_sensor, self.exit_grid, self.grids)
示例#18
0
def main():
	vizact.ontimer(0,updateJoy)
	vizact.ontimer(0, updateEuler)
	#vizact.ontimer(0, shoot)
	FileReader()
	initializeObjectFiles()
	initializeLocations()
	getCurrentTestingLocationOrder()
	vizact.ontimer(0.1, update)
	vizact.onkeydown(' ', statusUpdate)
示例#19
0
def main():
	### Configuration parameters
	# moved to config.py

	### Game startup
	#overwrite escape key
	viz.setOption('viz.default_key.quit','0')
	
	# Physics
	viz.phys.enable()
	#viz.phys.setGravity(0,0,0)

	# Initialize pointer tool
	# Unused?
	glove = viz.addChild('.\\dataset\\Hand\\handPoint_Reduced.ply')
	glove.disable([viz.PHYSICS, viz.DYNAMICS])

	glovePhys = glove.collideSphere()
	glove.setPosition([0,1,0])
	glove.setScale([1,1,1])

	# Initialize environment this will load the coliseum and sky
	sky = viz.addChild('sky_day.osgb')
	sky.collideMesh()
	sky.disable(viz.DYNAMICS)
	init.loadTemple()

	# Initialize pointer controls
	device = init.pointerInput(config.pointerMode, glove, sky)

	# Initialize display
	puzzle.model.display = init.DisplayInstance(config.dispMode,config.camMode,device,glove)
	#init.display(config.dispMode)

	# Initialize camera controls
	#init.cameraInput(config.camMode,config.dispMode, device, glove)

	# Launch menu system
	menu.init()
	puzzle.model.pointer = glove
	puzzle.model.pointer.setScale(0.015, 0.015, 0.015)
	puzzle.model.pointer.setEuler(0, -115, 0)
	
	# Override default escape key map to call main menu
	vizact.onkeydown(viz.KEY_ESCAPE, menu.toggle)
	
#	# Record moviefilms
#	viz.setOption('viz.AVIRecorder.maxWidth', '1280')
#	viz.setOption('viz.AVIRecorder.maxHeight', '720')
#	vizact.onkeydown(viz.KEY_F11, viz.window.startRecording, 'D:\\recording.avi')
#	vizact.onkeydown(viz.KEY_F12, viz.window.stopRecording)
	
	# Stuff to run on program termination
	vizact.onexit(puzzle.controller.end)
示例#20
0
def main():
    ### Configuration parameters
    # moved to config.py

    ### Game startup
    # overwrite escape key
    viz.setOption("viz.default_key.quit", "0")

    # Physics
    viz.phys.enable()
    # viz.phys.setGravity(0,0,0)

    # Initialize pointer tool
    # Unused?
    glove = viz.addChild(".\\dataset\\Hand\\handPoint_Reduced.ply")
    glove.disable([viz.PHYSICS, viz.DYNAMICS])

    glovePhys = glove.collideSphere()
    glove.setPosition([0, 1, 0])
    glove.setScale([1, 1, 1])

    # Initialize environment this will load the coliseum and sky
    sky = viz.addChild("sky_day.osgb")
    sky.collideMesh()
    sky.disable(viz.DYNAMICS)
    init.loadTemple()

    # Initialize pointer controls
    device = init.pointerInput(config.pointerMode, glove, sky)

    # Initialize display
    puzzle.model.display = init.DisplayInstance(config.dispMode, config.camMode, device, glove)
    # init.display(config.dispMode)

    # Initialize camera controls
    # init.cameraInput(config.camMode,config.dispMode, device, glove)

    # Launch menu system
    menu.init()
    puzzle.model.pointer = glove
    puzzle.model.pointer.setScale(0.015, 0.015, 0.015)
    puzzle.model.pointer.setEuler(0, -115, 0)

    # Override default escape key map to call main menu
    vizact.onkeydown(viz.KEY_ESCAPE, menu.toggle)

    # 	# Record moviefilms
    # 	viz.setOption('viz.AVIRecorder.maxWidth', '1280')
    # 	viz.setOption('viz.AVIRecorder.maxHeight', '720')
    # 	vizact.onkeydown(viz.KEY_F11, viz.window.startRecording, 'D:\\recording.avi')
    # 	vizact.onkeydown(viz.KEY_F12, viz.window.stopRecording)

    # Stuff to run on program termination
    vizact.onexit(puzzle.controller.end)
示例#21
0
	def __init__(self):		
		super(self.__class__,self).__init__()
		
		# Link navigation node to main view
#		self.NODE = viz.addGroup()
#		self.VIEW_LINK = viz.link(self.NODE, self.VIEW)
		
		# --add oculus as HMD
		self.hmd = oculus.Rift()
		
		if not self.hmd.getSensor():
			viz.logError('** ERROR: Failed to detect Oculus Rift')
		else:
			# Reset HMD orientation
			self.hmd.getSensor().reset()

			# Setup navigation node and link to main view
#			self.NODE = viz.addGroup()
#			self.VIEW_LINK = viz.link(self.NODE, viz.VIEW)
			self.VIEW_LINK.preMultLinkable(self.hmd.getSensor())

			# --Apply user profile eye height to view
			profile = self.hmd.getProfile()
			if profile:
				self.VIEW_LINK.setOffset([0,profile.eyeHeight,0])
				viz.logNotice('Oculus profile name:', profile.name)
				viz.logNotice('Oculus IPD:', profile.ipd)
				viz.logNotice('Oculus player height:', profile.playerHeight)
				viz.logNotice('Oculus eye height:', profile.eyeHeight)
			else: 
				self.VIEW_LINK.setOffset([0,self.EYE_HEIGHT,0])
				
			# Check if HMD supports position tracking
			supportPositionTracking = self.hmd.getSensor().getSrcMask() & viz.LINK_POS
			if supportPositionTracking:
				
				# Add camera bounds model
				self.camera_bounds = self.hmd.addCameraBounds()
				self.camera_bounds.visible(False)

				# Change color of bounds to reflect whether position was tracked
				def checkPositionTracked():
					if self.hmd.getSensor().getStatus() & oculus.STATUS_POSITION_TRACKED:
						self.camera_bounds.color(viz.GREEN)
					else:
						self.camera_bounds.color(viz.RED)
				vizact.onupdate(0, checkPositionTracked)

				# Setup camera bounds toggle key
				def toggleBounds():
					self.camera_bounds.visible(viz.TOGGLE)
				vizact.onkeydown(self.KEYS['camera'], toggleBounds)
def updateViewHQ():
	viz.MainView.setEuler(0,90,270)
	viz.MainView.setPosition(0.15,0.85,0.5)	#[y,z,x]
	viz.cam.setReset()
	vizact.onkeydown(' ',viz.cam.reset)
	
	targetL = vizshape.addQuad(size=(SL_Left,0.15),axis=vizshape.AXIS_Y, cullFace=False, color=viz.GREEN, pos=(SL_Left/2,0.01,0.7))
	targetL_bottom = vizshape.addQuad(size=(0.01,0.35),axis=vizshape.AXIS_Y, cullFace=False, color=viz.RED, pos=(SL_Left - 3*sd_Left,0.01,0.7))
	targetL_top = vizshape.addQuad(size=(0.01,0.35),axis=vizshape.AXIS_Y, cullFace=False, color=viz.RED, pos=(SL_Left + 3*sd_Left,0.01,0.7))

	targetR = vizshape.addQuad(size=(SL_Right,0.15),axis=vizshape.AXIS_Y, cullFace=False, color=viz.BLUE, pos=( SL_Right/2 ,0.01,0.3))
	targetR_bottom = vizshape.addQuad(size=(0.01,0.35),axis=vizshape.AXIS_Y, cullFace=False, color=viz.RED, pos=(SL_Right - 3*sd_Right,0.01,0.3))
	targetR_top = vizshape.addQuad(size=(0.01,0.35),axis=vizshape.AXIS_Y, cullFace=False, color=viz.RED, pos=(SL_Right + 3*sd_Right,0.01,0.3))
示例#23
0
def enable():
	global car, call_screen, SCENE
	viz.MainWindow.setScene(SCENE)
	reset()
	vizact.onkeydown('r', reset)
	#PhoneRadio.test(SCENE, car, call_screen)
	PhoneRadio.enable(SCENE, car, call_screen)
	
	#wait for keypress 1 to start object finding portion
	viz.callback(PhoneRadio.INTRO_OVER_EVENT, PosessionHunting.enable)
	
	#waits for last object to be found, and then schedules police narrative
	viz.callback(PosessionHunting.FINDING_TASK_OVER_EVENT, police.enable)
示例#24
0
 def __init__(self, scene=viz.Scene1, avatar=None):
   self.scene = scene
   self.avatar = avatar
   self.subwindow = None
   self.subview = None
   self.scale = 0.4
   
   self.initScreen()
   
   if self.avatar is not None:
     self.initAvatar()
     
   vizact.onkeydown(' ',self.toggleVisibility)
   viz.callback(viz.MOUSEWHEEL_EVENT,self.rescale)
def showImageToBothEyes():
	global cam1
	global cam2
	
	video = viz.add('VideoCamera.dle')
	outP = video.getWebcamNames(available = False)
	print(outP)
	
	cam1 = video.addWebcam(id=0, size=(640,480))
	cam2 = video.addWebcam(id=1, size=(640,480))
	
	s = 3000
	focalLen = 0.00081566 * s
	planeHeight = 0.00126 * s
	planeWidth = 0.0022 * s
	camcenter_dX = (640-606.3966)*1.75*(10^-6) * s
	camcenter_dY = (360-310.6875)*1.75*(10^-6) * s

	pl_left = vizshape.addPlane(
		size = [planeWidth,planeHeight],
		axis = vizshape.AXIS_Z,
		cullFace = False
	)
	
	pl_right = vizshape.addPlane(
		size = [planeWidth,planeHeight],
		axis = vizshape.AXIS_Z,
		cullFace = False
	)
		
	pl_left.texture(cam1)
	
	pl_right.texture(cam2)
	
	pl_left.setParent(config.leftEyeNode)
	pl_left.setPosition([0,0,focalLen],viz.ABS_PARENT)	
	
	pl_right.setParent(config.rightEyeNode)
	pl_right.setPosition([0,0,focalLen],viz.ABS_PARENT)
	
	## Add code to update orientation with changes in head orientation
	headEuler_YPR = config.headTracker.getEuler()
	pl_left.setEuler([180+headEuler_YPR[0],0+headEuler_YPR[1],-90+headEuler_YPR[2]])
	pl_right.setEuler([180+headEuler_YPR[0],0+headEuler_YPR[1],-90+headEuler_YPR[2]])
	
	pl_left.renderToEye(viz.LEFT_EYE)
	pl_right.renderToEye(viz.RIGHT_EYE)
	
	# Press 'w' to change camera order
	vizact.onkeydown('w', changeCamID)
def enable():
    viz.MainWindow.setScene(SCENE)
    reset()

    global ambientAudio
    ambientAudio.volume(0.1)
    ambientAudio.loop(viz.ON)
    ambientAudio.play()

    viz.MainView.getHeadLight().disable()

    AvatarStories.enable()

    # Keypresses
    toggleBusLightsOnKeyPress.setEnabled(True)
    vizact.onkeydown("r", reset)
示例#27
0
def init(flagPile):
    global lhandtar, rhandtar, placeFlagSound, pickupFlagSound
    # viz.playSound(globals_oa.AUDIO_DIRECTORY + 'bell.wav', viz.SOUND_PRELOAD)
    placeFlagSound = viz.addAudio(globals_oa.AUDIO_DIRECTORY + "flag_in_ground.mp3")
    placeFlagSound.play()
    placeFlagSound.stop()
    pickupFlagSound = viz.addAudio(globals_oa.AUDIO_DIRECTORY + "flag_in_hand.mp3")
    pickupFlagSound.play()
    pickupFlagSound.stop()
    # adding a manager for touching the snails
    global snailTouchManager
    snailTouchManager = vizproximity.Manager()
    # 	snailTouchManager.setDebug(viz.ON)
    vizact.onkeydown("k", snailTouchManager.setDebug, viz.TOGGLE)

    # adding sensor for the flag pile
    flagPileSensor = vizproximity.Sensor(vizproximity.Sphere(0.3, center=(-0.8, -1, -1.8)), source=flagPile)
    flagPileManager = vizproximity.Manager()
    flagPileManager.addSensor(flagPileSensor)
    vizact.onkeydown(",", flagPileManager.setDebug, viz.TOGGLE)
    flagPileManager.onEnter(flagPileSensor, EnterProximity)

    global rhandtar, lhandtar
    if globals_oa.rhModel is not None:
        rhsphere = vizshape.addSphere(radius=0.06)
        rhsphere.setParent(globals_oa.rhModel)
        rhsphere.setPosition([0, 0, 0.55])
        rhsphere.disable(viz.RENDERING)
        rhandtar = vizproximity.Target(rhsphere)  # globals_oa.rhModel)
        snailTouchManager.addTarget(rhandtar)
        flagPileManager.addTarget(rhandtar)
    if globals_oa.lhModel is not None:
        lhsphere = vizshape.addSphere(radius=0.06)
        lhsphere.setParent(globals_oa.lhModel)
        lhsphere.setPosition([0, 0, 0.55])
        lhsphere.disable(viz.RENDERING)
        lhandtar = vizproximity.Target(lhsphere)  # globals_oa.lhModel)
        snailTouchManager.addTarget(lhandtar)
        flagPileManager.addTarget(lhandtar)

        # adding the sensors around the snails
    for snailAndFlagItem in globals_oa.snailAndFlagItemsInZone1:
        snailSensor = vizproximity.addBoundingSphereSensor(snailAndFlagItem.snailItemFromZoneModel, scale=(3.0))
        snailTouchManager.addSensor(snailSensor)

    snailTouchManager.onEnter(None, ShowFlagAtSnail)
    def __init__(self, background_noise):
        """
        Initializes a BaseScene instance which loads vizconnect configuration.

        Args:
            background_noise: if enabled plays a background white noise on repeat

        """

        if background_noise:
            noise = self.add_and_play_background_noise(volume=0.1)

        # todo test
        vizact.onkeydown('s', self.noise.play, viz.TOGGLE)

        self.instruction = self.instruction_canvas_vr(40)
        # Press 'i' to toggle instruction visibility
        vizact.onkeydown('i', self.instruction.visible, viz.TOGGLE)
        vizact.onmousedown(viz.MOUSEBUTTON_RIGHT, self.instruction.visible,
                           viz.TOGGLE)
示例#29
0
    def lisenToKeyboard(self):

        for ls in self.dict.itervalues():
           for jEObj in ls:
                if jEObj.key:
                    vizactEObj = vizact.whilekeydown(jEObj.key,self.sendJEvent,self.jEHandler.getEventID("JASON_KEYDOWN_EVENT")
                                                    ,jEObj)
                    self.listForVizact.append(vizactEObj)
        #if we hit spacebar the programm stops reakting to keyboadevents
        unLisen = vizact.onkeydown(" ", self.unLisenToKeyboard)
        self.listForVizact.append(unLisen)
示例#30
0
    def __init__(self, maze_type, subject, show_avatar_hands=False):

        # call constructor of superclass
        super(VisualMazeScene, self).__init__(background_noise=True)

        if not maze_type == 'baseline':

            # create proximity manager for maze ground units and corner types
            self.poi_manager = super(VisualMazeScene,
                                     self).create_proximity_manager()
            vizact.onkeydown('p', self.poi_manager.setDebug, viz.TOGGLE)

            # init drawing tool
            self.draw_tool = pencil.Pencil()
            self.draw_sphere = VisualMazeScene.add_sphere(
                'draw_sphere', 0.1, viz.RED, [0, 0, 0], viz.OFF, False, None)

            # arrow for warning when head is leaving the maze path
            self.arrow = viz.add('resources/arrow.dae')
            self.arrow.visible(viz.OFF)
            self.arrow.setScale(2, 2, 2)
            self.arrow.color(viz.RED)

            # add draw frame 3D model
            self.drawing_frame = viz.add('resources/frame_model.osgb')
            self.drawing_frame.setScale(1.5, 1.5, 1.5)
            self.drawing_frame.visible(viz.OFF)

            # add local landmark (flash)
            self.flash_quad = screen_flash.Flasher(color=viz.WHITE)

            # reward feedback
            self.coin = viz.add('resources/model2.dae')
            self.coin.setScale(1, 1, 1)
            self.coin.visible(viz.OFF)

            # tracked 3D object for hand collision
            self.feedback_sphere_right = VisualMazeScene.add_sphere(
                'wall_touch', 0.001, viz.WHITE, [0, 0, 0], viz.ON, False, None)
            self.feedback_sphere_right.setScale([0.29 * 350, 0.29 * 350, 0.01])
            self.feedback_sphere_right.alpha(0)
def enable():
  viz.MainWindow.setScene(SCENE)
  reset()
  
  global introAudio
  global ambientAudio
  
  ambientAudio.volume(.1)
  ambientAudio.loop(viz.ON)
  introAudio.volume(2)
  ambientAudio.play()
  introAudio.play()
  
  # Functionality
  CreepySeatChanging.enable()
  
  # Keypresses
  controlAvOnKeyPress.setEnabled(True)
  controlViewOnKeyPress.setEnabled(True)
  toggleBusLightsOnKeyPress.setEnabled(True)
  vizact.onkeydown('r', reset)
示例#32
0
def setup():
	global lhPPT, rhPPT, headPPT, headLink;
	global lhSphere, rhSphere
	
	nvis.nvisorSX111();
	#nvis.nvisorSX60();
	viz.mouse.setVisible(False)
	#viz.cursor(viz.OFF);
	view = viz.MainView
	isense = viz.add('intersense.dle')
	headTracker = isense.addTracker(port=1)
	vizact.onkeydown('r',headTracker.resetHeading)
	vrpn = viz.add('vrpn7.dle');
	PPT_HOSTNAME = '171.64.33.43';
	headPPTorig = vrpn.addTracker('PPT0@' + PPT_HOSTNAME, 0);

	#Merge two links together
	headPPT = viz.mergeLinkable(headPPTorig,headTracker)
	headLink = viz.link(headPPT, viz.MainView);
	headLink.postTrans([EYE_VECTOR[0], EYE_VECTOR[1], EYE_VECTOR[2]]);
	
	#now add the PPT hands tracker
	rhPPT = vrpn.addTracker('PPT0@' + PPT_HOSTNAME, 1)
	lhPPT = vrpn.addTracker('PPT0@' + PPT_HOSTNAME, 2)
	
	grid = vizshape.addGrid();
	grid.color([0.5] * 3);
	
	viz.callback(viz.KEYDOWN_EVENT, onKeyDown);
	
	if(DEBUG_MODE):
		print "adding spheres";
		rhSphere = vizshape.addSphere(radius = 0.1, color = viz.WHITE);
		lhSphere = vizshape.addSphere(radius = 0.1, color = viz.WHITE);
		rfSphere = vizshape.addSphere(radius = 0.1, color = viz.WHITE);
		lfSphere = vizshape.addSphere(radius = 0.1, color = viz.WHITE);
		

	
	return;
示例#33
0
def main():
    global wingl
#    global wingr
    viz.cam.setHandler(vizcam.KeyboardCamera())
    myo.init()
    gyrolist = [[0,0,0]]
    viz.setMultiSample(4)
#    
    wingl = viz.addChild('basketball.osgb')
    wingl.setScale([10,0.3,1])
    wingl.setCenter([100,100,100])
    wingl.setEuler([0,90,0])
    wingl.collideSphere(0.5)
    lStartPOS = [ 0, 2.5, 2 ]
    wingl.setPosition( lStartPOS )
#    wingr = viz.addChild('basketball.osgb')
#    wingr.setScale([10,0.3,1])
#    wingr.setCenter([100,100,100])
#    wingr.setEuler([0,90,0])
#    wingr.collideSphere(0.5)
#    rStartPOS = [ 0, 2.5, 2 ]
#    wingr.setPosition( rStartPOS )

    #viz.MainView.setPosition([0,2,-15])
    hub = myo.Hub()
    hub.set_locking_policy(myo.locking_policy.none)
    hub.run(1000, Listener())
    vizact.ontimer(0.01 ,updateMyo, [gy, gy2, gy3, wingl, orx, ory, orz, orw, or1x, or1y, or1z, or1w])
    vizact.onkeydown('p', hub.shutdown)
    FileReader()
    initializeObjectFiles()
    initializeLocations()
    vizact.ontimer(0.1, update)
    vizact.onkeydown(' ', statusUpdate)
    vizact.onkeydown('s', hub.shutdown)
    
#    viz.AVIRecorder.maxWidth = 1920;
#    viz.AVIRecorder.maxHight = 1080;
    vizact.onkeydown('b', viz.window.startRecording, 'myo_capture.avi' ) 
    vizact.onkeydown('e', viz.window.stopRecording )
def computeFrustumPyramid(vfov, hfov):
	z = 10
	
	# Calculate x and y
	x = 2 * z * math.tan(hfov/2)
	y = 2 * z * math.tan(vfov/2)

	# Make pyramid
	pyr = vizshape.addPyramid(base=[x,y], height=z, axis=vizshape.AXIS_Z)
	pyrInner = vizshape.addPyramid(base=[x,y], height=z, axis=vizshape.AXIS_Z, flipFaces=True)
	pyrInner.setParent(pyr)

	axes = vizshape.addAxes()
	axes.setScale([5]*3)
	axes.setParent(pyr)
	
	# Link to MainView
	pyrlink = viz.link(viz.MainView, pyr)
	pyrlink.preTrans([0,0,z])
	pyrlink.preEuler([180,0,0])
	vizact.onkeydown('b', pyrlink.disable)
	vizact.onkeydown('n', pyrlink.enable)
示例#35
0
def updateViewHQ(LeftAnkle, RightAnkle, LeftGTO, RightGTO):
	viz.MainView.setEuler(0,90,270)
	xyzCamera = qualisys.getMarker(RightGTO).getPosition()
#	print xyzCamera
	xyzCamera1 = qualisys.getMarker(2).getPosition()
#	print xyzCamera1
	viz.MainView.setPosition(0.1,0.5,.4)
	viz.cam.setReset()
	vizact.onkeydown(' ',viz.cam.reset)
	
	positionL = qualisys.getMarker(LeftAnkle).getPosition()
#print positionL
	positionR = qualisys.getMarker(RightAnkle).getPosition()
	#print positionR
	analog = qualisys.getAnalog(0)
	#print analog
	ForcePlates = analog.getData()
	#print ForcePlates
	calibrationFz= 1000      # 3,3 value in Bertec calibation matrix
	GRFL = ForcePlates[3]*calibrationFz
	GRFR = ForcePlates[10]*calibrationFz
	#print "Left", GRFL
	#print "Right", GRFR
	
	positionL_Hip = qualisys.getMarker(LeftGTO).getPosition()
	positionR_Hip = qualisys.getMarker(RightGTO).getPosition()

	targetL = vizshape.addQuad(size=(SL_Left, .15,),axis=vizshape.AXIS_Y, cullFace=False,color=viz.GREEN,pos=(SL_Left/2,0.01,positionL[2]))
	targetL2 = vizshape.addQuad(size=(SL_Left*8, .15,),axis=vizshape.AXIS_Y, cullFace=False,color=viz.GREEN,pos=(-4*SL_Left,0.01,positionL[2]))
	targetL_bottom = vizshape.addQuad(size=(0.01, .25,),axis=vizshape.AXIS_Y, cullFace=False,color=viz.RED,pos=(SL_Left - 2*sd_Left,0.01,positionL[2]))
	targetL_top = vizshape.addQuad(size=(0.01, .25,),axis=vizshape.AXIS_Y, cullFace=False,color=viz.RED,pos=(SL_Left + 2*sd_Left,0.01,positionL[2] ))

	targetR = vizshape.addQuad(size=(SL_Right, .15,),axis=vizshape.AXIS_Y, cullFace=False,color=viz.BLUE,pos=( SL_Right/2 ,0.01,positionR[2]))
	targetR2 = vizshape.addQuad(size=(SL_Right*8, .15,),axis=vizshape.AXIS_Y, cullFace=False,color=viz.BLUE,pos=(-4*SL_Right,0.01,positionR[2]))
	targetR_bottom = vizshape.addQuad(size=(0.01, .25,),axis=vizshape.AXIS_Y, cullFace=False,color=viz.RED,pos=(SL_Right - 2*sd_Right,0.01,positionR[2]))
	targetR_top = vizshape.addQuad(size=(0.01, .25,),axis=vizshape.AXIS_Y, cullFace=False,color=viz.RED,pos=(SL_Right + 2*sd_Right,0.01,positionR[2] ))
示例#36
0
	def updateKeybindings(self):
		"""Menu keybinding state machine"""
		for keybinding in self.keybindings:
			keybinding.remove()
		if self.activeMenu == self.inGameMenu:
			self.keybindings.append(vizact.onkeydown(viz.KEY_ESCAPE, self.toggle))
		elif self.activeMenu == self.layerMenu:
			self.keybindings.append(vizact.onkeydown(viz.KEY_RETURN, lambda: viztask.schedule(self.start))) #use viztask to make loading screen appear before loading (necessary event when not multithreading)
			self.keybindings.append(vizact.onkeydown(viz.KEY_ESCAPE, self.backMenu))
		elif self.activeMenu == self.mainMenu:
			self.keybindings.append(vizact.onkeydown(viz.KEY_RETURN, self.nextMenu))
			self.keybindings.append(vizact.onkeydown(viz.KEY_ESCAPE, self.exitGame))
		elif self.activeMenu == self.modeMenu:
			self.keybindings.append(vizact.onkeydown(viz.KEY_RETURN, self.nextMenu))
			self.keybindings.append(vizact.onkeydown(viz.KEY_ESCAPE, self.backMenu))
def load(sceneRef=viz.MainScene):
    global SCENE
    SCENE = sceneRef  # TODO: Add scene params to all viz.add calls, etc in this module and submodules
    SCENE = viz.MainScene  # TODO: Add scene params to all viz.add calls, etc in this module and submodules

    # add bus
    BUS_OBJ_SCALE = 0.0365
    BUS_OSGB_SCALE = 35
    curscale = BUS_OSGB_SCALE
    bus = vizfx.addChild("bus_obj/Bus_Final_Scene2.osgb", scene=SCENE)
    bus.setScale([curscale] * 3)
    # bus.emissive(1,1,1) # Makes it look like daytime

    # add bus ambient noise
    global ambientAudio
    ambientAudio = viz.addAudio("Audio/Bus Scene/BusAmbientNoise.wav")

    # add homeless avatars
    global avatars
    avatars = avatarconfigStories.initAvatars(SCENE)

    # nodes to be removed at the end of the bus scene
    global toRemove
    toRemove = getRemoveNodes(bus)

    # make exit sign a node for selection to allow for ending the scene.
    exit = bus.getChild("Plane007")
    exit.name = "exit"
    exit.done = False
    avatars.append(exit)

    # init Avatar Stories and narration
    AvatarStories.init(avatars, toRemove, ambientAudio, SCENE)

    # BusLighting.addLighting(SCENE)
    BusLighting.addStreetlights(SCENE)
    global toggleBusLightsOnKeyPress
    toggleBusLightsOnKeyPress = vizact.onkeydown("z", BusLighting.toggleBusLighting)
示例#38
0
 def updateKeybindings(self):
     """Menu keybinding state machine"""
     for keybinding in self.keybindings:
         keybinding.remove()
     if self.activeMenu == self.inGameMenu:
         self.keybindings.append(
             vizact.onkeydown(viz.KEY_ESCAPE, self.toggle))
     elif self.activeMenu == self.layerMenu:
         self.keybindings.append(
             vizact.onkeydown(viz.KEY_RETURN,
                              lambda: viztask.schedule(self.start))
         )  #use viztask to make loading screen appear before loading (necessary event when not multithreading)
         self.keybindings.append(
             vizact.onkeydown(viz.KEY_ESCAPE, self.backMenu))
     elif self.activeMenu == self.mainMenu:
         self.keybindings.append(
             vizact.onkeydown(viz.KEY_RETURN, self.nextMenu))
         self.keybindings.append(
             vizact.onkeydown(viz.KEY_ESCAPE, self.exitGame))
     elif self.activeMenu == self.modeMenu:
         self.keybindings.append(
             vizact.onkeydown(viz.KEY_RETURN, self.nextMenu))
         self.keybindings.append(
             vizact.onkeydown(viz.KEY_ESCAPE, self.backMenu))
示例#39
0
    room.walls.remove()

    viz.addChild('piazza.osgb')

    shutterRigid = config.mocap.returnPointerToRigid('shutter')

    eyeSphere = visEnv.visObj(room, 'sphere', size=0.1, alpha=1)
    eyeSphere.setMocapRigidBody(config.mocap, 'shutter')

    eyeSphere.toggleUpdateWithRigid()

    env.attachViewToGlasses(eyeSphere.visNode, shutterRigid)

    markerNum = 0

    vizact.onkeydown('1', env.setNewCornerPosition, 0, markerNum)
    vizact.onkeydown('2', env.setNewCornerPosition, 1, markerNum)
    vizact.onkeydown('3', env.setNewCornerPosition, 2, markerNum)
    vizact.onkeydown('4', env.setNewCornerPosition, 3, markerNum)

    vizact.onkeydown('0', env.updatePowerwall)

    vizact.onkeydown('s', config.mocap.resetRigid, 'shutterGlass')
    vizact.onkeydown('S', config.mocap.saveRigid, 'shutterGlass')

    wii = viz.add('wiimote.dle')  #Add wiimote extension

    vizact.onsensorup(config.wiimote, wii.BUTTON_LEFT,
                      env.setNewCornerPosition, 0, markerNum)
    vizact.onsensorup(config.wiimote, wii.BUTTON_UP, env.setNewCornerPosition,
                      1, markerNum)
示例#40
0
    def __init__(self):
        #init canvas and create themes for the test panel
        self.canvas = viz.addGUICanvas(align=viz.ALIGN_CENTER_CENTER)
        self.canvas.setPosition(0, 0, 0)
        viz.mouse.setVisible(False)
        self.name = 'test'
        self._theme = viz.Theme()
        self._theme.borderColor = (0.1, 0.1, 0.1, 1)
        self._theme.backColor = (0.4, 0.4, 0.4, 1)
        self._theme.lightBackColor = (0.6, 0.6, 0.6, 1)
        self._theme.darkBackColor = (0.2, 0.2, 0.2, 1)
        self._theme.highBackColor = (0.2, 0.2, 0.2, 1)
        self._theme.textColor = (1, 1, 1, 1)
        self._theme.highTextColor = (1, 1, 1, 1)

        #initialize test panel
        vizdlg.Panel.__init__(self,
                              parent=self.canvas,
                              theme=self._theme,
                              align=viz.ALIGN_CENTER_TOP,
                              fontSize=15)
        self.visible(viz.OFF)
        self.setScale(*[i * config.menuScale[self.name] for i in [1, 1, 1]])
        self.alpha(0.6)

        #		#title
        title = vizdlg.TitleBar('INSTRUCTIONS')
        self.addItem(title, align=viz.ALIGN_CENTER_TOP)

        #bones to be snapped. source snapped to target.
        source = 'a' * 20
        self.sourceText = viz.addTextbox(parent=self.canvas)
        self.sourceText.setLength(1.5)
        target = 'a' * 20
        self.targetText = viz.addTextbox(parent=self.canvas)
        self.targetText.setLength(1.5)

        #instructions
        self.Instruct1 = self.addItem(viz.addText('Snap the: ',
                                                  parent=self.canvas),
                                      align=viz.ALIGN_CENTER_TOP)
        self.sourceCommand = self.addItem(self.sourceText,
                                          align=viz.ALIGN_CENTER_TOP)
        self.Instruct2 = self.addItem(viz.addText('To the: ',
                                                  parent=self.canvas),
                                      align=viz.ALIGN_CENTER_TOP)
        self.targetCommand = self.addItem(self.targetText,
                                          align=viz.ALIGN_CENTER_TOP)

        #render canvas

        if config.dispMode == config.DisplayMode.monitor:
            self.canvas.billboard(viz.BILLBOARD_YAXIS)
            self.canvas.setPosition(-2, 0, 0)
            self.canvas.setBackdrop(viz.ALIGN_CENTER_TOP)

        if config.dispMode == config.DisplayMode.oculus:

            bb = self.canvas.getBoundingBox()
            self.canvas.setRenderWorldOverlay([bb.width * 1, bb.height * 1],
                                              fov=bb.height,
                                              distance=0.4)
            self.canvas.setPosition(0, 0.05, 0)
            self.canvasViewPos = self.canvas.getPosition()
            self.canvas.setEuler(0, 15, 0)
            self.canvas.setPosition(0, -5, 0)
            self.canvasHidePos = self.canvas.getPosition()
            viztask.schedule(self.updatePanelPos())

        vizact.onkeydown(viz.KEY_ESCAPE, self.toggle)
示例#41
0
文件: Main.py 项目: QuillanC/TaxiGame
sound = viz.addAudio('MoonlightSonata.wav')
sound.volume(.5)
#sound.setTime(1)
#sound.setRate(0.7)
sound.play()

# get mini map
miniMap = viz.addWindow()
miniMap.setSize([.3, .4])
miniMap.setPosition([0, 1])
miniMap.fov(70)
miniMapView = viz.addView()
miniMap.setView(miniMapView)

miniMapView.setPosition([250, 450, 275])
miniMapView.setEuler([90, 90, 0])

# set background color of window to gray
viz.MainWindow.clearcolor([150, 150, 150])

# allows mouse to rotate, translate, and zoom in/out on object
#pivotNav = vizcam.PivotNavigate()

e = Environment2()

vizact.onkeydown('q', viz.window.startRecording, 'test.avi')
vizact.onkeydown('e', viz.window.stopRecording)

# render the scene in the window
viz.go()
示例#42
0
import random
import parameters
import environment
import windSpeed
import logger
import statistics
import math

hitPosition = -1
collided = False
data = -1
positionList = []

# check if space is pressed and send signal which calls update movement
s = viztask.Signal()
vizact.onkeydown(' ',s.send)

def onCollide(e):
	global hitPosition
	global collided
	if not collided:
		hitPosition = environment.point.getPosition()
		collided = True
		#print(environment.point.getPosition())
	
def createPositions():
	if parameters.intro:
		return [int(4*random.random()) for i in xrange(parameters.numberOfIntroTrials)]
	elif parameters.training: 
		return [int(4*random.random()) for i in xrange(parameters.numberOfTrainingTrials)]
	else:

root = ''  #empty string
savestring = ''
speedlist = array.array('i')
q = Queue.Queue()  #initialize the queue
qq = Queue.Queue()  #another queue for treadmill commands
q3 = Queue.Queue()  #intialize another queue for saving data
#create threads for client
t1 = threading.Thread(target=runclient, args=(root, q))
t2 = threading.Thread(target=UpdateViz,
                      args=(root, q, speedlist, qq, savestring, q3))
t3 = threading.Thread(target=sendtreadmillcommand, args=(speedlist, qq))
t4 = threading.Thread(target=savedata, args=(savestring, q3))
t1.daemon = True
t2.daemon = True
t3.daemon = True
t4.daemon = True
#start the threads
t1.start()
t2.start()
t3.start()
t4.start()

print("\n")
print("press 'q' to stop")

vizact.onkeydown(
    'q', raisestop, 't'
)  #biggle is meaningless, just need to pass something into the raisestop callback
示例#44
0
sensor10 = vizproximity.Sensor(
    vizproximity.RectangleArea([2.5, 2.25], center=[4, 2.5]), None)
sensor11 = vizproximity.Sensor(
    vizproximity.RectangleArea([4.25, 1], center=[4, 0.375]), None)

sensorList = [
    sensor1, sensor2, sensor3, sensor4, sensor5, sensor6, sensor7, sensor8,
    sensor9, sensor10, sensor11
]
#------------------------------------------------

#-----------Manager creation & set up------------
manager = vizproximity.Manager()
avatarManager = vizproximity.Manager()
#Toggle debug shapes with keypress
vizact.onkeydown('p', manager.setDebug, viz.TOGGLE)
vizact.onkeydown('p', avatarManager.setDebug, viz.TOGGLE)
manager.addTarget(target)

#-----------Avatar's position creation & organization-----
positions = []
positions.append([-3, 0, 0.375])
positions.append([-3, 0, 2.5])
positions.append([-3, 0, 4.75])
positions.append([-3, 0, 6.75])
positions.append([-2, 0, 7.5])
positions.append([3, 0, 6.75])
positions.append([2, 0, 7.5])
positions.append([0, 0, 7])
positions.append([3, 0, 4.75])
positions.append([3, 0, 2.5])
#view.eyeheight(1.65)

# Setup navigation node and link to main view
navigationNode = viz.addGroup()
viewLink = viz.link(navigationNode, viz.MainView)
viewLink.preMultLinkable(hmd.getSensor())

#Oculus will automatically sense the height of the participant and adjust the view
profile = hmd.getProfile()
global height
height = profile.eyeHeight - .13  #after much testing, this seems to be most accurate to real world height
navigationNode.setPosition([0, height, 0])

# Setup heading reset key
KEYS = {'reset': 'r'}
vizact.onkeydown(KEYS['reset'], hmd.getSensor().reset)


def participantInfo():
    #Add an InfoPanel with a title bar
    participantInfo = vizinfo.InfoPanel('',
                                        title='Participant Information',
                                        align=viz.ALIGN_CENTER,
                                        icon=False)

    #Add ID field
    textbox_id = participantInfo.addLabelItem('ID', viz.addTextbox())
    participantInfo.addSeparator(padding=(10, 10))

    #Add eye height field
    textbox_EH = participantInfo.addLabelItem('Eye Height (m)',
示例#46
0
import viz
import vizact

viz.go()
ball = viz.add('ball.wrl')
ball.center([1,0,0])
ball.setPosition([0,1.82,2])
spinForever = vizact.spin(0,1,0, 90, viz.FOREVER)
ball.addAction(spinForever)

vizact.onkeydown('1', ball.endAction)
vizact.onkeydown('2', ball.addAction, spinForever)
示例#47
0
#vizact.ontimer(0,UpdateJoystick)
'''
# Setup Oculus Rift HMD
hmd = oculus.Rift()
if not hmd.getSensor():
	sys.exit('Oculus Rift not detected')

# Go fullscreen if HMD is in desktop display mode
if hmd.getSensor().getDisplayMode() == oculus.DISPLAY_DESKTOP:
	viz.window.setFullscreen(True)
	
# Setup navigation node and link to main view
viz.link(hmd.getSensor(), viz.MainView)
'''
'''
# Setup Oculus Rift HMD
hmd = oculus.Rift()
if not hmd.getSensor():
	sys.exit('Oculus Rift not detected')

# Go fullscreen if HMD is in desktop display mode
if hmd.getSensor().getDisplayMode() == oculus.DISPLAY_DESKTOP:
	viz.window.setFullscreen(True)

# Key commands
KEYS = { 'forward'	: viz.KEY_UP
		,'back' 	: viz.KEY_DOWN
		,'left' 	: viz.KEY_LEFT
		,'right'	: viz.KEY_RIGHT
		,'reset'	: 'r'
示例#48
0
def masterLoop(num):
	# global variables within masterLoop
	global DATA_COLLECT, DO_PRACTICE, is_practice, is_freewalk, data_collect, trial_stage, trial_num, \
	freewalk_session, time, time_stamp, cur_pos, conditions, practice_conditions, condition, K, B, _alpha, \
	reset_countDown, controlType,instruction, screenshot, data_batch, leaderSpd, leader, avatarID,\
	time_elapsed, HZ, flag

	# Time elapsed since the last run of masterLoop and then added to the global time
	time_elapsed = viz.getFrameElapsed()
	time += time_elapsed
	

	if os.path.isfile(OUTPUT_DIR + 'image'+ str(screenshot) +'.bmp') == True:
		screenshot += 1
		
	vizact.onkeydown('p', viz.window.screenCapture, OUTPUT_DIR + 'image'+ str(screenshot) +'.bmp')
	
	# Current position and roation of the participant
	cur_pos = viz.get(viz.HEAD_POS)
	cur_rot = viz.get(viz.HEAD_ORI)
	#>> Will only work in VENLab <<
	emergencyWalls.popWalls(cur_pos) # Pops up the Emergency Walls when participant is close to physical room edge.

	
	##################
	# Begin Freewalk #
	##################
	
	if is_freewalk == True:
		
		
		# Writes Position and Rotation, but only when DATA_COLLECT set to True
		# and trial_stage has set data_collect to True
		if DATA_COLLECT and data_collect:			

			# Position: Target_x, Target_y, Target_z, Participant_x, Participant_y, Participant_z, Yaw, Pitch, Row, time stamp
			data = [cur_pos[0], cur_pos[1], cur_pos[2], cur_rot[0], cur_rot[1], cur_rot[2]]
			strData = [str(round(t,4)) for t in data+[time]]
			strData = ','.join(strData)+'\n'
			data_batch = data_batch + strData

		
		
		#########
		# 00 01 Freewalk Pretrial: sets up practice trial, establishes pole locations
		if trial_stage == 'pretrial_00_01':
			if flag:
				print '> Start Free Walking Session ' + str(freewalk_session) + ' Trial ' + str(trial_num) + ' ----------------------------------'
				flag = False
		
			# Set position of home pole (where participant stands to start trial)
			if models['homePole'].getVisible() == False:
				models['homePole'].setPosition(HOME_POLE[trial_num%2])
				models['homePole'].alpha(1.0)
				models['homePole'].visible(viz.ON)

			# Set position of orientation pole (where participant faces to start trial)
			if models['orientPole'].getVisible() == False:
				models['orientPole'].setPosition(HOME_POLE[(trial_num+1)%2])
				models['orientPole'].visible(viz.ON)
			
			if trial_num == 1 and freewalk_session == 1 and instruction:
				# placeholder for instructions
				instruction = False
			
			if not(trial_num == 1 and freewalk_session == 1) or countDown(5):
				# Move to next stage
				goToStage('orient_00_02')
				instruction = True
				reset_countDown = True				
				
		#########
		# 00 02 Orienting to Pole: Give time for participant to orient to the pole
		elif trial_stage == 'orient_00_02':
			flag = True
			if inRadiusAndFacing():
				if trial_num == 1 and instruction:					
					if freewalk_session == 2:
						pass # placeholder for instructions
					instruction = False
				if not(trial_num == 1) or (freewalk_session == 1) or (freewalk_session == 2 and countDown(5)):	
					# Move to stage 3
					goToStage('orient_00_02_wait')
					instruction = True
					reset_countDown = True
	
				
		#########
		# wait for orientation
		elif (trial_stage == 'orient_00_02_wait'):			
			if countDown(ORIENT_TIME):
				goToStage('inposition_00_03')
				reset_countDown = True
			if not inRadiusAndFacing():
				reset_countDown = True
		
		#########
		# 00 03 Freewalk In Position: proceeds once participant is standing on home and facing orient for three seconds
		elif (trial_stage == 'inposition_00_03'):
			print 'Free walk start'
			# Turn off home pole
			models['homePole'].visible(viz.OFF)
			models['orientPole'].visible(viz.OFF)
			models['targetPole'].setPosition(HOME_POLE[(trial_num+1)%2])
			models['targetPole'].visible(viz.ON)
			sounds['Begin'].play()
			
	
			# Start to collect data
			data_collect = True
		
			# initialize batch data output
			data_batch = ''
			time = 0
			
			# Move to Stage 4
			goToStage('target_00_04')
			
		#########
		# 00 04 Freewalk: Participants Moves
		elif (trial_stage == 'target_00_04'):
				
			# Detects participant location, moves to Stage 5 (Ends Trial) when participant reache the end line
			if (trial_num%2 == 1) and (cur_pos[2] > endLine(cur_pos[0])) or \
				(trial_num%2 == 0)and (cur_pos[2] < endLine(cur_pos[0])):
					
				goToStage('endtrial_00_05')
		
		#########
		# 00 05 End Freewalk Trial: Close out the trial and reset values for next practice trial or start Experiment
		elif trial_stage == 'endtrial_00_05':
		
			# Clears the target pole
			models['targetPole'].visible(viz.OFF)
			
			# save the data of this trial
			fileName = OUTPUT_DIR + NICKNAME + '_freewalk' + '_subj' + subject + '_s' + str(freewalk_session) + '_trial' + str(trial_num).zfill(3) + '.csv'
			with open(fileName, 'a') as file:
				file.write(data_batch)


			print 'End Freewalk Trial ' + str(trial_num)
			data_collect = False


			# End Check: When trial_num is greater than FREEWALK_TRIALS, end practice and start experiment block
			if trial_num == FREEWALK_TRIALS:
				print '>> End Freewalk Session<<'
				if freewalk_session == 2:
					print '>>> End Experiment <<<'
					goToStage('NULL')
					if instruction:
						sounds['End'].play()
						instruction = False
				elif freewalk_session == 1:
					goToStage('pretrial_01_01')
					is_freewalk = False
					trial_num = 1
					freewalk_session += 1
			# Returns to Stage 1, resets clock
			else:
				trial_num += 1
				goToStage('pretrial_00_01')
				instruction = True
		

	##################
	# Begin practice #
	##################
	
	elif is_practice == True:
		
	
		#########
		# 01 01 Practice Pretrial: sets up practice trial, establishes pole locations
		if trial_stage == 'pretrial_01_01':
			if flag:
				print '> Start Practice Trial ' + str(trial_num) + ' ----------------------------------'
				flag = False
			# load input
			if practice_conditions[trial_num][3] == 'avatar':
				avatarID = random.choice(range(len(avatars)))
				leader = avatars[avatarID]
				leader.state(5)
			else:
				leader = models['leaderPole']
				
			leaderSpd = 0
			# play instruction
			if trial_num == 1 and instruction:
				# placeholder for instructions
				instruction = False
				
			# Move to Stage 2
			if trial_num != 1 or countDown(5):
				goToStage('orient_01_02')
					
			
		#########
		# 01 02 Orienting to Pole: Give time for participant to orient to the pole
		elif (trial_stage == 'orient_01_02'):
			flag = True
			# Set position of home pole (where participant stands to start trial)
			if models['homePole'].getVisible() == False:
				models['homePole'].setPosition(HOME_POLE[trial_num%2])

			if _alpha < 1.0:
				models['homePole'].alpha(_alpha)
				models['homePole'].visible(viz.ON)
				_alpha += 1.0/HZ
	
			# Set position of orientation pole (where participant faces to start trial)
			if models['orientPole'].getVisible() == False:
				models['orientPole'].setPosition(HOME_POLE[(trial_num+1)%2])
				models['orientPole'].visible(viz.ON)
	
				
			if inRadiusAndFacing():					
				reset_countDown = True
				# Move to stage 3
				goToStage('orient_01_02_wait')
				instruction = True
				_alpha = 0.0
				# Current time
				time_stamp = time
				
		#########
		# wait for orientation
		elif (trial_stage == 'orient_01_02_wait'):
			if countDown(ORIENT_TIME):
				goToStage('inposition_01_03')
				reset_countDown = True
			if not inRadiusAndFacing():
				reset_countDown = True
				
				
		#########
		# 01 03 Practice In Position: proceeds once participant is standing on home and facing orient for three seconds
		elif trial_stage == 'inposition_01_03':
			
			print 'Practice Target Appears'
			
			# Turn off home pole and orientation pole
			models['homePole'].visible(viz.OFF)
			models['orientPole'].visible(viz.OFF)
			models['targetPole'].setPosition(HOME_POLE[(trial_num+1)%2])
			models['targetPole'].visible(viz.ON)
			sounds['Begin'].play()
			
			# Move to Stage 4
			goToStage('target_01_04')
			time = 0
			
		#########
		# 01 04 Moving leader: Leader Moves
		elif (trial_stage == 'target_01_04'):
			leaderOnset = float(practice_conditions[trial_num][4])
			d0 = float(practice_conditions[trial_num][1])
			v0 = float(practice_conditions[trial_num][2])
			if time > leaderOnset:
				if not leader.getVisible():
					models['targetPole'].visible(viz.OFF)
					# leader appear d0 meter in front of participant
					leader.setPosition(HOME_POLE[trial_num%2])
					leader.lookAt(HOME_POLE[(trial_num+1)%2], mode=viz.ABS_GLOBAL)
					home = models['homePole'].getPosition()						
					d = d0 + projection([x-y for x, y in zip(cur_pos, home)], [-x for x in home])
					moveTarget(leader, d/time_elapsed, conditions[trial_num][3] == 'avatar') # move the leader by d0 from homepole to leader					
					leader.visible(viz.ON)
				# leader moves
				moveTarget(leader, v0, practice_conditions[trial_num][3] == 'avatar')
			
			# Detects participant location, moves to Stage 6 (Ends Trial) when participant reache the end line
			if (trial_num%2 == 1) and (cur_pos[2] > endLine(cur_pos[0])) or \
				(trial_num%2 == 0)and (cur_pos[2] < endLine(cur_pos[0])):
				goToStage('endtrial_01_05')
		
		#########
		# 01 05 End Practice Trial: Close out the trial and reset values for next practice trial or start Experiment
		elif trial_stage == 'endtrial_01_05':
			
			# Clears the target pole
			leader.visible(viz.OFF)

			print 'End Practice Trial ' + str(trial_num)
			

			# End Check: When trial_num is greater than PRACTICE_TRIALS, end practice and start experiment block
			if trial_num >= PRACTICE_TRIALS:
				print '>> End Practice <<'
				goToStage('pretrial_02_01')
				is_practice = False
				trial_num = 1
			# Returns to Stage 1, resets clock
			else:
				trial_num += 1
				goToStage('pretrial_01_01')
			
	####################
	# Begin Experiment #
	####################
	
	elif is_practice == False:
		

		# Writes Position and Rotation, but only when DATA_COLLECT set to True
		# and trial_stage has set data_collect to True
		if DATA_COLLECT and data_collect:
			
			
			# Location of Target Pole
			leader_loc = leader.getPosition()
			
			leader_loc = leader.getPosition()
			# Position: Target_x, Target_y, Target_z, Participant_x, Participant_y, Participant_z, Yaw, Pitch, Row, time stamp
			data = [leader_loc[0], leader_loc[1], leader_loc[2], cur_pos[0], cur_pos[1], cur_pos[2], cur_rot[0], cur_rot[1], cur_rot[2]]
			strData = [str(round(t,4)) for t in data+[time]] + [str(avatarID)]
			strData = ','.join(strData)+'\n'
			data_batch = data_batch + strData

			# log IPD
			if trial_num == 1:
				file = open(OUTPUT_DIR + NICKNAME + '_subj' + subject + \
				'_IPD_' + str(IPD) + '.txt', 'a')
				file.close()
			
			
		#########
		# 02 01 Experiment Pretrial: sets up trial, establishes pole locations
		if trial_stage == 'pretrial_02_01':
			
			condition = ', '.join(conditions[trial_num][1:4])
			
			# Print start of trial, trial #, and type of trial [pos][speed][turn]
			if flag:
				print '> Start Trial ' + str(trial_num) + ': ' + condition + ' ----------------------------------'
				flag = False
			# load input
			if conditions[trial_num][3] == 'avatar':
				avatarID = random.choice(range(len(avatars)))
				leader = avatars[avatarID]
				leader.state(5)
			elif conditions[trial_num][3] == 'pole':
				leader = models['leaderPole']
						
			leaderSpd = 0
			
			# play instruction
			if trial_num == 1 and instruction:				
				instruction = False
			
			# Move to Stage 2			
			if trial_num != 1 or countDown(5):
				goToStage('orient_02_02')
				
				
		#########
		# 02 02 Orienting to Pole: Give time for participant to orient to the pole
		elif (trial_stage == 'orient_02_02'):
			flag = True
			## Set position of home pole (where participant stands to start trial)
			if models['homePole'].getVisible() == False:
				models['homePole'].setPosition(HOME_POLE[trial_num%2])
				
			if _alpha < 1.0:
				models['homePole'].alpha(_alpha)
				models['homePole'].visible(viz.ON)
				_alpha += 1.0/HZ
	
			# Set position of orient pole (where participant faces to start trial)
			if models['orientPole'].getVisible() == False:
				models['orientPole'].setPosition(HOME_POLE[(trial_num+1)%2])
				models['orientPole'].visible(viz.ON)

			if inRadiusAndFacing():					
				# Move to stage 3
				goToStage('orient_02_02_wait')
				_alpha = 0.0
				instruction = True
				reset_countDown = True				
	
		#########
		# wait for orientation
		elif (trial_stage == 'orient_02_02_wait'):
			if countDown(ORIENT_TIME):
				goToStage('inposition_02_03')
				reset_countDown = True
			if not inRadiusAndFacing():
				reset_countDown = True		
		
		#########
		# 02 03 In Position: proceeds once participant is standing on home and facing orient
		elif trial_stage == 'inposition_02_03':

			# Turn off home and orient poles
			models['homePole'].visible(viz.OFF)
			models['orientPole'].visible(viz.OFF)
			models['targetPole'].setPosition(HOME_POLE[(trial_num+1)%2])
			models['targetPole'].visible(viz.ON)
			sounds['Begin'].play()
			
			# Turn on data collection for this trial
			data_collect = True
				
			# Move to Stage 5
			goToStage('target_02_04')
			# initialize batch data output
			data_batch = ''
			time = 0

			
		#########
		# 02 04 Moving Leader: Leader Moves
		elif (trial_stage == 'target_02_04'):
			# read data
			leaderOnset = float(conditions[trial_num][4])
			d0 = float(conditions[trial_num][1])
			v0 = float(conditions[trial_num][2])
			if time > leaderOnset:
				if not leader.getVisible():
					models['targetPole'].visible(viz.OFF)
					# leader appear d0 meter in front of participant
					leader.setPosition(HOME_POLE[trial_num%2])
					leader.lookAt(HOME_POLE[(trial_num+1)%2], mode=viz.ABS_GLOBAL)
					home = models['homePole'].getPosition()
					d = d0 + projection([x-y for x, y in zip(cur_pos, home)], [-x for x in home])
					moveTarget(leader, d/time_elapsed, conditions[trial_num][3] == 'avatar') # move the leader by d0 from homepole to leader					
					leader.visible(viz.ON)
				# leader moves
				moveTarget(leader, v0, conditions[trial_num][3] == 'avatar')
				
				
			# Detects participant location, moves to Stage 6 (Ends Trial) when participant reache the end line
			if (trial_num%2 == 1) and (cur_pos[2] > endLine(cur_pos[0])) or \
				(trial_num%2 == 0)and (cur_pos[2] < endLine(cur_pos[0])):
				goToStage('endtrial_02_05')
				
			#########
		# 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')
    print("stop flag raised")
    endflag.set()
    t1.join()
    t2.join()
    t4.join()
    viz.quit()


root = ''  #empty string
savestring = ''
q = Queue.Queue()  #initialize the queue
q3 = Queue.Queue()  #intialize another queue for saving data
#create threads for client
t1 = threading.Thread(target=runclient, args=(root, q))
t2 = threading.Thread(target=UpdateViz, args=(root, q, savestring, q3))
t4 = threading.Thread(target=savedata, args=(savestring, q3))

t1.daemon = True
t2.daemon = True
t4.daemon = True
#start the threads
t1.start()
t2.start()
t4.start()

print("\n")
print("press 'q' to stop")
print("\n")

vizact.onkeydown('q', raisestop, 't')
示例#50
0
        else:
            csvw.writerow(savestring)
            print("data still writing to file")

    print("savedata finished writing")
    file.close()

root = ''  #empty string
savestring = ''
q = Queue.Queue()  #initialize the queue
q3 = Queue.Queue()  #intialize another queue for saving data
#create threads for client
t1 = threading.Thread(target=runclient, args=(root, q))
t2 = threading.Thread(target=UpdateViz, args=(root, q, savestring, q3))
t4 = threading.Thread(target=savedata, args=(savestring, q3))

t1.daemon = True
t2.daemon = True
t4.daemon = True
#start the threads
t1.start()
t2.start()
t4.start()

print("\n")
print("press 'q' to stop")
print("\n")

vizact.onkeydown('q', raisestop, 't')
vizact.onkeydown('r', ReCenterView, hmd)
def updateViewHQ():
	viz.MainView.setEuler(0,90,270)
	viz.MainView.setPosition(0.15,0.85,0.5)	#[y,z,x]
	viz.cam.setReset()
	vizact.onkeydown(' ',viz.cam.reset)
示例#52
0
	starting_box.audio_running.play()
	starting_box.runAction(vizact.move(0,-2,0,time=(starting_box_height/2)))
	starting_box.addAction(vizact.call(starting_box.audio_stop.play))
	starting_box.addAction(vizact.call(starting_box.audio_running.pause))	
		
def raiseBox():
	starting_box.setPosition([0,starting_box_height,0],viz.REL_LOCAL)

active = True
def setActive(value):
	global active
	if value == True:
		for obj in obj_vis:
			obj.visible(viz.ON)
		active = True
		scene3_music.play()
	else:
		lowerWalls()
		for obj in obj_vis:
			obj.visible(viz.OFF)
		active = False
		scene3_music.stop()

def getActive():
	return active

if __name__ == '__main__':
	viz.go()
	viz.MainView.getHeadLight().disable()
	vizact.onkeydown('1',lowerBox)
	vizact.onkeydown('2',raiseWalls)
示例#53
0
t3.start()
t4.start()

print("\n")
print("press 'q' to stop")


def TargetUpdate(arg):
    global target
    target = target + .05


def KepPressDetector(arg):
    global PSYCHO
    PSYCHO = arg
    prompt4TwoChoice.visible(0)


vizact.onkeydown(
    'q', raisestop, 'biggle'
)  #biggle is meaningless, just need to pass something into the raisestop callback
###################### CJS 12/17/2016 ######################
''' This will take the ibnput from the Logitech to indicate if the first or the second trial was longer'''
vizact.onkeydown('65366', KepPressDetector, 1)  # Second trial was longer
vizact.onkeyup('65366', KepPressDetector, 0)  #No longer indicating anything
vizact.onkeydown('65365', KepPressDetector, -1)  # First trial was longer
vizact.onkeyup('65365', KepPressDetector, 0)  #No longer indicating anything
print('^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^')
print('^^^^^^^^^^^^^^^^^^Key Press^^^^^^^^^^^^^^')
print('^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^')
############################################################
for avatar in male_avatars:
	avatar.setPosition([x, 0, z]);
	avatar.setEuler(-180,0,0)
	avatar.state(1)
	x += 1

# display female avatars
num_avatars = len(female_avatars)
x = .5 * num_avatars
z = -3 + num_avatars * -.5
for avatar in female_avatars:
	avatar.setPosition([x, 0, z]);
	avatar.state(1)
	x -= 1

# The below code allows you to set the reverse the mainview. In order to do
# so, I create a wrapper around the euler value, euler_t. Using the array
# wrapper, the function can edit the array and maintain the value, whereas
# integers are mutable and the change wouldn't persist.
euler_t = [0]
def flip_view(euler_t):
	euler = euler_t[0]
	if (euler == 0):
		euler = 180
	else:
		euler = 0
	viz.MainView.setEuler([euler,0,0])
	euler_t[0] = euler
vizact.onkeydown('r', flip_view, euler_t)
示例#55
0

def thread1():
    global endflag
    view = viz.MainView
    while not endflag.is_set():
        out = view.getPosition(mode=viz.ABS_GLOBAL)
        #		print('x: ',out)

        if (out[2] > 1.27 * 3 / 2):
            #			view.velocity(0,0,0)
            view.setPosition(0, 0.15, -1.27 * 3 / 2 + 0.002)


#			OF1.setPosition(0,0,1.27*9)
#			print('OF moved')
    print('thread terminated')


def raisestop(biggle):
    global endflag
    endflag.set()
    viz.quit()


t1 = threading.Thread(target=thread1)
t1.start()
vizact.onkeydown('s', viz.MainView.velocity, [0, 0, 1])
vizact.onupdate(0, UpdateTexture)
vizact.onkeydown('q', raisestop, 'biggle')
示例#56
0
#        posOutString = ''

#        # Build two seperate strings
#        for m in poseBuffer_sIdx:
#
#            timeStamp = currentTime-m[0]
#            quat_XYZW = m[1].getQuat()
#
#            pos_XYZ = m[1].getPosition()
#            #posOutString = posOutString  + '[ %f %f %f %f ] ' % (timeStamp, pos_XYZ[0], pos_XYZ[1], pos_XYZ[2])
#            posOutString = posOutString  + '[ %f - %f ] ' % (timeStamp, pos_XYZ[1])
#
#        print posOutString

#import vizact
# vizact.onkeydown('p',plotRigidPos,plotDur)
#vizact.ontimer(0.25,plotRigidPos,'shutter',plotDur)
#vizact.ontimer(0.05,plotMarkerPos,2,plotDur)

#mocapDataFile = open('mocapIntDataOut.txt','w+')

    mocap.startLogging('F:\Data\Stepover')

    #mocap.createOutputFile(mocapDataFile )


    def writeData(lookbackDurS):
        mocap.writer.writeDataFromTime = lookbackDurS

    vizact.onkeydown('w', writeData, 1)
示例#57
0
#manager.addSensor(xyloBar19)
#manager.addSensor(xyloBar20)
#manager.addSensor(xyloBar21)
#manager.addSensor(xyloBar22)
#manager.addSensor(xyloBar23)
#manager.addSensor(xyloBar24)
#manager.addSensor(xyloBar25)
#manager.addSensor(xyloBar26)
#manager.addSensor(xyloBar27)
#manager.addSensor(xyloBar28)
#manager.addSensor(xyloBar29)
#manager.addSensor(xyloBar30)
#manager.addSensor(xyloBar31)
#manager.addSensor(xyloBar32)
#manager.addSensor(xyloBar33)
#manager.addSensor(xyloBar34)
#manager.addSensor(xyloBar35)

lastPlayed = time.time()


def playBassDrumWrapper():
    global lastPlayed
    if time.time() - lastPlayed > maxPossPerSec:
        sp.playBassDrum()
        lastPlayed = time.time()


manager.onEnter(None, EnterProximity)
vizact.onkeydown('p', manager.setDebug, viz.TOGGLE)
示例#58
0
def setupTarget():
	viztask.waitTime(5)
	target = viz.add('arm/all_target.wrl')
	target.setScale(.01, .01, .01)
	target.setEuler(0, 90, 0)
	target.setPosition([-1.35, 1.5, -1.5])
	reportTargetTime()
	
	#Adds invisible cube that launches fire
	global targetcube 
	targetcube = []
	targetcube.append(TouchCube())
	targetcube[0].setPosition([-1.35, 1.5, -1.5])

vizact.onkeydown('t', setupTarget)

def setupTouchCubes():
	for i in range(NUM_CUBES):
		touchCubes.append(TouchCube())
		touchCubes[i].color(CUBE_DEFAULT_COLOR)
		touchCubes[i].alpha(CUBE_DEFAULT_ALPHA)
		touchCubes[i].setPosition(CUBE_DEFAULT_POS)

alreadyAwake = False
def wakeTouchCubes():
	global alreadyAwake
	if (not alreadyAwake):
		alreadyAwake = True
		touchCubes[0].touchCallback = activateTouchCubes
	
示例#59
0
	def bindKeys(self):
		self._keyBindings.append(vizact.onkeydown('o', model.proxManager.setDebug, viz.TOGGLE)) #debug shapes
		self._keyBindings.append(vizact.onkeydown(viz.KEY_ALT_R, self.pinCheck))
		self._keyBindings.append(vizact.onkeydown(viz.KEY_ALT_L, self.pinCheck))