Esempio n. 1
0
    def handle_collisions(self):
        self.collision_handling_mutex.acquire()
	self.groundCol.setIntoCollideMask(BitMask32.bit(0))
        self.groundCol.setFromCollideMask(BitMask32.bit(1))

        # Now check for collisions.

        self.cTrav.traverse(render)

        # Keep the camera at one foot above the terrain,
        # or two feet above the actor, whichever is greater.
        
        entries = []
        for i in range(self.groundHandler.getNumEntries()):
            entry = self.groundHandler.getEntry(i)
            entries.append(entry)
        entries.sort(lambda x,y: cmp(y.getSurfacePoint(render).getZ(),
                                     x.getSurfacePoint(render).getZ()))
        if (len(entries)>0) and (entries[0].getIntoNode().getName() == "terrain"):
            base.camera.setZ(entries[0].getSurfacePoint(render).getZ()+1.0)
        if (base.camera.getZ() < self.actor.getZ() + 2.0):
            base.camera.setZ(self.actor.getZ() + 2.0)
        
	self.groundCol.setIntoCollideMask(BitMask32.bit(0))
        self.groundCol.setFromCollideMask(BitMask32.bit(0))
        self.collision_handling_mutex.release()
Esempio n. 2
0
	def handle_collisions(self, seconds):
		self.collision_handling_mutex.acquire()
		self.groundCol.setIntoCollideMask(BitMask32.bit(0))
		self.groundCol.setFromCollideMask(BitMask32.bit(1))
		
		# Now check for collisions.
		self.cTrav.traverse(render)
		
		# Adjust the object's Z coordinate.  If the object's ray hit anything,
		# update its Z.
		
		current_z = self.attach_object.render_model.getZ() - self.object_bottom_buffer_distance
		entries = []
		for i in range(self.groundHandler.getNumEntries()):
			entry = self.groundHandler.getEntry(i)
			if (entry.getSurfacePoint(render).getZ() - 0.001 < current_z):
				entries.append(entry)

		entries.sort(lambda x,y: cmp(y.getSurfacePoint(render).getZ(),
					     x.getSurfacePoint(render).getZ()))
		if (len(entries)>0):
			surface_z = entries[0].getSurfacePoint(render).getZ()
			#print "> " + self.attach_object.name + " is falling toward " + entries[0].getIntoNode().getName() + "\n"
			new_z = current_z - (self.falling_velocity * seconds)
			if (new_z < surface_z):
				new_z = surface_z
			if ((new_z > current_z + 0.00001) or (new_z < current_z - 0.00001)):
				self.attach_object.render_model.setZ(new_z + self.object_bottom_buffer_distance)
		
		self.groundCol.setIntoCollideMask(BitMask32.bit(0))
		self.groundCol.setFromCollideMask(BitMask32.bit(0))
		self.collision_handling_mutex.release()
Esempio n. 3
0
 def makeNew(self, pos, nor, parent = None):
   """Makes a new bullet hole."""
   if parent == None:
     parent = self.container
   else:
     # Add a subnode to the parent, if it's not already there
     child = parent.find('bullet-holes')
     if child.isEmpty():
       parent = parent.attachNewNode('bullet-holes')
     else:
       parent = child
   newhole = NodePath(self.card.generate())
   newhole.reparentTo(parent)
   newhole.lookAt(render, Point3(newhole.getPos(render) - nor))
   newhole.setR(newhole, random() * 360.0)
   newhole.setPos(render, pos)
   # Offset it a little to avoid z-fighting
   # Increase this value if you still see it.
   newhole.setY(newhole, -.001 - random() * 0.01)
   del newhole
   # We don't want one batch per bullet hole, so flatten it.
   # This could be made smarter to preserve culling, but
   # I have yet to see a performance loss.
   # The clearTexture() is a necessary hack.
   parent.clearTexture()
   parent.flattenStrong()
   parent.setTexture(self.texture)
   parent.setTransparency(TransparencyAttrib.MDual)
   parent.setShaderOff(1)
   parent.hide(BitMask32.bit(2)) # Invisible to volumetric lighting camera (speedup)
   parent.hide(BitMask32.bit(3)) # Invisible to shadow cameras (speedup)
Esempio n. 4
0
  def __init__(self, ywn):
      '''
      Constructor
      '''
      Thing.__init__(self, "Lightswitch", ywn)
      
      self.model = loader.loadModel('models/Lightswitch')
      
      self.model.find("**/Piattina").node().setIntoCollideMask(BitMask32.bit(1))
      self.model.find("**/Piattina").node().setTag('ID', self.Id)
      self.model.find("**/Piattina").node().setTag('nodeId', "Piattina")
      
      self.model.find("**/Switch").node().setIntoCollideMask(BitMask32.bit(1))
      self.model.find("**/Switch").node().setTag('ID', self.Id)
      self.model.find("**/Switch").node().setTag('nodeId', "Switch")
      self.model.find("**/Switch").setP(332)
      
      self.model.find("**/TopScrew").node().setIntoCollideMask(BitMask32.bit(1))
      self.model.find("**/TopScrew").node().setTag('ID', self.Id)
      self.model.find("**/TopScrew").node().setTag('nodeId', "TopScrew")
 
      self.model.find("**/BottomScrew").node().setIntoCollideMask(BitMask32.bit(1))
      self.model.find("**/BottomScrew").node().setTag('ID', self.Id)
      self.model.find("**/BottomScrew").node().setTag('nodeId', "BottomScrew")
      
      self.model.setTag('ID', self.Id)
      
      self.status = Lightswitch.SWITCH_OFF
Esempio n. 5
0
    def __init__(self, model, run, walk, startPos, scale, select,ralph,saysome):

        self.actor = Actor(model, {"run":run, "walk":walk})
        self.actor.reparentTo(render)
        self.actor.setScale(scale)
        self.actor.setPos(startPos)
        self.actor.setHpr(90,0,0)
        self.playerGUI = saysome
        self.myralph = ralph
        self.setAI()

        self.cTrav = CollisionTraverser()

        self.groundRay = CollisionRay(0,0,1000,0,0,-1)  
        self.groundCol = CollisionNode('dinoRay')
        self.groundCol.addSolid(self.groundRay)
        self.groundCol.setFromCollideMask(BitMask32.bit(1))
        self.groundCol.setIntoCollideMask(BitMask32.allOff())
        self.groundColNp = self.actor.attachNewNode(self.groundCol)
        self.groundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.groundColNp, self.groundHandler)

        self.sphere = CollisionSphere(0,0,5,13)
        self.spherecol = CollisionNode('dinoSphere')
        self.spherecol.addSolid(self.sphere)
        self.spherecol.setCollideMask(BitMask32.bit(1))
        self.dinocolhs = self.actor.attachNewNode(self.spherecol)
Esempio n. 6
0
    def setupCollisions(self):

        #player sphere
        cPlayerSphere = CollisionSphere(Point3(0, 0, .5), 10)
        cPlayerNode = CollisionNode("Player")
        cPlayerNode.addSolid(cPlayerSphere)
        
        cPlayerNode.setFromCollideMask(BitMask32.bit(4))
        cPlayerNode.setIntoCollideMask(BitMask32(20))
        
        cPlayerNP = self.player.attachNewNode(cPlayerNode)
        self.cTrav.addCollider(cPlayerNP, self.playerGroundHandler)
        #self.cTrav.addCollider(cPlayerNP, self.cRocketHandler)
        #cPlayerNP.show()
        
        
        #enemy sphere
        cEnemySphere = CollisionSphere(Point3(0, 0, .5), 10)
        cEnemyNode = CollisionNode("Enemy")
        cEnemyNode.addSolid(cEnemySphere)
        
        cEnemyNode.setFromCollideMask(BitMask32.bit(4))
        cEnemyNode.setIntoCollideMask(BitMask32(18))
        
        cEnemyNP = self.enemy.attachNewNode(cEnemyNode)
        self.cTrav.addCollider(cEnemyNP, self.enemyGroundHandler)
Esempio n. 7
0
    def handle_collisions(self):
        self.collision_handling_mutex.acquire()
        self.groundCol.setIntoCollideMask(BitMask32.bit(0))
        self.groundCol.setFromCollideMask(BitMask32.bit(1))

        # Now check for collisions.
        self.cTrav.traverse(render)
        
        # Adjust the character's Z coordinate.  If the character's ray hit terrain,
        # update his Z. If it hit anything else, or didn't hit anything, put
        # him back where he was last frame.
        
        entries = []
        for i in range(self.groundHandler.getNumEntries()):
            entry = self.groundHandler.getEntry(i)
            entries.append(entry)
        entries.sort(lambda x,y: cmp(y.getSurfacePoint(render).getZ(),
                                     x.getSurfacePoint(render).getZ()))
        if (len(entries)>0) and (entries[0].getIntoNode().getName() == "terrain"):
            self.actor.setZ(entries[0].getSurfacePoint(render).getZ())
        else:
            self.actor.setPos(self.startpos)
        
        self.groundCol.setIntoCollideMask(BitMask32.bit(0))
        self.groundCol.setFromCollideMask(BitMask32.bit(0))
        self.collision_handling_mutex.release()
Esempio n. 8
0
 def makeNew(self, pos, nor, parent=None):
     """Makes a new bullet hole."""
     if parent == None:
         parent = self.container
     else:
         # Add a subnode to the parent, if it's not already there
         child = parent.find('bullet-holes')
         if child.isEmpty():
             parent = parent.attachNewNode('bullet-holes')
         else:
             parent = child
     newhole = NodePath(self.card.generate())
     newhole.reparentTo(parent)
     newhole.lookAt(render, Point3(newhole.getPos(render) - nor))
     newhole.setR(newhole, random() * 360.0)
     newhole.setPos(render, pos)
     # Offset it a little to avoid z-fighting
     # Increase this value if you still see it.
     newhole.setY(newhole, -.001 - random() * 0.01)
     del newhole
     # We don't want one batch per bullet hole, so flatten it.
     # This could be made smarter to preserve culling, but
     # I have yet to see a performance loss.
     # The clearTexture() is a necessary hack.
     parent.clearTexture()
     parent.flattenStrong()
     parent.setTexture(self.texture)
     parent.setTransparency(TransparencyAttrib.MDual)
     parent.setShaderOff(1)
     parent.hide(BitMask32.bit(
         2))  # Invisible to volumetric lighting camera (speedup)
     parent.hide(BitMask32.bit(3))  # Invisible to shadow cameras (speedup)
