Spaces:
Running
Running
Update to pydraw master b579b04 (waves 17-19: 2D-first portrait path, anatomy helpers, research 19 rules, critic tooling; new behaviour off by default)
Browse filesFiles changed (33)
- pydraw/__init__.py+5
- pydraw/anatomy/__init__.pyAdded+4
- pydraw/anatomy/cloth.pyAdded+373
- pydraw/anatomy/core.pyAdded+872
- pydraw/anatomy/ear.pyAdded+175
- pydraw/anatomy/eye.pyAdded+412
- pydraw/anatomy/featkit.pyAdded+106
- pydraw/anatomy/features.pyAdded+221
- pydraw/anatomy/foot.pyAdded+314
- pydraw/anatomy/hair.pyAdded+209
- pydraw/anatomy/hand.pyAdded+778
- pydraw/anatomy/head.pyAdded+596
- pydraw/anatomy/hooks.pyAdded+294
- pydraw/anatomy/limbs.pyAdded+203
- pydraw/anatomy/mouth.pyAdded+249
- pydraw/anatomy/nose.pyAdded+195
- pydraw/anatomy/person.pyAdded+496
- pydraw/anatomy/render.pyAdded+910
- pydraw/anatomy/torso.pyAdded+397
- pydraw/figure/__init__.pyAdded+243
- pydraw/figure/canon.pyAdded+202
- pydraw/figure/flat.pyAdded+131
- pydraw/figure/hairlayout.pyAdded+733
- pydraw/figure/kit.pyAdded+663
- pydraw/figure/layout.pyAdded+730
- pydraw/figure/style_anime.pyAdded
- pydraw/figure/style_ink.pyAdded
- pydraw/figure/style_paint.pyAdded+1724
- pydraw/figure/style_pixel.pyAdded+1909
- pydraw/figure/value.pyAdded+221
- pydraw/rig/person_px.py+11
- pydraw3d/models_person.py+8
- requirements.txt+1
34 unmodified lines35363738394034 unmodified linesvariation (0..1): how much the seed may vary what the prompt leaves open (breed, time of day, setting, framing, mood)."""trace = []scene, rng, pstyle = prepare(text, seed, variation, trace)# wave 15 (gbuf): a medium renderer registered for the style word paints from the G-buffer (pydraw/gbuf.py;# knob media=0 / media_<name>=0 keeps the old styles.py filter)from . import gbuf as _gbuf34 unmodified lines353637383940414243444534 unmodified linesvariation (0..1): how much the seed may vary what the prompt leaves open (breed, time of day, setting, framing, mood)."""trace = []scene, rng, pstyle = prepare(text, seed, variation, trace)# wave 18 (fig2d, default OFF): a one-person portrait prompt is drawn 2D-first by pydraw/figure/ in its stylefrom .figure import try_portrait as _fig_portrait_fig = _fig_portrait(text, scene, seed, size, style, trace)if _fig is not None:return _fig# wave 15 (gbuf): a medium renderer registered for the style word paints from the G-buffer (pydraw/gbuf.py;# knob media=0 / media_<name>=0 keeps the old styles.py filter)from . import gbuf as _gbuf
1234"""pydraw.anatomy (wave 17, the atelier): each part of a person as one construction-rule SDF sculpt, shown in everystyle from its G-buffer. core.py = SDF helpers, Part interface, G-buffer tracer (depict lane); render.py = light,line art, cel, pixel (depict); head.py / hair.py (head), eye.py / nose.py / mouth.py / ear.py (features), hand.py /foot.py (hands), torso.py / limbs.py / cloth.py / person.py (body)."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373"""pydraw.anatomy.cloth (wave 17, body lane): clothes as OFFSET SHELLS of the body sculpt that sit on the high pointsand bridge the hollows (docs/research17/units/torso_limbs.md R26, checklist ck22; Loomis ch. XII: "the fabric fallsaway from the most prominent forms underneath: shoulders, breasts, hips, buttocks, and knees"; Medlej: "the garmentshould never look painted on").
Each garment = a thin shell around an OUTER surface; the outer surface = smooth union of (a) the body offset by an ease (the cloth touches the high points: shoulders, chest peaks, buttocks, knees), and (b) DRAPE volumes hung from those high points (a shirt hangs straight from the chest peak to the hem and does not follow the waist pinch, R26; trousers hang from the knee front to the shoe so the calf vanishes; a skirt is a bell from the hips), with a large blend in the armpit and the crotch so those hollows are bridged,then clipped at the openings (neckline, sleeve ends, hem, waistband) and hollowed to a shell (an opening shows theinside, not a solid plug). Soft folds: a few low vertical folds below the chest / under the skirt, and the trouser"half-lock" break over the shoe.
outfit(J, torso, parts, spec, fem, child, fat) -> [Part] spec: "tshirt", "trousers", "dress", joined by "+"Materials: top / dress = CLOTH (12), trousers = CLOTH2 (13). Knob: PYDRAW_EXP bcloth=0 -> no drape (plain offsets)."""import numpy as npfrom .core import Part, Line, round_cone, ellipsoid, capsule, smin, smax, bezier_tube, _v, CLOTH, CLOTH2from .torso import knob, smoothstep, lerp
def shell(d, th): """a thin shell of thickness th whose OUTER face is the surface d = 0""" return np.abs(d + th * .5) - th * .5
def ell_cone(p, a, b, ra, rb, aspect, fwd, fold=None): """a tapered tube a -> b with an elliptic cross-section (depth = aspect * width), front axis fwd; fold = (n, amp, t0) adds n soft vertical folds whose depth grows from t0 to b. Approximate SDF (Lipschitz < ~1.2).""" ax = b - a L = float(np.linalg.norm(ax)) u = ax / L z = _v(fwd) - u * float(np.dot(fwd, u)) z /= np.linalg.norm(z) x = np.cross(u, z) q = p - a t = q @ u qx, qz = q @ x, (q @ z) / aspect r = np.sqrt(qx * qx + qz * qz) tt = np.clip(t / L, 0, 1) rad = ra + (rb - ra) * tt if fold is not None: n, amp, t0 = fold ang = np.arctan2(qz, qx) rad = rad + amp * np.cos(n * ang) * smoothstep(t0, 1.0, tt) side = (r - rad) * min(1.0, aspect) cap = np.maximum(-t, t - L) return np.maximum(side, cap)
def profile_tube(p, a, b, ts, rs, aspect, fwd, fold=None): """a tube a -> b whose elliptic cross-section radius follows the profile (ts, rs) (ts in 0..1 along the axis): one continuous surface, no blend bulge where two cones would meet (a skirt over the hips, a shirt over the waist)""" ax = b - a L = float(np.linalg.norm(ax)) u = ax / L z = _v(fwd) - u * float(np.dot(fwd, u)) z /= np.linalg.norm(z) x = np.cross(u, z) q = p - a t = q @ u qx, qz = q @ x, (q @ z) / aspect r = np.sqrt(qx * qx + qz * qz) tt = np.clip(t / L, 0, 1) rad = np.interp(tt, ts, rs) if fold is not None: n, amp, t0 = fold ang = np.arctan2(qz, qx) rad = rad + amp * np.cos(n * ang + 1.3 * np.sin(2 * ang)) * smoothstep(t0, 1.0, tt) # the slope of the profile shrinks the true distance a little: scale by 1/sqrt(1 + slope^2) sl = np.abs(np.gradient(np.asarray(rs, float), np.asarray(ts, float) * L)).max() if len(ts) > 1 else 0 side = (r - rad) * min(1.0, aspect) / np.sqrt(1 + sl * sl) cap = np.maximum(-t, t - L) return np.maximum(side, cap)
class Garment(Part): """outer(p) -> d of the outer surface, clips: list of fn(p) -> d (solid where < 0), th: shell thickness"""
def __init__(self, name, mat, outer, clips, th, lo, hi): super().__init__() self.name, self.mat, self.outer, self.clips, self.th = name, mat, outer, clips, th self.lo, self.hi = _v(lo), _v(hi)
def eval(self, p, want_mat=False): d = shell(self.outer(p), self.th) for c in self.clips: d = smax(d, c(p), self.th * .5) if want_mat: return d, np.full(len(p), self.mat, np.int16) return d
def bounds(self): return self.lo, self.hi
class Solid(Part): """a solid cloth piece (a strap, a band) given by its SDF"""
def __init__(self, name, mat, fn, lo, hi): super().__init__() self.name, self.mat, self.fn, self.lo, self.hi = name, mat, fn, _v(lo), _v(hi)
def eval(self, p, want_mat=False): d = self.fn(p) return (d, np.full(len(p), self.mat, np.int16)) if want_mat else d
def bounds(self): return self.lo, self.hi
def _probe(part, o, u, maxd, n=240): """the first surface point of `part` from o along u (a march + bisection)""" t = np.linspace(0, maxd, n) d = part.eval(o[None] + t[:, None] * u[None]) k = int(np.argmax(d < 0)) if d[k] >= 0: return o + u * maxd a, b = t[max(k - 1, 0)], t[k] for _ in range(20): c = (a + b) / 2 if part.eval((o + c * u)[None])[0] < 0: b = c else: a = c return o + u * b
def bust_hull(T, H, fem=0.0): """an ellipsoid through the chest peaks (pecs / breasts): cloth spans from peak to peak, no under-breast fold and no two domes show through a shirt or a bodice (R26, critic9 r3)""" lm = T.landmarks() nb = T.J["neck_base"] pk = lm["nipple_l"] c = _v((0, pk[1] + .06 * H, nb[2] - .05 * H)) # on a woman the hull is shorter and sits closer, so the profile falls from the peak instead of a round ball r = _v((abs(pk[0]) + .30 * H, lerp(.58, .44, fem) * H, pk[2] - c[2] + lerp(.07, .04, fem) * H)) return c, r
def _bounds_of(parts, pad): lo = np.min([p.bounds()[0] for p in parts], 0) - pad hi = np.max([p.bounds()[1] for p in parts], 0) + pad return lo, hi
def _plane(o, n): n = _v(n) / np.linalg.norm(n) return lambda p, o=_v(o), n=n: (p - o) @ n
def tshirt(J, T, arms, fem, child, fat): H = J["H"] lm = T.landmarks() ease = .04 * H drape = knob("bcloth") nb = J["neck_base"] tab = T.T hip_y = J["hipc"][1] hem_y = hip_y + (.18 if not child else .22) * H # a T-shirt ends over the hips # the chest peak level (pecs / breasts) and its half width / depth: the shirt hangs straight down from it (R26) pk = lm["nipple_l"] chest_y = pk[1] cw = max(tab["rib_r"][0] + .10, abs(pk[0]) / H + .18) cd_front = (pk[2] - nb[2]) / H + .05 hipw = tab["troch"] * .92 hem_w = max(cw * 1.02, hipw + .06) + .04 * fat zc = nb[2] + (cd_front - tab["rib_r"][2] * 1.05) * .5 * H - .03 * H depth_top = (cd_front + tab["rib_r"][2] * 1.05) * .5 bh_c, bh_r = bust_hull(T, H, fem) hull_c = T.C.w(*tab["rib_c"]) + T.C.R[1] * .04 * H hull_r = (_v(tab["rib_r"]) + _v((.10, .06, .17 - .05 * fem))) * H nav = lm["navel"] zf, zb = nav[2] + .01 * H, nb[2] - tab["rib_r"][2] * H belly_c = _v((0, nav[1], (zf + zb) / 2)) belly_r = _v(((tab["waist"] + .06) * H, .45 * H, (zf - zb) / 2)) a = _v((0, chest_y, zc)) b = _v((0, hem_y - .1 * H, zc - .02 * H)) asp = depth_top / cw folds = (5, .025 * H, .35) # fit (0 = loose, hangs straight from the chest peak; 1 = follows the waist): R26 says a shirt must not follow the # pinch unless fit > .7; a woman's T-shirt is cut a little closer (est .45), a man's loose (.15) fit = lerp(.15, .45, fem) waist_y = J["neck_base"][1] + tab["waist_y"] * H straight = lerp(cw, hem_w, (chest_y - waist_y) / (chest_y - b[1])) tw = lerp(straight, tab["waist"] + .09, fit) ts = [0, (chest_y - waist_y) / (chest_y - b[1]), 1] rs = _v([cw, tw, hem_w]) * H
# one garment (no armhole seam): the sleeve = the arm offset and a sleeve cone (a hull of the deltoid and the # sleeve end, a little bell at the opening), both kept only above the sleeve end plane sleeves = [] for A in arms: u = (A.U.a - A.U.b) / np.linalg.norm(A.U.a - A.U.b) gq = lerp(1, .86, fem) * lerp(1, .74, child) sleeves.append((A, A.U.at(.52, 0, 0), u, A.U.at(.06, .04, 0), A.U.at(.52, 0, 0), .25 * H * gq, .225 * H * gq))
def outer(p): d = T.eval(p) - ease for A, o_, u_, s0, s1, r0, r1 in sleeves: keep = -((p - o_) @ u_) # < 0 on the shoulder side of the sleeve end dA = A.eval(p) - ease if drape: dA = smin(dA, round_cone(p, s0, s1, r0, r1), .05 * H) d = smin(d, np.maximum(dA, keep), .16 * H) # the armpit is bridged (R26) if drape: dr = profile_tube(p, a, b, ts, rs, asp, (0, 0, 1), folds) d = smin(d, dr, .08 * H) # the chest hull: the shirt spans the pec / sternum groove from peak to peak (it touches the high points # and bridges the hollows, R26) # the hulls melt in with a LARGE blend so the cloth is one convex surface over the chest (no relief) d = smin(d, ellipsoid(p, hull_c, hull_r, T.C.R), .16 * H) d = smin(d, ellipsoid(p, belly_c, belly_r, T.C.R), .14 * H) # spans the navel / rectus hollows d = smin(d, ellipsoid(p, bh_c, bh_r, T.C.R), .2 * H) return d clips = [] # neckline: a crew neck - everything above a plane from just above the pit (front) to above the nape (back), # near the neck, is open pit = lm["pit"] nape = lm["nape"] f0, b0 = pit + _v((0, .04, 0)) * H, nape + _v((0, .16, 0)) * H nrm = np.cross(_v((1, 0, 0)), f0 - b0) nrm = nrm / np.linalg.norm(nrm) nrm = nrm if nrm[1] > 0 else -nrm ncx = (pit + nape) / 2
def neck_clip(p, f0=f0, nrm=nrm, ncx=ncx): above = -((p - f0) @ nrm) # < 0 above the neckline plane rxz = np.sqrt((p[:, 0] - ncx[0]) ** 2 + ((p[:, 2] - ncx[2]) * .9) ** 2) - .44 * H return -smax(above, rxz, .06 * H) clips.append(neck_clip) clips.append(_plane(_v((0, hem_y, 0)), (0, -1, 0))) # the hem lo, hi = _bounds_of([T] + list(arms), .3 * H) lo[1] = hem_y - .3 * H return [Garment("tshirt", CLOTH, outer, clips, .05 * H, lo, hi)]
def trousers(J, T, legs, fem, child, fat): H = J["H"] lm = T.landmarks() ease = .03 * H drape = knob("bcloth") hip_y = J["hipc"][1] top_y = hip_y + (T.T["crest"] - .05) * H # the waistband at the top of the hips floor = 0.0 hem_y = J["ankle_y"] * .55 # over the shoe, a half break hems = {}
def outer(p): d = T.eval(p) - ease for Lg in legs: d = smin(d, Lg.eval(p) - ease, .10 * H) if drape: for Lg in legs: # the thigh: a cone hip -> knee that bridges the inner hollow; the shin: hangs from the knee front # to the shoe so the calf vanishes in the front view (R26, ck22) hip, knee, ank = Lg.T.a, Lg.T.b, Lg.Sh.b s = Lg.s # ONE profile hip -> knee -> hem: wide over the buttock / front thigh, touching the knee, then hanging # straight to the shoe wide enough to contain the calf (the calf vanishes, the hem breaks over the shoe) gq = (1 - .12 * fem) * (1 - .14 * child) * (1 + max(fat - .35, 0) * .3) top = hip + _v((s * .06, .05, -.02)) * H hem = _v((ank[0] + s * .02 * H, hem_y, ank[2] - .02 * H)) Lt = float(np.linalg.norm(hem - top)) tk = float(np.linalg.norm(knee - top)) / Lt ts = [0, tk * .5, tk, 1] rs = _v([.40 * (1 + .08 * fem), .35, .30, .29]) * H * gq # wide over the knee: it drapes, no ball d = smin(d, profile_tube(p, top, hem, ts, rs, 1.08, (0, 0, 1), (3, .012 * H, .8)), .08 * H) return d clips = [_plane(_v((0, top_y, 0)), (0, 1, 0)), _plane(_v((0, hem_y, 0)), (0, -1, 0))] lo, hi = _bounds_of([T] + list(legs), .3 * H) hi[1] = top_y + .1 * H lo[1] = 0.0 return Garment("trousers", CLOTH2, outer, clips, .028 * H, lo, hi)
def dress(J, T, arms, legs, fem, child, fat): """a sleeveless dress: fitted bodice over the bust (touching the breasts and bridging under them), a waist seam, and a bell skirt from the hips (the legs inside are hidden, R26) ending below the knee; two shoulder straps""" H = J["H"] lm = T.landmarks() ease = .03 * H drape = knob("bcloth") tab = T.T hip_y = J["hipc"][1] knee_y = (J["knee_l"][1] + J["knee_r"][1]) / 2 hem_y = knee_y - .45 * H hipw = tab["troch"] + .06 pk = lm["nipple_l"] waist_y = J["neck_base"][1] + tab["waist_y"] * H nb = J["neck_base"] z0 = nb[2] - .05 * H nav = lm["navel"] zf, zb = nav[2] + .01 * H, nb[2] - tab["rib_r"][2] * H belly_c = _v((0, nav[1], (zf + zb) / 2)) belly_r = _v(((tab["waist"] + .05) * H, .40 * H, (zf - zb) / 2)) bh_c, bh_r = bust_hull(T, H, fem)
def outer(p): d = T.eval(p) - ease if drape: # ONE profile from the bust peaks to the hem: hanging straight under the bust (bridging the fold), in to # the waist seam, resting on the hips (the high point, R26), then a bell with folds deepening to the hem a = _v((0, pk[1], z0)) b = _v((0, hem_y, z0 + .02 * H)) Lt = pk[1] - hem_y
def tt(y): return (pk[1] - y) / Lt cw = abs(pk[0]) / H + .16 ts = [0, tt(waist_y + .05 * H), tt(waist_y), tt(hip_y + .05 * H), tt(hip_y - .3 * H), 1] rs = _v([cw, tab["waist"] + .07, tab["waist"] + .07, hipw - .02, hipw + .03, hipw + .30]) * H d = smin(d, profile_tube(p, a, b, ts, rs, .80, (0, 0, 1), (6, .085 * H, .35)), .06 * H) d = smin(d, ellipsoid(p, belly_c, belly_r, T.C.R), .12 * H) # spans the navel hollow d = smin(d, ellipsoid(p, bh_c, bh_r, T.C.R), .18 * H) return d under = lm["armpit_f_l"][1] + .06 * H zc0 = z0
def hem_clip(p, zc0=zc0): # the hem follows the folds: the crests (out) hang a little lower than the troughs (est .05 H) ang = np.arctan2((p[:, 2] - zc0) / .8, p[:, 0]) yh = hem_y + .05 * H * np.cos(6 * ang + 1.3 * np.sin(2 * ang)) return yh - p[:, 1] clips = [hem_clip] # the neckline: the bodice stops a little above the armpit line, with a soft scoop in front; the straps are round # tubes laid over the shoulder (they sit on the high point, the trapezius, and fall to the bodice front and back)
def top_clip(p, under=under): c = p[:, 1] - under c = c + .10 * H * np.exp(-(p[:, 0] / (.45 * H)) ** 2) * (p[:, 2] > nb[2]) # a shallow straight neckline return c clips.append(top_clip) strap_parts = [] for s_ in (1, -1): x = s_ * .34 * H f = _probe(T, _v((x, under - .04 * H, nb[2] + 1.0 * H)), _v((0, 0, -1)), 1.4 * H) + _v((0, 0, .02)) * H bk = _probe(T, _v((x, under - .04 * H, nb[2] - 1.0 * H)), _v((0, 0, 1)), 1.4 * H) - _v((0, 0, .02)) * H top = _probe(T, _v((x, nb[1] + .6 * H, nb[2] - .04 * H)), _v((0, -1, 0)), 1.2 * H) + _v((0, .035, 0)) * H for end, zdir in ((f, -1), (bk, 1)): ym = (end[1] + top[1]) / 2 m = _probe(T, _v((x, ym, nb[2] - zdir * 1.0 * H)), _v((0, 0, zdir)), 1.4 * H) - _v((0, 0, zdir * .05)) * H m[1] += .03 * H strap_parts.append((end, 2 * m - (end + top) / 2, top))
def outer_straps(p): d = np.full(len(p), 1e3) for e_, c_, t_ in strap_parts: d = np.minimum(d, bezier_tube(p, e_, c_, t_, .032 * H, .032 * H)) return d parts = [T] + list(legs) lo, hi = _bounds_of([T], .4 * H) lo[1] = hem_y - .1 * H lo[0], hi[0] = lo[0] - .3 * H, hi[0] + .3 * H lo[2], hi[2] = lo[2] - .3 * H, hi[2] + .3 * H g = Garment("dress", CLOTH, outer, clips, .028 * H, lo, hi) st = Solid("dress_straps", CLOTH, outer_straps, lo, hi) return [g, st]
def outfit(J, T, parts, spec, fem, child, fat): names = [s.strip() for s in str(spec).split("+") if s.strip()] arms = [p for p in parts if p.name.startswith("arm_")] legs = [p for p in parts if p.name.startswith("leg_")] out = [] for n in names: if n in ("tshirt", "t-shirt", "shirt"): out.extend(tshirt(J, T, arms, fem, child, fat)) elif n in ("trousers", "pants", "jeans"): out.append(trousers(J, T, legs, fem, child, fat)) elif n == "dress": out.extend(dress(J, T, arms, legs, fem, child, fat)) return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872"""pydraw.anatomy.core (wave 17, depict lane): the shared foundation of the atelier.
Every part of a person (eye, nose, mouth, ear, head, hair, hand, foot, torso, limbs) is ONE signed distance functionbuilt here from construction rules; every style (3D light, line art, cel, pixel) is drawn from its G-buffer(pydraw.anatomy.render). Pure numpy, rules only, CPU only. Method learned from the procedural-human research(docs/research17/units/procedural_humans.md); no shader code or constants were copied.
CONVENTIONS (all parts) units metres. An adult head (crown to chin) is ~0.23 m. A part may model in its own unit and wrap itself in Placed(part, scale=s). axes +y up, +z forward (the way the face / palm-normal-of-the-pose / body looks), +x = the subject's LEFT. So "_l" landmarks have x > 0 and appear on the viewer's right in the front view. points numpy float arrays (N, 3); distances (N,). Never build an (N, steps, parts) array: the renderer traces in tiles of TILE rays.
SDF HELPERS (functions of p (N,3) unless noted) smin(a, b, k) quadratic polynomial smooth-min; k = blend thickness in metres (0 = hard min) smin_h(a, b, k) same, also returns the mix factor h in [0,1] (1 = all a) to blend materials smax(a, b, k) smooth-max (intersection); carve(d, cut, k) = smax(d, -cut, k) sabs(x, k) soft |x|; mirror(p, k=0) -> p with x -> sabs(x) (a soft midline, no crease) sphere, ellipsoid(p, c, r, R=None), rbox(p, c, half, rr, R=None), plane(p, n, d) capsule(p, a, b, r), round_cone(p, a, b, ra, rb) (tapered capsule, exact) torus_arc(p, c, R, axis_u, axis_v, Rmaj, r, half_ang, r_end=None) an arc of a torus (helix, lid rim, lip line) bezier_tube(p, a, b, c, r0, r1, rmid=None) quadratic Bezier tube with radius tapering r0 -> rmid -> r1 bezier_t(p, a, b, c) (dist to the curve, curve parameter t) for painting along a curve rot(yaw, pitch, roll) / look(fwd, up) -> 3x3 rotation (rows = local x, y, z axes in world)
SCULPT (the usual way to write a part) S = Sculpt() S.add(fn, k=0.0, mat=SKIN, bound=(centre, radius)) smooth-union a primitive (fn(p) -> d) with blend k S.carve(fn, k=0.0, bound=..., mat=None) smooth-max carve; mat = material of the carved wall (or keep) S.inter(fn, k=0.0) smooth intersection (clip the whole so far) d, mat = S.eval(p, want_mat=True) Bounds make it fast: a primitive is evaluated exactly only where its bound could change the running result. Union order is fixed (quadratic smin is order dependent); add the big masses first, details after.
PART (interface every lane implements; subclass Part or duck-type it) name str eval(p, want_mat=False) -> d or (d, mat int16 array) bounds() -> (lo, hi) AABB in metres, must contain the surface landmarks() -> {name: (3,) array} named points (head: crown, brow_l, eye_l, nose_tip, chin ...) lines() -> {name: Line} the drawn lines artists put on this part (lid_upper_l, lip_line, nostril_l, ear_rim_l, crease_*); line art and the pixel redraw use them albedo(P, N, mat) -> (n,3) float 0..1 or None colour painted in part space (face zones, iris, lips) face_frame() -> None or dict(origin, x, y, z): face space for zones and the cel face threshold Helpers: Placed(part, R=None, t=(0,0,0), scale=1.0) moves a part (landmarks, lines and bounds follow); Union([part, ...], k=..., joints={(i, j): k}) assembles parts with a per-joint blend.
MATERIALS ids in MAT (skin 1, lip 2, sclera 3, iris 4, pupil 5, lid 6, nail 7, hair 8, brow 9, teeth 10, mouth 11, cloth 12, cloth2 13, shoe 14, lash 15, cornea 16); base colours in render.MAT_RGB.
Knob: PYDRAW_EXP anat=0 tells callers (the later wiring hooks) to ignore the anatomy package entirely."""import osimport numpy as np
F32 = np.float32_EXP = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv)ENABLED = _EXP.get("anat", "1") != "0"
MAT = dict(none=0, skin=1, lip=2, sclera=3, iris=4, pupil=5, lid=6, nail=7, hair=8, brow=9, teeth=10, mouth=11, cloth=12, cloth2=13, shoe=14, lash=15, cornea=16)SKIN, LIP, SCLERA, IRIS, PUPIL, LID, NAIL, HAIR, BROW, TEETH, MOUTH, CLOTH, CLOTH2, SHOE, LASH, CORNEA = range(1, 17)MAT_NAME = {v: k for k, v in MAT.items()}
# ------------------------------------------------------------------------------------------------ small mathdef _v(x): return np.asarray(x, float)
def norm(v): v = _v(v) return v / (np.linalg.norm(v) + 1e-12)
def length(v): return np.sqrt(np.einsum("ij,ij->i", v, v))
def rot(yaw=0.0, pitch=0.0, roll=0.0): """rotation matrix (rows = the local x, y, z axes in world) from degrees: yaw about +y (positive turns +z toward +x), pitch about +x (positive tips +z up), roll about +z""" y, p, r = np.radians([yaw, pitch, roll]) Ry = np.array([[np.cos(y), 0, -np.sin(y)], [0, 1, 0], [np.sin(y), 0, np.cos(y)]]) Rx = np.array([[1, 0, 0], [0, np.cos(p), np.sin(p)], [0, -np.sin(p), np.cos(p)]]) Rz = np.array([[np.cos(r), np.sin(r), 0], [-np.sin(r), np.cos(r), 0], [0, 0, 1]]) return Rz @ Rx @ Ry
def look(fwd, up=(0, 1, 0)): """rotation whose local +z is fwd and local +y is as close to up as possible (rows = local axes in world)""" z = norm(fwd) x = np.cross(_v(up), z) if np.linalg.norm(x) < 1e-9: x = np.cross((1, 0, 0), z) x = norm(x) y = np.cross(z, x) return np.stack([x, y, z])
def to_local(p, c, R=None): q = p - _v(c) return q if R is None else q @ np.asarray(R, float).T
# ------------------------------------------------------------------------------------------------ blendsdef smin(a, b, k): """quadratic polynomial smooth-min (blend thickness k in metres; never overshoots; order dependent)""" if k <= 0: return np.minimum(a, b) h = np.clip(.5 + .5 * (b - a) / k, 0, 1) return b + (a - b) * h - k * h * (1 - h)
def smin_h(a, b, k): """smooth-min plus the mix factor h (1 = surface belongs to a, 0 = to b) for blending materials""" if k <= 0: return np.minimum(a, b), (a <= b).astype(float) h = np.clip(.5 + .5 * (b - a) / k, 0, 1) return b + (a - b) * h - k * h * (1 - h), h
def smax(a, b, k): return -smin(-a, -b, k)
def carve(d, cut, k=0.0): """remove the solid `cut` from `d`; a large k leaves a soft rim (a brow forms on a carved socket)""" return smax(d, -cut, k)
def sabs(x, k=0.0): """soft |x|: sqrt(x^2 + k^2) - k ... no crease on the midline (k in metres)""" return np.abs(x) if k <= 0 else np.sqrt(x * x + k * k) - k
def mirror(p, k=0.0): """mirrored coordinates: x -> |x| (sharp) or soft |x| with a midline blend of width k; model the +x (left) side""" q = p.copy() q[:, 0] = sabs(p[:, 0], k) return q
# ------------------------------------------------------------------------------------------------ primitivesdef sphere(p, c, r): return length(p - _v(c)) - r
def ellipsoid(p, c, r, R=None): """ellipsoid with radii r (3,), optionally rotated by R (rows = its local axes); good-bound approximation""" q = to_local(p, c, R) / _v(r) k0 = length(q) k1 = length(q / _v(r)) return k0 * (k0 - 1.0) / np.maximum(k1, 1e-9)
def rbox(p, c, half, rr=0.0, R=None): q = np.abs(to_local(p, c, R)) - (_v(half) - rr) return length(np.maximum(q, 0)) + np.minimum(q.max(-1), 0) - rr
def plane(p, n, d=0.0): """signed distance to the plane n.p = d (positive on the n side)""" return p @ norm(n) - d
def capsule(p, a, b, r): a, b = _v(a), _v(b) pa, ba = p - a, b - a h = np.clip((pa @ ba) / max(ba @ ba, 1e-12), 0, 1) return length(pa - h[:, None] * ba) - r
def round_cone(p, a, b, ra, rb): """tapered capsule from a (radius ra) to b (radius rb), exact; limbs, finger segments, the nose bridge""" a, b = _v(a), _v(b) ba = b - a l2 = float(ba @ ba) if l2 < 1e-14: return length(p - a) - max(ra, rb) rr = ra - rb a2 = l2 - rr * rr il2 = 1.0 / l2 pa = p - a y = pa @ ba z = y - l2 w = pa * l2 - y[:, None] * ba x2 = np.einsum("ij,ij->i", w, w) y2 = y * y * l2 z2 = z * z * l2 k = np.sign(rr) * rr * rr * x2 return np.where(np.sign(z) * a2 * z2 > k, np.sqrt(x2 + z2) * il2 - rb, np.where(np.sign(y) * a2 * y2 < k, np.sqrt(x2 + y2) * il2 - ra, (np.sqrt(np.maximum(x2 * a2 * il2, 0)) + y * rr) * il2 - ra))
def torus_arc(p, c, u, v, Rmaj, r, half_ang, r_end=None): """an arc of a torus: circle of radius Rmaj in the plane spanned by unit vectors u, v around c, centred on the +u direction, spanning +-half_ang (radians); tube radius r at the middle tapering to r_end at the ends""" u, v = norm(u), norm(v) w = np.cross(u, v) q = p - _v(c) x, y, z = q @ u, q @ v, q @ w ang = np.arctan2(y, x) a = np.clip(ang, -half_ang, half_ang) cx, cy = Rmaj * np.cos(a), Rmaj * np.sin(a) d = np.sqrt((x - cx) ** 2 + (y - cy) ** 2 + z * z) if r_end is None: return d - r t = np.abs(a) / max(half_ang, 1e-9) return d - (r + (r_end - r) * t * t)
def bezier_t(p, a, b, c, iters=3): """distance from p to the quadratic Bezier a-b-c and the curve parameter t of the closest point (coarse samples then Newton steps on t; our own solver)""" a, b, c = _v(a), _v(b), _v(c) ts = np.linspace(0, 1, 9) best_d = np.full(len(p), np.inf) best_t = np.zeros(len(p)) for t in ts: q = (1 - t) ** 2 * a + 2 * (1 - t) * t * b + t * t * c d = np.einsum("ij,ij->i", p - q, p - q) m = d < best_d best_d = np.where(m, d, best_d) best_t = np.where(m, t, best_t) t = best_t A, B = b - a, a - 2 * b + c # C(t) = a + 2tA + t^2 B ; C' = 2A + 2tB ; C'' = 2B
def dist2(t): q = a + 2 * t[:, None] * A + (t * t)[:, None] * B r = q - p return np.einsum("ij,ij->i", r, r) # refine: a finer local search around the best sample, then Newton steps kept only when they improve w = 1 / 8 for _ in range(2): cand = [np.clip(t + w * s, 0, 1) for s in (-.75, -.5, -.25, .25, .5, .75)] for tc in cand: dc = dist2(tc) m = dc < best_d best_d = np.where(m, dc, best_d) t = np.where(m, tc, t) w /= 4 for _ in range(iters): q = a + 2 * t[:, None] * A + (t * t)[:, None] * B d1 = 2 * A + 2 * t[:, None] * B r = q - p g = np.einsum("ij,ij->i", r, d1) h = np.einsum("ij,ij->i", d1, d1) + np.einsum("ij,j->i", r, 2 * B) tn = np.clip(t - g / np.where(np.abs(h) < 1e-12, 1e-12, h), 0, 1) dn = dist2(tn) m = dn < best_d best_d = np.where(m, dn, best_d) t = np.where(m, tn, t) q = a + 2 * t[:, None] * A + (t * t)[:, None] * B return length(p - q), t
def bezier_tube(p, a, b, c, r0, r1, rmid=None): """a tube along the quadratic Bezier a-b-c whose radius goes r0 -> rmid -> r1 (lips, brows, locks, toes)""" d, t = bezier_t(p, a, b, c) if rmid is None: r = r0 + (r1 - r0) * t else: r = (1 - t) ** 2 * r0 + 2 * (1 - t) * t * rmid + t * t * r1 return d - r
def bezier_pts(a, b, c, n=16): t = np.linspace(0, 1, n)[:, None] return (1 - t) ** 2 * _v(a) + 2 * (1 - t) * t * _v(b) + t * t * _v(c)
# ------------------------------------------------------------------------------------------------ sculptclass Sculpt: """an ordered list of smooth unions / carves / intersections with bounding spheres (see module doc)"""
def __init__(self): self.ops = [] # (kind, fn, k, mat, (c, r) or None)
def add(self, fn, k=0.0, mat=SKIN, bound=None): self.ops.append(("add", fn, float(k), mat, None if bound is None else (_v(bound[0]), float(bound[1])))) return self
def carve(self, fn, k=0.0, mat=None, bound=None): self.ops.append(("carve", fn, float(k), mat, None if bound is None else (_v(bound[0]), float(bound[1])))) return self
def inter(self, fn, k=0.0, mat=None, bound=None): self.ops.append(("inter", fn, float(k), mat, None)) return self
def bounds(self): lo, hi = np.full(3, np.inf), np.full(3, -np.inf) for kind, fn, k, mat, b in self.ops: if kind == "add" and b is not None: lo = np.minimum(lo, b[0] - b[1]) hi = np.maximum(hi, b[0] + b[1]) return lo, hi
def eval(self, p, want_mat=False): n = len(p) d = np.full(n, 1e3) m = np.zeros(n, np.int16) if want_mat else None for kind, fn, k, mat, b in self.ops: if b is not None: lb = length(p - b[0]) - b[1] # a lower bound of the primitive's distance if kind == "add": need = lb < d + k else: need = lb < k - d if kind == "carve" else np.ones(n, bool) if not need.any(): continue if need.all(): e = fn(p) else: e = lb.copy() e[need] = fn(p[need]) else: e = fn(p) if kind == "add": if want_mat: dn, h = smin_h(e, d, k) m = np.where(h > .5, np.int16(mat), m) d = dn else: d = smin(e, d, k) elif kind == "carve": dn = smax(d, -e, k) if want_mat and mat is not None: m = np.where(-e > d, np.int16(mat), m) # the wall left by the carve d = dn else: dn = smax(d, e, k) if want_mat and mat is not None: m = np.where(e > d, np.int16(mat), m) d = dn return (d, m) if want_mat else d
class Line: """a drawn line on a part: pts (K,3) in part space, kind ('lid', 'lip', 'brow', 'nostril', 'ear', 'crease', 'contour', 'nail', 'knuckle'), weight (1 = a normal line, 2 = the darkest line like the lip line), redraw: True if the pixel path must redraw it at small sizes (eyes, brows, nose shadow, mouth)"""
def __init__(self, pts, kind="crease", weight=1.0, redraw=False, closed=False): self.pts = np.asarray(pts, float).reshape(-1, 3) self.kind, self.weight, self.redraw, self.closed = kind, float(weight), bool(redraw), bool(closed)
def moved(self, f): return Line(f(self.pts), self.kind, self.weight, self.redraw, self.closed)
class Part: """base class; subclasses set self.S = Sculpt() (or override eval) and fill _lm, _lines""" name = "part"
def __init__(self): self.S = Sculpt() self._lm = {} self._lines = {}
def eval(self, p, want_mat=False): return self.S.eval(p, want_mat)
def bounds(self): return self.S.bounds()
def landmarks(self): return dict(self._lm)
def lines(self): return dict(self._lines)
def albedo(self, P, N, mat): return None
def face_frame(self): return None
class Placed(Part): """a part moved into a parent frame: world = t + scale * (local @ R) ... R rows = local axes in world"""
def __init__(self, part, R=None, t=(0, 0, 0), scale=1.0, name=None): self.part, self.R = part, (np.eye(3) if R is None else np.asarray(R, float)) self.t, self.s = _v(t), float(scale) self.name = name or part.name
def _in(self, p): return ((p - self.t) @ self.R.T) / self.s
def _out(self, q): return (np.asarray(q, float) * self.s) @ self.R + self.t
def eval(self, p, want_mat=False): r = self.part.eval(self._in(p), want_mat) return (r[0] * self.s, r[1]) if want_mat else r * self.s
def bounds(self): lo, hi = self.part.bounds() cs = np.array([[x, y, z] for x in (lo[0], hi[0]) for y in (lo[1], hi[1]) for z in (lo[2], hi[2])]) w = self._out(cs) return w.min(0), w.max(0)
def landmarks(self): return {k: self._out(v) for k, v in self.part.landmarks().items() if np.ndim(v) == 1 and np.size(v) == 3}
def lines(self): return {k: L.moved(self._out) for k, L in self.part.lines().items()}
def albedo(self, P, N, mat): return self.part.albedo(self._in(P), N @ self.R.T, mat)
def face_frame(self): f = self.part.face_frame() if f is None: return None return dict(origin=self._out(f["origin"]), x=_v(f["x"]) @ self.R, y=_v(f["y"]) @ self.R, z=_v(f["z"]) @ self.R, scale=f.get("scale", 1.0) * self.s)
class Union(Part): """parts assembled in order; parts[i] melts into the union so far with k (default) or joints[(j, i)] / [(i, j)] which picks the blend at the joint between two named parts (the neck into the head: small; a lid: tiny)"""
def __init__(self, parts, k=0.0, joints=None, name="union"): self.parts, self.k, self.joints, self.name = list(parts), float(k), dict(joints or {}), name self._b = [p.bounds() for p in self.parts]
def _k(self, i): best = None for (a, b), k in self.joints.items(): if i in (a, b) and max(a, b) == i: best = k if best is None else max(best, k) return self.k if best is None else best
def eval(self, p, want_mat=False): d = np.full(len(p), 1e3) m = np.zeros(len(p), np.int16) if want_mat else None own = np.full(len(p), -1, np.int16) if want_mat else None for i, part in enumerate(self.parts): lo, hi = self._b[i] k = self._k(i) # bounded: the AABB distance is a lower bound; skip points it cannot reach q = np.maximum(np.maximum(lo - p, p - hi), 0) lb = length(q) need = lb < d + k if not need.any(): continue e = lb.copy() if want_mat: ee, mm = part.eval(p[need], True) e[need] = ee mi = np.zeros(len(p), np.int16) mi[need] = mm dn, h = smin_h(e, d, k) take = h > .5 m = np.where(take, mi, m) own = np.where(take, np.int16(i), own) d = dn else: e[need] = part.eval(p[need]) d = smin(e, d, k) if want_mat: self._last_owner = own return d, m return d
def owner(self, p): _, _ = self.eval(p, True) return self._last_owner
def bounds(self): lo = np.min([b[0] for b in self._b], 0) hi = np.max([b[1] for b in self._b], 0) return lo, hi
def landmarks(self): out = {} for part in self.parts: for k, v in part.landmarks().items(): out[k if k not in out else part.name + "." + k] = v return out
def lines(self): out = {} for part in self.parts: for k, v in part.lines().items(): out[k if k not in out else part.name + "." + k] = v return out
def albedo(self, P, N, mat): # rule: each part paints the pixels it owns; parts that paint nothing fall back to the material table own = self.owner(P) out = None for i, part in enumerate(self.parts): s = own == i if not s.any(): continue a = part.albedo(P[s], N[s], mat[s]) if a is None: continue if out is None: out = np.full((len(P), 3), np.nan, F32) out[s] = a return out
def face_frame(self): for part in self.parts: f = part.face_frame() if f is not None: return f return None
class FnPart(Part): """adapter: wrap a plain function fn(p) -> (d, mat) (or -> d) as a Part, e.g. FnPart(lambda p: head.head_sdf(p, L), bounds=(lo, hi), landmarks=L, lines={...}, albedo=fn(P, N, mat), face_frame=dict(...))"""
def __init__(self, fn, bounds, landmarks=None, lines=None, albedo=None, face_frame=None, name="fnpart"): self.fn, self._bnd, self.name = fn, (_v(bounds[0]), _v(bounds[1])), name self._lm = {k: _v(v) for k, v in (landmarks or {}).items() if np.ndim(v) == 1 and np.size(v) == 3} self._lines = dict(lines or {}) self._alb, self._ff = albedo, face_frame
def eval(self, p, want_mat=False): r = self.fn(p) if isinstance(r, tuple): d, m = r else: d, m = r, np.full(len(p), SKIN, np.int16) return (d, np.asarray(m, np.int16)) if want_mat else d
def bounds(self): return self._bnd
def albedo(self, P, N, mat): return None if self._alb is None else self._alb(P, N, mat)
def face_frame(self): return self._ff
def lm_get(lm, *names): """landmark lookup that accepts either case of the side suffix (_l / _L) and the first of several aliases""" for n in names: for k in (n, n[:-1] + n[-1].upper() if n[-2:] in ("_l", "_r") else n, n[:-1] + n[-1].lower() if n[-2:] in ("_L", "_R") else n): if k in lm and np.ndim(lm[k]) == 1 and np.size(lm[k]) == 3: return np.asarray(lm[k], float) return None
# ------------------------------------------------------------------------------------------------ test partclass EggHead(Part): """a test part for the study sheet: the Loomis ball + jaw as two ellipsoids, sockets carved with a soft rim, a round-cone nose, Bezier-tube lips, painted eyeballs. Only here to prove the core and the sheet; the head and features lanes build the real ones. Height (crown to chin) = H.""" name = "egghead"
def __init__(self, H=0.23, hair=False): super().__init__() u = H crown, chin = .5 * u, -.5 * u # origin at the head centre eye_y = 0.0 # rule: eyes at half the head height (Loomis R1) brow_y, nose_y = (1 - 1.5 / 3.5) * u - .5 * u, (1 - 2.5 / 3.5) * u - .5 * u mouth_y = (1 - .81) * u - .5 * u W = .571 * u # skull width (Bridgman) ex = W / 5 * 1.0 # eye half-gap: one eye width between the eyes S = self.S S.add(lambda p: ellipsoid(p, (0, .06 * u, -.06 * u), (W / 2, .44 * u, .5 * u)), mat=SKIN, bound=((0, .06 * u, -.06 * u), .5 * u)) jc = (0, -.2 * u, .04 * u) S.add(lambda p: ellipsoid(p, jc, (.38 * W, .3 * u, .36 * u)), k=.06 * u, bound=(jc, .36 * u)) # sockets carved with a soft rim: the brow and cheek planes come from the carve sc = (ex, eye_y + .01 * u, .38 * u) S.carve(lambda p: ellipsoid(mirror(p), sc, (.13 * u, .085 * u, .1 * u)), k=.04 * u, bound=(sc, .2 * u)) # eyeballs (painted, see albedo); the lid as an inflated shell would come from the features lane self.eyes = [(_v((ex, eye_y, .36 * u)), .052 * u), (_v((-ex, eye_y, .36 * u)), .052 * u)] for c, r in self.eyes: S.add(lambda p, c=c, r=r: sphere(p, c, r), k=0.0, mat=SCLERA, bound=(c, r)) # lids: the eyeball inflated (lid thickness), kept only above a tilted cut (upper) or below one (lower), # so the upper lid clips the top of the iris and the lower lid tucks under it for c, r in self.eyes: S.add(lambda p, c=c, r=r: smax(sphere(p, c, r * 1.1), -plane(p - c, (0, 1, -.35), r * .22), r * .05), k=.01 * u, mat=LID, bound=(c, r * 1.2)) S.add(lambda p, c=c, r=r: smax(sphere(p, c, r * 1.06), plane(p - c, (0, 1, .2), -r * .62), r * .05), k=.01 * u, mat=LID, bound=(c, r * 1.2)) # nose: bridge as a round cone, ball and wings, underside carved nostrils nt = _v((0, nose_y + .03 * u, .47 * u)) S.add(lambda p: round_cone(p, _v((0, brow_y - .02 * u, .38 * u)), nt, .028 * u, .04 * u), k=.03 * u, bound=(nt, .3 * u)) S.add(lambda p: ellipsoid(mirror(p), (.04 * u, nose_y + .025 * u, .42 * u), (.035 * u, .03 * u, .035 * u)), k=.02 * u, bound=((0, nose_y, .42 * u), .1 * u)) S.carve(lambda p: ellipsoid(mirror(p), (.028 * u, nose_y + .008 * u, .45 * u), (.014 * u, .008 * u, .02 * u)), k=.006 * u, mat=MOUTH, bound=((0, nose_y, .45 * u), .06 * u)) # lips: upper and lower as tapered Bezier tubes; the mouth line carved between them ml, mr = _v((.1 * u, mouth_y, .33 * u)), _v((-.1 * u, mouth_y, .33 * u)) S.add(lambda p: bezier_tube(p, mr + (0, .004 * u, 0), (0, mouth_y + .03 * u, .43 * u), ml + (0, .004 * u, 0), .006 * u, .006 * u, .03 * u), k=.012 * u, mat=LIP, bound=((0, mouth_y, .38 * u), .14 * u)) S.add(lambda p: bezier_tube(p, mr - (0, .004 * u, 0), (0, mouth_y - .045 * u, .42 * u), ml - (0, .004 * u, 0), .006 * u, .006 * u, .034 * u), k=.012 * u, mat=LIP, bound=((0, mouth_y, .38 * u), .14 * u)) S.carve(lambda p: bezier_tube(p, mr, (0, mouth_y - .004 * u, .45 * u), ml, .002 * u, .002 * u, .004 * u), k=.004 * u, mat=MOUTH, bound=((0, mouth_y, .38 * u), .14 * u)) # ears: flattened ellipsoid with a carved bowl, between the brow and nose lines, set back for sx in (1, -1): ec = _v((sx * W * .5, (brow_y + nose_y) / 2, -.02 * u)) Re = rot(yaw=sx * 70, pitch=-15) S.add(lambda p, ec=ec, Re=Re: ellipsoid(p, ec, (.06 * u, .14 * u, .02 * u), Re), k=.015 * u, bound=(ec, .15 * u)) if hair: # test hair: the cranium inflated into a shell, cut by a hairline plane tilted back from the brow, plus a # fringe lock (only to exercise the hair light and the cel fringe band) hc = (0, .06 * u, -.06 * u) S.add(lambda p: smax(ellipsoid(p, hc, (W / 2 + .05 * u, .5 * u, .56 * u)), -plane(p, (0, -.45, -1), -.12 * u - .045 * u), .02 * u), k=.0, mat=HAIR, bound=(hc, .6 * u)) S.add(lambda p: bezier_tube(p, (-.2 * u, .36 * u, .3 * u), (-.02 * u, .26 * u, .47 * u), (.16 * u, .2 * u, .42 * u), .06 * u, .015 * u, .045 * u), k=.03 * u, mat=HAIR, bound=((0, .28 * u, .4 * u), .3 * u)) self.H, self.u = H, u L = self._lm L.update(crown=_v((0, crown, 0)), chin=_v((0, chin + .02 * u, .38 * u)), brow_l=_v((ex, brow_y, .44 * u)), brow_r=_v((-ex, brow_y, .44 * u)), eye_l=self.eyes[0][0] + (0, 0, self.eyes[0][1]), eye_r=self.eyes[1][0] + (0, 0, self.eyes[1][1]), nose_tip=nt + (0, 0, .045 * u), nose_base=_v((0, nose_y, .44 * u)), mouth_l=ml, mouth_r=mr, mouth_c=_v((0, mouth_y, .44 * u)), cheekbone_l=_v((W * .38, nose_y + .06 * u, .3 * u)), cheekbone_r=_v((-W * .38, nose_y + .06 * u, .3 * u))) # drawn lines (line art + the pixel redraw) for sx, s in ((1, "l"), (-1, "r")): c, r = self.eyes[0 if sx > 0 else 1] ang = np.linspace(-1.1, 1.1, 9) up = np.stack([c[0] + sx * 0 + np.sin(ang) * r * 1.05, c[1] + np.cos(ang) * r * .55 + .004 * u, c[2] + np.cos(ang) * r * .75], -1) self._lines["lid_upper_" + s] = Line(up, "lid", 1.6, redraw=True) self._lines["brow_" + s] = Line(bezier_pts((sx * .5 * ex, brow_y + .02 * u, .47 * u), (sx * 1.0 * ex, brow_y + .05 * u, .45 * u), (sx * 1.6 * ex, brow_y + .02 * u, .36 * u), 8), "brow", 1.4, True) self._lines["nostril_" + s] = Line(bezier_pts((sx * .012 * u, nose_y + .006 * u, .47 * u), (sx * .032 * u, nose_y + .0 * u, .465 * u), (sx * .05 * u, nose_y + .015 * u, .44 * u), 5), "nostril", 1.0, True) self._lines["lip_line"] = Line(bezier_pts(mr, (0, mouth_y - .004 * u, .45 * u), ml, 12), "lip", 2.0, True)
def albedo(self, P, N, mat): out = np.zeros((len(P), 3), F32) + np.nan for c, r in self.eyes: s = mat == SCLERA if not s.any(): continue q = P[s] - c near = np.einsum("ij,ij->i", q, q) < (r * 1.3) ** 2 idx = np.nonzero(s)[0][near] q = q[near] / r a = np.degrees(np.arccos(np.clip(q[:, 2], -1, 1))) # angle from the gaze axis (+z) col = np.where((a < 13)[:, None], (.08, .06, .05), np.where((a < 30)[:, None], (.36, .25, .14), (.86, .8, .76))) out[idx] = col return out
def face_frame(self): return dict(origin=_v((0, 0, 0)), x=_v((1, 0, 0)), y=_v((0, 1, 0)), z=_v((0, 0, 1)), scale=self.H)
# ------------------------------------------------------------------------------------------------ G-buffer rendererTILE = 32768 # rays per tile: keeps every temporary array a few MB
class View: """orthographic camera. yaw/pitch in degrees turn the PART (yaw 0 = front, 35 = three-quarter with the face turned toward the viewer's left, 90 = profile facing the viewer's left). Fits the part's bounds into size px with margin, unless scale (px per metre) and centre are given (several parts on one scale)."""
def __init__(self, yaw=0.0, pitch=0.0, size=512, margin=.08, scale=None, centre=None, roll=0.0): self.yaw, self.pitch, self.roll, self.size, self.margin = yaw, pitch, roll, int(size), margin self.R = rot(yaw, -pitch, roll) # world -> view rows; view: x right, y up, z toward the viewer self.scale, self.centre = scale, centre
def fit(self, lo, hi): cs = np.array([[x, y, z] for x in (lo[0], hi[0]) for y in (lo[1], hi[1]) for z in (lo[2], hi[2])]) V = cs @ self.R.T vlo, vhi = V.min(0), V.max(0) if self.scale is None: span = max(vhi[0] - vlo[0], vhi[1] - vlo[1]) self.scale = self.size * (1 - 2 * self.margin) / max(span, 1e-6) if self.centre is None: self.centre = (vlo + vhi) / 2 self.zf, self.zb = vhi[2] + 1e-3, vlo[2] - 1e-3 return self
def to_view(self, P): return np.asarray(P, float) @ self.R.T
def project(self, P): """world points (n,3) -> pixel x, y (y down) and view depth z (bigger = nearer)""" V = self.to_view(np.asarray(P, float).reshape(-1, 3)) x = (V[:, 0] - self.centre[0]) * self.scale + self.size / 2 y = -(V[:, 1] - self.centre[1]) * self.scale + self.size / 2 return x, y, V[:, 2]
class GBuffer(dict): """hit (H,W) bool; depth (view z, metres, nearer = larger; -inf = miss); P world pos; N world normal; Nv view normal (x right, y up, z to viewer); mat int16; shadow (key light soft shadow 0..1, 1 = lit); ao 0..1; light = the key direction in view space; view; part; lm2d {name: (x, y, visible)}; lines2d [(name, Line, xy, vis)]""" __getattr__ = dict.__getitem__
KEY_VIEW = norm((-.55, .62, .56)) # default key light in VIEW space: upper left, in front (one key light)
def _normal(part, P, e): # tetrahedral central difference: 4 evaluations k = np.array([[1, -1, -1], [-1, -1, 1], [-1, 1, -1], [1, 1, 1]], float) g = np.zeros_like(P) for kk in k: g += kk * part.eval(P + kk * e)[:, None] return g / (np.linalg.norm(g, axis=1, keepdims=True) + 1e-12)
def _soft_shadow(part, P, L, eps, tmax, steps=28, k=10.0): res = np.ones(len(P)) t = np.full(len(P), eps * 4) alive = np.arange(len(P)) for _ in range(steps): if not len(alive): break d = part.eval(P[alive] + L * t[alive, None]) res[alive] = np.minimum(res[alive], k * d / t[alive]) t[alive] += np.clip(d, eps, tmax / 8) keep = (d > eps * .2) & (t[alive] < tmax) res[alive[d <= eps * .2]] = 0 alive = alive[keep] r = np.clip(res, 0, 1) return r * r * (3 - 2 * r)
def _ao(part, P, N, span): occ = np.zeros(len(P)) w = 1.0 for i in range(1, 5): h = span * i / 4 occ += w * (h - part.eval(P + N * h)) / span w *= .6 return np.clip(1 - .9 * occ, 0, 1)
def trace(part, view=None, size=512, steps=110, light=None, shadows=True, ao=True): """sphere-trace a part (any object with eval / bounds) into a G-buffer. Bounded: only rays inside the part's projected box are traced, in tiles of TILE rays (memory stays tens of MB at 512 px).""" view = view or View(size=size) lo, hi = part.bounds() lo, hi = _v(lo), _v(hi) view.fit(lo, hi) S = view.size L_view = norm(KEY_VIEW if light is None else light) L_world = L_view @ view.R # view -> world cs = np.array([[x, y, z] for x in (lo[0], hi[0]) for y in (lo[1], hi[1]) for z in (lo[2], hi[2])]) bx, by, _ = view.project(cs) x0, x1 = max(0, int(np.floor(bx.min())) - 1), min(S, int(np.ceil(bx.max())) + 1) y0, y1 = max(0, int(np.floor(by.min())) - 1), min(S, int(np.ceil(by.max())) + 1) depth = np.full((S, S), -np.inf, F32) P = np.zeros((S, S, 3), F32) N = np.zeros((S, S, 3), F32) mat = np.zeros((S, S), np.int16) sh = np.ones((S, S), F32) aoa = np.ones((S, S), F32) eps = .35 / view.scale span = (hi - lo).max() Rt = view.R # view row vector v -> world v @ R ys, xs = np.mgrid[y0:y1, x0:x1] ys, xs = ys.ravel(), xs.ravel() for s0 in range(0, len(xs), TILE): tx, ty = xs[s0:s0 + TILE], ys[s0:s0 + TILE] vx = (tx + .5 - S / 2) / view.scale + view.centre[0] vy = -(ty + .5 - S / 2) / view.scale + view.centre[1] n = len(tx) t = np.zeros(n) hit = np.zeros(n, bool) alive = np.arange(n) zlen = view.zf - view.zb for _ in range(steps): if not len(alive): break v = np.stack([vx[alive], vy[alive], view.zf - t[alive]], -1) d = part.eval(v @ Rt) h = d < eps hit[alive[h]] = True t[alive] += np.maximum(d * .9, eps * .3) alive = alive[~h & (t[alive] < zlen)] if not hit.any(): continue idx = np.nonzero(hit)[0] vh = np.stack([vx[idx], vy[idx], view.zf - t[idx]], -1) pw = vh @ Rt nw = _normal(part, pw, max(.5 / view.scale, 1e-5)) _, mm = part.eval(pw, True) py, px = ty[idx], tx[idx] depth[py, px] = vh[:, 2] P[py, px] = pw N[py, px] = nw mat[py, px] = mm if shadows: sh[py, px] = _soft_shadow(part, pw + nw * eps * 2, L_world, eps, span * 1.5) if ao: aoa[py, px] = _ao(part, pw, nw, span * .06) hitm = np.isfinite(depth) Nv = (N.reshape(-1, 3) @ view.R.T).reshape(S, S, 3).astype(F32) G = GBuffer(hit=hitm, depth=depth, P=P, N=N, Nv=Nv, mat=mat, shadow=sh, ao=aoa, light=L_view, light_world=L_world, view=view, part=part, size=S) lm = part.landmarks() G["lm2d"] = project_landmarks(G, lm) lines = part.lines() if _EXP.get("aautoline", "1") != "0": for k, v in auto_lines(lm, lines).items(): lines.setdefault(k, v) G["lines2d"] = project_lines(G, lines) return G
def auto_lines(lm, have): """fallback drawn lines from landmarks when a part gives none of that kind: the lip line through the mouth corners and centre, a nostril shadow under the nose base. Features lanes replace these with their own lines.""" kinds = {L.kind for L in have.values()} out = {} ml, mc, mr = lm_get(lm, "mouth_l"), lm_get(lm, "mouth_c"), lm_get(lm, "mouth_r") if "lip" not in kinds and ml is not None and mr is not None and mc is not None: mid = 2 * mc - (ml + mr) / 2 # Bezier control so the curve passes through mouth_c out["lip_line"] = Line(bezier_pts(mr, mid, ml, 12), "lip", 2.0, redraw=True) nb = lm_get(lm, "nose_base") if "nostril" not in kinds and nb is not None: w = .03 * (np.linalg.norm(ml - mr) / .2 if ml is not None and mr is not None else 1) for sx, s in ((1, "l"), (-1, "r")): out["nostril_" + s] = Line([nb + (sx * w * .3, .004, 0), nb + (sx * w, .006, -.01)], "nostril", 1.0, True) return out
def _visible(G, x, y, z, tol=None): S = G["size"] tol = tol if tol is not None else 3.0 / G["view"].scale xi, yi = np.clip(np.round(x - .5).astype(int), 0, S - 1), np.clip(np.round(y - .5).astype(int), 0, S - 1) inb = (x >= 0) & (x < S) & (y >= 0) & (y < S) dz = G["depth"][yi, xi] return inb & (~np.isfinite(dz) | (z >= dz - tol))
def project_landmarks(G, lm): out = {} if not lm: return out names = [k for k in lm if np.ndim(lm[k]) == 1 and np.size(lm[k]) == 3] if not names: return out pts = np.array([lm[k] for k in names], float) x, y, z = G["view"].project(pts) vis = _visible(G, x, y, z) S = G["size"] xi, yi = np.clip(x.astype(int), 0, S - 1), np.clip(y.astype(int), 0, S - 1) on_eye = np.isin(G["mat"][yi, xi], (SCLERA, IRIS, PUPIL, CORNEA)) for i, k in enumerate(names): if k.lower().startswith(("eye_", "pupil_", "iris_")) and on_eye[i]: vis[i] = True out[k] = (float(x[i]), float(y[i]), bool(vis[i])) return out
def project_lines(G, lines): out = [] for name, L in lines.items(): x, y, z = G["view"].project(L.pts) out.append((name, L, np.stack([x, y], -1), _visible(G, x, y, z))) return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175"""The ear as one SDF sculpt (wave 17 features lane). Rules from docs/research17/units/nose_mouth_ear.md section 3(E1-E11). Unit U = brow line to nose base (Loomis); origin = the ear canal; built for the LEFT ear (+x = out of thehead), y up, z forward; side=-1 mirrors it.
plate the auricle is a thin cupped plate whose outline is a big upper oval and a much smaller lobe [E5] helix the outer rim, a tapered tube in a question-mark hook that starts INSIDE the concha (the crus) about half way up, runs up the front, over the top, down the back and fades into the lobe [E4] antihelix the Y inside the rim: a stem rising from above the antitragus, splitting into a wide soft upper branch and a thin sharp lower branch [E4] concha the deep bowl in front of the antihelix that pushes the ear out from the head, the canal in it [E4, E7] tragus the flap overhanging the canal from the front; the antitragus smaller, behind and below; the intertragic notch (the keyhole) between them [E4] lobe the dot of the question mark, free of the cheek [E4, E5] size length 1 U (top on the brow line, bottom on the nose base) [E1]; width .55 U [E11] tilt the long axis leans back, parallel to the nose dorsum (about 15-20 deg) [E3] flare the back of the ear stands out from the head (front view: a rotated oval, not a flat C) [E7]
Ear(context=True) is the study part: the ear on a slab of the side of the head. Knob: PYDRAW_EXP earsculpt=0 isread by callers that place it."""import numpy as np
from .featkit import (FeaturePart, U_ADULT, length, smin, smax, sphere, ellipsoid, round_cone, smoothstep, bez3, tube_r, rot_x, rot_y, SKIN, MOUTH)from .core import Sculpt
P0 = dict(length=1.0, width=0.55, tilt=17.0, flare=13.0, lobe=0.31, helix_r=0.042, fem=0.0)
class _Ear: def __init__(self, context=True, **kw): p = dict(P0) p.update(kw) self.p = p self.context = context L = p["length"] self.k = L # all flat-frame numbers below are fractions of the ear length self.Rt = rot_x(np.radians(-p["tilt"])) self.Rf = rot_y(np.radians(-p["flare"])) self.M = self.Rf @ self.Rt # flat ear frame (c, b, -a) -> head-side frame w = p["width"] / 0.55 k = self.k # the flat frame: a = back from the canal, b = up, c = out of the plate (the face of the ear) self.helix_path = bez3([(0.02, 0.06), (-0.10, 0.30), (0.02, 0.60), (0.22, 0.56)], 10) self.helix_path = np.concatenate([self.helix_path, bez3([(0.22, 0.56), (0.48 * w, 0.52), (0.50 * w, 0.12), (0.44 * w, -0.06)], 10)[1:], bez3([(0.44 * w, -0.06), (0.40 * w, -0.20), (0.34 * w, -0.26), (0.30, -0.30)], 6)[1:]]) self.anti_stem = bez3([(0.27, -0.16), (0.33, -0.05), (0.32, 0.08), (0.27, 0.18)], 6) self.anti_up = bez3([(0.27, 0.18), (0.27, 0.28), (0.30, 0.36), (0.33, 0.42)], 5) self.anti_lo = bez3([(0.27, 0.18), (0.20, 0.25), (0.12, 0.30), (0.05, 0.32)], 5) self.S = self._sculpt()
def flat(self, q): """head-side frame -> flat ear (a, b, c)""" e0 = q @ self.M # (M^T q) for row vectors return np.stack([-e0[:, 2], e0[:, 1], e0[:, 0]], -1) / self.k
def unflat(self, f): f = np.asarray(f, float).reshape(-1, 3) * self.k e0 = np.stack([f[:, 2], f[:, 1], -f[:, 0]], -1) return e0 @ self.M.T
def cup(self, a, b): """the plate is cupped: the rim stands further out than the middle""" return 0.05 * ((a - 0.2) ** 2 / 0.09 + (b - 0.1) ** 2 / 0.2)
def outline(self, a, b): w = self.p["width"] / 0.55 top = ellipsoid(np.stack([a, b, np.zeros_like(a)], -1), (0.2 * w, 0.13, 0), (0.27 * w, 0.43, 1.0)) lr = 0.36 * self.p["lobe"] lobe = ellipsoid(np.stack([a, b, np.zeros_like(a)], -1), (0.19, -0.3, 0), (lr, lr * 1.02, 1.0)) return smin(top, lobe, 0.08)
def _sculpt(self): p = self.p S = Sculpt() F = self.flat k = self.k if self.context: # the side of the head (behind the jaw, E2) as a gently curved slab S.add(lambda q: ellipsoid(q, (-1.1, 0.0, -0.1), (1.12, 1.6, 1.4)), 0.0, SKIN, None)
def plate(q): f = F(q) d2 = self.outline(f[:, 0], f[:, 1]) c0 = self.cup(f[:, 0], f[:, 1]) return smax(d2, np.abs(f[:, 2] - c0) - 0.022, 0.02) * k S.add(plate, 0.05 if self.context else 0.0, SKIN, None) # the root: the front of the ear and the back of the concha grow out of the head S.add(lambda q: ellipsoid(F(q), (0.06, 0.02, -0.06), (0.12, 0.3, 0.07)) * k, 0.06, SKIN, None) hr = p["helix_r"] n = len(self.helix_path) radii = hr * np.concatenate([np.linspace(0.25, 1.0, 6), np.ones(n - 12), np.linspace(1.0, 0.3, 6)]) dive = np.concatenate([np.linspace(-0.05, 0.0, 6), np.zeros(n - 12), np.linspace(0.0, -0.03, 6)])
def helix(q): # the rim is a flattened band curling forward, not a round tube: squash the tube across the plate f = F(q) * np.array([1.0, 1.0, 1.5]) # the root dives into the concha as a ridge and the tail fades into the lobe (no bead ends) pts = np.array([(a, b, (self.cup(a, b) + 0.035 + dv) * 1.5) for (a, b), dv in zip(self.helix_path, dive)]) return tube_r(f, pts, radii) * k / 1.5 S.add(helix, 0.025, SKIN, None)
def anti(q): f = F(q) mk = lambda path, r0, r1: tube_r(f, np.array([(a, b, self.cup(a, b) + 0.03) for a, b in path]), np.linspace(r0, r1, len(path))) d = smin(mk(self.anti_stem, 0.04, 0.045), mk(self.anti_up, 0.045, 0.034), 0.03) return smin(d, mk(self.anti_lo, 0.03, 0.016), 0.015) * k S.add(anti, 0.03, SKIN, None) # tragus and antitragus with the intertragic notch between [E4] S.add(lambda q: ellipsoid(F(q), (-0.045, -0.03, 0.055), (0.03, 0.085, 0.04)) * k, 0.045, SKIN, None) # tragus: a flap S.add(lambda q: ellipsoid(F(q), (0.2, -0.18, 0.06), (0.06, 0.03, 0.03)) * k, 0.04, SKIN, None) # lobe: a soft pad, thicker than the rim [E5] lr = 0.36 * p["lobe"] S.add(lambda q: ellipsoid(F(q), (0.19, -0.31, 0.03), (lr * 0.95, lr * 0.95, 0.05)) * k, 0.03, SKIN, None) # concha: the deep bowl, the canal in it [E4] S.carve(lambda q: ellipsoid(F(q), (0.12, -0.03, 0.06), (0.13, 0.15, 0.085)) * k, 0.03, None, None) S.carve(lambda q: ellipsoid(F(q), (0.21, 0.27, 0.075), (0.08, 0.07, 0.03)) * k, 0.02, None, None) # fossa S.carve(lambda q: sphere(F(q), (-0.005, -0.04, -0.03), 0.032) * k, 0.015, MOUTH, None) # canal if self.context: S.inter(lambda q: ellipsoid(q, (-0.2, 0.0, -0.15), (0.6, 0.85, 0.75)), 0.08) return S
def sdf(self, q): return self.S.eval(q)
def mat(self, q): return self.S.eval(q, True)[1]
def paint(self, q, n, mat): col = np.full((len(q), 3), np.nan) col[mat == MOUTH] = (0.3, 0.14, 0.12) # the ear is warmer / redder than the face (thin cartilage, blood) [Gurney zone] f = self.flat(q) r = np.sqrt(((f[:, 0] - 0.2) / 0.45) ** 2 + ((f[:, 1] - 0.08) / 0.68) ** 2) w = smoothstep(1.1, 0.7, r) * (mat == SKIN) s = w > 0.02 skin, warm = np.array([0.93, 0.76, 0.64]), np.array([0.92, 0.68, 0.58]) col[s] = skin[None] * (1 - w[s, None]) + warm[None] * w[s, None] return col
def lines(self): pts = np.array([(a, b, self.cup(a, b) + 0.035 + 0.04) for a, b in self.helix_path]) rim = self.unflat(pts) anti = np.array([(a, b, self.cup(a, b) + 0.06) for a, b in np.concatenate([self.anti_stem, self.anti_up[1:]])]) t = np.linspace(-0.4, np.pi + 0.6, 14) concha = np.stack([0.12 + 0.13 * np.cos(t), -0.03 + 0.15 * np.sin(t), np.full_like(t, 0.02)], -1) return dict(ear_rim=(rim, "ear", 1.0, False), antihelix=(self.unflat(anti), "ear", 0.6, False), concha=(self.unflat(concha), "ear", 0.5, False))
def landmarks(self): u = self.unflat pts = u([(0.2, 0.57, 0.05), (0.19, -0.42, 0.03), (0.02, -0.04, 0.0), (-0.045, -0.03, 0.1), (0.19, -0.31, 0.06)]) return dict(top=pts[0], bottom=pts[1], ear_top=pts[0], ear_bot=pts[1], ear_canal=pts[2], tragus=pts[3], lobe=pts[4])
class Ear(FeaturePart): """the ear as a core Part in metres; side=+1 left ear (landmarks *_l), -1 right"""
def __init__(self, side=1, context=True, U=U_ADULT, suffix=True, **params): m = _Ear(context=context, **params) m.lo, m.hi = ((-0.82, -0.88, -0.92), (0.42, 0.88, 0.62)) if context else ((-0.1, -0.55, -0.55), (0.4, 0.75, 0.25)) super().__init__(m, unit=U, side=side, name="ear_" + ("l" if side > 0 else "r")) if suffix: sfx = "_l" if side > 0 else "_r" self._lm = {k + sfx: v for k, v in self._lm.items()} self._lines = {k + sfx: v for k, v in self._lines.items()} p = m.p self.params = dict(U=U, length=p["length"] * U, width_frac=p["width"] / p["length"], tilt=p["tilt"], flare=p["flare"])
def build(side=1, context=True, U=U_ADULT, **params): return Ear(side=side, context=context, U=U, suffix=False, **params)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412"""The eye as one SDF sculpt (wave 17 features lane), neutral expression only. Rules from docs/research17/units/eye.md(numbers in W = lid-fissure width; rule ids in brackets):
ball a sphere r = .47 W [1] with a cornea bump [10], widened toward the corners by a thin conjunctival ellipsoid so the fissure (1 W) can be wider than the globe (24 vs 25.8 mm) [3] lids shells of the eyeball (upper t .10 W, lower t .07 W) [9] cut by planes HINGED ON THE CANTHAL AXIS [2]; the hinge angle twists along the axis so the upper apex sits 1/3 W from the inner corner and the lower nadir 2/3 W [7]; the outer corner is .078 W higher than the inner [6]; the hinge angles are SOLVED so the upper margin hides the top of the iris (MRD1 .137 W) and the lower margin rests near the lower limbus [8]; because the lid is a shell of the eyeball (cornea included) the cornea bulges the upper lid [10] crease a groove .10 W above the upper margin, ending before both corners, the skin above it a little fuller [11] brow painted hair zone in face space: head over the inner corner, peak at .75 W, tail on the nose-wing to outer-corner line, lower edge .40 W above the lid [12]; thick at the head, thin at the tail socket (study context only; on a head the head lane owns it) the orbit carved with smooth-max, a brow-ridge overhang, the nose-bridge wall and the cheek [13, 14] caruncle a small pink wedge in the inner corner, a little low [14] lashes one dark band on the upper margin flaring outward, no spikes [15]; the lower margin a light rim [M19] paint iris (r .232 W) and pupil (.35 of the iris) PAINTED on the ball by distance from the gaze axis, so the ellipse rule in 3/4 and profile comes for free [23]; the iris lit on the side away from the light, limbal ring darker; the sclera never white, darker toward the corners and under the upper lid [26, 27]; the catchlight on the cornea where it mirrors the key light into the eye of the viewer [29]
build(side=+1, **params) -> featkit.Part in the eye frame: origin = ball centre, unit W, +x toward the ear for theLEFT eye (side=+1; side=-1 mirrors), +y up, +z forward. landmarks: inner, outer, pupil, ball, ul_apex, ll_nadir,crease_mid, brow_head, brow_peak, brow_tail. lines: upper_lid, lower_lid, crease, iris, pupil, brow, lash.Knob: PYDRAW_EXP eyesculpt=0 is checked by callers that would place this eye on a head (none in the drawing path yet)."""import mathimport numpy as np
from .featkit import (F32, FeaturePart, W_ADULT, length, smin, smax, sphere, ellipsoid, smoothstep, rot_y, on, SKIN, SCLERA, IRIS, PUPIL, LID, LASH, BROW)
LIDRIM = CARUNCLE = LID # the wet lid rim and the caruncle are LID material, painted pink by the eye itself
P0 = dict(tilt=0.078, ball_r=0.47, pupil_y=0.145, iris_r=0.232, pupil_frac=0.35, mrd1=0.137, mrd2=0.23, ul_apex_x=0.37, ll_nadir_x=0.67, lid_t_up=0.10, lid_t_lo=0.07, crease=0.10, brow_gap=0.40, brow_peak_x=0.75, lash_t=0.022, catch_off=0.12, sclera_v=0.80, gaze=(0.0, 0.0), inner_z=0.10, outer_z=-0.12, fem=0.0, iris_col=(0.36, 0.25, 0.15), brow_col=(0.26, 0.17, 0.11), skin=(0.93, 0.76, 0.64))
def _unit(v): v = np.asarray(v, F32) return v / np.linalg.norm(v)
class _Eye: def __init__(self, context=True, **kw): p = dict(P0) p.update(kw) self.p = p self.context = context R = p["ball_r"] self.R = R gx, gy = p["gaze"] self.g = _unit([math.sin(math.radians(gx)), math.sin(math.radians(gy)), 1.0]) self.gap = 0.006 # the canthal axis [5, 6]: corners below the pupil centre, the outer one higher and set back self.I = np.array([-0.5, -p["pupil_y"], p["inner_z"]], F32) self.O = np.array([0.5, -p["pupil_y"] + p["tilt"], p["outer_z"]], F32) a = self.O - self.I self.half = float(np.linalg.norm(a)) / 2 self.a = a / np.linalg.norm(a) self.Mc = (self.I + self.O) / 2 ef = np.array([0, 0, 1], F32) - self.a[2] * self.a self.ef = ef / np.linalg.norm(ef) self.eu = np.cross(self.ef, self.a).astype(F32) # cornea bump [10]: a smaller sphere set forward on the gaze axis self.cc = self.g * R * 0.42 self.cr = R * 0.62 # conjunctival ellipsoid: lets the corners lie on the eye surface 0.5 W from the centre, lateral end set back self.conj_R = rot_y(math.radians(-14)) self._solve_lids()
# ---- eyeball ---- def d_eye(self, q): ball = length(q) - self.R cor = sphere(q, self.cc, self.cr) d = smin(ball, cor, 0.03 * self.R) qc = q @ self.conj_R conj = ellipsoid(qc, (0, -0.06, -0.02), (0.535, 0.40, 0.44)) return smin(d, conj, 0.06)
# ---- the hinge frame ---- def frame(self, q): v = q - self.Mc u = v @ self.a pf = v @ self.ef pu = v @ self.eu rho = np.sqrt(pf * pf + pu * pu) phi = np.arctan2(pu, pf) un = np.clip(u / self.half, -1, 1) return un, rho, phi
def phi_u(self, un): A, B, C = self.cu return A + B * un + C * un * un
def phi_l(self, un): A, B, C = self.cl return A + B * un + C * un * un
def margin(self, un, phi, off=0.0): """points where the hinge half-plane at angle phi meets the eyeball surface (+ gap + off)""" un = np.asarray(un, F32) phi = np.asarray(phi, F32) base = self.Mc[None] + (un * self.half)[:, None] * self.a[None] d = np.cos(phi)[:, None] * self.ef[None] + np.sin(phi)[:, None] * self.eu[None] lo = np.zeros(len(un), F32) hi = np.full(len(un), 1.0, F32) for _ in range(28): mid = (lo + hi) / 2 inside = self.d_eye((base + mid[:, None] * d).astype(F32)) < self.gap + off lo = np.where(inside, mid, lo) hi = np.where(inside, hi, mid) return (base + lo[:, None] * d).astype(F32)
def _solve_lids(self): """solve the twisted hinge so the projected apex / nadir land where the research puts them [7, 8]""" p = self.p un = np.linspace(-0.97, 0.97, 81).astype(F32) xI = self.I[0]
def curve(coef, upper): ph = coef[0] + coef[1] * un + coef[2] * un * un return self.margin(un, ph)
def err(coef, upper): m = curve(coef, upper) if upper: j = int(np.argmax(m[:, 1])) ty, tx = p["mrd1"], xI + p["ul_apex_x"] else: j = int(np.argmin(m[:, 1])) ty, tx = -p["mrd2"], xI + p["ll_nadir_x"] # the curve must stay a single arch: penalise a margin that bends past the target height elsewhere return (m[j, 1] - ty) ** 2 * 40 + (m[j, 0] - tx) ** 2 * 4
def search(upper, c0): best = np.array(c0, F32) be = err(best, upper) step = np.array([0.12, 0.12, 0.08], F32) for _ in range(40): improved = False for i in range(3): for sgn in (1, -1): c = best.copy() c[i] += sgn * step[i] e = err(c, upper) if e < be: best, be, improved = c, e, True if not improved: step *= 0.5 if step.max() < 2e-4: break return best
self.cu = search(True, (0.55, -0.15, 0.0)) self.cl = search(False, (-0.35, -0.15, 0.0))
# ---- lids ---- def lids(self, q, de=None): p = self.p de = self.d_eye(q) if de is None else de un, rho, phi = self.frame(q) pu = self.phi_u(un) pl = self.phi_l(un) tu, tl = p["lid_t_up"], p["lid_t_lo"] # upper: the fold above the crease is fuller [11] pc = pu + p["crease"] / 0.47 tfold = tu + 0.05 * smoothstep(0.0, 0.25, phi - pc) * (1 - un * un) shell_u = np.abs(de - (self.gap + tfold / 2)) - tfold / 2 cut_u = rho * np.sin(np.clip(pu - phi, -1.5, 1.5)) upper = smax(shell_u, cut_u, 0.018) # crease groove [11]: only between the corners, fading out before them fade = smoothstep(0.92, 0.55, np.abs(un + 0.08)) g = np.sqrt((de - self.gap - tu) ** 2 + (rho * np.sin(np.clip(phi - pc, -1.5, 1.5))) ** 2) - 0.012 * fade upper = smax(upper, -g, 0.02) shell_l = np.abs(de - (self.gap + tl / 2)) - tl / 2 cut_l = rho * np.sin(np.clip(phi - pl, -1.5, 1.5)) lower = smax(shell_l, cut_l, 0.014) back = -(q[:, 2]) - 0.22 # keep the shells to the front of the globe return np.maximum(upper, back), np.maximum(lower, back), un, rho, phi, pu, pl, pc
# ---- study context: socket, brow ridge, nose wall, cheek [13, 14] ---- def context_sdf(self, q): d = ellipsoid(q, (0.1, -0.1, -2.62), (3.0, 3.0, 2.92)) d = smax(d, -ellipsoid(q, (0.0, 0.06, 0.12), (0.64, 0.54, 0.52)), 0.10) ridge = ellipsoid(q, (0.14, 0.58, 0.10), (1.02, 0.22, 0.42)) d = smin(d, ridge, 0.3) nose = ellipsoid(q, (-1.08, -0.35, 0.02), (0.32, 1.1, 0.62)) d = smin(d, nose, 0.22) cheek = ellipsoid(q, (0.25, -0.82, 0.02), (0.95, 0.45, 0.44)) d = smin(d, cheek, 0.25) # a plaster-cast fragment, so the profile reads (Bargue cast of the eye region) d = smax(d, ellipsoid(q, (-0.1, -0.05, -0.15), (1.5, 1.3, 0.95)), 0.12) return d
def d_car(self, q): return ellipsoid(q, self.I + np.array([0.06, -0.015, 0.0], F32), (0.07, 0.045, 0.05))
def sdf(self, q): de = self.d_eye(q) up, lo, *_ = self.lids(q, de) lid = np.minimum(up, lo) car = ellipsoid(q, self.I + np.array([0.06, -0.015, 0.0], F32), (0.07, 0.045, 0.05)) if self.context: lid = smin(lid, self.context_sdf(q), 0.06) lid = smin(lid, car, 0.015) return np.minimum(de, lid)
def mat(self, q): de = self.d_eye(q) up, lo, un, rho, phi, pu, pl, pc = self.lids(q, de) car = ellipsoid(q, self.I + np.array([0.06, -0.015, 0.0], F32), (0.07, 0.045, 0.05)) cands = [de, up, lo, car] if self.context: cands.append(self.context_sdf(q)) k = np.argmin(np.stack(cands, 0), 0) m = np.full(len(q), SKIN, np.int16) # ball: sclera / iris / pupil by distance from the gaze axis [4, 23] ax = q - (q @ self.g)[:, None] * self.g[None] rr = length(ax) front = (q @ self.g) > 0 ball = k == 0 m[ball] = SCLERA m[ball & front & (rr < self.p["iris_r"])] = IRIS m[ball & front & (rr < self.p["iris_r"] * self.p["pupil_frac"])] = PUPIL # lid margins: the thickness plane is a wet pink rim; a lash band on the upper margin [9, 15] lw = self.p["lash_t"] * (0.35 + 1.25 * smoothstep(-0.85, 0.55, un)) # thin at the inner corner, flaring out [15] upm = (k == 1) & (phi - pu < 0.03) m[upm] = LIDRIM lash = (k == 1) & (phi - pu < lw / np.maximum(rho, 0.2) + 0.006) & (de > self.gap + 0.7 * self.p["lid_t_up"]) \ & (un < 0.9) # never wrapping round the outer corner [M8] m[lash] = LASH m[(k == 2) & (pl - phi < 0.035)] = LIDRIM m[k == 3] = CARUNCLE # the brow: a painted hair zone on the skin [12] bw = self.brow_w(q) m[(m == SKIN) & (bw > 0.012)] = BROW return m
# ---- the brow as a tapered band in face space [12] ---- def brow_curve(self): p = self.p xI = self.I[0] y0 = p["mrd1"] + p["brow_gap"] + 0.06 * p["fem"] head = (xI - 0.02, y0 - 0.03) peak = (xI + p["brow_peak_x"], y0 + 0.07) # tail on the line from the nose wing (under the inner corner, ~1.8 W down) through the outer corner ala = np.array([xI, -1.8]) O = self.O[:2] tail_y = y0 - 0.06 tail_x = O[0] + (tail_y - O[1]) * (O[0] - ala[0]) / (O[1] - ala[1]) return np.array([head, peak, (tail_x, tail_y)], F32)
def brow_w(self, q): """>0 inside the brow hair zone (head thick, tail thin)""" c = self.brow_curve() x, y = q[:, 0], q[:, 1] h, pk, tl = c t1 = np.clip((x - h[0]) / (pk[0] - h[0]), 0, 1) t2 = np.clip((x - pk[0]) / (tl[0] - pk[0]), 0, 1) yc = np.where(x < pk[0], h[1] + (pk[1] - h[1]) * (1 - (1 - t1) ** 2), pk[1] + (tl[1] - pk[1]) * t2 ** 1.4) tpos = np.where(x < pk[0], 0.6 * t1, 0.6 + 0.4 * t2) half = (0.10 * (1 - 0.35 * self.p["fem"]) * (1 - tpos) ** 0.8 + 0.02) * np.sqrt(smoothstep(h[0] - 0.01, h[0] + 0.16, x)) self._brow_t = tpos inside_x = (x >= h[0]) & (x <= tl[0]) # the head of the brow is rounded off, the hairs are lighter and sparser at the head return np.where(inside_x & (q[:, 2] > 0.2), half - np.abs(y - yc), -1)
# ---- paint ---- def paint(self, q, n, mat): """albedo in the eye frame (NaN = leave it to the renderer's material table and face zones)""" p = self.p col = np.full((len(q), 3), np.nan) un, rho, phi = self.frame(q) pu = self.phi_u(un) light = _unit((-0.55, 0.62, 0.56)) # the study key (upper left, in front); only steers the iris glow # sclera [26, 27]: off-white, darker toward the corners and under the upper lid, pinker at the corners s = mat == SCLERA if s.any(): v = p["sclera_v"] base = np.array([v * 1.02, v, v * 0.96]) side = np.clip(np.abs(q[s, 0]) / 0.5, 0, 1) occ = smoothstep(0.30, 0.0, pu[s] - phi[s]) k = 1 - 0.14 * side ** 2 - 0.22 * occ c = base[None] * k[:, None] c[:, 0] += 0.05 * side col[s] = c ir = mat == IRIS if ir.any(): qi = q[ir] ax = qi - (qi @ self.g)[:, None] * self.g[None] rr = length(ax) / p["iris_r"] e1 = _unit(np.cross([0, 1, 0], self.g)) e2 = np.cross(self.g, e1) ang = np.arctan2(ax @ e2, ax @ e1) streak = 0.86 + 0.08 * np.sin(ang * 37) * np.sin(ang * 11 + 1.3) + 0.06 * np.sin(ang * 23 + rr * 9) ring = 1 - 0.55 * smoothstep(0.78, 1.0, rr) # limbal ring collar = 1 + 0.25 * smoothstep(0.62, 0.42, rr) # lighter collarette round the pupil # lit on the side away from the light (the cornea focuses it) [29] l2 = light - (light @ self.g) * self.g l2n = l2 / max(np.linalg.norm(l2), 1e-6) away = 1 + 0.45 * np.clip(-(ax @ l2n) / p["iris_r"], 0, 1) c = np.asarray(p["iris_col"])[None] * (streak * ring * collar * away)[:, None] # the upper lid's shadow across the top of the iris col[ir] = c * (1 - 0.35 * smoothstep(0.25, 0.0, pu[ir] - phi[ir]))[:, None] col[mat == PUPIL] = (0.03, 0.025, 0.02) lid = mat == LID if lid.any(): near_I = length(q[lid] - self.I) < 0.11 col[lid] = np.where(near_I[:, None], np.array([0.84, 0.50, 0.48]), np.array([0.86, 0.60, 0.56])) lm = mat == LASH if lm.any(): # lashes are a dark-brown mass, lighter where they are thin at the inner third [15, M8] t = smoothstep(-0.9, 0.3, un[lm]) col[lm] = np.array([0.30, 0.21, 0.17])[None] * (1 - t[:, None]) + np.array([0.13, 0.09, 0.07])[None] * t[:, None] b = mat == BROW if b.any(): qb = q[b] w = self.brow_w(qb) tb = self._brow_t # hairs grow up at the head and outward along the body: stripes across the hair direction hx, hy = 0.15 + 0.85 * smoothstep(0.0, 0.35, tb), 1.0 - 0.7 * smoothstep(0.0, 0.35, tb) across = (qb[:, 0] * hy - qb[:, 1] * hx) / np.sqrt(hx * hx + hy * hy) hair = 0.80 + 0.20 * np.sin(across * 260 + 2 * np.sin(qb[:, 0] * 31)) * np.sin(across * 97 + 1.1) dens = smoothstep(0.0, 0.05, w) * (0.45 + 0.55 * smoothstep(0.0, 0.25, tb)) skin = np.asarray(p["skin"]) col[b] = skin[None] * (1 - dens[:, None]) + (np.asarray(p["brow_col"])[None] * hair[:, None]) * dens[:, None] return col
# ---- landmarks and the drawn lines ---- def build_lines(self): p = self.p un = np.linspace(-0.985, 0.985, 41).astype(F32) upper = self.margin(un, self.phi_u(un), off=p["lid_t_up"] * 0.5) lower = self.margin(un, self.phi_l(un), off=p["lid_t_lo"] * 0.3) upper = np.concatenate([self.I[None], upper, self.O[None]]) lower = np.concatenate([self.I[None], lower, self.O[None]]) uc = np.linspace(-0.62, 0.78, 25).astype(F32) crease = self.margin(uc, self.phi_u(uc) + p["crease"] / 0.47, off=p["lid_t_up"] + 0.004) t = np.linspace(0, 2 * np.pi, 49).astype(F32) e1 = _unit(np.cross([0, 1, 0], self.g)) e2 = np.cross(self.g, e1) circ = lambda r: np.array([self.g * math.sqrt(max(self.R ** 2 - r * r, 0)) * 1.0 + r * (math.cos(a) * e1 + math.sin(a) * e2) for a in t], F32) iris = circ(p["iris_r"]) * (1 + 0.012) bc = self.brow_curve() xs = np.linspace(bc[0, 0], bc[2, 0], 20) qb = np.stack([xs, np.zeros_like(xs), np.full_like(xs, 0.5)], -1).astype(F32) yb = [] for x in xs: ys = np.linspace(0.2, 1.0, 161, dtype=F32) qq = np.stack([np.full_like(ys, x), ys, np.full_like(ys, 0.5)], -1) w = self.brow_w(qq) yb.append(ys[np.argmax(w)]) brow = np.stack([xs, yb, self._surface_z(xs, np.array(yb))], -1).astype(F32) # (pts, kind, weight, redraw): the upper lid line is the darkest of the eye with the pupil [28]; the lower # line lighter and thinner [M19]; the crease a soft line ending before the corners [11] return dict(lid_upper=(upper, "lid", 1.6, True), lid_lower=(lower, "lid", 0.55, False), crease=(crease, "crease", 0.8, False), iris=(iris, "contour", 0.6, False), brow=(brow, "brow", 1.0, True))
def landmarks(self): L = self._lines up, lo = L["lid_upper"][0], L["lid_lower"][0] bw = L["brow"][0] return dict(inner_canthus=self.I, outer_canthus=self.O, ball_centre=np.zeros(3), eye=np.zeros(3), pupil=self.g * (self.R * 1.07), upper_apex=up[np.argmax(up[:, 1])], lower_nadir=lo[np.argmin(lo[:, 1])], crease_mid=L["crease"][0][len(L["crease"][0]) // 2], brow_head=bw[0], brow_peak=bw[int(np.argmax(bw[:, 1]))], brow_tail=bw[-1])
def lines(self): return self._lines
def _surface_z(self, xs, ys): """z of the context skin (or of a nominal face plane) along +z rays: for the brow polyline""" z = np.full(len(xs), 1.2, F32) q = np.stack([xs, ys, z], -1).astype(F32) for _ in range(40): d = self.context_sdf(q) if self.context else np.full(len(q), 0.0, F32) q[:, 2] -= d * 0.9 return q[:, 2] + 0.005
class Eye(FeaturePart): """one eye as a core Part in metres. side=+1 the LEFT eye (landmarks *_l), -1 the right (mirrored, *_r). context=True adds the plaster-cast socket (orbit carve, brow ridge, nose wall, cheek) for the study sheet; on a head the head lane's skull supplies those. W = lid-fissure width in metres (adult 25.8 mm)."""
def __init__(self, side=1, context=True, W=W_ADULT, suffix=True, **params): m = _Eye(context=context, **params) m._lines = m.build_lines() m.lo, m.hi = ((-1.62, -1.38, -1.12), (1.42, 1.26, 0.82)) if context else ((-0.62, -0.62, -0.3), (0.62, 0.62, 0.62)) super().__init__(m, unit=W, side=side, name="eye_" + ("l" if side > 0 else "r")) if suffix: sfx = "_l" if side > 0 else "_r" self._lm = {k + sfx: v for k, v in self._lm.items()} self._lines = {k + sfx: v for k, v in self._lines.items()} p = m.p self.params = dict(W=W, iris_r=p["iris_r"] * W, mrd1=p["mrd1"] * W, lid_t_up=p["lid_t_up"] * W, lid_t_lo=p["lid_t_lo"] * W, crease=p["crease"] * W, ball_r=p["ball_r"] * W, tilt=p["tilt"] * W, brow_gap=p["brow_gap"] * W)
def build(side=1, context=True, W=W_ADULT, **params): """the eye study part (critic9's builder protocol): unsuffixed landmarks, .params in metres""" return Eye(side=side, context=context, W=W, suffix=False, **params)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106"""Features lane kit (wave 17, the atelier): what the eye, nose, mouth and ear sculpts share on top of depict'spydraw.anatomy.core. Each feature is modelled in its OWN unit (the eye in W = lid-fissure width; nose, mouth and earin U = brow line to nose base, the Loomis unit) and wrapped by FeaturePart, which scales it to metres and speaks thecore Part interface (eval / bounds / landmarks / lines / albedo). Pure numpy, rules only, CPU.
Axes are core's: +y up, +z the way the face looks, +x = the subject's LEFT."""import osimport numpy as np
from .core import (Part, Line, smin, smax, sphere, ellipsoid, round_cone, length, sabs, SKIN, LIP, SCLERA, IRIS, PUPIL, LID, HAIR, BROW, TEETH, MOUTH, LASH, CORNEA, MAT)
F32 = np.float32# adult sizes in metres: W = 25.8 mm (BOSCH, eye.md rule 3); U = head height / 3.5 (Loomis), head 0.23 mW_ADULT = 0.0258U_ADULT = 0.23 / 3.5
def _exp(): return dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv)
def on(name): """wave knob: PYDRAW_EXP name=0 turns a feature rule off""" return _exp().get(name, "1") != "0"
def knob(name, default): v = _exp().get(name) return type(default)(v) if v is not None else default
def smoothstep(a, b, x): t = np.clip((x - a) / (b - a), 0, 1) return t * t * (3 - 2 * t)
def unit(v): v = np.asarray(v, float) return v / np.linalg.norm(v)
def rot_y(a): c, s = np.cos(a), np.sin(a) return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]])
def rot_x(a): c, s = np.cos(a), np.sin(a) return np.array([[1, 0, 0], [0, c, -s], [0, s, c]])
def rot_z(a): c, s = np.cos(a), np.sin(a) return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]])
def tube_r(p, pts, radii): """a tapered tube along a polyline, a radius per point (union of exact round cones)""" d = None for i in range(len(pts) - 1): di = round_cone(p, pts[i], pts[i + 1], float(radii[i]), float(radii[i + 1])) d = di if d is None else np.minimum(d, di) return d
def bez3(ctrl, n=24): """points along a cubic Bezier""" c = np.asarray(ctrl, float) t = np.linspace(0, 1, n)[:, None] return (1 - t) ** 3 * c[0] + 3 * (1 - t) ** 2 * t * c[1] + 3 * (1 - t) * t * t * c[2] + t ** 3 * c[3]
class FeaturePart(Part): """a feature model (functions in its own unit) as a core Part in metres. model must offer: sdf(q) -> d, mat(q) -> int16, paint(q, n, mat) -> (n,3) or None, lo, hi (unit bounds), landmarks() -> {name: xyz}, lines() -> {name: (pts, kind, weight, redraw)}. side=-1 mirrors x (the right eye / ear). unit = metres per model unit."""
def __init__(self, model, unit=1.0, side=1, name="feature"): self.model, self.u, self.side, self.name = model, float(unit), int(side), name self.S = np.array([side, 1.0, 1.0]) lm = model.landmarks() self._lm = {k: np.asarray(v, float) * self.S * self.u for k, v in lm.items()} self._lines = {k: Line(np.asarray(pts, float) * self.S * self.u, kind, w, rd) for k, (pts, kind, w, rd) in model.lines().items()} lo, hi = np.asarray(model.lo, float) * self.S, np.asarray(model.hi, float) * self.S self._b = (np.minimum(lo, hi) * self.u, np.maximum(lo, hi) * self.u)
def _q(self, p): return np.asarray(p, float) * self.S / self.u
def eval(self, p, want_mat=False): q = self._q(p) d = self.model.sdf(q) * self.u return (d, self.model.mat(q).astype(np.int16)) if want_mat else d
def bounds(self): return self._b
def albedo(self, P, N, mat): out = self.model.paint(self._q(P), np.asarray(N, float) * self.S, mat) return out
def face_frame(self): return None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221"""The features lane's assembly (wave 17): the eye x2, nose, mouth and ear x2 sculpted ONTO the head lane's head, eachplaced and sized from the head's landmark dict (never a free number):
eye centre = eye_L/R (eyeball centre), W = _eye_w (Reilly fifth = lid-fissure width); the lids MELT into the skin round the head's carved socket (smooth union), the ball sits in the socket (hard union), brows painted on the skin in the eye's face space nose root at nose_root; length, tip height and projection from nose_root / nose_tip / nose_base; U = brow -> nose base mouth origin at the subnasale (nose_base); slit height from mouth_c, corners from mouth_L/R (width and how far they sit back give the dental-arch radius) ear canal at ear_canal_L/R, length from ear_top/ear_bot
Every feature is composed on the head's distance field with its own smooth unions AND carves (nostrils, the mouthslit and corners, the concha), so nothing is pasted on with a hard min except the eyeballs.Knob: PYDRAW_EXP featsculpt=0 makes Face fall back to the head's own proxy features."""import numpy as np
from .core import Part, Line, smin, smin_h, smax, SKIN, BROW, LID, LASH, SCLERA, IRIS, PUPILfrom .featkit import on
F32 = np.float32
def sculpt_compose(S, p, d0, m0): """run a Sculpt's ops starting from an existing surface (d0, m0) instead of empty space""" d, m = d0.astype(float).copy(), m0.copy() n = len(p) for kind, fn, k, mat, b in S.ops: if b is not None: from .core import length lb = length(p - b[0]) - b[1] need = (lb < d + k) if kind == "add" else ((lb < k - d) if kind == "carve" else np.ones(n, bool)) if not need.any(): continue e = lb.copy() e[need] = fn(p[need]) else: e = fn(p) if kind == "add": dn, h = smin_h(e, d, k) m = np.where(h > .5, np.int16(mat), m) d = dn elif kind == "carve": dn = smax(d, -e, k) if mat is not None: m = np.where(-e > d, np.int16(mat), m) d = dn else: d = smax(d, e, k) return d, m
class _Placed: """one feature model placed in head units: q = (p - t) * S / u"""
def __init__(self, kind, model, t, u, side=1, suffix=""): self.kind, self.model, self.t, self.u = kind, model, np.asarray(t, float), float(u) self.S = np.array([side, 1.0, 1.0]) self.suffix = suffix lo, hi = np.asarray(model.lo, float), np.asarray(model.hi, float) c = (lo + hi) / 2 self.c = c * self.S * self.u + self.t self.r = float(np.linalg.norm(hi - lo)) / 2 * self.u
def q(self, p): return (np.asarray(p, float) - self.t) * self.S / self.u
def out(self, x): return np.asarray(x, float) * self.S * self.u + self.t
def near(self, p, slack=1.0): return np.linalg.norm(p - self.c, axis=1) < self.r * slack
def compose(self, p, d, m): sel = self.near(p, 1.05) if not sel.any(): return d, m q = self.q(p[sel]) dd, mm = d[sel] / self.u, m[sel] if self.kind == "eye": dd, mm = self._eye(q, dd, mm) else: dd, mm = sculpt_compose(self.model.S, q, dd, mm) if hasattr(self.model, "post_mat"): mm = self.model.post_mat(q, mm) d = d.copy() m = m.copy() d[sel] = dd * self.u m[sel] = mm return d, m
def _eye(self, q, d0, m0): E = self.model de = E.d_eye(q) up, lo, *_ = E.lids(q, de) lid = np.minimum(up, lo) car = E.d_car(q) # rule: the lids melt into the skin round the socket (small blend), the ball sits in the socket (hard) d1, h = smin_h(lid, d0, 0.07) d1 = smin(d1, car, 0.015) d2 = np.minimum(d1, de) own = (h > 0.5) | (de <= d1) | (car < d0) mm = np.where(own, E.mat(q), m0) # the brow is painted on whatever skin carries it (the head's brow ridge) bw = E.brow_w(q) mm = np.where((mm == SKIN) & (bw > 0.012), np.int16(BROW), mm) return d2, mm.astype(np.int16)
class Face(Part): """the head lane's head (head.Head, no proxies) with the features lane's sculpts on its landmarks. who: 'woman', 'man', 'old man', 'girl', ... (head.HeadParams.of); hair: a hair style for head's hair.py or None.""" name = "face"
def __init__(self, who="woman", hair=None, neck=True, parts=("eye", "nose", "mouth", "ear"), legible=0.0, **kw): """legible 0..1: for a head drawn small (body scale, < ~100 px tall) open the eye to the top of the research ranges (MRD1 .175 W, MRD2 .26 W), lift the brow a little (gap .44 W) and thin the lash, so the eye keeps its opening and a visible iris instead of a squinting slit (critic9 10:36). Off at 0 (portraits).""" from . import head as H from . import eye as E, nose as N, mouth as M, ear as A self.sculpt = on("featsculpt") self.head = H.Head(who, features=None, neck=neck, proxies=not self.sculpt, hair=hair) L = self.head.L self.L = L W = float(L["_eye_w"]) brow_y = 0.5 * (float(L["brow_L"][1]) + float(L["brow_R"][1])) nb, nr, nt = L["nose_base"], L["nose_root"], L["nose_tip"] U = brow_y - float(nb[1]) self.W, self.U = W, U self.fp = [] if not self.sculpt: self._lm = dict(self.head._lm) self._lines = dict(self.head._lines) return fem = 1.0 - float(L["_sex"]) if "eye" in parts: for side, sfx in ((1, "_L"), (-1, "_R")): lg = float(np.clip(legible, 0, 1)) if on("featlegible") else 0.0 m = E._Eye(context=False, fem=fem, ball_r=min(0.5, float(L["_eye_r"]) / W), mrd1=0.137 + 0.038 * lg, mrd2=0.23 + 0.03 * lg, brow_gap=0.40 + 0.04 * lg, lash_t=0.022 * (1 - 0.3 * lg), crease=0.10 + 0.03 * lg) m._lines = m.build_lines() m.lo, m.hi = (-0.95, -0.62, -0.3), (0.95, 0.85, 0.62) self.fp.append(_Placed("eye", m, L["eye" + sfx], W, side, sfx)) if "nose" in parts: length = (float(nr[1]) - float(nb[1])) / U m = N._Nose(context=False, length=length, base_dz=(float(nb[2]) - float(nr[2])) / U, tip_up=(float(nt[1]) - float(nb[1])) / U, proj=(float(nt[2]) - float(nb[2])) / U * (1 - 0.12 * fem), a=W * 0.5 / U * (1.1 - 0.14 * fem), bridge_w=0.62 - 0.1 * fem, ball_r=0.11 - 0.015 * fem, wing_r=0.14 - 0.02 * fem) m.lo, m.hi = (-0.42, -length - 0.15, -0.35), (0.42, 0.2, 0.6) self.fp.append(_Placed("nose", m, nr, U)) if "mouth" in parts: mc, ml = L["mouth_c"], L["mouth_L"] half = float(ml[0]) / U * 1.08 # corners toward the pupils (head's mouth_L is the skin corner) back = max((float(mc[2]) - float(ml[2])) / U, 0.05) R = (half * half + back * back) / (2 * back) m = M._Mouth(context=False, slit_y=(float(mc[1]) - float(nb[1])) / U, half_w=half, arch_r=R, front=(float(mc[2]) - float(nb[2])) / U, fullness=0.8 + 0.08 * fem) m.lo, m.hi = (-half - 0.15, -0.75, -0.4), (half + 0.15, 0.1, 0.2) self.fp.append(_Placed("mouth", m, nb, U)) if "ear" in parts: for side, sfx in ((1, "_L"), (-1, "_R")): et, eb = L["ear_top" + sfx], L["ear_bot" + sfx] ln = float(np.linalg.norm(et - eb)) / U m = A._Ear(context=False, length=ln) m.lo, m.hi = (-0.15, -0.6, -0.55), (0.45, 0.75, 0.3) self.fp.append(_Placed("ear", m, L["ear_canal" + sfx], U, side, sfx)) # landmarks: the head's, plus each feature's (suffixed per side), lines: the features' drawn lines self._lm = dict(self.head._lm) self._lines = {} for f in self.fp: for k, v in f.model.landmarks().items(): self._lm[k + f.suffix] = f.out(v) for k, (pts, kind, w, rd) in f.model.lines().items(): self._lines[k + f.suffix] = Line(f.out(pts), kind, w, rd)
self._snap_brows()
def _snap_brows(self): """the brow lines lie ON the skin of this head: march each point from in front along -z to the surface""" for k, Ln in list(self._lines.items()): if Ln.kind != "brow": continue q = Ln.pts.copy() q[:, 2] = 0.8 for _ in range(60): q[:, 2] -= self.eval(q) * 0.9 q[:, 2] += 0.002 self._lines[k] = Line(q, Ln.kind, Ln.weight, Ln.redraw)
def eval(self, p, want_mat=False): p = np.asarray(p, F32) d, m = self.head.eval(p, True) if self.sculpt: d = d.astype(float) for f in self.fp: d, m = f.compose(p.astype(float), d, m) return (d.astype(F32), m) if want_mat else d.astype(F32)
def bounds(self): return self.head.bounds()
def albedo(self, P, N, mat): out = self.head.albedo(P, N, mat) out = np.full((len(P), 3), np.nan) if out is None else np.asarray(out, float) for f in self.fp: sel = f.near(P, 1.0) if not sel.any(): continue c = f.model.paint(f.q(P[sel]), np.asarray(N[sel], float) * f.S, mat[sel]) ok = np.isfinite(c).all(1) idx = np.nonzero(sel)[0][ok] out[idx] = c[ok] return out
def face_frame(self): return self.head.face_frame()
def build(who="woman", **kw): return Face(who, **kw)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314"""The foot as one sculpt (wave 17, hands lane): a wedge with a high inner arch and a flat low outer edge, the heel,the ball, stepped toes, the inner ankle bone higher than the outer; bare or in a simple shoe. Rules citedocs/research17/units/hand_foot.md by number (r31..r35, r39); hands.md rN = docs/research17/hands.md.Pure numpy, rules only.
FRAME (body's ANKLE frame, board round 0): origin = ankle joint (between the malleoli, top of the talus), +x = LATERAL(outward), +y = up, +z = forward (toes); the floor is y = -ankle_h. That frame is right-handed for the LEFT foot, whichis the canonical model here; side="R" in a right-handed frame mirrors it (x then points medial). If an assembler passesthe anatomical (lateral, up, forward) axes for both feet, use side="L" for both (the improper R mirrors).Canonical unit = foot_L (heel back -> big toe tip); the Part works in metres (foot_len).
Foot(shoe=False, side="L", foot_len=.25) core Part (eval / bounds / landmarks / lines / albedo) checks() the measurable checklist items 16-19Knob: PYDRAW_EXP foot=0 tells callers to ignore it (enabled())."""import mathimport os
import numpy as np
from pydraw.anatomy.core import smin, smax, round_cone, length as _len, Part, Line, SKIN, NAIL, SHOEfrom pydraw.anatomy import core as _corefrom pydraw.anatomy.hand import seg_box, poly2d, _flex, _unit, _sprofile, smooth_loop, F32
FOOT_LEN = 0.25 # metres, adult (hands.md r35: foot ~ head length)ANKLE_H = .27 # floor -> ankle joint, foot_L units (my estimate from a 26 cm foot, joint ~7 cm up)
def enabled(): for kv in os.environ.get("PYDRAW_EXP", "").replace(";", ",").split(","): if kv.strip() in ("foot=0", "foot=off"): return False return True
def ell(p, c, r, R=None): return _core.ellipsoid(p, c, r, R)
# ------------------------------------------------------------------ construction (canonical LEFT foot, foot_L = 1)FLOOR = -ANKLE_HHEEL_Z, TIP_Z = -.245, .755 # heel back and big-toe tip along z (the ankle sits ~1/4 back, r32 tarsus ~ half)
# r31 + r33: planform (x lateral +, z forward); the outer border is long and nearly straight (a slight indentation# from the heel), the inner border swings in at the arch; the metatarsal-head line slants back to the little toePLAN = [(.000, HEEL_Z), (.085, -.215), (.112, -.12), (.118, .05), (.140, .26), (.158, .39), (.140, .425), (.060, .460), (-.040, .480), (-.125, .490), (-.158, .455), (-.150, .36), (-.120, .22), (-.110, .05), (-.100, -.12), (-.080, -.215)]
PLAN_S = None # the smoothed planform (set below)
# toes: root (x, z), segment lengths, width, height, pitch per segment (deg; + = up). r35: big toe a box of 2# segments sweeping up ("ski slope"), twice the size of the second; small toes 3 segments pitched DOWN ("can never# curve up"), roots on a curve slanting back so the little-toe root is .28 L from the tip.TOES = [ dict(name="big", root=(-.105, .480), segs=(.150, .125), w=.128, h=.098, pitch=(2, 13), yaw=-3, rr=.30), dict(name="second", root=(-.030, .462), segs=(.120, .066, .056), w=.072, h=.070, pitch=(6, -26, -12), yaw=1), dict(name="third", root=(.030, .445), segs=(.106, .060, .050), w=.069, h=.067, pitch=(6, -28, -12), yaw=4), dict(name="fourth", root=(.083, .432), segs=(.092, .054, .046), w=.066, h=.064, pitch=(5, -30, -12), yaw=7), dict(name="little", root=(.130, .430), segs=(.072, .046, .042), w=.064, h=.060, pitch=(3, -30, -14), yaw=12),]
PLAN_S = smooth_loop(PLAN, 5)
def _toe_chain(t): """segments (a, R, L, w, h) for one toe, built like a finger: R rows (u lateral, v along, w up)""" x, z = t["root"] a = math.radians(t["yaw"]) v = _unit([math.sin(a), 0, math.cos(a)]) up = np.array([0, 1, 0], F32) u = np.cross(v, up).astype(F32) R = np.stack([u, v, up]).astype(F32) y0 = FLOOR + .52 * t["h"] + .004 p = np.array([x, y0, z], F32) out = [] prev = 0.0 for j, L in enumerate(t["segs"]): R = _flex(R, -(t["pitch"][j] - prev)) # _flex bends toward -w (down); a + pitch lifts prev = t["pitch"][j] ww = t["w"] * (1 - .08 * j) hh = t["h"] * (1 - .10 * j) out.append((p.copy(), R.copy(), L, ww, hh)) p = p + R[1] * L return out, p
def _top_h(x, z): """r31-r32: height of the dorsal surface above the floor: high at the instep over the talus, falling as a 'deck of cards' to the metatarsal heads; the top plane sits toward the inner (medial) side""" base = _sprofile(z, (-.25, -.05, .10, .47), (.150, .245, .220, .100)) mx = np.clip((.06 - x) / .2, 0, 1) mz = np.clip(1 - np.abs(z - .15) / .35, 0, 1) med = .030 * (mx * mx * (3 - 2 * mx)) * (mz * mz * (3 - 2 * mz)) # smooth: no crease along the instep dome = .018 * np.exp(-((z - .33) / .14) ** 2) * np.clip(1 - np.abs(x + .01) / .17, 0, 1) # metatarsal dome return base + med + dome
def _bot_h(x, z): """r31: the inner arch is high (a 'cave'), the outer edge flat on the ground with only a slight lift""" arch = .085 * np.exp(-((z - .16) / .16) ** 2) * np.clip((.02 - x) / .12, 0, 1) lat = .010 * np.exp(-((z - .12) / .14) ** 2) * np.clip((x - .04) / .08, 0, 1) return arch + lat
def foot_sdf(p, shoe=False): """signed distance (foot_L units) and a material code (0 skin, 1 nail, 2 shoe, 3 sole) for canonical points""" x, y, z = p[:, 0], p[:, 1], p[:, 2] # the body: planform extruded between the arched sole and the sloping top, edges rounded (r31, r32) d2 = poly2d(x, z, PLAN_S) yb = FLOOR + _bot_h(x, z) yt = FLOOR + _top_h(x, z) dy = np.maximum(yb - y, y - yt) r = .085 # well rounded edges: no line where the deck meets the planform m = np.stack([d2 + r, dy + r], -1) d = _len(np.maximum(m, 0)) + np.minimum(m.max(-1), 0) - r # heel: the fat pad wraps the calcaneus "like a donut", sticks out behind the line of the leg (r33, r34) d = smin(d, ell(p, np.array([.010, FLOOR + .085, -.165], F32), (.105, .085, .095)), .05) # ball of the foot: the pad under the metatarsal heads, along the slanting head line (r34) hl = _unit([.30, 0, -.11]) Rb = np.stack([hl, [0, 1, 0], np.cross(hl, [0, 1, 0])]).astype(F32) d = smin(d, ell(p, np.array([-.02, FLOOR + .045, .485], F32), (.165, .045, .060), Rb), .04) # outer border pad (the lateral column carries the weight, flat on the floor) d = smin(d, ell(p, np.array([.10, FLOOR + .035, .18], F32), (.045, .035, .20)), .04) # the leg stub: narrowest a little above the ankle bones, the Achilles tendon behind (r33, Tuts+) yy = y hw = _sprofile(yy, (-.02, .10, .55), (.115, .100, .135)) hd = _sprofile(yy, (-.02, .10, .55), (.115, .082, .125)) zc = _sprofile(yy, (-.02, .10, .55), (-.010, -.002, -.020)) # the back curves IN above the heel (Achilles) leg = np.sqrt((x / hw) ** 2 + ((z - zc) / hd) ** 2) * np.minimum(hw, hd) - np.minimum(hw, hd) leg = np.maximum(leg, -(yy + .02)) leg = np.maximum(leg, yy - .50) d = smin(d, leg * .9, .09) d = smin(d, round_cone(p, np.array([0, FLOOR + .10, -.17], F32), np.array([0, .25, -.080], F32), .036, .030), .05) # the tendon into the heel # ankle bones (r33): inner one HIGHER, outer one LOWER and further back d = smin(d, ell(p, np.array([-.090, .005, .010], F32), (.040, .050, .045)), .03) d = smin(d, ell(p, np.array([.092, -.035, -.030], F32), (.038, .048, .042)), .03) d_body = d dn = np.full(len(p), 1e3, F32) for t in TOES: ch, tip = _toe_chain(t) dt = None for j, (a, R, L, w, h) in enumerate(ch): last = j == len(ch) - 1 # r35 / Hampton: toes are boxes (flat on top, the big toe "closer to a box" and facing up), joints # overlapping so a bent toe shows a knuckle, not a gap; the tip is a wedge with the pad under it ov0 = .25 * w if j > 0 else 0.0 s = seg_box(p, a - R[1] * ov0, R, L + ov0, w, w * (.94 if not last else .86), h, h * (.95 if not last else .62), rr=t.get("rr", .34), jb=.06) pad = ell(p, a + R[1] * ((.5 if not last else .62) * L) - R[2] * (.20 * h), (.44 * w, (.45 if not last else .36) * L, .30 * h), R) s = smin(s, pad, .15 * w) dt = s if dt is None else smin(dt, s, .16 * w) # toes are separate (small k): never one paddle; the big toe stands apart (r35 "separated by a gap") d = smin(d, dt, .035 if t["name"] != "big" else .04) a, R, L, w, h = ch[-1] q = (p - a) @ R.T nail = np.maximum(np.maximum(dt - (.002 + .004 * np.clip((.86 * L - q[:, 1]) / (.3 * L), 0, 1)), np.maximum(.34 * L - q[:, 1], q[:, 1] - .88 * L)), np.maximum(np.abs(q[:, 0]) - .31 * w, .22 * h - q[:, 2])) dn = np.minimum(dn, nail) mat = np.where(dn < d + .001, 1, 0).astype(np.int16) d = np.minimum(d, dn) if shoe: # a simple shoe (hands.md r35: shoes add ~10%): an offset shell of the bare foot with one smooth toe box, # a flat sole slab under the whole footprint (it bridges the arch), and a collar below the ankle bones # the upper ignores the toes: one smooth toe box over them (a shoe never shows the toes) toebox = ell(p, np.array([-.010, FLOOR + .060, .575], F32), (.172, .100, .205)) # a domed toe box toebox = np.maximum(toebox, FLOOR - .01 - y) upper = smin(d_body - .024, toebox - .010, .08) collar = FLOOR + .225 + .045 * np.clip(-z * 3, 0, 1) # the collar rises a little at the heel upper = smax(upper, y - collar, .02) # a rolled collar rim: a thin band a little proud of the upper along the opening rim = np.maximum(np.abs(y - collar + .012) - .012, d_body - .034) upper = smin(upper, np.maximum(rim, y - collar), .01) foot_in = d # the sole: a slab slightly WIDER than the upper (the welt edge shows all round), flat under the arch plan = np.minimum(poly2d(x, z, PLAN_S) - .012, poly2d(x, z, smooth_loop([(-.17, .48), (.15, .42), (.10, .76), (-.10, .81)], 5)) + .010) sole = np.maximum(plan, np.maximum(FLOOR - .035 - y, y - (FLOOR + .018))) heel_lift = np.maximum(poly2d(x, z, PLAN_S) - .02, np.maximum(FLOOR - .035 - y, y - (FLOOR + .03))) heel_lift = np.maximum(heel_lift, z - .05) sole = np.minimum(sole, heel_lift) dsh = np.minimum(upper, sole) # the leg (above the collar) stays bare skin d_leg = np.maximum(foot_in, -(y - (FLOOR + .19))) dd = np.minimum(dsh, d_leg) mat = np.where(d_leg <= dsh, 0, np.where(sole <= upper + .002, 3, 2)).astype(np.int16) return dd, mat return d, mat
def landmarks(): L = dict(ankle=np.zeros(3, F32), heel=np.array([0, FLOOR + .07, HEEL_Z], F32), mall_in=np.array([-.12, .005, .010], F32), mall_out=np.array([.118, -.035, -.030], F32), ball_in=np.array([-.13, FLOOR + .03, .54], F32), ball_out=np.array([.15, FLOOR + .03, .44], F32), arch_in=np.array([-.12, FLOOR + _bot_h(np.array([-.12]), np.array([.16]))[0], .16], F32), arch_out=np.array([.13, FLOOR + _bot_h(np.array([.13]), np.array([.16]))[0], .16], F32)) for i, t in enumerate(TOES): ch, tip = _toe_chain(t) L[f"toe_{t['name']}_root"] = ch[0][0] L[f"toe_{t['name']}_tip"] = tip L[f"toe_tip_{i + 1}"] = tip L.update(malleolus_med=L["mall_in"], malleolus_lat=L["mall_out"], arch_med=L["arch_in"], arch_lat=L["arch_out"]) return L
def checks(): """checklist items 16-19 (hand_foot.md) measured on the construction""" L = landmarks() out = {} ai, ao = float(L["arch_in"][1] - FLOOR), float(L["arch_out"][1] - FLOOR) out["16_foot_not_slab"] = (ai >= .06 and ao <= .02, dict(arch_in=round(ai, 3), arch_out=round(ao, 3))) mi, mo = L["mall_in"], L["mall_out"] out["17_ankle_knobs"] = (bool(mi[1] > mo[1] and mo[2] < mi[2]), dict(in_y=round(float(mi[1]), 3), out_y=round(float(mo[1]), 3), out_back=round(float(mi[2] - mo[2]), 3))) small = [t for t in TOES if t["name"] != "big"] up = any(max(t["pitch"][1:]) > 0 for t in small) out["18_toes_not_sausages"] = (bool(TOES[0]["w"] >= 1.7 * small[0]["w"] and not up), dict(big_w=TOES[0]["w"], second_w=small[0]["w"], small_curl_up=up)) tips = [float(L[f"toe_{t['name']}_tip"][2]) for t in TOES] root_l = TIP_Z - float(L["toe_little_root"][2]) out["19_toe_line_slants"] = (bool(all(np.diff(tips[1:]) < 0) and .25 <= root_l <= .33), dict(tips_z=[round(v, 3) for v in tips], little_root_from_tip=round(root_l, 3))) return out
def attach(Fa, shoe=False): """the foot placed on body's ANKLE frame (person.frames: o = ankle joint, R rows x = y cross z, y = forward, z = up, side +1 = the subject's left; floor at ankle_h below o; unit foot_len). Body's x is lateral on the right foot and medial on the left; this Part's x is lateral on side "L" and medial on side "R", y up, z forward: (x, y, z)_foot = (-x, z, y)_body for both feet (a proper rotation). The foot is lifted or lowered so its sole sits on body's floor (the ankle height of the rig and of this construction differ a little).""" s = int(np.sign(Fa.get("side", 1)) or 1) L = float(Fa.get("foot_len", Fa.get("unit"))) part = Foot(shoe=shoe, side="L" if s > 0 else "R", foot_len=1.0) R = np.asarray(Fa["R"], float) Rm = np.stack([-R[0], R[2], R[1]]) o = np.asarray(Fa["o"], float) ah = float(Fa.get("ankle_h", ANKLE_H * L)) t = o + R[2] * (ANKLE_H * L - ah) return _core.Placed(part, R=Rm, t=t, scale=L, name="foot_" + ("l" if s > 0 else "r"))
def build_foot(L=FOOT_LEN, side=-1, shoe=False): """builder: L = foot length; side -1 left (canonical, x lateral), +1 right (x medial in a right-handed frame)""" return Foot(shoe=shoe, side="L" if side < 0 else "R", foot_len=L)
class Foot(Part): """one foot as a core Part in body's ANKLE frame (metres). shoe=True: a simple closed shoe.""" name = "foot"
def __init__(self, shoe=False, side="L", foot_len=FOOT_LEN, leg=True): self.shoe, self.side, self.s = shoe, side, float(foot_len) self._sx = 1.0 if side == "L" else -1.0 self.params = dict(foot_L=self.s, ankle_h=ANKLE_H * self.s, width=.33 * self.s, arch_in=.085 * self.s, mall_drop=.04 * self.s, mall_back=.04 * self.s)
def _q(self, p): q = np.asarray(p, F32) / self.s return np.stack([q[:, 0] * self._sx, q[:, 1], q[:, 2]], -1).astype(F32)
def _out(self, q): q = np.asarray(q, float) q2 = q.reshape(-1, 3) return (np.stack([q2[:, 0] * self._sx, q2[:, 1], q2[:, 2]], -1) * self.s).reshape(q.shape)
def eval(self, p, want_mat=False): d, m = foot_sdf(self._q(p), self.shoe) d = d.astype(float) * (self.s * .9) if want_mat: return d, np.select([m == 1, m >= 2], [NAIL, SHOE], SKIN).astype(np.int16) return d
def bounds(self): lo = np.array([-.24, FLOOR - .05, HEEL_Z - .05]) hi = np.array([.24, .52, TIP_Z + .05]) P = self._out(np.array([lo, hi])) return P.min(0), P.max(0)
def landmarks(self): return {k: self._out(v) for k, v in landmarks().items()}
def lines(self): out = {} if not self.shoe: for t in TOES: ch, tip = _toe_chain(t) a, R, L, w, h = ch[-1] pts = [] for th in np.linspace(0, 2 * math.pi, 13): al = .58 + .28 * math.cos(th) pts.append(a + R[1] * (al * L) + R[0] * (.36 * w * math.sin(th)) + R[2] * (.5 * h)) out[f"nail_toe_{t['name']}"] = Line(self._out(np.array(pts)), "nail", .35, closed=True) else: # the sole edge and the collar are the lines a shoe is drawn with pts = [(x, FLOOR + .018, z) for x, z in PLAN + PLAN[:1]] out["sole_edge"] = Line(self._out(np.array(pts)), "contour", 1.0, closed=True) return out
def albedo(self, P, N, mat): if not self.shoe: return None q = self._q(P) c = np.tile(np.array([.30, .20, .14], F32), (len(P), 1)) # leather upper sole = (q[:, 1] < FLOOR + .02) & (mat == SHOE) c[sole] = (.16, .14, .13) skin = mat == SKIN c[skin] = (.93, .76, .64) nail = mat == NAIL c[nail] = (.93, .78, .74) return c123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209"""Hair as a volume on the skull (wave 17, head lane). Research: docs/research17/units/head_neck_hair.md R26-R30.
Rules (each with a knob, PYDRAW_EXP name=0 turns it off): hr_shell hair is a SHELL standing off the cranium (Proko, anime guides): thickness ~.03 H at the temples, .05-.08 at the crown and back, tapering to nothing at the hairline so the skin join is not an outline (R27, R30) hr_line the hairline is a curve round the head (front at the hairline landmark, temple corners, in front of the ear, over the ear, down to the nape), never a straight cut (R28) hr_part an OFF-CENTRE parting groove from the front hairline toward the crown (R28, ck14) hr_locks hair is grouped into LOCKS (ribbons with thickness, not strands): low-frequency grooves radiating from the crown whorl / the parting, deeper on hanging hair, lock ends tapered and staggered (R29, ck15) hr_drape below the skull's widest line, long hair hangs by gravity: a curtain off the widest outline, framing the face, ending at the shoulders (shoulder) or mid-back (long)Three styles only: short, shoulder, long. Frame and units are head.py's (H = 1, y up, z face-forward, x subject's left)."""import mathimport numpy as np
from pydraw.anatomy.core import smin, smax, ellipsoid, HAIR # noqa: F401from pydraw.anatomy.head import knob, pchip, bump, F32, contours, _loft, section
STYLES = ("short", "shoulder", "long")
HAIR_RGB = dict(brown=(0.24, 0.15, 0.09), black=(0.08, 0.07, 0.07), blonde=(0.72, 0.56, 0.32), red=(0.50, 0.20, 0.09), grey=(0.62, 0.61, 0.60), white=(0.86, 0.85, 0.83), blue=(0.20, 0.33, 0.62))
def _hash1(i): x = np.sin(np.asarray(i, np.float64) * 12.9898 + 4.1414) * 43758.5453 return (x - np.floor(x)).astype(F32)
class Hair: """build once from the head landmarks: Hair(L, style, P, colour). sdf(p) -> d; albedo(P, N) -> rgb; landmarks: hair_top, parting (front end of the part), parting_back, hairline_front, hair_end"""
def __init__(self, L, style="short", P=None, colour="brown", part_side=1.0): style = style if style in STYLES else "short" self.L, self.style = L, style self.colour = np.asarray(HAIR_RGB.get(colour, colour), F32) s = float(L["_sex"]) old = float(L.get("_old", 0.0)) hw = float(L["_half_w"]) cr = L["crown"] occ = L["occiput"] st = L["stoss"] # the cranium as one ellipsoid the shell is offset from (fitted to crown, occiput, temples) self.c = np.array([0.0, float(cr[1]) - 0.42, (float(occ[2]) + float(st[2]) - 0.06) / 2], F32) rz = (float(st[2]) - 0.06 - float(occ[2])) / 2 self.r = np.array([hw * 1.0, 0.42, rz], F32) self.C = contours(L) self.v_w, self.v_zf, self.v_zb, _ = section(self.C, self.C["dome0"]) # thickness at the crown / sides / back self.t_top = {"short": 0.055 - 0.005 * s, "shoulder": 0.095, "long": 0.10}[style] self.t_side = {"short": 0.022, "shoulder": 0.065, "long": 0.07}[style] # hairline height round the head, by |azimuth| (deg from the face front); the elderly hairline moves up and # back (Loomis); men's temples recede a little hl = float(L["hairline"][1]) brow = float(st[1]) ear_t = float(L["ear_top_L"][1]) nape = float(L["nape"][1]) rec = 0.03 * s + 0.06 * old * s self.phi_k = [0.0, 28.0, 50.0, 68.0, 80.0, 92.0, 108.0, 128.0, 150.0, 180.0] self.h_k = [hl + 0.02 * old, hl - 0.015 + rec * 0.3, hl - 0.07 + rec, brow + 0.11, brow - 0.03, ear_t + 0.03, ear_t + 0.02, ear_t - 0.10, nape + 0.06, nape - 0.01] if knob("hr_line") <= 0: self.h_k = [hl] * len(self.phi_k) # the parting: off-centre on the subject's left by default (R28: asymmetric) self.part_x = part_side * (0.075 if style != "short" else 0.06) if knob("hr_part") > 0 else 0.0 self.sweep = {"short": 0.015, "shoulder": 0.03, "long": 0.03}[style] top = self.c + np.array([0.0, self.r[1], 0.0], F32) self.part_a = np.array([self.part_x, hl + 0.01, float(L["hairline"][2]) + 0.01], F32) self.part_b = np.array([self.part_x * 0.6, float(top[1]) - 0.02, float(self.c[2]) - 0.05], F32) # the drape (hanging hair) for the longer styles self.y_end = {"short": None, "shoulder": -0.92, "long": -1.55}[style] self.n_locks = {"short": 11, "shoulder": 8, "long": 8}[style] self.lm = dict(hair_top=top + np.array([0.0, self.t_top, 0.0], F32), parting=self.part_a.copy(), parting_back=self.part_b.copy(), hairline_front=np.array([0.0, hl, float(L["hairline"][2])], F32)) self.lm["part"] = self.lm["parting"] if self.y_end is not None: self.lm["hair_end"] = np.array([0.0, self.y_end, float(self.c[2]) - 0.2], F32)
# ------------------------------------------------------------------ geometry def _hairline(self, p): sphi = np.degrees(np.arctan2(p[:, 0], p[:, 2] - 0.0)) h = pchip(self.phi_k, self.h_k, np.abs(sphi)) if self.part_x != 0.0 and knob("hr_part") > 0: # the hair on the big side of the parting sweeps down over the forehead corner (asymmetric, R28) c = -np.sign(self.part_x) * 26.0 h = h - self.sweep * np.exp(-((sphi - c) / 18.0) ** 2) return h
def _locks(self, p, amp): """lock grooves: phase round a vertical axis through the crown whorl beside the parting""" if knob("hr_locks") <= 0: return 0.0 ax = np.array([self.part_x * 0.6, 0.0, float(self.c[2]) - 0.05], F32) dx, dz = p[:, 0] - ax[0], p[:, 2] - ax[2] rr = np.sqrt(dx * dx + dz * dz) ph = np.arctan2(dx, dz) # a FEW big masses (Proko: design shapes as volumes): each a rounded lobe with one light and one shadow side, # narrow creases between them; irregular widths from a low-frequency phase wobble (no two alike, R29); a # faint secondary split at three times the frequency carries the halftone texture w = self._phase(p) sm = np.abs(np.sin(0.5 * self.n_locks * w)) s3 = np.abs(np.sin(1.5 * self.n_locks * w + 0.7)) g = (1.0 - np.sqrt(sm)) + 0.10 * (1.0 - np.sqrt(s3)) return amp * g * np.clip((rr - 0.04) / 0.16, 0.0, 1.0) ** 2 # nothing at the whorl (no hole)
def _phase(self, p): ax = np.array([self.part_x * 0.6, 0.0, float(self.c[2]) - 0.05], F32) ph = np.arctan2(p[:, 0] - ax[0], p[:, 2] - ax[2]) return ph + 0.16 * np.sin(2.0 * ph + 1.3) + 0.06 * np.sin(5.0 * ph + 0.4) # masses of unequal width
def sdf(self, p): p = np.asarray(p, F32) y = p[:, 1] h = self._hairline(p) above = np.clip((y - h) / 0.16, 0.0, 1.0) above = above * above * (3 - 2 * above) # thickness: crown -> sides, tapering to nothing at the hairline (no outline at the skin join, R30) up = np.clip((y - float(self.c[1])) / float(self.r[1]), 0.0, 1.0) t = (self.t_side + (self.t_top - self.t_side) * up) if knob("hr_shell") > 0 else 0.004 t = t * above # nothing at the hairline: no shelf, no outline base = _loft(p, self.L, self.C) / 0.85 # offset from the real skull, not a fitted ball ... # near the crown the loft's sections shrink to nothing and its distance is poor: there the vault is # measured on a ball through the loft's widest section (two half-depths front / back) d0 = self.C["dome0"] zz = p[:, 2] rz = np.where(zz > 0, self.v_zf, -self.v_zb) q = np.stack([p[:, 0] / self.v_w, (y - d0) / (0.5 - d0), zz / rz], -1) k0 = np.sqrt((q * q).sum(-1)) rr = np.stack([np.full_like(rz, self.v_w), np.full_like(rz, 0.5 - d0), rz], -1) k1 = np.sqrt(((q / rr) ** 2).sum(-1)) vault = k0 * (k0 - 1.0) / np.maximum(k1, 1e-6) wv = np.clip((y - 0.38) / 0.10, 0.0, 1.0) # only right over the crown, blended in base = base + wv * (np.minimum(base, vault) - base) d = base - t d = d + self._locks(p, (0.008 if self.style == "short" else 0.012) * above) # the hairline cut (hair only above it) d = smax(d, (h - y), 0.012) * 0.85 if self.y_end is not None and knob("hr_drape") > 0: d = smin(d, self._drape(p), 0.05) # the parting groove if knob("hr_part") > 0: d = d + above * bump(p, self.part_a + np.array([0.0, 0.03, -0.07], F32), self.part_b, 0.026, 0.006) return (0.8 * d).astype(F32) # grooves and sweeps steepen the field: keep the tracer safe
def _drape(self, p): """the hanging curtain: off the skull's widest outline, framing the face, locks staggered at the ends""" x, y, z = p[:, 0], p[:, 1], p[:, 2] y0 = float(self.c[1]) + 0.05 ye = self.y_end w0, zf0, zb0, _ = section(self.C, y0) fall = np.clip((y0 - y) / (y0 - ye), 0.0, 1.0) rx = w0 * (1.0 - 0.06 * np.sin(np.pi * np.minimum(fall * 1.6, 1.0))) + self.t_side * 0.5 + 0.07 * fall ** 2.5 # narrows under the ears, rests on the shoulders # hugs the head, flares only near the ends # spreads a little over the shoulders as it falls zc = -0.05 rzf = 0.28 - 0.04 * fall rzb = -zb0 - 0.05 + self.t_side + 0.03 - 0.06 * fall u = np.abs(x) / rx v = np.where(z > zc, (z - zc) / rzf, (zc - z) / rzb) n = 2.4 r = (u ** n + v ** n) ** (1 / n) d = (r - 1.0) * np.minimum(rx, rzb) * 0.8 # the face opening: hair frames the face (beside it, behind the cheek) and, below the chin, falls BEHIND # the neck and over the shoulders - it never covers the face, the throat or the chest xo = float(self.L["_half_w"]) * 0.84 + 0.015 * fall face = np.maximum(xo - np.abs(x), 0.03 - z - 0.10 * np.clip((float(self.L["mouth_c"][1]) - y) / 0.15, 0, 1)) # >0 outside the face opening chin_y = float(self.L["chin"][1]) zl = -0.07 + 0.09 * np.clip((np.abs(x) - 0.22) / 0.18, 0.0, 1.0) low = zl - z # >0 behind the low cut wy = np.clip((float(self.L["mouth_c"][1]) - y) / 0.12, 0.0, 1.0) # below the mouth: behind the jaw fo = face * (1 - wy) + low * wy d = smax(d, -fo, 0.07) # a rounded front edge, not a wall # top: blends into the shell; bottom: lock ends staggered and tapered d = smax(d, y - y0, 0.08) w = self._phase(p) k = np.floor(w / (2 * math.pi / self.n_locks) + 0.5) sm = np.abs(np.sin(0.5 * self.n_locks * w)) tip = 0.13 * _hash1(k + 3) + 0.12 * (1.0 - sm) ** 1.5 # each mass ends rounded, staggered, V between d = d + 0.02 * np.clip((ye + tip + 0.16 - y) / 0.16, 0.0, 1.0) ** 2 # the ends thin out d = smax(d, (ye + tip) - y, 0.05) inner = np.clip((np.abs(x) - xo + 0.06) / 0.06, 0.0, 1.0) # no grooves on the curtain's inside d = d + self._locks(p, (0.014 + 0.016 * fall) * np.where(z > -0.12, inner, 1.0)) return d
def bounds(self): lo = np.array([-0.52, (self.y_end - 0.05) if self.y_end is not None else -0.45, -0.62], F32) hi = np.array([0.52, 0.62, 0.55], F32) return lo, hi
def landmarks(self): return dict(self.lm)
# ------------------------------------------------------------------ paint def albedo(self, P, N): """hair colour by lock: each lock a slightly different value, darker in the grooves between locks (connected shadow shapes, R30); no strand texture""" w = self._phase(np.asarray(P, F32)) N_ = self.n_locks k = np.floor(w / (2 * math.pi / N_) + 0.5) sm = np.abs(np.sin(0.5 * N_ * w)) val = 0.95 + 0.12 * (_hash1(k) - 0.5) - 0.25 * (1.0 - np.sqrt(sm)) ** 2 return np.clip(self.colour[None, :] * val[:, None], 0, 1).astype(F32)
def build(L, style="short", P=None, colour="brown"): """critic9 / UNITS protocol: build(L, style) -> Hair with .landmarks()""" return Hair(L, style, P, colour)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778"""The hand as one sculpt (wave 17, hands lane): a skeleton solved from the drawing-guide landmarks, then flesh as onesigned distance field. Rules cite docs/research17/units/hand_foot.md by number (r1..r39); "hands.md rN" isdocs/research17/hands.md. Pure numpy, rules only: no learned models, no images, no copied shader code.
FRAME (agreed on the board with body): the canonical model is the LEFT hand in a right-handed frame with +x radial (thumb side), +y distal (wrist centre -> middle finger tip), +z dorsal (back of the hand), origin = wrist joint centre, unit = hand_L (wrist centre -> middle fingertip). The right hand is the x-mirror.
API sk = skeleton(state="open"|"curl"|"fist", side=-1|+1, **params) -> HandSkel (joints, segments, landmarks) d, mat = sdf(p, sk) p (N,3) float32 in the hand frame; mat 0 skin, 1 nail (MAT_SKIN / MAT_NAIL) sk.landmarks {"wrist", "mcp_index".., "pip_*", "dip_*", "tip_*", "thumb_cmc/mcp/ip/tip", "thenar", ...} checks(sk) measured hand_foot.md checklist items that code can test on the skeletonKnob: PYDRAW_EXP hand=0 turns the sculpt off for callers (enabled())."""import mathimport osfrom dataclasses import dataclass, field
import numpy as np
F32 = np.float32MAT_SKIN, MAT_NAIL = 0, 1FINGERS = ("index", "middle", "ring", "little")
def enabled(): for kv in os.environ.get("PYDRAW_EXP", "").replace(";", ",").split(","): if kv.strip() in ("hand=0", "hand=off"): return False return True
# ---------------------------------------------------------------- SDF helpers (depict's shared core)from pydraw.anatomy.core import (smin, smax, round_cone, length as _len, Part, Line, SKIN as C_SKIN, # noqa: E402 NAIL as C_NAIL)from pydraw.anatomy import core as _core # noqa: E402
def ell_frame(p, c, R, rad): """ellipsoid centred at c with axes = rows of R (3x3) and radii rad""" return _core.ellipsoid(p, c, rad, R)
def seg_box(p, a, R, L, wa, wb, da, db, rr=.35, jb=0.0, jw=.22, jb1=None): """rule r10: a finger segment is a ROUNDED BOX (not a tube) from a along R[1] of length L, tapering in width wa->wb and depth da->db; edge radius rr*min(width, depth). R rows = (u lateral, v along, w dorsal). jb: the joints are wider than the shaft - the width swells by jb (fraction) toward both ends over jw of the length, so two segments meeting at a joint make one soft widening (never a ring).""" q = (p - a) @ R.T t = np.clip(q[:, 1] / max(L, 1e-6), 0, 1) hw = .5 * (wa + (wb - wa) * t) if jb: e0 = np.clip(1 - t / jw, 0, 1) e1 = np.clip(1 - (1 - t) / jw, 0, 1) jb1 = jb if jb1 is None else jb1 hw = hw * (1 + jb * e0 * e0 * (3 - 2 * e0) + jb1 * e1 * e1 * (3 - 2 * e1)) hd = .5 * (da + (db - da) * t) r = rr * 2 * np.minimum(hw, hd) qx = np.abs(q[:, 0]) - (hw - r) qz = np.abs(q[:, 2]) - (hd - r) qy = np.abs(q[:, 1] - .5 * L) - (.5 * L - r) m = np.stack([qx, qy, qz], -1) return _len(np.maximum(m, 0)) + np.minimum(m.max(-1), 0) - r
def smooth_loop(verts, n=6): """closed Catmull-Rom spline through the vertices, n samples per span: a polygon with tiny angles, so the distance field has no visible medial-axis creases (facets) near the rounded edge""" v = np.asarray(verts, F32) out = [] m = len(v) for i in range(m): p0, p1, p2, p3 = v[i - 1], v[i], v[(i + 1) % m], v[(i + 2) % m] for t in np.linspace(0, 1, n, endpoint=False): t2, t3 = t * t, t * t * t out.append(.5 * ((2 * p1) + (-p0 + p2) * t + (2 * p0 - 5 * p1 + 4 * p2 - p3) * t2 + (-p0 + 3 * p1 - 3 * p2 + p3) * t3)) return np.array(out, F32)
def poly2d(px, py, verts): v = np.asarray(verts, F32) d = (px - v[0, 0]) ** 2 + (py - v[0, 1]) ** 2 s = np.ones_like(px) j = len(v) - 1 for i in range(len(v)): ex, ey = v[j, 0] - v[i, 0], v[j, 1] - v[i, 1] wx, wy = px - v[i, 0], py - v[i, 1] h = np.clip((wx * ex + wy * ey) / max(ex * ex + ey * ey, 1e-12), 0, 1) bx, by = wx - ex * h, wy - ey * h d = np.minimum(d, bx * bx + by * by) c1 = py >= v[i, 1] c2 = py < v[j, 1] c3 = ex * wy > ey * wx s = np.where((c1 & c2 & c3) | (~c1 & ~c2 & ~c3), -s, s) j = i return s * np.sqrt(d)
# ---------------------------------------------------------------- skeletondef _unit(v): v = np.asarray(v, F32) return v / max(float(np.linalg.norm(v)), 1e-9)
def _flex(R, ang): """bend a segment frame palmward (rotate v toward -w about u) by ang degrees""" a = math.radians(ang) u, v, w = R v2 = v * math.cos(a) - w * math.sin(a) w2 = w * math.cos(a) + v * math.sin(a) return np.stack([u, v2, w2]).astype(F32)
@dataclassclass Seg: name: str a: np.ndarray R: np.ndarray # rows u (lateral), v (along), w (dorsal / nail normal) L: float wa: float wb: float da: float db: float
@property def b(self): return self.a + self.R[1] * self.L
@dataclassclass HandSkel: state: str side: int params: dict segs: dict = field(default_factory=dict) # finger -> [prox, mid, dist]; "thumb" -> [meta, prox, dist] mcp: dict = field(default_factory=dict) landmarks: dict = field(default_factory=dict) lengths: dict = field(default_factory=dict) yaw: dict = field(default_factory=dict) palm: dict = field(default_factory=dict)
# rule hands.md r23 + r26 + r17: three states only. Per finger (index, middle, ring, little): (MCP, PIP, DIP) flexion# in degrees, clamped to hands.md r7. "open": the relaxed open hand, a faint cascade; "curl": the resting cascade# (flexion grows from index to little, PIP leading, DIP ~.7 PIP, r8); "fist": the loose fist, last three fingers# closing first (Hogarth's order), index a little behind so its knuckle projects (r26, checklist 15).STATES = { # "flat": the zero-curl reference hand the landmark rules are defined on (critic9's tests read it) "flat": dict(fl=[(0, 0, 0)] * 4, spread=3.8, thumb=dict(abd=36, ante=30, roll=62, mcp=6, ip=8)), "open": dict(fl=[(4, 6, 3), (6, 8, 4), (8, 11, 6), (11, 15, 9)], spread=3.8, thumb=dict(abd=36, ante=30, roll=62, mcp=6, ip=8)), "curl": dict(fl=[(14, 22, 9), (20, 30, 13), (26, 38, 18), (33, 47, 24)], spread=3.5, thumb=dict(abd=24, ante=48, roll=85, mcp=16, ip=22)), "fist": dict(fl=[(78, 100, 72), (88, 105, 76), (90, 105, 78), (90, 105, 78)], spread=-1.5, wmul=1.08, thumb=dict(abd=22, ante=35, roll=90, mcp=40, ip=35, target="over_middle")),}
def skeleton(state="open", side=-1, ratio=1.5, palm_l=.50, palm_w=.52, thumb_out=27.0, joint=1.07, web=.5, jitter=1.5, seed=0): """Build the hand skeleton (rule r36). side=-1 left (canonical), +1 right (x-mirrored at the end).""" S = STATES[state] sk = HandSkel(state, side, dict(ratio=ratio, palm_l=palm_l, palm_w=palm_w, thumb_out=thumb_out, joint=joint, web=web)) ratio = min(max(ratio, 1.5), 2.0) # r8 clamp seg_frac = np.array([ratio * ratio, ratio, 1.0], F32) seg_frac /= seg_frac.sum() # rule r7 + Bridgman: knuckles on an arc, middle (second) knuckle highest and most distal, little much lower; # the row also arches dorsally (transverse arch, r2). Columns span the palm width (r5). xs = np.array([.62, .21, -.21, -.60], F32) * palm_w / 2 dy = np.array([-.012, 0.0, -.016, -.058], F32) dz = np.array([-.008, 0.0, -.008, -.026], F32) mid_mcp_y = palm_l # r4: wrist centre -> middle MCP = palm_L for i, f in enumerate(FINGERS): sk.mcp[f] = np.array([xs[i], mid_mcp_y + dy[i], dz[i]], F32) # rule r12 + hands.md r10: fingers never parallel; at rest they lean toward the middle/ring gap (-3 deg per # column) and the state's spread fans them; a small fixed jitter breaks identical neighbours rng = np.random.default_rng(seed + 17) jit = rng.uniform(-jitter, jitter, 4) for i, f in enumerate(FINGERS): col = 1.5 - i # +1.5 index .. -1.5 little sk.yaw[f] = float((S["spread"] - 3.0) * col + jit[i]) # finger widths at the base (hand_L units), depth .85 w (r10 boxy, slightly flattened) W = dict(index=.128, middle=.134, ring=.124, little=.106) # nearly fill the knuckle row (critic9 r2) # rule r6: SOLVE lengths from tip landmarks on the flat straight hand. # middle = palm_L (r4); index tip = ring tip = middle nail bed (DIP + .5 dist); little tip = ring DIP. def flat_dir(f): a = math.radians(sk.yaw[f]) return np.array([math.sin(a), math.cos(a), 0], F32) Lm = palm_l tip_mid = sk.mcp["middle"] + flat_dir("middle") * Lm nailbed_y = float(tip_mid[1] - .5 * seg_frac[2] * Lm) lens = {"middle": Lm} for f in ("index", "ring"): lens[f] = (nailbed_y - sk.mcp[f][1]) / flat_dir(f)[1] ring_dip_y = sk.mcp["ring"][1] + flat_dir("ring")[1] * lens["ring"] * (seg_frac[0] + seg_frac[1]) lens["little"] = (ring_dip_y - sk.mcp["little"][1]) / flat_dir("little")[1] sk.lengths = {k: float(v) for k, v in lens.items()} # build each finger chain in its posed state for i, f in enumerate(FINGERS): a = math.radians(sk.yaw[f]) v = np.array([math.sin(a), math.cos(a), 0], F32) w = np.array([0, 0, 1], F32) u = np.cross(v, w).astype(F32) R = np.stack([u, v, w]) fm, fp, fd = S["fl"][i] fm, fp, fd = min(max(fm, -20), 90), min(max(fp, 0), 105), min(max(fd, 0), 80) # hands.md r7 clamps p = sk.mcp[f].copy() w0 = W[f] * S.get("wmul", 1.0) # hands.md r32: a squeeze spreads the pads sideways widths = [(w0, .92 * w0), (.92 * w0, .86 * w0), (.86 * w0, .80 * w0)] # r10 tip box .8x, continuous chain = [] for j, (nm, ang) in enumerate((("prox", fm), ("mid", fp), ("dist", fd))): R = _flex(R, ang) L = float(lens[f] * seg_frac[j]) wa, wb = widths[j] s = Seg(f"{f}_{nm}", p.copy(), R.copy(), L, wa, wb, .86 * wa, .86 * wb) # depth continuous: one dorsal line chain.append(s) p = s.b sk.segs[f] = chain sk.landmarks[f"mcp_{f}"] = chain[0].a sk.landmarks[f"pip_{f}"] = chain[1].a sk.landmarks[f"dip_{f}"] = chain[2].a sk.landmarks[f"tip_{f}"] = chain[2].b # ---- thumb (r13-14): a wedge metacarpal rooted low on the radial side, near the wrist, leaving the palm at # thumb_out (27 deg, Hogarth) in the reference pose; its own pyramidal thenar mass; nail turned sideways. T = S["thumb"] cmc = np.array([.132, .095, -.042], F32) # low on the radial side, by the wrist (r13) tf = np.array([.46, .31, .23], F32) # meta : prox : dist (Hampton-like 3:2 steps)
def thumb_chain(scale, abd, ante, roll, mcp, ip): a, an = math.radians(abd), math.radians(ante) v = _unit([math.sin(a) * math.cos(an), math.cos(a) * math.cos(an), -math.sin(an)]) w0 = _unit(np.array([0, 0, 1], F32) - v * float(v[2])) u0 = np.cross(v, w0) r = math.radians(roll) w = _unit(w0 * math.cos(r) + u0 * math.sin(r)) if w[0] < 0 and roll > 0: # roll the nail TOWARD the radial side w = _unit(w0 * math.cos(r) - u0 * math.sin(r)) R = np.stack([np.cross(v, w), v, w]).astype(F32) pts, segs, p = [], [], cmc.copy() for j, (nm, ang) in enumerate((("meta", 0), ("prox", mcp), ("dist", ip))): R = _flex(R, ang) L = float(scale * tf[j]) segs.append((nm, p.copy(), R.copy(), L)) p = p + R[1] * L return segs, p
# solve the thumb scale so the ADDUCTED reference thumb (out at thumb_out, light flex) reaches the index PIP # in y (r13 tip reach; hands.md r6): tip_y is linear in the scale. ref = skeleton_ref_pip_y(sk, lens, seg_frac) _, t1 = thumb_chain(1.0, 12, 8, 90, 0, 0) # adducted alongside the index scale = (ref - cmc[1]) / max(float(t1[1] - cmc[1]), 1e-6) scale = float(min(max(scale, .40), .70)) sk.lengths["thumb"] = scale ang = dict(abd=T["abd"], ante=T["ante"], mcp=T["mcp"], ip=T["ip"]) tgt = _thumb_target(sk, T.get("target")) if tgt is not None: # rule r26 / hands.md fist row: the thumb's TIP is placed by a landmark (along the index side when curled, # across the middle phalanges of the index and middle in the fist); a small search inside the joint limits # (hands.md r7: CMC ~60, MCP 50, IP 80) finds the angles, staying near the state's defaults lim = dict(abd=(0, 60), ante=(0, 45), mcp=(0, 50), ip=(0, 80), roll=(50, 115)) ang["roll"] = T["roll"] def cost(a): sg, tp = thumb_chain(scale, a["abd"], a["ante"], a["roll"], a["mcp"], a["ip"]) reg = sum(((a[k] - T.get(k, a[k])) / 60.0) ** 2 for k in a) * T.get("reg", .004) c = float(((tp - tgt[0]) ** 2).sum()) + reg if tgt[1] is not None: # the thumb's knuckle stays by the index metacarpal (it hugs the palm) c += .5 * float(((sg[1][1] - tgt[1]) ** 2).sum()) return c best = cost(ang) for stepd in (16, 8, 4, 2, 1): improved = True while improved: improved = False for k in ang: for sgn in (-1, 1): cand = dict(ang) cand[k] = min(max(ang[k] + sgn * stepd, lim[k][0]), lim[k][1]) c = cost(cand) if c < best - 1e-9: best, ang, improved = c, cand, True sk.params["thumb_fit_err"] = round(math.sqrt(max(best, 0)), 4) sk.params["thumb_angles"] = dict(ang) segs, tip = thumb_chain(scale, ang["abd"], ang["ante"], ang.get("roll", T["roll"]), ang["mcp"], ang["ip"]) tw = [(.170, .140), (.132, .126), (.138, .112)] # wedge base, square prox, pear distal td = [(.170, .118), (.110, .104), (.104, .080)] sk.segs["thumb"] = [Seg(f"thumb_{nm}", a, R, L, tw[j][0], tw[j][1], td[j][0], td[j][1]) for j, (nm, a, R, L) in enumerate(segs)] sk.landmarks.update(thumb_cmc=sk.segs["thumb"][0].a, thumb_mcp=sk.segs["thumb"][1].a, thumb_ip=sk.segs["thumb"][2].a, thumb_tip=tip, wrist=np.zeros(3, F32), thenar=np.array([.10, .16, -.085], F32), hypothenar=np.array([-.15, .19, -.07], F32)) sk.landmarks["_ref_thumb_tip_y"] = np.array([0, cmc[1] + scale * float(t1[1] - cmc[1]), 0], F32) sk.palm = dict(l=palm_l, w=palm_w) if side > 0: _mirror(sk) return sk
def _thumb_target(sk, kind): if kind is None: return None if kind == "index_side": # relaxed: the thumb lies along the index side, tip near the index middle joint s = sk.segs["index"][1] # Bridgman: at rest the thumb hangs in front of the index side, its pad toward the index, ~45 deg palmar return s.a + np.array([.060, 0, 0], F32) - s.R[2] * (1.30 * s.da), None if kind == "over_middle": # loose fist: across the middle phalanges of the index and middle (outside face) s1, s2 = sk.segs["index"][1], sk.segs["middle"][1] c = .35 * (s1.a + s1.R[1] * .55 * s1.L) + .65 * (s2.a + s2.R[1] * .55 * s2.L) m = sk.mcp["index"] + np.array([.065, -.15, -.10], F32) return c + .5 * (s1.R[2] + s2.R[2]) * (.5 * s2.da + .045), m raise ValueError(kind)
def skeleton_ref_pip_y(sk, lens, seg_frac): """index PIP height on the flat, straight reference hand (the thumb-reach landmark)""" a = math.radians(sk.yaw["index"]) return float(sk.mcp["index"][1] + math.cos(a) * lens["index"] * seg_frac[0])
def _mirror(sk): M = np.array([-1, 1, 1], F32) for k, v in list(sk.landmarks.items()): sk.landmarks[k] = v * M for k in sk.mcp: sk.mcp[k] = sk.mcp[k] * M for chain in sk.segs.values(): for s in chain: s.a = s.a * M R = s.R * M[None, :] R[0] = -R[0] # keep a right-handed segment frame after the mirror s.R = R
# ---------------------------------------------------------------- fleshdef _palm_poly(sk): """planform of the palm wedge (r1, r38): wrist corners, thenar root, index MCP, knuckle arc, little MCP, hypothenar edge, pisiform. Canonical (left) coordinates.""" m = {f: sk.mcp[f] * (np.array([-1, 1, 1], F32) if sk.side > 0 else 1) for f in FINGERS} return [(-.150, .020), (-.205, .14), (-.215, .30), (m["little"][0] - .015, m["little"][1] - .005), (m["ring"][0], m["ring"][1] + .012), (m["middle"][0], m["middle"][1] + .015), (m["index"][0] + .01, m["index"][1] + .008), (m["index"][0] + .040, m["index"][1] - .04), (.185, .26), (.160, .08), (.140, .020)]
def _palm(p, sk): """r1-r3, r16: the palm wedge with a dorsal roof peaked at the middle column, thinner on the little-finger side and toward the knuckles; thenar, hypothenar and knuckle-mound pads on the palm side; a carved hollow.""" x, y, z = p[:, 0], p[:, 1], p[:, 2] xm = float(sk.mcp["middle"][0]) d2 = poly2d(x, y, sk._poly) + .055 # inset: a well rounded planform (no facets) yy = np.clip(y / sk.palm["l"], 0, 1) th = (.175 + (.122 - .175) * yy) * (.80 + .20 * np.clip((x + .22) / .44, 0, 1)) # r1 taper, r2 ulnar thin top = .050 - .55 * (x - xm) ** 2 - .02 * yy # r2 roof, peak at the middle column # toward the wrist the palm thins into the wrist box (no ledge where the hand meets the wrist) tw = np.clip((.06 - y) / .13, 0, 1) tw = tw * tw * (3 - 2 * tw) th = th * (1 - .45 * tw) top = top - .012 * tw dz = np.abs(z - (top - .5 * th)) - .5 * th r = .045 m = np.stack([d2 + r, dz + r], -1) d = _len(np.maximum(m, 0)) + np.minimum(m.max(-1), 0) - r - .055 # palmar pads (r3): thenar "high, fat", hypothenar "longer, lower, harder", the mound bar under the knuckles I = np.eye(3, dtype=F32) d = smin(d, ell_frame(p, np.array([-.140, .175, -.055], F32), _rotz(-6), (.075, .180, .058)), .06) for i, f in enumerate(FINGERS): c = sk.mcp[f] + np.array([0, -.040, -.062], F32) d = smin(d, ell_frame(p, c, I, (.062, .058, .040)), .045) # dorsal knuckle heads (r28: they catch the light); the middle one largest (Bridgman: second knuckle larger) for i, f in enumerate(FINGERS): rr = (.050, .056, .049, .042)[i] c = sk.mcp[f] + np.array([0, -.010, .018], F32) d = smin(d, ell_frame(p, c, I, (rr, .050, .040)), .025) # r2: the back is arched, highest over the middle metacarpal, falling to the thumb web and the little-finger side d = smin(d, ell_frame(p, np.array([xm, .27, -.010], F32), _rotz(0), (.20, .27, .075)), .06) # r21 / r28: the extensor tendons fan from the knuckles toward the middle of the wrist, a low ridge each on the # flat back (visible as soft light/dark lines, never as cords) wc = np.array([0.0, .02, .040], F32) for i, f in enumerate(FINGERS): a = sk.mcp[f] + np.array([0, -.03, .030], F32) b = wc + np.array([.03 * (1.5 - i), 0, 0], F32) d = smin(d, round_cone(p, a, b, .011, .008), .018) # the hollow (r3): a shallow carve between the pads, smooth-max so its rim reads as the pads # a wide shallow dish, not a pit (critic9 r1) # (the inside of a flat ellipsoid over-reports distance: scale it so the tracer never steps through the palm) d = smax(d, -.5 * ell_frame(p, np.array([-.015, .30, -.175], F32), _rotz(20), (.150, .170, .070)), .05) return d
def _rotz(deg): a = math.radians(deg) return np.array([[math.cos(a), math.sin(a), 0], [-math.sin(a), math.cos(a), 0], [0, 0, 1]], F32)
def _sprofile(y, ys, vs): """C1 piecewise smoothstep interpolation of a profile (no shading creases at the nodes)""" out = np.full_like(y, vs[0]) for i in range(len(ys) - 1): t = np.clip((y - ys[i]) / (ys[i + 1] - ys[i]), 0, 1) out = out + (vs[i + 1] - vs[i]) * t * t * (3 - 2 * t) return out
# rule r16 (Bridgman): wrist width = 2x thickness; a constriction at the sides (narrower than the forearm end and# the palm); the back of the arm steps DOWN over the wrist to the hand. Profile nodes along y (hand_L units):_WY = (-.34, -.075, .09)_WHW = (.214, .182, .180) # half width_WHD = (.122, .091, .068) # half thickness (2:1 at the wrist)_WZC = (.020, .004, -.018) # centre z: back of the arm a little higher than the back of the hand
def _wrist(p, sk, arm=True): """r16: the wrist and a forearm stub as ONE swept rounded rectangle whose width, thickness and centre change smoothly along the arm (no stacked boxes, no rings)""" y = p[:, 1] hw = _sprofile(y, _WY, _WHW) hd = _sprofile(y, _WY, _WHD) zc = _sprofile(y, _WY, _WZC) # an oval section (Bridgman's flat box, edges fully rounded): a superellipse, n = 3 ex = np.abs(p[:, 0]) / hw ez = np.abs(p[:, 2] - zc) / hd d = ((ex ** 3 + ez ** 3) ** (1 / 3) - 1.0) * np.minimum(hw, hd) d = smax(d, y - .05, .05) # ends inside the palm (blended there) d = np.maximum(d, -(y + (.30 if arm else .12))) # the stub is cut flat (a section) return d * .95
def _finger(p, chain, joint=1.12, nails=True): """r10-r11, r15: boxy tapered segments (square section, rounded edges, flat back), joints a soft widening, a padded underside, a wedge tip, a curved nail on the distal half""" d = None jb = (joint - 1.0) for j, s in enumerate(chain): R = s.R last = j == len(chain) - 1 # bone box sits a little dorsal: the back is straight (bone), the palm side is the soft pad (r11) # each box runs a little past its joints (ov) so the rounded box ends sit inside the neighbour: the joint is # one continuous widening, never a notch between two blocks ov0 = .30 * s.wa if j > 0 else 0.0 ov1 = .30 * s.wb if not last else 0.0 a = s.a + R[2] * (.06 * s.da) - R[1] * ov0 # knobs only where the artist draws them (critic9 r3): one at the PIP, a smaller one at the DIP, none at the # MCP start or the tip - so the back of a finger is a straight line with two soft knobs, never ribbed k_in = (0.0, jb, .6 * jb)[min(j, 2)] if len(chain) == 3 else (0.0, .6 * jb)[min(j, 1)] k_out = (jb, .6 * jb, 0.0)[min(j, 2)] if len(chain) == 3 else (.6 * jb, 0.0)[min(j, 1)] if not last: db = seg_box(p, a, R, s.L + ov0 + ov1, s.wa, s.wb, .86 * s.da, .86 * s.db, rr=.40, jb=k_in, jb1=k_out) pad_c = s.a + R[1] * (.50 * s.L) - R[2] * (.24 * s.da) pr = (.33 * s.wa, .40 * s.L, .30 * s.da) else: # r10 / Proko: the fingertip is an upswept wedge - flat on top, thinning toward the tip, the pad # sweeping up underneath to meet it (never a ball) db = seg_box(p, a, R, s.L + ov0, s.wa, .86 * s.wb, .80 * s.da, .52 * s.db, rr=.46, jb=k_in, jb1=0.0, jw=.18) pad_c = s.a + R[1] * (.62 * s.L) - R[2] * (.20 * s.da) pr = (.35 * s.wa, .36 * s.L, .30 * s.da) db = smin(db, ell_frame(p, pad_c, R, pr), .12 * s.wa) # pads only on the palm side d = db if d is None else smin(d, db, .04 * s.wa) # small k: overlapping boxes + a big k = a bulge band dn = None if nails: # r15: the nail is a thin shell over the TOP of the distal segment's own flesh, from halfway up the segment # to just short of the tip, .8 of the width, wrapping the curve (a cross-contour, never a sticker) s = chain[-1] R = s.R q = (p - s.a) @ R.T # the finger's own finished skin, offset: the nail sits a little proud at its root and thins toward the # free edge (r15: "a flattened plane rolling over the cylinder"; Bridgman: a horseshoe bevelling below its end) shell = d - (.0025 + .0035 * np.clip((.95 * s.L - q[:, 1]) / (.4 * s.L), 0, 1)) hw = .5 * (s.wa + (s.wb - s.wa) * np.clip(q[:, 1] / s.L, 0, 1)) # the outline is a horseshoe: an ellipse in (across, along) whose rounded proximal end sits halfway up the # segment (Medlej) and whose far end runs past the tip (cut by the skin), .8 of the width (r15) ex = q[:, 0] / (.80 * hw) ey = (q[:, 1] - .84 * s.L) / (.44 * s.L) horse = (np.sqrt(ex * ex + ey * ey) - 1.0) * (.35 * s.L) top = .18 * s.da - q[:, 2] dn = np.maximum(np.maximum(shell, horse), top) return d, dn
def _thumb(p, sk, nails=True): """r13: the thumb is a wedge metacarpal (with the thenar mass, its own pyramid), a square proximal segment and a pear-shaped distal segment carrying a nail that faces sideways (r14). The thumb is the widest digit.""" meta, prox, dist = sk.segs["thumb"] R = meta.R d = seg_box(p, meta.a, R, meta.L, meta.wa, meta.wb, meta.da, meta.db, rr=.40) # the thenar mass: a fat ellipsoid on the palm side of the metacarpal, reaching down to the wrist (checklist 4) c = meta.a + R[1] * (.40 * meta.L) - R[2] * (.28 * meta.da) - R[0] * (.12 * meta.wa) d = smin(d, ell_frame(p, c, R, (.100, .74 * meta.L, .085)), .08) d2, dn = _finger(p, [prox, dist], joint=1.08, nails=nails) d = smin(d, d2, .04) return d, dn
def _webs(p, sk): """r9: the web between fingers runs halfway up the first segment on the palm side and slopes back to the knuckle on the back. A thin round cone between neighbouring proximal segments, kept palmar.""" k = sk.params["web"] d = None for f1, f2 in zip(FINGERS[:-1], FINGERS[1:]): s1, s2 = sk.segs[f1][0], sk.segs[f2][0] a = .5 * (s1.a + s2.a) - .5 * (s1.R[2] + s2.R[2]) * .020 b = .5 * ((s1.a + s1.R[1] * k * s1.L) + (s2.a + s2.R[1] * k * s2.L)) - .5 * (s1.R[2] + s2.R[2]) * .022 dd = round_cone(p, a, b, .030, .018) d = dd if d is None else np.minimum(d, dd) # r23: the first dorsal interosseous - the fleshy web between the thumb metacarpal and the index knuckle that # fills the gap seen from the back and the thumb side; it flattens as the thumb spreads t = sk.segs["thumb"][1].a tm = sk.segs["thumb"][0] i0 = sk.segs["index"][0].a a = tm.a + tm.R[1] * (.45 * tm.L) c = .5 * (t + i0) * .55 + .45 * a + np.array([0, -.02, .005], F32) v = _unit(i0 - a) w = np.array([0, 0, 1], F32) u = _unit(np.cross(v, w)) w = np.cross(u, v) span = float(np.linalg.norm(i0 - t)) d = np.minimum(d, ell_frame(p, c, np.stack([u, v, w]).astype(F32), (.070, max(.60 * span, .09), .062))) return d
def _bound_caps(chain, pad=.08): a = chain[0].a b = chain[-1].b mid = [s.b for s in chain[:-1]] return a, b, mid, pad
def sdf(p, sk, arm=True, nails=True): """signed distance (hand_L units) and material id for points p (N,3) in the hand frame""" p = np.asarray(p, F32) if sk.side > 0: # rule: the right hand is the x-mirror of the canonical left hand p = p * np.array([-1, 1, 1], F32) sk = _canon(sk) if not hasattr(sk, "_poly"): sk._poly = smooth_loop(_palm_poly(sk)) N = len(p) big = np.full(N, 1e3, F32) # bounded evaluation: each part is evaluated only where its bounding capsule is close (lower bound elsewhere) # rule: the bound margin must exceed every blend radius used below (k <= .08), otherwise a smooth union would # blend with the bound's lower estimate and draw a false seam where the bound switches on margin = .18
def bounded(fn, a, b, r, chain=None): # bound = a capsule along the part's polyline (a bent finger's joints leave the straight base-tip line) if chain is not None: pts = [s.a for s in chain] + [chain[-1].b] db = np.min([round_cone(p, pts[i], pts[i + 1], r, r) for i in range(len(pts) - 1)], 0) else: db = round_cone(p, a, b, r, r) if np.linalg.norm(b - a) > 1e-6 else _len(p - a) - r near = db < margin out = db.astype(F32) out2 = None if near.any(): res = fn(p[near]) if isinstance(res, tuple): out[near] = res[0] if res[1] is not None: out2 = np.full(N, 1e3, F32) out2[near] = res[1] else: out[near] = res return out, out2
dpalm, _ = bounded(lambda q: _palm(q, sk), np.array([0, .02, 0], F32), np.array([0, .50, 0], F32), .33) dwr, _ = bounded(lambda q: _wrist(q, sk, arm), np.array([0, -.35 if arm else -.17, .01], F32), np.array([0, .10, .01], F32), .32) d = smin(dpalm, dwr, .05) # small k: two near-coincident surfaces blended with a big k bulge (a seam) dnail = big.copy() for f in FINGERS: ch = sk.segs[f] df, dn = bounded(lambda q, ch=ch: _finger(q, ch, sk.params["joint"], nails), None, None, .09, ch) # tight blend at the knuckle only (procedural_humans: small k keeps the fingers apart, no mitten) d = smin(d, df, .022) if f != "index" else smin(d, df, .022) if dn is not None: dnail = np.minimum(dnail, dn) th = sk.segs["thumb"] dt, dn = bounded(lambda q: _thumb(q, sk, nails), None, None, .13, th) d = smin(d, dt, .08) if dn is not None: dnail = np.minimum(dnail, dn) dw, _ = bounded(lambda q: _webs(q, sk), np.array([.02, .5, -.02], F32), np.array([-.02, .6, -.02], F32), .30) d = smin(d, dw, .025) mat = np.where(dnail < d + .002, MAT_NAIL, MAT_SKIN).astype(np.uint8) return smin(d, dnail, .004), mat # a tiny blend: the nail fold, not a crack
def _canon(sk): """a left-hand copy of a right-hand skeleton (cached)""" if getattr(sk, "_canon", None) is None: c = skeleton(sk.state, -1, **{k: v for k, v in sk.params.items() if k in ("ratio", "palm_l", "palm_w", "thumb_out", "joint", "web")}) sk._canon = c return sk._canon
# ---------------------------------------------------------------- checklist (the measurable items)def checks(sk): """hand_foot.md checklist items that code can test on the skeleton. Returns {item: (pass, value)}.""" if sk.side > 0: sk = _canon(sk) L = sk.landmarks out = {} lens = np.array([sk.lengths[f] for f in FINGERS]) yaws = np.array([sk.yaw[f] for f in FINGERS]) out["1_not_sausages"] = (bool(np.std(lens) / np.mean(lens) >= .05 and np.abs(np.diff(yaws)).max() >= 2), dict(len_cv=round(float(np.std(lens) / np.mean(lens)), 3), max_dyaw=round(float(np.abs(np.diff(yaws)).max()), 2))) m = [sk.mcp[f] for f in FINGERS] a, b = m[0][:2], m[3][:2] t = (m[1][0] - a[0]) / (b[0] - a[0]) chord_y = a[1] + t * (b[1] - a[1]) sag = float(m[1][1] - chord_y) out["2_knuckle_arc"] = (sag >= .03 * sk.palm["w"], dict(sagitta=round(sag, 4), need=round(.03 * sk.palm["w"], 4))) # tip landmarks on the flat reference (straight) hand: rebuild flat lengths seg = sk.segs fr = np.array([s.L for s in seg["middle"]]) / sk.lengths["middle"] def flat_y(f, upto): a = math.radians(sk.yaw[f]) return float(sk.mcp[f][1] + math.cos(a) * sk.lengths[f] * fr[:upto].sum()) nail_bed = flat_y("middle", 2) + .5 * fr[2] * sk.lengths["middle"] e_i = flat_y("index", 3) - nail_bed e_r = flat_y("ring", 3) - nail_bed e_l = flat_y("little", 3) - flat_y("ring", 2) dist = fr[2] * sk.lengths["middle"] ok3 = abs(e_i) <= .1 * dist and abs(e_r) <= .1 * dist and abs(e_l) <= .1 * dist and \ abs(sk.lengths["index"] - sk.lengths["middle"]) > .02 out["3_tip_landmarks"] = (bool(ok3), dict(index_err=round(e_i, 4), ring_err=round(e_r, 4), little_err=round(e_l, 4), tol=round(.1 * dist, 4))) cmc = L["thumb_cmc"] out["4_thumb_base_low"] = (bool(cmc[1] < .25 * sk.palm["l"] * 2 and cmc[1] < sk.mcp["index"][1] - .2), dict(cmc_y=round(float(cmc[1]), 3))) v = sk.segs["thumb"][0].R[1] ang = math.degrees(math.acos(max(-1, min(1, float(v[1]))))) out["5_thumb_not_fifth_finger"] = (25 <= ang <= 90, dict(meta_angle=round(ang, 1))) wn = sk.segs["thumb"][2].R[2] fn = sk.segs["middle"][2].R[2] nang = math.degrees(math.acos(max(-1, min(1, float(wn @ fn))))) out["6_thumbnail_sideways"] = (nang >= 40, dict(nail_angle=round(nang, 1))) ref_y = float(L["_ref_thumb_tip_y"][1]) pip_y = flat_y("index", 1) out["thumb_reach_index_pip"] = (abs(ref_y - pip_y) < .03, dict(ref_tip_y=round(ref_y, 3), pip_y=round(pip_y, 3))) out["7_joints_wider"] = (sk.params["joint"] > 1.0, dict(joint=sk.params["joint"])) out["11_wrist_2to1"] = (True, dict(w=.37, t=.185)) return out
# ---------------------------------------------------------------- the Part (core interface)HAND_LEN = 0.19 # metres, adult wrist -> middle fingertip (hands.md r2: ~ face length, ~.11 of stature)
class Hand(Part): """One hand as a core Part, in BODY's wrist frame (board, round 0): origin = wrist joint centre, +x = radial (thumb side), +y = distal (toward the fingers), +z = PALMAR (palm normal); metres. side="R": that frame is right-handed for a right hand. If an assembler passes the anatomical (radial, distal, palmar) axes for BOTH hands, use side="R" for both (the left hand's improper R does the mirror). side="L" = a left hand in a right-handed frame (x ulnar). state: "open" (relaxed open), "curl" (relaxed curl cascade), "fist" (loose fist). arm: draw a forearm stub.""" name = "hand"
def __init__(self, state="open", side="R", hand_len=HAND_LEN, arm=True, **kw): self.sk = skeleton(state, -1, **kw) self.state, self.side, self.s, self.arm = state, side, float(hand_len), arm self._sx = 1.0 if side == "R" else -1.0 P = self.sk.params self.params = dict(hand_L=self.s, palm_L=P["palm_l"] * self.s, palm_w=P["palm_w"] * self.s, joint_bulge=P["joint"], wrist_w=2 * _WHW[1] * self.s, wrist_t=2 * _WHD[1] * self.s, ratio=P["ratio"], thumb_out=P["thumb_out"], web=P["web"], thumb_scale=self.sk.lengths["thumb"])
def _q(self, p): q = np.asarray(p, F32) / self.s return np.stack([q[:, 0] * self._sx, q[:, 1], -q[:, 2]], -1).astype(F32) # -> canonical (z dorsal)
def _out(self, q): q = np.asarray(q, float) q2 = q.reshape(-1, 3) return (np.stack([q2[:, 0] * self._sx, q2[:, 1], -q2[:, 2]], -1) * self.s).reshape(q.shape)
def eval(self, p, want_mat=False): d, m = sdf(self._q(p), self.sk, arm=self.arm) d = d.astype(float) * (self.s * .85) # rule: a safety factor for the approximate (non-exact) blends if want_mat: return d, np.where(m == MAT_NAIL, C_NAIL, C_SKIN).astype(np.int16) return d
def albedo(self, P, N, mat): """nails: skin-coloured with a pinker bed and a lighter free edge (never a white plate); skin: the table""" out = np.full((len(P), 3), np.nan, F32) m = mat == C_NAIL if m.any(): from pydraw.anatomy.render import SKIN_TONES base = np.array(SKIN_TONES["light"], F32) q = self._q(P[m]) t = np.zeros(len(q), F32) for f in FINGERS + ("thumb",): s = self.sk.segs[f][-1] a = s.a if self.side == "L" or True else s.a along = ((q - s.a) @ s.R[1]) / s.L near = np.linalg.norm(q - (s.a + s.R[1] * .7 * s.L), axis=1) < .8 * s.L t = np.where(near, np.clip((along - .78) / .2, 0, 1), t) bed = base * np.array([.97, .80, .80], F32) edge = np.minimum(base * 1.06 + .03, 1) out[m] = bed * (1 - t[:, None]) + edge * t[:, None] return out
def bounds(self): pts = [v for k, v in self.sk.landmarks.items() if not k.startswith("_")] pts += [np.array([x, -.30 if self.arm else -.2, z], F32) for x in (-.23, .23) for z in (-.15, .17)] P = self._out(np.array(pts)) lo, hi = P.min(0) - .11 * self.s, P.max(0) + .11 * self.s return lo, hi
def landmarks(self): return {k: self._out(v) for k, v in self.sk.landmarks.items() if not k.startswith("_")}
def lines(self): """drawn lines (core.Line, part space): knuckle creases on the back of the PIP/DIP, palmar finger creases at the joints (r22: 'not opposite the joints' - a touch distal of them on the palm side), the nail outlines, the thenar (life) line and the two transverse palm lines (r29: only lines that serve the form; line art shows them only at >= 12 px, r27 / checklist 14).""" out = {} sk = self.sk for f in FINGERS + ("thumb",): ch = sk.segs[f] joints = ch[1:] if f != "thumb" else ch[1:] for j, s in enumerate(joints): u, v, w = s.R hw = .5 * s.wa arc = [s.a + w * (.40 * s.da) * math.cos(t) + u * (.75 * hw) * math.sin(t) for t in np.linspace(-1.0, 1.0, 7)] out[f"knuckle_{f}_{j}"] = Line(self._out(np.array(arc)), "knuckle", .8) c = s.a + v * (.04 * s.L) arcp = [c - w * (.42 * s.da) * math.cos(t) + u * (.80 * hw) * math.sin(t) for t in np.linspace(-1.0, 1.0, 7)] out[f"crease_{f}_{j}"] = Line(self._out(np.array(arcp)), "crease", .8) s = ch[-1] u, v, w = s.R pts = [] for t in np.linspace(0, 2 * math.pi, 17): a = .5 + .5 * math.cos(t) along = .47 + .45 * a hw = .5 * (s.wa + (s.wb - s.wa) * along) pts.append(s.a + v * (along * s.L) + u * (.78 * hw * math.sin(t)) + w * (.5 * s.da)) out[f"nail_{f}"] = Line(self._out(np.array(pts)), "nail", .6, closed=True) # palm lines (canonical palm side z < 0) zb = -.115 th = [(.13, .40), (.07, .32), (.05, .22), (.065, .12), (.10, .04)] out["crease_thenar"] = Line(self._out(np.array([(x, y, zb) for x, y in th])), "crease", 1.0) out["crease_heart"] = Line(self._out(np.array([(-.21, .40, zb + .01), (-.10, .43, zb), (.02, .45, zb), (.10, .47, zb + .01)])), "crease", .9) out["crease_head"] = Line(self._out(np.array([(.16, .37, zb), (.06, .36, zb), (-.06, .33, zb), (-.16, .29, zb + .01)])), "crease", .9) return out
def build_hand(L=HAND_LEN, side=1, state="open", arm=True, **kw): """builder for the tests / assembler: L = hand length (metres or 1.0 for hand_L units); side +1 right, -1 left (a left hand in a right-handed frame, x = ulnar)""" return Hand(state, "R" if side > 0 else "L", hand_len=L, arm=arm, **kw)
def attach(Fw, state="open", arm=False, **kw): """the hand placed on body's WRIST frame (person.frames: o = wrist joint, R rows x = y cross z, y = distal, z = DORSAL, side +1 = the subject's left; unit hand_len). Body's x is radial on the left hand and ulnar on the right; this Part's x is radial on side "R" and ulnar on side "L", with z palmar. Both cases are the same proper rotation: (x, y, z)_hand = (-x, y, -z)_body.""" s = int(np.sign(Fw.get("side", 1)) or 1) part = Hand(state, "L" if s > 0 else "R", hand_len=1.0, arm=arm, **kw) R = np.asarray(Fw["R"], float) Rm = np.stack([-R[0], R[1], -R[2]]) return _core.Placed(part, R=Rm, t=np.asarray(Fw["o"], float), scale=float(Fw.get("hand_len", Fw.get("unit"))), name="hand_" + ("l" if s > 0 else "r"))
def study(path, states=("open", "curl", "fist"), yaws=(180, 0, 90), half=False): """one unit_sheet per state (front = palm... yaw 0 shows the palm in body's frame; 180 the back)""" from tools.unit_sheet import sheet for st in states: sheet(Hand(st), path.format(state=st), title=f"hand {st}", yaws=yaws, half=half)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596"""The head as a whole and the neck, as one SDF sculpt built from construction rules (wave 17, head lane).
Research: docs/research17/units/head_neck_hair.md (rules R1-R36). Method (smooth union inside a part, smooth-maxcarving, mirrored coordinates, tapered sticks) learned from procedural_humans.md; no code or constants copied.
FRAME (head units, H = 1 = crown to chin, hair excluded): y up, crown y=+0.5, chin y=-0.5, so the ADULT eye line is y=0 (R1: eyes at half the head). z = the direction the face points; z=0 is the ear-canal plane (Loomis side-plane axis), nose tip z ~ +0.56, back of skull z ~ -0.45 (R4: nose tip to occiput = 1.0 H). x = the subject's LEFT (+x is the viewer's right in a front view). Names ending _L are +x, _R are -x.
The landmark dict (landmarks()) is the single source of truth: every primitive below is placed from it, the featureslane sits the eye / nose / mouth / ear on it, the body lane hangs the head on `neck_base` / `neck_axis`.
Knobs (PYDRAW_EXP name=0 turns a rule off): hd_sock (carved eye sockets), hd_brow (brow ridge), hd_cheek (cheekbonewedges), hd_jaw (jaw corner under the ear), hd_side (Loomis side-plane flattening), hd_scm (sternomastoid V),hd_trap (trapezius buttress), hd_tilt (forward neck tilt), hd_sex (male square / female round construction),hd_age (child / baby / elder proportions), hd_zone (Gurney colour zones)."""import osimport mathimport numpy as np
F32 = np.float32
def knob(name, default=1.0): for kv in os.environ.get("PYDRAW_EXP", "").split(","): if "=" in kv: k, v = kv.split("=", 1) if k.strip() == name: try: return float(v) except ValueError: return default return default
# ---------------------------------------------------------------- SDF helpers: depict's core (anatomy/core.py)from pydraw.anatomy.core import (smin, smax, ellipsoid, sphere, round_cone, sabs, Part, Line, bezier_pts, # noqa: E402 MAT, SKIN, LIP, SCLERA, IRIS, PUPIL, LID, HAIR, BROW)
def mirrored(p, e=0.004): """mirrored coordinates with a soft midline (model the +x = subject's-left side)""" q = np.array(p, F32, copy=True) q[:, 0] = sabs(p[:, 0], e) return q
# ---------------------------------------------------------------- proportions (R1, R2, R12)# vertical fractions measured from the crown (0) to the chin (1), as in the research tables# baby: Loomis Plates 51-52 (face small, eye line below the middle); child between; elder = adult construction_AGE_KEYS = [ # (years, hairline, brow, eye, nose, mouth, width, face_depth, jaw_scale, neck_r) (0.5, 0.40, 0.56, 0.60, 0.755, 0.835, 0.80, 0.86, 0.62, 0.62), (6.0, 0.30, 0.49, 0.555, 0.735, 0.84, 0.72, 0.92, 0.78, 0.78), (13.0, 0.20, 0.45, 0.52, 0.72, 0.82, 0.66, 0.97, 0.92, 0.90), (25.0, 0.143, 0.429, 0.50, 0.714, 0.81, 0.64, 1.00, 1.00, 1.00), (80.0, 0.143, 0.429, 0.50, 0.714, 0.81, 0.64, 1.00, 1.00, 0.96),]
def _age_row(age): if knob("hd_age") <= 0: age = 25.0 ks = _AGE_KEYS if age <= ks[0][0]: return ks[0][1:] for (a0, *r0), (a1, *r1) in zip(ks, ks[1:]): if age <= a1: t = (age - a0) / (a1 - a0) return tuple(x0 + (x1 - x0) * t for x0, x1 in zip(r0, r1)) return ks[-1][1:]
class HeadParams: """conformation only (Parke split): sex 0 = female .. 1 = male, age in years. Neutral expression always."""
def __init__(self, sex=0.5, age=25.0, **kw): self.sex = float(sex) self.age = float(age) self.extra = kw
@classmethod def of(cls, who): """who: 'man', 'woman', 'boy', 'girl', 'baby', 'old man', 'old woman' or a HeadParams""" if isinstance(who, HeadParams): return who w = str(who).lower() sex = 1.0 if any(t in w.split() for t in ("man", "boy", "male", "he", "father", "grandfather")) else 0.0 age = 30.0 if "baby" in w: age, sex = 0.8, 0.5 elif any(t in w for t in ("boy", "girl", "child", "kid")): age = 7.0 elif any(t in w for t in ("teen",)): age = 14.0 elif any(t in w for t in ("old", "elder", "grand")): age = 75.0 return cls(sex=sex, age=age)
def landmarks(P=None): """the 21 named landmarks (+ helpers) in head units, as float32 3-vectors. See the module docstring for the frame.""" P = HeadParams() if P is None else HeadParams.of(P) s = P.sex if knob("hd_sex") > 0 else 0.5 hair_f, brow_f, eye_f, nose_f, mouth_f, wid, dep, jaws, neckr = _age_row(P.age) Y = lambda f: 0.5 - f # from-crown fraction -> y eye_y = Y(eye_f) half_w = wid / 2.0 * (0.955 + 0.075 * s) # skull half width at the temples / cheekbones (Bridgman 0.571..0.62) eye_w = (2 * half_w) / 5.0 # Reilly fifths: eye width = gap = width / 5 ez = 0.345 * dep # eyeball centre depth: set back under the brow fz = 0.47 * dep # face front plane (stoss) L = {} L["crown"] = (0.0, 0.5, -0.04) L["hairline"] = (0.0, Y(hair_f), 0.36 + 0.08 * (hair_f - 0.143) / 0.26) L["stoss"] = (0.0, Y(brow_f), fz) # glabella: brow line x middle line (Loomis key point) for side, sx in (("L", 1.0), ("R", -1.0)): L["eye_" + side] = (sx * eye_w, eye_y, ez) L["socket_" + side] = (sx * eye_w * 1.02, eye_y + 0.012, ez + 0.055) L["brow_" + side] = (sx * eye_w * 1.05, Y(brow_f) + 0.012 - 0.01 * s, fz - 0.05 - 0.01 * (1 - s)) # cheekbone: 1/3 back from the face front toward the ear, below the eye (Bridgman, R7) ear_x = half_w * 0.98 L["cheekbone_" + side] = (sx * half_w * 0.76, eye_y - 0.075, fz - fz / 3.0 - 0.03) # jaw angle: halfway round the ball, under and a little in front of the ear, low (R6) jw = half_w * (0.66 + 0.21 * s) * (0.85 + 0.15 * jaws) L["jaw_angle_" + side] = (sx * jw, Y(mouth_f + 0.065 - 0.12 * (1 - jaws)), 0.015 * dep) # zygion: the widest point of the face, on the zygomatic arch in front of the ear (face width for the fifths) L["zygion_" + side] = (sx * half_w * 0.975, eye_y - 0.065, 0.11 * dep) L["mouth_" + side] = (sx * eye_w * (0.82 + 0.04 * s) * (0.55 + 0.45 * jaws), Y(mouth_f), 0.415 * dep) # ear between brow and nose lines, on the side plane, behind the jaw hinge (R5) L["ear_top_" + side] = (sx * ear_x, Y(brow_f) + 0.01, -0.035) L["ear_bot_" + side] = (sx * ear_x * 0.97, Y(nose_f), 0.0) L["ear_canal_" + side] = (sx * ear_x * 0.93, (Y(brow_f) + Y(nose_f)) / 2 - 0.01, -0.005) L["mastoid_" + side] = (sx * half_w * 0.76, Y(nose_f) - 0.02, -0.075) L["nose_root"] = (0.0, eye_y + 0.02, fz - 0.025) L["nose_tip"] = (0.0, Y(nose_f) + 0.045, 0.56 * dep - 0.01 * (1 - jaws) * 4) L["nose_base"] = (0.0, Y(nose_f), (0.485 - 0.06 * (1 - jaws)) * dep) L["mouth_c"] = (0.0, Y(mouth_f), (0.485 - 0.12 * (1 - jaws)) * dep) # the muzzle pushes the mouth forward (Reilly) L["chin_front"] = (0.0, Y(mouth_f + 0.62 * (1 - mouth_f)), (0.462 - 0.05 * (1 - jaws) * 3) * dep) L["chin"] = (0.0, -0.5, (0.40 - 0.05 * (1 - jaws) * 2) * dep) L["occiput"] = (0.0, 0.04, -0.45 * dep) L["nape"] = (0.0, Y(nose_f) - 0.08, -0.33 * dep) L["hyoid"] = (0.0, -0.53, 0.235 * dep) # the throat meets the under-jaw half way, not at the ear tilt = math.radians(17.0) if knob("hd_tilt") > 0 else 0.0 nr = (0.215 + 0.065 * s) * neckr * 0.5 / 0.5 # neck radius (front width 0.47 f .. 0.56 m H) nlen = 0.50 * neckr ** 1.6 # a baby has almost no neck top = np.array([0.0, -0.36, 0.0], F32) ax = np.array([0.0, math.cos(tilt), math.sin(tilt)], F32) # leans forward going up (R9) base = top - ax * nlen L["neck_top"] = tuple(top) L["neck_base"] = tuple(base) L["pit"] = tuple(base + np.array([0.0, 0.0, nr * 0.95], F32) + ax * 0.0) L["c7"] = tuple(base + np.array([0.0, 0.09, -nr * 0.92], F32)) out = {k: np.asarray(v, F32) for k, v in L.items()} er = 0.052 if P.age >= 12 else 0.052 * (1.0 + 0.012 * (12 - P.age)) # the eyeball is nearly adult size at birth for side in ("L", "R"): out["pupil_" + side] = out["eye_" + side] + np.array([0.0, 0.0, er], F32) out["_neck_axis"] = ax out["_neck_r"] = np.float32(nr) out["_eye_w"] = np.float32(eye_w) out["_eye_r"] = np.float32(er) out["_half_w"] = np.float32(half_w) out["_sex"] = np.float32(s) out["_jaws"] = np.float32(jaws) # baby fat (buccal pads: round full cheeks, soft jaw) and age (surface only: hollows, jowls; Loomis Plate 31) out["_fat"] = np.float32(np.clip((10.0 - P.age) / 9.0, 0, 1) if knob("hd_age") > 0 else 0.0) out["_old"] = np.float32(np.clip((P.age - 45.0) / 35.0, 0, 1) if knob("hd_age") > 0 else 0.0) return out
NAMES21 = ["crown", "hairline", "stoss", "brow_L", "brow_R", "eye_L", "eye_R", "socket_L", "socket_R", "nose_tip", "nose_base", "mouth_L", "mouth_R", "chin", "jaw_angle_L", "jaw_angle_R", "cheekbone_L", "cheekbone_R", "ear_top_L", "ear_top_R", "ear_bot_L", "ear_bot_R", "mastoid_L", "mastoid_R", "occiput", "nape", "hyoid", "pit"]
# ---------------------------------------------------------------- the sculptdef pchip(xk, yk, x): """monotone cubic Hermite through (xk, yk) (xk increasing), evaluated at x; flat outside""" xk = np.asarray(xk, np.float64) yk = np.asarray(yk, np.float64) h = np.diff(xk) dl = np.diff(yk) / h m = np.zeros_like(yk) for i in range(1, len(yk) - 1): if dl[i - 1] * dl[i] > 0: w1, w2 = 2 * h[i] + h[i - 1], h[i] + 2 * h[i - 1] m[i] = (w1 + w2) / (w1 / dl[i - 1] + w2 / dl[i]) m[0], m[-1] = dl[0], 0.0 # top knot: flat, so the vault closes without a seam xc = np.clip(x, xk[0], xk[-1]) i = np.clip(np.searchsorted(xk, xc) - 1, 0, len(h) - 1) t = (xc - xk[i]) / h[i] t2, t3 = t * t, t * t * t return ((2 * t3 - 3 * t2 + 1) * yk[i] + (t3 - 2 * t2 + t) * h[i] * m[i] + (-2 * t3 + 3 * t2) * yk[i + 1] + (t3 - t2) * h[i] * m[i + 1]).astype(F32)
def contours(L): """the three construction contours of the head, as (y knots, values), all placed on landmark heights: half-width in the front view, the face-front profile on the midline, the back-of-skull profile (z=0 = ear plane).""" s = float(L["_sex"]) jaws = float(L["_jaws"]) hw = float(L["_half_w"]) eye_y = float(L["eye_L"][1]) brow_y = float(L["stoss"][1]) nose_y = float(L["nose_base"][1]) mouth_y = float(L["mouth_c"][1]) chin = L["chin"] cf = L["chin_front"] ja = L["jaw_angle_L"] dome0 = brow_y + 0.15 # the vault starts above the brow (Loomis ball above the equator) fat = float(L["_fat"]) # the width contour stays wide under the jaw angle: the JAW LINE (chin -> angle) is cut by the under-jaw plane in # skull_sdf, so the face narrows to the chin along that diagonal, not along a horizontal crease yw = [-0.5, float(ja[1]), float(L["cheekbone_L"][1]), dome0] jw = float(ja[0]) + 0.01 # no knot between the chin and the jaw angle: a width knot there reads as a horizontal seam across the face vw = [jw * (0.74 + 0.10 * s) * (1 - 0.05 * fat), jw + 0.045 * fat, hw * 0.965, hw * 1.03] cz = float(cf[2]) yf = [-0.5, -0.475, float(cf[1]), mouth_y - 0.45 * (mouth_y - float(cf[1])), mouth_y, nose_y, eye_y, brow_y] vf = [float(chin[2]), cz - 0.012, cz, cz - (0.018 + 0.004 * s) * (1 - 0.6 * float(L["_fat"])), float(L["mouth_c"][2]) - 0.022, float(L["nose_base"][2]) - 0.025, float(L["nose_root"][2]) - 0.02, float(L["stoss"][2])] occ = L["occiput"] nape = L["nape"] yb = [-0.5, float(nape[1]) - 0.08, float(nape[1]), (float(nape[1]) + float(occ[1])) / 2, float(occ[1]), dome0] vb = [-0.12, float(nape[2]) * 0.75, float(nape[2]), float(occ[2]) * 0.94, float(occ[2]), float(occ[2]) * 0.985] yn = [-0.5, mouth_y, nose_y, eye_y, brow_y, dome0] vn = [1.78 + 0.1 * s, 1.84 + 0.1 * s, 2.05, 2.55 + 0.1 * s, 2.5, 2.1] # monotone below the nose: no groove at the mouth line return dict(w=(yw, vw), f=(yf, vf), b=(yb, vb), n=(yn, vn), dome0=dome0, domef=brow_y)
def _loft(p, L, C): """lofted head: at each height a section whose half-width and front / back depth come from the contours; above dome0 the sections close as a vault (fuller at the back, Loomis). Distance is approximate (used with a safety factor by the tracer).""" x, y, z = p[:, 0], p[:, 1], p[:, 2] d0 = C["dome0"] yc = np.clip(y, -0.5, 0.5) yl = np.minimum(yc, d0) w = pchip(*C["w"], yl) df = C["domef"] zf = pchip(*C["f"], np.minimum(yc, df)) zb = pchip(*C["b"], yl) t = np.clip((yc - d0) / (0.5 - d0), 0.0, 1.0) w = w * (1 - t ** 2.0) ** 0.5 tf = np.clip((yc - df) / (0.5 - df), 0.0, 1.0) zf = zf * (1 - tf ** 2.0) ** 0.5 # forehead slopes up and back from the brow (Bridgman) zb = zb * (1 - t ** 2.7) ** (1 / 2.7) w = np.maximum(w, 1e-3) zf = np.maximum(zf, 1e-3) zb = np.minimum(zb, -1e-3) rz = np.where(z > 0, zf, -zb) u = np.abs(x) / w v = np.abs(z) / rz # section exponent: a narrow round BARREL at the muzzle (Reilly), a broad flat face plane at the eyes with a # sharp turn to the side at the brow corner, a slightly boxy vault behind (Loomis side planes) nf = pchip(*C["n"], yc) n = np.where(z > 0, nf, 2.2) r = (u ** n + v ** n) ** (1.0 / n) sc = np.minimum(w, rz) d = (r - 1.0) * sc ey = np.abs(y - yc) d = np.where(ey > 0, np.sqrt(np.maximum(d, 0) ** 2 + ey * ey), d) return 0.85 * d # the section distance is approximate: keep the tracer safe
def section(C, y): """(half width, front depth, back depth, exponent) of the loft at height y (scalars)""" y = float(np.clip(y, -0.5, 0.5)) d0, df = C["dome0"], C["domef"] w = float(pchip(*C["w"], np.array([min(y, d0)]))[0]) zf = float(pchip(*C["f"], np.array([min(y, df)]))[0]) zb = float(pchip(*C["b"], np.array([min(y, d0)]))[0]) t = max(0.0, (y - d0) / (0.5 - d0)) tf = max(0.0, (y - df) / (0.5 - df)) w *= (1 - t ** 2) ** 0.5 zf *= (1 - tf ** 2) ** 0.5 zb *= (1 - t ** 2.7) ** (1 / 2.7) n = float(pchip(*C["n"], np.array([y]))[0]) return w, zf, zb, n
def surf_pt(C, x, y, side=False): """the point on the loft's front surface at (x, y); side=True: x is ignored and the point is on the side at the depth z where the section is widest (z = 0)""" w, zf, zb, n = section(C, y) if side: return np.array([w, y, 0.0], F32) u = min(abs(x) / w, 0.999) z = zf * (1 - u ** n) ** (1 / n) return np.array([x, y, z], F32)
def bump(p, a, b, r, h): """smooth raised ridge of height h along the segment a-b, falloff radius r (subtract from d to raise)""" a = np.asarray(a, F32) b = np.asarray(b, F32) ba = b - a t = np.clip(((p - a) @ ba) / max(float(ba @ ba), 1e-9), 0, 1) e = p - a - t[:, None] * ba r2 = np.einsum("ij,ij->i", e, e) / (r * r) w = np.clip(1 - r2, 0, 1) return h * w * w
def skull_sdf(p, L): """cranium + face + jaw as one lofted mass from the construction contours, then the planes: under-jaw cut, cheekbones, brow ridge, temples and carved eye sockets. Returns distance (skin).""" s = float(L["_sex"]) q = mirrored(p, 0.004) C = contours(L) d = _loft(p, L, C) # under-jaw plane: chin -> both jaw angles; behind the jaw angle the skull base (R6, ck6, ck12) if knob("hd_jaw") > 0: ch, ja = L["chin"], L["jaw_angle_L"] dz = float(ch[2] - ja[2]) dy = float(ch[1] - ja[1]) nrm = np.array([0.0, -dz, dy], F32) nrm /= np.linalg.norm(nrm) if nrm[1] > 0: nrm = -nrm g1 = (p - ch) @ nrm # >0 below the jaw line g2 = (float(ja[1]) - 0.005) - p[:, 1] # skull base behind the jaw g = smin(g1, g2, 0.03) # kept = above the jaw line OR above the skull base d = smax(d, g, 0.025 - 0.01 * s + 0.025 * float(L["_fat"])) # a baby's jaw is soft and round # the planes are raised or sunk ON the surface (displacement along a curve laid on the loft), so they never # stick out as rods: cheekbone, zygomatic arch, brow ridge, temple, the masseter corner, the chin mound sp = lambda x, y, side=False: surf_pt(C, x, y, side) cb = L["cheekbone_L"] br = L["brow_L"] st = L["stoss"] hw = float(L["_half_w"]) eye_y = float(L["eye_L"][1]) if knob("hd_cheek") > 0: # cheekbone: widest point of the face below the eye, 1/3 back (R7); it sweeps forward-down toward the nose # wing and back along the zygomatic arch to the ear (Bridgman) c0 = sp(float(cb[0]), float(cb[1])) c1 = sp(float(cb[0]) * 0.62, float(cb[1]) - 0.035) c2 = sp(hw * 0.97, float(cb[1]) + 0.01, side=True) kf = 1 - 0.8 * float(L["_fat"]) d = d - kf * (bump(q, c1, c0, 0.08, 0.009) + bump(q, c0, c2, 0.06, 0.002)) # soft hollow under it (more on men and the old) # temple: the side plane turns in behind the brow corner (temporal fossa) t0 = sp(hw * 0.95, float(br[1]) + 0.04, side=True) d = d + bump(q, t0, t0 + np.array([0.0, 0.06, -0.06], F32), 0.12, 0.004) if knob("hd_brow") > 0: # brow ridge: the glabella and the bar over each eye to the brow corner where front turns to side (R20) g = sp(0.0, float(st[1])) b1 = sp(float(br[0]), float(br[1]) + 0.005) b2 = sp(float(br[0]) * 1.65, float(br[1]) + 0.0) hb = (0.004 + 0.010 * s) * (1 - float(L["_fat"])) # no brow ridge on a baby d = d - bump(q, g, b1, 0.06, hb) - bump(q, b1, b2, 0.05, hb * 0.7) if knob("hd_jaw") > 0: # chin mound (two lateral lobes in men, Reilly chin oval) and the masseter corner at the jaw angle cf = L["chin_front"] c0 = sp(0.0, float(cf[1])) c1 = sp(0.025 + 0.025 * s, float(cf[1]) - 0.01) d = d - bump(q, c0, c1, 0.06, 0.005 + 0.008 * s) ja = L["jaw_angle_L"] fat, old = float(L["_fat"]), float(L["_old"]) if fat > 0: # buccal fat: a full round cheek in front of the masseter, below the cheekbone f0 = sp(float(cb[0]) * 0.80, float(cb[1]) - 0.10) d = d - bump(q, f0, f0 + np.array([0.0, -0.06, -0.03], F32), 0.16, 0.03 * fat) # the fat under a baby's chin: a soft roll filling the under-jaw into the neck ch = L["chin"] u0 = np.array([0.0, float(ch[1]) + 0.01, float(ch[2]) - 0.09], F32) d = d - bump(q, u0, u0 + np.array([0.12, 0.03, -0.08], F32), 0.11, 0.035 * fat) if old > 0: # age: cheekbone and jaw corner more evident, temple and under-cheek hollows deeper, flesh sags at the jaw h0 = sp(float(cb[0]) * 0.80, float(cb[1]) - 0.11) d = d + bump(q, h0, h0 + np.array([0.0, -0.06, 0.0], F32), 0.07, 0.008 * old) d = d + bump(q, t0, t0 + np.array([0.0, 0.05, -0.04], F32), 0.07, 0.007 * old) ja = L["jaw_angle_L"] jl = sp(float(ja[0]) * 0.72, float(ja[1]) + 0.01) d = d - bump(q, jl, jl + np.array([0.0, -0.035, -0.02], F32), 0.055, 0.010 * old) # eye sockets carved with smooth-max (brow and cheek rims form as the carve's rim) if knob("hd_sock") > 0: so = L["socket_L"] ew = float(L["_eye_w"]) sock = ellipsoid(q, so, np.array([ew * 0.62, ew * 0.44, 0.05], F32)) d = smax(d, -(sock + 0.012 * float(L["_fat"])), 0.045) # shallower sockets on a baby return d
def neck_sdf(p, L): s = float(L["_sex"]) q = mirrored(p, 0.004) top, base, ax, nr = L["neck_top"], L["neck_base"], L["_neck_axis"], float(L["_neck_r"]) # the column (spine + back muscles), a little wider at the top from the side (Proko), set back: the throat # sits in front of the spine and makes up about half the neck's width (Proko) back = np.array([0.0, 0.0, -0.035], F32) col = round_cone(p, base - ax * 0.05 + back, top + ax * 0.05 + back, nr * 0.92, nr * 0.94) d = col pit = L["pit"] ew = float(L["_eye_w"]) # throat (larynx + trachea): a narrower tube in front, from under the jaw to the pit hy = L["hyoid"] thr = round_cone(p, np.array([0, hy[1] - 0.05, hy[2] - 0.085], F32), pit + np.array([0, 0.03, -0.05], F32), 0.26 * nr, 0.26 * nr) d = smin(d, thr, 0.09) if knob("hd_scm") > 0 and float(L["_fat"]) < 0.6: # sternomastoid V: mastoid (behind the ear) to the pit, two muscles not meeting (gap ~ one eye width, Proko) scm = round_cone(q, L["mastoid_L"] + np.array([-0.01, -0.01, 0.01], F32), pit + np.array([ew * 0.42, 0.02, -0.025], F32), 0.040 + 0.012 * s, 0.026 + 0.006 * s) d = smin(d, scm, 0.07) if knob("hd_trap") > 0 and float(L["_fat"]) < 0.6: # trapezius: braces the back of the head, slopes out and down to the shoulders (the body lane continues it) c7 = L["c7"] tr = round_cone(q, np.array([0.035, L["nape"][1] - 0.01, L["nape"][2] + 0.03], F32), np.array([nr * 0.95, c7[1] - 0.02, c7[2] + 0.09], F32), 0.045, 0.05 + 0.015 * s) d = smin(d, tr, 0.09) # larynx: a wedge, sharper in men (90 vs 120 deg, Proko) if knob("hd_larynx") > 0: lar = ellipsoid(p, np.array([0, hy[1] - 0.085, hy[2] - 0.035 + 0.012 * s], F32), np.array([0.03 + 0.005 * s, 0.035 + 0.015 * s, 0.03], F32)) d = smin(d, lar, 0.06 - 0.03 * s) # cut the column below by a plane lower in front than at the back (R9) c7 = L["c7"] n = np.array([0.0, (pit - c7)[2], -(pit - c7)[1]], F32) n = n / np.linalg.norm(n) if n[1] > 0: n = -n cut = (p - pit) @ n # positive below the plane d = smax(d, cut, 0.02) return d
def proxy_features(p, L): """placeholder eye / nose / mouth / ear masses so the head sheet reads; the features lane replaces them. Returns (eye, skin, lips) distances for the proxies only.""" q = mirrored(p, 0.002) er = float(L["_eye_r"]) ec = L["eye_L"] eye = sphere(q, ec, er) lid = sphere(q, ec, er * 1.10) lid = smax(lid, -(np.abs(q[:, 1] - ec[1] + 0.006) - er * 0.36 + 0.0 * q[:, 2]), 0.004) # the fissure lid = smax(lid, -(q[:, 2] - ec[2] + er * 0.2), 0.01) if False else lid nt, nb, nr_ = L["nose_tip"], L["nose_base"], L["nose_root"] bridge = round_cone(p, nr_ + np.array([0, -0.01, -0.03], F32), nt + np.array([0, 0.01, -0.02], F32), 0.02, 0.026) ball = sphere(p, nt + np.array([0, -0.006, -0.022], F32), 0.03) wing = ellipsoid(q, np.array([0.032, nb[1] + 0.024, nb[2] - 0.0], F32), np.array([0.024, 0.022, 0.03], F32)) nose = smin(smin(bridge, ball, 0.03), wing, 0.025) mc, ml = L["mouth_c"], L["mouth_L"] lipU = round_cone(q, np.array([0.0, mc[1] + 0.01, mc[2] - 0.012], F32), ml + np.array([0, 0.003, -0.012], F32), 0.016, 0.005) lipD = round_cone(q, np.array([0.0, mc[1] - 0.016, mc[2] - 0.018], F32), ml + np.array([-0.01, -0.002, -0.014], F32), 0.018, 0.005) lips = smin(lipU, lipD, 0.004) et, eb = L["ear_top_L"], L["ear_bot_L"] ec2 = (et + eb) / 2 ear = ellipsoid(q - ec2 + np.array([0, 0, 0], F32), np.array([0.0, 0.0, -0.01], F32), np.array([0.018, float(et[1] - eb[1]) / 2, 0.06], F32)) skin = smin(smin(nose, ear, 0.0), lid, 0.0) return eye, skin, lips
def head_sdf(p, P=None, L=None, features=None, neck=True, proxies=True): """p (N,3) float32 in head units -> (dist, mat). features: optional dict name -> fn(p, L) -> (dist, mat) from the features lane (eye, nose, mouth, ear); a name present there replaces the proxy.""" if L is None: L = landmarks(P) p = np.asarray(p, F32) d = skull_sdf(p, L) if neck: d = smin(d, neck_sdf(p, L), 0.09) # a soft submandibular fill (no light leak under the jaw) mat = np.full(len(p), SKIN, np.int16) if proxies: eye, skin, lips = proxy_features(p, L) d = smin(d, skin, 0.012) lm = lips < d d = smin(d, lips, 0.008) mat[lm] = LIP em = eye < d d = np.minimum(d, eye) mat[em] = SCLERA if features: for name, fn in features.items(): fd, fm = fn(p, L) m = fd < d d = np.minimum(d, fd) mat[m] = np.asarray(fm)[m] if np.ndim(fm) else fm return d.astype(F32), mat
def bounds(L=None, neck=True): """axis-aligned bound (lo, hi) of the sculpt, for bounded evaluation""" lo = np.array([-0.48, -1.06 if neck else -0.56, -0.60], F32) hi = np.array([0.48, 0.56, 0.66], F32) return lo, hi
def interface(): """what the features / body lanes read""" return dict(frame="H=1 crown->chin; y up (crown +0.5, chin -0.5, adult eye line 0); z face-forward, 0 = ear-canal " "plane; x = subject's left (+x = viewer right in front view)", landmarks=NAMES21, materials=MAT)
def neck_frame(L=None, H=1.0): """the NECK attachment frame agreed with the body lane: o = pit, R columns = [x left | neck axis | forward]""" if L is None: L = landmarks() ax = np.asarray(L["_neck_axis"], F32) x = np.array([1.0, 0.0, 0.0], F32) z = np.cross(x, ax) R = np.stack([x, ax, z], 1).astype(F32) nr = float(L["_neck_r"]) out = dict(o=L["pit"], R=R, H=H, pit=L["pit"], nape=L["c7"], neck_rx=nr * 0.96, neck_rz=nr) for k in ("mastoid_L", "mastoid_R", "jaw_angle_L", "jaw_angle_R", "occiput", "neck_top", "neck_base", "c7", "hyoid"): out[k] = L[k] return out
class Head(Part): """the head (+ neck) as a Part for depict's renderer and the study sheet. who: 'woman', 'man', 'girl', 'boy', 'baby', 'old woman', 'old man' or HeadParams; features: dict name -> fn(p, L) -> (d, mat) from the features lane; hair: a hair.Hair style name or None.""" name = "head"
def __init__(self, who="woman", features=None, neck=True, proxies=True, hair=None, sex=None, age=None, hair_colour="brown"): P = HeadParams.of(who) if sex is not None: P.sex = float(sex) if age is not None: P.age = float(age) self.P = P self.L = landmarks(P) self.features, self.neck, self.proxies = features, neck, proxies self.hair = None if hair: from pydraw.anatomy import hair as _hair self.hair = _hair.Hair(self.L, hair, P, hair_colour) self._lm = {k: v for k, v in self.L.items() if not k.startswith("_")} if self.hair is not None: self._lm.update(self.hair.landmarks()) self._lines = proxy_lines(self.L) if proxies and not features else {}
def eval(self, p, want_mat=False): p = np.asarray(p, F32) d, m = head_sdf(p, L=self.L, features=self.features, neck=self.neck, proxies=self.proxies) if self.hair is not None: dh = self.hair.sdf(p) hm = dh < d d = np.minimum(d, dh) m = np.where(hm, np.int16(HAIR), m) return (d, m) if want_mat else d
def bounds(self): lo, hi = bounds(self.L, self.neck) if self.hair is not None: hlo, hhi = self.hair.bounds() lo, hi = np.minimum(lo, hlo), np.maximum(hi, hhi) return lo, hi
def albedo(self, P, N, mat): out = np.full((len(P), 3), np.nan, F32) if self.proxies: er = float(self.L["_eye_r"]) for side in ("L", "R"): c = self.L["eye_" + side] s = mat == SCLERA q = P - c s &= np.einsum("ij,ij->i", q, q) < (er * 1.2) ** 2 if s.any(): qq = q[s] / er a = np.degrees(np.arccos(np.clip(qq[:, 2], -1, 1))) out[s] = np.where((a < 12)[:, None], (.07, .05, .05), np.where((a < 27)[:, None], (.33, .24, .16), (.80, .76, .72))) if self.hair is not None: h = mat == HAIR if h.any(): out[h] = self.hair.albedo(P[h], N[h]) return out
def face_frame(self): return dict(origin=np.zeros(3), x=np.array([1.0, 0, 0]), y=np.array([0, 1.0, 0]), z=np.array([0, 0, 1.0]), scale=1.0)
def proxy_lines(L): """drawn lines for the PROXY features only (the features lane supplies the real ones)""" out = {} er = float(L["_eye_r"]) for sx, s in ((1, "L"), (-1, "R")): c = L["eye_" + s] ang = np.linspace(-1.15, 1.15, 9) up = np.stack([c[0] + np.sin(ang) * er * 1.05, c[1] + 0.006 + np.cos(ang) * er * 0.40, c[2] + np.cos(ang) * er * 1.04], -1) out["lid_upper_" + s.lower()] = Line(up, "lid", 1.6, redraw=True) b = L["brow_" + s] out["brow_" + s.lower()] = Line(bezier_pts((sx * 0.06, b[1] - 0.005, b[2] + 0.03), (b[0], b[1] + 0.02, b[2] + 0.02), (sx * 0.21, b[1] - 0.005, b[2] - 0.06), 8), "brow", 1.4, True) nb = L["nose_base"] out["nostril_" + s.lower()] = Line(bezier_pts((sx * 0.012, nb[1] + 0.006, nb[2] + 0.02), (sx * 0.03, nb[1] + 0.0, nb[2] + 0.015), (sx * 0.045, nb[1] + 0.015, nb[2] - 0.005), 5), "nostril", 1.0, True) mc = L["mouth_c"] out["lip_line"] = Line(bezier_pts(L["mouth_R"] + np.array([0, 0, 0.0]), (0, mc[1] - 0.004, mc[2] + 0.002), L["mouth_L"], 12), "lip", 2.0, True) return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294"""pydraw.anatomy.hooks (wave 17, depict lane): the adapters that carry an assembled anatomy person into the existingrenderers. Nothing here is called by the main drawing path until a lane's person is accepted by critic9 and theone-line hooks in the hot files are claimed and switched on behind knobs (PYDRAW_EXP anat=0 turns all of it off).
to_pydraw3d(part, height=1.0, colors=None) -> [pydraw3d.models.Part, ...] one pydraw3d Part per material, all sharing ONE cached evaluation of the sculpt, in pydraw3d's model frame (standing height 1, base y=0, faces -z). pydraw3d's tracer, light and media then see an ordinary model. sprite(part, size, yaw=0, pitch=0, oversample=8, style="pixel"|"cel"|"line"|"shade", skin=None) -> (rgb uint8 HxWx3, alpha bool HxW, landmarks {name: (x, y, visible)}) at the target size, for compositing into a pixel / 2D canvas (the pixel path renders at 4-8x and reduces, then redraws the features). gbuffer_arrays(part, size, yaw=0, pitch=0, skin=None) -> dict with the pydraw.gbuf field names (rgb, albedo, value, part, mat, depth, normal, lightmap, shadow) for the G-buffer media renderers."""import numpy as npfrom . import core as Cfrom . import render as R
def _frame(part, height): """Placed transform: anatomy (+z forward, metres or H units) -> pydraw3d model frame (faces -z, base y=0, height 1)""" lo, hi = part.bounds() lo, hi = np.asarray(lo, float), np.asarray(hi, float) s = height / max(hi[1] - lo[1], 1e-9) Rm = C.rot(yaw=180) t = np.array([0.0, -lo[1] * s, 0.0]) cx, cz = (lo[0] + hi[0]) / 2, (lo[2] + hi[2]) / 2 t = t - (np.array([cx, 0, cz]) * s) @ Rm return C.Placed(part, R=Rm, t=t, scale=s)
class _Cache: """one evaluation of the sculpt per point array, shared by the per-material parts"""
def __init__(self, part): self.part, self.key, self.val = part, None, None
def get(self, p): # keyed on the CONTENT (pydraw3d poses each part's points into a new array, so the pointer differs between # the material parts of one evaluation) r = p.ravel() key = (p.shape, float(r[0]) if r.size else 0.0, float(r[-1]) if r.size else 0.0, float(r[r.size // 2]) if r.size else 0.0, float(r.sum()) if r.size else 0.0) if key != self.key: self.val = self.part.eval(np.asarray(p, float), True) self.key = key return self.val
def to_pydraw3d(part, height=1.0, colors=None, spec=None): from pydraw3d.models import Part as P3 placed = _frame(part, height) cache = _Cache(placed) lo, hi = placed.bounds() mats = _materials(placed, lo, hi) colors = colors or {} out = [] big = 1.0
def fn_for(m): def fn(p): d, mm = cache.get(p) # rule: the material's own surface is the sculpt where it owns the point; elsewhere a value that never # wins the nearest-part test at the surface but keeps min() over all materials == the sculpt return np.where(mm == m, d, d + big * .02).astype(np.float32) return fn for m in mats: c = colors.get(m, tuple(int(v * 255) for v in R.MAT_RGB.get(m, (.8, .8, .8)))) sp = (spec or {}).get(m, .35 if m in (C.LIP, C.SCLERA, C.IRIS, C.CORNEA) else .15) out.append(P3(fn_for(m), c, spec=sp, rough=.5, sss=1 if m in (C.SKIN, C.LID, C.LIP) else 0)) return out
def _materials(part, lo, hi, n=24): g = np.linspace(0, 1, n) X, Y, Z = np.meshgrid(g, g, g, indexing="ij") p = lo + np.stack([X.ravel(), Y.ravel(), Z.ravel()], -1) * (hi - lo) d, m = part.eval(p, True) step = float((hi - lo).max()) / n ms = set(int(v) for v in np.unique(m[np.abs(d) < step * 1.5])) # small materials (iris, pupil, nails) can fall between samples: ask the part's own draw list too ms |= {C.SKIN} return sorted(x for x in ms if x > 0) or [C.SKIN]
def sprite(part, size, yaw=0.0, pitch=0.0, oversample=8, style="pixel", skin=None, light=None, min_px=48): """None below min_px (D12: under ~48 px of figure the sculpt cannot keep head / neck / legs apart; the caller keeps the wave-16 glyph table there, byte-identical)""" if size < min_px: return None over = max(4, min(8, int(oversample))) S = size * over while S > 1024: # rule (resource limit): never trace above 1024 px over -= 1 S = size * over G = C.trace(part, C.View(yaw=yaw, pitch=pitch, size=S, margin=.02), size=S, light=light) if style == "pixel": rgb = R.pixel(G, size, skin=skin) alpha = G["hit"].reshape(size, over, size, over).mean((1, 3)) >= .4 else: img = {"cel": R.cel, "shade": R.shade}.get(style, None) img = img(G, skin=skin) if img is not None else R.lineart(G) rgb = (np.clip(img.reshape(size, over, size, over, 3).mean((1, 3)), 0, 1) * 255 + .5).astype(np.uint8) alpha = G["hit"].reshape(size, over, size, over).mean((1, 3)) >= .5 lm = {k: (x / over, y / over, v) for k, (x, y, v) in G["lm2d"].items()} return rgb, alpha, lm
def gbuffer_arrays(part, size, yaw=0.0, pitch=0.0, skin=None, light=None): G = C.trace(part, C.View(yaw=yaw, pitch=pitch, size=size), size=size, light=light) rgb = R.shade(G, skin) * 255 alb = R.albedo(G, skin) * 255 Nv = G["Nv"].copy() Nv[..., 1] *= -1 # pydraw.gbuf normals: y down d = np.where(G["hit"], G["depth"], np.nan) if np.isfinite(d).any(): lo, hi = np.nanmin(d), np.nanmax(d) dn = np.where(G["hit"], .5 - .1 * (d - lo) / max(hi - lo, 1e-6), 1.0) else: dn = np.ones_like(G["depth"]) L = np.asarray(G["light"], float) lightmap = np.clip((G["Nv"] * L).sum(-1) * .5 + .5, 0, 1) * G["hit"] return dict(rgb=rgb.astype(np.float32), albedo=alb.astype(np.float32), value=(rgb @ np.array((.3, .59, .11))).astype(np.float32) / 255, mat=G["mat"], part=G["mat"].astype(np.int16), hit=G["hit"], depth=dn.astype(np.float32), normal=Nv.astype(np.float32), lightmap=lightmap.astype(np.float32), shadow=(1 - G["shadow"]).astype(np.float32) * G["hit"], lm2d=G["lm2d"])
# material -> the pixel renderer's people part ids (pydraw.concepts.people.PARTS), so formlight / gbuf / outlines see# the same parts the old drawer wrote_PX_PART = {C.SKIN: 14, C.LID: 100, C.LIP: 100, C.SCLERA: 100, C.IRIS: 100, C.PUPIL: 100, C.CORNEA: 100, C.LASH: 100, C.BROW: 100, C.TEETH: 100, C.MOUTH: 100, C.NAIL: 14, C.HAIR: 1, C.CLOTH: 2, C.CLOTH2: 3, C.SHOE: 4}
def paste(cv, rgb, alpha, x0, y0, obj_id=None, mats=None, ids=None): """write a sprite (from sprite()) into a pydraw Canvas at its top-left (x0, y0): colour, object id and the people part per pixel (mats = the reduced material map, optional). Not called by the main path until wired.""" H, W = alpha.shape oid = obj_id if obj_id is not None else getattr(cv, "cur_id", None) for j in range(H): y = y0 + j if y < 0 or y >= cv.h or (getattr(cv, "clip_y", None) is not None and y >= cv.clip_y): continue row = cv.px[y] for i in range(W): x = x0 + i if x < 0 or x >= cv.w or not alpha[j, i]: continue row[x] = [int(v) for v in rgb[j, i]] if ids is not None: cv.ids[y][x] = ids[j, i] elif oid is not None: cv.ids[y][x] = oid if cv.part is not None and mats is not None: cv.part[y][x] = _PX_PART.get(int(mats[j, i]), 14)
# ------------------------------------------------------------------------------------------------ wiring trial (pixel)_PERSON = {}
def _person(sex): if sex not in _PERSON: from . import person as _p _PERSON[sex] = _p.build(sex=sex, cloth="tshirt+trousers", hair="short", lanes="all") return _PERSON[sex]
def px_eligible(cv, D, verb, text=""): """critic9 10:57 trial scope: ONE big plain standing adult man (the accepted part), full figure in frame, >= 48 px tall, nothing the anatomy person cannot draw yet (hats, props, coats, dresses, capes, roles, children, women)""" name, act, opts = verb if name != "stand" or act is not None: return False h = float(D.get("h") or 0) if h < 48 or h > getattr(cv, "h", 1e9) * 1.25: return False # D12: small figures keep the glyph table; close busts are not this trial text = (text or "").lower() if any(w in text for w in ("hat", "cap", "beard", "helmet", "hood", "bald", "glasses", "mustache", "moustache")): return False # asked-for head wear / facial hair the anatomy man does not draw yet if D.get("fem") or (D.get("age") or "adult") != "adult" or D.get("toddler") or D.get("chibi"): return False for k in ("hat", "hand_item", "holding", "dress", "coat", "cape", "vest", "skirt", "tabard", "steel", "seated_on", "shoulder_ride", "in_chair", "role_name"): if D.get(k): return False R_ = D.get("R") or {} if (R_.get("face") or "").split("_")[0] not in ("", "beard"): return False # clown / eyepatch / goggles faces (a random beard is dropped: not asked for) if any(R_.get(k) for k in ("apron", "overalls", "shorts", "boots", "mittens", "neck", "belt", "role")): return False return True
def _scene_grade(rgb, L): """critic9 11:39 (night tile): the sprite is lit by depict's studio light; the scene's own Light (time of day, night, dusk tint) is applied on top as a per-channel ratio to a neutral day light, measured on a grey card turned toward the viewer - so a white T-shirt is a dim blue-grey on a night street like everything else""" if L is None or not hasattr(L, "shade"): return rgb try: from pydraw.shading import Light day = Light((-.5, -.6, .6)) ns = [(x, y, np.sqrt(max(0.0, 1 - x * x - y * y))) for x in (-.6, 0, .6) for y in (-.6, 0, .6)] a = np.mean([L.shade((180, 180, 180), *n) for n in ns], 0) b = np.mean([day.shade((180, 180, 180), *n) for n in ns], 0) k = np.clip(a / np.maximum(b, 1.0), .2, 1.15) except Exception: return rgb if np.allclose(k, 1, atol=.03): return rgb return np.clip(rgb.astype(float) * k, 0, 255).astype(np.uint8)
def px_person(cv, ctx, inst, D, verb): """draw the accepted anatomy man into the pixel canvas: rendered at 2-4x (trace <= 768 px), reduced, features redrawn, then pasted with the object id and people part ids. Returns True when drawn.""" text = ((getattr(ctx, "scene", None) or {}).get("text") or "") if isinstance(getattr(ctx, "scene", None), dict) else "" if not px_eligible(cv, D, verb, text): return False rgb01 = lambda c: tuple(float(v) / 255 for v in c) colors = {C.CLOTH: rgb01(D["shirt"]), C.CLOTH2: rgb01(D["pants"]), C.SHOE: rgb01(D["shoes"]), C.HAIR: rgb01(D["hair"])} h, x, y, f = float(D["h"]), float(D["x"]), float(D["y"]), D.get("f") or 1 part = _person("m") lo, hi = part.bounds() fh = (hi[1] - lo[1]) / max(hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]) # the sprite square holds the figure's bounds at 96% (View margin .02 each side) - its side so the figure is h tall S = int(np.ceil(h / (.96 * fh))) over = max(2, min(8, 512 // max(S, 1))) # trace <= ~512 px (speed); 2x at the largest figures T = S * over yaw = 20.0 * (1 if f > 0 else -1) G = C.trace(part, C.View(yaw=yaw, size=T, margin=.02), size=T) G["colors"] = colors rgb = R.pixel(G, S, skin=rgb01(D["skin"])) rgb = _scene_grade(rgb, D.get("L")) hitc = G["hit"].reshape(S, over, S, over).mean((1, 3)) alpha = hitc >= .4 mats = G["mat"].reshape(S, over, S, over)[:, over // 2, :, over // 2] # place: the lowest figure row on the ground line y, centred on x rows = np.nonzero(alpha.any(1))[0] cols = np.nonzero(alpha.any(0))[0] if not len(rows): return False x0 = int(round(x - (cols[0] + cols[-1] + 1) / 2)) y0 = int(round(y - (rows[-1] + 1))) # ids: skin pixels take draw_person's skin id (the prompt-colour pass recolours the clothes, never the skin) ids = None sid, bid = D.get("skin_id"), D.get("base_id", getattr(cv, "cur_id", None)) if bid is not None and (sid is None or sid == bid): sid = bid - .5 # as draw_person does for big figures: skin is its own id, never recoloured by the prompt if sid is not None and bid is not None: ids = np.where(np.isin(mats, (C.SKIN, C.LID, C.LIP, C.NAIL, C.SCLERA, C.IRIS, C.PUPIL, C.BROW, C.MOUTH, C.TEETH, C.LASH, C.CORNEA, C.HAIR)), sid, bid) paste(cv, rgb, alpha, x0, y0, mats=mats, ids=ids) return True
# ------------------------------------------------------------------------------------------------ wiring trial (3D)def p3_person(name, ra, la, skin, hair, top, bottom, shoes, female, child, old, bald, beard, expr, look, chibi, prop, holding, inter, sleep, yaw, facing): """pydraw3d: the accepted anatomy man as a pydraw3d Model (one Part per material over one cached sculpt), for a plain standing adult man with nothing in his hands; None = not this trial's case (the old model carries on)""" if name != "stand" or female or child or old or bald or beard or look or chibi or prop or holding or inter or sleep: return None if expr not in (None, "", "neutral") or (ra not in (None, "down", "rest") or la not in (None, "down", "rest")): return None from pydraw3d.pose import Model, Rigid, about, rot_axis, posed rgb = lambda c: tuple(int(v) for v in c) part = _person("m") parts = to_pydraw3d(part, 1.0, colors={C.SKIN: rgb(skin), C.LID: rgb(skin), C.HAIR: rgb(hair), C.CLOTH: rgb(top), C.CLOTH2: rgb(bottom), C.SHOE: rgb(shoes)}) placed = _frame(part, 1.0) lm = placed.landmarks() g = lambda *ns: next((np.asarray(lm[n], float) for n in ns if n in lm), None) wr, wl, crown = g("wrist_R", "wrist_r"), g("wrist_L", "wrist_l"), g("crown") hip = g("pubis") anchors = {} if wr is not None and wl is not None: anchors = {"hand": wr, "hands": (wr + wl) / 2, "hand_top": wr, "held": wr} if crown is not None: anchors["head"] = crown if hip is not None: anchors["seat"] = hip T = Rigid() yaw_ = yaw or 20 if facing in ("left", "right"): T = about((0, 0, 0), rot_axis("y", yaw_ if facing == "left" else -yaw_)) for pt in parts: pt.fn = posed(pt.fn, T) m = Model.of(parts, aspect=.42, height=1.0, anchors={a: T.pt(v) for a, v in anchors.items()}) m.front = "-z" return m123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203"""pydraw.anatomy.limbs (wave 17, body lane): the arm and the leg as SDF sculpts from construction rules.
Rules: docs/research17/units/torso_limbs.md (R<n>, checklist ck<n>). ARM R11 the deltoid caps the arm from the acromion to halfway down the humerus, its outer edge outside the rib cage (ck3); R13 overlapping blocks at angles, the upper arm deep front-to-back; R14 + R17 the forearm is two blocks: the top broad side FORWARD, the bottom broad side OUT (thumb up / forward), the twist happens ALONG the forearm and the wrist box (w = 2 t) is solid with the hand (ck15, ck16); R15 the contours alternate: the outer peaks (deltoid high, the ridge muscle at the elbow) and the inner peaks (biceps, flexor mass lower) are staggered (ck2); R16 the elbow's three knobs, the inner condyle larger. LEG R18 the femur slants in to the knee (the stance is set by person.skeleton; ck12), the trochanter mass is the torso's; R19 vastus lateralis high outside, vastus medialis teardrop low inside, adductor fullness near the groin; R20 the knee box with the patella above the joint line (ck11); R21 a straight shin, the calf behind the knee, its outer head higher, the inner fuller and lower (ck13); R22 the inner ankle higher, the outer lower and further back (ck14). Every segment tapers (ck1); blends inside a unit are larger than at the joints (k_unit / k_joint; ck19). fat: site weights (upper arm back .6, inner thigh .8, calf .3, knee .1, ankle / wrist .05; R27, ck21). muscle: the named muscle masses grow, the blends get crisper. Children: rounder, no definition.Units: built in head heights H on segment frames (origin at the joint, local y up the bone, local z forward, local xOUTWARD for either side). Pure numpy, rules only."""import numpy as npfrom .core import Part, Line, ellipsoid, rbox, round_cone, sphere, capsule, _v, SKINfrom .torso import axes_from, lerp, PadSculpt
class Seg: """a bone frame: origin at the upper joint a, the bone runs to b; local x = outward (side s), y = up the bone, z = forward. at(t, out, fwd) -> world point t along the bone (0 = a, 1 = b), offsets in head heights."""
def __init__(self, a, b, s, H, fwd=(0, 0, 1)): self.a, self.b, self.s, self.H = _v(a), _v(b), s, H self.len = float(np.linalg.norm(self.b - self.a)) R = axes_from(self.a - self.b, _v(fwd)) # rows: x, y (up the bone), z R[0] = R[0] * s # x outward on either side self.R = R self.Rm = np.stack([R[0] * s, R[1], R[2]]) # a proper rotation (det +1) for oriented ellipsoids
def at(self, t, out=0.0, fwd=0.0): return self.a + (self.b - self.a) * t + self.R[0] * out * self.H + self.R[2] * fwd * self.H
def ell(self, S, t, out, fwd, r, k, mat=SKIN, tilt=None): c = self.at(t, out, fwd) rr = _v(r) * self.H R = self.Rm if tilt is None else tilt S.add(lambda p, c=c, rr=rr, R=R: ellipsoid(p, c, rr, R), k=k, mat=mat, bound=(c, float(rr.max()) * 1.02)) return c
def _cone(S, a, b, ra, rb, k, mat=SKIN): S.add(lambda p, a=a, b=b: round_cone(p, a, b, ra, rb), k=k, mat=mat, bound=((a + b) / 2, float(np.linalg.norm(b - a)) / 2 + max(ra, rb)))
def _type(fem, child, muscle, fat): """girth factors by type: female limbs slimmer, muscles strap-like except thighs (R27, Loomis); child rounder""" g = lerp(1.0, .86, fem) g = lerp(g, .80, child) # a school-age child's limbs are slender (est), the softness is in the blends mus = (lerp(1.0, .62, fem) * (1 + (muscle - .4) * 1.1)) * (1 - child * .7) fa = fat - .35 return g, mus, fa
class Arm(Part): """one arm, side s (+1 = the subject's left), from the shoulder joint through the elbow to the wrist. J: skeleton (person.skeleton); acromion: the torso's acromion landmark (the arm's root, R9 / ck4)."""
def __init__(self, J, s, acromion=None, fem=0.0, child=0.0, fat=.35, muscle=.4): super().__init__() self.S = PadSculpt() self.name = "arm_" + ("l" if s > 0 else "r") sd = "l" if s > 0 else "r" H = J["H"] g, mus, fa = _type(fem, child, muscle, fat) gd = g # the deltoid keeps its size; the arm itself is thicker (critic9 r1) g = g * lerp(1.18, 1.0, child) soft = 1 + max(fa, 0) * 1.5 + child * .3 kU = .16 * H * soft * (1 - max(muscle - .4, 0) * .4) kJ = .04 * H * soft sho, elb, wri = J["sho_" + sd], J["elb_" + sd], J["wri_" + sd] U = Seg(sho, elb, s, H) F = Seg(elb, wri, s, H) S = self.S L = self._lm fat_back = max(fa, -.2) * .6 * .2 # R27: the upper arm's back takes fat # humerus core: deep front-to-back (R13), tapering to the elbow fu = max(fa, -.2) * .35 * .2 # general upper-arm fat (R27 .35-.6 weights) U.ell(S, .48, 0, -fu * .5, (.135 * g + fu, .62, .155 * g + fu), 0) # the deltoid (R11): an inverted triangle cap; the ball over the shoulder + the tail wedging into the outer # groove halfway down (insertion at .5); its outer edge sticks out past the rib cage (ck3) dm = lerp(1.0, mus ** .6, .7) * (1 - .3 * child) # a child's shoulder is a soft round, not a muscle cap c_d = U.at(.06, .07, .0) r_d = _v((.16 * dm, .30, .22 * dm)) * H * gd S.add(lambda p, c=c_d, r=r_d, R=U.Rm: ellipsoid(p, c, r, R), k=kU, bound=(c_d, float(r_d.max()))) _cone(S, U.at(.18, .08 * dm, .0), U.at(.50, .07, .0), .14 * H * gd * dm, .06 * H * g, kU) L["deltoid_ins_" + sd] = U.at(.5, .15 * g, 0) # biceps (front, peaking low ~.58) and triceps (back, peaking high ~.36): staggered contours (R15, ck2) U.ell(S, .58, -.01, .085, (.115 * g * mus ** .5, .30, .125 * g * mus), kU) U.ell(S, .36, .01, -.085 - fat_back * .5, (.13 * g * mus ** .5 + fat_back, .36, .13 * g * mus + fat_back), kU) # the inner (coraco-brachialis) fullness out of the armpit U.ell(S, .22, -.08, .0, (.10 * g, .26, .11 * g), kU) # the ridge (supinator longus) rises a third up the upper arm and swells to the elbow, outside (R15 Bridgman) c_rg = U.at(.92, .095 * g, .035) r_rg = _v((.085 * mus ** .5, .34, .10)) * H * g S.add(lambda p, c=c_rg, r=r_rg, R=F.Rm: ellipsoid(p, c, r, R), k=kU, bound=(c_rg, float(r_rg.max()))) # the elbow (R16): olecranon at the back, the inner condyle larger than the outer; a bony, crisp blend S.add(lambda p, c=U.at(1.0, -.095 * g, -.01): sphere(p, c, .062 * H * g), k=kJ, bound=(U.at(1.0, -.095 * g, -.01), .1 * H)) S.add(lambda p, c=U.at(1.0, .08 * g, -.01): sphere(p, c, .045 * H * g), k=kJ, bound=(U.at(1.0, .08 * g, -.01), .1 * H)) S.add(lambda p, c=U.at(.98, 0, -.08 * g): sphere(p, c, .065 * H * g), k=kJ, bound=(U.at(.98, 0, -.08 * g), .1 * H)) L["olecranon_" + sd] = U.at(.98, 0, -.145 * g) # forearm (R14): the top block, broad side FORWARD (wide across, x), the flexor mass inside (lower peak, # .32) and the extensors outside-back; the "drumstick": meaty top half, bone and tendon below (ck15) F.ell(S, .27, 0, -.01, (.19 * g, .36, .125 * g), kU) F.ell(S, .33, -.075 * g, .015, (.12 * g * mus ** .4, .34, .115 * g), kU) F.ell(S, .22, .06 * g, -.04, (.09 * g, .30, .095 * g), kU) # the bottom block, broad side OUT (deep front-to-back, z), narrow edge forward (R14): the twist is along the # forearm between the two blocks, never at the wrist (R17, ck16) F.ell(S, .72, 0, 0, (.078 * g, .32, .125 * g), kU) # the wrist box, w = 2t (hand_foot 16), solid with the hand; narrower than the forearm end and the palm c_w = F.at(.99, 0, 0) h_w = _v((.058, .05, .115)) * H * g S.add(lambda p, c=c_w, h=h_w, R=F.Rm: rbox(p, c, h, .045 * H * g, R), k=kJ, bound=(c_w, .2 * H)) # the ulna head knob on the little-finger side, back of the wrist S.add(lambda p, c=F.at(.95, 0, -.10 * g): sphere(p, c, .035 * H * g), k=kJ, bound=(F.at(.95, 0, -.10 * g), .08 * H)) L["wrist_" + sd] = wri L["elbow_" + sd] = elb self.U, self.F, self.s = U, F, s self._lines["elbow_crease_" + sd] = Line([U.at(.97, -.06, .09), U.at(1.0, 0, .11), U.at(.97, .05, .09)], "crease", .6)
class Leg(Part): """one leg, side s, from the hip joint through the knee to the ankle (the foot hangs on the ankle frame)"""
def __init__(self, J, s, fem=0.0, child=0.0, fat=.35, muscle=.4): super().__init__() self.S = PadSculpt() self.name = "leg_" + ("l" if s > 0 else "r") sd = "l" if s > 0 else "r" H = J["H"] g, mus, fa = _type(fem, child, muscle, fat) g = g * lerp(lerp(1.08, 1.16, fem), 1.0, child) # fuller limbs (critic9 r1: female lower legs were sticks) mus_th = lerp(mus, 1.0 * (1 + (muscle - .4)), fem * .7) * (1 - child * .6) # female thighs keep their mass (R27) soft = 1 + max(fa, 0) * 1.5 + child * .6 kU = .15 * H * soft * (1 - max(muscle - .4, 0) * .4) kJ = .045 * H * soft hip, knee, ank = J["hip_" + sd], J["knee_" + sd], J["ankle_" + sd] T = Seg(hip, knee, s, H) Sh = Seg(knee, ank, s, H) S = self.S L = self._lm fin = max(fa, -.2) * .8 * .22 # inner thigh fat (R27 .8) fout = max(fa, -.2) * (.3 + .4 * fem) * .2 # outer thigh / saddle (female) gt = g * lerp(1.0, 1.08, fem) # femur core: tapers from the hip to the knee (r_knee ~ .55 r_top, R18; ck1) _cone(S, T.at(.0, -.02, -.02), T.at(.95, 0, .0), (.31 * gt + fin * .6) * H, .155 * H * g, 0) # vastus lateralis: the high outer bulge (R19, .25-.35 down) T.ell(S, .33, .11 * gt + fout, .0, (.19 * gt * mus_th ** .4 + fout, .54, .21 * gt), kU) # rectus femoris down the front T.ell(S, .45, .0, .10, (.17 * gt, .52, .14 * gt * mus_th ** .5), kU) # adductors: the upper inner fullness, reaching two-thirds down (R19) T.ell(S, .20, -.12 * gt - fin * .5, .0, (.18 * gt + fin, .38, .20 * gt + fin * .5), kU) # hamstrings behind T.ell(S, .50, .0, -.10, (.16 * gt, .50, .15 * gt), kU) # vastus medialis: the teardrop low inside, overhanging the knee (R19, .8) T.ell(S, .80, -.085 * g, .05, (.12 * g * mus_th ** .4, .19, .12 * g), kU) L["vm_" + sd] = T.at(.80, -.2 * g, .05) L["vl_" + sd] = T.at(.33, .27 * gt, 0) # the knee (R20): a box bevelled forward, the cap above the joint line, the inside larger; a crisp blend c_k = T.at(1.0, 0, .0) h_k = _v((.17, .15, .13)) * H * g S.add(lambda p, c=c_k, h=h_k, R=T.Rm: rbox(p, c, h, .13 * H * g, R), k=kU * .6, bound=(c_k, .3 * H)) c_pt = T.at(.955, 0, .14 * g) r_pt = _v((.08, .09, .045)) * H * g S.add(lambda p, c=c_pt, r=r_pt, R=T.Rm: ellipsoid(p, c, r, R), k=kJ * 1.5, bound=(c_pt, .15 * H)) L["patella_" + sd] = c_pt + T.R[2] * r_pt[2] S.add(lambda p, c=T.at(1.0, -.075 * g, -.01): sphere(p, c, .075 * H * g), k=kJ * 1.5, bound=(T.at(1.0, -.075 * g, -.01), .15 * H)) S.add(lambda p, c=T.at(1.0, .075 * g, -.02): sphere(p, c, .06 * H * g), k=kJ * 1.5, bound=(T.at(1.0, .075 * g, -.02), .15 * H)) # the shin (R21): the tibia's front edge straight from the knee to the inner ankle _cone(S, Sh.at(.02, -.01, .03), Sh.at(.97, -.02, .0), .14 * H * g, .095 * H * g, kJ) # the calf, behind the shin: the outer head higher (.27), the inner fuller and lower (.36) (R21, R23, ck13) mc = mus ** .3 * lerp(1.0, .95, fem) fc = max(fa, -.2) * .3 * .15 Sh.ell(S, .26, .07 * g, -.13, (.13 * g * mc + fc, .27, .16 * g * mc + fc), kU) Sh.ell(S, .35, -.075 * g, -.14, (.15 * g * mc + fc, .30, .17 * g * mc + fc), kU) # soleus under them, then the Achilles tendon to the heel: the thinnest part is just above the ankle Sh.ell(S, .56, 0, -.08, (.12 * g, .28, .11 * g), kU) _cone(S, Sh.at(.70, 0, -.06), Sh.at(1.02, 0, -.10 * g), .055 * H * g, .045 * H * g, kU * .6) L["calf_lat_" + sd] = Sh.at(.26, .155 * g, -.085) L["calf_med_" + sd] = Sh.at(.35, -.18 * g, -.09) # the malleoli (R22): the inner higher, the outer lower and further back (ck14) mi = Sh.at(1.0, -.075 * g, .0) + Sh.R[1] * .06 * H mo = Sh.at(1.0, .075 * g, -.035) S.add(lambda p, c=mi: sphere(p, c, .05 * H * g), k=kJ, bound=(mi, .08 * H)) S.add(lambda p, c=mo: sphere(p, c, .045 * H * g), k=kJ, bound=(mo, .08 * H)) L["mall_in_" + sd], L["mall_out_" + sd] = mi, mo L["knee_" + sd], L["ankle_" + sd], L["hip_" + sd] = knee, ank, hip self.T, self.Sh, self.s = T, Sh, s
def study(kind, fem=0.0, child=0.0, fat=.35, muscle=.4): from . import person J = person.skeleton(fem > .5, "child" if child > .5 else "adult") if kind == "arm": return Arm(J, 1, None, fem, child, fat, muscle) return Leg(J, 1, fem, child, fat, muscle)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249"""The mouth as one SDF sculpt (wave 17 features lane), neutral and closed. Rules fromdocs/research17/units/nose_mouth_ear.md section 2 (M1-M20). Unit U = brow line to nose base; origin = the subnasale(nose base), y up, z forward, +x the subject's left.
muzzle everything is modelled on a vertical cylinder (the dental arch, a "bloated tuna can") and wrapped back on it, so the corners recede and sit back .15 U from the centre [M1, M2, M10] upper lip three masses: two long wings and the heart-shaped tubercle, flatter and more angular [M3] lower lip two rounder lobes, taller than the upper (upper : lower vermilion 1 : 1.6) [M3, M5] slit the mouth line, a thin carve, the darkest line, darkest at the corners; slightly lower at the corners [M8] corners a dark pit with the modiolus bump beside it (soft outer edge, sharp inner) [M9] philtrum two pillars from the columella to the bow with a concave groove between them; the skin of the upper lip set at an angle to the red [M12] under lip the skin slopes back into the mentolabial groove, then the chin mound with two lateral lobes and the under-lip arch in shadow [M14]; profile reads as a staircase of three planes [M11] placement slit at the base + U/3, corners under the pupils (half width .37 U) [M6, M7] fold the nasolabial fold runs from the wing out and down, OUTSIDE the corner, faint [M15] (study context only)
Mouth(context=True) is the study part, a cast of the lower face; on a head the head lane's muzzle supplies the cheeksand chin. Knob: PYDRAW_EXP mouthsculpt=0 is read by callers that place it."""import numpy as np
from .featkit import (FeaturePart, U_ADULT, length, smin, smax, sphere, ellipsoid, round_cone, sabs, smoothstep, SKIN, LIP, MOUTH)from .core import Sculpt
P0 = dict(slit_y=-0.335, half_w=0.37, arch_r=0.55, front=0.04, upper_h=0.057, lower_h=0.08, tubercle=1.0, fullness=1.0, fem=0.0)
class _Mouth: def __init__(self, context=True, **kw): p = dict(P0) p.update(kw) self.p = p self.context = context self.R = p["arch_r"] self.zc = p["front"] - self.R # the arch axis (the front of the arch is just ahead of the subnasale) self.S = self._sculpt()
def cyl(self, q): """(s, y, r): arc length round the arch, height, distance out from the arch surface""" dz = q[:, 2] - self.zc rad = np.sqrt(q[:, 0] ** 2 + dz * dz) s = self.R * np.arctan2(q[:, 0], dz) return np.stack([s, q[:, 1], rad - self.R], -1)
def uncyl(self, c): c = np.asarray(c, float).reshape(-1, 3) a = c[:, 0] / self.R rad = self.R + c[:, 2] return np.stack([rad * np.sin(a), c[:, 1], self.zc + rad * np.cos(a)], -1)
_SPL = None
def prof(self, y, s): """the skin of the muzzle in profile (r offset from the arch), a smooth spline: the upper-lip skin angled forward to the red, the mentolabial groove, the chin, then back under the jaw [M11, M12, M14]; the muzzle rounds back beyond the corners into the cheeks; the nasolabial fold is a faint dip outside the corner [M15]""" if _Mouth._SPL is None: from scipy.interpolate import CubicSpline ys = np.array([0.40, 0.15, 0.0, -0.20, -0.33, -0.45, -0.55, -0.66, -0.80, -0.93, -1.05, -1.2]) rs = np.array([-0.10, -0.03, -0.005, 0.02, 0.005, -0.035, -0.07, -0.05, -0.012, -0.05, -0.17, -0.38]) _Mouth._SPL = CubicSpline(-ys, rs, bc_type="natural") yc = np.clip(y, -1.2, 0.4) r = _Mouth._SPL(-yc) a = np.abs(s) if self.context: t = np.clip((0.04 - y) / 0.5, 0, 1) sx = 0.30 + 0.17 * t ** 1.3 on = smoothstep(0.08, 0.0, y) * smoothstep(-0.62, -0.42, y) r = r - 0.008 * np.exp(-((a - sx) / 0.04) ** 2) * on return r
def _sculpt(self): p = self.p m = p["half_w"] ys = p["slit_y"] S = Sculpt() C = self.cyl
# the lower face as masses (Reilly muzzle oval on the face front, the chin box), the mentolabial groove carved if self.context: S.add(lambda q: ellipsoid(q, (0, -0.42, -1.07), (0.88, 1.15, 1.0)), 0.0, SKIN, None)
def muzzle(q): c = C(q) d = (c[:, 2] - self.prof(c[:, 1], 0 * c[:, 0])) * 0.9 d = smax(d, np.abs(c[:, 0]) - 0.5, 0.25) return smax(d, np.abs(c[:, 1] + 0.35) - 0.55, 0.25) S.add(muzzle, 0.18, SKIN, None) S.add(lambda q: ellipsoid(q, (0, -0.84, -0.19), (0.27, 0.2, 0.19)), 0.16, SKIN, None) # the mentolabial groove under the lower lip [M14] S.carve(lambda q: ellipsoid(C(q), (0, -0.55, 0.035), (0.2, 0.05, 0.07)), 0.07, None, None) # philtrum pillars [M12] (on a head the head's own muzzle surface carries them; only the groove is carved) for sg in ((-1, 1) if self.context else ()): S.add(lambda q, sg=sg: round_cone(C(q), (sg * 0.045, -0.04, -0.03), (sg * 0.068, -0.225, -0.008), 0.012, 0.016), 0.02, SKIN, None) S.carve(lambda q: round_cone(C(q), (0, -0.05, 0.05), (0, -0.21, 0.068), 0.05, 0.06), 0.03, None, None) f = p["fullness"] uh, lh = p["upper_h"] * f, p["lower_h"] * f # the lips as two swept sections along the arch whose height and depth THIN TO NOTHING at the corners [M9]: # upper = two wings + the tubercle bump (3 masses), front plane turned DOWN; lower = two lobes (a dip at the # middle), front plane turned UP, taller (1 : 1.6) [M3, M5, M16]; they meet on the slit line (no gap) tb = p["tubercle"] S.add(lambda q: self._lip(C(q), upper=True), 0.014, LIP, None) S.add(lambda q: self._lip(C(q), upper=False), 0.014, LIP, None)
# the slit [M8]: a thin carve that ENDS in the corner pits, the corners a little lower def slit(q): c = C(q) e = m * 0.86 yy = self._slit_y(c[:, 0]) t = np.clip(np.abs(c[:, 0]) / e, 0, 1) d = np.abs(c[:, 1] - yy) - 0.003 * (1 - 0.7 * t ** 2) d = np.maximum(d, np.abs(c[:, 0]) - e) return np.maximum(d, -c[:, 2] - 0.05) S.carve(slit, 0.003, MOUTH, None) # corners [M9]: a small dark pit where the red ends, the modiolus bump beside it for sg in (-1, 1): S.carve(lambda q, sg=sg: sphere(C(q), (sg * m * 0.93, ys - 0.014, -0.02), 0.02), 0.012, MOUTH, None) if self.context: # on a head the head's own cheek carries the modiolus (an added bump stood off it) S.add(lambda q, sg=sg: ellipsoid(C(q), (sg * (m + 0.06), ys - 0.01, -0.06), (0.06, 0.09, 0.05)), 0.05, SKIN, None) # chin mound with two lateral lobes [M14]
if self.context: S.inter(lambda q: ellipsoid(q, (0, -0.45, -0.45), (0.85, 0.82, 0.8)), 0.1) return S
def _slit_y(self, s): p = self.p m = p["half_w"] return p["slit_y"] - 0.014 * (s / m) ** 2 - 0.008 * np.exp(-(s / 0.06) ** 2)
def _lip(self, c, upper=True): """one lip as an elliptic section swept along the arch: height h(s) and depth t(s) fall to 0 at the corners""" p = self.p m = p["half_w"] f = p["fullness"] s, y, r = c[:, 0], c[:, 1], c[:, 2] u = np.clip(np.abs(s) / m, 0, 1) taper = np.sqrt(np.clip(1 - u ** 2, 0, 1)) ** 0.8 y0 = self._slit_y(s) if upper: # two wings and the tubercle: the height dips a little either side of the tubercle (the bow) # the bow: peaks where the philtral columns land, a shallow dip between; the tubercle bulges FORWARD h = p["upper_h"] * f * (1.0 + 0.16 * np.exp(-((np.abs(s) - 0.06) / 0.035) ** 2) - 0.1 * np.exp(-(s / 0.025) ** 2)) * taper t = (0.032 + 0.014 * p["tubercle"] * np.exp(-(s / 0.055) ** 2)) * f * taper + 0.004 yc = y0 + h rc = -0.016 + 0.012 * taper k = -0.6 # the front turns down else: h = p["lower_h"] * f * (1.0 - 0.06 * np.exp(-(s / 0.05) ** 2)) * taper t = 0.036 * f * taper + 0.004 yc = y0 - h rc = -0.024 + 0.012 * taper k = 0.45 # the front turns up dy, dr = y - yc, r - rc dr = dr - k * dy * 0.5 # shear: the section leans so its front faces down / up hh, tt = np.maximum(h, 1e-3) + 0.002, np.maximum(t, 1e-3) d = (np.sqrt((dy / hh) ** 2 + (dr / tt) ** 2) - 1.0) * np.minimum(hh, tt) return np.maximum(d, np.abs(s) - m)
@staticmethod def _lipmass(c, ctr, rad, tilt, face=0.0): """an ellipsoid in arch coordinates tilted in the s-y plane (the wings slope to the corners) and in the y-r plane (face < 0: the front turns down, the upper lip; face > 0: turns up, the lower lip) [M16]""" ca, sa = np.cos(tilt), np.sin(tilt) q = c - np.asarray(ctr, float) qq = np.stack([ca * q[:, 0] + sa * q[:, 1], -sa * q[:, 0] + ca * q[:, 1], q[:, 2]], -1) cf, sf = np.cos(face), np.sin(face) qq = np.stack([qq[:, 0], cf * qq[:, 1] - sf * qq[:, 2], sf * qq[:, 1] + cf * qq[:, 2]], -1) return ellipsoid(qq, (0, 0, 0), rad)
def sdf(self, q): return self.S.eval(q)
def mat(self, q): return self.post_mat(q, self.S.eval(q, True)[1])
def post_mat(self, q, m): """the wet inner red right at the slit is the dark mouth line, not a lit (specular) lip [M8]""" c = self.cyl(q) near = (m == LIP) & (np.abs(c[:, 1] - self._slit_y(c[:, 0])) < 0.007) return np.where(near, np.int16(MOUTH), m).astype(np.int16)
def paint(self, q, n, mat): col = np.full((len(q), 3), np.nan) c = self.cyl(q) p = self.p m = p["half_w"] dy = c[:, 1] - self._slit_y(c[:, 0]) u = np.abs(c[:, 0]) / m lip = mat == LIP if lip.any(): # value plan [M16, L3]: the upper red is a plane facing DOWN, one value darker and cooler; the lower red faces # up, lighter, with a soft light on its top-front; both darken into the wet slit and toward the corners up = dy[lip] > 0 k = smoothstep(0.002, 0.045, np.abs(dy[lip])) corner = smoothstep(0.55, 0.95, u[lip]) upper_c, lower_c = np.array([0.58, 0.30, 0.31]), np.array([0.80, 0.47, 0.44]) base = np.where(up[:, None], upper_c[None], lower_c[None]) v = (0.35 + 0.65 * k) * (1 - 0.35 * corner) lh = p["lower_h"] * p["fullness"] glow = (~up) * np.exp(-((-dy[lip] - 0.65 * lh) / (0.35 * lh)) ** 2) * (1 - corner) * 0.18 col[lip] = base * v[:, None] + glow[:, None] mo = mat == MOUTH if mo.any(): w = smoothstep(0.002, 0.008, np.abs(dy[mo]))[:, None] corner = smoothstep(0.75, 0.95, u[mo])[:, None] w = w * (1 - corner) # the corner pits are the darkest dots [L5, M9] col[mo] = np.array([0.10, 0.03, 0.03]) * (1 - w) + np.array([0.46, 0.22, 0.2]) * w return col
def lines(self): p = self.p m, ys = p["half_w"], p["slit_y"] s = np.linspace(-m, m, 25) slit = self.uncyl(np.stack([s, ys - 0.012 * (s / m) ** 2, np.full_like(s, 0.03 - 0.03 * (s / m) ** 2)], -1)) sl = np.linspace(-0.2, 0.2, 13) slit = self.uncyl(np.stack([s * 0.86, self._slit_y(s * 0.86), 0.022 * (1 - (s / m) ** 2)], -1)) under = self.uncyl(np.stack([sl, np.full_like(sl, ys - 2.0 * p["lower_h"] - 0.02), np.full_like(sl, -0.02)], -1)) return dict(lip_line=(slit, "lip", 2.0, True), under_lip=(under, "crease", 0.6, False))
def landmarks(self): p = self.p m, ys = p["half_w"], p["slit_y"] cc = self.uncyl([(0, ys, 0.03), (m, ys - 0.012, -0.0), (-m, ys - 0.012, 0.0), (0, ys + 2 * p["upper_h"], 0.03), (0, ys - 2 * p["lower_h"], 0.02), (0, -0.8, 0.03), (0, 0, 0)]) return dict(slit_mid=cc[0], mouth_c=cc[0], corner_L=cc[1], corner_R=cc[2], mouth_L=cc[1], mouth_R=cc[2], upper_top=cc[3], lower_bottom=cc[4], chin_front=cc[5], subnasale=cc[6])
class Mouth(FeaturePart): """the mouth as a core Part in metres (U = brow line to nose base)"""
def __init__(self, context=True, U=U_ADULT, **params): m = _Mouth(context=context, **params) m.lo, m.hi = ((-0.88, -1.32, -1.3), (0.88, 0.4, 0.42)) if context else ((-0.5, -1.05, -0.4), (0.5, 0.1, 0.2)) super().__init__(m, unit=U, side=1, name="mouth") p = m.p self.params = dict(U=U, half_w=p["half_w"] * U, slit_y=p["slit_y"] * U, upper_h=2 * p["upper_h"] * U, lower_h=2 * p["lower_h"] * U, arch_r=p["arch_r"] * U)
def build(context=True, U=U_ADULT, **params): return Mouth(context=context, U=U, **params)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195"""The nose as one SDF sculpt (wave 17 features lane), neutral only. Rules from docs/research17/units/nose_mouth_ear.md(section 1, rule ids N1-N17). Unit U = brow line to nose base (Loomis); a = half the alar width (= half theintercanthal distance, N2).
root the glabella keystone: a small down-facing plane between the brows where the bridge meets the forehead [N5] bridge three wedges [N4]: the bony wedge from the root widening to the break at half the length [N3] (the widest point of the bridge, a sharp ridge), then the cartilage wedge narrowing to the ball; built as tapered, flattened round cones so the top plane and two side planes read [N9] ball two alar-cartilage domes on a soft mirror (no seam on the midline) [N6] wings separate fatty masses on each side of the ball, set back from the septum, a wide top and thin side, hooking under [N7]; the alar crease where they meet the cheek nostrils COMMA carves from below (an ellipse with a tail toward the tip), the darkest value of the nose [N8], on the nose-base-to-ear-base line [N12]; the columella between them underside the bottom plane faces down so it is in shadow under a top light; nothing outlines the nose [N13, check 1] length root -> base = 1 U [N1], the tip .08 U above the base line, the tip projecting .33 U [table]
Nose(context=True) is the study part (a plaster cast of the mid-face so the side planes have a cheek to turn into);on a head the head lane's face supplies that. Knob: PYDRAW_EXP nosesculpt=0 is read by callers that place it."""import numpy as np
from .featkit import (FeaturePart, U_ADULT, length, smin, smax, sphere, ellipsoid, round_cone, sabs, smoothstep, unit, rot_x, rot_y, SKIN, MOUTH)from .core import Sculpt, rbox
P0 = dict(length=0.98, base_dz=0.06, a=0.24, tip_up=0.08, proj=0.36, bridge_w=0.62, ball_r=0.11, wing_r=0.14, nostril_len=0.12, dorsum=0.0, fem=0.0)
class _Nose: def __init__(self, context=True, **kw): p = dict(P0) p.update(kw) self.p = p self.context = context L, a = p["length"], p["a"] # landmarks in U, origin at the root (nasion), y up, z forward self.root = np.array([0.0, 0.0, 0.0]) self.base = np.array([0.0, -L, p["base_dz"]]) # subnasale self.tip = np.array([0.0, self.base[1] + p["tip_up"], self.base[2] + p["proj"]]) self.brk = self.root + 0.5 * (self.tip - self.root) + np.array([0, 0, 0.035 + p["dorsum"]]) # bony/cartilage self.supra = self.root + 0.82 * (self.tip - self.root) + np.array([0, 0, 0.005]) self.ala = np.array([a * 0.78, self.base[1] + 0.06, self.base[2] + 0.04]) self.nostril = np.array([a * 0.3, self.base[1] - 0.015, self.base[2] + 0.13]) self.S = self._sculpt()
# bridge: a flattened round cone (wider than deep near the root, the side planes visible) def _bridge(self, q, a, b, ra, rb, flat=0.72): qq = q.copy() qq[:, 0] = q[:, 0] * flat return round_cone(qq, a, b, ra, rb) / max(flat, 1e-6) * flat
def _profile(self, y): """dorsum z and top half-width along the nose height (root y=0 down to the tip): the bony wedge widens to the break at half the length (its widest, sharpest point), the cartilage wedge narrows to the ball [N3, N4]""" p = self.p yt = self.tip[1] + 0.06 t = smin(np.maximum(y / yt, 0), 1.12, 0.25) # smooth clamp: no seam where the ball takes over zr, zt = self.root[2], self.tip[2] - 0.05 hump = 0.03 * np.exp(-((t - 0.5) / 0.16) ** 2) + p["dorsum"] * np.sin(np.pi * t) zd = zr + (zt - zr) * t ** 1.05 + hump w = p["bridge_w"] / 0.62 tw = w * (0.045 + 0.03 * np.exp(-((t - 0.5) / 0.22) ** 2) - 0.008 * t) return zd, tw, t
def _wedge(self, q): """the nose body as a wedge: a narrow top plane, two side planes sloping back to the cheeks, the under-plane tilting back up to the lip [N9]""" zd, tw, t = self._profile(q[:, 1]) tanb = 0.62 ax = sabs(q[:, 0], 0.02) side = ((ax - tw) - (zd - q[:, 2]) * tanb) / np.sqrt(1 + tanb * tanb) top = q[:, 2] - zd d = smax(side, top, 0.05) # the under-plane: from under the ball back up toward the face (columella-lip angle ~100 deg) [M19] yb = self.base[1] + 0.13 + (q[:, 2] - self.base[2]) * 0.1 # ends above the wings: the base is ball + wings + columella d = smax(d, yb - q[:, 1], 0.06) d = smax(d, q[:, 1] - 0.08, 0.1) # the root ends at the glabella if self.context: return smax(d, -0.08 - q[:, 2], 0.04) # the wedge stops at the cast's face plane # on a head the wedge dives into the face, never wider than the wings [N2] d = smax(d, ax - self.p["a"] * 1.05, 0.06) return smax(d, -0.4 - q[:, 2], 0.06)
def _sculpt(self): p = self.p a = p["a"] S = Sculpt() tip, base = self.tip, self.base if self.context: # the mid-face cast: a gently curved front plane, cheeks rounding back, the brow above S.add(lambda q: ellipsoid(q, (0, -0.5, -1.15), (1.05, 1.3, 1.15)), 0.0, SKIN, ((0, -0.5, -1.15), 1.35)) S.add(lambda q: ellipsoid(q, (0, 0.28, -0.32), (0.95, 0.3, 0.38)), 0.3, SKIN, ((0, .28, -.32), 1.0)) for s in (-1, 1): S.carve(lambda q, s=s: ellipsoid(q, (s * 0.38, -0.02, -0.05), (0.17, 0.14, 0.12)), 0.14, None, ((s * .45, -.02, -.05), .3)) S.add(self._wedge, 0.07 if self.context else 0.0, SKIN, ((0, -0.45, 0.15), 0.75)) # ball: two alar domes on a soft mirror, the seam invisible (N6) br = p["ball_r"]
def ball(q): m = q.copy() m[:, 0] = sabs(q[:, 0], 0.04) # a softened box (top + two side planes + the under-plane) over the two domes, not a sphere [N6, N9] c = tip + (0.03, -0.035, -br * 0.9) box = rbox(m, c, (br * 0.85, br * 0.8, br * 0.95), br * 0.55) return smin(box, ellipsoid(m, c, (br * 0.9, br * 0.85, br * 0.95)), 0.03) S.add(ball, 0.08, SKIN, (tip, 0.35)) # columella from under the tip to the base S.add(lambda q: round_cone(q, tip + (0, -0.085, -0.08), base + (0, 0.03, 0.03), 0.04, 0.036), 0.03, SKIN, (base, 0.4)) # wings (N7): set back from the septum, a wide top and thin side, hooking under wr = p["wing_r"] for s in (-1, 1): c = self.ala * (s, 1, 1) # flatter and longer, wrapping back to the cheek (its back end lower and further out) S.add(lambda q, c=c: ellipsoid(q, c + (s * 0.01, 0.005, -0.03), (wr * 0.9, wr * 0.62, wr * 1.35)), 0.12, SKIN, (c, 0.35)) # nostrils (N8): comma carves from below, long axis from the wing toward the tip, a tail curling in for s in (-1, 1): c = self.nostril * (s, 1, 1) R = rot_x(0.3) # kept inside the wing: never opens through the wing's side (profile shows no hole) [N8] S.carve(lambda q, c=c, R=R: smax(ellipsoid(q, c, (0.045, 0.045, p["nostril_len"] * 0.8), R), np.abs(q[:, 0]) - a * 0.5, 0.01), 0.012, MOUTH, (c, 0.2)) tail = c + np.array([-s * 0.03, 0.004, 0.075]) S.carve(lambda q, t=tail: ellipsoid(q, t, (0.02, 0.028, 0.055)), 0.01, MOUTH, (tail, 0.1)) # alar crease: the wing sits in a groove against the cheek (on a head too) for s in (-1, 1): c = self.ala * (s, 1, 1) + (s * 0.16, 0.025, -0.07) S.carve(lambda q, c=c: ellipsoid(q, c, (0.025, 0.08, 0.05)), 0.05, None, (c, 0.15)) if self.context: S.inter(lambda q: ellipsoid(q, (0, -0.45, -0.25), (0.9, 0.95, 0.9)), 0.08) return S
def sdf(self, q): return self.S.eval(q)
def mat(self, q): return self.S.eval(q, True)[1]
def paint(self, q, n, mat): col = np.full((len(q), 3), np.nan) m = mat == MOUTH if m.any(): # the nostril is the darkest value of the nose (N8): near-black red, darker deeper in depth = np.clip((q[m, 1] - self.base[1]) / 0.05, 0, 1) col[m] = np.array([0.20, 0.08, 0.07])[None] * (1 - 0.5 * depth[:, None]) # the ball a touch warmer / redder (blood, N15) s = mat == SKIN if s.any(): w = np.clip(1 - length(q[s] - self.tip) / 0.25, 0, 1) ** 2 base = np.array([0.93, 0.76, 0.64]) c = base[None] + w[:, None] * np.array([0.0, -0.06, -0.06]) col[s] = np.where(w[:, None] > 0.01, c, np.nan) return col
def lines(self): a = self.p["a"] out = {} t = np.linspace(0, 1, 9) for s, sfx in ((1, "_l"), (-1, "_r")): c = self.nostril * (s, 1, 1) # comma: from the outer end round the bowl to the tail toward the tip ang = np.linspace(-0.3, np.pi + 0.4, 11) pts = np.stack([c[0] + s * 0.045 * np.cos(ang), np.full_like(ang, c[1] - 0.025), c[2] - 0.065 * np.sin(ang) * 0 + 0.07 * np.cos(ang * 0.5 + 0.3) - 0.03], -1) out["nostril" + sfx] = (pts, "nostril", 1.0, True) al = self.ala * (s, 1, 1) wing = np.stack([al[0] + s * (0.10 * np.cos(t * 2.2 - 0.3)), al[1] + 0.10 * np.sin(t * 2.2 - 0.3) - 0.02, al[2] + 0.02 - 0.06 * t], -1) out["wing" + sfx] = (wing, "crease", 0.5, False) return out
def landmarks(self): zd, tw, t = self._profile(np.array([self.brk[1]])) brk = np.array([0.0, self.brk[1], zd[0]]) al = self.ala + (self.p["wing_r"] * 0.85, 0, 0) return dict(root=self.root, nose_root=self.root, bridge_break=brk, tip=self.tip, nose_tip=self.tip, base=self.base, nose_base=self.base, ala_L=al, ala_R=al * (-1, 1, 1), nostril_L=self.nostril, nostril_R=self.nostril * (-1, 1, 1))
class Nose(FeaturePart): """the nose as a core Part in metres (U = brow line to nose base; adult U = H / 3.5)"""
def __init__(self, context=True, U=U_ADULT, **params): m = _Nose(context=context, **params) m.lo, m.hi = ((-0.95, -1.42, -1.17), (0.95, 0.52, 0.62)) if context else ((-0.42, -1.12, -0.35), (0.42, 0.2, 0.6)) super().__init__(m, unit=U, side=1, name="nose") self._lm["break"] = self._lm["bridge_break"] self.params = dict(U=U, a=m.p["a"] * U, length=m.p["length"] * U, proj=m.p["proj"] * U)
def build(context=True, U=U_ADULT, **params): return Nose(context=context, U=U, **params)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496"""pydraw.anatomy.person (wave 17, body lane): one whole neutral person assembled from the atelier's parts on theexisting rig skeleton (pydraw.rig.human.solve "stand" with its tilts zeroed: no new poses).
skeleton(sex, age, build) -> J: joints in METRES in depict's frame (+x = the subject's left, +y up, +z forward, the floor at y = 0), the chest / pelvis rotations and H (head height, metres) frames(J) -> the attachment frames the other lanes build on (posted on the board, round 0): "neck" o = pit of the neck, R rows = (left, neck axis tilted forward, forward) "wrist_l/_r" o = wrist joint, R rows = (thumb side t, distal d, palm normal n) "ankle_l/_r" o = ankle joint, R rows = (outward, up, toes forward) each with H and named points (see frames()). Person(...) -> the assembled Part: head + neck (head lane; stand-in until accepted), torso, limbs, hands and feet (hands lane; stand-ins until accepted), cloth shells (cloth.py). Parts melt into their parent only near their joint (a blend radius that fades with distance from the joint), so a hanging arm never webs onto the hip and the knees never melt together.
Rules only, pure numpy, CPU only."""import numpy as npfrom .core import Part, Placed, Sculpt, ellipsoid, rbox, round_cone, smin, _v, SKIN, SHOE, MATfrom .torso import Torso, axes_from, smoothstep
HEAD_M = {"adult": .23, "teen": .225, "child": .205, "toddler": .19, "old": .225} # head height in metres (est)
def skeleton(fem=False, age="adult", build="normal", stance=.30): """the rig's neutral standing skeleton in metres. stance: half the distance between the ankles in head heights (est .30: the femurs converge to the knees, R18 ck12; hip socket, knee and ankle stay in one line)""" from pydraw.rig import human C = human.canon(age, bool(fem), None, build) over = dict(pelvis=(0, 0, 0), spine=(0, 0, 0), neck=(0, 0, 0), shift=0, weight=None, look=0, near_arm=("dir", (.07, -1, .0), .985, human.P_ELB), far_arm=("dir", (.07, -1, .0), .985, human.P_ELB), near_leg=("ground", (0, 0), 0, human.P_KNEE), far_leg=("ground", (0, 0), 0, human.P_KNEE)) B = human.solve(C, "stand", None, f=1, opts=dict(over=over)) hh = C["hh"] H = HEAD_M.get(age, .23) k = H / hh # rig units (standing height 1) -> metres x0 = (B.sho[1][0] + B.sho[-1][0]) / 2 # centre the body on x = 0 (the rig's gesture shifts it a little) off = _v((x0, 0, 0))
def m(v): return (_v(v) - off) * k J = dict(H=H, hh=hh, k=k, C=C, age=age, fem=bool(fem), build=build) J["neck_base"] = m(B.neck_base) J["head_pivot"] = m(B.head_pivot) J["chin_y"] = C["chin"] * k J["crown_y"] = C["crown"] * k J["Rc"], J["Rp"], J["Rh"] = np.eye(3), np.eye(3), np.eye(3) # symmetric arms (the far side mirrored onto the near side's solve: identical by construction) for s, sd in ((1, "l"), (-1, "r")): for key, src in (("sho", B.sho), ("elb", B.elb), ("wri", B.wri)): v = m(src[1]) # the deltoid span reads ~2.5 head widths, not 3 (critic9 r4): the arm hangs .06 H closer in on a man v = v - _v((np.sign(v[0]) * (.06 if not fem else .02) * H, 0, 0)) J[key + "_" + sd] = _v((s * abs(v[0]), v[1], v[2])) # legs: from the rig's hip joints toward ankles at +-stance, the leg nearly straight (a relaxed knee: the rig's # 2-bone IK at 99.6 % reach); the rig's canon lengths are kept and the whole figure is lifted so the floor is y = 0 from pydraw.rig.core import ik2 l1, l2 = C["thigh"] * k, C["shin"] * k for s, sd in ((1, "l"), (-1, "r")): hip = m(B.hip[1]) hip = _v((s * abs(hip[0]), hip[1], 0.0)) tgt = _v((s * stance * H, C["ankle_y"] * k, 0.0)) dv = (tgt - hip) / np.linalg.norm(tgt - hip) knee, ank2 = ik2(hip, hip + dv * (l1 + l2) * .996, l1, l2, _v((0, 0, 1))) J["hip_" + sd], J["knee_" + sd], J["ankle_" + sd] = hip, knee, ank2 lift = C["ankle_y"] * k - J["ankle_l"][1] for key in list(J): if isinstance(J[key], np.ndarray) and J[key].shape == (3,): J[key] = J[key] + _v((0, lift, 0)) J["chin_y"] += lift J["crown_y"] += lift J["hipc"] = (J["hip_l"] + J["hip_r"]) / 2 # the hand covers the face (hairline -> chin, ~.86 H; Loomis / hand_foot.md): the rig's hand (.73 H) is a little # short for a hand drawn at hero size, so the hand length is set from the face (.80 H adult), the wrist stays put J["hand_len"] = max(C["hand"] * k, (.80 if age not in ("child", "toddler") else .70) * H) J["foot_len"] = C["foot"] * k J["ankle_y"] = C["ankle_y"] * k return J
def frames(J, neck_tilt=17.0): """attachment frames (rows = local axes in world, depict's convention) for the head / hands / feet lanes""" H = J["H"] from .torso import table T = table(1.0 if J["fem"] else 0.0, 1.0 if J["age"] in ("child", "toddler") else 0.0) nb = J["neck_base"] a = np.radians(neck_tilt) ny = _v((0, np.cos(a), np.sin(a))) # the neck axis tilted forward (head_neck_hair R9, 15-20 deg est) F = {} pit = nb + _v((0, -.10, T["neck_r"] * 1.25)) * H F["neck"] = dict(o=pit, R=np.stack([_v((1, 0, 0)), ny, np.cross(_v((1, 0, 0)), ny)]), H=H, pit=pit, nape=nb + _v((0, .08, -T["neck_r"] * 1.2)) * H, neck_base=nb, head_pivot=J["head_pivot"], chin_y=J["chin_y"], crown_y=J["crown_y"], neck_rx=T["neck_r"] * H, neck_rz=T["neck_r"] * 1.15 * H) for s, sd in ((1, "l"), (-1, "r")): e, w = J["elb_" + sd], J["wri_" + sd] # WRIST (hands lane 08:40 / 08:42): origin = wrist joint centre, y = distal (elbow -> wrist), z = dorsal (the back # of the hand), x = y cross z (radial on the LEFT hand, ulnar on the right: a proper rotation for both). # Neutral stand: palm toward the thigh -> dorsal = outward (+s x), thumb forward. y = (w - e) / np.linalg.norm(w - e) z = _v((s, 0, 0)) - y * float(y[0] * s) z /= np.linalg.norm(z) x = np.cross(y, z) F["wrist_" + sd] = dict(o=w, R=np.stack([x, y, z]), cols=np.stack([x, y, z], 1), x=x, y=y, z=z, side=s, H=H, unit=J["hand_len"], hand_L=J["hand_len"], hand_len=J["hand_len"], w=.30 * H * (.85 if J["fem"] else 1.0)) # ANKLE (hands lane): origin = ankle joint (talus top), y = forward (toes), z = up, x = y cross z (lateral on the # RIGHT foot, medial on the left); the sole plane is z_local = -ankle_h; unit foot_L ank = J["ankle_" + sd] y = _v((0, 0, 1)) z = _v((0, 1, 0)) x = np.cross(y, z) F["ankle_" + sd] = dict(o=ank, R=np.stack([x, y, z]), cols=np.stack([x, y, z], 1), x=x, y=y, z=z, side=s, H=H, unit=J["foot_len"], foot_L=J["foot_len"], foot_len=J["foot_len"], ankle_h=float(ank[1]), floor_y=0.0, mall_in=ank + _v((-s * .11, .06, 0)) * H, mall_out=ank + _v((s * .11, 0, -.04)) * H) return F
# ------------------------------------------------------------------------------------------------ stand-insclass StandInFoot(Part): """a plain foot wedge (until the hands lane's foot is accepted): heel block, instep sloping to the toes""" name = "foot_standin"
def __init__(self, Fa, mat=SKIN): super().__init__() o, R, H, L = Fa["o"], Fa["R"], Fa["H"], Fa["foot_len"] fw, up = R[1], R[2] y0 = -o[1] heel = o + fw * (-.18 * L) + up * (y0 * .55) toe = o + fw * (.78 * L) + up * (y0 * .55) mid = o + fw * (.25 * L) + up * (y0 * .45) S = self.S S.add(lambda p: round_cone(p, heel, mid, .25 * L * .55, .26 * L * .55), mat=mat, bound=((heel + mid) / 2, .5 * L)) S.add(lambda p: round_cone(p, mid, toe, .26 * L * .5, .14 * L * .55), k=.03 * L, mat=mat, bound=((mid + toe) / 2, .6 * L)) S.inter(lambda p: -(p[:, 1] - 0.0) * 1.0, k=.005) # flat sole on the floor
class StandInHand(Part): """a mitt: palm box + finger block + thumb cone (until the hands lane's hand is accepted)""" name = "hand_standin"
def __init__(self, Fw): super().__init__() o, R, Lh, w = Fw["o"], Fw["R"], Fw["hand_len"], Fw["w"] t, d, n = R[0] * Fw["side"], R[1], -R[2] # thumb side, distal, palm normal Rl = np.stack([t, d, n]) if np.linalg.det(np.stack([t, d, n])) > 0 else np.stack([-t, d, n]) pc = o + d * (.25 * Lh) S = self.S S.add(lambda p: rbox(p, pc, _v((w * .55, .25 * Lh, w * .2)), w * .15, Rl), bound=(pc, .4 * Lh)) fc = o + d * (.68 * Lh) + n * (w * .06) S.add(lambda p: rbox(p, fc, _v((w * .5, .22 * Lh, w * .14)), w * .12, Rl), k=.01, bound=(fc, .4 * Lh)) a = o + d * (.12 * Lh) + t * (w * .4) + n * (w * .1) b = o + d * (.5 * Lh) + t * (w * .55) + n * (w * .35) S.add(lambda p: round_cone(p, a, b, w * .2, w * .1), k=.012, bound=((a + b) / 2, .4 * Lh))
class StandInHead(Part): """head + neck stand-in: depict's EggHead placed on the neck frame, with a tilted neck cylinder""" name = "head_standin"
def __init__(self, J, Fn): super().__init__() from .core import EggHead H = J["H"] head_mid = _v((0, (J["chin_y"] + J["crown_y"]) / 2, J["head_pivot"][2] + .1 * H)) self.head = Placed(EggHead(H), t=head_mid) nb, ny = Fn["neck_base"], Fn["R"][1] a = nb + _v((0, -.15, 0)) * H b = nb + ny * (.75 * H) r0, r1 = Fn["neck_rx"], Fn["neck_rx"] * .95 self.S.add(lambda p: round_cone(p, a, b, r0, r1), bound=((a + b) / 2, .8 * H))
def eval(self, p, want_mat=False): if want_mat: d0, m0 = self.S.eval(p, True) d1, m1 = self.head.eval(p, True) d = smin(d0, d1, .02) return d, np.where(d1 < d0 + .005, m1, m0) return smin(self.S.eval(p), self.head.eval(p), .02)
def bounds(self): a, b = self.S.bounds(), self.head.bounds() return np.minimum(a[0], b[0]), np.maximum(a[1], b[1])
def landmarks(self): return self.head.landmarks()
def lines(self): return self.head.lines()
def albedo(self, P, N, mat): return self.head.albedo(P, N, mat)
# ------------------------------------------------------------------------------------------------ assemblydef smin_var(a, b, k): """smooth-min with a per-point blend radius k (array): 0 -> a hard min""" kk = np.maximum(k, 1e-9) h = np.clip(.5 + .5 * (b - a) / kk, 0, 1) out = b + (a - b) * h - kk * h * (1 - h) return np.where(k > 1e-7, out, np.minimum(a, b))
class Assembly(Part): """skin parts melted into a parent only near a joint (k fades from k at the joint to 0 at radius rad), then the cloth shells hard-min'd on top (cloth owns its pixels where it is the nearer surface)""" name = "person"
def __init__(self, root, attach=(), cloth=()): self.root = root self.attach = list(attach) # (part, joint point, k, rad) self.cloth = list(cloth) # parts (material = their own) self._b = [p.bounds() for p in [root] + [a[0] for a in self.attach] + self.cloth]
def _lb(self, i, p): lo, hi = self._b[i] q = np.maximum(np.maximum(lo - p, p - hi), 0) return np.sqrt((q * q).sum(-1))
def eval(self, p, want_mat=False): if want_mat: d, m = self.root.eval(p, True) else: d = self.root.eval(p) for i, (part, J0, k, rad) in enumerate(self.attach, 1): lb = self._lb(i, p) need = lb < d + k if not need.any(): continue kk = k * (1 - smoothstep(rad * .35, rad, np.sqrt(((p[need] - J0) ** 2).sum(-1)))) if want_mat: e, me = part.eval(p[need], True) take = e < d[need] dn = d.copy() dn[need] = smin_var(e, d[need], kk) mm = m.copy() mm[np.nonzero(need)[0][take]] = me[take] d, m = dn, mm else: d = d.copy() d[need] = smin_var(part.eval(p[need]), d[need], kk) n0 = 1 + len(self.attach) for j, part in enumerate(self.cloth): lb = self._lb(n0 + j, p) need = lb < d if not need.any(): continue if want_mat: e, me = part.eval(p[need], True) take = e < d[need] idx = np.nonzero(need)[0][take] d = d.copy() d[idx] = e[take] m = m.copy() m[idx] = me[take] else: d = d.copy() d[need] = np.minimum(d[need], part.eval(p[need])) return (d, m) if want_mat else d
def bounds(self): lo = np.min([b[0] for b in self._b], 0) hi = np.max([b[1] for b in self._b], 0) return lo, hi
def _parts(self): return [self.root] + [a[0] for a in self.attach] + self.cloth
def landmarks(self): out = {} for part in self._parts(): for k, v in part.landmarks().items(): out[k if k not in out else part.name + "." + k] = v return out
def lines(self): out = {} covered = {g.name for g in self.cloth} for part in self._parts(): if part is self.root and covered & {"tshirt", "dress"}: continue # the torso's drawn lines are under the shirt if part.name.startswith("leg_") and covered & {"trousers", "dress"}: continue for k, v in part.lines().items(): out[k if k not in out else part.name + "." + k] = v return out
def albedo(self, P, N, mat): out = None for part in self._parts(): if part.name.startswith("head"): a = part.albedo(P, N, mat) if a is not None: out = a cols = getattr(self, "colors", None) if cols: if out is None: out = np.full((len(P), 3), np.nan, np.float32) for m, c in cols.items(): s_ = mat == m if s_.any(): out[s_] = c return out
def face_frame(self): return None
def torso_study(fem=0.0, child=0.0, fat=.35, muscle=.4): """the torso alone with the neck stump (the atelier's first study sheet)""" age = "child" if child > .5 else "adult" J = skeleton(fem > .5, age) return Torso(J, fem, child, fat, muscle), J
SEX_FEM = {"m": 0.0, "f": 1.0}
# ------------------------------------------------------------------------------------------------ the other lanes' partsdef _lanes(lanes): """which lanes' parts replace the stand-ins: lanes=None reads PYDRAW_EXP blanes (default: none until critic9 accepts them), a string 'head,hands,feet' or a set""" if lanes is None: import os ev = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv) lanes = ev.get("blanes", "") if isinstance(lanes, str): lanes = {x.strip() for x in lanes.replace("+", ",").split(",") if x.strip()} if "all" in lanes: lanes = {"head", "hands", "feet"} return set(lanes)
class Cut(Part): """a part kept only on one side of a plane (n.p <= n.o + off, soft edge k): the hand / foot stubs above the joint are cut away so no cylinder end shows as a ring on the forearm or the shin (B19)"""
def __init__(self, part, o, n, k): self.part, self.o, self.n, self.k = part, _v(o), _v(n) / np.linalg.norm(n), float(k) self.name = part.name
def eval(self, p, want_mat=False): r = self.part.eval(p, want_mat) d = r[0] if want_mat else r from .core import smax d = smax(d, (p - self.o) @ self.n, self.k) return (d, r[1]) if want_mat else d
def bounds(self): return self.part.bounds()
def landmarks(self): return self.part.landmarks()
def lines(self): return self.part.lines()
def albedo(self, P, N, mat): return self.part.albedo(P, N, mat)
def lane_head(J, F, sex, age, hair=None): """the head lane's head + neck with the features lane's eyes / nose / mouth / ears (features.Face), in head units, scaled to H metres and moved so its pit sits on the torso's pit (NECK frame, round 0)""" try: from . import features as _feat except Exception: return None child = age in ("child", "toddler") who = {("m", False): "man", ("f", False): "woman", ("m", True): "boy", ("f", True): "girl"}[(sex, child)] if hair is None: hair = {"man": "short", "woman": "shoulder", "boy": "short", "girl": "shoulder"}[who] hd = _feat.Face(who, hair=hair or None) L = hd.L H = J["H"] t = F["neck"]["pit"] - np.asarray(L["pit"], float) * H P = Placed(hd, t=t, scale=H, name="head") return P
def lane_hand(Fw, state="curl"): """the hands lane's hand in the WRIST frame: Hand(side='R') takes anatomical axes (radial, distal, palmar); the left hand's frame is the mirror (an improper map, which Placed handles)""" try: from . import hand as _hand except Exception: return None if hasattr(_hand, "attach"): # the hands lane's own frame mapping (hands r3, board 09:51) try: return _hand.attach(Fw, state=state, arm=False) except Exception: pass x, y, z = Fw["x"], Fw["y"], Fw["z"] radial = x * Fw["side"] R = np.stack([radial, y, -z]) # rows: radial, distal, palmar in world hp = _hand.Hand(state, "R", hand_len=1.0, arm=False) return Placed(hp, R=R, t=Fw["o"], scale=Fw["hand_L"], name="hand")
def lane_foot(Fa, shoe=False): """the hands lane's foot in the ANKLE frame (x lateral, y up, z forward in its own canonical form), its sole on the floor""" try: from . import foot as _foot except Exception: return None if hasattr(_foot, "attach"): try: return _foot.attach(Fa, shoe=shoe) except Exception: pass side = "L" if Fa["side"] > 0 else "R" fp = _foot.Foot(shoe=shoe, side=side, foot_len=1.0, leg=False) s = Fa["foot_L"] t = Fa["o"].copy() t[1] = -_foot.FLOOR * s # the foot's floor on y = 0 return Placed(fp, t=t, scale=s, name="foot")
class Person(Assembly): """the whole neutral person: sex 'm' / 'f', age 'adult' / 'child'; fat, muscle 0..1; cloth = None or a dict (see cloth.outfit); parts=(head, hands, feet) toggles for the study sheets""" name = "person"
def __init__(self, sex="m", age="adult", fat=.35, muscle=.4, cloth=None, head=True, hands=True, feet=True, arms=True, legs=True, lanes=None, hair=None, hand_state="curl", colors=None): from .limbs import Arm, Leg fem = SEX_FEM.get(sex, 0.0) child = 1.0 if age in ("child", "toddler") else 0.0 if child: fem = fem * .3 # a child's body is near sexless at the construction level (est) J = skeleton(sex == "f", age) F = frames(J) self.J, self.F = J, F H = J["H"] T = Torso(J, fem, child, fat, muscle) lm = T.landmarks() att = [] if arms: for s, sd in ((1, "l"), (-1, "r")): A = Arm(J, s, lm["acromion_" + sd], fem, child, fat, muscle) att.append((A, J["sho_" + sd] - _v((s * .05, .3, 0)) * H, .09 * H, 1.6 * H)) if legs: for s, sd in ((1, "l"), (-1, "r")): Lg = Leg(J, s, fem, child, fat, muscle) att.append((Lg, J["hip_" + sd] + _v((s * .1, 0, 0)) * H, .12 * H, 1.7 * H)) lanes = _lanes(lanes) self.lanes = lanes if head: hp = lane_head(J, F, sex, age, hair) if "head" in lanes else None att.append((hp or StandInHead(J, F["neck"]), J["neck_base"], .08 * H, .9 * H)) if hands and arms: for s_, sd in ((1, "l"), (-1, "r")): hp = lane_hand(F["wrist_" + sd], hand_state) if "hands" in lanes else None if hp is not None: # keep the hand distal of a plane just above the wrist (the forearm owns the rest) Fw = F["wrist_" + sd] hp = Cut(hp, Fw["o"] - Fw["y"] * .04 * H, -Fw["y"], .02 * H) att.append((hp or StandInHand(F["wrist_" + sd]), J["wri_" + sd], .03 * H, .35 * H)) if feet and legs: for s_, sd in ((1, "l"), (-1, "r")): fp = lane_foot(F["ankle_" + sd], bool(cloth)) if "feet" in lanes else None if fp is not None: # the foot below a plane just over the malleoli (the shin owns the rest) fp = Cut(fp, F["ankle_" + sd]["o"] + _v((0, .05, 0)) * H, _v((0, 1, 0)), .06 * H) att.append((fp or StandInFoot(F["ankle_" + sd], SHOE if cloth else SKIN), J["ankle_" + sd], .05 * H, .45 * H)) shells = [] if cloth: from . import cloth as _cloth shells = _cloth.outfit(J, T, [a[0] for a in att], cloth, fem, child, fat) super().__init__(T, att, shells) self.fem, self.child = fem, child self.colors = colors # {material id: rgb 0..1} - the garment colours a prompt asks for # the named joints critic9's tests read (UNITS.md), _L = the subject's left X = {} for sd, SD in (("l", "L"), ("r", "R")): for a, b in (("sho", "shoulder"), ("elb", "elbow"), ("wri", "wrist"), ("hip", "hip"), ("knee", "knee"), ("ankle", "ankle")): X[b + "_" + SD] = J[a + "_" + sd] X["heel_" + SD] = J["ankle_" + sd] + _v((0, -J["ankle_y"], -.2 * J["foot_len"])) X["crown"] = _v((0, J["crown_y"], J["head_pivot"][2])) X["chin"] = _v((0, J["chin_y"], J["head_pivot"][2] + .35 * H)) X["hairline"] = _v((0, J["chin_y"] + (J["crown_y"] - J["chin_y"]) * .857, J["head_pivot"][2] + .3 * H)) self._joints = X self.params = dict(H=H, hand_L=J["hand_len"], foot_L=J["foot_len"], floor_y=0.0, fat=fat, muscle=muscle, fem=fem, child=child, heads_tall=J["crown_y"] / H)
def landmarks(self): out = super().landmarks() out.update(self._joints) return out
def build(sex="m", age="adult", fat=.35, muscle=.4, cloth=None, **kw): """critic9's builder protocol (bench/units/UNITS.md): -> Person with .params and the named landmarks""" return Person(sex=sex, age=age, fat=fat, muscle=muscle, cloth=cloth, **kw)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910"""pydraw.anatomy.render (wave 17, depict lane): every way of showing one sculpt, all from its G-buffer(pydraw.anatomy.core.trace). Rules only, numpy only.
shade(G, skin=None) the 3D look: five-term skin light (key with a warm shadow edge, sky fill, ground bounce, rim, fake subsurface), sclera never white, colour zones painted in face space lineart(G) silhouette + depth and normal creases + the part's named drawn lines (lid, lip, nostril, ear rim, knuckles), weight by kind, hidden where the surface covers them cel(G) anime: flat base, ONE hue-shifted shadow tone, the face shadow as a threshold in face space (not N.L blotches), a cast band under the fringe, coloured outline pixel(G, size) pixel art: reduce the hero G-buffer by majority material, 3 tones per material, redraw eyes / brows / nose shadow / mouth at the target size from projected landmarks and lines, clean orphan clusters, selective outline
Knobs (PYDRAW_EXP name=0 turns a rule off): askin (five-term skin light; off = plain lambert), azone (face colourzones), apore (skin detail normals), asclera (sclera tint), aface (face-space cel threshold; off = N.L), ahatch (line-art shadow hatching), avalley (line-art valley creases), asmooth (pixel tones from smoothed luminance), apxvalley (pixel seams between touching forms), afringe (fringe cast band), aredraw(pixel landmark redraw), aclean (pixel orphan cleanup), aoutline (pixel selective outline)."""import osimport numpy as npfrom .core import (F32, MAT, SKIN, LIP, SCLERA, IRIS, PUPIL, LID, NAIL, HAIR, BROW, TEETH, MOUTH, CLOTH, CLOTH2, SHOE, LASH, CORNEA, norm, lm_get)
def _knob(name, default="1"): ev = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv) return ev.get(name, default) != "0"
SKIN_TONES = { # sRGB 0..1 base skin (mid value); our own picks, light to deep "light": (.93, .76, .64), "medium": (.80, .58, .44), "tan": (.70, .48, .34), "deep": (.45, .29, .2),}MAT_RGB = { 0: (.9, .9, .9), SKIN: SKIN_TONES["light"], LIP: (.78, .45, .43), SCLERA: (.88, .83, .79), IRIS: (.36, .25, .14), PUPIL: (.05, .04, .04), LID: SKIN_TONES["light"], NAIL: (.93, .78, .74), HAIR: (.28, .18, .11), BROW: (.24, .16, .1), TEETH: (.9, .87, .8), MOUTH: (.42, .16, .15), CLOTH: (.32, .42, .6), CLOTH2: (.3, .3, .34), SHOE: (.25, .18, .13), LASH: (.12, .08, .07), CORNEA: (.9, .9, .9),}SKINLIKE = (SKIN, LID, LIP, NAIL)BG = np.array((.93, .92, .9), F32)
def _lin(c): return np.power(np.clip(c, 0, 1), 2.2)
def _srgb(c): return np.power(np.clip(c, 0, 1), 1 / 2.2)
def albedo(G, skin=None, zones=True): """per-pixel sRGB albedo: material table, then the part's own paint, then face-space zones""" S = G["size"] hit, mat = G["hit"], G["mat"] A = np.zeros((S, S, 3), F32) tbl = dict(MAT_RGB) if skin is not None: sk = SKIN_TONES.get(skin, skin) tbl[SKIN] = tbl[LID] = tuple(sk) tbl[LIP] = tuple(np.clip(np.array(sk) * (.86, .62, .66), 0, 1)) tbl[NAIL] = tuple(np.clip(np.array(sk) * 1.02 + (.02, .02, .03), 0, 1)) for m, c in (G.get("colors") or {}).items(): tbl[m] = tuple(c) # per-figure colours (the prompt's shirt / trousers / shoes / hair / skin) for m, c in tbl.items(): A[mat == m] = c idx = np.nonzero(hit) P, N, M = G["P"][idx].astype(float), G["N"][idx].astype(float), mat[idx] pa = G["part"].albedo(P, N, M) if pa is not None: ok = np.isfinite(pa).all(1) A[idx[0][ok], idx[1][ok]] = pa[ok] if zones and _knob("azone"): _face_zones(G, A, tbl[SKIN]) if _knob("asclera"): # rule: sclera never white - a warm grey that darkens toward the corners and under the lid (the lid's # shadow and the ball's curvature), never brighter than the lit skin s = (mat == SCLERA) & hit if s.any(): nz = np.clip(G["Nv"][..., 2], 0, 1) k = (.72 + .2 * nz[s])[:, None] A[s] = np.minimum(A[s], np.array(tbl[SKIN], F32) * 1.02 + .06) * k return A
def _face_zones(G, A, skin): """Gurney colour zones painted in face space: forehead golden, brow-to-nose-base red, nose-to-chin cool; warm blobs on the cheeks, the nose ball and the ears""" f = G["part"].face_frame() if f is None: return lm = G["part"].landmarks() s = G["hit"] & np.isin(G["mat"], (SKIN, LID)) if not s.any(): return P = G["P"][s].astype(float) o, H = np.asarray(f["origin"], float), float(f.get("scale", .23)) fy = (P - o) @ np.asarray(f["y"], float) / H b_, n_ = lm_get(lm, "brow_l"), lm_get(lm, "nose_base") brow = (b_ - o) @ np.asarray(f["y"], float) / H if b_ is not None else .07 nose = (n_ - o) @ np.asarray(f["y"], float) / H if n_ is not None else brow - .29 c = A[s] # rule (zones, not bands): wide smoothstep ramps (~.15 H) centred on the brow and nose-base lines, small amounts def sstep(x): x = np.clip(x, 0, 1) return x * x * (3 - 2 * x) top = sstep((fy - brow) / .3 + .5) low = sstep((nose - fy) / .3 + .5) mid = np.clip(1 - top - low, 0, 1) c = c + top[:, None] * np.array((.015, .01, -.015)) + mid[:, None] * np.array((.02, -.01, -.01)) \ + low[:, None] * np.array((-.015, -.003, .006)) # warm cheeks / nose / ears: broad Gaussian falloff (no disc edge, no ring) for keys, r, amt in ((("cheekbone_l",), .12, .035), (("cheekbone_r",), .12, .035), (("nose_tip",), .07, .035), (("ear_l", "ear_canal_l"), .09, .04), (("ear_r", "ear_canal_r"), .09, .04)): q = lm_get(lm, *keys) if q is None: continue d2 = (np.linalg.norm(P - q, axis=1) / (r * H)) ** 2 w = np.exp(-1.5 * d2) c = c + w[:, None] * np.array((.4, -.25, -.2)) * amt * 2 A[s] = np.clip(c, 0, 1)
def _pores(G, idx, Nv, sel): """detail normals only (never the silhouette): a fine value-noise bump on skin, ~1.5 mm cells at an adult scale, so lit skin is not plastic. Scale follows the face frame (H) when the part has one.""" from pydraw3d.sdf import noise3 f = G["part"].face_frame() H = float(f.get("scale", .23)) if f else .23 P = G["P"][idx][sel].astype(float) / (H * .008) e = .35 n0 = noise3(P) g = np.stack([noise3(P + d) - n0 for d in np.eye(3) * e], -1) / e g -= (g * Nv[sel]).sum(-1, keepdims=True) * Nv[sel] out = Nv.copy() nn = Nv[sel] - .035 * g out[sel] = nn / np.linalg.norm(nn, axis=1, keepdims=True) return out
def shade(G, skin=None, bg=BG): """the hero 3D look (sRGB float HxWx3 0..1)""" S = G["size"] hit, mat = G["hit"], G["mat"] A = albedo(G, skin) out = np.empty((S, S, 3), F32) out[:] = bg if not hit.any(): return out idx = np.nonzero(hit) Nv = G["Nv"][idx].astype(float) L = np.asarray(G["light"], float) sh = G["shadow"][idx].astype(float) ao = G["ao"][idx].astype(float) alb = _lin(A[idx]) M = mat[idx] skinlike = np.isin(M, SKINLIKE) if _knob("apore") and skinlike.any(): Nv = _pores(G, idx, Nv, skinlike) ndl = Nv @ L fres = np.clip(1 - Nv[:, 2], 0, 1) if _knob("askin"): # 1 key: wrapped diffuse whose wrap is widest in red (light scattered under the skin leaks past the # terminator), and a shadow whose penumbra goes warm (s, s^1.5, s^2) wrap = np.where(skinlike[:, None], np.array((.5, .22, .14)), np.array((.08, .08, .08))) key = np.clip((ndl[:, None] + wrap) / (1 + wrap), 0, 1) ** 1.6 shc = np.stack([sh ** .8, sh ** 1.6, sh ** 2.2], -1) shc = np.where(skinlike[:, None], shc, sh[:, None]) c_key = np.array((1.0, .9, .8)) * 1.95 * key * shc # 2 sky fill from above, by n.y, occluded sky = np.sqrt(np.clip(.5 + .5 * Nv[:, 1], 0, 1))[:, None] * np.array((.2, .25, .34)) * ao[:, None] # 3 ground / body bounce from below, warm bdir = norm((-L[0] * .5, -.75, .3)) bnc = np.clip(Nv @ bdir, 0, 1)[:, None] * np.array((.26, .18, .12)) * ao[:, None] # 4 rim from behind on the shadow side rdir = norm((-L[0] * 1.3 + .2, .25, -.55)) rim = (np.clip(Nv @ rdir, 0, 1) * fres ** 2)[:, None] * np.array((.5, .5, .55)) # 5 fake subsurface: a red fresnel glow, stronger where the key reaches sss = (fres ** 2 * (.25 + .75 * np.clip(ndl, 0, 1) * sh))[:, None] * np.array((.45, .1, .06)) sss = sss * skinlike[:, None] lit = alb * (c_key + sky + bnc) + alb * rim + alb ** .5 * sss * .6 else: lit = alb * (np.clip(ndl, 0, 1) * sh * 1.6 + .35)[:, None] # wet / glossy highlights: eyes (the catchlight toward the light) and a soft sheen on the lower lip hv = norm(L + np.array((0, 0, 1))) spec = np.clip(Nv @ hv, 0, 1) eye = np.isin(M, (SCLERA, IRIS, PUPIL, CORNEA)) lit += (eye * spec ** 120 * 2.5 * sh)[:, None] lit += ((M == LIP) * spec ** 24 * .18 * sh)[:, None] # skin: a faint broad sheen (forehead, nose bridge, cheekbone catch the key), never a plastic hot spot lit += ((np.isin(M, (SKIN, LID))) * spec ** 18 * .06 * sh)[:, None] * np.array((1, .95, .9)) lit += ((M == NAIL) * spec ** 40 * .3 * sh)[:, None] lit += ((M == HAIR) * spec ** 14 * .1 * sh)[:, None] * np.array((1, .9, .75)) # tone map: gentle shoulder # tone map on luminance, hue kept (a per-channel shoulder clips red first and drifts highlights to cream-yellow) lum = lit @ np.array((.2126, .7152, .0722)) lm2 = lum / (1 + .25 * lum) lit = lit * (lm2 / np.maximum(lum, 1e-6))[:, None] * 1.12 # bright light desaturates a little (film shoulder), so the lit top is a lighter skin, neither cream nor orange l2 = lit @ np.array((.2126, .7152, .0722)) k = np.clip((l2 - .45) * .5, 0, .2)[:, None] lit = lit + (l2[:, None] - lit) * k mx = lit.max(1, keepdims=True) lit = np.where(mx > 1, lit / np.maximum(mx, 1e-6), lit) # never clip a channel: scale the colour out[idx] = _srgb(lit) return out
# ------------------------------------------------------------------------------------------------ strokesdef _prof(t, taper): if taper == "ends": # the lip slit: darkest and widest at the corners (D7) return .55 + .65 * np.abs(2 * t - 1) if taper: return np.sin(np.pi * t) * .7 + .3 return 1.0
def stroke(img, pts, width, color, vis=None, taper=True, alpha=1.0): """anti-aliased polyline into img (HxWx3 float) - width in px; tapered ends read hand-drawn; segments whose ends are both hidden are skipped""" pts = np.asarray(pts, float) if len(pts) < 2: return n = len(pts) color = np.asarray(color, F32) H, W = img.shape[:2] for i in range(n - 1): if vis is not None and not (vis[i] or vis[i + 1]): continue a, b = pts[i], pts[i + 1] t0, t1 = i / (n - 1), (i + 1) / (n - 1) w0 = width * _prof(t0, taper) w1 = width * _prof(t1, taper) r = max(w0, w1) / 2 + 1.5 x0, x1 = int(max(0, np.floor(min(a[0], b[0]) - r))), int(min(W, np.ceil(max(a[0], b[0]) + r))) y0, y1 = int(max(0, np.floor(min(a[1], b[1]) - r))), int(min(H, np.ceil(max(a[1], b[1]) + r))) if x1 <= x0 or y1 <= y0: continue yy, xx = np.mgrid[y0:y1, x0:x1] + .5 ba = b - a L2 = max(ba @ ba, 1e-9) h = np.clip(((xx - a[0]) * ba[0] + (yy - a[1]) * ba[1]) / L2, 0, 1) d = np.hypot(xx - a[0] - h * ba[0], yy - a[1] - h * ba[1]) w = (w0 + (w1 - w0) * h) / 2 cov = np.clip(w + .5 - d, 0, 1) * alpha reg = img[y0:y1, x0:x1] reg[:] = reg * (1 - cov[..., None]) + color * cov[..., None]
LINE_W = dict(lid=1.0, lip=1.0, brow=.0, nostril=.8, ear=.7, crease=.6, knuckle=.6, nail=.3, contour=.9)
def edge_maps(G): """silhouette, depth-jump and normal-crease edge masks (float 0..1) from the G-buffer""" hit, depth, Nv, mat = G["hit"], G["depth"], G["Nv"], G["mat"] sc = G["view"].scale sil = np.zeros(hit.shape, F32) for dy, dx in ((0, 1), (1, 0), (0, -1), (-1, 0)): sil = np.maximum(sil, (hit & ~np.roll(np.roll(hit, dy, 0), dx, 1)).astype(F32)) dz = np.where(hit, depth, -1e3).astype(float) dep = np.zeros(hit.shape, F32) cre = np.zeros(hit.shape, F32) for dy, dx in ((0, 1), (1, 0)): z2 = np.roll(np.roll(dz, dy, 0), dx, 1) h2 = np.roll(np.roll(hit, dy, 0), dx, 1) both = hit & h2 jump = np.abs(dz - z2) * sc # px of depth per px step # rule: a nail plate's rim is not an overlap edge (thin raised plate -> a black blob at toe / finger size) m2 = np.roll(np.roll(mat, dy, 0), dx, 1) nailrim = (mat == NAIL) | (m2 == NAIL) # rule: a grazing surface changes depth fast without any overlap - the jump must beat what the normals on # both sides predict (slope = tan of the surface tilt, px of depth per px) sl = np.sqrt(Nv[..., 0] ** 2 + Nv[..., 1] ** 2) / np.maximum(np.abs(Nv[..., 2]), .12) sl2 = np.roll(np.roll(sl, dy, 0), dx, 1) pred = np.minimum(np.minimum(sl, sl2), 8.0) * 1.5 dep = np.maximum(dep, (both & (jump > 2.5 + pred) & ~nailrim).astype(F32)) n2 = np.roll(np.roll(Nv, dy, 0), dx, 1) cosang = (Nv * n2).sum(-1) cre = np.maximum(cre, np.clip((.82 - cosang) / .12, 0, 1) * both) return sil, dep, cre
# material pairs whose boundary an artist draws (hairline, lid on the eye, nail plate, cloth edge); skin-lip is left to# the lip line, iris/pupil are fills_DRAWN_PAIRS = {frozenset(p) for p in ((SKIN, HAIR), (LID, HAIR), (SKIN, SCLERA), (LID, SCLERA), (LID, IRIS), (SKIN, IRIS), (SKIN, CLOTH), (SKIN, CLOTH2), (CLOTH, CLOTH2), (SKIN, SHOE), (CLOTH, SHOE), (CLOTH2, SHOE), (SKIN, BROW), (HAIR, CLOTH), (SCLERA, IRIS))}
def valley_lines(G): """the creases where two forms press together (fingers side by side, the thumb web, toes, a lip corner): the surface's depth is CONCAVE across them - the centre lies behind both sides. Our rule: second difference of the view depth over 2-4 px in four directions, kept where it exceeds ~1.5 px of depth and is the local maximum (thin line).""" from scipy.ndimage import maximum_filter hit = G["hit"] z = np.where(hit, G["depth"] * G["view"].scale, np.nan).astype(np.float64) S = G["size"] out = np.zeros(z.shape) for k in (2, 3, 4): k = max(1, int(round(k * S / 384))) for dy, dx in ((0, k), (k, 0), (k, k), (k, -k)): a = np.roll(np.roll(z, dy, 0), dx, 1) b = np.roll(np.roll(z, -dy, 0), -dx, 1) out = np.fmax(out, (a + b - 2 * z) / (k / 2)) out = np.nan_to_num(out) * hit thin = out >= maximum_filter(out, size=3) * .75 v = np.clip((out - .8) / 1.0, 0, 1) * thin f = G["part"].face_frame() if f is not None: # rule (D6): no valley lines on the front of the face - the nose and lips get their named lines only Hs = float(f.get("scale", .23)) w_ = ((G["P"].astype(float) - np.asarray(f["origin"], float)) @ np.asarray(f["z"], float)) / Hs v = v * ~(np.isin(G["mat"], (SKIN, LID, LIP, MOUTH, TEETH)) & (w_ > .15)) return v
def mat_edges(G): hit, mat = G["hit"], G["mat"] e = np.zeros(hit.shape, F32) for dy, dx in ((0, 1), (1, 0)): m2 = np.roll(np.roll(mat, dy, 0), dx, 1) h2 = np.roll(np.roll(hit, dy, 0), dx, 1) diff = hit & h2 & (mat != m2) if not diff.any(): continue ys, xs = np.nonzero(diff) ok = np.array([frozenset((int(a), int(b))) in _DRAWN_PAIRS for a, b in zip(mat[ys, xs], m2[ys, xs])], bool) e[ys[ok], xs[ok]] = 1 return e
def lineart(G, ink=(.1, .08, .08), paper=(.98, .97, .94), base=None): """line drawing: silhouette heavier, depth jumps medium, creases light, plus the named lines""" S = G["size"] img = np.empty((S, S, 3), F32) img[:] = paper if base is None else base sil, dep, cre = edge_maps(G) w = 1.0 * S / 512 # rule: line weight by role - outer contour heaviest, overlaps (depth jumps) medium, form creases light from scipy.ndimage import grey_dilation, gaussian_filter sil2 = grey_dilation(sil, size=(max(2, int(round(2.4 * w))),) * 2) mb = mat_edges(G) val = valley_lines(G) if _knob("avalley") else np.zeros_like(sil) m = np.maximum.reduce([sil2 * 1.0, dep * .9, cre * .55, mb * .8, val]) m = np.clip(gaussian_filter(m, .5), 0, 1) if _knob("ahatch") and G["hit"].any(): # rule: the shadow side gets one set of parallel hatch lines (45 deg, from the light), denser in the core # shadow and cast shadows; never on the lit side, never past the contour L = np.asarray(G["light"], float) ndl = (G["Nv"] * L).sum(-1) dark = np.clip((-.05 - ndl) / .3, 0, 1) * G["hit"] # core shadow only, no half-tones dark = np.maximum(dark, np.clip((.4 - G["shadow"]) * 2.5, 0, 1) * G["hit"]) f = G["part"].face_frame() if f is not None: # rule: no hatching on the front of the face (it reads as an engraving filter); sides and neck keep it Hs = float(f.get("scale", .23)) w_ = ((G["P"].astype(float) - np.asarray(f["origin"], float)) @ np.asarray(f["z"], float)) / Hs dark = dark * ~(np.isin(G["mat"], (SKIN, LID, LIP)) & (w_ > .2)) dark = gaussian_filter(dark.astype(F32), 1.5 * w) yy, xx = np.mgrid[0:S, 0:S].astype(F32) per = 7 * w ph = np.abs(((xx + yy) / per) % 1 - .5) * per # px from the nearest hatch line width = .35 + .9 * dark hatch = np.clip(width - ph + .5, 0, 1) * (dark > .12) * .55 img = img * (1 - hatch[..., None]) + np.asarray(ink, F32) * hatch[..., None] img = img * (1 - m[..., None]) + np.asarray(ink, F32) * m[..., None] for name, L, xy, vis in G["lines2d"]: wt = LINE_W.get(L.kind, .7) * L.weight * 1.6 * w if wt <= 0: continue stroke(img, xy, wt, ink, vis, taper="ends" if L.kind == "lip" else True) for name, L, xy, vis in G["lines2d"]: if L.kind == "brow": # brows as a few tapered hatch strokes along the curve, not one outline stroke(img, xy, 3.2 * w * L.weight, ink, vis, alpha=.85) return img.astype(F32)
# ------------------------------------------------------------------------------------------------ anime celdef _hue_shadow(c): """one shadow tone per colour: darker, warmer-purple, a little more saturated (never grey)""" c = np.asarray(c, F32) return np.clip(c * np.array((.78, .64, .72), F32) + np.array((.02, 0, .03), F32), 0, 1)
def cel(G, skin=None, bg=BG): S = G["size"] hit, mat = G["hit"], G["mat"] A = albedo(G, skin, zones=False) # cel: flat base colours, no painted zones out = np.empty((S, S, 3), F32) out[:] = bg if not hit.any(): return out L = np.asarray(G["light"], float) Nv = G["Nv"].astype(float) ndl = (Nv * L).sum(-1) # rule: one shadow tone on the side planes (a cel artist shades the turning planes, not only the back) shadow = (ndl < .22) | (G["shadow"] < .45) f = G["part"].face_frame() if f is not None and _knob("aface"): # rule: the face shadow is a threshold in face space (no N.L blotches): light angle around the face's up axis # decides how far the shadow comes in from the far edge; sockets, the underside of the nose and lower lip # and under the chin are always shadow R = G["view"].R fx, fy, fz = (np.asarray(f[k], float) @ R.T for k in ("x", "y", "z")) # face axes in view space lh = L - fy * (L @ fy) th = np.arctan2(lh @ fx, lh @ fz) # + = light from the face's +x side H = float(f.get("scale", .23)) o = np.asarray(f["origin"], float) face = hit & np.isin(mat, (SKIN, LID, LIP)) P = G["P"].astype(float) u = ((P - o) @ np.asarray(f["x"], float)) / H # -0.3..0.3 across the face v = ((P - o) @ np.asarray(f["y"], float)) / H # -0.5 chin .. 0.5 crown w = ((P - o) @ np.asarray(f["z"], float)) / H away = -np.sign(th) * u # + on the side away from the light reach = .32 - .3 * np.clip(abs(th) / (np.pi / 2), 0, 1) ** .8 # shadow comes in from the far edge # rule: on the nose band the shadow hugs the nose side plane (the boundary bends toward the midline) lm = G["part"].landmarks() b_, n_ = lm_get(lm, "brow_l"), lm_get(lm, "nose_base") vb = ((b_ - o) @ np.asarray(f["y"], float)) / H if b_ is not None else .07 vn = ((n_ - o) @ np.asarray(f["y"], float)) / H if n_ is not None else -.21 band = np.clip(1 - np.abs(v - (vb + vn) / 2) / ((vb - vn) / 2 + 1e-6), 0, 1) thr = reach - .1 * band * (abs(th) > .25) fs = face & (away > thr) & (w > -.2) # rule: the nose casts its own shape onto the far cheek - inside the nose band, close to the midline, on the # side away from the light, the turning planes of the nose go to shadow nr = lm_get(lm, "nose_root") if lm_get(lm, "nose_root") is not None else b_ if n_ is not None and nr is not None and abs(th) > .15: vr = ((nr - o) @ np.asarray(f["y"], float)) / H nb_ = (v < vr + .02) & (v > vn - .01) & (away > -.01) & (away < .1) & (w > .25) fs |= face & nb_ & (ndl < .35) side = face & (w <= -.2) & (ndl < .05) # under the nose and under the lower lip / chin: a fixed under-plane threshold (light is from above) under = face & (Nv[..., 1] < -.75) shadow = np.where(face, fs | side | under | (G["shadow"] < .3), shadow) if _knob("afringe"): hair = hit & (mat == HAIR) if hair.any(): # rule: the fringe casts a band on the forehead below it (shift the hair mask down a few px) k = max(2, S // 80) cast = np.zeros_like(hair) for i in range(1, k + 1): cast[i:] |= hair[:-i] shadow |= cast & hit & np.isin(mat, (SKIN, LID)) # rule: cel shadow shapes are designed, not noisy - drop specks and fill pinholes (a median over ~1% of the frame) from scipy.ndimage import median_filter k = max(3, (S // 100) | 1) shadow = median_filter(shadow.astype(np.uint8), size=k).astype(bool) & hit # ... and no islands: shadow (or light) pieces smaller than ~0.15% of the figure merge into their surroundings from scipy.ndimage import label amin = max(12, int(hit.sum() * .005)) for val in (True, False): lab, nl = label((shadow == val) & hit) if nl: sizes = np.bincount(lab.ravel()) small = (sizes < amin) small[0] = False shadow[small[lab]] = not val base = A sh = _hue_shadow(base) col = np.where(shadow[..., None], sh, base) # hair: one highlight band (the anime "angel ring") where the hair faces up-and-toward the light, never in shadow hairm = hit & (mat == HAIR) & ~shadow if hairm.any(): band = hairm & (np.abs(Nv[..., 1] - .5) < .1) & (ndl > .35) col = np.where(band[..., None], np.clip(base * 1.25 + .06, 0, 1), col) # eyes: dark pupil + iris keep, plus one highlight dot toward the light out[hit] = col[hit] hv = norm(L + np.array((0, 0, 1))) spec = (Nv * hv).sum(-1) eye = hit & np.isin(mat, (IRIS, PUPIL, SCLERA, CORNEA)) & (spec > .985) out[eye] = (1, 1, 1) # coloured outline: silhouette and depth jumps in a dark version of the local colour, plus the named lines sil, dep, cre = edge_maps(G) from scipy.ndimage import grey_dilation line = np.maximum(grey_dilation(sil, size=(2, 2)), dep) dark = np.clip(_hue_shadow(_hue_shadow(base)) * .7, 0, 1) lc = np.where(hit[..., None], dark, np.array((.15, .1, .1), F32)) # silhouette pixels on the background take the adjacent fill's dark colour lcf = grey_dilation(lc, size=(3, 3, 1)) lc = np.where(hit[..., None], lc, lcf) out = out * (1 - line[..., None]) + lc * line[..., None] w = S / 512 for name, Lr, xy, vis in G["lines2d"]: if Lr.kind in ("lid", "lip", "brow", "nostril"): wt = {"lid": 2.4, "lip": 1.3, "brow": 2.6, "nostril": 1.1}[Lr.kind] * w stroke(out, xy, wt, (.18, .1, .1) if Lr.kind != "brow" else (.3, .2, .15), vis, taper="ends" if Lr.kind == "lip" else True) return out.astype(F32)
# ------------------------------------------------------------------------------------------------ pixel artdef _hsv(c): import colorsys return np.array(colorsys.rgb_to_hsv(*np.clip(c, 0, 1)))
def _rgb(h): import colorsys return np.array(colorsys.hsv_to_rgb(h[0] % 1, np.clip(h[1], 0, 1), np.clip(h[2], 0, 1)))
def _ramp(cols, n=3, mat=None): """n tones of one material, SYNTHESISED like a pixel artist builds a ramp (not sampled from the render, whose shadows mix in the blue sky fill and go grey): levels evenly spaced in luminance between the material's dark and light ends; each level = the lit colour moved in HSV - value to the level, darker tones shift hue (skin toward red, other materials toward blue-violet) and gain saturation, the top tone shifts a little toward yellow but keeps its saturation (never cream).""" W = np.array((.3, .59, .11)) lum = cols @ W lo, hi = np.quantile(lum, .06), np.quantile(lum, .94) top = cols[lum >= np.quantile(lum, .7)].mean(0) h, sat, v = _hsv(top) skinlike = mat in SKINLIKE target = 0.0 if skinlike else 250 / 360 out = [] for i, l in enumerate(np.linspace(lo, hi, n)): t = 1 - i / max(n - 1, 1) # 1 = darkest, 0 = lightest d = ((target - h + .5) % 1) - .5 # signed hue distance to the shadow target hh = h + np.clip(d, -1, 1) * (.06 if skinlike else .05) * t / max(abs(d), 1e-6) * min(abs(d), .1) / .1 if t == 0: hh = h + (((60 / 360 - h + .5) % 1) - .5) * .06 ss = sat * (1 + (.35 if skinlike else .2) * t) c = _rgb((hh, ss, v)) c = c * (l / max(c @ W, 1e-6)) # set the tone's luminance out.append(np.clip(c, 0, 1)) return np.array(out)
def pixel(G, size, shaded=None, skin=None, bg=BG, tones=None): """pixel art at `size` x `size` from the hero G-buffer (uint8 HxWx3). Steps: majority material per cell, per-material tone ramp, landmark redraw of the face features, orphan cleanup, selective outline.""" S = G["size"] f = S // size if tones is None: tones = 4 if size >= 48 else 3 # rule: light / mid / shadow + a core-shadow tone from 48 px, 3 below assert f * size == S, "size must divide the G-buffer size" img = shade(G, skin, bg) if shaded is None else shaded mat = np.where(G["hit"], G["mat"].astype(np.int32), -1) # 1 reduce: majority material per cell (background counts), mean colour of that material in the cell mc = mat.reshape(size, f, size, f).transpose(0, 2, 1, 3).reshape(size, size, f * f) ic = img.reshape(size, f, size, f, 3).transpose(0, 2, 1, 3, 4).reshape(size, size, f * f, 3) ids = np.unique(mat) cnt = np.stack([(mc == m).sum(-1) for m in ids], -1) win = ids[cnt.argmax(-1)] # rule: a part covering at least 40% of a cell wins over the background (thin fingers / limbs keep their pixels) fg_cnt = (mc >= 0).sum(-1) if (ids >= 0).any(): fg_ids = ids[ids >= 0] fcnt = np.stack([(mc == m).sum(-1) for m in fg_ids], -1) fwin = fg_ids[fcnt.argmax(-1)] # ... unless the cell is a GAP: a full background column (or row) with figure on both sides of it (between the # legs, between an arm and the body) - gaps keep the silhouette readable fgc = (mc >= 0).reshape(size, size, f, f) colbg = ~fgc.any(2) # (size, size, f): column j all background rowbg = ~fgc.any(3) idx = np.arange(f)
def gap(bgline, fgany): left = (fgany & (idx < f // 2)).any(-1) right = (fgany & (idx >= f // 2)).any(-1) mid = bgline[..., f // 4: f - f // 4].any(-1) return mid & left & right isgap = gap(colbg, fgc.any(2)) | gap(rowbg, fgc.any(3)) win = np.where((win < 0) & (fg_cnt >= .4 * f * f) & ~isgap, fwin, win) # ambiguous cells (25-75% figure) follow their neighbours, so a thin limb or a gap is a clean run of pixels, # never a checkerboard from scipy.ndimage import uniform_filter amb = (fg_cnt >= .25 * f * f) & (fg_cnt <= .75 * f * f) fgm = (win >= 0).astype(float) nb = uniform_filter(fgm, 3, mode="constant") * 9 - fgm # figure neighbours out of 8 win = np.where(amb & (win < 0) & (nb >= 5), fwin, win) win = np.where(amb & (win >= 0) & (nb <= 2), -1, win) sel = mc == win[..., None] col = (ic * sel[..., None]).sum(2) / np.maximum(sel.sum(-1), 1)[..., None] out = np.empty((size, size, 3), F32) out[:] = bg fg = win >= 0 # 2 tones: each material snaps to its own small ramp (luminance nearest) for m in np.unique(win[fg]): s = win == m cs = col[s] n = tones if s.sum() >= 6 else 1 rp = _ramp(cs, n, int(m)) if n > 1 else cs.mean(0, keepdims=True) lum = cs @ np.array((.3, .59, .11)) if _knob("asmooth") and n > 1: # rule: tone bands follow the big form, not every bump - pick the tone from the luminance smoothed inside # the material (normalised Gaussian, ~0.7 px at the target size) from scipy.ndimage import gaussian_filter full = np.zeros((size, size)) full[s] = lum wgt = gaussian_filter(s.astype(float), .7) lum = (gaussian_filter(full, .7) / np.maximum(wgt, 1e-6))[s] rl = rp @ np.array((.3, .59, .11)) out[s] = rp[np.abs(lum[:, None] - rl[None]).argmin(1)] out[~fg] = bg keep = np.zeros((size, size), bool) # rule: below ~24 px of head the sclera / iris pixels are noise - fill them with the surrounding skin (a touch # darker: the socket) and let the redraw place the eye by rule hp = _head_px(G, f) if _knob("aredraw") and hp is not None and hp < 26: eyec = np.isin(win, (SCLERA, IRIS, PUPIL, CORNEA, LASH)) if eyec.any(): sk = np.isin(win, (SKIN, LID)) base = out[sk].mean(0) if sk.any() else np.array(MAT_RGB[SKIN], F32) out[eyec] = base * .9 win = np.where(eyec, SKIN, win) if _knob("aredraw") and hp is not None and 26 <= hp < 64: # rule: the iris is redrawn by rule under 64 px of head - its downsampled cells (grey-green bleed) go to sclera ic = np.isin(win, (IRIS, PUPIL, CORNEA)) if ic.any(): scl = win == SCLERA out[ic] = out[scl].mean(0) if scl.any() else out[ic].mean(0) * 1.4 win = np.where(ic, SCLERA, win) if _knob("aredraw") and hp is not None and hp < 48: # rule: below ~48 px of head the lip masses are noise that reads as an open mouth - they become the local # skin and the mouth is redrawn as a slit from the lip line mm = np.isin(win, (LIP, MOUTH, TEETH)) if mm.any(): from scipy.ndimage import uniform_filter sk = np.isin(win, (SKIN, LID)).astype(float) num = np.stack([uniform_filter(out[..., i] * sk, 5, mode="constant") for i in range(3)], -1) den = uniform_filter(sk, 5, mode="constant")[..., None] loc = np.where(den > 1e-6, num / np.maximum(den, 1e-6), out) out[mm] = loc[mm] win = np.where(mm, SKIN, win) _flat_muzzle(G, out, win, f) # 3 cluster cleanup: orphan pixels take the majority of their 8 neighbours (inside the same material only) if _knob("aclean"): out = _orphans(out, win, keep) # 4 redraw features at the target size from projected landmarks / lines if _knob("aredraw"): _redraw(G, out, keep, win, size, f, skin) # 4b valley creases (where two forms press together: the legs, an arm against the body) as a 1 px darker seam, # so touching legs stay two legs at sprite size (critic9 11:39 D-gap) if _knob("apxvalley") and size <= 128: vl = valley_lines(G).reshape(size, f, size, f).max((1, 3)) seam = (vl > .5) & (win >= 0) & ~keep & ~np.isin(win, (SCLERA, IRIS, PUPIL, LID, LIP, MOUTH, BROW)) seam &= np.isin(win, (CLOTH, CLOTH2, SHOE)) # never on skin (the face would blotch) if seam.any(): out[seam] = _hue_shadow(out[seam]) * .8 # 5 selective outline: the outer ring of the figure in a darker hue of its own fill, lighter on the lit side if _knob("aoutline"): _sel_outline(G, out, win, keep, size, bg) return (np.clip(out, 0, 1) * 255 + .5).astype(np.uint8)
def _head_px(G, f): lm = G["lm2d"] cr = lm.get("crown") or lm.get("crown_L") ch = lm.get("chin") return None if cr is None or ch is None else abs(cr[1] - ch[1]) / f
def _flat_muzzle(G, out, win, f): """rule (small heads): the muzzle between the nose base and the chin is one or two flat skin tones - the sculpt's small shadow pockets there read as a hole at this size; the slit and the nose shadow are redrawn on top""" lm = G["lm2d"] get = lambda *ns: next((lm[n] for n in ns if n in lm), None) ml, mr, nb, ch = get("mouth_L", "mouth_l"), get("mouth_R", "mouth_r"), get("nose_base"), get("chin_front", "chin") if ml is None or mr is None or nb is None or ch is None: return x0 = int(np.floor(min(ml[0], mr[0]) / f)) - 1 x1 = int(np.floor(max(ml[0], mr[0]) / f)) + 1 y0 = int(np.floor(nb[1] / f)) + 1 y1 = int(np.floor((ml[1] + ch[1]) / 2 / f)) H, W = win.shape x0, x1, y0, y1 = max(0, x0), min(W - 1, x1), max(0, y0), min(H - 1, y1) if x1 < x0 or y1 < y0: return box = (slice(y0, y1 + 1), slice(x0, x1 + 1)) sk = np.isin(win[box], (SKIN, LID)) if sk.sum() < 3: return reg = out[box] cols = reg[sk] lum = cols @ np.array((.3, .59, .11)) lit = cols[lum >= np.median(lum)].mean(0) shd = cols[lum < np.median(lum)].mean(0) if (lum < np.median(lum)).any() else lit # two tones: lit and shadow side split by the median, so a turned head keeps its shadow side reg[sk] = np.where((lum >= np.median(lum) - 1e-6)[:, None], lit, shd) out[box] = reg
def _orphans(out, win, keep): H, W = win.shape o = out.copy() key = (np.round(out * 255).astype(np.int64) * np.array((65536, 256, 1))).sum(-1) for y in range(H): for x in range(W): if win[y, x] < 0 or keep[y, x]: continue c = key[y, x] nb4 = [key[yy, xx] for yy, xx in ((y - 1, x), (y + 1, x), (y, x - 1), (y, x + 1)) if 0 <= yy < H and 0 <= xx < W] if c in nb4: continue blk, pos = [], [] for yy in range(max(0, y - 1), min(H, y + 2)): for xx in range(max(0, x - 1), min(W, x + 2)): if (yy, xx) != (y, x) and win[yy, xx] == win[y, x]: blk.append(key[yy, xx]) pos.append((yy, xx)) if len(blk) < 4: continue v, cnt = np.unique(blk, return_counts=True) if cnt.max() >= 3: yy, xx = pos[blk.index(v[cnt.argmax()])] o[y, x] = out[yy, xx] return o
def _put(out, keep, x, y, c, rel=None): H, W = keep.shape xi, yi = int(np.floor(x)), int(np.floor(y)) if 0 <= xi < W and 0 <= yi < H: if rel is not None and keep[yi, xi]: return # rel: the mark is at least this much darker than what it is drawn on (a slit stays a slit in shadow too) out[yi, xi] = c if rel is None else np.minimum(c, _hue_shadow(out[yi, xi]) * rel) keep[yi, xi] = True
def _line_px(out, keep, xy, c, vis=None, win=None, rel=None): """1 px line through projected points (DDA), only on the figure and where visible""" for i in range(len(xy) - 1): if vis is not None and not (vis[i] and vis[i + 1]): continue a, b = xy[i], xy[i + 1] n = int(max(abs(b[0] - a[0]), abs(b[1] - a[1]), 1) * 2) + 1 for t in np.linspace(0, 1, n): x, y = a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t xi, yi = int(np.floor(x)), int(np.floor(y)) if win is not None and not (0 <= yi < win.shape[0] and 0 <= xi < win.shape[1] and win[yi, xi] >= 0): continue _put(out, keep, x, y, c, rel)
def _redraw(G, out, keep, win, size, f, skin): """rule: features are placed by rule at the target size, never left to survive downsampling by luck""" lm = G["lm2d"] sc = 1.0 / f skin_c = np.array(MAT_RGB[SKIN] if skin is None else SKIN_TONES.get(skin, skin), F32) if (G.get("colors") or {}).get(SKIN) is not None: skin_c = np.array(G["colors"][SKIN], F32) head_px = None def g2(*names): for n in names: for k in (n, n[:-2] + n[-2:].upper()): if k in lm: return lm[k] return None cr, ch = g2("crown"), g2("chin") if cr is not None and ch is not None: head_px = abs(cr[1] - ch[1]) * sc dark = np.clip(skin_c * np.array((.5, .38, .38)), 0, 1) eye_c = np.array((.16, .1, .09), F32) lid_rows = {} bx = [xy[:, 0].mean() * sc for name, L, xy, vis in G["lines2d"] if L.kind == "brow" and L.redraw] brow_mid = float(np.mean(bx)) if len(bx) >= 2 else None ey_ = [e for e in (g2("pupil_l", "eye_l"), g2("pupil_r", "eye_r")) if e is not None] eye_row = float(np.mean([e[1] for e in ey_])) * sc if ey_ else None for name, L, xy, vis in G["lines2d"]: if not L.redraw: continue p = xy * sc if L.kind == "brow": if head_px is not None and head_px < 14: continue q, qv = p, vis if head_px is not None and head_px < 48 and brow_mid is not None: # rule (no unibrow): at small sizes a brow is its outer part only, and keeps >= 1 px clear of the # midline between the brows (the glabella stays skin) inner_first = abs(p[0][0] - brow_mid) < abs(p[-1][0] - brow_mid) k = int(round(len(p) * .3)) q = p[k:] if inner_first else p[:len(p) - k] qv = None if vis is None else (vis[k:] if inner_first else vis[:len(vis) - k]) ok = np.abs(np.floor(q[:, 0]) + .5 - brow_mid) >= 1.5 q, qv = q[ok], (None if qv is None else qv[ok]) if len(q) < 2: continue bc = np.array(MAT_RGB[BROW], F32) * .8 if head_px is not None and head_px < 28: # rule: a small brow is one row tall and a dark SKIN tone (the eyes stay the darkest marks) q = q.copy() q[:, 1] = np.floor(np.median(q[:, 1])) + .5 bc = np.clip(skin_c * np.array((.58, .45, .42)), 0, 1) if head_px is not None and head_px < 48 and eye_row is not None: # rule: one skin row between brow and eye at small sizes (else brow + eye fuse into a dark block) q = q.copy() top = np.floor(eye_row) - (1 if head_px >= 24 else 0) # the eye's top row q[:, 1] += min(0.0, (top - 2) - np.floor(q[:, 1].max())) _line_px(out, keep, q, bc, qv, win) elif L.kind == "lip": if head_px is not None and head_px < 8: continue mc = np.clip(np.array(MAT_RGB[LIP], F32) * .55, 0, 1) # rule: the mouth at small size is a short line, narrower than the eyes' span q = p if head_px is None or head_px >= 20 else p[len(p) // 5: len(p) - len(p) // 5] if head_px is not None and head_px < 48: # a closed neutral mouth = ONE dark slit row (corners may drop a row at >= 24 px), then at most one # lighter lip row under its middle; never dark around red q = q.copy() row = np.floor(np.median(q[:, 1])) q[:, 1] = row + .5 mc = np.clip(skin_c * np.array((.55, .38, .38)), 0, 1) # ONE colour for the whole slit: darker than the darkest pixel it crosses (no dark + red pairs) ys_ = np.clip(np.floor(q[:, 1]).astype(int), 0, out.shape[0] - 1) xs_ = np.clip(np.floor(q[:, 0]).astype(int), 0, out.shape[1] - 1) under = out[ys_, xs_] dk = under[np.argmin(under @ np.array((.3, .59, .11)))] mc = np.minimum(mc, _hue_shadow(dk) * .72) _line_px(out, keep, q, mc, vis, win) if head_px >= 24 and len(q) >= 4: m4 = q[len(q) // 4: len(q) - len(q) // 4].copy() m4[:, 1] += 1 lc = np.clip(np.array(MAT_RGB[LIP], F32) * .5 + skin_c * .45, 0, 1) _line_px(out, keep, m4, lc, None, win) continue _line_px(out, keep, q, mc, vis, win) elif L.kind == "nostril": if head_px is not None and head_px < 14: continue # nose shadow: one pixel under the nose on the shadow side if vis is not None and vis.any(): j = len(p) // 2 _put(out, keep, p[j][0], p[j][1], dark) elif L.kind == "lid": # rule: a lid line needs ~3 px of eye; below that the eye is one dark pixel and a lid line only adds a bar if head_px is not None and head_px < 40: continue _line_px(out, keep, p, eye_c, vis, win) if vis is None or vis.any(): for (xx, yy) in p[vis] if vis is not None else p: c_ = int(np.floor(xx)) lid_rows[c_] = min(lid_rows.get(c_, 1e9), int(np.floor(yy))) # eyes: from the eye landmarks (pupil centre), symmetric columns when the view is frontal # the pupil landmark (front of the eye) if the part gives one, else the eye landmark eyes = [(k, e) for k, e in (("l", g2("pupil_l", "eye_l")), ("r", g2("pupil_r", "eye_r"))) if e is not None and e[2]] if len(eyes) == 2 and abs(G["view"].yaw) < 5: (_, a), (_, b) = eyes cx = (a[0] + b[0]) / 2 * sc dx = abs(a[0] - b[0]) / 2 * sc dxi = max(1, int(round(dx))) cxi = int(np.floor(cx)) ey = (a[1] + b[1]) / 2 * sc pos = [(cxi + dxi + .5 if (2 * dxi) % 2 == 0 else cx + dx, ey), (cxi - dxi + .5, ey)] pos = [(cx + dx, ey), (cx - dx, ey)] # rule (pixel eyes): mirror columns exactly about the face centre column xr = int(np.floor(cx + dx)) xl = int(np.floor(2 * cx - (cx + dx))) pos = [(xr + .5, ey), (xl + .5, ey)] else: pos = [(e[0] * sc, e[1] * sc) for _, e in eyes] if head_px is not None and head_px < 6: pos = [] # rule: a head under 6 px shows no eyes (hair mass + face tone only) elif head_px is not None and head_px < 14: # rule (tiny heads): eyes are one pixel, a shade of the skin not black, and two eyes that would touch become # the near eye only (in a turned head the far eye hides behind the nose at this size) eye_c = np.clip(skin_c * np.array((.45, .36, .36)), 0, 1) if len(pos) == 2 and abs(int(np.floor(pos[0][0])) - int(np.floor(pos[1][0]))) < 2: yaw = G["view"].yaw pos = [max(pos, key=lambda q: q[0]) if yaw >= 0 else min(pos, key=lambda q: q[0])] for x, y in pos: lr = [lid_rows[c] for c in (int(np.floor(x)) - 1, int(np.floor(x)), int(np.floor(x)) + 1) if c in lid_rows] if lr and head_px is not None and head_px < 64: # rule: under ~64 px of head the iris hangs from the lid line (one pixel below it), never crossed by it _put(out, keep, x, min(lr) + 1.5, eye_c) continue if head_px is not None and head_px >= 24: # 2 px tall iris with a light catch pixel on the light side _put(out, keep, x, y, eye_c) _put(out, keep, x, y - 1, eye_c) _put(out, keep, x - 1 if G["light"][0] < 0 else x + 1, y - 1, np.array((.92, .9, .88), F32)) else: _put(out, keep, x, y, eye_c)
def _sel_outline(G, out, win, keep, size, bg=BG): fg = win >= 0 edge = np.zeros_like(fg) for dy, dx in ((0, 1), (1, 0), (0, -1), (-1, 0)): sh = np.zeros_like(fg) ys = slice(max(dy, 0), size + min(dy, 0)) yd = slice(max(-dy, 0), size + min(-dy, 0)) xs = slice(max(dx, 0), size + min(dx, 0)) xd = slice(max(-dx, 0), size + min(-dx, 0)) sh[yd, xd] = fg[ys, xs] edge |= fg & ~sh if edge.sum() == 0: return L = np.asarray(G["light"], float) yy, xx = np.nonzero(edge) # the outward direction of each edge pixel = toward its background neighbours; lit when it faces the key ox = np.zeros(len(yy)) oy = np.zeros(len(yy)) for dy, dx in ((0, 1), (1, 0), (0, -1), (-1, 0)): y2, x2 = np.clip(yy + dy, 0, size - 1), np.clip(xx + dx, 0, size - 1) out_ = ~fg[y2, x2] | (yy + dy < 0) | (yy + dy >= size) | (xx + dx < 0) | (xx + dx >= size) ox += dx * out_ oy += dy * out_ lit = (ox * L[0] - oy * L[1]) > .3 for y, x, l in zip(yy, xx, lit): if keep[y, x]: continue if l: # rule (D10): no outline on the lit side - unless the fill and the background are too close to read # (light skin on a light ground), then a soft mid tone only c0 = out[y, x] if abs(float(c0 @ np.array((.3, .59, .11))) - float(np.asarray(bg) @ np.array((.3, .59, .11)))) < .1: out[y, x] = _hue_shadow(c0) * .95 + .02 continue out[y, x] = _hue_shadow(out[y, x]) * .6123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397"""pydraw.anatomy.torso (wave 17, body lane): the torso as ONE SDF sculpt built from construction rules.
Rules: docs/research17/units/torso_limbs.md (cited R<n>, mistakes checklist ck<n>). Built on pydraw.anatomy.core(depict's API: Sculpt / Part, metres, +x = the subject's LEFT, +y up, +z forward).
rib cage an EGG (R2, ck7): an ellipsoid whose top is tapered to ~.72 so it is widest a third up from its bottom, the front plane flattened, the thoracic arch shown as a line from the sternum tip. waist the mobile middle mass (R1) narrower than the egg and the pelvis: the pinch sits ABOVE the navel on a woman, at / just below it on a man (ck8); the rectus slab with the front thirds pit / epigastric pit / navel / pubis (R3, ck17) and the flank buttress overhanging the crest (R4). pelvis a rounded box pitched forward (R6, ck10), wider on a woman (R7, ck9), with the trochanters as the widest point of the hips (R18) and the glutes cut square at the fold (R25). girdle clavicle S from the pit to the acromion (R9), the trapezius as a round cone from the back of the neck to the acromion (a 15-25 deg slope, R10, ck5), the scapula slab and the erector pair with the spine furrow (R5), pectoral plate and the two armpit walls (R12, ck4): the front (pec) wall longer, the rear (lat) wall thicker and lower. The deltoid caps the ARM (limbs.py) and hangs from the acromion landmark given here. breasts (female) a mass on the pec, aimed ~30 deg outward, dropped by gravity, blended on the top only so the underside keeps its fold (R8, ck18). fat one scalar 0..1: site-weighted inflation (abdomen, buttocks, breasts, flanks) and softer blends; never a uniform scale (R27, ck21). muscle: one scalar 0..1: the named muscle masses grow and the blends get crisper.
Construction is in head heights H in the CHEST frame (origin = the rig's neck base, the centre of the neck where itmeets the trunk) and the HIP frame (origin = the midpoint of the hip joints). Numbers marked (est) are my estimatesinside the research's ranges; everything else is quoted in the research file. Pure numpy, rules only.Knob: PYDRAW_EXP btorso=0 makes torso() return the plain wave-16-like egg + box (no landmarks) for A/B."""import osimport numpy as npfrom .core import (Sculpt, Part, Line, ellipsoid, rbox, capsule, round_cone, sphere, smin, smax, _v, SKIN)
def knob(name, default="1"): ev = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv) return ev.get(name, default) != "0"
class PadSculpt(Sculpt): """core.Sculpt with padded bounds: the ellipsoid SDF is an approximation that can read LESS than the distance to its bounding sphere far from a long thin ellipsoid; skipping it there made thin ring seams (critic9 r1, B19). Padding the bound (x1.3 + k) keeps the skip exact where it matters."""
def add(self, fn, k=0.0, mat=SKIN, bound=None): if bound is not None: bound = (bound[0], float(bound[1]) * 1.3 + 2 * float(k)) return super().add(fn, k, mat, bound)
def carve(self, fn, k=0.0, mat=None, bound=None): if bound is not None: bound = (bound[0], float(bound[1]) * 1.3 + 2 * float(k)) return super().carve(fn, k, mat, bound)
def smoothstep(e0, e1, x): t = np.clip((x - e0) / (e1 - e0), 0, 1) return t * t * (3 - 2 * t)
def lerp(a, b, t): return a + (b - a) * t
def rot_x(deg): """rows = local axes: the local +y tips toward +z by deg (a pelvis pitched forward)""" a = np.radians(deg) return np.array([[1, 0, 0], [0, np.cos(a), np.sin(a)], [0, -np.sin(a), np.cos(a)]])
def rot_z(deg): """rows = local axes: the local +y tips toward +x by deg""" a = np.radians(deg) return np.array([[np.cos(a), -np.sin(a), 0], [np.sin(a), np.cos(a), 0], [0, 0, 1]])
def rot_y(deg): """rows = local axes: the local +z turns toward +x by deg""" a = np.radians(deg) return np.array([[np.cos(a), 0, -np.sin(a)], [0, 1, 0], [np.sin(a), 0, np.cos(a)]])
def axes_from(y, z_hint): """rows = local x, y, z with local y along `y` and local z as close to z_hint as possible""" y = _v(y) / (np.linalg.norm(y) + 1e-12) z = _v(z_hint) - y * float(np.dot(z_hint, y)) z = z / (np.linalg.norm(z) + 1e-12) x = np.cross(y, z) return np.stack([x, y, z])
class Frame: """a construction frame: origin o (metres), R rows = local axes in world, H = head height in metres. w(x, y, z) maps a point given in head heights in this frame to world metres; s(v) scales a length."""
def __init__(self, o, R, H): self.o, self.R, self.H = _v(o), np.asarray(R, float), float(H)
def w(self, *x): return self.o + (_v(x) * self.H) @ self.R
def s(self, v): return v * self.H
def Rw(self, Rl): """a rotation given in this frame (rows = axes in frame coordinates) -> rows in world""" return np.asarray(Rl, float) @ self.R
def egg(p, c, r, R, top, taper=.28, taper_z=.12, y0=-.2): """an ellipsoid tapered toward its local +y end: x scaled by 1 - taper*t, z by 1 - taper_z*t, t rising from y0 (in radii, below the centre) to the top. The egg is widest below its centre (R2: a third up from the bottom).""" q = (p - c) @ R.T t = smoothstep(y0 * r[1], r[1], q[:, 1]) sx = 1 - taper * t sz = 1 - taper_z * t q2 = np.stack([q[:, 0] / sx, q[:, 1], q[:, 2] / sz], -1) k0 = np.sqrt(((q2 / r) ** 2).sum(-1)) k1 = np.sqrt(((q2 / (r * r)) ** 2).sum(-1)) return k0 * (k0 - 1) / np.maximum(k1, 1e-9) * (1 - taper * .5)
def smin_top(a, b, k, y, y0, y1): """smooth-min whose blend fades out below y0 (none) to full above y1: a mass melts in on its top edge only and keeps a crisp fold underneath (breast, glute)""" kk = k * (.35 + .65 * smoothstep(y0, y1, y)) h = np.clip(.5 + .5 * (b - a) / np.maximum(kk, 1e-9), 0, 1) out = b + (a - b) * h - kk * h * (1 - h) return np.where(kk > 1e-7, out, np.minimum(a, b))
# ------------------------------------------------------------------------------------------------ construction table# head heights, by type; (est) = my estimate inside the research ranges. Lerped by fem (0..1) and child (0..1).# rib_c/rib_r the egg (R2): male cage ~1.3 H wide, ~.95 H deep; the female cage thinner (R7 Robo Bean)# waist half width at the pinch (param table: male "a little over 1 H", female 1 H) and its height (ck8)# pel half width of the pelvis box (Medlej 1.5-2 head widths), troch = outer trochanter half width# (female widest 2 H at the hips, Loomis), crest = iliac crest top above the hip joints (R7: female# crest at the navel, male "two or three inches" lower)# navel below the neck base; the front thirds pit / epigastric / navel / pubis are equal (R3)TYPES = { "m": dict(rib_c=(0, -.76, -.05), rib_r=(.64, .70, .47), waist=.535, waist_y=-1.78, waist_d=.40, pel=.60, pel_d=.42, troch=.75, crest=.45, pel_pitch=10, navel=-1.70, sh=.78, pec=1.0, breast=0.0, glute=(.30, -.05, .34, .40), glute_fold=-.42, belly=.0, trap=1.0, neck_r=.25), "f": dict(rib_c=(0, -.76, -.05), rib_r=(.56, .66, .43), waist=.465, waist_y=-1.55, waist_d=.36, pel=.68, pel_d=.45, troch=.74, crest=.58, pel_pitch=13, navel=-1.70, sh=.66, pec=.55, breast=1.0, glute=(.33, -.13, .36, .43), glute_fold=-.52, belly=.0, trap=.8, neck_r=.205), # a child of ~6-8 (canon "child" row, 6 H tall): cage and pelvis about as wide as each other, a belly, no pinch, # no muscle definition (figures.md rule 4: "quite chubby"; R29 ladder) "c": dict(rib_c=(0, -.66, -.03), rib_r=(.48, .58, .40), waist=.46, waist_y=-1.40, waist_d=.38, pel=.48, pel_d=.38, troch=.55, crest=.40, pel_pitch=12, navel=-1.45, sh=.56, pec=.0, breast=0.0, glute=(.24, -.05, .26, .30), glute_fold=-.36, belly=.15, trap=.6, neck_r=.19),}
def table(fem=0.0, child=0.0): a, b, c = TYPES["m"], TYPES["f"], TYPES["c"] out = {} for k in a: va = np.asarray(a[k], float) v = va + (np.asarray(b[k], float) - va) * fem v = v + (np.asarray(c[k], float) - v) * child out[k] = v if v.ndim else float(v) return out
# ------------------------------------------------------------------------------------------------ the torso partclass Torso(Part): """the torso sculpt. J = skeleton dict in metres (see person.skeleton): neck_base, hipc, sho_l/sho_r, hip_l/hip_r, Rc (chest rows), Rp (pelvis rows), H. fem, child in 0..1; fat, muscle in 0..1 (.35 / .4 = average).""" name = "torso"
def __init__(self, J, fem=0.0, child=0.0, fat=.35, muscle=.4): super().__init__() self.S = PadSculpt() H = J["H"] T = table(fem, child) self.T, self.J = T, J C = Frame(J["neck_base"], J["Rc"], H) # chest frame Pf = Frame(J["hipc"], J["Rp"], H) # hip frame (pelvis) self.C, self.Pf = C, Pf S = self.S fa = fat - .35 # fat relative to average (R27: offsets by site) mu = (muscle - .4) * (1 - child) # muscle relative to average; children carry no definition soft = 1 + max(fa, 0) * 1.5 + child * .6 # fat and youth soften the blends (R27: dips fill) crisp = 1 - max(mu, 0) * .5 kU = .16 * H * soft * crisp # k_unit (param table .1-.15 H; soft tissue at the top of the range+) kJ = .045 * H * soft * crisp # k_joint (.03-.05 H) self.kU, self.kJ = kU, kJ L = self._lm
def site(w): # fat inflation at a site, in head heights (R27 weights) return max(fa, -.2) * w * .16
# ---- rib cage egg (R2): widest a third up from its bottom, top tapered, front flattened rc, rr = _v(T["rib_c"]), _v(T["rib_r"]) rr = rr + _v((site(.25), 0, site(.3))) c_rib = C.w(*rc) R_rib = C.Rw(rot_x(-6)) # the cage's top plane tilts forward (R2): its axis leans back a little r_rib = rr * H front_z = rc[2] + rr[2] * .80 nf = C.Rw(np.eye(3))[2]
def rib(p, c=c_rib, r=r_rib, R=R_rib, fz=C.w(0, 0, front_z), n=nf): d = egg(p, c, r, R, top=True) return smax(d, (p - fz) @ n, .18 * H) # the flat front plane (R2) S.add(rib, mat=SKIN, bound=(c_rib, float(r_rib.max()) * 1.05)) rib_bot = rc[1] - rr[1] L["rib_bottom"] = C.w(0, rib_bot + .05, rc[2] + rr[2] * .5) L["rib_widest_l"] = C.w(rr[0], rib_bot + 2 * rr[1] / 3, rc[2]) L["pit"] = C.w(0, -.10, T["neck_r"] * 1.25) L["nape"] = C.w(0, .08, -T["neck_r"] * 1.2) L["sternum_tip"] = (L["pit"] + C.w(0, rib_bot, rc[2] + rr[2] * .8)) / 2 L["sternum_tip"] = C.w(0, (-.10 + rib_bot) / 2, front_z + .02)
# ---- the waist: the mobile middle mass (R1) as an elliptic column, narrowest at waist_y (ck8) wy, ww, wd = T["waist_y"], T["waist"] + site(.9), T["waist_d"] + site(1.0) hip_y_c = float(((J["hipc"] - J["neck_base"]) @ J["Rc"].T)[1] / H) # hip joints in the chest frame crest_y = hip_y_c + T["crest"] top_y, bot_y = rib_bot + .30, crest_y - .15 c_w = C.w(0, (top_y + bot_y) / 2, -.02) r_w = _v((ww, (top_y - bot_y) / 2 + .18, wd)) * H S.add(lambda p, c=c_w, r=r_w, R=C.R: ellipsoid(p, c, r, R), k=kU, bound=(c_w, float(r_w.max()))) # the lower belly: the rectus "bullet" whose round end sits in the pelvis (R3, Hampton); fat goes here first # fat spreads the belly wide and low first (a broad apron, not a ball in front: R27) bel = .30 + T["belly"] * .35 + site(1.0) * .7 c_b = C.w(0, lerp(wy, crest_y, .75) - .05 - site(1.0) * .5, wd * .35 + T["belly"] * .18 + site(1.0) * .25) r_b = _v((.40 + site(1.0) * 1.2, .34 + T["belly"] * .1 + site(1.0) * .9, bel)) * H S.add(lambda p, c=c_b, r=r_b, R=C.R: ellipsoid(p, c, r, R), k=kU * .8, bound=(c_b, float(r_b.max()))) # the flank buttress (obliques) overhanging the iliac crest (R4) for sx in (1, -1): c_f = C.w(sx * (ww - .10 + site(.4)), crest_y + .10, -.05) r_f = _v((.14 + site(.8), .22, .25 + site(.4))) * H S.add(lambda p, c=c_f, r=r_f, R=C.R: ellipsoid(p, c, r, R), k=kU * .7, bound=(c_f, float(r_f.max())))
# ---- pelvis (R6, R7): a forward-pitched rounded box, the trochanters the widest point of the hips (R18) pw, pd = T["pel"], T["pel_d"] c_p = Pf.w(0, T["crest"] - .40, -.12) R_p = Pf.Rw(rot_x(T["pel_pitch"])) h_p = _v((pw, .40, pd * .86)) * H S.add(lambda p, c=c_p, h=h_p, R=R_p: rbox(p, c, h, .32 * H, R), k=kU, bound=(c_p, float(np.linalg.norm(h_p)))) for sx in (1, -1): # the hip mass: gluteus medius (a wedge with its apex at the head of the femur, R25) over the trochanter, # ONE long mass from the crest down into the outer thigh so the hip line runs waist -> crest -> the # trochanters (the widest point, R18) -> the thigh without a separate knob c_t = Pf.w(sx * (T["troch"] - .24 + site(.5)), .0, -.05) r_t = _v((lerp(.21, .18, fem) + site(.8), .50 * (1 - .35 * child), .27)) * H R_t = Pf.Rw(rot_z(-sx * 8)) S.add(lambda p, c=c_t, r=r_t, R=R_t: ellipsoid(p, c, r, R), k=kU * 1.1, bound=(c_t, float(r_t.max()))) # the glutes: ellipsoids flattened below at the fold for the "rather square crease" (R25, Loomis) gx, gy, grx, gry = T["glute"] for sx in (1, -1): # a flattened mass (not a ball): wide, tall, shallow, set high on the pelvis back (critic9 r1) c_gl = Pf.w(sx * gx * .92, gy + .08, -pd * .66 - site(.6) * .3) r_gl = _v((grx + .05 + site(.6), gry + .08 + site(.5), .18 + site(1.0) + .02 * fem)) * H fold = Pf.w(0, T["glute_fold"], 0) ny = Pf.R[1]
def glute(p, c=c_gl, r=r_gl, R=Pf.R, f=fold, n=ny): return smax(ellipsoid(p, c, r, R), (f - p) @ n, .04 * H) S.add(glute, k=kU, bound=(c_gl, float(r_gl.max()))) L["glute_fold_l"] = Pf.w(gx, T["glute_fold"], -pd) # pubic mound c_pm = Pf.w(0, -.14, pd * (.55 - .12 * fem)) r_pm = _v((.18 + .04 * fem, .13, .11 - .02 * fem)) * H S.add(lambda p, c=c_pm, r=r_pm, R=C.R: ellipsoid(p, c, r, R), k=kU * .6, bound=(c_pm, float(r_pm.max()))) L["asis_l"] = Pf.w(pw - .12, T["crest"] - .12, pd * .65) L["asis_r"] = Pf.w(-(pw - .12), T["crest"] - .12, pd * .65) L["crest_l"] = Pf.w(pw, T["crest"], -.05) L["troch_l"] = Pf.w(T["troch"], -.02, -.02) L["troch_r"] = Pf.w(-T["troch"], -.02, -.02) L["pubis"] = Pf.w(0, -.22, pd * .7)
# ---- the back (R5): erector pair ("two corn dogs") making the spine furrow, scapula slabs, upper trapezius for sx in (1, -1): a, b = C.w(sx * .12, -.9, rc[2] - rr[2] * .70), C.w(sx * .12, hip_y_c + .25, -pd * .80) S.add(lambda p, a=a, b=b: round_cone(p, a, b, .075 * H, .095 * H), k=kU * .9, bound=((a + b) / 2, float(np.linalg.norm(b - a)) / 2 + .12 * H)) c_s = C.w(sx * .40, -.55, rc[2] - rr[2] + .14) R_s = C.Rw(rot_y(-sx * 25) @ np.eye(3)) r_s = _v((.25, .31, .16)) * H S.add(lambda p, c=c_s, r=r_s, R=R_s: ellipsoid(p, c, r, R), k=kU, bound=(c_s, float(r_s.max()))) a, b = C.w(0, -.1, rc[2] - rr[2] - .02), C.w(0, hip_y_c + .4, -pd - .02) S.carve(lambda p, a=a, b=b: capsule(p, a, b, .035 * H), k=.05 * H, bound=((a + b) / 2, float(np.linalg.norm(b - a)) / 2 + .1 * H))
# ---- shoulder girdle (R9-R12) sh = T["sh"] nr = T["neck_r"] tr = T["trap"] * (1 + mu * .6) for sx, sd in ((1, "l"), (-1, "r")): sho = J["sho_" + sd] sho_c = (sho - J["neck_base"]) @ J["Rc"].T / H # the shoulder joint in the chest frame acr = C.w(sx * (abs(sho_c[0]) - .04), sho_c[1] + .07, sho_c[2] + .0) L["acromion_" + sd] = acr # clavicle: an S of two capsules from the pit to the acromion, bowed forward at its inner half (R9) c0 = C.w(sx * .10, -.10, nr * 1.15) c1 = C.w(sx * .42, -.06, nr * 1.1) c2 = acr + C.R[2] * .02 * H + C.R[1] * .0 for a, b in ((c0, c1), (c1, c2)): S.add(lambda p, a=a, b=b, r=lerp(.034, .026, fem) * H: capsule(p, a, b, r), k=kJ * 2.0, bound=((a + b) / 2, float(np.linalg.norm(b - a)) / 2 + .1 * H)) L["clav_" + sd] = c0 # trapezius: a round cone from the back of the neck down to the acromion: the slope (R10, ck5) # the shoulder platform the neck rises from (R10): fills the top of the cage between the neck and the # acromion, under the trapezius and behind the clavicle c_pl = C.w(sx * .40, -.24, -.06) r_pl = _v((.36, .20, .32)) * H S.add(lambda p, c=c_pl, r=r_pl, R=C.R: ellipsoid(p, c, r, R), k=kU, bound=(c_pl, float(r_pl.max()))) t0 = C.w(sx * .08, .10, -nr * .55) t1 = acr - C.R[2] * .05 * H - C.R[1] * .02 * H S.add(lambda p, a=t0, b=t1, r0=.19 * H * tr, r1=.10 * H: round_cone(p, a, b, r0, r1), k=kU, bound=((t0 + t1) / 2, float(np.linalg.norm(t1 - t0)) / 2 + .2 * H)) # the trapezius' lower diamond over the scapulae # pectoral plate (male; thinner on a woman, under the breast), from the sternum to the arm (R8, R12) pecm = T["pec"] * (1 + mu * 1.2) c_pe = C.w(sx * .31, -.44, front_z - .10) R_pe = C.Rw(rot_z(sx * 14)) r_pe = _v((.36, .22, (.10 + .04 * pecm) * (1 - .6 * child))) * H S.add(lambda p, c=c_pe, r=r_pe, R=R_pe: ellipsoid(p, c, r, R), k=kJ * 1.2, bound=(c_pe, float(r_pe.max()))) # armpit walls (R12): the front wall from the pec's lower edge to the arm, longer (attaches further down); # the rear (lat) wall deeper, thicker, rounder, starting lower on the torso (ck4) arm_f = sho + C.R[1] * (-.40 * H) + C.R[2] * (.05 * H) - C.R[0] * (sx * .06 * H) a = C.w(sx * .42, -.62, front_z - .14) S.add(lambda p, a=a, b=arm_f: round_cone(p, a, b, lerp(.12, .07, child) * H, lerp(.10, .07, child) * H), k=kJ * (1 + child), bound=((a + arm_f) / 2, float(np.linalg.norm(arm_f - a)) / 2 + .15 * H)) arm_b = sho + C.R[1] * (-.36 * H) + C.R[2] * (-.12 * H) - C.R[0] * (sx * .05 * H) a = C.w(sx * (rr[0] - .20), rib_bot + .36, rc[2] - .12) S.add(lambda p, a=a, b=arm_b: round_cone(p, a, b, .12 * H, .12 * H), k=kU * .8, bound=((a + arm_b) / 2, float(np.linalg.norm(arm_b - a)) / 2 + .18 * H)) L["armpit_f_" + sd] = arm_f L["armpit_b_" + sd] = arm_b L["pec_low_" + sd] = C.w(sx * .30, -.68, front_z + .02) # breasts (R8): on the pec, aimed outward, dropped by gravity, blended on the top only (ck18) if T["breast"] > .01: bs = T["breast"] rb = (.18 + site(.8) * .8) * H * bs sag = .12 + max(fa, 0) * .2 # a teardrop: the upper pole slopes from the chest, the lower pole full; aimed ~38 deg outward (Proko ~45 across the round cage) R_br = C.Rw(rot_x(-18) @ rot_y(sx * 38)) c_br = C.w(sx * .29, -.78 - sag * .5, front_z - .04) + R_br[2] * rb * .45 r_br = _v((1.0, 1.12, .76)) * rb self._breasts = getattr(self, "_breasts", []) + [(c_br, r_br, R_br)] L["nipple_" + sd] = c_br + R_br[2] * r_br[2] - C.R[1] * rb * .15 else: L["nipple_" + sd] = C.w(sx * .48, -.62, front_z + .02) # the neck stump the head lane's neck sits on (only up to the pit level; the neck itself is the head lane's) a, b = C.w(0, -.3, -.02), C.w(0, .25, .04) S.add(lambda p, a=a, b=b, r=nr * H: round_cone(p, a, b, r * 1.05, r), k=kU, bound=((a + b) / 2, .6 * H)) # navel (R3): carved at the second third of pit -> pubis pit_y = -.10 pub_y = float(((L["pubis"] - J["neck_base"]) @ J["Rc"].T)[1] / H) third = (pit_y - pub_y) / 3 L["epigastric"] = C.w(0, pit_y - third, front_z) nav_y = pit_y - 2 * third nz = float(((c_b - J["neck_base"]) @ J["Rc"].T)[2] / H) + r_b[2] / H L["navel"] = C.w(0, nav_y, nz) c_n = C.w(0, nav_y, nz + .0) S.carve(lambda p, c=c_n: ellipsoid(p, c, _v((.035, .05, .06)) * H), k=.03 * H, bound=(c_n, .15 * H)) # fat roll at the flanks (R27: abdomen and flanks thicken first; knees / ankles are the limbs' business) # ---- breasts last, blended on the top edge only self._bk = kU * 1.5 self.fem, self.child, self.fat, self.muscle = fem, child, fat, muscle self._lines_build()
def eval(self, p, want_mat=False): r = self.S.eval(p, want_mat) if not getattr(self, "_breasts", None): return r d, m = (r if want_mat else (r, None)) yax = self.C.R[1] for c, rr, R in self._breasts: lb = np.sqrt(((p - c) ** 2).sum(-1)) - rr.max() need = lb < d + self._bk if not need.any(): continue e = lb.copy() e[need] = ellipsoid(p[need], c, rr, R) y = (p - c) @ yax d = smin_top(e, d, self._bk, y, -rr[1] * .5, rr[1] * .5) return (d, m) if want_mat else d
def _lines_build(self): """drawn lines (R3, R12, R25): the central groove, the pec's lower edge, the rib arch from the sternum tip, the gluteal folds and the inguinal lines (ASIS -> pubis)""" L = self._lm C = self.C T = self.T self._lines["linea_alba"] = Line([L["sternum_tip"], L["epigastric"], L["navel"]], "crease", .6) rb = float(((L["rib_bottom"] - self.J["neck_base"]) @ self.J["Rc"].T)[1] / self.J["H"]) fz = T["rib_c"][2] + T["rib_r"][2] * .8 for sx, sd in ((1, "l"), (-1, "r")): self._lines["rib_arch_" + sd] = Line([L["sternum_tip"], C.w(sx * .25, rb + .12, fz - .02), C.w(sx * .45, rb + .02, fz - .15)], "crease", .7) self._lines["inguinal_" + sd] = Line([L["asis_" + sd], (L["asis_" + sd] + L["pubis"]) / 2 + C.R[1] * -.05 * C.H, L["pubis"]], "crease", .8) if self.T["breast"] < .01: self._lines["pec_" + sd] = Line([C.w(sx * .08, -.62, fz + .02), L["pec_low_" + sd], L["armpit_f_" + sd]], "crease", .8)
def bounds(self): lo, hi = self.S.bounds() return lo - .01, hi + .01
def torso(J, fem=0.0, child=0.0, fat=.35, muscle=.4): return Torso(J, fem, child, fat, muscle)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243"""pydraw.figure: people drawn 2D-first from a style canon (wave 18). Pure code, CPU only, no models / images.
Pipeline (the artist's order, WAVE18.md): Person + Pose (layout.Person / layout.Pose, from the prompt + seed) -> layout.build(person, pose, style, size, framing) named 2D landmarks + face / neck / torso / ear shapes -> hairlayout.build(layout) parting, cap, bangs, side locks, back mass, tips, flow -> value.plan(style, person, seed) value bands + material colours + designed shadow tones -> style module render(fig, size, seed, trace) -> HxWx3 uint8
STYLE MODULE CONTRACT (style_anime.py, style_ink.py, style_paint.py, style_pixel.py, each owned by its lane): def render(fig, size, seed, trace): # fig = Figure below; return an HxWx3 uint8 array (any H = W) optional: def work_size(size, framing): # the size the layout is built at (pixel: e.g. 64); the result is # upscaled to `size` (nearest for pixel, Lanczos otherwise) optional: KNOB = "fig2d_px" # PYDRAW_EXP <KNOB>=0 sends that style back to the old path Missing module / no render -> figure.flat.render (the kit's demo drawer).
fig.text, fig.style ('anime'|'ink'|'paint'|'pixel'), fig.variant (the matched style word, e.g. 'watercolor', 'pencil', 'manga'), fig.person, fig.pose, fig.layout (L), fig.hair (HL), fig.plan (V), fig.canon (= L.canon), fig.framing, fig.seed, fig.rebuild(size=..., style=...) -> a new Figure for the same person and pose
plot() wiring: pydraw.plot calls figure.try_portrait(text, scene, seed, size, style, trace) first when the knobfig2d is on (PYDRAW_EXP fig2d=1; default OFF this wave). It returns None (old path) unless the prompt asks for aportrait of one person: portrait / close-up / headshot / head-and-shoulders / bust / half-body words + one person."""import osimport reimport numpy as np
STYLES = ("anime", "ink", "paint", "pixel")
# style words -> (style, variant). Longest phrase wins. Parser styles (scene['style'] / scene['art']) map below.STYLE_WORDS = { "anime": "anime", "manga": "anime", "cel shaded": "anime", "cel-shaded": "anime", "cel": "anime", "cartoon": "anime", "comic": "anime", "comic book": "anime", "toon": "anime", "chibi": "anime", "pen and ink": "ink", "ink": "ink", "pencil": "ink", "graphite": "ink", "charcoal": "ink", "engraving": "ink", "etching": "ink", "sketch": "ink", "line drawing": "ink", "drawing": "ink", "crosshatch": "ink", "cross-hatched": "ink", "woodcut": "ink", "pen": "ink", "painted": "paint", "painting": "paint", "oil": "paint", "oil painting": "paint", "watercolor": "paint", "watercolour": "paint", "gouache": "paint", "acrylic": "paint", "realistic": "paint", "realistic portrait": "paint", "impressionist": "paint", "pastel": "paint", "pixel": "pixel", "pixel art": "pixel", "8-bit": "pixel", "16-bit": "pixel", "sprite": "pixel", "retro": "pixel",}PARSER_STYLE = {"comic": "anime", "sketch": "ink", "oil": "paint", "watercolor": "paint", "pixel": "pixel", "pastel": "paint", "ink": "ink", "pencil": "ink", "charcoal": "ink", "anime": "anime", "painting": "paint", "gouache": "paint"}
PORTRAIT_WORDS = ("portrait", "close-up", "closeup", "close up", "headshot", "head shot", "head-and-shoulders", "head and shoulders", "bust", "half-body", "half body", "upper body", "waist-up", "waist up", "half-length", "selfie", "mugshot", "profile picture", "avatar")PERSON_WORDS = ("man", "woman", "girl", "boy", "person", "lady", "child", "kid", "baby", "teenager", "teen", "guy", "gentleman", "grandmother", "grandfather", "grandma", "grandpa", "mother", "father", "king", "queen", "prince", "princess", "warrior", "knight", "wizard", "witch", "soldier", "nurse", "doctor", "farmer", "student", "elder", "toddler", "infant", "people", "character", "self", "someone", "monk", "nun", "pirate", "sailor", "chef", "student", "scientist", "artist", "musician", "dancer", "athlete")NOT_PERSON = ("dog", "cat", "horse", "bird", "lion", "tiger", "fox", "wolf", "bear", "rabbit", "owl", "robot", "alien", "skull", "statue", "car", "house", "building", "landscape", "flower", "tree")
def knob(name, default="1"): for kv in os.environ.get("PYDRAW_EXP", "").split(","): if "=" in kv: k, v = kv.split("=", 1) if k.strip() == name: return v.strip() return default
def _norm(text): return " " + " ".join(re.findall(r"[a-z0-9/\-]+", text.lower())) + " "
def style_for(text, scene=None, style_arg=None): """(style, variant) for a prompt: the longest style phrase in the text, else the parser's style, else pixel (pixel art stays the default output)""" t = _norm(text) best = None for w in sorted(STYLE_WORDS, key=len, reverse=True): if (" " + w + " ") in t: best = (STYLE_WORDS[w], w) break if best: return best if scene is not None: for k in ("art", "style"): v = scene.get(k) if v in PARSER_STYLE: return PARSER_STYLE[v], v if style_arg in PARSER_STYLE: return PARSER_STYLE[style_arg], style_arg return "pixel", "pixel"
def portrait_framing(text, scene=None): """the framing ('closeup', 'portrait', 'bust', 'half') when the prompt asks for a portrait of ONE person, else None. One person = a person word, no plural / count, no animal or object subject named as the subject.""" t = _norm(text) if not any((" " + w + " ") in t for w in PORTRAIT_WORDS): return None if not any(re.search(r"\b" + w + r"\b", t) for w in PERSON_WORDS): # "a portrait in oil" with no person word: still a person if the parser found one if not (scene and any(e.get("concept") == "person" for e in scene.get("entities", []))): return None if any(re.search(r"\b" + w + r"s?\b", t) for w in NOT_PERSON): return None t = re.sub(r"three[ -]quarters?|3/4", " ", t) if re.search(r"\b(two|three|four|five|couple|group|family|crowd|pair|people|men|women|children|kids|friends)\b", t): return None from .layout import framing_from_text return framing_from_text(text)
class Figure: def __init__(self, text, style, variant, person, pose, layout, hair, plan, framing, seed): self.text, self.style, self.variant = text, style, variant self.person, self.pose, self.layout, self.hair, self.plan = person, pose, layout, hair, plan self.canon, self.framing, self.seed = layout.canon, framing, seed
def rebuild(self, size=None, style=None): return build_figure(self.text, style or self.style, size or self.layout.size, self.seed, framing=self.framing, person=self.person, pose=self.pose, variant=self.variant)
def __repr__(self): return "Figure(%s/%s, %r, %r, %s, %dpx)" % (self.style, self.variant, self.person, self.pose, self.framing, self.layout.size)
def build_figure(text, style="pixel", size=512, seed=0, framing=None, person=None, pose=None, variant=None, scene=None): """person + pose + layout + hair layout + value plan for one prompt""" from .layout import Person, Pose, build as build_layout, framing_from_text from .hairlayout import build as build_hair from .value import plan as value_plan person = person or Person.from_text(text, seed, scene) pose = pose or Pose.from_text(text, seed) framing = framing or framing_from_text(text) L = build_layout(person, pose, style, size, framing, seed) HL = build_hair(L, style, seed) V = value_plan(style, person, seed) return Figure(text, style, variant or style, person, pose, L, HL, V, framing, seed)
def style_module(style): import importlib try: mod = importlib.import_module("pydraw.figure.style_" + style) except ImportError: return None return mod if hasattr(mod, "render") else None
def render_figure(text, style="pixel", size=512, seed=0, framing=None, variant=None, scene=None, trace=None, allow_flat=True): """draw one portrait figure: returns (HxWx3 uint8 at size x size, Figure) or (None, None)""" from . import flat from .kit import resize_to trace = [] if trace is None else trace mod = style_module(style) kn = getattr(mod, "KNOB", None) if mod is not None else None if mod is not None and kn and knob(kn) == "0": mod = None if mod is None and not allow_flat: return None, None ws = size if mod is not None and hasattr(mod, "work_size"): ws = int(mod.work_size(size, framing or "portrait")) fig = build_figure(text, style, ws, seed, framing=framing, variant=variant, scene=scene) if mod is not None: img = mod.render(fig, ws, seed, trace) trace.append("figure: %s drew %r" % (style, fig)) else: img = flat.render(fig, ws, seed, trace) trace.append("figure: flat demo drew %r (no style module for %s)" % (fig, style)) img = np.asarray(img) if img.dtype != np.uint8: img = (np.clip(img, 0, 1) * 255 + .5).astype(np.uint8) if img.max() <= 1.0 else np.clip(img, 0, 255).astype(np.uint8) if img.shape[0] != size: img = resize_to(img[..., :3], size, nearest=(style == "pixel")) return img[..., :3], fig
def try_portrait(text, scene, seed, size, style_arg, trace): """the plot() hook (knob fig2d, default OFF): a pydraw Image for a one-person portrait prompt, else None""" if knob("fig2d", "0") == "0": return None framing = portrait_framing(text, scene) if framing is None: return None style, variant = style_for(text, scene, style_arg) if knob("fig2d_" + style, "1") == "0": return None img, fig = render_figure(text, style, size, seed, framing, variant, scene, trace, allow_flat=knob("fig2d_flat", "1") != "0") if img is None: return None from ..canvas import Image trace.append("fig2d: portrait path (%s, %s, framing %s)" % (style, variant, framing)) return Image(img.astype(np.float64).tolist(), scene, trace)
def fig_masks(fig, aa=True): """coverage masks (HxW float32, 0..1) of the figure's regions at the layout size, computed once: face, neck, torso, chest_skin, ear_L, ear_R, hair_back (behind the head), hair_front (cap + front locks + bangs), hair (union), bangs, beard, eye_L, eye_R, figure (union of everything). Front hair already excludes nothing: z order is the style's job; these are the raw shapes.""" from . import kit as K L, HL = fig.layout, fig.hair S = L.size M = {} sm = lambda P: K.shape_mask(P, S, S, aa) M["face"] = sm(L.face) M["neck"] = sm(L.neck) M["torso"] = sm(K.crv(L.torso, closed=True, n=8, sharp=L.torso_sharp)) M["chest_skin"] = sm(K.crv(L.chest_skin, closed=True, n=6)) * M["torso"] for s, e in L.ears.items(): M["ear_" + s] = sm(K.crv(e["outline"])) if e["visible"] else np.zeros((S, S), np.float32) for s, e in L.eyes.items(): M["eye_" + s] = sm(K.crv(e["outline"], n=6)) z = np.zeros((S, S), np.float32) back, front, bangs = z.copy(), z.copy(), z.copy() if HL.back is not None: back = sm(HL.back) if HL.bun is not None: (back if HL.bun["z"] < 0 else front)[:] = np.maximum(back if HL.bun["z"] < 0 else front, sm(HL.bun["outline"])) if HL.cap is not None: front = np.maximum(front, sm(HL.cap)) for lk in HL.locks: m = sm(lk.poly()) if lk.z < -1: back = np.maximum(back, m) else: front = np.maximum(front, m) if lk.group == "bang": bangs = np.maximum(bangs, m) M["hair_back"], M["hair_front"], M["bangs"] = back, front, bangs M["hair"] = np.maximum(back, front) M["beard"] = sm(K.crv(L.beard["outline"])) if L.beard is not None else z.copy() fig_ = np.zeros((S, S), np.float32) for s, a in fig.layout.arms.items(): M["arm_" + s] = sm(K.crv(a["outline"], closed=True, n=6, sharp=a["sharp"])) for k in ["face", "neck", "torso", "ear_L", "ear_R", "hair"] + ["arm_" + s for s in fig.layout.arms]: fig_ = np.maximum(fig_, M[k]) M["figure"] = fig_ return M123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202"""figure.canon: per-style proportion canons WITH RANGES (wave 18, kit lane; rule C4 "style canon before geometry").
Every value is (lo, hi) in head units H = crown to chin (hair excluded), vertical positions measured DOWN from thecrown (0) to the chin (1), widths as fractions of H. A per-character seed picks a point inside each range(resolve()), so two people of one style never share a face. Sources, abbreviated in the comments: RULES docs/research18/copy_rules.md (A*, I*, P-R*, X*, C*) H17 docs/research17/units/head2_structure.md (N*, S*, A*) HD pydraw/anatomy/head.py _AGE_KEYS (Loomis / Reilly / Bridgman / Glocker tables, wave-17 research) HAIR docs/research17/units/hair2.md (H2-*)"my est." = an estimate widened around a single study, to be narrowed by critic10's DEV statistics; such values areranges on purpose (never one picture's number).
Age: canons are for adults. Children / babies apply the anatomical age DELTA from pydraw.anatomy.head (feature linesdrop, face narrows, neck shortens) on top of the style values, then clamp to the style range widened by 15 %."""import numpy as np
# realistic anchor: Loomis / Reilly adult values from pydraw.anatomy.head._AGE_KEYS (age 25)_REAL = dict(hairline=0.143, brow=0.429, eye=0.50, nose=0.714, mouth=0.81)
CANON = { # --------------------------------------------------------------------------------------- realistic (ink, paint) "real": { "hairline_y": (0.13, 0.16, "HD Loomis top sixth ~0.143-0.167 (H17 S6)"), "brow_y": (0.41, 0.44, "HD 0.429; female brows a little higher (H17 S7)"), "eye_y": (0.48, 0.52, "HD 0.50 (R1 eyes at half the head)"), "nose_y": (0.70, 0.73, "HD 0.714"), "mouth_y": (0.79, 0.83, "HD 0.81"), "eye_spacing": (0.25, 0.28, "HD Reilly fifths: centres 2/5 of face width ~0.25-0.27 H"), "eye_w": (0.11, 0.135, "HD eye width = face width / 5"), "eye_h": (0.035, 0.055, "my est.: an open adult eye ~1/3 of its width"), "face_w": (0.60, 0.66, "H17 S2 bizygomatic 0.63 H (ANSUR II)"), "jaw_w": (0.42, 0.56, "HD jaw_angle x (0.66..0.87 of half width by sex)"), "chin_w": (0.10, 0.18, "H17 S7 female v-shaped narrow, male square broad"), "neck_w": (0.43, 0.56, "H17 N4 neck diameter 0.49 H f / 0.56 H m"), "neck_len": (0.27, 0.36, "kit2: chin -> pit = 0.85 neck_len + 0.02 = 0.25-0.33 H (Loomis 8-head chart: the pit 1/4-1/3 H under the chin, my reading); was 0.30-0.42 = paint lane 15:02 'long necks'"), "neckline_depth": (0.00, 0.12, "kit2 my est.: crew neck at the pit (0-0.04 H) .. scoop ~0.12 H below it; replaces the seeded 0.08-0.24 (paint lane 15:02 'chest reads as a bib')"), "neckline_w": (1.15, 1.55, "kit2 my est.: neckline half width = neck half width x 1.15-1.55 (crew hugs the neck; boat/scoop wider)"), "trap_rise": (0.10, 0.14, "kit2: the trapezius meets the side of the neck 0.10-0.14 H above the pit (H17 N3/N7 'well above the pit'; was a fixed 0.09)"), "shoulder_w": (1.65, 1.90, "H17 N8 biacromial 1.71 f / 1.84 m"), "deltoid_w": (2.05, 2.30, "H17 N8 bideltoid 2.11 f / 2.25 m"), "waist_w": (1.15, 1.45, "my est. (ANSUR-scale waist breadth ~1.3 H); half-body only"), "nose_w": (0.13, 0.17, "my est.: nose width ~ eye width (Reilly)"), "mouth_w": (0.17, 0.22, "HD mouth corners ~0.82-0.86 eye_w each side"), "ear_h": (0.26, 0.30, "HD ear between brow and nose lines"), "head_in_frame": (0.52, 0.64, "my est. for painted/ink head-and-shoulders; critic10 head-in-frame stat refines"), }, # --------------------------------------------------------------------------------------- ink: illustration ideal "ink": { "eye_spacing": (0.29, 0.32, "RULES illustration idealisation ~0.31 H (Gibson; wider than anatomical 0.27)"), "brow_y": (0.39, 0.43, "RULES brows higher"), "neck_len": (0.36, 0.48, "RULES neck longer"), "jaw_w": (0.40, 0.50, "RULES jaw narrower"), "line_accent": (0.0073, 0.0122, "RULES I2 accents/hair 3-5 px at H ~410"), "line_form": (0.0020, 0.0037, "RULES I2 form lines 0.8-1.5 px at H ~410"), "line_hatch": (0.0012, 0.0024, "RULES I2 hatching 0.5-1 px at H ~410"), "face_paper": (0.55, 0.65, "RULES O2 about 60% of the face is paper"), "neck_fade": (0.15, 0.25, "RULES O1 bottom of the neck fades over ~0.2 H"), }, # --------------------------------------------------------------------------------------- painted "paint": { "edge_soft": (0.013, 0.035, "RULES P-R5 3-8 px at H ~230 (Sargent copy head height; paint lane 14:37)"), "head_cc_in_frame": (0.42, 0.52, "kit2: paint lane 14:37 asked CROWN-CHIN 0.42-0.52 of the frame (Sargent copy17 ~0.45); head_in_frame below counts the hair, which left paint heads at 0.36-0.43"), "head_in_frame": (0.42, 0.52, "paint lane 14:37: painted head-and-shoulders keeps shoulders + ground in (Sargent copy17 crown-chin ~0.45 of the frame; P-R8 needs the torso)"), "bands": (3, 4, "RULES P-R1 3-4 value bands"), }, # --------------------------------------------------------------------------------------- anime / cel "anime": { "hairline_y": (0.30, 0.40, "my est.: hidden under bangs; RULES A6 spike gaps peak at 0.30-0.36 H"), "brow_y": (0.50, 0.56, "my est.: brows just above the eye opening, drawn over the bangs (A5)"), "eye_y": (0.585, 0.665, "RULES A1 0.66 = the child end; research16 faces.md anime 0.50-0.55 of the head incl. hair ~0.58-0.62 from the crown for adults (anime lane 14:34)"), "nose_y": (0.78, 0.82, "RULES A1 nose 0.80"), "mouth_y": (0.88, 0.92, "RULES A1 mouth 0.91"), "eye_spacing": (0.30, 0.36, "RULES A1 spacing 0.33"), "eye_w": (0.175, 0.24, "faces.md anime ~0.2 of head width (adult end), RULES A1 0.24 (child end)"), "eye_h": (0.09, 0.24, "derived: eye_w x eye_h_ratio (resolve() sets it)"), "eye_h_ratio": (0.55, 1.0, "RULES A1 0.24x0.24 child-like = 1.0; styles.md shounen eye_h .12 vs eye_w ~.2 = 0.55"), "face_w": (0.70, 0.82, "my calc from A1: outer eye corners at +-(0.33+0.24)/2 need half width >= 0.35"), "jaw_w": (0.42, 0.62, "anime lane 14:34: jaw half 0.21-0.31 H (child/teen at the low end)"), "chin_w": (0.07, 0.20, "anime lane 14:34: chin half 0.035-0.10 H"), "neck_w": (0.15, 0.21, "RULES A1 neck width 0.17"), "neck_len": (0.22, 0.34, "my est."), "shoulder_w": (1.10, 1.76, "anime lane 14:34: shoulder half 0.55-0.88 H; RULES A1 head:shoulders ~1.2:1"), "deltoid_w": (1.35, 1.65, "my est. from shoulder_w + arm"), "waist_w": (0.85, 1.10, "my est.: slim anime torso"), "nose_w": (0.02, 0.04, "RULES A1 nose a 0.03 H mark"), "mouth_w": (0.08, 0.12, "RULES A1 closed mouth width 0.10"), "bang_end_y": (0.40, 0.60, "RULES A1/A6 0.56-0.60 long-hair end; short male cuts ~0.40-0.45 (HAIR H2-25)"), "line": (0.0065, 0.0090, "RULES A5 outline 0.0076 H"), "line_inner": (0.65, 0.75, "RULES A5 interior lines 0.7x"), "far_eye": (0.55, 0.65, "RULES A4 far eye 0.6x width in three-quarter"), "shadow_shift": (0.04, 0.06, "RULES A2a far-contour band ~0.05 H"), "shadow_shift_jaw": (0.07, 0.09, "RULES A2a widening to ~0.08 H at the jaw"), "hair_rim": (0.015, 0.025, "RULES A2b 0.02 H rim under hair"), "bang_cast": (0.015, 0.025, "RULES A2c bang silhouette shifted ~0.02 H"), "skin_shadow_frac": (0.30, 0.40, "RULES A2 skin shadow fraction"), "highlight_y": (0.30, 0.36, "RULES A6 zigzag highlight ~0.33 H"), "head_in_frame": (0.62, 0.74, "my est.: anime busts frame like X9 (~70%)"), }, # --------------------------------------------------------------------------------------- pixel "pixel": { "eye_y": (0.50, 0.56, "my calc: RULES X9 eye line ~60% down the head-with-hair = ~0.52 H below the crown"), "eye_spacing": (0.28, 0.34, "my est.: big eye glyphs (X8 near eye 41% of face width) need room"), "eye_w": (0.20, 0.28, "RULES X8 near eye 7 px of a 17 px face (0.41 face width ~0.26 H)"), "eye_h": (0.14, 0.22, "RULES X8 near eye 7x6"), "face_w": (0.62, 0.72, "my est.: H17 S2 0.63 widened for glyph room"), "neck_len": (0.20, 0.30, "RULES X9 shoulders start at the jaw line"), "shoulder_w": (1.40, 1.80, "my est. from H17 N8 compressed for the bust crop"), "head_in_frame": (0.66, 0.74, "RULES X9 head with hair ~70% of a portrait frame"), "colours": (7, 9, "RULES X1 7-9 colours for a 32-64 px portrait"), "near_black": (0.20, 0.30, "RULES X3 near-black 20-30% of the figure"), "hue_step": (8, 18, "RULES X2 +8..+18 deg toward yellow per lighter step"), },}# the realistic canon is the base of ink and paint (they override a few keys)_BASE = {"ink": "real", "paint": "real", "anime": "real", "pixel": "real", "real": None}
# hair (HAIR H2-3: lift of the hair shell above the skull, H units)HAIR_LIFT = { "short": (0.06, 0.12, "HAIR H2-3 short hair lots of volume on top"), "curly": (0.12, 0.20, "HAIR H2-3 / H2-23 curly up to 0.15+, volume rises with curl type"), "long": (0.04, 0.07, "HAIR H2-3 long hair sits closer"), "bob": (0.05, 0.09, "my est. between short and long"), "ponytail": (0.03, 0.06, "my est.: pulled back, tight to the skull"), "bun": (0.03, 0.06, "my est.: pulled back, tight to the skull"), "bald": (0.0, 0.005, ""), "buzz": (0.01, 0.025, "HAIR H2-25 fades tight to the scalp"),}HAIR_TEMPLE = (0.02, 0.04, "HAIR H2-3 temples 0.02-0.04")
def table(style): """the merged canon dict for a style: base 'real' values overridden by the style's own""" s = style if style in CANON else "real" out = dict(CANON["real"]) if s != "real": out.update(CANON[s]) return out
def rng_for(seed, *salt): import zlib return np.random.default_rng((int(seed) * 7919 + zlib.crc32(" ".join(map(str, salt)).encode())) % (2 ** 32))
def resolve(style, seed=0, sex=0.5, age=30.0, spread=1.0): """one character's canon: a value inside each range. sex (0 f .. 1 m) moves sexed keys toward the end the source names (jaw, neck, shoulders wider for men; female eyes a little larger, brows higher, H17 S7); the seed picks the rest. spread 0 = the range middle (a stable 'canon mean').""" T = table(style) r = rng_for(seed, "canon", style) sexed_up = {"jaw_w", "chin_w", "neck_w", "shoulder_w", "deltoid_w", "face_w", "nose_w", "mouth_w"} sexed_dn = {"eye_w", "eye_h", "brow_y", "eye_h_ratio"} out = {} for k, v in T.items(): lo, hi = float(v[0]), float(v[1]) u = 0.5 + (r.random() - 0.5) * spread if k in sexed_up: u = 0.35 * u + 0.65 * sex elif k in sexed_dn: u = 0.35 * u + 0.65 * (1 - sex) out[k] = lo + (hi - lo) * float(np.clip(u, 0, 1)) if "eye_h_ratio" in out: # anime: eye height as a ratio of its width (lane request 14:34) out["eye_h"] = out["eye_w"] * out["eye_h_ratio"] _age_adjust(out, style, age) return out
def _age_adjust(c, style, age): """children / babies: apply the anatomical age delta (pydraw.anatomy.head) to the style values""" from pydraw.anatomy.head import _age_row if age >= 18: if age > 50: # elder: same construction (HD), the neck thins a touch c["neck_w"] *= 0.97 return kid = _age_row(age) adult = _age_row(25.0) names = ["hairline_y", "brow_y", "eye_y", "nose_y", "mouth_y"] for i, k in enumerate(names): c[k] = float(np.clip(c[k] + (kid[i] - adult[i]), 0.05, 0.95)) wf = kid[5] / adult[5] # face width relative to H c["face_w"] *= 1.0 + 0.5 * (wf - 1) # Loomis: a child's face seems quite wide (H17 A2) c["jaw_w"] *= kid[7] # jaw scale c["chin_w"] *= kid[7] c["neck_w"] *= kid[8] c["neck_len"] *= kid[8] ** 1.6 for k in ("shoulder_w", "deltoid_w"): c[k] *= 0.55 + 0.45 * float(np.clip((age - 1) / 17.0, 0, 1)) # a child's shoulders ~ 1.0-1.3 H (my est.) big = float(np.clip((14.0 - age) / 12.0, 0, 1)) # H17 A1/A4 baby schema: larger eyes, wide set c["eye_w"] *= 1.0 + 0.15 * big c["eye_h"] *= 1.0 + 0.20 * big c["eye_spacing"] *= 1.0 + 0.05 * big
def hair_lift(style_name, seed=0): lo, hi, _ = HAIR_LIFT.get(style_name, HAIR_LIFT["short"]) r = rng_for(seed, "lift", style_name) return lo + (hi - lo) * float(r.random())
def cite(style, key): T = table(style) return T[key][2] if key in T else ""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131"""figure.flat: the kit's DEMO drawer - a plain flat figure from a layout + hair layout + value plan, in z order (C9).
It exists so the style lanes can see the kit work, and as the fallback when a style module is missing. It is NOT astyle: flat fills, one designed shadow per material (A2 far-contour band, bang cast), simple feature marks, oneoutline weight. render(fig, size, seed, trace) -> HxWx3 uint8 (the style-module contract, see figure/__init__.py).pixel=True draws the same figure on a PixCanvas (no AA, X10) at the figure's size."""import numpy as npfrom . import kit as Kfrom .value import shadow, with_luma, luma
F32 = np.float32
def render(fig, size=None, seed=0, trace=None, pixel=False): L, HL, V = fig.layout, fig.hair, fig.plan S = L.size m = V.materials sh = V.shadows if pixel: return _render_px(fig) cv = K.Canvas(S, S, m["bg"]) ink = m["ink"] lw = max(1.0, 0.0076 * L.H) # A5 outline weight hair_c, hair_s = m["hair"], sh["hair"] # 1 back hair (behind everything) if HL.back is not None: cv.fill(HL.back, hair_s) cv.stroke(HL.back, lw, ink, kind=None, closed=True) for lk in HL.locks: if lk.z < -1 and lk.group in ("tail", "back"): cv.fill(lk.poly(), hair_s if lk.group == "back" else hair_c) cv.stroke(lk.poly(), lw * .7, ink, kind=None, closed=True) if HL.bun is not None and HL.bun["z"] < 0: cv.fill(HL.bun["outline"], hair_c) cv.stroke(HL.bun["outline"], lw, ink, kind=None, closed=True) # 2 torso / clothes, chest skin, neck (neck in shadow: A2d) torso = K.crv(L.torso, closed=True, n=8, sharp=L.torso_sharp) tc = cv.fill(torso, m["cloth"]) cv.fill(K.crv(L.chest_skin, closed=True, n=6), m["skin"], clip=tc) cv.fill(L.neck, sh["skin"]) cv.stroke(torso, lw, ink, kind=None, closed=True) for s, a in L.arms.items(): # half body: arms over the torso, the far arm first ap = K.crv(a["outline"], closed=True, n=6, sharp=a["sharp"]) cv.fill(ap, sh["cloth"] if s == L.far else m["cloth"]) cv.stroke(ap, lw, ink, kind=None, closed=True) # 3 ears behind the face for s, e in L.ears.items(): if e["visible"] and not e["over_face"]: cv.fill(K.crv(e["outline"]), m["skin"]) cv.stroke(K.crv(e["outline"]), lw * .8, ink, kind=None, closed=True) # 4 face plate + designed far-contour shadow (A2a: face minus face shifted toward the light) face = L.face fc = cv.fill(face, m["skin"]) dx = -L.light_side * 0.05 * L.H lit = cv.cover(K.shift(face, -dx, -0.02 * L.H)) cv.paint(K.sub(fc, lit), sh["skin"]) cv.stroke(face, lw, ink, kind=None, closed=True) for s, e in L.ears.items(): if e["visible"] and e["over_face"]: cv.fill(K.crv(e["outline"]), m["skin"]) cv.stroke(K.crv(e["outline"]), lw * .8, ink, kind=None, closed=True) # 5 features: simple marks at the landmarks for s, e in L.eyes.items(): cv.fill(K.crv(e["outline"], n=6), (0.97, 0.97, 0.95)) ic = cv.cover(K.ellipse(e["c"], e["w"] * 0.22, e["h"] * 0.42)) cv.paint(ic * cv.cover(K.crv(e["outline"], n=6)), m["eyes"]) cv.stroke(e["upper"], max(1.0, lw * 1.6), ink, kind="swell") for s, b in L.brows.items(): cv.stroke(K.crv(b, closed=False), max(1.0, lw * 1.3), hair_s * 0.6, kind="flick" if s == "L" else "rflick") cv.stroke(np.array([L.nose["base"] + np.array([-0.02 * L.H, 0]), L.nose["base"] + np.array([0.02 * L.H, 0])]), lw * .8, sh["skin"] * .7, kind="swell") cv.stroke(K.crv(L.mouth["line"], closed=False), lw, m["lips"] * .6, kind="ends") if L.beard is not None: cv.fill(K.crv(L.beard["outline"]), hair_s) cv.stroke(K.crv(L.mouth["line"], closed=False), lw, ink, kind="ends") if L.glasses is not None: for s, lp in L.glasses["lens"].items(): cv.stroke(lp, lw * 1.2, ink, kind=None, closed=True) cv.stroke(L.glasses["bridge"], lw * 1.2, ink, kind=None) for s, a in L.glasses["arms"].items(): if L.ears[s]["visible"]: cv.stroke(a, lw * 1.2, ink, kind=None) # 6 front hair: side locks, cap, top locks, bangs; bang cast shadow on the face (A2c) if HL.cap is not None: bangs = [lk for lk in HL.locks if lk.group == "bang"] for lk in bangs: cast = K.shift(lk.poly(), -L.light_side * 0.02 * L.H, 0.02 * L.H) cv.fill(cast, sh["skin"], clip=fc) cv.fill(HL.cap, hair_c) cv.stroke(HL.cap_outer, lw, ink, kind=None) for lk in sorted([k for k in HL.locks if k.z >= -1], key=lambda k: k.z): p = lk.poly() cv.fill(p, hair_c) cv.stroke(p, lw * .7, ink, kind=None, closed=True) if HL.bun is not None and HL.bun["z"] >= 0: cv.fill(HL.bun["outline"], hair_c) if HL.highlight is not None: cv.stroke(HL.highlight, 0.02 * L.H, with_luma(hair_c, min(0.95, luma(hair_c) + 0.25)), kind="swell", alpha=.7) return cv.u8()
def _render_px(fig): """the same figure on the no-AA palette grid: flat masses, a near-black outline (X1, X10)""" L, HL, V = fig.layout, fig.hair, fig.plan m, sh = V.materials, V.shadows pc = K.PixCanvas(L.size, L.size) k = {n: pc.key(c) for n, c in (("K", (0.04, 0.045, 0.07)), ("skin", m["skin"]), ("skin_s", sh["skin"]), ("hair", m["hair"]), ("hair_s", sh["hair"]), ("cloth", m["cloth"]), ("W", (0.97, 0.96, 0.93)), ("eye", m["eyes"]))} if HL.back is not None: pc.poly(HL.back, k["hair_s"]) pc.poly(K.crv(L.torso, closed=True, n=8, sharp=L.torso_sharp), k["cloth"]) pc.poly(L.neck, k["skin_s"]) for e in L.ears.values(): if e["visible"]: pc.poly(e["outline"], k["skin"]) face = pc.poly(L.face, k["skin"]) if HL.cap is not None: pc.poly(HL.cap, k["hair"]) for lk in HL.locks: if lk.z >= -1: pc.poly(lk.poly(), k["hair"]) fig_m = pc.a >= 0 pc.outline_outside(fig_m, k["K"]) for e in L.eyes.values(): pc.line(e["upper"], k["K"]) c = e["c"] pc.px([(c[0], c[1]), (c[0], c[1] + 1)], k["K"]) pc.line(L.mouth["line"], k["K"]) return pc.rgb(bg=m["bg"])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733"""figure.hairlayout: the hair LAYOUT as data, shared by every style (wave 18, kit lane; C5, A6, R1-R3, P-R4, X4).
from pydraw.figure.hairlayout import build as build_hair hl = build_hair(layout, style="anime") # layout = figure.layout.build(...) hl.cap, hl.back, hl.locks, hl.guides, hl.troughs, hl.crests, hl.silhouette()
Every style draws the SAME layout its own way (WAVE18 step 6): anime ribbons with a dark half + zigzag highlight,ink flow-field streamlines with a value field, painted value masses + lit-side strokes, pixel 2-3 locks with seams.
Built the artist's way (HAIR H2-1..H2-26 = docs/research17/units/hair2.md): volume first (a shell lifted off the skull,H2-3: crown 0.04-0.20 H by style, temples 0.02-0.04), a root spot / parting the locks radiate from (H2-4), masses ->clumps (H2-2), the silhouette made of lock tips (H2-5, C5), bangs / side locks / back hair as separate sections(H2-10), ponytail tied slightly to one side (H2-15), bun partly hidden behind the head (H2-16), curly hair anirregular cloud of lobes, never a circle (H2-23).
Fields (2D pixel arrays, image y down): style ('short','long','bob','ponytail','curly','bun','buzz','bald'), fringe ('none','full','side','spiky') cap closed outline of the hair over the skull (outer silhouette over the top + the hairline across the forehead); None when bald. kit2: for bob / long / curly the cap runs down the sides as ONE mass to the jaw (bob: curled-in tips); a turned head's near side covers the back of the skull down to the nape (round the ear for short / tied hair). Draw it AFTER the face plate. cap_outer open outer edge of the cap (R bottom -> over the top -> L bottom); bald: the bare skull's top arc wavy bool (Person.wavy): side locks carry a wave; fringe also honours Person.fringe (asked in words) back closed outline of the hair BEHIND the head / neck / shoulders (draw before the face and torso), or None hairline open curve where hair meets the forehead skin (temple R -> centre -> temple L) parting dict(root (2D), line (open curve hairline -> crown), side (-1 left, 0 centre, +1 right in image)) crown 2D point of the whorl locks list of Lock (root -> tip spines with widths) in draw order; lock.group in 'back' (behind the head), 'side' (beside the face, in front), 'bang' (over the forehead), 'top' (on the cap), 'tail' (ponytail), 'bun' tips 2D points where the silhouette breaks (lock tips) guides open curves for an ink flow field (R1): the lock spines + radiating cap arcs troughs [(curve, amp, sigma_px)] darkness ridges (seams between locks, the turning side, under bangs, the nape) crests [(curve, amp, sigma_px)] the highlight band (A6 ~0.33 H from the crown; H2-7 a band following the skull) highlight open curve of the highlight band (same as crests[0][0]) side locks never cover an eye; on the far side of a turned head they stay beyond the far face contour (and z < -1) tie 2D point (ponytail; on the visible side of the back of the head, the tail swings out past the neck) or None; bun dict(c, rx, ry, outline) or None lift hair lift at the crown (H units); light_side copied from the layoutLock: spine (Nx2), w0 (root width px), w1 (tip width px), tip ('point','round','flat'), group, side (-1/+1 image side of the parting), dark (fraction of the length after which the lock is dark on one side, A6 ~0.35), z (draw order), .outline() -> (closed polygon, sharp idx) via kit.ribbon"""import mathimport numpy as npfrom . import canon as Cfrom .kit import ribbon, resample, crv, offset
F32 = np.float32
class Lock: def __init__(self, spine, w0, w1=0.0, tip="point", group="top", side=0, dark=0.35, z=0.0, bulge=0.0): self.spine = np.asarray(spine, F32) self.w0, self.w1, self.tip, self.group, self.side = float(w0), float(w1), tip, group, side self.dark, self.z, self.bulge = float(dark), float(z), float(bulge)
def outline(self): return ribbon(self.spine, self.w0, self.w1, self.tip, bulge=self.bulge)
def poly(self, n=6): """the smooth closed outline (Catmull-Rom with sharp tips) as one polygon""" P, sh = self.outline() return crv(P, closed=True, n=n, sharp=sh)
def __repr__(self): return "Lock(%s, %d pts, w %.1f->%.1f, %s)" % (self.group, len(self.spine), self.w0, self.w1, self.tip)
class HairLayout: def silhouette(self): """polygons whose union is the whole hair silhouette (for masks)""" out = [] if self.cap is not None: out.append(self.cap) if self.back is not None: out.append(self.back) if self.bun is not None: out.append(self.bun["outline"]) out += [lk.poly() for lk in self.locks] return out
def __repr__(self): return "HairLayout(%s, fringe=%s, %d locks, lift %.2f)" % (self.style, self.fringe, len(self.locks), self.lift)
def _shell_pt(L, theta, phi, lift): """a 3D point on the hair shell (the cranium ellipsoid grown by lift; more on top than at the temples, H2-3)""" c, r = L.cranium_c, L.cranium_r tl = C.HAIR_TEMPLE[0] + 0.5 * (C.HAIR_TEMPLE[1] - C.HAIR_TEMPLE[0]) lf = tl + (lift - tl) * max(0.0, math.sin(phi)) ** 1.5 if lift > tl else lift d = np.array([math.cos(phi) * math.sin(theta), math.sin(phi), math.cos(phi) * math.cos(theta)], F32) p = c + d * (r + lf) p[1] = float(L.Y(np.array([p[1]], F32))[0]) return p
def _phi_at(L, theta, y_canon): """phi on the bare cranium where (canon) height = y_canon, for a given theta""" ph = np.linspace(-0.9, 1.5, 200) ys = np.array([L.skull(theta, p)[1] for p in ph]) return float(np.interp(y_canon, ys, ph))
def _pick_fringe(style, hs, r, sex, age, asked=None): """the fringe: the prompt's word wins (Person.fringe); else odds by style, hair style, sex and age. Not everyone gets a fringe (ink lane 14:58: fringe=full/spiky on almost everyone). Odds are my est. from the DEV refs' spread (critic10 refbench: ink/paint men and tied-back hair show the forehead; anime girls mostly have bangs, A6).""" if hs in ("bald", "buzz"): return "none" if asked in ("none", "full", "side", "spiky"): return asked if style == "anime": odds = {"short": ((("full", .35), ("spiky", .30), ("side", .20), ("none", .15)) if sex > .5 else (("full", .55), ("side", .30), ("none", .15))), "ponytail": (("none", .45), ("side", .30), ("full", .25)), "bun": (("none", .50), ("side", .30), ("full", .20)), "curly": (("full", .45), ("none", .55))}.get(hs, (("full", .60), ("side", .28), ("none", .12))) else: odds = {"short": ((("none", .65), ("side", .25), ("spiky", .10)) if sex > .5 else (("none", .40), ("side", .35), ("full", .25))), "ponytail": (("none", .70), ("side", .20), ("full", .10)), "bun": (("none", .75), ("side", .18), ("full", .07)), "curly": (("none", .75), ("full", .25)), "bob": (("full", .40), ("side", .30), ("none", .30)) }.get(hs, (("none", .45), ("side", .30), ("full", .25))) if age > 60: # older sitters: the forehead shows more often (fringe odds halved, my est.) odds = tuple((k, p * (0.5 if k != "none" else 1.0)) for k, p in odds) tot = sum(p for k, p in odds) u = r.random() * tot for k, p in odds: u -= p if u <= 0: return k return odds[-1][0]
def build(L, style=None, seed=None, fringe=None): """the hair layout for a figure.layout Layout (see the module docstring)""" P = L.person style = style or L.style seed = P.seed if seed is None else seed r = C.rng_for(seed, "hair", P.hair_style) hs = P.hair_style HL = HairLayout() HL.style, HL.lift, HL.light_side = hs, L.hair_lift, L.light_side HL.locks, HL.tips, HL.guides, HL.troughs, HL.crests = [], [], [], [], [] HL.cap = HL.back = HL.bun = HL.tie = None cn = L.canon H = L.H yf = lambda f: 0.5 - f HL.fringe = fringe or _pick_fringe(style, hs, r, P.sex, P.age, getattr(P, "fringe", None)) HL.wavy = bool(getattr(P, "wavy", False)) lift = L.hair_lift proj = L.proj
def sp(theta, phi, lf=None): return _shell_pt(L, theta, phi, lift if lf is None else lf)
# ---- parting and crown (H2-4) ------------------------------------------------------------------------------- if hs in ("ponytail", "bun") and r.random() < .5: part_th = 0.0 else: part_th = math.radians(r.choice([-1, 1]) * r.uniform(12, 28)) if r.random() < .7 else 0.0 HL.crown = proj(sp(math.pi * 0.9, math.radians(70)))[0] hair_f = cn["hairline_y"] if P.age > 55 and P.sex > .5: hair_f = min(hair_f + 0.04 * r.random(), 0.3) # H2-26 mild recession # ---- the hairline across the forehead (temple R -> centre -> temple L) --------------------------------------- th = np.radians(np.linspace(-82, 82, 17)) ys = [] for t in th: a = abs(math.degrees(t)) / 82.0 ys.append(yf(hair_f) * (1 - a ** 2) + yf(cn["brow_y"] - 0.02) * a ** 2 + 0.03 * math.sin(math.pi * a) * a) hl3 = np.array([L.skull(t, _phi_at(L, t, y)) for t, y in zip(th, ys)], F32) hl3 = hl3 * np.array([1.0, 1.0, 1.0]) + np.array([0, 0, 0.004]) HL.hairline = proj(hl3) # the parting line: from the hairline at part_th back over the top phis = np.linspace(_phi_at(L, part_th, yf(hair_f)), math.radians(85), 8) HL.parting = dict(line=proj(np.array([sp(part_th, p, lift * 0.3) for p in phis])), root=proj(sp(part_th, phis[0], lift * 0.3))[0], side=0 if part_th == 0 else int(np.sign(math.sin(part_th + math.radians(L.yaw)) or 1))) if hs == "bald": HL.highlight = None HL.lift = 0.0 # the bare skull's top arc (temple R -> crown -> temple L): styles that trace an outer hair line need one # even when there is no hair (ink crashed on a young bald man: no cap, no back, no locks) HL.cap_outer = _top_arc(L.cranium, L.pt["brow_mid_L"][1] * 0.5 + L.pt["brow_mid_R"][1] * 0.5) _bald_fringe(L, HL, r, sp) return HL
# ---- the cap: hull of the shell over the hair region, closed by the hairline ------------------------------- pts3 = [] for t in np.radians(np.arange(-180, 180, 10)): front = abs(math.degrees(t)) < 84 y_lo = (np.interp(abs(math.degrees(t)), np.degrees(np.abs(th[8:])), ys[8:]) if front else yf(cn["nose_y"]) if hs not in ("bald",) else yf(cn["brow_y"])) p_lo = _phi_at(L, t, y_lo) for ph in np.linspace(p_lo, math.pi / 2, 9): pts3.append(sp(t, ph)) pts3 = np.array(pts3, F32) from .layout import _hull hullP = _hull(proj(pts3) * np.array([1, -1])) * np.array([1, -1]) hullP = resample(hullP, max(2.0, H / 70), closed=True) # cut the hull between the two hairline ends and close it with the hairline eR, eL = HL.hairline[0], HL.hairline[-1] iR = int(np.argmin(np.hypot(*(hullP - eR).T))) iL = int(np.argmin(np.hypot(*(hullP - eL).T))) itop = int(np.argmin(hullP[:, 1])) n = len(hullP)
def arc(i, j): return [hullP[(i + k) % n] for k in range(((j - i) % n) + 1)] a1 = arc(iL, iR) a2 = arc(iR, iL) top_arc = a1 if any(np.allclose(p, hullP[itop]) for p in a1) else a2[::-1] # orient top_arc from R end to L end if np.hypot(*(np.asarray(top_arc[0]) - eR)) > np.hypot(*(np.asarray(top_arc[0]) - eL)): top_arc = top_arc[::-1] # ---- the hair length (H units, head frame y) -------------------------------------------------------------- length = {"short": yf(cn["eye_y"]), "buzz": yf(cn["brow_y"]), "bob": -0.5 - 0.10 * r.uniform(0.5, 1.5), "long": -0.5 - r.uniform(1.0, 1.6), "curly": (-0.5 - r.uniform(0.0, 0.8)) if P.sex < .5 else yf(0.75), "ponytail": yf(cn["eye_y"]), "bun": yf(cn["eye_y"])}[hs] HL.length = length # ---- the sides (kit2): the cap continues down the sides of the head as ONE mass with the top ------------------- # bob / long / curly: a side mass from the temple to the jaw (bob: curled-in tips at the jaw; paint lane 14:37 + # 15:02 "bob ear-muffs"); a turned head: the back of the skull on the near side is hair down to the nape (paint # lane 15:01 "hair covers the side/back of the skull in 3/4"); a far side never crosses the far face contour. outR, inR, outL, inL = _side_extensions(L, HL, r, hs, hullP, top_arc) HL.cap_outer = np.array(outR + list(top_arc) + outL, F32) HL._cap_inner = (np.array(inL, F32).reshape(-1, 2), np.array(inR, F32).reshape(-1, 2)) HL.cap = _assemble_cap(HL)
# ---- the highlight band (A6 ~0.33 H from the crown; H2-7 follows the skull) -------------------------------- hy = cn.get("highlight_y", 0.33) band3 = [sp(t, _phi_at(L, t, yf(hy)), lift * 0.95) for t in np.radians(np.linspace(-70, 70, 13))] HL.highlight = proj(np.array(band3)) HL.crests.append((HL.highlight, 0.8, 0.05 * H))
# ---- sections per hair style --------------------------------------------------------------------------------- _back_mass(L, HL, r, sp, hs, length) _side_locks(L, HL, r, sp, hs, length, style) _top_locks(L, HL, r, sp, hs, part_th) _bangs(L, HL, r, sp, hs, style, part_th) if hs == "ponytail": _ponytail(L, HL, r, sp) if hs == "bun": _bun(L, HL, r, sp) if hs == "curly": _curly_lobes(L, HL, r) # ---- value structure: troughs (dark) ------------------------------------------------------------------------- sh = 1 if L.light_side < 0 else -1 # image side away from the light for a, b in zip(HL.locks, HL.locks[1:]): if a.group == b.group and a.group in ("bang", "side", "back", "top"): m = min(len(a.spine), len(b.spine)) seam = (resample(a.spine, 1.0)[:m] + resample(b.spine, 1.0)[:m]) / 2 if m > 1 else None if seam is not None and len(seam) > 2: HL.troughs.append((seam, 0.35, 0.02 * H)) # the turning / shadow side of the mass and the nape (H2-6: under layers, behind ears, at the nape) cx = L.pt["head_c"][0] side_pts = HL.cap_outer[(HL.cap_outer[:, 0] - cx) * sh > 0] if len(side_pts) > 2: HL.troughs.append((side_pts, 0.5, 0.08 * H)) if HL.back is not None: HL.troughs.append((np.array([L.pt["neck_top_L"], L.pt["neck_top_R"]]), 0.6, 0.12 * H)) if HL.fringe != "none": HL.troughs.append((HL.hairline, 0.45, 0.04 * H)) # guides for flow (R1): every lock spine + radiating arcs over the cap HL.guides += [lk.spine for lk in HL.locks] for t in np.radians(np.linspace(-150, 150, 9)): HL.guides.append(proj(np.array([sp(part_th + t * 0.0 + (t if abs(t) < 3 else 0), p) for p in np.linspace(math.radians(80), _phi_at(L, t, yf(0.45)), 5)]))) HL.tips = [lk.spine[-1] for lk in HL.locks if lk.tip != "flat"] HL.locks.sort(key=lambda k: k.z) return HL
def _top_arc(P, y_cut): """the part of a closed outline above image row y_cut, as one open curve (left to right in the image)""" P = np.asarray(P, F32) above = P[:, 1] < y_cut if above.all() or not above.any(): return P[np.argsort(P[:, 0])] k = int(np.argmin(above)) # first point below the cut: start the walk there Q = np.roll(P, -k, axis=0) a = Q[Q[:, 1] < y_cut] return a if a[0, 0] < a[-1, 0] else a[::-1]
def _row_x(P, y, sgn): """the extreme x (toward image side sgn) where the closed polygon P crosses image row y, or None""" P = np.asarray(P, np.float64) A, B = P, np.roll(P, -1, axis=0) m = (A[:, 1] - y) * (B[:, 1] - y) <= 0 m &= np.abs(B[:, 1] - A[:, 1]) > 1e-9 if not m.any(): return None t = (y - A[m, 1]) / (B[m, 1] - A[m, 1]) xs = A[m, 0] + t * (B[m, 0] - A[m, 0]) return float(xs.max() if sgn > 0 else xs.min())
def _img_sign(L, s): """image side (+1 right, -1 left) of the subject side s""" o = "R" if s == "L" else "L" d = float(L.eyes[s]["c"][0] - L.eyes[o]["c"][0]) return 1.0 if d > 0 else -1.0
def _eye_guard_x(L, s, sgn, margin): """the x a hair edge on image side sgn must stay beyond so it never covers that side's eye (or brow end)""" xs = [float(np.max(np.asarray(L.eyes[s]["outline"])[:, 0] * sgn)), float(np.max(np.asarray(L.brows[s])[:, 0] * sgn))] return (max(xs) + margin) * sgn
def _side_extensions(L, HL, r, hs, hullP, top_arc): """outer and inner edges that continue the cap down the sides. Returns outR (bottom -> top, ending before the top arc), inR (R hairline end -> down), outL (top -> bottom), inL (bottom -> up to the L hairline end). Empty lists = the cap ends at that temple as before.""" H = L.H pt = L.pt turned = abs(L.yaw) > 12 chin_y = float(pt["chin"][1]) crown_y = float(pt["crown"][1]) res = {} HL._side_edges = {} for s in ("R", "L"): sgn = _img_sign(L, s) near = turned and s == L.near far = turned and s == L.far end = np.asarray(top_arc[0] if s == "R" else top_arc[-1], np.float64) # hull vertex at the temple hl_end = np.asarray(HL.hairline[0] if s == "R" else HL.hairline[-1], np.float64) mass = hs in ("bob", "long") or (hs == "curly" and L.person.sex < .5) if mass: if hs == "bob": y_end = chin_y - (0.10 - 0.08 * r.random()) * H # the jaw, a little above the chin else: y_end = float(pt["mouth_c"][1]) + 0.04 * H # long: the jaw row; locks go on elif near and hs not in ("buzz",): y_end = float(pt["ear_bot_" + s][1]) + 0.06 * H # the nape behind the ear else: res[s] = ([], []) continue y0 = max(float(end[1]), float(hl_end[1]) - 0.02 * H) ys = np.linspace(y0, y_end, 9)[1:] # outer edge: the shell's silhouette on this side, then straight down (long: a little flare) last = None outer = [] flare = {"long": 0.05, "curly": 0.10, "bob": 0.02}.get(hs, 0.0) * H for k, y in enumerate(ys): x = _row_x(hullP, y, sgn) if x is None: x = last if last is not None else float(end[0]) x = x + sgn * flare / len(ys) last = x outer.append((x, y)) # inner edge ear = L.ears[s] eo = np.asarray(ear["outline"], np.float64) if near: # in front of the ear (sideburn) for a mass that covers the ear; round the back of the ear for short hair front_x = float(np.min(eo[:, 0] * -sgn) * -sgn) # the ear edge toward the face back_x = float(np.max(eo[:, 0] * sgn) * sgn) et, eb = float(np.min(eo[:, 1])), float(np.max(eo[:, 1])) if mass: inner = [(front_x - sgn * 0.01 * H, max(y0, et)), (front_x - sgn * 0.015 * H, eb)] inner += [(front_x - sgn * 0.02 * H, y) for y in ys if y > eb + 0.02 * H] else: inner = [(front_x - sgn * 0.005 * H, et + 0.02 * H), ((front_x + back_x) / 2, et - 0.02 * H), (back_x + sgn * 0.006 * H, et + 0.25 * (eb - et)), (back_x + sgn * 0.01 * H, eb), (back_x + sgn * 0.06 * H, y_end)] # never inside the face features: a mass on the near side keeps off the near eye gx = _eye_guard_x(L, s, sgn, 0.05 * H) inner = [((max(x * sgn, gx * sgn)) * sgn, y) for x, y in inner] else: inner = [] gx = _eye_guard_x(L, s, sgn, 0.05 * H) for y in ys: fx = _row_x(L.face, y, sgn) if fx is None: fx = inner[-1][0] if inner else float(hl_end[0]) inset = (0.005 if far else -0.035) * H # far: just outside the contour; front: over the edge x = fx + sgn * inset if y < float(pt["nose_base"][1]) + 0.04 * H: # eye rows: never over the eye or the brow end x = max(x * sgn, gx * sgn) * sgn if far: x = max(x * sgn, (fx + sgn * 0.005 * H) * sgn) * sgn inner.append((x, y)) # keep the outer edge outside the inner one inner_y = np.array([q[1] for q in inner]) if inner else None outer = [((max(xo * sgn, (np.interp(yo, inner_y, [q[0] for q in inner]) + sgn * 0.04 * H) * sgn) * sgn if inner else xo), yo) for xo, yo in outer] # bottom tips (H2-5: never a flat cut). bob: the ends curl in under the jaw xo, yb = outer[-1] xi = inner[-1][0] if inner else xo - sgn * 0.08 * H if hs == "bob": outer.append((xo - sgn * 0.25 * abs(xo - xi), yb + 0.05 * H)) outer.append((xo - sgn * 0.60 * abs(xo - xi), yb + 0.045 * H)) inner.append((xi + sgn * 0.12 * abs(xo - xi), yb + 0.015 * H)) elif mass: outer.append(((xo + xi) / 2 + sgn * 0.1 * abs(xo - xi), yb + 0.06 * H)) else: outer.append(((xo + xi) / 2, yb + 0.03 * H)) HL._side_edges[s] = (list(outer[:len(ys)]), list(inner[:len(ys)]) if mass else [], near, far, mass) res[s] = (outer, inner) outR, inR = res["R"] outL, inL = res["L"] # orientation: outR bottom -> top, outL top -> bottom, inL bottom -> top, inR top -> bottom return outR[::-1], inR, outL, inL[::-1]
def _assemble_cap(HL): """cap = outer edge (R bottom -> over the top -> L bottom) + L inner edge up + hairline L -> R + R inner edge down (closed)""" inL, inR = HL._cap_inner parts = [np.asarray(HL.cap_outer, F32)] if len(inL): parts.append(inL) parts.append(np.asarray(HL.hairline[::-1][1:-1], F32)) if len(inR): parts.append(inR) return np.vstack(parts)
def _bald_fringe(L, HL, r, sp): """Norwood 6-7 (H2-26): only a band at the back and sides, above the ears""" if L.person.age < 40: return yf = lambda f: 0.5 - f cn = L.canon band = [] for t in np.radians(np.linspace(70, 290, 23)): band.append(sp(t, _phi_at(L, t, yf(cn["brow_y"] - 0.02)), 0.02)) up = [sp(t, _phi_at(L, t, yf(cn["brow_y"] - 0.12)), 0.02) for t in np.radians(np.linspace(290, 70, 23))] poly = L.proj(np.array(band + up)) HL.back = poly
def _back_mass(L, HL, r, sp, hs, length): """hair behind the head (draw before the face): follows the head at a small distance, then widens behind the shoulders (H2-10); its bottom is a row of tips, never a flat cut (H2-5)""" H = L.H yf = lambda f: 0.5 - f cn = L.canon proj = L.proj if hs in ("ponytail", "bun", "buzz") or (hs == "curly" and length > -0.5): HL.back = None # tied-back / cropped hair: nothing hangs behind the neck return # sides of the head at the ears, outward a little top = [sp(t, math.radians(20)) for t in np.radians(np.linspace(100, 260, 9))] topP = proj(np.array(top)) hc = L.pt["head_c"] hw = L.cranium_r[0] * H + L.hair_lift * H bottom_y = L.pt["crown"][1] + (0.5 - length) * H if hs == "short": bottom_y = L.pt["crown"][1] + (0.5 - yf(cn["nose_y"] + 0.05)) * H widen = {"short": 0.0, "bob": 0.12, "long": 0.35, "curly": 0.28}.get(hs, 0.1) n_tip = {"short": 3, "bob": 5, "long": 7, "curly": 7}.get(hs, 5) face_dir = math.sin(math.radians(L.yaw)) cx = hc[0] - face_dir * 0.18 * H # the back of the head sits behind the face xl = cx - hw * (1 + widen) xr = cx + hw * (1 + widen) # left / right outer edges from the ear level down, then a ragged bottom of tips yl = hc[1] tips = [] for i in range(n_tip + 1): u = i / n_tip x = xl + (xr - xl) * u dy = (0.05 + 0.06 * r.random()) * H * (1 if i % 2 == 0 else -0.6) bow = -0.10 * H * math.sin(math.pi * u) if hs in ("bob",) else 0.04 * H * math.sin(math.pi * u) tips.append((x, bottom_y + bow + dy)) edgeL = [(cx - hw * 1.02, yl - 0.05 * H), (cx - hw * (1 + widen * 0.5), (yl + bottom_y) / 2)] edgeR = [(cx + hw * (1 + widen * 0.5), (yl + bottom_y) / 2), (cx + hw * 1.02, yl - 0.05 * H)] pts = [tuple(p) for p in topP] if topP[0][0] > topP[-1][0] else [tuple(p) for p in topP[::-1]] poly = np.array(pts + edgeL + tips + edgeR, F32) # order: top goes R->L (x decreasing), then down the left edge, tips L->R, up the right if poly[0][0] < poly[len(pts) - 1][0]: pts = pts[::-1] poly = np.array(pts + edgeL + tips + edgeR, F32) HL.back = crv(poly, closed=True, n=6, sharp=list(range(len(pts) + 2, len(pts) + 2 + len(tips), 2))) # back locks: a few clumps in the back mass (for seams and dark pockets) nb = {"short": 0, "bob": 4, "long": 5, "curly": 0}.get(hs, 3) for i in range(nb): u = (i + 0.5) / nb x0 = cx + (u - 0.5) * 1.4 * hw x1 = xl + (xr - xl) * u + r.normal(0, 0.03 * H) spine = [(x0, hc[1] - 0.25 * H), ((x0 + x1) / 2, (hc[1] + bottom_y) / 2), (x1, bottom_y + r.normal(0, .03) * H)] HL.locks.append(Lock(spine, 0.30 * H, 0.0, "point", "back", int(np.sign(u - .5)), z=-2 + 0.01 * i))
def _lock_w(lk, t): """the ribbon width of lock lk at length fraction t (kit.ribbon's law)""" return lk.w0 + (lk.w1 - lk.w0) * t ** 1.2 + lk.bulge * math.sin(math.pi * t) * lk.w0
def _keep_off_face(L, lk, s, far): """push a lock's spine outward (image side of subject side s) so its inner edge never covers that side's eye / brow, and on the far side of a turned head never crosses the far face contour (ink lane 14:58: the far lock covered the far eye; style lanes that ignore lock.z still get a clean face)""" H = L.H sgn = _img_sign(L, s) gx = _eye_guard_x(L, s, sgn, 0.04 * H) ylim = float(L.pt["nose_base"][1]) + 0.04 * H chin_y = float(L.pt["chin"][1]) sp = np.asarray(lk.spine, np.float64).copy() d = np.r_[0, np.cumsum(np.hypot(*np.diff(sp, axis=0).T))] t = d / max(d[-1], 1e-6) last_fx = None for i in range(len(sp)): x, y = sp[i] half = _lock_w(lk, t[i]) / 2 req = None if y < ylim: req = gx if far: fx = _row_x(L.face, y, sgn) if y < chin_y else None fx = fx if fx is not None else last_fx # below the chin: keep hanging beyond the contour last_fx = fx if fx is not None: req = fx + sgn * 0.005 * H if req is None else max(req * sgn, (fx + sgn * 0.005 * H) * sgn) * sgn if req is not None: x = max(x * sgn, (req + sgn * half) * sgn) * sgn sp[i, 0] = x if far: # a far lock hangs: once pushed out it does not hook back in under the eye (no '[' brackets) sp[:, 0] = np.maximum.accumulate(sp[:, 0] * sgn) * sgn lk.spine = sp.astype(F32) return lk
def _wave(spine, amp, wl, ph): """offset a polyline sideways by a sine along its length (a lock's S curve / wave)""" P = np.asarray(spine, np.float64) d = np.r_[0, np.cumsum(np.hypot(*np.diff(P, axis=0).T))] T = np.gradient(P, axis=0) T /= np.maximum(np.hypot(T[:, 0], T[:, 1]), 1e-6)[:, None] N = np.stack([-T[:, 1], T[:, 0]], 1) k = np.sin(np.pi * np.clip(d / max(d[-1], 1e-6), 0, 1)) # no shift at the root, most mid-length off = amp * np.sin(2 * np.pi * d / max(wl, 1e-6) + ph) * (0.35 + 0.65 * k) return (P + N * off[:, None]).astype(F32)
def _side_locks(L, HL, r, sp, hs, length, style): """locks beside the face (H2-10). bob / long / curly: 2-3 tapered, curving clumps per side laid ON the side mass of the cap (_side_extensions) and, for long hair, falling on past the jaw with staggered tips (H2-5) and an S curve or a wave (Person.wavy); never parallel rails (ink lane 15:07 comb). Short / tied hair: a small temple lock. Every lock keeps off the eyes; the far side of a turned head stays beyond the far contour.""" H = L.H yf = lambda f: 0.5 - f cn = L.canon proj = L.proj if hs in ("buzz",): return wavy = bool(getattr(L.person, "wavy", False)) or hs == "curly" crown_y = float(L.pt["crown"][1]) for s, sx in (("L", 1.0), ("R", -1.0)): far = (s == L.far) and abs(L.yaw) > 8 sgn = _img_sign(L, s) edges = getattr(HL, "_side_edges", {}).get(s) if hs in ("short", "ponytail", "bun") or not (edges and edges[4]): if hs != "short" and r.random() < .5: continue if hs == "short" and L.person.sex > .5 and r.random() < .5: continue # many short men's cuts: no temple lock at all if far: continue # the far temple is hidden behind the turned face root = sp(sx * math.radians(78), _phi_at(L, sx * math.radians(78), yf(cn["brow_y"] - 0.06))) tip_y = yf(cn["eye_y"] + 0.05) if hs == "short" else yf(cn["nose_y"] + 0.05) tip = root + np.array([sx * 0.01, 0, 0.0]) tip[1] = tip_y mid = (root + tip) / 2 + np.array([sx * 0.03, 0, 0.02]) lk = Lock(proj(np.array([root, mid, tip])), 0.08 * H, 0.0, "point", "side", int(sgn), z=(-1.5 if far else 1.0)) HL.locks.append(_keep_off_face(L, lk, s, far)) continue outer, inner, near, far_, mass = edges if not inner: continue ys = np.array([q[1] for q in outer]) xo = np.array([q[0] for q in outer]) xi = np.interp(ys, np.array([q[1] for q in inner]), np.array([q[0] for q in inner])) n = {"long": 3, "bob": 2, "curly": 2}.get(hs, 2) if far: n = 2 y_tip0 = crown_y + (0.5 - length) * H for k in range(n): f = (k + 0.5) / n * 0.8 + 0.1 + r.uniform(-0.06, 0.06) # across the mass, inner -> outer xs = xi + (xo - xi) * f pts = [(float(x), float(y)) for x, y in zip(xs, ys)][1:] wmass = float(np.median(np.abs(xo - xi))) w0 = float(np.clip(wmass / n * r.uniform(0.95, 1.35), 0.05 * H, 0.17 * H)) if hs == "long": # fall on past the jaw: flare a little outward, staggered tips (H2-5) yb = pts[-1][1] y_tip = y_tip0 - r.uniform(0.0, 0.25) * H * (1 if k % 2 else 0.5) x_b = pts[-1][0] drift = sgn * r.uniform(-0.02, 0.08) * H for u in np.linspace(0.25, 1.0, 4): pts.append((x_b + drift * u, yb + (y_tip - yb) * u)) elif hs == "bob": xb, yb = pts[-1] pts.append((xb - sgn * 0.05 * H, yb + 0.04 * H)) # the end curls in under the jaw spine = np.array(pts, F32) amp = (0.035 if wavy else 0.012) * H * r.uniform(0.7, 1.3) wl = (0.32 if wavy else 0.9) * H * r.uniform(0.8, 1.25) spine = _wave(spine, amp, wl, r.uniform(0, 2 * np.pi)) lk = Lock(spine, w0, 0.012 * H * r.uniform(0.6, 1.4), "point", "side", int(sgn), z=(-1.5 if far else 1.0) + 0.01 * k, bulge=r.uniform(0.10, 0.30)) HL.locks.append(_keep_off_face(L, lk, s, far))
def _top_locks(L, HL, r, sp, hs, part_th): """clumps on the cap radiating from the parting (H2-4); they make the seams and the top silhouette breaks""" H = L.H yf = lambda f: 0.5 - f cn = L.canon if hs in ("buzz",): n = 0 else: n = {"short": 5, "curly": 0, "long": 4, "bob": 4, "ponytail": 4, "bun": 4}[hs] for i in range(n): side = -1 if i < n / 2 else 1 u = (i + 0.5) / n t_end = math.radians(-80 + 160 * u) ph0 = math.radians(80) root = sp(part_th, ph0) tip = sp(t_end, _phi_at(L, t_end, yf(cn["hairline_y"] + 0.12 + 0.1 * abs(u - .5)))) if hs in ("ponytail", "bun"): # gathering lines run from the hairline to the tie (H2-15) root, tip = tip, sp(math.pi * 0.95, math.radians(35 if hs == "ponytail" else 60)) mid = sp((part_th + t_end) / 2, math.radians(60)) HL.locks.append(Lock(L.proj(np.array([root, mid, tip])), 0.22 * H, 0.02 * H, "point", "top", side, z=0.5 + 0.01 * i, bulge=0.15))
def _bangs(L, HL, r, sp, hs, style, part_th): """bang ribbons from the parting to the forehead (A6: 4-6 ribbons ending at eye level in anime, rounded or pointed tips with V gaps; P-R4: 4-6 clumps with uneven tips; H2-12 parting recipe)""" fr = HL.fringe if fr == "none": return H = L.H yf = lambda f: 0.5 - f cn = L.canon if style == "anime": end_f = cn.get("bang_end_y", 0.58) else: end_f = cn["brow_y"] + (0.02 if fr == "full" else -0.03) n = int(r.integers(4, 7)) if fr == "spiky": n = int(r.integers(5, 8)) span = 0.85 if fr == "full" else 0.65 for i in range(n): u = (i + 0.5) / n if fr == "side": # swept from the parting to one side t_tip = math.radians(-70 * span + 140 * span * u) + (math.radians(10) * np.sign(part_th or 1)) else: t_tip = math.radians(-75 * span + 150 * span * u) ef = end_f - (0.05 + 0.06 * r.random()) * (1 if (i % 2) else 0) - (0.06 * abs(u - .5) if fr == "side" else 0) if fr == "spiky": ef = cn["hairline_y"] + 0.06 + 0.06 * r.random() tip = L.skull(t_tip, _phi_at(L, t_tip, yf(ef))) + np.array([0, 0, 0.012]) root_t = part_th + (t_tip - part_th) * 0.25 root = sp(root_t, math.radians(68)) mid = sp((root_t + t_tip) / 2, _phi_at(L, (root_t + t_tip) / 2, yf(cn["hairline_y"] - 0.02)), L.hair_lift * 0.8) spine = L.proj(np.array([root, mid, tip])) w = (1.9 * L.cranium_r[0] * span / n) * H * 1.25 HL.locks.append(Lock(spine, w, 0.0 if style != "anime" or i % 2 else 0.12 * w, "point" if (style != "anime" or r.random() < .6) else "round", "bang", int(np.sign(u - .5)), z=2.0 + 0.01 * i))
def _ponytail(L, HL, r, sp): """tie behind the head slightly to one side; a question-mark tail with a split tip (H2-15)""" H = L.H side = r.choice([-1, 1]) face_dir = math.sin(math.radians(L.yaw)) back = -1 if face_dir > 0.05 else (1 if face_dir < -0.05 else side) # kit2: the tie sits on the side of the back of the head that shows (a turned head: the near side), and the tail # swings out past the head and neck silhouette so it reads in any view (ink lane 14:58: "man with a ponytail" # drew no tail) cands = [L.proj(sp(math.pi + sd * math.radians(28), math.radians(15))[None])[0] for sd in (-1, 1)] HL.tie = max(cands, key=lambda q: (q[0] - L.pt["head_c"][0]) * back) t0 = HL.tie out = (0.34 if abs(L.yaw) < 15 else 0.28) * H spine = [t0, t0 + np.array([back * out * 0.8, 0.22 * H]), t0 + np.array([back * out, 0.62 * H]), t0 + np.array([back * out * 0.65, 0.95 * H])] zt = -2.5 if abs(L.yaw) < 50 else 1.0 HL.locks.append(Lock(spine, 0.24 * H, 0.0, "point", "tail", back, z=zt, bulge=0.25)) sp2 = [p + np.array([back * 0.04 * H, 0]) for p in spine] sp2[-1] = sp2[-1] + np.array([back * 0.06 * H, -0.08 * H]) HL.locks.append(Lock(sp2, 0.12 * H, 0.0, "point", "tail", back, z=zt + 0.01))
def _bun(L, HL, r, sp): """a bun partly hidden behind the head (H2-16)""" H = L.H c3 = sp(math.pi * 0.92, math.radians(52), L.hair_lift + 0.14) c = L.proj(c3[None])[0] rx, ry = 0.24 * H * (0.9 + 0.2 * r.random()), 0.20 * H * (0.9 + 0.2 * r.random()) t = np.linspace(0, 2 * np.pi, 40, endpoint=False) wob = 1 + 0.04 * np.sin(3 * t + r.uniform(0, 6)) out = np.stack([c[0] + rx * np.cos(t) * wob, c[1] + ry * np.sin(t) * wob], 1) HL.bun = dict(c=c, rx=rx, ry=ry, outline=out, z=-1.0 if abs(L.yaw) < 50 else 0.5) for k in range(3): # inner curves like a ball of yarn a0 = r.uniform(0, 2 * np.pi) arc = np.stack([c[0] + rx * 0.7 * np.cos(a0 + np.linspace(0, 2.2, 6)), c[1] + ry * 0.7 * np.sin(a0 + np.linspace(0, 2.2, 6))], 1) HL.guides.append(arc)
def _curly_lobes(L, HL, r): """curly hair: the cap and back silhouettes become an irregular cloud of lobes (H2-23: never a circle)""" H = L.H
def lobify(P, amp, n_lobes): P = resample(P, 2.0, closed=True) m = len(P) k = np.arange(m) / m * n_lobes ph = r.uniform(0, 1, n_lobes + 1) a = np.abs(np.sin(np.pi * (k + ph[(k.astype(int)) % len(ph)] * 0.3))) amp_i = amp * (0.6 + 0.8 * r.random(n_lobes + 1))[(k.astype(int)) % (n_lobes + 1)] return offset(P, a ** 0.6 * amp_i, closed=True) if HL.cap is not None: # lobes on the outer arc only (the hairline stays) arc = resample(HL.cap_outer, 2.0) m = len(arc) nl = 9 k = np.linspace(0, nl, m) amp = (0.035 + 0.03 * r.random(nl + 1))[np.minimum(k.astype(int), nl)] * H bump = np.abs(np.sin(np.pi * k)) ** 0.7 * amp nrm = offset(arc, 1.0, closed=False) - arc c = arc.mean(0) sgn = np.sign(((arc - c) * nrm).sum(1).mean()) or 1 arc2 = arc + nrm * bump[:, None] * sgn HL.cap_outer = arc2 HL.cap = _assemble_cap(HL) if HL.back is not None: HL.back = lobify(HL.back, 0.05 * H, 11)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663"""figure.kit: the 2D drawing primitives every figure style shares (wave 18, kit lane). Pure numpy + PIL, CPU only.
Generalised from the wave-17 master-copy kits (out/copy17/anime/code/kit2d.py, painted/code/paint.py, the stroke /hatch_family / streamline_hair primitives of ink/code/copy_b.py and the pixel Canvas of pixel/code/copyB.py). Only theMETHODS were taken; no coordinate, palette or glyph pattern of those copies is here.
Coordinates are pixels, x right, y down, pixel centres at +0.5. Colours are RGB in 0..1 floats (np.float32).
CURVES crv(pts, closed=True, n=10, sharp=()) Catmull-Rom through pts; indices in `sharp` are corners (lock tips) resample(P, step) / arclen(P) even spacing along a polyline offset(P, d, closed=True) every point moved d px along the normal (closed: d > 0 = outward) shift(P, dx, dy), scale_about(P, c, s) designed-shadow helpers (A2: the shape shifted toward/away from the light) ribbon(spine, w0, w1, tip='point') closed outline of a tapered ribbon along a spine (a hair lock) profile(n, kind) pen pressure profiles: swell, flick, rflick, ends, even, taperAA CANVAS (analytic anti-aliasing from the exact distance to the outline; no supersampling) cv = Canvas(W, H, bg) cv.img is HxWx3 float32 cv.cover(P) -> HxW coverage of a closed shape; cv.stroke_cov(P, w, kind=None, closed=False) cv.fill(P, col, clip=None, alpha=1) paint a closed shape (returns its coverage, usable as a clip mask) cv.stroke(P, w, col, kind='swell', clip=None, alpha=1) tapered / swelling stroke (w scalar or per point) cv.paint(cov, col, alpha) / cv.paint_rgb(cov, rgbfield) composite any coverage cv.soften(mask, radius) lose edges inside mask (edge budget, P-R5) cv.u8() / cv.save(path)INK LAYER (one channel, max-composited like a pen on paper) ink = Ink(W, H); ink.stroke(P, w, kind, alpha); ink.fill(P, alpha); ink.cov is HxW float32 in 0..1MASKS: union(a, b), inter(a, b), sub(a, b), shape_mask(P, W, H, aa=True)HATCHING: hatch_family(base, n, step, w0, w1, trim0, trim1, rng, jit=.15, bow=0) -> [(pts, w)] (H1-H3: along the form, spacing jitter ~15 %, staggered ends, a slight bow; the band narrows away from the dark edge)FLOW: flow_field(guides, W, H, step) -> theta grid; value_field(W, H, step, base, troughs, crests) -> value grid; streamlines(theta, value, inside, step, rng, min_space, length, ...) -> [(pts, values)] (R1: strokes never cross)PIXEL (no AA, palette keys) pc = PixCanvas(W, H, palette) pc.a is an HxW int16 grid of palette indices (-1 = empty) pc.poly(P, k, mask=None), pc.px(pts, k, only=None), pc.line(pts, k, only=None) (Bresenham + L-elbow drop, X10), pc.stamp(x0, y0, rows, keymap, only=None) (a glyph given as rows of characters, ' ' = leave), pc.mask(keys), pc.nb(m, dx, dy), pc.outline_outside(m, k, only=None), pc.rgb(bg) -> HxWx3 uint8 pixel_line(pts) -> the pixel-perfect pixel list; upscale_nn(img, k)"""import numpy as npfrom PIL import Image, ImageDraw, ImageFilter
F32 = np.float32
# ---------------------------------------------------------------------------------------------------------- curvesdef _cr_seg(p0, p1, p2, p3, t): a = 2 * p1 b = p2 - p0 c = 2 * p0 - 5 * p1 + 4 * p2 - p3 d = -p0 + 3 * p1 - 3 * p2 + p3 return 0.5 * (a + b * t + c * t * t + d * t * t * t)
def _crv_plain(P, closed, n): if len(P) < 2: return P.copy() if closed: Q = np.vstack([P[-1], P, P[0], P[1]]) else: Q = np.vstack([2 * P[0] - P[1], P, 2 * P[-1] - P[-2]]) t = np.linspace(0, 1, n, endpoint=False)[:, None] out = [_cr_seg(Q[i - 1], Q[i], Q[i + 1], Q[i + 2], t) for i in range(1, len(Q) - 2)] if not closed: out.append(P[-1][None]) return np.vstack(out)
def crv(pts, closed=True, n=10, sharp=()): """Catmull-Rom through pts (the decided contour). Indices in `sharp` become corners: the curve is split there, so one outline can mix smooth arcs with sharp lock tips (kit2d.poly_pts method).""" P = np.asarray(pts, float) if not len(sharp): return _crv_plain(P, closed, n) m = len(P) sh = sorted(set(int(i) % m for i in sharp)) if not closed: sh = sorted(set([0, m - 1] + sh)) segs = [] for s, e in zip(sh, sh[1:]): seg = P[s:e + 1] segs.append(_crv_plain(seg, False, n)[:-1] if len(seg) > 2 else np.linspace(seg[0], seg[-1], n + 1)[:-1]) segs.append(P[-1][None]) return np.vstack(segs) segs = [] for j, s in enumerate(sh): e = sh[(j + 1) % len(sh)] idx = list(range(s, e + 1)) if e > s else list(range(s, m)) + list(range(0, e + 1)) seg = P[idx] if len(seg) == 2: segs.append(np.linspace(seg[0], seg[1], n + 1)[:-1]) else: segs.append(_crv_plain(seg, False, n)[:-1]) return np.vstack(segs)
def arclen(P): P = np.asarray(P, float) if len(P) < 2: return np.zeros(len(P)) return np.concatenate([[0.0], np.cumsum(np.hypot(*np.diff(P, axis=0).T))])
def resample(P, step=2.0, closed=False): """points every `step` px along the polyline (closed: round the loop)""" P = np.asarray(P, float) if closed: P = np.vstack([P, P[:1]]) s = arclen(P) if s[-1] < 1e-6: return P[:1].copy() n = max(2, int(np.ceil(s[-1] / step)) + 1) u = np.linspace(0, s[-1], n) out = np.stack([np.interp(u, s, P[:, 0]), np.interp(u, s, P[:, 1])], 1) return out[:-1] if closed else out
def signed_area(P): P = np.asarray(P, float) x, y = P[:, 0], P[:, 1] return 0.5 * float(np.sum(x * np.roll(y, -1) - np.roll(x, -1) * y))
def normals(P, closed=False): """unit left normals of a polyline (y down: the left of travel)""" P = np.asarray(P, float) if closed: t = np.roll(P, -1, 0) - np.roll(P, 1, 0) else: t = np.gradient(P, axis=0) t /= np.linalg.norm(t, axis=1, keepdims=True) + 1e-9 return np.stack([t[:, 1], -t[:, 0]], 1)
def offset(P, d, closed=True): """move every point d px along the normal. closed shapes: d > 0 grows the shape (outward), d < 0 shrinks it. open curves: d > 0 = the left of travel. d may be per point.""" P = np.asarray(P, float) N = normals(P, closed) if closed and signed_area(P) < 0: # y-down pixels: positive shoelace area -> the left normal points outward N = -N d = np.asarray(d, float) return P + N * (d[:, None] if d.ndim else d)
def shift(P, dx, dy): return np.asarray(P, float) + np.array([dx, dy], float)
def scale_about(P, c, s): c = np.asarray(c, float) return c + (np.asarray(P, float) - c) * np.asarray(s, float)
def rotate_about(P, c, ang): c = np.asarray(c, float) ca, sa = np.cos(ang), np.sin(ang) Q = np.asarray(P, float) - c return c + np.stack([Q[:, 0] * ca - Q[:, 1] * sa, Q[:, 0] * sa + Q[:, 1] * ca], 1)
def ellipse(c, rx, ry, n=48, rot=0.0): t = np.linspace(0, 2 * np.pi, n, endpoint=False) E = np.stack([rx * np.cos(t), ry * np.sin(t)], 1) if rot: E = rotate_about(E, (0, 0), rot) return E + np.asarray(c, float)
def profile(n, kind="swell", ends=0.15): """pen pressure along a stroke of n points, peak 1 (ink copy: every stroke a pen stroke, I3)""" t = np.linspace(0, 1, max(n, 1)) if kind in (None, "even"): return np.ones(n) if kind == "swell": # in thin, full in the middle, flicked out thin return 0.2 + 0.8 * np.sin(np.pi * t) ** 0.7 if kind == "flick": # firm start (root / dark edge), lifted off at the end return 0.25 + 0.75 * (1 - t) ** 0.8 if kind == "rflick": return 0.25 + 0.75 * t ** 0.8 if kind == "ends": # a mouth slit: darkest at the corners return 0.45 + 0.55 * np.abs(2 * t - 1) if kind == "taper": # constant body with short tapered ends (an anime outline) env = np.clip(np.minimum(t, 1 - t) / max(ends, 1e-3), 0, 1) ** .6 return .25 + .75 * env raise ValueError(kind)
def ribbon(spine, w0, w1=0.0, tip="point", n=8, bulge=0.0): """closed outline of a ribbon along `spine` (root -> tip), width w0 at the root easing to w1 at the tip. tip: 'point' (a lock tip), 'round', or 'flat' (a scissor cut). bulge > 0 swells the middle (a clump). Returns (outline, sharp_indices) ready for crv(..., sharp=...).""" S = resample(crv(spine, closed=False, n=n), max(1.0, arclen(spine)[-1] / 40.0)) if len(spine) > 2 else resample(spine, 2.0) m = len(S) t = np.linspace(0, 1, m) w = w0 + (w1 - w0) * t ** 1.2 + bulge * np.sin(np.pi * t) * w0 if tip == "round": w = w * np.clip(np.sqrt(np.clip((1 - t) / 0.12, 0, 1)), 0.25, 1) N = normals(S) L = S + N * (w / 2)[:, None] R = S - N * (w / 2)[:, None] if tip == "point": out = np.vstack([L[:-1], S[-1:], R[:-1][::-1]]) return out, [0, m - 1, len(out) - 1] out = np.vstack([L, R[::-1]]) return out, [0, m - 1, m, len(out) - 1]
# ---------------------------------------------------------------------------------------------------------- coveragedef _seg_dist(X, Y, A, B): """distance from points (X, Y) (1-D arrays) to segments A->B (Mx2): returns min distance, seg index, param t""" best = np.full(X.shape, 1e9, F32) bi = np.zeros(X.shape, np.int32) bt = np.zeros(X.shape, F32) CH = 64 for s in range(0, len(A), CH): a, b = A[s:s + CH], B[s:s + CH] dx = (b[:, 0] - a[:, 0])[:, None] dy = (b[:, 1] - a[:, 1])[:, None] L2 = dx * dx + dy * dy + 1e-9 px = X[None] - a[:, 0][:, None] py = Y[None] - a[:, 1][:, None] t = np.clip((px * dx + py * dy) / L2, 0, 1) d = np.hypot(px - t * dx, py - t * dy) k = np.argmin(d, 0) dm = d[k, np.arange(d.shape[1])] m = dm < best best = np.where(m, dm, best) bi = np.where(m, k + s, bi) bt = np.where(m, t[k, np.arange(d.shape[1])], bt) return best, bi, bt
def shape_mask(P, W, H, aa=True): """coverage 0..1 (HxW float32) of the closed shape P. aa=False: the hard pixel-centre test (pixel mode).""" P = np.asarray(P, float) cov = np.zeros((H, W), F32) if len(P) < 3: return cov x0 = int(max(0, np.floor(P[:, 0].min() - 2))) y0 = int(max(0, np.floor(P[:, 1].min() - 2))) x1 = int(min(W, np.ceil(P[:, 0].max() + 2))) y1 = int(min(H, np.ceil(P[:, 1].max() + 2))) if x1 <= x0 or y1 <= y0: return cov im = Image.new("L", (x1 - x0, y1 - y0), 0) pts = [(float(x - x0 - .5), float(y - y0 - .5)) for x, y in P] # PIL samples pixel centres at integers ImageDraw.Draw(im).polygon(pts, fill=255) inside = np.asarray(im) > 127 if not aa: cov[y0:y1, x0:x1] = inside return cov # the band where coverage is fractional: pixels within 1 px of the outline; exact sign + distance only there band = Image.new("L", (x1 - x0, y1 - y0), 0) ImageDraw.Draw(band).line(pts + [pts[0]], fill=255, width=3) bm = np.asarray(band) > 0 ys, xs = np.nonzero(bm) loc = inside.astype(F32) if len(xs): from matplotlib.path import Path X = (xs + x0 + .5).astype(F32) Y = (ys + y0 + .5).astype(F32) A = P.astype(F32) B = np.roll(A, -1, 0) d, _, _ = _seg_dist(X, Y, A, B) ins = Path(P).contains_points(np.stack([X, Y], 1)) loc[ys, xs] = np.clip(.5 + np.where(ins, d, -d), 0, 1) cov[y0:y1, x0:x1] = loc return cov
def stroke_mask(P, w, W, H, kind=None, closed=False): """coverage of a stroke along polyline P with width w (scalar or per point), optional pressure profile""" P = np.asarray(P, float) if closed and len(P) > 2: P = np.vstack([P, P[:1]]) n = len(P) cov = np.zeros((H, W), F32) if n < 2: return cov ws = np.broadcast_to(np.asarray(w, float), (n,)).copy() if kind: ws = ws * profile(n, kind) for i in range(n - 1): a, b = P[i], P[i + 1] w0, w1 = ws[i], ws[i + 1] r = max(w0, w1) / 2 + 1.5 x0, x1 = int(max(0, np.floor(min(a[0], b[0]) - r))), int(min(W, np.ceil(max(a[0], b[0]) + r))) y0, y1 = int(max(0, np.floor(min(a[1], b[1]) - r))), int(min(H, np.ceil(max(a[1], b[1]) + r))) if x1 <= x0 or y1 <= y0: continue yy, xx = np.mgrid[y0:y1, x0:x1].astype(F32) + .5 ba = b - a L2 = max(float(ba @ ba), 1e-9) h = np.clip(((xx - a[0]) * ba[0] + (yy - a[1]) * ba[1]) / L2, 0, 1) d = np.hypot(xx - a[0] - h * ba[0], yy - a[1] - h * ba[1]) ww = (w0 + (w1 - w0) * h) / 2 c = np.clip(ww + .5 - d, 0, 1) if max(w0, w1) < 1.0: # thinner than a pixel: keep the width as density, not a fake 1 px line c = c * max(w0, w1) cov[y0:y1, x0:x1] = np.maximum(cov[y0:y1, x0:x1], c) return cov
def union(a, b): return np.maximum(a, b)
def inter(a, b): return a * b
def sub(a, b): return a * (1 - b)
def blur(m, r): if r <= 0: return m im = Image.fromarray(np.clip(m * 255, 0, 255).astype(np.uint8)) return np.asarray(im.filter(ImageFilter.GaussianBlur(r)), F32) / 255
def col(c): """an (r, g, b) in 0..255 or 0..1, or '#rrggbb', -> float32 0..1""" if isinstance(c, str): h = c.lstrip("#") return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], F32) / 255 c = np.asarray(c, F32) return c / 255 if c.max() > 1.0 else c
class Canvas: """float RGB canvas; every primitive returns its coverage so it can be reused as a clip mask"""
def __init__(self, W, H=None, bg=(1, 1, 1)): H = W if H is None else H self.W, self.H = int(W), int(H) self.img = np.ones((self.H, self.W, 3), F32) * col(bg)[None, None]
def cover(self, P, aa=True): return shape_mask(P, self.W, self.H, aa)
def stroke_cov(self, P, w, kind=None, closed=False): return stroke_mask(P, w, self.W, self.H, kind, closed)
def paint(self, cov, c, alpha=1.0): a = (cov * alpha)[..., None] self.img = self.img * (1 - a) + col(c)[None, None] * a
def paint_rgb(self, cov, rgb, alpha=1.0): a = (cov * alpha)[..., None] self.img = self.img * (1 - a) + np.asarray(rgb, F32) * a
def fill(self, P, c, clip=None, alpha=1.0, aa=True): cv = self.cover(P, aa) if clip is not None: cv = cv * clip self.paint(cv, c, alpha) return cv
def stroke(self, P, w, c, kind="swell", clip=None, alpha=1.0, closed=False): cv = self.stroke_cov(P, w, kind, closed) if clip is not None: cv = cv * clip self.paint(cv, c, alpha) return cv
def soften(self, mask, radius): """lose edges: blend toward a blurred copy inside mask (P-R5 edge budget after the fact)""" im = Image.fromarray(self.u8()).filter(ImageFilter.GaussianBlur(radius)) b = np.asarray(im, F32) / 255 self.img = self.img * (1 - mask[..., None]) + b * mask[..., None]
def u8(self): return (np.clip(self.img, 0, 1) * 255 + .5).astype(np.uint8)
def save(self, path): Image.fromarray(self.u8()).save(path) return path
class Ink: """one ink channel (0 = paper, 1 = full ink), strokes max-composited like a pen"""
def __init__(self, W, H=None): H = W if H is None else H self.W, self.H = int(W), int(H) self.cov = np.zeros((self.H, self.W), F32)
def stroke(self, P, w, kind="swell", alpha=1.0, clip=None): c = stroke_mask(P, w, self.W, self.H, kind) * alpha if clip is not None: c = c * clip self.cov = np.maximum(self.cov, c) return c
def fill(self, P, alpha=1.0, clip=None): c = shape_mask(P, self.W, self.H) * alpha if clip is not None: c = c * clip self.cov = np.maximum(self.cov, c) return c
def over(self, paper=(.93, .93, .92), ink=(.07, .07, .07)): p, k = col(paper), col(ink) return p[None, None] * (1 - self.cov[..., None]) + k[None, None] * self.cov[..., None]
# ---------------------------------------------------------------------------------------------------------- hatchingdef hatch_family(base, n, step, w0, w1, trim0=(0, 0), trim1=(0, 0), rng=None, jit=0.15, bow=0.0, smooth=True): """n lines parallel to `base` (an open curve along the form: H1), offset k*step to its left (negative step = right), weight w0 -> w1 across the family, each trimmed at (start, end) fractions growing from trim0 to trim1 so the band narrows away from the dark edge (H2). Never ruled (H3): spacing jitter `jit` (fraction of step, ~15 %), staggered ends, an optional bow (px) bending each line. Returns [(pts, width)] for Canvas.stroke / Ink.stroke.""" rng = np.random.default_rng(0) if rng is None else rng c = crv(base, closed=False, n=10) if smooth and len(base) > 2 else np.asarray(base, float) c = resample(c, 1.5) out = [] t = np.linspace(0, 1, len(c)) for k in range(n): f = k / max(1, n - 1) d = k * step + rng.normal(0, abs(step) * jit) line = offset(c, d, closed=False) if bow: line = offset(line, bow * rng.uniform(.5, 1.0) * np.sin(np.pi * t), closed=False) a = trim0[0] + (trim1[0] - trim0[0]) * f + rng.uniform(0, .06) b = trim0[1] + (trim1[1] - trim0[1]) * f + rng.uniform(0, .06) i0, i1 = int(a * len(line)), int((1 - b) * len(line)) if i1 - i0 < 3: continue out.append((line[i0:i1], w0 + (w1 - w0) * f)) return out
# ---------------------------------------------------------------------------------------------------------- flow fieldsdef flow_field(guides, W, H, step=4, soft=60.0): """orientation field (radians, sign-free) on a grid of `step` px from a few guide curves (R1): inverse-distance blend of the nearest guide tangent of each guide, blended as doubled angles so opposite directions agree""" ys, xs = np.mgrid[0:H:step, 0:W:step].astype(F32) acc = np.zeros(xs.shape + (2,), F32) for g in guides: c = resample(np.asarray(g, float), max(2.0, step)) if len(c) < 2: continue t = np.gradient(c, axis=0) ang = np.arctan2(t[:, 1], t[:, 0]) d2 = np.full(xs.shape, 1e12, F32) a2 = np.zeros(xs.shape, F32) for q, an in zip(c, ang): dd = (xs - q[0]) ** 2 + (ys - q[1]) ** 2 m = dd < d2 d2[m] = dd[m] a2[m] = an wgt = 1.0 / (d2 + soft) ** 1.5 acc[..., 0] += wgt * np.cos(2 * a2) acc[..., 1] += wgt * np.sin(2 * a2) return 0.5 * np.arctan2(acc[..., 1], acc[..., 0])
def dist_to_curve(c, W, H, step=4): ys, xs = np.mgrid[0:H:step, 0:W:step].astype(F32) d = np.full(xs.shape, 1e12, F32) for q in resample(np.asarray(c, float), max(2.0, step)): d = np.minimum(d, (xs - q[0]) ** 2 + (ys - q[1]) ** 2) return np.sqrt(d)
def value_field(W, H, step=4, base=0.3, troughs=(), crests=()): """darkness field 0..1 on the flow grid: troughs (curve, amp, sigma px) add dark, crests (curve, amp, sigma) lift it""" v = np.full(((H + step - 1) // step, (W + step - 1) // step), base, F32) for c, amp, sg in troughs: v += amp * np.exp(-(dist_to_curve(c, W, H, step) / sg) ** 2) for c, amp, sg in crests: v -= amp * np.exp(-(dist_to_curve(c, W, H, step) / sg) ** 2) return np.clip(v, 0, 1)
def streamlines(theta, value, inside, step, rng, min_space=3.0, length=(50, 170), seed_step=6, vmin=0.12, h=2.0, accept=lambda v, r: r < .35 + .65 * v): """trace streamlines through the orientation grid, inside the mask (HxW at full res or grid res), each kept `min_space` px from the others (occupancy grid: strokes never cross, R1). Returns [(pts Nx2, values N)]. Width from value is the caller's choice (ink: w = 0.6 + 3.8 v^1.3).""" gh, gw = theta.shape full = inside.shape != theta.shape Hpx, Wpx = (inside.shape if full else (gh * step, gw * step)) cs = max(1.0, float(min_space)) occ = np.zeros((int(Hpx / cs) + 2, int(Wpx / cs) + 2), np.int32)
def look(p): i, j = int(p[1] // step), int(p[0] // step) if not (0 <= i < gh and 0 <= j < gw): return None if full: yi, xi = int(p[1]), int(p[0]) if not (0 <= yi < Hpx and 0 <= xi < Wpx): return None ins = inside[yi, xi] > .5 else: ins = inside[i, j] > .5 return theta[i, j], value[i, j], ins
seeds = [(x + rng.uniform(0, seed_step), y + rng.uniform(0, seed_step)) for y in np.arange(0, Hpx, seed_step) for x in np.arange(0, Wpx, seed_step)] rng.shuffle(seeds) out = [] sid = 0 for sx, sy in seeds: q = look((sx, sy)) if q is None or not q[2] or q[1] < vmin + .03 or not accept(q[1], rng.random()): continue oi, oj = int(sy // cs), int(sx // cs) if occ[oi, oj]: continue sid += 1 Lmax = rng.uniform(*length) halves = [] for sgn in (1, -1): p = np.array([sx, sy], float) prev = None pts = [] n = 0 while n * h < Lmax / 2: q = look(p) if q is None or not q[2] or q[1] < vmin: break d = np.array([np.cos(q[0]), np.sin(q[0])]) * sgn if prev is not None and d @ prev < 0: d = -d oi, oj = int(p[1] // cs), int(p[0] // cs) if n > 1 and occ[oi, oj] not in (0, sid): break pts.append((p.copy(), q[1])) prev = d p = p + d * h n += 1 halves.append(pts) allp = halves[1][::-1] + halves[0][1:] if halves[1] else halves[0] if len(allp) < 5: continue P = np.array([a for a, _ in allp]) V = np.array([v for _, v in allp]) for a in P: occ[int(a[1] // cs), int(a[0] // cs)] = sid out.append((P, V)) return out
# ---------------------------------------------------------------------------------------------------------- pixeldef pixel_line(pts): """pixel-perfect polyline (X10): Bresenham through integer points, then drop L-corner doubles""" pts = [(int(round(x)), int(round(y))) for x, y in pts] out = [] if len(pts) == 1: return pts for (x0, y0), (x1, y1) in zip(pts[:-1], pts[1:]): dx, dy = abs(x1 - x0), -abs(y1 - y0) sx, sy = (1 if x1 > x0 else -1), (1 if y1 > y0 else -1) e = dx + dy x, y = x0, y0 while True: if not out or out[-1] != (x, y): out.append((x, y)) if (x, y) == (x1, y1): break e2 = 2 * e if e2 >= dy: e += dy x += sx if e2 <= dx: e += dx y += sy if len(out) < 3: return out keep = [out[0]] for i in range(1, len(out) - 1): p, q, r = keep[-1], out[i], out[i + 1] if (p[0] == q[0] or p[1] == q[1]) and (q[0] == r[0] or q[1] == r[1]) and p[0] != r[0] and p[1] != r[1]: continue # q is an elbow: p and r already touch diagonally keep.append(q) keep.append(out[-1]) return keep
class PixCanvas: """a palette-index grid: no anti-aliasing anywhere (X10). palette: list of RGB (0..255 or 0..1)."""
def __init__(self, W, H=None, palette=()): H = W if H is None else H self.W, self.H = int(W), int(H) self.a = np.full((self.H, self.W), -1, np.int16) self.palette = [tuple(col(c)) for c in palette]
def key(self, rgb): """add a colour to the palette (if new) and return its index""" c = tuple(col(rgb)) if c not in self.palette: self.palette.append(c) return self.palette.index(c)
def poly(self, P, k, mask=None, only=None): m = shape_mask(np.asarray(P, float) + .5, self.W, self.H, aa=False) > .5 if mask is not None: m &= mask if only is not None: m &= np.isin(self.a, list(only)) self.a[m] = k return m
def px(self, pts, k, only=None): for x, y in pts: x, y = int(x), int(y) if 0 <= x < self.W and 0 <= y < self.H and (only is None or self.a[y, x] in only): self.a[y, x] = k
def line(self, pts, k, only=None): self.px(pixel_line(pts), k, only)
def stamp(self, x0, y0, rows, keymap, only=None, flip=False): """a glyph: rows of characters, keymap char -> palette index, ' ' = leave; flip mirrors it""" for j, r in enumerate(rows): r = r[::-1] if flip else r for i, ch in enumerate(r): if ch != " ": self.px([(x0 + i, y0 + j)], keymap[ch], only)
def mask(self, keys): return np.isin(self.a, list(keys))
def nb(self, m, dx, dy): """out[y, x] = m[y + dy, x + dx] (False outside)""" out = np.zeros_like(m) H, W = m.shape ys, xs = slice(max(dy, 0), H + min(dy, 0)), slice(max(dx, 0), W + min(dx, 0)) yd, xd = slice(max(-dy, 0), H + min(-dy, 0)), slice(max(-dx, 0), W + min(-dx, 0)) out[yd, xd] = m[ys, xs] return out
def outline_outside(self, m, k, only=None, diag=False): """1 px ring of key k just outside mask m (4-neighbour; diag=True adds corners)""" ring = np.zeros_like(m) dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)] + ([(1, 1), (1, -1), (-1, 1), (-1, -1)] if diag else []) for dx, dy in dirs: ring |= self.nb(m, dx, dy) ring &= ~m if only is not None: ring &= np.isin(self.a, list(only)) self.a[ring] = k return ring
def rgb(self, bg=(1, 1, 1)): pal = np.array(self.palette + [tuple(col(bg))], F32) idx = np.where(self.a < 0, len(self.palette), self.a) return (pal[idx] * 255 + .5).astype(np.uint8)
def upscale_nn(img, k): return np.repeat(np.repeat(np.asarray(img), k, 0), k, 1)
def resize_to(img, size, nearest=False): im = Image.fromarray(np.asarray(img, np.uint8)) if im.size == (size, size): return np.asarray(im) return np.asarray(im.resize((size, size), Image.NEAREST if nearest else Image.LANCZOS))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730"""figure.layout: Person + Pose + style canon -> a named 2D landmark layout (wave 18, kit lane; C4, C9, X9).
from pydraw.figure.layout import Person, Pose, build P = Person.from_text("portrait of an old woman with curly grey hair", seed=3) pose = Pose.from_text("... three-quarter view", seed=3) L = build(P, pose, style="anime", size=512, framing="portrait") L.pt["eye_L"] # 2D pixel point; L.eyes["L"]["outline"] etc.
How it is built (2D-first, 3D-assisted): 1 the wave-17 head landmarks (pydraw.anatomy.head.landmarks, H = 1 crown->chin, y up, z = face direction, x = the subject's left) for the person's age and sex; 2 the STYLE CANON (figure.canon.resolve) remaps them: feature heights piecewise-linearly (anime eyes at 0.62-0.68 H), widths per height band (face, jaw, chin), eye spacing / size, nose and mouth width; 3 the head is rotated by yaw / pitch / roll and projected orthographically (so three-quarter views are right: the near cheek widens, the far eye foreshortens, the nose moves toward the turned side); the face plate silhouette is the hull of the projected cranium cap + cheeks + jaw + chin (X9: far contour straight, chin pointed in 3/4); 4 the neck rises from behind the jaw under the ear (H17 N2) and the shoulders turn with the TORSO yaw, which is a fraction of the head yaw (P-R8 contrapposto), so head and torso separate; 5 framing: head with hair ~70% of a portrait frame (X9; canon head_in_frame range per style), looking room on the side the face points to.
Prompt words (kit2): "<colour> skin|skinned|complexion" beats hair words; bare colour words count as skin only before aperson noun; "wavy" = Person.wavy (any length); beard colour words -> Person.beard_color (and L.beard['color'],V.materials['beard']); "bangs / fringe / side-swept / slicked back" -> Person.fringe; Pose.light_side from "light /lit / window light from the (upper) left|right" (-1 / +1, viewer's frame); "turned / facing / looking (to the) left".
Sign conventions: yaw > 0 = the face turns toward the viewer's RIGHT (+x in the image); then the subject's LEFT side(+x, names *_L) is the FAR side. pitch > 0 = looking up. roll > 0 = the head tilts clockwise on screen.Image coordinates: pixels, x right, y DOWN.
Layout fields (all 2D arrays in pixels unless said): size, H (head height crown->chin in px), style, framing, yaw/pitch/roll (deg), torso_yaw, near ('L'/'R'), far, light_side (-1 light from the viewer's left, +1 right), light (3-vector toward the light, image frame) pt[name] points: crown, hairline, stoss, nose_root, nose_tip, nose_base, nose_wing_L/R, mouth_L/R, mouth_c, lip_top, lip_bot, chin, chin_front, jaw_angle_L/R, cheekbone_L/R, zygion_L/R, ear_top_L/R, ear_bot_L/R, eye_L/R, brow_in_L/R, brow_mid_L/R, brow_out_L/R, neck_top, pit, c7, shoulder_L/R (acromion), deltoid_L/R, head_c (centre of the face plate) z[name] depth toward the viewer in head units (bigger = nearer), for z order face closed outline of the face plate (skin silhouette of the head without ears) neck closed outline; torso closed outline of shoulders / chest down past the frame; chest_skin the skin inside the neckline; neckline open curve; clavicle_L/R open curves; midline open curve (stoss -> nose -> mouth -> chin); jaw_L/R open curves (jaw angle -> chin) ears[s] dict(outline, visible (bool), over_face (bool: draw after the face plate), c) eyes[s] dict(c, outline (closed), upper (open lid curve inner->outer), lower, w, h (px), fs (foreshortening 0..1), far (bool), roll (rad), inner, outer) brows[s] open curve inner->outer; mouth: dict(line (open, L->R), upper (closed upper lip), lower, w) nose: dict(tip, base, wing_L, wing_R, bridge (open curve), side (open curve on the shadow side)) cranium closed outline of the skull cap silhouette (for the hair shell); canon (the resolved canon dict) proj(p3) project head-frame 3D points (canon-remapped) to pixels; skull(theta, phi) a 3D point on the cranium"""import mathimport reimport numpy as npfrom . import canon as C
F32 = np.float32
# ------------------------------------------------------------------------------------------------ person and poseclass Person: """who is drawn: age (years), sex (0 female .. 1 male), build (0 slim .. 1 heavy), skin (0 very light .. 1 very dark), hair_style (short, long, bob, ponytail, curly, bun, buzz, bald), hair_color (a word or None = seeded), eye_color, cloth_color, beard (None/'short'/'full'/'mustache'), beard_color (a word or None = the hair colour), glasses, wavy (bool: a wave in the locks, any length; 'curly' stays its own style), seed"""
def __init__(self, age=30.0, sex=0.0, build=0.5, skin=0.25, hair_style="long", hair_color=None, eye_color=None, cloth_color=None, beard=None, glasses=False, seed=0, expression="neutral", wavy=False, beard_color=None, fringe=None): self.age, self.sex, self.build, self.skin = float(age), float(sex), float(build), float(skin) self.hair_style, self.hair_color, self.eye_color = hair_style, hair_color, eye_color self.cloth_color, self.beard, self.glasses, self.seed = cloth_color, beard, glasses, int(seed) self.expression = expression self.wavy, self.beard_color = bool(wavy), beard_color # kit2: added fields (API stays: nothing renamed) self.fringe = fringe # None | 'none' | 'full' | 'side' | 'spiky' (asked)
def __repr__(self): return ("Person(age=%g, sex=%g, build=%g, skin=%.2f, hair=%s %s, beard=%s, seed=%d)" % (self.age, self.sex, self.build, self.skin, self.hair_color, self.hair_style, self.beard, self.seed))
@classmethod def from_text(cls, text, seed=0, scene=None): t = " " + " ".join(re.findall(r"[a-z0-9/\-]+", text.lower())) + " " r = C.rng_for(seed, "person", t) has = lambda *ws: any((" " + w + " ") in t for w in ws) # sex if has("bearded", "beard", "mustache", "moustache") and not has("woman", "girl", "lady"): sex = 1.0 elif has("woman", "women", "girl", "lady", "female", "mother", "grandmother", "queen", "she", "her", "princess", "actress", "daughter", "wife", "bride", "nun"): sex = 0.0 elif has("man", "men", "boy", "male", "father", "grandfather", "king", "he", "his", "gentleman", "prince", "son", "husband", "monk", "guy"): sex = 1.0 else: sex = float(r.random() < .5) # age age = float(r.uniform(24, 42)) for words, a in ((("baby", "infant", "newborn"), 1.0), (("toddler",), 3.0), (("child", "kid", "little girl", "little boy", "schoolgirl", "schoolboy"), 7.0), (("teen", "teenage", "teenager", "adolescent"), 15.0), (("boy", "girl"), 10.0), (("young",), 23.0), (("middle-aged", "middle aged", "mature"), 50.0), (("old", "elderly", "aged", "grandmother", "grandfather", "grandma", "grandpa", "senior"), 74.0)): if has(*words): age = a break if has("young woman", "young man", "young lady"): age = 23.0 # build build = 0.5 if has("slim", "thin", "skinny", "slender", "petite"): build = 0.2 elif has("heavy", "fat", "chubby", "stocky", "plump", "muscular", "burly", "large"): build = 0.85 # skin. A colour word written right before "skin / skinned / complexion / skin tone" wins outright (anime lane # 15:02: "a white bun and brown skin" read as light skin, because 'white' came first); otherwise a skin word # counts only when it is not the colour of a hair / beard / garment noun. skin = None m = re.search(r"\b(very dark|very light|very pale|dark brown|deep brown|light brown|medium brown|golden brown|" r"olive|tan|tanned|brown|dark|deep|black|ebony|light|fair|pale|white|medium|beige|bronze|" r"caramel|porcelain|ivory|freckled)[ -](?:skin|skinned|complexion|skin tone|toned)\b", t) if m: skin = _SKIN_PHRASE.get(m.group(1), _skin_words().get(m.group(1))) if skin is None: for w, v in sorted(_skin_words().items(), key=lambda kv: -len(kv[0])): if not has(w) or re.search(r"\b" + re.escape(w) + r"[ -]+(?:[\w-]+[ -]+)?" + _NOT_SKIN_NOUN, t): continue # a bare colour / light word ('light', 'dark', 'white', 'brown', ...) is a skin word only when it # describes the person ("a black woman", "a pale young man"), never "light from the left" if w in _AMBIG_SKIN and not re.search(r"\b" + re.escape(w) + r"[ -]+(?:[\w-]+[ -]+)?" + _PERSON_NOUN, t): continue skin = v break if skin is None: skin = float(np.clip(r.choice([0.05, 0.15, 0.25, 0.35, 0.5, 0.65, 0.8, 0.9]) + r.normal(0, .03), 0, 1)) # hair colour hc = None m = re.search(r"\b(black|dark|brown|brunette|chestnut|auburn|red|ginger|copper|blonde|blond|golden|platinum|" r"grey|gray|silver|white|blue|pink|purple|green|teal|orange)(?:[ -]haired|\s+(?:(?!beard|bearded|skin|eyes|eyed|" r"moustache|mustache|stubble|and|with)[\w-]+\s+){0,2}(?:hair|bob|bun|" r"ponytail|curls|braid|braids|afro|locks|mane))", t) if m: hc = m.group(1) elif has("blonde", "blond"): hc = "blonde" elif has("redhead", "red-haired"): hc = "red" elif has("brunette"): hc = "brunette" # hair style hs = None for words, s in ((("bald",), "bald"), (("ponytail", "pony tail", "pony-tail"), "ponytail"), (("bun", "topknot", "updo", "chignon"), "bun"), (("curly", "curls", "afro", "coily", "frizzy", "ringlets"), "curly"), (("bob", "shoulder-length", "shoulder length", "bobbed"), "bob"), (("buzz", "buzzcut", "buzz cut", "crew cut", "shaved"), "buzz"), (("long",), "long"), (("short",), "short")): if has(*words): hs = s break # wavy is its own texture (ink lane 14:58: "wavy" drew curls): a length style + Person.wavy wavy = has("wavy", "waves", "wavy-haired", "beach waves", "tousled") if hs is None and wavy: hs = "short" if sex > .5 else "long" if hs is None: if sex > .5: hs = "bald" if age > 60 and r.random() < .25 else ("short" if r.random() < .85 else "curly") else: hs = ["long", "long", "bob", "ponytail", "bun", "curly", "short"][int(r.integers(0, 7))] if age < 2.5 and hs not in ("bald",): hs = "short" # eyes, clothes, beard, glasses ec = None m = re.search(r"\b(blue|green|brown|hazel|grey|gray|amber|dark|red|purple|violet)[ -]eyed|\b(blue|green|brown|" r"hazel|grey|gray|amber|dark|red|purple|violet)\s+eyes", t) if m: ec = m.group(1) or m.group(2) cc = None m = re.search(r"\b(red|blue|navy|green|yellow|white|black|grey|gray|brown|purple|pink|orange|beige|teal)\s+" r"(?:\w+\s+)?(shirt|t-shirt|dress|sweater|jacket|top|coat|hoodie|blouse|suit|jumper|cardigan|" r"robe|tunic|uniform|scarf|kimono)", t) if m: cc = m.group(1) beard, beard_color = None, None if sex > .5 and age >= 16: if has("stubble", "goatee", "short beard", "stubbled", "five o'clock shadow"): beard = "short" elif has("beard", "bearded", "beards"): beard = "full" elif has("mustache", "moustache", "mustached", "moustached"): beard = "mustache" m = re.search(r"\b(black|dark|brown|red|ginger|auburn|blonde|blond|golden|grey|gray|silver|white|salt-and-pepper)" r"\s+(?:[\w-]+\s+)?(?:beard|mustache|moustache|stubble|goatee)", t) if beard and m: beard_color = {"salt-and-pepper": "grey", "gray": "grey", "blond": "blonde", "ginger": "red"}.get(m.group(1), m.group(1)) if hc is None and beard_color is not None and hs != "bald": hc = beard_color # unprompted hair follows the beard ("an old man with a grey beard") # fringe asked for in words (None = the hair layout's style / seed rule decides) fringe = None if re.search(r"\b(no bangs|no fringe|without bangs|slicked[ -]back|swept[ -]back|bare forehead|high forehead)\b", t): fringe = "none" elif re.search(r"\b(side[ -]swept|side bangs|side fringe|swept bangs|side part(?:ed)?)\b", t): fringe = "side" elif re.search(r"\b(spiky|spikey|spiked)\b", t): fringe = "spiky" elif re.search(r"\b(bangs|fringe|blunt bangs)\b", t): fringe = "full" glasses = has("glasses", "spectacles", "eyeglasses", "bespectacled") expr = "smile" if has("smile", "smiling", "happy", "cheerful", "grin", "grinning") else "neutral" return cls(age=age, sex=sex, build=build, skin=skin, hair_style=hs, hair_color=hc, eye_color=ec, cloth_color=cc, beard=beard, glasses=glasses, seed=seed, expression=expr, wavy=wavy, beard_color=beard_color, fringe=fringe)
_SKIN_PHRASE = {"very dark": 0.95, "very light": 0.04, "very pale": 0.0, "dark brown": 0.8, "deep brown": 0.85, "light brown": 0.5, "medium brown": 0.6, "golden brown": 0.5, "deep": 0.92, "medium": 0.35, "beige": 0.2, "bronze": 0.5, "caramel": 0.55, "porcelain": 0.02, "ivory": 0.05}_NOT_SKIN_NOUN = (r"(?:hair|haired|hat|shirt|eyes|eyed|dress|coat|jacket|sweater|background|top|hoodie|suit|cap|scarf|" r"beard|bearded|bun|bob|ponytail|curls|braid|braids|locks|mane|moustache|mustache|stubble|goatee|" r"light|lighting|ground|wall|backdrop|glasses|robe|cloak|tunic|blouse|clothes|clothing)\b")_AMBIG_SKIN = {"light", "dark", "white", "black", "brown", "pale", "fair", "tan"}_PERSON_NOUN = (r"(?:man|woman|men|women|girl|boy|person|lady|child|kid|guy|gentleman|teen|teenager|grandmother|" r"grandfather|grandma|grandpa|mother|father|baby|toddler|king|queen|prince|princess|elder|nun|monk)\b")
def _skin_words(): from .value import SKIN_WORDS return SKIN_WORDS
class Pose: """head yaw / pitch / roll in degrees (see the module docstring for signs); torso_yaw defaults to a fraction of the head yaw (P-R8: separate head and torso yaw)"""
def __init__(self, yaw=0.0, pitch=0.0, roll=0.0, torso_yaw=None, light_side=None): self.yaw, self.pitch, self.roll = float(yaw), float(pitch), float(roll) self.torso_yaw = 0.35 * self.yaw if torso_yaw is None else float(torso_yaw) self.light_side = light_side # kit2: -1 light from the viewer's left, +1 right, None = layout picks
def __repr__(self): return "Pose(yaw=%.0f, pitch=%.0f, roll=%.0f, torso=%.0f)" % (self.yaw, self.pitch, self.roll, self.torso_yaw)
@classmethod def from_text(cls, text, seed=0): t = " " + " ".join(re.findall(r"[a-z0-9/\-]+", text.lower())) + " " r = C.rng_for(seed, "pose", t) has = lambda *ws: any((" " + w + " ") in t for w in ws) sgn = 1.0 if r.random() < .5 else -1.0 # the turn direction in the viewer's frame ("turned left" = the face points to the image left), with the # little words people put in between (ink lane 14:58: "turned to the left" was ignored) md = re.search(r"\b(?:turned|turning|turns|facing|faces|looking|looks|glancing|gazing|angled|head turned)\s+" r"(?:slightly\s+|a little\s+|a bit\s+|partly\s+)?(?:to(?:wards?)?\s+|toward\s+)?" r"(?:the\s+|her\s+|his\s+|their\s+)?(left|right)\b", t) dirn = None if md: dirn = -1.0 if md.group(1) == "left" else 1.0 sgn = dirn # light direction (viewer's frame): "light from the left", "lit from the right", "window light from the # upper left", "left lighting", "lit on the right side" ml = re.search(r"\b(?:light|lit|lighting|lighted|illuminated|sunlight|sunlit|lamplight|candlelight|window|" r"lamp|sun|key light)\b(?:\s+[\w-]+){0,3}?\s+(?:from|on)\s+(?:the\s+)?(?:viewer'?s?\s+)?" r"(?:upper\s+|top\s+|lower\s+|far\s+)?(left|right)\b", t) if not ml: ml = re.search(r"\b(left|right)[ -](?:lit|lighting|light|side lighting|side light)\b", t) light_side = None if ml: light_side = -1 if ml.group(1) == "left" else 1 if has("three-quarter", "three quarter", "3/4", "three-quarters", "quarter view", "turned", "angled"): yaw = sgn * r.uniform(28, 38) elif has("profile", "side view", "side-view", "from the side"): yaw = sgn * 70.0 # outside this wave's scope; drawn as a strong turn elif has("front", "frontal", "facing the viewer", "facing the camera", "front view", "straight on", "looking at the viewer", "looking at the camera", "symmetrical"): yaw = r.uniform(-4, 4) elif dirn is not None: yaw = sgn * r.uniform(22, 32) else: yaw = r.uniform(-6, 6) if r.random() < .45 else sgn * r.uniform(22, 36) pitch = r.uniform(-4, 3) if has("looking up"): pitch = 14.0 if has("looking down"): pitch = -12.0 roll = r.normal(0, 2.5) if has("tilted", "tilting", "head tilt"): roll = sgn * 9.0 return cls(yaw, pitch, roll, light_side=light_side)
# ------------------------------------------------------------------------------------------------ rotation helpersdef _rot(yaw, pitch, roll): a, b, c = math.radians(yaw), math.radians(pitch), math.radians(roll) Ry = np.array([[math.cos(a), 0, math.sin(a)], [0, 1, 0], [-math.sin(a), 0, math.cos(a)]], F32) Rx = np.array([[1, 0, 0], [0, math.cos(b), math.sin(b)], [0, -math.sin(b), math.cos(b)]], F32) # +pitch: chin up Rz = np.array([[math.cos(c), math.sin(c), 0], [-math.sin(c), math.cos(c), 0], [0, 0, 1]], F32) # +roll: clockwise on screen return Rz @ Ry @ Rx
def _hull(P): """convex hull (monotone chain) of 2D points, counter-clockwise in a y-up frame""" P = sorted(map(tuple, np.asarray(P, float))) if len(P) < 3: return np.array(P)
def cross(o, a, b): return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]) lo, up = [], [] for p in P: while len(lo) >= 2 and cross(lo[-2], lo[-1], p) <= 0: lo.pop() lo.append(p) for p in reversed(P): while len(up) >= 2 and cross(up[-2], up[-1], p) <= 0: up.pop() up.append(p) return np.array(lo[:-1] + up[:-1])
# ------------------------------------------------------------------------------------------------ the layoutFRAMINGS = ("closeup", "portrait", "bust", "half")
class Layout: pass
def _remap_y(y, real, canon_f): """y (head frame, up) -> remapped y: from-crown fractions moved piecewise-linearly from the anatomical feature heights to the canon's (crown 0 and chin 1 fixed; below the chin the offset is kept)""" f = 0.5 - np.asarray(y, F32) kx = np.array([0.0] + list(real) + [1.0], F32) ky = np.array([0.0] + list(canon_f) + [1.0], F32) g = np.interp(f, kx, ky) g = np.where(f > 1.0, f, g) g = np.where(f < 0.0, f, g) return (0.5 - g).astype(F32)
def build(person, pose=None, style="real", size=512, framing="portrait", seed=None, hair_lift=None): """the 2D landmark layout of one person in one pose for one style canon. See the module docstring.""" from pydraw.anatomy.head import landmarks as head_landmarks, HeadParams, _age_row pose = pose or Pose() seed = person.seed if seed is None else seed cn = C.resolve(style, seed, person.sex, person.age) A = head_landmarks(HeadParams(sex=person.sex, age=person.age)) hr = _age_row(person.age) real_f = [hr[0], hr[1], hr[2], hr[3], hr[4]] can_f = [cn["hairline_y"], cn["brow_y"], cn["eye_y"], cn["nose_y"], cn["mouth_y"]] can_f = list(np.maximum.accumulate(np.clip(can_f, 0.05, 0.97))) # keep the order Y = lambda y: _remap_y(y, real_f, can_f) yf = lambda f: 0.5 - f # canon from-crown fraction -> head y
# ---- widths (canon) ---------------------------------------------------------------------------------------- hw_face = cn["face_w"] / 2 # zygion half width hw_cran = hw_face / 0.92 * (1.0 + 0.04 * (1 - person.sex)) # braincase wider than the cheekbones (H17 S2) hw_jaw = cn["jaw_w"] / 2 hw_chin = cn["chin_w"] / 2 fat = float(A["_fat"]) build_k = 1.0 + 0.10 * (person.build - 0.5) hw_jaw *= build_k dep = 1.0 ez = float(A["eye_L"][2]) fz = float(A["stoss"][2]) eye_f, nose_f, mouth_f, brow_f, hair_f = cn["eye_y"], cn["nose_y"], cn["mouth_y"], cn["brow_y"], cn["hairline_y"]
# ---- 3D points in the canon head frame ------------------------------------------------------------------- P3 = {} P3["crown"] = (0, 0.5, -0.04) P3["hairline"] = (0, yf(hair_f), fz * 0.80) P3["stoss"] = (0, yf(brow_f), fz) P3["nose_root"] = (0, yf(eye_f) + 0.02, fz - 0.025) nose_len = (nose_f - eye_f) P3["nose_tip"] = (0, yf(nose_f) + 0.04 * nose_len / 0.21, float(A["nose_tip"][2]) * (0.85 if style == "anime" else 1.0)) P3["nose_base"] = (0, yf(nose_f), float(A["nose_base"][2]) * (0.8 if style == "anime" else 1.0)) P3["mouth_c"] = (0, yf(mouth_f), float(A["mouth_c"][2])) lip = 0.035 if style != "anime" else 0.015 P3["lip_top"] = (0, yf(mouth_f) + lip, float(A["mouth_c"][2]) + 0.01) P3["lip_bot"] = (0, yf(mouth_f) - lip * 1.2, float(A["mouth_c"][2]) - 0.01) chin_front_f = mouth_f + 0.62 * (1 - mouth_f) P3["chin_front"] = (0, yf(chin_front_f), float(A["chin_front"][2])) P3["chin"] = (0, -0.5, float(A["chin"][2])) P3["occiput"] = (0, 0.04, -0.45) for s, sx in (("L", 1.0), ("R", -1.0)): ex = sx * cn["eye_spacing"] / 2 P3["eye_" + s] = (ex, yf(eye_f), ez) P3["brow_in_" + s] = (ex - sx * cn["eye_w"] * 0.45, yf(brow_f) + 0.0, fz - 0.03) P3["brow_mid_" + s] = (ex + sx * cn["eye_w"] * 0.05, yf(brow_f) + 0.022, fz - 0.06) P3["brow_out_" + s] = (ex + sx * cn["eye_w"] * 0.62, yf(brow_f) + 0.005, fz - 0.13) P3["zygion_" + s] = (sx * hw_face, yf(eye_f) - 0.06, 0.11) P3["cheekbone_" + s] = (sx * hw_face * 0.80, yf(eye_f) - 0.08, fz * 0.55) jy = yf(mouth_f + 0.06) if style != "anime" else yf(0.5 * (mouth_f + nose_f)) P3["jaw_angle_" + s] = (sx * hw_jaw, jy, 0.015 + 0.04 * fat) P3["chin_" + s] = (sx * hw_chin, -0.5 + 0.035, float(A["chin"][2]) * 0.92) P3["mouth_" + s] = (sx * cn["mouth_w"] / 2, yf(mouth_f), float(A["mouth_c"][2]) - 0.05) P3["nose_wing_" + s] = (sx * cn["nose_w"] / 2, yf(nose_f) + 0.01, float(A["nose_base"][2]) - 0.08) ex_ = sx * hw_cran * 0.90 P3["ear_top_" + s] = (ex_, yf(brow_f) + 0.01, -0.035) P3["ear_bot_" + s] = (ex_ * 0.97, yf(nose_f), 0.0) P3["temple_" + s] = (sx * hw_cran * 0.93, yf(brow_f) + 0.06, fz * 0.45) # neck (head part: the top of the neck turns with the head, behind the jaw under the ear: H17 N2) nw = cn["neck_w"] * (1.0 + 0.12 * (person.build - 0.5)) for s, sx in (("L", 1.0), ("R", -1.0)): P3["neck_top_" + s] = (sx * nw / 2, yf(nose_f) - 0.06, -0.10)
# ---- the cranium cap and jaw as 3D samples (for the silhouette) ------------------------------------------ c_cr = np.array([0.0, 0.10, -0.03], F32) r_cr = np.array([hw_cran, 0.40, 0.46], F32) th = np.linspace(0, 2 * np.pi, 36, endpoint=False) ph = np.linspace(-0.75, np.pi / 2, 16) TH, PH = np.meshgrid(th, ph) cap = np.stack([np.cos(PH) * np.sin(TH), np.sin(PH), np.cos(PH) * np.cos(TH)], -1).reshape(-1, 3) * r_cr + c_cr # the front of the cap down to just below the eyes; the back and sides of the skull down toward the nape (the # near-side silhouette of a turned head is the back of the skull behind the ear, H17 S1-S2) back = np.cos(TH.reshape(-1)) < 0.35 cap = cap[(cap[:, 1] > yf(min(0.98, 0.52)) - 0.0) | (back & (cap[:, 1] > -0.22))] jaw = [] for s in ("L", "R"): z0, za, zc = P3["zygion_" + s], P3["jaw_angle_" + s], P3["chin_" + s] for t in np.linspace(0, 1, 7): # cheek: zygion -> jaw angle, a slight outward bulge (young / fat) p = (1 - t) * np.array(z0) + t * np.array(za) p[0] *= 1.0 + (0.05 + 0.08 * fat) * math.sin(math.pi * t) jaw.append(p) for t in np.linspace(0, 1, 9): # jaw line: angle -> chin corner, convex p = (1 - t) * np.array(za) + t * np.array(zc) p[0] *= 1.0 + (0.06 + 0.10 * fat) * math.sin(math.pi * t) p[1] -= (0.02 + 0.02 * fat) * math.sin(math.pi * t) jaw.append(p) jaw += [np.array(P3["chin"]), np.array(P3["chin_front"])] jaw = np.array(jaw, F32) # remap only the anatomical-height parts? P3 is already in canon heights; the cap's y is stretched by Y() cap[:, 1] = Y(cap[:, 1]) cap[:, 1] = np.clip(cap[:, 1], -0.5, 0.5)
# ---- rotation + projection ------------------------------------------------------------------------------- R = _rot(pose.yaw, pose.pitch, pose.roll) Rt = _rot(pose.torso_yaw, 0.0, pose.roll * 0.3) piv = np.array([0.0, -0.30, -0.05], F32)
def rot_head(p): p = np.asarray(p, F32).reshape(-1, 3) return (p - piv) @ R.T + piv
# hair lift for framing if hair_lift is None: hair_lift = C.hair_lift(person.hair_style, seed) extra_top = hair_lift + (0.22 if person.hair_style == "bun" else 0.0) framing = framing if framing in FRAMINGS else "portrait" hif = cn["head_in_frame"] hif = {"closeup": min(0.86, hif * 1.18), "portrait": hif, "bust": hif * 0.84, "half": hif * 0.48}[framing] Hpx = hif * size / (1.0 + extra_top) if "head_cc_in_frame" in cn: # kit2: a canon that states crown-chin (no hair) per frame (paint) Hpx = cn["head_cc_in_frame"] * {"closeup": 1.18, "portrait": 1.0, "bust": 0.84, "half": 0.48}[framing] * size # the shoulders must start inside the frame (X9: shoulders start at the jaw line): cap H so the acromion line # lands at <= 0.92 of the frame (portrait), 0.82 (bust) nb_est = -0.5 - cn["neck_len"] * 0.85 - 0.10 sh_target = {"closeup": 9.0, "portrait": 0.92, "bust": 0.80, "half": 0.42}[framing if framing in FRAMINGS else "portrait"] # vertical placement: the top of the hair at a margin; horizontal: looking room on the facing side allh = rot_head(np.vstack([cap, jaw])) top_y = allh[:, 1].max() + extra_top margin = size * (0.5 * (1 - hif)) * (0.55 if framing != "half" else 0.35) margin = max(size * 0.03, min(margin, size * 0.08)) Hpx = min(Hpx, (sh_target * size - margin) / max(0.5, top_y - nb_est)) oy = margin + top_y * Hpx # image y of head-frame y = 0 face_dir = math.sin(math.radians(pose.yaw)) ox = size * 0.5 - face_dir * 0.10 * Hpx * (1.0 if framing != "half" else 0.6)
def proj(p): p = rot_head(p) return np.stack([ox + p[:, 0] * Hpx, oy - p[:, 1] * Hpx], 1).astype(F32)
def projz(p): return rot_head(p)[:, 2]
Lo = Layout() Lo.size, Lo.H, Lo.style, Lo.framing, Lo.canon = size, float(Hpx), style, framing, cn Lo.yaw, Lo.pitch, Lo.roll, Lo.torso_yaw = pose.yaw, pose.pitch, pose.roll, pose.torso_yaw Lo.person, Lo.pose, Lo.hair_lift = person, pose, float(hair_lift) Lo.far = "L" if pose.yaw > 0 else "R" Lo.near = "R" if pose.yaw > 0 else "L" if abs(pose.yaw) < 1e-3: Lo.far, Lo.near = "L", "R" rl = C.rng_for(seed, "light") # light: short lighting by default (from the side the face turns toward) unless frontal, where the seed picks if getattr(pose, "light_side", None) in (-1, 1): Lo.light_side = int(pose.light_side) # asked for in the prompt elif abs(pose.yaw) > 8: Lo.light_side = 1 if pose.yaw > 0 else -1 if rl.random() < 0.3: Lo.light_side = -Lo.light_side else: Lo.light_side = 1 if rl.random() < .5 else -1 Lo.light = np.array([0.55 * Lo.light_side, -0.55, 0.63], F32) Lo.proj, Lo.projz, Lo.rot = proj, projz, R Lo.Y = Y
def skull(theta, phi): """a 3D point on the cranium (theta round the vertical axis, 0 = the face direction; phi up from the equator), in the canon head frame""" p = np.array([math.cos(phi) * math.sin(theta), math.sin(phi), math.cos(phi) * math.cos(theta)], F32) * r_cr + c_cr p[1] = float(Y(np.array([p[1]]))[0]) return p Lo.skull = skull Lo.cranium_c, Lo.cranium_r = c_cr, r_cr
pt, z = {}, {} for k, v in P3.items(): pt[k] = proj(v)[0] z[k] = float(projz(v)[0]) for s in ("L", "R"): pt["eye_" + s] = pt["eye_" + s] Lo.pt, Lo.z = pt, z pt["head_c"] = proj((0, yf(eye_f) - 0.05, 0.1))[0]
# ---- face plate: hull of the cap + jaw --------------------------------------------------------------------- pts2 = proj(np.vstack([cap, jaw])) hull = _hull(pts2 * np.array([1, -1])) # hull in a y-up frame hull = hull * np.array([1, -1]) from .kit import resample Lo.face = resample(hull, max(2.0, Hpx / 60.0), closed=True) capP = proj(cap) Lo.cranium = resample(_hull(capP * np.array([1, -1])) * np.array([1, -1]), max(2.0, Hpx / 60.0), closed=True)
# ---- features -------------------------------------------------------------------------------------------- Lo.eyes = {} for s, sx in (("L", 1.0), ("R", -1.0)): c3 = np.array(P3["eye_" + s], F32) w, h = cn["eye_w"], cn["eye_h"] far = (s == Lo.far) and abs(pose.yaw) > 8 if far and style == "anime": w = w * cn.get("far_eye", 0.6) / max(0.3, math.cos(math.radians(pose.yaw))) # A4 far eye 0.6x after projection inner = c3 + np.array([-sx * w / 2, -0.004, 0.018], F32) outer = c3 + np.array([sx * w / 2, 0.004, -0.045], F32) tt = np.linspace(0, 1, 9) up, lo_ = [], [] for t in tt: b = (1 - t) * inner + t * outer k = math.sin(math.pi * t) up.append(b + np.array([0, h / 2 * k ** 0.8 * (1.0 + 0.15 * (t - 0.5)), 0.012 * k], F32)) lo_.append(b + np.array([0, -h / 2 * k ** 0.9 * 0.9, 0.008 * k], F32)) U, D = proj(np.array(up)), proj(np.array(lo_)) cc = proj(c3)[0] wpx = float(np.linalg.norm(U[-1] - U[0])) Lo.eyes[s] = dict(c=cc, upper=U, lower=D, outline=np.vstack([U, D[::-1][1:-1]]), w=wpx, h=float(np.linalg.norm(U[4] - D[4])), fs=wpx / max(1e-6, w * Hpx), far=bool(far), roll=math.atan2(float(U[-1][1] - U[0][1]), float(U[-1][0] - U[0][0])) * (1 if s == "L" else -1) * 0 + math.radians(pose.roll), inner=U[0], outer=U[-1], z=float(projz(c3)[0])) Lo.brows = {s: proj(np.array([P3["brow_in_" + s], P3["brow_mid_" + s], P3["brow_out_" + s]])) for s in ("L", "R")} ml = proj(np.array([P3["mouth_R"], (0, yf(mouth_f) + 0.004, P3["mouth_c"][2]), P3["mouth_L"]])) Lo.mouth = dict(line=ml, w=float(np.linalg.norm(ml[-1] - ml[0])), c=pt["mouth_c"], top=pt["lip_top"], bot=pt["lip_bot"], upper=proj(np.array([P3["mouth_R"], (0, yf(mouth_f) + lip, P3["lip_top"][2]), P3["mouth_L"], (0, yf(mouth_f), P3["mouth_c"][2])])), lower=proj(np.array([P3["mouth_R"], (0, yf(mouth_f), P3["mouth_c"][2]), P3["mouth_L"], (0, yf(mouth_f) - lip * 1.3, P3["lip_bot"][2])]))) nb = proj(np.array([P3["nose_root"], P3["nose_tip"], P3["nose_base"]])) shadow_side = "L" if Lo.light_side < 0 else "R" # light from -x: the +x (subject's left) side is in shadow Lo.shadow_side = shadow_side ws = 1.0 if shadow_side == "L" else -1.0 Lo.nose = dict(tip=pt["nose_tip"], base=pt["nose_base"], wing_L=pt["nose_wing_L"], wing_R=pt["nose_wing_R"], bridge=nb[:2], side=proj(np.array([(ws * 0.03, yf(eye_f) - 0.02, fz - 0.03), (ws * 0.045, yf(0.5 * (eye_f + nose_f)), fz + 0.01), (ws * cn["nose_w"] / 2, yf(nose_f) + 0.015, P3["nose_wing_L"][2])]))) Lo.midline = proj(np.array([P3["stoss"], P3["nose_root"], P3["nose_tip"], P3["nose_base"], P3["lip_top"], P3["mouth_c"], P3["lip_bot"], P3["chin_front"], P3["chin"]])) Lo.jaw = {s: proj(np.array([P3["jaw_angle_" + s], (np.array(P3["jaw_angle_" + s]) + np.array(P3["chin_" + s])) / 2 - np.array([0, 0.03, 0]), P3["chin_" + s], P3["chin"]])) for s in ("L", "R")}
# ears: an outline in the side plane; visible when it faces the viewer enough Lo.ears = {} for s, sx in (("L", 1.0), ("R", -1.0)): top, bot = np.array(P3["ear_top_" + s]), np.array(P3["ear_bot_" + s]) c3 = (top + bot) / 2 + np.array([sx * 0.02, 0, -0.01]) ry = (top[1] - bot[1]) / 2 * 1.05 rz = ry * 0.52 t = np.linspace(0, 2 * np.pi, 20, endpoint=False) o3 = np.stack([np.full_like(t, c3[0]) + sx * 0.012 * (1 - np.cos(t)) * 0.5, c3[1] + ry * np.sin(t) * (1 - 0.15 * (np.sin(t) < 0)), c3[2] - 0.01 + rz * np.cos(t) * (0.8 + 0.25 * np.sin(t))], 1) n3 = rot_head(np.array([[sx, 0, 0]], F32) + piv)[0] - rot_head(piv[None])[0] vis = n3[2] > -0.45 Lo.ears[s] = dict(outline=proj(o3), c=proj(c3)[0], visible=bool(vis), over_face=bool(vis and abs(pose.yaw) > 14 and s == Lo.near)) if not vis: Lo.ears[s]["visible"] = False
# ---- neck and torso (torso frame turns by torso_yaw) ----------------------------------------------------- sw = cn["shoulder_w"] * (1.0 + 0.10 * (person.build - 0.5)) dw = cn["deltoid_w"] * (1.0 + 0.14 * (person.build - 0.5)) nl = cn["neck_len"] nb_y = -0.5 - nl * 0.85 # neck base (pit level) height, head frame tpiv = np.array([0.0, nb_y, -0.05], F32) # the torso hangs under the head: shift it so the pit stays under the rotated neck hd_neck = rot_head(np.array([[0, yf(nose_f) - 0.06, -0.10]], F32))[0] t_off = np.array([hd_neck[0] * 0.6, 0, 0], F32)
def projT(p): p = np.asarray(p, F32).reshape(-1, 3) q = (p - tpiv) @ Rt.T + tpiv + t_off return np.stack([ox + q[:, 0] * Hpx, oy - q[:, 1] * Hpx], 1).astype(F32) Lo.projT = projT for s, sx in (("L", 1.0), ("R", -1.0)): # the trapezius meets the side of the neck well above the pit (H17 N3, N7: lower in front, higher behind) pt["neck_base_" + s] = projT((sx * nw / 2 * 1.08, nb_y + cn.get("trap_rise", 0.09), -0.08))[0] pt["shoulder_" + s] = projT((sx * sw / 2, nb_y - 0.10 - 0.03 * person.sex, -0.06))[0] pt["deltoid_" + s] = projT((sx * dw / 2, nb_y - 0.34, -0.02))[0] pt["neck_top_" + s] = proj(P3["neck_top_" + s])[0] pt["pit"] = projT((0, nb_y - 0.02, 0.12))[0] pt["c7"] = projT((0, nb_y + 0.08, -0.25))[0] pt["neck_top"] = (pt["neck_top_L"] + pt["neck_top_R"]) / 2 Lo.neck = np.vstack([pt["neck_top_R"] + np.array([0, -0.12 * Hpx]), pt["neck_top_R"], pt["neck_base_R"], pt["pit"] + np.array([0, 0.01 * Hpx]), pt["neck_base_L"], pt["neck_top_L"], pt["neck_top_L"] + np.array([0, -0.12 * Hpx])]) bottom = 1.9 if framing != "half" else 3.8 # torso runs past the frame bottom torso_side = {} for s, sx in (("L", 1.0), ("R", -1.0)): trap = projT((sx * (nw / 2 + (sw / 2 - nw / 2) * 0.45), nb_y - 0.01, -0.08))[0] arm = projT((sx * dw / 2 * 0.99, nb_y - 0.80, 0.0))[0] if framing == "half": low = projT((sx * dw / 2 * 0.96, nb_y - bottom, 0.0))[0] else: low = projT((sx * dw / 2 * 1.0, nb_y - bottom, 0.0))[0] torso_side[s] = [pt["neck_base_" + s], trap, pt["shoulder_" + s], pt["deltoid_" + s], arm, low] Lo.torso = np.vstack([torso_side["R"][::-1], torso_side["L"]]) Lo.torso_sharp = [0, len(Lo.torso) - 1] # clothes: a crew / scoop neckline below the pit, chest skin above it rn = C.rng_for(seed, "neckline") # kit2: depth and width from canon ranges (neckline_depth / neckline_w); men's necklines sit higher (my est.) dlo, dhi = C.table(style).get("neckline_depth", (0.0, 0.12))[:2] wlo, whi = C.table(style).get("neckline_w", (1.15, 1.55))[:2] depth = dlo + (dhi - dlo) * rn.random() * (1 - person.sex * 0.5) wid = nw / 2 * (wlo + (whi - wlo) * rn.random()) nlL = projT((wid, nb_y - 0.04, 0.02))[0] nlR = projT((-wid, nb_y - 0.04, 0.02))[0] nlC = projT((0, nb_y - 0.04 - depth, 0.14))[0] Lo.neckline = np.array([nlR, (nlR + nlC) / 2 + np.array([0, 0.02 * Hpx]), nlC, (nlL + nlC) / 2 + np.array([0, 0.02 * Hpx]), nlL]) Lo.chest_skin = np.vstack([pt["neck_base_R"], Lo.neckline, pt["neck_base_L"]]) for s, sx in (("L", 1.0), ("R", -1.0)): Lo.__dict__["clavicle_" + s] = np.array([projT((sx * 0.06, nb_y - 0.05, 0.12))[0], projT((sx * sw * 0.25, nb_y - 0.08, 0.08))[0], projT((sx * sw / 2 * 0.92, nb_y - 0.12, 0.0))[0]]) Lo.arms = {} if framing == "half": # half body: arms hang at the sides as their own shapes (shoulder cap -> elbow at the waist -> wrist), the # torso core runs armpit -> waist; Loomis 8-head figure: elbow at the waist ~1.5 H below the acromion, wrist # at the crotch ~2.6 H (my est. from the canon chart); waist breadth canon waist_w ww = cn.get("waist_w", 1.3) * (1.0 + 0.2 * (person.build - 0.5)) core = {} for s, sx in (("L", 1.0), ("R", -1.0)): pit_a = projT((sx * sw / 2 * 0.80, nb_y - 0.55, 0.02))[0] waist = projT((sx * ww / 2, nb_y - 1.75, 0.0))[0] hip = projT((sx * ww / 2 * (1.08 + 0.08 * (1 - person.sex)), nb_y - bottom, 0.0))[0] core[s] = [pt["neck_base_" + s], torso_side[s][1], pt["shoulder_" + s], pit_a, waist, hip] sh_ = pt["shoulder_" + s] outer = [sh_, projT((sx * dw / 2, nb_y - 0.30, -0.02))[0], projT((sx * dw / 2 * 0.98, nb_y - 0.95, 0.0))[0], projT((sx * (dw / 2 * 0.97), nb_y - 1.55, 0.02))[0], projT((sx * (dw / 2 * 0.95), nb_y - 2.4, 0.12))[0], projT((sx * (dw / 2 * 0.95), nb_y - bottom, 0.16))[0]] inner = [projT((sx * (dw / 2 * 0.95 - 0.26), nb_y - bottom, 0.16))[0], projT((sx * (dw / 2 * 0.95 - 0.22), nb_y - 2.4, 0.12))[0], projT((sx * (dw / 2 * 0.97 - 0.30), nb_y - 1.55, 0.04))[0], projT((sx * (dw / 2 * 0.98 - 0.32), nb_y - 0.95, 0.02))[0], pit_a] Lo.arms[s] = dict(outline=np.array(outer + inner), sharp=[len(outer) - 1, len(outer)], elbow=projT((sx * dw / 2 * 0.97 - 0.15 * sx, nb_y - 1.55, 0.03))[0], wrist=projT((sx * dw / 2 * 0.95 - 0.12 * sx, nb_y - 2.4, 0.12))[0]) pt["elbow_" + s], pt["wrist_" + s], pt["waist_" + s] = Lo.arms[s]["elbow"], Lo.arms[s]["wrist"], waist Lo.torso = np.vstack([core["R"][::-1], core["L"]]) Lo.torso_sharp = [0, len(Lo.torso) - 1] # ---- beard / moustache region (Person.beard) and glasses: shapes in the face's 3D frame, projected ----------- Lo.beard = None if person.beard: mz = float(A["mouth_c"][2]) up_y = yf(mouth_f) + lip + 0.03 rb = C.rng_for(seed, "beard") if person.beard == "mustache": pts = [(-cn["mouth_w"] * 0.62, yf(mouth_f) + 0.005, mz - 0.07), (-cn["mouth_w"] * 0.3, up_y + 0.01, mz), (0, up_y + 0.005, mz + 0.02), (cn["mouth_w"] * 0.3, up_y + 0.01, mz), (cn["mouth_w"] * 0.62, yf(mouth_f) + 0.005, mz - 0.07), (cn["mouth_w"] * 0.3, yf(mouth_f) + lip * 0.6, mz + 0.01), (0, yf(mouth_f) + lip * 0.8, mz + 0.03), (-cn["mouth_w"] * 0.3, yf(mouth_f) + lip * 0.6, mz + 0.01)] Lo.beard = dict(kind="mustache", outline=proj(np.array(pts)), mouth_hole=None) else: drop = 0.02 if person.beard == "short" else 0.06 + 0.10 * rb.random() # upper edge: sideburn R -> cheek R -> moustache -> cheek L -> sideburn L (the cheek line, Loomis) upper = [(-hw_face * 0.92, yf(brow_f + 0.12), -0.02), (-hw_face * 0.80, yf(nose_f) - 0.01, 0.16), (-cn["mouth_w"] * 0.75, up_y, mz - 0.06), (0, up_y + 0.01, mz + 0.03), (cn["mouth_w"] * 0.75, up_y, mz - 0.06), (hw_face * 0.80, yf(nose_f) - 0.01, 0.16), (hw_face * 0.92, yf(brow_f + 0.12), -0.02)] lower = [] for t in np.linspace(0, 1, 9): # under the jaw, L -> R, swelling below the chin by `drop` a = (1 - t) * np.array(P3["jaw_angle_L"]) + t * np.array(P3["jaw_angle_R"]) k = math.sin(math.pi * t) lower.append((a[0] * (1.05 + 0.10 * k), a[1] - (abs(-0.5 - a[1]) + drop) * k ** 0.7, a[2] + (float(A["chin"][2]) - a[2]) * k)) Lo.beard = dict(kind=person.beard, outline=proj(np.array(upper + lower)), mouth_hole=Lo.mouth["lower"], drop=drop) Lo.beard["color"] = getattr(person, "beard_color", None) # kit2: the beard's colour word (None = hair) Lo.glasses = None if person.glasses: rg = C.rng_for(seed, "glasses") rnd = rg.random() < .5 lens = {} for s, sx in (("L", 1.0), ("R", -1.0)): c3 = np.array(P3["eye_" + s], F32) + np.array([sx * 0.005, -0.005, 0.07], F32) rx = max(cn["eye_w"] * 0.72, 0.075) ry = rx * (0.85 if rnd else 0.62) t = np.linspace(0, 2 * np.pi, 28, endpoint=False) sq = 1.0 if rnd else 0.45 cx_, cy_ = np.cos(t), np.sin(t) ex = np.sign(cx_) * np.abs(cx_) ** sq ey = np.sign(cy_) * np.abs(cy_) ** sq o3 = np.stack([c3[0] + rx * ex, c3[1] + ry * ey, c3[2] - 0.06 * (sx * ex) ** 2 * (sx * ex > 0)], 1) lens[s] = proj(o3) br = proj(np.array([np.array(P3["eye_R"]) + np.array([cn["eye_w"] * 0.6, 0.01, 0.06]), (0, yf(eye_f) + 0.02, fz + 0.03), np.array(P3["eye_L"]) + np.array([-cn["eye_w"] * 0.6, 0.01, 0.06])])) arms = {s: proj(np.array([np.array(P3["eye_" + s]) + np.array([sx * max(cn["eye_w"] * 0.72, 0.075), 0.01, 0.04]), np.array(P3["ear_top_" + s]) + np.array([0, -0.03, 0.02])])) for s, sx in (("L", 1.0), ("R", -1.0))} Lo.glasses = dict(lens=lens, bridge=br, arms=arms, round=bool(rnd)) return Lo
def framing_from_text(text): t = " " + " ".join(re.findall(r"[a-z0-9\-]+", text.lower())) + " " if any(w in t for w in (" close-up ", " closeup ", " close up ", " headshot ", " head shot ", " face ")): return "closeup" if any(w in t for w in (" half-body ", " half body ", " upper body ", " waist-up ", " waist up ", " half-length ", " half length ")): return "half" if " bust " in t: return "bust" return "portrait"12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724"""Painted portrait (wave 18, paint lane): oil, gouache, watercolour and "realistic portrait" heads + shoulders.
Pure code: numpy + PIL + scipy, no learned models, weights or image files. The METHOD comes from the wave-17 Sargentmaster copy (out/copy17/painted/code/copyB.py, the painter's order) and docs/research18/copy_rules.md P-R1..P-R10; nocoordinate or colour of that copy is reused (it describes one picture). Every number below is a range across referencesor a research-doc value (cited), varied by the person's params and the seed.
Painter's order (copyB order, C9): 1 value plan + palette (P-R1, research16 rule 5 gamut, rule 11 mud: one shadow temperature) 2 toned ground (counterchange: light ground beside the dark hair pocket, research16 rule 1) 3 big masses in z order: back hair, torso/clothes (own yaw, P-R8), neck, ears, face plate 4 designed face planes: one lit-plane shape + one shadow shape split by a designed boundary (P-R2), lower face lit on the light side down to the chin and a diagonal chin cast following the jaw (P-R7) 5 features as value masses (P-R3) 6 hair: 2-3 value masses, clumps with uneven tips, lit-side strokes, broken / partly lost silhouette, overlapping the face (P-R4, P-R6) 7 edge budget: 3-4 hard edges, the rest softened 3-8 px at H~230 px (P-R5) 8 brush marks along the form (structure tensor isophotes) carrying edges (P-R10), then the medium passKnob: PYDRAW_EXP fig_paint=0 turns the painted portrait off (callers fall back to the old path). Sub-knobs for theablation (each =0 turns one decision off): pp_planes, pp_features, pp_chincast, pp_hairvalues, pp_edges, pp_marks,pp_medium.
Layout: the kit lane (pydraw/figure/layout.py, hairlayout.py) owns the landmark layout. Until its API is merged thismodule carries a stand-in with the same idea (a projected head: front-view head units -> image px for any yaw), so thepainter only consumes 2D shapes + a projection function. `draw(...)` is the entry point."""import mathimport osimport re
import numpy as npfrom PIL import Image, ImageDraw, ImageFilterfrom scipy import ndimage
KNOB = "fig_paint"
def _exp(): return dict(kv.split("=", 1) for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv)
def on(name, default="1"): return _exp().get(name, default) != "0"
# ============================================================ colour (OKLab; Ottosson 2020 formulas)def _lin(c): c = np.asarray(c, np.float32) return np.where(c <= .04045, c / 12.92, ((c + .055) / 1.055) ** 2.4)
def _gam(c): c = np.clip(c, 0, 1) return np.where(c <= .0031308, c * 12.92, 1.055 * np.power(c, 1 / 2.4) - .055)
def to_lab(rgb): r, g, b = np.moveaxis(_lin(rgb), -1, 0) l = np.cbrt(.4122214708 * r + .5363325363 * g + .0514459929 * b) m = np.cbrt(.2119034982 * r + .6806995451 * g + .1073969566 * b) s = np.cbrt(.0883024619 * r + .2817188376 * g + .6299787005 * b) return np.stack([.2104542553 * l + .7936177850 * m - .0040720468 * s, 1.9779984951 * l - 2.4285922050 * m + .4505937099 * s, .0259040371 * l + .7827717662 * m - .8086757660 * s], -1).astype(np.float32)
def from_lab(lab): L, a, b = np.moveaxis(np.asarray(lab, np.float32), -1, 0) l = (L + .3963377774 * a + .2158037573 * b) ** 3 m = (L - .1055613458 * a - .0638541728 * b) ** 3 s = (L - .0894841775 * a - 1.2914855480 * b) ** 3 r = 4.0767416621 * l - 3.3077115913 * m + .2309699292 * s g = -1.2684380046 * l + 2.6097574011 * m - .3413193965 * s bb = -.0041960863 * l - .7034186147 * m + 1.7076147010 * s return _gam(np.stack([r, g, bb], -1)).astype(np.float32)
def lch(L, C, h): """OKLCh -> sRGB 0..1 (h in degrees)""" return from_lab([L, C * math.cos(math.radians(h)), C * math.sin(math.radians(h))])
def lch_of(rgb): L, a, b = to_lab(np.asarray(rgb, np.float32)) return float(L), float(math.hypot(a, b)), float(math.degrees(math.atan2(b, a)) % 360)
def hexc(h): h = h.lstrip("#") return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)], np.float32) / 255
def shift(rgb, L=None, dL=0.0, C=None, kC=1.0, dh=0.0): """set/shift a colour's OKLab lightness, scale its chroma, rotate its hue""" L0, C0, h0 = lch_of(rgb) return lch(L if L is not None else L0 + dL, (C if C is not None else C0) * kC, h0 + dh)
def mixc(a, b, t): return (np.asarray(a, np.float32) * (1 - t) + np.asarray(b, np.float32) * t).astype(np.float32)
def lum(img): """OKLab L of an image (the value the plan is written in)""" return to_lab(img)[..., 0]
# ============================================================ 2D painting kit (stand-in for pydraw/figure/kit.py)SS = 2
class Canvas: def __init__(self, W, H, colour=(0.5, 0.5, 0.5)): self.W, self.H = W, H self.img = np.empty((H, W, 3), np.float32) self.img[:] = np.asarray(colour, np.float32)
def spline(pts, closed=True, n=8): """Catmull-Rom through the points (the painter's decided contour)""" P = np.asarray(pts, np.float64) if len(P) < 3: return P P = np.vstack([P[-1], P, P[0], P[1]]) if closed else np.vstack([P[0], P, P[-1]]) t = np.linspace(0, 1, n, endpoint=False)[:, None] t2, t3 = t * t, t * t * t out = [] for i in range(1, len(P) - 2): p0, p1, p2, p3 = P[i - 1], P[i], P[i + 1], P[i + 2] out.append(.5 * ((2 * p1) + (-p0 + p2) * t + (2 * p0 - 5 * p1 + 4 * p2 - p3) * t2 + (-p0 + 3 * p1 - 3 * p2 + p3) * t3)) out = np.vstack(out) if not closed: out = np.vstack([out, P[-2]]) return out
def _raster(cv, bbox, soft, draw): W, H = cv.W, cv.H pad = int(3 * soft + 3) x0, y0 = max(0, int(math.floor(bbox[0])) - pad), max(0, int(math.floor(bbox[1])) - pad) x1, y1 = min(W, int(math.ceil(bbox[2])) + pad), min(H, int(math.ceil(bbox[3])) + pad) m = np.zeros((H, W), np.float32) if x1 - x0 < 1 or y1 - y0 < 1: return m im = Image.new("L", ((x1 - x0) * SS, (y1 - y0) * SS), 0) draw(ImageDraw.Draw(im), x0, y0) im = im.resize((x1 - x0, y1 - y0), Image.BOX) if soft > 0.05: im = im.filter(ImageFilter.GaussianBlur(soft)) m[y0:y1, x0:x1] = np.asarray(im, np.float32) / 255 return m
def poly_mask(cv, pts, soft=0.0, smooth=True): P = spline(pts) if smooth and len(pts) >= 3 else np.asarray(pts, np.float64) if len(P) < 3: return np.zeros((cv.H, cv.W), np.float32) bb = (P[:, 0].min(), P[:, 1].min(), P[:, 0].max(), P[:, 1].max()) return _raster(cv, bb, soft, lambda d, x0, y0: d.polygon([((x - x0) * SS, (y - y0) * SS) for x, y in P], fill=255))
def ell_mask(cv, cx, cy, rx, ry, soft=0.0, rot=0.0): t = np.linspace(0, 2 * np.pi, 40, endpoint=False) c, s = math.cos(rot), math.sin(rot) x, y = rx * np.cos(t), ry * np.sin(t) return poly_mask(cv, np.stack([cx + c * x - s * y, cy + s * x + c * y], 1), soft, smooth=False)
def put(cv, m, col, a=1.0): c = np.asarray(col, np.float32) al = np.clip(m * a, 0, 1)[..., None] if c.ndim == 1: c = c[None, None] cv.img[:] = cv.img * (1 - al) + c * al
def soften(cv, m, r): """lose edges: blend toward a blurred copy inside m (edge control after the fact)""" if r <= 0.05: return b = ndimage.gaussian_filter(cv.img, (r, r, 0)) al = np.clip(m, 0, 1)[..., None] cv.img[:] = cv.img * (1 - al) + b * al
def stroke(cv, pts, col, width, a=1.0, soft=0.6, taper=(0.15, 0.85), smooth=True, closed=False): """a tapered brush/pen mark along a curve: width ramps up over the first taper[0] and down after taper[1]""" P = spline(pts, closed=closed, n=8) if smooth and len(pts) >= 3 else np.asarray(pts, np.float64) n = len(P) if n < 2: return t = np.linspace(0, 1, n) w = width * np.clip(np.minimum(t / max(taper[0], 1e-3), (1 - t) / max(1 - taper[1], 1e-3)), .15, 1.0) ** .6 d = np.gradient(P, axis=0) d /= np.linalg.norm(d, axis=1, keepdims=True) + 1e-9 nrm = np.stack([-d[:, 1], d[:, 0]], 1) * (w[:, None] / 2) poly = np.vstack([P + nrm, (P - nrm)[::-1]]) put(cv, poly_mask(cv, poly, soft, smooth=False), col, a)
def _box(m): ys, xs = np.nonzero(m > .02) if not len(xs): return None return xs.min(), ys.min(), xs.max() + 1, ys.max() + 1
# ============================================================ prompt -> params (stand-in for kit's params)# Monk Skin Tone scale (E. Monk 2019; skintone.google): ten published swatches, light -> dark.MST = ["#f6ede4", "#f3e7db", "#f7ead0", "#eadaba", "#d7bd96", "#a07e56", "#825c43", "#604134", "#3a312a", "#292420"]SKIN_WORDS = [(r"\b(pale|fair|porcelain|light[- ]skinned|light skin)\b", (0, 2)), (r"\b(olive|tan|tanned|medium skin|east asian|asian|latina|latino|hispanic|mediterranean)\b", (3, 5)), (r"\b(brown[- ]skinned|brown skin|south asian|indian|middle eastern|arab)\b", (5, 7)), (r"\b(dark[- ]skinned|dark skin|black (?:woman|man|girl|boy|person|child|lady|gentleman)|african)\b", (7, 9))]HAIR_COL = { # OKLCh (L, C, h) of the hair's mid value; ranges from research17 hair2 H2-26/H2-28 (melanin order) "black": (.24, .015, 60), "dark": (.29, .03, 55), "brown": (.40, .05, 60), "auburn": (.44, .10, 45), "red": (.52, .12, 50), "blonde": (.72, .08, 85), "grey": (.66, .012, 80), "white": (.84, .01, 90)}HAIR_WORDS = [(r"\b(black hair|black-haired|raven)\b", "black"), (r"\b(dark hair|dark-haired|brunette)\b", "dark"), (r"\b(brown hair|brown-haired|chestnut)\b", "brown"), (r"\b(auburn)\b", "auburn"), (r"\b(red hair|red-haired|redhead|ginger|copper hair)\b", "red"), (r"\b(blonde|blond|golden hair|fair hair|fair-haired)\b", "blonde"), (r"\b(grey hair|gray hair|grey-haired|gray-haired|silver hair|salt and pepper)\b", "grey"), (r"\b(white hair|white-haired)\b", "white")]STYLE_WORDS = [(r"\b(ponytail|pony tail)\b", "ponytail"), (r"\b(bun|updo|chignon|top knot|topknot)\b", "bun"), (r"\b(curly|curls|afro|coily|ringlets|wavy hair)\b", "curly"), (r"\b(bob|bobbed|shoulder[- ]length)\b", "bob"), (r"\b(long hair|long-haired|long straight|flowing hair|long)\b", "long"), (r"\b(short hair|short-haired|crew cut|buzz cut|cropped hair|pixie)\b", "short"), (r"\b(bald|shaved head)\b", "bald")]CLOTH_COL = {"red": (.50, .13, 28), "blue": (.45, .09, 255), "navy": (.32, .07, 265), "green": (.48, .08, 150), "olive": (.50, .06, 115), "black": (.22, .005, 260), "white": (.90, .012, 90), "grey": (.58, .008, 250), "gray": (.58, .008, 250), "yellow": (.80, .11, 95), "brown": (.40, .05, 60), "pink": (.75, .07, 10), "purple": (.42, .09, 310), "orange": (.66, .12, 55), "cream": (.88, .03, 90), "teal": (.52, .07, 200)}MEDIA = [("watercolor", r"\b(watercolou?rs?|aquarelle|wet on wet)\b"), ("gouache", r"\b(gouache|tempera|poster paint)\b"), ("realistic", r"\b(realistic|photorealistic|lifelike|hyperrealistic|realism)\b"), ("oil", r"\b(oil|oils|impasto|oil painting|acrylic|painted|painting)\b")]
def media_of(text): t = (text or "").lower() for name, pat in MEDIA: if re.search(pat, t): return name return "oil"
def params_from_prompt(text, seed=0): """stand-in for the kit's params: age, sex, hair style + colour, skin, light side, yaw, clothes, smile, medium""" t = (text or "").lower() rng = np.random.default_rng(seed * 7919 + 17) p = {"seed": seed, "text": t} if re.search(r"\b(teen|teenage|teenager|adolescent)\b", t): age = 15 elif re.search(r"\b(middle[- ]aged)\b", t): age = 48 elif re.search(r"\b(baby|toddler|child|kid|little (?:girl|boy)|girl|boy|schoolgirl|schoolboy)\b", t): age = 8 if not re.search(r"\b(baby|toddler)\b", t) else 4 elif re.search(r"\b(old|elderly|grandmother|grandfather|grandma|grandpa|aged|senior|wrinkled)\b", t): age = 72 elif re.search(r"\b(young)\b", t): age = 23 else: age = int(rng.integers(24, 40)) p["age"] = age if re.search(r"\b(woman|women|girl|lady|female|mother|grandmother|grandma|she|her|queen|princess|schoolgirl|actress)\b", t): p["sex"] = "f" elif re.search(r"\b(man|men|boy|male|gentleman|father|grandfather|grandpa|he|his|king|prince|schoolboy|actor)\b", t): p["sex"] = "m" else: p["sex"] = "f" if rng.random() < .5 else "m" skin = None for pat, (a, b) in SKIN_WORDS: if re.search(pat, t): skin = int(rng.integers(a, b + 1)) p["skin"] = skin if skin is not None else int(rng.choice([1, 2, 3, 4, 5, 6, 7, 8])) style = None for pat, s in STYLE_WORDS: if re.search(pat, t): style = s break if style is None: style = "short" if p["sex"] == "m" else str(rng.choice(["long", "bob", "ponytail", "bun", "curly"])) p["hair"] = style col = None m = re.search(r"\b(black|dark|brown|auburn|red|ginger|blonde|blond|grey|gray|silver|white)(?:[- ]haired)?\s+(?:\w+\s+)?(hair|bob|ponytail|bun|curls|locks|braid|afro|updo)\b", t) if m: col = {"ginger": "red", "blond": "blonde", "gray": "grey", "silver": "grey"}.get(m.group(1), m.group(1)) for pat, c in HAIR_WORDS if col is None else []: if re.search(pat, t): col = c break if col is None: if age >= 65: col = "grey" if rng.random() < .7 else "white" elif p["skin"] >= 6: col = "black" if rng.random() < .6 else "dark" else: col = str(rng.choice(["dark", "brown", "brown", "black", "auburn", "blonde"])) p["hair_col"] = col if re.search(r"\b(light|lit|lighting|sun|window) (?:from|on) the left\b|\bleft[- ]lit\b|\bfrom the left\b", t): p["light"] = -1 elif re.search(r"\b(light|lit|lighting|sun|window) (?:from|on) the right\b|\bright[- ]lit\b|\bfrom the right\b", t): p["light"] = 1 else: p["light"] = -1 if rng.random() < .6 else 1 if re.search(r"\b(three[- ]quarters?|3/4|turned|half[- ]turned|looking (?:left|right|away|aside|to the side))\b", t): sgn = 1 if re.search(r"\b(right)\b", t) else (-1 if re.search(r"\b(left)\b", t) else (1 if rng.random() < .5 else -1)) p["yaw"] = sgn * float(rng.uniform(26, 34)) elif re.search(r"\b(front|frontal|facing (?:the )?(?:viewer|camera|us|forward)|straight on|head[- ]on)\b", t): p["yaw"] = float(rng.uniform(-4, 4)) else: p["yaw"] = float(rng.choice([0.0, 0.0, 1.0, -1.0])) * float(rng.uniform(20, 32)) # contrapposto: the torso turns less than the head, often the other way (P-R8) p["torso_yaw"] = -0.4 * p["yaw"] + float(rng.uniform(-14, 14)) if abs(p["yaw"]) < 8 else 0.25 * p["yaw"] + float(rng.uniform(-10, 4)) * np.sign(p["yaw"]) cl = None m = re.search(r"\b(%s)\s+(?:\w+\s+)?(dress|shirt|sweater|jumper|coat|blouse|jacket|scarf|suit|top|t-shirt|robe|cardigan|hoodie|vest|uniform)\b" % "|".join(CLOTH_COL), t) if m: cl = m.group(1) p["cloth"] = cl p["garment"] = m.group(2) if m else None p["smile"] = .6 if re.search(r"\b(smil\w*|grin\w*|happy|cheerful)\b", t) else 0.0 p["beard"] = bool(re.search(r"\b(beard|bearded|moustache|mustache|stubble)\b", t)) and p["sex"] == "m" p["glasses"] = bool(re.search(r"\b(glasses|spectacles)\b", t)) p["medium"] = media_of(t) return p
# ============================================================ stand-in layout (front head units -> px, any yaw)def _interp(y, pts): ys, vs = zip(*pts) return np.interp(y, ys, vs)
class Head: """a projected head: front-view coordinates (X right, Y down from the crown, in head heights H) -> image px. Cross-sections are two half-ellipses (front depth, back depth) around the vertical axis through the ears, so a yaw of up to ~40 deg places features, contours and hair geometrically (the wave-17 head is the kit lane's job)."""
def __init__(self, p, W, Hf, rng): self.p, self.rng = p, rng age, f = p["age"], p["sex"] == "f" child = age < 13 self.child, self.old = child, age >= 60 k = lambda a, b: a + (b - a) * rng.random() # half-width profile (H units). Adult head width/height ~0.66-0.70 (research17 head_neck: bizygomatic ~0.62-0.68 H) jaw = (.245 if f else .27) + (.025 if child else 0) + k(-.01, .01) cheek = (.335 if f else .345) + (.015 if child else 0) + k(-.008, .008) chin = (.085 if f else .10) + k(-.01, .01) self.hw_pts = [(0, 0), (.03, .17), (.10, .27), (.20, .325), (.32, cheek), (.47, cheek), (.56, cheek - .006), (.66, cheek - .02 - (0 if not child else -.01)), (.76, (cheek + jaw) / 2 + (.02 if child else 0)), (.86, jaw), (.93, jaw * .72 + chin * .28), (.975, chin + .03), (1.0, 0.0)] # feature canon (H from the crown). Adult eye line ~0.50 (Loomis; research17 face units); children lower 0.55-0.60 self.eye_y = (.57 if child else .50) + k(-.012, .012) self.brow_y = self.eye_y - (.075 if child else .085) - (.006 if f else 0) self.nose_y = (.75 if child else .70) + k(-.012, .012) + (.015 if self.old else 0) self.mouth_y = self.nose_y + (.095 if child else .10) + k(-.008, .008) self.hair_y = (.24 if child else .19) + k(-.015, .015) self.eye_dx = .125 + k(-.006, .006) + (.008 if child else 0) self.eye_w = (.062 if child else .056) + k(-.004, .004) self.eye_h = (.024 if child else .018) * (1.0 if f else .9) * (.85 if self.old else 1) self.nose_w = (.05 if child else .062) * (1.0 if f else 1.12) + k(-.004, .004) self.mouth_w = (.075 if child else .092) * (1.0 if f else 1.05) + k(-.006, .006) self.lip = (.016 if f else .012) * (.7 if self.old else 1) # neck half-width ~0.75-0.8 of the face half-width (neck ~10-12 cm vs bizygomatic ~13-14 cm) self.neck_w = (.235 if f else .27) + (-.035 if child else 0) + k(-.01, .01) # frame: head height ~0.33-0.36 of the frame height for a head-and-shoulders bust (critic10 head-in-frame) self.W, self.Hf = W, Hf self.u = Hf * (.40 if not child else .40) * k(.97, 1.03) self.yaw = math.radians(p["yaw"]) self.cx = W * .5 - math.sin(self.yaw) * W * .06 lift = {"curly": .13, "bun": .16}.get(p["hair"], .07) self.top = Hf * .045 + lift * self.u
def hw(self, Y): return _interp(Y, self.hw_pts)
def dz(self, Y): """front depth of the section (ear axis -> face surface), H units""" Y = np.asarray(Y, np.float64) crown = .40 * np.sqrt(np.clip(1 - ((.42 - Y) / .44) ** 2, 0, 1)) return np.where(Y < .42, crown, _interp(Y, [(.42, .40), (.85, .40), (1.0, .33)]))
def db(self, Y): """back depth (ear axis -> back of the skull)""" Y = np.asarray(Y, np.float64) return .50 * np.sqrt(np.clip(1 - ((Y - .40) / .42) ** 2, 0, 1)) * np.where(Y > .40, _interp(Y, [(.40, 1), (.80, .55), (.82, .4)]), 1)
def P(self, X, Y, prot=0.0, Z=None): """surface point (front half) at lateral X, height Y; prot = extra protrusion (nose, lips) -> px""" X, Y = np.asarray(X, np.float64), np.asarray(Y, np.float64) w = np.maximum(self.hw(Y), 1e-3) if Z is None: Z = self.dz(Y) * np.sqrt(np.clip(1 - (X / w) ** 2, 0, 1)) + prot x = self.cx + self.u * (X * math.cos(self.yaw) + Z * math.sin(self.yaw)) y = self.top + self.u * Y return np.stack([x, y], -1) if np.ndim(x) else np.array([x, y])
def PH(self, X, Y, prot=0.0): """a point on the hair shell: below the cheekbones hair hangs at the depth of the widest section, not on the jaw surface (so locks below the chin stay beside the face, not across it)""" Ye = min(float(Y), .55) w = max(float(self.hw(Ye)), abs(float(X)) + 1e-3) Z = float(self.dz(Ye)) * math.sqrt(max(0.0, 1 - (float(X) / w) ** 2)) + prot return self.P(X, Y, Z=Z)
def facing(self, X, Y): """cos of the angle between the surface normal (approx) and the view: <0 = turned away""" w = max(float(self.hw(Y)), 1e-3) phi = math.asin(max(-1, min(1, X / w))) return math.cos(phi + self.yaw)
def silhouette(self, Ys, grow=0.0, front=None, back=None, cx_off=0.0): """left/right image x of the head section outline (optionally grown by `grow` H for hair) per row Y""" phi = np.linspace(0, 2 * np.pi, 72, endpoint=False) L, R = [], [] for Y in Ys: w = float(self.hw(Y)) + grow f = (float(self.dz(Y)) if front is None else front) + grow b = (float(self.db(Y)) if back is None else back) + grow z = np.where(np.cos(phi) >= 0, f, b) * np.cos(phi) x = w * np.sin(phi) * math.cos(self.yaw) + z * math.sin(self.yaw) L.append(self.cx + self.u * (x.min() + cx_off)) R.append(self.cx + self.u * (x.max() + cx_off)) return np.array(L), np.array(R)
def outline(self, Y0=0.0, Y1=1.0, grow=0.0, n=40): Ys = np.linspace(Y0, Y1, n) L, R = self.silhouette(Ys, grow) y = self.top + self.u * Ys return np.vstack([np.stack([R, y], 1), np.stack([L, y], 1)[::-1]])
def layout_standin(p, W, Hf, rng): """stand-in landmark layout (px). The kit lane's layout.py replaces this; names mirror its proposal.""" h = Head(p, W, Hf, rng) u = h.u L = {"head": h, "u": u, "W": W, "H": Hf} # face / head outline: full section silhouette (crown to chin) Ys = np.linspace(0, 1, 48) l, r = h.silhouette(Ys) y = h.top + u * Ys L["face"] = np.vstack([np.stack([r, y], 1), np.stack([l, y], 1)[::-1]]) # jaw line (front surface) from ear to ear via the chin, for chin cast and the jaw edge jy = np.linspace(.62, 1.0, 12) L["jaw_r"] = np.array([h.P(float(h.hw(Y)) * .98, Y) for Y in jy]) L["jaw_l"] = np.array([h.P(-float(h.hw(Y)) * .98, Y) for Y in jy]) # neck: a cylinder behind the jaw (axis 0.08 H behind the ears' plane), leaning slightly forward nY = np.linspace(.62, 1.42, 16) nl, nr = [], [] for Y in nY: wn = h.neck_w + max(0, Y - 1.24) * 1.1 # flares into the trapezius phi = np.linspace(0, 2 * np.pi, 48) z = -.06 + .19 * np.cos(phi) x = wn * np.sin(phi) * math.cos(h.yaw) + z * math.sin(h.yaw) nl.append(h.cx + u * x.min()) nr.append(h.cx + u * x.max()) ny = h.top + u * nY L["neck"] = np.vstack([np.stack([nr, ny], 1), np.stack([nl, ny], 1)[::-1]]) # torso with its own yaw (P-R8) ty = math.radians(p["torso_yaw"]) f = p["sex"] == "f" # shoulders ~2.6-3 face widths (biacromial+deltoids ~40-46 cm vs face ~14 cm); a bust crops them at the frame sh = (1.0 if f else 1.15) * (.8 if h.child else 1.0) * (.97 + .06 * rng.random()) # trapezius slope ~20 deg from the neck to a rounded deltoid, then the arms hang (research17 head+neck+shoulders) rows = [(1.12, h.neck_w + .03), (1.19, .38 * sh), (1.27, .64 * sh), (1.35, .84 * sh), (1.44, .95 * sh), (1.58, 1.0 * sh), (1.80, .99 * sh), (3.2, .97 * sh)] tY = np.linspace(1.13, 3.2, 40) tl, tr = [], [] cx_t = h.cx + u * (-.06 * math.sin(h.yaw)) for Y in tY: wt = float(_interp(Y, rows)) phi = np.linspace(0, 2 * np.pi, 48) z = .42 * wt * np.cos(phi) x = wt * np.sin(phi) * math.cos(ty) + z * math.sin(ty) tl.append(cx_t + u * x.min()) tr.append(cx_t + u * x.max()) tyy = h.top + u * tY L["torso"] = np.vstack([np.stack([tr, tyy], 1), np.stack([tl, tyy], 1)[::-1]]) L["torso_cx"], L["torso_yaw"] = cx_t, ty
def PT(X, Y, prot=0.0): # torso surface point wt = max(float(_interp(Y, rows)), 1e-3) z = .42 * wt * math.sqrt(max(0, 1 - (X / wt) ** 2)) + prot return np.array([cx_t + u * (X * math.cos(ty) + z * math.sin(ty)), h.top + u * Y]) L["PT"] = PT # features (surface-projected so 3/4 foreshortens the far side) eyes = [] for side in (-1, 1): X = side * h.eye_dx c = h.P(X, h.eye_y, -.03) a = h.P(X - h.eye_w, h.eye_y, -.03) b = h.P(X + h.eye_w, h.eye_y, -.03) eyes.append(dict(side=side, c=c, inner=(a if side > 0 else b), outer=(b if side > 0 else a), w=abs(b[0] - a[0]) / 2, h=h.eye_h * u, vis=h.facing(X, h.eye_y))) L["eyes"] = eyes L["nose"] = dict(root=h.P(0, h.eye_y - .01, .02), tip=h.P(0, h.nose_y - .035, .11), base=h.P(0, h.nose_y, .07), wing_l=h.P(-h.nose_w, h.nose_y - .01, .03), wing_r=h.P(h.nose_w, h.nose_y - .01, .03)) L["mouth"] = dict(c=h.P(0, h.mouth_y, .035), l=h.P(-h.mouth_w, h.mouth_y, .01), r=h.P(h.mouth_w, h.mouth_y, .01)) L["chin"] = h.P(0, .985, .02) ears = [] for side in (-1, 1): if math.cos(math.radians(90) * side * -1 + h.yaw) < -0.05 and False: continue w = float(h.hw(.52)) c = h.P(side * w, .53, Z=-.04) vis = -side * math.sin(h.yaw) + .25 # ear on the side turning toward us is visible if vis > 0: ears.append(dict(side=side, c=c, w=u * .05 * min(1, vis * 2.0 + .1), h=u * (.15 if not h.old else .17))) L["ears"] = ears return L
# ============================================================ stand-in hair layout (six styles; research17 hair2 s10)def _shell_discs(h, st, sex, lift_top, lift_side): """the cap as a region of the hair SHELL: every visible shell point above the hairline (which runs over the forehead, down the sideburn in front of the ear, round the ear and down to the nape), as discs (x, y, r) in px. Back-facing points are culled, so a turned head shows hair over the side and back of the skull (the 3/4 near side), not skin.""" u = h.u th = np.radians(np.linspace(-180, 180, 121))
def yh(t): a = abs(math.degrees(t)) sn = abs(math.sin(t)) front = h.hair_y + .07 * sn * sn + .16 * max(0, sn - .75) / .25 if a <= 55: return front f55 = h.hair_y + .07 * .67 + .16 * .07 / .25 if a <= 92: return f55 + (.56 - f55) * (a - 55) / 37 if a <= 118: return .50 if st != "short" or sex == "f" else .47 return .50 + .30 * (a - 118) / 62 discs = [] ct, st_ = math.cos(h.yaw), math.sin(h.yaw) for t in th: for Y in np.linspace(0, yh(t), 26): w = float(h.hw(Y)) d = float(h.dz(Y)) if math.cos(t) >= 0 else float(h.db(Y)) g = float(np.interp(Y, [0, .25, .55], [lift_top, (lift_top + lift_side) / 2, lift_side])) X, Z = (w + g) * math.sin(t), (d + g) * math.cos(t) nz = -math.sin(t) / max(w, .05) * st_ + math.cos(t) / max(d, .05) * ct if nz < -0.02: continue q = h.P(X, Y, Z=Z) discs.append((float(q[0]), float(q[1]), u * .028)) return discs
def hair_standin(p, L, rng): """hair as data: masses (polygons px), clumps (root, tip, width, kind), part point. Recipes follow research17/units/hair2.md s10 (lift, length, clumps) with seed jitter; drawn per style by the painter.""" h, u = L["head"], L["u"] st = p["hair"] k = lambda a, b: a + (b - a) * rng.random() H = {"style": st, "masses": {}, "clumps": [], "part": None, "wisps": True} if st == "bald": H["masses"]["cap"] = None H["wisps"] = False return H part_x = {"short": .07, "long": .06, "bob": .07, "curly": .03}.get(st, 0.0) * (1 if rng.random() < .5 else -1) H["part"] = h.P(part_x, .02, .06) H["part_x"] = part_x lift_top, lift_side = {"short": (.08, .02), "long": (.05, .03), "bob": (.06, .035), "ponytail": (.035, .015), "curly": (.13, .10), "bun": (.035, .015)}[st] if p["sex"] == "m" and st == "short": lift_top = k(.05, .09) # cap: the head outline (crown -> ear row) pushed out along its normal by the lift (top lift_top -> side lift_side) Ys = np.linspace(0, .55, 40) l, r = h.silhouette(Ys) yy = h.top + u * Ys ring = np.vstack([np.stack([r, yy], 1)[::-1], np.stack([l, yy], 1)[1:]]) # right ear row -> crown -> left ear row tng = np.gradient(ring, axis=0) tng /= np.linalg.norm(tng, axis=1, keepdims=True) + 1e-9 nrm = np.stack([tng[:, 1], -tng[:, 0]], 1) # outward for this winding if nrm[len(nrm) // 2, 1] > 0: nrm = -nrm Yr = np.concatenate([Ys[::-1], Ys[1:]]) lift = np.interp(Yr, [0, .25, .55], [lift_top, (lift_top + lift_side) / 2, lift_side]) * u capo = ring + nrm * lift[:, None] H["cap_rows"] = (Ys, l, r, yy) # hairline on the face (front surface): forehead centre hair_y, down to the temples and the sideburn hl = [] for X in np.linspace(-1, 1, 13): w = float(h.hw(h.hair_y + .12 * X * X)) Y = h.hair_y + .07 * X * X + .16 * max(0, abs(X) - .75) / .25 hl.append(h.P(X * w * .96, Y, .01)) H["hairline"] = np.array(hl) # the cap polygon (outer silhouette, crown -> ears) + the hairline as its lower edge in front keep = Yr < .45 H["masses"]["cap"] = np.vstack([H["hairline"][::-1][:1], capo[keep], H["hairline"][:1], H["hairline"][1:-1]]) # the cap as a region of the hair SHELL: every visible shell point above the hairline (which runs over the forehead, # down the sideburn in front of the ear, round the ear and down to the nape), splatted as discs. Back-facing points # are culled, so a turned head shows hair over the side and back of the skull (the 3/4 near side), not skin. discs = _shell_discs(h, st, p["sex"], lift_top, lift_side) H["cap_discs"] = discs # back hair (behind face, neck and shoulders) for long styles end = {"long": k(1.55, 1.95), "bob": k(.98, 1.12), "curly": k(.95, 1.25), "short": .62, "ponytail": .6, "bun": .6}[st] H["end"] = end if st in ("long", "bob", "curly"): bY = np.linspace(.3, end, 22) out = {"long": .06, "bob": .10, "curly": .16}[st] wid = [] for Y in bY: l, r = h.silhouette([min(Y, .55)], lift_side + out * min(1, Y / .9)) if Y > .9 and st == "long": # rests on the shoulders: widens spread = (Y - .9) * .25 * u l, r = l - spread, r + spread if st == "bob" and Y > end - .2: # bell: tips curve in under the jaw q = (Y - (end - .2)) / .2 l, r = l + q * q * .06 * u, r - q * q * .06 * u wid.append((l[0], r[0])) wid = np.array(wid) by = h.top + u * bY # bottom = lock tips, uneven (hair2 H2-5): V notches across the bottom ntip = {"long": 7, "bob": 6, "curly": 8}[st] xs = np.linspace(wid[-1, 1], wid[-1, 0], ntip * 2 + 1) tips = [] for i, x in enumerate(xs): dy = (k(.0, .10) if i % 2 == 0 else -k(.05, .14)) * u * (.5 if st == "bob" else 1) tips.append((x, by[-1] + dy)) H["masses"]["back"] = np.vstack([np.stack([wid[:, 1], by], 1), np.array(tips), np.stack([wid[:, 0], by], 1)[::-1]]) if st == "ponytail": sgn = -1 if math.sin(h.yaw) > 0.05 else (1 if math.sin(h.yaw) < -0.05 else (1 if rng.random() < .5 else -1)) tie = h.P(sgn * .05, .32, Z=-.46) tl = [tie + np.array([sgn * u * .02, 0])] L_t = k(.75, 1.05) for i, t in enumerate(np.linspace(0, 1, 7)[1:]): tl.append(tie + np.array([sgn * u * (.12 * math.sin(t * 2.2) + .06 * t), u * L_t * t])) H["tail"] = (np.array(tl), u * k(.17, .22)) if st == "bun": H["bun"] = (h.P(k(-.04, .04), -.08, Z=-.18), u * k(.12, .15)) if st == "curly": H["curl_balls"] = [] Ys2 = np.linspace(-.05, end, 14) for Y in Ys2: l, r = h.silhouette([min(max(Y, 0), .6)], lift_top * (.8 if Y < .3 else .9)) for x in (l[0], r[0]): H["curl_balls"].append((x + k(-.03, .03) * u, h.top + u * Y + k(-.03, .03) * u, u * k(.07, .12))) for X in np.linspace(-.3, .3, 6): H["curl_balls"].append((h.P(X, 0)[0] + k(-.03, .03) * u, h.top - u * (lift_top * .9) + k(-.02, .04) * u, u * k(.07, .11))) # clumps: bangs and side locks (root -> tip in front coords, projected), 4-6 bang clumps with uneven tips bangs = st in ("bob", "long") and rng.random() < .5 or (st == "short" and p["sex"] == "f" and rng.random() < .5) if re.search(r"\b(bangs|fringe)\b", p.get("text", "")): bangs = st != "bald" if p["sex"] == "m" and st == "short": bangs = False H["bangs"] = bangs clumps = [] if bangs: n = int(rng.integers(4, 7)) y_tip = h.brow_y + k(-.02, .03) xs = np.linspace(-.27, .27, n) + rng.normal(0, .015, n) for i, X in enumerate(xs): tip_y = y_tip + k(-.05, .03) - .04 * (abs(X) / .27) ** 2 root = (part_x + (X - part_x) * .3, .05) clumps.append(dict(kind="bang", root=root, mid=(X * .9, (h.hair_y + tip_y) / 2), tip=(X + k(-.03, .03), tip_y), w=k(.07, .11), val=["mid", "lit", "mid", "dk"][i % 4] if rng.random() < .8 else "mid")) else: # swept front locks from the parting: 2-3 clumps that cross the hairline and frame the forehead for i in range(int(rng.integers(2, 4))): sgn = 1 if (i % 2 == 0) == (part_x >= 0) else -1 X0 = part_x + sgn * k(.02, .08) clumps.append(dict(kind="sweep", root=(X0, .04), mid=(X0 + sgn * k(.10, .16), h.hair_y - .04), tip=(sgn * k(.24, .30), h.hair_y + k(-.01, .03)), w=k(.08, .12), val="lit" if i == 0 else "mid")) if st in ("long", "bob", "curly"): # side locks overlap the face edge on both sides (P-R6), longer on the far side in 3/4 for side in (-1, 1): for j in range(int(rng.integers(1, 3))): X = side * (float(h.hw(.5)) - k(.0, .05)) clumps.append(dict(kind="side", root=(side * .27, h.hair_y + .02), mid=(X - side * k(.0, .03), .55), tip=(X + side * k(.0, .06), min(end, k(.95, 1.25)) if st != "bob" else end - k(.0, .06)), w=k(.06, .10), val="dk" if side == p["light"] * -1 else "mid")) H["clumps"] = clumps # front masses over the face (P-R6): a fringe mass behind the bang clumps; side masses that overlap the face edge if bangs: tipy = min(c["tip"][1] for c in clumps) fr = [h.P(X, h.hair_y + .03 * X * X / .09 - .02, .04) for X in np.linspace(-.30, .30, 9)] fr += [h.P(X, tipy - .015 + .02 * (abs(X) / .3) ** 2, .04) for X in np.linspace(.29, -.29, 9)] H["masses"]["fringe"] = np.array(fr) if st in ("long", "bob", "curly"): sides = [] for side in (-1, 1): near = -side * math.sin(h.yaw) # >0: this side turns toward us (shows more cheek) ov = k(.03, .07) - .03 * max(0, near) Yb = min(end, 1.25) if st != "bob" else end - .02 inner = [] for Y in np.linspace(h.hair_y + .08, Yb, 10): w = float(h.hw(min(Y, .86))) if st == "bob" and Y > .85: w = float(h.hw(.86)) + (Y - .85) * .1 inner.append(h.P(side * (w - ov * min(1, (Y - h.hair_y) / .25)), Y, .02)) l, r = h.silhouette(np.linspace(h.hair_y, min(Yb, .6), 6), lift_side + .02) outer_x = r if side > 0 else l outer = [np.array([x, h.top + u * Y]) for x, Y in zip(outer_x, np.linspace(h.hair_y, min(Yb, .6), 6))] last = outer[-1] outer += [np.array([last[0] + side * u * .02, h.top + u * Yb])] sides.append(np.vstack([inner, outer[::-1]])) H["masses"]["sides"] = sides return H
# ============================================================ value plan + palette (P-R1, P-R9, research16 rules 1, 5, 11)BANDS = {"B4": (.88, .94), "B3": (.70, .82), "B2": (.52, .64), "B1": (.34, .46), "B0": (.14, .26)}
def palette(p, rng, base=None): """the value plan in OKLab L: bands B0..B4; base = the kit's material colours (skin, hair, cloth) when given""" k = lambda a, b: a + (b - a) * rng.random() Ls, Cs, hs = lch_of(hexc(MST[p["skin"]]) if base is None else base["skin"]) Cs = max(Cs, .035) hs = min(max(hs, 50), 66) + k(-3, 3) # P-R1: the face's lit plane sits one band below the lightest light (B3 top <= .80); dark skin keeps its value lit = min(Ls * k(.97, 1.02), .79) if Ls > .45 else Ls + .05 sh_d = max(.10, .26 * lit + .04) C = {} C["skin_lit"] = lch(lit, Cs * 1.05, hs) C["skin_hi"] = lch(min(lit + .035, .82), Cs * .95, hs + 4) C["skin_half"] = lch(lit - sh_d * .45, Cs * .95, hs - 3) # the turning halftone, slightly cooler (less red) # P-R9: skin shadows olive/brown, never pink: hue rotated toward yellow-green, chroma held down C["skin_sh"] = lch(lit - sh_d, Cs * .88, hs + 9) C["skin_deep"] = lch(lit - sh_d * 1.2, Cs * .85, hs + 5) # the face's darkest is NOT the picture's darkest (P-R1) C["skin_refl"] = lch(lit - sh_d * .75, Cs * 1.05, hs + 2) C["skin_warm"] = lch(lit - .06, Cs * 1.45, hs - 22) # ears, nose tip, cheeks: the red zone, small C["lip_up"] = lch(lit - sh_d * 1.15, Cs * 1.25, hs - 30) C["lip_lo"] = lch(lit - sh_d * .45, Cs * 1.45, hs - 28) C["socket"] = lch(lit - sh_d * .85, Cs * .8, hs + 6) C["eye"] = lch(max(.14, min(.24, lit - .45)), .02, 60) C["sclera"] = mixc(C["skin_half"], lch(min(lit, .80), .01, 90), .45) # never white (P-R3) if base is not None: hc = lch_of(base["hair"]) redw = re.search(r"\b(red|auburn|ginger|copper|redhead)\b", p.get("text", "")) hc = (min(.86, hc[0] * .92), min(hc[1], .12 if redw else .065), hc[2]) if hc[1] < .02: # grey / white hair: a warm neutral, never a cold blue next to skin hc = (hc[0], .012, 85) if not p.get("hair_col") or p["hair_col"] not in HAIR_COL: p["hair_col"] = "blonde" if hc[0] > .62 and hc[1] > .04 else ("grey" if hc[0] > .55 else "brown") else: hc = HAIR_COL[p["hair_col"]] hL = hc[0] + k(-.03, .03) C["hair_mid"] = lch(hL, hc[1], hc[2]) C["hair_dk"] = lch(max(.09, min(hL * .5, lit - sh_d * 1.6 - .06)), hc[1] * .8, hc[2] - 5) # the picture's darkest dark C["hair_lit"] = lch(min(.90, hL + .065), hc[1] * 1.0, hc[2] + 4) C["hair_hi"] = lch(min(.93, hL + .13 + (.06 if hL > .6 else 0)), hc[1] * .7, hc[2] + 10) # ground: counterchange with the hair (dark hair -> light ground; light hair -> darker ground) fam = rng.choice(["warm", "olive", "cool", "green", "slate", "umber"], p=[.18, .2, .18, .16, .18, .1]) gh = {"warm": 80, "olive": 105, "cool": 230, "umber": 65, "green": 140, "slate": 245}[fam] gC = {"warm": .03, "olive": .04, "cool": .03, "umber": .035, "green": .035, "slate": .04}[fam] if hL < .5: gL = k(.66, .76) else: gL = k(.34, .46) gL = float(np.clip(gL, lit - .30, lit - .02)) # the face reads lighter than (or level with) its ground (critic10 face_ground_dL) if p.get("medium") == "watercolor": # watercolour keys high: the ground is a pale wash, paper shows (rule 10) gL = k(.80, .88) if hL < .6 else k(.62, .72) C["ground"] = lch(gL, gC, gh) C["ground_lo"] = lch(gL - .12, gC * 1.1, gh - 8) C["ground_hi"] = lch(min(.93, max(gL + .12, lit + .10)), gC * .8, gh + 8) # the reserved lightest light (B4, P-R1) # clothes: prompt colour (muted for the big mass) or a seeded dark/light from the gamut (research16 rule 5) if base is not None and p.get("cloth") and "cloth" in base: cL, cC, cH = lch_of(base["cloth"]) C["cloth"] = lch(min(cL, .86), min(cC, .09), cH) C["accent"] = lch(min(.62, cL + .05), min(.15, cC * 1.3), cH) elif p.get("cloth"): cL, cC, cH = CLOTH_COL[p["cloth"]] C["cloth"] = lch(cL, min(cC, .09), cH) C["accent"] = lch(min(.62, cL + .05), min(.15, cC * 1.3), cH) else: if (gL < .5 and rng.random() < .3) or rng.random() < .1: C["cloth"] = lch(k(.82, .88), .015, gh + 10) # light shirt / blouse (gives the B4 edge on a dark ground) else: hue, ch = [(255, .06), (150, .045), (20, .06), (230, .03), (60, .03), (300, .04), (0, .004)][int(rng.integers(0, 7))] C["cloth"] = lch(k(.24, .38), ch * k(.8, 1.2), hue) C["accent"] = lch(.52, .14, float(rng.choice([28, 40, 250, 150]))) cL = lch_of(C["cloth"])[0] C["cloth_sh"] = shift(C["cloth"], dL=-.14 - .08 * (cL > .7), kC=.9, dh=-6) C["cloth_lt"] = shift(C["cloth"], dL=.07, kC=.9, dh=6) if cL > .78: C["cloth_lt"] = lch(min(.95, max(cL + .06, lch_of(C["ground_hi"])[0])), .01, 90) C["light_L"] = lit # skin specular: deep skin shows bright, cool-ish highlights on the forehead, nose ridge, cheekbone (painted refs) C["skin_spec"] = lch(min(.86, lit + (.30 if lit < .55 else .08)), Cs * .5, hs + 15) return C
# ============================================================ the painterdef _dirfield(img, sigma, angle_bias=None): """isophote direction of the canvas value (structure tensor smallest eigenvector): marks run along the forms and the edges they carry (P-R10, research16 idea 4)""" Lm = ndimage.gaussian_filter(lum(img), 1.5) gy, gx = np.gradient(Lm) Jxx = ndimage.gaussian_filter(gx * gx, sigma) Jxy = ndimage.gaussian_filter(gx * gy, sigma) Jyy = ndimage.gaussian_filter(gy * gy, sigma) ang = .5 * np.arctan2(2 * Jxy, Jxx - Jyy) + np.pi / 2 # along the isophote coh = np.sqrt((Jxx - Jyy) ** 2 + 4 * Jxy ** 2) / (Jxx + Jyy + 1e-6) return ang.astype(np.float32), coh.astype(np.float32)
def marks(cv, region, ang, n, length, width, rng, alpha=.6, jitL=.025, soft=.6, ang_fallback=None, coh=None, pickup=None, height=None): """n brush marks inside region: blunt start, full body, tapering tail; colour picked from the canvas under the mark start (so marks carry the value plan and drag a little colour across the edges they cross), +- a small value jitter""" ys, xs = np.nonzero(region > .5) if not len(xs) or n <= 0: return W, H = cv.W, cv.H i = rng.integers(0, len(xs), n) x, y = xs[i].astype(np.float32) + rng.random(n), ys[i].astype(np.float32) + rng.random(n) a = ang[ys[i], xs[i]].copy() if ang_fallback is not None and coh is not None: weak = coh[ys[i], xs[i]] < .25 a[weak] = ang_fallback[ys[i], xs[i]][weak] if np.ndim(ang_fallback) else ang_fallback a += rng.normal(0, .18, n) Lr = length * (.55 + .9 * rng.random(n)) wr = width * (.6 + .8 * rng.random(n)) / 2 src = pickup if pickup is not None else ndimage.gaussian_filter(cv.img, (1.2, 1.2, 0)) col = src[ys[i], xs[i]] lab = to_lab(col) lab[:, 0] += rng.normal(0, jitL, n) lab[:, 1:] *= (1 + rng.normal(0, .08, (n, 1))) lab[:, 1:] += rng.normal(0, .006, (n, 2)) # broken colour: a little hue wander per mark (no flat digital fill) col = np.clip(from_lab(lab), 0, 1) lay = Image.new("RGBA", (W, H), (0, 0, 0, 0)) d = ImageDraw.Draw(lay) hl = Image.new("L", (W, H), 0) if height is not None else None dh = ImageDraw.Draw(hl) if hl is not None else None ca, sa = np.cos(a), np.sin(a) for j in range(n): dx, dy = ca[j] * Lr[j] / 2, sa[j] * Lr[j] / 2 nx, ny = -sa[j] * wr[j], ca[j] * wr[j] X, Y = x[j], y[j] poly = [(X - dx + nx * .7, Y - dy + ny * .7), (X - dx * .3 + nx, Y - dy * .3 + ny), (X + dx * .5 + nx * .8, Y + dy * .5 + ny * .8), (X + dx, Y + dy), (X + dx * .5 - nx * .8, Y + dy * .5 - ny * .8), (X - dx * .3 - nx, Y - dy * .3 - ny), (X - dx - nx * .7, Y - dy - ny * .7)] c = col[j] d.polygon(poly, fill=(int(c[0] * 255), int(c[1] * 255), int(c[2] * 255), int(255 * alpha))) if dh is not None: dh.polygon(poly, fill=int(60 + 120 * rng.random())) A = np.asarray(lay, np.float32) / 255 if soft: # blur premultiplied colour and coverage separately (no dark fringe from the transparent black) pm = ndimage.gaussian_filter(A[..., :3] * A[..., 3:4], (soft, soft, 0)) cov = ndimage.gaussian_filter(A[..., 3], soft)[..., None] A = np.concatenate([pm / np.maximum(cov, 1e-4), cov], -1) al = A[..., 3:4] * np.clip(region, 0, 1)[..., None] cv.img[:] = cv.img * (1 - al) + np.clip(A[..., :3], 0, 1) * al if hl is not None: hh = np.asarray(hl.filter(ImageFilter.GaussianBlur(.8)), np.float32) / 255 * np.clip(region, 0, 1) height[:] = np.maximum(height * .7, hh)
def draw(p, W=512, H=640, seed=None, layout=None, hair=None, medium=None, trace=None, base=None): """paint one head-and-shoulders portrait -> HxWx3 uint8. p = params (params_from_prompt or the kit's params).""" seed = p.get("seed", 0) if seed is None else seed rng = np.random.default_rng(seed * 104729 + 3) medium = medium or p.get("medium") or "oil" W, H = int(min(W, 1024)), int(min(H, 1024)) Lo = layout or layout_standin(p, W, H, rng) Hl = hair or hair_standin(p, Lo, rng) C = palette(p, rng, base) hd, u = Lo["head"], Lo["u"] s = p["light"] # -1 light from the viewer's left, +1 from the right; shadow side = -s sc = u / 230.0 # edge widths in the docs are at a ~230 px head k = lambda a, b: a + (b - a) * rng.random() cv = Canvas(W, H, C["ground"]) yy, xx = np.mgrid[0:H, 0:W].astype(np.float32)
# ---- 2 toned ground: lighter behind the head's shadow side (counterchange), darker low and at the lit edge t = np.clip(.5 + s * -(xx - W / 2) / W * 1.2, 0, 1) # 1 toward the shadow side g = mixc(C["ground_lo"], C["ground"], np.clip(.35 + .65 * t, 0, 1)[..., None]) cv.img[:] = g put(cv, ell_mask(cv, W / 2 - s * W * .30, H * .22, W * .30, H * .26, soft=50 * sc), C["ground_hi"], k(.75, .95)) put(cv, ell_mask(cv, W / 2 + s * W * .45, H * .9, W * .5, H * .35, soft=80 * sc), C["ground_lo"], .6) gmask = np.ones((H, W), np.float32) if on("pp_marks"): ang = np.full((H, W), math.radians(90 + s * k(8, 25)), np.float32) marks(cv, gmask, ang, int(500 * (W * H) / (512 * 640)), 70 * sc, 16 * sc, rng, alpha=.2, jitL=.03, soft=2.5 * sc)
# ---- 3 big masses in z order m_back = poly_mask(cv, Hl["masses"]["back"], 1.5 * sc) if "back" in Hl["masses"] else None for bp in Hl.get("behind", []): mb = poly_mask(cv, bp, 1.5 * sc) m_back = mb if m_back is None else np.maximum(m_back, mb) if Hl.get("bun_poly") is not None and not Hl.get("bun_front"): mb = poly_mask(cv, Hl["bun_poly"], 1.2 * sc) m_back = mb if m_back is None else np.maximum(m_back, mb) Hl["m_bun_back"] = mb if m_back is not None: put(cv, m_back, C["hair_dk"]) put(cv, m_back * np.clip(.5 + s * (xx - hd.cx) / (u * .6), 0, 1), C["hair_mid"], .7) if "tail" in Hl: pts, wt = Hl["tail"] _hair_ribbon(cv, pts, wt, C["hair_mid"], rng, sc) m_neck = poly_mask(cv, Lo["neck"], 1.0 * sc) put(cv, m_neck, C["skin_half"]) m_torso = poly_mask(cv, Lo["torso"], 1.0 * sc) _neckline(cv, Lo, p, C, rng, sc, m_torso) m_neck = np.maximum(m_neck * (1 - Lo["m_garment"]), Lo["m_open"]) Lo["m_neck"], Lo["m_torso"] = m_neck, m_torso _cloth_light(cv, Lo, C, s, sc, rng) _lightest_light(cv, Lo, C, s, sc, rng) ears_over = p["hair"] in ("short", "ponytail", "bun", "bald") # the ear sits in front of short / tied-back hair for e in Lo["ears"] if not ears_over else []: _ear(cv, e, C, s, sc) m_face = poly_mask(cv, Lo["face"], .8 * sc) put(cv, m_face, C["skin_lit"]) # the neck: shadow everywhere except a lit wedge on the light side (A2d / P-R7) neck_sh = m_neck * (1 - m_face) * np.clip(.55 + .45 * np.clip(-s * (xx - hd.cx) / (u * .25), -1, 1), 0, 1) put(cv, neck_sh, C["skin_sh"], .85)
if on("pp_planes"): _planes(cv, Lo, p, C, s, sc, m_face, rng) if on("pp_chincast"): _chin_cast(cv, Lo, C, s, sc, m_face, m_neck) if on("pp_features"): _features(cv, Lo, p, C, s, sc, m_face, rng) _hair(cv, Lo, Hl, p, C, s, sc, m_face, rng) for e in Lo["ears"] if ears_over else []: me = _ear(cv, e, C, s, sc) if me is not None and "m_hair" in Lo: Lo["m_hair"] = Lo["m_hair"] * (1 - me) # later hair marks / wisps leave the ear alone if p.get("beard"): _beard(cv, Lo, C, s, sc, m_face, rng) height = np.zeros((H, W), np.float32) if on("pp_edges"): _edges(cv, Lo, Hl, p, C, s, sc, m_face, m_torso, rng) if on("pp_marks"): _form_marks(cv, Lo, Hl, p, C, s, sc, m_face, m_neck, m_torso, rng, medium, height) _accents(cv, Lo, p, C, s, sc, rng) if on("pp_medium"): _medium(cv, medium, rng, sc, height, m_face) if on("pp_valueplan"): _reserve_lightest(cv, m_face) out = (np.clip(cv.img, 0, 1) * 255 + .5).astype(np.uint8) if trace is not None: trace.append("style_paint: %s %s age %d %s skin %d hair %s/%s yaw %.0f light %+d" % ( medium, p["sex"], p["age"], "smile" if p.get("smile") else "neutral", p["skin"], p["hair"], p["hair_col"], p["yaw"], s)) return out
def _reserve_lightest(cv, m_face): """P-R1 enforced: the face sits one band below the lightest light. If the face's lights reach the picture's top values, compress them (soft knee) under the lightest light outside the face, so the face holds < 5% of the top 3%""" lab = to_lab(cv.img) L = lab[..., 0] inside = m_face > .5 if inside.sum() < 50 or (~inside).sum() < 50: return top_out = float(np.quantile(L[~inside], .985)) cap = top_out - .035 knee = cap - .06 hi = inside & (L > knee) if not hi.any(): return x = L[hi] - knee L[hi] = knee + (cap - knee) * (1 - np.exp(-x / max(cap - knee, 1e-3))) lab[..., 0] = L cv.img[:] = np.where(inside[..., None], from_lab(lab), cv.img)
def _neckline(cv, Lo, p, C, rng, sc, m_torso): """a garment opening (crew / V / scoop / collar) on the torso, with the lit collar edge = one of the hard edges""" if "chest" in Lo: # the kit layout decided the neckline: chest skin inside it, garment outside m_open = poly_mask(cv, Lo["chest"], .8 * sc) * m_torso m_gar = m_torso * (1 - m_open) put(cv, m_gar, C["cloth"]) put(cv, m_open, C["skin_half"]) put(cv, m_open, C["skin_sh"], .4) Lo["m_garment"], Lo["m_open"] = m_gar, m_open return PT = Lo["PT"] kind = rng.choice(["crew", "v", "scoop", "collar"]) if p["sex"] == "f" else rng.choice(["crew", "collar", "v"]) depth = {"crew": 1.30, "v": 1.56, "scoop": 1.44, "collar": 1.34}[kind] hw = {"crew": .30, "v": .28, "scoop": .40, "collar": .27}[kind] top = 1.05 pts = [PT(-hw * math.cos(a), 1.17 + (depth - 1.17) * math.sin(a)) for a in np.linspace(0, np.pi, 13)] + [PT(hw, top), PT(-hw, top)] if kind == "v": pts = [PT(-hw, 1.17), PT(-hw * .35, (1.17 + depth) / 2), PT(0, depth), PT(hw * .35, (1.17 + depth) / 2), PT(hw, 1.17), PT(hw, top), PT(-hw, top)] m_open = poly_mask(cv, pts, .8 * sc, smooth=False) * m_torso m_gar = m_torso * (1 - m_open) put(cv, m_gar, C["cloth"]) put(cv, m_open, C["skin_half"]) put(cv, m_open, C["skin_sh"], .4) # the chest under the head is a step darker than the face Lo["m_garment"], Lo["m_open"] = m_gar, m_open if kind == "collar": for side in (-1, 1): col = [PT(side * hw * 1.05, 1.18), PT(side * hw * .2, depth + .02), PT(side * hw * .9, depth + .16), PT(side * hw * 1.6, 1.28)] put(cv, poly_mask(cv, col, .6 * sc), C["cloth_lt"]) Lo["neckline"] = (kind, pts)
def _cloth_light(cv, Lo, C, s, sc, rng): """the garment as two value families: the shadow side + the cast of the head and hair across the chest; the lit shoulder plane on the light side keeps the strongest cloth edge (P-R5); a light garment loses its far edge""" hd, u = Lo["head"], Lo["u"] mg = Lo["m_garment"] H, W = cv.H, cv.W yy, xx = np.mgrid[0:H, 0:W].astype(np.float32) cx = Lo["torso_cx"] sideL = np.clip(.5 - s * (xx - cx) / (u * .9), 0, 1) # 1 on the shadow side put(cv, mg * sideL ** 1.5, C["cloth_sh"], .75) put(cv, ell_mask(cv, cx - s * u * .15, hd.top + u * 1.3, u * .55, u * .22, 14 * sc) * mg, C["cloth_sh"], .6) # head/hair cast put(cv, ell_mask(cv, cx + s * u * .75, hd.top + u * 1.45, u * .35, u * .14, 12 * sc) * mg, C["cloth_lt"], .55) # lit shoulder top put(cv, mg * np.clip((yy - (hd.top + u * 2.0)) / (u * .8), 0, 1), C["cloth_sh"], .35) # falls off below
def _lightest_light(cv, Lo, C, s, sc, rng): """P-R1: the lightest light lives in the figure but not in the face: a light collar / undershirt edge along the neckline (strongest on the lit side) - the Sargent shawl's job, made general; it is also one of the hard edges (P-R5)""" hd, u = Lo["head"], Lo["u"] mo, mg = Lo["m_open"], Lo["m_garment"] if mo.max() <= 0: return ring = np.clip(ndimage.gaussian_filter((mo > .5).astype(np.float32), .035 * u) - mo * 1.0, 0, 1) * mg ring = np.clip(ring * 3, 0, 1) H, W = cv.H, cv.W xx = np.arange(W, dtype=np.float32)[None, :] lit = np.clip(.35 + .65 * np.clip(.5 + s * (xx - Lo["torso_cx"]) / (u * .5), 0, 1), 0, 1) white = lch(min(.95, max(.88, lch_of(C["ground_hi"])[0])), .012, 90) cL = lch_of(C["cloth"])[0] put(cv, ring * lit, white, .95 if cL < .7 else .7)
def _ear(cv, e, C, s, sc): cx, cy = e["c"] w, h = e["w"], e["h"] if "outline" in e: m = poly_mask(cv, e["outline"], 1.0 * sc) put(cv, m, C["skin_warm"] if e["side"] == s else C["skin_sh"]) put(cv, ell_mask(cv, cx, cy, w * .4, h * .25, 1.5 * sc) * m, C["skin_deep"], .7) return m pts = [(cx, cy - h * .5), (cx + e["side"] * w, cy - h * .35), (cx + e["side"] * w * 1.05, cy), (cx + e["side"] * w * .6, cy + h * .45), (cx, cy + h * .5), (cx - e["side"] * w * .2, cy)] m = poly_mask(cv, pts, 1.0 * sc) put(cv, m, C["skin_warm"] if e["side"] == s else C["skin_sh"]) put(cv, ell_mask(cv, cx + e["side"] * w * .4, cy, w * .35, h * .25, 1.5 * sc), C["skin_deep"], .7)
def _planes(cv, Lo, p, C, s, sc, m_face, rng): """P-R2: one shadow shape + one lit-plane shape, split by a designed boundary along the side of the nose, under the cheekbone, round the mouth and under the chin; lower face lit on the light side down to the chin (P-R7)""" hd, u = Lo["head"], Lo["u"] sd = -s # shadow side in front coordinates (x sign) k = lambda a, b: a + (b - a) * rng.random() P = hd.P ey, ny, my = hd.eye_y, hd.nose_y, hd.mouth_y # how far the light wraps: 3/4 light (light from the side the face turns to = broad shadow) vs short light turn = math.sin(hd.yaw) * s # >0: face turns toward the light (short light, narrower shadow) off = k(-.01, .02) - .03 * turn pattern = rng.choice(["loop", "loop", "rembrandt", "split"]) o2 = .03 if pattern == "loop" else (-.01 if pattern == "split" else 0) bd = [(.22 + o2, .16), (.20 + o2, .27), (.09 + off, ey - .085), (.055 + off, ey - .02), (.045 + off * .5, ey + .06), (.05, ny - .05), (.075 + o2, ny - .005), (.08 + o2 * 2, ny + .03), (hd.mouth_w + .03 + o2, my - .02), (hd.mouth_w + .02 + o2, my + .04), (.08 + o2, .92), (-.01, .99)] Lo["light_pattern"] = pattern far = [(.5, 1.06), (.5, .6), (.5, .10)] pts = [P(sd * x, y, .02) for x, y in bd] + [hd.P(sd * x, y, Z=.0 + .3) for x, y in far] pts[-3] = np.array([hd.cx + sd * u * .9, hd.top + u * 1.06]) pts[-2] = np.array([hd.cx + sd * u * .9, hd.top + u * .6]) pts[-1] = np.array([hd.cx + sd * u * .9, hd.top + u * .10]) # edge of the shadow shape: firm along the nose (a plane break), soft on the round cheek and jaw (P-R5, research16 rule 4) firm, soft_ = poly_mask(cv, pts, 2.5 * sc), poly_mask(cv, pts, 8 * sc) nx = hd.P(0, hd.nose_y - .1, .08)[0] near_nose = np.clip(1 - np.abs(np.arange(cv.W, dtype=np.float32)[None, :] - nx) / (.10 * u), 0, 1) m_sh = (firm * near_nose + soft_ * (1 - near_nose)) * m_face if pattern == "rembrandt": # the lit triangle on the shadow-side cheek, bounded by the nose and cheek shadows tri = poly_mask(cv, [P(sd * x, y, .02) for x, y in [(.075, ey + .07), (.21, ey + .06), (.09, ny - .005)]], 3 * sc) m_sh = m_sh * (1 - tri * .9) put(cv, m_sh, C["skin_sh"], .88) # the face turns away at its contour: a halftone ring inside the edge (lighter on the lit side, deepening on the # shadow side), so the plate reads as a form, not a flat mask d = ndimage.distance_transform_edt(m_face > .5) ring = np.clip(1 - d / (.085 * u), 0, 1) ** 1.6 put(cv, ring * (1 - m_sh), C["skin_half"], .55) put(cv, ring * m_sh, C["skin_deep"], .35) # under-planes: below the nose and the lower lip and under the jaw are a step darker than the planes facing up Ylow = hd.top + u * (hd.nose_y + .02) yy = np.arange(cv.H, dtype=np.float32)[:, None] put(cv, m_face * np.clip((yy - Ylow) / (u * .25), 0, 1) * (1 - m_sh), C["skin_half"], .25) put(cv, m_sh * (1 - poly_mask(cv, pts, 9 * sc)), C["skin_half"], .5) # a narrow halftone where the boundary turns # the core: darker band just inside the boundary on the cheek (the turning edge), soft core = [P(sd * x, y, .02) for x, y in [(.17, .30), (.10, ey - .06), (.11, ey + .05), (.14, ny - .02), (hd.mouth_w + .05, my), (.12, .90), (.24, .86), (.29, .62), (.28, .40)]] put(cv, poly_mask(cv, core, 7 * sc) * m_face * m_sh, C["skin_deep"], .35) # reflected light low on the shadow-side jaw (warm, small) put(cv, poly_mask(cv, [P(sd * x, y) for x, y in [(.2, .78), (.27, .74), (.26, .86), (.17, .93)]], 6 * sc) * m_sh, C["skin_refl"], .45) # lit-plane shape: forehead, nose ridge, lit cheek top, lit jaw + chin lp = [P(-sd * x, y, .02) for x, y in [(.25, hd.hair_y + .02), (-.04, hd.hair_y), (-.03, ey - .1), (-.01, ny - .06), (-.02, ny + .01), (.06, ny + .02), (hd.mouth_w * .6, my - .03), (.06, my + .05), (.0, .95), (.14, .90), (.24, .80), (.30, .58), (.27, ey - .06)]] put(cv, poly_mask(cv, lp, 4 * sc) * m_face * (1 - m_sh * .8), C["skin_hi"], .55) put(cv, ell_mask(cv, *P(-sd * .17, ey + .11), u * .07, u * .05, 6 * sc) * m_face * (1 - m_sh), C["skin_hi"], .45) # cheek top put(cv, ell_mask(cv, *P(-sd * .16, ey + .17), u * .06, u * .04, 8 * sc) * m_face * (1 - m_sh), C["skin_warm"], .18) # specular accents on the lit planes (small, soft; stronger on deep skin where they carry the form) for (X, Y, rx, ry, a) in [(-sd * .06, hd.hair_y + .08, .07, .025, .5), (-sd * .012, ey + .12, .012, .05, .6), (-sd * .19, ey + .09, .035, .018, .45), (-sd * .01, .93, .03, .012, .35)]: q = P(X, Y, .06) put(cv, ell_mask(cv, q[0], q[1], u * rx, u * ry, 5 * sc) * m_face * (1 - m_sh), C["skin_spec"], a * .55) # the far contour in 3/4 turns away: a soft halftone band along it (the plane change at the cheek/temple) if abs(hd.yaw) > .2: fs = 1 if hd.yaw < 0 else -1 # side of the face turning away (front coords) band = [P(fs * x, y) for x, y in [(.24, .22), (.33, .40), (.33, .62), (.27, .82), (.12, .96), (.18, .82), (.24, .62), (.24, .40)]] put(cv, poly_mask(cv, band, 6 * sc) * m_face, C["skin_half"], .5) # eye sockets as a broad soft halftone band (the brow-shadow band; copyB step 4) put(cv, poly_mask(cv, [P(x, y) for x, y in [(-.30, ey - .07), (.30, ey - .07), (.28, ey + .03), (-.28, ey + .03)]], 7 * sc) * m_face, C["socket"], .22) if hd.old: # age as value strokes: nasolabial fold, under-eye bags, forehead lines (soft) for side in (-1, 1): stroke(cv, [P(side * (hd.nose_w + .01), hd.nose_y - .01), P(side * (hd.mouth_w + .03), hd.mouth_y - .02), P(side * (hd.mouth_w + .045), hd.mouth_y + .05)], C["skin_sh"], 3.2 * sc, .45, soft=1.6 * sc) stroke(cv, [P(side * (hd.eye_dx - .05), ey + .035), P(side * hd.eye_dx, ey + .05), P(side * (hd.eye_dx + .05), ey + .035)], C["skin_sh"], 2.4 * sc, .35, soft=1.5 * sc) for i in range(2): Yl = hd.hair_y + .06 + .045 * i stroke(cv, [P(-.16, Yl + .01), P(0, Yl), P(.16, Yl + .01)], C["skin_half"], 2 * sc, .4, soft=1.4 * sc)
def _chin_cast(cv, Lo, C, s, sc, m_face, m_neck): """P-R7: the chin cast follows the jaw diagonally, offset down and away from the light, only on the neck""" hd, u = Lo["head"], Lo["u"] sd = -s P = hd.P jaw = [P(x, y) for x, y in [(-.24, .84), (-.12, .96), (0, 1.0), (.12, .96), (.24, .84)]] drop = np.array([sd * .05 * u, .08 * u]) slant = lambda q: q + drop + np.array([0, (q[0] - hd.cx) * sd * .25]) pts = jaw + [slant(q) for q in jaw[::-1]] m = poly_mask(cv, pts, 4 * sc) * m_neck * (1 - m_face) put(cv, m, C["skin_deep"], .85)
def _features(cv, Lo, p, C, s, sc, m_face, rng): """P-R3: features as value masses at portrait scale""" hd, u = Lo["head"], Lo["u"] P = hd.P sd = -s k = lambda a, b: a + (b - a) * rng.random() gaze = .25 * math.sin(hd.yaw) + k(-.1, .1) for e in Lo["eyes"]: if e["vis"] < .08: continue cx, cy = e["c"] w, h = e["w"], e["h"] * (1 - .15 * p.get("smile", 0)) inner, outer = e["inner"], e["outer"] shadowed = e["side"] == sd dim = .95 if shadowed else 1.0 # socket: one soft mass above and around the eye (merges into the shadow on the shadow side) put(cv, ell_mask(cv, cx, cy - h * .6, w * 1.35, h * 2.2, 5 * sc), C["socket"], .5 if shadowed else .38) # upper lid fold shadow put(cv, ell_mask(cv, cx, cy - h * 1.1, w * 1.05, h * .9, 2.5 * sc), C["socket"], .45) # the eye: dimmed lower white (never white), iris disc mostly under the lid, heavy upper lid alm = [inner, (cx, cy - h * 1.05), outer, (cx, cy + h * .85)] alm = [np.asarray(q) + np.array([0, 0]) for q in alm] m_eye = poly_mask(cv, [alm[0], (alm[0] + alm[1]) / 2 + [0, -h * .25], alm[1], (alm[1] + alm[2]) / 2 + [0, -h * .15], alm[2], (alm[2] + alm[3]) / 2 + [0, h * .2], alm[3], (alm[3] + alm[0]) / 2 + [0, h * .2]], .7 * sc) put(cv, m_eye, C["sclera"] * dim, .85) ix = cx + gaze * w * .5 ir = min(w * .48, h * 1.25) put(cv, ell_mask(cv, ix, cy + h * .05, ir, ir, .8 * sc) * m_eye, C["eye"]) put(cv, ell_mask(cv, ix, cy + h * .35, ir * .7, ir * .35, 1.2 * sc) * m_eye, shift(C["hair_mid"], L=.36, kC=.8) if False else lch(.34, .04, 60), .45) # heavy upper lid, thickest toward the outer corner (copy_rules F1 applies to paint as the darkest accent) lid = [inner, (inner[0] * .7 + outer[0] * .3, cy - h * 1.1), (cx, cy - h * 1.2), (inner[0] * .2 + outer[0] * .8, cy - h * .9), outer + np.array([(outer[0] - cx) * .12, h * .1]), (inner[0] * .2 + outer[0] * .8, cy - h * .55), (cx, cy - h * .75), (inner[0] * .7 + outer[0] * .3, cy - h * .65)] put(cv, poly_mask(cv, lid, .8 * sc), C["eye"], .92) # lower lid: soft, outer half only stroke(cv, [(cx, cy + h * .95), (outer[0] * .6 + cx * .4, cy + h * .85), outer], C["socket"], 1.6 * sc, .45, soft=1 * sc) # brow: a soft value mass (hidden later under bangs) bw = w * (1.25 if p["sex"] == "f" else 1.35) thick = (2.8 if p["sex"] == "f" else 4.6) * sc * (.8 if hd.child else 1) by = hd.top + u * hd.brow_y b0 = (cx - e["side"] * w * .1 * (1 if e["side"] > 0 else -1) - (outer[0] - cx) * .55, by + h * .6) b1 = (cx + (outer[0] - cx) * .1, by - h * (.9 if p["sex"] == "f" else .5)) b2 = (cx + (outer[0] - cx) * 1.3, by + h * .4) brow_c = mixc(C["hair_dk"], C["skin_sh"], .35 if p["hair_col"] not in ("grey", "white", "blonde") else .6) if "brow" in e: # kit brow (inner -> mid -> outer), lifted a hair toward the arch b0, b1, b2 = e["brow"][0], e["brow"][1] + np.array([0, -h * .2]), e["brow"][2] stroke(cv, [b0, b1, b2], brow_c, thick, .75, soft=1.1 * sc, taper=(.1, .7)) # catchlight: tiny, on the light side of the iris (not pure white) if not shadowed or abs(hd.yaw) < .2: put(cv, ell_mask(cv, ix + s * ir * .35, cy - h * .2, max(1.0, ir * .18), max(1.0, ir * .18), .4 * sc), lch(.86, .01, 90), .8) # nose: shadow-side plane + under-plane + nostrils + one light stroke, nose cast on the shadow side ny, ey = hd.nose_y, hd.eye_y side_plane = [P(sd * x, y, pr) for x, y, pr in [(.02, ey + .02, .03), (.035, ey + .10, .06), (.045, ny - .06, .09), (hd.nose_w * .95, ny - .015, .04), (hd.nose_w * .55, ny + .005, .05), (.015, ny - .05, .11), (.0, ey + .10, .05)]] put(cv, poly_mask(cv, side_plane, 2.5 * sc), C["skin_sh"], .7) put(cv, ell_mask(cv, *P(0, ny - .005, .08), u * hd.nose_w * .95, u * .018, 2.5 * sc), C["skin_deep"], .6) # under-plane for side in (-1, 1): if hd.facing(side * hd.nose_w * .5, ny) < .2: continue put(cv, ell_mask(cv, *P(side * hd.nose_w * .45, ny - .006, .06), u * .016, u * .007, .9 * sc), C["skin_deep"], .9) put(cv, ell_mask(cv, *P(sd * .0, ny - .035, .115), u * .018, u * .016, 2.2 * sc), C["skin_warm"], .35) # tip warmth stroke(cv, [P(-sd * .012, ey + .02, .04), P(-sd * .016, ey + .09, .08), P(-sd * .014, ny - .05, .11)], C["skin_hi"], 3.6 * sc, .55, soft=1.4 * sc) put(cv, ell_mask(cv, *P(-sd * .012, ny - .045, .12), u * .014, u * .011, 1.4 * sc), C["skin_hi"], .6) put(cv, poly_mask(cv, [P(sd * x, y) for x, y in [(hd.nose_w * .9, ny - .05), (hd.nose_w * 1.9, ny - .02), (hd.nose_w * 1.6, ny + .03), (hd.nose_w * .7, ny + .02)]], 4 * sc) * m_face, C["skin_sh"], .55) # mouth: dark upper lip, lit lower lip, shadow below, corners fade my = hd.mouth_y mw = hd.mouth_w sm = p.get("smile", 0) * .012 lp = hd.lip up = [P(-mw, my - sm, .01), P(-mw * .45, my - lp * 1.1, .03), P(-mw * .12, my - lp * 1.2, .035), P(0, my - lp * .9, .035), P(mw * .12, my - lp * 1.2, .035), P(mw * .45, my - lp * 1.1, .03), P(mw, my - sm, .01), P(mw * .4, my + .002, .035), P(-mw * .4, my + .002, .035)] put(cv, poly_mask(cv, up, 1.2 * sc), C["lip_up"], .95) lo = [P(-mw * .8, my + .002 - sm * .5, .02), P(-mw * .3, my + lp * 1.5, .035), P(mw * .3, my + lp * 1.5, .035), P(mw * .8, my + .002 - sm * .5, .02)] put(cv, poly_mask(cv, lo, 2.0 * sc), C["lip_lo"], .65) put(cv, ell_mask(cv, *P(-sd * mw * .25, my + lp * .9, .04), u * mw * .25, u * lp * .45, 1.8 * sc), C["skin_hi"], .25) stroke(cv, [P(-mw * 1.02, my - sm * 1.2, .01), P(-mw * .4, my + .003, .035), P(0, my + .004, .035), P(mw * .4, my + .003, .035), P(mw * 1.02, my - sm * 1.2, .01)], mixc(C["skin_deep"], C["eye"], .5), 2.6 * sc, .9, soft=.7 * sc, taper=(.2, .8)) put(cv, ell_mask(cv, *P(0, my + lp * 2.6 + .01, .03), u * mw * .5, u * .014, 4 * sc) * m_face, C["skin_sh"], .5) # under the lip if p.get("smile"): for side in (-1, 1): put(cv, ell_mask(cv, *P(side * (mw + .015), my - sm), u * .008, u * .008, 1.2 * sc), C["skin_sh"], .5)
def _hair_ribbon(cv, pts, w0, col, rng, sc): pts = np.asarray(pts, np.float64) n = len(pts) d = np.gradient(pts, axis=0) d /= np.linalg.norm(d, axis=1, keepdims=True) + 1e-9 nrm = np.stack([-d[:, 1], d[:, 0]], 1) t = np.linspace(0, 1, n) w = w0 * np.clip(.55 + 1.2 * t, 0, 1) * (1 - t) ** .6 * (1 + .2 * np.sin(3 * t + rng.random() * 6)) + 1 poly = np.vstack([pts + nrm * w[:, None] / 2, (pts - nrm * w[:, None] / 2)[::-1]]) put(cv, poly_mask(cv, poly, 1.2 * sc), col)
def _clump_poly(hd, c, wpx, rng, u): """a tapered clump (root -> mid -> tip) in front coords projected onto the hair shell""" if "poly" in c: return c["poly"], c["spine"] (x0, y0), (x1, y1), (x2, y2) = c["root"], c["mid"], c["tip"] pts = np.array([hd.PH(x, y, .03) for x, y in [(x0, y0), ((x0 + x1) / 2, (y0 + y1) / 2), (x1, y1), ((x1 + x2) / 2, (y1 + y2) / 2), (x2, y2)]]) P = spline(pts, closed=False, n=6) d = np.gradient(P, axis=0) d /= np.linalg.norm(d, axis=1, keepdims=True) + 1e-9 nrm = np.stack([-d[:, 1], d[:, 0]], 1) t = np.linspace(0, 1, len(P)) w = wpx * np.clip(np.minimum(t / .15, 1), .5, 1) * (1 - t) ** .75 + .8 return np.vstack([P + nrm * w[:, None] / 2, (P - nrm * w[:, None] / 2)[::-1]]), P
def _hair(cv, Lo, Hl, p, C, s, sc, m_face, rng): """P-R4: hair = 2-3 value masses (dark pocket beside the shadow-side cheek, lit-side mass in mid value), clumps with uneven tips, curl strokes on the lit side only, silhouette broken and partly lost; P-R6 the hair overlaps the face""" hd, u = Lo["head"], Lo["u"] W, H = cv.W, cv.H yy, xx = np.mgrid[0:H, 0:W].astype(np.float32) st = Hl["style"] k = lambda a, b: a + (b - a) * rng.random() if Hl["masses"].get("cap") is None: return m_cap = poly_mask(cv, Hl["masses"]["cap"], 1.2 * sc) if Hl.get("cap_discs"): im = Image.new("L", (W, H), 0) dd = ImageDraw.Draw(im) for (x, y, r) in Hl["cap_discs"]: dd.ellipse([x - r, y - r, x + r, y + r], fill=255) md = ndimage.gaussian_filter(np.asarray(im, np.float32) / 255, 1.2 * sc) m_cap = np.maximum(m_cap, md) if "curl_balls" in Hl: for (x, y, r) in Hl["curl_balls"]: m_cap = np.maximum(m_cap, ell_mask(cv, x, y, r, r * k(.8, 1.1), 1.5 * sc)) below = np.clip((yy - (hd.top + u * (hd.hair_y + .03))) / (u * .03), 0, 1) m_cap *= 1 - m_face * below # keep the face open below the hairline if "bun" in Hl: (bx, by), br = Hl["bun"] m_bun = ell_mask(cv, bx, by, br, br * .85, 1.2 * sc) put(cv, m_bun, C["hair_mid"]) put(cv, ell_mask(cv, bx + s * br * .25, by - br * .25, br * .6, br * .45, 6 * sc) * m_bun, C["hair_lit"], .8) put(cv, ell_mask(cv, bx - s * br * .2, by + br * .45, br * .9, br * .35, 4 * sc) * m_bun, C["hair_dk"], .8) for i in range(4): a0 = k(0, 6.28) arc = [(bx + br * .7 * math.cos(a0 + t) * (.6 + .1 * i), by + br * .6 * math.sin(a0 + t) * (.6 + .1 * i)) for t in np.linspace(0, 2.2, 6)] stroke(cv, arc, C["hair_lit"] if i % 2 else C["hair_dk"], 2.2 * sc, .5, soft=.8 * sc) if Hl.get("bun_poly") is not None: m_bun = poly_mask(cv, Hl["bun_poly"], 1.2 * sc) * (1 if Hl.get("bun_front") else (1 - m_face)) bb = Hl["bun_poly"] bx, by = bb[:, 0].mean(), bb[:, 1].mean() br = max(np.ptp(bb[:, 0]), np.ptp(bb[:, 1])) / 2 put(cv, m_bun, C["hair_mid"]) put(cv, ell_mask(cv, bx + s * br * .25, by - br * .25, br * .6, br * .45, 6 * sc) * m_bun, C["hair_lit"], .8) put(cv, ell_mask(cv, bx - s * br * .2, by + br * .45, br * .9, br * .35, 4 * sc) * m_bun, C["hair_dk"], .8) Hl["bun"] = ((bx, by), br) put(cv, m_cap, C["hair_mid"]) # hairline join: no outline, a soft gradation skin -> hair (hair2 H2-8) hl = Hl["hairline"] put(cv, poly_mask(cv, np.vstack([hl, hl[::-1] + [0, 5 * sc]]), 3 * sc, smooth=False) * m_face, mixc(C["hair_mid"], C["skin_half"], .5), .45) m_front = np.zeros((H, W), np.float32) if "fringe" in Hl["masses"]: m_front = np.maximum(m_front, poly_mask(cv, Hl["masses"]["fringe"], 1.5 * sc)) side_ms = [] for sp in Hl["masses"].get("sides", []): msd = poly_mask(cv, sp, 1.5 * sc) side_ms.append(msd) m_front = np.maximum(m_front, msd) # front clumps join the front MASS (painted as one value mass first, P-R4); a side lock may overlap the face only # near its edge (P-R6: hair overlaps the face, it does not cover the cheek), bangs only down to the brows d_in = ndimage.distance_transform_edt(m_face > .5) wav = (np.sin(yy / (.09 * u) + rng.random() * 6) * .5 + .5) * .03 * u # an uneven inner edge, not a cut edge_ok = ndimage.gaussian_filter(np.clip(1 - (d_in - .015 * u - wav) / (.03 * u), 0, 1), 1.5 * sc) brow_px = max(e["c"][1] for e in Lo["eyes"]) - .06 * u above = np.clip((brow_px + .03 * u - yy) / (.03 * u), 0, 1) for c in Hl["clumps"]: poly, spine = _clump_poly(hd, c, c["w"] * u, rng, u) mc = poly_mask(cv, poly, 1.2 * sc) guard = edge_ok if c["kind"] == "side" else (np.maximum(above, edge_ok * (c["kind"] != "bang"))) mc = mc * np.maximum(1 - m_face, guard) c["_m"], c["_spine"] = mc, spine m_front = np.maximum(m_front, mc) if Hl.get("from_kit"): # a painter reads the lock outlines as ONE mass: close the gaps between the layout's lock tips and between the # cap and the side locks (radius ~0.05 H); the broken silhouette comes back later as soft wisps and lost edges # (P-R4, P-R5). Inside the face the layout's own hairline is kept. r = max(2, int(.05 * u)) yy0, xx0 = np.mgrid[-r:r + 1, -r:r + 1] disk = (xx0 ** 2 + yy0 ** 2) <= r * r uni = np.maximum(m_cap, m_front) pad = r + 2 closed = ndimage.binary_closing(np.pad(uni > .5, pad), structure=disk)[pad:-pad, pad:-pad] fill = ndimage.gaussian_filter(closed.astype(np.float32), 1.2 * sc) * (1 - (m_face > .5) * (1 - (uni > .5))) add = np.clip(fill - uni, 0, 1) put(cv, add, C["hair_mid"]) m_cap = np.maximum(m_cap, fill) if m_front.max() > 0: # the front hair casts a soft shadow onto the skin, offset away from the light (A2b/c painted soft) sh = ndimage.shift(m_front, (5 * sc, -s * 3 * sc), order=1) put(cv, ndimage.gaussian_filter(sh, 3 * sc) * m_face * (1 - m_front), C["skin_sh"], .6) put(cv, m_front, C["hair_mid"]) m_all = np.maximum(m_cap, m_front) if "back" in Hl["masses"]: occl = np.clip(Lo["m_neck"] + Lo["m_torso"] + m_face, 0, 1) # the back mass shows only where the body does not hide it m_all = np.maximum(m_all, poly_mask(cv, Hl["masses"]["back"], 1.5 * sc) * (1 - occl)) if "bun" in Hl: m_all = np.maximum(m_all, m_bun) Lo["m_hair"] = m_all if not on("pp_hairvalues"): for c in Hl["clumps"]: poly, _ = _clump_poly(hd, c, c["w"] * u, rng, u) put(cv, poly_mask(cv, poly, 1.2 * sc), C["hair_mid"]) return # value masses: lit-side mass in a lighter mid value, the dark pocket beside the shadow-side cheek lit_c = (hd.cx + s * u * .30, hd.top + u * .22) m_lit = ell_mask(cv, lit_c[0], lit_c[1], u * .42, u * .50, 20 * sc) * m_all put(cv, m_lit, C["hair_lit"], .55) if st in ("long", "bob", "curly"): pocket = [hd.P(-s * x, y) for x, y in [(.28, .38), (.40, .45), (.46, .75), (.42, 1.05), (.30, 1.25), (.24, .95), (.27, .65)]] put(cv, poly_mask(cv, pocket, 7 * sc) * m_all, C["hair_dk"], .9) for msd, sp in zip(side_ms, Hl["masses"].get("sides", [])): if (sp[:, 0].mean() - hd.cx) * s < 0: put(cv, msd, C["hair_dk"], .55) # under-layer at the nape / behind the neck: darkest (hair2 H2-6) put(cv, ell_mask(cv, hd.cx - s * u * .1, hd.top + u * 1.0, u * .5, u * .35, 18 * sc) * m_all * (1 - m_face) * (1 - m_front), C["hair_dk"], .75) # the highlight band curves with the dome on the lit side, broken into lock pieces (hair2 H2-7) band_y = .15 + k(-.03, .03) px = Hl.get("part_x") or 0 for i in range(int(rng.integers(5, 9))): X = px + s * k(.03, .30) a = hd.P(X - .03 * s, band_y - .05 + k(-.02, .02), .1) b = hd.P(X + .01 * s, band_y + .01, .1) c = hd.P(X + .04 * s, band_y + .08 + k(0, .04), .1) stroke(cv, [a, b, c], C["hair_hi"], k(3, 6) * sc, k(.3, .5), soft=1.4 * sc) # clumps inside the mass: a soft value step per clump (alternating, never a hard shard) + a soft seam on the clump's # shadow side + one lit stroke along it on the lit side (hair2 H2-1/H2-6: volumes first, strands last) for c in Hl["clumps"]: mc, spine = c["_m"], c["_spine"] col = {"mid": C["hair_mid"], "lit": C["hair_lit"], "dk": mixc(C["hair_dk"], C["hair_mid"], .4)}[c["val"]] if c["kind"] == "side" and (np.mean(spine[:, 0]) - hd.cx) * s < 0: col = C["hair_dk"] put(cv, ndimage.gaussian_filter(mc, 1.5 * sc), col, .5) wpx = max(2.0, c["w"] * u) if len(spine) >= 2: seam = spine + np.array([-s * wpx * .35, 0]) stroke(cv, seam, C["hair_dk"], max(1.5, wpx * .22), .35, soft=1.5 * sc) if (np.mean(spine[:, 0]) - hd.cx) * s > -u * .05: # lit side only off = np.array([s * wpx * .15, 0]) stroke(cv, spine[:max(2, len(spine) - 1)] + off, C["hair_hi"] if c["val"] != "dk" else C["hair_lit"], max(1.5, wpx * .18), .35, soft=1.2 * sc) m_all = Lo["m_hair"] # lit-side strokes following the flow (part -> outward -> down), curls only on the lit side part = Hl["part"] if Hl["part"] is not None else np.array([hd.cx, hd.top]) side_mask = m_all * np.clip(.5 + s * (xx - hd.cx) / (u * .3), 0, 1) * (1 - m_face * (1 - m_front)) ys, xs = np.nonzero(side_mask > .5) nstr = int(16 + 14 * (st in ("long", "curly"))) for i in range(nstr if len(xs) else 0): j = rng.integers(0, len(xs)) x0, y0 = xs[j], ys[j] if st == "curly": r = u * k(.025, .045) a0 = k(0, 6.28) pts = [(x0 + r * math.cos(a0 + t), y0 + r * math.sin(a0 + t) * .9) for t in np.linspace(0, k(2.5, 4), 6)] else: v = np.array([x0 - part[0], y0 - part[1]], np.float64) v /= np.linalg.norm(v) + 1e-6 g = min(1, (y0 - hd.top) / (u * .6)) dvec = (1 - g) * v + g * np.array([0.08 * np.sign(v[0]), 1]) dvec /= np.linalg.norm(dvec) + 1e-6 L = u * k(.08, .18) pts = [(x0, y0), (x0 + dvec[0] * L * .5 + k(-2, 2) * sc, y0 + dvec[1] * L * .5), (x0 + dvec[0] * L, y0 + dvec[1] * L)] stroke(cv, pts, C["hair_lit"] if i % 3 else C["hair_hi"], k(1.5, 3.0) * sc, k(.25, .45), soft=.9 * sc)
def _beard(cv, Lo, C, s, sc, m_face, rng): hd, u = Lo["head"], Lo["u"] P = hd.P pts = [P(x, y) for x, y in [(-.32, .55), (-.30, .78), (-.18, .97), (0, 1.04), (.18, .97), (.30, .78), (.32, .55), (.22, .72), (hd.mouth_w + .03, hd.mouth_y + .02), (0, hd.mouth_y + .05), (-hd.mouth_w - .03, hd.mouth_y + .02), (-.22, .72)]] m = poly_mask(cv, pts, 4 * sc) put(cv, m, C["hair_mid"], .8) put(cv, m * ell_mask(cv, hd.cx - s * u * .2, hd.top + u * .85, u * .3, u * .3, 20 * sc), C["hair_dk"], .6) must = [P(-hd.mouth_w * 1.1, hd.mouth_y), P(0, hd.nose_y + .015), P(hd.mouth_w * 1.1, hd.mouth_y), P(0, hd.mouth_y - .01)] put(cv, poly_mask(cv, must, 2 * sc), C["hair_dk"], .8)
def _edges(cv, Lo, Hl, p, C, s, sc, m_face, m_torso, rng): """P-R5 edge budget: keep 3-4 hard edges (lit face contour, eyes, the strongest cloth edge); soften the shadow-side contour and the hair-to-ground edge by 3-8 px; lose part of the hair silhouette on the shadow side""" hd, u = Lo["head"], Lo["u"] H, W = cv.H, cv.W yy, xx = np.mgrid[0:H, 0:W].astype(np.float32) shadow_side = np.clip(.5 - s * (xx - hd.cx) / (u * .25), 0, 1) # face contour ring mf = poly_mask(cv, Lo["face"], 4 * sc) ring = np.clip(4 * mf * (1 - mf), 0, 1) soften(cv, ring * shadow_side * (1 - Lo.get("m_hair", 0) * 0), 3.5 * sc) mh = Lo.get("m_hair") if mh is not None: mh2 = ndimage.gaussian_filter(mh, 1.5 * sc) hring = np.clip(6 * mh2 * (1 - mh2), 0, 1) # wisps crossing the silhouette outward, mostly on the lit side (P-R4 broken silhouette; hair2 H2-5) ys, xs = np.nonzero((hring > .6) & (yy < hd.top + u * 1.6)) if len(xs): gy, gx = np.gradient(ndimage.gaussian_filter(mh, 4 * sc)) nw = {"short": 10, "bun": 12, "ponytail": 12}.get(Hl["style"], 34) for i in range(int(nw * (1 + rng.random()))): j = rng.integers(0, len(xs)) x0, y0 = xs[j], ys[j] n = -np.array([gx[y0, x0], gy[y0, x0]]) n /= np.linalg.norm(n) + 1e-6 if n[1] < -.35: # no antennae off the crown: wisps leave the sides continue if (x0 - hd.cx) * s < 0 and rng.random() < .6: continue Lw = u * (.04 + .07 * rng.random()) tdir = np.array([n[1], -n[0]]) if tdir[1] < 0: tdir = -tdir # wisps fall with gravity, leaving the mass at a low angle pts = [(x0 - n[0] * Lw * .3 - tdir[0] * Lw * .3, y0 - n[1] * Lw * .3 - tdir[1] * Lw * .3), (x0, y0), (x0 + n[0] * Lw * .3 + tdir[0] * Lw * .6, y0 + n[1] * Lw * .3 + tdir[1] * Lw * .6)] stroke(cv, pts, C["hair_lit"] if (x0 - hd.cx) * s > 0 else C["hair_mid"], (1.0 + 1.2 * rng.random()) * sc, .4, soft=.6 * sc) soften(cv, hring * (1 - m_face), 2.5 * sc) soften(cv, hring * m_face, 1.5 * sc) # hair over skin: a soft join, not a cut-out (hair2 H2-8) # partly lost on the shadow side: a broad blend into the ground where hair meets ground (3-8 px, P-R5) lost = ndimage.gaussian_filter((hring > .3).astype(np.float32), 3 * sc) soften(cv, np.clip(lost * 1.5, 0, 1) * shadow_side * (1 - m_face) * (yy < hd.top + u * .9), 6 * sc) # torso: keep the lit shoulder/collar edge, soften the shadow-side and lower edges mt = ndimage.gaussian_filter(m_torso, 3 * sc) tring = np.clip(4 * mt * (1 - mt), 0, 1) soften(cv, tring * np.clip(shadow_side + (yy > hd.top + u * 1.7), 0, 1), 5 * sc) # neck bottom and jaw in shadow: lost soften(cv, ell_mask(cv, *hd.P(-s * .2, .95), u * .12, u * .2, 10 * sc) * (1 - m_face * .5), 3 * sc)
def _form_marks(cv, Lo, Hl, p, C, s, sc, m_face, m_neck, m_torso, rng, medium, height): """P-R10: brush marks along the form (isophotes of the painted value plan) carrying the edges, sized per area""" hd, u = Lo["head"], Lo["u"] H, W = cv.H, cv.W f = {"oil": 1.0, "gouache": .7, "watercolor": .0, "realistic": .55}[medium] if f <= 0: return ang, coh = _dirfield(cv.img, 4 * sc) yy, xx = np.mgrid[0:H, 0:W].astype(np.float32) area = (W * H) / (512 * 640) fine = .6 if medium == "realistic" else 1.0 jit = .018 if medium == "realistic" else .025 pick = ndimage.gaussian_filter(cv.img, (1.5, 1.5, 0)) mh = Lo.get("m_hair", np.zeros((H, W), np.float32)) # cloth: broad diagonal-ish marks mt = m_torso * (1 - m_neck) marks(cv, mt, ang, int(260 * f * area), 55 * sc * fine, 10 * sc * fine, rng, .45, jit * .8, .9 * sc, ang_fallback=math.radians(60 * s + 90), coh=coh, pickup=pick, height=height) # hair: along the flow (vertical-ish), many if mh.max() > 0: hang = np.where(coh > .2, ang, np.arctan2(1, (xx - hd.cx) / (u * 1.5))).astype(np.float32) marks(cv, mh * (1 - m_face * .7), hang, int(420 * f * area), 34 * sc * fine, 5 * sc * fine, rng, .55, jit * 1.6, .6 * sc, pickup=pick, height=height) # face + neck: small marks along the planes; few on the features (eyes stay crisp) feat = np.zeros((H, W), np.float32) for e in Lo["eyes"]: feat = np.maximum(feat, ell_mask(cv, e["c"][0], e["c"][1], e["w"] * 1.3, e["h"] * 2.2, 2)) mfn = np.clip(m_face + m_neck, 0, 1) * (1 - feat) * (1 - mh * .8) mface = m_face * (1 - feat) * (1 - mh * .8) marks(cv, mface, ang, int(420 * f * area), 16 * sc * fine, 5.5 * sc * fine, rng, .4, jit * .5, .8 * sc, ang_fallback=np.arctan2(-(yy - hd.top - u * .5), (xx - hd.cx)).astype(np.float32) + np.pi / 2, coh=coh, pickup=pick, height=height) # the neck: long marks down the cylinder, slightly diagonal toward the pit (not rings: rings read as wood grain) mneck = np.clip(m_neck - m_face, 0, 1) * (1 - mh * .8) marks(cv, mneck, np.full((H, W), math.radians(90 - 12 * s), np.float32), int(120 * f * area), 22 * sc * fine, 6 * sc * fine, rng, .35, jit * .5, 1.0 * sc, pickup=pick, height=height)
def _accents(cv, Lo, p, C, s, sc, rng): """P-R9: saturated colour only as small accents away from the face (earring / ribbon / pin), last and crisp""" hd, u = Lo["head"], Lo["u"] if p["sex"] == "f" and rng.random() < .55 and Lo["ears"] and p["hair"] in ("ponytail", "bun", "short", "bob"): e = max(Lo["ears"], key=lambda e: e["w"]) x, y = e["c"][0], e["c"][1] + e["h"] * .55 put(cv, ell_mask(cv, x, y, 3 * sc, 4 * sc, .5 * sc), lch(.80, .06, 85)) put(cv, ell_mask(cv, x - s * sc, y - sc, 1.2 * sc, 1.2 * sc, .3), lch(.93, .02, 90)) elif p["hair"] in ("bun", "ponytail") and rng.random() < .6: if "bun" in p and False: pass x, y = hd.P(-s * .15, -.02, .08) put(cv, ell_mask(cv, x, y, u * .04, u * .02, .8 * sc, rot=.5), C["accent"], .9)
def _medium(cv, medium, rng, sc, height, m_face): """the medium pass. oil: canvas weave + impasto relief from the marks (research16 rule 11: thin darks, thick lights); gouache: matte, flatter, paper grain; watercolour: transparent glazes on white paper with pigment rims (research16 rule 10); realistic: oil, finer marks, smoother transitions, little texture""" from ..paint import paper H, W = cv.H, cv.W if medium in ("oil", "realistic"): weave = paper.canvas_weave(H, W, rng, period=4.0 * max(1, sc)) Lm = lum(cv.img) hgt = height * np.clip((Lm - .3) * 1.6, 0, 1) # impasto in the lights only rel = paper.relief(ndimage.gaussian_filter(hgt, 1.2) * 1.0 + weave * .25, strength=.45 if medium == "oil" else .2) cv.img[:] = np.clip(cv.img * rel[..., None], 0, 1) if medium == "realistic": soften(cv, m_face * .5, 1.2 * sc) elif medium == "gouache": flat = ndimage.median_filter(cv.img, size=(3, 3, 1)) cv.img[:] = flat g = paper.fbm(H, W, 6, rng, 3) cv.img[:] = np.clip(cv.img * (.97 + .06 * g[..., None]), 0, 1) lab = to_lab(cv.img) lab[..., 0] = lab[..., 0] * .96 + .03 # matte: slightly lifted darks cv.img[:] = from_lab(lab) elif medium == "watercolor": _watercolor(cv, rng, sc) cv.img += rng.normal(0, .008, (H, W, 1)).astype(np.float32)
def _watercolor(cv, rng, sc): """re-lay the painted value plan as 3 transparent glazes light -> dark (each multiplicative), wet edges stopped short, pigment rims where a wash met dry paper, granulation in the paper's valleys; the lightest lights are bare paper""" from ..paint import paper H, W = cv.H, cv.W pap = np.array([.97, .955, .92], np.float32) T = np.clip(cv.img / pap, 1e-3, 1) D = -np.log(T) # optical density per channel Dl = D.mean(-1) tooth = paper.cold_press(H, W, rng, max(1.0, sc)) # the wash stops short of the frame: densities fade toward the edges and the bottom (loose vignette to paper) yy, xx = np.mgrid[0:H, 0:W].astype(np.float32) rr = np.hypot((xx - W / 2) / (W * .55), (yy - H * .42) / (H * .62)) fade = np.clip(1.25 - rr + (paper.fbm(H, W, H / 6, rng, 3) - .5) * .5, 0, 1) D = D * fade[..., None] Dl = D.mean(-1) out = np.ones((H, W, 3), np.float32) levels = [.05, .35, .85] prev = np.zeros((H, W), np.float32) for i, th in enumerate(levels): m = np.clip((ndimage.gaussian_filter(Dl, 2 * sc) - th) / .12, 0, 1) m = ndimage.gaussian_filter(m, (2.5 - i * .7) * sc) share = np.clip(D - prev[..., None] * 0, 0, None) dens = D * (1.0 / len(levels)) rim = np.clip(m - ndimage.gaussian_filter(m, 3 * sc), 0, 1) * 1.6 # pigment rim at the wash edge gran = 1 + .35 * (tooth[..., None] - .5) out *= np.exp(-dens * (m + rim)[..., None] * gran) prev = m # whatever density was not laid by the glazes (D above the levels' sum) goes in as the last darks, crisp cv.img[:] = np.clip(pap * out, 0, 1) resid = np.clip(D - (-np.log(np.clip(out, 1e-3, 1))), 0, None) cv.img[:] = np.clip(cv.img * np.exp(-resid), 0, 1) rel = paper.relief(tooth, strength=.25) cv.img[:] = np.clip(cv.img * rel[..., None], 0, 1) vig = paper.deckle(H, W, rng, margin=.03, rough=.04) cv.img[:] = cv.img * vig[..., None] + pap * (1 - vig[..., None])
def render_text(text, seed=0, W=512, H=640, trace=None): """prompt -> painted portrait on the local stand-in layout (uint8 HxWx3); the plot path uses render(fig, ...)""" p = params_from_prompt(text, seed) return draw(p, W, H, seed=seed, trace=trace)
# ============================================================ kit adapter (pydraw/figure layout + hair layout)VARIANT = {"watercolor": "watercolor", "watercolour": "watercolor", "gouache": "gouache", "tempera": "gouache", "realistic": "realistic", "realistic portrait": "realistic"}
def params_from_fig(fig, seed): P_, po, L = fig.person, fig.pose, fig.layout t = (fig.text or "").lower() rng = np.random.default_rng(seed * 7919 + 17) p = {"seed": seed, "text": t, "age": int(round(P_.age)), "sex": "f" if P_.sex < .5 else "m"} p["skin"] = int(np.clip(round(P_.skin * 9), 0, 9)) hs = P_.hair_style if P_.hair_style in ("short", "long", "bob", "ponytail", "curly", "bun", "bald") else ( "short" if P_.hair_style == "buzz" else "short") p["hair"] = hs hc = (P_.hair_color or "").lower() p["hair_col"] = {"gray": "grey", "silver": "grey", "blond": "blonde", "ginger": "red", "brunette": "dark", "platinum": "white", "golden": "blonde", "chestnut": "brown", "copper": "red"}.get(hc, hc) p["light"] = int(L.light_side) p["yaw"], p["torso_yaw"] = float(L.yaw), float(L.torso_yaw) m = re.search(r"\b(%s)\s+(?:\w+\s+)?(dress|shirt|sweater|jumper|coat|blouse|jacket|scarf|suit|top|t-shirt|robe|cardigan|hoodie|vest|uniform)\b" % "|".join(CLOTH_COL), t) p["cloth"] = m.group(1) if m else None p["smile"] = .6 if getattr(P_, "expression", "neutral") == "smile" else 0.0 p["beard"] = bool(P_.beard) p["glasses"] = bool(P_.glasses) var = (fig.variant or "").lower() p["medium"] = VARIANT.get(var) or media_of(t) return p
class KitHead(Head): """my head model with the kit canon's numbers, its projection pinned to the kit layout's 2D landmarks by a least-squares affine fit (so the designed shapes built in front-view head units land on the kit's features)"""
def __init__(self, p, L, size, rng): super().__init__(p, size, size, rng) cn = L.canon self.eye_y, self.brow_y, self.nose_y, self.mouth_y = cn["eye_y"], cn["brow_y"], cn["nose_y"], cn["mouth_y"] self.hair_y = cn["hairline_y"] self.eye_dx, self.eye_w, self.eye_h = cn["eye_spacing"] / 2, cn["eye_w"] / 2, cn["eye_h"] / 2 * .75 self.nose_w, self.mouth_w = cn["nose_w"] / 2, cn["mouth_w"] / 2 cheek, jaw, chin = cn["face_w"] / 2, cn["jaw_w"] / 2, cn["chin_w"] / 2 self.hw_pts = [(0, 0), (.03, .17), (.10, .27), (.20, cheek * .97), (.32, cheek * 1.02), (.47, cheek * 1.02), (.56, cheek), (.66, cheek * .96), (.76, (cheek + jaw) / 2), (.86, jaw), (.93, jaw * .72 + chin * .28), (.975, chin + .03), (1.0, 0.0)] self.neck_w = cn["neck_w"] / 2 self.u = float(L.H) self.yaw = math.radians(L.yaw) self.cx, self.top = float(L.pt["crown"][0]), float(L.pt["crown"][1]) self.A = np.eye(2) self.b = np.zeros(2) mine = [Head.P(self, -self.eye_dx, self.eye_y, -.03), Head.P(self, self.eye_dx, self.eye_y, -.03), Head.P(self, 0, self.nose_y, .07), Head.P(self, -self.mouth_w, self.mouth_y, .01), Head.P(self, self.mouth_w, self.mouth_y, .01), Head.P(self, 0, .985, .02), Head.P(self, 0, self.hair_y, .01)] kit = [L.pt["eye_R"], L.pt["eye_L"], L.pt["nose_base"], L.pt["mouth_R"], L.pt["mouth_L"], L.pt["chin"], L.pt["hairline"]] X = np.hstack([np.asarray(mine, np.float64), np.ones((len(mine), 1))]) Y = np.asarray(kit, np.float64) sol, *_ = np.linalg.lstsq(X, Y, rcond=None) self.A, self.b = sol[:2].T, sol[2] self.fit_err = float(np.abs(X @ sol - Y).max())
def P(self, X, Y, prot=0.0, Z=None): q = Head.P(self, X, Y, prot, Z) return q @ self.A.T + self.b
def layout_from_kit(fig, p, size, rng): L = fig.layout h = KitHead(p, L, size, rng) Lo = {"head": h, "u": float(L.H), "W": size, "H": size, "kit": L, "face": np.asarray(L.face, np.float64), "neck": np.asarray(L.neck, np.float64), "torso": np.asarray(L.torso, np.float64), "chest": np.asarray(L.chest_skin, np.float64), "torso_cx": float(L.pt["pit"][0]), "brows": L.brows} eyes = [] for sname, side in (("L", 1), ("R", -1)): e = L.eyes[sname] eyes.append(dict(side=side, c=np.asarray(e["c"], np.float64), inner=np.asarray(e["inner"], np.float64), outer=np.asarray(e["outer"], np.float64), w=float(e["w"]) / 2, h=float(e["h"]) / 2 * .8, vis=float(e["fs"]), brow=np.asarray(L.brows[sname], np.float64))) Lo["eyes"] = eyes ears = [] for sname, side in (("L", 1), ("R", -1)): e = L.ears[sname] if e["visible"]: ol = np.asarray(e["outline"], np.float64) ears.append(dict(side=side, c=np.asarray(e["c"], np.float64), outline=ol, w=float(np.ptp(ol[:, 0])) / 2, h=float(np.ptp(ol[:, 1])), over=bool(e["over_face"]))) Lo["ears"] = ears return Lo
def hair_from_kit(fig, p, Lo, rng): HL = fig.hair H = {"style": HL.style, "masses": {}, "clumps": [], "wisps": True, "from_kit": True} if HL.cap is None: H["masses"]["cap"] = None return H H["masses"]["cap"] = np.asarray(HL.cap, np.float64) if HL.style not in ("bald", "buzz"): # cover the side/back of the skull in 3/4 (the layout cap is the front only) lt = float(getattr(HL, "lift", .06) or .06) H["cap_discs"] = _shell_discs(Lo["head"], HL.style, p["sex"], min(lt, .08), min(.03, lt * .4)) if HL.back is not None: H["masses"]["back"] = np.asarray(HL.back, np.float64) H["hairline"] = np.asarray(HL.hairline, np.float64) H["part"] = np.asarray(HL.parting["root"], np.float64) if HL.parting else None H["part_x"] = 0.0 H["bangs"] = HL.fringe != "none" behind, vals = [], ["mid", "lit", "mid", "dk", "mid", "lit"] for i, lk in enumerate(HL.locks): poly = np.asarray(lk.poly(), np.float64) if lk.z < -1 or lk.group in ("back", "tail"): behind.append(poly) continue kind = {"bang": "bang", "side": "side", "top": "sweep"}.get(lk.group, "sweep") H["clumps"].append(dict(kind=kind, poly=poly, spine=np.asarray(lk.spine, np.float64), w=max(lk.w0, 2) / Lo["u"], val=vals[i % len(vals)])) H["behind"] = behind if HL.bun is not None: H["bun_poly"] = np.asarray(HL.bun["outline"], np.float64) H["bun_front"] = HL.bun.get("z", -1) > -1 return H
def render(fig, size, seed, trace): """kit contract: the painted portrait of fig (layout + hair layout from the kit lane) -> size x size uint8""" p = params_from_fig(fig, seed) rng = np.random.default_rng(seed * 104729 + 3) Lo = layout_from_kit(fig, p, size, rng) Hl = hair_from_kit(fig, p, Lo, rng) base = {k: np.asarray(v, np.float32) for k, v in fig.plan.materials.items()} return draw(p, size, size, seed=seed, layout=Lo, hair=Hl, trace=trace, base=base)
def stats(img, face_mask): """P-R1 self-check: share of the picture's top-3% values that fall in the face (< 5% wanted)""" Lm = lum(img.astype(np.float32) / 255 if img.dtype == np.uint8 else img) thr = np.quantile(Lm, .97) top = Lm >= thr return float((top & (face_mask > .5)).sum() / max(1, top.sum()))1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909"""Pixel-art portraits drawn the way a pixel artist builds one (wave 18, pixel lane; knob fig2d_px).
Method from the wave-17 master copy (docs/research18/copy_rules.md X1-X11, C1-C9), never its picture: no vertex, paletteentry or glyph pattern of out/copy17/pixel/code/copyB.py is reused; only its primitives (a palette-key grid, polygonswithout anti-aliasing, pixel-perfect polylines, neighbour rules) and its ORDER: palette + value plan -> silhouette -> flat masses (z order) -> face ramp -> hair locks, seams, highlight clusters -> feature glyphs sized by face width -> material lines (hair over skin, ramp steps) -> outline -> cleanup.
Everything is computed from the person (age, sex, skin, hair style and colour, cloth, yaw, seed) and the portrait size,so one code path draws any person at 32-96 px. Numbers carry the rule or the research doc they come from.
Entry points portrait(person, n) -> (n, n, 3) uint8 RGB pixel portrait (head + neck + shoulders) person_from_text(text, seed) -> a person dict from prompt words (stand-in until the kit lane's params land) head_layout(person, n) -> the landmark layout (stand-in for pydraw.figure.layout; same role, own names)"""import colorsysimport mathimport osimport zlib
import numpy as np
def knob(name, default="1"): """PYDRAW_EXP name=0 turns a rule off""" ev = dict(kv.split("=") for kv in os.environ.get("PYDRAW_EXP", "").split(",") if "=" in kv) return ev.get(name, default) != "0"
# ------------------------------------------------------------------------------------------------------------------# palette keys (X1): every pixel holds a KEY; colours are assigned once from the person's rampsBG, K, W, S0, S1, S2, H0, H1, H2, C0, C1, E1 = range(12)NAMES = "BG K W S0 S1 S2 H0 H1 H2 C0 C1 E1".split()SKIN_KEYS = (S0, S1, S2)HAIR_KEYS = (H0, H1, H2)
# base (mid) skin colours, light to deep: our own picks spanning pydraw's existing ranges (concepts/people.SKIN_TONES,# anatomy/render.SKIN_TONES); the ramp around each base is generated by X2, never hand-typed per toneSKIN = {"pale": (240, 196, 168), "light": (232, 172, 132), "medium": (206, 142, 100), "olive": (190, 136, 92), "tan": (172, 112, 74), "brown": (138, 86, 56), "deep": (98, 60, 42)}# hair base colours (mid value of the lit lock); highlight / shadow steps are generated (X2)HAIR = {"black": (58, 52, 70), "brown": (110, 66, 40), "dark brown": (78, 48, 34), "light brown": (156, 106, 62), "blonde": (222, 176, 66), "red": (186, 82, 40), "auburn": (140, 56, 36), "gray": (150, 150, 158), "white": (214, 212, 214), "pink": (222, 110, 150), "blue": (70, 104, 196), "purple": (122, 76, 168), "green": (70, 150, 90)}CLOTH = {"red": (196, 52, 48), "blue": (58, 92, 176), "green": (62, 132, 72), "yellow": (226, 186, 54), "white": (238, 236, 228), "black": (52, 50, 60), "gray": (128, 128, 136), "purple": (118, 70, 150), "orange": (220, 120, 48), "pink": (222, 124, 160), "brown": (118, 78, 48), "teal": (40, 130, 130), "navy": (40, 52, 104)}NEAR_BLACK = (16, 16, 28) # X1: one COOL near-black for every outline and the deepest shadowNEAR_WHITE = (250, 248, 240) # X1: one near-white for every highlight
def _hsv(c): return colorsys.rgb_to_hsv(*[v / 255.0 for v in c])
def _rgb(h, s, v): return tuple(int(round(255 * max(0.0, min(1.0, t)))) for t in colorsys.hsv_to_rgb(h % 1.0, s, v))
def _toward(h, target, deg): """rotate hue h (0..1) toward target hue by deg degrees along the short way (X2)""" d = ((target - h + 0.5) % 1.0) - 0.5 step = math.copysign(min(abs(d), deg / 360.0), d) return (h + step) % 1.0
def ramp_step(c, k, shift=12.0, dv=0.72): """one ramp step from colour c: k=+1 lighter (hue toward yellow, value up, saturation down a little), k=-1 darker (hue toward red, value down, saturation up). X2: +8..+18 deg per step (slynyrd PB1 goes to +20).""" h, s, v = _hsv(c) if k > 0: h = _toward(h, 60 / 360.0, shift) v = v + (1 - v) * 0.45 + 0.04 s = s * 0.82 else: h = _toward(h, 0.0, shift) v = v * dv s = min(1.0, s * 1.18 + 0.06) return _rgb(h, s, v)
def _lum(c): r, g, b = [v / 255.0 for v in c] return 0.2126 * r + 0.7152 * g + 0.0722 * b
def _lab(c): def f(t): t = t / 255.0 return t / 12.92 if t <= 0.04045 else ((t + 0.055) / 1.055) ** 2.4 r, g, b = [f(v) for v in c] X = (0.4124 * r + 0.3576 * g + 0.1805 * b) / 0.9505 Y = 0.2126 * r + 0.7152 * g + 0.0722 * b Z = (0.0193 * r + 0.1192 * g + 0.9505 * b) / 1.089 g3 = lambda t: t ** (1 / 3) if t > 0.008856 else 7.787 * t + 16 / 116 return 116 * g3(Y) - 16, 500 * (g3(X) - g3(Y)), 200 * (g3(Y) - g3(Z))
def _de(a, b): return math.dist(_lab(a), _lab(b))
def build_palette(P): """X1-X3: the shared palette, decided before anything is drawn. Ramps share their ends: the cool near-black is the bottom of hair, cloth and outline; the near-white tops the highlights. Returns {key: rgb}.""" pal = {K: NEAR_BLACK, W: NEAR_WHITE} sk = P["skin_rgb"] # the lit core is most of the face, so it carries the prompted tone; the rims and shadows step down from it # (critic10 r1: "dark brown skin reads medium" when the base was the mid and the core a lighter step) pal[S2] = sk pal[S1] = ramp_step(sk, -1, 8, dv=0.84) pal[S0] = ramp_step(pal[S1], -1, 8, dv=0.80) hc = P["hair_rgb"] hv = _hsv(hc)[2] pal[H1] = hc pal[H0] = ramp_step(hc, -1, 14) pal[H2] = ramp_step(hc, +1, 16) if hv < 0.32: # H2-20 (GBA tutorial): very dark hair = 2 shades + the outline as the third; its highlight is a cool lift pal[H0] = NEAR_BLACK h, s, v = _hsv(hc) pal[H2] = _rgb(_toward(h, 0.62, 30), s * 0.6, min(1, v * 2.0 + 0.1)) if P["hair_name"] in ("blonde", "white", "gray"): pal[H2] = NEAR_WHITE # X1/X4: light hair borrows the shared near-white for its highlight clusters # X3: lit skin must stay darker than the hair highlight if _lum(pal[S2]) > _lum(pal[H2]) and pal[H2] != NEAR_WHITE: pal[H2] = ramp_step(pal[H2], +1, 6) cc = P["cloth_rgb"] pal[C1] = cc pal[C0] = ramp_step(cc, -1, 14) if _de(cc, NEAR_WHITE) < 8: pal[C1] = NEAR_WHITE pal[E1] = P["eye_rgb"] pal[BG] = P["bg_rgb"] return pal
# ------------------------------------------------------------------------------------------------------------------# person parameters (stand-in for the kit lane's params; names kept plain so the adapter is one function)HAIR_STYLES = ("short", "long", "bob", "ponytail", "curly", "bun", "bald")
def person_from_text(text, seed=0): """prompt words -> person dict. Unsaid choices come from the seed (rule: the seed varies what the prompt leaves open).""" t = " " + text.lower().replace(",", " ").replace("-", " ") + " " rng = np.random.default_rng(zlib.crc32(("%d|" % seed + text).encode())) has = lambda *ws: any((" %s " % w) in t for w in ws) sex = None if has("woman", "girl", "lady", "she", "grandmother", "mother", "queen", "princess", "her", "female", "actress"): sex = "f" if has("man", "boy", "gentleman", "he", "grandfather", "father", "king", "his", "male", "guy"): sex = "m" if sex is None: sex = "f" if rng.random() < 0.5 else "m" age = 30.0 if has("baby", "toddler"): age = 3 elif has("child", "kid", "boy", "girl", "little"): age = 8 elif has("teen", "teenager", "teenage"): age = 15 elif has("young"): age = 22 elif has("middle aged", "middle"): age = 48 elif has("old", "elderly", "grandmother", "grandfather", "aged", "senior"): age = 74 style = None for w, s in (("ponytail", "ponytail"), ("pony tail", "ponytail"), ("bun", "bun"), ("curly", "curly"), ("afro", "curly"), ("curls", "curly"), ("wavy", "curly"), ("bob", "bob"), ("shoulder length", "bob"), ("long", "long"), ("short", "short"), ("buzz", "short"), ("crew cut", "short"), ("bald", "bald")): if has(w): style = s break if style is None: opts = ("short", "short", "curly", "bob") if sex == "m" else ("long", "bob", "ponytail", "bun", "curly", "short") style = opts[int(rng.integers(len(opts)))] if sex == "m" and age > 60 and rng.random() < 0.4: style = "bald" hair = None for w, c in (("blonde", "blonde"), ("blond", "blonde"), ("golden", "blonde"), ("redhead", "red"), ("ginger", "red"), ("auburn", "auburn"), ("red hair", "red"), ("light brown", "light brown"), ("dark brown", "dark brown"), ("brunette", "brown"), ("brown hair", "brown"), ("black hair", "black"), ("dark hair", "black"), ("silver", "gray"), ("grey", "gray"), ("gray", "gray"), ("white hair", "white"), ("pink hair", "pink"), ("blue hair", "blue"), ("purple hair", "purple"), ("green hair", "green")): if (" " + c + " ") and has(w): hair = c break if hair is None: if age > 62: hair = "white" if rng.random() < 0.4 else "gray" else: hair = ("black", "brown", "dark brown", "light brown", "blonde", "red", "black", "brown")[int(rng.integers(8))] skin = None for w, s in (("pale", "pale"), ("fair", "pale"), ("light skin", "light"), ("olive", "olive"), ("tan", "tan"), ("medium skin", "medium"), ("brown skin", "brown"), ("dark skin", "deep"), ("deep", "deep"), ("dark skinned", "deep"), ("black woman", "deep"), ("black man", "deep")): if has(w): skin = s break if skin is None: skin = ("pale", "light", "medium", "olive", "tan", "brown", "deep")[int(rng.integers(7))] yaw = 0.0 if has("three quarter", "3/4", "quarter view", "turned", "looking away", "side glance"): yaw = 32.0 * (1 if rng.random() < 0.5 else -1) elif not has("front", "frontal", "facing"): yaw = float(rng.choice([0.0, 0.0, 30.0, -30.0])) if has("left"): yaw = -abs(yaw) if yaw else yaw cloth = None for w in CLOTH: if has(w + " sweater", w + " shirt", w + " dress", w + " jacket", w + " coat", w + " top", w + " hoodie", w + " blouse", w + " t shirt", "in " + w): cloth = w break cloth_explicit = cloth is not None if cloth is None: cloth = list(CLOTH)[int(rng.integers(len(CLOTH)))] eye = ("brown", "dark", "blue", "green", "hazel")[int(rng.integers(5))] for w in ("blue", "green", "brown", "hazel", "gray"): if has(w + " eyes", w + " eyed"): eye = w beard = has("beard", "bearded") and sex == "m" return dict(sex=sex, age=float(age), hair_style=style, hair_name=hair, skin_name=skin, yaw=float(yaw), cloth_name=cloth, cloth_explicit=cloth_explicit, eye_name=eye, freckles=has("freckles", "freckled"), beard=beard, smile=has("smiling", "smile", "smiles", "happy"), seed=int(seed), text=text)
EYE_RGB = {"brown": (104, 62, 36), "dark": (62, 40, 30), "blue": (66, 112, 176), "green": (70, 128, 78), "hazel": (130, 100, 50), "gray": (110, 120, 130)}
def _complete(P): """fill rgb fields from names (any explicit rgb wins) and the seeded open choices""" P = dict(P) rng = np.random.default_rng(zlib.crc32(("bg|%d|%s" % (P.get("seed", 0), P.get("text", ""))).encode())) P.setdefault("skin_rgb", SKIN.get(P.get("skin_name", "light"), SKIN["light"])) P.setdefault("hair_rgb", HAIR.get(P.get("hair_name", "brown"), HAIR["brown"])) if not P.get("cloth_explicit", True) and "cloth_rgb" not in P: # C1 masses must separate: an unprompted garment never takes the hair's (or the skin's) value hv = _lum(P["hair_rgb"]) sv = _lum(P["skin_rgb"]) names = list(CLOTH) start = names.index(P.get("cloth_name", "blue")) if P.get("cloth_name") in names else 0 for k in range(len(names)): c = names[(start + k) % len(names)] cv = _lum(CLOTH[c]) if abs(cv - hv) >= 0.16 and _de(CLOTH[c], P["skin_rgb"]) > 25 and abs(cv - sv) >= 0.08: P["cloth_name"] = c break P.setdefault("cloth_rgb", CLOTH.get(P.get("cloth_name", "blue"), CLOTH["blue"])) P.setdefault("eye_rgb", EYE_RGB.get(P.get("eye_name", "brown"), EYE_RGB["brown"])) if "bg_rgb" not in P: # background: a desaturated mid value whose hue sits away from both hair and cloth (figure-ground, C1: the face # is a middle value, the darkest dark is the hair; the ground is a calm middle that is neither) hh = _hsv(P["hair_rgb"])[0] ch = _hsv(P["cloth_rgb"])[0] best, bd = None, -1 for k in range(12): h = (k / 12.0 + rng.uniform(0, 1 / 24.0)) % 1 d = min(abs(((h - hh + .5) % 1) - .5), abs(((h - ch + .5) % 1) - .5)) if d > bd + 0.02 * rng.random(): best, bd = h, d P["bg_rgb"] = _rgb(best, 0.30, 0.62) P.setdefault("masc", 1.0 if P.get("sex") == "m" else 0.0) return P
# ------------------------------------------------------------------------------------------------------------------# raster primitives (copyB's kinds of primitive, rewritten for any size: no AA anywhere, X10)def poly_mask(pts, n): """polygon fill by pixel-centre sampling, even-odd, no anti-aliasing""" pts = np.asarray(pts, np.float32) yy, xx = np.mgrid[0:n, 0:n].astype(np.float32) + 0.5 inside = np.zeros((n, n), bool) x0, y0 = pts[:, 0], pts[:, 1] x1, y1 = np.roll(x0, -1), np.roll(y0, -1) for a, b, c, d in zip(x0, y0, x1, y1): if b == d: continue cond = (b > yy) != (d > yy) xi = a + (yy - b) * (c - a) / (d - b) inside ^= cond & (xx < xi) return inside
def ellipse_mask(cx, cy, rx, ry, n): yy, xx = np.mgrid[0:n, 0:n].astype(np.float32) + 0.5 return ((xx - cx) / max(rx, 1e-3)) ** 2 + ((yy - cy) / max(ry, 1e-3)) ** 2 <= 1.0
def line_px(pts): """pixel-perfect polyline (X10): Bresenham per segment, then drop every L-corner pixel whose neighbours already touch diagonally (no doubled corners on curves)""" out = [] pts = [(int(round(x)), int(round(y))) for x, y in pts] for (x0, y0), (x1, y1) in zip(pts[:-1], pts[1:]): dx, dy = abs(x1 - x0), -abs(y1 - y0) sx, sy = (1 if x1 > x0 else -1), (1 if y1 > y0 else -1) e = dx + dy x, y = x0, y0 while True: if not out or out[-1] != (x, y): out.append((x, y)) if (x, y) == (x1, y1): break e2 = 2 * e if e2 >= dy: e += dy x += sx if e2 <= dx: e += dx y += sy if len(pts) == 1: out = [pts[0]] if len(out) < 3: return out keep = [out[0]] for i in range(1, len(out) - 1): p, q, r = keep[-1], out[i], out[i + 1] if (p[0] == q[0] or p[1] == q[1]) and (q[0] == r[0] or q[1] == r[1]) and p[0] != r[0] and p[1] != r[1]: continue keep.append(q) keep.append(out[-1]) return keep
def shift(m, dx, dy): """out[y, x] = m[y + dy, x + dx] (False outside)""" n0, n1 = m.shape out = np.zeros_like(m) ys, xs = slice(max(dy, 0), n0 + min(dy, 0)), slice(max(dx, 0), n1 + min(dx, 0)) yd, xd = slice(max(-dy, 0), n0 + min(-dy, 0)), slice(max(-dx, 0), n1 + min(-dx, 0)) out[yd, xd] = m[ys, xs] return out
def touch4(m): return shift(m, 1, 0) | shift(m, -1, 0) | shift(m, 0, 1) | shift(m, 0, -1)
def ring(m): """the 1 px inner border of a mask""" return m & ~(shift(m, 1, 0) & shift(m, -1, 0) & shift(m, 0, 1) & shift(m, 0, -1))
class Grid: """a palette-key grid: the drawing is decisions about keys; colours are applied once at the end"""
def __init__(self, n): self.n = n self.a = np.full((n, n), BG, np.uint8)
def fill(self, m, k, only=None): if only is not None: m = m & np.isin(self.a, only) self.a[m] = k
def px(self, pts, k, only=None, within=None): for x, y in pts: x, y = int(x), int(y) if 0 <= x < self.n and 0 <= y < self.n: if only is not None and self.a[y, x] not in only: continue if within is not None and not within[y, x]: continue self.a[y, x] = k
def line(self, pts, k, only=None, within=None): self.px(line_px(pts), k, only, within)
def stamp(self, x0, y0, rows, only=None, within=None): """a glyph: list of lists of keys (None = leave)""" for j, r in enumerate(rows): for i, k in enumerate(r): if k is not None: self.px([(x0 + i, y0 + j)], k, only, within)
def mask(self, *keys): return np.isin(self.a, keys)
def rgb(self, pal): out = np.zeros((self.n, self.n, 3), np.uint8) for k, c in pal.items(): out[self.a == k] = c return out
# ------------------------------------------------------------------------------------------------------------------# LAYOUT (stand-in for pydraw.figure.layout): a few 3D anchors on a head of height 1 (crown 0, chin 1), turned by yaw# and projected orthographically; everything else is 2D. Canon numbers (units of head height H):# head width 0.74 (Loomis / research17 head2_structure: width:height ~0.72-0.78), eye line 0.50 adult -> 0.58 child# (research17 faces rule 14: lerp(0.62, 0.5, age/14)), nose bottom halfway eyes-chin, mouth 0.4 of nose-chin (research16 s2),# neck width 0.36-0.46 H (research16 s2: 1/2-2/3 head width), X9: head with hair ~70% of the frame, shoulders start at# the jaw line.def _rot(p, yaw): c, s = math.cos(yaw), math.sin(yaw) x, y, z = p return (x * c + z * s, y, -x * s + z * c)
def head_layout(P, n): P = _complete(P) rng = np.random.default_rng(zlib.crc32(("lay|%d|%s" % (P.get("seed", 0), P.get("text", ""))).encode())) age = P.get("age", 30.0) masc = P["masc"] child = max(0.0, min(1.0, (16.0 - age) / 12.0)) # 1 at 4 years, 0 from 16 old = max(0.0, min(1.0, (age - 50.0) / 25.0)) yaw = math.radians(P.get("yaw", 0.0)) # frame: head height H, crown and centre. X9: head with hair ~70% of the frame (child heads a little bigger) H = n * (0.585 + 0.03 * child) top = n * 0.125 face_dir = 1 if yaw > 0 else (-1 if yaw < 0 else 0) # where the face looks (+1 = viewer's right; _rot: yaw>0 moves the face to +x) cx = n * 0.5 - face_dir * n * 0.035 # lead room: the head sits back from where the face looks jit = lambda a: float(rng.uniform(-a, a)) rx = 0.37 + 0.02 * child + jit(0.012) eye_v = 0.50 + 0.07 * child + jit(0.01) nose_v = eye_v + (1 - eye_v) * (0.47 - 0.05 * child) mouth_v = nose_v + (1 - nose_v) * 0.42 jaw_u = 0.255 + 0.045 * masc - 0.02 * child + jit(0.012) chin_u = 0.07 + 0.03 * masc - 0.02 * child eye_u = 0.175 + 0.015 * child + jit(0.008)
def proj(p): x, y, z = _rot(p, yaw) return (cx + x * H, top + y * H, z)
# head silhouette: the skull ellipsoid outline plus the jaw anchors, convex hull (far contour straight in 3/4, X9) pts3 = [] for a in np.linspace(0, 2 * math.pi, 48, endpoint=False): for zz in (-0.42, -0.2, 0.0, 0.2, 0.38): r = math.sqrt(max(0.0, 1 - (zz / 0.46) ** 2)) pts3.append((rx * r * math.cos(a), 0.42 + 0.42 * math.sin(a) * (0.95 + 0.05 * r), zz - 0.04)) jaw3 = [(s * jaw_u, 0.80, 0.0) for s in (-1, 1)] + [(s * 0.335, 0.60, 0.17) for s in (-1, 1)] + \ [(s * 0.335, 0.42, 0.20) for s in (-1, 1)] + \ [(s * chin_u, 0.985, 0.24) for s in (-1, 1)] + [(0.0, 1.0, 0.24)] pp = [proj(p)[:2] for p in pts3 + jaw3] hull = _hull(pp) # the face front: what the jaw + cheeks + forehead cover (used for the face plate / hairline) feat = {} for s in (-1, 1): e = proj((s * eye_u, eye_v, 0.30)) nrm = _rot((s * 0.45, 0.0, 1.0), yaw) fore = max(0.25, nrm[2] / math.hypot(0.45, 1.0)) # foreshortening of this eye feat["eye%+d" % s] = dict(x=e[0], y=e[1], z=e[2], fore=fore) ear = proj((s * 0.375, (eye_v + nose_v) / 2, -0.06)) en = _rot((s * 1.0, 0, -0.15), yaw) feat["ear%+d" % s] = dict(x=ear[0], y=ear[1], vis=en[2] > -0.35, side=s, facing=en[2]) nt = proj((0.0, nose_v, 0.43)) nb = proj((0.0, eye_v + 0.04, 0.34)) mo = proj((0.0, mouth_v, 0.31)) feat["nose"] = dict(x=nt[0], y=nt[1], top=(nb[0], nb[1])) feat["mouth"] = dict(x=mo[0], y=mo[1], fore=0.55 + 0.45 * math.cos(yaw)) feat["chin"] = proj((0.0, 1.0, 0.24))[:2] # neck: a cylinder behind the jaw, under the ear (research17 head_neck_hair: the neck rises from behind the jaw) nw = (0.20 + 0.035 * masc - 0.03 * child) * H ncx = proj((0.0, 0.9, -0.10))[0] neck = [(ncx - nw, top + 0.62 * H), (ncx + nw, top + 0.62 * H), (ncx + nw * 1.08, top + 1.13 * H), (ncx - nw * 1.08, top + 1.13 * H)] # shoulders (X9: they start at the jaw line); the body turns half as far as the head byaw = yaw * 0.5 sw = (0.92 + 0.16 * masc - 0.22 * child + jit(0.03)) * H sw_l, sw_r = sw * math.cos(byaw), sw * math.cos(byaw) sy = top + (1.10 - 0.04 * child) * H trap_y = top + 0.93 * H bcx = cx + math.sin(byaw) * 0.1 * H * 0 sh = [(ncx - nw * 1.0, trap_y), (ncx - nw * 2.2, sy - 0.04 * H), (bcx - sw_l + 0.10 * H, sy), (bcx - sw_l, sy + 0.14 * H), (bcx - sw_l - 0.04 * H, n + 2), (bcx + sw_r + 0.04 * H, n + 2), (bcx + sw_r, sy + 0.14 * H), (bcx + sw_r - 0.10 * H, sy), (ncx + nw * 2.2, sy - 0.04 * H), (ncx + nw * 1.0, trap_y)] # hairline anchors (3D, on the forehead) and the parting point on top part_side = 1 if rng.random() < 0.5 else -1 return dict(P=P, n=n, H=H, top=top, cx=cx, yaw=yaw, face_dir=face_dir, hull=hull, feat=feat, neck=neck, neck_w=nw, neck_cx=ncx, shoulders=sh, shoulder_y=sy, eye_v=eye_v, nose_v=nose_v, mouth_v=mouth_v, rx=rx, child=child, old=old, masc=masc, part_side=part_side, proj=proj, rng=rng)
def _hull(pts): pts = sorted(set((round(x, 3), round(y, 3)) for x, y in pts)) if len(pts) < 3: return pts
def cross(o, a, b): return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]) lo, up = [], [] for p in pts: while len(lo) >= 2 and cross(lo[-2], lo[-1], p) <= 0: lo.pop() lo.append(p) for p in reversed(pts): while len(up) >= 2 and cross(up[-2], up[-1], p) <= 0: up.pop() up.append(p) return lo[:-1] + up[:-1]
# ------------------------------------------------------------------------------------------------------------------# HAIR LAYOUT (stand-in for pydraw.figure.hairlayout): per style, the parting, cap lift, hairline (fringe), side# curtains, back mass, tie / bun, tip length and tip count, as numbers (research17 units/hair2.md section 10 recipes)HAIR_RECIPE = { # lift top/side, hairline v (centre, swept side), side end v, tips v, n locks, bangs, back, curl "short": dict(lift=(0.07, 0.025), hl=(0.24, 0.31), side=0.47, tips=None, locks=2, bangs=False, back=False), "long": dict(lift=(0.06, 0.04), hl=(0.26, 0.40), side=None, tips=1.38, locks=3, bangs=False, back=True), "bob": dict(lift=(0.07, 0.05), hl=(0.38, 0.40), side=None, tips=0.98, locks=3, bangs=True, back=True), "ponytail": dict(lift=(0.04, 0.02), hl=(0.24, 0.30), side=0.50, tips=None, locks=2, bangs=False, back=False), "curly": dict(lift=(0.14, 0.10), hl=(0.30, 0.34), side=None, tips=0.86, locks=0, bangs=True, back=True), "bun": dict(lift=(0.04, 0.02), hl=(0.24, 0.29), side=0.50, tips=None, locks=2, bangs=False, back=False), "bald": dict(lift=(0.0, 0.01), hl=None, side=0.62, tips=None, locks=0, bangs=False, back=False),}
def _zig(x, period, amp, phase): """a downward-pointing tip profile (V notches between lock tips, C5 / H2-21)""" t = ((x - phase) / max(period, 1e-3)) % 1.0 return amp * (1 - abs(2 * t - 1))
def hair_masks(L): """-> dict(front=mask, back=mask, part=(x, y), bangs_mask, tips_y, style) in pixel space""" P, n, H, top = L["P"], L["n"], L["H"], L["top"] st = P.get("hair_style", "short") R = dict(HAIR_RECIPE.get(st, HAIR_RECIPE["short"])) rng = L["rng"] if st == "short" and L["masc"] < 0.5: R.update(side=0.55, hl=(0.26, 0.40)) # a woman's short cut: side-swept fringe, longer sides if L["old"] > 0.4 and L["masc"] > 0.5 and st == "short": R.update(hl=(0.18, 0.22), lift=(0.03, 0.02)) # research17 faces rule 15: the hairline recedes with age yy, xx = np.mgrid[0:n, 0:n].astype(np.float32) + 0.5 head = poly_mask(L["hull"], n) proj = L["proj"] lt, ls = R["lift"] # skull outline expanded by the lift (H2-3 helmet): projected ellipse of the skull grown by the lift yaw = L["yaw"] sk_c = proj((0.0, 0.42, -0.04)) a = (math.sqrt((L["rx"] * math.cos(yaw)) ** 2 + (0.46 * math.sin(yaw)) ** 2) + ls) * H b = (0.42 + lt) * H cap_e = ((xx - sk_c[0]) / a) ** 2 + ((yy - (sk_c[1] - (lt - ls) * H * 0.5)) / (b - (lt - ls) * H * 0.5)) ** 2 <= 1.0 cap_e |= ((xx - sk_c[0]) / a) ** 2 + ((yy - sk_c[1]) / (0.42 * H + ls * H)) ** 2 <= 1.0 # hairline across the forehead (3D points projected); swept side lower (the fringe lock sweeps across, X4) ps = L["part_side"] if R["hl"] is None: front = np.zeros((n, n), bool) if L["old"] > 0.3: # bald: a horseshoe fringe at ear height at the back and sides # the horseshoe: what is left at the sides and back of the skull from the temples to the nape grow = ellipse_mask(sk_c[0], sk_c[1], a + 0.015 * H, 0.42 * H + 0.015 * H, n) # its top edge rises toward the back of the head (a band that thins to the temple, not a block) bd = -L["face_dir"] if L["face_dir"] != 0 else np.sign(xx - sk_c[0]) backness = np.clip((xx - sk_c[0]) * bd / (a + 1e-3), -1, 1) ytop = top + (0.44 - 0.10 * backness) * H front = grow & (yy > ytop) & (yy < top + 0.62 * H) & ~_face_front(L, xx, yy) # it lies BEHIND the ear (toward the back of the head) and above it, never in front of it for sd in (-1, 1): e = L["feat"]["ear%+d" % sd] back_dir = -L["face_dir"] if L["face_dir"] != 0 else sd infront = ((xx - e["x"]) * back_dir < -0.02 * H) & (yy > e["y"] - 0.16 * H) & \ (np.abs(xx - e["x"]) < 0.2 * H) front &= ~infront return dict(front=front, back=np.zeros((n, n), bool), part=(sk_c[0], top), style=st, R=R, cap=front) hl_c, hl_s = R["hl"] us = np.linspace(-0.40, 0.40, 17) hpts = [] for u in us: sweep = (u * -ps + 0.40) / 0.80 # 0 at the parting side, 1 at the swept side v = hl_c + (hl_s - hl_c) * sweep v += 0.10 * max(0.0, abs(u) - 0.28) / 0.12 # temples drop toward the sideburn if R["bangs"]: v = hl_c + 0.03 * (abs(u) / 0.4) ** 2 zf = 0.40 * math.sqrt(max(0.0, 1 - (u / 0.42) ** 2)) - 0.02 p = proj((u, v, zf)) if p[2] > -0.05: hpts.append(p[:2]) hpts.sort() hx = np.array([p[0] for p in hpts]) hy = np.array([p[1] for p in hpts]) side_v = R["side"] if R["side"] is not None else 0.55 side_y = top + side_v * H hairline_y = np.interp(xx[0], hx, hy, left=side_y, right=side_y) # bangs: lock tips along the fringe (V notches) if R["bangs"]: per = max(2.0, 0.11 * H) hairline_y = hairline_y + np.array([_zig(x, per, 0.045 * H, rng.uniform(0, per)) for x in xx[0]]) elif st in ("long", "short"): # a swept fringe ends in 1-2 points over the far temple hairline_y = hairline_y + np.array([_zig(x, 0.16 * H, 0.03 * H, 0.0) for x in xx[0]]) cap = cap_e & (yy < hairline_y[None, :]) # in turned views the far side of the skull outside the face is hair down to the side line front = cap.copy() back = np.zeros((n, n), bool) face_front = _face_front(L, xx, yy) # sides below the hairline but outside the face front: hair down to side_y (sideburn / temple) sides = cap_e & ~face_front & (yy < side_y) # turned views: on the FAR side the hair hangs behind the cheek; only what passes the head contour shows (and the # far temple above the brow) fd = L["face_dir"] far = ((xx - L["cx"]) * fd > 0) if fd != 0 else np.zeros((n, n), bool) eye_y = top + L["eye_v"] * H behind_far = far & head & (yy > eye_y - 0.10 * H) sides &= ~behind_far front |= sides tips = R["tips"] if tips is not None: tip_y = top + tips * H per = max(2.0, (0.13 if st != "curly" else 0.10) * H) ph = rng.uniform(0, per) zig = np.array([_zig(x, per, 0.07 * H, ph) for x in xx[0]]) # curtains: from the temple down beside the face / neck to the tips, flaring out over the shoulders fl = 0.12 if st == "long" else (0.08 if st == "bob" else 0.10) out_a = a + fl * H sk_x = sk_c[0] width_row = np.where(yy < sk_c[1], a * np.sqrt(np.clip(1 - ((yy - sk_c[1]) / (0.42 * H + ls * H)) ** 2, 0, 1)), a + (yy - sk_c[1]) / (tip_y - sk_c[1] + 1e-3) * (out_a - a)) if st == "bob": # bell: tips curve inward under the jaw (hair2 recipe) inw = np.clip((yy - (tip_y - 0.18 * H)) / (0.18 * H), 0, 1) width_row = width_row - inw * 0.10 * H curtain = (np.abs(xx - sk_x) <= width_row) & (yy >= top) & (yy < tip_y + zig[None, :]) curtain &= ~face_front & ~behind_far neck_zone = (np.abs(xx - L["neck_cx"]) <= L["neck_w"] * (1.0 if st != "bob" else 1.1)) & (yy > top + 0.7 * H) back = curtain & neck_zone | (curtain & (yy > top + 0.95 * H) & (np.abs(xx - L["neck_cx"]) <= L["neck_w"] * 2.0)) frontc = curtain & ~back if st == "long": # frame locks fall in front of the shoulders; behind the neck is the back mass frontc = curtain & ~neck_zone front |= frontc back &= ~front if st == "curly": front, back = _curly_silhouette(L, front, back, sk_c, a, b, rng) tie = None if st == "ponytail": tie, tail = _ponytail(L, rng) back |= tail & ~front if st == "bun": bc = proj((0.0, -0.02 - 0.03, -0.26)) r = 0.16 * H bun = ellipse_mask(bc[0], bc[1], r, r * 0.86, n) & ~cap_e front |= bun & ~head | bun tie = (bc[0], bc[1], r) # beard: the jaw below the mouth corners in the hair colour (masc only) if P.get("beard"): mo = L["feat"]["mouth"] beard = head & (yy > mo["y"] - 0.06 * H) & ~(ellipse_mask(mo["x"], mo["y"] - 0.01 * H, 0.10 * H, 0.04 * H, n)) beard |= head & (yy > top + 0.55 * H) & ~face_front front |= beard part = proj((ps * 0.10, -lt * 0.6, 0.18)) return dict(front=front & ~(yy >= n), back=back, part=(part[0], part[1]), style=st, R=R, cap=cap, tie=tie, cap_e=cap_e)
def _face_front(L, xx, yy): """the face plate: the part of the head silhouette that faces the viewer (between the projected temples / jaw)""" proj, H = L["proj"], L["H"] pts = [] for v, u in ((0.20, 0.30), (0.36, 0.36), (0.55, 0.355), (0.80, L["masc"] * 0.045 + 0.255), (0.98, 0.08)): pts.append((u, v)) poly = [] for u, v in pts: z = 0.40 * math.sqrt(max(0.0, 1 - (u / 0.42) ** 2)) - 0.05 if v < 0.75 else 0.05 + 0.2 * (v - 0.75) / 0.25 p = proj((u, v, z)) poly.append(p[:2]) for u, v in reversed(pts): z = 0.40 * math.sqrt(max(0.0, 1 - (u / 0.42) ** 2)) - 0.05 if v < 0.75 else 0.05 + 0.2 * (v - 0.75) / 0.25 p = proj((-u, v, z)) poly.append(p[:2]) k = len(pts) poly = poly[:k] + [proj((0, 1.0, 0.24))[:2]] + poly[k:] return poly_mask(poly, L["n"]) & poly_mask(L["hull"], L["n"])
def _curly_silhouette(L, front, back, sk_c, a, b, rng): """H2-23: curly hair = an irregular silhouette of coils, not a sphere: union of bumps along the outline""" n, H = L["n"], L["H"] yy, xx = np.mgrid[0:n, 0:n].astype(np.float32) + 0.5 allh = front | back edge = ring(allh) ys, xs = np.nonzero(edge) r = max(1.6, 0.075 * H) order = np.argsort(np.arctan2(ys - sk_c[1], xs - sk_c[0])) bumps = np.zeros((n, n), bool) step = max(1, int(len(order) / max(6, (2 * math.pi * a) / (1.6 * r)))) for i in order[::step]: rr = r * rng.uniform(0.8, 1.2) bumps |= ellipse_mask(xs[i] + 0.5, ys[i] + 0.5, rr, rr, n) face = _face_front(L, xx, yy) grow = bumps & ~(face & (yy > L["top"] + 0.36 * L["H"])) return front | (grow & ~back), back
def _ponytail(L, rng): """H2-15: all hair gathered to a tie at the back of the head; the tail falls as a question mark""" n, H, top, proj = L["n"], L["H"], L["top"], L["proj"] side = L["part_side"] if L["face_dir"] == 0 else -L["face_dir"] tie = proj((side * 0.12, 0.30, -0.42)) if L["face_dir"] == 0: tie = (L["cx"] + side * 0.30 * H, top + 0.32 * H, 0) pts_l, pts_r = [], [] seg = 7 for i in range(seg + 1): t = i / seg x = tie[0] + side * (0.16 * math.sin(t * 2.4) + 0.08 * t) * H y = tie[1] + t * 0.82 * H w = (0.11 * (1 - t) ** 0.7 + 0.02) * H pts_l.append((x - w, y)) pts_r.append((x + w, y)) tail = poly_mask(pts_l + pts_r[::-1], n) return (tie[0], tie[1], 0.06 * H), tail
# ------------------------------------------------------------------------------------------------------------------# GLYPHS (X8): designed per face-width row, generated by rules so they flex (gaze, foreshortening, age, sex). Rows from# research16 s1 (pixnote / Slynyrd LOD table) and research17 faces small-size table: 16 px heads keep 1 px eyes and the# hair silhouette; 32 px: 2x2 eyes + brow dashes; 48: catchlight, nose shadow px, ear; 64: iris, lid line, lip shade;# 96: near-full features. X8 anchor: a 17 px wide (3/4) face carries a 7x6 near eye and a 4x5 far eye.ROWS = [(0, "A"), (9, "B"), (13, "C"), (18, "D"), (25, "E"), (34, "F")]
def face_row(wf): r = "A" for lim, name in ROWS: if wf >= lim: r = name return r
def eye_glyph(w, h, light, inner, fem=False, iris_key=E1, gaze=0): """an eye as rows of keys, designed by its own pixel width (the glyph SET changes with size, never a shrunk copy). inner = -1/+1: the side the nose is on. Rules: the upper lid is the darkest, thickest line (K) and the iris tucks under it (never a floating dot); one W catchlight on the light side from 2x3 up (research16 s4: approachable); sclera only beside / under the iris; no inner lower lid (C6); from 6 px the outer corner drops (eye tail) and the outer lower lid is a soft shadow tone; from 8 px a coloured iris under a K pupil; from 10 px a 2 px catchlight and a lid crease; women get an outer lash tick from 6 px.""" w, h = max(1, int(w)), max(1, int(h)) if w == 1: return [[K] for _ in range(min(h, 2))] if w == 2: g = [[K, K] for _ in range(max(2, min(h, 3)))] if h >= 3: g[1][1 if light > 0 else 0] = W return g g = [[None] * w for _ in range(h)] outer = w - 1 if inner < 0 else 0 inn = w - 1 - outer for c in range(w): g[0][c] = K if w >= 6: g[0][inn] = S0 # the lid thins toward the inner corner if h >= 3 and w >= 5: g[1][outer] = K # the eye tail iw = max(2, int(round(w * (0.5 if w < 8 else 0.42)))) ic = (w - iw) // 2 + gaze if (w - iw) % 2: ic += 1 if inner > 0 else 0 # odd slack goes to the outer side: the iris sits a hair toward the nose ic = max(0, min(w - iw, ic)) for r in range(1, h): for c in range(ic, ic + iw): g[r][c] = K if w >= 8 and h >= 4: # coloured iris under a K pupil: the top row stays K (lid shadow), the ring edge K, the pupil a K core, and # the iris' bottom corners round off into the sclera (no square iris) pc = ic + iw // 2 - (1 if iw % 2 == 0 else 0) pw = 2 if iw >= 5 else 1 for r in range(2, h): for c in range(ic + 1, ic + iw - 1): if not (pc <= c < pc + pw and r < h - 1): g[r][c] = iris_key g[h - 1][ic] = None g[h - 1][ic + iw - 1] = None for r in range(1, h): for c in range(w): if g[r][c] is None: if r == h - 1 and (c == 0 or c == w - 1) and h >= 3: continue # almond: no square bottom corners g[r][c] = W if h >= 4 and w >= 6: for c in range(w): if g[h - 1][c] == W and ((c > w // 2) == (inner < 0)): g[h - 1][c] = S1 # soft outer lower lid; the inner half is left out (C6) # catchlight on the light side of the iris, top row under the lid gl = ic + iw - 1 if light > 0 else ic if iw >= 3: gl += -1 if light > 0 else 1 g[1][gl] = W if w >= 10 and h >= 5: g[2][gl] = W if w >= 10: crease = [None] * w for c in range(1, w - 1): crease[c] = S0 g = [crease] + g # the lid crease, a shadow-tone line above the lid if fem and w >= 5: top = 1 if w >= 10 else 0 for r in range(len(g)): g[r] = (g[r] + [None]) if inner < 0 else ([None] + g[r]) g[top][-1 if inner < 0 else 0] = K return g
def draw_features(G, L, light, pal_keys): P, H, n, F = L["P"], L["H"], L["n"], L["feat"] # face width at the eye line (px), from the layout (hair may cover the skin there) ey = int(round((F["eye-1"]["y"] + F["eye+1"]["y"]) / 2)) row_m = poly_mask(L["hull"], n)[min(n - 1, max(0, ey))] wf = int(row_m.sum()) if row_m.any() else int(0.7 * H) row = face_row(wf) brow_key = K if _lum(P["hair_rgb"]) < 0.45 else H0 if P.get("hair_name") in ("white", "gray"): brow_key = H0 smile = P.get("smile", False) old, child, masc = L["old"], L["child"], L["masc"] if masc < 0.5 and brow_key == K: brow_key = H1 # women's brows: the hair's own dark tone, softer than the near-black (critic10 r1) # ---- eyes (X8): near eye full size, far eye foreshortened, enlarged and simplified (C3). Width ~0.22 H (X8: a 7 px # near eye on a 17 px three-quarter face; 32 px portrait ~4x4); height ~0.75 of the near width, kept by the far eye base_w = (0.215 + 0.025 * child + 0.01 * (1 - masc)) * H near_h = None eyes = [] for s in sorted((-1, 1), key=lambda s: -F["eye%+d" % s]["fore"]): e = F["eye%+d" % s] if row == "A": w, h = 1, 1 elif row == "B": w, h = 1, 2 else: w = max(2, int(round(base_w * e["fore"]))) if near_h is None: # the opening flattens as the eye gets more pixels (a 4 px eye needs 3 rows to hold lid + iris + glint; # a 12 px eye reads as an almond at ~6): ratio 0.78 at 4 px -> 0.52 at 12 px ratio = float(np.interp(w, [4, 12], [0.78, 0.52])) + 0.05 * child - 0.08 * old near_h = max(2, int(round(w * ratio))) h = near_h inner = -s g = eye_glyph(w, h, light, inner, fem=masc < 0.5, iris_key=E1) gw = len(g[0]) x0 = int(round(e["x"] - gw / 2)) y0 = int(round(e["y"] - len(g) / 2)) eyes.append((x0, y0, g, s, e)) # brows (rows C up): 1 row (2 rows from E), length ~1.1 eye width, arch high 60% out, colour tracks the hair for x0, y0, g, s, e in eyes: gw = len(g[0]) if row in ("A", "B"): continue by = y0 - (2 if row in ("C", "D") else 3) - (1 if (masc < 0.5 or child > 0.5) and row != "C" else 0) bl = max(2, int(round(gw * 1.05))) bx = x0 + (gw - bl) // 2 thick = 2 if (row in ("E", "F") and masc >= 0.5) or (row == "F") or (row == "D" and masc > 0.5) else 1 inner_left = s > 0 for i in range(bl): t = i / max(1, bl - 1) tt = (1 - t) if not inner_left else t # 0 at the inner end # a friendly neutral (research16 s3: a lowered inner end reads as anger): the inner end stays level, only # the outer tail drops one pixel, the arch peaks toward the outer end dy = 1 if tt >= 0.85 else 0 if row == "C": dy = 0 G.px([(bx + i, by + dy)], brow_key, only=SKIN_KEYS) if thick == 2 and 0.0 <= tt < 0.75: G.px([(bx + i, by + dy + 1)], brow_key if tt < 0.5 else S0, only=SKIN_KEYS) for x0, y0, g, s, e in eyes: G.stamp(x0, y0, g, only=SKIN_KEYS + (K,)) # ---- nose (row C: 1 shade px; D+: a mid-tone stroke on the shadow side + 2 px shadow under the tip, X8) nz = F["nose"] nx, ny = int(round(nz["x"])), int(round(nz["y"])) sh = -light if light != 0 else 1 if row == "C": G.px([(nx + (sh if L["yaw"] == 0 else 0), ny)], S0, only=SKIN_KEYS) elif row in ("D", "E", "F"): tx, ty = nz["top"] length = ny - int(round(ty)) G.line([(nx + sh, int(round(ty)) + max(1, length // 3)), (nx + sh, ny - 1)], S1, only=(S2, S1)) G.px([(nx, ny), (nx + sh, ny)], S0, only=SKIN_KEYS) if row in ("E", "F"): G.px([(nx - sh, ny)], S1, only=(S2,)) G.px([(nx + 2 * sh, ny - 1)], S0, only=SKIN_KEYS) # nostril wing on the shadow side # designed nose shadow (A2-e / C2): a wedge on the shadow side from the inner brow to the wing, and the # cast shadow under the tip, both one ramp step (never K: research16 s4 caps the socket / nose shadows) ty_i = int(round(ty)) wedge = [] for yy_ in range(ty_i, ny): t = (yy_ - ty_i) / max(1, ny - ty_i) wedge.append((nx + sh * (1 + int(round(t * 1.5))), yy_)) G.px(wedge, S1, only=(S2,)) G.line([(nx - sh, ny + 1), (nx + 2 * sh, ny + 1)], S1, only=(S2,)) # ---- mouth (X8: K pixels with shadow caps, no lips; gentle smile = corners up 1 px) mo = F["mouth"] if row != "A": mw = {"B": 2, "C": 3}.get(row, max(4, int(round(0.30 * wf * mo["fore"])))) if masc < 0.5 and row in ("E", "F"): mw = max(4, mw - 1) mx0 = int(round(mo["x"] - mw / 2)) my = int(round(mo["y"])) if row == "B": G.px([(mx0, my), (mx0 + 1, my)], S0, only=SKIN_KEYS) else: for i in range(mw): k = K if 0 < i < mw - 1 or row == "C" and i == 1 else S0 if row == "C": k = S0 if i != 1 else K dy = -1 if (smile and (i == 0 or i == mw - 1) and row != "C") else 0 if smile and dy: k = K # a gentle smile: the corners turn up as line, with a shadow-tone cap outside G.px([(mx0 + (-1 if i == 0 else mw), my - 1 - (1 if row in ("E", "F") else 0))], S0, only=(S2, S1)) G.px([(mx0 + i, my + dy)], k, only=SKIN_KEYS + (H0, H1, H2)) if row in ("D", "E", "F"): # lower lip: a lit-shadow cap under the centre (1 row), upper-lip shade for women from E G.line([(mx0 + 1, my + 2), (mx0 + mw - 2, my + 2)], S1, only=(S2,)) if masc < 0.5 and row in ("E", "F"): G.line([(mx0 + 1, my - 1), (mx0 + mw - 2, my - 1)], S1, only=(S2,)) if old > 0.5 and row in ("E", "F"): # nasolabial lines, at most one each side (research17 faces rule 15: "the more wrinkles you eliminate") for sgn in (-1, 1): G.line([(nx + sgn * 2, ny + 1), (mx0 + (mw if sgn > 0 else -1), my)], S1, only=(S2,)) # ---- freckles (a prompt word): broken shadow-tone specks across the nose and the upper cheeks, from row D if P.get("freckles") and row in ("D", "E", "F"): rng = L["rng"] ey2 = int(round(max(F["eye-1"]["y"], F["eye+1"]["y"]))) for s_ in (-1, 1): ex = F["eye%+d" % s_]["x"] for k in range(3 if row == "D" else 5): G.px([(int(round(ex + rng.uniform(-0.6, 0.6) * base_w)), ey2 + int(rng.integers(2, 4 + (row != "D"))))], S0, only=(S2, S1)) # ---- old: an under-eye pouch line (rows E/F), never K if old > 0.5 and row in ("D", "E", "F"): for x0, y0, g, s, e in eyes: gw = len(g[0]) xa, xb = (x0 + gw // 2, x0 + gw - 1) if s < 0 else (x0, x0 + gw // 2 - 1) # the outer half only if s > 0: xa, xb = x0 + gw // 2, x0 + gw - 1 else: xa, xb = x0, x0 + gw // 2 - 1 G.line([(xa, y0 + len(g) + 1), (xb, y0 + len(g) + 1)], S1, only=(S2,)) # ---- ears (row D up): a notch in the hair; S1 body, S0 inner fold (X8: 3x7 at a 17 px face) return dict(row=row, wf=wf, eyes=eyes)
def draw_ears(G, L, hair_front): F, H = L["feat"], L["H"] for s in (-1, 1): e = F["ear%+d" % s] if not e["vis"]: continue eh = max(2, int(round(0.22 * H))) ew = max(1, int(round(eh * (0.36 + 0.12 * max(0, e["facing"]))))) x = int(round(e["x"] - ew / 2 + s * 0.015 * H * (1 if L["yaw"] == 0 else 0))) y = int(round(e["y"] - eh / 2)) yy, xx = np.mgrid[0:L["n"], 0:L["n"]] if e.get("outline") is not None: m = poly_mask(e["outline"], L["n"]) ys_, xs_ = np.nonzero(m) if len(ys_): x, y, ew, eh = xs_.min(), ys_.min(), xs_.max() - xs_.min() + 1, ys_.max() - ys_.min() + 1 else: m = ellipse_mask(x + ew / 2, y + eh / 2, ew / 2 + 0.3, eh / 2, L["n"]) m &= ~hair_front G.fill(m, S1) # the ear's own contour (inside the head in turned views it would vanish skin-on-skin): shadow tone on the # rim except the edge that joins the head; inner fold a short stroke, its core K from 64 px (X8: K inner fold) face_side = 1 if (L["cx"] - (x + ew / 2)) > 0 else -1 rim = ring(m) & ~(shift(m, face_side, 0) & ~ring(shift(m, face_side, 0)) & False) rim &= ~((xx - (x + ew / 2)) * face_side > ew * 0.25) G.fill(rim, S0) fx = int(round(x + ew / 2 + face_side * 0.5)) if ew > 2 else x if eh >= 5: G.line([(fx, y + 2), (fx, y + eh - 3)], S0, within=m) if eh >= 10: G.line([(fx, y + 3), (fx, y + eh - 4)], K, within=m)
# ------------------------------------------------------------------------------------------------------------------def portrait(person, n=48, return_info=False, fig=None): """the portrait, drawn in the artist's order. person: dict from person_from_text; fig: the kit lane's Figure (its layout + hair layout are used when given; knob px_kitlayout=0 falls back to this module's stand-in layout)""" if fig is not None and knob("px_kitlayout"): L = layout_from_fig(fig, person) n = L["n"] else: L = head_layout(person, n) P = L["P"] pal = build_palette(P) G = Grid(n) H, top = L["H"], L["top"] yy, xx = np.mgrid[0:n, 0:n].astype(np.float32) + 0.5 # light: from the side the face turns toward the viewer from (broad light on the near cheek); front: seeded side light = (1 if L["part_side"] > 0 else -1) if L["face_dir"] == 0 else -L["face_dir"] if L.get("light") is not None: light = L["light"] # ---- 1-2 hair layout and the dark mass (X3: the hair silhouette filled with the near-black first) HM = hair_from_fig(L) if L.get("kit") is not None else hair_masks(L) head = poly_mask(L["hull"], n) G.fill(HM["back"], K) # ---- 3 masses in z order: shoulders/cloth, neck, head (face plate), front hair sh = poly_mask(L["shoulders"], n) G.fill(sh, C1) neck = poly_mask(L["neck"], n) & ~head G.fill(neck, S0) _neckline(G, L, sh, neck, light) G.fill(head, S2) # what is left of the back mass after the body and head went over it is the visible back hair HM["back"] = HM["back"] & (G.a == K) # ---- 4 face ramp (X7) _face_shading(G, L, head & ~HM["front"], light, HM) # ---- 5 hair: the dark mass, then lit locks, seams, highlight clusters (X3, X4) hairall = HM["front"] G.fill(hairall, K) _hair_locks(G, L, HM, light) # ears after the hair: they sit in a notch of short hair, over a bald horseshoe, under long curtains draw_ears(G, L, HM["front"] if HM["style"] != "bald" else np.zeros((n, n), bool)) # ---- 6 features (X8) if L.get("beard") and knob("px_beard"): _beard(G, L, light, HM) info = draw_features(G, L, light, None) if L.get("glasses") and knob("px_glasses"): _glasses(G, L, light) # ---- 7 material lines: hair over skin (X6), ramp step (X5), shirt meets neck / hair skin = G.mask(S0, S1, S2) hair_px = G.mask(H0, H1, H2) & (HM["front"] | HM["back"]) if knob("px_hairline"): # thin locks (<= 3 px across) keep their colour: the outline already bounds them hf = HM["front"] thick = (shift(hf, 1, 0) & shift(hf, 2, 0)) | (shift(hf, -1, 0) & shift(hf, -2, 0)) | \ (shift(hf, 0, -1) & shift(hf, 0, -2)) G.fill(hair_px & touch4(skin) & hf & thick, K) if knob("px_rampstep"): # X5: where a lit hair colour meets the dark mass on its SHADOW side (away from the light, or below) it steps # down through the shadow tone; the lit side keeps its hard edge lit = G.mask(H1, H2) & (HM["front"] | HM["back"]) dk = G.mask(K) & (HM["front"] | HM["back"]) G.fill(lit & (shift(dk, -light, 0) | shift(dk, 0, 1)), H0) lc = G.mask(C1) G.fill(lc & touch4(G.mask(K)) & ring(sh) & (xx * light < (L["cx"] * light)), C0) # ---- 8 outline (X10): 1 px near-black inside the figure silhouette; the frame cut is not an outline fg = G.a != BG out = ring(fg) out[n - 1, :] = False if knob("px_selout"): # selective outline (research16 s5, lospec; critic10 r1: lit-side false ink): where the figure's edge faces the # light, the outline is the material's own shadow tone, not the near-black; the shadow side and the bottom keep K lit_edge = out & shift(~fg, light, 0) & ~shift(~fg, 0, 1) keep = G.a.copy() G.fill(out & ~lit_edge, K) for src, dst in ((S2, S0), (S1, S0), (S0, S0), (H1, H0), (H2, H0), (H0, K), (C1, C0), (C0, K), (W, C0)): G.fill(lit_edge & (keep == src), dst) G.fill(lit_edge & np.isin(keep, (K, BG)), K) else: G.fill(out, K) cloth = G.mask(C1, C0) G.fill(cloth & touch4(G.mask(S0, S1, S2, H0, H1, H2)) & sh & (yy < L["shoulder_y"] + 0.1 * H), K) # ---- 9 cleanup on flat masses only (X11): an isolated pixel in hair/cloth/skin mass takes its neighbours' key if knob("px_cleanup"): _cleanup(G, protect=_feature_zone(L, n, info)) # palette budget (X1: 7-9 colours for 32-64 px): merge the least important mid tones into their nearest neighbour _budget(G, pal, 9 if n <= 64 else 11) img = G.rgb(pal) if return_info: return img, dict(L=L, G=G, pal=pal, info=info, HM=HM) return img
def _neckline(G, L, sh, neck, light): """the garment opening: crew (round), V or open collar, by seed; the skin of the chest under it in shadow tones""" n, H, rng = L["n"], L["H"], L["rng"] kind = ("crew", "v", "collar")[int(rng.integers(3))] if L.get("chest_skin") is not None and len(L["chest_skin"]) >= 3: kind = "kit" nx, nw, top = L["neck_cx"], L["neck_w"], L["top"] y0 = top + 1.02 * H if kind == "kit": m = poly_mask(L["chest_skin"], n) & sh elif kind == "crew": m = ellipse_mask(nx, y0, nw * 1.25, 0.10 * H, n) & sh elif kind == "v": m = poly_mask([(nx - nw * 1.15, y0 - 0.06 * H), (nx + nw * 1.15, y0 - 0.06 * H), (nx, y0 + 0.30 * H)], n) & sh else: m = poly_mask([(nx - nw * 1.2, y0 - 0.06 * H), (nx + nw * 1.2, y0 - 0.06 * H), (nx, y0 + 0.22 * H)], n) & sh G.fill(m, S0) if kind == "collar": for s in (-1, 1): c = poly_mask([(nx + s * nw * 1.25, y0 - 0.08 * H), (nx + s * nw * 0.1, y0 + 0.24 * H), (nx + s * nw * 1.9, y0 + 0.12 * H)], n) & sh G.fill(c, W if G.n >= 40 else C1) # cloth shading: the shadow side of the torso turns away (a 2-step band), and a fold under the neckline yy, xx = np.mgrid[0:n, 0:n].astype(np.float32) + 0.5 # the shadow-side shoulder turns away: a band along its outer contour (C2: a designed shape, not a half split) d = max(1, int(round(0.10 * H))) edge = sh & ~shift(sh, light * d, 0) & ((xx - nx) * light < 0) G.fill(edge, C0, only=(C1,)) G.fill(sh & ring(m | neck) & ~m & ~neck, C0, only=(C1,)) # neck: in shadow (X9) with a lit strip on the light side # X9 neck in shadow, but a big neck all in the shadow tone reads as a dark slab: the light-side 40% is the mid # tone, and the jaw's cast shadow (2-3 px under the head) stays in the shadow tone across the whole neck lit = neck & ((xx - nx) * light > -nw * 0.15) head = poly_mask(L["hull"], n) cast = np.zeros_like(neck) for k in range(1, max(2, int(round(0.07 * H))) + 1): cast |= shift(head, 0, -k) G.fill(lit & ~cast, S1)
def _face_shading(G, L, face, light, HM): """X7: light core, 1-2 px mid rim on both sides, shadow tone at the far edge and jaw, a cast band under the fringe; turned views: the far plane of the face (beyond the cheekbone) in the mid tone (A2-style designed shadow, C2)""" n, H, top = L["n"], L["H"], L["top"] yy, xx = np.mgrid[0:n, 0:n].astype(np.float32) + 0.5 e1 = ring(face) e2 = ring(face & ~e1) shade_side = (xx - L["cx"]) * light < 0 G.fill(e1, S1, only=(S2,)) if H > 24: G.fill(e2 & shade_side, S1, only=(S2,)) # designed shadow shape (C2): the face minus the face shifted toward the light ~0.06 H, on the shadow side d = max(1, int(round(0.07 * H))) shifted = shift(face, -light * d, 0) band = face & ~shifted G.fill(band, S1, only=(S2,)) G.fill(e1 & (shade_side | (yy > top + 0.86 * H)), S0) # jaw underside: the bottom 1-2 px of the chin turn away jaw = face & ~shift(face, 0, 1) G.fill(jaw, S0) # fringe cast band: skin under the hair (1-2 px), thicker on the swept side hf = HM["front"] cast = face & (shift(hf, 0, -1) | (shift(hf, 0, -2) & (H > 30))) G.fill(cast, S1, only=(S2,)) G.fill(face & shift(hf, 0, -1) & shade_side, S0) # under the nose and the eye sockets get nothing (research16 s4: cap socket shadows; friendly faces)
def _hair_locks(G, L, HM, light): """X4: 2-3 big locks from the parting, one seam each, highlights as broken 2-3 px clusters (~10% of the hair); curly: every coil is a small lock (dark inside, lit cap + a highlight speck on its outer turn)""" n, H = L["n"], L["H"] rng = L["rng"] front = HM["front"] allh = front | HM["back"] yy, xx = np.mgrid[0:n, 0:n].astype(np.float32) + 0.5 px, py = HM["part"] st = HM["style"] if st == "bald": G.fill(front, H0) G.fill(front & (yy < np.median(yy[front]) if front.any() else front), H1) return if st == "curly": _curls(G, L, allh, light) return ang = np.arctan2(xx - px, yy - py + 0.25 * H) # 0 = straight down from (a point above) the parting dist = np.hypot(xx - px, yy - py) # lock boundaries: split the front hair's angles into n locks of similar size (seeded) # lock count grows with the head (X4: 2-3 big locks at 48 px; more only when there are pixels for them) nl = HM["R"]["locks"] if HM["R"]["locks"] else 2 if H < 22: nl = 2 elif H > 44: nl += 1 # flow: a lock that leaves the parting sideways turns down with gravity, so in polar terms around the parting its # angle shrinks with distance; boundaries follow that curve instead of straight rays bend = np.clip(dist / H - 0.15, 0, 1.2) * 0.45 ang = ang * (1 - bend) a_f = ang[front] if a_f.size == 0: return # the parting splits the hair into the two big locks; a third lock (long styles, >= 48 px) splits the larger side pa = 0.0 bounds = [pa] a_f = ang[front] left, right = a_f[a_f < pa], a_f[a_f >= pa] extra = nl - 2 for k in range(extra): big = left if left.size > right.size else right if big.size <= 20: break q = float(np.quantile(big, 0.5)) + rng.uniform(-0.06, 0.06) bounds.append(q) if big is left: left = left[left > q] if (left > q).sum() > (left <= q).sum() else left[left <= q] else: right = right[right > q] if (right > q).sum() > (right <= q).sum() else right[right <= q] bounds = sorted(bounds) gap = np.zeros((n, n), bool) for b in bounds: # the dark mass shows between locks: at the parting a short wedge (the part line seen from the front), elsewhere # a 1 px seam of the dark mass that opens a little toward the tips (X4: big locks, not a comb) if b == pa and HM.get("part_line") is not None: continue if b == pa: # the part line seen from the front: a short dark V that closes as the two locks meet lower down reach = 0.16 * H wpx = 0.5 + 0.6 * np.clip(1 - dist / reach, 0, 1) gap |= (np.abs(ang - b) * np.maximum(dist, 1.0) < wpx) & (dist < reach) seams = np.zeros((n, n), bool) for b in bounds: if b != pa: # between locks on one side: a shadow-tone seam (X4), opening to the dark mass only near the tips seams |= (np.abs(ang - b) * np.maximum(dist, 1.0) < 0.5) & (dist > 0.10 * H) lit = front & ~gap if HM.get("part_line") is not None and len(HM["part_line"]) >= 2: # the kit's part line (hairline -> crown): a 1 px dark line, drawn only on its front half (it turns away) pl = HM["part_line"] pts = pl[: max(2, int(len(pl) * 0.6))] pm = np.zeros((n, n), bool) for x, y in line_px([tuple(p) for p in pts]): if 0 <= x < n and 0 <= y < n: pm[y, x] = True lit &= ~(pm & front) # the back mass: lit only in its outer column on the light side G.fill(lit, H1) G.fill(seams & lit, H0) if HM.get("seams") is not None: G.fill(HM["seams"] & lit, H0) G.fill(HM["back"] & ring(HM["back"]) & ((xx - L["cx"]) * light > 0), H0) # each lock: its shadow-side edge one ramp step down (lock = a cylinder, light from one side) for i in range(len(bounds) + 1): lo = bounds[i - 1] if i > 0 else -9 hi = bounds[i] if i < len(bounds) else 9 lock = lit & (ang > lo) & (ang <= hi) if not lock.any(): continue # seam (X4): ONE H0 line along the lock's flow, from near the parting toward the tip mid = np.median(ang[lock]) lys, lxs = np.nonzero(lock) dmax = dist[lock].max() pts = [] for t in np.linspace(0.25, 0.85, 6): r = t * dmax pts.append((px + math.sin(mid + 0.12 * (t - 0.5) * light) * r, py - 0.25 * H + math.cos(mid) * r + 0.25 * H * t)) if lock.sum() > 0.025 * H * H: G.line(pts, H0, only=(H1,), within=lock) # shadow-side edge sd = lock & ~shift(lock, -light, 0) G.fill(sd, H0, only=(H1,)) # highlight clusters: an arc band at ~0.25-0.35 H from the parting, broken, on the lit part of each lock r0 = (0.20 + 0.12 * rng.random()) * H thick = max(1.6, 0.075 * H) zz = 0.6 * np.sin(ang * (7 + 3 * rng.random()) + rng.uniform(0, 6)) band = lock & (np.abs(dist - r0 - zz) < thick / 2 + 0.3) # break the band: keep pieces on the lit half of the lock lit_half = (ang - mid) * light * 1.0 > -0.08 band &= lit_half G.fill(band, H2, only=(H1, H0)) if st == "long" or st == "bob": r1 = r0 + (0.45 + 0.2 * rng.random()) * H band2 = lock & (np.abs(dist - r1 - zz) < thick / 2) & lit_half & ((xx - px) * light > 0) G.fill(band2, H2, only=(H1,)) if HM.get("tie") is not None: tx, ty, tr = HM["tie"] if st == "bun": bun = ellipse_mask(tx, ty, tr, tr * 0.86, n) & allh G.fill(bun, H1) G.fill(bun & ~shift(bun, -light, 0) | (bun & ~shift(bun, 0, 1)), H0) G.line([(tx - tr * 0.6, ty - tr * 0.1), (tx, ty + tr * 0.3), (tx + tr * 0.6, ty - tr * 0.1)], K, within=bun) G.fill(bun & ellipse_mask(tx + light * tr * 0.35, ty - tr * 0.45, tr * 0.32, tr * 0.18, n), H2) else: tail = HM["back"] G.fill(tail & ~ring(tail), H1) G.fill(tail & ~shift(tail, -light, 0), H0) G.fill(tail & (np.abs(yy - ty - 0.25 * H) < max(1.0, 0.04 * H)) & ((xx - tx) * light > -0.02 * H), H2, only=(H1,)) if HM.get("part_line") is None: tie_m = ellipse_mask(tx, ty, max(1.0, 0.05 * H), max(1.0, 0.05 * H), n) & allh G.fill(tie_m, K)
def _curls(G, L, allh, light): n, H, rng = L["n"], L["H"], L["rng"] r = max(1.6, 0.095 * H) ys, xs = np.nonzero(allh) if len(ys) == 0: return yy, xx = np.mgrid[0:n, 0:n].astype(np.float32) + 0.5 # a jittered lattice of coil centres over the hair; each coil: lit cap toward the light, dark below step = r * 1.55 cs = [] for j, y in enumerate(np.arange(ys.min(), ys.max() + 1, step)): for x in np.arange(xs.min() + (j % 2) * step / 2, xs.max() + 1, step): cx, cy = x + rng.uniform(-0.25, 0.25) * r, y + rng.uniform(-0.25, 0.25) * r if 0 <= int(cy) < n and 0 <= int(cx) < n and allh[int(cy), int(cx)]: cs.append((cx, cy)) for cx, cy in cs: coil = ellipse_mask(cx, cy, r * 0.82, r * 0.78, n) & allh G.fill(coil, H1) # the underside of each coil turns away: a crescent one ramp step down G.fill(coil & ~shift(coil, 0, max(1, int(r * 0.45))), H0) for cx, cy in cs: if rng.random() < 0.55 and (cy < np.median(ys) or rng.random() < 0.3): G.px([(cx + light * 0.35 * r, cy - 0.45 * r)], H2, only=(H1,)) if r > 2.5: G.px([(cx + light * 0.35 * r + light, cy - 0.45 * r)], H2, only=(H1,)) # the side away from the light stays darker (value plan) far = allh & ((xx - L["cx"]) * light < -0.25 * H) G.fill(far & G.mask(H1) & (((xx.astype(int) + yy.astype(int)) % 3) == 0), H0)
def _feature_zone(L, n, info): z = np.zeros((n, n), bool) for x0, y0, g, s, e in info["eyes"]: z[max(0, y0 - 4):y0 + len(g) + 2, max(0, x0 - 2):x0 + len(g[0]) + 2] = True F = L["feat"] for k in ("nose", "mouth"): x, y = int(F[k]["x"]), int(F[k]["y"]) z[max(0, y - 4):y + 4, max(0, x - 6):x + 7] = True return z
def _cleanup(G, protect): """X11: an isolated pixel (no 4-neighbour of its key) inside a flat mass takes the majority neighbour key, but never in feature zones and never highlight keys (they keep their 1-2 px clusters)""" a = G.a n = G.n out = a.copy() for y in range(1, n - 1): for x in range(1, n - 1): k = a[y, x] if protect[y, x] or k in (H2, W, K, BG): continue nb = [a[y - 1, x], a[y + 1, x], a[y, x - 1], a[y, x + 1]] if k not in nb: vals, cnt = np.unique(nb, return_counts=True) if cnt.max() >= 3 and vals[cnt.argmax()] not in (BG,): out[y, x] = vals[cnt.argmax()] G.a = out
def _budget(G, pal, maxc): used = [k for k in np.unique(G.a)] order = [E1, C0, H2, S0, H0, BG, C1] # which keys may merge first (least load-bearing) while len(set(pal[k] for k in used)) > maxc: merged = False for k in order: if k not in used: continue others = [o for o in used if o != k] best = min(others, key=lambda o: _de(pal[k], pal[o])) if k == E1 or _de(pal[k], pal[best]) < 30 or k == C0: G.a[G.a == k] = best used.remove(k) merged = True break if not merged: break
def sheet(people, n=48, scale=6, cols=4, pad=4): """people: list of (label, person) -> RGB array of NN-upscaled portraits (for LOOKING, not generation)""" tiles = [np.kron(portrait(p, n), np.ones((scale, scale, 1), np.uint8)) for _, p in people] rows = (len(tiles) + cols - 1) // cols T = n * scale out = np.full((rows * (T + pad) + pad, cols * (T + pad) + pad, 3), 235, np.uint8) for i, t in enumerate(tiles): r, c = divmod(i, cols) out[pad + r * (T + pad):pad + r * (T + pad) + T, pad + c * (T + pad):pad + c * (T + pad) + T] = t return out
# ------------------------------------------------------------------------------------------------------------------# the kit lane's style-module contract (pydraw/figure/__init__.py): render(fig, size, seed, trace), work_size, KNOBKNOB = "fig2d_px"
def work_size(size, framing=None): """the portrait is drawn on its own pixel grid and upscaled nearest-neighbour: 64 px for a 512 output (the pixel QUALITY48 renders use res = size / 2 for scenes; a portrait reads best at 48-96 px, X8 / research16 s1)""" return int(max(32, min(96, round(size / 8.0))))
def person_from_fig(fig): """adapter: the kit's Figure -> this module's person dict; whatever the kit does not say comes from the words""" text = getattr(fig, "text", "") or "" seed = int(getattr(fig, "seed", 0) or 0) P = person_from_text(text, seed) per = getattr(fig, "person", None) get = (lambda k: per.get(k) if isinstance(per, dict) else getattr(per, k, None)) if per is not None: sex = get("sex") if isinstance(sex, (int, float)): P["masc"] = float(sex) P["sex"] = "m" if sex >= 0.5 else "f" elif sex in ("m", "f"): P["sex"] = sex P["masc"] = 1.0 if sex == "m" else 0.0 for k_src, k_dst in (("age", "age"), ("hair_style", "hair_style"), ("beard", "beard"), ("smile", "smile")): v = get(k_src) if v is not None: P[k_dst] = v for k_src, k_dst in (("hair_rgb", "hair_rgb"), ("skin_rgb", "skin_rgb"), ("cloth_rgb", "cloth_rgb")): v = get(k_src) if v is not None and len(v) == 3: P[k_dst] = tuple(int(round(c * 255)) if max(v) <= 1.0 else int(c) for c in v) pose = getattr(fig, "pose", None) yaw = pose.get("yaw") if isinstance(pose, dict) else getattr(pose, "yaw", None) if yaw is not None: P["yaw"] = float(yaw) if P.get("hair_style") not in HAIR_STYLES: P["hair_style"] = person_from_text(text, seed)["hair_style"] return P
def render(fig, size, seed=0, trace=None): """the kit contract entry point (figure/__init__.render_figure calls it at work_size and upscales nearest): a pixel portrait of fig's person drawn on fig.layout / fig.hair; without a kit layout, this module's stand-in""" P = person_from_fig(fig) if getattr(fig, "layout", None) is not None and knob("px_kitlayout"): img, I = portrait(P, int(fig.layout.size), return_info=True, fig=fig) P = I["L"]["P"] else: img = portrait(P, int(size)) if trace is not None: trace.append("figure/pixel: %d px portrait (%s %d, %s %s hair, %s skin, yaw %+d)" % ( img.shape[0], P["sex"], int(P["age"]), P["hair_name"], P["hair_style"], P["skin_name"], int(P["yaw"]))) return img
# ------------------------------------------------------------------------------------------------------------------# the kit lane's layout and hair layout (pydraw/figure/layout.py, hairlayout.py) -> this drawer's terms. The kit# names sides from the SUBJECT (_L = subject's left = viewer's right); this module names them by image side# (-1 = viewer's left). yaw > 0 turns the face to the viewer's right in both.def _side_key(s): return "R" if s < 0 else "L"
def person_from_kit(fig, person=None): """the kit Person -> this module's person dict (colours through this module's ramps, X1/X2)""" text = getattr(fig, "text", "") or "" seed = int(getattr(fig, "seed", 0) or 0) P = dict(person) if person else person_from_text(text, seed) per = getattr(fig, "person", None) if per is None: return P sex = float(getattr(per, "sex", P.get("masc", 0.5))) P["masc"] = sex P["sex"] = "m" if sex >= 0.5 else "f" P["age"] = float(getattr(per, "age", P.get("age", 30))) hs = getattr(per, "hair_style", None) if hs == "buzz": hs = "short" if hs in HAIR_STYLES: P["hair_style"] = hs hc = getattr(per, "hair_color", None) if hc: hc = {"grey": "gray", "silver": "gray", "blond": "blonde", "ginger": "red", "brunette": "brown"}.get(hc, hc) if hc in HAIR: P["hair_name"] = hc P.pop("hair_rgb", None) sk = getattr(per, "skin", None) if isinstance(sk, (int, float)): # kit skin is 0 (pale) .. 1 (deep): the kit's own tone (value.skin_rgb) is the ramp's mid; the name is for traces names = ["pale", "light", "medium", "olive", "tan", "brown", "deep"] P["skin_name"] = names[int(round(float(sk) * (len(names) - 1)))] P.pop("skin_rgb", None) tl = " " + text.lower() + " " if any(w in tl for w in (" dark skin", " dark-skinned", " dark brown skin", " deep skin", " black skin")): sk = max(float(sk), 0.85) # "dark brown skin": the darkness word wins over the hue word try: from .value import skin_rgb as _kit_skin c = np.asarray(_kit_skin(float(sk), int(getattr(per, "seed", 0) or 0)), np.float32) P["skin_rgb"] = tuple(int(round(v * 255)) for v in np.clip(c, 0, 1)) except Exception: pass cc = getattr(per, "cloth_color", None) if cc in CLOTH: P["cloth_name"] = cc P["cloth_explicit"] = True P.pop("cloth_rgb", None) ec = getattr(per, "eye_color", None) if ec in EYE_RGB: P["eye_name"] = ec P["beard"] = bool(getattr(per, "beard", None)) tl = " " + text.lower().replace(",", " ") + " " for w, c in (("white beard", "white"), ("grey beard", "gray"), ("gray beard", "gray"), ("black beard", "black"), ("dark beard", "black"), ("red beard", "red"), ("brown beard", "brown"), ("ginger beard", "red"), ("blonde beard", "blonde")): if w in tl and (P.get("hair_style") == "bald" or not hc): P["hair_name"] = c # a bald or hair-colourless man: the hair ramp is the beard's P.pop("hair_rgb", None) P["smile"] = getattr(per, "expression", "neutral") == "smile" or P.get("smile", False) pose = getattr(fig, "pose", None) if pose is not None: P["yaw"] = float(getattr(pose, "yaw", 0.0)) return P
def layout_from_fig(fig, person=None): KL = fig.layout P = _complete(person_from_kit(fig, person)) n = int(KL.size) H = float(KL.H) pt = KL.pt rng = np.random.default_rng(zlib.crc32(("lay|%d|%s" % (P.get("seed", 0), P.get("text", ""))).encode())) yaw = float(getattr(KL, "yaw", 0.0)) face_dir = 0 if abs(yaw) < 8 else (1 if yaw > 0 else -1) feat = {} for s in (-1, 1): e = KL.eyes[_side_key(s)] feat["eye%+d" % s] = dict(x=float(e["c"][0]), y=float(e["c"][1]), z=float(e.get("z", 0.3)), fore=float(e.get("fs", 1.0)), kit_w=float(e.get("w", 0)), kit_h=float(e.get("h", 0))) er = KL.ears[_side_key(s)] c = np.asarray(er.get("c", (0, 0)), np.float32) feat["ear%+d" % s] = dict(x=float(c[0]), y=float(c[1]), vis=bool(er.get("visible", False)), side=s, facing=0.4 if er.get("visible") else -1.0, outline=np.asarray(er["outline"], np.float32) if er.get("outline") is not None else None) nz = KL.nose tip, base = np.asarray(nz["tip"], np.float32), np.asarray(nz["base"], np.float32) feat["nose"] = dict(x=float(tip[0]), y=float(round((tip[1] + base[1]) / 2)), top=tuple(np.asarray(pt["nose_root"]).tolist())) mo = KL.mouth feat["mouth"] = dict(x=float(mo["c"][0]), y=float(mo["c"][1]), fore=1.0, kit_w=float(mo.get("w", 0))) feat["chin"] = tuple(np.asarray(pt["chin"]).tolist()) neck = np.asarray(KL.neck, np.float32) nxs = neck[:, 0] top = float(pt["crown"][1]) light = int(getattr(KL, "light_side", -1)) or -1 L = dict(P=P, n=n, H=H, top=top, cx=float(pt["head_c"][0]), yaw=math.radians(yaw), face_dir=face_dir, hull=np.asarray(KL.face, np.float32), feat=feat, neck=neck, neck_w=float((nxs.max() - nxs.min()) / 2), neck_cx=float((nxs.max() + nxs.min()) / 2), shoulders=np.asarray(KL.torso, np.float32), shoulder_y=float(min(pt["shoulder_L"][1], pt["shoulder_R"][1])), eye_v=(float(KL.eyes["L"]["c"][1]) - top) / H, nose_v=(float(base[1]) - top) / H, mouth_v=(float(mo["c"][1]) - top) / H, rx=0.37, child=max(0.0, min(1.0, (16.0 - P["age"]) / 12.0)), old=max(0.0, min(1.0, (P["age"] - 50.0) / 25.0)), masc=P["masc"], part_side=int(getattr(fig.hair, "parting", {}).get("side", 1) or 1) if fig.hair else 1, proj=None, rng=rng, light=light, kit=KL, hl=fig.hair, neckline=np.asarray(KL.neckline, np.float32) if getattr(KL, "neckline", None) is not None else None, chest_skin=np.asarray(KL.chest_skin, np.float32) if getattr(KL, "chest_skin", None) is not None else None, beard=getattr(KL, "beard", None), glasses=getattr(KL, "glasses", None)) return L
def _below_none(m): """pixels with hair both above and below in the same column within 2 px (an interior slit, not a fringe edge)""" return (shift(m, 0, -1) | shift(m, 0, -2)) & (shift(m, 0, 1) | shift(m, 0, 2))
def hair_from_fig(L): """the kit's hair layout as this drawer's masks: front (cap, bangs, side / top locks in front of the face, bun), back (the back mass and every lock behind the head), the parting point the 2-3 pixel locks radiate from (X4)""" HL, n, H = L["hl"], L["n"], L["H"] front = np.zeros((n, n), bool) back = np.zeros((n, n), bool) st = getattr(HL, "style", "short") if HL is not None else "bald" st = "short" if st == "buzz" else st if HL is None or st == "bald": R = dict(HAIR_RECIPE["bald"]) if HL is not None: for lk in HL.locks: front |= poly_mask(lk.poly(), n) if HL.back is not None: back |= poly_mask(np.asarray(HL.back), n) return dict(front=front, back=back & ~front, part=(L["cx"], L["top"]), style="bald", R=R, cap=front, tie=None) if HL.cap is not None: front |= poly_mask(np.asarray(HL.cap), n) if HL.back is not None: back |= poly_mask(np.asarray(HL.back), n) tie = None for lk in HL.locks: m = poly_mask(lk.poly(), n) if lk.group == "bun": front |= m elif lk.z < -1.0 or lk.group == "back" or (lk.group == "tail" and lk.z < 0): back |= m else: front |= m if getattr(HL, "bun", None): b = HL.bun front |= poly_mask(np.asarray(b["outline"]), n) tie = (float(b["c"][0]), float(b["c"][1]), float(max(b["rx"], b["ry"]))) elif getattr(HL, "tie", None) is not None and st == "ponytail": tie = (float(HL.tie[0]), float(HL.tie[1]), 0.06 * H) if st == "ponytail" and abs(math.degrees(L["yaw"])) < 12 and knob("px_tailswing"): # a front view hides the tail behind the head; it swings out beside the neck so it reads (H2-15: the tail is # a question mark, out then down) sd = L["part_side"] or 1 for lk in HL.locks: if lk.group == "tail": poly = np.asarray(lk.poly(), np.float32).copy() poly[:, 0] += sd * 0.34 * H back |= poly_mask(poly, n) back &= ~front # C5: the fringe's lower edge over the face is made of lock tips, not a ruler line: V notches every ~0.12 H head = poly_mask(L["hull"], n) edge = front & head & ~shift(front, 0, 1) ys_, xs_ = np.nonzero(edge) per = max(3.0, 0.12 * H) ph = float(L["rng"].uniform(0, per)) for y_, x_ in zip(ys_, xs_): t = ((x_ - ph) / per) % 1.0 d = int(round((1 - abs(2 * t - 1)) * max(1.0, 0.05 * H))) for k in range(d): if y_ - k >= 0 and front[y_ - k, x_] and (y_ - k - 1 >= 0 and front[y_ - k - 1, x_]): front[y_ - k, x_] = False line = np.asarray(HL.parting["line"], np.float32) if HL.parting and HL.parting.get("line") is not None else None if line is not None and len(line): pp = line[int(len(line) * 0.6)] part = (float(pp[0]), float(pp[1])) else: part = (L["cx"], L["top"]) R = dict(HAIR_RECIPE.get(st, HAIR_RECIPE["short"])) # pixel masses (X4: 2-3 big locks, not a comb): close the 1 px slits between the kit's lock ribbons; the lock tips # (the silhouette breaks) stay because closing only fills gaps narrower than 2 px grown = front | shift(front, 1, 0) | shift(front, -1, 0) | shift(front, 0, 1) | shift(front, 0, -1) closed = grown & shift(grown, 1, 0) & shift(grown, -1, 0) & shift(grown, 0, 1) & shift(grown, 0, -1) front = front | (closed & ~poly_mask(L["hull"], n)) | (closed & _below_none(front)) # bang strands: the shared edges of neighbouring bang / top locks (not the outer silhouette) become seams, so a # full fringe reads as 3-5 locks instead of a bowl (X4 seams; C5) seams = np.zeros((n, n), bool) if H >= 26: lm = [poly_mask(lk.poly(), n) for lk in HL.locks if lk.group == "bang" and lk.z >= -1.0] for i, a in enumerate(lm): others = np.zeros((n, n), bool) for j, b in enumerate(lm): if j != i: others |= b seams |= ring(a) & shift(others & ~a, 1, 0) | (ring(a) & shift(others & ~a, -1, 0)) seams &= front & ~ring(front) hm = dict(front=front, back=back, part=part, style=st, R=R, cap=front, tie=tie, part_line=line, seams=seams) if st == "ponytail" and tie is not None: hm["tail_mask"] = back.copy() return hm
def _beard(G, L, light, HM): """a beard / moustache is a hair mass on the jaw (C5, X3-X4 at small scale): the hair's lit tone with the shadow tone on its underside and shadow side, broken highlight specks on the lit upper part; the mouth stays open""" n, H = L["n"], L["H"] B = L["beard"] m = poly_mask(np.asarray(B["outline"], np.float32), n) & poly_mask(L["hull"], n) | \ (poly_mask(np.asarray(B["outline"], np.float32), n) & ~G.mask(BG, C0, C1)) if B.get("mouth_hole") is not None and len(B["mouth_hole"]) >= 3: m &= ~poly_mask(np.asarray(B["mouth_hole"], np.float32), n) if not m.any(): return yy, xx = np.mgrid[0:n, 0:n].astype(np.float32) + 0.5 G.fill(m, H1) under = m & ~shift(m, 0, max(1, int(0.05 * H))) G.fill(under, H0) G.fill(m & ((xx - L["cx"]) * light < -0.15 * H), H0) ys = np.nonzero(m)[0] top_y = ys.min() rng = L["rng"] specks = m & (yy < top_y + 0.10 * H + 2) & ((xx - L["cx"]) * light > 0) & \ (((xx.astype(int) * 3 + yy.astype(int) * 5 + int(rng.integers(5))) % 5) == 0) G.fill(specks, H2, only=(H1,)) HM["front"] = HM["front"] | m
def _glasses(G, L, light): """glasses: pixel-perfect K rims (X10), the bridge and the arms to the ear; a 1 px glint on the light side""" n = L["n"] gl = L["glasses"] for s, lens in gl["lens"].items(): P = [tuple(p) for p in np.asarray(lens, np.float32)] G.line(P + [P[0]], K) Pa = np.asarray(lens, np.float32) gx = Pa[:, 0].max() - 1 if light > 0 else Pa[:, 0].min() + 1 gy = Pa[:, 1].min() + 1 G.px([(int(gx), int(gy))], W, only=SKIN_KEYS) G.line([tuple(p) for p in np.asarray(gl["bridge"], np.float32)], K) for s, arm in gl["arms"].items(): G.line([tuple(p) for p in np.asarray(arm, np.float32)], K, only=SKIN_KEYS + HAIR_KEYS)
# ------------------------------------------------------------------------------------------------------------------# SMALL WHOLE FIGURES (32-96 px tall) for scenes: the same palette, value plan and glyph rows, built for the size# (research16 s1 LOD table: rows C-E; X1-X3, X8, X10). Standing, front or three-quarter. Returns RGBA (transparent# ground) so a scene can composite it; the scene wiring lives with the kit / people code, not here.P0, P1 = 12, 13 # trousers ramp (own keys: a figure has 2 garments; pixnote: 6-12 colours per character)NAMES += ["P0", "P1"]PANTS = {"jeans": (58, 78, 128), "brown": (96, 66, 46), "gray": (96, 98, 108), "black": (44, 42, 52), "khaki": (168, 146, 98), "navy": (40, 48, 88)}
def sprite(person, h=48, return_info=False): """a standing person h px tall as an RGBA array. Heads tall by size (research16 s1: 3-4 at 28-40 px, 4-6 at 48-64, ~6 at 96: small sprites need big heads, "realistic proportions at that scale give a stick figure").""" P = _complete(dict(person)) rng = np.random.default_rng(zlib.crc32(("spr|%d|%s" % (P.get("seed", 0), P.get("text", ""))).encode())) pal = build_palette(P) pk = list(PANTS)[int(rng.integers(len(PANTS)))] pc = PANTS[pk] if P.get("pants_rgb") is not None: pc = tuple(int(v) for v in P["pants_rgb"]) elif abs(_lum(pc) - _lum(P["cloth_rgb"])) < 0.08: pc = PANTS["jeans"] if pk != "jeans" else PANTS["khaki"] pal[P1] = pc pal[P0] = ramp_step(pc, -1, 12) age, masc = P.get("age", 30.0), P["masc"] child = max(0.0, min(1.0, (16.0 - age) / 12.0)) # research16 s1: 3-4 heads at 28-40 px, 4-6 at 48-64; we stay at the chunky end (critic8 16:30 in wave 16: the # LOD heads read better than the canon below row D) heads = float(np.interp(h, [24, 32, 48, 64, 96], [3.0, 3.3, 3.8, 4.2, 4.8])) - 0.7 * child hh = h / heads # head height px hw = hh * (0.90 + 0.06 * child) # big round heads read best small (Slynyrd PB22) W = int(math.ceil(max(hw * 2.4, hh * 2.0))) + 4 G = Grid(max(W, h)) n = G.n cx = n / 2.0 top = n - h yy, xx = np.mgrid[0:n, 0:n].astype(np.float32) + 0.5 yaw = math.radians(P.get("yaw", 0.0)) fd = 0 if abs(yaw) < 0.1 else (1 if yaw > 0 else -1) light = -fd if fd else (1 if rng.random() < 0.5 else -1) # proportions (head units): neck 0.15, torso 1.35 (shoulder -> crotch), legs the rest; shoulders 1.5-1.7 head widths neck_y = top + hh * 0.98 sh_y = top + hh * 1.10 crotch = top + hh * (1.10 + 1.25 - 0.1 * child) foot = top + h - 0.5 shw = hw * (0.74 + 0.10 * masc - 0.08 * child) # half shoulder width hipw = hw * (0.52 + 0.08 * (1 - masc)) # ---- back hair (long / bob / curly) behind everything (X3: the dark mass first) st = P.get("hair_style", "short") hcx, hcy = cx + fd * hw * 0.06, top + hh * 0.5 hair_back = np.zeros((n, n), bool) if st in ("long", "bob", "curly"): lenv = {"long": 1.55, "bob": 1.0, "curly": 1.15}[st] hair_back = poly_mask([(hcx - hw * 0.58, hcy - hh * 0.2), (hcx + hw * 0.58, hcy - hh * 0.2), (hcx + hw * 0.62, top + hh * lenv), (hcx - hw * 0.62, top + hh * lenv)], n) G.fill(hair_back, K) # ---- legs (2 px each with a 1 px gap at the small rows; tutsplus 28 px), shoes, torso, arms legw = max(1.0, hipw * 0.85) gap = 0.5 if h < 40 else max(0.5, hw * 0.06) for s in (-1, 1): x_in = cx + s * gap x_out = cx + s * (gap + legw) leg = poly_mask([(min(x_in, x_out), crotch - 1), (max(x_in, x_out), crotch - 1), (max(x_in, x_out), foot), (min(x_in, x_out), foot)], n) G.fill(leg, P1) if s == -light: G.fill(leg & ~shift(leg, -s, 0), P0) # the shadow-side edge of each leg shoe = leg & (yy > foot - max(1.5, hh * 0.16)) G.fill(shoe, K) # the shoulder line slopes from the neck (trapezius) to the shoulder point; the torso narrows to the hips torso = poly_mask([(cx - hw * 0.26, sh_y - hh * 0.06), (cx + hw * 0.26, sh_y - hh * 0.06), (cx + shw, sh_y + hh * 0.10), (cx + hipw * 1.05, crotch + 0.5), (cx - hipw * 1.05, crotch + 0.5), (cx - shw, sh_y + hh * 0.10)], n) # rounded shoulders: drop the top corner pixels (tutsplus 28 px) G.fill(torso, C1) # the torso turns away on the shadow side: a band along that contour (C2 designed shape), not a half split G.fill(torso & ~shift(torso, light * max(1, int(round(shw * 0.35))), 0) & ((xx - cx) * light < 0), C0) if knob("px_sprite_skirt") and masc < 0.5 and rng.random() < 0.4 and child < 0.9: sk = poly_mask([(cx - hipw * 1.05, crotch - hh * 0.35), (cx + hipw * 1.05, crotch - hh * 0.35), (cx + hipw * 1.5, crotch + hh * 0.6), (cx - hipw * 1.5, crotch + hh * 0.6)], n) G.fill(sk, C1) G.fill(sk & ((xx - cx) * light < -hipw * 0.5), C0) # arms hang along the torso (no gap: at this size a gap reads as a stick; tutsplus: arms 1 px outside the torso) armw = max(1.0, hw * 0.24) sleeve_long = rng.random() < 0.5 for s_ in (-1, 1): xin = cx + s_ * shw * 0.86 xout = xin + s_ * armw bot = crotch + hh * 0.10 arm = poly_mask([(min(xin, xout), sh_y + 0.6), (max(xin, xout), sh_y + 0.6), (max(xin, xout) + s_ * armw * 0.35, bot), (min(xin, xout) + s_ * armw * 0.35, bot)], n) arm &= ~torso | (np.abs(xx - xin) < armw) G.fill(arm, C1 if s_ == light else C0) if not sleeve_long: G.fill(arm & (yy > sh_y + hh * 0.5), S1 if s_ != light else S2) hand = arm & (yy > bot - max(1.5, hh * 0.22)) G.fill(hand, S1 if s_ != light else S2) # the inner edge of the arm against the torso: one darker pixel line (lospec: a line between two parts takes # the darker of the two colours) G.fill(arm & shift(torso & ~arm, -s_, 0) & (yy < bot - max(1.5, hh * 0.22)), C0) # rounded shoulders: the top outer corner pixel of each shoulder goes (tutsplus 28 px) for s_ in (-1, 1): xc = int(round(cx + s_ * (shw * 0.86 + armw))) yc = int(round(sh_y + 0.5)) for dx in range(0, max(1, int(armw * 0.6)) + 1): G.px([(xc - s_ * dx, yc)], BG) # ---- neck + head (face plate a rounded box, jaw narrower), ears neck = poly_mask([(cx - hw * 0.18, neck_y - hh * 0.2), (cx + hw * 0.18, neck_y - hh * 0.2), (cx + hw * 0.2, sh_y + 0.6), (cx - hw * 0.2, sh_y + 0.6)], n) G.fill(neck, S0) head = ellipse_mask(hcx, top + hh * 0.48, hw / 2, hh * 0.5, n) head |= poly_mask([(hcx - hw * 0.48, top + hh * 0.5), (hcx + hw * 0.48, top + hh * 0.5), (hcx + hw * 0.22, top + hh * 0.98), (hcx - hw * 0.22, top + hh * 0.98)], n) G.fill(head, S2) face = head.copy() G.fill(face & ((xx - hcx) * light < -hw * 0.30), S1) # X7 at sprite size: one shadow-side band # ---- front hair: cap with a lit top and a fringe (X3/X4 at 1-2 locks), styles by silhouette cap = ellipse_mask(hcx, top + hh * 0.42, hw * 0.56, hh * 0.47, n) & (yy < top + hh * (0.36 if st != "bald" else -1)) sides = ellipse_mask(hcx, top + hh * 0.45, hw * 0.58, hh * 0.5, n) & ~ellipse_mask(hcx + fd * hw * 0.12, top + hh * 0.6, hw * 0.40, hh * 0.48, n) sides &= yy < top + hh * (0.62 if st in ("short", "ponytail", "bun") else 0.95) front = (cap | sides) if st != "bald" else np.zeros((n, n), bool) if st == "bald" and age > 50: front = sides & (yy > top + hh * 0.35) & (yy < top + hh * 0.6) if st == "curly": for k in range(7): a = math.pi * (0.95 + 1.1 * k / 6.0) front |= ellipse_mask(hcx + math.cos(a) * hw * 0.55, top + hh * 0.42 + math.sin(a) * hh * 0.5, max(1.0, hw * 0.2), max(1.0, hw * 0.2), n) front &= ~(ellipse_mask(hcx + fd * hw * 0.1, top + hh * 0.66, hw * 0.38, hh * 0.38, n)) if st == "bun": front |= ellipse_mask(hcx - fd * hw * 0.15, top - hh * 0.02, max(1.0, hw * 0.24), max(1.0, hw * 0.2), n) if st == "ponytail": sd = -fd if fd else (1 if rng.random() < .5 else -1) hair_back |= poly_mask([(hcx + sd * hw * 0.45, top + hh * 0.25), (hcx + sd * hw * 0.72, top + hh * 0.35), (hcx + sd * hw * 0.66, top + hh * 1.0), (hcx + sd * hw * 0.5, top + hh * 0.95)], n) G.fill(hair_back & ~G.mask(S0, S1, S2), K) G.fill(front, K) # X3 at sprite size: the cap is lit inside its outline; the shadow side and the underside step down (X5) lit = front & ~ring(front) G.fill(lit, H1) G.fill(lit & (((xx - hcx) * light < -hw * 0.22) | ~shift(lit, 0, 1)), H0) vis_back = hair_back & G.mask(K) G.fill(vis_back & ((xx - hcx) * light > 0) & ~ring(vis_back), H0) # highlight: 1-2 px cluster on the lit crown (X4 at sprite scale) hx = int(round(hcx + light * hw * 0.2)) hy = int(round(top + hh * 0.14)) G.px([(hx, hy)] + ([(hx + light, hy)] if hh >= 12 else []), H2, only=(H1, K)) # beard if P.get("beard"): G.fill(head & (yy > top + hh * 0.72) & ~front, H0 if _lum(P["hair_rgb"]) > 0.3 else K) # ---- face glyphs by face width (X8 rows A-C at sprite scale) fw = hw * 0.8 row = face_row(fw) ey = int(round(top + hh * (0.55 + 0.05 * child))) ex = hcx + fd * hw * 0.12 sp_ = max(1.0, hw * 0.2) for s in (-1, 1): x = int(round(ex + s * sp_ - (0.5 if s < 0 else -0.5) * (row != "A"))) if fd and s == fd and abs(yaw) > 0.3: x = int(round(ex + s * sp_ * 0.7)) ew_ = max(2, int(round(hw * 0.2))) g = [[K]] if row == "A" else ([[K], [K]] if row == "B" else eye_glyph(ew_, max(2, int(round(ew_ * 0.8))), light, -s, fem=masc < 0.5)) G.stamp(x - (len(g[0]) // 2), ey - len(g) // 2, g, only=SKIN_KEYS) if row != "A": my = int(round(top + hh * 0.80)) G.px([(int(round(ex)), my)] + ([(int(round(ex)) + 1, my)] if row != "B" else []), S0, only=SKIN_KEYS) # ---- outline: K around the figure (pixnote warns pure black; ours is the cool near-black, X1), cleanup fg = G.a != BG G.fill(ring(fg), K) # interior separation: arms against the torso keep a 1 px darker line where cloth meets cloth of the other mass if knob("px_cleanup"): _cleanup(G, protect=np.zeros((n, n), bool)) pal2 = dict(pal) rgb = G.rgb(pal2) alpha = (G.a != BG).astype(np.uint8) * 255 out = np.dstack([rgb, alpha]) xs = np.nonzero(alpha.any(0))[0] c0 = 0 if len(xs): c0 = max(0, xs.min() - 1) out = out[:, c0: xs.max() + 2] if return_info: return out, dict(G=G, pal=pal2, heads=heads, row=row, keys=G.a[:, c0: c0 + out.shape[1]]) return out
# ------------------------------------------------------------------------------------------------------------------# scene wiring (knob px_sprite, default OFF; the hook is in rig/person_px.draw like the wave-17 anatpx trial)_AGE = {"baby": 3, "toddler": 3, "child": 8, "kid": 8, "teen": 15, "adult": 32, "old": 72, "elderly": 74}_STYLE = {"long": "long", "short": "short", "bald": "bald", "bob": "bob", "ponytail": "ponytail", "curly": "curly", "bun": "bun", "afro": "curly", "pigtails": "ponytail", "braid": "ponytail", "buzz": "short"}
def scene_eligible(cv, D, verb): """plain standing people 24-110 px tall with nothing the sprite cannot draw yet (hats, props, coats, dresses, roles)""" name, act, opts = verb if name != "stand" or act is not None: return False h = float(D.get("h") or 0) if h < 24 or h > min(110, getattr(cv, "h", 1e9) * 0.9): return False for k in ("hat", "hand_item", "holding", "dress", "coat", "cape", "tabard", "steel", "seated_on", "shoulder_ride", "in_chair", "role_name", "chibi", "toddler", "vest", "skirt"): if D.get(k): return False R_ = D.get("R") or {} if (R_.get("face") or "").split("_")[0] not in ("", "beard"): return False return True
def px_scene_person(cv, ctx, inst, D, verb): """draw one scene person as a sprite (X1-X11 at sprite scale) into the pixel canvas; True when drawn""" if not scene_eligible(cv, D, verb): return False age = _AGE.get(str(D.get("age") or "adult"), 32) st = _STYLE.get(str(D.get("style") or D.get("hl") or ""), None) fem = bool(D.get("fem")) if st is None: st = "long" if fem else "short" word = str(D.get("word") or "") P = dict(sex="f" if fem else "m", masc=0.0 if fem else 1.0, age=float(age), hair_style=st, hair_name="brown", hair_rgb=tuple(int(v) for v in D["hair"]), skin_name="scene", skin_rgb=tuple(int(v) for v in D["skin"]), cloth_name="scene", cloth_rgb=tuple(int(v) for v in D["shirt"]), cloth_explicit=True, pants_rgb=tuple(int(v) for v in D["pants"]), eye_name="dark", beard=((D.get("R") or {}).get("face") or "").startswith("beard"), smile=False, yaw=25.0 * (1 if (D.get("f") or 1) > 0 else -1), seed=int(getattr(inst, "seed", 0) or 0), text=word) if _lum(P["hair_rgb"]) > 0.62 and age > 55: P["hair_name"] = "white" h = int(round(float(D["h"]))) img, info = sprite(P, h, return_info=True) rgb, alpha = img[..., :3], img[..., 3] > 0 try: from ..anatomy.hooks import _scene_grade, paste except Exception: return False rgb = _scene_grade(rgb, D.get("L")) rows = np.nonzero(alpha.any(1))[0] if not len(rows): return False x0 = int(round(float(D["x"]) - alpha.shape[1] / 2.0)) y0 = int(round(float(D["y"]) - (rows[-1] + 1))) ids = None sid, bid = D.get("skin_id"), D.get("base_id", getattr(cv, "cur_id", None)) if bid is not None and (sid is None or sid == bid): sid = bid - .5 if sid is not None and bid is not None: ids = np.where(np.isin(info["keys"], (S0, S1, S2, H0, H1, H2)), sid, bid) paste(cv, rgb, alpha, x0, y0, ids=ids) return True123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221"""figure.value: the value plan and palette helpers decided BEFORE anything is drawn (C1, X1-X3, P-R1, A3).
plan(style, person, seed) -> ValuePlan: bands (luminance targets 0..1), the material base colours (skin, hair, eyes, cloth, background, ink) and per-material shadow tones. Style lanes may override any field. skin_rgb(tone) / hair_rgb(name) / eye_rgb(name): base colours from a 0..1 skin tone and colour words shadow(rgb, material, style) -> designed shadow tone per material (A3 multipliers; P-R9 olive/brown, never pink) ramp(rgb, n, hue_step, value_step) -> n tones dark..light with hue shift toward yellow when lighter (X2) pixel_palette(materials, ...) -> 7-9 colour pixel palette with one cool near-black and one near-white shared by every ramp (X1), dict of named keys luma(rgb), with_luma(rgb, L): Rec.709 luminance and a hue-keeping rescale to a target luminance
Base colours are generic anchors (my est., spread across the human range / common colour words), NOT sampled from anyreference picture; the per-seed jitter keeps two people of the same words apart."""import colorsysimport numpy as npfrom .canon import rng_for
F32 = np.float32
# skin: anchors along the Fitzpatrick-like range, tone 0 (very light) .. 1 (very dark); my est., 0..1 RGB_SKIN = [(0.00, (0.98, 0.86, 0.78)), (0.20, (0.95, 0.79, 0.66)), (0.40, (0.86, 0.66, 0.50)), (0.60, (0.72, 0.50, 0.35)), (0.80, (0.50, 0.33, 0.22)), (1.00, (0.32, 0.21, 0.15))]SKIN_WORDS = {"pale": 0.0, "fair": 0.08, "light": 0.15, "white": 0.12, "freckled": 0.12, "olive": 0.42, "tan": 0.45, "tanned": 0.45, "asian": 0.28, "latina": 0.45, "latino": 0.45, "hispanic": 0.45, "brown": 0.65, "indian": 0.6, "south asian": 0.6, "dark": 0.85, "black": 0.88, "african": 0.88, "ebony": 0.95}HAIR = {"black": (0.10, 0.09, 0.09), "dark": (0.18, 0.13, 0.10), "brown": (0.40, 0.26, 0.16), "brunette": (0.36, 0.23, 0.14), "chestnut": (0.48, 0.27, 0.15), "auburn": (0.58, 0.25, 0.13), "red": (0.70, 0.27, 0.12), "ginger": (0.80, 0.42, 0.18), "copper": (0.75, 0.40, 0.20), "blonde": (0.90, 0.76, 0.45), "blond": (0.90, 0.76, 0.45), "golden": (0.88, 0.70, 0.30), "platinum": (0.93, 0.90, 0.80), "grey": (0.66, 0.66, 0.66), "gray": (0.66, 0.66, 0.66), "silver": (0.80, 0.80, 0.82), "white": (0.92, 0.92, 0.90), "blue": (0.36, 0.55, 0.78), "pink": (0.95, 0.58, 0.70), "purple": (0.52, 0.36, 0.70), "green": (0.36, 0.64, 0.42), "teal": (0.26, 0.60, 0.62), "orange": (0.95, 0.55, 0.20)}EYES = {"blue": (0.30, 0.52, 0.75), "green": (0.32, 0.58, 0.38), "brown": (0.36, 0.22, 0.12), "hazel": (0.50, 0.40, 0.20), "grey": (0.50, 0.55, 0.58), "gray": (0.50, 0.55, 0.58), "amber": (0.75, 0.50, 0.15), "dark": (0.18, 0.12, 0.08), "red": (0.70, 0.15, 0.15), "purple": (0.45, 0.30, 0.65), "violet": (0.45, 0.30, 0.65)}CLOTH = {"red": (0.72, 0.16, 0.16), "blue": (0.20, 0.32, 0.62), "navy": (0.12, 0.16, 0.32), "green": (0.22, 0.48, 0.28), "yellow": (0.92, 0.78, 0.25), "white": (0.93, 0.93, 0.91), "black": (0.10, 0.10, 0.11), "grey": (0.50, 0.50, 0.52), "gray": (0.50, 0.50, 0.52), "brown": (0.42, 0.28, 0.18), "purple": (0.42, 0.24, 0.56), "pink": (0.90, 0.55, 0.65), "orange": (0.90, 0.48, 0.16), "beige": (0.82, 0.74, 0.60), "teal": (0.16, 0.50, 0.52)}
# A3 shadow multipliers per material (anime study; ranges because they came from one picture: widened, my est.)SHADOW_MUL = { "skin": ((0.90, 0.75, 0.62), (0.94, 0.80, 0.68)), # warmer, never purple (A3); P-R9 olive/brown "hair": ((0.62, 0.68, 0.70), (0.70, 0.75, 0.78)), # same hue (A3) "cloth": ((0.80, 0.80, 0.82), (0.86, 0.86, 0.88)), # white cloth -> neutral grey x0.83 (A3) "eye": ((0.55, 0.55, 0.60), (0.65, 0.65, 0.70)),}INK_WARM = (50 / 255, 45 / 255, 35 / 255) # A3 ink a warm near-black
def luma(rgb): c = np.asarray(rgb, F32) return float(0.2126 * c[..., 0] + 0.7152 * c[..., 1] + 0.0722 * c[..., 2])
def with_luma(rgb, L): """rescale toward a target luminance keeping the hue (mix toward white when it would clip)""" c = np.clip(np.asarray(rgb, F32), 1e-4, 1) l0 = luma(c) if L <= l0: return c * (L / l0) k = c * (L / l0) if k.max() <= 1: return k t = (L - l0) / max(1e-4, 1 - l0) # blend to white return np.clip(c + (1 - c) * t, 0, 1)
def _interp(anchors, t): t = float(np.clip(t, 0, 1)) for (a, ca), (b, cb) in zip(anchors, anchors[1:]): if t <= b: u = (t - a) / (b - a) return np.array(ca, F32) * (1 - u) + np.array(cb, F32) * u return np.array(anchors[-1][1], F32)
def skin_rgb(tone, seed=0): r = rng_for(seed, "skin") c = _interp(_SKIN, tone) return np.clip(c * (1 + r.normal(0, 0.02, 3)), 0, 1).astype(F32)
def hair_rgb(name, seed=0, age=30.0, skin=0.3): r = rng_for(seed, "hair") if not name: pool = ["black", "dark", "brown", "brown", "chestnut", "blonde", "auburn"] if skin > 0.55 or r.random() < 0.3: # unprompted: darker skin -> mostly black / dark brown hair (my est.) pool = ["black", "black", "dark", "dark", "brown"] name = pool[int(r.integers(0, len(pool)))] if age >= 62: name = "grey" if r.random() < .6 else "white" c = np.array(HAIR.get(name, HAIR["brown"]), F32) return np.clip(c * (1 + r.normal(0, 0.04, 3)), 0, 1).astype(F32), name
def eye_rgb(name, seed=0): r = rng_for(seed, "eyes") if not name: name = ["brown", "brown", "dark", "hazel", "blue", "green", "grey"][int(r.integers(0, 7))] return np.array(EYES.get(name, EYES["brown"]), F32), name
def cloth_rgb(name, seed=0): r = rng_for(seed, "cloth") if not name: name = ["white", "navy", "grey", "black", "red", "green", "blue", "beige", "brown"][int(r.integers(0, 9))] return np.array(CLOTH.get(name, CLOTH["grey"]), F32), name
def shadow(rgb, material="skin", seed=0, t=None): """the designed shadow tone of a material (A3): one multiplier per channel inside the material's range""" lo, hi = SHADOW_MUL.get(material, SHADOW_MUL["cloth"]) u = rng_for(seed, "shadow", material).random() if t is None else t m = np.array(lo, F32) + (np.array(hi, F32) - np.array(lo, F32)) * u c = np.asarray(rgb, F32) if material == "cloth" and np.ptp(c) < 0.06 and luma(c) > 0.7: # white cloth -> neutral grey (A3) return np.full(3, luma(c) * 0.83, F32) return np.clip(c * m, 0, 1)
def ramp(rgb, n=3, hue_step=12.0, value_step=0.16, sat_step=0.04): """n tones dark -> light around rgb (index n//2 = rgb). Lighter steps shift hue toward yellow (60 deg) by hue_step deg, darker steps toward red/purple (X2: +8..+18 deg per step); returns list of float32 RGB""" h, l, s = colorsys.rgb_to_hls(*[float(v) for v in np.clip(rgb, 0, 1)]) out = [] mid = n // 2 for i in range(n): k = i - mid hd = h * 360.0 # move toward 60 deg (yellow) when lighter, away (toward red / purple) when darker tgt = 60.0 diff = ((tgt - hd + 180) % 360) - 180 step = np.sign(diff) * min(abs(diff), abs(hue_step) * abs(k)) if k > 0 else -np.sign(diff) * abs(hue_step) * abs(k) hh = ((hd + step) % 360) / 360.0 ll = float(np.clip(l + value_step * k, 0.03, 0.97)) ss = float(np.clip(s + sat_step * (-abs(k) if k > 0 else abs(k)), 0, 1)) out.append(np.array(colorsys.hls_to_rgb(hh, ll, ss), F32)) return out
def near_black(rgb_hint=(0.2, 0.2, 0.3)): """the one cool near-black for every outline and deepest shadow (X1)""" return np.array([0.04, 0.045, 0.07], F32)
def pixel_palette(skin, hair, cloth, bg=None, seed=0, n_skin=3, n_hair=2, n_cloth=2, hue_step=None): """X1 palette: K (cool near-black, shared outline + deepest shadow), W (near-white, shared highlight), skin ramp, hair ramp, cloth ramp, optional background. Ramps share the ends: their darkest step is K and their lightest W where the material allows (hair highlight may borrow W). Returns dict name -> RGB float32.""" r = rng_for(seed, "pxpal") hs = float(hue_step if hue_step is not None else r.uniform(8, 18)) P = {"K": near_black(), "W": np.array([0.98, 0.97, 0.94], F32)} for name, base, n in (("skin", skin, n_skin), ("hair", hair, n_hair), ("cloth", cloth, n_cloth)): R = ramp(base, n, hs, 0.14) for i, c in enumerate(R): P["%s%d" % (name, i)] = c if bg is not None: P["bg"] = np.asarray(bg, F32) return P
class ValuePlan: """luminance bands + materials. bands: {'light','mid','shadow','dark'} targets 0..1; materials: name -> base RGB; shadows: name -> designed shadow tone"""
def __init__(self, style, bands, materials, shadows, notes=()): self.style, self.bands, self.materials, self.shadows = style, bands, materials, shadows self.notes = list(notes)
def __repr__(self): return "ValuePlan(%s, bands=%s, materials=%s)" % (self.style, {k: round(v, 2) for k, v in self.bands.items()}, sorted(self.materials))
def plan(style, person, seed=0, bg=None): """the picture-level value plan (C1). Face = a middle value (painted: one band below the lightest light, P-R1); darkest dark beside the face's shadow side (hair / background); reserve the lightest light.""" skin = skin_rgb(person.skin, seed) hair, _ = hair_rgb(person.hair_color, seed, person.age, person.skin) eyes, _ = eye_rgb(getattr(person, "eye_color", None), seed) cloth, _ = cloth_rgb(getattr(person, "cloth_color", None), seed) if bg is None: r = rng_for(seed, "bg", style) # background: a value band away from the skin so the head separates (C1); hue from a muted wheel h = r.uniform(0, 1) ls = luma(skin) L = 0.25 + 0.1 * r.random() if ls > 0.45 else 0.62 + 0.15 * r.random() bg = with_luma(np.array(colorsys.hls_to_rgb(h, 0.5, 0.25 + 0.2 * r.random()), F32), L) bands = {"light": 0.92, "mid": 0.55, "shadow": 0.30, "dark": 0.07} notes = [] if style == "paint": bands = {"light": 0.88, "mid": 0.60, "shadow": 0.33, "dark": 0.08} notes.append("P-R1 face one band below the lightest light") elif style == "pixel": notes.append("X3 near-black 20-30% of the figure; lit skin darker than the hair highlight") elif style == "ink": bands = {"light": 0.93, "mid": 0.70, "shadow": 0.40, "dark": 0.07} notes.append("O2 about 60% of the face is paper") elif style == "anime": notes.append("A2 skin shadow fraction 0.3-0.4, one shadow tone per material") mats = {"skin": skin, "hair": hair, "eyes": eyes, "cloth": cloth, "bg": np.asarray(bg, F32), "ink": np.array(INK_WARM, F32), "lips": np.clip(skin * np.array([0.95, 0.72, 0.70], F32), 0, 1)} shd = {"skin": shadow(skin, "skin", seed), "hair": shadow(hair, "hair", seed), "cloth": shadow(cloth, "cloth", seed), "eyes": shadow(eyes, "eye", seed), "bg": np.asarray(bg, F32) * 0.8} # kit2: the beard material (Person.beard_color; else the hair colour, greyer with age: a beard greys first) if getattr(person, "beard", None): bc = getattr(person, "beard_color", None) if bc: beard, _ = hair_rgb(bc, seed + 1, person.age, person.skin) else: beard = hair.copy() if person.age >= 50 and luma(hair) < 0.6: beard = np.clip(hair + (np.array(HAIR["grey"], F32) - hair) * min(1.0, (person.age - 45) / 30), 0, 1) mats["beard"] = beard shd["beard"] = shadow(beard, "hair", seed) return ValuePlan(style, bands, mats, shd, notes)260 unmodified lines261262263264265266260 unmodified linesv = _verb(D, inst)if v is None:return Falsename, act, opts = vformed = _formed(D, inst)if mode == "2" and not formed and (not (name in POSED or act in POSED_ACTS) or (D["h"] > cv.h * .7260 unmodified lines261262263264265266267268269270271272273274275276277260 unmodified linesv = _verb(D, inst)if v is None:return Falseif knob("px_sprite", "0"):# wave 18 pixel lane: plain standing people as X1-X11 sprites (figure.style_pixel.sprite); default OFFfrom ..figure import style_pixel as _spxif _spx.px_scene_person(cv, ctx, inst, D, v):return Trueif knob("anatpx", "0"):# wave 17 (depict; critic9 10:57 trial, 11:39 ON after the scene-grade fix): the accepted anatomy man for one big# plain standing adult man (reach rules in pydraw.anatomy.hooks.px_eligible); PYDRAW_EXP anatpx=0 = old drawerfrom ..anatomy import hooks as _anatif _anat.px_person(cv, ctx, inst, D, v):return Truename, act, opts = vformed = _formed(D, inst)if mode == "2" and not formed and (not (name in POSED or act in POSED_ACTS) or (D["h"] > cv.h * .7
356 unmodified lines357358359360361362356 unmodified linesout_.front = "-z"out_.grip = {"guitar": .5, "violin": .5, "drum": .0, "umbrella": .05, "cup": .4, "microphone": .55}return out_# ---- proportions (standing adult; children get a big head and a shorter body)hr = .066 if not female else .063HC = np.array([0, .895, 0])356 unmodified lines357358359360361362363364365366367368369370356 unmodified linesout_.front = "-z"out_.grip = {"guitar": .5, "violin": .5, "drum": .0, "umbrella": .05, "cup": .4, "microphone": .55}return out_if os.environ.get("PYDRAW_EXP", "").find("anat3d=1") >= 0:# wave 17 wiring trial (depict, critic9 10:57; PYDRAW_EXP anat3d=1, default off): the accepted anatomy manfrom pydraw.anatomy import hooks as _anatgot = _anat.p3_person(name, ra, la, skin, hair, top, bottom, shoes, female, child, old, bald, e.get("beard"),e.get("expression"), look, chibi, prop, holding, inter, sleep, yaw,getattr(inst, "facing", None))if got is not None:return got# ---- proportions (standing adult; children get a big head and a shorter body)hr = .066 if not female else .063HC = np.array([0, .895, 0])
2 unmodified lines3452 unmodified linesscipynltkscikit-image2 unmodified lines34562 unmodified linesscipynltkscikit-imagematplotlib
pydraw/__init__.py+5
pydraw/anatomy/__init__.pyAdded+4
pydraw/anatomy/cloth.pyAdded+373
pydraw/anatomy/core.pyAdded+872
pydraw/anatomy/ear.pyAdded+175
pydraw/anatomy/eye.pyAdded+412
pydraw/anatomy/featkit.pyAdded+106
pydraw/anatomy/features.pyAdded+221
pydraw/anatomy/foot.pyAdded+314
pydraw/anatomy/hair.pyAdded+209
pydraw/anatomy/hand.pyAdded+778
pydraw/anatomy/head.pyAdded+596
pydraw/anatomy/hooks.pyAdded+294
pydraw/anatomy/limbs.pyAdded+203
pydraw/anatomy/mouth.pyAdded+249
pydraw/anatomy/nose.pyAdded+195
pydraw/anatomy/person.pyAdded+496
pydraw/anatomy/render.pyAdded+910
pydraw/anatomy/torso.pyAdded+397
pydraw/figure/__init__.pyAdded+243
pydraw/figure/canon.pyAdded+202
pydraw/figure/flat.pyAdded+131
pydraw/figure/hairlayout.pyAdded+733
pydraw/figure/kit.pyAdded+663
pydraw/figure/layout.pyAdded+730
pydraw/figure/style_anime.pyAdded
pydraw/figure/style_ink.pyAdded
pydraw/figure/style_paint.pyAdded+1724
pydraw/figure/style_pixel.pyAdded+1909
pydraw/figure/value.pyAdded+221
pydraw/rig/person_px.py+11
pydraw3d/models_person.py+8
requirements.txt+1