def parse_surface(world: bpy.types.World, node_surface: bpy.types.Node, frag: Shader): wrd = bpy.data.worlds['Arm'] rpdat = arm.utils.get_rp() solid_mat = rpdat.arm_material_model == 'Solid' if node_surface.type in ('BACKGROUND', 'EMISSION'): # Append irradiance define if rpdat.arm_irradiance and not solid_mat: wrd.world_defs += '_Irr' # Extract environment strength # Todo: follow/parse strength input world.arm_envtex_strength = node_surface.inputs[1].default_value # Color out = cycles.parse_vector_input(node_surface.inputs[0]) frag.write(f'fragColor.rgb = {out};') if not node_surface.inputs[0].is_linked: solid_mat = rpdat.arm_material_model == 'Solid' if rpdat.arm_irradiance and not solid_mat: world.world_defs += '_Irr' world.arm_envtex_color = node_surface.inputs[0].default_value world.arm_envtex_strength = 1.0 else: log.warn( f'World node type {node_surface.type} must not be connected to the world output node!' ) # Invalidate the parser state for subsequent executions cycles.state = None
def write_norpos(con_mesh: shader.ShaderContext, vert: shader.Shader, declare=False, write_nor=True): is_bone = con_mesh.is_elem('bone') if is_bone: make_skin.skin_pos(vert) if write_nor: prep = 'vec3 ' if declare else '' if is_bone: make_skin.skin_nor(vert, prep) else: vert.write_attrib(prep + 'wnormal = normalize(N * vec3(nor.xy, pos.w));') if con_mesh.is_elem('ipos'): make_inst.inst_pos(con_mesh, vert)
def parse(self, frag: Shader, vert: Shader) -> str: if self.input_type == "uniform": frag.add_uniform(f'{self.variable_type} {self.variable_name}', link=self.variable_name) return self.variable_name else: if self.input_source == "frag": frag.add_in(f'{self.variable_type} {self.variable_name}') return self.variable_name # Reroute input from vertex shader to fragment shader (input must exist!) else: vert.add_out(f'{self.variable_type} out_{self.variable_name}') frag.add_in(f'{self.variable_type} out_{self.variable_name}') vert.write(f'out_{self.variable_name} = {self.variable_name};') return 'out_' + self.variable_name
def write_norpos(con_mesh: ShaderContext, vert: Shader, declare=False, write_nor=True): is_bone = con_mesh.is_elem('bone') is_morph = con_mesh.is_elem('morph') if is_morph: make_morph_target.morph_pos(vert) if is_bone: make_skin.skin_pos(vert) if write_nor: prep = 'vec3 ' if declare else '' if is_morph: make_morph_target.morph_nor(vert, is_bone, prep) if is_bone: make_skin.skin_nor(vert, is_morph, prep) if not is_morph and not is_bone: vert.write_attrib(prep + 'wnormal = normalize(N * vec3(nor.xy, pos.w));') if con_mesh.is_elem('ipos'): make_inst.inst_pos(con_mesh, vert)
def build_node_tree(world: bpy.types.World, frag: Shader): """Generates the shader code for the given world.""" world_name = arm.utils.safestr(world.name) world.world_defs = '' rpdat = arm.utils.get_rp() wrd = bpy.data.worlds['Arm'] if callback is not None: callback() # Traverse world node tree is_parsed = False if world.node_tree is not None: output_node = node_utils.get_node_by_type(world.node_tree, 'OUTPUT_WORLD') if output_node is not None: is_parsed = parse_world_output(world, output_node, frag) # No world nodes/no output node, use background color if not is_parsed: solid_mat = rpdat.arm_material_model == 'Solid' if rpdat.arm_irradiance and not solid_mat: world.world_defs += '_Irr' col = world.color world.arm_envtex_color = [col[0], col[1], col[2], 1.0] world.arm_envtex_strength = 1.0 # Clear to color if no texture or sky is provided if '_EnvSky' not in world.world_defs and '_EnvTex' not in world.world_defs: if '_EnvImg' not in world.world_defs: world.world_defs += '_EnvCol' frag.add_uniform('vec3 backgroundCol', link='_backgroundCol') # Irradiance json file name world.arm_envtex_name = world_name world.arm_envtex_irr_name = world_name write_probes.write_color_irradiance(world_name, world.arm_envtex_color) # film_transparent if bpy.context.scene is not None and hasattr( bpy.context.scene.render, 'film_transparent') and bpy.context.scene.render.film_transparent: world.world_defs += '_EnvTransp' world.world_defs += '_EnvCol' frag.add_uniform('vec3 backgroundCol', link='_backgroundCol') # Clouds enabled if rpdat.arm_clouds and world.arm_use_clouds: world.world_defs += '_EnvClouds' # Also set this flag globally so that the required textures are # included wrd.world_defs += '_EnvClouds' frag_write_clouds(world, frag) if '_EnvSky' in world.world_defs or '_EnvTex' in world.world_defs or '_EnvImg' in world.world_defs or '_EnvClouds' in world.world_defs: frag.add_uniform('float envmapStrength', link='_envmapStrength') frag_write_main(world, frag)
def write_shader(rel_path: str, shader: Shader, ext: str, rpass: str, matname: str, keep_cache=True) -> None: if shader is None or shader.is_linked: return # TODO: blend context if rpass == 'mesh' and mat_state.material.arm_blending: rpass = '******' file_ext = '.glsl' if shader.noprocessing: # Use hlsl directly hlsl_dir = arm.utils.build_dir() + '/compiled/Hlsl/' if not os.path.exists(hlsl_dir): os.makedirs(hlsl_dir) file_ext = '.hlsl' rel_path = rel_path.replace('/compiled/Shaders/', '/compiled/Hlsl/') shader_file = matname + '_' + rpass + '.' + ext + file_ext shader_path = arm.utils.get_fp() + '/' + rel_path + '/' + shader_file assets.add_shader(shader_path) if not os.path.isfile(shader_path) or not keep_cache: with open(shader_path, 'w') as f: f.write(shader.get()) if shader.noprocessing: cwd = os.getcwd() os.chdir(arm.utils.get_fp() + '/' + rel_path) hlslbin_path = arm.utils.get_sdk_path( ) + '/lib/armory_tools/hlslbin/hlslbin.exe' prof = 'vs_5_0' if ext == 'vert' else 'ps_5_0' if ext == 'frag' else 'gs_5_0' # noprocessing flag - gets renamed to .d3d11 args = [ hlslbin_path.replace('/', '\\').replace('\\\\', '\\'), shader_file, shader_file[:-4] + 'glsl', prof ] if ext == 'vert': args.append('-i') args.append('pos') proc = subprocess.call(args) os.chdir(cwd)
def finalize(frag: Shader, vert: Shader): """Checks the given fragment shader for completeness and adds variable initializations if required. TODO: Merge with make_finalize? """ if frag.contains('pos') and not frag.contains('vec3 pos'): frag.write_attrib('vec3 pos = -n;') if frag.contains('vVec') and not frag.contains('vec3 vVec'): # For worlds, the camera seems to be always at origin in # Blender, so we can just use the normals as the incoming vector frag.write_attrib('vec3 vVec = n;') for var in ('bposition', 'mposition', 'wposition'): if (frag.contains(var) and not frag.contains(f'vec3 {var}')) or vert.contains(var): frag.add_in(f'vec3 {var}') vert.add_out(f'vec3 {var}') vert.write(f'{var} = pos;') if frag.contains('wtangent') and not frag.contains('vec3 wtangent'): frag.write_attrib('vec3 wtangent = vec3(0.0);') if frag.contains('texCoord') and not frag.contains('vec2 texCoord'): frag.add_in('vec2 texCoord') vert.add_out('vec2 texCoord') # World has no UV map vert.write('texCoord = vec2(1.0, 1.0);')
def build_node_tree(world: bpy.types.World, frag: Shader, vert: Shader, con: ShaderContext): """Generates the shader code for the given world.""" world_name = arm.utils.safestr(world.name) world.world_defs = '' rpdat = arm.utils.get_rp() wrd = bpy.data.worlds['Arm'] if callback is not None: callback() # film_transparent, do not render if bpy.context.scene is not None and bpy.context.scene.render.film_transparent: world.world_defs += '_EnvCol' frag.add_uniform('vec3 backgroundCol', link='_backgroundCol') frag.write('fragColor.rgb = backgroundCol;') return parser_state = ParserState(ParserContext.WORLD, world) parser_state.con = con parser_state.curshader = frag parser_state.frag = frag parser_state.vert = vert cycles.state = parser_state # Traverse world node tree is_parsed = False if world.node_tree is not None: output_node = node_utils.get_node_by_type(world.node_tree, 'OUTPUT_WORLD') if output_node is not None: is_parsed = parse_world_output(world, output_node, frag) # No world nodes/no output node, use background color if not is_parsed: solid_mat = rpdat.arm_material_model == 'Solid' if rpdat.arm_irradiance and not solid_mat: world.world_defs += '_Irr' col = world.color world.arm_envtex_color = [col[0], col[1], col[2], 1.0] world.arm_envtex_strength = 1.0 world.world_defs += '_EnvCol' # Clouds enabled if rpdat.arm_clouds and world.arm_use_clouds: world.world_defs += '_EnvClouds' # Also set this flag globally so that the required textures are # included wrd.world_defs += '_EnvClouds' frag_write_clouds(world, frag) if '_EnvSky' in world.world_defs or '_EnvTex' in world.world_defs or '_EnvImg' in world.world_defs or '_EnvClouds' in world.world_defs: frag.add_uniform('float envmapStrength', link='_envmapStrength') # Clear background color if '_EnvCol' in world.world_defs: frag.write('fragColor.rgb = backgroundCol;') elif '_EnvTex' in world.world_defs and '_EnvLDR' in world.world_defs: frag.write('fragColor.rgb = pow(fragColor.rgb, vec3(2.2));') if '_EnvClouds' in world.world_defs: frag.write( 'if (pos.z > 0.0) fragColor.rgb = mix(fragColor.rgb, traceClouds(fragColor.rgb, pos), clamp(pos.z * 5.0, 0, 1));' ) if '_EnvLDR' in world.world_defs: frag.write('fragColor.rgb = pow(fragColor.rgb, vec3(1.0 / 2.2));') # Mark as non-opaque frag.write('fragColor.a = 0.0;') finalize(frag, vert)
def make_tese(self): self.data['tesseval_shader'] = self.matname + '_' + self.data[ 'name'] + '.tese' self.tese = Shader(self, 'tese') return self.tese
def make_tesc(self): self.data['tesscontrol_shader'] = self.matname + '_' + self.data[ 'name'] + '.tesc' self.tesc = Shader(self, 'tesc') return self.tesc
def make_geom(self): self.data['geometry_shader'] = self.matname + '_' + self.data[ 'name'] + '.geom' self.geom = Shader(self, 'geom') return self.geom
def parse_color(world: bpy.types.World, node: bpy.types.Node, frag: Shader): wrd = bpy.data.worlds['Arm'] rpdat = arm.utils.get_rp() mobile_mat = rpdat.arm_material_model == 'Mobile' or rpdat.arm_material_model == 'Solid' # Env map included if node.type == 'TEX_ENVIRONMENT' and node.image is not None: world.world_defs += '_EnvTex' frag.add_include('std/math.glsl') frag.add_uniform('sampler2D envmap', link='_envmap') image = node.image filepath = image.filepath if image.packed_file is None and not os.path.isfile( arm.utils.asset_path(filepath)): log.warn(world.name + ' - unable to open ' + image.filepath) return # Reference image name tex_file = arm.utils.extract_filename(image.filepath) base = tex_file.rsplit('.', 1) ext = base[1].lower() if ext == 'hdr': target_format = 'HDR' else: target_format = 'JPEG' do_convert = ext != 'hdr' and ext != 'jpg' if do_convert: if ext == 'exr': tex_file = base[0] + '.hdr' target_format = 'HDR' else: tex_file = base[0] + '.jpg' target_format = 'JPEG' if image.packed_file is not None: # Extract packed data unpack_path = arm.utils.get_fp_build( ) + '/compiled/Assets/unpacked' if not os.path.exists(unpack_path): os.makedirs(unpack_path) unpack_filepath = unpack_path + '/' + tex_file filepath = unpack_filepath if do_convert: if not os.path.isfile(unpack_filepath): arm.utils.unpack_image(image, unpack_filepath, file_format=target_format) elif not os.path.isfile(unpack_filepath) or os.path.getsize( unpack_filepath) != image.packed_file.size: with open(unpack_filepath, 'wb') as f: f.write(image.packed_file.data) assets.add(unpack_filepath) else: if do_convert: unpack_path = arm.utils.get_fp_build( ) + '/compiled/Assets/unpacked' if not os.path.exists(unpack_path): os.makedirs(unpack_path) converted_path = unpack_path + '/' + tex_file filepath = converted_path # TODO: delete cache when file changes if not os.path.isfile(converted_path): arm.utils.convert_image(image, converted_path, file_format=target_format) assets.add(converted_path) else: # Link image path to assets assets.add(arm.utils.asset_path(image.filepath)) # Generate prefiltered envmaps world.arm_envtex_name = tex_file world.arm_envtex_irr_name = tex_file.rsplit('.', 1)[0] disable_hdr = target_format == 'JPEG' mip_count = world.arm_envtex_num_mips mip_count = write_probes.write_probes(filepath, disable_hdr, mip_count, arm_radiance=rpdat.arm_radiance) world.arm_envtex_num_mips = mip_count # Append LDR define if disable_hdr: world.world_defs += '_EnvLDR' # Append radiance define if rpdat.arm_irradiance and rpdat.arm_radiance and not mobile_mat: wrd.world_defs += '_Rad' # Static image background elif node.type == 'TEX_IMAGE': world.world_defs += '_EnvImg' # Background texture frag.add_uniform('sampler2D envmap', link='_envmap') frag.add_uniform('vec2 screenSize', link='_screenSize') image = node.image filepath = image.filepath if image.packed_file is not None: # Extract packed data filepath = arm.utils.build_dir() + '/compiled/Assets/unpacked' unpack_path = arm.utils.get_fp() + filepath if not os.path.exists(unpack_path): os.makedirs(unpack_path) unpack_filepath = unpack_path + '/' + image.name if os.path.isfile(unpack_filepath) == False or os.path.getsize( unpack_filepath) != image.packed_file.size: with open(unpack_filepath, 'wb') as f: f.write(image.packed_file.data) assets.add(unpack_filepath) else: # Link image path to assets assets.add(arm.utils.asset_path(image.filepath)) # Reference image name tex_file = arm.utils.extract_filename(image.filepath) base = tex_file.rsplit('.', 1) ext = base[1].lower() if ext == 'hdr': target_format = 'HDR' else: target_format = 'JPEG' # Generate prefiltered envmaps world.arm_envtex_name = tex_file world.arm_envtex_irr_name = tex_file.rsplit('.', 1)[0] disable_hdr = target_format == 'JPEG' mip_count = world.arm_envtex_num_mips mip_count = write_probes.write_probes(filepath, disable_hdr, mip_count, arm_radiance=rpdat.arm_radiance) world.arm_envtex_num_mips = mip_count # Append sky define elif node.type == 'TEX_SKY': # Match to cycles world.arm_envtex_strength *= 0.1 world.world_defs += '_EnvSky' assets.add_khafile_def('arm_hosek') frag.add_uniform('vec3 A', link="_hosekA") frag.add_uniform('vec3 B', link="_hosekB") frag.add_uniform('vec3 C', link="_hosekC") frag.add_uniform('vec3 D', link="_hosekD") frag.add_uniform('vec3 E', link="_hosekE") frag.add_uniform('vec3 F', link="_hosekF") frag.add_uniform('vec3 G', link="_hosekG") frag.add_uniform('vec3 H', link="_hosekH") frag.add_uniform('vec3 I', link="_hosekI") frag.add_uniform('vec3 Z', link="_hosekZ") frag.add_uniform('vec3 hosekSunDirection', link="_hosekSunDirection") frag.add_function( '''vec3 hosekWilkie(float cos_theta, float gamma, float cos_gamma) { \tvec3 chi = (1 + cos_gamma * cos_gamma) / pow(1 + H * H - 2 * cos_gamma * H, vec3(1.5)); \treturn (1 + A * exp(B / (cos_theta + 0.01))) * (C + D * exp(E * gamma) + F * (cos_gamma * cos_gamma) + G * chi + I * sqrt(cos_theta)); }''') world.arm_envtex_sun_direction = [ node.sun_direction[0], node.sun_direction[1], node.sun_direction[2] ] world.arm_envtex_turbidity = node.turbidity world.arm_envtex_ground_albedo = node.ground_albedo # Irradiance json file name wname = arm.utils.safestr(world.name) world.arm_envtex_irr_name = wname write_probes.write_sky_irradiance(wname) # Radiance if rpdat.arm_radiance and rpdat.arm_irradiance and not mobile_mat: wrd.world_defs += '_Rad' hosek_path = 'armory/Assets/hosek/' sdk_path = arm.utils.get_sdk_path() # Use fake maps for now assets.add(sdk_path + '/' + hosek_path + 'hosek_radiance.hdr') for i in range(0, 8): assets.add(sdk_path + '/' + hosek_path + 'hosek_radiance_' + str(i) + '.hdr') world.arm_envtex_name = 'hosek' world.arm_envtex_num_mips = 8
def build_node_tree(world: bpy.types.World, frag: Shader, vert: Shader, con: ShaderContext): """Generates the shader code for the given world.""" world_name = arm.utils.safestr(world.name) world.world_defs = '' rpdat = arm.utils.get_rp() wrd = bpy.data.worlds['Arm'] if callback is not None: callback() # film_transparent, do not render if bpy.context.scene is not None and bpy.context.scene.render.film_transparent: world.world_defs += '_EnvCol' frag.add_uniform('vec3 backgroundCol', link='_backgroundCol') frag.write('fragColor.rgb = backgroundCol;') return parser_state = ParserState(ParserContext.WORLD, world) parser_state.con = con parser_state.curshader = frag parser_state.frag = frag parser_state.vert = vert cycles.state = parser_state # Traverse world node tree is_parsed = False if world.node_tree is not None: output_node = node_utils.get_node_by_type(world.node_tree, 'OUTPUT_WORLD') if output_node is not None: is_parsed = parse_world_output(world, output_node, frag) # No world nodes/no output node, use background color if not is_parsed: solid_mat = rpdat.arm_material_model == 'Solid' if rpdat.arm_irradiance and not solid_mat: world.world_defs += '_Irr' col = world.color world.arm_envtex_color = [col[0], col[1], col[2], 1.0] world.arm_envtex_strength = 1.0 # Irradiance/Radiance: clear to color if no texture or sky is provided if rpdat.arm_irradiance or rpdat.arm_irradiance: if '_EnvSky' not in world.world_defs and '_EnvTex' not in world.world_defs and '_EnvImg' not in world.world_defs: # Irradiance json file name world.arm_envtex_name = world_name world.arm_envtex_irr_name = world_name write_probes.write_color_irradiance(world_name, world.arm_envtex_color) # Clouds enabled if rpdat.arm_clouds and world.arm_use_clouds: world.world_defs += '_EnvClouds' # Also set this flag globally so that the required textures are # included wrd.world_defs += '_EnvClouds' frag_write_clouds(world, frag) if '_EnvSky' in world.world_defs or '_EnvTex' in world.world_defs or '_EnvImg' in world.world_defs or '_EnvClouds' in world.world_defs: frag.add_uniform('float envmapStrength', link='_envmapStrength') # Clear background color if '_EnvCol' in world.world_defs: frag.write('fragColor.rgb = backgroundCol;') elif '_EnvTex' in world.world_defs and '_EnvLDR' in world.world_defs: frag.write('fragColor.rgb = pow(fragColor.rgb, vec3(2.2));') if '_EnvClouds' in world.world_defs: frag.write( 'if (n.z > 0.0) fragColor.rgb = mix(fragColor.rgb, traceClouds(fragColor.rgb, n), clamp(n.z * 5.0, 0, 1));' ) if '_EnvLDR' in world.world_defs: frag.write('fragColor.rgb = pow(fragColor.rgb, vec3(1.0 / 2.2));') # Mark as non-opaque frag.write('fragColor.a = 0.0;') # Hack to make procedural textures work frag_bpos = ( frag.contains('bposition') and not frag.contains('vec3 bposition')) or vert.contains('bposition') if frag_bpos: frag.add_in('vec3 bposition') vert.add_out('vec3 bposition') # Use normals for now vert.write('bposition = nor;') frag_mpos = ( frag.contains('mposition') and not frag.contains('vec3 mposition')) or vert.contains('mposition') if frag_mpos: frag.add_in('vec3 mposition') vert.add_out('vec3 mposition') # Use normals for now vert.write('mposition = nor;') if frag.contains('texCoord') and not frag.contains('vec2 texCoord'): frag.add_in('vec2 texCoord') vert.add_out('vec2 texCoord') # World has no UV map vert.write('texCoord = vec2(1.0, 1.0);')
def write_tex_coords(con_mesh: ShaderContext, vert: Shader, frag: Shader, tese: Optional[Shader]): rpdat = arm.utils.get_rp() if con_mesh.is_elem('tex'): vert.add_out('vec2 texCoord') vert.add_uniform('float texUnpack', link='_texUnpack') if mat_state.material.arm_tilesheet_flag: if mat_state.material.arm_particle_flag and rpdat.arm_particles == 'On': make_particle.write_tilesheet(vert) else: vert.add_uniform('vec2 tilesheetOffset', '_tilesheetOffset') vert.write_attrib( 'texCoord = tex * texUnpack + tilesheetOffset;') else: vert.write_attrib('texCoord = tex * texUnpack;') if tese is not None: tese.write_pre = True make_tess.interpolate(tese, 'texCoord', 2, declare_out=frag.contains('texCoord')) tese.write_pre = False if con_mesh.is_elem('tex1'): vert.add_out('vec2 texCoord1') vert.add_uniform('float texUnpack', link='_texUnpack') vert.write_attrib('texCoord1 = tex1 * texUnpack;') if tese is not None: tese.write_pre = True make_tess.interpolate(tese, 'texCoord1', 2, declare_out=frag.contains('texCoord1')) tese.write_pre = False
def parse(self, vertshdr:Shader,part_con) -> str: if(self.sclX or self.sclY or self.sclZ): scl = parse_vector_input(self.inputs[2]) if(self.sclX): vertshdr.write(f'spos.x *= {scl}.x;') if(self.sclY): vertshdr.write(f'spos.y *= {scl}.y;') if(self.sclX): vertshdr.write(f'spos.z *= {scl}.z;') if(self.billBoard): vertshdr.add_uniform('mat4 WV', '_worldViewMatrix') vertshdr.write('spos = mat4(transpose(mat3(WV))) * spos;') if(self.rotX or self.rotY or self.rotZ): rot = parse_vector_input(self.inputs[1]) if(self.rotX and not self.rotY and not self.rotZ): vertshdr.write(f'mat3 part_rot_mat = mat3(1.0, 0.0, 0.0,') vertshdr.write(f' 0.0, cos({rot}.x), sin({rot}.x),') vertshdr.write(f' 0.0, -sin({rot}.x), cos({rot}.x));') if(not self.rotX and self.rotY and not self.rotZ): vertshdr.write(f'mat3 part_rot_mat = mat3(cos({rot}.y), 0.0, -sin({rot}.y),') vertshdr.write(f' 0.0, 1.0, 0.0,') vertshdr.write(f' sin({rot}.y), 0.0, cos({rot}.y));') if(not self.rotX and not self.rotY and self.rotZ): vertshdr.write(f'mat3 part_rot_mat = mat3(cos({rot}.z), sin({rot}.z), 0.0,') vertshdr.write(f' -sin({rot}.z), cos({rot}.z), 0.0,') vertshdr.write(f' 0.0, 0.0, 1.0);') if(self.rotX and self.rotY and not self.rotZ): vertshdr.write(f'mat3 part_rot_mat = mat3(cos({rot}.y), 0.0, -sin({rot}.y),') vertshdr.write(f' sin({rot}.y) * sin({rot}.x), cos({rot}.x), cos({rot}.y) * sin({rot}.x),') vertshdr.write(f' sin({rot}.y) * cos({rot}.x), -sin({rot}.x), cos({rot}.y) * cos({rot}.x));') if(self.rotX and not self.rotY and self.rotZ): vertshdr.write(f'mat3 part_rot_mat = mat3(cos({rot}.z), sin({rot}.z), 0.0,') vertshdr.write(f' -sin({rot}.z) * cos({rot}.x), cos({rot}.z) * cos({rot}.x), sin({rot}.x),') vertshdr.write(f' sin({rot}.z) * sin({rot}.x), -cos({rot}.z) * sin({rot}.x), cos({rot}.x));') if(not self.rotX and self.rotY and self.rotZ): vertshdr.write(f'mat3 part_rot_mat = mat3(cos({rot}.z) * cos({rot}.y), sin({rot}.z) * cos({rot}.y), -sin({rot}.y),') vertshdr.write(f' -sin({rot}.z) , cos({rot}.z), 0.0,') vertshdr.write(f' cos({rot}.z) * sin({rot}.y), sin({rot}.z) * sin({rot}.y), cos({rot}.y));') if(self.rotX and self.rotY and self.rotZ): vertshdr.write(f'mat3 part_rot_mat = mat3(cos({rot}.z) * cos({rot}.y), sin({rot}.z) * cos({rot}.y), -sin({rot}.y),') vertshdr.write(f' -sin({rot}.z) * cos({rot}.x) + cos({rot}.z) * sin({rot}.y) * sin({rot}.x), cos({rot}.z) * cos({rot}.x) + sin({rot}.z) * sin({rot}.y) * sin({rot}.x), cos({rot}.y) * sin({rot}.x),') vertshdr.write(f' sin({rot}.z) * sin({rot}.x) + cos({rot}.z) * sin({rot}.y) * cos({rot}.x), -cos({rot}.z) * sin({rot}.x) + sin({rot}.z) * sin({rot}.y) * cos({rot}.x), cos({rot}.y) * cos({rot}.x));') if(self.rotX or self.rotY or self.rotZ): vertshdr.write('spos.xyz = part_rot_mat * spos.xyz;') if((part_con.data['name'] == 'mesh' or 'translucent') and vertshdr.contains('wnormal')): vertshdr.write('wnormal = transpose(inverse(part_rot_mat)) * wnormal;') if(self.posX or self.posY or self.posZ): pos = parse_vector_input(self.inputs[0]) if(self.posX): vertshdr.write(f'spos.x += {pos}.x;') if(self.posY): vertshdr.write(f'spos.y += {pos}.y;') if(self.posZ): vertshdr.write(f'spos.z += {pos}.z;') if(vertshdr.contains('vec3 disp')): vertshdr.write('wposition = vec4(W * spos).xyz;')
def frag_write_main(world: bpy.types.World, frag: Shader): if '_EnvSky' in world.world_defs or '_EnvTex' in world.world_defs or '_EnvClouds' in world.world_defs: frag.write('vec3 n = normalize(normal);') if '_EnvCol' in world.world_defs: frag.write('fragColor.rgb = backgroundCol;') if '_EnvTransp' in world.world_defs: frag.write('return;') # Static background image elif '_EnvImg' in world.world_defs: # Will have to get rid of gl_FragCoord, pass texture coords from # vertex shader frag.write('vec2 texco = gl_FragCoord.xy / screenSize;') frag.write( 'fragColor.rgb = texture(envmap, vec2(texco.x, 1.0 - texco.y)).rgb * envmapStrength;' ) # Environment texture # Also check for _EnvSky to prevent case when sky radiance is enabled elif '_EnvTex' in world.world_defs and '_EnvSky' not in world.world_defs: frag.write( 'fragColor.rgb = texture(envmap, envMapEquirect(n)).rgb * envmapStrength;' ) if '_EnvLDR' in world.world_defs: frag.write('fragColor.rgb = pow(fragColor.rgb, vec3(2.2));') if '_EnvSky' in world.world_defs: frag.write('float cos_theta = clamp(n.z, 0.0, 1.0);') frag.write('float cos_gamma = dot(n, hosekSunDirection);') frag.write('float gamma_val = acos(cos_gamma);') frag.write( 'fragColor.rgb = Z * hosekWilkie(cos_theta, gamma_val, cos_gamma) * envmapStrength;' ) if '_EnvClouds' in world.world_defs: frag.write( 'if (n.z > 0.0) fragColor.rgb = mix(fragColor.rgb, traceClouds(fragColor.rgb, n), clamp(n.z * 5.0, 0, 1));' ) if '_EnvLDR' in world.world_defs: frag.write('fragColor.rgb = pow(fragColor.rgb, vec3(1.0 / 2.2));') # Mark as non-opaque frag.write('fragColor.a = 0.0;')
def frag_write_clouds(world: bpy.types.World, frag: Shader): """References: GPU PRO 7 - Real-time Volumetric Cloudscapes https://www.guerrilla-games.com/read/the-real-time-volumetric-cloudscapes-of-horizon-zero-dawn https://github.com/sebh/TileableVolumeNoise """ frag.add_uniform('sampler3D scloudsBase', link='$clouds_base.raw') frag.add_uniform('sampler3D scloudsDetail', link='$clouds_detail.raw') frag.add_uniform('sampler2D scloudsMap', link='$clouds_map.png') frag.add_uniform('float time', link='_time') frag.add_const('float', 'cloudsLower', str(round(world.arm_clouds_lower * 100) / 100)) frag.add_const('float', 'cloudsUpper', str(round(world.arm_clouds_upper * 100) / 100)) frag.add_const( 'vec2', 'cloudsWind', 'vec2(' + str(round(world.arm_clouds_wind[0] * 100) / 100) + ',' + str(round(world.arm_clouds_wind[1] * 100) / 100) + ')') frag.add_const('float', 'cloudsPrecipitation', str(round(world.arm_clouds_precipitation * 100) / 100)) frag.add_const('float', 'cloudsSecondary', str(round(world.arm_clouds_secondary * 100) / 100)) frag.add_const('float', 'cloudsSteps', str(round(world.arm_clouds_steps * 100) / 100)) frag.add_function( '''float remap(float old_val, float old_min, float old_max, float new_min, float new_max) { \treturn new_min + (((old_val - old_min) / (old_max - old_min)) * (new_max - new_min)); }''') frag.add_function( '''float getDensityHeightGradientForPoint(float height, float cloud_type) { \tconst vec4 stratusGrad = vec4(0.02f, 0.05f, 0.09f, 0.11f); \tconst vec4 stratocumulusGrad = vec4(0.02f, 0.2f, 0.48f, 0.625f); \tconst vec4 cumulusGrad = vec4(0.01f, 0.0625f, 0.78f, 1.0f); \tfloat stratus = 1.0f - clamp(cloud_type * 2.0f, 0, 1); \tfloat stratocumulus = 1.0f - abs(cloud_type - 0.5f) * 2.0f; \tfloat cumulus = clamp(cloud_type - 0.5f, 0, 1) * 2.0f; \tvec4 cloudGradient = stratusGrad * stratus + stratocumulusGrad * stratocumulus + cumulusGrad * cumulus; \treturn smoothstep(cloudGradient.x, cloudGradient.y, height) - smoothstep(cloudGradient.z, cloudGradient.w, height); }''') frag.add_function('''float sampleCloudDensity(vec3 p) { \tfloat cloud_base = textureLod(scloudsBase, p, 0).r * 40; // Base noise \tvec3 weather_data = textureLod(scloudsMap, p.xy, 0).rgb; // Weather map \tcloud_base *= getDensityHeightGradientForPoint(p.z, weather_data.b); // Cloud type \tcloud_base = remap(cloud_base, weather_data.r, 1.0, 0.0, 1.0); // Coverage \tcloud_base *= weather_data.r; \tfloat cloud_detail = textureLod(scloudsDetail, p, 0).r * 2; // Detail noise \tfloat cloud_detail_mod = mix(cloud_detail, 1.0 - cloud_detail, clamp(p.z * 10.0, 0, 1)); \tcloud_base = remap(cloud_base, cloud_detail_mod * 0.2, 1.0, 0.0, 1.0); \treturn cloud_base; }''') func_cloud_radiance = 'float cloudRadiance(vec3 p, vec3 dir) {\n' if '_EnvSky' in world.world_defs: # Nishita sky if 'vec3 sunDir' in frag.uniforms: func_cloud_radiance += '\tvec3 sun_dir = sunDir;\n' # Hosek else: func_cloud_radiance += '\tvec3 sun_dir = hosekSunDirection;\n' else: func_cloud_radiance += '\tvec3 sun_dir = vec3(0, 0, -1);\n' func_cloud_radiance += '''\tconst int steps = 8; \tfloat step_size = 0.5 / float(steps); \tfloat d = 0.0; \tp += sun_dir * step_size; \tfor(int i = 0; i < steps; ++i) { \t\td += sampleCloudDensity(p + sun_dir * float(i) * step_size); \t} \treturn 1.0 - d; }''' frag.add_function(func_cloud_radiance) func_trace_clouds = '''vec3 traceClouds(vec3 sky, vec3 dir) { \tconst float step_size = 0.5 / float(cloudsSteps); \tfloat T = 1.0; \tfloat C = 0.0; \tvec2 uv = dir.xy / dir.z * 0.4 * cloudsLower + cloudsWind * time * 0.02; \tfor (int i = 0; i < cloudsSteps; ++i) { \t\tfloat h = float(i) / float(cloudsSteps); \t\tvec3 p = vec3(uv * 0.04, h); \t\tfloat d = sampleCloudDensity(p); \t\tif (d > 0) { \t\t\t// float radiance = cloudRadiance(p, dir); \t\t\tC += T * exp(h) * d * step_size * 0.6 * cloudsPrecipitation; \t\t\tT *= exp(-d * step_size); \t\t\tif (T < 0.01) break; \t\t} \t\tuv += (dir.xy / dir.z) * step_size * cloudsUpper; \t} ''' if world.arm_darken_clouds: func_trace_clouds += '\t// Darken clouds when the sun is low\n' # Nishita sky if 'vec3 sunDir' in frag.uniforms: func_trace_clouds += '\tC *= smoothstep(-0.02, 0.25, sunDir.z);\n' # Hosek else: func_trace_clouds += '\tC *= smoothstep(0.04, 0.32, hosekSunDirection.z);\n' func_trace_clouds += '\treturn vec3(C) + sky * T;\n}' frag.add_function(func_trace_clouds)
def make_vert(self): self.data[ 'vertex_shader'] = self.matname + '_' + self.data['name'] + '.vert' self.vert = Shader(self, 'vert') return self.vert
def parse(self, frag: Shader, vert: Shader) -> str: if self.input_type == "uniform": frag.add_uniform(f'{self.variable_type} {self.variable_name}', link=self.variable_name) vert.add_uniform(f'{self.variable_type} {self.variable_name}', link=self.variable_name) if self.variable_type == "sampler2D": frag.add_uniform('vec2 screenSize', link='_screenSize') return f'texture({self.variable_name}, gl_FragCoord.xy / screenSize).rgb' return self.variable_name else: if self.input_source == "frag": frag.add_in(f'{self.variable_type} {self.variable_name}') return self.variable_name # Reroute input from vertex shader to fragment shader (input must exist!) else: vert.add_out(f'{self.variable_type} out_{self.variable_name}') frag.add_in(f'{self.variable_type} out_{self.variable_name}') vert.write(f'out_{self.variable_name} = {self.variable_name};') return 'out_' + self.variable_name
def make_frag(self): self.data['fragment_shader'] = self.matname + '_' + self.data[ 'name'] + '.frag' self.frag = Shader(self, 'frag') return self.frag