Esempio n. 9
0
  def start(self):
    if self.bgColour!=None: base.setBackgroundColor(self.bgColour)

    if self.model!=None:
      self.model.show()
      self.model.hide(BitMask32.bit(1)) # Hide from the reflection camera
      self.model.hide(BitMask32.bit(2)) # Hide from the volumetric lighting camera
      self.model.hide(BitMask32.bit(3)) # Hide from the shadow camera(s), if any
Esempio n. 10
0
    def start(self):
        if self.bgColour != None: base.setBackgroundColor(self.bgColour)

        if self.model != None:
            self.model.show()
            self.model.hide(
                BitMask32.bit(1))  # Hide from the reflection camera
            self.model.hide(
                BitMask32.bit(2))  # Hide from the volumetric lighting camera
            self.model.hide(
                BitMask32.bit(3))  # Hide from the shadow camera(s), if any
Esempio n. 11
0
  def __init__(self,manager,xml):
    self.surface = getWaterSurface(manager)
    self.surface.reparentTo(render)
    self.surface.hide(BitMask32.bit(1)) # Invisible to reflection camera (speedup)
    self.surface.hide(BitMask32.bit(2)) # Invisible to volumetric lighting camera (speedup)
    self.surface.hide(BitMask32.bit(3)) # Invisible to shadow cameras (speedup)
    self.surface.setShader(loader.loadShader(manager.get('paths').getConfig().find('shaders').get('path')+'/water.cg'))
    self.surface.setShaderInput('time', 0.0, 0.0, 0.0, 0.0)
    ntex = loader.loadTexture(manager.get('paths').getConfig().find('textures').get('path')+'/water-normal.png')
    ntex.setMinfilter(Texture.FTLinearMipmapLinear)
    self.surface.setShaderInput('normal', ntex)
    self.surface.setShaderInput('camera', base.cam)
    self.surface.setTransparency(TransparencyAttrib.MDual, 10)
    self.surface.setTwoSided(True)

    self.surface.setShaderInput('waveInfo', Vec4(0.4, 0.4, 0.4, 0))
    self.surface.setShaderInput('param2', Vec4(-0.015,0.005, 0.05, 0.05))
    self.surface.setShaderInput('param3', Vec4(0.7, 0.3, 0, 0))
    self.surface.setShaderInput('param4', Vec4(2.0, 0.5, 0.5, 0.0))
    #self.surface.setShaderInput('speed', Vec4(-.8, -.4, -.9, .3))
    self.surface.setShaderInput('speed', Vec4(0.2, -1.2, -0.2, -0.7))
    self.surface.setShaderInput('deepcolor', Vec4(0.0,0.3,0.5,1.0))
    self.surface.setShaderInput('shallowcolor', Vec4(0.0,1.0,1.0,1.0))
    self.surface.setShaderInput('reflectioncolor', Vec4(0.95,1.0,1.0,1.0))
    self.surface.hide()

    self.wbuffer = base.win.makeTextureBuffer('water', 512, 512)
    self.wbuffer.setClearColorActive(True)
    self.wbuffer.setClearColor(base.win.getClearColor())
    self.wcamera = base.makeCamera(self.wbuffer)
    if manager.get('sky') != None and manager.get('sky').model != None:
      self.sky = manager.get('sky').model.copyTo(self.wcamera)
      self.sky.setTwoSided(True)
      self.sky.setSz(self.sky, -1)
      self.sky.setClipPlaneOff(1)
      self.sky.show()
      self.sky.hide(BitMask32.bit(0)) # Hide for normal camera
      self.sky.hide(BitMask32.bit(2)) # Hide for volumetric lighting camera
      self.sky.hide(BitMask32.bit(3)) # Hide for shadow camera(s), if any
    else:
      self.sky = None
    self.wcamera.reparentTo(render)
    self.wcamera.node().setLens(base.camLens)
    self.wcamera.node().setCameraMask(BitMask32.bit(1))
    self.surface.hide(BitMask32.bit(1))
    wtexture = self.wbuffer.getTexture()
    wtexture.setWrapU(Texture.WMClamp)
    wtexture.setWrapV(Texture.WMClamp)
    wtexture.setMinfilter(Texture.FTLinearMipmapLinear)
    self.surface.setShaderInput('reflection', wtexture)
    self.wplane = Plane(Vec3(0, 0, 1), Point3(0, 0, 0))
    self.wplanenp = render.attachNewNode(PlaneNode('water', self.wplane))
    tmpnp = NodePath('StateInitializer')
    tmpnp.setClipPlane(self.wplanenp)
    tmpnp.setAttrib(CullFaceAttrib.makeReverse())
    self.wcamera.node().setInitialState(tmpnp.getState())

    #self.fog = Fog('UnderwaterFog')
    #self.fog.setColor(0.0,0.3,0.5)
    self.fogEnabled = False
Esempio n. 12
0
	def initialize_collision_handling(self):
		self.collision_handling_mutex = Lock()
		
		self.cTrav = CollisionTraverser()
		
		self.groundRay = CollisionRay()
		self.groundRay.setOrigin(0,0,1000)
		self.groundRay.setDirection(0,0,-1)
		self.groundCol = CollisionNode(self.attach_object.name + "_collision_node")
		self.groundCol.setIntoCollideMask(BitMask32.bit(0))
		self.groundCol.setFromCollideMask(BitMask32.bit(0))
		self.groundCol.addSolid(self.groundRay)
		self.groundColNp = self.attach_object.render_model.attachNewNode(self.groundCol)
		self.groundHandler = CollisionHandlerQueue()
		self.cTrav.addCollider(self.groundColNp, self.groundHandler)
    def __setupNPC(self):
        # This is to support the collisions for each node. See the paragraph comment
        # above where we modify the npc's collision node
#        playerCollisionNP = self.__mainTarget.find("* collision node")

        modelStanding = "models/ralph"
        modelRunning = "models/ralph-run"
        modelWalking = "models/ralph-walk"
        self.__NPC = NPC(modelStanding, 
                                {"run":modelRunning, "walk":modelWalking},
                                turnRate = 150, 
                                speed = 15,
                                agentList = self.__globalAgentList,
                                name = "Ralph",
                                collisionMask = BitMask32.bit(3),
                                rangeFinderCount = 13,
                                adjacencySensorThreshold = 5,
                                radarSlices = 5,
                                radarLength = 0,
                                scale = 1.0,
                                massKg = 35.0,
                                collisionHandler = self.physicsCollisionHandler,
                                collisionTraverser = self.cTrav,
                                waypoints = self.roomWaypoints)
        self.__NPC.setFluidPos(render, 20, 10, 0)#-190
        self.__NPC.setScale(render, 1)
        self.__NPC.setTarget(self.__mainTarget)

        self.__NPC.reparentTo(render)
	self.__NPC.start()
Esempio n. 14
0
	def make(self):
		"""Build a finished renderable heightMap."""
		
		# apply shader
		#logging.info( "applying shader")
		self.terrain.texturer.apply(self.getRoot())
		
		# detail settings
		#self.getRoot().setSz(1.0 / self.heightMapDetail)
		#self.getRoot().setSy(1.0 / self.heightMapDetail)
		
		#logging.info( "making height map")
		self.makeHeightMap()
		#logging.info( "setHeight()")
		self.setHeight()
		#self.getRoot().setSz(self.maxHeight)
		
		#http://www.panda3d.org/forums/viewtopic.php?=t=12054
		self.calcAmbientOcclusion()
		#loggin.info( "generate()")
		self.generate()
		self.getRoot().setCollideMask(BitMask32.bit(1))
		
		#self.makeSlopeMap()
		#logging.info( "createGroups()")
		self.createGroups()
		self.terrain.populator.populate(self)
Esempio n. 15
0
File: Book.py Progetto: sambarza/bo
 def __init__(self, ywn):
     '''
     Constructor
     '''
     Thing.__init__(self, "Book", ywn)
     
     self.model = loader.loadModel('models/Book')
     
     self.model.find("**/Front").node().setIntoCollideMask(BitMask32.bit(1))
     self.model.find("**/Back").node().setIntoCollideMask(BitMask32.bit(1))
     self.model.find("**/Front").node().setTag('ID', self.Id)
     self.model.find("**/Back").node().setTag('ID', self.Id)
     self.model.find("**/Front").node().setTag('nodeId', "front")
     self.model.find("**/Back").node().setTag('nodeId', "back")
     
     self.model.setTag('ID', self.Id)
Esempio n. 16
0
 def __init__(self, render, camera):
     #Since we are using collision detection to do picking, we set it up like any other collision detection system with a traverser and a handler 
     self.picker = CollisionTraverser()            #Make a traverser 
     self.pq     = CollisionHandlerQueue()         #Make a handler 
     #Make a collision node for our picker ray 
     self.pickerNode = CollisionNode('mouseRay') 
     #Attach that node to the camera since the ray will need to be positioned relative to it 
     self.pickerNP = camera.attachNewNode(self.pickerNode) 
     #Everything to be picked will use bit 1. This way if we were doing other collision we could seperate it 
     self.pickerNode.setFromCollideMask(BitMask32.bit(1)) 
     self.pickerRay = CollisionRay()               #Make our ray 
     self.pickerNode.addSolid(self.pickerRay)      #Add it to the collision node 
     #Register the ray as something that can cause collisions 
     self.picker.addCollider(self.pickerNP, self.pq) 
     #self.picker.showCollisions(render) 
     
     self.pst = CollisionTraverser()            #Make a traverser 
     self.hqp     = CollisionHandlerQueue()         #Make a handler 
     #Make a collision node for our picker ray 
     
     self.pstNode = CollisionNode('mouseRaytoObj') 
     #Attach that node to the camera since the ray will need to be positioned relative to it 
     self.pstNode.setFromCollideMask(GeomNode.getDefaultCollideMask())
     self.pstNode2 = camera.attachNewNode(self.pstNode) 
     self.pickerRayObj = CollisionRay()   
     #Everything to be picked will use bit 1. This way if we were doing other collision we could seperate it 
     #self.pstNode.setFromCollideMask(BitMask32.bit(1)) 
     self.pstNode.addSolid(self.pickerRayObj)      #Add it to the collision node 
     #Register the ray as something that can cause collisions 
     self.pst.addCollider(self.pstNode2, self.hqp) 
     #self.pst.showCollisions(render) 
    def __setupNPC(self):
        # This is to support the collisions for each node. See the paragraph comment
        # above where we modify the npc's collision node
        #        playerCollisionNP = self.__mainTarget.find("* collision node")

        modelStanding = "models/ralph"
        modelRunning = "models/ralph-run"
        modelWalking = "models/ralph-walk"
        self.__NPC = NPC(modelStanding, {
            "run": modelRunning,
            "walk": modelWalking
        },
                         turnRate=150,
                         speed=15,
                         agentList=self.__globalAgentList,
                         name="Ralph",
                         collisionMask=BitMask32.bit(3),
                         rangeFinderCount=13,
                         adjacencySensorThreshold=5,
                         radarSlices=5,
                         radarLength=0,
                         scale=1.0,
                         massKg=35.0,
                         collisionHandler=self.physicsCollisionHandler,
                         collisionTraverser=self.cTrav,
                         waypoints=self.roomWaypoints)
        self.__NPC.setFluidPos(render, 20, 10, 0)  #-190
        self.__NPC.setScale(render, 1)
        self.__NPC.setTarget(self.__mainTarget)

        self.__NPC.reparentTo(render)
        self.__NPC.start()
