File size: 37,882 Bytes
9d8a713
a54e6a7
 
 
 
9d8a713
a54e6a7
 
 
 
 
 
 
 
9d8a713
a54e6a7
 
 
 
 
9d8a713
 
a54e6a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d8a713
a54e6a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d8a713
a54e6a7
 
 
 
 
 
 
 
 
 
9d8a713
a54e6a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d8a713
a54e6a7
 
 
 
 
 
 
 
 
 
9d8a713
a54e6a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d8a713
a54e6a7
 
 
 
9d8a713
a54e6a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
"""10-17 (user: v7 条件,开始编码数据) the v7 condition of every training window -> /data/yuzhewu/datasets/windows/proxy/clip_<key>.pt
  cond  [48,31,30,52] bf16   VAE latent of the v7 condition video (832x480 crop)
  dep   [121,60,104] f16     planar depth (m) at the cell centres for the token coordinates (0 = none: sky / characters)
  tier  [121,60,104] u8      0 sky | 1 unknown | 2 coarse | 3 exact (token tier channel; characters' cells carry nothing via dep = 0)
  meta  dict                 source, variant (moge / holes / patch), normals
Encoding (proxy_encode.py): R height, B depth (v5), skeleton on top with a black outline (+ the player's shield disc), G = tier, exact G modulated by normals.
Sources (tier by where the geometry comes from):
  ww    exact   WildWorld 8-bit depth (sigma 5), characters = silhouette_mask, background behind them from other frames
  bk    exact   Black Knife raw depth_packed (lossless), characters = capsules of shot.npz, other frames
  roam  exact   memroam windows: capture.mkv depth, player capsules (prep_mem), skeleton layer = prep_mem.Skel, R/B built here
  synth exact   ground plane (analytic) + the v5 props; above the horizon: sky (MoGe-2 by direction) / unknown
  er,ue coarse  the BOSSV2V proxy geometry of the v5 condition, black = sky (MoGe-2) / unknown
Variants (fixed per window by its key): 30% MoGe-2 first-frame world (coarse; outside it unknown; exact sources: 50% of them get a world-anchored exact patch),
15% time-spanning holes (unknown), normals off for 20%.
   build_proxy.py <source> --rank R --world N [--limit K] [--preview]"""
import sys, os, json, gzip, hashlib, argparse, subprocess, time
import numpy as np, cv2, torch
import torch.nn.functional as F
sys.path.insert(0, "/data/yuzhewu/runs/v7demo"); sys.path.insert(0, "/data/yuzhewu/wancond_mem"); sys.path.insert(0, "/data/yuzhewu/wancond")
sys.path.insert(0, "/data/yuzhewu/datasets/wildworld"); sys.path.insert(0, "/data/yuzhewu/runs/proxykit")
import proxy_encode as E
DS = "/data/yuzhewu/datasets"; OUT = f"{DS}/windows"; CK = "/data/yuzhewu/models/Wan2.2-TI2V-5B"; N = 121; W8, H8, X0 = 853, 480, 10
GV, GU = np.mgrid[0:60, 0:104]; CV, CU = 8 * GV + 4, 8 * GU + 4 + X0                 # cell centres in the 853x480 frame
NB = (-60, -40, -25, -12, 12, 25, 40, 60)                                               # other frames for the background behind the characters
PAR17 = [-1, 0, 1, 2, 3, 2, 5, 6, 2, 8, 9, 0, 11, 12, 0, 14, 15]
key_of = lambda v: hashlib.md5(v.encode()).hexdigest()[:16]
def u100(key, salt): return int(hashlib.md5((key + salt).encode()).hexdigest(), 16) % 100

def ff(path, start, n, w=None, h=None, fmt="rgb24", scale=None):
    """frames [start, start+n) of a video -> uint8/uint16 array"""
    vf = f"select='between(n\\,{start}\\,{start + n - 1})'" + (f",scale={scale[0]}:{scale[1]}:flags=area" if scale else "")
    if w is None or scale:
        if scale: w, h = scale
        else: w, h = map(int, subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "csv=p=0", path], capture_output=True, text=True).stdout.strip().split(",")[:2])
    raw = subprocess.run(["ffmpeg", "-v", "error", "-i", path, "-vf", vf, "-vsync", "0", "-f", "rawvideo", "-pix_fmt", fmt, "-"], capture_output=True).stdout
    dt = np.uint16 if fmt == "rgb48le" else np.uint8; a = np.frombuffer(raw, dt)
    return a.reshape(-1, h, w, 3)[:n]
def r853(x, interp=cv2.INTER_AREA): return cv2.resize(x, (W8, H8), interpolation=interp)
def z853(z, ok):
    """planar depth -> 853x480 by AREA in disparity (nearest aliases into a grid in the normals); 0 where mostly invalid"""
    d = np.where(ok, 1.0 / np.maximum(z, 1e-3), 0).astype(np.float32); w = ok.astype(np.float32)
    d = cv2.resize(d, (W8, H8), interpolation=cv2.INTER_AREA); w = cv2.resize(w, (W8, H8), interpolation=cv2.INTER_AREA); good = w > 0.5
    return np.where(good, 1.0 / np.maximum(d / np.maximum(w, 1e-6), 1e-6), 0.0), good

class Models:
    def __init__(self):
        from wanvendor.vae2_2 import Wan2_2_VAE
        self.vae = Wan2_2_VAE(vae_pth=f"{CK}/Wan2.2_VAE.pth", device="cuda"); self.moge = None
    def mg(self, im):
        if self.moge is None:
            from moge.model.v2 import MoGeModel; self.moge = MoGeModel.from_pretrained("Ruicheng/moge-2-vitl-normal").to("cuda").eval()
        with torch.no_grad(): o = self.moge.infer(torch.from_numpy(np.ascontiguousarray(im)).permute(2, 0, 1).float().div(255).cuda())
        return o["points"].cpu().numpy().astype(np.float64), o["mask"].cpu().numpy().astype(bool)
    def encode(self, v):                                                                # [121,480,832,3] uint8 (numpy or cuda) -> [48,31,30,52]
        if isinstance(v, np.ndarray): v = torch.from_numpy(np.ascontiguousarray(v))
        x = v.cuda().permute(3, 0, 1, 2).float().div(127.5).sub(1.0)
        with torch.no_grad(): return self.vae.encode([x])[0].to(torch.bfloat16).cpu()

