Ejemplo n.º 1
0
    def __init__(self, target_signal=None, motion='suit'):
        super(Experiment, self).__init__()

        self.left_finger = vizshape.addSphere(0.02, color=viz.RED)
        self.right_finger = vizshape.addSphere(0.02, color=viz.GREEN)
        self.target = vizshape.addSphere(0.05, color=viz.WHITE)
        self.target_signal = target_signal

        self.setup_world()
        self.setup_mocap(motion)
        self.setup_proximity()
def setUpHandSensors():
 global rhandtarget, lhandtarget
 rhsphere = vizshape.addSphere(radius = 0.05) 
 rhsphere.setParent(globals_oa.rhModel)
 rhsphere.setPosition([0,0,.55])
 rhsphere.disable(viz.RENDERING)
 lhsphere = vizshape.addSphere(radius = 0.05) 
 lhsphere.setParent(globals_oa.lhModel)
 lhsphere.setPosition([0,0,.55])
 lhsphere.disable(viz.RENDERING)
 if globals_oa.rhModel is not None:rhandtarget = vizproximity.Target(rhsphere)#globals_oa.rhModel)
 if globals_oa.lhModel is not None:lhandtarget = vizproximity.Target(lhsphere)#globals_oa.lhModel)
Ejemplo n.º 3
0
    def __init__(self):

        intersect = vizshape.addSphere(radius=0.1)
        intersect.disable(viz.RENDERING)

        render = vizshape.addSphere(radius=0.075,
                                    color=viz.WHITE,
                                    parent=intersect)
        render.disable(viz.INTERSECTION)

        viz.VizNode.__init__(self, intersect.id)

        self._render = render
        self._looking = False
Ejemplo n.º 4
0
def loadStuffAtStart():
 global city
#loading fadeSphere#
 globals_oa.fadingSphere = vizshape.addSphere(0.5, flipFaces=True)
 globals_oa.fadingSphere.alpha(0)
 globals_oa.fadingSphere.color(viz.BLACK)
 sphereLink = viz.link(viz.MainView, globals_oa.fadingSphere)
#loading the Crystal Ball Scene
 globals_oa.globeScene = vizfx.addChild(globals_oa.FILE_PATH_TO_GLOBE)
 globals_oa.globeScene.setScale([0.2,0.2,0.2])
 globals_oa.globeScene.setPosition([-1,0,0])
 globals_oa.globeScene.disable(viz.RENDERING)
 

 #load city scene assets
 city = vizfx.addChild(globals_oa.FILE_PATH_TO_CITY)
 city.setPosition([-8,0,11])
 city.disable(viz.RENDERING)
 if not globals_oa.transportSetUpCalled:
  transport_vhil.setUp()

 if not globals_oa.loadAudioAssetsCalled:
  audioCache.loadAudioAssets()

# if not globals_oa.initBoatCalled:
#  boat_scene.loadStuffAtStartAndHideThemALL()
  
 if not globals_oa.cg_scene_init_called:
  CG_scenes.loadStuffAtStartAndHideThemALL()
Ejemplo n.º 5
0
	def staticCalibrationMethod(self):
		
		if ( self.calibrationInProgress == False ):
			self.calibrationBlockCounter += 100
			self.toggleRoomWallsVisibility()
			self.calibrationInProgress = True
			self.calibrationCounter = 0
			self.calibrationSphereRadius = self.initialValue
			self.calibrationSphere = vizshape.addSphere(self.calibrationSphereRadius, color = viz.PURPLE)
			self.calibrationSphere.emissive(viz.PURPLE)
			self.calibrationSphere.setParent(self.parentNode)
			self.setSphereRadius(self.parentNode.getPosition(viz.ABS_GLOBAL), self.calibrationPositions[self.calibrationCounter,:], 0)
			print 'FirstPos', self.calibrationPositions[self.calibrationCounter,:]
			newPos = [self.calibrationPositions[self.calibrationCounter,0], self.calibrationPositions[self.calibrationCounter,1], self.calibrationPositions[self.calibrationCounter,2]]
			self.calibrationSphere.setPosition(newPos[0], newPos[1], newPos[2],viz.ABS_PARENT)

			self.text_object = viz.addText('')
			self.text_object.setParent(self.calibrationSphere)
			self.text_object.renderOnlyToWindows([self.renderToWindows])
			self.localAction = vizact.onupdate(viz.PRIORITY_INPUT+1,self.calculateAngularError, self.cyclopEyeSphere.node3D, 0.0, self.text_object)#self.currentTrial.ballObj.node3D

			print 'Static Calibration Started'
		else:
			self.calibrationInProgress = False
			self.calibrationCounter = 0
			self.calibrationSphere.remove()
			self.localAction.remove()
			self.text_object.remove()
			self.toggleRoomWallsVisibility()
			print 'Quit Static Calibration!!'
    def mytask():
        triggerSeries = [
            0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 1, 3, 5, 7, 9, 11, 2, 4, 6,
            8, 10
        ]
        for triggernum in triggerSeries:
            counter = 0
            currentpos = position[str(triggernum)]
            trigger = vizshape.addSphere(
                radius=0.15,
                slices=20,
                stacks=20,
                axis=vizshape.AXIS_Y,
                pos=[currentpos[0], currentpos[1] - 0.9, currentpos[2]])
            trigger.color(viz.RED)
            while True:
                counter += 1
                cue = onlinecueInitial(0.01)

                #serial.serialWrite(counter)
                yield viztask.addAction(squares['square' + str(1)], cue)
                triggerWrite(i)
                yield stistage()
                if counter >= 10:
                    break
            trigger.remove()
Ejemplo n.º 7
0
    def _setup_vizard_configuration(self):
        """
		Setup some stuff for Vizard
		"""
        viz.setMultiSample(cfg.multi_sample_level)

        # Disable the head light for better lighting
        viz.MainView.getHeadLight().disable()

        # Disable the mouse with controller controls.
        # Without deactivation, the controller would move the mouse.
        if cfg.control_scheme == "controller":
            # Trap the mouse in the graphics window.
            viz.mouse.setTrap(viz.ON)
            # Make the mouse invisible.
            viz.mouse.setVisible(viz.OFF)

        # Display models for the trackers
        tracker_names = ['r_hand_tracker', 'l_hand_tracker']
        for tracker_name in tracker_names:
            controller = vizconnect.getRawTracker(tracker_name)

            if cfg.control_scheme == "steamvr":
                if not isinstance(controller, viz.VizGroup):
                    # Display HTC Vive controller model if the controller is connected
                    model = controller.addModel()
                    viz.link(controller, model)

            elif cfg.control_scheme == "controller":
                # Display a sphere, when controlled with a gamepad
                model = vizshape.addSphere(.05, color=viz.GRAY)
                viz.link(controller, model)
Ejemplo n.º 8
0
    def add_sphere(name, rad, col, position, vis, proximity, scale):
        """
        Adds a sphere object and returns it. Optionally adds a proximity sensor around the sphere.

        Args:
            name: name of the sphere object
            rad: radius of the sphere, e.g. 1.0
            col: color of the sphere, e.g. "viz.RED"
            position: specified position by [x, y, z]
            vis: visibility of the sphere, i.e. "viz.ON" or "viz.OFF"
            proximity: if True create a BoundingSphereSensor proximity sensor around the sphere
            scale: scale factor or size of BoundingSphereSensor

        Returns: A Vizard sphere object with the optionality of creating a proximity sensor around the sphere.

        """

        sphere = vizshape.addSphere(radius=rad, color=col)
        sphere.name = name
        sphere.setPosition(position)
        sphere.visible(vis)

        if proximity:
            sphere.sensor = vizproximity.addBoundingSphereSensor(sphere,
                                                                 scale=scale)

        return sphere
Ejemplo n.º 9
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)
Ejemplo n.º 10
0
    def __init__(self, control_style):
        """
        Every instance of class subject should have at least a code.

        Args:
            id: subject Code determined on BeMoBIL subject questionnaire
            sex: male / female
            age: integer of subjects age
            handedness: left / right
            vision: impaired, corrected, corrected-to-normal
            cap_size: EEG cap size
            neck_size: EEG neck size
            labelscheme: EEG labeling scheme of the cap in use (e.g. MoBI, 10/20 etc.)
            control_style: subject interaction with VR
        """

        self._id = id
        self.hand_tracker_id = None
        # self._sex = sex
        # self._age = age
        # self._handedness = handedness
        # self._vision = vision
        # self._cap_size = cap_size
        # self._neck_size = neck_size
        # self._labelscheme = labelscheme

        # register button press events
        self.BUTTON_A_EVENT = viz.getEventID('A')
        self.BUTTON_B_EVENT = viz.getEventID('B')

        if control_style == 'steamvr without PS':
            self.sphere_radius = 0.01
            self.right_hand_sphere = vizshape.addSphere(
                radius=self.sphere_radius)
            self.right_hand_sphere_target = vizproximity.Target(
                self.right_hand_sphere)
            self.right_hand_sphere.alpha(0)
            self.right_hand_sphere.collideSphere()
            self.right_hand_sphere.disable(viz.DYNAMICS)

            self.head_sphere = vizshape.addSphere(radius=self.sphere_radius)
            self.head_sphere_target = vizproximity.Target(self.head_sphere)
            self.head_sphere.alpha(0)
            self.head_sphere.collideSphere()
            self.head_sphere.disable(viz.DYNAMICS)
Ejemplo n.º 11
0
def addSphericalImage( enabled=False, scene=viz.MainScene ):
	landscape = vizshape.addSphere(radius=3.5, flipFaces=True, scene=scene)
	landscape.color(viz.GRAY)
	landscape.emissive(viz.GRAY)
	landscape.setPosition([0.45,1.38,-1.38])
	landscape.alpha(1) if enabled else landscape.alpha(0)

	tex = viz.addTexture('resources/images/parkinglot.jpg')
	landscape.texture(tex)
Ejemplo n.º 12
0
 def __init__(self, index, x, y, z):
     self.index = index
     self.center = x, y, z
     self.sphere = vizshape.addSphere(0.1)
     self.sphere.setPosition(self.center)
     self.sphere.color(viz.WHITE)
     self.sensor = vizproximity.addBoundingSphereSensor(self.sphere, scale=1)
     self.signal = viztask.Signal()
     self.sound = viz.addAudio('{:02d}.wav'.format(index))
Ejemplo n.º 13
0
	def drawEyes(self,draw_eyes):
		"""Draw the eyes of the user"""		
		
		self.__assertBoolean(draw_eyes)		
		
		if self.__left_eye != None:
			self.__left_eye.remove()
			self.__left_eye = None
				
		if self.__right_eye != None:
			self.__right_eye.remove()
			self.__right_eye = None
			
		if draw_eyes:
			self.__left_eye = vizshape.addSphere(self.__EYE_RADIUS)
			self.__left_eye.color(1,0,0)
			self.__right_eye = vizshape.addSphere(self.__EYE_RADIUS)
			self.__right_eye.color(0,1,0)
Ejemplo n.º 14
0
 def __init__(self, index, x, y, z):
     self.index = index
     self.center = x, y, z
     self.sphere = vizshape.addSphere(0.1)
     self.sphere.setPosition(self.center)
     self.sphere.color(viz.WHITE)
     self.sensor = vizproximity.addBoundingSphereSensor(self.sphere,
                                                        scale=1)
     self.signal = viztask.Signal()
     self.sound = viz.addAudio('{:02d}.wav'.format(index))
	def setScreen(self, radius=DEFAULT_RADIUS):
		self.radius = radius
		self.screen = vizshape.addSphere(radius=self.radius,
			slices = 32, stacks = 32,
			flipFaces=True, cullFace=True, lighting=True)
		
		self.screen.setPosition([0,1.82,0]) # Eyeheight
		self.screen.setEuler([180,0,0])
		
		self.screen.emissive([1,1,1])
Ejemplo n.º 16
0
	def dynamicCalibrationMethod(self):
		
		if ( self.calibrationInProgress == False ):
			self.calibrationInProgress = True
			self.toggleRoomWallsVisibility()
			self.calibrationCounter = 27
			self.calibrationSphereRadius = self.initialValue
			self.calibrationSphere = vizshape.addSphere(self.calibrationSphereRadius, color = viz.PURPLE)
			self.calibrationSphere.emissive(viz.PURPLE)
			self.calibrationSphere.setParent(self.parentNode)
			newPos = [-3,-.5,12]
			self.setSphereRadius(self.parentNode.getPosition(viz.ABS_GLOBAL), newPos, 0)
			self.calibrationSphere.setPosition(newPos[0], newPos[1], newPos[2],viz.ABS_PARENT)
			self.targetMovingAction = vizact.onupdate(viz.PRIORITY_INPUT+1, self.checkActionDone)

			self.text_object = viz.addText('')
			self.text_object.setParent(self.calibrationSphere)
			self.text_object.renderOnlyToWindows([self.renderToWindows])
			self.localAction = vizact.onupdate(viz.PRIORITY_INPUT+1,self.calculateAngularError, self.cyclopEyeSphere.node3D, 0.0, self.text_object)#self.currentTrial.ballObj.node3D

			print 'Dynamic Calibration Procedure Started'
			#Use a moveTo action to move a node to the point [0,0,25] at 2 meters per second  
			self.moveAction = vizact.moveTo([-3,-0.5,12],speed=2)
			self.calibrationSphere.addAction(self.moveAction)
			self.moveAction = vizact.moveTo([3,-0.5,12],speed=2)
			self.calibrationSphere.addAction(self.moveAction)
			self.moveAction = vizact.moveTo([3,3,12],speed=2)
			self.calibrationSphere.addAction(self.moveAction)
			self.moveAction = vizact.moveTo([-3,3,12],speed=2)
			self.calibrationSphere.addAction(self.moveAction)
			self.moveAction = vizact.moveTo([-3,-0.5,12],speed=2)
			self.calibrationSphere.addAction(self.moveAction)

			self.moveAction = vizact.moveTo([-3,-0.5,6],speed=2)
			self.calibrationSphere.addAction(self.moveAction)
			self.moveAction = vizact.moveTo([3,-0.5,6],speed=2)
			self.calibrationSphere.addAction(self.moveAction)
			self.moveAction = vizact.moveTo([3,3,6],speed=2)
			self.calibrationSphere.addAction(self.moveAction)
			self.moveAction = vizact.moveTo([-3,3,6],speed=2)
			self.calibrationSphere.addAction(self.moveAction)
			self.moveAction = vizact.moveTo([-3,0,6],speed=2)
			self.calibrationSphere.addAction(self.moveAction)



		else:
			self.localAction.remove()
			self.text_object.remove()
			self.calibrationInProgress = False
			self.calibrationCounter = 0
			self.calibrationSphere.remove()
			self.toggleRoomWallsVisibility()
			print 'Quit Dynamic Calibration!!'
Ejemplo n.º 17
0
def AddSphere(name, position):

    sphere = vizshape.addSphere(radius=0.2)
    sphere.setPosition(position)

    sensor = vizproximity.addBoundingSphereSensor(sphere,scale=5)
    sensor.name = name
    sphereSensors.append(sensor)
    manager.addSensor(sensor)

    manager.onEnter(sensor, EnterSphere, sphere)
    manager.onExit(sensor, ExitSphere, sphere)