Esempio n. 18
0
File: fpsTest.py Progetto: croza/RR2
    def __init__(self, parserClass, mainClass, mapLoaderClass, modelLoaderClass):
        self.switchState = False

        # self.t = Timer()

        self.keyMap = {"left": 0, "right": 0, "forward": 0, "backward": 0}
        self.ralph = Actor(
            "data/models/units/ralph/ralph",
            {"run": "data/models/units/ralph/ralph-run", "walk": "data/models/units/ralph/ralph-walk"},
        )
        self.ralph.reparentTo(render)
        # 		self.ralph.setPos(42, 30, 0)
        self.ralph.setPos(6, 10, 0)
        self.ralph.setScale(0.1)

        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left", 1])
        self.accept("arrow_left-up", self.setKey, ["left", 0])
        self.accept("arrow_right", self.setKey, ["right", 1])
        self.accept("arrow_right-up", self.setKey, ["right", 0])
        self.accept("arrow_up", self.setKey, ["forward", 1])
        self.accept("arrow_up-up", self.setKey, ["forward", 0])
        self.accept("arrow_down", self.setKey, ["backward", 1])
        self.accept("arrow_down-up", self.setKey, ["backward", 0])

        self.isMoving = False

        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.ralphGroundCol.show()

        base.cam.reparentTo(self.ralph)
        base.cam.setPos(0, 9, 7)
        self.floater2 = NodePath(PandaNode("floater2"))
        self.floater2.reparentTo(self.ralph)
        self.floater2.setZ(self.floater2.getZ() + 6)
        base.cam.lookAt(self.floater2)

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

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        taskMgr.add(self.move, "movingTask", extraArgs=[mainClass, parserClass, mapLoaderClass, modelLoaderClass])
Esempio n. 19
0
    def __init__(self,actor):

        self.actor = actor
        self.prevtime = 0
        self.controlMap = {"left":0, "right":0}

        taskMgr.add(self.move,"cameraMoveTask")
        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        base.disableMouse()
        #base.camera.setPos(self.actor.getX(),self.actor.getY()+10,2)
        base.camera.setPos(self.actor.getX()-30,self.actor.getY()-10,self.actor.getZ()+7)
        camera.setHpr(-60,0,0)

        self.cTrav = CollisionTraverser()
        self.groundRay = CollisionRay()
        self.groundRay.setOrigin(0,0,1000)
        self.groundRay.setDirection(0,0,-1)
        self.groundCol = CollisionNode('camRay')
        self.groundCol.addSolid(self.groundRay)
        self.groundCol.setFromCollideMask(BitMask32.bit(1))
        self.groundCol.setIntoCollideMask(BitMask32.allOff())
        self.groundColNp = base.camera.attachNewNode(self.groundCol)
        self.groundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.groundColNp, self.groundHandler)

        self.groundColNp.show()
    def make(self):
        """Build a finished renderable heightMap."""

        # apply shader
        #logging.info( "applying shader")
        self.terrain.texturer.apply(self.getRoot())

        # detail settings
        #self.getRoot().setSx(1.0 / self.heightMapDetail)
        #self.getRoot().setSy(1.0 / self.heightMapDetail)

        #logging.info( "making height map")
        self.makeHeightMap()
        #logging.info( "setHeight()")
        self.setHeight()
        #self.getRoot().setSz(self.maxHeight)

        #http://www.panda3d.org/forums/viewtopic.php?t=12054
        self.calcAmbientOcclusion()
        #logging.info( "generate()")
        self.generate()
        self.getRoot().setCollideMask(BitMask32.bit(1))

        #self.makeSlopeMap()
        #logging.info( "createGroups()")
        self.createGroups()
        self.terrain.populator.populate(self)
Esempio n. 21
0
    def placeItem(self, item):
        # Add ground collision detector to the health item
        self.cTrav1 = CollisionTraverser()

        self.collectGroundRay = CollisionRay()
        self.collectGroundRay.setOrigin(0,0,300)
        self.collectGroundRay.setDirection(0,0,-1)
        self.collectGroundCol = CollisionNode('colRay')
        self.collectGroundCol.addSolid(self.collectGroundRay)
        self.collectGroundCol.setFromCollideMask(BitMask32.bit(1))
        self.collectGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.collectGroundColNp = item.attachNewNode(self.collectGroundCol)
        self.collectGroundHandler = CollisionHandlerQueue()
        base.cTrav1.addCollider(self.collectGroundColNp, self.collectGroundHandler)
        
        placed = False;
        while placed == False:
            # re-randomize position
            item.setPos(-random.randint(-350,300),-random.randint(-100,150),0)
            
            base.cTrav1.traverse(render)
            
            # Get Z position from terrain collision
            entries = []
            for j in range(self.collectGroundHandler.getNumEntries()):
                entry = self.collectGroundHandler.getEntry(j)
                entries.append(entry)
            entries.sort(lambda x,y: cmp(y.getSurfacePoint(render).getZ(),
                                         x.getSurfacePoint(render).getZ()))
        
            if (len(entries)>0) and (entries[0].getIntoNode().getName() == "terrain"):
                item.setZ(entries[0].getSurfacePoint(render).getZ()+4)
                placed = True
Esempio n. 22
0
    def __init__(self, manager, xml):
        self.light = PDirectionalLight("dlight")
        self.lightNode = NodePath(self.light)
        self.lightNode.setCompass()
        if hasattr(self.lightNode.node(), "setCameraMask"):
            self.lightNode.node().setCameraMask(BitMask32.bit(3))

        self.reload(manager, xml)
Esempio n. 23
0
  def __init__(self,manager,xml):
    self.light = PDirectionalLight('dlight')
    self.lightNode = NodePath(self.light)
    self.lightNode.setCompass()
    if hasattr(self.lightNode.node(), "setCameraMask"):
      self.lightNode.node().setCameraMask(BitMask32.bit(3))

    self.reload(manager,xml)
Esempio n. 24
0
def intersect(lbase, delta, mask=None):
    t = time.time()
    root = lbase.rootnode
    terrain = root.getChildren()[2]
    terrain.setCollideMask(BitMask32.bit(1))
    player = root
    collTrav = CollisionTraverser() #the collision traverser. we need this to perform collide in the end
    fromObject = player.attachNewNode(CollisionNode('colNode'))

    camera_pos = tuple(lbase.cameras.getPos())

    lens = lbase.cameras.getChildren()[0].node().getLens()
    fov = np.radians(lens.getMinFov())
    zpos = camera_pos[1]
    sw = 2. * np.abs(zpos) * np.tan(fov / 2.)

    rvals = np.arange(-sw/2., sw/2., delta)
    if mask is None:
        poses = [(xpos , -1 * zpos, ypos) for xpos in rvals for ypos in rvals]
    else:
        assert mask.shape == (len(rvals), len(rvals))
        poses = [(xpos , -1 * zpos, ypos) for _i, xpos in enumerate(rvals) for _j, ypos in enumerate(rvals) if mask[_j, _i] < 1]
        print(len(poses), 'lp', len(rvals)**2)
    print('1a', time.time() - t)
    t = time.time()
    for p in poses:
        vec = camera_pos + p
        fromObject.node().addSolid(CollisionRay(*vec))
    print('1', time.time() - t)
    t = time.time()

    #and now we turn turn of the collision for the playermodel so it wont collide with the ray or anything.
    player.node().setIntoCollideMask(BitMask32.allOff())
    fromObject.node().setFromCollideMask(BitMask32.bit(1))

    queue = CollisionHandlerQueue()
    collTrav.addCollider(fromObject, queue)
    print('2', time.time() - t)
    t = time.time()

    collTrav.traverse(root)
    print('3', time.time() - t)
    return queue
Esempio n. 25
0
 def __init__(self):
     self.picker         = CollisionTraverser()            
     self.pickerQ        = CollisionHandlerQueue()         
     pickerCollN         = CollisionNode('heightChecker')       
     self.pickerNode     = render.attachNewNode(pickerCollN) 
     pickerCollN.setFromCollideMask(BitMask32.bit(1))         
     pickerCollN.setIntoCollideMask(BitMask32.allOff())         
     self.pickerRay      = CollisionRay(0,0,300,0,0,-1)                
     pickerCollN.addSolid(self.pickerRay)      
     self.picker.addCollider(self.pickerNode, self.pickerQ)
Esempio n. 26
0
 def setMousePicker(self):
     self.picker = CollisionTraverser()
     self.pq = CollisionHandlerQueue()
     self.pickerNode = CollisionNode('mouseRay')
     self.pickerNP = camera.attachNewNode(self.pickerNode)
     self.pickerNode.setFromCollideMask(BitMask32.bit(1))
     self.pickerRay = CollisionRay()
     self.pickerNode.addSolid(self.pickerRay)
     self.picker.addCollider(self.pickerNP, self.pq)
     self.selectable = render.attachNewNode("selectable")
