Files
Warehouse-Digital-Twin-and-…/src/warehouse_twin/interfaces/usd_generator.py
T

345 lines
15 KiB
Python

"""OpenUSD scene generator for Warehouse Robot Fleet Digital Twin.
Exports an ASCII OpenUSD (.usda) scene compliant with NVIDIA Omniverse Kit 110.4
and standard USD specifications (Z-up, 1.0 meter units). Supports visual representations
of facility geometry, zones, operational stations, charging pads, and the AMR robot fleet.
"""
from __future__ import annotations
from pathlib import Path
from typing import Any, Dict, List, Optional
from warehouse_twin.domain.robot import Robot, RobotTypeSpec
from warehouse_twin.domain.warehouse import WarehouseModel
class WarehouseUSDGenerator:
"""Generates OpenUSD (.usda) 3D scenes from WarehouseModel and Robot fleet entities."""
def __init__(
self,
model: WarehouseModel,
robots: Optional[List[Robot]] = None,
) -> None:
"""Initialize generator with physical warehouse layout model and optional robot fleet."""
self.model = model
self.robots = robots or []
@classmethod
def from_config_bundle(cls, bundle: Any) -> WarehouseUSDGenerator:
"""Construct generator loading both warehouse layout and fleet from ConfigBundle."""
model = WarehouseModel.from_config_dict(bundle.warehouse)
# Parse robot type specs
type_specs: Dict[str, RobotTypeSpec] = {}
for t_id, t_data in bundle.robots.get("robot_types", {}).items():
type_specs[t_id] = RobotTypeSpec.from_dict(t_id, t_data)
# Build robot fleet entities
robots: List[Robot] = []
for r_data in bundle.robots.get("fleet", []):
robots.append(Robot.from_fleet_dict(r_data, type_specs))
return cls(model, robots)
def generate_usda_content(self) -> str:
"""Construct valid ASCII OpenUSD 3D stage content representing the warehouse and AMRs."""
dims = self.model.dimensions
w = dims.width
d = dims.depth
h = dims.height
lines: List[str] = [
"#usda 1.0",
"(",
' defaultPrim = "World"',
' metersPerUnit = 1.0',
' upAxis = "Z"',
" doc = \"Warehouse Robot Fleet Digital Twin - 3D Facility Model\"",
")",
"",
'def Xform "World"',
"{",
" # -------------------------------------------------------------------------",
" # Environment Lighting",
" # -------------------------------------------------------------------------",
' def DistantLight "SunLight"',
" {",
" float inputs:intensity = 3500.0",
" color3f inputs:color = (0.98, 0.96, 0.92)",
" float inputs:angle = 1.0",
" double3 xformOp:rotateXYZ = (-45.0, 30.0, 0.0)",
' uniform token[] xformOpOrder = ["xformOp:rotateXYZ"]',
" }",
"",
' def DomeLight "SkyLight"',
" {",
" float inputs:intensity = 800.0",
" color3f inputs:color = (0.85, 0.90, 0.98)",
" }",
"",
" # -------------------------------------------------------------------------",
" # Facility Shell: Ground Floor & Boundary Markers",
" # -------------------------------------------------------------------------",
' def Scope "Architecture"',
" {",
' def Mesh "GroundFloor"',
" {",
" float3[] extent = [(-2.0, -2.0, -0.2), (62.0, 42.0, 0.0)]",
" int[] faceVertexCounts = [4]",
" int[] faceVertexIndices = [0, 1, 2, 3]",
f" point3f[] points = [(-2.0, -2.0, 0.0), ({w + 2.0}, -2.0, 0.0), ({w + 2.0}, {d + 2.0}, 0.0), (-2.0, {d + 2.0}, 0.0)]",
" normal3f[] normals = [(0.0, 0.0, 1.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0)]",
" color3f[] primvars:displayColor = [(0.14, 0.16, 0.19)]",
" float[] primvars:displayRoughness = [0.35]",
" }",
"",
' def Cube "NorthWallGuide"',
" {",
f" double3 xformOp:translate = ({w / 2.0}, {d + 0.5}, 1.0)",
f" double3 xformOp:scale = ({w / 2.0}, 0.15, 1.0)",
' uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]',
" color3f[] primvars:displayColor = [(0.3, 0.35, 0.4)]",
" }",
"",
' def Cube "SouthWallGuide"',
" {",
f" double3 xformOp:translate = ({w / 2.0}, -0.5, 1.0)",
f" double3 xformOp:scale = ({w / 2.0}, 0.15, 1.0)",
' uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]',
" color3f[] primvars:displayColor = [(0.3, 0.35, 0.4)]",
" }",
"",
' def Cube "EastWallGuide"',
" {",
f" double3 xformOp:translate = ({w + 0.5}, {d / 2.0}, 1.0)",
f" double3 xformOp:scale = (0.15, {d / 2.0}, 1.0)",
' uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]',
" color3f[] primvars:displayColor = [(0.3, 0.35, 0.4)]",
" }",
" }",
"",
" # -------------------------------------------------------------------------",
" # Inventory Zones (Zone A, Zone B, Zone C Demarcations)",
" # -------------------------------------------------------------------------",
' def Scope "Zones"',
" {",
]
# Zone floor pads
zone_colors = {
"zone_a": "(0.15, 0.45, 0.85)", # Vibrant blue
"zone_b": "(0.85, 0.55, 0.12)", # Warning amber
"zone_c": "(0.12, 0.68, 0.38)", # Production green
}
for z_id, zone in self.model.zones.items():
area = zone.area
zx = (area.x_min + area.x_max) / 2.0
zy = (area.y_min + area.y_max) / 2.0
sx = (area.x_max - area.x_min) / 2.0
sy = (area.y_max - area.y_min) / 2.0
color = zone_colors.get(z_id, "(0.5, 0.5, 0.5)")
lines.extend([
f' def Cube "{z_id}"',
" {",
f" double3 xformOp:translate = ({zx:.2f}, {zy:.2f}, 0.005)",
f" double3 xformOp:scale = ({sx:.2f}, {sy:.2f}, 0.005)",
' uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]',
f" color3f[] primvars:displayColor = [{color}]",
" float[] primvars:displayOpacity = [0.25]",
" }",
])
lines.extend([
" }",
"",
" # -------------------------------------------------------------------------",
" # Storage Racks (13 Inventory Catalog Locations)",
" # -------------------------------------------------------------------------",
' def Scope "StorageRacks"',
" {",
])
# Storage Rack Primitives
rack_specs = {
"zone_a": {"color": "(0.2, 0.4, 0.7)", "scale": (0.9, 0.5, 1.8)}, # High-density parts shelving
"zone_b": {"color": "(0.8, 0.5, 0.1)", "scale": (1.4, 0.7, 2.2)}, # Heavy pallet racks
"zone_c": {"color": "(0.2, 0.6, 0.4)", "scale": (1.2, 0.6, 1.6)}, # Raw material racks
}
for loc_id, loc in self.model.storage_locations.items():
spec = rack_specs.get(loc.zone, {"color": "(0.5, 0.5, 0.5)", "scale": (1.0, 0.5, 1.5)})
col = spec["color"]
sx, sy, sz = spec["scale"]
rz = sz
lines.extend([
f' def Xform "{loc_id}"',
" {",
f" double3 xformOp:translate = ({loc.position.x:.2f}, {loc.position.y:.2f}, {rz:.2f})",
f" double3 xformOp:scale = ({sx:.2f}, {sy:.2f}, {sz:.2f})",
' uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]',
"",
' def Cube "RackFrame"',
" {",
f" color3f[] primvars:displayColor = [{col}]",
" float[] primvars:displayRoughness = [0.4]",
" }",
" }",
])
lines.extend([
" }",
"",
" # -------------------------------------------------------------------------",
" # Operational Stations",
" # -------------------------------------------------------------------------",
' def Scope "Stations"',
" {",
])
for st_id, st in self.model.stations.items():
pos = st.position
if "inbound" in st.station_type.value:
st_col = "(0.85, 0.25, 0.2)"
st_dim = (1.5, 2.0, 0.15)
elif "outbound" in st.station_type.value:
st_col = "(0.9, 0.4, 0.1)"
st_dim = (1.5, 2.0, 0.15)
elif "picking" in st.station_type.value:
st_col = "(0.2, 0.75, 0.85)"
st_dim = (2.0, 1.2, 0.4)
else:
st_col = "(0.25, 0.8, 0.35)"
st_dim = (1.8, 1.8, 0.25)
lines.extend([
f' def Xform "{st_id}"',
" {",
f" double3 xformOp:translate = ({pos.x:.2f}, {pos.y:.2f}, {st_dim[2]:.2f})",
f" double3 xformOp:scale = ({st_dim[0]:.2f}, {st_dim[1]:.2f}, {st_dim[2]:.2f})",
' uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]',
"",
' def Cube "Platform"',
" {",
f" color3f[] primvars:displayColor = [{st_col}]",
" }",
" }",
])
lines.extend([
" }",
"",
" # -------------------------------------------------------------------------",
" # Autonomous Mobile Robot (AMR) Charging Bays",
" # -------------------------------------------------------------------------",
' def Scope "ChargingStations"',
" {",
])
for ch_id, ch in self.model.charging_stations.items():
pos = ch.position
lines.extend([
f' def Xform "{ch_id}"',
" {",
f" double3 xformOp:translate = ({pos.x:.2f}, {pos.y:.2f}, 0.05)",
' double3 xformOp:scale = (0.75, 0.75, 0.05)',
' uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]',
"",
' def Cube "ChargePad"',
" {",
" color3f[] primvars:displayColor = [(0.15, 0.85, 0.95)]",
" }",
"",
' def Cube "StationPedestal"',
" {",
" double3 xformOp:translate = (0.0, 0.6, 0.6)",
" double3 xformOp:scale = (0.2, 0.1, 0.6)",
' uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]',
" color3f[] primvars:displayColor = [(0.2, 0.25, 0.3)]",
" }",
" }",
])
lines.extend([
" }",
])
# -------------------------------------------------------------------------
# Autonomous Mobile Robot (AMR) Fleet (Phase 2 Addition)
# -------------------------------------------------------------------------
if self.robots:
lines.extend([
"",
" # -------------------------------------------------------------------------",
" # Autonomous Mobile Robot (AMR) Fleet",
" # -------------------------------------------------------------------------",
' def Scope "Robots"',
" {",
])
for robot in self.robots:
is_heavy = "heavy" in robot.robot_type
pos = robot.position
if is_heavy:
# Heavy AMR: Industrial Amber rugged pallet chassis (1.4m x 1.0m x 0.45m)
chassis_col = "(0.92, 0.65, 0.08)"
indicator_col = "(0.15, 0.85, 0.3)" # Emerald ready glow
scale_tuple = (0.70, 0.50, 0.225)
elev_z = 0.225
else:
# Light AMR: High-tech pearl white agile chassis (0.8m x 0.6m x 0.35m)
chassis_col = "(0.88, 0.90, 0.95)"
indicator_col = "(0.15, 0.75, 0.95)" # Electric cyan ready glow
scale_tuple = (0.40, 0.30, 0.175)
elev_z = 0.175
lines.extend([
f' def Xform "{robot.robot_id}"',
" {",
f" double3 xformOp:translate = ({pos.x:.2f}, {pos.y:.2f}, {elev_z:.3f})",
f" double3 xformOp:rotateXYZ = (0.0, 0.0, {robot.yaw_degrees:.1f})",
' uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ"]',
"",
' def Cube "Chassis"',
" {",
f" double3 xformOp:scale = ({scale_tuple[0]}, {scale_tuple[1]}, {scale_tuple[2]})",
' uniform token[] xformOpOrder = ["xformOp:scale"]',
f" color3f[] primvars:displayColor = [{chassis_col}]",
" float[] primvars:displayRoughness = [0.25]",
" }",
"",
' def Cube "StatusDome"',
" {",
f" double3 xformOp:translate = (0.0, 0.0, {scale_tuple[2] + 0.08:.3f})",
f" double3 xformOp:scale = ({scale_tuple[0] * 0.4:.3f}, {scale_tuple[1] * 0.4:.3f}, 0.05)",
' uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]',
f" color3f[] primvars:displayColor = [{indicator_col}]",
" }",
" }",
])
lines.extend([
" }",
])
lines.extend([
"}",
"",
])
return "\n".join(lines)
def export_usda(self, filepath: Path | str) -> Path:
"""Generate and save the ASCII OpenUSD (.usda) scene to disk."""
target_path = Path(filepath).resolve()
target_path.parent.mkdir(parents=True, exist_ok=True)
content = self.generate_usda_content()
target_path.write_text(content, encoding="utf-8")
return target_path