Esempio n. 1
0
    def __init__(self, game):
        self.game = game
        
        #poista se fysiikka-avaruus ja vaan tee se alue... justiinsa
        self.collGeom = OdeBoxGeom( 24,8,2 )

        
        #self.collGeom.setBody(self.body)
        self.collGeom.setCategoryBits( BitMask32(1) )
        self.collGeom.setCollideBits( BitMask32(1) )
        

#        self.collGeomOuter = OdeBoxGeom( self.game.physicsSpace, 28,6,2)
#        #self.collGeom.setBody(self.body)
#        self.collGeomOuter.setCategoryBits( BitMask32(1) )
#        self.collGeomOuter.setCollideBits( BitMask32(1) )
        
        self.visualNode = NodePath('Visual node')
        self.visualNode.reparentTo(render)
        model = loader.loadModel('Base.egg')
        model.reparentTo(self.visualNode)
        
        plight = PointLight('baselight')
        plight.setPoint( Point3(0, 0, 12) )
        plight.setColor( Vec4(1,1,1,1) )
        plight.setAttenuation( Vec3(0.1, 0.1, 0.005) )
        self.visualNode.setLight(model.attachNewNode(plight))
Esempio n. 2
0
    def __init__(self, game, color):
        self.game = game
        
        
        self.visualNode = NodePath('Visual node')
        self.visualNode.reparentTo(render)
        model = loader.loadModel('testipalikka.egg')
        model.reparentTo(self.visualNode)

        plight = PointLight('plight')
        plight.setPoint( Point3(0.6, 0, 5) )
        plight.setColor( color )
        plight.setAttenuation( Vec3(0.5, 0.01, 0.01) )
        plightNodePath = model.attachNewNode(plight)
        model.setLight(plightNodePath)
        
        self.body = OdeBody(game.physicsWorld)
        self.mass = OdeMass()
        self.mass.setBox(10,1,1,1)
        self.body.setMass(self.mass)
        self.body.setGravityMode(False)
        #self.juttu = OdeUtil()
        
        self.collGeom = OdeSphereGeom( self.game.physicsSpace, 2)
        self.collGeom.setBody(self.body)
        self.collGeom.setCategoryBits( BitMask32(0xffffffff) )
        self.collGeom.setCollideBits( BitMask32(0xffffffff) )
Esempio n. 3
0
class Lighting:
  def __init__(self, ancestor = None):
    print "____________________________________________________"
    print "Class Lights"
    self.ancestor = ancestor

    #Initialize bg colour
    colour = (0.2, 0.2, 0.6)
    base.setBackgroundColor(*colour)
    base.camLens.setFar(1000.0)

    self.alight = AmbientLight('ambient_light')
    self.alight.setColor(Vec4(0.7, 0.7, 0.7, 1))
    self.alnp = base.render.attachNewNode(self.alight)
    base.render.setLight(self.alnp)

    self.plight = PointLight('sunlight')
    self.plight.setColor(Vec4(2.5, 2.5, 2.5, 1))
    self.plnp = base.render.attachNewNode(self.plight)
    self.plnp.setPos(50, 0, 300)
    self.plnp.lookAt(self.ancestor.terrain.root)
    base.render.setLight(self.plnp)

    # Initialize linear fog
    self.fog = Fog("Fog object")
    self.fog.setMode(Fog.MLinear)
    self.fog.setLinearRange(14.0,40.0)
    self.fog.setColor(*colour)
Esempio n. 4
0
    def __init__(self, game, color):
        #self.POWER = 100
        self.game = game
        
        self.thrust = False
        self.thrustLeft = False
        self.thrustRight = False
        self.thrustBack = False
        self.rotation = 0

        self.body = OdeBody(game.physicsWorld)
        self.mass = OdeMass()
        self.mass.setBox(10,1,1,1)
        self.body.setMass(self.mass)

        #odespheregeom(... , size of hitbox sphere)
        self.collGeom = OdeSphereGeom( self.game.physicsSpace, 5)
        self.collGeom.setBody(self.body)
        self.collGeom.setCategoryBits( BitMask32(0xffffffff) )
        self.collGeom.setCollideBits( BitMask32(0xffffffff) )
        
        self.visualNode = NodePath('Visual node')
        self.visualNode.reparentTo(render)
        model = loader.loadModel('lautanen2.egg')
        model.reparentTo(self.visualNode)
        
        plight = PointLight('plight')
        plight.setPoint( Point3(0.6, 0, 5) )
        plight.setColor( color )
        plight.setAttenuation( Vec3(0.5, 0.01, 0.01) )
        plightNodePath = model.attachNewNode(plight)
        model.setLight(plightNodePath)
Esempio n. 5
0
class PointLight:
    """Creates a simple point light"""
    def __init__(self, manager, xml):
        self.light = PPointLight('plight')
        self.lightNode = render.attachNewNode(self.light)

        self.reload(manager, xml)

    def reload(self, manager, xml):
        color = xml.find('color')
        if color != None:
            self.light.setColor(
                VBase4(float(color.get('r')), float(color.get('g')),
                       float(color.get('b')), 1.0))

        pos = xml.find('pos')
        if pos != None:
            self.lightNode.setPos(render, float(pos.get('x')),
                                  float(pos.get('y')), float(pos.get('z')))

    def start(self):
        render.setLight(self.lightNode)

    def stop(self):
        render.clearLight(self.lightNode)
Esempio n. 6
0
    def __init__(self, game, color, value = 1, drain = 20):
        self.game = game
        self.VALUE = value
        self.DRAIN = drain
        
        #self.idnumber = id
        self.visualNode = NodePath('Visual node')
        self.visualNode.reparentTo(render)
        model = loader.loadModel('Ball2.egg')
        model.setScale(2.5)
        model.reparentTo(self.visualNode)

        plight = PointLight('plight')
        plight.setPoint( Point3(0, 0, 3) )
        plight.setColor( color )
        plight.setAttenuation( Vec3(0.05, 0.01, 0.01) )
        self.plightNodePath = model.attachNewNode(plight)
        model.setLight(self.plightNodePath)

        self.body = OdeBody(game.physicsWorld)
        self.mass = OdeMass()
        self.mass.setBox(10,1,1,1)
        self.body.setMass(self.mass)

        self.body.setGravityMode(True)

        #self.body.setGravityMode(False)
        #self.juttu = OdeUtil()
        
        self.collGeom = OdeSphereGeom( self.game.physicsSpace, 3.5)
        self.collGeom.setBody(self.body)
        self.collGeom.setCategoryBits( BitMask32(0xffffffff) )
        self.collGeom.setCollideBits( BitMask32(0xffffffff) )
Esempio n. 7
0
 def setColor(self, color):
     plight = PointLight('plight')
     plight.setPoint( Point3(0.6, 0, 5) )
     plight.setColor( color )
     plight.setAttenuation( Vec3(0.5, 0.01, 0.01) )
     plightNodePath = self.model.attachNewNode(plight)
     self.model.setLight(plightNodePath)
	def addPointLight(self,	 pos):
		k = 12
		light = PointLight("light-point")
		light.setColor(VBase4(k, k, k, 1))
		light.setAttenuation(Point3(0.2, 0.1, 0.01))
		node = render.attachNewNode(light)
		node.setPos(*pos)
		render.setLight(node)
Esempio n. 9
0
 def setupLights(self):
     # create a point light
     plight = PointLight('plight')
     # set its color
     plight.setColor(VBase4(1.0, 1.0, 1.0, 1))
     # attach the light to the render
     plnp = render.attachNewNode(plight)
     # set position
     plnp.setPos(0.0, 0.0, 2.0)
     # turn on light
     render.setLight(plnp)
