| |
| """ |
| 高质量 Blender 场景渲染脚本 (对齐 InternScenes 渲染器) |
| |
| 使用方法: |
| conda activate blender |
| python visualize_blender_hq.py --scene_path scene.json --output render.png --view diagonal |
| |
| 坐标系说明: |
| - 输入JSON使用 Z-up 右手坐标系 |
| - Blender 也使用 Z-up 右手坐标系 (无需转换) |
| """ |
|
|
| from __future__ import annotations |
|
|
| import json |
| import math |
| import os |
| import sys |
| import argparse |
| from dataclasses import dataclass |
| from pathlib import Path |
| from typing import Dict, List, Sequence, Tuple, Optional, Iterable |
|
|
| import bpy |
| import bmesh |
| from mathutils import Vector, Euler, Matrix |
|
|
| try: |
| from PIL import Image |
| HAS_PIL = True |
| except ImportError: |
| HAS_PIL = False |
|
|
|
|
| |
| |
| |
|
|
| @dataclass |
| class SceneBounds: |
| """Axis-aligned bounds for the scene.""" |
| min_corner: Vector |
| max_corner: Vector |
|
|
| @property |
| def center(self) -> Vector: |
| return (self.min_corner + self.max_corner) * 0.5 |
|
|
| @property |
| def extent(self) -> Vector: |
| return self.max_corner - self.min_corner |
|
|
| @property |
| def radius(self) -> float: |
| return self.extent.length |
|
|
|
|
| def compute_bounds_from_objects(objects: Sequence[bpy.types.Object]) -> SceneBounds: |
| """Compute bounding box from mesh objects.""" |
| 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: |
| |
| return SceneBounds(min_corner=Vector((0, 0, 0)), max_corner=Vector((10, 10, 3))) |
|
|
| return SceneBounds(min_corner=min_corner, max_corner=max_corner) |
|
|
|
|
| def compute_bounds_from_boundary(boundary_polygon: List) -> Optional[SceneBounds]: |
| """Compute bounds from boundary polygon.""" |
| if not boundary_polygon or len(boundary_polygon) < 3: |
| return None |
| |
| xs, ys = [], [] |
| for v in boundary_polygon: |
| if isinstance(v, dict): |
| xs.append(v.get('x', v.get(0, 0))) |
| ys.append(v.get('z', v.get('y', v.get(1, 0)))) |
| elif isinstance(v, (list, tuple)) and len(v) >= 2: |
| xs.append(v[0]) |
| ys.append(v[1]) |
| |
| if not xs or not ys: |
| return None |
| |
| return SceneBounds( |
| min_corner=Vector((min(xs), min(ys), 0)), |
| max_corner=Vector((max(xs), max(ys), 3.0)) |
| ) |
|
|
|
|
| |
| |
| |
|
|
| def clear_scene(): |
| """Start from a clean Blender state.""" |
| bpy.ops.wm.read_factory_settings(use_empty=True) |
|
|
|
|
| def setup_world(background: Sequence[float] = (1.0, 1.0, 1.0, 1.0), |
| ambient_intensity: float = 1.0, |
| use_hdri: bool = False) -> None: |
| """Configure world/background settings (aligned with reference).""" |
| scene = bpy.context.scene |
| if scene.world is None: |
| scene.world = bpy.data.worlds.new("World") |
| world = scene.world |
| world.use_nodes = True |
| nodes = world.node_tree.nodes |
| links = world.node_tree.links |
| |
| |
| nodes.clear() |
| |
| |
| output_node = nodes.new(type="ShaderNodeOutputWorld") |
| output_node.location = (400, 0) |
| |
| if use_hdri: |
| |
| tex_coord = nodes.new(type="ShaderNodeTexCoord") |
| tex_coord.location = (-600, 0) |
| |
| mapping = nodes.new(type="ShaderNodeMapping") |
| mapping.location = (-400, 0) |
| |
| gradient = nodes.new(type="ShaderNodeTexGradient") |
| gradient.gradient_type = 'SPHERICAL' |
| gradient.location = (-200, 0) |
| |
| color_ramp = nodes.new(type="ShaderNodeValToRGB") |
| color_ramp.location = (0, 0) |
| color_ramp.color_ramp.elements[0].position = 0.0 |
| color_ramp.color_ramp.elements[0].color = (0.6, 0.65, 0.7, 1.0) |
| color_ramp.color_ramp.elements[1].position = 1.0 |
| color_ramp.color_ramp.elements[1].color = (1.0, 0.98, 0.95, 1.0) |
| |
| background_node = nodes.new(type="ShaderNodeBackground") |
| background_node.location = (200, 0) |
| background_node.inputs[1].default_value = max(0.0, ambient_intensity) |
| |
| links.new(tex_coord.outputs["Generated"], mapping.inputs["Vector"]) |
| links.new(mapping.outputs["Vector"], gradient.inputs["Vector"]) |
| links.new(gradient.outputs["Color"], color_ramp.inputs["Fac"]) |
| links.new(color_ramp.outputs["Color"], background_node.inputs["Color"]) |
| links.new(background_node.outputs["Background"], output_node.inputs["Surface"]) |
| else: |
| |
| background_node = nodes.new(type="ShaderNodeBackground") |
| background_node.location = (200, 0) |
| background_node.inputs[0].default_value = ( |
| background[0], background[1], background[2], |
| background[3] if len(background) > 3 else 1.0, |
| ) |
| background_node.inputs[1].default_value = max(0.0, ambient_intensity) |
| links.new(background_node.outputs["Background"], output_node.inputs["Surface"]) |
| |
| |
| scene.render.film_transparent = True |
| scene.render.image_settings.color_mode = "RGBA" |
|
|
|
|
| |
| |
| |
|
|
| def create_material(name: str, color: Tuple[float, ...], |
| alpha: float = 1.0, metallic: float = 0.0, |
| roughness: float = 0.5) -> bpy.types.Material: |
| """Create PBR material.""" |
| mat = bpy.data.materials.new(name=name) |
| mat.use_nodes = True |
| |
| nodes = mat.node_tree.nodes |
| links = mat.node_tree.links |
| nodes.clear() |
| |
| bsdf = nodes.new(type="ShaderNodeBsdfPrincipled") |
| output = nodes.new(type="ShaderNodeOutputMaterial") |
| links.new(bsdf.outputs["BSDF"], output.inputs["Surface"]) |
| |
| bsdf.inputs['Base Color'].default_value = (*color[:3], 1.0) |
| bsdf.inputs['Metallic'].default_value = metallic |
| bsdf.inputs['Roughness'].default_value = roughness |
| |
| if alpha < 1.0: |
| mat.blend_method = 'BLEND' |
| bsdf.inputs['Alpha'].default_value = alpha |
| |
| return mat |
|
|
|
|
| def create_floor_material() -> bpy.types.Material: |
| """Create pure white floor material (as requested).""" |
| mat = bpy.data.materials.new(name="FloorMaterial_White") |
| mat.use_nodes = True |
| |
| nodes = mat.node_tree.nodes |
| links = mat.node_tree.links |
| nodes.clear() |
| |
| bsdf = nodes.new(type="ShaderNodeBsdfPrincipled") |
| output = nodes.new(type="ShaderNodeOutputMaterial") |
| links.new(bsdf.outputs["BSDF"], output.inputs["Surface"]) |
| |
| |
| bsdf.inputs["Base Color"].default_value = (1.0, 1.0, 1.0, 1.0) |
| bsdf.inputs["Roughness"].default_value = 0.35 |
| bsdf.inputs["Metallic"].default_value = 0.0 |
| |
| mat.use_backface_culling = False |
| |
| return mat |
|
|
|
|
| |
| |
| |
|
|
| def create_floor(boundary_polygon: List) -> Optional[bpy.types.Object]: |
| """Create floor from boundary polygon.""" |
| if not boundary_polygon or len(boundary_polygon) < 3: |
| return None |
| |
| mesh = bpy.data.meshes.new("floor") |
| obj = bpy.data.objects.new("Floor", mesh) |
| |
| bm = bmesh.new() |
| blender_verts = [] |
| |
| for v in boundary_polygon: |
| if isinstance(v, dict): |
| x = v.get('x', v.get(0, 0)) |
| y = v.get('z', v.get('y', v.get(1, 0))) |
| blender_verts.append(bm.verts.new((x, y, 0))) |
| elif isinstance(v, (list, tuple)) and len(v) >= 2: |
| blender_verts.append(bm.verts.new((v[0], v[1], 0))) |
| |
| bm.verts.ensure_lookup_table() |
| |
| if len(blender_verts) >= 3: |
| try: |
| bm.faces.new(blender_verts) |
| except: |
| pass |
| |
| bm.to_mesh(mesh) |
| bm.free() |
| |
| |
| floor_mat = create_floor_material() |
| obj.data.materials.append(floor_mat) |
| |
| bpy.context.collection.objects.link(obj) |
| |
| |
| bpy.context.view_layer.objects.active = obj |
| obj.select_set(True) |
| bpy.ops.object.mode_set(mode='EDIT') |
| bpy.ops.mesh.select_all(action='SELECT') |
| bpy.ops.uv.smart_project() |
| bpy.ops.object.mode_set(mode='OBJECT') |
| |
| return obj |
|
|
|
|
| |
| |
| |
|
|
| def get_obj_dimensions(obj: bpy.types.Object) -> List[float]: |
| """Get object real dimensions.""" |
| if obj.type != 'MESH': |
| return [1, 1, 1] |
| |
| bbox_corners = [obj.matrix_world @ Vector(corner) for corner in obj.bound_box] |
| xs = [c.x for c in bbox_corners] |
| ys = [c.y for c in bbox_corners] |
| zs = [c.z for c in bbox_corners] |
| |
| return [max(xs) - min(xs), max(ys) - min(ys), max(zs) - min(zs)] |
|
|
|
|
| def load_3d_asset(file_path: str, combine_components: bool = True) -> Optional[bpy.types.Object]: |
| """Load GLB/OBJ file.""" |
| if not os.path.exists(file_path): |
| return None |
| |
| existing_objects = set(bpy.data.objects) |
| |
| ext = os.path.splitext(file_path)[1].lower() |
| try: |
| if ext == '.glb' or ext == '.gltf': |
| bpy.ops.import_scene.gltf(filepath=file_path) |
| elif ext == '.obj': |
| bpy.ops.wm.obj_import(filepath=file_path) |
| else: |
| return None |
| except Exception as e: |
| print(f" ⚠️ Failed to load: {file_path}: {e}") |
| return None |
| |
| new_objects = [obj for obj in bpy.data.objects if obj not in existing_objects] |
| |
| if not new_objects: |
| return None |
| |
| if combine_components and len(new_objects) > 1: |
| bpy.ops.object.select_all(action='DESELECT') |
| for obj in new_objects: |
| obj.select_set(True) |
| bpy.context.view_layer.objects.active = new_objects[0] |
| try: |
| bpy.ops.object.join() |
| except: |
| pass |
| |
| loaded_obj = bpy.context.view_layer.objects.active |
| return loaded_obj |
|
|
|
|
| def place_asset(obj_data: Dict, asset_dir: str) -> Optional[bpy.types.Object]: |
| """Load and place 3D asset.""" |
| obj_id = obj_data.get('id', 'unknown') |
| category = obj_data.get('object_name', obj_data.get('category', 'object')) |
| model_id = obj_data.get('model_id') |
| |
| |
| position = obj_data.get('position', {'x': 0, 'y': 0, 'z': 0}) |
| if isinstance(position, dict): |
| pos = [position.get('x', 0), position.get('y', 0), position.get('z', 0)] |
| elif isinstance(position, (list, tuple)): |
| pos = list(position[:3]) if len(position) >= 3 else [0, 0, 0] |
| else: |
| pos = [0, 0, 0] |
| |
| |
| rotation = obj_data.get('rotation', {'x': 0, 'y': 0, 'z': 0}) |
| if isinstance(rotation, dict): |
| rot_deg = [rotation.get('x', 0), rotation.get('y', 0), rotation.get('z', 0)] |
| elif isinstance(rotation, (list, tuple)): |
| rot_deg = list(rotation[:3]) if len(rotation) >= 3 else [0, 0, 0] |
| else: |
| rot_deg = [0, 0, 0] |
| |
| |
| size = obj_data.get('size', [0.5, 0.5, 0.5]) |
| if isinstance(size, (list, tuple)) and len(size) >= 3: |
| target_size = list(size) |
| else: |
| target_size = [0.5, 0.5, 0.5] |
| |
| |
| loaded_obj = None |
| if model_id and asset_dir: |
| asset_paths = [ |
| os.path.join(asset_dir, model_id, f"{model_id}.glb"), |
| os.path.join(asset_dir, model_id, f"{model_id}.obj"), |
| os.path.join(asset_dir, model_id, "model.glb"), |
| ] |
| |
| for path in asset_paths: |
| if os.path.exists(path): |
| loaded_obj = load_3d_asset(path) |
| if loaded_obj: |
| break |
| |
| if loaded_obj is None: |
| |
| bpy.ops.mesh.primitive_cube_add(size=1) |
| loaded_obj = bpy.context.active_object |
| loaded_obj.scale = target_size |
| mat = create_material(f"mat_{obj_id}", (0.5, 0.5, 0.5), alpha=0.8) |
| loaded_obj.data.materials.append(mat) |
| else: |
| |
| bpy.ops.object.select_all(action='DESELECT') |
| loaded_obj.select_set(True) |
| bpy.context.view_layer.objects.active = loaded_obj |
| bpy.ops.object.origin_set(type='GEOMETRY_ORIGIN', center='BOUNDS') |
| |
| |
| bpy.ops.transform.rotate(value=-math.radians(90), orient_axis='Z') |
| |
| |
| current_dims = get_obj_dimensions(loaded_obj) |
| if current_dims[0] > 0 and current_dims[1] > 0 and current_dims[2] > 0: |
| scale_factor = min( |
| target_size[0] / current_dims[0], |
| target_size[1] / current_dims[1], |
| target_size[2] / current_dims[2] |
| ) |
| loaded_obj.scale = (scale_factor, scale_factor, scale_factor) |
| |
| bpy.ops.object.transform_apply(location=False, rotation=True, scale=True) |
| |
| |
| loaded_obj.name = f"Object_{obj_id}_{category}" |
| |
| |
| loaded_obj.rotation_mode = 'XYZ' |
| loaded_obj.rotation_euler = ( |
| math.radians(rot_deg[0]), |
| math.radians(rot_deg[1]), |
| math.radians(rot_deg[2]) |
| ) |
| |
| bpy.ops.object.transform_apply(location=False, rotation=True, scale=False) |
| |
| |
| obj_height = get_obj_dimensions(loaded_obj)[2] |
| pos[2] = pos[2] if pos[2] > 0 else obj_height / 2 |
| |
| |
| loaded_obj.location = pos |
| |
| return loaded_obj |
|
|
|
|
| |
| |
| |
|
|
| def _look_at(camera: bpy.types.Object, target: Vector) -> None: |
| """Make camera look at target.""" |
| direction = target - camera.location |
| if direction.length < 1e-6: |
| direction = Vector((0.0, 0.0, -1.0)) |
| else: |
| direction.normalize() |
| quat = direction.to_track_quat("-Z", "Y") |
| camera.rotation_euler = quat.to_euler() |
|
|
|
|
| def setup_camera(bounds: SceneBounds, |
| view: str = 'diagonal', |
| camera_factor: float = 0.8, |
| topdown_height: float = 1.5, |
| topdown_scale: float = 1.0, |
| diagonal_distance: float = 1.0, |
| diagonal_height_offset: float = 0.15, |
| side_elevation_angle: float = 30.0, |
| side_distance: float = 1.5) -> bpy.types.Object: |
| """Configure camera (aligned with reference code). |
| |
| View modes: |
| - diagonal: Classic isometric-like view from (1,1,1) direction (front-right) |
| - diagonal2: Opposite corner view from (-1,-1,1) direction (back-left) |
| - diagonal3: Corner view from (1,-1,1) direction (back-right) |
| - diagonal4: Corner view from (-1,1,1) direction (front-left) |
| - topdown/top: Bird's eye orthographic view from above |
| - side_front: Front view with slight elevation |
| - side_back: Back view with slight elevation |
| - side_left: Left view with slight elevation |
| - side_right: Right view with slight elevation |
| """ |
| camera_data = bpy.data.cameras.new(name='Camera') |
| camera_obj = bpy.data.objects.new('Camera', camera_data) |
| bpy.context.collection.objects.link(camera_obj) |
| bpy.context.scene.camera = camera_obj |
| |
| center = bounds.center |
| radius = max(bounds.radius, 1e-3) |
| |
| |
| if view == 'top': |
| view = 'topdown' |
| |
| if view == 'topdown': |
| |
| camera_data.type = "ORTHO" |
| camera_data.ortho_scale = radius * topdown_scale |
| eye = center + Vector((0.0, 0.0, radius * topdown_height)) |
| camera_obj.location = eye |
| camera_data.lens = 50.0 |
| _look_at(camera_obj, center) |
| |
| elif view.startswith("side_"): |
| |
| camera_data.type = "PERSP" |
| camera_data.lens = 35.0 |
| |
| elev_rad = math.radians(side_elevation_angle) |
| horizontal_dist = math.cos(elev_rad) |
| vertical_dist = math.sin(elev_rad) |
| |
| if view == "side_front": |
| horiz_dir = Vector((0.0, 1.0, 0.0)) |
| elif view == "side_back": |
| horiz_dir = Vector((0.0, -1.0, 0.0)) |
| elif view == "side_left": |
| horiz_dir = Vector((-1.0, 0.0, 0.0)) |
| elif view == "side_right": |
| horiz_dir = Vector((1.0, 0.0, 0.0)) |
| else: |
| horiz_dir = Vector((0.0, 1.0, 0.0)) |
| |
| distance = radius * max(1.0, side_distance * camera_factor * 1.5) |
| direction = Vector(( |
| horiz_dir.x * horizontal_dist, |
| horiz_dir.y * horizontal_dist, |
| vertical_dist |
| )) |
| direction.normalize() |
| |
| eye = center + direction * distance |
| camera_obj.location = eye |
| _look_at(camera_obj, center) |
| |
| elif view in ("diagonal", "diagonal2", "diagonal3", "diagonal4"): |
| |
| camera_data.type = "PERSP" |
| camera_data.lens = 35.0 |
| |
| if view == "diagonal": |
| diag_direction = Vector((1.0, 1.0, 1.0)) |
| elif view == "diagonal2": |
| diag_direction = Vector((-1.0, -1.0, 1.0)) |
| elif view == "diagonal3": |
| diag_direction = Vector((1.0, -1.0, 1.0)) |
| else: |
| diag_direction = Vector((-1.0, 1.0, 1.0)) |
| diag_direction.normalize() |
| |
| distance = radius * max(1.0, diagonal_distance * camera_factor * 1.5) |
| eye = center + diag_direction * distance |
| |
| look_target = center.copy() |
| |
| |
| z_offset = radius * diagonal_height_offset |
| eye.z -= z_offset |
| look_target.z -= z_offset |
| |
| camera_obj.location = eye |
| _look_at(camera_obj, look_target) |
| else: |
| |
| camera_data.type = "PERSP" |
| camera_data.lens = 35.0 |
| diag_direction = Vector((1.0, 1.0, 1.0)).normalized() |
| distance = radius * max(1.0, diagonal_distance * camera_factor * 1.5) |
| eye = center + diag_direction * distance |
| camera_obj.location = eye |
| _look_at(camera_obj, center) |
| |
| camera_data.clip_start = 0.01 |
| camera_data.clip_end = radius * 100.0 |
| |
| return camera_obj |
|
|
|
|
| |
| |
| |
|
|
| def setup_sun(camera: bpy.types.Object, bounds: SceneBounds, |
| sun_intensity: float = 3.5, |
| sun_color: Sequence[float] = (1.0, 0.98, 0.94)) -> bpy.types.Object: |
| """Configure sun light (aligned with reference).""" |
| light_data = bpy.data.lights.new(name='Sun', type='SUN') |
| sun = bpy.data.objects.new('Sun', light_data) |
| bpy.context.collection.objects.link(sun) |
| |
| center = bounds.center |
| radius = max(bounds.radius, 1e-3) |
| |
| view_dir = center - camera.location |
| if view_dir.length < 1e-6: |
| view_dir = Vector((0.0, 0.0, -1.0)) |
| else: |
| view_dir.normalize() |
| |
| sun_dir = view_dir * 0.6 + Vector((0.0, 0.0, -0.8)) |
| if sun_dir.length < 1e-6: |
| sun_dir = Vector((0.0, 0.0, -1.0)) |
| else: |
| sun_dir.normalize() |
| |
| sun.location = center + sun_dir * radius * 2.0 |
| quat = sun_dir.to_track_quat("-Z", "Y") |
| sun.rotation_euler = quat.to_euler() |
| |
| light_data.energy = max(0.01, sun_intensity) |
| if len(sun_color) >= 3: |
| light_data.color = (sun_color[0], sun_color[1], sun_color[2]) |
| |
| |
| if hasattr(light_data, "angle"): |
| light_data.angle = math.radians(1.0) |
| |
| return sun |
|
|
|
|
| def add_fill_lights(bounds: SceneBounds, intensity: float = 0.5) -> None: |
| """Add fill lights to reduce harsh shadows (aligned with reference).""" |
| center = bounds.center |
| radius = max(bounds.radius, 1e-3) |
| |
| |
| fill_data = bpy.data.lights.new("FillLight", type="AREA") |
| fill_obj = bpy.data.objects.new("FillLight", fill_data) |
| bpy.context.collection.objects.link(fill_obj) |
| |
| fill_obj.location = center + Vector((0.0, -radius * 0.5, radius * 1.5)) |
| fill_obj.rotation_euler = (math.radians(45), 0, 0) |
| fill_data.energy = intensity * 100 |
| fill_data.color = (1.0, 0.98, 0.95) |
| fill_data.size = radius * 2 |
| |
| |
| rim_data = bpy.data.lights.new("RimLight", type="AREA") |
| rim_obj = bpy.data.objects.new("RimLight", rim_data) |
| bpy.context.collection.objects.link(rim_obj) |
| |
| rim_obj.location = center + Vector((radius * 0.5, radius, radius)) |
| rim_obj.rotation_euler = (math.radians(-45), math.radians(30), 0) |
| rim_data.energy = intensity * 50 |
| rim_data.color = (0.95, 0.97, 1.0) |
| rim_data.size = radius |
|
|
|
|
| |
| |
| |
|
|
| def setup_render_settings(engine: str = "CYCLES", |
| width: int = 1600, |
| height: int = 900, |
| samples: int = 256, |
| exposure: float = 0.0) -> None: |
| """Configure render settings (aligned with reference).""" |
| scene = bpy.context.scene |
| render = scene.render |
| |
| |
| available_engines = {item.identifier for item in render.bl_rna.properties["engine"].enum_items} |
| target_engine = engine |
| |
| if target_engine not in available_engines: |
| if target_engine == "BLENDER_EEVEE" and "BLENDER_EEVEE_NEXT" in available_engines: |
| target_engine = "BLENDER_EEVEE_NEXT" |
| elif "CYCLES" in available_engines: |
| target_engine = "CYCLES" |
| else: |
| target_engine = list(available_engines)[0] |
| |
| render.engine = target_engine |
| render.resolution_x = width |
| render.resolution_y = height |
| render.image_settings.file_format = "PNG" |
| render.image_settings.color_mode = "RGBA" |
| render.film_transparent = True |
| render.use_persistent_data = False |
| |
| scene.view_settings.exposure = exposure |
| |
| if target_engine == "CYCLES": |
| scene.cycles.samples = max(1, samples) |
| scene.cycles.preview_samples = min(scene.cycles.samples, 64) |
| scene.cycles.use_denoising = True |
| scene.cycles.use_adaptive_sampling = True |
| scene.cycles.max_bounces = 12 |
| scene.cycles.diffuse_bounces = 4 |
| scene.cycles.glossy_bounces = 4 |
| scene.cycles.transmission_bounces = 8 |
| scene.cycles.volume_bounces = 2 |
| |
| try: |
| bpy.context.preferences.addons['cycles'].preferences.compute_device_type = 'CUDA' |
| bpy.context.preferences.addons['cycles'].preferences.get_devices() |
| scene.cycles.device = 'GPU' |
| except: |
| pass |
| |
| elif target_engine in {"BLENDER_EEVEE", "BLENDER_EEVEE_NEXT"}: |
| eevee = scene.eevee |
| if hasattr(eevee, "taa_render_samples"): |
| eevee.taa_render_samples = max(1, samples) |
| elif hasattr(eevee, "samples"): |
| eevee.samples = max(1, samples) |
| |
| if hasattr(eevee, "use_gtao"): |
| eevee.use_gtao = True |
| if hasattr(eevee, "gtao_distance"): |
| eevee.gtao_distance = 0.5 |
| if hasattr(eevee, "gtao_quality"): |
| eevee.gtao_quality = 0.5 |
| |
| if hasattr(eevee, "use_bloom"): |
| eevee.use_bloom = True |
| if hasattr(eevee, "bloom_threshold"): |
| eevee.bloom_threshold = 0.8 |
| if hasattr(eevee, "bloom_intensity"): |
| eevee.bloom_intensity = 0.1 |
| |
| if hasattr(eevee, "use_ssr"): |
| eevee.use_ssr = True |
| if hasattr(eevee, "use_ssr_refraction"): |
| eevee.use_ssr_refraction = True |
| |
| if hasattr(eevee, "use_soft_shadows"): |
| eevee.use_soft_shadows = True |
| if hasattr(eevee, "shadow_cube_size"): |
| eevee.shadow_cube_size = '1024' |
| if hasattr(eevee, "shadow_cascade_size"): |
| eevee.shadow_cascade_size = '2048' |
| if hasattr(eevee, "use_denoise"): |
| eevee.use_denoise = True |
|
|
|
|
| |
| |
| |
|
|
| def auto_crop_image(image_path: str, padding: int = 10) -> None: |
| """Crop rendered image to remove transparent margins.""" |
| if not HAS_PIL: |
| return |
| |
| img = Image.open(image_path) |
| if img.mode != "RGBA": |
| img = img.convert("RGBA") |
| |
| alpha = img.split()[-1] |
| bbox = alpha.getbbox() |
| |
| if bbox is None: |
| return |
| |
| left = max(0, bbox[0] - padding) |
| top = max(0, bbox[1] - padding) |
| right = min(img.width, bbox[2] + padding) |
| bottom = min(img.height, bbox[3] + padding) |
| |
| cropped = img.crop((left, top, right, bottom)) |
| cropped.save(image_path) |
|
|
|
|
| |
| |
| |
|
|
| def extract_objects(scene: Dict) -> List[Dict]: |
| """Extract all objects from scene data.""" |
| objects = [] |
| |
| |
| zones = scene.get('functional_zones', []) |
| for zone in zones: |
| zone_assets = zone.get('assets', []) |
| for asset in zone_assets: |
| objects.append(asset) |
| |
| |
| assets = scene.get('assets', []) |
| if isinstance(assets, list): |
| for asset in assets: |
| objects.append(asset) |
| elif isinstance(assets, dict): |
| for key, asset in assets.items(): |
| if isinstance(asset, dict): |
| asset['id'] = asset.get('id', key) |
| objects.append(asset) |
| |
| return objects |
|
|
|
|
| def render_scene(scene: Dict, |
| output_path: str, |
| asset_dir: str = None, |
| view: str = 'diagonal', |
| |
| engine: str = "CYCLES", |
| width: int = 1600, |
| height: int = 900, |
| samples: int = 256, |
| |
| camera_factor: float = 0.8, |
| topdown_height: float = 1.5, |
| topdown_scale: float = 1.0, |
| diagonal_distance: float = 1.0, |
| diagonal_height_offset: float = 0.15, |
| |
| sun_intensity: float = 3.5, |
| ambient_intensity: float = 1.0, |
| sun_color: Sequence[float] = (1.0, 0.98, 0.94), |
| use_fill_lights: bool = True, |
| fill_intensity: float = 0.5, |
| use_hdri: bool = False, |
| |
| auto_crop: bool = True, |
| crop_padding: int = 10) -> str: |
| """Render scene with high quality settings (aligned with reference).""" |
| |
| clear_scene() |
| |
| |
| boundary = scene.get('boundary', scene.get('architecture', {}).get('boundary_polygon', [])) |
| if isinstance(boundary, dict): |
| boundary = boundary.get('floor_vertices', []) |
| |
| |
| if boundary: |
| create_floor(boundary) |
| |
| |
| bounds = compute_bounds_from_boundary(boundary) |
| if bounds is None: |
| bounds = SceneBounds(min_corner=Vector((0, 0, 0)), max_corner=Vector((10, 10, 3))) |
| |
| |
| objects_data = extract_objects(scene) |
| print(f" Scene has {len(objects_data)} objects") |
| |
| for obj_data in objects_data: |
| try: |
| place_asset(obj_data, asset_dir) |
| except Exception as e: |
| print(f" ⚠️ Failed to place object: {e}") |
| |
| |
| mesh_objects = [obj for obj in bpy.context.scene.objects if obj.type == "MESH"] |
| if mesh_objects: |
| bounds = compute_bounds_from_objects(mesh_objects) |
| |
| |
| setup_render_settings(engine, width, height, samples) |
| setup_world((1.0, 1.0, 1.0, 1.0), ambient_intensity, use_hdri) |
| |
| camera = setup_camera(bounds, view, camera_factor, |
| topdown_height, topdown_scale, |
| diagonal_distance, diagonal_height_offset) |
| |
| setup_sun(camera, bounds, sun_intensity, sun_color) |
| |
| if use_fill_lights: |
| add_fill_lights(bounds, fill_intensity) |
| |
| |
| output_abs = os.path.abspath(output_path) |
| output_dir = os.path.dirname(output_abs) |
| if output_dir: |
| os.makedirs(output_dir, exist_ok=True) |
| |
| bpy.context.scene.render.filepath = output_abs |
| bpy.ops.render.render(write_still=True) |
| |
| |
| if auto_crop: |
| auto_crop_image(output_abs, crop_padding) |
| |
| print(f" ✅ Rendered to: {output_path}") |
| return output_path |
|
|
|
|
| def load_scene(scene_path: str) -> Dict: |
| """Load scene JSON.""" |
| with open(scene_path, 'r') as f: |
| return json.load(f) |
|
|
|
|
| def main(): |
| """Main function.""" |
| parser = argparse.ArgumentParser(description='High-Quality Blender Scene Renderer') |
| parser.add_argument('--scene_path', type=str, required=True, help='Scene JSON file path') |
| parser.add_argument('--output', type=str, default=None, help='Output PNG path') |
| parser.add_argument('--asset_dir', type=str, default=None, help='3D assets directory') |
| parser.add_argument('--view', type=str, default='diagonal', |
| choices=['top', 'topdown', 'diagonal', 'diagonal2', 'diagonal3', 'diagonal4', |
| 'side_front', 'side_back', 'side_left', 'side_right'], |
| help='Camera view mode') |
| |
| parser.add_argument('--engine', type=str, default='CYCLES', |
| choices=['CYCLES', 'BLENDER_EEVEE', 'BLENDER_EEVEE_NEXT']) |
| parser.add_argument('--width', type=int, default=1600) |
| parser.add_argument('--height', type=int, default=900) |
| parser.add_argument('--samples', type=int, default=256) |
| |
| parser.add_argument('--camera-factor', type=float, default=0.8) |
| parser.add_argument('--topdown-height', type=float, default=4.0) |
| parser.add_argument('--topdown-scale', type=float, default=2.5) |
| parser.add_argument('--diagonal-distance', type=float, default=1.2) |
| parser.add_argument('--diagonal-height-offset', type=float, default=0.1) |
| |
| parser.add_argument('--sun-intensity', type=float, default=3.5) |
| parser.add_argument('--ambient-intensity', type=float, default=1.0) |
| parser.add_argument('--fill-lights', action='store_true', default=True) |
| parser.add_argument('--no-fill-lights', dest='fill_lights', action='store_false') |
| parser.add_argument('--fill-intensity', type=float, default=0.5) |
| |
| parser.add_argument('--auto-crop', action='store_true', default=True) |
| parser.add_argument('--no-auto-crop', dest='auto_crop', action='store_false') |
| parser.add_argument('--crop-padding', type=int, default=10) |
| |
| args = parser.parse_args() |
| |
| if args.asset_dir: |
| args.asset_dir = os.path.expanduser(args.asset_dir) |
| |
| print(f" Loading scene: {args.scene_path}") |
| print(f" Asset directory: {args.asset_dir}") |
| print(f" View: {args.view}") |
| print(f" Engine: {args.engine}") |
| |
| if os.path.exists(args.scene_path): |
| scene = load_scene(args.scene_path) |
| render_scene( |
| scene, |
| args.output, |
| args.asset_dir, |
| args.view, |
| engine=args.engine, |
| width=args.width, |
| height=args.height, |
| samples=args.samples, |
| camera_factor=args.camera_factor, |
| topdown_height=args.topdown_height, |
| topdown_scale=args.topdown_scale, |
| diagonal_distance=args.diagonal_distance, |
| diagonal_height_offset=args.diagonal_height_offset, |
| sun_intensity=args.sun_intensity, |
| ambient_intensity=args.ambient_intensity, |
| use_fill_lights=args.fill_lights, |
| fill_intensity=args.fill_intensity, |
| auto_crop=args.auto_crop, |
| crop_padding=args.crop_padding, |
| ) |
| else: |
| print(f" ❌ Scene file not found: {args.scene_path}") |
| sys.exit(1) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|