コード例 #1
0
 def renderQuadInto(self, mul=1, div=1, align=1, depthtex=None, colortex=None, auxtex0=None, auxtex1=None):
     texgroup = (
      depthtex, colortex, auxtex0, auxtex1)
     winx, winy = self.getScaledSize(mul, div, align)
     depthbits = bool(depthtex != None)
     buffer = self.createBuffer('filter-stage', winx, winy, texgroup, depthbits)
     if buffer == None:
         return
     cm = CardMaker('filter-stage-quad')
     cm.setFrameFullscreenQuad()
     quad = NodePath(cm.generate())
     quad.setDepthTest(0)
     quad.setDepthWrite(0)
     quad.setColor(1, 0.5, 0.5, 1)
     quadcamnode = Camera('filter-quad-cam')
     lens = OrthographicLens()
     lens.setFilmSize(2, 2)
     lens.setFilmOffset(0, 0)
     lens.setNearFar(-1000, 1000)
     quadcamnode.setLens(lens)
     quadcam = quad.attachNewNode(quadcamnode)
     dr = buffer.makeDisplayRegion((0, 1, 0, 1))
     dr.disableClears()
     dr.setCamera(quadcam)
     dr.setActive(True)
     dr.setScissorEnabled(False)
     buffer.setClearColor((0, 0, 0, 1))
     buffer.setClearColorActive(True)
     self.buffers.append(buffer)
     self.sizes.append((mul, div, align))
     return quad
コード例 #2
0
    def renderQuadInto(self, xsize, ysize, colortex=None, cmode = GraphicsOutput.RTMBindOrCopy, auxtex = None):

        buffer = self.createBuffer("filter-stage", xsize, ysize, colortex, cmode, auxtex)

        if (buffer == None):
            return None

        cm = CardMaker("filter-stage-quad")
        cm.setFrameFullscreenQuad()
        quad = NodePath(cm.generate())
        quad.setDepthTest(0)
        quad.setDepthWrite(0)
        quad.setColor(Vec4(1,0.5,0.5,1))

        quadcamnode = Camera("filter-quad-cam")
        lens = OrthographicLens()
        lens.setFilmSize(2, 2)
        lens.setFilmOffset(0, 0)
        lens.setNearFar(-1000, 1000)
        quadcamnode.setLens(lens)
        quadcam = quad.attachNewNode(quadcamnode)
        
        buffer.getDisplayRegion(0).setCamera(quadcam)
        buffer.getDisplayRegion(0).setActive(1)

        return quad, buffer
コード例 #3
0
ファイル: panda3d.py プロジェクト: linsats/pybullet_rendering
class PbCameraNode(NodePath):
    """Pybullet-compatible camera node wrapper
    """

    Z2Y = Mat4(1, 0, 0, 0, 0, 0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 1)

    def __init__(self, render: NodePath):
        self._camera = Camera('pb_camera')
        self._lens = MatrixLens()
        self._camera.set_lens(self._lens)
        super().__init__(self._camera)
        self.reparent_to(render)

    def set_active(self, active: bool):
        self._camera.set_active(active)

    def is_active(self):
        return self._camera.is_active()

    def update(self, pb_camera):
        self.set_mat(self.Z2Y * Mat4(*pb_camera.pose_mat))
        mat = np.asarray(pb_camera.proj_mat).reshape(4, 4)
        m22, m32 = -mat[2, 2], -mat[3, 2]
        zfar = (2.0 * m32) / (2.0 * m22 - 2.0)
        znear = ((m22 - 1.0) * zfar) / (m22 + 1.0)
        self._lens.set_near_far(znear, zfar)
        self._lens.set_user_mat(self.Z2Y * Mat4(*pb_camera.proj_mat))
コード例 #4
0
    def create(self):
        # Create voxelize camera
        self.voxelizeCamera = Camera("VoxelizeCamera")
        self.voxelizeCamera.setCameraMask(BitMask32.bit(4))
        self.voxelizeCameraNode = Globals.render.attachNewNode(
            self.voxelizeCamera)
        self.voxelizeLens = OrthographicLens()
        self.voxelizeLens.setFilmSize(self.voxelGridSize * 2,
                                      self.voxelGridSize * 2)
        self.voxelizeLens.setNearFar(0.0, self.voxelGridSize * 2)
        self.voxelizeCamera.setLens(self.voxelizeLens)
        self.voxelizeCamera.setTagStateKey("VoxelizePassShader")
        Globals.render.setTag("VoxelizePassShader", "Default")

        # Create voxelize tareet
        self.target = RenderTarget("VoxelizePass")
        self.target.setSize(self.voxelGridResolution *
                            self.gridResolutionMultiplier)

        if self.pipeline.settings.useDebugAttachments:
            self.target.addColorTexture()
        else:
            self.target.setColorWrite(False)

        self.target.setCreateOverlayQuad(False)
        self.target.setSource(self.voxelizeCameraNode, Globals.base.win)
        self.target.prepareSceneRender()
        self.target.setActive(False)
コード例 #5
0
    def create(self):
        self.camera = Camera("PSSMDistShadowsESM")
        self.cam_lens = OrthographicLens()
        self.cam_lens.set_film_size(12000, 12000)
        self.cam_lens.set_near_far(10.0, self.sun_distance * 2)
        self.camera.set_lens(self.cam_lens)
        self.cam_node = Globals.base.render.attach_new_node(self.camera)

        self.target = self.create_target("ShadowMap")
        self.target.size = self.resolution
        self.target.add_depth_attachment(bits=32)
        self.target.prepare_render(self.cam_node)

        self.target_convert = self.create_target("ConvertToESM")
        self.target_convert.size = self.resolution
        self.target_convert.add_color_attachment(bits=(32, 0, 0, 0))
        self.target_convert.prepare_buffer()
        self.target_convert.set_shader_input("SourceTex", self.target.depth_tex)

        self.target_blur_v = self.create_target("BlurVert")
        self.target_blur_v.size = self.resolution
        self.target_blur_v.add_color_attachment(bits=(32, 0, 0, 0))
        self.target_blur_v.prepare_buffer()
        self.target_blur_v.set_shader_input("SourceTex", self.target_convert.color_tex)
        self.target_blur_v.set_shader_input("direction", LVecBase2i(1, 0))

        self.target_blur_h = self.create_target("BlurHoriz")
        self.target_blur_h.size = self.resolution
        self.target_blur_h.add_color_attachment(bits=(32, 0, 0, 0))
        self.target_blur_h.prepare_buffer()
        self.target_blur_h.set_shader_input("SourceTex", self.target_blur_v.color_tex)
        self.target_blur_h.set_shader_input("direction", LVecBase2i(0, 1))

        # Register shadow camera
        self._pipeline.tag_mgr.register_camera("shadow", self.camera)
コード例 #6
0
    def setupCamera2d(self,
                      sort=10,
                      displayRegion=(0, 1, 0, 1),
                      coords=(-1, 1, -1, 1)):
        dr = self.win.makeMonoDisplayRegion(*displayRegion)
        dr.setSort(10)

        # Enable clearing of the depth buffer on this new display
        # region (see the comment in setupRender2d, above).
        dr.setClearDepthActive(1)

        # Make any texture reloads on the gui come up immediately.
        dr.setIncompleteRender(False)

        left, right, bottom, top = coords

        # Now make a new Camera node.
        cam2dNode = Camera('cam2d')

        lens = OrthographicLens()
        lens.setFilmSize(right - left, top - bottom)
        lens.setFilmOffset((right + left) * 0.5, (top + bottom) * 0.5)
        lens.setNearFar(-1000, 1000)
        cam2dNode.setLens(lens)

        # self.camera2d is the analog of self.camera, although it's
        # not as clear how useful it is.
        self.camera2d = self.render2d.attachNewNode('camera2d')

        camera2d = self.camera2d.attachNewNode(cam2dNode)
        dr.setCamera(camera2d)

        self.cam2d = camera2d

        return camera2d
コード例 #7
0
    def create(self):
        self.camera = Camera("SkyAOCaptureCam")
        self.cam_lens = OrthographicLens()
        self.cam_lens.set_film_size(200, 200)
        self.cam_lens.set_near_far(0.0, 500.0)
        self.camera.set_lens(self.cam_lens)
        self.cam_node = Globals.base.render.attach_new_node(self.camera)
        self.cam_node.look_at(0, 0, -1)
        self.cam_node.set_r(0)

        self.target = self.create_target("SkyAOCapture")
        self.target.size = 1024
        self.target.add_depth_attachment(bits=16)
        self.target.prepare_render(self.cam_node)

        self.target_convert = self.create_target("ConvertDepth")
        self.target_convert.size = 1024
        self.target_convert.add_color_attachment(bits=(16, 0, 0, 0))
        self.target_convert.prepare_buffer()

        self.target_convert.set_shader_input("DepthTex", self.target.depth_tex)
        self.target_convert.set_shader_input("position", self.pta_position)

        # Register camera
        self._pipeline.tag_mgr.register_camera("shadow", self.camera)
コード例 #8
0
class _Camera_:

    key_map = {}
    mouse_map = {}

    # Public.
    def set_focus(self, obj):
        if self.FOCUS and obj is self.FOCUS: return
        self.FOCUS = obj
        self.focus_pos.set(0, obj.radius * 12, 0)
        obj_state = self.env.client.SIM.get_object_state(obj.name, ["sys_pos"])
        obj.sys_pos = LVector3d(*obj_state['sys_pos'])
        self.sys_pos = obj.sys_pos - self.focus_pos

    # Setup.
    def __init__(self, env):
        self.env = env
        self.cam_node = Camera(self.__class__.__name__.lower())
        self.cam_node.setScene(env.NP)
        self.NP = NodePath(self.cam_node)
        self.NP.reparentTo(env.NP)
        self.LENS = self.cam_node.getLens()
        self.LENS.setFar(_cam.FAR)
        self.LENS.setFov(base.camLens.getFov())
        self.FOCUS = None

        self.focus_pos = LVector3d(0, 0, 0)
        self.sys_pos = LVector3d(0, 0, 0)
コード例 #9
0
    def __init__(self, app):
        self.app = app
        self.do = DirectObject()

        self.running = False
        self.displayRegion = None
        self.root = NodePath('creditsRender')
        self.camera = Camera('creditsCam')
        self.cameraNP = NodePath(self.camera)

        # Set parameters to match those of render2d
        self.root.setDepthTest(0)
        self.root.setDepthWrite(0)
        self.root.setMaterialOff(1)
        self.root.setTwoSided(1)

        self.aspect2d = self.root  # self.root.attachNewNode('creditsAspect')

        lens = OrthographicLens()
        lens.setFilmSize(2, 2)
        lens.setFilmOffset(0, 0)
        lens.setNearFar(-1000, 1000)
        self.camera.setLens(lens)

        self.cameraNP.reparentTo(self.root)

        self.scrollTask = None
        self.lastTime = None
        self.creditsFileLoaded = False