Esempio n. 10
0
 def setupLights( self ):
     # create a point light
     plight = PointLight( 'plight' )
     # set its color
     plight.setColor( VBase4( 1.0, 1.0, 1.0, 1 ) )
     # attach the light to the render
     plnp = render.attachNewNode( plight )
     # set position
     plnp.setPos( 0.0, 0.0, 2.0 )
     # turn on light
     render.setLight( plnp )
Esempio n. 11
0
 def inspect_planet(self, planet):
     plight = PointLight('plight')
     plight.setColor(Vec4(1,1,1,1))
     plnp = self.base.render.attachNewNode(plight)
     plnp.setPos(-50,-100,50)
     view = PlanetView(self.base, planet)
     view.set_light(plnp)
     self.base.camera.setPos(0, 0, -4)
     self.base.camera.lookAt(view.node)
     self.base.accept("enter", lambda: self.inspect(random.choice(planet.galaxy.planets)))
     self.slowly_rotate(view)
     self.view = view
Esempio n. 12
0
        def loadLights(self):
                plight = PointLight('plight')
                plight.setColor(VBase4(1, 1, 1, 1))
                self.plnp = render.attachNewNode(plight)
                self.plnp.setPos(0, 0, 0)
                render.setLight(self.plnp)

                self.ambientLight = AmbientLight( 'ambientLight' )
                self.ambientLight.setColor( Vec4( 0.1, 0.1, 0.1, 1 ) )
                
                self.ambientLightNP = render.attachNewNode( self.ambientLight.upcastToPandaNode() )
                render.setLight(self.ambientLightNP)
Esempio n. 13
0
 def inspect_planet(self, planet):
     plight = PointLight('plight')
     plight.setColor(Vec4(1, 1, 1, 1))
     plnp = self.base.render.attachNewNode(plight)
     plnp.setPos(-50, -100, 50)
     view = PlanetView(self.base, planet)
     view.set_light(plnp)
     self.base.camera.setPos(0, 0, -4)
     self.base.camera.lookAt(view.node)
     self.base.accept(
         "enter",
         lambda: self.inspect(random.choice(planet.galaxy.planets)))
     self.slowly_rotate(view)
     self.view = view
Esempio n. 14
0
    def _set_light_sources(self):
        light_positions = [(1, -1, 1), (-1, -5, 1)]
        intensity = 0.8
        for l_pos in light_positions:
            plight = PointLight('plight')
            plight.setColor(VBase4(intensity, intensity, intensity, 1))
            plnp = render.attachNewNode(plight)
            plnp.setPos(l_pos[0], l_pos[1], l_pos[2])
            render.setLight(plnp)
        light = AmbientLight('')
        light.setColor(VBase4(0.4, 0.4, 0.4, 1))
        light_np = render.attachNewNode(light)
        light_np.setPos(0, 0, 0)
        render.setLight(light_np)

        pass
Esempio n. 15
0
 def _set_light_sources(self):
     light_positions = [(1,-1,1),(-1,-5,1)]
     intensity = 0.8
     for l_pos in light_positions:
         plight = PointLight('plight')
         plight.setColor(VBase4(intensity, intensity, intensity, 1))
         plnp = render.attachNewNode(plight)
         plnp.setPos(l_pos[0], l_pos[1], l_pos[2])
         render.setLight(plnp)
     light = AmbientLight('')
     light.setColor(VBase4(0.4,0.4,0.4,1))
     light_np = render.attachNewNode(light)
     light_np.setPos(0,0,0)
     render.setLight(light_np)
     
     
     pass
Esempio n. 16
0
class Camera(DirectObject.DirectObject):
	def __init__(self):
		
		self.scrollingSpeed = 15
		base.disableMouse()
		camera.setP(-90)
		camera.setZ(15)
		self.accept('wheel_up',self.cameraZoomIn)
		self.accept('wheel_down',self.cameraZoomOut)
		taskMgr.add(self.cameraMovements,"cameraMovements")
		
		self.cameraLightNode = PointLight("cameraLight")
		self.cameraLightNode.setColor(Vec4(1,1,1,1))
		self.cameraLight = render.attachNewNode(self.cameraLightNode)
		render.setLight(self.cameraLight)
		
	def cameraZoomIn(self):
		if camera.getZ() > 10:
			camera.setY(camera, 1)
	def cameraZoomOut(self):
		if camera.getZ() < 20:
			camera.setY(camera, -1)
	def cameraMovements(self, task):
		if base.mouseWatcherNode.hasMouse() and not objSelectionTool.booSelecting:
			x = base.mouseWatcherNode.getMouseX()
			y = base.mouseWatcherNode.getMouseY()
			
			self.dt = globalClock.getDt() * self.scrollingSpeed
			if x < -0.99 and camera.getX():
				camera.setX(camera.getX()-self.dt)
				
			if x > 0.99 and camera.getX():
				camera.setX(camera.getX()+self.dt)
				
			if y > 0.99 and camera.getY():
				camera.setY(camera.getY()+self.dt)
				
			if y < -0.99 and camera.getY():
				camera.setY(camera.getY()-self.dt)
			
			self.cameraLight.setX(camera.getX())
			self.cameraLight.setY(camera.getY())
			self.cameraLight.setZ(camera.getZ())
		
		return task.cont
Esempio n. 17
0
    def showStartScreen(self):
        '''
        the first screen with "press any Key"
        the device with the first key press will be the first player
        '''
        self._notify.info("Initializing StartScreen")

        self.wii = []

        # StartScreen Node
        self.startNode = NodePath("StartNode")
        self.startNode.reparentTo(render)
        self.startNode.setPos(-5, 15, 3)

        # Headline model
        headline = loader.loadModel("data/models/logo.egg")
        headline.setX(4.7)
        headline.setY(-4)
        headline.setZ(-2)
        headline.setP(90)
        headline.reparentTo(self.startNode)

        # Press any key text
        presskey = TextNode("PressAnyKey")
        presskey.setFont(self.font)
        presskey.setText(_("Press any key!!"))
        textNodePath = NodePath("PressAnyNode")
        textNodePath.attachNewNode(presskey)
        textNodePath.setPos(0, 10, -9.5)
        textNodePath.reparentTo(self.startNode)

        # Show the start screen
        self.startNode.show()

        # LICHT
        plight = PointLight('plight')
        plight.setColor(VBase4(10, 10, 10, 1))
        plnp = self.startNode.attachNewNode(plight)
        plnp.setPos(20, -800, 30)
        self.startNode.setLight(plnp)

        # Camera
        self.camera = base.makeCamera(base.win)

        self._notify.info("StarScreen initialized")