# ------------------------------------------------------------------ geometry helpers (853x480, cam = (pos, Rrows right/up/forward, f, cx, cy), y up, metres)
def world_pts(cam, z):
    pos, R, f, cx, cy = cam; v, u = np.mgrid[0:z.shape[0], 0:z.shape[1]] + 0.5
    return pos + ((u - cx) / f * z)[..., None] * R[0] - ((v - cy) / f * z)[..., None] * R[1] + z[..., None] * R[2]
def capsules(cam, J, rad, shape, par=PAR17):
    """character mask from joints [n,3] (world): bones as thick lines of radius rad (m) in perspective"""
    pos, R, f, cx, cy = cam; rel = J - pos; X, Y, Zc = rel @ R[0], rel @ R[1], rel @ R[2]; m = np.zeros(shape, np.uint8)
    for j, p in enumerate(par):
        if p is None or not (np.isfinite(J[j]).all() and np.isfinite(J[p]).all()): continue
        if p < 0 or Zc[j] < 0.2 or Zc[p] < 0.2: continue
        a = (int(cx + f * X[j] / Zc[j]), int(cy - f * Y[j] / Zc[j])); b = (int(cx + f * X[p] / Zc[p]), int(cy - f * Y[p] / Zc[p]))
        wpx = max(3, int(round(f * rad / min(Zc[j], Zc[p])))); cv2.line(m, a, b, 1, 2 * wpx); cv2.circle(m, a, wpx, 1, -1)
    return m.astype(bool)
def fill_chars(Z, valid, CH, cams):
    """depth behind the characters: other frames reprojected (proxy_encode.temporal_fill), then the smooth fill"""
    out = []
    for t in range(len(Z)):
        m = CH[t] & valid[t]; z = Z[t]
        if m.any():
            srcs = [(cams[t + d], Z[t + d], valid[t + d] & ~CH[t + d]) for d in NB if 0 <= t + d < len(Z)]
            z, got = E.temporal_fill(cams[t], np.where(m, 0, z), m, srcs); m = m & ~got
            z = E.fill_under(z, m, valid[t] | CH[t])
        out.append(z)
    return np.stack(out)
def height_fit(V5, Z, valid, cams):
    """the v5 R = a * (world height) + b on the environment of frame 0 (each source has its own range / origin)"""
    P = world_pts(cams[0], Z[0]); r = V5[0][..., 0].astype(float) / 255; ok = valid[0] & (r > 0.52) & (r < 0.98) & (V5[0][..., 1] < 20)
    if ok.sum() < 500: return 0.5 / 56, 0.5 + 0.5 * 8 / 56
    A = np.stack([P[..., 1][ok], np.ones(ok.sum())], 1); a, b = np.linalg.lstsq(A, r[ok], rcond=None)[0]; return a, b
def rb_from(z, cam, ab):
    P = world_pts(cam, z); R_ = np.clip(ab[0] * P[..., 1] + ab[1], 0.5, 1.0); B_ = 1 - np.clip((z - 0.1) / 79.9, 0, 1); return R_, B_