コード例 #10
0
class SkyAOCaptureStage(RenderStage):

    """ This stage captures the sky ao by rendering the scene from above """

    required_inputs = []
    required_pipes = []

    @property
    def produced_pipes(self):
        return {"SkyAOHeight": self.target_convert.color_tex}

    @property
    def produced_inputs(self):
        return {"SkyAOCapturePosition": self.pta_position}

    def __init__(self, pipeline):
        RenderStage.__init__(self, pipeline)
        self.pta_position = PTALVecBase3f.empty_array(1)
        self.resolution = 512
        self.capture_height = 100.0
        self.max_radius = 100.0

    def create(self):
        self.camera = Camera("SkyAOCaptureCam")
        self.cam_lens = OrthographicLens()
        self.cam_lens.set_film_size(self.max_radius, self.max_radius)
        self.cam_lens.set_near_far(0, self.capture_height)
        self.camera.set_lens(self.cam_lens)
        self.cam_node = Globals.base.render.attach_new_node(self.camera)
        self.cam_node.look_at(0, 0, -1)
        self.cam_node.set_r(0)

        self.target = self.create_target("SkyAOCapture")
        self.target.size = self.resolution
        self.target.add_depth_attachment(bits=16)
        self.target.prepare_render(self.cam_node)

        self.target_convert = self.create_target("ConvertDepth")
        self.target_convert.size = self.resolution
        self.target_convert.add_color_attachment(bits=(16, 0, 0, 0))
        self.target_convert.prepare_buffer()

        self.target_convert.set_shader_inputs(
            DepthTex=self.target.depth_tex,
            position=self.pta_position)

        # Register camera
        self._pipeline.tag_mgr.register_camera("shadow", self.camera)

    def update(self):
        snap_size = self.max_radius / self.resolution
        cam_pos = Globals.base.camera.get_pos(Globals.base.render)
        self.cam_node.set_pos(
            cam_pos.x - cam_pos.x % snap_size,
            cam_pos.y - cam_pos.y % snap_size,
            self.capture_height / 2.0)
        self.pta_position[0] = self.cam_node.get_pos()

    def reload_shaders(self):
        self.target_convert.shader = self.load_plugin_shader("convert_depth.frag.glsl")
コード例 #11
0
    def __init__(self):
        """ Creates a new ShadowSource. After the creation, a lens can be added
        with setupPerspectiveLens or setupOrtographicLens. """
        self.index = self._generateUID()
        DebugObject.__init__(self, "ShadowSource-" + str(self.index))
        ShaderStructElement.__init__(self)

        self.valid = False
        self.camera = Camera("ShadowSource-" + str(self.index))
        self.camera.setActive(False)
        self.cameraNode = NodePath(self.camera)
        self.cameraNode.reparentTo(Globals.render.find("RPCameraDummys"))
        self.cameraNode.hide()
        self.resolution = 512
        self.atlasPos = Vec2(0)
        self.doesHaveAtlasPos = False
        self.sourceIndex = 0
        self.mvp = UnalignedLMatrix4f()
        self.sourceIndex = -1
        self.nearPlane = 0.0
        self.farPlane = 1000.0
        self.converterYUR = None
        self.transforMat = TransformState.makeMat(
            Mat4.convertMat(
                Globals.base.win.getGsg().getInternalCoordinateSystem(),
                CSZupRight))
コード例 #12
0
ファイル: cameras.py プロジェクト: svfgit/solex
class _Camera_:
        
    key_map = {}
    mouse_map = {}
    
    # Public.
    def set_focus(self, obj):
        if self.FOCUS and obj is self.FOCUS: return
        self.FOCUS = obj
        self.focus_pos.set(0, obj.radius*12, 0)
        obj_state = self.env.client.SIM.get_object_state(obj.name, ["sys_pos"])
        obj.sys_pos = LVector3d(*obj_state['sys_pos'])
        self.sys_pos = obj.sys_pos - self.focus_pos
    
    # Setup.
    def __init__(self, env):
        self.env = env
        self.cam_node = Camera(self.__class__.__name__.lower())
        self.cam_node.setScene(env.NP)
        self.NP = NodePath(self.cam_node)
        self.NP.reparentTo(env.NP)
        self.LENS = self.cam_node.getLens()
        self.LENS.setFar(_cam.FAR)
        self.LENS.setFov(base.camLens.getFov())
        self.FOCUS = None
        
        self.focus_pos = LVector3d(0,0,0)
        self.sys_pos = LVector3d(0,0,0)
コード例 #13
0
class SkyAOCaptureStage(RenderStage):
    """ This stage captures the sky ao by rendering the scene from above """

    required_inputs = []
    required_pipes = []

    @property
    def produced_pipes(self):
        return {"SkyAOHeight": self.target_convert.color_tex}

    @property
    def produced_inputs(self):
        return {"SkyAOCapturePosition": self.pta_position}

    def __init__(self, pipeline):
        RenderStage.__init__(self, pipeline)
        self.pta_position = PTALVecBase3f.empty_array(1)
        self.resolution = 512
        self.capture_height = 100.0
        self.max_radius = 100.0

    def create(self):
        self.camera = Camera("SkyAOCaptureCam")
        self.cam_lens = OrthographicLens()
        self.cam_lens.set_film_size(self.max_radius, self.max_radius)
        self.cam_lens.set_near_far(0, self.capture_height)
        self.camera.set_lens(self.cam_lens)
        self.cam_node = Globals.base.render.attach_new_node(self.camera)
        self.cam_node.look_at(0, 0, -1)
        self.cam_node.set_r(0)

        self.target = self.create_target("SkyAOCapture")
        self.target.size = self.resolution
        self.target.add_depth_attachment(bits=16)
        self.target.prepare_render(self.cam_node)

        self.target_convert = self.create_target("ConvertDepth")
        self.target_convert.size = self.resolution
        self.target_convert.add_color_attachment(bits=(16, 0, 0, 0))
        self.target_convert.prepare_buffer()

        self.target_convert.set_shader_inputs(DepthTex=self.target.depth_tex,
                                              position=self.pta_position)

        # Register camera
        self._pipeline.tag_mgr.register_camera("shadow", self.camera)

    def update(self):
        snap_size = self.max_radius / self.resolution
        cam_pos = Globals.base.camera.get_pos(Globals.base.render)
        self.cam_node.set_pos(cam_pos.x - cam_pos.x % snap_size,
                              cam_pos.y - cam_pos.y % snap_size,
                              self.capture_height / 2.0)
        self.pta_position[0] = self.cam_node.get_pos()

    def reload_shaders(self):
        self.target_convert.shader = self.load_plugin_shader(
            "convert_depth.frag.glsl")
コード例 #14
0
class CameraInstanceComponent(PandaInstanceComponent):
    def __init__(self, entity, component):
        self._camera = Camera(entity.__class__.__name__)

    def set_root_nodepath(self, nodepath):
        nodepath.attach_new_node(self._camera)

    def on_destroyed(self):
        self._camera.remove_node()
コード例 #15
0
    def renderQuadInto(self,
                       mul=1,
                       div=1,
                       align=1,
                       depthtex=None,
                       colortex=None,
                       auxtex0=None,
                       auxtex1=None):
        """ Creates an offscreen buffer for an intermediate
        computation. Installs a quad into the buffer.  Returns
        the fullscreen quad.  The size of the buffer is initially
        equal to the size of the main window.  The parameters 'mul',
        'div', and 'align' can be used to adjust that size. """

        texgroup = (depthtex, colortex, auxtex0, auxtex1)

        winx, winy = self.getScaledSize(mul, div, align)

        depthbits = bool(depthtex != None)

        buffer = self.createBuffer("filter-stage", winx, winy, texgroup,
                                   depthbits)

        if (buffer == None):
            return None

        cm = CardMaker("filter-stage-quad")
        cm.setFrameFullscreenQuad()
        quad = NodePath(cm.generate())
        quad.setDepthTest(0)
        quad.setDepthWrite(0)
        quad.setColor(1, 0.5, 0.5, 1)

        quadcamnode = Camera("filter-quad-cam")
        lens = OrthographicLens()
        lens.setFilmSize(2, 2)
        lens.setFilmOffset(0, 0)
        lens.setNearFar(-1000, 1000)
        quadcamnode.setLens(lens)
        quadcam = quad.attachNewNode(quadcamnode)

        dr = buffer.makeDisplayRegion((0, 1, 0, 1))
        dr.disableClears()
        dr.setCamera(quadcam)
        dr.setActive(True)
        dr.setScissorEnabled(False)

        # This clear stage is important if the buffer is padded, so that
        # any pixels accidentally sampled in the padded region won't
        # be reading from unititialised memory.
        buffer.setClearColor((0, 0, 0, 1))
        buffer.setClearColorActive(True)

        self.buffers.append(buffer)
        self.sizes.append((mul, div, align))

        return quad
コード例 #16
0
    def create(self):
        # Create the atlas target
        self.target = RenderTarget("ShadowAtlas")
        self.target.setSize(self.size)
        self.target.addDepthTexture()
        self.target.setDepthBits(32)
        self.target.setColorWrite(False)
        self.target.setCreateOverlayQuad(False)
        # self.target.setActive(False)
        self.target.setSource(
            NodePath(Camera("tmp")), Globals.base.win)

        self.target.prepareSceneRender()
        self.target.setClearDepth(False)


        # Set the appropriate filter modes
        dTex = self.target.getDepthTexture()
        dTex.setWrapU(SamplerState.WMClamp)
        dTex.setWrapV(SamplerState.WMClamp)

        # Remove the default postprocess quad
        # self.target.getQuad().node().removeAllChildren()
        # self.target.getInternalRegion().setSort(-200)
        self.target.getInternalRegion().disableClears()
        self.target.getInternalBuffer().disableClears()
        # self.target.getInternalBuffer().setSort(-300)

        # Create a camera for each update
        self.shadowCameras = []
        for i in xrange(self.maxRegions):
            shadowCam = Camera("ShadowMapCamera-" + str(i))
            shadowCam.setTagStateKey("ShadowPassShader")
            # shadowCam.setCameraMask(BitMask32.bit(3))
            shadowCamNode = self.shadowScene.attachNewNode(shadowCam)
            self.shadowCameras.append(shadowCamNode)

        # Create regions
        self.renderRegions = []
        buff = self.target.getInternalBuffer()
        
        for i in xrange(self.maxRegions):
            dr = buff.makeDisplayRegion()
            dr.setSort(1000)
            dr.setClearDepthActive(True)
            dr.setClearDepth(1.0)
            # dr.setClearColorActive(False)
            # dr.setClearColor(Vec4(1,1,1,1))
            dr.setCamera(self.shadowCameras[i])
            dr.setActive(False)
            self.renderRegions.append(dr)

        self.pcfSampleState = SamplerState()
        self.pcfSampleState.setMinfilter(SamplerState.FTShadow)
        self.pcfSampleState.setMagfilter(SamplerState.FTShadow)
        self.pcfSampleState.setWrapU(SamplerState.WMClamp)
        self.pcfSampleState.setWrapV(SamplerState.WMClamp)
コード例 #17
0
 def _makeFullscreenCam(self):
     """ Create a orthographic camera for this buffer """
     bufferCam = Camera("BufferCamera")
     lens = OrthographicLens()
     lens.setFilmSize(2, 2)
     lens.setFilmOffset(0, 0)
     lens.setNearFar(-1000, 1000)
     bufferCam.setLens(lens)
     bufferCam.setCullBounds(OmniBoundingVolume())
     return bufferCam
コード例 #18
0
    def create_camera(self, name, projection_mat):
        """
        Create a camera with the given projection matrix.
        """

        cam_node = Camera(name)
        lens = MatrixLens()
        lens.set_user_mat(projection_mat)
        cam_node.set_lens(lens)
        return cam_node
コード例 #19
0
 def renderSceneInto(self, depthtex=None, colortex=None, auxtex=None, auxbits=0, textures=None):
     if textures:
         colortex = textures.get('color', None)
         depthtex = textures.get('depth', None)
         auxtex = textures.get('aux', None)
         auxtex0 = textures.get('aux0', auxtex)
         auxtex1 = textures.get('aux1', None)
     else:
         auxtex0 = auxtex
         auxtex1 = None
     if colortex == None:
         colortex = Texture('filter-base-color')
         colortex.setWrapU(Texture.WMClamp)
         colortex.setWrapV(Texture.WMClamp)
     texgroup = (depthtex, colortex, auxtex0, auxtex1)
     winx, winy = self.getScaledSize(1, 1, 1)
     buffer = self.createBuffer('filter-base', winx, winy, texgroup)
     if buffer == None:
         return
     cm = CardMaker('filter-base-quad')
     cm.setFrameFullscreenQuad()
     quad = NodePath(cm.generate())
     quad.setDepthTest(0)
     quad.setDepthWrite(0)
     quad.setTexture(colortex)
     quad.setColor(1, 0.5, 0.5, 1)
     cs = NodePath('dummy')
     cs.setState(self.camstate)
     if auxbits:
         cs.setAttrib(AuxBitplaneAttrib.make(auxbits))
     self.camera.node().setInitialState(cs.getState())
     quadcamnode = Camera('filter-quad-cam')
     lens = OrthographicLens()
     lens.setFilmSize(2, 2)
     lens.setFilmOffset(0, 0)
     lens.setNearFar(-1000, 1000)
     quadcamnode.setLens(lens)
     quadcam = quad.attachNewNode(quadcamnode)
     self.region.setCamera(quadcam)
     self.setStackedClears(buffer, self.rclears, self.wclears)
     if auxtex0:
         buffer.setClearActive(GraphicsOutput.RTPAuxRgba0, 1)
         buffer.setClearValue(GraphicsOutput.RTPAuxRgba0, (0.5, 0.5, 1.0, 0.0))
     if auxtex1:
         buffer.setClearActive(GraphicsOutput.RTPAuxRgba1, 1)
     self.region.disableClears()
     if self.isFullscreen():
         self.win.disableClears()
     dr = buffer.makeDisplayRegion()
     dr.disableClears()
     dr.setCamera(self.camera)
     dr.setActive(1)
     self.buffers.append(buffer)
     self.sizes.append((1, 1, 1))
     return quad
コード例 #20
0
    def create(self):
        # Create the atlas target
        self.target = RenderTarget("ShadowAtlas")
        self.target.setSize(self.size)
        self.target.addDepthTexture()
        self.target.setDepthBits(32)
        self.target.setColorWrite(False)
        self.target.setCreateOverlayQuad(False)
        # self.target.setActive(False)
        self.target.setSource(NodePath(Camera("tmp")), Globals.base.win)

        self.target.prepareSceneRender()
        self.target.setClearDepth(False)

        # Set the appropriate filter modes
        dTex = self.target.getDepthTexture()
        dTex.setWrapU(SamplerState.WMClamp)
        dTex.setWrapV(SamplerState.WMClamp)

        # Remove the default postprocess quad
        # self.target.getQuad().node().removeAllChildren()
        # self.target.getInternalRegion().setSort(-200)
        self.target.getInternalRegion().disableClears()
        self.target.getInternalBuffer().disableClears()
        # self.target.getInternalBuffer().setSort(-300)

        # Create a camera for each update
        self.shadowCameras = []
        for i in xrange(self.maxRegions):
            shadowCam = Camera("ShadowMapCamera-" + str(i))
            shadowCam.setTagStateKey("ShadowPassShader")
            # shadowCam.setCameraMask(BitMask32.bit(3))
            shadowCamNode = self.shadowScene.attachNewNode(shadowCam)
            self.shadowCameras.append(shadowCamNode)

        # Create regions
        self.renderRegions = []
        buff = self.target.getInternalBuffer()

        for i in xrange(self.maxRegions):
            dr = buff.makeDisplayRegion()
            dr.setSort(1000)
            dr.setClearDepthActive(True)
            dr.setClearDepth(1.0)
            # dr.setClearColorActive(False)
            # dr.setClearColor(Vec4(1,1,1,1))
            dr.setCamera(self.shadowCameras[i])
            dr.setActive(False)
            self.renderRegions.append(dr)

        self.pcfSampleState = SamplerState()
        self.pcfSampleState.setMinfilter(SamplerState.FTShadow)
        self.pcfSampleState.setMagfilter(SamplerState.FTShadow)
        self.pcfSampleState.setWrapU(SamplerState.WMClamp)
        self.pcfSampleState.setWrapV(SamplerState.WMClamp)
コード例 #21
0
 def _make_fullscreen_cam(self):
     """ Creates an orthographic camera for the buffer """
     buffer_cam = Camera("BufferCamera")
     lens = OrthographicLens()
     lens.set_film_size(2, 2)
     lens.set_film_offset(0, 0)
     lens.set_near_far(-100, 100)
     buffer_cam.set_lens(lens)
     buffer_cam.set_cull_bounds(OmniBoundingVolume())
     self._camera = self._node.attach_new_node(buffer_cam)
     self._region.set_camera(self._camera)
コード例 #22
0
    def __init__(self, env):
        self.env = env
        self.cam_node = Camera(self.__class__.__name__.lower())
        self.cam_node.setScene(env.NP)
        self.NP = NodePath(self.cam_node)
        self.NP.reparentTo(env.NP)
        self.LENS = self.cam_node.getLens()
        self.LENS.setFar(_cam.FAR)
        self.LENS.setFov(base.camLens.getFov())
        self.FOCUS = None

        self.focus_pos = LVector3d(0, 0, 0)
        self.sys_pos = LVector3d(0, 0, 0)
コード例 #23
0
    def _initDepthCapture(self):

        for camera in self.cameras:

            camNode = Camera('Depth camera')
            camNode.setCameraMask(self.cameraMask)
            lens = PerspectiveLens()
            lens.setFov(self.fov)
            lens.setAspectRatio(float(self.size[0]) / float(self.size[1]))
            lens.setNear(self.zNear)
            lens.setFar(self.zFar)
            camNode.setLens(lens)
            camNode.setScene(self.scene.scene)
            cam = camera.attachNewNode(camNode)

            winprops = WindowProperties.size(self.size[0], self.size[1])
            fbprops = FrameBufferProperties.getDefault()
            fbprops = FrameBufferProperties(fbprops)
            fbprops.setRgbColor(False)
            fbprops.setRgbaBits(0, 0, 0, 0)
            fbprops.setStencilBits(0)
            fbprops.setMultisamples(0)
            fbprops.setBackBuffers(0)
            fbprops.setDepthBits(16)

            flags = GraphicsPipe.BFFbPropsOptional
            if self.mode == 'onscreen':
                flags = flags | GraphicsPipe.BFRequireWindow
            elif self.mode == 'offscreen':
                flags = flags | GraphicsPipe.BFRefuseWindow
            else:
                raise Exception('Unsupported rendering mode: %s' % (self.mode))

            buf = self.graphicsEngine.makeOutput(self.pipe, 'Depth buffer', 0,
                                                 fbprops, winprops, flags)
            if buf is None:
                raise Exception('Unable to create depth buffer')

            # Set to render at the end
            buf.setSort(10000)

            dr = buf.makeDisplayRegion()
            dr.setSort(0)
            dr.setCamera(cam)
            dr = camNode.getDisplayRegion(0)

            tex = Texture()
            tex.setFormat(Texture.FDepthComponent)
            tex.setComponentType(Texture.TFloat)
            buf.addRenderTexture(tex, GraphicsOutput.RTMCopyRam,
                                 GraphicsOutput.RTPDepth)
            # XXX: should use tex.setMatchFramebufferFormat(True)?

            agent = camera.getParent()
            self.depthBuffers[agent.getName()] = buf
            self.depthTextures[agent.getName()] = tex
コード例 #24
0
    def renderQuadInto(self, mul=1, div=1, align=1, depthtex=None, colortex=None, auxtex0=None, auxtex1=None):

        """ Creates an offscreen buffer for an intermediate
        computation. Installs a quad into the buffer.  Returns
        the fullscreen quad.  The size of the buffer is initially
        equal to the size of the main window.  The parameters 'mul',
        'div', and 'align' can be used to adjust that size. """

        texgroup = (depthtex, colortex, auxtex0, auxtex1)

        winx, winy = self.getScaledSize(mul, div, align)
        
        depthbits = bool(depthtex != None)

        buffer = self.createBuffer("filter-stage", winx, winy, texgroup, depthbits)

        if (buffer == None):
            return None

        cm = CardMaker("filter-stage-quad")
        cm.setFrameFullscreenQuad()
        quad = NodePath(cm.generate())
        quad.setDepthTest(0)
        quad.setDepthWrite(0)
        quad.setColor(1, 0.5, 0.5, 1)

        quadcamnode = Camera("filter-quad-cam")
        lens = OrthographicLens()
        lens.setFilmSize(2, 2)
        lens.setFilmOffset(0, 0)
        lens.setNearFar(-1000, 1000)
        quadcamnode.setLens(lens)
        quadcam = quad.attachNewNode(quadcamnode)

        dr = buffer.makeDisplayRegion((0, 1, 0, 1))
        dr.disableClears()
        dr.setCamera(quadcam)
        dr.setActive(True)
        dr.setScissorEnabled(False)

        # This clear stage is important if the buffer is padded, so that
        # any pixels accidentally sampled in the padded region won't
        # be reading from unititialised memory.
        buffer.setClearColor((0, 0, 0, 1))
        buffer.setClearColorActive(True)

        self.buffers.append(buffer)
        self.sizes.append((mul, div, align))
        
        return quad
コード例 #25
0
 def enable(self):
     camNode = Camera('shadowCam')
     camNode.setCameraMask(CIGlobals.ShadowCameraBitmask)
     self.shadowLens = OrthographicLens()
     self.shadowLens.setFilmSize(60 * 4, 60 * 4)
     camNode.setLens(self.shadowLens)
     self.shadowCamArm = camera.attachNewNode('shadowCamArm')
     self.shadowCam = self.shadowCamArm.attachNewNode(camNode)
     self.shadowCamArm.setPos(0, 40, 0)
     self.shadowCam.setPos(0, -40, 0)
     self.shadowTex = Texture('shadow')
     self.shadowTex.setBorderColor(self.clearColor)
     self.shadowTex.setWrapU(Texture.WMBorderColor)
     self.shadowTex.setWrapV(Texture.WMBorderColor)
     self.casterState = NodePath('temp')
     self.casterState.setColorScaleOff(10)
     self.casterState.setColor(self.shadowColor, self.shadowColor,
                               self.shadowColor, 1, 10)
     self.casterState.setTextureOff(10)
     self.casterState.setLightOff(10)
     self.casterState.setFogOff(10)
     camNode.setInitialState(self.casterState.getState())
     render.hide(CIGlobals.ShadowCameraBitmask)
     self.shadowStage = TextureStage('shadow')
     self.shadowStage.setSort(1000)
     self.turnOnShadows()
コード例 #26
0
    def create(self):

        earlyZ = self.pipeline.settings.enableEarlyZ

        if earlyZ:
            self.prepassCam = Camera(Globals.base.camNode)
            self.prepassCam.setTagStateKey("EarlyZShader")
            self.prepassCam.setName("EarlyZCamera")
            self.prepassCamNode = Globals.base.camera.attachNewNode(
                self.prepassCam)
            Globals.render.setTag("EarlyZShader", "Default")
        else:
            self.prepassCam = None

        # modify default camera initial state
        initial = Globals.base.camNode.getInitialState()
        initialNode = NodePath("IntiialState")
        initialNode.setState(initial)

        if earlyZ:
            initialNode.setAttrib(DepthWriteAttrib.make(DepthWriteAttrib.MOff))
            initialNode.setAttrib(DepthTestAttrib.make(DepthTestAttrib.MEqual))
            pass
        else:
            initialNode.setAttrib(
                DepthTestAttrib.make(DepthTestAttrib.MLessEqual))

        # initialNode.setAttrib(ColorWriteAttrib.make(ColorWriteAttrib.COff), 10000)
        # initialNode.setAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullClockwise), 10000)
        Globals.base.camNode.setInitialState(initialNode.getState())

        self.target = RenderTarget("DeferredScenePass")
        self.target.addColorAndDepth()
        self.target.addAuxTextures(3)
        self.target.setAuxBits(16)
        self.target.setDepthBits(32)
        self.target.setCreateOverlayQuad(False)

        if earlyZ:
            self.target.prepareSceneRender(earlyZ=True,
                                           earlyZCam=self.prepassCamNode)
        else:
            self.target.prepareSceneRender()

        self.target.setClearColor(True, color=Vec4(1, 1, 0, 1))

        if earlyZ:
            self.target.setClearDepth(False)
        else:
            self.target.setClearDepth(True)
