File size: 12,871 Bytes
5c769c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
import bpy
import os
import json
import math
import numpy as np
import random
from math import radians
import struct
import mathutils

# --- Config Parameters ---
CONFIG = {
    "RESULTS_PATH": os.environ.get("RESULTS_PATH"),
    "EXPOSURES": [0.125, 0.25, 1.0, 2.0, 8.0],
    # "EXPOSURES": [0.666, 0.333, 0.166, 0.1, 0.05],
    # "EXPOSURES": [0.333, 0.125, 0.066, 0.0333, 0.0166],
    # "EXPOSURES": [0.333, 0.166, 0.1, 0.05, 0.0222],
    # "EXPOSURES": [2.0, 1.0, 0.5, 0.25, 0.125],
    # "EXPOSURES": [0.03125, 0.125, 0.5, 2.0, 8],
    # "EXPOSURES": [0.0625, 0.25, 1, 4.0, 16],
    # "EXPOSURES": [0.125, 0.5, 2.0, 8.0, 32.0],
    # "EXPOSURES": [8, 32, 128, 512, 2048],

    # ================ Upload From Camera ================
    "ROWS": 5,
    "COLS": 7,
    "ROT_STEP": 2.5,
    # "ROT_STEP": 5.0,
    "RESOLUTION": 448,
    "SAMPLES": 2048,
    "TONEMAP_POOL": ['AgX', 'Filmic', 'Standard'],
}

chosen_tonemap = None

import math

def update_config_from_camera():
    cam = bpy.data.objects.get('Camera')
    if not cam:
        print("Error: No object named 'Camera' found in the scene")
        return
    loc = cam.location
    CONFIG["INIT_LOC"] = np.array([[loc.x], [loc.z], [-loc.y]])
    CONFIG["RADIUS"] = loc.length 
    CONFIG["MAX_DISTANCE"] = loc.length * 1.5
    rot = cam.rotation_euler
    pitch = math.degrees(rot.x) - 90
    yaw = math.degrees(rot.z)
    roll = math.degrees(rot.y)
    CONFIG["INIT_ROT"] = [pitch, yaw, roll]
    print(f"--- CONFIG updated automatically ---")
    print(f"INIT_LOC: {CONFIG['INIT_LOC'].flatten()}")
    print(f"INIT_ROT: {CONFIG['INIT_ROT']}")
    print(f"RADIUS: {CONFIG['RADIUS']:.4f}")
    print(f"MAX_DISTANCE: {CONFIG['MAX_DISTANCE']:.4f}")

def setup_environment():
    global chosen_tonemap
    scene = bpy.context.scene
    scene.render.engine = 'CYCLES'
    scene.cycles.samples = CONFIG["SAMPLES"]
    scene.render.resolution_x = CONFIG["RESOLUTION"]
    scene.render.resolution_y = CONFIG["RESOLUTION"]
    scene.render.resolution_percentage = 100
    scene.render.dither_intensity = 0.0
    scene.render.film_transparent = True
    scene.render.use_persistent_data = True
    
    # Default HDR output settings
    scene.render.image_settings.file_format = 'OPEN_EXR'
    scene.render.image_settings.color_depth = '32'

    # Randomly select Tonemapping
    chosen_tonemap = random.choice(CONFIG["TONEMAP_POOL"]) if chosen_tonemap is None else chosen_tonemap
    bpy.context.scene.view_settings.view_transform = chosen_tonemap

    # GPU acceleration
    try:
        cprefs = bpy.context.preferences.addons['cycles'].preferences
        cprefs.compute_device_type = 'OPTIX'
        cprefs.get_devices()
        for d in cprefs.devices: d.use = True
        scene.cycles.device = 'GPU'
    except:
        print("Using CPU Rendering...")

def setup_nodes(save_root):
    scene = bpy.context.scene
    scene.use_nodes = True
    tree = scene.node_tree
    tree.nodes.clear()

    rl = tree.nodes.new('CompositorNodeRLayers')
    scene.view_layers["ViewLayer"].use_pass_normal = True
    scene.view_layers["ViewLayer"].use_pass_z = True
    
    # --- 1. Depth and normal output (PNG) ---
    aux_out = tree.nodes.new('CompositorNodeOutputFile')
    aux_out.format.file_format = 'PNG'
    
    map_node = tree.nodes.new('CompositorNodeMapRange')
    map_node.inputs['From Max'].default_value = CONFIG["MAX_DISTANCE"]
    map_node.inputs['To Min'].default_value = 1
    map_node.inputs['To Max'].default_value = 0

    tree.links.new(rl.outputs['Depth'], map_node.inputs[0])
    
    aux_out.file_slots[0].path = "depth_"
    tree.links.new(map_node.outputs[0], aux_out.inputs[0])
    aux_out.file_slots.new("normal_")
    tree.links.new(rl.outputs['Normal'], aux_out.inputs[1])

    # --- 2. Exposure bracket LDR output ---
    ldr_out = tree.nodes.new('CompositorNodeOutputFile')
    ldr_out.format.file_format = 'PNG'
    ldr_out.base_path = ""
    ldr_out.file_slots.clear()

    for i, exp_val in enumerate(CONFIG["EXPOSURES"]):
        mix_node = tree.nodes.new('CompositorNodeMixRGB')
        mix_node.blend_type = 'MULTIPLY'
        mix_node.inputs[2].default_value = (exp_val, exp_val, exp_val, 1)
        mix_node.inputs[0].default_value = 1.0
        
        slot_name = f"ldr_exp_{str(i).replace('.', '_')}_"
        ldr_out.file_slots.new(slot_name)
        
        tree.links.new(rl.outputs['Image'], mix_node.inputs[1])
        tree.links.new(mix_node.outputs[0], ldr_out.inputs[i])
        
    return aux_out, ldr_out

