File size: 8,052 Bytes
6cf51a3
 
 
 
 
 
 
0d6b007
bc88e82
d1bfda0
bc88e82
60df411
6cf51a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c65989
 
 
 
 
 
 
 
6cf51a3
06a58b9
 
6cf51a3
 
 
06a58b9
60df411
6cf51a3
0d6b007
 
6cf51a3
 
 
 
 
 
 
 
 
06a58b9
 
6cf51a3
 
 
 
 
 
 
60df411
6cf51a3
 
 
 
 
60df411
 
06a58b9
 
60df411
 
6cf51a3
 
 
 
06a58b9
 
 
 
 
 
 
1c65989
06a58b9
 
 
0d6b007
 
 
 
 
 
06a58b9
 
 
 
 
0d6b007
06a58b9
 
 
 
 
 
 
 
 
 
 
1c65989
0d6b007
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60df411
 
 
 
 
 
 
6cf51a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06a58b9
6cf51a3
 
 
06a58b9
60df411
 
 
1c65989
 
60df411
6cf51a3
1c65989
 
 
 
 
0d6b007
 
 
 
1c65989
6cf51a3
 
 
 
 
 
 
 
1c65989
6cf51a3
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
#!/usr/bin/env python3
import os
import sys
import argparse
from PIL import Image
import numpy as np

#VIEW_NAMES = ("front_left", "back_right", "front_left_overlay", "back_right_overlay")
VIEW_NAMES = ("front_left", "back_left")
#VIEW_NAMES = ("front_left_static", "back_left_static")
#VIEW_NAMES = ("front_left_static", "back_left_static", "left_side_static", "right_side_static")

def resolve_renderer_path(renderer_path):
    if not renderer_path or not os.path.exists(renderer_path):
        raise FileNotFoundError(f"Renderer directory '{renderer_path}' does not exist.")
    return os.path.abspath(renderer_path)

def parse_bg_color(bg_color):
    if bg_color is None:
        return None
    if isinstance(bg_color, str):
        cleaned = bg_color.strip().lower()
        if cleaned in ("none", "transparent", ""):
            return None
        if cleaned.startswith("(") and cleaned.endswith(")"):
            cleaned = cleaned[1:-1]
        if "," in cleaned:
            parts = [int(p.strip()) for p in cleaned.split(",")]
            return tuple(parts)
        return bg_color
    return bg_color

