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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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
# Standard Library Imports
import os
import sys
import copy
import time
import argparse
import datetime
from pathlib import Path
from collections import defaultdict, namedtuple
import struct

# Add local modules to path
sys.path.append("/home/sebastian.cavada/scsv/mast3r_complete")
sys.path.append("/home/sebastian.cavada/scsv/mast3r_complete/dust3r")
sys.path.append("/home/sebastian.cavada/scsv/mast3r_complete/_evaluation")

# Third-Party Imports
import numpy as np
import torch
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
# import matplotlib.pyplot as plt
# import plotly.graph_objects as go
from PIL import Image
from tqdm import tqdm

# Local Application/Library Imports
import mast3r.utils.path_to_dust3r  # noqa
from mast3r.model import AsymmetricMASt3R
from dust3r.datasets import get_data_loader  # noqa
from dust3r.model import AsymmetricCroCo3DStereo
from dust3r.utils.geometry import geotrf, inv, normalize_pointcloud
import dust3r.datasets
import croco.utils.misc as misc  # noqa

from dust3r.inference import inference
from dust3r.image_pairs import make_pairs
from dust3r.utils.image import load_images, rgb
from dust3r.utils.device import to_numpy
from dust3r.viz import add_scene_cam, CAM_COLORS, OPENGL, pts3d_to_trimesh, cat_meshes
from dust3r.cloud_opt import global_aligner, GlobalAlignerMode

# Import utility functions
from utils.general import get_batch_colmap, plot_3d_points_with_frustums, voxel_downsample_with_colors # noqa

# creating a new dataloader
from dust3r.datasets import CustomCOLMAP

# Define infinity constant
inf = float('inf')

# Set random seed for reproducibility
seed = 777 + misc.get_rank()
torch.manual_seed(seed)
np.random.seed(seed)
cudnn.benchmark = False

# Define Point3D namedtuple for COLMAP compatibility
Point3D = namedtuple(
    "Point3D", ["id", "xyz", "rgb", "error", "image_ids", "point2D_idxs"]
)

# Default configuration
DEFAULT_CONFIG = {
    'device': 'cuda',
    'batch_size': 4,
    'schedule': 'cosine',
    'lr': 0.01,
    'niter': 300,
    'min_conf_thr': 0
}

# Model configurations
MODEL_CONFIGS = {
    'dust3r': {
        'path': '/home/sebastian.cavada/scsv/thesis/mast3r_complete/checkpoints/dust3r_512dpt/DUSt3R_ViTLarge_BaseDecoder_512_dpt.pth',
        'architecture': "AsymmetricCroCo3DStereo(pos_embed='RoPE100', patch_embed_cls='ManyAR_PatchEmbed', img_size=(512, 512), head_type='dpt', output_mode='pts3d', depth_mode=('exp', -inf, inf), conf_mode=('exp', 1, inf), enc_embed_dim=1024, enc_depth=24, enc_num_heads=16, dec_embed_dim=768, dec_depth=12, dec_num_heads=12)"
    },
    'mast3r': {
        'path': '/home/sebastian.cavada/Documents/scsv/thesis/thesis_2025/mast3r_complete/checkpoints/dust3r_512dpt/MASt3R_ViTLarge_BaseDecoder_512_catmlpdpt_metric.pth',
        'architecture': "AsymmetricMASt3R(pos_embed='RoPE100', patch_embed_cls='ManyAR_PatchEmbed', img_size=(512, 512), head_type='catmlp+dpt', output_mode='pts3d+desc24', depth_mode=('exp', -inf, inf), conf_mode=('exp', 1, inf), enc_embed_dim=1024, enc_depth=24, enc_num_heads=16, dec_embed_dim=768, dec_depth=12, dec_num_heads=12, two_confs=True, desc_conf_mode=('exp', 0, inf), use_intrinsics=False, use_extrinsics=False)"
    }
}

def read_next_bytes(fid, num_bytes, format_char_sequence, endian_character="<"):
    """Read and unpack the next bytes from a binary file.
    :param fid:
    :param num_bytes: Sum of combination of {2, 4, 8}, e.g. 2, 6, 16, 30, etc.
    :param format_char_sequence: List of {c, e, f, d, h, H, i, I, l, L, q, Q}.
    :param endian_character: Any of {@, =, <, >, !}
    :return: Tuple of read and unpacked values.
    """
    data = fid.read(num_bytes)
    return struct.unpack(endian_character + format_char_sequence, data)

