File size: 9,346 Bytes
acdc230 | 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 | import tomllib
import bpy
import os
import json
import mathutils
import itertools
import math
import tomllib
import sys
import argparse
cam_order_file = "splatworks_cam_order.txt"
depth_dir = "depths/"
normal_dir = "normals/"
masks_dir = "masks/"
params_dir = "cam_params/"
output_dir = bpy.path.abspath("//")
with open(output_dir + "scene_data.toml", "rb") as f:
data = tomllib.load(f)
scene_data = data["scene_data"]
# TOML has no tuple type, so ref_objs comes back as a list of lists.
# Convert back to a list of tuples to match the original structure.
scene_data["ref_objs"] = [tuple(obj) for obj in scene_data["ref_objs"]]
if len(scene_data["ref_objs"]) == 0:
skip_ref = True
else:
skip_ref = False
soils2weights = data["soils2weights"]
traj2offset = data["traj2offset"]
def parse_args():
# Blender swallows its own args and passes everything after a
# standalone "--" straight through, so only look at that slice.
if "--" in sys.argv:
argv = sys.argv[sys.argv.index("--") + 1:]
else:
argv = []
parser = argparse.ArgumentParser()
parser.add_argument(
"--world",
type=str,
default=None,
help="Name of a single world map to render (must match a name in "
"scene_data['world_maps']). If omitted, all world maps are "
"rendered, same as before.",
)
parser.add_argument(
"--gt",
action=argparse.BooleanOptionalAction,
default=None,
help="Whether to write ground truth depth/mask output. Pass "
"--gt to force it on, --no-gt to force it off and save "
"disk space. If omitted, falls back to scene_data['gt'] "
"from the TOML, same as before.",
)
return parser.parse_args(argv)
def main():
args = parse_args()
write_gt = scene_data["gt"] if args.gt is None else args.gt
render(scene_data, selected_world=args.world, write_gt=write_gt)
def render(scene_data, selected_world=None, write_gt=None):
if write_gt is None:
write_gt = scene_data["gt"]
world_maps = scene_data["world_maps"]
if selected_world is not None:
if selected_world not in world_maps:
raise ValueError(
f"'{selected_world}' not found in scene_data['world_maps']: "
f"{world_maps}"
)
world_maps = [selected_world]
for traj in scene_data["trajectories"]:
for world in world_maps:
bpy.context.scene.world = bpy.data.worlds[world]
render_world(
traj,
scene_data["soil_settings"],
world,
output_dir,
True,
write_gt,
)
if not skip_ref:
render_world(
traj,
scene_data["ref_settings"],
world,
output_dir,
False,
write_gt,
)
def render_world(traj, settings, world, output_dir, is_soiling: bool, write_gt: bool):
frame_start = scene_data["frame_start"]
frame_stop = scene_data["frame_end"]
traj_label, frame_stop = get_traj_label_frame_stop(traj, frame_stop)
nodes = bpy.data.node_groups["Compositing Node Tree"].nodes
for setting in settings:
if skip_ref:
coat_label = "soil=verylow"
else:
coat_label = setup_material(is_soiling, setting)
coat_dir = ",".join([coat_label, traj_label, "clean"])
img_path = os.path.join(output_dir, world, coat_dir)
coat_gt_dir = ",".join([coat_label, traj_label])
depth_path = os.path.join(output_dir, depth_dir, world, coat_gt_dir)
param_path = os.path.join(
output_dir, params_dir, world, coat_gt_dir)
mask_path = os.path.join(output_dir, masks_dir, world, coat_gt_dir)
os.makedirs(img_path, exist_ok=True)
os.makedirs(depth_path, exist_ok=True)
os.makedirs(param_path, exist_ok=True)
os.makedirs(mask_path, exist_ok=True)
nodes["Depth Output"].directory = depth_path
nodes["Image Output"].directory = img_path
nodes["Mask Output"].directory = mask_path
render_frames(traj, frame_start, frame_stop,
param_path, write_gt)
def setup_material(is_soiling, setting):
ref_obj_names = scene_data["ref_objs"]
if is_soiling:
set_objs_materials(ref_obj_names, scene_data["soiling_mat_name"])
set_soil_weight(
scene_data["soiling_mat_name"], soils2weights[setting])
coat_label = "soil=" + setting
else:
# if it's not soiling, it's reflectivity
set_objs_materials(ref_obj_names, scene_data['ref_mat_name'])
set_ref_weight(scene_data["ref_mat_name"], setting)
coat_label = "ref=" + str(setting)
return coat_label
def render_frames(
traj: str,
frame_start: int,
frame_stop: int,
param_frame_dir: str,
write_GT: bool,
):
if traj != "trendspek":
valid_cams = get_valid_cams(traj)
else:
valid_cams = ["Camera"]*frame_stop
print(f"Rendering up to frame: {frame_stop}")
nodes = bpy.data.node_groups["Compositing Node Tree"].nodes
for frame in range(frame_start, frame_stop):
bpy.context.scene.frame_set(frame) # set the current frame
frame_string = str("%08d" % frame)
print(f"Rendering Frame {frame}")
cam_name = valid_cams[frame]
select_camera(cam_name)
cam = bpy.data.objects[cam_name]
cam_data_name = os.path.join(
param_frame_dir, frame_string + ".json")
nodes["Enable Depth"].inputs[0].default_value = write_GT
nodes["Enable Mask"].inputs[0].default_value = write_GT
nodes["Image Output"].file_name = frame_string + ".jpg"
nodes["Mask Output"].file_name = frame_string + ".png"
nodes["Depth Output"].file_name = frame_string + ".exr"
bpy.ops.render.render()
export_cam_parameters(cam_data_name, cam)
def get_traj_label_frame_stop(traj, frame_stop):
if traj == "trendspek":
traj_label = "traj=" + traj
else:
valid_cams = get_valid_cams(traj)
n_valid_cams = len(valid_cams)
frame_stop = min(frame_stop, n_valid_cams)
traj_label = "traj=proxy_surface_" + str(traj2offset[traj])
return traj_label, frame_stop
def get_valid_cams(traj):
offset = traj2offset[traj]
scene = bpy.context.scene
scene.splatworks_props.camera_proxy_offset = offset
cam_order_file_path = os.path.join(
output_dir,
"cam_order",
f"traj=proxy_surface_{offset}",
cam_order_file
)
valid_cams = load_cam_names(cam_order_file_path)
return valid_cams
def select_camera(name):
try:
ob = bpy.context.scene.objects[name] # Get the object
bpy.ops.object.select_all(action="DESELECT") # Deselect all objects
bpy.context.view_layer.objects.active = ob # Make the cube the active object
ob.select_set(True)
bpy.context.scene.camera = ob
if "vehicle" in bpy.data.objects.keys():
drone = bpy.data.objects['vehicle']
drone.constraints['Copy Location'].target = bpy.data.objects[name]
drone.constraints['Copy Rotation'].target = bpy.data.objects[name]
print(drone.constraints['Copy Location'].target)
except KeyError:
print(f"No camera object called {name}")
raise ValueError(f"No camera object called {name}")
def load_cam_names(f_name):
with open(f_name) as f:
contents = f.read()
return contents.split('\n')[:-1]
def set_objs_materials(ref_objs: list[tuple], mat_name: str):
for ref_obj in ref_objs:
obj_name = ref_obj[0]
slot = ref_obj[1]
obj = bpy.data.objects[obj_name]
obj_mat_slot = obj.material_slots[slot]
obj_mat_slot.material = bpy.data.materials[mat_name]
def set_soil_weight(mat_name: str, weight: float):
mat = bpy.data.materials[mat_name]
mat.node_tree.nodes["Math"].inputs[1].default_value = weight
def set_ref_weight(mat_name: str, weight: float):
mat = bpy.data.materials[mat_name]
mat.node_tree.nodes["Mix Shader.001"].inputs[0].default_value = 1 - weight
def export_cam_parameters(f_name, cam_obj):
"""
Export the camera parameters for a given camera object to a file
"""
rot_mode = cam_obj.rotation_mode
rot_mode_tuple = tuple(rot_mode)
if rot_mode_tuple in list(itertools.permutations("XYZ", 3)):
eul = mathutils.Euler(cam_obj.rotation_euler, rot_mode)
rot_out = eul.to_quaternion()
elif rot_mode == "AXIS_ANGLE":
raise NotImplementedError()
else: # quaternion case
rot_out = mathutils.Quaternion(cam_obj.rotation_quaternion)
out_dict = {
"name": cam_obj.name,
"loc": tuple(cam_obj.location),
"rot": [rot_out.w, rot_out.x, rot_out.y, rot_out.z],
"focal_length": cam_obj.data.lens,
"sensor_width": cam_obj.data.sensor_width,
"clip_end": cam_obj.data.clip_end,
"clip_start": cam_obj.data.clip_start,
}
with open(f_name, "w") as f:
json.dump(out_dict, f, indent="\t")
if __name__ == "__main__":
main()
|