def setShaders(self): shaderCoC = Shader.load(Shader.SLGLSL, "Shader/DefaultPostProcess.vertex", "Shader/DoF/DoFCoC.fragment") self.targetCoC.setShader(shaderCoC) # shaderSprites = Shader.load(Shader.SLGLSL, # "Shader/DoF/DoFSprite.vertex", # "Shader/DoF/DoFSprite.fragment") # self.targetSpawnSprites.setShader(shaderSprites) shaderBlurV = Shader.load(Shader.SLGLSL, "Shader/DefaultPostProcess.vertex", "Shader/DoF/DoFBlurV.fragment") self.targetBlurV.setShader(shaderBlurV) shaderBlurH = Shader.load(Shader.SLGLSL, "Shader/DefaultPostProcess.vertex", "Shader/DoF/DoFBlurH.fragment") self.targetBlurH.setShader(shaderBlurH) shaderCombine = Shader.load(Shader.SLGLSL, "Shader/DefaultPostProcess.vertex", "Shader/DoF/DoFCombine.fragment") self.targetCombine.setShader(shaderCombine) return [shaderCoC, shaderBlurV, shaderBlurH, shaderCombine]
def test_shader_load_compute(vfs, ramdir): # Try non-existent first. shad0 = Shader.load_compute(Shader.SL_GLSL, "/nonexistent.glsl") assert shad0 is None comp_file = Filename(ramdir, "shader.glsl") # Now write some actual content to the shader file. vfs.write_file(comp_file, b"#version 100\nvoid main() {}\n", False) shad1 = Shader.load_compute(Shader.SL_GLSL, comp_file) assert shad1 is not None assert shad1.this # Load the same shader, it should return the cached result. shad2 = Shader.load_compute(Shader.SL_GLSL, comp_file) assert shad2 is not None assert shad1.this == shad2.this # After waiting a second to make the timestamp different, modify the # shader and load again, it should result in a different object now time.sleep(1.0) vfs.write_file(comp_file, b"#version 110\nvoid main() {}\n", False) shad2 = Shader.load_compute(Shader.SL_GLSL, comp_file) assert shad2.this != shad1.this
def __init__(self, N, sourceTex, normalizationFactor): """ Creates a new fft instance. The source texture has to specified from the begining, as the shaderAttributes are pregenerated for performance reasons """ DebugObject.__init__(self, "GPU-FFT") self.size = N self.log2Size = int(math.log(N, 2)) self.normalizationFactor = normalizationFactor # Create a ping and a pong texture, because we can't write to the # same texture while reading to it (that would lead to unexpected # behaviour, we could solve that by using an appropriate thread size, # but it works fine so far) self.pingTexture = Texture("FFTPing") self.pingTexture.setup2dTexture(self.size, self.size, Texture.TFloat, Texture.FRgba32) self.pongTexture = Texture("FFTPong") self.pongTexture.setup2dTexture(self.size, self.size, Texture.TFloat, Texture.FRgba32) self.sourceTex = sourceTex for tex in [self.pingTexture, self.pongTexture, sourceTex]: tex.setMinfilter(Texture.FTNearest) tex.setMagfilter(Texture.FTNearest) tex.setWrapU(Texture.WMClamp) tex.setWrapV(Texture.WMClamp) # Pregenerate weights & indices for the shaders self._computeWeighting() # Pre generate the shaders, we have 2 passes: Horizontal and Vertical # which both execute log2(N) times with varying radii self.horizontalFFTShader = Shader.loadCompute( Shader.SLGLSL, "Shader/WaterFFT/HorizontalFFT.compute") self.horizontalFFT = NodePath("HorizontalFFT") self.horizontalFFT.setShader(self.horizontalFFTShader) self.horizontalFFT.setShaderInput("precomputedWeights", self.weightsLookupTex) self.horizontalFFT.setShaderInput("N", LVecBase2i(self.size)) self.verticalFFTShader = Shader.loadCompute( Shader.SLGLSL, "Shader/WaterFFT/VerticalFFT.compute") self.verticalFFT = NodePath("VerticalFFT") self.verticalFFT.setShader(self.verticalFFTShader) self.verticalFFT.setShaderInput("precomputedWeights", self.weightsLookupTex) self.verticalFFT.setShaderInput("N", LVecBase2i(self.size)) # Create a texture where the result is stored self.resultTexture = Texture("Result") self.resultTexture.setup2dTexture(self.size, self.size, Texture.TFloat, Texture.FRgba16) self.resultTexture.setMinfilter(Texture.FTLinear) self.resultTexture.setMagfilter(Texture.FTLinear) # Prepare the shader attributes, so we don't have to regenerate them # every frame -> That is VERY slow (3ms per fft instance) self._prepareAttributes()
def __init__(self, N, sourceTex, normalizationFactor): """ Creates a new fft instance. The source texture has to specified from the begining, as the shaderAttributes are pregenerated for performance reasons """ DebugObject.__init__(self, "GPU-FFT") self.size = N self.log2Size = int(math.log(N, 2)) self.normalizationFactor = normalizationFactor # Create a ping and a pong texture, because we can't write to the # same texture while reading to it (that would lead to unexpected # behaviour, we could solve that by using an appropriate thread size, # but it works fine so far) self.pingTexture = Texture("FFTPing") self.pingTexture.setup2dTexture( self.size, self.size, Texture.TFloat, Texture.FRgba32) self.pongTexture = Texture("FFTPong") self.pongTexture.setup2dTexture( self.size, self.size, Texture.TFloat, Texture.FRgba32) self.sourceTex = sourceTex for tex in [self.pingTexture, self.pongTexture, sourceTex]: tex.setMinfilter(Texture.FTNearest) tex.setMagfilter(Texture.FTNearest) tex.setWrapU(Texture.WMClamp) tex.setWrapV(Texture.WMClamp) # Pregenerate weights & indices for the shaders self._computeWeighting() # Pre generate the shaders, we have 2 passes: Horizontal and Vertical # which both execute log2(N) times with varying radii self.horizontalFFTShader = Shader.loadCompute(Shader.SLGLSL, "Shader/Water/HorizontalFFT.compute") self.horizontalFFT = NodePath("HorizontalFFT") self.horizontalFFT.setShader(self.horizontalFFTShader) self.horizontalFFT.setShaderInput( "precomputedWeights", self.weightsLookupTex) self.horizontalFFT.setShaderInput("N", LVecBase2i(self.size)) self.verticalFFTShader = Shader.loadCompute(Shader.SLGLSL, "Shader/Water/VerticalFFT.compute") self.verticalFFT = NodePath("VerticalFFT") self.verticalFFT.setShader(self.verticalFFTShader) self.verticalFFT.setShaderInput( "precomputedWeights", self.weightsLookupTex) self.verticalFFT.setShaderInput("N", LVecBase2i(self.size)) # Create a texture where the result is stored self.resultTexture = Texture("Result") self.resultTexture.setup2dTexture( self.size, self.size, Texture.TFloat, Texture.FRgba16) self.resultTexture.setMinfilter(Texture.FTLinear) self.resultTexture.setMagfilter(Texture.FTLinear) # Prepare the shader attributes, so we don't have to regenerate them # every frame -> That is VERY slow (3ms per fft instance) self._prepareAttributes()
def shader(self, value): try: self.setShader(Shader.load(f'{value}.sha', Shader.SL_Cg)) except: self.setShader( Shader.load(Shader.SL_GLSL, vertex=f'{value}.vert', fragment=f'{value}.frag'))
def __init__(self, size, source_tex, normalization_factor): """ Creates a new fft instance. The source texture has to specified from the begining, as the shaderAttributes are pregenerated for performance reasons """ self.size = size self.log2_size = int(math.log(size, 2)) self.normalization_factor = normalization_factor # Create a ping and a pong texture, because we can't write to the # same texture while reading to it (that would lead to unexpected # behaviour, we could solve that by using an appropriate thread size, # but it works fine so far) self.ping_texture = Texture("FFTPing") self.ping_texture.setup_2d_texture(self.size, self.size, Texture.TFloat, Texture.FRgba32) self.pong_texture = Texture("FFTPong") self.pong_texture.setup_2d_texture(self.size, self.size, Texture.TFloat, Texture.FRgba32) self.source_tex = source_tex for tex in [self.ping_texture, self.pong_texture, source_tex]: tex.set_minfilter(Texture.FTNearest) tex.set_magfilter(Texture.FTNearest) tex.set_wrap_u(Texture.WMClamp) tex.set_wrap_v(Texture.WMClamp) # Pregenerate weights & indices for the shaders self._compute_weighting() # Pre generate the shaders, we have 2 passes: Horizontal and Vertical # which both execute log2(N) times with varying radii self.horizontal_fft_shader = Shader.load_compute( Shader.SLGLSL, "/$$rp/rpcore/water/shader/horizontal_fft.compute") self.horizontal_fft = NodePath("HorizontalFFT") self.horizontal_fft.set_shader(self.horizontal_fft_shader) self.horizontal_fft.set_shader_input("precomputedWeights", self.weights_lookup_tex) self.horizontal_fft.set_shader_input("N", LVecBase2i(self.size)) self.vertical_fft_shader = Shader.load_compute( Shader.SLGLSL, "/$$rp/rpcore/water/shader/vertical_fft.compute") self.vertical_fft = NodePath("VerticalFFT") self.vertical_fft.set_shader(self.vertical_fft_shader) self.vertical_fft.set_shader_input("precomputedWeights", self.weights_lookup_tex) self.vertical_fft.set_shader_input("N", LVecBase2i(self.size)) # Create a texture where the result is stored self.result_texture = Texture("Result") self.result_texture.setup2dTexture(self.size, self.size, Texture.TFloat, Texture.FRgba16) self.result_texture.set_minfilter(Texture.FTLinear) self.result_texture.set_magfilter(Texture.FTLinear) # Prepare the shader attributes, so we don't have to regenerate them # every frame -> That is VERY slow (3ms per fft instance) self._prepare_attributes()
def __init__(self): ShowBase.__init__(self) self.disableMouse() self.scene = self.loader.loadModel('models/environment') self.scene.reparentTo(self.render) self.scene.setScale(0.25, 0.25, 0.25) self.scene.setPos(-8, 42, 0) self.taskMgr.add(self.spin_camera_task, 'SpinCameraTask') self.taskMgr.add(self.update_shader_inputs_task, 'UpdateShaderInputsTask') self.pandaActor = Actor('models/panda-model', {'walk': 'models/panda-walk4'}) self.pandaActor.setScale(0.005, 0.005, 0.005) self.pandaActor.reparentTo(self.render) self.pandaActor.loop('walk') pos_interval1 = self.pandaActor.posInterval(13, Point3(0, -10, 0), startPos=Point3(0, 10, 0)) pos_interval2 = self.pandaActor.posInterval(13, Point3(0, 10, 0), startPos=Point3(0, -10, 0)) hpr_interval1 = self.pandaActor.hprInterval(3, Point3(180, 0, 0), startHpr=Point3(0, 0, 0)) hpr_interval2 = self.pandaActor.hprInterval(3, Point3(0, 0, 0), startHpr=Point3(180, 0, 0)) self.pandaPace = Sequence(pos_interval1, hpr_interval1, pos_interval2, hpr_interval2, name="pandaPace") self.pandaPace.loop() my_vertex_shader_path = os.path.join(SHADERS_DIR, 'my_shader.vert') my_fragment_shader_path = os.path.join(SHADERS_DIR, 'my_shader.frag') my_shader = Shader.load(Shader.SL_GLSL, vertex=my_vertex_shader_path, fragment=my_fragment_shader_path) tutorial_vertex_shader_path = os.path.join(SHADERS_DIR, 'tutorial_shader.vert') tutorial_fragment_shader_path = os.path.join(SHADERS_DIR, 'tutorial_shader.frag') tutorial_shader = Shader.load(Shader.SL_GLSL, vertex=tutorial_vertex_shader_path, fragment=tutorial_fragment_shader_path) self.pandaActor.setShaderInputs( **{ 'u_resolution': Vec2(self.win.getXSize(), self.win.getYSize()), }) self.pandaActor.set_shader(tutorial_shader)
def __init__(self, base, render, cam_node): # State vars self.scroll_down = False self.shift_down = False self.cam_node = cam_node self.base = base self.render = render self.cam_active = True self.delta_mouse = (0, 0) self.last_mouse = (0, 0) self.start_mouse = (0, 0) self.orbit_center = LVector3f(0, 0, 0) self.start_orbit = self.orbit_center self.plane_normal = np.array([0, 0, 0]) # Load skinned shader self.base.cam.node().setTagStateKey("shader type") shader_folder_path = Path( path.realpath(__file__)).parent.parent.parent / "res/shaders" self.skinned_shader = Shader.load( Shader.SL_GLSL, vertex=Filename(shader_folder_path / "skinned.vert").cStr(), fragment=Filename(shader_folder_path / "skinned.frag").cStr()) skinned_render_state = NodePath("") skinned_render_state.set_shader(self.skinned_shader) self.base.cam.node().setTagState("skinned", skinned_render_state.get_state()) # Load gizmo shader self.gizmo_shader = Shader.load( Shader.SL_GLSL, vertex=Filename(shader_folder_path / "gizmo.vert").cStr(), fragment=Filename(shader_folder_path / "gizmo.frag").cStr()) gizmo_render_state = NodePath("") gizmo_render_state.set_shader(self.gizmo_shader) self.base.render.set_shader_input("cam_pos", self.cam_node.getPos()) self.base.cam.node().setTagState("gizmo", gizmo_render_state.get_state()) # Register events self.accept("mouse2", self.handle_scroll_pressed) self.accept("mouse2-up", self.handle_scroll_released) self.accept("shift-mouse2", self.handle_shift_scroll_pressed) self.accept("shift-mouse2-up", self.handle_shift_scroll_released) self.accept("wheel_up", self.handle_scroll_up) self.accept("wheel_down", self.handle_scroll_down) # Set up camera self.cam_node.setPos(0, -1, 0) self.forward = (-self.cam_node.getPos()).normalized() self.up_angle = 0 self.left_angle = 0 self.addTask(self.cam_ctrl_task)
def apply(self): winprops = WindowProperties.size(2048, 2048) props = FrameBufferProperties() props.setRgbColor(1) props.setAlphaBits(1) props.setDepthBits(1) lbuffer = base.graphicsEngine.makeOutput(base.pipe, 'offscreen buffer', -2, props, winprops, GraphicsPipe.BFRefuseWindow, base.win.getGsg(), base.win) self.buffer = lbuffer ldepthmap = Texture() lbuffer.addRenderTexture(ldepthmap, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPDepthStencil) ldepthmap.setMinfilter(Texture.FTShadow) ldepthmap.setMagfilter(Texture.FTShadow) base.camLens.setNearFar(1.0, 10000) base.camLens.setFov(75) self.lcam = base.makeCamera(lbuffer) self.lcam.node().setScene(render) self.lcam.node().getLens().setFov(45) self.lcam.node().getLens().setNearFar(1, 100) render.setShaderInput('light', self.lcam) render.setShaderInput('depthmap', ldepthmap) render.setShaderInput('ambient', .15, .15, .15, 1.0) lci = NodePath(PandaNode('light camera initializer')) with open('yyagl/assets/shaders/caster.vert') as f: vert = f.read() with open('yyagl/assets/shaders/caster.frag') as f: frag = f.read() lci.setShader(Shader.make(Shader.SLGLSL, vert, frag)) self.lcam.node().setInitialState(lci.getState()) mci = NodePath(PandaNode('main camera initializer')) with open('yyagl/assets/shaders/main.vert') as f: vert = f.read() with open('yyagl/assets/shaders/main.frag') as f: frag = f.read() frag = frag.replace('<LIGHTS>', str(len(self.lights))) # use PTALVecBaseX instead # setShaderInput('vec3argname', PTALVecBase3(((0, 0, 0), (1, 1, 1)))) render.setShader(Shader.make(Shader.SLGLSL, vert, frag)) render.setShaderInput('num_lights', len(self.lights)) map(lambda lgt: self.set_lgt_args(*lgt), enumerate(self.lights)) mci.setShader(Shader.make(Shader.SLGLSL, vert, frag)) base.cam.node().setInitialState(mci.getState()) self.lcam.setPos(15, 30, 45) self.lcam.lookAt(0, 15, 0) self.lcam.node().getLens().setNearFar(1, 100)
def setShaders(self): shader = Shader.load(Shader.SLGLSL, "Shader/DefaultPostProcess.vertex", "Shader/MotionBlur.fragment") self.target.setShader(shader) shaderDilate = Shader.load(Shader.SLGLSL, "Shader/DefaultPostProcess.vertex", "Shader/MotionBlurDilate.fragment") self.targetDilate0.setShader(shaderDilate) self.targetDilate1.setShader(shaderDilate) return [shader, shaderDilate]
def setShaders(self): shaderV = Shader.load(Shader.SLGLSL, "Shader/DefaultPostProcess.vertex", "Shader/OcclusionBlurV.fragment") self.targetV.setShader(shaderV) shaderH = Shader.load(Shader.SLGLSL, "Shader/DefaultPostProcess.vertex", "Shader/OcclusionBlurH.fragment") self.targetH.setShader(shaderH) return [shaderV, shaderH]
def load_shaders(self): shaders = Shader.load(Shader.SL_GLSL, 'gas_giant_vertex.glsl', 'gas_giant_fragment.glsl', '', "Shader/DefaultShaders/Opaque/tesscontrol.glsl", "Shader/DefaultShaders/Opaque/tesseval.glsl") shaders = Shader.load(Shader.SL_GLSL, 'gas_giant_vertex.glsl', 'gas_giant_fragment.glsl') #convertToPatches(self.node_path) self.node_path.set_shader(shaders, 51)
def shader(self, value): if isinstance(value, Shader): self.setShader(value) return if value is None: self.setShaderAuto() return try: self.setShader(Shader.load(f'{value}.sha', Shader.SL_Cg)) except: self.setShader(Shader.load(Shader.SL_GLSL, vertex=f'{value}.vert', fragment=f'{value}.frag'))
def setShaders(self): shader = Shader.load(Shader.SLGLSL, "Shader/DefaultPostProcess.vertex", "Shader/BloomExtract.fragment") self.target.setShader(shader) shaderV = Shader.load(Shader.SLGLSL, "Shader/DefaultPostProcess.vertex", "Shader/BloomBlurV.fragment") self.targetV.setShader(shaderV) shaderH = Shader.load(Shader.SLGLSL, "Shader/DefaultPostProcess.vertex", "Shader/BloomBlurH.fragment") self.targetH.setShader(shaderH) shaderMerge = Shader.load(Shader.SLGLSL, "Shader/DefaultPostProcess.vertex", "Shader/BloomMerge.fragment") self.targetMerge.setShader(shaderMerge) return [shader, shaderV, shaderH]
def enable_fxaa(self): tex1 = Texture() quad1 = self._manager.renderQuadInto(colortex=tex1) tex2 = Texture() self._quads.append(quad1) quad1.setShader(Shader.load("assets/shaders/post/fxaa.sha")) quad1.setShaderInput("color", tex1) quad1.setShaderInput("active", 1) quad2 = self._manager.renderSceneInto(colortex=tex2) self._quads.append(quad2) quad2.setShader(Shader.load("assets/shaders/post/color.sha")) quad2.setShaderInput("tex", tex2)
def setShaders(self): shader = Shader.load(Shader.SLGLSL, "Shader/DefaultPostProcess.vertex", "Shader/SkyboxMask.fragment") self.target.setShader(shader) return [shader]
def setShaders(self): shader = Shader.load(Shader.SLGLSL, "Shader/DefaultPostProcess.vertex", "Shader/TransparencyPass.fragment") self.target.setShader(shader) return [shader]
def create_instance(self): self.create_buffer() # Water surface maker = CardMaker('water') maker.setFrame(self.x1, self.x2, self.y1, self.y2) self.waterNP = self.parent.instance.attachNewNode(maker.generate()) self.waterNP.hide(BaseObject.AllCamerasMask) self.waterNP.show(BaseObject.DefaultCameraMask) self.waterNP.setHpr(0, -90, 0) self.waterNP.setPos(0, 0, self.z) self.waterNP.setTransparency(TransparencyAttrib.MAlpha) vertex_shader = defaultDirContext.find_shader('water-vertex.glsl') fragment_shader = defaultDirContext.find_shader('water-fragment.glsl') self.waterNP.setShader( Shader.load( Shader.SL_GLSL, vertex=Filename.from_os_specific(vertex_shader).get_fullpath(), fragment=Filename.from_os_specific( fragment_shader).get_fullpath())) self.waterNP.setShaderInput('wateranim', Vec4(0.03, -0.015, self.scale, 0)) # vx, vy, scale, skip # offset, strength, refraction factor (0=perfect mirror, 1=total refraction), refractivity self.waterNP.setShaderInput('waterdistort', Vec4(0.4, 1.0, 0.25, 0.45)) self.waterNP.setShaderInput('time', 0) self.waterNP.setShaderInput('reflection_tex', self.texture) # distortion texture tex1 = loader.loadTexture('textures/water.png') self.waterNP.setShaderInput('distortion_tex', tex1)
def __init__(self): load_prc_file_data("", """ textures-power-2 none window-type offscreen win-size 100 100 gl-coordinate-system default notify-level-display error print-pipe-types #f """) ShowBase.__init__(self) dest_tex = Texture() dest_tex.setup_2d_texture(2048, 2048, Texture.T_unsigned_byte, Texture.F_rgba8) cshader = Shader.load_compute(Shader.SL_GLSL, "grain.compute.glsl") node = NodePath("") node.set_shader(cshader) node.set_shader_input("DestTex", dest_tex) attr = node.get_attrib(ShaderAttrib) self.graphicsEngine.dispatch_compute( (2048 // 16, 2048 // 16, 1), attr, self.win.get_gsg()) base.graphicsEngine.extract_texture_data(dest_tex, base.win.get_gsg()) # Convert to single channel img = PNMImage(2048, 2048, 1, 255) dest_tex.store(img) img.set_num_channels(1) tex = Texture() tex.load(img) tex.write("grain.txo.pz")
def load(self, *args): """ Loads a shader in the order: vertex, fragment, geometry, tesseval, tesscontrol """ newArgs = [] toHash = "" for arg in args: if len(arg) < 1: newArgs.append("") continue content = self._handleIncludes(arg) newArgs.append(content) toHash += content self._writeDebugShader("Shader-" + str(arg), content) self._clearIncludeStack() # Check if we already have the result cached hashed = hash(toHash) if hashed in self._ShaderCache: # Cache entry found return self._ShaderCache[hashed] shaderName = args[1].replace("Shader", "").split(".")[0].lstrip("/") result = Shader.make(Shader.SLGLSL, *newArgs) self._ShaderCache[hashed] = result return result
def compile(self): self._shader = Panda3dShader.make(self.language, self.vertex, self.fragment, self.geometry) self.compiled = True if not self in imported_shaders: imported_shaders.append(self)
def setShaders(self): shader = Shader.load(Shader.SLGLSL, "Shader/DefaultPostProcess.vertex", "Shader/Antialiasing/FXAA/FXAA3.fragment") self.target.setShader(shader) return [shader]
def __init__(self): # The basics ShowBase.__init__(self) base.disableMouse() base.setBackgroundColor(0.1, 0.1, 0.1) base.setFrameRateMeter(True) self.accept("escape", sys.exit) # Camera self.camera_orbit = base.render.attach_new_node("Camera orbit") self.camera_pitch = self.camera_orbit.attach_new_node("Camera pitch") base.camera.reparent_to(self.camera_pitch) base.camera.set_pos(0, -5, 0) # Camera control self.camera_movement = (0, 0) self.accept("arrow_up", self.change_camera_movement, [ 0, -1]) self.accept("arrow_up-up", self.change_camera_movement, [ 0, 1]) self.accept("arrow_down", self.change_camera_movement, [ 0, 1]) self.accept("arrow_down-up", self.change_camera_movement, [ 0, -1]) self.accept("arrow_left", self.change_camera_movement, [-1, 0]) self.accept("arrow_left-up", self.change_camera_movement, [ 1, 0]) self.accept("arrow_right", self.change_camera_movement, [ 1, 0]) self.accept("arrow_right-up", self.change_camera_movement, [-1, 0]) base.taskMgr.add(self.move_camera, "Move camera") # Object self.model = loader.loadModel("models/smiley") self.model.reparent_to(base.render) shader = Shader.make( Shader.SL_GLSL, vertex = vertex_shader, fragment = fragment_shader, ) self.model.set_shader(shader)
def setShaders(self): shader = Shader.load(Shader.SLGLSL, "Shader/DefaultPostProcess.vertex", "Shader/LightingPass.fragment") self.target.setShader(shader) return [shader]
def create_instance(self): self.create_buffer() # Water surface maker = CardMaker('water') maker.setFrame(self.x1, self.x2, self.y1, self.y2) self.waterNP = self.parent.instance.attachNewNode(maker.generate()) self.waterNP.setHpr(0, -90, 0) self.waterNP.setPos(0, 0, self.z) self.waterNP.setTransparency(TransparencyAttrib.MAlpha) self.waterNP.setShader(Shader.load(Shader.SL_GLSL, vertex=defaultDirContext.find_shader('water-vertex.glsl'), fragment=defaultDirContext.find_shader('water-fragment.glsl'))) self.waterNP.setShaderInput('wateranim', Vec4(0.03, -0.015, self.scale, 0)) # vx, vy, scale, skip # offset, strength, refraction factor (0=perfect mirror, 1=total refraction), refractivity self.waterNP.setShaderInput('waterdistort', Vec4(0.4, 4.0, 0.25, 0.45)) self.waterNP.setShaderInput('time', 0) # Reflection plane self.waterPlane = Plane(Vec3(0, 0, self.z + 1), Point3(0, 0, self.z)) planeNode = PlaneNode('waterPlane') planeNode.setPlane(self.waterPlane) # reflection texture, created in realtime by the 'water camera' tex0 = self.buffer.getTexture() tex0.setWrapU(Texture.WMClamp) tex0.setWrapV(Texture.WMClamp) ts0 = TextureStage('reflection') self.waterNP.setTexture(ts0, tex0) # distortion texture tex1 = loader.loadTexture('textures/water.png') ts1 = TextureStage('distortion') self.waterNP.setTexture(ts1, tex1) self.task = taskMgr.add(self.update, "waterTask")
def setShaders(self): shader = Shader.load(Shader.SLGLSL, "Shader/DefaultPostProcess.vertex", "Shader/PrecomputeLights.fragment") self.target.setShader(shader) return [shader]
def __init__(self): ShowBase.__init__(self) mesh = Mesh.create_plate(position=(0, 0), width=6, height=2, num_elements_width=6, num_elements_height=3) geom = mesh.get_render_mesh() node = GeomNode('g-node') node.addGeom(geom) node_path = self.render.attachNewNode(node) # noinspection PyArgumentList shader = Shader.load(lang=Shader.SL_GLSL, vertex="../shaders/grid_shader.vert", fragment="../shaders/grid_shader.frag") node_path.setShader(shader) node_path.set_shader_input('color', (0.2, 0.5, 0)) self.camera.setPos(0, 0, 10) self.camera.lookAt(node_path) self.disableMouse() controller = MouseController(self.camera, self) controller.zoom()
def reload_shader(self): self.model.set_shader(Shader.load(Shader.SL_GLSL, vertex = "shader.vert", tess_control = "shader.tesc", tess_evaluation = "shader.tese", geometry = "shader.geom", fragment = "shader.frag"))
def _makeShader(shaderEffects, baseShader=None): """ Generates shader source from effects and converts it into a Panda3D shader object baseShader is source to inject effects into """ source=shadereffects.makeSource(shaderEffects, baseShader) key=source if key not in builtEffectsShaders: if useShaderFiles: # preflatten should not impact anything much, but lets us get the full names shaderEffects=[s.flatten() for s in shaderEffects] name='debug('+','.join([e.name for e in shaderEffects])+')' outLoc='ShadersOut/'+name+'.sha' print 'Making Shader: '+outLoc builtEffectsShaders[key]=Shader.make(source) if useShaderFiles: fOut=open(outLoc, 'w') fOut.write(source) fOut.close() return builtEffectsShaders[key]
def create_model(self): # Set up the vertex arrays vformat = GeomVertexFormat.get_v3c4() vdata = GeomVertexData("Data", vformat, Geom.UHStatic) vertex = GeomVertexWriter(vdata, 'vertex') color = GeomVertexWriter(vdata, 'color') geom = Geom(vdata) # Vertex data vertex.addData3f(1.5, 0, -1) color.addData4f(1, 0, 0, 1) vertex.addData3f(-1.5, 0, -1) color.addData4f(0, 1, 0, 1) vertex.addData3f(0, 0, 1) color.addData4f(0, 0, 1, 1) # Primitive tri = GeomTriangles(Geom.UHStatic) tri.add_vertex(2) tri.add_vertex(1) tri.add_vertex(0) tri.close_primitive() geom.addPrimitive(tri) # Create the actual node node = GeomNode('geom_node') node.addGeom(geom) np = NodePath(node) # Shader and initial shader vars np.set_shader( Shader.load(Shader.SL_GLSL, "shader/shader.vert", "shader/shader.frag")) np.set_shader_input("time", 0.0) # No instancing necessary #np.set_instance_count(27) # return np np.reparent_to(base.render) self.model = np
def displayCBuffer(self, manager): tex = Texture() #Color texture dtex = Texture() #Depth texture quad = manager.renderSceneInto(colortex=tex, depthtex=dtex) #Produce filter of window quad.setShader(Shader.load("z_buf.sha")) #Apply shader to scene quad.setShaderInput("dtex", dtex) quad.setTexture(tex) #Apply regular color texture to filter
def setup(self, scenario: Scenario): self._scenario = scenario self._root_np = NodePath("sim") self._root_np.reparentTo(self.render) with pkg_resources.path( glsl, "unlit_shader.vert" ) as vshader_path, pkg_resources.path( glsl, "unlit_shader.frag" ) as fshader_path: unlit_shader = Shader.load( Shader.SL_GLSL, vertex=str(vshader_path.absolute()), fragment=str(fshader_path.absolute()), ) self._root_np.setShader(unlit_shader) self._setup_road_network() self._vehicles_np = self._root_np.attachNewNode("vehicles") self._bubble_manager = BubbleManager(scenario.bubbles, scenario.road_network) self._trap_manager = TrapManager(scenario) self._setup_bullet_client(self._bullet_client) provider_state = self._setup_providers(self._scenario) self._agent_manager.setup_agents(self) self._harmonize_providers(provider_state) self._last_provider_state = provider_state self._is_setup = True
def _recompile_pbr(self): gles = ConfigVariableString("load-display").getValue() if gles == "pandagles2": pbr_defines = { 'MAX_LIGHTS': self.max_lights, } if self.use_normal_maps: pbr_defines['USE_NORMAL_MAP'] = '' if self.use_emission_maps: pbr_defines['USE_EMISSION_MAP'] = '' if self.enable_shadows: pbr_defines['ENABLE_SHADOWS'] = '' if self.enable_fog: pbr_defines['ENABLE_FOG'] = '' if self.use_occlusion_maps: pbr_defines['USE_OCCLUSION_MAP'] = '' pbr_vert_str = _load_shader_str('simplepbr_gles.vert', pbr_defines) pbr_frag_str = _load_shader_str('simplepbr_gles.frag', pbr_defines) pbrshader = Shader.make( Shader.SL_GLSL, vertex=pbr_vert_str, fragment=pbr_frag_str, ) self.render_node.set_shader(pbrshader) else: super(OurPipeline, self)._recompile_pbr()
def __init__(self, terrain_model="content/models/terrain.egg"): myShader = Shader.load(Shader.SLGLSL, "content/shaders/terr_vert.glsl", "content/shaders/terr_frag.glsl") self.terrain = loader.loadModel("content/models/terrain.egg") self.terrain.reparentTo(render) def prepareTexture(tex): tex.setMinfilter(Texture.FTLinearMipmapLinear) self.terrain.setShaderInput("tilingFactor", 50) dirtTex = loader.loadTexture("content/textures/sand.jpg") prepareTexture(dirtTex) self.terrain.setShaderInput("region1ColorMap", dirtTex) dirtTex = loader.loadTexture("content/textures/dirt.JPG") prepareTexture(dirtTex) self.terrain.setShaderInput("region2ColorMap", dirtTex) dirtTex = loader.loadTexture("content/textures/rock.JPG") prepareTexture(dirtTex) self.terrain.setShaderInput("region3ColorMap", dirtTex) dirtTex = loader.loadTexture("content/textures/snow.JPG") prepareTexture(dirtTex) self.terrain.setShaderInput("region4ColorMap", dirtTex) print self.terrain.ls(); self.collider = self.terrain.find('**/Terrain') self.terrain.setShader(myShader)
def __init__(self): load_prc_file_data( "", """ textures-power-2 none window-type offscreen win-size 100 100 gl-coordinate-system default notify-level-display error print-pipe-types #f """) ShowBase.__init__(self) dest_tex = Texture() dest_tex.setup_2d_texture(2048, 2048, Texture.T_unsigned_byte, Texture.F_rgba8) cshader = Shader.load_compute(Shader.SL_GLSL, "grain.compute.glsl") node = NodePath("") node.set_shader(cshader) node.set_shader_input("DestTex", dest_tex) attr = node.get_attrib(ShaderAttrib) self.graphicsEngine.dispatch_compute((2048 // 16, 2048 // 16, 1), attr, self.win.get_gsg()) base.graphicsEngine.extract_texture_data(dest_tex, base.win.get_gsg()) # Convert to single channel img = PNMImage(2048, 2048, 1, 255) dest_tex.store(img) img.set_num_channels(1) tex = Texture() tex.load(img) tex.write("grain.txo.pz")
def setShaders(self): shader = Shader.load(Shader.SLGLSL, "Shader/DefaultPostProcess.vertex", "Shader/CombineOcclusion.fragment") self.target.setShader(shader) return [shader]
def setShaders(self): shader = Shader.load(Shader.SLGLSL, "Shader/DefaultPostProcess.vertex", "Shader/VolumetricLighting.fragment") self.target.setShader(shader) return [shader]
def setShaders(self): shader = Shader.load(Shader.SLGLSL, "Shader/DefaultPostProcess.vertex", "Shader/RenderClouds.fragment") self.target.setShader(shader) shaderV = Shader.load(Shader.SLGLSL, "Shader/DefaultPostProcess.vertex", "Shader/CloudBlurV.fragment") self.targetV.setShader(shaderV) shaderH = Shader.load(Shader.SLGLSL, "Shader/DefaultPostProcess.vertex", "Shader/CloudBlurH.fragment") self.targetH.setShader(shaderH) return [shader]
def SetupVisibleTerrain(self): self.terrain_node = ShaderTerrainMesh() self.terrain_node.heightfield = self.loader.loadTexture(self.PngDEM) self.terrain_node.target_triangle_width = 100.0 self.terrain_node.generate() self.terrain = self.render.attach_new_node(self.terrain_node) self.terrain.set_scale(self.PixelNr * self.MeterScale, self.PixelNr * self.MeterScale, self.HeightRange) terrain_shader = Shader.load(Shader.SL_GLSL, "terrain.vert.glsl", "terrain.frag.glsl") self.terrain.set_shader(terrain_shader) self.terrain.set_shader_input("camera", self.camera) grass_tex = self.loader.loadTexture(self.TextureImage) grass_tex.set_anisotropic_degree(16) self.terrain.set_texture(grass_tex) self.terrain.setPos(0, 0, self.OffsetHeight)
def __init__(self): # The basics ShowBase.__init__(self) base.disableMouse() base.setBackgroundColor(0.1, 0.1, 0.1) base.setFrameRateMeter(True) self.accept("escape", sys.exit) # Camera self.camera_orbit = base.render.attach_new_node("Camera orbit") self.camera_pitch = self.camera_orbit.attach_new_node("Camera pitch") base.camera.reparent_to(self.camera_pitch) base.camera.set_pos(0, -5, 0) # Camera control self.camera_movement = (0, 0) self.accept("arrow_up", self.change_camera_movement, [0, -1]) self.accept("arrow_up-up", self.change_camera_movement, [0, 1]) self.accept("arrow_down", self.change_camera_movement, [0, 1]) self.accept("arrow_down-up", self.change_camera_movement, [0, -1]) self.accept("arrow_left", self.change_camera_movement, [-1, 0]) self.accept("arrow_left-up", self.change_camera_movement, [1, 0]) self.accept("arrow_right", self.change_camera_movement, [1, 0]) self.accept("arrow_right-up", self.change_camera_movement, [-1, 0]) base.taskMgr.add(self.move_camera, "Move camera") # Object self.model = loader.loadModel("models/smiley") self.model.reparent_to(base.render) shader = Shader.make( Shader.SL_GLSL, vertex=vertex_shader, fragment=fragment_shader, ) self.model.set_shader(shader)
def _makeFontShader(self): self.fontShader = Shader.make(Shader.SLGLSL, """ #version 150 uniform mat4 p3d_ModelViewProjectionMatrix; in vec4 p3d_Vertex; in vec2 p3d_MultiTexCoord0; uniform float displData[100]; out vec2 texcoord; uniform vec2 pos; uniform vec2 size; void main() { int rawDispl = int(displData[gl_InstanceID]); ivec2 offsetDispl = ivec2( rawDispl % 16, rawDispl / 16); vec2 offsetCoordReal = vec2(offsetDispl.x / 16.0, (5.0 - offsetDispl.y) / 6.0); texcoord = p3d_MultiTexCoord0 / vec2(16,6) + offsetCoordReal; vec4 offset = vec4(gl_InstanceID*size.x*0.55 , 0, 0, 0) + vec4(pos.x, 0, pos.y, 0); vec4 finalPos = p3d_Vertex * vec4(size.x, size.x, size.x, 1.0) + offset; gl_Position = p3d_ModelViewProjectionMatrix * finalPos; } """, """ #version 150 #pragma file FastText.fragment in vec2 texcoord; uniform sampler2D font; uniform vec3 color; out vec4 result; void main() { float textFactor = texture(font, texcoord).x; result = vec4(color, textFactor); } """)
def create_model(self): # Set up the vertex arrays vformat = GeomVertexFormat.get_v3c4() vdata = GeomVertexData("Data", vformat, Geom.UHStatic) vertex = GeomVertexWriter(vdata, 'vertex') color = GeomVertexWriter(vdata, 'color') geom = Geom(vdata) # Vertex data vertex.addData3f(1.5, 0, -1) color.addData4f(1, 0, 0, 1) vertex.addData3f(-1.5, 0, -1) color.addData4f(0, 1, 0, 1) vertex.addData3f(0, 0, 1) color.addData4f(0, 0, 1, 1) # Primitive tri = GeomTriangles(Geom.UHStatic) tri.add_vertex(2) tri.add_vertex(1) tri.add_vertex(0) tri.close_primitive() geom.addPrimitive(tri) # Create the actual node node = GeomNode('geom_node') node.addGeom(geom) np = NodePath(node) # Shader and initial shader vars np.set_shader(Shader.load(Shader.SL_GLSL, "shader/shader.vert", "shader/shader.frag")) np.set_shader_input("time", 0.0) # No instancing necessary #np.set_instance_count(27) # return np np.reparent_to(base.render) self.model = np
def _makeShader(shaderEffects, baseShader=None): """ Generates shader source from effects and converts it into a Panda3D shader object baseShader is source to inject effects into """ source = shadereffects.makeSource(shaderEffects, baseShader) key = source if key not in builtEffectsShaders: if useShaderFiles: # preflatten should not impact anything much, but lets us get the full names shaderEffects = [s.flatten() for s in shaderEffects] name = 'debug(' + ','.join([e.name for e in shaderEffects]) + ')' outLoc = 'ShadersOut/' + name + '.sha' print 'Making Shader: ' + outLoc builtEffectsShaders[key] = Shader.make(source) if useShaderFiles: fOut = open(outLoc, 'w') fOut.write(source) fOut.close() return builtEffectsShaders[key]
def enableEffects(self, reflScene, refrScene, underwaterRefrScene): self.disableFakeEffect() static = loader.loadTexture(self.spec.staticTex) if not self.spec.cheap: self.topNP.setShader( Shader.load(Shader.SL_GLSL, "phase_14/models/shaders/water_v.glsl", "phase_14/models/shaders/water_f.glsl"), 2) self.topNP.setShaderInput("dudv", static) self.topNP.setShaderInput("dudv_tile", self.spec.dudvTile) self.topNP.setShaderInput("dudv_strength", self.spec.dudvStrength) self.topNP.setShaderInput("move_factor", self.spec.moveFactor) self.topNP.setShaderInput("near", CIGlobals.DefaultCameraNear) self.topNP.setShaderInput("far", CIGlobals.DefaultCameraFar) self.topNP.setShaderInput("normal_map", static) self.topNP.setShaderInput("fog_density", self.spec.fog.density) self.topNP.setShaderInput("fog_color", self.spec.fog.color) self.topNP.setShaderInput("water_tint", self.spec.tint) self.topNP.setShaderInput("reflect_factor", self.spec.reflectFactor) self.topNP.setShaderInput("static_depth", self.depth) self.botNP.setShader( Shader.load(Shader.SL_GLSL, "phase_14/models/shaders/water_bottom_v.glsl", "phase_14/models/shaders/water_bottom_f.glsl"), 2) self.botNP.setShaderInput("dudv", static) self.botNP.setShaderInput("dudv_tile", self.spec.dudvTile) self.botNP.setShaderInput("dudv_strength", self.spec.dudvStrength) self.botNP.setShaderInput("move_factor", self.spec.moveFactor) self.botNP.setShaderInput("water_tint", self.spec.tint) else: # We are doing cheap water self.topNP.setShader( Shader.load(Shader.SL_GLSL, "phase_14/models/shaders/water_cheap_v.glsl", "phase_14/models/shaders/water_cheap_f.glsl"), 2) self.topNP.setShaderInput("tex_scale", self.spec.dudvTile) self.topNP.setShaderInput("cube_map", self.cubemap) self.topNP.setShaderInput("normal_map", static) self.topNP.setShaderInput("base_map", static) self.topNP.setShaderInput("reflectivity", self.spec.reflectivity) self.topNP.setShaderInput("water_tint", self.spec.tint) self.setTextureInputs(reflScene, refrScene, underwaterRefrScene)
def setup(self, bloom=True, hdr=True): self.cleanup() textures = {"sceneColorSampler": self.getSceneColorTexture()} if hdr: self.hdr = HDREffect(self) self.hdr.getHdrPass().setExposureOutput( base.shaderGenerator.getExposureAdjustment()) self.addEffect(self.hdr) if bloom: self.bloom = BloomEffect(self) self.addEffect(self.bloom) textures["bloomSampler"] = self.bloom.getFinalTexture() finalQuad = self.getScenePass().getQuad() vtext = "#version 330\n" vtext += "uniform mat4 p3d_ModelViewProjectionMatrix;\n" vtext += "in vec4 p3d_Vertex;\n" vtext += "in vec4 texcoord;\n" vtext += "out vec2 l_texcoord;\n" vtext += "void main()\n" vtext += "{\n" vtext += " gl_Position = p3d_ModelViewProjectionMatrix * p3d_Vertex;\n" vtext += " l_texcoord = texcoord.xy;\n" vtext += "}\n" ptext = "#version 330\n" ptext += "out vec4 outputColor;\n" ptext += "in vec2 l_texcoord;\n" for sampler in textures.keys(): ptext += "uniform sampler2D " + sampler + ";\n" if self.flashEnabled: ptext += "uniform vec3 flashColor[1];\n" ptext += "void main()\n" ptext += "{\n" ptext += " outputColor = texture(sceneColorSampler, l_texcoord);\n" if bloom: ptext += " outputColor.rgb += texture(bloomSampler, l_texcoord).rgb;\n" if self.flashEnabled: ptext += " outputColor.rgb += pow(flashColor[0], vec3(2.2));\n" ptext += "}\n" shader = Shader.make(Shader.SL_GLSL, vtext, ptext) if not shader: return finalQuad.setShader(shader) for sampler, texture in textures.items(): finalQuad.setShaderInput(sampler, texture) if self.flashEnabled: finalQuad.setShaderInput("flashColor", self.flashColor)
def _setGuiShaders(self): """ Sets the default shaders to the gui, this is required when disabling the fixed function pipeline """ shader = Shader.load(Shader.SLGLSL, "Shader/GUI/vertex.glsl", "Shader/GUI/fragment.glsl") for target in [self.showbase.aspect2d, self.showbase.render2d, self.showbase.pixel2d, self.showbase.aspect2dp, self.showbase.render2dp, self.showbase.pixel2dp]: # target.setShader(shader, 50) pass
def setup_post_effect(self): self.manager = FilterManager(base.win, base.cam) tex = Texture() dtex = Texture() quad = self.manager.renderSceneInto(colortex=tex, depthtex=dtex) quad.setShader(Shader.load(Shader.SL_GLSL, "vertex.glsl", "fragment.glsl")) quad.setShaderInput("tex", tex) quad.setShaderInput("dtex", dtex)
def _createInitialGrid(self): """ Creates the initial cloud grid """ shader = Shader.loadCompute(Shader.SLGLSL, "Shader/Clouds/InitialGrid.compute") dummy = NodePath("dummy") dummy.setShader(shader) dummy.setShaderInput("cloudGrid", self.voxelGrid) sattr = dummy.getAttrib(ShaderAttrib) Globals.base.graphicsEngine.dispatch_compute( (self.cloudResolution / 8, self.cloudResolution / 8, self.cloudResolutionH / 8), sattr, Globals.base.win.getGsg()) shader = Shader.loadCompute(Shader.SLGLSL, "Shader/Clouds/CloudNoise.compute") dummy = NodePath("dummy") dummy.setShader(shader) dummy.setShaderInput("noiseGrid", self.cloudNoise) sattr = dummy.getAttrib(ShaderAttrib) Globals.base.graphicsEngine.dispatch_compute( (64 / 8, 64 / 8, 64 / 8), sattr, Globals.base.win.getGsg())
def loadCompute(self, source): """ Loads a compute shader """ content = self._handleIncludes(source) result = Shader.makeCompute(Shader.SLGLSL, content) self._writeDebugShader("Compute-" + str(source), content) self._clearIncludeStack() return result
def setShaders(self, refreshPipeline=True): """ Sets all shaders """ self.debug("Reloading Shaders ..") if self.renderPipeline: self.scene.setShader( self.renderPipeline.getDefaultObjectShader(False)) self.model.setShader(Shader.load(Shader.SLGLSL, "DefaultObjectShader/vertex.glsl", "dynamicMaterialFragment.glsl")) if refreshPipeline: self.renderPipeline.reloadShaders() if self.skybox: self.skybox.setShader(Shader.load(Shader.SLGLSL, "DefaultObjectShader/vertex.glsl", "Skybox/fragment.glsl"))
def setShaders(self): shader = Shader.load(Shader.SLGLSL, "Shader/TransparencyShade/vertex.glsl", "Shader/TransparencyShade/fragment.glsl", "Shader/TransparencyShade/geometry.glsl", ) self.target.setShader(shader) return [shader]
def load_shader(self): """ The function loads the vertex and fragment shader. It provides an example of sending the model-view-projection matrix to the shader program when it's calculated. """ self.shader = Shader.load(Shader.SL_GLSL, "vertex.glsl", "fragment.glsl"); self.model.set_shader(self.shader) self.model.set_shader_input("my_ModelViewProjectionMatrix", LMatrix4f())
def setShaders(self): shaderFirstPass = Shader.load(Shader.SLGLSL, "Shader/DefaultPostProcess.vertex", "Shader/DownsampleFirstPass.fragment") self.downscalePass0.setShader(shaderFirstPass) shaderDownsample = Shader.load(Shader.SLGLSL, "Shader/DefaultPostProcess.vertex", "Shader/Downsample.fragment") for scalePass in self.downscalePasses: scalePass.setShader(shaderDownsample) shaderFinal = Shader.load(Shader.SLGLSL, "Shader/DefaultPostProcess.vertex", "Shader/DownsampleFinalPass.fragment") self.finalDownsamplePass.setShader(shaderFinal) return [shaderFirstPass, shaderDownsample, shaderFinal]
def _createGenerateMipmapsShader(self): """ Loads the shader for generating the voxel grid mipmaps """ computeSize = self.voxelGridResolution for child in self.mipmapTargets: computeSize /= 2 shader = Shader.load(Shader.SLGLSL, "Shader/DefaultPostProcess.vertex", "Shader/GI/GenerateMipmaps/" + str(computeSize) + ".fragment") child.setShader(shader)