Esempio n. 18
0
    def make_lights(light_spec=None, lname=None):
        """ Create one point light and an ambient light."""
        if lname is None:
            lname = 'lights'
        lights = NodePath(lname)

        if light_spec is None:
            # Create point lights
            plight = PointLight('plight1')
            light = lights.attachNewNode(plight)
            plight.setColor((0.1, 0.1, 0.1, 1.0))
            light.setPos((-2, -6, 4))
            light.lookAt(0, 0, 0)

        # Create ambient light
            alight = AmbientLight('alight')
            alight.setColor((1, 1, 1, 1.0))
            lights.attachNewNode(alight)
        else:
            for lspec in light_spec:
                light_type = lspec['type']
                light_name = lspec['name']
                assert light_type in ['AmbientLight', 'PointLight',  'DirectionalLight', 'SpotLight'], light_type
                if light_type == 'AmbientLight':
                    light = AmbientLight(light_name)
                    light.setColor(lspec['color'])
                    lights.attachNewNode(light)
                elif light_type == 'PointLight':
                    light = PointLight(light_name)
                    lights.attachNewNode(light)
                    light.setColor(lspec['color'])
                    light.setPoint(lspec['pos'])
                elif light_type == 'DirectionalLight':
                    light = DirectionalLight(light_name)
                    lights.attachNewNode(light)
                    light.setColor(lspec['color'])
                    light.setPoint(lspec['pos'])
                    light.setDirection(lspec['direction'])
                    

        return lights
Esempio n. 19
0
    def __init__(self, gameManager, gameData, *args, **kwargs):
        BaseState.__init__(self, gameManager, *args, **kwargs)

        self._gameData = gameData

        self._gameData.scene.reparentTo(render)

        base.camera.display()

        plight = PointLight('plight')
        plight.setColor(VBase4(0.2, 0.2, 0.2, 1))
        plnp = self._gameData.scene.attachNewNode(plight)
        plnp.setPos(10, 20, 0)
        self._gameData.scene.setLight(plnp)

        alight = AmbientLight('alight')
        alight.setColor(VBase4(0.2, 0.2, 0.2, 1))
        alnp = self._gameData.scene.attachNewNode(alight)
        self._gameData.scene.setLight(alnp)

        self.addTask(self.updateTask, 'globalUpdate')
Esempio n. 20
0
    def initNode(self):
        '''
        Create a clear menu
        '''
        self.camera = None
        self.selected = 0
        self.options = []
        self.optionsModells = []
        self.menuNode = NodePath("menuNode")
        self.menuNode.reparentTo(render)
        self.menuNode.setPos(-4.5, 15, 3)
        self.menuNode.setH(40)

        self.colorA = Vec4(1, 1, 0, 0)
        self.colorB = Vec4(0, 1, 1, 0)

        # LICHT
        plight = PointLight('plight')
        plight.setColor(VBase4(10, 10, 10, 1))
        plnp = self.menuNode.attachNewNode(plight)
        plnp.setPos(-10, -800, 20)
        self.menuNode.setLight(plnp)
Esempio n. 21
0
    def __init__(self, game, color):

        self.POWER = 200
        self.game = game
        self.SHIP_TYPE = "RAKETTI"
        self.Ball_offset = 10.0
     #   self.hasBall = False
        self.thrust = False
        self.thrustLeft = False
        self.thrustRight = False
        self.thrustBack = False
        self.rotation = 0

        self.body = OdeBody(game.physicsWorld)
        self.mass = OdeMass()
        self.mass.setBox(10,1,1,1)
        self.body.setMass(self.mass)
        #self.body.setGravityMode(False)

        #odespheregeom(... , size of hitbox sphere)
        self.collGeom = OdeSphereGeom( self.game.physicsSpace, 3)
        self.collGeom.setBody(self.body)
        self.collGeom.setCategoryBits( BitMask32(0xffffffff) )
        self.collGeom.setCollideBits( BitMask32(0xffffffff) )
        
        self.visualNode = NodePath('Visual node')
        self.visualNode.reparentTo(render)
        model = loader.loadModel('spaceship.egg')
        model.setH(180)
        model.setY(15)
        model.reparentTo(self.visualNode)
        self.visualNode.setScale(0.4)
        plight = PointLight('plight')
        plight.setPoint( Point3(0.6, 0, 5) )
        plight.setColor( color )
        plight.setAttenuation( Vec3(0.5, 0.01, 0.01) )
        plightNodePath = model.attachNewNode(plight)
        model.setLight(plightNodePath)
Esempio n. 22
0
class PointLight:
  """Creates a simple point light"""
  def __init__(self,manager,xml):
    self.light = PPointLight('plight')
    self.lightNode = render.attachNewNode(self.light)

    self.reload(manager,xml)


  def reload(self,manager,xml):
    color = xml.find('color')
    if color!=None:
      self.light.setColor(VBase4(float(color.get('r')), float(color.get('g')), float(color.get('b')), 1.0))

    pos = xml.find('pos')
    if pos!=None:
      self.lightNode.setPos(render, float(pos.get('x')), float(pos.get('y')), float(pos.get('z')))


  def start(self):
    render.setLight(self.lightNode)

  def stop(self):
    render.clearLight(self.lightNode)
