Пример #1
1
	def setAsMain(self):
		viz.logStatus("""Setting KeyboardMouse as main""")
		
#		self.VIEW_LINK.preTrans([0,-self.EYE_HEIGHT,0])
		
		viz.mouse.setOverride(viz.ON) 
		viz.fov(self.FOV)

#		self.MOVE_SPEED = 2
		
		vizact.ontimer(0,self.updateView)
		vizact.onkeyup(self.KEYS['reset'],self.reset)
		
		def onMouseMove(e):
			euler = self.VIEW.getEuler(viz.HEAD_ORI)
			euler[0] += e.dx*0.05
			euler[1] += -e.dy*0.05
			euler[1] = viz.clamp(euler[1],-85.0,85.0)
			self.VIEW.setEuler(euler,viz.HEAD_ORI)
		viz.callback(viz.MOUSE_MOVE_EVENT, onMouseMove)	
Пример #2
0
def main():
    
    global wingl
    global wingr
    viz.cam.setHandler(vizcam.KeyboardCamera())
    myo.init()
    gyrolist = [[0,0,0]]
    viz.setMultiSample(4)
    viz.fov(150)
    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, wingr])
Пример #3
0
    def __init__(self,
                 offset,
                 particle=None,
                 sensorNum=0,
                 attachTo=viz.MainView,
                 preTrans=[0, 0, 0.1778]):
        viz.EventClass.__init__(self)

        self.offset = offset
        self.particle = particle
        self.sensorNum = sensorNum
        self.attachTo = attachTo
        self.preTran = preTrans

        self.off = True

        self.vrpn = viz.add('vrpn6.dle')
        self.tracker = self.vrpn.addTracker('[email protected]', sensorNum)
        self.tracker.swapPos([1, 3, 2])
        self.tracker.swapQuat([-1, -3, -2, 4])

        self.preMat = vizmat.Transform()
        self.preMat.preEuler([-90, 0, 0])
        self.preMat.preTrans(self.preTran)

        self.postMat = vizmat.Transform()
        self.postMat.postTrans(offset)

        vizact.ontimer(0, self.updateView)
        self.pos = [0, 0, 0]
        self.rot = [0, 0, 0, 0]
        self.turnOn()
Пример #4
0
def main():
	global loc_list
	global active_location
	loc_list = []
	
	mainSceneWindow = None
	cameraWindow = None
	cameraWindowView = None
	cam = None
	pause_screen = None
	nunchuck_disconnect_screen = None
	message_screen = None
	wiimote = None
	nunchuck_wiimote = None
	should_it_run = None
	
	mainSceneWindow, cameraWindow, cameraWindowView, cam, pause_screen, nunchuck_disconnect_screen, message_screen, wiimote, nunchuck_wiimote, should_it_run = init_settings(mainSceneWindow, cameraWindow, cameraWindowView, cam, pause_screen, nunchuck_disconnect_screen, message_screen, wiimote, nunchuck_wiimote, should_it_run)
	
	vizact.ontimer(0, moveCamera, nunchuck_wiimote, should_it_run)
	viz.callback(wii.EXT_CONNECT_EVENT,onConnect)
	viz.callback(wii.EXT_DISCONNECT_EVENT,onDisconnect)
	
	initializer(loc_list)
	arMarkerLoader(cam)
	wiimoteInitializer(wiimote, nunchuck_wiimote, should_it_run, message_screen)
	
	viz.go() # Inicia VIZ
	
	for item in loc_list:
		if item.space_name == "piazza.osgb":
			active_location = item
			item.addLocation()
Пример #5
0
	def __init__(self, offset, particle=None, sensorNum=0, attachTo=viz.MainView, preTrans = [0, 0, 0.1778]) :
		viz.EventClass.__init__(self)

		self.offset 	= offset
		self.particle   = particle
		self.sensorNum = sensorNum
		self.attachTo = attachTo
		self.preTran = preTrans
		
		self.off 			   = True

		self.vrpn = viz.add('vrpn6.dle')
		self.tracker = self.vrpn.addTracker('[email protected]', sensorNum) 
		self.tracker.swapPos([1,3,2]) 
		self.tracker.swapQuat([-1,-3,-2,4])
		
		self.preMat = vizmat.Transform()
		self.preMat.preEuler([-90, 0, 0]);
		self.preMat.preTrans(self.preTran);
		
		self.postMat = vizmat.Transform();
		self.postMat.postTrans(offset);
		
		vizact.ontimer(0, self.updateView)
		self.pos = [0,0,0]
		self.rot = [0, 0, 0, 0]
		self.turnOn()
Пример #6
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__(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)
Пример #8
0
def main():
	global initialStep
#	if initialStep:
	time.sleep(3)
	text1.setPosition(0,1.6,4)
	print "START"
	vizact.ontimer2(0.33, 2, getInitial)
	vizact.ontimer(1/60, checkStep)
Пример #9
0
def testPhase():
    info.setText("Experiment running")
    info.visible(viz.ON)
    vizact.ontimer(1, getData)
    yield viztask.waitTime(10)
    
    info.setText("Experiment over")
    yield viztask.waitTime(2)
Пример #10
0
	def setAsMain(self):
		viz.logStatus('Setting Joyculus as main')

		val = mathlite.getNewRange(self.joy.getSlider(),1,-1,self.MIN_SPEED,self.MAX_SPEED)
		self.MOVE_SPEED = val
		
		vizact.onsensordown(self.joy,self.KEYS['reset'],self.reset)
		vizact.ontimer(0,self.updateView)
		viz.callback(getExtension().SLIDER_EVENT,self.onSliderChange)
def addStreetlights(scene=viz.MainScene):
  global timeToMove, streetLight, origPOS, endPOS
  timeToMove = 1.2
  origPOS = [ [8, 2.5, 5] , [8,2.5,-5] ]
  endPOS = [ [-11,2.5,5] , [-11,2.5,-5] ]
  streetLight = vizfx.addPointLight()
  streetLight.intensity(.4)
  streetLight.color(viz.WHITE)
  moveStreetlight()
  vizact.ontimer(timeToMove+1, moveStreetlight)
Пример #12
0
def initialize():
    global controller
    # Create a sample listener and controller
    # 	listener = SampleListener()
    controller = Leap.Controller()

    # Have the sample listener receive events from the controller
    # 	controller.add_listener(listener)

    vizact.ontimer(0.01, getLeapData)
Пример #13
0
	def __init__(self, node=None, scene=viz.Scene1):
		self.scene = scene
		self.node = node
		self.found = []
		self.returnPosition = True
		self.returnEuler = True
		self.returnCurrent = True
		self.selected = None
		self.enabled = False
		vizact.ontimer(.1, self.cursorChange)
		vizact.onmousedown(viz.MOUSEBUTTON_LEFT, self.computeDistance)
def main():
 global co2models, moleculeManager,overOceanSensor
 loadBoatScene()
 #terrain_LW = vizfx.addChild(('./art/ENV_Island_Main.osgb').getChild('Ocean001'))
 setUpMolecAnimation()
# viz.MainScene.enable(viz.FOG, op=viz.OP_ROOT)
 vizact.ontimer(0, masterTimer)
 overOceanSensor = vizproximity.addBoundingBoxSensor(globals_oa.boat, scale = [.8,.8,.65])
 moleculeManager.addSensor(overOceanSensor)
 initializeBoatGrabberAndPhysics()
 setUpHandSensors()
