Files
NODEDC_MISSION_CORE/simulation/ai-polygon/run_realtime.py
T

830 lines
40 KiB
Python

"""Native Worker-local physics/render/camera loop, independent of Core and AI latency."""
import argparse
import json
import math
import os
import shutil
import sys
import time
import traceback
from datetime import UTC, datetime
from pathlib import Path
from episode_failure import consume_pipeline_failure
from scheduling_policy import build_scheduling_policy
from local_state import StateChannel, read_json, write_json
from motion_control import RoverMotionControl
from observer_camera import ObserverCamera, SmoothView
from qualification_scenarios import QualificationScenario, scenario_from_run
from realtime_ai import LatestInference
from rover_profile import create_rover, open_drive
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--run", type=Path, required=True)
parser.add_argument("--source", type=Path, required=True)
parser.add_argument("--stream-address", required=True)
parser.add_argument("--no-stream", action="store_true", help="Qualify sensors without WebRTC")
args, _ = parser.parse_known_args()
root = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(root / "src"))
run = read_json(args.run)
scenario_document = scenario_from_run(run)
challenge = QualificationScenario(scenario_document) if scenario_document else None
settings = run["world"]["settings"]
directory = args.run.parent
channel = StateChannel(directory)
result = {"outcome": "failed", "message": "Симуляция не завершена."}
app = ai = None
mounted = None
physics_callbacks = []
SENSOR_HZ = 10
def startup_phase(phase):
record = {"phase": phase, "utc": datetime.now(UTC).isoformat(), "monotonic": time.monotonic()}
write_json(directory / "startup.json", record)
print(json.dumps({"startup": record}), flush=True)
try:
from k1link.simulation.ai_polygon.run_inputs import resolve_run_inputs
from k1link.simulation.ai_polygon.run_robot import resolve_run_robot
robot = resolve_run_robot(run)
execution_inputs = resolve_run_inputs(run, robot)
write_json(directory / "execution-inputs.json", execution_inputs)
rig = execution_inputs["sensors"]
sensor_width, sensor_height = rig["image_size"]
SENSOR_HZ = rig["capture_hz"]
max_speed = execution_inputs["behavior"]["max_speed_mps"]
PROFILE = robot["physics"]
CONTROL_PROFILE = robot["control"]
startup_phase("native-runtime")
from isaacsim import SimulationApp
from native_experience import prepare_experience
app = SimulationApp(
{
"headless": True,
"hide_ui": True,
"multi_gpu": False,
"width": 1280,
"height": 720,
"window_width": 1280,
"window_height": 720,
"renderer": "RaytracedLighting",
"display_options": 0,
"extra_args": [
"--/app/window/hideUi=true",
"--/persistent/app/viewport/noPadding=true",
"--/app/viewport/defaults/hud/cameraSpeed/visible=false",
"--/app/viewport/defaults/hud/toastMessage/visible=false",
"--/exts/omni.kit.viewport.window/startup/cameraManipulator/enabled=false",
"--/exts/omni.kit.viewport.window/startup/selectionManipulator/enabled=false",
"--/app/player/useFixedTimeStepping=false",
"--/app/runLoops/main/manualModeEnabled=false",
"--/exts/isaacsim.core.throttling/enable_manualmode=false",
],
},
experience=prepare_experience(os.environ["EXP_PATH"], directory / "native-experience"),
)
import carb.settings
import numpy as np
import omni.kit.app
import omni.replicator.core as rep
import omni.timeline
import omni.usd
from isaacsim.core.experimental.utils.app import enable_extension
from isaacsim.core.simulation_manager import SimulationEvent, SimulationManager
from navigation.footprint import FRAME_DEADLINE_SECONDS
from navigation_client import ComposedInference
from omni.kit.loop import _loop as omni_loop
from omni.kit.viewport.utility import get_active_viewport
from pxr import Gf, Usd, UsdGeom, UsdLux, UsdPhysics
from terrain import RangeSensor, install_terrain
from k1link.simulation.ai_polygon.mission_policy import inclination
startup_phase("stream-and-gaussian-runtime")
config = carb.settings.get_settings()
# Section planes are preview-only and never inherited by an evaluation.
config.set_bool("/rtx/sectionPlane/enabled", False)
prefix = "/exts/omni.kit.livestream.app/primaryStream/"
for key, value in {
"publicIp": args.stream_address,
"signalPort": 49100,
"streamPort": 47998,
"targetFps": 30,
"enableEventTracing": False,
}.items():
config.set(prefix + key, value)
if not args.no_stream:
enable_extension("omni.kit.livestream.app")
enable_extension("omni.kit.converter.gsplat")
from usd_convert_gsplat import read_ply
from gaussian_usd import write_gaussian_usd
from gaussian_cache import file_sha256, prepare_gaussian
gaussian_recipe = dict(reader=file_sha256(sys.modules[read_ply.__module__].__file__),
writer=file_sha256(sys.modules[write_gaussian_usd.__module__].__file__),
runtime=dict(kit=omni.kit.app.get_app().get_build_version(),
usd=list(Usd.GetVersion()), python=sys.version, numpy=np.__version__),
output_schema="missioncore.gaussian-usd/v1")
converted, gaussian_receipt = prepare_gaussian(args.source,
lambda source, temporary: write_gaussian_usd(read_ply(str(source)), temporary,
progress=lambda done, total: startup_phase(f"gaussian-conversion:{done}/{total}")),
gaussian_recipe)
write_json(directory / "gaussian-visual.json", gaussian_receipt)
stage = omni.usd.get_context().get_stage()
UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z)
UsdGeom.SetStageMetersPerUnit(stage, 1)
visual = UsdGeom.Xform.Define(stage, "/World/Scan")
visual.AddRotateXYZOp().Set(Gf.Vec3f(*settings["rotation_degrees"]))
visual.AddScaleOp().Set(Gf.Vec3f(settings["meters_per_unit"]))
stage.DefinePrim("/World/Scan/Gaussians").GetReferences().AddReference(str(converted))
startup_phase("terrain")
wheel_center_z, terrain_record = install_terrain(stage, run["terrain_manifest"], run["world"],
physics_profile=robot["physics"])
write_json(directory / "terrain.json", terrain_record)
obstacle = None
if challenge and scenario_document["obstacle"] is not None:
from qualification_scene import ObstacleFixture
obstacle = ObstacleFixture(stage, scenario_document["obstacle"], PROFILE,
physics_profile=robot["physics"])
UsdLux.DomeLight.Define(stage, "/World/Light").CreateIntensityAttr(500)
startup_phase("rover-model")
from rover_visual import prepare_visual
asset, visual_receipt = prepare_visual(app, robot, directory.parent.parent / "assets/robots")
write_json(directory / "robot-visual.json", visual_receipt)
create_rover(
stage,
[*settings["spawn_xy"], wheel_center_z],
settings["heading_degrees"],
terrain_record["initial_ground_normal"],
visual_asset=asset,
document=robot,
)
write_json(directory / "robot-profile.json", robot)
if run.get("rover_configuration") is not None:
mass_api = UsdPhysics.MassAPI(stage.GetPrimAtPath("/World/Rover/chassis"))
write_json(
directory / "robot-physics.json",
{
"configuration_sha256": run["rover_configuration"]["sha256"],
"effective_robot_sha256": robot["sha256"],
"mass_kg": float(mass_api.GetMassAttr().Get()),
"centre_of_mass_local_m": list(mass_api.GetCenterOfMassAttr().Get()),
"diagonal_inertia_kg_m2": list(mass_api.GetDiagonalInertiaAttr().Get()),
"requested_max_speed_mps": max_speed,
},
)
write_json(directory / "motion-control.json", CONTROL_PROFILE)
write_json(
directory / "sensor-clock.json",
{
"requested_hz": SENSOR_HZ,
"maximum_pending_inference_frames": 1,
"frame_deadline_seconds": FRAME_DEADLINE_SECONDS,
"ray_packet": "world-mounts-indexed-endpoints-organized-ranges-v2",
},
)
startup_phase("cameras")
def camera(path, aspect, focal_length=24, aperture=36):
value = UsdGeom.Camera.Define(stage, path)
value.CreateFocalLengthAttr(focal_length)
value.CreateHorizontalApertureAttr(aperture)
value.CreateVerticalApertureAttr(aperture / aspect)
value.CreateClippingRangeAttr(Gf.Vec2f(0.05, 1000))
return value, value.AddTranslateOp(), value.AddOrientOp()
if "mounts" in rig:
from mounted_sensors import MountedRange, MountedSensors
mounted = MountedSensors(stage, rig, PROFILE["body_contact_height_m"])
mounted.update(
UsdGeom.Xformable(
stage.GetPrimAtPath("/World/Rover/chassis")
).ComputeLocalToWorldTransform(Usd.TimeCode.Default())
)
write_json(directory / "sensor-mounts.json", rig["mounts"])
else:
sensor, sensor_pos, sensor_rot = camera(
"/World/Sensor",
sensor_width / sensor_height,
rig["focal_length_mm"],
rig["horizontal_aperture_mm"],
)
focal_pixels = sensor_width * rig["focal_length_mm"] / rig["horizontal_aperture_mm"]
observer, observer_pos, observer_rot = camera("/World/Observer", 16 / 9)
if mounted is None:
product = rep.create.render_product(str(sensor.GetPath()), (sensor_width, sensor_height))
annotator = rep.AnnotatorRegistry.get_annotator("rgb")
annotator.attach(product)
config.set("/omni/replicator/captureOnPlay", True)
viewport = get_active_viewport()
if viewport is None:
raise RuntimeError("Streaming viewport is unavailable")
# These HUD options are independent of display_options in Isaac 6.1.
# Metrics Assembler draws the bottom-left units badge. Set the live path
# as well as its persisted default: the layer subscribes to the live path.
for hud in (
"cameraSpeed",
"toastMessage",
"renderFPS",
"renderResolution",
"deviceMemory",
"hostMemory",
"metrics/assembler",
):
config.set_bool(f"/persistent/app/viewport/{viewport.id}/hud/{hud}/visible", False)
config.set_bool(f"/app/viewport/{viewport.id}/hud/{hud}/visible", False)
viewport.camera_path = str(observer.GetPath())
viewport.set_texture_resolution((1280, 720))
# Initialise the final camera before the first rendered frames. Starting
# WebRTC with an uninitialised observer and an already paused timeline can
# leave the native stream without its first image/offer.
initial = Gf.Vec3d(*settings["spawn_xy"], wheel_center_z + 0.12)
heading = math.radians(settings["heading_degrees"])
initial_eye = initial + Gf.Vec3d(-math.cos(heading) * 2.5, -math.sin(heading) * 2.5, 1.5)
observer_pos.Set(initial_eye)
observer_rot.Set(
Gf.Quatf(
Gf.Matrix4d()
.SetLookAt(initial_eye, initial + Gf.Vec3d(0.1, 0, 0.2), Gf.Vec3d(0, 0, 1))
.GetInverse()
.ExtractRotationQuat()
)
)
startup_phase("physics-setup")
SimulationManager.setup_simulation(dt=1 / 60, device="cpu")
timeline = omni.timeline.get_timeline_interface()
# Render rate and physics rate are separate. Physics steps follow elapsed time.
config.set("/app/player/useFixedTimeStepping", False)
config.set("/exts/isaacsim.core.throttling/enable_manualmode", False)
omni_loop.acquire_loop_interface().set_manual_mode(False)
timeline.set_play_every_frame(False)
config.set("/persistent/simulation/minFrameRate", 1)
config.set("/app/runLoops/main/rateLimitEnabled", True)
config.set("/app/runLoops/main/rateLimitFrequency", 30)
startup_phase("initial-render-and-contact")
timeline.play()
for _ in range(30):
app.update()
drive = open_drive(
contact_filter_paths=["/World/Terrain"] + ([obstacle.path] if obstacle else []),
document=robot,
)
body = drive.body
def body_transform():
positions, orientations = body.get_world_poses()
position, orientation = positions.numpy()[0], orientations.numpy()[0]
transform = Gf.Matrix4d(1)
transform.SetRotate(Gf.Quatd(float(orientation[0]), Gf.Vec3d(*map(float, orientation[1:]))))
transform.SetTranslateOnly(Gf.Vec3d(*map(float, position)))
return transform
if mounted:
# RTX must render the installed sensor pose before any observation is
# published. Otherwise the initial image still belongs to the camera's
# construction pose and can poison causal semantics at rover poses.
for _ in range(8):
mounted.update(body_transform())
app.update()
settled = body_transform().ExtractTranslation()
write_json(
directory / "initial-contact.json",
{
"pose": list(settled),
"expected_xy": settings["spawn_xy"],
"spawn_contact_z": terrain_record["initial_contact_z"],
},
)
if math.hypot(settled[0] - settings["spawn_xy"][0], settled[1] - settings["spawn_xy"][1]) > 0.2:
raise RuntimeError("Rover start is unstable on this reconstructed surface")
timeline.pause()
app.update()
startup_phase("ready")
baseline = SimulationManager.get_num_physics_steps()
range_sensor = MountedRange(rig, PROFILE["body_contact_height_m"]) if mounted else RangeSensor()
from route_view import RouteView
from terrain_picker import TerrainPicker
route_view = RouteView(run, TerrainPicker(stage))
from k1link.simulation.ai_polygon.route_mission import mission_for_inputs
# The episode owns the mission. Reconnecting a failed model client must not
# rewind its route cursor, recovery budget or latched terminal condition.
mission = mission_for_inputs(execution_inputs)
continuous = rig["schema_version"] == "missioncore.simulation-sensor-rig/v4"
scheduling = build_scheduling_policy(continuous=continuous, physics_dt=1/60,
capture_hz=SENSOR_HZ, main_loop_hz=30)
config.set("/persistent/simulation/minFrameRate",
scheduling["min_simulation_frame_rate_hz"])
if config.get("/persistent/simulation/minFrameRate") != scheduling["min_simulation_frame_rate_hz"]:
raise RuntimeError("Native catch-up setting differs from scheduling policy")
write_json(directory / "simulation-scheduling.json", scheduling)
if continuous:
from process_pipeline import ProcessPipeline
ai = ProcessPipeline(root / "simulation/ai-polygon", run, directory / "camera")
mission = ai.mission
else:
ai = LatestInference(
lambda: ComposedInference(
root / "simulation/ai-polygon", run, directory / "camera", mission=mission
),
None,
directory / "camera",
)
ai.start()
operator_camera = ObserverCamera()
smooth_view = SmoothView()
control = {"control": "pause", "control_sequence": 0, "camera": "follow"}
start = last_report = last_sensor = last_control = time.monotonic()
render_frames = sensor_frames = sequence = 0
prior_metrics = (start, 0, 0, 0, baseline)
speed = 0.0
had_ai = False
unstable = False
terminal_at = None
motion_control = RoverMotionControl(robot, max_speed)
envelope, chassis_feedback = motion_control.envelope, motion_control.feedback
state = {"velocity": 0.0, "yaw_rate": 0.0, "stop_reason": "paused", "decision": None}
physics_rows = []
physics_seconds = 0.0
from motion_metrics import PlanarDistance, planar_twist
travelled = PlanarDistance()
from rover_motion import UsdTrackMotion
track_motion = (
UsdTrackMotion(stage, "/World/Rover/chassis/DCD006", robot["visual"]["motion"])
if robot["visual"].get("motion")
else None
)
def control_step(dt, _context):
axes = state["transform"]
forward = axes.TransformDir(Gf.Vec3d(1, 0, 0)).GetNormalized()
lateral = axes.TransformDir(Gf.Vec3d(0, 1, 0)).GetNormalized()
def shape(velocity, yaw_rate, reason):
return motion_control.step(velocity, yaw_rate, dt,
float(np.dot(state["body_velocity"], forward)),
float(np.dot(state["body_angular_velocity"], lateral)),
stop=reason != "none")
if continuous:
velocity, yaw_rate, reason, decision = ai.apply_command(
drive.command, shape=shape, stop=unstable)
else:
velocity, yaw_rate, reason, decision = ai.command(
time.monotonic(), frame_deadline=FRAME_DEADLINE_SECONDS)
if unstable or (decision and decision['decision']['reason'] in
{'unstable', 'stuck', 'goal-reached'}):
velocity = yaw_rate = 0.0
reason = 'control-blocked'
velocity, yaw_rate = shape(velocity, yaw_rate, reason)
drive.command(velocity, yaw_rate)
drive.step(dt)
state.update(
velocity=velocity,
yaw_rate=yaw_rate,
stop_reason="unstable" if unstable else reason,
decision=decision,
)
def update_cameras():
transform = body_transform()
position = transform.ExtractTranslation()
forward = transform.TransformDir(Gf.Vec3d(1, 0, 0)).GetNormalized()
yaw = math.atan2(forward[1], forward[0])
# Both sensor position and attitude follow the physical body.
# Mounting height is measured from nominal wheel contact.
eye = transform.Transform(
Gf.Vec3d(
rig["camera_forward_m"],
0,
rig["camera_height_m"] - PROFILE["body_contact_height_m"],
)
)
pitch = math.radians(rig["camera_pitch_degrees"])
camera_axes = [
transform.TransformDir(Gf.Vec3d(*axis)).GetNormalized()
for axis in (
(math.cos(pitch), 0, math.sin(pitch)),
(0, 1, 0),
(-math.sin(pitch), 0, math.cos(pitch)),
)
]
def look_at(pos, rotation, origin, target, up=None):
if up is None:
up = Gf.Vec3d(0, 0, 1)
pos.Set(origin)
rotation.Set(
Gf.Quatf(
Gf.Matrix4d().SetLookAt(origin, target, up).GetInverse().ExtractRotationQuat()
)
)
if mounted:
mounted.update(transform)
else:
look_at(sensor_pos, sensor_rot, eye, eye + camera_axes[0], camera_axes[2])
mode = control.get("camera", "follow")
if route_view.editing:
viewport.camera_path = str(observer.GetPath())
route_view.camera(observer, observer_pos, observer_rot)
else:
viewport.camera_path = str(observer.GetPath())
operator_eye, target, up = operator_camera.update(
mode, list(position), yaw, list(eye), control.get("observer_input")
)
operator_eye, target, up = smooth_view.update(
mode, (operator_eye, target, up), time.monotonic()
)
look_at(
observer_pos,
observer_rot,
Gf.Vec3d(*operator_eye),
Gf.Vec3d(*target),
Gf.Vec3d(*up),
)
linear, angular = body.get_velocities()
q = transform.ExtractRotationQuat()
state.update(
transform=transform,
position=position,
yaw=yaw,
eye=eye,
camera_axes=camera_axes,
mode=mode,
pose=list(position) + list(q.GetImaginary()) + [q.GetReal()],
speed=float(np.linalg.norm(linear.numpy()[0, :2])),
body_velocity=linear.numpy()[0].tolist(),
body_angular_velocity=angular.numpy()[0].tolist(),
)
def physics_step(dt, _context):
nonlocal unstable, physics_seconds
physics_seconds += dt
update_cameras()
travelled.observe(state["pose"][:2])
if continuous:
heading = state['transform'].TransformDir(Gf.Vec3d(1, 0, 0))
ai.observe_pose(state["pose"], state["speed"], time.monotonic(), measured_twist=
planar_twist(state['body_velocity'], state['body_angular_velocity'], heading))
if track_motion:
track_motion.advance(dt, *drive.side_speeds())
unstable |= inclination(state["pose"]) >= PROFILE["stop_tilt_degrees"]
physics_rows.append(
{
"monotonic": time.monotonic(),
"simulation_time_ns": round(physics_seconds * 1e9),
"dt": dt,
"pose": state["pose"],
"velocity": state["body_velocity"],
"angular_velocity": state["body_angular_velocity"],
"command": [state["velocity"], state["yaw_rate"]],
"side_intent_mps": [envelope.requested.left_mps, envelope.requested.right_mps],
"side_nominal_mps": list(envelope.wheels),
"side_applied_mps": [
state["velocity"] - state["yaw_rate"] * PROFILE["track_width_m"] / 2,
state["velocity"] + state["yaw_rate"] * PROFILE["track_width_m"] / 2,
],
"chassis_speed_feedback": chassis_feedback.metrics if chassis_feedback else None,
"side_actual_mps": drive.side_speeds(),
"drivetrain": drive.metrics,
"stop_reason": state["stop_reason"],
"decision_reason": (state.get("decision") or {})
.get("decision", {})
.get("reason", "unknown"),
"decision_frame_id": (state.get("decision") or {}).get("frame_id"),
"decision_captured_at": (state.get("decision") or {}).get("captured_at"),
"decision_completed_at": (state.get("decision") or {}).get("completed_at"),
"applied_target": getattr(ai, "applied_target", None) if continuous else None,
}
)
if challenge:
challenge.observe_motion(physics_rows[-1])
callback_errors = []
def guarded(callback):
def invoke(dt, context):
try:
callback(dt, context)
except Exception:
# Native event dispatch logs Python exceptions and continues.
# A failed control/camera callback must instead end this run.
callback_errors.append(traceback.format_exc())
ai.enable(False)
drive.command(0.0, 0.0)
return invoke
update_cameras()
physics_callbacks.extend(
[
SimulationManager.register_callback(
guarded(control_step), SimulationEvent.PHYSICS_PRE_STEP
),
SimulationManager.register_callback(
guarded(physics_step), SimulationEvent.PHYSICS_POST_STEP
),
]
)
with (
(directory / "motion.jsonl").open("a", encoding="utf-8") as motion,
(directory / "physics-motion.jsonl").open("a", encoding="utf-8") as physics_motion,
(directory / "challenge-events.jsonl").open("a", encoding="utf-8") as challenge_events,
):
while app.is_running():
now = time.monotonic()
failure = consume_pipeline_failure(ai, directory, drive.command)
if failure is not None:
result = failure
break
if now - last_control >= 0.1:
control = channel.read("control", control)
route_view.apply(control.get("planning_commands", []))
last_control = now
if control["control"] == "stop":
result = {
"outcome": "stopped",
"mission_outcome": "operator-stop",
"message": "Симуляция и inference остановлены.",
}
break
requested_play = control["control"] == "play" and not route_view.editing
playing = requested_play and channel.read("models", {}).get("ready", False)
ai.enable(playing)
had_ai |= playing
if playing and not timeline.is_playing():
timeline.play()
elif not playing and timeline.is_playing():
timeline.pause()
velocity, yaw_rate, stop_reason, decision = ai.command(
now, frame_deadline=FRAME_DEADLINE_SECONDS
)
transform = body_transform()
q = transform.ExtractRotationQuat()
pose = list(transform.ExtractTranslation()) + list(q.GetImaginary()) + [q.GetReal()]
unstable |= inclination(pose) >= PROFILE["stop_tilt_degrees"]
if unstable:
velocity, yaw_rate, stop_reason = 0.0, 0.0, "unstable"
terminal_reason = (
"unstable" if unstable else (decision["decision"]["reason"] if decision else None)
)
if terminal_reason in {"unstable", "stuck", "goal-reached"}:
velocity, yaw_rate = 0.0, 0.0
terminal_at = now if terminal_at is None else terminal_at
if now - terminal_at >= 2:
result = {
"outcome": "completed" if terminal_reason == "goal-reached" else "failed",
"mission_outcome": terminal_reason,
"message": {
"goal-reached": "Ровер достиг цели маршрута.",
"stuck": "Ровер не нашёл проезд после трёх попыток. Прогон завершён.",
"unstable": "Прогон завершён из-за опасного наклона ровера.",
}[terminal_reason],
}
break
# The selected physics adapter owns actuator forces and stop mode.
if not playing:
drive.command(*envelope.step(0.0, 0.0, 0.0, stop=True))
update_cameras()
state.update(
velocity=0.0, yaw_rate=0.0, stop_reason="paused", speed=0.0, decision=decision
)
if challenge:
# Apply fixtures before rendering so RGB and range observe the
# same environment. Never mutate the rover or its controller.
challenge.tick(time.monotonic(), obstacle)
app.update() # Never waits for inference, a network request, or an operator ACK.
if track_motion:
track_motion.publish()
if callback_errors:
raise RuntimeError(callback_errors[0])
render_frames += 1
captured_at = time.monotonic()
if challenge:
challenge.deliver_due(captured_at, ai.submit)
transform, position = state["transform"], state["position"]
eye, camera_axes = state["eye"], state["camera_axes"]
pose, yaw, speed, mode = state["pose"], state["yaw"], state["speed"], state["mode"]
velocity, yaw_rate = state["velocity"], state["yaw_rate"]
stop_reason, decision = state["stop_reason"], state["decision"]
if physics_rows:
physics_motion.writelines(
json.dumps(row, allow_nan=False) + "\n" for row in physics_rows
)
physics_rows.clear()
physics_motion.flush()
physics = SimulationManager.get_num_physics_steps()
sim_ns = round((physics - baseline) * 1e9 / 60)
if playing and captured_at - last_sensor >= 1 / SENSOR_HZ:
mounted_observation = None
if mounted:
intent = getattr(mission, "perception_target", mission.orientation_target)()
captured = mounted.capture(intent)
rgb, mounted_observation = captured if captured else (None, None)
else:
rgb = annotator.get_data()
rgb_ready_at = time.monotonic()
if isinstance(rgb, np.ndarray) and (
mounted is not None or rgb.shape[:2] == (sensor_height, sensor_width)
):
sensor_frames += 1
rear_eye = transform.Transform(
Gf.Vec3d(
PROFILE["rear_range_forward_m"],
0,
rig["camera_height_m"] - PROFILE["body_contact_height_m"],
)
)
points = (
range_sensor.capture(transform)
if mounted
else range_sensor.capture(eye, transform, rear_eye)
)
range_ready_at = time.monotonic()
if obstacle and challenge.started is not None:
challenge.record(
"obstacle-observation",
range_ready_at,
frame_id=sensor_frames,
hits=range_sensor.hit_paths.get(obstacle.path, 0),
)
quaternion = transform.ExtractRotationQuat()
imaginary = quaternion.GetImaginary()
# Columns are the camera's forward/left/up axes in world.
observation = {
"sensor_timing_ms": {
"rgb_read": (rgb_ready_at - captured_at) * 1000,
"range_capture": (range_ready_at - rgb_ready_at) * 1000,
},
"simulation_time_ns": sim_ns,
"points": points,
"range_rays": range_sensor.rays,
"pose": [float(v) for v in position]
+ [float(v) for v in imaginary]
+ [float(quaternion.GetReal())],
"calibration": {
"origin": list(eye),
"rotation": np.array(camera_axes).T.reshape(-1).tolist(),
"intrinsics": [
focal_pixels,
focal_pixels,
sensor_width / 2,
sensor_height / 2,
],
"body_contact_height_m": PROFILE["body_contact_height_m"],
"range_origins": [list(eye), list(rear_eye)],
},
}
if mounted_observation is not None:
observation.update(mounted_observation)
observation["calibration"]["range_origins"] = range_sensor.rays[
"origins"
].tolist()
observation["realsense_depth"] = range_sensor.depth.copy()
observation["range_source_counts"] = dict(range_sensor.source_counts)
packet = (
np.array(rgb[:, :, :3], copy=True, order="C"),
sensor_frames,
captured_at,
sim_ns,
observation,
)
if challenge:
challenge.submit(packet, time.monotonic(), ai.submit)
else:
ai.submit(*packet)
last_sensor = captured_at
if challenge:
challenge_events.writelines(
json.dumps(e, allow_nan=False) + "\n" for e in challenge.drain_events()
)
challenge_events.flush()
if captured_at - last_report >= 0.25:
prior_at, prior_render, prior_sensor, prior_ai, prior_physics = prior_metrics
elapsed = captured_at - prior_at
report = dict(
sequence=sequence,
control_sequence=control["control_sequence"],
state="running" if requested_play else "paused" if had_ai else "ready",
phase="models" if requested_play and not ai.ever_ready else "running",
simulation_time_ns=sim_ns,
distance_m=travelled.metres,
wall_elapsed_seconds=captured_at - start,
physics_steps=physics - baseline,
render_frames=render_frames,
sensor_frames=sensor_frames,
inference_count=ai.count,
dropped_frames=ai.dropped,
rtf=(physics - prior_physics) / 60 / elapsed,
render_fps=(render_frames - prior_render) / elapsed,
sensor_fps=(sensor_frames - prior_sensor) / elapsed,
ai_hz=(ai.count - prior_ai) / elapsed,
inference_ms=decision["inference_ms"] if decision else None,
frame_age_ms=(captured_at - decision.get("perception_captured_at", decision["captured_at"])) * 1000
if decision
else None,
command_age_ms=(captured_at - decision.get("control_completed_at", decision["completed_at"])) * 1000
if decision
else None,
pose_xy=[float(position[0]), float(position[1])],
pose_yaw=yaw,
speed_mps=speed,
applied_speed_mps=velocity,
applied_yaw_rate_rps=yaw_rate,
decision=decision["decision"] if decision else None,
stop_reason=stop_reason,
ai_ready=ai.ready,
stream_ready=not args.no_stream,
camera=mode,
route_overlay=route_view.overlay(
observer,
[
float(position[0]),
float(position[1]),
float(position[2] - PROFILE["body_contact_height_m"] + 0.05),
],
mission.index,
),
planning=route_view.draft() if route_view.editing else None,
)
channel.write("snapshot", report)
motion.write(
json.dumps(
{
**report,
"monotonic": captured_at,
"track_motion": track_motion.metrics() if track_motion else None,
"pose_xyz_xyzw": pose,
"tilt_degrees": inclination(pose),
"side_actual_mps": drive.side_speeds(),
"drivetrain": drive.metrics,
"wheel_velocity_rps": body.get_dof_velocities(dof_indices=drive.indices)
.numpy()[0]
.tolist()
if hasattr(drive, "indices")
else None,
"usd_position_xyz": list(
UsdGeom.XformCache()
.GetLocalToWorldTransform(
stage.GetPrimAtPath("/World/Rover/chassis")
)
.ExtractTranslation()
),
},
allow_nan=False,
)
+ "\n"
)
motion.flush()
last_report = captured_at
sequence += 1
if elapsed >= 1:
prior_metrics = (captured_at, render_frames, sensor_frames, ai.count, physics)
if shutil.disk_usage(directory).free < 1024**3:
raise RuntimeError("Worker evidence disk is full")
except Exception as exc:
message = str(exc)
placement_failure = any(
text in message
for text in (
"Configured spawn",
"Rover start",
"reconstructed ground",
"reconstructed support",
)
)
result = {
"outcome": "failed",
"mission_outcome": "error",
"message": "Не удалось устойчиво разместить ровер на грунте. Измените положение старта."
if placement_failure
else "Симуляция прервана из-за ошибки на Worker. Журнал сохранён.",
}
traceback.print_exc()
finally:
for callback_id in physics_callbacks:
SimulationManager.deregister_callback(callback_id)
channel.close()
if ai is not None:
ai.close()
if mounted is not None:
mounted.close()
write_json(directory / "result.json", result)
if app is not None:
app.close()
if __name__ == "__main__":
main()