| |
| """ |
| 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 |
|
|
| |
| SCRIPT_DIR = Path(__file__).parent |
| REPO_ROOT = SCRIPT_DIR.parent.parent |
| sys.path.insert(0, str(REPO_ROOT)) |
|
|
| |
| sys.path.insert(0, os.path.join(REPO_ROOT, "InternScenes", "InternScenes_Real2Sim")) |
|
|
| |
| from compose_scenes import AssetMeshLoader |
|
|
| |
| 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) |
| |
| |
| mesh_size = np.maximum(mesh_size, 1e-6) |
| |
| if category == "carpet": |
| scale_factors = target_size / mesh_size |
| |
| |
| 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]: |
| |
| 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: |
| |
| 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 |
|
|
|
|
| |
| |
| |
|
|
| |
| FLOOR_COLOR = np.array([200, 200, 200, 255], dtype=np.uint8) |
| WALL_COLOR = np.array([240, 240, 240, 180], dtype=np.uint8) |
| CEILING_COLOR = np.array([250, 250, 250, 128], dtype=np.uint8) |
|
|
|
|
| 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 |
| |
| |
| polygon = ShapelyPolygon(vertices_2d) |
| |
| |
| if not polygon.is_valid: |
| polygon = polygon.buffer(0) |
| |
| |
| try: |
| |
| result_vertices, result_faces = trimesh.creation.triangulate_polygon( |
| polygon, |
| triangle_args=None, |
| engine='earcut' |
| ) |
| |
| |
| return np.array(result_vertices), result_faces |
| |
| except Exception as e: |
| print(f"Warning: trimesh triangulation failed: {e}, trying earcut directly") |
| |
| |
| try: |
| import mapbox_earcut as earcut |
| |
| |
| rings = np.array([len(vertices_2d)]) |
| flat_coords = vertices_2d.flatten() |
| |
| |
| triangle_indices = earcut.triangulate_float64(flat_coords, rings) |
| |
| |
| 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}") |
| |
| |
| 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: |
| |
| |
| result_vertices_2d, faces = triangulate_polygon(floor_vertices_2d) |
| |
| |
| 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: |
| |
| |
| result_vertices_2d, faces = triangulate_polygon(floor_vertices_2d) |
| |
| |
| vertices_3d = np.column_stack([result_vertices_2d, np.full(len(result_vertices_2d), z_height)]) |
| |
| |
| 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 |
| |
| |
| 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) |
| |
| if not boundary_polygon: |
| print("Warning: No boundary_polygon found in architecture, skipping room geometry") |
| return geometries |
| |
| |
| |
| |
| boundary_polygon = np.array(boundary_polygon) |
| |
| if len(boundary_polygon) == 0: |
| return geometries |
| |
| |
| |
| |
| if boundary_polygon.shape[1] >= 3: |
| z_values = boundary_polygon[:, 2] |
| z_min = np.min(z_values) |
| z_max = np.max(z_values) |
| |
| |
| if abs(z_max - z_min) < 0.01: |
| floor_vertices = boundary_polygon |
| floor_z = z_min |
| ceiling_z = z_min + height |
| else: |
| |
| 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: |
| |
| floor_vertices = np.column_stack([boundary_polygon, np.zeros(len(boundary_polygon))]) |
| floor_z = 0 |
| ceiling_z = height |
| |
| |
| floor_vertices_2d = floor_vertices[:, :2] |
| |
| |
| if add_floor: |
| floor_mesh = create_floor_mesh(floor_vertices_2d, floor_z) |
| if floor_mesh is not None: |
| geometries.append(("floor", floor_mesh)) |
| |
| |
| 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)) |
| |
| |
| 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: |
| |
| 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" |
| |
| |
| |
| |
| |
| 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}") |
| |
| |
| 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() |
| |
| |
| 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: |
| |
| |
| mesh = loader.load_canonical_mesh(uid, use_texture=True) |
| if mesh is None: |
| print(f"Warning: Mesh not found for {uid}") |
| continue |
| |
| |
| pos = None |
| rot = None |
| size = None |
| |
| |
| if "transform" in instance and isinstance(instance["transform"], dict): |
| t = instance["transform"] |
| pos = t.get("pos") |
| rot = t.get("rot") |
| size = t.get("size") |
| |
| |
| if pos is None: |
| pos = instance.get("pos") |
| if rot is None: |
| rot = instance.get("rot") |
| if size is None: |
| size = instance.get("size") |
| |
| |
| if pos is None and "bbox" in instance: |
| bbox = instance["bbox"] |
| pos = bbox[0:3] |
| size = bbox[3:6] |
| rot = bbox[6:9] |
|
|
| |
| if pos is None and "transform" in instance and isinstance(instance["transform"], list): |
| |
| |
| transform_matrix = np.array(instance["transform"]).reshape(4, 4) |
| |
| 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 |
|
|
| |
| pos = np.array(pos, dtype=np.float64) |
| rot = np.array(rot, dtype=np.float64) |
| size = np.array(size, dtype=np.float64) |
| |
| |
| if input_coord_system == "y-up": |
| |
| 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]]) |
| |
| |
| |
| |
| |
| if abs(pos[2]) < 1e-3: |
| pos[2] = size[2] / 2.0 |
| |
| |
| |
| rot = normalize_rotation(rot) |
| |
| |
| transform_final = np.eye(4) |
| |
| |
| 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 |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| rot_mat = trimesh.transformations.euler_matrix(rot[0], rot[1], rot[2], axes='rzxy') |
| transform_final = rot_mat @ transform_final |
| |
| |
| transform_final[:3, 3] = pos |
| |
| |
| |
| global_rot = trimesh.transformations.rotation_matrix(-np.pi / 2, [1, 0, 0]) |
| transform_final = global_rot @ transform_final |
| |
| |
| |
| node_name = f"{i}_{uid.replace('/', '_')}" |
| |
| |
| scene.graph.update(frame_to=node_name, matrix=transform_final) |
| |
| |
| if isinstance(mesh, trimesh.Scene): |
| |
| 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: |
| |
| 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 |
| |
| |
| 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: |
| |
| 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)") |
| |
| |
| 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)") |
| |
| _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() |
| |
| |
| 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 |
| ) |
|
|