from __future__ import annotations import json import hashlib import math import os import shutil from pathlib import Path from typing import Any, Literal import yaml # type: ignore[import-untyped] from pydantic import BaseModel, ConfigDict, Field, model_validator from packages.core.files import atomic_write_text PBRChannelName = Literal["albedo", "roughness", "metallic", "normal", "height", "ao"] class _StrictModel(BaseModel): model_config = ConfigDict(extra="forbid") class PBRChannel(_StrictModel): texture: str | None = None scalar: float | tuple[float, float, float] | None = None color_space: Literal["sRGB", "raw"] @model_validator(mode="after") def validate_source(self) -> PBRChannel: if self.texture is None and self.scalar is None: raise ValueError("PBR channel needs a texture or scalar") if isinstance(self.scalar, float) and not 0.0 <= self.scalar <= 1.0: raise ValueError("scalar PBR channels must be within [0, 1]") if isinstance(self.scalar, tuple) and any(not 0.0 <= item <= 1.0 for item in self.scalar): raise ValueError("PBR color channels must be within [0, 1]") return self class PBRMaterialSpec(_StrictModel): entity_id: str material_class: str profile: Literal["imported", "uniform", "detailed"] channels: dict[PBRChannelName, PBRChannel] = Field(default_factory=dict) uv_primvar: str = "st" uv_scale_m: float = Field(default=1.0, gt=0) normal_convention: Literal["OpenGL", "DirectX"] = "OpenGL" opacity: float = Field(default=1.0, ge=0, le=1) required: bool = True class PBRManifest(_StrictModel): schema_version: Literal["1.0"] = "1.0" workflow: Literal["metallic_roughness"] = "metallic_roughness" materials: list[PBRMaterialSpec] DEFAULT_PBR_POLICY = ( Path(__file__).resolve().parents[2] / "configs" / "scene_generation" / "pbr_profiles_v1.yaml" ) def load_pbr_policy(path: Path | None = None) -> dict[str, Any]: selected = path or Path(os.environ.get("RHG_PBR_POLICY", DEFAULT_PBR_POLICY)) value = yaml.safe_load(selected.expanduser().resolve().read_text(encoding="utf-8")) if not isinstance(value, dict) or value.get("schema_version") != "1.0": raise ValueError("PBR policy must use schema_version 1.0") return value def compile_pbr_manifest(task: dict[str, Any], policy: dict[str, Any]) -> PBRManifest: detailed = {str(item).casefold() for item in policy["detailed_material_classes"]} color_spaces = policy["color_spaces"] materials: list[PBRMaterialSpec] = [] for entity in task.get("entities", []): if not isinstance(entity, dict) or entity.get("role") in {"ROBOT", "REGION"}: continue entity_id = str(entity.get("entity_id") or "") if not entity_id: continue attributes = entity.get("attributes") or {} appearance = attributes.get("appearance") or {} if not appearance and isinstance(attributes.get("procedural_geometry"), dict): components = attributes["procedural_geometry"].get("components") or [] first = components[0] if components and isinstance(components[0], dict) else {} appearance = { "base_color_rgb": first.get("display_color", [0.5, 0.5, 0.5]), "roughness": 0.5, "metallic": 0.0, "material_class": "uniform", } if not appearance: materials.append( PBRMaterialSpec( entity_id=entity_id, material_class="imported", profile="imported", required=bool(entity.get("required", True)), ) ) continue material_class = str( appearance.get("material_class") or attributes.get("material_class") or "uniform" ).casefold() profile: Literal["uniform", "detailed"] = ( "detailed" if material_class in detailed else "uniform" ) textures = appearance.get("textures") or {} if not isinstance(textures, dict): raise ValueError(f"appearance.textures must be an object for {entity_id}") channels: dict[PBRChannelName, PBRChannel] = {} scalar_values: dict[str, Any] = { "albedo": appearance.get("base_color_rgb"), "roughness": appearance.get("roughness"), "metallic": appearance.get("metallic"), } for channel in ("albedo", "roughness", "metallic", "normal", "height", "ao"): texture = textures.get(channel) scalar = scalar_values.get(channel) if texture is None and scalar is None: continue if channel == "albedo" and scalar is not None: if not isinstance(scalar, (list, tuple)) or len(scalar) != 3: raise ValueError(f"base_color_rgb must contain 3 values for {entity_id}") scalar = tuple(float(item) for item in scalar) elif scalar is not None: scalar = float(scalar) channels[channel] = PBRChannel( texture=str(texture) if texture is not None else None, scalar=scalar, color_space=color_spaces[channel], ) materials.append( PBRMaterialSpec( entity_id=entity_id, material_class=material_class, profile=profile, channels=channels, uv_primvar=str(appearance.get("uv_primvar", "st")), uv_scale_m=float(appearance.get("uv_scale_m", 1.0)), normal_convention=str(appearance.get("normal_convention", "OpenGL")), opacity=float(appearance.get("opacity", 1.0)), required=bool(entity.get("required", True)), ) ) return PBRManifest(materials=materials) def validate_pbr_manifest( manifest: PBRManifest, policy: dict[str, Any], *, imported_bindings: dict[str, bool] | None = None, ) -> dict[str, Any]: bindings_supplied = imported_bindings is not None imported_bindings = imported_bindings or {} profiles = policy["profiles"] uv_limits = policy["uv_scale_m"] results: list[dict[str, Any]] = [] for material in manifest.materials: profile = profiles[material.profile] required_channels = set(profile["required_channels"]) allow_scalar = set(profile["allow_scalar"]) missing = sorted(required_channels - set(material.channels)) invalid_scalar = sorted( channel for channel, spec in material.channels.items() if spec.texture is None and channel not in allow_scalar ) wrong_color_space = sorted( channel for channel, spec in material.channels.items() if spec.color_space != policy["color_spaces"][channel] ) missing_binding = not imported_bindings.get(material.entity_id, False) uv_valid = uv_limits["minimum"] <= material.uv_scale_m <= uv_limits["maximum"] passed = ( not missing and not invalid_scalar and not wrong_color_space and uv_valid and (not bindings_supplied or not missing_binding) ) if material.profile == "imported": # Imported appearance is owned by the catalog asset. A missing # UsdShade binding may still be an MDL/displayColor/native renderer # material and cannot invalidate an otherwise physical asset. passed = True results.append( { "entity_id": material.entity_id, "material_class": material.material_class, "profile": material.profile, "passed": passed, "required": material.required, "missing_channels": missing, "invalid_scalar_channels": invalid_scalar, "wrong_color_space": wrong_color_space, "uv_scale_m": material.uv_scale_m, "uv_scale_valid": uv_valid, "imported_material_bound": imported_bindings.get(material.entity_id), } ) failed = [item["entity_id"] for item in results if item["required"] and not item["passed"]] material_warnings = { item["entity_id"]: ["source_material_binding_not_detected"] for item in results if bindings_supplied and item["profile"] == "imported" and item["imported_material_bound"] is False } return { "schema_version": "1.0", "passed": not failed, "failed_entities": failed, "material_warnings": material_warnings, "materials": results, } def _normalize_imported_material_adjustment( entity_id: str, adjustment: dict[str, Any] ) -> dict[str, Any]: allowed = {"base_color_rgb", "roughness", "metallic"} unknown = set(adjustment) - allowed if unknown: raise ValueError( f"unsupported imported material adjustment for {entity_id}: {sorted(unknown)}" ) if not adjustment: raise ValueError(f"imported material adjustment for {entity_id} is empty") normalized: dict[str, Any] = {} for name in ("roughness", "metallic"): if name not in adjustment: continue value = adjustment[name] if isinstance(value, bool): raise ValueError(f"imported {name} adjustment for {entity_id} must be numeric") try: scalar = float(value) except (TypeError, ValueError) as error: raise ValueError( f"imported {name} adjustment for {entity_id} must be numeric" ) from error if not math.isfinite(scalar) or not 0.0 <= scalar <= 1.0: raise ValueError( f"imported {name} adjustment for {entity_id} must be finite and in [0, 1]" ) normalized[name] = scalar if "base_color_rgb" in adjustment: color = adjustment["base_color_rgb"] if not isinstance(color, (list, tuple)) or len(color) != 3: raise ValueError( f"imported base_color_rgb adjustment for {entity_id} must contain 3 values" ) values: list[float] = [] for item in color: if isinstance(item, bool): raise ValueError( f"imported base_color_rgb adjustment for {entity_id} must be numeric" ) try: value = float(item) except (TypeError, ValueError) as error: raise ValueError( f"imported base_color_rgb adjustment for {entity_id} must be numeric" ) from error if not math.isfinite(value) or not 0.0 <= value <= 1.0: raise ValueError( f"imported base_color_rgb adjustment for {entity_id} must be finite and in [0, 1]" ) values.append(value) normalized["base_color_rgb"] = tuple(values) return normalized def _summarize_imported_material_adjustment( normalized: dict[str, Any], shader_paths: set[str], authored_channels: dict[str, set[str]], ) -> dict[str, Any]: """Describe a best-effort override without rejecting the source material.""" unapplied = sorted(name for name, paths in authored_channels.items() if not paths) return { **normalized, "shader_paths": sorted(shader_paths), "authored_channels": { name: sorted(paths) for name, paths in authored_channels.items() }, "fully_applied": not unapplied, "unapplied_channels": unapplied, "preserved_source_material": bool(unapplied), } def author_and_validate_pbr( root_usd: Path, task_manifest: Path, scene_manifest: Path, report_path: Path, *, policy_path: Path | None = None, ) -> dict[str, Any]: """Author task-owned PBR opinions after conversion and validate the result.""" try: from pxr import Gf, Sdf, Usd, UsdGeom, UsdShade # type: ignore[import-not-found] except ImportError as error: raise RuntimeError("pxr is required for PBR authoring and validation") from error root_usd = root_usd.resolve() task = json.loads(task_manifest.read_text(encoding="utf-8")) scene = json.loads(scene_manifest.read_text(encoding="utf-8")) policy = load_pbr_policy(policy_path) manifest = compile_pbr_manifest(task, policy) manifest_path = report_path.with_name("material_manifest.json") atomic_write_text(manifest_path, manifest.model_dump_json(indent=2) + "\n") stage = Usd.Stage.Open(str(root_usd)) if stage is None: raise RuntimeError(f"could not open composed stage: {root_usd}") # Author appearance independently from physics so either concern can be # reviewed, replaced, or hashed without mutating the other layer. material_layer_path = root_usd.parent / "layers" / "materials.usda" layer = next( ( item for item in stage.GetLayerStack() if item.realPath and Path(item.realPath).resolve() == material_layer_path.resolve() ), None, ) if layer is None: raise RuntimeError( f"material override layer is not in the stage stack: {material_layer_path}" ) stage.SetEditTarget(layer) bindings = scene.get("entity_prim_paths") or {} looks = UsdGeom.Scope.Define(stage, "/World/RoboHouseGenPBRLooks") authored: dict[str, str] = {} imported_bound: dict[str, bool] = {} missing_texture_files: dict[str, list[str]] = {} imported_adjustments: dict[str, dict[str, Any]] = {} def renderable_gprims(entity_prim: Any) -> list[Any]: """Return appearance geometry, never guide/proxy collision geometry.""" result: list[Any] = [] for item in Usd.PrimRange(entity_prim): if item.IsInstanceProxy() or not item.IsA(UsdGeom.Gprim): continue purpose = UsdGeom.Imageable(item).ComputePurpose() if purpose in {UsdGeom.Tokens.default_, UsdGeom.Tokens.render}: result.append(item) continue # Remove stale task-layer bindings produced by older versions. A # purpose=guide/proxy collider must never acquire an appearance. binding_api = UsdShade.MaterialBindingAPI(item) binding_api.UnbindDirectBinding() return result def preview_material(name: str, color: tuple[float, float, float], roughness: float, metallic: float) -> Any: material = UsdShade.Material.Define(stage, looks.GetPath().AppendChild(name)) shader = UsdShade.Shader.Define(stage, material.GetPath().AppendChild("PreviewSurface")) shader.CreateIdAttr("UsdPreviewSurface") shader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set(Gf.Vec3f(*color)) shader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set(roughness) shader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(metallic) material.CreateSurfaceOutput().ConnectToSource(shader.ConnectableAPI(), "surface") return material # The official G1 asset used by the validated runtime has correct geometry # and articulation, but its source USD ships with a single flat-white # preview material. Add a task-owned appearance layer so RTX evidence reads # as a robot, without mutating the official robot payload or physics. robot_prim = stage.GetPrimAtPath(str(scene.get("robot_prim_path") or "/World/Robot")) if robot_prim.IsValid(): robot_materials = { "shell": preview_material("g1_shell", (0.58, 0.62, 0.66), 0.3, 0.35), "joint": preview_material("g1_joint", (0.035, 0.045, 0.055), 0.38, 0.18), "head": preview_material("g1_head", (0.01, 0.015, 0.02), 0.24, 0.25), } joint_terms = ( "hip", "knee", "ankle", "waist", "shoulder", "elbow", "wrist", "hand" ) for gprim in renderable_gprims(robot_prim): path = str(gprim.GetPath()).casefold() role = "head" if "head_link" in path else "joint" if any(term in path for term in joint_terms) else "shell" UsdShade.MaterialBindingAPI.Apply(gprim).Bind( robot_materials[role], bindingStrength=UsdShade.Tokens.strongerThanDescendants ) authored["__robot_g1_appearance__"] = ",".join( str(material.GetPath()) for material in robot_materials.values() ) for entity in task.get("entities", []): if not isinstance(entity, dict): continue entity_id = str(entity.get("entity_id") or "") adjustment = (entity.get("attributes") or {}).get("imported_material_adjustment") if not isinstance(adjustment, dict): continue normalized = _normalize_imported_material_adjustment(entity_id, adjustment) entity_prim = stage.GetPrimAtPath(str(bindings.get(entity_id) or "")) shader_paths: set[str] = set() authored_channels: dict[str, set[str]] = { name: set() for name in normalized } if entity_prim: for gprim in renderable_gprims(entity_prim): material = UsdShade.MaterialBindingAPI(gprim).ComputeBoundMaterial()[0] if not material: continue for shader_prim in Usd.PrimRange(material.GetPrim()): if shader_prim.GetTypeName() != "Shader": continue shader = UsdShade.Shader(shader_prim) shader_id = str(shader.GetIdAttr().Get() or "") override = UsdShade.Shader(stage.OverridePrim(shader_prim.GetPath())) for name, value in normalized.items(): input_name = "diffuseColor" if name == "base_color_rgb" else name if shader_id != "UsdPreviewSurface" and not shader.GetInput(input_name): continue value_type = ( Sdf.ValueTypeNames.Color3f if name == "base_color_rgb" else Sdf.ValueTypeNames.Float ) authored_input = override.CreateInput(input_name, value_type) authored_input.DisconnectSource() authored_input.Set( Gf.Vec3f(*value) if name == "base_color_rgb" else value ) shader_path = str(shader_prim.GetPath()) shader_paths.add(shader_path) authored_channels[name].add(shader_path) imported_adjustments[entity_id] = _summarize_imported_material_adjustment( normalized, shader_paths, authored_channels ) for spec in manifest.materials: prim = stage.GetPrimAtPath(str(bindings.get(spec.entity_id) or "")) if not prim.IsValid(): imported_bound[spec.entity_id] = False continue gprims = renderable_gprims(prim) imported_bound[spec.entity_id] = any( UsdShade.MaterialBindingAPI(item).ComputeBoundMaterial()[0] for item in gprims ) if spec.profile == "imported": continue material = UsdShade.Material.Define(stage, looks.GetPath().AppendChild(spec.entity_id)) shader = UsdShade.Shader.Define(stage, material.GetPath().AppendChild("PreviewSurface")) shader.CreateIdAttr("UsdPreviewSurface") primvar = UsdShade.Shader.Define(stage, material.GetPath().AppendChild("PrimvarReader")) primvar.CreateIdAttr("UsdPrimvarReader_float2") primvar.CreateInput("varname", Sdf.ValueTypeNames.Token).Set(spec.uv_primvar) primvar.CreateOutput("result", Sdf.ValueTypeNames.Float2) uv_transform = UsdShade.Shader.Define(stage, material.GetPath().AppendChild("UVScale")) uv_transform.CreateIdAttr("UsdTransform2d") uv_transform.CreateInput("in", Sdf.ValueTypeNames.Float2).ConnectToSource( primvar.ConnectableAPI(), "result" ) repeat = 1.0 / spec.uv_scale_m uv_transform.CreateInput("scale", Sdf.ValueTypeNames.Float2).Set(Gf.Vec2f(repeat, repeat)) uv_transform.CreateOutput("result", Sdf.ValueTypeNames.Float2) scalar_inputs = { "albedo": ("diffuseColor", Sdf.ValueTypeNames.Color3f), "roughness": ("roughness", Sdf.ValueTypeNames.Float), "metallic": ("metallic", Sdf.ValueTypeNames.Float), } shader.CreateInput("opacity", Sdf.ValueTypeNames.Float).Set(spec.opacity) staged_channels: dict[str, str] = {} missing_textures: list[str] = [] for channel, channel_spec in spec.channels.items(): if channel_spec.scalar is not None and channel in scalar_inputs: name, value_type = scalar_inputs[channel] value: Any = channel_spec.scalar if channel == "albedo": value = Gf.Vec3f(*value) shader.CreateInput(name, value_type).Set(value) if channel_spec.texture is not None: expanded = Path(os.path.expandvars(channel_spec.texture)).expanduser() candidates = ( [expanded] if expanded.is_absolute() else [task_manifest.parent / expanded, root_usd.parent / expanded, expanded] ) approved_roots = [task_manifest.parent.resolve(), root_usd.parent.resolve()] if material_root := os.environ.get("RHG_MATERIAL_ROOT"): approved_roots.append(Path(material_root).expanduser().resolve()) source = None for candidate in candidates: if candidate.is_symlink() or not candidate.is_file(): continue resolved = candidate.resolve() if any(resolved.is_relative_to(allowed) for allowed in approved_roots): source = resolved break if source is None: missing_textures.append(f"{channel}:{channel_spec.texture}") continue source_digest = hashlib.sha256(source.read_bytes()).hexdigest()[:16] destination = ( root_usd.parent / "textures" / "pbr" / spec.entity_id / f"{source.stem}-{source_digest}{source.suffix}" ) destination.parent.mkdir(parents=True, exist_ok=True) if not destination.is_file(): try: os.link(source, destination) except OSError: shutil.copy2(source, destination) if hashlib.sha256(destination.read_bytes()).hexdigest() != hashlib.sha256(source.read_bytes()).hexdigest(): raise RuntimeError(f"PBR texture copy hash mismatch: {source}") staged_channels[channel] = destination.relative_to(root_usd.parent).as_posix() texture = UsdShade.Shader.Define( stage, material.GetPath().AppendChild(f"{channel}_texture") ) texture.CreateIdAttr("UsdUVTexture") texture.CreateInput("file", Sdf.ValueTypeNames.Asset).Set( Sdf.AssetPath(f"../{staged_channels[channel]}") ) texture.CreateInput("sourceColorSpace", Sdf.ValueTypeNames.Token).Set( channel_spec.color_space ) texture.CreateInput("st", Sdf.ValueTypeNames.Float2).ConnectToSource( uv_transform.ConnectableAPI(), "result" ) if channel in {"albedo", "normal"}: texture.CreateOutput("rgb", Sdf.ValueTypeNames.Float3) else: texture.CreateOutput("r", Sdf.ValueTypeNames.Float) if channel == "albedo": shader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).ConnectToSource( texture.ConnectableAPI(), "rgb" ) elif channel in {"roughness", "metallic"}: shader.CreateInput(channel, Sdf.ValueTypeNames.Float).ConnectToSource( texture.ConnectableAPI(), "r" ) elif channel == "normal": shader.CreateInput("normal", Sdf.ValueTypeNames.Normal3f).ConnectToSource( texture.ConnectableAPI(), "rgb" ) elif channel in {"height", "ao"}: shader.GetPrim().SetCustomDataByKey( "robothousegen:unsupported_pbr_channel", channel ) shader.GetPrim().SetCustomDataByKey("robothousegen:pbr_channels", staged_channels) shader.GetPrim().SetCustomDataByKey("robothousegen:material_class", spec.material_class) shader.GetPrim().SetCustomDataByKey("robothousegen:uv_scale_m", spec.uv_scale_m) shader.GetPrim().SetCustomDataByKey( "robothousegen:normal_convention", spec.normal_convention ) material.CreateSurfaceOutput().ConnectToSource(shader.ConnectableAPI(), "surface") for gprim in gprims: UsdShade.MaterialBindingAPI.Apply(gprim).Bind( material, bindingStrength=UsdShade.Tokens.strongerThanDescendants ) imported_bound[spec.entity_id] = bool(gprims) authored[spec.entity_id] = str(material.GetPath()) if missing_textures: missing_texture_files[spec.entity_id] = missing_textures layer.Save() report = validate_pbr_manifest(manifest, policy, imported_bindings=imported_bound) report["imported_material_adjustments"] = imported_adjustments report["material_adjustment_warnings"] = { entity_id: item["unapplied_channels"] for entity_id, item in imported_adjustments.items() if item["unapplied_channels"] } if missing_texture_files: report["passed"] = False report["failed_entities"] = sorted( set(report["failed_entities"]) | set(missing_texture_files) ) report.update( { "material_layer": material_layer_path.relative_to(root_usd.parent).as_posix(), "material_manifest": manifest_path.relative_to(root_usd.parent).as_posix(), "authored_materials": authored, "missing_texture_files": missing_texture_files, } ) atomic_write_text(report_path, json.dumps(report, ensure_ascii=False, indent=2) + "\n") return report