A 3D model pipeline, pushed by Gemini 4 Argon
agent (cont.)
+3:33read_file{"EndLine":300,"Path":"~/work/lowmarch/tools/plates.py","StartLine":1}
input
{ "EndLine": 300, "Path": "~/work/lowmarch/tools/plates.py", "StartLine": 1 }result, 301 lines
Showing lines 1-300 of 487 1: """Plates drawn as outlines: the armour kit's second generation (portrait guide, lesson 13). 2: 3: The first kit builds plate as bands (limb_lames, pauldron lames) or shrink-wraps (the cuirass): fine 4: for stacked lames, but it can't draw a shape. Here a plate is drawn like a pattern piece laid on a 5: dress form. 6: 7: A chart wraps a body region in two coordinates: 8: TorsoChart u = degrees round the body (0 front, +90 the character's right, 180 back), v = height (m) 9: LimbChart u = degrees round a bone (0 = `front`), v = fraction along it (0 at the joint) 10: point(u, v) is on the surface the chart covers: a ray out of the chart's axis, at a radius taken from 11: a field of ray casts that is filled and smoothed (and, as a shell, kept from following hollows), so 12: plates come out as shells rather than mouldings of the skin. 13: 14: A plate is the region between two edge curves over a range of u, bottom(u) and top(u), so its outline 15: is exactly the mesh boundary (no jagged clipping) and a pointed waist, a scooped neckline or a pointed 16: cuff is one function each. It sits `offset` off the chart, is domed by `crown`, given thickness, and 17: carries per-vertex plate data for the painted renderer: 18: plate = (1, distance to the outline in metres, gold border width in metres, height in the plate 0..1) 19: from which the shader paints the border, an engraved line inside it, and a top-to-bottom gradient 20: so a flat plate doesn't read as one flat value. 21: """ 22: import math 23: 24: import numpy as np 25: from scipy.ndimage import gaussian_filter 26: from scipy.spatial import cKDTree 27: 28: 29: def _fill_nan(R, wrap_u=True): 30: """Fill missing radii (rays that hit nothing) from their neighbours round u, then along v.""" 31: R = R.copy() 32: nu, nv = R.shape 33: idx = np.arange(nu) 34: for j in range(nv): 35: col = R[:, j] 36: ok = np.isfinite(col) 37: if ok.sum() >= 2: 38: if wrap_u: 39: xs = np.concatenate([idx[ok] - nu, idx[ok], idx[ok] + nu]) 40: R[:, j] = np.interp(idx, xs, np.tile(col[ok], 3)) 41: else: 42: R[:, j] = np.interp(idx, idx[ok], col[ok]) 43: good = np.isfinite(R).all(0) 44: if not good.any(): 45: raise ValueError("chart: no ray hit the surface") 46: for j in range(nv): 47: if not good[j]: 48: k = np.nonzero(good)[0] 49: R[:, j] = R[:, k[np.argmin(np.abs(k - j))]] 50: return R 51: 52: 53: class _Chart: 54: """Shared: a radius field R[u, v] over a grid, sampled bilinearly (u wraps).""" 55: 56: def _setup(self, R, smooth, shell, wrap_u): 57: R = _fill_nan(R, wrap_u) 58: mode = ("wrap" if wrap_u else "nearest", "nearest") 59: if shell: # bridge hollows (between the breasts, the spine) 60: R = np.maximum(R, gaussian_filter(R, (smooth[0] * 3, smooth[1] * 3), mode=mode)) 61: self.R = gaussian_filter(R, smooth, mode=mode) 62: 63: def radius(self, u, v): 64: u, v = np.broadcast_arrays(np.asarray(u, float), np.asarray(v, float)) 65: fu = (u - self.u0) / self.du 66: fv = np.clip((v - self.v0) / self.dv, 0, self.R.shape[1] - 1.000001) 67: nu = self.R.shape[0] 68: if self.wrap: 69: fu = np.mod(fu, nu) 70: else: 71: fu = np.clip(fu, 0, nu - 1.000001) 72: i0 = np.floor(fu).astype(int) 73: i1 = (i0 + 1) % nu if self.wrap else np.minimum(i0 + 1, nu - 1) 74: j0 = np.floor(fv).astype(int) 75: j1 = np.minimum(j0 + 1, self.R.shape[1] - 1) 76: a, b = fu - i0, fv - j0 77: R = self.R 78: return ((R[i0, j0] * (1 - a) + R[i1, j0] * a) * (1 - b) + (R[i0, j1] * (1 - a) + R[i1, j1] * a) * b) 79: 80: def point(self, u, v, off=0.0): 81: o, d = self.ray(u, v) 82: return o + d * (self.radius(u, v) + off)[..., None] 83: 84: def normal(self, u, v, eu=1.0, ev=None): 85: """The chart surface's outward normal (finite differences of point()).""" 86: ev = self.ev if ev is None else ev 87: pu = self.point(np.asarray(u) + eu, v) - self.point(np.asarray(u) - eu, v) 88: pv = self.point(u, np.asarray(v) + ev) - self.point(u, np.asarray(v) - ev) 89: n = np.cross(pv, pu) 90: _, d = self.ray(u, v) 91: n = np.where((np.einsum("...i,...i->...", n, d) < 0)[..., None], -n, n) 92: return n / np.maximum(np.linalg.norm(n, axis=-1, keepdims=True), 1e-12) 93: 94: 95: class TorsoChart(_Chart): 96: """u = degrees round the vertical axis through (cx, cz) (0 = front, -z; +90 = the character's 97: right, +x), v = height in metres. `over`: the Surface the plates sit on.""" 98: 99: def __init__(self, over, y0, y1, cx=0.0, cz=0.0, du=3.0, dv=0.01, smooth=(1.5, 1.2), shell=True, rmax=0.4): 100: self.cx, self.cz, self.wrap = cx, cz, True 101: self.u0, self.du, self.v0, self.dv, self.ev = -180.0, du, y0, dv, dv * 0.5 102: us = np.arange(-180.0, 180.0, du) 103: vs = np.arange(y0, y1 + dv * 0.5, dv) 104: R = np.full((len(us), len(vs)), np.nan) 105: for i, u in enumerate(us): 106: d = np.array([math.sin(math.radians(u)), 0.0, -math.cos(math.radians(u))]) 107: for j, v in enumerate(vs): 108: R[i, j] = over.cast(np.array([cx, v, cz]), d, rmax=rmax, far=True) 109: self._setup(R, smooth, shell, True) 110: 111: def ray(self, u, v): 112: u, v = np.broadcast_arrays(np.asarray(u, float), np.asarray(v, float)) 113: ur = np.radians(u) 114: d = np.stack([np.sin(ur), np.zeros_like(ur), -np.cos(ur)], -1) 115: o = np.stack([np.full_like(u, self.cx), v, np.full_like(u, self.cz)], -1) 116: return o, d 117: 118: def metric(self, u, v): 119: """(arc length round the body, height) in metres: distances along the surface for trim.""" 120: return np.stack([np.radians(u) * self.radius(u, v), np.asarray(v, float) + 0 * np.asarray(u, float)], -1) 121: 122: def centre(self, v): 123: return np.array([self.cx, v, self.cz]) 124: 125: 126: class ConeChart(TorsoChart): 127: """A TorsoChart whose radius is a function r(u, v) instead of ray casts: a skirt's cone, a 128: plate standing off a skirt. r_fn takes and returns arrays.""" 129: 130: def __init__(self, r_fn, cx=0.0, cz=0.0, ev=0.005): 131: self.cx, self.cz, self.r_fn, self.ev, self.wrap = cx, cz, r_fn, ev, True 132: 133: def radius(self, u, v): 134: u, v = np.broadcast_arrays(np.asarray(u, float), np.asarray(v, float)) 135: return np.asarray(self.r_fn(u, v), float) + 0 * u 136: 137: 138: class LimbChart(_Chart): 139: """u = degrees round the bone from a to b (0 = toward `front`, +90 = toward front x axis, i.e. 140: the right-handed turn about the bone), v = fraction along it (0 at a, 1 at b; -0.2..1.2 covered).""" 141: 142: def __init__(self, over, a, b, front=(0, 0, -1), du=6.0, dv=0.025, smooth=(1.2, 1.2), shell=True, rmax=0.14, 143: v_range=(-0.2, 1.2)): 144: self.a, self.b = np.asarray(a, float), np.asarray(b, float) 145: ax = self.b - self.a 146: self.L = float(np.linalg.norm(ax)) 147: self.ax = ax / self.L 148: f = np.asarray(front, float) - self.ax * (np.asarray(front, float) @ self.ax) 149: self.f = f / np.linalg.norm(f) 150: self.s = np.cross(self.ax, self.f) 151: self.wrap = True 152: self.u0, self.du, self.v0, self.dv, self.ev = -180.0, du, v_range[0], dv, dv * 0.5 153: us = np.arange(-180.0, 180.0, du) 154: vs = np.arange(v_range[0], v_range[1] + dv * 0.5, dv) 155: R = np.full((len(us), len(vs)), np.nan) 156: for i, u in enumerate(us): 157: ur = math.radians(u) 158: d = self.f * math.cos(ur) + self.s * math.sin(ur) 159: for j, v in enumerate(vs): 160: R[i, j] = over.cast(self.a + self.ax * self.L * v, d, rmax=rmax, far=True) 161: self._setup(R, smooth, shell, True) 162: 163: def ray(self, u, v): 164: u, v = np.broadcast_arrays(np.asarray(u, float), np.asarray(v, float)) 165: ur = np.radians(u) 166: d = np.cos(ur)[..., None] * self.f + np.sin(ur)[..., None] * self.s 167: o = self.a + self.ax * (self.L * v)[..., None] 168: return o, d 169: 170: def metric(self, u, v): 171: return np.stack([np.radians(u) * self.radius(u, v), np.asarray(v, float) * self.L + 0 * np.asarray(u, float)], -1) 172: 173: def centre(self, v): 174: return self.a + self.ax * self.L * v 175: 176: 177: def _thick(G, n, thickness, data, uv): 178: """A grid shell (outer face G, inner face G - n*thickness, the four edges closed) with per-vertex 179: plate data and decal coordinates: the inner face copies the outer, edge walls sit at the outline 180: (distance 0).""" 181: U, V = G.shape[:2] 182: idx = np.arange(U * V).reshape(U, V) 183: a, b, c, d = idx[:-1, :-1], idx[1:, :-1], idx[1:, 1:], idx[:-1, 1:] 184: tri = np.concatenate([np.stack([a, b, c], -1).reshape(-1, 3), np.stack([a, c, d], -1).reshape(-1, 3)]) 185: th = np.asarray(thickness, float) 186: outer, inner = G.reshape(-1, 3), (G - n * (th[..., None] if th.ndim else th)).reshape(-1, 3) 187: fn = np.cross(outer[tri[:, 1]] - outer[tri[:, 0]], outer[tri[:, 2]] - outer[tri[:, 0]]) 188: if (np.einsum("ij,ij->i", fn, n.reshape(-1, 3)[tri[:, 0]]) < 0).mean() > 0.5: 189: tri = tri[:, ::-1] # the outer face winds outward (along the chart normal) 190: mid = (outer.mean(0) + inner.mean(0)) / 2 191: D, UV = data.reshape(-1, 4), uv.reshape(-1, 2) 192: pos, tris, dat, uvs = [outer, inner], [tri, tri[:, ::-1] + U * V], [D, D], [UV, UV] 193: off = 2 * U * V 194: for e in (idx[:, 0], idx[:, -1], idx[0, :], idx[-1, :]): 195: m = len(e) 196: P = np.concatenate([outer[e], inner[e]]) 197: k = np.arange(m - 1) 198: t = np.concatenate([np.stack([k, k + 1, m + k + 1], 1), np.stack([k, m + k + 1, m + k], 1)]) 199: wn = np.cross(P[t[:, 1]] - P[t[:, 0]], P[t[:, 2]] - P[t[:, 0]]) 200: if (np.einsum("ij,ij->i", wn, P[t[:, 0]] - mid) < 0).mean() > 0.5: 201: t = t[:, ::-1] # edge walls face away from the plate's middle 202: pos.append(P) 203: tris.append(t + off) 204: dd = np.concatenate([D[e], D[e]]) 205: dd[:, 1] = 0.0 206: dat.append(dd) 207: uvs.append(np.concatenate([UV[e], UV[e]])) 208: off += 2 * m 209: return np.concatenate(pos), np.concatenate(tris), np.concatenate(dat), np.concatenate(uvs) 210: 211: 212: # ---- decals: designs drawn in a piece's own surface coordinates ----------------------------------- 213: # A decal is an RGB texture over the piece's (s, t) square (t up): R = paint (the character's motif 214: # colour), G = groove (a dark recessed line), B = gold inlay. The painted renderer reads it per pixel. 215: CHANNEL = {"paint": 0, "groove": 1, "gold": 2} 216: 217: 218: class Canvas: 219: """Draw shapes given in (s, t) in 0..1 (t up) at w x h pixels, supersampled for clean edges.""" 220: 221: def __init__(self, w, h, ss=3): 222: from PIL import Image, ImageDraw 223: self.w, self.h, self.ss = int(w), int(h), ss 224: self.layers = [Image.new("L", (self.w * ss, self.h * ss), 0) for _ in range(3)] 225: self.draw = [ImageDraw.Draw(im) for im in self.layers] 226: 227: def _xy(self, st): 228: st = np.atleast_2d(np.asarray(st, float)) 229: return [(float(s * self.w * self.ss), float((1 - t) * self.h * self.ss)) for s, t in st] 230: 231: def poly(self, st, ch): 232: self.draw[CHANNEL[ch]].polygon(self._xy(st), fill=255) 233: 234: def line(self, st, width_px, ch): 235: xy = self._xy(st) 236: w = max(1, int(round(width_px * self.ss))) 237: self.draw[CHANNEL[ch]].line(xy, fill=255, width=w, joint="curve") 238: r = w / 2 239: for x, y in (xy[0], xy[-1]): # round caps 240: self.draw[CHANNEL[ch]].ellipse((x - r, y - r, x + r, y + r), fill=255) 241: 242: def dot(self, st, rx_px, ry_px, ch): 243: (x, y), = self._xy(st) 244: self.draw[CHANNEL[ch]].ellipse((x - rx_px * self.ss, y - ry_px * self.ss, x + rx_px * self.ss, y + ry_px * self.ss), 245: fill=255) 246: 247: def array(self): 248: from PIL import Image 249: chans = [np.asarray(im.resize((self.w, self.h), Image.LANCZOS)) for im in self.layers] 250: return np.dstack(chans + [np.full((self.h, self.w), 255, np.uint8)]).astype(np.uint8) 251: 252: 253: def _seg_distance(P, A, B): 254: """Distance from points P (N,2) to segments A->B (M,2): (N,) minimum.""" 255: d = B - A 256: L2 = np.maximum((d * d).sum(1), 1e-18) 257: t = np.clip(((P[:, None] - A[None]) * d[None]).sum(-1) / L2[None], 0, 1) 258: Q = A[None] + t[..., None] * d[None] 259: return np.linalg.norm(P[:, None] - Q, axis=-1).min(1) 260: 261: 262: def outline_plate(name, role, chart, u0, u1, bottom, top, offset=0.012, crown=0.0, flare=None, thickness=0.003, 263: nu=48, nv=18, trim=0.0, roll=0.0026, roll_edges=("bottom", "top", "left", "right"), 264: roll_role=None, rivets=None, rivet_role="gold", seams=(), groove=(0.004, 0.0025), 265: panel_crown=0.0, studs=(), stud_r=0.004, stud_role=None, facets=None, decal=(), decal_px=1400, 266: pattern=None): 267: """A plate between bottom(u) and top(u) over u in [u0, u1] on `chart`. 268: offset: off the chart surface; crown: extra rise in the middle of the plate (0 at the outline); 269: flare(u, v, s, t) -> extra offset (s across, t up, both 0..1), e.g. a cuff belling out at one end; 270: thickness: metres, or thickness(u, v, s, t) per point (a beard filled down to the face); 271: trim: gold border width painted by the renderer (0 = none); roll: rolled-edge tube radius along 272: `roll_edges` (0 = none); rivets: (spacing, inset, radius) studs inside the outline (rivet_role). 273: seams: polylines [(u, v), ...] dividing the plate into panels: each panel domes by panel_crown, 274: the seams sink into grooves (width, depth) and are painted as dark grooves; 275: studs: (u, v) points (seam junctions) given domed studs of radius stud_r; 276: facets: u angles where the plate turns a corner: flat between them (a TorsoChart's horizontal rows); 277: decal: shapes in chart coordinates painted on the plate (see Canvas): 278: ("poly", [(u, v), ...], channel) / ("line", [(u, v), ...], width_m, channel) / ("dot", (u, v), r_m, channel) 279: channels: "paint" (the character's motif colour), "groove", "gold". 280: Returns (plate piece, [extra pieces: rolls, rivets, studs]); bind them all before export.""" 281: from outfit import piece, pipe, ball 282: U = np.linspace(u0, u1, nu) 283: S = np.linspace(0, 1, nu) 284: T = np.linspace(0, 1, nv) 285: vb = np.array([bottom(u) for u in U]) 286: vt = np.array([top(u) for u in U]) 287: uu = np.repeat(U[:, None], nv, 1) 288: vv = vb[:, None] + (vt - vb)[:, None] * T[None, :] 289: n = chart.normal(uu, vv) 290: lift = np.full(uu.shape, float(offset)) 291: if crown: 292: lift += crown * np.sqrt(np.clip(np.sin(np.pi * S)[:, None] * np.sin(np.pi * T)[None, :], 0, 1)) 293: if flare is not None: 294: lift += np.array([[flare(U[i], vv[i, j], S[i], T[j]) for j in range(nv)] for i in range(nu)]) 295: if seams: # panels dome between seams that sink into grooves 296: M = chart.metric(uu, vv).reshape(-1, 2) 297: segs = [(chart.metric(np.array([a[0], b[0]]), np.array([a[1], b[1]]))) for L in seams for a, b in zip(L[:-1], L[1:])] 298: A = np.array([sg[0] for sg in segs]) 299: Bv = np.array([sg[1] for sg in segs]) 300: dseam = _seg_distance(M, A, Bv).reshape(uu.shape)read_file{"EndLine":1200,"Path":"~/work/lowmarch/review/vroid-02/index.html","StartLine":801}
input
{ "EndLine": 1200, "Path": "~/work/lowmarch/review/vroid-02/index.html", "StartLine": 801 }result, 401 lines
Showing lines 801-1200 of 1737 801: const d = new THREE.Vector3(W[i].x - C.x, 0, W[i].z - C.z).normalize(), t = new THREE.Vector3(-d.z, 0, d.x); 802: let carry = 0; 803: for (let j = 1; j < V; j++) { 804: const k = idx(i, j); 805: let need = carry; // below a contact the cloth hangs from it 806: for (let it = 0; it < 6; it++) { 807: p.copy(W[i]).addScaledVector(d, this.r0[k] + need).addScaledVector(t, this.t0[k]); p.y += this.h0[k]; 808: let worst = 0; 809: for (const c of caps) { 810: ab.subVectors(c.b, c.a); const tt = THREE.MathUtils.clamp(ap.subVectors(p, c.a).dot(ab) / ab.lengthSq(), 0, 1); 811: cp.copy(c.a).addScaledVector(ab, tt); 812: const dx = p.x - cp.x, dz = p.z - cp.z, dist = Math.hypot(dx, p.y - cp.y, dz); 813: if (dist < c.r) worst = Math.max(worst, c.r - dist); 814: } 815: if (worst < 1e-4) break; 816: need += worst * 1.15; 817: } 818: target[k] = carry = need; 819: } 820: } 821: for (let pass = 0; pass < 2; pass++) // smooth round the skirt 822: for (let j = 1; j < V; j++) { 823: const row = []; 824: for (let i = 0; i < U; i++) row.push((target[idx((i + U - 1) % U, j)] + 2 * target[idx(i, j)] + target[idx((i + 1) % U, j)]) / 4); 825: for (let i = 0; i < U; i++) target[idx(i, j)] = Math.max(row[i], target[idx(i, j)] * 0.6); 826: } 827: const ease = instant ? 1 : Math.min(1, dt * 9); 828: for (let k = 0; k < U * V; k++) this.push[k] += (target[k] - this.push[k]) * ease; 829: for (let i = 0; i < U; i++) { 830: const d = new THREE.Vector3(W[i].x - C.x, 0, W[i].z - C.z).normalize(), t = new THREE.Vector3(-d.z, 0, d.x); 831: let prev = W[i].clone(), pr = 0, ph = 0, pt = 0; 832: X[3 * idx(i, 0)] = prev.x; X[3 * idx(i, 0) + 1] = prev.y; X[3 * idx(i, 0) + 2] = prev.z; 833: for (let j = 1; j < V; j++) { 834: const k = idx(i, j), r = this.r0[k] + this.push[k], h0 = this.h0[k], tt = this.t0[k]; 835: // keep the rest length of this segment: what the push adds outward comes off the drop 836: const L = Math.hypot(this.r0[k] - this.r0[k - 1], h0 - this.h0[k - 1], tt - this.t0[k - 1]); 837: const dr = r - pr, dtan = tt - pt, dh = -Math.sqrt(Math.max(L * L - dr * dr - dtan * dtan, 1e-6)); 838: const h = ph + (j === 1 ? Math.min(dh, h0) : dh); 839: const q = W[i].clone().addScaledVector(d, r).addScaledVector(t, tt); q.y += h; 840: X[3 * k] = q.x; X[3 * k + 1] = q.y; X[3 * k + 2] = q.z; 841: pr = r; ph = h; pt = tt; 842: } 843: } 844: this.prev.set(X); 845: } 846: reset() { this.push.fill(0); this.pose(0, true); } 847: step(dt) { this.pose(dt, false); } 848: } 849: 850: // ---- materials per mesh ---------------------------------------------------------------------------------------------- 851: const KEY = new THREE.Vector3(-0.45, 0.55, 0.70).normalize(); 852: // stage grades: ambient multiply, key colour, back rim (characters and stage share them) 853: const GRADE = { battle: { ambient: [0.84, 0.87, 0.98], key: [1.05, 1.0, 0.92], rim: [0.38, 0.34, 0.26] }, 854: bust: { ambient: [0.90, 0.90, 0.98], key: [1.03, 1.0, 0.96], rim: [0.24, 0.24, 0.34] } }; 855: // Brows draw over the bangs: they are lifted this far (m) toward the camera, more than the bangs stand off the 856: // forehead and much less than the head is deep, so a brow still hides behind the skull when the head turns away. 857: const BROW_LIFT = 0.04; 858: const KIND = { cloth: 0, skin: 1, hair: 2, steel: 3, gold: 4, leather: 5, world: 6 }; 859: function paintMaterial(V, role, map, index, infoRole = role, decal = false) { 860: const Rl = V.roles[role] || { mode: "flat", color: "#ff00ff" }, P = (V.paint || {})[role]; 861: const u = { uKind: { value: 9 }, uBase: { value: new THREE.Color(0.8, 0.8, 0.8) }, uKey: { value: KEY.clone() }, 862: uMap: { value: map || white }, uAlpha: { value: 0 }, uPass: { value: 0 }, 863: uInfo: { value: new THREE.Vector4(roleId(infoRole) / 255, (index % 256) / 255, Math.floor(index / 256) / 255, 1) }, 864: uEye: { value: V.roles.iris.colors.map(hex) }, uFlat: { value: new THREE.Color() }, uSkinRef: { value: new THREE.Vector3(0.965, 0.878, 0.80) }, 865: uGold: { value: hex((V.paint && V.paint.gold && V.paint.gold.base) || "#b08b3f") }, 866: uAmbient: { value: new THREE.Vector3(1, 1, 1) }, uKeyCol: { value: new THREE.Vector3(1, 1, 1) }, uRimCol: { value: new THREE.Vector3() }, 867: uGrain: { value: 0.05 }, uFaceTex: { value: 0 }, uDecal: { value: decal ? 1 : 0 }, uBand: { value: null }, 868: uSkinTone: { value: new THREE.Vector3(1, 1, 1) }, uShadeOnly: { value: 0 }, 869: uSkinRamp: { value: 0 }, uSkinL: { value: new THREE.Color() }, uSkinS: { value: new THREE.Color() }, uSkinC: { value: new THREE.Color() }, 870: tCastInfo: { value: null }, tCastDepth: { value: null }, uCastRes: { value: new THREE.Vector2(1, 1) }, uCastOn: { value: 0 }, 871: uCastNear: { value: 0.1 }, uCastFar: { value: 40 }, uCastPpm: { value: 1 }, 872: uMotif: { value: hex((V.paint && V.paint.motif && V.paint.motif.base) || "#3a44a0") }, uLift: { value: 0 } }; 873: if (P) { u.uKind.value = KIND[P.kind] ?? 0; if (P.base) u.uBase.value = hex(P.base); if (P.grain != null) u.uGrain.value = P.grain; } 874: else if (Rl.bands) { u.uKind.value = Rl.world ? 6 : 0; u.uBase.value = hex(Rl.bands[Math.min(1, Rl.bands.length - 1)][1]); } 875: if (P && P.kind === "world") { u.uKey.value = new THREE.Vector3(...V.sun); u.uGrain.value = 0.12; } 876: if (P && P.shade) u.uShadeOnly.value = 1; // shadow cards: skin, always in its shade tone 877: if (P && P.kind === "skin" && P.ramp) { // a designed ramp: lit, shade, deep shade 878: u.uSkinRamp.value = 1; u.uSkinL.value = hex(P.ramp[0]); u.uSkinS.value = hex(P.ramp[1]); u.uSkinC.value = hex(P.ramp[2]); 879: } 880: if (P && P.kind === "skin" && P.base) { // skin tone: the base colour against the default light skin 881: const c = hex(P.base); u.uSkinTone.value.set(c.r / 0.973, c.g / 0.882, c.b / 0.835); 882: } 883: if (role === "face" && map) u.uFaceTex.value = 1; 884: if (role === "hair" && map) u.uAlpha.value = 1; 885: if (role === "iris") { u.uKind.value = 7; u.uAlpha.value = 1; } 886: else if (role === "white" || role === "highlight") { u.uKind.value = map ? 8 : 9; if (map) u.uAlpha.value = 1; u.uFlat.value = hex(Rl.color || "#ffffff"); } 887: else if (!P && Rl.mode === "flat") { u.uKind.value = 9; u.uFlat.value = hex(Rl.color); if (map) u.uAlpha.value = role === "line" ? 2 : 1; } 888: if (role === "brow") u.uLift.value = BROW_LIFT; 889: if (role === "mouth" && map) u.uKind.value = 10; 890: u.uBand.value = u.uGold.value.clone(); 891: const m = new THREE.ShaderMaterial({ uniforms: u, vertexShader: PAINT_VS, fragmentShader: PAINT_FS, side: THREE.DoubleSide, 892: extensions: { derivatives: true } }); 893: // meshes without plate data or a cloth edge read zeros, not whatever another program left in that slot 894: m.defaultAttributeValues = { ...m.defaultAttributeValues, _plate: [0, 0, 0, 0], edge: [0] }; 895: return m; 896: } 897: 898: // ---- models ------------------------------------------------------------------------------------------------------ 899: const loader = new GLTFLoader(); 900: const chars = new Map(); // name -> loaded character 901: let ground = null; 902: const stage = new THREE.Group(); // the duel: both fighters stand on it; the turn slider rotates it 903: scene.add(stage); 904: // the lineup: every enemy model standing in a row (camera.json's lineup), each turning in place 905: const LINEUP = CAM.lineup || { order: [], spacing: 0.9 }; 906: const ROW_VIEW = () => state.view === "lineup" || state.view === "compare"; // several models in a row, each turning in place 907: const CAM_VIEW = () => state.view === "duel" || ROW_VIEW() ? CAM.duel.cam : charDef(state.who).cams[state.view]; 908: const activeNames = () => state.view === "duel" ? [CAM.duel.order.player, CAM.duel.order.opponent] 909: : state.view === "lineup" ? LINEUP.order : state.view === "compare" ? state.compare : [state.who]; 910: const active = () => activeNames().map(n => chars.get(n)).filter(Boolean); 911: 912: async function parseGlb(file) { 913: const j = await (await fetch(file)).json(); 914: const bin = Uint8Array.from(atob(j.glb), c => c.charCodeAt(0)); 915: return await new Promise((ok, bad) => loader.parse(bin.buffer, "", ok, bad)); 916: } 917: let meshIndex = 1; 918: function prepMesh(o, V, opts = {}) { 919: const m0 = o.material, role = o.userData.role || "body", raw = rawTex(m0.map); 920: const infoRole = role === "hair" && opts.hairB ? "hair_b" : role === "shadow" ? "body" : role; 921: const decal = !!(m0.userData && m0.userData.decal); // the map is a design mask, not a colour 922: const base = { map: decal ? null : (m0.map || null), color: m0.color.clone(), side: THREE.DoubleSide, alphaTest: m0.alphaTest || 0 }; 923: const clay = new THREE.MeshStandardMaterial({ ...base, roughness: 0.85, metalness: m0.metalness || 0 }); 924: const toon = new THREE.MeshToonMaterial({ ...base, gradientMap: gradient }); 925: if (role === "hair" && m0.map && V.paint && V.paint.hair) { 926: // the VRoid sample's hair texture carries its own colour (dark on some samples): in 3D use the 927: // character's hair colour, with the texture's light and dark only for strand detail 928: for (const m of [clay, toon]) { 929: m.color = hex(V.paint.hair.base); 930: m.onBeforeCompile = sh => { sh.fragmentShader = sh.fragmentShader.replace("#include <map_fragment>", 931: `#ifdef USE_MAP 932: vec4 texel_ = texture2D(map, vMapUv); 933: diffuseColor.rgb *= mix(1.0, clamp(dot(texel_.rgb, vec3(0.3333)) / 0.5, 0.45, 1.35), 0.6); 934: diffuseColor.a *= texel_.a; 935: #endif`); }; 936: m.customProgramCacheKey = () => "hairlum"; 937: } 938: } 939: o.userData.mats = { clay, toon, painted: paintMaterial(V, role, raw, meshIndex, infoRole, decal) }; 940: meshIndex++; 941: o.userData.group = o.userData.group || "body"; 942: o.userData.role = role; 943: o.frustumCulled = false; 944: } 945: 946: async function loadCharacter(name) { 947: if (chars.has(name)) return chars.get(name); 948: const def = charDef(name), V = def.info, ci = CAM.characters.indexOf(def); 949: const gltf = await parseGlb(`${name}.glb.json`); 950: const turn = new THREE.Group(), holder = new THREE.Group(); 951: turn.add(holder); holder.add(gltf.scene); 952: const meshes = []; 953: gltf.scene.traverse(o => { if (o.isMesh) { prepMesh(o, V, { hairB: ci > 0 }); meshes.push(o); } }); 954: gltf.scene.updateMatrixWorld(true); 955: const bone = n => gltf.scene.getObjectByName(n); 956: const cloths = [], world = new THREE.Group(); 957: for (const [cname, info] of Object.entries(V.cloth || {})) { 958: const skinned = meshes.find(m => m.userData.material === cname); 959: if (!skinned) continue; 960: const trims = meshes.filter(m => info.trims.includes(m.userData.material)); 961: const caps = V.capsules.filter(c => !info.collide || info.collide.some(k => c.bones[0].includes(k))); 962: const cl = info.closed ? new SkirtRig(skinned, info.u, info.v, trims, caps, bone, info.edges === "hem") 963: : new Cloth(skinned, info.u, info.v, trims, caps, bone, false, info.edges === "hem"); 964: const band = info.band || "gold", BR = V.roles[band] || V.roles.gold; 965: const gold = hex(BR.bands ? BR.bands[Math.min(1, BR.bands.length - 1)][1] : BR.color); 966: const PB = (V.paint || {})[band]; 967: if (PB && PB.base) skinned.userData.mats.painted.uniforms.uBand.value = hex(PB.base); // gold stays gold for decals 968: cl.lines3d = new THREE.LineSegments(cl.lines.geometry, new THREE.LineBasicMaterial({ color: gold })); 969: cl.lines3d.frustumCulled = false; 970: world.add(cl.display, cl.lines3d); 971: cloths.push(cl); 972: } 973: const mixer = new THREE.AnimationMixer(gltf.scene); 974: const actions = Object.fromEntries(gltf.animations.map(c => [c.name, mixer.clipAction(c)])); 975: const skeleton = meshes.find(m => m.isSkinnedMesh)?.skeleton; 976: const c = { name, info: V, turn, holder, root: gltf.scene, meshes, cloths, world, mixer, actions, skeleton, 977: clip: "idle", t: 0, groups: [...new Set(meshes.map(m => m.userData.group))] }; 978: c.springs = makeSprings(c, V.springs); 979: chars.set(name, c); 980: return c; 981: } 982: 983: async function loadGround() { 984: if (ground) return ground; 985: const V = CAM.characters[0].info, gltf = await parseGlb("plains.glb.json"), meshes = []; 986: gltf.scene.traverse(o => { if (o.isMesh) { prepMesh(o, V); meshes.push(o); } }); 987: ground = { root: gltf.scene, meshes }; 988: return ground; 989: } 990: 991: const allMeshes = () => [...active().flatMap(c => [...c.meshes, ...c.cloths.map(cl => cl.display)]), 992: ...(ground && ground.root.parent && state.view !== "bust" ? ground.meshes : [])]; 993: const isSimTrim = o => state.cloth && active().some(c => c.cloths.some(cl => cl.trims.includes(o) || cl.skinned === o)); 994: function applyMaterials() { 995: allMeshes().forEach(o => { 996: const mat = state.toon ? o.userData.mats.toon : o.userData.mats.clay; 997: const x = state.xray && COSTUME.has(o.userData.group); 998: mat.transparent = x; mat.opacity = x ? 0.28 : 1; mat.depthWrite = !x; mat.needsUpdate = true; 999: o.userData.mat3d = mat; 1000: const isDisplay = o.userData.cloth; 1001: o.visible = !state.hidden.has(o.userData.group) && (isDisplay ? state.cloth : !isSimTrim(o)); 1002: }); 1003: } 1004: const trimsShown = c => state.cloth && !state.hidden.has("trim") && !state.hidden.has(c.skinned.userData.group); 1005: 1006: // ---- animation ------------------------------------------------------------------------------------------------------ 1007: // A clip only carries the bones it moves away from the reference pose, so each one starts from the 1008: // reference pose (otherwise "arms out" would keep the idle's legs). 1009: const CLIP_VIEW = { clash: "duel", idle: "battle", attack: "battle", apose: "battle" }; 1010: const lineupX = i => (i - (LINEUP.order.length - 1) / 2) * LINEUP.spacing; 1011: function setClip(name, blendFrom = null) { 1012: for (const c of active()) { 1013: const n = c.actions[name] ? name : "idle"; 1014: if (!blendFrom) c.skeleton && c.skeleton.pose(); 1015: c.clip = n; c.t = 0; 1016: Object.entries(c.actions).forEach(([k, a]) => { if (k === n) { a.reset(); a.setEffectiveWeight(1); a.play(); } else a.stop(); }); 1017: // ease in from another clip: legs stepping out gradually push the cloth (a long skirt) instead of 1018: // jumping through it 1019: c.blend = blendFrom && c.actions[blendFrom] ? { from: blendFrom, t: 0, dur: 0.8 } : null; 1020: } 1021: state.clip = name; 1022: document.querySelectorAll("[data-clip]").forEach(b => b.setAttribute("aria-pressed", String(b.dataset.clip === name && state.view !== "bust"))); 1023: } 1024: function animate(dt) { 1025: for (const c of active()) { 1026: if (ARMORY_PAGE && !SHEET) { c.mixer.stopAllAction(); c.skeleton && c.skeleton.pose(); applyPose(c); applyMotion(c, dt); continue; } 1027: if (state.view === "bust") { c.mixer.stopAllAction(); c.skeleton && c.skeleton.pose(); continue; } 1028: const a = c.actions[c.clip]; if (!a) continue; 1029: if (!a.isRunning()) a.play(); 1030: const dur = a.getClip().duration; 1031: c.t += dt; 1032: if (c.clip === "attack" && c.t > dur + 0.25) { setClip("idle"); return animate(0); } 1033: const t = state.stepped ? Math.floor(c.t * 12) / 12 : c.t; 1034: a.time = c.clip === "attack" ? Math.min(t, dur) : t % dur; // the others loop 1035: if (c.blend) { 1036: c.blend.t += dt; 1037: const w = Math.min(1, c.blend.t / c.blend.dur), b = c.actions[c.blend.from]; 1038: if (!b.isRunning()) b.play(); 1039: b.time = t % b.getClip().duration; b.setEffectiveWeight(1 - w); a.setEffectiveWeight(w); 1040: if (w >= 1) { b.stop(); a.setEffectiveWeight(1); c.blend = null; } 1041: } 1042: c.mixer.update(0); 1043: } 1044: } 1045: 1046: // ---- the armory's poses and its side-by-side comparison -------------------------------------------------------------- 1047: // From the reference (bind) pose, which is the T-pose: each upper arm (and for "up" the collarbone) turns about the 1048: // body's front axis. Which way lowers an arm is read from where its hand points, so no bone's rest angle is assumed. 1049: const POSES = { up: { arm: -78, shoulder: -14 }, out: { arm: 0, shoulder: 0 }, down: { arm: 74, shoulder: 0 } }; 1050: const v3 = () => new THREE.Vector3(), q4 = () => new THREE.Quaternion(); 1051: function armSide(c, side) { // +1 when the arm points along the model's +x 1052: if (!c.armSide) { 1053: c.skeleton && c.skeleton.pose(); c.root.updateMatrixWorld(true); 1054: const inv = c.root.matrixWorld.clone().invert(), at = n => c.root.getObjectByName(n)?.getWorldPosition(v3()).applyMatrix4(inv); 1055: c.armSide = Object.fromEntries(["L", "R"].map(s => { const a = at(`J_Bip_${s}_UpperArm`), h = at(`J_Bip_${s}_Hand`); 1056: return [s, a && h ? Math.sign(h.x - a.x) || 1 : 1]; })); 1057: } 1058: return c.armSide[side]; 1059: } 1060: function turnBone(c, name, deg) { // about the model's front axis, at the bone's own joint 1061: const b = c.root.getObjectByName(name); 1062: if (!b || !deg) return; 1063: const axis = new THREE.Vector3(0, 0, 1).applyQuaternion(c.root.getWorldQuaternion(q4())) 1064: .applyQuaternion(b.parent.getWorldQuaternion(q4()).invert()); 1065: b.quaternion.premultiply(q4().setFromAxisAngle(axis, THREE.MathUtils.degToRad(deg))); 1066: b.updateMatrixWorld(true); 1067: } 1068: function applyPose(c) { 1069: const p = POSES[state.pose] || POSES.out; 1070: if (!p.arm && !p.shoulder) return; 1071: c.root.updateMatrixWorld(true); 1072: for (const s of ["L", "R"]) { 1073: const k = -armSide(c, s); // turning +x toward +y raises it: lowering is the other way 1074: turnBone(c, `J_Bip_${s}_Shoulder`, k * p.shoulder); 1075: turnBone(c, `J_Bip_${s}_UpperArm`, k * p.arm); 1076: } 1077: } 1078: // ---- motion and spring bones ---------------------------------------------------------------------------------------- 1079: // The armory's bodies stand still; Bounce bobs the hips as a jog's footfalls do and Twist turns the upper body side 1080: // to side, so the spring bones (VRoid's breasts, on the women) show how they move 1081: function applyMotion(c, dt) { 1082: c.motionT = (c.motionT || 0) + dt; 1083: const t = c.motionT; 1084: if (state.motion === "bounce") { 1085: const hips = c.root.getObjectByName("J_Bip_C_Hips"); 1086: if (hips) { hips.position.y += 0.035 * Math.abs(Math.sin(Math.PI * 2.4 * t)); hips.updateMatrixWorld(true); } 1087: } else if (state.motion === "twist") { 1088: const spine = c.root.getObjectByName("J_Bip_C_Spine"); 1089: if (spine) { 1090: const axis = new THREE.Vector3(0, 1, 0).applyQuaternion(spine.parent.getWorldQuaternion(q4()).invert()); 1091: spine.quaternion.premultiply(q4().setFromAxisAngle(axis, THREE.MathUtils.degToRad(22) * Math.sin(2 * Math.PI * 0.9 * t))); 1092: spine.updateMatrixWorld(true); 1093: } 1094: } 1095: } 1096: // VRM 0.x spring bones as UniVRM runs them: each joint's tail keeps its momentum (less the drag), is pulled back 1097: // toward where the pose holds it (stiffness) and down (gravity), and stays its length from the joint; the bone 1098: // then turns to point at it. A bone with no child gets a tail 7 cm on along its own line (UniVRM's rule) 1099: function makeSprings(c, groups) { 1100: const joints = []; 1101: if (!groups || !groups.length) return joints; 1102: c.skeleton && c.skeleton.pose(); c.root.updateMatrixWorld(true); 1103: for (const g of groups) { // collision spheres: a bone, an offset in its frame (turned as the export 1104: g.spheres = (g.colliders || []).map(s => ({ bone: c.root.getObjectByName(s.bone), // turns the model) 1105: offset: new THREE.Vector3(-s.offset[0], s.offset[1], -s.offset[2]), radius: s.radius })).filter(s => s.bone); 1106: } 1107: for (const g of groups) for (const rootName of g.bones) { 1108: const root = c.root.getObjectByName(rootName); 1109: if (!root) continue; 1110: root.traverse(b => { 1111: if (!b.isBone) return; 1112: const child = b.children.find(k => k.isBone); 1113: const head = b.getWorldPosition(v3()); 1114: const tailW = child ? child.getWorldPosition(v3()) 1115: : head.clone().add(head.clone().sub(b.parent.getWorldPosition(v3())).normalize().multiplyScalar(0.07)); 1116: const tailL = b.worldToLocal(tailW.clone()); 1117: joints.push({ b, rest: b.quaternion.clone(), axis: tailL.clone().normalize(), tailL, len: head.distanceTo(tailW), 1118: g, grav: new THREE.Vector3(...(g.gravity_dir || [0, -1, 0])).normalize(), cur: null, prev: null, at: null }); 1119: }); 1120: } 1121: return joints; 1122: } 1123: function stepSprings(c, dt) { 1124: const head = v3(), pq = q4(), m = q4(); 1125: if (!c.springsSettled) { // the first frames: hair settles under its springs before it can be seen 1126: c.springsSettled = true; // swinging in from its modelled shape (the probe ignores these) 1127: for (let s = 0; s < 120; s++) stepSprings(c, 1 / 120); 1128: c.springMax = 0; 1129: } 1130: for (const j of c.springs) { 1131: const b = j.b; 1132: b.quaternion.copy(j.rest); b.updateMatrixWorld(true); 1133: b.getWorldPosition(head); 1134: b.parent.getWorldQuaternion(pq); 1135: // first frame, or the body jumped (a new layout): start at rest 1136: if (!j.cur || j.at.distanceTo(head) > 0.25) { j.cur = b.localToWorld(j.tailL.clone()); j.prev = j.cur.clone(); } 1137: j.at = head.clone(); 1138: const restDir = j.axis.clone().applyQuaternion(pq.clone().multiply(j.rest)); 1139: const next = j.cur.clone().add(j.cur.clone().sub(j.prev).multiplyScalar(1 - j.g.drag)) 1140: .addScaledVector(restDir, j.g.stiffness * dt).addScaledVector(j.grav, j.g.gravity * dt); 1141: next.sub(head).setLength(j.len).add(head); 1142: for (const s of j.g.spheres || []) { // out of each collision sphere (the tail's own radius added) 1143: const cp = s.bone.localToWorld(s.offset.clone()), r = s.radius + (j.g.radius || 0), d = next.distanceTo(cp); 1144: if (d < r) next.sub(cp).setLength(r).add(cp).sub(head).setLength(j.len).add(head); 1145: } 1146: j.prev.copy(j.cur); j.cur.copy(next); 1147: const to = next.clone().sub(head).applyQuaternion(m.copy(pq).multiply(j.rest).invert()).normalize(); 1148: b.quaternion.copy(j.rest).multiply(q4().setFromUnitVectors(j.axis, to)); 1149: b.updateMatrixWorld(true); 1150: c.springMax = Math.max(c.springMax || 0, THREE.MathUtils.radToDeg(2 * Math.acos(Math.min(1, Math.abs(b.quaternion.dot(j.rest)))))); 1151: } 1152: } 1153: // side by side: each model gets room to turn in place in the current pose (its posed skin's reach round its own 1154: // axis), and the frame fits the row and the tallest reach (raised hands) 1155: const COMPARE = { frame: { w: 2.0, top: 1.6, bottom: -1.3 }, room: [] }; 1156: function layoutCompare() { 1157: const cs = active(), gap = 0.15, rooms = [], p = v3(), m4 = new THREE.Matrix4(); 1158: let top = 0; 1159: for (const c of cs) { 1160: c.skeleton && c.skeleton.pose(); applyPose(c); c.root.updateMatrixWorld(true); c.skeleton && c.skeleton.update(); 1161: const inv = c.root.matrixWorld.clone().invert(); 1162: let r = 0; 1163: for (const m of c.meshes) { 1164: const pos = m.geometry.attributes.position, step = Math.max(1, Math.floor(pos.count / 6000)); 1165: m4.multiplyMatrices(inv, m.matrixWorld); 1166: for (let i = 0; i < pos.count; i += step) { 1167: m.getVertexPosition(i, p).applyMatrix4(m4); 1168: r = Math.max(r, Math.hypot(p.x, p.z)); top = Math.max(top, p.y); 1169: } 1170: } 1171: rooms.push(r + 0.04); 1172: } 1173: const total = rooms.reduce((a, r) => a + 2 * r + gap, -gap); 1174: let x = -total / 2; 1175: cs.forEach((c, i) => { c.turn.position.set(x + rooms[i], 0, 0); x += 2 * rooms[i] + gap; }); 1176: COMPARE.room = rooms; 1177: COMPARE.frame = { w: Math.max(2.0, total + 0.2), top: Math.max(1.0, top - 1.0 + 0.1), bottom: -1.32 }; 1178: } 1179: function placeTags() { // the names under the feet 1180: const box = $("tags"); 1181: if (state.view !== "compare" || SHEET) { if (box.childElementCount) box.textContent = ""; return; } 1182: const cs = active(); 1183: if (box.childElementCount !== cs.length) { box.textContent = ""; cs.forEach(() => box.appendChild(document.createElement("span"))); } 1184: const W = stageEl.clientWidth, H = stageEl.clientHeight, mpp = (camera.right - camera.left) / camera.zoom / Math.max(1, W); 1185: cs.forEach((c, i) => { 1186: const el = box.children[i], label = charDef(c.name).label; 1187: if (el.textContent !== label) el.textContent = label; 1188: const p = c.turn.getWorldPosition(v3()); p.y = -0.03; p.project(camera); 1189: el.style.left = `${(p.x + 1) / 2 * W}px`; el.style.top = `${(1 - p.y) / 2 * H + 6}px`; 1190: el.style.maxWidth = `${Math.max(70, 2 * (COMPARE.room[i] || 0.5) / mpp - 10)}px`; 1191: }); 1192: } 1193: function compareChanged() { // the comparison is in the link, to share it 1194: const u = new URL(location.href); 1195: u.searchParams.set("view", "compare"); u.searchParams.set("compare", state.compare.join(",")); u.searchParams.set("pose", state.pose); 1196: try { history.replaceState(null, "", u); } catch (e) { /* a sandboxed page may refuse: the view still changes */ } 1197: setView("compare"); 1198: } 1199:1 more lines not shown.