ZoneMaestro_code / tools /data_gen /compose_generated.py
kkkkiiii's picture
Add files using upload-large-folder tool
4f9eed9 verified
Raw
History Blame Contribute Delete
25.9 kB
#!/usr/bin/env python3
"""
Compose Generated Scene Script
This script takes a layout JSON (with model_uids) and composes a GLB scene.
It handles flattening of functional zones/groups and applies transforms.
Also generates room geometry (floor, walls, ceiling) from boundary_polygon.
Supports both:
- Original asset library (with per-asset-type rotation handling)
- Normalized asset library (pre-processed, no rotation needed)
"""
import os
import json
import trimesh
import numpy as np
import argparse
import sys
from pathlib import Path
from shapely.geometry import Polygon as ShapelyPolygon
from trimesh.visual import ColorVisuals
# Add project root
SCRIPT_DIR = Path(__file__).parent
REPO_ROOT = SCRIPT_DIR.parent.parent
sys.path.insert(0, str(REPO_ROOT))
# Add InternScenes_Real2Sim to path to import compose_scenes
sys.path.insert(0, os.path.join(REPO_ROOT, "InternScenes", "InternScenes_Real2Sim"))
# Import loaders
from compose_scenes import AssetMeshLoader
# Try to import normalized asset loader
try:
from tools.asset_description.normalized_asset_loader import NormalizedAssetMeshLoader
NORMALIZED_LOADER_AVAILABLE = True
except ImportError:
NORMALIZED_LOADER_AVAILABLE = False
def normalize_rotation(rot):
"""
Normalize rotation to radians.
Heuristic: if any value is outside [-2pi, 2pi], assume degrees.
"""
rot = np.array(rot, dtype=np.float64)
if np.any(np.abs(rot) > 2 * np.pi + 1e-3):
return np.radians(rot)
return rot
def get_scale_transform(mesh_size, target_size, category):
"""
Calculate scale matrix based on target size and mesh size.
Includes special handling for carpets/clothes similar to compose_scenes.py
"""
scale_matrix = np.eye(4)
# Avoid division by zero
mesh_size = np.maximum(mesh_size, 1e-6)
if category == "carpet":
scale_factors = target_size / mesh_size
# Check for orientation issues (carpet standing up)
# Heuristic from compose_scenes.py
if target_size[2]/target_size[0] > 150 or target_size[2]/target_size[1] > 150:
if target_size[2]/target_size[0] > target_size[2]/target_size[1]:
# Rotate 90 around Y
rot_mat = trimesh.transformations.rotation_matrix(0.5 * np.pi, [0, 1, 0])
new_target = np.array([target_size[2], target_size[0], target_size[1]])
scale_factors = new_target / mesh_size
scale_matrix = np.diag([scale_factors[0], scale_factors[1], scale_factors[2]/100.0, 1])
return scale_matrix @ rot_mat
else:
# Rotate 90 around X
rot_mat = trimesh.transformations.rotation_matrix(0.5 * np.pi, [1, 0, 0])
new_target = np.array([target_size[0], target_size[2], target_size[1]])
scale_factors = new_target / mesh_size
scale_matrix = np.diag([scale_factors[0], scale_factors[1], scale_factors[2]/100.0, 1])
return scale_matrix @ rot_mat
else:
scale_matrix = np.diag([scale_factors[0], scale_factors[1], scale_factors[2]/100.0, 1])
return scale_matrix
elif category == "clothes":
scale = target_size / mesh_size
min_scale = min(scale)
scale_matrix = np.diag([min_scale, min_scale, min_scale, 1])
return scale_matrix
else:
scale = target_size / mesh_size
scale_matrix = np.diag([scale[0], scale[1], scale[2], 1])
return scale_matrix
# ============================================
# Room Geometry Generation from Boundary
# ============================================
# Default colors for room structure
FLOOR_COLOR = np.array([200, 200, 200, 255], dtype=np.uint8) # Light gray
WALL_COLOR = np.array([240, 240, 240, 180], dtype=np.uint8) # White with some transparency
CEILING_COLOR = np.array([250, 250, 250, 128], dtype=np.uint8) # Very light, more transparent
def triangulate_polygon(vertices_2d: np.ndarray) -> tuple:
"""
Triangulate a 2D polygon (supports concave polygons like L-shape, H-shape).
Uses trimesh's triangulate_polygon which handles concave polygons correctly
via earcut algorithm.
Args:
vertices_2d: Nx2 array of (x, y) coordinates in order (CCW or CW)
Returns:
tuple: (vertices_2d, faces) where vertices may have additional points added
and faces is Mx3 array of face indices
"""
from shapely.geometry import Polygon as ShapelyPolygon
# Create a proper shapely polygon
polygon = ShapelyPolygon(vertices_2d)
# Fix invalid polygons
if not polygon.is_valid:
polygon = polygon.buffer(0)
# Use trimesh's triangulation which uses mapbox_earcut for concave polygons
try:
# trimesh.creation.triangulate_polygon returns (vertices, faces)
result_vertices, result_faces = trimesh.creation.triangulate_polygon(
polygon,
triangle_args=None, # Use default earcut
engine='earcut' # Explicitly use earcut for concave support
)
# Return both vertices and faces - trimesh may add/reorder vertices
return np.array(result_vertices), result_faces
except Exception as e:
print(f"Warning: trimesh triangulation failed: {e}, trying earcut directly")
# Fallback: use mapbox_earcut directly if available
try:
import mapbox_earcut as earcut
# earcut expects flattened coordinates and ring indices
rings = np.array([len(vertices_2d)]) # Single ring (no holes)
flat_coords = vertices_2d.flatten()
# Triangulate - returns flat array of triangle vertex indices
triangle_indices = earcut.triangulate_float64(flat_coords, rings)
# Reshape to Nx3
faces = np.array(triangle_indices).reshape(-1, 3)
return vertices_2d, faces
except ImportError:
print("Warning: mapbox_earcut not available, using fan triangulation")
except Exception as e:
print(f"Warning: earcut failed: {e}")
# Last resort: simple fan triangulation (only works for convex polygons)
n = len(vertices_2d)
faces = np.array([[0, i, i+1] for i in range(1, n-1)])
return vertices_2d, faces
def create_floor_mesh(floor_vertices_2d: np.ndarray, z_height: float = 0.0) -> trimesh.Trimesh:
"""
Create a floor mesh from 2D polygon vertices.
Supports concave polygons (L-shape, H-shape, etc.)
Args:
floor_vertices_2d: Nx2 array of (x, y) coordinates in order
z_height: Z coordinate for the floor (default 0)
Returns:
trimesh.Trimesh: Floor mesh
"""
try:
# Triangulate using earcut (supports concave polygons)
# triangulate_polygon returns (vertices_2d, faces) - vertices may be different from input
result_vertices_2d, faces = triangulate_polygon(floor_vertices_2d)
# Create 3D vertices from the triangulation result
vertices_3d = np.column_stack([result_vertices_2d, np.full(len(result_vertices_2d), z_height)])
floor_mesh = trimesh.Trimesh(vertices=vertices_3d, faces=faces)
floor_mesh.visual = ColorVisuals(mesh=floor_mesh, vertex_colors=np.tile(FLOOR_COLOR, (len(vertices_3d), 1)))
return floor_mesh
except Exception as e:
print(f"Warning: Failed to create floor mesh: {e}")
import traceback
traceback.print_exc()
return None
def create_ceiling_mesh(floor_vertices_2d: np.ndarray, z_height: float) -> trimesh.Trimesh:
"""
Create a ceiling mesh from 2D polygon vertices.
Supports concave polygons (L-shape, H-shape, etc.)
Args:
floor_vertices_2d: Nx2 array of (x, y) coordinates
z_height: Z coordinate for the ceiling
Returns:
trimesh.Trimesh: Ceiling mesh
"""
try:
# Triangulate using earcut (supports concave polygons)
# triangulate_polygon returns (vertices_2d, faces) - vertices may be different from input
result_vertices_2d, faces = triangulate_polygon(floor_vertices_2d)
# Create 3D vertices from the triangulation result
vertices_3d = np.column_stack([result_vertices_2d, np.full(len(result_vertices_2d), z_height)])
# Reverse face winding for ceiling (faces down)
faces = faces[:, ::-1]
ceiling_mesh = trimesh.Trimesh(vertices=vertices_3d, faces=faces)
ceiling_mesh.visual = ColorVisuals(mesh=ceiling_mesh, vertex_colors=np.tile(CEILING_COLOR, (len(vertices_3d), 1)))
return ceiling_mesh
except Exception as e:
print(f"Warning: Failed to create ceiling mesh: {e}")
import traceback
traceback.print_exc()
return None
def create_wall_mesh(v1_bottom: np.ndarray, v2_bottom: np.ndarray, height: float) -> trimesh.Trimesh:
"""
Create a single wall segment mesh.
Args:
v1_bottom: First bottom vertex (x, y, z)
v2_bottom: Second bottom vertex (x, y, z)
height: Wall height
Returns:
trimesh.Trimesh: Wall mesh
"""
v1_top = v1_bottom.copy()
v1_top[2] = v1_bottom[2] + height
v2_top = v2_bottom.copy()
v2_top[2] = v2_bottom[2] + height
# Create quad as two triangles
vertices = np.array([v1_bottom, v2_bottom, v2_top, v1_top])
faces = np.array([[0, 1, 2], [0, 2, 3]])
wall_mesh = trimesh.Trimesh(vertices=vertices, faces=faces)
wall_mesh.visual = ColorVisuals(mesh=wall_mesh, vertex_colors=np.tile(WALL_COLOR, (4, 1)))
return wall_mesh
def create_walls_mesh(floor_vertices_2d: np.ndarray, floor_z: float, height: float) -> trimesh.Trimesh:
"""
Create all wall meshes from floor polygon.
Args:
floor_vertices_2d: Nx2 array of (x, y) floor coordinates
floor_z: Z coordinate of the floor
height: Wall height
Returns:
trimesh.Trimesh: Combined walls mesh
"""
wall_meshes = []
n = len(floor_vertices_2d)
for i in range(n):
v1_2d = floor_vertices_2d[i]
v2_2d = floor_vertices_2d[(i + 1) % n]
v1_bottom = np.array([v1_2d[0], v1_2d[1], floor_z])
v2_bottom = np.array([v2_2d[0], v2_2d[1], floor_z])
wall = create_wall_mesh(v1_bottom, v2_bottom, height)
if wall is not None:
wall_meshes.append(wall)
if wall_meshes:
return trimesh.util.concatenate(wall_meshes)
return None
def generate_room_geometry(layout: dict, add_floor: bool = True, add_walls: bool = True, add_ceiling: bool = True) -> list:
"""
Generate room geometry (floor, walls, ceiling) from layout's architecture data.
Args:
layout: Layout dictionary containing 'architecture' with 'boundary_polygon' and 'height'
add_floor: Whether to add floor mesh
add_walls: Whether to add wall meshes
add_ceiling: Whether to add ceiling mesh
Returns:
List of (name, mesh) tuples
"""
geometries = []
architecture = layout.get("architecture", {})
boundary_polygon = architecture.get("boundary_polygon", [])
height = architecture.get("height", 2.6) # Default 2.6m height
if not boundary_polygon:
print("Warning: No boundary_polygon found in architecture, skipping room geometry")
return geometries
# Parse boundary polygon
# Format: [[x, y, z], ...] - first half are floor vertices, second half are ceiling vertices
# Or it could be just floor vertices with separate height
boundary_polygon = np.array(boundary_polygon)
if len(boundary_polygon) == 0:
return geometries
# Determine floor and ceiling vertices
# Usually boundary_polygon contains floor vertices (z=0) and ceiling vertices (z=height)
# Split by z coordinate
if boundary_polygon.shape[1] >= 3:
z_values = boundary_polygon[:, 2]
z_min = np.min(z_values)
z_max = np.max(z_values)
# If all z values are the same, use height parameter
if abs(z_max - z_min) < 0.01:
floor_vertices = boundary_polygon
floor_z = z_min
ceiling_z = z_min + height
else:
# Split into floor and ceiling based on z
z_mid = (z_min + z_max) / 2
floor_mask = z_values < z_mid
floor_vertices = boundary_polygon[floor_mask]
ceiling_vertices = boundary_polygon[~floor_mask]
if len(floor_vertices) == 0:
floor_vertices = ceiling_vertices
floor_z = z_min
else:
floor_z = floor_vertices[0, 2] if len(floor_vertices) > 0 else z_min
ceiling_z = z_max
height = ceiling_z - floor_z
else:
# 2D polygon, assume z=0 for floor
floor_vertices = np.column_stack([boundary_polygon, np.zeros(len(boundary_polygon))])
floor_z = 0
ceiling_z = height
# Extract 2D coordinates (x, y) for triangulation
floor_vertices_2d = floor_vertices[:, :2]
# Create floor
if add_floor:
floor_mesh = create_floor_mesh(floor_vertices_2d, floor_z)
if floor_mesh is not None:
geometries.append(("floor", floor_mesh))
# Create walls
if add_walls:
walls_mesh = create_walls_mesh(floor_vertices_2d, floor_z, height)
if walls_mesh is not None:
geometries.append(("walls", walls_mesh))
# Create ceiling
if add_ceiling:
ceiling_mesh = create_ceiling_mesh(floor_vertices_2d, ceiling_z)
if ceiling_mesh is not None:
geometries.append(("ceiling", ceiling_mesh))
return geometries
def compose_scene(layout, output_path, add_floor=True, add_walls=True, add_ceiling=True,
input_coord_system="z-up", use_normalized_assets=True, normalized_asset_dir=None):
"""
Compose a scene from layout JSON.
Args:
layout: layout JSON
output_path: Path to output GLB file
add_floor: Whether to add floor mesh
add_walls: Whether to add wall meshes
add_ceiling: Whether to add ceiling mesh
input_coord_system: Coordinate system of input data. "z-up" (default) or "y-up"
use_normalized_assets: If True, use pre-normalized assets (no per-type rotation)
normalized_asset_dir: Path to normalized asset library (only if use_normalized_assets=True)
"""
# 如果没有指定路径,从环境变量读取
if normalized_asset_dir is None:
normalized_asset_dir = os.environ.get('PTH_ASSET_NORMALIZED_LIBRARY')
if not normalized_asset_dir:
# 优先使用 ~/backup (本地环境),如果不存在则使用 /backup (集群环境)
home_path = os.path.expanduser("~/backup/datas/InternScenes/asset_library_normalized")
if os.path.exists(home_path):
normalized_asset_dir = home_path
else:
normalized_asset_dir = "/backup/datas/InternScenes/asset_library_normalized"
# with open(layout_path, 'r') as f:
# layout = json.load(f)
# Auto-detect coordinate system from meta if available
meta = layout.get("meta", {})
if "coordinate_system" in meta:
detected = meta["coordinate_system"].lower().replace("_", "-")
if detected in ["z-up", "zup"]:
input_coord_system = "z-up"
elif detected in ["y-up", "yup"]:
input_coord_system = "y-up"
print(f"Using coordinate system: {input_coord_system}")
# Select asset loader
if use_normalized_assets:
if not NORMALIZED_LOADER_AVAILABLE:
raise ImportError("NormalizedAssetMeshLoader not available. Please check installation.")
loader = NormalizedAssetMeshLoader(normalized_asset_dir)
print(f"Using normalized asset library: {loader.asset_dir}")
else:
loader = AssetMeshLoader()
print("Using original asset library with per-type rotation")
scene = trimesh.Scene()
# Flatten assets
instances = []
if "assets" in layout:
instances.extend(layout["assets"])
if "functional_zones" in layout:
for zone in layout["functional_zones"]:
if "assets" in zone:
instances.extend(zone["assets"])
if "groups" in layout:
for group in layout["groups"]:
if "objects" in group:
instances.extend(group["objects"])
print(f"Composing scene with {len(instances)} instances...")
for i, instance in enumerate(instances):
uid = instance.get("model_uid")
if not uid:
continue
try:
# Load canonical mesh (centers and aligns)
# use_texture=True is important for rendering
mesh = loader.load_canonical_mesh(uid, use_texture=True)
if mesh is None:
print(f"Warning: Mesh not found for {uid}")
continue
# Extract transform data
pos = None
rot = None
size = None
# Case 1: Nested transform (Unified Layout / 3D-FRONT)
if "transform" in instance and isinstance(instance["transform"], dict):
t = instance["transform"]
pos = t.get("pos")
rot = t.get("rot")
size = t.get("size")
# Case 2: Flat structure (Zones Data / Model Output)
if pos is None:
pos = instance.get("pos")
if rot is None:
rot = instance.get("rot")
if size is None:
size = instance.get("size")
# Case 3: Legacy bbox (9 elements)
if pos is None and "bbox" in instance:
bbox = instance["bbox"]
pos = bbox[0:3]
size = bbox[3:6]
rot = bbox[6:9]
# Case 4: Matrix transform (fallback)
if pos is None and "transform" in instance and isinstance(instance["transform"], list):
# This is a raw matrix, we can just use it directly if we trust it
# But usually we want to use the decomposed values if available
transform_matrix = np.array(instance["transform"]).reshape(4, 4)
# Apply directly
scene.add_geometry(mesh, transform=transform_matrix)
continue
if pos is None or rot is None or size is None:
print(f"Warning: Missing transform data for {uid}")
continue
# Convert to numpy
pos = np.array(pos, dtype=np.float64)
rot = np.array(rot, dtype=np.float64)
size = np.array(size, dtype=np.float64)
# --- Coordinate System Handling ---
if input_coord_system == "y-up":
# Convert Y-up to Z-up: [x, y, z]_Yup -> [x, z, y]_Zup
pos = np.array([pos[0], pos[2], pos[1]])
size = np.array([size[0], size[2], size[1]])
rot = np.array([rot[0], rot[2], rot[1]])
# else: input is already Z-up, no conversion needed
# Adjust for Floor Alignment
# In Z-up, Z is height. If pos[2] ≈ 0 (object on floor),
# we need to lift it by half its height (size[2]) since mesh is centered.
if abs(pos[2]) < 1e-3:
pos[2] = size[2] / 2.0
# ---------------------------------------------------
# Normalize rotation (degrees -> radians if needed)
rot = normalize_rotation(rot)
# Start with identity
transform_final = np.eye(4)
# 1. Scale
mesh_size = mesh.bounding_box.extents
category = instance.get("category", "")
scale_mat = get_scale_transform(mesh_size, size, category)
transform_final = scale_mat @ transform_final
# 2. Rotation
# Use rzxy order as per compose_scenes.py
# Note: compose_scenes.py uses euler_matrix(rot[0], rot[1], rot[2], axes='rzxy')
# where rot is [rx, ry, rz] (or [rx, rz, ry] after our conversion).
# 'rzxy' means rotate around Z, then X, then Y.
# The input 'rot' from layout is typically [0, rotation_y, 0] for simple objects.
# After our conversion to Z-up, it becomes [0, 0, rotation_y].
# So rot[0]=0, rot[1]=0, rot[2]=rotation_y.
# euler_matrix(0, 0, rotation_y, 'rzxy') -> rotates around Z by rotation_y. Correct.
rot_mat = trimesh.transformations.euler_matrix(rot[0], rot[1], rot[2], axes='rzxy')
transform_final = rot_mat @ transform_final
# 3. Translation
transform_final[:3, 3] = pos
# 4. Global Rotation (Z-up to Y-up)
# compose_scenes.py applies -90 deg around X at the end
global_rot = trimesh.transformations.rotation_matrix(-np.pi / 2, [1, 0, 0])
transform_final = global_rot @ transform_final
# Add to scene
# We use a unique node name to avoid conflicts
node_name = f"{i}_{uid.replace('/', '_')}"
# Create a parent node with the transform (same as compose_scenes.py)
scene.graph.update(frame_to=node_name, matrix=transform_final)
# Handle both Trimesh and Scene types
if isinstance(mesh, trimesh.Scene):
# Add all geometries from the sub-scene as children
for geom_name, mesh_part in mesh.geometry.items():
nodes_for_geom = mesh.graph.geometry_nodes.get(geom_name, [])
for j, sub_node in enumerate(nodes_for_geom):
internal_transform, _ = mesh.graph.get(sub_node)
scene.add_geometry(
mesh_part,
geom_name=f"{node_name}_{geom_name}_{j}",
transform=internal_transform,
parent_node_name=node_name
)
else:
# Simple Trimesh - add as child of parent node (same as compose_scenes.py)
scene.add_geometry(
mesh,
geom_name=f"{node_name}_geom",
parent_node_name=node_name
)
except Exception as e:
print(f"Error processing {uid}: {e}")
import traceback
traceback.print_exc()
continue
# Generate and add room geometry (floor, walls, ceiling)
print("Generating room geometry from boundary polygon...")
room_geometries = generate_room_geometry(layout, add_floor=add_floor, add_walls=add_walls, add_ceiling=add_ceiling)
for name, geom in room_geometries:
# Apply the same global rotation to room geometry
global_rot = trimesh.transformations.rotation_matrix(-np.pi / 2, [1, 0, 0])
scene.add_geometry(geom, node_name=name, transform=global_rot)
print(f" Added {name} geometry")
if not room_geometries:
print(" Warning: No room geometry generated (missing boundary_polygon in architecture)")
# Export
print(f"Exporting scene to {output_path}")
os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True)
scene.export(output_path)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--input", required=True, help="Input layout JSON file")
parser.add_argument("--output", required=True, help="Output GLB file")
parser.add_argument("--no-floor", action="store_true", help="Don't add floor mesh")
parser.add_argument("--no-walls", action="store_true", help="Don't add wall meshes")
parser.add_argument("--no-ceiling", action="store_true", help="Don't add ceiling mesh")
parser.add_argument("--coord-system", type=str, default="z-up", choices=["z-up", "y-up"],
help="Input coordinate system (default: z-up)")
parser.add_argument("--use-normalized", default=True,
help="Use pre-normalized asset library (no per-type rotations needed)")
# 默认路径逻辑:优先 ~/backup,否则 /backup
_default_normalized_dir = os.environ.get('PTH_ASSET_NORMALIZED_LIBRARY')
if not _default_normalized_dir:
_home_path = os.path.expanduser("~/backup/datas/InternScenes/asset_library_normalized")
_default_normalized_dir = _home_path if os.path.exists(_home_path) else "/backup/datas/InternScenes/asset_library_normalized"
parser.add_argument("--normalized-dir", type=str, default=_default_normalized_dir,
help="Path to normalized asset directory (required if --use-normalized)")
args = parser.parse_args()
# Validate normalized asset arguments
if args.use_normalized and not args.normalized_dir:
parser.error("--normalized-dir is required when using --use-normalized")
compose_scene(
args.input,
args.output,
add_floor=not args.no_floor,
add_walls=not args.no_walls,
add_ceiling=not args.no_ceiling,
input_coord_system=args.coord_system,
use_normalized_assets=args.use_normalized,
normalized_asset_dir=args.normalized_dir
)