示例#1
0
 def configure_instance(self, instance):
     blendAttrib = None
     translucid = False
     if self.blend == TransparentTexture.TB_Alpha:
         blendAttrib = ColorBlendAttrib.make(
             ColorBlendAttrib.MAdd, ColorBlendAttrib.O_incoming_alpha,
             ColorBlendAttrib.O_one_minus_incoming_alpha,
             ColorBlendAttrib.M_add, ColorBlendAttrib.O_one,
             ColorBlendAttrib.O_one)
         translucid = True
     elif self.blend == TransparentTexture.TB_PremultipliedAlpha:
         blendAttrib = ColorBlendAttrib.make(
             ColorBlendAttrib.MAdd, ColorBlendAttrib.O_one,
             ColorBlendAttrib.O_one_minus_incoming_alpha,
             ColorBlendAttrib.M_add, ColorBlendAttrib.O_one,
             ColorBlendAttrib.O_one)
         translucid = True
     elif self.blend == TransparentTexture.TB_Additive:
         blendAttrib = ColorBlendAttrib.make(ColorBlendAttrib.MAdd,
                                             ColorBlendAttrib.O_one,
                                             ColorBlendAttrib.O_one,
                                             ColorBlendAttrib.M_add,
                                             ColorBlendAttrib.O_one,
                                             ColorBlendAttrib.O_one)
         translucid = True
     elif self.blend == TransparentTexture.TB_AlphaAdditive:
         blendAttrib = ColorBlendAttrib.make(
             ColorBlendAttrib.MAdd, ColorBlendAttrib.O_incoming_alpha,
             ColorBlendAttrib.O_one, ColorBlendAttrib.M_add,
             ColorBlendAttrib.O_one, ColorBlendAttrib.O_one)
         translucid = True
     if blendAttrib is not None:
         instance.setAttrib(blendAttrib)
     if translucid:
         instance.setTransparency(TransparencyAttrib.MAlpha)
示例#2
0
    def __init__(self, left_barrel, right_barrel, world):
        self.scene = world.scene
        self.physics = world.physics
        self.world = world
        self.left_plasma = load_model('plasma_sight.egg')
        self.right_plasma = load_model('plasma_sight.egg')
        self.left_plasma.reparent_to(left_barrel)
        self.right_plasma.reparent_to(right_barrel)
        self.left_plasma.set_r(180)
        self.left_plasma.find("**/sight").setColor(*SIGHTS_FRIENDLY_COLOR)
        self.right_plasma.find("**/sight").setColor(*SIGHTS_FRIENDLY_COLOR)

        # inverted colors based on colors behind sights
        self.left_plasma.setTransparency(TransparencyAttrib.MAlpha)
        self.left_plasma.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MInvSubtract,
              ColorBlendAttrib.OIncomingAlpha, ColorBlendAttrib.OOne))
        self.right_plasma.setTransparency(TransparencyAttrib.MAlpha)
        self.right_plasma.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MInvSubtract,
              ColorBlendAttrib.OIncomingAlpha, ColorBlendAttrib.OOne))

        # ambient light source for lighting sight shapes
        sight_light = AmbientLight('sight_light')
        sight_light.set_color(VBase4(1,1,1,1))
        sight_lightnp = self.scene.attach_new_node(sight_light)

        # the following excludes the sights from z-culling (always visible)
        self.left_plasma.set_bin("fixed", 40)
        self.left_plasma.set_depth_test(False)
        self.left_plasma.set_depth_write(False)
        self.left_plasma.set_light(sight_lightnp)
        self.right_plasma.set_bin("fixed", 40)
        self.right_plasma.set_depth_test(False)
        self.right_plasma.set_depth_write(False)
        self.right_plasma.set_light(sight_lightnp)
示例#3
0
    def create_cards(self):
        """ 
        Create cards: these are panda3d objects that are required for displaying textures.
        You can't just have a disembodied texture. In pandastim (at least for now) we are
        only showing 2d projections of textures, so we use cards.       
        """
        cardmaker = CardMaker("stimcard")
        cardmaker.setFrameFullscreenQuad()
        #Binocular cards
        if self.current_stim_params['stim_type'] == 'b':
            self.setBackgroundColor(
                (0, 0, 0, 1))  # without this the cards will appear washed out
            self.left_card = self.aspect2d.attachNewNode(cardmaker.generate())
            self.left_card.setAttrib(
                ColorBlendAttrib.make(
                    ColorBlendAttrib.M_add))  # otherwise only right card shows

            self.right_card = self.aspect2d.attachNewNode(cardmaker.generate())
            self.right_card.setAttrib(
                ColorBlendAttrib.make(ColorBlendAttrib.M_add))
            if self.profile_on:
                self.center_indicator = OnscreenText(
                    "x",
                    style=1,
                    fg=(1, 1, 1, 1),
                    bg=(0, 0, 0, .8),
                    pos=self.current_stim_params['position'],
                    scale=0.05)
        # Tex card
        elif self.current_stim_params['stim_type'] == 's':
            self.card = self.aspect2d.attachNewNode(cardmaker.generate())
            self.card.setColor((1, 1, 1, 1))  #?
            self.card.setScale(self.scale)
        return
示例#4
0
    def load(self):
        Entity.load(self)

        scale = self.getEntityValueFloat("spriteScale")
        color = self.getEntityValueColor("spriteColor")

        sunVec = base.shaderGenerator.getSunVector()
        self.pivotNode = camera.attachNewNode('env_sun-pivot')
        self.pivotNode.lookAt(sunVec)
        self.pivotNode.setCompass()

        cm = CardMaker('sun_sprite')
        cm.setFrame(-0.5, 0.5, -0.5, 0.5)
        self.sunSprite = self.pivotNode.attachNewNode(
            GlowNode(cm.generate(), 32.0 * scale))
        self.sunSprite.setAttrib(
            ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OOne,
                                  ColorBlendAttrib.OOne), 1)
        self.sunSprite.setBSPMaterial("phase_14/materials/sun/sunsprite.mat",
                                      1)
        self.sunSprite.setFogOff(10)
        self.sunSprite.setBillboardPointEye()
        self.sunSprite.setDepthTest(False)
        self.sunSprite.setDepthWrite(False)
        self.sunSprite.setScale(scale * 100)
        self.sunSprite.setColorScale(color, 1)
        self.sunSprite.setY(1000)
        self.sunSprite.node().setBounds(OmniBoundingVolume())
        self.sunSprite.node().setFinal(True)
示例#5
0
 def __init__(self, startSize, endSize, roll, color, duration):
     NodePath.__init__(self, 'muzzleParticle')
     
     cm = CardMaker("muzzleSpriteCard")
     cm.setFrame(-1, 1, -1, 1)
     cm.setHasUvs(True)
     cm.setUvRange((0, 0), (1, 1))
     cmnp = self.attachNewNode(cm.generate())
     cmnp.setBillboardAxis()
     
     self.setTexture(loader.loadTexture(self.muzzleroot.format(random.randint(*self.muzzles))), 1)
     #self.setShaderOff(1)
     self.setLightOff(1)
     self.setMaterialOff(1)
     self.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OOne, ColorBlendAttrib.OOne), 1)
     self.setDepthWrite(False, 1)
     #self.setTransparency(1)
     
     self.startAlpha = 0.5
     self.endAlpha = 0.0
     self.duration = duration
     self.startSize = startSize
     self.endSize = endSize
     self.color = color
     self.startTime = globalClock.getFrameTime()
     self.roll = roll
     taskMgr.add(self.particleUpdate, "muzzleParticleUpdate-" + str(id(self)))
示例#6
0
    def load(self):
        Entity.load(self)

        self.setPos(self.cEntity.getOrigin())
        self.setHpr(self.cEntity.getAngles())

        self.setDepthWrite(False, 1)
        col = self.getEntityValueColor("_light")
        self.rgbColor = col
        self.setAttrib(
            ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OOne,
                                  ColorBlendAttrib.OOne), 1)

        self.hide(CIGlobals.ShadowCameraBitmask)

        self.spotlightLength = self.getEntityValueFloat(
            "SpotlightLength") / 16.0
        self.spotlightWidth = self.getEntityValueFloat("SpotlightWidth") / 16.0

        beamAndHalo = loader.loadModel(
            "phase_14/models/misc/light_beam_and_halo.bam")

        # Blend between halo and beam
        spotlightroot = self.attachNewNode('spotlightRoot')
        spotlightroot.setP(90)
        self.spotlight = beamAndHalo.find("**/beam")
        self.spotlight.setBillboardAxis()
        self.spotlight.reparentTo(spotlightroot)

        self.halo = CIGlobals.makeLightGlow(self.spotlightWidth)
        self.halo.reparentTo(self)

        beamAndHalo.removeNode()

        entPos = self.getPos()

        spotDir = self.getQuat().getForward()
        # User specified a max length, but clip that length so the spot effect doesn't appear to go through a floor or wall
        traceEnd = entPos + (spotDir * self.spotlightLength)
        endPos = self.bspLoader.clipLine(entPos, traceEnd)
        realLength = (endPos - entPos).length()
        self.spotlight.setSz(realLength)
        self.spotlight.setSx(self.spotlightWidth)

        self.spotlightDir = spotDir
        self.negSpotlightDir = -self.spotlightDir

        # Full beam, no halo
        self.setBeamHaloFactor(1.0)

        self.reparentTo(render)

        # Only update the spotlight if the object passes the Cull test.
        self.node().setFinal(True)
        clbk = CallbackNode('point_spotlight_callback')
        clbk.setCullCallback(CallbackObject.make(self.__spotlightThink))
        clbk.setBounds(BoundingSphere((0, 0, 0), 0))
        self.callback = self.attachNewNode(clbk)
        self.callback.hide(CIGlobals.ReflectionCameraBitmask)
        self.callback.hide(CIGlobals.ShadowCameraBitmask)
示例#7
0
    def alterHealth(self,
                    dHealth,
                    incomingImpulse,
                    knockback,
                    flinchValue,
                    overcharge=False):
        GameObject.alterHealth(self, dHealth, incomingImpulse, knockback,
                               flinchValue, overcharge)

        self.flinchCounter -= flinchValue
        if self.flinchCounter <= 0:
            self.resetFlinchCounter()
            self.flinch()

        if dHealth < 0 and incomingImpulse is not None:
            shield = Common.framework.showBase.loader.loadModel(
                "../Section2SpaceflightDocking/Models/shield")
            shield.setScale(self.size)
            shield.reparentTo(self.root)
            shield.setAttrib(
                ColorBlendAttrib.make(ColorBlendAttrib.MAdd,
                                      ColorBlendAttrib.OIncomingAlpha,
                                      ColorBlendAttrib.OOne))
            shield.lookAt(
                Common.framework.showBase.render,
                self.root.getPos(Common.framework.showBase.render) +
                incomingImpulse)
            shield.setBin("unsorted", 1)
            shield.setDepthWrite(False)
            self.shields.append([shield, 0])
示例#8
0
    def __init__(self, physic_world, config=None):
        logging.info("INIT PLAYER...")
        logging.info("INIT FSM...")
        FSM.__init__(self, "FSM-Player")
        logging.info("INIT CONFIG...")
        Config.__init__(self)
        # additional initial configuration settings set by the outher application
        self.physic_world = physic_world
        logging.info("INIT PHYSICS...")
        Physics.__init__(self)
        logging.info("INIT CONTROLS...")
        Control.__init__(self)
        logging.info("INIT CAMERA...")
        Camera.__init__(self, self.cam_near_clip, self.cam_far_clip,
                        self.cam_fov)
        logging.info("INIT ANIMATOR...")
        Animator.__init__(self)
        logging.info("INIT PLAYER DONE")

        #
        # STATES SETUP
        #
        self.on_ground_states = [
            self.STATE_IDLE, self.STATE_IDLE_TO_WALK, self.STATE_WALK,
            self.STATE_WALK_TO_IDLE, self.STATE_PLANT
        ]
        # set the possible transition in the FSM
        self.defaultTransitions = {
            self.STATE_IDLE: [self.STATE_IDLE_TO_WALK, self.STATE_PLANT],
            self.STATE_IDLE_TO_WALK: [self.STATE_IDLE, self.STATE_WALK],
            self.STATE_WALK: [self.STATE_IDLE, self.STATE_WALK_TO_IDLE],
            self.STATE_WALK_TO_IDLE: [self.STATE_IDLE, self.STATE_WALK],
            self.STATE_PLANT: [self.STATE_IDLE],
        }

        #
        # ACTOR SETUP
        #
        Actor.__init__(
            self, self.model, {
                self.IDLE: self.anim_idle,
                self.WALK: self.anim_walk,
                self.PLANT: self.anim_plant,
            })
        self.setBlend(frameBlend=self.enable_interpolation)

        alphaSettings = ColorBlendAttrib.make(ColorBlendAttrib.MAdd,
                                              ColorBlendAttrib.OIncomingAlpha,
                                              ColorBlendAttrib.OOne,
                                              (0, 0, 0, 0))
        #self.setAttrib(alphaSettings)
        self.setBin("fixed", 15)
        self.setDepthWrite(False)

        #
        # CONTROLS SETUP
        #
        self.isDown = base.mouseWatcherNode.isButtonDown
        self.mainNode = self