Esempio n. 27
0
 def setupCollision(self):
     # create collision traverser
     self.picker = CollisionTraverser()
     # create collision handler
     self.pq = CollisionHandlerQueue()
     # create collision node
     self.pickerNode = CollisionNode('mouseRay')  # create collision node
     # attach new collision node to camera node
     self.pickerNP = camera.attachNewNode(
         self.pickerNode)  # attach collision node to camera
     # set bit mask to one
     self.pickerNode.setFromCollideMask(BitMask32.bit(1))  # set bit mask
     # create a collision ray
     self.pickerRay = CollisionRay()  # create collision ray
     # add picker ray to the picker node
     self.pickerNode.addSolid(
         self.pickerRay)  # add the collision ray to the collision node
     # make the traverser know about the picker node and its even handler queue
     self.picker.addCollider(
         self.pickerNP,
         self.pq)  # add the colision node path and collision handler queue
     #self.picker.showCollisions( render ) # render or draw the collisions
     #self.pickerNP.show( ) # render picker ray
     # create col node
     self.colPlane = CollisionNode('colPlane')
     # add solid to col node plane
     self.colPlane.addSolid(
         CollisionPlane(Plane(Vec3(0, 0, 1), Point3(0, 0, 0))))
     # attach new node to the render
     self.colPlanePath = render.attachNewNode(self.colPlane)
     #self.colPlanePath.show( ) # render node
     # make the col plane look at the camera
     # this makes it alway look at the camera no matter the orientation
     # we need this because the ray nees to intersect a plane parallel
     # to the camera
     self.colPlanePath.lookAt(camera)
     # prop up the col plane
     self.colPlanePath.setP(-45)
     # set bit mask to one
     # as I understand it, this makes all col nodes with bit mask one
     # create collisions while ignoring others of other masks
     self.colPlanePath.node().setIntoCollideMask(BitMask32.bit(1))
Esempio n. 28
0
    def __init__(self, model, run, walk, startPos, scale):        
        """Initialise the character. 
        
        Arguments: 
        model -- The path to the character's model file (string) 
           run : The path to the model's run animation (string) 
           walk : The path to the model's walk animation (string) 
           startPos : Where in the world the character will begin (pos) 
           scale : The amount by which the size of the model will be scaled 
                   (float) 
                    
           """ 

        self.controlMap = {"left":0, "right":0, "up":0, "down":0} 

        self.actor = Actor(Config.MYDIR+model, 
                                 {"run":Config.MYDIR+run, 
                                  "walk":Config.MYDIR+walk})        
        self.actor.reparentTo(render) 
        self.actor.setScale(scale) 
        self.actor.setPos(startPos) 

        self.controller = Controller.LocalController(self)
        
        taskMgr.add(self.move,"moveTask") # Note: deriving classes DO NOT need 
                                          # to add their own move tasks to the 
                                          # task manager. If they override 
                                          # self.move, then their own self.move 
                                          # function will get called by the 
                                          # task manager (they must then 
                                          # explicitly call Character.move in 
                                          # that function if they want it). 
        self.prevtime = 0 
        self.isMoving = False 

        # 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.groundRay = CollisionRay() 
        self.groundRay.setOrigin(0,0,1000) 
        self.groundRay.setDirection(0,0,-1) 
        self.groundCol = CollisionNode('ralphRay') 
        self.groundCol.addSolid(self.groundRay) 
        self.groundCol.setFromCollideMask(BitMask32.bit(1)) 
        self.groundCol.setIntoCollideMask(BitMask32.allOff()) 
        self.groundColNp = self.actor.attachNewNode(self.groundCol)
        self.groundHandler = CollisionHandlerQueue() 
        self.cTrav.addCollider(self.groundColNp, self.groundHandler) 
Esempio n. 29
0
 def __init__(self):
     self.picker         = CollisionTraverser()            
     self.pickerQ        = CollisionHandlerQueue()         
     pickerCollN         = CollisionNode('mouseRay')       
     pickerCamN          = base.camera.attachNewNode(pickerCollN) 
     pickerCollN.setFromCollideMask(BitMask32.bit(1))         
     pickerCollN.setIntoCollideMask(BitMask32.allOff())         
     self.pickerRay      = CollisionRay()                
     pickerCollN.addSolid(self.pickerRay)      
     self.picker.addCollider(pickerCamN, self.pickerQ) 
     self.accept('mouse1',self.pick)                
Esempio n. 30
0
    def startGame(self):
        self.hideLogin()
        
        """Initialise the game environment and characters.""" 
        # Post some onscreen instructions. 

        title = addTitle("Nexus Demo") 
        # inst1 = addInstructions(0.95, "[ESC]: Quit") 
        # inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left") 
        # inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right") 
        # inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward") 
        # inst4 = addInstructions(0.75, "[Down Arrow]: Run Ralph Backward") 
        # inst6 = addInstructions(0.65, "[A]: Rotate Camera Left") 
        # inst7 = addInstructions(0.60, "[S]: Rotate Camera Right") 

        # Initialise the environment. 

        base.win.setClearColor(Vec4(0,0,0,1)) 
        environ = loader.loadModel(Config.MYDIR+"/models/world/world")      
        environ.reparentTo(render) 
        environ.setPos(0,0,0)    
        environ.setCollideMask(BitMask32.bit(1)) 

        # Create a character for the player. 

        player = Character("/models/ralph/ralph", 
                        "/models/ralph/ralph-run", 
                        "/models/ralph/ralph-walk", 
                        environ.find("**/start_point").getPos(), 
                        .2) 
                        
        # Hook up some control keys to the character 
        
        self.accept("arrow_left", player.setControl, ["left",1]) 
        self.accept("arrow_right", player.setControl, ["right",1]) 
        self.accept("arrow_up", player.setControl, ["up",1]) 
        self.accept("arrow_down", player.setControl, ["down",1]) 
        
        # Stop event handling if the keys are lifted up
        self.accept("arrow_left-up", player.setControl, ["left",0])
        self.accept("arrow_right-up", player.setControl, ["right",0]) 
        self.accept("arrow_up-up", player.setControl, ["up",0]) 
        self.accept("arrow_down-up", player.setControl, ["down",0])
         
        # Create a camera to follow the player. 

        camera = Camera(player.actor) 
    
        # Accept some keys to move the camera. 

        self.accept("a-up", camera.setControl, ["left",0]) 
        self.accept("s-up", camera.setControl, ["right",0]) 
        self.accept("a", camera.setControl, ["left",1]) 
        self.accept("s", camera.setControl, ["right",1]) 
Esempio n. 31
0
    def initialize_collision_handling(self):
        # A CollisionRay beginning above the camera and going down toward the
        # ground is used to detect camera collisions and the height of the
        # camera above the ground. A ray may hit the terrain, or it may hit a
        # rock or a tree.  If it hits the terrain, we detect the camera's
        # height.  If it hits anything else, the camera is in an illegal
        # position.

        self.collision_handling_mutex = Lock()

        self.cTrav = CollisionTraverser()
        self.groundRay = CollisionRay()
        self.groundRay.setOrigin(0,0,1000)
        self.groundRay.setDirection(0,0,-1)
        self.groundCol = CollisionNode('camRay')
        self.groundCol.setIntoCollideMask(BitMask32.bit(0))
        self.groundCol.setFromCollideMask(BitMask32.bit(0))
        self.groundCol.addSolid(self.groundRay)
        self.groundColNp = base.camera.attachNewNode(self.groundCol)
        self.groundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.groundColNp, self.groundHandler)
Esempio n. 32
0
 def draw(self, render_node):
     if self.texture != None :
         if self.model == None :
             self.model = loader.loadModel("eggs/cube.egg")
             self.model.setPos((self._x, self._y, self._z))
             self.model.setScale(self.size, self.size, self.size) 
         
         self.rendernode = render_node
         self.model.setTexture(textures[self.texture])
         self.model.reparentTo(render_node)
         self.model.setCollideMask(BitMask32.bit(1))
         self.model.setTag('cube',str(self._x) + ',' + str(self._y) + ',' + str(self._z))
Esempio n. 33
0
 def loadTerrain(self,hfFile):
     self.terrain.setHeightfield(Filename(hfFile))
     self.terrain.setBlockSize(32)
     self.terrain.setFactor(64)
     self.terrain.setMinLevel(2)
     self.terrain.getRoot().reparentTo(render)
     self.terrain.getRoot().setSz (30)
     self.terrain.generate()
     self.terrain.setFocalPoint(base.camera)
     gnodes=self.terrain.getRoot().findAllMatches("+GeomNode")
     for gnode in gnodes:
         gnode.node().setIntoCollideMask(BitMask32.bit(1))
Esempio n. 34
0
    def __init__(self,model):
        # 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)
Esempio n. 35
0
 def __init__(self, id, model, nodeName):
     
     nodeRegEx = "**/" + nodeName
     
     self.nodeName = nodeName
     self.nodePath = model.find(nodeRegEx)
     self.node = self.nodePath.node()
     
     self.node.setIntoCollideMask(BitMask32.bit(1))
     self.node.setTag('ID', id)
     self.node.setTag('nodeId', nodeName)
     
     self.lighting = None
Esempio n. 36
0
File: Box.py Progetto: sambarza/bo
 def __init__(self, ywn):
     '''
     Constructor
     '''
     Thing.__init__(self, "Box", ywn)
     
     self.model = loader.loadModel('models/untitled2')
     
     self.model.find("**/Cube").node().setIntoCollideMask(BitMask32.bit(1))
     self.model.find("**/Cube").node().setTag('ID', self.Id)
     self.model.find("**/Cube").node().setTag('nodeId', "cube")
     
     self.model.setTag('ID', self.Id)