Пример #15
0
def addSirens(scene=viz.MainScene):
    redSiren = makeSiren(scene=scene)
    redSiren.color(viz.RED)
    redSiren.position(0.93, 1.43, -1.98, 1)

    blueSiren = makeSiren(scene=scene)
    blueSiren.color(viz.BLUE)
    blueSiren.position(-0.5, 1.43, -1.98, 1)

    global sirenAudio
    sirenAudio = redSiren.playsound("resources/audio/PoliceSiren.wav")
    vizact.ontimer(0.1, moveSirens, redSiren, blueSiren)
Пример #16
0
    def __init__(self, fig):
        self.canvasData = viz.Data(lock=threading.Lock(), havenewData=False)
        self.fig = fig
        self.t = threading.Thread(target=self.computeFigureThread)
        self.t.start()

        #IMPORTANT: Wait for thread to finish before exiting
        vizact.onexit(self.t.join)
        #Create a blank texture to display canvas data
        self.tex = viz.addBlankTexture([1, 1])
        #Create onscreen quad to display texture
        self.quad = viz.addTexQuad(parent=viz.ORTHO, texture=self.tex)
        self.quad.alpha(0.5)
        self.link = viz.link(viz.MainWindow.CenterCenter, self.quad)
        #	self.link.setOffset([400,200,0])
        self.drawer = vizact.ontimer(0, self.drawPlot)
        self.rate_ctr = time.time()
        self.drawrate_txt = viz.addText('', viz.SCREEN)
        self.drawrate_txt.setPosition(0, 0.01)
        self.drawrate_txt.scale(.7, .7)
        self.drawrate_txt.color(viz.WHITE)
        self.drawrate_txt.visible(0)
        self.rate = 0
        #scale variables to change size of plot image
        self.scale_x = 1
        self.scale_y = 1
Пример #17
0
	def __init__(self, fig):
		self.canvasData = viz.Data(lock = threading.Lock(), havenewData=False )	
		self.fig = fig
		self.t = threading.Thread(target=self.computeFigureThread)
		self.t.start()

		#IMPORTANT: Wait for thread to finish before exiting
		vizact.onexit(self.t.join)
		#Create a blank texture to display canvas data
		self.tex = viz.addBlankTexture([1,1])
		#Create onscreen quad to display texture
		self.quad = viz.addTexQuad(parent=viz.ORTHO,texture=self.tex)
		self.quad.alpha(0.5)
		self.link = viz.link(viz.MainWindow.CenterCenter,self.quad)
	#	self.link.setOffset([400,200,0])
		self.drawer = vizact.ontimer(0, self.drawPlot)
		self.rate_ctr = time.time()
		self.drawrate_txt = viz.addText('', viz.SCREEN)
		self.drawrate_txt.setPosition(0,0.01)
		self.drawrate_txt.scale(.7,.7)
		self.drawrate_txt.color(viz.WHITE)
		self.drawrate_txt.visible(0)
		self.rate = 0
		#scale variables to change size of plot image
		self.scale_x = 1
		self.scale_y = 1
	def __init__(self):
			

		self.targetNumber = 3
		self.maxNum = 7
		
		self.buffSize  = 7
		self.updateRateSecs = 0.75
		
		self.nextBuffer  = np.array([])
		self.lastBuffer = []
		
		while(self.nextBuffer.size < self.buffSize):
			self.addInt()
		
		self.textObj = viz.addText('',parent=viz.SCREEN)
		self.textObj.setPosition(0.5,0.5)
		self.textObj.color(viz.WHITE)
		self.textObj.alignment( viz.ALIGN_CENTER_CENTER) 
		self.textObj.fontSize(1000)
		
		self.targetTimer = []
		self.updateAction  = vizact.ontimer(self.updateRateSecs,self.presentNumber)
		
		self.stopPresentingNumbers()
		
		print 'Ready. To start countdown, run <numberCount>.startPresentingNumbers()' 
Пример #19
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) 
Пример #20
0
def InitHMD():
	global collisionLimbBoxes
	if(USE_HMD):
		pptExtension.setup();
		viz.go(viz.FULLSCREEN)
		viz.clip(0.1)
		vizact.onupdate(0, pptExtension.pptUpdate, avatar, ghostAvatar, collisionLimbBoxes);
		if(len(collisionLimbBoxes) > 0):
			vizact.ontimer(1, pptExtension.refreshAvatar, ghostAvatar, avatar, collisionLimbBoxes);
		else:
			vizact.ontimer(1, pptExtension.refreshAvatar, ghostAvatar, avatar, None);
	else:
		pptSimulation.setup(avatar);
		viz.clip(0.1)
		viz.go(viz.FULLSCREEN);
		vizact.onupdate(0, pptSimulation.pptUpdate, avatar, ghostAvatar, collisionLimbBoxes);
	def skipBackward(self):
		self.skipAmount -= 1
		if self.skipAmount == 0: # Was skipping forward, now is 0
			self.skipTimer.remove()
		elif self.skipAmount == -1: # Was at 0, now is skipping backward
			self.pause()
			self.skipTimer = vizact.ontimer(SKIP_PERIOD, self._skip)
		print 'skipping backward ' + str(self.skipAmount) + ' seconds per frame.'
Пример #22
0
	def fadeOutTask(self, fadeTime=1.5):
		"""Yieldable task to fade out to silent"""
		initialVolume = self._mixer.getVolume()
		amount = - initialVolume * (self._timeStep / fadeTime)
		self.updateEvent = vizact.ontimer(self._timeStep, self._updateFadeOut, amount)
		yield viztask.waitEvent(FADE_COMPLETE)
		self.updateEvent.setEnabled(False)
		self._mixer.stop()
Пример #23
0
    def __init__(self, subject, start_from_trial=0):
        """
        Setup data path, room, ball, baseball glove and trial list. Initialize events and actions.
        :param subject: subject nr
        :param start_from_trial: number of first trial (used when experiment crashed)
        """
        # call superclass constructor
        viz.EventClass.__init__(self)

        # create data path
        self.data_dir = 'data/{}/'.format(subject)

        # read experiment info (config dict)
        with open(self.data_dir + 'exp_info.txt') as info_file:
            config = json.load(info_file)

        # setup hardware
        hardware.setup(config['hardware'])

        # initialize visual environment
        print '\nSetting up visual environment...'
        self.room = Room(config)
        self.config = config['experiment']

        # add ball
        ball_size = self.config['ball_size']
        ball_initial_pos = [0, ball_size, 36.22]
        self.ball = Ball(room=self.room, size=ball_size, position=ball_initial_pos, color=[1, 1, 1])
        self.ball.setAlpha(0)

        self.glove = None
        self.catch_sound = None
        # add glove
        if self.config['glove']:
            self.glove = BaseballGlove(room=self.room, size=self.config['glove_radius'], marker_num=1,
                                       hand=config['experiment']['hand'])
            self.catch_sound = viz.addAudio('res/sounds/applause.wav')

        # initialize trial list
        self.trials = pd.read_csv(self.data_dir + 'trials.csv').to_dict('records')
        self.trial_num = start_from_trial - 1
        self.current_trial = None
        self.current_block = None

        self.message_panel = None
        if hardware.hmd:
            # HMD message panel for showing messages between blocks and at the end of the experiment
            self.message_panel = hardware.hmd.addMessagePanel('You did it!')
            self.message_panel.visible(False)

        # key-press events (for starting the experiment)
        self.callback(viz.KEYDOWN_EVENT, self.on_key_down)

        # handle collisions (register when glove touches ball)
        vizact.onupdate(0, self.handle_collisions)

        # play sound if participant leaves allowed area
        self.allowed_area_action = vizact.ontimer(0.7, self.check_allowed_area)
    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()
