"""GRASS CUTTER - the stylized, hand-painted tool kit: hand-painted albedo over real PBR metal ("mix PBR and hand paint"). Shapes follow the chunky, soft-bevelled forms of ArtSource/Blender/stylized/ref/style_telescope.png; the palette is grounded (steel, dark iron, brass, ash wood, linen) with no purple anywhere. Shared by gc_style_scythe.py and gc_style_tools.py. A tool builder makes its parts with the builders here (lofts, lathes, rounded boxes, hex bolts, octagonal poles along a path, bands, nibs, clamps, blades); the parts go to the object named by group() ("Body", "BladeA", ...). run() then, per tool: joins each group into its object and puts the object's origin on its pivot (the game frame), packs every part's own island (tubes and lathes unwrap to one rectangle each) into one UV map across the tool's objects, bakes with Cycles, from one "painter" shader per surface type (palette PAINT, shared by the whole set): T__Painted.png the albedo: a gradient between a dark and a light paint along the soft top light and the part's own up (on blades: spine light, edge darker), painted light edges where the Bevel node's normal leaves the facet normal (baked from a flat-shaded twin so every facet counts), dark creases from AO, streaks and brush strokes from noise stretched along each part, a bright ground edge on blades. Metals carry less painted light, so the real reflections do the work there. T__Mask.png URP's metallic map: metallic in RGB, smoothness in A (per surface type; worn edges and a blade's ground edge polished higher), gives every object one material M__Painted (Principled: albedo, metallic = mask R, roughness = 1 - mask A, a little of the paint as emission), exports fbx/.fbx with common.export's settings, renders previews/_*.png (EEVEE, a studio HDRI for the reflections, a soft key, a warm rim, a neutral grey backdrop, and the ViewModel hold), saves .blend (opens in Material Preview), and writes the material into ArtSource/materials_style.json (with "mask" and "paintGlow"). Writes only into ArtSource/Blender/stylized/ (and the json). Never into Assets/. Blender space: metres, Z up, Blender -Y = Unity forward, Unity +X = Blender -X. """ import bpy, bmesh, math, os, sys, random, json, time from mathutils import Vector, Matrix HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.normpath(os.path.join(HERE, "..", "..", "..")) OUT = os.path.join(ROOT, "ArtSource", "Blender", "stylized") GAME = os.path.join(ROOT, "Assets", "Art", "Models") MATJSON = os.path.join(ROOT, "ArtSource", "materials_style.json") DEG = math.radians TAU = 2 * math.pi Z = Vector((0, 0, 1)) def lin(h): h = h.lstrip("#") c = [int(h[i:i + 2], 16) / 255.0 for i in (0, 2, 4)] return tuple(((x + 0.055) / 1.055) ** 2.4 if x > 0.04045 else x / 12.92 for x in c) # ======================================================================= the shared palette (sRGB hex) # light/dark: the ends of the painted gradient (shadows are darker values of the same hue); edge: painted edge light; occ: crease colour; # st1/st2: light and dark streaks (colour, amount, (scale round the part, scale along it) in 1/m); mot: brush mottling; wn/wg: weight of # the soft top light and of the part's own gradient; e0/e1: edge mask range; er: bevel radius (m, times the tool's paint scale); ek: edge # strength; metal/smooth: the PBR mask (worn edges + edge_s smoother, a blade's ground edge strip_s). PAINT = { "wood": dict(light="#a87447", dark="#4b301d", edge="#d6a873", occ="#1f150e", st1=("#c08a58", 0.55, (70, 4)), st2=("#3a2414", 0.5, (140, 3)), mot=0.09, wn=0.58, wg=0.34, e0=0.018, e1=0.045, er=0.016, ek=0.85, metal=0.0, smooth=0.3, edge_s=0.05), "knob": dict(light="#8c5a36", dark="#36210f", edge="#c8966a", occ="#1a1009", st1=("#a26c43", 0.45, (90, 9)), st2=("#2c1a0c", 0.4, (160, 6)), mot=0.09, wn=0.7, wg=0.2, e0=0.04, e1=0.10, er=0.007, ek=0.85, metal=0.0, smooth=0.35, edge_s=0.05), "wrap": dict(light="#d8c8a4", dark="#7a6a50", edge="#f2e8d0", occ="#2e2518", st1=("#e6d8b6", 0.3, (60, 6)), st2=("#9c8a6a", 0.3, (110, 5)), mot=0.08, wn=0.72, wg=0.18, e0=0.04, e1=0.10, er=0.007, ek=0.6, metal=0.0, smooth=0.12, edge_s=0.0), "steel": dict(light="#c3c7cc", dark="#4b5058", edge="#eef0f3", occ="#1a1c20", gamma=1.6, st1=("#d6dade", 0.28, (60, 3.0)), st2=("#5e646c", 0.25, (80, 2.5)), mot=0.05, wn=0.1, wg=0.5, e0=0.035, e1=0.10, er=0.006, ek=0.55, strip="#eef1f4", line="#3c4048", metal=0.8, smooth=0.74, edge_s=0.06, strip_s=0.92), "iron": dict(light="#7c8086", dark="#2a2c30", edge="#b2b6bc", occ="#101113", st1=("#8c9096", 0.15, (40, 6)), st2=("#222428", 0.15, (50, 6)), mot=0.08, wn=0.3, wg=0.1, e0=0.035, e1=0.10, er=0.008, ek=0.6, metal=0.75, smooth=0.5, edge_s=0.12, gamma=1.4), "brass": dict(light="#b48f52", dark="#4c3820", edge="#e4c88c", occ="#1e160b", st1=("#c8a466", 0.15, (40, 6)), st2=("#3e2c16", 0.12, (50, 6)), mot=0.08, wn=0.4, wg=0.12, e0=0.035, e1=0.10, er=0.008, ek=0.6, metal=0.8, smooth=0.6, edge_s=0.12), } KEYS = list(PAINT) # ======================================================================= tool state class Tool: name = "" group = "Body" parts = [] rng = random.Random(7) T = Tool() def new_tool(name): bpy.ops.wm.read_factory_settings(use_empty=True) for c in (bpy.data.meshes, bpy.data.materials, bpy.data.objects, bpy.data.images, bpy.data.lights, bpy.data.cameras): for d in list(c): c.remove(d) T.name = name T.group = "Body" T.parts = [] T.rng = random.Random(sum(map(ord, name))) def group(name): """Parts made from now on go to the object `name`.""" T.group = name # ======================================================================= geometry kit def mesh_obj(name, bm): me = bpy.data.meshes.new(name) bm.to_mesh(me) bm.free() o = bpy.data.objects.new(name, me) bpy.context.scene.collection.objects.link(o) return o def new_bm(): bm = bmesh.new() bm.loops.layers.uv.new("UVMap") bm.loops.layers.uv.new("G") return bm def set_uv(bm, l, uv): for k in ("UVMap", "G"): l[bm.loops.layers.uv[k]].uv = uv def finish_part(name, bm, key, up=Z, edgedist=None, grads=None): """bm has UV layers UVMap and G. Adds the attributes grad (0 underneath .. 1 on top along `up`, or `grads` per vertex) and edgedist (metres to a blade's edge; 1 elsewhere), the paint slot, and files the part under the current group.""" bmesh.ops.recalc_face_normals(bm, faces=bm.faces) up = Vector(up).normalized() hs = [v.co.dot(up) for v in bm.verts] lo, hi = min(hs), max(hs) g = bm.loops.layers.uv["G"] du, dv = T.rng.uniform(0, 20), T.rng.uniform(0, 20) # no two parts carry the same strokes for f in bm.faces: f.smooth = True f.material_index = 0 for l in f.loops: l[g].uv = (l[g].uv.x + du, l[g].uv.y + dv) o = mesh_obj(name, bm) me = o.data ga = me.attributes.new("grad", "FLOAT", "POINT") ea = me.attributes.new("edgedist", "FLOAT", "POINT") for i, v in enumerate(me.vertices): ga.data[i].value = grads[i] if grads is not None else (v.co.dot(up) - lo) / max(1e-6, hi - lo) ea.data[i].value = edgedist[i] if edgedist is not None else 1.0 me.materials.append(paint_slot(key)) o["grp"] = T.group T.parts.append(o) return o def cap_face(bm, verts): """An n-gon cap with a planar unwrap of its own.""" f = bm.faces.new(verts) c = sum((v.co for v in verts), Vector()) / len(verts) n = Vector() for a, b in zip(verts, verts[1:] + verts[:1]): n += a.co.cross(b.co) n = n.normalized() if n.length > 1e-12 else Z u = (verts[0].co - c) u = (u - n * u.dot(n)).normalized() v = n.cross(u) for l in f.loops: d = l.vert.co - c set_uv(bm, l, (d.dot(u), d.dot(v))) return f def loft(name, rings, key, closed=True, cap0=False, cap1=False, up=Z, edgedist=None, cuts=(), grads=None): """A skin through rings of points (lists of equal length, or a single point = a pole). UVs: around = arc length round the ring, centred; along = mean distance between rings: one tidy island per loft, or one per piece when `cuts` (ring indices) split it.""" bm = new_bm() V = [[bm.verts.new(tuple(p)) for p in r] for r in rings] def around(r): if len(r) == 1: return [0.0] m = len(r) cum = [0.0] for j in (range(m) if closed else range(m - 1)): cum.append(cum[-1] + (Vector(r[(j + 1) % m]) - Vector(r[j])).length) P = cum[-1] return [c - P / 2 for c in cum] AR = [around(r) for r in rings] along = [0.0] for a, b in zip(rings, rings[1:]): if len(a) == 1 or len(b) == 1: p, q = (a, b) if len(a) == 1 else (b, a) d = sum((Vector(x) - Vector(p[0])).length for x in q) / len(q) else: d = sum((Vector(x) - Vector(y)).length for x, y in zip(a, b)) / len(a) along.append(along[-1] + max(d, 1e-5)) n = max(len(r) for r in rings) jn = n if closed else n - 1 starts = [0] + sorted(cuts) uvm, gl = bm.loops.layers.uv["UVMap"], bm.loops.layers.uv["G"] for i in range(len(rings) - 1): a, b = V[i], V[i + 1] k0 = max(c for c in starts if c <= i) a0 = along[k0] for j in range(jn): k = (j + 1) % n try: if len(a) == 1: f = bm.faces.new((a[0], b[k], b[j])) uvs = [(0.0, along[i]), (AR[i + 1][j + 1], along[i + 1]), (AR[i + 1][j], along[i + 1])] elif len(b) == 1: f = bm.faces.new((a[j], a[k], b[0])) uvs = [(AR[i][j], along[i]), (AR[i][j + 1], along[i]), (0.0, along[i + 1])] else: f = bm.faces.new((a[j], a[k], b[k], b[j])) uvs = [(AR[i][j], along[i]), (AR[i][j + 1], along[i]), (AR[i + 1][j + 1], along[i + 1]), (AR[i + 1][j], along[i + 1])] except ValueError: continue for l, (u_, v_) in zip(f.loops, uvs): l[gl].uv = (u_, v_) # grain space runs on unbroken l[uvm].uv = (u_ + 10.0 * starts.index(k0), v_ - a0) # the packed map restarts at each cut if cap0 and len(V[0]) > 2: cap_face(bm, list(reversed(V[0]))) if cap1 and len(V[-1]) > 2: cap_face(bm, list(V[-1])) caps = [f for f in bm.faces if len(f.verts) > 4] if caps: bmesh.ops.triangulate(bm, faces=caps, quad_method="BEAUTY", ngon_method="BEAUTY") ed = [e for r in edgedist for e in r] if edgedist is not None else None gr = [g_ for r in grads for g_ in r] if grads is not None else None return finish_part(name, bm, key, up=up, edgedist=ed, grads=gr) def frame_z(c, d): """Matrix taking local Z to direction d, origin at c.""" q = Z.rotation_difference(Vector(d).normalized()) return Matrix.Translation(Vector(c)) @ q.to_matrix().to_4x4() def lathe(name, prof, key, segs=12, frame=Matrix.Identity(4), cap0=False, cap1=False, phase=0.0, up=Z): """prof: (r, z) bottom to top; r == 0 makes a pole.""" rings = [] for r, z in prof: if r <= 1e-6: rings.append([frame @ Vector((0, 0, z))]) else: rings.append([frame @ Vector((r * math.cos(TAU * j / segs + phase), r * math.sin(TAU * j / segs + phase), z)) for j in range(segs)]) return loft(name, rings, key, cap0=cap0, cap1=cap1, up=up) def rbox(name, c, size, key, bev=0.006, segs=2, rot=Matrix.Identity(4), up=Z): """A box with every edge rounded, box-projected UVs.""" bm = new_bm() bmesh.ops.create_cube(bm, size=1.0) for v in bm.verts: v.co = Vector((v.co.x * size[0], v.co.y * size[1], v.co.z * size[2])) bmesh.ops.bevel(bm, geom=list(bm.edges) + list(bm.verts), offset=bev, segments=segs, affect="EDGES", profile=0.5) M = Matrix.Translation(Vector(c)) @ rot for v in bm.verts: v.co = M @ v.co bmesh.ops.recalc_face_normals(bm, faces=bm.faces) for f in bm.faces: n = f.normal ax = max(range(3), key=lambda i: abs(n[i])) for l in f.loops: p = l.vert.co set_uv(bm, l, [(p.y, p.z), (p.x, p.z), (p.x, p.y)][ax]) return finish_part(name, bm, key, up=up) def hexbolt(name, c, d, r=0.016, h=0.012, washer=0.021, key="iron", wkey=None): """A chunky hex head with a chamfered crown on a round washer, standing on c along d.""" F = frame_z(c, d) k = r / 0.016 lathe(name + "_washer", [(washer * 0.92, -0.003 * k), (washer, 0.0), (washer, 0.0035 * k), (washer * 0.9, 0.005 * k)], wkey or key, segs=12, frame=F, cap1=True) z0 = 0.004 * k lathe(name, [(r, z0), (r, z0 + h * 0.62), (r * 0.82, z0 + h), (r * 0.42, z0 + h * 1.08), (0.0, z0 + h * 1.1)], key, segs=6, frame=F, phase=math.pi / 6) def dome(name, c, d, r, h, key="iron", segs=10): """A round domed rivet head.""" lathe(name, [(r, -h * 0.3), (r, h * 0.2), (r * 0.8, h * 0.75), (r * 0.42, h), (0.0, h * 1.04)], key, segs=segs, frame=frame_z(c, d)) # ======================================================================= paths, octagonal poles, bands def catmull(pts, per=12): P = [Vector(p) for p in pts] P = [P[0] * 2 - P[1]] + P + [P[-1] * 2 - P[-2]] out = [] for i in range(1, len(P) - 2): p0, p1, p2, p3 = P[i - 1], P[i], P[i + 1], P[i + 2] for k in range(per): t = k / per out.append(0.5 * ((2 * p1) + (-p0 + p2) * t + (2 * p0 - 5 * p1 + 4 * p2 - p3) * t * t + (-p0 + 3 * p1 - 3 * p2 + p3) * t ** 3)) out.append(P[-2]) return out class Path: """A Catmull-Rom path, addressed by arc length s (m). frame(s): tangent T, side X, up U (`up` is the hint, world Z by default).""" def __init__(self, pts, up=Z): self.P = catmull(pts, 24) if len(pts) > 2 else [Vector(pts[0]).lerp(Vector(pts[1]), k / 24) for k in range(25)] self.L = [0.0] for a, b in zip(self.P, self.P[1:]): self.L.append(self.L[-1] + (b - a).length) self.len = self.L[-1] self.up = Vector(up) # frames: from the up hint where it is well defined all along (so poles keep a flat face on top), else parallel transported (a path # that turns through the hint, like a stirrup running down and round, would otherwise flip its section) TT = [(self.P[min(k + 1, len(self.P) - 1)] - self.P[max(k - 1, 0)]).normalized() for k in range(len(self.P))] self.hint_ok = min(t.cross(self.up).length for t in TT) > 0.3 self.X = [] if not self.hint_ok: X = TT[0].cross(self.up) if X.length < 1e-4: X = TT[0].cross(Vector((0, -1, 0))) X.normalize() for k, t in enumerate(TT): if k: X = TT[k - 1].rotation_difference(t) @ X self.X.append(X.copy()) def at(self, s): s = max(0.0, min(self.len, s)) for k in range(len(self.L) - 1): if self.L[k + 1] >= s: f = (s - self.L[k]) / max(1e-9, self.L[k + 1] - self.L[k]) return self.P[k].lerp(self.P[k + 1], f) return self.P[-1].copy() def tan(self, s): e = min(0.01, self.len * 0.01) return (self.at(s + e) - self.at(s - e)).normalized() def frame(self, s): T_ = self.tan(s) if self.hint_ok: X = T_.cross(self.up) else: k = min(range(len(self.L)), key=lambda i: abs(self.L[i] - s)) X = self.X[k] - T_ * self.X[k].dot(T_) if X.length < 1e-4: X = T_.cross(Vector((0, -1, 0))) X.normalize() U = X.cross(T_).normalized() return T_, X, U def nearest_y(self, y): k = min(range(len(self.P)), key=lambda i: abs(self.P[i].y - y)) return self.L[k] def nearest_z(self, z): k = min(range(len(self.P)), key=lambda i: abs(self.P[i].z - z)) return self.L[k] def oct_section(r, ch=0.1, sides=8, sq=1.0): """A chamfered polygon (2*sides points, counter-clockwise, a flat face on top) of apothem r; sq stretches it sideways.""" a0 = math.pi / sides Rc = r / math.cos(a0) C = [Vector((Rc * math.cos(a0 + math.pi / 2 + k * TAU / sides) * sq, Rc * math.sin(a0 + math.pi / 2 + k * TAU / sides))) for k in range(sides)] out = [] for k in range(sides): a, c, b = C[k - 1], C[k], C[(k + 1) % sides] out.append(c + (a - c) * ch) out.append(c + (b - c) * ch) return out def sweep_rings(pth, stations, ch=0.1, sides=8, sq=1.0): """[(s, radius)] -> rings of a chamfered polygon round the path.""" rings = [] for s, r in stations: c = pth.at(s) T_, X, U = pth.frame(s) rings.append([c + X * p.x + U * p.y for p in oct_section(r, ch, sides, sq)]) return rings def pole(name, pth, rf, key, n=24, cap0=False, cap1=True, cuts=None, ch=0.1, sides=8, sq=1.0, s0=0.0, s1=None): """A chunky chamfered-octagon pole along pth from s0 to s1, radius rf(t) with t 0..1 over the pole.""" s1 = pth.len if s1 is None else s1 st = [(s0 + (s1 - s0) * i / n, rf(i / n)) for i in range(n + 1)] if cuts is None: k = max(1, int((s1 - s0) / 0.5 + 0.5)) cuts = tuple(int(n * q / k) for q in range(1, k)) return loft(name, sweep_rings(pth, st, ch, sides, sq), key, cap0=cap0, cap1=cap1, cuts=cuts) def band(name, pth, s0, w, r, e, key, ch=0.004, sides=8, sq=1.0): """A chunky band round a pole at s0, w long, standing e proud of radius r, chamfered ends.""" rr = [(s0 - w / 2, r - 0.002), (s0 - w / 2, r + e * 0.55), (s0 - w / 2 + ch, r + e), (s0 + w / 2 - ch, r + e), (s0 + w / 2, r + e * 0.55), (s0 + w / 2, r - 0.002)] return loft(name, sweep_rings(pth, rr, 0.12, sides, sq), key) def tube(name, pts, rf, key, segs=10, n=None, cap0=True, cap1=True, ch=None): """A round (segs-sided) tube along points, radius rf(t).""" pth = Path(pts) n = n or max(4, int(pth.len / 0.035)) rings = [] for i in range(n + 1): s = pth.len * i / n c = pth.at(s) T_, X, U = pth.frame(s) r = rf(i / n) rx, ry = r if isinstance(r, tuple) else (r, r) rings.append([c + X * (rx * math.cos(TAU * j / segs + math.pi / segs)) + U * (ry * math.sin(TAU * j / segs + math.pi / segs)) for j in range(segs)]) return loft(name, rings, key, cap0=cap0, cap1=cap1) # ======================================================================= tool pieces def nib(tag, x, y, z_top, r=0.036, z_low=-0.105, wrap="wrap", knob="knob", ferrule="brass", stem_to=None): """A grip hanging along Z at (x, y): a chunky wooden mushroom knob, a padded wrap in three pillows, a brass ferrule, a stem up to z stem_to (into the clamp above). Centred on (x, y), so the fist closes where the game expects it.""" fr = Matrix.Translation((x, y, 0)) k = r / 0.036 zl = z_low lathe(f"knob{tag}", [(0.0, zl - 0.032 * k), (0.02 * k, zl - 0.032 * k), (0.036 * k, zl - 0.027 * k), (0.0455 * k, zl - 0.016 * k), (0.047 * k, zl - 0.003 * k), (0.042 * k, zl + 0.008 * k), (0.033 * k, zl + 0.014 * k)], knob, segs=12, frame=fr) z0, z1 = zl + 0.006, z_top - 0.07 h = z1 - z0 q = lambda f: z0 + h * f prof = [(0.033 * k, q(0.0)), (0.0385 * k, q(0.035)), (0.041 * k, q(0.1)), (0.0415 * k, q(0.27)), (0.0395 * k, q(0.31)), (0.0365 * k, q(0.335)), (0.0395 * k, q(0.36)), (0.042 * k, q(0.4)), (0.042 * k, q(0.6)), (0.0395 * k, q(0.64)), (0.0365 * k, q(0.665)), (0.0395 * k, q(0.69)), (0.0415 * k, q(0.73)), (0.041 * k, q(0.9)), (0.0385 * k, q(0.965)), (0.034 * k, q(1.0))] lathe(f"wrap{tag}", prof, wrap, segs=12, frame=fr) lathe(f"ferrule{tag}", [(0.034 * k, z1 - 0.006), (0.0395 * k, z1 - 0.002), (0.0425 * k, z1 + 0.004), (0.0425 * k, z1 + 0.021), (0.0395 * k, z1 + 0.027), (0.031 * k, z1 + 0.031), (0.029 * k, z1 + 0.031)], ferrule, segs=12, frame=fr) if stem_to is not None: lathe(f"stem{tag}", [(0.026 * k, z1 + 0.028), (0.024 * k, z1 + 0.04), (0.0235 * k, stem_to)], "iron", segs=12, frame=fr) def clamp(tag, pth, s, r, side, w=0.056, e=0.0085, key="iron", saddle_xy=None, sides=8, sq=1.0, lug=True): """A band round the pole at s, a rounded lug on the +X (side 1) or -X side with a big hex bolt, a saddle block under the pole.""" band(f"clamp{tag}", pth, s, w, r, e, key, ch=0.006, sides=sides, sq=sq) ctr = pth.at(s) X = Vector((side, 0, 0)) if lug: lug_c = ctr + X * (r * sq + 0.012) rbox(f"lug{tag}", lug_c, (0.026, 0.044, 0.042), key, bev=0.007, segs=2) hexbolt(f"bolt{tag}", lug_c + X * 0.013, X, r=0.0155, h=0.012, washer=0.02) if saddle_xy is not None: rbox(f"saddle{tag}", (saddle_xy[0], saddle_xy[1], ctr.z - r - 0.006), (0.054, 0.05, 0.016), key, bev=0.006, segs=2) def blade(name, S, E, F, z0=0.0, rw=lambda u: 0.032, rh=lambda u: 0.02, hb=lambda u: 0.005, bev=lambda w, u: min(0.035, 0.34 * w), tip=None, cuts=(), key="steel", under=0.6, cap0=True): """A blade through stations: S[i] the spine and E[i] the edge (2D, in the plane z = z0 that F maps to the world). Section across from the spine: a thick rounded rib rw wide and rh tall (under * rh below), the body hb thick each side, a ground bevel `bev` wide down to the edge. tip: a 2D point the blade closes to (a pole). Writes edgedist (m to the edge) and grad (1 along the spine, 0 at the edge).""" n = len(S) rings, ED, GR = [], [], [] for i in range(n): u = i / max(1, n - 1) s, e = Vector(S[i]), Vector(E[i]) acr = e - s w = max(1e-4, acr.length) acr.normalize() rw_ = min(rw(u), 0.42 * w) rh_, hb_, bv = rh(u), hb(u), bev(w, u) bv = min(bv, w - rw_ * 1.05) prof = [(-0.2 * rw_, 0.05 * rh_), (-0.1 * rw_, 0.6 * rh_), (0.15 * rw_, 0.94 * rh_), (0.42 * rw_, 1.0 * rh_), (0.74 * rw_, 0.74 * rh_), (1.0 * rw_, hb_ * 1.25), (w - bv, hb_), (w - bv * 0.45, hb_ * 0.5), (w, 0.0), (w - bv * 0.45, -hb_ * 0.45), (w - bv, -hb_), (1.0 * rw_, -hb_ * 1.15), (0.62 * rw_, -under * 0.75 * rh_), (0.18 * rw_, -under * rh_), (-0.12 * rw_, -under * 0.72 * rh_)] rings.append([F @ Vector((*(s + acr * a), z0 + z)) for a, z in prof]) ED.append([max(0.0, w - a) for a, z in prof]) GR.append([max(0.0, 1.0 - max(0.0, a) / w) ** 0.8 for a, z in prof]) if tip is not None: rings.append([F @ Vector((tip[0], tip[1], z0))]) ED.append([0.0]) GR.append([0.35]) return loft(name, rings, key, cap0=cap0, edgedist=ED, cuts=cuts, grads=GR) def shear_blade(name, sx, sz, S, E, z_in, t, key="steel", tip=None, cuts=()): """A scissor or shear blade lying on one side of z = 0 (sz = +1 above): a flat inner face at z_in, a chunky rounded spine at S, the outer face, a broad ground bevel down to the edge at E. t(u): thickness.""" n = len(S) rings, ED, GR = [], [], [] for i in range(n): u = i / max(1, n - 1) s, e = Vector(S[i]), Vector(E[i]) acr = e - s w = max(1e-4, acr.length) acr.normalize() th = t(u) bv = 0.5 * w sp = min(0.35 * w, 0.006) prof = [(0.0, 0.0), (0.0, 0.55 * th), (sp * 0.35, 0.9 * th), (sp, th), (w - bv, th * 0.92), (w - bv * 0.4, th * 0.45), (w, th * 0.12), (w, 0.0)] rings.append([Vector((*(s + acr * a), sz * (z_in + z))) for a, z in prof]) ED.append([max(0.0, w - a) for a, z in prof]) GR.append([max(0.0, 1.0 - a / w) ** 0.8 for a, z in prof]) if tip is not None: rings.append([Vector((tip[0], tip[1], sz * (z_in + t(1.0) * 0.4)))]) ED.append([0.0]) GR.append([0.4]) return loft(name, rings, key, cap0=True, edgedist=ED, cuts=cuts, grads=GR) def oval_ring(name, c, rx, ry, r_in, r_z, key, seg=18, rseg=8, z=0.0): """A ring round an oval centre line in the XY plane at height z: r_in across in the plane, r_z up; an octagonal section.""" rings = [] for i in range(seg + 1): a = TAU * i / seg p = Vector((c[0] + rx * math.cos(a), c[1] + ry * math.sin(a), z)) nrm = Vector((math.cos(a) / rx, math.sin(a) / ry, 0)).normalized() rings.append([p + nrm * (r_in * math.cos(TAU * j / rseg + math.pi / rseg)) + Z * (r_z * math.sin(TAU * j / rseg + math.pi / rseg)) for j in range(rseg)]) return loft(name, rings, key, cuts=(seg // 2,)) # ======================================================================= painter (bake) and final material class NB: def __init__(self, nt): self.nt = nt def n(self, typ, **kw): nd = self.nt.nodes.new(typ) for k, v in kw.items(): setattr(nd, k, v) return nd def L(self, a, b): self.nt.links.new(a, b) def _in(self, sock, v): if isinstance(v, bpy.types.NodeSocket): self.L(v, sock) else: sock.default_value = v def m(self, op, a, b=0.0, c=0.0, clamp=False): nd = self.n("ShaderNodeMath", operation=op, use_clamp=clamp) self._in(nd.inputs[0], a) self._in(nd.inputs[1], b) if len(nd.inputs) > 2: self._in(nd.inputs[2], c) return nd.outputs[0] def sstep(self, v, lo, hi): nd = self.n("ShaderNodeMapRange", interpolation_type="SMOOTHSTEP", clamp=True) self._in(nd.inputs[0], v) nd.inputs[1].default_value = lo nd.inputs[2].default_value = hi nd.inputs[3].default_value = 0.0 nd.inputs[4].default_value = 1.0 return nd.outputs[0] def vm(self, op, a, b=None, scale=None): nd = self.n("ShaderNodeVectorMath", operation=op) self._in(nd.inputs[0], a) if b is not None: self._in(nd.inputs[1], b) if scale is not None: self._in(nd.inputs["Scale"], scale) return nd.outputs["Value"] if op in ("DOT_PRODUCT", "LENGTH", "DISTANCE") else nd.outputs["Vector"] def lerp(self, a, b, f): d = self.vm("SUBTRACT", b, a) return self.vm("ADD", a, self.vm("SCALE", d, scale=f)) def noise(self, vec, scale, detail=2.0, rough=0.5, distort=0.0): nd = self.n("ShaderNodeTexNoise", noise_dimensions="3D") self._in(nd.inputs["Vector"], vec) nd.inputs["Scale"].default_value = scale nd.inputs["Detail"].default_value = detail nd.inputs["Roughness"].default_value = rough nd.inputs["Distortion"].default_value = distort return nd.outputs["Fac"] def paint_slot(key): m = bpy.data.materials.get("bake_" + key) if m is None: m = bpy.data.materials.new("bake_" + key) return m def build_painter(m, key, img, ps=1.0, mode="albedo"): """mode "albedo": the painted colour; "mask": (metallic, smoothness, 0) for T__Mask. ps: the tool's paint scale (1 for a scythe); bevel radius, AO reach and the blade's edge strip scale with it, stroke sizes too.""" P = PAINT[key] try: m.use_nodes = True except Exception: pass nt = m.node_tree nt.nodes.clear() B = NB(nt) geo = B.n("ShaderNodeNewGeometry") bev = B.n("ShaderNodeBevel", samples=8) bev.inputs["Radius"].default_value = P["er"] * ps ao = B.n("ShaderNodeAmbientOcclusion", samples=16, only_local=False) ao.inputs["Distance"].default_value = 0.045 * ps att_g = B.n("ShaderNodeAttribute", attribute_name="grad").outputs["Fac"] uvg = B.n("ShaderNodeUVMap", uv_map="G").outputs["UV"] pos = geo.outputs["Position"] # painted edges: where the rounded normal leaves the facet normal, kept off concave creases by the AO ndot = B.vm("DOT_PRODUCT", bev.outputs["Normal"], geo.outputs["True Normal"]) edge = B.sstep(B.m("SUBTRACT", 1.0, ndot), P["e0"], P["e1"]) aoF = ao.outputs["AO"] edge = B.m("MULTIPLY", edge, B.sstep(aoF, 0.6, 0.92)) # the value of the paint: the soft top light (smooth normal kept in 'nz'), the part's own gradient, brush mottling nz = B.n("ShaderNodeAttribute", attribute_name="nz").outputs["Fac"] top = B.m("MULTIPLY_ADD", nz, 0.5, 0.5) t = B.m("MULTIPLY", top, P["wn"]) t = B.m("MULTIPLY_ADD", att_g, P["wg"], t) t = B.m("ADD", t, (1 - P["wn"] - P["wg"]) * 0.5) mapb = B.n("ShaderNodeMapping") B.L(uvg, mapb.inputs["Vector"]) mapb.inputs["Scale"].default_value = (9.0 / ps, 3.5 / ps, 1.0) br = B.noise(mapb.outputs["Vector"], 1.0, detail=1.0, rough=0.4, distort=0.3) t = B.m("ADD", t, B.m("MULTIPLY", B.m("SUBTRACT", br, 0.5), P["mot"] * 2.2)) br2 = B.noise(pos, 22.0 / ps, detail=0.5, rough=0.3) t = B.m("ADD", t, B.m("MULTIPLY", B.m("SUBTRACT", br2, 0.5), P["mot"])) t = B.sstep(t, 0.04, 1.02) if P.get("gamma", 1.0) != 1.0: # mix in a perceptual space, so the middle of a long gradient reads as a mid tone t = B.m("POWER", t, P["gamma"]) col = B.lerp(lin(P["dark"]), lin(P["light"]), t) # grain / streaks along the part (G: x round the part, y along it, in metres) for (hexc, amt, (sa, sl)), lo, hi, seed in ((P["st1"], 0.56, 0.68, 0.0), (P["st2"], 0.6, 0.72, 7.3)): mp = B.n("ShaderNodeMapping") B.L(uvg, mp.inputs["Vector"]) mp.inputs["Scale"].default_value = (sa / ps ** 0.5, sl / ps, 1.0) mp.inputs["Location"].default_value = (0, 0, seed) sn = B.noise(mp.outputs["Vector"], 1.0, detail=2.0, rough=0.45, distort=0.4) col = B.lerp(col, lin(hexc), B.m("MULTIPLY", B.sstep(sn, lo, hi), amt)) # blades: a dark painted line where the bevel starts, the bright ground edge below it if "strip" in P: ed = B.n("ShaderNodeAttribute", attribute_name="edgedist").outputs["Fac"] strip = B.m("SUBTRACT", 1.0, B.sstep(ed, 0.006 * ps, 0.02 * ps)) line = B.m("SUBTRACT", 1.0, B.sstep(B.m("ABSOLUTE", B.m("SUBTRACT", ed, 0.028 * ps)), 0.002 * ps, 0.008 * ps)) col = B.lerp(col, lin(P["line"]), B.m("MULTIPLY", line, 0.7)) col = B.lerp(col, lin(P["strip"]), B.m("MULTIPLY", strip, 0.95)) ek = B.m("MULTIPLY", edge, B.m("MULTIPLY_ADD", top, P["ek"] * 0.5, P["ek"] * 0.5)) col = B.lerp(col, lin(P["edge"]), ek) occ = B.m("SUBTRACT", 1.0, B.sstep(aoF, 0.25, 0.95)) col = B.lerp(col, lin(P["occ"]), B.m("MULTIPLY", occ, 0.85)) dbg = os.environ.get("STY_DEBUG") if dbg: # STY_DEBUG=edge|occ|top: bake one mask in grey, to tune the painter col = {"edge": edge, "occ": occ, "top": top}[dbg] if mode == "mask": # smoothness: the surface's own, worn edges a little higher, soft painted variation, crevices duller; a blade's ground edge polished sm = B.m("ADD", P["smooth"], B.m("MULTIPLY", edge, P["edge_s"])) sm = B.m("ADD", sm, B.m("MULTIPLY", B.m("SUBTRACT", br, 0.5), 0.08 if P["metal"] > 0 else 0.04)) sm = B.m("SUBTRACT", sm, B.m("MULTIPLY", occ, 0.12)) if "strip_s" in P: sm = B.m("ADD", sm, B.m("MULTIPLY", strip, P["strip_s"] - P["smooth"])) sm = B.m("MINIMUM", B.m("MAXIMUM", sm, 0.0), 1.0) cm = B.n("ShaderNodeCombineXYZ") cm.inputs[0].default_value = P["metal"] B.L(sm, cm.inputs[1]) col = cm.outputs[0] em = B.n("ShaderNodeEmission") B.L(col, em.inputs["Color"]) out = B.n("ShaderNodeOutputMaterial") B.L(em.outputs[0], out.inputs["Surface"]) tex = B.n("ShaderNodeTexImage", image=img) nt.nodes.active = tex PAINT_GLOW = 0.12 # a little of the paint as emission (materials_style.json "paintGlow") def final_material(name, img, mask): """Principled: the painted albedo, metallic from the mask's R, roughness = 1 - its A, the paint glowing a little.""" m = bpy.data.materials.get(name) or bpy.data.materials.new(name) try: m.use_nodes = True except Exception: pass nt = m.node_tree nt.nodes.clear() tex = nt.nodes.new("ShaderNodeTexImage") tex.image = img tex.location = (-700, 200) mask.colorspace_settings.name = "Non-Color" mask.alpha_mode = "CHANNEL_PACKED" mk = nt.nodes.new("ShaderNodeTexImage") mk.image = mask mk.location = (-700, -150) sep = nt.nodes.new("ShaderNodeSeparateColor") sep.location = (-400, -100) nt.links.new(mk.outputs["Color"], sep.inputs[0]) inv = nt.nodes.new("ShaderNodeMath") inv.operation = "SUBTRACT" inv.inputs[0].default_value = 1.0 inv.location = (-400, -300) nt.links.new(mk.outputs["Alpha"], inv.inputs[1]) bs = nt.nodes.new("ShaderNodeBsdfPrincipled") out = nt.nodes.new("ShaderNodeOutputMaterial") out.location = (350, 0) nt.links.new(tex.outputs["Color"], bs.inputs["Base Color"]) nt.links.new(sep.outputs[0], bs.inputs["Metallic"]) nt.links.new(inv.outputs[0], bs.inputs["Roughness"]) nt.links.new(tex.outputs["Color"], bs.inputs["Emission Color"]) bs.inputs["Emission Strength"].default_value = PAINT_GLOW nt.links.new(bs.outputs[0], out.inputs["Surface"]) return m # ======================================================================= assemble, unwrap, bake def join_groups(origins): """One object per group, its origin on origins[group] (default the world origin).""" objs = [] groups = {} for o in T.parts: groups.setdefault(o["grp"], []).append(o) for g, ps in groups.items(): for o in bpy.context.scene.objects: o.select_set(False) for o in ps: o.select_set(True) bpy.context.view_layer.objects.active = ps[0] if len(ps) > 1: bpy.ops.object.join() ob = bpy.context.view_layer.objects.active ob.name = g ob.data.name = g p = Vector(origins.get(g, (0, 0, 0))) ob.data.transform(Matrix.Translation(-p)) ob.matrix_world = Matrix.Translation(p) objs.append(ob) return objs def pack_uvs(objs, margin=0.006): for o in bpy.context.scene.objects: o.select_set(False) for o in objs: me = o.data me.uv_layers.active = me.uv_layers["UVMap"] me.uv_layers["UVMap"].active_render = True o.select_set(True) bpy.context.view_layer.objects.active = objs[0] bpy.ops.object.mode_set(mode="EDIT") bpy.ops.mesh.select_all(action="SELECT") bpy.context.scene.tool_settings.use_uv_select_sync = True try: bpy.ops.uv.pack_islands(rotate=True, rotate_method="CARDINAL", margin=margin) except TypeError: bpy.ops.uv.pack_islands(rotate=True, margin=margin) bpy.ops.object.mode_set(mode="OBJECT") def finish_normals(o): me = o.data try: me.set_sharp_from_angle(angle=DEG(50)) except Exception: pass md = o.modifiers.new("wn", "WEIGHTED_NORMAL") md.keep_sharp = True md.weight = 50 bpy.context.view_layer.objects.active = o bpy.ops.object.modifier_apply(modifier=md.name) a = me.attributes.new("nz", "FLOAT", "CORNER") cn = me.corner_normals rot = o.matrix_world.to_3x3() a.data.foreach_set("value", [(rot @ cn[i].vector).z for i in range(len(me.loops))]) def gpu_on(sc): try: prefs = bpy.context.preferences.addons["cycles"].preferences for t in ("OPTIX", "CUDA", "HIP", "ONEAPI", "METAL"): try: prefs.compute_device_type = t except Exception: continue prefs.get_devices() devs = [d for d in prefs.devices if d.type == t] if devs: for d in prefs.devices: d.use = d.type == t sc.cycles.device = "GPU" return except Exception as e: print("STY|no GPU:", e) sc.cycles.device = "CPU" def bake(objs, twins, tex, mask, res, samples, ps): """Bake the painters from flat-shaded twins (same UVs) of objs: the albedo into tex, then (metallic, smoothness) into the RGBA mask.""" sc = bpy.context.scene sc.render.engine = "CYCLES" gpu_on(sc) sc.cycles.samples = samples sc.cycles.use_denoising = False sc.render.bake.margin = max(8, res // 128) sc.render.bake.use_clear = True tws = [] for o, me in zip(objs, twins): tw = bpy.data.objects.new("BakeTwin_" + o.name, me) sc.collection.objects.link(tw) tw.matrix_world = o.matrix_world.copy() for p in me.polygons: p.use_smooth = False o.hide_render = True tws.append(tw) for o in sc.objects: o.select_set(o in tws) bpy.context.view_layer.objects.active = tws[0] out = {} for which, name in (("albedo", tex), ("mask", mask + "_bake")): img = bpy.data.images.new(name, res, res, alpha=False) if which == "mask": img.colorspace_settings.name = "Non-Color" img.generated_color = (0.0, 0.3, 0.0, 1) else: img.generated_color = (0.2, 0.17, 0.14, 1) for k in KEYS: m = bpy.data.materials.get("bake_" + k) if m: build_painter(m, k, img, ps, which) t0 = time.time() bpy.ops.object.bake(type="EMIT", margin=sc.render.bake.margin, use_clear=True) print(f"STY|{T.name}: baked {which} {res}px x {samples} samples in {time.time() - t0:.0f}s") out[which] = img for tw in tws: me = tw.data bpy.data.objects.remove(tw) bpy.data.meshes.remove(me) for o in objs: o.hide_render = False os.makedirs(os.path.join(OUT, "textures"), exist_ok=True) a = out["albedo"] a.filepath_raw = os.path.join(OUT, "textures", tex + ".png") a.file_format = "PNG" a.save() # the URP metallic map: metallic in RGB, smoothness in A import numpy as np b = out["mask"] px = np.array(b.pixels[:], dtype=np.float32).reshape(-1, 4) rgba = np.stack([px[:, 0], px[:, 0], px[:, 0], px[:, 1]], axis=1) mk = bpy.data.images.new(mask, res, res, alpha=True) mk.colorspace_settings.name = "Non-Color" mk.alpha_mode = "CHANNEL_PACKED" mk.pixels[:] = rgba.ravel() mk.filepath_raw = os.path.join(OUT, "textures", mask + ".png") mk.file_format = "PNG" mk.save() bpy.data.images.remove(b) return a, mk def collapse(objs, mat): for o in objs: me = o.data me.materials.clear() me.materials.append(mat) for p in me.polygons: p.material_index = 0 if "G" in me.uv_layers: me.uv_layers.remove(me.uv_layers["G"]) for a in ("grad", "edgedist", "nz"): if a in me.attributes: me.attributes.remove(me.attributes[a]) for k in KEYS: b = bpy.data.materials.get("bake_" + k) if b: bpy.data.materials.remove(b) def export_fbx(objs, name): path = os.path.join(OUT, "fbx", name + ".fbx") os.makedirs(os.path.dirname(path), exist_ok=True) for o in bpy.context.scene.objects: o.select_set(o in objs) # the settings of common.export bpy.ops.export_scene.fbx(filepath=path, 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) return path def write_material_json(mat, tex, mask): """Upsert the material in ArtSource/materials_style.json, in the format of M_Scythe_Painted plus "mask" (URP metallic map: metallic RGB, smoothness A) and "paintGlow". With a metallic map URP ignores _Metallic and scales the map's smoothness by _Smoothness, hence 1.0.""" try: with open(MATJSON, "r", encoding="utf-8") as f: data = json.load(f) except Exception: data = [] entry = {"name": mat, "color": "#FFFFFF", "texture": tex + ".png", "metallic": 1.0, "smoothness": 1.0, "emission": None, "transparent": False, "tiling": [1, 1], "mask": mask + ".png", "paintGlow": PAINT_GLOW} data = [d for d in data if d.get("name") != mat] + [entry] with open(MATJSON, "w", encoding="utf-8") as f: json.dump(data, f, indent=2) f.write("\n") # ======================================================================= presentation BG_TOP, BG_BOT = lin("#76716b"), lin("#34312e") # a neutral, slightly warm studio grey RIM = "#fff1e0" def stage(): sc = bpy.context.scene col = bpy.data.collections.get("Presentation") or bpy.data.collections.new("Presentation") if col.name not in sc.collection.children: sc.collection.children.link(col) def light(name, energy, color, size): ld = bpy.data.lights.new(name, "AREA") ld.energy = energy ld.color = color ld.shape = "DISK" ld.size = size o = bpy.data.objects.new(name, ld) col.objects.link(o) return o key = light("Key", 70.0, (1.0, 0.97, 0.93), 2.5) rim = light("Rim", 300.0, lin(RIM), 1.2) # a studio HDRI from Blender's own studio lights, for the metal to reflect w = bpy.data.worlds.new("Stage") sc.world = w try: w.use_nodes = True except Exception: pass nt = w.node_tree bgn = nt.nodes.get("Background") hdr = os.path.join(bpy.utils.system_resource("DATAFILES"), "studiolights", "world", "studio.exr") if os.path.exists(hdr): env = nt.nodes.new("ShaderNodeTexEnvironment") env.image = bpy.data.images.load(hdr, check_existing=True) nt.links.new(env.outputs["Color"], bgn.inputs[0]) bgn.inputs[1].default_value = 0.8 else: bgn.inputs[0].default_value = (*lin("#8a8580"), 1) bgn.inputs[1].default_value = 0.6 for eng in ("BLENDER_EEVEE", "BLENDER_EEVEE_NEXT"): try: sc.render.engine = eng break except Exception: continue try: sc.eevee.taa_render_samples = 64 except Exception: pass sc.view_settings.view_transform = "Standard" sc.view_settings.exposure = -0.2 sc.render.film_transparent = True return key, rim def backdrop(path): """The (transparent) render over a neutral warm grey radial gradient (a studio backdrop).""" import numpy as np im = bpy.data.images.load(path, check_existing=False) w, h = im.size a = np.array(im.pixels[:], dtype=np.float32).reshape(h, w, 4) yy, xx = np.mgrid[0:h, 0:w].astype(np.float32) d = np.sqrt(((xx - w * 0.45) / w) ** 2 + ((yy - h * 0.6) / h) ** 2) f = np.clip(d / 0.75, 0, 1)[..., None] to_srgb = lambda c: np.where(c <= 0.0031308, c * 12.92, 1.055 * np.power(c, 1 / 2.4) - 0.055) bg = to_srgb(np.array(BG_TOP)) * (1 - f) + to_srgb(np.array(BG_BOT)) * f al = a[..., 3:4] rgb = a[..., :3] * al + bg * (1 - al) im.pixels[:] = np.concatenate([rgb, np.ones_like(al)], axis=2).ravel() im.filepath_raw = path im.file_format = "PNG" im.save() bpy.data.images.remove(im) def place_lights(key, rim, tgt, dirv, d, rim_k=1.0): """The key from above, 50 degrees round to the camera's left; the rim behind the subject, low, so it lines silhouettes and does not wash over the tops.""" hv = Vector((dirv.x, dirv.y, 0)) hv = hv.normalized() if hv.length > 1e-4 else Vector((0, -1, 0)) kl = (Matrix.Rotation(DEG(-50), 3, "Z") @ hv) * 1.8 + Vector((0, 0, 2.0)) key.location = tgt + kl key.rotation_euler = (-kl).to_track_quat("-Z", "Y").to_euler() rd = max(0.6, d * 0.7) rim.location = tgt - hv * rd + Vector((0, 0, rd * 0.18)) rim.rotation_euler = (tgt - rim.location).to_track_quat("-Z", "Y").to_euler() rim.data.energy = 300.0 * rim_k * (rd / 1.8) ** 2 def cam_dir(elev, azim): el, az = DEG(elev), DEG(azim) return Vector((math.sin(az) * math.cos(el), -math.cos(az) * math.cos(el), math.sin(el))) def fit(verts, dirv, lens=50, margin=0.86): """Target and distance that frame verts (world points) from direction dirv on a square frame.""" f = -dirv r = f.cross(Z) r = r.normalized() if r.length > 1e-4 else Vector((1, 0, 0)) u = r.cross(f).normalized() c = sum(verts, Vector()) / len(verts) xs = [(p - c).dot(r) for p in verts] ys = [(p - c).dot(u) for p in verts] tgt = c + r * (max(xs) + min(xs)) / 2 + u * (max(ys) + min(ys)) / 2 tn = 18.0 / lens * margin d = max(max(abs((p - tgt).dot(r)), abs((p - tgt).dot(u))) / tn + (p - tgt).dot(dirv) for p in verts) return tgt, d def shoot(path, key, rim, tgt, d, dirv, res=(1200, 1200), lens=50, rim_k=1.0): sc = bpy.context.scene cam_d = bpy.data.cameras.new("cam") cam_d.lens = lens cam = bpy.data.objects.new("cam", cam_d) sc.collection.objects.link(cam) cam.location = tgt + dirv * d cam.rotation_euler = (tgt - cam.location).to_track_quat("-Z", "Y").to_euler() cam_d.clip_start = d * 0.01 cam_d.clip_end = d * 10 + 10 place_lights(key, rim, tgt, dirv, d, rim_k) sc.camera = cam sc.render.resolution_x, sc.render.resolution_y = res sc.render.filepath = path bpy.ops.render.render(write_still=True) backdrop(path) bpy.data.objects.remove(cam) print("STY|shot", path) def holds(): sys.path.insert(0, HERE) import gc_up5_check as K5 return K5.HOLDS def fpv_shot(path, objs, hold, key, rim, open_deg=0.35 * 18.0): """ViewModel.Holds (rest pose), the 62 degree overlay camera at the origin looking down Blender -Y; scissor blades opened like fpv().""" pos, eu, _, _, s = hold M = Matrix(((-1, 0, 0, 0), (0, 0, -1, 0), (0, 1, 0, 0), (0, 0, 0, 1))) E = Matrix.Rotation(DEG(eu[1]), 4, "Y") @ Matrix.Rotation(DEG(eu[0]), 4, "X") @ Matrix.Rotation(DEG(eu[2]), 4, "Z") W = M @ (Matrix.Translation(Vector(pos)) @ E @ Matrix.Scale(s, 4)) @ M.inverted() keep = {o: o.matrix_world.copy() for o in objs} for o in objs: b = o.matrix_world.copy() if o.name == "BladeA": b = b @ Matrix.Rotation(DEG(-open_deg), 4, "Z") elif o.name == "BladeB": b = b @ Matrix.Rotation(DEG(open_deg), 4, "Z") o.matrix_world = W @ b sc = bpy.context.scene cam_d = bpy.data.cameras.new("cam_fpv") cam_d.sensor_fit = "VERTICAL" cam_d.angle = DEG(62) cam_d.clip_start = 0.01 cam = bpy.data.objects.new("cam_fpv", cam_d) sc.collection.objects.link(cam) cam.rotation_euler = (DEG(90), 0, math.pi) sc.camera = cam ctr = sum((o.matrix_world.translation for o in objs), Vector()) / len(objs) place_lights(key, rim, ctr, Vector((0, 1, 0.3)).normalized(), 0.8, 0.35) sc.render.resolution_x, sc.render.resolution_y = 1280, 720 sc.render.filepath = path bpy.ops.render.render(write_still=True) backdrop(path) bpy.data.objects.remove(cam) for o, m in keep.items(): o.matrix_world = m print("STY|shot", path) def presentation(name, objs, full, views, hold, only=None): key, rim = stage() pv = os.path.join(OUT, "previews") os.makedirs(pv, exist_ok=True) verts = [o.matrix_world @ v.co for o in objs for v in o.data.vertices] for tag, (el, az) in full.items(): if only and tag not in only: continue dv = cam_dir(el, az) tgt, d = fit(verts, dv) shoot(os.path.join(pv, f"{name}_{tag}.png"), key, rim, tgt, d, dv, rim_k=0.5) for tag, tgt, rad, el, az in views: if only and tag not in only: continue dv = cam_dir(el, az) d = rad / math.tan(math.atan(18 / 50)) * 1.05 shoot(os.path.join(pv, f"{name}_{tag}.png"), key, rim, Vector(tgt), d, dv, rim_k=0.5) if hold and (not only or "fpv" in only): fpv_shot(os.path.join(pv, f"{name}_fpv.png"), objs, hold, key, rim) def viewport_material_preview(objs): verts = [o.matrix_world @ v.co for o in objs for v in o.data.vertices] c = sum(verts, Vector()) / len(verts) dv = cam_dir(30, -35) tgt, d = fit(verts, dv) for scr in bpy.data.screens: for area in scr.areas: for sp in area.spaces: if sp.type == "VIEW_3D": sp.shading.type = "MATERIAL" sp.clip_start = 0.005 r3 = sp.region_3d r3.view_location = tgt r3.view_distance = d r3.view_rotation = (-dv).to_track_quat("-Z", "Y") # ======================================================================= driver def argv(): a = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else [] o = dict(names=[], res=None, samples=128, bake=True, render=True, shots=None) i = 0 while i < len(a): if a[i] == "--res": o["res"] = int(a[i + 1]); i += 1 elif a[i] == "--samples": o["samples"] = int(a[i + 1]); i += 1 elif a[i] == "--no-bake": o["bake"] = False elif a[i] == "--no-render": o["render"] = False elif a[i] == "--shots": o["shots"] = a[i + 1].split(","); i += 1 elif not a[i].startswith("--"): o["names"].append(a[i]) i += 1 return o def short(name): return name.replace("SM_Tool_", "") def build_tool(name, builder, o): """builder() makes the parts and returns dict(origins={group: pivot}, res=2048, ps=1.0, full={tag: (elev, azim)}, views=[(tag, target, radius, elev, azim)], also=[other names to export the same result under]).""" new_tool(name) spec = builder() or {} sh = short(name) tex, mskn, matn = f"T_{sh}_Painted", f"T_{sh}_Mask", f"M_{sh}_Painted" objs = join_groups(spec.get("origins", {})) pack_uvs(objs) twins = [o_.data.copy() for o_ in objs] for ob, tw in zip(objs, twins): finish_normals(ob) a = tw.attributes.new("nz", "FLOAT", "CORNER") a.data.foreach_set("value", [d.value for d in ob.data.attributes["nz"].data]) tris = {ob.name: sum(len(p.vertices) - 2 for p in ob.data.polygons) for ob in objs} print(f"STY|{name}: tris {sum(tris.values())} {tris}") tex_path = os.path.join(OUT, "textures", tex + ".png") msk_path = os.path.join(OUT, "textures", mskn + ".png") res = o["res"] or spec.get("res", 2048) if o["bake"] or not (os.path.exists(tex_path) and os.path.exists(msk_path)): img, msk = bake(objs, twins, tex, mskn, res, o["samples"], spec.get("ps", 1.0)) for im, pth in ((img, tex_path), (msk, msk_path)): im.source = "FILE" im.filepath = pth im.reload() else: for tw in twins: bpy.data.meshes.remove(tw) img = bpy.data.images.load(tex_path) img.name = tex msk = bpy.data.images.load(msk_path) msk.name = mskn mat = final_material(matn, img, msk) collapse(objs, mat) write_material_json(matn, tex, mskn) for nm in [name] + spec.get("also", []): export_fbx(objs, nm) if o["render"]: hold = holds().get(name) presentation(name, objs, spec.get("full", {"full": (34, -35)}), spec.get("views", []), hold, o["shots"]) viewport_material_preview(objs) bpy.context.preferences.filepaths.save_version = 0 # no .blend1 next to it img.filepath = bpy.path.relpath(tex_path, start=OUT) msk.filepath = bpy.path.relpath(msk_path, start=OUT) for nm in [name] + spec.get("also", []): bpy.ops.wm.save_as_mainfile(filepath=os.path.join(OUT, nm + ".blend"), check_existing=False, relative_remap=True) print(f"STY|{name}: done") return tris def run(builders, order=None): o = argv() names = o["names"] or list(order or builders) for n in names: build_tool(n, builders[n], o)