Esempio n. 37
0
    def startGame(self):
        self.hideLogin()
        """Initialise the game environment and characters."""
        # Post some onscreen instructions.

        title = addTitle("Nexus Demo")
        # inst1 = addInstructions(0.95, "[ESC]: Quit")
        # inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left")
        # inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right")
        # inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward")
        # inst4 = addInstructions(0.75, "[Down Arrow]: Run Ralph Backward")
        # inst6 = addInstructions(0.65, "[A]: Rotate Camera Left")
        # inst7 = addInstructions(0.60, "[S]: Rotate Camera Right")

        # Initialise the environment.

        base.win.setClearColor(Vec4(0, 0, 0, 1))
        environ = loader.loadModel(Config.MYDIR + "/models/world/world")
        environ.reparentTo(render)
        environ.setPos(0, 0, 0)
        environ.setCollideMask(BitMask32.bit(1))

        # Create a character for the player.

        player = Character("/models/ralph/ralph", "/models/ralph/ralph-run",
                           "/models/ralph/ralph-walk",
                           environ.find("**/start_point").getPos(), .2)

        # Hook up some control keys to the character

        self.accept("arrow_left", player.setControl, ["left", 1])
        self.accept("arrow_right", player.setControl, ["right", 1])
        self.accept("arrow_up", player.setControl, ["up", 1])
        self.accept("arrow_down", player.setControl, ["down", 1])

        # Stop event handling if the keys are lifted up
        self.accept("arrow_left-up", player.setControl, ["left", 0])
        self.accept("arrow_right-up", player.setControl, ["right", 0])
        self.accept("arrow_up-up", player.setControl, ["up", 0])
        self.accept("arrow_down-up", player.setControl, ["down", 0])

        # Create a camera to follow the player.

        camera = Camera(player.actor)

        # Accept some keys to move the camera.

        self.accept("a-up", camera.setControl, ["left", 0])
        self.accept("s-up", camera.setControl, ["right", 0])
        self.accept("a", camera.setControl, ["left", 1])
        self.accept("s", camera.setControl, ["right", 1])
Esempio n. 38
0
 def __init__(self,rootNode,trav,id):
     self.GroundRay=CollisionRay(0,0,10,0,0,-1)
     self.GroundCol = CollisionNode('colDown_'+str(id))
     self.GroundCol.addSolid(self.GroundRay)
     self.GroundCol.setFromCollideMask(BitMask32.bit(1))
     self.GroundCol.setIntoCollideMask(BitMask32.allOff())
     self.GroundColNp = rootNode.attachNewNode(self.GroundCol)
     #self.GroundColNp.show()
     self.GroundHandler = CollisionHandlerQueue()
     trav.addCollider(self.GroundColNp, self.GroundHandler)
     
     self.EnvDetector=CollisionSphere(0, 0, 1, 0.8)
     self.EnvCol = CollisionNode('colEnv_'+str(id))
     self.EnvCol.addSolid(self.EnvDetector)
     self.EnvCol.setFromCollideMask(BitMask32.bit(2))
     self.EnvCol.setIntoCollideMask(BitMask32.allOff())
     self.EnvColNp = rootNode.attachNewNode(self.EnvCol)
     #self.EnvColNp.show()
     self.pusher = CollisionHandlerPusher()
     self.pusher.addCollider(self.EnvColNp, rootNode)
     trav.addCollider(self.EnvColNp, self.pusher)
         
     self.trav=trav
Esempio n. 39
0
    def __init__(self,actor): 
        """Initialise the camera, setting it to follow 'actor'. 
        
        Arguments: 
        actor -- The Actor that the camera will initially follow. 
        
        """ 
        
        self.actor = actor 
        self.prevtime = 0 

        # The camera's controls: 
        # "left" = move the camera left, 0 = off, 1 = on 
        # "right" = move the camera right, 0 = off, 1 = on 
        self.controlMap = {"left":0, "right":0} 

        taskMgr.add(self.move,"cameraMoveTask") 

        # Create a "floater" object. It is used to orient the camera above the 
        # target actor's head. 
        
        self.floater = NodePath(PandaNode("floater")) 
        self.floater.reparentTo(render)        

        # Set up the camera. 

        base.disableMouse() 
        base.camera.setPos(self.actor.getX(),self.actor.getY()+2, 2)
        # uncomment for topdown
        #base.camera.setPos(self.actor.getX(),self.actor.getY()+10,2) 
        #base.camera.setHpr(180, -50, 0)
        
        # A CollisionRay beginning above the camera and going down toward the 
        # ground is used to detect camera collisions and the height of the 
        # camera above the ground. A ray may hit the terrain, or it may hit a 
        # rock or a tree.  If it hits the terrain, we detect the camera's 
        # height.  If it hits anything else, the camera is in an illegal 
        # position. 

        self.cTrav = CollisionTraverser() 
        self.groundRay = CollisionRay() 
        self.groundRay.setOrigin(0,0,1000) 
        self.groundRay.setDirection(0,0,-1) 
        self.groundCol = CollisionNode('camRay') 
        self.groundCol.addSolid(self.groundRay) 
        self.groundCol.setFromCollideMask(BitMask32.bit(1)) 
        self.groundCol.setIntoCollideMask(BitMask32.allOff()) 
        self.groundColNp = base.camera.attachNewNode(self.groundCol) 
        self.groundHandler = CollisionHandlerQueue() 
        self.cTrav.addCollider(self.groundColNp, self.groundHandler) 
Esempio n. 40
0
    def __init__(self, actor):
        """Initialise the camera, setting it to follow 'actor'. 
        
        Arguments: 
        actor -- The Actor that the camera will initially follow. 
        
        """

        self.actor = actor
        self.prevtime = 0

        # The camera's controls:
        # "left" = move the camera left, 0 = off, 1 = on
        # "right" = move the camera right, 0 = off, 1 = on
        self.controlMap = {"left": 0, "right": 0}

        taskMgr.add(self.move, "cameraMoveTask")

        # Create a "floater" object. It is used to orient the camera above the
        # target actor's head.

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        # Set up the camera.

        base.disableMouse()
        base.camera.setPos(self.actor.getX(), self.actor.getY() + 2, 2)
        # uncomment for topdown
        #base.camera.setPos(self.actor.getX(),self.actor.getY()+10,2)
        #base.camera.setHpr(180, -50, 0)

        # A CollisionRay beginning above the camera and going down toward the
        # ground is used to detect camera collisions and the height of the
        # camera above the ground. A ray may hit the terrain, or it may hit a
        # rock or a tree.  If it hits the terrain, we detect the camera's
        # height.  If it hits anything else, the camera is in an illegal
        # position.

        self.cTrav = CollisionTraverser()
        self.groundRay = CollisionRay()
        self.groundRay.setOrigin(0, 0, 1000)
        self.groundRay.setDirection(0, 0, -1)
        self.groundCol = CollisionNode('camRay')
        self.groundCol.addSolid(self.groundRay)
        self.groundCol.setFromCollideMask(BitMask32.bit(1))
        self.groundCol.setIntoCollideMask(BitMask32.allOff())
        self.groundColNp = base.camera.attachNewNode(self.groundCol)
        self.groundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.groundColNp, self.groundHandler)
Esempio n. 41
0
    def __init__(self):

        self.keys = {}
        for char in string.ascii_lowercase:
            self.keys[char] = BUTTON_UP

            def makeKeyPair(ch):
                def keyUp():
                    self.keys[ch] = BUTTON_DOWN
                    #print "%s UP" % (ch)
                def keyDown():
                    self.keys[ch] = BUTTON_UP
                    #print "%s DOWN" % (ch)

                return [keyUp, keyDown]

            keyPair = makeKeyPair(char)
            self.accept(char, keyPair[0])
            self.accept(char + '-up', keyPair[1])

        self.accept('mouse1', self.leftClick)
        self.accept('mouse1-up', self.leftClickUp)
        self.accept('mouse2', self.mClick)
        self.accept('mouse2-up', self.mClickUp)
        self.accept('mouse3', self.rightClick)
        self.accept('mouse3-up', self.rightClickUp)

        self.mouse1Down = False
        self.mouse2Down = False
        self.mouse3Down = False
        self.trackMouseTimeOld = 0
        self.trackMouseX = 0
        self.trackMouseY = 0
        self.trackMouse_Mouse1DownOld = False
        self.trackMouse_Mouse2DownOld = False
        self.trackMouse_Mouse3DownOld = False
        taskMgr.add(self.trackMouseTask, 'trackMouseTask')

        #
        base.cTrav = CollisionTraverser()
        self.pickerQ = CollisionHandlerQueue()
        self.pickerCollN = CollisionNode('mouseRay')
        self.pickerCamN = base.camera.attachNewNode(self.pickerCollN)
        self.pickerCollN.setFromCollideMask(BitMask32.bit(1))
        self.pickerRay = CollisionRay()
        self.pickerCollN.addSolid(self.pickerRay)
        base.cTrav.addCollider(self.pickerCamN, self.pickerQ)

        self.objectUnderCursor = None
Esempio n. 42
0
    def createBallColliderModel(self):
        #creates the collider sphere around the ball
        cSphereRad = 9.9
        self.cTrav = CollisionTraverser() #moves over all possible collisions

        self.ballModelSphere = CollisionSphere(0, 0, 0, cSphereRad)
            #collision mesh around ball is a simple sphere
        self.ballModelCol = CollisionNode('ballModelSphere')
        self.ballModelCol.addSolid(self.ballModelSphere)
        self.ballModelCol.setFromCollideMask(BitMask32.bit(0))
        self.ballModelCol.setIntoCollideMask(BitMask32.allOff())
        self.ballModelColNp = self.ballModel.attachNewNode(self.ballModelCol)
        self.ballModelGroundHandler = CollisionHandlerQueue()
            #collision handler queue stores all collision points
        self.cTrav.addCollider(self.ballModelColNp, self.ballModelGroundHandler)
Esempio n. 43
0
    def createCollisionHandlers(self):
        # Create a new collision traverser instance. We will use this to determine
        # if any collisions occurred after performing movement.
        self.cTrav = CollisionTraverser()

        camGroundRay = CollisionRay()
        camGroundRay.setOrigin(0, 0, 1000)
        camGroundRay.setDirection(0, 0, -1)
        camGroundCol = CollisionNode('camRay')
        camGroundCol.addSolid(camGroundRay)
        camGroundCol.setFromCollideMask(BitMask32.bit(0))
        camGroundCol.setIntoCollideMask(BitMask32.allOff())
        camGroundColNp = base.camera.attachNewNode(camGroundCol)
        self.camGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(camGroundColNp, self.camGroundHandler)

        # register the collision pusher
        self.pusher = CollisionHandlerPusher()

        # register collision event pattern names
        self.pusher.addInPattern('col-%fn-into')
 def __setupTarget(self):
     modelStanding = "models/ralph"
     modelRunning = "models/ralph-run"
     modelWalking = "models/ralph-walk"
     self.__mainTarget = NPC(modelStanding, {
         "run": modelRunning,
         "walk": modelWalking
     },
                             turnRate=150,
                             speed=0,
                             agentList=self.__globalAgentList,
                             collisionMask=BitMask32.bit(1),
                             name="target",
                             massKg=35.0,
                             collisionHandler=self.physicsCollisionHandler,
                             collisionTraverser=self.cTrav)
     # Make it visible
     self.__mainTarget.reparentTo(render)
     self.__mainTarget.setPos(-20, -10, 0)  #-210
     self.gate.find("**/Cube;+h").setCollideMask(
         ~self.__mainTarget.collisionMask)
