File size: 9,378 Bytes
8f2154a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
高质量批量渲染脚本 - 使用 visualize_blender_hq.py
"""

import os
import json
import math
import sys
import collections
import argparse
from tqdm import tqdm

# Import high-quality visualizer
try:
    import visualize_blender_hq as viz
except ImportError:
    print("Error: visualize_blender_hq.py not found in current directory.")
    sys.exit(1)


def prepare_task_assets(task, asset_dir):
    """
    Prepare assets metadata (Simplified version from end_to_end_pipeline.py)
    Does not depend on torch/clip.
    """
    if "layout_criteria" not in task:
        task["layout_criteria"] = "the layout should follow the task description and adhere to common sense"

    all_data = collections.defaultdict(list)
    
    for original_uid in task["assets"].keys():
        parts = original_uid.split('-')
        if len(parts) > 1 and parts[-1].isdigit():
             uid = '-'.join(parts[:-1])
        else:
             uid = original_uid
        
        data_path = os.path.join(asset_dir, uid, "data.json")
        if not os.path.exists(data_path):
            if os.path.exists(os.path.join(asset_dir, original_uid, "data.json")):
                uid = original_uid
                data_path = os.path.join(asset_dir, uid, "data.json")
            else:
                continue
            
        with open(data_path, "r") as f:
            data = json.load(f)
        data['path'] = os.path.join(asset_dir, uid, f"{uid}.glb")
        all_data[uid].append(data)

    category_count = collections.defaultdict(int)
    for uid, duplicated_assets in all_data.items():
        if not duplicated_assets: continue
        category_var_name = duplicated_assets[0]['annotations']['category']
        category_var_name = category_var_name.replace('-', "_").replace(" ", "_").replace("'", "_").replace("/", "_").replace(",", "_").lower()
        category_count[category_var_name] += 1

    new_assets = {}
    category_idx = collections.defaultdict(int)
    
    for uid, duplicated_assets in all_data.items():
        if not duplicated_assets: continue
        category_var_name = duplicated_assets[0]['annotations']['category']
        category_var_name = category_var_name.replace('-', "_").replace(" ", "_").replace("'", "_").replace("/", "_").replace(",", "_").lower()
        category_idx[category_var_name] += 1
        
        for instance_idx, data in enumerate(duplicated_assets):
            category_var_name_final = f"{category_var_name}_{chr(ord('A') + category_idx[category_var_name]-1)}" if category_count[category_var_name] > 1 else category_var_name
            var_name = f"{category_var_name_final}_{instance_idx}" if len(duplicated_assets) > 1 else category_var_name_final
            
            key = f"{category_var_name_final}-{instance_idx}"
            
            new_assets[key] = {
                "uid": uid,
                "count": len(duplicated_assets),
                "instance_var_name": var_name,
                "asset_var_name": category_var_name_final,
                "instance_idx": instance_idx,
                "annotations": data["annotations"],
                "category": data["annotations"]["category"],
                'description': data['annotations']['description'],
                'path': data['path'],
                'assetMetadata': {
                    "boundingBox": {
                        "x": float(data['assetMetadata']['boundingBox']['y']),
                        "y": float(data['assetMetadata']['boundingBox']['x']),
                        "z": float(data['assetMetadata']['boundingBox']['z'])
                    },
                }
            }

    task["assets"] = new_assets
    return task


def process_dataset(results_dir, asset_dir, views=['topdown', 'diagonal'],
                   engine='CYCLES', width=1600, height=900, samples=256):
    """Process all samples in a results directory"""
    print(f"Processing dataset: {results_dir}")
    
    samples = sorted([d for d in os.listdir(results_dir) if d.startswith('sample_')])
    
    for sample_name in tqdm(samples):
        sample_dir = os.path.join(results_dir, sample_name)
        scene_config_path = os.path.join(sample_dir, 'scene_config.json')
        layout_path = os.path.join(sample_dir, 'layout.json')
        
        # Skip if layout doesn't exist
        if not os.path.exists(layout_path):
            continue
            
        # Skip if already rendered (check one view)
        if os.path.exists(os.path.join(sample_dir, f'render_{views[0]}.png')):
            continue

        try:
            # 1. Load scene config
            with open(scene_config_path, 'r') as f:
                scene_config = json.load(f)
            
            # 2. Prepare assets (map UIDs to category-index keys)
            scene_config = prepare_task_assets(scene_config, asset_dir)
            
            # 3. Load layout
            with open(layout_path, 'r') as f:
                layout = json.load(f)
            
            # 4. Construct scene object for visualizer
            scene_objects = []
            
            for key, transform in layout.items():
                if key not in scene_config['assets']:
                    continue
                
                asset_info = scene_config['assets'][key]
                
                # Convert rotation from radians to degrees
                rot_rad = transform.get('rotation', [0, 0, 0])
                rot_deg = [math.degrees(r) for r in rot_rad]
                
                # Get size from bounding box
                bbox = asset_info['assetMetadata']['boundingBox']
                size = [bbox['x'], bbox['y'], bbox['z']]
                
                obj_data = {
                    'id': key,
                    'model_id': asset_info['uid'],
                    'category': asset_info['category'],
                    'position': transform.get('position', [0, 0, 0]),
                    'rotation': rot_deg,
                    'size': size
                }
                scene_objects.append(obj_data)
            
            scene_for_viz = {
                'boundary': scene_config.get('boundary', {}).get('floor_vertices', []),
                'assets': scene_objects
            }
            
            if not scene_for_viz['boundary'] and 'boundary' in scene_config:
                 if isinstance(scene_config['boundary'], dict):
                     scene_for_viz['boundary'] = scene_config['boundary'].get('floor_vertices', [])
            
            # 5. Render views
            for view in views:
                output_path = os.path.join(sample_dir, f'render_{view}.png')
                
                # Map view names
                viz_view = view
                if view == 'topdown': viz_view = 'topdown'
                elif view == 'top': viz_view = 'topdown'
                
                viz.render_scene(
                    scene_for_viz,
                    output_path=output_path,
                    asset_dir=asset_dir,
                    view=viz_view,
                    engine=engine,
                    width=width,
                    height=height,
                    samples=samples,
                    # Use high-quality defaults
                    sun_intensity=3.5,
                    ambient_intensity=1.0,
                    use_fill_lights=True,
                    fill_intensity=0.5,
                    auto_crop=True,
                    crop_padding=10,
                )
                
        except Exception as e:
            print(f"Error processing {sample_name}: {e}")
            import traceback
            traceback.print_exc()


def main():
    parser = argparse.ArgumentParser(description='High-Quality Batch Rendering')
    parser.add_argument('--asset_dir', required=True, help='3D assets directory')
    parser.add_argument('--results_dir', default=None, help='Results directory (default: both zones and bench)')
    parser.add_argument('--engine', default='CYCLES', choices=['CYCLES', 'BLENDER_EEVEE', 'BLENDER_EEVEE_NEXT'])
    parser.add_argument('--width', type=int, default=1600)
    parser.add_argument('--height', type=int, default=900)
    parser.add_argument('--samples', type=int, default=256)
    parser.add_argument('--views', nargs='+', default=['topdown', 'diagonal'],
                       help='Views to render (topdown, diagonal, diagonal2, diagonal3, diagonal4, side_front, etc.)')
    args = parser.parse_args()
    
    asset_dir = os.path.expanduser(args.asset_dir)
    
    if args.results_dir:
        process_dataset(args.results_dir, asset_dir, args.views,
                       engine=args.engine, width=args.width, 
                       height=args.height, samples=args.samples)
    else:
        # Default: process both datasets
        print("Processing Zones Test 1000...")
        process_dataset('results/zones_test_1000', asset_dir, args.views,
                       engine=args.engine, width=args.width, 
                       height=args.height, samples=args.samples)
        
        print("Processing Bench Test 700...")
        process_dataset('results/bench_test_700', asset_dir, args.views,
                       engine=args.engine, width=args.width, 
                       height=args.height, samples=args.samples)


if __name__ == "__main__":
    main()