A 3D model pipeline, pushed by Gemini 4 Carbon
agent
+13:26reasoning
The function hair.cap() appears to already exist, addressing the need for a dark inner cap. It is bound to a specific joint and incorporates parameters for lift and crown adjustments. Initial thought was that it needed to be built, but it seems to already exist.
The VRoid hair rendering reveals deep shadows within the hair, suggesting a dark inner cap is appropriate to model this. Examining the VRoid heads, the ears appear to be part of the body skin, so a shadow check can ensure that ears don't protrude brightly through the hair. A new branch, "carbon", will contain the files for the new rendering design.
A local importmap is employed to ensure the scene functions offline without CDN dependencies or external font fetches. Shader improvements include a three-quarter key lighting setup, shadow ramp adjustments for skin tones, and shadow casting on face and body to model the effects of hair. Ground contact shadows are also added to enhance realism.
Hair rendering will utilize hair_cap handling or !gl_FrontFacing with a HairBack material to achieve deep recessed shadows on inner hair surfaces and the scalp. Outer hair locks will employ a calm two-tone cel shading with a subtle crown halo band for a cleaner appearance. Brows will maintain depthTest: true and the closed-mouth stroke will be rendered with warm umber-rose to ensure visibility across yaw angles.
The battle backdrop design establishes a muted dusk color palette to complement character coloration, creating a grounded atmosphere. A Python script is employed to automate scene rendering and export by reading VRM files and computing camera parameters. The script strictly operates in read-only mode to prevent unintended file modifications. It supports both interactive scene viewing and automated high-resolution export.
Each character requires arm_room to prevent clipping. Two Lowmarch characters are built with vp.Portrait. The first, Valen, a Vanguard Captain, features warm ivory-peach skin, deep chestnut-espresso hair with a scalp cap, and clear steel-cobalt eyes. The second will be similar but with unique colors.
The character's outfit is built layer by layer, starting with a layered battle skirt over charcoal breeches and tall boots. Steel shin greaves and a leather belt are added to the outfit. A longsword and heater buckler complete the equipment; the buckler's size and position are carefully considered to frame the character's silhouette without obstructing the face or torso. Finally, a grounded fencing stance with specific angles is set to show her in an action pose.
Right (korin, Heavy Housecarl, arm_m_strong), skin color is a rich warm bronze-tan, with hue-shifted warm skin ramp on medium-deep skin. The hair is charcoal-iron, tousled, and short, fully visible, which ensures the 3/4 face, brows, jaw shadow, and dark inner hair cap are rendered correctly. His outfit includes a padded oat-linen quilted gambeson, a ringed dark-steel mail hauberk, a riveted dark-leather brigandine vest, a wide leather belt, a weathered oxblood wool shoulder mantle, sturdy leather-and-iron bracers, and baggy folded dark-olive/slate breeches.
vp.Portrait calls face_normals internally, negating the need for a redundant call. The portrait setup includes terrain with specific dimensions, grass tufts, and stones. The render process includes linking a three.js module, running a headless browser, and saving a PNG with exact timing information.
Portrait's face normal handling is now suspected to be causing issues; the approach of passing face_normals=0.0 within shape might be interfering with correct normal calculations. A direct call to vp.face_normals() after the Portrait setup, but before export, might be the solution. Initial suspicion that the reference pose is being altered prematurely appears unfounded. The current setup exports skinned models directly from the BUST_POSE that should be compatible with post-processing. A test run is needed to confirm the direct normal setting is effective before exporting.
read_file{"EndLine":650,"Path":"~/work/lowmarch/tools/gear.py","StartLine":250}
input
{ "EndLine": 650, "Path": "~/work/lowmarch/tools/gear.py", "StartLine": 250 }result, 402 lines
Showing lines 250-650 of 984 250: """A coat of plates: cloth-covered plates held by rows of rivets, front and back, open at the sides.""" 251: B = fit.bone 252: nk, hips = B["J_Bip_C_Neck"], B["J_Bip_C_Hips"] 253: y_top = nk[1] - 0.06 if y_top is None else y_top 254: y_bottom = hips[1] + 0.02 if y_bottom is None else y_bottom 255: cz = float(hips[2]) 256: tc = TorsoChart(under, y_bottom - 0.03, y_top + 0.03, cz=cz, du=3.0, dv=0.008) 257: out = [] 258: for nm, (u0, u1) in (("front", (-70, 70)), ("back", (110, 250))): 259: rows = [[(u, y_bottom + 0.02), (u, y_top - 0.02)] for u in np.arange(u0 + 14, u1 - 6, 14)] 260: top = (lambda u: y_top - 0.05 * max(0.0, 1 - abs(u) / 40)) if nm == "front" else (lambda u: y_top) 261: pc, ex = outline_plate(f"{name}_{nm}", role, tc, u0, u1, lambda u: y_bottom, top, offset=0.016, thickness=0.006, 262: nu=48, nv=18, roll=0.003, roll_edges=("bottom", "top", "left", "right"), 263: seams=rows, groove=(0.004, 0.002), panel_crown=0.003, 264: rivets=(0.03, 0.012, 0.0035), rivet_role=rivet_role) 265: fit.bind(pc, allow=("Spine", "Chest", "UpperChest", "Bust", "Hips"), fallback="J_Bip_C_Chest") 266: for q in ex: 267: O.inherit(q, pc) 268: out += [pc] + ex 269: return _group(out, "plate") 270: 271: 272: # ---- shields ----------------------------------------------------------------------------------------------- 273: def shield(fit, shape="heater", side="L", role="signature", face_role="heraldry", width=0.46, height=0.62, 274: curve=0.55, emblem=None, name="shield"): 275: """A shield strapped to the forearm, cut from an outline and curved round its long axis. 276: heater: flat top, curved sides to a point; tower: tall, near-rectangular; kite: rounded top to a long point.""" 277: E, H = fit.bone[f"J_Bip_{side}_LowerArm"], fit.bone[f"J_Bip_{side}_Hand"] 278: ax = (H - E) / np.linalg.norm(H - E) 279: lat = np.array([-1.0 if side == "L" else 1.0, 0, 0.0]) 280: lat -= ax * (lat @ ax) 281: lat /= np.linalg.norm(lat) 282: up = -ax 283: fw = np.cross(lat, up) 284: if shape == "heater": 285: t = np.linspace(0, 1, 13) 286: right = [(width / 2 * (1 - t_ ** 2.2), -height * 0.25 - height * 0.75 * t_) for t_ in t] 287: outline = [(-width / 2, height * 0.25), (width / 2, height * 0.25)] + right[1:] + [(-x, y) for x, y in right[::-1][1:-1]] 288: elif shape == "tower": 289: outline = [(-width / 2, height / 2), (width / 2, height / 2), (width / 2, -height / 2), (-width / 2, -height / 2)] 290: else: # kite 291: a = np.linspace(0, np.pi, 12) 292: top = [(width / 2 * math.cos(x), height * 0.22 + width / 2 * 0.6 * math.sin(x)) for x in a] 293: outline = top + [(-width / 2 * 0.9, height * 0.0), (0.0, -height * 0.78), (width / 2 * 0.9, height * 0.0)] 294: centre = E + ax * np.linalg.norm(H - E) * 0.5 + lat * 0.07 295: deco = emblem or [] 296: pc = flat_piece(name, role, outline, centre, fw, up, thickness=0.012, decal=deco, px=1200) 297: # curve round the long axis (the face bulges out) 298: P = pc["pos"] 299: x = (P - centre) @ fw 300: P += lat[None] * (-(x ** 2) / (2 * curve))[:, None] 301: pc["nrm"] = O.vertex_normals(P, pc["tri"]) 302: rim = O.pipe(f"{name}_rim", "steel", np.array([centre + fw * px_ + up * py_ + lat * (-(px_ ** 2) / (2 * curve) + 0.007) 303: for px_, py_ in outline]), r=0.006, seg=6, closed=True) 304: boss, _ = O.dome(f"{name}_boss", "steel", centre + lat * 0.007, lat, up, 0.035, 0.022, rows=6) 305: out = [pc, rim, boss] 306: _bind(fit, out, f"J_Bip_{side}_LowerArm") 307: return _group(out, "shield") 308: 309: 310: # ---- weapons (held like the sword: along the right hand's -z) ------------------------------------------------ 311: def _hand_frame(fit, hand="R"): 312: M = fit.world[f"J_Bip_{hand}_Hand"] 313: R, o = M[:3, :3], M[:3, 3] 314: R = R / np.linalg.norm(R, axis=0) 315: sx = 1 if hand == "R" else -1 316: g = getattr(fit, "grip", None) # the fist's measured hole (rig.grip_points) 317: fist = g[hand]["point"] if g else o + R @ np.array([sx * 0.045, -0.018, 0.0]) 318: fwd = R @ np.array([0, 0, -1.0]) 319: side = R @ np.array([sx * 1.0, 0, 0]) 320: return fist, fwd, side, np.cross(fwd, side), R 321: 322: 323: def spear(fit, length=2.0, grip=0.55, head=0.26, hand="R", shaft_role="wood", name="spear"): 324: """A spear held a little behind its middle: an ash shaft, a leaf blade with a socket, a butt cap.""" 325: fist, fwd, side, flat, _ = _hand_frame(fit, hand) 326: start = fist - fwd * grip 327: out = [O.tube(f"{name}_shaft", shaft_role, start, fwd, length, 0.0135)] 328: tip0 = start + fwd * length 329: out.append(O.tube(f"{name}_socket", "steel", tip0 - fwd * 0.06, fwd, 0.08, 0.016, 0.012)) 330: leaf = [(0.0, 0.0), (0.024, head * 0.30), (0.018, head * 0.65), (0.0, head), (-0.018, head * 0.65), (-0.024, head * 0.30)] 331: out.append(flat_piece(f"{name}_head", "steel", leaf, tip0 + fwd * 0.015, side, fwd, thickness=0.006)) 332: out.append(O.ball(f"{name}_butt", "steel", start - fwd * 0.01, 0.016, squash=(1, 1, 1.6))) 333: _bind(fit, out, f"J_Bip_{hand}_Hand") 334: return _group(out, "weapon") 335: 336: 337: def axe(fit, haft=0.85, blade=0.24, double=False, hand="R", shaft_role="wood", name="axe", grip=0.18): 338: """An axe: a haft with a bearded crescent blade (two for a great axe), a langet and a pommel.""" 339: fist, fwd, side, flat, _ = _hand_frame(fit, hand) 340: start = fist - fwd * grip 341: out = [O.tube(f"{name}_haft", shaft_role, start, fwd, haft, 0.016, 0.018)] 342: top = start + fwd * (haft - 0.02) 343: a = np.linspace(-1, 1, 15) 344: edge = [(blade * (0.72 + 0.28 * math.cos(x * 1.25)), blade * 0.62 * x) for x in a] 345: beard = [(blade * 0.30, -blade * 0.62), (0.03, -blade * 0.16), (0.03, blade * 0.12), (blade * 0.30, blade * 0.58)] 346: cres = [(0.02, -0.05)] + [p_ for p_ in beard[:1]] + edge + [beard[-1]] + [(0.02, 0.05)] 347: for k, sg in enumerate((1, -1) if double else (1,)): 348: pts = [(sg * x, y) for x, y in cres] 349: out.append(flat_piece(f"{name}_blade{k}", "steel", pts, top, side, fwd, thickness=0.009)) 350: out.append(O.box(f"{name}_eye", "steel", top, (side, flat, fwd), (0.026, 0.022, 0.06))) 351: out.append(O.ball(f"{name}_pommel", "steel", start, 0.022, squash=(1, 1, 0.8))) 352: _bind(fit, out, f"J_Bip_{hand}_Hand") 353: return _group(out, "weapon") 354: 355: 356: def dagger(fit, blade=0.24, hand="R", name="dagger"): 357: fist, fwd, side, flat, _ = _hand_frame(fit, hand) 358: out = [O.tube(f"{name}_grip", "leather", fist - fwd * 0.06, fwd, 0.11, 0.011)] 359: g = fist + fwd * 0.055 360: out.append(O.box(f"{name}_guard", "steel", g, (side, flat, fwd), (0.040, 0.008, 0.007))) 361: out.append(flat_piece(f"{name}_blade", "steel", [(0.016, 0), (0.012, blade * 0.7), (0, blade), (-0.012, blade * 0.7), (-0.016, 0)], 362: g + fwd * 0.006, side, fwd, thickness=0.005)) 363: _bind(fit, out, f"J_Bip_{hand}_Hand") 364: return _group(out, "weapon") 365: 366: 367: def staff(fit, length=1.65, hand="R", wood="wood", head_role="gold", name="staff", grip=0.75): 368: fist, fwd, side, flat, _ = _hand_frame(fit, hand) 369: start = fist - fwd * grip 370: out = [O.tube(f"{name}_shaft", wood, start, fwd, length, 0.014, 0.017)] 371: tip = start + fwd * length 372: out.append(O.ball(f"{name}_orb", head_role, tip + fwd * 0.04, 0.035)) 373: for k in range(3): # a cage of three prongs round the orb 374: ang = 2 * math.pi * k / 3 375: d = side * math.cos(ang) + flat * math.sin(ang) 376: pts = [tip - fwd * 0.02, tip + d * 0.03 + fwd * 0.02, tip + d * 0.042 + fwd * 0.05, tip + d * 0.02 + fwd * 0.085] 377: out.append(O.pipe(f"{name}_prong{k}", head_role, np.array(pts), r=0.004, seg=6)) 378: _bind(fit, out, f"J_Bip_{hand}_Hand") 379: return _group(out, "weapon") 380: 381: 382: def bow(fit, length=1.25, hand="L", name="bow", wood="wood"): 383: """A self bow in the lowered hand, hanging along the leg: limbs curving forward at the tips, a string.""" 384: M = fit.world[f"J_Bip_{hand}_Hand"] 385: R, o = M[:3, :3], M[:3, 3] 386: R = R / np.linalg.norm(R, axis=0) 387: sx = 1 if hand == "R" else -1 388: grip = o + R @ np.array([sx * 0.045, -0.018, 0.0]) 389: along = R @ np.array([sx * 1.0, 0, 0]) # the fingers' direction: down a hanging arm 390: belly = R @ np.array([0, 0, -1.0]) # the bow's back faces forward 391: t = np.linspace(-1, 1, 25) 392: curve = np.array([grip + along * (length / 2) * x + belly * (0.08 * (1 - x * x) - 0.02 * x ** 4) for x in t]) 393: limb = O.pipe(f"{name}_limb", wood, curve, r=0.012, seg=7) 394: taper(limb, len(t), 8, 1.0 - 0.55 * np.abs(t) ** 1.4) 395: limb["nrm"] = O.vertex_normals(limb["pos"], limb["tri"]) 396: string = O.pipe(f"{name}_string", "heraldry", np.array([curve[0], curve[-1]]), r=0.0014, seg=4) 397: wrap = O.tube(f"{name}_grip", "leather", grip - along * 0.05, along, 0.10, 0.016) 398: out = [limb, string, wrap] 399: _bind(fit, out, f"J_Bip_{hand}_Hand") 400: return _group(out, "weapon") 401: 402: 403: def quiver(fit, name="quiver", role="leather"): 404: """A quiver slung on the back, arrows showing.""" 405: B = fit.bone 406: sp = B["J_Bip_C_Chest"] 407: c = sp + np.array([0.06, 0.0, 0.11]) 408: d = np.array([-0.35, 1.0, 0.1]) 409: d /= np.linalg.norm(d) 410: out = [O.tube(f"{name}_case", role, c - d * 0.28, d, 0.5, 0.045, 0.05)] 411: for k in range(5): 412: off = np.array([math.cos(k * 1.3) * 0.02, 0, math.sin(k * 1.3) * 0.02]) 413: out.append(O.tube(f"{name}_arrow{k}", "wood", c + d * 0.2 + off, d, 0.12, 0.004)) 414: out.append(O.box(f"{name}_fletch{k}", "heraldry", c + d * 0.31 + off, (d, np.array([1.0, 0, 0]), np.cross(d, [1.0, 0, 0])), 415: (0.03, 0.012, 0.002))) 416: _bind(fit, out, "J_Bip_C_Chest") 417: return _group(out, "weapon") 418: 419: 420: # ---- casters: robes and hats -------------------------------------------------------------------------------- 421: def robe(fit, under, name="robe", role="signature", trim=0.012, y_hem=None, flare=0.16, split=0.0, sleeve_flare=0.07): 422: """A long robe: the body over the shirt, a skirt over a cone to the ankles (split at the front if 423: `split` degrees), bell sleeves widening to the wrist; gold-bordered edges.""" 424: B = fit.bone 425: nk, hips = B["J_Bip_C_Neck"], B["J_Bip_C_Hips"] 426: foot = B["J_Bip_L_Foot"][1] 427: y_hem = foot + 0.04 if y_hem is None else y_hem 428: cz = float(hips[2]) 429: y_waist = hips[1] + 0.06 430: tc = TorsoChart(under, y_waist - 0.04, nk[1] + 0.02, cz=cz, du=3.0, dv=0.008) 431: out = [] 432: body, _ = outline_plate(name, role, tc, -178, 178, lambda u: y_waist, lambda u: nk[1] - 0.025 - 0.03 * max(0.0, 1 - abs(u) / 60), 433: offset=0.008, thickness=0.004, nu=96, nv=20, roll=0, trim=trim) 434: fit.bind(body, allow=("Spine", "Chest", "UpperChest", "Bust", "Hips", "Neck", "Shoulder"), fallback="J_Bip_C_Chest") 435: out.append(body) 436: r0 = lambda u: float(tc.radius(u, y_waist)) + 0.010 437: cone = ConeChart(lambda u, v: np.vectorize(r0)(u) + flare * np.clip((y_waist - v) / (y_waist - y_hem), 0, 1.2) ** 1.4, cz=cz) 438: u0, u1 = (split, 360 - split) if split else (-178, 178) 439: skirt, _ = outline_plate(f"{name}_skirt", role, cone, u0, u1, lambda u: y_hem, lambda u: y_waist + 0.012, offset=0.002, 440: thickness=0.004, nu=120, nv=22, roll=0, trim=trim) 441: fit.bind(skirt, allow=("Hips", "UpperLeg"), fallback="J_Bip_C_Hips") 442: stiffen(skirt, fit, share=0.6) 443: out.append(skirt) 444: for side in ("L", "R"): 445: for seg, (a, b, v0, v1, fl) in enumerate(((f"J_Bip_{side}_UpperArm", f"J_Bip_{side}_LowerArm", -0.06, 1.02, 0.0), 446: (f"J_Bip_{side}_LowerArm", f"J_Bip_{side}_Hand", -0.02, 0.86, sleeve_flare))): 447: arm = O.limb_surface(fit, (a.replace("J_Bip_", ""), b.replace("J_Bip_", "")), side) 448: lc = LimbChart(arm, B[a], B[b], front=(0, 0, -1)) 449: sl, _ = outline_plate(f"{name}_sleeve_{side}{seg}", role, lc, -180, 180, lambda u, v1=v1: v1, lambda u, v0=v0: v0, 450: offset=0.010, thickness=0.004, nu=48, nv=12, roll=0, trim=trim if seg else 0.0, 451: flare=(lambda u, v, s, t, fl=fl: fl * (1 - t) ** 1.8) if fl else None) 452: fit.bind(sl, allow=(a.replace("J_Bip_", ""), b.replace("J_Bip_", "")), fallback=a) 453: out.append(sl) 454: return _group(out, "dress") 455: 456: 457: def witch_hat(fit, name="hat", role="signature", band_role="gold", height=0.32, brim=0.12, lift=0.034): 458: """A tall pointed hat: a wide soft brim, a crown narrowing to a tip that bends back, a band.""" 459: ch = head_chart(fit) 460: rim_v = lambda u: float(np.interp(abs(u), [0, 90, 180], [62, 74, 84])) 461: U = np.linspace(-180, 180, 49) 462: base = np.array([ch.point(u, rim_v(u), off=lift) for u in U]) 463: c0 = base.mean(0) 464: rings = [] 465: for k, t in enumerate(np.linspace(0, 1, 16)): 466: axis = c0 + np.array([0, height * t, 0.10 * t ** 2.2]) # the tip leans back 467: rings.append(axis + (base - c0) * (1 - t) ** 1.25 * (1 + 0.15 * math.sin(math.pi * t))) 468: G = np.stack(rings, 1) 469: pos, tri, outer = O.thick_grid(G, 0.004, outward_from=c0 + np.array([0, height * 0.3, 0])) 470: crown = O.piece(name, role, pos, tri) 471: d = base - ch.c 472: d[:, 1] = 0 473: d /= np.linalg.norm(d, axis=1, keepdims=True) 474: B_ = np.stack([base + d * brim * t - np.array([0, 0.03 * t ** 2, 0]) for t in np.linspace(0, 1, 6)], 1) 475: pos, tri, outer2 = O.thick_grid(B_, 0.004, outward_from=ch.c - np.array([0, 0.4, 0])) 476: brim_pc = O.piece(f"{name}_brim", role, pos, tri) 477: band = O.pipe(f"{name}_band", band_role, base + (base - c0) * 0.03 + np.array([0, 0.012, 0]), r=0.007, seg=6, closed=True) 478: out = [crown, brim_pc, band] 479: _bind(fit, out, "J_Bip_C_Head") 480: return _group(out, "helmet") 481: 482: 483: # ---- the study's detail layer (lesson 15): puffed sleeves, breastplates, scale and pleated skirts ---------- 484: def puff(fit, side, role="signature", size=1.0, name=None, piping=None, gather=0.48, cap=None, under=None): 485: """A puffed upper sleeve: a rounded box on the shoulder and upper arm, gathered toward the elbow 486: (the generic units' most recognisable shape). size scales it; piping: a role for a seam pipe. 487: 488: cap (default: on MakeHuman bodies) is the shape after the Unicorn Overlord study and an art 489: review: a shoulder cap, widest at the top and fuller at the back, gathered hard into a band that 490: sits on the sleeve above the elbow, with folds converging on the band. Its size follows the arm's 491: length only (capped), and the sleeves in `under` are tucked inside it, so a thick arm can't poke 492: through. The older shape sat lower, bulged evenly in and out, and on a muscled arm read as a 493: swollen bicep.""" 494: B = fit.bone 495: s = 1 if side == "R" else -1 496: sh, el = B[f"J_Bip_{side}_UpperArm"], B[f"J_Bip_{side}_LowerArm"] 497: L = float(np.linalg.norm(el - sh)) 498: down = (el - sh) / L 499: outw = np.array([s * 1.0, 0, 0]) - down * (s * down[0]) 500: outw /= np.linalg.norm(outw) 501: fwd = np.cross(down, outw) 502: fwd = -fwd if fwd[2] > 0 else fwd 503: up = -down 504: cap = getattr(fit, "cloth_hull", False) if cap is None else cap 505: if not cap: 506: # measured on a 23 cm upper arm; a thicker arm gets a bigger puff, or the arm pokes through it 507: w = fit.weight((f"{side}_UpperArm",)) 508: sk = np.unique(fit.tri) 509: P = fit.pos[sk[w[sk] > 0.6]] - sh 510: r = np.linalg.norm(P - np.outer(P @ down, down), axis=1) if len(P) else np.zeros(1) 511: kl = L / 0.23 512: kr = max(float(np.percentile(r, 90)) / 0.0534, float(np.percentile(r, 50)) / 0.0391) 513: k = size * max(kl, kr + 0.06 * min(1.0, max(0.0, kr - kl) / 0.05)) 514: c = sh + down * L * 0.32 + outw * 0.010 * k 515: ext = {"out": 0.058 * k, "in": 0.050 * k, "up": 0.082 * k, "down": 0.088 * k, "fwd": 0.056 * k, "back": 0.054 * k} 516: G, gexp, r_band = gather, 2.0, None 517: else: 518: k = size * min(1.15, L / 0.23) 519: # the arm's median radius: the puff must stand well clear of it to read as a puff at all 520: w = fit.weight((f"{side}_UpperArm",)) 521: sk = np.unique(fit.tri) 522: P = fit.pos[sk[w[sk] > 0.6]] - sh 523: r_arm = float(np.median(np.linalg.norm(P - np.outer(P @ down, down), axis=1))) if len(P) else 0.04 524: lk = max(k, 1.35 * r_arm / 0.052) 525: c = sh + down * L * 0.17 + outw * 0.008 * lk 526: ext = {"out": 0.058 * lk, "in": 0.046 * lk, "up": 0.050 * k, "down": 0.110 * k, "fwd": 0.048 * lk, "back": 0.062 * lk} 527: # the band sits on the sleeve, round the bone: its radius where the puff gathers, measured on 528: # the sleeve itself 529: t_g = float((c - up * ext["down"] * 0.97 - sh) @ down) 530: cg = sh + down * t_g 531: r_band = r_arm + 0.008 532: band_r = None # the band's radius by angle round the sleeve 533: cg0 = cg.copy() 534: 535: def measure(cg): 536: """The sleeve where the puff gathers: its centre, its 85th-percentile radius and its radius 537: by angle (None, None, None when there is no sleeve).""" 538: for pc_ in under or []: 539: Q = pc_["pos"] - cg 540: ax = Q @ down 541: on_arm = (np.array([f"{side}_UpperArm" in n for n in pc_["jnames"]])[pc_["J"]] * pc_["W"]).sum(1) > 0.5 542: near = (np.abs(ax) < 0.012) & on_arm 543: if near.sum() <= 6: 544: continue 545: Qn = Q[near] - np.outer(ax[near], down) 546: mid = Qn.mean(0) 547: Qn = Qn - mid 548: ang = np.arctan2(Qn @ fwd, Qn @ outw) 549: rad = np.linalg.norm(Qn, axis=1) 550: bins = (((ang + np.pi) / (2 * np.pi)) * 16).astype(int) % 16 551: med = np.array([rad[bins == i].max() if (bins == i).any() else np.nan for i in range(16)]) 552: ok = ~np.isnan(med) 553: cen = -np.pi + (np.arange(16) + 0.5) * 2 * np.pi / 16 554: med = np.interp(cen, cen[ok], med[ok], period=2 * np.pi) 555: med = (np.roll(med, 1) + 2 * med + np.roll(med, -1)) / 4 556: return (cg + mid, float(np.percentile(rad, 85)) + 0.003, 557: lambda f, cen=cen, med=med: float(np.interp(f, cen, med, period=2 * np.pi)) + 0.003) 558: return None, None, None 559: m_ = measure(cg0) 560: if m_[0] is not None: 561: cg, r_band, band_r = m_ 562: lat = (ext["out"] + ext["in"] + ext["fwd"] + ext["back"]) / 4 563: G, gexp = float(np.clip(1 - r_band / lat, 0.3, 0.8)), 2.6 564: 565: def surf_many(D): 566: """Puff surface points (relative to c, in outw/up/fwd) along directions D (N,3).""" 567: D = D / np.linalg.norm(D, axis=1, keepdims=True) 568: A = np.stack([np.where(D[:, 0] >= 0, ext["out"], ext["in"]), np.where(D[:, 1] >= 0, ext["up"], ext["down"]), 569: np.where(D[:, 2] >= 0, ext["fwd"], ext["back"])], 1) 570: r = (np.sum(np.abs(D / A) ** 3.0, axis=1)) ** (-1 / 3.0) 571: q = D * r[:, None] 572: g = np.where(q[:, 1] < 0, 1 - G * np.clip(-q[:, 1] / ext["down"], 0, 1) ** gexp, 1.0) 573: q[:, 0] *= g 574: q[:, 2] *= g 575: return q 576: 577: def surf(d): 578: q = surf_many(np.asarray(d, float)[None])[0] 579: return c + outw * q[0] + up * q[1] + fwd * q[2] 580: th = np.linspace(0, np.pi, 22) 581: ph = np.linspace(0, 2 * np.pi, 33) 582: Gd = np.array([[surf((math.sin(t) * math.cos(f), math.cos(t), math.sin(t) * math.sin(f))) for t in th] for f in ph]) 583: pos, tri = O.grid_mesh(Gd) 584: pc = O.piece(name or f"puff_{side}", role, pos, tri, outward_from=c) 585: P = pc["pos"].reshape(33, 22, 3) 586: for i, f in enumerate(ph): 587: if not cap: # puckered folds running down the sleeve 588: P[i] += (P[i] - c) * (0.05 * math.sin(f * 8)) 589: else: # five folds, deepening toward the band 590: hgt = ((P[i] - c) @ up) / ext["down"] 591: deep = np.clip(-hgt, 0, 1) ** 1.2 592: P[i] += (P[i] - c) * (0.07 * math.sin(f * 5)) * deep[:, None] 593: pc["pos"] = P.reshape(-1, 3) 594: pc["nrm"] = O.vertex_normals(pc["pos"], pc["tri"]) 595: fit.bind(pc, blend={f"J_Bip_{side}_UpperArm": 0.8, f"J_Bip_{side}_Shoulder": 0.2}) 596: out = [pc] 597: if cap: 598: # tuck the sleeves inside: anything of them within the puff's height that reaches past its skin 599: # is drawn back under it (the skin under a costume is culled, so only the sleeves can show) 600: for pc_ in under or []: 601: Q = pc_["pos"] - c 602: loc = np.stack([Q @ outw, Q @ up, Q @ fwd], 1) 603: span = (loc[:, 1] < ext["up"]) & (loc[:, 1] > -ext["down"] * 0.95) 604: arm = (np.array([f"{side}_UpperArm" in n or f"{side}_Shoulder" in n for n in pc_["jnames"]])[pc_["J"]] 605: * pc_["W"]).sum(1) > 0.3 606: sel = span & arm 607: if not sel.any(): 608: continue 609: qs = surf_many(loc[sel]) 610: lim = np.linalg.norm(qs, axis=1) - 0.005 611: dist = np.linalg.norm(loc[sel], axis=1) 612: over = dist > lim 613: idx = np.nonzero(sel)[0][over] 614: scale = (lim[over] / np.maximum(dist[over], 1e-9))[:, None] 615: pc_["pos"][idx] = c + (pc_["pos"][idx] - c) * scale 616: pc_["nrm"] = O.vertex_normals(pc_["pos"], pc_["tri"]) 617: piping = piping or "leather" 618: m_ = measure(cg0) # again, now the sleeve is tucked in 619: if m_[0] is not None: 620: cg, r_band, band_r = m_ 621: band = np.array([cg + up * ext["down"] * 0.04 + (outw * math.cos(f) + fwd * math.sin(f)) 622: * ((band_r(math.atan2(math.sin(f), math.cos(f))) if band_r else r_band) + 0.002) 623: for f in np.linspace(0, 2 * np.pi, 33)]) 624: bd = O.pipe(f"{pc['material'][7:]}_band", piping, band, r=0.0055, seg=8, closed=True) 625: fit.bind(bd, rigid=f"J_Bip_{side}_UpperArm") # it rides the sleeve, not the puff's shoulder blend 626: bd["group"] = pc.get("group") 627: out.append(bd) 628: elif piping: 629: band = np.array([surf((math.cos(f), -0.55, math.sin(f))) for f in np.linspace(0, 2 * np.pi, 33)]) 630: out.append(O.inherit(O.pipe(f"{pc['material'][7:]}_band", piping, band, r=0.004 * k, seg=6, closed=True), pc)) 631: return _group(out, "doublet") 632: 633: 634: LIMBS = {"arm": ("UpperArm", "LowerArm", "Hand"), "leg": ("UpperLeg", "LowerLeg", "Foot")} 635: 636: 637: def _limb_frame(fit, side, Q, limb="arm"): 638: """Points Q against one limb in the reference pose: the distance along it from the top joint (upper 639: segment 0..1, lower 1..2), the unit radial direction off the bone, its radius, its angle round the 640: limb (0 outward, +90 forward, 180 toward the body or the other leg), and the upper segment's length.""" 641: B = fit.bone 642: j0, j1, j2 = (B[f"J_Bip_{side}_{n}"] for n in LIMBS[limb]) 643: L1, L2 = float(np.linalg.norm(j1 - j0)), float(np.linalg.norm(j2 - j1)) 644: d1, d2 = (j1 - j0) / L1, (j2 - j1) / L2 645: lower = (Q - j1) @ d2 > 0 646: t = np.where(lower, np.clip((Q - j1) @ d2, 0, L2), np.clip((Q - j0) @ d1, -0.3 * L1, L1)) 647: ax = np.where(lower[:, None], d2, d1) 648: foot = np.where(lower[:, None], j1 + t[:, None] * d2, j0 + t[:, None] * d1)2 more lines not shown.
read_file{"EndLine":950,"Path":"~/work/lowmarch/tools/outfit.py","StartLine":750}
input
{ "EndLine": 950, "Path": "~/work/lowmarch/tools/outfit.py", "StartLine": 750 }result, 202 lines
Showing lines 750-950 of 1272 750: d[1] = 0 751: dist = np.linalg.norm(d) 752: d /= max(dist, 1e-9) 753: r = over.cast(o, d, rmax=0.30, far=True) 754: if not np.isnan(r) and dist < r + clr[j]: 755: P[i, j] = o + d * (r + clr[j]) + np.array([0, P[i, j, 1] - o[1], 0]) 756: return P 757: 758: P = push_out(P) 759: pinned = np.zeros((seg, rows), bool) 760: pinned[:, 0] = True 761: P = drape(P, over, clr, pinned, steps=110, bend=0.4) 762: for j, t in enumerate(np.linspace(0, 1, rows)): # soft folds toward the hem 763: P[:, j] += rad * (0.006 * t * np.sin(ang * 9 + 0.7))[:, None] 764: P = push_out(P) # and nothing pokes through after settling 765: pos, tri = grid_mesh(P) 766: pc = piece(name, role, pos, tri, outward_from=nk + [0, -0.25, 0], axis=[0, 1, 0]) 767: fit.bind(pc, allow=("Neck", "UpperChest", "Shoulder", "Chest"), fallback="J_Bip_C_UpperChest") 768: # the hood, folded down: a thick roll around the back half of the ring 769: k = np.where(np.abs(ang) < math.radians(105))[0] 770: lift = top[k] + rad[k] * 0.012 + np.array([0, 0.016, 0]) 771: hood = pipe(f"{name}_hood", role, lift, r=0.024, seg=10) 772: w = np.abs(ang[k]) / math.radians(105) # the roll thins toward the shoulders 773: hp = hood["pos"].reshape(len(k), 11, 3) 774: hp[:] = lift[:, None] + (hp - lift[:, None]) * (1 - 0.55 * w ** 2)[:, None, None] 775: hood["pos"] = hp.reshape(-1, 3) 776: inherit(hood, pc) 777: return pc, P, hood 778: 779: 780: def shield(fit, name, side="L", radius=0.20, boss=0.045): 781: """A round wooden shield, painted with the house's arms, strapped to the forearm's outer side: 782: a shallow dome in the signature colour, a cream chevron, a steel rim and boss.""" 783: E, H = fit.bone[f"J_Bip_{side}_LowerArm"], fit.bone[f"J_Bip_{side}_Hand"] 784: ax = (H - E) / np.linalg.norm(H - E) 785: lat = np.array([-1.0 if side == "L" else 1.0, 0, 0.0]) 786: lat -= ax * (lat @ ax) 787: lat /= np.linalg.norm(lat) 788: centre = E + ax * np.linalg.norm(H - E) * 0.48 + lat * 0.075 789: up = -ax # the shield's top points up the arm (toward the elbow) 790: fw = np.cross(lat, up) 791: rows, seg, depth = 9, 48, 0.035 792: ph = np.linspace(0, 2 * math.pi, seg + 1) 793: P = np.zeros((seg + 1, rows, 3)) 794: for j, t in enumerate(np.linspace(0, 1, rows)): 795: P[:, j] = centre + lat * depth * (1 - t * t) + np.outer(radius * t * np.cos(ph), up) + np.outer(radius * t * np.sin(ph), fw) 796: pos, tri, outer = thick_grid(P, 0.010, outward_from=centre - lat * 0.2) 797: face = piece(name, "signature", pos, tri) 798: surf = lambda u, v: centre + lat * (depth * (1 - (u * u + v * v)) + 0.0012) + up * u * radius + fw * v * radius 799: nrm_at = lambda u, v: lat + (up * u + fw * v) * 2 * depth / radius 800: chev = [(-0.48, -0.62), (0.10, -0.02), (-0.48, 0.58)] if side == "L" else [(-0.48, 0.62), (0.10, 0.02), (-0.48, -0.58)] 801: line = [] 802: for (u0, v0), (u1, v1) in zip(chev[:-1], chev[1:]): 803: for t in np.linspace(0, 1, 12, endpoint=False): 804: line.append((u0 + (u1 - u0) * t, v0 + (v1 - v0) * t)) 805: line.append(chev[-1]) 806: pts = np.array([surf(u, v) for u, v in line]) 807: nr = np.array([nrm_at(u, v) for u, v in line]) 808: device = ribbon(f"{name}_device", "heraldry", pts, width=radius * 0.24, lift=0.0, normals=nr) 809: rim = pipe(f"{name}_rim", "steel", outer[:-1, -1], r=0.0065, seg=8, closed=True) 810: bs, _ = dome(f"{name}_boss", "steel", centre + lat * (depth - 0.004), lat, up, boss, 0.026, rows=7) 811: out = [face, device, rim, bs] 812: for pc in out: 813: fit.bind(pc, rigid=f"J_Bip_{side}_LowerArm") 814: pc["group"] = "shield" 815: return out 816: 817: 818: # ---- dress, hairdo ------------------------------------------------------------------------- 819: def closed_grid_mesh(P): 820: """(U, V, 3) grid whose U direction wraps around (a skirt) -> (pos, tri).""" 821: U, V = P.shape[:2] 822: idx = np.arange(U * V).reshape(U, V) 823: a, b = idx[:, :-1], np.roll(idx, -1, 0)[:, :-1] 824: c, d = np.roll(idx, -1, 0)[:, 1:], idx[:, 1:] 825: tri = np.concatenate([np.stack([a, b, c], -1).reshape(-1, 3), np.stack([a, c, d], -1).reshape(-1, 3)]) 826: return P.reshape(-1, 3), tri 827: 828: 829: def skirt(fit, name, role, under, collide, y_top, length, flare=0.26, seg=56, rows=20, folds=9, fold_depth=0.012, 830: clear=(0.004, 0.02)): 831: """A full skirt: a closed ring at the waist cast onto `under`, belling out to the hem, settled 832: by the cloth solve against the legs. Simulated in the viewer as closed cloth (no seam).""" 833: cz = fit.bone["J_Bip_C_Hips"][2] 834: o = np.array([0.0, y_top, cz]) 835: ang = np.linspace(0, 2 * math.pi, seg, endpoint=False) 836: rad = np.stack([np.sin(ang), np.zeros_like(ang), np.cos(ang)], 1) 837: top = [] 838: for d in rad: 839: r = under.cast(o, d, rmax=0.3, far=True) 840: top.append(o + d * ((0.13 if np.isnan(r) else r) + clear[0])) 841: top = np.array(top) 842: P = np.zeros((seg, rows, 3)) 843: for j, t in enumerate(np.linspace(0, 1, rows)): 844: bell = flare * (1 - (1 - t) ** 1.6) # flares fast below the hips, then falls 845: wave = fold_depth * t * np.sin(ang * folds + 0.4) 846: P[:, j] = top + rad * (bell + wave)[:, None] + np.array([0, -length * t, 0]) 847: pinned = np.zeros((seg, rows), bool) 848: pinned[:, 0] = True 849: P = drape(P, collide, clear[0] + (clear[1] - clear[0]) * np.linspace(0, 1, rows), pinned, steps=60, closed=True) 850: pos, tri = closed_grid_mesh(P) 851: pc = piece(name, role, pos, tri, outward_from=o, axis=[0, 1, 0]) 852: fit.bind(pc, allow=("Hips", "UpperLeg"), fallback="J_Bip_C_Hips") 853: pc["grid"] = (seg, rows) 854: pc["closed"] = True 855: return pc, P 856: 857: 858: def updo(fit, hair_role="hair", ribbon_role="signature"): 859: """A braided bun at the back of the head, a ribbon tied on it, and one cowlick strand rising 860: from the crown. Offsets are measured on the female sample head and follow the head's scale.""" 861: H = fit.world["J_Bip_C_Head"] 862: hs = float(np.linalg.norm(H[:3, 0])) 863: h = H[:3, 3] 864: at = lambda x, y, z: h + hs * np.array([x, y, z]) 865: out = [] 866: c = at(0.0, 0.118, 0.142) 867: out.append(ball("bun", hair_role, c, 0.046 * hs, seg=20, rows=12, squash=(1.0, 0.86, 0.72))) 868: # the braid wound around the bun: two strands twisting around a ring 869: ring_r, n = 0.050 * hs, 96 870: th = np.linspace(0, 2 * math.pi, n, endpoint=False) 871: for k, ph in enumerate((0.0, math.pi)): 872: tw = th * 7 + ph 873: rr = ring_r + 0.008 * hs * np.cos(tw) 874: zz = 0.008 * hs * np.sin(tw) 875: pts = c + np.stack([rr * np.cos(th), rr * np.sin(th) * 0.86, -0.012 * hs + zz], 1) 876: out.append(pipe(f"braid{k}", hair_role, pts, r=0.0085 * hs, seg=7, closed=True)) 877: # ribbon: two loops and a knot on top of the bun 878: knot = c + hs * np.array([0.0, 0.040, -0.004]) 879: out.append(ball("ribbon_knot", ribbon_role, knot, 0.011 * hs, seg=10, rows=7)) 880: for sx in (-1, 1): 881: out.append(ball(f"ribbon_loop{(sx + 1) // 2}", ribbon_role, knot + hs * np.array([sx * 0.030, 0.006, 0.004]), 882: 0.022 * hs, seg=12, rows=8, squash=(1.0, 0.55, 0.32))) 883: # the cowlick: a tapered strand rising from the crown and curling forward 884: t = np.linspace(0, 1, 20) 885: pts = np.stack([0.003 * np.sin(t * 3), 0.236 + 0.062 * np.sin(t * 2.2), -0.004 - 0.050 * t - 0.012 * np.sin(t * 5)], 1) 886: pts = h + hs * pts 887: st = pipe("cowlick", hair_role, pts, r=0.013 * hs, seg=10) 888: sp = st["pos"].reshape(len(t), 11, 3) 889: off = sp - pts[:, None] 890: off[..., 0] *= 0.35 # a flat lock, not a round stalk 891: sp[:] = pts[:, None] + off * (1 - 0.9 * t ** 0.8)[:, None, None] 892: st["pos"] = sp.reshape(-1, 3) 893: out.append(st) 894: for pc in out: 895: fit.bind(pc, rigid="J_Bip_C_Head") 896: pc["group"] = "hair" 897: return out 898: 899: 900: def sabaton(fit, name, side, role="metal", pad=0.010, ridges=3, seg=26, rows=14): 901: """A steel shoe over the whole foot (hides the base model's toes), built as a shoe last from 902: the foot's measurements: sole outline rounded at heel and toe and widest at the ball, top 903: rising from a rounded toe over the instep to the ankle at the heel. Lame ridges follow its 904: cross-section over the instep. Rides the foot bone. 905: (A squashed ellipsoid read as a triangular hoof; a shell projected onto the foot's convex 906: hull creased on the hull's facets.)""" 907: w = fit.weight((f"{side}_Foot", f"{side}_ToeBase")) 908: P = fit.pos[w > 0.5] 909: P = P[(P[:, 0] < 0.01) if side == "L" else (P[:, 0] > -0.01)] 910: lo, hi = P.min(0), P.max(0) 911: sole = lo[1] - 0.003 912: ankle = fit.bone[f"J_Bip_{side}_Foot"][1] 913: z_heel, z_toe = hi[2] + pad, lo[2] - pad # the foot points -z 914: width = (hi[0] - lo[0]) + 2 * pad 915: S = np.linspace(0, 1, seg) 916: # centreline: the foot's middle at each station, smoothed 917: cx = np.array([np.median(P[np.abs(P[:, 2] - (z_heel + t * (z_toe - z_heel))) < 0.02, 0]) 918: if (np.abs(P[:, 2] - (z_heel + t * (z_toe - z_heel))) < 0.02).any() else (lo[0] + hi[0]) / 2 for t in S]) 919: cx = np.convolve(np.pad(cx, 3, mode="edge"), np.ones(7) / 7, "valid") 920: ends = np.sin(np.pi * np.clip(S, 0, 1)) ** 0.42 # rounds the heel and the toe 921: half_w = width / 2 * ends * (0.80 + 0.20 * np.sin(np.pi * np.clip(S * 1.2, 0, 1))) # widest at the ball 922: tall = (ankle + 0.02 - sole) * (1 - 0.62 * np.clip((S - 0.25) / 0.6, 0, 1) ** 0.8) # ankle at the heel, low toe 923: tall = np.maximum(tall * np.sin(np.pi * np.clip(S, 0, 1)) ** 0.22, 0.004) 924: phi = np.linspace(0, np.pi, rows) 925: G = np.zeros((seg, rows, 3)) 926: for i, t in enumerate(S): 927: z = z_heel + t * (z_toe - z_heel) 928: G[i] = np.stack([cx[i] + half_w[i] * np.cos(phi), sole + tall[i] * np.sin(phi), np.full(rows, z)], 1) 929: pos, tri = grid_mesh(G) 930: c = np.array([(lo[0] + hi[0]) / 2, sole, (z_heel + z_toe) / 2]) 931: pc = piece(name, role, pos, tri, outward_from=c - [0, 0.05, 0]) 932: out = [pc] 933: for k, t in enumerate(np.linspace(0.50, 0.74, ridges)): # lames over the instep 934: i = int(round(t * (seg - 1))) 935: ring = G[i, 1:-1] + np.stack([np.cos(phi[1:-1]), np.sin(phi[1:-1]) * 1.0, np.zeros(rows - 2)], 1) * 0.0018 936: out.append(pipe(f"{name}_ridge{k}", role, ring, r=0.0024)) 937: for q_ in out: 938: fit.bind(q_, rigid=f"J_Bip_{side}_Foot") 939: return out 940: 941: 942: def knight_dress(fit): 943: """A blonde knight-princess: a long blue dress with a white petticoat edge, a fitted steel 944: breastplate, small spaulders, steel gauntlets and armoured boots, a two-handed sword with a 945: gold hilt, and her hair up in a braided bun with a ribbon.""" 946: B = fit.bone 947: nk, hips = B["J_Bip_C_Neck"], B["J_Bip_C_Hips"] 948: knee = B["J_Bip_L_LowerLeg"][1] 949: out = [] 950: