| |
| """ |
| 批量渲染 IDesign 生成的场景 |
| 需要在 blender conda 环境下运行: conda activate blender |
| """ |
|
|
| import bpy |
| import json |
| import math |
| import os |
| import sys |
| from pathlib import Path |
| from datetime import datetime |
|
|
|
|
| def clear_scene(): |
| """清空场景""" |
| bpy.ops.object.select_all(action='SELECT') |
| bpy.ops.object.delete() |
| |
| |
| for block in bpy.data.meshes: |
| if block.users == 0: |
| bpy.data.meshes.remove(block) |
| for block in bpy.data.materials: |
| if block.users == 0: |
| bpy.data.materials.remove(block) |
|
|
|
|
| def import_glb(file_path, object_name): |
| """导入GLB文件""" |
| try: |
| bpy.ops.import_scene.gltf(filepath=file_path) |
| |
| imported = [obj for obj in bpy.context.selected_objects] |
| if imported: |
| |
| if len(imported) > 1: |
| bpy.ops.object.empty_add(type='PLAIN_AXES') |
| parent = bpy.context.active_object |
| parent.name = object_name |
| for obj in imported: |
| obj.parent = parent |
| return parent |
| else: |
| imported[0].name = object_name |
| return imported[0] |
| except Exception as e: |
| print(f" 导入失败 {object_name}: {e}") |
| return None |
|
|
|
|
| def create_room(width, depth, height): |
| """创建房间""" |
| |
| bpy.ops.mesh.primitive_plane_add(size=1, location=(width/2, depth/2, 0)) |
| floor = bpy.context.active_object |
| floor.scale = (width, depth, 1) |
| floor.name = "Floor" |
| |
| |
| floor_mat = bpy.data.materials.new(name="FloorMat") |
| floor_mat.use_nodes = True |
| floor_mat.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = (0.8, 0.75, 0.7, 1) |
| floor.data.materials.append(floor_mat) |
| |
| |
| bpy.ops.mesh.primitive_plane_add(size=1, location=(width/2, 0.01, height/2)) |
| back_wall = bpy.context.active_object |
| back_wall.scale = (width, 1, height) |
| back_wall.rotation_euler = (math.radians(90), 0, 0) |
| back_wall.name = "BackWall" |
| |
| |
| bpy.ops.mesh.primitive_plane_add(size=1, location=(0.01, depth/2, height/2)) |
| left_wall = bpy.context.active_object |
| left_wall.scale = (depth, 1, height) |
| left_wall.rotation_euler = (math.radians(90), 0, math.radians(90)) |
| left_wall.name = "LeftWall" |
| |
| |
| wall_mat = bpy.data.materials.new(name="WallMat") |
| wall_mat.use_nodes = True |
| wall_mat.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = (0.95, 0.95, 0.95, 1) |
| back_wall.data.materials.append(wall_mat) |
| left_wall.data.materials.append(wall_mat) |
|
|
|
|
| def setup_camera_and_lights(room_dims): |
| """设置相机和灯光""" |
| width, depth, height = room_dims |
| |
| |
| cam_x = width * 1.8 |
| cam_y = depth * 1.8 |
| cam_z = height * 1.5 |
| |
| bpy.ops.object.camera_add(location=(cam_x, cam_y, cam_z)) |
| camera = bpy.context.active_object |
| camera.name = "Camera" |
| |
| |
| target_x, target_y, target_z = width/2, depth/2, height/3 |
| |
| |
| dx = target_x - cam_x |
| dy = target_y - cam_y |
| dz = target_z - cam_z |
| |
| |
| dist_xy = math.sqrt(dx*dx + dy*dy) |
| rot_x = math.atan2(-dz, dist_xy) |
| rot_z = math.atan2(dy, dx) |
| |
| camera.rotation_euler = (math.pi/2 + rot_x, 0, rot_z + math.pi/2) |
| bpy.context.scene.camera = camera |
| |
| |
| bpy.ops.object.light_add(type='SUN', location=(width/2, depth/2, height + 3)) |
| sun = bpy.context.active_object |
| sun.name = "Sun" |
| sun.data.energy = 3 |
| sun.rotation_euler = (math.radians(45), math.radians(30), 0) |
| |
| |
| bpy.ops.object.light_add(type='AREA', location=(width*1.5, depth*1.5, height)) |
| area = bpy.context.active_object |
| area.name = "FillLight" |
| area.data.energy = 100 |
| area.data.size = 3 |
|
|
|
|
| def render_to_file(output_path, resolution=(800, 600), samples=32): |
| """渲染到文件""" |
| scene = bpy.context.scene |
| |
| scene.render.engine = 'CYCLES' |
| scene.render.resolution_x = resolution[0] |
| scene.render.resolution_y = resolution[1] |
| scene.cycles.samples = samples |
| scene.cycles.use_denoising = True |
| |
| |
| try: |
| prefs = bpy.context.preferences.addons['cycles'].preferences |
| prefs.compute_device_type = 'CUDA' |
| scene.cycles.device = 'GPU' |
| prefs.get_devices() |
| for device in prefs.devices: |
| device.use = True |
| except: |
| pass |
| |
| scene.render.filepath = str(output_path) |
| scene.render.image_settings.file_format = 'PNG' |
| bpy.ops.render.render(write_still=True) |
|
|
|
|
| def render_single_scene(scene_dir): |
| """渲染单个场景""" |
| scene_dir = Path(scene_dir) |
| |
| |
| scene_graph_json = scene_dir / "scene_graph.json" |
| if not scene_graph_json.exists(): |
| print(f" ⚠️ 无 scene_graph.json") |
| return False |
| |
| |
| assets_dir = None |
| for dirname in ['Assets', 'objects', 'glb']: |
| d = scene_dir / dirname |
| if d.exists() and any(d.glob('*.glb')): |
| assets_dir = d |
| break |
| |
| if not assets_dir: |
| print(f" ⚠️ 无 GLB 文件目录") |
| return False |
| |
| |
| with open(scene_graph_json, 'r') as f: |
| scene_data = json.load(f) |
| |
| |
| if isinstance(scene_data, dict): |
| objects_list = scene_data.get('objects_in_room', []) |
| else: |
| objects_list = scene_data |
| |
| |
| room_dims = [4, 4, 2.8] |
| for obj in objects_list: |
| obj_id = obj.get('new_object_id', '') |
| if obj_id == 'middle of the room': |
| size = obj.get('size_in_meters', {}) |
| room_dims = [ |
| size.get('length', 4), |
| size.get('width', 4), |
| 2.8 |
| ] |
| elif obj_id == 'ceiling': |
| pos = obj.get('position', {}) |
| if pos: |
| room_dims[2] = pos.get('z', 2.8) |
| |
| |
| valid_objects = [] |
| for obj in objects_list: |
| obj_id = obj.get('new_object_id', '') |
| if obj_id in ['south_wall', 'north_wall', 'east_wall', 'west_wall', 'middle of the room', 'ceiling']: |
| continue |
| |
| |
| pos = obj.get('position', {}) |
| if pos and 'x' in pos: |
| |
| glb_file = assets_dir / f"{obj_id}.glb" |
| if glb_file.exists(): |
| valid_objects.append((obj, glb_file)) |
| |
| if not valid_objects: |
| print(f" ⚠️ 无有效物体") |
| return False |
| |
| |
| clear_scene() |
| |
| |
| create_room(room_dims[0], room_dims[1], room_dims[2]) |
| |
| |
| loaded = 0 |
| for obj_data, glb_file in valid_objects: |
| obj_id = obj_data.get('new_object_id', '') |
| imported = import_glb(str(glb_file), obj_id) |
| |
| if imported: |
| |
| pos = obj_data.get('position', {}) |
| imported.location = (pos.get('x', 0), pos.get('y', 0), pos.get('z', 0)) |
| |
| |
| rot = obj_data.get('rotation', {}) |
| if isinstance(rot, dict): |
| z_angle = rot.get('z_angle', 0) |
| else: |
| z_angle = rot if rot else 0 |
| imported.rotation_euler = (0, 0, math.radians(z_angle)) |
| |
| |
| size = obj_data.get('size_in_meters', {}) |
| if size and imported.dimensions[0] > 0: |
| target = [size.get('length', 1), size.get('width', 1), size.get('height', 1)] |
| dims = imported.dimensions |
| scale = [target[i] / max(dims[i], 0.001) for i in range(3)] |
| imported.scale = scale |
| |
| loaded += 1 |
| |
| |
| setup_camera_and_lights(room_dims) |
| |
| |
| output_path = scene_dir / "render.png" |
| render_to_file(output_path) |
| |
| print(f" ✅ 完成 ({loaded} 物体)") |
| return True |
|
|
|
|
| def batch_render(results_dir, max_scenes=None): |
| """批量渲染""" |
| results_dir = Path(results_dir) |
| |
| if not results_dir.exists(): |
| print(f"目录不存在: {results_dir}") |
| return |
| |
| |
| scene_dirs = [d for d in results_dir.iterdir() |
| if d.is_dir() and (d / "scene_graph.json").exists()] |
| |
| if max_scenes: |
| scene_dirs = scene_dirs[:max_scenes] |
| |
| print(f"\n📂 找到 {len(scene_dirs)} 个场景") |
| |
| success = 0 |
| skipped = 0 |
| |
| for i, scene_dir in enumerate(scene_dirs, 1): |
| |
| if (scene_dir / "render.png").exists(): |
| print(f"[{i}/{len(scene_dirs)}] {scene_dir.name} - 已存在,跳过") |
| skipped += 1 |
| continue |
| |
| print(f"[{i}/{len(scene_dirs)}] {scene_dir.name}") |
| try: |
| if render_single_scene(scene_dir): |
| success += 1 |
| except Exception as e: |
| print(f" ❌ 错误: {e}") |
| |
| print(f"\n✅ 完成: {success} 成功, {skipped} 跳过, {len(scene_dirs) - success - skipped} 失败") |
|
|
|
|
| if __name__ == "__main__": |
| import argparse |
| parser = argparse.ArgumentParser() |
| parser.add_argument("--dataset", choices=["zones", "bench", "all"], default="all") |
| parser.add_argument("--max", type=int, default=None) |
| parser.add_argument("--single", type=str, default=None) |
| args = parser.parse_args() |
| |
| print(f"\n{'='*60}") |
| print(f"🎬 IDesign 批量渲染") |
| print(f"{'='*60}") |
| print(f"时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") |
| |
| if args.single: |
| render_single_scene(args.single) |
| else: |
| if args.dataset in ["zones", "all"]: |
| print("\n--- Zones 数据集 ---") |
| batch_render("/home/v-meiszhang/amlt-project/MetaSpatial/IDesign/evaluation/evaluation_results", args.max) |
| |
| if args.dataset in ["bench", "all"]: |
| print("\n--- Bench 数据集 ---") |
| batch_render("/home/v-meiszhang/amlt-project/MetaSpatial/IDesign/evaluation/layout_bench_results", args.max) |
| |
| print(f"\n{'='*60}") |
| print("✅ 渲染任务完成") |
|
|