コード例 #27
0
    def create(self):
        self.camera = Camera("PSSMSceneSunShadowCam")
        self.cam_lens = OrthographicLens()
        self.cam_lens.set_film_size(400, 400)
        self.cam_lens.set_near_far(100.0, 1800.0)
        self.camera.set_lens(self.cam_lens)
        self.cam_node = Globals.base.render.attach_new_node(self.camera)

        self.target = self.create_target("ShadowMap")
        self.target.size = self.resolution
        self.target.add_depth_attachment(bits=32)
        self.target.prepare_render(self.cam_node)

        # Register shadow camera
        self._pipeline.tag_mgr.register_camera("shadow", self.camera)
コード例 #28
0
    def create(self):
        self.camera = Camera("SkyAOCaptureCam")
        self.cam_lens = OrthographicLens()
        self.cam_lens.set_film_size(200, 200)
        self.cam_lens.set_near_far(0.0, 500.0)
        self.camera.set_lens(self.cam_lens)
        self.cam_node = Globals.base.render.attach_new_node(self.camera)
        self.cam_node.look_at(0, 0, -1)
        self.cam_node.set_r(0)

        self.target = self.create_target("SkyAOCapture")
        self.target.size = 1024
        self.target.add_depth_attachment(bits=16)
        self.target.prepare_render(self.cam_node)

        self.target_convert = self.create_target("ConvertDepth")
        self.target_convert.size = 1024
        self.target_convert.add_color_attachment(bits=(16, 0, 0, 0))
        self.target_convert.prepare_buffer()

        self.target_convert.set_shader_input("DepthTex", self.target.depth_tex)
        self.target_convert.set_shader_input("position", self.pta_position)

        # Register camera
        self._pipeline.tag_mgr.register_camera("shadow", self.camera)
コード例 #29
0
    def create(self):
        # Create the voxel grid used to store the voxels
        self._voxel_grid = Image.create_3d(
            "Voxels", self._voxel_res, self._voxel_res, self._voxel_res, Texture.T_float, Texture.F_r11_g11_b10
        )
        self._voxel_grid.set_clear_color(Vec4(0))

        # Create the camera for voxelization
        self._voxel_cam = Camera("VoxelizeCam")
        self._voxel_cam.set_camera_mask(self._pipeline.tag_mgr.get_voxelize_mask())
        self._voxel_cam_lens = OrthographicLens()
        self._voxel_cam_lens.set_film_size(-self._voxel_ws, self._voxel_ws)
        self._voxel_cam_lens.set_near_far(0.0, 2.0 * self._voxel_ws)
        self._voxel_cam.set_lens(self._voxel_cam_lens)
        self._voxel_cam_np = Globals.base.render.attach_new_node(self._voxel_cam)
        self._pipeline.tag_mgr.register_voxelize_camera(self._voxel_cam)

        # Create the voxelization target
        self._voxel_target = self._create_target("VoxelizeScene")
        self._voxel_target.set_source(source_cam=self._voxel_cam_np, source_win=Globals.base.win)
        self._voxel_target.set_size(self._voxel_res, self._voxel_res)
        self._voxel_target.set_create_overlay_quad(False)
        self._voxel_target.prepare_scene_render()

        # Create the initial state used for rendering voxels
        initial_state = NodePath("VXInitialState")
        initial_state.set_attrib(CullFaceAttrib.make(CullFaceAttrib.M_cull_none), 100000)
        initial_state.set_attrib(DepthTestAttrib.make(DepthTestAttrib.M_none), 100000)
        initial_state.set_attrib(ColorWriteAttrib.make(ColorWriteAttrib.C_off), 100000)
        self._voxel_cam.set_initial_state(initial_state.get_state())

        Globals.base.render.set_shader_input("voxelGridPosition", self._pta_grid_pos)
        Globals.base.render.set_shader_input("voxelGridRes", self._pta_grid_res)
        Globals.base.render.set_shader_input("voxelGridSize", self._pta_grid_size)
        Globals.base.render.set_shader_input("VoxelGridDest", self._voxel_grid.texture)
コード例 #30
0
    def __init__(self, base, *args, label='golog', **kwargs):
        self.base = base

        #initialize with an empty nodepath and no window
        #initialize a golog with no relative path (shouldn't be able to open files without one though)
        defaults = {'render': 'NodePath(label+\"_render\")'}
        for key in defaults:
            if key in kwargs: setattr(self, key, kwargs[key])
            else: setattr(self, key, eval(defaults[key]))

        self.Simplex_to_Graphics = dict()
        self.Graphics_to_Simplex = dict()
        self.NP_to_Graphics = dict()
        # Initialize simplicial set
        self.label = label
        self.sSet = hcat.simpSet(label=self.label, data={'node': self.render})
        self.sSet.simplex_to_graphics = dict()
        self.sSet.data['export_tag'] = 'golog'

        self.NPtoSimplex = dict()

        # set up camera
        self.camNode = Camera(label + "camNode")
        self.camera = self.render.attachNewNode(self.camNode)
        self.camera.setPos(0, -Camera_Distance, 0)

        # Load Models
        self.sphere = base.loader.loadModel("./misc_data/models/sphere.egg.pz")
        self.cone = base.loader.loadModel("./misc_data/models/sphere.egg.pz")
        self.cone.setScale(.6)

        #set up collision traverser
        #? move to mode_head?
        self.cTrav = CollisionTraverser(self.label + '_traverser')
コード例 #31
0
    def __init__(self):
        """ Creates a new ShadowSource. After the creation, a lens can be added
        with setupPerspectiveLens or setupOrtographicLens. """
        self.index = self._generateUID()
        DebugObject.__init__(self, "ShadowSource-" + str(self.index))
        ShaderStructElement.__init__(self)

        self.valid = False
        self.camera = Camera("ShadowSource-" + str(self.index))
        self.camera.setActive(False)
        self.cameraNode = NodePath(self.camera)
        self.cameraNode.reparentTo(Globals.render.find("RPCameraDummys"))
        self.cameraNode.hide()
        self.resolution = 512
        self.atlasPos = Vec2(0)
        self.doesHaveAtlasPos = False
        self.sourceIndex = 0
        self.mvp = UnalignedLMatrix4f()
        self.sourceIndex = -1
        self.nearPlane = 0.0
        self.farPlane = 1000.0
        self.converterYUR = None
        self.transforMat = TransformState.makeMat(
            Mat4.convertMat(Globals.base.win.getGsg().getInternalCoordinateSystem(),
                            CSZupRight))
コード例 #32
0
ファイル: GBufferStage.py プロジェクト: wdmwdm/RenderPipeline
    def _prepare_early_z(self, early_z=False):
        """ Prepares the earlyz stage """
        if early_z:
            self._prepass_cam = Camera(Globals.base.camNode)
            self._prepass_cam.set_tag_state_key("EarlyZShader")
            self._prepass_cam.set_name("EarlyZCamera")
            self._prepass_cam_node = Globals.base.camera.attach_new_node(
                self._prepass_cam)
            Globals.render.set_tag("EarlyZShader", "Default")
        else:
            self._prepass_cam = None

        # modify default camera initial state
        initial = Globals.base.camNode.get_initial_state()
        initial_node = NodePath("IntialState")
        initial_node.set_state(initial)

        if early_z:
            initial_node.set_attrib(
                DepthWriteAttrib.make(DepthWriteAttrib.M_off))
            initial_node.set_attrib(
                DepthTestAttrib.make(DepthTestAttrib.M_equal))
        else:
            initial_node.set_attrib(
                DepthTestAttrib.make(DepthTestAttrib.M_less_equal))

        Globals.base.camNode.set_initial_state(initial_node.get_state())
コード例 #33
0
    def create(self):
        # Create voxelize camera
        self.voxelizeCamera = Camera("VoxelizeCamera")
        self.voxelizeCamera.setCameraMask(BitMask32.bit(4))
        self.voxelizeCameraNode = Globals.render.attachNewNode(self.voxelizeCamera)
        self.voxelizeLens = OrthographicLens()
        self.voxelizeLens.setFilmSize(self.voxelGridSize * 2, self.voxelGridSize * 2)
        self.voxelizeLens.setNearFar(0.0, self.voxelGridSize * 2)
        self.voxelizeCamera.setLens(self.voxelizeLens)
        self.voxelizeCamera.setTagStateKey("VoxelizePassShader")
        Globals.render.setTag("VoxelizePassShader", "Default")

        # Create voxelize tareet
        self.target = RenderTarget("VoxelizePass")
        self.target.setSize(self.voxelGridResolution * self.gridResolutionMultiplier)

        if self.pipeline.settings.useDebugAttachments:
            self.target.addColorTexture()
        else:
            self.target.setColorWrite(False)

        self.target.setCreateOverlayQuad(False)
        self.target.setSource(self.voxelizeCameraNode, Globals.base.win)
        self.target.prepareSceneRender()
        self.target.setActive(False)
コード例 #34
0
    def create(self):
        self.camera = Camera("PSSMDistShadowsESM")
        self.cam_lens = OrthographicLens()
        self.cam_lens.set_film_size(12000, 12000)
        self.cam_lens.set_near_far(10.0, self.sun_distance * 2)
        self.camera.set_lens(self.cam_lens)
        self.cam_node = Globals.base.render.attach_new_node(self.camera)

        self.target = self.create_target("ShadowMap")
        self.target.size = self.resolution
        self.target.add_depth_attachment(bits=32)
        self.target.prepare_render(self.cam_node)

        self.target_convert = self.create_target("ConvertToESM")
        self.target_convert.size = self.resolution
        self.target_convert.add_color_attachment(bits=(32, 0, 0, 0))
        self.target_convert.prepare_buffer()
        self.target_convert.set_shader_input("SourceTex", self.target.depth_tex)

        self.target_blur_v = self.create_target("BlurVert")
        self.target_blur_v.size = self.resolution
        self.target_blur_v.add_color_attachment(bits=(32, 0, 0, 0))
        self.target_blur_v.prepare_buffer()
        self.target_blur_v.set_shader_input("SourceTex", self.target_convert.color_tex)
        self.target_blur_v.set_shader_input("direction", LVecBase2i(1, 0))

        self.target_blur_h = self.create_target("BlurHoriz")
        self.target_blur_h.size = self.resolution
        self.target_blur_h.add_color_attachment(bits=(32, 0, 0, 0))
        self.target_blur_h.prepare_buffer()
        self.target_blur_h.set_shader_input("SourceTex", self.target_blur_v.color_tex)
        self.target_blur_h.set_shader_input("direction", LVecBase2i(0, 1))

        # Register shadow camera
        self._pipeline.tag_mgr.register_camera("shadow", self.camera)