Ejemplo n.º 18
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;
Ejemplo n.º 19
0
def setControl(selectedControlSchema, isLeftHanded = 0):
#	global rightHandPitchJitters, leftHandPitchJitters, rightHandYawJitters, leftHandYawJitters
#	rightHandPitchJitters = Queue(maxsize=some_global_variables.numberOfRenderFramesToAverageThreshold)
#	leftHandPitchJitters = Queue(maxsize=some_global_variables.numberOfRenderFramesToAverageThreshold)
#	rightHandYawJitters = Queue(maxsize=some_global_variables.numberOfRenderFramesToAverageThreshold)
#	leftHandYawJitters = Queue(maxsize=some_global_variables.numberOfRenderFramesToAverageThreshold)
#	while not rightHandPitchJitters.full():
#		rightHandPitchJitters.put(0.0)
#		leftHandPitchJitters.put(0.0)
#		rightHandYawJitters.put(0.0)
#		leftHandYawJitters.put(0.0)
	
	vizact.onupdate(0, controlSchemaForAppendages)
	global rightForearmSphere, rightWristSphere, rightFingerSphere, leftForearmSphere, leftWristSphere, leftFingerSphere
	rightForearmSphere = vizshape.addSphere(radius=0.02)
	rightForearmSphere.color(viz.RED)
	rightWristSphere = vizshape.addSphere(radius=0.02)
	rightWristSphere.color(viz.GREEN)
	rightFingerSphere = vizshape.addSphere(radius=0.02)
	rightFingerSphere.color(viz.BLUE)
	leftForearmSphere = vizshape.addSphere(radius=0.02)
	leftForearmSphere.color(viz.CYAN)
	leftWristSphere = vizshape.addSphere(radius=0.02)
	leftWristSphere.color(viz.MAGENTA)
	leftFingerSphere = vizshape.addSphere(radius=0.02)
	leftFingerSphere.color(viz.YELLOW)
	if not some_global_variables.SHOW_SPHERES:
		rightWristSphere.visible(False)
		rightFingerSphere.visible(False)
		leftWristSphere.visible(False)
		leftFingerSphere.visible(False)
		rightForearmSphere.visible(False)
		leftForearmSphere.visible(False)
Ejemplo n.º 20
0
 def __init__(self, window=None, clientMask=viz.MASTER, color=viz.WHITE):
     if window is None:
         window = viz.MainWindow
     view = window.getView()
     self._color = color
     self._clientMask = clientMask
     # Add red quad to flash screen after falling
     self._flashSphere = vizshape.addSphere(10.0, flipFaces=True)
     link = viz.link(view, self._flashSphere)
     link.preTrans([0, 0, 10.1])
     self._flashSphere.color(self._color)
     self._flashSphere.visible(False)
     self._flashSphere.renderOnlyToWindows([window])
Ejemplo n.º 21
0
Archivo: Main.py Proyecto: Dethro16/NFI
	def __init__(self,use_keyboard = True, desktop_mode = False):
		"""Initialization function."""
		#
		viz.phys.enable()
		self.view = viz.MainView;
		
		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\
		self.cylinder = vizshape.addCylinder(15,0.002,axis=vizshape.AXIS_X)
		self.cylinder.setEuler([0,0,0])
		#self.cylinder.setCenter([0,0,-1])
		self.cylinder.setPosition(7.5,0.08,0)
		
		self.stuff = vizshape.addSphere(0.0001)
		self.cylinder.setParent(self.stuff)
		
#		temp = vizshape.addSphere(0.05)
#		temp.setParent(self.cylinder)
#		temp.setPosition(self.cylinder.getCenter())
		
		self.wand = self.stuff
#		self.wand.setPosition(.5,-1,0)
#		self.cm = self.wand.getMatrix()
#		self.Room = viz.addChild('D:\Cave software\NFI Cave\Scene\ScannedRoom.3DS')
#		self.Room.collidePlane()
#		self.Room.setScale([1.25,1.25,1.25])
#		self.Room.setEuler([90,0,0])
#		self.Room.setPosition([-1.5,0,1.55])
		self.Room = viz.addChild('scene/ScannedRoom.3DS')
		self.Room.collidePlane()
		self.Room.setScale([0.002,0.002,0.002])
		self.Room.setEuler([90,0,0])
		self.Room.setPosition([-1.5,0.015,1.58])
		"""
		mylight = viz.addLight() 
		mylight.enable() 
		mylight.position(0, 1, 0) 
		mylight.spread(180) 
		mylight.intensity(2)
#		vizact.onkeydown('f', dance)
		"""
		
		viz.disable(viz.LIGHTING)
		self.headLight = viz.MainView.getHeadLight() #disable the headlight
		self.headLight.disable() #the headlight is disabled because the piazza.osgb is already shaded
		
		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
Ejemplo n.º 22
0
def setup(avatar):
	global headSphere, lhSphere, rhSphere, lfSphere, rfSphere;
	global rhPos, lhPos, rfPos, lfPos, bodyPos;
	
	rhPos = avatar.getBone('Bip01 R Hand').getPosition(viz.ABS_GLOBAL);
	lhPos = avatar.getBone('Bip01 L Hand').getPosition(viz.ABS_GLOBAL);
	rfPos = avatar.getBone('Bip01 R Foot').getPosition(viz.ABS_GLOBAL);
	lfPos = avatar.getBone('Bip01 L Foot').getPosition(viz.ABS_GLOBAL);
	bodyPos = avatar.getBone('Bip01').getPosition(viz.ABS_GLOBAL);
	
	viz.MainView.setPosition(2.2, 0.5, -1.7)
	viz.MainView.setEuler(-110, 0, 0)
	viz.MainWindow.fov(90)
	
	grid = vizshape.addGrid();
	grid.color([0.5] * 3);
	
	global bodyBox;
	bodyBox = vizshape.addBox();
	bodyBox.setScale(0.45, 1.2, 0.35);
	
	bodyBox.visible(viz.OFF);
	
	viz.callback(viz.KEYDOWN_EVENT, onKeyDown);
	
	#link = viz.link(avatar.getBone('Bip01 Head'), viz.MainView)
	#link = viz.link(viz.MainView, avatar.getBone('Bip01 Head'))
	#link.postTrans([0, 0, -0.2]);
	
	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);
		
		headSphere = vizshape.addSphere(radius = 0.1, color = viz.YELLOW);
	return;
Ejemplo n.º 23
0
	def placeEyeNodes(self):
		'''
		For convenience, this places nodes at the cyclopean eye, left eye, and right eye.
		When linkjing things to the eyes, link them to the cyclopean, left, or right eye nodes
		e.g. viz.link(config.cycEyeNode,vizshape.addSphere(radius=0.05))
		'''
		
		IOD = self.hmd.getIPD() 
		print("IOD")
		print(IOD)
		
		self.cycEyeNode = vizshape.addSphere(0.015, color = viz.GREEN)
		self.cycEyeNode.setParent(self.headTracker)
		self.cycEyeNode.disable(viz.RENDERING)
		
		self.leftEyeNode = vizshape.addSphere(0.005, color = viz.BLUE)
		self.leftEyeNode.disable(viz.RENDERING)
		self.leftEyeNode.setParent(self.headTracker)
		self.leftEyeNode.setPosition(-IOD/2, 0, 0.0,viz.ABS_PARENT)
		
		self.rightEyeNode = vizshape.addSphere(0.005, color = viz.RED)
		self.rightEyeNode.disable(viz.RENDERING)
		self.rightEyeNode.setParent(self.headTracker)
		self.rightEyeNode.setPosition(IOD/2, 0, 0.0,viz.ABS_PARENT)
Ejemplo n.º 24
0
def create_bubble():
    for bbbbnum in range(bubble_num):
        pos_b_x = random.randint(-3000, 3000)
        pos_b_y = random.randint(-1000, 100)
        pos_b_z = random.randint(-3000, 3000)
        bubble = vizshape.addSphere(radius=bubble_radius,
                                    pos=(pos_b_x / 100, pos_b_y / 100 - 2,
                                         pos_b_z / 100 - 75),
                                    color=(255, 255, 255),
                                    slices=6,
                                    stacks=6)
        bubble.alpha(bubble_transpare)
        bubble.visible(viz.OFF)
        groups_bubble.append(bubble)
        obj_vis.append(bubble)
Ejemplo n.º 25
0
def addPoliceLights(scene=viz.MainScene):
    policeLight = vizfx.addSpotLight(scene=scene)
    policeLight.setEuler(-105, 0, 0)
    policeLight.color(viz.WHITE)
    policeLight.emissive(viz.WHITE)
    policeLight.spotexponent(1)
    policeLight.quadraticattenuation(1)
    policeLight.intensity(10)

    orb = vizshape.addSphere(radius=0.4, flipFaces=True, scene=scene)
    orb.color(viz.WHITE)
    orb.emissive(viz.WHITE)
    orb.alpha(1)
    viz.link(policeLight, orb)
    return policeLight
Ejemplo n.º 26
0
	def myCalibrationMethod(self):
		
		if ( self.calibrationInProgress == False):
			self.calibrationInProgress = True
			self.calibrationCounter = 0
			self.calibrationSphere = vizshape.addSphere(self.calibrationSphereRadius, color = viz.PURPLE)
			self.calibrationSphere.setParent(self.parentNode)
			self.setSphereRadius(self.parentNode.getPosition(viz.ABS_GLOBAL), self.calibrationPositions[self.calibrationCounter,:], 0)
			print 'FirstPos', self.calibrationPositions[self.calibrationCounter,:]
			newPos = [self.calibrationPositions[self.calibrationCounter,0], self.calibrationPositions[self.calibrationCounter,1], self.calibrationPositions[self.calibrationCounter,2]]
			self.calibrationSphere.setPosition(newPos[0], newPos[1], newPos[2],viz.ABS_PARENT)
			print 'Calibration Procedure Started'
		else:
			self.calibrationInProgress = False
			self.calibrationCounter = 0
			self.calibrationSphere.remove()
			print 'Quit Calibration!!'
def CreateVisualObjects():

    global ball, Head, Hand, GazeLine, EyeBallLine;
    #creats a sphere(the ball) with radius of 5cm
    ball = vizshape.addSphere(radius = .05)
    #colors the ball red
    ball.color(viz.YELLOW)
    ball.visible(True)

    Origin = vizshape.addAxes()
    Origin.setPosition(0,0,0)
    #creats a sphere(the ball) with radius of 5cm
    #Head = vizshape.addCone( radius = 0.5, height = 0.8)
    Head = vizshape.addArrow(1, color = viz.YELLOW_ORANGE)
    #colors the ball red
    Head.color(viz.PURPLE)
    Head.visible(True)
    Head.setScale(.2,.2,.3)

    #creats a sphere(the hand) with radius of 10cm
    Hand = vizshape.addCylinder( height = 0.02, radius = 0.2)
    #colors the hand red
    Hand.color(viz.RED)
    Hand.visible(True)

    # Creating a Line to represent Gaze Vector
    viz.startLayer(viz.LINES)
    viz.vertex(0,0,0)
    viz.vertex(0,0,3)
    viz.vertexColor(viz.GREEN)
    GazeLine = viz.endLayer() # Object will contain both points and lines
    GazeLine.visible(True)
    GazeLine.setScale(5,5,5)


    # Creating a Line to represent Eye-Ball Vector
    viz.startLayer(viz.LINES)
    viz.vertex(0,0,0)
    viz.vertex(0,0,3)
    viz.vertexColor(viz.YELLOW)
    EyeBallLine = viz.endLayer() # Object will contain both points and lines
    EyeBallLine.visible(True)
    EyeBallLine.setScale(5,5,5)
Ejemplo n.º 28
0
 def mytask():
     yield onlineStiStage()
     triggerSeries = [
         0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 1, 3, 5, 7, 9, 11, 0, 2, 4,
         6, 8, 10
     ]
     for triggernum in triggerSeries:
         counter = 0
         currentpos = position[str(triggernum)]
         trigger = vizshape.addSphere(
             radius=0.15,
             slices=20,
             stacks=20,
             axis=vizshape.AXIS_Y,
             pos=[currentpos[0], currentpos[1] - 0.9, currentpos[2]])
         trigger.color(viz.RED)
         yield viztask.addAction(
             trigger,
             timeCountActionInitial(triggerNum=triggernum, timeLength=10))
         trigger.remove()
Ejemplo n.º 29
0
    def baseline(self):
        # set num_sphere positions of spheres randomly, spheres have to be touched then next sphere appears
        # baselines:
        # 1. spectrum (averaging 90% best 1s windows of the baseline period, has touches and walking but no 'task')
        # 2. ersp/connectivity: reaches without meaning but different visual feedback

        # set height of spheres to head - 20cm
        z_range = 3  # lab restrictions
        x_range = 2  # lab restrictions
        height = self.subject.head_sphere.getPosition()[1] - .2

        # number of spheres to touch
        num_sphere = 7

        self.log_exp_progress('type:baseline_start;')
        self.scene.poi_manager.addTarget(self.subject.right_hand_sphere_target)

        # spawn num_sphere balls and touch them consecutively
        for i in range(num_sphere):

            z_pos = random.randrange(0, 2 * z_range + 1) - z_range
            x_pos = random.randrange(0, 2 * x_range + 1) - x_range
            pos = [x_pos, height, z_pos]

            # make a sphere at a random position in the plusminus z and x range
            sphere = vizshape.addSphere(.1)
            sphere.color(viz.YELLOW)
            sphere.setPosition(pos)
            sphere_sensor = vizproximity.addBoundingSphereSensor(sphere)
            self.scene.poi_manager.addSensor(sphere_sensor)

            # yield wait enter hand sphere
            yield vizproximity.waitEnter(sphere_sensor)
            self.log_exp_progress('type:baseline_touch;number:' + str(i + 1) +
                                  ';')
            self.scene.poi_manager.removeSensor(sphere_sensor)
            sphere.remove()

        self.scene.poi_manager.removeTarget(
            self.subject.right_hand_sphere_target)
        self.log_exp_progress('type:baseline_end;')
Ejemplo n.º 30
0
	def __init__(self,eyeTracker,eye,parentNode,renderToWindows = None,sphereColor=viz.RED):
		
		self.sizeInDegrees = 0.5
		self.sphereDistance = 1
		self.renderToWindows = renderToWindows
		from math import tan, radians
		
		self.radius = tan(radians(self.sizeInDegrees)) * self.sphereDistance
		#with viz.cluster.MaskedContext(viz.CLIENT1):
		self.node3D = vizshape.addSphere(radius=self.radius, color = sphereColor, alpha = 0.4)
		
		if( self.renderToWindows ):
			self.node3D.renderOnlyToWindows(self.renderToWindows)
		
		self.node3D.disable(viz.RENDERING)
		
		self.updateAct = []
		
		self.eyeTracker = eyeTracker
		self.eye = eye
		self.node3D.setParent(parentNode)
Ejemplo n.º 31
0
	def __init__(self,eyeTracker,eye,parentNode,renderToWindows = None,sphereColor=viz.RED):
		
		self.sizeInDegrees = 0.5
		self.sphereDistance = 1
		self.renderToWindows = renderToWindows
		from math import tan, radians
		
		self.radius = tan(radians(self.sizeInDegrees)) * self.sphereDistance
		#with viz.cluster.MaskedContext(viz.CLIENT1):
		self.node3D = vizshape.addSphere(radius=self.radius, color = sphereColor, alpha = 0.7)
		
		if( self.renderToWindows ):
			self.node3D.renderOnlyToWindows(self.renderToWindows)
		
		self.node3D.disable(viz.RENDERING)
		
		self.updateAct = []
		
		self.eyeTracker = eyeTracker
		self.eye = eye
		self.node3D.setParent(parentNode)
    def changeScene(self, scene, remove=False):
        ''' Changes IVE scenes based on type IMG , VID , 3D '''

        if scene[-4:] == ".png":
            mode = "IMG"
        elif scene[-4:] == ".MP4":
            mode = "VID"
        elif scene[-4:] == "osgb":
            mode = "3D"

        if remove:
            if mode == "IMG":
                self.sky.remove()
                self.link.remove()
            if mode == "VID":
                self.video.remove()
                self.sky.remove()
        else:

            if mode == "VID":
                print scene
                self.video = viz.addVideo(IMAGE_PATH + "/" + scene)
                self.sky = vizshape.addSphere(radius=10000, flipFaces=True)
                self.sky.texture(self.video)
                self.sky.drawOrder(-100)
                self.video.play()
                self.sky.disable(viz.DEPTH_TEST)
                self.sky.drawOrder(-100)

            if mode == "IMG":
                self.env = viz.addEnvironmentMap(IMAGE_PATH + "/" + scene)
                self.sky = viz.addCustomNode('skydome.dlc')
                self.sky.texture(self.env)

            if mode == "3D":
                scene = viz.add(scene)
                navigationNode = viz.addGroup()
                self.link = viz.link(navigationNode, viz.MainView)
                self.link.preMultLinkable(self.hmd.getSensor())
                self.link.setOffset([0, 1.8, 0])