Esempio n. 45
0
 def __setupMainAgent(self):
     modelStanding = "models/ralph"
     modelRunning = "models/ralph-run"
     modelWalking = "models/ralph-walk"
     self.__mainAgent = Player(
         modelStanding, {
             "run": modelRunning,
             "walk": modelWalking
         },
         turnRate=150,
         speed=25,
         agentList=self.__globalAgentList,
         collisionMask=BitMask32.bit(1),
         name="ralph",
         massKg=35.0,
         collisionHandler=self.physicsCollisionHandler,
         collisionTraverser=self.cTrav)
     # Make it visible
     self.__mainAgent.reparentTo(render)
     self.__mainAgent.setPos(31, 35, 50)
     self.gate.find("**/Cube;+h").setCollideMask(
         ~self.__mainAgent.collisionMask)
Esempio n. 46
0
    def loadWallModel(self):
        #loads the wall model (the maze) 
        wallScale = 0.3
        wallModelName = self.randomWallModel()
            #randomly select a maze

        self.wallModel = loader.loadModel(wallModelName)
        self.wallModel.setScale(wallScale)
        self.wallModel.setPos(0, 0, 0)
        self.wallModel.setCollideMask(BitMask32.allOff())
        self.wallModel.reparentTo(render)

        ### Setting Texture ###
        texScale = 0.08
        self.wallModel.setTexGen(TextureStage.getDefault(),
                                   TexGenAttrib.MWorldNormal)
        self.wallModel.setTexProjector(TextureStage.getDefault(),
                                         render, self.wallModel)
        self.wallModel.setTexScale(TextureStage.getDefault(), texScale)
        tex = loader.load3DTexture('/Users/jianwei/Documents/School/Freshman/Semester1/15-112/TERMPROJECT/Project/wallTex/wallTex_#.png')
        self.wallModel.setTexture(tex)

        #creating visual geometry collision
        self.wallModel.setCollideMask(BitMask32.bit(0))
Esempio n. 47
0
    def __init__(self, name, world, pos):
        ActorNode.__init__(self, name)

        self.nodePath = NodePath(self)

        self.world = world

        # init the model or the Actor
        self.model = self.getModel()
        self.model.reparentTo(self.nodePath)

        self.nodePath.setPos(*pos)

        self.prevPos = self.nodePath.getPos()

        # collision detection
        fromObject = self.nodePath.attachNewNode(CollisionNode(name))
        self.addSolids(fromObject)
        fromObject.show()

        # setup the ground ray, needed for detecting the ground
        groundRay = CollisionRay()
        groundRay.setOrigin(0, 0, 1000)
        groundRay.setDirection(0, 0, -1)
        groundCol = CollisionNode('groundRay')
        groundCol.addSolid(groundRay)
        groundCol.setFromCollideMask(BitMask32.bit(0))
        groundCol.setIntoCollideMask(BitMask32.allOff())
        groundColNp = base.camera.attachNewNode(groundCol)
        self.groundHandler = CollisionHandlerQueue()
        self.world.cTrav.addCollider(groundColNp, self.groundHandler)

        #        self.world.cTrav.addCollider(fromObject, self.world.pusher)
        #        self.world.pusher.addCollider(fromObject, self.nodePath)

        self.postInit()
class GameObject:
    bitmaskAll = BitMask32.allOn()
    bitmaskDefault = BitMask32.bit(0)
    bitmaskBullet = BitMask32.bit(1)
    bitmaskCharacter = BitMask32.bit(2)
    bitmaskBox = BitMask32.bit(3)
    bitmaskTileGlued = BitMask32.bit(4)
    bitmaskTile = BitMask32.bit(5)

    def __init__(self, world):
        world.addObject(self)
        self.world = world
        self.body = None
        self.geom = None
        self.node = None

        self.active = True
        self.visibleAfterDestroy = False
        self.dissipateCountdown = 0

    def updatePosFromPhysics(self):
        if self.body != None:
            self.node.setPosQuat(render, self.body.getPosition(),
                                 Quat(self.body.getQuaternion()))

    def getMomentum(self):
        mass = self.body.getMass().getMagnitude()
        speed = self.body.getLinearVel().length()
        return mass * speed

    def dissipate(self, factor, interval=5):
        if self.body == None or self.dissipateCountdown > 0:
            return
        self.body.setLinearVel(self.body.getLinearVel() * factor)
        self.body.setAngularVel(self.body.getAngularVel() * factor)
        self.dissipateCountdown = interval + 1
        self.dissipateRecover()

    def dissipateRecover(self):
        self.dissipateCountdown -= 1
        if self.dissipateCountdown > 0:
            self.world.performAfterStep(self.dissipateRecover, [])

    def onCollision(self, otherBody, entry):
        pass

    def destroy(self):
        self.active = False
        self.world.removeObject(self)

    def doDestroy(self):
        if self.node != None and not self.visibleAfterDestroy:
            self.node.detachNode()
        if self.geom != None:
            self.geom.disable()
        if self.body != None:
            self.body.disable()
        return

        # This is the code that actually removes the elements instead of just disabling them.
        # But it doesn't work.
        obj = self
        print obj  #DEBUG
        print threading.current_thread()  #DEBUG
        print "0",  #DEBUG
        if obj.node != None:
            obj.node.detachNode()
            obj.node = None
        print "1",  #DEBUG
        if obj.geom != None:
            self.world.space.remove(obj.geom)  #Probably unnecessary
        print "2",  #DEBUG
        if obj.geom != None:
            obj.geom.destroy()
            obj.geom = None
        print "3",  #DEBUG
        if obj.body != None:
            obj.body.destroy()
            obj.body = None
        print "4"  #DEBUG