def create_template(
    skin_path,
    output_path,
    renderer_path,
    size="256x576",
    bg_color="black",
    show_wireframe=False,
):
    """
    Render the configured views with PyVista, then merge them into one
    horizontal image.

    :param skin_path: Path to the input skin PNG image.
    :param output_path: Destination path for the merged output template image.
    :param renderer_path: Path to differentiable_minecraft_renderer config directory (required).
    :param size: Resolution tuple (W, H) or string (e.g. "256x576"). Default is "256x576".
    :param bg_color: Background color for the output template image (default: "black"). Set to None or "transparent" for transparent background.
    :param show_wireframe: Render textured views and overlay outer layers with black
        texel grid edges. Overlay views always include a white wireframe core.
    :return: Path to generated output file.
    """
    if not os.path.exists(skin_path):
        raise FileNotFoundError(f"Skin image '{skin_path}' does not exist.")

    dmr_path = resolve_renderer_path(renderer_path)
    if dmr_path not in sys.path:
        sys.path.insert(0, dmr_path)

    from config import get_views, parse_sizes, static_offset, static_rot, walk_offset, walk_rot
    from mc_skin_utils import mc_render

    if isinstance(size, str):
        parsed = parse_sizes(size)
        target_size = parsed[0]
    elif isinstance(size, (tuple, list)) and len(size) == 2:
        target_size = (int(size[0]), int(size[1]))
    else:
        target_size = (256, 576)

    print(f"Loading skin image from: {skin_path}")
    skin_img = Image.open(skin_path).convert("RGBA")
    skin_np = np.array(skin_img)

    if skin_img.size != (64, 64):
        raise ValueError(
            f"Minecraft rendering requires a 64x64 skin, got "
            f"{skin_img.size[0]}x{skin_img.size[1]}."
        )

    # Clean semi-transparency to match build_target_img preprocessing
    alpha = skin_np[..., 3]
    semi_transparent = (alpha > 0) & (alpha < 255)
    skin_np[semi_transparent, 3] = 255

    views_config = get_views(target_size)
    missing_views = [view_name for view_name in VIEW_NAMES if view_name not in views_config]
    if missing_views:
        raise KeyError(
            f"Views missing from renderer config: {', '.join(missing_views)}. "
            f"Available views: {', '.join(views_config)}"
        )

    rendered_images = []
    render_skin_img = Image.fromarray(skin_np)
    white_core_np = np.full_like(skin_np, 255)
    # Keep the slim-skin marker so the white core uses the same arm geometry.
    if skin_np[52, 47, 3] == 0:
        white_core_np[52, 47, 3] = 0
    white_core_img = Image.fromarray(white_core_np)

    for view_name in VIEW_NAMES:
        params = views_config[view_name]
        rot_args = walk_rot if params["walk"] else static_rot
        offset_args = walk_offset if params["walk"] else static_offset
        print(f"Rendering view with PyVista: {view_name} (Size: {target_size})...")
        render_kwargs = dict(
            output_size=params["output_size"],
            cam_front=params["cam_front"],
            zoom=params["zoom"],
            look_at_y=params["look_at_y"],
            use_voxels=False,
            light=False,
            transparent_background=True,
            rot_args=rot_args,
            offset_args=offset_args,
            ortho=params.get("ortho", False),
            off_screen=True,
        )

        if "overlay" in view_name.lower():
            core_rendered = mc_render.render_skin(
                skin=white_core_img,
                core_display=params["decor_display"],
                decor_display=[],
                show_wireframe=True,
                **render_kwargs,
            )
            outer_rendered = mc_render.render_skin(
                skin=render_skin_img,
                core_display=params["core_display"],
                decor_display=params["decor_display"],
                show_wireframe=show_wireframe,
                **render_kwargs,
            )
            rendered_image = Image.alpha_composite(
                Image.fromarray(core_rendered).convert("RGBA"),
                Image.fromarray(outer_rendered).convert("RGBA"),
            )
        else:
            rendered = mc_render.render_skin(
                skin=render_skin_img,
                core_display=params["core_display"],
                decor_display=params["decor_display"],
                show_wireframe=show_wireframe,
                **render_kwargs,
            )
            rendered_image = Image.fromarray(rendered).convert("RGBA")

        rendered_images.append(rendered_image)

    widths, heights = zip(*(image.size for image in rendered_images))
    merged_img = Image.new("RGBA", (sum(widths), max(heights)))
    x_offset = 0
    for image in rendered_images:
        merged_img.paste(image, (x_offset, 0))
        x_offset += image.width

    parsed_bg = parse_bg_color(bg_color)
    if parsed_bg is not None:
        bg = Image.new("RGBA", merged_img.size, parsed_bg)
        merged_img = Image.alpha_composite(bg, merged_img)

    out_dir = os.path.dirname(os.path.abspath(output_path))
    if out_dir:
        os.makedirs(out_dir, exist_ok=True)

    merged_img.save(output_path)
    print(f"Successfully generated merged template: {output_path} (Size: {merged_img.size})")
    return output_path

def main():
    parser = argparse.ArgumentParser(
        description="Create a horizontal Minecraft reference template using PyVista."
    )
    parser.add_argument("--skin", "--skin_path", dest="skin_path", required=True, help="Path to input skin image file.")
    parser.add_argument("--output", "--output_path", dest="output_path", required=True, help="Path to save the merged output template image.")
    parser.add_argument("--renderer_path", "--renderer", dest="renderer_path", required=True, help="Path to differentiable_minecraft_renderer config directory.")
    parser.add_argument(
        "--size",
        "--resolution",
        default="512x1024",
        help="Resolution per view.",
    )
    parser.add_argument("--bg_color", "--bg-color", "--background", dest="bg_color", default="black", help="Background color for the output template image (default: black). Set to 'none' or 'transparent' for transparency.")
    parser.add_argument(
        "--wireframe",
        "--grid",
        dest="show_wireframe",
        action="store_true",
        help=(
            "Render textured PyVista views with black texel grid edges. "
            "Overlay views always include a white wireframe core."
        ),
    )

    args = parser.parse_args()
    create_template(
        skin_path=args.skin_path,
        output_path=args.output_path,
        renderer_path=args.renderer_path,
        size=args.size,
        bg_color=args.bg_color,
        show_wireframe=args.show_wireframe,
    )

if __name__ == "__main__":
    main()