Esempio n. 23
0
class Scene(DirectObject):
    def __init__(self):
        """Initialise the scene."""

        # Show the framerate
        base.setFrameRateMeter(True)

        # Initialise terrain:
        # Make 4 terrain nodepath objects with different hilliness values
        # and arrange them side-by-side in a 2x2 grid, giving a big terrain
        # with variable hilly and flat areas.

        color = (0.6, 0.8, 0.5, 1)  # Bright green-ish
        scale = 12
        height = 18  # FIXME: For now we are raising the terrain so it
        # floats above the sea to prevent lakes from
        # appearing (but you still get them sometimes)

        t1 = Terrain(color=color,
                     scale=scale,
                     trees=0.7,
                     pos=P.Point3(0, 0, height))
        t1.prime.reparentTo(render)
        t2 = Terrain(color=color,
                     scale=scale,
                     h=24,
                     pos=P.Point3(32 * scale, 0, height),
                     trees=0.5)
        t2.prime.reparentTo(render)
        t3 = Terrain(color=color,
                     scale=scale,
                     h=16,
                     pos=P.Point3(32 * scale, 32 * scale, height),
                     trees=0.3)
        t3.prime.reparentTo(render)
        t4 = Terrain(color=color,
                     scale=scale,
                     h=2,
                     pos=P.Point3(0, 32 * scale, height),
                     trees=0.9)
        t4.prime.reparentTo(render)

        #tnp1.setPos(tnp1,-32,-32,terrainHeight)

        # Initialise sea
        sea = Sea()

        # Initialise skybox.
        self.box = loader.loadModel("models/skybox/space_sky_box.x")
        self.box.setScale(6)
        self.box.reparentTo(render)

        # Initialise characters
        self.characters = []
        self.player = C.Character(model='models/eve',
                                  run='models/eve-run',
                                  walk='models/eve-walk')
        self.player.prime.setZ(100)
        self.player._pos = SteerVec(32 * 12 + random.random() * 100,
                                    32 * 12 + random.random() * 100)
        self.player.maxforce = 0.4
        self.player.maxspeed = 0.55
        EdgeScreenTracker(self.player.prime, dist=200)  # Setup camera
        for i in range(0, 11):
            self.characters.append(C.Character())
            self.characters[i].prime.setZ(100)
            self.characters[i].wander()
            self.characters[i].maxforce = 0.3
            self.characters[i].maxspeed = 0.2
            self.characters[i]._pos = SteerVec(32 * 12 + random.random() * 100,
                                               32 * 12 + random.random() * 100)

        C.setContainer(
            ContainerSquare(pos=SteerVec(32 * 12, 32 * 12), radius=31 * 12))

        #C.toggleAnnotation()

        # Initialise keyboard controls.
        self.accept("c", C.toggleAnnotation)
        self.accept("escape", sys.exit)

        # Setup CollisionRay and CollisionHandlerQueue for mouse picking.
        self.pickerQ = P.CollisionHandlerQueue()
        self.picker = camera.attachNewNode(
            P.CollisionNode('Picker CollisionNode'))
        self.picker.node().addSolid(P.CollisionRay())
        # We want the picker ray to collide with the floor and nothing else.
        self.picker.node().setFromCollideMask(C.floorMASK)
        self.picker.setCollideMask(P.BitMask32.allOff())
        base.cTrav.addCollider(self.picker, self.pickerQ)
        try:
            handler.addCollider(self.picker, camera)
        except:
            pass
        self.accept('mouse1', self.onClick)

        # Set the far clipping plane to be far enough away that we can see the
        # skybox.
        base.camLens.setFar(10000)

        # Initialise lighting
        self.alight = AmbientLight('alight')
        self.alight.setColor(VBase4(0.35, 0.35, 0.35, 1))
        self.alnp = render.attachNewNode(self.alight)
        render.setLight(self.alnp)

        self.dlight = DirectionalLight('dlight')
        self.dlight.setColor(VBase4(0.4, 0.4, 0.4, 1))
        self.dlnp = render.attachNewNode(self.dlight)
        self.dlnp.setHpr(45, -45, 0)
        render.setLight(self.dlnp)

        self.plight = PointLight('plight')
        self.plight.setColor(VBase4(0.8, 0.8, 0.5, 1))
        self.plnp = render.attachNewNode(self.plight)
        self.plnp.setPos(160, 160, 50)

        self.slight = Spotlight('slight')
        self.slight.setColor(VBase4(1, 1, 1, 1))
        lens = PerspectiveLens()
        self.slight.setLens(lens)
        self.slnp = render.attachNewNode(self.slight)
        self.slnp.setPos(-20, -20, 20)
        self.slnp.lookAt(50, 50, 0)

        # Initialise some scene-wide exponential fog
        colour = (0.5, 0.8, 0.8)
        self.expfog = Fog("Scene-wide exponential Fog object")
        self.expfog.setColor(*colour)
        self.expfog.setExpDensity(0.0005)
        render.setFog(self.expfog)
        base.setBackgroundColor(*colour)

        # Add a task for this Plant to the global task manager.
        self.stepcount = 0
        taskMgr.add(self.step, "Plant step task")

    def step(self, task):
        if self.stepcount < 3:
            self.stepcount += 1
            return Task.cont
        else:
            plantNode.flattenStrong()
            print render.analyze()
            return Task.done

    def onClick(self):
        """Handle the mouse-click event."""

        mpos = base.mouseWatcherNode.getMouse()
        # Makes the ray's origin the camera and make the ray point to mpos
        ###self.picker.node().getSolid(0).setFromLens(
        ###base.camNode,mpos.getX(),mpos.getY())
        ##zuck
        self.picker.node().modifySolid(0).setFromLens(base.camNode,
                                                      mpos.getX(), mpos.getY())
        # We don't want to traverse now, so wait for panda to do it then move.
        taskMgr.doMethodLater(.02, self.setDestination, 'setDest')

    def setDestination(self, task):
        """Helper method for onClick.

    Find the position in the 3D scene that was clicked and pass it to the
    click method of the currently active plugin.

    """
        if self.pickerQ.getNumEntries() > 0:
            self.pickerQ.sortEntries()
            self.point = self.pickerQ.getEntry(0).getSurfacePoint(render)
            self.player.arrive(SteerVec(self.point.getX(), self.point.getY()))
Esempio n. 24
0
class Scene(DirectObject):

  def __init__(self):
    """Initialise the scene."""

    # Show the framerate
    base.setFrameRateMeter(True)

    # Initialise terrain:
    # Make 4 terrain nodepath objects with different hilliness values
    # and arrange them side-by-side in a 2x2 grid, giving a big terrain
    # with variable hilly and flat areas.

    color = (0.6,0.8,0.5,1) # Bright green-ish
    scale = 12
    height = 18  # FIXME: For now we are raising the terrain so it
           # floats above the sea to prevent lakes from
           # appearing (but you still get them sometimes)

    t1 = Terrain(color=color,scale=scale,trees=0.7,pos=P.Point3(0,0,height))
    t1.prime.reparentTo(render)
    t2 = Terrain(color=color,scale=scale,h=24,pos=P.Point3(32*scale,0,height),trees=0.5)
    t2.prime.reparentTo(render)
    t3 = Terrain(color=color,scale=scale,h=16,pos=P.Point3(32*scale,32*scale,height),trees=0.3)
    t3.prime.reparentTo(render)
    t4 = Terrain(color=color,scale=scale,h=2,pos=P.Point3(0,32*scale,height),trees=0.9)
    t4.prime.reparentTo(render)

    #tnp1.setPos(tnp1,-32,-32,terrainHeight)

    # Initialise sea
    sea = Sea()

    # Initialise skybox.
    self.box = loader.loadModel("models/skybox/space_sky_box.x")
    self.box.setScale(6)
    self.box.reparentTo(render)

    # Initialise characters
    self.characters = []
    self.player = C.Character(model='models/eve',run='models/eve-run',
                  walk='models/eve-walk')
    self.player.prime.setZ(100)
    self.player._pos = SteerVec(32*12+random.random()*100,32*12+random.random()*100)
    self.player.maxforce = 0.4
    self.player.maxspeed = 0.55
    EdgeScreenTracker(self.player.prime,dist=200) # Setup camera
    for i in range(0,11):
      self.characters.append(C.Character())
      self.characters[i].prime.setZ(100)
      self.characters[i].wander()
      self.characters[i].maxforce = 0.3
      self.characters[i].maxspeed = 0.2
      self.characters[i]._pos = SteerVec(32*12+random.random()*100,32*12+random.random()*100)

    C.setContainer(ContainerSquare(pos=SteerVec(32*12,32*12),radius=31*12))

    #C.toggleAnnotation()

    # Initialise keyboard controls.
    self.accept("c",C.toggleAnnotation)
    self.accept("escape", sys.exit)

    # Setup CollisionRay and CollisionHandlerQueue for mouse picking.
    self.pickerQ = P.CollisionHandlerQueue()
    self.picker = camera.attachNewNode(P.CollisionNode('Picker CollisionNode'))
    self.picker.node().addSolid(P.CollisionRay())
    # We want the picker ray to collide with the floor and nothing else.
    self.picker.node().setFromCollideMask(C.floorMASK)
    self.picker.setCollideMask(P.BitMask32.allOff())
    base.cTrav.addCollider(self.picker,self.pickerQ)
    try:
      handler.addCollider(self.picker,camera)
    except:
      pass
    self.accept('mouse1',self.onClick)

    # Set the far clipping plane to be far enough away that we can see the
    # skybox.
    base.camLens.setFar(10000)

    # Initialise lighting
    self.alight = AmbientLight('alight')
    self.alight.setColor(VBase4(0.35, 0.35, 0.35, 1))
    self.alnp = render.attachNewNode(self.alight)
    render.setLight(self.alnp)

    self.dlight = DirectionalLight('dlight')
    self.dlight.setColor(VBase4(0.4, 0.4, 0.4, 1))
    self.dlnp = render.attachNewNode(self.dlight)
    self.dlnp.setHpr(45, -45, 0)
    render.setLight(self.dlnp)

    self.plight = PointLight('plight')
    self.plight.setColor(VBase4(0.8, 0.8, 0.5, 1))
    self.plnp = render.attachNewNode(self.plight)
    self.plnp.setPos(160, 160, 50)

    self.slight = Spotlight('slight')
    self.slight.setColor(VBase4(1, 1, 1, 1))
    lens = PerspectiveLens()
    self.slight.setLens(lens)
    self.slnp = render.attachNewNode(self.slight)
    self.slnp.setPos(-20, -20, 20)
    self.slnp.lookAt(50,50,0)

    # Initialise some scene-wide exponential fog
    colour = (0.5,0.8,0.8)
    self.expfog = Fog("Scene-wide exponential Fog object")
    self.expfog.setColor(*colour)
    self.expfog.setExpDensity(0.0005)
    render.setFog(self.expfog)
    base.setBackgroundColor(*colour)

    # Add a task for this Plant to the global task manager.
    self.stepcount = 0
    taskMgr.add(self.step,"Plant step task")

  def step(self,task):
    if self.stepcount < 3:
      self.stepcount+=1
      return Task.cont
    else:
      plantNode.flattenStrong()
      print render.analyze()
      return Task.done

  def onClick(self):
    """Handle the mouse-click event."""

    mpos=base.mouseWatcherNode.getMouse()
    # Makes the ray's origin the camera and make the ray point to mpos
    ###self.picker.node().getSolid(0).setFromLens(
      ###base.camNode,mpos.getX(),mpos.getY())
    ##zuck
    self.picker.node().modifySolid(0).setFromLens(
      base.camNode,mpos.getX(),mpos.getY()
    )
    # We don't want to traverse now, so wait for panda to do it then move.
    taskMgr.doMethodLater(.02,self.setDestination,'setDest')

  def setDestination(self,task):
    """Helper method for onClick.

    Find the position in the 3D scene that was clicked and pass it to the
    click method of the currently active plugin.

    """
    if self.pickerQ.getNumEntries() > 0:
      self.pickerQ.sortEntries()
      self.point=self.pickerQ.getEntry(0).getSurfacePoint(render)
      self.player.arrive(SteerVec(self.point.getX(),self.point.getY()))