def get_pose_matrix(pitch_deg, yaw_deg, radius):
    phi, theta = radians(pitch_deg), radians(yaw_deg)
    trans_t = np.array([[1,0,0,0],[0,1,0,0],[0,0,1,radius],[0,0,0,1]], dtype=float)
    rot_phi = np.array([[1,0,0,0],[0,np.cos(phi),-np.sin(phi),0],[0,np.sin(phi),np.cos(phi),0],[0,0,0,1]], dtype=float)
    rot_theta = np.array([[np.cos(theta),0,np.sin(theta),0],[0,1,0,0],[-np.sin(theta),0,np.cos(theta),0],[0,0,0,1]], dtype=float)
    return rot_theta @ (rot_phi @ trans_t)

def save_as_cameras_bin(data, file_path):
    if os.path.exists(file_path):
        print(f"Already have {file_path}. Skipping...")
        return
    w = int(data["w"])         # Width
    h = int(data["h"])         # Height
    fx = data["fl_x"]          # Horizontal focal length
    fy = data["fl_y"]          # Vertical focal length
    cx = data["cx"]            # Principal point X
    cy = data["cy"]            # Principal point Y
    with open(file_path, "wb") as f:
        # A. First write the camera count: 1 camera (format Q represents uint64)
        f.write(struct.pack("<Q", 1))
        # Set ID to 1 (I), set model to 1 for PINHOLE (i), Width (Q), Height (Q)
        f.write(struct.pack("<iiQQ", 1, 1, w, h))        
        # C. Write the 4 core camera intrinsic parameters: fx, fy, cx, cy (format dddd represents 4 doubles)
        f.write(struct.pack("<dddd", fx, fy, cx, cy))

def save_all_frames_to_bin(json_data, bin_path):
    flip_mat = mathutils.Matrix.Scale(-1, 4, (0,1,0)) @ mathutils.Matrix.Scale(-1, 4, (0,0,1))

    if os.path.exists(bin_path):
        f = open(bin_path, "r+b")
        total = struct.unpack("<Q", f.read(8))[0]
        f.seek(0, 2)  # Move to the end of the file
    else:
        f = open(bin_path, "wb")
        f.write(struct.pack("<Q", 0))
        total = 0

    for frame in json_data["frames"]:
        total += 1

        m = mathutils.Matrix(frame["transform_matrix"])
        w2c = (m @ flip_mat).inverted()
        q = w2c.to_quaternion()
        t = w2c.translation

        # Match the reader exactly: <I dddd ddd I  -> 64 bytes
        f.write(struct.pack(
            "<I dddd ddd I",
            total,
            q.w, q.x, q.y, q.z,
            t.x, t.y, t.z,
            1
        ))

        name = os.path.basename(frame["file_path"]) # train_hdr_000.exr
        name = name.replace("train_hdr_", "train_ldr_").replace("test_hdr_", "test_ldr_").replace(".exr", "_3.png")
        name = name.encode("utf-8") + b"\x00"
        # name = os.path.basename(frame["file_path"]).encode("utf-8") + b"\x00"
        f.write(name)
        f.write(struct.pack("<Q", 0))  # num_points = 0
    f.seek(0)
    f.write(struct.pack("<Q", total))
    f.close()
    return


    