Пример #25
0
def InitHMD():
#BL:start		
	global collisionLimbBoxes
#	if USE_HMD:
	pptextension.setup()
	if some_global_variables.headTrackingActive:
		viz.go(viz.HMD | viz.TRACKER)
	else:
		viz.go()
	viz.window.setSize(1260, 950)		
	#viz.go(viz.FULLSCREEN)
#BL:end
	viz.clip(0.1)
	vizact.onupdate(0, pptextension.pptUpdate, some_global_variables.avatar, some_global_variables.ghostAvatar, collisionLimbBoxes);
	if(len(collisionLimbBoxes) > 0):
		vizact.ontimer(1, pptextension.refreshAvatar, some_global_variables.ghostAvatar, some_global_variables.avatar, collisionLimbBoxes);
	else:
		vizact.ontimer(1, pptextension.refreshAvatar, some_global_variables.ghostAvatar, some_global_variables.avatar, None);
Пример #26
0
 def showToolTip(self, flag):
     if flag:
         self.tooltip.visible(viz.ON)
         self.nameLine.visible(viz.ON)
         self._lineUpdateEvent = vizact.ontimer(0, self.updateNameLine)
     if not flag:
         self.tooltip.visible(viz.OFF)
         self.nameLine.visible(viz.OFF)
         if self._lineUpdateEvent:
             self._lineUpdateEvent.remove()
Пример #27
0
def bmw_card_driver():
	
	car = viz.addChild('bmw.dae')
	car.setEuler([0,0,0])
	car.setScale(0.5,0.5,0.5)
	MOVE_SPEED = 5
	TURN_SPEED = 60

	def updatecar():
		#move view forward and backward
		if viz.key.isDown(viz.KEY_UP):
			view.move([0,0,MOVE_SPEED*viz.elapsed()],viz.BODY_ORI)
		elif viz.key.isDown(viz.KEY_DOWN):
			view.move([0,0,-MOVE_SPEED*viz.elapsed()],viz.BODY_ORI)

		#rotate body of view left and right
		if viz.key.isDown(viz.KEY_RIGHT):
			view.setEuler([TURN_SPEED*viz.elapsed(),0,0],viz.BODY_ORI,viz.REL_PARENT)
		elif viz.key.isDown(viz.KEY_LEFT):
			view.setEuler([-TURN_SPEED*viz.elapsed(),0,0],viz.BODY_ORI,viz.REL_PARENT)

		#set the car to view position and body orientation
		car.setPosition(view.getPosition())
		car.setEuler(view.getEuler(viz.BODY_ORI))
		car.setPosition([3.02,-5.50,5.04],viz.REL_LOCAL)

	vizact.ontimer(0,updatecar)

	#update head of view based on mouse movements
	def mousemove(e):
		euler = view.getEuler(viz.HEAD_ORI)
		euler[0] += e.dx*0.1
		euler[1] += -e.dy*0.1
		euler[1] = viz.clamp(euler[1],-85.0,85.0)
		view.setEuler(euler,viz.HEAD_ORI)

	viz.callback(viz.MOUSE_MOVE_EVENT,mousemove)
	viz.mouse(viz.OFF)
	viz.mouse.setVisible(False)

	vizact.onmousedown(viz.MOUSEBUTTON_LEFT,view.reset,viz.HEAD_ORI)
	vizact.onmousedown(viz.MOUSEBUTTON_RIGHT,view.reset, viz.BODY_ORI |viz.HEAD_POS)
	vizact.onmousedown(viz.MOUSEBUTTON_RIGHT,updatecar)
Пример #28
0
def InitHMD():
	global collisionLimbBoxes
	if(USE_HMD):
#BL:start		
		viz.go(viz.HMD | viz.TRACKER)
		viz.window.setSize(1260, 950)		
		pptExtension.setup();
		#viz.go(viz.FULLSCREEN)
#BL:end
		viz.clip(0.1)
		vizact.onupdate(0, pptExtension.pptUpdate, avatar, ghostAvatar, collisionLimbBoxes);
		if(len(collisionLimbBoxes) > 0):
			vizact.ontimer(1, pptExtension.refreshAvatar, ghostAvatar, avatar, collisionLimbBoxes);
		else:
			vizact.ontimer(1, pptExtension.refreshAvatar, ghostAvatar, avatar, None);
	else:
		pptSimulation.setup(avatar);
		viz.clip(0.1)
		viz.go(viz.FULLSCREEN);
		vizact.onupdate(0, pptSimulation.pptUpdate, avatar, ghostAvatar, collisionLimbBoxes);
Пример #29
0
def InitHMD():
    # BL:start
    global collisionLimbBoxes, isLeftHanded
    if USE_HMD:
        viz.go(viz.HMD | viz.TRACKER)
        viz.window.setSize(1260, 950)
        pptExtension.setup(isLeftHanded)
        # viz.go(viz.FULLSCREEN)
        # BL:end
        viz.clip(0.1)
        vizact.onupdate(0, pptExtension.pptUpdate, avatar, ghostAvatar, collisionLimbBoxes)
        if len(collisionLimbBoxes) > 0:
            vizact.ontimer(1, pptExtension.refreshAvatar, ghostAvatar, avatar, collisionLimbBoxes)
        else:
            vizact.ontimer(1, pptExtension.refreshAvatar, ghostAvatar, avatar, None)
    else:
        pptSimulation.setup(avatar)
        viz.clip(0.1)
        viz.go(viz.FULLSCREEN)
        vizact.onupdate(0, pptSimulation.pptUpdate, avatar, ghostAvatar, collisionLimbBoxes)
Пример #30
0
	def __init__(self, mouseClickCallback=None, mouseOverCallback=None):
		self.mouseOverCallback = mouseOverCallback
		self.mouseClickCallback = mouseClickCallback

		self.timer = vizact.ontimer(.1, self.pick)
		if mouseClickCallback:
			self.mouseEvent = vizact.onmousedown(viz.MOUSEBUTTON_LEFT, self.executeMouseClickCallback)
		else:
			self.mouseEvent = None
		
		self.pause()
Пример #31
0
def on_release(e):
    """
        Callback-Funktion, die bem Loslassen eines Bauteils
        aufgerufen wird.

        Args:
            e: Event, wird nicht verwendet
    """
    global robot, robot_parts, part_index
    # Position des Bauteils mit der des Templates vergleichen
    part = robot_parts[part_index]
    pos_1 = np.array(part.getPosition(viz.ABS_GLOBAL), dtype=np.float32)
    pos_2 = np.array(robot.get_position(part_index), dtype=np.float32)
    dist = np.linalg.norm(pos_1 - pos_2)
    # Falls sich das Bauteil nahe genug an der korrekten Position befindet
    # TODO: Orientierung ueberpruefen
    if dist <= max_dist:
        # Bauteil positionieren und Physik fuer dieses
        # Bauteil ausschalten
        part.disable(viz.DYNAMICS)
        part.collideMesh()
        part.setPosition(robot.get_position(part_index), viz.ABS_GLOBAL)
        part.setAxisAngle(robot.get_orientation(part_index), viz.ABS_GLOBAL)
        # Falls noch Bauteile uebrig geblieben sind, das
        # naechste Bauteil fuer den grabber freischalten
        if part != robot_parts[-1]:
            part_index += 1
            grabber.setItems(robot_parts[part_index:part_index + 1])
            # Ansonsten den Ball fuer den Grabber freischalten und
            # den Roboter dem Ball folgen lassen.
        else:
            # Template sichtbar machen
            robot.visible(True)
            # Neu gebauten Roboter unsichtbar machen
            for p in robot_parts:
                p.visible(False)
            # Ball freischalten
            grabber.setItems([ball])
            # Roboter folgt dem Ball
            vizact.ontimer(1. / float(viz.getOption('viz.max_frame_rate')),
                           robot_follows_marker, robot, ball)