Esempio n. 25
0
class BaseApp(AppShell):
    appname = "CG2"
    usecommandarea = 1
    usestatusarea = 1

    def _get_filename(self):
        return self.getVariable("surface", "filename").get()

    surface_filename = property(_get_filename)

    def _get_regular_grids(self):
        return [
            bool(self.getVariable("surface", "regular grid %d" % index).get()) for index in range(self._num_surfaces)
        ]

    surface_regular_grids = property(_get_regular_grids)

    def _get_implicit_surfaces(self):
        return [
            bool(self.getVariable("surface", "implicit surface %d" % index).get())
            for index in range(self._num_surfaces)
        ]

    surface_implicit_surfaces = property(_get_implicit_surfaces)

    def _get_point_cloud(self):
        return bool(self.getVariable("surface", "point cloud").get())

    surface_point_cloud = property(_get_point_cloud)

    def _get_subdivisions(self):
        return [int(widget.get()) for widget in self.tk_subdivisions]

    surface_subdivisions = property(_get_subdivisions)

    def _get_degree(self):
        return int(self.tk_degree.get())

    surface_degree = property(_get_degree)

    def _get_light_angle(self):
        return int(self.tk_light_angle.get())

    surface_light_angle = property(_get_light_angle)

    def __init__(self):
        self._log = logging.getLogger("BaseApp")
        self._num_surfaces = 2
        AppShell.__init__(self)
        self.initialiseoptions(BaseApp)
        self.createScene()

    def createInterface(self):
        self._log.info(u"Creating interface...")
        self.tk_filename = self.newCreateLabeledEntry(
            parent=self.interior(), category="surface", text="filename", side=TOP, fill=X, expand=0
        )
        self.tk_light_angle = self.newCreateEntryScale(
            parent=self.interior(),
            category="surface",
            text="light angle",
            max=360,
            min=1,
            resolution=1,
            command=self.rotate_light,
            side=TOP,
            fill=X,
            expand=0,
        )
        self.tk_subdivisions = []
        for index in range(self._num_surfaces):
            self.tk_subdivisions.append(
                self.newCreateEntryScale(
                    parent=self.interior(),
                    category="surface",
                    text="subdivisions %d" % index,
                    max=30,
                    resolution=1,
                    side=TOP,
                    fill=X,
                    expand=0,
                )
            )
        self.tk_degree = self.newCreateEntryScale(
            parent=self.interior(),
            category="surface",
            text="degree",
            max=3,
            min=1,
            resolution=1,
            side=TOP,
            fill=X,
            expand=0,
        )
        self.tk_point_cloud = self.newCreateCheckbutton(
            parent=self.interior(),
            category="surface",
            text="point cloud",
            command=self._toggle_point_cloud,
            side=TOP,
            fill=X,
            expand=0,
        )
        self.tk_regular_grids = []
        for index in range(self._num_surfaces):
            self.tk_regular_grids.append(
                self.newCreateCheckbutton(
                    parent=self.interior(),
                    category="surface",
                    text="regular grid %d" % index,
                    command=self._toggle_regular_grids,
                    side=TOP,
                    fill=X,
                    expand=0,
                )
            )
        self.tk_implicit_surfaces = []
        for index in range(self._num_surfaces):
            self.tk_implicit_surfaces.append(
                self.newCreateCheckbutton(
                    parent=self.interior(),
                    category="surface",
                    text="implicit surface %d" % index,
                    command=self._toggle_implicit_surfaces,
                    side=TOP,
                    fill=X,
                    expand=0,
                )
            )
        self.tk_apply = self.buttonAdd(
            buttonName="Apply", helpMessage="Apply", statusMessage="Apply", command=self.apply
        )

        # set default values
        self.getVariable("surface", "filename").set("pointdata/cat.off")
        self.tk_degree.set(1)
        self.tk_light_angle.set(1)
        self.getVariable("surface", "regular grid 0").set(1)
        self.getVariable("surface", "point cloud").set(1)

    def createScene(self):
        self._log.debug(u"Creating scene...")
        base.setBackgroundColor(0.3, 0.3, 0.3)
        self.gl_dlight = PointLight("dlight")
        self.gl_dlight.setColor(Vec4(0.5, 0.5, 0.5, 1))
        self.np_dlight = render.attachNewNode(self.gl_dlight)
        # self.np_dlight.setHpr(90, 0, 0)
        # self.np_dlight.lookAt(1, 1, -10)
        render.setLight(self.np_dlight)
        render.setTransparency(TransparencyAttrib.MAlpha)
        self._camera_control = CameraHandler()
        self.clearScene()
        self.rotate_light()

    def clearScene(self):
        if not hasattr(self, "surfaces"):
            self.surfaces = [None] * self._num_surfaces
        if not hasattr(self, "grids"):
            self.grids = [None] * self._num_surfaces
        if not hasattr(self, "implicit_surfaces"):
            self.implicit_surfaces = [None] * self._num_surfaces

        for surface_index in range(self._num_surfaces):
            if self.surfaces[surface_index]:
                self.surfaces[surface_index] = None
                if self.grids[surface_index]:
                    self.grids[surface_index].removeNode()
                self.grids[surface_index] = None
                if self.implicit_surfaces[surface_index]:
                    self.implicit_surfaces[surface_index].removeNode()
                self.implicit_surfaces[surface_index] = None

        if hasattr(self, "point_cloud") and self.point_cloud:
            self.point_cloud.removeNode()
        self.point_cloud = None

    @log_exceptions
    @profile(immediate=True)
    def apply(self):
        self._log.info("Applying values...")
        self.clearScene()
        for index in range(self._num_surfaces):
            self.surfaces[index] = ImplicitSurface.from_file(self.surface_filename)
        self._toggle_implicit_surfaces()
        self._toggle_regular_grids()
        self._toggle_point_cloud()
        self._camera_control.setTarget(*self.surfaces[0].center[0:3])

    @log_exceptions
    def _toggle_regular_grids(self):
        for index in range(self._num_surfaces):
            self._toggle_regular_grid(index)

    def _toggle_regular_grid(self, index):
        if self.surfaces[index]:
            self._log.debug(u"Toggling regular grid %d display..." % index)
            if not self.grids[index]:
                self._log.debug(u"Creating regular grid %d..." % index)
                self.grids[index] = render.attachNewNode(
                    self.surfaces[index].get_parameter_grid(self.surface_subdivisions[index], self.surface_degree)
                )
                self.grids[index].setLightOff()
            if self.surface_regular_grids[index]:
                self._log.debug(u"Regular grid %d is now visible." % index)
                self.grids[index].show()
            else:
                self._log.debug(u"Regular grid %d is now hidden." % index)
                self.grids[index].hide()
        else:
            self._log.debug(u"No surface loaded, cannot create regular grid %d..." % index)

    @log_exceptions
    def _toggle_implicit_surfaces(self):
        for index in range(self._num_surfaces):
            self._toggle_implicit_surface(index)

    def _toggle_implicit_surface(self, index):
        if self.surfaces[index]:
            self._log.debug(u"Toggling implicit surface %d display..." % index)
            if not self.implicit_surfaces[index]:
                self._log.debug(u"Creating implicit surface %d..." % index)
                self.implicit_surfaces[index] = render.attachNewNode(
                    self.surfaces[index].get_implicit_surface(self.surface_subdivisions[index], self.surface_degree)
                )
            if self.surface_implicit_surfaces[index]:
                self._log.debug(u"implicit surface %d is now visible." % index)
                self.implicit_surfaces[index].show()
            else:
                self._log.debug(u"implicit surface %d is now hidden." % index)
                self.implicit_surfaces[index].hide()
        else:
            self._log.debug(u"No surface loaded, cannot create implicit surface %d..." % index)

    @log_exceptions
    def _toggle_point_cloud(self):
        if self.surfaces[0]:
            self._log.debug(u"Toggling point cloud display...")
            if not self.point_cloud:
                self._log.debug(u"Creating point_cloud...")
                self.point_cloud = render.attachNewNode(self.surfaces[0].get_original_point_cloud())
                self.point_cloud.setLightOff()
            if self.surface_point_cloud:
                self._log.debug(u"point cloud is now visible.")
                self.point_cloud.show()
            else:
                self._log.debug(u"point cloud is now hidden.")
                self.point_cloud.hide()
        else:
            self._log.debug(u"No surface loaded, cannot create point cloud...")

    @log_exceptions
    def rotate_light(self, val=None):
        if hasattr(self, "np_dlight"):
            self._log.debug(u"Setting light angle %d..." % self.surface_light_angle)
            angle_radians = self.surface_light_angle * (math.pi / 180.0)
            self.np_dlight.setPos(1000.0 * math.sin(angle_radians), -1000.0 * math.cos(angle_radians), 0)
