"""GRASS CUTTER crew remaster, stage 3: puts it together. From /_stage1.blend (crew_rebake.py) and the repainted map (crew_repaint.py): ArtSource/Blender/remaster/crew/.blend the game model with the new map (old skin kept hidden in Originals) ArtSource/Blender/remaster/crew/fbx/.fbx same rig/weights/parts, new UVs on the skin (export as os_crew) ArtSource/Blender/remaster/crew/previews/_{front,34,back}.png, _compare.png (before/after), _maps.png and checks the new FBX against the game's: names, parents, transforms, bones, vertices and weights must all match. Run: blender -b --factory-startup --python crew_assemble.py --python-exit-code 1 -- [hank lin ...] """ import sys, os, math HERE = os.path.dirname(os.path.abspath(__file__)) BASE = os.path.normpath(os.path.join(HERE, "..")) ROOT = os.path.normpath(os.path.join(BASE, "..", "..", "..", "..")) import bpy import numpy as np from mathutils import Vector, Matrix CREW = ("hank", "otis", "lin", "rustam", "marcus", "gus", "wade", "kenji") DIRECTOR = ("boss", "assistant") GAME_TEX = os.path.join(ROOT, "Assets", "Art", "Textures") GAME_MODELS = os.path.join(ROOT, "Assets", "Art", "Models") RES = (600, 800) def sm_name(n): return ("SM_Dir_" if n in DIRECTOR else "SM_Crew_") + n.capitalize() def body_of(n): return bpy.data.objects["DirBody" if n in DIRECTOR else "CrewBody"] def relink_images(): """The FBX points its maps at Assets/Art/Models; they live in Assets/Art/Textures.""" for im in bpy.data.images: if im.source != "FILE": continue fn = os.path.basename(im.filepath) p = os.path.join(GAME_TEX, fn) if os.path.exists(p): im.filepath = p im.reload() def tex_node(m): return next((n for n in m.node_tree.nodes if n.type == "TEX_IMAGE"), None) def soften_materials(): for m in bpy.data.materials: if not m.node_tree: continue b = next((n for n in m.node_tree.nodes if n.type == "BSDF_PRINCIPLED"), None) if b: b.inputs["Roughness"].default_value = 0.75 if "Specular IOR Level" in b.inputs: b.inputs["Specular IOR Level"].default_value = 0.25 b.inputs["Metallic"].default_value = 0.0 if m.name != "M_Brass" else 0.6 def set_texture(m, path, uv): n = tex_node(m) if n is None: n = m.node_tree.nodes.new("ShaderNodeTexImage") b = next(x for x in m.node_tree.nodes if x.type == "BSDF_PRINCIPLED") m.node_tree.links.new(n.outputs["Color"], b.inputs["Base Color"]) n.image = bpy.data.images.load(path, check_existing=True) n.interpolation = "Linear" uvn = next((x for x in m.node_tree.nodes if x.type == "UVMAP"), None) if uvn is None: uvn = m.node_tree.nodes.new("ShaderNodeUVMap") m.node_tree.links.new(uvn.outputs["UV"], n.inputs["Vector"]) uvn.uv_map = uv def stage(scene_objs): """Soft studio light and a world, shared by the previews.""" sc = bpy.context.scene sc.render.engine = "BLENDER_EEVEE" sc.render.resolution_x, sc.render.resolution_y = RES sc.render.film_transparent = False sc.view_settings.view_transform = "Standard" sc.view_settings.look = "None" w = bpy.data.worlds.get("Studio") or bpy.data.worlds.new("Studio") sc.world = w w.use_nodes = True bg = w.node_tree.nodes["Background"] bg.inputs[0].default_value = (0.62, 0.68, 0.72, 1) bg.inputs[1].default_value = 0.9 for nm, kind, en, rot, size in (("Key", "SUN", 2.6, (52, 8, -38), 18), ("Rim", "SUN", 1.4, (35, 0, 160), 10)): if nm in bpy.data.objects: continue ld = bpy.data.lights.new(nm, kind) ld.energy = en ld.angle = math.radians(size) lo = bpy.data.objects.new(nm, ld) sc.collection.objects.link(lo) lo.rotation_euler = [math.radians(a) for a in rot] if "Fill" not in bpy.data.objects: ld = bpy.data.lights.new("Fill", "AREA") ld.energy = 120 ld.size = 3 lo = bpy.data.objects.new("Fill", ld) sc.collection.objects.link(lo) lo.location = (-2.5, -2.5, 1.6) lo.rotation_euler = (Vector((0, 0, 0.7)) - lo.location).to_track_quat("-Z", "Y").to_euler() def bounds(objs): mn, mx = Vector((1e9,) * 3), Vector((-1e9,) * 3) for o in objs: for c in o.bound_box: w = o.matrix_world @ Vector(c) mn = Vector(map(min, mn, w)) mx = Vector(map(max, mx, w)) return mn, mx def camera(objs): sc = bpy.context.scene cam = bpy.data.objects.get("PreviewCam") if cam is None: cd = bpy.data.cameras.new("PreviewCam") cd.type = "ORTHO" cam = bpy.data.objects.new("PreviewCam", cd) sc.collection.objects.link(cam) mn, mx = bounds(objs) cam.data.ortho_scale = (mx.z - mn.z) * 1.1 # the taller side of the frame sc.camera = cam return cam, (mn + mx) / 2 def aim(cam, ctr, az, el=8): a, e = math.radians(az), math.radians(el) cam.location = ctr + Vector((math.sin(a) * math.cos(e), -math.cos(a) * math.cos(e), math.sin(e))) * 6 cam.rotation_euler = (ctr - cam.location).to_track_quat("-Z", "Y").to_euler() cam.data.clip_end = 20 VIEWS = (("front", 0), ("34", -35), ("back", 180)) CLOSE = (("head", -20), ("legs", 25)) # close-ups in the comparison: the face and the trousers def render(path): bpy.context.scene.render.filepath = path bpy.ops.render.render(write_still=True) def read_png(path): im = bpy.data.images.load(path) w, h = im.size px = np.zeros(w * h * 4, np.float32) im.pixels.foreach_get(px) bpy.data.images.remove(im) return px.reshape(h, w, 4) def write_png(arr, path): h, w = arr.shape[:2] im = bpy.data.images.new("out", w, h, alpha=True) im.pixels.foreach_set(arr.astype(np.float32).ravel()) im.filepath_raw = path im.file_format = "PNG" im.save() bpy.data.images.remove(im) def label(text, cam, at): cu = bpy.data.curves.new("lbl", "FONT") cu.body = text cu.size = cam.data.ortho_scale * 0.06 cu.align_x = "LEFT" o = bpy.data.objects.new("lbl_" + text, cu) bpy.context.scene.collection.objects.link(o) m = bpy.data.materials.new("lbl") m.use_nodes = True e = m.node_tree.nodes.new("ShaderNodeEmission") e.inputs[0].default_value = (0.02, 0.02, 0.03, 1) m.node_tree.links.new(e.outputs[0], m.node_tree.nodes["Material Output"].inputs[0]) o.data.materials.append(m) o.parent = cam o.location = (-cam.data.ortho_scale * 0.5 * RES[0] / RES[1] + cam.data.ortho_scale * 0.03, cam.data.ortho_scale * 0.5 - cam.data.ortho_scale * 0.09, -1) return o def build(name, scratch): sm = sm_name(name) bpy.ops.wm.open_mainfile(filepath=os.path.join(scratch, name + "_stage1.blend")) sc = bpy.context.scene relink_images() soften_materials() body = body_of(name) rig = next(o for o in sc.objects if o.type == "ARMATURE") mat = next(m for m in body.data.materials if m.name.startswith("M_Crew_")) old_tex = os.path.join(GAME_TEX, "T_Crew_" + name.capitalize() + ".png") new_tex = os.path.join(BASE, "textures", "T_Crew_" + name.capitalize() + ".png") # the game's own skin (kept by crew_rebake before any change: its positions, weights and map), hidden in Originals old = bpy.data.objects[body.name + "_Old"] om = mat.copy() om.name = mat.name + "_Old" set_texture(om, old_tex, "UVMap") old.data.materials[[m.name for m in old.data.materials].index(mat.name)] = om col = bpy.data.collections.new("Originals") sc.collection.children.link(col) for c_ in list(old.users_collection): c_.objects.unlink(old) col.objects.link(old) old.data.uv_layers["UVMap"].active_render = True # the new skin body.data.uv_layers.remove(body.data.uv_layers["UVOld"]) body.data.uv_layers["UVMap"].active_render = True set_texture(mat, new_tex, "UVMap") # export, exactly as os_crew.export_rigged, without the old copy fbx = os.path.join(BASE, "fbx", sm + ".fbx") for o in sc.objects: o.select_set(o.type in ("MESH", "EMPTY", "ARMATURE") and o is not old) old.hide_set(False) bpy.ops.export_scene.fbx(filepath=fbx, use_selection=True, axis_forward="-Z", axis_up="Y", apply_scale_options="FBX_SCALE_ALL", bake_space_transform=False, use_mesh_modifiers=False, mesh_smooth_type="FACE", add_leaf_bones=False, object_types={"MESH", "EMPTY", "ARMATURE"}, use_armature_deform_only=False, armature_nodetype="NULL", primary_bone_axis="Y", secondary_bone_axis="X", bake_anim=False, path_mode="STRIP", use_custom_props=False) # previews stage(sc.objects) figure = [o for o in sc.objects if o.type == "MESH" and o is not old] cam, ctr = camera(figure) prv = os.path.join(BASE, "previews") os.makedirs(prv, exist_ok=True) old.hide_render = True for tag, az in VIEWS: aim(cam, ctr, az) render(os.path.join(prv, f"{sm}_{tag}.png")) # before / after: the same views with the old skin in place of the new tiles = {} mn, mx = bounds(figure) full = cam.data.ortho_scale shots = [(t, a, None) for t, a in VIEWS] + [(t, a, z) for (t, a), z in zip(CLOSE, ("head", "legs"))] for state in ("before", "after"): old.hide_render = state == "after" body.hide_render = state == "before" for tag, az, zoom in shots: if zoom == "head": cam.data.ortho_scale = (mx.z - mn.z) * 0.42 aim(cam, Vector((ctr.x, ctr.y, mx.z - (mx.z - mn.z) * 0.2)), az) elif zoom == "legs": cam.data.ortho_scale = (mx.z - mn.z) * 0.5 aim(cam, Vector((ctr.x, ctr.y, mn.z + (mx.z - mn.z) * 0.3)), az) else: cam.data.ortho_scale = full aim(cam, ctr, az) lb = label("BEFORE" if state == "before" else "AFTER", cam, None) p = os.path.join(scratch, f"{name}_{state}_{tag}.png") render(p) tiles[state, tag] = read_png(p) bpy.data.objects.remove(lb) cam.data.ortho_scale = full old.hide_render = False body.hide_render = False rows = [np.concatenate([tiles[s, t] for t, _, _ in shots], 1) for s in ("after", "before")] # images run bottom-up write_png(np.concatenate(rows, 0), os.path.join(prv, f"{sm}_compare.png")) closeups(name, sm, scratch, body, old, rig, cam) # the maps side by side (old | new), half size a = read_png(old_tex)[::2, ::2] b = read_png(new_tex)[::2, ::2] write_png(np.concatenate([a, np.ones((a.shape[0], 16, 4), np.float32), b], 1), os.path.join(prv, f"{sm}_maps.png")) # the blend: Material Preview in every 3D view, old skin hidden old.hide_set(True) old.hide_render = True col.hide_render = True lc = bpy.context.view_layer.layer_collection.children["Originals"] lc.hide_viewport = True for scr in bpy.data.screens: for area in scr.areas: if area.type == "VIEW_3D": for sp in area.spaces: if sp.type == "VIEW_3D": sp.shading.type = "MATERIAL" for im in bpy.data.images: if im.filepath and not im.packed_file: pass path = os.path.join(BASE, sm + ".blend") bpy.ops.wm.save_as_mainfile(filepath=path, check_existing=False, relative_remap=True) bpy.ops.file.make_paths_relative() bpy.ops.wm.save_mainfile() return fbx def closeups(name, sm, scratch, body, old, rig, cam): """previews/arms/_arms.png and previews/faces/_face.png: before (top) and after (bottom), clay and painted.""" sc = bpy.context.scene keep_res = (sc.render.resolution_x, sc.render.resolution_y) sc.render.resolution_x = sc.render.resolution_y = 600 clay = bpy.data.materials.get("Clay") or bpy.data.materials.new("Clay") clay.use_nodes = True b = clay.node_tree.nodes["Principled BSDF"] b.inputs["Base Color"].default_value = (0.33, 0.33, 0.35, 1) b.inputs["Roughness"].default_value = 0.55 vl = bpy.context.view_layer eyes = [o for o in sc.objects if o.name.startswith("EyeBall_")] anchor = [o for o in sc.objects if o.name.startswith("Anchor_Eye_")] if eyes or anchor: ez = sum((o.matrix_world.translation.z for o in (eyes or anchor))) / len(eyes or anchor) else: ez = rig.data.bones["Head"].head_local.z + 0.17 sets = { "arms": [("clay", 0, Vector((0, 0, 0.64)), 0.78), ("clay", 90, Vector((0.2, 0, 0.64)), 0.62), ("paint", -30, Vector((0.1, 0, 0.64)), 0.7)], "faces": [("clay", 0, Vector((0, 0, ez - 0.09)), 0.5), ("clay", -35, Vector((0, 0, ez - 0.09)), 0.5), ("paint", -35, Vector((0, 0, ez - 0.09)), 0.5)], } for kind, shots in sets.items(): rows = [] for state in ("after", "before"): old.hide_render = state == "after" body.hide_render = state == "before" tiles = [] for i, (look, az, at, scale) in enumerate(shots): vl.material_override = clay if look == "clay" else None cam.data.ortho_scale = scale aim(cam, at, az, el=6) lb = label("BEFORE" if state == "before" else "AFTER", cam, None) lb.location = (-scale * 0.47, scale * 0.41, -1) p = os.path.join(scratch, f"{name}_{kind}_{state}_{i}.png") render(p) tiles.append(read_png(p)) bpy.data.objects.remove(lb) rows.append(np.concatenate(tiles, 1)) vl.material_override = None d = os.path.join(BASE, "previews", kind) os.makedirs(d, exist_ok=True) write_png(np.concatenate(rows, 0), os.path.join(d, f"{sm}_{'arms' if kind == 'arms' else 'face'}.png")) old.hide_render = False body.hide_render = False sc.render.resolution_x, sc.render.resolution_y = keep_res # ------------------------------------------------------------------------------------------------ the check def snapshot(path): bpy.ops.wm.read_factory_settings(use_empty=True) bpy.ops.import_scene.fbx(filepath=path) S = {} for o in bpy.context.scene.objects: e = dict(type=o.type, parent=o.parent.name if o.parent else None, ptype=o.parent_type, pbone=o.parent_bone, mw=np.array(o.matrix_world)) if o.type == "MESH": me = o.data co = np.zeros(len(me.vertices) * 3) me.vertices.foreach_get("co", co) e["co"] = co.reshape(-1, 3) e["polys"] = len(me.polygons) e["mats"] = [m.name for m in me.materials] e["uvs"] = [u.name for u in me.uv_layers] gn = [g.name for g in o.vertex_groups] e["groups"] = gn W = np.zeros((len(me.vertices), max(1, len(gn)))) for v in me.vertices: for g in v.groups: W[v.index, g.group] = g.weight e["w"] = W if o.type == "ARMATURE": e["bones"] = {b.name: (np.array(b.matrix_local), b.parent.name if b.parent else None) for b in o.data.bones} S[o.name] = e return S def check(name, fbx, scratch): A = snapshot(os.path.join(GAME_MODELS, sm_name(name) + ".fbx")) B = snapshot(fbx) bad = [] # the skin vertices the shape fixes were allowed to move or re-weight (crew_rebake: arms, shoulders, lower face) edited = np.load(os.path.join(scratch, name + "_maps.npz"))["edited"] skin = "DirBody" if name in DIRECTOR else "CrewBody" note = "" if set(A) != set(B): bad.append(f"objects differ: {set(A) ^ set(B)}") for k in set(A) & set(B): a, b = A[k], B[k] for f in ("type", "parent", "ptype", "pbone"): if a[f] != b[f]: bad.append(f"{k}.{f}: {a[f]} vs {b[f]}") dm = np.abs(a["mw"] - b["mw"]).max() if dm > 1e-4: bad.append(f"{k} transform differs by {dm:.2e}") if a["type"] == "MESH": if a["co"].shape != b["co"].shape or a["polys"] != b["polys"]: bad.append(f"{k} topology {a['co'].shape}/{a['polys']} vs {b['co'].shape}/{b['polys']}") else: free = edited if (k == skin and len(edited) == len(a["co"])) else np.full(len(a["co"]), k.split(".")[0] == "Vest") dv = np.abs(a["co"] - b["co"])[~free].max(initial=0) if dv > 1e-5: bad.append(f"{k} vertices outside the edited arms/face move by {dv:.2e}") if free.any(): mv = np.linalg.norm(a["co"] - b["co"], axis=1)[free] note += f" {k}: {int(free.sum())} arm/face vertices edited (moved up to {mv.max() * 100:.1f} cm, mean {mv.mean() * 1000:.1f} mm);" if a["mats"] != b["mats"]: bad.append(f"{k} materials {a['mats']} vs {b['mats']}") if a["groups"] != b["groups"]: bad.append(f"{k} groups {a['groups']} vs {b['groups']}") elif a["w"].shape == b["w"].shape: free = edited if (k == skin and len(edited) == len(a["w"])) else np.zeros(len(a["w"]), bool) dw = np.abs(a["w"] - b["w"])[~free].max(initial=0) if dw > 2e-4: bad.append(f"{k} weights outside the edited arms differ by {dw:.2e}") tot = b["w"].sum(1) if k == skin and np.abs(tot - 1).max() > 0.01: bad.append(f"{k} new weights do not sum to 1 ({tot.min():.3f}..{tot.max():.3f})") if a["type"] == "ARMATURE": if set(a["bones"]) != set(b["bones"]): bad.append(f"bones differ {set(a['bones']) ^ set(b['bones'])}") for bn in set(a["bones"]) & set(b["bones"]): d = np.abs(a["bones"][bn][0] - b["bones"][bn][0]).max() if d > 1e-4 or a["bones"][bn][1] != b["bones"][bn][1]: bad.append(f"bone {bn} differs by {d:.2e} / parent {a['bones'][bn][1]} vs {b['bones'][bn][1]}") print(f" CHECK {sm_name(name)}: {len(A)} objects;", "same names, parents, bones, part transforms, vertex counts; " "everything outside the edited skin identical." + note if not bad else "PROBLEMS:", flush=True) for x in bad: print(" ", x, flush=True) return not bad if __name__ == "__main__": args = sys.argv[sys.argv.index("--") + 1:] scratch = args[0] ok = True for nm in (args[1:] or CREW + DIRECTOR): print(f"=== {nm}", flush=True) fbx = build(nm, scratch) ok &= check(nm, fbx, scratch) if not ok: sys.exit(1)