Пример #32
0
	def setAsMain(self):
#		self.VIEW_LINK.setOffset([0,self.EYE_HEIGHT,0])
		self.VIEW_LINK.preTrans([0,-self.EYE_HEIGHT,0])
		
		viz.mouse.setOverride(viz.ON) 
		viz.fov(self.FOV)
		
		val = mathlite.getNewRange(self.joy.getSlider(),1,-1,self.MIN_SPEED,self.MAX_SPEED)
		self.MOVE_SPEED = val
		
		vizact.ontimer(0, self.updateView)
		vizact.onsensorup(self.joy, self.KEYS['reset'], self.reset)
		viz.callback(getExtension().SLIDER_EVENT,self.onSliderChange)
		
		def onMouseMove(e):
			euler = self.VIEW.getEuler()
			euler[0] += e.dx*0.05
			euler[1] += -e.dy*0.05
			euler[1] = viz.clamp(euler[1],-85.0,85.0)
			self.VIEW.setEuler(euler)
		viz.callback(viz.MOUSE_MOVE_EVENT, onMouseMove)	
Пример #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 )
Пример #34
0
def main():
	
	global wingl
	global wingr
	viz.cam.setHandler(vizcam.KeyboardCamera())
	myo.init()
	gyrolist = [[0,0,0]]

	viz.fov(150)
	#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.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 )


	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, wingr])

	vizact.ontimer(0, updateEuler)

	FileReader()
	initializeObjectFiles()
	initializeLocations()
	getCurrentTestingLocationOrder()
	vizact.ontimer(0.1, update)
Пример #35
0
def main():
	print(sys.version_info);
	#vizact.ontimer(0, printPos);
	p = win32pipe.CreateNamedPipe(
		r'\\.\pipe\Demo',
		win32pipe.PIPE_ACCESS_DUPLEX,
		win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_WAIT,
		1,
		65536,
		65536,
		300,
		None)
	print("pre connect")
	#win32pipe.ConnectNamedPipe(p, None)
	print("post connect")





	#vizact.ontimer(0, printPos)
	vizact.ontimer(1, pipeRefresh, p)
Пример #36
0
	def __init__(self, fishFilepath, numFish, radius, center, speed, modScale):
		self.FISH_FILE = fishFilepath
		self.center = center
		self.radius = radius
		self.speed = speed
		self.angularOffsets = DEFAULT_ANGULAR_OFFSETS
		self.maxHop = DEFAULT_HOP
		self.hopsPerRev = DEFAULT_HOPS_PER_REVOLUTION
		self.numFish = numFish
		self.modScale = modScale

		self.addFishes()
		self.timer = vizact.ontimer(UPDATE_RATE, self.update)
Пример #37
0
def training3DJoystick():
    training = True
    positions = createPositions()
    joystickMove = vizact.ontimer(0, UpdateMovement)
    environment3D.point.setVelocity([0, 0, 0])

    for i in positions:
        environment3D.point.setPosition(0, 20, 0)
        if i == 0:
            environment3D.goal.setPosition(position0Xtrain, 0, position0Ztrain)
        elif i == 1:
            environment3D.goal.setPosition(position1Xtrain, 0, position1Ztrain)
        elif i == 2:
            environment3D.goal.setPosition(position2Xtrain, 0, position2Ztrain)
        elif i == 3:
            environment3D.goal.setPosition(position3Xtrain, 0, position3Xtrain)

        #enable joystick movement
        environment3D.point.visible(viz.ON)
        environment3D.goal.visible(viz.ON)
        environment3D.arrow.visible(viz.ON)
        environment3D.thrust.disable()
        joystickMove.setEnabled(viz.ON)
        #wait till key is pressed let object fall down
        yield s.wait()
        joystickMove.setEnabled(viz.OFF)
        #set force on the point + gravity
        [x, z] = windSpeed.computeWindForce(environment3D.point.getPosition())
        environment3D.thrust.setForce([x, gravity, z])
        environment3D.thrust.enable()
        print(environment3D.point.getPosition())
        yield viztask.waitTime(1)
        #show fallen object
        print(environment3D.point.getPosition())
        environment3D.thrust.disable()
        environment3D.point.setVelocity([0, 0, 0])
        yield viztask.waitTime(0.5)
        #make point invisible wait and start next trial
        environment3D.point.visible(viz.OFF)
        environment3D.goal.visible(viz.OFF)
        environment3D.arrow.visible(viz.OFF)
        yield viztask.waitTime(1)
Пример #38
0
#Get the tracking data.
def getData():
    orientation = viz.MainView.getEuler()
    position = viz.MainView.getPosition()
    currTime = time.clock()
    #Make a string out of the data.
    data = str(currTime - startTime) + '\t' + str(position[0]) + '\t' + str(
        position[2]) + '\t' + str(orientation[0]) + '\n'
    #Write it to the tracking file.
    tracking_data.write(data)


##LAUNCH EXPERIMENT####
global startTime
startTime = time.clock()
viztask.schedule(
    EXPERIMENT(trials_per_object, initial_collect_per_object, TestObjects,
               TestObjectLocs, ITI, scaleFactors, runs))
vizact.ontimer(0.05, getData)

######### SCREEN SHOTS ########
#counterScreenShots=0;
# Method for taking screenshots
#def takeScreenshot():
#	global counterScreenShots
#	ScreenshotName='ScreenShotTraining_' + str(counterScreenShots)+'.jpg';
#	viz.window.screenCapture(ScreenshotName);
#	counterScreenShots=counterScreenShots+1;
#
#vizact.onkeydown('s', takeScreenshot)
Пример #39
0
 def start(self):
     vizact.ontimer(2, self.sendit)
Пример #40
0
viz.clearcolor(viz.SKYBLUE)

MOVE_SPEED = 5
TURN_SPEED = 60

car = viz.addChild('mini.osg')
ground = viz.addChild('ground.osgb')

view = viz.MainView


def updatecar():
    if viz.key.isDown(viz.KEY_UP):
        view.move([0, 0, MOVE_SPEED * viz.elapsed()], viz.BODY_ORI)
    elif viz.key.isDown(viz.KEY_DOWN):
        view.move([0, 0, -MOVE_SPEED * viz.elapsed()], viz.BODY_ORI)
    elif viz.key.isDown(viz.KEY_RIGHT):
        view.setEuler([TURN_SPEED * viz.elapsed(), 0, 0], viz.BODY_ORI,
                      viz.REL_PARENT)
    elif viz.key.isDown(viz.KEY_LEFT):
        view.setEuler([-TURN_SPEED * viz.elapsed(), 0, 0], viz.BODY_ORI,
                      viz.REL_PARENT)

    car.setPosition(view.getPosition())
    car.setEuler(view.getEuler(viz.BODY_ORI))
    car.setPosition([0.35, -1.2, 0.2], viz.REL_LOCAL)