Esempio n. 26
0
class PointOverbright (object):

    _count = 0

    def __init__ (self, parent, color, radius, halfat=None,
                  subnode=None, pos=Point3(), name=None):

        self.parent = parent

        if halfat is None:
            halfat = 0.5

        if name is None:
            name = "poverbright%d" % PointOverbright._count
        self.name = name

        self._pntlt = PointLight(self.name)
        pnode = subnode if subnode is not None else self.parent.node
        self.node = pnode.attachNewNode(self._pntlt)
        self.node.setPos(pos)

        self.update(color, radius, halfat, pos)

        self.alive = True
        PointOverbright._count += 1
        base.taskMgr.add(self._loop, "poverbright-loop")


    def destroy (self):

        if not self.alive:
            return
        self.alive = False
        self.node.removeNode()


    def update (self, color=None, radius=None, halfat=None, pos=None):

        if color is not None:
            self._pntlt.setColor(color)
            self.color = color
            self._colamp = Vec3(color[0], color[1], color[2]).length()
        if radius is not None or halfat is not None:
            if radius is None:
                radius = self.radius
            if halfat is None:
                halfat = self.halfat
            assert 0.0 < halfat < 1.0
            radpow = log(0.5) / log(halfat)
            self._pntlt.setAttenuation(Vec3(radius, radpow, 0.0))
            self.radius = radius
            self.halfat = halfat
            self._radpow = radpow
        if pos is not None:
            self.node.setPos(pos)


    def strength (self, dist):

        if self._colamp > 0.0:
            att = 1.0
            if dist > 0.0:
                att -= pow(min(dist / self.radius, 1.0), self._radpow)
            return self._colamp * att
        else:
            return 0.0


    def _loop (self, task):

        if not self.alive:
            return task.done
        if not self.parent.alive:
            self.destroy()
            return task.done
        return task.cont