def read_points3D_binary(path_to_model_file):
    """
    Read Points3D from COLMAP binary file.
    
    Args:
        path_to_model_file: Path to COLMAP points3D.bin file
        
    Returns:
        points3D: Dictionary of Point3D objects
    """
    points3D = {}
    with open(path_to_model_file, "rb") as fid:
        num_points = read_next_bytes(fid, 8, "Q")[0]
        for _ in range(num_points):
            binary_point_line_properties = read_next_bytes(
                fid, num_bytes=43, format_char_sequence="QdddBBBd"
            )
            point3D_id = binary_point_line_properties[0]
            xyz = np.array(binary_point_line_properties[1:4])
            rgb = np.array(binary_point_line_properties[4:7])
            error = np.array(binary_point_line_properties[7])
            track_length = read_next_bytes(
                fid, num_bytes=8, format_char_sequence="Q"
            )[0]
            track_elems = read_next_bytes(
                fid,
                num_bytes=8 * track_length,
                format_char_sequence="ii" * track_length,
            )
            image_ids = np.array(tuple(map(int, track_elems[0::2])))
            point2D_idxs = np.array(tuple(map(int, track_elems[1::2])))
            points3D[point3D_id] = Point3D(
                id=point3D_id,
                xyz=xyz,
                rgb=rgb,
                error=error,
                image_ids=image_ids,
                point2D_idxs=point2D_idxs,
            )
    return points3D

def write_next_bytes(fid, data, format_char_sequence, endian_character="<"):
    """Pack and write to a binary file.
    :param fid:
    :param data: data to send, if multiple elements are sent at the same time,
    they should be encapsuled either in a list or a tuple
    :param format_char_sequence: List of {c, e, f, d, h, H, i, I, l, L, q, Q}.
    should be the same length as the data list or tuple
    :param endian_character: Any of {@, =, <, >, !}
    """
    if isinstance(data, (list, tuple)):
        bytes = struct.pack(endian_character + format_char_sequence, *data)
    else:
        bytes = struct.pack(endian_character + format_char_sequence, data)
    fid.write(bytes)

def write_points3D_binary(points3D, path_to_model_file):
    """
    Write Points3D to COLMAP binary file.
    
    Args:
        points3D: Dictionary of Point3D objects
        path_to_model_file: Path to write COLMAP points3D.bin file
    """
    with open(path_to_model_file, "wb") as fid:
        write_next_bytes(fid, len(points3D), "Q")
        for _, pt in points3D.items():
            write_next_bytes(fid, pt.id, "Q")
            write_next_bytes(fid, pt.xyz.tolist(), "ddd")
            write_next_bytes(fid, pt.rgb.tolist(), "BBB")
            write_next_bytes(fid, pt.error, "d")
            track_length = pt.image_ids.shape[0]
            write_next_bytes(fid, track_length, "Q")
            for image_id, point2D_id in zip(pt.image_ids, pt.point2D_idxs):
                write_next_bytes(fid, [image_id, point2D_id], "ii")

def load_model(model_name, device):
    """
    Load the specified model.

    Args:
        model_name: Name of the model to load ('dust3r', 'mast3r')
        device: Device to load the model on

    Returns:
        loaded_model: The loaded model
    """
    if model_name not in MODEL_CONFIGS:
        raise ValueError(f"Model {model_name} not supported. Choose from: {list(MODEL_CONFIGS.keys())}")

    config = MODEL_CONFIGS[model_name]
    model_path = config['path']
    model_architecture = config['architecture']

    # Create model instance based on architecture string
    model = eval(model_architecture)
    model.to(device)

    print(f'Loading pretrained model: {model_path}')
    checkpoint = torch.load(model_path, map_location=device)
    model.load_state_dict(checkpoint['model'], strict=False)
    model.eval()

    return model