vizact.ontimer(0, updatecar)
Пример #41
0
import viz
import vizact
import vizshape

viz.go()

VRPN_SOURCE = '[email protected]'
#VRPN_SOURCE = 'Nexus@localhost'

viz.move([0, -1, -5])

axes = vizshape.addAxes(length=0.5)

vrpn = viz.add('vrpn7.dle')
headtracker = vrpn.addTracker(VRPN_SOURCE)
headtracker.swapPos([-1, 3, -2])

#viz.link(headtracker,axes)


def showData():
    print('position')
    print headtracker.getPosition()


#	print headtracker.getEuler()

vizact.ontimer(1, showData)
    def use_control(self, control_style):
        """
        Enable the control modality depending on the provided input modality.

        Different experimental setup make use of different ways to exert control over the experimental world.
        Use this function to define and setup the necessary things depending on the control modality to be used.

        Args:
            control_style: interaction possibilities between subject and VR world. Currently supports:
            'mouse and keyboard', 'joystick', 'wiimote with dk2 head', 'dk2 head only', 'dk2 head hands'

        """

        # control type for test purposes
        if control_style == 'mouse and keyboard': # control type for test purposes

            viz.mouse(viz.ON)
            vizact.onmousedown(viz.MOUSEBUTTON_LEFT, self.on_button_press, 'A')
            vizact.onmousedown(viz.MOUSEBUTTON_RIGHT, self.on_button_press, 'B')

            self.sphere_radius = 0.02
            self.right_hand_sphere = vizshape.addSphere(radius=self.sphere_radius)
            self.right_hand_sphere.color(viz.GREEN)
            self.right_hand_target = self.right_hand_sphere.collideSphere()
            self.right_hand_sphere.disable(viz.DYNAMICS)

            self.right_hand_sphere.alpha(1)

            self.head_sphere = vizshape.addSphere(radius=self.sphere_radius)
            self.head_sphere.color(viz.YELLOW)
            self.head_target = self.head_sphere.collideSphere()
            self.head_sphere.disable(viz.DYNAMICS)

            MOVE_SPEED = 0.025

            def move_hand():
                if viz.key.isDown(viz.KEY_UP):
                    self.right_hand_sphere.setPosition([self.right_hand_sphere.getPosition()[0], 1.6, self.right_hand_sphere.getPosition()[2]+MOVE_SPEED])
                elif viz.key.isDown(viz.KEY_DOWN):
                    self.right_hand_sphere.setPosition([self.right_hand_sphere.getPosition()[0], 1.6, self.right_hand_sphere.getPosition()[2]-MOVE_SPEED])
                elif viz.key.isDown(viz.KEY_LEFT):
                    self.right_hand_sphere.setPosition(self.right_hand_sphere.getPosition()[0]-MOVE_SPEED, 1.6, self.right_hand_sphere.getPosition()[2])
                elif viz.key.isDown(viz.KEY_RIGHT):
                    self.right_hand_sphere.setPosition(self.right_hand_sphere.getPosition()[0]+MOVE_SPEED, 1.6, self.right_hand_sphere.getPosition()[2])

            def move_head():
                if viz.key.isDown('w'):
                    self.head_sphere.setPosition([self.head_sphere.getPosition()[0], 1.6, self.head_sphere.getPosition()[2]+MOVE_SPEED])
                elif viz.key.isDown('s'):
                    self.head_sphere.setPosition([self.head_sphere.getPosition()[0], 1.6, self.head_sphere.getPosition()[2]-MOVE_SPEED])
                elif viz.key.isDown('a'):
                    self.head_sphere.setPosition(self.head_sphere.getPosition()[0]-MOVE_SPEED, 1.6, self.head_sphere.getPosition()[2])
                elif viz.key.isDown('d'):
                    self.head_sphere.setPosition(self.head_sphere.getPosition()[0]+MOVE_SPEED, 1.6, self.head_sphere.getPosition()[2])

            vizact.ontimer(0, move_hand)
            vizact.ontimer(0, move_head)

        elif control_style == 'joystick':

            # first load the oculus rift plugin and link sensor to viewpoint
            import oculus
            hmd = oculus.Rift()

            # loads the DirectInput plug-in and adds first available joystick
            dinput = viz.add('DirectInput.dle')
            self.joy = dinput.addJoystick()

            # Set dead zone threshold so small movements of joystick are ignored
            self.joy.setDeadZone(0.2)

            # add viewpoint at subject height
            eye_height = float(self._height) - 0.05

            joystick_node = viz.addGroup(pos=(0, eye_height, 0))
            viz.link(joystick_node, viz.MainView)

            # joystick control class with lsl streams of pos and ori as in the dk2 tracker class
            # stream pos and ori in joystick movement function which gets called with ontimer / onupdate
            # set lsl stream parameters
            lsl_streamName = 'vizard_hmd6dof_stateLog_joystick'
            lsl_streamType = 'sixFloat'  # no official lsl type (not recognized by eeglab or mobilab)
            lsl_numChannels = 6
            lsl_regularSPS = 75  # regular rate, one sample per DK2 frame
            lsl_dataType = 'float32'
            lsl_streamUuid = socket.gethostname()  # PC name as uuid

            # create stream
            lsl_hmd6dofStreamInfo = StreamInfo(lsl_streamName, lsl_streamType, lsl_numChannels, lsl_regularSPS,
                                                    lsl_dataType, lsl_streamUuid)
            lsl_hmd6dofStreamInfo.desc().append_child('synchronization').append_child_value('can_drop_samples',
                                                                                                 'true')
            lsl_hmd6dofOutlet = StreamOutlet(lsl_hmd6dofStreamInfo)

            viz.callback(viz.SENSOR_DOWN_EVENT, self.on_button_press)
            vizact.onupdate(0, self.update_joystick_movement, self.joy, joystick_node, 5, 90, lsl_hmd6dofOutlet)

        else:
            self.start_dk2_head_tracker(control_style)
        "This is not a basketball"
        #  ser.writelines(b'L')
        vizact.ontimer(1, releaseBall)
        vizact.ontimer(2, releaseBall)
        vizact.ontimer(3, releaseBall)
        vizact.ontimer(4, releaseBall)
        vizact.ontimer(5, releaseBall)
        vizact.ontimer(6, releaseBall)
        vizact.ontimer(7, releaseBall)
        vizact.ontimer(8, releaseBall)
        vizact.ontimer(9, releaseBall)
        vizact.ontimer(10, releaseBall)
        vizact.ontimer(11, releaseBall)
        vizact.ontimer(12, releaseBall)
        vizact.ontimer(13, releaseBall)
        vizact.ontimer(14, releaseBall)
        vizact.ontimer(15, releaseBall)
        vizact.ontimer(16, releaseBall)


def releaseBall():
    global link
    link.remove()
    print
    "open hand - released grip on basketball"
    link = None


