mirror of
https://github.com/bherbruck/solidcraft.git
synced 2026-11-07 20:41:50 +00:00
9e6e0b8df1
* wip(render): reconcile completed material and image pipeline source with 0.20 (#5493) Source-only integration reference for staged review, not a merge-ready aggregate. Donor: 0xlillith/solidcraft@aea20b0115. Upstream:858e5995d6. Retain original CPU/material contracts and explicit GPU donor provenance in docs/render-materials-lab.md (#2067, #2191, #2780, #3306). Preserve released format migrations and current navigation/startup/shell behavior. New saved records use pending descriptors. The physical-card descriptor follows the maintainer's material-engineering-cards naming request, with a legacy-lab format-29 regression. Replace raw new panel hosts with shared containers. Repository checks, complete workspace/all-target Clippy, and the independent physical/resource authoring checks pass for this source. The fresh full local CI invocation has reached test compilation and is not yet complete. Do not transfer donor native output or prior test totals to this integration. Generated review screenshots, video, package ZIP and machine logs remain at the immutable personal evidence pin. Uncommitted geometric displacement is backed up separately, not silently included. No kernel/vendor change, direct main write, release or independent contributor-branch rewrite. Co-authored-by: Christian Svensson <blue@cmd.nu> * test(cli): pin the Compact camera-sample admission diagnostic (#5493) The bounded request still refuses 1024x1024x64 samples before host initialization and writes no output. Update only the stale expected diagnostic to the existing Compact budget wording; production limits and code are unchanged. Exact-tree CLI regression suite: 14 passed, 0 failed. The full repository gate has been invoked separately and is not yet complete. * Normalize UI container violation paths across platforms Report repository-relative paths with forward slashes so diagnostics and the existing nested-package regression assertions agree on Windows and Unix. Keep the container detection rules unchanged. Validation: official ui-containers gate and all seven focused xtask tests passed; rustfmt and diff checks passed. Only xtask/dependencies were compiled; no application build or heavy tests. (cherry picked from commit44b58d8e10) * fix(render): preserve camera contracts and correct acceptance regressions (#5493) Preserve Design view.apply semantics with a separate strict Render camera command. Retain existing translations when English-only aliases collide; add material-axis entries and camera-specific pitch labels. Compare complete validated engineering cards and retain job handles before cancellation. Focused and native acceptance is pinned to treef8a423b21f. Full CI has been invoked separately and is not claimed green. Landing follows the render integration policy in #5493. * fix(render): resolve showcase licence and upstream resource hygiene (#5493) Record SychPL's explicit MIT OR Apache-2.0 grant, retaining source/model bytes and the Ubuntu lettering notice. Remove 80 absent attribution rows, personal fork records, dead delivery attributes and three fork/resource-only workflows. Existing xtask assets now performs bounded offline hash checks and rejects orphan render attribution; no parallel draft CI or package installation. Original authoring reproduction remains explicit. Scoped xtask tests, assets, Clippy, formatting and prepared SELENE validation pass; no application or renderer-wide result is inferred. * fix(render): align saved bounds and progressive sample resolution (#5493) Address review r4364211669/r4364211677/r4364211681/r4364211691/r4364211695. Persisted light/frame domains respect the existing 1e9 document bound; related LED/rectangle/direction cases use the same bound. Workstation primary resolve shares the 4096 admission cap and film counters use checked conversions. Exact candidate: 485 CPU render tests, 21 render document tests and strict scoped Clippy pass, including positive boundary round trips and 2048/4096 end-to-end checkpoints. No released format/migration edits, relaxed test limits or full-stack acceptance claim. * wip(render): isolate optional resources and harden sample handling (#5493) Review work in progress: opt-in encoded render library with reproducible runtime catalog exports; native-only robust dependency through the workspace; checked bloom slices; per-sample point-light diagnostics; independent area-light spatial/film keys. Resource-module binaries in both configurations, generation, Cargo production feature graphs and attribution checks pass. Full engine/render regression and combined acceptance are pending: do not merge this donor as a constituent or treat scoped resource proof as runtime acceptance. * fix(gpu): preserve donor allocations through the scope-safety repair (#5722) Port the native-validated #5723 scope-cleanup correction into the experimental donor, retaining its adaptive, volume, aging, photographic and bloom allocations. Same reverse-drain helper and regression cases; the donor combination still needs its own compile/test gate and is not covered retroactively by render-base results. * claim: #1369 * Reject unknown pending concepts after format folding (#1369) * test(render): close bounded sampling and bloom review regressions (#5493) Validate the optional-resource/lighting/dependency donor at its exact tree. Required Vulkan GPU 127/0/3; CPU renderer 487/0; engine Render 72/0; document render 21/0; lean library 7/0; strict scoped Clippy, assets/layers/lists/containers and lean-engine WASM pass. Preserve original failed controller/typing attempts. This is the draft donor/disposition source, not a replacement for constituent render PRs or final main acceptance. * wip(render): preserve stable aging target validation candidate Exact staged source from prior review work on donor3b892eab5e. This is a recovery/review checkpoint, NOT accepted delivery. An actual command-path regression currently fails because the selected executor refuses ordered surface aging. No assertion, capability or admission limit is weakened. Native/UI/full combination acceptance remains pending. Saved/runtime split adds one pending descriptor and retains original file scope; no main/render branch is changed. * test(render): preserve numeric setup intent at the admitted coordinate bound Follow up jyviko review on #5494 without weakening the corrected saved-coordinate contract. The positive clicked fixture uses 1e9 instead of inadmissible 2e9; explicit out-of-range cases still refuse, and the full saved setup round-trips through JSON and the native container. Exact-source Render workspace 95/0 and strict all-target UI Clippy pass. This does not incorporate the separately failing stable-aging candidate or claim full current-render acceptance. * test(render): use the real GPU executor for saved aging Move successful native cold-reopen Check/Start coverage from the CPU-backed protocol fixture into the production GPU executor tests. Verify capture-index changes preserve the stable target and that enabling aging changes both PNG and raw EXR output. Retain explicit, allocation-free refusal coverage for executors without aging support. Production capabilities and admission checks are unchanged. * fix(render): persist stable identities for targeted aging (#5493) Separate saved RenderBodyTarget identities from captured mesh ordinals. Reject legacy ambiguous targets, resolve Check/Start after visibility changes and preserve native reopening, copies and undo. Unsupported executors still refuse; real AMD Vulkan regression completes saved aging after reordered capture. Source tree6b84c8adpasses document 23, engine Render 75, GPU effects 5 and Render UI 95 with no failures; scoped strict Clippy, WASM and repository gates pass. Fresh CLI/native reopen and clean/aged GPU exports pass with identical physical totals and inspected actual images. Whole current-render integration is separate. * fix(render): reconcile combined CPU/GPU contracts on current upstream Unify captured resources/status and CPU-vs-GPU request schemas after the real two-parent integration; remove obsolete duplicate Vulkan selector and retain combined platform-filter regression. Deduplicate only identical or superseded test definitions, retaining the stronger card metadata and reserved-executor assertions. No assertions, admission limits or feature refusals are weakened. All targets of render dependencies, GPU, engine, UI, CLI and native app pass cargo check with raytrace-cpu and bundled-render-library at treec70d00d1. Native executable tests and full current-source acceptance remain pending. This is a private integration rehearsal for subsequent constituent PRs, not an aggregate official render/main merge. * test(render): retain one complete host lifetime regression set Deduplicate byte-identical DropProbe/task-lifetime tests and retain the adapted environment/texture ownership regressions with every assertion and complete memory estimate. Keep the registered-geometry admission regression once; only struct field order differed. Replace a one-element diagnostic loop with its equivalent block, preserving all wrap/width assertions. Test-only integration repair. Formatting and diff checks pass; refreshed executable validation is required. No production behavior, limits, assertions or ignores changed. * fix(doc): recognize the proven format-29 card descriptor alias Normalize only the historical format-29 physical-material-cards spelling, and only when material-engineering-cards is registered. Admission and migration de-duplication use the same identity. Unknown concepts, wrong versions and incapable readers still refuse before mutation. Six controlled-history Rust regressions and actual CLI migration/no-clobber acceptance pass. No version, released migration or CI changes. Refs #5793, #1369, #5493. * test(render): preserve grounding refusal before explicit instance moves Update the two Render binding fixtures for upstream first-occurrence grounding. Verify grounded movement refuses without changing document/history, then explicitly unground through the public command before the intended move. Retain every target, resource, copy and persistence assertion. Refs #5493. --------- Co-authored-by: Christian Svensson <blue@cmd.nu> Co-authored-by: Victor Santos Oliveira <56417388+Vittuu@users.noreply.github.com> Co-authored-by: cfaulkingham <colin.faulkingham@gmail.com>
344 lines
20 KiB
Python
344 lines
20 KiB
Python
#!/usr/bin/env python3
|
|
"""Inspect a native candidate and compile reviewed opaque appearance overlays.
|
|
|
|
Python 3.11 development tooling only. Never evaluates geometry, solves joints,
|
|
downloads a model, modifies a native design, or automatically approves a source.
|
|
Run --help or read ../README.md. Output files are created exclusively, not replaced.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import hashlib
|
|
import io
|
|
import json
|
|
import math
|
|
import re
|
|
import sys
|
|
import zipfile
|
|
from collections import Counter, defaultdict, deque
|
|
from pathlib import Path, PurePosixPath
|
|
|
|
|
|
PACKAGE = Path(__file__).resolve().parents[1]
|
|
MAX_ARCHIVE_BYTES = 64 * 1024 * 1024
|
|
MAX_DOCUMENT_BYTES = 128 * 1024 * 1024
|
|
MAX_RECORDS = 100_000
|
|
JOINT_VALUES = {
|
|
"rigid": [], "revolute": ["rad"], "slider": ["mm"],
|
|
"cylindrical": ["rad", "mm"], "pin_slot": ["rad", "mm"],
|
|
"planar": ["mm", "mm", "rad"], "ball": ["rad", "rad", "rad"],
|
|
}
|
|
|
|
|
|
def require(condition: bool, message: str) -> None:
|
|
if not condition:
|
|
raise ValueError(message)
|
|
|
|
|
|
def unique_object(pairs: list[tuple]) -> dict:
|
|
result = {}
|
|
for key, value in pairs:
|
|
require(key not in result, f"Duplicate JSON key: {key}")
|
|
result[key] = value
|
|
return result
|
|
|
|
|
|
def reject_constant(value: str) -> None:
|
|
raise ValueError(f"Non-finite JSON number: {value}")
|
|
|
|
|
|
def decode(data: bytes) -> dict:
|
|
value = json.loads(data.decode("utf-8"), object_pairs_hook=unique_object,
|
|
parse_constant=reject_constant)
|
|
require(isinstance(value, dict), "Expected a JSON object.")
|
|
pending = [value]
|
|
while pending:
|
|
node = pending.pop()
|
|
if isinstance(node, dict):
|
|
pending.extend(node.values())
|
|
elif isinstance(node, list):
|
|
pending.extend(node)
|
|
elif isinstance(node, float):
|
|
require(math.isfinite(node), "Non-finite JSON number.")
|
|
return value
|
|
|
|
|
|
def read_json(path: Path) -> dict:
|
|
with path.open("rb") as stream:
|
|
data = stream.read(MAX_DOCUMENT_BYTES + 1)
|
|
require(len(data) <= MAX_DOCUMENT_BYTES, "JSON file exceeds inspection budget.")
|
|
return decode(data)
|
|
|
|
|
|
def write_json(path: Path, value: dict) -> None:
|
|
encoded = json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n"
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
with path.open("x", encoding="utf-8") as stream:
|
|
stream.write(encoded)
|
|
|
|
|
|
def number(value: object) -> bool:
|
|
return type(value) is int or (type(value) is float and math.isfinite(value))
|
|
|
|
|
|
def index_records(value: object, label: str) -> dict[int, dict]:
|
|
require(isinstance(value, list) and len(value) <= MAX_RECORDS,
|
|
f"{label}: expected at most {MAX_RECORDS} records.")
|
|
result = {}
|
|
for item in value:
|
|
require(isinstance(item, dict), f"{label}: expected object records.")
|
|
identity = item.get("id")
|
|
require(type(identity) is int and 0 < identity < 2**64,
|
|
f"{label}: invalid positive integer ID.")
|
|
require(identity not in result, f"{label}: duplicate ID {identity}.")
|
|
result[identity] = item
|
|
return result
|
|
|
|
|
|
def inspect_native(path: Path) -> dict:
|
|
with path.open("rb") as stream:
|
|
data = stream.read(MAX_ARCHIVE_BYTES + 1)
|
|
require(len(data) <= MAX_ARCHIVE_BYTES, "Native file exceeds 64 MiB inspection budget.")
|
|
snapshot = io.BytesIO(data)
|
|
require(zipfile.is_zipfile(snapshot), "Expected a ZIP-based .solidcraft native container.")
|
|
with zipfile.ZipFile(snapshot) as archive:
|
|
entries = archive.infolist()
|
|
require(0 < len(entries) <= 1024, "Invalid or excessive ZIP entry count.")
|
|
names = [item.filename for item in entries]
|
|
require(len(names) == len(set(names)), "Duplicate ZIP entry names.")
|
|
require("document.json" in names, "Native container lacks document.json.")
|
|
require(sum(item.file_size for item in entries) <= 512 * 1024 * 1024,
|
|
"Native container exceeds expanded inspection budget.")
|
|
for item in entries:
|
|
name = PurePosixPath(item.filename)
|
|
require(not name.is_absolute() and ".." not in name.parts and "\\" not in item.filename,
|
|
"Unsafe ZIP entry path.")
|
|
require(not item.flag_bits & 1, "Encrypted ZIP entries are unsupported.")
|
|
entry = archive.getinfo("document.json")
|
|
require(entry.file_size <= MAX_DOCUMENT_BYTES, "Native document exceeds inspection budget.")
|
|
document = decode(archive.read(entry))
|
|
require(re.fullmatch(r"solidcraft/[1-9][0-9]*", document.get("format", "")) is not None,
|
|
"Unknown native document format tag.")
|
|
require(document.get("units") == "mm", "This demo requires native millimeter dimensions.")
|
|
components = index_records(document.get("components", []), "components")
|
|
occurrences = index_records(document.get("occurrences", []), "occurrences")
|
|
features = index_records(document.get("features", []), "features")
|
|
assembly = document.get("assembly", {})
|
|
require(isinstance(assembly, dict), "Invalid native assembly object.")
|
|
joints = index_records(assembly.get("joints", []), "joints")
|
|
studies = index_records(assembly.get("studies", []), "studies")
|
|
links = assembly.get("links", [])
|
|
require(isinstance(links, list) and len(links) <= MAX_RECORDS, "Invalid motion link list.")
|
|
component_ids, occurrence_ids = set(components) | {0}, set(occurrences) | {0}
|
|
for component in components.values():
|
|
require(component.get("parent", 0) in component_ids, "Unknown parent component.")
|
|
for occurrence in occurrences.values():
|
|
require(occurrence.get("component") in components, "Unknown occurrence component.")
|
|
require(occurrence.get("parent", 0) in component_ids, "Unknown placement parent component.")
|
|
require(type(occurrence.get("grounded", False)) is bool, "Invalid grounded flag.")
|
|
adjacency = defaultdict(set)
|
|
for joint in joints.values():
|
|
require(joint.get("kind") in JOINT_VALUES, "Unrecognized joint type; extend the inspector explicitly.")
|
|
a, b = joint.get("a", {}), joint.get("b", {})
|
|
require(isinstance(a, dict) and isinstance(b, dict), "Invalid joint origins.")
|
|
a, b = a.get("occurrence"), b.get("occurrence")
|
|
require(type(a) is int and type(b) is int and a != b
|
|
and a in occurrence_ids and b in occurrence_ids, "Invalid joint occurrence reference.")
|
|
if not joint.get("suppressed", False):
|
|
adjacency[a].add(b)
|
|
adjacency[b].add(a)
|
|
units = JOINT_VALUES[joint["kind"]]
|
|
values, limits = joint.get("values", []), joint.get("limits", [])
|
|
require(isinstance(values, list) and len(values) <= len(units)
|
|
and all(number(x) for x in values), "Invalid joint values.")
|
|
require(isinstance(limits, list) and len(limits) <= len(units), "Invalid joint limits.")
|
|
for limit in limits:
|
|
require(limit is None or (isinstance(limit, list) and len(limit) == 2
|
|
and all(number(x) for x in limit) and limit[0] <= limit[1]), "Invalid joint limit interval.")
|
|
for link in links:
|
|
require(isinstance(link, dict) and link.get("a") in joints and link.get("b") in joints,
|
|
"Motion link references an unknown joint.")
|
|
for study in studies.values():
|
|
keys = study.get("keys", [])
|
|
require(isinstance(keys, list) and len(keys) <= MAX_RECORDS, "Invalid motion study keys.")
|
|
for key in keys:
|
|
require(isinstance(key, dict) and key.get("joint") in joints, "Study references an unknown joint.")
|
|
grounded = {0} | {key for key, item in occurrences.items() if item.get("grounded", False)}
|
|
reachable, queue = set(grounded), deque(grounded)
|
|
while queue:
|
|
for following in adjacency[queue.popleft()] - reachable:
|
|
reachable.add(following)
|
|
queue.append(following)
|
|
declared_names = set()
|
|
for feature in features.values():
|
|
if not feature.get("suppressed", False):
|
|
names = feature.get("body_names", [])
|
|
require(isinstance(names, list) and all(isinstance(x, str) for x in names), "Invalid declared body names.")
|
|
declared_names.update(names)
|
|
return {
|
|
"schema_version": "0.1.0", "status": "inspected_container_only",
|
|
"sha256": hashlib.sha256(data).hexdigest(), "size_bytes": len(data),
|
|
"format": document["format"], "units": document["units"], "up_axis": "+Z",
|
|
"name": document.get("name"),
|
|
"counts": {"components_excluding_root": len(components), "occurrences": len(occurrences),
|
|
"history_features": len(features), "joints": len(joints), "motion_links": len(links),
|
|
"motion_studies": len(studies), "joints_by_kind": dict(Counter(j["kind"] for j in joints.values()))},
|
|
"components": list(components.values()), "occurrences": list(occurrences.values()),
|
|
"joints": list(joints.values()), "motion_links": links, "motion_studies": list(studies.values()),
|
|
"declared_body_names": sorted(declared_names),
|
|
"joint_graph": {"grounded_occurrence_ids": sorted(grounded),
|
|
"not_connected_to_ground_by_unsuppressed_joints": sorted(set(occurrences) - reachable),
|
|
"scope": "Undirected joint-edge reachability only; ignores nested placement inheritance and is not a DOF, closure, collision or solvability result."},
|
|
"limitations": ["Native joint values, limits and study keys remain radians/mm; command angles use degrees.",
|
|
"Declared body names are feature metadata, not proof that a body survives evaluated history.",
|
|
"No geometry evaluation, world bounds, native migration, motion playback or rendering was performed.",
|
|
"Shape/count matches do not establish that this is the author's improved SELENE variant."],
|
|
}
|
|
|
|
|
|
def binding_template(model: Path) -> dict:
|
|
native = inspect_native(model)
|
|
roles = [role for role in read_json(PACKAGE / "scenes/roles.json")["items"]
|
|
if role.get("kind") == "appearance" and role.get("owner") == "subject"
|
|
and role.get("opaque_proxy_allowed") is True]
|
|
return {
|
|
"schema_version": "0.1.0", "language": "en", "status": "unreviewed_template",
|
|
"source_sha256": native["sha256"], "review_scope": "opaque_body_subset_only",
|
|
"review": {"reviewer": None, "date": None, "evaluated_body_targets_checked": False,
|
|
"shared_definition_scope_checked": False,
|
|
"physical_materials_preserved": False, "opaque_approximations_accepted": False},
|
|
"assignments": [{"role": role["id"], "status": "unresolved", "recipe_id": None,
|
|
"override_reason": None,
|
|
"bodies": [], "note": "Select exact evaluated body names on the admitted improved source; no automatic v7 mapping."}
|
|
for role in roles],
|
|
}
|
|
|
|
|
|
def compile_overlay(model: Path, lock_path: Path, bindings_path: Path) -> dict:
|
|
native, lock, bindings = inspect_native(model), read_json(lock_path), read_json(bindings_path)
|
|
source = lock.get("active_source", {})
|
|
require(source.get("status") == "pinned_native", "Improved native source is not admitted: source-lock status must be pinned_native.")
|
|
for field in ("sha256", "size_bytes", "format", "units", "up_axis"):
|
|
require(source.get(field) == native[field], f"Source-lock mismatch: {field}.")
|
|
for old in lock.get("legacy_sources", []):
|
|
require(old.get("sha256") != native["sha256"], "Historical Rover v7 cannot substitute for the improved showcase source.")
|
|
require(source.get("variant") == "SELENE-showcase", "Unexpected active variant.")
|
|
provenance_url = source.get("download_url")
|
|
if not provenance_url and source.get("repository") and source.get("path"):
|
|
require(re.fullmatch(r"[0-9a-f]{40}", source.get("commit") or "") is not None, "Repository source requires a pinned commit.")
|
|
provenance_url = "https://github.com/" + source["repository"]
|
|
require(isinstance(provenance_url, str) and provenance_url.startswith("https://"), "Pinned source requires an HTTPS provenance location.")
|
|
admission = lock.get("admission_review", {})
|
|
require(admission.get("variant_identity_confirmed") is True
|
|
and admission.get("license_and_attribution_reviewed") is True
|
|
and isinstance(admission.get("reviewer"), str) and bool(admission["reviewer"].strip()),
|
|
"Source identity and attribution need a recorded review.")
|
|
require(isinstance(admission.get("evidence_url"), str) and admission["evidence_url"].startswith("https://")
|
|
and isinstance(admission.get("review_date"), str)
|
|
and re.fullmatch(r"\d{4}-\d{2}-\d{2}", admission["review_date"]) is not None,
|
|
"Source admission needs a dated provenance review with an HTTPS evidence URL.")
|
|
license_review = lock.get("license_review", {})
|
|
require(license_review.get("status") == "reviewed"
|
|
and isinstance(license_review.get("license_expression"), str)
|
|
and bool(license_review["license_expression"].strip())
|
|
and isinstance(license_review.get("notices"), list),
|
|
"Complete the file-specific license expression and notice inventory before source admission.")
|
|
require(int(native["format"].split("/")[1]) <= 21,
|
|
"Source format exceeds the inspected render integration contract (21); revalidate the adapter against the actual executor.")
|
|
require(bindings.get("source_sha256") == native["sha256"], "Bindings belong to a different native revision.")
|
|
review = bindings.get("review", {})
|
|
require(bindings.get("status") == "reviewed" and isinstance(review.get("reviewer"), str)
|
|
and bool(review["reviewer"].strip()) and isinstance(review.get("date"), str)
|
|
and re.fullmatch(r"\d{4}-\d{2}-\d{2}", review["date"]) is not None,
|
|
"Bindings need a named, dated review.")
|
|
for key in ("evaluated_body_targets_checked", "shared_definition_scope_checked",
|
|
"physical_materials_preserved", "opaque_approximations_accepted"):
|
|
require(review.get(key) is True, f"Binding review missing: {key}.")
|
|
recipes = {item["id"]: item for item in read_json(PACKAGE / "materials/appearance-pack.json")["items"]}
|
|
roles = {item["id"]: item for item in read_json(PACKAGE / "scenes/roles.json")["items"]}
|
|
assignments = bindings.get("assignments", [])
|
|
require(isinstance(assignments, list) and 0 < len(assignments) <= len(roles), "Invalid assignment collection.")
|
|
commands, used_bodies, used_roles = [], set(), set()
|
|
declared = set(native["declared_body_names"])
|
|
for assignment in assignments:
|
|
require(isinstance(assignment, dict), "Invalid assignment object.")
|
|
role = assignment.get("role")
|
|
require(role in roles and role not in used_roles, "Unknown or repeated appearance role.")
|
|
used_roles.add(role)
|
|
if assignment.get("status") == "omitted":
|
|
require(isinstance(assignment.get("note"), str) and bool(assignment["note"].strip())
|
|
and not assignment.get("bodies"), "Omitted role requires a reason and no targets.")
|
|
continue
|
|
require(assignment.get("status") == "reviewed", f"Unresolved role: {role}.")
|
|
require(roles[role].get("kind") == "appearance" and roles[role].get("owner") == "subject"
|
|
and roles[role].get("opaque_proxy_allowed") is True,
|
|
"The opaque native-body adapter cannot bind framing, terrain, layers, light sources or optical/emissive roles.")
|
|
recipe = recipes.get(assignment.get("recipe_id"))
|
|
require(recipe is not None, f"Unknown appearance recipe for {role}.")
|
|
if roles[role].get("candidate_material_id") not in recipe.get("source_catalog_ids", []):
|
|
require(isinstance(assignment.get("override_reason"), str)
|
|
and bool(assignment["override_reason"].strip()),
|
|
"A different material concept requires a recorded appearance-override reason.")
|
|
bodies = assignment.get("bodies")
|
|
require(isinstance(bodies, list) and 0 < len(bodies) <= 10_000
|
|
and all(isinstance(x, str) and x in declared for x in bodies),
|
|
"Targets must be exact body names declared in this native source and reviewed in the evaluated app.")
|
|
require(len(set(bodies)) == len(bodies) and not used_bodies.intersection(bodies),
|
|
"Overlapping body assignments would replace a previous appearance.")
|
|
used_bodies.update(bodies)
|
|
parameters = dict(recipe["baseline_projection"]["runtime_parameters"])
|
|
require(set(parameters) == {"appearance", "color", "opacity", "pbr"}
|
|
and number(parameters["opacity"]) and parameters["opacity"] == 1,
|
|
"Only the inspected opaque PBR parameter contract may be emitted.")
|
|
require(isinstance(parameters["appearance"], str) and bool(parameters["appearance"].strip())
|
|
and len(parameters["appearance"].encode("utf-8")) <= 128,
|
|
"Appearance label must be nonempty and fit the prepared pack's 128-byte bound.")
|
|
require(isinstance(parameters["color"], str)
|
|
and re.fullmatch(r"#[0-9a-fA-F]{6}", parameters["color"]) is not None,
|
|
"Prepared appearance colors must be #rrggbb sRGB8 strings.")
|
|
pbr = parameters["pbr"]
|
|
require(isinstance(pbr, dict) and set(pbr) == {"metallic", "roughness", "dielectric_ior"}
|
|
and all(number(x) for x in pbr.values()) and 0 <= pbr["metallic"] <= 1
|
|
and 0.045 <= pbr["roughness"] <= 1 and 1 <= pbr["dielectric_ior"] <= 3,
|
|
"Appearance PBR fields exceed the inspected runtime contract.")
|
|
parameters["bodies"] = bodies
|
|
commands.append({"command": "appearance.assign", "params": parameters})
|
|
require(bool(commands), "No reviewed opaque body assignments to compile.")
|
|
# A command script is intentionally only the engine's documented envelope.
|
|
# The native model and reviewed bindings retain provenance alongside it.
|
|
return {"commands": commands}
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
sub = parser.add_subparsers(dest="operation", required=True)
|
|
for name, help_text in (("inspect", "Read native identity and assembly metadata without evaluating geometry."),
|
|
("template", "Write an unreviewed role-binding template for a candidate native file."),
|
|
("compile", "Compile only explicitly reviewed opaque body assignments after source admission.")):
|
|
command = sub.add_parser(name, help=help_text)
|
|
command.add_argument("--model", type=Path, required=True)
|
|
command.add_argument("--out", type=Path, required=True)
|
|
if name == "compile":
|
|
command.add_argument("--lock", type=Path, default=PACKAGE / "source-lock.json")
|
|
command.add_argument("--bindings", type=Path, required=True)
|
|
args = parser.parse_args()
|
|
try:
|
|
if args.operation == "inspect":
|
|
result = inspect_native(args.model)
|
|
elif args.operation == "template":
|
|
result = binding_template(args.model)
|
|
else:
|
|
result = compile_overlay(args.model, args.lock, args.bindings)
|
|
write_json(args.out, result)
|
|
print(f"Wrote {args.out}. Native source unchanged; no engine commands executed.")
|
|
return 0
|
|
except (OSError, ValueError, TypeError, KeyError, AttributeError, OverflowError,
|
|
RecursionError, zipfile.BadZipFile, NotImplementedError) as exc:
|
|
print(f"Preparation blocked: {exc}", file=sys.stderr)
|
|
return 2
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|