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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
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
485
486
487
488
#!/usr/bin/env python3
"""
Zone Isolation Visualization - Render each functional zone independently.

This script renders each zone separately with close-up "in your face" camera views
while ensuring all assets in the zone are visible. Renders 8 views per zone:
- 4 diagonal views (diagonal, diagonal2, diagonal3, diagonal4)
- 4 side views (side_front, side_back, side_left, side_right)

Output structure:
  output_dir/
    zone_<id>/
      diagonal.png
      diagonal2.png
      diagonal3.png
      diagonal4.png
      side_front.png
      side_back.png
      side_left.png
      side_right.png
      zone_info.json

Based on visualize_zones_progressive.py logic.
"""

import os
import json
import argparse
import subprocess
import sys
import shutil
from pathlib import Path
from typing import List, Dict, Any, Optional, Tuple
from copy import deepcopy

import numpy as np
import trimesh
from trimesh.visual.material import PBRMaterial

# Add project root
SCRIPT_DIR = Path(__file__).parent
REPO_ROOT = SCRIPT_DIR.parent.parent
sys.path.insert(0, str(REPO_ROOT))

# Import from visualize_zones
from tools.utils.visualize_zones import (
    ZONE_COLORS,
    compute_zone_bbox,
    compute_all_zone_bboxes,
    get_scene_bounds,
)


# All 8 view modes
DIAGONAL_VIEWS = ["diagonal", "diagonal2", "diagonal3", "diagonal4"]
SIDE_VIEWS = ["side_front", "side_back", "side_left", "side_right"]
ALL_VIEWS = DIAGONAL_VIEWS + SIDE_VIEWS


def run_command(cmd, env=None, quiet=False):
    """Run a shell command."""
    if not quiet:
        print(f"  Running: {cmd[:100]}...")
    try:
        if quiet:
            subprocess.check_call(cmd, shell=True, env=env,
                                  stdout=subprocess.DEVNULL,
                                  stderr=subprocess.DEVNULL)
        else:
            subprocess.check_call(cmd, shell=True, env=env)
        return True
    except subprocess.CalledProcessError as e:
        print(f"  Command failed: {e}")
        return False


def compose_single_zone_scene(
    layout: Dict,
    zone_index: int,
    output_path: str,
    use_retrieval: bool = True,
    embedding_manager=None,
    asset_finder=None,
) -> str:
    """
    Compose a scene with only a single zone's assets.
    
    Args:
        layout: Full layout dictionary
        zone_index: Index of zone to include (0-based)
        output_path: Output GLB path
        use_retrieval: Whether to run asset retrieval
        embedding_manager: Pre-initialized embedding manager
        asset_finder: Pre-initialized asset finder
        
    Returns:
        Path to composed GLB
    """
    from tools.data_gen.compose_generated import compose_scene
    
    # Create layout with only the selected zone
    partial_layout = deepcopy(layout)
    
    all_zones = layout.get('functional_zones', [])
    
    if zone_index >= len(all_zones):
        raise ValueError(f"Zone index {zone_index} out of range (total: {len(all_zones)})")
    
    # Keep only the specified zone
    partial_layout['functional_zones'] = [all_zones[zone_index]]
    
    # Remove top-level assets to avoid duplication
    partial_layout.pop('assets', None)
    partial_layout.pop('groups', None)
    
    if use_retrieval:
        from tools.data_gen.layout_retrieval import process_layout
        
        # Use provided managers or create new ones
        if embedding_manager is None or asset_finder is None:
            from tools.asset_description.asset_embedding_manager import AssetEmbeddingManager
            from tools.asset_description.asset_finder import AssetFinder
            
            asset_library_dir = os.path.join(REPO_ROOT, "data/asset_library")
            embeddings_file = os.path.join(REPO_ROOT, "tools/asset_embeddings.pkl")
            
            embedding_manager = AssetEmbeddingManager(embeddings_file=embeddings_file)
            asset_finder = AssetFinder(asset_library_dir)
        
        partial_layout = process_layout(partial_layout, embedding_manager, asset_finder)
    
    # Compose scene - no floor, walls, or ceiling for isolated zone view
    compose_scene(
        layout=partial_layout,
        output_path=output_path,
        add_floor=False,
        add_walls=False,
        add_ceiling=False,
    )
    
    return output_path