Esempio n. 27
0
class Main(DirectObject):
    def __init__(self):
        
        # Display nodes creation
        self.patches_node    = render.attachNewNode("patches_node")
        self.agents_node     = render.attachNewNode("agents_node")
        self.lines_node      = render.attachNewNode("lines_node")
        self.light_node      = render.attachNewNode("light_node")
        self.floor_node      = render.attachNewNode("floor_node")
        self.frame_node      = render.attachNewNode("frame_node")
        self.env_node        = render.attachNewNode("env_node")
        
        # Light settings
        self.light = True
        self.dlight = PointLight("dlight")
        self.dlight.setColor(Vec4(.8,.8,.5,1))
        self.dlnp = render.attachNewNode(self.dlight)
        self.dlnp.setPos(0,100,100)
        render.setLight(self.dlnp)
        
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.4, .4, .4, 1))
        render.setLight(render.attachNewNode(ambientLight))
        
        #self.create_floor(121, 121, "grass_floor") 
        self.create_frame(121, 121, 0) 
        self.add_model(self.env_node, "env", (60,60,-0.5), 200)
        self.fill_env()
        
        taskMgr.add(self.game_loop, "game_loop")
        taskMgr.add(self.close_window, "close_window")
        
    def toggle_lights(self):
        self.light = not(self.light)
        
        if self.light:
            render.setLight(self.dlnp)
        else:
            render.setLightOff(self.dlnp)
    
    def add_model(self, rendering_node, model, position, scale, heading=0):
        new_model = loader.loadModel("eggs/"+model)
        new_model.setPos(*position)
        new_model.setScale(scale)
        new_model.setH(heading)
        new_model.reparentTo(rendering_node)
    
    def add_line(self, rendering_node, color, thickness, start, end):
        linesegs = LineSegs()  
        linesegs.setColor(*color) 
        linesegs.setThickness(thickness)
        linesegs.drawTo((start[0], start[1], start[2])) 
        linesegs.drawTo((end[0], end[1], end[2]))    
        new_node = linesegs.create()
        rendering_node.attachNewNode(new_node)
        
    def fill_env(self):

        for _ in range (100) :
            self.add_model(self.env_node, "daisy", (random.random()*121,random.random()*121,0), 2)
            self.add_model(self.env_node, "Fern", (random.random()*121,random.random()*121,0), 0.01, random.random()*360)
            self.add_model(self.env_node, "rock", (random.random()*121,random.random()*121,0), random.random()*0.1+0.1, random.random()*360)      

        self.env_node.flattenStrong()
        
    def game_loop(self, task):    
          
        for lock in worlds_locks :
            worlds_locks[lock].acquire()
   
        for world_name in worlds :
            patch_center = worlds[world_name].patches_size / 2.0

            for patch in worlds[world_name].updated_patches :
                if patch.check_visibility() :
                    patch.draw(self.patches_node)
            if len(worlds[world_name].updated_patches) > 0 :
                worlds[world_name].updated_patches = list()
            
            for lines in worlds[world_name].updated_lines :
                start = (lines[1][0]+patch_center, lines[1][1]+patch_center, lines[1][2]+patch_center)
                end = (lines[2][0]+patch_center, lines[2][1]+patch_center, lines[2][2]+patch_center)
                self.add_line(self.lines_node, (1,0,0,1), lines[0].pen_size, start, end)

            if len(worlds[world_name].updated_lines) > 0 :
                self.lines_node.flattenStrong() 
                worlds[world_name].updated_lines = list()
            
            for turtle_type in worlds[world_name].turtles_dictionary :
                for turtle in worlds[world_name].turtles_dictionary[turtle_type] :
                    if not turtle.hidden :
                        turtle.model.setPos(turtle._x+patch_center, turtle._y+patch_center, turtle._z+patch_center)
                        turtle.draw(self.agents_node)
                   
        for lock in worlds_locks :
            worlds_locks[lock].release()
            
        return Task.cont
    
    def close_window(self, task):
        if base.win.isClosed() :  
            for world_name in worlds :
                worlds[world_name].stop()
    
    def create_floor(self, size_x_axis, size_y_axis, texture):
        
        card_maker = CardMaker('')
        card_maker.setFrame(0,size_x_axis,0,size_y_axis)
        '''
        for y in range(size_y_axis):
            for x in range(size_x_axis):
                new_node = self.floorNode.attachNewNode(card_maker.generate())
                new_node.setP(-90)
                new_node.setPos(x, y, 0)
        '''
        new_node = self.floor_node.attachNewNode(card_maker.generate())
        new_node.setP(-90)
        new_node.setPos(0, 0, 0)
        new_node.setTexture(textures[texture])    
        
        self.floor_node.flattenStrong()

    
    def create_frame(self, size_x_axis, size_y_axis, size_z_axis):
        
        edges = [((0,0,0),(size_x_axis, 0, 0)), 
                 ((0,0,0),(0, size_y_axis, 0)),
                 ((0,0,0),(0, 0, size_z_axis)), 
                 ((0,0,size_z_axis),(size_x_axis, 0, size_z_axis)),
                 ((size_x_axis,0,0),(size_x_axis, 0, size_z_axis)),
                 ((size_x_axis,0,0),(size_x_axis, size_y_axis, 0)),
                 ((size_x_axis,0,size_z_axis),(size_x_axis, size_y_axis, size_z_axis)),
                 ((size_x_axis,size_y_axis,0),(size_x_axis, size_y_axis, size_z_axis)),
                 ((0,0,size_z_axis),(0, size_y_axis, size_z_axis)),
                 ((0,size_y_axis,0),(0, size_y_axis, size_z_axis)),
                 ((0,size_y_axis,0),(size_x_axis, size_y_axis, 0)),
                 ((0,size_y_axis,size_z_axis),(size_x_axis, size_y_axis, size_z_axis)),       
                 ]
        
        for edge in edges :
            self.add_line(self.frame_node, (0,0,0,0), 3, edge[0], edge[1])  
Esempio n. 28
0
        arrow.set_length(start_length)
    else:
        t = task.time % time_to_full_length
        t = t / time_to_full_length
        length_diff = max_length - start_length
        new_length = start_length + t * length_diff
        arrow.set_length(new_length)
    return Task.cont


if __name__ == "__main__":
    from direct.directbase import DirectStart
    global base, render
    print "Arrow::main"
    arrow = Arrow()
    arrow.set_angle_x_z_plane(45)
    #arrow.set_length(0.5)
    base.disableMouse()
    base.camera.setPos(0, -5, .5)

    #taskMgr.add(rotate, 'rotate', extraArgs=[arrow.root_node_path,0.05,0], appendTask=True)
    #taskMgr.add(scale, 'scale', extraArgs=[arrow,1.0,0.5,1.0], appendTask=True)

    plight = PointLight('plight')
    plight.setColor(VBase4(1, 1, 1, 1))
    plnp = render.attachNewNode(plight)
    plnp.setPos(0, -10, 0)
    render.setLight(plnp)

    run()
Esempio n. 29
0
 def __init__(self):
     ShowBase.__init__(self)
     resize_window = ConfigVariableBool('viewer-resize-window', '#t')
     if resize_window.getValue():
         self.win_size = (800, 800)
     # Black background
     self.win.setClearColor((1,1,1,1))
     # Set up lights.
     ablight = AmbientLight("ambientlight")
     ablight.setColor(Vec4(0.5, 0.5, 0.5, 1))
     ablightnode = self.render.attachNewNode(ablight)
     self.render.setLight(ablightnode)
     ptlight0 = PointLight("pointlight0")
     ptlight0.setColor(VBase4(1, 1, 1, 1))
     ptlightnode0 = self.render.attachNewNode(ptlight0)
     ptlightnode0.setPos(500, 0, 500)
     base.render.setLight(ptlightnode0)
     ptlight1 = PointLight("pointlight1")
     ptlight1.setColor(VBase4(1, 1, 1, 1))
     ptlightnode1 = base.render.attachNewNode(ptlight1)
     ptlightnode1.setPos(0, 500, 500)
     base.render.setLight(ptlightnode1)
     # Spotlight. Casts shadows.
     slight = Spotlight("slight")
     slight.setScene(self.render)
     slight.setShadowCaster(True, 2 ** 11, 2 ** 11)
     # Set shadow mask, so we can exclude objects from casting shadows
     self.shadow_mask = BitMask32.bit(2)
     slight.setCameraMask(self.shadow_mask)
     slight.setColor((1.2, 1.2, 1.2, 1.))
     slight.getLens().setFov(45)
     slight.getLens().setNearFar(1, 100)
     slnp = self.lights.attachNewNode(slight)
     slnp.setPos((6, 8, 20))
     slnp.lookAt(0, 0, 0)
     self.render.setLight(slnp)
     # Ambient light.
     alight = AmbientLight("alight")
     a = 0.75
     alight.setColor((a, a, a, 1.0))
     #alight.setColor((0.8, 0.8, 0.8, 1.0))
     alnp = self.lights.attachNewNode(alight)
     self.render.setLight(alnp)
     self.lights.reparentTo(self.render)
     # Set auto shading for shadows
     use_shaders = ConfigVariableBool('viewer-use-shaders', '#t')
     if use_shaders.getValue():
         self.render.setShaderAuto()
     # Set antialiasing on
     self.render.setAntialias(AntialiasAttrib.MAuto)
     # Camera
     self.camera_rot = self.render.attachNewNode("camera_rot")
     self.cameras = self.camera_rot.attachNewNode("cameras")
     self.cameras.setPos(14, 32, 9.)
     self.look_at = self.render.attachNewNode("look_at")
     self.look_at.setPos(Point3(2, 0, 1))
     self.cameras.lookAt(self.look_at)
     self.camera.reparentTo(self.cameras)
     # Adjust the camera's lens
     lens = PerspectiveLens()
     self.camLens = lens
     self.camLens.setNearFar(0.01, 1000.0)
     setlens = ConfigVariableBool('viewer-set-cam-lens', '#t')
     if setlens:
         self.cam.node().setLens(self.camLens)
     #
     # Initialize / set variables
     self.sso = None
     self.ssos = []
     self.cache = None
     self.scene = SSO("scene")
     self.scene.reparentTo(self.render)
     # Key callbacks.
     self.accept("shift-control-escape", self.exit)
     self.accept("escape", self.exit)
     self.accept("0", self.reset_sso)
     self.accept("arrow_left", self.prev)
     self.accept("arrow_right", self.next)
     self.accept("page_down", self.prev, [100])
     self.accept("page_up", self.next, [100])
     self.accept("f1", self.toggle_debug)
     self.accept("o", self.physics_once, extraArgs=[1. / 10])
     self.accept("i", self.physics_once, extraArgs=[1. / 10000])
     # Remove existing keyboard tasks.
     self.mandatory_events = ("window-event", "async_loader_0",
                              "render-texture-targets-changed",
                              "shift-control-escape")
     # Task list: name: (key, args)
     events = {"physics": ("p",),
               "repel": ("t",),
               "bump": ("f",),
               "rotate": ("r", 20),
               "rotate90": ("h",),
               "ss_task": ("s",),
               "ssa_task": ("w",),
               "bp": ("b",)}
     # Add events
     for key, val in events.iteritems():
         call = [key] + list(val[1:])
         self.accept(val[0], self.toggle_task, call)
     # These are the key events that we will never ignore
     self.permanent_events = self.getAllAccepting()
     # These are the key events that we will never ignore
     self.permanent_tasks = [task.getName()
                             for task in self.taskMgr.getAllTasks()]
     self.start_time = -1
     self.old_elapsed = 0
