def generate(self, helperInfo): color = self.mapObject.getPropertyValue("_light", default=Vec4( 255, 255, 255, 255)) color = CIGlobals.colorFromRGBScalar255(color) color = CIGlobals.vec3GammaToLinear(color) constant = float( self.mapObject.getPropertyValue("_constant_attn", default="0.0")) linear = float( self.mapObject.getPropertyValue("_linear_attn", default="0.0")) quadratic = float( self.mapObject.getPropertyValue("_quadratic_attn", default="1.0")) # Scale intensity for unit 100 distance ratio = (constant + 100 * linear + 100 * 100 * quadratic) if ratio > 0: color *= ratio pl = Spotlight("lightHelper-light_spot") pl.setColor(Vec4(color[0], color[1], color[2], 1.0)) pl.setAttenuation(Vec3(constant, linear, quadratic)) pl.setExponent(self.mapObject.getPropertyValue("_exponent")) pl.setMaxDistance(self.mapObject.getPropertyValue("_distance")) pl.getLens().setFov(self.mapObject.getPropertyValue("_cone")) pl.getLens().setViewHpr(0, -90, 0) self.light = self.mapObject.helperRoot.attachNewNode(pl) if self.mapObject.doc.numlights < 64: self.mapObject.doc.render.setLight(self.light) self.mapObject.doc.numlights += 1 self.hasLight = True
def setup_world_lightning(self): """ Sets up the ambient and specular lighting of the world :return: """ ambientLight = AmbientLight("ambientLight") ambientLight.setColor((2, 2, 2, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setShadowCaster(True) directionalLight.setDirection(LVector3(-1, -1, -1)) directionalLight.setColor((.5, .5, .5, 1)) dir_light_node = self.render.attachNewNode(directionalLight) # dir_light_node.setPos(10, 2, 7) # dir_light_node.lookAt(2, 2, 0) self.render.setLight(dir_light_node) self.render.setLight(self.render.attachNewNode(ambientLight)) spot = Spotlight("Spot") spot.setColorTemperature(9000) spot.setColor(LVector3(1, 1, 1)) light = self.render.attachNewNode(spot) light.node().setScene(self.render) light.node().setShadowCaster(True) # light.node().showFrustum() light.node().getLens().setFov(40) light.node().getLens().setNearFar(2, 100) # light.setPos(10, 2, 7) light.setPos(10, 20, 20) light.lookAt(2, 2, 0) self.render.setLight(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 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 _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 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 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 set_spotlight(self, col, exp, cutoff, pos, look_at): lgt = Spotlight('spotlight') lgt.setColor(col) lgt.setExponent(exp) lgt.getLens().setFov(cutoff, cutoff) self.__set_lgt(lgt) self.lights[-1].setPos(*pos) self.lights[-1].lookAt(*look_at)
def makeSpotlight(name, color, pos, hpr): spot = Spotlight(name + "-spotlight") spot.setColor(color) if metadata.USE_REAL_SHADOWS: spot.setShadowCaster(True, 512, 512) snp = render.attachNewNode(spot) snp.setHpr(hpr) snp.setPos(pos) return snp
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 __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 __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 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): # 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 setup_lights(self): pl = PointLight('pl') pl.setColor((1, 1, 1, 1)) plNP = self.render.attachNewNode(pl) plNP.setPos(-10, -10, 10) self.render.setLight(plNP) pos = [[[0, 0, 50], [0, 0, -10]], [[0, -50, 0], [0, 10, 0]], [[-50, 0, 0], [10, 0, 0]]] for i in pos: dl = Spotlight('dl') dl.setColor((1, 1, 1, 1)) dlNP = self.render.attachNewNode(dl) dlNP.setPos(*i[0]) dlNP.lookAt(*i[1]) dlNP.node().setShadowCaster(False) self.render.setLight(dlNP)
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.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 setup_lights(self): pl = PointLight('pl') pl.setColor((1, 1, 1, 1)) plNP = render.attachNewNode(pl) plNP.setPos(0, 0, 0) render.setLight(plNP) # make shadows less black al = AmbientLight('al') al.setColor((0.1, 0.1, 0.1, 1)) alNP = render.attachNewNode(al) render.setLight(alNP) positions = [[[0, 0, 3], [0, 0, -1]], [[0, -3, 0], [0, 1, 0]], [[-3, 0, 0], [1, 0, 0]]] # set up directional lights (shadow casting) for i in positions: dl = Spotlight('dl') dl.setColor((1, 1, 1, 1)) dlNP = render.attachNewNode(dl) dlNP.setPos(*i[0]) # unpack the args dlNP.lookAt(*i[1]) dlNP.node().setShadowCaster(True) render.setLight(dlNP)
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
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
makeFractalTree(bodydata, nodePath, length, newPos, 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)
class MyApp(ShowBase): def __init__(self, screen_size=84, DEBUGGING=False): ShowBase.__init__(self) self.render_stuff = True self.actions = 3 self.render.setShaderAuto() self.cam.setPos(0, 0, 7) self.cam.lookAt(0, 0, 0) wp = WindowProperties() window_size = screen_size wp.setSize(window_size, window_size) self.win.requestProperties(wp) # Create Ambient Light self.ambientLight = AmbientLight('ambientLight') self.ambientLight.setColor((0.2, 0.2, 0.2, 1)) self.ambientLightNP = self.render.attachNewNode(self.ambientLight) self.render.setLight(self.ambientLightNP) # Spotlight self.light = Spotlight('light') self.light.setColor((0.9, 0.9, 0.9, 1)) self.lightNP = self.render.attachNewNode(self.light) self.lightNP.setPos(0, 10, 10) self.lightNP.lookAt(0, 0, 0) self.lightNP.node().getLens().setFov(40) self.lightNP.node().getLens().setNearFar(10, 100) self.lightNP.node().setShadowCaster(True, 1024, 1024) self.render.setLight(self.lightNP) self.world = BulletWorld() self.world.setGravity(Vec3(0, 0, -9.81)) if DEBUGGING is True: debugNode = BulletDebugNode('Debug') debugNode.showWireframe(True) debugNode.showConstraints(True) debugNode.showBoundingBoxes(False) debugNode.showNormals(False) debugNP = render.attachNewNode(debugNode) debugNP.show() self.world.setDebugNode(debugNP.node()) # Reward zone self.rzone_shape = BulletBoxShape(Vec3(.8, 1, 0.5)) self.rzone_ghost = BulletGhostNode('Reward Zone') self.rzone_ghost.addShape(self.rzone_shape) self.rzone_ghostNP = self.render.attachNewNode(self.rzone_ghost) self.rzone_ghostNP.setPos(2.2, 0.0, 0.86) self.rzone_ghostNP.setCollideMask(BitMask32(0x0f)) self.world.attachGhost(self.rzone_ghost) # Needed for camera image self.dr = self.camNode.getDisplayRegion(0) # Needed for camera depth image winprops = WindowProperties.size(self.win.getXSize(), self.win.getYSize()) fbprops = FrameBufferProperties() fbprops.setDepthBits(1) self.depthBuffer = self.graphicsEngine.makeOutput( self.pipe, "depth buffer", -2, fbprops, winprops, GraphicsPipe.BFRefuseWindow, self.win.getGsg(), self.win) self.depthTex = Texture() self.depthTex.setFormat(Texture.FDepthComponent) self.depthBuffer.addRenderTexture(self.depthTex, GraphicsOutput.RTMCopyRam, GraphicsOutput.RTPDepth) lens = self.cam.node().getLens() # the near and far clipping distances can be changed if desired # lens.setNear(5.0) # lens.setFar(500.0) self.depthCam = self.makeCamera(self.depthBuffer, lens=lens, scene=render) self.depthCam.reparentTo(self.cam) def reset(self): namelist = [ 'Ground', 'Conveyor', 'Finger', 'Block', 'Scrambled Block', 'Not Rewardable', 'Teleport Me' ] for child in render.getChildren(): for test in namelist: if child.node().name == test: self.world.remove(child.node()) child.removeNode() break # Plane self.plane_shape = BulletPlaneShape(Vec3(0, 0, 1), 1) self.plane_node = BulletRigidBodyNode('Ground') self.plane_node.addShape(self.plane_shape) self.plane_np = self.render.attachNewNode(self.plane_node) self.plane_np.setPos(0.0, 0.0, -1.0) self.world.attachRigidBody(self.plane_node) # Conveyor self.conv_node = BulletRigidBodyNode('Conveyor') self.conv_node.setFriction(1.0) self.conv_np = self.render.attachNewNode(self.conv_node) self.conv_shape = BulletBoxShape(Vec3(100.0, 1.0, 0.05)) self.conv_node.setMass(1000.0) self.conv_np.setPos(-95.0, 0.0, 0.1) self.conv_node.addShape(self.conv_shape) self.world.attachRigidBody(self.conv_node) self.model = loader.loadModel('assets/conv.egg') self.model.flattenLight() self.model.reparentTo(self.conv_np) # Finger self.finger_node = BulletRigidBodyNode('Finger') self.finger_node.setFriction(1.0) self.finger_np = self.render.attachNewNode(self.finger_node) self.finger_shape = BulletCylinderShape(0.1, 0.25, ZUp) self.finger_node.setMass(0) self.finger_np.setPos(1.8, 0.0, 0.24 + 0.0254 * 3.5) self.finger_node.addShape(self.finger_shape) self.world.attachRigidBody(self.finger_node) self.model = loader.loadModel('assets/finger.egg') self.model.flattenLight() self.model.reparentTo(self.finger_np) self.blocks = [] for block_num in range(15): new_block = self.spawn_block(Vec3(18, 0, (0.2 * block_num) + 2.0)) self.blocks.append(new_block) self.have_scramble = False self.penalty_applied = False self.spawnned = False self.score = 10 self.teleport_cooled_down = True self.fps = 20 self.framecount = 0 return self.step(1)[0] def spawn_block(self, location): node = BulletRigidBodyNode('Block') node.setFriction(1.0) block_np = self.render.attachNewNode(node) block_np.setAntialias(AntialiasAttrib.MMultisample) shape = BulletBoxShape(Vec3(0.0254 * 4, 0.0254 * 24, 0.0254 * 2)) node.setMass(1.0) #block_np.setPos(-3.7, 0.0, 2.0) block_np.setPos(location) block_np.setHpr(random.uniform(-60, 60), 0.0, 0.0) node.addShape(shape) self.world.attachRigidBody(node) model = loader.loadModel('assets/bullet-samples/models/box.egg') model.setH(90) model.setSy(0.0254 * 4 * 2) model.setSx(0.0254 * 24 * 2) model.setSz(0.0254 * 2 * 2) model.flattenLight() model.reparentTo(block_np) return block_np def get_camera_image(self, requested_format=None): """ Returns the camera's image, which is of type uint8 and has values between 0 and 255. The 'requested_format' argument should specify in which order the components of the image must be. For example, valid format strings are "RGBA" and "BGRA". By default, Panda's internal format "BGRA" is used, in which case no data is copied over. """ tex = self.dr.getScreenshot() if requested_format is None: data = tex.getRamImage() else: data = tex.getRamImageAs(requested_format) image = np.frombuffer( data, np.uint8) # use data.get_data() instead of data in python 2 image.shape = (tex.getYSize(), tex.getXSize(), tex.getNumComponents()) image = np.flipud(image) return image[:, :, :3] def reset_conv(self): conveyor_dist_left = 1 - self.conv_np.getPos()[0] if conveyor_dist_left < 10: self.conv_np.setX(-95.0) self.conv_np.setY(0.0) # self.conv_np.setY(0.0) # self.conv_np.setHpr(0.0, 0.0, 0.0) def check_penalty(self): penalty = 0 self.pzone_ghost = self.pzone_ghostNP.node() for node in self.pzone_ghost.getOverlappingNodes(): if node.name == 'Block': penalty = 1 node.name = 'Scramble' self.have_scramble = False return penalty def check_rewards(self): reward = 0 # Check for reward blocks (recently cleared scrambles) rzone_ghost = self.rzone_ghostNP.node() scrambled = False for node in rzone_ghost.getOverlappingNodes(): if node.name == 'Block' or node.name == 'Scrambled Block': node.name = 'Scrambled Block' scrambled = True # Rename blocks that are not eligable for reward due to being too late for block in self.blocks: block_x = block.getPos()[0] block_name = block.node().name if block_x > 2.4 and block_name == 'Scrambled Block': self.have_scramble = False scrambled = False block.node().name = 'Not Rewardable' if scrambled is True: self.have_scramble = True else: if self.have_scramble is True: reward = 1 self.have_scramble = False return reward def check_teleportable(self, blocks_per_minute): self.time = self.framecount / self.fps if self.time % (1 / (blocks_per_minute / 60)) < 0.1: self.time_to_teleport = True else: self.time_to_teleport = False self.teleport_cooled_down = True for block in self.blocks: block_x = block.getPos()[0] if block_x > 5: if block.node().name == 'Scrambled Block': self.have_scramble = False block.node().name = 'Teleport Me' if self.time_to_teleport is True and self.teleport_cooled_down is True: self.teleport_cooled_down = False block.setX(-4) block.setY(0.0) block.setZ(2.0) block.setHpr(random.uniform(-60, 60), 0.0, 0.0) block.node().name = 'Block' def step(self, action): dt = 1 / self.fps self.framecount += 1 finger_meters_per_second = 2 max_dist = 1.1 real_displacement = finger_meters_per_second * dt # Move finger if action == 0: self.finger_np.setY(self.finger_np.getY() + real_displacement) if self.finger_np.getY() > max_dist: self.finger_np.setY(max_dist) if action == 2: self.finger_np.setY(self.finger_np.getY() - real_displacement) if self.finger_np.getY() < -max_dist: self.finger_np.setY(-max_dist) self.world.doPhysics(dt, 5, 1.0 / 120.0) self.reset_conv() self.check_teleportable(blocks_per_minute=1.1 * 60) # Keep the conveyor moving self.conv_np.node().setLinearVelocity(Vec3(1.0, 0.0, 0.0)) if self.render_stuff == True: self.graphicsEngine.renderFrame() image = self.get_camera_image() # image = cv2.resize(image, (84, 84), interpolation=cv2.INTER_CUBIC) score = 0 score += self.check_rewards() #score -= self.check_penalty() done = False return image, score, done
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")
class MyApp(ShowBase): def __init__(self, screen_size=84, DEBUGGING=False, human_playable=False): ShowBase.__init__(self) self.forward_button = KeyboardButton.ascii_key(b'w') self.backward_button = KeyboardButton.ascii_key(b's') self.fps = 20 self.human_playable = human_playable self.actions = 3 self.last_frame_start_time = time.time() self.action_buffer = [1, 1, 1] self.last_teleport_time = 0.0 self.time_to_teleport = False if self.human_playable is False: winprops = WindowProperties.size(screen_size, screen_size) fbprops = FrameBufferProperties() fbprops.set_rgba_bits(8, 8, 8, 0) fbprops.set_depth_bits(24) self.pipe = GraphicsPipeSelection.get_global_ptr().make_module_pipe('pandagl') self.imageBuffer = self.graphicsEngine.makeOutput( self.pipe, "image buffer", 1, fbprops, winprops, GraphicsPipe.BFRefuseWindow) self.camera = Camera('cam') self.cam = NodePath(self.camera) self.cam.reparentTo(self.render) self.dr = self.imageBuffer.makeDisplayRegion() self.dr.setCamera(self.cam) self.render.setShaderAuto() self.cam.setPos(0.5, 0, 6) self.cam.lookAt(0.5, 0, 0) # Create Ambient Light self.ambientLight = AmbientLight('ambientLight') self.ambientLight.setColor((0.2, 0.2, 0.2, 1)) self.ambientLightNP = self.render.attachNewNode(self.ambientLight) self.render.setLight(self.ambientLightNP) # Spotlight self.light = Spotlight('light') self.light.setColor((0.9, 0.9, 0.9, 1)) self.lightNP = self.render.attachNewNode(self.light) self.lightNP.setPos(0, 10, 10) self.lightNP.lookAt(0, 0, 0) self.lightNP.node().getLens().setFov(40) self.lightNP.node().getLens().setNearFar(10, 100) self.lightNP.node().setShadowCaster(True, 1024, 1024) self.render.setLight(self.lightNP) self.world = BulletWorld() self.world.setGravity(Vec3(0, 0, -9.81)) if DEBUGGING is True: debugNode = BulletDebugNode('Debug') debugNode.showWireframe(True) debugNode.showConstraints(True) debugNode.showBoundingBoxes(False) debugNode.showNormals(False) debugNP = render.attachNewNode(debugNode) debugNP.show() self.world.setDebugNode(debugNP.node()) self.finger_speed_mps = 0.0 self.penalty_applied = False self.teleport_cooled_down = True self.fps = 20 self.framecount = 0 self.reset() def reset(self): namelist = ['Ground', 'Conveyor', 'Finger', 'Block', 'Scrambled Block', 'Not Rewardable', 'Teleport Me'] for child in self.render.getChildren(): for test in namelist: if child.node().name == test: self.world.remove(child.node()) child.removeNode() break # Plane self.plane_shape = BulletPlaneShape(Vec3(0, 0, 1), 1) self.plane_node = BulletRigidBodyNode('Ground') self.plane_node.addShape(self.plane_shape) self.plane_np = self.render.attachNewNode(self.plane_node) self.plane_np.setPos(0.0, 0.0, -1.0) self.world.attachRigidBody(self.plane_node) # Conveyor self.conv_node = BulletRigidBodyNode('Conveyor') self.conv_node.setFriction(1.0) self.conv_np = self.render.attachNewNode(self.conv_node) self.conv_shape = BulletBoxShape(Vec3(100.0, 1.0, 0.05)) self.conv_node.setMass(1000.0) self.conv_np.setPos(-95.0, 0.0, 0.1) self.conv_node.addShape(self.conv_shape) self.world.attachRigidBody(self.conv_node) self.model = loader.loadModel('assets/conv.egg') self.model.flattenLight() self.model.reparentTo(self.conv_np) # Finger self.finger_node = BulletRigidBodyNode('Finger') self.finger_node.setFriction(1.0) self.finger_np = self.render.attachNewNode(self.finger_node) self.finger_shape = BulletCylinderShape(0.1, 0.25, ZUp) self.finger_node.setMass(0) self.finger_np.setPos(1.8, 0.0, 0.24 + 0.0254*3.5) self.finger_node.addShape(self.finger_shape) self.world.attachRigidBody(self.finger_node) self.model = loader.loadModel('assets/finger.egg') self.model.flattenLight() self.model.reparentTo(self.finger_np) self.blocks = [] for block_num in range(15): new_block = self.spawn_block(Vec3(28, random.uniform(-3, 3), (0.2 * block_num) + 2.0), 2, random.choice([4, 4, 6]), random.choice([10, 11, 12, 13, 14, 15, 15, 16, 16, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 23, 23, 23, 23, 23, 24])) # new_block = self.spawn_block(Vec3(18, 0, (0.2 * block_num) + 2.0), # 2, 4, 24) self.blocks.append(new_block) self.finger_speed_mps = 0.0 self.penalty_applied = False self.teleport_cooled_down = True self.fps = 20 self.framecount = 0 self.last_teleport_time = 0.0 self.time_to_teleport = False return self.step(1)[0] def spawn_block(self, location, z_inches, y_inches, x_inches): """ Spawns a block """ node = BulletRigidBodyNode('Block') node.setFriction(1.0) block_np = self.render.attachNewNode(node) shape = BulletBoxShape(Vec3(0.0254*y_inches, 0.0254*x_inches, 0.0254*z_inches)) node.setMass(1.0) block_np.setPos(location) block_np.setHpr(random.uniform(-60, 60), 0.0, 0.0) node.addShape(shape) self.world.attachRigidBody(node) model = loader.loadModel('assets/bullet-samples/models/box.egg') model.setH(90) model.setSx(0.0254*x_inches*2) model.setSy(0.0254*y_inches*2) model.setSz(0.0254*z_inches*2) model.flattenLight() model.reparentTo(block_np) block_np.node().setTag('scrambled', 'False') return block_np def get_camera_image(self, requested_format=None): """ Returns the camera's image, which is of type uint8 and has values between 0 and 255. The 'requested_format' argument should specify in which order the components of the image must be. For example, valid format strings are "RGBA" and "BGRA". By default, Panda's internal format "BGRA" is used, in which case no data is copied over. """ tex = self.dr.getScreenshot() if requested_format is None: data = tex.getRamImage() else: data = tex.getRamImageAs(requested_format) image = np.frombuffer(data, np.uint8) # use data.get_data() instead of data in python 2 image.shape = (tex.getYSize(), tex.getXSize(), tex.getNumComponents()) image = np.flipud(image) return image[:,:,:3] def reset_conv(self): conveyor_dist_left = 1 - self.conv_np.getPos()[0] if conveyor_dist_left < 10: self.conv_np.setX(-95.0) self.conv_np.setY(0.0) def check_rewards(self): reward = 0 for block in self.blocks: block_x, block_y, block_z = block.getPos() if block_z > 0.16 and block_x > -1 and block_x < 0: block.node().setTag('scrambled', 'True') if block_x < 2.3 and block_z < 0.16 and block.node().getTag('scrambled') == 'True': block.node().setTag('scrambled', 'False') reward = 1 return reward def check_teleportable(self, blocks_per_minute): self.time = self.framecount/self.fps # if self.time % (1/(blocks_per_minute/60)) < 0.1: # self.time_to_teleport = True # else: # self.time_to_teleport = False # self.teleport_cooled_down = True teleport_cooled_down = True if self.last_teleport_time + 0.4 < self.time else False if random.choice([True, False, False, False]) and teleport_cooled_down: self.last_teleport_time = self.time self.time_to_teleport = True for block in self.blocks: block_x = block.getPos()[0] if block_x > 5: block.node().setTag('scrambled', 'False') if self.time_to_teleport is True: self.time_to_teleport = False block.setX(-3) block.setY(0.0) block.setZ(2.0) block.setHpr(random.uniform(-60, 60), 0.0, 0.0) def step(self, action): dt = 1/self.fps self.framecount += 1 max_dist = 1.1 # Move finger finger_max_speed = 2 finger_accel = 10.0 finger_deccel = 10.0 self.action_buffer.pop(0) self.action_buffer.append(action) action = self.action_buffer[0] if action == 0: self.finger_speed_mps += dt * finger_accel if self.finger_speed_mps > finger_max_speed: self.finger_speed_mps = 2 if action == 1: if self.finger_speed_mps > 0.01: self.finger_speed_mps -= finger_deccel * dt if self.finger_speed_mps < -0.01: self.finger_speed_mps += finger_deccel * dt if action == 2: self.finger_speed_mps -= dt * finger_accel if self.finger_speed_mps < -finger_max_speed: self.finger_speed_mps = -finger_max_speed real_displacement = self.finger_speed_mps * dt self.finger_np.setY(self.finger_np.getY() + real_displacement) if self.finger_np.getY() > max_dist: self.finger_np.setY(max_dist) self.finger_speed_mps = 0 if self.finger_np.getY() < -max_dist: self.finger_np.setY(-max_dist) self.finger_speed_mps = 0 # self.world.doPhysics(dt, 5, 1.0/120.0) self.world.doPhysics(dt, 20, 1.0/240.0) self.reset_conv() self.check_teleportable(blocks_per_minute=59) # Keep the conveyor moving self.conv_np.node().setLinearVelocity(Vec3(1.0, 0.0, 0.0)) if self.human_playable is False: self.graphicsEngine.renderFrame() TransformState.garbageCollect() RenderState.garbageCollect() image = self.get_camera_image() else: image = None score = 0 score += self.check_rewards() done = False return image, score, done def update(self, task): is_down = self.mouseWatcherNode.is_button_down next_act = 1 if is_down(self.forward_button): next_act = 0 if is_down(self.backward_button): next_act = 2 _, reward, _ = self.step(next_act) if reward != 0: print(reward) last_frame_duration = time.time() - self.last_frame_start_time if last_frame_duration < (1/self.fps): time.sleep((1/self.fps) - last_frame_duration) self.last_frame_start_time = time.time() return task.cont
class Client(DirectObject): def __init__(self, parent, player, player_id, type="ContGame", game_id = TEST_GAME_ID ): self.parent = parent self.player = player self.player_id = player_id self.game_id = game_id self.type = type # Flags self._game_initialized = False # This handles message queue - we will process messages in sync one by one self._message_in_process = False # This handles interface interactions - we will not allow interaction if current animation is not done self._anim_in_process = False self.fsm = ClientFSM(self, 'ClientFSM') self.rRegion = RocketRegion.make('squad_select', base.win) self.rContext = self.rRegion.getContext() ih = RocketInputHandler() base.mouseWatcher.attachNewNode(ih) self.rRegion.setInputHandler(ih) # Initialize game mode (network) base.accept('n', render.setShaderAuto) base.accept('m', render.setShaderOff) self.net = Net(self) self.net.startNet() ClientMsg.getMyGames() if type == "ContGame": ClientMsg.enterGame( game_id ) taskMgr.doMethodLater(1, ClientMsg.forceFirstTurn, 'ForceTurn', extraArgs = []) elif type == 'NewGame': ClientMsg.startNewGame('base2', 1000, [17, 19]) def newGameStarted(self, game_id): print "aaaaaaaaaa", game_id ClientMsg.enterGame( game_id ) ClientMsg.forceFirstTurn() def getPlayerName(self, player_id): for p in self.players: if p['id'] == player_id: return p['name'] def deselectUnit(self): self.movement.deleteUnitAvailMove() self.sgm.hideVisibleEnemies() self.interface.clearUnitData() if self.sel_unit_id != None: self.sgm.unit_np_dict[self.sel_unit_id].clearAllFlags() self.sel_unit_id = None def selectUnit(self, unit_id): if self._anim_in_process == True: return if not self.units.has_key(unit_id): return if self.sel_unit_id != unit_id: self.deselectUnit() self.sel_unit_id = unit_id self.interface.processUnitData(unit_id) self.interface.printUnitData(unit_id) self.interface.refreshUnitInfo(unit_id) # If it is our turn, display available move tiles if self.player == self.turn_player: self.sgm.unit_np_dict[unit_id].setSelected() self.movement.calcUnitAvailMove(unit_id) self.sgm.showVisibleEnemies(unit_id) def selectNextUnit(self): if self.sel_unit_id == None: last = 0 else: last = self.sel_unit_id d = {} for unit_id in self.units.iterkeys(): if self.isThisMyUnit(unit_id): d[unit_id] = self.units[unit_id] l = sorted(d.iterkeys()) if len(l) <= 1: return else: if l[-1] == last: new_unit_id = l[0] else: for i in l: if i > last: new_unit_id = i break self.selectUnit(new_unit_id) def selectPrevUnit(self): if self.sel_unit_id == None: # TODO: ogs: Kaj fakat? last = 9999999 else: last = self.sel_unit_id d = {} for unit_id in self.units.iterkeys(): if self.isThisMyUnit(unit_id): d[unit_id] = self.units[unit_id] l = sorted(d.iterkeys()) l.reverse() if len(l) <= 1: return else: if l[-1] == last: new_unit_id = l[0] else: for i in l: if i < last: new_unit_id = i break self.selectUnit(new_unit_id) def refreshUnit(self, unit): if unit['alive'] == False: if self.sel_unit_id == unit['id']: self.sel_unit_id = None if self.sgm.unit_np_dict.has_key(unit['id']): self.sgm.hideUnit(unit['id']) if self.units.has_key(unit['id']): if self.isThisMyUnit(unit['id']): self.inactive_units[unit['id']] = unit self.deleteUnit(unit['id']) self.level.removeUnitDict(unit) else: self.units[unit['id']] = unit self.level.removeUnitId(unit['id']) self.level.putUnitDict(unit) def deleteUnit(self, unit_id): self.level.removeUnitId(unit_id) self.units.pop(unit_id) def getUnitData(self, unit_id): if self.units.has_key(unit_id): return self.units[unit_id] def isThisMyUnit(self, unit_id): if self.units.has_key(unit_id): if self.units[unit_id]['owner_id'] == self.player_id: return True else: return False else: return False def isThisEnemyUnit(self, unit_id): if self.units.has_key(unit_id): if self.units[unit_id]['owner_id'] != self.player_id: return True else: return False else: return False def isUnitAlive(self, unit_id): return self.units[unit_id]['alive'] def getCoordsByUnit(self, unit_id): if self.units.has_key(unit_id): unit = self.units[unit_id] return Point2(unit['pos'][0], unit['pos'][1]) def getUnitByCoords(self, pos): for u in self.units.itervalues(): if u['pos'][0] == pos.getX() and u['pos'][1] == pos.getY(): return u['id'] return None def beforeAnimHook(self): self._anim_in_process = True self.movement.deleteUnitAvailMove() self.sgm.hideVisibleEnemies() for u in self.sgm.unit_np_dict.itervalues(): u.clearTargeted() self.movement.hovered_unit_id = None def afterAnimHook(self): self._anim_in_process = False self._message_in_process = False #======================================================================== # Client animation handler methods def handleMove(self, move_msg): move = self.buildMove(move_msg) s = Sequence(Func(self.beforeAnimHook), move, Func(self.afterAnimHook)) s.start() def buildMove(self, move_msg): unit_id = move_msg[0] action_list = move_msg[1] pos = None heading = None unit_model = None s = Sequence() d = 0.0 if self.units.has_key(unit_id): pos = Point3(utils.TILE_SIZE*(self.units[unit_id]['pos'][0] + 0.5), utils.TILE_SIZE*(self.units[unit_id]['pos'][1] + 0.5), utils.GROUND_LEVEL) heading = utils.getHeadingAngle(self.units[unit_id]['heading']) if self.sgm.unit_np_dict.has_key(unit_id): unit_model = self.sgm.unit_np_dict[unit_id] else: # This is the first time we see this unit, we have no record of it in client.units dict or sgm nodepath list and dict # First action we MUST receive here is 'spot', otherwise client will break as we dont have unit_model defined None for idx, action in enumerate(action_list): action_type = action[0] if action_type == "move": end_pos = Point3(utils.TILE_SIZE*(action[1][0] + 0.5), utils.TILE_SIZE*(action[1][1] + 0.5), utils.GROUND_LEVEL) i, duration, pos, heading = self.buildMoveAnim(unit_model, pos, end_pos, heading) d += duration s.append(i) elif action_type == "rotate": end_pos = Point3(utils.TILE_SIZE*(action[1][0] + 0.5), utils.TILE_SIZE*(action[1][1] + 0.5), utils.GROUND_LEVEL) i, duration, pos, heading = self.buildRotateAnim(unit_model, pos, end_pos, heading) d += duration s.append(i) elif action_type == "spot": spotted_unit = action[1] self.units[spotted_unit['id']] = spotted_unit # Check if we have this unit in our scene graph records if self.sgm.unit_np_dict.has_key(spotted_unit['id']): spotted_unit_model = self.sgm.unit_np_dict[spotted_unit['id']] # This is the first time we see this unit, fill out starting variables for move and rotate actions else: wpn_list = utils.getUnitWeapons(spotted_unit) spotted_unit_model = self.sgm.loadUnit(spotted_unit['id'], wpn_list) # If this is our move message, means we spotted an enemy, and he will not be moving # If this is enemy move message, means we have spotted a moving enemy and we will set unit_model variable if self.isThisEnemyUnit(unit_id): unit_model = spotted_unit_model pos = Point3(utils.TILE_SIZE*(self.units[spotted_unit['id']]['pos'][0] + 0.5), utils.TILE_SIZE*(self.units[spotted_unit['id']]['pos'][1] + 0.5), utils.GROUND_LEVEL ) heading = utils.getHeadingAngle(self.units[spotted_unit['id']]['heading']) spotted_pos = pos spotted_h = heading else: spotted_pos = None spotted_h = None i = self.buildSpotAnim(spotted_unit_model, spotted_pos, spotted_h) s.append(i) elif action_type == "vanish": vanish_unit_id = action[1] spotted_later = False for a in action_list[idx:]: if a[0] == "spot": spotted_later = True break if spotted_later: i = self.buildDetachAnim(vanish_unit_id) else: i = self.buildDeleteAnim(vanish_unit_id) s.append(i) elif action_type == "overwatch": action_list = action[1] i = self.buildOverwatchAnim(action_list) s.append(i) if unit_model.fsm.state == 'Overwatch': #move = Sequence(unit_model.model.actorInterval('stand_up'), Func(unit_model.fsm.request, 'Walk'), s, Func(unit_model.fsm.request, 'Idle')) move = Sequence(unit_model.model.actorInterval('stand_up'), Func(unit_model.fsm.request, 'Walk'), s, Func(unit_model.fsm.request, 'Idle')) else: move = Sequence(Func(unit_model.fsm.request, 'Walk'), s, Func(unit_model.fsm.request, 'Idle')) return move def buildMoveAnim(self, unit_model, start_pos, end_pos, start_h): dummy_start = NodePath("dummy_start") dummy_end = NodePath("dummy_end") duration = 0.0 p = None dummy_start.setPos(start_pos) dummy_end.setPos(end_pos) dummy_start.lookAt(dummy_end) end_h = dummy_start.getH(render) # Model heading is different than movement heading, first create animation that turns model to his destination i_h = None if end_h != start_h: i_h = unit_model.model.quatInterval(0.2, hpr = Point3(end_h, 0, 0), startHpr = Point3(start_h, 0, 0)) i = unit_model.node.posInterval(0.5, end_pos, start_pos) duration += 0.5 if i_h: p = Parallel(i, i_h) else: p = i return p, duration, end_pos, end_h def buildRotateAnim(self, unit_model, start_pos, end_pos, start_h, heading=None): if heading == None: dummy_start = NodePath("dummy_start") dummy_end = NodePath("dummy_end") dummy_start.setPos(start_pos) dummy_end.setPos(end_pos) dummy_start.lookAt(dummy_end) end_h = dummy_start.getH(render) else: end_h = utils.getHeadingAngle(heading) interval = unit_model.model.quatInterval(0.2, hpr = Point3(end_h, 0, 0), startHpr = Point3(start_h, 0, 0)) duration = 0.2 return interval, duration, start_pos, end_h def buildSpotAnim(self, unit_model, pos, heading): return Sequence(Func(self.sgm.showUnit, unit_model, pos, None) ,Wait(0.2) ,Func(self.interface.setMarker, unit_model.id) ,Func(self.interface.console.consoleOutput, 'Unit spotted!', utils.CONSOLE_SYSTEM_MESSAGE) ,Func(self.interface.console.show) ) def buildDeleteAnim(self, unit_id): return Sequence(Func(self.interface.clearMarker, unit_id), Func(self.sgm.hideUnit, unit_id), Func(self.deleteUnit, unit_id), Wait(0.2)) def buildDetachAnim(self, unit_id): return Sequence(Func(self.sgm.detachUnit, unit_id), Wait(0.2)) def buildOverwatchAnim(self, action_list): i = self.buildShoot(action_list) return i def handleShoot(self, action_list): shoot = self.buildShoot(action_list) s = Sequence(Func(self.beforeAnimHook), Wait(0.2), shoot, Func(self.afterAnimHook)) s.start() def buildShoot(self, action_list): s = Sequence() d = 0.0 for action in action_list: action_type = action[0] if action_type == "shoot": shooter_id = action[1] # unit_id of the shooter shoot_tile = action[2] # (x,y) pos of targeted tile weapon = action[3] # weapon id damage_list = action[4] # list of all damaged/missed/bounced/killed units if shooter_id >= 0: shooter_model = self.sgm.unit_np_dict[shooter_id] a = self.buildShootAnim(shooter_model, weapon) shooter_pos = Point3(utils.TILE_SIZE*(self.units[shooter_id]['pos'][0] + 0.5), utils.TILE_SIZE*(self.units[shooter_id]['pos'][1] + 0.5), utils.GROUND_LEVEL ) b = self.buildBulletAnim(shooter_pos, shoot_tile) i = self.buildDamageAnim(damage_list) bi = Sequence(b, i) s.append(Parallel(a, bi)) #if action_type == "shoot": # shooter_id = action[1] # unit_id of the shooter # shoot_tile = action[2] # (x,y) pos of targeted tile # weapon = action[3] # weapon id # damage_list = action[4] # list of all damaged/missed/bounced/killed units # if shooter_id >= 0: # shooter_model = self.sgm.unit_np_dict[shooter_id] # a = self.buildShootAnim(shooter_model, weapon) # b = Sequence(Func(self.buildLaserAnim, shooter_model.node, self.sgm.unit_np_dict[damage_list[0][1]].node)) # i = self.buildDamageAnim(damage_list) # bi = Sequence(b, i) # s.append(Parallel(a, bi)) elif action_type == "melee": shooter_id = action[1] # unit_id of the shooter shoot_tile = action[2] # (x,y) pos of targeted tile weapon = action[3] # weapon id damage_list = action[4] # list of all damaged/missed/bounced/killed units shooter_model = self.sgm.unit_np_dict[shooter_id] i = self.buildMeleeAnim(shooter_model, shoot_tile, weapon) s.append(i) i = self.buildDamageAnim(damage_list) s.append(i) elif action_type == "rotate": unit_id = action[1] heading = action[2] unit_model = self.sgm.unit_np_dict[unit_id] start_h = utils.getHeadingAngle(self.units[unit_id]['heading']) i, duration, pos, h = self.buildRotateAnim(unit_model, None, None, start_h, heading) s.append(i) elif action_type == "overwatch": action_list = action[1] i = self.buildOverwatchAnim(action_list) s.append(i) # Start our shoot sequence return s def buildShootAnim(self, unit_model, weapon): # Unit shooting animation shoot_anim = Func(unit_model.fsm.request, 'Shoot') return shoot_anim def buildBulletAnim(self, start_pos, target_tile): # We create the bullet and its animation self.bullet = loader.loadModel("sphere") self.bullet.setScale(0.05) start_pos = Point3(start_pos.getX(), start_pos.getY(), 0.9) end_pos = Point3(utils.TILE_SIZE*(target_tile[0] + 0.5), utils.TILE_SIZE*(target_tile[1] + 0.5), 0.9) dest_node = NodePath("dest_node") dest_node.setPos(end_pos) start_node = NodePath("start_node") start_node.setPos(start_pos) time = round(start_node.getDistance(dest_node) / utils.BULLET_SPEED, 2) bullet_sequence = Sequence(Func(self.sgm.setBullet, self.bullet), self.bullet.posInterval(time, end_pos, start_pos), Func(self.sgm.deleteBullet, self.bullet) ) return bullet_sequence def buildLaserAnim(self, source, target): self.combat.source = source self.combat.target = target taskMgr.add(self.combat.drawBeam, 'beamtask') def buildMeleeAnim(self, unit_model, target_tile, weapon): # Unit melee animation melee_anim = Func(unit_model.fsm.request, 'Melee') return melee_anim def buildDamageAnim(self, damage_list): # Find all damaged units and play their damage/kill/miss animation damage_parallel = Parallel() for action in damage_list: damage_type = action[0] target_unit_id = action[1] target_unit = self.sgm.unit_np_dict[target_unit_id] t = TextNode('dmg') if damage_type == "bounce": target_anim = Func(target_unit.fsm.request, 'GetHit') dmg = 'bounce' elif damage_type == "miss": target_anim = Func(target_unit.fsm.request, 'GetHit') dmg = 'miss' elif damage_type == "damage": color_interval = Sequence(LerpColorScaleInterval(target_unit.model, 0.2, (10,10,10,1)) ,LerpColorScaleInterval(target_unit.model, 0.2, (1,1,1,1))) target_anim = Sequence(Func(target_unit.fsm.request, 'GetHit') , color_interval) dmg = str(action[2]) elif damage_type == "kill": color_interval = Sequence(LerpColorScaleInterval(target_unit.model, 0.2, (10,10,10,1)) ,LerpColorScaleInterval(target_unit.model, 0.2, (1,1,1,1))) target_anim = Parallel(Func(target_unit.fsm.request, 'Die') , color_interval) dmg = str(action[2]) t.setText( "%s" % dmg) t.setTextColor(1, 0, 0, 1) t.setAlign(TextNode.ACenter) textNodePath = NodePath("textnp") textNodePath.attachNewNode(t) textNodePath.setScale(0.35) textNodePath.setBillboardPointEye() textNodePath.setLightOff() # textNodePath will be reparented to unitmodel, so set start and end pos relative to the unit start_pos = Point3(0, 0, 0.9) end_pos = start_pos + Point3(0, 0, 3) damage_text_sequence = Sequence(Func(self.sgm.setDamageNode, textNodePath, target_unit.node), textNodePath.posInterval(1, end_pos, start_pos), Func(self.sgm.deleteDamageNode, textNodePath) ) damage_parallel = Parallel(damage_text_sequence, target_anim) return damage_parallel def handleVanish(self, unit_id): i = self.buildDeleteAnim(unit_id) s = Sequence(i, Func(self.afterAnimHook)) s.start() def handleSpot(self, unit): self.units[unit['id']] = unit # This is the first time we see this unit, fill out starting variables for move and rotate actions wpn_list = utils.getUnitWeapons(unit) spotted_unit_model = self.sgm.loadUnit(unit['id'], wpn_list) pos = Point3(utils.TILE_SIZE*(self.units[unit['id']]['pos'][0] + 0.5), utils.TILE_SIZE*(self.units[unit['id']]['pos'][1] + 0.5), utils.GROUND_LEVEL ) heading = utils.getHeadingAngle(self.units[unit['id']]['heading']) i = self.buildSpotAnim(spotted_unit_model, pos, heading) s = Sequence(i, Func(self.afterAnimHook)) s.start() def handleNewTurn(self): text = TextNode('new turn node') text.setText("TURN: "+self.turn_player) textnp = NodePath("textnp") textNodePath = textnp.attachNewNode(text) textNodePath.setColor(1, 0, 0) textNodePath.setScale(0.01, 0.01, 0.01) textNodePath.setPos(-0.7, 0, 0) textNodePath.reparentTo(aspect2d) s = Sequence(textNodePath.scaleInterval(.3, textNodePath.getScale()*20,blendType='easeIn'), Wait(1.0), textNodePath.scaleInterval(.3, textNodePath.getScale()*0.05,blendType='easeIn'), Func(self.sgm.deleteTurnNode, textNodePath), Func(self.afterAnimHook) ) s.start() def setCamPoss(self, off): self.altCam.setPos(self.altCam.getPos() + Point3(0, 0, 0.1)*off) print self.altCam.getPos() def setCamLook(self, off): self.altCam.setP(self.altCam.getP() + 0.5*off) print self.altCam.getP() def deploySquadScreen(self): self.dr2 = base.win.makeDisplayRegion(0.0, 0.5, 0.65, 1.0) self.dr2.setClearColor(VBase4(0, 0, 0, 0.3)) self.dr2.setClearColorActive(False) self.dr2.setClearDepthActive(True) self.render2 = NodePath('render2') self.cam2 = self.render2.attachNewNode(Camera('cam2')) self.cam2.node().getLens().setAspectRatio(1.8) self.dr2.setCamera(self.cam2) self.floor2np = self.render2.attachNewNode('floor2') tex = loader.loadTexture('scifi_floor.png') tex.setMagfilter(Texture.FTLinearMipmapLinear) tex.setMinfilter(Texture.FTLinearMipmapLinear) cm = CardMaker('cm_floor') cm.setFrame(0, 1, 0, 1) for x in xrange(10): for y in xrange(10): cpos = self.floor2np.attachNewNode(cm.generate()) cpos.setPos(x-5, y-5, 0) cpos.setP(-90) cpos.setTexture(tex) self.floor2np.flattenStrong() self.cam2.setPos(0, -10, 5) self.cam2.setP(-20) for idx, u in enumerate(self.deploy_queue): unit = utils.loadUnit('marine', u.lower(), self.player_id) unit.reparentTo(self.render2) unit.setScale(1) if idx == 0: unit.setPos(0, 0, 0) elif idx == 1: unit.setPos(1.5, 1.5, 0) unit.setH(-20) elif idx == 2: unit.setPos(-1.5, 1.8, 0) unit.setH(-10) elif idx == 3: unit.setPos(2.2, 2.5, 0) unit.setH(-20) elif idx == 4: unit.setPos(-1.4, 3.5, 0) elif idx == 5: unit.setPos(3.5, -0.5, 0) unit.setH(-35) elif idx == 6: unit.setPos(-2.6, 2.5, 0) unit.setH(30) elif idx == 7: unit.setPos(-4.5, 0, 0) unit.setH(40) unit.setTag('id', str(idx)) unit.setTag('type', u.lower()) self.altalight = AmbientLight("alight") self.altalight.setColor(VBase4(0.2, 0.2, 0.2, 1.0)) self.altalnp = self.render2.attachNewNode(self.altalight) self.render2.setLight(self.altalnp) self.altalight2 = AmbientLight("alight2") self.altalight2.setColor(VBase4(0.4, 0.4, 0.4, 1.0)) self.altalnp2 = self.render2.attachNewNode(self.altalight2) self.altslight = Spotlight('slight') self.altslight.setColor(VBase4(0.6, 0.6, 0.6, 1)) self.altslnp = self.render2.attachNewNode(self.altslight) self.altslnp.setPos(5, 1, 15) self.altslnp.lookAt(0, 0, 0) self.render2.setLight(self.altslnp) self.render2.setShaderAuto() self.deploy_index = 0 self.deploy_unit_np = render.attachNewNode('deploy_unit_np') self.getDeployee() def getDeployee(self): if len(self.deploy_queue) > self.deploy_index: self.deploy_unit = self.render2.find('=id='+str(self.deploy_index)) self.deploy_unit.setLight(self.altalnp2) self.deploy_index += 1 else: self.deploy_unit = None def deployUnit(self): if self.deploy_unit != None: if base.mouseWatcherNode.hasMouse(): mpos = base.mouseWatcherNode.getMouse() pos3d = Point3() nearPoint = Point3() farPoint = Point3() base.camLens.extrude(mpos, nearPoint, farPoint) if self.plane.intersectsLine(pos3d, render.getRelativePoint(camera, nearPoint), render.getRelativePoint(camera, farPoint)): pos = (int(pos3d.getX()), int(pos3d.getY())) if self.deploy_dict.has_key(pos) and self.deploy_dict[pos] == None: unit = self.deploy_unit unit.reparentTo(self.deploy_unit_np) unit.setScale(0.3) unit.setPos(int(pos3d.getX()) + 0.5, int(pos3d.getY()) + 0.5, utils.GROUND_LEVEL) self.deploy_dict[pos] = unit.getTag('type') self.deploy_unit.setLightOff() self.getDeployee() def endDeploy(self): if len(self.deploy_queue) > self.deploy_index: print "You must deploy all units" else: army_list = [] for key in self.deploy_dict: if self.deploy_dict[key] != None: tup = (key[0], key[1], 'marine_'+self.deploy_dict[key]) army_list.append(tup) ClientMsg.armyList(army_list) @pstat def getInvisibleTiles(self): a = [] for u in self.units: if self.isThisMyUnit(u): a.append(self.units[u]) t = time.clock() l = levelVisibilityDict(a, self.level) print "tiles timer:::", (time.clock()-t)*1000 return l @pstat def getInvisibleWalls(self): a = [] for u in self.units: if self.isThisMyUnit(u): a.append(self.units[u]) t = time.clock() l = visibleWalls(a, self.level) print "walls timer:::", (time.clock()-t)*1000 return l