Spaces:
Running
Running
Download tools/isaac_thumbs.py from projectsim/simready-library: direct link, hf CLI and curl.
- Browser
- Download file 16.9 kB
-
https://huggingface.co/spaces/projectsim/simready-library/resolve/main/tools/isaac_thumbs.py
- Command line
-
hf download hf://spaces/projectsim/simready-library/tools/isaac_thumbs.py
-
curl -L -o isaac_thumbs.py https://huggingface.co/spaces/projectsim/simready-library/resolve/main/tools/isaac_thumbs.py
16.9 kB
| """Isaac Sim (RTX) thumbnails for the Library: <out_dir>/dark/<asset>.webp and <out_dir>/light/<asset>.webp. | |
| Renders each SimReady package with its own materials (MDL glass, liquids, OpenPBR), the | |
| way it looks in sim, instead of the simplified preview GLB: a three-quarter view from the | |
| front-right (the package's simready:assetFrame:forwardDirection when it has one, else -Y), | |
| lit by Tyler's HDRI (Poly Haven small_hangar_02) as a dome that isn't visible in the image. | |
| Path tracing with Tyler's settings: max bounces 4, specular/transmission bounces 6, | |
| subsurface scattering on. | |
| The asset stands on a floor that fills the whole frame, rendered twice, once per Library | |
| theme (the app picks by theme): | |
| dark: plain matte dark floor that ends up #1a1a1a, the dark theme's thumbnail | |
| background (--thumb), with a fade to it over the outer 4% of the frame, so the | |
| image melts into the card and only the asset and its soft shadow show. | |
| light: NVIDIA-style grey studio: light grey floor with a faint grid (1-2-5 cm cells, | |
| about a tenth of the asset's size) and soft reflections, balanced so the far | |
| floor reads neutral grey (158,159,161). | |
| Both get the same white balance for the warm HDRI (fixed gains), plus a small per-image | |
| nudge that puts the far floor on its target colour. | |
| Workaround, render only (the package is not changed): RTX draws a package's MaterialX | |
| (OpenPBR) network, and an OpenPBR whose geometry_normal comes from an ND_normalmap node | |
| that has a tangent input (the shared brushed and milled steel looks, normal map plus | |
| material_tangent primvar) renders pure black there. Those geometry_normal links are cut | |
| before rendering, so the steel shows with its colour, roughness and anisotropy, without | |
| the fine normal-map detail. | |
| Run on a GPU machine with Isaac Sim 6.x (pip install or /opt/IsaacSim/python.sh): | |
| OMNI_KIT_ACCEPT_EULA=YES python isaac_thumbs.py <assets_dir> <out_dir> <hdri.exr> [asset ...] | |
| <assets_dir>/<asset>/simready_usd/<asset>.usd for every asset (a download of | |
| projectsim/simready-assets). Assets with both thumbnails already are skipped unless --force. | |
| """ | |
| import argparse | |
| import math | |
| import os | |
| import sys | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("assets_dir") | |
| ap.add_argument("out_dir") | |
| ap.add_argument("hdri") | |
| ap.add_argument("assets", nargs="*") | |
| ap.add_argument("--variants", default="dark,light") | |
| ap.add_argument("--size", type=int, default=640, help="output size in px") | |
| ap.add_argument("--render-size", type=int, default=1024, help="rendered size before downscaling") | |
| ap.add_argument("--spp", type=int, default=256, help="path-tracing samples per pixel") | |
| ap.add_argument("--dome", type=float, default=1500.0, help="HDRI dome intensity") | |
| ap.add_argument("--wb", default="1.63,2.14,2.93", help="white balance + exposure for the warm HDRI (linear RGB gains)") | |
| ap.add_argument("--dark-floor", type=float, default=0.175, help="dark floor albedo (sRGB 0-1)") | |
| ap.add_argument("--grid-grey", type=float, default=0.62, help="light (grid) floor albedo (sRGB 0-1)") | |
| ap.add_argument("--fill", type=float, default=0.92, help="share of the frame the bounding box fills") | |
| ap.add_argument("--azimuth", type=float, default=35.0, help="degrees right of the front") | |
| ap.add_argument("--elevation", type=float, default=24.0) | |
| ap.add_argument("--fov", type=float, default=22.0, help="vertical field of view, degrees") | |
| ap.add_argument("--max-bounces", type=int, default=4) | |
| ap.add_argument("--max-spec-bounces", type=int, default=6, help="max specular and transmission bounces") | |
| ap.add_argument("--force", action="store_true") | |
| args = ap.parse_intermixed_args() # asset names may follow the flags | |
| sys.argv = sys.argv[:1] # keep our flags away from Kit's own argument parsing | |
| VARIANTS = { # floor material, far-floor target (sRGB), fade the border to it | |
| "dark": ("matte", (26, 26, 26), True), | |
| "light": ("grid", (158, 159, 161), False), | |
| } | |
| variants = [v for v in args.variants.split(",") if v in VARIANTS] | |
| from isaacsim import SimulationApp # noqa: E402 | |
| R = args.render_size | |
| app = SimulationApp({"headless": True, "renderer": "PathTracing", "width": R, "height": R}) | |
| import carb # noqa: E402 | |
| import numpy as np # noqa: E402 | |
| import omni.replicator.core as rep # noqa: E402 | |
| import omni.usd # noqa: E402 | |
| from PIL import Image # noqa: E402 | |
| from pxr import Gf, Sdf, Usd, UsdGeom, UsdLux, UsdShade # noqa: E402 | |
| settings = carb.settings.get_settings() | |
| for key, value in { | |
| "/rtx/pathtracing/totalSpp": args.spp, | |
| "/rtx/pathtracing/spp": 16, | |
| "/rtx/pathtracing/maxBounces": args.max_bounces, # Tyler's settings | |
| "/rtx/pathtracing/maxSpecularAndTransmissionBounces": args.max_spec_bounces, | |
| "/rtx/pathtracing/optixDenoiser/enabled": True, | |
| # subsurface scattering (Tyler): frosted plastics, nylon, wax look flat without it | |
| "/rtx/raytracing/subsurface/enabled": True, | |
| "/rtx/raytracing/subsurface/transmission/enabled": True, | |
| "/rtx/pathtracing/maxVolumeBounces": 15, | |
| # load materials and textures before rendering, not in the background (otherwise the | |
| # first image after a material change can show the previous floor) | |
| "/rtx/materialDb/syncLoads": True, | |
| "/rtx/hydra/materialSyncLoads": True, | |
| "/rtx-transient/resourcemanager/texturestreaming/async": False, | |
| "/omni.kit.plugin/syncUsdLoads": True, | |
| }.items(): | |
| settings.set(key, value) | |
| def to_lin(c): | |
| c = np.asarray(c, np.float32) | |
| return np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4) | |
| def to_srgb(c): | |
| return np.where(c <= 0.0031308, c * 12.92, 1.055 * np.power(np.clip(c, 0, None), 1 / 2.4) - 0.055) | |
| WB = np.array([float(v) for v in args.wb.split(",")], np.float32) | |
| for v in variants: | |
| os.makedirs(f"{args.out_dir}/{v}", exist_ok=True) | |
| names = args.assets or sorted(n for n in os.listdir(args.assets_dir) | |
| if os.path.isfile(f"{args.assets_dir}/{n}/simready_usd/{n}.usd")) | |
| todo = [n for n in names if args.force or args.assets | |
| or not all(os.path.exists(f"{args.out_dir}/{v}/{n}.webp") for v in variants)] | |
| print(f"{len(todo)} assets to render ({', '.join(variants)})", flush=True) | |
| ctx = omni.usd.get_context() | |
| ctx.new_stage() | |
| for _ in range(5): | |
| app.update() | |
| stage = ctx.get_stage() | |
| UsdGeom.SetStageMetersPerUnit(stage, 1.0) | |
| dome = UsdLux.DomeLight.Define(stage, "/World/Dome") | |
| dome.CreateTextureFileAttr(os.path.abspath(args.hdri)) | |
| dome.CreateTextureFormatAttr("latlong") | |
| dome.CreateIntensityAttr(args.dome) | |
| dome.GetPrim().CreateAttribute("visibleInPrimaryRay", Sdf.ValueTypeNames.Bool).Set(False) | |
| floor = UsdGeom.Mesh.Define(stage, "/World/Floor") | |
| floor.CreatePointsAttr([(-1, -1, 0), (1, -1, 0), (1, 1, 0), (-1, 1, 0)]) | |
| floor.CreateFaceVertexCountsAttr([4]) | |
| floor.CreateFaceVertexIndicesAttr([0, 1, 2, 3]) | |
| floor_st = UsdGeom.PrimvarsAPI(floor.GetPrim()).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.vertex) | |
| floor_st.Set([(0, 0), (1, 0), (1, 1), (0, 1)]) | |
| floor_binding = UsdShade.MaterialBindingAPI.Apply(floor.GetPrim()) | |
| # dark: matte, no reflections, so it's one even colour up to the frame edges | |
| matte = UsdShade.Material.Define(stage, "/World/Looks/Matte") | |
| s1 = UsdShade.Shader.Define(stage, "/World/Looks/Matte/Surface") | |
| s1.CreateIdAttr("UsdPreviewSurface") | |
| s1.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set(1.0) | |
| s1.CreateInput("useSpecularWorkflow", Sdf.ValueTypeNames.Int).Set(1) | |
| s1.CreateInput("specularColor", Sdf.ValueTypeNames.Color3f).Set(Gf.Vec3f(0, 0, 0)) | |
| g = float(to_lin(args.dark_floor)) | |
| s1.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set(Gf.Vec3f(g, g, g)) | |
| matte.CreateSurfaceOutput().ConnectToSource(s1.ConnectableAPI(), "surface") | |
| # light: grey studio floor with a faint grid, one texture tile = 8 x 8 cells | |
| GRID = os.path.abspath(os.path.join(args.out_dir, "_studio_grid.png")) | |
| tile = np.full((1024, 1024), args.grid_grey * 255, np.float32) | |
| for k in range(0, 1024, 128): | |
| tile[k:k + 2, :] *= 0.9 | |
| tile[:, k:k + 2] *= 0.9 | |
| tile[0:3, :] *= 0.93 | |
| tile[:, 0:3] *= 0.93 | |
| Image.fromarray(tile.clip(0, 255).astype(np.uint8), "L").convert("RGB").save(GRID) | |
| grid = UsdShade.Material.Define(stage, "/World/Looks/Grid") | |
| s2 = UsdShade.Shader.Define(stage, "/World/Looks/Grid/Surface") | |
| s2.CreateIdAttr("UsdPreviewSurface") | |
| s2.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set(0.6) | |
| s2.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(0.0) | |
| reader = UsdShade.Shader.Define(stage, "/World/Looks/Grid/St") | |
| reader.CreateIdAttr("UsdPrimvarReader_float2") | |
| reader.CreateInput("varname", Sdf.ValueTypeNames.String).Set("st") | |
| tex = UsdShade.Shader.Define(stage, "/World/Looks/Grid/Texture") | |
| tex.CreateIdAttr("UsdUVTexture") | |
| tex.CreateInput("file", Sdf.ValueTypeNames.Asset).Set(GRID) | |
| tex.CreateInput("wrapS", Sdf.ValueTypeNames.Token).Set("repeat") | |
| tex.CreateInput("wrapT", Sdf.ValueTypeNames.Token).Set("repeat") | |
| tex.CreateInput("sourceColorSpace", Sdf.ValueTypeNames.Token).Set("sRGB") | |
| tex.CreateInput("st", Sdf.ValueTypeNames.Float2).ConnectToSource(reader.ConnectableAPI(), "result") | |
| s2.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).ConnectToSource(tex.ConnectableAPI(), "rgb") | |
| grid.CreateSurfaceOutput().ConnectToSource(s2.ConnectableAPI(), "surface") | |
| FLOORS = {"matte": matte, "grid": grid} | |
| cam = UsdGeom.Camera.Define(stage, "/World/Cam") | |
| APERTURE = 20.955 | |
| cam.CreateFocalLengthAttr(APERTURE / 2 / math.tan(math.radians(args.fov) / 2)) | |
| cam.CreateHorizontalApertureAttr(APERTURE) | |
| cam.CreateVerticalApertureAttr(APERTURE) | |
| cam_xf = cam.AddTransformOp() | |
| rp = rep.create.render_product(str(cam.GetPath()), (R, R)) | |
| rgb = rep.AnnotatorRegistry.get_annotator("rgb") | |
| rgb.attach(rp) | |
| PURPOSES = [UsdGeom.Tokens.default_, UsdGeom.Tokens.render] | |
| HALF = math.tan(math.radians(args.fov) / 2) * args.fill | |
| SUBFRAMES = max(1, args.spp // 16) | |
| edge = np.minimum(np.arange(R) + 0.5, R - np.arange(R) - 0.5) / (0.04 * R) # 0 at the edge, 1 at 4% in | |
| edge = np.clip(edge, 0, 1) | |
| edge = edge * edge * (3 - 2 * edge) | |
| KEEP = np.minimum.outer(edge, edge)[..., None] | |
| def basis(up_axis, forward): | |
| """Stage up vector, and the asset's front as a horizontal unit vector.""" | |
| up = Gf.Vec3d(0, 0, 1) if up_axis == "Z" else Gf.Vec3d(0, 1, 0) | |
| f = Gf.Vec3d(*forward) if forward else (Gf.Vec3d(0, -1, 0) if up_axis == "Z" else Gf.Vec3d(0, 0, 1)) | |
| f = f - up * Gf.Dot(f, up) | |
| if f.GetLength() < 1e-6: | |
| f = Gf.Vec3d(0, -1, 0) if up_axis == "Z" else Gf.Vec3d(0, 0, 1) | |
| return up, f.GetNormalized() | |
| def fix_mtlx_normals(root): | |
| """Cut OpenPBR geometry_normal links that come from an ND_normalmap with a tangent input.""" | |
| n = 0 | |
| for p in Usd.PrimRange(root): | |
| if not p.IsA(UsdShade.Shader) or UsdShade.Shader(p).GetIdAttr().Get() != "ND_open_pbr_surface_surfaceshader": | |
| continue | |
| inp = UsdShade.Shader(p).GetInput("geometry_normal") | |
| srcs = inp.GetConnectedSources()[0] if inp else [] | |
| if not srcs: | |
| continue | |
| node = UsdShade.Shader(srcs[0].source.GetPrim()) | |
| tangent = node.GetInput("tangent") | |
| if node.GetIdAttr().Get() == "ND_normalmap" and tangent and tangent.HasConnectedSource(): | |
| UsdShade.ConnectableAPI.DisconnectSource(inp) # blocks the link from the referenced layer | |
| n += 1 | |
| return n | |
| def render(): | |
| # Render without advancing time: a step that moves the timeline also steps physics, and | |
| # the asset (a rigid body, with no collider under it) drops a millimetre or two into the | |
| # floor, which swallows thin parts lying flat (angle brackets). | |
| try: | |
| rep.orchestrator.step(rt_subframes=SUBFRAMES, delta_time=0.0, pause_timeline=True) | |
| except TypeError: | |
| rep.orchestrator.step(rt_subframes=SUBFRAMES) | |
| return np.asarray(rgb.get_data()) | |
| def finish(img, card, fade): | |
| """White balance, nudge the far floor onto its target colour, optionally fade the border to it.""" | |
| lin = to_lin(img[..., :3].astype(np.float32) / 255) | |
| k = max(4, R // 10) | |
| ref = np.concatenate([lin[:k, :k].reshape(-1, 3), lin[:k, -k:].reshape(-1, 3)]) | |
| target = to_lin(np.array(card, np.float32) / 255) | |
| gain = WB * np.clip(target / np.maximum(np.median(ref, axis=0) * WB, 1e-5), 0.75, 1.25) | |
| lin = lin * gain | |
| if fade: | |
| lin = lin * KEEP + target * (1 - KEEP) | |
| out = Image.fromarray((np.clip(to_srgb(lin), 0, 1) * 255 + 0.5).astype(np.uint8), "RGB") | |
| if args.size != R: | |
| out = out.resize((args.size, args.size), Image.LANCZOS) | |
| return out, gain, np.median(ref, axis=0) | |
| # warm-up: compile both floor materials and load the grid texture before the first asset | |
| for kind in ("grid", "matte"): | |
| floor_binding.Bind(FLOORS[kind]) | |
| for _ in range(5): | |
| app.update() | |
| render() | |
| for i, name in enumerate(todo, 1): | |
| usd = f"{args.assets_dir}/{name}/simready_usd/{name}.usd" | |
| try: | |
| if stage.GetPrimAtPath("/World/Asset"): | |
| stage.RemovePrim("/World/Asset") | |
| app.update() | |
| src = Usd.Stage.Open(usd, Usd.Stage.LoadNone) | |
| up_axis = UsdGeom.GetStageUpAxis(src) | |
| root = src.GetDefaultPrim() | |
| fwd_attr = root.GetAttribute("simready:assetFrame:forwardDirection") if root else None | |
| forward = fwd_attr.Get() if fwd_attr and fwd_attr.HasAuthoredValue() else None | |
| if forward is not None and root.IsA(UsdGeom.Xformable): # authored in the prim's local frame | |
| forward = UsdGeom.Xformable(root).GetLocalTransformation().TransformDir(Gf.Vec3d(*forward)) | |
| UsdGeom.SetStageUpAxis(stage, up_axis) | |
| up, front = basis(up_axis, forward) | |
| asset = stage.DefinePrim("/World/Asset", "Xform") | |
| asset.GetReferences().AddReference(usd) | |
| cut = fix_mtlx_normals(asset) | |
| for _ in range(10): | |
| app.update() | |
| rng = UsdGeom.BBoxCache(Usd.TimeCode.Default(), PURPOSES).ComputeWorldBound(asset).ComputeAlignedRange() | |
| if rng.IsEmpty(): | |
| print(f"THUMB_SKIP {name}: empty bounds", flush=True) | |
| continue | |
| centre = (rng.GetMin() + rng.GetMax()) / 2 | |
| size = max(rng.GetSize().GetLength(), 1e-3) | |
| # view direction: front turned toward the right by the azimuth, raised by the elevation | |
| a, e = math.radians(args.azimuth), math.radians(args.elevation) | |
| right = Gf.Cross(front, up) | |
| view = ((front * math.cos(a) + right * math.sin(a)) * math.cos(e) + up * math.sin(e)).GetNormalized() | |
| # distance: smallest that keeps every bounding-box corner inside the frame | |
| lo, hi = rng.GetMin(), rng.GetMax() | |
| box = [Gf.Vec3d(x, y, z) for x in (lo[0], hi[0]) for y in (lo[1], hi[1]) for z in (lo[2], hi[2])] | |
| def fits(d): | |
| m = Gf.Matrix4d().SetLookAt(centre + view * d, centre, up) | |
| for p in box: | |
| q = m.Transform(p) | |
| if -q[2] <= 1e-6 or max(abs(q[0]), abs(q[1])) / -q[2] > HALF: | |
| return False | |
| return True | |
| lo_d, hi_d = size * 0.3, size * 20 | |
| for _ in range(40): | |
| mid = (lo_d + hi_d) / 2 | |
| lo_d, hi_d = (lo_d, mid) if fits(mid) else (mid, hi_d) | |
| cam_xf.Set(Gf.Matrix4d().SetLookAt(centre + view * hi_d, centre, up).GetInverse()) | |
| cam.CreateClippingRangeAttr(Gf.Vec2f(max(hi_d * 0.02, 1e-4), hi_d + size * 200)) | |
| # floor under the asset, reaching well past the top of the frame | |
| base = lo[2] if up_axis == "Z" else lo[1] | |
| w = size * 60 | |
| quad = ((-w, -w), (w, -w), (w, w), (-w, w)) | |
| floor.GetPointsAttr().Set([(centre[0] + x, centre[1] + y, base) for x, y in quad] if up_axis == "Z" | |
| else [(centre[0] + x, base, centre[2] - y) for x, y in quad]) | |
| want = size / 10 # grid cells of 1-2-5 cm steps, about a tenth of the asset | |
| mag = 10 ** math.floor(math.log10(want)) | |
| cell = min((m * mag for m in (1, 2, 5, 10)), key=lambda c: abs(math.log(c / want))) | |
| reps = 2 * w / (8 * cell) | |
| floor_st.Set([(0, 0), (reps, 0), (reps, reps), (0, reps)]) | |
| gains = [] | |
| for v in variants: | |
| kind, card, fade = VARIANTS[v] | |
| floor_binding.Bind(FLOORS[kind]) | |
| for _ in range(3): | |
| app.update() | |
| img = render() | |
| if img.ndim != 3 or img.shape[2] < 3: | |
| raise RuntimeError("no image") | |
| out, gain, raw = finish(img, card, fade) | |
| out.save(f"{args.out_dir}/{v}/{name}.webp", quality=90) | |
| gains.append(f"{v}={round(float(gain[1] / WB[1]), 2)} raw={np.round(raw, 4).tolist()}") | |
| print(f"THUMB_OK {name} {i}/{len(todo)} nudge {' '.join(gains)}" + (f" normal_links_cut={cut}" if cut else ""), flush=True) | |
| except Exception as exc: # keep going; report at the end | |
| print(f"THUMB_FAIL {name}: {exc}", flush=True) | |
| rep.orchestrator.wait_until_complete() | |
| print("THUMBS DONE", flush=True) | |
| app.close() | |