"""Pip the dragon (for a friend): mesh pieces for a walker-style linkset. Run headless: "C:/Program Files/Blender Foundation/Blender 5.2/blender.exe" -b -P gen_dragon.py -- [--out DIR] [--render] [--probe] [--tris SCALE --suffix _lite] [--quick] Same pipeline as ../walker/mesh/walker_mesh.py: every shape is a signed distance field (ellipsoids, round cones, extruded 2D outlines, smooth-unioned), meshed with surface nets, decimated with a mirror symmetry, snapped back onto the field, normals from the field gradient. Each colour is its own closed shell poking out of the one under it (clean colour borders without UV work); faces of a shell that are buried inside another shell are culled. Every piece is exported centred on its bbox (SL puts the prim origin there), Z-up / X-forward (`export_yup=False`). Frames. The design frame has the ground at z 0, x forward, y left, the dragon centred on x=y=0. The root (body) frame is the design frame shifted so the body's bbox centre is the origin. A child at rotation R (in the root frame) whose joint is at J (root frame) goes at pos = J - R * pivot (LSL: J - pivot * R), pivot = the piece's joint relative to its bbox centre in its own frame. At R = identity: head, arm_l/r, wing_l/r: rest pose as modelled (wings spread flat in the local y-z plane, see README). thigh, shin: the bone hangs straight down local -z from the pivot (hip, knee). foot: flat on the ground, toes along +x, pivot at the ankle. tail1..4: the segment points straight back along local -x from its pivot. Writes .glb for all 16 pieces, rig.json (the joint table, pivots, rest rotations, sizes), rig.lsl (the same as LSL globals named like pip.lsl's), and with --render PNGs of the assembled dragon placed by the same table (--quick: Workbench, for iterating). With --suffix the files get it too (rig_lite.json...). --probe prints the numbers only. Claude Opus 5.5 (subagent for Tessel), 2026-10-12.""" import json import math import os import sys import bmesh import bpy import numpy as np from mathutils import Euler, Matrix, Quaternion, Vector argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else [] OUT = argv[argv.index("--out") + 1] if "--out" in argv else os.path.dirname(os.path.abspath(__file__)) RENDER = "--render" in argv PROBE = "--probe" in argv QUICK = "--quick" in argv # workbench test renders TRIS = float(argv[argv.index("--tris") + 1]) if "--tris" in argv else 1.0 SUFFIX = argv[argv.index("--suffix") + 1] if "--suffix" in argv else "" CARD = "--card" in argv # 10-16: Pip on a transparent background for a friend's holo card idea SKIN, BELLY, MEMBRANE, GOLD, NAVY = "#4FA89A", "#F2E6C8", "#F08A70", "#D9A441", "#2E3D6B" EYE, GLINT, MOUTH, BLUSH = "#1E2430", "#FFFFFF", "#2A2F3A", "#F4AFA3" # ---------------------------------------------------------------- distance fields (P: (N, 3) array) def ell(P, c, r, R=None): """Ellipsoid (iq's bound). R: optional 3x3 whose columns are the ellipsoid's axes.""" q = P - np.asarray(c, float) if R is not None: q = q @ np.asarray(R, float) q = q / r k0 = np.linalg.norm(q, axis=1) k1 = np.linalg.norm(q / r, axis=1) return k0 * (k0 - 1.0) / np.maximum(k1, 1e-9) def sphere(P, c, r): return np.linalg.norm(P - np.asarray(c, float), axis=1) - r def rcone(P, a, b, r1, r2): """Round cone from sphere (a, r1) to sphere (b, r2).""" a = np.asarray(a, float) ba = np.asarray(b, float) - a l2 = ba @ ba rr = r1 - r2 a2 = l2 - rr * rr il2 = 1.0 / l2 pa = P - a y = pa @ ba z = y - l2 w = pa * l2 - np.outer(y, ba) x2 = np.einsum("ij,ij->i", w, w) y2 = y * y * l2 z2 = z * z * l2 k = np.sign(rr) * rr * rr * x2 d3 = (np.sqrt(np.maximum(x2 * a2 * il2, 0)) + y * rr) * il2 - r1 d1 = np.sqrt(x2 + z2) * il2 - r2 d2 = np.sqrt(x2 + y2) * il2 - r1 return np.where(np.sign(z) * a2 * z2 > k, d1, np.where(np.sign(y) * a2 * y2 < k, d2, d3)) def smin(a, b, k): h = np.clip(0.5 + 0.5 * (b - a) / k, 0, 1) return b * (1 - h) + a * h - k * h * (1 - h) def smax(a, b, k): return -smin(-a, -b, k) def mirror(f): """Apply a +y shape on both sides.""" def g(P): Q = P.copy() Q[:, 1] = np.abs(Q[:, 1]) return f(Q) return g def poly2d(Q, pts): """Signed distance to a closed 2D polygon (iq). Q (N, 2), pts (M, 2).""" pts = np.asarray(pts, float) d = np.full(len(Q), np.inf) s = np.ones(len(Q)) for i in range(len(pts)): a, b = pts[i], pts[i - 1] e = b - a w = Q - a t = np.clip((w @ e) / (e @ e), 0, 1) dd = w - np.outer(t, e) d = np.minimum(d, np.einsum("ij,ij->i", dd, dd)) c1 = Q[:, 1] >= a[1] c2 = Q[:, 1] < b[1] c3 = e[0] * w[:, 1] > e[1] * w[:, 0] flip = (c1 & c2 & c3) | (~c1 & ~c2 & ~c3) s[flip] *= -1 return s * np.sqrt(d) def extrude(d2, h, half, rnd): """Slab of half-thickness `half` over a 2D distance d2, edges rounded by rnd (<= half).""" w = np.stack([d2 + rnd, np.abs(h) - half + rnd], 1) return np.minimum(np.maximum(w[:, 0], w[:, 1]), 0) + np.linalg.norm(np.maximum(w, 0), axis=1) - rnd def frame(n, up): """Columns: (n, side, up') orthonormal, n first.""" n = np.asarray(n, float) / np.linalg.norm(n) s = np.cross(np.asarray(up, float), n) s /= np.linalg.norm(s) return np.stack([n, s, np.cross(n, s)], 1) def norm(v): v = np.asarray(v, float) return v / np.linalg.norm(v) def ray_hit(f, o, d, tmax=1.0): """First point where f goes from + to - along o + t d.""" o, d = np.asarray(o, float), norm(d) t = np.linspace(0, tmax, 4001) v = f(o + np.outer(t, d)) i = np.argmax(v < 0) if v[0] > 0 else np.argmax(v > 0) return o + t[i] * d def grad(f, P, e=1e-4): g = np.empty_like(P) for i in range(3): o = np.zeros(3) o[i] = e g[:, i] = (f(P + o) - f(P - o)) / (2 * e) return g def surf_normal(f, p): return norm(grad(f, np.atleast_2d(np.asarray(p, float)))[0]) # ---------------------------------------------------------------- the design (metres, design frame unless noted) HIP = np.array([0.0, 0.20, 0.62]) # left; right = y negated ANKLE_REST = np.array([-0.03, 0.23, 0.14]) L_THIGH, L_SHIN, ANKLE_H = 0.30, 0.30, 0.14 SHOULDER = np.array([0.07, 0.25, 1.04]) NECK = np.array([0.03, 0.0, 1.25]) WING_ROOT = np.array([-0.17, 0.13, 1.13]) TAIL_ROOT = np.array([-0.26, 0.0, 0.64]) TAIL = [ # length, r at pivot, r at end (next segment starts 4 mm thinner so its ball hides in this one) (0.30, 0.150, 0.120), (0.27, 0.116, 0.095), (0.24, 0.091, 0.070), (0.20, 0.066, 0.050), ] TAIL_REST_PITCH = [-28.0, -16.0, -4.0, 14.0] # degrees about +y, absolute in the root frame (+ lifts the tip) # body --------------------------------------------------------------------------------------------- def body_skin(P): d = ell(P, (0.0, 0, 0.84), (0.31, 0.33, 0.36)) # pear: wide bottom d = smin(d, ell(P, (0.0, 0, 1.08), (0.22, 0.245, 0.19)), 0.10) # chest d = smin(d, ell(P, (NECK[0], 0, 1.235), (0.135, 0.135, 0.12)), 0.07) # neck stub (inside the head above ~1.3) d = smin(d, mirror(lambda Q: ell(Q, (0.0, 0.18, 0.64), (0.17, 0.15, 0.16)))(P), 0.07) # haunches d = smin(d, ell(P, (-0.2, 0, 0.66), (0.16, 0.13, 0.14)), 0.07) # tail base return d BELLY_LINES = (0.64, 0.75, 0.86, 0.97) def body_belly(P): region = ell(np.stack([0 * P[:, 0], P[:, 1], P[:, 2]], 1), (0, 0, 0.83), (1.0, 0.215, 0.33)) region = smax(region, 0.04 - P[:, 0], 0.03) d = smax(body_skin(P) - 0.014, region, 0.01) g = np.zeros(len(P)) for z0 in BELLY_LINES: g = np.maximum(g, np.clip(1 - ((P[:, 2] - z0) / 0.011) ** 2, 0, 1)) return d + 0.007 * g def _front_x(f, y, z): return ray_hit(f, (0.6, y, z), (-1, 0, 0))[0] KNOT = None def body_scarf(P): band = np.abs(P[:, 2] - 1.17) - 0.036 Q = P * (0, 1, 1) tails = mirror(lambda R: rcone(R, (0, 0.02, 1.15), (0, 0.095, 1.0), 0.026, 0.042))(Q) region = np.minimum(band, smax(tails, 0.05 - P[:, 0], 0.01)) d = smax(body_skin(P) - 0.02, region, 0.006) d = smin(d, ell(P, (KNOT, 0, 1.155), (0.05, 0.068, 0.052)), 0.015) # knot return d # head --------------------------------------------------------------------------------------------- def head_skin(P): d = ell(P, (0.02, 0, 1.6), (0.28, 0.32, 0.275)) # cranium d = smin(d, ell(P, (0.235, 0, 1.45), (0.16, 0.2, 0.115)), 0.07) # muzzle d = smin(d, mirror(lambda Q: ell(Q, (0.13, 0.17, 1.46), (0.12, 0.11, 0.10)))(P), 0.06) # cheeks d = smin(d, ell(P, (NECK[0], 0, 1.36), (0.17, 0.18, 0.09)), 0.07) # underside over the neck return d def head_cream(P): """Cream chin: an ellipsoid bulging ~1 cm out of the muzzle's underside.""" return ell(P, (0.18, 0, 1.385), (0.21, 0.17, 0.07)) def head_face(P): return np.minimum(head_skin(P), head_cream(P)) HEAD_C = np.array([0.03, 0.0, 1.55]) EYE_C = None # set below (surface point), left eye EYE_R = None EYE_RAD = np.array([0.05, 0.084, 0.11]) # depth, width, height def head_eyes(P): return mirror(lambda Q: ell(Q, EYE_C, EYE_RAD, EYE_R))(P) GLINTS = [] def head_glints(P): def f(Q): d = np.full(len(Q), np.inf) for c, r in GLINTS: d = np.minimum(d, sphere(Q, c, r)) return d return mirror(f)(P) MOUTH_PTS = None NOSTRIL = None def head_mouth(P): d = np.full(len(P), np.inf) for a, b in zip(MOUTH_PTS[:-1], MOUTH_PTS[1:]): d = np.minimum(d, rcone(P, a, b, 0.0085, 0.0085)) Q = P.copy() Q[:, 1] = np.abs(Q[:, 1]) d = np.minimum(d, ell(Q, NOSTRIL[0], (0.014, 0.018, 0.011), NOSTRIL[1])) return d HORN_A, HORN_B, HORN_C = (-0.02, 0.15, 1.76), (-0.09, 0.19, 1.90), (-0.17, 0.205, 1.975) def head_horns(P): return mirror(lambda Q: smin(rcone(Q, HORN_A, HORN_B, 0.058, 0.04), rcone(Q, HORN_B, HORN_C, 0.04, 0.022), 0.02))(P) FIN = None # (base point, frame) def head_fins(P): def f(Q): base, R = FIN u, v = R[:, 1], R[:, 2] # in-plane axes (outward, up); R[:, 0] is the fin normal d = np.full(len(Q), np.inf) for ang, ln in ((-48, 0.085), (0, 0.11), (48, 0.095)): a = math.radians(ang) dr = math.cos(a) * u + math.sin(a) * v ax = np.stack([dr, np.cross(R[:, 0], dr), R[:, 0]], 1) e = ell(Q, base + dr * ln * 0.75, (ln, 0.036, 0.016), ax) d = e if ang == -48 else smin(d, e, 0.018) return d return mirror(f)(P) BLUSH_C = None def head_blush(P): return mirror(lambda Q: ell(Q, BLUSH_C[0], (0.018, 0.058, 0.036), BLUSH_C[1]))(P) # arm (left, design frame) ------------------------------------------------------------------------ ELBOW = np.array([0.12, 0.33, 0.92]) WRIST = np.array([0.25, 0.27, 0.895]) HAND = np.array([0.30, 0.215, 0.895]) FINGERS = [] def arm_skin(P): d = rcone(P, SHOULDER, ELBOW, 0.088, 0.072) d = smin(d, rcone(P, ELBOW, WRIST, 0.072, 0.062), 0.03) d = smin(d, ell(P, HAND, (0.072, 0.066, 0.07)), 0.03) for a, b, _ in FINGERS: d = smin(d, rcone(P, a, b, 0.03, 0.024), 0.015) return d def arm_claws(P): d = np.full(len(P), np.inf) for _, b, t in FINGERS: d = np.minimum(d, rcone(P, b, t, 0.016, 0.004)) return d def _fingers(): base = norm((0.5, -0.4, -0.75)) side = norm(np.cross(base, (0, 0, 1))) out = [] for k in (-1, 0, 1): dr = norm(base + 0.55 * k * side) a = HAND + dr * 0.035 b = HAND + dr * 0.085 out.append((a, b, b + dr * 0.028)) return out # wing (local: pivot at the origin, membrane in the y-z plane, extends +y; symmetric in x) --------- W_ROOT0 = np.array([0.0, 0.0, 0.0]) W_WRIST = np.array([0.0, 0.27, 0.24]) W_TIPS = [np.array([0.0, 0.60, 0.40]), np.array([0.0, 0.68, 0.10]), np.array([0.0, 0.50, -0.20])] W_BACK = np.array([0.0, 0.03, -0.13]) W_THUMB = (W_WRIST + np.array([0, 0.012, 0.03]), W_WRIST + np.array([0, 0.035, 0.085])) def _scallop(a, b, depth, n=10): a, b = np.asarray(a, float), np.asarray(b, float) toward = W_WRIST[1:] - (a + b) / 2 toward /= np.linalg.norm(toward) return [a + (b - a) * t + toward * depth * math.sin(math.pi * t) for t in np.linspace(0, 1, n + 1)[1:-1]] def _wing_outline(): pts = [W_ROOT0[1:] + (0.0, 0.05), W_WRIST[1:], W_TIPS[0][1:]] pts += _scallop(W_TIPS[0][1:], W_TIPS[1][1:], 0.075) pts += [W_TIPS[1][1:]] pts += _scallop(W_TIPS[1][1:], W_TIPS[2][1:], 0.085) pts += [W_TIPS[2][1:]] pts += _scallop(W_TIPS[2][1:], W_BACK[1:], 0.09) pts += [W_BACK[1:]] return np.array(pts) W_OUTLINE = _wing_outline() def wing_membrane(P): return extrude(poly2d(P[:, 1:], W_OUTLINE), P[:, 0], 0.0065, 0.006) def wing_bones(P): d = rcone(P, W_ROOT0 + (0, -0.03, 0), W_WRIST, 0.046, 0.034) d = smin(d, sphere(P, W_WRIST, 0.04), 0.02) for tip, r in zip(W_TIPS, (0.027, 0.027, 0.025)): d = smin(d, rcone(P, W_WRIST, tip, r, 0.014), 0.02) return d def wing_claw(P): return rcone(P, W_THUMB[0], W_THUMB[1], 0.018, 0.005) # tail segments (local: pivot at the origin, segment along -x; tail4 carries the spade) ------------- def tail_skin(i): L, r1, r2 = TAIL[i] def f(P): return rcone(P, (0, 0, 0), (-L, 0, 0), r1, r2) return f def tail_cream(i): L, r1, r2 = TAIL[i] def f(P): return rcone(P, (0, 0, -0.36 * r1), (-L, 0, -0.36 * r2), 0.72 * r1, 0.72 * r2) return f def spade(P): L = TAIL[3][0] Q = P[:, :2] lobes = np.minimum(np.linalg.norm(Q - (-L - 0.055, 0.06), axis=1) - 0.06, np.linalg.norm(Q - (-L - 0.055, -0.06), axis=1) - 0.06) tri = poly2d(Q, [(-L - 0.03, 0.10), (-L - 0.03, -0.10), (-L - 0.20, 0.0)]) d2 = smin(lobes, tri - 0.012, 0.03) return extrude(d2, P[:, 2], 0.022, 0.018) def tail4_skin(P): return smin(tail_skin(3)(P), sphere(P, (-TAIL[3][0] - 0.02, 0, 0), 0.04), 0.02) # legs (local; thigh pivot = hip, shin pivot = knee, both hang along -z; foot pivot = ankle) --------- def thigh_skin(P): d = rcone(P, (0, 0, 0), (0, 0, -L_THIGH), 0.15, 0.11) return smin(d, ell(P, (0.0, 0, -0.09), (0.16, 0.145, 0.16)), 0.05) def shin_skin(P): return smin(rcone(P, (0, 0, 0), (0, 0, -L_SHIN), 0.106, 0.078), ell(P, (-0.02, 0, -0.09), (0.1, 0.095, 0.11)), 0.04) # a little calf TOES = [((0.215, 0.0, -0.085), 0.0), ((0.19, 0.08, -0.09), 0.38), ((0.19, -0.08, -0.09), -0.38)] def foot_skin(P): d = ell(P, (0.06, 0, -0.07), (0.17, 0.125, 0.09)) d = smin(d, sphere(P, (0, 0, 0), 0.093), 0.06) for c, a in TOES: R = np.array([[math.cos(a), -math.sin(a), 0], [math.sin(a), math.cos(a), 0], [0, 0, 1]]) d = smin(d, ell(P, c, (0.07, 0.052, 0.058), R), 0.03) return smax(d, -(P[:, 2] + ANKLE_H), 0.015) def foot_claws(P): d = np.full(len(P), np.inf) for c, a in TOES: dr = np.array([math.cos(a), math.sin(a), 0]) b = np.asarray(c) + dr * 0.055 + (0, 0, -0.005) d = np.minimum(d, rcone(P, b, b + dr * 0.045 + (0, 0, -0.02), 0.022, 0.006)) return d # ---------------------------------------------------------------- derived placement (computed from the fields) def _setup(): global KNOT, EYE_C, EYE_R, GLINTS, MOUTH_PTS, NOSTRIL, FIN, BLUSH_C, FINGERS KNOT = _front_x(body_skin, 0.0, 1.16) + 0.012 # eyes: on the face, oriented along the surface normal, poking out ~1.4 cm sp = ray_hit(head_skin, HEAD_C + (0, 0.128, 0.075), (1, 0.12, 0), 0.6) sp = ray_hit(head_skin, sp + (0.2, 0, 0), (-1, 0, 0), 0.4) n = surf_normal(head_skin, sp) n = norm(n * (1, 0.75, 0.3)) # face them mostly forward EYE_R = frame(n, (0, 0, 1)) EYE_C = sp - n * (EYE_RAD[0] - 0.016) # glints on the eye surface: a big one upper-outer, a small one lower-inner GLINTS = [] eye_f = lambda Q: ell(Q, EYE_C, EYE_RAD, EYE_R) for side, up, r in ((0.35, 0.42, 0.024), (-0.25, -0.35, 0.012)): loc = EYE_C + EYE_R[:, 1] * side * EYE_RAD[1] + EYE_R[:, 2] * up * EYE_RAD[2] p = ray_hit(eye_f, loc + n * 0.2, -n, 0.3) GLINTS.append((p - n * (r * 0.45), r)) # smile: a shallow U on the front of the muzzle, under the nose, projected onto the surface pts = [] for t in np.linspace(-1, 1, 11): y = 0.07 * t z = 1.432 + 0.012 * t * t + 0.016 * t ** 6 p = ray_hit(head_face, (0.6, y, z), (-1, 0, 0)) pts.append(p - surf_normal(head_face, p) * 0.003) MOUTH_PTS = pts p = ray_hit(head_skin, (0.6, 0.048, 1.505), (-1, 0, 0)) nn = surf_normal(head_skin, p) NOSTRIL = (p - nn * 0.005, frame(nn, (0, 0, 1))) # ear-fins on the sides behind the eyes, fanning out and up, facing forward p = ray_hit(head_skin, HEAD_C + (-0.06, 0, 0.1), (-0.15, 1, 0.1), 0.6) # frame columns (normal ~forward, side = outward leaning back, up) FIN = (p - norm((-0.15, 1, 0.1)) * 0.02, frame(norm((1, 0.3, 0.05)), (0, 0, 1))) # blush on the cheeks, below and outside the eyes p = ray_hit(head_skin, HEAD_C + (0, 0, -0.08), (0.75, 0.75, -0.12), 0.6) nn = surf_normal(head_skin, p) BLUSH_C = (p - nn * (0.018 - 0.005), frame(nn, (0, 0, 1))) FINGERS = _fingers() _setup() # ---------------------------------------------------------------- meshing def surface_nets(f, lo, hi, h): xs, ys, zs = (np.arange(lo[i] - 2 * h, hi[i] + 2 * h, h) for i in range(3)) G = np.stack(np.meshgrid(xs, ys, zs, indexing="ij"), -1) F = f(G.reshape(-1, 3)).reshape(G.shape[:3]) for ax in range(3): for side in (0, -1): assert F.take(side, axis=ax).min() > 0, f"shape reaches the grid edge: axis {ax} {'lo' if side == 0 else 'hi'}" n = np.array(F.shape) cdims = n - 1 cid = lambda i, j, k: (i * cdims[1] + j) * cdims[2] + k acc = np.zeros((cdims.prod(), 3)) cnt = np.zeros(cdims.prod()) quads = [] for ax in range(3): s0 = [slice(None)] * 3 s1 = [slice(None)] * 3 s0[ax] = slice(0, -1) s1[ax] = slice(1, None) f0, f1 = F[tuple(s0)], F[tuple(s1)] cross = (f0 < 0) != (f1 < 0) idx = np.argwhere(cross) a, b = f0[cross], f1[cross] t = a / (a - b) pts = np.stack([xs[0] + idx[:, 0] * h, ys[0] + idx[:, 1] * h, zs[0] + idx[:, 2] * h], 1) pts[:, ax] += t * h u, v = [x for x in range(3) if x != ax] cells = [] for du, dv in ((-1, -1), (0, -1), (0, 0), (-1, 0)): c = idx.copy() c[:, u] += du c[:, v] += dv cells.append(c) for c in cells: ok = np.all((c >= 0) & (c < cdims), axis=1) ci = cid(c[ok, 0], c[ok, 1], c[ok, 2]) np.add.at(acc, ci, pts[ok]) np.add.at(cnt, ci, 1) q = np.stack([cid(c[:, 0], c[:, 1], c[:, 2]) for c in cells], 1) flip = (a < 0) if ax != 1 else (a >= 0) q[~flip] = q[~flip][:, ::-1] quads.append(q) quads = np.concatenate(quads) used = np.nonzero(cnt)[0] remap = -np.ones(cdims.prod(), int) remap[used] = np.arange(len(used)) V = acc[used] / cnt[used, None] return V, remap[quads] def project(f, V, iters=4): for _ in range(iters): g = grad(f, V) V = V - (f(V) / np.maximum(np.einsum("ij,ij->i", g, g), 1e-9))[:, None] * g return V def decimated(f, lo, hi, h, tris, name, axis=1): """Surface nets, decimate, keep the + half along `axis` and mirror it (None = no mirror), snap onto the field.""" V, Q = surface_nets(f, lo, hi, h) me = bpy.data.meshes.new(name + "_raw") me.from_pydata(V.tolist(), [], Q.tolist()) ob = bpy.data.objects.new(name + "_raw", me) bpy.context.scene.collection.objects.link(ob) m = ob.modifiers.new("dec", "DECIMATE") m.ratio = min(1.0, tris / (2 * len(Q))) m.use_collapse_triangulate = True bm = bmesh.new() bm.from_object(ob, bpy.context.evaluated_depsgraph_get()) bpy.data.objects.remove(ob) bpy.data.meshes.remove(me) if axis is not None: no = [0, 0, 0] no[axis] = 1 bmesh.ops.bisect_plane(bm, geom=bm.verts[:] + bm.edges[:] + bm.faces[:], plane_co=(0, 0, 0), plane_no=no, clear_inner=True) bmesh.ops.triangulate(bm, faces=bm.faces[:]) V = np.array([v.co[:] for v in bm.verts]) bm.verts.index_update() F = np.array([[v.index for v in fc.verts] for fc in bm.faces]) bm.free() area2 = np.linalg.norm(np.cross(V[F[:, 1]] - V[F[:, 0]], V[F[:, 2]] - V[F[:, 0]]), axis=1) F = F[area2 > 1e-9] if axis is not None: assert V[:, axis].min() > -1e-6 rim = np.nonzero(np.abs(V[:, axis]) < 1e-6)[0] V[rim, axis] = 0 n = len(V) other = np.arange(n) + n other[rim] = rim sgn = np.ones(3) sgn[axis] = -1 V = np.concatenate([V, V * sgn]) F = np.concatenate([F, other[F[:, ::-1]]]) V = project(f, V) area2 = np.linalg.norm(np.cross(V[F[:, 1]] - V[F[:, 0]], V[F[:, 2]] - V[F[:, 0]]), axis=1) F = F[area2 > 1e-8] used = np.unique(F) remap = -np.ones(len(V), int) remap[used] = np.arange(len(used)) return V[used], remap[F] def srgb(h): c = [int(h[i:i + 2], 16) / 255 for i in (1, 3, 5)] return tuple(v / 12.92 if v <= 0.04045 else ((v + 0.055) / 1.055) ** 2.4 for v in c) def material(name, hexcol, rough=0.6, metal=0.0, emit=0.0): m = bpy.data.materials.get(name) or bpy.data.materials.new(name) m.use_nodes = True b = m.node_tree.nodes["Principled BSDF"] b.inputs["Base Color"].default_value = (*srgb(hexcol), 1) b.inputs["Roughness"].default_value = rough b.inputs["Metallic"].default_value = metal if emit: b.inputs["Emission Color"].default_value = (*srgb(hexcol), 1) b.inputs["Emission Strength"].default_value = emit m.diffuse_color = (*srgb(hexcol), 1) # workbench return m MATS = {} def mat(name, hexcol, **kw): if name not in MATS: MATS[name] = material(name, hexcol, **kw) return MATS[name] class Piece: """A mesh in its own local frame (before bbox centring). parts: [(V, F, sdf, material)].""" def __init__(self, name, parts, pivot, info): self.name, self.info = name, info Vs, Fs, Ns, Ms, self.mats, off = [], [], [], [], [], 0 fields = [p[2] for p in parts] for i, (V, F, f, m) in enumerate(parts): # cull faces buried in another shell of this piece others = [g for j, g in enumerate(fields) if j != i] if others: inside = np.min([g(V) for g in others], axis=0) < -0.0025 keep = ~inside[F].all(1) F = F[keep] used = np.unique(F) remap = -np.ones(len(V), int) remap[used] = np.arange(len(used)) V, F = V[used], remap[F] g = grad(f, V) Ns.append(g / np.linalg.norm(g, axis=1, keepdims=True)) Vs.append(V) Fs.append(F + off) Ms += [i] * len(F) self.mats.append(m) off += len(V) self.V, self.F, self.N, self.M = np.concatenate(Vs), np.concatenate(Fs), np.concatenate(Ns), np.array(Ms) self.centre = (self.V.min(0) + self.V.max(0)) / 2 self.pivot_local = np.asarray(pivot, float) # joint in the piece's local (pre-centring) frame self.ob = None def mirrored(self, name, info): p = Piece.__new__(Piece) p.name, p.info, p.mats = name, info, self.mats s = np.array([1, -1, 1]) p.V, p.N, p.F, p.M = self.V * s, self.N * s, self.F[:, ::-1].copy(), self.M p.centre = self.centre * s p.pivot_local = self.pivot_local * s p.ob = None return p @property def size(self): return self.V.max(0) - self.V.min(0) @property def pivot(self): """Joint relative to the bbox centre, in the piece frame: what the script rotates about.""" return self.pivot_local - self.centre def object(self): if self.ob: return self.ob V = self.V - self.centre F = self.F me = bpy.data.meshes.new(self.name) me.from_pydata(V.tolist(), [], F.tolist()) for m in self.mats: me.materials.append(m) me.polygons.foreach_set("material_index", self.M.tolist()) me.polygons.foreach_set("use_smooth", [True] * len(F)) uv = me.uv_layers.new(name="UVMap") fn = np.cross(V[F[:, 1]] - V[F[:, 0]], V[F[:, 2]] - V[F[:, 0]]) dom = np.abs(fn).argmax(1) lv = np.empty(len(me.loops), int) me.loops.foreach_get("vertex_index", lv) keep = np.array([[1, 2], [0, 2], [0, 1]])[np.repeat(dom, 3)] uvs = np.take_along_axis(V[lv], keep, 1) + 0.5 uv.data.foreach_set("uv", uvs.ravel()) me.normals_split_custom_set_from_vertices(self.N.tolist()) me.update() self.ob = bpy.data.objects.new(self.name, me) bpy.context.scene.collection.objects.link(self.ob) self.ob.hide_render = True return self.ob def export(ob, path): for o in bpy.context.scene.objects: o.select_set(o == ob) bpy.context.view_layer.objects.active = ob bpy.ops.export_scene.gltf(filepath=path, export_format="GLB", use_selection=True, export_yup=False, export_apply=True) def glb_bounds(path): """POSITION accessor min/max straight from the .glb, to check what SL will get.""" with open(path, "rb") as fh: data = fh.read() n = int.from_bytes(data[12:16], "little") js = json.loads(data[20:20 + n]) lo, hi = np.full(3, np.inf), np.full(3, -np.inf) for m in js["meshes"]: for pr in m["primitives"]: a = js["accessors"][pr["attributes"]["POSITION"]] lo, hi = np.minimum(lo, a["min"]), np.maximum(hi, a["max"]) nodes = [nd for nd in js["nodes"] if "rotation" in nd or "translation" in nd or "scale" in nd] return lo, hi, nodes # ---------------------------------------------------------------- build for o in list(bpy.data.objects): bpy.data.objects.remove(o) M_SKIN = mat("0_skin", SKIN, rough=0.55) T = TRIS def build_parts(specs, axis=1): """specs: [(sdf, lo, hi, h, tris, material)] -> parts with meshes.""" out = [] for f, lo, hi, h, n, m in specs: V, F = decimated(f, lo, hi, h, n * T, m.name, axis) out.append((V, F, f, m)) return out pieces = {} # body: design frame body = Piece("body", build_parts([ (body_skin, (-0.45, -0.42, 0.42), (0.36, 0.42, 1.4), 0.011, 1150, M_SKIN), (body_belly, (0.02, -0.28, 0.45), (0.38, 0.28, 1.2), 0.0065, 380, mat("1_belly", BELLY)), (body_scarf, (-0.3, -0.3, 0.9), (0.3, 0.3, 1.3), 0.0055, 340, mat("2_scarf", NAVY, rough=0.7)), ]), np.zeros(3), "root") C_B = body.centre.copy() body.pivot_local = C_B.copy() # the root's 'joint' is its own centre pieces["body"] = body # design -> root frame: subtract C_B head = Piece("head", build_parts([ (head_skin, (-0.3, -0.38, 1.22), (0.44, 0.38, 1.9), 0.0095, 960, M_SKIN), (head_cream, (-0.02, -0.2, 1.3), (0.42, 0.2, 1.5), 0.006, 200, mat("1_belly", BELLY)), (head_horns, (-0.25, -0.28, 1.68), (0.06, 0.28, 2.03), 0.006, 110, mat("2_horn", GOLD, rough=0.35, metal=0.3)), (head_eyes, (0.15, -0.26, 1.48), (0.36, 0.26, 1.78), 0.0045, 150, mat("3_eye", EYE, rough=0.25)), (head_glints, (0.2, -0.25, 1.5), (0.36, 0.25, 1.76), 0.003, 48, mat("4_glint", GLINT, rough=0.3)), (head_mouth, (0.3, -0.12, 1.36), (0.46, 0.12, 1.54), 0.0028, 90, mat("5_mouth", MOUTH, rough=0.5)), (head_fins, (-0.25, -0.55, 1.45), (0.12, 0.55, 1.9), 0.005, 150, mat("6_fin", MEMBRANE)), (head_blush, (0.15, -0.36, 1.32), (0.4, 0.36, 1.56), 0.0025, 80, mat("7_blush", BLUSH)), ]), NECK, "rest pose as modelled; head yaw/pitch about the neck") pieces["head"] = head arm_l = Piece("arm_l", build_parts([ (arm_skin, (-0.05, 0.1, 0.7), (0.45, 0.45, 1.16), 0.0065, 330, M_SKIN), (arm_claws, (0.25, 0.08, 0.68), (0.45, 0.35, 0.86), 0.003, 40, mat("1_claw", GOLD, rough=0.35, metal=0.3)), ], axis=None), SHOULDER, "rest pose as modelled (hands near the chest)") pieces["arm_l"] = arm_l pieces["arm_r"] = arm_l.mirrored("arm_r", arm_l.info) wing_l = Piece("wing_l", build_parts([ (wing_bones, (-0.06, -0.08, -0.26), (0.06, 0.73, 0.46), 0.005, 270, M_SKIN), (wing_membrane, (-0.03, -0.03, -0.28), (0.03, 0.72, 0.45), 0.004, 150, mat("1_membrane", MEMBRANE)), (wing_claw, (-0.04, 0.2, 0.2), (0.04, 0.35, 0.37), 0.0025, 24, mat("2_claw", GOLD, rough=0.35, metal=0.3)), ], axis=0), W_ROOT0, "spread flat in local y-z (extends +y), symmetric in x") pieces["wing_l"] = wing_l pieces["wing_r"] = wing_l.mirrored("wing_r", wing_l.info) for i in range(4): L, r1, r2 = TAIL[i] sk = tail4_skin if i == 3 else tail_skin(i) lo = (-L - r2 - 0.04, -r1 - 0.03, -r1 - 0.03) specs = [(sk, lo, (r1 + 0.03, r1 + 0.03, r1 + 0.03), 0.0075, (250, 220, 190, 170)[i], M_SKIN), (tail_cream(i), lo, (r1 + 0.03, r1 + 0.03, r1 + 0.03), 0.0065, (110, 100, 90, 70)[i], mat("1_belly", BELLY))] if i == 3: specs.append((spade, (-L - 0.25, -0.17, -0.05), (-L + 0.01, 0.17, 0.05), 0.005, 160, mat("2_spade", MEMBRANE))) pieces[f"tail{i + 1}"] = Piece(f"tail{i + 1}", build_parts(specs), np.zeros(3), "points along local -x from its pivot") thigh = Piece("thigh_l", build_parts([ (thigh_skin, (-0.22, -0.22, -0.45), (0.22, 0.22, 0.22), 0.008, 200, M_SKIN)]), np.zeros(3), "bone along local -z from the hip pivot") shin = Piece("shin_l", build_parts([ (shin_skin, (-0.15, -0.15, -0.4), (0.15, 0.15, 0.15), 0.007, 170, M_SKIN)]), np.zeros(3), "bone along local -z from the knee pivot") foot = Piece("foot_l", build_parts([ (foot_skin, (-0.15, -0.22, -0.2), (0.36, 0.22, 0.12), 0.006, 300, M_SKIN), (foot_claws, (0.18, -0.22, -0.16), (0.36, 0.22, -0.04), 0.003, 60, mat("1_claw", GOLD, rough=0.35, metal=0.3))]), np.zeros(3), "flat on the ground at identity, toes +x, pivot at the ankle") for side, s in (("l", 1), ("r", -1)): for base, nm in ((thigh, "thigh"), (shin, "shin"), (foot, "foot")): pieces[f"{nm}_{side}"] = base if side == "l" else base.mirrored(f"{nm}_r", base.info) # (thigh/shin/foot are symmetric in y, so _r has the same shape as _l; exported anyway for a uniform table) # ---------------------------------------------------------------- joint table (root frame) and rest pose def rootp(p): return np.asarray(p, float) - C_B def qz(deg): return Quaternion((0, 0, 1), math.radians(deg)) def qy(deg): return Quaternion((0, 1, 0), math.radians(deg)) def qx(deg): return Quaternion((1, 0, 0), math.radians(deg)) def mirror_q(q): """Rotation for the y-mirrored piece on the right side.""" return Quaternion((q.w, -q.x, q.y, -q.z)) WING_SPREAD = qz(18) @ qx(22) # swept back a little, tips raised WING_FOLD = qy(-38) @ qz(84) # pointing back along the body, tip up; with WING_FOLD_SCALE WING_FOLD_SCALE = (1.0, 1.0, 0.34) # PRIM_SIZE factor on the local axes: fingers close together def two_bone(hip, target, l1, l2, pole=(1, 0, 0)): hip, target = Vector(hip), Vector(target) d = target - hip dist = min(d.length, l1 + l2 - 1e-4) dr = d.normalized() a = math.acos(max(-1, min(1, (l1 * l1 + dist * dist - l2 * l2) / (2 * l1 * dist)))) pole = Vector(pole) p = (pole - dr * pole.dot(dr)).normalized() knee = hip + dr * (l1 * math.cos(a)) + p * (l1 * math.sin(a)) end = hip + dr * dist return knee, end def pose(wings="fold", head_q=None, ankles=None, tail=None): """Returns {piece: (joint position in root frame, rotation, scale)}.""" P = {"body": (np.zeros(3), Quaternion(), (1, 1, 1))} P["head"] = (rootp(NECK), head_q or Quaternion(), (1, 1, 1)) for side, s in (("l", 1), ("r", -1)): m = np.array([1, s, 1]) P[f"arm_{side}"] = (rootp(SHOULDER * m), Quaternion(), (1, 1, 1)) q = WING_SPREAD if wings == "spread" else WING_FOLD sc = (1, 1, 1) if wings == "spread" else WING_FOLD_SCALE P[f"wing_{side}"] = (rootp(WING_ROOT * m), q if s > 0 else mirror_q(q), sc) hip = rootp(HIP * m) ank = rootp((ankles or {}).get(side, ANKLE_REST * m)) knee, end = two_bone(hip, ank, L_THIGH, L_SHIN) down = Vector((0, 0, -1)) P[f"thigh_{side}"] = (hip, down.rotation_difference(knee - Vector(hip)), (1, 1, 1)) P[f"shin_{side}"] = (np.array(knee), down.rotation_difference(end - knee), (1, 1, 1)) P[f"foot_{side}"] = (np.array(end), Quaternion(), (1, 1, 1)) j = Vector(rootp(TAIL_ROOT)) for i, a in enumerate(tail or TAIL_REST_PITCH): q = qz(a[1]) @ qy(a[0]) if isinstance(a, tuple) else qy(a) # (pitch, yaw) degrees, absolute P[f"tail{i + 1}"] = (np.array(j), q, (1, 1, 1)) j = j + q @ Vector((-TAIL[i][0], 0, 0)) return P def place(piece, J, q, sc): """Position (root frame) of the piece's bbox centre: J - R * (pivot * scale).""" return np.array(Vector(J) - q @ Vector(piece.pivot * np.asarray(sc))) REST = pose() ground_root = -C_B[2] # ---------------------------------------------------------------- report def r3(v, n=3): return tuple(round(float(x), n) for x in v) print(f"\nroot = body bbox centre at design {r3(C_B)}; ground at root z {ground_root:+.3f}") total = 0 for nm, p in pieces.items(): total += len(p.F) E = np.linalg.norm(p.V[p.F] - p.V[np.roll(p.F, 1, 1)], axis=2).max(1) worst = [(int(p.M[i]), round(float(E[i]), 3)) for i in np.argsort(-E)[:2]] print(f"{nm:8s} {len(p.F):5d} tris longest edges (part, m) {worst} size {r3(p.size)} pivot from bbox centre {r3(p.pivot)} " f"faces {[m.name for m in p.mats]}") print(f"total {total} tris") joints = { "neck": rootp(NECK), "shoulder_l": rootp(SHOULDER), "wing_root_l": rootp(WING_ROOT), "hip_l": rootp(HIP), "knee_l (rest)": REST["shin_l"][0], "ankle_l (rest)": REST["foot_l"][0], "tail_root": rootp(TAIL_ROOT), } for i in range(1, 4): joints[f"tail{i}-{i + 1} (rest)"] = REST[f"tail{i + 1}"][0] for k, v in joints.items(): print(f" joint {k:16s} {r3(v)}") # fit checks: signed distance (+ outside) of joints in the shells that should hide them fb = body_skin print("fit (sdf, + = outside):") for nm, p, f in [("hip in body", HIP, fb), ("shoulder in body", SHOULDER, fb), ("wing root in body", WING_ROOT, fb), ("tail root in body", TAIL_ROOT, fb), ("neck pivot in body", NECK, fb), ("neck stub top in head", (NECK[0], 0, 1.33), head_skin)]: print(f" {nm:24s} {f(np.atleast_2d(p))[0]:+.3f}") # thigh ball radius 0.13 at the hip: how far does it poke out of the haunch at rest swing? print(f" thigh top ball (r .15) outer point sdf {fb(np.atleast_2d(HIP + (0, 0.15, 0)))[0]:+.3f}") # neck stub visibility at the head's bottom: the head skin along the stub's rim rim = np.array([[NECK[0] + 0.12 * math.cos(a), 0.12 * math.sin(a), 1.30] for a in np.linspace(0, 2 * math.pi, 12)]) print(f" neck rim at z 1.30 inside head: max sdf {head_skin(rim).max():+.3f}") zs = np.linspace(2.2, 1.0, 2401) top_horn = zs[np.argmax(head_horns(np.stack([np.full_like(zs, HORN_C[0]), np.full_like(zs, HORN_C[1]), zs], 1)) < 0)] print(f" standing height (horn tip) {top_horn:.3f} m; head top {zs[np.argmax(head_skin(np.stack([0 * zs + 0.03, 0 * zs, zs], 1)) < 0)]:.3f}") print(f" eye centre {r3(EYE_C)}, knot x {KNOT:.3f}") rig = { "note": "root frame = body bbox centre; x forward, y left, z up; metres at scale 1. pos = J - R*pivot*scale", "root_centre_in_design": r3(C_B, 4), "ground_z_root": round(float(ground_root), 4), "joints": {k: r3(v, 4) for k, v in joints.items()}, "pieces": {nm: {"tris": int(len(p.F)), "size": r3(p.size, 4), "pivot": r3(p.pivot, 4), "faces": [m.name for m in p.mats], "frame": p.info} for nm, p in pieces.items()}, "rest": {nm: {"joint": r3(J, 4), "rot_xyzs": r3((q.x, q.y, q.z, q.w), 5), "euler_deg": r3([math.degrees(a) for a in q.to_euler("XYZ")], 2), "scale": list(sc), "centre": r3(place(pieces[nm], J, q, sc), 4)} for nm, (J, q, sc) in REST.items()}, "wing_spread_l": {"rot_xyzs": r3((WING_SPREAD.x, WING_SPREAD.y, WING_SPREAD.z, WING_SPREAD.w), 5), "euler_deg": r3([math.degrees(a) for a in WING_SPREAD.to_euler("XYZ")], 2)}, "wing_fold_l": {"rot_xyzs": r3((WING_FOLD.x, WING_FOLD.y, WING_FOLD.z, WING_FOLD.w), 5), "euler_deg": r3([math.degrees(a) for a in WING_FOLD.to_euler("XYZ")], 2), "scale": list(WING_FOLD_SCALE)}, "tail": {"lengths": [t[0] for t in TAIL], "rest_pitch_deg": TAIL_REST_PITCH}, "legs": {"thigh": L_THIGH, "shin": L_SHIN, "ankle_height": ANKLE_H, "ankle_rest_design": r3(ANKLE_REST)}, } if PROBE: print(json.dumps(rig["rest"], indent=None)[:4000]) sys.exit(0) os.makedirs(OUT, exist_ok=True) for nm, p in pieces.items(): path = os.path.join(OUT, f"{nm}{SUFFIX}.glb") export(p.object(), path) lo, hi, nodes = glb_bounds(path) off = (lo + hi) / 2 assert np.abs(off).max() < 1e-3 and np.abs((hi - lo) - p.size).max() < 1e-3 and not nodes, (nm, lo, hi, nodes) print(f"wrote {len(pieces)} .glb (bounds checked: centred, Z-up sizes match, no node transforms)") with open(os.path.join(OUT, f"rig{SUFFIX}.json"), "w") as fh: json.dump(rig, fh, indent=1) def lv(v): return "<" + ", ".join(f"{float(x):.4f}" for x in v) + ">" def lq(q): return "<" + ", ".join(f"{float(x):.5f}" for x in (q.x, q.y, q.z, q.w)) + ">" pv = {nm: p.pivot for nm, p in pieces.items()} lsl = [f"// ---- joint table from gen_dragon.py{(' (' + SUFFIX + ' meshes)') if SUFFIX else ''}, scale 1; body frame: x forward, y left, z up;", "// origin = body bbox centre. A piece at local rotation R whose joint is at J: PRIM_POS_LOCAL = J - (PIV * SCALE) * R.", "// Right-side rotations mirror the left: <-x, y, -z, s>.", f"vector BODY_SIZE = {lv(body.size)};", f"vector HIP_L = {lv(rootp(HIP))}; vector HIP_R = {lv(rootp(HIP * (1, -1, 1)))};", f"float L1 = {L_THIGH}; float L2 = {L_SHIN}; // thigh, shin (hip -> knee -> ankle)", f"float ANKLE_H = {ANKLE_H}; // ankle (foot pivot) above the sole: IK target = ground point + <0,0,ANKLE_H*SCALE>", f"float H = {-ground_root:.4f}; // body origin above the ground when standing", f"vector ANKLE_REST_L = {lv(REST['foot_l'][0])}; // standing ankle in the body frame (right: y negated)", f"vector NECK = {lv(rootp(NECK))};", f"vector SHOULDER_L = {lv(rootp(SHOULDER))}; vector SHOULDER_R = {lv(rootp(SHOULDER * (1, -1, 1)))};", f"vector WING_L = {lv(rootp(WING_ROOT))}; vector WING_R = {lv(rootp(WING_ROOT * (1, -1, 1)))};", f"vector TAIL0 = {lv(rootp(TAIL_ROOT))}; list TAIL_LEN = [{', '.join(str(t[0]) for t in TAIL)}];", f"list TAIL_REST_PITCH = [{', '.join(str(a) for a in TAIL_REST_PITCH)}]; // degrees about y, absolute (+ lifts the tip)", "// per piece: pivot offset from bbox centre and rest bone direction, in the piece's own frame", f"vector PIV_THIGH = {lv(pv['thigh_l'])}; vector DIR_THIGH = <0, 0, -1>; // same for thigh_r", f"vector PIV_SHIN = {lv(pv['shin_l'])}; vector DIR_SHIN = <0, 0, -1>; // same for shin_r", f"vector PIV_FOOT = {lv(pv['foot_l'])}; // foot rotation ZERO_ROTATION = flat, toes +x; same for foot_r", f"vector PIV_HEAD = {lv(pv['head'])};", f"vector PIV_ARM_L = {lv(pv['arm_l'])}; vector PIV_ARM_R = {lv(pv['arm_r'])}; // identity = rest pose", f"vector PIV_WING_L = {lv(pv['wing_l'])}; vector PIV_WING_R = {lv(pv['wing_r'])}; // identity = spread flat sideways", f"list PIV_TAIL = [{', '.join(lv(pv[f'tail{i}']) for i in range(1, 5))}]; vector DIR_TAIL = <-1, 0, 0>;", "// wings (left; right = <-x, y, -z, s>). Folded = WING_FOLD_L with the wing's PRIM_SIZE and PIV scaled by WING_FOLD_SCALE", "// per axis (the fingers close up like a fan). WING_SPREAD_L is the pose in render_spread.png.", f"vector WING_SIZE = {lv(pieces['wing_l'].size)};", f"rotation WING_FOLD_L = {lq(WING_FOLD)}; vector WING_FOLD_SCALE = {lv(WING_FOLD_SCALE)};", f"rotation WING_SPREAD_L = {lq(WING_SPREAD)};", "// ------------------------------------------------------------------------------------------------------------------"] with open(os.path.join(OUT, f"rig{SUFFIX}.lsl"), "w") as fh: fh.write("\n".join(lsl) + "\n") if not RENDER: sys.exit(0) # ---------------------------------------------------------------- renders, assembled by the joint table scene = bpy.context.scene if QUICK: scene.render.engine = "BLENDER_WORKBENCH" scene.display.shading.light = "STUDIO" scene.display.shading.color_type = "MATERIAL" scene.display.shading.show_shadows = True scene.render.resolution_x, scene.render.resolution_y = 800, 600 else: scene.render.engine = "BLENDER_EEVEE" scene.eevee.taa_render_samples = 24 scene.render.resolution_x, scene.render.resolution_y = 1280, 960 scene.view_settings.view_transform = "Standard" scene.world = bpy.data.worlds.new("w") scene.world.use_nodes = True scene.world.node_tree.nodes["Background"].inputs["Color"].default_value = (*srgb("#D5DAE0"), 1) scene.world.node_tree.nodes["Background"].inputs["Strength"].default_value = 0.7 scene.world.color = srgb("#D5DAE0") sun = bpy.data.objects.new("sun", bpy.data.lights.new("sun", "SUN")) sun.data.energy = 3.0 sun.data.angle = math.radians(25) sun.rotation_euler = Euler((math.radians(45), 0, math.radians(-35))) scene.collection.objects.link(sun) fill = bpy.data.objects.new("fill", bpy.data.lights.new("fill", "SUN")) fill.data.energy = 0.9 fill.data.angle = math.radians(40) fill.rotation_euler = Euler((math.radians(60), 0, math.radians(160))) scene.collection.objects.link(fill) bpy.ops.mesh.primitive_plane_add(size=30) ground = bpy.context.active_object ground.data.materials.append(material("ground", "#B9BFB4", 0.95)) made = [] def assemble(P, at=(0, 0, 0), yaw=0.0): for o in made: bpy.data.objects.remove(o) made.clear() Rr = Quaternion((0, 0, 1), yaw) base = Vector(at) + Vector(C_B) # root (body bbox centre) in the world for nm, (J, q, sc) in P.items(): pc = pieces[nm] o = bpy.data.objects.new(nm + "_i", pc.object().data) scene.collection.objects.link(o) o.location = base + Rr @ Vector(place(pc, J, q, sc)) o.rotation_mode = "QUATERNION" o.rotation_quaternion = Rr @ q o.scale = sc made.append(o) def camera(target, az, el, dist, lens=50): cam = bpy.data.objects.new("cam", bpy.data.cameras.new("cam")) scene.collection.objects.link(cam) cam.data.lens = lens t = Vector(target) d = Vector((math.cos(math.radians(el)) * math.cos(math.radians(az)), math.cos(math.radians(el)) * math.sin(math.radians(az)), math.sin(math.radians(el)))) cam.location = t + d * dist cam.rotation_euler = (-d).to_track_quat("-Z", "Y").to_euler() scene.camera = cam return cam def shot(fname, target, az, el, dist, lens=50): cam = camera(target, az, el, dist, lens) scene.render.filepath = os.path.join(OUT, fname) bpy.ops.render.render(write_still=True) bpy.data.objects.remove(cam) print("rendered", fname) if CARD: scene.render.film_transparent = True ground.hide_render = True scene.render.resolution_x, scene.render.resolution_y = 1048, 800 assemble(pose(wings="spread", head_q=qz(18) @ qy(-6))) shot("card_pip.png", (0, 0, 1.08), 32, 9, 5.0) # 10-20: the same pose from behind, for the infinity card's mirror reflections (flipped there) shot("card_pip_back.png", (0, 0, 1.08), 32 + 180, 9, 5.0) sys.exit(0) assemble(pose()) shot(f"render_34{SUFFIX}.png", (0, 0, 1.0), 35, 12, 6.0) if SUFFIX: sys.exit(0) shot("render_side.png", (-0.15, 0, 1.0), 90, 6, 6.2) shot("render_front.png", (0, 0, 1.0), 0, 6, 5.6) shot("render_back.png", (0, 0, 1.0), 200, 25, 6.0) assemble(pose(wings="spread", head_q=qy(-8))) shot("render_spread.png", (0, 0, 1.05), 30, 12, 6.0) shot("render_spread_back.png", (0, 0, 1.05), 160, 18, 6.0) assemble(pose()) shot("render_head.png", (0.1, 0, 1.55), 20, 6, 2.4) # a mid-stride check: head turned, left foot lifted forward, tail swung, wings half open (not a rest pose) assemble(pose(wings="spread", head_q=qz(40) @ qy(-6), ankles={"l": ANKLE_REST + (0.2, 0, 0.08), "r": ANKLE_REST * (1, -1, 1) + (-0.1, 0, 0)}, tail=[(-24, 10), (-14, 14), (-4, 14), (12, 10)])) shot("render_motion.png", (0, 0, 1.0), 50, 14, 6.0)