def setAsMain(self): viz.logStatus("""Setting KeyboardMouse as main""") # self.VIEW_LINK.preTrans([0,-self.EYE_HEIGHT,0]) viz.mouse.setOverride(viz.ON) viz.fov(self.FOV) # self.MOVE_SPEED = 2 vizact.ontimer(0,self.updateView) vizact.onkeyup(self.KEYS['reset'],self.reset) def onMouseMove(e): euler = self.VIEW.getEuler(viz.HEAD_ORI) euler[0] += e.dx*0.05 euler[1] += -e.dy*0.05 euler[1] = viz.clamp(euler[1],-85.0,85.0) self.VIEW.setEuler(euler,viz.HEAD_ORI) viz.callback(viz.MOUSE_MOVE_EVENT, onMouseMove)
def add_periodic(self, period, callback): '''Call some code periodically while running a task. The given `callback` will be called every `period` seconds between the firings of the PRE_RUN and POST_RUN events for this task. Parameters ---------- period : float Number of seconds between successive calls to the `callback`. callback : callable (no arguments) Call this function every `period` seconds. Returns ------- timer_id : The Vizard timer ID. Can be used to kill this periodic event. ''' timer_id = 1 + max(self._timers) self._timers.append(timer_id) viz.callback(self.POST_RUN_EVENT, lambda me: viz.killtimer(timer_id)) def start(me): def clock(t): if t == timer_id: callback() viz.callback(viz.TIMER_EVENT, clock) viz.starttimer(timer_id, period, viz.FOREVER) viz.callback(self.PRE_RUN_EVENT, start) return timer_id
def start(me): def clock(t): if t == timer_id: callback() viz.callback(viz.TIMER_EVENT, clock) viz.starttimer(timer_id, period, viz.FOREVER)
def main(): global loc_list global active_location loc_list = [] mainSceneWindow = None cameraWindow = None cameraWindowView = None cam = None pause_screen = None nunchuck_disconnect_screen = None message_screen = None wiimote = None nunchuck_wiimote = None should_it_run = None mainSceneWindow, cameraWindow, cameraWindowView, cam, pause_screen, nunchuck_disconnect_screen, message_screen, wiimote, nunchuck_wiimote, should_it_run = init_settings(mainSceneWindow, cameraWindow, cameraWindowView, cam, pause_screen, nunchuck_disconnect_screen, message_screen, wiimote, nunchuck_wiimote, should_it_run) vizact.ontimer(0, moveCamera, nunchuck_wiimote, should_it_run) viz.callback(wii.EXT_CONNECT_EVENT,onConnect) viz.callback(wii.EXT_DISCONNECT_EVENT,onDisconnect) initializer(loc_list) arMarkerLoader(cam) wiimoteInitializer(wiimote, nunchuck_wiimote, should_it_run, message_screen) viz.go() # Inicia VIZ for item in loc_list: if item.space_name == "piazza.osgb": active_location = item item.addLocation()
def ReadInHotSpots(filename, scale=4, radius=0.5, movement=None): global __HOTSPOTS, __HOTSPOT_SOUNDS, __GOTO_SOUNDS, __MESSAGE, __IN_HOTSPOT global __CALLBACK, __START, __RADIUS, __SCALE, __MOVEMENT num = 0 for (x, z) in __HOTSPOTS: # remove any existing hotspots num += 1 viz.deletehotspot(num) viz.deletehotspot(-num) # reset variables __HOTSPOTS = [] __HOTSPOT_SOUNDS = [] __GOTO_SOUNDS = [] __MESSAGE = None __CALLBACK = None __START = None __IN_HOTSPOT = 0 __RADIUS = radius __SCALE = scale if movement is None: __MOVEMENT = Movement else: __MOVEMENT = movement try: inFile = open(filename, 'r') except: raise "\n\n********************************************\nCan not open the hotspot file:\n\t%s\nMake sure that the file exists and that\nthe current working directory is correct.\n********************************************\n" % filename for line in inFile.readlines(): # read in hotspot info from each line words = line.split('|') __HOTSPOTS.append((int(float(words[0])), int(float(words[1])))) __HOTSPOT_SOUNDS.append(string.strip(words[2])) __GOTO_SOUNDS.append(string.strip(words[3])) inFile.close() ResetHotSpots() # resets hotspots (which will activate them) viz.callback(viz.HOTSPOT_EVENT, HotSpotHandler) # set viz callback function for hotspots
def __init__(self, x=0, y=0, angle=0, scale=4, speed=DEFAULT_MAX_SPEED, center_offset=0, callback=None, **kwargs): print 'Initializing Joystick.movement' global __JOYSTICK_VAR frequency = 0.01 timer_id = 1 self.motion = __JOYSTICK_VAR = InputHandler(frequency, speed * scale / 8, **kwargs) self.scale = float(scale) self.callbacks = {timer_id: self.UpdateLocation} self.coords = (x, y, angle) self.callback = callback self.center_offset = center_offset viz.eyeheight(0.0) viz.setfov(70, 1) viz.mouse(viz.OFF) # don't want vizard mouse navigation viz.callback(viz.TIMER_EVENT, self.TimerCallback) viz.starttimer(timer_id, frequency, -1)
def initializeBoatGrabberAndPhysics(): global grabberTool, ObjectsToGrab, ALL_GRABBED_EVENT globals_oa.boat.collideMesh() usingPhysics=False from tools import grabber from tools import highlighter global rhGrabber, lhGrabber if rhGrabber is None: rhGrabber = grabber.Grabber(usingPhysics=False, usingSprings=False, highlightMode=highlighter.MODE_BOX) if lhGrabber is None: lhGrabber = grabber.Grabber(usingPhysics=False, usingSprings=False, highlightMode=highlighter.MODE_BOX) rhGrabber.setUpdateFunction(rUpdateGrabberOnBoat) if globals_oa.rhModel is not None: rhGrabber.setParent(globals_oa.rhModel) lhGrabber.setUpdateFunction(lUpdateGrabberOnBoat) if globals_oa.lhModel is not None: lhGrabber.setParent(globals_oa.lhModel) for obj in ObjectsToGrab: obj.collideBox() rhGrabber.setItems(ObjectsToGrab) lhGrabber.setItems(ObjectsToGrab) viz.callback(grabber.GRAB_EVENT,grabObject) viz.callback(grabber.RELEASE_EVENT, releaseObject)
def motion(): # Create Fixation Dot viz.startLayer(viz.POINTS) viz.pointSize(self.POINTSIZE) viz.vertexColor(viz.GRAY) viz.vertex(0, 1.8, 4) points = viz.endLayer() points.disable(viz.CULLING) # Create the circles sphere = self.createCircles(26, 1, 30, -26) sphere2 = self.createCircles(22, 0.8, 30, -26) sphere3 = self.createCircles(18, 0.6, 30, -26) sphere4 = self.createCircles(14, 0.4, 30, -26) sphere5 = self.createCircles(10, 0.2, 30, -26) viz.MainView.move([0, 0, 3]) def keydown(key): if key == 'f': self.response = 'self motion' self.keyPressTime = viz.tick() # get time for keypress print(self.response, self.keyPressTime) self.STATE = 'State - self Motion' if key == 'j': self.response = 'object motion' self.keyPressTime = viz.tick() # get time for keypress print(self.response, self.keyPressTime) self.STATE = 'State - Object Motion' viz.callback(viz.KEYDOWN_EVENT, keydown)
def __init__(self): viz.callback(viz.COLLIDE_BEGIN_EVENT, onCollide) self.node = vizshape.addCube(TouchCube.DEFAULT_SIZE) viz.VizNode.__init__(self,self.node.id) self.collideBox() self.disable(viz.DYNAMICS) self.enable(viz.COLLIDE_NOTIFY) #BL:start if USING_VIZSONIC: if TouchCube.activateSound == None: TouchCube.activateSound = self.playsound("./Resources/Misc/tcActivate.wav", viz.STOP, volume=0.1) if TouchCube.bingSound == None: # Bing TouchCube.bingSound = self.playsound("./Resources/Misc/bingCropped.wav", viz.STOP, volume = 0.1) else: print "skipping those errors!" if TouchCube.activateSound == None: TouchCube.activateSound = self.playsound("./Resources/Misc/tcActivate_mono.wav", viz.STOP) if TouchCube.bingSound == None: # Bing TouchCube.bingSound = self.playsound("./Resources/Misc/bingCropped_mono.wav", viz.STOP) #BL:end self.color = self._changeColor self._dimColor = [1,1,1] self._isLit = False self.disabledTouchers = []
def __init__(self): # create simple GUI window with buttons for: pause, continue and a window to print strings self.pause_button = viz.addButtonLabel('pause Experiment') self.pause_button.setPosition(.5, .7) self.pause_button.setScale(2, 2) self.continue_button = viz.addButtonLabel('continue Experiment') self.continue_button.setPosition(.5, .5) self.continue_button.setScale(2, 2) self.text_screen = viz.addText('current marker:', viz.SCREEN) self.text_screen.setPosition(.25, .3) self.marker_field = viz.addButtonLabel('markers') self.marker_field.setPosition(.5, .2) self.marker_field.setScale(2, 2) # register callbacks for GUI to either pause or continue function viz.callback(viz.BUTTON_EVENT, self.on_button_press) # create network outlet self.connection_to_vr_machine = viz.addNetwork('BPN-C043') # register callback for network event handling viz.callback(viz.NETWORK_EVENT, self.write) # send behavioral to LSL stream (saved extra for faster testing of behavioral data) # create and start LSL marker stream self.behavior_stream_info = StreamInfo('BehavioralMarkerStream', 'Markers', 1, 0, 'string', socket.gethostname()) self.behavior_stream = StreamOutlet(self.behavior_stream_info)
def __init__(self): viz.callback(viz.COLLIDE_BEGIN_EVENT, onCollide) self.node = vizshape.addCube(TouchCube.DEFAULT_SIZE) viz.VizNode.__init__(self,self.node.id) self.collideBox() self.disable(viz.DYNAMICS) self.enable(viz.COLLIDE_NOTIFY) #BL:start if some_global_variables.PPT1: if TouchCube.activateSound == None: TouchCube.activateSound = self.playsound(PATH_TO_STUFF + "./Resources/Misc/tcActivate.wav", viz.STOP, volume=0.1) if TouchCube.bingSound == None: # Bing TouchCube.bingSound = self.playsound(PATH_TO_STUFF + "./Resources/Misc/bingCropped.wav", viz.STOP, volume = 0.1) else: if TouchCube.activateSound == None: TouchCube.activateSound = self.playsound(PATH_TO_STUFF + "./Resources/Misc/tcActivate_mono.wav", viz.STOP) if TouchCube.bingSound == None: # Bing TouchCube.bingSound = self.playsound(PATH_TO_STUFF + "./Resources/Misc/bingCropped_mono.wav", viz.STOP) #BL:end self.color = self._changeColor self._dimColor = [1,1,1] self._isLit = False self.disabledTouchers = []
def creepilyMoveCloser(node): global introAudio1, introAudio2 global comeForward, firstSeatPosition, seatQueue global PID dout = DataOutputHelper(PID) comeForward = seatQueue[-2] firstSeatPosition = seatQueue[0] node.setPosition(firstSeatPosition) yield viztask.waitMediaEnd(introAudio1) introAudio2.play() # We want the participant to have a minute after the audio ends viz.callback(viz.MEDIA_EVENT,onAudioEnd) dout.timestamp(dout.busFile, 'Initial audio ended') yield viztask.waitMediaEnd(introAudio2) yield viztask.waitTime(.1) # Pause necessary for NodeViewDetection to get necessary info about node nvd = DetectWhetherInView.NodeViewDetection(node) FadeObject.beginFading() moveAsUsual = False getCloserBeforeBackAway = True while getCloserBeforeBackAway: node.setPosition(firstSeatPosition) yield waitTilNodeAndDestOutsideView(nvd, firstSeatPosition) yield waitTilNodeInsideView(nvd) node.setPosition(comeForward) yield creepilyMakeEyeContact(node, comeForward, dout) yield moveBackToFirstSeat(node, seatQueue) if abs(node.getPosition()[0] - firstSeatPosition[0]) < 0.1: getCloserBeforeBackAway = False moveAsUsual = True print 'waiting til node inside view...' yield waitTilNodeInsideView(nvd) while moveAsUsual: print 'waiting until node and dest outside view...' nextPosition = seatQueue[1] # Peek at nextPosition yield waitTilNodeAndDestOutsideView(nvd, nextPosition) # Pauses til node and that position are outside of view # Move to nextPosition print 'node and dest are outside view! Moving to next position...' node.setPosition(nextPosition) seatQueue.rotate(-1) # update seatQueue print 'waiting til node inside view...' yield waitTilNodeInsideView(nvd) print 'creepily dodging eye contact...' yield creepilyMakeEyeContact(node, seatQueue[0], dout) #if seatQueue[0] is not finalSeatPosition: print 'waiting 5 seconds then moving him back if hes in view at the end of the 5 seconds.' # TODO: This is not exactly what we want. yield moveBackwardsIfStaredAt(node, nvd) # If the node is not in the last seat position,
def setAsMain(self): viz.logStatus('Setting Joyculus as main') val = mathlite.getNewRange(self.joy.getSlider(),1,-1,self.MIN_SPEED,self.MAX_SPEED) self.MOVE_SPEED = val vizact.onsensordown(self.joy,self.KEYS['reset'],self.reset) vizact.ontimer(0,self.updateView) viz.callback(getExtension().SLIDER_EVENT,self.onSliderChange)
def changeQ(sceneIndex, qList, delayTime, panelTitle, breakQ=True): indexQuestion = "delay" global indexQuestion if sceneIndex == "U_0_control.png" or sceneIndex == "2_med.png": condition = "demo" indexscene = sceneIndex shuffleQuestionList = list(IntroQ) shuffle(shuffleQuestionList) else: condition = "scene" indexScene = env_map_namelist[sceneIndex] shuffleQuestionList = list(qList) shuffle(shuffleQuestionList) global indexScene Panelvisible(Panel, 0) yield viztask.waitTime(delayTime) Panelvisible(Panel, 1) rowBottom.visible(viz.ON) maxNumber.visible(viz.ON) qIndex = 0 while qIndex < len(qList): Panel.setTitle(panelTitle) viz.callback(dinput.HAT_EVENT, onHatChange) question = shuffleQuestionList[qIndex] changeMessage(shuffleQuestionList[qIndex], breakQ) if condition == "scene": index = mainQOrig.index(question) if condition == "demo": index = IntroQ.index(question) indexQuestion = str(index + 1) global indexQuestion #track.setEnabled(viz.OFF) yield viztask.waitAny([waitButton1], d) if d.condition is waitButton1: yield viztask.waitTime(.2) pos = Slider.get() if round(abs(pos / .1), 1) > 0: saveRate(qIndex, sceneIndex, index) Slider.set(0) Slider.message("") qIndex = qIndex + 1 else: yield viztask.waitTime(.2) #Panel.setTitle("MINIMUM SELECTION IS (0)") yield viztask.waitTime(3) if qIndex == len(qList): #viztask.schedule(FadeToGrayTask()) Panelvisible(Panel, 0) sky.visible(viz.OFF) yield viztask.waitTime(1)
def enable(): global car, call_screen, SCENE viz.MainWindow.setScene(SCENE) reset() vizact.onkeydown('r', reset) #PhoneRadio.test(SCENE, car, call_screen) PhoneRadio.enable(SCENE, car, call_screen) #wait for keypress 1 to start object finding portion viz.callback(PhoneRadio.INTRO_OVER_EVENT, PosessionHunting.enable) #waits for last object to be found, and then schedules police narrative viz.callback(PosessionHunting.FINDING_TASK_OVER_EVENT, police.enable)
def setup(conf): """ Set up all the hardware used in the ball catching experiment :param conf: config['hardware'] entry of full config dict :return: None """ global config global hmd global head_tracker global eye_tracker global link config = conf print '\nSetting up hardware modules...' # configure Oculus Rift if config['use_hmd']: hmd = oculus.Rift() hmd.setMonoMirror(True) hmd.getSensor().reset() # setup position tracking (WorldViz PPTX) if config['use_ppt']: head_tracker = ppt.add_tracker(0) link = ppt.link(tracker=head_tracker, ori=hmd.getSensor(), target=viz.MainView, pre_trans=[-0.05, -0.05, 0.02]) head_tracker = head_tracker # no ppt else: link = viz.link(hmd.getSensor(), viz.MainView, mask=viz.LINK_ORI) link.setOffset([0, 1.8, 0]) viz.MainView.setPosition([0, 1.8, -3]) # setup eye tracker if config['eye_tracking']: eye_tracker = EyeTracker() # configure screen setup else: viz.MainView.setPosition(0, 0, -4, viz.REL_LOCAL) viz.setOption('viz.fullscreen.monitor', 2) keyboard_cam = vizcam.KeyboardCamera() link = link # keys for hardware control viz.callback(viz.KEYDOWN_EVENT, on_key_down)
def main(): viz.vsync(viz.ON) viz.window.setFullscreenMonitor([2]) viz.setMultiSample(4) viz.MainWindow.clip(0.01, 200) viz.go(viz.FULLSCREEN) environment = viz.addChild("piazza.osgb") environment.setPosition(2.75, 0, -0.75) mocap = phasespace.Phasespace() head = mocap.get_rigidTracker("hmd") # DOES NOT ACCOUNT FOR RIGID BODY OFFSET DURING RESET # mocap.track_rigid('Resources/hmd-nvisMount.rb', center_markers=(1,2)) head.link_pose(viz.MainView) # glove = mocap.track_points([8, 9, 10]) paddle = mocap.track_rigid({17: (0, 0, 1), 19: (0, 0, 0), 20: (1, 0, 0), 22: (0, 1, 0)}) mocap.start_thread() # mocap.start_timer() def log_mocap(timer_id): # print 'glove#9 pos {0[1]:.2f} {0[1]:.2f} {0[2]:.2f}'.format(*glove.get_marker(9)) print "head pos {0[0]:.2f} {0[1]:.2f} {0[2]:.2f}, quat {1[0]:.3f} {1[1]:.3f} {1[2]:.3f} {1[3]:.3f}".format( *head.get_pose() ) print "main " + str(viz.MainView.getPosition()) # print 'paddle pos {0[0]:.2f} {0[1]:.2f} {0[2]:.2f}, quat {1[0]:.3f} {1[1]:.3f} {1[2]:.3f} {1[3]:.3f}'.format(*paddle.get_pose()) viz.callback(viz.TIMER_EVENT, log_mocap) viz.starttimer(0, 1, viz.FOREVER) def keydown(key): if key == "h": head.reset() if key == "H": head.save() elif key == "1": print "Marker Pos: " + str(mocap.get_MarkerPos(1)) viz.callback(viz.KEYDOWN_EVENT, keydown)
def __init__(self, scene=viz.Scene1, avatar=None): self.scene = scene self.avatar = avatar self.subwindow = None self.subview = None self.scale = 0.4 self.initScreen() if self.avatar is not None: self.initAvatar() vizact.onkeydown(' ',self.toggleVisibility) viz.callback(viz.MOUSEWHEEL_EVENT,self.rescale)
def __init__(self, handTracker = None): # These two lines are weird necessities to subclass the VizNode class (which most Vizard objects are?) self.node = viz.addChild(Dart._MODEL_FILE) viz.VizNode.__init__(self,self.node.id) self.setScale(Dart._SCALE, Dart._SCALE, Dart._SCALE) self.color(1, 0, 0) self.collideBox() self.enable(viz.COLLIDE_NOTIFY) viz.callback(viz.COLLIDE_BEGIN_EVENT, onCollide) self.initVelocity() self.initEuler() self.setVelocity([0, 0, 0]) if handTracker != None: self.attachToHand(handTracker)
def main(): viz.setOption('viz.fullscreen.monitor', 1) viz.setOption('viz.window.width', 2 * 640) viz.setOption('viz.window.height', 480) viz.setMultiSample(4) viz.MainWindow.clip(0.01, 500) vizconfig.register(nvis.nvisorSX111()) viz.go(viz.FULLSCREEN) piazza = viz.addChild('piazza.osgb') mocap = phasespace.Mocap('192.168.1.230') head = mocap.track_rigid('Resources/hmd-nvis.rb', center_markers=(0, 5)) head.link_pose(viz.MainView) glove = mocap.track_points([8, 9, 10]) paddle = mocap.track_rigid({ 17: (0, 0, 1), 19: (0, 0, 0), 20: (1, 0, 0), 22: (0, 1, 0), }) mocap.start_thread() #mocap.start_timer() def log_mocap(timer_id): print 'glove#9 pos {0[1]:.2f} {0[1]:.2f} {0[2]:.2f}'.format( *glove.get_marker(9)) print 'head pos {0[0]:.2f} {0[1]:.2f} {0[2]:.2f}, quat {1[0]:.3f} {1[1]:.3f} {1[2]:.3f} {1[3]:.3f}'.format( *head.get_pose()) print 'paddle pos {0[0]:.2f} {0[1]:.2f} {0[2]:.2f}, quat {1[0]:.3f} {1[1]:.3f} {1[2]:.3f} {1[3]:.3f}'.format( *paddle.get_pose()) viz.callback(viz.TIMER_EVENT, log_mocap) viz.starttimer(0, 1, viz.FOREVER) def keydown(*args): head.reset() paddle.reset() viz.callback(viz.KEYDOWN_EVENT, keydown)
def __setupTracking__(self): #get mocap interface self.mocap = Connector.getMocapInterface() #Get the shutter-glass rigid body self.shutterGlass = self.mocap.returnPointerToRigid(Connector.SHUTTERGLASSES) self.head_tracker = viz.link(self.shutterGlass.vizNode,viz.NullLinkable,srcFlag=viz.ABS_PARENT) self.cave.setTracker(self.head_tracker) # Create cave view cave_origin = vizcave.CaveView(self.head_tracker) #In case you want to override & translate the physical location of cave, uncommnet this ''' origin_tracker = viztracker.KeyboardMouse6DOF() origin_link = viz.link(origin_tracker, cave_origin) origin_link.setMask(viz.LINK_POS) ''' #Foot rigidBodies leftFootRigid = self.mocap.returnPointerToRigid(Connector.L_FOOT) rightFootRigid = self.mocap.returnPointerToRigid(Connector.R_FOOT) #Foot visuals, make them 100% transparent when not in debug mode self.leftFootViz = vizshape.addBox(size=(.2,.2,.2)) self.rightFootViz = vizshape.addBox(size=(.2,.2,.2)) if(self.debug): self.leftFootViz.alpha(0.025) self.rightFootViz.alpha(0.025) else: self.leftFootViz.alpha(0.0075) self.rightFootViz.alpha(0.0075) #Foot class objects self.leftFoot = Foot(mocapFootObj = leftFootRigid, name="Left") self.rightFoot = Foot(mocapFootObj = rightFootRigid, name="Right") #setup buffer updates vizact.onupdate(0, self.leftFoot.populateNextBufferElement) vizact.onupdate(0, self.rightFoot.populateNextBufferElement) vizact.onupdate(0, self.updateBooties) viz.callback(viz.COLLIDE_BEGIN_EVENT, self.collideDetected)
def main(): viz.setOption('viz.fullscreen.monitor', 1) viz.setOption('viz.window.width', 2 * 640) viz.setOption('viz.window.height', 480) viz.setMultiSample(4) viz.MainWindow.clip(0.01, 500) vizconfig.register(nvis.nvisorSX111()) viz.go(viz.FULLSCREEN) piazza = viz.addChild('piazza.osgb') mocap = phasespace.Mocap('192.168.1.230') head = mocap.track_rigid('Resources/hmd-nvis.rb', center_markers=(0, 5)) head.link_pose(viz.MainView) glove = mocap.track_points([8, 9, 10]) paddle = mocap.track_rigid({ 17:(0, 0, 1), 19:(0, 0, 0), 20:(1, 0, 0), 22:(0, 1, 0), }) mocap.start_thread() #mocap.start_timer() def log_mocap(timer_id): print 'glove#9 pos {0[1]:.2f} {0[1]:.2f} {0[2]:.2f}'.format(*glove.get_marker(9)) print 'head pos {0[0]:.2f} {0[1]:.2f} {0[2]:.2f}, quat {1[0]:.3f} {1[1]:.3f} {1[2]:.3f} {1[3]:.3f}'.format(*head.get_pose()) print 'paddle pos {0[0]:.2f} {0[1]:.2f} {0[2]:.2f}, quat {1[0]:.3f} {1[1]:.3f} {1[2]:.3f} {1[3]:.3f}'.format(*paddle.get_pose()) viz.callback(viz.TIMER_EVENT, log_mocap) viz.starttimer(0, 1, viz.FOREVER) def keydown(*args): head.reset() paddle.reset() viz.callback(viz.KEYDOWN_EVENT, keydown)
def bmw_card_driver(): car = viz.addChild('bmw.dae') car.setEuler([0,0,0]) car.setScale(0.5,0.5,0.5) MOVE_SPEED = 5 TURN_SPEED = 60 def updatecar(): #move view forward and backward if viz.key.isDown(viz.KEY_UP): view.move([0,0,MOVE_SPEED*viz.elapsed()],viz.BODY_ORI) elif viz.key.isDown(viz.KEY_DOWN): view.move([0,0,-MOVE_SPEED*viz.elapsed()],viz.BODY_ORI) #rotate body of view left and right if viz.key.isDown(viz.KEY_RIGHT): view.setEuler([TURN_SPEED*viz.elapsed(),0,0],viz.BODY_ORI,viz.REL_PARENT) elif viz.key.isDown(viz.KEY_LEFT): view.setEuler([-TURN_SPEED*viz.elapsed(),0,0],viz.BODY_ORI,viz.REL_PARENT) #set the car to view position and body orientation car.setPosition(view.getPosition()) car.setEuler(view.getEuler(viz.BODY_ORI)) car.setPosition([3.02,-5.50,5.04],viz.REL_LOCAL) vizact.ontimer(0,updatecar) #update head of view based on mouse movements def mousemove(e): euler = view.getEuler(viz.HEAD_ORI) euler[0] += e.dx*0.1 euler[1] += -e.dy*0.1 euler[1] = viz.clamp(euler[1],-85.0,85.0) view.setEuler(euler,viz.HEAD_ORI) viz.callback(viz.MOUSE_MOVE_EVENT,mousemove) viz.mouse(viz.OFF) viz.mouse.setVisible(False) vizact.onmousedown(viz.MOUSEBUTTON_LEFT,view.reset,viz.HEAD_ORI) vizact.onmousedown(viz.MOUSEBUTTON_RIGHT,view.reset, viz.BODY_ORI |viz.HEAD_POS) vizact.onmousedown(viz.MOUSEBUTTON_RIGHT,updatecar)
def init(): """Code for one time initialization routine.""" # add grabber tools based on proxy tools for proxyWrapper in vizconnect.getToolsWithMode('Proxy'): grabberTool = tools.grabber.HandGrabber( usingPhysics=False, usingSprings=False, placementMode=tools.placer.MODE_DROP_DOWN) name = 'grabber_tool_based_on_' + proxyWrapper.getName() grabberWrapper = vizconnect.addTool(raw=grabberTool, name=name, make='Virtual', model='Grabber') # parent the grabber wrapper to the proxy's parent grabberWrapper.setParent(proxyWrapper) grabberTool.setItems(grabbableItems) viz.callback(viz.getEventID('RESET_THE_LOFT_LAYOUT'), lambda e: resetMovedObjects())
def setAsMain(self): # self.VIEW_LINK.setOffset([0,self.EYE_HEIGHT,0]) self.VIEW_LINK.preTrans([0,-self.EYE_HEIGHT,0]) viz.mouse.setOverride(viz.ON) viz.fov(self.FOV) val = mathlite.getNewRange(self.joy.getSlider(),1,-1,self.MIN_SPEED,self.MAX_SPEED) self.MOVE_SPEED = val vizact.ontimer(0, self.updateView) vizact.onsensorup(self.joy, self.KEYS['reset'], self.reset) viz.callback(getExtension().SLIDER_EVENT,self.onSliderChange) def onMouseMove(e): euler = self.VIEW.getEuler() euler[0] += e.dx*0.05 euler[1] += -e.dy*0.05 euler[1] = viz.clamp(euler[1],-85.0,85.0) self.VIEW.setEuler(euler) viz.callback(viz.MOUSE_MOVE_EVENT, onMouseMove)
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;
def Init(LayoutFile=None,scale=4,speed=None,center_offset=0): """ Initialize the module. Must be called before any of the module functions can be called. Parameters: All parameters are optional. LayoutFile: <String> The name of the text file defining the map. If this parameter is provided, then the module will keep track of the subject's position in the layout and the subject will be prevented from moving through walls. This parameter must be given to use CanMoveForward and GetView. scale: <Float> The distance in meters between the center of two nodes in the environment. This is the distance that the subject will move when GoForward is called. speed: <Float> The speed that the subject will move forward in meters per second. If None, then the speed will be set to scale. center_offset: <Float> The distance in meters that the subject is separated from his axis of rotation. The axis of rotation is always the center of a node. Return Value: None. """ global __MOVEMENT_VAR, __PLAT_VAR if not speed: speed = scale __MOVEMENT_VAR = __MOVEMENT_CLASS(0,0,0,scale,speed,center_offset) viz.eyeheight(0.0) #viz.setfov(70,1) viz.mouse(viz.OFF) # don't want mouse input viz.callback(viz.TIMER_EVENT, TimerCallback) if LayoutFile: try: # use __PLAT_VAR to hold info about LayoutFile width, height, size = Navigator.getPlatDim(LayoutFile) __PLAT_VAR = Navigator.PLAT(width,height,size) __PLAT_VAR.ReadTextImage(LayoutFile) __PLAT_VAR.ComputeAllViews(100) except: __PLAT_VAR = None raise ("\n****** Error in Movement.Init ******\nUnable to initialize Plat Object with '%s'\n"%LayoutFile)
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;
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) viz.callback(viz.KEYDOWN_EVENT, mykeyboard)
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)
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')
histR = 0 global histL histL = 0 global HistBallL HistBallL = viz.add('footprint2.obj', color=viz.YELLOW, scale=[0.03,0.03,0.1], cache=viz.CACHE_NONE) HistBallL.setPosition([-0.2,targetL*scalorxx,0]) HistBallR.setEuler(180,0,0) HistBallL.alpha(0.8) # Register callback for our "connected" event. def onConnected(): print 'MotionMonitor server connected.' viz.callback(mmserver.CONNECTED_EVENT, onConnected) # Register callback for our "disconnected" event. def onDisconnected(): print 'MotionMonitor server disconnected.' # mmserver.waitForConnection(IP_PORT) # NOTE: if we want the server to be available for another connection after being disconnected, enable this line viz.callback(mmserver.DISCONNECTED_EVENT, onDisconnected) # Register callback for our "calibration file generated" event. #def onCalibrationFileGenerated(calibrationFileName): # print 'Calibration file generated.' # import pickle # with open(calibrationFileName, 'rb') as file: # data = pickle.load(file) # load the data from the calibration file # animator.setCalibrationData(data) # send the calibration data to the animator module... this should make the avatar's segments snap into their correct positions #viz.callback(mmserver.CALIBRATION_FILE_GENERATED_EVENT, onCalibrationFileGenerated)
body.getPosition()).strip('[]') + ',' + str( body.getEuler()).strip('[]') + ',' + str( tracker.getPosition()).strip('[]') FrameNo += 1 record.write(data + '\n') yield viztask.waitTime(1 / 120) def onNetwork(e): msg = str(e.data) info.setText(msg) if msg[2] == 'B': global recording print msg recording = viztask.schedule(writing(msg[2:-3].replace(' ', '_', 3))) elif msg[2] == 'R': try: recording.kill() except NameError: pass viz.callback(viz.NETWORK_EVENT, onNetwork) def keyInstruc(key): if key == 's' or key == 'S': myNetwork.send(message='start') viz.callback(viz.KEYDOWN_EVENT, keyInstruc)
def runSetOfTrials(): global data global collided global positionList global hitPosition collided = False viz.callback( viz.COLLIDE_BEGIN_EVENT, onCollide ) positions = createPositions() move = vizact.ontimer(0, UpdateMovement) variances = [] accuracys = [] for i in positions: data = "" positionList = [] logger.newTrial() environment.point.setPosition(0,parameters.point_height,0) if i == 0: [x,z] = polar2cartesian(parameters.radialCoordinate, parameters.angularCoordinate1) elif i == 1: [x,z] = polar2cartesian(parameters.radialCoordinate, parameters.angularCoordinate2) elif i == 2: [x,z] = polar2cartesian(parameters.radialCoordinate, parameters.angularCoordinate3) elif i == 3: [x,z] = polar2cartesian(parameters.radialCoordinate, parameters.angularCoordinate4) print [x,z] environment.goal.setPosition(x, parameters.goal_height,z) data += ( "\nGoal Position: " + str(environment.goal.getPosition())) #enable joystick movement environment.point.visible(viz.ON) environment.goal.visible(viz.ON) if parameters.dreiDEnvironment: environment.shadow.visible(viz.ON) if (parameters.training or parameters.intro): environment.arrow.visible(viz.ON) environment.thrust.disable() move.setEnabled(viz.ON) #wait till key is pressed let object fall down yield s.wait() if parameters.dreiDEnvironment: environment.shadow.visible(viz.OFF) dropPosition = environment.point.getPosition() data += ('\nDrop Position: ' + str(dropPosition)) move.setEnabled(viz.OFF) #set force on the point + no gravity [x,z] = windSpeed.computeWindForce(environment.point.getPosition()) if parameters.dreiDEnvironment: environment.thrust.setForce([x,parameters.gravity,z]) else: environment.thrust.setForce([x,0,z]) environment.thrust.enable(); #print(environment.point.getPosition()) yield viztask.waitTime(1) #show fallen object environment.thrust.disable() environment.point.setVelocity([0,0,0]) yield viztask.waitTime(1) #save hit position use global hit position if 3D based on collision or get last position of point in 2d if not parameters.dreiDEnvironment: hitPosition = environment.point.getPosition() data+= '\nHit Position: ' + str(hitPosition) #compute statistics accuracy = statistics.computeAccuracy(hitPosition, environment.goal.getPosition()) variance = statistics.computeVariance(dropPosition, positionList) data+= '\nAccuracy: ' + str(accuracy) data+= '\nVariance: ' + str(variance) #make point invisible wait and start next trial environment.point.visible(viz.OFF) environment.goal.visible(viz.OFF) if (parameters.training or parameters.intro): environment.arrow.visible(viz.OFF) yield viztask.waitTime(1) parameters.trialNumber+= 1 data+= "\n" + str(positionList) logger.write_logger(data) accuracys.append(accuracy) variances.append(variance) viztask.returnValue([variances,accuracys,positions.__len__()])
from msvcrt import getch import viz viz.go() def onKeyDown(key): print key, ' is down.' if key == viz.KEY_TAB: print 'you hit the tab key' #Register the callback which to call the 'onKeyDown' function. viz.callback(viz.KEYDOWN_EVENT, onKeyDown)
def pointerInput(mode, pointer, arena): viz.phys.enable() """ Initialize the pointer tool Mode selection: 0 - Keyboard driven 1 - Spacemouse (WARNING: potential conflict with camera mode 1) """ proxy = vizproximity.Manager() proxy.setDebug(viz.TOGGLE) # theSensor = vizproximity.addBoundingBoxSensor(arena, scale = [0.95, 0.95, 0.95]) theTarget = vizproximity.Target(pointer) # proxy.addSensor(theSensor) proxy.addTarget(theTarget) vizact.onkeydown('l',pointer.setPosition,[0,1,0]) vizact.onkeydown('l',pointer.setVelocity,[0,0,0]) vizact.onkeydown('l',pointer.setAngularVelocity,[0,0,0]) if mode == 0: # Keyboard driven pointer, in case you don't have a space mouse # wx/da/ez control #For keyboard controls the glove is only linked via orientation #linking via position was causing issues with the camera focusing feature #fixedRotation = viz.link(viz.MainView,pointer) #fixedRotation.setMask(viz.LINK_ORI) speed = 3.0 vizact.whilekeydown('w',pointer.setPosition,[0,vizact.elapsed(speed),0],viz.REL_LOCAL) vizact.whilekeydown('x',pointer.setPosition,[0,vizact.elapsed(-speed),0],viz.REL_LOCAL) vizact.whilekeydown('d',pointer.setPosition,[vizact.elapsed(speed),0,0],viz.REL_LOCAL) vizact.whilekeydown('a',pointer.setPosition,[vizact.elapsed(-speed),0,0],viz.REL_LOCAL) vizact.whilekeydown('e',pointer.setPosition,[0,0,vizact.elapsed(speed)],viz.REL_LOCAL) vizact.whilekeydown('z',pointer.setPosition,[0,0,vizact.elapsed(-speed)],viz.REL_LOCAL) elif mode == 1: # Set up pointer control with the Spacemouse connexion = viz.add('3dconnexion.dle') device = connexion.addDevice() def buttonPress(e): pointer.setPosition([0,1,0]) pointer.setVelocity([0,0,0]) pointer.setAngularVelocity([0,0,0]) viz.callback(viz.SENSOR_DOWN_EVENT,buttonPress) #call this every loop #all of this should likely go in controls, we need to fix controls!! -ADE def getCoords(source, destination, log = False): """ source should be a 3D connection device, and the destination should be a 3d node type """ while True: yield viztask.waitTime( .01 ) position = source.getRawTranslation() orientation = source.getRawRotation() #sets the velocity of the glove (destination) to zero destination.setVelocity([0,0,0], viz.ABS_GLOBAL) destination.setAngularVelocity([0,0,0] ,viz.ABS_GLOBAL) #if selected do log scale on orientation if log: config.SMEulerScale= [0.5, 0.5 , 0.5] orientation = logScale(orientation) #rescale position position = list(numpy.multiply(position,config.SMPositionScale)) orientation = list(numpy.multiply(orientation,config.SMEulerScale)) #invert signs of x and z x,y,z = position #invert signs of x and z rotations, and exchange b and a a,b,g = orientation orientation = [b,a,g] destination.setPosition(position, viz.REL_PARENT) destination.setEuler(orientation, viz.REL_PARENT) #schedule controller loop with viztask scheduler viztask.schedule(getCoords(device, pointer)) return device else: raise ValueError('Invaid control mode selection')
# 02 05 End Trial: Close out the trial and reset values for next trial elif trial_stage == 'endtrial_02_05': # Clears the target pole leader.visible(viz.OFF) # End data collection for this trial data_collect = False # save the data of this trial fileName = OUTPUT_DIR + NICKNAME + '_subj' + subject + '_trial' + str(trial_num).zfill(3) + '_' + condition + '.csv' with open(fileName, 'a') as file: file.write(data_batch) print 'End Trial ' + str(trial_num) # When trial_num is greater than TOTAL_TRIALS, end experiment if trial_num == TOTAL_TRIALS: is_freewalk = True goToStage('pretrial_00_01') trial_num = 1 # Returns to Stage 1, resets clock else: trial_num += 1 goToStage('pretrial_02_01') # Restarts the loop, at a rate of 60Hz viz.callback(viz.TIMER_EVENT,masterLoop) viz.starttimer(0,1.0/HZ,viz.FOREVER)
viz.MainView.setEuler(0, 90, 0) def onTimer(num): #Use the time ids to identify the timer. move_speed = 5 if viz.MainWindow.isCulled(gplane1): print "gplane1 culled" gplane1.setPosition(0, 0, texture_z_size * 2, viz.REL_GLOBAL) #bring to driver pos if viz.MainWindow.isCulled(gplane2): print "gplane2 culled" gplane2.setPosition(0, 0, texture_z_size * 2, viz.REL_GLOBAL) #bring to driver pos if viz.key.isDown(viz.KEY_UP): viz.MainView.move([0, 0, move_speed * viz.elapsed()], viz.BODY_ORI) elif viz.key.isDown(viz.KEY_DOWN): viz.MainView.move([0, 0, move_speed * viz.elapsed()], viz.BODY_ORI) #Register the timer callback. viz.callback(viz.TIMER_EVENT, onTimer) #Start both timers. #The first will be repeated. viz.starttimer(0, 1 / 60.0, viz.PERPETUAL)
tool = grabber.Grabber(usingPhysics=usingPhysics, usingSprings=usingPhysics, highlightMode=highlighter.MODE_OUTLINE) tool.setItems([soccerball,basketball,volleyball]) # update code for grabber def updateGrabber(tool): state = viz.mouse.getState() if state & viz. MOUSEBUTTON_LEFT: tool.grabAndHold() tool.setUpdateFunction(updateGrabber) #Link the grabber to an arrow in order to #visualize it's position from vizconnect.util import virtual_trackers mouseTracker = virtual_trackers.ScrollWheel(followMouse = True) mouseTracker.distance = 1.4 arrow = vizshape.addArrow(length=0.2,color=viz.BLUE) arrowLink = viz.link(mouseTracker,arrow) arrowLink.postMultLinkable(viz.MainView) viz.link(arrowLink,tool) spin = vizact.spin(0,1,0,30,2) #Add a spin action to the ball when its released def onRelease(e): e.released.runAction(spin) viz.callback(grabber.RELEASE_EVENT,onRelease) #Disable mouse navigation and hide the mouse curser viz.mouse(viz.OFF) viz.mouse.setVisible(viz.OFF)
def use_control(self, control_style): """ Enable the control modality depending on the provided input modality. Different experimental setup make use of different ways to exert control over the experimental world. Use this function to define and setup the necessary things depending on the control modality to be used. Args: control_style: interaction possibilities between subject and VR world. Currently supports: 'mouse and keyboard', 'joystick', 'wiimote with dk2 head', 'dk2 head only', 'dk2 head hands' """ # control type for test purposes if control_style == 'mouse and keyboard': # control type for test purposes viz.mouse(viz.ON) vizact.onmousedown(viz.MOUSEBUTTON_LEFT, self.on_button_press, 'A') vizact.onmousedown(viz.MOUSEBUTTON_RIGHT, self.on_button_press, 'B') self.sphere_radius = 0.02 self.right_hand_sphere = vizshape.addSphere(radius=self.sphere_radius) self.right_hand_sphere.color(viz.GREEN) self.right_hand_target = self.right_hand_sphere.collideSphere() self.right_hand_sphere.disable(viz.DYNAMICS) self.right_hand_sphere.alpha(1) self.head_sphere = vizshape.addSphere(radius=self.sphere_radius) self.head_sphere.color(viz.YELLOW) self.head_target = self.head_sphere.collideSphere() self.head_sphere.disable(viz.DYNAMICS) MOVE_SPEED = 0.025 def move_hand(): if viz.key.isDown(viz.KEY_UP): self.right_hand_sphere.setPosition([self.right_hand_sphere.getPosition()[0], 1.6, self.right_hand_sphere.getPosition()[2]+MOVE_SPEED]) elif viz.key.isDown(viz.KEY_DOWN): self.right_hand_sphere.setPosition([self.right_hand_sphere.getPosition()[0], 1.6, self.right_hand_sphere.getPosition()[2]-MOVE_SPEED]) elif viz.key.isDown(viz.KEY_LEFT): self.right_hand_sphere.setPosition(self.right_hand_sphere.getPosition()[0]-MOVE_SPEED, 1.6, self.right_hand_sphere.getPosition()[2]) elif viz.key.isDown(viz.KEY_RIGHT): self.right_hand_sphere.setPosition(self.right_hand_sphere.getPosition()[0]+MOVE_SPEED, 1.6, self.right_hand_sphere.getPosition()[2]) def move_head(): if viz.key.isDown('w'): self.head_sphere.setPosition([self.head_sphere.getPosition()[0], 1.6, self.head_sphere.getPosition()[2]+MOVE_SPEED]) elif viz.key.isDown('s'): self.head_sphere.setPosition([self.head_sphere.getPosition()[0], 1.6, self.head_sphere.getPosition()[2]-MOVE_SPEED]) elif viz.key.isDown('a'): self.head_sphere.setPosition(self.head_sphere.getPosition()[0]-MOVE_SPEED, 1.6, self.head_sphere.getPosition()[2]) elif viz.key.isDown('d'): self.head_sphere.setPosition(self.head_sphere.getPosition()[0]+MOVE_SPEED, 1.6, self.head_sphere.getPosition()[2]) vizact.ontimer(0, move_hand) vizact.ontimer(0, move_head) elif control_style == 'joystick': # first load the oculus rift plugin and link sensor to viewpoint import oculus hmd = oculus.Rift() # loads the DirectInput plug-in and adds first available joystick dinput = viz.add('DirectInput.dle') self.joy = dinput.addJoystick() # Set dead zone threshold so small movements of joystick are ignored self.joy.setDeadZone(0.2) # add viewpoint at subject height eye_height = float(self._height) - 0.05 joystick_node = viz.addGroup(pos=(0, eye_height, 0)) viz.link(joystick_node, viz.MainView) # joystick control class with lsl streams of pos and ori as in the dk2 tracker class # stream pos and ori in joystick movement function which gets called with ontimer / onupdate # set lsl stream parameters lsl_streamName = 'vizard_hmd6dof_stateLog_joystick' lsl_streamType = 'sixFloat' # no official lsl type (not recognized by eeglab or mobilab) lsl_numChannels = 6 lsl_regularSPS = 75 # regular rate, one sample per DK2 frame lsl_dataType = 'float32' lsl_streamUuid = socket.gethostname() # PC name as uuid # create stream lsl_hmd6dofStreamInfo = StreamInfo(lsl_streamName, lsl_streamType, lsl_numChannels, lsl_regularSPS, lsl_dataType, lsl_streamUuid) lsl_hmd6dofStreamInfo.desc().append_child('synchronization').append_child_value('can_drop_samples', 'true') lsl_hmd6dofOutlet = StreamOutlet(lsl_hmd6dofStreamInfo) viz.callback(viz.SENSOR_DOWN_EVENT, self.on_button_press) vizact.onupdate(0, self.update_joystick_movement, self.joy, joystick_node, 5, 90, lsl_hmd6dofOutlet) else: self.start_dk2_head_tracker(control_style)
def CloseConnections(EYETRACKING): """Shuts down EYETRACKING and wheel threads then quits viz""" print("Closing connections") if EYETRACKING: comms.stop_trial() #closes recording #kill automation viz.quit() if __name__ == '__main__': ###### SET EXPERIMENT OPTIONS ###### EYETRACKING = True PRACTICE = True TILING = True #to reduce memory load set True to create two groundplane tiles that dynamically follow the driver's position instead of one massive groundplane. EXP_ID = "BenLui17" if PRACTICE == True: # HACK EYETRACKING = False ParticipantNumber = viz.input('Enter participant number') #cmg edit myExp = myExperiment( EYETRACKING, PRACTICE, TILING, EXP_ID, ppid=ParticipantNumber) #initialises a myExperiment class viz.callback(viz.EXIT_EVENT, CloseConnections, myExp.EYETRACKING) viztask.schedule(myExp.runtrials())
def pointerInput(mode, pointer, arena): viz.phys.enable() """ Initialize the pointer tool Mode selection: 0 - Keyboard driven 1 - Spacemouse (WARNING: potential conflict with camera mode 1) """ proxy = vizproximity.Manager() proxy.setDebug(viz.TOGGLE) theSensor = vizproximity.addBoundingBoxSensor(arena, scale=[.95, .95, .95]) theTarget = vizproximity.Target(pointer) proxy.addSensor(theSensor) proxy.addTarget(theTarget) def EnterProximity(e): #print('Hit the wall') pointer.setVelocity([0, 0, 0]) pointer.setAngularVelocity([0, 0, 0]) print(e.target.getPosition()) temp = e.target.getPosition() #pointer.setPosition([1,1,1]) def ExitProximity(e): #print('Hit the wall') x, y, z = pointer.getPosition() if (y < .4): y = .5 elif (y > 4.5): y = 4.4 if (abs(x) > abs(z) and abs(x) > 5): if (x < 0): x = -4.9 else: x = 4.9 elif (abs(z) > 4): if (z < 0): z = -3.9 elif (z > 0): z = 3.9 pointer.setPosition(x, y, z) pointer.setVelocity([0, 0, 0]) pointer.setAngularVelocity([0, 0, 0]) proxy.onEnter(None, EnterProximity) proxy.onExit(None, ExitProximity) vizact.onkeydown('l', pointer.setPosition, [0, 1, 0]) vizact.onkeydown('l', pointer.setVelocity, [0, 0, 0]) vizact.onkeydown('l', pointer.setAngularVelocity, [0, 0, 0]) if mode == 0: # Keyboard driven pointer, in case you don't have a space mouse # wx/da/ez control #For keyboard controls the glove is only linked via orientation #linking via position was causing issues with the camera focusing feature #fixedRotation = viz.link(viz.MainView,pointer) #fixedRotation.setMask(viz.LINK_ORI) speed = 3.0 vizact.whilekeydown('w', pointer.setPosition, [0, vizact.elapsed(speed), 0], viz.REL_LOCAL) vizact.whilekeydown('x', pointer.setPosition, [0, vizact.elapsed(-speed), 0], viz.REL_LOCAL) vizact.whilekeydown('d', pointer.setPosition, [vizact.elapsed(speed), 0, 0], viz.REL_LOCAL) vizact.whilekeydown('a', pointer.setPosition, [vizact.elapsed(-speed), 0, 0], viz.REL_LOCAL) vizact.whilekeydown('e', pointer.setPosition, [0, 0, vizact.elapsed(speed)], viz.REL_LOCAL) vizact.whilekeydown('z', pointer.setPosition, [0, 0, vizact.elapsed(-speed)], viz.REL_LOCAL) elif mode == 1: # Set up pointer control with the Spacemouse connexion = viz.add('3dconnexion.dle') device = connexion.addDevice() def buttonPress(e): pointer.setPosition([0, 1, 0]) pointer.setVelocity([0, 0, 0]) pointer.setAngularVelocity([0, 0, 0]) viz.callback(viz.SENSOR_DOWN_EVENT, buttonPress) #device.setTranslateScale([1,1,1]) #device.setRotateScale([0,0,0]) # i don't think we need this #add 3Dnode object that follows mainview exactly, called MainViewShadow # MainViewShadow = vizshape.addSphere(radius = .5) # MainViewShadow.disable(viz.RENDERING) # viz.link(viz.MainView, MainViewShadow) #make glove () child of MainViewShadow #fixedRotation = viz.link(MainViewShadow,pointer) #fixedRotation.setMask(viz.LINK_ORI) #pointer.setParent(MainViewShadow) #call this every loop #all of this should likely go in controls, we need to fix controls!! -ADE def getCoords(source, destination): """ source should be a 3D connection device, and the destination should be a 3d node type """ def logScale(orientation): """ list or len() = 3 -> list of len 3 takes the orintation list and returns the log of the magnitude of each element , and then keeps the original sign ex) [ 10 , -10 ,1000] -> [1 , -1, 3] """ import math base = 2 mag_orientation = [] sign = [] #list of signs #make all elements positive, store original signs for element in orientation: if math.fabs(element) == element: #element is positive mag_orientation.append(element) sign.append(1) else: #element is negative mag_orientation.append(-1 * element) sign.append(-1) #handle case where number is zero, and set to 1 n = 0 for element in mag_orientation: if element == 0: mag_orientation[n] = 1 n += 1 #take log of each element log_orientation = [] for element in mag_orientation: log = math.log(element, base) log_orientation.append(log) #restablish original signs orientation = scalarMult(sign, log_orientation) return orientation #set source scale # scale1 = [.0001,.0001,.0001] # scale2 =[.01,.01,.01] #log log = False while True: yield viztask.waitTime(.01) position = source.getRawTranslation() orientation = source.getRawRotation() #sets the velocity of the glove (destination) to zero destination.setVelocity([0, 0, 0], viz.ABS_GLOBAL) destination.setAngularVelocity([0, 0, 0], viz.ABS_GLOBAL) #if selected do log scale on orientation if log == True: config.orientationVector = [.5, .5, .5] orientation = logScale(orientation) #rescale position position = scalarMult(position, config.positionVector) orientation = scalarMult(orientation, config.orientationVector) #invert signs of x and z x, y, z = position #invert signs of x and z rotations, and exchange b and a a, b, g = orientation orientation = [b, a, g] #print(orientation) destination.setPosition(position, viz.REL_PARENT) destination.setEuler(orientation, viz.REL_PARENT) def scalarMult(lst1, lst2): """ takes 2 lists, and returns the scalar multiplication of the lists *lists must be the same length """ new_lst = [] for i in range(len(lst1)): n_val = lst1[i] * lst2[i] new_lst.append(n_val) return new_lst #schedule controller loop with viztask scheduler viztask.schedule(getCoords(device, pointer)) #vizact.ontimer2(.01,1, delayedSet ) #viz.link(device, pointer, viz.REL_PARENT) #link.preEuler([0,90,0]) return device else: raise ValueError('Invaid control mode selection') #question guys. if keyboard is selected, should the init script call code #in the control module to set the functions? - Alex
import viz viz.go() # Create arrow symbol at center of screen text = viz.addText("^", parent=viz.SCREEN, pos=(0.5, 0.5, 0), align=viz.ALIGN_CENTER_CENTER) # Import our new module import mymodule # Register callback for our mouse enter event def onMouseEnter(pos): text.setEuler(0, 0, -vizmat.AngleToPoint([0.5, 0.5], pos)) text.color(viz.WHITE) viz.callback(mymodule.MOUSE_ENTER_EVENT, onMouseEnter) # Register callback for our mouse leave event def onMouseLeave(pos): text.setEuler(0, 0, -vizmat.AngleToPoint([0.5, 0.5], pos)) text.color(viz.RED) viz.callback(mymodule.MOUSE_LEAVE_EVENT, onMouseLeave)
def reset(self): print 'RESET WAS CALLED' global timerEnded timerEnded = False viz.starttimer(TIMER, self.__delay) viz.callback(viz.TIMER_EVENT,onTimer)
Swapped = True RFootLink = viz.link(Tracking[1], rFoot, offset=(0,-Tracker_Offset,0, viz.REL_PARENT))###FIX LFootLink = viz.link(Tracking[0], lFoot, offset=(0,-Tracker_Offset,0, viz.REL_PARENT)) elif Swapped == True: Swapped = False RFootLink = viz.link(Tracking[0], rFoot, offset=(0,-Tracker_Offset,0, viz.REL_PARENT))###FIX LFootLink = viz.link(Tracking[1], lFoot, offset=(0,-Tracker_Offset,0, viz.REL_PARENT)) if key == viz.KEY_ESCAPE: out.flush() out2.flush() os.fsync(out) os.fsync(out2) out.close() out2.close() viz.quit() ######################### # Register myKeyboard function with any keyboard event # Ideally this should be a keyboard up event, but this will work too! # TO DO: Look into the keyboard up events later viz.callback(viz.KEYBOARD_EVENT,myKeyboard) #~~~~~~~~~~Experiment Logic end~~~~~~~~#
global fileStartIndex fileStartIndex = (fileStartIndex + 1) % len(objects) moveObjects(fileStartIndex) #hide the objects if(key == 'h'): for x in range (len(objects)): objects[x].visible(viz.OFF) #show the objects if(key == 's'): for x in range (len(objects)): objects[x].visible(viz.ON) if(key == viz.KEY_LEFT): view.setEuler(view.getEuler()[0]-1) elif(key == viz.KEY_RIGHT): view.setEuler(view.getEuler()[0]+1) elif(key == viz.KEY_UP): view.move(0,0,0.05) elif(key == viz.KEY_DOWN): view.move(0,0,-0.05) elif(key == 'o'): objectSet = (objectSet + 1) % len(objectFiles) moveObjects(fileStartIndex) viz.callback(viz.KEYBOARD_EVENT, keyEvent)
def __init__(self, groundPlotUrl, widthInMeter, mapUrl, squaresPerMeter=1, offsetX=0, offsetY=0): self.offsetX = offsetX self.offsetY = offsetY # add map self.world = World.World() #viz.collision(True) self.station = vizfx.addChild(mapUrl) self.station.anisotropy(8) self.initSignList() # transform user position according to mapper matrix self.currentUserPosition = viz.MainView.getPosition() self.currentUserPosition[0] = self.currentUserPosition[0] self.currentUserPosition[2] = self.currentUserPosition[2] # ## Scene dynamic viz.cam.setHandler(RadARCameraHandler) viz.callback(viz.UPDATE_EVENT, self.updatePosition) viz.callback(viz.EXIT_EVENT, self.onExit) # create a matrix to detext obstacles for navigation calculaton self.mapper = Mapper(widthInMeter, squaresPerMeter) self.mapper.createMatrix(groundPlotUrl) print("Image was mapped to matrix") self.trainManager = TrainManager(self, self.station.getChild("Train")) self.trainManager.addTrains() # Add running clocks self.clock = StationClocks(self.trainManager) self.clock.loadModel(self.station) self.clock.setCurrentTime() # add people into station model self.peopleAdder = PeopleAdder(self) self.peopleAdder.addPeople() self.peopleAdder.addPeopleAtfixedPosition() self.trainManager.sendTrainByIdx(11) self.trainManager.sendTrainByIdx(10) # Necessary for navigation self.aStar = AStar() # Navigation objects self.navigationObj = viz.addChild(self.NAVIGATION_SYMBOL) self.poiObj = viz.addChild(self.POI_SYSMBOL) # Productivity item objects self.cashMachineObject = viz.addChild(self.CASH_MACHINE) self.snackMachineObject = viz.addChild(self.SNACK_MACHINE) self.postBoxObject = viz.addChild(self.POST_BOX) self.mode = self.RECOMMENDER_ABIDANCE_MODE self.navigateTo = None viz.playSound('../resources/Hauptbahnhof.wav', viz.LOOP)
def displayHeatmap(project=True): ''' - Load accumulated view textures - Add cube projector with given textures and shader converting intensities to heat map colors - Let projector affect scene - auto_update = True will set the shader uniforms automatically each frame ''' import viz import vizact import vizcam viz.setMultiSample(4) viz.go() #vizcam.WalkNavigate() if project: piazza = viz.addChild('piazza.osgb') cube_textures = { viz.POSITIVE_X: viz.addTexture('accumulated_p_x.bmp'), viz.NEGATIVE_X: viz.addTexture('accumulated_n_x.bmp'), viz.POSITIVE_Y: viz.addTexture('accumulated_p_y.bmp'), viz.NEGATIVE_Y: viz.addTexture('accumulated_n_y.bmp'), viz.POSITIVE_Z: viz.addTexture('accumulated_p_z.bmp'), viz.NEGATIVE_Z: viz.addTexture('accumulated_n_z.bmp') } heat_projector = HeatmapVisualizer(cube_textures, auto_update=True) heat_projector.setPosition(viz.MainView.getPosition()) heat_projector.affect(piazza) ## GUI for manipulation of the output heatmap i_slider = viz.addSlider() i_x = 1.0 - i_slider.getBoundingBox().width / 2.0 i_y = 0.0 + i_slider.getBoundingBox().height / 2.0 i_slider.setPosition([i_x, i_y, 0]) i_slider.set(0.5) i_text = viz.addText('intensity scale', parent=viz.SCREEN) i_text.setPosition([ i_x - i_text.getBoundingBox().width / 2 - i_slider.getBoundingBox().width / 2, 0.01, 0.0 ]) i_text.setScale([0.4, 0.4, 1.0]) def onSlider(obj, pos): if obj == i_slider: heat_projector.setIntensityScale(pos + 0.5) viz.callback(viz.SLIDER_EVENT, onSlider) else: import vizshape env = viz.addEnvironmentMap( 'accumulated.bmp', faces=['_p_x', '_n_x', '_p_y', '_n_y', '_p_z', '_n_z']) sb = vizshape.addSkyBox() sb.texture(env)
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;
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() viztask.schedule(pg.generatePaths())
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
def loadModel(self, hbf): """ Alle Uhrzeiger im Modell hier referenzieren Reihenfolge muss mit updateTime übereinstimmen """ uhr1 = [ hbf.getChild('SekundenzeigerVorn'), hbf.getChild('SekundenzeigerHinten'), hbf.getChild('MinutenzeigerVorn'), hbf.getChild('MinutenzeigerHinten'), hbf.getChild('StundenzeigerVorn'), hbf.getChild('StundenzeigerHinten')] uhr2 = [ hbf.getChild('SekundenzeigerVorn.001'), hbf.getChild('SekundenzeigerHinten.001'), hbf.getChild('MinutenzeigerVorn.001'), hbf.getChild('MinutenzeigerHinten.001'), hbf.getChild('StundenzeigerVorn.001'), hbf.getChild('StundenzeigerHinten.001')] uhr3 = [ hbf.getChild('SekundenzeigerVorn.002'), hbf.getChild('SekundenzeigerHinten.002'), hbf.getChild('MinutenzeigerVorn.002'), hbf.getChild('MinutenzeigerHinten.002'), hbf.getChild('StundenzeigerVorn.002'), hbf.getChild('StundenzeigerHinten.002')] uhr4 = [ hbf.getChild('SekundenzeigerVorn.003'), hbf.getChild('SekundenzeigerHinten.003'), hbf.getChild('MinutenzeigerVorn.003'), hbf.getChild('MinutenzeigerHinten.003'), hbf.getChild('StundenzeigerVorn.003'), hbf.getChild('StundenzeigerHinten.003')] uhr5 = [ hbf.getChild('SekundenzeigerVorn.004'), hbf.getChild('SekundenzeigerHinten.004'), hbf.getChild('MinutenzeigerVorn.004'), hbf.getChild('MinutenzeigerHinten.004'), hbf.getChild('StundenzeigerVorn.004'), hbf.getChild('StundenzeigerHinten.004')] uhr6 = [ hbf.getChild('SekundenzeigerVorn.005'), hbf.getChild('SekundenzeigerHinten.005'), hbf.getChild('MinutenzeigerVorn.005'), hbf.getChild('MinutenzeigerHinten.005'), hbf.getChild('StundenzeigerVorn.005'), hbf.getChild('StundenzeigerHinten.005')] uhr7 = [ hbf.getChild('SekundenzeigerVorn.006'), hbf.getChild('SekundenzeigerHinten.006'), hbf.getChild('MinutenzeigerVorn.006'), hbf.getChild('MinutenzeigerHinten.006'), hbf.getChild('StundenzeigerVorn.006'), hbf.getChild('StundenzeigerHinten.006')] uhr8 = [ hbf.getChild('MinutenzeigerVorn.007'), hbf.getChild('MinutenzeigerHinten.007'), hbf.getChild('SekundenzeigerVorn.007'), hbf.getChild('SekundenzeigerHinten.007'), hbf.getChild('StundenzeigerVorn.007'), hbf.getChild('StundenzeigerHinten.007')] uhr9 = [ hbf.getChild('SekundenzeigerVorn.008'), hbf.getChild('SekundenzeigerHinten.008'), hbf.getChild('MinutenzeigerVorn.008'), hbf.getChild('MinutenzeigerHinten.008'), hbf.getChild('StundenzeigerVorn.008'), hbf.getChild('StundenzeigerHinten.008')] uhr10 = [ hbf.getChild('SekundenzeigerVorn.009'), hbf.getChild('SekundenzeigerHinten.009'), hbf.getChild('MinutenzeigerVorn.009'), hbf.getChild('MinutenzeigerHinten.009'), hbf.getChild('StundenzeigerVorn.009'), hbf.getChild('StundenzeigerHinten.009')] uhr11 = [ hbf.getChild('SekundenzeigerVorn.010'), hbf.getChild('SekundenzeigerHinten.010'), hbf.getChild('MinutenzeigerVorn.010'), hbf.getChild('MinutenzeigerHinten.010'), hbf.getChild('StundenzeigerVorn.010'), hbf.getChild('StundenzeigerHinten.010')] self.uhren = [uhr1,uhr2,uhr3,uhr4,uhr5,uhr6,uhr7,uhr8,uhr9,uhr10,uhr11] viz.callback(viz.TIMER_EVENT, self.onTimer) viz.starttimer(1, 1, viz.PERPETUAL)
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)
def openAvatarRecording(participantID, controlSchema): global filePointerForAvatarData filename = 'avatarBoneData/' + participantID + '_' + str(controlSchema) + '_avatarBoneData' + '.dat' filePointerForAvatarData = data_recording.openFileForRecordingData(filename, 'w') viz.callback(viz.TIMER_EVENT, onTimer)
import vizact wii1 = wiiObj() vizact.onsensordown(wii1.wiimote,wii.BUTTON_B,counter.targetDetected) ############################################################################################################################################################################### ############################################################################################################################################################################### ############################################################################################################################################################################### networkingOn = True; if networkingOn : netClient = viz.addNetwork('performLabVR2') else: counter.startPresentingNumbers() def onNetwork(packet): print 'Received network message: ' + packet.message if( packet.message == 'start' ): counter.startPresentingNumbers() elif( packet.message == 'stop' ): counter.stopPresentingNumbers() viz.callback(viz.NETWORK_EVENT, onNetwork)
print('Running Visualization Code ...\n\n\n') print('Attach View to Head = ', room.attachViewPortToHead) print('Save Images for RL = ', room.saveImagesForRL) print('Save Images for Data Set = ', room.saveImagesForDataSet) print('Ball Disappears = ', room.includeBlankDuration, '\n') if (room.attachViewPortToHead == False): #sets where the camera view is located #viz.MainView.setPosition([-0.46132529973983765, 1.8138036012649536, -1.4800882935523987]) viz.MainView.setPosition( [0.27629128098487854, 1.9876298904418945, -3.3362717628479004]) viz.MainView.setEuler([-18.816675186157227, 0.0, 0.0]) #viz.MainView.setPosition([-1.8827998638153076, 2.381239414215088, 0.05993637815117836]) #sets the angle at which the camera view is pointed viz.MainView.setEuler(3.1846203804016113, -0.0, 0.0) #lEyeOffsetMatrix = np.array([[1, 0, 0, -0.03],[0, 1, 0, 0], [0, 0, 1, 0],[0, 0, 0, 1]], dtype = float) #lEyeRotationMatrix = np.eye(4, dtype = float); #counter = 1 #FrameNumber = TrialStartIndex[0] - 100; #FrameNumber = 1; #SetRotationAngle(1.6); #if the timer goes off go to the onTimer function value = np.array(room.rawDataFrame.viewPos.values[0]) value = value + np.array([0.4, -1.4, 0]) #print('First Value',value) room.male.setPosition(value[0], value[1], value[2]) # - np.array([0,-1.5,0])) viz.callback(viz.KEYDOWN_EVENT, keyDown) viz.callback(viz.TIMER_EVENT, onTimer) viz.starttimer(1, TimeInterval, viz.FOREVER)
vizact.moveTo((0, 2.2, 2), speed=0.03), viz.FOREVER)) text3D.setThickness(0.001) def myTask(): sound = viz.addAudio('sound/samplerButton.wav') sound.play() fadeout = vizact.fadeTo(0, time=2) yield text3D.addAction(fadeout) yield text3D.disable(True) yield grid.addAction(fadeout) yield viztask.waitTime(3) # ここでGLNAGANOのロゴ表示 import opning yield opning.Logo() yield viztask.waitTime(10) import promothion promothion def mykeyboard(whichKey): if whichKey == viz.KEY_RETURN: text3D.endAction() viztask.schedule(myTask()) viz.callback(viz.KEYDOWN_EVENT, mykeyboard)