示例#9
0
文件: sun.py 项目: karlexceed/naith
  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
示例#10
0
def initializeLightCone(np, bin='fixed', sorting=3):
    np.node().setAttrib(
        ColorBlendAttrib.make(ColorBlendAttrib.MAdd,
                              ColorBlendAttrib.OIncomingAlpha,
                              ColorBlendAttrib.OOne))
    if bin:
        np.setBin(bin, sorting)
    np.setDepthWrite(False)
    np.setTwoSided(True, 10000)
示例#11
0
    def __init__(self, name = 'glow', amount = 0, red = 100, green = 100, blue = 100):
        print "Glow enabled!"
        
        ## Glow by Adam Bell ([email protected])
        ## with some original code from Kwasi Mensah ([email protected])
        ## for PandaCamp (code.google.com/p/pandacamp/)
        
        #The shader is important (but yet a variable). 
        
        ## The next part I'll replace with a single file as soon 
        ## as I can work with variables in the *.SHA files.
        
        redd = red / 100
        greend = green / 100
        blued = blue / 100
        
        if amount == 0:
            print "glowShader set to it's default value of 1."
            amount = 1
        
        ## Custom number for a positive non-integer or above 4.
        if amount > 0:
            ### NOTE: the line below is an RGB
            render.setShaderInput('amnt',amount * redd,amount * greend,amount * blued,amount)
            print "glowShader set as " + str(amount) + "!"
            
        if amount < 0:
            raise TypeError('Only positive numbers work for the glowShader!')


        # except that only the glowing materials should show up nonblack.
        base.disableMouse()
        glowBuffer=base.win.makeTextureBuffer("Glow scene", 512, 512)
        glowBuffer.setSort(-3)
        glowBuffer.setClearColor(Vec4(0,0,0,1))
        
        glowCamera=base.makeCamera(glowBuffer, lens=base.cam.node().getLens())
        
        
        # Tell the glow camera to use the glow shader
        tempnode = NodePath(PandaNode("temp node"))
        tempnode.setShader(loader.loadShader('/c/panda/pandacamp/src/shaders/glowShader.sha'))
        ## Was 'Shader.load'
        glowCamera.node().setInitialState(tempnode.getState())
        
        # X and Y shaders to make the earlier "glowShader.sha" work (or effective).
        blurXBuffer=makeFilterBuffer(glowBuffer,  "Blur X", -2, "/c/panda/pandacamp/src/shaders/XBlurShader.sha")
        blurYBuffer=makeFilterBuffer(blurXBuffer, "Blur Y", -1, "/c/panda/pandacamp/src/shaders/YBlurShader.sha")
        self.finalcard = blurYBuffer.getTextureCard()
        self.finalcard.reparentTo(render2d)
        self.finalcard.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd))
        
        # Panda contains a built-in viewer that lets you view the results of
        # your render-to-texture operations.  This code configures the viewer.
        base.bufferViewer.setPosition("llcorner")
        base.bufferViewer.setLayout("hline")
        base.bufferViewer.setCardSize(0.652,0)
示例#12
0
    def build(self, wld_container, f, start_index, n_polys, tex_idx,debug=False):

        
        # f.dump()
        self.sprite_list_index = f.fragment1-1        # the fragment1 ref is used as sprite list index
        sprite = wld_container.getSprite(tex_idx, self.sprite_list_index)
            
        polyList = f.polyList
        poly_idx = start_index
        for poly in range(0, n_polys):
            p = polyList[poly_idx]
            poly_idx += 1
            self.primitives.addVertices(p[0], p[1], p[2])

        self.node = GeomNode(self.name)
        self.node.addGeom(self.geom)
        
        # make a node path for our GEOM, these will be attached under our parent mesh's root
        self.nodePath = NodePath(self.node)
            
        # self.nodePath.setRenderModeWireframe()
        # self.nodePath.setRenderModeFilled()
        # self.nodePath.showBounds()
        
        self.nodePath.setPos(f.centerX, f.centerY,f.centerZ)    # translate to correct position
        self.nodePath.setAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullCounterClockwise))
        # self.nodePath.setAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullClockwise))

        # Texture setup
        if sprite != None:
            # sprite.dump()
            if sprite.numtex > 0:   
                t = sprite.textures[0]
                self.nodePath.setTexture(t)
                if debug:
                    print("    polygroup build had texture count: " + str(sprite.numtex) + " AnimDelay: " + str(sprite.anim_delay))
                patchInvertDDSV(self.nodePath,t,debug)
                if sprite.anim_delay > 0:
                    geom_num = self.node.getNumGeoms()-1
                    if debug:
                        print("Adding geom render state for " + self.name)
                    from panda3d.core import ColorBlendAttrib
                    
                    # seems animated "masked" textrue need this in order to function
                    # dont want to have it on the main zone geoms though cause it breaks
                    # semi trasparent surfaces (water etc). Probably should move away from making those
                    # transparent through color blending and simply patch up their alpha channels as needed?
                    if sprite.masked == 1:
                        self.node.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd,ColorBlendAttrib.OAlphaScale,ColorBlendAttrib.OOne))
                    
                    sprite.addAnimGeomRenderState( (self.node,geom_num,self.node.getGeomState(geom_num),self.name) )
        else:
            print 'Error: texture (idx=%i) not found. PolyGroup will be rendered untextured' % (tex_idx)

        return 1
示例#13
0
 def apply(blend, instance):
     blendAttrib = None
     translucid = False
     if blend == TransparencyBlend.TB_Alpha:
         blendAttrib = ColorBlendAttrib.make(
             ColorBlendAttrib.MAdd, ColorBlendAttrib.O_incoming_alpha,
             ColorBlendAttrib.O_one_minus_incoming_alpha,
             ColorBlendAttrib.M_add, ColorBlendAttrib.O_one,
             ColorBlendAttrib.O_one)
         translucid = True
     elif blend == TransparencyBlend.TB_PremultipliedAlpha:
         blendAttrib = ColorBlendAttrib.make(
             ColorBlendAttrib.MAdd, ColorBlendAttrib.O_one,
             ColorBlendAttrib.O_one_minus_incoming_alpha,
             ColorBlendAttrib.M_add, ColorBlendAttrib.O_one,
             ColorBlendAttrib.O_one)
         translucid = True
     elif blend == TransparencyBlend.TB_Additive:
         blendAttrib = ColorBlendAttrib.make(ColorBlendAttrib.MAdd,
                                             ColorBlendAttrib.O_one,
                                             ColorBlendAttrib.O_one,
                                             ColorBlendAttrib.M_add,
                                             ColorBlendAttrib.O_one,
                                             ColorBlendAttrib.O_one)
         translucid = True
     elif blend == TransparencyBlend.TB_AlphaAdditive:
         blendAttrib = ColorBlendAttrib.make(
             ColorBlendAttrib.MAdd, ColorBlendAttrib.O_one,
             ColorBlendAttrib.O_incoming_alpha, ColorBlendAttrib.M_add,
             ColorBlendAttrib.O_one, ColorBlendAttrib.O_one)
         translucid = True
     elif blend == TransparencyBlend.TB_Saturare:
         blendAttrib = ColorBlendAttrib.make(
             ColorBlendAttrib.MAdd,
             ColorBlendAttrib.O_one_minus_fbuffer_color,
             ColorBlendAttrib.O_one, ColorBlendAttrib.M_add,
             ColorBlendAttrib.O_one, ColorBlendAttrib.O_one)
         translucid = True
     if blendAttrib is not None:
         instance.setAttrib(blendAttrib)
     if translucid:
         instance.setTransparency(TransparencyAttrib.MAlpha)
示例#14
0
    def create(self):
        self.targetCoC = RenderTarget("DOF-CoC")
        self.targetCoC.setColorBits(16)
        self.targetCoC.setAuxBits(16)
        self.targetCoC.addColorTexture()
        self.targetCoC.addAuxTexture()
        self.targetCoC.prepareOffscreenBuffer()

        if False:
            self.targetSpawnSprites = RenderTarget("DOF-Sprites")
            # self.targetSpawnSprites.setHalfResolution()
            self.targetSpawnSprites.addColorTexture()
            self.targetSpawnSprites.setColorBits(16)
            self.targetSpawnSprites.prepareOffscreenBuffer()
            self.targetSpawnSprites.setClearColor(True)

            quad = self.targetSpawnSprites.getQuad()
            quad.setDepthTest(False)
            quad.setDepthWrite(False)
            quad.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd))

            w, h = int(Globals.resolution.x / 1), int(Globals.resolution.y / 1)

            bokehTex = loader.loadTexture("Data/Textures/BokehShape.png")
            bokehTex.setMinfilter(Texture.FTLinear)
            bokehTex.setMagfilter(Texture.FTLinear)
            bokehTex.setWrapU(Texture.WMClamp)
            bokehTex.setWrapV(Texture.WMClamp)
            bokehTex.setAnisotropicDegree(0)
            quad.setShaderInput("bokehTex", bokehTex)
            quad.setShaderInput("sourceTex", self.targetCoC.getColorTexture())
            quad.setInstanceCount(w * h)  # Poor GPU

        self.targetBlurV = RenderTarget("DOF-BlurV")
        self.targetBlurV.setColorBits(16)
        self.targetBlurV.addColorTexture()
        self.targetBlurV.prepareOffscreenBuffer()
        self.targetBlurV.setShaderInput("sourceBlurTex",
                                        self.targetCoC.getAuxTexture(0))

        self.targetBlurH = RenderTarget("DOF-BlurH")
        self.targetBlurH.setColorBits(16)
        self.targetBlurH.addColorTexture()
        self.targetBlurH.prepareOffscreenBuffer()
        self.targetBlurH.setShaderInput("sourceBlurTex",
                                        self.targetBlurV.getColorTexture())

        self.targetCombine = RenderTarget("DOF-Combine")
        self.targetCombine.addColorTexture()
        self.targetCombine.setColorBits(16)
        self.targetCombine.prepareOffscreenBuffer()

        self.targetCombine.setShaderInput("sceneBlurTex",
                                          self.targetBlurH.getColorTexture())
示例#15
0
 def apply(blend, instance):
     blendAttrib = None
     translucid = False
     if blend == TransparencyBlend.TB_None:
         pass
     elif blend == TransparencyBlend.TB_Alpha:
         blendAttrib = ColorBlendAttrib.make(ColorBlendAttrib.MAdd,
                                             ColorBlendAttrib.O_incoming_alpha, ColorBlendAttrib.O_one_minus_incoming_alpha,
                                             ColorBlendAttrib.M_add,
                                             ColorBlendAttrib.O_one, ColorBlendAttrib.O_one_minus_incoming_alpha)
         translucid = True
     elif blend == TransparencyBlend.TB_PremultipliedAlpha:
         blendAttrib = ColorBlendAttrib.make(ColorBlendAttrib.MAdd,
                                             ColorBlendAttrib.O_one, ColorBlendAttrib.O_one_minus_incoming_alpha,
                                             ColorBlendAttrib.M_add,
                                             ColorBlendAttrib.O_one, ColorBlendAttrib.O_one_minus_incoming_alpha)
         translucid = True
     elif blend == TransparencyBlend.TB_Additive:
         blendAttrib = ColorBlendAttrib.make(ColorBlendAttrib.MAdd,
                                             ColorBlendAttrib.O_one, ColorBlendAttrib.O_one,
                                             ColorBlendAttrib.M_add,
                                             ColorBlendAttrib.O_one, ColorBlendAttrib.O_one)
         translucid = False
     elif blend == TransparencyBlend.TB_AlphaAdditive:
         blendAttrib = ColorBlendAttrib.make(ColorBlendAttrib.MAdd,
                                             ColorBlendAttrib.O_one, ColorBlendAttrib.O_incoming_alpha,
                                             ColorBlendAttrib.M_add,
                                             ColorBlendAttrib.O_one, ColorBlendAttrib.O_incoming_alpha)
         translucid = True
     elif blend == TransparencyBlend.TB_Saturate:
         blendAttrib = ColorBlendAttrib.make(ColorBlendAttrib.MAdd,
                                             ColorBlendAttrib.O_one_minus_fbuffer_color, ColorBlendAttrib.O_one,
                                             ColorBlendAttrib.M_add,
                                             ColorBlendAttrib.O_one, ColorBlendAttrib.O_one)
         translucid = True
     else:
         print("Unknown blend mode", blend)
     if blendAttrib is not None:
         instance.setAttrib(blendAttrib)
     if translucid:
         instance.set_bin('transparent', 0)
