"""Isaac adapter for a rigid aggregate of two CAD-shaped continuous belts. Native contacts supply support and collision. Moving belts use TrackDynamics traction; stopped, held belts use native static/dynamic friction instead. Support sampling admits only measured nearby terrain; no invisible ground. """ import math import hashlib import json from pathlib import Path import numpy as np from track_dynamics import TrackDynamics def body_colliders(document): """Pinned CAD envelopes; legacy receipts retain their declared box model.""" descriptor = document['tracked_contact'].get('body_colliders') if descriptor is None: return None path = Path(__file__).parent / descriptor['path'] if not path.resolve().is_relative_to(Path(__file__).parent.resolve()): raise ValueError('Body collider path must belong to the installed artifact') raw = path.read_bytes() if hashlib.sha256(raw).hexdigest() != descriptor['sha256']: raise ValueError('Body collider identity changed') value = json.loads(raw) if (value['schema_version'] != 'missioncore.cad-rigid-body-colliders/v1' or value['source_sha256'] != document['visual']['motion']['source_sha256'] or not np.allclose(value['translation_m'], document['visual']['motion']['shift_m'])): raise ValueError('Body colliders and belt CAD do not share a frame/source') return value['components'] def belt_outline(motion, pad): points = [] for kind, _, length, data in motion["segments"]: count = max(2, math.ceil(length / 0.03)) for t in np.linspace(0, length, count, endpoint=False): if kind == "arc": cx, cz, radius, angle = data angle -= t / radius x, z = cx + radius * math.cos(angle), cz + radius * math.sin(angle) nx, nz = math.cos(angle), math.sin(angle) else: x, z = data[0] + data[2] * t, data[1] + data[3] * t nx, nz = -data[3], data[2] points.append([x + motion["shift_m"][0] + pad * nx, z + pad * nz]) return np.asarray(points) def create_tracked_rover(stage, document, spawn, heading, ground_normal, root_path, visual_asset): from pxr import Gf, PhysxSchema, UsdGeom, UsdPhysics, UsdShade p, dynamics = document["physics"], document["tracked_contact"] motion = document["visual"]["motion"] outline = belt_outline(motion, dynamics["belt_pad_extent_m"]) source_com_z = float(outline[:, 1].min()) + p["body_contact_height_m"] root = UsdGeom.Xform.Define(stage, root_path) root.AddTranslateOp().Set(Gf.Vec3d(*spawn)) tilt = Gf.Rotation(Gf.Vec3d(0, 0, 1), Gf.Vec3d(*ground_normal)).GetQuat() yaw = Gf.Rotation(Gf.Vec3d(0, 0, 1), heading).GetQuat() root.AddOrientOp().Set(Gf.Quatf(tilt * yaw)) body = UsdGeom.Xform.Define(stage, root_path + "/chassis") body.AddTranslateOp().Set(Gf.Vec3d(0, 0, p["body_contact_height_m"] - p["wheel_radius_m"])) UsdPhysics.RigidBodyAPI.Apply(body.GetPrim()) PhysxSchema.PhysxContactReportAPI.Apply(body.GetPrim()).CreateThresholdAttr(0.0) physics = PhysxSchema.PhysxRigidBodyAPI.Apply(body.GetPrim()) physics.CreateSolverPositionIterationCountAttr(p["solver_position_iterations"]) physics.CreateSolverVelocityIterationCountAttr(p["solver_velocity_iterations"]) physics.CreateMaxDepenetrationVelocityAttr(1.0) physics.CreateSleepThresholdAttr(0.0) # Contact loads are needed while the drive is idle. mass = UsdPhysics.MassAPI.Apply(body.GetPrim()) mass.CreateMassAttr(p["mass_kg"]) mass.CreateCenterOfMassAttr( Gf.Vec3f(0, 0, dynamics["chassis_com_height_m"] - p["body_contact_height_m"]) ) mass.CreateDiagonalInertiaAttr(Gf.Vec3f(*dynamics["chassis_inertia_kg_m2"])) def collision(prim): UsdPhysics.CollisionAPI.Apply(prim) contact = PhysxSchema.PhysxCollisionAPI.Apply(prim) contact.CreateContactOffsetAttr(p["contact_offset_m"]) contact.CreateRestOffsetAttr(0.0) body_shapes = [] components = body_colliders(document) if components is None: hull = UsdGeom.Cube.Define(stage, body.GetPath().AppendChild('hull')) hull.CreateSizeAttr(1) hull.AddTranslateOp().Set(Gf.Vec3d(0, 0, .24-source_com_z)) hull.AddScaleOp().Set(Gf.Vec3f(p['length_m'], document['mechanics']['inner_gap_m'], .24)) body_shapes.append(hull) else: for index, component in enumerate(components): hull = UsdGeom.Mesh.Define(stage, body.GetPath().AppendChild(f'body_{index}')) hull.CreatePointsAttr([[x,y,z-source_com_z] for x,y,z in component['points_m']]) hull.CreateFaceVertexCountsAttr([len(f) for f in component['faces']]) hull.CreateFaceVertexIndicesAttr([i for f in component['faces'] for i in f]) hull.CreateSubdivisionSchemeAttr(UsdGeom.Tokens.none) UsdPhysics.MeshCollisionAPI.Apply(hull.GetPrim()).CreateApproximationAttr('convexHull') body_shapes.append(hull) for hull in body_shapes: collision(hull.GetPrim()) for name, sign in (("left", 1), ("right", -1)): material = UsdShade.Material.Define(stage, root_path + "/" + name + "_belt_material") material_physics = UsdPhysics.MaterialAPI.Apply(material.GetPrim()) material_physics.CreateStaticFrictionAttr(dynamics["static_friction_coefficient"]) material_physics.CreateDynamicFrictionAttr(dynamics["friction_coefficient"]) material_physics.CreateRestitutionAttr(0.0) PhysxSchema.PhysxMaterialAPI.Apply(material.GetPrim()).CreateFrictionCombineModeAttr("min") y = sign * p["track_width_m"] / 2 vertices = [ [ float(x), y + edge * document["mechanics"]["track_width_m"] / 2, float(z) - source_com_z, ] for edge in (-1, 1) for x, z in outline ] n = len(outline) faces = [list(range(n - 1, -1, -1)), list(range(n, 2 * n))] faces += [[i, (i + 1) % n, (i + 1) % n + n, i + n] for i in range(n)] mesh = UsdGeom.Mesh.Define(stage, body.GetPath().AppendChild(name + "_belt")) mesh.CreatePointsAttr(vertices) mesh.CreateFaceVertexCountsAttr([len(f) for f in faces]) mesh.CreateFaceVertexIndicesAttr([v for face in faces for v in face]) mesh.CreateSubdivisionSchemeAttr(UsdGeom.Tokens.none) collision(mesh.GetPrim()) UsdPhysics.MeshCollisionAPI.Apply(mesh.GetPrim()).CreateApproximationAttr("convexHull") UsdShade.MaterialBindingAPI.Apply(mesh.GetPrim()).Bind( material, UsdShade.Tokens.weakerThanDescendants, "physics" ) if visual_asset is not None: mesh.CreateVisibilityAttr(UsdGeom.Tokens.invisible) if visual_asset is not None: for hull in body_shapes: hull.CreateVisibilityAttr(UsdGeom.Tokens.invisible) visual = UsdGeom.Xform.Define(stage, body.GetPath().AppendChild("DCD006")) visual.GetPrim().GetReferences().AddReference(str(visual_asset)) visual.AddTranslateOp().Set(Gf.Vec3d(0, 0, -p["body_contact_height_m"])) class TrackedDrive: def __init__(self, document, root_path, contact_filter_paths): import omni.physx import omni.usd from isaacsim.core.experimental.prims import RigidPrim from isaacsim.core.simulation_manager import PhysicsScene from pxr import UsdPhysics self.document = document self.p = document["tracked_contact"] self.physics = document["physics"] self.root_path = root_path self.contact_filter_paths = tuple(contact_filter_paths) self.stage = omni.usd.get_context().get_stage() scenes = PhysicsScene.get_physics_scene_paths(self.stage) if len(scenes) != 1: raise ValueError("Tracked contact requires one declared physics scene") self.gravity = np.array(PhysicsScene(scenes[0]).get_gravity(), dtype=float) self.body = RigidPrim( root_path + "/chassis", contact_filter_paths=contact_filter_paths, max_contact_count=self.p["max_contact_count"], ) self.query = omni.physx.get_physx_scene_query_interface() self.model = TrackDynamics(self.p, self.physics["mass_kg"]) self.target = np.zeros(2) self.mode = self.p["zero_mode"] self.metrics = {} self.contact_frame = None self.contact_outline = belt_outline(document['visual']['motion'], self.p['belt_pad_extent_m']) self.source_com_z = float(self.contact_outline[:, 1].min()) + self.p['chassis_com_height_m'] self.materials = {} self.belt_materials = [ UsdPhysics.MaterialAPI( self.stage.GetPrimAtPath(root_path + "/" + side + "_belt_material") ) for side in ("left", "right") ] # Scene creation starts at rest with both transmissions held, including # the initial settling frames before the first command callback. self.held = np.ones(2, dtype=bool) self.native_coefficients = [ (self.p["static_friction_coefficient"], self.p["friction_coefficient"]) for _ in range(2) ] def update_hold(self, normal_loads): requested = ( np.abs(self.target) < 1e-8 if self.mode in {"drive", "hold"} and self.p["zero_mode"] == "hold" else np.zeros(2, dtype=bool) ) self.held = requested & ( self.held | (np.abs(self.model.belt_mps) <= self.p["lock_capture_speed_mps"]) ) for side, material in enumerate(self.belt_materials): coefficients = hold_material_coefficients(self.p, normal_loads[side], self.held[side]) if coefficients != self.native_coefficients[side]: material.GetStaticFrictionAttr().Set(coefficients[0]) material.GetDynamicFrictionAttr().Set(coefficients[1]) self.native_coefficients[side] = coefficients def command(self, velocity, yaw_rate=0.0, *, mode=None): half = self.physics["track_width_m"] / 2 self.target = np.array([velocity - yaw_rate * half, velocity + yaw_rate * half]) self.mode = mode or (self.p["zero_mode"] if np.max(np.abs(self.target)) < 1e-8 else "drive") def side_speeds(self): return self.model.belt_mps.tolist() def friction(self, path): from pxr import UsdPhysics, UsdShade if path not in self.materials: prim = self.stage.GetPrimAtPath(path) material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial("physics") if not material: raise ValueError("Support surface has no declared physics material") coefficient = UsdPhysics.MaterialAPI(material.GetPrim()).GetDynamicFrictionAttr().Get() self.materials[path] = min(self.p["friction_coefficient"], float(coefficient)) return self.materials[path] def ground_hit(self, point, normal): hits = [] errors = [] def collect(hit): try: path = str(hit.collision) if not path.startswith(self.root_path + "/"): hits.append( { "collision": path, "distance": float(hit.distance), "position": tuple(hit.position), "normal": tuple(hit.normal), } ) return True except Exception as error: # PhysX logs and swallows callback exceptions. Re-raise after # dispatch so a query failure cannot masquerade as no ground. errors.append(error) return False self.query.raycast_all( tuple(point + normal * 0.02), tuple(-normal), 0.04, collect, bothSides=True ) if errors: raise RuntimeError("Track support query failed") from errors[0] return min(hits, key=lambda h: h["distance"]) if hits else None def step(self, dt): from pxr import Gf xyz, quaternion = self.body.get_world_poses() centre, q = xyz.numpy()[0].astype(float), quaternion.numpy()[0].astype(float) rotation = np.asarray(Gf.Matrix3d(Gf.Quatd(q[0], Gf.Vec3d(*q[1:])))).T centre += rotation[:, 2] * ( self.p["chassis_com_height_m"] - self.physics["body_contact_height_m"] ) # Native points describe contact generation before the preceding # integration. Label their collider region in that same body frame. # Using the newly integrated pose can move an inner belt edge into # the chassis gap, silently discarding its normal load during a turn. contact_centre, contact_rotation = ( (centre, rotation) if self.contact_frame is None else self.contact_frame ) linear, angular = self.body.get_velocities() # CPU tensor views can alias buffers reused by subsequent contact or # friction queries. Keep one immutable contact-generation snapshot. data = [a.numpy().copy() for a in self.body.get_contact_force_data(dt=dt)] forces, points, normals, _, counts, starts = data if counts.sum() >= self.p["max_contact_count"]: raise RuntimeError("Track contact buffer exhausted") measured = [[], []] external = np.r_[self.gravity * self.physics["mass_kg"], np.zeros(3)] normal_total = np.zeros(3) for filter_index, (start, count) in enumerate(zip(starts.flat, counts.flat, strict=True)): for i in range(int(start), int(start + count)): load = float(forces[i, 0]) # Reconstructed meshes can generate hundreds of proximity # contacts but only a few carry force. Zero load contributes # neither a wrench nor traction: do not run CAD classification # for each dormant point at every physics step. if load == 0: continue normal_force = normals[i] * load normal_total += normal_force external[:3] += normal_force external[3:] += np.cross(points[i] - centre, normal_force) side = belt_contact_side( points[i], contact_centre, contact_rotation, self.document["mechanics"]["inner_gap_m"], outline=self.contact_outline, source_com_z=self.source_com_z, belt_width=self.document['mechanics']['track_width_m'], ) if load <= 0 or side is None: continue if abs(np.dot(normals[i], contact_rotation[:, 1])) > 0.5: continue measured[side].append( ( points[i].astype(float), normals[i].astype(float), load, self.friction( self.contact_filter_paths[filter_index % len(self.contact_filter_paths)] ), ) ) contacts = [] measured_fallback_sides = [] for side, records in enumerate(measured): if not records: continue total = sum(r[2] for r in records) average = sum(r[0] * r[2] for r in records) / total normal = sum(r[1] * r[2] for r in records) / total normal /= np.linalg.norm(normal) local_points = [(rotation.T @ (r[0] - centre))[0] for r in records] low, high = min(local_points), max(local_points) samples = [] # An aggregate pressure patch, constrained by real ray hits. # Endpoints retain point support when a belt tips onto an edge. for x in np.linspace(low, high, 9) if high - low > 0.02 else [(low + high) / 2]: point = average + rotation[:, 0] * (x - (rotation.T @ (average - centre))[0]) hit = self.ground_hit(point, normal) if hit is not None: samples.append( ( float((rotation.T @ (np.array(hit["position"]) - centre))[0]), np.array(hit["position"]), np.array(hit["normal"]), self.friction(str(hit["collision"])), ) ) centre_x = float((rotation.T @ (average - centre))[0]) patch, fallback = pressure_patch(side, records, samples, centre_x) contacts.extend(patch) if fallback: measured_fallback_sides.append(side) self.update_hold([sum(r[2] for r in records) for records in measured]) friction_forces, friction_points, friction_counts, friction_starts = ( a.numpy().copy() for a in self.body.get_friction_data(dt=dt) ) native_reaction = np.zeros(2) for start, count in zip(friction_starts.flat, friction_counts.flat, strict=True): for i in range(int(start), int(start + count)): point, tangent_force = friction_points[i], friction_forces[i] external[:3] += tangent_force external[3:] += np.cross(point - centre, tangent_force) side = belt_contact_side( point, contact_centre, contact_rotation, self.document["mechanics"]["inner_gap_m"], outline=self.contact_outline, source_com_z=self.source_com_z, belt_width=self.document['mechanics']['track_width_m'], ) if side is not None: native_reaction[side] += np.dot(tangent_force, rotation[:, 0]) force, torque, self.metrics = self.model.step( self.target, contacts, rotation, linear.numpy()[0], angular.numpy()[0], centre, dt, self.mode, external_wrench=external, held_sides=self.held, ) self.metrics["native_friction_coefficients"] = self.native_coefficients self.metrics["native_hold_reaction_nm"] = ( native_reaction * self.p["drive_sprocket_effective_radius_m"] ).tolist() self.metrics["predictor_external_wrench"] = external.tolist() self.metrics["native_contact_count"] = int(counts.sum()) self.metrics["native_normal_force_n"] = normal_total.tolist() self.metrics["reported_normal_force_n"] = ( self.body.get_contact_force_matrix(dt=dt).numpy().sum(axis=(0, 1)).tolist() ) self.metrics["contact_geometry_frame"] = { "centre": contact_centre.tolist(), "rotation": contact_rotation.tolist(), "prior_step": self.contact_frame is not None, } self.metrics["measured_contact_fallback_sides"] = measured_fallback_sides self.metrics["native_contacts"] = [ { "load_n": float(forces[i, 0]), "point": points[i].tolist(), "normal": normals[i].tolist(), } for start, count in zip(starts.flat, counts.flat, strict=True) for i in range(int(start), int(start + count)) if forces[i, 0] != 0 ] self.metrics["native_loaded_contact_count"] = len(self.metrics["native_contacts"]) self.metrics["supports"] = [ { "side": c[0], "point": c[1].tolist(), "normal": c[2].tolist(), "load_n": c[3], "friction": c[4], } for c in contacts ] self.body.apply_forces_and_torques_at_pos(force, torque, positions=centre) self.contact_frame = (centre.copy(), rotation.copy()) def belt_contact_side(point, contact_centre, contact_rotation, inner_gap_m, *, outline=None, source_com_z=0, belt_width=None): """Classify native geometry using its contact-generation pose, not now. This only labels a measured contact. World points, loads, support queries, force application and PhysX integration remain unchanged. """ local = contact_rotation.T @ (point-contact_centre) local_y = float(local[1]) if abs(local_y) < inner_gap_m / 2 - 0.002: return None if outline is not None: if abs(local_y) > inner_gap_m/2 + belt_width + .01: return None # Frame/motor contacts must never masquerade as driven belt contacts. # CAD and native convex cooking/contact tolerances bound this shell. xz = local[[0, 2]] + [0, source_com_z] edges = np.roll(outline, -1, axis=0)-outline along = np.clip(np.einsum('ij,ij->i',xz-outline,edges) / np.maximum(np.sum(edges*edges,axis=1),1e-12),0,1) if np.min(np.linalg.norm(outline+along[:,None]*edges-xz,axis=1)) > .02: return None return 0 if local_y > 0 else 1 def pressure_patch(side, records, samples, centre_x): """Prefer a resolved pressure line; retain native contacts on irregular mesh. A belt's force-bearing contacts can lie on different lateral strips or heights. Their average line may cross a hole even though the real contacts are supported. In that case use the exact measured points, normals, loads and filtered terrain materials, preserving their full centre of pressure. Never move those loads onto a surviving synthetic point across a gap. """ xs = np.array([s[0] for s in samples]) normals = np.array([r[1] for r in records]) mixed_faces = np.min(normals @ normals.T) < math.cos(math.radians(2)) if mixed_faces or not len(xs) or not xs.min() - 0.002 <= centre_x <= xs.max() + 0.002: return [ (side, point, normal, load, friction) for point, normal, load, friction in records ], True total = sum(r[2] for r in records) weights = np.ones(len(samples)) if np.ptp(xs) > 1e-5: lo, hi = -1000.0, 1000.0 for _ in range(32): factor = (lo + hi) / 2 exponent = factor * (xs - xs.mean()) weights = np.exp(exponent - exponent.max()) if np.dot(weights, xs) / weights.sum() < centre_x: lo = factor else: hi = factor weights /= weights.sum() return [ (side, point, normal, total * weight, friction) for (_, point, normal, friction), weight in zip(samples, weights, strict=True) ], False def hold_material_coefficients(profile, normal_load, held): """Finite shaft capacity bounds native friction while a belt is locked. The ground's own material still applies via PhysX `min` combination, so a locked transmission does not anchor the chassis to ice or to empty space. This isotropic cap is conservative for side forces at high contact loads. """ if not math.isfinite(normal_load) or normal_load < 0: raise ValueError("Invalid hold normal load") if not held: return 0.0, 0.0 cap = profile["max_hold_torque_nm"] / ( profile["drive_sprocket_effective_radius_m"] * max(normal_load, 1e-9) ) return min(profile["static_friction_coefficient"], cap), min( profile["friction_coefficient"], cap )