Ejemplo n.º 33
0
    def _setup_stressindicator(self):
        """
		Setup all objects for the stessindicator.
		"""
        # Create a 3D text to display the measured stress
        self._stressindicator_text = viz.addText3D('3D Text', pos=[0, -1, 0])
        self._stressindicator_text.alignment(viz.ALIGN_LEFT_BOTTOM)
        self._stressindicator_text.color(viz.GREEN)
        self._stressindicator_text.setScale([.05, .05, .05])
        # Create a green sphere where the measurement takes place
        self._stressindicator = vizshape.addSphere(radius=0.01,
                                                   color=viz.GREEN)
        self._stressindicator_text.setParent(self._stressindicator)
        self._stressindicator_text.setPosition([0, .1, 0], viz.ABS_PARENT)
        # Create a group to add an offset to the measurement sphere
        tmp = viz.addGroup()
        self._stressindicator.setParent(tmp)
        self._stressindicator.setPosition([0, -.01, .05], viz.ABS_PARENT)
        self._stressindicator.setEuler([0, 90, 0], viz.ABS_PARENT)
        # Connect the stressindicator to the right controller
        viz.link(vizconnect.getRawTracker('r_hand_tracker'), tmp)
        # Hide the objects until the stressindicator gets used
        self._stressindicator.visible(False)
Ejemplo n.º 34
0
    def setup(self):
        # set up a folder to store data for a subject.
        dirname = self.find_output(threshold_min=GAP_MINUTES)
        self.output = os.path.join(BASE_PATH, dirname)
        logging.info('storing output in %s', self.output)

        # configure the phasespace.
        mocap = vrlab.Phasespace('192.168.1.230', freq=120)
        self.suit = mocap.track_points(range(len(suit.MARKER_LABELS)))
        self.leds = []
        for i in range(50):
            sphere = vizshape.addSphere(0.02, color=viz.RED)
            self.suit.link_marker(i, sphere)
            self.leds.append(sphere)
        mocap.start_thread()

        # set up a proximity manager to detect touch events.
        self.prox = vizproximity.Manager()
        #self.prox.setDebug(viz.ON)

        # add an environment and navigation to help with visualization.
        self.environment = viz.addChild('dojo.osgb')
        viz.cam.setHandler(None)
Ejemplo n.º 35
0
    def setup(self):
        # set up a folder to store data for a subject.
        dirname = self.find_output(threshold_min=GAP_MINUTES)
        self.output = os.path.join(BASE_PATH, dirname)
        logging.info('storing output in %s', self.output)

        # configure the phasespace.
        mocap = vrlab.Phasespace('192.168.1.230', freq=120)
        self.suit = mocap.track_points(range(len(suit.MARKER_LABELS)))
        self.leds = []
        for i in range(50):
            sphere = vizshape.addSphere(0.02, color=viz.RED)
            self.suit.link_marker(i, sphere)
            self.leds.append(sphere)
        mocap.start_thread()

        # set up a proximity manager to detect touch events.
        self.prox = vizproximity.Manager()
        #self.prox.setDebug(viz.ON)

        # add an environment and navigation to help with visualization.
        self.environment = viz.addChild('dojo.osgb')
        viz.cam.setHandler(None)
Ejemplo n.º 36
0
def Create_Shape(Number, x_pace, y_pace, z_pace, set_Time):
    #create an array of shapes
    shapes = []
    #	ranges = ([-10,0],[1,11])
    X = list()  #these will be saved to a file
    Y = list()
    Z = list()
    n = 0
    while (n <= Number):
        x = random.uniform(-4, 4)
        y = random.uniform(-4, 4)
        z = random.uniform(0, 500)

        if (-3 <= x <= 3) and (-3 <= y <= 3):
            print('in exclusion range')
            print(n)
            pass
        else:
            shape = vizshape.addSphere(0.05, 10, 10)
            shape.setPosition([x, y, z])
            shape.color(1, 1, 1)
            shapes.append(shape)
            X.append(x)
            Y.append(y)
            Z.append(z)
            n += 1
            print(n)
    print('X:')
    print(X)
    #	file = open('OpticFlow1.txt','w+')
    #	csvw = csv.writer(file)
    #	csvw.writerow(X)
    #	csvw.writerow(Y)
    #	csvw.writerow(Z)
    #	file.close()

    viz.MainView.velocity(x_pace, y_pace, z_pace)
Ejemplo n.º 37
0
def Create_Shape(Number,x_pace,y_pace,z_pace,set_Time) :
	#create an array of shapes
	shapes = []
#	ranges = ([-10,0],[1,11])
	X = list() #these will be saved to a file
	Y = list()
	Z = list()
	n = 0
	while (n<=Number):
		x = random.uniform(-4,4)
		y = random.uniform(-4,4)
		z = random.uniform(0,500)
		
		if (-3 <= x <= 3) and (-3 <= y <= 3):
			print('in exclusion range')
			print(n)
			pass
		else:
			shape = vizshape.addSphere(0.05,10,10)
			shape.setPosition([x,y,z])
			shape.color(1,1,1)
			shapes.append(shape)
			X.append(x)
			Y.append(y)
			Z.append(z)
			n += 1
			print(n)
	print('X:')
	print(X)
#	file = open('OpticFlow1.txt','w+')
#	csvw = csv.writer(file)
#	csvw.writerow(X)
#	csvw.writerow(Y)
#	csvw.writerow(Z)
#	file.close()
	
	viz.MainView.velocity(x_pace,y_pace,z_pace)
Ejemplo n.º 38
0
def Block3():
    datafile.write('\n')
    datafile.write('Block3')
    global dum3
    if dum == 2.5 and dum2 == 3.5:
        dum3 = 38
    if dum == 2.5 and dum2 == 38:
        dum3 = 3.5
    if dum == 3.5 and dum2 == 2.5:
        dum3 = 38
    if dum == 3.5 and dum2 == 38:
        dum3 = 2.5
    if dum == 38 and dum2 == 2.5:
        dum3 = 3.5
    if dum == 38 and dum2 == 3.5:
        dum3 = 2.5
    targets = [
        4.8, 6.2, 7.6, 9, 10.4, 11.8, 13.2, 14.6, 17.4, 20.2, 23, 25.8, 30,
        float(dum3),
        float(dum3)
    ]
    while len(targets) > 0:
        global k
        k = 0
        yield viztask.waitTime(.5)
        ready_text = viz.addText3D('Get ready!', pos=[-2, 1.7, 20])
        ready_text.color(0, 0, 0)
        yield viztask.waitTime(1)
        ready_text.remove()
        yield viztask.waitTime(2)
        yield room()
        doors = []
        D1 = random.choice([-4.25, -3.25, -2.25, -1.25])
        D2 = random.choice([4.75, 5.75, 6.75, 7.75])
        D3 = random.choice([13.75, 14.75, 15.75, 16.75])
        D4 = random.choice([22.75, 23.75, 24.75, 25.75])
        D5 = random.choice([31.75, 32.75, 33.75, 34.75])
        L_doors = []
        L_doors.append(D1)
        L_doors.append(D2)
        L_doors.append(D3)
        L_doors.append(D4)
        L_doors.append(D5)
        D7 = random.choice([-4.25, -3.25, -2.25, -1.25])
        D8 = random.choice([4.75, 5.75, 6.75, 7.75])
        D9 = random.choice([13.75, 14.75, 15.75, 16.75])
        D10 = random.choice([22.75, 23.75, 24.75, 25.75])
        D11 = random.choice([31.75, 32.75, 33.75, 34.75])
        R_doors = []
        R_doors.append(D7)
        R_doors.append(D8)
        R_doors.append(D9)
        R_doors.append(D10)
        R_doors.append(D11)
        people = []
        P1 = random.choice([-3.75, -2.75, -1.75, .75, 1.75, 2.75, 3.75, 5.25])
        P2 = random.choice(
            [9.25, 10.25, 11.25, 12.25, 18.25, 19.25, 20.25, 21.25])
        P3 = random.choice(
            [27.25, 28.25, 29.25, 30.25, 36.25, 37.25, 38.25, 39.25])
        L_people = []
        L_people.append(P1)
        L_people.append(P2)
        L_people.append(P3)
        P4 = random.choice([-3.75, -2.75, -1.75, .75, 1.75, 2.75, 3.75, 5.25])
        P5 = random.choice(
            [9.25, 10.25, 11.25, 12.25, 18.25, 19.25, 20.25, 21.25])
        P6 = random.choice(
            [27.25, 28.25, 29.25, 30.25, 36.25, 37.25, 38.25, 39.25])
        R_people = []
        R_people.append(P4)
        R_people.append(P5)
        R_people.append(P6)
        targ = random.choice(targets)
        if targ == 2.5:
            size = .051006
        if targ == 3.5:
            size = .071409
        if targ == 4.8:
            size = .097932
        if targ == 6.2:
            size = .126495
        if targ == 7.6:
            size = .155059
        if targ == 9:
            size = .183622
        if targ == 10.4:
            size = .212186
        if targ == 11.8:
            size = .240749
        if targ == 13.2:
            size = .269313
        if targ == 14.6:
            size = .297876
        if targ == 17.4:
            size = .355003
        if targ == 20.2:
            size = .41213
        if targ == 23:
            size = .469257
        if targ == 25.8:
            size = .526384
        if targ == 30:
            size = .612075
        if targ == 38:
            size = .775295
        print targ
        datafile.write('\n')
        datafile.write('%f' % (targ))
        sphere = vizshape.addSphere((size), 20, 20)
        sphere.color(1.02, .444, 0)
        sphere.setPosition([0, (size), (targ)])
        shadow = vizshape.addCircle((size), 20)
        shadow.color([.05, .05, .05])
        shadow.setEuler([0, 90, 0])
        shadow.setPosition([0, .001, (targ)])
        for z in np.asarray(L_doors):
            door = vizshape.addBox(size=[.04445, 2.13, .91])
            door.texture(wood)
            door.setPosition([-4.9733, 1.065, float(z)])
            doors.append(door)
            doorknob = vizshape.addSphere(radius=.045, axis=vizshape.AXIS_X)
            doorknob.color(viz.YELLOW)
            doorknob.setPosition(-4.9396, 1, (float(z) - .3364))
            doors.append(doorknob)
        for z in np.asarray(R_doors):
            door = vizshape.addBox(size=[.04445, 2.13, .91])
            door.texture(wood)
            door.setPosition([4.9683, 1.065, float(z)])
            doors.append(door)
            doorknob = vizshape.addSphere(radius=.045, axis=vizshape.AXIS_X)
            doorknob.color(viz.YELLOW)
            doorknob.setPosition(4.9396, 1, (float(z) - .3364))
            doors.append(doorknob)
        for z in np.asarray(L_people):
            object = random.choice([1, 2, 3])
            if object == 1:
                x = random.choice([0, 90, 180])
                person = viz.addAvatar('vcc_female.cfg',
                                       euler=(float(x), 0, 0))
                person.setPosition([-4.25, 0, float(z)])
                person.state(1)
                people.append(person)
            if object == 2:
                x = random.choice([0, 90, 180])
                person = viz.addAvatar('vcc_male.cfg', euler=(float(x), 0, 0))
                person.setPosition([-4.25, 0, float(z)])
                person.state(1)
                people.append(person)
            if object == 3:
                x = random.choice([0, 90, 180])
                person = viz.addAvatar('vcc_male2.cfg', euler=(float(x), 0, 0))
                person.setPosition([-4.25, 0, float(z)])
                person.state(1)
                people.append(person)
        for z in np.asarray(R_people):
            object = random.choice([1, 2, 3])
            if object == 1:
                x = random.choice([0, 180, 270])
                person = viz.addAvatar('vcc_female.cfg',
                                       euler=(float(x), 0, 0))
                person.setPosition([4.5, 0, float(z)])
                person.state(1)
                people.append(person)
            if object == 2:
                x = random.choice([0, 180, 270])
                person = viz.addAvatar('vcc_male.cfg', euler=(float(x), 0, 0))
                person.setPosition([4.5, 0, float(z)])
                person.state(1)
                people.append(person)
            if object == 3:
                x = random.choice([0, 180, 270])
                person = viz.addAvatar('vcc_male2.cfg', euler=(float(x), 0, 0))
                person.setPosition([4.5, 0, float(z)])
                person.state(1)
                people.append(person)
        targets.remove(targ)
        en_env()
        tic = time.time()
        yield viztask.waitTime(5.5)  #Actually is closer to 5 seconds
        toc = time.time()
        mask.enable(viz.RENDERING)
        dis_env()
        sphere.remove()
        shadow.remove()
        for door in np.asarray(doors):
            door.remove()
        for person in np.asarray(people):
            person.remove()
        yield viztask.waitTime(1)
        mask.disable(viz.RENDERING)
        print toc - tic
        datafile.write(' %f' % (toc - tic))
        viz.callback(viz.KEYDOWN_EVENT, KeyEvents)
        yield viztask.waitKeyDown(viz.KEY_KP_ENTER)
        if k == 1:
            targets.append(targ)
            datafile.write(' targ missed')
Ejemplo n.º 39
0
def view():
    yield room()
    doors = []
    D1 = random.choice([-4.25, -3.25, -2.25, -1.25])
    D2 = random.choice([4.75, 5.75, 6.75, 7.75])
    D3 = random.choice([13.75, 14.75, 15.75, 16.75])
    D4 = random.choice([22.75, 23.75, 24.75, 25.75])
    D5 = random.choice([31.75, 32.75, 33.75, 34.75])
    L_doors = []
    L_doors.append(D1)
    L_doors.append(D2)
    L_doors.append(D3)
    L_doors.append(D4)
    L_doors.append(D5)
    D7 = random.choice([-4.25, -3.25, -2.25, -1.25])
    D8 = random.choice([4.75, 5.75, 6.75, 7.75])
    D9 = random.choice([13.75, 14.75, 15.75, 16.75])
    D10 = random.choice([22.75, 23.75, 24.75, 25.75])
    D11 = random.choice([31.75, 32.75, 33.75, 34.75])
    R_doors = []
    R_doors.append(D7)
    R_doors.append(D8)
    R_doors.append(D9)
    R_doors.append(D10)
    R_doors.append(D11)
    people = []
    P1 = random.choice([-3.75, -2.75, -1.75, .75, 1.75, 2.75, 3.75, 5.25])
    P2 = random.choice([9.25, 10.25, 11.25, 12.25, 18.25, 19.25, 20.25, 21.25])
    P3 = random.choice(
        [27.25, 28.25, 29.25, 30.25, 36.25, 37.25, 38.25, 39.25])
    L_people = []
    L_people.append(P1)
    L_people.append(P2)
    L_people.append(P3)
    P4 = random.choice([-3.75, -2.75, -1.75, .75, 1.75, 2.75, 3.75, 5.25])
    P5 = random.choice([9.25, 10.25, 11.25, 12.25, 18.25, 19.25, 20.25, 21.25])
    P6 = random.choice(
        [27.25, 28.25, 29.25, 30.25, 36.25, 37.25, 38.25, 39.25])
    R_people = []
    R_people.append(P4)
    R_people.append(P5)
    R_people.append(P6)
    for z in np.asarray(L_doors):
        door = vizshape.addBox(size=[.04445, 2.13, .91])
        door.texture(wood)
        door.setPosition([-4.9733, 1.065, float(z)])
        doors.append(door)
        doorknob = vizshape.addSphere(radius=.045, axis=vizshape.AXIS_X)
        doorknob.color(viz.YELLOW)
        doorknob.setPosition(-4.9396, 1, (float(z) - .3364))
        doors.append(doorknob)
    for z in np.asarray(R_doors):
        door = vizshape.addBox(size=[.04445, 2.13, .91])
        door.texture(wood)
        door.setPosition([4.9683, 1.065, float(z)])
        doors.append(door)
        doorknob = vizshape.addSphere(radius=.045, axis=vizshape.AXIS_X)
        doorknob.color(viz.YELLOW)
        doorknob.setPosition(4.9396, 1, (float(z) - .3364))
        doors.append(doorknob)
    for z in np.asarray(L_people):
        object = random.choice([1, 2, 3])
        if object == 1:
            x = random.choice([0, 90, 180])
            person = viz.addAvatar('vcc_female.cfg', euler=(float(x), 0, 0))
            person.setPosition([-4.25, 0, float(z)])
            person.state(1)
            people.append(person)
        if object == 2:
            x = random.choice([0, 90, 180])
            person = viz.addAvatar('vcc_male.cfg', euler=(float(x), 0, 0))
            person.setPosition([-4.25, 0, float(z)])
            person.state(1)
            people.append(person)
        if object == 3:
            x = random.choice([0, 90, 180])
            person = viz.addAvatar('vcc_male2.cfg', euler=(float(x), 0, 0))
            person.setPosition([-4.25, 0, float(z)])
            person.state(1)
            people.append(person)
    for z in np.asarray(R_people):
        object = random.choice([1, 2, 3])
        if object == 1:
            x = random.choice([0, 180, 270])
            person = viz.addAvatar('vcc_female.cfg', euler=(float(x), 0, 0))
            person.setPosition([4.5, 0, float(z)])
            person.state(1)
            people.append(person)
        if object == 2:
            x = random.choice([0, 180, 270])
            person = viz.addAvatar('vcc_male.cfg', euler=(float(x), 0, 0))
            person.setPosition([4.5, 0, float(z)])
            person.state(1)
            people.append(person)
        if object == 3:
            x = random.choice([0, 180, 270])
            person = viz.addAvatar('vcc_male2.cfg', euler=(float(x), 0, 0))
            person.setPosition([4.5, 0, float(z)])
            person.state(1)
            people.append(person)
    en_env()
    tic = time.time()
    yield viztask.waitTime(10.5)
    toc = time.time()
    dis_env()
    print 'View length: ', (toc - tic)
    for door in np.asarray(doors):
        door.remove()
    for person in np.asarray(people):
        person.remove()