示例#16
0
 def customize(nodePath):
     volume = nodePath.find("light_volume")
     volume.setTransparency(True)
     volume.setAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullNone))
     volume.setDepthWrite(False)
     volume.setAttrib(
         ColorBlendAttrib.make(ColorBlendAttrib.M_add,
                               ColorBlendAttrib.OIncomingAlpha,
                               ColorBlendAttrib.O_one))
     volume.setShader(
         Shader.load(Shader.SL_GLSL,
                     vertex=Filename("shaders/streetlight.vert"),
                     fragment=Filename("shaders/streetlight.frag")))
示例#17
0
    def create(self):
        self.targetCoC = RenderTarget("DOF-CoC")
        self.targetCoC.setColorBits(16)
        self.targetCoC.setAuxBits(16)
        self.targetCoC.addColorTexture()
        self.targetCoC.addAuxTexture()
        self.targetCoC.prepareOffscreenBuffer()

        if False:
            self.targetSpawnSprites = RenderTarget("DOF-Sprites")
            # self.targetSpawnSprites.setHalfResolution()
            self.targetSpawnSprites.addColorTexture()
            self.targetSpawnSprites.setColorBits(16)
            self.targetSpawnSprites.prepareOffscreenBuffer()
            self.targetSpawnSprites.setClearColor(True)

            quad = self.targetSpawnSprites.getQuad()
            quad.setDepthTest(False)
            quad.setDepthWrite(False)
            quad.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd))

            w, h = int(Globals.resolution.x / 1), int(Globals.resolution.y / 1)

            bokehTex = loader.loadTexture("Data/Textures/BokehShape.png")
            bokehTex.setMinfilter(Texture.FTLinear)
            bokehTex.setMagfilter(Texture.FTLinear)
            bokehTex.setWrapU(Texture.WMClamp)
            bokehTex.setWrapV(Texture.WMClamp)
            bokehTex.setAnisotropicDegree(0)
            quad.setShaderInput("bokehTex", bokehTex)
            quad.setShaderInput("sourceTex", self.targetCoC.getColorTexture())
            quad.setInstanceCount(w * h) # Poor GPU

        self.targetBlurV = RenderTarget("DOF-BlurV")
        self.targetBlurV.setColorBits(16)
        self.targetBlurV.addColorTexture()
        self.targetBlurV.prepareOffscreenBuffer()
        self.targetBlurV.setShaderInput("sourceBlurTex", self.targetCoC.getAuxTexture(0))
        
        self.targetBlurH = RenderTarget("DOF-BlurH")
        self.targetBlurH.setColorBits(16)
        self.targetBlurH.addColorTexture()
        self.targetBlurH.prepareOffscreenBuffer()
        self.targetBlurH.setShaderInput("sourceBlurTex", self.targetBlurV.getColorTexture())
        
        self.targetCombine = RenderTarget("DOF-Combine")
        self.targetCombine.addColorTexture()
        self.targetCombine.setColorBits(16)
        self.targetCombine.prepareOffscreenBuffer()

        self.targetCombine.setShaderInput("sceneBlurTex", self.targetBlurH.getColorTexture())
示例#18
0
    def create_instance(self):
        self.shape.set_radius(self.radius)
        ShapeObject.create_instance(self)
        self.instance.setTransparency(TransparencyAttrib.MAlpha)
        blendAttrib = ColorBlendAttrib.make(ColorBlendAttrib.MAdd,
                                            ColorBlendAttrib.OOne,
                                            self.alpha_mode)
        self.instance.setAttrib(blendAttrib)
        self.instance.setAttrib(
            CullFaceAttrib.make(CullFaceAttrib.MCullCounterClockwise))
        self.instance.set_depth_write(False)

        def create_scattering_shader(self, atmosphere, calc_in_fragment):
            return None
 def load(self):
     Entity.load(self)
     
     entnum = self.cEntity.getBspEntnum()
     loader = base.bspLoader
     
     lightColor = self.getEntityValueColor("_light")
     width = self.getEntityValueFloat("width")
     height = self.getEntityValueFloat("height")
     self.lightGlow = CIGlobals.makeLightGlow((width, 1, height))
     self.lightGlow.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OOne, ColorBlendAttrib.OOne), 1)
     self.lightGlow.reparentTo(self)
     self.lightGlow.setTwoSided(True)
     self.lightGlow.setColorScale(lightColor, 1)
     
     self.reparentTo(render)
     self.setPos(self.cEntity.getOrigin())
示例#20
0
    def __init__(self, size, shaderName, shaderInputs, inputTextureName,
                 randomVal1, randomVal2):
        self.explosionCard = Explosion.getCard()
        self.explosionCard.setScale(size)
        self.explosionCard.setBin("unsorted", 1)
        self.explosionCard.setDepthWrite(False)
        self.explosionCard.setAttrib(
            ColorBlendAttrib.make(ColorBlendAttrib.MAdd,
                                  ColorBlendAttrib.OIncomingAlpha,
                                  ColorBlendAttrib.OOne))
        self.explosionCard.setBillboardPointEye()

        shader = Shader.load(
            Shader.SL_GLSL,
            "../Section2SpaceflightDocking/Shaders/{0}Vertex.glsl".format(
                shaderName),
            "../Section2SpaceflightDocking/Shaders/{0}Fragment.glsl".format(
                shaderName))
        self.explosionCard.setShader(shader)

        for inputName, inputValue in shaderInputs.items():
            self.explosionCard.setShaderInput(inputName, inputValue)

        self.explosionCard.setShaderInput(
            "sourceTex1",
            Common.framework.showBase.loader.loadTexture(
                "../Section2SpaceflightDocking/Shaders/{0}1.png".format(
                    inputTextureName)))
        self.explosionCard.setShaderInput(
            "sourceTex2",
            Common.framework.showBase.loader.loadTexture(
                "../Section2SpaceflightDocking/Shaders/{0}2.png".format(
                    inputTextureName)))

        self.explosionCard.setShaderInput("randomisation1", randomVal1)
        self.explosionCard.setShaderInput("randomisation2", randomVal2)

        self.calcFullDuration(shaderInputs)

        self.startTime = -1000
        self.explosionCard.setShaderInput("startTime", self.startTime)

        self.velocity = Vec3(0, 0, 0)
示例#21
0
    def create(self):
        self.target = RenderTarget("ApplyLights")
        self.target.addColorTexture()
        self.target.setColorBits(16)
        self.target.prepareOffscreenBuffer()
        self.target.setClearColor(True)

        self.target.getQuad().removeNode()
        self.target.getNode().setAttrib(
            TransparencyAttrib.make(TransparencyAttrib.MNone), 1000)
        self.target.getNode().setAttrib(
            ColorBlendAttrib.make(ColorBlendAttrib.MAdd), 1000)

        self.quads = {}

        numInstances = self.tileCount.x * self.tileCount.y

        for lightType in ["DirectionalLightShadow"]:
            cm = CardMaker("BufferQuad-" + lightType)
            cm.setFrameFullscreenQuad()
            quad = NodePath(cm.generate())
            quad.setDepthTest(0)
            quad.setDepthWrite(0)
            quad.setAttrib(TransparencyAttrib.make(TransparencyAttrib.MNone),
                           1000)
            quad.setColor(Vec4(1, 0.5, 0.5, 1))

            # Disable culling
            quad.node().setFinal(True)
            quad.node().setBounds(OmniBoundingVolume())
            quad.setBin("unsorted", 10)
            quad.setInstanceCount(numInstances)

            quad.reparentTo(self.target.getNode())

            self.quads[lightType] = quad

        self.target.getNode().setShaderInput("tileCount", self.tileCount)
示例#22
0
    def setup_glow_shader(self):
        glow_shader = self.base.loader.loadShader("shader/glowShader.cg")
        glow_buffer = self.base.win.makeTextureBuffer("Glow scene", 512, 512)
        glow_buffer.setSort(-3)
        glow_buffer.setClearColor(Vec4(0, 0, 0, 1))
        self.glowcam = self.base.makeCamera(
            glow_buffer, lens=self.base.cam.node().getLens())
        tempnode = NodePath(PandaNode("temp node"))
        tempnode.setShader(glow_shader)
        self.glowcam.node().setInitialState(tempnode.getState())
        self.glowcam.reparentTo(self.base.camera)
        blurXBuffer = self.makeFilterBuffer(glow_buffer, "Blur X", -2,
                                            "shader/XBlurShader.cg")
        blurYBuffer = self.makeFilterBuffer(blurXBuffer, "Blur Y", -1,
                                            "shader/YBlurShader.cg")
        self.finalcard = blurYBuffer.getTextureCard()
        self.finalcard.reparentTo(self.base.render2d)
        self.finalcard.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd))

        self.base.accept("v", self.base.bufferViewer.toggleEnable)
        self.base.accept("V", self.base.bufferViewer.toggleEnable)
        self.base.bufferViewer.setPosition("llcorner")
        self.base.bufferViewer.setLayout("hline")
        self.base.bufferViewer.setCardSize(0.652, 0)
示例#23
0
    def makeRealProjectileFromTemplate(template, projectilePosition):
        result = template.__class__(template.modelName,
                                    template.mask,
                                    template.range,
                                    template.damage,
                                    template.maxSpeed,
                                    template.size,
                                    template.knockback,
                                    template.flinchValue,
                                    template.aoeRadius,
                                    template.blastModelFile,
                                    pos=projectilePosition,
                                    damageByTime=template.damageByTime)

        result.root.setAttrib(
            ColorBlendAttrib.make(ColorBlendAttrib.MAdd,
                                  ColorBlendAttrib.OIncomingAlpha,
                                  ColorBlendAttrib.OOne))
        result.root.setBin("unsorted", 1)
        result.root.setDepthWrite(False)

        result.generateCollisionObject()

        return result
    def makePropAttackTrack(self):
        prop = BattleProps.globalPropPool.getProp(self.attackProp)
        propIsActor = True
        animName = 'throw-paper'
        x, y, z, h, p, r = (0.1, 0.2, -0.35, 0, 336, 0)
        if self.attackProp == 'redtape':
            animName = 'throw-object'
            x, y, z, h, p, r = (0.24, 0.09, -0.38, -1.152, 86.581, -76.784)
            propIsActor = False
        elif self.attackProp == 'newspaper':
            animName = 'throw-object'
            propIsActor = False
            x, y, z, h, p, r = (-0.07, 0.17, -0.13, 161.867, -33.149, -48.086)
            prop.setScale(4)
        elif self.attackProp == 'pink-slip':
            animName = 'throw-paper'
            propIsActor = False
            x, y, z, h, p, r = (0.07, -0.06, -0.18, -172.075, -26.715, -89.131)
            prop.setScale(5)
        elif self.attackProp == 'power-tie':
            animName = 'throw-paper'
            propIsActor = False
            x, y, z, h, p, r = (1.16, 0.24, 0.63, 171.561, 1.745, -163.443)
            prop.setScale(4)
        elif self.attackProp == 'baseball':
            animName = 'throw-object'
            propIsActor = False
            x, y, z, h, p, r = (0.04, 0.03, -0.31, 0, 336, 0)
            prop.setScale(4)
        elif self.attackProp == 'teeth':
            animName = 'throw-object'
            propIsActor = True
            x, y, z, h, p, r = -0.05, 0.41, -0.54, 4.465, -3.563, 51.479
            prop.setScale(3)
        elif self.attackProp == 'golf-ball':
            propIsActor = False
            x, y, z = self.getGolfStartPoint()
            h, p, r = 0, 0, 0
            prop.setScale(1.5)

        # Make prop virtual:
        prop.setColorScale(1.0, 0.0, 0.0, 0.8)
        prop.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd))

        # Prop collisions:
        colNode = CollisionNode(self.uniqueName('SuitAttack'))
        colNode.setTag('damage', str(self.attackInfo[1]))

        bounds = prop.getBounds()
        center = bounds.getCenter()
        radius = bounds.getRadius()
        sphere = CollisionSphere(center.getX(), center.getY(), center.getZ(), radius)
        sphere.setTangible(0)
        colNode.addSolid(sphere)
        colNode.setIntoCollideMask(WallBitmask)
        prop.attachNewNode(colNode)

        toonId = self.toon

        toon = base.cr.doId2do.get(toonId)
        if not toon:
            return

        self.virtualSuit.lookAt(toon)

        if self.virtualSuit.style.body in ['a', 'b']:
            throwDelay = 3
        elif self.virtualSuit.style.body == 'c':
            throwDelay = 2.3
        else:
            throwDelay = 2

        def throwProp():
            if not self.virtualSuit:
                return

            toon = self.cr.doId2do.get(toonId)
            if not toon:
                self.cleanupProp(prop, propIsActor)
                self.finishPropAttack()
                return

            self.virtualSuit.lookAt(toon)

            prop.wrtReparentTo(render)

            hitPos = toon.getPos() + Vec3(0, 0, 2.5)
            distance = (prop.getPos() - hitPos).length()
            speed = 50.0
            if self.attackProp == 'golf-ball':
                speed *= 2

            if self.attackProp == 'teeth':
                throwSequence = Sequence(
                    Parallel(
                        prop.posInterval(distance / speed, hitPos),
                        ActorInterval(prop, 'teeth', duration=distance / speed),
                    ),
                    Func(self.cleanupProp, prop, propIsActor),
                )
            else:
                throwSequence = Sequence(
                    prop.posInterval(distance / speed, hitPos),
                    Func(self.cleanupProp, prop, propIsActor)
                )

            throwSequence.start()

        if self.attackProp == 'golf-ball':
            club = BattleProps.globalPropPool.getProp('golf-club')
            club.setScale(1.1)
            track = Sequence(
                Parallel(
                    Track(
                        (0.4, Func(club.reparentTo, self.virtualSuit.getRightHand())),
                        (0.0, Func(club.setPosHpr, 0.0, 0.0, 0.0, 63.097, 43.988, -18.435)),
                        (0.0, Func(prop.reparentTo, self.virtualSuit)),
                        (0.0, Func(prop.setPosHpr, x, y, z, h, p, r)),
                        (0.0, Func(self.sayFaceoffTaunt)),
                        (0.1, Sequence(
                            ActorInterval(self.virtualSuit, 'golf-club-swing'),
                            Func(self.virtualSuit.loop, 'neutral', 0))
                         ),
                        (4.1, SoundInterval(self.teeOffSfx, node=self.virtualSuit)),
                        (throwDelay + 1.5, Func(throwProp)),
                        (throwDelay + 2, Func(club.removeNode)),
                        (throwDelay + 3, Func(self.finishPropAttack))
                    ),
                ),
                Func(self.virtualSuit.setHpr, 0, 0, 0),
                Func(self.virtualSuit.loop, 'walk', 0),
            )
        else:
            track = Sequence(
                Parallel(
                    Sequence(
                        ActorInterval(self.virtualSuit, animName),
                        Func(self.virtualSuit.loop, 'neutral', 0)
                    ),
                    Track(
                        (0.4, Func(prop.reparentTo, self.virtualSuit.getRightHand())),
                        (0.0, Func(prop.setPosHpr, x, y, z, h, p, r)),
                        (0.0, Func(self.sayFaceoffTaunt)),
                        (throwDelay, Func(throwProp)),
                        (throwDelay + 2, Func(self.finishPropAttack))
                    ),
                ),
                Func(self.virtualSuit.setHpr, 0, 0, 0),
                Func(self.virtualSuit.loop, 'walk', 0),
            )
        track.prop = prop
        track.propIsActor = propIsActor

        return track