vizact.ontimer(0, grabBall)
vizact.ontimer(15, releaseBall)
Пример #44
0
    def setUpPaddle(self):
        PS1 = testSensorNew.addPhaseSpaceMulti()
        PS1.addMarkers(0, 1, 2, 3, 4, 5, 6)
        PS1.setPointMarker()
        PS1.setServerAddress('128.174.14.227')
        PS1.setFrequency(240)
        PS1.setScale(0.001, 0.001, 0.001)
        PS1.setSlave()
        #PS1.startStreaming()

        viz.setOption('viz.model.apply_collada_scale', 1)

        ball = viz.add('white_ball.wrl')
        ball.color(viz.WHITE)
        #ball.setScale(0)
        #ojo = viz.addChild('sky_day.osgb')
        print PS1
        viz.link(PS1, ball)

        PS2 = testSensorNew.addPhaseSpaceMulti()
        PS2.addMarkers(7, 8, 9, 10, 11, 12)
        PS2.setPointMarker()

        PS2.setServerAddress('128.174.14.227')
        PS2.setFrequency(240)
        PS2.setScale(0.001, 0.001, 0.001)
        PS2.setSlave()
        PS1.startStreaming()
        PS2.startStreaming()

        ball1 = viz.add('white_ball.wrl')
        ball1.color(viz.WHITE)
        #ball1.alpha = 0
        #ball1.setScale(0)
        #ball1.setPosition(0,2,0)

        print PS2
        viz.link(PS2, ball1)

        water_level = 0

        self.paddle = viz.addChild('paddle/newOar.dae', parent=self.board)
        #self.paddle.collideMesh()
        #self.paddle.disable(viz.DYNAMICS)
        self.paddle.setEuler([90, 0, 0])
        #viz.link(ball, paddle)
        v_x = [1, 0, 0]
        global v_paddle
        v_paddle_last = self.paddle.getEuler()
        Trans = vizmat.Transform()
        '''
        global prev_p0 
        prev_p0 = ball.getPosition()
        global prev_p1
        prev_p1 = ball1.getPosition()
        '''
        self.last_pos_ball = ball.getPosition()

        def TestRecording():
            print ball.getPosition()
            print ball1.getPosition()

        def RotatePaddle():
            p0 = ball.getPosition()
            p1 = ball1.getPosition()
            #camera_pos = self.camera.getPosition()
            board_pos = self.camera.getPosition()
            #camera_rot = self.camera.get()
            board_dir = self.camera.getEuler()
            #print("dir" , board_dir)
            add_x = math.cos(board_dir[2])
            add_z = math.sin(board_dir[2])
            #print("dir", add_x)
            v_true = [p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2]]
            position_true = [(p1[0] + p0[0]) / 2 - 0.2,
                             (p1[1] + p0[1]) / 2 - 1,
                             (p1[2] + p0[2]) / 2 + 1.5]

            position_true[1] -= 2
            Trans.makeVecRotVec(v_x, v_true)
            euler = Trans.getEuler()
            #for data in euler:
            #    data = -data
            #qut =
            self.paddle.setEuler(euler)
            #self.paddle.setPosition(self.view.getPosition())
            #self.paddle.setEuler(self.view.getEuler())
            #self.paddle.setPosition([1,0,0], viz.REL_LOCAL)
            self.paddle.setPosition(position_true)

        def updateSpeed():
            p0 = ball.getPosition()
            p1 = ball1.getPosition()
            mid = (p0[0] + p0[1]) / 2
            camera_pos = self.camera.getPosition()
            print("paddle height = ", p0[1])
            move_amount = 1
            turn_amount = 0
            if (self.last_pos_ball[1] > p0[1] + 0.05
                    and p0[1] <= self.water_level):
                message_panel.setText('Let\'s explore the islands!')
                self.move_speed = min(self.move_speed + 2, self.max_speed)
                print("speed up", self.move_speed)
            elif (p0[1] <= self.water_level
                  and abs(self.last_pos_ball[1] - p0[1]) < 1):
                self.move_speed = max(self.move_speed - 0.1, 2)
                print("slow down", self.move_speed)
            else:
                self.move_speed = max(self.move_speed - 0.01, 2)
                print("no action", self.move_speed)
            self.last_pos_ball[1] = p0[1]
            self.transform(move_amount, turn_amount)
            #print(Trans.getForward(self.camera.getEuler()))
            #print(self.camera.getEuler().getForward())
            #print("ball pos", self.ball_board.getPosition)
            #print("board pos", self.board.getPosition())

        def updateDirection():
            p0 = ball.getPosition()
            p1 = ball1.getPosition()
            mid = (p0[0] + p0[1]) / 2
            camera_pos = self.camera.getPosition()
            move_amount = 0
            turn_amount = 0
            print("mid", mid)
            print("p0[0]", p0[0])
            if (self.last_pos_ball[1] > p0[1] + 0.05
                    and p0[1] <= self.water_level):
                if (p0[0] > mid):
                    #turn right
                    print("turn right")
                    turn_amount = 10
                else:
                    print("turn left")
                    turn_amount = -10
            '''
            elif(p0[1] <= self.water_level and abs(self.last_pos_ball[1] - p0[1]) < 0.05):
                if(p0[0] < mid):
                    #turn left   
                    print("turn left")
                    turn_amount = -1
                else:
                    print("turn right")
                    turn_amount = 1
            '''
            self.transform(move_amount, turn_amount)

        def updatePos():
            move_amount = 1
            turn_amount = 0
            self.transform(move_amount, turn_amount)

        vizact.onkeydown(' ', TestRecording)
        vizact.ontimer(0.0, RotatePaddle)
        vizact.ontimer(0.0, updateDirection)
        vizact.ontimer(0.4, updateSpeed)
        vizact.ontimer(0.0, updatePos)
        self.PS1 = PS1
        self.PS2 = PS2
        self.ball1 = ball1
        self.ball = ball
Пример #45
0
      return 0

#simulate landing
def landing():
   if(ontable() == 0 and onground() == 0): #when dropping
      if(calfR.getEuler()[2] > -9):
         calfR.lock()
         calfL.lock()
         text3D.message('Dropping')
         print('drop!')
         print(time.time())
      if(calfR.getEuler()[2]> -30):
         calfR.setEuler(0, 0, calfR.getEuler()[2]-10)
         calfL.setEuler(0, 0, calfL.getEuler()[2]-10)
   if(ontable() == 0 and onground() == 1):    #after landing
      if(calfR.getEuler()[2] < -28):
         text3D.message('Finished')
         print('hit the ground!')
         print(time.time())
      if(calfR.getEuler()[2] < -10):
         calfR.setEuler(0, 0, calfR.getEuler()[2]+10)
         calfL.setEuler(0, 0, calfL.getEuler()[2]+10)


#press space to start the simulation
vizact.ontimer(0, landing)
vizact.onkeydown(' ', start)
vizact.onkeydown('a', reset)
vizact.onkeydown('r', ready)

Пример #46
0
ori_marker = vrpn.addTracker('Tracker0@' + VRPNserver, 9)
ori_marker.swapPos([1, 2, -3])
ori_marker.swapQuat([-1, -2, 3, 4])
pos_marker = vrpn.addTracker('Tracker0@' + VRPNserver, 4)

# Setup navigation node and link to main view
view = viz.MainView
viewLink = viz.link(ori_marker, view, mask=viz.LINK_ORI)


def UpdatePos():
    pos = pos_marker.getPosition()
    view.setPosition([pos[0], pos[1] - 0.2, -pos[2]], viz.ABS_GLOBAL)


