Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 | 1x 1x 1x 1x 339x 339x 339x 339x 339x 339x 339x 339x 339x 339x 339x 339x 339x 339x 339x 339x 339x 339x 339x 339x 339x 339x 339x 339x 339x 678x 678x 678x 678x 339x 339x 339x 339x 339x 339x 339x 339x 339x 678x 339x 339x 339x 339x 339x 339x 339x 339x 339x 339x 339x 339x 339x 339x 339x 339x 339x 339x 678x 339x 339x 1017x 678x 678x 678x 678x 339x 339x 339x 339x 339x 339x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 678x 1017x 339x 339x 2034x 1356x 1356x 2034x 339x 339x 278x 278x 278x 278x 278x 278x 278x 278x 278x 278x 278x 339x 774x 774x 774x 91x 774x 683x 683x 774x 6x 774x 768x 768x 774x 6x 6x 774x 339x 83x 83x 83x 83x 83x 83x 83x 339x 76x 76x 76x 76x 339x 339x 96x 96x 192x 192x 192x 192x 192x 192x 192x 96x 192x 192x 192x 192x 96x 96x 96x 96x 96x 96x 96x 95x 95x 96x 1x 1x 96x 96x 339x 339x 5454x 5454x 5454x 5454x 5454x 5454x 5454x 5454x 5454x 5454x 5454x 5454x 1915x 1915x 170x 170x 1915x 1915x 1915x 1915x 1915x 1915x 5454x 3539x 3539x 5454x 32724x 32724x 32724x 21816x 21816x 21816x 10908x 10908x 10908x 32724x 3830x 3830x 3830x 3830x 1915x 1915x 1915x 1915x 3830x 32724x 32724x 21816x 21816x 21816x 21816x 21816x 21816x 21816x 21816x 16362x 21816x 10908x 10908x 21816x 21816x 4797x 4797x 4797x 4797x 4797x 4797x 4797x 4797x 4797x 4797x 4797x 4797x 4797x 4797x 4797x 4797x 4797x 21816x 6109x 6109x 6109x 6109x 6109x 6109x 6109x 6109x 6109x 6109x 6109x 6109x 6109x 6109x 6109x 6109x 6109x 6109x 6109x 6109x 6109x 6109x 6109x 6109x 6109x 6109x 6109x 21816x 32724x 10908x 5454x 2168x 2168x 2168x 2168x 2168x 2168x 2168x 2166x 2166x 2168x 2x 2x 2168x 4334x 4334x 4334x 4334x 4334x 4334x 5454x 3286x 3286x 3286x 5454x 339x 53x 318x 318x 53x 53x 339x 2992x 2992x 2992x 2992x 2992x 2992x 339x 5911x 5911x 339x 89x 89x 89x 89x 89x 89x 89x 89x 178x 178x 178x 178x 89x 89x 89x 89x 89x 89x 89x 89x 89x 178x 178x 178x 178x 178x 178x 178x 178x 178x 178x 178x 178x 178x 178x 178x 178x 89x 178x 178x 178x 178x 178x 89x 534x 534x 534x 89x 339x | import RAPIER from '@dimforge/rapier3d-compat';
import { RobotAssemblySpec } from '../cad/types';
import { VirtualMotor, MotorPort } from './motor-controller';
if (!Object.prototype.hasOwnProperty.call(VirtualMotor.prototype, 'targetVelocityDegPerSec')) {
Object.defineProperty(VirtualMotor.prototype, 'targetVelocityDegPerSec', {
get(this: VirtualMotor) {
return this.targetSpeedDegPerSec;
},
set(this: VirtualMotor, v: number) {
this.targetSpeedDegPerSec = v;
},
configurable: true,
});
}
export interface SpawnPose {
x: number;
y: number;
z: number;
yawDegrees: number;
}
export class RobotPhysicsBody {
public world: RAPIER.World;
public spec: RobotAssemblySpec;
public chassisBody!: RAPIER.RigidBody;
public wheelBodies: Map<string, RAPIER.RigidBody> = new Map();
public motors: Map<MotorPort, VirtualMotor> = new Map();
public joints: Map<string, RAPIER.UnitImpulseJoint> = new Map();
// Robot physical specs
public wheelRadius = 0.028; // 56mm diameter / 2 = 28mm radius
public trackWidth = 0.128; // 128mm (16 studs)
// Active drivebase ports and wheel cluster tracking
public driveLeftPort: MotorPort = 'A';
public driveRightPort: MotorPort = 'B';
public leftWheelClusterId: string | null = null;
public rightWheelClusterId: string | null = null;
constructor(world: RAPIER.World, spec: RobotAssemblySpec, spawnPose: SpawnPose) {
this.world = world;
this.spec = spec;
this.spawn(spawnPose);
}
public spawn(pose: SpawnPose): void {
const yawRad = (pose.yawDegrees * Math.PI) / 180;
const halfYaw = yawRad / 2;
const qy = Math.sin(halfYaw);
const qw = Math.cos(halfYaw);
const cosY = Math.cos(yawRad);
const sinY = Math.sin(yawRad);
const rotateLocal = (dx: number, dy: number, dz: number) => ({
x: dx * cosY + dz * sinY,
y: dy,
z: -dx * sinY + dz * cosY,
});
// 1. Root Chassis Rigid Body
const rootCluster = this.spec.clusters.find((c) => c.isRootChassis) || this.spec.clusters[0];
const chassisDesc = RAPIER.RigidBodyDesc.dynamic()
.setTranslation(pose.x, pose.y, pose.z)
.setRotation({ x: 0, y: qy, z: 0, w: qw })
.setLinearDamping(0.5)
.setAngularDamping(2.0)
.setAdditionalMass(rootCluster.totalMassKg);
this.chassisBody = this.world.createRigidBody(chassisDesc);
// Add main chassis frame colliders (elevated slightly above ground)
for (const c of rootCluster.colliders) {
if (c.shape === 'sphere') {
const sphereDesc = RAPIER.ColliderDesc.ball(c.radius || 0.01)
.setTranslation(c.offset[0], c.offset[1], c.offset[2])
.setFriction(c.friction ?? 0.0)
.setRestitution(0.0)
.setDensity(0.0);
this.world.createCollider(sphereDesc, this.chassisBody);
} else {
const colDesc = RAPIER.ColliderDesc.cuboid(
c.halfExtents ? c.halfExtents[0] : 0.044,
c.halfExtents ? c.halfExtents[1] : 0.012,
c.halfExtents ? c.halfExtents[2] : 0.050
)
.setTranslation(c.offset[0], c.offset[1], c.offset[2])
.setFriction(c.friction)
.setRestitution(0.0)
.setMass(rootCluster.totalMassKg);
this.world.createCollider(colDesc, this.chassisBody);
}
}
// 2. Drive Wheels & Revolute Joints
const nonRootClusters = this.spec.clusters.filter((c) => !c.isRootChassis);
for (const cluster of nonRootClusters) {
if (cluster.name === 'Drive Wheel') {
const jointSpec = this.spec.joints.find((j) => j.childClusterId === cluster.clusterId);
const anchor = jointSpec?.anchorParent || [0, 0, 0];
const isLeft = anchor[0] < 0;
if (isLeft) {
this.leftWheelClusterId = cluster.clusterId;
if (jointSpec?.motorPort) this.driveLeftPort = jointSpec.motorPort;
} else {
this.rightWheelClusterId = cluster.clusterId;
if (jointSpec?.motorPort) this.driveRightPort = jointSpec.motorPort;
}
const port = jointSpec?.motorPort || (isLeft ? this.driveLeftPort : this.driveRightPort);
// Rotate wheel local position into world space
const rotatedAnchor = rotateLocal(anchor[0], anchor[1], anchor[2]);
const wheelPos = {
x: pose.x + rotatedAnchor.x,
y: pose.y + rotatedAnchor.y,
z: pose.z + rotatedAnchor.z,
};
const wheelDesc = RAPIER.RigidBodyDesc.dynamic()
.setTranslation(wheelPos.x, wheelPos.y, wheelPos.z)
.setRotation({ x: 0, y: qy, z: 0, w: qw })
.setLinearDamping(0.2)
.setAngularDamping(0.5);
const wheelBody = this.world.createRigidBody(wheelDesc);
// Use roundCylinder with 3mm rounded tire edge radius (total radius 28mm, width 26mm).
// This models the rounded rubber tire crown and eliminates sharp cylinder edge singularities
// that cause normal-flipping contact impulses on flat surfaces.
const wheelColliderDesc = RAPIER.ColliderDesc.roundCylinder(
0.010, // halfHeight core
0.025, // radius core
0.003 // borderRadius: 0.025 + 0.003 = 0.028m radius (56mm diameter)
)
.setRotation({ x: 0, y: 0, z: 0.7071, w: 0.7071 }) // Cylinder axis along X
.setFriction(0.9) // High rubber traction
.setRestitution(0.0) // Completely inelastic
.setMass(cluster.totalMassKg || 0.04);
this.world.createCollider(wheelColliderDesc, wheelBody);
this.wheelBodies.set(cluster.clusterId, wheelBody);
// Revolute joint connecting wheel to chassis (mechanical axle constraint)
const anchorChassis = { x: anchor[0], y: anchor[1], z: anchor[2] };
const anchorWheel = { x: 0, y: 0, z: 0 };
const axis = { x: 1, y: 0, z: 0 };
const jointParams = RAPIER.JointData.revolute(anchorChassis, anchorWheel, axis);
const impulseJoint = this.world.createImpulseJoint(
jointParams,
this.chassisBody,
wheelBody,
true
) as RAPIER.UnitImpulseJoint;
// Disable contact solver between wheel and chassis bodies to avoid jitter
impulseJoint.setContactsEnabled(false);
// Free rotation around axle: motors exert direct physical torque rather than constraint velocity
impulseJoint.setMotorMaxForce(0.0);
impulseJoint.configureMotorVelocity(0.0, 0.0);
if (jointSpec) {
this.joints.set(jointSpec.jointId, impulseJoint);
}
// Register virtual motor
if (port) {
this.motors.set(port, new VirtualMotor(port));
}
}
}
// Ensure all 6 standard SPIKE Prime ports (A-F) are initialized
const allPorts: MotorPort[] = ['A', 'B', 'C', 'D', 'E', 'F'];
for (const p of allPorts) {
if (!this.motors.has(p)) {
this.motors.set(p, new VirtualMotor(p));
}
}
}
/**
* Sets active drive wheel motor ports, dynamically updating left and right wheel assignments.
*/
public setDrivePorts(leftPort: MotorPort, rightPort: MotorPort): void {
this.driveLeftPort = leftPort;
this.driveRightPort = rightPort;
if (this.leftWheelClusterId) {
const jL = this.spec.joints.find((j) => j.childClusterId === this.leftWheelClusterId);
if (jL) jL.motorPort = leftPort;
}
if (this.rightWheelClusterId) {
const jR = this.spec.joints.find((j) => j.childClusterId === this.rightWheelClusterId);
if (jR) jR.motorPort = rightPort;
}
}
/**
* Set continuous driving speeds for configured drivebase ports (left & right)
*/
public setDriveSpeeds(leftPercent: number, rightPercent: number): void {
const motorL = this.motors.get(this.driveLeftPort);
const motorR = this.motors.get(this.driveRightPort);
if (Math.abs(leftPercent) < 0.1) {
motorL?.stop('BRAKE');
} else {
motorL?.start(leftPercent);
}
if (Math.abs(rightPercent) < 0.1) {
motorR?.stop('BRAKE');
} else {
motorR?.start(rightPercent);
}
if (Math.abs(leftPercent) < 0.1 && Math.abs(rightPercent) < 0.1) {
this.brakeChassisAndWheels();
}
}
/**
* Set continuous speed for a specific motor port
*/
public setMotorSpeed(port: MotorPort, speedPercent: number): void {
const motor = this.motors.get(port);
if (!motor) return;
if (Math.abs(speedPercent) < 0.1) {
motor.stop('BRAKE');
const isDrivePort = port === this.driveLeftPort || port === this.driveRightPort;
if (isDrivePort) {
const spdL = this.motors.get(this.driveLeftPort)?.targetSpeedDegPerSec ?? 0;
const spdR = this.motors.get(this.driveRightPort)?.targetSpeedDegPerSec ?? 0;
if (Math.abs(spdL) < 0.1 && Math.abs(spdR) < 0.1) {
this.brakeChassisAndWheels();
}
}
} else {
motor.start(speedPercent);
}
}
/**
* Stop an individual motor port with electromagnetic brake
*/
public stopMotor(port: MotorPort): void {
this.motors.get(port)?.stop('BRAKE');
const isDrivePort = port === this.driveLeftPort || port === this.driveRightPort;
if (isDrivePort) {
const spdL = this.motors.get(this.driveLeftPort)?.targetSpeedDegPerSec ?? 0;
const spdR = this.motors.get(this.driveRightPort)?.targetSpeedDegPerSec ?? 0;
if (Math.abs(spdL) < 0.1 && Math.abs(spdR) < 0.1) {
this.brakeChassisAndWheels();
}
}
}
public onBrakeEngaged?: () => void;
/**
* Applies an active electromagnetic brake to wheels and chassis, bringing the robot to an
* immediate standstill without coasting or micro-creeping across the mat.
*/
public brakeChassisAndWheels(): void {
this.straightTargetYaw = null;
for (const wb of this.wheelBodies.values()) {
wb.resetForces(true);
wb.resetTorques(true);
wb.setAngularDamping(50.0);
wb.setAngvel({ x: 0, y: 0, z: 0 }, true);
const wLin = wb.linvel();
wb.setLinvel({ x: 0, y: wLin.y, z: 0 }, true);
}
for (const joint of this.joints.values()) {
try {
(joint as any).configureMotorVelocity(0.0, 5.0);
} catch (_) {}
}
this.chassisBody.resetForces(true);
this.chassisBody.resetTorques(true);
this.chassisBody.setAngularDamping(20.0);
this.chassisBody.setLinearDamping(20.0);
const lin = this.chassisBody.linvel();
const horizSpd = Math.sqrt(lin.x * lin.x + lin.z * lin.z);
if (horizSpd < 0.35) {
this.chassisBody.setLinvel({ x: 0, y: lin.y, z: 0 }, true);
this.chassisBody.setAngvel({ x: 0, y: 0, z: 0 }, true);
} else {
// Rapid deceleration simulating rubber tire skidding to dead stop
this.chassisBody.setLinvel({ x: lin.x * 0.2, y: lin.y, z: lin.z * 0.2 }, true);
}
this.onBrakeEngaged?.();
}
public straightTargetYaw: number | null = null;
/**
* Applies motor target speeds using direct speed-governed physical torque each physics tick.
* This accurately reflects real-world LEGO SPIKE large motors (0.25-0.45 Nm torque) without
* triggering Rapier constraint-solver fighting on high-friction mats.
* Includes active straight-line gyro assist to prevent veering/turning when driving straight.
*/
public updateMotors(dt: number): void {
const rot = this.chassisBody.rotation();
// Axle unit vector in world space: rotate local axle (1, 0, 0) by chassis orientation quaternion
const ux = 1 - 2 * (rot.y * rot.y + rot.z * rot.z);
const uy = 2 * (rot.x * rot.y + rot.z * rot.w);
const uz = 2 * (rot.x * rot.z - rot.y * rot.w);
const nonRootClusters = this.spec.clusters.filter((c) => !c.isRootChassis);
let anyDriveActive = false;
// Detect straight-line driving between configured Drive Motors
const spdL = this.motors.get(this.driveLeftPort)?.targetSpeedDegPerSec ?? 0;
const spdR = this.motors.get(this.driveRightPort)?.targetSpeedDegPerSec ?? 0;
const isDrivingStraight =
Math.abs(spdL) >= 1.0 && Math.abs(spdR) >= 1.0 && Math.abs(spdL - spdR) < 1.0;
let yawError = 0;
if (isDrivingStraight) {
const curYaw = this.getYawDegrees();
if (this.straightTargetYaw === null) {
this.straightTargetYaw = curYaw;
}
yawError = curYaw - this.straightTargetYaw;
while (yawError > 180) yawError -= 360;
while (yawError < -180) yawError += 360;
// Active Gyro Drive Assist (SPIKE Prime IMU straight-line heading lock)
// Restoring counter-yaw torque prevents mat contact drag or caster friction from veering
const Kyaw = 0.008;
const yawRestoringTorque = Math.max(-0.05, Math.min(0.05, -yawError * Kyaw));
this.chassisBody.addTorque({ x: 0, y: yawRestoringTorque, z: 0 }, true);
} else {
this.straightTargetYaw = null;
}
for (const [port, motor] of this.motors.entries()) {
const isDriveLeft = port === this.driveLeftPort;
const isDriveRight = port === this.driveRightPort;
// Non-drive / auxiliary motors step independently and never touch drive wheel physics
if (!isDriveLeft && !isDriveRight) {
motor.step(dt);
continue;
}
// Drive wheels
const targetDegPerSec = motor.targetSpeedDegPerSec;
const isIdle = Math.abs(targetDegPerSec) < 1.0;
let targetRadPerSec = (targetDegPerSec * Math.PI) / 180;
// Differential wheel speed trim to keep wheels in lockstep
if (isDrivingStraight && !isIdle) {
const trimGain = 0.05;
const trim = Math.max(-1.5, Math.min(1.5, yawError * trimGain));
const sign = targetDegPerSec > 0 ? 1 : -1;
if (isDriveLeft) {
targetRadPerSec -= trim * sign;
} else if (isDriveRight) {
targetRadPerSec += trim * sign;
}
}
for (const cluster of nonRootClusters) {
if (cluster.name === 'Drive Wheel') {
const jointSpec = this.spec.joints.find((j) => j.childClusterId === cluster.clusterId);
const anchorX = jointSpec?.anchorParent[0] ?? 0;
const isLeftWheel =
cluster.clusterId === this.leftWheelClusterId || anchorX < 0;
const isRightWheel =
cluster.clusterId === this.rightWheelClusterId || anchorX > 0;
// Discriminate physical wheel match: only the assigned drive port actuates its wheel
const isWheelMatch =
(isDriveLeft && isLeftWheel) ||
(isDriveRight && isRightWheel);
if (!isWheelMatch) continue;
const wb = this.wheelBodies.get(cluster.clusterId);
if (!wb) continue;
const joint = jointSpec ? this.joints.get(jointSpec.jointId) : undefined;
if (isIdle) {
// Electromagnetic holding brake: remove spin along axle vector u while preserving yaw rate (w_y)
wb.setAngularDamping(0.5);
const wAng = wb.angvel();
const axleSpin = wAng.x * ux + wAng.y * uy + wAng.z * uz;
wb.setAngvel(
{
x: wAng.x - axleSpin * ux,
y: wAng.y - axleSpin * uy,
z: wAng.z - axleSpin * uz,
},
true
);
if (joint) {
try {
(joint as any).configureMotorVelocity(0.0, 5.0);
} catch (_) {}
}
motor.step(dt, 0);
} else {
anyDriveActive = true;
if (joint) {
try {
(joint as any).configureMotorVelocity(0.0, 0.0);
} catch (_) {}
}
this.chassisBody.wakeUp();
wb.wakeUp();
wb.setAngularDamping(0.2);
const wAng = wb.angvel();
const currentSpin = wAng.x * ux + wAng.y * uy + wAng.z * uz;
// Record physical measured spin in motor
motor.step(dt, currentSpin);
const spinError = targetRadPerSec - currentSpin;
const Kp = 0.005; // Smooth stable velocity governor for low-inertia wheels
const maxTorque = 0.06; // 0.06 Nm max drive torque eliminates slippage and reaction flipping
const torque = Math.max(-maxTorque, Math.min(maxTorque, spinError * Kp));
wb.addTorque({ x: torque * ux, y: torque * uy, z: torque * uz }, true);
const spinAcc = Math.max(-2.0, Math.min(2.0, (torque / 0.001) * dt));
wb.setAngvel(
{
x: wAng.x + spinAcc * ux,
y: wAng.y + spinAcc * uy,
z: wAng.z + spinAcc * uz,
},
true
);
}
}
}
}
if (!anyDriveActive) {
// Both drive motors idle: apply holding brake to chassis and wheels to eliminate residual coasting
this.chassisBody.resetForces(true);
this.chassisBody.resetTorques(true);
this.chassisBody.setLinearDamping(20.0);
this.chassisBody.setAngularDamping(20.0);
const cv = this.chassisBody.linvel();
const horizSpd = Math.sqrt(cv.x * cv.x + cv.z * cv.z);
if (horizSpd < 0.30) {
this.chassisBody.setLinvel({ x: 0, y: cv.y, z: 0 }, true);
this.chassisBody.setAngvel({ x: 0, y: 0, z: 0 }, true);
} else {
this.chassisBody.setLinvel({ x: cv.x * 0.4, y: cv.y, z: cv.z * 0.4 }, true);
}
for (const wb of this.wheelBodies.values()) {
wb.resetForces(true);
wb.resetTorques(true);
wb.setLinvel({ x: 0, y: wb.linvel().y, z: 0 }, true);
wb.setAngvel({ x: 0, y: 0, z: 0 }, true);
wb.setAngularDamping(50.0);
}
} else {
// Actively driving: standard chassis damping
this.chassisBody.setLinearDamping(0.5);
this.chassisBody.setAngularDamping(2.0);
}
}
/**
* Immediately stops all virtual drive and auxiliary motors with electromagnetic brake
*/
public stopAllMotors(): void {
for (const motor of this.motors.values()) {
motor.stop('BRAKE');
}
this.brakeChassisAndWheels();
}
public getYawDegrees(): number {
const rot = this.chassisBody.rotation();
const siny_cosp = 2 * (rot.w * rot.y - rot.z * rot.x);
const cosy_cosp = 1 - 2 * (rot.y * rot.y + rot.x * rot.x);
const yawRad = Math.atan2(siny_cosp, cosy_cosp);
return (yawRad * 180) / Math.PI;
}
public getPosition(): { x: number; y: number; z: number } {
return this.chassisBody.translation();
}
public reset(pose: SpawnPose): void {
this.straightTargetYaw = null;
const yawRad = (pose.yawDegrees * Math.PI) / 180;
const halfYaw = yawRad / 2;
const qy = Math.sin(halfYaw);
const qw = Math.cos(halfYaw);
const cosY = Math.cos(yawRad);
const sinY = Math.sin(yawRad);
const rotateLocal = (dx: number, dy: number, dz: number) => ({
x: dx * cosY + dz * sinY,
y: dy,
z: -dx * sinY + dz * cosY,
});
// 1. Reset root chassis body
this.chassisBody.setLinvel({ x: 0, y: 0, z: 0 }, true);
this.chassisBody.setAngvel({ x: 0, y: 0, z: 0 }, true);
this.chassisBody.resetForces(true);
this.chassisBody.resetTorques(true);
this.chassisBody.setLinearDamping(20.0);
this.chassisBody.setAngularDamping(20.0);
this.chassisBody.setTranslation({ x: pose.x, y: pose.y, z: pose.z }, true);
this.chassisBody.setRotation({ x: 0, y: qy, z: 0, w: qw }, true);
// 2. Reset wheel bodies
for (const [clusterId, wheelBody] of this.wheelBodies.entries()) {
const jointSpec = this.spec.joints.find((j) => j.childClusterId === clusterId);
const anchor = jointSpec?.anchorParent || [0, 0, 0];
const rotatedAnchor = rotateLocal(anchor[0], anchor[1], anchor[2]);
wheelBody.setLinvel({ x: 0, y: 0, z: 0 }, true);
wheelBody.setAngvel({ x: 0, y: 0, z: 0 }, true);
wheelBody.resetForces(true);
wheelBody.resetTorques(true);
wheelBody.setAngularDamping(50.0);
wheelBody.setLinearDamping(20.0);
wheelBody.setTranslation({
x: pose.x + rotatedAnchor.x,
y: pose.y + rotatedAnchor.y,
z: pose.z + rotatedAnchor.z,
}, true);
wheelBody.setRotation({ x: 0, y: qy, z: 0, w: qw }, true);
}
// 3. Reset joint motors & constraint damping
for (const joint of this.joints.values()) {
try {
(joint as any).configureMotorVelocity(0.0, 0.0);
(joint as any).setMotorMaxForce(0.0);
} catch (_) {}
}
// 4. Reset motors
for (const motor of this.motors.values()) {
motor.resetDegrees();
motor.stop('BRAKE');
}
}
}
|