示例#25
0
    def __init__(self):
        # Initialize the ShowBase class from which we inherit, which will
        # create a window and set up everything we need for rendering into it.
        ShowBase.__init__(self)
        self.setBackgroundColor((0, 0, 0, 0))

        # Preliminary capabilities check.

        if not self.win.getGsg().getSupportsBasicShaders():
            self.t = addTitle("Firefly Demo: Video driver reports that Cg "
                              "shaders are not supported.")
            return
        if not self.win.getGsg().getSupportsDepthTexture():
            self.t = addTitle("Firefly Demo: Video driver reports that depth "
                              "textures are not supported.")
            return

        # This algorithm uses two offscreen buffers, one of which has
        # an auxiliary bitplane, and the offscreen buffers share a single
        # depth buffer.  This is a heck of a complicated buffer setup.

        self.modelbuffer = self.makeFBO("model buffer", 1)
        self.lightbuffer = self.makeFBO("light buffer", 0)

        # Creation of a high-powered buffer can fail, if the graphics card
        # doesn't support the necessary OpenGL extensions.

        if self.modelbuffer is None or self.lightbuffer is None:
            self.t = addTitle("Toon Shader: Video driver does not support "
                              "multiple render targets")
            return

        # Create four render textures: depth, normal, albedo, and final.
        # attach them to the various bitplanes of the offscreen buffers.

        self.texDepth = Texture()
        self.texDepth.setFormat(Texture.FDepthStencil)
        self.texAlbedo = Texture()
        self.texNormal = Texture()
        self.texFinal = Texture()

        self.modelbuffer.addRenderTexture(self.texDepth,
            GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPDepthStencil)
        self.modelbuffer.addRenderTexture(self.texAlbedo,
            GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPColor)
        self.modelbuffer.addRenderTexture(self.texNormal,
            GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPAuxRgba0)

        self.lightbuffer.addRenderTexture(self.texFinal,
            GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPColor)

        # Set the near and far clipping planes.

        self.cam.node().getLens().setNear(50.0)
        self.cam.node().getLens().setFar(500.0)
        lens = self.cam.node().getLens()

        # This algorithm uses three cameras: one to render the models into the
        # model buffer, one to render the lights into the light buffer, and
        # one to render "plain" stuff (non-deferred shaded) stuff into the
        # light buffer.  Each camera has a bitmask to identify it.

        self.modelMask = 1
        self.lightMask = 2
        self.plainMask = 4

        self.modelcam = self.makeCamera(self.modelbuffer,
            lens=lens, scene=render, mask=self.modelMask)
        self.lightcam = self.makeCamera(self.lightbuffer,
            lens=lens, scene=render, mask=self.lightMask)
        self.plaincam = self.makeCamera(self.lightbuffer,
            lens=lens, scene=render, mask=self.plainMask)

        # Panda's main camera is not used.

        self.cam.node().setActive(0)

        # Take explicit control over the order in which the three
        # buffers are rendered.

        self.modelbuffer.setSort(1)
        self.lightbuffer.setSort(2)
        self.win.setSort(3)

        # Within the light buffer, control the order of the two cams.

        self.lightcam.node().getDisplayRegion(0).setSort(1)
        self.plaincam.node().getDisplayRegion(0).setSort(2)

        # By default, panda usually clears the screen before every
        # camera and before every window.  Tell it not to do that.
        # Then, tell it specifically when to clear and what to clear.

        self.modelcam.node().getDisplayRegion(0).disableClears()
        self.lightcam.node().getDisplayRegion(0).disableClears()
        self.plaincam.node().getDisplayRegion(0).disableClears()
        self.cam.node().getDisplayRegion(0).disableClears()
        self.cam2d.node().getDisplayRegion(0).disableClears()
        self.modelbuffer.disableClears()
        self.win.disableClears()

        self.modelbuffer.setClearColorActive(1)
        self.modelbuffer.setClearDepthActive(1)
        self.lightbuffer.setClearColorActive(1)
        self.lightbuffer.setClearColor((0, 0, 0, 1))

        # Miscellaneous stuff.

        self.disableMouse()
        self.camera.setPos(-9.112, -211.077, 46.951)
        self.camera.setHpr(0, -7.5, 2.4)
        random.seed()

        # Calculate the projection parameters for the final shader.
        # The math here is too complex to explain in an inline comment,
        # I've put in a full explanation into the HTML intro.

        proj = self.cam.node().getLens().getProjectionMat()
        proj_x = 0.5 * proj.getCell(3, 2) / proj.getCell(0, 0)
        proj_y = 0.5 * proj.getCell(3, 2)
        proj_z = 0.5 * proj.getCell(3, 2) / proj.getCell(2, 1)
        proj_w = -0.5 - 0.5 * proj.getCell(1, 2)

        # Configure the render state of the model camera.

        tempnode = NodePath(PandaNode("temp node"))
        tempnode.setAttrib(
            AlphaTestAttrib.make(RenderAttrib.MGreaterEqual, 0.5))
        tempnode.setShader(loader.loadShader("model.sha"))
        tempnode.setAttrib(DepthTestAttrib.make(RenderAttrib.MLessEqual))
        self.modelcam.node().setInitialState(tempnode.getState())

        # Configure the render state of the light camera.

        tempnode = NodePath(PandaNode("temp node"))
        tempnode.setShader(loader.loadShader("light.sha"))
        tempnode.setShaderInput("texnormal", self.texNormal)
        tempnode.setShaderInput("texalbedo", self.texAlbedo)
        tempnode.setShaderInput("texdepth", self.texDepth)
        tempnode.setShaderInput("proj", (proj_x, proj_y, proj_z, proj_w))
        tempnode.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd,
            ColorBlendAttrib.OOne, ColorBlendAttrib.OOne))
        tempnode.setAttrib(
            CullFaceAttrib.make(CullFaceAttrib.MCullCounterClockwise))
        # The next line causes problems on Linux.
        # tempnode.setAttrib(DepthTestAttrib.make(RenderAttrib.MGreaterEqual))
        tempnode.setAttrib(DepthWriteAttrib.make(DepthWriteAttrib.MOff))
        self.lightcam.node().setInitialState(tempnode.getState())

        # Configure the render state of the plain camera.

        rs = RenderState.makeEmpty()
        self.plaincam.node().setInitialState(rs)

        # Clear any render attribs on the root node. This is necessary
        # because by default, panda assigns some attribs to the root
        # node.  These default attribs will override the
        # carefully-configured render attribs that we just attached
        # to the cameras.  The simplest solution is to just clear
        # them all out.

        render.setState(RenderState.makeEmpty())

        # My artist created a model in which some of the polygons
        # don't have textures.  This confuses the shader I wrote.
        # This little hack guarantees that everything has a texture.

        white = loader.loadTexture("models/white.jpg")
        render.setTexture(white, 0)

        # Create two subroots, to help speed cull traversal.

        self.lightroot = NodePath(PandaNode("lightroot"))
        self.lightroot.reparentTo(render)
        self.modelroot = NodePath(PandaNode("modelroot"))
        self.modelroot.reparentTo(render)
        self.lightroot.hide(BitMask32(self.modelMask))
        self.modelroot.hide(BitMask32(self.lightMask))
        self.modelroot.hide(BitMask32(self.plainMask))

        # Load the model of a forest.  Make it visible to the model camera.
        # This is a big model, so we load it asynchronously while showing a
        # load text.  We do this by passing in a callback function.
        self.loading = addTitle("Loading models...")

        self.forest = NodePath(PandaNode("Forest Root"))
        self.forest.reparentTo(render)
        self.forest.hide(BitMask32(self.lightMask | self.plainMask))
        loader.loadModel([
            "models/background",
            "models/foliage01",
            "models/foliage02",
            "models/foliage03",
            "models/foliage04",
            "models/foliage05",
            "models/foliage06",
            "models/foliage07",
            "models/foliage08",
            "models/foliage09"],
            callback=self.finishLoading)

        # Cause the final results to be rendered into the main window on a
        # card.

        self.card = self.lightbuffer.getTextureCard()
        self.card.setTexture(self.texFinal)
        self.card.reparentTo(render2d)

        # Panda contains a built-in viewer that lets you view the results of
        # your render-to-texture operations.  This code configures the viewer.

        self.bufferViewer.setPosition("llcorner")
        self.bufferViewer.setCardSize(0, 0.40)
        self.bufferViewer.setLayout("vline")
        self.toggleCards()
        self.toggleCards()

        # Firefly parameters

        self.fireflies = []
        self.sequences = []
        self.scaleseqs = []
        self.glowspheres = []
        self.fireflysize = 1.0
        self.spheremodel = loader.loadModel("misc/sphere")

        # Create the firefly model, a fuzzy dot
        dotSize = 1.0
        cm = CardMaker("firefly")
        cm.setFrame(-dotSize, dotSize, -dotSize, dotSize)
        self.firefly = NodePath(cm.generate())
        self.firefly.setTexture(loader.loadTexture("models/firefly.png"))
        self.firefly.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.M_add,
            ColorBlendAttrib.O_incoming_alpha, ColorBlendAttrib.O_one))

        # these allow you to change parameters in realtime

        self.accept("escape", sys.exit, [0])
        self.accept("arrow_up",   self.incFireflyCount, [1.1111111])
        self.accept("arrow_down", self.decFireflyCount, [0.9000000])
        self.accept("arrow_right", self.setFireflySize, [1.1111111])
        self.accept("arrow_left",  self.setFireflySize, [0.9000000])
        self.accept("v", self.toggleCards)
        self.accept("V", self.toggleCards)
    def makeWriteOffTrack(self):
        pad = BattleProps.globalPropPool.getProp('pad')
        pad.setScale(1.89)
        pencil = BattleProps.globalPropPool.getProp('pencil')
        BattleParticles.loadParticles()
        checkmark = copyProp(BattleParticles.getParticle('checkmark'))
        checkmark.setBillboardPointEye()

        # Make prop virtual:
        pad.setColorScale(1.0, 0.0, 0.0, 0.8)
        pad.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd))
        pencil.setColorScale(1.0, 0.0, 0.0, 0.8)
        pencil.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd))
        checkmark.setColorScale(1.0, 0.0, 0.0, 0.8)
        checkmark.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd))

        # Prop collisions:
        colNode = CollisionNode(self.uniqueName('SuitAttack'))
        colNode.setTag('damage', str(self.attackInfo[1]))

        bounds = checkmark.getBounds()
        center = bounds.getCenter()
        radius = bounds.getRadius()
        sphere = CollisionSphere(center.getX(), center.getY(), center.getZ(), radius)
        sphere.setTangible(0)
        colNode.addSolid(sphere)
        colNode.setIntoCollideMask(WallBitmask)
        checkmark.attachNewNode(colNode)

        toonId = self.toon

        toon = base.cr.doId2do.get(toonId)
        if not toon:
            return

        self.virtualSuit.lookAt(toon)

        if self.virtualSuit.style.body in ['a', 'b']:
            throwDelay = 3
        elif self.virtualSuit.style.body == 'c':
            throwDelay = 2.3
        else:
            throwDelay = 2

        def throwProp():
            if not self.virtualSuit:
                return

            toon = self.cr.doId2do.get(toonId)
            if not toon:
                self.cleanupProp(checkmark, False)
                self.finishPropAttack()
                return

            self.virtualSuit.lookAt(toon)

            checkmark.wrtReparentTo(render)

            hitPos = toon.getPos() + Vec3(0, 0, 2.5)
            distance = (checkmark.getPos() - hitPos).length()
            speed = 50.0

            if self.attackProp == 'teeth':
                throwSequence = Sequence(
                    Parallel(
                        checkmark.posInterval(distance / speed, hitPos),
                        ActorInterval(checkmark, 'teeth', duration=distance / speed),
                    ),
                    Func(self.cleanupProp, checkmark, False),
                )
            else:
                throwSequence = Sequence(
                    checkmark.posInterval(distance / speed, hitPos),
                    Func(self.cleanupProp, checkmark, False)
                )

            throwSequence.start()

        pencilTrack = Sequence(
            Wait(0.5),
            Func(pencil.setPosHpr, -0.47, 1.08, 0.28, 21.045, 12.702, -176.374),
            Func(pencil.reparentTo, self.virtualSuit.getRightHand()),
            LerpScaleInterval(pencil, 0.5, Point3(1.5, 1.5, 1.5),
                              startScale=Point3(0.01)),
            Wait(throwDelay),
            Func(checkmark.reparentTo, render),
            Func(checkmark.setScale, 1.6),
            Func(checkmark.setPosHpr, pencil, 0, 0, 0, 0, 0, 0),
            Func(checkmark.setP, 0),
            Func(checkmark.setR, 0),
            Func(throwProp),
            Wait(0.3),
            LerpScaleInterval(pencil, 0.5, Point3(0.01, 0.01, 0.01)),
            Func(pencil.removeNode),
        )

        suitTrack = Sequence(
            ActorInterval(self.virtualSuit, 'hold-pencil'),
            Func(self.virtualSuit.loop, 'neutral', 0),
        )

        soundTrack = Sequence(
            Wait(2.3),
            SoundInterval(self.writeOffSfx, duration=0.9, node=self.virtualSuit),
            SoundInterval(self.dingSfx, node=self.virtualSuit)
        )

        padTrack = Track(
            (0.0, Func(pad.setPosHpr, -0.25, 1.38, -0.08, -19.078, -6.603, -171.594)),
            (0.4, Func(pad.reparentTo, self.virtualSuit.getLeftHand())),
            (3.0, Func(pad.removeNode)),
        )

        track = Sequence(
            Parallel(
                suitTrack, soundTrack, padTrack, pencilTrack, Func(self.sayFaceoffTaunt)
            ),
            Func(self.virtualSuit.loop, 'walk', 0)
        )
        return track
    def makeCrunchTrack(self):
        toonId = self.toon

        toon = base.cr.doId2do.get(toonId)
        if not toon:
            return

        self.virtualSuit.lookAt(toon)

        if self.virtualSuit.style.body in ['a', 'b']:
            throwDelay = 3
        elif self.virtualSuit.style.body == 'c':
            throwDelay = 2.3
        else:
            throwDelay = 2

        numberNames = ['one',
         'two',
         'three',
         'four',
         'five',
         'six']
        BattleParticles.loadParticles()
        numberSpill1 = BattleParticles.createParticleEffect(file='numberSpill')
        numberSpill2 = BattleParticles.createParticleEffect(file='numberSpill')
        spillTexture1 = random.choice(numberNames)
        spillTexture2 = random.choice(numberNames)
        BattleParticles.setEffectTexture(numberSpill1, 'audit-' + spillTexture1)
        BattleParticles.setEffectTexture(numberSpill2, 'audit-' + spillTexture2)
        numberSpillTrack1 = getPartTrack(numberSpill1, 1.1, 2.2, [numberSpill1, self.virtualSuit, 0])
        numberSpillTrack2 = getPartTrack(numberSpill2, 1.5, 1.0, [numberSpill2, self.virtualSuit, 0])
        numberSprayTracks = Parallel()
        numOfNumbers = random.randint(5, 9)
        for i in xrange(0, numOfNumbers - 1):
            nextSpray = BattleParticles.createParticleEffect(file='numberSpray')
            nextTexture = random.choice(numberNames)
            BattleParticles.setEffectTexture(nextSpray, 'audit-' + nextTexture)
            nextStartTime = random.random() * 0.6 + 3.03
            nextDuration = random.random() * 0.4 + 1.4
            nextSprayTrack = getPartTrack(nextSpray, nextStartTime, nextDuration, [nextSpray, self.virtualSuit, 0])
            numberSprayTracks.append(nextSprayTrack)

        def throwProp(prop):
            if not self.virtualSuit:
                return

            toon = self.cr.doId2do.get(toonId)
            if not toon:
                self.cleanupProp(prop, False)
                self.finishPropAttack()
                return

            self.virtualSuit.lookAt(toon)

            prop.wrtReparentTo(render)

            hitPos = toon.getPos() + Vec3(0, 0, 2.5)
            distance = (prop.getPos() - hitPos).length()
            speed = 50.0

            throwSequence = Sequence(
                prop.posInterval(distance / speed, hitPos),
                Func(self.cleanupProp, prop, False)
            )

            throwSequence.start()

        numberTracks = Parallel()
        for i in xrange(0, numOfNumbers):
            texture = random.choice(numberNames)
            next = copyProp(BattleParticles.getParticle('audit-' + texture))
            next.reparentTo(self.virtualSuit.getRightHand())
            next.setScale(0.01, 0.01, 0.01)
            next.setColor(Vec4(0.0, 0.0, 0.0, 1.0))
            next.setPos(random.random() * 0.6 - 0.3, random.random() * 0.6 - 0.3, random.random() * 0.6 - 0.3)
            next.setHpr(VBase3(-1.15, 86.58, -76.78))

            # Make prop virtual:
            next.setColorScale(1.0, 0.0, 0.0, 0.8)
            next.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd))

            # Prop collisions:
            colNode = CollisionNode(self.uniqueName('SuitAttack'))
            colNode.setTag('damage', str(self.attackInfo[1]))

            bounds = next.getBounds()
            center = bounds.getCenter()
            radius = bounds.getRadius()
            sphere = CollisionSphere(center.getX(), center.getY(), center.getZ(), radius)
            sphere.setTangible(0)
            colNode.addSolid(sphere)
            colNode.setIntoCollideMask(WallBitmask)
            next.attachNewNode(colNode)

            numberTrack = Sequence(
                Wait(throwDelay),
                Parallel(
                    LerpScaleInterval(next, 0.6, Point3(1.0, 1.0, 1.0)),
                    Func(throwProp, next),
                ),
            )
            numberTracks.append(numberTrack)

            suitTrack = Parallel(
                    Func(self.sayFaceoffTaunt),
                    Sequence(
                        ActorInterval(self.virtualSuit, 'throw-object'),
                        ActorInterval(self.virtualSuit, 'neutral')
                    ),
            )

            return Sequence(
                Parallel(
                    suitTrack,
                    numberSpillTrack1,
                    numberSpillTrack2,
                    numberTracks,
                    numberSprayTracks
                ),
                Func(self.virtualSuit.loop, 'walk', 0),
                Func(self.virtualSuit.setHpr, 0, 0, 0),
            )
