A 3D model pipeline, pushed by Gemini 4 Carbon
agent
+1:10:59reasoning
I'm thinking through how to approach this.
read_file{"EndLine":400,"Path":"~/work/lowmarch/tools/blender_sculpt_cast.py","StartLine":1}
input
{ "EndLine": 400, "Path": "~/work/lowmarch/tools/blender_sculpt_cast.py", "StartLine": 1 }result, 401 lines
Showing lines 1-400 of 1443 1: """Headless Blender 5.2 sculpt and bespoke asset builder for Lowmarch (adversarial pass). 2: 3: Runs inside Blender 5.2 (`blender -b --factory-startup --python tools/blender_sculpt_cast.py -- in.npz out.npz valen|korin`). 4: Replaces VRoid hair cards, stock body proportions, juvenile face shapes, and procedural tube garments with: 5: 1. Anatomically resculpted heroic body proportions and muscle contours (`bmesh` + smooth falloffs). 6: 2. Mature anime face sculpt across all shared face layers + Blender `DATA_TRANSFER` head-proxy normals. 7: 3. 100% original 3D Bezier-curve anime lock hair with chevron-ridge bevels, nonlinear taper, and dome-blended normals. 8: 4. Bespoke Subdivision/Bevel/Solidify gothic-anime Valkyrie armour, split surcoat, tassets, winged poleyns, 9: sabatons, swept-wing longsword, and 3D-relief sunburst shield. 10: """ 11: import math 12: import sys 13: 14: import bmesh 15: import bpy 16: import numpy as np 17: from mathutils import Matrix, Vector 18: from mathutils.bvhtree import BVHTree 19: 20: 21: def vrm_to_bl(P): 22: """Map VRM BUST_POSE (x right+, y up+, z back+) -> Blender (X right+, Y fwd+, Z up+); det = +1.""" 23: P = np.asarray(P, dtype=np.float64) 24: if P.ndim == 1: 25: return np.array([P[0], -P[2], P[1]], dtype=np.float64) 26: return np.stack([P[:, 0], -P[:, 2], P[:, 1]], axis=-1) 27: 28: 29: def bl_to_vrm(P): 30: """Inverse SO(3) map Blender (X, Y, Z) -> VRM (X, Z, -Y); det = +1.""" 31: P = np.asarray(P, dtype=np.float64) 32: if P.ndim == 1: 33: return np.array([P[0], P[2], -P[1]], dtype=np.float64) 34: return np.stack([P[:, 0], P[:, 2], -P[:, 1]], axis=-1) 35: 36: 37: def clear_scene(): 38: bpy.ops.wm.read_factory_settings(use_empty=True) 39: 40: 41: def make_mesh_obj(name, verts_bl, faces): 42: me = bpy.data.meshes.new(name) 43: me.from_pydata(verts_bl.tolist(), [], faces.tolist()) 44: me.update() 45: ob = bpy.data.objects.new(name, me) 46: bpy.context.collection.objects.link(ob) 47: return ob 48: 49: 50: def eval_mesh_data(ob, triangulate=True): 51: deps = bpy.context.evaluated_depsgraph_get() 52: ev = ob.evaluated_get(deps) 53: me = ev.to_mesh() 54: bm = bmesh.new() 55: bm.from_mesh(me) 56: if triangulate: 57: bmesh.ops.triangulate(bm, faces=bm.faces[:]) 58: bm.normal_update() 59: bm.verts.ensure_lookup_table() 60: bm.faces.ensure_lookup_table() 61: 62: # Read custom split normals if present on evaluated mesh, else smooth vertex normals 63: me_tri = bpy.data.meshes.new("_tmp_eval") 64: bm.to_mesh(me_tri) 65: bm.free() 66: me_tri.calc_normals_split() if hasattr(me_tri, "calc_normals_split") else None 67: 68: nv = len(me_tri.vertices) 69: nf = len(me_tri.polygons) 70: pos = np.empty(nv * 3, dtype=np.float64) 71: me_tri.vertices.foreach_get("co", pos) 72: pos = pos.reshape(nv, 3) 73: 74: # Accumulate corner normals onto vertices so custom DATA_TRANSFER normals carry through cleanly 75: nc = len(me_tri.loops) 76: loop_v = np.empty(nc, dtype=np.int32) 77: me_tri.loops.foreach_get("vertex_index", loop_v) 78: cnrm = np.empty(nc * 3, dtype=np.float64) 79: me_tri.corner_normals.foreach_get("vector", cnrm) 80: cnrm = cnrm.reshape(nc, 3) 81: nrm = np.zeros((nv, 3), dtype=np.float64) 82: np.add.at(nrm, loop_v, cnrm) 83: ln = np.linalg.norm(nrm, axis=1, keepdims=True) 84: fallback = np.empty(nv * 3, dtype=np.float64) 85: me_tri.vertices.foreach_get("normal", fallback) 86: fallback = fallback.reshape(nv, 3) 87: nrm = np.where(ln > 1e-8, nrm / np.maximum(ln, 1e-8), fallback) 88: 89: tri = np.empty(nf * 3, dtype=np.int32) 90: me_tri.polygons.foreach_get("vertices", tri) 91: tri = tri.reshape(nf, 3) 92: 93: bpy.data.meshes.remove(me_tri) 94: ev.to_mesh_clear() 95: return bl_to_vrm(pos).astype(np.float32), bl_to_vrm(nrm).astype(np.float32), tri 96: 97: 98: def smoothstep(a, b, x): 99: t = np.clip((x - a) / (b - a), 0.0, 1.0) 100: return t * t * (3.0 - 2.0 * t) 101: 102: 103: # --------------------------------------------------------------------------- 104: # 1. Body & Mature Anime Face Sculpt + Blender DATA_TRANSFER Head Proxy Normals 105: # --------------------------------------------------------------------------- 106: def sculpt_valen_body_and_face(body_pos_vrm, body_tri, face_pos_vrm, face_tri, bones_vrm, lm_vrm): 107: """Resculpt Valen's body & face in Blender 5.2; return updated positions + custom face normals.""" 108: B = bones_vrm 109: hips_z = B["J_Bip_C_Hips"][1] 110: chest_z = B["J_Bip_C_Chest"][1] 111: uchest_z = B["J_Bip_C_UpperChest"][1] 112: neck_z = B["J_Bip_C_Neck"][1] 113: head_z = B["J_Bip_C_Head"][1] 114: knee_z = B["J_Bip_L_LowerLeg"][1] 115: ankle_z = B["J_Bip_L_Foot"][1] 116: 117: # --- Sculpt body in Blender space (X right, Y fwd, Z up) --- 118: bp = vrm_to_bl(body_pos_vrm).copy() 119: x, y, z = bp[:, 0], bp[:, 1], bp[:, 2] 120: 121: # Mask out hands/arms so finger grip frames stay crisp; only torso, neck, hips, legs get sculpted 122: arm_mask = smoothstep(0.125, 0.175, np.abs(x)) * smoothstep(hips_z - 0.08, uchest_z + 0.08, z) 123: core_w = 1.0 - arm_mask 124: 125: # Cinched high Valkyrie waist + lifted ribcage + flared iliac hip curve 126: waist_z = hips_z + 0.095 127: w_band = np.exp(-((z - waist_z) / 0.085) ** 2) * core_w 128: hip_band = np.exp(-((z - (hips_z - 0.015)) / 0.085) ** 2) * core_w 129: rib_band = np.exp(-((z - (uchest_z - 0.015)) / 0.080) ** 2) * core_w 130: 131: bp[:, 0] *= 1.0 - 0.155 * w_band + 0.055 * hip_band + 0.035 * rib_band 132: bp[:, 1] *= 1.0 - 0.125 * w_band + 0.030 * hip_band + 0.045 * rib_band 133: # Subtle heroic sternum lift 134: bp[:, 1] += 0.006 * rib_band * np.clip(y / 0.08, 0.0, 1.0) 135: 136: # Athletic thigh-to-knee taper & sculpted gastrocnemius calf + slim ankle 137: thigh_band = np.exp(-((z - (0.58 * hips_z + 0.42 * knee_z)) / 0.13) ** 2) 138: knee_band = np.exp(-((z - knee_z) / 0.065) ** 2) 139: calf_hi = np.exp(-((z - (0.66 * knee_z + 0.34 * ankle_z)) / 0.085) ** 2) 140: ankle_band = np.exp(-((z - (ankle_z + 0.055)) / 0.065) ** 2) 141: for sx in (-1.0, 1.0): 142: leg_cx = sx * abs(B["J_Bip_L_UpperLeg"][0]) 143: m_leg = (x * sx > 0.0) & (z < hips_z + 0.02) 144: dx = bp[m_leg, 0] - leg_cx 145: scale_leg = (1.0 + 0.045 * thigh_band[m_leg] - 0.065 * knee_band[m_leg] 146: + 0.038 * calf_hi[m_leg] - 0.11 * ankle_band[m_leg]) 147: bp[m_leg, 0] = leg_cx + dx * scale_leg 148: dy_c = bp[m_leg, 1] - (-B["J_Bip_L_UpperLeg"][2]) 149: bp[m_leg, 1] = (-B["J_Bip_L_UpperLeg"][2]) + dy_c * scale_leg 150: 151: # --- Shared mature face deformation field F(p) applied to BOTH face (all 8 layers) and head skin --- 152: eye_z = float(lm_vrm["eye_y"]) 153: chin_z = float(lm_vrm["chin"][1]) 154: nose_bl = vrm_to_bl(lm_vrm["nose"]) 155: eye_x = abs(float(lm_vrm["eyeR"][0])) 156: 157: def mature_face_field(P_bl): 158: Q = P_bl.copy() 159: px, py, pz = Q[:, 0], Q[:, 1], Q[:, 2] 160: head_w = smoothstep(neck_z - 0.02, neck_z + 0.05, pz) 161: if not np.any(head_w > 0): 162: return Q 163: 164: # 1. Slimmer aristocratic V-jaw & cheek contour (removes juvenile puffy lower cheek) 165: jaw_band = np.exp(-((pz - (chin_z + 0.036)) / 0.048) ** 2) * smoothstep(0.015, 0.065, np.abs(px)) 166: chin_tip = np.exp(-((pz - (chin_z + 0.008)) / 0.024) ** 2) * np.exp(-(px / 0.028) ** 2) 167: Q[:, 0] -= px * (0.088 * jaw_band + 0.065 * chin_tip) * head_w 168: Q[:, 1] += 0.0024 * chin_tip * head_w # crisp forward chin point 169: 170: # 2. Poised commander almond eyes: tighten vertical aperture 7.5% & cant outer corner +2.3 mm 171: eye_band_z = np.exp(-((pz - eye_z) / 0.020) ** 2) 172: eye_band_x = np.exp(-((np.abs(px) - eye_x) / 0.024) ** 2) 173: eye_f = eye_band_z * eye_band_x * head_w * smoothstep(0.06, 0.11, py) 174: Q[:, 2] = pz + (pz - eye_z) * (-0.075 * eye_f) 175: outer_cant = smoothstep(eye_x - 0.004, eye_x + 0.018, np.abs(px)) * eye_f 176: Q[:, 2] += 0.0023 * outer_cant 177: 178: # 3. Refined straight anime nose bridge & narrower alar wings 179: nose_f = np.exp(-((pz - nose_bl[2]) / 0.022) ** 2) * np.exp(-(px / 0.018) ** 2) * smoothstep(0.10, 0.14, py) 180: Q[:, 0] *= 1.0 - 0.11 * nose_f * head_w 181: Q[:, 1] += 0.0018 * nose_f * np.exp(-(px / 0.007) ** 2) * head_w 182: return Q 183: 184: bp = mature_face_field(bp) 185: fp = mature_face_field(vrm_to_bl(face_pos_vrm)) 186: 187: # Build Blender objects and run DATA_TRANSFER from a sculpted anime Head-Proxy ellipsoid 188: ob_face = make_mesh_obj("ValenFace", fp, face_tri) 189: bpy.ops.mesh.primitive_uv_sphere_add(segments=48, ring_count=32, radius=1.0, location=(0.0, 0.0, 0.0)) 190: proxy = bpy.context.active_object 191: proxy.name = "AnimeFaceNormalProxy" 192: # Position proxy slightly forward toward the face mask so 3/4 terminator carves a crisp cheek curve 193: p_center = np.array([0.0, nose_bl[1] - 0.068, eye_z + 0.006]) 194: pm = proxy.data 195: pv = np.empty(len(pm.vertices) * 3, dtype=np.float64) 196: pm.vertices.foreach_get("co", pv) 197: pv = pv.reshape(-1, 3) 198: # Sculpted anime proxy: slightly flattened front, defined cheekbone flare 199: cheek_flare = 1.0 + 0.10 * np.exp(-((pv[:, 2] + 0.12) / 0.35) ** 2) * np.clip(pv[:, 1], 0.0, 1.0) 200: pv[:, 0] *= 0.088 * cheek_flare 201: pv[:, 1] *= 0.098 202: pv[:, 2] *= 0.118 203: pv += p_center 204: pm.vertices.foreach_set("co", pv.ravel()) 205: pm.update() 206: for poly in pm.polygons: 207: poly.use_smooth = True 208: 209: for poly in ob_face.data.polygons: 210: poly.use_smooth = True 211: 212: mod = ob_face.modifiers.new(name="ProxyNormals", type="DATA_TRANSFER") 213: mod.object = proxy 214: mod.use_loop_data = True 215: mod.data_types_loops = {"CUSTOM_NORMAL"} 216: mod.loop_mapping = "POLYINTERP_NEAREST" 217: mod.mix_factor = 0.88 218: 219: _, face_nrm_vrm, _ = eval_mesh_data(ob_face, triangulate=False) 220: 221: # Smooth body normals in Blender 222: ob_body = make_mesh_obj("ValenBody", bp, body_tri) 223: for poly in ob_body.data.polygons: 224: poly.use_smooth = True 225: _, body_nrm_vrm, _ = eval_mesh_data(ob_body, triangulate=False) 226: 227: bpy.data.objects.remove(ob_face, do_unlink=True) 228: bpy.data.objects.remove(proxy, do_unlink=True) 229: bpy.data.objects.remove(ob_body, do_unlink=True) 230: return bl_to_vrm(bp).astype(np.float32), body_nrm_vrm, bl_to_vrm(fp).astype(np.float32), face_nrm_vrm 231: 232: 233: # --------------------------------------------------------------------------- 234: # 2. Blender 5.2 Curve-to-Mesh 3D Anime Hair Builder (Zero VRoid Cards!) 235: # --------------------------------------------------------------------------- 236: def _make_chevron_bevel_and_taper(profile_kind="lock"): 237: """Create anime lock bevel cross-section (sharp central dorsal ridge, tucked underside) + taper curve.""" 238: bev_cu = bpy.data.curves.new(f"Bevel_{profile_kind}", type="CURVE") 239: bev_cu.dimensions = "2D" 240: sp = bev_cu.splines.new("POLY") 241: if profile_kind == "braid": 242: pts = [(-1.0, 0.0), (-0.65, 0.72), (0.0, 1.05), (0.65, 0.72), 243: (1.0, 0.0), (0.65, -0.68), (0.0, -0.95), (-0.65, -0.68)] 244: else: 245: # Crisp dorsal ridge at +Y (outer normal) so cel lighting splits cleanly along the lock crest! 246: pts = [(-1.0, -0.05), (-0.58, 0.42), (0.0, 0.92), (0.58, 0.42), 247: (1.0, -0.05), (0.52, -0.34), (0.0, -0.40), (-0.52, -0.34)] 248: sp.points.add(len(pts) - 1) 249: for i, (px, py) in enumerate(pts): 250: sp.points[i].co = (px, py, 0.0, 1.0) 251: sp.use_cyclic_u = True 252: bev_ob = bpy.data.objects.new(f"BevelOb_{profile_kind}", bev_cu) 253: bpy.context.collection.objects.link(bev_ob) 254: 255: tap_cu = bpy.data.curves.new(f"Taper_{profile_kind}", type="CURVE") 256: tap_cu.dimensions = "2D" 257: tsp = tap_cu.splines.new("NURBS") 258: # Nonlinear anime swell at 30%, needle-sharp point at tip 259: tpts = [(0.0, 0.72), (0.16, 1.06), (0.38, 1.12), (0.66, 0.84), (0.86, 0.42), (0.96, 0.14), (1.0, 0.025)] 260: tsp.points.add(len(tpts) - 1) 261: for i, (tx, ty) in enumerate(tpts): 262: tsp.points[i].co = (tx, ty, 0.0, 1.0) 263: tsp.use_endpoint_u = True 264: tsp.order_u = 4 265: tap_ob = bpy.data.objects.new(f"TaperOb_{profile_kind}", tap_cu) 266: bpy.context.collection.objects.link(tap_ob) 267: return bev_ob, tap_ob 268: 269: 270: def _add_lock_curve(name, pts_bl, width, thick_ratio, head_center_bl, bev_ob, tap_ob, twist=0.0, res_u=14): 271: cu = bpy.data.curves.new(name, type="CURVE") 272: cu.dimensions = "3D" 273: cu.resolution_u = res_u 274: cu.bevel_mode = "OBJECT" 275: cu.bevel_object = bev_ob 276: cu.taper_object = tap_ob 277: cu.use_fill_caps = True 278: 279: sp = cu.splines.new("NURBS") 280: sp.points.add(len(pts_bl) - 1) 281: pts = np.asarray(pts_bl, dtype=np.float64) 282: tang = np.gradient(pts, axis=0) 283: 284: for i, p in enumerate(pts): 285: sp.points[i].co = (p[0], p[1], p[2], 1.0) 286: sp.points[i].radius = width 287: # Orient local +Y of bevel cross-section away from skull center! 288: t = tang[i] 289: tn = np.linalg.norm(t) 290: t = t / tn if tn > 1e-8 else np.array([0.0, 0.0, -1.0]) 291: away = p - head_center_bl 292: away = away - t * np.dot(away, t) 293: an = np.linalg.norm(away) 294: away = away / an if an > 1e-8 else np.array([0.0, 1.0, 0.0]) 295: 296: # Blender curve MINIMUM twist frame approximation: compute angle around tangent from Z-up ref 297: up_ref = np.array([0.0, 0.0, 1.0]) 298: if abs(np.dot(t, up_ref)) > 0.94: 299: up_ref = np.array([0.0, 1.0, 0.0]) 300: b0 = np.cross(up_ref, t) 301: b0 /= max(np.linalg.norm(b0), 1e-8) 302: n0 = np.cross(t, b0) 303: ang = math.atan2(np.dot(away, b0), np.dot(away, n0)) 304: sp.points[i].tilt = ang + twist * (i / max(1, len(pts) - 1)) 305: 306: sp.use_endpoint_u = True 307: sp.order_u = min(4, len(pts)) 308: cu.twist_mode = "Z_UP" 309: 310: ob = bpy.data.objects.new(name, cu) 311: bpy.context.collection.objects.link(ob) 312: 313: # Convert to mesh and scale cross-section aspect slightly if needed 314: deps = bpy.context.evaluated_depsgraph_get() 315: ev = ob.evaluated_get(deps) 316: me = bpy.data.meshes.new_from_object(ev) 317: for poly in me.polygons: 318: poly.use_smooth = True 319: mob = bpy.data.objects.new(name + "_m", me) 320: bpy.context.collection.objects.link(mob) 321: bpy.data.objects.remove(ob, do_unlink=True) 322: return mob 323: 324: 325: def build_valen_valkyrie_hair(face_pos_vrm, face_tri, body_pos_vrm, body_tri, bones_vrm, lm_vrm): 326: """Build Valen's 100% original 3D sculpted Valkyrie crown-braid & high S-curve ponytail in Blender 5.2.""" 327: fp_bl = vrm_to_bl(face_pos_vrm) 328: bp_bl = vrm_to_bl(body_pos_vrm) 329: head_z = bones_vrm["J_Bip_C_Head"][1] 330: neck_z = bones_vrm["J_Bip_C_Neck"][1] 331: eye_z = float(lm_vrm["eye_y"]) 332: crown_bl = vrm_to_bl(lm_vrm["crown"]) 333: fore_bl = vrm_to_bl(lm_vrm["forehead"]) 334: 335: # Build BVHTree of skull + face in Blender space so every hair root hugs the real head cleanly! 336: skull_mask = bp_bl[:, 2] > neck_z - 0.02 337: skull_idx_map = np.where(skull_mask)[0] 338: keep_bt = np.all(skull_mask[body_tri], axis=1) 339: all_v = np.vstack([fp_bl, bp_bl[skull_mask]]) 340: remap = np.zeros(len(bp_bl), dtype=np.int32) 341: remap[skull_idx_map] = np.arange(len(skull_idx_map)) + len(fp_bl) 342: all_f = np.vstack([face_tri, remap[body_tri[keep_bt]]]) 343: bvh = BVHTree.FromPolygons(all_v.tolist(), all_f.tolist()) 344: 345: hc = np.array([0.0, (fore_bl[1] - 0.085), eye_z + 0.032]) 346: 347: def skull_pt(az_deg, el_deg, lift=0.008): 348: """Spherical ray from skull center hc: az_deg (0=+Y front, +90=+X right, 180=-Y back), el_deg (0=+Z crown, 90=level).""" 349: az = math.radians(az_deg) 350: el = math.radians(el_deg) 351: d = Vector((math.sin(el) * math.sin(az), math.sin(el) * math.cos(az), math.cos(el))) 352: loc, _, _, _ = bvh.ray_cast(Vector(hc) + d * 0.32, -d, 0.30) 353: if loc is None: 354: r = 0.102 355: return hc + np.array([d.x, d.y, d.z]) * (r + lift) 356: return np.array([loc.x, loc.y, loc.z]) + np.array([d.x, d.y, d.z]) * lift 357: 358: bev_lock, tap_lock = _make_chevron_bevel_and_taper("lock") 359: bev_braid, tap_braid = _make_chevron_bevel_and_taper("braid") 360: hair_objs = [] 361: 362: # 1. Sculpted Watertight Cranial Hair Dome (covers crown, temples, and nape cleanly) 363: nu, nv = 48, 22 364: azs = np.linspace(-180.0, 180.0, nu, endpoint=False) 365: dome_grid = np.zeros((nu, nv, 3)) 366: for i, az in enumerate(azs): 367: # Hairline arches high over forehead (52 deg), dips at temples (76 deg), sweeps down nape (134 deg) 368: hl_max = float(np.interp(abs(az), [0, 32, 62, 95, 138, 180], [50, 56, 76, 98, 128, 136])) 369: for j, t in enumerate(np.linspace(0.02, 1.0, nv)): 370: el = hl_max * t 371: swell = 0.004 + 0.013 * math.sin(math.pi * min(1.0, t * 1.15)) * (0.65 + 0.35 * (abs(az) / 180.0)) 372: dome_grid[i, j] = skull_pt(az, el, lift=swell) 373: # Build dome mesh with pole cap at crown 374: crown_top = skull_pt(0.0, 0.0, lift=0.015) 375: d_verts = [crown_top] + dome_grid.reshape(-1, 3).tolist() 376: d_faces = [] 377: for i in range(nu): 378: inext = (i + 1) % nu 379: d_faces.append([0, 1 + i * nv, 1 + inext * nv]) 380: for j in range(nv - 1): 381: a = 1 + i * nv + j 382: b = 1 + inext * nv + j 383: c = 1 + inext * nv + j + 1 384: d = 1 + i * nv + j + 1 385: d_faces.append([a, b, c]) 386: d_faces.append([a, c, d]) 387: dome_ob = make_mesh_obj("HairDome", np.array(d_verts), np.array(d_faces)) 388: for poly in dome_ob.data.polygons: 389: poly.use_smooth = True 390: sub = dome_ob.modifiers.new("Sub", "SUBSURF") 391: sub.levels = sub.render_levels = 1 392: hair_objs.append(dome_ob) 393: 394: # Parting point slightly right of center (-20 deg azimuth) for asymmetric commander bangs 395: part_pt = skull_pt(-18.0, 26.0, lift=0.016) 396: 397: # 2. Asymmetric Swept Commander Bangs (parted cleanly so brows & sapphire eyes read!) 398: bang_specs = [ 399: # Main swept left-ward curtain locks across forehead1 more lines not shown.
read_file{"EndLine":700,"Path":"~/work/lowmarch/tools/blender_sculpt_cast.py","StartLine":401}
input
{ "EndLine": 700, "Path": "~/work/lowmarch/tools/blender_sculpt_cast.py", "StartLine": 401 }result, 301 lines
Showing lines 401-700 of 1443 401: skull_pt(23, 79, 0.011)], 0.020, 0.12), 402: ([part_pt, skull_pt(-12, 40, 0.019), skull_pt(-2, 54, 0.020), skull_pt(5, 69, 0.016), 403: skull_pt(9, 82, 0.009)], 0.017, 0.08), 404: # Central delicate V-accent lock between eyes 405: ([part_pt, skull_pt(-16, 42, 0.018), skull_pt(-10, 58, 0.017), skull_pt(-4, 73, 0.012)], 0.012, 0.0), 406: # Right-side parted counter-sweep framing outer right brow 407: ([part_pt, skull_pt(-26, 38, 0.020), skull_pt(-36, 53, 0.021), skull_pt(-43, 69, 0.017), 408: skull_pt(-47, 84, 0.011)], 0.019, -0.15), 409: # Outer temple transitional framing locks 410: ([skull_pt(16, 30, 0.018), skull_pt(30, 48, 0.022), skull_pt(40, 67, 0.020), 411: skull_pt(46, 86, 0.014)], 0.019, 0.18), 412: ([skull_pt(-24, 30, 0.018), skull_pt(-40, 48, 0.022), skull_pt(-50, 68, 0.020), 413: skull_pt(-55, 88, 0.014)], 0.018, -0.18), 414: # Windswept Heroic Valkyrie Ahoge / Crest Lock arcing up from the part! 415: ([part_pt + np.array([0.0, -0.005, -0.003]), 416: part_pt + np.array([0.010, 0.012, 0.032]), 417: part_pt + np.array([0.028, 0.002, 0.052]), 418: part_pt + np.array([0.048, -0.022, 0.044]), 419: part_pt + np.array([0.062, -0.045, 0.026])], 0.011, 0.25), 420: ] 421: for k, (pts, wd, tw) in enumerate(bang_specs): 422: hair_objs.append(_add_lock_curve(f"Bang_{k}", pts, wd, 0.45, hc, bev_lock, tap_lock, twist=tw)) 423: 424: # 3. Layered Valkyrie Cheek & Collarbone Side-Tresses (Left & Right) 425: for side_nm, sx in (("R", 1.0), ("L", -1.0)): 426: # Shorter hime jaw-framing lock 427: p_jaw = [ 428: skull_pt(sx * 48, 42, 0.018), 429: skull_pt(sx * 58, 68, 0.022), 430: skull_pt(sx * 60, 96, 0.020), 431: np.array([sx * 0.078, fore_bl[1] - 0.036, eye_z - 0.072]), 432: np.array([sx * 0.064, fore_bl[1] - 0.020, eye_z - 0.118]), 433: ] 434: hair_objs.append(_add_lock_curve(f"CheekLock_{side_nm}", p_jaw, 0.020, 0.45, hc, bev_lock, tap_lock, twist=sx * 0.18)) 435: 436: # Long sweeping collarbone tress draping forward over shoulder-gorget 437: p_long = [ 438: skull_pt(sx * 64, 48, 0.019), 439: skull_pt(sx * 74, 78, 0.024), 440: skull_pt(sx * 76, 106, 0.024), 441: np.array([sx * 0.098, fore_bl[1] - 0.052, neck_z - 0.010]), 442: np.array([sx * 0.106, fore_bl[1] - 0.026, neck_z - 0.082]), 443: np.array([sx * 0.092, fore_bl[1] - 0.008, neck_z - 0.148]), 444: ] 445: hair_objs.append(_add_lock_curve(f"CollarTress_{side_nm}", p_long, 0.021, 0.45, hc, bev_lock, tap_lock, twist=-sx * 0.22)) 446: 447: # 4. Crown Volume Locks sweeping back into the high ponytail gathering point 448: tie_bl = skull_pt(180.0, 62.0, lift=0.026) # High occipital Valkyrie ponytail anchor 449: for i, az in enumerate((-148, -118, -88, 88, 118, 148, 176)): 450: p_cr = [ 451: skull_pt(az * 0.35, 16, 0.017), 452: skull_pt(az * 0.72, 38, 0.022), 453: skull_pt(az, 58, 0.024), 454: tie_bl + np.array([0.012 * math.sin(math.radians(az)), 0.005, 0.004]), 455: ] 456: hair_objs.append(_add_lock_curve(f"CrownSweep_{i}", p_cr, 0.024, 0.45, hc, bev_lock, tap_lock)) 457: 458: # 5. Twin Temple Crown-Braids wrapping into the ponytail cuff! 459: for side_nm, sx in (("R", 1.0), ("L", -1.0)): 460: b_pts = [] 461: for s in np.linspace(0.0, 1.0, 9): 462: az = sx * (54.0 + 122.0 * s) 463: el = 58.0 + 6.0 * math.sin(math.pi * s) 464: wobble = 0.0035 * math.sin(s * math.pi * 6.0) 465: b_pts.append(skull_pt(az, el, lift=0.025 + wobble)) 466: hair_objs.append(_add_lock_curve(f"CrownBraid_{side_nm}", b_pts, 0.015, 0.85, hc, bev_braid, tap_braid, twist=sx * 3.8, res_u=18)) 467: 468: # Nape tucked locks below the ponytail 469: for i, az in enumerate((-152, -168, 180, 168, 152)): 470: p_np = [ 471: skull_pt(az, 92, 0.018), 472: skull_pt(az, 118, 0.020), 473: skull_pt(az, 136, 0.016) + np.array([0.0, -0.008, -0.028]), 474: ] 475: hair_objs.append(_add_lock_curve(f"NapeLock_{i}", p_np, 0.018, 0.45, hc, bev_lock, tap_lock)) 476: 477: # 6. Massive Dynamic S-Curving High Valkyrie Ponytail (14 layered sweeping 3D plumes!) 478: # Sweeps upward-back from tie_bl, arches proudly, and fans down to mid-back with windswept drama! 479: ponytail_objs = [] 480: tail_specs = [ 481: # Upper crest plumes (bold anime silhouette arc) 482: (0.00, 0.042, 0.30, 0.030, 0.0), 483: (-0.028, 0.036, 0.28, 0.026, -0.25), 484: (0.028, 0.036, 0.28, 0.026, 0.25), 485: # Wide fanned middle plumes 486: (-0.058, 0.020, 0.34, 0.028, -0.40), 487: (0.058, 0.020, 0.34, 0.028, 0.40), 488: (-0.035, 0.012, 0.38, 0.030, -0.20), 489: (0.035, 0.012, 0.38, 0.030, 0.20), 490: (0.00, 0.018, 0.40, 0.032, 0.08), 491: # Long lower streamer locks with upturned anime fork tips 492: (-0.072, -0.005, 0.43, 0.022, -0.55), 493: (0.072, -0.005, 0.43, 0.022, 0.55), 494: (-0.024, -0.010, 0.46, 0.025, -0.15), 495: (0.024, -0.010, 0.46, 0.025, 0.15), 496: # Fine outer flyaway accent wisps for silhouette energy 497: (-0.092, 0.028, 0.29, 0.013, -0.70), 498: (0.092, 0.028, 0.29, 0.013, 0.70), 499: ] 500: for k, (lat_x, crest_z, drop_len, wd, tw) in enumerate(tail_specs): 501: # Windswept leftward flow (-X in Blender is character's left = rightward in camera 3/4 view, wait: 502: # Valen stands on left facing +32 deg yaw, cape blows left (-X_cam). In VRM/BL: -X_vrm -> +X_glb! 503: # Wait: Valen's cape blows LEFT on screen, which in VRM is +X! Let's fan symmetrically with slight +X sweep!) 504: sway = 0.032 * (k % 3 - 1) * 0.35 - 0.028 505: p_tail = [ 506: tie_bl + np.array([lat_x * 0.18, 0.005, 0.0]), 507: tie_bl + np.array([lat_x * 0.55 + sway * 0.2, -0.048, 0.038 + crest_z]), 508: tie_bl + np.array([lat_x * 0.95 + sway * 0.5, -0.115, 0.012 + crest_z * 0.6 - drop_len * 0.28]), 509: tie_bl + np.array([lat_x * 1.25 + sway * 0.85, -0.165, -drop_len * 0.68]), 510: tie_bl + np.array([lat_x * 1.42 + sway * 1.15, -0.195, -drop_len * 0.96]), 511: tie_bl + np.array([lat_x * 1.55 + sway * 1.30, -0.228, -drop_len * 1.04 + 0.018]), 512: ] 513: ponytail_objs.append(_add_lock_curve(f"Ponytail_{k}", p_tail, wd, 0.48, tie_bl + np.array([0, 0.05, -0.15]), 514: bev_lock, tap_lock, twist=tw, res_u=16)) 515: 516: # Join crown hair vs ponytail separately so ponytail can take slight neck/chest follow-through weight! 517: def join_and_proxy_normals(objs, name, proxy_center, proxy_radii, mix=0.52): 518: bpy.ops.object.select_all(action="DESELECT") 519: for o in objs: 520: o.select_set(True) 521: bpy.context.view_layer.objects.active = objs[0] 522: if len(objs) > 1: 523: bpy.ops.object.join() 524: joined = bpy.context.active_object 525: joined.name = name 526: 527: bpy.ops.mesh.primitive_uv_sphere_add(segments=36, ring_count=24, radius=1.0, location=(0, 0, 0)) 528: prx = bpy.context.active_object 529: pv = np.empty(len(prx.data.vertices) * 3, dtype=np.float64) 530: prx.data.vertices.foreach_get("co", pv) 531: pv = pv.reshape(-1, 3) * np.asarray(proxy_radii) + np.asarray(proxy_center) 532: prx.data.vertices.foreach_set("co", pv.ravel()) 533: prx.data.update() 534: for poly in prx.data.polygons: 535: poly.use_smooth = True 536: 537: dt = joined.modifiers.new("HairDomeNormals", "DATA_TRANSFER") 538: dt.object = prx 539: dt.use_loop_data = True 540: dt.data_types_loops = {"CUSTOM_NORMAL"} 541: dt.loop_mapping = "POLYINTERP_NEAREST" 542: dt.mix_factor = mix # 52% cohesive anime crown halo + 48% sharp 3D lock-ridge cel planes! 543: 544: pos_v, nrm_v, tri_v = eval_mesh_data(joined, triangulate=True) 545: bpy.data.objects.remove(joined, do_unlink=True) 546: bpy.data.objects.remove(prx, do_unlink=True) 547: return pos_v, nrm_v, tri_v 548: 549: crown_pos, crown_nrm, crown_tri = join_and_proxy_normals( 550: hair_objs, "ValenHairCrown", hc + np.array([0, -0.01, 0.02]), (0.13, 0.14, 0.14), mix=0.52 551: ) 552: tail_pos, tail_nrm, tail_tri = join_and_proxy_normals( 553: ponytail_objs, "ValenHairTail", tie_bl + np.array([0, -0.10, -0.14]), (0.16, 0.16, 0.26), mix=0.42 554: ) 555: 556: # Ornate Gilded Valkyrie Hair-Cuff & Ribbon Ties at tie_bl 557: bpy.ops.mesh.primitive_torus_add( 558: major_radius=0.032, minor_radius=0.0085, major_segments=24, minor_segments=10, 559: location=tuple(tie_bl + np.array([0.0, -0.010, 0.004])), 560: rotation=(math.radians(58.0), 0.0, 0.0) 561: ) 562: cuff = bpy.context.active_object 563: for poly in cuff.data.polygons: 564: poly.use_smooth = True 565: cuff_pos, cuff_nrm, cuff_tri = eval_mesh_data(cuff, triangulate=True) 566: bpy.data.objects.remove(cuff, do_unlink=True) 567: 568: ribbon_objs = [] 569: for sx in (-1.0, 1.0): 570: r_pts = [ 571: tie_bl + np.array([sx * 0.022, -0.016, -0.004]), 572: tie_bl + np.array([sx * 0.052, -0.055, -0.045]), 573: tie_bl + np.array([sx * 0.078, -0.092, -0.125]), 574: tie_bl + np.array([sx * 0.095, -0.118, -0.215]), 575: ] 576: ribbon_objs.append(_add_lock_curve(f"HairRibbon_{sx}", r_pts, 0.014, 0.25, tie_bl, bev_lock, tap_lock, twist=sx * 0.5)) 577: rib_pos, rib_nrm, rib_tri = join_and_proxy_normals(ribbon_objs, "ValenHairRibbons", tie_bl, (0.15, 0.15, 0.20), mix=0.25) 578: 579: bpy.data.objects.remove(bev_lock, do_unlink=True) 580: bpy.data.objects.remove(tap_lock, do_unlink=True) 581: bpy.data.objects.remove(bev_braid, do_unlink=True) 582: bpy.data.objects.remove(tap_braid, do_unlink=True) 583: 584: return [ 585: ("hair_crown", "hair", crown_pos, crown_nrm, crown_tri, "head_rigid"), 586: ("hair_ponytail", "hair", tail_pos, tail_nrm, tail_tri, "ponytail_blend"), 587: ("hair_cuff", "gold", cuff_pos, cuff_nrm, cuff_tri, "head_rigid"), 588: ("hair_ribbon", "signature", rib_pos, rib_nrm, rib_tri, "ponytail_blend"), 589: ] 590: 591: 592: # --------------------------------------------------------------------------- 593: # 3. Blender 5.2 Bespoke Gothic-Anime Valkyrie Armour, Surcoat & Weapons 594: # --------------------------------------------------------------------------- 595: def _grid_shell_in_blender(name, grid_bl, thickness=0.005, subsurf=1, cyclic_u=False): 596: """Build a smooth Catmull-Clark subdivided + solidified shell in Blender from a (U, V, 3) point grid.""" 597: U, V = grid_bl.shape[:2] 598: verts = grid_bl.reshape(-1, 3).tolist() 599: faces = [] 600: u_lim = U if cyclic_u else U - 1 601: for i in range(u_lim): 602: inext = (i + 1) % U 603: for j in range(V - 1): 604: a = i * V + j 605: b = inext * V + j 606: c = inext * V + j + 1 607: d = i * V + j + 1 608: faces.append([a, b, c, d]) 609: ob = make_mesh_obj(name, np.array(verts), np.array(faces)) 610: # Ensure consistent outward normals away from grid centroid 611: bm = bmesh.new() 612: bm.from_mesh(ob.data) 613: bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:]) 614: center = Vector(grid_bl.reshape(-1, 3).mean(axis=0)) 615: dot_sum = sum((f.calc_center_median() - center).dot(f.normal) for f in bm.faces) 616: if dot_sum < 0: 617: bmesh.ops.reverse_faces(bm, faces=bm.faces[:]) 618: # Crease boundary edges slightly so Catmull-Clark keeps crisp armour silhouettes! 619: crease_layer = bm.edges.layers.crease.verify() if hasattr(bm.edges.layers, "crease") else None 620: for e in bm.edges: 621: if e.is_boundary and crease_layer is not None: 622: e[crease_layer] = 0.55 623: bm.to_mesh(ob.data) 624: bm.free() 625: for poly in ob.data.polygons: 626: poly.use_smooth = True 627: 628: if subsurf > 0: 629: sub = ob.modifiers.new("Sub", "SUBSURF") 630: sub.levels = sub.render_levels = subsurf 631: if thickness > 0: 632: sol = ob.modifiers.new("Sol", "SOLIDIFY") 633: sol.thickness = thickness 634: sol.offset = 1.0 # thicken outward 635: sol.use_rim = True 636: pos_v, nrm_v, tri_v = eval_mesh_data(ob, triangulate=True) 637: bpy.data.objects.remove(ob, do_unlink=True) 638: return pos_v, nrm_v, tri_v 639: 640: 641: def _curve_pipe_in_blender(name, pts_bl, radius=0.0032, cyclic=False, seg=8): 642: cu = bpy.data.curves.new(name, type="CURVE") 643: cu.dimensions = "3D" 644: cu.resolution_u = 8 645: cu.bevel_depth = radius 646: cu.bevel_resolution = max(1, seg // 2 - 1) 647: cu.use_fill_caps = not cyclic 648: sp = cu.splines.new("POLY") 649: sp.points.add(len(pts_bl) - 1) 650: for i, p in enumerate(pts_bl): 651: sp.points[i].co = (float(p[0]), float(p[1]), float(p[2]), 1.0) 652: sp.use_cyclic_u = cyclic 653: ob = bpy.data.objects.new(name, cu) 654: bpy.context.collection.objects.link(ob) 655: pos_v, nrm_v, tri_v = eval_mesh_data(ob, triangulate=True) 656: bpy.data.objects.remove(ob, do_unlink=True) 657: return pos_v, nrm_v, tri_v 658: 659: 660: def build_valen_bespoke_armour(body_pos_vrm, body_tri, bones_vrm, guard_arm_L_vrm): 661: """Build Valen's complete original Valkyrie-Marshal armour, tailoring & weapons in Blender 5.2.""" 662: bp_bl = vrm_to_bl(body_pos_vrm) 663: bvh_body = BVHTree.FromPolygons(bp_bl.tolist(), body_tri.tolist()) 664: B = {k: vrm_to_bl(v) for k, v in bones_vrm.items()} 665: 666: hips_z = B["J_Bip_C_Hips"][2] 667: waist_z = hips_z + 0.095 668: chest_z = B["J_Bip_C_Chest"][2] 669: uchest_z = B["J_Bip_C_UpperChest"][2] 670: neck_z = B["J_Bip_C_Neck"][2] 671: knee_z = B["J_Bip_L_LowerLeg"][2] 672: ankle_z = B["J_Bip_L_Foot"][2] 673: torso_y = B["J_Bip_C_Chest"][1] 674: 675: # Torso BVH excluding arms/shoulders so torso raycasts never snag hanging arms! 676: torso_v_mask = (np.abs(bp_bl[:, 0]) < 0.155) | (bp_bl[:, 2] < hips_z + 0.04) 677: torso_f = body_tri[np.all(torso_v_mask[body_tri], axis=1)] 678: bvh_torso = BVHTree.FromPolygons(bp_bl.tolist(), torso_f.tolist()) 679: 680: def torso_ray(az_deg, z_val, lift=0.008, default_r=0.115): 681: """Level ray out from torso spine at height z_val; az_deg: 0=+Y front, +90=+X right, 180=-Y back.""" 682: az = math.radians(az_deg) 683: cy = float(np.interp(z_val, [hips_z - 0.1, waist_z, uchest_z, neck_z], 684: [B["J_Bip_C_Hips"][1], torso_y, B["J_Bip_C_UpperChest"][1], B["J_Bip_C_Neck"][1]])) 685: orig = Vector((0.0, cy, z_val)) 686: d = Vector((math.sin(az), math.cos(az), 0.0)) 687: # Cast inward from outside so we always get outermost skin hit! 688: hit, _, _, _ = bvh_torso.ray_cast(orig + d * 0.28, -d, 0.27) 689: r = (hit - orig).length if hit is not None else default_r 690: r = np.clip(r, 0.048, 0.195) 691: return np.array([orig.x + d.x * (r + lift), orig.y + d.y * (r + lift), z_val]) 692: 693: pieces = [] 694: add = lambda nm, role, pos_nrm_tri, bind_tag, grp="plate": pieces.append( 695: (nm, role, pos_nrm_tri[0], pos_nrm_tri[1], pos_nrm_tri[2], bind_tag, grp) 696: ) 697: 698: # 1. High-Collar Midnight-Indigo Quilted Arming Tunic + Officer Collar with Gold Rim 699: nu_t, nv_t = 44, 16 700: az_t = np.linspace(-180, 180, nu_t, endpoint=False)read_file{"EndLine":550,"Path":"~/work/lowmarch/tools/export_glb.py","StartLine":400}
input
{ "EndLine": 550, "Path": "~/work/lowmarch/tools/export_glb.py", "StartLine": 400 }result, 152 lines
Showing lines 400-550 of 567 400: order = sorted(joints) 401: jidx = {nodes_v[i].get("name"): k for k, i in enumerate(order)} 402: ref = portrait.pose_ref 403: local_ref = {i: F4 @ v.local_matrix(i, ref) @ F4 for i in order} 404: world_ref = {} 405: 406: def wref(i): 407: if i not in world_ref: 408: world_ref[i] = (wref(parent[i]) @ local_ref[i]) if parent.get(i) in joints else local_ref[i] 409: return world_ref[i] 410: 411: # glTF assembly (reuses the static exporter's buffer helpers by building a fresh document) 412: bin_ = bytearray() 413: views, accessors, meshes, gnodes, materials, textures, images, anims = [], [], [], [], [], [], [], [] 414: tex_index = {} 415: 416: def add_view(data, target=None): 417: while len(bin_) % 4: 418: bin_.append(0) 419: off = len(bin_) 420: bin_.extend(data) 421: vw = dict(buffer=0, byteOffset=off, byteLength=len(data)) 422: if target: 423: vw["target"] = target 424: views.append(vw) 425: return len(views) - 1 426: 427: def add_acc(arr, kind, comp, target=None, minmax=False): 428: arr = np.ascontiguousarray(arr) 429: a = dict(bufferView=add_view(arr.tobytes(), target), componentType=comp, count=int(arr.shape[0]), type=kind) 430: if minmax or (kind == "VEC3" and comp == 5126): 431: a["min"] = np.atleast_1d(arr.min(0)).tolist() 432: a["max"] = np.atleast_1d(arr.max(0)).tolist() 433: accessors.append(a) 434: return len(accessors) - 1 435: 436: def add_texture(key, rgba, limit=None): 437: if key in tex_index: 438: return tex_index[key] 439: im = Image.fromarray(rgba) 440: lim = limit or max_tex 441: if max(im.size) > lim: 442: k = lim / max(im.size) 443: im = im.resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS) 444: b = io.BytesIO() 445: im.save(b, "PNG", optimize=True) 446: images.append(dict(bufferView=add_view(b.getvalue()), mimeType="image/png")) 447: textures.append(dict(source=len(images) - 1, sampler=0)) 448: tex_index[key] = len(textures) - 1 449: return tex_index[key] 450: 451: # joint nodes 452: node_of = {} 453: for i in order: 454: t, q, sc = _trs(local_ref[i]) 455: node_of[i] = len(gnodes) 456: gnodes.append(dict(name=nodes_v[i].get("name"), translation=t.tolist(), rotation=q.tolist(), scale=sc.tolist())) 457: for i in order: 458: kids = [node_of[c] for c in nodes_v[i].get("children", []) if c in joints] 459: if kids: 460: gnodes[node_of[i]]["children"] = kids 461: roots = [node_of[i] for i in order if parent.get(i) not in joints] 462: ibm = np.stack([np.linalg.inv(wref(i)).T for i in order]).astype(np.float32) # column-major 463: skin = dict(joints=[node_of[i] for i in order], inverseBindMatrices=add_acc(ibm.reshape(-1, 16), "MAT4", 5126), 464: skeleton=roots[0]) 465: mesh_nodes = [] 466: for k, (p, role) in enumerate(zip(portrait.prims, portrait.roles)): 467: if role == "skip" or not len(p["tri"]) or p.get("world") or "J" not in p: 468: continue 469: usedv, inv = np.unique(p["tri"], return_inverse=True) 470: pos = (p["pos"][usedv] * FLIP).astype(np.float32) 471: nrm = p["nrm"][usedv] * FLIP 472: nrm = (nrm / np.maximum(np.linalg.norm(nrm, axis=1, keepdims=True), 1e-9)).astype(np.float32) 473: remap = np.array([jidx.get(n, jidx.get("J_Bip_C_Head")) for n in p["jnames"]]) 474: J = remap[p["J"][usedv]].astype(np.uint16) 475: W = p["W"][usedv].astype(np.float32) 476: W /= np.maximum(W.sum(1, keepdims=True), 1e-9) 477: attrs = dict(POSITION=add_acc(pos, "VEC3", 5126, 34962), NORMAL=add_acc(nrm, "VEC3", 5126, 34962), 478: JOINTS_0=add_acc(J, "VEC4", 5123, 34962), WEIGHTS_0=add_acc(W, "VEC4", 5126, 34962)) 479: if "plate" in p: # outline plates (tools/plates.py): border, engraving, gradient 480: attrs["_PLATE"] = add_acc(np.asarray(p["plate"])[usedv].astype(np.float32), "VEC4", 5126, 34962) 481: mat = dict(name=f"{group_of(p, role)}:{role}", doubleSided=True, 482: pbrMetallicRoughness=dict(metallicFactor=0.0, roughnessFactor=0.9)) 483: tone = ROLE_TONE.get(role) 484: extra = getattr(portrait, "paint", None) or {} 485: color = hex_rgb(palette[tone]) if tone in palette else \ 486: hex_rgb(extra[role]) if isinstance(extra.get(role), str) else [0.8, 0.8, 0.8] 487: if role in TEXTURED: 488: src = portrait._hair_v if role == "hair" and getattr(portrait, "_hair_v", None) is not None \ 489: and "_HAIR" in p["material"] else portrait.v 490: raw = src.material_texture(p["mi"]) if p["mi"] >= 0 else None 491: if raw is not None and role == "line": 492: raw = fill_line_specks(raw) 493: if p.get("lid_fill") is not None: # a shut eye's lid (vroid_portrait): its lash solid 494: raw = fill_lid(raw, p["lid_fill"]) 495: if raw is not None and role == "mouth": 496: raw = even_mouth(raw) 497: if raw is not None: 498: attrs["TEXCOORD_0"] = add_acc(p["uv"][usedv].astype(np.float32), "VEC2", 5126, 34962) 499: mat["pbrMetallicRoughness"]["baseColorTexture"] = dict( 500: index=add_texture((id(src), p["mi"], p.get("lid_fill")), raw)) 501: if role == "hair": 502: mat["pbrMetallicRoughness"]["baseColorFactor"] = color + [1.0] 503: if role in ("hair", "line", "brow", "iris", "highlight"): 504: mat["alphaMode"], mat["alphaCutoff"] = "MASK", 0.5 505: else: 506: mat["pbrMetallicRoughness"]["baseColorFactor"] = color + [1.0] 507: else: 508: mat["pbrMetallicRoughness"]["baseColorFactor"] = color + [1.0] 509: if role in ("metal", "steel", "gold"): 510: mat["pbrMetallicRoughness"].update(metallicFactor=0.6, roughnessFactor=0.35) 511: if p.get("strands"): # kit hair (tools/hair.py): one shared strand texture 512: import hair as _hair 513: attrs["TEXCOORD_0"] = add_acc(np.asarray(p["uv"], np.float32)[usedv], "VEC2", 5126, 34962) 514: mat["pbrMetallicRoughness"]["baseColorTexture"] = dict(index=add_texture(("strands",), _hair.STRANDS)) 515: if "decal" in p: # a design in the piece's own coordinates (tools/plates.py Canvas) 516: uvd = np.asarray(p["uv"], np.float32)[usedv].copy() 517: uvd[:, 1] = 1 - uvd[:, 1] # the canvas draws t up; glTF's texture origin is the top left 518: attrs["TEXCOORD_0"] = add_acc(uvd, "VEC2", 5126, 34962) 519: mat["pbrMetallicRoughness"]["baseColorTexture"] = dict(index=add_texture(("decal", k), p["decal"], limit=1024)) 520: mat["extras"] = dict(decal=True) 521: materials.append(mat) 522: meshes.append(dict(name=group_of(p, role), primitives=[dict(attributes=attrs, 523: indices=add_acc(inv.reshape(-1).astype(np.uint32), "SCALAR", 5125, 34963), material=len(materials) - 1)])) 524: mesh_nodes.append(len(gnodes)) 525: gnodes.append(dict(name=f"{group_of(p, role)}/{p['material']}", mesh=len(meshes) - 1, skin=0, 526: extras=dict(group=group_of(p, role), role=role, material=p["material"]))) 527: # animations 528: for name, keys in (clips or {}).items(): 529: times = np.array([t for t, _ in keys], np.float32) 530: tacc = add_acc(times.reshape(-1, 1), "SCALAR", 5126, minmax=True) 531: samplers, channels = [], [] 532: for i in order: 533: mats = [F4 @ v.local_matrix(i, vp.bone_pose(v, portrait.shape, pose)) @ F4 for _, pose in keys] 534: trs = [_trs(m) for m in mats] 535: T = np.array([a for a, _, _ in trs], np.float32) 536: Q = np.array([b for _, b, _ in trs], np.float32) 537: for k in range(1, len(Q)): # keep quaternions on one hemisphere 538: if np.dot(Q[k], Q[k - 1]) < 0: 539: Q[k] = -Q[k] 540: t0, q0, _ = _trs(local_ref[i]) 541: if np.dot(Q[0], q0) < 0: 542: q0 = -q0 543: # a channel whenever the clip leaves the reference pose, even if it then holds still 544: if np.abs(Q - q0).max() > 1e-5: 545: samplers.append(dict(input=tacc, output=add_acc(Q, "VEC4", 5126), interpolation="LINEAR")) 546: channels.append(dict(sampler=len(samplers) - 1, target=dict(node=node_of[i], path="rotation"))) 547: if np.abs(T - t0).max() > 1e-5: 548: samplers.append(dict(input=tacc, output=add_acc(T, "VEC3", 5126), interpolation="LINEAR")) 549: channels.append(dict(sampler=len(samplers) - 1, target=dict(node=node_of[i], path="translation"))) 550: anims.append(dict(name=name, samplers=samplers, channels=channels))