"""Prepare a bounded mission region from an existing Gaussian Pipeline package. Uses the installed SplatTransform, preserves LOD0 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 prepare_project(client, run, state, episode, job, pulse, isaac): 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"] 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 package["artifacts"] 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 package["artifacts"]: 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") # Keep 12 m of surrounding visual context in every direction. A saved route # bounds the adaptation. Retain LOD0 and all SH bands without a count ceiling. points = run["plan"]["points"] prior = run["plan"].get("prepared_route") if prior: # A curved A/B route needs its entire preview, not just its endpoints. # Unselected graph branches must not force the whole city into RTX. # Long detours outside this visual region require spatial streaming; # the graph never substitutes for live support in such an area. points = points + [{"position": p} for p in prior["preview_xyz"]] xyz = [[p["position"][0], p["position"][2], -p["position"][1]] for p in points] bounds = [min(p[i] for p in xyz) - 12 for i in range(3)] + [ max(p[i] for p in xyz) + 12 for i in range(3) ] key = hashlib.sha256( json.dumps( {"world": world["sha256"], "bounds": bounds, "adapter": digest(Path(__file__)), "region_adapter": digest(Path(__file__).with_name("route_region.py"))}, 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 and crop 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", "0", str(visual), "-r", "0,0,180", "-r", ",".join(map(str, scene["visual_rotation"])), "-B", ",".join(map(str, bounds)), "-r", "0,0,180", str(temporary), ] commands = [command] filtered = temporary.with_suffix(".region.ply") if prior: region = episode / "visual-region.json" write_json(region, {"route_xz": [[p[0],-p[1]] for p in prior["preview_xyz"]], "radius_m": 12, "authority": "visual-context-only"}) commands.append([str(isaac / "python.bat"), str(Path(__file__).with_name("route_region.py")), "--source",str(temporary),"--output",str(filtered),"--region",str(region)]) 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) if prior: filtered.replace(temporary) 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 mission region is empty") temporary.replace(output) write_json( receipt, { "sha256": digest(output), "gaussian_count": count, "lod": 0, "bounds_y_up": bounds, "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_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