示例#28
0
    def __init__(self,
                 tex,
                 stim_angles=(0, 0),
                 strip_angle=0,
                 position=(0, 0),
                 velocities=(0, 0),
                 strip_width=4,
                 fps=30,
                 window_size=None,
                 window_name='BinocularDrift',
                 profile_on=False):
        super().__init__()
        self.tex = tex
        if window_size == None:
            self.window_size = tex.texture_size
        else:
            self.window_size = window_size
        self.mask_position_card = position
        self.mask_position_uv = (utils.card2uv(self.mask_position_card[0]),
                                 utils.card2uv(self.mask_position_card[1]))
        self.scale = np.sqrt(
            8)  #so it can handle arbitrary rotations and shifts
        self.left_texture_angle = stim_angles[0]
        self.right_texture_angle = stim_angles[1]
        self.left_velocity = velocities[0]
        self.right_velocity = velocities[1]
        self.strip_angle = strip_angle  #this will change fairly frequently
        self.fps = fps
        self.window_name = window_name
        self.profile_on = profile_on

        #Set window title and size
        self.window_properties = WindowProperties()
        self.window_properties.setSize(self.window_size, self.window_size)
        self.window_properties.setTitle(self.window_name)
        ShowBaseGlobal.base.win.requestProperties(
            self.window_properties)  #base is a panda3d global

        #CREATE MASK ARRAYS
        self.left_mask_array = 255 * np.ones(
            (self.tex.texture_size, self.tex.texture_size), dtype=np.uint8)
        self.left_mask_array[:, self.tex.texture_size // 2 -
                             strip_width // 2:] = 0
        self.right_mask_array = 255 * np.ones(
            (self.tex.texture_size, self.tex.texture_size), dtype=np.uint8)
        self.right_mask_array[:, :self.tex.texture_size // 2 +
                              strip_width // 2] = 0

        #TEXTURE STAGES FOR LEFT CARD
        self.left_texture_stage = TextureStage('left_texture_stage')
        #Mask
        self.left_mask = Texture("left_mask_texture")
        self.left_mask.setup2dTexture(self.tex.texture_size,
                                      self.tex.texture_size,
                                      Texture.T_unsigned_byte,
                                      Texture.F_luminance)
        self.left_mask.setRamImage(self.left_mask_array)
        self.left_mask_stage = TextureStage('left_mask_array')
        #Multiply the texture stages together
        self.left_mask_stage.setCombineRgb(TextureStage.CMModulate,
                                           TextureStage.CSTexture,
                                           TextureStage.COSrcColor,
                                           TextureStage.CSPrevious,
                                           TextureStage.COSrcColor)

        #TEXTURE STAGES FOR RIGHT CARD
        self.right_texture_stage = TextureStage('right_texture_stage')
        #Mask
        self.right_mask = Texture("right_mask_texture")
        self.right_mask.setup2dTexture(self.tex.texture_size,
                                       self.tex.texture_size,
                                       Texture.T_unsigned_byte,
                                       Texture.F_luminance)
        self.right_mask.setRamImage(self.right_mask_array)
        self.right_mask_stage = TextureStage('right_mask_stage')
        #Multiply the texture stages together
        self.right_mask_stage.setCombineRgb(TextureStage.CMModulate,
                                            TextureStage.CSTexture,
                                            TextureStage.COSrcColor,
                                            TextureStage.CSPrevious,
                                            TextureStage.COSrcColor)

        #CREATE CARDS/SCENEGRAPH
        cm = CardMaker('stimcard')
        cm.setFrameFullscreenQuad()
        #self.setBackgroundColor((0,0,0,1))
        self.left_card = self.aspect2d.attachNewNode(cm.generate())
        self.right_card = self.aspect2d.attachNewNode(cm.generate())
        self.left_card.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.M_add))
        self.right_card.setAttrib(ColorBlendAttrib.make(
            ColorBlendAttrib.M_add))

        #ADD TEXTURE STAGES TO CARDS
        self.left_card.setTexture(self.left_texture_stage, self.tex.texture)
        self.left_card.setTexture(self.left_mask_stage, self.left_mask)
        self.right_card.setTexture(self.right_texture_stage, self.tex.texture)
        self.right_card.setTexture(self.right_mask_stage, self.right_mask)
        self.setBackgroundColor(
            (0, 0, 0, 1))  # without this the cards will appear washed out

        #TRANSFORMS
        #Masks
        self.mask_transform = self.trs_transform()
        self.left_card.setTexTransform(self.left_mask_stage,
                                       self.mask_transform)
        self.right_card.setTexTransform(self.right_mask_stage,
                                        self.mask_transform)
        #Left texture
        self.left_card.setTexScale(self.left_texture_stage, 1 / self.scale)
        self.left_card.setTexRotate(self.left_texture_stage,
                                    self.left_texture_angle)
        #Right texture
        self.right_card.setTexScale(self.right_texture_stage, 1 / self.scale)
        self.right_card.setTexRotate(self.right_texture_stage,
                                     self.right_texture_angle)

        #Set dynamic transforms
        if self.left_velocity != 0 and self.right_velocity != 0:
            self.taskMgr.add(self.textures_update, "move_both")
        elif self.left_velocity != 0 and self.right_velocity == 0:
            self.taskMgr.add(self.left_texture_update, "move_left")
        elif self.left_velocity == 0 and self.right_velocity != 0:
            self.taskMgr.add(self.right_texture_update, "move_right")

        # Set frame rate
        ShowBaseGlobal.globalClock.setMode(ClockObject.MLimited)
        ShowBaseGlobal.globalClock.setFrameRate(
            self.fps)  #can lock this at whatever

        #Set up profiling if desired
        if profile_on:
            PStatClient.connect()  # this will only work if pstats is running
            ShowBaseGlobal.base.setFrameRateMeter(True)  #Show frame rate
            # Following will show a small x at the center
            self.title = OnscreenText("x",
                                      style=1,
                                      fg=(1, 1, 1, 1),
                                      bg=(0, 0, 0, .8),
                                      pos=self.mask_position_card,
                                      scale=0.05)
