Exemplo n.º 1
0
def initialise_display():
	
	# viz.message('Calibration on Pupil Capture must be set to Manual Marker')
	
	#load scene for luminance.
	# start empty world
	EH = 1.2 #metres from ground.
	Eye_ScreenDist = 1 #distance from screen of ocular point
	Proj_V = 1.12 #measured on 18/01/18 #vertical extent of projection (m)
	Proj_H = 1.965 #horizontal extent of projection (m)

	# setting Field-of-View fov(vertical degree, horizontal ratio(vertical*ratio[deg]))
	vfov = ((np.arctan((Proj_V/2)/Eye_ScreenDist))*2) * (180/np.pi)
	h2v = Proj_H/Proj_V

	#viz.setDisplayMode(1920,1080)
	viz.go()
	viz.window.setSize(1920,1080)
	#viz.fov(vfov,h2v) #sets window aspect ratio.
	viz.fov(vfov,h2v) #sets window aspect ratio.
	#viz.window.setSize([1920,1080]) 
	#viz.window.setBorder(viz.BORDER_NONE)	
	#viz.window.setFullscreen(1)
	#viz.window.setFullscreenMonitor(2)
	#viz.window.setFullscreenRectangle( [0,0,1920,1080] )

	viz.eyeheight(1.2)#viz.MainView.setPosition(0,EH,0) 
	viz.clip(1,60) #clips world at 60m
	# background color
	viz.clearcolor(viz.SKYBLUE)	
Exemplo n.º 2
0
 def fwdMovementCallback(self):
     if self.movement != Movement:
         self.outputMove('ContMv')
         print 'Continuous: Mode', self.mode, 'Moves = ', self.movement.GetNumForwardMoves(
         )
     if self.mode == 'Explore' and HotSpots.InHotSpot():
         self.VisitedHotSpots.mark(HotSpots.InHotSpot())
         if self.VisitedHotSpots.all():
             if not self.positionList:
                 endPos = None
             else:
                 positionPair = self.positionList.pop()
                 endPos = positionPair[1]
                 while endPos == HotSpots.InHotSpot(
                 ) and self.positionList.count(endPos) < len(
                         self.positionList):
                     #only get another position if the list contains a position other than endPos
                     self.positionList.insert(0, endPos)
                     s, endPos = self.positionList.pop()
             HotSpots.StartTrials(numtrials=1,
                                  callback=self.callback,
                                  targetHotspot=endPos,
                                  AnnounceLater=0)
     elif self.mode == 'BoundedWander':
         if (self.movement.GetNumForwardMoves() > self.moveBound):
             SoundQueue.PlaySound('SharedMedia/Sounds/Finished.wav')
             viz.clearcolor(1, 1, 1)
             self.closeCurtain()
             self.openCurtain()
             viz.clearcolor(0, 0, 0)
             print "Finished BoundedWander after", self.movement.GetNumForwardMoves(
             ), "moves"
             if self.onFinish: self.onFinish(self)
 def EvalTest(self, train):
     if (train.numSuccess >= train.numGoodTrials
             and (train.numGoodTrials == 1 or train.VisitedHotSpots.all())):
         print "Achieved competency"
         train.log("### Achieved competency\n")
         dir = GetDirections(self.prefix, self.env, group=self.group)
         train.onFinish = next.Next
         next.setTrain(train)
         next.Next(train)
     # Director will have more inefficient routes than efficient, or has too many failures.
     elif (((self.numTrials + train.numGoodTrials) >
            (self.maxTrials + train.numSuccess))
           or (train.numFailures > 3)):
         print "Failed test"
         train.log("### Failed competency\n")
         self.setTrain(train)  #reset
         (self.startPos, self.endPos) = self.QuizList.pop()
         train.onFinish = self.Prep
         viz.clearcolor(0, 0, 0)
         train.numSuccess = 0
         train.numOK = 0
         train.numFailures = 0
         train.MoveToNext(self.startPos, 'BoundedWander')
     else:
         print "Continue test with trial ", self.numTrials, " and successes ", train.numSuccess
         self.Prep(train)
Exemplo n.º 4
0
def mykeyboard(whichKey):
    print 'The following key was pressed: ', whichKey
    global color
    color = color ^ 1

    if whichKey == viz.KEY_F1:
        print 'Fkey 1 pressed'
    elif whichKey == viz.KEY_F2:
        print 'Fkey 2 pressed'
    elif whichKey == viz.KEY_F3:
        print 'Fkey 2 pressed'
    elif whichKey == viz.KEY_F4:
        print 'Fkey 2 pressed'
    elif whichKey == viz.KEY_UP:
        print 'Up arrow pressed'
    elif whichKey == viz.KEY_DOWN:
        print 'Down arrow pressed'
    elif whichKey == viz.KEY_LEFT:
        print 'Left arrow pressed'
    elif whichKey == viz.KEY_RIGHT:
        print 'Right arrow pressed'
    elif whichKey == viz.KEY_ESCAPE:
        print '==================================================='
        print '==================================================='
        print '==================================================='
        print '==================================================='
        print '==================================================='
        print '==================================================='
        print '==================================================='
        print '==================================================='
        print '==================================================='


    viz.clearcolor(color, color, color)
Exemplo n.º 5
0
def createEnvironment():	
	#create 2D environment
	if parameters.DreiDEnvironment:
		viz.clearcolor(viz.WHITE)

		#look from above
		viz.MainView.setPosition([0,50,0])
		viz.MainView.setEuler([0,90,0])
		
		goal.setEuler(0,90,0)
		goal.color(viz.GREEN)
		
		point.setEuler(0,90,0)
		point.setPosition(0,20,0)
		point.color(viz.RED)	
		
		arrow.setPosition(0,20,0)
		arrow.color(viz.BLUE)
	#or create 3d environment
	else:
		piazza = viz.addChild('piazza.osgb')
	
		#look from above
		viz.MainView.setPosition([0,1.8,0])
		#viz.MainView.setEuler([0,90,0])
		
		goal.setEuler(0,90,0)
		goal.color(viz.GREEN)
		
		point.setEuler(0,90,0)
		point.setPosition(0,20,0)
		point.color(viz.RED)	
		
		arrow.setPosition(0,20,0)
		arrow.color(viz.BLUE)
Exemplo n.º 6
0
 def efficiencyTest(self):
     start = HotSpots.GetCurrentStart()
     target = HotSpots.GetCurrentTarget()
     accuracy = float(self.hotspotdist[start, target]) / float(
         self.movement.GetNumForwardMoves())
     success = (accuracy >= self.trialAccuracy)
     if self.mode == 'EfficiencyTest':
         self.VisitedHotSpots.mark(HotSpots.InHotSpot())
         if success:
             self.numSuccess += 1
             viz.clearcolor(0, 1, 0)
         else:
             self.numOK += 1
             viz.clearcolor(0, 0, 1)
         if self.numOK >= 3:
             self.numSuccess = 0
             self.numOK = 0
     print "Efficiency: ", accuracy, " Succ: ", self.numSuccess, " OK: ", self.numOK, "Fail:", self.numFailures
     print 'Visited HotSpots', self.VisitedHotSpots, self.VisitedHotSpots.all(
     )
     OUTFILE = open(self.logdir + self.outfile, 'a')
     OUTFILE.write(">E;\t%d to %d;\t" % (start, target))
     OUTFILE.write("%d / %d" % (self.movement.GetNumForwardMoves(),
                                self.hotspotdist[start, target]))
     OUTFILE.write(" = %f;\t" % (accuracy))
     OUTFILE.write("Successes %d;\t" % (self.numSuccess))
     OUTFILE.write("OK %d;\t" % (self.numOK))
     OUTFILE.write("Failures %d;\t" % (self.numFailures))
     OUTFILE.write("\n")
     OUTFILE.close()
     return success
def setStage():
    """Creates grass textured groundplane"""

    ###should set this hope so it builds new tiles if you are reaching the boundary.
    fName = 'C:/VENLAB data/shared_modules/textures/strong_edge.bmp'
    #fName = 'strong_edge.bmp'

    # add groundplane (wrap mode)
    groundtexture = viz.addTexture(fName)
    groundtexture.wrap(viz.WRAP_T, viz.REPEAT)
    groundtexture.wrap(viz.WRAP_S, viz.REPEAT)
    groundtexture.anisotropy(16)

    groundplane = viz.addTexQuad()  ##ground for right bends (tight)
    tilesize = 500
    #planesize = tilesize/5
    planesize = 40
    groundplane.setScale(tilesize, tilesize, tilesize)

    groundplane.setEuler((0, 90, 0), viz.REL_LOCAL)
    #groundplane.setPosition((0,0,1000),viz.REL_LOCAL) #move forward 1km so don't need to render as much.
    matrix = vizmat.Transform()
    matrix.setScale(planesize, planesize, planesize)
    groundplane.texmat(matrix)
    groundplane.texture(groundtexture)
    groundplane.visible(1)

    viz.clearcolor(viz.SKYBLUE)

    return groundplane
Exemplo n.º 8
0
def setStage(TILING=True):
    """Creates grass textured groundplane"""

    global gtexture

    # background color
    viz.clearcolor(viz.SKYBLUE)

    #CODE UP TILE-WORK WITH GROUNDPLANE.
    ##should set this up so it builds new tiles if you are reaching the boundary.
    #fName = 'textures\\strong_edge_redoutline.bmp'
    fName = 'textures\\strong_edge.bmp'
    gtexture = viz.addTexture(fName)
    gtexture.wrap(viz.WRAP_T, viz.REPEAT)
    gtexture.wrap(viz.WRAP_S, viz.REPEAT)
    # #add groundplane (wrap mode)
    ###UNCOMMENT FOR TILING
    # Tiling saves memory by using two groundplane tiles instead of a massive groundplane. Since the drivers are essentially driving linearly forward, they cover a lot of distance across the z axis.
    gplane1 = viz.addTexQuad()  ##
    tilesize = 3000
    texture_z_size = tilesize * 2
    #planesize = tilesize/5
    planesize = tilesize / 5.0
    gplane1.setScale(tilesize, tilesize * 2, tilesize)
    gplane1.setEuler((0, 90, 0), viz.REL_LOCAL)
    #groundplane.setPosition((0,0,1000),viz.REL_LOCAL) #move forward 1km so don't need to render as much (was originally commented out)
    matrix = vizmat.Transform()
    matrix.setScale(planesize, planesize * 2, planesize)
    gplane1.texmat(matrix)
    #gplane1.texture(gtexture)
    gplane1.texture(gtexture)
    gplane1.visible(1)
    #
    if TILING:
        # fName2 = 'textures\\strong_edge_blueoutline.bmp'
        #fName2 = 'textures\\strong_edge_blueoutline.bmp'
        fName2 = 'textures\\strong_edge.bmp'
        gtexture2 = viz.addTexture(fName2)
        gtexture2.wrap(viz.WRAP_T, viz.REPEAT)
        gtexture2.wrap(viz.WRAP_S, viz.REPEAT)
        gplane2 = gplane1.copy()  #create duplicate.
        gplane2.setScale(tilesize, tilesize * 2, tilesize)
        gplane2.setEuler((0, 90, 0), viz.REL_LOCAL)
        #groundplane.setPosition((0,0,1000),viz.REL_LOCAL) #move forward 1km so don't need to render as much.
        gplane2.texmat(matrix)
        #gplane1.texture(gtexture)
        gplane2.texture(gtexture2)
        gplane2.visible(1)
        gplane2.setPosition(0, 0, tilesize * 2)
        gplane2.zoffset(-1)
    else:
        gplane2 = []

    return (gplane1, gplane2, texture_z_size)
