File size: 7,821 Bytes
8ca7ba0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import hashlib
import json
import os
import re
from pathlib import Path
from typing import Any

import yaml  # type: ignore[import-untyped]
from pydantic import BaseModel, ConfigDict, Field, model_validator

from packages.asset_registry.models import (
    AssetFile,
    AssetRecord,
    DimensionSource,
    GeometryMetadata,
    MountType,
    PlacementMetadata,
    RuntimeCompatibility,
)
from packages.asset_registry.proxy_sdf import render_proxy_sdf


class ParametricMaterial(BaseModel):
    model_config = ConfigDict(extra="forbid")
    base_color_texture: str | None = None
    roughness_texture: str | None = None
    normal_texture: str | None = None
    base_color: tuple[float, float, float, float] = (0.5, 0.5, 0.5, 1.0)
    roughness: float = Field(default=0.45, ge=0.0, le=1.0)
    metallic: float = Field(default=0.0, ge=0.0, le=1.0)
    texture_scale: tuple[float, float] = (1.0, 1.0)


class ParametricAssetRecipe(BaseModel):
    model_config = ConfigDict(extra="forbid")
    asset_id: str
    display_name: str
    description: str
    category: str
    tags: list[str]
    synonyms: list[str] = Field(default_factory=list)
    dimensions_m: tuple[float, float, float]
    geometry_style: str = "slab"
    module_count: int = Field(default=1, ge=1, le=16)
    mount: MountType
    support_surfaces: list[str] = Field(default_factory=list)
    bevel_m: float = Field(default=0.004, ge=0.0)
    material: ParametricMaterial
    source_url: str
    source_license: str = "CC0-1.0"

    @model_validator(mode="after")
    def validate_geometry(self) -> ParametricAssetRecipe:
        if any(value <= 0.0 for value in self.dimensions_m):
            raise ValueError("parametric asset dimensions must be positive")
        if self.bevel_m * 2.0 >= min(self.dimensions_m):
            raise ValueError("bevel_m must be smaller than half the shortest dimension")
        return self


class ParametricAssetLibrary(BaseModel):
    model_config = ConfigDict(extra="forbid")
    schema_version: str = "1.0"
    output_root: str
    assets: list[ParametricAssetRecipe]


def _expand_path(value: str, *, base: Path) -> Path:
    expanded = os.path.expandvars(value)
    unresolved = re.findall(r"\$\{[^}]+\}|\$[A-Za-z_][A-Za-z0-9_]*", expanded)
    if unresolved:
        raise ValueError(f"unresolved environment variables in path {value!r}: {unresolved}")
    path = Path(expanded).expanduser()
    return (path if path.is_absolute() else base / path).resolve()


def load_parametric_asset_library(path: Path) -> ParametricAssetLibrary:
    payload = yaml.safe_load(path.read_text(encoding="utf-8"))
    return ParametricAssetLibrary.model_validate(payload)


def build_jobs(
    library: ParametricAssetLibrary,
    *,
    recipe_path: Path,
) -> tuple[Path, list[dict[str, Any]]]:
    output_root = _expand_path(library.output_root, base=recipe_path.parent)
    jobs: list[dict[str, Any]] = []
    for recipe in library.assets:
        safe_id = re.sub(r"[^A-Za-z0-9_.-]+", "_", recipe.asset_id)
        asset_root = output_root / safe_id
        material = recipe.material.model_dump(mode="json")
        for key in ("base_color_texture", "roughness_texture", "normal_texture"):
            if material.get(key):
                material[key] = str(_expand_path(str(material[key]), base=recipe_path.parent))
        jobs.append(
            {
                "asset_id": recipe.asset_id,
                "dimensions_m": list(recipe.dimensions_m),
                "geometry_style": recipe.geometry_style,
                "module_count": recipe.module_count,
                "bevel_m": recipe.bevel_m,
                "material": material,
                "canonical_usd": str(asset_root / "asset.usdc"),
                "proxy_glb": str(asset_root / "asset.glb"),
            }
        )
    return output_root, jobs


def _md5(path: Path) -> str:
    digest = hashlib.md5(usedforsecurity=False)
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(4 * 1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def records_from_outputs(
    library: ParametricAssetLibrary,
    *,
    recipe_path: Path,
    jobs: list[dict[str, Any]],
) -> list[AssetRecord]:
    jobs_by_id = {str(job["asset_id"]): job for job in jobs}
    records: list[AssetRecord] = []
    for recipe in library.assets:
        job = jobs_by_id[recipe.asset_id]
        canonical = Path(job["canonical_usd"])
        proxy = Path(job["proxy_glb"])
        for required in (canonical, proxy):
            if not required.is_file() or required.stat().st_size == 0:
                raise RuntimeError(f"parametric asset output is missing: {required}")
        dimensions = recipe.dimensions_m
        bbox_min = (-dimensions[0] / 2.0, -dimensions[1] / 2.0, 0.0)
        bbox_max = (dimensions[0] / 2.0, dimensions[1] / 2.0, dimensions[2])
        sdf = proxy.with_suffix(".sdf")
        sdf.write_text(
            render_proxy_sdf(
                recipe.asset_id,
                proxy.name,
                bbox_min,
                bbox_max,
                articulated=False,
            ),
            encoding="utf-8",
        )
        records.append(
            AssetRecord(
                asset_id=recipe.asset_id,
                scene_name=re.sub(r"[^A-Za-z0-9_]", "_", recipe.asset_id),
                display_name=recipe.display_name,
                description=recipe.description,
                source="RoboHouseGen Parametric",
                source_license=recipe.source_license,
                category=recipe.category,
                tags=recipe.tags,
                synonyms=recipe.synonyms,
                files=[
                    AssetFile(
                        relative_path=str(canonical.relative_to(canonical.parent.parent)),
                        source_url=recipe.source_url,
                        md5=_md5(canonical),
                        size_bytes=canonical.stat().st_size,
                    )
                ],
                usd_path=str(canonical),
                dimensions_m=dimensions,
                quality_tier="A",
                qa_status="CONVERTED",
                normalized_category=recipe.category,
                dimension_source=DimensionSource.MEASURED,
                dimension_confidence=1.0,
                geometry_metadata=GeometryMetadata(
                    bbox_min_m=bbox_min,
                    bbox_max_m=bbox_max,
                    footprint_m=(dimensions[0], dimensions[1]),
                    ground_offset_m=0.0,
                    meters_per_unit=1.0,
                    up_axis="Z",
                ),
                placement_metadata=PlacementMetadata(
                    mount=recipe.mount,
                    support_surfaces=recipe.support_surfaces,
                ),
                runtime_compatibility=RuntimeCompatibility(
                    canonical_usd_path=str(canonical),
                    proxy_gltf_path=str(proxy),
                    proxy_sdf_path=str(sdf),
                    compatible_backends=["isaac-sim", "scenesmith"],
                    articulation=False,
                    has_collision=False,
                ),
            )
        )
    return records


def merge_records(existing: list[AssetRecord], generated: list[AssetRecord]) -> list[AssetRecord]:
    replacements = {record.asset_id: record for record in generated}
    merged = [record for record in existing if record.asset_id not in replacements]
    merged.extend(generated)
    return sorted(merged, key=lambda record: record.asset_id)


def write_job_manifest(path: Path, jobs: list[dict[str, Any]]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(jobs, indent=2) + "\n", encoding="utf-8")