コード例 #35
0
    def _prepareVoxelScene(self):
        """ Creates the internal buffer to voxelize the scene on the fly """
        self.voxelizeScene = Globals.render
        self.voxelizeCamera = Camera("VoxelizeScene")
        self.voxelizeCameraNode = self.voxelizeScene.attachNewNode(
            self.voxelizeCamera)
        self.voxelizeLens = OrthographicLens()
        self.voxelizeLens.setFilmSize(self.voxelGridSizeWS.x * 2,
                                      self.voxelGridSizeWS.y * 2)
        self.voxelizeLens.setNearFar(0.0, self.voxelGridSizeWS.x * 2)
        self.voxelizeCamera.setLens(self.voxelizeLens)
        self.voxelizeCamera.setTagStateKey("VoxelizePassShader")

        self.targetSpace.setTag("VoxelizePassShader", "Default")

        self.voxelizeCameraNode.setPos(0, 0, 0)
        self.voxelizeCameraNode.lookAt(0, 0, 0)

        self.voxelizeTarget = RenderTarget("DynamicVoxelization")
        self.voxelizeTarget.setSize(self.voxelBaseResolution)
        # self.voxelizeTarget.addDepthTexture()
        # self.voxelizeTarget.addColorTexture()
        # self.voxelizeTarget.setColorBits(16)
        self.voxelizeTarget.setSource(self.voxelizeCameraNode,
                                      Globals.base.win)
        self.voxelizeTarget.prepareSceneRender()

        self.voxelizeTarget.getQuad().node().removeAllChildren()
        self.voxelizeTarget.getInternalRegion().setSort(-400)
        self.voxelizeTarget.getInternalBuffer().setSort(-399)

        # for tex in [self.voxelizeTarget.getColorTexture()]:
        #     tex.setWrapU(Texture.WMClamp)
        #     tex.setWrapV(Texture.WMClamp)
        #     tex.setMinfilter(Texture.FTNearest)
        #     tex.setMagfilter(Texture.FTNearest)

        voxelSize = Vec3(
            self.voxelGridSizeWS.x * 2.0 / self.voxelGridResolution.x,
            self.voxelGridSizeWS.y * 2.0 / self.voxelGridResolution.y,
            self.voxelGridSizeWS.z * 2.0 / self.voxelGridResolution.z)

        self.targetSpace.setShaderInput("dv_gridSize",
                                        self.voxelGridSizeWS * 2)
        self.targetSpace.setShaderInput("dv_voxelSize", voxelSize)
        self.targetSpace.setShaderInput("dv_gridResolution",
                                        self.voxelGridResolution)
コード例 #36
0
    def _initRgbCapture(self):

        for camera in self.cameras:

            camNode = Camera('Semantic camera')
            camNode.setCameraMask(self.cameraMask)
            lens = PerspectiveLens()
            lens.setFov(self.fov)
            lens.setAspectRatio(float(self.size[0]) / float(self.size[1]))
            lens.setNear(self.zNear)
            lens.setFar(self.zFar)
            camNode.setLens(lens)
            camNode.setScene(self.scene.scene)
            cam = camera.attachNewNode(camNode)

            winprops = WindowProperties.size(self.size[0], self.size[1])
            fbprops = FrameBufferProperties.getDefault()
            fbprops = FrameBufferProperties(fbprops)
            fbprops.setRgbaBits(8, 8, 8, 8)

            flags = GraphicsPipe.BFFbPropsOptional
            if self.mode == 'onscreen':
                flags = flags | GraphicsPipe.BFRequireWindow
            elif self.mode == 'offscreen':
                flags = flags | GraphicsPipe.BFRefuseWindow
            else:
                raise Exception('Unsupported rendering mode: %s' % (self.mode))

            buf = self.graphicsEngine.makeOutput(self.pipe,
                                                 'RGB-buffer-Semantics', 0,
                                                 fbprops, winprops, flags)
            if buf is None:
                raise Exception('Unable to create RGB buffer')

            # Set to render at the end
            buf.setSort(10000)

            dr = buf.makeDisplayRegion()
            dr.setSort(0)
            dr.setCamera(cam)
            dr = camNode.getDisplayRegion(0)

            tex = Texture()
            tex.setFormat(Texture.FRgba8)
            tex.setComponentType(Texture.TUnsignedByte)
            buf.addRenderTexture(tex, GraphicsOutput.RTMCopyRam,
                                 GraphicsOutput.RTPColor)
            # XXX: should use tex.setMatchFramebufferFormat(True)?

            self.rgbBuffers[camera.getNetTag('agent-id')] = buf
            self.rgbTextures[camera.getNetTag('agent-id')] = tex
コード例 #37
0
 def __init__(self):
     DebugObject.__init__(self, "ShadowSource")
     self.valid = False
     ShadowSource._GlobalShadowIndex += 1
     self.index = ShadowSource._GlobalShadowIndex
     self.camera = Camera("ShadowSource-" + str(self.index))
     self.cameraNode = NodePath(self.camera)
     self.cameraNode.reparentTo(render)
     # self.camera.showFrustum()
     self.resolution = 1024
     self.atlasPos = Vec2(0)
     self.doesHaveAtlasPos = False
     self.sourceIndex = 0
     self.mvp = Mat4()
     self.sourceIndex = -1
     self.nearPlane = 0.0
     self.farPlane = 1000.0
コード例 #38
0
class ForwardStage(RenderStage):
    """ Forward shading stage, which first renders all forward objects,
    and then merges them with the scene """

    required_inputs = [
        "DefaultEnvmap", "PrefilteredBRDF", "PrefilteredCoatBRDF", "EnvProbes"
    ]
    required_pipes = [
        "SceneDepth", "ShadedScene", "PerCellProbes", "CellIndices"
    ]

    @property
    def produced_pipes(self):
        return {"ShadedScene": self.target_merge.color_tex}

    def create(self):
        self.forward_cam = Camera("ForwardShadingCam")
        self.forward_cam.set_lens(Globals.base.camLens)
        self.forward_cam_np = Globals.base.camera.attach_new_node(
            self.forward_cam)

        self.target = self.create_target("ForwardShading")
        self.target.add_color_attachment(bits=16, alpha=True)
        self.target.add_depth_attachment(bits=32)
        self.target.prepare_render(self.forward_cam_np)

        self.target.set_clear_color(0, 0, 0, 0)

        self._pipeline.tag_mgr.register_camera("forward", self.forward_cam)

        self.target_merge = self.create_target("MergeWithDeferred")
        self.target_merge.add_color_attachment(bits=16)
        self.target_merge.prepare_buffer()
        self.target_merge.set_shader_input("ForwardDepth",
                                           self.target.depth_tex)
        self.target_merge.set_shader_input("ForwardColor",
                                           self.target.color_tex)

    def set_shader_input(self, *args):
        Globals.base.render.set_shader_input(*args)
        RenderStage.set_shader_input(self, *args)

    def reload_shaders(self):
        self.target_merge.shader = self.load_plugin_shader(
            "merge_with_deferred.frag.glsl")
コード例 #39
0
ファイル: cosmonium.py プロジェクト: cosmonium/cosmonium
 def create_additional_display_regions(self):
     self.near_dr = self.win.make_display_region()
     self.near_dr.set_sort(1)
     self.near_dr.set_clear_depth_active(True)
     near_cam_node = Camera('nearcam')
     self.near_cam = self.camera.attach_new_node(near_cam_node)
     self.near_dr.setCamera(self.near_cam)
     self.near_cam.node().set_camera_mask(BaseObject.NearCameraMask)
     self.near_cam.node().get_lens().set_near_far(units.m /settings.scale, float('inf'))
コード例 #40
0
    def __init__(self, *args, **kwargs):
        Controller.__init__(self, *args,
                            **exclude_from_dict(kwargs, ["camera", "origin"]))

        self.__base = self._services.graphics.window
        self.__cam = kwargs["camera"] if "camera" in kwargs else self.__base.cam
        self.__origin = kwargs["origin"]

        self.camNode = Camera('cam')
        self.camNP = NodePath(self.camNode)
        self.camNP.reparentTo(self.__origin)

        self.lens = self.__base.camNode.getLens()
        self.target_size = 6.37800000E+06
        self.render_ratio = 1.0e-6
        self.deg_per_sec = 60.0
        self.min_dist = 3.0
        self.max_dist = 4000.0
        self.zoom_per_sec = 4
        self.longitude_deg = 0.0
        self.latitude_deg = -25
        self.dist = 10.0
        self.key_map = {
            "left": 0,
            "right": 0,
            "up": 0,
            "down": 0,
            "wheelup": 0,
            "wheeldown": 0,
            "top_view": 0
        }

        self.angle = 0

        # EVENTS #

        # disables the default camera behaviour
        self.__base.disable_mouse()

        # Setup down events for arrow keys : rotating camera latitude and longitude
        self.accept("a", self.update_key_map, ["left", 1])
        self.accept("d", self.update_key_map, ["right", 1])
        self.accept("w", self.update_key_map, ["up", 1])
        self.accept("s", self.update_key_map, ["down", 1])
        self.accept("q", self.update_key_map, ["top_view", 1])
        self.accept("a-up", self.update_key_map, ["left", 0])
        self.accept("d-up", self.update_key_map, ["right", 0])
        self.accept("w-up", self.update_key_map, ["up", 0])
        self.accept("s-up", self.update_key_map, ["down", 0])

        # Use the scroll mouse button/touchpad to zoom in and out
        self.accept("wheel_up", self.update_key_map, ["wheelup", 1])
        self.accept("wheel_down", self.update_key_map, ["wheeldown", 1])

        self.__task = self.__base.taskMgr.add(self.move_orbital_camera_task,
                                              "move_orbital_camera_task")
コード例 #41
0
ファイル: SpotLight.py プロジェクト: swq0553/RenderPipeline
    def __init__(self):
        """ Creates a new spot light. """
        Light.__init__(self)
        DebugObject.__init__(self, "SpotLight")
        self.typeName = "SpotLight"

        self.nearPlane = 0.5
        self.radius = 30.0
        self.spotSize = Vec2(30, 30)

        # Used to compute the MVP
        self.ghostCamera = Camera("PointLight")
        self.ghostCamera.setActive(False)
        self.ghostLens = PerspectiveLens()
        self.ghostLens.setFov(130)
        self.ghostCamera.setLens(self.ghostLens)
        self.ghostCameraNode = NodePath(self.ghostCamera)
        self.ghostCameraNode.reparentTo(Globals.render)
        self.ghostCameraNode.hide()
コード例 #42
0
    def create(self):
        self.forward_cam = Camera("ForwardShadingCam")
        self.forward_cam.set_lens(Globals.base.camLens)
        self.forward_cam_np = Globals.base.camera.attach_new_node(self.forward_cam)

        self.target = self.create_target("ForwardShading")
        self.target.add_color_attachment(bits=16, alpha=True)
        self.target.add_depth_attachment(bits=32)
        self.target.prepare_render(self.forward_cam_np)
        self.target.set_clear_color(0, 0, 0, 0)

        self._pipeline.tag_mgr.register_camera("forward", self.forward_cam)

        self.target_merge = self.create_target("MergeWithDeferred")
        self.target_merge.add_color_attachment(bits=16)
        self.target_merge.prepare_buffer()
        self.target_merge.set_shader_inputs(
            ForwardDepth=self.target.depth_tex,
            ForwardColor=self.target.color_tex)
コード例 #43
0
class ForwardStage(RenderStage):

    """ Forward shading stage, which first renders all forward objects,
    and then merges them with the scene """

    required_inputs = ["DefaultEnvmap", "PrefilteredBRDF", "PrefilteredCoatBRDF"]
    required_pipes = ["SceneDepth", "ShadedScene", "CellIndices"]

    @property
    def produced_pipes(self):
        return {"ShadedScene": self.target_merge.color_tex}

    def create(self):
        self.forward_cam = Camera("ForwardShadingCam")
        self.forward_cam.set_lens(Globals.base.camLens)
        self.forward_cam_np = Globals.base.camera.attach_new_node(self.forward_cam)

        self.target = self.create_target("ForwardShading")
        self.target.add_color_attachment(bits=16, alpha=True)
        self.target.add_depth_attachment(bits=32)
        self.target.prepare_render(self.forward_cam_np)
        self.target.set_clear_color(0, 0, 0, 0)

        self._pipeline.tag_mgr.register_camera("forward", self.forward_cam)

        self.target_merge = self.create_target("MergeWithDeferred")
        self.target_merge.add_color_attachment(bits=16)
        self.target_merge.prepare_buffer()
        self.target_merge.set_shader_inputs(
            ForwardDepth=self.target.depth_tex,
            ForwardColor=self.target.color_tex)

    def set_shader_input(self, *args):
        Globals.base.render.set_shader_input(*args)
        RenderStage.set_shader_input(self, *args)

    def set_shader_inputs(self, **kwargs):
        Globals.base.render.set_shader_inputs(**kwargs)
        RenderStage.set_shader_inputs(self, **kwargs)

    def reload_shaders(self):
        self.target_merge.shader = self.load_plugin_shader("merge_with_deferred.frag.glsl")