Ejemplo n.º 40
0
    def onKeyDown(self, key):
        if (key == viz.KEY_LEFT):
            # turn self.avatar ccw, as viewed from above
            self.ship.yrot -= 2
            self.theta -= 2
        elif (key == viz.KEY_RIGHT):
            # turn self.avatar cw, as viewed from above
            self.ship.yrot += 2
            self.theta += 2
        elif (key == viz.KEY_UP):
            # move avatar forward
            dx = 0.2 * math.sin(math.radians(self.theta))
            dz = 0.2 * math.cos(math.radians(self.theta))
            self.ship.x = self.ship.x + dx
            self.ship.z = self.ship.z + dz
            self.x = self.x + dx
            self.z = self.z + dz
        elif (key == viz.KEY_DOWN):
            # increase the velocity of the ball
            dx = 0.2 * math.sin(math.radians(self.theta))
            dz = 0.2 * math.cos(math.radians(self.theta))
            self.ship.x = self.ship.x - dx
            self.ship.z = self.ship.z - dz
            self.x = self.x - dx
            self.z = self.z - dz

        elif (key == "1"):
            self.start.remove()

            pic = viz.addTexture('snow.jpg')
            # Create surface to wrap the texture on
            self.snow = viz.addTexQuad()
            mat = viz.Matrix()
            mat.postScale(1.995, 1.5, 1.5)
            self.snow.setMatrix(mat)
            self.snow.setPosition([0, 0, 0])  #put quad in view
            # Wrap texture on quad
            self.snow.texture(pic)
            self.mylight.color(.3, .3, .3)
            view = viz.MainView
            mat = viz.Matrix()
            mat.postTrans(0, 0, -1.9)
            view.setMatrix(mat)
            self.t1.remove()
            self.t.remove()
            self.t = viz.addText("Score:" + "" + ` self.score `,
                                 viz.SCREEN,
                                 pos=[0, 0, 0])
            self.t.fontSize(100)
            self.t.font('Chiller')
            self.t1 = viz.addText("Lives:" + "" + ` self.life `,
                                  viz.SCREEN,
                                  pos=[0.8, 0, 0])
            self.t1.fontSize(100)
            self.t1.font('Chiller')

        elif (key == "2"):
            viz.playSound('soundtrack.wav')
            self.mode = "firstperson"

        elif key == 'w':
            if self.deskPressed:
                self.desk.setOrientation(self.desk.getX(), self.desk.getY(),
                                         self.desk.getZ() + 1, 1, 90)
            elif self.shelfPressed:
                self.shelf.setOrientation(self.shelf.getX(), self.shelf.getY(),
                                          self.shelf.getZ() + 1, 1, 0)
        elif key == 'a':
            if self.deskPressed:
                self.desk.setOrientation(self.desk.getX() - 1,
                                         self.desk.getY(), self.desk.getZ(), 1,
                                         90)
            elif self.shelfPressed:
                self.shelf.setOrientation(self.shelf.getX() - 1,
                                          self.shelf.getY(), self.shelf.getZ(),
                                          1, 0)
        elif key == 's':
            if self.deskPressed:
                self.desk.setOrientation(self.desk.getX(), self.desk.getY(),
                                         self.desk.getZ() - 1, 1, 90)
            elif self.shelfPressed:
                self.shelf.setOrientation(self.shelf.getX(), self.shelf.getY(),
                                          self.shelf.getZ() - 1, 1, 0)
        elif key == 'd':
            if self.deskPressed:
                self.desk.setOrientation(self.desk.getX() + 1,
                                         self.desk.getY(), self.desk.getZ(), 1,
                                         90)
            elif self.shelfPressed:
                self.shelf.setOrientation(self.shelf.getX() + 1,
                                          self.shelf.getY(), self.shelf.getZ(),
                                          1, 0)

        elif (key == " "):
            if self.life > 0:
                self.boolean = True
                self.bullet = vizshape.addSphere(radius=.07, color=viz.BLACK)
                mat = viz.Matrix()
                mat.postTrans(self.ship.getX(), self.ship.getY(),
                              self.bZ + 0.05)
                self.bullet.setMatrix(mat)
                self.bullet.collideSphere(bounce=3)
                self.bullet.enable(viz.COLLIDE_NOTIFY)
                self.bullet.setVelocity([0, 0, 5])

        elif (key == viz.KEY_RETURN):
            if self.tower == 1:
                self.snow.remove()
                view = viz.MainView
                mat = viz.Matrix()
                mat.postAxisAngle(1, 0, 0, 30)
                mat.postTrans(4.5, 3.5, .5)
                view.setMatrix(mat)
                viz.playSound('start.wav')
            elif self.tower == 2:
                self.egypt.remove()
                view = viz.MainView
                mat = viz.Matrix()
                mat.postAxisAngle(1, 0, 0, 30)
                mat.postTrans(4.5, 3.5, 7.5)
                view.setMatrix(mat)
                viz.playSound('start.wav')
            elif self.tower == 3:
                self.city.remove()
                view = viz.MainView
                mat = viz.Matrix()
                mat.postAxisAngle(1, 0, 0, 30)
                mat.postTrans(13.5, 3.5, 7.5)
                view.setMatrix(mat)
                viz.playSound('start.wav')
            elif self.tower == 4:
                self.forest7.remove()
                view = viz.MainView
                mat = viz.Matrix()
                mat.postAxisAngle(1, 0, 0, 30)
                mat.postTrans(13.5, 3.5, 0.5)
                view.setMatrix(mat)
                viz.playSound('start.wav')

        if (self.mode == "firstperson"):
            self.start.remove()
            self.mylight.color(.7, .7, .7)
            dx = 0.1 * math.sin(math.radians(self.theta))
            dz = 0.1 * math.cos(math.radians(self.theta))
            view = viz.MainView
            mat = viz.Matrix()
            mat.postAxisAngle(0, 1, 0, self.theta)
            mat.postTrans(self.x, self.y, self.z + 0.15)
            view.setMatrix(mat)
            self.ship.setOrientation(4.5, -17, 4, 0.06, 180)
        self.ship.setTransMatrix()
Ejemplo n.º 41
0
def practice():
    practice_text = viz.addText3D('Practice trials', pos=[-2.5, 1.7, 20])
    practice_text.color(0, 0, 0)
    yield viztask.waitKeyDown(viz.KEY_KP_ENTER)
    practice_text.remove()
    targets = [5, 12, 24]
    while len(targets) > 0:
        global k
        k = 0
        yield viztask.waitTime(.5)
        ready_text = viz.addText3D('Get ready!', pos=[-2, 1.7, 20])
        ready_text.color(0, 0, 0)
        yield viztask.waitTime(1)
        ready_text.remove()
        yield viztask.waitTime(2)
        yield room()
        doors = []
        D1 = random.choice([-4.25, -3.25, -2.25, -1.25])
        D2 = random.choice([4.75, 5.75, 6.75, 7.75])
        D3 = random.choice([13.75, 14.75, 15.75, 16.75])
        D4 = random.choice([22.75, 23.75, 24.75, 25.75])
        D5 = random.choice([31.75, 32.75, 33.75, 34.75])
        L_doors = []
        L_doors.append(D1)
        L_doors.append(D2)
        L_doors.append(D3)
        L_doors.append(D4)
        L_doors.append(D5)
        D7 = random.choice([-4.25, -3.25, -2.25, -1.25])
        D8 = random.choice([4.75, 5.75, 6.75, 7.75])
        D9 = random.choice([13.75, 14.75, 15.75, 16.75])
        D10 = random.choice([22.75, 23.75, 24.75, 25.75])
        D11 = random.choice([31.75, 32.75, 33.75, 34.75])
        R_doors = []
        R_doors.append(D7)
        R_doors.append(D8)
        R_doors.append(D9)
        R_doors.append(D10)
        R_doors.append(D11)
        people = []
        P1 = random.choice(
            [9.25, 10.25, 11.25, 12.25, 18.25, 19.25, 20.25, 21.25])
        P2 = random.choice(
            [27.25, 28.25, 29.25, 30.25, 36.25, 37.25, 38.25, 39.25])
        L_people = []
        L_people.append(P1)
        L_people.append(P2)
        P3 = random.choice(
            [9.25, 10.25, 11.25, 12.25, 18.25, 19.25, 20.25, 21.25])
        P4 = random.choice(
            [27.25, 28.25, 29.25, 30.25, 36.25, 37.25, 38.25, 39.25])
        R_people = []
        R_people.append(P3)
        R_people.append(P4)
        targ = random.choice(targets)
        if targ == 5:
            size = .102012
        if targ == 12:
            size = .24483
        if targ == 24:
            size = .48966
        sphere = vizshape.addSphere((size), 20, 20)
        sphere.color(1.02, .444, 0)
        sphere.setPosition([0, (size), (targ)])
        shadow = vizshape.addCircle((size), 20)
        shadow.color(
            [.05, .05, .05]
        )  #proportion of 1 for amount of each color (red, green, blue). 0,0,0 = black, 1,1,1 = white.
        shadow.setEuler([0, 90, 0])
        shadow.setPosition([0, .001, (targ)])
        for z in np.asarray(L_doors):
            door = vizshape.addBox(size=[.04445, 2.13, .91])
            door.texture(wood)
            door.setPosition([-4.9733, 1.065, float(z)])
            doors.append(door)
            doorknob = vizshape.addSphere(radius=.045, axis=vizshape.AXIS_X)
            doorknob.color(viz.YELLOW)
            doorknob.setPosition(-4.9396, 1, (float(z) - .3364))
            doors.append(doorknob)
        for z in np.asarray(R_doors):
            door = vizshape.addBox(size=[.04445, 2.13, .91])
            door.texture(wood)
            door.setPosition([4.9683, 1.065, float(z)])
            doors.append(door)
            doorknob = vizshape.addSphere(radius=.045, axis=vizshape.AXIS_X)
            doorknob.color(viz.YELLOW)
            doorknob.setPosition(4.9396, 1, (float(z) - .3364))
            doors.append(doorknob)
        for z in np.asarray(L_people):
            x = random.choice([0, 90, 180])
            person = viz.addAvatar('vcc_female.cfg', euler=(float(x), 0, 0))
            person.setPosition([-4.25, 0, float(z)])
            person.state(1)
            people.append(person)
        for z in np.asarray(R_people):
            x = random.choice([0, 180, 270])
            person = viz.addAvatar('vcc_female.cfg', euler=(float(x), 0, 0))
            person.setPosition([4.5, 0, float(z)])
            person.state(1)
            people.append(person)
        targets.remove(targ)
        en_env()
        tic = time.time()
        yield viztask.waitTime(
            .01
        )  #this is necessary to keep the headset display on for the duration of time.sleep. Can't use time.sleep for any longer than 100 ms or so bc it pauses tracking
        time.sleep(
            .09
        )  #this is necessary to be as precise as possible in the display time. Still not perfect bc of unknown processing time of background functions
        toc = time.time()
        mask.enable(viz.RENDERING)
        dis_env()
        sphere.remove()
        shadow.remove()
        for door in np.asarray(doors):
            door.remove()
        for person in np.asarray(people):
            person.remove()
        yield viztask.waitTime(1)
        mask.disable(viz.RENDERING)
        print toc - tic
        viz.callback(
            viz.KEYDOWN_EVENT, KeyEvents
        )  #press Enter (main keyboard) if the participant misses the target and the target will be appended back into the list.
        yield viztask.waitKeyDown(viz.KEY_KP_ENTER)
        if k == 1:
            targets.append(targ)
Ejemplo n.º 42
0
#Test Suite:
#[30,0,0] GOOD
#[10,0,10] GOOD
#[10,5,10] X: 8.944, Y: 4.472
#[10,-5,10] X: 8.944, Y: -4.472
#[10,10,10] X: 7.07, Y: 7.07
#[10,-10,10] X: 7.07, Y: -7.07
#[-10,0,10] GOOD
#[-10,-5,10] X: 8.944, Y: -4.472
#[-10,-6,10] X: 8.575, Y: -5.145

endValueX1 = 10
endValueY1 = 5
endValueZ1 = 10

#the location of [baseValueX1, baseValueY1, baseValueZ1] is the first marker and [endValueX1, endValueY1, endValueZ1]

sphere = vizshape.addSphere(radius=1)
#sphere = viz.addChild('thesis/niceHand_1.dae');
sphere.setPosition([baseValueX1, baseValueY1, baseValueZ1])
#sphere.setEuler(90);

sphere2 = vizshape.addSphere(radius=1)
sphere2.setPosition([endValueX1, endValueY1, endValueZ1])

#positions = setPositionsLinear(positions, numPositions, baseValueX1, baseValueY1, baseValueZ1, endValueX1, endValueY1, endValueZ1);
positions = setPositionsQuadratic(positions, parabolaHeight, baseValueX1,
                                  baseValueY1, baseValueZ1, endValueX1,
                                  endValueY1, endValueZ1)

DrawArrow(positions, parabolaHeight)
Ejemplo n.º 43
0
    y = f.readline()
    y = y.replace('\n', '')
    y = y.split(',')
    for n in range(len(y)):
        y[n] = float(y[n])
    z = f.readline()
    z = z.replace('\n', '')
    z = z.split(',')
    for n in range(len(z)):
        z[n] = float(z[n])
    f.close()
    #	print(type(x[0]))
    #	print(y)
    #	print(z)
    for n in range(len(x)):
        shape = vizshape.addSphere(0.1, 10, 10)
        shape.setPosition([x[n], y[n], z[n]])
        shape.color(1, 1, 1)
        shapes.append(shape)

else:
    print('Error file containing coordinated for flow not found...')