def render_task(is_train=True):
    global chosen_tonemap
    sub_folder = "train" if is_train else "test"
    flag = 1 if is_train else 0
    # Resolve outputs from the dataset root, independently of the .blend location.
    root_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), CONFIG["RESULTS_PATH"])
    
    setup_environment()

    cam = bpy.data.objects['Camera']
    bpy.context.scene.camera = cam
    bpy.context.scene.frame_set(1)
    if cam.animation_data:
        cam.animation_data_clear()

    aux_node, ldr_node = setup_nodes(root_path)

    # Set up the camera rig
    if 'Empty' in bpy.data.objects:
        bpy.data.objects.remove(bpy.data.objects['Empty'], do_unlink=True)
    b_empty = bpy.data.objects.new("Empty", None)
    bpy.context.scene.collection.objects.link(b_empty)
    cam.parent = b_empty
    cam.location = (0, 0, 0)
    cam.rotation_euler = (0, 0, 0)


    base_matrix = get_pose_matrix(CONFIG["INIT_ROT"][0], CONFIG["INIT_ROT"][1], CONFIG["RADIUS"])
    # json_data = {'camera_angle_x': cam.data.angle_x, 'frames': []}

    res_x, res_y = bpy.context.scene.render.resolution_x, bpy.context.scene.render.resolution_y
    fl_x = (res_x / 2) / math.tan(cam.data.angle_x / 2)
    fl_y = (res_y / 2) / math.tan(cam.data.angle_y / 2)
    json_data = {
        "camera_angle_x": cam.data.angle_x,
        "camera_angle_y": cam.data.angle_y,
        "fl_x": fl_x, 
        "fl_y": fl_y,
        "cx": res_x / 2, 
        "cy": res_y / 2,
        "w": res_x, 
        "h": res_y,
        'tonemapping': chosen_tonemap, # New field
        'look': bpy.context.scene.view_settings.look,
        'exposure_bracket': CONFIG["EXPOSURES"],
        "frames": []
    }
    exposure_data = {}

    sparse_path = os.path.join(root_path, 'sparse', '0')
    os.makedirs(sparse_path, exist_ok=True)
    save_as_cameras_bin(json_data, os.path.join(sparse_path, 'cameras.bin'))
    
    count = 0
    row_cen, col_cen = (CONFIG["ROWS"]-1)/2, (CONFIG["COLS"]-1)/2

    for r in range(CONFIG["ROWS"]):
        for c in range(CONFIG["COLS"]):
            if (r + c) % 2 == flag: continue

            # Calculate the camera pose
            curr_pitch = (r - row_cen) * CONFIG["ROT_STEP"] + CONFIG["INIT_ROT"][0]
            curr_yaw = (c - col_cen) * CONFIG["ROT_STEP"] + CONFIG["INIT_ROT"][1]
            trans_m = get_pose_matrix(curr_pitch, curr_yaw, CONFIG["RADIUS"])
            loc_offset = trans_m[:3, 3:] - base_matrix[:3, 3:] + CONFIG["INIT_LOC"]
            b_empty.location = (loc_offset[0][0], -loc_offset[2][0], loc_offset[1][0])
            b_empty.rotation_euler = (radians(curr_pitch + 90), 0, radians(curr_yaw))
            # bpy.context.view_layer.update()

            # DEBUG
            # b_empty.location = (2.5, 1.437, 0.4669)
            # b_empty.rotation_euler = (radians(80.914), 0, radians(-246.58))
            # print(b_empty.location)
            # print(b_empty.rotation_euler)
            # print((curr_pitch + 90, 0, curr_yaw))
            # print(cam.location)
            # print(cam.rotation_euler)
            # print("Camera world position:", cam.matrix_world.to_translation())
            # print(cam.data.lens)
            # print(cam.data.sensor_width)
            # while True:
            #     pass
            

            # Set output paths
            hdr_dir = os.path.join(root_path, 'images_hdr')
            img_dir = os.path.join(root_path, 'images')
            depth_dir = os.path.join(root_path, 'depth')
            normal_dir = os.path.join(root_path, 'normal')
            for d in [hdr_dir, img_dir, depth_dir, normal_dir]:
                if not os.path.exists(d): os.makedirs(d)

            bpy.context.scene.render.filepath = os.path.join(hdr_dir, f"{sub_folder}_hdr_{count:03d}.exr")
            ldr_node.base_path = img_dir
            for i, exp_val in enumerate(CONFIG["EXPOSURES"]):
                slot_filename = f"{sub_folder}_ldr_{count:03d}_{i}_"
                ldr_node.file_slots[i].path = slot_filename
                slot_filename = f"{sub_folder}_ldr_{count:03d}_{i}.png"
                exposure_data[slot_filename] = exp_val
            aux_node.base_path = root_path
            aux_node.file_slots[0].path = f"depth/{sub_folder}_depth_{count:03d}_" # Automatically save to the depth subfolder
            aux_node.file_slots[1].path = f"normal/{sub_folder}_normal_{count:03d}_"

            # Render
            bpy.ops.render.render(write_still=True)

            # Clean up all PNG suffixes in one pass
            for folder in [img_dir, depth_dir, normal_dir]:
                for f in os.listdir(folder):
                    if f.endswith("0001.png"):
                        os.rename(os.path.join(folder, f), os.path.join(folder, f.replace("_0001.png", ".png")))

            # Save random information to JSON
            json_data['frames'].append({
                'file_path': os.path.join(f"{CONFIG['RESULTS_PATH']}", 'images_hdr', f"{sub_folder}_hdr_{count:03d}.exr"),
                'transform_matrix': [list(row) for row in cam.matrix_world],
            })
            count += 1

    with open(os.path.join(root_path, f"transforms_{sub_folder}.json"), 'w') as f:
        json.dump(json_data, f, indent=4)
    save_all_frames_to_bin(json_data, os.path.join(sparse_path, 'images.bin'))

    path = os.path.join(root_path, "exposure.json")
    json_data = json.load(open(path)) if os.path.exists(path) else {}
    json_data.update(exposure_data)
    with open(path, "w") as f:
        json.dump(json_data, f, indent=4)


if __name__ == "__main__":
    update_config_from_camera()
    render_task(True)
    render_task(False)