def get_transformation_between_cameras(target_poses, source_poses):
    """
    Calculate transformation between source and target camera poses.
    
    Args:
        target_poses: Target camera poses (ground truth)
        source_poses: Source camera poses (predicted)
        
    Returns:
        scale: Scale factor
        rotation_matrix: Rotation matrix
        translation_shift: Translation vector
    """
    source_translation_1 = source_poses[0][:3, 3]
    source_translation_2 = source_poses[1][:3, 3]

    source_rotation_1 = source_poses[0][:3, :3]
    source_rotation_2 = source_poses[1][:3, :3]

    target_translation_1 = target_poses[0][:3, 3]
    target_translation_2 = target_poses[1][:3, 3]

    target_rotation_1 = target_poses[0][:3, :3]
    target_rotation_2 = target_poses[1][:3, :3]

    # 1. Calculate scale: ratio of distances between corresponding positions (target vs source)
    source_distance = np.linalg.norm(source_translation_2 - source_translation_1)
    target_distance = np.linalg.norm(target_translation_2 - target_translation_1)
    
    scale = target_distance / source_distance

    # 2. Compute rotation matrix to align source with target
    rotation_matrix = source_rotation_1 @ np.linalg.inv(target_rotation_1)

    # 3. Calculate translation shift
    # since the first camera is always in the origin:
    translation_shift = target_translation_1 - source_translation_1

    return scale, rotation_matrix, translation_shift

def process_scene(scene_config, dataset, model, device):
    """
    Process a scene with the given configuration.
    
    Args:
        scene_config: Configuration for the scene
        dataset: Dataset object
        model: Model to use for inference
        device: Device to run inference on
        
    Returns:
        points_cat: List of transformed point clouds
        colors_cat: List of point colors
        cameras_cat: List of camera poses
    """
    # Extract scene configuration
    selected_indices = scene_config.get('selected_indices', [])
    if not selected_indices and scene_config.get('auto_select', False):
        # Generate indices automatically based on configuration
        num_images = scene_config.get('num_images', 120)
        distance = scene_config.get('distance', 10)
        offset = scene_config.get('offset', 0)
        step = scene_config.get('step', 3)
        
        selected_indices = [(i + j) + offset for i in range(0, num_images, distance) 
                           for j in (0, step) if i + j < num_images]
    
    # Make sure we have an even number of indices for pair processing
    if len(selected_indices) % 2 != 0:
        selected_indices = selected_indices[:-1]
        
    print(f"Processing scene with indices: {selected_indices}")
    
    # Get batch of data for selected indices
    batch = get_batch_colmap(dataset, 
                            scene_config.get('max_batch_size', 50), 
                            scene_id=scene_config.get('scene_id', 0), 
                            selected_indices=selected_indices)
    
    print(f"Batch size: {len(batch)}")
    
    predictions = []
    camera_poses_gt_from_pred = []
    
    # Process each pair of images
    for i in tqdm(range(0, len(selected_indices), 2), desc="Processing pairs"):
        print(f"Processing pair {i//2+1}/{len(selected_indices)//2}")
        pair_batch = batch[i:i+2]
        
        # Load images and make pairs
        images = load_images([pair_batch[0]['path'][0], pair_batch[1]['path'][0]], size=512)
        pairs = make_pairs(images, scene_graph='complete', prefilter=None, symmetrize=True)    
        
        # Run inference
        output = inference(pairs, model, device, batch_size=scene_config.get('batch_size', 32))
        
        # Global alignment
        scene = global_aligner(output, device=device, mode=GlobalAlignerMode.PointCloudOptimizer)
        scene.compute_global_alignment(
            init="mst", 
            niter=scene_config.get('niter', 100), 
            schedule=scene_config.get('schedule', 'cosine'), 
            lr=scene_config.get('lr', 0.001)
        )
        
        # Post-processing
        scene.mask_sky()
        scene.clean_pointcloud()
        predictions.append(scene)
        
        # Get ground truth camera poses
        gt_poses_0 = pair_batch[0]['camera_pose']
        gt_poses_1 = pair_batch[1]['camera_pose']
        gt_poses = torch.cat([gt_poses_0, gt_poses_1], dim=0).cpu()
        camera_poses_gt_from_pred.append(gt_poses)
    
    # Combine results
    points_cat = []
    colors_cat = []
    cameras_cat = []
    
    for i, scene in enumerate(predictions):
        rgbimg = scene.imgs
        pts3d = to_numpy(scene.get_pts3d())
        mask = to_numpy(scene.get_masks())
        im_poses = scene.get_im_poses()
        
        # Concatenate points and colors
        points = np.concatenate([p[m] for p, m in zip(pts3d, mask)])
        colors = np.concatenate([p[m] for p, m in zip(rgbimg, mask)]) * 255
        
        # Transform to align with ground truth
        scale, rotation, translation = get_transformation_between_cameras(
            camera_poses_gt_from_pred[i].detach().cpu(), 
            im_poses.detach().cpu()
        )
        
        # Apply transformation to points
        points_scaled = points * scale
        points_translated = points_scaled @ rotation.numpy() + translation.numpy()
        
        points_cat.append(points_translated)
        colors_cat.append(colors)
        cameras_cat.append(camera_poses_gt_from_pred[i])
    
    return points_cat, colors_cat, cameras_cat