コード例 #44
0
class ForwardInjectionStage(RenderStage):
    """ Forward shading stage, which renders all forward objects and injects
    them into the clustered grid. Also produces a depth map which is used
    later on in the shading stage. """

    required_inputs = []
    required_pipes = []

    @property
    def produced_pipes(self):
        return {}

    def create(self):
        self.forward_cam = Camera("ForwardShadingCam")
        self.forward_cam.set_lens(Globals.base.camLens)
        self.forward_cam_np = Globals.base.camera.attach_new_node(
            self.forward_cam)

        self.target = self.create_target("ForwardShading")
        self.target.add_color_attachment(bits=16, alpha=True)
        self.target.add_depth_attachment(bits=32)
        self.target.prepare_render(self.forward_cam_np)

        self.target.set_clear_color(0, 0, 0, 0)

        self._pipeline.tag_mgr.register_camera("forward", self.forward_cam)

        self.target_merge = self.create_target("MergeWithDeferred")
        self.target_merge.add_color_attachment(bits=16)
        self.target_merge.prepare_buffer()
        self.target_merge.set_shader_input("ForwardDepth",
                                           self.target.depth_tex)
        self.target_merge.set_shader_input("ForwardColor",
                                           self.target.color_tex)

    def set_shader_input(self, *args):
        Globals.base.render.set_shader_input(*args)
        RenderStage.set_shader_input(self, *args)

    def reload_shaders(self):
        self.target_merge.shader = self.load_plugin_shader(
            "merge_with_deferred.frag.glsl")
コード例 #45
0
ファイル: cameras.py プロジェクト: svfgit/solex
 def __init__(self, env):
     self.env = env
     self.cam_node = Camera(self.__class__.__name__.lower())
     self.cam_node.setScene(env.NP)
     self.NP = NodePath(self.cam_node)
     self.NP.reparentTo(env.NP)
     self.LENS = self.cam_node.getLens()
     self.LENS.setFar(_cam.FAR)
     self.LENS.setFov(base.camLens.getFov())
     self.FOCUS = None
     
     self.focus_pos = LVector3d(0,0,0)
     self.sys_pos = LVector3d(0,0,0)
コード例 #46
0
class ForwardInjectionStage(RenderStage):

    """ Forward shading stage, which renders all forward objects and injects
    them into the clustered grid. Also produces a depth map which is used
    later on in the shading stage. """

    required_inputs = []
    required_pipes = []

    @property
    def produced_pipes(self):
        return {}

    def create(self):
        self.forward_cam = Camera("ForwardShadingCam")
        self.forward_cam.set_lens(Globals.base.camLens)
        self.forward_cam_np = Globals.base.camera.attach_new_node(self.forward_cam)

        self.target = self.create_target("ForwardShading")
        self.target.add_color_attachment(bits=16, alpha=True)
        self.target.add_depth_attachment(bits=32)
        self.target.prepare_render(self.forward_cam_np)

        self.target.set_clear_color(0, 0, 0, 0)

        self._pipeline.tag_mgr.register_camera("forward", self.forward_cam)

        self.target_merge = self.create_target("MergeWithDeferred")
        self.target_merge.add_color_attachment(bits=16)
        self.target_merge.prepare_buffer()
        self.target_merge.set_shader_input("ForwardDepth", self.target.depth_tex)
        self.target_merge.set_shader_input("ForwardColor", self.target.color_tex)

    def set_shader_input(self, *args):
        Globals.base.render.set_shader_input(*args)
        RenderStage.set_shader_input(self, *args)

    def reload_shaders(self):
        self.target_merge.shader = self.load_plugin_shader("merge_with_deferred.frag.glsl")
コード例 #47
0
    def create(self):
        self.camera = Camera("PSSMSceneSunShadowCam")
        self.cam_lens = OrthographicLens()
        self.cam_lens.set_film_size(400, 400)
        self.cam_lens.set_near_far(100.0, 1800.0)
        self.camera.set_lens(self.cam_lens)
        self.cam_node = Globals.base.render.attach_new_node(self.camera)

        self.target = self.create_target("ShadowMap")
        self.target.size = self.resolution
        self.target.add_depth_attachment(bits=32)
        self.target.prepare_render(self.cam_node)

        # Register shadow camera
        self._pipeline.tag_mgr.register_camera("shadow", self.camera)
コード例 #48
0
    def create(self):

        earlyZ = self.pipeline.settings.enableEarlyZ

        if earlyZ:
            self.prepassCam = Camera(Globals.base.camNode)
            self.prepassCam.setTagStateKey("EarlyZShader")
            self.prepassCam.setName("EarlyZCamera")
            self.prepassCamNode = Globals.base.camera.attachNewNode(self.prepassCam)
            Globals.render.setTag("EarlyZShader", "Default")
        else:
            self.prepassCam = None

        # modify default camera initial state
        initial = Globals.base.camNode.getInitialState()
        initialNode = NodePath("IntiialState")
        initialNode.setState(initial)
        
        if earlyZ:
            initialNode.setAttrib(DepthWriteAttrib.make(DepthWriteAttrib.MOff))
            initialNode.setAttrib(DepthTestAttrib.make(DepthTestAttrib.MEqual))
            pass
        else:
            initialNode.setAttrib(DepthTestAttrib.make(DepthTestAttrib.MLessEqual))

        # initialNode.setAttrib(ColorWriteAttrib.make(ColorWriteAttrib.COff), 10000)
        # initialNode.setAttrib(CullFaceAttrib.make(CullFaceAttrib.MCullClockwise), 10000)
        Globals.base.camNode.setInitialState(initialNode.getState())

        self.target = RenderTarget("DeferredScenePass")
        self.target.addColorAndDepth()
        self.target.addAuxTextures(3)
        self.target.setAuxBits(16)
        self.target.setDepthBits(32)
        self.target.setCreateOverlayQuad(False)
        
        if earlyZ:
            self.target.prepareSceneRender(earlyZ=True, earlyZCam=self.prepassCamNode)
        else:
            self.target.prepareSceneRender()

        self.target.setClearColor(True, color=Vec4(1, 1, 0, 1))

        if earlyZ:
            self.target.setClearDepth(False)
        else:
            self.target.setClearDepth(True)
コード例 #49
0
    def create(self):
        self.forward_cam = Camera("ForwardShadingCam")
        self.forward_cam.set_lens(Globals.base.camLens)
        self.forward_cam_np = Globals.base.camera.attach_new_node(self.forward_cam)

        self.target = self.create_target("ForwardShading")
        self.target.add_color_attachment(bits=16, alpha=True)
        self.target.add_depth_attachment(bits=32)
        self.target.prepare_render(self.forward_cam_np)
        self.target.set_clear_color(0, 0, 0, 0)

        self._pipeline.tag_mgr.register_camera("forward", self.forward_cam)

        self.target_merge = self.create_target("MergeWithDeferred")
        self.target_merge.add_color_attachment(bits=16)
        self.target_merge.prepare_buffer()
        self.target_merge.set_shader_input("ForwardDepth", self.target.depth_tex)
        self.target_merge.set_shader_input("ForwardColor", self.target.color_tex)
コード例 #50
0
ファイル: Main.py プロジェクト: 2015-CS454/rr-team
    def enterGame(self, task):
        if self.gameState == self.gameStateDict["Login"]:
            # responseValue = 1 indicates that this state has been finished
            if self.responseValue == 1:
                # Authentication succeeded
                self.cManager.sendRequest(Constants.CMSG_CREATE_LOBBY, ["raceroyal", "0", "1"])
                self.gameState = self.gameStateDict["CreateLobby"]
                self.responseValue = -1
        elif self.gameState == self.gameStateDict["CreateLobby"]:
            if self.responseValue == 1:
                # Lobby Created and we are already in
                self.gameState = self.gameStateDict["EnterGame"]
                self.responseValue = -1
            elif self.responseValue == 0:
                # Game already created, let's join it
                self.cManager.sendRequest(Constants.CMSG_ENTER_GAME_NAME, "raceroyal")
                self.gameState = self.gameStateDict["EnterGame"]
                self.responseValue = -1

        elif self.gameState == self.gameStateDict["EnterGame"]:
            if self.responseValue == 1:
                #                 When the positions are sent, an acknowledgment is sent and we begin the InitializeGame
                self.responseValue = -1
                self.gameState = self.gameStateDict["InitializeGame"]
                #               Everyone is in the game, we send ReqReady, and the server will send positions when every client did
                self.cManager.sendRequest(Constants.CMSG_READY)


        elif self.gameState == self.gameStateDict["InitializeGame"]:
            if self.responseValue == 1:
                # Set up the camera
                self.camera = Camera(self.mainChar, self.bulletWorld)
                self.gameState = self.gameStateDict["BeginGame"]
                self.cManager.sendRequest(Constants.CMSG_READY)
                self.responseValue = -1

        elif self.gameState == self.gameStateDict["BeginGame"]:
            if self.responseValue == 1:
                self.loading.finish()
                taskMgr.doMethodLater(.1, self.updateMove, 'updateMove')
                taskMgr.doMethodLater(5, self.move, "moveTask")
                return task.done

        return task.cont
コード例 #51
0
    def create(self):

        self._camera = Camera("VXGISunShadowCam")
        self._cam_lens = OrthographicLens()
        self._cam_lens.set_film_size(400, 400)
        self._cam_lens.set_near_far(0.0, 800.0)
        self._camera.set_lens(self._cam_lens)
        self._cam_node = Globals.base.render.attach_new_node(self._camera)

        self._target = self.make_target("PSSMDistShadowMap")
        self._target.set_source(self._cam_node, Globals.base.win)
        self._target.size = self._resolution
        self._target.add_depth_texture(bits=32)
        self._target.create_overlay_quad = False
        self._target.color_write = False
        self._target.prepare_scene_render()

        # Register shadow camera
        self._pipeline.tag_mgr.register_shadow_camera(self._camera)
コード例 #52
0
    def __init__(self):
        """ Creates a new ShadowSource. After the creation, a lens can be added
        with setupPerspectiveLens. """
        self.index = self._generateUID()

        DebugObject.__init__(self, "ShadowSource-" + str(self.index))
        ShaderStructElement.__init__(self)

        self.valid = False
        self.camera = Camera("ShadowSource-" + str(self.index))
        self.cameraNode = NodePath(self.camera)
        self.cameraNode.reparentTo(Globals.render)
        self.resolution = 1024
        self.atlasPos = Vec2(0)
        self.doesHaveAtlasPos = False
        self.sourceIndex = 0
        self.mvp = Mat4()
        self.sourceIndex = -1
        self.nearPlane = 0.0
        self.farPlane = 1000.0
        self.converterYUR = None
コード例 #53
0
    def init(self):
        for i in range(self._max_updates):
            camera = Camera("ShadowCam-" + str(i))
            camera.set_lens(MatrixLens())
            camera.set_active(False)
            camera.set_scene(self._scene_parent)
            self._tag_state_mgr.register_shadow_camera(camera)
            self._camera_nps.append(self._scene_parent.attach_new_node(camera))
            self._cameras.append(camera)

            region = self._atlas_graphics_output.make_display_region()
            region.set_sort(1000)
            region.set_clear_depth_active(True)
            region.set_clear_depth(1.0)
            region.set_clear_color_active(False)
            region.set_camera(self._camera_nps[i])
            region.set_active(False)
            self._display_regions.append(region)

        self._atlas = ShadowAtlas(self._atlas_size)
