"""v9 condition images. For every frame of a run: cond.png = semantic palette for the scene classes, and the player / boss (class 10 / 11, capsules in the v9 labels) shaded by code from the per-frame capsule segments, tinted per role. usage: cond_v9.py RUN_DIR [--preview OUT.mp4 SECONDS] [--every N]""" import os, sys, glob, json, subprocess, shutil import numpy as np from PIL import Image, ImageDraw, ImageFont from concurrent.futures import ThreadPoolExecutor PAL = np.array([[18, 20, 26], [122, 156, 92], [196, 186, 160], [182, 98, 72], [128, 120, 132], [52, 128, 60], [214, 168, 52]] + [[0, 0, 0]] * 3 + [[80, 150, 255], [255, 80, 70]] + [[255, 0, 255]] * 244, np.uint8) TINT = {10: np.array([0.62, 0.80, 1.0]), 11: np.array([1.0, 0.66, 0.60])} SIDE = {'l_': 0.80, 'r_': 1.0} def cap_hit(ro, rd, a, b, r): """ray / capsule intersection (vectorised over rays); returns t (inf = miss)""" ba = b - a; oa = ro - a; baba = ba @ ba; bard = rd @ ba; baoa = oa @ ba; rdoa = np.einsum('ij,ij->i', rd, oa); oaoa = np.einsum('ij,ij->i', oa, oa) A = baba - bard * bard; B = baba * rdoa - baoa * bard; C = baba * oaoa - baoa * baoa - r * r * baba h = B * B - A * C; t = np.full(len(ro), np.inf) ok = (h >= 0) & (np.abs(A) > 1e-9) t1 = np.where(ok, (-B - np.sqrt(np.maximum(h, 0))) / np.where(np.abs(A) > 1e-9, A, 1), np.inf); y = baoa + t1 * bard body = ok & (y > 0) & (y < baba); t = np.where(body, t1, t) for end in (a, b): # sphere caps oc = ro - end; bb = np.einsum('ij,ij->i', rd, oc); cc = np.einsum('ij,ij->i', oc, oc) - r * r; hh = bb * bb - cc ts = np.where(hh > 0, -bb - np.sqrt(np.maximum(hh, 0)), np.inf); t = np.minimum(t, np.where(ts > 0, ts, np.inf)) return t def char_shading(ids, J): """shade the capsule characters by code from the per-frame capsule segments (same geometry as the labels): orthographic view rays from world_to_clip, nearest capsule hit, lambert + ambient from a light fixed in view space, left limbs slightly darker so the pose reads. Returns (H, W) shade in 0..1 for class 10 / 11 pixels.""" H, W = ids.shape; m = (ids == 10) | (ids == 11); shade = np.zeros((H, W)); caps = [] for ch in ((J.get('v9') or {}).get('characters') or []): for c in ch['capsules']: k = 0.88 if c['name'] == 'weapon' else SIDE.get(c['name'][:2], 1.0) caps.append((np.array(c['a'], float), np.array(c['b'], float), float(c['r']), k)) if not m.any() or not caps: return shade, m M = np.array(J['world_to_clip'], float).reshape(4, 4); Mi = np.linalg.inv(M) V = np.array(J['world_to_view'], float).reshape(4, 4) vy, vx = np.nonzero(m); nx = ((vx + 0.5) / W - 0.5) * 2; ny = (0.5 - (vy + 0.5) / H) * 2 def unproj(z): p = np.stack([nx, ny, np.full_like(nx, z), np.ones_like(nx)], 1) @ Mi; return p[:, :3] / p[:, 3:4] p0, p1 = unproj(0.9), unproj(0.1); rd = p1 - p0; rd /= np.linalg.norm(rd, axis=1, keepdims=True) fwd = V[:3, 2] / np.linalg.norm(V[:3, 2]) # world direction of the view forward axis (row-vector convention) if (rd @ fwd).mean() < 0: rd = -rd ro = p0 - rd * 5000.0 best = np.full(len(ro), np.inf); kk = np.ones(len(ro)); nn = np.zeros((len(ro), 3)) for a, b, r, k in caps: t = cap_hit(ro, rd, a, b, r); w = t < best if w.any(): best[w] = t[w]; kk[w] = k; P = ro[w] + rd[w] * t[w, None]; ba = b - a hseg = np.clip(((P - a) @ ba) / max(ba @ ba, 1e-6), 0, 1); n = P - a - hseg[:, None] * ba; nn[w] = n / np.maximum(np.linalg.norm(n, axis=1, keepdims=True), 1e-6) right, up = V[:3, 0] / np.linalg.norm(V[:3, 0]), V[:3, 1] / np.linalg.norm(V[:3, 1]) L = -0.45 * right + 0.55 * up - 0.70 * fwd; L /= np.linalg.norm(L) lam = np.clip(nn @ L, 0, 1); s = np.where(np.isfinite(best), (0.30 + 0.70 * lam) * kk, 0.62) shade[vy, vx] = s; return shade, m def cond(ids, J): out = PAL[ids].astype(np.float32) shade, m = char_shading(ids, J) for c, t in TINT.items(): mc = ids == c if mc.any(): out[mc] = np.clip(shade[mc, None] * 1.1, 0, 1) * t * 255.0 return np.clip(out, 0, 255).astype(np.uint8) def one(base): ids = np.asarray(Image.open(base + '.ids.png')); ids = ids[..., 0] if ids.ndim == 3 else ids c = cond(ids, json.load(open(base + '.json'))) Image.fromarray(c).save(base + '.cond.png', optimize=False, compress_level=3) return base def clip_index(run, bases): """81-frame training clips on the v9 cut grid: starts at multiples of cut_grid (96); a clip is kept only if all 81 frames share look, camera variant and episode and the player never jumps > 4 m between frames (unscheduled teleports).""" cr = json.load(open(os.path.join(run, 'capture_result.json'), encoding='utf-8')); v9 = cr.get('v9') or {} G = int(v9.get('cut_grid', 96)); n = len(bases) def meta(b): j = json.load(open(b + '.json')); a = {x['role']: x for x in j.get('actors', [])} return ((j.get('v9') or {}).get('look'), j.get('camera_variant'), j.get('episode'), (a.get('player') or {}).get('position_cm')) with ThreadPoolExecutor(8) as ex: M = list(ex.map(meta, bases)) keep, drop = [], [] for s in range(0, n - 80, G): w = M[s:s + 81]; ok = len({(m[0], m[1], m[2]) for m in w}) == 1 if ok: for a, b in zip(w, w[1:]): if a[3] and b[3] and np.linalg.norm(np.array(a[3]) - np.array(b[3])) > 400: ok = False; break (keep if ok else drop).append({'start': s, 'end': s + 80, 'look': w[0][0], 'camera_variant': w[0][1], 'episode': w[0][2]}) looks = {l['index']: l['name'] for l in v9.get('look_log', [])} for c in keep: c['look_name'] = looks.get(c['look'], '') json.dump({'clip_frames': 81, 'cut_grid': G, 'rule': 'clips start at multiples of cut_grid; looks / cameras / episodes only change between frame k*cut_grid+%d and the next' % v9.get('cut_phase', 80), 'clips': keep, 'dropped': drop}, open(os.path.join(run, 'clips_81_v9.json'), 'w'), indent=1) print('clips kept', len(keep), 'dropped', len(drop), flush=True) def main(): run = sys.argv[1]; every = 1 if '--every' in sys.argv: every = int(sys.argv[sys.argv.index('--every') + 1]) bases = sorted(p[:-8] for p in glob.glob(os.path.join(run, 'raw', '[0-9]' * 6 + '.ids.png')))[::every] with ThreadPoolExecutor(8) as ex: list(ex.map(one, bases)) print('cond frames', len(bases), flush=True) if every == 1: clip_index(run, bases) if '--preview' in sys.argv: k = sys.argv.index('--preview'); out = sys.argv[k + 1]; sec = float(sys.argv[k + 2]) tmp = out + '_tmp'; shutil.rmtree(tmp, ignore_errors=True); os.makedirs(tmp) try: F = ImageFont.truetype('C:/Windows/Fonts/msyh.ttc', 22) except Exception: F = ImageFont.load_default() sel = bases[:int(sec * 16)] def pv(a): i, b = a rgb = Image.open(b + '.jpg').convert('RGB').resize((960, 528), Image.LANCZOS); cd = Image.open(b + '.cond.png').convert('RGB').resize((960, 528), Image.NEAREST) j = json.load(open(b + '.json')); nm = (j.get('v9') or {}).get('look_name', '') fr = Image.new('RGB', (1928, 576), (10, 10, 14)); fr.paste(rgb, (0, 48)); fr.paste(cd, (968, 48)); d = ImageDraw.Draw(fr) d.text((14, 10), 'RGB · ' + nm, font=F, fill=(255, 214, 110)); d.text((982, 10), 'cond(场景语义 + 胶囊白膜角色) · ortho %.0f cm' % j.get('ortho_width_cm', 0), font=F, fill=(200, 200, 210)) fr.save(os.path.join(tmp, '%05d.jpg' % i), quality=90) with ThreadPoolExecutor(8) as ex: list(ex.map(pv, enumerate(sel))) subprocess.run(['ffmpeg', '-y', '-loglevel', 'error', '-framerate', '16', '-i', os.path.join(tmp, '%05d.jpg'), '-c:v', 'libx264', '-crf', '22', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', out]) shutil.rmtree(tmp, ignore_errors=True); print('preview', out) main()