def compute_zone_camera_params(zone_info: Dict) -> Dict:
    """
    Compute camera parameters to get a close-up view of the zone.
    
    Args:
        zone_info: Zone info dict with bbox
        
    Returns:
        Dict with camera parameters
    """
    bbox = zone_info['bbox']
    bbox_min = np.array(bbox['min'])
    bbox_max = np.array(bbox['max'])
    
    # Compute center and size
    center = (bbox_min + bbox_max) / 2.0
    size = bbox_max - bbox_min
    
    # Diagonal of the bbox - determines how far camera needs to be
    diagonal = np.linalg.norm(size)
    
    # For close-up view, use smaller distance factor
    # The camera will be positioned at diagonal_distance * diagonal from center
    camera_distance_factor = 0.8  # Close-up but still see everything
    
    return {
        'center': center.tolist(),
        'size': size.tolist(),
        'diagonal': float(diagonal),
        'camera_distance_factor': camera_distance_factor,
    }


def render_zone_view(
    glb_path: str,
    output_path: str,
    view_mode: str,
    zone_camera_params: Dict,
    width: int = 1600,
    height: int = 1200,
    engine: str = "BLENDER_EEVEE",
    samples: int = 256,
):
    """
    Render a zone from a specific view with close-up camera.
    
    Args:
        glb_path: Input GLB path
        output_path: Output PNG path
        view_mode: Camera view mode
        zone_camera_params: Camera parameters computed from zone bbox
        width: Image width
        height: Image height
        engine: Blender render engine
        samples: Number of samples
    """
    current_env = os.environ.copy()
    
    # Use smaller diagonal distance for close-up view
    diagonal_distance = zone_camera_params['camera_distance_factor']
    
    # High quality render args similar to visualize_gt_hq.py
    HQ_RENDER_ARGS = (
        f"--engine {engine} --samples {samples} "
        "--fill-lights "
        "--floor-material solid"  # Simple floor for zone isolation
    )
    
    # Side views get slight elevation angle for better perspective
    elevation_arg = ""
    if view_mode.startswith("side_"):
        elevation_arg = "--side-elevation-angle 25"
    
    cmd = (
        f"conda run -n blender python InternScenes/InternScenes_Real2Sim/blender_renderer.py "
        f"--input '{glb_path}' "
        f"--output '{output_path}' "
        f"--width {width} --height {height} "
        f"--view-mode {view_mode} "
        f"--diagonal-distance {diagonal_distance} "
        f"--camera-factor 1.2 "  # Slightly wider field of view
        f"{elevation_arg} "
        f"{HQ_RENDER_ARGS}"
    )
    
    return run_command(cmd, env=current_env, quiet=True)