updateView = vizact.ontimer(0, UpdatePos)

########################################################################################################

info = hmd.addMessagePanel(' ', pos=(0, 0, 3))

info.visible(viz.OFF)

# Setup a sound
sound = viz.addAudio('Bottle_80.mp3')  # The metronome.
sound.loop(viz.ON)
sound.volume(1)

alert = viz.addAudio(
    'alert.mp3')  # An alert to notify the participant to stop.
alert.loop(viz.OFF)
Пример #47
0
    if gear > -1:
        gear -= 1


def SwapAuto():
    global auto
    global gear
    global speed
    global steer

    if auto == 1:
        auto = 0
    else:
        auto = 1

    gear = 0
    speed = 0
    steer = 0


#vizact.onkeydown('[', ChangeCar, 1)
#vizact.onkeydown(']', ChangeCar, 2)
vizact.ontimer(0.1, CarUpdate)
vizact.whilekeydown(viz.KEY_UP, Accelerate)
vizact.whilekeydown(' ', Brake)
vizact.whilekeydown(viz.KEY_LEFT, SteerLeft)
vizact.whilekeydown(viz.KEY_RIGHT, SteerRight)
vizact.whilekeydown(viz.KEY_DOWN, Reverse)
vizact.onkeydown('z', GearDown)
vizact.onkeydown('x', GearUp)
vizact.onkeydown('g', SwapAuto)
Пример #48
0
        yaw, pitch, roll = viewLink.getEuler()
        m = viz.Matrix.euler(yaw, 0, 0)
        dm = viz.getFrameElapsed() * MOVE_SPEED
        high = viz.getFrameElapsed() * MOVE_SPEED
        if viz.key.isDown(KEYS['forward']):
            m.preTrans([0, 0, dm])
        if viz.key.isDown(KEYS['back']):
            m.preTrans([0, 0, -dm])
        if viz.key.isDown(KEYS['left']):
            m.preTrans([-dm, 0, 0])
        if viz.key.isDown(KEYS['right']):
            m.preTrans([dm, 0, 0])

        navigationNode.setPosition(m.getPosition(), viz.REL_PARENT)

    vizact.ontimer(0, UpdateView)
else:  # 繋がってないとき
    tracker = vizcam.addWalkNavigate(moveScale=1.0)
    tracker.setPosition([0, 1.8, 0])
    viz.link(tracker, viz.MainView)
    viz.mouse.setVisible(True)

# grid 表示
grid = vizshape.addGrid()
grid.color(viz.GREEN)
viz.clearcolor(viz.BLACK)

viz.mouse.setTrap(True)  #アプリ内でしか動けなくなる
viz.mouse.setVisible(False)
viz.mouse.setOverride(viz.ON)
Пример #49
0
    def __init__(self, UDPmanHdl, SceneDefHdl, DeliveryHdl, oneCtx=0):
        # run super constructor
        viz.EventClass.__init__(self)

        # one context flag for control condition
        self.oneCtx = oneCtx

        if self.oneCtx:
            self.condStr = "oneContext"
        else:
            self.condStr = "twoContexts"

        self.callback(viz.ACTION_END_EVENT, self.updateWalkTarget)

        # save handles
        self.UDPmanHdl = UDPmanHdl
        self.sceneDefHdl = SceneDefHdl
        self.deliveryHdl = DeliveryHdl

        # create background process to calculate
        # closest distances from avPos to house
        # entrance within same context
        self.homeTargetFinder = HomeTargetQueue(DeliveryHdl.grid, oneCtx)

        # add pickup zone targets
        self.homeTargetFinder.addTargets(
            [pZ.getZoneXYZ() for pZ in self.deliveryHdl.pZones],
            [pZ.getCtx() for pZ in self.deliveryHdl.pZones])
        viztask.schedule(self.homeTargetFinder.checkQueue())  # start queue

        # overall number of avatars walking around
        # first half belongs to context 1
        # second half belongs to context 2
        self.nAvtrs = len(SceneDefHdl.agents)

        # list with avatars
        self.avatars = []

        # avatrs that do random actions according to their context
        # will contain copied avatar objects
        self.actors = []

        self.avCtr = [0, 0]

        # get number of different characters that will
        # appear in our scene.
        self.charNames = os.listdir(
            ct.AVATAR_PATH)  # each folder corresponds to one character
        self.nChars = len(self.charNames)

        # add avatars and tell them first wp
        for avInd in range(len(self.UDPmanHdl.agentPos)):
            self.routeAvatar(avInd)

        # define log files for avatar and subject position
        self.avPosLogFile = "%s_%s_%s" % (
            ct.SUBJECT_NAME, self.condStr,
            time.strftime('avPos_%d-%m-%y_%H-%M.txt'))
        self.subjPosLogFile = "%s_%s_%s" % (
            ct.SUBJECT_NAME, self.condStr,
            time.strftime('subjPos_%d-%m-%y_%H-%M.txt'))

        # log avatar position every 5 seconds to text file
        vizact.ontimer(5, self.logAvatarPos)
Пример #50
0

def moveAvatar():
    global curAvatar

    a = random.choice(avatars)
    #so a different avatar is choosen each time
    while (a == curAvatar):
        a = random.choice(avatars)

    curAvatar = a
    walk = vizact.walkTo(random.choice(positions))
    a.runAction(walk)


myTimerAction = vizact.ontimer(4, moveAvatar)
vizact.onkeydown('x', myTimerAction.setEnabled, 0)

#------------Analytics--------------------------

global startTime
analytics = []
cur_dict = {}


def writeToFile():
    global analytics
    global MainViewApproaches
    global startTime

    file = open('analytics_file', 'w')
Пример #51
0
        if self.paused is True:
            return self.TimeWhenItWasPaused
        else:
            return time.time() - self.TimerOffset

    def Pause(self):
        self.TimeWhenItWasPaused = time.time() - self.TimerOffset
        self.paused = True

    def UnPause(self):
        self.TimerOffset = time.time() - self.TimeWhenItWasPaused
        self.paused = False


# define/turn off global events
joy_timer = vizact.ontimer(0, update_joystick)
joy_timer.setEnabled(viz.OFF)
pos_timer = vizact.ontimer(0, check_pos)
pos_timer.setEnabled(viz.OFF)
pos_move_timer = vizact.ontimer(0, check_pos_and_move)
pos_move_timer.setEnabled(viz.OFF)
coor_timer = vizact.ontimer(.25, update_coordinates)
coor_timer.setEnabled(viz.OFF)
write_onkey = vizact.onkeydown('q', write_trial_data)
write_onkey.setEnabled(viz.OFF)
quit_onkey = vizact.onkeydown('q', viz.quit)
quit_onkey.setEnabled(viz.OFF)
time_timer = vizact.ontimer(0, check_time)
time_timer.setEnabled(viz.OFF)

# lauch the program
Пример #52
0
    yield StartDemo(demo2, True)

    breakLimit = 10
    global breakLimit
    index = 0

    track.setEnabled(viz.ON)

    for i in range(0, rounds):

        for sceneIndex in range(i * scenePerRound, ((i + 1) * scenePerRound)):

            print "now loading scene" + str(sceneIndex + 1)
            Sky(1)
            Changescene(sceneIndex)
            yield changeQ(sceneIndex, Qselect, delay, "")
            Sky(0)
            if sceneIndex + 1 == len(env_map_namelist):
                track.setEnabled(viz.OFF)
                tracking_data.close()
                participant_data.close()
                group_data.close()
                finalDemo()
                sys.exit()

        yield recess()


