#!/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") 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()