"""Metric collision proxy and occlusion-aware virtual range sensor on Worker.""" import hashlib import json import math import struct from pathlib import Path import numpy as np def load_glb(path, rotation=None): data = Path(path).read_bytes() magic, version, size = struct.unpack_from("= len(points): raise ValueError("Invalid collision vertices") points = points @ transform.T vertices.append(points[:, [0, 2, 1]] * np.array([1, -1, 1], np.float32)) faces.append(triangles + base) base += len(points) return np.concatenate(vertices), np.concatenate(faces) def ground_intersections(vertices, faces, x, y): """Vertical mesh intersections, used only to place the initial rigid body.""" triangles = vertices[faces] low, high = triangles[:, :, :2].min(axis=1), triangles[:, :, :2].max(axis=1) candidate = triangles[ (low[:, 0] <= x) & (high[:, 0] >= x) & (low[:, 1] <= y) & (high[:, 1] >= y) ] if not len(candidate): return np.empty(0) a, b, c = candidate[:, 0], candidate[:, 1], candidate[:, 2] den = (b[:, 1] - c[:, 1]) * (a[:, 0] - c[:, 0]) + (c[:, 0] - b[:, 0]) * (a[:, 1] - c[:, 1]) valid = np.abs(den) > 1e-8 a, b, c, den = a[valid], b[valid], c[valid], den[valid] u = ((b[:, 1] - c[:, 1]) * (x - c[:, 0]) + (c[:, 0] - b[:, 0]) * (y - c[:, 1])) / den v = ((c[:, 1] - a[:, 1]) * (x - c[:, 0]) + (a[:, 0] - c[:, 0]) * (y - c[:, 1])) / den inside = (u >= -1e-6) & (v >= -1e-6) & (u + v <= 1 + 1e-6) return (u * a[:, 2] + v * b[:, 2] + (1 - u - v) * c[:, 2])[inside] def terrain_contact_policy(physics_profile): """Metric contact generation distance, independent of a map's full extent.""" offset = physics_profile["contact_offset_m"] if type(offset) not in (float, int) or not math.isfinite(offset) or offset <= 0: raise ValueError("Terrain contact offset requires a positive finite metric profile value") return dict(contact_offset_m=float(offset), rest_offset_m=0., source="robot.physics.contact_offset_m", derived_from_map_extent=False) CONTACT_READBACK_TOLERANCE_M = 1e-7 # Fixed USD float32 readback tolerance, not a contact margin. def _contact_policy_readback(prim, policy): from pxr import PhysxSchema, UsdPhysics if not prim or not prim.IsValid() or not prim.HasAPI(UsdPhysics.CollisionAPI): raise ValueError("Environment contact policy requires an existing collision prim") if not prim.HasAPI(PhysxSchema.PhysxCollisionAPI): raise ValueError("Environment contact policy must be explicitly authored") api = PhysxSchema.PhysxCollisionAPI(prim) values = {} for key, attribute in ( ("contact_offset_m", api.GetContactOffsetAttr()), ("rest_offset_m", api.GetRestOffsetAttr()), ): if not attribute or not attribute.HasAuthoredValueOpinion(): raise ValueError("Environment contact offset cannot use an automatic default") value = attribute.Get() if ( type(value) not in (float, int) or not math.isfinite(value) or (key == "contact_offset_m" and value <= 0) or (key == "rest_offset_m" and value != 0.0) or not math.isclose( value, policy[key], rel_tol=0.0, abs_tol=CONTACT_READBACK_TOLERANCE_M ) ): raise ValueError("Authored environment contact policy differs from effective robot") values[key] = float(value) return dict( collider=str(prim.GetPath()), **values, contact_offset_authored=True, rest_offset_authored=True, ) def apply_environment_contact_policy(prim, physics_profile): """Author the same metric policy for terrain, native pads and obstacles.""" from pxr import PhysxSchema policy = terrain_contact_policy(physics_profile) api = PhysxSchema.PhysxCollisionAPI.Apply(prim) api.CreateContactOffsetAttr(policy["contact_offset_m"]) api.CreateRestOffsetAttr(policy["rest_offset_m"]) return _contact_policy_readback(prim, policy) def validate_environment_contact_policy(stage, collider_paths, physics_profile): """Read-only USD preflight. It does not claim a cooked-native readback.""" from pxr import Sdf, UsdGeom if ( not isinstance(collider_paths, (list, tuple)) or not collider_paths or any(not isinstance(path, str) for path in collider_paths) or len(set(collider_paths)) != len(collider_paths) ): raise ValueError("Exact unique environment collider paths are required") if stage is None: raise ValueError("Native scene stage is missing") units = UsdGeom.GetStageMetersPerUnit(stage) if type(units) not in (float, int) or not math.isfinite(units) or units != 1.0: raise ValueError("Metric environment contact policy requires metre stage units") policy = terrain_contact_policy(physics_profile) colliders = [] for name in collider_paths: path = Sdf.Path(name) if not path.IsAbsolutePath() or not path.IsPrimPath() or str(path) != name: raise ValueError("Environment contact policy needs exact absolute prim paths") prim = stage.GetPrimAtPath(path) if not prim or not prim.IsValid() or str(prim.GetPath()) != name: raise ValueError("Environment contact policy prim is missing or mismatched") colliders.append(_contact_policy_readback(prim, policy)) policy_sha256 = hashlib.sha256( json.dumps(policy, sort_keys=True, separators=(",", ":"), allow_nan=False).encode() ).hexdigest() return dict( schema_version="missioncore.environment-contact-policy/v1", policy=policy, policy_sha256=policy_sha256, meters_per_unit=float(units), readback_tolerance_m=CONTACT_READBACK_TOLERANCE_M, colliders=colliders, scope="authored-usd-readback; native-cooked-not-verified", ) def install_terrain(stage, manifest_path, world, *, physics_profile=None): from pxr import UsdGeom, UsdPhysics, UsdShade from rover_profile import PROFILE from k1link.simulation.ai_polygon.terrain_contract import terrain_matches manifest = json.loads(Path(manifest_path).read_text(encoding="utf-8-sig")) if not terrain_matches(manifest, world): raise ValueError("Terrain does not match the world calibration") path = Path(manifest["collider"]) if hashlib.sha256(path.read_bytes()).hexdigest() != manifest["collider_sha256"]: raise ValueError("Collision mesh identity changed") points, triangles = load_glb(path, manifest.get("collision_rotation")) settings = world["settings"] heights = ground_intersections(points, triangles, *settings["spawn_xy"]) candidates = heights[np.abs(heights - settings["ground_z"]) < 0.8] if not len(candidates): raise ValueError("No reconstructed ground at the configured spawn") # Place the whole footprint above nearby ground, without embedding a wheel # in a stone beside the centre ray. This is setup, never a planner input. angle = math.radians(settings["heading_degrees"]) support, offsets = [], [] for dx in (-PROFILE["length_m"] / 2, 0, PROFILE["length_m"] / 2): for dy in (-PROFILE["width_m"] / 2, 0, PROFILE["width_m"] / 2): x = settings["spawn_xy"][0] + dx * math.cos(angle) - dy * math.sin(angle) y = settings["spawn_xy"][1] + dx * math.sin(angle) + dy * math.cos(angle) intersections = ground_intersections(points, triangles, x, y) nearby = intersections[np.abs(intersections - settings["ground_z"]) < 0.8] if not len(nearby): raise ValueError("Rover footprint has no reconstructed support") support.append(float(nearby.max())) offsets.append([x - settings["spawn_xy"][0], y - settings["spawn_xy"][1], 1]) plane = np.linalg.lstsq(np.asarray(offsets), np.asarray(support), rcond=None)[0] residual = np.asarray(support) - np.asarray(offsets) @ plane normal = np.array([-plane[0], -plane[1], 1.0]) normal /= np.linalg.norm(normal) if np.max(np.abs(residual)) > 0.12 or normal[2] < math.cos(math.radians(25)): raise ValueError("Configured spawn is too uneven for the metre-wide rover") from spawn_clearance import obstructing_triangles if obstructing_triangles( points, triangles, settings["spawn_xy"], settings["heading_degrees"], plane, step=PROFILE["max_step_m"], length=PROFILE["length_m"], width=PROFILE["width_m"], ): raise ValueError("Configured spawn contains an obstacle inside the rover footprint") # Align to the local support plane before gravity settles the suspensionless # lab chassis. Wheel centres start 4 cm above the highest residual contact. wheel_center_z = float( plane[2] + (PROFILE["wheel_radius_m"] + 0.04) / normal[2] + max(0, residual.max()) ) mesh = UsdGeom.Mesh.Define(stage, "/World/Terrain") mesh.CreatePointsAttr(points.tolist()) mesh.CreateFaceVertexCountsAttr([3] * len(triangles)) mesh.CreateFaceVertexIndicesAttr(triangles.reshape(-1).tolist()) mesh.CreateSubdivisionSchemeAttr(UsdGeom.Tokens.none) mesh.CreateDoubleSidedAttr(True) mesh.CreateVisibilityAttr(UsdGeom.Tokens.invisible) UsdPhysics.CollisionAPI.Apply(mesh.GetPrim()) UsdPhysics.MeshCollisionAPI.Apply(mesh.GetPrim()).CreateApproximationAttr("none") effective_physics = PROFILE if physics_profile is None else physics_profile apply_environment_contact_policy(mesh.GetPrim(), effective_physics) contact_policy = terrain_contact_policy(effective_physics) material = UsdShade.Material.Define(stage, "/World/Materials/Terrain") surface = UsdPhysics.MaterialAPI.Apply(material.GetPrim()) surface.CreateStaticFrictionAttr(0.9) surface.CreateDynamicFrictionAttr(0.8) surface.CreateRestitutionAttr(0) UsdShade.MaterialBindingAPI.Apply(mesh.GetPrim()).Bind( material, UsdShade.Tokens.weakerThanDescendants, "physics" ) return wheel_center_z, dict( manifest, vertex_count=len(points), triangle_count=len(triangles), initial_contact_z=float(plane[2]), initial_ground_normal=normal.tolist(), support_residual_m=float(np.max(np.abs(residual))), contact_policy=contact_policy, ) class RangeSensor: """Front 360-degree LiDAR plus rear near-field fan; first physical hit. Separate mounts observe the ground beyond each bumper without seeing through the chassis. The rear fan adds 660 rays to the 2160 front rays. """ def __init__(self): import omni.physx self.query = omni.physx.get_physx_scene_query_interface() elevations = (-80, -75, -70, -60, -45, -35, -28, -22, -18, -14, -10, -5, 0, 5, 15) self.directions = np.array( [ (math.cos(e) * math.cos(a), math.cos(e) * math.sin(a), math.sin(e)) for e in np.radians(elevations) for a in np.radians(np.arange(-180, 180, 2.5)) ] ) self.rear_directions = np.array( [ (math.cos(e) * math.cos(a), math.cos(e) * math.sin(a), math.sin(e)) for e in np.radians(np.arange(-80, 16, 5)) for a in np.radians(np.arange(100, 261, 5)) ] ) def capture(self, origin, rotation, rear_origin=None): points = [] # Qualification evidence only. Collider identities never enter the # observation packet consumed by navigation or semantic inference. self.hit_paths = {} ray_origin_indices, ray_ends = [], [] # Gf uses row vectors. Transform the whole fan once, preserving all # rays and the closest-hit/self-occlusion policy of the sensor. axes = np.asarray(rotation, dtype=float)[:3, :3] mounts = [(origin, self.directions)] if rear_origin is not None: mounts.append((rear_origin, self.rear_directions)) for mount_index, (mount, directions) in enumerate(mounts): rays = np.asarray(directions) @ axes rays /= np.linalg.norm(rays, axis=1, keepdims=True) mount = tuple(mount) for ray in rays.tolist(): hit = self.query.raycast_closest(mount, tuple(ray), 8.0, bothSides=True) # A valid no-echo beam observes free space to its maximum range. # Self-occluded rays grant no clearing evidence behind the body. if not hit["hit"]: ray_origin_indices.append(mount_index) ray_ends.append(np.asarray(mount) + np.asarray(ray) * 8.0) if hit["hit"] and not str(hit.get("rigidBody", "")).startswith("/World/Rover"): points.append(hit["position"]) ray_origin_indices.append(mount_index) ray_ends.append(hit["position"]) path = str(hit.get("collision", "")) if path: self.hit_paths[path] = self.hit_paths.get(path, 0) + 1 self.rays = { "origins": np.asarray([m for m, _ in mounts], dtype=np.float32).reshape(-1, 3), "origin_indices": np.asarray(ray_origin_indices, dtype=np.int32), "ends": np.asarray(ray_ends, dtype=np.float32).reshape(-1, 3), } return np.asarray(points, dtype=np.float32).reshape(-1, 3)