track = vizact.ontimer(.25, headTrack().makeMarkers)
viztask.schedule(exc())
Пример #53
0
sun.alpha(.8)
sun.addAction(vizact.spin(0, 1, 0, 5))


def updateView():
    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)
    elif viz.key.isDown(viz.KEY_LEFT):
        viz.MainView.move([-MOVE_SPEED * viz.elapsed(), 0, 0], viz.BODY_ORI)
    elif viz.key.isDown(viz.KEY_RIGHT):
        viz.MainView.move([MOVE_SPEED * viz.elapsed(), 0, 0], viz.BODY_ORI)


vizact.ontimer(0, updateView)


def onButtonDown(e):
    if e.button is 0 and count >= 0:
        count = count - 1
        if count > 0 and mode is 0:
            viz.MainView.setPosition([0, 0, z_coordinates[count]])
            viz.MainView.setEuler([0, 0, 0])
        if count > 0 and mode is 1:
            viz.MainView.setPosition([x_coordinates[count], -3, -30])
            viz.MainView.setEuler([0, 0, 0])
        if count < 0:
            count = 0

    elif e.button is 1:
Пример #54
0
def main():

    # create instance of class
    com = CenterOfMass()
    # call method in event class
    vizact.ontimer(0, com.calculate_segment_CoM)
Пример #55
0
import viz
import vizact
viz.go()

viz.clearcolor(viz.SLATE)

#Create a quad to display texture
quad = viz.addTexQuad(pos=[0,1.8,3])

#Create texture with repeating wrap mode
tex = viz.addTexture('images/tile_grass.jpg', wrap=viz.REPEAT)
tex.pos = 0

#Apply texture to quad
quad.texture(tex)

ANIMATE_SPEED = 0.1

def animateTexture():
    #Increment texture position
    tex.pos += ANIMATE_SPEED * viz.elapsed()

    #Create transform for texture
    mat = viz.Transform()
    mat.setTrans(tex.pos,0,0)

    #Apply transform to texture
    quad.texmat(mat)

vizact.ontimer(0,animateTexture)
Пример #56
0
    viz.fogcolor(0.7686, 0.8745, 0.8824)
    effect.setEnabled(viz.ON)
    timer.setEnabled(viz.OFF)
    waterSound.stop()
    move_and_scale()


def waterRise():
    waterPlane.setPosition([0, 0.005, 0], viz.REL_LOCAL)
    viewHeight = viz.MainView.getPosition()[1]
    waterHeight = waterPlane.getPosition()[1]
    if waterHeight > (viewHeight - 0.6):
        viz.sendEvent(WATER_RISE_EVENT)


timer = vizact.ontimer(0, waterRise)
timer.setEnabled(viz.OFF)

#'''
#-------------------------------------------------add bubble behaviour------------------------

##---------------------------------------------add sphere around----------------------------------------------
#[-1.79732, 8.96285, -92.03959]

#----------------------------------------add the sphere behaviour----------------------------------------
##----------------------------------------------------------sphere one---------------------------------

#center_pos=([21.57,3.49,-15.08],[31.48,5.88,-11.97],[22.08,4.50,-1.641],[1.2,2,1],[-1.2,2,1])
center_pos = ([-1.53117, 8.69384, -92.32681], [21.57, -30.49, -85.08])

center_num = len(center_pos)
def grabBall():
    gesture = int(sensor.get()[-1])
    gestureText.message(gestureName[gesture])
    object = viz.pick(
    )  # Command detects which object the mouse is currently over and returns it

    if (gesture
            == 0) and (object
                       == basketball):  # Check to see if object is basketball
        print
        "closed fist - gripped basketball"
        #  ser.writelines(b'T')
        global link
        link = viz.grab(hand, basketball)  # Use hand to grab basketball
        glove.getSensorRawAll()

    else:
        print
        "This is not a basketball"
        #  ser.writelines(b'L')
        vizact.ontimer(1, releaseBall)
        vizact.ontimer(2, releaseBall)
        vizact.ontimer(3, releaseBall)
        vizact.ontimer(4, releaseBall)
        vizact.ontimer(5, releaseBall)
        vizact.ontimer(6, releaseBall)
        vizact.ontimer(7, releaseBall)
        vizact.ontimer(8, releaseBall)
        vizact.ontimer(9, releaseBall)
        vizact.ontimer(10, releaseBall)
        vizact.ontimer(11, releaseBall)
        vizact.ontimer(12, releaseBall)
        vizact.ontimer(13, releaseBall)
        vizact.ontimer(14, releaseBall)
        vizact.ontimer(15, releaseBall)
        vizact.ontimer(16, releaseBall)
Пример #58
0
chime_sound = viz.addAudio(sound['chime'])
elevator_sound = viz.addAudio(sound['elevator'])
explosion_sound = viz.addAudio(sound['deslave'])
hammer_sound = viz.addAudio(sound['hammer'])
dirt_sound = viz.addAudio(sound['dirt'])
cave_sound = viz.addAudio(sound['cave'])

viz.MainView.eyeheight(4.75)
#viz.MainView.setPosition(-65,5,8)
toogleCollide(True)

joy = vizjoy.add()

print "MenuPrincipal"

vizact.ontimer(0, UpdateJoystick)

# Key commands
KEYS = {
    'forward': viz.KEY_UP,
    'back': viz.KEY_DOWN,
    'left': viz.KEY_LEFT,
    'right': viz.KEY_RIGHT,
    'reset': 'r',
    'camera': 'c',
    'help': ' '
}

# Initialize window
viz.setMultiSample(8)
viz.go()
Пример #59
0
        viz.startLayer(viz.LINES)

        for i in range(n):
            r = 1.0 / (n)

            newPoint = [
                baseValueX + parametricValueX * 2 * r,
                baseValueY + parametricValueY * 2 * r,
                baseValueZ + parametricValueZ * 2 * r
            ]
            positions.append(newPoint)

            #sphere = vizshape.addSphere(radius=1);
            #sphere.setScale(0.2);
            #sphere.setPosition(newPoint);

            viz.vertex(newPoint)

            n = n - 1
            print positions

        myLines = viz.endLayer()
        markerLink2 = viz.link(marker, myLines)

    if not marker.getVisible() or not endMarker.getVisible():
        triangle.remove()
        triangle2.remove()


vizact.ontimer(0, main)
Пример #60
0
import hand
h = hand.add(sensor)
h.setEuler(0,-90,0)

#Uncomment if you are using it for left hand
#h.leftHand()

tips = []
for x in range(5):
     tips.append( vizshape.addSphere(radius=0.001,color=viz.BLUE) )

def UpdateFingerTips():
  '''
  Uncomment line 1 of this function if you add Fastrak
  '''
  #h.setPosition(fastrak.getPosition())
	for x,tip in enumerate(tips):
		 mat = h.getFingerTip(x)
		 tip.setPosition(mat.getPosition())
		 tip.setQuat(mat.getQuat()) 

vizact.ontimer(0,UpdateFingerTips)

import vizcam
cam = vizcam.PivotNavigate()
cam.setCenter(0,0,0)
cam.setDistance(0.3)

viz.clearcolor(viz.GRAY)