#generate forward velocity
#scroll = vizact.move(0,0,-1*beltspeed,50)
#for x in range(1,50,1):
#	rt["T{0}".format(x)].add(scroll)
#	r2t["T{0}".format(x)].add(scroll)
#	r3t["T{0}".format(x)].add(scroll)
#	r4t["T{0}".format(x)].add(scroll)
#	r5t["T{0}".format(x)].add(scroll)
Ejemplo n.º 44
0
def validation():
	'''
	Show same calibration points and compare calulated gaze point to ground truth. 
	(Displays both + angular error)
	'''
	
	# ask for the sub port
	req.send_string('SUB_PORT')
	sub_port = req.recv_string()

	# open a sub port to listen to pupil
	sub = ctx.socket(zmq.SUB)
	sub.connect("tcp://{}:{}".format(addr, sub_port))
	sub.setsockopt_string(zmq.SUBSCRIBE, u'gaze')

	# add gaze marker
	m_gaze = vizshape.addSphere(radius=sphere_size, color=viz.GREEN)
	m_gaze.disable(viz.INTERSECTION)
	if not gaze_marker_visible:
		m_gaze.disable(viz.RENDER) # invisible but phyisically present



	def get_gaze(eye_number):
		'''
		checks gaze stream for confident measures of the eye (eye_number) until it finds them
		Args:    eye_number (int): 1=left, 0=right
		Returns: [x, y] (float): normalized x and y values range [0,1]
		'''
		found_confident_val = False
		
		while found_confident_val == False:

			topic = sub.recv_string() # unused
			msg = sub.recv()
			msg = loads(msg, encoding='utf-8')
			
			confidence = msg['confidence']
			
			if msg['id'] == eye_number:
				
				if confidence > confidence_level:
				
					found_confident_val = True
					
					t = msg['timestamp'] # unused
					npx = msg['norm_pos'][0]
					npy = msg['norm_pos'][1]
					
					return [npx, npy]


	def updateGaze():	
		'''
		calls 'get_gaze function' and takes the average of two
		eyes for the normal values - they will be used to project a 
		sphere on where subjects look at
		'''
		
		# get gaze data
		norm_pos_x = np.mean([get_gaze(1)[0], get_gaze(0)[0]])
		norm_pos_y = np.mean([get_gaze(1)[1], get_gaze(0)[1]])
				
		# find the intersection and project sphere
		line = viz.MainWindow.screenToWorld([norm_pos_x, norm_pos_y])
		intersection = viz.intersect(line.begin, line.end)
		m_gaze.setPosition(intersection.point)
		
	# update cursor location on every sample		
	vizact.onupdate(viz.PRIORITY_LINKS+1, updateGaze)


	dot_norm_pos=[]
	gaze_norm_pos=[]
	ang_error = []


	yield showMessage('Zum Starten der Validierung die Leertaste drücken')
	
	for p in norm_positions:
		
		print('calibration point: ', p)
	
		norm_x = p[0]
		norm_y = p[1]
		
		first_run = True
		
		if first_run:
			
			first_run = False
		
			'''set up a plane 'right in front of user' on which we want to project the dots'''
	
			# target the current center of view
			p_line = viz.MainWindow.screenToWorld(.5, .5)
		
			# let's modify the line and call it line 2. Here we let the line end at the "depth" value
			p_line_2 = viz.Line(begin=p_line.begin, end=p_line.end, dir=p_line.dir, length=depth)
						
			# Add the plane and apply the matrix of our viewpoint to the plane
			plane = vizshape.addBox(size=[3.6, 2, .1])
			mymat = viz.MainView.getMatrix()
			plane.setMatrix(mymat)
			
			# Reposition the plane to the end of line 2
			plane.setPosition(p_line_2.end)
			plane.color([.25,.25,.25])
			plane.alpha(.95)
			
			# Lock it to user
			plane_link = viz.grab(viz.MainView, plane)
		
		
		# interpolate a line from norm values to 3d coordinates
		line = viz.MainWindow.screenToWorld([norm_x, norm_y])
		
		# find the intersection
		intersection = viz.intersect(line.begin, line.end)
		
		# place a dot (at depth level of line) 
		dot = vizshape.addSphere(radius=sphere_size)
		dot.setPosition(intersection.point)
		
		# lock dot to user
		view_link = viz.grab(viz.MainView, dot)
		
		print('ready')
		viz.playSound('beep500_200.wav')
		yield viztask.waitKeyDown(' ')
				
		for s in range(60):
			
			# get the current pupil time (pupil uses CLOCK_MONOTONIC with adjustable timebase).
			# You can set the pupil timebase to another clock and use that.
			t = get_pupil_timestamp()

			dot_norm_pos.append(p)
			gaze_norm_pos.append(viz.MainWindow.worldToScreen(m_gaze.getPosition()))

			yield viztask.waitTime(1/60.)
			print(t)
		
		dot.color(viz.RED)
		
		print('waiting for next position...')
		
		yield viztask.waitKeyDown(' ')
		
		yield dot.remove()
				
	time.sleep(2)
		
	showMessage('validation done!')
	
	for p in norm_positions:
		
		i = norm_positions.index(p)
		chunk = range(i*60, (i+1)*60)
		print(i)
		dmx = np.mean([gaze_norm_pos[x][0] for x in chunk])
		dmy = np.mean([gaze_norm_pos[y][1] for y in chunk])
		
		# interpolate a line from norm values to 3d coordinates
		line = viz.MainWindow.screenToWorld([p[0], p[1]])
		line_v = viz.MainWindow.screenToWorld([dmx, dmy])
		
		# find the intersection
		intersection = viz.intersect(line.begin, line.end)
		intersection_v = viz.intersect(line_v.begin, line_v.end)
		
		# place a dots (at depth level of line) for both ground truth and gaze point
		dot = vizshape.addSphere(radius=sphere_size)
		dot.setPosition(intersection.point)
		dot.color(viz.BLUE)
		
		dot_v = vizshape.addSphere(radius=sphere_size*0.75)
		dot_v.setPosition(intersection_v.point)
		dot_v.color(viz.YELLOW_ORANGE)
		
		# lock dots to user
		view_link = viz.grab(viz.MainView, dot)
		viel_link2 = viz.grab(viz.MainView, dot_v)
		
		# calculate angular error
		error = vizmat.AngleBetweenVector(line.dir, line_v.dir)
#		cosangle = np.dot(a,b) / (np.linalg.norm(a) * np.linalg.norm(b))
#		angle = np.arccos(cosangle)
#		error = np.degrees(angle)
		
		ang_error.append(error)
		
		print('angle is: ', error, 'for ', p)

	
	showMessage('mean angular error is: {}'.format(np.mean(ang_error)))
	
	print('mean angular error is: ', np.mean(ang_error), ' deg/ visual angle')
Ejemplo n.º 45
0
RIGHTANKLE = 22
RIGHTFOOT = 23

# Store trackers, links, and vizshape objects
trackers = []
links = []
shapes = []

# Start vrpn
vrpn = viz.addExtension('vrpn7.dle')
trackerLocationA = '[email protected]'
trackerLocationB = '[email protected]'
# Now add all trackers and link a shape to it
for i in range(0,24):
	t = vrpn.addTracker(trackerLocationA, i)
	s = vizshape.addSphere(radius = 0.1)
	l = viz.link(t,s)
	trackers.append(t)
	links.append(l)
	shapes.append(s)

	if i == HEAD:
		s.color(viz.GREEN)
	elif i == TORSO:
		s.color(viz.RED)
		# Add an arrow pointing from the torso in the direction the body is facing
		arrow = vizshape.addCylinder(1,0.05,topRadius=0)
		arrow.parent(s)
		arrow.setEuler([0,-90,0])
		arrow.setPosition([0,0,-0.5])
		arrow.color(viz.RED)
    def startLeap(self, headset):
            # Create a listener and controller.
            self.controller = Leap.Controller()
            self.controller.add_listener(self)
            
            # Set controller policies for VR.         
            self.controller.set_policy(Leap.Controller.POLICY_BACKGROUND_FRAMES)
            self.controller.set_policy(Leap.Controller.POLICY_OPTIMIZE_HMD)
            
            # Set up relationships for the hands, joints, bones to the head.
            self.hand_box  = viz.addGroup()
            
            self.left_joints = viz.addGroup()
            self.left_bones  = viz.addGroup()
            self.ljLink = viz.link(self.hand_box, self.left_joints)
            self.lbLink = viz.link(self.hand_box, self.left_bones)
            
            self.right_joints  = viz.addGroup()
            self.right_bones  = viz.addGroup()
            self.rjLink = viz.link(self.hand_box, self.right_joints)
            self.rbLink = viz.link(self.hand_box, self.right_bones)
            
            self.headlink = viz.link(headset, self.hand_box)
            self.headlink.preTrans([0,0,0.1143])
           
            self.rhj = [] # right hand joints (knuckles)
            for i in range(23):
                if i is 0:
                    self.rhj.append(vizshape.addSphere(.015))
                else:
                    self.rhj.append(vizshape.addSphere(self.JOINT_SIZE))
                self.rhj[i].setParent(self.right_joints)
            
            self.rhb = [] # right hand bones
            for i in range(21):
                if (i == 12) or (i == 8) or (i >= 20) :
                    self.rhb.append(vizshape.addCube(.01))
                    self.rhb[i].visible(viz.OFF)
                else:
                    self.rhb.append(vizshape.addCylinder(1.0, self.FINGER_WIDTH, axis=vizshape.AXIS_Z))
                self.rhb[i].setParent(self.right_bones)

            self.lhj = [] # left hand joints (knuckles)
            for i in range(23):
                if i is 0:
                    self.lhj.append(vizshape.addSphere(.015))
                else:
                    self.lhj.append(vizshape.addSphere(self.JOINT_SIZE))
                self.lhj[i].setParent(self.left_joints)
                              
            self.lhb = [] # left hand bones
            for i in range(21):
                if  (i == 12) or (i == 8) or (i >= 20) :
                    self.lhb.append(vizshape.addCube(0.01))
                    self.lhb[i].visible(viz.OFF)
                else:
                    self.lhb.append(vizshape.addCylinder(1.0, self.FINGER_WIDTH, axis=vizshape.AXIS_Z))
                self.lhb[i].setParent(self.left_bones)
                            
            self.right_bones.color(viz.WHITE)
            self.left_bones.color(viz.WHITE)
            self.right_joints.color(viz.AZURE)
            self.left_joints.color(viz.AZURE)
            
            self.initialized = True      
            print 'Initialized the Hands!'
Ejemplo n.º 47
0
def initialize(zonePointer, fileWithListOfObjects):

	global species, nodesToHuntForEachSpecies, nodeNamesToHuntForEachSpecies, numObjectsToFind, displayObjects, dictionaryMappingHuntItemsToNamesFromZoneModel, flagPileSensor

	vizact.onkeydown('-', endHunt)
	
	if globals_oa.scavengerHuntInProgress:
		print "Please finish the previous species search first!"
		return

	#format of the input files:
	# each line has one species, and the nodes of that species from the zone model, which are to be hunted
	# the first name in each line is the name of the species and the following names are the names of the nodes
	# there should be no spaces before or after the commas separating the names
#	speciesWithNodeNamesToHunt = createListFromInputFile(fileWithListOfObjects, False)
	createListFromInputFile(fileWithListOfObjects)
	
#	for s in speciesWithNodeNamesToHunt:
#		species.append(s[0])
#		numObjectsToFind.append(0)
#		nodesToHuntForEachSpecies[s[0]] = []
#		speciesRegex[s[0]] = re.compile(s[1] + '[ ]*\d*$') #Assuming node names are of the form 'species + maybe a space + number'
	hud = None
	if globals_oa.hmdUsed == globals_oa.HMD_TYPE['RIFT']: hud = globals_oa.rift.getHUD()
	displayPos = [0, 0.05, 1]

	print "TO FIND:"
#	for zone in [zonePointer]:#, terrainZone2, terrainZone3]:
	
	for name in zonePointer.getNodeNames():
#			nameBlocks = name.split(' ')
#			if 'Ocinebrina' in nameBlocks:
#				print name
		item = None
		speciesIndexCounter = 0
		for s in species:
#				if speciesRegex[s].match(name):#s in name:
			if name in nodeNamesToHuntForEachSpecies[s]:
				item = zonePointer.getChild(name)
				if item:
					nodesToHuntForEachSpecies[s].append(item)
					dictionaryMappingHuntItemsToNamesFromZoneModel[item] = []
					dictionaryMappingHuntItemsToNamesFromZoneModel[item].append(name)
					numObjectsToFind[speciesIndexCounter] += 1
					if 'octopus' in name.lower():
						Octopus.append(item)
					if 'eel' in name.lower():
						Eel.append(item)
					if 'grass' in name.lower():
						Grass.append(item)
				else:
					print name + ' cannot be located'
				break
			else:
				speciesIndexCounter += 1

#	if globals_oa.currentZoneNumber == 3:
#		addHiddenSnailInZone3()
	
	#adding the display objects for each species for the current zone
#	for s in species:
#		displaySpeciesLoc = globals_oa.DISPLAY_OBJECT_DIRECTORY + str(globals_oa.currentZoneNumber) + '/' + str(s).lower()+ '.osgb'
#		print "loading display object from " + displaySpeciesLoc
#		if hud is not None:
#			displaySpeciesNode = vizfx.addChild(displaySpeciesLoc, pos=displayPos, parent=hud)
#	#		displayEdwardsii = vizfx.addChild(FAUNA_DIRECTORY + globals_oa.SNAIL, pos=displayPos, parent=hud)
#			displaySpeciesNode.visible(False)
#			displayObjects.append(displaySpeciesNode)

	print "SPECIES:"
	print str(len(species))
#	print species
	print nodesToHuntForEachSpecies
	print numObjectsToFind
	
	#set up display objects (all invisible)
#	hud = transport_vhil.rift.getHUD()
#	displayEdwardsii = vizfx.addChild(FAUNA_DIRECTORY + globals_oa.SNAIL, pos=displayPos, parent=hud)
#	displayEdwardsii.visible(False)
#	displayObjects.append(displayEdwardsii)
#	displayOctopus = vizfx.addChild(FAUNA_DIRECTORY + 'octopus_vulgaris/octopus vulgaris.osgb', pos=displayPos, parent=hud)
#	displayOctopus.visible(False)
#	displayObjects.append(displayOctopus)
	
#	global slate
	if globals_oa.slate is not None:
#		slate = vizfx.addChild(EQUIPMENT_DIRECTORY + 'Slate_New.osgb')
#		slateLink = viz.link(viz.MainView, globals_oa.slate, offset = (0, -0.75, 0.0))
#		slateLink.setEuler([None,0,0], 1)
#		slateLink.preTrans(globals_oa.INITIAL_POSITIONAL_OFFSET_FOR_SLATE, 0)
#		slateLink.preEuler(globals_oa.INITIAL_ROTATIONAL_OFFSET_FOR_SLATE)
#		slateLink.clampPosY([-1.25, -0.75])
#	else:
		globals_oa.slate.visible(True)
#	if globals_oa.lhModel is not None: globals_oa.slate.setParent(globals_oa.lhModel)
#	globals_oa.slate.setPosition([0.01, 0, -0.5])
#	globals_oa.slate.setEuler([-90,0,0])
#	globals_oa.slate.setScale([0.8,0.8,0.8])
		
		
#	global basket
#	basket = vizfx.addChild(EQUIPMENT_DIRECTORY + 'diveBasket.osgb')
#	basket.setScale([0.75, 0.85, 0.75])
	globals_oa.basket.visible(True)
	if globals_oa.currentZoneNumber == 1:
		#globals_oa.basket.setPosition([0,-1.74,0]) old basket position
		#globals_oa.basket.setPosition([2,-.2,0])
#		globals_oa.basket.setPosition([2,-1.3,2])
		globals_oa.basket.setPosition(globals_oa.basketPosInCGscene1)
	elif globals_oa.currentZoneNumber == 3:
		globals_oa.basket.setPosition([58.8, -1.78, 0.281726598739624])#947296142578125
#		basketLink = viz.link(viz.MainView, basket, offset = (0, -0.75, 0.0))
#		basketLink.setEuler([None,0,0], 1)
#		basketLink.preTrans([.5, 0, 0.70], 0)
#		basketLink.preEuler([50,0,0])
#		basketLink.clampPosY([-1.25, -0.75])

	
	global basketManager
	basketManager = vizproximity.Manager()
	basketSensor = vizproximity.addBoundingBoxSensor(globals_oa.basket, scale = (1.5, 2, 1.5))
	basketManager.addSensor(basketSensor)
#	basketManager.onEnter(None, selectObject)
	
#	vizact.onkeydown('f',basketManager.setDebug,viz.TOGGLE)
	
	
#	global slateFadingManager
#	slateFadingManager = vizproximity.Manager()
#
#
##	slateFadingManager.addSensor(globals_oa.oceanFloorCollisionSensor)
##	slateFadingManager.addSensor(globals_oa.rockChunkCollisionSensor1)
##	slateFadingManager.addSensor(globals_oa.rockChunkCollisionSensor2)
##	slateFadingManager.addSensor(globals_oa.rockChunkCollisionSensor3)
#	
#	target = vizproximity.Target(globals_oa.slate)
#	slateFadingManager.addTarget(target)
#	
#	slateFadingManager.onEnter(None,EnterProximity)
#	slateFadingManager.onExit(None,ExitProximity)
#	
#	vizact.onkeydown('0',slateFadingManager.setDebug,viz.TOGGLE)

	textScale = 0.05
	
	slateEuler = [0,0,0]
	averageInitPos = [0.0, 1.5, -0.15]
	# Create time limit text
	global time_text
#	if time_text is None:
		
