| |
| """ |
| Blender Scene Renderer - 用于渲染完整的 3D 场景(GLB 文件) |
| |
| 支持多种视角: |
| - diagonal: 斜角俯视图 |
| - topdown: 俯视图 |
| - front: 正面视图 |
| |
| Usage: |
| blender --background --python blender_scene_renderer.py -- \ |
| --input scene.glb --output render.png --view-mode diagonal |
| |
| 或者直接运行(需要 bpy 包): |
| python blender_scene_renderer.py --input scene.glb --output render.png --view-mode diagonal |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import math |
| import os |
| import sys |
| from typing import Tuple |
|
|
| try: |
| import bpy |
| from mathutils import Matrix, Vector |
| HAS_BPY = True |
| except ImportError: |
| HAS_BPY = False |
| print("Warning: bpy not available. This script requires Blender.") |
|
|
|
|
| def reset_scene() -> None: |
| """清空场景""" |
| bpy.ops.wm.read_factory_settings(use_empty=True) |
|
|
|
|
| def import_glb(filepath: str): |
| """导入 GLB 文件""" |
| if not os.path.exists(filepath): |
| raise FileNotFoundError(f"Input GLB not found: {filepath}") |
| |
| reset_scene() |
| bpy.ops.import_scene.gltf(filepath=filepath) |
| imported = list(bpy.context.selected_objects) |
| if not imported: |
| raise RuntimeError(f"No objects imported from {filepath}") |
| return imported |
|
|
|
|
| def compute_bounds(objects) -> Tuple[Vector, Vector, Vector, float]: |
| """计算所有 mesh 对象的边界框""" |
| min_corner = Vector((float("inf"), float("inf"), float("inf"))) |
| max_corner = Vector((float("-inf"), float("-inf"), float("-inf"))) |
| |
| has_mesh = False |
| for obj in objects: |
| if obj.type != "MESH": |
| continue |
| has_mesh = True |
| for vertex in obj.bound_box: |
| world_corner = obj.matrix_world @ Vector(vertex) |
| min_corner.x = min(min_corner.x, world_corner.x) |
| min_corner.y = min(min_corner.y, world_corner.y) |
| min_corner.z = min(min_corner.z, world_corner.z) |
| max_corner.x = max(max_corner.x, world_corner.x) |
| max_corner.y = max(max_corner.y, world_corner.y) |
| max_corner.z = max(max_corner.z, world_corner.z) |
| |
| if not has_mesh: |
| min_corner = Vector((-5, -5, 0)) |
| max_corner = Vector((5, 5, 3)) |
| |
| center = (min_corner + max_corner) * 0.5 |
| extent = max_corner - min_corner |
| radius = extent.length / 2.0 |
| |
| return min_corner, max_corner, center, max(radius, 0.5) |
|
|
|
|
| def setup_camera_diagonal(center: Vector, radius: float, distance_factor: float = 2.5) -> None: |
| """设置斜角俯视相机""" |
| camera = bpy.data.objects.get("SceneCamera") |
| if camera is None: |
| camera_data = bpy.data.cameras.new("SceneCamera") |
| camera = bpy.data.objects.new("SceneCamera", camera_data) |
| bpy.context.collection.objects.link(camera) |
| |
| bpy.context.scene.camera = camera |
| |
| |
| azimuth_rad = math.radians(45) |
| elevation_rad = math.radians(35) |
| distance = radius * distance_factor |
| |
| x = center.x + distance * math.cos(elevation_rad) * math.cos(azimuth_rad) |
| y = center.y + distance * math.cos(elevation_rad) * math.sin(azimuth_rad) |
| z = center.z + distance * math.sin(elevation_rad) |
| |
| camera.location = Vector((x, y, z)) |
| |
| direction = center - camera.location |
| if direction.length > 1e-6: |
| direction.normalize() |
| quat = direction.to_track_quat("-Z", "Y") |
| camera.rotation_euler = quat.to_euler() |
| |
| camera.data.type = "PERSP" |
| camera.data.lens = 35.0 |
| camera.data.clip_start = 0.01 |
| camera.data.clip_end = radius * 100.0 |
|
|
|
|
| def setup_camera_topdown(center: Vector, radius: float, distance_factor: float = 2.0) -> None: |
| """设置俯视相机""" |
| camera = bpy.data.objects.get("SceneCamera") |
| if camera is None: |
| camera_data = bpy.data.cameras.new("SceneCamera") |
| camera = bpy.data.objects.new("SceneCamera", camera_data) |
| bpy.context.collection.objects.link(camera) |
| |
| bpy.context.scene.camera = camera |
| |
| |
| distance = radius * distance_factor |
| camera.location = Vector((center.x, center.y, center.z + distance)) |
| |
| |
| camera.rotation_euler = (0, 0, 0) |
| |
| |
| camera.data.type = "ORTHO" |
| camera.data.ortho_scale = radius * 2.5 |
| camera.data.clip_start = 0.01 |
| camera.data.clip_end = distance * 3.0 |
|
|
|
|
| def setup_camera_front(center: Vector, radius: float, distance_factor: float = 2.5) -> None: |
| """设置正面相机""" |
| camera = bpy.data.objects.get("SceneCamera") |
| if camera is None: |
| camera_data = bpy.data.cameras.new("SceneCamera") |
| camera = bpy.data.objects.new("SceneCamera", camera_data) |
| bpy.context.collection.objects.link(camera) |
| |
| bpy.context.scene.camera = camera |
| |
| |
| distance = radius * distance_factor |
| camera.location = Vector((center.x, center.y - distance, center.z + radius * 0.3)) |
| |
| direction = center - camera.location |
| if direction.length > 1e-6: |
| direction.normalize() |
| quat = direction.to_track_quat("-Z", "Y") |
| camera.rotation_euler = quat.to_euler() |
| |
| camera.data.type = "PERSP" |
| camera.data.lens = 35.0 |
| camera.data.clip_start = 0.01 |
| camera.data.clip_end = radius * 100.0 |
|
|
|
|
| def setup_lighting(center: Vector, radius: float) -> None: |
| """设置灯光""" |
| |
| key_light = bpy.data.objects.get("KeyLight") |
| if key_light is None: |
| key_data = bpy.data.lights.new("KeyLight", type="SUN") |
| key_light = bpy.data.objects.new("KeyLight", key_data) |
| bpy.context.collection.objects.link(key_light) |
| |
| key_light.location = center + Vector((radius * 2, -radius * 2, radius * 4)) |
| key_light.data.energy = 3.0 |
| key_light.data.color = (1.0, 0.98, 0.95) |
| |
| |
| fill_light = bpy.data.objects.get("FillLight") |
| if fill_light is None: |
| fill_data = bpy.data.lights.new("FillLight", type="SUN") |
| fill_light = bpy.data.objects.new("FillLight", fill_data) |
| bpy.context.collection.objects.link(fill_light) |
| |
| fill_light.location = center + Vector((-radius * 2, radius, radius * 3)) |
| fill_light.data.energy = 1.5 |
| fill_light.data.color = (0.9, 0.95, 1.0) |
| |
| |
| back_light = bpy.data.objects.get("BackLight") |
| if back_light is None: |
| back_data = bpy.data.lights.new("BackLight", type="SUN") |
| back_light = bpy.data.objects.new("BackLight", back_data) |
| bpy.context.collection.objects.link(back_light) |
| |
| back_light.location = center + Vector((0, radius * 2, radius * 3)) |
| back_light.data.energy = 2.0 |
|
|
|
|
| def setup_world() -> None: |
| """设置世界环境""" |
| scene = bpy.context.scene |
| if scene.world is None: |
| scene.world = bpy.data.worlds.new("SceneWorld") |
| |
| world = scene.world |
| world.use_nodes = True |
| nodes = world.node_tree.nodes |
| |
| background_node = nodes.get("Background") |
| if background_node is None: |
| background_node = nodes.new(type="ShaderNodeBackground") |
| |
| |
| background_node.inputs[0].default_value = (0.9, 0.9, 0.9, 1.0) |
| background_node.inputs[1].default_value = 1.0 |
|
|
|
|
| def setup_render_settings(width: int, height: int, samples: int, engine: str = "EEVEE") -> None: |
| """配置渲染设置""" |
| scene = bpy.context.scene |
| render = scene.render |
| |
| render.resolution_x = width |
| render.resolution_y = height |
| render.resolution_percentage = 100 |
| |
| available_engines = {item.identifier for item in render.bl_rna.properties["engine"].enum_items} |
| |
| |
| is_headless = ( |
| os.environ.get("LIBGL_ALWAYS_SOFTWARE") == "1" or |
| not os.environ.get("DISPLAY") or |
| os.environ.get("BLENDER_HEADLESS") == "1" |
| ) |
| |
| |
| if is_headless and engine == "EEVEE": |
| print("Headless mode detected, switching from EEVEE to Cycles CPU") |
| engine = "CYCLES" |
| |
| if engine == "CYCLES" and "CYCLES" in available_engines: |
| render.engine = "CYCLES" |
| scene.cycles.samples = samples |
| scene.cycles.use_denoising = True |
| |
| |
| if is_headless: |
| print("Using Cycles CPU rendering for headless environment") |
| scene.cycles.device = "CPU" |
| else: |
| try: |
| bpy.context.preferences.addons["cycles"].preferences.compute_device_type = "CUDA" |
| bpy.context.preferences.addons["cycles"].preferences.get_devices() |
| for device in bpy.context.preferences.addons["cycles"].preferences.devices: |
| device.use = True |
| scene.cycles.device = "GPU" |
| except: |
| scene.cycles.device = "CPU" |
| elif not is_headless and "BLENDER_EEVEE_NEXT" in available_engines: |
| render.engine = "BLENDER_EEVEE_NEXT" |
| elif not is_headless and "BLENDER_EEVEE" in available_engines: |
| render.engine = "BLENDER_EEVEE" |
| elif "CYCLES" in available_engines: |
| |
| render.engine = "CYCLES" |
| scene.cycles.samples = samples |
| scene.cycles.use_denoising = True |
| scene.cycles.device = "CPU" |
| |
| render.image_settings.file_format = "PNG" |
| render.image_settings.color_mode = "RGBA" |
| render.image_settings.color_depth = "8" |
| render.film_transparent = True |
| |
| print(f"Render engine: {render.engine}, Device: {getattr(scene.cycles, 'device', 'N/A')}") |
|
|
|
|
| def render_scene( |
| glb_path: str, |
| output_path: str, |
| view_mode: str = "diagonal", |
| width: int = 1600, |
| height: int = 900, |
| samples: int = 64, |
| engine: str = "EEVEE" |
| ) -> bool: |
| """ |
| 渲染场景。 |
| |
| Args: |
| glb_path: 输入 GLB 文件路径 |
| output_path: 输出图片路径 |
| view_mode: 视角模式 (diagonal, topdown, front) |
| width: 图片宽度 |
| height: 图片高度 |
| samples: 渲染采样数 |
| engine: 渲染引擎 (EEVEE, CYCLES) |
| |
| Returns: |
| 是否成功 |
| """ |
| |
| objects = import_glb(glb_path) |
| |
| |
| min_corner, max_corner, center, radius = compute_bounds(objects) |
| |
| print(f"Scene bounds: min={min_corner}, max={max_corner}") |
| print(f"Scene center: {center}, radius: {radius}") |
| |
| |
| setup_lighting(center, radius) |
| setup_world() |
| setup_render_settings(width, height, samples, engine) |
| |
| |
| if view_mode == "topdown": |
| setup_camera_topdown(center, radius) |
| elif view_mode == "front": |
| setup_camera_front(center, radius) |
| else: |
| setup_camera_diagonal(center, radius) |
| |
| |
| os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True) |
| bpy.context.scene.render.filepath = output_path |
| bpy.ops.render.render(write_still=True) |
| |
| if os.path.exists(output_path): |
| print(f"Rendered: {output_path}") |
| return True |
| else: |
| print(f"Failed to render: {output_path}") |
| return False |
|
|
|
|
| def main(): |
| |
| if "--" in sys.argv: |
| argv = sys.argv[sys.argv.index("--") + 1:] |
| else: |
| argv = sys.argv[1:] |
| |
| parser = argparse.ArgumentParser(description="Render 3D scene using Blender") |
| parser.add_argument("--input", required=True, help="Input GLB file path") |
| parser.add_argument("--output", required=True, help="Output image path") |
| parser.add_argument("--view-mode", type=str, default="diagonal", |
| choices=["diagonal", "topdown", "front"], |
| help="Camera view mode") |
| parser.add_argument("--width", type=int, default=1600, help="Image width") |
| parser.add_argument("--height", type=int, default=900, help="Image height") |
| parser.add_argument("--samples", type=int, default=64, help="Render samples") |
| parser.add_argument("--engine", type=str, default="EEVEE", |
| choices=["EEVEE", "CYCLES"], |
| help="Render engine") |
| |
| args = parser.parse_args(argv) |
| |
| if not HAS_BPY: |
| print("Error: bpy module not available. Run this script with Blender.") |
| print("Usage: blender --background --python blender_scene_renderer.py -- --input scene.glb --output render.png") |
| sys.exit(1) |
| |
| try: |
| success = render_scene( |
| args.input, |
| args.output, |
| args.view_mode, |
| args.width, |
| args.height, |
| args.samples, |
| args.engine |
| ) |
| if not success: |
| sys.exit(1) |
| except Exception as e: |
| print(f"Error: {e}") |
| import traceback |
| traceback.print_exc() |
| sys.exit(1) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|