"""GRASS CUTTER - remaster v2: a real geometry pass on top of remaster.py (review copies, nothing in Assets/ is touched). v1 (../../remaster/scripts/remaster.py) kept the game silhouettes and only added a 1-segment bevel, panels and a paint bake, so round things stayed 6-12 sided and boxes razor sharp. v2 keeps the v1 paint bake and output layout and replaces the geometry step, loose part by loose part: 1. classify every edge of the part: hard - dihedral >= HARD_DEG, open edges, the border of a glass/screen/decal slot -> crease 1 chamfer- a softer edge between a narrow strip and a much wider flat region (a 1-segment chamfer on a box, the rim of a big flat face) -> crease 1 soft - the rest: facets of something round (wheels, pipes, posts, handles, domes) -> smoothed 2. parts with soft edges get Catmull-Clark subdivision (1 or 2 levels, chosen from the facet angle and the size of the curve, so a big wheel gets ~32 sides and a thin stay ~12) with the hard edges creased. The cage is solved so the limit surface passes through the original vertices (no shrinking: wheels keep their radius, posts their thickness, parts that sat on each other still meet). Coplanar faces the subdivision made (cylinder lengths, flat caps, box sides) are merged back to keep the triangle count sane. 3. every remaining hard edge (box edges, creased rims, chamfers) gets a rounded 2-3 segment bevel with harden normals, falling back to gentler settings per part where a bevel would blow the part out. 4. objects the game drives by material / UV (Lamp, Fill, Glow, Glass, Screen, Display, Sign, Belt, ...) and pack geometry (M_Pack faces of the models in PACK_KEEP: the Synty rocking chair and bucket of SM_CrewCabin) are left exactly as they are. Then UVs, bake, material, FBX, blend and previews as in v1, written to ArtSource/Blender/remaster_v2/. On top: previews/compare/_3way.png game original | v1 | v2, same camera previews/closeup/_closeup.png clay + wire close-up of a round part, original | v1 | v2 Run: blender -b --factory-startup --python remaster_v2.py --python-exit-code 1 -- [names...] [--force] [--nopreview] [--compare-only] (re-render the 3-way / close-up images from the saved blends) """ import os, sys, math, json, time, traceback HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.normpath(os.path.join(HERE, "..", "..", "..", "..")) V1_DIR = os.path.join(ROOT, "ArtSource", "Blender", "remaster") V2_DIR = os.path.join(ROOT, "ArtSource", "Blender", "remaster_v2") os.environ["RM_OUT"] = V2_DIR # remaster.py reads it at import: every v1 helper now writes to v2 sys.path.insert(0, os.path.join(V1_DIR, "scripts")) import remaster as R # noqa: E402 import bpy, bmesh # noqa: E402 import numpy as np # noqa: E402 from mathutils import Vector, Matrix # noqa: E402 from mathutils.bvhtree import BVHTree # noqa: E402 from mathutils.kdtree import KDTree # noqa: E402 assert R.OUT == V2_DIR, R.OUT CLOSEOUT = os.path.join(R.PREVOUT, "closeup") log = lambda *a: print("[remaster_v2]", *a, flush=True) PILOT = ["SM_RobotMower", "SM_Windmill", "SM_Tool_Scythe", "SM_VendBeer", "SM_CrewCabin"] SYNTY = {"SM_PushMower", "SM_RiderMower", "SM_HaulTractor", "SM_WideMulcher", "SM_BalerTractor", "SM_GarageDoor"} # models with pack geometry merged in: faces of these slots are pack parts, their geometry and look stay as they are PACK_KEEP = {"SM_CrewCabin": {"M_Pack"}, "SM_SupplyWall": {"M_Pack"}} HERO = {"SM_RobotMower", "SM_Windmill", "SM_CrewCabin", "SM_TrainLoco", "SM_Reaper", "SM_Drone", "SM_Ufo"} HARD_DEG = 62.0 # dihedral at or above this is a real edge FLAT_DEG = 3.0 # below: same flat region CHAMFER_RATIO = 3.2 # soft edge whose two flat regions differ in width this much is the rim of a flat face: crease BEVEL_DEG = 38.0 # bevel limit after the subdivision (subdivided curves are well under it) # close-up of a round part per model: (object name or None, world centre or None, radius, elev, azim) CLOSEUPS = { "SM_RobotMower": ("Wheel_FL", None, 0.26, 12, 70), "SM_Windmill": ("Spin", None, 0.62, 14, -20), "SM_Tool_Scythe": (None, (0.0, -0.42, 0.02), 0.32, 30, -50), "SM_VendBeer": (None, (-0.3, -0.52, 1.6), 0.36, 12, -28), "SM_CrewCabin": (None, (2.3, -1.45, 0.75), 0.75, 14, -30), } # ---------------------------------------------------------------- analysis def face_parts(me): """Loose part id of every face of a mesh.""" find, union = _uf(len(me.polygons)) first = {} for p in me.polygons: for k in p.edge_keys: if k in first: union(first[k], p.index) else: first[k] = p.index return [find(i) for i in range(len(me.polygons))] def decoration_test(diag): """deco(o) -> test(face, sag): True when another part sits within ~1.8 sagitta in front of the face (world BVH over every mesh of the model, the face's own part ignored).""" verts, polys, owner = [], [], [] for ob in bpy.context.scene.objects: if ob.type != "MESH": continue me = ob.data pid = face_parts(me) mw = ob.matrix_world b = len(verts) verts.extend(mw @ v.co for v in me.vertices) for p in me.polygons: polys.append([b + i for i in p.vertices]) owner.append((ob.name, pid[p.index])) tree = BVHTree.FromPolygons(verts, polys, epsilon=0.0) eps = 1e-4 * diag def for_obj(o): mw = o.matrix_world n3 = mw.to_3x3().inverted().transposed() pid = face_parts(o.data) def test(f, sag): me_owner = (o.name, pid[f.index]) n = (n3 @ f.normal).normalized() c = mw @ f.calc_center_median() pts = [c] + [c + ((mw @ v.co) - c) * 0.6 for v in f.verts] dist = 1.8 * sag + 0.0005 * diag for q in pts: hit = tree.ray_cast(q + n * eps, n, dist) if hit[0] is not None and owner[hit[2]] != me_owner: return True return False return test return for_obj def _uf(n): par = list(range(n)) def find(i): while par[i] != i: par[i] = par[par[i]] i = par[i] return i def union(a, b): ra, rb = find(a), find(b) if ra != rb: par[ra] = rb return find, union def analyse(o, diag, keep_mats, deco=None): """Loose parts of o with edge classes and a subdivision level each. Returns (parts, crease) where parts = [dict(faces=[idx], level, keep, ...)] and crease = {edge index: 1.0}.""" me = o.data mats = [R.base_name(m.name) if m else "" for m in me.materials] bm = bmesh.new() bm.from_mesh(me) bm.faces.ensure_lookup_table() bm.edges.ensure_lookup_table() bm.verts.ensure_lookup_table() nf = len(bm.faces) fmat = [mats[f.material_index] if f.material_index < len(mats) else "" for f in bm.faces] fspecial = [R.is_special(m) for m in fmat] # loose parts and flat regions pfind, punion = _uf(nf) rfind, runion = _uf(nf) ang = {} for e in bm.edges: lf = e.link_faces if len(lf) == 2: a = math.degrees(e.calc_face_angle(math.pi)) ang[e.index] = a punion(lf[0].index, lf[1].index) if a < FLAT_DEG and fmat[lf[0].index] == fmat[lf[1].index]: runion(lf[0].index, lf[1].index) elif len(lf) > 2: for f in lf[1:]: punion(lf[0].index, f.index) regions = {} for f in bm.faces: regions.setdefault(rfind(f.index), set()).update(v.index for v in f.verts) co = np.array([v.co[:] for v in bm.verts]) if bm.verts else np.zeros((0, 3)) rverts = {k: co[sorted(vs)] for k, vs in regions.items()} def width(f, e): """Extent of the flat region of face f across edge e (in the face plane, perpendicular to e).""" d = (e.verts[1].co - e.verts[0].co) if d.length < 1e-9: return 0.0 perp = f.normal.cross(d).normalized() p = rverts[rfind(f.index)] @ np.array(perp[:]) return float(p.max() - p.min()) # part sizes first (a lone fold is judged against its part) psize = {} pverts = {} for f in bm.faces: pverts.setdefault(pfind(f.index), set()).update(v.index for v in f.verts) for k, vs in pverts.items(): pc = co[sorted(vs)] psize[k] = float(np.linalg.norm(pc.max(0) - pc.min(0))) crease = {} cand = [] # soft candidates: (edge, region 1, region 2, w1, w2, angle) for e in bm.edges: lf = e.link_faces if len(lf) != 2: crease[e.index] = 1.0 continue a = ang[e.index] f1, f2 = lf if fspecial[f1.index] != fspecial[f2.index] or (fspecial[f1.index] and fmat[f1.index] != fmat[f2.index]): crease[e.index] = 1.0 continue if a < FLAT_DEG: continue if a >= HARD_DEG: crease[e.index] = 1.0 continue w1, w2 = width(f1, e), width(f2, e) if max(w1, w2) > CHAMFER_RATIO * max(min(w1, w2), 1e-6): crease[e.index] = 1.0 continue cand.append((e, rfind(f1.index), rfind(f2.index), f1, f2, w1, w2, a)) # a region is a strip of a curve when soft candidates bound it on two different sides (cylinder sides, dome # wedges); a lone fold between two wide flat regions (a roof ridge, a bent plate) is not a curve: crease it redges = {} for c in cand: redges.setdefault(c[1], []).append((c[0], c[3], c[5])) redges.setdefault(c[2], []).append((c[0], c[4], c[6])) def is_strip(r): es = redges.get(r, []) if len(es) < 2: return False e0, f0, w0 = es[0] d = (e0.verts[1].co - e0.verts[0].co).normalized() perp = f0.normal.cross(d).normalized() o0 = (e0.verts[0].co + e0.verts[1].co) / 2 return any(abs(((e.verts[0].co + e.verts[1].co) / 2 - o0).dot(perp)) > 0.25 * max(w0, 1e-6) for e, _, _ in es[1:]) strip = {} soft = {} # part root -> [(angle, width mean, length)] for e, r1, r2, f1, f2, w1, w2, a in cand: for r in (r1, r2): if r not in strip: strip[r] = is_strip(r) if not (strip[r1] or strip[r2]) and max(w1, w2) > 0.15 * psize[pfind(f1.index)]: crease[e.index] = 1.0 continue soft.setdefault(pfind(f1.index), []).append((a, (w1 + w2) / 2, e.calc_length(), e, f1, f2, w1, w2)) # faces something is mounted on (a door on a tower, a plaque on a drum) must not bulge into it: their edges are # creased so they stay flat; a part that is mostly decorated stays faceted (bevel only) if deco is not None: for root in list(soft): sl = soft[root] sag = {} for a, wm, l, e, f1, f2, w1, w2 in sl: d = (e.verts[1].co - e.verts[0].co).normalized() for f in (f1, f2): perp = f.normal.cross(d) pr = [v.co.dot(perp) for v in f.verts] fw = max(pr) - min(pr) # the face's own width: a fitted curve bulges ~ w * angle / 8 sag[f.index] = max(sag.get(f.index, 0.0), fw * math.radians(a) / 8) dec = {fi for fi, sg in sag.items() if deco(bm.faces[fi], sg)} if not dec: continue area = sum(bm.faces[fi].calc_area() for fi in sag) if sum(bm.faces[fi].calc_area() for fi in dec) > 0.15 * area: for a, wm, l, e, *_ in sl: crease[e.index] = 1.0 del soft[root] continue keep = [] for item in sl: e = item[3] if item[4].index in dec or item[5].index in dec: crease[e.index] = 1.0 else: keep.append(item) if keep: soft[root] = keep else: del soft[root] soft = {k: [(a, wm, l) for a, wm, l, *_ in v] for k, v in soft.items()} groups = {} for f in bm.faces: groups.setdefault(pfind(f.index), []).append(f.index) parts = [] for root, fis in groups.items(): keep = all(fmat[i] in keep_mats for i in fis) vs = {v.index for i in fis for v in bm.faces[i].verts} pc = co[sorted(vs)] size = float(np.linalg.norm(pc.max(0) - pc.min(0))) thin = float((pc.max(0) - pc.min(0)).min()) tris = sum(len(bm.faces[i].verts) - 2 for i in fis) sl = soft.get(root, []) a75, rr = 0.0, 0.0 if sl and not keep: tot = sum(l for _, _, l in sl) acc = 0.0 for a, w, l in sorted(sl): acc += l if acc >= 0.6 * tot: a75 = a break wmean = sum(w * l for _, w, l in sl) / max(tot, 1e-9) rr = wmean / max(math.radians(a75), 1e-3) / diag # radius of the curve, relative to the model nloops = sum(len(bm.faces[i].verts) for i in fis) nhard = 0 for i in fis: for e in bm.faces[i].edges: if crease.get(e.index) and (len(e.link_faces) != 2 or ang.get(e.index, 90) >= BEVEL_DEG): nhard += 1 nhard //= 2 parts.append(dict(faces=fis, keep=keep, size=size / diag, thin=thin, tris=tris, a=a75, rr=rr, nloops=nloops, nhard=nhard)) bm.free() return parts, crease def facet_target(rr): """Facet angle (deg) a curve of relative radius rr should end up with: big curves smoother than small ones.""" return 10.0 if rr >= 0.10 else 13.0 if rr >= 0.04 else 18.0 if rr >= 0.015 else 24.0 if rr >= 0.006 else 32.0 if rr >= 0.002 else 48.0 def level_for(p, coarse=1.0): if p["keep"] or p["a"] <= 0: return 0 # a big prism with few sides (the windmill's octagonal base and gallery deck) is architecture, not a faceted # curve: the railing, door and trims follow its sides, so it stays faceted and only gets the bevels if p["a"] >= 40 and p["rr"] >= 0.08: return 0 tgt = facet_target(p["rr"]) * coarse a = p["a"] if a <= tgt * 1.15: return 0 lvl = 1 if a / 2 <= tgt * 1.15 else 2 # level 2 only for parts that show (or cost little): not for a field of small bolts if (p["size"] < 0.06 and p["tris"] > 80) or p["size"] < 0.015 or coarse >= 1.8: lvl = min(lvl, 1) return lvl # ---------------------------------------------------------------- per group objects def make_group(o, face_set, name): """A copy of o holding only the faces in face_set (same matrix, no parent, no modifiers).""" me = o.data.copy() bm = bmesh.new() bm.from_mesh(me) bm.faces.ensure_lookup_table() dead = [f for f in bm.faces if f.index not in face_set] bmesh.ops.delete(bm, geom=dead, context="FACES") loose = [v for v in bm.verts if not v.link_faces] if loose: bmesh.ops.delete(bm, geom=loose, context="VERTS") bm.to_mesh(me) bm.free() g = bpy.data.objects.new(name, me) bpy.context.scene.collection.objects.link(g) g.matrix_world = o.matrix_world.copy() return g def set_creases(g, crease_co): """Crease the edges of g whose two end points match a creased edge of the source (by position).""" me = g.data bm = bmesh.new() bm.from_mesh(me) lay = bm.edges.layers.float.get("crease_edge") or bm.edges.layers.float.new("crease_edge") n = 0 for e in bm.edges: k = _ekey(e.verts[0].co, e.verts[1].co) c = 1.0 if (k in crease_co or len(e.link_faces) != 2) else 0.0 e[lay] = c n += c > 0 bm.to_mesh(me) bm.free() return n def _ekey(a, b): ka = tuple(round(x, 6) for x in a) kb = tuple(round(x, 6) for x in b) return (ka, kb) if ka <= kb else (kb, ka) def quadify(g): """Join triangle pairs into quads before subdividing (fewer poles and pinches); positions do not change.""" me = g.data bm = bmesh.new() bm.from_mesh(me) tris = [f for f in bm.faces if len(f.verts) == 3] if tris: bmesh.ops.join_triangles(bm, faces=tris, angle_face_threshold=math.radians(30), angle_shape_threshold=math.radians(50), cmp_materials=True, cmp_uvs=True, cmp_seam=False, cmp_sharp=False, cmp_vcols=False) bm.to_mesh(me) bm.free() def subdivide_fit(g, level, iters=10): """Catmull-Clark at `level`, the cage solved so the limit surface passes through the original vertices. Returns the remaining max error relative to the part size.""" me = g.data nv = len(me.vertices) orig = np.empty(nv * 3) me.vertices.foreach_get("co", orig) orig = orig.reshape(nv, 3) m = g.modifiers.new("rm_sub", "SUBSURF") m.levels = m.render_levels = level m.quality = 3 m.use_limit_surface = True m.use_creases = True m.use_custom_normals = False m.uv_smooth = "NONE" # UVs stay inside their atlas swatch / texture island m.boundary_smooth = "PRESERVE_CORNERS" cage = orig.copy() span = max(np.ptp(orig, axis=0).max(), 1e-6) best = None dg = bpy.context.evaluated_depsgraph_get() for it in range(iters + 1): dg.update() ev = g.evaluated_get(dg).data lim = np.empty(len(ev.vertices) * 3) ev.vertices.foreach_get("co", lim) lim = lim.reshape(-1, 3)[:nv] err = orig - lim e = np.abs(err).max() / span if best is None or e < best[0]: best = (e, cage.copy()) if it == iters or e < 2e-4: break cage = cage + err me.vertices.foreach_set("co", cage.ravel()) me.update() me.vertices.foreach_set("co", best[1].ravel()) me.update() R.apply_mods(g) return best[0] def merge_flat(g): """Merge coplanar neighbours the subdivision made (along cylinders, flat caps, box sides). UV/material borders stay.""" me = g.data bm = bmesh.new() bm.from_mesh(me) bmesh.ops.dissolve_limit(bm, angle_limit=math.radians(0.6), use_dissolve_boundaries=False, verts=bm.verts[:], edges=bm.edges[:], delimit={"MATERIAL", "UV", "SEAM"}) # big n-gons (often concave: a cabinet front around a sign) are ear-clipped here, not left to the importer big = [f for f in bm.faces if len(f.verts) > 8] if big: bmesh.ops.triangulate(bm, faces=big, quad_method="BEAUTY", ngon_method="BEAUTY") bm.to_mesh(me) bm.free() # ---------------------------------------------------------------- bevel SUB_SHARE = 0.6 # share of the triangle budget the subdivided bodies may take; bevels get the rest def _set_bevel(o, cfg): o.modifiers.clear() if cfg is None: return segs, ang, width = cfg b = o.modifiers.new("rm_bevel", "BEVEL") b.width = width b.segments = segs b.limit_method = "ANGLE" b.angle_limit = math.radians(ang) b.harden_normals = False # weighted normals over the whole object afterwards b.use_clamp_overlap = True b.miter_outer = "MITER_ARC" b.profile = 0.5 def bevel_width(diag): return min(max(0.0085 * diag, 0.0015), 0.03) def bevel_options(pt, diag): """Clean bevel options of one loose part, strongest first: [(segs, cfg, tris)], (0, None, tris) last. A config is clean when no vertex leaves the part's surface or wanders off its corners (v1 _spiky).""" t0 = R.tris_of([pt], evaluated=False) dg = bpy.context.evaluated_depsgraph_get() tree = BVHTree.FromObject(pt, dg, deform=False) me = pt.data kd = KDTree(len(me.vertices)) for i, v in enumerate(me.vertices): kd.insert(v.co, i) kd.balance() d = pt.dimensions w = min(bevel_width(diag), 0.22 * max(min(d), 1e-4)) out = [] for segs in (3, 2, 1): for cfg in ((segs, BEVEL_DEG, w), (segs, BEVEL_DEG, w * 0.55)): _set_bevel(pt, cfg) if not R._spiky(pt, tree, kd, cfg[2]): out.append((segs, cfg, R.tris_of([pt]))) break pt.modifiers.clear() out.append((0, None, t0)) return out, w def importance(pt, w, diag): """How much a rounded edge on this part shows: the bevel radius it can take x its size on screen.""" w0 = bevel_width(diag) size = pt.dimensions.length / diag return (w / w0) * min(1.0, size / 0.05) def allot(table, budget): """Segments per part: importance thresholds scaled until the bevelled model fits. table: [(imp, opts)].""" for f in (1.0, 1.35, 1.8, 2.5, 3.5, 5.0, 8.0, 1e9): t3, t2, t1 = 0.75 * f, 0.30 * f, 0.08 * f pick, tot = [], 0 for imp, opts in table: want = 0 if imp is None else 3 if imp >= t3 else 2 if imp >= t2 else 1 if imp >= t1 else 0 o = next(o for o in opts if o[0] <= want) pick.append(o) tot += o[2] if tot <= budget: return pick, f, tot return pick, f, tot # ---------------------------------------------------------------- the v2 geometry pass def subdivide_object(o, diag, ana, coarse, notes, stats): """Round the soft parts of o (subdivision with creases, fitted to the original vertices); hard parts as they are.""" parts, crease = ana me = o.data crease_co = set() for ei in crease: e = me.edges[ei] crease_co.add(_ekey(me.vertices[e.vertices[0]].co, me.vertices[e.vertices[1]].co)) by = {} for p in parts: key = "keep" if p["keep"] else "L%d" % level_for(p, coarse) by.setdefault(key, set()).update(p["faces"]) stats[key] = stats.get(key, 0) + 1 groups = [] for key in sorted(by): g = make_group(o, by[key], "%s__%s" % (o.name, key)) groups.append((key, g)) for key, g in groups: if key == "keep": continue R.clear_custom_normals(g) lvl = int(key[1:]) if lvl > 0: quadify(g) set_creases(g, crease_co) err = subdivide_fit(g, lvl) if err > 0.01: notes.append("%s %s: limit fit off by %.1f%% of the part" % (o.name, key, err * 100)) merge_flat(g) R.smooth_by_angle(g, BEVEL_DEG + 2) R._join_back(o, [g for _, g in groups]) # o keeps its name, parent, transform, origin if "crease_edge" in o.data.attributes: o.data.attributes.remove(o.data.attributes["crease_edge"]) def weighted_normals(o, keep_mats): """Face-area weighted normals: big flat faces shade flat, bevels and curves take the bend. Pack faces keep theirs.""" me = o.data ms = _slot_names(o) keep_v = set() for p in me.polygons: if p.material_index < len(ms) and ms[p.material_index] in keep_mats: keep_v.update(p.vertices) vg = None if keep_v: vg = o.vertex_groups.new(name="rm_wn") vg.add([i for i in range(len(me.vertices)) if i not in keep_v], 1.0, "REPLACE") m = o.modifiers.new("rm_wn", "WEIGHTED_NORMAL") m.mode = "FACE_AREA" m.weight = 50 m.thresh = 0.01 m.keep_sharp = True if vg: m.vertex_group = vg.name R.apply_mods(o) if vg: o.vertex_groups.remove(o.vertex_groups["rm_wn"]) def est_sub(parts, coarse): n = 0 for p in parts: lvl = level_for(p, coarse) n += p["tris"] if lvl == 0 else 2 * p["nloops"] * 4 ** (lvl - 1) * 0.85 return n def budget_of(name, tris0): hero = name in HERO return int(min(tris0 * (4.5 if hero else 4.0), 40000 if hero else 30000)) def _slot_names(o): return [R.base_name(m.name) if m else "" for m in o.data.materials] def geometry_model(name, paint, untouched_tris, diag, keep_mats, notes, stats): """The v2 pass on all paint objects inside the model's triangle budget: round parts first (their level from the facet targets, coarser until the subdivided bodies fit SUB_SHARE of the budget), then rounded bevels with the segments handed out by importance until the whole fits.""" tris0 = R.tris_of(paint, evaluated=False) + untouched_tris budget = budget_of(name, tris0) - untouched_tris deco = decoration_test(diag) anas = {o.name: analyse(o, diag, keep_mats, deco(o)) for o in paint} allparts = [p for a in anas.values() for p in a[0]] steps = [1.0, 1.25, 1.5, 1.8, 2.2, 2.8, 3.5, 1e9] k = next(i for i, c in enumerate(steps) if est_sub(allparts, c) <= SUB_SHARE * budget or c > 100) backup = {o.name: o.data.copy() for o in paint} while True: coarse = steps[k] st, nn = {}, [] for o in paint: subdivide_object(o, diag, anas[o.name], coarse, nn, st) sub_tris = R.tris_of(paint, evaluated=False) splits, table, pts = {}, [], [] for o in paint: parts = R._split_loose(o) splits[o.name] = parts for pt in parts: ms = _slot_names(pt) used = {ms[p.material_index] for p in pt.data.polygons if p.material_index < len(ms)} if used and used <= keep_mats: table.append((None, [(0, None, R.tris_of([pt], evaluated=False))])) else: opts, w = bevel_options(pt, diag) table.append((importance(pt, w, diag), opts)) pts.append(pt) pick, f, tot = allot(table, budget) log(" coarse %.2f: subdivided %d (est %d), bevelled %d, budget %d, bevel scale %.2f" % (coarse, sub_tris, est_sub(allparts, coarse), tot, budget, f), st) if tot <= budget * 1.03 or k == len(steps) - 1: break # over even with the bevels cut back: subdivide coarser for o in paint: for pt in splits[o.name]: me = pt.data bpy.data.objects.remove(pt) if me.users == 0: bpy.data.meshes.remove(me) old = o.data o.data = backup[o.name].copy() o.data.name = old.name bpy.data.meshes.remove(old) k += 1 segs = {} for pt, (sg, cfg, t) in zip(pts, pick): segs[sg] = segs.get(sg, 0) + 1 if cfg is not None: _set_bevel(pt, cfg) R.apply_mods(pt) for o in paint: R._join_back(o, splits[o.name]) weighted_normals(o, keep_mats) for m in backup.values(): bpy.data.meshes.remove(m) notes.extend(nn) stats.update(st) stats["subdiv_coarse"] = coarse stats["bevel_segments"] = {str(k): v for k, v in sorted(segs.items())} stats["budget"] = budget + untouched_tris if tot > budget * 1.03: notes.append("over budget: %d tris for %d" % (tot + untouched_tris, budget + untouched_tris)) return coarse # ---------------------------------------------------------------- one model (v1 pipeline, v2 geometry) def process(name, do_preview=True): if name in SYNTY: raise RuntimeError("Synty pack model, not ours to touch") t0 = time.time() st = {"name": name, "category": R.CAT_OF.get(name), "notes": [], "version": 2} keep_mats = PACK_KEEP.get(name, set()) saved_keep = set(R.KEEP_MATS) R.KEEP_MATS |= keep_mats # pack slots keep their own material and atlas UVs (not repainted) try: return _process(name, do_preview, st, keep_mats, t0) finally: R.KEEP_MATS.clear() R.KEEP_MATS |= saved_keep def _process(name, do_preview, st, keep_mats, t0): R.reset() sc = bpy.context.scene objs = R.import_model(name) meshes = [o for o in objs if o.type == "MESH"] st["tris_before"] = R.tris_of(meshes, evaluated=False) v1s = os.path.join(V1_DIR, "stats", name + ".json") if os.path.exists(v1s): with open(v1s) as f: st["tris_v1"] = json.load(f).get("tris_after") st["objects"] = sorted(o.name for o in objs) xf_before = {o.name: (o.matrix_world.copy(), o.parent.name if o.parent else None) for o in objs} cat = R.CAT_OF.get(name, "Props") look = R.CAT_LOOK[cat] mn, mx = R.bbox(meshes) diag = max((mx - mn).length, 0.02) cam = R.make_camera(meshes) paint = [] for o in meshes: if o.name in R.UNTOUCHED_OBJ: continue mats = [R.base_name(m.name) if m else "" for m in o.data.materials] if not mats or all(R.is_special(m) for m in mats): continue paint.append(o) st["untouched"] = sorted(o.name for o in meshes if o not in paint) if not paint: raise RuntimeError("nothing paintable") for o in paint: me = o.data if len(me.uv_layers) == 0: me.uv_layers.new(name="OrigUV") me.uv_layers[0].name = "OrigUV" for l in list(me.uv_layers)[1:]: me.uv_layers.remove(l) # geometry tg = time.time() gstats = {} untouched_tris = R.tris_of([o for o in meshes if o not in paint], evaluated=False) geometry_model(name, paint, untouched_tris, diag, keep_mats, st["notes"], gstats) st["parts"] = gstats st["geo_s"] = round(time.time() - tg, 1) if not R.mesh_sane(paint): st["notes"].append("NaN vertices after geometry") st["tris_geo"] = R.tris_of(meshes, evaluated=False) log(name, "geometry %d -> %d tris" % (st["tris_before"], st["tris_geo"]), gstats, "%.0fs" % st["geo_s"]) # UVs (special slots keep their original UVs) for o in paint: me = o.data if "OrigUV" not in me.uv_layers: me.uv_layers.new(name="OrigUV", do_init=False) st["notes"].append("%s: original UVs lost" % o.name) for l in [l for l in me.uv_layers if l.name != "OrigUV"]: me.uv_layers.remove(l) pu = me.uv_layers.new(name="PaintUV", do_init=True) me.uv_layers.active = pu area = 0.0 for o in paint: mats = [R.base_name(m.name) if m else "" for m in o.data.materials] area += sum(p.area for p in o.data.polygons if not R.is_special(mats[p.material_index] if p.material_index < len(mats) else "")) saved = {} for o in paint: me = o.data lo = R.special_loops(o) ouv = me.uv_layers["OrigUV"].data puv = me.uv_layers["PaintUV"].data saved[o.name] = [(li, ouv[li].uv.copy()) for li in lo] for li in lo: puv[li].uv = (-3.0, -3.0) res = 2048 if (area > 5.0 or diag > 3.5 or st["tris_before"] > 9000) else 1024 st["texture"] = res margin = 0.006 if res == 2048 else 0.009 R.smart_uv(paint, margin) # bake (v1 paint layer) img = bpy.data.images.new("T_%s_Paint" % R.short(name), res, res, alpha=False) img.colorspace_settings.name = "sRGB" img_ms = bpy.data.images.new("T_%s_MS" % R.short(name), res // 2, res // 2, alpha=False) img_ms.colorspace_settings.name = "Non-Color" info = dict(img=img, img_ms=img_ms, diag=diag, zmin=mn.z, zmax=mx.z, ao_dist=min(max(0.06 * diag, 0.025), 0.45), edge_r=min(max(0.0045 * diag, 0.0015), 0.012)) slotnames = sorted({R.base_name(m.name) for o in paint for m in o.data.materials if m}) orig_slots = {o.name: [m for m in o.data.materials] for o in paint} st["device"] = R.gpu(sc) sc.cycles.use_denoising = False sc.render.bake.margin_type = "EXTEND" sc.render.bake.use_clear = True sc.render.bake.target = "IMAGE_TEXTURES" bpy.ops.object.select_all(action="DESELECT") for o in paint: o.select_set(True) bpy.context.view_layer.objects.active = paint[0] tb = time.time() for mode, samples, mg in (("paint", 64, 16), ("ms", 1, 8)): bk = R.build_bake_mats(slotnames, info, look, mode) for o in paint: for i, m in enumerate(orig_slots[o.name]): if m: o.data.materials[i] = bk[R.base_name(m.name)] sc.cycles.samples = samples sc.render.bake.margin = mg bpy.ops.object.bake(type="EMIT", margin=mg, use_clear=True) for m in bk.values(): bpy.data.materials.remove(m) st["bake_s"] = round(time.time() - tb, 1) for o in paint: for i, m in enumerate(orig_slots[o.name]): o.data.materials[i] = m os.makedirs(R.TEXOUT, exist_ok=True) for im in (img, img_ms): p = os.path.join(R.TEXOUT, im.name + ".png") im.filepath_raw = p im.file_format = "PNG" im.save() im.filepath = p im.source = "FILE" im.reload() # final material, UVs, slots pm = bpy.data.materials.new("M_Paint_%s" % R.short(name)) nt = pm.node_tree bs = nt.nodes.get("Principled BSDF") ti = nt.nodes.new("ShaderNodeTexImage") ti.image = img ti.location = (-600, 200) tm = nt.nodes.new("ShaderNodeTexImage") tm.image = img_ms tm.location = (-600, -150) spn = nt.nodes.new("ShaderNodeSeparateColor") spn.location = (-300, -150) nt.links.new(ti.outputs["Color"], bs.inputs["Base Color"]) nt.links.new(tm.outputs["Color"], spn.inputs[0]) nt.links.new(spn.outputs[0], bs.inputs["Metallic"]) nt.links.new(spn.outputs[1], bs.inputs["Roughness"]) for o in paint: me = o.data puv = me.uv_layers["PaintUV"].data for li, uv in saved[o.name]: puv[li].uv = uv me.uv_layers.remove(me.uv_layers["OrigUV"]) me.uv_layers["PaintUV"].name = "UVMap" old = [m for m in me.materials] newl, remap = [], [] for m in old: tgt = m if (m is not None and R.is_special(m.name)) else pm if tgt not in newl: newl.append(tgt) remap.append(newl.index(tgt)) idx = [0] * len(me.polygons) me.polygons.foreach_get("material_index", idx) idx = [remap[i] if i < len(remap) else 0 for i in idx] me.materials.clear() for m in newl: me.materials.append(m) me.polygons.foreach_set("material_index", idx) me.update() for m in list(bpy.data.materials): if m.users == 0: bpy.data.materials.remove(m) st["tris_after"] = R.tris_of(meshes, evaluated=False) st["ratio"] = round(st["tris_after"] / max(st["tris_before"], 1), 2) for o in objs: mw, p = xf_before[o.name] if max(abs(a - b) for ra, rb in zip(mw, o.matrix_world) for a, b in zip(ra, rb)) > 1e-5 or \ (o.parent.name if o.parent else None) != p: st["notes"].append("transform changed: " + o.name) os.makedirs(R.FBXOUT, exist_ok=True) bpy.ops.object.select_all(action="DESELECT") for o in sc.objects: o.select_set(o.type in ("MESH", "EMPTY")) bpy.ops.export_scene.fbx(filepath=os.path.join(R.FBXOUT, name + ".fbx"), use_selection=True, axis_forward="-Z", axis_up="Y", apply_scale_options="FBX_SCALE_ALL", bake_space_transform=False, use_mesh_modifiers=True, mesh_smooth_type="FACE", add_leaf_bones=False, object_types={"MESH", "EMPTY"}, path_mode="STRIP", use_custom_props=False) sc.render.engine = "BLENDER_EEVEE" bpy.ops.wm.save_as_mainfile(filepath=os.path.join(R.OUT, name + ".blend"), check_existing=False, relative_remap=True, compress=True) if do_preview: R.render(os.path.join(R.PREVOUT, name + ".png"), cam) st["seconds"] = round(time.time() - t0, 1) return st # ---------------------------------------------------------------- comparison images def _cam_of(name): R.reset() objs = R.import_model(name) return R.make_camera([o for o in objs if o.type == "MESH"]) def _open(path): bpy.ops.wm.open_mainfile(filepath=path) for o in list(bpy.data.objects): if o.type in ("CAMERA", "LIGHT"): bpy.data.objects.remove(o) def _load(src, name): if src == "orig": R.reset() R.import_model(name) else: _open(os.path.join(V1_DIR if src == "v1" else V2_DIR, name + ".blend")) return [o for o in bpy.context.scene.objects if o.type in ("MESH", "EMPTY")] def _stitch(paths, out, labels=None): ims = [bpy.data.images.load(p) for p in paths] w, h = ims[0].size arrs = [] for im in ims: a = np.empty(w * h * 4, dtype=np.float32) im.pixels.foreach_get(a) arrs.append(a.reshape(h, w, 4)) gap = np.ones((h, 8, 4), dtype=np.float32) gap[..., :3] = 0.15 row = [] for i, a in enumerate(arrs): if i: row.append(gap) row.append(a) pc = np.concatenate(row, axis=1) im = bpy.data.images.new("stitch", pc.shape[1], h, alpha=True) im.pixels.foreach_set(pc.ravel()) im.filepath_raw = out im.file_format = "PNG" im.save() for i in ims + [im]: bpy.data.images.remove(i) def clay_render(path, objs, cen, rad, elev, azim, res=640): """Workbench clay (studio light) with a dark wire overlay, framed on a sphere (cen, rad).""" sc = bpy.context.scene helpers = [] dg = bpy.context.evaluated_depsgraph_get() wire_t = 2.0 * rad / res * 1.1 for o in objs: if o.type != "MESH": continue o.color = (0.78, 0.76, 0.72, 1) me = bpy.data.meshes.new_from_object(o.evaluated_get(dg)) w = bpy.data.objects.new(o.name + "_wire", me) sc.collection.objects.link(w) w.matrix_world = o.matrix_world.copy() md = w.modifiers.new("wf", "WIREFRAME") md.thickness = wire_t md.use_even_offset = False md.use_relative_offset = False md.use_replace = True md.offset = 1.0 w.color = (0.06, 0.07, 0.09, 1) helpers.append(w) cd = bpy.data.cameras.new("ClayCam") cd.lens = 70 co = bpy.data.objects.new("ClayCam", cd) sc.collection.objects.link(co) helpers.append(co) d = rad / math.tan(math.atan(18 / 70)) * 1.02 el, az = math.radians(elev), math.radians(azim) cen = Vector(cen) co.location = cen + Vector((math.sin(az) * math.cos(el), -math.cos(az) * math.cos(el), math.sin(el))) * d co.rotation_euler = (cen - co.location).to_track_quat("-Z", "Y").to_euler() cd.clip_start = d * 0.01 cd.clip_end = d * 20 sc.camera = co sc.render.engine = "BLENDER_WORKBENCH" sh = sc.display.shading sh.light = "STUDIO" sh.color_type = "OBJECT" sh.show_cavity = False sh.show_shadows = False sh.show_specular_highlight = True sc.render.resolution_x = sc.render.resolution_y = res sc.render.film_transparent = False sc.world = sc.world or bpy.data.worlds.new("W") sc.world.color = (0.32, 0.34, 0.37) sc.display.render_aa = "16" sc.view_settings.view_transform = "Standard" sc.render.image_settings.file_format = "PNG" sc.render.filepath = path bpy.ops.render.render(write_still=True) for h in helpers: dd = h.data bpy.data.objects.remove(h) if isinstance(dd, bpy.types.Mesh): bpy.data.meshes.remove(dd) elif isinstance(dd, bpy.types.Camera): bpy.data.cameras.remove(dd) def compare(name): os.makedirs(R.CMPOUT, exist_ok=True) os.makedirs(CLOSEOUT, exist_ok=True) cam = _cam_of(name) shots, clays = [], [] cu = CLOSEUPS.get(name) cen = None for src in ("orig", "v1", "v2"): objs = _load(src, name) p = os.path.join(R.CMPOUT, "%s_%s.png" % (name, src)) R.render(p, cam) shots.append(p) if cu: on, c, rad, el, az = cu if cen is None: if on: o = bpy.data.objects[on] mn, mx = R.bbox([o]) cen = (mn + mx) / 2 else: cen = Vector(c) pc = os.path.join(CLOSEOUT, "%s_%s.png" % (name, src)) clay_render(pc, objs, cen, rad, el, az) clays.append(pc) _stitch(shots, os.path.join(R.CMPOUT, name + "_3way.png")) if clays: _stitch(clays, os.path.join(CLOSEOUT, name + "_closeup.png")) # ---------------------------------------------------------------- main def main(): args = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else [] force = "--force" in args nopv = "--nopreview" in args cmp_only = "--compare-only" in args names = [a for a in args if not a.startswith("--")] or PILOT for d in (R.OUT, R.TEXOUT, R.FBXOUT, R.PREVOUT, R.CMPOUT, R.STATS, CLOSEOUT): os.makedirs(d, exist_ok=True) for n in names: if n in SYNTY: log("skip (Synty pack model)", n) continue sp = os.path.join(R.STATS, n + ".json") try: if not cmp_only: if os.path.exists(sp) and not force: log("skip (done)", n) else: log("start", n) st = process(n, do_preview=not nopv) with open(sp, "w") as f: json.dump(st, f, indent=1) log("done", n, "tris %d -> v1 %s -> v2 %d" % (st["tris_before"], st.get("tris_v1"), st["tris_after"]), "%.0fs" % st["seconds"], st["notes"]) if not nopv: compare(n) except Exception: traceback.print_exc() with open(os.path.join(R.STATS, n + ".error.txt"), "w") as f: f.write(traceback.format_exc()) log("FAILED", n) if __name__ == "__main__": main()