def main():
    """
    Main function to run the multi-scene reconstruction pipeline.
    """
    # Define scene configurations
    scene_configs = [
        # {
        #     'name': 'campus_hydro',
        #     'selected_indices': [0, 5, 10, 15, 20, 25, 30, 35]        
        # },
        {
            'name': 'campus_core',
            'selected_indices': [0, 5, 10, 15, 20, 25, 30, 35],
            'voxel_size': 0.05

        }
        # {
        #     'name': 'campus_hydro_secondary',
        #     'scene_id': 0,
        #     'selected_indices': [0, 5, 10, 15, 20, 25, 30, 35],
        #     'batch_size': 32,
        #     'schedule': 'cosine',
        #     'lr': 0.001,
        #     'niter': 100,
        #     'min_conf_thr': 0.5,
        #     'voxel_size': 0.05
        # }
    ]
    
    # Setup paths
    base_path = "/l/users/sebastian.cavada/MBZUAI-Campus/global_OG"
    data_path = f"{base_path}/_data_global"
    output_path = f"{base_path}/_data_global_denser"
    
    # Parse arguments (using default values for now)
    args = argparse.Namespace(
        model='mast3r',
        device='cuda',
        batch_size=32
    )        
    
    # Load model
    model = load_model(args.model, args.device)
    
    # Process each scene
    all_points = []
    all_colors = []
    
    for scene_config in scene_configs:
        print(f"\nLoading dataset for scene: {scene_config['name']}")
        # Load dataset
        dataset = CustomCOLMAP(
            size=200,
            split='train',
            images_path=f"{data_path}/images/",
            sfm_path=f"{data_path}/{scene_config['name']}/0",
            resolution=(512, 384),
            seed=777,
        )


        print(f"\nProcessing scene: {scene_config['name']}")
        
        # Process scene
        points_cat, colors_cat, cameras_cat = process_scene(
            scene_config, dataset, model, args.device
        )
        
        # Combine points and colors
        if points_cat:
            scene_points = np.concatenate(points_cat, axis=0)
            scene_colors = np.concatenate(colors_cat, axis=0)
            
            # Downsample if needed
            if scene_config.get('voxel_size', 0) > 0:
                scene_points, scene_colors, _ = voxel_downsample_with_colors(
                    scene_points, scene_colors, voxel_size=scene_config.get('voxel_size', 0.05)
                )
            
            all_points.append(scene_points)
            all_colors.append(scene_colors)
            
            print(f"Added {len(scene_points)} points from scene {scene_config['name']}")
    
    # Combine all scenes
    if all_points:
        points_total = np.concatenate(all_points, axis=0)
        colors_total = np.concatenate(all_colors, axis=0)
        
        print(f"Total points before final downsampling: {len(points_total)}")
        
        # Final downsampling
        total_points_downsampled, total_colors_downsampled, _ = voxel_downsample_with_colors(
            points_total, colors_total, voxel_size=0.05
        )
        
        print(f"Total points after final downsampling: {len(total_points_downsampled)}")
        
        # Read existing COLMAP points
        output_dir = f"{output_path}/campus_hydro"
        os.makedirs(output_dir, exist_ok=True)
        
        try:
            points_colmap = read_points3D_binary(f"{data_path}/campus_hydro/0/points3D.bin")
            print(f"Loaded {len(points_colmap)} existing points from COLMAP")
        except FileNotFoundError:
            points_colmap = {}
            print("No existing COLMAP points found, starting with empty set")
        
        # Find highest ID
        highest_id = max(points_colmap.keys()) if points_colmap else 0
        
        # Add new points
        for xyz, rgb in zip(total_points_downsampled, total_colors_downsampled):
            xyz_np = np.array(xyz)
            rgb_int = rgb.astype(int)
            
            highest_id += 1
            points_colmap[highest_id] = Point3D(
                id=highest_id,
                xyz=xyz_np,
                rgb=rgb_int,
                error=0,
                image_ids=np.array([]),
                point2D_idxs=np.array([])
            )
        
        print(f"Final point count: {len(points_colmap)}")
        
        # Write points to file
        write_points3D_binary(points_colmap, f"{output_dir}/points3D.bin")
        print(f"Points written to {output_dir}/points3D.bin")
    else:
        print("No points were processed. Check scene configurations.")

if __name__ == "__main__":
    main()