"""Poses: one small vocabulary of body poses shared by every creature family (quadruped, primate, bird, fish, reptile, person), plus the rigid-transform helpers the families use to pose their skeletons. A pose is a NAME (stand, walk, run, sit, lie, sleep, jump, rear, upright, howl, graze, swim, fly, perch, hang, one_leg, crawl, ride ...) chosen from the instance (inst.pose from the parser, inst.attrs["action"], interactions set by the layout / 3D placement). Each family turns the name into joint angles for its own skeleton (spine pitch, neck / head pitch and yaw, per-leg foot targets solved with 2-bone IK, tail, wings, mouth, eyelids), so a pose works for every species of the family, never per word. Posed models are scaled like the same animal standing (a lying dog is low, a rearing horse is tall), and they report ANCHORS in the model frame (mouth, nose, beak, hand, saddle, seat ...) so the 3D renderer can put a held thing in a mouth or hand and a rider on a back. Pure numpy; no learned anything. """ import math import numpy as np # ---------------------------------------------------------------- vocabulary # rule: every pose word the parser or layout may set maps to one canonical pose CANON = { None: None, "standing": "stand", "stand": "stand", "parked": None, "posing": "stand", "walking": "walk", "walk": "walk", "strolling": "walk", "trotting": "walk", "wandering": "walk", "marching": "walk", "running": "run", "run": "run", "racing": "run", "galloping": "run", "sprinting": "run", "chasing": "run", "fleeing": "run", "charging": "run", "dashing": "run", "jogging": "run", "sitting": "sit", "sit": "sit", "seated": "sit", "crouching": "sit", "begging": "sit", "lying": "lie", "lie": "lie", "resting": "lie", "lounging": "lie", "laying": "lie", "sunbathing": "lie", "basking": "lie", "sleeping": "sleep", "sleep": "sleep", "napping": "sleep", "asleep": "sleep", "curled": "sleep", "dozing": "sleep", "jumping": "jump", "jump": "jump", "leaping": "jump", "hopping": "jump", "bouncing": "jump", "pouncing": "jump", "rearing": "rear", "rear": "rear", "upright": "upright", "hind": "upright", "howling": "howl", "howl": "howl", "roaring": "howl", "baying": "howl", "crowing": "howl", "singing_up": "howl", "grazing": "graze", "graze": "graze", "eating": "graze", "drinking": "graze", "sniffing": "graze", "foraging": "graze", "swimming": "swim", "swim": "swim", "floating": "swim", "paddling": "swim", "diving": "swim", "flying": "fly", "fly": "fly", "soaring": "fly", "hovering": "fly", "gliding": "fly", "airborne": "fly", "levitating": "fly", "perched": "perch", "perch": "perch", "perching": "perch", "hanging": "hang", "hang": "hang", "dangling": "hang", "swinging": "hang", "one_leg": "one_leg", "crawling": "crawl", "crawl": "crawl", "creeping": "crawl", "slithering": "crawl", "stalking": "crawl", "sneaking": "crawl", "riding": "ride", "ride": "ride", "coiled": "coil", "coil": "coil", "balancing": "balance", "balance": "balance", "kneeling": "kneel", "kneel": "kneel", "dancing": "dance", "dance": "dance", } def canon(name): if name is None: return None return CANON.get(name, name if name in set(CANON.values()) else None) def pose_of(inst, default=None): """canonical pose of a layout instance (or None). Order: an explicit pose3d set by interactions, then the parser's pose, then the action verb.""" if inst is None: return default for k in ("pose3d", "pose"): v = canon(getattr(inst, k, None)) if v: return v a = (getattr(inst, "attrs", None) or {}).get("action") v = canon(a) if a else None return v or default def action_of(inst): return (getattr(inst, "attrs", None) or {}).get("action") if inst is not None else None # ---------------------------------------------------------------- rigid transforms class Rigid: """world = R @ local + t (R a 3x3 rotation). Compose with @; .inv_pts maps world points back to local, so a part built in its rest frame is posed by evaluating it at inv_pts(p) (rigid motions keep SDFs exact).""" __slots__ = ("R", "t") def __init__(self, R=None, t=None): self.R = np.eye(3) if R is None else np.asarray(R, float) self.t = np.zeros(3) if t is None else np.asarray(t, float) def __matmul__(self, o): return Rigid(self.R @ o.R, self.R @ o.t + self.t) def pt(self, x): return self.R @ np.asarray(x, float) + self.t def vec(self, v): return self.R @ np.asarray(v, float) def inv_pts(self, p): return (p - self.t) @ self.R # = R^T (p - t) for row vectors def is_id(self): return np.allclose(self.R, np.eye(3)) and np.allclose(self.t, 0) def rot_axis(axis, deg): a = math.radians(deg) c, s = math.cos(a), math.sin(a) if axis == "z": # + = counter-clockwise in x-y: a +x-facing body pitches its front UP return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1.0]]) if axis == "y": # + = turns +x toward -z (toward the camera, which looks along +z from -z) return np.array([[c, 0, s], [0, 1.0, 0], [-s, 0, c]]) return np.array([[1.0, 0, 0], [0, c, -s], [0, s, c]]) # x: + rolls +y toward +z def about(pivot, R, t=(0, 0, 0)): """rotation R about `pivot`, then a translation t""" pivot = np.asarray(pivot, float) return Rigid(R, pivot - R @ pivot + np.asarray(t, float)) def posed(fn, T): """an SDF built in its rest frame, moved by rigid transform T (identity -> the same function)""" if T is None or T.is_id(): return fn return lambda p: fn(T.inv_pts(p)) def ik2(a, f, l1, l2, bend): """2-bone IK in the x-y plane (z interpolated): joint position between root a and end f with bone lengths l1, l2. bend: +1 = the joint sticks out toward +x (forward), -1 toward -x. An unreachable end is pulled in.""" a, f = np.asarray(a, float), np.asarray(f, float) d = f - a L = float(np.hypot(d[0], d[1])) if L > (l1 + l2) * .999: f = a + d * ((l1 + l2) * .999 / max(L, 1e-6)) d = f - a L = (l1 + l2) * .999 L = max(L, abs(l1 - l2) + 1e-4) x = (l1 * l1 - l2 * l2 + L * L) / (2 * L) h = math.sqrt(max(l1 * l1 - x * x, 0.0)) u = d[:2] / max(L, 1e-6) perp = np.array([-u[1], u[0]]) if perp[0] * bend < 0 or (abs(perp[0]) < 1e-6 and bend < 0): perp = -perp j = a[:2] + u * x + perp * h return np.array([j[0], j[1], (a[2] + f[2]) * .5]), f # ---------------------------------------------------------------- posed model container class Model(list): """a list of Parts that also carries the posed model's facts: aspect (width / standing height), height (posed height in standing units; 1.0 standing, < 1 lying, > 1 rearing), anchors {name: (x, y, z)} in the model frame (base y=0, standing height 1, centred), facing (+x for side-view animals).""" aspect = None height = 1.0 anchors = None fit_width = False # True: the 3D placement shrinks the model to the layout box width (its pose made it wider) @classmethod def of(cls, parts, aspect=None, height=1.0, anchors=None): m = cls(parts) m.aspect, m.height, m.anchors = aspect, height, dict(anchors or {}) return m def measure(parts, lo=(-4., -4., -4.), hi=(4., 4., 4.)): """bounding box of the union of parts (coarse grid then a fine one)""" def dist(q): d = None for pt in parts: e = pt.fn(q) d = e if d is None else np.minimum(d, e) return d lo, hi = np.array(lo, float), np.array(hi, float) for n in (26, 44): ax = [np.linspace(lo[i], hi[i], n) for i in range(3)] g = np.stack(np.meshgrid(*ax, indexing="ij"), -1).reshape(-1, 3) step = (hi - lo) / (n - 1) inside = dist(g) < step.max() * .5 if not inside.any(): return np.array([-.5, 0, -.3]), np.array([.5, 1, .3]) pts = g[inside] lo, hi = pts.min(0) - step, pts.max(0) + step return lo + step * .5, hi - step * .5 def finish_posed(parts, href, anchors=None, floor=None, box=None, max_h=1.35, center_x=None): """normalise a posed raw model: uniform scale 1/href (the STANDING height, so poses keep the animal's size), lowest point (or `floor`, e.g. a water line) on y=0, centred in x and z. A pose taller than max_h x standing is shrunk to max_h. Returns a Model with aspect / height / anchors in the contract frame.""" lo, hi = box if box is not None else measure(parts) y0 = lo[1] if floor is None else floor h = max(hi[1] - y0, 1e-3) s = 1.0 / max(href, 1e-3) if h * s > max_h: s = max_h / h cx = (lo[0] + hi[0]) * .5 if center_x is None else center_x sh = np.array([cx, y0, (lo[2] + hi[2]) * .5]) for pt in parts: pt.fn = (lambda f: (lambda p: f(p / s + sh) * s))(pt.fn) anc = {k: tuple((np.asarray(v, float) - sh) * s) for k, v in (anchors or {}).items()} return Model.of(parts, aspect=(hi[0] - lo[0]) * s, height=h * s, anchors=anc) def eyelids(c, r, n, col, both=True, mirror=None): """closed eyes: a lid of skin / fur colour over the eye ball plus a dark lash line across it (sleeping).""" from .models import Part from . import sdf as S c, n = np.asarray(c, float), np.asarray(n, float) n = n / np.linalg.norm(n) side = np.cross(np.array([0, 1.0, 0]), n) if np.linalg.norm(side) < 1e-6: side = np.array([1.0, 0, 0]) side /= np.linalg.norm(side) M = mirror if (both and mirror is not None) else (lambda p: p) lc = c + n * r * .55 - np.array([0, r * .12, 0]) a, b = lc - side * r * .75, lc + side * r * .75 lid = Part(lambda p: S.sphere(M(p), c, r * 1.03), col, spec=.2, rough=.6) lash = Part(lambda p: S.capsule(M(p), a, b, r * .16), (30, 24, 22), spec=.3, rough=.5) return [lid, lash] def pitch_parts(parts, deg): """whole-body pitch (deg, + = nose up) of a raw model about its origin, before the family's fit() measures it (rigid-bodied families: a jumping fish / frog arcs nose-up, a grazing fish noses down)""" if not deg: return parts T = Rigid(rot_axis("z", deg)) for pt in parts: pt.fn = posed(pt.fn, T) return parts