Пример #1
0
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
Пример #2
0
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)
Пример #3
0
def build_environment_texture_background(world: bpy.types.World,
                                         hdri_path: str,
                                         rotation: float = 0.0) -> None:
    world.use_nodes = True
    node_tree = world.node_tree

    environment_texture_node = node_tree.nodes.new(
        type="ShaderNodeTexEnvironment")
    environment_texture_node.image = bpy.data.images.load(hdri_path)

    mapping_node = node_tree.nodes.new(type="ShaderNodeMapping")
    if bpy.app.version >= (2, 81, 0):
        mapping_node.inputs["Rotation"].default_value = (0.0, 0.0, rotation)
    else:
        mapping_node.rotation[2] = rotation

    tex_coord_node = node_tree.nodes.new(type="ShaderNodeTexCoord")

    node_tree.links.new(tex_coord_node.outputs["Generated"],
                        mapping_node.inputs["Vector"])
    node_tree.links.new(mapping_node.outputs["Vector"],
                        environment_texture_node.inputs["Vector"])
    node_tree.links.new(environment_texture_node.outputs["Color"],
                        node_tree.nodes["Background"].inputs["Color"])

    arrange_nodes(node_tree)
Пример #4
0
def set_tex_environment(world: bpy.types.World, path: str):
    # shader node tree
    world.use_nodes = True
    bpysnt = world.node_tree # ShaderNodeTree
    bpysn_texenv = bpysnt.nodes.new(type="ShaderNodeTexEnvironment") # ShaderNodeTexEnvironment
    bpysn_texenv.image = bpy.data.images.load(path)
    bpysn_texcrd = bpysnt.nodes.new(type="ShaderNodeTexCoord")
    bpysnt.links.new(bpysn_texcrd.outputs["Generated"], bpysn_texenv.inputs["Vector"])
    bpysnt.links.new(bpysn_texenv.outputs["Color"], bpysnt.nodes["Background"].inputs["Color"])
Пример #5
0
def build_rgb_background(world: bpy.types.World,
                         rgb: Tuple[float, float, float, float] = (0.9, 0.9, 0.9, 1.0),
                         strength: float = 1.0) -> None:
    world.use_nodes = True
    node_tree = world.node_tree

    rgb_node = node_tree.nodes.new(type="ShaderNodeRGB")
    rgb_node.outputs["Color"].default_value = rgb

    node_tree.nodes["Background"].inputs["Strength"].default_value = strength

    node_tree.links.new(rgb_node.outputs["Color"], node_tree.nodes["Background"].inputs["Color"])

    arrange_nodes(node_tree)
Пример #6
0
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
        if node_surface.inputs[0].is_linked:
            color_node = node_utils.find_node_by_link(world.node_tree,
                                                      node_surface,
                                                      node_surface.inputs[0])
            parse_color(world, color_node, frag)
        else:
            world.arm_envtex_color = node_surface.inputs[0].default_value
Пример #7
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)
Пример #8
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

    # 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);')
Пример #9
0
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