示例#29
0
    def levelDone(self, model):
        self.level = model
        self.level.hide()
        self.level.reparentTo(render)
        self.level.setPos(0, 0, -2)

    	# lights for this world
    	directLight = DirectionalLight("directLight")
    	directLightNP = self.level.attachNewNode(directLight)
    	directLightNP.setHpr(0, -60, 0)
    	render.setLight(directLightNP)

        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(VBase4(0.2, 0.2, 0.2, 1))
        ambientLightNP = self.level.attachNewNode(ambientLight)
        render.setLight(ambientLightNP)

        # spawn NPCs
        self.numNPCs = 15
        self.npcList = []
        for i in range(self.numNPCs):
            npc = Actor(
                "character/character",
                {"Idle": "character/character-Idle"})
            npc.setBlend(frameBlend=True)
            npc.setScale(random.uniform(0.4, 1.0))
            npc.loop("Idle")
            point = self.level.find("**/NPC.%03d"%i)
            npc.reparentTo(point)
            self.npcList.append(npc)

        #
        # Fix alpha problems
        #
        alphaSettings = ColorBlendAttrib.make(
            ColorBlendAttrib.MAdd,
            ColorBlendAttrib.OIncomingAlpha,
            ColorBlendAttrib.OOne,
            (0, 0, 0, 0))
        for np in self.level.findAllMatches("**/Godray*"):
            np.setAttrib(alphaSettings)
            np.setBin("fixed", 10)
            np.setDepthWrite(False)
        water = self.level.find("**/Water")
        water.setAttrib(alphaSettings)
        water.setBin("fixed", 11)
        water.setDepthWrite(False)

        # Extra Collision solids
        loader.loadModel("forest/Bridge1", callback=self.bridge1Done)
        loader.loadModel("forest/Bridge2", callback=self.bridge2Done)
        loader.loadModel("forest/Bridge3", callback=self.bridge3Done)
        loader.loadModel("forest/Bridge4", callback=self.bridge4Done)
        loader.loadModel("forest/Plant1", callback=self.plant1Done)
        loader.loadModel("forest/Plant2", callback=self.plant2Done)

        # some light green fog
        self.fog = Fog("Forest Fog")
        self.fog.setColor(0.0, 0.9, 0.7)
        self.fog.setExpDensity(0.01)
        render.setFog(self.fog)

        ## Seeds ##
        self.numSeedPositions = 20
        self.tutorialSeed = None
        self.spawnedSeeds = {}

        self.spawnSeeds(15)

        base.messenger.send("LevelLoaded")
示例#30
0
 def scaleRadar(self):
     DistributedCashbotBossGoon.scaleRadar(self)
     self.radar.setColorScale(0.7, 0.0, 0.0, 0.8)
     self.radar.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd))
示例#31
0
    def levelDone(self, model):
        self.level = model
        self.level.hide()
        self.level.reparentTo(render)
        self.level.setPos(0, 0, -2)

        # lights for this world
        directLight = DirectionalLight("directLight")
        directLightNP = self.level.attachNewNode(directLight)
        directLightNP.setHpr(0, -60, 0)
        render.setLight(directLightNP)

        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(VBase4(0.2, 0.2, 0.2, 1))
        ambientLightNP = self.level.attachNewNode(ambientLight)
        render.setLight(ambientLightNP)

        # spawn NPCs
        self.numNPCs = 15
        self.npcList = []
        for i in range(self.numNPCs):
            npc = Actor("character/character",
                        {"Idle": "character/character-Idle"})
            npc.setBlend(frameBlend=True)
            npc.setScale(random.uniform(0.4, 1.0))
            npc.loop("Idle")
            point = self.level.find("**/NPC.%03d" % i)
            npc.reparentTo(point)
            self.npcList.append(npc)

        #
        # Fix alpha problems
        #
        alphaSettings = ColorBlendAttrib.make(ColorBlendAttrib.MAdd,
                                              ColorBlendAttrib.OIncomingAlpha,
                                              ColorBlendAttrib.OOne,
                                              (0, 0, 0, 0))
        for np in self.level.findAllMatches("**/Godray*"):
            np.setAttrib(alphaSettings)
            np.setBin("fixed", 10)
            np.setDepthWrite(False)
        water = self.level.find("**/Water")
        water.setAttrib(alphaSettings)
        water.setBin("fixed", 11)
        water.setDepthWrite(False)

        # Extra Collision solids
        loader.loadModel("forest/Bridge1", callback=self.bridge1Done)
        loader.loadModel("forest/Bridge2", callback=self.bridge2Done)
        loader.loadModel("forest/Bridge3", callback=self.bridge3Done)
        loader.loadModel("forest/Bridge4", callback=self.bridge4Done)
        loader.loadModel("forest/Plant1", callback=self.plant1Done)
        loader.loadModel("forest/Plant2", callback=self.plant2Done)

        # some light green fog
        self.fog = Fog("Forest Fog")
        self.fog.setColor(0.0, 0.9, 0.7)
        self.fog.setExpDensity(0.01)
        render.setFog(self.fog)

        ## Seeds ##
        self.numSeedPositions = 20
        self.tutorialSeed = None
        self.spawnedSeeds = {}

        self.spawnSeeds(15)

        base.messenger.send("LevelLoaded")
示例#32
0
文件: CogdoUtil.py 项目: nate97/src
def initializeLightCone(np, bin = 'fixed', sorting = 3):
    np.node().setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OIncomingAlpha, ColorBlendAttrib.OOne))
    if bin:
        np.setBin(bin, sorting)
    np.setDepthWrite(False)
    np.setTwoSided(True, 10000)
示例#33
0
    def __init__(self):
        # Initialize the ShowBase class from which we inherit, which will
        # create a window and set up everything we need for rendering into it.
        ShowBase.__init__(self)

        base.disableMouse()
        base.setBackgroundColor(0, 0, 0)
        camera.setPos(0, -50, 0)

        # Check video card capabilities.
        if not base.win.getGsg().getSupportsBasicShaders():
            addTitle(
                "Glow Filter: Video driver reports that Cg shaders are not supported.")
            return

        # Post the instructions
        self.title = addTitle("Panda3D: Tutorial - Glow Filter")
        self.inst1 = addInstructions(0.06, "ESC: Quit")
        self.inst2 = addInstructions(0.12, "Space: Toggle Glow Filter On/Off")
        self.inst3 = addInstructions(0.18, "Enter: Toggle Running/Spinning")
        self.inst4 = addInstructions(0.24, "V: View the render-to-texture results")

        # Create the shader that will determime what parts of the scene will
        # glow
        glowShader = loader.loadShader("shaders/glowShader.sha")

        # load our model
        self.tron = Actor()
        self.tron.loadModel("models/tron")
        self.tron.loadAnims({"running": "models/tron_anim"})
        self.tron.reparentTo(render)
        self.interval = self.tron.hprInterval(60, LPoint3(360, 0, 0))
        self.interval.loop()
        self.isRunning = False

        # put some lighting on the tron model
        dlight = DirectionalLight('dlight')
        alight = AmbientLight('alight')
        dlnp = render.attachNewNode(dlight)
        alnp = render.attachNewNode(alight)
        dlight.setColor(LVector4(1.0, 0.7, 0.2, 1))
        alight.setColor(LVector4(0.2, 0.2, 0.2, 1))
        dlnp.setHpr(0, -60, 0)
        render.setLight(dlnp)
        render.setLight(alnp)

        # create the glow buffer. This buffer renders like a normal scene,
        # except that only the glowing materials should show up nonblack.
        glowBuffer = base.win.makeTextureBuffer("Glow scene", 512, 512)
        glowBuffer.setSort(-3)
        glowBuffer.setClearColor(LVector4(0, 0, 0, 1))

        # We have to attach a camera to the glow buffer. The glow camera
        # must have the same frustum as the main camera. As long as the aspect
        # ratios match, the rest will take care of itself.
        glowCamera = base.makeCamera(
            glowBuffer, lens=base.cam.node().getLens())

        # Tell the glow camera to use the glow shader
        tempnode = NodePath(PandaNode("temp node"))
        tempnode.setShader(glowShader)
        glowCamera.node().setInitialState(tempnode.getState())

        # set up the pipeline: from glow scene to blur x to blur y to main
        # window.
        blurXBuffer = makeFilterBuffer(
            glowBuffer,  "Blur X", -2, "shaders/XBlurShader.sha")
        blurYBuffer = makeFilterBuffer(
            blurXBuffer, "Blur Y", -1, "shaders/YBlurShader.sha")
        self.finalcard = blurYBuffer.getTextureCard()
        self.finalcard.reparentTo(render2d)

        # This attribute is used to add the results of the post-processing
        # effects to the existing framebuffer image, rather than replace it.
        # This is mainly useful for glow effects like ours.
        self.finalcard.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd))

        # Panda contains a built-in viewer that lets you view the results of
        # your render-to-texture operations.  This code configures the viewer.
        self.accept("v", base.bufferViewer.toggleEnable)
        self.accept("V", base.bufferViewer.toggleEnable)
        base.bufferViewer.setPosition("llcorner")
        base.bufferViewer.setLayout("hline")
        base.bufferViewer.setCardSize(0.652, 0)

        # event handling
        self.accept("space", self.toggleGlow)
        self.accept("enter", self.toggleDisplay)
        self.accept("escape", sys.exit, [0])

        self.glowOn = True
示例#34
0
def pleaseMakeTransparent(nodePath):
    nodePath.setTransparency(True)
    nodePath.setAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullNone))
    nodePath.setDepthWrite(False)
    nodePath.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd))