コード例 #54
0
    def create(self):
        # Create voxelize camera
        self.voxelizeCamera = Camera("VoxelizeScene")
        self.voxelizeCamera.setCameraMask(BitMask32.bit(4))
        self.voxelizeCameraNode = Globals.render.attachNewNode(self.voxelizeCamera)
        self.voxelizeLens = OrthographicLens()
        self.voxelizeLens.setFilmSize(self.voxelGridSize.x*2, self.voxelGridSize.y*2)
        self.voxelizeLens.setNearFar(0.0, self.voxelGridSize.x*2)
        self.voxelizeCamera.setLens(self.voxelizeLens)
        self.voxelizeCamera.setTagStateKey("VoxelizePassShader")
        Globals.render.setTag("VoxelizePassShader", "Default")

        # Create voxelize tareet
        self.target = RenderTarget("VoxelizePass")
        self.target.setSize( self.voxelGridResolution.x * 4 )
        self.target.setColorWrite(False)
        self.target.setCreateOverlayQuad(False)
        self.target.setSource(self.voxelizeCameraNode, Globals.base.win)
        self.target.prepareSceneRender()
        self.target.setActive(False)

        self.target.getInternalRegion().setSort(-400)
        self.target.getInternalBuffer().setSort(-399)
コード例 #55
0
    def _make_particle_scene(self):

        # Create a new scene root
        self._particle_scene = Globals.base.render.attach_new_node("CloudParticles")
        self._particle_scene.hide(self._pipeline.tag_mgr.get_gbuffer_mask())
        self._particle_scene.hide(self._pipeline.tag_mgr.get_shadow_mask())
        self._particle_scene.hide(self._pipeline.tag_mgr.get_voxelize_mask())

        cm = CardMaker("")
        cm.set_frame(-1.0, 1.0, -1.0, 1.0)
        cm.set_has_normals(False)
        cm.set_has_uvs(False)
        card_node = cm.generate()
        card_node.set_bounds(OmniBoundingVolume())
        card_node.set_final(True)
        self._particle_np = self._particle_scene.attach_new_node(card_node)
        self._particle_np.set_shader_input("CloudVoxels", self._cloud_voxels.get_texture())
        self._particle_np.set_instance_count(self._voxel_res_xy * self._voxel_res_xy * self._voxel_res_z)
        self._particle_np.set_transparency(TransparencyAttrib.M_multisample, 1000000)
        self._particle_scene.set_transparency(TransparencyAttrib.M_multisample, 1000000)

        self._particle_cam = Camera("CloudParticleCam")
        self._particle_cam.set_lens(Globals.base.camLens)
        self._particle_cam_np = self._particle_scene.attach_new_node(self._particle_cam)

        cloud_particle_mask = BitMask32.bit(16)
        self._particle_cam.set_camera_mask(cloud_particle_mask)
        render.hide(cloud_particle_mask)
        self._particle_scene.show_through(cloud_particle_mask)

        self._particle_target = self._create_target("Clouds:RenderParticles")
        self._particle_target.add_color_texture(bits=16)
        self._particle_target.set_source(self._particle_cam_np, Globals.base.win)
        self._particle_target.set_enable_transparency(True)
        self._particle_target.prepare_scene_render()
        self._particle_target.set_clear_color(True, color=Vec4(0, 0, 0, 0))
コード例 #56
0
class ShadowSource(DebugObject, ShaderStructElement):

    """ This class can be seen as a camera. It stores the necessary
    data to generate and store the shadow map for the assigned lens
    (like computing the MVP), and also stores information about the
    shadowmap, like position in the shadow atlas, or resolution. Each
    ShadowSource has a unique index, which is used by the LightClass
    to identify which sources belong to it.

    TODO: Support OrtographicLens
    """

    # Store a global index for assigning unique ids to the instances
    _GlobalShadowIndex = 1000

    @classmethod
    def getExposedAttributes(self):
        return {
            "resolution": "int",
            "atlasPos": "vec2",
            "mvp": "mat4",
            "nearPlane": "float",
            "farPlane": "float"
        }

    @classmethod
    def _generateUID(self):
        """ Generates an uid and returns that """
        self._GlobalShadowIndex += 1
        return self._GlobalShadowIndex

    def __init__(self):
        """ Creates a new ShadowSource. After the creation, a lens can be added
        with setupPerspectiveLens. """
        self.index = self._generateUID()

        DebugObject.__init__(self, "ShadowSource-" + str(self.index))
        ShaderStructElement.__init__(self)

        self.valid = False
        self.camera = Camera("ShadowSource-" + str(self.index))
        self.cameraNode = NodePath(self.camera)
        self.cameraNode.reparentTo(Globals.render)
        self.resolution = 1024
        self.atlasPos = Vec2(0)
        self.doesHaveAtlasPos = False
        self.sourceIndex = 0
        self.mvp = Mat4()
        self.sourceIndex = -1
        self.nearPlane = 0.0
        self.farPlane = 1000.0
        self.converterYUR = None
        

    def getSourceIndex(self):
        """ Returns the assigned source index. The source index is the index
        of the ShadowSource in the ShadowSources array of the assigned
        Light. """
        return self.sourceIndex

    def getUid(self):
        """ Returns the uid of the light """
        return self.index

    def setSourceIndex(self, index):
        """ Sets the source index of this source. This is called by the light,
        as only the light knows at which position this source is in the
        Sources array. """
        self.sourceIndex = index

    def computeMVP(self):
        """ Computes the modelViewProjection matrix for the lens. Actually,
        this is the worldViewProjection matrix, but for convenience it is
        called mvp. """
        projMat = self.converterYUR
        transformMat = TransformState.makeMat(
            Mat4.convertMat(Globals.base.win.getGsg().getInternalCoordinateSystem(),
                            CSZupRight))
        modelViewMat = transformMat.invertCompose(
            Globals.render.getTransform(self.cameraNode)).getMat()
        self.mvp = UnalignedLMatrix4f(modelViewMat * projMat)

    def assignAtlasPos(self, x, y):
        """ Assigns this source a position in the shadow atlas. This is called
        by the shadow atlas. Coordinates are float from 0 .. 1 """
        self.atlasPos = Vec2(x, y)
        self.doesHaveAtlasPos = True

    def update(self):
        """ Updates the shadow source. Currently only recomputes the mvp. """
        self.computeMVP()

    def getAtlasPos(self):
        """ Returns the assigned atlas pos, if present. Coordinates are float
        from 0 .. 1 """
        return self.atlasPos

    def hasAtlasPos(self):
        """ Returns wheter this ShadowSource has already a position in the
        shadow atlas """
        return self.doesHaveAtlasPos

    def removeFromAtlas(self):
        """ Deletes the atlas coordinates, called by the atlas after the
        Source got removed from the atlas """
        self.doesHaveAtlasPos = False
        self.atlasPos = Vec2(0)

    def setResolution(self, resolution):
        """ Sets the resolution in pixels of this shadow source. Has to be
        a multiple of the tileSize specified in LightManager """
        assert(resolution > 1 and resolution <= 8192)
        self.resolution = resolution

    def getResolution(self):
        """ Returns the resolution of the shadow source in pixels """
        return self.resolution

    def setupPerspectiveLens(self, near=0.1, far=100.0, fov=(90, 90)):
        """ Setups a PerspectiveLens with a given nearPlane, farPlane
        and FoV. The FoV is a tuple in the format
        (Horizontal FoV, Vertical FoV) """
        # self.debug("setupPerspectiveLens(",near,",",far,",",fov,")")
        self.lens = PerspectiveLens()
        self.lens.setNearFar(near, far)
        self.lens.setFov(fov[0], fov[1])
        self.camera.setLens(self.lens)
        self.nearPlane = near
        self.farPlane = far
        self.rebuildMatrixCache()

    def setupOrtographicLens(self, near=0.1, far=100.0, filmSize=(512, 512)):
        """ Setups a OrtographicLens with a given nearPlane, farPlane
        and filmSize. The filmSize is a tuple in the format
        (filmWidth, filmHeight) in world space. """
        # self.debug("setupOrtographicLens(",near,",",far,",",filmSize,")")
        self.lens = OrtographicLens()
        self.lens.setNearFar(near, far)
        self.lens.setFilmSize(*filmSize)
        self.camera.setLens(self.lens)
        self.nearPlane = near
        self.farPlane = far
        self.rebuildMatrixCache()

    def rebuildMatrixCache(self):
        """ Computes values frequently used to compute the mvp """
        self.converterYUR = Mat4.convertMat(CSYupRight, self.lens.getCoordinateSystem()) * self.lens.getProjectionMat()

    def setPos(self, pos):
        """ Sets the position in world space """
        self.cameraNode.setPos(pos)

    def setHpr(self, hpr):
        """ Sets the rotation in world space """
        self.cameraNode.setHpr(hpr)

    def lookAt(self, pos):
        """ Looks at a point (in world space) """
        self.cameraNode.lookAt(pos.x, pos.y, pos.z)

    def invalidate(self):
        """ Invalidates this shadow source, means telling the LightManager
        that the shadow map for this light should be rebuilt. Otherwise it
        won't get refreshed """
        self.valid = False

    def setValid(self):
        """ The LightManager calls this after the shadow map got updated
        successfully """
        self.valid = True

    def isValid(self):
        """ Returns wether the shadow map is still valid or should
        be refreshed """
        return self.valid

    def __repr__(self):
        """ Returns a representative string of this instance """
        return "ShadowSource[id=" + str(self.index) + "]"
コード例 #57
0
    def create(self):
        # Create the voxel grid used to generate the voxels
        self.voxel_temp_grid = Image.create_3d(
            "VoxelsTemp", self.voxel_resolution, self.voxel_resolution,
            self.voxel_resolution, "RGBA8")
        self.voxel_temp_grid.set_clear_color(Vec4(0))
        self.voxel_temp_nrm_grid = Image.create_3d(
            "VoxelsTemp", self.voxel_resolution, self.voxel_resolution,
            self.voxel_resolution, "R11G11B10")
        self.voxel_temp_nrm_grid.set_clear_color(Vec4(0))

        # Create the voxel grid which is a copy of the temporary grid, but stable
        self.voxel_grid = Image.create_3d(
            "Voxels", self.voxel_resolution, self.voxel_resolution, self.voxel_resolution, "RGBA8")
        self.voxel_grid.set_clear_color(Vec4(0))
        self.voxel_grid.set_minfilter(SamplerState.FT_linear_mipmap_linear)

        # Create the camera for voxelization
        self.voxel_cam = Camera("VoxelizeCam")
        self.voxel_cam.set_camera_mask(self._pipeline.tag_mgr.get_voxelize_mask())
        self.voxel_cam_lens = OrthographicLens()
        self.voxel_cam_lens.set_film_size(
            -2.0 * self.voxel_world_size, 2.0 * self.voxel_world_size)
        self.voxel_cam_lens.set_near_far(0.0, 2.0 * self.voxel_world_size)
        self.voxel_cam.set_lens(self.voxel_cam_lens)
        self.voxel_cam_np = Globals.base.render.attach_new_node(self.voxel_cam)
        self._pipeline.tag_mgr.register_camera("voxelize", self.voxel_cam)

        # Create the voxelization target
        self.voxel_target = self.create_target("VoxelizeScene")
        self.voxel_target.size = self.voxel_resolution
        self.voxel_target.prepare_render(self.voxel_cam_np)

        # Create the target which copies the voxel grid
        self.copy_target = self.create_target("CopyVoxels")
        self.copy_target.size = self.voxel_resolution
        self.copy_target.prepare_buffer()

        # TODO! Does not work with the new render target yet - maybe add option
        # to post process region for instances?
        self.copy_target.instance_count = self.voxel_resolution
        self.copy_target.set_shader_input("SourceTex", self.voxel_temp_grid)
        self.copy_target.set_shader_input("DestTex", self.voxel_grid)

        # Create the target which generates the mipmaps
        self.mip_targets = []
        mip_size, mip = self.voxel_resolution, 0
        while mip_size > 1:
            mip_size, mip = mip_size // 2, mip + 1
            mip_target = self.create_target("GenMipmaps:" + str(mip))
            mip_target.size = mip_size
            mip_target.prepare_buffer()
            mip_target.instance_count = mip_size
            mip_target.set_shader_input("SourceTex", self.voxel_grid)
            mip_target.set_shader_input("sourceMip", mip - 1)
            mip_target.set_shader_input("DestTex", self.voxel_grid, False, True, -1, mip, 0)
            self.mip_targets.append(mip_target)

        # Create the initial state used for rendering voxels
        initial_state = NodePath("VXGIInitialState")
        initial_state.set_attrib(CullFaceAttrib.make(CullFaceAttrib.M_cull_none), 100000)
        initial_state.set_attrib(DepthTestAttrib.make(DepthTestAttrib.M_none), 100000)
        initial_state.set_attrib(ColorWriteAttrib.make(ColorWriteAttrib.C_off), 100000)
        self.voxel_cam.set_initial_state(initial_state.get_state())

        Globals.base.render.set_shader_input("voxelGridPosition", self.pta_next_grid_pos)
        Globals.base.render.set_shader_input("VoxelGridDest", self.voxel_temp_grid)