Exemplo n.º 9
0
 def openCurtain(self):
     self.room.visible(viz.ON)
     self.cues.showAllCues(1)
     viz.visible(viz.ON)
     viz.clearcolor(0, 0, 0)
     self.curtain = 0
     if self.mode != 'TurnAround' and self.movement != Movement:
         self.movement.AllowMotion(forward=True)
     for name in self.envs.keys():
         if name != self.layout:
             self.envs[name].visible(viz.OFF)
             for cue in self.envCues[name]:
                 cue.Object.visible(viz.OFF)
Exemplo n.º 10
0
	def fadingFadeThing():
		yield viztask.waitTime(1)
		globals_oa.fadingSphere.addAction(fadeOutSphere)
		yield viztask.waitActionEnd(globals_oa.fadingSphere, fadeOutSphere)
		globals_oa.terrainZone3.visible(viz.OFF)
		globals_oa.ocean.visible(viz.OFF)
#		globals_oa.terrainZone1.visible(viz.ON)
		globals_oa.globeScene.enable(viz.RENDERING)
		globals_oa.user.setPosition(0.0,-0.05,0.0)
		viz.fogcolor(viz.BLACK)
		viz.fog(0.2)
		viz.clearcolor(viz.BLACK)
		globals_oa.fader.fadeOutTask()
		globals_oa.fader.fadeInTask()
#		yield viztask.waitTime(2)
		yield globals_oa.fadingSphere.addAction(fadeInSphere)
Exemplo n.º 11
0
    def setupLighting(self):
        viz.MainView.getHeadLight().remove()

        # Create Sky
        viz.clearcolor(viz.SKYBLUE)
        sky = viz.add('sky_day.osgb')
        sky.setScale(2, 2, 2)
        sky.setPosition(0, 0, 0)

        lightColor = [0.8, 0.7, 0.6]

        # Create directional lights
        sun = vizfx.addDirectionalLight(euler=([-120.00000, 24.50000,
                                                0.00000]),
                                        color=lightColor)

        # Adjust ambient color
        vizfx.setAmbientColor([0.95, 0.95, 0.95])
Exemplo n.º 12
0
	def failedToDetect(self):
		
		print 'Failed to detect'
		
		viz.clearcolor(viz.RED)
		# Temporarily stop presenting numbers
		self.stopPresentingNumbers()
		vizact.ontimer2(self.updateRateSecs,0,viz.clearcolor,viz.BLACK)
		vizact.ontimer2(self.updateRateSecs,0,self.startPresentingNumbers)
		
		import winsound
		Freq = 200 # Set Frequency To 2500 Hertz
		Dur = 150 # Set Duration To 1000 ms == 1 second

		winsound.Beep(Freq,Dur)
		
		if( networkingOn  ):
			netClient.send(message='numberTaskError')
Exemplo n.º 13
0
	def toggleEyeCalib(self):
		"""
		Toggles the calibration for eye tracking.
		Note, that for this to work, toggling 
		# self.config.camera must turn off your world model
		# This is setup in testRoom.init().
		
		# Example of what's needed in testRoom.init
		self.room = viz.addGroup()
		self.model = viz.add('pit.osgb',parent = self.room)
		"""
		
		if not self.config.mocap:
			pass
		#elif (self.config.mocap.isOn() == 1): 
		elif( self.config.mocap.mainViewUpdateAction == False):
			#self.config.mocap.turnOff()
			self.config.mocap.enableHMDTracking()
			#self.config.mocap.turnOn()
		else:
			self.config.mocap.disableHMDTracking()
			
		viz.mouse.setOverride(viz.TOGGLE)
		self.config.eyeTrackingCal.toggleCalib()
		
		self.inCalibrateMode = not self.inCalibrateMode
		
		if self.inCalibrateMode:
			viz.clearcolor(.5, .5, .5)
			viz.MainView.setPosition(0,0,0)
			viz.MainView.setAxisAngle(0, 1, 0, 0)
			viz.MainView.velocity([0,0,0]);
			
		else:
			viz.clearcolor(0, 0, 0)
			
		if self.room:
			#self.room.visible(viz.disable)
			self.room.walls.visible(viz.TOGGLE)
			self.room.objects.visible(viz.TOGGLE)
Exemplo n.º 14
0
def addGroundPlane():
    """adds a scene"""

    fName = 'C:/VENLAB data/shared_modules/textures/strong_edge.bmp'

    # add groundplane (wrap mode)
    groundtexture = viz.addTexture(fName)
    groundtexture.wrap(viz.WRAP_T, viz.REPEAT)
    groundtexture.wrap(viz.WRAP_S, viz.REPEAT)

    groundplane = viz.addTexQuad()  ##ground for right bends (tight)
    tilesize = 300
    planesize = tilesize / 5
    groundplane.setScale(tilesize, tilesize, tilesize)
    groundplane.setEuler((0, 90, 0), viz.REL_LOCAL)
    matrix = vizmat.Transform()
    matrix.setScale(planesize, planesize, planesize)
    groundplane.texmat(matrix)
    groundplane.texture(groundtexture)
    groundplane.visible(1)

    viz.clearcolor(viz.SKYBLUE)
# Used to gain access to the entire Vizard library
import viz
import vizshape
import vizact

# Enable full screen anti-aliasing FSAA to smooth edges
viz.setMultiSample(4)
# Increase the field of view(fov) to 60 degrees from default 40 degress
viz.fov(74.73,1.77)
# viz.go starts an empty world
viz.go()

viz.clearcolor(viz.SKYBLUE) #Setting the background color

viz.MainView.getHeadLight().enable()

cam = viz.MainView
cam.setPosition([0,1.06,0])

##
s = 1
focalLen = 0.00081566 * s
planeWidth = 0.00126 * s
planeHeight = 0.0022 * s
camcenter_dX = (640-606.3966)*1.75*(10^-6) * s
camcenter_dY = (360-310.6875)*1.75*(10^-6) * s