示例#35
0
    def pandaRender(self):
        frameList = []
        for node in self.compositeFrames.getiterator('composite-frame'):
            if node.tag == "composite-frame" and node.attrib.get("id") == str(self.internalFrameIndex):
                for frameCallNode in node:
                    for frameNode in self.frames.getiterator('frame'):
                        if frameNode.tag == "frame" and frameNode.attrib.get("id") == frameCallNode.attrib.get("id"):
                            offsetX = 0 if frameCallNode.attrib.get("offset-x") == None else float(frameCallNode.attrib.get("offset-x"))
                            offsetY = 0 if frameCallNode.attrib.get("offset-y") == None else float(frameCallNode.attrib.get("offset-y"))
                            tweenId = frameCallNode.attrib.get("tween")
                            frameInTween = 0 if frameCallNode.attrib.get("frame-in-tween") == None else int(frameCallNode.attrib.get("frame-in-tween"))
                            addWidth = 0 if frameNode.attrib.get("w") == None else float(frameNode.attrib.get("w"))
                            addHeight = 0 if frameNode.attrib.get("h") == None else float(frameNode.attrib.get("h"))
                            sInPixels = 0 if frameNode.attrib.get("s") == None else float(frameNode.attrib.get("s"))
                            tInPixels = 0 if frameNode.attrib.get("t") == None else float(frameNode.attrib.get("t"))
                            swInPixels = sInPixels + addWidth
                            thInPixels = tInPixels + addHeight
                            s = (sInPixels / self.baseWidth)
                            t = 1 - (tInPixels / self.baseHeight) # Complemented to deal with loading image upside down.
                            S = (swInPixels / self.baseWidth)
                            T = 1 - (thInPixels / self.baseHeight) # Complemented to deal with loading image upside down.
                            blend = "overwrite" if frameCallNode.attrib.get("blend") == None else frameCallNode.attrib.get("blend")
                            scaleX = 1 if frameCallNode.attrib.get("scale-x") == None else float(frameCallNode.attrib.get("scale-x"))
                            scaleY = 1 if frameCallNode.attrib.get("scale-y") == None else float(frameCallNode.attrib.get("scale-y"))
                            color = Color(1,1,1,1)
                            tweenHasColor = False
                            frameCallHasColor = False
                            frameCallColorName = frameCallNode.attrib.get("color-name")
                            if frameCallColorName != None:
                                # Get color at frame call as first resort.
                                frameCallHasColor = True
                                for colorNode in self.colors.getiterator('color'):
                                    if colorNode.tag == 'color' and colorNode.attrib.get("name") == frameCallColorName:
                                        R = 1 if colorNode.attrib.get("r") == None else float(colorNode.attrib.get("r"))
                                        G = 1 if colorNode.attrib.get("g") == None else float(colorNode.attrib.get("g"))
                                        B = 1 if colorNode.attrib.get("b") == None else float(colorNode.attrib.get("b"))
                                        A = 1 if colorNode.attrib.get("a") == None else float(colorNode.attrib.get("a"))
                                        color = Color(R, G, B, A)
                                        break # leave for loop when we find the correct color
                                pass

                            if tweenId != None and tweenId != "0":
                                # Get color at tween frame as second resort.
                                thisTween = None
                                frameLength = 1
                                advancementFunction = "linear"
                                foundTween = False
                                pointList = []
                                colorList = []
                                for tweenNode in self.tweens.getiterator('motion-tween'):
                                    if tweenNode.tag == "motion-tween" and tweenNode.attrib.get("id") == tweenId:
                                        foundTween = True
                                        frameLength = 1 if tweenNode.attrib.get("length-in-frames") == None else tweenNode.attrib.get("length-in-frames")
                                        advancementFunction = "linear" if tweenNode.attrib.get("advancement-function") == None else tweenNode.attrib.get("advancement-function")
                                        for pointOrColorNode in tweenNode.getiterator():
                                            if pointOrColorNode.tag == "point":
                                                pX = 0 if pointOrColorNode.attrib.get("x") == None else float(pointOrColorNode.attrib.get("x"))
                                                pY = 0 if pointOrColorNode.attrib.get("y") == None else float(pointOrColorNode.attrib.get("y"))
                                                pointList.append(Point(pX, pY, 0))
                                            elif pointOrColorNode.tag == "color-state":
                                                colorName = "white" if pointOrColorNode.attrib.get("name") == None else pointOrColorNode.attrib.get("name")
                                                for colorNode in self.colors.getiterator('color'):
                                                    if colorNode.tag == 'color' and colorNode.attrib.get("name") == colorName:
                                                        R = 1 if colorNode.attrib.get("r") == None else float(colorNode.attrib.get("r"))
                                                        G = 1 if colorNode.attrib.get("g") == None else float(colorNode.attrib.get("g"))
                                                        B = 1 if colorNode.attrib.get("b") == None else float(colorNode.attrib.get("b"))
                                                        A = 1 if colorNode.attrib.get("a") == None else float(colorNode.attrib.get("a"))
                                                        colorList.append(Color(R, G, B, A))
                                                        break # leave for loop when we find the correct color reference
                                            pass # Run through all child nodes of selected tween
                                        break # Exit after finding correct tween
                                pass
                                if foundTween:
                                    thisTween = Tween(frameLength, advancementFunction, pointList, colorList)
                                    offset = thisTween.XYFromFrame(frameInTween);
                                    offsetFromTweenX = int(offset.X);
                                    offsetFromTweenY = int(offset.Y);
                                    offsetX += int(offset.X);
                                    offsetY += int(offset.Y);
                                    if thisTween.hasColorComponent():
                                        tweenHasColor = True;
                                        if frameCallHasColor == False:
                                            color = thisTween.colorFromFrame(frameInTween);
                                    pass
                            if frameNode.attrib.get("color-name") != None and frameCallHasColor == False and tweenHasColor == False:
                                # Get color at frame definition as last resort.
                                for colorNode in colors.getiterator('color'):
                                    if colorNode.tag == 'color' and colorNode.attrib.get("name") == frameNode.attrib.get("color-name"):
                                        R = 1 if colorNode.attrib.get("r") == None else float(colorNode.attrib.get("r"))
                                        G = 1 if colorNode.attrib.get("g") == None else float(colorNode.attrib.get("g"))
                                        B = 1 if colorNode.attrib.get("b") == None else float(colorNode.attrib.get("b"))
                                        A = 1 if colorNode.attrib.get("a") == None else float(colorNode.attrib.get("a"))
                                        color = Color(R, G, B, A)
                                        break # leave for loop when we find the correct color
                                pass
                            rotationZ = 0 if frameCallNode.attrib.get("rotation-z") == None else float(frameCallNode.attrib.get("rotation-z"))
                            frameList.append(Frame(Bound(offsetX, offsetY, addWidth, addHeight), s, t, S, T, blend, scaleX, scaleY, color, rotationZ))
                    pass 
                break # Leave once we've found the appropriate frame

        # Prepare tracking list of consumed nodes.
        self.clearNodesForDrawing()
        # Make an identifier to tack onto primitive names in Panda3d's scene graph.
        frameIndexForName = 1
                
        # Loop through loaded frames that make up composite frame.
        for loadedFrame in frameList:              
            # For debugging purposes, print the object.
            if False:
                loadedFrame.printAsString()
            
            # Set up place to store primitive 3d object; note: requires vertex data made by GeomVertexData
            squareMadeByTriangleStrips = GeomTristrips(Geom.UHDynamic)
              
            # Set up place to hold 3d data and for the following coordinates:
            #   square's points (V3: x, y, z), 
            #   the colors at each point of the square (c4: r, g, b, a), and
            #   for the UV texture coordinates at each point of the square     (t2: S, T).
            vertexData = GeomVertexData('square-'+str(frameIndexForName), GeomVertexFormat.getV3c4t2(), Geom.UHDynamic)
            vertex = GeomVertexWriter(vertexData, 'vertex')
            color = GeomVertexWriter(vertexData, 'color')
            texcoord = GeomVertexWriter(vertexData, 'texcoord') 
              
            # Add the square's data
            # Upper-Left corner of square
            vertex.addData3f(-loadedFrame.bound.Width / 2.0, 0, -loadedFrame.bound.Height / 2.0)
            color.addData4f(loadedFrame.color.R,loadedFrame.color.G,loadedFrame.color.B,loadedFrame.color.A)
            texcoord.addData2f(loadedFrame.s, loadedFrame.T)

            # Upper-Right corner of square
            vertex.addData3f(loadedFrame.bound.Width / 2.0, 0, -loadedFrame.bound.Height / 2.0)
            color.addData4f(loadedFrame.color.R,loadedFrame.color.G,loadedFrame.color.B,loadedFrame.color.A)
            texcoord.addData2f(loadedFrame.S, loadedFrame.T)
            
            # Lower-Left corner of square
            vertex.addData3f(-loadedFrame.bound.Width / 2.0, 0, loadedFrame.bound.Height / 2.0)
            color.addData4f(loadedFrame.color.R,loadedFrame.color.G,loadedFrame.color.B,loadedFrame.color.A)
            texcoord.addData2f(loadedFrame.s, loadedFrame.t)
            
            # Lower-Right corner of square
            vertex.addData3f(loadedFrame.bound.Width / 2.0, 0, loadedFrame.bound.Height / 2.0)
            color.addData4f(loadedFrame.color.R,loadedFrame.color.G,loadedFrame.color.B,loadedFrame.color.A)
            texcoord.addData2f(loadedFrame.S, loadedFrame.t)

            # Pass data to primitive
            squareMadeByTriangleStrips.addNextVertices(4)
            squareMadeByTriangleStrips.closePrimitive()
            square = Geom(vertexData)
            square.addPrimitive(squareMadeByTriangleStrips)
            # Pass primtive to drawing node
            drawPrimitiveNode=GeomNode('square-'+str(frameIndexForName))    
            drawPrimitiveNode.addGeom(square)
            # Pass node to scene (effect camera)
            nodePath = self.effectCameraNodePath.attachNewNode(drawPrimitiveNode)
            # Linear dodge:
            if loadedFrame.blendMode == "darken":
                nodePath.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OOneMinusFbufferColor, ColorBlendAttrib.OOneMinusIncomingColor))
                pass
            elif loadedFrame.blendMode == "multiply":
                nodePath.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OFbufferColor, ColorBlendAttrib.OZero))
                pass
            elif loadedFrame.blendMode == "color-burn":
                nodePath.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OZero, ColorBlendAttrib.OOneMinusIncomingColor))
                pass
            elif loadedFrame.blendMode == "linear-burn":
                nodePath.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OZero, ColorBlendAttrib.OIncomingColor))
                pass
            elif loadedFrame.blendMode == "lighten":
                nodePath.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MMax, ColorBlendAttrib.OIncomingColor, ColorBlendAttrib.OFbufferColor))
                pass
            elif loadedFrame.blendMode == "color-dodge":
                nodePath.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OOne, ColorBlendAttrib.OOne))
                pass
            elif loadedFrame.blendMode == "linear-dodge":
                nodePath.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OOne, ColorBlendAttrib.OOneMinusIncomingColor))
                pass
            else: # Overwrite:
                nodePath.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OIncomingAlpha, ColorBlendAttrib.OOneMinusIncomingAlpha))
                pass
            nodePath.setDepthTest(False)
            # Apply texture
            nodePath.setTexture(self.tex)
            # Apply translation, then rotation, then scaling to node.
            nodePath.setPos((loadedFrame.bound.X + loadedFrame.bound.Width / 2.0, 1, -loadedFrame.bound.Y - loadedFrame.bound.Height / 2.0))
            nodePath.setR(loadedFrame.rotationZ)
            nodePath.setScale(loadedFrame.scaleX, 1, loadedFrame.scaleY)
            nodePath.setTwoSided(True)
            self.consumedNodesList.append(nodePath)
            frameIndexForName = frameIndexForName + 1
        # Loop continues on through each frame called in the composite frame.
        pass
 def scaleRadar(self):
     DistributedCashbotBossGoon.scaleRadar(self)
     self.radar.setColorScale(0.7, 0.0, 0.0, 0.8)
     self.radar.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd))
示例#37
0
    def __init__(self, physic_world, config=None):
        logging.info("INIT PLAYER...")
        logging.info("INIT FSM...")
        FSM.__init__(self, "FSM-Player")
        logging.info("INIT CONFIG...")
        Config.__init__(self)
        # additional initial configuration settings set by the outher application
        self.physic_world = physic_world
        logging.info("INIT PHYSICS...")
        Physics.__init__(self)
        logging.info("INIT CONTROLS...")
        Control.__init__(self)
        logging.info("INIT CAMERA...")
        Camera.__init__(
            self,
            self.cam_near_clip,
            self.cam_far_clip,
            self.cam_fov)
        logging.info("INIT ANIMATOR...")
        Animator.__init__(self)
        logging.info("INIT PLAYER DONE")

        #
        # STATES SETUP
        #
        self.on_ground_states = [
            self.STATE_IDLE,
            self.STATE_IDLE_TO_WALK,
            self.STATE_WALK,
            self.STATE_WALK_TO_IDLE,
            self.STATE_PLANT]
        # set the possible transition in the FSM
        self.defaultTransitions = {
            self.STATE_IDLE: [self.STATE_IDLE_TO_WALK, self.STATE_PLANT],
            self.STATE_IDLE_TO_WALK: [self.STATE_IDLE, self.STATE_WALK],
            self.STATE_WALK: [self.STATE_IDLE, self.STATE_WALK_TO_IDLE],
            self.STATE_WALK_TO_IDLE: [self.STATE_IDLE, self.STATE_WALK],
            self.STATE_PLANT: [self.STATE_IDLE],
            }

        #
        # ACTOR SETUP
        #
        Actor.__init__(
            self,
            self.model,
            {
                self.IDLE: self.anim_idle,
                self.WALK: self.anim_walk,
                self.PLANT: self.anim_plant,
            })
        self.setBlend(frameBlend=self.enable_interpolation)

        alphaSettings = ColorBlendAttrib.make(
            ColorBlendAttrib.MAdd,
            ColorBlendAttrib.OIncomingAlpha,
            ColorBlendAttrib.OOne,
            (0, 0, 0, 0))
        #self.setAttrib(alphaSettings)
        self.setBin("fixed", 15)
        self.setDepthWrite(False)

        #
        # CONTROLS SETUP
        #
        self.isDown = base.mouseWatcherNode.isButtonDown
        self.mainNode = self