#		time_text_link.setEuler([None,90,0], 2)
#		time_text_link.preTrans([0.0, 0.01, 0.1], 1)
#	else:
	if time_text is not None:
		time_text.visible(True)
#	time_text = viz.addText3D('', pos = [0, 0, 0])
	time_text.alignment(viz.ALIGN_CENTER_TOP)
	time_text.setParent(globals_oa.slate)
#	time_text.setPosition([0,0.01,0.25])
	time_text.setPosition(averageInitPos[0], averageInitPos[1] + 0.5, averageInitPos[2])
	time_text.setEuler(slateEuler)
#		time_text_link = viz.link(globals_oa.slate, time_text)#, offset = (0, 0.01,0.05))
	time_text.setScale(textScale, textScale, textScale)
		
	# Create score text
#	global score_text
#	if score_text is None:
#		#score_text = viz.addText3D('',pos = [-0.4, 0.3, 1], parent=hud)
#		score_text = viz.addText('',pos = [0, 0.01, -0.05])
#		score_text.setScale(textScale, textScale, textScale)
#		score_text.alignment(viz.ALIGN_CENTER_TOP)
#		score_text.setParent(globals_oa.slate)
#		score_text.setPosition([0,0.01,-0.05])
#		score_text.setEuler([180,-90,0])
##		score_text_link = viz.link(globals_oa.slate, score_text)
##		#score_text_link.setMask(viz.LINK_POS)
##		#score_text.setEuler([0, 90, 0], mode = viz.REL_LOCAL)
##		score_text_link.setEuler([None,90,0], 2)
###		score_text_link.preTrans([0.0, 0.01, -0.05], 1)
##		score_text_link.preTrans([0.05, 0.01, 0.0], 1)
##	
#		score_text.color(viz.BLACK)
#		#score_text.alignment(viz.ALIGN_LEFT_TOP)
#		#score_text.setBackdrop(viz.BACKDROP_OUTLINE)
#		#viz.link(viz.MainWindow.LeftTop,score_text,offset=[20,-20,0])
#	else:
#		score_text.visible(True)
#	
	global pics
#	pics = []
#	pics.append( viz.addTexture('resources/Ocinebrina Edwardsii_Zone' + str(globals_oa.currentZoneNumber) + '.png') )
#	pics.append( viz.addTexture('resources/Octopus_2D.png') )
#	pics.append( viz.addTexture('resources/Eel_2D.png') )
#	pics.append( viz.addTexture('resources/seagrass.jpg') ) # Get picture of seagrass
	
	global count_text1
	global count_text2
	global count_text3
	global quad1
	global quad2
	global quad3
	
	if quad1 is not None:
		quad1.visible(True)
		quad2.visible(True)
		quad3.visible(True)
		count_text1.visible(True)
		count_text2.visible(True)
		count_text3.visible(True)
	
#	if quad1 is None: #need to be initialized
#		quad1 = viz.addTexQuad(size = 0.15)
#		quad2 = viz.addTexQuad(size = 0.15)
#		quad3 = viz.addTexQuad(size = 0.15)
#		count_text1 = viz.addText('count: 0')
#		count_text2 = viz.addText('count: 0')
#		count_text3 = viz.addText('count: 0')
		
	#the following should be read from a file carrying textures names for species to be hunted, specific to each zone
	horizontalShift = 0.1
	if globals_oa.currentZoneNumber == 1:
		quad1.setTexQuadDisplayMode(viz.TEXQUAD_FIT)
		quad1.setParent(globals_oa.slate)
#		quad1.setPosition([-.1,0.01,0.1])
		quad1.setPosition(averageInitPos[0] - horizontalShift, averageInitPos[1] + 0.25, averageInitPos[2])
		quad1.setEuler(slateEuler)
		#quad1.setScale([0.75,0.75,0.75])
		quad1.texture(pics[0])
		pics[0].hint(viz.PRELOAD_HINT)
		
		count_text1.setScale(textScale, textScale, textScale)
		count_text1.alignment(viz.ALIGN_CENTER_TOP)
		count_text1.setParent(globals_oa.slate)
		count_text1.setPosition(averageInitPos[0] + horizontalShift, averageInitPos[1] + 0.25, averageInitPos[2])#[0.1,0.01,0.15])
		count_text1.setEuler(slateEuler)
		count_text1.color(viz.BLACK)
		
		
#		quad2.setTexQuadDisplayMode(viz.TEXQUAD_FIT)
#		quad2.setParent(globals_oa.slate)
##		quad2.setPosition([-.1,0.01,-0.1])
#		quad2.setPosition(averageInitPos[0] - horizontalShift, averageInitPos[1] + 0.2, averageInitPos[2])
#		quad2.setEuler(slateEuler)
#		#quad2.setScale([0.75,0.75,0.75])
#		quad2.texture(pics[1])
#		pics[1].hint(viz.PRELOAD_HINT)
#		
#		count_text2.setScale(textScale, textScale, textScale)
#		count_text2.alignment(viz.ALIGN_CENTER_TOP)
#		count_text2.setParent(globals_oa.slate)
##		count_text2.setPosition([0.1,0.01,-0.05])
#		count_text2.setPosition(averageInitPos[0] + horizontalShift, averageInitPos[1] + 0.2, averageInitPos[2])
#		count_text2.setEuler(slateEuler)
#		count_text2.color(viz.BLACK)
		
		quad2.visible(False)
		count_text2.visible(False)
		
#		quad3.setTexQuadDisplayMode(viz.TEXQUAD_FIT)
#		quad3.setParent(globals_oa.slate)
##		quad3.setPosition([-0.1,0.01,-0.3])
#		quad3.setPosition(averageInitPos[0] - horizontalShift, averageInitPos[1] + 0.05, averageInitPos[2])
#		quad3.setEuler(slateEuler)
#		#quad3.setScale([0.75,0.75,0.75])
#		quad3.texture(pics[2])
#		pics[2].hint(viz.PRELOAD_HINT)
#		
#		count_text3.setScale(textScale, textScale, textScale)
#		count_text3.alignment(viz.ALIGN_CENTER_TOP)
#		count_text3.setParent(globals_oa.slate)
##		count_text3.setPosition([0.1,0.01,-0.25])
#		count_text3.setPosition(averageInitPos[0] + horizontalShift, averageInitPos[1] + 0.05, averageInitPos[2])
#		count_text3.setEuler(slateEuler)
#		count_text3.color(viz.BLACK)
		
		quad3.visible(False)
		count_text3.visible(False)
		
	elif globals_oa.currentZoneNumber == 3:
		quad1.setTexQuadDisplayMode(viz.TEXQUAD_FIT)
		quad1.setParent(globals_oa.slate)
#		quad1.setPosition([-0.1,0.01,0.1])
		quad1.setPosition(averageInitPos[0] - horizontalShift, averageInitPos[1] + 0.3, averageInitPos[2])
		quad1.setEuler(slateEuler)
		quad1.texture(pics[0])
		pics[0].hint(viz.PRELOAD_HINT)
		
		count_text1.setScale(textScale, textScale, textScale)
		count_text1.alignment(viz.ALIGN_CENTER_TOP)
		count_text1.setParent(globals_oa.slate)
#		count_text1.setPosition([0.1,0.01,0.15])
		count_text1.setPosition(averageInitPos[0] + horizontalShift, averageInitPos[1] + 0.3, averageInitPos[2])
		count_text1.setEuler(slateEuler)
		count_text1.color(viz.BLACK)
		count_text1.message('found: 0')
		
		quad2.setTexQuadDisplayMode(viz.TEXQUAD_FIT)
		quad2.setParent(globals_oa.slate)
#		quad2.setPosition([-0.1,0.01,-0.1])
		quad2.setPosition(averageInitPos[0] - horizontalShift, averageInitPos[1] + 0.1, averageInitPos[2])
		quad2.setEuler(slateEuler)
		quad2.texture(pics[3])
		pics[3].hint(viz.PRELOAD_HINT)
		
		count_text2.setScale(textScale, textScale, textScale)
		count_text2.alignment(viz.ALIGN_CENTER_TOP)
		count_text2.setParent(globals_oa.slate)
#		count_text2.setPosition([0.1,0.01,-0.05])
		count_text2.setPosition(averageInitPos[0] + horizontalShift, averageInitPos[1] + 0.1, averageInitPos[2])
		count_text2.setEuler(slateEuler)
		count_text2.color(viz.BLACK)
		count_text2.message('found: 0')
		
		quad3.visible(False)
		count_text3.visible(False)


	# Create surface to wrap the texture on 
#	global quad
#	if quad is None:
#		quad = viz.addTexQuad(size = 0.25) 
#		quad.setTexQuadDisplayMode(viz.TEXQUAD_FIT)
#		quad.setParent(globals_oa.slate)
#		quad.setPosition([0,0.01,0])
#		quad.setEuler([180,-90,0])
#		quad.setScale([0.5,0.5,0.5])
#		# Wrap texture on quad 
#		display_image_link = viz.link(globals_oa.slate, quad)# offset = (0.0, 0.01, 0.25))
#		#display_image_link = viz.addTexQuad(texture=viz.add('resources/Ocinebrina Edwardsii.tif'), size=0.1)
#		#display_image_link.setMask(viz.LINK_POS)
#		display_image_link.setEuler([None,90,0], 1)
#		display_image_link.preTrans([0.0, 0.01, 0.25], 0)
#		#quad.setEuler([0, 90, 0], mode = viz.REL_LOCAL)
#		quad.disable(viz.INTERSECTION)
#		quad.disable(viz.LIGHTING)
#		quad.disable(viz.FOG)
	else:
		quad.visible(True)

	
	
	textPos = [0, -0.05, 1]
	speciesTextScale = 0.05
	global speciesText
	if speciesText is None:
		if hud is not None:
			speciesText = viz.addText("", pos=textPos, parent=hud)
			speciesText.alignment(viz.ALIGN_CENTER_TOP)
			speciesText.setScale(speciesTextScale, speciesTextScale, speciesTextScale)
			speciesText.color(viz.BLACK)
			speciesText.visible(False)

	#viz.callback(viz.TIMER_EVENT,onTimer) 

	if (((globals_oa.currentZoneNumber == 0) and globals_oa.scavengerHuntCompleteInTestZone) or ((globals_oa.currentZoneNumber == 1) and globals_oa.scavengerHuntCompleteInZone1) or 
	((globals_oa.currentZoneNumber == 2) and globals_oa.scavengerHuntCompleteInZone2) or ((globals_oa.currentZoneNumber == 3) and globals_oa.scavengerHuntCompleteInZone3)):
		print "This scavenger hunt is already completed! Please try the hunt in a different zone."
		return

	print 'Scavenger Hunt started'
	global scavengerHuntStartSound
	if scavengerHuntStartSound is None:
		scavengerHuntStartSound = loadAudioFile(AUDIO_DIRECTORY + 'bell.wav')
	
	#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
	global flagPileManager
	flagPileSensor = vizproximity.Sensor(vizproximity.Sphere(.3,center=[1.3, -1.23484, 0.8]), source=flagPile)
	flagPileManager = vizproximity.Manager()
	flagPileManager.addSensor(flagPileSensor)
	vizact.onkeydown(';', flagPileManager.setDebug, viz.TOGGLE)

	
	#scavengerHuntStartSound.play()
	#vizact.onsensordown(globals_oa.wiimote, globals_oa.wii.BUTTON_B,selectObject)
	if (globals_oa.hmdUsed == globals_oa.HMD_TYPE['VIVE']) and (globals_oa.rhViveTracker is not None):
		print "USING VIVE"
		#vizact.onsensordown(globals_oa.rhViveTracker, steamvr.BUTTON_TRIGGER,selectObject)
#		if globals_oa.rhViveTracker:
#			handModel1 = globals_oa.rhViveTracker.addModel()
#			link1 = viz.link(globals_oa.rightHandLink, handModel1)
#		if globals_oa.lhViveTracker:
#			handModel2 = globals_oa.lhViveTracker.addModel()
#			link2 = viz.link(globals_oa.leftHandLink, handModel2)
			
#		from tools import grabber
#		from tools import highlighter
#		global rhtool, lhtool
#		
#		if rhtool is None:
#			rhtool = grabber.Grabber(usingPhysics=False, usingSprings=False, highlightMode=highlighter.MODE_BOX)
#		if lhtool is None:
#			lhtool = grabber.Grabber(usingPhysics=False, usingSprings=False, highlightMode=highlighter.MODE_BOX)
		
