"""Condition renderer for arbitrary skeleton topologies, encoding identical to BOSSV2V capture_720p30_v1. The fragment shader is the dataset's analytic ray caster (entity_geometry_gpu.py) with larger uniform arrays (256 capsules, 128 boxes) so non-humanoid monsters fit. Per pixel, nearest surface among: sea plane (id 5), finite platform disc (id 1), yaw-rotated boxes (ids 2-4), capsules/spheres (id = slot * 32 + part_id). R = environment: 0.5 + 0.5 * h ; actors: 0.2 * h h = clamp((world_z_m - hmin) / (hmax - hmin)) G = actor id / 255 (environment 0) B = 1 - clamp((camera_forward_depth_m - near) / (far - near)) Output rgb16 (H, W, 3) uint16, bottom-up flipped to image order. """ import math, shutil, subprocess import numpy as np import moderngl MAX_CAPSULES, MAX_BOXES = 256, 128 HEIGHT_RANGE_M, DEPTH_RANGE_M = (-8.0, 32.0), (0.1, 80.0) VERTEX = '''#version 330 void main(){vec2 p=vec2((gl_VertexID<<1)&2,gl_VertexID&2);gl_Position=vec4(p*2.-1.,0.,1.);}''' FRAGMENT = '''#version 330 uniform vec2 resolution;uniform vec3 origin,forward,right,up;uniform float hfov; uniform vec2 heightRange,depthRange; uniform int sceneCount;uniform vec4 boxCenter[%(B)d],boxSize[%(B)d];uniform vec3 platform; uniform int count;uniform vec4 aa[%(C)d],bb[%(C)d];layout(location=0) out uvec4 outData; float sphere(vec3 rd,vec3 center,float r){vec3 q=-center;float b=dot(q,rd),c=dot(q,q)-r*r,h=b*b-c;if(h<0.)return 1e20;float t=-b-sqrt(h);if(t<=1.)t=-b+sqrt(h);return t>1.?t:1e20;} float capsule(vec3 rd,vec3 a,vec3 b,float radius){ vec3 ba=b-a,oa=-a;float baba=dot(ba,ba),result=min(sphere(rd,a,radius),sphere(rd,b,radius)); if(baba<1e-8)return result; float bard=dot(ba,rd),baoa=dot(ba,oa),rdoa=dot(rd,oa); float A=baba-bard*bard,B=baba*rdoa-baoa*bard,C=baba*dot(oa,oa)-baoa*baoa-radius*radius*baba; float h=B*B-A*C;if(h>=0.&&abs(A)>1e-8){float root=sqrt(h); float t=(-B-root)/A,y=baoa+t*bard;if(t>1.&&y>=0.&&y<=baba)result=min(result,t); t=(-B+root)/A;y=baoa+t*bard;if(t>1.&&y>=0.&&y<=baba)result=min(result,t);} return result; } float boxHit(vec3 rd,vec4 center,vec3 halfSize){ vec3 q=origin-center.xyz;float c=cos(center.w),s=sin(center.w); vec3 ro=vec3(c*q.x+s*q.y,-s*q.x+c*q.y,q.z);rd=vec3(c*rd.x+s*rd.y,-s*rd.x+c*rd.y,rd.z); float nearT=-1e20,farT=1e20; for(int k=0;k<3;k++){if(abs(rd[k])<1e-8){if(abs(ro[k])>halfSize[k])return 1e20;} else{float a=(-halfSize[k]-ro[k])/rd[k],b=(halfSize[k]-ro[k])/rd[k];nearT=max(nearT,min(a,b));farT=min(farT,max(a,b));}} if(farT1.?nearT:farT;return t>1.?t:1e20; } void main(){ vec2 xy=(gl_FragCoord.xy-resolution*.5)/(resolution.x*.5/tan(hfov*.5)); vec3 localRay=normalize(vec3(1.,xy.x,xy.y));vec3 ray=forward*localRay.x+right*localRay.y+up*localRay.z; float t=1e20;uint id=0u; if(abs(ray.z)>1e-7){float d=(platform.z-origin.z)/ray.z;if(d>1.&&d<100000.){t=d;id=5u;} d=(platform.y-origin.z)/ray.z;vec2 p=origin.xy+ray.xy*d;if(d>1.&&d=sceneCount)break;float d=boxHit(ray,boxCenter[i],boxSize[i].xyz);if(d=count)break;float d=capsule(localRay,aa[i].xyz,bb[i].xyz,aa[i].w);if(dheightRange.y)flags|=1u; if(depthdepthRange.y)flags|=environment?4u:2u; outData=uvec4(uint(round(red*65535.)),environment?0u:id*257u,uint(round(blue*65535.)),flags); }''' % {"B": MAX_BOXES, "C": MAX_CAPSULES} class Renderer: """scene: dict(platform=dict(radius_cm, z_cm), sea_z_cm, boxes=[dict(center_cm, size_cm, yaw_degrees, label)]).""" def __init__(self, scene, width=1280, height=720, device_index=None): kw = dict(backend="egl", require=330) if device_index is not None: kw["device_index"] = int(device_index) self.ctx = moderngl.create_standalone_context(**kw) self.w, self.h = width, height self.program = self.ctx.program(vertex_shader=VERTEX, fragment_shader=FRAGMENT) self.vao = self.ctx.vertex_array(self.program, []) self.texture = self.ctx.texture((width, height), 4, dtype="u2") self.fbo = self.ctx.framebuffer(color_attachments=[self.texture]) self.program["resolution"].value = (width, height) self.program["heightRange"].value = HEIGHT_RANGE_M self.program["depthRange"].value = DEPTH_RANGE_M self.set_scene(scene) def set_scene(self, scene): boxes = scene.get("boxes", []) assert len(boxes) <= MAX_BOXES, f"{len(boxes)} boxes > {MAX_BOXES}" self.program["platform"].value = (scene["platform"]["radius_cm"], scene["platform"]["z_cm"], scene["sea_z_cm"]) centers = np.zeros((MAX_BOXES, 4), np.float32); sizes = np.zeros_like(centers) for i, b in enumerate(boxes): assert b["label"] in (2, 3, 4) centers[i] = [*b["center_cm"], math.radians(b["yaw_degrees"])] sizes[i] = [*[v * 0.5 for v in b["size_cm"]], b["label"]] self.program["boxCenter"].write(centers.tobytes()); self.program["boxSize"].write(sizes.tobytes()) self.program["sceneCount"].value = len(boxes) def render(self, camera, capsules): """camera: geometry.Camera; capsules: iterable of (a_cm, b_cm, radius_cm, label). Returns rgb16 and clip stats.""" rot = camera.R; origin = np.asarray(camera.position, float) for i, key in enumerate(["forward", "right", "up"]): self.program[key].value = tuple(rot[:, i]) self.program["origin"].value = tuple(origin) self.program["hfov"].value = math.radians(camera.fov) aa = np.zeros((MAX_CAPSULES, 4), np.float32); bb = np.zeros_like(aa); n = 0 for a, b, radius, label in capsules: assert n < MAX_CAPSULES, "too many capsules" assert 0 < int(label) < 256 and int(label) > 5, f"actor label {label} collides with environment ids" aa[n] = [*((np.asarray(a, float) - origin) @ rot), radius] bb[n] = [*((np.asarray(b, float) - origin) @ rot), label] n += 1 self.program["aa"].write(aa.tobytes()); self.program["bb"].write(bb.tobytes()); self.program["count"].value = n self.fbo.use(); self.ctx.viewport = (0, 0, self.w, self.h); self.vao.render(vertices=3) rgba = np.frombuffer(self.fbo.read(components=4, dtype="u2", alignment=1), dtype=" 10-bit 4:4:4 full-range BT.709 CRF12 MP4 (dataset settings); optional 1024x576 training scale.""" def __init__(self, path, width=1280, height=720, fps=30, scale_to=None): vf = "scale=in_range=full:out_range=full:out_color_matrix=bt709" if scale_to: vf = f"scale={scale_to[0]}:{scale_to[1]}:flags=area:in_range=full:out_range=full:out_color_matrix=bt709" cmd = [shutil.which("ffmpeg"), "-threads", "2", "-filter_threads", "1", "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "rgb48le", "-s", f"{width}x{height}", "-r", str(fps), "-i", "-", "-an", "-vf", vf, "-threads", "2", "-c:v", "libx264", "-crf", "12", "-preset", "fast", "-pix_fmt", "yuv444p10le", "-profile:v", "high444", "-color_range", "pc", "-colorspace", "bt709", "-color_primaries", "bt709", "-color_trc", "bt709", "-movflags", "+faststart", str(path)] self.proc = subprocess.Popen(cmd, stdin=subprocess.PIPE) def write(self, rgb16): self.proc.stdin.write(np.ascontiguousarray(rgb16, dtype=" RGB8 for the human-readable view: hue by slot, shade by part (head bright, left limbs light, right limbs dark, tail/wings mid), weapon bright yellow.""" lut = np.zeros((256, 3), np.float32) for g in range(33, 256): slot, part = divmod(g, 32) if slot not in _SLOT_HUES or part == 0: continue base = np.array(_SLOT_HUES[slot], np.float32) if part == 18: lut[g] = (255, 255, 90) continue if part == 5: k = 1.25 elif part in (6, 7, 8, 12, 13, 14, 23, 24, 25, 29): k = 1.1 elif part in (9, 10, 11, 15, 16, 17, 26, 27, 28, 30): k = 0.7 else: k = 0.9 lut[g] = np.clip(base * k + (40 if part == 5 else 0), 0, 255) return lut.astype(np.uint8) ACTOR_LUT = _actor_lut() def readable_rgb8(rgb16): """Human-readable frame from an exact (pre-encoding) condition frame: environment in grey shaded by nearness, sky dark blue, actors coloured by identity slot and body part.""" g = (rgb16[..., 1] // 257).astype(np.int32) r = rgb16[..., 0].astype(np.float32) / 65535 b = rgb16[..., 2].astype(np.float32) / 65535 out = np.empty(rgb16.shape, np.uint8) out[:] = (18, 22, 38) env = (g == 0) & (r > 0) shade = np.clip(60 + 150 * b + 60 * (r - 0.5), 0, 255) out[env] = shade[env][:, None].astype(np.uint8) actor = g > 0 out[actor] = ACTOR_LUT[g[actor]] return out class ReadableWriter: """RGB8 frames -> H.264 yuv420p CRF18 MP4 for viewing.""" def __init__(self, path, width=1280, height=720, fps=30): cmd = [shutil.which("ffmpeg"), "-threads", "2", "-filter_threads", "1", "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", f"{width}x{height}", "-r", str(fps), "-i", "-", "-an", "-threads", "2", "-c:v", "libx264", "-crf", "18", "-preset", "fast", "-pix_fmt", "yuv420p", "-movflags", "+faststart", str(path)] self.proc = subprocess.Popen(cmd, stdin=subprocess.PIPE) def write(self, rgb8): self.proc.stdin.write(np.ascontiguousarray(rgb8, dtype=np.uint8).tobytes()) def close(self): self.proc.stdin.close() assert self.proc.wait(timeout=300) == 0, "ffmpeg failed"