# ------------------------------------------------------------------ the shared core
def core(key, src, V5, Z, valid, sky, CH, cams, exact_src, sig, rgb0, M, shield=None, ab=None, tier0=None):
    """V5 [121,480,853,3] (characters drawn), Z planar depth (0 = none), valid geometry, sky, CH characters (excluded from geometry),
    tier0: optional base tier map (synth). GPU (v7gpu.py). Returns v7 frames (cuda uint8 [121,480,832,3]), dep cells, tier cells, meta."""
    import v7gpu as G
    dev = "cuda"; moge = u100(key, "moge") < 30; holes = u100(key, "holes") < 15; normals = u100(key, "nrm") >= 20; patch = exact_src and moge and u100(key, "patch") < 50
    pos = torch.tensor(np.stack([c[0] for c in cams]), dtype=torch.float32, device=dev); R = torch.tensor(np.stack([c[1] for c in cams]), dtype=torch.float32, device=dev)
    f, cx, cy = float(cams[0][2]), float(cams[0][3]), float(cams[0][4])
    Zt = torch.from_numpy(np.ascontiguousarray(Z)).float().to(dev); vt = torch.from_numpy(valid).to(dev); skt = torch.from_numpy(sky).to(dev); cht = torch.from_numpy(CH).to(dev)
    if exact_src: Zf, miss = G.temporal_fill(Zt, vt, cht, pos, R, f, cx, cy); Zf = G.fill_rest(Zf, miss, vt)
    else: Zf = Zt
    if tier0 is not None: tier = torch.from_numpy(tier0).to(dev)
    else: tier = torch.where(vt, torch.full_like(Zt, 3 if exact_src else 2), torch.where(skt, torch.zeros_like(Zt), torch.ones_like(Zt))).to(torch.uint8)
    Zc = Zf; RB = None; pm = None
    if moge:                                                                             # the inference world: MoGe-2 of the first frame along the true cameras
        Zf0 = Zf[0].cpu().numpy().astype(np.float64)
        P, ok = M.mg(rgb0); sel = valid[0] & ok & ~CH[0]
        s = float(np.median((Z[0][sel] + 1e-6) / (P[..., 2][sel] + 1e-6))) if sel.sum() > 500 else 1.0
        chm = cv2.dilate(CH[0].astype(np.uint8), np.ones((15, 15), np.uint8)).astype(bool)
        near = valid[0] & (s * P[..., 2] < 0.9 * Zf0 - 0.3)                            # (10-18) nearer than the environment = a character (bodies are wider than skeleton lines)
        g0 = V5[0][..., 1].astype(int); hull = np.zeros((H8, W8), np.uint8)               # and each character's skeleton hull (a boss against the sky has no environment behind it)
        for slot in np.unique(g0[g0 >= 20] // 32):
            ys, xs = np.nonzero((g0 >= 20) & (g0 // 32 == slot))
            if len(xs) >= 3: cv2.fillConvexPoly(hull, cv2.convexHull(np.stack([xs, ys], 1).astype(np.int32)), 1)
        near |= cv2.dilate(hull, np.ones((61, 61), np.uint8)).astype(bool)
        chm |= cv2.dilate(near.astype(np.uint8), np.ones((9, 9), np.uint8)).astype(bool); okm = ok & ~chm & np.isfinite(P).all(-1)
        fillm = chm & ~char_fill(~ok, chm)                                               # the characters' pixels whose surroundings are ground / walls (not sky): fill those only
        zM = np.where(okm, s * P[..., 2], 0.0); zM = E.fill_under(zM, fillm, okm | fillm); okm = okm | fillm
        Pw = world_pts(cams[0], zM); st = 2; Q = Pw[::st, ::st]; mm = okm[::st, ::st]; dd = zM[::st, ::st]; idx = np.arange(mm.size).reshape(mm.shape)
        a_, b_, c_, d_ = idx[:-1, :-1], idx[:-1, 1:], idx[1:, :-1], idx[1:, 1:]; D4 = np.stack([dd[:-1, :-1], dd[:-1, 1:], dd[1:, :-1], dd[1:, 1:]])
        g = mm[:-1, :-1] & mm[:-1, 1:] & mm[1:, :-1] & mm[1:, 1:] & (D4.max(0) < 1.12 * D4.min(0))
        F_ = np.concatenate([np.stack([a_[g], b_[g], c_[g]], 1), np.stack([b_[g], d_[g], c_[g]], 1)]); Vm = Q.reshape(-1, 3)[F_].reshape(-1, 3).astype("f4")
        zc = G.splat_grid(torch.from_numpy(Pw).float().to(dev), torch.from_numpy(okm).to(dev), pos, R, f, cx, cy, H8, W8)   # GPU surface splat (EGL in many processes aborts: exit 134)
        if ab is None: ab = height_fit(V5, Zf.cpu().numpy(), valid, cams)
        ray = G.rays(N, H8, W8, f, cx, cy, R, dev); Py = (pos[:, None, None] + zc[..., None] * ray)[..., 1]
        RB = ((ab[0] * Py + ab[1]).clamp(0.5, 1.0), 1 - ((zc - 0.1) / 79.9).clamp(0, 1)); cov = zc > 0
        skyd = torch.from_numpy(sky_dirs(cams, char_fill(~ok, cv2.dilate(chm.astype(np.uint8), np.ones((15, 15), np.uint8)).astype(bool)))).to(dev)                      # what inference knows: sky = directions frame 0 saw as sky
        skyd &= ~(vt & ~cht)                                                              # (10-18) sky only where the truth has no geometry: a big boss's char_fill must not call the ruins behind it sky
        tier = torch.where(cov, torch.full_like(tier, 2), torch.where(skyd, torch.zeros_like(tier), torch.ones_like(tier))); Zc = torch.where(cov, zc, Zf)
        if patch:                                                                         # a world-anchored exact block round a ground point of frame 0 (an agent's object)
            yy, xx = int(H8 * 0.68), W8 // 2
            if valid[0][yy, xx]:
                Pf = pos[:, None, None] + Zf[..., None] * ray; pc = Pf[0, yy, xx]; half = torch.tensor([2.0, 2.5, 2.0], device=dev)
                pm = ((Pf - pc).abs() < half).all(-1) & vt; tier[pm] = 3; Zc = torch.where(pm, Zf, Zc)
    if holes:                                                                           # 1-3 ellipses, each over a contiguous span of frames
        rng = np.random.default_rng(int(key, 16) % 2 ** 32); hm = np.zeros((N, H8, W8), bool)
        for _ in range(int(rng.integers(1, 4))):
            t0 = int(rng.integers(0, 80)); t1 = int(rng.integers(t0 + 40, N + 1)); cx_, cy_ = int(rng.integers(100, 750)), int(rng.integers(80, 400))
            ax_ = (int(rng.integers(60, 220)), int(rng.integers(40, 160))); m = np.zeros((H8, W8), np.uint8); cv2.ellipse(m, (cx_, cy_), ax_, float(rng.uniform(0, 180)), 0, 360, 1, -1)
            hm[t0:t1] |= m.astype(bool)[None]
        hm = torch.from_numpy(hm).to(dev); tier = torch.where(hm & (tier != 0), torch.ones_like(tier), tier)
    if os.environ.get("MEMUNK") == "1":                                                # (10-19 user: 必须看记忆的窗口一定比例给未知) the whole environment unknown in the VIDEO; the cells keep their depth -> tokens keep coordinates
        tier = torch.where(tier != 0, torch.ones_like(tier), tier); meta_memunk = True
    if shield is not None: V5 = np.stack([E.draw_shield_853(V5[t], shield[t]) if np.isfinite(shield[t][0]) else V5[t] for t in range(N)])
    V5t = torch.from_numpy(np.ascontiguousarray(V5)).to(dev)
    if RB is not None:                                                                  # the coarse MoGe world's R / B (the patch and the characters keep theirs)
        keep = (V5t[..., 1] >= 20) | (pm if pm is not None else torch.zeros_like(vt))
        V5t[..., 0] = torch.where(keep, V5t[..., 0], torch.round(RB[0] * 255).to(torch.uint8)); V5t[..., 2] = torch.where(keep, V5t[..., 2], torch.round(RB[1] * 255).to(torch.uint8))
    ex = tier == 3
    sh = G.shade(torch.where(ex, Zf, Zc), ex, R, f, cx, cy, sig * W8 / 1280) if normals else torch.full_like(Zt, 0.5)
    out = G.compose(V5t, tier, sh)[:, :, X0:X0 + 832]
    cvi = torch.from_numpy(CV).to(dev); cui = torch.from_numpy(CU).to(dev)
    chc = F.max_pool2d(cht[:, None].float(), 9, 1, 4)[:, 0] > 0
    zc_ = torch.where(chc | (tier == 0), torch.zeros_like(Zc), Zc)
    zc_ = torch.where(torch.isfinite(zc_) & (zc_ < 1000), zc_, torch.zeros_like(zc_))           # f16 cells: nothing past 1 km
    dep = zc_[:, cvi, cui].half().cpu().numpy(); tc = tier[:, cvi, cui].cpu().numpy()
    return out, dep, tc, dict(src=src, moge=moge, holes=holes, patch=bool(patch and pm is not None), normals=normals)

_ctx = {}
class egl_lock:
    """one EGL user per card at a time: many processes rendering on one card stall in the driver's lock (os_acquire_rwlock) and abort (exit 134)"""
    def __enter__(self):
        import fcntl; self.f = open(f"/tmp/v7_egl_{os.environ.get('EGL', '0')}.lock", "w"); fcntl.flock(self.f, fcntl.LOCK_EX); return self
    def __exit__(self, *a):
        import fcntl; fcntl.flock(self.f, fcntl.LOCK_UN); self.f.close()

def render_mesh(Vm, cams):
    with egl_lock(): return _render_mesh(Vm, cams)

def _render_mesh(Vm, cams):
    import moderngl
    if True:                                                                             # a fresh context per call: Skel's renderer can invalidate a cached one
        ctx = moderngl.create_standalone_context(backend="egl", require=330, device_index=int(os.environ.get("EGL", "0"))); ctx.enable(moderngl.DEPTH_TEST)
        prog = ctx.program(vertex_shader="""#version 330
uniform vec3 cf, cr, cu, cpos; uniform float foc, ox, oy, hw, hh; in vec3 pos; out float fd;
void main(){ vec3 d = pos - cpos; float z = dot(d, cf); fd = z; float n = 0.05, f = 5000.0;
gl_Position = vec4((foc * dot(d, cr) + ox * z) / hw, (foc * dot(d, cu) + oy * z) / hh, z * (f + n) / (f - n) - 2.0 * f * n / (f - n), z); }""",
                           fragment_shader="#version 330\nin float fd; out float o; void main(){ o = fd; }")
        fbo = ctx.framebuffer(color_attachments=[ctx.texture((W8, H8), 1, dtype="f4")], depth_attachment=ctx.depth_renderbuffer((W8, H8)))
        _ctx.update(ctx=ctx, prog=prog, fbo=fbo)
    ctx, prog, fbo = _ctx["ctx"], _ctx["prog"], _ctx["fbo"]; buf = ctx.buffer(Vm.tobytes()); vao = ctx.vertex_array(prog, [(buf, "3f", "pos")]); out = []
    prog["hw"].value = W8 / 2; prog["hh"].value = H8 / 2
    for pos, R, f, cx, cy in cams:
        for k_, v_ in (("cf", R[2]), ("cr", R[0]), ("cu", R[1]), ("cpos", pos)): prog[k_].value = tuple(map(float, v_))
        prog["foc"].value = float(f); prog["ox"].value = float(cx - W8 / 2); prog["oy"].value = float(-(cy - H8 / 2))
        fbo.use(); fbo.clear(0.0, 0.0, 0.0, 0.0, depth=1.0); vao.render(); out.append(np.frombuffer(fbo.read(components=1, dtype="f4"), np.float32).reshape(H8, W8)[::-1].astype(np.float64))
    vao.release(); buf.release(); fbo.release(); prog.release(); ctx.release(); _ctx.clear(); return np.stack(out)

def dir_grid(cam):
    pos, R, f, cx, cy = cam; v, u = np.mgrid[0:H8, 0:W8] + 0.5
    d = ((u - cx) / f)[..., None] * R[0] - ((v - cy) / f)[..., None] * R[1] + R[2]; d /= np.linalg.norm(d, axis=-1, keepdims=True)
    yaw = ((np.degrees(np.arctan2(d[..., 0], d[..., 2])) + 180) * 2).astype(int) % 720; pit = np.clip(((np.degrees(np.arcsin(np.clip(d[..., 1], -1, 1))) + 90) * 2).astype(int), 0, 359)
    return pit, yaw
def char_fill(sky, char):
    """(10-18) characters must not decide sky / not sky (a character-shaped unknown hole in the sky = a cut-out trace): inside the character
    mask take the label of the nearest pixel outside it"""
    if not char.any() or char.all(): return sky
    from scipy import ndimage as ndi
    _, (iy, ix) = ndi.distance_transform_edt(char, return_indices=True); return np.where(char, sky[iy, ix], sky)

def sky_dirs(cams, sky0):
    """sky in every frame = the directions frame 0 saw as sky (0.5 deg grid); directions frame 0 never saw are NOT sky"""
    sky0 = cv2.morphologyEx(sky0.astype(np.uint8), cv2.MORPH_OPEN, np.ones((7, 7), np.uint8)).astype(bool)   # MoGe's invalid specks on grass / edges are not sky
    p0, y0 = dir_grid(cams[0]); sky0 &= p0 >= 178                                                         # and nothing below the horizon is sky
    G = np.zeros((360, 720), np.int8); G[p0[sky0], y0[sky0]] = 1
    G = cv2.dilate(G.astype(np.uint8), np.ones((3, 3), np.uint8)).astype(bool)
    return np.stack([G[dir_grid(c)] for c in cams])

def gb_cams(gb):
    Kg = gb["K"].numpy().astype(float); f = Kg[0] * 8; cx = Kg[2] * 8 + X0; cy = Kg[3] * 8
    return [(gb["pos"][t].numpy().astype(float), gb["R"][t].numpy().astype(float), f, cx, cy) for t in range(N)]
def sky_mg(M, frames, every=10, CH=None):
    """MoGe-2 sky (its invalid mask) every `every` frames, nearest for the rest; characters filled from their surroundings"""
    ks = list(range(0, N, every)) + ([N - 1] if (N - 1) % every else []); S = {k: (char_fill(~M.mg(frames[k])[1], CH[k]) if CH is not None else ~M.mg(frames[k])[1]) for k in ks}
    return np.stack([S[min(ks, key=lambda k: abs(k - t))] for t in range(N)])

# ------------------------------------------------------------------ sources
def rows_of(src):
    v5 = {json.loads(l)["video"]: json.loads(l) for l in open(f"{OUT}/v5_list.jsonl")}
    rows = [json.loads(l) for l in open(f"{OUT}/v6_rows.jsonl")]
    if src == "ww": return [r for r in rows if r["group"] == "ww"]
    if src == "bk": return [r for r in rows if r["group"] == "bk"]
    if src == "er": return [r for r in rows if r["group"] == "er"]
    if src == "ue": return [r for r in rows if r["group"] == "ue"]
    if src == "synth": return [r for r in rows if r["group"] in ("e1o", "e2o", "e1n", "e2n", "e1x", "turn")]
def cond_of(v):
    d = os.path.dirname(v); b = os.path.basename(v)
    return f"{d}/" + (b.replace("rgb_", "condition_") if b.startswith("rgb_") else "cond.mp4")

def do_coarse(r, M):
    key = r["key"]; gb = torch.load(f"{OUT}/geometry/clip_{key}.pt", weights_only=False); cams = gb_cams(gb)
    V5 = np.stack([r853(x) for x in ff(cond_of(r["video"]), 0, N)]); rgb = np.stack([r853(x) for x in ff(r["video"], 0, N)])
    env = ((V5[..., 0] > 8) | (V5[..., 2] > 8)) & (V5[..., 1] < 20); Z = np.where(env, 0.1 + (1 - V5[..., 2] / 255.0) * 79.9, 0.0)
    CH = np.stack([cv2.dilate((x[..., 1] >= 20).astype(np.uint8), np.ones((15, 15), np.uint8)) > 0 for x in V5]); valid = env | CH
    CHw = np.stack([cv2.dilate((x[..., 1] >= 20).astype(np.uint8), np.ones((41, 41), np.uint8)) > 0 for x in V5])
    sky = sky_mg(M, rgb, CH=CHw) & ~valid
    return core(key, r["group"], V5, Z, valid, sky, CH, cams, False, 1.0, rgb[0], M, shield=shield_of(key))
def shield_of(key):
    p = f"{OUT}/shield/clip_{key}.npy"; return np.load(p) if os.path.exists(p) else None

def do_ww(r, M, cache):
    import ww_to_windows as WW
    from proxykit.geometry import Camera, quat_from_matrix
    wd = os.path.dirname(r["video"]); m = json.load(open(f"{wd}/meta.json")); sd = f"{DS}/wildworld/data_part1/{m['sample']}"; t0 = int(m["t0"]); ts = np.arange(t0, t0 + N)
    if cache.get("sid") != m["sample"]:
        st = WW.load_state(f"{sd}/state.csv"); z = np.load(f"{sd}/skeleton.npz"); keys = {k[0]: k for k in z.files}; ents = {}
        edges = json.load(open(f"{DS}/wildworld/skeleton_edges.json"))
        for kind, rotcol in (("n", "npc.list.1.rot"), ("m", "monster.list.1.rot")):
            k = keys[kind]; tid = k.split("_", 1)[1]; ek = "npc" if kind == "n" else f"em_{tid}"
            parts, parent, size, labels, _ = WW.assign_parts(z[k], edges[ek], st[rotcol], kind); ents[kind] = dict(joints=z[k], parts=parts, parent=parent, size_m=size)
        cache.clear(); cache.update(sid=m["sample"], st=st, ents=ents)
    st, ents = cache["st"], cache["ents"]; K = st["camera.K"][ts]; ground = float(m["ground_y_m"]); to_ue = lambda p: WW.S_SWAP(p - np.array([0, ground, 0])) * 100.0
    dep = WW.decode_gray(f"{sd}/depth.mkv", t0, N); W_, H_ = 1280, 720
    global LUT8
    if "LUT8" not in globals(): LUT8 = WW.depth8_to_m(np.arange(256, dtype=np.uint8))
    e_ = lambda v: np.array([v[0], v[2], -v[1]], float)
    V5 = np.stack([r853(x) for x in ff(f"{wd}/cond.mp4", 0, N)]); rgb0 = r853(ff(r["video"], 0, 1)[0])
    Z, valid, sky, CH, cams = [], [], [], [], []
    for i, t in enumerate(ts):
        Rgl = WW.q2R(st["camera.rot"][t]); Mx = np.stack([WW.S_SWAP(-Rgl[:, 2]), WW.S_SWAP(Rgl[:, 0]), WW.S_SWAP(Rgl[:, 1])], 1)
        cam = Camera(to_ue(st["camera.pos"][t]), quat_from_matrix(Mx), float(np.degrees(2 * np.arctan(W_ / 2 / K[i, 0]))), W_, H_)
        zm = LUT8[dep[i]]; sk = dep[i] >= WW.SKY_DEPTH8
        zz, gd = z853(zm, ~sk); Z.append(zz); sky.append(~gd); valid.append(gd)
        s = 480 / 720; cams.append((e_(cam.position) / 100.0, np.stack([e_(cam.R[:, 1]), e_(cam.R[:, 2]), e_(cam.R[:, 0])]), cam.focal * s, W8 / 2, H8 / 2))
        m = np.zeros((H8, W8), bool)                                                      # characters: capsules round their bones (radius by body size)
        for e in ents.values():
            Jw = np.stack([e_(to_ue(q)) / 100.0 if np.isfinite(q).all() else np.full(3, np.nan) for q in e["joints"][t]])
            par = [int(p) if (p is not None and p >= 0 and e["parts"][j] > 0 and e["parts"][int(p)] > 0) else None for j, p in enumerate(e["parent"])]
            m |= capsules(cams[-1], Jw, max(0.3, 0.16 * float(e["size_m"])), (H8, W8), par)
        CH.append(cv2.dilate(m.astype(np.uint8), np.ones((11, 11), np.uint8)) > 0)
    Z = np.stack(Z).astype(np.float64); return core(r["key"], "ww", V5, Z, np.stack(valid), np.stack(sky), np.stack(CH), cams, True, 5.0, rgb0, M)

def do_bk(r, M):
    import prep_mem as PM
    v = r["video"]; clip = os.path.dirname(v); k = int(os.path.basename(v)[4:7]); b0 = k * 120
    src = clip.replace("/blackknife_121/", "/blackknife_cond/"); meta = json.load(open(f"{src}/meta.json")); raw = meta["attempt"]; sh = np.load(f"{src}/shot.npz")
    off = int(round(float(meta.get("window", [0.0])[0]) * 30))                          # the cond's frame 0 in the raw capture
    gb = torch.load(f"{OUT}/geometry/clip_{r['key']}.pt", weights_only=False); cams = gb_cams(gb)
    V5 = np.stack([r853(x) for x in ff(cond_of(v), 0, N)]); dp = ff(f"{raw}/depth_packed.mkv", off + b0, N); rgb0 = r853(ff(f"{raw}/rgb.mp4", off + b0, 1)[0])
    e_ = lambda p: np.stack([p[..., 0], p[..., 2], -p[..., 1]], -1) / 100.0
    Z, valid, CH = [], [], []
    for i in range(N):
        z, ok = PM.depth_m(dp[i]); ok &= z < 2000; zz, gd = z853(z, ok); Z.append(zz); valid.append(gd)
        m = capsules(cams[i], e_(sh["player_poses"][b0 + i]), 0.30, (H8, W8)) | capsules(cams[i], e_(sh["boss_poses"][b0 + i]), 0.35, (H8, W8))
        CH.append(m | (cv2.dilate((V5[i][..., 1] >= 20).astype(np.uint8), np.ones((7, 7), np.uint8)) > 0))
    Z = np.stack(Z).astype(np.float64); valid = np.stack(valid); return core(r["key"], "bk", V5, Z, valid, ~valid, np.stack(CH), cams, True, 1.0, rgb0, M, shield=shield_of(r["key"]))

def do_synth(r, M):
    key = r["key"]; gb = torch.load(f"{OUT}/geometry/clip_{key}.pt", weights_only=False); cams = gb_cams(gb)
    V5 = np.stack([r853(x) for x in ff(cond_of(r["video"]), 0, N)]); rgb = np.stack([r853(x) for x in ff(r["video"], 0, N)])
    Z, geo, CH, dirs = [], [], [], []
    v, u = np.mgrid[0:H8, 0:W8] + 0.5
    for t in range(N):
        pos, R, f, cx, cy = cams[t]; d = ((u - cx) / f)[..., None] * R[0] - ((v - cy) / f)[..., None] * R[1] + R[2]
        tt = np.where(d[..., 1] < -1e-6, -pos[1] / np.minimum(d[..., 1], -1e-6), 0.0); gnd = (tt > 0) & (tt < 60.0)
        c5 = V5[t]; env5 = ((c5[..., 0] > 8) | (c5[..., 2] > 8)) & (c5[..., 1] < 20); z5 = 0.1 + (1 - c5[..., 2] / 255.0) * 79.9
        prop = env5 & ~(gnd & (np.abs(tt - z5) < 0.05 * tt + 0.3)); Z.append(np.where(prop, z5, np.where(gnd, tt, 0))); geo.append(gnd | env5)
        CH.append(cv2.dilate((c5[..., 1] >= 20).astype(np.uint8), np.ones((15, 15), np.uint8)) > 0); dirs.append(d / np.linalg.norm(d, axis=-1, keepdims=True))
    # sky by DIRECTION (the HDRI is at infinity): MoGe-2 on frames 0 / 60 / 120 votes into a yaw-pitch grid
    G_ = np.zeros((360, 720, 2), np.int32)
    for k in (0, 60, 120):
        skym = char_fill(~M.mg(rgb[k])[1], cv2.dilate(CH[k].astype(np.uint8), np.ones((29, 29), np.uint8)).astype(bool)) & ~geo[k]; dd = dirs[k]; yaw = ((np.degrees(np.arctan2(dd[..., 0], dd[..., 2])) + 180) * 2).astype(int) % 720; pit = np.clip(((np.degrees(np.arcsin(np.clip(dd[..., 1], -1, 1))) + 90) * 2).astype(int), 0, 359)
        np.add.at(G_, (pit.ravel(), yaw.ravel(), skym.ravel().astype(int)), 1)
    sky = []
    for t in range(N):
        dd = dirs[t]; yaw = ((np.degrees(np.arctan2(dd[..., 0], dd[..., 2])) + 180) * 2).astype(int) % 720; pit = np.clip(((np.degrees(np.arcsin(np.clip(dd[..., 1], -1, 1))) + 90) * 2).astype(int), 0, 359)
        c = G_[pit, yaw]; sky.append((c[..., 1] > c[..., 0]) & ~geo[t])
    Z = np.stack(Z).astype(np.float64); geo = np.stack(geo); sky = np.stack(sky)
    tier0 = np.where(geo, 3, np.where(sky, 0, 1)).astype(np.uint8)
    return core(key, r["group"], V5, Z, geo, sky, np.stack(CH), cams, True, 1.0, rgb[0], M, tier0=tier0)


# ------------------------------------------------------------------ roam (memroam windows; whole segments read once)
def roam_rows():
    """memroam training windows (Leyndell held out); user 10-17: Siofra 1/2, snowfield 1/4, every clip (outfit) keeps >= 1 window"""
    idx = json.load(open(f"{DS}/wan_memroam/index.json")); by = {}
    ev = set(json.load(open(f"{OUT}/leyndell_eval.json"))["eval_segments"])          # (user 10-17) Leyndell trains too, only the 4 eval windows' segments stay out
    for name, v in idx.items():
        if v["test"] and v["seg"] in ev: continue
        by.setdefault(v["seg"], []).append((int(v["f0"]), name[5:-3], v["session"]))
    out = []
    for seg, ws in by.items():
        ws.sort(); keep = 2 if "siofra" in ws[0][2] else 4 if "snowfield" in ws[0][2] else 1
        out += [dict(seg=seg, f0=f0, key=k, session=s) for i, (f0, k, s) in enumerate(ws) if i % keep == 0]
    return out

def skel_layer(key, M):
    """memroam stored the skeleton-only layer (prep_mem.Skel, the live engine's actor layer) as a VAE latent: decode it, keep the bone pixels"""
    z = torch.load(f"{DS}/wan_memroam/clips/clip_{key}.pt", map_location="cpu", weights_only=False)["skel"].float().cuda()
    with torch.no_grad(): x = M.vae.decode([z])[0]
    v = ((x.clamp(-1, 1) + 1) * 127.5).round().byte().permute(1, 2, 3, 0).cpu().numpy()[:N]
    m = v[..., 1] >= 24; return np.where(m[..., None], v, 0).astype(np.uint8)

def _weapon_track(rows, M, ground):
    """(10-18) the roaming player's sword: samples' weapons[0] (start, end), world = local + the row's offset; into the Skel frame (cm, z up, grounded)"""
    W_ = []
    for r in rows:
        if r["Wp"]:
            off = np.asarray(r["J"][0], float) - np.asarray(r["Jl"][0], float)
            W_.append(np.stack([(np.asarray(p, float) - off) @ M.T * 100.0 for p in r["Wp"][0]]))
        else: W_.append(None)
    ok = [i for i, w in enumerate(W_) if w is not None]
    out = np.stack([W_[min(ok, key=lambda j: abs(j - i))] for i in range(len(W_))]); out[..., 2] -= ground; return out

_SKW = None
def skel_weapon(rows):
    """(10-18) the player's skeleton layer WITH the sword, drawn by prep_mem.Skel.video itself (same renderer, same codes) with tr.weapon set
    (memroam's stored layer has tr.weapon = None, so the roaming windows had no sword condition while every boss-fight source draws it)"""
    global _SKW
    import prep_mem as PM, inspect, textwrap
    if _SKW is None:
        src = textwrap.dedent(inspect.getsource(PM.Skel.video)); assert src.count("tr.weapon = None") == 1
        ns = dict(PM.__dict__); ns["_weapon_track"] = _weapon_track; exec(src.replace("tr.weapon = None", "tr.weapon = _weapon_track(rows, M, ground)"), ns)
        cls = type("SkelW", (PM.Skel,), {"video": ns["video"]}); _SKW = cls(int(os.environ.get("EGL", "0")))
    with egl_lock(): return _SKW.video(rows)

def do_roam_seg(seg, wins, M, sk):
    """every window of one recording segment: rgb + packed depth decoded once"""
    import prep_mem as PM
    rows = PM.load_states(seg); last = max(w["f0"] for w in wins) + N; need = set(f for w in wins for f in range(w["f0"], w["f0"] + N))
    S = [json.loads(l) for l in gzip.open(seg + "/samples.jsonl.gz", "rt")]; FA = [json.loads(l) for l in gzip.open(seg + "/frame_association.jsonl.gz", "rt")]
    def equip(f):
        r = FA[f]; s = S[r["raw_sample_index"]] if r["raw_sample_index"] < len(S) else None; return (s or {}).get("equipment") or {}
    RGB, DP = {}, {}
    for f, (fr, fd) in enumerate(zip(PM.frames(seg, 0), PM.frames(seg, 1))):
        if f >= last: break
        if f in need: RGB[f] = r853(fr); DP[f] = fd.copy()
    res = []
    for w in wins:
        f0 = w["f0"]; R_ = [rows[f0 + i] for i in range(N)]
        if any(r is None for r in R_) or (f0 + N - 1) not in DP: continue
        cams, Z, valid, CH = [], [], [], []
        for i, r in enumerate(R_):
            fx, fy, cx, cy = r["K"]; s = 480 / 540; cams.append((np.asarray(r["pos"], float), np.asarray(r["R"], float), fx * s, cx * s, cy * s))
            z, ok = PM.depth_m(DP[f0 + i]); ok &= z < 2000; zz, gd = z853(z, ok); Z.append(zz); valid.append(gd)
            CH.append(capsules(cams[-1], np.asarray(r["J"], float), 0.35, (H8, W8)))
        Z = np.stack(Z); valid = np.stack(valid); CH = np.stack(CH)
        feet = float(np.asarray(R_[0]["J"])[:, 1].min()); ab = (1 / 112.0, 0.5 + (8 - feet) / 112.0)        # R = 0.5 + 0.5 clamp((h - feet + 8) / 56)
        skl = skel_weapon(R_) if os.environ.get("V7_SWORD") and any(r["Wp"] for r in R_) else skel_layer(w["key"], M)   # (10-18) sword off: the samples' weapon direction is unreliable (curved / reverse-grip blades point the wrong way)                                                    # the player's skeleton layer prep_mem.Skel drew for this window (no EGL here)
        V5 = np.zeros((N, H8, W8, 3), np.uint8)
        for t in range(N):
            Rr, Bb = rb_from(Z[t], cams[t], ab); V5[t][..., 0] = np.where(valid[t], np.round(Rr * 255), 0); V5[t][..., 2] = np.where(valid[t], np.round(Bb * 255), 0)
            a = skl[t][..., 1] > 0; V5[t][:, X0:X0 + 832][a] = skl[t][a]
        sh = None                                                                         # the round shield (left_param_id 30000000..33000000): a disc 6 cm past the left hand, r 0.30 m
        if 30000000 <= int(equip(f0).get("left_param_id") or 0) < 33000000:
            sh = []
            for t, r in enumerate(R_):
                J = np.asarray(r["J"], float); pos, Rm, f, cx, cy = cams[t]; p = J[7] + 0.06 * (J[7] - J[6]) / max(np.linalg.norm(J[7] - J[6]), 1e-6) - pos
                x, y, z = p @ Rm[0], p @ Rm[1], p @ Rm[2]
                sh.append((cx + f * x / z - X0, cy - f * y / z, f * 0.30 / z) if z > 0.2 else (np.nan,) * 3)
            sh = np.array(sh)
        res.append((w, core(w["key"], "roam", V5, Z, valid, ~valid, CH, cams, True, 1.0, RGB[f0], M, shield=sh, ab=ab)))
    return res

MARK = os.environ.get("V7_MARK", "redo_"); C7 = os.environ.get("V7_SUB", "proxy")   # (10-19) MEMUNK=1 V7_SUB=cond7_memunk writes the variant beside the normal ones
KEYS = set(json.load(open(os.environ["V7_KEYS"]))) if os.environ.get("V7_KEYS") else None   # (10-18) re-render these windows (overwrite); a redo_<key> marker = done
def main():
    ap = argparse.ArgumentParser(); ap.add_argument("src"); ap.add_argument("--rank", type=int, default=0); ap.add_argument("--world", type=int, default=1)
    ap.add_argument("--limit", type=int, default=0); ap.add_argument("--preview", action="store_true"); a = ap.parse_args()
    os.makedirs(f"{OUT}/proxy", exist_ok=True); os.makedirs(f"{OUT}/{C7}", exist_ok=True); os.makedirs(f"{OUT}/preview", exist_ok=True); torch.set_num_threads(4); cv2.setNumThreads(4)
    if a.src == "roam":
        import prep_mem as PM
        W_ = roam_rows(); segs = {}
        if KEYS is not None: W_ = [w for w in W_ if w["key"] in KEYS]
        for w in W_: segs.setdefault(w["seg"], []).append(w)
        mine = sorted(segs)[a.rank::a.world]; M = Models(); sk = None; n = 0; t_ = time.time()                                             # skeleton layer from memroam's latent
        print(f"rank {a.rank} roam: {len(W_)} windows in {len(segs)} segments, mine {len(mine)}", flush=True)
        for seg in mine:
            todo = [w for w in segs[seg] if KEYS is not None and not os.path.exists(f"{OUT}/{C7}/{MARK}{w['key']}") or not os.path.exists(f"{OUT}/{C7}/clip_{w['key']}.pt")]
            if not todo: continue
            try: res = do_roam_seg(seg, todo, M, sk)
            except Exception as ex:
                import traceback; print("FAIL", seg, repr(ex)[:200], traceback.format_exc().splitlines()[-3:], flush=True); continue
            for w, (v7, dep, tc, meta) in res:
                dst = f"{OUT}/{C7}/clip_{w['key']}.pt"; meta["session"] = w["session"]
                torch.save(dict(cond=M.encode(v7), dep=torch.from_numpy(dep), tier=torch.from_numpy(tc), meta=meta), dst + ".tmp"); os.replace(dst + ".tmp", dst); n += 1
                if KEYS is not None: open(f"{OUT}/{C7}/{MARK}{w['key']}", "w").close()
                if a.preview and n <= 3: cv2.imwrite(f"{OUT}/preview/roam_{w['key']}.jpg", cv2.cvtColor(np.concatenate([v7[i].cpu().numpy() for i in (0, 60, 120)], 1), cv2.COLOR_RGB2BGR))
                if a.limit and n >= a.limit: break
            print(f"rank {a.rank} roam: {n} done, {(time.time() - t_) / max(n, 1):.1f} s/window", flush=True)
            if a.limit and n >= a.limit: break
        print(f"rank {a.rank} roam BUILD_V7_DONE {n}", flush=True); return
    rows = rows_of(a.src)
    if KEYS is not None: rows = [r for r in rows if r["key"] in KEYS]
    if a.src == "ww": rows = sorted(rows, key=lambda r: r["video"])                      # windows of one sample together (state cache)
    rows = rows[a.rank::a.world]; M = Models(); cache = {}; n = 0; t_ = time.time()
    if os.environ.get("REVERSE"): rows = rows[::-1]                                       # a second host works from the other end
    for r in rows:
        dst = f"{OUT}/{C7}/clip_{r['key']}.pt"
        if os.path.exists(dst) and (KEYS is None or os.path.exists(f"{OUT}/{C7}/{MARK}{r['key']}")): continue
        try:
            if a.src in ("er", "ue"): v7, dep, tc, meta = do_coarse(r, M)
            elif a.src == "ww": v7, dep, tc, meta = do_ww(r, M, cache)
            elif a.src == "bk": v7, dep, tc, meta = do_bk(r, M)
            elif a.src == "synth": v7, dep, tc, meta = do_synth(r, M)
        except Exception as ex:
            import traceback; print("FAIL", r["video"], repr(ex)[:200], traceback.format_exc().splitlines()[-3:], flush=True); continue
        lat = M.encode(v7); torch.save(dict(cond=lat, dep=torch.from_numpy(dep), tier=torch.from_numpy(tc), meta=meta), dst + ".tmp"); os.replace(dst + ".tmp", dst); n += 1
        if KEYS is not None: open(f"{OUT}/{C7}/{MARK}{r['key']}", "w").close()
        if a.preview and n <= 3:
            img = np.concatenate([v7[i].cpu().numpy() for i in (0, 60, 120)], 1); cv2.imwrite(f"{OUT}/preview/{a.src}_{r['key']}_{'m' if meta['moge'] else ''}{'h' if meta['holes'] else ''}{'p' if meta['patch'] else ''}.jpg", cv2.cvtColor(img, cv2.COLOR_RGB2BGR))
        if n % 20 == 0: print(f"rank {a.rank} {a.src}: {n} done, {(time.time() - t_) / n:.1f} s/window", flush=True)
        if a.limit and n >= a.limit: break
    print(f"rank {a.rank} {a.src} BUILD_V7_DONE {n}", flush=True)

if __name__ == "__main__":
    main()