agent (cont.)

+3:19
  • read_file{"EndLine":1407,"Path":"~/work/lowmarch/tools/vroid_portrait.py","StartLine":700}

    input

    {
      "EndLine": 1407,
      "Path": "~/work/lowmarch/tools/vroid_portrait.py",
      "StartLine": 700
    }

    result, 709 lines

    Showing lines 700-1407 of 1407
    700:     mouth = verts("mouth")
    701:     eL, eR = lm["eyeL"], lm["eyeR"]
    702:     ex = abs(eR[0] - eL[0]) / 2                                  # half the distance between the eyes
    703:     span = lm["span"]
    704:     zf = pos[:, 2].min() - 0.05                                  # in front of the face (it faces -z)
    705:     mo = lm["mouth"]
    706:     mhw = 0.55 * np.ptp(mouth[:, 0])                             # half the mouth's width (the inner mouth spans it)
    707: 
    708:     def eye_box(c):
    709:         """Half the visible eye's width and height: VRoid's iris card spans the opening's height, and
    710:         the opening is about 1.6 irises wide (the white card is far bigger than what shows)."""
    711:         w = iris[np.sign(iris[:, 0]) == np.sign(c[0])]
    712:         return 0.8 * np.ptp(w[:, 0]), np.ptp(w[:, 1]) / 2
    713: 
    714:     def drop(x, y):
    715:         """A point on the face seen straight on: the nearest surface hit from the front."""
    716:         t = surf.cast(np.array([x, y, zf]), np.array([0.0, 0.0, 1.0]), rmax=0.3, far=False)
    717:         return None if np.isnan(t) else np.array([x, y, zf + t])
    718: 
    719:     def to_uv(P):
    720:         _, cp, ti = surf.query(P)
    721:         T = pos[tri[ti]]
    722:         v0, v1, v2 = T[:, 1] - T[:, 0], T[:, 2] - T[:, 0], cp - T[:, 0]
    723:         d00, d01, d11 = (v0 * v0).sum(1), (v0 * v1).sum(1), (v1 * v1).sum(1)
    724:         d20, d21 = (v2 * v0).sum(1), (v2 * v1).sum(1)
    725:         den = np.where(np.abs(d00 * d11 - d01 * d01) < 1e-20, 1e-20, d00 * d11 - d01 * d01)
    726:         b1 = (d11 * d20 - d01 * d21) / den
    727:         b2 = (d00 * d21 - d01 * d20) / den
    728:         U = uv[tri[ti]]
    729:         return U[:, 0] * (1 - b1 - b2)[:, None] + U[:, 1] * b1[:, None] + U[:, 2] * b2[:, None]
    730: 
    731:     def curve(ctrl, n=24):
    732:         """A smooth stroke through control points (x, y), quadratic B-spline-ish via Chaikin."""
    733:         Q = np.asarray(ctrl, float)
    734:         for _ in range(3):
    735:             if len(Q) < 3:
    736:                 break
    737:             Q = np.vstack([Q[:1]] + [np.vstack([0.75 * Q[i] + 0.25 * Q[i + 1], 0.25 * Q[i] + 0.75 * Q[i + 1]])
    738:                                      for i in range(len(Q) - 1)] + [Q[-1:]])
    739:         t = np.linspace(0, 1, n)
    740:         L = np.r_[0, np.cumsum(np.linalg.norm(np.diff(Q, axis=0), axis=1))]
    741:         return np.stack([np.interp(t * L[-1], L, Q[:, 0]), np.interp(t * L[-1], L, Q[:, 1])], 1)
    742: 
    743:     a = float(np.clip(amount, 0, 1))
    744:     strokes = []                                                 # (2D curve, width scale, darkness scale)
    745:     for c, sd in ((eL, -1), (eR, 1)):
    746:         ew, eh = eye_box(c)
    747:         out = sd                                                 # +x is the character's right
    748:         # under the eye: one arc below the lower lid; a second, fainter, when old
    749:         strokes.append((curve([(c[0] - out * 0.45 * ew, c[1] - 0.80 * eh), (c[0], c[1] - 1.05 * eh),
    750:                                (c[0] + out * 0.55 * ew, c[1] - 0.85 * eh)]), 1.0, 1.0))
    751:         if a > 0.55:
    752:             strokes.append((curve([(c[0] - out * 0.15 * ew, c[1] - 1.35 * eh), (c[0] + out * 0.35 * ew, c[1] - 1.40 * eh),
    753:                                    (c[0] + out * 0.75 * ew, c[1] - 1.20 * eh)]), 0.8, 0.7))
    754:         # from the nose's wing round the mouth
    755:         nose_y = lm["nose"][1]
    756:         strokes.append((curve([(out * 0.32 * ex, nose_y + 0.03 * span), (out * 0.56 * ex, nose_y - 0.10 * span),
    757:                                (out * (mhw + 0.18 * ex), mo[1] + 0.02 * span)]), 1.2, 1.0))
    758:         # crow's feet at the outer corner
    759:         if a > 0.4:
    760:             oc = np.array([c[0] + out * 1.05 * ew, c[1]])
    761:             for ang in ((-18, 1.0), (8, 0.8)) if a < 0.75 else ((-25, 1.0), (0, 0.9), (22, 0.8)):
    762:                 d = np.radians(ang[0])
    763:                 tip = oc + np.array([out * np.cos(d), np.sin(d)]) * 0.55 * ew
    764:                 strokes.append((curve([oc, (oc + tip) / 2, tip], 10), 0.7 * ang[1], 0.8))
    765:         # down from the mouth's corner
    766:         if a > 0.85:
    767:             strokes.append((curve([(out * (mhw + 0.06 * ex), mo[1] - 0.06 * span),
    768:                                    (out * (mhw + 0.10 * ex), mo[1] - 0.30 * span)], 14), 0.9, 0.85))
    769:     # a frown between the brows
    770:     if a > 0.3:
    771:         y0 = (eL[1] + eR[1]) / 2
    772:         _, eh = eye_box(eL)
    773:         for sd in (-1, 1):
    774:             strokes.append((curve([(sd * 0.10 * ex, y0 + 0.9 * eh), (sd * 0.13 * ex, y0 + 1.9 * eh)], 10), 0.85, 0.8))
    775:     # paint: each stroke dropped onto the face, into texture space, tapered at both ends
    776:     src = None
    777:     for p in face:
    778:         m = v.j["materials"][p["mi"]]
    779:         t = m.get("pbrMetallicRoughness", {}).get("baseColorTexture")
    780:         if t is not None:
    781:             src = v.j["textures"][t["index"]]["source"]
    782:             break
    783:     if src is None:
    784:         return
    785:     tex = v.image(src).copy()
    786:     H, W = tex.shape[:2]
    787:     S = 2                                                        # supersampled mask
    788:     mask = Image.new("L", (W * S, H * S), 0)
    789:     dr = ImageDraw.Draw(mask)
    790:     base_w = 4.2 * W / 1024 * (0.7 + 0.4 * a)
    791:     for C, ws, ds in strokes:
    792:         P = [drop(x, y) for x, y in C]
    793:         P = np.array([q for q in P if q is not None])
    794:         if len(P) < 3:
    795:             continue
    796:         U = to_uv(P) * [W * S, H * S]
    797:         n = len(U)
    798:         for i in range(n - 1):
    799:             t = (i + 0.5) / (n - 1)
    800:             w = base_w * S * ws * np.sin(np.pi * np.clip(t, 0.05, 0.95)) ** 0.7
    801:             dr.line([tuple(U[i]), tuple(U[i + 1])], fill=int(255 * min(1.0, ds)), width=max(1, int(round(w))))
    802:     mk = np.asarray(mask.resize((W, H), Image.LANCZOS), float) / 255
    803:     dark = (0.30 + 0.22 * a) * mk
    804:     tex = tex.astype(float)
    805:     tex[..., :3] *= (1 - dark)[..., None]
    806:     v._img[src] = np.clip(tex, 0, 255).astype(np.uint8)
    807: 
    808: 
    809: MOUTH_ROOM = 0.002      # m: an open mouth's inside stays this far within the face's lower outline
    810: 
    811: 
    812: def mouth_room(v, mo, pose, yaws=(0.0, 30.0, -30.0)):
    813:     """How far (m) the mouth's inside (teeth, tongue, its dark) stays above the face's lower outline, seen from the
    814:     front and turned: the least, over columns 2 mm wide, of its lowest point less the face skin's. Negative: it
    815:     shows below the chin."""
    816:     prs = v.primitives(mo, pose)
    817:     # the face skin as points along its triangles' edges, so every column holds a piece of its outline
    818:     F = [p["pos"][p["tri"]] for p in prs if role_of(p["material"]) == "face" and len(p["tri"])]
    819:     M = [p["pos"][np.unique(p["tri"])] for p in prs if role_of(p["material"]) == "mouth" and len(p["tri"])]
    820:     if not F or not M:
    821:         return np.inf
    822:     T, M = np.concatenate(F), np.concatenate(M)
    823:     F = np.concatenate([T[:, i] * (1 - t) + T[:, (i + 1) % 3] * t for i in range(3) for t in np.linspace(0, 1, 6)[:-1]])
    824:     least = np.inf
    825:     for yaw in yaws:
    826:         a = np.radians(yaw)
    827:         fx = F[:, 0] * np.cos(a) + F[:, 2] * np.sin(a)
    828:         mx = M[:, 0] * np.cos(a) + M[:, 2] * np.sin(a)
    829:         fb, mb = np.floor(fx / 0.002).astype(int), np.floor(mx / 0.002).astype(int)
    830:         for b in np.unique(mb):
    831:             f = F[fb == b, 1]
    832:             if len(f):
    833:                 least = min(least, M[mb == b, 1].min() - f.min())
    834:     return least
    835: 
    836: 
    837: def hold_mouth(v, mo, pose):
    838:     """A recipe's mouth shapes (Fcl_MTH_*, together) scaled down until the mouth's inside stays MOUTH_ROOM within the
    839:     face, so weights past VRoid's 1 (a shout) open each face only as far as it holds: on a long jaw the lower teeth
    840:     and the mouth's floor came out under the chin. Returns the shapes and the scale (1: unchanged)."""
    841:     keys = [k for k in mo if "MTH_" in k and mo[k] > 0]
    842:     if not keys or mouth_room(v, mo, pose) >= MOUTH_ROOM:
    843:         return mo, 1.0
    844:     scaled = lambda s: dict(mo, **{k: mo[k] * s for k in keys})
    845:     lo, hi = 0.0, 1.0
    846:     for _ in range(7):
    847:         mid = (lo + hi) / 2
    848:         lo, hi = (mid, hi) if mouth_room(v, scaled(mid), pose) >= MOUTH_ROOM else (lo, mid)
    849:     return scaled(lo), lo
    850: 
    851: 
    852: def reshape(prims, roles, lm, sh):
    853:     """Face length, sculpting, eye size/tilt and mouth width (skeleton and expression are applied
    854:     earlier, when the primitives are built)."""
    855:     ey, cy = lm["eye_y"], lm["chin"][1]
    856:     span = ey - cy
    857:     if sh["face_len"]:
    858:         from vrm import bone_weight
    859:         for p, r in zip(prims, roles):
    860:             if r in SCULPT_ROLES:
    861:                 t = np.clip((ey - p["pos"][:, 1]) / span, 0, None)
    862:                 d = sh["face_len"] * span * np.minimum(t, 1.0)
    863:                 if r == "body" and "J" in p:            # the neck below the head stays where the clothes were fitted
    864:                     d = d * np.clip(bone_weight(p, ("Head",)), 0, 1)
    865:                 p["pos"][:, 1] -= d
    866:         lm = dict(lm, chin=lm["chin"] - [0, sh["face_len"] * span, 0])
    867:     sculpt(prims, roles, lm, sh)
    868:     for p, r in zip(prims, roles):
    869:         P = p["pos"]
    870:         if sh["mouth"] != 1.0 and r == "mouth":
    871:             P[:, 0] = lm["mouth"][0] + (P[:, 0] - lm["mouth"][0]) * sh["mouth"]
    872:         if r in ("iris", "highlight") and sh.get("iris", 1.0) != 1.0:      # smaller irises read older
    873:             for c in (lm["eyeL"], lm["eyeR"]):
    874:                 side = (P[:, 0] < 0) if c[0] < 0 else (P[:, 0] >= 0)
    875:                 q = P[side] - c
    876:                 q[:, :2] *= sh["iris"]
    877:                 P[side] = c + q
    878:         if r in ("iris", "white", "highlight", "line") and (sh["eye"] != 1 or sh["eye_tilt"]):
    879:             for c in (lm["eyeL"], lm["eyeR"]):
    880:                 side = (P[:, 0] < 0) if c[0] < 0 else (P[:, 0] >= 0)
    881:                 q = P[side] - c
    882:                 q[:, :2] *= sh["eye"]
    883:                 q[:, 1] += sh["eye_tilt"] * np.sign(c[0]) * q[:, 0] * 0.4
    884:                 P[side] = c + q
    885: 
    886: 
    887: def keep_lash_fan(prims, now, k, lines, closure):
    888:     """A shut eye closed further (`lid_gap`) moves its lash fan (VRoid's FaceEyelash) with the lid edge instead of
    889:     folding it past shut: the fan stays as the expression's own close leaves it, shifted as the edge shifts at each x.
    890:     now: the primitives before the extra close; k: the eyeline's index."""
    891:     E = prims[k]["pos"]
    892:     for side, (_, _, edge, _) in lines.items():
    893:         if closure.get(side, 0.0) < 0.9:
    894:             continue
    895:         o = np.argsort(now[k]["pos"][edge, 0])
    896:         d = E[edge][o] - now[k]["pos"][edge][o]
    897:         for p, q in zip(prims, now):
    898:             if "FaceEyelash" not in p["material"]:
    899:                 continue
    900:             m = (q["pos"][:, 0] < 0) == (side == "L")
    901:             for ax in range(3):
    902:                 p["pos"][m, ax] = q["pos"][m, ax] + np.interp(q["pos"][m, 0], now[k]["pos"][edge][o, 0], d[:, ax])
    903: 
    904: 
    905: class Portrait:
    906:     def __init__(self, path, morphs=None, pose=BUST_POSE, shape=None, hair_from=None, costume=None,
    907:                  mouth="curve", world=None, ref_pose=BUST_POSE, hair_trim=None):
    908:         """mouth: how the closed mouth is drawn. 'texture' = VRoid's painted lip line, thickened;
    909:         'texture+lip' = that plus a lower-lip shade; 'drawn' = an FE8-style mouth between the
    910:         projected mouth corners; 'none' = geometry only (the line disappears when closed)."""
    911:         self.mouth = mouth
    912:         self.v = VRM(path)
    913:         sh = dict(NEUTRAL, **(shape or {}))
    914:         mo = dict(sh["rest"])
    915:         for k_, w_ in (morphs or {}).items():
    916:             mo[k_] = min(1.0, mo.get(k_, 0.0) + w_)
    917:         if sh["fangs"] < 1.0:                            # some faces' teeth have fangs (sample V's); 0 files them away
    918:             mo["Fcl_HA_Short"] = max(mo.get("Fcl_HA_Short", 0.0), 1.0 - sh["fangs"])
    919:         # everything is built in the reference pose (arms down), then posed through the skeleton
    920:         target_pose = bone_pose(self.v, sh, pose)
    921:         pose = bone_pose(self.v, sh, ref_pose)
    922:         mo, self.mouth_hold = hold_mouth(self.v, mo, pose)
    923:         closure = eye_closure(mo)
    924:         lines = None
    925:         if max(closure.values()) > 0.05 or sh["lash"] != 1.0:   # the eyeline open, and how far a shut eye must close
    926:             eyes = {k_: w_ for k_, w_ in mo.items() if "EYE_" not in k_ and "ALL_" not in k_}
    927:             now = self.v.primitives(mo, pose)
    928:             ln = [i_ for i_, p_ in enumerate(now) if "FaceEyeline" in p_["material"]]
    929:             if ln:
    930:                 prs = [self.v.primitives(eyes, pose)[ln[0]], now[ln[0]],
    931:                        self.v.primitives(dict(eyes, Fcl_EYE_Close=1.0), pose)[ln[0]]]
    932:                 eye = eye_lines(prs[0])
    933:                 # the character's one lash size: set on the open lash, which every closed lid is moved from
    934:                 lines = (ln[0], lash_size(prs[0]["pos"].copy(), prs[0]["uv"], eye, sh["lash"]), eye, now)
    935:                 further = lid_gap(prs[1]["pos"], prs[2]["pos"], prs[0]["pos"], lines[2], prs[0]["uv"], prs[0]["tri"],
    936:                                   self.v.material_texture(prs[0]["mi"]))
    937:         mo = hide_closed_irises(mo, further if lines else None)
    938:         self.pose_now = target_pose
    939:         self.pose_ref = pose
    940:         self.shape = sh
    941:         self.prims = self.v.primitives(mo, pose)
    942:         if lines:                                        # a closing lid is the model's own open lash, moved
    943:             k_, P_open, eye, now = lines
    944:             p_ = self.prims[k_]
    945:             keep_lash_weight(p_, P_open, p_["uv"], eye, closure)
    946:             lash_size(p_["pos"], p_["uv"], {s_: v_ for s_, v_ in eye.items() if closure[s_] <= 0.05}, sh["lash"])
    947:             keep_lash_fan(self.prims, now, k_, eye, closure)
    948:             for side, (up, others, edge, _) in eye.items():   # a shut eye is one closed lid:
    949:                 if closure[side] < 0.9:
    950:                     continue
    951:                 if others:                                  # its lower line goes,
    952:                     p_["tri"] = p_["tri"][~np.isin(p_["tri"], np.concatenate(others)).all(1)]
    953:                 m = np.isin(p_["tri"], up).all(1)           # and its lash is drawn solid (export_glb.fill_lid):
    954:                 self.prims.append(dict(p_, tri=p_["tri"][m], lid_fill=float(p_["uv"][edge, 1].max())))
    955:                 p_["tri"] = p_["tri"][~m]                   # the open lash's pale streaks and hollows read as
    956:                                                             # shine beside an eye, but split a lid over skin
    957:         if hair_from:                                    # swap in another model's hair
    958:             hv = VRM(hair_from)
    959:             hp = hv.primitives(None, ref_pose)
    960:             hroles = [role_of(p["material"]) for p in hp]
    961:             src = landmarks(hp, hroles)
    962:             dst = landmarks(self.prims, [role_of(p["material"]) for p in self.prims])
    963:             k = (abs(dst["eyeR"][0] - dst["eyeL"][0]) / abs(src["eyeR"][0] - src["eyeL"][0])
    964:                  + (dst["eye_y"] - dst["chin"][1]) / (src["eye_y"] - src["chin"][1])) / 2
    965:             c_src = (src["eyeL"] + src["eyeR"]) / 2
    966:             c_dst = (dst["eyeL"] + dst["eyeR"]) / 2
    967:             hair = [p for p in hp if "_HAIR" in p["material"]]
    968:             for p in hair:
    969:                 p["pos"] = c_dst + (p["pos"] - c_src) * k
    970:                 n_ = len(p["pos"])                       # rides our head bone from here on
    971:                 p["J"], p["W"], p["jnames"] = np.zeros((n_, 4), np.int64), np.tile([1.0, 0, 0, 0], (n_, 1)), ["J_Bip_C_Head"]
    972:             self.prims = [p for p in self.prims if "_HAIR" not in p["material"]] + hair
    973:             self._hair_v = hv
    974:         if hair_trim:                                    # drop hair pieces reaching past |x| = hair_trim (e.g. twin tails)
    975:             self.prims = [p for p in self.prims if "_HAIR" not in p["material"]
    976:                           or np.abs(p["pos"][np.unique(p["tri"]), 0]).max() <= hair_trim]
    977:         self.roles = [p.get("role") or role_of(p["material"]) for p in self.prims]
    978:         for side, c in eye_closure(mo).items():          # a shut eye shows no white (it can poke between the lids)
    979:             if c < 0.9:
    980:                 continue
    981:             for p, r in zip(self.prims, self.roles):
    982:                 if r == "white" and len(p["tri"]):
    983:                     cx = p["pos"][p["tri"]].mean(1)[:, 0]
    984:                     p["tri"] = p["tri"][(cx < 0) != (side == "L")]
    985:         self.lm = landmarks(self.prims, self.roles)
    986:         if costume:                                      # replace VRoid's clothes with ours
    987:             import outfit
    988:             fit = outfit.Fit(self.v, pose, self.prims, self.roles)
    989:             import rig
    990:             fit.grip = rig.grip_points(self.v, sh, ref_pose)  # where each fist closes (weapons sit there)
    991:             keep_ = [k for k, r in enumerate(self.roles) if r != "cloth"]
    992:             self.prims = [self.prims[k] for k in keep_]
    993:             self.roles = [self.roles[k] for k in keep_]
    994:             costume = outfit.COSTUMES[costume] if isinstance(costume, str) else costume
    995:             fit.keep_skin = ()                       # a costume may leave skin bare (fit.keep_skin = bones)
    996:             for pc in costume(fit):
    997:                 self.prims.append(pc)
    998:                 self.roles.append(pc["role"])
    999:         # body skin below the neck is always under clothes in a bust; drop it so it can't poke through
    1000:         cy = self.lm["chin"][1]
    1001:         from vrm import bone_weight
    1002:         for p, r in zip(self.prims, self.roles):
    1003:             if r != "body":
    1004:                 continue
    1005:             if costume:                     # keep head, neck and upper chest (the throat shows in the collar opening)
    1006:                 wv = bone_weight(p, ("Head", "Neck", "UpperChest") + tuple(getattr(fit, "keep_skin", ())))
    1007:                 p["tri"] = p["tri"][(wv[p["tri"]] >= 0.5).all(1)]
    1008:                 if getattr(fit, "drop_skin", None) is not None:      # a costume may hide the skin it covers
    1009:                     p["tri"] = p["tri"][~fit.drop_skin(p)[p["tri"]].all(1)]
    1010:             else:
    1011:                 T = p["pos"][p["tri"]]
    1012:                 head = T[:, :, 1].min(1) > cy - 0.02
    1013:                 neck = (T[:, :, 1].min(1) > cy - 0.14) & (np.abs(T[:, :, 0]).max(1) < 0.055)
    1014:                 p["tri"] = p["tri"][head | neck]
    1015:         for pc in world or []:              # scenery: does not turn with the character
    1016:             self.prims.append(pc)
    1017:             self.roles.append(pc["role"])
    1018:         # framing uses the unshaped face at the base head size, so head-size changes still show
    1019:         self.span = (self.lm["eye_y"] - self.lm["chin"][1]) / sh["head"]
    1020:         reshape(self.prims, self.roles, self.lm, sh)
    1021:         strip_blush(self.prims, self.roles, self.v, sh["blush"])
    1022:         face_lines(self.prims, self.roles, self.v, sh["age_lines"])
    1023:         lm_now = landmarks(self.prims, self.roles)          # after the sculpt
    1024:         names, Wn = self.v.nodes_by_name(), self.v.node_world(pose)
    1025:         neck = (Wn[names["J_Bip_C_Neck"]][:3, 3], Wn[names["J_Bip_C_Head"]][:3, 3]) \
    1026:             if "J_Bip_C_Neck" in names and "J_Bip_C_Head" in names else None
    1027:         face_normals(self.prims, self.roles, lm_now, sh["face_normals"], sh["hair_normals"], neck=neck)
    1028:         for pc, rl in shadow_cards(self.prims, self.roles, lm_now, sh["shadow_cards"], neck):
    1029:             self.prims.append(pc)
    1030:             self.roles.append(rl)
    1031:         if pose is not target_pose and any(not np.allclose(pose.get(k_, np.eye(4)), target_pose.get(k_, np.eye(4)))
    1032:                                            for k_ in set(pose) | set(target_pose)):
    1033:             repose(self.v, [p for p in self.prims if not p.get("world")], pose, target_pose)
    1034:         names = self.v.nodes_by_name()
    1035:         Wn = self.v.node_world()
    1036:         self.eye = (Wn[names["J_Adj_L_FaceEye"]][:3, 3] + Wn[names["J_Adj_R_FaceEye"]][:3, 3]) / 2
    1037:         self.chin_y = self.lm["chin"][1]
    1038:         self.tex = {}
    1039:         for k, p in enumerate(self.prims):
    1040:             if self.roles[k] in ("line", "brow", "iris", "highlight", "white", "hair", "mouth"):
    1041:                 src = self._hair_v if (hair_from and "_HAIR" in p["material"]) else self.v
    1042:                 t = src.material_texture(p["mi"])
    1043:                 if t is not None and self.roles[k] == "line":
    1044:                     # VRoid's upper lid is a thick graded band over the iris; keep its dark core only
    1045:                     t = t.copy()
    1046:                     t[..., 3] = np.where(t[..., :3].mean(-1) < LID_CORE, t[..., 3], 0)
    1047:                 if t is not None:
    1048:                     self.tex[k] = t
    1049:         # painted face marks (lip line, nose) from the face texture, grown so they survive the vote
    1050:         from scipy.ndimage import binary_dilation, label
    1051:         self.marks = {}
    1052:         self.mouth_pts = None
    1053:         self.mouth_curve = None
    1054:         for k, p in enumerate(self.prims):
    1055:             if self.roles[k] != "face":
    1056:                 continue
    1057:             t = self.v.material_texture(p["mi"])
    1058:             if t is None:
    1059:                 continue
    1060:             th, tw = t.shape[:2]
    1061:             vv, uu = np.mgrid[0:th, 0:tw]
    1062:             vv, uu = (vv + 0.5) / th, (uu + 0.5) / tw
    1063:             win = ((uu > MARK_WINDOW["u"][0]) & (uu < MARK_WINDOW["u"][1])
    1064:                    & (vv > MARK_WINDOW["v"][0]) & (vv < MARK_WINDOW["v"][1]))
    1065:             raw = (t[..., :3].mean(-1) / 255 < FACE_MARK) & (t[..., 3] > 0) & win
    1066:             grown = binary_dilation(raw, iterations=MARK_GROW) & win
    1067:             # 2 = mouth (dark line), 1 = nose mark (one tone softer)
    1068:             self.marks[k] = np.where(grown, np.where(vv >= MARK_WINDOW["nose_below"], 2, 1), 0).astype(np.uint8)
    1069:             if self.mouth_pts is None and raw.any():
    1070:                 lab, n = label(raw)
    1071:                 if n:
    1072:                     widths = [np.ptp(np.nonzero(lab == i)[1]) for i in range(1, n + 1)]
    1073:                     ys, xs = np.nonzero(lab == 1 + int(np.argmax(widths)))
    1074:                     th, tw = raw.shape
    1075:                     ends = [(xs.min() + 0.5, ys[xs == xs.min()].mean()), (xs.max() + 0.5, ys[xs == xs.max()].mean()),
    1076:                             (xs.mean(), ys.mean())]
    1077:                     face_prims = [q for q, r in zip(self.prims, self.roles) if r == "face"]
    1078:                     pts = [uv_to_3d(face_prims, (ex / tw, ey / th)) for ex, ey in ends]
    1079:                     if pts[0] is not None and pts[1] is not None:
    1080:                         if pts[2] is None:
    1081:                             pts[2] = (pts[0] + pts[1]) / 2
    1082:                         self.mouth_pts = pts
    1083:                     # the painted line's centre, traced across: a 3D curve that hugs the lips
    1084:                     lab_m = lab == 1 + int(np.argmax(widths))
    1085:                     curve = []
    1086:                     for x_ in np.linspace(xs.min(), xs.max(), 24):
    1087:                         col = np.nonzero(lab_m[:, int(round(x_))])[0]
    1088:                         if len(col):
    1089:                             q = uv_to_3d(face_prims, ((x_ + 0.5) / tw, (col.mean() + 0.5) / th))
    1090:                             if q is not None:
    1091:                                 curve.append(q)
    1092:                     self.mouth_curve = np.array(curve) if len(curve) >= 4 else None
    1093: 
    1094:     def frame(self, view="bust", pitch=None, w=None, h=None):
    1095:         """The view's camera (self.camera, which the live viewer uses) without rendering."""
    1096:         return self._frame(view, pitch, w, h)[0]
    1097: 
    1098:     def _frame(self, view, pitch, w, h):

    309 more lines not shown.

  • read_file{"EndLine":300,"Path":"~/work/lowmarch/tools/export_glb.py","StartLine":1}

    input

    {
      "EndLine": 300,
      "Path": "~/work/lowmarch/tools/export_glb.py",
      "StartLine": 1
    }

    result, 301 lines

    Showing lines 1-300 of 567
    1: """Export a composed character (VRoid base + our shapes, costume, props, scenery) to GLB for the
    2: browser 3D viewer.
    3: 
    4: Each primitive becomes a mesh named by its group (body, hair, costume pieces, sword, terrain) so
    5: the viewer can toggle and x-ray them. Face, eye, line, brow, mouth and hair keep VRoid's textures
    6: (downscaled) for alpha and detail; everything else gets the character's palette colour. The model
    7: is turned to face +z, the direction a default three.js camera looks from.
    8: """
    9: import io
    10: import math
    11: import json
    12: import struct
    13: 
    14: import numpy as np
    15: from PIL import Image
    16: 
    17: FLIP = np.array([-1.0, 1.0, -1.0])
    18: TEXTURED = ("face", "iris", "white", "highlight", "line", "brow", "mouth", "hair")
    19: ROLE_TONE = {"face": "5", "body": "4", "shadow": "3", "hair": "D", "brow": "B", "coat": "M", "cape": "W", "metal": "8",
    20:              "signature": "M", "doublet": "S", "heraldry": "N",
    21:              "steel": "8", "gold": "H", "leather": "v", "boot": "v", "glove": "x", "cloth": "M",
    22:              "grass": "c", "dirt": "f", "stone": "l", "mouth": "2", "line": "o", "iris": "s", "white": "w",
    23:              "highlight": "w"}
    24: 
    25: 
    26: def group_of(p, role):
    27:     if p.get("world"):
    28:         return "terrain"
    29:     if p.get("group"):
    30:         return p["group"]
    31:     if role in ("face", "body", "shadow", "iris", "white", "highlight", "line", "brow", "mouth"):
    32:         return "body"
    33:     if role == "hair":
    34:         return "hair"
    35:     name = p["material"].replace("OUTFIT_", "")
    36:     for key in ("trim", "edge", "hem", "placket", "buckle", "clasp"):
    37:         if key in name:
    38:             return "trim"
    39:     for key in ("pauldron", "cape", "collar", "tunic", "tails", "belt", "trousers", "boots", "gloves"):
    40:         if name.startswith(key):
    41:             return key
    42:     if name in ("blade", "guard", "grip", "pommel", "fuller"):
    43:         return "sword"
    44:     return "costume"
    45: 
    46: 
    47: def skin_ramp(h):
    48:     """A skin tone's lit, shade and deep-shade colours from its lit colour. The shade is darker and a little more
    49:     saturated, its hue nudged toward red on human tones (so deep skin stays rich and warm, not ashy) and toward
    50:     violet on the fantasy blues, greens and greys. Hex strings, light to dark."""
    51:     import colorsys
    52:     r, g, b = (int(h[i:i + 2], 16) / 255 for i in (1, 3, 5))
    53:     hue, sat, val = colorsys.rgb_to_hsv(r, g, b)
    54:     warm = hue < 0.17 or hue > 0.9
    55:     dh = -0.015 if warm else (0.025 if hue < 0.75 else -0.025)
    56: 
    57:     def tone(k, dv, ds):
    58:         rr, gg, bb = colorsys.hsv_to_rgb((hue + k * dh) % 1.0, min(1.0, sat + (1 - sat) * ds), val * dv)
    59:         return "#%02x%02x%02x" % tuple(int(round(c * 255)) for c in (rr, gg, bb))
    60:     return [h, tone(1, 0.80, 0.12), tone(2, 0.50, 0.22)]
    61: 
    62: 
    63: def hex_rgb(h):
    64:     h = h.lstrip("#")
    65:     return [int(h[i:i + 2], 16) / 255 for i in (0, 2, 4)]
    66: 
    67: 
    68: def export(portrait, palette, path, max_tex=512, only_world=False):
    69:     """portrait: vroid_portrait.Portrait. palette: full char -> hex map. only_world: export just
    70:     the scenery (the character goes out skinned through export_skinned)."""
    71:     bin_ = bytearray()
    72:     views, accessors, meshes, nodes, materials, textures, images = [], [], [], [], [], [], []
    73:     tex_index = {}
    74: 
    75:     def add_view(data, target=None):
    76:         while len(bin_) % 4:
    77:             bin_.append(0)
    78:         off = len(bin_)
    79:         bin_.extend(data)
    80:         v = dict(buffer=0, byteOffset=off, byteLength=len(data))
    81:         if target:
    82:             v["target"] = target
    83:         views.append(v)
    84:         return len(views) - 1
    85: 
    86:     def add_acc(arr, kind, comp, target):
    87:         arr = np.ascontiguousarray(arr)
    88:         vi = add_view(arr.tobytes(), target)
    89:         a = dict(bufferView=vi, componentType=comp, count=int(arr.shape[0]), type=kind)
    90:         if kind == "VEC3" and comp == 5126:
    91:             a["min"] = arr.min(0).tolist()
    92:             a["max"] = arr.max(0).tolist()
    93:         accessors.append(a)
    94:         return len(accessors) - 1
    95: 
    96:     def add_texture(key, rgba):
    97:         if key in tex_index:
    98:             return tex_index[key]
    99:         im = Image.fromarray(rgba)
    100:         if max(im.size) > max_tex:
    101:             k = max_tex / max(im.size)
    102:             im = im.resize((max(1, int(im.width * k)), max(1, int(im.height * k))), Image.LANCZOS)
    103:         b = io.BytesIO()
    104:         im.save(b, "PNG", optimize=True)
    105:         vi = add_view(b.getvalue())
    106:         images.append(dict(bufferView=vi, mimeType="image/png"))
    107:         textures.append(dict(source=len(images) - 1, sampler=0))
    108:         tex_index[key] = len(textures) - 1
    109:         return tex_index[key]
    110: 
    111:     for k, (p, role) in enumerate(zip(portrait.prims, portrait.roles)):
    112:         if role == "skip" or not len(p["tri"]) or (only_world and not p.get("world")):
    113:             continue
    114:         used, inv = np.unique(p["tri"], return_inverse=True)
    115:         pos = (p["pos"][used] * FLIP).astype(np.float32)
    116:         nrm = p["nrm"][used] * FLIP
    117:         nrm = (nrm / np.maximum(np.linalg.norm(nrm, axis=1, keepdims=True), 1e-9)).astype(np.float32)
    118:         tri = inv.reshape(-1, 3).astype(np.uint32)               # FLIP is a 180-degree turn: winding holds
    119:         attrs = dict(POSITION=add_acc(pos, "VEC3", 5126, 34962), NORMAL=add_acc(nrm, "VEC3", 5126, 34962))
    120:         mat = dict(name=f"{group_of(p, role)}:{role}", doubleSided=True,
    121:                    pbrMetallicRoughness=dict(metallicFactor=0.0, roughnessFactor=0.9))
    122:         tone = ROLE_TONE.get(role)
    123:         color = hex_rgb(palette[tone]) if tone in palette else [0.8, 0.8, 0.8]
    124:         tex = portrait.tex.get(k)
    125:         if role == "face":
    126:             tex = portrait.v.material_texture(p["mi"])
    127:         if role in TEXTURED and tex is not None:
    128:             uv = p["uv"][used].astype(np.float32)
    129:             attrs["TEXCOORD_0"] = add_acc(uv, "VEC2", 5126, 34962)
    130:             src = portrait._hair_v if role == "hair" and getattr(portrait, "_hair_v", None) is not None \
    131:                 and "_HAIR" in p["material"] else portrait.v
    132:             raw = src.material_texture(p["mi"])
    133:             mat["pbrMetallicRoughness"]["baseColorTexture"] = dict(index=add_texture((id(src), p["mi"], role), raw))
    134:             if role == "hair":                        # strands are grey in the texture: tint them
    135:                 mat["pbrMetallicRoughness"]["baseColorFactor"] = color + [1.0]
    136:             if role in ("hair", "line", "brow", "iris", "highlight"):
    137:                 mat["alphaMode"] = "MASK"
    138:                 mat["alphaCutoff"] = 0.5
    139:         else:
    140:             mat["pbrMetallicRoughness"]["baseColorFactor"] = color + [1.0]
    141:         if role in ("metal", "steel", "gold"):
    142:             mat["pbrMetallicRoughness"].update(metallicFactor=0.6, roughnessFactor=0.35)
    143:         materials.append(mat)
    144:         meshes.append(dict(name=group_of(p, role), primitives=[dict(
    145:             attributes=attrs, indices=add_acc(tri.reshape(-1), "SCALAR", 5125, 34963), material=len(materials) - 1)]))
    146:         nodes.append(dict(name=f"{group_of(p, role)}/{p['material']}", mesh=len(meshes) - 1,
    147:                           extras=dict(group=group_of(p, role), role=role, world=bool(p.get("world")), material=p["material"])))
    148:     gltf = dict(asset=dict(version="2.0", generator="lowmarch export_glb"), scene=0,
    149:                 scenes=[dict(nodes=list(range(len(nodes))))], nodes=nodes, meshes=meshes, materials=materials,
    150:                 accessors=accessors, bufferViews=views, buffers=[dict(byteLength=len(bin_))],
    151:                 samplers=[dict(magFilter=9729, minFilter=9987)])
    152:     if textures:
    153:         gltf.update(textures=textures, images=images)
    154:     js = json.dumps(gltf, separators=(",", ":")).encode()
    155:     js += b" " * ((4 - len(js) % 4) % 4)
    156:     while len(bin_) % 4:
    157:         bin_.append(0)
    158:     out = struct.pack("<4sII", b"glTF", 2, 12 + 8 + len(js) + 8 + len(bin_))
    159:     out += struct.pack("<I4s", len(js), b"JSON") + js + struct.pack("<I4s", len(bin_), b"BIN\x00") + bytes(bin_)
    160:     open(path, "wb").write(out)
    161:     return len(out)
    162: 
    163: 
    164: # ---- data for the real-time viewer ----------------------------------------------------------
    165: CAPSULES = [("J_Bip_C_Hips", "J_Bip_C_Spine"), ("J_Bip_C_Spine", "J_Bip_C_Chest"),
    166:             ("J_Bip_C_Chest", "J_Bip_C_UpperChest"), ("J_Bip_C_UpperChest", "J_Bip_C_Neck"),
    167:             ("J_Bip_C_Neck", "J_Bip_C_Head")] + \
    168:            [(f"J_Bip_{s}_{a}", f"J_Bip_{s}_{b}") for s in "LR" for a, b in
    169:             (("UpperArm", "LowerArm"), ("LowerArm", "Hand"), ("UpperLeg", "LowerLeg"), ("LowerLeg", "Foot"))]
    170: # simulated cloth: piece -> (its static trims, hidden while the cloth simulates; the role whose colour
    171: # the simulated border band takes; the bones whose colliders it meets, None for all). Panels hanging
    172: # from the belt meet the legs only: the hip collider's round end pushes them out behind.
    173: LEGS = ("UpperLeg", "LowerLeg")
    174: CLOTH = {"OUTFIT_cape": (("OUTFIT_cape_trim", "OUTFIT_cape_hem", "OUTFIT_cape_edge0", "OUTFIT_cape_edge1"), "gold", None),
    175:          "OUTFIT_tails": (("OUTFIT_tails_hem",), "gold", LEGS),
    176:          "OUTFIT_tabard": (("OUTFIT_tabard_hem", "OUTFIT_tabard_edge0", "OUTFIT_tabard_edge1"), "heraldry", LEGS),
    177:          "OUTFIT_tabard_back": (("OUTFIT_tabard_back_hem", "OUTFIT_tabard_back_edge0", "OUTFIT_tabard_back_edge1"),
    178:                                 "heraldry", LEGS),
    179:          "OUTFIT_skirt": (("OUTFIT_skirt_hem",), "heraldry", LEGS)}
    180: CLOTH_HEM_ONLY = {"OUTFIT_skirt"}            # border band on the hem row only (its waist has a gold trim)
    181: 
    182: 
    183: def scene_info(portrait, palette):
    184:     """Everything the browser's pixel renderer and cloth solver need besides the meshes: palette
    185:     bands per role, the lights, body colliders, cloth grids and the mouth curve (model space,
    186:     turned to face +z like the GLB)."""
    187:     import vroid_portrait as vp
    188:     from vrm import bone_weight
    189:     hexp = lambda c: palette[c]
    190:     bands = lambda tbl: [[thr if thr > -5 else -9, hexp(c)] for thr, c in tbl]
    191:     roles = {"face": dict(mode="bands", bands=bands(vp.SKIN_BANDS)),
    192:              "body": dict(mode="bands", bands=bands(vp.SKIN_BANDS), cap=hexp("4")),
    193:              "shadow": dict(mode="flat", color=hexp("3")),
    194:              "hair": dict(mode="bands", bands=bands(vp.HAIR_BANDS)),
    195:              "cloth": dict(mode="bands", bands=bands(vp.CLOTH_BANDS)),
    196:              "line": dict(mode="flat", color=hexp("o")), "brow": dict(mode="flat", color=hexp("A")),
    197:              "mouth": dict(mode="flat", color=hexp("1")), "white": dict(mode="flat", color=hexp("w")),
    198:              "highlight": dict(mode="flat", color=hexp("w")),
    199:              "iris": dict(mode="iris", colors=[hexp("r"), hexp("s"), hexp("t")], cuts=[0.25, 0.5])}
    200:     for r, tbl in vp.MATERIALS.items():
    201:         roles[r] = dict(mode="bands", bands=bands(tbl), world=r in vp.WORLD_ROLES)
    202:     names = portrait.v.nodes_by_name()
    203:     W = portrait.v.node_world(portrait.pose_now)
    204:     body = [p for p, r in zip(portrait.prims, portrait.roles) if r == "body"][0]
    205:     caps = []
    206:     for a, b in CAPSULES:
    207:         if a not in names or b not in names:
    208:             continue
    209:         A, B = W[names[a]][:3, 3], W[names[b]][:3, 3]
    210:         wv = bone_weight(body, (a,))
    211:         pts = body["pos"][wv > 0.5]
    212:         if len(pts) < 8:
    213:             continue
    214:         ab = B - A
    215:         t = np.clip(((pts - A) @ ab) / (ab @ ab), 0, 1)
    216:         d = np.linalg.norm(pts - (A + t[:, None] * ab), axis=1)
    217:         caps.append(dict(a=(A * FLIP).tolist(), b=(B * FLIP).tolist(), r=float(np.percentile(d, 70) + 0.012),
    218:                          bones=[a, b]))
    219:     cloth = {}
    220:     for p in portrait.prims:
    221:         if p["material"] in CLOTH and "grid" in p:
    222:             trims, band, collide = CLOTH[p["material"]]
    223:             cloth[p["material"]] = dict(u=int(p["grid"][0]), v=int(p["grid"][1]), trims=list(trims), band=band,
    224:                                         collide=list(collide) if collide else None, closed=bool(p.get("closed")),
    225:                                         edges="hem" if p["material"] in CLOTH_HEM_ONLY else "all")
    226:     curve = None
    227:     if getattr(portrait, "mouth_curve", None) is not None:
    228:         face = [p for p, r in zip(portrait.prims, portrait.roles) if r == "face"]
    229:         allp = np.concatenate([p["pos"] for p in face])
    230:         alln = np.concatenate([p["nrm"] for p in face])
    231:         from scipy.spatial import cKDTree
    232:         _, i = cKDTree(allp).query(portrait.mouth_curve)
    233:         curve = ((portrait.mouth_curve + alln[i] * 0.0015) * FLIP).tolist()
    234:     marks = None
    235:     if getattr(portrait, "marks", None):
    236:         m = next(iter(portrait.marks.values()))
    237:         img = Image.fromarray(np.where(m == 1, 128, 0).astype(np.uint8), "L")     # nose mark only; the mouth is a line
    238:         b = io.BytesIO()
    239:         img.save(b, "PNG", optimize=True)
    240:         import base64
    241:         marks = base64.b64encode(b.getvalue()).decode()
    242:     # painted renderer: a material kind and one base colour per role; the shader builds the ramp
    243:     pc = dict(signature="#7d1e2c", doublet="#2a2d3d", heraldry="#dfe2e8", leather="#5f3e2b", boot="#4a3326", glove="#5f3e2b",
    244:               steel="#a6adbb", gold="#b08b3f", hair=hexp("C"), trim="#b08b3f")
    245:     pc.update(getattr(portrait, "paint", None) or {})
    246:     skin = dict(kind="skin", base=pc.get("skin") or "#f8e1d5")                       # light skin unless a tone is set
    247:     skin["ramp"] = skin_ramp(skin["base"])                                              # its lit, shade and deep shade
    248:     paint = {"face": dict(skin), "body": dict(skin), "shadow": dict(skin, shade=True),   # shadow cards: skin in shade
    249:              "hair": dict(kind="hair", base=pc["hair"]),
    250:              "coat": dict(kind="cloth", base=pc["signature"]), "cape": dict(kind="cloth", base=pc["signature"]),
    251:              "signature": dict(kind="cloth", base=pc["signature"]), "doublet": dict(kind="cloth", base=pc["doublet"]),
    252:              "cloth": dict(kind="cloth", base=pc["doublet"]), "heraldry": dict(kind="cloth", base=pc["heraldry"]),
    253:              "leather": dict(kind="leather", base=pc["leather"]), "boot": dict(kind="leather", base=pc["boot"]),
    254:              "glove": dict(kind="leather", base=pc["glove"]), "metal": dict(kind="steel", base=pc["steel"]),
    255:              "steel": dict(kind="steel", base=pc["steel"]), "gold": dict(kind="gold", base=pc["gold"]),
    256:              "grass": dict(kind="world", base="#5a7a3a"), "dirt": dict(kind="world", base="#6a4a32"),
    257:              "stone": dict(kind="world", base="#7c7a86"),
    258:              "motif": dict(kind="cloth", base=pc.get("motif", "#3a44a0"))}       # decal paint on steel (tools/plates.py)
    259:     for role, val in pc.items():                             # extra roles a cast entry names (cloth unless it says)
    260:         if role not in paint and isinstance(val, str) and val.startswith("#"):
    261:             paint[role] = dict(kind="cloth", base=val)
    262:         elif role not in paint and isinstance(val, dict) and "base" in val:
    263:             paint[role] = dict(kind=val.get("kind", "cloth"), base=val["base"])
    264:     for role, g in (pc.get("grain") or {}).items():          # optional per-role brush grain (big flat cloth mottles)
    265:         if role in paint:
    266:             paint[role]["grain"] = g
    267:     return dict(roles=roles, light=vp.LIGHT.tolist(), sun=vp.SUN.tolist(), capsules=caps, cloth=cloth, face_marks=marks,
    268:                 paint=paint,
    269:                 mouth_curve=curve, mouth_bone="J_Bip_C_Head", ink=dict(o=hexp("o"), skin=hexp("1"), hair=hexp("A")),
    270:                 skin=[hexp(c) for c in "12345"], depth_gap=0.012)
    271: 
    272: 
    273: # ---- skinned export: one rigged character + animation clips --------------------------------------------------------
    274: F4 = np.diag([-1.0, 1.0, -1.0, 1.0])
    275: 
    276: 
    277: def _quat(R):
    278:     """Rotation matrix -> quaternion (x, y, z, w)."""
    279:     t = np.trace(R)
    280:     if t > 0:
    281:         s = math.sqrt(t + 1.0) * 2
    282:         w, x, y, z = 0.25 * s, (R[2, 1] - R[1, 2]) / s, (R[0, 2] - R[2, 0]) / s, (R[1, 0] - R[0, 1]) / s
    283:     elif R[0, 0] > R[1, 1] and R[0, 0] > R[2, 2]:
    284:         s = math.sqrt(1.0 + R[0, 0] - R[1, 1] - R[2, 2]) * 2
    285:         w, x, y, z = (R[2, 1] - R[1, 2]) / s, 0.25 * s, (R[0, 1] + R[1, 0]) / s, (R[0, 2] + R[2, 0]) / s
    286:     elif R[1, 1] > R[2, 2]:
    287:         s = math.sqrt(1.0 + R[1, 1] - R[0, 0] - R[2, 2]) * 2
    288:         w, x, y, z = (R[0, 2] - R[2, 0]) / s, (R[0, 1] + R[1, 0]) / s, 0.25 * s, (R[1, 2] + R[2, 1]) / s
    289:     else:
    290:         s = math.sqrt(1.0 + R[2, 2] - R[0, 0] - R[1, 1]) * 2
    291:         w, x, y, z = (R[1, 0] - R[0, 1]) / s, (R[0, 2] + R[2, 0]) / s, (R[1, 2] + R[2, 1]) / s, 0.25 * s
    292:     q = np.array([x, y, z, w])
    293:     return q / np.linalg.norm(q)
    294: 
    295: 
    296: def _trs(m):
    297:     t = m[:3, 3].copy()
    298:     sc = np.linalg.norm(m[:3, :3], axis=0)
    299:     return t, _quat(m[:3, :3] / sc), sc
    300: