def launch_panda_window(panda_widget, size) : """ Configure and create Panda window Connect to the gtk widget resize event Load a panda """ props = WindowProperties().getDefault() props.setOrigin(0, 0) props.setSize(*size) props.setParentWindow(panda_widget.window.xid) base.openDefaultWindow(props=props) # == panda_widget.connect("size_allocate", resize_panda_window) # == panda = loader.loadModel("panda") panda.reparentTo(render) panda.setPos(0, 40, -5) pl = render.attachNewNode( PointLight( "redPointLight" ) ) pl.node().setColor( Vec4( .9, .8, .8, 1 ) ) render.setLight(pl) pl.node().setAttenuation( Vec3( 0, 0, 0.05 ) ) slight = Spotlight('slight') slight.setColor(VBase4(1, 1, 1, 1)) lens = PerspectiveLens() slight.setLens(lens) slnp = render.attachNewNode(slight) slnp.setPos(2, 20, 0) mid = PandaNode('mid') panda.attachNewNode(mid) # slnp.lookAt(mid) render.setLight(slnp)
def __create_spot_light(self, lightId, lightColor, lightPos, targetId, shadow = True): spotLight = Spotlight(lightId) spotLight.setColor(lightColor) spotLight.setLens(PerspectiveLens()) spotLight.setShadowCaster(shadow) spotLightNP = NodePath(spotLight) spotLightNP.setPos(lightPos) if isinstance(targetId, list) is True: spotLightNP.lookAt(self.__sceneMgr.get_res(targetId[0])) else: spotLightNP.lookAt(self.__sceneMgr.get_res(targetId)) if self.__targetMap.has_key(lightId) is False: self.__targetMap[lightId] = [] self.__targetMap[lightId].append(targetId) return spotLightNP
def setupLights(self): panda = self.app.panda panda.setBackgroundColor(.9, .9, .9, 1) panda.render.clearLight() keylight = Spotlight('keylight') keylight.setLens(PerspectiveLens()) np = self._insertLight( keylight, colour=(1, 1, 1, 1), pos=(0, -5, 2), ) np.lookAt((0, 0, 0.9)) # Turn off shadows until we have fix for # https://bugs.launchpad.net/panda3d/+bug/1212752 # keylight.setShadowCaster(True, 512, 512) sunlight = PointLight('sunlight') self._insertLight( sunlight, colour=(1, 1, 1, 1), pos=(1, -2, 20), ) self._insertLight( AmbientLight('ambientLight'), colour=(.25, .25, .25, 1), )
def addLight(self, id, parent, attenuation, position, color, specular, stroboscopic, spot, lookat): if spot: slight = Spotlight(id) slight.setColor(VBase4(1, 1, 1, 1)) lens = PerspectiveLens() slight.setLens(lens) light = render.attachNewNode(slight) light.setPos(LVector3(position[0], position[1], position[2])) if lookat == None: light.lookAt(parent) else: light.lookAt(render.find("**/" + lookat)) else: light = parent.attachNewNode(PointLight(id)) light.node().setAttenuation(attenuation) light.setPos(LVector3(position[0], position[1], position[2])) light.node().setColor(color) light.node().setSpecularColor(specular) render.setLight(light) self.light_elements[id] = light if stroboscopic: self.stroboscopic_lights.append(id) if id: self.nodes_by_id[id] = light return light
class SpotLight: """Creates a simple spot light""" def __init__(self, manager, xml): self.light = PSpotLight('slight') lens = PerspectiveLens() self.light.setLens(lens) self.lightNode = render.attachNewNode(self.light) self.reload(manager, xml) def reload(self, manager, xml): color = xml.find('color') if color != None: self.light.setColor( VBase4(float(color.get('r')), float(color.get('g')), float(color.get('b')), 1.0)) pos = xml.find('pos') if pos != None: self.lightNode.setPos(render, float(pos.get('x')), float(pos.get('y')), float(pos.get('z'))) lookAt = xml.find('lookAt') if lookAt != None: self.lightNode.lookAt(render, float(lookAt.get('x')), float(lookAt.get('y')), float(lookAt.get('z'))) def start(self): render.setLight(self.lightNode) def stop(self): render.clearLight(self.lightNode)
def addLight(self, id, parent, attenuation, position, color, specular, stroboscopic, spot, lookat): if spot: slight = Spotlight(id) slight.setColor(VBase4(1, 1, 1, 1)) lens = PerspectiveLens() slight.setLens(lens) light = render.attachNewNode(slight) light.setPos(LVector3(position[0], position[1], position[2])) if lookat == None: light.lookAt(parent) else: light.lookAt(render.find("**/"+lookat)) else: light = parent.attachNewNode(PointLight(id)) light.node().setAttenuation(attenuation) light.setPos(LVector3(position[0], position[1], position[2])) light.node().setColor(color) light.node().setSpecularColor(specular) render.setLight(light) self.light_elements[id] = light if stroboscopic: self.stroboscopic_lights.append(id) if id: self.nodes_by_id[id] = light return light
def __init__(self): ShowBase.__init__(self) ambLight = AmbientLight("ambient") ambLight.setColor(Vec4(0.1,0.11,0.12,1.0)) ambNode = render.attachNewNode(ambLight) render.setLight(ambNode) dirLight = DirectionalLight("directional") dirLight.setColor(Vec4(0.7,0.7,0.68,1.0)) dirNode = render.attachNewNode(dirLight) dirNode.setHpr(60,-40,90) render.setLight(dirNode) sptLight = Spotlight("spot") sptLens = PerspectiveLens() sptLight.setLens(sptLens) sptLight.setColor(Vec4(0.6,0.6,0.6,1.0)) sptLight.setShadowCaster(True) sptNode = render.attachNewNode(sptLight) sptNode.setPos(0,0,20) sptNode.lookAt(0,0,0) render.setLight(sptNode) render.setShaderAuto() base.camLens.setFov(70) base.camLens.setNear(0.1) base.camLens.setFar(50) self.cam.setPos(-1,-4,4) self.cam.lookAt(0,-1,1)
def __init__(self, _base): self.game = _base # Player object self.playerObject = self.game.meotech.engine.GameObjects["player"] # Attach the flashlight cone to the player (self, _height, _radius, _pos, _hpr) self.flashlightConeBody = self.game.meotech.engine.factory.basePhysics.buildConeShape(10.0, 1.5, self.playerObject.bulletBody.getPos(), self.playerObject.bulletBody.getHpr()) # Attach the flashlight model to the player self.flashlight = loader.loadModel("game/models/flashlight") self.flashlight.setScale(0.2) self.flashlight.reparentTo(self.flashlightConeBody) # Attach the light to the flashlight model slight = Spotlight('slight') slight.setColor(VBase4(1, 1, 1, 1)) lens = PerspectiveLens() lens.setFar(25) lens.setFov(40, 40) slight.setLens(lens) slight.setShadowCaster(True, 512, 512) self.flashlightLight = render.attachNewNode(slight) self.flashlightLight.reparentTo(self.flashlight.find("LightPos")) render.setLight(self.flashlightLight) self.flashlightConeBody.reparentTo(self.playerObject.bulletBody) self.flashlightConeBody.setPos(base.cam.getPos())
def _set_general_lights(self, train_np): """Set initial Sun lights. Args: train_np (panda3d.core.NodePath): Train node. Returns: panda3d.core.AmbientLight: Sun ambient light. panda3d.core.DirectionalLight: Sun directional light. panda3d.core.NodePath: NodePath of the Sun. """ amb_light = AmbientLight("sun_amb") amb_light.setColor(self._color["amb"]) render.setLight(render.attachNewNode(amb_light)) # noqa: F821 lens = PerspectiveLens() lens.setNearFar(1, 100) lens.setFov(20, 20) sun_light = Spotlight("sun_dir") sun_light.setColor(self._color["dir"]) sun_light.setShadowCaster(True, 8192, 8192, sort=-2000) sun_light.setLens(lens) sun_light.setExponent(0.5) sun_light.setCameraMask(0b0001) sun_np = train_np.attachNewNode(sun_light) render.setLight(sun_np) # noqa: F821 return amb_light, sun_light, sun_np
def setupLights(self): """Setup extrnal lights""" # ambient light alight = AmbientLight('alight') alight.setColor((0.2, 0.2, 0.2, 1)) alnp = self.render.attachNewNode(alight) self.render.setLight(alnp) # directional light dlight = DirectionalLight('dlight') dlight.setColor((0.8, 0.8, 0.5, 1)) lens = PerspectiveLens() lens.setNearFar(1, 5) dlight.setLens(lens) dlight.setShadowCaster(True, args.shadow_resolution, args.shadow_resolution) dlnp = self.render.attachNewNode(dlight) dlnp.setPos(2, -2, 3) dlnp.lookAt(0, 0, 0) self.render.setLight(dlnp) # spotlight slight = Spotlight('slight') slight.setColor((0.7, 0.7, 1.0, 1)) lens = PerspectiveLens() lens.setNearFar(1, 5) slight.setLens(lens) slight.setShadowCaster(True, args.shadow_resolution, args.shadow_resolution) slnp = self.render.attachNewNode(slight) slnp.setPos(1, 1, 2) slnp.lookAt(0, 0, 0) self.render.setLight(slnp)
def launch_panda_window(panda_widget, size): """ Configure and create Panda window Connect to the gtk widget resize event Load a panda """ props = WindowProperties().getDefault() props.setOrigin(0, 0) props.setSize(*size) props.setParentWindow(panda_widget.window.xid) base.openDefaultWindow(props=props) # == panda_widget.connect("size_allocate", resize_panda_window) # == panda = loader.loadModel("panda") panda.reparentTo(render) panda.setPos(0, 40, -5) pl = render.attachNewNode(PointLight("redPointLight")) pl.node().setColor(Vec4(.9, .8, .8, 1)) render.setLight(pl) pl.node().setAttenuation(Vec3(0, 0, 0.05)) slight = Spotlight('slight') slight.setColor(VBase4(1, 1, 1, 1)) lens = PerspectiveLens() slight.setLens(lens) slnp = render.attachNewNode(slight) slnp.setPos(2, 20, 0) mid = PandaNode('mid') panda.attachNewNode(mid) # slnp.lookAt(mid) render.setLight(slnp)
def initLights(self): torches = self.level.findAllMatches("**/TorchTop*") self.lights = [] for torch in torches: tLight = PointLight(torch.getName()) tLight.setColor((.4, .2, .0, 1)) tlnp = render.attachNewNode(tLight) tlnp.setPos(torch.getPos(render)) render.setLight(tlnp) self.lights.append(tlnp) windows = self.level.findAllMatches("**/Window*") plates = self.level.findAllMatches("**/Plate*") spikes = self.level.findAllMatches("**/Spikes*") for window in windows: wLight = Spotlight(window.getName()) lens = PerspectiveLens() wLight.setLens(lens) wLight.setColor((0.5, 0.4, 0.5, 1)) wlnp = render.attachNewNode(wLight) wlnp.setPos(window.getPos(render)) wlnp.lookAt((0, window.getY(), 0)) for plate in plates: plate.setLight(wlnp) self.lights.append(wlnp) ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.1, .1, .025, 1)) render.setLight(render.attachNewNode(ambientLight))
def initLights(self): # Create some lighting #self.environ.ls() #print(self.environ.findAllMatches("**/Spot")) ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(0.8, 0.8, 0.8, 0.65)) """ directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-10, -10, 5)) directionalLight.showFrustum() directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) dirnp = render.attachNewNode(directionalLight) dirnp.setPos(10, 0, 6) """ plight1 = PointLight('plight1') plight1.setColor(VBase4(1, 1, 1, 1)) plight1.showFrustum() #plight1.setShadowCaster(True) plnp1 = render.attachNewNode(plight1) plnp1.setPos(26.71, -33.2, 26) plight2 = PointLight('plight2') plight2.setColor(VBase4(1, 1, 1, 1)) plight2.showFrustum() plnp2 = render.attachNewNode(plight2) plnp2.setPos(-25, 25, 25) slight = Spotlight('slight') slight.setColor(VBase4(1, 1, 1, 1)) lens = PerspectiveLens() lens.setFilmSize(1, 1) # Or whatever is appropriate for your scene slight.setLens(lens) slight.setShadowCaster(True, 512, 512) slight.showFrustum() slnp = render.attachNewNode(slight) slnp.setPos(0, 0, 100) slnp.lookAt(Vec3(0,0,0)) render.setLight(slnp) render.setLight(plnp1) render.setLight(plnp2) #render.setLight(render.attachNewNode(ambientLight)) #render.setLight(dirnp) render.setShaderAuto() #render.setLight(render.attachNewNode(directionalLight)) """
def __init__(self): ShowBase.__init__(self) #setting background self.environ = self.loader.loadModel("models/world") #Reparent the model to render #self.environ.reparentTo(self.render) #Apply scale and position transforms on the model self.environ.setScale(1000, 1000, 1000) self.environ.setPos(0, 0, 0) self.gameTask = taskMgr.add(self.gameLoop, "gameLoop") base.disableMouse() base.camera.setPos(0, -300, 100) base.camera.lookAt(0, 0, 0) slight = Spotlight('slight') slight.setColor(VBase4(1, 1, 1, 1)) lens = PerspectiveLens() slight.setLens(lens) self.shipList = [ Xwing("xwing1"), # Ywing("ywing1"), # Awing("awing1")#, # Bwing("bwing1"), # TieFighter("tiefighter1"), # TieInterceptor("tieinterceptor1") ] lightColors = [ Vec4(0.9, 0.9, 0.9, 1), Vec4(1, 1, 0, 1), Vec4(1, 0, 0, 1), Vec4(0, 0, 1, 1), Vec4(0.4, 0.4, 0.4, 1), Vec4(0.1, 0.1, 0.1, 1) ] for i, ship in enumerate(self.shipList): ship.reparentTo(render) ship.setPos(Point3(i * 10, 0, 0)) directionalLight = DirectionalLight('directionalLight') directionalLight.setColor(lightColors[i]) directionalLightNP = render.attachNewNode(directionalLight) directionalLightNP.setHpr(180, -20, 0) ship.setLight(directionalLightNP) self.count = 0 self.fire = False
def setup_spot_light(self, x, y, z): slight = Spotlight('slight') slight.setColor(VBase4(1, 1, 1, 1)) lens = self.base.camLens slight.setLens(lens) light = self.base.render.attachNewNode(slight) light.setPos(x, y, z) light.lookAt(0, 0, 0) self.direct_light.append(light) self.base.render.setLight(light)
def __setSpotlight(self,props): light = Spotlight(props['name']) light.setShadowCaster(props['castShadows'],2048,2048) light.setAttenuation(props['attenuation']) lens = PerspectiveLens() fov = math.degrees( props['range'].x ) lens.setFov(fov) lens.setFilmSize(5096); light.setLens(lens) return self.__createLight(light,props)
def __setSpotlight(self, props): light = Spotlight(props['name']) light.setShadowCaster(props['castShadows'], 2048, 2048) light.setAttenuation(props['attenuation']) lens = PerspectiveLens() fov = math.degrees(props['range'].x) lens.setFov(fov) lens.setFilmSize(5096) light.setLens(lens) return self.__createLight(light, props)
def buildSubType(self): """Build the light with the given subType""" if self.subType == "pointType": # make a point light c = self.color pointLight = PointLight(self.name) pointLight.setColor(VBase4(c[0], c[1], c[2], c[3])) pointLight.setShadowCaster(True, 512, 512) plnp = self.renderObjectsLight.attachNewNode(pointLight) plnp.setPos(self.position) self.lightNP = plnp self.setLightSwitch(True) if self.subType == "directType": # make a directional light c = self.color directLight = DirectionalLight(self.name) directLight.setColor(VBase4(c[0], c[1], c[2], c[3])) directLight.setShadowCaster(True, 512, 512) dlnp = self.renderObjectsLight.attachNewNode(directLight) #dlnp.setHpr(0, -60, 0) # no idea why its like that.. but it works self.lightNP = dlnp self.setLightSwitch(True) if self.subType == "ambientType": # make a ambient light c = self.color ambientLight = AmbientLight(self.name) ambientLight.setColor(VBase4(c[0], c[1],c[2], c[3])) alnp = self.renderObjectsLight.attachNewNode(ambientLight) self.lightNP = alnp self.setLightSwitch(True) if self.subType == "spotType": # make a spot light # lookAtObj = _object.getTag("lookAt") get rid of this. c = self.color spotLight = Spotlight(self.name) spotLight.setColor(VBase4(c[0], c[1], c[2], c[3])) spotLight.setShadowCaster(True, 512, 512) lens = PerspectiveLens() spotLight.setLens(lens) slnp = self.renderObjectsLight.attachNewNode(spotLight) slnp.setPos(self.position) slnp.setHpr(self.hpr) # Find out if this is really the only option # because setHpr doesnt seem to have any effect. # lookAt would be okay but that means adding anothe type #slnp.lookAt(self.main.GameObjects["player"].collisionBody) self.lightNP = slnp self.setLightSwitch(True)
def __init__(self): self.testTexture = loader.loadTexture("maps/envir-reeds.png") self.accept("1", self.toggleTex) self.accept("2", self.toggleLightsSide) self.accept("3", self.toggleLightsUp) self.LightsOn = False self.LightsOn1 = False slight = Spotlight('slight') slight.setColor((1, 1, 1, 1)) lens = PerspectiveLens() slight.setLens(lens) self.slnp = render.attachNewNode(slight) self.slnp1 = render.attachNewNode(slight)
def __init__(self): self.accept("1", self.breakProgram) #lighting slight = Spotlight('slight') slight.setColor((1, 1, 1, 1)) lens = PerspectiveLens() slight.setLens(lens) #attaching lighting self.slnp = render.attachNewNode(slight) self.slnp1 = render.attachNewNode(slight) #runs as a thread to change the HPR of the plane taskMgr.add(rotatemycube)
def buildSubType(self): """Build the light with the given subType""" if self.subType == "pointType": # make a point light c = self.color pointLight = PointLight(self.name) pointLight.setColor(VBase4(c[0], c[1], c[2], c[3])) plnp = self.renderObjectsLight.attachNewNode(pointLight) plnp.setPos(self.position) self.lightNP = plnp self.setLightSwitch(True) if self.subType == "directType": # make a directional light c = self.color directLight = DirectionalLight(self.name) directLight.setColor(VBase4(c[0], c[1], c[2], c[3])) dlnp = self.renderObjectsLight.attachNewNode(directLight) dlnp.setHpr(0, -60, 0) # no idea why its like that.. but it works self.lightNP = dlnp self.setLightSwitch(True) if self.subType == "ambientType": # make a ambient light c = self.color ambientLight = AmbientLight(self.name) ambientLight.setColor(VBase4(c[0], c[1], c[2], c[3])) alnp = self.renderObjectsLight.attachNewNode(ambientLight) self.lightNP = alnp self.setLightSwitch(True) if self.subType == "spotType": # make a spot light # lookAtObj = _object.getTag("lookAt") get rid of this. c = self.color spotLight = Spotlight(self.name) spotLight.setColor(VBase4(c[0], c[1], c[2], c[3])) lens = PerspectiveLens() spotLight.setLens(lens) slnp = self.renderObjectsLight.attachNewNode(spotLight) slnp.setPos(self.position) slnp.setHpr(self.hpr) # Find out if this is really the only option # because setHpr doesnt seem to have any effect. # lookAt would be okay but that means adding anothe type #slnp.lookAt(self.main.GameObjects["player"].collisionBody) self.lightNP = slnp self.setLightSwitch(True)
def __init__(self): """initialise and start the Game""" ShowBase.__init__(self) self.accept("escape", exit) render.setShaderAuto(True) # # SIMPLE LEVEL SETUP # self.ralph = Actor("Ralph", { "idle": "Ralph-Idle", "walk": "Ralph-Walk", "run": "Ralph-Run" }) self.ralph.loop("idle") self.ralph.reparentTo(render) self.ralph.setPos(0, 3, -2) #self.ralph.setScale(10) self.ralphIval = self.ralph.hprInterval(5.0, Vec3(-360, 0, 0)) self.ralphIval.loop() #self.ralph.setH(-20) self.environment = loader.loadModel("environment") self.environment.reparentTo(render) self.environment.setScale(0.08) self.environment.setPos(-0.5, 15, -2) base.trackball.node().setHpr(0, 22, 0) # # Lights # alight = AmbientLight("Ambient") alight.setColor(VBase4(0.3, 0.3, 0.3, 1)) alnp = render.attachNewNode(alight) render.setLight(alnp) slight = Spotlight("slight") slight.setColor(VBase4(1, 1, 1, 1)) # Use a 512x512 resolution shadow map slight.setShadowCaster(True, 2048, 2048) lens = PerspectiveLens() lens.setFov(45) slight.setLens(lens) slnp = render.attachNewNode(slight) slnp.setPos(5, -10, 5) slnp.lookAt(0, 3, -2) render.setLight(slnp)
def __init__(self): """initialise and start the Game""" ShowBase.__init__(self) self.accept("escape", exit) render.setShaderAuto(True) # # SIMPLE LEVEL SETUP # self.ralph = Actor("Ralph", {"idle": "Ralph-Idle", "walk": "Ralph-Walk", "run": "Ralph-Run"}) self.ralph.loop("idle") self.ralph.reparentTo(render) self.ralph.setPos(0, 3, -2) #self.ralph.setScale(10) self.ralphIval = self.ralph.hprInterval(5.0, Vec3(-360, 0, 0)) self.ralphIval.loop() #self.ralph.setH(-20) self.environment = loader.loadModel("environment") self.environment.reparentTo(render) self.environment.setScale(0.08) self.environment.setPos(-0.5, 15, -2) base.trackball.node().setHpr(0, 22, 0) # # Lights # alight = AmbientLight("Ambient") alight.setColor(VBase4(0.3, 0.3, 0.3, 1)) alnp = render.attachNewNode(alight) render.setLight(alnp) slight = Spotlight("slight") slight.setColor(VBase4(1, 1, 1, 1)) # Use a 512x512 resolution shadow map slight.setShadowCaster(True, 2048, 2048) lens = PerspectiveLens() lens.setFov(45) slight.setLens(lens) slnp = render.attachNewNode(slight) slnp.setPos(5, -10, 5) slnp.lookAt(0, 3, -2) render.setLight(slnp)
def __init__(self): # Toggle options self.accept("2", self.toggleLightsSide) self.accept("3", self.toggleLightsUp) self.LightsOn = True self.LightsOn1 = True slight = Spotlight('slight') slight.setColor((1, 1, 1, 1)) lens = PerspectiveLens() slight.setLens(lens) self.slnp = render.attachNewNode(slight) self.slnp1 = render.attachNewNode(slight) self.color = np.zeros(3) self.coords = [0, 0, 0] self.cube = None
def __init__(self): ShowBase.__init__(self) self.gameTask = taskMgr.add(self.gameLoop, "gameLoop") base.disableMouse() base.camera.setPos(500, 500, 2000) base.camera.lookAt(500, 500, 0) slight = Spotlight('slight') slight.setColor(VBase4(1, 1, 1, 1)) lens = PerspectiveLens() slight.setLens(lens) # create rebel ships self.rebels = [Xwing('xwing' + str(x)) for x in xrange(10)] self.rebels += [Ywing('ywing' + str(x)) for x in xrange(10)] self.rebels += [Awing('awing' + str(x)) for x in xrange(10)] self.rebels += [Bwing('bwing' + str(x)) for x in xrange(10)] # create imperial ships self.imperials = [ TieFighter('tiefighter' + str(x)) for x in xrange(10) ] self.imperials += [ TieInterceptor('tieinterceptor' + str(x)) for x in xrange(10) ] self.shipList = [] self.shipList += self.rebels + self.imperials for i, ship in enumerate(self.shipList): ship.reparentTo(render) ship.setScale(2) ship.setPos( Point3(random() * 1000, random() * 1000, random() * 1000)) directionalLight = DirectionalLight('directionalLight') directionalLightNP = render.attachNewNode(directionalLight) directionalLightNP.setHpr(180, -20, 0) ship.setLight(directionalLightNP)
def __init__(self): ShowBase.__init__(self) self.gameTask = taskMgr.add(self.gameLoop, "gameLoop") base.disableMouse() base.camera.setPos(500, 500, 2000) base.camera.lookAt(500,500,0) slight = Spotlight('slight') slight.setColor(VBase4(1, 1, 1, 1)) lens = PerspectiveLens() slight.setLens(lens) # create rebel ships self.rebels = [Xwing('xwing' + str(x)) for x in xrange(20)] self.rebels += [Ywing('ywing' + str(x)) for x in xrange(20)] self.rebels += [Awing('awing' + str(x)) for x in xrange(20)] self.rebels += [Bwing('bwing' + str(x)) for x in xrange(20)] # create imperial ships self.imperials = [TieFighter('tiefighter' + str(x)) for x in xrange(80)] self.imperials += [TieInterceptor('tieinterceptor' + str(x)) for x in xrange(80)] self.shipList = [] self.shipList += self.rebels + self.imperials for i, ship in enumerate(self.shipList): ship.reparentTo(render) ship.setScale(2) ship.setPos(Point3(random()*1000, random()*1000, random()*1000)) directionalLight = DirectionalLight('directionalLight') directionalLightNP = render.attachNewNode(directionalLight) directionalLightNP.setHpr(180, -20, 0) ship.setLight(directionalLightNP) self.outFile = open('rebels_20_each_imperial_80_each_ship2ship','w') self.camFilter = LpfVec3(Vec3(0,0,0),20)
def __init__(self): ShowBase.__init__(self) self.cc = CentralController() self.gameTask = taskMgr.add(self.cc.run, "cc.run") base.disableMouse() base.camera.setPos(-20, 50, 70) base.camera.lookAt(20, 0, 0) slight = Spotlight('slight') slight.setColor(VBase4(1, 1, 1, 1)) lens = PerspectiveLens() slight.setLens(lens) self.shipList = [ Xwing("models/ywing", 0.3, "xwing1"), Ywing("models/xwing", 0.3, "ywing1") ] lightColors = [Vec4(0.9, 0.9, 0.9, 1), Vec4(1, 1, 0, 1)] for i, ship in enumerate(self.shipList): ship.reparentTo(render) ship.setScale(2) ship.setPos(Point3(i * 20, 0, 0)) directionalLight = DirectionalLight('directionalLight') directionalLight.setColor(lightColors[i]) directionalLightNP = render.attachNewNode(directionalLight) directionalLightNP.setHpr(180, -20, 0) ship.setLight(directionalLightNP) self.cc.addObject(ship) self.count = 0
def __init__(self): self._train_pos = base.train.root_node.getPos() # noqa: F821 self._mod = loader.loadModel(address("city_hangar")) # noqa: F821 base.camera_ctrl.set_hangar_pos(self._mod) # noqa: F821 self._mod.reparentTo(base.train.model) # noqa: F821 lens = PerspectiveLens() lens.setNearFar(0, 10) lens.setFov(100, 100) lighter = Spotlight("hangar_light") lighter.setColor((1, 1, 1, 1)) lighter.setLens(lens) self._lighter_np = self._mod.attachNewNode(lighter) self._lighter_np.setPos(-0.3, 0.65, 4) self._lighter_np.lookAt(base.train.model) # noqa: F821 render.setLight(self._lighter_np) # noqa: F821 flies = ParticleEffect() flies.loadConfig("effects/flies.ptf") flies.setPos(-0.465, 0.11, 0.17) flies.start(self._mod, render) # noqa: F821 lens = PerspectiveLens() lens.setNearFar(0, 50) lens.setFov(80, 80) lamp = Spotlight("hangar_light") lamp.setColor((0.7, 0.7, 0.7, 1)) lamp.setLens(lens) lamp.setExponent(0.002) self._lamp_np = self._mod.attachNewNode(lamp) self._lamp_np.setPos(-0.47, 0.11, 0.195) self._lamp_np.setHpr(-180, -60, 0) render.setLight(self._lamp_np) # noqa: F821
def _set_lights(self): """Configure the locomotive lights. Sets the main locomotive lighter and lights above the doors. Returns: list: NodePath's of the Train lights. """ lens = PerspectiveLens() lens.setNearFar(0, 50) lens.setFov(60, 60) floodlight = Spotlight("train_main_lighter") floodlight.setColor((0.5, 0.5, 0.5, 1)) floodlight.setLens(lens) floodlight.setExponent(0.4) floodlight_np = self.model.attachNewNode(floodlight) floodlight_np.setPos(0, 0.34, 50) render.setLight(floodlight_np) # noqa: F821 train_lights = [floodlight_np] for name, coors in ( ("train_right_door_light", (0.073, -0.17, 50)), ("train_left_door_light", (-0.073, -0.17, 50)), ("train_back_door_light", (0, -0.63, 50)), ): lamp = PointLight(name) lamp.setColor((0.89, 0.81, 0.55, 1)) lamp.setAttenuation(3) lamp_np = self.model.attachNewNode(lamp) lamp_np.setPos(*coors) render.setLight(lamp_np) # noqa: F821 train_lights.append(lamp_np) return train_lights
class Flashlight: POWER_MIN = 0.06 POWER_DRAIN_RATE = -1/240.0 POWER_GAIN_RATE = 1/480.0 EXPONENET = 40 COLOR = Vec4(1.0, 1.0, 0.9, 1) ATT_CONST = 0 ATT_LIN = 0.3 ATT_QUAD = 0.05 def __init__(self, name, owner, scene, pos, fov=60, near=0.01, far=100, resol=(1920, 1080)): self.owner = owner self.scene = scene self.last = 0.0 self.power = 1.0 self.on = True self.powerrate = Flashlight.POWER_DRAIN_RATE #TODO: Change lens parameters for a unique 'lens' parameter lens = PerspectiveLens() lens.setFov(fov) lens.setNearFar(near, far) lens.setFilmSize(resol[0], resol[1]) self.light = Spotlight(name + '/wide') self.light.setLens(lens) #TODO: Shadows don't work well anymore #self.light.setShadowCaster(True, resol[0], resol[1]) self.light.setColor(Flashlight.COLOR) self.light.setExponent(40) self.nodepath = owner.cam.attachNewNode(self.light) self.nodepath.setPos(pos) self.nodepath.setHpr((5,5,0)) self.scene.setLight(self.nodepath) def __del__(self): self.nodepath.removeNode() def toggle(self): self.on = not self.on if self.on: self.scene.setLight(self.nodepath) self.powerrate = Flashlight.POWER_DRAIN_RATE else: self.scene.clearLight(self.nodepath) self.powerrate = Flashlight.POWER_GAIN_RATE def updatePower(self, task): elapsed = task.time - self.last self.last = task.time self.power = max(Flashlight.POWER_MIN, min(1.0, self.power + elapsed * self.powerrate)) self.light.setAttenuation((Flashlight.ATT_CONST, Flashlight.ATT_LIN, Flashlight.ATT_QUAD / self.power)) return task.cont def getNodePath(self): return self.nodepath def setHpr(self, vec): self.nodepath.setHpr(vec) def isOn(self): return self.on
smallRandomAxis(vecList)) else: drawBody(nodePath, bodydata, pos, vecList, length.getX(), False) drawLeaf(nodePath, bodydata, pos, vecList) alight = AmbientLight('alight') alight.setColor((0.5, 0.5, 0.5, 1)) alnp = render.attachNewNode(alight) render.setLight(alnp) slight = Spotlight('slight') slight.setColor((1, 1, 1, 1)) lens = PerspectiveLens() slight.setLens(lens) slnp = render.attachNewNode(slight) render.setLight(slnp) slnp.setPos(0, 0, 40) # rotating light to show that normals are calculated correctly def updateLight(task): global slnp currPos = slnp.getPos() currPos.setX(100 * math.cos(task.time) / 2) currPos.setY(100 * math.sin(task.time) / 2) slnp.setPos(currPos) slnp.lookAt(render)
class Hooded(AICharacter): SIGHT=7.5 FOV=60.0 HEIGHT = 1.3 STATE_PATROL = 0 STATE_SEARCH = 1 STATE_WANDER = 2 STATE_ATTACK = 3 STATE_PAUSED = 4 class StatePatrol: pass def __init__(self, name, root, route, mass, movforce, maxforce): AICharacter.__init__(self, name, root, mass, movforce, maxforce) self.state = Hooded.STATE_PATROL self.initTimer = True self.attackTimer = True # we create a spotlight that will be the sentinel's eye and will be used to fire the inView method self.slight = Spotlight('slight') self.slight.setColor((1, 1, 1, 1)) lens = PerspectiveLens() lens.setNear(0.1) lens.setFar(Hooded.SIGHT) lens.setFov(Hooded.FOV) self.slight.setLens(lens) self.slnp = self.get_node_path().attachNewNode(self.slight) #TODO: Substitute for a collision polygon, so that the player class alerts an enemy of its presence #self.slight.showFrustum() self.slnp.setH(self.slnp.getH()-180) self.slnp.setPos(0, 0, Hooded.HEIGHT) self.hearing = 5.0 self.dynamicObstacles = [] self.detected = False self.pathfinding = False self.lostTarget = False self.countTime = False self.goingBack = False self.heard = False self.isProtected = False self.attacked = False self.started = False self.sentinelHandler = CollisionHandlerQueue() #TODO: Intruders should be added via an external method self.intruders = [] # this is important: as we said the inView method don't cull geometry but take everything is in sight frustum - therefore to simulate an hide and seek feature we gotta cheat a little: this ray is masked to collide with walls and so if the avatar is behind a wall the ray will be 'deflected' (we'll see how later in the sent_traverse function) - so we know who's behind a wall but we fake we can't see it. sentraygeom = CollisionSegment(0, 0, Hooded.HEIGHT, 0, Hooded.SIGHT, Hooded.HEIGHT) sentinelRay = self.get_node_path().attachNewNode(CollisionNode('sentinelray')) sentinelRay.node().addSolid(sentraygeom) # we set to the ray a cumulative masking using the or operator to detect either the avatar's body and the wall geometry sentinelRay.node().setFromCollideMask(CollisionMask.PLAYER) sentinelRay.node().setIntoCollideMask(CollisionMask.NONE) # we add the ray to the sentinel collider and now it is ready to go base.cTrav.addCollider(sentinelRay, self.sentinelHandler) self.screechsound = loader.loadSfx("assets/sounds/enemies/nazgul_scream.mp3") self.setPatrolPos(route) def __del__(self): self.slnp.removeNode() def addIntruder(self, intruder): self.intruders.append(intruder) def setPatrolPos(self, route): self.currentTarget = 0 self.route = route self.numTargets = len(route) self.increment = 1 self.getAiBehaviors().seek(self.route[0]) #to update the AIWorld def update(self): if (self.started == False): return False captured = self.sent_detect() if (captured): if (self.isProtected): self.state = Hooded.STATE_PAUSED elif (self.state != Hooded.STATE_SEARCH): self.state = Hooded.STATE_SEARCH self.getAiBehaviors().pauseAi("all") self.lostTarget = False self.heard = False self.resetTimer() """elif (self.heard): self.heard = False self.pursueTarget = self.hearingPos self.getAiBehaviors().pauseAi("all") self.state = Hooded.STATE_SEARCH elif (self.state == Hooded.STATE_SEARCH and self.lostTarget == False and self.goingBack == False): self.startTimer(1.5) hasFinished = self.timer() if (hasFinished == True): self.lostTarget = True self.getAiBehaviors().pauseAi("all") #self.state = 4 self.pursueTarget = self.TargetPos else: self.lostTarget = False""" if self.state == Hooded.STATE_PATROL: self.patrol() elif self.state == Hooded.STATE_SEARCH: self.pursue() elif self.state == Hooded.STATE_WANDER: self.wander() elif self.state == Hooded.STATE_ATTACK: self.kill() elif self.state == Hooded.STATE_PAUSED: self.pause() #elif self.state == Hooded.STATE_SEARCH: #self.pathfind() if (self.attacked): self.attacked = False return True return False #TODO: Patrol is ready for refactoring, if needed PATROL_PAUSE = 3.0 PATROL_DISTANCE = 1.0 def patrol(self): distance = self.get_node_path().getDistance(self.route[self.currentTarget]) if (distance < Hooded.PATROL_DISTANCE): self.startTimer(Hooded.PATROL_PAUSE) self.getAiBehaviors().pauseAi("all") if self.timer(): self.currentTarget = (self.currentTarget + 1) % len(self.route) self.resetTimer() self.getAiBehaviors().pauseAi("all") self.getAiBehaviors().seek(self.route[self.currentTarget]) self.getAiBehaviors().resumeAi("seek") def pathfind(self): if (not self.getAiBehaviors().behaviorStatus("pathfollow") in ["active", "done"]): self.getAiBehaviors().initPathFind("assets/navmesh.csv") self.getAiBehaviors().pauseAi("all") if isinstance(self.pursueTarget, NodePath): self.getAiBehaviors().pathFindTo(self.pursueTarget) else: self.getAiBehaviors().pathFindTo(self.pursueTarget.getNodePath()) for i in self.dynamicObstacles: self.getAiBehaviors().addDynamicObstacle(i) #self.pathfinding = True currentPos = self.get_node_path().getPos(render) if (isinstance(self.pursueTarget, NodePath)): self.TargetPos = self.pursueTarget else: self.TargetPos = self.pursueTarget.getNodePath() # print currentPos, self.TargetPos distance = self.get_node_path().getDistance(self.TargetPos) if (self.getAiBehaviors().behaviorStatus("pathfollow") == "done"): if (distance > 5): self.getAiBehaviors().pauseAi("all") return if (self.lostTarget == False): if (self.goingBack == True): self.getAiBehaviors().pauseAi("all") self.getAiBehaviors().seek(self.route[self.currentTarget]) self.state = Hooded.STATE_PATROL self.getAiBehaviors().resumeAi("seek") self.resetTimer() self.goingBack = False elif (self.heard == True): if (isinstance(self.pursueTarget, NodePath)): self.getAiBehaviors().pauseAi("all") self.state = Hooded.STATE_ATTACK else: self.startTimer(5) self.countTime = True self.pathfinding = False self.state = Hooded.STATE_WANDER self.radius = 5 self.aoe = 10 else: self.getAiBehaviors().pauseAi("all") self.state = Hooded.STATE_ATTACK else: self.startTimer(5) self.countTime = True self.pathfinding = False self.state = Hooded.STATE_WANDER self.radius = 5 self.aoe = 10 def wander(self): if (self.getAiBehaviors().behaviorStatus("wander") != "active"): self.getAiBehaviors().pauseAi("all") self.getAiBehaviors().wander(self.radius, 0,self.aoe, 1.0) #self.getAiBehaviors().resumeAi("wander") if (self.lostTarget == True and self.countTime == True): self.startTimer(5) hasFinished = self.timer() if (hasFinished == True): self.currentTarget += self.increment if (self.currentTarget == self.numTargets - 1): self.increment = -1 else: if (self.currentTarget == 0): self.increment = 1 self.pursueTarget = self.route[self.currentTarget] self.state = Hooded.STATE_SEARCH self.goingBack = True self.lostTarget= False self.getAiBehaviors().pauseAi("all") #self.getAiBehaviors().seek(self.route[self.currentTarget]) def kill(self): if (self.attackTimer): self.attacked = True self.attackTimer = False self.startTimer(3) self.pause() else: hasFinished = self.timer() if (hasFinished): self.attackTimer = True self.resetTimer() self.state = Hooded.STATE_SEARCH else: self.attacked = False #TODO: Use event handling, instead? def sent_traverse(self, suspect): if (self.sentinelHandler.getNumEntries() > 0): self.sentinelHandler.sortEntries() # for i in range(self.sentinelHandler.getNumEntries()): # print self.sentinelHandler.getEntry(i) entry = self.sentinelHandler.getEntry(0) self.sentinelHandler.clearEntries() colliderNP = entry.getIntoNodePath() if colliderNP.getParent() == suspect.getNodePath(): # self = False if self.detected == False: self.detected = True self.screechsound.play() suspect.boo() return True #TODO: This was meant for the implementation of safe areas, where the player could not be reached elif colliderNP.getName() == 'lightarea': newEntry = self.sentinelHandler.getEntry(1) newColliderNode = newEntry.getIntoNode() if (newColliderNode.getName() == 'playercol'): #check if player is really inside light area self.isProtected = True return True return False #** Here then we'll unleash the power of isInView method - this function is just a query if a 3D point is inside its frustum so it works for objects with lens, such as cameras or even, as in this case, a spotlight. But to make this happen, we got cheat a little, knowing in advance who we're going to seek, to query its position afterwards, and that's what the next line is about: to collect all the references for objects named 'smiley' def sent_detect(self): for o in self.intruders: # query the spotlight if something listed as 'intruders' is-In-View at its position and if this is the case we'll call the traverse function above to see if is open air or hidden from the sentinel's sight if self.slnp.node().isInView(o.getNodePath().getPos(self.slnp)): self.get_node_path().lookAt(o.getNodePath()) if self.sent_traverse(o): self.pursueTarget = o return True return False def timer(self): currentTime = time.time() diff = currentTime - self.time if (diff > self.interval): self.initTimer = True return True else: return False def resetTimer(self): self.initTimer = True def startTimer(self, interval): if (self.initTimer == True): self.interval = interval self.initTimer = False self.time = time.time() def addDynamicObject(self, dynamicObject): self.dynamicObstacles.append(dynamicObject) def hear(self, noisePos): dist = self.get_node_path().getDistance(noisePos) if (dist <= self.hearing): self.heard = True self.hearingPos = noisePos def pause(self): self.getAiBehaviors().pauseAi("all") #print "nao pausei?" def start(self): self.started = True def stop(self): self.started = False def clean(self): loader.unloadSfx(self.screechsound) def pursue(self): self.getAiBehaviors().pursue(self.pursueTarget.getNodePath()) if (self.get_node_path().getDistance(self.pursueTarget.getNodePath()) < 1): self.state = Hooded.STATE_ATTACK
class FactorySneakGuardSuit(Suit, FSM): notify = directNotify.newCategory("FactorySneakGuardSuit") SUIT = SuitBank.MrHollywood VARIANT = Variant.NORMAL VIEW_DISTANCE_TASK_NAME = "ViewDistanceTask" MAX_VIEW_DISTANCE = 100.0 GUARD_DIED_DELAY = 6.0 PROWLER_DISTANCE = 40.0 IN_VIEW = "somethingInSight" HEARD = "heard" TRY_TO_CONFIRM_TIME = 5.0 def __init__(self, world, guardKey): Suit.__init__(self) FSM.__init__(self, 'FactorySneakGuardSuit') self.gameWorld = world self.guardKey = guardKey self.viewDistanceTaskName = self.VIEW_DISTANCE_TASK_NAME + "-" + str( id(self)) self.diedTaskName = "GuardDied-" + str(id(self)) self.health = 0 self.maxHealth = 0 self.eyeLight = None self.eyeLens = None self.eyeNode = None self.moveTrack = None self.trav = None self.rayNP = None self.queue = None self.currentKey = self.guardKey self.firstPoint = CGG.GuardPointData[self.guardKey] self.walkTrack = None self.pathQueue = [] self.currentPathIndex = 0 def enterGuard(self): self.loop('neutral') pos, hpr = CGG.FactoryGuardPoints[self.guardKey] self.setHpr(hpr - (180, 0, 0)) self.setPos(pos) base.taskMgr.add(self.__guard, self.taskName("guard")) def __checkToon(self): self.rayNP.lookAt(base.localAvatar) self.trav.traverse(render) if self.queue.getNumEntries() > 0: self.queue.sortEntries() hitObj = self.queue.getEntry(0).getIntoNodePath() print hitObj isLocalAvatar = hitObj.getParent().getPythonTag('localAvatar') if isLocalAvatar == 1: # Yes! We see the prowler! return 1 return 0 def __guard(self, task): # Let me check if the target is my frustrum, and if it's a close enough distance from me. if (self.eyeNode.node().isInView(base.localAvatar.getPos(self.eyeNode)) and self.getDistance(base.localAvatar) <= self.PROWLER_DISTANCE): # Now, let me check if the toon is standing right in front of me; not occluded. if self.__checkToon(): # Yes! We see some one! self.request('SeekTarget', self.IN_VIEW) return task.done return task.cont def exitGuard(self): base.taskMgr.remove(self.taskName("guard")) def enterTurnToGuardSpot(self): self.loop('walk') _, hpr = CGG.FactoryGuardPoints[self.guardKey] self.moveTrack = LerpHprInterval(self, duration=1.0, hpr=hpr, startHpr=self.getHpr()) self.moveTrack.setDoneEvent(self.uniqueName('TurnedToGuardSpot')) self.acceptOnce(self.moveTrack.getDoneEvent(), self.request, ['Guard']) self.moveTrack.start() def exitTurnToGuardSpot(self): if self.moveTrack: self.ignore(self.moveTrack.getDoneEvent()) self.moveTrack.finish() self.moveTrack = None def enterSeekTarget(self, event): dialogue = random.choice(CGG.GuardDialog[event]) self.setChat(dialogue) self.loop('walk') self.moveTrack = NPCLookInterval(self, base.localAvatar) self.moveTrack.setDoneEvent(self.uniqueName("SeekLocalAvatar")) self.acceptOnce(self.moveTrack.getDoneEvent(), self.request, ['TryToConfirmTarget']) self.moveTrack.start() def exitSeekTarget(self): if self.moveTrack: self.ignore(self.moveTrack.getDoneEvent()) self.moveTrack.finish() self.moveTrack = None def enterTryToConfirmTarget(self): self.loop('neutral') base.taskMgr.add(self.__tryToConfirmTarget, self.uniqueName('TryToConfirmTarget')) def __tryToConfirmTarget(self, task): if task.time >= self.TRY_TO_CONFIRM_TIME: # Hmm, I guess it was nothing. chat = random.choice(CGG.GuardDialog['disregard']) self.setChat(chat) self.request('TurnToGuardSpot') return task.done # Let me see the target again, so I know it's actually something. if (self.eyeNode.node().isInView(base.localAvatar.getPos(self.eyeNode)) and self.getDistance(base.localAvatar) <= self.PROWLER_DISTANCE): # Now, let me check if the toon is standing right in front of me; not occluded. if self.__checkToon(): # There he is! chat = random.choice(CGG.GuardDialog['spot']) self.setChat(chat) self.request('Pursue') return task.done return task.cont def exitTryToConfirmTarget(self): base.taskMgr.remove(self.uniqueName('TryToConfirmTarget')) def enterGoBackToGuardSpot(self): self.walkBackToGuardSpot() def walkBackToGuardSpot(self): self.currentPathIndex = 0 self.pathQueue = SuitPathFinder.find_path(CGG.FactoryWalkPoints, CGG.FactoryWayPointData, self.currentKey, self.guardKey) self.currentKey = self.guardKey self.walk(0.2) self.loop('walk') def exitGoBackToGuardSpot(self): pass def enterPursue(self): self.numTries = 0 self.maxTries = 3 #self.runToClosestPoint() self.setPlayRate(1.5, 'walk') self.loop('walk') messenger.send('guardPursue') def getClosestPoint(self): # Return the key of the closest point to the localAvatar. closestPoint = None pointKey2range = {} for key, point in CGG.FactoryWalkPoints.items(): dummyNode = render.attachNewNode('dummyNode') dummyNode.setPos(point) pointKey2range[key] = base.localAvatar.getDistance(dummyNode) dummyNode.removeNode() ranges = [] for distance in pointKey2range.values(): ranges.append(distance) ranges.sort() for key in pointKey2range.keys(): distance = pointKey2range[key] if distance == ranges[0]: closestPoint = key break return closestPoint def runToClosestPoint(self): self.numTries += 1 closestPoint = self.getClosestPoint() self.currentPathIndex = 0 startKey = None if self.currentKey == self.guardKey: startKey = CGG.GuardPointData[self.firstPoint] else: startKey = self.currentKey self.pathQueue = SuitPathFinder.find_path(CGG.FactoryWalkPoints, CGG.FactoryWayPointData, startKey, closestPoint) if self.currentKey == self.guardKey: self.pathQueue.insert(0, 1) else: self.pathQueue.insert(0, 0) self.currentKey = closestPoint self.walk(0.1) def walk(self, speed=0.2): self.currentPathIndex += 1 if len(self.pathQueue) <= self.currentPathIndex: if self.getCurrentOrNextState() == 'Pursue': if self.getClosestPoint() != self.currentKey: # Wow, the player ran off somewhere else! Go there! if self.numTries >= self.maxTries: # Dang it, give up, we can't get to them! self.request('GoBackToGuardSpot') else: self.runToClosestPoint() elif self.getCurrentOrNextState() == 'GoBackToGuardSpot': self.request('Guard') return print self.pathQueue[self.currentPathIndex] if self.currentPathIndex == 1 and self.pathQueue[0] == 1: # We need to walk from our guard point to the first waypoint in our path startPoint = self.getPos(render) endPoint = CGG.FactoryWalkPoints[self.firstPoint] else: if self.pathQueue[0] == 0: self.pathQueue.remove(self.pathQueue[0]) key = self.pathQueue[self.currentPathIndex] endPoint = CGG.FactoryWalkPoints[key] oldKey = self.pathQueue[self.currentPathIndex - 1] startPoint = CGG.FactoryWalkPoints[oldKey] self.walkTrack = NPCWalkInterval(self, endPoint, speed, startPoint) self.walkTrack.setDoneEvent(self.uniqueName('guardWalkDone')) self.acceptOnce(self.uniqueName('guardWalkDone'), self.walk) self.walkTrack.start() def exitPursue(self): self.setPlayRate(1.0, 'walk') del self.numTries if self.walkTrack: self.ignore(self.walkTrack.getDoneEvent()) self.walkTrack.pause() self.walkTrack = None messenger.send('guardStopPursue') def uniqueName(self, name): return self.taskName(name) def taskName(self, name): return name + "-" + str(id(self)) def shot(self): dialogue = random.choice(CGG.GuardDialog['shot']) self.setChat(dialogue) def dead(self): self.request('Off') self.animFSM.request('die') base.taskMgr.doMethodLater(self.GUARD_DIED_DELAY, self.__diedDone, self.diedTaskName) def __diedDone(self, task): self.gameWorld.deleteGuard(self) return task.done def setHealth(self, hp): self.health = hp self.updateHealthBar(hp) def getHealth(self): return self.health def generate(self): self.level = 12 self.maxHealth = 200 self.health = 200 Suit.generate(self, FactorySneakGuardSuit.SUIT, FactorySneakGuardSuit.VARIANT, hideFirst=False) self.setName(self.suitPlan.getName(), None) self.cleanupPropeller() base.taskMgr.add(self.__viewDistance, self.viewDistanceTaskName) self.setPythonTag('guard', self) self.eyeLight = Spotlight('eyes') self.eyeLens = PerspectiveLens() self.eyeLens.setMinFov(90.0 / (4. / 3.)) self.eyeLight.setLens(self.eyeLens) self.eyeNode = self.headModel.attachNewNode(self.eyeLight) self.eyeNode.setZ(-5) self.eyeNode.setY(-4.5) self.trav = CollisionTraverser(self.uniqueName('eyeTrav')) ray = CollisionRay(0, 0, 0, 0, 1, 0) rayNode = CollisionNode('ToonFPS.rayNode') rayNode.addSolid(ray) rayNode.setFromCollideMask(CGG.GuardBitmask | CIGlobals.WallBitmask) rayNode.setIntoCollideMask(BitMask32.allOff()) self.rayNP = base.camera.attachNewNode(rayNode) self.rayNP.setZ(3) self.queue = CollisionHandlerQueue() self.trav.addCollider(self.rayNP, self.queue) self.trav.addCollider(self.gameWorld.mg.avatarBody, self.queue) self.request('Guard') def __viewDistance(self, task): # All the guards in the warehouse eat up a lot of frames. This task will # hide the guard geometry if it's too far away. if self.getDistance(base.localAvatar) > self.MAX_VIEW_DISTANCE: if not self.isHidden(): self.hide() else: if self.isHidden(): self.show() task.delayTime = 1.0 return task.again def disable(self): self.request('Off') base.taskMgr.remove(self.taskName("guard")) base.taskMgr.remove(self.diedTaskName) base.taskMgr.remove(self.viewDistanceTaskName) self.trav = None if self.rayNP: self.rayNP.removeNode() self.rayNP = None self.queue = None self.currentPathIndex = None if self.eyeNode: self.eyeNode.removeNode() self.eyeNode = None self.eyeLens = None self.eyeLight = None self.viewDistanceTaskName = None self.guardKey = None self.gameWorld = None self.pathQueue = None if self.walkTrack: self.ignore(self.walkTrack.getDoneEvent()) self.walkTrack.finish() self.walkTrack = None Suit.disable(self)
numIterations - 1, numCopies, smallRandomAxis(vecList)) else: drawBody(nodePath, bodydata, pos, vecList, length.getX(), False) drawLeaf(nodePath, bodydata, pos, vecList) alight = AmbientLight('alight') alight.setColor((0.5, 0.5, 0.5, 1)) alnp = render.attachNewNode(alight) render.setLight(alnp) slight = Spotlight('slight') slight.setColor((1, 1, 1, 1)) lens = PerspectiveLens() slight.setLens(lens) slnp = render.attachNewNode(slight) render.setLight(slnp) slnp.setPos(0, 0, 40) # rotating light to show that normals are calculated correctly def updateLight(task): global slnp currPos = slnp.getPos() currPos.setX(100 * math.cos(task.time) / 2) currPos.setY(100 * math.sin(task.time) / 2) slnp.setPos(currPos) slnp.lookAt(render) return Task.cont
def getLightsForModel(self, modelId): lights = [] if modelId in self.supportedModelIds: for n, lightData in enumerate(self.data[modelId]): attenuation = LVector3f(*lightData['attenuation']) #TODO: implement light power #power = float(lightData['power']) positionYup = LVector3f(*lightData['position']) yupTozupMat = LMatrix4f.convertMat(CS_yup_right, CS_zup_right) position = yupTozupMat.xformVec(positionYup) colorHtml = lightData['color'] color = LVector3f(*[ int('0x' + colorHtml[i:i + 2], 16) for i in range(1, len(colorHtml), 2) ]) / 255.0 direction = None lightType = lightData['type'] lightName = modelId + '-light-' + str(n) if lightType == 'SpotLight': light = Spotlight(lightName) light.setAttenuation(attenuation) light.setColor(color) cutoffAngle = float(lightData['cutoffAngle']) lens = PerspectiveLens() lens.setFov(cutoffAngle / np.pi * 180.0) light.setLens(lens) # NOTE: unused attributes #dropoffRate = float(lightData['dropoffRate']) directionYup = LVector3f(*lightData['direction']) direction = yupTozupMat.xformVec(directionYup) elif lightType == 'PointLight': light = PointLight(lightName) light.setAttenuation(attenuation) light.setColor(color) elif lightType == 'LineLight': #XXX: we may wish to use RectangleLight from the devel branch of Panda3D light = PointLight(lightName) light.setAttenuation(attenuation) light.setColor(color) # NOTE: unused attributes #dropoffRate = float(lightData['dropoffRate']) #cutoffAngle = float(lightData['cutoffAngle']) #position2Yup = LVector3f(*lightData['position2']) #position2 = yupTozupMat.xformVec(position2Yup) #directionYup = LVector3f(*lightData['direction']) #direction = yupTozupMat.xformVec(directionYup) else: raise Exception('Unsupported light type: %s' % (lightType)) lightNp = NodePath(light) # Set position and direction of light lightNp.setPos(position) if direction is not None: targetPos = position + direction lightNp.look_at(targetPos, LVector3f.up()) lights.append(lightNp) return lights
class FactorySneakGuardSuit(Suit, FSM): notify = directNotify.newCategory('FactorySneakGuardSuit') SUIT = 'mrhollywood' VIEW_DISTANCE_TASK_NAME = 'ViewDistanceTask' MAX_VIEW_DISTANCE = 100.0 GUARD_DIED_DELAY = 6.0 MAX_HP = 200 PROWLER_DISTANCE = 40.0 IN_VIEW = 'somethingInSight' HEARD = 'heard' TRY_TO_CONFIRM_TIME = 5.0 def __init__(self, world, guardKey): Suit.__init__(self) FSM.__init__(self, 'FactorySneakGuardSuit') self.gameWorld = world self.guardKey = guardKey self.viewDistanceTaskName = self.VIEW_DISTANCE_TASK_NAME + '-' + str( id(self)) self.diedTaskName = 'GuardDied-' + str(id(self)) self.health = 0 self.maxHealth = self.MAX_HP self.eyeLight = None self.eyeLens = None self.eyeNode = None self.moveTrack = None self.trav = None self.rayNP = None self.queue = None self.currentKey = self.guardKey self.firstPoint = CGG.GuardPointData[self.guardKey] self.walkTrack = None self.pathQueue = [] self.currentPathIndex = 0 return def enterGuard(self): self.loop('neutral') pos, hpr = CGG.FactoryGuardPoints[self.guardKey] self.setHpr(hpr - (180, 0, 0)) self.setPos(pos) base.taskMgr.add(self.__guard, self.taskName('guard')) def __checkToon(self): self.rayNP.lookAt(base.localAvatar) self.trav.traverse(render) if self.queue.getNumEntries() > 0: self.queue.sortEntries() hitObj = self.queue.getEntry(0).getIntoNodePath() print hitObj isLocalAvatar = hitObj.getParent().getPythonTag('localAvatar') if isLocalAvatar == 1: return 1 return 0 def __guard(self, task): if self.eyeNode.node().isInView(base.localAvatar.getPos( self.eyeNode)) and self.getDistance( base.localAvatar) <= self.PROWLER_DISTANCE: if self.__checkToon(): self.request('SeekTarget', self.IN_VIEW) return task.done return task.cont def exitGuard(self): base.taskMgr.remove(self.taskName('guard')) def enterTurnToGuardSpot(self): self.loop('walk') _, hpr = CGG.FactoryGuardPoints[self.guardKey] self.moveTrack = LerpHprInterval(self, duration=1.0, hpr=hpr, startHpr=self.getHpr()) self.moveTrack.setDoneEvent(self.uniqueName('TurnedToGuardSpot')) self.acceptOnce(self.moveTrack.getDoneEvent(), self.request, ['Guard']) self.moveTrack.start() def exitTurnToGuardSpot(self): if self.moveTrack: self.ignore(self.moveTrack.getDoneEvent()) self.moveTrack.finish() self.moveTrack = None return def enterSeekTarget(self, event): dialogue = random.choice(CGG.GuardDialog[event]) self.setChat(dialogue) self.loop('walk') self.moveTrack = NPCLookInterval(self, base.localAvatar) self.moveTrack.setDoneEvent(self.uniqueName('SeekLocalAvatar')) self.acceptOnce(self.moveTrack.getDoneEvent(), self.request, ['TryToConfirmTarget']) self.moveTrack.start() def exitSeekTarget(self): if self.moveTrack: self.ignore(self.moveTrack.getDoneEvent()) self.moveTrack.finish() self.moveTrack = None return def enterTryToConfirmTarget(self): self.loop('neutral') base.taskMgr.add(self.__tryToConfirmTarget, self.uniqueName('TryToConfirmTarget')) def __tryToConfirmTarget(self, task): if task.time >= self.TRY_TO_CONFIRM_TIME: chat = random.choice(CGG.GuardDialog['disregard']) self.setChat(chat) self.request('TurnToGuardSpot') return task.done if self.eyeNode.node().isInView(base.localAvatar.getPos( self.eyeNode)) and self.getDistance( base.localAvatar) <= self.PROWLER_DISTANCE: if self.__checkToon(): chat = random.choice(CGG.GuardDialog['spot']) self.setChat(chat) self.request('Pursue') return task.done return task.cont def exitTryToConfirmTarget(self): base.taskMgr.remove(self.uniqueName('TryToConfirmTarget')) def enterGoBackToGuardSpot(self): self.walkBackToGuardSpot() def walkBackToGuardSpot(self): self.currentPathIndex = 0 self.pathQueue = SuitPathFinder.find_path(CGG.FactoryWalkPoints, CGG.FactoryWayPointData, self.currentKey, self.guardKey) self.currentKey = self.guardKey self.walk(0.2) self.loop('walk') def exitGoBackToGuardSpot(self): pass def enterPursue(self): self.numTries = 0 self.maxTries = 3 self.runToClosestPoint() self.setPlayRate(1.5, 'walk') self.loop('walk') messenger.send('guardPursue') def getClosestPoint(self): closestPoint = None pointKey2range = {} for key, point in CGG.FactoryWalkPoints.items(): dummyNode = render.attachNewNode('dummyNode') dummyNode.setPos(point) pointKey2range[key] = base.localAvatar.getDistance(dummyNode) dummyNode.removeNode() ranges = [] for distance in pointKey2range.values(): ranges.append(distance) ranges.sort() for key in pointKey2range.keys(): distance = pointKey2range[key] if distance == ranges[0]: closestPoint = key break return closestPoint def runToClosestPoint(self): self.numTries += 1 closestPoint = self.getClosestPoint() self.currentPathIndex = 0 startKey = None if self.currentKey == self.guardKey and self.firstPoint in CGG.GuardPointData: startKey = CGG.GuardPointData[self.firstPoint] else: startKey = self.currentKey self.pathQueue = SuitPathFinder.find_path(CGG.FactoryWalkPoints, CGG.FactoryWayPointData, startKey, closestPoint) if self.currentKey == self.guardKey: self.pathQueue.insert(0, 1) else: self.pathQueue.insert(0, 0) self.currentKey = closestPoint self.walk(0.1) return def walk(self, speed=0.2): self.currentPathIndex += 1 if len(self.pathQueue) <= self.currentPathIndex: if self.getCurrentOrNextState() == 'Pursue': if self.getClosestPoint() != self.currentKey: if self.numTries >= self.maxTries: self.request('GoBackToGuardSpot') else: self.runToClosestPoint() else: if self.getCurrentOrNextState() == 'GoBackToGuardSpot': self.request('Guard') return print self.pathQueue[self.currentPathIndex] if self.currentPathIndex == 1 and self.pathQueue[0] == 1: startPoint = self.getPos(render) endPoint = CGG.FactoryWalkPoints[self.firstPoint] else: if self.pathQueue[0] == 0: self.pathQueue.remove(self.pathQueue[0]) key = self.pathQueue[self.currentPathIndex] endPoint = CGG.FactoryWalkPoints[key] oldKey = self.pathQueue[self.currentPathIndex - 1] startPoint = CGG.FactoryWalkPoints[oldKey] self.walkTrack = NPCWalkInterval(self, endPoint, speed, startPoint) self.walkTrack.setDoneEvent(self.uniqueName('guardWalkDone')) self.acceptOnce(self.uniqueName('guardWalkDone'), self.walk) self.walkTrack.start() def exitPursue(self): self.setPlayRate(1.0, 'walk') del self.numTries if self.walkTrack: self.ignore(self.walkTrack.getDoneEvent()) self.walkTrack.pause() self.walkTrack = None messenger.send('guardStopPursue') return def uniqueName(self, name): return self.taskName(name) def taskName(self, name): return name + '-' + str(id(self)) def setHealth(self, hp): self.health = hp def getHealth(self): return self.health def shot(self): dialogue = random.choice(CGG.GuardDialog['shot']) self.setChat(dialogue) def dead(self): self.request('Off') self.animFSM.request('die') base.taskMgr.doMethodLater(self.GUARD_DIED_DELAY, self.__diedDone, self.diedTaskName) def __diedDone(self, task): self.gameWorld.deleteGuard(self) return task.done def generate(self): data = CIGlobals.SuitBodyData[self.SUIT] type = data[0] team = data[1] self.team = team self.level = 12 self.suit = type Suit.generate(self, SuitBank.MrHollywood, 0, hideFirst=False) self.suit = type base.taskMgr.add(self.__viewDistance, self.viewDistanceTaskName) self.setPythonTag('guard', self) self.eyeLight = Spotlight('eyes') self.eyeLens = PerspectiveLens() self.eyeLens.setMinFov(90.0 / (4.0 / 3.0)) self.eyeLight.setLens(self.eyeLens) self.eyeNode = self.headModel.attachNewNode(self.eyeLight) self.eyeNode.setZ(-5) self.eyeNode.setY(-4.5) self.trav = CollisionTraverser(self.uniqueName('eyeTrav')) ray = CollisionRay(0, 0, 0, 0, 1, 0) rayNode = CollisionNode('ToonFPS.rayNode') rayNode.addSolid(ray) rayNode.setFromCollideMask(CGG.GuardBitmask | CIGlobals.WallBitmask) rayNode.setIntoCollideMask(BitMask32.allOff()) self.rayNP = base.camera.attachNewNode(rayNode) self.rayNP.setZ(3) self.queue = CollisionHandlerQueue() self.trav.addCollider(self.rayNP, self.queue) self.trav.addCollider(self.gameWorld.mg.avatarBody, self.queue) self.request('Guard') def __viewDistance(self, task): if self.getDistance(base.localAvatar) > self.MAX_VIEW_DISTANCE: if not self.isHidden(): self.hide() else: if self.isHidden(): self.show() task.delayTime = 1.0 return task.again def disable(self): self.request('Off') base.taskMgr.remove(self.taskName('guard')) base.taskMgr.remove(self.diedTaskName) base.taskMgr.remove(self.viewDistanceTaskName) self.trav = None if self.rayNP: self.rayNP.removeNode() self.rayNP = None self.queue = None self.currentPathIndex = None if self.eyeNode: self.eyeNode.removeNode() self.eyeNode = None self.eyeLens = None self.eyeLight = None self.viewDistanceTaskName = None self.guardKey = None self.gameWorld = None self.pathQueue = None if self.walkTrack: self.ignore(self.walkTrack.getDoneEvent()) self.walkTrack.finish() self.walkTrack = None Suit.disable(self) return
def __init__(self): ShowBase.__init__(self) self.gameTask = taskMgr.add(self.flyCircles, "circles") base.disableMouse() base.camera.setPos(-400, 00, 400) base.camera.lookAt(00, 000, 0) slight = Spotlight('slight') slight.setColor(VBase4(1, 1, 1, 1)) lens = PerspectiveLens() slight.setLens(lens) self.rebels = [] self.imperials = [] # add rebel ships self.rebels += [Xwing('xwing' + str(x)) for x in xrange(1)] #self.rebels += [Ywing('ywing' + str(x)) for x in xrange(1)] #self.rebels += [Awing('awing' + str(x)) for x in xrange(1)] #self.rebels += [Bwing('bwing' + str(x)) for x in xrange(1)] # add imperial ships self.imperials += [TieFighter('tiefighter' + str(x)) for x in xrange(1)] #self.imperials += [TieInterceptor('tieinterceptor' + str(x)) for x in xrange(2)] # add rebel ships self.rebels += [Xwing('xwing' + str(x) + 'second') for x in xrange(1)] #self.rebels += [Ywing('ywing' + str(x) + 'second') for x in xrange(1)] #self.rebels += [Awing('awing' + str(x) + 'second') for x in xrange(1)] #self.rebels += [Bwing('bwing' + str(x) + 'second') for x in xrange(1)] # add more imperial ships #self.imperials += [TieFighter('tiefighter' + str(x) + 'second') for x in xrange(2)] self.imperials += [TieInterceptor('tieinterceptor' + str(x) + 'second') for x in xrange(1)] # create ship list self.shipList = self.rebels + self.imperials #self.shipList = [ # Xwing("xwing1"), TieFighter("tie1"), Bwing("xwing2")] lightColors = [ Vec4(0.9, 0.9, 0.9, 1), Vec4(0.9, 0.9, 0.9, 1),] for i, ship in enumerate(self.shipList): ship.reparentTo(render) ship.setScale(2) ship.setPos(Point3(i*50+50,i*100+100,i*50+50)) directionalLight = DirectionalLight('directionalLight') directionalLightNP = render.attachNewNode(directionalLight) directionalLightNP.setHpr(180, -20, 0) ship.setLight(directionalLightNP) #ship.navSystem.setPursue() self.count = 0 self.iter = 0 camera.lookAt(self.shipList[1].getPos())
def __init__(self): ShowBase.__init__(self) self.cc = CentralController() self.gameTask = taskMgr.add(self.flyCircles, "circles") base.disableMouse() base.camera.setPos(1000, 100, 4000) base.camera.lookAt(200, 1000, 0) slight = Spotlight('slight') slight.setColor(VBase4(1, 1, 1, 1)) lens = PerspectiveLens() slight.setLens(lens) self.rebels = [] self.imperials = [] # add rebel ships self.rebels += [Xwing('xwing' + str(x)) for x in xrange(1)] #self.rebels += [Ywing('ywing' + str(x)) for x in xrange(1)] #self.rebels += [Awing('awing' + str(x)) for x in xrange(1)] #self.rebels += [Bwing('bwing' + str(x)) for x in xrange(1)] # add imperial ships self.imperials += [ TieFighter('tiefighter' + str(x)) for x in xrange(1) ] #self.imperials += [TieInterceptor('tieinterceptor' + str(x)) for x in xrange(2)] # add rebel ships self.rebels += [Xwing('xwing' + str(x) + 'second') for x in xrange(1)] #self.rebels += [Ywing('ywing' + str(x) + 'second') for x in xrange(1)] #self.rebels += [Awing('awing' + str(x) + 'second') for x in xrange(1)] #self.rebels += [Bwing('bwing' + str(x) + 'second') for x in xrange(1)] # add more imperial ships #self.imperials += [TieFighter('tiefighter' + str(x) + 'second') for x in xrange(2)] self.imperials += [ TieInterceptor('tieinterceptor' + str(x) + 'second') for x in xrange(1) ] # create ship list self.shipList = self.rebels + self.imperials #self.shipList = [ # Xwing("xwing1"), TieFighter("tie1"), Bwing("xwing2")] lightColors = [ Vec4(0.9, 0.9, 0.9, 1), Vec4(0.9, 0.9, 0.9, 1), ] for i, ship in enumerate(self.shipList): ship.reparentTo(render) ship.setScale(2) ship.setPos(Point3(i * 50 + 50, i * 100 + 100, i * 50 + 50)) directionalLight = DirectionalLight('directionalLight') directionalLightNP = render.attachNewNode(directionalLight) directionalLightNP.setHpr(180, -20, 0) ship.setLight(directionalLightNP) #ship.navSystem.setPursue() self.cc.addObject(ship) self.count = 0 self.iter = 0 camera.lookAt(self.shipList[1].getPos())
def parse_scene(self,scene,parent=None): tmp_statics = scene["statics"]; lst_statics = {}; it = 0 for elt in tmp_statics["sol"]: if not self.dic_statics.has_key(elt): self.dic_statics[elt] = base.loader.loadModel(elt+".bam") for posrot in tmp_statics["sol"][elt]: tmp_inst = render.attachNewNode("sol_"+str(it)); self.dic_statics[elt].instanceTo(tmp_inst) tmp_inst.setPos(posrot[0][0]*4.8,posrot[0][1]*4.8,posrot[0][2]*4.8); tmp_inst.setHpr(posrot[1][0],posrot[1][1],posrot[1][2]) tmp_inst.reparentTo(render); lst_statics["sol_"+str(it)] = tmp_inst # # TODO : génération de la carte si besoin # # TODO : voir pour le navigational mesh ici # it += 1 for key in ["nord","sud","est","ouest"]: for elt in tmp_statics["bords"][key]: # print elt # if key == "nord": # # pass elif key == "sud": # # pass elif key == "est": # # pass elif key == "ouest": # # pass # pass for elt in tmp_statics["murs"][key]: # print elt # # pass for elt in tmp_statics["decors"][key]: # print elt # # pass # # TODO : chargement des animations # tmp_dynamics = scene["dynamics"]; lst_dynamics = {} # for elt in tmp_dynamics: # # # pass # # tmp_lights = scene["lights"]; lst_lights = {} for lght in tmp_lights: tmp_lght = None if lght[0] == 0: spot_light = Spotlight("spotlight"); spot_light.setColor(Vec4(lght[1][0],lght[1][1],lght[1][2],lght[1][3])) lens = PerspectiveLens(); spot_light.setLens(lens); tmp_lght = render.attachNewNode(spot_light) tmp_lght.lookAt(lght[3][0],lght[3][1],lght[3][2]); tmp_lght.setPos(lght[2][0],lght[2][1],lght[2][2]) elif lght[0] == 1: dir_light = DirectionalLight("dir_light"); dir_light.setColor(Vec4(lght[1][0],lght[1][1],lght[1][2],lght[1][3])) tmp_lght = render.attachNewNode(dir_light); tmp_lght.setHpr(lght[3][0],lght[3][1],lght[3][2]) if lght[4]: if lght[5] != None: lght[5].setLight(tmp_lght) else: render.setLight(tmp_lght) lst_lights[lght[6]] = tmp_lght # # # return lst_statics, lst_dynamics, lst_lights
class FactorySneakGuardSuit(Suit, FSM): notify = directNotify.newCategory('FactorySneakGuardSuit') SUIT = 'mrhollywood' VIEW_DISTANCE_TASK_NAME = 'ViewDistanceTask' MAX_VIEW_DISTANCE = 100.0 GUARD_DIED_DELAY = 6.0 MAX_HP = 200 IN_VIEW = 'somethingInSight' HEARD = 'heard' TRY_TO_CONFIRM_TIME = 5.0 def __init__(self, world, guardKey): Suit.__init__(self) FSM.__init__(self, 'FactorySneakGuardSuit') self.gameWorld = world self.guardKey = guardKey self.viewDistanceTaskName = self.VIEW_DISTANCE_TASK_NAME + '-' + str(id(self)) self.diedTaskName = 'GuardDied-' + str(id(self)) self.health = 0 self.maxHealth = self.MAX_HP self.eyeLight = None self.eyeLens = None self.eyeNode = None self.moveTrack = None return def enterGuard(self): self.loop('neutral') pos, hpr = CGG.FactoryGuardPoints[self.guardKey] self.setHpr(hpr - (180, 0, 0)) self.setPos(pos) base.taskMgr.add(self.__guard, self.taskName('guard')) def __guard(self, task): if self.eyeNode.node().isInView(base.localAvatar.getPos(self.eyeNode)): self.request('SeekTarget', self.IN_VIEW) return task.done return task.cont def exitGuard(self): base.taskMgr.remove(self.taskName('guard')) def enterTurnToGuardSpot(self): self.loop('walk') _, hpr = CGG.FactoryGuardPoints[self.guardKey] self.moveTrack = LerpHprInterval(self, duration=1.0, hpr=hpr, startHpr=self.getHpr()) self.moveTrack.setDoneEvent(self.uniqueName('TurnedToGuardSpot')) self.acceptOnce(self.moveTrack.getDoneEvent(), self.request, ['Guard']) self.moveTrack.start() def exitTurnToGuardSpot(self): if self.moveTrack: self.ignore(self.moveTrack.getDoneEvent()) self.moveTrack.finish() self.moveTrack = None return def enterSeekTarget(self, event): dialogue = random.choice(CGG.GuardDialog[event]) self.setChat(dialogue) self.loop('walk') self.moveTrack = NPCLookInterval(self, base.localAvatar) self.moveTrack.setDoneEvent(self.uniqueName('SeekLocalAvatar')) self.acceptOnce(self.moveTrack.getDoneEvent(), self.request, ['TryToConfirmTarget']) self.moveTrack.start() def exitSeekTarget(self): if self.moveTrack: self.ignore(self.moveTrack.getDoneEvent()) self.moveTrack.finish() self.moveTrack = None return def enterTryToConfirmTarget(self): self.loop('neutral') base.taskMgr.add(self.__tryToConfirmTarget, self.uniqueName('TryToConfirmTarget')) def __tryToConfirmTarget(self, task): if task.time >= self.TRY_TO_CONFIRM_TIME: chat = random.choice(CGG.GuardDialog['disregard']) self.setChat(chat) self.request('TurnToGuardSpot') return task.done if self.eyeNode.node().isInView(base.localAvatar.getPos(self.eyeNode)): chat = random.choice(CGG.GuardDialog['spot']) self.setChat(chat) return task.done return task.cont def exitTryToConfirmTarget(self): base.taskMgr.remove(self.uniqueName('TryToConfirmTarget')) def uniqueName(self, name): return self.taskName(name) def taskName(self, name): return name + '-' + str(id(self)) def setHealth(self, hp): self.health = hp def getHealth(self): return self.health def shot(self): dialogue = random.choice(CGG.GuardDialog['shot']) self.setChat(dialogue) def dead(self): self.animFSM.request('die') base.taskMgr.doMethodLater(self.GUARD_DIED_DELAY, self.__diedDone, self.diedTaskName) def __diedDone(self, task): self.gameWorld.deleteGuard(self) return task.done def generate(self): data = CIGlobals.SuitBodyData[self.SUIT] type = data[0] team = data[1] self.generateSuit(type, self.SUIT, team, self.MAX_HP, 0, False) base.taskMgr.add(self.__viewDistance, self.viewDistanceTaskName) self.setPythonTag('guard', self) self.eyeLight = Spotlight('eyes') self.eyeLens = PerspectiveLens() self.eyeLens.setMinFov(90.0 / (4.0 / 3.0)) self.eyeLight.setLens(self.eyeLens) self.eyeNode = self.headModel.attachNewNode(self.eyeLight) self.eyeNode.setZ(-5) self.eyeNode.setY(-4.5) self.request('Guard') def __viewDistance(self, task): if self.getDistance(base.localAvatar) > self.MAX_VIEW_DISTANCE: if not self.isHidden(): self.hide() elif self.isHidden(): self.show() task.delayTime = 1.0 return task.again def disable(self): base.taskMgr.remove(self.diedTaskName) base.taskMgr.remove(self.viewDistanceTaskName) if self.eyeNode: self.eyeNode.removeNode() self.eyeNode = None self.eyeLens = None self.eyeLight = None self.viewDistanceTaskName = None self.guardKey = None self.gameWorld = None Suit.disable(self) return
def __init__(self): ShowBase.__init__(self) #Setup scene = BulletWorld() scene.setGravity(Vec3(0, 0, -9.81)) base.setBackgroundColor(0.6,0.9,0.9) fog = Fog("The Fog") fog.setColor(0.9,0.9,1.0) fog.setExpDensity(0.003) render.setFog(fog) #Lighting #Sun light sun = DirectionalLight("The Sun") sun_np = render.attachNewNode(sun) sun_np.setHpr(0,-60,0) render.setLight(sun_np) #Ambient light amb = AmbientLight("The Ambient Light") amb.setColor(VBase4(0.39,0.39,0.39, 1)) amb_np = render.attachNewNode(amb) render.setLight(amb_np) #Variables self.gear = 0 self.start = 0 self.Pbrake = 0 self.terrain_var = 1 self.time = 0 self.headlight_var = 0 self.RPM = 0 self.clutch = 0 self.carmaxspeed = 100 #KPH self.carmaxreversespeed = -40 #KPH self.steering = 0 #Functions def V1(): camera.setPos(0.25,-1.2,0.5) camera.setHpr(0,-13,0) def V2(): camera.setPos(0,-15,3) camera.setHpr(0,-10,0) def V3(): camera.setPos(0,0,9) camera.setHpr(0,-90,0) def up(): self.gear = self.gear -1 if self.gear < -1: self.gear = -1 def down(): self.gear = self.gear +1 if self.gear > 1: self.gear = 1 def start_function(): self.start = 1 self.start_sound.play() self.engine_idle_sound.play() self.RPM = 1000 def stop_function(): self.start = 0 self.engine_idle_sound.stop() def parkingbrake(): self.Pbrake = (self.Pbrake + 1) % 2 def rotate(): Car_np.setHpr(0, 0, 0) def horn(): self.horn_sound.play() def set_time(): if self.time == -1: sun.setColor(VBase4(0.4, 0.3, 0.3, 1)) base.setBackgroundColor(0.8,0.7,0.7) if self.time == 0: sun.setColor(VBase4(0.7, 0.7, 0.7, 1)) base.setBackgroundColor(0.6,0.9,0.9) if self.time == 1: sun.setColor(VBase4(0.2, 0.2, 0.2, 1)) base.setBackgroundColor(0.55,0.5,0.5) if self.time == 2: sun.setColor(VBase4(0.02, 0.02, 0.05, 1)) base.setBackgroundColor(0.3,0.3,0.3) if self.time == -2: self.time = -1 if self.time == 3: self.time = 2 def time_forward(): self.time = self.time + 1 def time_backward(): self.time = self.time -1 def set_terrain(): if self.terrain_var == 1: self.ground_model.setTexture(self.ground_tex, 1) self.ground_model.setScale(3) if self.terrain_var == 2: self.ground_model.setTexture(self.ground_tex2, 1) self.ground_model.setScale(3) if self.terrain_var == 3: self.ground_model.setTexture(self.ground_tex3, 1) self.ground_model.setScale(4) if self.terrain_var == 4: self.terrain_var = 1 if self.terrain_var == 0: self.terrain_var = 3 def next_terrain(): self.terrain_var = self.terrain_var + 1 def previous_terrain(): self.terrain_var = self.terrain_var - 1 def show_menu(): self.menu_win.show() self.a1.show() self.a2.show() self.a3.show() self.a4.show() self.t1.show() self.t2.show() self.ok.show() self.exit_button.show() def hide_menu(): self.menu_win.hide() self.a1.hide() self.a2.hide() self.a3.hide() self.a4.hide() self.ok.hide() self.t1.hide() self.t2.hide() self.exit_button.hide() def Menu(): self.menu_win = OnscreenImage(image = "Textures/menu.png", pos = (0.9,0,0), scale = (0.5)) self.menu_win.setTransparency(TransparencyAttrib.MAlpha) #The Arrow Buttons self.a1 = DirectButton(text = "<", scale = 0.2, pos = (0.55,0,0.25), command = previous_terrain) self.a2 = DirectButton(text = ">", scale = 0.2, pos = (1.15,0,0.25), command = next_terrain) self.a3 = DirectButton(text = "<", scale = 0.2, pos = (0.55,0,0.0), command = time_backward) self.a4 = DirectButton(text = ">", scale = 0.2, pos = (1.15,0,0.0), command = time_forward) #The Text self.t1 = OnscreenText(text = "Terrain", pos = (0.85,0.25,0), scale = 0.1, fg = (0.4,0.4,0.5,1)) self.t2 = OnscreenText(text = "Time", pos = (0.85,0,0), scale = 0.1, fg = (0.4,0.4,0.5,1)) #The Buttons self.ok = DirectButton(text = "Okay", scale = 0.11, pos = (0.87,0,-0.25), command = hide_menu) self.exit_button = DirectButton(text = "Quit", scale = 0.11, pos = (0.87,0,-0.42), command = sys.exit) Menu() def take_screenshot(): base.screenshot("Screenshot") def set_headlights(): if self.headlight_var == 1: Headlight1.setColor(VBase4(9.0,8.9,8.9,1)) Headlight2.setColor(VBase4(9.0,8.9,8.9,1)) if self.headlight_var == 0: Headlight1.setColor(VBase4(0,0,0,1)) Headlight2.setColor(VBase4(0,0,0,1)) def headlights(): self.headlight_var = (self.headlight_var + 1) % 2 def update_rpm(): #Simulate RPM if self.start == 1: if self.gear == 0: self.RPM = self.RPM - self.RPM / 400 else: self.RPM = self.RPM + self.carspeed / 9 self.RPM = self.RPM - self.RPM / 200 #Reset RPM to 0 when engine is off if self.start == 0: if self.RPM > 0.0: self.RPM = self.RPM - 40 if self.RPM < 10: self.RPM = 0.0 #Idle RPM power if self.start == 1: if self.RPM < 650: self.RPM = self.RPM + 4 if self.RPM < 600: self.clutch = 1 else: self.clutch = 0 #RPM limit if self.RPM > 6000: self.RPM = 6000 #Controls inputState.watchWithModifiers("F", "arrow_up") inputState.watchWithModifiers("B", "arrow_down") inputState.watchWithModifiers("L", "arrow_left") inputState.watchWithModifiers("R", "arrow_right") do = DirectObject() do.accept("escape", show_menu) do.accept("1", V1) do.accept("2", V2) do.accept("3", V3) do.accept("page_up", up) do.accept("page_down", down) do.accept("x-repeat", start_function) do.accept("x", stop_function) do.accept("p", parkingbrake) do.accept("backspace", rotate) do.accept("enter", horn) do.accept("f12", take_screenshot) do.accept("h", headlights) #The ground self.ground = BulletPlaneShape(Vec3(0, 0, 1,), 1) self.ground_node = BulletRigidBodyNode("The ground") self.ground_node.addShape(self.ground) self.ground_np = render.attachNewNode(self.ground_node) self.ground_np.setPos(0, 0, -2) scene.attachRigidBody(self.ground_node) self.ground_model = loader.loadModel("Models/plane.egg") self.ground_model.reparentTo(render) self.ground_model.setPos(0,0,-1) self.ground_model.setScale(3) self.ground_tex = loader.loadTexture("Textures/ground.png") self.ground_tex2 = loader.loadTexture("Textures/ground2.png") self.ground_tex3 = loader.loadTexture("Textures/ground3.png") self.ground_model.setTexture(self.ground_tex, 1) #The car Car_shape = BulletBoxShape(Vec3(1, 2.0, 1.0)) Car_node = BulletRigidBodyNode("The Car") Car_node.setMass(1200.0) Car_node.addShape(Car_shape) Car_np = render.attachNewNode(Car_node) Car_np.setPos(0,0,3) Car_np.setHpr(0,0,0) Car_np.node().setDeactivationEnabled(False) scene.attachRigidBody(Car_node) Car_model = loader.loadModel("Models/Car.egg") Car_model.reparentTo(Car_np) Car_tex = loader.loadTexture("Textures/Car1.png") Car_model.setTexture(Car_tex, 1) self.Car_sim = BulletVehicle(scene, Car_np.node()) self.Car_sim.setCoordinateSystem(ZUp) scene.attachVehicle(self.Car_sim) #The inside of the car Car_int = loader.loadModel("Models/inside.egg") Car_int.reparentTo(Car_np) Car_int_tex = loader.loadTexture("Textures/inside.png") Car_int.setTexture(Car_int_tex, 1) Car_int.setTransparency(TransparencyAttrib.MAlpha) #The steering wheel Sw = loader.loadModel("Models/Steering wheel.egg") Sw.reparentTo(Car_np) Sw.setPos(0.25,0,-0.025) #The first headlight Headlight1 = Spotlight("Headlight1") lens = PerspectiveLens() lens.setFov(180) Headlight1.setLens(lens) Headlight1np = render.attachNewNode(Headlight1) Headlight1np.reparentTo(Car_np) Headlight1np.setPos(-0.8,2.5,-0.5) Headlight1np.setP(-15) render.setLight(Headlight1np) #The second headlight Headlight2 = Spotlight("Headlight2") Headlight2.setLens(lens) Headlight2np = render.attachNewNode(Headlight2) Headlight2np.reparentTo(Car_np) Headlight2np.setPos(0.8,2.5,-0.5) Headlight2np.setP(-15) render.setLight(Headlight2np) #Sounds self.horn_sound = loader.loadSfx("Sounds/horn.ogg") self.start_sound = loader.loadSfx("Sounds/enginestart.ogg") self.engine_idle_sound = loader.loadSfx("Sounds/engineidle.ogg") self.engine_idle_sound.setLoop(True) self.accelerate_sound = loader.loadSfx("Sounds/enginethrottle.ogg") #Camera base.disableMouse() camera.reparentTo(Car_np) camera.setPos(0,-15,3) camera.setHpr(0,-10,0) #Wheel function def Wheel(pos, np, r, f): w = self.Car_sim.createWheel() w.setNode(np.node()) w.setChassisConnectionPointCs(pos) w.setFrontWheel(f) w.setWheelDirectionCs(Vec3(0, 0, -1)) w.setWheelAxleCs(Vec3(1, 0, 0)) w.setWheelRadius(r) w.setMaxSuspensionTravelCm(40) w.setSuspensionStiffness(120) w.setWheelsDampingRelaxation(2.3) w.setWheelsDampingCompression(4.4) w.setFrictionSlip(50) w.setRollInfluence(0.1) #Wheels w1_np = loader.loadModel("Models/Lwheel") w1_np.reparentTo(render) w1_np.setColorScale(0,6) Wheel(Point3(-1,1,-0.6), w1_np, 0.4, False) w2_np = loader.loadModel("Models/Rwheel") w2_np.reparentTo(render) w2_np.setColorScale(0,6) Wheel(Point3(-1.1,-1.2,-0.6), w2_np, 0.4, True) w3_np = loader.loadModel("Models/Lwheel") w3_np.reparentTo(render) w3_np.setColorScale(0,6) Wheel(Point3(1.1,-1,-0.6), w3_np, 0.4, True) w4_np = loader.loadModel("Models/Rwheel") w4_np.reparentTo(render) w4_np.setColorScale(0,6) Wheel(Point3(1,1,-0.6), w4_np, 0.4, False) #The engine and steering def processInput(dt): #Vehicle properties self.steeringClamp = 35.0 self.steeringIncrement = 70 engineForce = 0.0 brakeForce = 0.0 #Get the vehicle's current speed self.carspeed = self.Car_sim.getCurrentSpeedKmHour() #Engage clutch when in gear 0 if self.gear == 0: self.clutch = 1 #Slow the steering when at higher speeds self.steeringIncrement = self.steeringIncrement - self.carspeed / 1.5 #Reset the steering if not inputState.isSet("L") and not inputState.isSet("R"): if self.steering < 0.00: self.steering = self.steering + 0.6 if self.steering > 0.00: self.steering = self.steering - 0.6 if self.steering < 1.0 and self.steering > -1.0: self.steering = 0 #Slow the car down while it's moving if self.clutch == 0: brakeForce = brakeForce + self.carspeed / 5 else: brakeForce = brakeForce + self.carspeed / 15 #Forward if self.start == 1: if inputState.isSet("F"): self.RPM = self.RPM + 35 self.accelerate_sound.play() if self.clutch == 0: if self.gear == -1: if self.carspeed > self.carmaxreversespeed: engineForce = -self.RPM / 3 if self.gear == 1: if self.carspeed < self.carmaxspeed: engineForce = self.RPM / 1 #Brake if inputState.isSet("B"): engineForce = 0.0 brakeForce = 12.0 if self.gear != 0 and self.clutch == 0: self.RPM = self.RPM - 20 #Left if inputState.isSet("L"): if self.steering < 0.0: #This makes the steering reset at the correct speed when turning from right to left self.steering += dt * self.steeringIncrement + 0.6 self.steering = min(self.steering, self.steeringClamp) else: #Normal steering self.steering += dt * self.steeringIncrement self.steering = min(self.steering, self.steeringClamp) #Right if inputState.isSet("R"): if self.steering > 0.0: #This makes the steering reset at the correct speed when turning from left to right self.steering -= dt * self.steeringIncrement + 0.6 self.steering = max(self.steering, -self.steeringClamp) else: #Normal steering self.steering -= dt * self.steeringIncrement self.steering = max(self.steering, -self.steeringClamp) #Park if self.Pbrake == 1: brakeForce = 10.0 if self.gear != 0 and self. clutch == 0: self.RPM = self.RPM - 20 #Apply forces to wheels self.Car_sim.applyEngineForce(engineForce, 0); self.Car_sim.applyEngineForce(engineForce, 3); self.Car_sim.setBrake(brakeForce, 1); self.Car_sim.setBrake(brakeForce, 2); self.Car_sim.setSteeringValue(self.steering, 0); self.Car_sim.setSteeringValue(self.steering, 3); #Steering wheel Sw.setHpr(0,0,-self.steering*10) #The HUD self.gear_hud = OnscreenImage(image = "Textures/gear_hud.png", pos = (-1,0,-0.85), scale = (0.2)) self.gear_hud.setTransparency(TransparencyAttrib.MAlpha) self.gear2_hud = OnscreenImage(image = "Textures/gear2_hud.png", pos = (-1,0,-0.85), scale = (0.2)) self.gear2_hud.setTransparency(TransparencyAttrib.MAlpha) self.starter = OnscreenImage(image = "Textures/starter.png", pos = (-1.2,0,-0.85), scale = (0.15)) self.starter.setTransparency(TransparencyAttrib.MAlpha) self.park = OnscreenImage(image = "Textures/pbrake.png", pos = (-0.8,0,-0.85), scale = (0.1)) self.park.setTransparency(TransparencyAttrib.MAlpha) self.rev_counter = OnscreenImage(image = "Textures/dial.png", pos = (-1.6, 0.0, -0.70), scale = (0.6,0.6,0.4)) self.rev_counter.setTransparency(TransparencyAttrib.MAlpha) self.rev_needle = OnscreenImage(image = "Textures/needle.png", pos = (-1.6, 0.0, -0.70), scale = (0.5)) self.rev_needle.setTransparency(TransparencyAttrib.MAlpha) self.rev_text = OnscreenText(text = " ", pos = (-1.6, -0.90, 0), scale = 0.05) self.speedometer = OnscreenImage(image = "Textures/dial.png", pos = (-1.68, 0.0, -0.10), scale = (0.7,0.7,0.5)) self.speedometer.setTransparency(TransparencyAttrib.MAlpha) self.speedometer_needle = OnscreenImage(image = "Textures/needle.png", pos = (-1.68, 0.0, -0.10), scale = (0.5)) self.speedometer_needle.setTransparency(TransparencyAttrib.MAlpha) self.speedometer_text = OnscreenText(text = " ", pos = (-1.68, -0.35, 0), scale = 0.05) #Update the HUD def Update_HUD(): #Move gear selector if self.gear == -1: self.gear2_hud.setPos(-1,0,-0.785) if self.gear == 0: self.gear2_hud.setPos(-1,0,-0.85) if self.gear == 1: self.gear2_hud.setPos(-1,0,-0.91) #Rotate starter if self.start == 0: self.starter.setHpr(0,0,0) else: self.starter.setHpr(0,0,45) #Update the parking brake light if self.Pbrake == 1: self.park.setImage("Textures/pbrake2.png") self.park.setTransparency(TransparencyAttrib.MAlpha) else: self.park.setImage("Textures/pbrake.png") self.park.setTransparency(TransparencyAttrib.MAlpha) #Update the rev counter self.rev_needle.setR(self.RPM/22) rev_string = str(self.RPM)[:4] self.rev_text.setText(rev_string+" RPM") #Update the speedometer if self.carspeed > 0.0: self.speedometer_needle.setR(self.carspeed*2.5) if self.carspeed < 0.0: self.speedometer_needle.setR(-self.carspeed*2.5) speed_string = str(self.carspeed)[:3] self.speedometer_text.setText(speed_string+" KPH") #Update the program def update(task): dt = globalClock.getDt() processInput(dt) Update_HUD() set_time() set_terrain() set_headlights() update_rpm() scene.doPhysics(dt, 5, 1.0/180.0) return task.cont taskMgr.add(update, "Update")
def __init__(self, app): self.app = app camera.setPos(0, -62, 12) camera.setHpr(0, -10, 0) #lights dlghtnode = DirectionalLight("dir light") dlghtnode.setColor(Vec4(0.8, 0.8, 0.8, 1)) dlght_top = render.attachNewNode(dlghtnode) dlght_top.setHpr(0, -70, 0) render.setLight(dlght_top) self.app.lst_lghts.append(dlght_top) dlght_right = render.attachNewNode(dlghtnode) dlght_right.setHpr(-30, -10, 0) render.setLight(dlght_right) self.app.lst_lghts.append(dlght_right) dlght_left = render.attachNewNode(dlghtnode) dlght_left.setHpr(30, -10, 0) render.setLight(dlght_left) self.app.lst_lghts.append(dlght_left) spotnode = Spotlight("spot_aux_menu") spotnode.setColor(Vec4(0.8, 0.8, 0.8, 1)) lens = PerspectiveLens() spotnode.setLens(lens) spotlght = render.attachNewNode(spotnode) render.setLight(spotlght) spotlght.lookAt(6, -0.5, -1.5) spotlght.setPos(-8, 0, 9) self.app.lst_lghts.append(spotlght) #decors self.lst_decor = [] arcs_shower = loader.loadModel("models/static/main_arcs_show") arcs_shower.reparentTo(render) arcs_shower.setPos(0, 7.3, 3) self.lst_decor.append(arcs_shower) arcs_shower_hprInterv = arcs_shower.hprInterval(5, Point3(360, 0, 0), startHpr=Point3( 0, 0, 0)) arcs_shower_pace = Sequence(arcs_shower_hprInterv, name="arcs_shower_pace") arcs_shower_pace.loop() arc_title = loader.loadModel("models/static/main_title") arc_title.reparentTo(render) self.lst_decor.append(arc_title) #arc_main_menu self.arc_main_menu = Actor("models/dynamic/main_m_menu") self.arc_main_menu.reparentTo(render) self.arc_main_menu.pose("load", 1) #arc_aux_menu self.arc_aux_menu = Actor("models/dynamic/main_a_menu") self.arc_aux_menu.reparentTo(render) self.arc_aux_menu.pose("load", 1) #arrows for main menu arr_up = render.attachNewNode("arrow-up") arr_up.setHpr(0, 90, 0) arr_up.setPos(4.5, 1.5, 7) arr_up.hide() self.app.arrow.instanceTo(arr_up) arr_up.reparentTo(render) self.app.lst_arrows.append({ "name": "arr_up", "status": 0, "node": arr_up, "posn": [4.5, 1.5, 7], "posh": [4.5, 1.7, 7.2] }) sqp_up = render.attachNewNode(self.app.c_arr.generate()) sqp_up.hide() sqp_up.node().setIntoCollideMask(BitMask32.bit(1)) sqp_up.node().setTag("arrow", "up") sqp_up.reparentTo(self.app.pickly_node) sqp_up.setPos(4.5, 1.5, 7) arr_dn = render.attachNewNode("arrow-dn") arr_dn.setHpr(180, -90, 0) arr_dn.setPos(4.5, 1.5, 5) arr_dn.hide() self.app.arrow.instanceTo(arr_dn) arr_dn.reparentTo(render) self.app.lst_arrows.append({ "name": "arr_dn", "status": 0, "node": arr_dn, "posn": [4.5, 1.5, 5], "posh": [4.5, 1.7, 4.8] }) sqp_dn = render.attachNewNode(self.app.c_arr.generate()) sqp_dn.hide() sqp_dn.node().setIntoCollideMask(BitMask32.bit(1)) sqp_dn.node().setTag("arrow", "dn") sqp_dn.reparentTo(self.app.pickly_node) sqp_dn.setPos(4.5, 1.5, 5.2) #arrows for campaign menu arr_camp_up = render.attachNewNode("arr-camp-up") arr_camp_up.setScale(0.5) arr_camp_up.setHpr(-90, 90, 0) arr_camp_up.setPos(8, -2.5, 7) arr_camp_up.hide() self.app.arrow.instanceTo(arr_camp_up) arr_camp_up.reparentTo(render) self.app.lst_arrows.append({ "name": "arr_camp_up", "status": 0, "node": arr_camp_up, "posn": [8, -2.5, 7], "posh": [8.1, -2.5, 7.1] }) sqp_c_up = render.attachNewNode(self.app.c_arr.generate()) sqp_c_up.hide() sqp_c_up.node().setIntoCollideMask(BitMask32.bit(1)) sqp_c_up.node().setTag("arrow_c", "up") sqp_c_up.reparentTo(self.app.pickly_node) sqp_c_up.setScale(0.5) sqp_c_up.setHpr(-90, 0, 0) sqp_c_up.setPos(8, -2.5, 7) arr_camp_dn = render.attachNewNode("arr-camp-dn") arr_camp_dn.setScale(0.5) arr_camp_dn.setHpr(90, -90, 0) arr_camp_dn.setPos(8, -2.5, 2) arr_camp_dn.hide() self.app.arrow.instanceTo(arr_camp_dn) arr_camp_up.reparentTo(render) self.app.lst_arrows.append({ "name": "arr_camp_dn", "status": 0, "node": arr_camp_dn, "posn": [8, -2.5, 2], "posh": [8.1, -2.5, 1.9] }) sqp_c_dn = render.attachNewNode(self.app.c_arr.generate()) sqp_c_dn.hide() sqp_c_dn.node().setIntoCollideMask(BitMask32.bit(1)) sqp_c_dn.node().setTag("arrow_c", "dn") sqp_c_dn.reparentTo(self.app.pickly_node) sqp_c_dn.setScale(0.5) sqp_c_dn.setHpr(-90, 0, 0) sqp_c_dn.setPos(8, -2.5, 2.1) #arrows for missions menu # #TODO : arrows up/down for mission selection # #TODO : arrows up/down for save selection # # #gates self.gates = Actor("models/dynamic/main_gates") self.gates.reparentTo(render) self.gates.setPos(0, -48.2, 9.5) self.gates.setHpr(0, 80, 0) self.gates.play("open_gates") #env self.sol = base.loader.loadModel("models/static/main_sol") self.sol.reparentTo(render) self.sol.setPos(0, 0, 0) self.roofs = base.loader.loadModel("models/static/main_roofs") self.roofs.reparentTo(render) self.roofs.setPos(0, 0, 0) #GUI self.lst_menus = [ 0, 0, 0 ] #0 -> which menu, 1 -> val main_menu, 2 -> val aux_menu self.lst_gui = { "frames": [], "main_frame": [], "camp_frame": [], "mission_frame": [], "option_frame": [], "saves": [] } #GUI : frames main_frame = DirectFrame() main_frame.hide() self.lst_gui["frames"].append(main_frame) camp_frame = DirectFrame() camp_frame.hide() self.lst_gui["frames"].append(camp_frame) mission_frame = DirectFrame() mission_frame.hide() self.lst_gui["frames"].append(mission_frame) option_frame = DirectFrame() option_frame.hide() self.lst_gui["frames"].append(option_frame) #GUI : main menu campaign_btn = arcButton(self.app.lang["main_menu"]["campaign"], (-0.15, 0, -0.2), self.valid_main_menu, scale=0.12) campaign_btn.reparentTo(main_frame) campaign_btn["state"] = DGG.DISABLED self.lst_gui["main_frame"].append(campaign_btn) mission_btn = arcButton(self.app.lang["main_menu"]["mission"], (-0.19, 0, -0.34), self.valid_main_menu, scale=0.1) mission_btn.reparentTo(main_frame) mission_btn["state"] = DGG.DISABLED self.lst_gui["main_frame"].append(mission_btn) options_btn = arcButton(self.app.lang["main_menu"]["options"], (-0.26, 0, -0.47), self.valid_main_menu, scale=0.09) options_btn.reparentTo(main_frame) options_btn["state"] = DGG.DISABLED self.lst_gui["main_frame"].append(options_btn) quit_btn = arcButton(self.app.lang["main_menu"]["quit"], (-0.35, 0, -0.58), self.valid_main_menu, scale=0.07) quit_btn.reparentTo(main_frame) quit_btn["state"] = DGG.DISABLED self.lst_gui["main_frame"].append(quit_btn) #GUI : aux_menu -> campaign camp_stitre = arcLabel(self.app.lang["camp_menu"]["stitre"], (-1, 0, 0.7), 0.13) camp_stitre.reparentTo(camp_frame) self.lst_gui["camp_frame"].append(camp_stitre) camp_create_lab = arcLabel(self.app.lang["camp_menu"]["new_unit"], (-1.1, 0, 0.4)) camp_create_lab.reparentTo(camp_frame) self.lst_gui["camp_frame"].append(camp_create_lab) camp_entry = arcEntry((-1, 0, 0.25), cmd=self.crea_unit) camp_entry.reparentTo(camp_frame) self.lst_gui["camp_frame"].append(camp_entry) camp_create = arcButton(self.app.lang["camp_menu"]["crea_unit"], (-0.3, 0, 0.4), self.crea_unit) camp_create.reparentTo(camp_frame) self.lst_gui["camp_frame"].append(camp_create) camp_used = arcLabel(self.app.lang["camp_menu"]["used_name"], (-1, 0, 0.1)) camp_used.reparentTo(camp_frame) camp_used.hide() self.lst_gui["camp_frame"].append(camp_used) camp_select_lab = arcLabel(self.app.lang["camp_menu"]["sel_lab"], (0.1, 0, 0.4)) camp_select_lab.reparentTo(camp_frame) self.lst_gui["camp_frame"].append(camp_select_lab) camp_play = arcButton(self.app.lang["camp_menu"]["launch"], (0, 0, -0.2), self.valid_aux_menu) camp_play.hide() camp_play.reparentTo(camp_frame) self.lst_gui["camp_frame"].append(camp_play) camp_remove = arcButton(self.app.lang["camp_menu"]["supp_unit"], (0.3, 0, -0.2), self.supp_unit) camp_remove.hide() camp_remove.reparentTo(camp_frame) self.lst_gui["camp_frame"].append(camp_remove) camp_nosave = arcLabel(self.app.lang["camp_menu"]["no_unit"], (0, 0, 0)) camp_nosave.hide() camp_nosave.reparentTo(camp_frame) self.lst_gui["camp_frame"].append(camp_nosave) camp_cancel = arcButton(self.app.lang["aux_menu"]["return_btn"], (-1, 0, -0.7), self.aux_quitmenu) camp_cancel.reparentTo(camp_frame) self.lst_gui["camp_frame"].append(camp_cancel) camp_time = arcLabel("", (1.25, 0, 0), 0.07, TextNode.ARight) camp_time.hide() camp_time.reparentTo(camp_frame) self.lst_gui["camp_frame"].append(camp_time) camp_date = arcLabel("", (1.25, 0, -0.08), 0.07, TextNode.ARight) camp_date.hide() camp_date.reparentTo(camp_frame) self.lst_gui["camp_frame"].append(camp_date) #GUI : aux_menu -> missions mission_stitre = arcLabel(self.app.lang["mission_menu"]["stitre"], (-1, 0, 0.7), 0.13) mission_stitre.reparentTo(mission_frame) self.lst_gui["mission_frame"].append(mission_stitre) # # #TODO : all the mission form is missing # # mission_cancel = arcButton(self.app.lang["aux_menu"]["return_btn"], (-1, 0, -0.7), self.aux_quitmenu) mission_cancel.reparentTo(mission_frame) self.lst_gui["mission_frame"].append(mission_cancel) #GUI : aux_menu -> options option_stitre = arcLabel(self.app.lang["option_menu"]["stitre"], (-1, 0, 0.7), 0.13) option_stitre.reparentTo(option_frame) self.lst_gui["option_frame"].append(option_stitre) self.opt_var = { "chg": [False, False, False], "fullscreen": [self.app.main_config["fullscreen"]], "size_chx": self.app.main_config["size_chx"], "lang_chx": self.app.main_config["lang_chx"] } lst_rad = [[ self.app.lang["option_menu"]["windowed"], self.opt_var["fullscreen"], [False], self.opt_change, [0], (-1.1, 0, 0.4) ], [ self.app.lang["option_menu"]["fullscreen"], self.opt_var["fullscreen"], [True], self.opt_change, [0], (-1.1, 0, 0.3) ]] arcRadioButton(lst_rad, option_frame, self.lst_gui["option_frame"]) self.lst_gui["option_frame"][1]["indicatorValue"] = ( 0 if self.opt_var["fullscreen"][0] else 1) self.lst_gui["option_frame"][2]["indicatorValue"] = ( 1 if self.opt_var["fullscreen"][0] else 0) opt_chx_res_lab = arcLabel(self.app.lang["option_menu"]["res_chx"], (-1.1, 0, 0)) opt_chx_res_lab.reparentTo(option_frame) self.lst_gui["option_frame"].append(opt_chx_res_lab) opt_chx_res = arcOptMenu( self.app.main_config["size"][self.app.main_config["size_chx"]], (-0.4, 0, 0), self.app.main_config["size"], init=self.app.main_config["size_chx"], cmd=self.opt_change, extraArgs=[1]) opt_chx_res.reparentTo(option_frame) self.lst_gui["option_frame"].append(opt_chx_res) opt_chx_lang_lab = arcLabel(self.app.lang["option_menu"]["lang_chx"], (-1.1, 0, -0.2)) opt_chx_lang_lab.reparentTo(option_frame) self.lst_gui["option_frame"].append(opt_chx_lang_lab) lst_lang = [] for elt in self.app.main_config["lang"]: lst_lang.append(elt[1]) opt_chx_lang = arcOptMenu( self.app.main_config["lang"][self.app.main_config["lang_chx"]][1], (-0.4, 0, -0.2), lst_lang, init=self.app.main_config["lang_chx"], cmd=self.opt_change, extraArgs=[2]) opt_chx_lang.reparentTo(option_frame) self.lst_gui["option_frame"].append(opt_chx_lang) opt_valid = arcButton(self.app.lang["option_menu"]["btn_valid"], (0, 0, -0.7), self.opt_action, extraArgs=[0]) opt_valid["state"] = DGG.DISABLED opt_valid.reparentTo(option_frame) self.lst_gui["option_frame"].append(opt_valid) opt_reset = arcButton(self.app.lang["option_menu"]["btn_reset"], (0.4, 0, -0.7), self.opt_action, extraArgs=[1]) opt_reset["state"] = DGG.DISABLED opt_reset.reparentTo(option_frame) self.lst_gui["option_frame"].append(opt_reset) option_cancel = arcButton(self.app.lang["aux_menu"]["return_btn"], (-1, 0, -0.7), self.aux_quitmenu) option_cancel.reparentTo(option_frame) self.lst_gui["option_frame"].append(option_cancel) #delayed tasks taskMgr.doMethodLater(6.5, self.main_start_task, "main start task") taskMgr.doMethodLater(9, self.main_stmm_task, "main start main menu task") taskMgr.doMethodLater(11, self.main_affmm_task, "main aff main menu task")