def visualize_zone_isolation(
    layout_path: str,
    output_dir: str,
    use_retrieval: bool = True,
    render_diagonal: bool = True,
    render_side: bool = True,
    width: int = 1600,
    height: int = 1200,
    engine: str = "BLENDER_EEVEE",
    samples: int = 256,
    zone_indices: List[int] = None,
):
    """
    Main function: render each zone independently with close-up views.
    
    Args:
        layout_path: Path to layout.json file
        output_dir: Directory to save outputs
        use_retrieval: Whether to run asset retrieval
        render_diagonal: Whether to render 4 diagonal views
        render_side: Whether to render 4 side views
        width: Image width
        height: Image height
        engine: Blender render engine
        samples: Number of render samples
        zone_indices: Specific zone indices to render (None = all zones)
    """
    print(f"\n{'='*60}")
    print(f"Zone Isolation Visualization")
    print(f"{'='*60}")
    print(f"Input: {layout_path}")
    print(f"Output: {output_dir}")
    print(f"Engine: {engine}, Samples: {samples}")
    print(f"Resolution: {width}x{height}")
    print(f"{'='*60}\n")
    
    # Load layout
    with open(layout_path, 'r') as f:
        layout = json.load(f)
    
    # Create output directory
    os.makedirs(output_dir, exist_ok=True)
    
    # Get zones info
    functional_zones = layout.get('functional_zones', [])
    n_zones = len(functional_zones)
    
    if n_zones == 0:
        print("Error: No functional zones found in layout!")
        return
    
    print(f"Found {n_zones} functional zones")
    
    # Compute zone bboxes
    print("\nComputing zone bounding boxes...")
    zones_info = compute_all_zone_bboxes(layout)
    
    if len(zones_info) == 0:
        print("Error: No valid zones with bbox found!")
        return
    
    # Map zone_id to original index
    zone_id_to_original_idx = {}
    for i, zone in enumerate(functional_zones):
        zone_id = zone.get('id', f'zone_{i}')
        zone_id_to_original_idx[zone_id] = i
    
    for zone_info in zones_info:
        zone_info['original_index'] = zone_id_to_original_idx.get(zone_info['zone_id'], -1)
    
    # Filter to specific zone indices if provided
    if zone_indices is not None:
        zones_info = [z for z in zones_info if z['original_index'] in zone_indices]
        print(f"Filtering to {len(zones_info)} specified zones")
    
    # Print zone info
    print("\nZones to render:")
    for zone_info in zones_info:
        print(f"  [{zone_info['original_index']}] {zone_info['zone_id']}: {zone_info['semantic_label']} ({zone_info['asset_count']} assets)")
    
    # Determine views to render
    views_to_render = []
    if render_diagonal:
        views_to_render.extend(DIAGONAL_VIEWS)
    if render_side:
        views_to_render.extend(SIDE_VIEWS)
    
    if not views_to_render:
        print("Error: No views to render! Enable at least --diagonal or --side")
        return
    
    print(f"\nViews to render per zone: {views_to_render}")
    
    # Create temp directory for intermediate GLBs
    temp_dir = os.path.join(output_dir, "_temp")
    os.makedirs(temp_dir, exist_ok=True)
    
    # Initialize embedding manager and asset finder once
    embedding_manager = None
    asset_finder = None
    if use_retrieval:
        print("\nInitializing asset retrieval system...")
        from tools.asset_description.asset_embedding_manager import AssetEmbeddingManager
        from tools.asset_description.asset_finder import AssetFinder
        
        asset_library_dir = os.path.join(REPO_ROOT, "data/asset_library")
        embeddings_file = os.path.join(REPO_ROOT, "tools/asset_embeddings.pkl")
        
        embedding_manager = AssetEmbeddingManager(embeddings_file=embeddings_file)
        asset_finder = AssetFinder(asset_library_dir)
        print("  Asset retrieval system initialized.")
    
    # Process each zone
    for zone_info in zones_info:
        zone_id = zone_info['zone_id']
        zone_idx = zone_info['original_index']
        semantic_label = zone_info['semantic_label']
        
        print(f"\n{'='*50}")
        print(f"Processing Zone: {zone_id} ({semantic_label})")
        print(f"{'='*50}")
        
        # Create zone output directory
        zone_output_dir = os.path.join(output_dir, f"zone_{zone_id}")
        os.makedirs(zone_output_dir, exist_ok=True)
        
        # Compose scene with only this zone's assets
        zone_glb_path = os.path.join(temp_dir, f"zone_{zone_id}_scene.glb")
        print(f"  Composing zone scene...")
        try:
            compose_single_zone_scene(
                layout=layout,
                zone_index=zone_idx,
                output_path=zone_glb_path,
                use_retrieval=use_retrieval,
                embedding_manager=embedding_manager,
                asset_finder=asset_finder,
            )
        except Exception as e:
            print(f"  Error composing zone: {e}")
            continue
        
        # Compute camera params for close-up view
        camera_params = compute_zone_camera_params(zone_info)
        print(f"  Zone bbox diagonal: {camera_params['diagonal']:.2f}m")
        
        # Render all views
        for view in views_to_render:
            output_img = os.path.join(zone_output_dir, f"{view}.png")
            print(f"  Rendering {view}...")
            
            success = render_zone_view(
                glb_path=zone_glb_path,
                output_path=output_img,
                view_mode=view,
                zone_camera_params=camera_params,
                width=width,
                height=height,
                engine=engine,
                samples=samples,
            )
            
            if success and os.path.exists(output_img):
                print(f"    ✓ Saved: {output_img}")
            else:
                print(f"    ✗ Failed to render {view}")
        
        # Save zone info
        zone_info_path = os.path.join(zone_output_dir, "zone_info.json")
        zone_info_to_save = {
            'zone_id': zone_id,
            'semantic_label': semantic_label,
            'asset_count': zone_info['asset_count'],
            'bbox': zone_info['bbox'],
            'camera_params': camera_params,
        }
        with open(zone_info_path, 'w') as f:
            json.dump(zone_info_to_save, f, indent=2)
    
    # Clean up temp directory
    # shutil.rmtree(temp_dir)  # Uncomment to auto-clean
    
    print(f"\n{'='*60}")
    print(f"Done! Outputs saved to: {output_dir}")
    print(f"{'='*60}")
    
    # Summary
    print("\n=== Output Summary ===")
    for zone_info in zones_info:
        zone_id = zone_info['zone_id']
        zone_dir = os.path.join(output_dir, f"zone_{zone_id}")
        if os.path.exists(zone_dir):
            files = [f for f in os.listdir(zone_dir) if f.endswith('.png')]
            print(f"  zone_{zone_id}/: {len(files)} images")


