"""GRASS CUTTER crew remaster, stage 1: a clean unwrap and a clean colour carry onto the game's own crew meshes. The game's SM_Crew_.fbx (and SM_Dir_Boss / SM_Dir_Assistant) are imported as they are: rig, weights, part names and vertex positions are kept untouched. Only the body skin (CrewBody / DirBody) gets a new UV map: * smart-project charts, their saw-tooth edges smoothed and their crumbs merged into neighbours, then each chart opened out by minimum stretch along those seams, self-overlapping charts split in two, the head given more texels, and everything packed with a real margin (no strips of hundreds of fragments); The colour is then carried from the Tripo source shell (ArtSource/Crew/.glb or ArtSource/Director/.glb): * the arms are swung back up into the T-pose by inverting gc_tripo_crew.lower_arms with the mesh's own Arm/Fore weights, so every texel has its exact place on the source; * each texel looks along its own normal for the nearest FRONT-facing source surface within a few millimetres (never a neighbouring part, never extrapolated past its triangle's edge), and reads the source map at the nearest texel that is inside the source triangle (no bilinear pick-up of the source's own gutters); * the old eyes/brows are painted out as before (gc_crew_face.repaint). An ambient-occlusion map of the skin in its rest pose is baked as well, for stage 2 (crew_repaint.py). Output: /_stage1.blend and /_maps.npz. Run: blender -b --factory-startup --python crew_rebake.py --python-exit-code 1 -- [hank lin ...] """ import sys, os, math, time HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.normpath(os.path.join(HERE, "..", "..", "..", "..", "..")) sys.path.insert(0, os.path.join(ROOT, "ArtSource", "Blender", "scripts")) sys.path.insert(0, HERE) import bpy, bmesh import numpy as np from mathutils import Vector, Matrix from mathutils.bvhtree import BVHTree import gc_tripo_crew as TC import gc_crew_face as FACE import common CREW = ("hank", "otis", "lin", "rustam", "marcus", "gus", "wade", "kenji") DIRECTOR = ("boss", "assistant") MAP = 2048 ANGLE = 66 # smart-project angle limit MIN_FACES = 60 # charts smaller than this are merged into a neighbour HEAD_GAIN = 1.3 # linear texel-density gain for the head charts MARGIN = 0.0075 # pack margin (fraction of the map): ~15 px between charts EDGE_PX = 1.25 # texels up to this far outside a triangle still take its (edge-clamped) colour OUTER = 0.004 # source units a visible face may lie outside the game skin SEARCH = 0.012 # how far (source units) outside and inside the skin the source surface is looked for def sm_name(n): return ("SM_Dir_" if n in DIRECTOR else "SM_Crew_") + n.capitalize() def body_name(n): return "DirBody" if n in DIRECTOR else "CrewBody" # ------------------------------------------------------------------------------------------------ the source def load_source(name): """The carved source shell exactly as gc_tripo_crew / gc_director made it (before the remesh), and F, J.""" if name in DIRECTOR: import gc_director as GD TC.SOURCE = os.path.join(ROOT, "ArtSource", "Director") o = TC.load(name) F = None if name in GD.MOVING_EYES: FACE._photo = GD._windowed(name) F = FACE.measure(o) FACE._photo = GD._photo kept = GD.keep_glasses(o, name) FACE.carve(o, F) for i, c in kept.items(): o.data.vertices[i].co = c else: TC.SOURCE = os.path.join(ROOT, "ArtSource", "Crew") o = TC.load(name) F = FACE.measure(o) FACE.carve(o, F) bm = bmesh.new() bm.from_mesh(o.data) bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=1e-5) bm.to_mesh(o.data) bm.free() o.name = "Source" J = TC.measure(o) return o, F, J # ------------------------------------------------------------------------------------------------ the game mesh def import_game(name): path = os.path.join(ROOT, "Assets", "Art", "Models", sm_name(name) + ".fbx") before = set(bpy.data.objects) bpy.ops.import_scene.fbx(filepath=path) new = [o for o in bpy.data.objects if o not in before] body = next(o for o in new if o.type == "MESH" and o.name.startswith(body_name(name))) rig = next(o for o in new if o.type == "ARMATURE") return body, rig, new def tpose(body, rig, J): """Source-unit T-pose position of every vertex of the game skin: lower_arms undone, the scale k taken off.""" me = body.data n = len(me.vertices) co = np.zeros(n * 3, np.float32) me.vertices.foreach_get("co", co) co = co.reshape(-1, 3).astype(np.float64) co = (np.array(body.matrix_world) @ np.c_[co, np.ones(n)].T).T[:, :3] k_j = TC.SHOULDER / J["arm_z"] piv = {s: np.array(rig.matrix_world @ rig.data.bones["Arm_" + s].head_local) for s in "LR"} k = piv["L"][0] / 0.135 print(f" k from the source {k_j:.4f}, from the rig {k:.4f}", flush=True) gi = {g.name: g.index for g in body.vertex_groups} w = {s: np.zeros(n) for s in "LR"} for v in me.vertices: for g in v.groups: for s in "LR": if g.group in (gi.get("Arm_" + s), gi.get("Fore_" + s)): w[s][v.index] += g.weight out = co.copy() for s, sx in (("L", 1), ("R", -1)): R = np.array(Matrix.Rotation(math.radians(sx * TC.HANG), 3, "Y")) m = w[s] > 1e-6 for i in np.nonzero(m)[0]: M = (1 - w[s][i]) * np.eye(3) + w[s][i] * R out[i] = piv[s] + np.linalg.solve(M, co[i] - piv[s]) return out / k, k, co, {s: piv[s] / k for s in "LR"} def normals_of(me, co): """Vertex normals of me's faces laid on the positions co.""" tmp = bpy.data.meshes.new("tmp") tmp.from_pydata([tuple(c) for c in co], [], [tuple(p.vertices) for p in me.polygons]) tmp.update() nr = np.zeros(len(co) * 3, np.float32) tmp.vertex_normals.foreach_get("vector", nr) bpy.data.meshes.remove(tmp) return nr.reshape(-1, 3).astype(np.float64) # ------------------------------------------------------------------------------------------------ the unwrap def uv_islands(bm, uvl, faces): """Face -> island id, by shared edges whose two UV corners match on both sides.""" lab, cur = {}, 0 fs = set(faces) for f0 in faces: if f0 in lab: continue lab[f0] = cur st = [f0] while st: f = st.pop() for l in f.loops: e = l.edge for l2 in e.link_loops: g = l2.face if g is f or g in lab or g not in fs: continue # l: v0->v1 in f; l2 runs the other way in g a0, a1 = l[uvl].uv, l.link_loop_next[uvl].uv b0, b1 = l2.link_loop_next[uvl].uv, l2[uvl].uv if (a0 - b0).length < 1e-6 and (a1 - b1).length < 1e-6: lab[g] = cur st.append(g) cur += 1 return lab def nbrs(f, fs): out = [] for e in f.edges: for g in e.link_faces: if g is not f and g in fs: out.append(g) return out def tidy(lab, faces): """Smooths chart borders (a face goes with two of its three neighbours) and merges crumbs into the neighbour they share most border with.""" fs = set(faces) # every face against the faces round its corners: a face whose ring mostly belongs to another chart goes with it, # which files the saw teeth of the voxel skin off the chart borders ring = {f: [g for v in f.verts for g in v.link_faces if g is not f and g in fs] for f in faces} for _ in range(25): ch = 0 for f in faces: nb = ring[f] if not nb: continue cnt = {} for g in nb: cnt[lab[g]] = cnt.get(lab[g], 0) + 1 L = max(cnt, key=cnt.get) if L != lab[f] and cnt[L] > 0.5 * len(nb) and cnt[L] > cnt.get(lab[f], 0): lab[f] = L ch += 1 if not ch: break frozen = set() for _ in range(400): members = {} for f in faces: members.setdefault(lab[f], []).append(f) small = sorted((len(m), L) for L, m in members.items() if len(m) < MIN_FACES and L not in frozen) if not small: break touched = set() for _s, L in small: if L in touched: continue border = {} for f in members[L]: for g in nbrs(f, fs): if lab[g] != L: border[lab[g]] = border.get(lab[g], 0) + 1 if not border: frozen.add(L) # an isolated piece: kept as it is continue to = max(border, key=border.get) for f in members[L]: lab[f] = to members[to] = members.get(to, []) + members[L] touched.update((L, to)) # charts must be connected pieces: split any that are not out, nid = {}, 0 for f0 in faces: if f0 in out: continue out[f0] = nid st = [f0] while st: f = st.pop() for g in nbrs(f, fs): if g not in out and lab[g] == lab[f0]: out[g] = nid st.append(g) nid += 1 return out def seams_from(bm, lab, void): for e in bm.edges: lf = e.link_faces e.seam = False if len(lf) != 2: continue a, b = lf if (a in void) != (b in void) or (a not in void and lab[a] != lab[b]): e.seam = True def raster(tri_uv, size, cb, edge_px=0.0): """Calls cb(t, gy, gx, b(n,3), d) for every triangle with the texels it covers (d: signed px distance inside).""" for t in range(len(tri_uv)): u = tri_uv[t] * size - 0.5 x0, y0 = np.floor(u.min(0) - edge_px).astype(int) x1, y1 = np.ceil(u.max(0) + edge_px).astype(int) + 1 x0, y0, x1, y1 = max(x0, 0), max(y0, 0), min(x1, size), min(y1, size) if x0 >= x1 or y0 >= y1: continue e0, e1 = u[1] - u[0], u[2] - u[0] det = e0[0] * e1[1] - e0[1] * e1[0] if abs(det) < 1e-12: continue gx, gy = np.meshgrid(np.arange(x0, x1), np.arange(y0, y1)) dx, dy = gx - u[0, 0], gy - u[0, 1] b1 = (dx * e1[1] - dy * e1[0]) / det b2 = (dy * e0[0] - dx * e0[1]) / det b0 = 1 - b1 - b2 # altitudes in px: distance of a texel inside each edge = b_i * h_i L = [np.linalg.norm(u[2] - u[1]), np.linalg.norm(u[2] - u[0]), np.linalg.norm(u[1] - u[0])] A = abs(det) h = [A / max(l, 1e-9) for l in L] d = np.minimum(np.minimum(b0 * h[0], b1 * h[1]), b2 * h[2]) ok = d > -edge_px if not ok.any(): continue b = np.stack([b0[ok], b1[ok], b2[ok]], 1) cb(t, gy[ok], gx[ok], b, d[ok]) def tri_data(me, uvname): me.calc_loop_triangles() tris = me.loop_triangles n = len(tris) tl = np.zeros(n * 3, np.int32) tris.foreach_get("loops", tl) tv = np.zeros(n * 3, np.int32) tris.foreach_get("vertices", tv) tp = np.zeros(n, np.int32) tris.foreach_get("polygon_index", tp) luv = np.zeros(len(me.loops) * 2, np.float32) me.uv_layers[uvname].data.foreach_get("uv", luv) luv = luv.reshape(-1, 2).astype(np.float64) return tl.reshape(-1, 3), tv.reshape(-1, 3), tp, luv def overlapping(me, void_idx, size=1024): """Polygon indices that share texels with another triangle (inside both).""" tl, tv, tp, luv = tri_data(me, "UVMap") mi = np.zeros(len(me.polygons), np.int32) me.polygons.foreach_get("material_index", mi) keep = mi[tp] != void_idx cnt = np.zeros((size, size), np.int32) owner = np.full((size, size), -1, np.int32) bad = set() tri_uv = luv[tl] def cb(t, gy, gx, b, d): if not keep[t]: return m = d > 0.35 gy, gx = gy[m], gx[m] cnt[gy, gx] += 1 raster(tri_uv, size, cb) def cb2(t, gy, gx, b, d): if not keep[t]: return m = d > 0.35 if (cnt[gy[m], gx[m]] > 1).any(): bad.add(int(tp[t])) raster(tri_uv, size, cb2) return bad def unwrap(body, void_idx, head_w): me = body.data old = me.uv_layers.active old.name = "UVOld" me.uv_layers.new(name="UVMap") me.uv_layers.active = me.uv_layers["UVMap"] for x in bpy.context.scene.objects: x.select_set(False) body.select_set(True) bpy.context.view_layer.objects.active = body bpy.ops.object.mode_set(mode="EDIT") bpy.ops.mesh.select_mode(type="FACE") bm = bmesh.from_edit_mesh(me) bm.faces.ensure_lookup_table() void = {f for f in bm.faces if f.material_index == void_idx} for f in bm.faces: f.select_set(f not in void) bmesh.update_edit_mesh(me) bpy.ops.uv.smart_project(angle_limit=math.radians(ANGLE), island_margin=0.0, area_weight=0.0, scale_to_bounds=False) bm = bmesh.from_edit_mesh(me) bm.faces.ensure_lookup_table() uvl = bm.loops.layers.uv["UVMap"] faces = [f for f in bm.faces if f not in void] lab0 = uv_islands(bm, uvl, faces) lab = tidy(dict(lab0), faces) print(f" charts: smart project {len(set(lab0.values()))} -> tidied {len(set(lab.values()))}", flush=True) seams_from(bm, lab, void) bmesh.update_edit_mesh(me) def open_out(): bpy.ops.mesh.select_all(action="DESELECT") bm_ = bmesh.from_edit_mesh(me) for f in bm_.faces: f.select_set(f.material_index != void_idx) bmesh.update_edit_mesh(me) bpy.ops.uv.select_all(action="SELECT") bpy.ops.uv.unwrap(method="MINIMUM_STRETCH", margin=0.0) bm_ = bmesh.from_edit_mesh(me) uvl_ = bm_.loops.layers.uv["UVMap"] # charts the solver folded or squeezed (faces with next to no room on the map: every texel of such a face # takes one colour, a blotch): opened again by angles, then conformally if that squeezes them too for method in ("ANGLE_BASED", "CONFORMAL"): flat = _collapsed(bm_, uvl_, void_idx) if not flat: break bpy.ops.mesh.select_all(action="DESELECT") for f in flat: f.select_set(True) bmesh.update_edit_mesh(me) bpy.ops.mesh.select_linked(delimit={"SEAM"}) bpy.ops.uv.select_all(action="SELECT") bpy.ops.uv.unwrap(method=method, margin=0.0) print(f" squeezed faces re-opened ({method.lower()}):", len(flat), flush=True) bm_ = bmesh.from_edit_mesh(me) uvl_ = bm_.loops.layers.uv["UVMap"] flat = _collapsed(bm_, uvl_, void_idx) if flat: fs_ = [f for f in bm_.faces if f.material_index != void_idx and f.calc_area() > 1e-9] ratio = float(np.median([abs(_uv_area(f, uvl_)) / f.calc_area() for f in fs_])) isl_ = uv_islands(bm_, uvl_, fs_) for L in {isl_[f] for f in flat}: _flatten(bm_, uvl_, [f for f, l in isl_.items() if l == L], ratio) bmesh.update_edit_mesh(me) print(" squeezed faces laid flat:", len(flat), flush=True) bpy.ops.mesh.select_all(action="DESELECT") bm_ = bmesh.from_edit_mesh(me) for f in bm_.faces: f.select_set(f.material_index != void_idx) bmesh.update_edit_mesh(me) bpy.ops.uv.select_all(action="SELECT") bpy.ops.uv.average_islands_scale() # the head gets more texels bm_ = bmesh.from_edit_mesh(me) uvl_ = bm_.loops.layers.uv["UVMap"] isl = uv_islands(bm_, uvl_, [f for f in bm_.faces if f.material_index != void_idx]) groups = {} for f, L in isl.items(): groups.setdefault(L, []).append(f) boosted = 0 for L, fs in groups.items(): hw = np.mean([head_w[v.index] for f in fs for v in f.verts]) if hw > 0.5: c = sum((l[uvl_].uv for f in fs for l in f.loops), Vector((0, 0))) / sum(len(f.loops) for f in fs) done = set() for f in fs: for l in f.loops: if l.index in done: continue done.add(l.index) l[uvl_].uv = c + (l[uvl_].uv - c) * HEAD_GAIN boosted += 1 bmesh.update_edit_mesh(me) bpy.ops.uv.select_all(action="SELECT") bpy.ops.uv.pack_islands(rotate=True, scale=True, margin_method="FRACTION", margin=MARGIN, shape_method="CONCAVE") return len(groups), boosted n, boosted = open_out() print(f" {n} charts opened out, {boosted} of them head", flush=True) # charts that lie on themselves: cut in two across their longest extent, and the whole map opened and packed again for it in range(6): bpy.ops.object.mode_set(mode="OBJECT") bad = overlapping(me, void_idx) bpy.ops.object.mode_set(mode="EDIT") print(f" pass {it}: faces lying on others: {len(bad)}", flush=True) if not bad: break bm = bmesh.from_edit_mesh(me) bm.faces.ensure_lookup_table() uvl = bm.loops.layers.uv["UVMap"] isl = uv_islands(bm, uvl, [f for f in bm.faces if f.material_index != void_idx]) hit = {isl[bm.faces[i]] for i in bad if bm.faces[i] in isl} for L in hit: fs = [f for f, l in isl.items() if l == L] P = np.array([tuple(f.calc_center_median()) for f in fs]) c = P.mean(0) _, _, vt = np.linalg.svd(P - c, full_matrices=False) ax = vt[0] side = {f: (np.dot(np.array(tuple(f.calc_center_median())) - c, ax) > 0) for f in fs} for f in fs: for e in f.edges: lf = [g for g in e.link_faces if g in side] if len(lf) == 2 and side[lf[0]] != side[lf[1]]: e.seam = True bmesh.update_edit_mesh(me) n, boosted = open_out() print(f" split {len(hit)} charts -> {n}", flush=True) # the mouth's void faces: one point in the corner bm = bmesh.from_edit_mesh(me) uvl = bm.loops.layers.uv["UVMap"] left = _collapsed(bm, uvl, void_idx) if left: # what no chart-wide solve opens: those faces cut out as charts of their own, at the map's texel density, # and the whole map packed again fs_ = [f for f in bm.faces if f.material_index != void_idx and f.calc_area() > 1e-9 and f not in set(left)] ratio = float(np.median([abs(_uv_area(f, uvl)) / f.calc_area() for f in fs_])) # each face laid out flat on its own plane, exactly its shape, at the map's density: a chart of its own for f in left: P = np.array([tuple(v.co) for v in f.verts]) c3 = P.mean(0) nrm = np.array(tuple(f.normal)) ax = P[1] - P[0] ax = ax - nrm * (ax @ nrm) ax /= max(np.linalg.norm(ax), 1e-12) ay = np.cross(nrm, ax) q = (P - c3) @ np.stack([ax, ay], 1) * np.sqrt(ratio) base = sum((l[uvl].uv for l in f.loops), Vector((0, 0))) / len(f.loops) for l, qq in zip(f.loops, q): l[uvl].uv = Vector((base[0] + qq[0] + 1e-4, base[1] + qq[1] + 1e-4)) groups = left bmesh.update_edit_mesh(me) print(f" before packing: {len(_collapsed(bm, uvl, void_idx))} squeezed", flush=True) bpy.ops.mesh.select_all(action="DESELECT") for f in bm.faces: f.select_set(f.material_index != void_idx) bmesh.update_edit_mesh(me) bpy.ops.uv.select_all(action="SELECT") bpy.ops.uv.pack_islands(rotate=True, scale=True, margin_method="FRACTION", margin=MARGIN, shape_method="CONCAVE") bm = bmesh.from_edit_mesh(me) uvl = bm.loops.layers.uv["UVMap"] print(f" squeezed faces cut out as charts of their own: {len(left)} in {len(groups)} charts", flush=True) left = _collapsed(bm, uvl, void_idx) for f in left[:6]: print(f" left: {len(f.verts)}-gon, area {f.calc_area() * 1e4:.3f} cm2, map area {_uv_area(f, uvl):.2e}", flush=True) print(f" squeezed faces left: {len(left)} ({sum(f.calc_area() for f in left) * 1e4:.1f} cm2 source)", flush=True) for f in bm.faces: if f.material_index == void_idx: for l in f.loops: l[uvl].uv = (0.0005, 0.0005) bmesh.update_edit_mesh(me) bpy.ops.object.mode_set(mode="OBJECT") def _collapsed(bm, uvl, void_idx, frac=0.08): """Faces whose map area is under frac of their chart's usual map area per unit of surface.""" fs = [f for f in bm.faces if f.material_index != void_idx and f.calc_area() > 1e-9] isl = uv_islands(bm, uvl, fs) r = {f: abs(_uv_area(f, uvl)) / f.calc_area() for f in fs} by = {} for f, L in isl.items(): by.setdefault(L, []).append(r[f]) med = {L: float(np.median(v)) for L, v in by.items()} # a chart squeezed as a whole (to a line or a point) has no usual area of its own: the map's is used glob_ = float(np.median(list(r.values()))) return [f for f in fs if r[f] < frac * max(med[isl[f]], 0.25 * glob_)] def _flatten(bm, uvl, faces, ratio): """Last resort for a chart no solver opens: its faces projected flat onto their best-fit plane, at the map's usual size, next to where they were.""" vs = list({v for f in faces for v in f.verts}) P = np.array([tuple(v.co) for v in vs]) c = P.mean(0) _, _, vt = np.linalg.svd(P - c, full_matrices=False) q = (P - c) @ vt[:2].T * np.sqrt(ratio) at = {v: q[i] for i, v in enumerate(vs)} base = np.mean([tuple(l[uvl].uv) for f in faces for l in f.loops], 0) for f in faces: for l in f.loops: l[uvl].uv = Vector((base[0] + at[l.vert][0], base[1] + at[l.vert][1])) def _uv_area(f, uvl): p = [l[uvl].uv for l in f.loops] a = 0.0 for i in range(1, len(p) - 1): a += (p[i].x - p[0].x) * (p[i + 1].y - p[0].y) - (p[i].y - p[0].y) * (p[i + 1].x - p[0].x) return a / 2 # ------------------------------------------------------------------------------------------------ the colour def carry(name, body, src, T, NT, game_co, void_idx, arm_v=None, J=None): me = body.data tl, tv, tp, luv = tri_data(me, "UVMap") mi = np.zeros(len(me.polygons), np.int32) me.polygons.foreach_get("material_index", mi) NG = normals_of(me, game_co) pos = np.zeros((MAP, MAP, 3), np.float32) nor = np.zeros((MAP, MAP, 3), np.float32) ngm = np.zeros((MAP, MAP, 3), np.float32) gpos = np.zeros((MAP, MAP, 3), np.float32) best = np.full((MAP, MAP), -1e9, np.float32) inside = np.zeros((MAP, MAP), bool) tri = np.full((MAP, MAP), -1, np.int32) armw = np.zeros((MAP, MAP), np.float32) if arm_v is None: arm_v = np.zeros(len(T)) tri_uv = luv[tl] def cb(t, gy, gx, b, d): if mi[tp[t]] == void_idx: return ok = d > best[gy, gx] gy, gx, b, d = gy[ok], gx[ok], b[ok], d[ok] best[gy, gx] = d bc = np.clip(b, 0, None) bc /= bc.sum(1, keepdims=True) vs = tv[t] pos[gy, gx] = bc @ T[vs] gpos[gy, gx] = bc @ game_co[vs] n = bc @ NT[vs] nor[gy, gx] = n / np.maximum(np.linalg.norm(n, axis=1), 1e-9)[:, None] n = bc @ NG[vs] ngm[gy, gx] = n / np.maximum(np.linalg.norm(n, axis=1), 1e-9)[:, None] tri[gy, gx] = t armw[gy, gx] = bc @ arm_v[vs] inside[gy, gx] |= d >= 0 t0 = time.time() raster(tri_uv, MAP, cb, EDGE_PX) hit = tri >= 0 print(f" rasterised: {hit.mean() * 100:.1f}% of the map covered ({time.time() - t0:.1f}s)", flush=True) # the source as triangles hi = src.data hi.calc_loop_triangles() hv = [v.co.copy() for v in hi.vertices] htv = np.array([tuple(t.vertices) for t in hi.loop_triangles]) htl = np.array([tuple(t.loops) for t in hi.loop_triangles]) bvh = BVHTree.FromPolygons(hv, [tuple(t) for t in htv], all_triangles=True) hco = np.array([tuple(c) for c in hv]) # the source without its arms (T-pose: out past the ribs, round the shoulder height): the torso's own skin, which # the torso reads from, so the side of the body under a lowered arm never takes the arm's colour tc_ = hco[htv].mean(1) if J is not None: is_arm = (np.abs(tc_[:, 0]) > J["ribs"] + 0.005) & (np.abs(tc_[:, 2] - J["arm_z"]) < 0.1) else: is_arm = np.zeros(len(htv), bool) keep_t = np.nonzero(~is_arm)[0] bvh_torso = BVHTree.FromPolygons(hv, [tuple(t) for t in htv[keep_t]], all_triangles=True) hn = np.cross(hco[htv[:, 1]] - hco[htv[:, 0]], hco[htv[:, 2]] - hco[htv[:, 0]]) hn /= np.maximum(np.linalg.norm(hn, axis=1), 1e-12)[:, None] huv = np.zeros(len(hi.loops) * 2, np.float32) hi.uv_layers.active.data.foreach_get("uv", huv) huv = huv.reshape(-1, 2).astype(np.float64) img = hi.materials[0].node_tree.nodes["Principled BSDF"].inputs["Base Color"].links[0].from_node.image sw, sh = img.size sp = np.zeros(sw * sh * 4, np.float32) img.pixels.foreach_get(sp) sp = sp.reshape(sh, sw, 4)[..., :3].copy() ys, xs = np.nonzero(hit) P = pos[ys, xs].astype(np.float64) N = nor[ys, xs].astype(np.float64) near = np.zeros((len(P), 3)) tri_s = np.zeros(len(P), np.int32) how = np.zeros(len(P), np.int8) AW = armw[ys, xs] # flat things worn on the front (badges, cards, buckles: crew_repaint.CFG "protect_front", discs in game metres seen # from the front) are read straight from the front, as the viewer sees them: the rebuilt skin smooths a buckle away G = gpos[ys, xs] NGt = ngm[ys, xs] flat = np.zeros(len(P), bool) for x, z, r in _front_discs(name): flat |= (np.hypot(G[:, 0] - x, G[:, 2] - z) < r) & (G[:, 1] < 0.02) & (NGt[:, 1] < 0.35) t0 = time.time() for i in range(len(P)): q = Vector(P[i]) n = Vector(N[i]) got = None torso_only = AW[i] < 0.3 # on the arms the sleeve's hem (its rim, standing edge-on to the skin) does not count as looking this way face_min = 0.15 if torso_only else 0.5 ray = bvh_torso.ray_cast if torso_only else bvh.ray_cast find = bvh_torso.find_nearest if torso_only else bvh.find_nearest if flat[i]: r = ray(q - Vector((0, 0.05, 0)), Vector((0, 1, 0)), 0.08) if r[0] is not None: got = r how[i] = 3 if got is None and n.length > 0.5: # from outside in: the first source face that looks the same way as this texel, closest to the skin start = q + n * SEARCH at, left, cands = start, 2 * SEARCH, [] for _ in range(4): r = ray(at, -n, left) if r[0] is None: break travelled = (r[0] - start).length # a face looking the other way is either the inside of something or one of the source's flipped # faces: it counts, but a face looking the right way within 4 mm wins over it facing = hn[keep_t[r[2]] if torso_only else r[2]] @ np.asarray(n) cands.append((abs(travelled - SEARCH) + (0.0 if facing > face_min else 0.004), r, travelled, facing > face_min)) left = 2 * SEARCH - travelled - 1e-5 at = r[0] - n * 1e-5 if left <= 0: break if cands: # what is seen from outside: the outermost source face looking this way that lies no further than # OUTER outside the game skin (the rebuilt skin is an envelope; where it bridges a gap, between a # neckerchief's flap and the strap under it, the nearest face would be the hidden one); failing # that, the face nearest the skin outer = [c_ for c_ in cands if c_[3] and c_[2] >= SEARCH - OUTER] got = (min(outer, key=lambda c_: c_[2]) if outer else min(cands, key=lambda c_: c_[0]))[1] how[i] = 1 if got is None and n.length > 0.5: # nothing within SEARCH (a smoothed elbow or shoulder lies further off the source's crumpled skin): the # source face looking this way nearest the skin along the normal, up to 3 x as far either side -- the # nearest point in space would be the inside of the sleeve or the torso next to it start = q + n * (3 * SEARCH) at, left, cands = start, 6 * SEARCH, [] for _ in range(6): r = ray(at, -n, left) if r[0] is None: break travelled = (r[0] - start).length facing = hn[keep_t[r[2]] if torso_only else r[2]] @ np.asarray(n) if facing > face_min: cands.append((abs(travelled - 3 * SEARCH), r)) left = 6 * SEARCH - travelled - 1e-5 at = r[0] - n * 1e-5 if left <= 0: break if cands: got = min(cands, key=lambda c_: c_[0])[1] how[i] = 4 if got is None: got = find(q) how[i] = 2 near[i] = got[0] tri_s[i] = keep_t[got[2]] if torso_only else got[2] print(f" carried {len(P)} texels in {time.time() - t0:.0f}s; by ray {np.mean(how == 1) * 100:.1f}%, nearest {np.mean(how == 2) * 100:.1f}%, from the front {int((how == 3).sum())}, by a longer ray {np.mean(how == 4) * 100:.1f}%", flush=True) a, b, c = hco[htv[tri_s, 0]], hco[htv[tri_s, 1]], hco[htv[tri_s, 2]] v0, v1, v2 = b - a, c - a, near - a d00, d01, d11 = (v0 * v0).sum(1), (v0 * v1).sum(1), (v1 * v1).sum(1) d20, d21 = (v2 * v0).sum(1), (v2 * v1).sum(1) den = np.maximum(d00 * d11 - d01 * d01, 1e-18) bb, bc = (d11 * d20 - d01 * d21) / den, (d00 * d21 - d01 * d20) / den ba = 1 - bb - bc B = np.clip(np.stack([ba, bb, bc], 1), 0, None) B /= np.maximum(B.sum(1, keepdims=True), 1e-12) U = htl[tri_s] uv = B[:, 0:1] * huv[U[:, 0]] + B[:, 1:2] * huv[U[:, 1]] + B[:, 2:3] * huv[U[:, 2]] # pulled toward the middle of its source triangle by up to a texel: never the source's own gutter cen = (huv[U[:, 0]] + huv[U[:, 1]] + huv[U[:, 2]]) / 3 dv = (cen - uv) * np.array([sw, sh]) dl = np.linalg.norm(dv, axis=1) uv += (dv / np.maximum(dl, 1e-9)[:, None] * np.minimum(dl, 0.9)[:, None]) / np.array([sw, sh]) ix = np.clip((uv[:, 0] * sw).astype(int), 0, sw - 1) iy = np.clip((uv[:, 1] * sh).astype(int), 0, sh - 1) col = np.zeros((MAP, MAP, 3), np.float32) col[ys, xs] = sp[iy, ix] howm = np.zeros((MAP, MAP), np.int8) howm[ys, xs] = how return dict(pos=pos, nor=nor, ngame=ngm, gpos=gpos, col=col, hit=hit, inside=inside, tri=tri, how=howm, armw=armw, poly=np.where(hit, tp[np.maximum(tri, 0)], -1).astype(np.int32)) def _front_discs(name): try: sys.path.insert(0, HERE) import crew_repaint return crew_repaint.CFG.get(name, {}).get("protect_front", []) except Exception as e: print(" (no front discs:", e, ")", flush=True) return [] def bake_ao(body, others, void_idx): """Rest-pose ambient occlusion of the skin on its own, into the new UV map.""" sc = bpy.context.scene sc.render.engine = "CYCLES" sc.cycles.device = "CPU" sc.cycles.samples = 96 w = bpy.data.worlds.new("AOWorld") sc.world = w w.light_settings.distance = 0.12 for o in others: o.hide_render = True img = bpy.data.images.new("AO", MAP, MAP, alpha=False, float_buffer=True) added = [] for m in body.data.materials: n = m.node_tree.nodes.new("ShaderNodeTexImage") n.image = img m.node_tree.nodes.active = n added.append((m, n)) for x in sc.objects: x.select_set(False) body.select_set(True) bpy.context.view_layer.objects.active = body sc.render.bake.margin = 0 sc.render.bake.use_clear = True t0 = time.time() bpy.ops.object.bake(type="AO", uv_layer="UVMap") print(f" AO baked in {time.time() - t0:.0f}s", flush=True) ao = np.zeros(MAP * MAP * 4, np.float32) img.pixels.foreach_get(ao) for m, n in added: m.node_tree.nodes.remove(n) bpy.data.images.remove(img) for o in others: o.hide_render = False return ao.reshape(MAP, MAP, 4)[..., 0].copy() def run(name, scratch): t0 = time.time() common.reset() print(f"=== {name}", flush=True) src, F, J = load_source(name) for x in list(bpy.data.objects): if x is not src: bpy.data.objects.remove(x) body, rig, objs = import_game(name) T, k, game_co, piv_src = tpose(body, rig, J) game_old = game_co.copy() # the game's own skin, kept for the before/after pictures old = body.copy() old.data = body.data.copy() old.name = old.data.name = body.name + "_Old" bpy.context.scene.collection.objects.link(old) # the shape fixes (crew_shape): a relaxed lower face, smoother arms that clear the torso and the strap import crew_shape as CS gnames, W = CS.read_weights(body) adj = CS.neighbours(body.data) parts = [o for o in objs if o.type == "MESH" and o.name.split(".")[0] in ("EyeBall_L", "EyeBall_R", "Lid_L", "Lid_R", "LidLow_L", "LidLow_R", "Brow_L", "Brow_R")] eye_parts = None if parts: vs, fs = [], [] for o in parts: base = len(vs) vs += [tuple(o.matrix_world @ v.co) for v in o.data.vertices] fs += [tuple(base + i for i in p.vertices) for p in o.data.polygons] eye_parts = (np.array(vs) / k, fs) T1, face_m = CS.fix_face(body, T, gnames, W, eye_parts, k, J, adj) T, P, Wn, out, arm_m = CS.fix_arms(body, gnames, W, T1, J, piv_src, k, TC.HANG, adj) faces = [tuple(p.vertices) for p in body.data.polygons] game_co, dented = CS.dent_torso(P * k, gnames, Wn, faces, T, adj) P = game_co / k # (the dented torso keeps its colour from where it was: T is not changed) vest = next((o for o in objs if o.name.split(".")[0] == "Vest"), None) if vest is not None: CS.regen_strap(vest, game_co, gnames, Wn, faces, J["arm_y"] * k) body.data.vertices.foreach_set("co", game_co.astype(np.float32).ravel()) body.data.update() CS.write_weights(body, gnames, Wn) CS.smooth_normals(body) edited = (np.abs(Wn - W).max(1) > 1e-7) | (np.linalg.norm(P * k - game_old, axis=1) > 1e-6) # how well the game skin lies on the source in the T-pose (it was rebuilt over a thickened shell: a few mm) hv = [v.co.copy() for v in src.data.vertices] bvh = BVHTree.FromPolygons(hv, [tuple(p.vertices) for p in src.data.polygons]) dist = np.array([(bvh.find_nearest(Vector(p))[0] - Vector(p)).length for p in T[::7]]) print(f" game skin to source: median {np.median(dist):.4f}, 95% {np.percentile(dist, 95):.4f}, max {dist.max():.4f} (source units)", flush=True) names = [m.name for m in body.data.materials] void_idx = names.index("M_MouthVoid") if "M_MouthVoid" in names else -99 NT = normals_of(body.data, T) gi = {g.name: g.index for g in body.vertex_groups} head_w = np.zeros(len(body.data.vertices)) for v in body.data.vertices: for g in v.groups: if g.group in (gi.get("Head"), gi.get("Top")): head_w[v.index] += g.weight unwrap(body, void_idx, head_w) ixw = {nm_: i for i, nm_ in enumerate(gnames)} arm_v = sum(Wn[:, ixw[g]] for g in CS.ARM_GROUPS if g in ixw) maps = carry(name, body, src, T, NT, game_co, void_idx, arm_v, J) if F: col_ = maps["col"] FACE.repaint(F, maps["pos"].astype(np.float64), col_, maps["hit"]) maps["col"] = col_ bpy.data.objects.remove(src) maps["ao"] = bake_ao(body, [o for o in objs if o is not body and o.type == "MESH"] + [old], void_idx) maps["k"] = np.array(k) maps["edited"] = edited maps["arm_out"] = np.array(out * k) np.savez(os.path.join(scratch, name + "_maps.npz"), **maps) bpy.ops.wm.save_as_mainfile(filepath=os.path.join(scratch, name + "_stage1.blend"), check_existing=False) print(f"=== {name} done in {time.time() - t0:.0f}s", flush=True) if __name__ == "__main__": args = sys.argv[sys.argv.index("--") + 1:] scratch = args[0] os.makedirs(scratch, exist_ok=True) for nm in (args[1:] or CREW + DIRECTOR): run(nm, scratch)