File size: 11,331 Bytes
a781d1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
336
337
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
SAGE-3D USDA Builder
====================

This utility converts a directory of USDZ scenes into USDA files by cloning a
template stage and swapping scene-specific references.

Key features
------------
- Fully configurable input/output directories through CLI arguments.
- Customizable template placeholder ID with safety checks on occurrence count.
- Optional overrides for the USDZ reference path and the collision payload path.
- Automatic adjustment of the authoring layer to match the generated filename.
"""

from __future__ import annotations

import argparse
from pathlib import Path
from typing import Iterable, Optional


# -----------------------------------------------------------------------------
# Helper utilities
# -----------------------------------------------------------------------------


def read_template(template_path: Path, base_id: str, expected_count: int) -> str:
    """Load and validate template content."""
    if not template_path.exists():
        raise FileNotFoundError(f"Template file not found: {template_path}")

    content = template_path.read_text(encoding="utf-8")
    actual_count = content.count(base_id)
    if actual_count != expected_count:
        raise ValueError(
            f"Placeholder '{base_id}' appears {actual_count} time(s), expected {expected_count}."
        )
    
    # Validate that placeholder strings exist in template
    if "@usdz_root" not in content:
        print("[WARN] Template does not contain '@usdz_root' placeholder")
    if "@collision_root@" not in content:
        print("[WARN] Template does not contain '@collision_root@' placeholder")
    
    return content


def iter_usdz_files(usdz_dir: Path) -> Iterable[Path]:
    """Yield USDZ files with purely numeric stems (scene IDs)."""
    if not usdz_dir.exists():
        raise FileNotFoundError(f"USDZ directory not found: {usdz_dir}")

    for usdz_path in sorted(usdz_dir.glob("*.usdz")):
        if usdz_path.stem.isdigit():
            yield usdz_path


def replace_placeholder(
    content: str,
    placeholder: str,
    replacement: str,
    label: str,
) -> str:
    """Replace a placeholder string within content.

    Args:
        content: Text to modify.
        placeholder: Placeholder string to search for (e.g., "@usdz_root[gauss.usda]@").
        replacement: Replacement string.
        label: Human readable name for logging.

    Returns:
        Updated content string.
    """
    if placeholder not in content:
        print(f"[WARN] {label} placeholder '{placeholder}' not found in template")
        return content

    occurrences = content.count(placeholder)
    content = content.replace(placeholder, replacement)

    if occurrences > 1:
        print(
            f"[WARN] {label} placeholder found {occurrences} times; "
            "all occurrences were replaced."
        )
    return content


def build_usda_content(
    template_text: str,
    scene_id: str,
    base_id: str,
    usdz_placeholder: str,
    usdz_path_template: str,
    collision_placeholder: str,
    collision_path_template: str,
) -> str:
    """Generate the USDA content for a single scene.
    
    Args:
        template_text: Template file content.
        scene_id: Scene ID to generate USDA for.
        base_id: Base placeholder ID in template (e.g., "839920").
        usdz_placeholder: Placeholder string in template (e.g., "@usdz_root[gauss.usda]@").
        usdz_path_template: Template for USDZ path with {scene_id} placeholder.
        collision_placeholder: Placeholder string in template (e.g., "@collision_root@").
        collision_path_template: Template for collision path with {scene_id} placeholder.
    
    Returns:
        Generated USDA content string.
    """
    content = template_text
    
    # Replace base_id placeholder (for authoring_layer and any other occurrences)
    content = content.replace(base_id, scene_id)

    # Replace USDZ reference placeholder
    usdz_path = usdz_path_template.format(scene_id=scene_id)
    content = replace_placeholder(
        content,
        usdz_placeholder,
        usdz_path,
        label="USDZ reference",
    )

    # Replace collision payload placeholder
    collision_path = collision_path_template.format(scene_id=scene_id)
    content = replace_placeholder(
        content,
        collision_placeholder,
        collision_path,
        label="Collision payload",
    )

    # Ensure authoring layer follows "./<scene_id>.usda"
    authoring_search = f'string authoring_layer = "./{scene_id}.usda"'
    if authoring_search not in content:
        authoring_base = f'string authoring_layer = "./{base_id}.usda"'
        replacement = f'string authoring_layer = "./{scene_id}.usda"'
        if authoring_base in content:
            content = content.replace(authoring_base, replacement, 1)
        else:
            print(f"[WARN] Authoring layer token not found for scene {scene_id}")

    return content


def generate_usda_files(
    usdz_dir: Path,
    out_dir: Path,
    template_path: Path,
    base_id: str,
    expected_count: int,
    usdz_placeholder: str,
    usdz_path_template: str,
    collision_placeholder: str,
    collision_path_template: str,
    overwrite: bool,
    limit: Optional[int] = None,
) -> None:
    """Generate USDA files by cloning the template for each USDZ scene.
    
    Args:
        usdz_dir: Directory containing input .usdz files.
        out_dir: Output directory for generated .usda files.
        template_path: Path to template USDA file.
        base_id: Base placeholder ID in template.
        expected_count: Expected count of base_id in template.
        usdz_placeholder: Placeholder string for USDZ reference (e.g., "@usdz_root[gauss.usda]@").
        usdz_path_template: Template for USDZ path with {scene_id} placeholder.
        collision_placeholder: Placeholder string for collision (e.g., "@collision_root@").
        collision_path_template: Template for collision path with {scene_id} placeholder.
        overwrite: Whether to overwrite existing files.
        limit: Limit number of files to generate (for testing).
    """
    template_text = read_template(template_path, base_id, expected_count)

    out_dir.mkdir(parents=True, exist_ok=True)
    usdz_files = list(iter_usdz_files(usdz_dir))
    if not usdz_files:
        print(f"[WARN] No USDZ files found in {usdz_dir}")
        return

    generated = 0
    skipped = 0

    for usdz_path in usdz_files:
        scene_id = usdz_path.stem
        out_path = out_dir / f"{scene_id}.usda"

        if out_path.exists() and not overwrite:
            print(f"[SKIP] {out_path} already exists (use --overwrite to replace)")
            skipped += 1
            continue

        content = build_usda_content(
            template_text,
            scene_id=scene_id,
            base_id=base_id,
            usdz_placeholder=usdz_placeholder,
            usdz_path_template=usdz_path_template,
            collision_placeholder=collision_placeholder,
            collision_path_template=collision_path_template,
        )

        out_path.write_text(content, encoding="utf-8")
        generated += 1
        print(f"[OK] Generated USDA: {out_path}")

        if limit and generated >= limit:
            print(f"[INFO] Limit reached ({limit} files). Stopping early.")
            break

    print(
        f"[SUMMARY] Generated: {generated}, Skipped: {skipped}, "
        f"Output directory: {out_dir}"
    )


# -----------------------------------------------------------------------------
# CLI
# -----------------------------------------------------------------------------


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Batch convert USDZ assets into USDA files using a template."
    )

    parser.add_argument(
        "--usdz-dir",
        type=Path,
        default=Path("/path/to/data/InteriorGS_usdz"),
        help="Directory containing input .usdz files.",
    )
    parser.add_argument(
        "--out-dir",
        type=Path,
        default=Path("/path/to/data/InteriorGS_usda"),
        help="Directory to store generated .usda files.",
    )
    parser.add_argument(
        "--template",
        type=Path,
        default=Path("Data/template.usda"),
        help="Path to the USDA template file containing the placeholder ID.",
    )
    parser.add_argument(
        "--base-id",
        type=str,
        default="839920",
        help="Placeholder ID present in the template (e.g., 839920) for scene ID replacement.",
    )
    parser.add_argument(
        "--expected-count",
        type=int,
        default=1,
        help="Expected number of occurrences of the placeholder ID in the template (for authoring_layer).",
    )
    parser.add_argument(
        "--usdz-placeholder",
        type=str,
        default="@usdz_root[gauss.usda]@",
        help="Placeholder string in template for USDZ reference (e.g., '@usdz_root[gauss.usda]@').",
    )
    parser.add_argument(
        "--usdz-path-template",
        type=str,
        default="/path/to/data/InteriorGS_usdz/{scene_id}.usdz[gauss.usda]",
        help="Template for the USDZ reference path. Use {scene_id} as placeholder. Note: '@' symbols will be added automatically.",
    )
    parser.add_argument(
        "--collision-placeholder",
        type=str,
        default="@collision_root@",
        help="Placeholder string in template for collision payload (e.g., '@collision_root@').",
    )
    parser.add_argument(
        "--collision-path-template",
        type=str,
        default="/path/to/data/InteriorGS_Collision/Collision/{scene_id}/{scene_id}_collision.usd",
        help="Template for the collision payload path. Use {scene_id} as placeholder. Note: '@' symbols will be added automatically.",
    )
    parser.add_argument(
        "--overwrite",
        action="store_true",
        help="Overwrite existing USDA files in the output directory.",
    )
    parser.add_argument(
        "--limit",
        type=int,
        help="Limit the number of files to generate (for testing).",
    )

    return parser.parse_args()


def main() -> None:
    args = parse_args()

    # Ensure path templates have '@' symbols if not provided
    usdz_path_template = args.usdz_path_template
    if not usdz_path_template.startswith("@"):
        usdz_path_template = "@" + usdz_path_template
    if not usdz_path_template.endswith("@"):
        usdz_path_template = usdz_path_template + "@"

    collision_path_template = args.collision_path_template
    if not collision_path_template.startswith("@"):
        collision_path_template = "@" + collision_path_template
    if not collision_path_template.endswith("@"):
        collision_path_template = collision_path_template + "@"

    generate_usda_files(
        usdz_dir=args.usdz_dir,
        out_dir=args.out_dir,
        template_path=args.template,
        base_id=args.base_id,
        expected_count=args.expected_count,
        usdz_placeholder=args.usdz_placeholder,
        usdz_path_template=usdz_path_template,
        collision_placeholder=args.collision_placeholder,
        collision_path_template=collision_path_template,
        overwrite=args.overwrite,
        limit=args.limit,
    )


if __name__ == "__main__":
    main()