def main():
    parser = argparse.ArgumentParser(
        description="Render each functional zone independently with close-up views",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  # Basic usage - render all zones with all 8 views
  python visualize_zone_isolation.py --input layout.json --output zone_output
  
  # Render only diagonal views
  python visualize_zone_isolation.py --input layout.json --output zone_output --no-side
  
  # Render only side views
  python visualize_zone_isolation.py --input layout.json --output zone_output --no-diagonal
  
  # Render specific zones only (by index)
  python visualize_zone_isolation.py --input layout.json --output zone_output --zones 0 2 3
  
  # Higher quality with CYCLES
  python visualize_zone_isolation.py --input layout.json --output zone_output --engine CYCLES --samples 512
  
  # Higher resolution
  python visualize_zone_isolation.py --input layout.json --output zone_output --width 2400 --height 1800

Views rendered per zone:
  Diagonal: diagonal, diagonal2, diagonal3, diagonal4
  Side: side_front, side_back, side_left, side_right
"""
    )
    
    parser.add_argument("--input", default="case_hq/H-shaped_01_001536_1766364802273481/layout_retrieved/layout_retrieved.json", help="Path to layout JSON file")
    parser.add_argument("--output", default="zone_isolation_output1536", help="Output directory")
    parser.add_argument("--no-retrieval", action="store_true", help="Skip asset retrieval (use existing model_uid)")
    parser.add_argument("--no-diagonal", action="store_true", help="Skip diagonal views")
    parser.add_argument("--no-side", action="store_true", help="Skip side views")
    parser.add_argument("--zones", type=int, nargs="+", help="Specific zone indices to render")
    parser.add_argument("--width", type=int, default=1600, help="Image width (default: 1600)")
    parser.add_argument("--height", type=int, default=1200, help="Image height (default: 1200)")
    parser.add_argument("--engine", default="BLENDER_EEVEE", choices=["BLENDER_EEVEE", "CYCLES"],
                       help="Blender render engine (default: BLENDER_EEVEE)")
    parser.add_argument("--samples", type=int, default=256, help="Render samples (default: 256)")
    
    args = parser.parse_args()
    
    visualize_zone_isolation(
        layout_path=args.input,
        output_dir=args.output,
        use_retrieval=not args.no_retrieval,
        render_diagonal=not args.no_diagonal,
        render_side=not args.no_side,
        width=args.width,
        height=args.height,
        engine=args.engine,
        samples=args.samples,
        zone_indices=args.zones,
    )


if __name__ == "__main__":
    main()