Files

242 lines
9.4 KiB
Python

"""Prepare the complete visual scene from an existing Gaussian Pipeline package.
Uses the installed SplatTransform, preserves the selected source LOD and SH, and reuses verified
Worker artifacts. The local editor and Isaac share the same collider bytes and
saved calibration; this is format adaptation, not another reconstruction.
"""
import hashlib
import json
import re
import shutil
import subprocess
import time
from pathlib import Path
from urllib.parse import quote
from local_state import write_json
from scene_capacity import scene_diagnostics
def digest(path):
with path.open("rb") as stream:
return hashlib.file_digest(stream, "sha256").hexdigest()
def project_members(package, lod):
required = {package["visual_path"], package["collision_path"]}
# SplatTransform 3.4 opens the multi-LOD source before applying selectLod.
# Its layout comes from the first LOD-0 chunk, including that chunk's
# textures. A cold package must contain this bootstrap dependency even
# when output uses another LOD; it does not add LOD-0 splats to the output.
return [item for item in package["artifacts"] if (
item["logical_path"] in required or
item["logical_path"].startswith((f"streamed/{lod}_", "streamed/0_0/", "streamed/env/")))]
def prepare_project(client, run, state, episode, job, pulse, isaac, *, lod=0):
if type(lod) is not int or not 0 <= lod <= 6:
raise ValueError("Invalid source LOD")
world = run["world"]
package = client.request("/worker/worlds/" + world["world_id"] + "/project-assets")
if package["world_sha256"] != world["sha256"]:
raise ValueError("Project changed after mission admission")
pid, provider_job = package["project_id"], package["provider_job_id"]
members = project_members(package, lod)
if not re.fullmatch(r"sim-[a-f0-9]{32}", pid) or not re.fullmatch(
r"gsp-[0-9]{14}-[a-f0-9]{8}", provider_job
):
raise ValueError("Invalid Gaussian package identity")
native = Path("D:/NDC_GAUSSIAN_PIPELINE/data/jobs") / provider_job / "output"
root = state / "project-packages" / world["sha256"]
root.mkdir(parents=True, exist_ok=True)
required = sum(
item["byte_length"]
for item in members
if not (root / item["logical_path"]).is_file()
)
if shutil.disk_usage(root).free < required + 4 * 1024**3:
raise RuntimeError("Недостаточно места на Worker для подготовки локации.")
# A filesystem package is needed by the stock streamed-SOG reader. Reuse
# local verified bytes without re-encoding. Keep an owned immutable copy for the run.
for item in members:
name = item["logical_path"]
if (
not re.fullmatch(r"[A-Za-z0-9_. /-]+", name)
or ".." in Path(name).parts
or Path(name).is_absolute()
):
raise ValueError("Invalid package member")
target = root / name
if (
target.is_file()
and target.stat().st_size == item["byte_length"]
and digest(target) == item["sha256"]
):
continue
pulse()
target.parent.mkdir(parents=True, exist_ok=True)
source = native / name
if (
source.is_file()
and source.stat().st_size == item["byte_length"]
and digest(source) == item["sha256"]
):
temporary = target.with_suffix(target.suffix + ".part")
shutil.copyfile(source, temporary)
temporary.replace(target)
else:
client.download_asset(
"/api/v1/simulation-worlds/projects/" + pid + "/artifacts/" + quote(name, safe="/"),
item,
target,
pulse=pulse,
)
scene = world["local_scene"]
visual = root / package["visual_path"]
collider = root / package["collision_path"]
if not visual.is_file() or not collider.is_file():
raise ValueError("Incomplete project scene")
# The route is guidance, not permission to remove the rest of the world.
# Adapt the complete selected source LOD and preserve every SH coefficient.
key = hashlib.sha256(
json.dumps(
{"world": world["sha256"], "coverage": "complete-source", "lod": lod, "adapter": digest(Path(__file__))},
sort_keys=True,
).encode()
).hexdigest()
output = root / (key + ".ply")
receipt = output.with_suffix(".json")
if not (
receipt.exists()
and output.exists()
and json.loads(receipt.read_text())["sha256"] == digest(output)
):
converter = (
state.parent
/ "tools/splat-transform-3.4.0/node_modules/@playcanvas/splat-transform/bin/cli.mjs"
)
node = shutil.which("node")
if not node or not converter.exists():
raise RuntimeError("Installed SOG converter is unavailable")
temporary = root / (key + ".part.ply")
# SplatTransform uses Rz(180) for PLY/SOG input/output conventions.
# Work in the calibrated PlayCanvas Y-up frame, then retain
# that frame in the output PLY. Isaac applies the declared Rx(90).
command = [
node,
"--max-old-space-size=8192",
str(converter),
"--gpu",
"cpu",
"--max-workers",
"4",
"-w",
"--select-lod",
str(lod),
str(visual),
"-r",
"0,0,180",
"-r",
",".join(map(str, scene["visual_rotation"])),
"-r",
"0,0,180",
str(temporary),
]
commands = [command]
with (episode / "project-preparation.log").open("wb") as log:
for command in commands:
process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT)
job.assign(process)
deadline = time.monotonic() + 600
try:
while process.poll() is None:
pulse()
if time.monotonic() > deadline:
raise TimeoutError("Project preparation timed out")
time.sleep(1)
if process.returncode:
raise RuntimeError("SOG adaptation failed; inspect Worker evidence")
finally:
if process.poll() is None:
from worker import terminate_episode
terminate_episode(process)
with temporary.open("rb") as f:
header = f.read(65536).split(b"end_header", 1)[0].decode("ascii")
count = int(re.search(r"element vertex (\d+)", header)[1])
if count <= 0:
raise ValueError("Prepared visual scene is empty")
temporary.replace(output)
write_json(
receipt,
{
"sha256": digest(output),
"gaussian_count": count,
"lod": lod,
"coverage": "complete-source",
"spatially_cropped": False,
"source_sha256": world["sha256"],
"converter": "splat-transform-3.4.0",
"decimated": False,
},
)
# Capacity is evidence only, never an admission gate or a count ceiling.
count = json.loads(receipt.read_text())["gaussian_count"]
write_json(episode / "scene-capacity.json", {**scene_diagnostics(count, output.stat().st_size),
"source_lod": lod, "coverage": "complete-source", "spatially_cropped": False})
source_collider_sha256 = digest(collider)
decoded = root / (source_collider_sha256 + ".decoded.glb")
decoder = Path(__file__).with_name("decode_collision.cjs")
decoded_receipt = decoded.with_suffix(".json")
valid = (
decoded.exists()
and decoded_receipt.exists()
and json.loads(decoded_receipt.read_text()).get("decoder_sha256") == digest(decoder)
and json.loads(decoded_receipt.read_text()).get("sha256") == digest(decoded)
)
if not valid:
temporary = decoded.with_suffix(".part.glb")
process = subprocess.Popen(
[
shutil.which("node"),
str(Path(__file__).with_name("decode_collision.cjs")),
str(collider),
str(temporary),
],
stdout=subprocess.DEVNULL,
)
job.assign(process)
try:
process.wait(timeout=45)
if process.returncode:
raise RuntimeError("Collision decompression failed")
finally:
if process.poll() is None:
from worker import terminate_episode
terminate_episode(process)
temporary.replace(decoded)
write_json(
decoded_receipt,
{
"sha256": digest(decoded),
"decoder_sha256": digest(decoder),
"source_sha256": source_collider_sha256,
},
)
collider = decoded
terrain = root / "terrain.json"
write_json(
terrain,
{
"generator": "paired-source",
"source_collider_sha256": source_collider_sha256,
"source_sha256": world["sha256"],
"settings": world["settings"],
"collider": str(collider),
"collider_sha256": digest(collider),
"collision_rotation": scene["collision_rotation"],
},
)
return output, terrain