-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathrender_setup.py
319 lines (247 loc) · 11.4 KB
/
render_setup.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
import bpy
import math
import mathutils
def create_cameras_on_one_ring(
num_cameras=16, max_size=1, name_prefix="Camera", fov=22.5
):
"""
Create n cameras evenly distributed on a ring around the world origin (Z-axis).
:param max_size: The maximum size of the object to be captured by the cameras.
:param name_prefix: Prefix for naming the cameras.
:param fov: Field of view for the cameras in degrees.
:return: List of created camera objects.
"""
cameras = []
# Convert FOV from degrees to radians
fov_rad = math.radians(fov)
# Calculate the distance from the origin such that the FOV covers max_size
radius = (max_size * 0.5) / math.tan(fov_rad * 0.5)
angle_offset = math.pi / num_cameras # Offset for the ring cameras
# Set the vertical offset for the rings (small elevation above/below the object)
elevation = radius * 0.25 # Adjust this value to control the elevation
# Loop to create the ring (around Z-axis), offset by half an angle
for i in range(num_cameras):
theta = (2 * math.pi / num_cameras) * i + angle_offset
# Position for the upper ring (XZ-plane)
x = radius * math.cos(theta)
y = radius * math.sin(theta)
location = mathutils.Vector((x, y, elevation))
# Create upper ring camera
bpy.ops.object.camera_add(location=location)
camera = bpy.context.object
camera.name = f"{name_prefix}_{i+1}"
# Set the camera's FOV
camera.data.lens_unit = "FOV"
camera.data.angle = fov_rad
# Point the camera at the origin
direction_upper = camera.location - mathutils.Vector((0, 0, 0))
rot_quat_upper = direction_upper.to_track_quat("Z", "Y")
camera.rotation_euler = rot_quat_upper.to_euler()
cameras.append(camera)
return cameras
def create_cameras_on_two_rings(
num_cameras=16, max_size=1, name_prefix="Camera", fov=22.5
):
"""
Create 16 cameras evenly distributed on two rings around the world origin (Z-axis).
Each ring will have 8 cameras, with the upper and lower rings' cameras placed in the gaps of each other.
:param max_size: The maximum size of the object to be captured by the cameras.
:param name_prefix: Prefix for naming the cameras.
:param fov: Field of view for the cameras in degrees.
:return: List of created camera objects.
"""
cameras = []
# Convert FOV from degrees to radians
fov_rad = math.radians(fov)
# Calculate the distance from the origin such that the FOV covers max_size
radius = (max_size * 0.5) / math.tan(fov_rad * 0.5)
num_cameras_per_ring = num_cameras // 2
angle_offset = math.pi / num_cameras_per_ring # Offset for the upper ring cameras
# Set the vertical offset for the rings (small elevation above/below the object)
elevation_upper = radius * 0.5 # Adjust this value to control the elevation
elevation_lower = -radius * 0.5
# Loop to create the lower ring (around Z-axis)
for i in range(num_cameras_per_ring):
theta = (2 * math.pi / num_cameras_per_ring) * i
# Position for the lower ring (XZ-plane)
x = radius * math.cos(theta)
y = radius * math.sin(theta)
location_lower = mathutils.Vector((x, y, elevation_lower))
# Create lower ring camera
bpy.ops.object.camera_add(location=location_lower)
camera_lower = bpy.context.object
camera_lower.name = f"{name_prefix}_LowerRing_{i+1}"
# Set the camera's FOV
camera_lower.data.lens_unit = "FOV"
camera_lower.data.angle = fov_rad
# Point the camera at the origin
direction_lower = camera_lower.location - mathutils.Vector((0, 0, 0))
rot_quat_lower = direction_lower.to_track_quat("Z", "Y")
camera_lower.rotation_euler = rot_quat_lower.to_euler()
cameras.append(camera_lower)
# Loop to create the upper ring (around Z-axis), offset by half an angle
for i in range(num_cameras_per_ring):
theta = (2 * math.pi / num_cameras_per_ring) * i + angle_offset
# Position for the upper ring (XZ-plane)
x = radius * math.cos(theta)
y = radius * math.sin(theta)
location_upper = mathutils.Vector((x, y, elevation_upper))
# Create upper ring camera
bpy.ops.object.camera_add(location=location_upper)
camera_upper = bpy.context.object
camera_upper.name = f"{name_prefix}_UpperRing_{i+1}"
# Set the camera's FOV
camera_upper.data.lens_unit = "FOV"
camera_upper.data.angle = fov_rad
# Point the camera at the origin
direction_upper = camera_upper.location - mathutils.Vector((0, 0, 0))
rot_quat_upper = direction_upper.to_track_quat("Z", "Y")
camera_upper.rotation_euler = rot_quat_upper.to_euler()
cameras.append(camera_upper)
return cameras
def create_cameras_on_sphere(
num_cameras=16, max_size=1, name_prefix="Camera", fov=22.5
):
"""
Create cameras evenly distributed on a sphere around the world origin,
with each camera positioned such that it perfectly frames an object of size
max_size using a field of view of fov.
:param num_cameras: Number of cameras to create.
:param max_size: The maximum size of the object to be captured by the cameras.
:param name_prefix: Prefix for naming the cameras.
:param offset: Offset to change views slightly.
:param fov: Field of view for the cameras in degrees.
:return: List of created camera objects.
"""
cameras = []
phi = math.pi * (3.0 - math.sqrt(5.0)) # Golden angle in radians
# Convert FOV from degrees to radians
fov_rad = math.radians(fov)
# Calculate the distance from the origin such that the FOV covers max_size
radius = (max_size * 0.5) / math.tan(fov_rad * 0.5)
for i in range(num_cameras):
y = 1 - (i / float(num_cameras - 1)) * 2 # y goes from 1 to -1
radius_at_y = math.sqrt(1 - y * y) # Radius at y
theta = (phi) * i # Golden angle increment
x = math.cos(theta) * radius_at_y
z = math.sin(theta) * radius_at_y
location = mathutils.Vector((x, y, z)) * radius
# if offset:
# # Swap coordinates: x -> y, y -> z, z -> x
# location = mathutils.Vector((location.y, location.z, location.x))
# Create camera
bpy.ops.object.camera_add(location=location)
camera = bpy.context.object
camera.name = f"{name_prefix}_{i+1}"
# Set the camera's FOV
camera.data.lens_unit = "FOV"
camera.data.angle = fov_rad
# Point the camera at the origin
direction = camera.location - mathutils.Vector((0, 0, 0))
rot_quat = direction.to_track_quat("Z", "Y")
camera.rotation_euler = rot_quat.to_euler()
cameras.append(camera)
return cameras
def setup_render_settings(scene, resolution=(512, 512)):
"""
Configure render settings, including enabling specific passes and setting up the node tree.
:param scene: The scene to configure.
:param resolution: Tuple specifying the render resolution (width, height).
:return: A dictionary containing references to the output nodes for each pass.
"""
# Enable Cycles (Eevee does not offer UV output)
scene.render.engine = "CYCLES"
# Attempt to enable GPU support with preference order: OPTIX, CUDA, OPENCL, CPU
preferences = bpy.context.preferences.addons["cycles"].preferences
try:
preferences.compute_device_type = "OPTIX"
print("Using OPTIX for rendering.")
except Exception as e_optix:
print(f"OPTIX failed: {e_optix}")
try:
preferences.compute_device_type = "CUDA"
print("Using CUDA for rendering.")
except:
raise SystemError("You need an NVidia GPU for this Addon!")
# Set rendering samples and noise threshold
scene.cycles.samples = 1 # Reduce to 1 sample for no anti-aliasing in Cycles
scene.cycles.use_denoising = False
scene.cycles.use_light_tree = False
scene.cycles.max_bounces = 1
scene.cycles.diffuse_bounces = 1
scene.cycles.glossy_bounces = 0
scene.cycles.transmission_bounces = 0
scene.cycles.volume_bounces = 0
scene.cycles.transparent_max_bounces = 0
# Set filter size to minimum (0.01 to disable most filtering)
scene.render.filter_size = 0.01
# Enable transparent background
scene.render.film_transparent = True
# Set the render resolution
scene.render.resolution_x, scene.render.resolution_y = resolution
# put render resolution scale to 100%
scene.render.resolution_percentage = 100
# Prevent interpolation for the UV, depth, and normal outputs
scene.render.image_settings.file_format = "OPEN_EXR"
scene.render.image_settings.color_depth = "32" # Ensure high precision
# Ensure the scene uses nodes
scene.use_nodes = True
# Clear existing nodes
if scene.node_tree:
scene.node_tree.nodes.clear()
# Create a new node tree
tree = scene.node_tree
links = tree.links
# Create render layers node
render_layers = tree.nodes.new("CompositorNodeRLayers")
# Enable necessary passes
scene.view_layers["ViewLayer"].use_pass_z = True
scene.view_layers["ViewLayer"].use_pass_normal = True
scene.view_layers["ViewLayer"].use_pass_uv = True
scene.view_layers["ViewLayer"].use_pass_position = True
# scene.world.light_settings.use_ambient_occlusion = True # turn AO on
# scene.world.light_settings.ao_factor = 1.0
scene.view_layers["ViewLayer"].use_pass_ambient_occlusion = True # Enable AO pass
# Create output nodes for each pass
output_nodes = {}
# Depth pass
depth_output = tree.nodes.new("CompositorNodeOutputFile")
depth_output.label = "Depth Output"
depth_output.name = "DepthOutput"
depth_output.base_path = "" # Set the base path in the calling function if needed
depth_output.file_slots[0].path = "depth_"
links.new(render_layers.outputs["Depth"], depth_output.inputs[0])
output_nodes["depth"] = depth_output
# Normal pass
normal_output = tree.nodes.new("CompositorNodeOutputFile")
normal_output.label = "Normal Output"
normal_output.name = "NormalOutput"
normal_output.base_path = ""
normal_output.file_slots[0].path = "normal_"
links.new(render_layers.outputs["Normal"], normal_output.inputs[0])
output_nodes["normal"] = normal_output
# UV pass
uv_output = tree.nodes.new("CompositorNodeOutputFile")
uv_output.label = "UV Output"
uv_output.name = "UVOutput"
uv_output.base_path = ""
uv_output.file_slots[0].path = "uv_"
links.new(render_layers.outputs["UV"], uv_output.inputs[0])
output_nodes["uv"] = uv_output
# Position pass
position_output = tree.nodes.new("CompositorNodeOutputFile")
position_output.label = "Position Output"
position_output.name = "PositionOutput"
position_output.base_path = ""
position_output.file_slots[0].path = "position_"
links.new(render_layers.outputs["Position"], position_output.inputs[0])
output_nodes["position"] = position_output
# Ambient Occlusion pass
img_output = tree.nodes.new("CompositorNodeOutputFile")
img_output.label = "Image Output"
img_output.name = "ImageOutput"
img_output.base_path = ""
img_output.file_slots[0].path = "img_"
links.new(render_layers.outputs["Image"], img_output.inputs[0])
output_nodes["img"] = img_output
return output_nodes