#		rhtool.setUpdateFunction(rUpdateGrabber)
#		if globals_oa.rhModel is not None:rhtool.setParent(globals_oa.rhModel)
#		
#		lhtool.setUpdateFunction(lUpdateGrabber)
#		if globals_oa.lhModel is not None: lhtool.setParent(globals_oa.lhModel) 
		#sphere = vizshape.addSphere(radius = 0.3)
		
		#sphere.setParent(globals_oa.rhModel)
		
		global rhandtar, lhandtar
		if globals_oa.rhModel is not None:
			rhsphere = vizshape.addSphere(radius = 0.05) 
			rhsphere.setParent(globals_oa.rhModel)
			rhsphere.setPosition([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.05) 
			lhsphere.setParent(globals_oa.lhModel)
			lhsphere.setPosition([0,0,.55])
			lhsphere.disable(viz.RENDERING)
			lhandtar = vizproximity.Target(lhsphere)#globals_oa.lhModel)
			snailTouchManager.addTarget(lhandtar)
			flagPileManager.addTarget(lhandtar)
#		basketManager.addTarget(rhandtar)
#		basketManager.addTarget(lhandtar)

	#adding the sensors around the snails
	for snailAndFlagItem in globals_oa.snailAndFlagItemsInZone1:
		snailSensor = vizproximity.addBoundingSphereSensor(snailAndFlagItem.snailItemFromZoneModel, scale = (1.0))
		snailTouchManager.addSensor(snailSensor)
	
	def EnterProximity(e):
		global snapFlagLeftHand, snapFlagRightHand
		if e.target == lhandtar:
			snapFlagLeftHand()
		elif e.target ==rhandtar:
			snapFlagRightHand()
	flagPileManager.onEnter(flagPileSensor, EnterProximity)

		#viz.link(globals_oa.rhModel, tool)
#		viz.callback(grabber.GRAB_EVENT,grabObject)
#		viz.callback(grabber.RELEASE_EVENT, releaseObject)
	
	snailTouchManager.onEnter(None, ShowFlagAtSnail)
	
	if globals_oa.currentZoneNumber == 1: globals_oa.MOVEMENT_DATA_RECORDING_TAG = globals_oa.TAG_SCAVENGER_HUNT_START_ZONE_1
	else: globals_oa.MOVEMENT_DATA_RECORDING_TAG = globals_oa.TAG_SCAVENGER_HUNT_START_ZONE_3
	
	global speciesIndex, numFound
	speciesIndex = 0
	numFound = 0
	viztask.schedule( findObject() )
Ejemplo n.º 48
0
    def __init__(self):

        viz.EventClass.__init__(self)

        # curve that represents the track
        self.track = CoasterCurve()

        # controls the camera's view in 3rd person
        self.rotateView = 0
        self.distView = -200
        self.view = 3

        # Environment map - puts the scene inside a large box and
        # texture maps sky images onto the six box sides.
        sky = viz.add(viz.ENVIRONMENT_MAP, 'sky.jpg')
        skybox = viz.add('skydome.dlc')
        skybox.texture(sky)

        # Create a coaster car consisting of a box with a spherical cap in front.
        # The front of the car faces down the -Z axis.
        self.car = viz.addGroup()
        c1 = vizshape.addBox([2, 2, 4], color=viz.GREEN)
        m = viz.Matrix()
        m.postTrans(0, 1, 0)  # raise bottom of box to XY plane
        c1.setMatrix(m)
        c1.setParent(self.car)
        c1 = vizshape.addBox([1, 2, 1.9], color=viz.BLACK)
        m = viz.Matrix()
        m.postTrans(0, 1.5, 1)
        c1.setMatrix(m)
        c1.setParent(self.car)
        c2 = vizshape.addSphere(radius=1, color=viz.YELLOW)
        m = viz.Matrix()
        m.postTrans(0, 1, -2)  # move to front of box
        c2.setMatrix(m)
        c2.setParent(self.car)

        viz.startLayer(viz.LINE_STRIP)
        viz.vertexColor(viz.BLACK)
        for i in range(1, 928):
            temp = self.track.getLocationAtDist(i)
            viz.vertex(temp)
        self.lineStrip = viz.endLayer()

        self.tunnel = vizshape.addCylinder(height=75,
                                           radius=10,
                                           bottom=False,
                                           top=False,
                                           cullFace=False)
        m = viz.Matrix()
        m.postAxisAngle(1, 0, 0, 90)
        m.postMult(self.track.getCurOrient())
        m.postTrans(self.track.getCurLocation())
        m.postTrans(75, 0, 0)
        self.tunnel.setMatrix(m)

        self.tunnelText = viz.addTexture('tunnel.jpg')
        self.tunnel.texture(self.tunnelText)

        # set key board callback function
        self.callback(viz.KEYDOWN_EVENT, self.onKeyDown)

        # call keyboard callback to initialize the view to 3rd person
        self.onKeyDown("3")
hmd = oculus.Rift()
hmd.getSensor

global targetL
targetL = 0.2649054
global targetR
targetR = 0.2586855

global targetmean
targetmean = (targetR+targetL)/2

global targettol
targettol = 0.02

global circleL #slow leg circle marker
circleL = vizshape.addSphere(0.01,50,50,color=viz.GREEN)
circleL.setPosition(-0.03,targetL,0)
circleL.disable(viz.LIGHTING)#no shading, we don't want depth perception here

global circleR #slow leg circle marker
circleR = vizshape.addSphere(0.01,50,50)
circleR.color(1,0.7,0)
circleR.setPosition(0.04,targetR,0)
circleR.disable(viz.LIGHTING)#no shading, we don't want depth perception here

global highlightr
highlightr = vizshape.addBox(size=[0.25,0.0175,0.001])
highlightr.color(0,0,1)
highlightr.setPosition(0.145,targetmean,0)
highlightr.disable(viz.LIGHTING)
Ejemplo n.º 50
0
def main():
    # global variables
    global debug
    global pieces
    global shape
    global sidebar
    global sidebarBG
    global blockState
    global cursor
    global cursorPos
    global highlightedObj
    global highlightedObjType
    global selectedObj
    global selectedObjType
    global animRot
    global identity
    global selectedIndex
    global won
    global is900Sensor1
    global old_data
    global all_data
    global iSenseMode

    # ---------------------------------------------------------------------------
    # init vizard

    # initialize pdb if debugging is needed
    # pdb.set_trace()

    # init intersense tracker
    iSenseMode = False
    # 	isense = viz.add('intersense.dle')
    # 	# wand.
    # 	if isense.valid() == True :
    # 		iSenseMode = True
    # 		is900Sensor1 = isense.addTracker(port=1,station=2)

    # 	viz.add('court.ive')

    """
	Set the pivot point 2 meters above the origin.
	Set the rotation mode to blend its orientation
	from its current orientation to that associated
	with the pivot.
	"""
    # 	gotoRight = vizact.goto([2,1,-2],rotate_mode=viz.BLEND_ROTATE,pivot=[0,2,0],ori_mask=viz.BODY_ORI)
    # 	gotoLeft = vizact.goto([-2,2,-2],rotate_mode=viz.BLEND_ROTATE,pivot=[0,2,0],ori_mask=viz.BODY_ORI)

    # Use keyboard actions to move the viewpoint.
    # 	vizact.onkeydown(viz.KEY_ALT_L, viz.MainView.runAction, gotoRight )
    #
    # 	vizact.onkeydown(viz.KEY_ALT_R, viz.MainView.runAction, gotoLeft )

    # 	cam = vizcam.PivotNavigate(center=[0,1,0],distance=4)
    # 	viz.cam.setHandler(cam)
    #
    # 	cam.enabled = True
    # 	viz.cam.setHandler(vizcam.KeyboardCamera())

    # 	vizcam.PivotNavigate(center=[0,1,0],distance=5)

    # assign space mouse callbacks
    # viz.callback(vizspace.ROTATE_EVENT,spaceRot)

    old_data = []
    all_data = []

    # set the maximum frame rate to something lower than the minimum the application runs
    # so that the FPS is constant throughout the run
    viz.setOption("viz.max_frame_rate", "60")

    # set the full screen monitor to 1
    viz.setOption("viz.fullscreen.monitor", 2)

    # start in full screen
    # viz.go(viz.FULLSCREEN)
    viz.go()

    # 	vizcam.PivotNavigate(center=[0,1,0],distance=5)

    # set cursor visibility
    # viz.mouse.setVisible(viz.OFF)

    # enable backface culling
    viz.enable(viz.CULL_FACE)

    # set clear color for raster
    viz.clearcolor(Colors.WHITE)

    # ---------------------------------------------------------------------------
    # init variables

    # flag to toggle debug breakpoints - Use 'x' to toggle
    debug = False

    # list of pieces available
    pieces = []

    # won the game
    won = False

    # group with all cubes in their final position - read from file
    shape = viz.add(viz.GROUP, viz.WORLD)

    # input file with description of pieces and
    # input_file = open('puzzle.txt','r')
    # parseInputFile(input_file)
    # since we still don't have an input format, we build the puzzle manually
    buildPuzzle(3, 3, 3)

    # create sidebar to indicate existing pieces/possibilities
    sidebar = []
    sidebarBG = createQuad([0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0])
    sidebarBG.depthFunc(viz.GL_ALWAYS)
    sidebarBG.drawOrder(100)
    buildSideBar()

    animRot = 0

    identity = vizmat.Transform()
    identity.makeIdent()

    cursor = vizshape.addSphere(radius=0.2)
    cursor.color(Colors.LIGHT_BLUE)
    cursorPos = [0.0, 0.0, 3.0]

    selectedObj = None
    selectedObjType = None
    selectedIndex = -1
    highlightedObj = None
    highlightedObjType = None

    # assign keyDown and keyUp as callback functions for events
    viz.callback(viz.KEYDOWN_EVENT, keyDown)
    viz.callback(viz.KEYUP_EVENT, keyUp)

    # register the update function to be called every iteration of the main loop
    vizact.ontimer(0, update)
Ejemplo n.º 51
0
def addAvatar():
    global shader, avatar, num, link
    global ghostAvatar
    global gender
    if gender == 0:
        avatar = viz.add("tweaked/female_050912/CC2_m002_hipoly_A3.cfg")
        if skin == 9:
            texture = viz.addTexture("skin_tones/010.png")
            texture.wrap(viz.WRAP_S, viz.REPEAT)
            texture.wrap(viz.WRAP_T, viz.REPEAT)
        else:
            texture = viz.addTexture("skin_tones/00" + skinChoices[skin] + ".png")
            texture.wrap(viz.WRAP_S, viz.REPEAT)
            texture.wrap(viz.WRAP_T, viz.REPEAT)
        avatar.texture(texture)
        avatar.emissive([0.75, 0.75, 0.75])
        ghostAvatar = viz.add("tweaked/female_050912/CC2_m002_hipoly_A3.cfg")
    else:
        avatar = viz.add("tweaked/Male_New/CC2_m002_hipoly_A3.cfg")
        if skin == 9:
            texture = viz.addTexture("skin_tones/010.png")
            texture.wrap(viz.WRAP_S, viz.REPEAT)
            texture.wrap(viz.WRAP_T, viz.REPEAT)
        else:
            texture = viz.addTexture("skin_tones/00" + skinChoices[skin] + ".png")
            texture.wrap(viz.WRAP_S, viz.REPEAT)
            texture.wrap(viz.WRAP_T, viz.REPEAT)
        avatar.texture(texture)
        avatar.emissive([0.75, 0.75, 0.75])
        ghostAvatar = viz.add("tweaked/Male_New/CC2_m002_hipoly_A3.cfg")
    ghostAvatar.visible(viz.OFF)

    avatar.neck = avatar.getBone("Bip01 Neck")
    avatar.head = avatar.getBone("Bip01 Head")
    avatar.head.lock()

    # Initialize Avatar bones
    if USE_HMD:
        bone = None
        pptExtension.mAvatarBones = avatar.getBoneList()
        numBones = len(pptExtension.mAvatarBones)
        for i in range(0, numBones):
            bone = pptExtension.mAvatarBones[i]
            bone.lock()  # Disable automatic bone animatics on
            pptExtension.mAvatarBoneNames.append(bone.getName())
            pptExtension.mAvatarBonePositions.append(bone.getPosition(viz.ABS_GLOBAL))
    else:
        bone.lock()  # Disable automatic bone animation
        pptSimulation.mAvatarBoneNames.append(bone.getName())
        pptSimulation.mAvatarBonePositions.append(bone.getPosition(viz.ABS_GLOBAL))
    ghostAvatarBones = ghostAvatar.getBoneList()
    for i in range(0, numBones):
        bone = ghostAvatarBones[i]
        bone.lock()

    avatar.state(1)
    avatar.setEuler([180.0, 0.0, 0.0])
    ghostAvatar.setEuler([180.0, 0.0, 0.0])

    avatar.setPosition([0, 0.0, -2])
    ghostAvatar.setPosition([0, 0.0, -2])

    num += 1
    if num >= NUM_AVATARS:
        num = 0

        # Add finger collisions
    leftFingerBones = ["Bip01 L Finger1Nub", "Bip01 L Finger2Nub", "Bip01 L Finger3Nub", "Bip01 L Finger4Nub"]
    # fingerBones.extend(['Bip01 R Finger1Nub', 'Bip01 R Finger2Nub', 'Bip01 R Finger3Nub', 'Bip01 R Finger4Nub'])
    rightFingerBones = ["Bip01 R Finger1Nub", "Bip01 R Finger2Nub", "Bip01 R Finger3Nub", "Bip01 R Finger4Nub"]

    # for bone in fingerBones:
    for bone in leftFingerBones:
        finColObj = vizshape.addSphere(radius=0.005)
        viz.link(avatar.getBone(bone), finColObj)
        finColObj.collideSphere()
        finColObj.disable(viz.DYNAMICS)
        finColObj.disable(viz.RENDERING)
        leftHandIDs.append(finColObj.id)

    for bone in rightFingerBones:
        finColObj = vizshape.addSphere(radius=0.005)
        viz.link(avatar.getBone(bone), finColObj)
        finColObj.collideSphere()
        finColObj.disable(viz.DYNAMICS)
        finColObj.disable(viz.RENDERING)
        rightHandIDS.append(finColObj.id)
Ejemplo n.º 52
0
def setup(isLeftHanded):
	global lhPPT, rhPPT, lfPPT, rfPPT, headPPT, headLink, headPPTmarker, rhPPTlink, lhPPTlink, offsetTimerEvent
	global lhSphere, rhSphere
	global riftLink
	
	#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)
	
	vrpn = viz.add('vrpn7.dle');
	PPT_HOSTNAME = '171.64.33.43';
	
	#ading the headPPT marker
#	headPPTmarker = vrpn.addTracker('PPT0@' + PPT_HOSTNAME, 0);
	headPPTmarker = vrpn.addTracker('PPT0@' + PPT_HOSTNAME, some_global_variables.headPPTmarkerVirtualID - 1);
	headMarkerNode = viz.addGroup()
	headMarker = viz.link(headPPTmarker, headMarkerNode)
#	headMarker.preTrans(list(EYE_VECTOR))
#	headMarker.setOffset(some_global_variables.pptMarkerWeirdOffset)
	
	#now add the PPT hands tracker
	if isLeftHanded == 0:
		#user right-handed
#		rhPPT = vrpn.addTracker('PPT0@' + PPT_HOSTNAME, 1)
#		rhPPT = vrpn.addTracker('PPT0@' + PPT_HOSTNAME, some_global_variables.rhPPTmarkerVirtualID - 1)
		rhPPTmarker = vrpn.addTracker('PPT0@' + PPT_HOSTNAME, some_global_variables.rhPPTmarkerVirtualID - 1)
#		lhPPT = vrpn.addTracker('PPT0@' + PPT_HOSTNAME, 2)
		lhPPTmarker = vrpn.addTracker('PPT0@' + PPT_HOSTNAME, some_global_variables.lhPPTmarkerVirtualID - 1)
	else:
		#user left-handed
#		rhPPT = vrpn.addTracker('PPT0@' + PPT_HOSTNAME, 2)
		rhPPTmarker = vrpn.addTracker('PPT0@' + PPT_HOSTNAME, some_global_variables.rhPPTmarkerVirtualID)
#		lhPPT = vrpn.addTracker('PPT0@' + PPT_HOSTNAME, 1)
		lhPPTmarker = vrpn.addTracker('PPT0@' + PPT_HOSTNAME, some_global_variables.lhPPTmarkerVirtualID)
	if USE_LEG:
		rfPPT = vrpn.addTracker('PPT0@' + PPT_HOSTNAME, 3)
		lfPPT = vrpn.addTracker('PPT0@' + PPT_HOSTNAME, 4)

	headPPT = None
	headTracker = None
	#loading rift
	#rift = oculus.Rift()
	#headTracker = rift.getSensor()
	if headTracker is None:
		#DK2 not found, trying the vive now
		hmd = steamvr.HMD()
		headTracker = hmd.getSensor()
		headPPT = headTracker
		#activating a timer to adjust the PPT-Vive offset at runtime
		if some_global_variables.ADJUST_PPT_VIVE_OFFSET_AT_RUNTIME:
			offsetTimerEvent = vizact.ontimer(0, offsetTimer)
	else:
		vizact.onkeydown('r',headTracker.reset)
		headPPT = viz.mergeLinkable(headMarker,headTracker)
	
	#if rift is not available
	
	#Merge two links together
	#headPPT = viz.mergeLinkable(headPPTmarker,headTracker)
	headLink = viz.link(headPPT, viz.MainView);
	#headLink.postTrans([EYE_VECTOR[0], EYE_VECTOR[1], EYE_VECTOR[2]]);
	riftLink = headLink
	#riftLink.preTrans(EYE_VECTOR)
	#view.preTrans(EYE_VECTOR)
	#headPPT.preTrans([0,10,0]);
	
	rhPPT = viz.addGroup()
	rhPPTlink = viz.link(rhPPTmarker, rhPPT)
#	rhPPTlink.setOffset(some_global_variables.pptMarkerWeirdOffset)

	lhPPT = viz.addGroup()
	lhPPTlink = viz.link(lhPPTmarker, lhPPT)
#	lhPPTlink.setOffset(some_global_variables.pptMarkerWeirdOffset)

	
	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;
Ejemplo n.º 53
0
#Declare some constants
GRID_WIDTH = 6
GRID_HEIGHT = 6
SPACING = 1.1
MAX_BALLS = 20
MIN_POWER = 5
MAX_POWER = 10

#We need to enable physics
viz.phys.enable()

balls = []

for x in range(MAX_BALLS):
    ball = vizshape.addSphere(0.05, color=viz.BLACK)
    ball.collideSphere()
    balls.append(ball)

#Create a generator this will loop through the balls
nextBall = viz.cycle(balls)

#Add a green marker that will show where we are aiming, disable picking on it
import vizshape
marker = vizshape.addSphere(radius=0.1, color=viz.GREEN)
marker.visible(False)
marker.disable(viz.PICKING)

#Add a progress bar to the screen that will show how much power is charged up
power = viz.addProgressBar('Power', pos=(0.8, 0.1, 0))
power.disable()
		m.setEuler(euler)
		m.preEuler(bones[bone][1])
		bone.setEuler(m.getEuler(), viz.ABS_GLOBAL)
		
vizact.ontimer(0, animate)

viz.MainView.setPosition([0, 2.5, 1.8])
viz.MainView.setEuler([180, 25, 0])


############### interactive activity ###############

viz.phys.enable()

#Set right hand interaction
rightHandSphere = vizshape.addSphere(radius = 0.08)
rightHandSphere.color( viz.BLUE )
rightHandSphere.alpha( 0.3 )
rightHandSphere.collideSphere(radius = 0.08)
rightHandSphere.enable( viz.COLLIDE_NOTIFY )
rightHandSphere.disable( viz.DYNAMICS )
rightHandLink = viz.link( avatar.getBone('Bip01 R Finger0') , rightHandSphere )
rightHandLink.preTrans([0,0,0])

#Set left hand interaction
leftHandSphere = vizshape.addSphere(radius = 0.08)
leftHandSphere.color( viz.BLUE )
leftHandSphere.alpha( 0.3 )
leftHandSphere.collideSphere(radius = 0.08)
leftHandSphere.enable( viz.COLLIDE_NOTIFY )
leftHandSphere.disable( viz.DYNAMICS )
Ejemplo n.º 55
0
    numPoints = 20
    if j >= 2: numPoints = 1
    for i in range(0, numPoints):
        if j == 0: 
            col = viz.BLUE
        elif j == 1:
            col = viz.RED
        elif j == 2:
            col = viz.GREEN
        elif j == 3:
            col = viz.YELLOW
        elif j == 4:
            col = viz.PURPLE
        else:
            col = viz.ORANGE
        sphere = vizshape.addSphere(radius = 0.1, color = col)
        skeletons[j].append(sphere)

def renderMan():
    sensor.refreshData()
    kinectTimeStamp = sensor.getKinectTimeStamp(0)
    #print (kinectTimeStamp / 1000.0)
    for j in range (0,2):
        skeletonData = sensor.getTrackedSkeleton(0, j)
        numPoints = 20
        if j >= 2: numPoints = 1
        if skeletonData != None:
            #print skeletonData
            
            temp = sensor.getTrackedSkeletonNums(0)
            skelNum = temp[0]
Ejemplo n.º 56
0
def setup():
	global leftWristPPT, rightWristPPT, lfPPT, rfPPT, headPPT, viewLink, navigationNode
	global lhSphere, rhSphere
	global hmdLink
	#add more trackers for trying things out
	global rightFingersPPT, leftFingersPPT, leftForeArmPPT, rightForeArmPPT, rightHandViveController, leftHandViveController
	
	#nvis.nvisorSX111();
	#nvis.nvisorSX60();
	#try the oculus rift
	hmd = None
	headOriTracker = None
	
	if some_global_variables.PPT1:
		vrpn = viz.add('vrpn7.dle')

	#trying to connect the vive now
	if not some_global_variables.DONT_USE_VIVE:
		hmd = steamvr.HMD()
		headOriTracker = hmd.getSensor()
	headPosTracker = None
	headPosLink = None

	if headOriTracker is None:
		print "HTC Vive is not connected. Trying Oculus Rift now"
		hmd = oculus.Rift()
		headOriTracker = hmd.getSensor()
		if headOriTracker is None:
			print "Rift is also not connected!"
		else:
			print "Connected to Rift!"
			vizact.onkeydown('r',headOriTracker.reset)
			if some_global_variables.PPT1:
				headPosTracker = vrpn.addTracker('PPT0@' + some_global_variables.PPT_HOSTNAME, some_global_variables.PPT_HEAD_VIRTUAL_ID - 1)
				headPosTrackerNode = viz.addGroup()
				headPosLink = viz.link(headPosTracker, headPosTrackerNode)
				headPosLink.preTrans(list(EYE_VECTOR))
	else:
		print "Connected to Vive!"

	#Merge position and orientation links for the head tracker, if needed
	if headPosLink is not None:
		#using DK2 in PPT1 with a PPT marker for head tracking
		headPPT = viz.mergeLinkable(headPosLink,headOriTracker)
	else:
		#like using vive, or DK2 outside PPT1
		headPPT = headOriTracker

	if headOriTracker is not None:
		some_global_variables.headTrackingActive = True

	viz.mouse.setVisible(False)
	#viz.cursor(viz.OFF);
	view = viz.MainView

	viewLink = None
	navigationNode = viz.addGroup()
	viewLink = viz.link(navigationNode, viz.MainView)
	if headPPT is not None:
		viewLink.preMultLinkable(headPPT)
		
	if not some_global_variables.PPT1:
		viewLink.setOffset([0,1.4,0])
#		viewLink = viz.link(headPPT, viz.MainView)
	#viewLink.postTrans([EYE_VECTOR[0], EYE_VECTOR[1], EYE_VECTOR[2]])
	#hmdLink.preTrans(EYE_VECTOR)
	#view.preTrans(EYE_VECTOR)
	#headPPT.preTrans([0,10,0]);
	
	#now add the PPT hands tracker
	if some_global_variables.PPT1:
		rightForeArmPPT = vrpn.addTracker('PPT0@' + some_global_variables.PPT_HOSTNAME, some_global_variables.PPT_RIGHT_FOREARM_VIRTUAL_ID-1)
		if rightForeArmPPT is not None: print "right forearm tracker is active with virtual PPT ID = " + str(some_global_variables.PPT_RIGHT_FOREARM_VIRTUAL_ID)

		leftForeArmPPT = vrpn.addTracker('PPT0@' + some_global_variables.PPT_HOSTNAME, some_global_variables.PPT_LEFT_FOREARM_VIRTUAL_ID-1)
		if leftForeArmPPT is not None: print "left forearm tracker is active with virtual PPT ID = " + str(some_global_variables.PPT_LEFT_FOREARM_VIRTUAL_ID)
		
		appendageControlWithVive = vizinput.choose('Using Vive controllers or a bunch of PPT markers?', ['Vive','4 extra PPT marker!'])
		
		if appendageControlWithVive == 0: #using vive hand controllers
			some_global_variables.usingViveHandControllers = True
			viveHandControllerList = steamvr.getControllerList()
			controllerCount = 0
			for controller in steamvr.getControllerList():
				controllerCount += 1
				#Right Hand Controller Setup
				if controllerCount == 1:
				  rightHandViveController = viveHandControllerList[0]
				#Left Hand Controller Setup
				elif controllerCount == 2:
				  leftHandViveController = viveHandControllerList[1]
		else: #using four extra PPT markers - could be noisy due to interference
			rightFingersPPT = vrpn.addTracker('PPT0@' + some_global_variables.PPT_HOSTNAME, some_global_variables.PPT_RIGHT_FINGERS_VIRTUAL_ID-1)
			if rightFingersPPT is not None: print "right fingers tracker is active with virtual PPT ID = " + str(some_global_variables.PPT_RIGHT_FINGERS_VIRTUAL_ID)

			leftFingersPPT = vrpn.addTracker('PPT0@' + some_global_variables.PPT_HOSTNAME, some_global_variables.PPT_LEFT_FINGERS_VIRTUAL_ID-1)
			if leftFingersPPT is not None: print "left fingers tracker is active with virtual PPT ID = " + str(some_global_variables.PPT_LEFT_FINGERS_VIRTUAL_ID)

			rightWristPPT = vrpn.addTracker('PPT0@' + some_global_variables.PPT_HOSTNAME, some_global_variables.PPT_RIGHT_WRIST_VIRTUAL_ID-1)
			if rightWristPPT is not None: print "right wrist tracker is active with virtual PPT ID = " + str(some_global_variables.PPT_RIGHT_WRIST_VIRTUAL_ID)

			leftWristPPT = vrpn.addTracker('PPT0@' + some_global_variables.PPT_HOSTNAME, some_global_variables.PPT_LEFT_WRIST_VIRTUAL_ID-1)
			if leftWristPPT is not None: print "left wrist tracker is active with virtual PPT ID = " + str(some_global_variables.PPT_LEFT_WRIST_VIRTUAL_ID)

			
	
	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
Ejemplo n.º 57
0
def calibration():
	''' The heart of the calibration routine. Presents points and collects data. '''


	# start calibration routine and sample data
	n = {'subject':'calibration.should_start', 'hmd_video_frame_size':(2160,1200), 'outlier_threshold':35}
	print(send_recv_notification(n))


	ref_data = []
	
	yield showMessage('Zum Starten die Leertaste drücken')
	
	for p in norm_positions:
		
		print('calibration point: ', p)
	
		norm_x = p[0]
		norm_y = p[1]
		
		first_run = True
		
		if first_run:
			
			first_run = False
		
			'''set up a plane 'right in front of user' on which we want to project the dots'''
	
			# target the current center of view
			p_line = viz.MainWindow.screenToWorld(.5, .5)
		
			# let's modify the line and call it line 2. Here we let the line end at the "depth" value
			p_line_2 = viz.Line(begin=p_line.begin, end=p_line.end, dir=p_line.dir, length=depth)
						
			# Add the plane and apply the matrix of our viewpoint to the plane
			plane = vizshape.addBox(size=[3.6, 2, .1])
			mymat = viz.MainView.getMatrix()
			plane.setMatrix(mymat)
			
			# Reposition the plane to the end of line 2
			plane.setPosition(p_line_2.end)
			plane.color([.25,.25,.25])
			plane.alpha(.95)
			
			# Lock it to user
			plane_link = viz.grab(viz.MainView, plane)
		
		
		# interpolate a line from norm values to 3d coordinates
		line = viz.MainWindow.screenToWorld([norm_x, norm_y])
		
		# find the intersection
		intersection = viz.intersect(line.begin, line.end)
		
		# place a dot (at depth level of line) 
		dot = vizshape.addSphere(radius=sphere_size)
		dot.setPosition(intersection.point)
		
		# lock dot to user
		view_link = viz.grab(viz.MainView, dot)
		
		print('ready')
		viz.playSound('beep500_200.wav')
		yield viztask.waitKeyDown(' ')
				
		for s in range(60):
			
			# get the current pupil time (pupil uses CLOCK_MONOTONIC with adjustable timebase).
			# You can set the pupil timebase to another clock and use that.
			t = get_pupil_timestamp()

			# here the left and right screen marker positions are identical.
			datum0 = {'norm_pos':p,'timestamp':t,'id':0}
			datum1 = {'norm_pos':p,'timestamp':t,'id':1}
			ref_data.append(datum0)
			ref_data.append(datum1)
			yield viztask.waitTime(1/60.)
			print(t)
		
		dot.color(viz.RED)
		
		print('waiting for next position...')
		
		yield viztask.waitKeyDown(' ')
		
		yield dot.remove()
		
	

	# send ref data to Pupil Capture/Service:
	# this notification can be sent once at the end or multiple times.
	# during one calibraiton all new data will be appended.
	n = {'subject':'calibration.add_ref_data','ref_data':ref_data}
	print(send_recv_notification(n))

	# stop calibration
	# pupil will correlate pupil and ref data based on timestamps,
	# compute the gaze mapping params, and start a new gaze mapper.
	n = {'subject':'calibration.should_stop'}
	print(send_recv_notification(n))

	time.sleep(2)
		
	showMessage('calibration done! - now validate!')

	plane.remove()
	
	yield viztask.waitTime(2)
Ejemplo n.º 58
0
    def __init__(self, canvas):

        sf = 0.5
        model.pointer.setEuler(0, 0, 0)
        model.pointer.setPosition(0, 0, 0)
        self.gloveStart = model.pointer.getPosition()
        self.iterations = 0
        self.canvas = canvas
        self.origPosVec = config.positionVector
        self.origOrienVec = config.orientationVector

        # creating directions panel
        # 		viz.mouse.setVisible(False)
        # 		directions = vizinfo.InfoPanel('', fontSize = 10, parent = canvas, align = viz.ALIGN_LEFT_TOP, title = 'Tutorial', icon = False)
        # 		if config.pointerMode ==0:
        # 			directions.addItem(viz.addText('Keyboard Controls:'))
        # 			directions.addLabelItem(viz.addText('W'))
        #
        # 		if config.pointerMode ==1:
        # 			directions.addItem(viz.addText('Spacemouse Controls:'))
        # 			directions.addItem(viz.addTexQuad(size = 300, parent = canvas, texture = viz.addTexture('.\\mouse key.png')))

        # creating tutorial objects
        self.dog = viz.addChild(".\\dataset\\dog\\dog.obj")
        self.dogOutline = viz.addChild(".\\dataset\\dog\\dog.obj")
        self.dogStart = self.dog.getPosition()
        self.dog.setScale([sf, sf, sf])
        self.dogOutline.setScale([sf, sf, sf])
        self.startColor = model.pointer.getColor()

        # creating dog outline
        self.dogOutline.alpha(0.8)
        self.dogOutline.color(0, 5, 0)
        self.dogOutline.texture(None)

        # creating proximity manager
        self.manager = vizproximity.Manager()

        """creating dog grab and snap sensors around sphere palced in the center of the dog"""
        self.dogCenter = vizshape.addSphere(0.1, pos=(self.dogStart))
        self.dogSnapSensor = vizproximity.Sensor(vizproximity.Sphere(0.35, center=[0, 1, 0]), source=self.dogCenter)
        self.outlineCenter = vizshape.addSphere(0.1, pos=(self.dogStart))

        self.dogCenter.setPosition([0, -0.35, 0])
        self.outlineCenter.setPosition([0, -0.35, 0])

        self.centerStart = self.dogCenter.getPosition()
        self.dogGrab = viz.grab(self.dogCenter, self.dog)
        self.outlineGrab = viz.grab(self.outlineCenter, self.dogOutline)

        self.dogCenter.color(5, 0, 0)
        self.outlineCenter.color(0, 5, 0)
        self.dogCenter.visible(viz.OFF)
        self.outlineCenter.visible(viz.OFF)

        self.dogSnapSensor = vizproximity.Sensor(vizproximity.Sphere(0.35, center=[0, 1, 0]), source=self.dogCenter)
        self.manager.addSensor(self.dogSnapSensor)
        self.dogGrabSensor = vizproximity.Sensor(vizproximity.Sphere(0.85, center=[0, 1, 0]), source=self.dogCenter)
        self.manager.addSensor(self.dogGrabSensor)

        """creating glove target and a dog target. the dog target is a sphere placed at the center of the dog outline"""
        self.gloveTarget = vizproximity.Target(model.pointer)
        self.manager.addTarget(self.gloveTarget)
        self.dogTargetMold = vizshape.addSphere(0.2, parent=self.dogOutline, pos=(self.dogStart))
        self.dogTargetMold.setPosition([0, 1.2, 0])
        self.dogTargetMold.visible(viz.OFF)
        self.dogTarget = vizproximity.Target(self.dogTargetMold)
        self.manager.addTarget(self.dogTarget)

        # manager proximity events
        self.manager.onEnter(self.dogGrabSensor, EnterProximity, self.gloveTarget, model.pointer)
        self.manager.onExit(self.dogGrabSensor, ExitProximity, model.pointer, self.startColor)
        self.manager.onEnter(self.dogSnapSensor, snapCheckEnter, self.dogTarget)
        self.manager.onExit(self.dogSnapSensor, snapCheckExit, self.dogTargetMold)

        # reset command
        self.keybindings = []
        self.keybindings.append(
            vizact.onkeydown("l", resetGlove, self.manager, self.gloveStart, self.dogCenter, self.outlineCenter)
        )
        self.keybindings.append(vizact.onkeydown("p", self.debugger))

        # task schedule
        self.interface = viztask.schedule(self.interfaceTasks())
        self.gameMechanics = viztask.schedule(self.mechanics())
Ejemplo n.º 59
0
    #import vizshape
    #vizshape.addGrid()

    piazza = viz.addChild('piazza.osgb')
    viz.window.setFullscreenMonitor(2)
    viz.go(viz.FULLSCREEN)

    viz.clearcolor(viz.BLACK)

    #######

    sg = mocap.returnPointerToRigid('shutter')

    import vizshape
    sgSphere = vizshape.addSphere(radius=0.02)

    # First, link visual to rigid body
    sg.link_pose(sgSphere)

    #######

    import matplotlib
    matplotlib.use('agg')
    import matplotlib.pyplot as plt

    import vizmatplot

    plotDur = 3

    ###---matplotlib codes---####
hmd.getSensor

global targetL
targetL = 0.5099501

global targetR6
targetR = 0.5237383

global targetmeann
targetmean = (targetR + targetL) / 2

global targettol
targettol = 0.02

global circleL  #slow leg circle marker
circleL = vizshape.addSphere(0.01, 50, 50, color=viz.GREEN)
circleL.setPosition(-0.03, targetL, 0)
circleL.disable(viz.LIGHTING)  #no shading, we don't want depth perception here

global circleR  #slow leg circle marker
circleR = vizshape.addSphere(0.01, 50, 50)
circleR.color(1, 0.7, 0)
circleR.setPosition(0.04, targetR, 0)
circleR.disable(viz.LIGHTING)  #no shading, we don't want depth perception here

global highlightr
highlightr = vizshape.addBox(size=[0.25, 0.0175, 0.001])
highlightr.color(0, 0, 1)
highlightr.setPosition(0.145, targetmean, 0)
highlightr.disable(viz.LIGHTING)