Preserve installed operator workspace before consolidation
Local preservation snapshot, not a new deployment or simulation acceptance.
This commit is contained in:
@@ -0,0 +1,295 @@
|
||||
"""Worker-only route editing and projection. No annotation prim enters the stage.
|
||||
|
||||
The operator receives 2D overlay coordinates over WebRTC. Neither RGB render
|
||||
products nor range sensors can observe those UI annotations.
|
||||
"""
|
||||
|
||||
import copy
|
||||
import math
|
||||
import time
|
||||
from uuid import uuid4
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
def project_point(position, world_to_camera, focal, aperture, aspect=16 / 9):
|
||||
local = np.append(position, 1.0) @ np.asarray(world_to_camera)
|
||||
if local[2] >= -0.05:
|
||||
return None
|
||||
x = 0.5 + local[0] * focal / aperture / -local[2]
|
||||
y = 0.5 - local[1] * focal / (aperture / aspect) / -local[2]
|
||||
return [float(x), float(y)] if -2 <= x <= 3 and -2 <= y <= 3 else None
|
||||
|
||||
|
||||
class RouteView:
|
||||
def __init__(self, run, query):
|
||||
self.query = query
|
||||
self.editing = run["request"].get("purpose") == "planning"
|
||||
settings = run["world"]["settings"]
|
||||
self.target = np.array([*settings["spawn_xy"], settings["ground_z"]], dtype=float)
|
||||
self.yaw = math.radians(settings["heading_degrees"]) + math.pi
|
||||
self.elevation, self.distance = math.radians(55), 12.0
|
||||
self.home_eye = self.target + self.distance * np.array(
|
||||
[
|
||||
math.cos(self.yaw) * math.cos(self.elevation),
|
||||
math.sin(self.yaw) * math.cos(self.elevation),
|
||||
math.sin(self.elevation),
|
||||
]
|
||||
)
|
||||
self.home_angles = np.array([self.yaw + math.pi, -self.elevation])
|
||||
self.eye = self.desired_eye = self.home_eye.copy()
|
||||
self.angles = self.desired_angles = self.home_angles.copy()
|
||||
self.camera_updated = time.monotonic()
|
||||
self.height_bounds = getattr(query, "height_bounds", None)
|
||||
self.sequence = self.revision = 0
|
||||
self.error = None
|
||||
self.clip_height = None
|
||||
self._clip_applied = None
|
||||
self.history, self.trail = [], []
|
||||
self.points = []
|
||||
source = (run.get("plan") or {}).get("points")
|
||||
if source:
|
||||
self.points = copy.deepcopy(source)
|
||||
else:
|
||||
for xy in [
|
||||
settings["spawn_xy"],
|
||||
*([] if self.editing else settings.get("route_xy", [])),
|
||||
]:
|
||||
try:
|
||||
position = self.ground(*xy, settings["ground_z"])
|
||||
self.points.append(self.point(position))
|
||||
except ValueError:
|
||||
self.error = (
|
||||
"У исходной точки нет подтверждённой поверхности. Добавьте старт по клику."
|
||||
)
|
||||
self.matrix = np.eye(4)
|
||||
self.focal, self.aperture = 24.0, 36.0
|
||||
|
||||
@staticmethod
|
||||
def point(position):
|
||||
return {"id": uuid4().hex[:16], "position": list(map(float, position))}
|
||||
|
||||
def ground(self, x, y, z):
|
||||
hits = []
|
||||
|
||||
def collect(hit):
|
||||
if str(hit.get("collision", "")) == "/World/Terrain" and abs(
|
||||
hit["normal"][2]
|
||||
) >= math.cos(math.radians(45)):
|
||||
hits.append(hit["position"])
|
||||
return True
|
||||
|
||||
self.query.raycast_all(
|
||||
(float(x), float(y), float(z) + 4), (0, 0, -1), 8, collect, bothSides=True
|
||||
)
|
||||
if not hits:
|
||||
raise ValueError("В этой точке нет подготовленной поверхности для маршрута.")
|
||||
return list(min(hits, key=lambda p: abs(p[2] - z)))
|
||||
|
||||
def ray(self, x, y):
|
||||
inverse = np.linalg.inv(self.matrix)
|
||||
origin = inverse[3, :3]
|
||||
direction = (
|
||||
np.array(
|
||||
[
|
||||
(x - 0.5) * self.aperture / self.focal,
|
||||
(0.5 - y) * self.aperture / (16 / 9) / self.focal,
|
||||
-1.0,
|
||||
0,
|
||||
]
|
||||
)
|
||||
@ inverse
|
||||
)
|
||||
direction = direction[:3] / np.linalg.norm(direction[:3])
|
||||
return origin, direction
|
||||
|
||||
def hit(self, x, y):
|
||||
origin, direction = self.ray(x, y)
|
||||
hits = []
|
||||
|
||||
def collect(hit):
|
||||
if str(hit.get("collision", "")) == "/World/Terrain":
|
||||
p = hit["position"]
|
||||
if (self.clip_height is None or p[2] <= self.clip_height) and abs(
|
||||
hit["normal"][2]
|
||||
) >= math.cos(math.radians(45)):
|
||||
hits.append(p)
|
||||
return True
|
||||
|
||||
self.query.raycast_all(
|
||||
tuple(map(float, origin)), tuple(map(float, direction)), 250.0, collect, bothSides=True
|
||||
)
|
||||
if not hits:
|
||||
raise ValueError("Под курсором нет подготовленной поверхности. Измените обзор.")
|
||||
return min(hits, key=lambda p: np.linalg.norm(np.asarray(p) - origin))
|
||||
|
||||
def apply(self, commands):
|
||||
if not self.editing:
|
||||
return
|
||||
for event in commands:
|
||||
if event["sequence"] <= self.sequence:
|
||||
continue
|
||||
self.sequence = event["sequence"]
|
||||
self.error = None
|
||||
try:
|
||||
action = event["action"]
|
||||
if action in {"add", "move"} and event["view_revision"] != self.revision:
|
||||
raise ValueError("Обзор изменился. Повторите действие после обновления видео.")
|
||||
if action == "orbit":
|
||||
self.desired_angles = self.desired_angles + [-event["x"] * 3, -event["y"] * 2]
|
||||
self.desired_angles[1] = np.clip(self.desired_angles[1], -1.56, 1.56)
|
||||
self.revision += 1
|
||||
elif action == "pan":
|
||||
forward, right, up = self.camera_axes(self.desired_angles)
|
||||
self.translate(12 * (-event["x"] * right + event["y"] * up))
|
||||
self.revision += 1
|
||||
elif action == "zoom":
|
||||
forward, _, _ = self.camera_axes(self.desired_angles)
|
||||
self.translate(-forward * max(-3, min(3, event["amount"])))
|
||||
self.revision += 1
|
||||
elif action == "fly":
|
||||
forward, right, _ = self.camera_axes(self.desired_angles)
|
||||
# Each command is a bounded displacement, never a latched velocity.
|
||||
# Lost key-up, hidden tabs and disconnects cannot leave the camera flying.
|
||||
self.translate(
|
||||
event["x"] * right
|
||||
+ event["y"] * forward
|
||||
+ np.array([0, 0, max(-3, min(3, event["amount"]))])
|
||||
)
|
||||
self.revision += 1
|
||||
elif action == "home":
|
||||
self.desired_eye = self.home_eye.copy()
|
||||
self.desired_angles = self.home_angles.copy()
|
||||
self.revision += 1
|
||||
elif action == "clip":
|
||||
self.clip_height = (
|
||||
float(event["amount"]) if event.get("enabled", True) else None
|
||||
)
|
||||
self.revision += 1
|
||||
elif action == "undo":
|
||||
if self.history:
|
||||
self.points = self.history.pop()
|
||||
else:
|
||||
changed = copy.deepcopy(self.points)
|
||||
if action == "clear":
|
||||
changed = []
|
||||
elif action == "add":
|
||||
if len(changed) >= 33:
|
||||
raise ValueError("Доступно не более 33 точек со стартом.")
|
||||
changed.append(self.point(self.hit(event["x"], event["y"])))
|
||||
elif action in {"move", "delete"}:
|
||||
point = next((p for p in changed if p["id"] == event["point_id"]), None)
|
||||
if point is None:
|
||||
raise ValueError("Точка уже удалена.")
|
||||
if action == "delete":
|
||||
changed.remove(point)
|
||||
else:
|
||||
origin, direction = self.ray(event["x"], event["y"])
|
||||
if abs(direction[2]) < 1e-4:
|
||||
raise ValueError("Для перемещения наклоните обзор к поверхности.")
|
||||
t = (point["position"][2] - origin[2]) / direction[2]
|
||||
if t <= 0:
|
||||
raise ValueError("Точка находится за камерой.")
|
||||
candidate = origin + t * direction
|
||||
if event.get("axis") == "x":
|
||||
candidate[1] = point["position"][1]
|
||||
elif event.get("axis") == "y":
|
||||
candidate[0] = point["position"][0]
|
||||
point["position"] = self.ground(*candidate[:2], point["position"][2])
|
||||
self.history = (self.history + [self.points])[-30:]
|
||||
self.points = changed
|
||||
except ValueError as exc:
|
||||
self.error = str(exc)
|
||||
|
||||
@staticmethod
|
||||
def camera_axes(angles):
|
||||
yaw, pitch = angles
|
||||
forward = np.array(
|
||||
[math.cos(yaw) * math.cos(pitch), math.sin(yaw) * math.cos(pitch), math.sin(pitch)]
|
||||
)
|
||||
right = np.array([math.sin(yaw), -math.cos(yaw), 0])
|
||||
return forward, right, np.cross(right, forward)
|
||||
|
||||
def translate(self, delta):
|
||||
self.desired_eye = np.clip(self.desired_eye + delta, -10000, 10000)
|
||||
|
||||
@property
|
||||
def camera_moving(self):
|
||||
return bool(
|
||||
np.linalg.norm(self.desired_eye - self.eye) > 0.002
|
||||
or np.linalg.norm(self.desired_angles - self.angles) > 0.0002
|
||||
)
|
||||
|
||||
def advance_camera(self, dt):
|
||||
alpha = 1 - math.exp(-max(0, dt) / 0.075)
|
||||
self.eye = self.eye + alpha * (self.desired_eye - self.eye)
|
||||
self.angles = self.angles + alpha * (self.desired_angles - self.angles)
|
||||
|
||||
def camera(self, usd_camera, position, orientation):
|
||||
from pxr import Gf
|
||||
|
||||
now = time.monotonic()
|
||||
self.advance_camera(min(0.1, now - self.camera_updated))
|
||||
self.camera_updated = now
|
||||
forward, _, _ = self.camera_axes(self.angles)
|
||||
eye = Gf.Vec3d(*map(float, self.eye))
|
||||
target = Gf.Vec3d(*map(float, self.eye + forward))
|
||||
transform = Gf.Matrix4d().SetLookAt(eye, target, Gf.Vec3d(0, 0, 1)).GetInverse()
|
||||
position.Set(eye)
|
||||
orientation.Set(Gf.Quatf(transform.ExtractRotationQuat()))
|
||||
if self.clip_height != self._clip_applied:
|
||||
import carb.settings
|
||||
|
||||
renderer = carb.settings.get_settings()
|
||||
renderer.set_float_array(
|
||||
"/rtx/sectionPlane/plane", [0.0, 0.0, -1.0, float(self.clip_height or 0)]
|
||||
)
|
||||
renderer.set_bool("/rtx/sectionPlane/enabled", self.clip_height is not None)
|
||||
self._clip_applied = self.clip_height
|
||||
|
||||
def overlay(self, camera, body_position, active_index):
|
||||
from pxr import Usd
|
||||
|
||||
self.matrix = np.array(
|
||||
camera.ComputeLocalToWorldTransform(Usd.TimeCode.Default()).GetInverse()
|
||||
)
|
||||
self.focal = camera.GetFocalLengthAttr().Get()
|
||||
self.aperture = camera.GetHorizontalApertureAttr().Get()
|
||||
|
||||
def screen(p):
|
||||
return project_point(p, self.matrix, self.focal, self.aperture)
|
||||
|
||||
markers = []
|
||||
for i, point in enumerate(self.points):
|
||||
p = np.asarray(point["position"])
|
||||
markers.append(
|
||||
{
|
||||
**point,
|
||||
"index": i,
|
||||
"base": screen(p + [0, 0, 0.05]),
|
||||
"top": screen(p + [0, 0, 1.2]),
|
||||
"x_axis": screen(p + [0.65, 0, 0.05]),
|
||||
"y_axis": screen(p + [0, 0.65, 0.05]),
|
||||
}
|
||||
)
|
||||
if not self.editing and (not self.trail or math.dist(body_position, self.trail[-1]) >= 0.1):
|
||||
self.trail = (self.trail + [list(body_position)])[-256:]
|
||||
return {
|
||||
"markers": markers,
|
||||
"trace": [screen(p) for p in self.trail],
|
||||
"active_index": active_index + 1,
|
||||
"view_revision": self.revision,
|
||||
}
|
||||
|
||||
def draft(self):
|
||||
return {
|
||||
"sequence": self.sequence,
|
||||
"view_revision": self.revision,
|
||||
"points": self.points,
|
||||
"error": self.error,
|
||||
"can_undo": bool(self.history),
|
||||
"clip_height": self.clip_height,
|
||||
"height_min": self.height_bounds[0] if self.height_bounds else None,
|
||||
"height_max": self.height_bounds[1] if self.height_bounds else None,
|
||||
"camera_moving": self.camera_moving,
|
||||
}
|
||||
Reference in New Issue
Block a user