ImagePlane = vizshape.addPlane(
	size = [planeWidth,planeHeight],
	axis = -vizshape.AXIS_Z,
	cullFace = False
    TotalN = NCndts * TrialsPerCondition

    TRIALSEQ = range(0, NCndts) * TrialsPerCondition
    np.random.shuffle(TRIALSEQ)

    direc = [1, -1] * (TotalN / 2)  #makes half left and half right.
    np.random.shuffle(direc)

    TRIALSEQ_signed = np.array(direc) * np.array(TRIALSEQ)

    return (TRIALSEQ_signed, ConditionList_heading, ConditionList_dots)


# background color
viz.clearcolor(
    viz.SKYBLUE
)  # comment out for black sky plane but might be best to leave sky blue in order


# ground texture setting
def setStage(TILING=True):

    global ndots, tilesize

    fName = 'textures\\black.jpg'
    gtexture = viz.addTexture(fName)
    gtexture.wrap(viz.WRAP_T, viz.REPEAT)
    gtexture.wrap(viz.WRAP_S, viz.REPEAT)

    # #add groundplane (wrap mode)
    ###UNCOMMENT FOR TILING
Exemplo n.º 17
0
    def mykey(self, key):
        if self.curtain:
            if key != ' ': return
            print "Mode:", self.mode, " jump: ", self.jump
            if self.jump:
                self.jump = 0
                if self.mode == 'TurnAround':
                    HotSpots.AnnounceHotSpots(1)
                    HotSpots.SayCurrentHotSpot(
                        'SharedMedia/Sounds/TurnAround.wav')
            else:
                if not self.starttime: self.starttime = time.time()
                if self.mode in ('Explore', 'BoundedWander'):
                    HotSpots.ResetHotSpots()
                    self.MoveToNext(
                        random.randint(1, len(HotSpots.GetHotSpots())),
                        self.mode)
                    self.jump = 0
                    self.VisitedHotSpots.reset(HotSpots.InHotSpot())
                elif self.mode in ('HotspotQuiz', 'EfficiencyTest'):
                    self.endTrial()
            if self.mode in ('Directions', ):
                if self.onFinish: return self.onFinish(self)
            else:
                HotSpots.AnnounceHotSpots(1)
                self.openCurtain()
        elif key in ('0', 'm', 'M',
                     ' ') and self.mode == 'TurnAround' and self.onFinish:
            return self.onFinish(self)
        elif not self.movement.OkMove():
            return

        print key, self.movement.GetNumForwardMoves(
        ), self.mode, 'HotSpot', HotSpots.InHotSpot()
        if key in ('w', 'W'):
            self.outputMove('WchHS')
            HotSpots.SayCurrentHotSpot()
        elif key in ('t', 'T', 'd', 'D') and self.mode in ('HotspotQuiz',
                                                           'EfficiencyTest'):
            self.outputMove('CurrTgt')
            HotSpots.SayCurrentTarget()
        elif key in ('d', 'D') and self.mode == 'Directions':
            self.outputMove('ReDirct')
            DirectionDialog(filename=self.directions, dir=self.directionDir)
        elif key == ' ':
            if self.mode in ('HotspotQuiz', 'EfficiencyTest', 'Directions'):
                done = 0
                if HotSpots.GetCurrentTarget() == HotSpots.InHotSpot():
                    self.outputMove('CorrTgt')
                    self.efficiencyTest()
                    if self.mode == 'EfficiencyTest':
                        #SoundQueue.PlaySound('SharedMedia/Sounds/correct.wav')
                        if (self.numSuccess >= self.numGoodTrials
                                and (self.numGoodTrials == 1
                                     or self.VisitedHotSpots.all())):
                            HotSpots.StopTrials()
                            self.closeCurtain()
                            done = 1
                else:
                    self.outputMove('IncrTgt')
                    if self.mode == 'EfficiencyTest':
                        SoundQueue.PlaySound(
                            'SharedMedia/Sounds/Incorrect.wav')
                        self.numSuccess = 0
                        self.numOK = 0
                        self.numFailures += 1
                        viz.clearcolor(1, 0, 0)
                self.movement.ResetNumMoves()
                self.endTrial(done)

        if self.movement != Movement:  # Are we using discrete motion keys?
            return

        if key in ('8', '*'):
            if self.mode == 'TurnAround':
                SoundQueue.PlaySound('SharedMedia/Sounds/TurnAround.wav')
            elif self.movement.GoForward(self.fwdMovementCallback):
                self.outputMove('Forward')
        elif key in ('4', 'u', 'U'):
            if self.movement.RotateLeft():
                self.outputMove('Left')
        elif key in ('6', 'o', 'O'):
            if self.movement.RotateRight():
                self.outputMove('Right')
Exemplo n.º 18
0
def goCG():
	bgcolor = [0.15*1.2, 0.67*1.2, 0.95*1.2]
	viz.clearcolor(bgcolor)
	global skipKey, egg
	flagPile = globals_oa.terrainZone1.getChild('flagPile.OSGB', viz.CHILD_REPLACE_TRANSFORM)
	fishZone1 = schooling.initialize(1)
#	yield viztask.waitEvent(globals_oa.VIDEO_END_EVENT)
	
#	loadStuffAtStartAndHideThemALL()
	
	vizact.onsensorup(globals_oa.rhViveTracker, steamvr.BUTTON_TRIGGER, printRightHandPosition)
	vizact.onsensorup(globals_oa.lhViveTracker, steamvr.BUTTON_TRIGGER, printLeftHandPosition)
	
	globals_oa.terrainZone1.visible(viz.ON)
	globals_oa.ocean.visible(viz.ON)
#	schooling.hidePercentage(0)
#	schooling.chromis_chromis.hidePercentage(0)
#	schooling.diplodus_annularis.hidePercentage(0)
#	schooling.labrus_viridis.hidePercentage(0)
#	schooling.sarpa_salpa.hidePercentage(0)
	
#	schooling.show(fishZone1)
	
#	fog = vizfx.addFogEffect(colorRamp=viz.addTexture(globals_oa.MODEL_DIRECTORY + 'FogRamp.tif'), height=1, density=(.09))
#	fog = vizfx.addFogEffect(colorRamp=viz.addTexture(globals_oa.MODEL_DIRECTORY + 'FogRamp.tif'), height=1, density=(10))
#	vizfx.getComposer().addEffect(fog)
#	viz.MainScene.enable(viz.FOG, op=viz.OP_ROOT)
	
	viz.fogcolor(viz.AZURE)
	viz.fog(0.025)
	
#	worldvizcode.initVFXforDC(globals_oa.terrainZone1) # should moved into loadAndHide?
	worldvizcode.startEffects(globals_oa.terrainZone1) #not needed?
	
	#positioning the user on the terrain
#	offsetting the user on the terrain
	y_offset = -1.5
	userPos = globals_oa.user.getPosition(viz.ABS_GLOBAL)
	globals_oa.user.setPosition([userPos[0], y_offset, userPos[2]])
	
#####** Healthy CG zone fades in**
#	terrain1Child = globals_oa.terrainZone1.getChild('Terrain_Zone009')
#	posToMoveUserTo = terrain1Child.getBoundingBox().center
#	print "posToMoveUserTo = " + str(posToMoveUserTo)
	
	if globals_oa.fader is None: globals_oa.fader = View_Fader.addFader(fadeTime=5)
	globals_oa.fader.fadeIn()

#####	#This is a healthy reef, where carbon dioxide has not yet altered seawater chemistry. 
	#
#####	#When scientists measure the health and biodiversity of a reef, they perform something called a species count. 
#####	#Today, you will be counting the number of sea snails on this part of the reef. Look at your right hand
	#
	globals_oa.TRANSITION_TO_CG.play()
	yield viztask.waitAny([viztask.waitTime(10), skipKey])
	globals_oa.CG_SCENE1_1.play()
#	getAllChildrenZone1 = viz.MainScene.getChildren(all=True)
	def fadeAllZone1():
		globals_oa.terrainZone1.alpha(0)
		globals_oa.terrainZone1.visible(viz.ON)
		worldvizcode.stopEffects()
		viz.fog(0)
		fadeInZone1 = vizact.fadeTo(1, time=2)
		yield globals_oa.terrainZone1.addAction(fadeInZone1)
#		for child in getAllChildrenZone1: 
#			child.addAction(fadeInZone1)
			
	yield viztask.waitAny([viztask.waitTime(17), skipKey])	
#	globals_oa.CG_SCENE1_1.stop()
	
	#*participant sees 3D model of sea snail rotating like a hologram*
#	if globals_oa.rhViveTracker is not None:
#	vizact.ontimer2(0.004, 25, scavengerhunt.vibrateHandController, 2)
#	leftHandVibrateTimer.setEnabled(True)
#	rightHandVibrateTimer.setEnabled(True)
	
	
	rotatingSnail.visible(viz.ON)
	snailLink = None
	vizact.ontimer2(.004, 50, vibrateRightHand)
	if globals_oa.rhViveTracker is not None:
		snailLink = viz.link(globals_oa.rhViveTracker, rotatingSnail)
		snailLink.setOffset([0.0, y_offset, 0.0])
		snailLink.preTrans([0.01,-0.03,-0.13])
		snailLink.preEuler([0,0,180])

	
	yield viztask.waitTime(11)
	

#####	#*hologram disappears, species count begins*
	if snailLink is not None: snailLink.remove()
	rotatingSnail.visible(viz.OFF)
	rotatingSnail.remove()

##### flashing the flag pile ######
	egg.visible(viz.ON)
	flashOn = vizact.fadeTo(1, time=1, interpolate=vizact.easeInOut)
	flashOff = vizact.fadeTo(0, time=1, interpolate=vizact.easeInOut)
	flashSequence = vizact.sequence(flashOn, flashOff, 5)
	egg.add(flashSequence)
	
	
	yield viztask.waitTime(11)

	globals_oa.CG_SCENE1_2.play()
	print "playing CG_SCENE1_2 now"
#	yield viztask.waitAny([viztask.waitMediaEnd(globals_oa.CG_SCENE1_2), skipKey])
	yield viztask.waitAny([viztask.waitTime(17), skipKey])
#	scavengerhunt.initialize(globals_oa.terrainZone1, globals_oa.filePathToSpeciesForScavengerHuntInZone1)
#	scavengerhunt.hideBasketAndStuffAttachedToIt()
	print "waiting for the species hunt end event, or for a timer to run out"
#	yield viztask.waitAny([viztask.waitEvent(scavengerhunt.ZONE1_OVER_EVENT), viztask.waitTime(60), skipKey])
	yield viztask.waitAny([viztask.waitTime(35), skipKey])
	print "species hunt is over"
#	leftHandVibrateTimer.setEnabled(False)
#	rightHandVibrateTimer.setEnabled(False)
#	scavengerhunt.endScavengerHunt()
#	yield viztask.waitEvent(scavengerhunt.ZONE1_OVER_EVENT)
#	scavengerhunt.disableGrabber()

	#waiting for the audio to end
	print "waiting for the narration to end"
	yield viztask.waitAny([viztask.waitTime(5), skipKey])

	#healthy zone fading out
#	print "fading out from zone-1 begin"
#	globals_oa.fader.fadeOutTask()
	globals_oa.fader.fadeOut()
#	print "fading out from zone-1 complete"
	
	yield viztask.waitAny([viztask.waitTime(5), skipKey])
	
#####	#**Unhealthy CG zone fades in**
#	globals_oa.terrainZone1.disable(viz.RENDERING)
	globals_oa.terrainZone1.visible(viz.OFF)
	if globals_oa.lhModelFlag is not None: globals_oa.lhModelFlag.visible(viz.OFF)
	if globals_oa.rhModelFlag is not None: globals_oa.rhModelFlag.visible(viz.OFF)
	schooling.hide(fishZone1)
	
#	userPos = globals_oa.user.getPosition()
#	globals_oa.user.setPosition(userPos[0] + globals_oa.zone3_X_offset, userPos[1], userPos[2])
#	globals_oa.user.setPosition(userPos[0], userPos[1], userPos[2])
#	globals_oa.basket.setPosition(globals_oa.basketPosInCGscene3)
#	globals_oa.terrainZone3.setPosition(-60.73, 0.0, 0.0)
#	scavengerhunt.hideBasketAndStuffAttachedToIt()
	
	globals_oa.terrainZone3.visible(viz.ON)
#	worldvizcode.stopEffects()
	worldvizcode.startEffects(globals_oa.terrainZone3)

#	schooling.show(fishZone2)	

#	print "fading into zone-3 begin"
#	globals_oa.fader.fadeInTask()
	globals_oa.fader.fadeIn()
#	print "fading into zone-3 complete"

#####	Observe the changes that have occurred as acidity has increased. Reach out and touch one of the streams of bubbles rising from the sea floor
	globals_oa.CG_SCENE2_1.play()
	print "playing CG_SCENE2_1 now"
#	yield viztask.waitAny([viztask.waitMediaEnd(globals_oa.CG_SCENE2_1), skipKey])

#adding proximity handling for touching the bubbles
	global bubbleVibratorManager
	bubbleVibratorManager = vizproximity.Manager()
	
#	bubbleVibratorManager.setDebug(viz.ON)
	vizact.onkeydown('b', bubbleVibratorManager.setDebug, viz.TOGGLE)

	#adding bounding box sensors around the bubbles
	updateVibrationSensors()
#	vizact.onkeydown('u',updateVibrationSensors)

	#adding boxes around the hands as targets
	global rhandtar, lhandtar
#	rhsphere = vizshape.addSphere(radius = 0.07) 
	rhsphere = vizshape.addBox(size=(0.1,0.1,0.3))
	rhsphere.setParent(globals_oa.rightHand)
	rhsphere.setPosition([0,0,-0.15])
	rhsphere.disable(viz.RENDERING)
#	lhsphere = vizshape.addSphere(radius = 0.07) 
	lhsphere = vizshape.addBox(size=(0.1,0.1,0.3))
	lhsphere.setParent(globals_oa.leftHand)
	lhsphere.setPosition([0,0,-0.15])
	lhsphere.disable(viz.RENDERING)
#	if globals_oa.rhModel is not None:
	rhandtar = vizproximity.Target(rhsphere)#globals_oa.rhModel)
#	if globals_oa.lhModel is not None:
	lhandtar = vizproximity.Target(lhsphere)#globals_oa.lhModel)
	
	bubbleVibratorManager.addTarget(rhandtar)
	bubbleVibratorManager.addTarget(lhandtar)

	bubbleVibratorManager.onEnter(None, vibrateHandInBubbles)
	bubbleVibratorManager.onExit(None, stopVibrationOfHandInBubbles)
	
	print "*********************************** SENSORS ADDED FOR VIBRATING BUBBLES ***********************************"

	yield viztask.waitAny([viztask.waitTime(globals_oa.CG_SCENE2_1.getDuration()), skipKey])
	
#####	**wait until participant touches a stream of bubbles**
#####	** repeat last sentence until they do so**


#####The vents here in Ischia are releasing carbon dioxide, which is making the water more acidic. 
#####You study this part of the reef to predict how human carbon dioxide emissions will affect 
#####our world’s oceans and the species that live within them. 
#####Look at your right hand.
	globals_oa.CG_SCENE2_2.play()
	print "playing CG_SCENE2_2 now"
	
	yield viztask.waitAny([viztask.waitTime(16), skipKey])
	
	if globals_oa.rhViveTracker is not None:
		corrodedRotatingSnail.visible(viz.ON)
		vizact.ontimer2(.004, 50, vibrateRightHand)
		print '***********linking cooroded snail'
		snailLink = viz.link(globals_oa.rhViveTracker, corrodedRotatingSnail)
		snailLink.setOffset([0.0, y_offset, 0.0])
		snailLink.preTrans([0.01, -0.03, -0.13])
		snailLink.preEuler([0, 0, 180])
		snailLink.setMask(viz.LINK_POS)
		spinForever = vizact.spin(0,1,0, 90, dur = viz.FOREVER)
		corrodedRotatingSnail.runAction(spinForever)
	yield viztask.waitTime(10)
	corrodedRotatingSnail.visible(viz.OFF)
	
	yield viztask.waitAny([viztask.waitTime(40), skipKey])
	if bubbleVibratorManager is not None:
		bubbleVibratorManager.clearSensors()
		bubbleVibratorManager.clearTargets()

	if rightHandVibrateTimer is not None: rightHandVibrateTimer.setEnabled(False)
	if leftHandVibrateTimer is not None: leftHandVibrateTimer.setEnabled(False)
	globals_oa.finalTransitionSound.play()
#	yield viztask.waitTime(1)
	bubbleStreams = globals_oa.terrainZone3.getChild('zone2_smaller.OSGB')
	bubbleStreams.setAnimationSpeed(0.1)
	globals_oa.UNDERWATER_AMBIENT.stop()
	yield viztask.waitTime(3)
	globals_oa.FINAL_SCENE.play()
	yield viztask.waitAny([viztask.waitTime(10), skipKey])
	fadeInSphere = vizact.fadeTo(0, time=2)
	fadeOutSphere = vizact.fadeTo(1, time=2)
	def fadingFadeThing():
		yield viztask.waitTime(1)
		globals_oa.fadingSphere.addAction(fadeOutSphere)
		yield viztask.waitActionEnd(globals_oa.fadingSphere, fadeOutSphere)
		globals_oa.terrainZone3.visible(viz.OFF)
		globals_oa.ocean.visible(viz.OFF)
#		globals_oa.terrainZone1.visible(viz.ON)
		globals_oa.globeScene.enable(viz.RENDERING)
		globals_oa.user.setPosition(0.0,-0.05,0.0)
		viz.fogcolor(viz.BLACK)
		viz.fog(0.2)
		viz.clearcolor(viz.BLACK)
		globals_oa.fader.fadeOutTask()
		globals_oa.fader.fadeInTask()
#		yield viztask.waitTime(2)
		yield globals_oa.fadingSphere.addAction(fadeInSphere)
	viztask.schedule(fadingFadeThing)
	globals_oa.fader.fadeOutTask()
Exemplo n.º 19
0
import viz
import viztask
import steamvr
import datetime
import scipy.io as scio
import math
import utils

nSecWait = 6  # number of seconds of data to capture to determine noise in the tracker output
multiplier = 100  # set thresholds at mean+lambda*SD times the noise recorded, where lmbda is the multiplier set here
qHaveSimultaneous = True  # use setup with Vive and simultaneous PPT and Intersense (True), or not (False)?

setup = utils.init(qHaveSimultaneous)

viz.clearcolor(viz.WHITE)


def TrackTask():
    prevPos = None
    tracking = True
    allData = []
    tRegained = 0.
    waitingForTrack = True
    t = 0.
    while True:
        # wait for trigger press
        while not (steamvr.getControllerList()[0].isButtonDown(2)
                   or viz.key.isDown('c', immediate=True)):
            # limit to update rate
            d = yield viztask.waitDraw()
Exemplo n.º 20
0
def createEnvironment():	
	global point 
	global arrow 
	global goal	 
	global thrust
	global shadow

	#create 3D environment
	if parameters.dreiDEnvironment:

		piazza = viz.addChild('piazza.osgb')
	
		#look from above
		viz.MainView.setPosition([0,1.8,-5])
		viz.MainView.setEuler([0,20,0])
		viz.collision(viz.ON)
		# gorund for collision
		ground = viz.add('tut_ground.wrl')  # Add ground
		ground.collidePlane()   # Make collideable plane 
		ground.disable(viz.RENDERING)
		ground.disable(viz.DEPTH_WRITE)
		
		# point
		#point = viz.add('ball.wrl')
		point = vizshape.addSphere(radius = parameters.pointRadius, slices = 20, stacks = 20, axis = vizshape.AXIS_Y)
		pointPhys = point.collideSphere()   # Define ball's physical properties 
	
		point.setEuler(0,90,0)
		point.setPosition(0,parameters.point_height,0)
		point.color(viz.RED)
		point.setScale(0.5,0.5,0.5)
		point.enable( viz.COLLIDE_NOTIFY )
		
		#goal
		goal = vizshape.addCircle(slices=100, radius=0.3)		
		goal.setEuler(0,90,0)
		goal.color(viz.GREEN)		
		goal.setPosition(0,parameters.goal_height,0)
		goal.setScale(parameters.goal_scale3D,parameters.goal_scale3D,parameters.goal_scale3D)
		
		#shadow
		shadow = vizshape.addCircle(slices=100, radius=0.3)		
		shadow.setEuler(0,90,0)
		shadow.color(viz.GRAY)		
		shadow.setPosition(0,parameters.shadow_height,0)
		shadow.setScale(parameters.shadow_scale3D,parameters.shadow_scale3D,parameters.shadow_scale3D)

		#arrow
		arrow = vizshape.addArrow()	
		arrow.setPosition(0,parameters.arrow_height3D,0)
		arrow.color(viz.BLUE)
		
		#thrust
		thrust = point.addThruster(force=[0,0,0]) 

	#or create 2d environment
	else:
		viz.clearcolor(viz.WHITE)

		#look from above
		viz.MainView.setPosition([0,8,0])
		viz.MainView.setEuler([0,90,0])
		
		#point = viz.add('ball.wrl')
		point = vizshape.addSphere(radius = parameters.pointRadius, slices = 20, stacks = 20, axis = vizshape.AXIS_Y)
		pointPhys = point.collideSphere()   # Define ball's physical properties 		
		point.setEuler(0,90,0)
		point.setPosition(0,parameters.point_height,0)
		point.color(viz.RED)	
		point.visible(False)
		point.enable( viz.COLLIDE_NOTIFY )

		#wind force
		thrust = point.addThruster(force=[0,0,0]) 
		
		#goal
		goal = vizshape.addCircle(slices=100, radius=0.2)
		goal.setEuler(0,90,0)
		goal.color(viz.GREEN)
		goal.visible(False)
		goal.setScale(parameters.goal_scale2D,parameters.goal_scale2D,parameters.goal_scale2D)
		
		#arrow
		arrow = vizshape.addArrow()
		viz.mouse(viz.OFF)
		arrow.setPosition(0,parameters.arrow_height2D,0)
		arrow.color(viz.BLUE)
		arrow.visible(False)
import viz
import vizmat

viz.go()
#create two textures

# background color
viz.clearcolor(viz.SKYBLUE)

fName = 'textures\\strong_edge_redoutline.bmp'
gtexture = viz.addTexture(fName)
gtexture.wrap(viz.WRAP_T, viz.REPEAT)
gtexture.wrap(viz.WRAP_S, viz.REPEAT)

gplane1 = viz.addTexQuad()  ##
tilesize = 5

planesize = tilesize / 5.0
gplane1.setScale(tilesize, tilesize * 2, tilesize)
gplane1.setEuler((0, 90, 0), viz.REL_LOCAL)

texture_z_size = tilesize * 2

matrix = vizmat.Transform()
matrix.setScale(planesize, planesize * 2, planesize)
gplane1.texmat(matrix)
gplane1.texture(gtexture)
gplane1.visible(1)

#create second texture
fName2 = 'textures\\strong_edge_blueoutline.bmp'
Exemplo n.º 22
0
viz.window.setFullscreenMonitor([2, 1])
clock = 0
GRAVITY = 9.81
num = 0
NUM_AVATARS = 2
headLocation = viz.addGroup()

##########################
#### Scene Creation   ####
##########################

light = viz.MainView.getHeadLight().ambient(1, 1, 1)
light2 = viz.addLight()

roomGroup = None
viz.clearcolor(0.1, 0.1, 0.3)
link = None

# list of limbs to check for collision body
COLLISION_LIMBS = [
    "Bip01 Head",
    "Bip01 L UpperArm",
    "Bip01 L Forearm",
    "Bip01 L Thigh",
    "Bip01 L Calf",
    "Bip01 R UpperArm",
    "Bip01 R Forearm",
    "Bip01 R Thigh",
    "Bip01 R Calf",
    "Bip01 Spine",
    "Bip01 Spine1",
Exemplo n.º 23
0
    def runtrials(self):
        """Loops through the trial sequence"""

        viz.MainScene.visible(viz.ON, viz.WORLD)
        viz.mouse.setVisible(viz.OFF)  #switch mouse off
        viz.clearcolor(
            viz.SKYBLUE)  #HACK, since eyetracker background is white.
        if self.EYETRACKING:
            #pass it the filename, and also the timestamp.
            et_file = str(self.EXP_ID) + '_' + str(
                self.PP_id)  #one file for the whole task.
            self.comms.start_trial(fname=et_file, timestamp=viz.tick())

        if self.EYETRACKING:
            #viz.MainScene.visible(viz.OFF,viz.WORLD)

            #remove straight
            self.Straight.ToggleVisibility(0)
            filename = str(self.EXP_ID) + "_Calibration_" + str(
                self.PP_id
            )  #+ str(demographics[0]) + "_" + str(demographics[2]) #add experimental block to filename
            print(filename)

            # Start logging the pupil data
            pupilfile = gzip.open(
                os.path.join("Data", filename + ".pupil.jsons.gz"), 'a')

            closer = pupil_logger.start_logging(pupilfile,
                                                timestamper=viz.tick)

            def stop_pupil_logging():
                closer()
                pupilfile.close()

            EXIT_CALLBACKS.insert(0, stop_pupil_logging)

            yield run_calibration(self.comms, filename)
            yield run_accuracy(self.comms, filename)

            #put straight visible
            self.Straight.ToggleVisibility(1)
            #add message after calibration to give the experimenter and participant time to prepare for the simulation.

            self.markers = Markers()

            #set up distractor task
        if self.DISTRACTOR_TYPE is not None:
            distractorfilename = str(self.EXP_ID) + '_' + str(
                self.PP_id) + '_distractor_'
            Distractor = Count_Adjustable.Distractor(
                distractorfilename,
                self.targetnumber,
                ppid=1,
                startscreentime=self.StartScreenTime,
                triallength=np.inf,
                ntrials=len(self.TRIALSEQ_df.index))
        else:
            Distractor = None

        #set up scene before eyetracking
        self.driver = vizdriver.Driver(self.caveview, Distractor)

        viz.message(
            '\t\tYou will now begin the experiment \n\n The automated vehicle will attempt to navigate a series of bends. \nYour task as the supervisory driver is to make sure the vehicle stays within the road edges. \nDuring automation please keep your hands loosely on the wheel. \nYou may take control by pressing the gear pads. \nOnce pressed, you will immediately be in control of the vehicle \n\n Please fixate the centre of the calibration point in between trials'
        )
        self.ToggleTextVisibility(viz.ON)

        for i, trial in self.TRIALSEQ_df.iterrows():

            #if half-way through do accuracy test.
            #Trial loop has finished.
            if i == int(np.round(self.total_trials / 2, 0)):
                if self.EYETRACKING:
                    self.markers.markers_visibility(
                        0)  #remove markers for calibration
                    self.Straight.ToggleVisibility(0)

                    accuracy_filename = filename + '_middle'
                    yield run_accuracy(self.comms, accuracy_filename)
                    yield viztask.waitTime(
                        1)  #a second pause before going into

                    self.markers.markers_visibility(
                        1)  #remove markersthe next trial
                    self.Straight.ToggleVisibility(1)

            #import vizjoy

            print("Trialn: ", str(i))

            print("current trial:", trial)

            #trial is now a row from a dataframe
            print("current trial radius:", trial["radius"])
            trial_radii = trial['radius']
            trial_yawrate_offset = trial['sab']
            trial_dir = trial['bend']

            print(str([trial_radii, trial_yawrate_offset]))

            txtDir = ""

            #print ("Length of bend array:", len(self.rightbends))

            self.driver.setAutomation(True)
            self.AUTOMATION = True
            self.txtMode.message('A')
            if self.AUTOWHEEL:
                self.Wheel.control_on()

            if self.DISTRACTOR_TYPE is not None:
                if i == 0:  #the first trial.

                    #annotate eyetracking
                    if self.EYETRACKING:
                        self.comms.annotate("DistractorScreen")

                    #switch texts off for the first trial.

                    self.ToggleTextVisibility(viz.OFF)

                    Distractor.StartTrial(self.targetoccurence_prob,
                                          self.targetnumber,
                                          trialn=i,
                                          displayscreen=True)  #starts trial
                    yield viztask.waitTrue(Distractor.getPlaySoundFlag)

                    self.ToggleTextVisibility(viz.ON)

                else:
                    Distractor.StartTrial(self.targetoccurence_prob,
                                          self.targetnumber,
                                          trialn=i,
                                          displayscreen=False)  #starts trial

            radius_index = self.FACTOR_radiiPool.index(trial_radii)

            #choose correct road object.

            if trial_dir > 0:  #right bend
                trialbend = self.rightbends[radius_index]
                txtDir = "R"
            else:
                trialbend = self.leftbends[radius_index]
                txtDir = "L"
                #trialbend = self.rightbends[radius_index]
                #txtDir = "R"

            trialbend.ToggleVisibility(viz.ON)

            if trial_radii > 0:  #if trial_radii is above zero it is a bend, not a straight
                msg = "Radius: " + str(trial_radii) + txtDir + '_' + str(
                    trial_yawrate_offset)
            else:
                msg = "Radius: Straight" + txtDir + '_' + str(
                    trial_yawrate_offset)


#			txtCondt.message(msg)

#pick radius
            self.Trial_radius = trial_radii

            #pick file. Put this in dedicated function. TODO: Should open all of these at the start of the file to save on processing.

            self.Trial_autofile_i = int(trial['autofile_i'])

            self.Trial_YR_readout = self.YR_readouts_80[self.Trial_autofile_i]
            self.Trial_SWA_readout = self.SWA_readouts_80[
                self.Trial_autofile_i]
            self.Trial_playbackfilename = self.PlaybackPool80[
                self.Trial_autofile_i]
            """
			if self.Trial_radius == 40:
				i = random.choice(range(len(self.YR_readouts_40)))
				self.Trial_YR_readout = self.YR_readouts_40[i]
				self.Trial_SWA_readout = self.SWA_readouts_40[i]
				self.Trial_playbackfilename = self.PlaybackPool40[i]
				

			elif self.Trial_radius == 80:
				i = random.choice(range(len(self.YR_readouts_80)))
				self.Trial_YR_readout = self.YR_readouts_80[i]
				self.Trial_SWA_readout = self.SWA_readouts_80[i]
				self.Trial_playbackfilename = self.PlaybackPool80[i]

			else:
				raise Exception("Something bad happened")

			"""

            #update class#
            self.Trial_simulatedttlc = trial['simulated_ttlc']
            self.Trial_design = trial['design']
            self.Trial_dir = trial_dir
            self.Trial_N = i
            self.Trial_YawRate_Offset = trial_yawrate_offset
            self.Trial_BendObject = trialbend
            self.Trial_trialtype_signed = trial_dir
            self.Trial_playbacklength = len(self.Trial_YR_readout)
            self.Trial_midline = np.vstack(
                (self.Straight.midline, self.Trial_BendObject.midline))
            self.Trial_OnsetTime = trial['onsettime']
            #self.Trial_OnsetTime = np.random.choice(self.OnsetTimePool, size=1)[0]
            self.Trial_SaveName = str(self.EXP_ID) + '_' + str(
                self.PP_id) + '_' + str(self.Trial_N)

            #renew data frame.
            #self.OutputWriter = pd.DataFrame(index = range(self.TrialLength*60), columns=self.datacolumns) #make new empty EndofTrial data

            #renew csv writer
            self.OutputFile = io.BytesIO()
            self.OutputWriter = csv.writer(self.OutputFile)
            self.OutputWriter.writerow(self.datacolumns)  #write headers.

            #annotate eyetracking
            if self.EYETRACKING:
                self.comms.annotate('Start_' + self.Trial_SaveName)

            yield viztask.waitTime(.5)  #pause at beginning of trial

            #annotate eyetracking
            if self.EYETRACKING:
                #remove calib_pt and wait a further .5 s
                #TODO: add 1 s calibration dot.
                self.calib_pt.visible(1)
                yield viztask.waitTime(1.5)  #pause at beginning of trial
                self.calib_pt.visible(0)
                yield viztask.waitTime(.5)  #pause at beginning of trial

            if self.DEBUG:
                conditionmessage = 'SAB: ' + str(self.Trial_YawRate_Offset) + \
                '\nRadius: ' +str(self.Trial_radius) + \
                '\nOnsetTime: ' + str(self.Trial_OnsetTime) + \
                '\nAutoFile: ' + str(self.Trial_autofile_i) + \
                '\nsim TTLC: ' + str(self.Trial_simulatedttlc) + \
                '\nDesign: ' + str(self.Trial_design) + \
                '\nTask: ' + str(self.DISTRACTOR_TYPE)
                self.txtTrial.message(conditionmessage)

                if self.DEBUG_PLOT:
                    #realtime plot.
                    self.line_midline.set_data(self.Trial_midline[:, 0],
                                               self.Trial_midline[:, 1])
                    self.dot_origin.set_data(
                        self.Trial_BendObject.CurveOrigin[0],
                        self.Trial_BendObject.CurveOrigin[1])
                    self.plot_ax.axis([
                        min(self.Trial_midline[:, 0]) - 10,
                        max(self.Trial_midline[:, 0]) + 10,
                        min(self.Trial_midline[:, 1]) - 10,
                        max(self.Trial_midline[:, 1]) + 10
                    ])  #set axis limits

                    self.plot_positionarray_x, self.plot_positionarray_z, self.plot_closestpt_x,  self.plot_closestpt_z = [], [], [], [] #arrays to store plot data in

            self.UPDATELOOP = True  #

            def PlaybackReached():
                """checks for playback limit or whether automation has been disengaged"""

                end = False

                #check whether automation has been switched off.
                if self.Current_playbackindex >= self.Trial_playbacklength:
                    end = True

                return (end)

            def CheckDisengage():
                """checks automation status of driver class """

                end = False
                auto = self.driver.getAutomation()
                if auto == False:

                    self.AUTOMATION = auto
                    self.txtMode.message('M')
                    #switch wheel control off, because user has disengaged
                    #begin = timer()
                    if self.AUTOWHEEL:
                        self.Wheel.control_off()

                    if self.EYETRACKING:
                        self.comms.annotate('Disengage_' + self.Trial_SaveName)
                        #pass
                    #print ("WheelControlOff", timer() - begin)
                    end = True

                return (end)

            #create viztask functions.
            waitPlayback = viztask.waitTrue(PlaybackReached)
            waitDisengage = viztask.waitTrue(CheckDisengage)

            d = yield viztask.waitAny([waitPlayback, waitDisengage])

            if d.condition is waitPlayback:
                print('Playback Limit Reached')
            elif d.condition is waitDisengage:
                print('Automation Disengaged')

                self.SingleBeep()

                def RoadRunout():
                    """temporary HACK function to check whether the participant has ran out of road"""

                    end = False
                    if self.Trial_Timer > self.TrialLength:
                        end = True

                    return (end)

                #waitRoad = viztask.waitTrue (RoadRunout)
                #waitManual = viztask.waitTime(5)

                #d = yield viztask.waitAny( [ waitRoad, waitManual ] )

                yield viztask.waitTrue(RoadRunout)
                print("Run out of Road")
                #if d.condition is waitRoad:
                #	print ('Run out of Road')
                #elif d.condition is waitManual:
                #	print ('Manual Time Elapsed')

            ##### END STEERING TASK ######

            self.UPDATELOOP = False

            self.Trial_BendObject.ToggleVisibility(viz.OFF)

            ##reset trial. Also need to annotate each eyetracking trial.
            viz.director(self.SaveData, self.OutputFile, self.Trial_SaveName)

            self.ResetTrialAndDriver(
            )  #reset parameters for beginning of trial

            ##### INITIALISE END OF TRIAL SCREEN FOR DISTRACTOR TASK #######
            if self.DISTRACTOR_TYPE is not None:

                #annotate eyetracking
                if self.EYETRACKING:
                    self.comms.annotate('Distractor_' + self.Trial_SaveName)

                if self.AUTOWHEEL:
                    self.Wheel.control_off()

                #switch text off
                self.ToggleTextVisibility(viz.OFF)

                Distractor.EndofTrial()  #throw up the screen to record counts.

                # Pause before the query screen to avoid
                # spurious presses carrying over from the
                # task.
                # Hack the screen to be blank
                Distractor.EoTScreen.visible(viz.ON)
                Distractor.Question.visible(viz.OFF)
                Distractor.lblscore.visible(viz.OFF)
                yield viztask.waitTime(1.0)
                Distractor.EoTScreen_Visibility(viz.ON)

                ###interface with End of Trial Screen
                pressed = 0
                while pressed < self.targetnumber:

                    #keep looking for gearpad presses until pressed reaches trial_targetnumber
                    print("waiting for gear press")
                    yield viztask.waitTrue(self.driver.getGearPressed)
                    pressed += 1
                    print('pressed ' + str(pressed))

                    Distractor.gearpaddown()

                    self.driver.setGearPressed(False)

                    yield viztask.waitTime(.5)
                    #Distractor.EoTScreen_Visibility(viz.OFF)
                Distractor.RecordCounts()

                self.ToggleTextVisibility(viz.ON)

            #annotate eyetracking
            if self.EYETRACKING:
                self.comms.annotate('End_' + self.Trial_SaveName)

        #Trial loop has finished.
        if self.EYETRACKING:
            self.markers.remove_markers()  #remove markers
            self.Straight.ToggleVisibility(0)
            accuracy_filename = filename + '_end'
            yield run_accuracy(self.comms, accuracy_filename)
        self.CloseConnections()
Exemplo n.º 24
0
import viz
import vizact

viz.setMultiSample(4)
viz.fov(60)
viz.go()

viz.clearcolor( viz.SLATE )

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

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

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

		if d.condition is waitPlayback:
			print ('end of trial reached')
			
		elif d.condition is waitDisengage:
			print ('Automation Disengaged')
			if not DEBUG: txtmode.message('M')
			
			AUTOFLAG = False				
			wheel.FF_on(.2)				
			SingleBeep()
			yield viztask.waitTime(trialtime - (viz.tick()-trialstart))
			
		#END OF STEERING TASK
		
		#reset trial
		track.ToggleVisibility(0)
		ground.visible(viz.OFF)
		driver.reset()
		wait_texture.visible(1)
		viz.clearcolor(wait_col)
		UPDATE = False
		if not DEBUG: txtmode.message('A')
		
		yield viztask.waitTime(.5)
		wait_texture.visible(0)
		UPDATE = True
		
		savename = save_prefix +'_'+str(trial_i)
		SaveData(OutputFile, savename)
	
	
	CloseConnections(wheel)
Exemplo n.º 26
0
import timeit
import time
import vizconnect
import steamvr
from vizconnect.util import view_collision


viz.setMultiSample(4)
viz.fov(60)
vizconnect.go('vizconnect_config_htcvive.py')  #run htc vive config script
viz.go()
viz.phys.enable()


#set lab environment and light
viz.clearcolor(0.7,0.7,0.8)
viz.MainView.setPosition([9,3,15])
viz.MainView.setEuler(180, 0, 0)
lab = viz.addChild('lab.osgb')
lab.setPosition([0,0,0])
vizfx.addDirectionalLight(euler=(0,45,0))

env = viz.add(viz.ENVIRONMENT_MAP,'sky.jpg')
dome = viz.add('skydome.dlc')
dome.texture(env)

#set up collider and avatar
ground = lab.getChild('ground')  # get ground 
ground.collidePlane(bounce = 0, friction = 0.01)   # Make collideable plane 

#get table for experiment
Exemplo n.º 27
0
{} pigeons flew the coop and are hiding out in the piazza.
You have {} seconds to catch each one before it flys away.
Listen carefully and you might be able to hear where they are hiding.
Use the mouse and WASD keys to move around.
Press spacebar to begin the hunt!""".format(TRIAL_COUNT,TRIAL_DURATION)

RESULTS = """You found {} of {} pigeons.
Press spacebar to start over or escape to exit."""

TRIAL_SUCCESS = 'You caught the pigeon!'
TRIAL_FAIL = 'The pigeon flew away!'

viz.setMultiSample(4)
viz.fov(60)
viz.go(viz.FULLSCREEN)
viz.clearcolor(viz.PURPLE)


# Setup directional light
viz.MainView.getHeadLight().disable()
sky_light = viz.addDirectionalLight(euler=(0,20,0))
sky_light.color(viz.WHITE)
sky_light.ambient([0.8]*3)
viz.setOption('viz.lightModel.ambient',[0]*3)

# Setup keyboard/mouse tracker
tracker = vizcam.addWalkNavigate(moveScale=2.0)
tracker.setPosition([0,1.8,0])
viz.link(tracker,viz.MainView)
viz.mouse.setVisible(False)
Exemplo n.º 28
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)
Exemplo n.º 29
0
# loads experimental conditions
inputFile = INPUT_DIR + NICKNAME + '_subject' + subject + '.csv'
with open(inputFile, 'rb') as data:
	rows = csv.reader(data)
	conditions = [row for row in rows]
condition = ''
# loads practice conditions
if conditions[1][3] == 'avatar':
	inputFile = INPUT_DIR + NICKNAME + '_practice_avatar.csv'
else:
	inputFile = INPUT_DIR + NICKNAME + '_practice_pole.csv'
with open(inputFile, 'rb') as data:
	rows = csv.reader(data)
	practice_conditions = [row for row in rows]
	
viz.clearcolor(0,0.4,1.0) # blue world
models = {}
models['homePole'] = viz.add(MODEL_DIR + 'pole_blue.osgb')
models['orientPole'] = viz.add(MODEL_DIR + 'pole_red.osgb')
models['targetPole'] = viz.add(MODEL_DIR + 'pole_green.osgb') # Consist of three green poles with their original size [0.4, 3, 0.4] 
models['leaderPole'] = viz.add(MODEL_DIR + 'pole_yellow.osgb')
models['ground'] = viz.add(MODEL_DIR + 'Tomato3_ground.osgb')


# load avatars such as "CC2_f001_hipoly_A0.cfg", "CC2_m001_hipoly_A0.cfg"
# The stride length of avatars are around 1 meter, frequency is 0.6 second per step, 5/3 step per second.
avatars = []
for i in range(20):
	avatars.append(viz.add(AVATAR_DIR + 'CC2_f' + str(i+1).zfill(3) + '_hipoly_A0.cfg'))
for i in range(20):
	avatars.append(viz.add(AVATAR_DIR + 'CC2_m' + str(i+1).zfill(3) + '_hipoly_A0.cfg'))		
Exemplo n.º 30
0
def startBoatOutro():
 global skipKey
 #yield viztask.waitEvent(scavengerhunt.ZONE3_OVER_EVENT)
 yield viztask.waitAny([viztask.waitTime(52), skipKey])
 globals_oa.ZONE3_AUDIO_1.stop()
 yield fader.fadeOutTask()
 globals_oa.user.setPosition([0,0,0])
 killOceanScene()
 
 yield fader.fadeOutTask()
 globals_oa.AUDIO_SPHERICAL_TRANSITION.play()
 result = yield viztask.waitAny([viztask.waitMediaEnd(globals_oa.AUDIO_SPHERICAL_TRANSITION), skipKey])
 if result.condition is skipKey:
  globals_oa.AUDIO_SPHERICAL_TRANSITION.stop()
 
 # Gets rid of all the fish
 for school in schooling.all_fish_schools:
  school.hidePercentage(100)
 
 # Stops swimming
 # transport_vhil.onKeyDown('g')
# viz.MainScene.disable(viz.FOG, op=viz.OP_ROOT)

 # Change parameters to False, True for PPT 1
 vhilGo(True, False, keyboardcontrol=False)
 player = spherical_player_Vive.Player(globals_oa.SPHERICAL_VIDEO, PPT1=False, radius=2.7, playPauseKey=' ')
 
 screenPosition = player.screen.getPosition()
 viz.MainView.setPosition([screenPosition[0], 1.82, screenPosition[1]])
 
 player.toggleLooping()
 player.play()
 yield fader.fadeInTask()

 yield viztask.waitAny([viztask.waitTime(2), skipKey])
 globals_oa.AUDIO_SPHERICAL_1.play()
 result = yield viztask.waitAny([viztask.waitMediaEnd(globals_oa.AUDIO_SPHERICAL_1), skipKey])
 if result.condition is skipKey:
  globals_oa.AUDIO_SPHERICAL_1.stop()
 
 yield viztask.waitTime(1)
 globals_oa.AUDIO_SPHERICAL_2.play()
 result = yield viztask.waitAny([viztask.waitMediaEnd(globals_oa.AUDIO_SPHERICAL_2), skipKey])
 if result.condition is skipKey:
  globals_oa.AUDIO_SPHERICAL_2.stop()
 
 # Waits until the video is done playing
 result = yield viztask.waitAny([viztask.waitTime(player.getVideoDuration() - globals_oa.AUDIO_SPHERICAL_1.getDuration() - globals_oa.AUDIO_SPHERICAL_2.getDuration() - 3.5), skipKey])
 if result.condition is skipKey:
  player.pause()

 yield fader.fadeOutTask()
 
 player.screen.visible(viz.OFF)
 globals_oa.AUDIO_ZONE3_AMBIENT.pause()
 
# killOceanScene()
 boatscene.revealScene()
 boatscene.unhideBoatAndIschia()
 yield viztask.waitAny([viztask.waitTime(3), skipKey])
 globals_oa.AUDIO_BOAT_AMBIENT_OUTRO.play()
 yield fader.fadeInTask()
 yield viztask.waitAny([viztask.waitTime(3), skipKey])
 
 playAudioAndSaveGlobalPointer(globals_oa.BOAT_AUDIO_OUTRO_2)
 result = yield viztask.waitAny([viztask.waitMediaEnd(globals_oa.BOAT_AUDIO_OUTRO_2), skipKey])
 markAudioPlayAsEnded()
 if result.condition is skipKey:
  globals_oa.BOAT_AUDIO_OUTRO_2.stop()

 viz.clearcolor(0, 0, 0)
 
 yield fader.fadeOutTask()
 boatscene.killScene()
 
 
 yield viztask.waitTime(3)
 
 viztask.schedule(loadAcknowledgment)
 yield fader.fadeInTask() #1.5
 yield viztask.waitTime(globals_oa.BETWEEN_FADING_TIME) #4
 yield fader.fadeOutTask() #1.5
Exemplo n.º 31
0
#timing
ITI = 2  #intertrial interval, in seconds

##env shape
global radius
radius = 14.5  #in meters, made global for convenience so be careful

##ground
ground = vizshape.addPlane(size=(40.0, 40.0), axis=vizshape.AXIS_Y)
ground.setPosition(0, 0, 0)
t1 = viz.addTexture('tex2.jpg', wrap=viz.REPEAT)
ground.texture(t1)
ground.texmat(viz.Matrix.scale(20, 20, 1))

##sky color
viz.clearcolor(0.1, 0.1, 0.2)

###CONTEXT GEN FUNCTION####


def ContextGen(runNum):

    if runNum % 2 == 0:
        if subject % 2 == 0:
            context = 1
        else:
            context = 2
    else:
        if subject % 2 == 0:
            context = 2
        else:
Exemplo n.º 32
0
def trials(block_no,
           isPoles='None',
           trialNo=10,
           trialtype='Offset',
           continued=False):
    info.setText("Hurrah!! Please wait for the experimenter.")

    if isPoles in ['flipped', 'staying']:
        poles, polelist = poleCreator(ground, pole_wd, pole_dep, pole_ht,
                                      pole_no)
        writePolePos(isPoles, polelist)

    for m in range(trialNo):
        # Set up the response recording file
        global sub_rt

        if continued:
            sub_rt = open(
                'VRrt_' + str(id) + '_Block_' + str(block_no) + '_Trial_' +
                str(m + 9) + '_' + time.strftime("%d-%b-%y_%H-%M") + '.csv',
                'a')
        else:
            sub_rt = open(
                'VRrt_' + str(id) + '_Block_' + str(block_no) + '_Trial_' +
                str(m + 1) + '_' + time.strftime("%d-%b-%y_%H-%M") + '.csv',
                'a')

        data = 'frameNo,Color,TimeStamp,Response'
        sub_rt.write('\n' + data)

        # Set up the real target sensor area
        sensor_Target = vizproximity.Sensor(
            vizproximity.RectangleArea([6, 0.1],
                                       center=[0,
                                               real_tg_dist[(-1)**(m + 1)]]),
            None)
        manager.addSensor(sensor_Target)
        # Set up poles if they change between trials
        if isPoles == 'changing':
            poles, polelist = poleCreator(ground, pole_wd, pole_dep, pole_ht,
                                          pole_no)
            writePolePos(isPoles, polelist)
        elif isPoles == 'flipped':
            poles.setEuler([(90 * (1 - (-1)**m)), 0, 0], mode=viz.ABS_PARENT)
            poles.setPosition([0, 0, polePos[(-1)**(m)]], mode=viz.ABS_PARENT)

        # Stand by
        yield viztask.waitNetwork(serverName)

        # choose target depending on walking direction
        if isPoles == 'flipped':
            if flippedTarget == 'BO':
                if m % 2 == 0:
                    Target2.alpha(0)
                    Target1.color(tg2Color)
                else:
                    Target1.alpha(0)
                    Target2.color(tg2Color)
            else:
                if m % 2 == 0:
                    Target2.alpha(0)
                    Target1.color(tg1Color)
                else:
                    Target1.alpha(0)
                    Target2.color(tg1Color)
            viz.window.screenCapture('flipped_Image_' + str(m) + '.jpg')
        else:
            if m % 2 == 0:
                Target2.alpha(0)
                Target1.color(tg1Color)
            else:
                Target1.alpha(0)
                Target2.color(tg2Color)
            viz.window.screenCapture(isPoles + '_Image_' + str(m) + '.jpg')

        ground.visible(viz.ON)

        labNetwork.send('Ready')
        # Start walking
        yield viztask.waitNetwork(serverName)
        metronome.play()

        if isPoles == 'flipped':
            if flippedTarget == 'BO':
                if m % 2 == 0:
                    colorChange = viztask.schedule(changeColor2(Target1))
                else:
                    colorChange = viztask.schedule(changeColor2())
            else:
                if m % 2 == 0:
                    colorChange = viztask.schedule(changeColor1())
                else:
                    colorChange = viztask.schedule(changeColor1(Target2))
        else:
            if m % 2 == 0:
                colorChange = viztask.schedule(changeColor1())
            else:
                colorChange = viztask.schedule(changeColor2())

        labNetwork.send('Block' + str(block_no) + ' Trial ' + str(m))

        yield viztask.waitTime(0.25)

        # reach the target
        yield vizproximity.waitEnter(sensor_Target)
        alert.play()
        metronome.stop()
        viz.clearcolor(viz.BLACK)
        ground.visible(viz.OFF)
        colorChange.kill()
        labNetwork.send('Reach Target!')

        manager.clearSensors()
        print Target1.getPosition(viz.ABS_GLOBAL)
        print Target2.getPosition(viz.ABS_GLOBAL)
        # Set up the information for participants at the end of trial
        if m < trialNo - 1:
            info.visible(viz.ON)
            yield viztask.waitTime(3)
            info.visible(viz.OFF)
            if isPoles == 'changing':
                poles.remove()
        else:
            # finish writing the response
            info.setText('End of Block ' + str(block_no))
            info.visible(viz.ON)
            yield viztask.waitTime(3)
            info.visible(viz.OFF)
            if isPoles != 'None':
                poles.remove()

        # reset the targets
        if m % 2 == 0:
            Target2.alpha(1)
        else:
            Target1.alpha(1)
Exemplo n.º 33
0
	
def reset():
	viz.MainView.setPosition([10.2,22.92,-34.8])
	viz.MainView.setEuler([-179.16,0,0])

def viewCar():
	viz.MainView.setPosition([0,130,-150])
	viz.MainView.setEuler([0,50,0])

if __name__ == '__main__':
	viz.go()
	SCENE = viz.Scene2
	viz.MainView.setScene(SCENE)
	viz.MainView.setPosition([10.2*0.2,22.92*0.2,-34.8*0.2])
	viz.MainView.setEuler([-179.16,0,0])
	#day = viz.addChild('sky_day.osgb', scene=viz.Scene2)
	car = vizfx.addChild("Sept11_Car.OSGB", scene=SCENE)
	car.setScale(0.2,0.2,.2)
	head = viz.MainView.getHeadLight() 
	head.disable()
	
	control.control(viz.MainView)
	
	addDirectionalLights(0.2,SCENE)
	addFog(SCENE)
	
	vizact.onkeydown('r', reset)
	vizact.onkeydown('v', viewCar)
	
	viz.clearcolor([.1,.1,.1])
Exemplo n.º 34
0
def addFog(scene=viz.MainScene):
	viz.clearcolor([.1,.1,.1])
	#viz.fogcolor(viz.GRAY)
	vizfx.addFogEffect(color=viz.GRAY,start=5,end=0)
Exemplo n.º 35
0
import vizshape
import vizfx
import vizinfo
import oculus
import time
import projector

#Oculus setup code
hmd = oculus.Rift()
viz.link(hmd.getSensor(), viz.MainView)
viz.MainView

viz.setMultiSample(8)
viz.go()

viz.clearcolor(.5, .5, .5)

#For testing without headset
#view = viz.MainView
#view.eyeheight(1.65)

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

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

viz.clearcolor(viz.SLATE)

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

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

#Apply texture to quad
quad.texture(tex)

ANIMATE_SPEED = 0.1

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

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

    #Apply transform to texture
    quad.texmat(mat)

vizact.ontimer(0,animateTexture)
Exemplo n.º 37
0
MOVE_SPEED = .005
ROTATION_SPEED = 5
SUB_GROUP_SPACING = 20
for i in range(0, NUM_DOTS):
	x = random.random() - 0.5
	y = random.random() / 2
	z = random.random() - 0.5
	length = math.sqrt(x*x + y*y + z*z)
	x = x / length * RADIUS
	y = y / length * RADIUS
	z = z / length * RADIUS
	particleGroup = viz.addGroup()
	particleGroup.setPosition([x, y, z])
	particleGroup.setEuler([random.random()*360, random.random()*360, random.random()*360])
	particleGroup.addAction(vizact.spin(random.random(),random.random(),random.random(), random.random()*ROTATION_SPEED,viz.FOREVER))
	particleGroup.addAction(vizact.move(random.random()*MOVE_SPEED,random.random()*MOVE_SPEED,random.random()*MOVE_SPEED,viz.FOREVER), 1)
	
	for i in range(10):
		clone = particle.clone()
		clone.parent(particleGroup)
		clone.setScale([SCALE]*3)
		clone.setEuler([random.random()*360, random.random()*360, random.random()*360])
		clone.setPosition([random.random()*SUB_GROUP_SPACING, random.random()*SUB_GROUP_SPACING, random.random()*SUB_GROUP_SPACING])
	
	

if __name__ == '__main__':
	viz.go()
	viz.add('tut_ground.wrl')
	viz.clearcolor(viz.BLUE)
Exemplo n.º 38
0
#env = viz.add(viz.ENVIRONMENT_MAP, 'eucalyptus\eucalyptus.jpg',scene=viz.MainScene)
env = viz.add(viz.ENVIRONMENT_MAP, 'sky.jpg',scene=viz.MainScene)
sky = viz.add('skydome.dlc')
sky.texture(env)

TRANSLATE_INC = .2
ROTATION_INC = 2
SCALE = [0.03, 0.03, 0.03]
room = viz.add("../models/room2/room2.wrl")
room.setScale(SCALE)

ground = viz.add('tut_ground.wrl')
ground.setScale([5,1,5])
#viz.translate(viz.HEAD_POS,0,20,-20)
#viz.lookat(0,0,0)
viz.clearcolor(viz.SKYBLUE)


vizact.whilekeydown(viz.KEY_UP,viz.move,0,0,TRANSLATE_INC) #Move forward while up key is pressed
vizact.whilekeydown(viz.KEY_DOWN,viz.move,0,0,-TRANSLATE_INC) #Move backward while down key is pressed
vizact.whilekeydown(viz.KEY_LEFT,viz.rotate,viz.BODY_ORI,-ROTATION_INC,0,0) #Turn left while left arrow pressed
vizact.whilekeydown(viz.KEY_RIGHT,viz.rotate,viz.BODY_ORI,ROTATION_INC,0,0) #Turn right while right arrow pressed


def onCollideBegin(e):
	global pg
	if pg.abe.avatar == e.obj1:
		pg.abe.collision()
viz.callback(viz.COLLIDE_BEGIN_EVENT, onCollideBegin)

pg = path.PathGenerator()
Exemplo n.º 39
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
	
	#---------------------------------------------------------------------------
	# init vizard
	
	# initialize pdb if debugging is needed
	#pdb.set_trace()

	# 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()

	# 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)
Exemplo n.º 40
0
 yield viztask.waitTime(globals_oa.BETWEEN_FADING_TIME) #4
 yield fader.fadeOutTask() #1.5

# yield viztask.waitTime(globals_oa.CREDITS_TIME)
# yield fader.fadeOutTask()
# sys.exit('exiting now!')
 
#Load ALL assets for both scenes
#GodRay.init()
#boatscene.initFog()
#loadBoatScene2()
loadBoatScene()
globals_oa.user.setPosition([0,0,0])
loadDisabledOceanScene()
scavengerhunt.loadStuff()
viz.clearcolor(0, 0, 0)
#createSphereScene()
#schedule master scene manager
audiocache.loadAudioAssets()
viztask.schedule(loadOpeningTitle())
#viztask.schedule(loadBoatScene())
#viztask.schedule(boatscene.unhideBoatAndIschia())
#removeSphere()
viztask.schedule(startBoatIntro)



def playAudioAndSaveGlobalPointer(audioFilePointer):
 print "playing audio - " + str(audioFilePointer)
 globals_oa.audioFilePlaying = audioFilePointer
# if globals_oa.audioMixer is not None:
Exemplo n.º 41
0
	viztask.returnValue(descr)
	
def cross_block(list_of_trials,training=False):
	# keep track of trial results
	results = []
	successes = 0
	block_text.message("DEADLINE: %.2f"%list_of_trials[0][2])
	vizact.ontimer2(rate=MESSAGE_TIME, repeats=0,func=clear_text)
	# Loop over the rest of the trials
	for trial in list_of_trials[1:]:
		res = yield cross_trial(*trial,training=training)
		results.append(res)
		successes += results[-1]["success"]
	# Display successes at the end
	yield end_block(successes,len(list_of_trials))
	yield viztask.waitTime(4)
	# Clear the message
	block_text.message("")
	viztask.returnValue( results )

if  __name__ == "__main__":
	viz.go()
	viz.clearcolor(viz.GRAY)
	from design.sequence import create_full_experiment
	def multitrial():
		results = []
		blocks = create_full_experiment([0.3, 0.2, 0.4, 0.5])
		for block in blocks:
			results += yield cross_block(block,training=True)
		viztask.returnValue(results)
	res = viztask.schedule(multitrial())
Exemplo n.º 42
0
	viz.clip(.1,100000)
	
	ocean = vizfx.addChild(ART_DIRECTORY + './art/environment/OceanFloor.osgb')
	
	
	
	# Change properties to enable the god ray.
	water = ocean.getChild('Water')
	water.disable(viz.DEPTH_WRITE)
	water.drawOrder(101)

	# Create and apply global fog effect.
#	fog = vizfx.addFogEffect(  colorRamp=viz.addTexture(ART_DIRECTORY + './art/texture/FogRamp.tif'), height=1, density=(.09))
	fog = vizfx.addFogEffect(  colorRamp=viz.addTexture(globals_oa.MODEL_DIRECTORY + 'FogRamp.tif'), height=1, density=(.09))
	vizfx.getComposer().addEffect(fog)
	bgcolor = [0.15*1.2, 0.67*1.2, 0.95*1.2]
	viz.clearcolor(bgcolor)

	# Enable fog on main scene.
#	viz.MainScene.enable(viz.FOG, op=viz.OP_ROOT)

	# Add sun light.
	lightSun = vizfx.addPointLight()
	lightSun.constantAttenuation(0)
	lightSun.linearAttenuation(0)
	lightSun.quadraticAttenuation(.3)
	lightSun.setPosition([0.123,0.84911,-1.929])
	lightSun.color( viz.WHITE )
	lightSun.specular( viz.WHITE )
	lightSun.ambient( viz.BLACK )
#	viztracker.DEFAULT_HANDS = True
#	viztracker.go()

#so far so good

viz.setMultiSample(4)
viz.fov(60)
viz.go()
#Add a world axis with X,Y,Z labels
world_axes = vizshape.addAxes()
X = viz.addText3D('X',pos=[1.1,0,0],color=viz.RED,scale=[0.3,0.3,0.3],parent=world_axes)
Y = viz.addText3D('Y',pos=[0,1.1,0],color=viz.GREEN,scale=[0.3,0.3,0.3],align=viz.ALIGN_CENTER_BASE,parent=world_axes)
Z = viz.addText3D('Z',pos=[0,0,1.1],color=viz.BLUE,scale=[0.3,0.3,0.3],align=viz.ALIGN_CENTER_BASE,parent=world_axes)
#grids are good
grid = vizshape.addGrid(color=[0.2]*3)
viz.clearcolor(viz.GRAY)

#Create proximity manager
manager = vizproximity.Manager()
manager.setDebug(viz.ON)



#create our bisecting plane
mid_plane= vizshape.addPlane(size=(.00001,.00001),axis=vizshape.AXIS_X, cullFace=False)

start_node= right_node=vizshape.addCylinder(height, radius=2,topRadius= None,bottomRadius= None, axis=vizshape.AXIS_Y,slices=20,bottom=True,top=True)
     
left_node=vizshape.addCylinder(height, radius= 3,topRadius= None,bottomRadius= None, axis=vizshape.AXIS_Y,slices=20,bottom=True,top=True)        
right_node=vizshape.addCylinder(height, radius=2,topRadius= None,bottomRadius= None, axis=vizshape.AXIS_Y,slices=20,bottom=True,top=True)
left_plane1= vizshape.addPlane(size=(1*scale_x,1*scale_y,),axis=vizshape.AXIS_Y, cullFace=False)
import viz
import vizcam
import vizact
import cgi
import vizinfo
import vizhtml

viz.go()
viz.cam.setHandler(vizcam.KeyboardCamera())
viz.phys.enable()
viz.MainView.setPosition(-4, 1, -3)
viz.MainView.setEuler(30, 0, 0)

ground = viz.add('tut_ground.wrl')
viz.clearcolor([.5, .6, 1])
lab = viz.add('Living_Lab_Blinds_V2.OSGB', scale=[0.002] * 3)
lab.setPosition([0, 0.258, 5])

#Pagina de test: http://localhost:8080/vizhtml/custom_handler/
# Display form submitted message on screen
info = vizinfo.InfoPanel('')

code = """
<html>
<head>
    <title>vizhtml Custom Handler Example</title>
</head>
<body onload="document.the_form.message.focus();">
<img src='ball.jpg'>
<form name="the_form" method="post">
    <table>
Exemplo n.º 45
0
        logging.info(str(tformOutString + posOutString + mPositionOutString))

if __name__ == "__main__":

    mocap = phasespaceInterface()
    mocap.start_thread()

    #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')
Exemplo n.º 46
0
def createEnvironment():
    global point
    global arrow
    global goal
    global thrust
    global shadow

    #create 3D environment
    if parameters.dreiDEnvironment:

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

        #look from above
        viz.MainView.setPosition([0, 1.8, -5])
        viz.MainView.setEuler([0, 20, 0])
        viz.collision(viz.ON)
        # gorund for collision
        ground = viz.add('tut_ground.wrl')  # Add ground
        ground.collidePlane()  # Make collideable plane
        ground.disable(viz.RENDERING)
        ground.disable(viz.DEPTH_WRITE)

        # point
        #point = viz.add('ball.wrl')
        point = vizshape.addSphere(radius=parameters.pointRadius,
                                   slices=20,
                                   stacks=20,
                                   axis=vizshape.AXIS_Y)
        pointPhys = point.collideSphere()  # Define ball's physical properties

        point.setEuler(0, 90, 0)
        point.setPosition(0, parameters.point_height, 0)
        point.color(viz.RED)
        point.setScale(0.5, 0.5, 0.5)
        point.enable(viz.COLLIDE_NOTIFY)

        #goal
        goal = vizshape.addCircle(slices=100, radius=0.3)
        goal.setEuler(0, 90, 0)
        goal.color(viz.GREEN)
        goal.setPosition(0, parameters.goal_height, 0)
        goal.setScale(parameters.goal_scale3D, parameters.goal_scale3D,
                      parameters.goal_scale3D)

        #shadow
        shadow = vizshape.addCircle(slices=100, radius=0.3)
        shadow.setEuler(0, 90, 0)
        shadow.color(viz.GRAY)
        shadow.setPosition(0, parameters.shadow_height, 0)
        shadow.setScale(parameters.shadow_scale3D, parameters.shadow_scale3D,
                        parameters.shadow_scale3D)

        #arrow
        arrow = vizshape.addArrow()
        arrow.setPosition(0, parameters.arrow_height3D, 0)
        arrow.color(viz.BLUE)

        #thrust
        thrust = point.addThruster(force=[0, 0, 0])

    #or create 2d environment
    else:
        viz.clearcolor(viz.WHITE)

        #look from above
        viz.MainView.setPosition([0, 8, 0])
        viz.MainView.setEuler([0, 90, 0])

        #point = viz.add('ball.wrl')
        point = vizshape.addSphere(radius=parameters.pointRadius,
                                   slices=20,
                                   stacks=20,
                                   axis=vizshape.AXIS_Y)
        pointPhys = point.collideSphere()  # Define ball's physical properties
        point.setEuler(0, 90, 0)
        point.setPosition(0, parameters.point_height, 0)
        point.color(viz.RED)
        point.visible(False)
        point.enable(viz.COLLIDE_NOTIFY)

        #wind force
        thrust = point.addThruster(force=[0, 0, 0])

        #goal
        goal = vizshape.addCircle(slices=100, radius=0.2)
        goal.setEuler(0, 90, 0)
        goal.color(viz.GREEN)
        goal.visible(False)
        goal.setScale(parameters.goal_scale2D, parameters.goal_scale2D,
                      parameters.goal_scale2D)

        #arrow
        arrow = vizshape.addArrow()
        viz.mouse(viz.OFF)
        arrow.setPosition(0, parameters.arrow_height2D, 0)
        arrow.color(viz.BLUE)
        arrow.visible(False)