コード例 #58
0
class PSSMSceneShadowStage(RenderStage):

    """ This stage creates the shadow map which covers the whole important part
    of the scene. This is required because the shadow cascades only cover the
    view frustum, but many plugins (VXGI, EnvMaps) require a shadow map. """

    required_inputs = []
    required_pipes = []

    def __init__(self, pipeline):
        RenderStage.__init__(self, pipeline)
        self.resolution = 2048
        self.sun_vector = Vec3(0, 0, 1)
        self.sun_distance = 10.0
        self.pta_mvp = PTAMat4.empty_array(1)
        self.focus = None

        # Store last focus entirely for the purpose of being able to see
        # it in the debugger
        self.last_focus = None

    @property
    def produced_inputs(self):
        return {"PSSMSceneSunShadowMVP": self.pta_mvp}

    @property
    def produced_pipes(self):
        return {"PSSMSceneSunShadowMapPCF": (self.target.depth_tex, self.make_pcf_state())}

    def make_pcf_state(self):
        state = SamplerState()
        state.set_minfilter(SamplerState.FT_shadow)
        state.set_magfilter(SamplerState.FT_shadow)
        return state

    def request_focus(self, focus_point, focus_size):
        self.focus = (focus_point, focus_size)
        self.last_focus = self.focus

    @property
    def mvp(self):
        return Globals.base.render.get_transform(self.cam_node).get_mat() * \
            self.cam_lens.get_projection_mat()

    def update(self):
        if self._pipeline.task_scheduler.is_scheduled("pssm_scene_shadows"):
            if self.focus is None:
                # When no focus is set, there is no point in rendering the shadow map
                self.target.active = False
            else:
                focus_point, focus_size = self.focus

                self.cam_lens.set_near_far(0.0, 2 * (focus_size + self.sun_distance))
                self.cam_lens.set_film_size(2 * focus_size, 2 * focus_size)
                self.cam_node.set_pos(
                    focus_point + self.sun_vector * (self.sun_distance + focus_size))
                self.cam_node.look_at(focus_point)

                snap_shadow_map(self.mvp, self.cam_node, self.resolution)
                self.target.active = True
                self.pta_mvp[0] = self.mvp

                self.focus = None
        else:
            self.target.active = False

    def create(self):
        self.camera = Camera("PSSMSceneSunShadowCam")
        self.cam_lens = OrthographicLens()
        self.cam_lens.set_film_size(400, 400)
        self.cam_lens.set_near_far(100.0, 1800.0)
        self.camera.set_lens(self.cam_lens)
        self.cam_node = Globals.base.render.attach_new_node(self.camera)

        self.target = self.create_target("ShadowMap")
        self.target.size = self.resolution
        self.target.add_depth_attachment(bits=32)
        self.target.prepare_render(self.cam_node)

        # Register shadow camera
        self._pipeline.tag_mgr.register_camera("shadow", self.camera)

    def set_shader_input(self, *args):
        Globals.render.set_shader_input(*args)

    def set_shader_inputs(self, **kwargs):
        Globals.render.set_shader_inputs(**kwargs)
コード例 #59
0
class VoxelizationStage(RenderStage):

    """ This stage voxelizes the whole scene """

    required_inputs = ["DefaultEnvmap", "AllLightsData", "maxLightIndex"]
    required_pipes = []

    # The different states of voxelization
    S_disabled = 0
    S_voxelize_x = 1
    S_voxelize_y = 2
    S_voxelize_z = 3
    S_gen_mipmaps = 4

    def __init__(self, pipeline):
        RenderStage.__init__(self, pipeline)
        self.voxel_resolution = 256
        self.voxel_world_size = -1
        self.state = self.S_disabled
        self.create_ptas()

    def set_grid_position(self, pos):
        self.pta_next_grid_pos[0] = pos

    def create_ptas(self):
        self.pta_next_grid_pos = PTALVecBase3.empty_array(1)
        self.pta_grid_pos = PTALVecBase3.empty_array(1)

    @property
    def produced_inputs(self):
        return {"voxelGridPosition": self.pta_grid_pos}

    @property
    def produced_pipes(self):
        return {"SceneVoxels": self.voxel_grid}

    def create(self):
        # Create the voxel grid used to generate the voxels
        self.voxel_temp_grid = Image.create_3d(
            "VoxelsTemp", self.voxel_resolution, self.voxel_resolution,
            self.voxel_resolution, "RGBA8")
        self.voxel_temp_grid.set_clear_color(Vec4(0))
        self.voxel_temp_nrm_grid = Image.create_3d(
            "VoxelsTemp", self.voxel_resolution, self.voxel_resolution,
            self.voxel_resolution, "R11G11B10")
        self.voxel_temp_nrm_grid.set_clear_color(Vec4(0))

        # Create the voxel grid which is a copy of the temporary grid, but stable
        self.voxel_grid = Image.create_3d(
            "Voxels", self.voxel_resolution, self.voxel_resolution, self.voxel_resolution, "RGBA8")
        self.voxel_grid.set_clear_color(Vec4(0))
        self.voxel_grid.set_minfilter(SamplerState.FT_linear_mipmap_linear)

        # Create the camera for voxelization
        self.voxel_cam = Camera("VoxelizeCam")
        self.voxel_cam.set_camera_mask(self._pipeline.tag_mgr.get_voxelize_mask())
        self.voxel_cam_lens = OrthographicLens()
        self.voxel_cam_lens.set_film_size(
            -2.0 * self.voxel_world_size, 2.0 * self.voxel_world_size)
        self.voxel_cam_lens.set_near_far(0.0, 2.0 * self.voxel_world_size)
        self.voxel_cam.set_lens(self.voxel_cam_lens)
        self.voxel_cam_np = Globals.base.render.attach_new_node(self.voxel_cam)
        self._pipeline.tag_mgr.register_camera("voxelize", self.voxel_cam)

        # Create the voxelization target
        self.voxel_target = self.create_target("VoxelizeScene")
        self.voxel_target.size = self.voxel_resolution
        self.voxel_target.prepare_render(self.voxel_cam_np)

        # Create the target which copies the voxel grid
        self.copy_target = self.create_target("CopyVoxels")
        self.copy_target.size = self.voxel_resolution
        self.copy_target.prepare_buffer()

        # TODO! Does not work with the new render target yet - maybe add option
        # to post process region for instances?
        self.copy_target.instance_count = self.voxel_resolution
        self.copy_target.set_shader_input("SourceTex", self.voxel_temp_grid)
        self.copy_target.set_shader_input("DestTex", self.voxel_grid)

        # Create the target which generates the mipmaps
        self.mip_targets = []
        mip_size, mip = self.voxel_resolution, 0
        while mip_size > 1:
            mip_size, mip = mip_size // 2, mip + 1
            mip_target = self.create_target("GenMipmaps:" + str(mip))
            mip_target.size = mip_size
            mip_target.prepare_buffer()
            mip_target.instance_count = mip_size
            mip_target.set_shader_input("SourceTex", self.voxel_grid)
            mip_target.set_shader_input("sourceMip", mip - 1)
            mip_target.set_shader_input("DestTex", self.voxel_grid, False, True, -1, mip, 0)
            self.mip_targets.append(mip_target)

        # Create the initial state used for rendering voxels
        initial_state = NodePath("VXGIInitialState")
        initial_state.set_attrib(CullFaceAttrib.make(CullFaceAttrib.M_cull_none), 100000)
        initial_state.set_attrib(DepthTestAttrib.make(DepthTestAttrib.M_none), 100000)
        initial_state.set_attrib(ColorWriteAttrib.make(ColorWriteAttrib.C_off), 100000)
        self.voxel_cam.set_initial_state(initial_state.get_state())

        Globals.base.render.set_shader_input("voxelGridPosition", self.pta_next_grid_pos)
        Globals.base.render.set_shader_input("VoxelGridDest", self.voxel_temp_grid)

    def update(self):
        self.voxel_cam_np.show()
        self.voxel_target.active = True
        self.copy_target.active = False

        for target in self.mip_targets:
            target.active = False

        # Voxelization disable
        if self.state == self.S_disabled:
            self.voxel_cam_np.hide()
            self.voxel_target.active = False

        # Voxelization from X-Axis
        elif self.state == self.S_voxelize_x:
            # Clear voxel grid
            self.voxel_temp_grid.clear_image()
            self.voxel_cam_np.set_pos(
                self.pta_next_grid_pos[0] + Vec3(self.voxel_world_size, 0, 0))
            self.voxel_cam_np.look_at(self.pta_next_grid_pos[0])

        # Voxelization from Y-Axis
        elif self.state == self.S_voxelize_y:
            self.voxel_cam_np.set_pos(
                self.pta_next_grid_pos[0] + Vec3(0, self.voxel_world_size, 0))
            self.voxel_cam_np.look_at(self.pta_next_grid_pos[0])

        # Voxelization from Z-Axis
        elif self.state == self.S_voxelize_z:
            self.voxel_cam_np.set_pos(
                self.pta_next_grid_pos[0] + Vec3(0, 0, self.voxel_world_size))
            self.voxel_cam_np.look_at(self.pta_next_grid_pos[0])

        # Generate mipmaps
        elif self.state == self.S_gen_mipmaps:
            self.voxel_target.active = False
            self.copy_target.active = True
            self.voxel_cam_np.hide()

            for target in self.mip_targets:
                target.active = True

            # As soon as we generate the mipmaps, we need to update the grid position
            # as well
            self.pta_grid_pos[0] = self.pta_next_grid_pos[0]

    def reload_shaders(self):
        self.copy_target.shader = self.load_plugin_shader(
            "/$$rp/shader/default_post_process_instanced.vert.glsl", "copy_voxels.frag.glsl")
        mip_shader = self.load_plugin_shader(
            "/$$rp/shader/default_post_process_instanced.vert.glsl", "generate_mipmaps.frag.glsl")
        for target in self.mip_targets:
            target.shader = mip_shader

    def set_shader_input(self, *args):
        Globals.render.set_shader_input(*args)