from pandac.PandaModules import BitMask32
NumVines = 20
GameDuration = 70
ShowScoresDuration = 4.0
VineStartingT = 0.25
VineFellDownT = 0.1
EndlessGame = False
BonusPerSecondLeft = 0.4
JumpTimeBuffer = 0.5
SpiderBitmask = ToontownGlobals.CatchGameBitmask
TreasureBitmask = ToontownGlobals.PieBitmask
VineXIncrement = 30
VineHeight = 30
BatMaxHeight = 28
BatMinHeight = 10
RadarCameraBitmask = BitMask32.bit(3)
CourseSections = (((20, 30, 4, 0), (19, 39, 3.1, 0), (18, 41, 4, 0),
                   (19, 38, 3.2, 0), (20, 30, 6, 0)),
                  ((20, 30, 3, 0), (18, 40, 4.1, 0), (19, 31, 5.1, 0),
                   (18, 41, 4.2, 0), (20, 30, 5, 0)),
                  ((20, 30, 3, 0), (15, 39, 4.1, 0), (19, 29, 5, 0),
                   (16, 38, 4.2, 0), (20, 30, 5, 0)),
                  ((20, 30, 3, 0), (18, 36, 4.1, 0), (19, 30, 5, 9),
                   (18, 38, 4.2, 0), (20, 30, 5, 0)),
                  ((20, 30, 3, 0), (18, 15, 4.1, 0), (19, 30, 5, 11), (18, 16,
                                                                       4.2, 0),
                   (20, 30, 5, 0)), ((20, 30, 3, 0), (18, 11, 4.1, 0),
                                     (15, 12, 5, 0), (18, 16, 4.2, 0), (20, 30,
                                                                        5, 0)),
                  ((20, 30, 3, 0), (15, 39, 4.1, 13), (19, 29, 5, 0), (16, 38,
                                                                       4.2, 0),
Esempio n. 50
0
#** Collision system ignition
base.cTrav = CollisionTraverser()

#** This is the known collision handler we use for floor collisions. We'll keep going with the usual settings here as well.
avatarFloorHandler = CollisionHandlerGravity()
avatarFloorHandler.setGravity(9.81 + 25)
avatarFloorHandler.setMaxVelocity(100)

#** the walls collider
wallHandler = CollisionHandlerPusher()

#** we'll use this to 'sense' the fallout impact velocity and also to 'read' various triggers we've put around the map for several purposes.
collisionEvent = CollisionHandlerEvent()

#** Collision masks - this time there is a new one: the TRIGGER_MASK is used to detect certain collision geometry to act as a trigger, therefore we need to distinguish'em from floor and walls.
FLOOR_MASK = BitMask32.bit(1)
WALL_MASK = BitMask32.bit(2)
TRIGGER_MASK = BitMask32.bit(3)

#** Our steering avatar
avatarNP = base.render.attachNewNode(ActorNode('yolkyNP'))
avatarNP.reparentTo(base.render)
# by the way: this time we wont use the same old smiley but a 2d guy for this snippet purposes only - it is just a plane with a texture glued on, a so 2d object then.
avatar = loader.loadModel('yolky')
avatar.reparentTo(avatarNP)
# why this? this is to have our flat puppet rendered always on top of all objects in the scene, either 2d and 3d.
avatar.setDepthWrite(True, 100)
# the rest of the stuff is as usual...
avatar.setPos(0, 0, 1)
avatar.setCollideMask(BitMask32.allOff())
avatarNP.setPos(0, 0, 15)
Esempio n. 51
0
# Main
"""
Here we settle up a simple scene with a wide terrain surface, where to compare 2 different floor colliders applied on it: the first is a whole single collision mesh with approx. 16.000 polygons and the other is the same former mesh but after being octreefied, using the octree script incorporated in the blender chicken exporter - have to know that the resulting model is not composed by a whole mesh anymore but rather by dozens of small mesh chunks that will relief the panda collision system for an extent you'll going to see by yourself with this snippet. The real deal with this tutorial is not much how to settle the collisions, explained in detail in former steps, but rather how to export your collision meshes with blender and how will change here the usual floor collision settings, because of the octreefication. I suggest you to check infos in oc3models.blend first and then return down here to continue.
"""
#=========================================================================

#** Collision system ignition
base.cTrav = CollisionTraverser()

#** The floor collision handler - all stuff explained in step3
avatarFloorHandler = CollisionHandlerGravity()
avatarFloorHandler.setGravity(9.81 + 25)
avatarFloorHandler.setMaxVelocity(100)

#** Collision masks
FLOOR_MASK = BitMask32.bit(1)
MASK_OFF = BitMask32.allOff()

#** Our steering avatar
avatarNP = base.render.attachNewNode(ActorNode('smileyNP'))
avatarNP.reparentTo(base.render)
avatar = loader.loadModel('smiley')
avatar.reparentTo(avatarNP)
avatar.setPos(0, 0, 1)
avatar.setCollideMask(MASK_OFF)
avatarNP.setPos(0, 0, 15)

#** Stick and set the ray collider to the avatar
raygeometry = CollisionRay(0, 0, 2, 0, 0, -1)
avatarRay = avatarNP.attachNewNode(CollisionNode('avatarRay'))
avatarRay.node().addSolid(raygeometry)
Esempio n. 52
0
    def __init__(self, manager, xml):
        self.updateTask = None

        self.sun = base.cam.attachNewNode('sun')
        loader.loadModel(
            manager.get('paths').getConfig().find('misc').get('path') +
            '/sphere').reparentTo(self.sun)
        self.sun.setScale(0.1)
        self.sun.setTwoSided(True)
        self.sun.setColorScale(10.0, 10.0, 10.0, 1.0, 10001)
        self.sun.setLightOff(1)
        self.sun.setShaderOff(1)
        self.sun.setFogOff(1)
        self.sun.setCompass()
        self.sun.setBin('background', 10)
        self.sun.setDepthWrite(False)
        self.sun.setDepthTest(False)
        # Workaround an annoyance in Panda. No idea why it's needed.
        self.sun.node().setBounds(OmniBoundingVolume())
        isa = xml.find('isa')
        inst = xml.find('instance')
        if isa != None or inst != None:
            if inst != None:
                orig = Vec3(float(inst.get('x',
                                           '0')), float(inst.get('y', '0')),
                            float(inst.get('z', '0')))
            else:
                level = manager.get(isa.get('source'))
                orig = Vec3(level.getByIsA(isa.get('name'))[0].getPos(render))
            orig.normalize()
            self.sun.setPos(orig)

        godrays = xml.find('godrays')
        if godrays != None:
            self.vlbuffer = base.win.makeTextureBuffer('volumetric-lighting',
                                                       base.win.getXSize() / 2,
                                                       base.win.getYSize() / 2)
            self.vlbuffer.setClearColor(Vec4(0, 0, 0, 1))
            cam = base.makeCamera(self.vlbuffer)
            cam.node().setLens(base.camLens)
            cam.reparentTo(base.cam)
            initstatenode = NodePath('InitialState')
            initstatenode.setColorScale(0, 0, 0, 1, 10000)
            initstatenode.setShaderOff(10000)
            initstatenode.setLightOff(10000)
            initstatenode.setMaterialOff(10000)
            initstatenode.setTransparency(TransparencyAttrib.MBinary, 10000)
            cam.node().setCameraMask(BitMask32.bit(2))
            cam.node().setInitialState(initstatenode.getState())
            self.vltexture = self.vlbuffer.getTexture()
            self.vltexture.setWrapU(Texture.WMClamp)
            self.vltexture.setWrapV(Texture.WMClamp)
            card = CardMaker('VolumetricLightingCard')
            card.setFrameFullscreenQuad()
            self.finalQuad = render2d.attachNewNode(card.generate())
            self.finalQuad.setAttrib(
                ColorBlendAttrib.make(ColorBlendAttrib.MAdd,
                                      ColorBlendAttrib.OIncomingColor,
                                      ColorBlendAttrib.OFbufferColor))

            self.finalQuad.setShader(
                Shader.load(
                    posixpath.join(
                        manager.get('paths').getConfig().find('shaders').get(
                            'path'), 'filter-vlight.cg')))
            self.finalQuad.setShaderInput('src', self.vltexture)
            self.finalQuad.setShaderInput(
                'vlparams', 32, 0.9 / 32.0, 0.97, 0.5
            )  # Note - first 32 is now hardcoded into shader for cards that don't support variable sized loops.
            self.finalQuad.setShaderInput('casterpos', 0.5, 0.5, 0, 0)
            # Last parameter to vlcolor is the exposure
            vlcolor = Vec4(float(godrays.get('r', '1')),
                           float(godrays.get('g', '1')),
                           float(godrays.get('b', '1')), 0.04)

            self.finalQuad.setShaderInput('vlcolor', vlcolor)
        else:
            self.finalQuad = None
Esempio n. 53
0
# Main
"""
Starting from step1, we just put an additional collision handler to take care to keep the avatar grounded. This will PUSH the avatar back as soon as hit geometry we settled to be a wall: in blender we modelled polygons to wrap around the little house and all around the terrain area so that this time the avatar, differently from step1, won't pass through the house and won't be able to leave the terrain perimeter anymore. I suggest you to open the blender source to find out what I'm talking about here.
"""
#=========================================================================

#** Collision system ignition
base.cTrav = CollisionTraverser()
# did you saw this stuff in step1?
floorHandler = CollisionHandlerFloor()
floorHandler.setMaxVelocity(14)
# here it is the new fella - this will take care to push the avatar off the walls
wallHandler = CollisionHandlerPusher()

#** As you know this mask is used to mark the geometries for the floor collisions...
FLOOR_MASK = BitMask32.bit(1)
#... and this time we need another one to mark the walls as well.
WALL_MASK = BitMask32.bit(2)

#** This is our steering avatar - this time we use a little different setup, more close to real applications: we wrap either the avatar and its collision ray into another nodepath. This way we add lotta flexibility allowing us to make fancy things like you'll see below, to make the avatar rolling while steering, a thing not possible before and also to get rid of the global floorHandler.setOffset(1.0) shift, to set our avatar precisly placed above the surface.
avatarNP = NodePath('smileyNP')
avatarNP.reparentTo(base.render)
avatar = loader.loadModel('smiley')
avatar.reparentTo(avatarNP)
# since our avatar origin is centered in a model sized 2,2,2, we need to shift it 1 unit above the ground and this time we make this happen shifting it off its own root node (avatarNP)
avatar.setPos(0, 0, 1)
avatar.setCollideMask(BitMask32.allOff())
avatarNP.setPos(0, 0, 15)
# we reintroduced in this snippet the renowned smiley collision sphere - we need it as low-poly collision geometry for the wall collision handler to know when the smiley hit a wall.
avatarCollider = avatar.attachNewNode(CollisionNode('smileycnode'))
avatarCollider.node().addSolid(CollisionSphere(0, 0, 0, 1))
Esempio n. 54
0
    'arrow_left', 'arrow_right', 'arrow_up', 'arrow_down', 'w', 'a', 's', 'd'
]

# Speed at which avatar controls work.
TurnPerSecond = 200
ForwardPerSecond = 25
BackwardPerSecond = 10

# Controlling the camera chasing.
MaxCameraDistance = 5
CameraPerSecond = 20

# Controlling camera-mouse mode.
CameraPerPixel = 0.1

WallBit = BitMask32.bit(0)
FloorBit = BitMask32.bit(1)
AvatarBit = BitMask32.bit(2)
SelfBit = BitMask32.bit(3)
WingsBit = BitMask32.bit(4)

CamMask = BitMask32.bit(0)
AvBufMask = BitMask32.bit(1)

South = 1
East = 2
North = 4
West = 8
Floor = 16
Ceiling = 32
AllDirs = South | East | North | West
Esempio n. 55
0
    def __init__(self):
        base.disableMouse()
        base.camLens.setFar(100)
        self.parserClass = Parser.Parser()  # Making the required instances
        self.mapLoaderClass = mapLoader.mapLoader(self)

        self.gameObjects = {}
        self.gameObjectID = 0

        self.mapX = self.mapLoaderClass.mapConfigParser.getint(
            "map", "width") - 1  # Name says it all really
        self.mapY = self.mapLoaderClass.mapConfigParser.getint(
            "map", "height") - 1

        self.modelLoaderClass = modelLoader.modelLoader(self)

        self.cameraClass = stratCam.CameraHandler(self)
        self.mouseClass = stratCam.mouseHandler(self)
        self.GUI = stratCam.GUI(self)
        #	self.GUI = stratCam.GUI(self)
        self.priorities = priorities.priorities()

        base.setFrameRateMeter(True)

        ###############
        base.cTrav2 = CollisionTraverser('world2')
        #	base.cTrav2.showCollisions(render)

        self.heightRay = CollisionRay(
        )  # A collision ray, used for getting the height of the terrain
        self.heightRay.setOrigin(0, 0, 100)
        self.heightRay.setDirection(0, 0, -1)

        self.heightCol = CollisionNode('unit Ray')
        self.heightCol.addSolid(self.heightRay)
        self.heightCol.setTag('units', 'ray1')

        self.heightCol.setFromCollideMask(BitMask32.bit(0))
        #	self.heightCol.setIntoCollideMask(BitMask32.allOff())
        self.heightColNp = render.attachNewNode(self.heightCol)
        self.heightColNp.setPos(2, 2, 0)
        self.heightHandler = CollisionHandlerQueue()

        base.cTrav2.addCollider(self.heightColNp, self.heightHandler)
        ###############

        #	myFrame = DirectFrame(frameColor=(0, 0, 0, 1),
        #					frameSize=(-0.25, 0.25, -1, 1),
        #					pos=(1.08, 0, 0))
        #	button = DirectButton(text = ("button"), scale = 0.1)
        #	button.reparentTo(myFrame)
        #	button.setPos(0, 0, 0.9)

        self.grids = astar.grid(self)

        self.unitHandler = unitHandler.world(self)
        #	self.unitHandler.addUnit(0, (10,10,5), self)
        #	self.unitHandler.addUnit(1, (6,10,5), self)
        #	self.unitHandler.moveTo(self, (6, 34), 0)
        #	self.unitHandler.moveTo(self, (34, 30), 1)

        self.buildingHandler = buildingHandler.buildingHandler(self)

        self.tileSelected = (0, 0)

        taskMgr.add(self.tskCheckWalls, "Wall checking")
        taskMgr.add(self.priorities.jobTask, "Jobs", extraArgs=[self])

        self.loadLight()

        self.accept("escape", sys.exit)
        self.accept("1", self.unitHandler.addUnit2, extraArgs=[0, self])
        self.accept("2", self.unitHandler.addUnit2, extraArgs=[1, self])
        self.accept("3", self.unitHandler.addUnit2, extraArgs=[2, self])

        self.accept("enter",
                    self.buildingHandler.addBuilding2,
                    extraArgs=[self, 0])

        self.accept("p", self.priorities.addJob)

        print 'END OF GAMEMAIN.PY!'
Esempio n. 56
0
)
snipstuff.info_show()