示例#38
0
    def __init__(self,
                 tex,
                 stim_angles=(0, 0),
                 initial_angle=0,
                 initial_position=(0, 0),
                 velocities=(0, 0),
                 strip_width=4,
                 fps=30,
                 window_size=None,
                 window_name='position control',
                 profile_on=False,
                 save_path=None):
        super().__init__()
        self.render.setAntialias(AntialiasAttrib.MMultisample)
        self.aspect2d.prepareScene(
            ShowBaseGlobal.base.win.getGsg())  # pre-loads world
        self.tex = tex
        if window_size == None:
            self.window_size = tex.texture_size
        else:
            self.window_size = window_size
        self.mask_position_card = initial_position
        self.strip_width = strip_width
        self.scale = np.sqrt(
            8)  #so it can handle arbitrary rotations and shifts
        self.strip_angle = initial_angle  #this will change fairly frequently
        self.stim_angles = stim_angles
        self.left_texture_angle = self.stim_angles[
            0] + self.strip_angle  #make this a property
        self.right_texture_angle = self.stim_angles[1] + self.strip_angle
        self.left_velocity = velocities[0]
        self.right_velocity = velocities[1]
        self.fps = fps
        self.window_name = window_name
        self.profile_on = profile_on
        print(save_path)
        self.save_path = save_path
        if self.save_path:
            initial_params = {
                'angles': stim_angles,
                'initial_angle': self.strip_angle,
                'velocities': velocities,
                'strip_width': self.strip_width,
                'initial_position': initial_position
            }
            print(tex, initial_params)
            self.filestream = utils.save_initialize(self.save_path, [tex],
                                                    [initial_params])
            print(self.filestream)
        else:
            self.filestream = None

        #Set window title and size
        self.window_properties = WindowProperties()
        self.window_properties.setSize(self.window_size, self.window_size)
        self.window_properties.setTitle(self.window_name)
        ShowBaseGlobal.base.win.requestProperties(
            self.window_properties)  #base is a panda3d global

        # Set frame rate
        ShowBaseGlobal.globalClock.setMode(ClockObject.MLimited)
        ShowBaseGlobal.globalClock.setFrameRate(
            self.fps)  #can lock this at whatever

        #CREATE MASK ARRAYS
        self.left_mask_array = 255 * np.ones(
            (self.tex.texture_size, self.tex.texture_size), dtype=np.uint8)
        self.left_mask_array[:, self.tex.texture_size // 2 -
                             self.strip_width // 2:] = 0
        self.right_mask_array = 255 * np.ones(
            (self.tex.texture_size, self.tex.texture_size), dtype=np.uint8)
        self.right_mask_array[:, :self.tex.texture_size // 2 +
                              self.strip_width // 2] = 0

        #TEXTURE STAGES FOR LEFT CARD
        self.left_texture_stage = TextureStage('left_texture_stage')
        #Mask
        self.left_mask = Texture("left_mask_texture")
        self.left_mask.setup2dTexture(self.tex.texture_size,
                                      self.tex.texture_size,
                                      Texture.T_unsigned_byte,
                                      Texture.F_luminance)
        self.left_mask.setRamImage(self.left_mask_array)
        self.left_mask_stage = TextureStage('left_mask_array')
        #Multiply the texture stages together
        self.left_mask_stage.setCombineRgb(TextureStage.CMModulate,
                                           TextureStage.CSTexture,
                                           TextureStage.COSrcColor,
                                           TextureStage.CSPrevious,
                                           TextureStage.COSrcColor)

        #TEXTURE STAGES FOR RIGHT CARD
        self.right_texture_stage = TextureStage('right_texture_stage')
        #Mask
        self.right_mask = Texture("right_mask_texture")
        self.right_mask.setup2dTexture(self.tex.texture_size,
                                       self.tex.texture_size,
                                       Texture.T_unsigned_byte,
                                       Texture.F_luminance)
        self.right_mask.setRamImage(self.right_mask_array)
        self.right_mask_stage = TextureStage('right_mask_stage')
        #Multiply the texture stages together
        self.right_mask_stage.setCombineRgb(TextureStage.CMModulate,
                                            TextureStage.CSTexture,
                                            TextureStage.COSrcColor,
                                            TextureStage.CSPrevious,
                                            TextureStage.COSrcColor)

        #CREATE CARDS/SCENEGRAPH
        cm = CardMaker('stimcard')
        cm.setFrameFullscreenQuad()
        #self.setBackgroundColor((0,0,0,1))
        self.left_card = self.aspect2d.attachNewNode(cm.generate())
        self.right_card = self.aspect2d.attachNewNode(cm.generate())
        self.left_card.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.M_add))
        self.right_card.setAttrib(ColorBlendAttrib.make(
            ColorBlendAttrib.M_add))

        #ADD TEXTURE STAGES TO CARDS
        self.left_card.setTexture(self.left_texture_stage, self.tex.texture)
        self.left_card.setTexture(self.left_mask_stage, self.left_mask)
        self.right_card.setTexture(self.right_texture_stage, self.tex.texture)
        self.right_card.setTexture(self.right_mask_stage, self.right_mask)
        self.setBackgroundColor(
            (0, 0, 0, 1))  # without this the cards will appear washed out
        #self.left_card.setAntialias(AntialiasAttrib.MMultisample)
        #self.right_card.setAntialias(AntialiasAttrib.MMultisample)
        #TRANSFORMS
        # Masks
        self.mask_transform = self.trs_transform()
        self.left_card.setTexTransform(self.left_mask_stage,
                                       self.mask_transform)
        self.right_card.setTexTransform(self.right_mask_stage,
                                        self.mask_transform)

        # Textures
        # Left
        self.left_card.setTexScale(self.left_texture_stage, 1 / self.scale)
        self.left_card.setTexRotate(self.left_texture_stage,
                                    self.left_texture_angle)
        # Right
        self.right_card.setTexScale(self.right_texture_stage, 1 / self.scale)
        self.right_card.setTexRotate(self.right_texture_stage,
                                     self.right_texture_angle)

        #Set task manager(s) for textures
        if self.left_velocity != 0 and self.right_velocity != 0:
            self.taskMgr.add(self.textures_update, "move_both")
        elif self.left_velocity != 0 and self.right_velocity == 0:
            self.taskMgr.add(self.left_texture_update, "move_left")
        elif self.left_velocity == 0 and self.right_velocity != 0:
            self.taskMgr.add(self.right_texture_update, "move_right")

        # Event handler to process the messages
        self.accept("stim", self.process_stim, [])

        #Set up profiling if desired
        if profile_on:
            PStatClient.connect()  # this will only work if pstats is running
            ShowBaseGlobal.base.setFrameRateMeter(True)  #Show frame rate
    def __init__(self, texture_array, stim_angles = (0, 0), mask_angle = 0, position = (0, 0), velocity = 0,
                 band_radius = 3, window_size = 512, texture_size = 512, bgcolor = (0, 0, 0, 1)):
        super().__init__()

        self.mask_position_ndc = position
        self.mask_position_uv = (ndc2uv(self.mask_position_ndc[0]), 
                                 ndc2uv(self.mask_position_ndc[1]))
        self.scale = np.sqrt(8)
        self.texture_array = texture_array
        self.texture_dtype = type(self.texture_array.flat[0])
        self.ndims = self.texture_array.ndim
        self.left_texture_angle = stim_angles[0]
        self.right_texture_angle = stim_angles[1]
        self.velocity = velocity
        self.mask_angle = mask_angle #this will change fairly frequently
        
        #Set window title and size
        self.window_properties = WindowProperties()
        self.window_properties.setSize(window_size, window_size)
        self.window_properties.setTitle("BinocularStatic")
        ShowBaseGlobal.base.win.requestProperties(self.window_properties)  #base is a panda3d global
        
        #CREATE MASKS (right mask for left tex, left mask for right tex)
        self.right_mask = 255*np.ones((texture_size,texture_size), dtype=np.uint8)    
        self.right_mask[:, texture_size//2 - band_radius :] = 0  
        self.left_mask = 255*np.ones((texture_size,texture_size), dtype=np.uint8)    
        self.left_mask[:, : texture_size//2 + band_radius] = 0  
        
        
        if False:  #set to True to debug
            import matplotlib.pyplot as plt
            plt.imshow(self.left_mask, cmap = 'gray')
            plt.show()
    
        #CREATE TEXTURE STAGES
        #Grating texture 
        self.grating_texture = Texture("Grating")  #T_unsigned_byte
        self.grating_texture.setup2dTexture(texture_size, texture_size, 
                                            Texture.T_unsigned_byte, Texture.F_luminance) 
        self.grating_texture.setRamImage(self.texture_array)   
                   
        #TEXTURE STAGES FOR RIGHT CARD
        self.right_texture_stage = TextureStage('right_texture')       
        #Mask
        self.left_mask_texture = Texture("left_mask")
        self.left_mask_texture.setup2dTexture(texture_size, texture_size, 
                                               Texture.T_unsigned_byte, Texture.F_luminance) 
        self.left_mask_texture.setRamImage(self.left_mask)  
        self.left_mask_stage = TextureStage('left_mask')
        #Multiply the texture stages together
        self.left_mask_stage.setCombineRgb(TextureStage.CMModulate, 
                                    TextureStage.CSTexture, 
                                    TextureStage.COSrcColor,
                                    TextureStage.CSPrevious, 
                                    TextureStage.COSrcColor)    
                                             
        #CREATE CARDS/SCENEGRAPH
        cm = CardMaker('stimcard')
        cm.setFrameFullscreenQuad()
        self.right_card = self.aspect2d.attachNewNode(cm.generate())
        self.setBackgroundColor((0,0,0,1))  #set above
        self.right_card.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.M_add))
        
        #SET TEXTURE STAGES
        self.right_card.setTexture(self.right_texture_stage, self.grating_texture)  
        self.right_card.setTexture(self.left_mask_stage, self.left_mask_texture)
        
        #SET static transforms
        #Left texture mask
        self.mask_transform = self.trs_transform()
        self.right_card.setTexTransform(self.left_mask_stage, self.mask_transform)
        #Right texture
        self.right_card.setTexScale(self.right_texture_stage, 1/self.scale)
        self.right_card.setTexRotate(self.right_texture_stage, self.right_texture_angle)

        #Set dynamic transforms
        if self.velocity != 0:
            self.taskMgr.add(self.texture_update, "moveTextureTask")


        self.title = OnscreenText("x",
                                  style = 1,
                                  fg = (1,1,1,1),
                                  bg = (0,0,0,.8),
                                  pos = self.mask_position_ndc, 
                                  scale = 0.05)
示例#40
0
    def __init__(self, name='glow', amount=0, red=100, green=100, blue=100):
        print "Glow enabled!"

        ## Glow by Adam Bell ([email protected])
        ## with some original code from Kwasi Mensah ([email protected])
        ## for PandaCamp (code.google.com/p/pandacamp/)

        #The shader is important (but yet a variable).

        ## The next part I'll replace with a single file as soon
        ## as I can work with variables in the *.SHA files.

        redd = red / 100
        greend = green / 100
        blued = blue / 100

        if amount == 0:
            print "glowShader set to it's default value of 1."
            amount = 1

        ## Custom number for a positive non-integer or above 4.
        if amount > 0:
            ### NOTE: the line below is an RGB
            render.setShaderInput('amnt', amount * redd, amount * greend,
                                  amount * blued, amount)
            print "glowShader set as " + str(amount) + "!"

        if amount < 0:
            raise TypeError('Only positive numbers work for the glowShader!')

        # except that only the glowing materials should show up nonblack.
        base.disableMouse()
        glowBuffer = base.win.makeTextureBuffer("Glow scene", 512, 512)
        glowBuffer.setSort(-3)
        glowBuffer.setClearColor(Vec4(0, 0, 0, 1))

        glowCamera = base.makeCamera(glowBuffer,
                                     lens=base.cam.node().getLens())

        # Tell the glow camera to use the glow shader
        tempnode = NodePath(PandaNode("temp node"))
        tempnode.setShader(
            loader.loadShader('/c/panda/pandacamp/src/shaders/glowShader.sha'))
        ## Was 'Shader.load'
        glowCamera.node().setInitialState(tempnode.getState())

        # X and Y shaders to make the earlier "glowShader.sha" work (or effective).
        blurXBuffer = makeFilterBuffer(
            glowBuffer, "Blur X", -2,
            "/c/panda/pandacamp/src/shaders/XBlurShader.sha")
        blurYBuffer = makeFilterBuffer(
            blurXBuffer, "Blur Y", -1,
            "/c/panda/pandacamp/src/shaders/YBlurShader.sha")
        self.finalcard = blurYBuffer.getTextureCard()
        self.finalcard.reparentTo(render2d)
        self.finalcard.setAttrib(ColorBlendAttrib.make(ColorBlendAttrib.MAdd))

        # Panda contains a built-in viewer that lets you view the results of
        # your render-to-texture operations.  This code configures the viewer.
        base.bufferViewer.setPosition("llcorner")
        base.bufferViewer.setLayout("hline")
        base.bufferViewer.setCardSize(0.652, 0)