def __init__(self, base, USE_RP): self.base = base """ direct.showbase.ShowBase """ if not USE_RP: alight = AmbientLight('alight') alnp = self.base.render.attachNewNode(alight) alight.setColor((0.2, 0.2, 0.2, 1)) self.base.render.setLight(alnp) # Put lighting on the main scene dlight = DirectionalLight('dlight') dlnp = self.base.render.attachNewNode(dlight) dlnp.setPos(0, 5, 5) dlight.setColor((0.8, 0.8, 0.5, 1)) dlnp.setHpr(0, 60, 0) self.base.render.setLight(dlnp) plight = PointLight('plight') plnp = self.base.render.attachNewNode(plight) plnp.setPos(0, -50, 50) plnp.setHpr(0, 60, 0) self.base.render.setLight(plnp) self.sounds = {}
def __init__(self): base.setBackgroundColor(0.1, 0.1, 0.8, 1) base.setFrameRateMeter(True) base.cam.setPos(0, -60, 20) base.cam.lookAt(0, 0, 0) # Light alight = AmbientLight('ambientLight') alight.setColor(Vec4(0.5, 0.5, 0.5, 1)) alightNP = render.attachNewNode(alight) dlight = DirectionalLight('directionalLight') dlight.setDirection(Vec3(1, 1, -1)) dlight.setColor(Vec4(0.7, 0.7, 0.7, 1)) dlightNP = render.attachNewNode(dlight) render.clearLight() render.setLight(alightNP) render.setLight(dlightNP) # Input self.accept('escape', self.doExit) self.accept('r', self.doReset) self.accept('f1', self.toggleWireframe) self.accept('f2', self.toggleTexture) self.accept('f3', self.toggleDebug) self.accept('f5', self.doScreenshot) # Task taskMgr.add(self.update, 'updateWorld') # Physics self.setup()
def loadPrisonCrater(): ## Sky color base.win.setClearColor(Vec4(.46,.824,.904,1)) ## Load Ground sand = loader.loadModel("data/models/sand.bam") sand.reparentTo(render) sand.setTexScale(TextureStage.getDefault(),5000,5000) craterwalls = loader.loadModel("data/models/craterwalls.bam") craterwalls.reparentTo(render) craterwalls.setTexScale(TextureStage.getDefault(),500,50) ## World Effects fog = Fog("Fog") fog.setColor(255,215,143) fog.setExpDensity(.0000001) render.setFog(fog) alight = render.attachNewNode(AmbientLight("Abient")) alight.node().setColor(Vec4(.9,.9,.9,1)) render.setLight(alight) sun = DirectionalLight('Sun') sun.setColor(Vec4(1,1,1,1)) sunNP = render.attachNewNode(sun) sunNP.setPos(0,0,4000) sunNP.setHpr(0,-90,0) render.setLight(sunNP)
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): # call superclass init (no implicit chaining) ShowBase.__init__(self) self.pnode = loader.loadModel("models/queen") self.pnode.reparentTo(render) self.pnode.setPos(0, 5, -1) self.pnode.setH(-60) self.pnode2 = loader.loadModel("models/pawn") self.pnode2.reparentTo(self.pnode) self.pnode2.setScale(0.5) self.ground = 1.2 self.pnode2.setPos(1, 0, self.ground) self.vz = 0 self.vx = 0 self.vy = 0 ############ lighting ############# alight = AmbientLight('alight') alight.setColor((.7, .3, .3, 1)) self.alnp = render.attachNewNode(alight) render.setLight(self.alnp) slight = DirectionalLight('slight') slight.setColor((1, .5, .5, 1)) slight.setDirection(LVector3(-0.8, 0, 0)) self.slnp = render.attachNewNode(slight) render.setLight(self.slnp) taskMgr.add(self.update, "update")
def __setDirectionalLight(self,props): light = DirectionalLight(props['name']) light.setShadowCaster(props['castShadows'],1024,1024) lens = PerspectiveLens() light.setLens(lens) lens.setFov(1200/props['pos'].z) return self.__createLight(light,props)
def __init__(self, base, name, speed, scale, color, mask, relA, xyz, relB, lookat, life): an = ActorNode() self.anp = base.render.attachNewNode(an) base.physicsMgr.attachPhysicalNode(an) self.anpo = an.getPhysicsObject() fn = ForceNode("force-missile") self.anp.attachNewNode(fn) bft = LinearVectorForce(Vec3(0, 1, 0)*speed) fn.addForce(bft) an.getPhysical(0).addLinearForce(bft) missile = base.loader.loadModel("./mdl/missile.egg") missile.setColor(color) missile.setScale(scale) missile.reparentTo(self.anp) missile.setTag(name, '1') missile_from_obj = missile.attachNewNode(CollisionNode(name)) missile_from_obj.node().addSolid(CollisionSphere(0, 0, 0, 1)) missile_from_obj.node().setFromCollideMask(mask) missile_from_obj.setCollideMask(mask) base.pusher.addCollider(missile_from_obj, self.anp) base.cTrav.addCollider(missile_from_obj, base.pusher) self.anp.setPos(relA, xyz) self.anp.lookAt(relB, lookat) # light the missile mlight = DirectionalLight('mlight') mlight.setColor(VBase4(1., 1., 1., 1)) mlnp = base.render.attachNewNode(mlight) mlnp.setHpr(self.anp.getHpr()) self.anp.setLightOff() self.anp.setLight(mlnp) # remove the missile base.taskMgr.doMethodLater(life, self.remove_missile, 'task-remove-missile', extraArgs=[self.anp], appendTask=True)
def setupLight(self): ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.8, .8, .8, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(LVector3(0, 45, -45)) directionalLight.setColor((0.2, 0.2, 0.2, 1)) render.setLight(render.attachNewNode(directionalLight)) render.setLight(render.attachNewNode(ambientLight))
def setupLights(self): ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.8, .8, .75, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(LVector3(0, 0, -2.5)) directionalLight.setColor((0.9, 0.8, 0.9, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))
def add_celestial(self, azimuth, elevation, color, intensity, radius): location = Vec3(to_cartesian(azimuth, elevation, 1000.0 * 255.0 / 256.0)) if intensity: dlight = DirectionalLight('celestial') dlight.set_color((color[0] * intensity, color[1] * intensity, color[2] * intensity, 1.0)) node = self.node.attach_new_node(dlight) node.look_at(*(location * -1)) self.node.set_light(node)
def setupLights(self): # Sets up some default lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.4, .4, .35, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(LVector3(0, 8, -2.5)) directionalLight.setColor((0.9, 0.8, 0.9, 1)) render.setLight(render.attachNewNode(directionalLight)) render.setLight(render.attachNewNode(ambientLight))
def loadSimpleLighting(self): ambientLight = AmbientLight( "ambientLight" ) ambientLight.setColor( Vec4(.8, .8, .8, 1) ) directionalLight = DirectionalLight( "directionalLight" ) directionalLight.setDirection( Vec3( 0, 45, -45 ) ) directionalLight.setColor( Vec4( 0.2, 0.2, 0.2, 0.6 ) ) render.setLight(render.attachNewNode( directionalLight ) ) render.setLight(render.attachNewNode( ambientLight ) )
def setupLights(self): #This function sets up some default lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.8, .8, .8, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(0, 45, -45)) directionalLight.setColor(Vec4(0.2, 0.2, 0.2, 1)) render.setLight(render.attachNewNode(directionalLight)) render.setLight(render.attachNewNode(ambientLight))
def setup_lights(self): ambientLight = AmbientLight('ambient') ambientLight.setColor( Vec4( .5, .5, .5, 1 ) ) render.setLight(render.attachNewNode(ambientLight)) directionalLight = DirectionalLight('directional') directionalLight.setDirection( Vec3( -10, 10, -25 ) ) directionalLight.setColor( Vec4( .1, .1, .1, 1 ) ) render.setLight(render.attachNewNode(directionalLight))
def setupLights(self): ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.4, .4, .35, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3( 0, 8, -2.5 ) ) directionalLight.setColor(Vec4( 0.9, 0.8, 0.9, 1 ) ) #Set lighting on teapot so spark doesn't get affected self.t.setLight(self.t.attachNewNode(directionalLight)) self.t.setLight(self.t.attachNewNode(ambientLight))
def setupLights(self): ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(0.4, 0.4, 0.35, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(0, 8, -2.5)) directionalLight.setColor(Vec4(0.9, 0.8, 0.9, 1)) render.setLight(render.attachNewNode(directionalLight)) render.setLight(render.attachNewNode(directionalLight)) self.env.setLightOff()
def setupLights(self): #This is one area I know hardly anything about. I really don't know how to get this to behave nicely. #The black pieces are hardly distinguishable. ambientLight = AmbientLight( "ambientLight" ) ambientLight.setColor( Vec4(.8, .8, .8, 1) ) directionalLight = DirectionalLight( "directionalLight" ) directionalLight.setDirection( Vec3( 0, 45, -45 ) ) directionalLight.setColor( Vec4( 0.2, 0.2, 0.2, 1 ) ) render.setLight(render.attachNewNode( directionalLight ) ) render.setLight(render.attachNewNode( ambientLight ) )
def __init__(self, player_tag): ShowBase.__init__(self) self.__player_tag = player_tag self.__rotations = {} # Panda pollutes the global namespace. Some of the extra globals can be referred to in nicer ways # (for example self.render instead of render). The globalClock object, though, is only a global! We # create a reference to it here, in a way that won't upset PyFlakes. self.globalClock = __builtins__["globalClock"] # Turn off the debugging system which allows the camera to be adjusted directly by the mouse. self.disableMouse() # Set up physics: the ground plane and the capsule which represents the player. self.world = BulletWorld() # The ground first: shape = BulletPlaneShape(Vec3(0, 0, 1), 0) node = BulletRigidBodyNode('Ground') node.addShape(shape) np = self.render.attachNewNode(node) np.setPos(0, 0, 0) self.world.attachRigidBody(node) # Load the 3dWarehouse model. cathedral = self.loader.loadModel("3dWarehouse_Reykjavik_Cathedral.egg") cathedral.reparentTo(self.render) cathedral.setScale(0.5) # Load the Blender model. self.humanoid = Actor("player.egg") self.humanoid.setScale(0.5) self.humanoid.reparentTo(self.render) self.humanoid.loop("Walk") humanoidPosInterval1 = self.humanoid.posInterval(58, Point3(13, -10, 0), startPos=Point3(13, 10, 0)) humanoidPosInterval2 = self.humanoid.posInterval(58, Point3(13, 10, 0), startPos=Point3(13, -10, 0)) humanoidHprInterval1 = self.humanoid.hprInterval(3, Point3(180, 0, 0), startHpr=Point3(0, 0, 0)) humanoidHprInterval2 = self.humanoid.hprInterval(3, Point3(0, 0, 0), startHpr=Point3(180, 0, 0)) # Make the Blender model walk up and down. self.humanoidPace = Sequence(humanoidPosInterval1, humanoidHprInterval1, humanoidPosInterval2, humanoidHprInterval2, name="humanoidPace") self.humanoidPace.loop() # Create a light so we can see the scene. dlight = DirectionalLight('dlight') dlight.setColor(VBase4(2, 2, 2, 0)) dlnp = self.render.attachNewNode(dlight) dlnp.setHpr(0, -60, 0) self.render.setLight(dlnp) # Create a task to update the scene regularly. self.taskMgr.add(self.update, "UpdateTask")
def __init__(self): base.setBackgroundColor(0.1, 0.1, 0.5, 1) base.setFrameRateMeter(True) base.cam.setPos(0, -20, 5) base.cam.lookAt(0, 0, 0) base.disableMouse() self.zoom = 50; self.viewPoint = "FRONT" # Light alight = AmbientLight('ambientLight') alight.setColor(Vec4(0.5, 0.5, 0.5, 1)) alightNP = render.attachNewNode(alight) dlight = DirectionalLight('directionalLight') dlight.setDirection(Vec3(1, 1, -1)) dlight.setColor(Vec4(0.7, 0.7, 0.7, 1)) dlightNP = render.attachNewNode(dlight) render.clearLight() render.setLight(alightNP) render.setLight(dlightNP) #bot self.ankleJont = 0 self.foot = 0 self.kneeJoint = 0 self.hipKneeJoint = 0 # Input self.accept('escape', self.doExit) self.accept('r', self.doReset) self.accept('f1', self.toggleWireframe) self.accept('f2', self.toggleTexture) self.accept('f3', self.toggleDebug) self.accept('f5', self.doScreenshot) self.accept('enter', self.doShoot) self.accept('a',self.setAngleMax) self.accept('o',self.setAngleMin) self.accept('1', self.setViewPointTOP) self.accept('2', self.setViewPointFRONT) self.accept('3', self.setViewPointLEFT) self.accept('4', self.setViewPointDIAG) self.accept('b', self.setZoomInc) self.accept('m', self.setZoomDec) # Task taskMgr.add(self.update, 'updateWorld') # Physics self.setup()
def setupLights(self): ambientLight = AmbientLight("ambiengtLight") ambientLight.setColor((0.4, 0.4, 0.35, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(LVector3(0, 8, -2.5)) directionalLight.setColor((0.9, 0.8, 0.9, 1)) directionalLight.setColor((0.9, 0.8, 0.9, 1)) self.teapot.setLight(self.teapot.attachNewNode(directionalLight)) self.teapot.setLight(self.teapot.attachNewNode(ambientLight))
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)
class Game(ShowBase): def __init__(self): ShowBase.__init__(self) self.setBackgroundColor(0.2,0.2,0.2) self.accept("escape", self.taskMgr.stop) #self.accept("mouse1", self.onClick) #self.accept("mouse2", self.onClick2) self.globalClock = ClockObject() self.addLight() self.liner = LineDrawer(self) self.taskMgr.add(self.update, "update") def update(self, task): self.globalClock.tick() t = self.globalClock.getFrameTime() #print t dt = self.globalClock.getDt() return task.cont def addLight(self): self.render.clearLight() self.lightCenter = self.render.attachNewNode(PandaNode("center")) #self.lightCenter.setCompass() # ambient light self.ambientLight = AmbientLight('ambientLight') self.ambientLight.setColor(Vec4(0.5,0.5,0.5, 1)) self.alight = self.lightCenter.attachNewNode(self.ambientLight) self.render.setLight(self.alight) # point light self.pointlight = PointLight("pLight") self.light = self.lightCenter.attachNewNode(self.pointlight) self.pointlight.setColor(Vec4(0.8,0.8,0.8,1)) self.light.setPos(0,0,2) self.render.setLight(self.light) # directional light self.dirlight = DirectionalLight("dLight") self.dlight = self.lightCenter.attachNewNode(self.dirlight) self.dirlight.setColor(Vec4(0.8,0.8,0.8,1)) self.dirlight.setShadowCaster(True) self.dlight.setPos(0,0,5) self.dlight.lookAt(5,10,0) self.render.setLight(self.dlight) self.render.setShaderAuto()
def __init__(self, _heightField): texture = loader.loadTexture("ground_tex.png") self.zScale = 45 self.terrain = GeoMipTerrain("BasicTerrain") self.terrain.setHeightfield(_heightField) # Dynamic settings? self.terrain.setBlockSize(16) self.terrain.setNear(20) self.terrain.setFar(100) self.terrain.setFocalPoint(base.camera) # Settings self.terrain.getRoot().setSz(self.zScale) self.terrain.getRoot().setTexture(texture) self.terrain.getRoot().reparentTo(render) self.terrain.generate() self.terrainSize = (self.terrain.heightfield().getReadXSize(), self.terrain.heightfield().getReadYSize()) print "Terrain Size:", self.terrainSize taskMgr.add(self.terrainTask, "TerrainTask") self.skydome = loader.loadModel("Skydome") self.skydome.setDepthTest(False) self.skydome.setAttrib(CullBinAttrib.make("skydomeBin", 1000)) self.skydome.reparentTo(camera) self.skydome.setScale(2) self.skydome.setPos(0, 0, -0.5) self.skydome.setCollideMask(BitMask32.allOff()) taskMgr.add(self.skydomeTask, "paperplanet_skydome") # Add some fancy fog self.fog = Fog("Fog Name") self.fog.setColor(0.4,0.2,0.3) self.fog.setExpDensity(0.015) render.setFog(self.fog) # Some Test light dlight = DirectionalLight("dlight") dlight.setColor(VBase4(0.8, 0.8, 0.5, 1)) dlnp = render.attachNewNode(dlight) dlnp.setHpr(0, -60, 0) render.setLight(dlnp) # Add basic blacksmith hut tmp = loader.loadModel("blacksmith_hut") tmp.reparentTo(render) tmp.setPos(164.054, 340.92, 11.3384)
def setupLights(self): # Light alight = AmbientLight('ambientLight') alight.setColor(Vec4(0.5, 0.5, 0.5, 1)) alightNP = render.attachNewNode(alight) dlight = DirectionalLight('directionalLight') dlight.setDirection(Vec3(1, 1, -1)) dlight.setColor(Vec4(0.7, 0.7, 0.7, 1)) dlightNP = render.attachNewNode(dlight) self.render.clearLight() self.render.setLight(alightNP) self.render.setLight(dlightNP)
def setupLights(self): #Create some lights and add them to the scene. By setting the lights on #render they affect the entire scene #Check out the lighting tutorial for more information on lights ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.4, .4, .35, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(0, 8, -2.5)) directionalLight.setColor(Vec4(0.9, 0.8, 0.9, 1)) render.setLight(render.attachNewNode(directionalLight)) render.setLight(render.attachNewNode(ambientLight)) #Explicitly set the environment to not be lit self.env.setLightOff()
def __create_directional_light(self, lightId, lightColor, lightHpr, shadow = True): directionalLight = DirectionalLight(lightId) directionalLight.setColor(lightColor) directionalLight.setShadowCaster(shadow) directionalLightNP = NodePath(directionalLight) directionalLightNP.setHpr(lightHpr) return directionalLightNP
def __init__(self): base.setBackgroundColor(0.1, 0.1, 0.8, 1) base.setFrameRateMeter(True) base.cam.setPos(0, -20, 4) base.cam.lookAt(0, 0, 0) # Light alight = AmbientLight('ambientLight') alight.setColor(Vec4(0.5, 0.5, 0.5, 1)) alightNP = render.attachNewNode(alight) dlight = DirectionalLight('directionalLight') dlight.setDirection(Vec3(1, 1, -1)) dlight.setColor(Vec4(0.7, 0.7, 0.7, 1)) dlightNP = render.attachNewNode(dlight) render.clearLight() render.setLight(alightNP) render.setLight(dlightNP) # Input self.accept('escape', self.doExit) self.accept('r', self.doReset) self.accept('f1', self.toggleWireframe) self.accept('f2', self.toggleTexture) self.accept('f3', self.toggleDebug) self.accept('f5', self.doScreenshot) self.accept('1', self.doSelect, [0,]) self.accept('2', self.doSelect, [1,]) self.accept('3', self.doSelect, [2,]) self.accept('4', self.doSelect, [3,]) self.accept('5', self.doSelect, [4,]) self.accept('6', self.doSelect, [5,]) inputState.watchWithModifiers('forward', 'w') inputState.watchWithModifiers('left', 'a') inputState.watchWithModifiers('reverse', 's') inputState.watchWithModifiers('right', 'd') inputState.watchWithModifiers('turnLeft', 'q') inputState.watchWithModifiers('turnRight', 'e') # Task taskMgr.add(self.update, 'updateWorld') # Physics self.setup()
def addLight(self): self.render.clearLight() self.lightCenter = self.render.attachNewNode(PandaNode("center")) #self.lightCenter.setCompass() # ambient light self.ambientLight = AmbientLight('ambientLight') self.ambientLight.setColor(Vec4(0.5,0.5,0.5, 1)) self.alight = self.lightCenter.attachNewNode(self.ambientLight) self.render.setLight(self.alight) # point light self.pointlight = PointLight("pLight") self.light = self.lightCenter.attachNewNode(self.pointlight) self.pointlight.setColor(Vec4(0.8,0.8,0.8,1)) self.light.setPos(0,0,2) self.render.setLight(self.light) # directional light self.dirlight = DirectionalLight("dLight") self.dlight = self.lightCenter.attachNewNode(self.dirlight) self.dirlight.setColor(Vec4(0.8,0.8,0.8,1)) self.dirlight.setShadowCaster(True) self.dlight.setPos(0,0,5) self.dlight.lookAt(5,10,0) self.render.setLight(self.dlight) self.render.setShaderAuto()
def __init__(self, collisionHandler): self.collHandler = collisionHandler # Load Model-------------------------------------------------------------- self.model = loader.loadModel('Models/bullet.egg.pz') self.model.setPythonTag("owner", self) self.model.reparentTo(render) # Load Light------------------------------------------------------------- self.lamp = DirectionalLight('shipdlight') self.lamp.setColor(VBase4(0.8,0.8,0.5,1)) self.lampNodePath = self.model.attachNewNode(self.lamp) self.lampNodePath.setHpr(0,15,0) render.setLight(self.lampNodePath) # Add Movment Update Task------------------------------------------------ self.movementTask = taskMgr.add(self.updatePosition, "ship-movement-task") self.movementTask.last = 0 self.bullets = [] self.reset() self.collisionNode = self.model.attachNewNode(CollisionNode("ship")) self.collisionNode.node().addSolid(CollisionSphere(0,0,0,1)) base.cTrav.addCollider(self.collisionNode, self.collHandler) self.accept('asteroid-into-ship', self.collideWithAsteroid)
def init_lights(self): print("-- init lights") # Light alight = AmbientLight('ambientLight') alight.setColor(Vec4(0.1, 0.1, 0.1, 1)) alightNP = render.attachNewNode(alight) dlight = DirectionalLight('directionalLight') dlight.setDirection(Vec3(1, 1, -1)) dlight.setColor(Vec4(0.7, 0.7, 0.7, 1)) dlightNP = render.attachNewNode(dlight) render.clearLight() render.setLight(alightNP) render.setLight(dlightNP)
def setup(self): # Debug (useful to turn on for physics) self.debugNP = self.render.attachNewNode(BulletDebugNode('Debug')) self.debugNP.hide() # Physics World self.world = BulletWorld() self.world.setGravity(Vec3(0, 0, -9.81)) self.world.setDebugNode(self.debugNP.node()) # Main Character self.player = Player() self.player.createPlayer(render, self.world) # Enemies self.createEnemies() # Music self.backgroundMusic = loader.loadSfx( '../sounds/elfman-piano-solo.ogg') self.backgroundMusic.setLoop(True) self.backgroundMusic.stop() self.backgroundMusic.setVolume( 0.9) # lower this when I add sound effects # Sound Effects self.collect = base.loader.loadSfx("../sounds/collect-sound.wav") self.collect.setVolume(1) self.damage = base.loader.loadSfx("../sounds/damage.wav") self.damage.setVolume(0.5) self.winner = base.loader.loadSfx("../sounds/win-yay.wav") self.winner.setVolume(1) self.dead = base.loader.loadSfx("../sounds/severe-damage.wav") self.dead.setVolume(1) # Level 1 Skybox self.skybox = loader.loadModel('../models/skybox_galaxy.egg') self.skybox.setScale(1000) # make big enough to cover whole terrain self.skybox.setBin('background', 1) self.skybox.setDepthWrite(0) self.skybox.setLightOff() self.skybox.reparentTo(render) # Lighting dLight = DirectionalLight("dLight") dLight.setColor(Vec4(0.8, 0.8, 0.5, 1)) dLight.setDirection(Vec3(-5, -5, -5)) dlnp = render.attachNewNode(dLight) dlnp.setHpr(0, 60, 0) render.setLight(dlnp) aLight = AmbientLight("aLight") aLight.setColor(Vec4(0.5, 0.5, 0.5, 1)) alnp = render.attachNewNode(aLight) render.setLight(alnp) # Fog colour = (0.2, 0.2, 0.3) genfog = Fog("general fog") genfog.setColor(*colour) genfog.setExpDensity(0.003) render.setFog(genfog) base.setBackgroundColor(*colour) # Create wall (x, y, z, h) self.createWall(-30.2215, -6.2, -2, 45) self.createWall(-203, 555.8, -2, 70) #-----Level 1 Platforms----- # Platform to collect B self.createPlatform(72, 70.2927, -1) # Platforms to collect R self.createPlatform(211, 210, -1) self.createPlatform(225, 223, 2.7) # Platforms to collect E and A self.createPlatform(330, 462, -0.4) self.createPlatform(340, 471, 2.1) self.createPlatform(350, 480, 4) self.createPlatform(335, 483, 5) # Platforms to collect K self.createPlatform(184, 712, -1) self.createPlatform(208, 730, -1) self.createPlatform(207, 711, -1) self.createPlatform(186, 731, -1) #-----Level 2 Platforms----- # Moving platforms if self.movingPlatforms > 0: del self.movingPlatforms[:] self.createMovingPlatforms() # Create complex mesh for Track using BulletTriangleMeshShape mesh = BulletTriangleMesh() self.track = loader.loadModel("../models/mountain_valley_track.egg") self.track.flattenStrong() for geomNP in self.track.findAllMatches('**/+GeomNode'): geomNode = geomNP.node() ts = geomNP.getTransform(self.track) for geom in geomNode.getGeoms(): mesh.addGeom(geom, ts) shape = BulletTriangleMeshShape(mesh, dynamic=False) node = BulletRigidBodyNode('Track') node.setMass(0) node.addShape(shape) tracknn = render.attachNewNode(node) self.world.attachRigidBody(tracknn.node()) tracknn.setPos(27, -5, -2) self.track.reparentTo(tracknn)
def __init__(self): super().__init__() # self.set_background_color(0, 0, 0, 1) # base.camera.setPos(0, 0, 0) # print("Skybox") self.skysphere = loader.loadModel("SkySphere.bam") self.skysphere.setBin('background', 1) self.skysphere.setDepthWrite(0) self.skysphere.reparentTo(self.render) lightIntensity = 0.7 # C:\Users\Bill\anaconda3\Lib\site-packages\panda3d\models #self.floor = self.loader.loadModel('myModels/soil_6') # material texture must be png (jpg not okay) #self.floor.setPos(0, 0, -0.5) #-2.5 #self.floor.reparentTo(self.render) self.floor = self.loader.loadModel('myModels/slab') self.floor.setPos(0, 0, -1.5) # -2.5 self.floor.reparentTo(self.render) tex = self.loader.loadTexture('myModels/tex/soil_6.jpg') self.floor.setTexture(tex, 1) self.floor.setTexScale(TextureStage.getDefault(), 50, 50) rndRange = 1.2 for i in range(20): # PUT 3x100 lettuce on teh scene: self.lett_1 = self.loader.loadModel( 'myModels/lettuce_3' ) # material texture must be png (jpg not okay) rnd = random.random() * 0.1 * rndRange self.lett_1.setPos(-0.5 - rnd, 2 + i / 2, -0.5) self.lett_1.setScale(0.1, 0.1, 0.1) self.lett_1.reparentTo(self.render) self.lett_2 = self.loader.loadModel( 'myModels/lettuce_32' ) # material texture must be png (jpg not okay) rnd = random.random() * 0.1 * rndRange self.lett_2.setPos(0 - rnd, 2 + i / 2, -0.5) self.lett_2.setScale(0.1, 0.1, 0.1) self.lett_2.reparentTo(self.render) self.lett_3 = self.loader.loadModel( 'myModels/lettuce_32' ) # material texture must be png (jpg not okay) rnd = random.random() * 0.1 * rndRange self.lett_3.setPos(0.5 - rnd, 2 + i / 2, -0.5) self.lett_3.setScale(0.1, 0.1, 0.1) self.lett_3.reparentTo(self.render) #self.cone = self.loader.loadModel('myModels/cone') # material texture must be png (jpg not okay) #self.cone.setPos(1, 2, -1) ##self.cone.setScale(0.1, 0.1, 0.1) #self.cone.reparentTo(self.render) self.tree3 = self.loader.loadModel('myModels/christmas_tree') self.tree3.setPos(-4, 7, -0.5) self.tree3.reparentTo(self.render) self.box = self.loader.loadModel('models/box') self.box.setPos(0, 0, 0) # liked to camera -0.2 0.2 self.box.setScale(0.2, 0.2, 0.2) self.box.reparentTo(self.cam) # ********* END MODELS ******** # ****** AMBIENT light ********** ambientLight = AmbientLight("ambient light") ambientLight.setColor(Vec4(0.7, 0.7, 0.7, 1)) # 0.2 0.2 0.2 lightIntensity self.ambientLightNodePath = self.render.attachNewNode( ambientLight) # attach to renderer ambiant light node path #self.trees.setLight(ambientLightNodePath) self.render.setLight( self.ambientLightNodePath) # illuminate everything # ****** DIRECTIONAL light ********** mainLight = DirectionalLight("main light") mainLight.setColor(Vec4(0.5, 0.5, 0.5, 1)) self.mainLightNodePath = self.render.attachNewNode(mainLight) # Turn it around by 45 degrees, and tilt it down by 45 degrees: setHpr(45, -45, 0) self.mainLightNodePath.setHpr(45, -90, 0) render.setLight(self.mainLightNodePath) self.render.setShaderAuto() # create shadow # ********* CAMERA ******** #self.camera.lookAt(0, 1, -0.5) # Camera tilted with Y & Z coordinates self.camera.setPos(0, 0, 0) #self.camera.setHpr(90, 0, 0) #not reacting #base.camera.setHpr(90, 0, 0) # SECOND stationery: wp = WindowProperties() wp.setSize(500, 500) wp.setOrigin(800, 50) win2 = base.openWindow(props=wp, aspectRatio=1) cam2 = base.camList[1] cam2.setPos(0, 18, 5) # 2nd relative to 'camera' 2 -20 10 cam2.lookAt(0, 0, 0) cam2.reparentTo(render) taskMgr.add(self.skysphereTask, "SkySphere Task")
def __init__(self): # Set up the window, camera, etc. ShowBase.__init__(self) # Set the background color to black self.win.setClearColor((0, 0, 0, 1)) # This is used to store which keys are currently pressed. self.keyMap = { "left": 0, "right": 0, "forward": 0, "cam-left": 0, "cam-right": 0} # Post the instructions self.title = addTitle( "Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)") self.inst1 = addInstructions(0.06, "[ESC]: Quit") self.inst2 = addInstructions(0.12, "[Left Arrow]: Rotate Ralph Left") self.inst3 = addInstructions(0.18, "[Right Arrow]: Rotate Ralph Right") self.inst4 = addInstructions(0.24, "[Up Arrow]: Run Ralph Forward") self.inst6 = addInstructions(0.30, "[A]: Rotate Camera Left") self.inst7 = addInstructions(0.36, "[S]: Rotate Camera Right") # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("maps/world") self.environ.reparentTo(render) # Create the main character, Ralph ralphStartPos = self.environ.find("**/start_point").getPos() self.ralph = Actor("models/ralph", {"run": "models/ralph-run", "walk": "models/ralph-walk"}) self.ralph.reparentTo(render) self.ralph.setScale(.2) self.ralph.setPos(ralphStartPos + (0, 0, 0.5)) # Create a floater object, which floats 2 units above ralph. We # use this as a target for the camera to look at. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(self.ralph) self.floater.setZ(2.0) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", True]) self.accept("arrow_right", self.setKey, ["right", True]) self.accept("arrow_up", self.setKey, ["forward", True]) self.accept("a", self.setKey, ["cam-left", True]) self.accept("s", self.setKey, ["cam-right", True]) self.accept("arrow_left-up", self.setKey, ["left", False]) self.accept("arrow_right-up", self.setKey, ["right", False]) self.accept("arrow_up-up", self.setKey, ["forward", False]) self.accept("a-up", self.setKey, ["cam-left", False]) self.accept("s-up", self.setKey, ["cam-right", False]) taskMgr.add(self.move, "moveTask") # Game state variables self.isMoving = False # Set up the camera self.disableMouse() self.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2) # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above ralph's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. self.cTrav = CollisionTraverser() self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0, 0, 9) self.ralphGroundRay.setDirection(0, 0, -1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(CollideMask.bit(0)) self.ralphGroundCol.setIntoCollideMask(CollideMask.allOff()) self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler) self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 9) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(CollideMask.bit(0)) self.camGroundCol.setIntoCollideMask(CollideMask.allOff()) self.camGroundColNp = self.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Uncomment this line to see the collision rays #self.ralphGroundColNp.show() #self.camGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring #self.cTrav.showCollisions(render) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection((-5, -5, -5)) directionalLight.setColor((1, 1, 1, 1)) directionalLight.setSpecularColor((1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))
def attachLights(render): dl = DirectionalLight('dirLight') dl.setColor(ColorToVec4('666060')) dlNP = render.attachNewNode(dl) dlNP.setHpr(0, -45, 0) render.setLight(dlNP) dl = DirectionalLight('dirLight') dl.setColor(ColorToVec4('606666')) dlNP = render.attachNewNode(dl) dlNP.setHpr(180, 45, 0) render.setLight(dlNP) dl = DirectionalLight('dirLight') dl.setColor(ColorToVec4('606060')) dlNP = render.attachNewNode(dl) dlNP.setHpr(90, -45, 0) render.setLight(dlNP) dl = DirectionalLight('dirLight') dl.setColor(ColorToVec4('626262')) dlNP = render.attachNewNode(dl) dlNP.setHpr(-90, 45, 0) render.setLight(dlNP) ambientLight = AmbientLight('ambientLight') ambientLight.setColor(Vec4(0.2, 0.2, 0.2, 1)) ambientLightNP = render.attachNewNode(ambientLight) render.setLight(ambientLightNP)
def update(task): forward, turn, strafe, hover = 0, 0, 0, 0 if s.mouseWatcherNode.is_button_down(KeyboardButton.up()): forward += 1 if s.mouseWatcherNode.is_button_down(KeyboardButton.down()): forward -= 1 if s.mouseWatcherNode.is_button_down(KeyboardButton.left()): turn -= 1 if s.mouseWatcherNode.is_button_down(KeyboardButton.right()): turn += 1 if s.mouseWatcherNode.is_button_down(KeyboardButton.ascii_key(b'a')): strafe -= 1 if s.mouseWatcherNode.is_button_down(KeyboardButton.ascii_key(b'd')): strafe += 1 if s.mouseWatcherNode.is_button_down(KeyboardButton.ascii_key(b's')): hover += 1 animate(forward, turn, strafe, hover) #if s.mouseWatcherNode.is_button_down(KeyboardButton.space()): # control("hover") return task.cont s.taskMgr.add(update) l = DirectionalLight("light") ln = render.attachNewNode(l) render.setLight(ln) s.run()
def __init__(self): ShowBase.__init__(self) self.grid = np.loadtxt("input/maze.txt") f = open("input/start_point.txt", "r") self.start_pos = eval(f.read()) if FULLSCREEN: wp = WindowProperties() wp.setFullscreen(True) base.win.requestProperties(wp) self.disableMouse() self.accept("escape", sys.exit) self.camera.setPosHpr(self.start_pos[0], self.start_pos[1], CAMERA_SCALE, 0, -90, 0) # maze wall offset = 0.05 # expand collision boundaries for the walls for i in range(-1, len(self.grid) + 1): for j in range(-1, len(self.grid[0]) + 1): if i == -1 or j == -1 or i == len(self.grid) or j == len( self.grid[0]) or self.grid[i][j]: #box-1_-1 is not a valid name so we change it to boxa_b texti = i textj = j if i == -1: texti = 'a' if j == -1: textj = 'b' suffix = str(texti) + "_" + str(textj) # model exec("self.box" + suffix + " = self.loader.loadModel('models/cube')") exec("self.box" + suffix + ".reparentTo(self.render)") exec("self.box" + suffix + ".setPos(" + str(i) + ", " + str(j) + ", 1)") # collision node exec("self.boxCollider" + suffix + " = self.box" + suffix + ".attachNewNode(CollisionNode('wall_collide'))") exec( "self.boxCollider" + suffix + ".node().addSolid(CollisionBox(Point3(0-offset,0-offset,0-offset),Point3(1+offset,1+offset,1+offset)))" ) exec("self.boxCollider" + suffix + ".node().setIntoCollideMask(BitMask32.bit(0))") #exec("self.boxCollider" + suffix + ".show()") # maze ground model self.maze = loader.loadModel("models/cube") self.maze.setScale(len(self.grid), len(self.grid[0]), 1) self.maze.reparentTo(self.render) # maze ground collision node self.walls = self.maze.attachNewNode(CollisionNode('wall_collide')) self.walls.node().addSolid( CollisionBox(Point3(0, 0, 0), Point3(1, 1, 1))) self.walls.node().setIntoCollideMask(BitMask32.bit(1)) # maze ground plane collision node self.mazeGround = self.maze.attachNewNode( CollisionNode('ground_collide')) self.mazeGround.node().addSolid( CollisionPlane(Plane(Vec3(0, 0, 1), Point3(2, 2, 1)))) self.mazeGround.node().setIntoCollideMask(BitMask32.bit(1)) # ball model self.ballRoot = render.attachNewNode("ballRoot") self.ball = loader.loadModel("models/ball") self.ball.reparentTo(self.ballRoot) # ball material m = Material() m.setSpecular((1, 1, 1, 1)) m.setShininess(96) self.ball.setMaterial(m, 1) # ball collision node self.ballSphere = self.ball.find("**/ball") self.ballSphere.node().setFromCollideMask(BitMask32.bit(0)) self.ballSphere.node().setIntoCollideMask(BitMask32.allOff()) # collision ray self.ballGroundRay = CollisionRay() self.ballGroundRay.setOrigin(0, 0, 10) self.ballGroundRay.setDirection(0, 0, -1) # ray collision node self.ballGroundCol = CollisionNode('groundRay') self.ballGroundCol.addSolid(self.ballGroundRay) self.ballGroundCol.setFromCollideMask(BitMask32.bit(1)) self.ballGroundCol.setIntoCollideMask(BitMask32.allOff()) # ray self.ballGroundColNp = self.ballRoot.attachNewNode(self.ballGroundCol) # collision traverser and handler queue self.cHandler = CollisionHandlerQueue() self.cTrav = CollisionTraverser() self.cTrav.addCollider(self.ballSphere, self.cHandler) self.cTrav.addCollider(self.ballGroundColNp, self.cHandler) # visual effects ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.55, .55, .55, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(LVector3(0, 0, -1)) directionalLight.setColor((0.375, 0.375, 0.375, 1)) directionalLight.setSpecularColor((1, 1, 1, 1)) self.ballRoot.setLight(render.attachNewNode(ambientLight)) self.ballRoot.setLight(render.attachNewNode(directionalLight)) self.start()
def __init__(self): self.keyMap = {"left":0, "right":0, "forward":0, "back":0, "cam-left":0, "cam-right":0} self.flag1=0 self.flag2=0 self.flag3=0 self.flag4=0 self.count=0 self.health = 100 self.points = -5 self.flagd=1 self.player_points = 0 base.win.setClearColor(Vec4(0,0,0,1)) self.mySound=base.loader.loadSfx("sounds/trial.mp3") self.mySound.play() self.title = addTitle("Bumping Cars") #Full Screen props = WindowProperties.getDefault() w=base.pipe.getDisplayWidth() h=base.pipe.getDisplayHeight() props.setSize(w,h) props.setFullscreen(True) props.setCursorHidden(True) base.win.requestProperties(props) # Load World self.environ = loader.loadModel("models/world.egg") self.environ.reparentTo(render) self.environ.setPos(0,0,0) #Load Sky self.sky = loader.loadModel("models/clouds.egg") self.sky.reparentTo(render) self.sky.setPos(60,0,-450) # Create Player Car carStartPos = self.environ.find("**/start_point").getPos() self.car = Actor("models/carnsx") self.car.reparentTo(render) self.car.setScale(0.25) #self.car.place() self.car.setPos(carStartPos) # Create Enemy Car 1 enemyCarStartPos1 = (-108,-1,-.5) self.car1 = Actor("models/enemy_cars/monstercar/carmonster") self.car1.reparentTo(render) self.car1.setScale(0.25) #self.car1.place() self.car1.setPos(enemyCarStartPos1) # Create Enemy Car 2 enemyCarStartPos2 = (-104,-26,-.02) self.car2 = Actor("models/enemy_cars/yugo/yugo") self.car2.reparentTo(render) self.car2.setScale(0.15) #self.car2.place() self.car2.setPos(enemyCarStartPos2) # Create Enemy Car 3 enemyCarStartPos3 = (-111,-26,0) self.car3 = Actor("models/enemy_cars/truck/cartruck") self.car3.reparentTo(render) self.car3.setScale(0.25) #self.car3.place() self.car3.setPos(enemyCarStartPos3) # Create Enemy Car 4 enemyCarStartPos4 = (-111,-2,-.5) self.car4 = Actor("models/enemy_cars/truck/cartruck-purple") self.car4.reparentTo(render) self.car4.setScale(0.25) #self.car4.place() self.car4.setPos(enemyCarStartPos4) # Create a floater object. We use the "floater" as a temporary # variable in a variety of calculations. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("a", self.setKey, ["cam-left",1]) self.accept("s", self.setKey, ["cam-right",1]) self.accept("arrow_up",self.setKey, ["forward",1]) self.accept("arrow_left",self.setKey, ["left",1]) self.accept("arrow_down",self.setKey, ["back",1]) self.accept("arrow_right",self.setKey, ["right",1]) self.accept("a-up", self.setKey, ["cam-left",0]) self.accept("s-up", self.setKey, ["cam-right",0]) self.accept("arrow_up-up",self.setKey, ["forward",0]) self.accept("arrow_left-up",self.setKey, ["left",0]) self.accept("arrow_right-up",self.setKey, ["right",0]) self.accept("arrow_down-up",self.setKey, ["back",0]) taskMgr.add(self.move,"moveTask") # Game state variables self.isMoving = False # Set up the camera base.disableMouse() base.camera.setPos(self.car.getX(),self.car.getY()+10,2) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight)) # AI self.AIworld = AIWorld(render) # AI Car 1 self.AIchar1 = AICharacter("car1",self.car1, 70, 0.1, 3) self.AIworld.addAiChar(self.AIchar1) self.AIbehaviors1 = self.AIchar1.getAiBehaviors() self.AIbehaviors1.pursue(self.car) # AI Car 2 self.AIchar2 = AICharacter("car2",self.car2, 180, 0.1, 1) self.AIworld.addAiChar(self.AIchar2) self.AIbehaviors2 = self.AIchar2.getAiBehaviors() self.AIbehaviors2.pursue(self.car4) # AI Car 3 self.AIchar3 = AICharacter("car3",self.car3, 70, 0.1, 3) self.AIworld.addAiChar(self.AIchar3) self.AIbehaviors3 = self.AIchar3.getAiBehaviors() self.AIbehaviors3.pursue(self.car) # AI Car 4 self.AIchar4 = AICharacter("car4",self.car4, 200, 0.5, 2) self.AIworld.addAiChar(self.AIchar4) self.AIbehaviors4 = self.AIchar4.getAiBehaviors() self.AIbehaviors4.pursue(self.car3) # Obstacle avoidance self.AIbehaviors1.obstacleAvoidance(1.0) self.AIworld.addObstacle(self.car2) self.AIworld.addObstacle(self.car3) self.AIworld.addObstacle(self.car4) self.AIbehaviors2.obstacleAvoidance(1.0) self.AIbehaviors3.obstacleAvoidance(1.0) self.AIbehaviors4.obstacleAvoidance(1.0) #AI World update taskMgr.add(self.AIUpdate,"AIUpdate") self.cTrav = CollisionTraverser() #self.cTrav.showCollisions(render) self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0,0,1000) self.ralphGroundRay.setDirection(0,0,-1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0)) self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff()) self.carGroundColNp = self.car.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.carGroundColNp, self.ralphGroundHandler) #car1 self.car1Ray = CollisionSphere(0,0,0,4) self.car1GroundCol = CollisionNode('car1Ray') self.car1GroundCol.addSolid(self.car1Ray) self.car1GroundCol.setFromCollideMask(BitMask32.bit(0)) self.car1GroundCol.setIntoCollideMask(BitMask32.allOff()) self.car1GroundColNp = self.car.attachNewNode(self.car1GroundCol) self.car1GroundHandler = CollisionHandlerQueue() #self.car1GroundColNp.show() self.cTrav.addCollider(self.car1GroundColNp, self.car1GroundHandler) cnodePath = self.car1.attachNewNode(CollisionNode('cnode1')) cnodePath.node().addSolid(self.car1Ray) #cnodePath.show() #car2 self.car2Ray = CollisionSphere(0,0,0,4) self.car2GroundCol = CollisionNode('car2Ray') self.car2GroundCol.addSolid(self.car2Ray) self.car2GroundCol.setFromCollideMask(BitMask32.bit(0)) self.car2GroundCol.setIntoCollideMask(BitMask32.allOff()) self.car2GroundColNp = self.car.attachNewNode(self.car2GroundCol) self.car2GroundHandler = CollisionHandlerQueue() #self.car2GroundColNp.show() self.cTrav.addCollider(self.car2GroundColNp, self.car2GroundHandler) cnodePath = self.car2.attachNewNode(CollisionNode('cnode2')) cnodePath.node().addSolid(self.car2Ray) #cnodePath.show() #car3 self.car3Ray = CollisionSphere(0,0,0,4) self.car3GroundCol = CollisionNode('car3Ray') self.car3GroundCol.addSolid(self.car3Ray) self.car3GroundCol.setFromCollideMask(BitMask32.bit(0)) self.car3GroundCol.setIntoCollideMask(BitMask32.allOff()) self.car3GroundColNp = self.car.attachNewNode(self.car3GroundCol) self.car3GroundHandler = CollisionHandlerQueue() #self.car3GroundColNp.show() self.cTrav.addCollider(self.car3GroundColNp, self.car3GroundHandler) cnodePath = self.car3.attachNewNode(CollisionNode('cnode3')) cnodePath.node().addSolid(self.car3Ray) #cnodePath.show() #car4 self.car4Ray = CollisionSphere(0,0,0,4) self.car4GroundCol = CollisionNode('car4Ray') self.car4GroundCol.addSolid(self.car4Ray) self.car4GroundCol.setFromCollideMask(BitMask32.bit(0)) self.car4GroundCol.setIntoCollideMask(BitMask32.allOff()) self.car4GroundColNp = self.car.attachNewNode(self.car4GroundCol) self.car4GroundHandler = CollisionHandlerQueue() #self.car4GroundColNp.show() self.cTrav.addCollider(self.car4GroundColNp, self.car4GroundHandler) cnodePath = self.car4.attachNewNode(CollisionNode('cnode4')) cnodePath.node().addSolid(self.car4Ray) #cnodePath.show() #camera self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0,0,1000) self.camGroundRay.setDirection(0,0,-1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(BitMask32.bit(0)) self.camGroundCol.setIntoCollideMask(BitMask32.allOff()) self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler)
def __init__(self): self.keyMap = { "arrow_left": 0, "arrow_right": 0, "arrow_up": 0, "arrow_down": 0, "cam-left": 0, "cam-right": 0, "make-bunny": 0, "do-something": 0, "ignore": 0 } base.win.setClearColor(Vec4(0, 0, 0, 1)) # Track all of the bunnies self.bunnies = [] # Post the instructions self.title = addTitle("Keyboard Roaming") self.inst1 = addInstructions(0.95, "[Shift+ESC]: Quit") self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left") self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right") self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward") self.inst4 = addInstructions(0.75, "[Down Arrow]: Run Ralph Backward") self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left") self.inst7 = addInstructions(0.65, "[S]: Rotate Camera Right") # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) self.environ.setPos(0, 0, 0) # Create the main character, Ralph ralphStartPos = self.environ.find("**/start_point").getPos() self.ralph = Actor("models/ralph", { "run": "models/ralph-run", "walk": "models/ralph-walk" }) self.ralph.reparentTo(render) self.ralph.setScale(0.3) self.ralph.setPos(ralphStartPos) # Create a floater object. We use the "floater" as a temporary # variable in a variety of calculations. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # Shift+ESC key exits self.accept("shift-escape", sys.exit) # Tke keyboard is divided into six sections or tiles: # # 1 2 # +----------------+ +-------------+ # | f1 ... F5 | | F6 ... F12 | # +----------------+ +-------------+ # # 3 4 # +----------------+ +-------------------------+ # | ` 1 2 3 4 5 6 | | 7 8 9 0 - = BACKSPACE | # | Q W E R T Y | | Y U I O P [ ] \ | # | A S D F G | | H J K L ; ' ENTER | # | Z X C V B | | N M , . / | # | CTRL WIN ALT | | SPACE ALT WIN MENU CTRL | # +----------------+ +-------------------------+ # # 5 # +----------------------+ # | PRT SCR PAUSE | # | INSERT HOME PAGEUP | # | DELETE END PAGEDOWN | # +----------------------+ # 6 # +----------------------+ # | UP LEFT DOWN RIGHT | # +----------------------+ # Section1 = ["f1", "f2", "f3", "f4", "f5"] Section2 = ["f6", "f7", "f8", "f9", "f10", "f11", "f12"] Section3 = [ "`", "1", "2", "3", "4", "5", "6", "q", "w", "e", "r", "t", "y", "a", "s", "d", "f", "g", "lshift", "z", "x", "c", "v", "b" ] Section4 = [ "7", "8", "9", "0", "backspace", "y", "u", "i", "o", "p", "[", "]", "\\", "h", "j", "k", "l", ";", "'", "enter", "n", "m", ",", ".", "/", "rshift" ] Section5 = [ "print_screen", "scroll_lock", "pause", "insert", "home", "page_up", "delete", "end", "page_down" ] Section6 = ["arrow_left", "arrow_right", "arrow_up", "arrow_down"] # Map each section action = "cam-left" for k in Section1: self.accept(k, self.setKey, [action, 1]) self.accept("shift-" + k, self.setKey, [action, 1]) self.accept(k + "-up", self.setKey, [action, 0]) self.accept("shift-" + k + "-up", self.setKey, [action, 0]) action = "cam-right" for k in Section2: self.accept(k, self.setKey, [action, 1]) self.accept("shift-" + k, self.setKey, [action, 1]) self.accept(k + "-up", self.setKey, [action, 0]) self.accept("shift-" + k + "-up", self.setKey, [action, 0]) action = "arrow_up" for k in Section3: self.accept(k, self.setKey, [action, 1]) self.accept("shift-" + k, self.setKey, [action, 1]) self.accept(k + "-up", self.setKey, [action, 0]) self.accept("shift-" + k + "-up", self.setKey, [action, 0]) action = "arrow_down" for k in Section4: self.accept(k, self.setKey, [action, 1]) self.accept("shift-" + k, self.setKey, [action, 1]) self.accept(k + "-up", self.setKey, [action, 0]) self.accept("shift-" + k + "-up", self.setKey, [action, 0]) action = "make-bunny" for k in Section5: self.accept(k, self.setKey, [action, 1]) self.accept("shift-" + k, self.setKey, [action, 1]) self.accept(k + "-up", self.setKey, [action, 0]) self.accept("shift-" + k + "-up", self.setKey, [action, 0]) for k in Section6: self.accept(k, self.setKey, [k, 1]) self.accept("shift-" + k, self.setKey, [k, 1]) self.accept(k + "-up", self.setKey, [k, 0]) self.accept("shift-" + k + "-up", self.setKey, [k, 0]) taskMgr.add(self.move, "moveTask") # Game state variables self.isMoving = False # Set up the camera base.disableMouse() base.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2) # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above ralph's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. self.cTrav = CollisionTraverser() self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0, 0, 1000) self.ralphGroundRay.setDirection(0, 0, -1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0)) self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff()) self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler) self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 1000) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(BitMask32.bit(0)) self.camGroundCol.setIntoCollideMask(BitMask32.allOff()) self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Uncomment this line to see the collision rays #self.ralphGroundColNp.show() #self.camGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring #self.cTrav.showCollisions(render) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight)) # Set up some sounds self.runSound = base.loader.loadSfx( "sounds/54779__bevangoldswain__running-hard-surface.wav") self.bumpSound = base.loader.loadSfx( "sounds/31126__calethos__bump.wav") self.spawnSound = base.loader.loadSfx( "sounds/51710__bristolstories__u-chimes3.mp3")
class Main(ShowBase): def __init__(self): ShowBase.__init__(self) self.key = {"left":0, "right": 0, "forward":0, "backward":0, "cam_left": 0,"cam_right": 0, "cam_down": 0, "cam_up": 0, "up":0, "down": 0} ##################### # # Simply testing procedural cave generation # ##################### self.start = PlatformSeg(LVector3(0,0,0)) self.start.generateAllParts(render) #################### # # Setting light so that we could see the definition in the walls # #################### render.setShaderAuto() self.dlight = DirectionalLight('dlight') self.dlight.setColor(LVector4(0.3, 0.1, 0.7, 1)) dlnp = render.attachNewNode(self.dlight) dlnp.setHpr(90, 20, 0) render.setLight(dlnp) self.alight = render.attachNewNode(AmbientLight("Ambient")) self.alight.node().setColor(LVector4(0.3, 0.3, 0.5, .1)) render.setLight(self.alight) base.disableMouse() base.camera.setPos(0, -20, 500) base.camera.setP(-50) self.bindKeys() def setKey(self, key, value): self.key[key] = value def bindKeys(self): self.accept("escape", sys.exit); self.accept("a", self.setKey, ["left", True]) self.accept("a-up", self.setKey, ["left", False]) self.accept("d", self.setKey, ["right", True]) self.accept("d-up", self.setKey, ["right", False]) self.accept("w", self.setKey, ["forward", True]) self.accept("w-up", self.setKey, ["forward", False]) self.accept("s", self.setKey, ["backward", True]) self.accept("s-up", self.setKey, ["backward", False]) self.accept("space", self.setKey, ["down", True]) self.accept("space-up", self.setKey, ["down", False]) self.accept("shift", self.setKey, ["up", True]) self.accept("shift-up", self.setKey, ["up", False]) self.accept("arrow_up", self.setKey, ["cam_up", True]) self.accept("arrow_up-up", self.setKey, ["cam_up", False]) self.accept("arrow_down", self.setKey, ["cam_down", True]) self.accept("arrow_down-up", self.setKey, ["cam_down", False]) self.accept("arrow_left", self.setKey, ["cam_left", True]) self.accept("arrow_left-up", self.setKey, ["cam_left", False]) self.accept("arrow_right", self.setKey, ["cam_right", True]) self.accept("arrow_right-up", self.setKey, ["cam_right", False]) taskMgr.add(self.update, "update") def update(self, task): delta = globalClock.getDt() WALKSPEED = 300 SPEED = 100 if self.key["left"]: base.camera.setX(base.camera.getX() - WALKSPEED*delta) if self.key["right"]: base.camera.setX(base.camera.getX() + WALKSPEED*delta) if self.key["forward"]: base.camera.setY(base.camera.getY() + WALKSPEED*delta) if self.key["backward"]: base.camera.setY(base.camera.getY() - WALKSPEED*delta) if self.key["up"]: base.camera.setZ(base.camera.getZ() + WALKSPEED*delta) if self.key["down"]: base.camera.setZ(base.camera.getZ() - WALKSPEED*delta) if self.key["cam_left"]: base.camera.setH(base.camera.getH() + SPEED*delta) if self.key["cam_right"]: base.camera.setH(base.camera.getH() - SPEED*delta) if self.key["cam_up"]: base.camera.setP(base.camera.getP() + SPEED*delta) if self.key["cam_down"]: base.camera.setP(base.camera.getP() - SPEED*delta) for p in self.start.iceCubes: p.bob() return task.cont
def __init__(self): ShowBase.__init__(self) # Override defaults self.disableMouse() self.setBackgroundColor(VBase3(160, 200, 150) / 255.0) self.setFrameRateMeter(True) # Lights dlight = DirectionalLight("dlight") dlnp = self.render.attachNewNode(dlight) dlnp.setHpr(180.0, -70.0, 0) self.render.setLight(dlnp) alight = AmbientLight("alight") alnp = self.render.attachNewNode(alight) alight.setColor(VBase4(0.4, 0.4, 0.4, 1)) self.render.setLight(alnp) # Collision traverser self.cTrav = CollisionTraverser("collisionTraverser") # Collision handlers self.carCollisionHandler = CollisionHandlerEvent() self.carCollisionHandler.addInPattern("%fn-into-%in") # Camera controls self.cameraController = CameraController(self, 400, math.pi / 4.0, math.pi / 4.0) # Load the track self.track = self.loader.loadModel("models/trackMotegi") #self.track = self.loader.loadModel("models/trackValencia") checkpointsCollision = self.track.find("checkpoints").node() checkpointsCollision.setIntoCollideMask(BitMask32(0xF0)) self.numCheckpoints = checkpointsCollision.getNumSolids() self.track.reparentTo(self.render) # Neuroevolution self.generationCount = 0 self.generationSize = 20 self.cars = [] for i in range(self.generationSize): car = NeuroevolutionCar(self, i) # Register car collisions with track self.cTrav.addCollider(car.carCollider, self.carCollisionHandler) self.accept("carCollider{}-into-trackCollision".format(i), car.onCrash) self.accept("carCollider{}-into-checkpoints".format(i), car.onCheckpoint) self.cars.append(car) # Run learning task self.taskMgr.add(self.neuroevolution, "NeuroevolutionTask") # DEBUG self.txtGen = OnscreenText(text='', pos=(0.0, -0.04), scale=0.05, align=TextNode.ALeft, fg=(1, 1, 1, 1), bg=(0, 0, 0, .4)) self.txtGen.reparentTo(self.a2dTopLeft)
def __init__(self): ShowBase.__init__(self) self.SPHERE_SIZE = 5 self.radius = self.SPHERE_SIZE / 1.5 # This is the extra distance between the spheres not immediately adjacent. # extra_distance specifies how much crowding is allowed. self.extra_distance = int(round(1.8 * self.radius)) self.DIST_BTW = 35 self.v1 = [1] self.v3 = [True] self.v4 = [1] self.params = [self.SPHERE_SIZE, 1, self.DIST_BTW, True, 1] """ Output: params[0] - sphere size params[1] - One point = 1, Two points = 2, Cerebellum simulation = 3 params[2] - how far apart two points will be if you choose two (2 for params[1]) params[3] - How many points for the cerebellar simulation, 4 = True, 5 = False params[4] - What color scheme. Gray = 1, random = 2, RGBY(W) = 3 """ # possible_vectors is calculated in self.calculate() possible_vectors = [] self.possible_vectors = possible_vectors # List of all the spheres. sphere_list = [] self.sphere_list = sphere_list # Lists of spheres that can actually grow. self.outside_sphere_list0 = [] self.outside_sphere_list1 = [] self.outside_sphere_list2 = [] self.outside_sphere_list3 = [] self.outside_sphere_list4 = [] # Counters for the lists that can grow. self.counter_list0 = [] self.counter_list1 = [] self.counter_list2 = [] self.counter_list3 = [] self.counter_list4 = [] # Set background color to white. base.setBackgroundColor(1, 1, 1) # Set ambient and directional light on the sphere. self.ambientLight = AmbientLight("ambientLight") self.ambientLight.setColor((0.3, 0.4, 0.5, 1)) self.directionalLight = DirectionalLight("directionalLight") # Angles the light just a little. self.directionalLight.setDirection(LVector3(0, 5, -5)) self.directionalLight.setColor((0.9, 0.9, 0.9, 1)) # Have to disable mouse to enable camera position. self.disableMouse() self.camera.setPos(0, -300, 0) # Sets the camera back. # Stock code from the Panda3D manual that reactivates the mouse standard. # Left click moves in the x and z planes, right click in the y plane. # Both together rotates around (0, 0, 0). mat = Mat4(camera.getMat()) mat.invertInPlace() base.mouseInterfaceNode.setMat(mat) base.enableMouse() # Call input_variables, DirectGui start screen. # It allows a user to adjust a few features of the Brownian tree(s) # and color. At present, the sphere size can be changed, but it # quickly runs into limited size due to limiting factors in the # self.add_sphere() function. It can't be too crowded around a sphere # or else you can't see anything between the rendered spheres. self.input_variables()
def __init__(self): # Initialize the ShowBase class from which we inherit, which will # create a window and set up everything we need for rendering into it. ShowBase.__init__(self) base.disableMouse() base.setBackgroundColor(0, 0, 0) camera.setPos(0, -50, 0) # Check video card capabilities. if not base.win.getGsg().getSupportsBasicShaders(): addTitle( "Glow Filter: Video driver reports that Cg shaders are not supported." ) return # Use class 'CommonFilters' to enable a bloom filter. # The brightness of a pixel is measured using a weighted average # of R,G,B,A. We put all the weight on Alpha, meaning that for # us, the framebuffer's alpha channel alpha controls bloom. self.filters = CommonFilters(base.win, base.cam) filterok = self.filters.setBloom(blend=(0, 0, 0, 1), desat=-0.5, intensity=3.0, size="small") if (filterok == False): addTitle( "Toon Shader: Video card not powerful enough to do image postprocessing" ) return self.glowSize = 1 # Post the instructions self.title = addTitle("Panda3D: Tutorial - Glow Filter") self.inst1 = addInstructions(0.06, "ESC: Quit") self.inst2 = addInstructions( 0.12, "Space: Toggle Glow Filter Small/Med/Large/Off") self.inst3 = addInstructions(0.18, "Enter: Toggle Running/Spinning") self.inst4 = addInstructions(0.24, "V: View the render-to-texture results") # load our model self.tron = Actor() self.tron.loadModel("models/tron") self.tron.loadAnims({"running": "models/tron_anim"}) self.tron.reparentTo(render) self.interval = self.tron.hprInterval(60, LPoint3(360, 0, 0)) self.interval.loop() self.isRunning = False # put some lighting on the model dlight = DirectionalLight('dlight') alight = AmbientLight('alight') dlnp = render.attachNewNode(dlight) alnp = render.attachNewNode(alight) dlight.setColor((1.0, 0.7, 0.2, 1)) alight.setColor((0.2, 0.2, 0.2, 1)) dlnp.setHpr(0, -60, 0) render.setLight(dlnp) render.setLight(alnp) # Panda contains a built-in viewer that lets you view the results of # your render-to-texture operations. This code configures the viewer. self.accept("v", base.bufferViewer.toggleEnable) self.accept("V", base.bufferViewer.toggleEnable) base.bufferViewer.setPosition("llcorner") base.bufferViewer.setLayout("hline") # base.camLens.setFov(100) # event handling self.accept("space", self.toggleGlow) self.accept("enter", self.toggleDisplay) self.accept("escape", sys.exit, [0])
def __init__(self): ShowBase.__init__(self) self.disableMouse() properties = WindowProperties() properties.setSize(1000, 750) self.win.requestProperties(properties) mainLight = DirectionalLight("main light") self.mainLightNodePath = render.attachNewNode(mainLight) self.mainLightNodePath.setHpr(45, -45, 0) render.setLight(self.mainLightNodePath) ambientLight = AmbientLight("ambient light") ambientLight.setColor(Vec4(0.2, 0.2, 0.2, 1)) self.ambientLightNodePath = render.attachNewNode(ambientLight) render.setLight(self.ambientLightNodePath) render.setShaderAuto() self.environment = loader.loadModel("Models/Misc/environment") self.environment.reparentTo(render) self.camera.setPos(0, 0, 32) self.camera.setP(-90) self.keyMap = { "up" : False, "down" : False, "left" : False, "right" : False, "shoot" : False } self.accept("w", self.updateKeyMap, ["up", True]) self.accept("w-up", self.updateKeyMap, ["up", False]) self.accept("s", self.updateKeyMap, ["down", True]) self.accept("s-up", self.updateKeyMap, ["down", False]) self.accept("a", self.updateKeyMap, ["left", True]) self.accept("a-up", self.updateKeyMap, ["left", False]) self.accept("d", self.updateKeyMap, ["right", True]) self.accept("d-up", self.updateKeyMap, ["right", False]) self.accept("mouse1", self.updateKeyMap, ["shoot", True]) self.accept("mouse1-up", self.updateKeyMap, ["shoot", False]) self.pusher = CollisionHandlerPusher() self.cTrav = CollisionTraverser() self.pusher.setHorizontal(True) wallSolid = CollisionTube(-8.0, 0, 0, 8.0, 0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(8.0) wallSolid = CollisionTube(-8.0, 0, 0, 8.0, 0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(-8.0) wallSolid = CollisionTube(0, -8.0, 0, 0, 8.0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setX(8.0) wallSolid = CollisionTube(0, -8.0, 0, 0, 8.0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setX(-8.0) self.updateTask = taskMgr.add(self.update, "update") self.player = Player(Vec3(0, 0, 0), "Models/PandaChan/act_p3d_chan", { "stand" : "Models/PandaChan/a_p3d_chan_idle", "walk" : "Models/PandaChan/a_p3d_chan_run" }, 5, 10, "player") self.tempEnemy = WalkingEnemy(Vec3(5, 0, 0))
def __init__(self): # Set up the window, camera, etc. ShowBase.__init__(self) # Set the background color to black self.win.setClearColor(BACKGROUND_COLOR) # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) # Create the main character playerStartPos = self.environ.find("**/start_point").getPos() self.player = Actor("models/player", {"run": "models/player-run", "walk": "models/player-walk"}) self.player.reparentTo(render) self.player.setScale(.2) self.player.setPos(playerStartPos + (0, 0, 0.5)) # Create a floater object, which floats 2 units above player. We # use this as a target for the camera to look at. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(self.player) self.floater.setZ(CAMERA_TARGET_HEIGHT_DELTA) self.first_person = False def key_dn(name): return lambda: self.setKey(name, True) def key_up(name): return lambda: self.setKey(name, False) def quit(): self.destroy() def toggle_first(): self.first_person = not self.first_person # Accept the control keys for movement and rotation key_map = [ # key command action help # --- ------- ------ ---- ("escape", "esc", lambda: quit(), '[ESC]: Quit'), ("arrow_left", 'left', key_dn("left"), "[Left Arrow]: Rotate Left"), ("arrow_left-up", 'left', key_up("left"), None), ("arrow_right", 'right', key_dn("right"), "[Right Arrow]: Rotate Right"), ("arrow_right-up", 'right', key_up("right"), None), ("arrow_up", 'forward', key_dn("forward"), "[Up Arrow]: Run Forward"), ("arrow_up-up", 'forward', key_up("forward"), None), ("arrow_down", 'backward', key_dn("backward"), "[Down Arrow]: Run Backward"), ("arrow_down-up", 'backward', key_up("backward"), None), ("a", 'cam-left', key_dn("cam-left"), "[A]: Rotate Camera Left"), ("a-up", 'cam-left', key_up("cam-left"), None), ("s", 'cam-right', key_dn("cam-right"), "[S]: Rotate Camera Right"), ("s-up", 'cam-right', key_up("cam-right"), None), ('f', 'first-pers', lambda: toggle_first(), '[F]: Toggle first-person'), ] self.keyMap = {} inst = Instructions() for key, command, action, description in key_map: if command: self.setKey(command, False) self.accept(key, action) if description: inst.add(description) taskMgr.add(self.move, "moveTask") # Game state variables self.isMoving = False # Set up the camera self.disableMouse() self.camera.setPos(self.player.getX(), self.player.getY() + 10, 2) # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above player's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. self.cTrav = CollisionTraverser() self.playerGroundRay = CollisionRay() self.playerGroundRay.setOrigin(0, 0, 9) self.playerGroundRay.setDirection(0, 0, -1) self.playerGroundCol = CollisionNode('playerRay') self.playerGroundCol.addSolid(self.playerGroundRay) self.playerGroundCol.setFromCollideMask(CollideMask.bit(0)) self.playerGroundCol.setIntoCollideMask(CollideMask.allOff()) self.playerGroundColNp = self.player.attachNewNode(self.playerGroundCol) self.playerGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.playerGroundColNp, self.playerGroundHandler) self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 9) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(CollideMask.bit(0)) self.camGroundCol.setIntoCollideMask(CollideMask.allOff()) self.camGroundColNp = self.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Uncomment this line to see the collision rays self.playerGroundColNp.show() self.camGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring self.cTrav.showCollisions(render) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection((-5, -5, -5)) directionalLight.setColor((1, 1, 1, 1)) directionalLight.setSpecularColor((1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))
def __init__(self): self.login = "******" base.setFrameRateMeter(True) #input states inputState.watchWithModifiers('forward', 'w') inputState.watchWithModifiers('left', 'a') inputState.watchWithModifiers('brake', 's') inputState.watchWithModifiers('right', 'd') inputState.watchWithModifiers('turnLeft', 'q') inputState.watchWithModifiers('turnRight', 'e') self.keyMap = { "hello": 0, "left": 0, "right": 0, "forward": 0, "backward": 0, "cam-left": 0, "cam-right": 0, "chat0": 0, "powerup": 0, "reset": 0 } base.win.setClearColor(Vec4(0, 0, 0, 1)) # Network Setup self.cManager = ConnectionManager(self) self.startConnection() #self.cManager.sendRequest(Constants.CMSG_LOGIN, ["username", "password"]) # chat box # self.chatbox = Chat(self.cManager, self) # Set up the environment # self.initializeBulletWorld(False) #self.createEnvironment() Track(self.bulletWorld) # Create the main character, Ralph self.mainCharRef = Vehicle(self.bulletWorld, (100, 10, 5, 0, 0, 0), self.login) #self.mainCharRef = Character(self, self.bulletWorld, 0, "Me") self.mainChar = self.mainCharRef.chassisNP #self.mainChar.setPos(0, 25, 16) # self.characters.append(self.mainCharRef) # self.TestChar = Character(self, self.bulletWorld, 0, "test") # self.TestChar.actor.setPos(0, 0, 0) self.previousPos = self.mainChar.getPos() taskMgr.doMethodLater(.1, self.updateMove, 'updateMove') # Set Dashboard self.dashboard = Dashboard(self.mainCharRef, taskMgr) self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # Accept the control keys for movement and rotation self.accept("escape", self.doExit) self.accept("a", self.setKey, ["left", 1]) self.accept("d", self.setKey, ["right", 1]) self.accept("w", self.setKey, ["forward", 1]) self.accept("s", self.setKey, ["backward", 1]) self.accept("arrow_left", self.setKey, ["cam-left", 1]) self.accept("arrow_right", self.setKey, ["cam-right", 1]) self.accept("a-up", self.setKey, ["left", 0]) self.accept("d-up", self.setKey, ["right", 0]) self.accept("w-up", self.setKey, ["forward", 0]) self.accept("s-up", self.setKey, ["backward", 0]) self.accept("arrow_left-up", self.setKey, ["cam-left", 0]) self.accept("arrow_right-up", self.setKey, ["cam-right", 0]) self.accept("h", self.setKey, ["hello", 1]) self.accept("h-up", self.setKey, ["hello", 0]) self.accept("0", self.setKey, ["chat0", 1]) self.accept("0-up", self.setKey, ["chat0", 0]) self.accept("1", self.setKey, ["powerup", 1]) self.accept("1-up", self.setKey, ["powerup", 0]) self.accept("2", self.setKey, ["powerup", 2]) self.accept("2-up", self.setKey, ["powerup", 0]) self.accept("3", self.setKey, ["powerup", 3]) self.accept("3-up", self.setKey, ["powerup", 0]) self.accept("r", self.doReset) self.accept("p", self.setTime) #taskMgr.add(self.move, "moveTask") # Game state variables self.isMoving = False # Sky Dome self.sky = SkyDome() # Set up the camera self.camera = Camera(self.mainChar) #base.disableMouse() #base.camera.setPos(self.mainChar.getX(), self.mainChar.getY() + 10, self.mainChar.getZ() + 2) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) directionalLight2 = DirectionalLight("directionalLight2") directionalLight2.setDirection(Vec3(5, 5, -5)) directionalLight2.setColor(Vec4(1, 1, 1, 1)) directionalLight2.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight)) render.setLight(render.attachNewNode(directionalLight2)) # Game initialisation self.gameState = self.gameStateDict["Login"] self.responseValue = -1 self.cManager.sendRequest(Constants.CMSG_LOGIN, [self.login, "1234"]) taskMgr.add(self.enterGame, "EnterGame") # Create Powerups self.createPowerups() taskMgr.add(self.powerups.checkPowerPickup, "checkPowerupTask") taskMgr.add(self.usePowerup, "usePowerUp")
def __init__(self): # Set up the window, camera, etc. ShowBase.__init__(self) # Set the background color to black self.win.setClearColor((0, 0, 0, 1)) # Post the instructions self.title = addTitle( "Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)") self.inst1 = addInstructions(0.06, "[ESC]: Quit") self.inst2 = addInstructions(0.12, "[Left trackpad]: Rotate Left") self.inst3 = addInstructions(0.18, "[Right trackpad]: Rotate Right") self.inst4 = addInstructions(0.24, "[Up trackpad]: Walk Forward") self.inst4 = addInstructions(0.30, "[Down trackpad]: Walk Backward") # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) # Create the main character, Ralph self.vr = RoamingRalphVR() self.vr.init() self.ralph = render.attachNewNode('ralph') self.ralphStartPos = self.environ.find("**/start_point").getPos() self.vr.tracking_space.setPos(self.ralphStartPos) self.ralph.setPos(self.vr.hmd_anchor.getPos(render)) self.accept("escape", sys.exit) taskMgr.add(self.collision, "collisionTask") # Set up the camera self.disableMouse() # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above ralph's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. self.cTrav = CollisionTraverser() self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0, 0, 9) self.ralphGroundRay.setDirection(0, 0, -1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(CollideMask.bit(0)) self.ralphGroundCol.setIntoCollideMask(CollideMask.allOff()) self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler) # Uncomment this line to see the collision rays #self.ralphGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring #self.cTrav.showCollisions(render) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection((-5, -5, -5)) directionalLight.setColor((1, 1, 1, 1)) directionalLight.setSpecularColor((1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))
def __init__(self): ShowBase.__init__(self) properties = WindowProperties() properties.setSize(1000, 750) self.dr = self.camNode.getDisplayRegion(0) self.dr.setActive(0) # disable print(self.dr.getSort()) self.dr1 = self.win.makeDisplayRegion(0.0, 0.5, 0, .5) self.dr1.setSort(self.dr.getSort()) self.dr1.setCamera(self.camList[0]) self.dr2 = self.win.makeDisplayRegion(0.5, 1, 0, 0.5) self.makeCamera(self.win,sort=0,displayRegion=(0.5,1,0.5,1),camName="cam2") self.disableMouse() self.environment = loader.loadModel("environment/environment") self.environment.reparentTo(render) self.monkey = Actor("models/monkey") self.monkey.set_scale(.25) self.monkey.reparentTo(render) self.monkey.set_pos(0,0,2) self.monkey2 = Actor("models/monkey") self.monkey2.set_scale(.25) self.monkey2.reparentTo(render) self.monkey2.set_pos(0,3,2) self.camList[0].reparentTo(self.monkey) self.camList[1].reparentTo(self.monkey2) self.taskMgr.add(self.example_Task, "updateTask") ambientLight = AmbientLight("ambient light") ambientLight.setColor(Vec4(0.2, 0.2, 0.2, 1)) self.ambientLightNodePath = render.attachNewNode(ambientLight) render.setLight(self.ambientLightNodePath) # In the body of your code mainLight = DirectionalLight("main light") self.mainLightNodePath = render.attachNewNode(mainLight) # Turn it around by 45 degrees, and tilt it down by 45 degrees self.mainLightNodePath.setHpr(45, -45, 0) render.setLight(self.mainLightNodePath) render.setShaderAuto() print('Cameras') print(self.camList) print('Number Of Display Regions') print(self.win.getNumDisplayRegions()) print('Active Display Regions') print(self.win.getActiveDisplayRegions()) self.win.removeDisplayRegion(self.win.getDisplayRegion(1)) self.win.removeDisplayRegion(self.win.getDisplayRegion(1)) self.win.removeDisplayRegion(self.win.getDisplayRegion(1)) print(self.win.getDisplayRegions()) print('Number Of Display Regions') print(self.win.getNumDisplayRegions()) self.disableMouse() self.useTrackball() #self.win.getDisplayRegion(2).saveScreenshotDefault('www') #this works but I get black screen because it gets the SC before the rendering texture = self.win.getDisplayRegion(1).getScreenshot() numpy_image_data=np.array(texture.getRamImageAs("RGB"), np.float32) print(np.max(numpy_image_data[123456]))
from direct.showbase.ShowBase import ShowBase import simplepbr from panda3d.core import DirectionalLight, AmbientLight ShowBase() pipeline = simplepbr.init() lightSun = DirectionalLight('light_sun') lightSun.setColorTemperature(5300) lightSun.setShadowCaster(True, 2048, 2048) lightSunNP = render.attachNewNode(lightSun) lightSunNP.setPos(2, 2, 2) lightSunNP.lookAt(0, 0, 0) render.setLight(lightSunNP) lightAmb = AmbientLight('light_ambient') lightAmb.setColor((0.1, 0.1, 0.1, 1)) lightAmbNP = render.attachNewNode(lightAmb) render.setLight(lightAmbNP) model = base.loader.loadModel("./warrior.bam") #model.setPos(0, 3, -0.5) model.setScale(50) model.reparentTo(render) run()
def __init__(self): ShowBase.__init__(self) self.cloud = False self.help = False self.screen_text = [] #Desglosamos archivo PDB pdbdata = sys.argv[1] parser = PDBParser(QUIET=True, PERMISSIVE=True) structure = parser.get_structure('model', pdbdata) #Hacemos la prediccion DSSP model = structure[0] dssp = DSSP(model, pdbdata) #Creamos los modelos self.cpknode = render.attachNewNode("CPK") self.aanode = render.attachNewNode("Aminoacids") self.bbnode = render.attachNewNode("BackBone") self.dsspnode = render.attachNewNode("DSSP") self.nnode = render.attachNewNode("Cloud") #CPK for atom in structure.get_atoms(): x, y, z = atom.coord atomid = atom.get_id() a = loader.loadModel("data/atom_sphere") a.setPos(x, y, z) a.reparentTo(self.cpknode) a.setColor(colorrgba(atomid)) a.setScale(vrad(atomid)) self.cpknode.flattenStrong() #Aminoacids self.residues = [ residue for residue in structure.get_residues() if residue.get_resname() in resdict.keys() ] for residue in self.residues: resid = residue.get_resname() color = colorrgba(restype(resid)) atoms = [atom for atom in residue.get_atoms()] for atom in atoms: x, y, z = atom.coord atomid = atom.get_id() a = loader.loadModel("data/atom_sphere") a.setPos(x, y, z) a.setColor(color) a.setScale(vrad(atomid)) a.reparentTo(self.aanode) self.residues2 = [ residue for residue in structure.get_residues() if not residue in self.residues and residue.get_resname() != 'HOH' ] for residue in self.residues2: atoms = [atom for atom in residue.get_atoms()] for atom in atoms: x, y, z = atom.coord atomid = atom.get_id() a = loader.loadModel("data/atom_sphere") a.setPos(x, y, z) a.setColor(colorrgba(atomid)) a.setScale(vrad(atomid)) a.reparentTo(self.aanode) self.aanode.flattenStrong() self.aanode.hide() #Backbone for chain in structure.get_chains(): carr = np.random.rand(3, 1) ccolor = float(carr[0]), float(carr[1]), float(carr[2]), 1.0 can_atoms = [ atom for atom in chain.get_atoms() if atom.get_name() == 'CA' or atom.get_name() == 'N' ] can_coordinates = [atom.coord for atom in can_atoms] for atom in can_atoms: x, y, z = atom.coord atomid = atom.get_id() a = loader.loadModel("data/atom_sphere") a.setPos(x, y, z) a.reparentTo(self.bbnode) a.setColor(ccolor) a.setScale(vrad(atomid) / 2.5) lines = LineSegs() lines.setColor(ccolor) lines.moveTo(can_coordinates[0][0], can_coordinates[0][1], can_coordinates[0][2]) for i in range(len(can_atoms))[1:]: lines.drawTo(can_coordinates[i][0], can_coordinates[i][1], can_coordinates[i][2]) lines.setThickness(6) lnode = lines.create() self.linenp = NodePath(lnode) self.linenp.instanceTo(self.bbnode) #Cloud catoms = [atom for atom in chain.get_atoms()] for atom in catoms: x, y, z = atom.coord atomid = atom.get_id() a = loader.loadModel("data/atom_sphere") a.setPos(x, y, z) a.reparentTo(self.nnode) a.setColor(ccolor) a.setScale(vrad(atomid) * 1.1) self.bbnode.flattenStrong() self.bbnode.hide() self.nnode.setTransparency(TransparencyAttrib.MAlpha) self.nnode.setAlphaScale(0.3) self.nnode.hide() #DSSP self.linenp.instanceTo(self.dsspnode) self.struct3 = [dssp[key][2] for key in list(dssp.keys())] for i in range(len(self.struct3)): dsspcolor = crgbaDSSP(self.struct3[i]) can_atoms = [ atom for atom in self.residues[i] if atom.get_name() == 'CA' or atom.get_name() == 'N' ] for atom in can_atoms: x, y, z = atom.coord atomid = atom.get_id() a = loader.loadModel("data/atom_sphere") a.setPos(x, y, z) a.reparentTo(self.dsspnode) a.setColor(dsspcolor) a.setScale(vrad(atomid) / 2.5) self.dsspnode.flattenStrong() self.dsspnode.hide() #Colocamos la proteina en el centro self.cpknode.setPos(0, 0, 0) self.bbnode.setPos(0, 0, 0) self.aanode.setPos(0, 0, 0) self.nnode.setPos(0, 0, 0) #Colocamos la camara en el centro xc, yc, zc = self.cpknode.getBounds().getCenter() self.center = xc, yc, zc self.pradius = self.cpknode.getBounds().getRadius() self.center_camera() #Creamos la iluminacion de ambiente self.ambient = AmbientLight('alight') self.ambient.setColor(LVecBase4f(0.16, 0.16, 0.17, 1.0)) self.alight = render.attachNewNode(self.ambient) render.setLight(self.alight) #Creamos la iluminacion direccional self.directional = DirectionalLight('dlight') self.directional.setColor(LVecBase4f(0.8, 0.7, 0.75, 1.0)) self.directional.setShadowCaster(True, 512, 512) render.setShaderAuto() self.dlight = render.attachNewNode(self.directional) self.dlight.setPos(0, -50, 0) render.setLight(self.dlight) self.dlight.lookAt(self.cpknode.getBounds().getCenter()) # Post procesado render.setAntialias(AntialiasAttrib.MAuto) #Teclado self.accept('c', self.toggle_cloud) self.accept('1', self.showmodel, [self.cpknode]) self.accept('2', self.showmodel, [self.aanode]) self.accept('3', self.showmodel, [self.bbnode]) self.accept('4', self.showmodel, [self.dsspnode]) self.accept('x', self.center_camera) self.accept('arrow_left', self.taskMgr.add, [self.spinCameraTaskX, "SpinCameraTaskX"]) self.accept('arrow_up', self.taskMgr.add, [self.spinCameraTaskY, "SpinCameraTaskY"]) self.accept('arrow_down', self.stop_camera) self.accept('escape', sys.exit)
def __init__(self): __builtin__.main = self self.cManager = ConnectionManager() self.startConnection() self.taskMgr = taskMgr self.base = base self.keyMap = { "left": 0, "right": 0, "forward": 0, "backward": 0, "cam-left": 0, "cam-right": 0 } self.characters = dict() self.cpList = dict() base.win.setClearColor(Vec4(0, 0, 0, 1)) #self.environ = loader.loadModel("models/world") self.environ = loader.loadModel("models/land") """ self.swordLeft = loader.loadModel("models/Sword_Left") self.swordRight = loader.loadModel("models/Sword_Right") self.shieldLeft = loader.loadModel("models/Shield_Left") self.shieldRight = loader.loadModel("models/Shield_Right") self.money = loader.loadModel("models/Money") """ self.left_atk_tower = loader.loadModel("models/attack_tower") self.left_def_tower = loader.loadModel("models/defense_tower") self.right_atk_tower = loader.loadModel("models/attack_tower") self.right_def_tower = loader.loadModel("models/defense_tower") self.money_cp = loader.loadModel("models/money_point") self.left_atk_tower.setPos(141.016, 0.440607, 0) self.left_def_tower.setPos(210.984, 115.005, 0) self.right_atk_tower.setPos(-149.953, 0.674369, 0) self.right_def_tower.setPos(-210.771, 113.753, 0) self.money_cp.setPos(-0.903916, 11.3765, 0) self.left_atk_tower.setScale(2.0) self.right_atk_tower.setScale(2.0) self.left_def_tower.setScale(2.0) self.right_def_tower.setScale(2.0) self.money_cp.setScale(2.0) self.left_atk_tower.reparentTo(render) self.right_atk_tower.reparentTo(render) self.left_def_tower.reparentTo(render) self.right_def_tower.reparentTo(render) self.money_cp.reparentTo(render) self.environ.reparentTo(render) """ self.swordLeft.reparentTo(render) self.swordRight.reparentTo(render) self.shieldLeft.reparentTo(render) self.shieldRight.reparentTo(render) self.money.reparentTo(render) """ self.environ.setPos(0, 0, 0) self.environ.setH(90) """ self.swordLeft.setH(90) self.swordRight.setH(90) self.shieldLeft.setH(90) self.shieldRight.setH(90) self.money.setH(90) """ mySound = loader.loadSfx("sound/Retribution.mp3") mySound.setLoop(True) mySound.play() fp = FilterProperties() #fp.addReverb(0.6, 0.5, 0.1, 0.1, 0.1) base.sfxManagerList[0].configureFilters(fp) ## swordsmanStartPos = self.environ.find("**/start_point").getPos() ## self.player = Swordsman("Swordsman", 0) ## self.player._character.reparentTo(render) ## self.player._character.setScale(.1) ## self.player._character.setPos(swordsmanStartPos) ## swordsmanStartPos.setY(swordsmanStartPos.getY()-10) ## self.player._character.setPos(swordsmanStartPos.getX(),swordsmanStartPos.getY(),swordsmanStartPos.getZ()) ## self.initx = swordsmanStartPos.getX() self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) ## self.characters["Axeman"] = Axeman("Axeman", 1) ## self.characters["Axeman"]._character.reparentTo(render) ## self.characters["Axeman"]._character.setScale(.1) ## self.characters["Axeman"]._character.setPos(swordsmanStartPos) ## swordsmanStartPos.setY(swordsmanStartPos.getY()-10) ## self.characters["Axeman"]._character.setPos(swordsmanStartPos.getX(),swordsmanStartPos.getY() - 10,swordsmanStartPos.getZ()) ## self.characters["Axeman"]._character.loop("idle") self.accept("a", self.setKey, ["left", 1]) self.accept("s", self.setKey, ["backward", 1]) self.accept("w", self.setKey, ["forward", 1]) self.accept("d", self.setKey, ["right", 1]) self.accept("a-up", self.setKey, ["left", 0]) self.accept("s-up", self.setKey, ["backward", 0]) self.accept("w-up", self.setKey, ["forward", 0]) self.accept("d-up", self.setKey, ["right", 0]) self.accept("arrow_left", self.setKey, ["cam-left", 1]) self.accept("arrow_right", self.setKey, ["cam-right", 1]) self.accept("arrow_left-up", self.setKey, ["cam-left", 0]) self.accept("arrow_right-up", self.setKey, ["cam-right", 0]) self.accept("mouse1", self.attack, [3]) self.accept("mouse3", self.attack, [4]) self.username = str(raw_input("Username: "******"Type: ") faction = input("Faction: ") self.cManager.sendRequest(Constants.CMSG_AUTH, [self.username, type, faction]) #taskMgr.add(self.move,"moveTask") taskMgr.doMethodLater(.10, self.refresh, "heartbeat") base.disableMouse() #base.camera.setPos(self.player._character.getX(),self.player._character.getY()+10,2) ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) directionalLight2 = DirectionalLight("directionalLight2") directionalLight2.setDirection(Vec3(5, 5, 5)) directionalLight2.setColor(Vec4(1, 1, 1, 1)) directionalLight2.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight)) render.setLight(render.attachNewNode(directionalLight2)) Chat(self.cManager) # Create control points self.cpList[1] = ControlPoint(1, 210.984, 115.005, -5, 10, RED) self.cpList[2] = ControlPoint(2, 141.016, 0.440607, -5, 10, RED) self.cpList[3] = ControlPoint(3, -0.903916, 11.3765, -2, 10, RED) self.cpList[4] = ControlPoint(4, -210.771, 113.753, -2, 10, BLUE) self.cpList[5] = ControlPoint(5, -149.953, 0.674369, -2, 10, BLUE) # Create the control point Bar UI self.cp_bar = ControlPointBar() # self.resource_bar = ResourceBar() taskMgr.doMethodLater(0.1, self.refresh, "heartbeat") taskMgr.doMethodLater(1, self.CPHandler, "CPHandler") taskMgr.doMethodLater(0.1, self.CPBarHandler, 'CPBarHandler') '''NPC Code Additions''' #self.isChased =[False,False] #self.npcList = [0,0] self.isChased = False self.npcList = 0 self.controlNpc = NPCController(render) taskMgr.add(self.taskAIUpdate, "AIUpdate") taskMgr.add(self.moveNpc, "Move")
def __init__(self): self.keyMap = {"left":0, "right":0, "forward":0, "cam-left":0, "cam-right":0} self.cManager = QueuedConnectionManager() self.cListener = QueuedConnectionListener(self.cManager, 0) self.cReader = QueuedConnectionReader(self.cManager, 0) self.cWriter = ConnectionWriter(self.cManager, 0) self.opponents = dict() self.logStat = -1 self.id = 0 self.username = "" host = "localhost" port = 9252 self.connection = self.cManager.openTCPClientConnection(host, port, 10000) self.received = 1 self.playersText = [] if self.connection: self.cReader.addConnection(self.connection) taskMgr.add(self.updateRoutine, 'updateRoutine') taskMgr.add(self.login, 'login') taskMgr.doMethodLater(.1, self.heartbeat, 'heartbeat') # Replace with actual, dynamic list of players from the server self.players = dict() # Placeholder, replace with actual # of players later self.numberOfPlayers = 2 # Stores the OnScreenText for each player in the players list # Populated and depopulated using listPlayers and delistPlayers self.playersText = [] # Stores all the player objects currently logged in self.playerObjects = [] base.win.setClearColor(Vec4(0,0,0,1)) # Post the instructions #self.title = addTitle("Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)") #self.inst1 = addInstructions(0.95, "[ESC]: Quit") #self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left") #self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right") #self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward") #self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left") #self.inst7 = addInstructions(0.65, "[S]: Rotate Camera Right") #self.inst8 = addInstructions(0.60, "[Q]: Display List Of Connected Players") # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) self.environ.setPos(0,0,0) # Create the main character, Ralph ralphStartPos = self.environ.find("**/start_point").getPos() self.ralph = Actor("models/ralph", {"run":"models/ralph-run", "walk":"models/ralph-walk"}) self.ralph.reparentTo(render) self.ralph.setScale(.2) self.ralph.setPos(ralphStartPos) ralphStartPos.setY(ralphStartPos.getY()-10) self.ralph.setPos(ralphStartPos.getX(),ralphStartPos.getY(),ralphStartPos.getZ()) self.initx = ralphStartPos.getX() # Add our Ralph to list to Ralphs self.playerObjects.append(self.ralph) # Load and transform the panda actor. self.pandaActor = Actor("models/panda-model", {"walk": "models/panda-walk4"}) self.pandaActor.setScale(0.003, 0.003, 0.003) self.pandaActor.reparentTo(render) # Loop its animation. #self.pandaActor.loop("walk") self.pandaActor.setPos(ralphStartPos.getX(),ralphStartPos.getY()-20,ralphStartPos.getZ()) # Create a floater object. We use the "floater" as a temporary # variable in a variety of calculations. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # Accept the control keys for movement and rotation self.accept("escape", self.disconnect) self.accept("arrow_left", self.setKey, ["left",1]) self.accept("arrow_right", self.setKey, ["right",1]) self.accept("arrow_up", self.setKey, ["forward",1]) self.accept("a", self.setKey, ["cam-left",1]) self.accept("s", self.setKey, ["cam-right",1]) self.accept("arrow_left-up", self.setKey, ["left",0]) self.accept("arrow_right-up", self.setKey, ["right",0]) self.accept("arrow_up-up", self.setKey, ["forward",0]) self.accept("a-up", self.setKey, ["cam-left",0]) self.accept("s-up", self.setKey, ["cam-right",0]) self.accept("q", self.listPlayers) self.accept("q-up", self.delistPlayers) taskMgr.add(self.move,"moveTask") # Call whenever a ralph has logged in, use arg "out" for logouts self.displayLoginText() # Game state variables self.isMoving = False # Set up the camera base.disableMouse() base.camera.setPos(self.ralph.getX(),self.ralph.getY()+10,2) # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above ralph's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. self.cTrav = CollisionTraverser() self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0,0,1000) self.ralphGroundRay.setDirection(0,0,-1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0)) self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff()) self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler) self.pandaActorGroundRay = CollisionRay() self.pandaActorGroundRay.setOrigin(0,0,1000) self.pandaActorGroundRay.setDirection(0,0,-1) self.pandaActorGroundCol = CollisionNode('pandaActorRay') self.pandaActorGroundCol.addSolid(self.pandaActorGroundRay) self.pandaActorGroundCol.setFromCollideMask(BitMask32.bit(0)) self.pandaActorGroundCol.setIntoCollideMask(BitMask32.allOff()) self.pandaActorGroundColNp = self.pandaActor.attachNewNode(self.pandaActorGroundCol) self.pandaActorGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.pandaActorGroundColNp, self.pandaActorGroundHandler) self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0,0,1000) self.camGroundRay.setDirection(0,0,-1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(BitMask32.bit(0)) self.camGroundCol.setIntoCollideMask(BitMask32.allOff()) self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Uncomment this line to see the collision rays #self.ralphGroundColNp.show() #self.camGroundColNp.show() self.miniMap = miniMap(self.ralph) self.miniMap.setNpc('tower_1', 'models/hexahedron.png', 0.05, 0.2, 0.3) self.miniMap.setNpc('tower_2', 'models/hexahedron.png', 0.05, -0.4, -0.5) # Uncomment this line to show a visual representation of the # collisions occuring #self.cTrav.showCollisions(render) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight)) self.setAI()
def __init__(self): self.keyMap = {"left": 0, "right": 0, "forward": 0, "backward": 0} base.win.setClearColor(Vec4(0, 0, 0, 1)) # number of collectibles self.numObjects = 10 # print the number of objects printNumObj(self.numObjects) # Post the instructions self.title = addTitle("Roaming Ralph (Edited by Adam Gressen)") self.inst1 = addInstructions(0.95, "[ESC]: Quit") self.inst2 = addInstructions(0.90, "[A]: Rotate Ralph Left") self.inst3 = addInstructions(0.85, "[D]: Rotate Ralph Right") self.inst4 = addInstructions(0.80, "[W]: Run Ralph Forward") self.inst5 = addInstructions(0.75, "[S]: Run Ralph Backward") self.inst6 = addInstructions(0.70, "[Space]: Run, Ralph, Run") # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) self.environ.setPos(0, 0, 0) # Timer to increment in the move task self.time = 0 # Get bounds of environment min, max = self.environ.getTightBounds() self.mapSize = max - min # Create the main character, Ralph self.ralphStartPos = self.environ.find("**/start_point").getPos() self.ralph = Actor("models/ralph", { "run": "models/ralph-run", "walk": "models/ralph-walk" }) self.ralph.reparentTo(render) self.ralph.setScale(.2) self.ralph.setPos(self.ralphStartPos) # ralph's health self.health = 100 # ralph's stamina self.stamina = 100 # Create a floater object. We use the "floater" as a temporary # variable in a variety of calculations. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) # these don't work well in combination with the space bar self.accept("arrow_left", self.setKey, ["left", 1]) self.accept("arrow_right", self.setKey, ["right", 1]) self.accept("arrow_up", self.setKey, ["forward", 1]) self.accept("arrow_down", self.setKey, ["backward", 1]) self.accept("arrow_left-up", self.setKey, ["left", 0]) self.accept("arrow_right-up", self.setKey, ["right", 0]) self.accept("arrow_up-up", self.setKey, ["forward", 0]) self.accept("arrow_down-up", self.setKey, ["backward", 0]) self.accept("space", self.runRalph, [True]) self.accept("space-up", self.runRalph, [False]) self.accept("a", self.setKey, ["left", 1]) self.accept("d", self.setKey, ["right", 1]) self.accept("w", self.setKey, ["forward", 1]) self.accept("s", self.setKey, ["backward", 1]) self.accept("a-up", self.setKey, ["left", 0]) self.accept("d-up", self.setKey, ["right", 0]) self.accept("w-up", self.setKey, ["forward", 0]) self.accept("s-up", self.setKey, ["backward", 0]) # Game state variables self.isMoving = False self.isRunning = False # Set up the camera base.disableMouse() #base.camera.setPos(self.ralph.getX(),self.ralph.getY()+10,2) base.camera.setPos(0, 0, 0) base.camera.reparentTo(self.ralph) base.camera.setPos(0, 40, 2) base.camera.lookAt(self.ralph) # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above ralph's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. base.cTrav = CollisionTraverser() self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0, 0, 300) self.ralphGroundRay.setDirection(0, 0, -1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0)) self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff()) self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() base.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler) # camera ground collision handler self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 300) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(BitMask32.bit(0)) self.camGroundCol.setIntoCollideMask(BitMask32.allOff()) self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() base.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Place the health items self.placeHealthItems() # Place the collectibles self.placeCollectibles() # Uncomment this line to show a visual representation of the # collisions occuring #base.cTrav.showCollisions(render) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight)) taskMgr.add(self.move, "moveTask") taskMgr.doMethodLater(0.5, self.healthDec, "healthTask")
def __init__(self, name="directional light", color=Vec4(1,1,1,1)): AssetBase.__init__(self) self.light = DL("directional light") self.light.setColor(color) self.node = NodePath(self.light)
def __init__(self): # Set up the window, camera, etc. ShowBase.__init__(self) # This is used to store which keys are currently pressed. self.keyMap = { "left": 0, "right": 0, "forward": 0, "backward": 0, "cam-left": 0, "cam-right": 0, } # Post the instructions self.title = addTitle( "Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)") self.inst1 = addInstructions(0.06, "[ESC]: Quit") self.inst2 = addInstructions(0.12, "[Left Arrow]: Rotate Ralph Left") self.inst3 = addInstructions(0.18, "[Right Arrow]: Rotate Ralph Right") self.inst4 = addInstructions(0.24, "[Up Arrow]: Run Ralph Forward") self.inst5 = addInstructions(0.30, "[Down Arrow]: Walk Ralph Backward") self.inst6 = addInstructions(0.36, "[A]: Rotate Camera Left") self.inst7 = addInstructions(0.42, "[S]: Rotate Camera Right") # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel( "/usr/share/panda3d/samples/roaming-ralph/models/world") self.environ.reparentTo(render) # We do not have a skybox, so we will just use a sky blue background color self.setBackgroundColor(0.53, 0.80, 0.92, 1) # Create the main character, Ralph ralphStartPos = self.environ.find("**/start_point").getPos() self.ralph = Actor( "/usr/share/panda3d/samples/roaming-ralph/models/ralph", { "run": "/usr/share/panda3d/samples/roaming-ralph/models/ralph-run", "walk": "/usr/share/panda3d/samples/roaming-ralph/models/ralph-walk" }) self.ralph.reparentTo(render) self.ralph.setScale(.2) self.ralph.setPos(ralphStartPos + (0, 0, 1.5)) # Create a floater object, which floats 2 units above ralph. We # use this as a target for the camera to look at. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(self.ralph) self.floater.setZ(2.0) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", True]) self.accept("arrow_right", self.setKey, ["right", True]) self.accept("arrow_up", self.setKey, ["forward", True]) self.accept("arrow_down", self.setKey, ["backward", True]) self.accept("a", self.setKey, ["cam-left", True]) self.accept("s", self.setKey, ["cam-right", True]) self.accept("arrow_leght-up", self.setKey, ["right", False]) self.accept("arrow_up-ft-up", self.setKey, ["left", False]) self.accept("arrow_riup", self.setKey, ["forward", False]) self.accept("arrow_down-up", self.setKey, ["backward", False]) self.accept("a-up", self.setKey, ["cam-left", False]) self.accept("s-up", self.setKey, ["cam-right", False]) taskMgr.add(self.move, "moveTask") # Set up the camera self.disableMouse() self.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2) self.cTrav = CollisionTraverser() # Use a CollisionHandlerPusher to handle collisions between Ralph and # the environment. Ralph is added as a "from" object which will be # "pushed" out of the environment if he walks into obstacles. # # Ralph is composed of two spheres, one around the torso and one # around the head. They are slightly oversized since we want Ralph to # keep some distance from obstacles. self.ralphCol = CollisionNode('ralph') self.ralphCol.addSolid(CollisionSphere(center=(0, 0, 2), radius=1.5)) self.ralphCol.addSolid( CollisionSphere(center=(0, -0.25, 4), radius=1.5)) self.ralphCol.setFromCollideMask(CollideMask.bit(0)) self.ralphCol.setIntoCollideMask(CollideMask.allOff()) self.ralphColNp = self.ralph.attachNewNode(self.ralphCol) self.ralphPusher = CollisionHandlerPusher() self.ralphPusher.horizontal = True # Note that we need to add ralph both to the pusher and to the # traverser; the pusher needs to know which node to push back when a # collision occurs! self.ralphPusher.addCollider(self.ralphColNp, self.ralph) self.cTrav.addCollider(self.ralphColNp, self.ralphPusher) # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above ralph's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0, 0, 9) self.ralphGroundRay.setDirection(0, 0, -1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(CollideMask.bit(0)) self.ralphGroundCol.setIntoCollideMask(CollideMask.allOff()) self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler) self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 9) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(CollideMask.bit(0)) self.camGroundCol.setIntoCollideMask(CollideMask.allOff()) self.camGroundColNp = self.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Uncomment this line to see the collision rays #self.ralphColNp.show() #self.camGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring #self.cTrav.showCollisions(render) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection((-5, -5, -5)) directionalLight.setColor((1, 1, 1, 1)) directionalLight.setSpecularColor((1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))
def __init__(self): # Setup logger import __builtin__ __builtin__.LOG = LogConsole() # Initialize event dispatcher self._dispatcher = Event.Dispatcher() # Setup controls self.keyboardcontroller = Controller.KeyboardController() self.mousecontroller = Controller.MouseController() # Build game board __builtin__.boardNP = NodePath("Game Board Parent") boardNP.reparentTo(render) self.gamePieces = [] self.gameMgr = GameManager() guiMgr = GuiManager() ######################################################################## w = Water(boardNP) self.gameMgr.addPlayer(1, "Player 1") self.gameMgr.addPlayer(2, "Player 2") s1 = BattleShip(parent=render, pos=Vec3(50, 0, 0)) s2 = BattleShip(parent=render, pos=Vec3(-30, 10, 0)) self.gameMgr.addPlayerUnit(1, s1) self.gameMgr.addPlayerUnit(2, s2) # move this to dispatcher s1.setGame(self) s2.setGame(self) # move this to dispatcher s1.startTurn() self.gamePieces = [s1, s2] ######################################################################## # Camera c = CameraManager() c.startCamera() c.setTarget(s1) ####LIGHTS######################################################### dlight = DirectionalLight('dlight') alight = AmbientLight('alight') dlnp = render.attachNewNode(dlight) alnp = render.attachNewNode(alight) dlight.setColor(Vec4(0.5, 0.5, 0.7, 1)) alight.setColor(Vec4(0.7, 0.7, 0.7, 1)) dlnp.setHpr(0, -60, 0) render.setLight(dlnp) render.setLight(alnp) # Glow test #glowShader=loader.loadShader("shaders/glowShader.sha") # ## create the glow buffer. This buffer renders like a normal scene, ## except that only the glowing materials should show up nonblack. #glowBuffer=base.win.makeTextureBuffer("Glow scene", 512, 512) #glowBuffer.setSort(-3) #glowBuffer.setClearColor(Vec4(0,0,0,1)) # ## We have to attach a camera to the glow buffer. The glow camera ## must have the same frustum as the main camera. As long as the aspect ## ratios match, the rest will take care of itself. #glowCamera=base.makeCamera(glowBuffer, lens=base.cam.node().getLens()) # ## Tell the glow camera to use the glow shader #tempnode = NodePath(PandaNode("temp node")) #tempnode.setShader(glowShader) #glowCamera.node().setInitialState(tempnode.getState()) # ## set up the pipeline: from glow scene to blur x to blur y to main window. #blurXBuffer=self.makeFilterBuffer(glowBuffer, "Blur X", -2, "shaders/XBlurShader.sha") #blurYBuffer=self.makeFilterBuffer(blurXBuffer, "Blur Y", -1, "shaders/YBlurShader.sha") #self.finalcard = blurYBuffer.getTextureCard() #self.finalcard.reparentTo(render2d) #self.finalcard.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd)) # #base.bufferViewer.setPosition("llcorner") #base.bufferViewer.setLayout("hline") #base.bufferViewer.setCardSize(0.652,0) #base.bufferViewer.toggleEnable # Toon test #self.separation = 0.5 ## This shader's job is to render the model with discrete lighting ## levels. The lighting calculations built into the shader assume ## a single nonattenuating point light. # #tempnode = NodePath(PandaNode("temp node")) #tempnode.setShader(loader.loadShader("shaders/lightingGen.sha")) #base.cam.node().setInitialState(tempnode.getState()) # ## This is the object that represents the single "light", as far ## the shader is concerned. It's not a real Panda3D LightNode, but ## the shader doesn't care about that. # #light = render.attachNewNode("light") #light.setPos(30,-50,0) # ## this call puts the light's nodepath into the render state. ## this enables the shader to access this light by name. # #render.setShaderInput("light", light) # ## The "normals buffer" will contain a picture of the model colorized ## so that the color of the model is a representation of the model's ## normal at that point. # #normalsBuffer=base.win.makeTextureBuffer("normalsBuffer", 0, 0) #normalsBuffer.setClearColor(Vec4(0.5,0.5,0.5,1)) #self.normalsBuffer=normalsBuffer #normalsCamera=base.makeCamera(normalsBuffer, lens=base.cam.node().getLens()) #normalsCamera.node().setScene(render) #tempnode = NodePath(PandaNode("temp node")) #tempnode.setShader(loader.loadShader("shaders/normalGen.sha")) #normalsCamera.node().setInitialState(tempnode.getState()) # ##what we actually do to put edges on screen is apply them as a texture to ##a transparent screen-fitted card # #drawnScene=normalsBuffer.getTextureCard() #drawnScene.setTransparency(1) #drawnScene.setColor(1,1,1,0) #drawnScene.reparentTo(render2d) #self.drawnScene = drawnScene # ## this shader accepts, as input, the picture from the normals buffer. ## it compares each adjacent pixel, looking for discontinuities. ## wherever a discontinuity exists, it emits black ink. # #self.separation = 0.001 #self.cutoff = 0.3 #inkGen = loader.loadShader("shaders/inkGen.sha") #drawnScene.setShader(inkGen) #drawnScene.setShaderInput("separation", Vec4(self.separation,0,self.separation,0)); #drawnScene.setShaderInput("cutoff", Vec4(self.cutoff,self.cutoff,self.cutoff,self.cutoff)); ### GO GO GO ##################################### self.gameMgr.startGame()
def __init__(self): ShowBase.__init__(self) props = WindowProperties() props.setTitle('Differentiable Physics Engine') self.win.requestProperties(props) self.t = 0 self.starttime = time.time() #self.setFrameRateMeter(True) cour = self.loader.loadFont('cmtt12.egg') self.textObject = None #OnscreenText(font= cour, text = 'abcdefghijklmnopqrstuvwxyz', pos=(0, -0.045), parent = self.a2dTopCenter, bg=(0,0,0,0.5), fg =(1,1,1,1), scale = 0.07, mayChange=True) cm = CardMaker("ground") cm.setFrame(-2000, 2000, -2000, 2000) cm.setUvRange(Point2(-2000 / 5, -2000 / 5), Point2(2000 / 5, 2000 / 5)) tmp = self.render.attachNewNode(cm.generate()) tmp.reparentTo(self.render) self.camLens.setNear(0.1) tmp.setPos(0, 0, 0) tmp.lookAt((0, 0, -2)) tmp.setColor(1.0, 1.0, 1.0, 0.) tmp.setTexScale(TextureStage.getDefault(), 1, 1) tex = self.loader.loadTexture('textures/grid2.png') tex.setWrapU(Texture.WMRepeat) tex.setWrapV(Texture.WMRepeat) tmp.setTexture(tex, 1) self.setBackgroundColor(0.0, 191.0 / 255.0, 1.0, 1.0) #color of the sky ambientLight = AmbientLight('ambientLight') ambientLight.setColor(Vec4(0.2, 0.2, 0.2, 1)) ambientLightNP = self.render.attachNewNode(ambientLight) self.render.setLight(ambientLightNP) # Directional light 01 directionalLight = DirectionalLight('directionalLight') directionalLight.setColor(Vec4(0.8, 0.8, 0.8, 1)) directionalLightNP = self.render.attachNewNode(directionalLight) # This light is facing backwards, towards the camera. directionalLightNP.setHpr(-120, -50, 0) directionalLightNP.node().setScene(self.render) directionalLightNP.node().setShadowCaster(True) directionalLightNP.node().getLens().setFov(40) directionalLightNP.node().getLens().setNearFar(10, 100) self.render.setLight(directionalLightNP) # Add the spinCameraTask procedure to the task manager. self.taskMgr.add(self.spinCameraTask, "SpinCameraTask") self.physics = Rigid3DBodyEngine() # Load the environment model. self.objects = dict() #self.load_robot_model("robotmodel/test.json") #self.load_robot_model("robotmodel/predator.json") #self.load_robot_model("robotmodel/full_predator.json") #self.load_robot_model("robotmodel/demi_predator.json") #self.load_robot_model("robotmodel/ball.json") self.load_robot_model("robotmodel/robot_arm.json") #self.load_robot_model("robotmodel/robot_arm_mini.json") self.physics.compile() self.step = np.zeros(shape=(16, ))
def __init__(self): ShowBase.__init__(self) # Allows importing components from project folder sys.path.append(".") # Initial scene setup self.disableMouse() self.setBackgroundColor(0.15, 0.15, 0.15, 1) EComponent.panda_root_node = self.render.attach_new_node(PandaNode("Root")) EComponent.base = self # Attach a directional light to the camera self.dir_light = DirectionalLight("cam_dir_light") dir_light_path = self.camera.attach_new_node(self.dir_light) EComponent.panda_root_node.setLight(dir_light_path) # Set up scene data self.envedit_data = EnveditData() self.envedit_data.update_callback = self.update_gui self.envedit_data.scene_root = GraphNode("Scene Root", []) self.envedit_data.panda_root_node = EComponent.panda_root_node # Read the project config file config_path = Path("project.yaml") config = None if not config_path.exists(): sys.stderr.write("Error: Could not find project.yaml.") return with open("project.yaml", "r") as file: config = yaml.load(file, Loader=yaml.FullLoader) self.envedit_data.project_name = config["project"] # Set up GUI system self.gui_system = GUISystem(self) GUIFontLoader.base = self GUISystem.fonts["default"] = GUIFontLoader.load_font("open-sans/OpenSans-Regular.ttf") GUISystem.fonts["default_bold"] = GUIFontLoader.load_font("open-sans/OpenSans-Bold.ttf") GUISystem.fonts["default_light"] = GUIFontLoader.load_font("open-sans/OpenSans-Light.ttf") window_layout = GUIDockLayout() self.gui_system.window.set_child(window_layout) # Set up Tkinter (for file dialogs) root = tk.Tk() root.withdraw() # Set up gizmo system self.gizmo_system = GizmoSystem(self, self.envedit_data) # Add floor self.floor_node = FloorNode(self) floor_path = self.render.attach_new_node(self.floor_node) floor_path.setTwoSided(True) floor_path.set_shader_input("object_id", 0) # Add camera controller self.cam_controller = CameraController(self, self.render, self.camera) # Add graph viewer self.graph_viewer = GraphViewer() window_layout.set_child_dock(self.graph_viewer, GUIDockLayout.LEFT) self.graph_viewer.set_envedit_data(self.envedit_data) # Add component viewer self.component_viewer = ComponentViewer() window_layout.set_child_dock(self.component_viewer, GUIDockLayout.RIGHT) self.component_viewer.set_envedit_data(self.envedit_data) self.component_viewer.set_components(config["components"]) component_reloader = ComponentReloader(self.component_viewer) # Add toolbar self.toolbar = Toolbar() window_layout.set_child_dock(self.toolbar, GUIDockLayout.TOP) self.toolbar.set_envedit_data(self.envedit_data) # Add empty center panel self.center_panel = CenterPanel(self.cam_controller) window_layout.set_child_dock(self.center_panel, GUIDockLayout.CENTER) # Add task to update nodes self.add_task(self.update_nodes) # Set up event handlers for key combinations self.accept("control-n", self.handle_new) self.accept("control-o", self.handle_open) self.accept("control-s", self.handle_save) self.update_gui()
def __init__(self): base.setBackgroundColor(0.1, 0.1, 0.8, 1) base.setFrameRateMeter(True) # road geometry generation #road=trail(100,50,40,0.2) # generating a circular lane track self.precision = 0.5 # length of a piece of centerLine road = basicFreeWay(200, 50, 1, self.precision, 2) # generating a piece of freeway #road=straightCenter(np.array([0,0]),math.pi/2,300,2) self.segLine = road.getLine() # the centerLine self.road = roadGenerator(np.array([0, -1]), 4, 2, road.getFollowing(), self.segLine, -1) # generate road polygon node = self.road.getNode() # road texture floorTex = loader.loadTexture('maps/street3.jpg') floor = render.attachNewNode(node) floor.setTexture(floorTex) floor.flattenStrong() # grass background generation floorTex1 = loader.loadTexture('maps/envir-ground.jpg') cm1 = CardMaker('') cm1.setFrame(-2, 2, -2, 2) floor1 = render.attachNewNode(PandaNode("floor1")) for y in range(100): for x in range(30): nn1 = floor1.attachNewNode(cm1.generate()) nn1.setP(-90) nn1.setPos((x - 20) * 4, (y - 20) * 4, -1.1) floor1.setTexture(floorTex1) floor1.flattenStrong() # initial camera base.cam.setPos(0, -20, 4) base.cam.lookAt(0, 0, 0) # Light alight = AmbientLight('ambientLight') alight.setColor(Vec4(0.5, 0.5, 0.5, 1)) alightNP = render.attachNewNode(alight) dlight = DirectionalLight('directionalLight') dlight.setDirection(Vec3(1, 1, -1)) dlight.setColor(Vec4(0.7, 0.7, 0.7, 1)) dlightNP = render.attachNewNode(dlight) render.clearLight() render.setLight(alightNP) render.setLight(dlightNP) # Input setup self.accept('escape', self.doExit) self.accept('r', self.doReset) self.accept('f1', self.toggleWireframe) self.accept('f2', self.toggleTexture) self.accept('f3', self.toggleDebug) self.accept('f5', self.doScreenshot) inputState.watchWithModifiers('forward', 'w') inputState.watchWithModifiers('reverse', 's') inputState.watchWithModifiers('turnLeft', 'a') inputState.watchWithModifiers('turnRight', 'd') inputState.watchWithModifiers('brake1', 'x') inputState.watchWithModifiers('For', 'i') inputState.watchWithModifiers('Back', 'k') inputState.watchWithModifiers('Lef', 'j') inputState.watchWithModifiers('Righ', 'l') inputState.watchWithModifiers('brake2', 'space') # Task manager taskMgr.add(self.update, 'updateWorld') # Physics self.setup()
class main(ShowBase): def __init__(self): ShowBase.__init__(self) self.SPHERE_SIZE = 5 self.radius = self.SPHERE_SIZE / 1.5 # This is the extra distance between the spheres not immediately adjacent. # extra_distance specifies how much crowding is allowed. self.extra_distance = int(round(1.8 * self.radius)) self.DIST_BTW = 35 self.v1 = [1] self.v3 = [True] self.v4 = [1] self.params = [self.SPHERE_SIZE, 1, self.DIST_BTW, True, 1] """ Output: params[0] - sphere size params[1] - One point = 1, Two points = 2, Cerebellum simulation = 3 params[2] - how far apart two points will be if you choose two (2 for params[1]) params[3] - How many points for the cerebellar simulation, 4 = True, 5 = False params[4] - What color scheme. Gray = 1, random = 2, RGBY(W) = 3 """ # possible_vectors is calculated in self.calculate() possible_vectors = [] self.possible_vectors = possible_vectors # List of all the spheres. sphere_list = [] self.sphere_list = sphere_list # Lists of spheres that can actually grow. self.outside_sphere_list0 = [] self.outside_sphere_list1 = [] self.outside_sphere_list2 = [] self.outside_sphere_list3 = [] self.outside_sphere_list4 = [] # Counters for the lists that can grow. self.counter_list0 = [] self.counter_list1 = [] self.counter_list2 = [] self.counter_list3 = [] self.counter_list4 = [] # Set background color to white. base.setBackgroundColor(1, 1, 1) # Set ambient and directional light on the sphere. self.ambientLight = AmbientLight("ambientLight") self.ambientLight.setColor((0.3, 0.4, 0.5, 1)) self.directionalLight = DirectionalLight("directionalLight") # Angles the light just a little. self.directionalLight.setDirection(LVector3(0, 5, -5)) self.directionalLight.setColor((0.9, 0.9, 0.9, 1)) # Have to disable mouse to enable camera position. self.disableMouse() self.camera.setPos(0, -300, 0) # Sets the camera back. # Stock code from the Panda3D manual that reactivates the mouse standard. # Left click moves in the x and z planes, right click in the y plane. # Both together rotates around (0, 0, 0). mat = Mat4(camera.getMat()) mat.invertInPlace() base.mouseInterfaceNode.setMat(mat) base.enableMouse() # Call input_variables, DirectGui start screen. # It allows a user to adjust a few features of the Brownian tree(s) # and color. At present, the sphere size can be changed, but it # quickly runs into limited size due to limiting factors in the # self.add_sphere() function. It can't be too crowded around a sphere # or else you can't see anything between the rendered spheres. self.input_variables() def input_variables(self): # Calls to the text and button widgets. # Q0 sphere size. button0_text = OnscreenText(text="Sphere Size", scale=0.1, pos=(0, 0.9), align=TextNode.ACenter) button0 = DirectEntry(text="", command=self.item0, initialText="5", scale=0.1, width=10, numLines=1, pos=(-0.4, 0, 0.75)) # Q1 User chooses one point, two points, or cerebellum simulation button1_text = OnscreenText(text="What type of simulation?", scale=0.1, pos=(0, 0.6), align=TextNode.ACenter) # For DirectButton variables, the value has to be in the form of a list. # This value can be anything, but you have to call it later as, # in this case, v1[0] to return a value and not a list. button11 = DirectRadioButton(text="One Point", command=self.item1, variable=self.v1, value=[1], scale=0.1, pos=(-0.56, 0, 0.45), pressEffect=1, indicatorValue=0) button12 = DirectRadioButton(text="Two Point", command=self.item1, variable=self.v1, value=[2], scale=0.1, pos=(0, 0, 0.45), pressEffect=1, indicatorValue=0) button13 = DirectRadioButton(text="Cerebellum", command=self.item1, variable=self.v1, value=[3], scale=0.1, pos=(0.6, 0, 0.45), pressEffect=1, indicatorValue=0) # You have to setOthers() to have the DirectRadioButton allow only one # value for each button clicked. The current 'checked' box won't # 'uncheck' when you select a different button without this. buttons1 = [button11, button12, button13] for button in buttons1: button.setOthers(buttons1) # Q2 How far apart will the two points be if you use two. button2_text = OnscreenText(text="How far apart (if two points)", scale=0.1, pos=(0, 0.3), align=TextNode.ACenter) button2 = DirectEntry(text="", command=self.item2, initialText="30", scale=0.1, width=10, numLines=1, pos=(-0.4, 0, 0.15)) # Q3 How many points in the cerebellar simulation? button3_text = OnscreenText(text="What type of simulation?", scale=0.1, pos=(0, 0), align=TextNode.ACenter) button31 = DirectRadioButton(text="Four", command=self.item3, variable=self.v3, value=[True], scale=0.1, pos=(-0.2, 0, -0.15), pressEffect=1, indicatorValue=0) button32 = DirectRadioButton(text="Five", command=self.item3, variable=self.v3, value=[False], scale=0.1, pos=(0.2, 0, -0.15), pressEffect=1, indicatorValue=0) buttons3 = [button31, button32] for button in buttons3: button.setOthers(buttons3) # Q4 What color scheme? Gray, random, RGBY(W)? The colors come from # the paper mentioned at the start. button4_text = OnscreenText(text="What color scheme?", scale=0.1, pos=(0, -0.3), align=TextNode.ACenter) button41 = DirectRadioButton(text="Gray", command=self.item4, variable=self.v4, value=[1], scale=0.1, pos=(-0.5, 0, -0.45), pressEffect=1, indicatorValue=0) button42 = DirectRadioButton(text="Random", command=self.item4, variable=self.v4, value=[2], scale=0.1, pos=(-0.05, 0, -0.45), pressEffect=1, indicatorValue=0) button43 = DirectRadioButton(text="RGBY(W)", command=self.item4, variable=self.v4, value=[3], scale=0.1, pos=(0.5, 0, -0.45), pressEffect=1, indicatorValue=0) buttons4 = [button41, button42, button43] for button in buttons4: button.setOthers(buttons4) # Exit. exit_button = DirectButton(text="Make it so!", command=self.exit_button, scale=0.1, pos=(0, 0, -0.75), pressEffect=1) self.button0_text = button0_text self.button0 = button0 self.button1_text = button1_text self.button11 = button11 self.button12 = button12 self.button13 = button13 self.button2_text = button2_text self.button2 = button2 self.button3_text = button3_text self.button31 = button31 self.button32 = button32 self.button4_text = button4_text self.button41 = button41 self.button42 = button42 self.button43 = button43 self.exit_button = exit_button # sphere size def item0(self, param0): try: param0 = int(param0) except ValueError: param0 = 5 self.params[0] = param0 # One point, two points, cerebellum simulation def item1(self): # For variables entries, self.params[1] = self.v1[0] # How far apart will the two points be if you use two. def item2(self, param2): try: param2 = int(param2) except ValueError: param2 = 30 self.params[2] = param2 # How many points in the cerebellar simulation, 4 or 5 def item3(self): self.params[3] = self.v3[0] # What color scheme. Gray, random, RGBY(W)? def item4(self): self.params[4] = self.v4[0] def exit_button(self): self.button0_text.cleanup() self.button0.destroy() self.button1_text.cleanup() self.button11.destroy() self.button12.destroy() self.button13.destroy() self.button2_text.cleanup() self.button2.destroy() self.button3_text.cleanup() self.button31.destroy() self.button32.destroy() self.button4_text.cleanup() self.button41.destroy() self.button42.destroy() self.button43.destroy() self.exit_button.destroy() # Call the meat of the program upon exit of start menu. self.calculate() self.choose_and_run() def calculate(self): # one or two points or the cerebellum simulation self.SPHERE_SIZE = self.params[0] self.DIST_BTW = self.params[2] self.radius = self.SPHERE_SIZE / 1.5 self.extra_distance = int(round(1.8 * self.radius)) # Allowable vectors from a point. # Calculates number of possible vectors of a certain distance. # That distance is proportional to radius. # Turns degrees into radians 1 degree through 360 degrees. thetas = [(float(i) * pi) / 180 for i in range(360)] phis = thetas for theta in thetas: for phi in phis: x = self.radius * sin(theta) * cos(phi) y = self.radius * sin(theta) * sin(phi) z = self.radius * cos(theta) x = int(round(x)) y = int(round(y)) z = int(round(z)) self.possible_vectors.append((x, y, z)) self.possible_vectors = list(set(self.possible_vectors)) def choose_and_run(self): # one sphere at (0, 0, 0) if self.params[1] == 1: self.sphere_list = [(0, 0, 0)] self.outside_sphere_list0 = [] self.outside_sphere_list0.append(self.sphere_list[0]) self.counter_list0 = [0] if self.params[4] == 1: COLOR = VBase4(0.4, 0.4, 0.4, 1) # Choose random color if self.params[4] == 2: COLOR = random_color() if self.params[4] == 3: g = randint(0, 4) COLOR = ([ VBase4(1, 0, 0, 1), VBase4(0, 0.5, 0, 1), VBase4(0, 0, 1, 1), VBase4(1, 1, 0, 1), VBase4(1, 1, 1, 1) ][g]) # Two spheres DIST_BTW apart if user selects "Two Spheres" # Sets cerebellum to True if user selects "Cerebellum?" elif self.params[1] == 2: self.sphere_list = [(-self.DIST_BTW / 2, 0, 0), (self.DIST_BTW / 2, 0, 0)] if self.params[4] == 1: COLOR = [VBase4(0.4, 0.4, 0.4, 1), VBase4(0.6, 0.6, 0.6, 1)] elif self.params[4] == 2: COLOR = [] COLOR.append(random_color()) COLOR.append(random_color()) elif self.params[4] == 3: COLOR = [] for i in range(2): g = randint(0, 4) COLOR.append([ VBase4(1, 0, 0, 1), VBase4(0, 0.5, 0, 1), VBase4(0, 0, 1, 1), VBase4(1, 1, 0, 1), VBase4(1, 1, 1, 1) ][g]) # Will need these local variable lists. They define which # nodes are chosen each iteration to 'grow.' # Will need one list for each time we want a new node # (coudn't find a way around it). self.outside_sphere_list0.append(self.sphere_list[0]) self.counter_list0 = [0] self.outside_sphere_list1.append(self.sphere_list[1]) self.counter_list1 = [0] elif self.params[1] == 3: self.sphere_list = [(-25, 0, 0), (25, 0, 0), (0, 0, 13), (0, 0, -17), (-25, 0, -17)] # choose colors based on user input. if self.params[4] == 1: COLOR = [ VBase4(float(i) / 10, float(i) / 10, float(i) / 10, 1) for i in range(3, 8) ] elif self.params[4] == 2: COLOR = [random_color() for i in range(5)] elif self.params[4] == 3: COLOR = [ VBase4(1, 0, 0, 1), VBase4(0, 0.5, 0, 1), VBase4(0, 0, 1, 1), VBase4(1, 1, 0, 1), VBase4(1, 1, 1, 1) ] # Similar to if the user chooses two points, but more points obviously self.outside_sphere_list0.append(self.sphere_list[0]) self.counter_list0 = [0] self.outside_sphere_list1.append(self.sphere_list[1]) self.counter_list1 = [0] self.outside_sphere_list2.append(self.sphere_list[2]) self.counter_list2 = [0] self.outside_sphere_list3.append(self.sphere_list[3]) self.counter_list3 = [0] if self.params[3] == False: self.outside_sphere_list4 = [] self.outside_sphere_list4.append(self.sphere_list[4]) self.counter_list4 = [0] # task manager for drawing the spheres with add_sphere below if self.params[1] == 1: self.load_sphere(self.sphere_list[0], self.directionalLight, self.ambientLight, COLOR) self.taskMgr.add(self.add_sphere, "add_sphere", extraArgs=[ COLOR, self.sphere_list[0], self.outside_sphere_list0, self.counter_list0 ], appendTask=True) if self.params[1] == 2: self.load_sphere(self.sphere_list[0], self.directionalLight, self.ambientLight, COLOR[0]) self.load_sphere(self.sphere_list[1], self.directionalLight, self.ambientLight, COLOR[1]) self.taskMgr.add(self.add_sphere, "add_sphere", extraArgs=[ COLOR[0], self.sphere_list[0], self.outside_sphere_list0, self.counter_list0 ], appendTask=True) self.taskMgr.add(self.add_sphere, "add_sphere", extraArgs=[ COLOR[1], self.sphere_list[1], self.outside_sphere_list1, self.counter_list1 ], appendTask=True) # This is for all the spheres in the cerebellum simulation. if self.params[1] == 3: if self.params[3] == True: four_or_five = 4 elif self.params[3] == False: four_or_five = 5 for i in range(four_or_five): self.load_sphere(self.sphere_list[i], self.directionalLight, self.ambientLight, COLOR[i]) self.taskMgr.add(self.add_sphere, "add_sphere", extraArgs=[ COLOR[0], self.sphere_list[0], self.outside_sphere_list0, self.counter_list0 ], appendTask=True) self.taskMgr.add(self.add_sphere, "add_sphere", extraArgs=[ COLOR[1], self.sphere_list[1], self.outside_sphere_list1, self.counter_list1 ], appendTask=True) self.taskMgr.add(self.add_sphere, "add_sphere", extraArgs=[ COLOR[2], self.sphere_list[2], self.outside_sphere_list2, self.counter_list2 ], appendTask=True) self.taskMgr.add(self.add_sphere, "add_sphere", extraArgs=[ COLOR[3], self.sphere_list[3], self.outside_sphere_list3, self.counter_list3 ], appendTask=True) if self.params[3] == False: self.taskMgr.add(self.add_sphere, "add_sphere", extraArgs=[ COLOR[4], self.sphere_list[4], self.outside_sphere_list4, self.counter_list4 ], appendTask=True) # Loads a sphere. The inputs are self explanatory. # I set the directional and ambient light to class globals, # so it wouldn't creat a new light per sphere, which is possible # but apparently expensive. def load_sphere(self, position, directionalLight, ambientLight, color): # Load a sphere. pos = position self.sphere = self.loader.loadModel("ball") self.sphere.setScale(self.SPHERE_SIZE, self.SPHERE_SIZE, self.SPHERE_SIZE) self.sphere.setPos(pos) # Sets the sphere color. self.sphere.setColor(color) self.sphere.reparentTo(render) # Make the sphere a material (to behave with the light). material = Material() material.setShininess(10.0) self.sphere.setMaterial(material) # Set lighting on the sphere. self.sphere.setLight(self.sphere.attachNewNode(directionalLight)) self.sphere.setLight(self.sphere.attachNewNode(ambientLight)) # Adds spheres to the scene. def add_sphere(self, color, starting_node, outside_sphere_list, counter_list, task): # select randomly from the list of spheres n = randint(0, len(outside_sphere_list) - 1) chosen_sphere = outside_sphere_list[n] # select randomly from the list of possible vectors n = randint(0, len(self.possible_vectors) - 1) chosen_vector = self.possible_vectors[n] # add the vectors together to get a new location # for a sphere x = chosen_sphere[0] + chosen_vector[0] y = chosen_sphere[1] + chosen_vector[1] z = chosen_sphere[2] + chosen_vector[2] # calculates the distance from where the new sphere will randomly be # drawn to the other spheres, removes reduntant numbers d = [] f = [] distances = [] pop = list(self.sphere_list) if len(pop) > 1: pop.remove(chosen_sphere) d = [(x, y, z) for i in range(len(pop))] distances = [int(euclidean(d[i], pop[i])) \ for i in range(len(pop))] distances = list(set(distances)) # Recalculate distances from the other spheres for the chosen_sphere. # This method of culling spheres is a little inefficient. Perhaps in # the future I could make it more efficient by just choosing spheres # that are nearby. I'm not sure yet how to accomplish this. d = [] chosen_distances = [] d = [chosen_sphere for i in range(len(pop))] chosen_distances = [ int(euclidean(d[i], pop[i])) for i in range(len(pop)) ] chosen_distances = list(set(chosen_distances)) # Sorts the chosen_distances lowest to highest. chosen_distances.sort() # temp will be used to index the counter of chosen_sphere. temp = outside_sphere_list.index(chosen_sphere) # Make the new sphere list and render the sphere. # First if statement only allows the render if the sphere # is going to be a certain distance away from all the other spheres, # in this case a 'radius' distance away. if min(distances) >= int(self.radius): if counter_list[temp] <= 1: if len(chosen_distances) <= 5: outside_sphere_list.append((x, y, z)) self.sphere_list.append((x, y, z)) counter_list.append(0) # The chosen_sphere counter goes up by one. counter_list[temp] += 1 # Render sphere. self.load_sphere((x, y, z), self.directionalLight, self.ambientLight, color) if len(chosen_distances) > 5 \ and chosen_distances[5] >= int(self.radius) \ + self.extra_distance: outside_sphere_list.append((x, y, z)) self.sphere_list.append((x, y, z)) counter_list.append(0) # The chosen_sphere counter goes up by one. counter_list[temp] += 1 # draw sphere self.load_sphere((x, y, z), self.directionalLight, self.ambientLight, color) # The only available spheres for selection are the outside # ones in sphere_list. They 'burn out' after the number chosen # in the if statement. if counter_list[temp] > 1: outside_sphere_list.remove(chosen_sphere) del counter_list[temp] return Task.cont
def __init__(self): ShowBase.__init__(self) # Override defaults self.disableMouse() self.setBackgroundColor(VBase3(160, 200, 150) / 255.0) self.setFrameRateMeter(True) # Lights dlight = DirectionalLight("dlight") dlnp = self.render.attachNewNode(dlight) dlnp.setHpr(180.0, -70.0, 0) self.render.setLight(dlnp) alight = AmbientLight("alight") alnp = self.render.attachNewNode(alight) alight.setColor(VBase4(0.4, 0.4, 0.4, 1)) self.render.setLight(alnp) # Collision traverser self.cTrav = CollisionTraverser("collisionTraverser") # self.cTrav.showCollisions(self.render) # Collision handlers self.carCollisionHandler = CollisionHandlerEvent() self.carCollisionHandler.addInPattern("%fn-into-%in") # Camera controls self.cameraController = CameraController(self, 600, math.radians(45), math.radians(60)) # Load the track self.track = self.loader.loadModel("models/trackMotegi") # self.track = self.loader.loadModel("models/trackValencia") checkpointsCollision = self.track.find("checkpoints").node() checkpointsCollision.setIntoCollideMask(BitMask32(0xF0)) self.numCheckpoints = checkpointsCollision.getNumSolids() self.track.reparentTo(self.render) # Enemy cars enemyColor = LColor(204 / 255.0, 72 / 255.0, 63 / 255.0, 1.0) self.enemyPos = [(-150, -110, 60), (113, -233, 45), (-255, -264, 20), (-364, -237, -90), (-204, -46, 230)] self.enemyCars = [] for pos in self.enemyPos: car = NeuralNetworkCar(self) car.getNodePath().setColor(enemyColor) car.getNodePath().setX(pos[0]) car.getNodePath().setY(pos[1]) car.getNodePath().setH(pos[2]) self.enemyCars.append(car) # Neuroevolution # self.loggingActive = False self.inputLayerSize = 9 self.hiddenLayer1Size = 5 self.hiddenLayer2Size = 5 self.numLabels = 2 self.thetaSizes = [(self.hiddenLayer1Size, self.inputLayerSize + 1), (self.hiddenLayer2Size, self.hiddenLayer1Size + 1), (self.numLabels, self.hiddenLayer2Size + 1)] self.generationSize = 15 self.weightInit = 0.12 self.replaceRatio = 0.02 self.scaleRatio = 0.02 self.addRatio = 0.02 self.generationCount = 1 self.cars = [] for i in range(self.generationSize): car = NeuroevolutionCar(self, i, self.inputLayerSize) # Register car collisions with track self.cTrav.addCollider(car.carCollider, self.carCollisionHandler) self.accept("carCollider{}-into-carCollider".format(i), car.onCrash) self.accept("carCollider{}-into-trackCollision".format(i), car.onCrash) self.accept("carCollider{}-into-checkpoints".format(i), car.onCheckpoint) self.cars.append(car) # Initial generation np.random.seed(0) for i in range(self.generationSize): theta1 = self.randWeights(self.thetaSizes[0], self.weightInit) theta2 = self.randWeights(self.thetaSizes[1], self.weightInit) theta3 = self.randWeights(self.thetaSizes[2], self.weightInit) self.cars[i].startSimulation(theta1, theta2, theta3) # Run learning task self.taskMgr.add(self.neuroevolution, "NeuroevolutionTask") # DEBUG self.accept("l", self.logGeneration) self.txtGen = OnscreenText(text='', pos=(0.0, -0.04), scale=0.05, align=TextNode.ALeft, fg=(1, 1, 1, 1), bg=(0, 0, 0, .4)) self.txtGen.reparentTo(self.a2dTopLeft)