Esempio n. 30
0
        arrow.set_length(start_length)
    else:
        t = task.time % time_to_full_length
        t = t/time_to_full_length
        length_diff = max_length - start_length
        new_length = start_length+t*length_diff
        arrow.set_length(new_length)
    return Task.cont

if __name__ == "__main__":
    from direct.directbase import DirectStart
    global base, render
    print "Arrow::main"
    arrow = Arrow()
    arrow.set_angle_x_z_plane(45)
    #arrow.set_length(0.5)
    base.disableMouse()
    base.camera.setPos(0,-5,.5)
    
    #taskMgr.add(rotate, 'rotate', extraArgs=[arrow.root_node_path,0.05,0], appendTask=True)
    #taskMgr.add(scale, 'scale', extraArgs=[arrow,1.0,0.5,1.0], appendTask=True)

    plight = PointLight('plight')
    plight.setColor(VBase4(1, 1, 1, 1))
    plnp = render.attachNewNode(plight)
    plnp.setPos(0, -10, 0)
    render.setLight(plnp)
    
    run()
    
Esempio n. 31
0
 def __init__(self):
     ShowBase.__init__(self)
     resize_window = ConfigVariableBool('viewer-resize-window', '#t')
     if resize_window.getValue():
         self.win_size = (800, 800)
     # Black background
     self.win.setClearColor((1, 1, 1, 1))
     # Set up lights.
     ablight = AmbientLight("ambientlight")
     ablight.setColor(Vec4(0.5, 0.5, 0.5, 1))
     ablightnode = self.render.attachNewNode(ablight)
     self.render.setLight(ablightnode)
     ptlight0 = PointLight("pointlight0")
     ptlight0.setColor(VBase4(1, 1, 1, 1))
     ptlightnode0 = self.render.attachNewNode(ptlight0)
     ptlightnode0.setPos(500, 0, 500)
     base.render.setLight(ptlightnode0)
     ptlight1 = PointLight("pointlight1")
     ptlight1.setColor(VBase4(1, 1, 1, 1))
     ptlightnode1 = base.render.attachNewNode(ptlight1)
     ptlightnode1.setPos(0, 500, 500)
     base.render.setLight(ptlightnode1)
     # Spotlight. Casts shadows.
     slight = Spotlight("slight")
     slight.setScene(self.render)
     slight.setShadowCaster(True, 2**11, 2**11)
     # Set shadow mask, so we can exclude objects from casting shadows
     self.shadow_mask = BitMask32.bit(2)
     slight.setCameraMask(self.shadow_mask)
     slight.setColor((1.2, 1.2, 1.2, 1.))
     slight.getLens().setFov(45)
     slight.getLens().setNearFar(1, 100)
     slnp = self.lights.attachNewNode(slight)
     slnp.setPos((6, 8, 20))
     slnp.lookAt(0, 0, 0)
     self.render.setLight(slnp)
     # Ambient light.
     alight = AmbientLight("alight")
     a = 0.75
     alight.setColor((a, a, a, 1.0))
     #alight.setColor((0.8, 0.8, 0.8, 1.0))
     alnp = self.lights.attachNewNode(alight)
     self.render.setLight(alnp)
     self.lights.reparentTo(self.render)
     # Set auto shading for shadows
     use_shaders = ConfigVariableBool('viewer-use-shaders', '#t')
     if use_shaders.getValue():
         self.render.setShaderAuto()
     # Set antialiasing on
     self.render.setAntialias(AntialiasAttrib.MAuto)
     # Camera
     self.camera_rot = self.render.attachNewNode("camera_rot")
     self.cameras = self.camera_rot.attachNewNode("cameras")
     self.cameras.setPos(14, 32, 9.)
     self.look_at = self.render.attachNewNode("look_at")
     self.look_at.setPos(Point3(2, 0, 1))
     self.cameras.lookAt(self.look_at)
     self.camera.reparentTo(self.cameras)
     # Adjust the camera's lens
     lens = PerspectiveLens()
     self.camLens = lens
     self.camLens.setNearFar(0.01, 1000.0)
     setlens = ConfigVariableBool('viewer-set-cam-lens', '#t')
     if setlens:
         self.cam.node().setLens(self.camLens)
     #
     # Initialize / set variables
     self.sso = None
     self.ssos = []
     self.cache = None
     self.scene = SSO("scene")
     self.scene.reparentTo(self.render)
     # Key callbacks.
     self.accept("shift-control-escape", self.exit)
     self.accept("escape", self.exit)
     self.accept("0", self.reset_sso)
     self.accept("arrow_left", self.prev)
     self.accept("arrow_right", self.next)
     self.accept("page_down", self.prev, [100])
     self.accept("page_up", self.next, [100])
     self.accept("f1", self.toggle_debug)
     self.accept("o", self.physics_once, extraArgs=[1. / 10])
     self.accept("i", self.physics_once, extraArgs=[1. / 10000])
     # Remove existing keyboard tasks.
     self.mandatory_events = ("window-event", "async_loader_0",
                              "render-texture-targets-changed",
                              "shift-control-escape")
     # Task list: name: (key, args)
     events = {
         "physics": ("p", ),
         "repel": ("t", ),
         "bump": ("f", ),
         "rotate": ("r", 20),
         "rotate90": ("h", ),
         "ss_task": ("s", ),
         "ssa_task": ("w", ),
         "bp": ("b", )
     }
     # Add events
     for key, val in events.iteritems():
         call = [key] + list(val[1:])
         self.accept(val[0], self.toggle_task, call)
     # These are the key events that we will never ignore
     self.permanent_events = self.getAllAccepting()
     # These are the key events that we will never ignore
     self.permanent_tasks = [
         task.getName() for task in self.taskMgr.getAllTasks()
     ]
     self.start_time = -1
     self.old_elapsed = 0