#=========================================================================
# Main
"""
To biefly sum up what will happen below,we create 4 interacting objects: 2 FROM objects (heart shaped) and 2 INTO objects (ball shaped), the FROM will generate a collision event as soon as touch the INTO object with the same mask. As we did before, we'll use the CollisionHandlerQueue collision handler to orchestrate the collision operations.
"""
#=========================================================================

#** let's ignite the collision system as usual and declare the main handler - the important role of these two should already be clear to you, see step1.py if not
base.cTrav = CollisionTraverser()
collisionHandler = CollisionHandlerQueue()

#** First off we define here the collision masks - a mask is a special kind of integer that goes into range 0-32 that we'll use to discriminate from one object to another, like a cattle mark, therefore the number of masks we could define is 33 - we'll need just 2 so it is more than enough.
LOVE_MASK = BitMask32.bit(1)
BROKEN_LOVE_MASK = BitMask32.bit(2)

#** We'll load now the heart trigger - I don't go down into details you may find in step1.py
heartModel = loader.loadModel('heart')
# we exclude the heart geometry from all collisions so that it won't interfere with our following setups
heartModel.setCollideMask(BitMask32.allOff())
heartModel.reparentTo(render)
heartModel.setPos(0, 25, -2)
# this just make the heart move
heartModel.reparentTo(base.camera)
# as we know now here we get the collider reference off the heart model tree...
heartCollider = heartModel.find("**/collider_heart")
# ...but this time we'll assign it also a mask, to distinguish from the upcoming other heart  we'll define later
heartCollider.node().setFromCollideMask(LOVE_MASK)
# and now we're ready to add it to the collision system as usual
Esempio n. 57
0
    def __init__(self):
        """Initialise the singleton zcanvas instance: setup the viewport node,
        the collision rays for mouse picking, and start the task method used
        for mouse picking, and other initialisation details.

        """
        # This is the node that is transformed to implement viewport panning and
        # zooming.
        self.viewport = aspect2d.attachNewNode('zcanvas')

        # This is the node that user classes attach nodepaths to if they want
        # them to be on the zoom plane.
        self.home = self.viewport.attachNewNode('home')
        #self.home.showTightBounds()
                
        # This interval is used when the viewport is automatically transformed
        # to focus on a given nodepath, and also when the viewport is zoomed in
        # or out manually.
        self._zoomInterval = None

        # The time (in seconds) that it takes to move the viewport from the 
        # minimum to the maximum position on the Y axis when manually zooming.
        # (Controls the speed when manually zooming the viewport.)
        self.zoom_time = 2
        
        # Minimum and maximum positions for the viewport when manually moving on
        # the Y axis. FIXME: remove these arbitrary limits?
        self.max_zoom = 4.0
        self.min_zoom = .1
        
        # Interval used to manually pan the viewport left and right, and its
        # speed and minimum and maximum positions.
        self.pan_x_interval = None
        self.pan_x_time = 2
        self.max_pan_x = 1.33
        self.min_pan_x = -1.33

        # Interval used to manually pan the viewport up and down, and its
        # speed and minimum and maximum positions.
        self.pan_z_interval = None
        self.pan_z_time = 2
        self.max_pan_z = 1.0
        self.min_pan_z = -1.0 

        # The zcanvas' collision ray, collision mask, etc. used for mouse
        # picking.
        cn = CollisionNode('zoom collision ray')
        cn.addSolid(CollisionRay(0,-100,0, 0,1,0))
        from pandac.PandaModules import BitMask32
        self.mask = BitMask32.bit(0)
        cn.setFromCollideMask(self.mask)
        cn.setIntoCollideMask(BitMask32.allOff())
        self._cnp = aspect2d.attachNewNode(cn)
        self._ctrav=CollisionTraverser()
        self._queue = CollisionHandlerQueue()
        self._ctrav.addCollider(self._cnp, self._queue)
        # For debugging only.
        # self._ctrav.showCollisions(self.viewport)

        # Attributes that record which zoomable, draggable and highlightable
        # (if any) the mouse pointer is currently over.
        self._zoomMouseOver = None
        self._dragMouseOver = None
        self._highlightMouseOver = None

        # The draggable (if any) that is currently being dragged.
        self._draggee = None

        # Task method that does the mouse picking.
        taskMgr.add(self._mouseOverTask,'_mouseOverTask')

        # The currently focused node. A managed property.
        self.__focus = None

        # Catch the 'zoom done' message from panda's messenger system and echo
        # it to my custom messager system. (Because we use
        # interval.setDoneEvent to send the 'zoom done' message it must
        # initially be sent through panda's messenger).
        base.accept('zoom done',messager.send,['zoom done'])
Esempio n. 58
0
SKIP_NONE = 0
SKIP_HIDDEN = 1
SKIP_BACKFACE = 2
SKIP_CAMERA = 4
SKIP_UNPICKABLE = 8
SKIP_WIDGET = 16
SKIP_ALL = SKIP_HIDDEN | SKIP_BACKFACE | SKIP_CAMERA | SKIP_UNPICKABLE | SKIP_WIDGET

# bit flags for indicating how editable an object is
EDIT_TYPE_UNMOVABLE = 1
EDIT_TYPE_UNSCALABLE = 2
EDIT_TYPE_UNROTATABLE = 4
EDIT_TYPE_UNEDITABLE = EDIT_TYPE_UNMOVABLE | EDIT_TYPE_UNSCALABLE | EDIT_TYPE_UNROTATABLE

# [gjeon] stuffs for new LE multi camera support
LE_TOP_CAM_MASK = BitMask32.bit(0)
LE_FRONT_CAM_MASK = BitMask32.bit(1)
LE_LEFT_CAM_MASK = BitMask32.bit(2)
LE_PERSP_CAM_MASK = BitMask32.bit(3)

LE_CAM_MASKS = {
    'persp': LE_PERSP_CAM_MASK,
    'left': LE_LEFT_CAM_MASK,
    'front': LE_FRONT_CAM_MASK,
    'top': LE_TOP_CAM_MASK
}


def LE_showInAllCam(nodePath):
    for camName in LE_CAM_MASKS.keys():
        nodePath.show(LE_CAM_MASKS[camName])
    def __init__(self, filters):
        self.filters = filters
        self.updateTask = None
        self.finalQuad = None

        self.sun = base.cam.attachNewNode('sun')
        loader.loadModel("models/sphere").reparentTo(self.sun)
        self.sun.setScale(0.08)
        self.sun.setTwoSided(True)
        self.sun.setColorScale(1.0, 1.0, 1.0, 1.0, 10001)
        self.sun.setLightOff(1)
        self.sun.setShaderOff(1)
        self.sun.setFogOff(1)
        self.sun.setCompass()
        self.sun.setBin('background', 2)
        self.sun.setDepthWrite(False)
        self.sun.setDepthTest(False)
        # Workaround an annoyance in Panda. No idea why it's needed.
        self.sun.node().setBounds(OmniBoundingVolume())     

        direct = Vec4(2.0, 1.9, 1.8, 1) #bright for hdr
        #direct = Vec4(0.7, 0.65, 0.6, 1)
        self.dlight = DirectionalLight('dlight')
        self.dlight.setColor(direct)
        dlnp = self.sun.attachNewNode(self.dlight)
        render.setLight(dlnp)
        render.setShaderInput('dlight0', dlnp)

        self.setTime(700.0)

        pandaVolumetricLighting = False


        if pandaVolumetricLighting:
            self.filters.setVolumetricLighting( dlnp )
        else:
            self.vlbuffer = base.win.makeTextureBuffer('volumetric-lighting', base.win.getXSize() / 2, base.win.getYSize() / 2)
            self.vlbuffer.setClearColor(Vec4(0, 0, 0, 1))
            cam = base.makeCamera(self.vlbuffer)
            cam.node().setLens(base.camLens)
            cam.reparentTo(base.cam)
            initstatenode = NodePath('InitialState')
            initstatenode.setColorScale(0, 0, 0, 1, 10000)
            initstatenode.setShaderOff(10000)
            initstatenode.setFogOff(1)
            initstatenode.setLightOff(10000)
            initstatenode.setMaterialOff(10000)
            initstatenode.setTransparency(TransparencyAttrib.MBinary, 10000)
            cam.node().setCameraMask(BitMask32.bit(2))
            cam.node().setInitialState(initstatenode.getState())
            self.vltexture = self.vlbuffer.getTexture()
            self.vltexture.setWrapU(Texture.WMClamp)
            self.vltexture.setWrapV(Texture.WMClamp)
            card = CardMaker('VolumetricLightingCard')
            card.setFrameFullscreenQuad()
            self.finalQuad = render2d.attachNewNode(card.generate())
            self.finalQuad.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OIncomingColor, ColorBlendAttrib.OFbufferColor))
            self.finalQuad.setShader(Shader.load("shaders/filter-vlight.cg"))
            self.finalQuad.setShaderInput('src', self.vltexture)
            self.finalQuad.setShaderInput('vlparams', 32, 0.95 / 32.0, 0.985, 0.5) # Note - first 32 is now hardcoded into shader for cards that don't support variable sized loops.
            self.finalQuad.setShaderInput('casterpos', 0.5, 0.5, 0, 0)
            # Last parameter to vlcolor is the exposure
            vlcolor = Vec4(1, 0.99, 0.80, 0.03)
            self.finalQuad.setShaderInput('vlcolor', vlcolor)

        self.start()