All files / src main.ts

0% Statements 0/774
0% Branches 0/1
0% Functions 0/1
0% Lines 0/774

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 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
import { SimulationPhysicsEngine } from './physics/engine';
import { Viewport3D } from './view/viewport';
import { Robot3DRenderer } from './view/robot-renderer';
import { MotorPort } from './physics/motor-controller';
import { VirtualSensorManager } from './sensors/sensor-manager';
import { VirtualSpikeApi } from './runtime/spike-api';
import { PythonScriptRunner } from './runtime/python-runner';
import { SimulatorHud } from './ui/hud';
import { LDrawImporter } from './cad/ldraw-importer';
import { RobotAssemblySpec } from './cad/types';
import { MissionManager } from './missions/mission-manager';
import { SandboxInteractionTool } from './sandbox/interaction-tool';
import { CustomImportedMissionElement } from './missions/custom-imported-element';
import { FieldLayoutManager } from './missions/field-layout-manager';
import { CadModelInspector } from './ui/cad-inspector';
import './ui/cad-inspector.css';
import { profiler } from './core/performance-profiler';
import { getFllAdvanceDrivingBaseSpec, getFllCompactDrivingBaseSpec } from './cad/models/advance-driving-base';
 
async function bootstrapSimulator() {
  const viewportContainer = document.getElementById('viewport-container');
  if (!viewportContainer) {
    throw new Error('Viewport container element not found');
  }
 
  // 1. Initialize Rapier3D Physics Engine
  const engine = new SimulationPhysicsEngine();
  await engine.init();
 
  // 2. Initialize Three.js WebGL Viewport
  const viewport = new Viewport3D(viewportContainer);
 
  // 3. Initialize Sensor Manager & Hook to Competition Mat
  const sensors = new VirtualSensorManager(engine.robot);
  sensors.setMatSampler(viewport.matTexture);
 
  // 4. Initialize 3D Robot Visual Representation
  const robotRenderer = new Robot3DRenderer();
  robotRenderer.setSensorManager(sensors);
  viewport.scene.add(robotRenderer.rootGroup);
  viewport.setRobotVisualRoot(robotRenderer.rootGroup);
 
  // 5. Initialize Mission Elements Manager & Interactive Sandbox Tool (starts with clean field)
  const missionManager = new MissionManager();
  missionManager.init(engine.world, viewport.scene, {
    loadSampleMechanisms: false,
    autoLoadSeasonMissions: false,
  });
 
  const interactionTool = new SandboxInteractionTool();
  interactionTool.init(engine.world, viewport.scene);
  interactionTool.setActive(false); // Inactive until sandbox mode
  viewport.setInteractionTool(interactionTool);
  viewport.setMissionManager(missionManager);
 
  // Helper to synchronize all mission elements to HUD Asset Drawer
  const syncHudMissionElements = () => {
    const allElems = missionManager.getAllElements().map((elem) => ({
      id: elem.id,
      name: elem.name,
      description: elem.description,
      sourceFile: elem.sourceFile,
      isPlacedOnField: elem.isPlacedOnField !== false,
      position: elem.getPosition(),
      yawDegrees: elem.getYawDegrees ? elem.getYawDegrees() : 0,
      isCustom: elem instanceof CustomImportedMissionElement,
      isDualLocked: elem.isDualLocked ?? (elem instanceof CustomImportedMissionElement ? elem.getIsBaseFixed() : true),
    }));
    hud.setMissionElements(allElems, missionManager.getSeasonMissionsStatus());
  };
  missionManager.onMissionListChanged = syncHudMissionElements;
 
  // 6. Initialize Virtual SPIKE Prime API & Python Runner
  let api = new VirtualSpikeApi(engine, sensors);
  let runner = new PythonScriptRunner(api);
 
  // Setup automatic safety sanity recovery handler
  engine.onSanityReset = (reason: string) => {
    runner.abort();
    engine.robot.stopAllMotors();
    hud.stopAllManualDriving();
    sensors.resetYaw();
    hud.setExecutionState('ERROR');
    hud.logConsole(`⚠️ [Safety Sanity System] Robot reset to Launch Area: ${reason}`);
  };
 
  // 6. Initialize Simulator HUD & Controls
  let cadInspector: CadModelInspector;
  let hud: SimulatorHud;
  hud = new SimulatorHud(document.body, {
    onRunScript: async (code: string) => {
      hud.stopAllManualDriving();
      hud.logConsole('Executing SPIKE Python script...');
      runner.stepDelayMs = 40;
      try {
        await runner.execute(
          code,
          (msg) => {
            hud.logConsole(msg);
            hud.logCommand('PROGRAM', 'print()', msg);
          },
          (lineNum) => {
            hud.setExecutingLine(lineNum);
          },
          false
        );
        hud.setExecutionState('IDLE');
        hud.clearExecutingLine();
        hud.logConsole('Script completed successfully.');
      } catch (err: any) {
        hud.setExecutionState('ERROR');
        hud.clearExecutingLine();
        hud.logConsole(`Runtime Error: ${err.message || err}`);
      } finally {
        engine.robot.stopAllMotors();
      }
    },
    onPauseScript: () => {
      runner.pause();
      hud.setExecutionState('PAUSED');
      hud.logConsole('⏸ Script execution paused.');
    },
    onResumeScript: () => {
      runner.resume();
      hud.setExecutionState('RUNNING');
      hud.logConsole('▶ Script execution resumed.');
    },
    onStepScript: async (code?: string) => {
      if (runner.isPaused) {
        runner.step();
      } else {
        hud.stopAllManualDriving();
        const codeToRun = code || hud.getActiveCode();
        runner.stepDelayMs = 0;
        try {
          await runner.execute(
            codeToRun,
            (msg) => {
              hud.logConsole(msg);
              hud.logCommand('PROGRAM', 'print()', msg);
            },
            (lineNum) => {
              hud.setExecutingLine(lineNum);
            },
            true
          );
          hud.setExecutionState('IDLE');
          hud.clearExecutingLine();
          hud.logConsole('Script completed successfully.');
        } catch (err: any) {
          hud.setExecutionState('ERROR');
          hud.clearExecutingLine();
          hud.logConsole(`Runtime Error: ${err.message || err}`);
        } finally {
          engine.robot.stopAllMotors();
        }
      }
    },
    onStopScript: () => {
      runner.abort();
      engine.robot.stopAllMotors();
      hud.stopAllManualDriving();
      hud.clearExecutingLine();
      hud.setExecutionState('IDLE');
    },
    onResetRobot: () => {
      runner.abort();
      engine.robot.stopAllMotors();
      hud.stopAllManualDriving();
      hud.clearExecutingLine();
      const spawnPose = hud.getSpawnPose();
      engine.resetRobot(spawnPose);
      viewport.setRobotYaw(spawnPose.yawDegrees);
      sensors.resetYaw();
      const mappings = hud.getPortMappings();
      const isPort = (p: string): p is MotorPort => ['A', 'B', 'C', 'D', 'E', 'F'].includes(p);
      const left = isPort(mappings.driveLeft) ? mappings.driveLeft : 'A';
      const right = isPort(mappings.driveRight) ? mappings.driveRight : 'B';
      engine.robot.setDrivePorts?.(left, right);
      missionManager.resetAll();
      hud.setExecutionState('IDLE');
    },
    onSpawnPoseChange: (pose) => {
      engine.setDefaultPose(pose);
      viewport.setRobotYaw(pose.yawDegrees);
    },
    onMoveRobotToPose: (pose, label) => {
      runner.abort();
      engine.robot.stopAllMotors();
      hud.stopAllManualDriving();
      engine.resetRobot(pose);
      engine.setDefaultPose(pose);
      viewport.setRobotYaw(pose.yawDegrees);
      sensors.resetYaw();
      const mappings = hud.getPortMappings();
      const isPort = (p: string): p is MotorPort => ['A', 'B', 'C', 'D', 'E', 'F'].includes(p);
      const left = isPort(mappings.driveLeft) ? mappings.driveLeft : 'A';
      const right = isPort(mappings.driveRight) ? mappings.driveRight : 'B';
      engine.robot.setDrivePorts?.(left, right);
      hud.setExecutionState('IDLE');
      hud.setSpawnPose(pose);
      const targetName = label || `(X=${pose.x.toFixed(2)}m, Z=${pose.z.toFixed(2)}m, Yaw=${pose.yawDegrees.toFixed(1)}°)`;
      hud.logConsole(`⏹ Stopped run and relocated robot to: ${targetName}`);
    },
    onCaptureCurrentPose: () => {
      const pos = engine.robot.getPosition();
      const yaw = engine.robot.getYawDegrees();
      const pose = {
        x: Number(pos.x.toFixed(2)),
        y: 0.035,
        z: Number(pos.z.toFixed(2)),
        yawDegrees: Number(yaw.toFixed(1)),
      };
      hud.setSpawnPose(pose);
      engine.setDefaultPose(pose);
      viewport.setRobotYaw(pose.yawDegrees);
      hud.logConsole(`📌 Captured current pose: X=${pose.x}m, Z=${pose.z}m, Yaw=${pose.yawDegrees}°`);
    },
    onCameraChange: (preset) => {
      viewport.setCameraPreset(preset);
    },
    onMapChange: async (mapType) => {
      hud.logConsole(`Loading map "${mapType}"...`);
      await viewport.matTexture.loadMap(mapType);
      hud.logConsole(`Map updated.`);
    },
    onImportFile: async (file: File) => {
      hud.logConsole(`Loading robot model "${file.name}"...`);
      try {
        let spec;
        if (file.name.endsWith('.io')) {
          const buffer = await file.arrayBuffer();
          spec = await LDrawImporter.parseStudioIo(buffer);
        } else {
          const text = await file.text();
          const parsed = LDrawImporter.parseLDrawText(text, file.name);
          const { CadClusteringPreSolver } = await import('./cad/clustering-solver');
          spec = CadClusteringPreSolver.solve(parsed);
        }
 
        // Re-spawn robot with imported CAD specification
        await engine.init(spec);
        hud.logConsole(`Imported robot "${file.name}" successfully! Clustered into ${spec.clusters.length} rigid bodies.`);
      } catch (err: any) {
        hud.logConsole(`Robot CAD Import Failed: ${err.message || err}`);
      }
    },
    onImportMissionElement: async (file: File) => {
      hud.logConsole(`Importing mission model "${file.name}" into asset library...`);
      try {
        let spec;
        if (file.name.endsWith('.io')) {
          const buffer = await file.arrayBuffer();
          spec = await LDrawImporter.parseStudioIo(buffer);
        } else {
          const text = await file.text();
          const parsed = LDrawImporter.parseLDrawText(text, file.name);
          const { CadClusteringPreSolver } = await import('./cad/clustering-solver');
          spec = CadClusteringPreSolver.solve(parsed);
        }
 
        const customElem = new CustomImportedMissionElement(spec, {
          id: `custom_${Date.now()}`,
          name: file.name.replace(/\.[^/.]+$/, ''),
          description: `Imported Studio/LDraw model (${file.name})`,
          sourceFile: file.name,
          isBaseFixed: spec.clusters.length > 1,
        });
 
        // Place on field mat
        customElem.init(missionManager.getWorld(), { x: 0.10, y: 0.002, z: 0.20 }, 0);
        missionManager.registerCustomElement(customElem);
        syncHudMissionElements();
        viewport.selectMissionElement(customElem.id);
        hud.logConsole(`✅ Imported mission model "${file.name}"! Added to field and asset library.`);
      } catch (err: any) {
        hud.logConsole(`Mission Model Import Failed: ${err.message || err}`);
      }
    },
    onImportSpikeScratch: async (file: File) => {
      hud.logConsole(`🎯 Loaded SPIKE program "${file.name}" into Word Blocks editor.`);
    },
    onResetAllMissions: () => {
      missionManager.resetAll();
      interactionTool.resetAll();
      syncHudMissionElements();
      hud.logConsole('🔄 Reset all mission elements back to starting idle state.');
    },
    onElementTransformChange: (id, x, z, yaw) => {
      missionManager.setElementTransform(id, { x, y: 0.002, z }, yaw);
      viewport.updateElementTransform(id, { x, y: 0.002, z }, yaw);
    },
    onElementTogglePlaced: (id, placed) => {
      missionManager.setElementPlaced(id, placed);
      if (placed) {
        viewport.selectMissionElement(id);
      }
      syncHudMissionElements();
      hud.logConsole(`${placed ? 'Deployed' : 'Stowed'} element "${id}" ${placed ? 'on field' : 'in drawer'}.`);
    },
    onElementDelete: (id) => {
      missionManager.removeElement(id);
      syncHudMissionElements();
      viewport.selectMissionElement(null);
      hud.logConsole(`Removed mission element "${id}".`);
    },
    onElementFocus: (id) => {
      const elem = missionManager.getElement(id);
      if (elem) {
        viewport.selectMissionElement(id);
        viewport.focusOnElement(elem.getPosition());
      }
    },
    onFocusTarget: (target) => {
      if (target === 'robot') {
        viewport.selectMissionElement(null);
        viewport.focusOnElement(engine.robot.getPosition());
      } else if (target === 'center') {
        viewport.selectMissionElement(null);
        viewport.focusOnElement({ x: 0, y: 0.05, z: 0 });
      } else {
        const elem = missionManager.getElement(target);
        if (elem) {
          viewport.selectMissionElement(target);
          viewport.focusOnElement(elem.getPosition());
        }
      }
    },
    onToggleSeasonMission: async (id, enable) => {
      hud.logConsole(`${enable ? 'Loading' : 'Unloading'} season mission ${id}...`);
      try {
        await missionManager.toggleSeasonMission(id, enable);
        syncHudMissionElements();
        hud.logConsole(`✅ Season mission ${id} ${enable ? 'loaded onto mat' : 'unloaded'}.`);
      } catch (err: any) {
        hud.logConsole(`Failed to toggle season mission ${id}: ${err.message || err}`);
      }
    },
    onApplyMissionPreset: async (presetKey) => {
      hud.logConsole(`Applying mission preset "${presetKey}"...`);
      try {
        const loadedIds = await missionManager.applyMissionPreset(presetKey);
        syncHudMissionElements();
        hud.logConsole(`✅ Applied preset "${presetKey}": ${loadedIds.length > 0 ? loadedIds.join(', ') : 'None (cleared)'} active on mat.`);
      } catch (err: any) {
        hud.logConsole(`Failed to apply mission preset: ${err.message || err}`);
      }
    },
    onOpenInspector: (missionId?: string) => {
      const activePreset = hud ? hud.getActiveRobotPreset() : 'advanced';
      const targetId = missionId || (activePreset === 'compact' ? 'ROBOT_COMPACT' : 'ROBOT_DROIDBOT');
      if (targetId === 'ROBOT_DROIDBOT') {
        cadInspector.open('ROBOT_DROIDBOT');
        cadInspector.inspectSpec(getFllAdvanceDrivingBaseSpec(), 'DroidBot-E Advance Driving Base', 'ROBOT_DROIDBOT');
      } else if (targetId === 'ROBOT_COMPACT') {
        cadInspector.open('ROBOT_COMPACT');
        cadInspector.inspectSpec(getFllCompactDrivingBaseSpec(), 'Compact SPIKE Prime Base', 'ROBOT_COMPACT');
      } else {
        const elem = missionManager.getElement(targetId);
        if (elem && (elem as any).spec) {
          cadInspector.open(targetId);
          cadInspector.inspectSpec((elem as any).spec, elem.name, elem.id);
        } else {
          cadInspector.open(targetId);
        }
      }
    },
    onModeChange: (mode) => {
      missionManager.setMode(mode);
      viewport.setMode(mode);
      syncHudMissionElements();
      if (mode === 'ARENA') {
        interactionTool.setActive(false);
        viewport.setCameraPreset('ISO');
        engine.setRobotStationary(false);
        const spawnPose = hud.getSpawnPose();
        engine.resetRobot(spawnPose);
        viewport.setRobotYaw(spawnPose.yawDegrees);
        hud.logConsole('Switched to Competition Arena (4x8 ft mat).');
      } else {
        interactionTool.setActive(true);
        hud.setPusherActive(true);
        if (mode === 'SANDBOX_RISER') {
          interactionTool.setPusherInitialPose({ x: -0.22, y: 0.02, z: 0.0 });
        } else if (mode === 'SANDBOX_DIAL') {
          interactionTool.setPusherInitialPose({ x: 0.12, y: 0.02, z: 0.08 });
        } else if (mode === 'SANDBOX_CASCADE') {
          interactionTool.setPusherInitialPose({ x: -0.045, y: 0.02, z: 0.08 });
        }
        viewport.focusOnElement({ x: 0, y: 0.05, z: 0 });
        if (hud.isDynoModeActive()) {
          engine.setRobotStationary(true);
          engine.resetRobot({ x: 0.30, y: 0.035, z: 0.0, yawDegrees: -90 });
          viewport.setRobotYaw(-90);
        } else {
          engine.resetRobot({ x: 0, y: -20, z: 0, yawDegrees: 0 });
        }
        hud.logConsole(`Switched to Sandbox Mode. Mouse pusher tool active.`);
      }
    },
    onTogglePusherTool: (active) => {
      interactionTool.setActive(active);
    },
    onSpawnTestBlock: () => {
      interactionTool.spawnTestBlock();
    },
    onToggleDynoMode: (active) => {
      engine.setRobotStationary(active);
      if (missionManager.currentMode !== 'ARENA') {
        if (active) {
          engine.resetRobot({ x: 0.30, y: 0.035, z: 0.0, yawDegrees: -90 });
          viewport.setRobotYaw(-90);
          hud.logConsole('Robot mounted on Workbench Dyno Jig (facing mechanism, pinned in place).');
        } else {
          engine.resetRobot({ x: 0, y: -20, z: 0, yawDegrees: 0 });
          hud.logConsole('Robot parked off-stage (workbench cleared).');
        }
      }
    },
    onResetMission: () => {
      missionManager.resetCurrent();
      interactionTool.resetAll();
      syncHudMissionElements();
      if (missionManager.currentMode === 'SANDBOX_RISER') {
        interactionTool.setPusherInitialPose({ x: -0.22, y: 0.02, z: 0.0 });
      } else if (missionManager.currentMode === 'SANDBOX_DIAL') {
        interactionTool.setPusherInitialPose({ x: 0.12, y: 0.02, z: 0.08 });
      } else if (missionManager.currentMode === 'SANDBOX_CASCADE') {
        interactionTool.setPusherInitialPose({ x: -0.15, y: 0.02, z: 0.15 });
      }
      if (missionManager.currentMode !== 'ARENA' && hud.isDynoModeActive()) {
        engine.resetRobot({ x: 0.30, y: 0.035, z: 0.0, yawDegrees: -90 });
        viewport.setRobotYaw(-90);
      }
    },
    onToggleDualLockTool: (active, eraseMode) => {
      viewport.setDualLockToolActive(active, eraseMode);
    },
    onToggleDualLockSelected: () => {
      const selected = viewport.getSelectedElement();
      if (selected) {
        const willLock = !selected.isDualLocked;
        if (selected.setDualLocked) {
          selected.setDualLocked(willLock);
        }
        hud.setSelectedElement(selected.id, willLock, selected.name);
        hud.showFastenerStatus(`${willLock ? '🔒 Dual-Locked' : '🔓 Unfastened'}: "${selected.name}"`);
        hud.logConsole(`${willLock ? '🔒 [Dual Lock] Fastened' : '🔓 [Dual Lock] Unfastened'} "${selected.name}".`);
        syncHudMissionElements();
      }
    },
    onToggleDualLockElement: (id) => {
      const elem = missionManager.getElement(id);
      if (elem) {
        const willLock = !elem.isDualLocked;
        if (elem.setDualLocked) {
          elem.setDualLocked(willLock);
        }
        if (viewport.getSelectedElement()?.id === id) {
          hud.setSelectedElement(id, willLock, elem.name);
        }
        hud.showFastenerStatus(`${willLock ? '🔒 Dual-Locked' : '🔓 Unfastened'}: "${elem.name}"`);
        hud.logConsole(`${willLock ? '🔒 [Dual Lock] Fastened' : '🔓 [Dual Lock] Unfastened'} "${elem.name}".`);
        syncHudMissionElements();
      }
    },
    onSaveFieldLayout: () => {
      const layout = FieldLayoutManager.saveCurrentLayout(missionManager.getAllElements());
      const lockedCount = layout.elements.filter((e) => e.isDualLocked).length;
      hud.showFastenerStatus(`💾 Layout saved (${layout.elements.length} objects, ${lockedCount} Dual-Locked)`);
      hud.logConsole(`💾 [Layout] Saved custom field layout (${layout.elements.length} objects, ${lockedCount} Dual-Locked) to browser storage.`);
    },
    onLoadFieldLayout: async () => {
      const saved = FieldLayoutManager.loadSavedLayout();
      if (!saved) {
        hud.showFastenerStatus('⚠️ No saved layout found in browser storage');
        hud.logConsole('⚠️ [Layout] No saved field layout found in local storage.');
        return;
      }
      const { restoredCount, dualLockedCount } = await FieldLayoutManager.applyLayout(saved, missionManager);
      syncHudMissionElements();
      hud.showFastenerStatus(`📂 Restored layout (${restoredCount} objects, ${dualLockedCount} Dual-Locked)`);
      hud.logConsole(`📂 [Layout] Restored field layout (${restoredCount} objects, ${dualLockedCount} Dual-Locked).`);
    },
    onExportFieldLayout: () => {
      const layout = FieldLayoutManager.saveCurrentLayout(missionManager.getAllElements());
      FieldLayoutManager.exportLayoutToFile(layout);
      hud.logConsole(`📥 [Layout] Exported layout file "fll-competition-layout.json".`);
    },
    onImportFieldLayout: async (file) => {
      try {
        const data = await FieldLayoutManager.importLayoutFromFile(file);
        const { restoredCount, dualLockedCount } = await FieldLayoutManager.applyLayout(data, missionManager);
        syncHudMissionElements();
        hud.showFastenerStatus(`📤 Imported layout "${file.name}"`);
        hud.logConsole(`📤 [Layout] Successfully imported layout "${file.name}" (${restoredCount} objects, ${dualLockedCount} Dual-Locked).`);
      } catch (err: any) {
        hud.logConsole(`❌ [Layout] Import failed: ${err.message || err}`);
      }
    },
    onDualLockAllBases: () => {
      let count = 0;
      for (const elem of missionManager.getAllElements()) {
        if (elem.setDualLocked) {
          elem.setDualLocked(true);
          count++;
        }
      }
      syncHudMissionElements();
      hud.showFastenerStatus(`🔒 Dual-Locked all ${count} objects`);
      hud.logConsole(`🔒 [Dual Lock] Fastened all ${count} objects to the field mat.`);
    },
    onUnlockAllElements: () => {
      let count = 0;
      for (const elem of missionManager.getAllElements()) {
        if (elem.setDualLocked) {
          elem.setDualLocked(false);
          count++;
        }
      }
      syncHudMissionElements();
      hud.showFastenerStatus(`🔓 Released all ${count} objects (Dynamic)`);
      hud.logConsole(`🔓 [Dual Lock] Released all ${count} objects to dynamic physics.`);
    },
    onManualDriveBase: (leftSpeed: number, rightSpeed: number) => {
      engine.robot.setDriveSpeeds(leftSpeed, rightSpeed);
      hud.logCommand(
        'DRIVE',
        'WASD Keys',
        `DriveBase commanded: Left=${leftSpeed > 0 ? '+' : ''}${leftSpeed.toFixed(0)}%, Right=${rightSpeed > 0 ? '+' : ''}${rightSpeed.toFixed(0)}%`
      );
    },
    onManualDriveBaseStop: () => {
      engine.robot.setDriveSpeeds(0, 0);
      hud.logCommand('STOP', 'WASD Release', 'DriveBase stopped: Electromagnetic brake engaged (Left=0%, Right=0%)');
    },
    onManualMotorSpeed: (port, speed) => {
      engine.robot.setMotorSpeed(port, speed);
      hud.logCommand('MOTOR', `Port ${port}`, `Speed commanded: ${speed > 0 ? '+' : ''}${speed.toFixed(0)}%`);
    },
    onManualMotorStop: (port) => {
      engine.robot.stopMotor(port);
      hud.logCommand('STOP', `Port ${port}`, `Motor stopped: Brake engaged`);
    },
    onResetEncoders: () => {
      for (const m of engine.robot.motors.values()) {
        m.resetDegrees();
      }
      hud?.logConsole?.('🔄 Zeroed all virtual motor encoders.');
      hud?.logCommand?.('CMD', 'UI Button', 'Zeroed all motor encoders to 0.0°');
    },
    onResetGyro: () => {
      sensors.resetYaw();
      hud?.logConsole?.('🧭 Zeroed Gyro heading to 0.0°.');
      hud?.logCommand?.('CMD', 'UI Button', 'Calibrated and zeroed Gyro IMU heading to 0.0°');
    },
    onRobotPresetChange: (preset) => {
      robotRenderer.setRobotPreset(preset);
      hud?.logConsole?.(
        `🤖 Field robot visual model updated to: ${
          preset === 'advanced'
            ? 'DroidBot-E (Dual Color Sensors + Ultrasonic + Articulated Motor Arms)'
            : 'Compact SPIKE Base (Single Color Sensor)'
        }`
      );
    },
    onPortMappingChange: (mappings) => {
      const isPort = (p: string): p is MotorPort => ['A', 'B', 'C', 'D', 'E', 'F'].includes(p);
      const left = isPort(mappings.driveLeft) ? mappings.driveLeft : 'A';
      const right = isPort(mappings.driveRight) ? mappings.driveRight : 'B';
      engine.robot.setDrivePorts?.(left, right);
      hud?.logConsole?.(`⚙️ Updated drive wheel ports: Left=[${left}], Right=[${right}]`);
    },
  });
 
  // Sync initial robot visual preset and port mappings with HUD saved state
  robotRenderer.setRobotPreset(hud.getActiveRobotPreset());
  const initialPortMappings = hud.getPortMappings();
  const isPort = (p: string): p is MotorPort => ['A', 'B', 'C', 'D', 'E', 'F'].includes(p);
  const initLeft = isPort(initialPortMappings.driveLeft) ? initialPortMappings.driveLeft : 'A';
  const initRight = isPort(initialPortMappings.driveRight) ? initialPortMappings.driveRight : 'B';
  engine.robot.setDrivePorts?.(initLeft, initRight);
 
  engine.robot.onBrakeEngaged = () => {
    hud.logCommand('BRAKE', 'Physics Engine', 'Active electromagnetic brake: Chassis & wheels clamped (0.00 Nm torque)');
  };
 
  // 7. Initialize CAD Model Inspector & Diagnostic Validator
  cadInspector = new CadModelInspector({
    onDeployToField: async (missionId: string, customSpec?: RobotAssemblySpec) => {
      await missionManager.toggleSeasonMission(missionId, true, customSpec);
      syncHudMissionElements();
      viewport.selectMissionElement(missionId);
      const elem = missionManager.getElement(missionId);
      if (elem) {
        viewport.focusOnElement(elem.getPosition());
      }
      hud.logConsole(`🚀 Deployed inspected mission "${missionId}" to field mat.`);
    },
    onToggleSolidMode: (missionId: string, solid: boolean) => {
      const elem = missionManager.getElement(missionId);
      if (elem && elem instanceof CustomImportedMissionElement) {
        elem.setSolidRigidMode(solid);
        hud.logConsole(`⚙️ Set mission "${missionId}" physics mode: ${solid ? 'Solid Anchor' : 'Articulated Physics'}`);
      }
    },
  });
 
  // Initialize HUD spawn inputs with default pose
  const defaultPose = engine.getDefaultPose();
  hud.setSpawnPose(defaultPose);
  viewport.setRobotYaw(defaultPose.yawDegrees);
  syncHudMissionElements();
 
  // Hook 3D Viewport Interactive Drag-and-Drop Placement & Rotation
  viewport.onRobotDragStart = () => {
    runner.abort();
    engine.robot.stopAllMotors();
    hud.setExecutionState('IDLE');
  };
 
  viewport.onRobotRotate = (yawDegrees: number) => {
    const currentPose = hud.getSpawnPose();
    const updatedPose = { ...currentPose, yawDegrees };
    engine.resetRobot(updatedPose);
    engine.setDefaultPose(updatedPose);
    hud.setSpawnPose(updatedPose);
  };
 
  viewport.onRobotDragMove = (x: number, z: number, yawDegrees?: number) => {
    const currentPose = hud.getSpawnPose();
    const liveYaw = yawDegrees !== undefined ? yawDegrees : currentPose.yawDegrees;
    const livePose = {
      x: Number(x.toFixed(2)),
      y: 0.035,
      z: Number(z.toFixed(2)),
      yawDegrees: liveYaw,
    };
    engine.resetRobot(livePose);
    viewport.updateReticleYaw(liveYaw);
    hud.setSpawnPose(livePose);
  };
 
  viewport.onRobotDrop = (x: number, z: number, yawDegrees?: number) => {
    runner.abort();
    engine.robot.stopAllMotors();
    hud.setExecutionState('IDLE');
    const currentPose = hud.getSpawnPose();
    const finalYaw = yawDegrees !== undefined ? yawDegrees : currentPose.yawDegrees;
    const newPose = {
      x: Number(x.toFixed(2)),
      y: 0.035,
      z: Number(z.toFixed(2)),
      yawDegrees: finalYaw,
    };
    engine.resetRobot(newPose);
    engine.setDefaultPose(newPose);
    hud.setSpawnPose(newPose);
    viewport.setRobotYaw(finalYaw);
    sensors.resetYaw();
    hud.logConsole(`📍 Robot placed at (X: ${newPose.x}m, Z: ${newPose.z}m) Heading: ${newPose.yawDegrees}°.`);
  };
 
  // Hook Mission Element 3D Drag & Drop Placement
  viewport.onElementDragMove = (_id: string, _x: number, _z: number, _yaw: number) => {
    syncHudMissionElements();
  };
 
  viewport.onElementDrop = (id: string, x: number, z: number, yaw: number) => {
    syncHudMissionElements();
    hud.logConsole(`📍 Placed mission element "${id}" at (X: ${x.toFixed(2)}m, Z: ${z.toFixed(2)}m) Yaw: ${yaw.toFixed(0)}°`);
  };
 
  viewport.onElementSelected = (id: string | null) => {
    if (id) {
      const elem = missionManager.getElement(id);
      const isLocked = elem?.isDualLocked ?? (elem instanceof CustomImportedMissionElement ? elem.getIsBaseFixed() : true);
      hud.setSelectedElement(id, isLocked, elem?.name);
      hud.logConsole(`Selected mission element "${elem?.name || id}". Use mouse wheel or R key to rotate.`);
    } else {
      hud.setSelectedElement(null);
    }
  };
 
  viewport.onDualLockToggle = (elementId: string, locked: boolean) => {
    const elem = missionManager.getElement(elementId);
    hud.setSelectedElement(elementId, locked, elem?.name);
    hud.showFastenerStatus(`${locked ? '🔒 Dual-Locked' : '✂️ Unfastened'}: "${elem?.name || elementId}"`);
    hud.logConsole(`${locked ? '🔒 [Dual Lock] Fastened' : '✂️ [Dual Lock] Unfastened'} "${elem?.name || elementId}".`);
    syncHudMissionElements();
  };
 
  viewport.onHoverFastenerChange = (info) => {
    hud.setPointerToolInfo(info);
  };
 
  // 7. Main Animation & Physics Loop
  let lastTime = performance.now();
 
  function animate(now: number) {
    requestAnimationFrame(animate);
 
    const deltaSeconds = Math.min((now - lastTime) / 1000, 0.05);
    lastTime = now;
 
    profiler.startFrame(now);
 
    // Physics step
    const t0 = performance.now();
    engine.update(deltaSeconds);
    const t1 = performance.now();
    profiler.recordPhysicsTime(t1 - t0);
 
    // Sync visual meshes with physics bodies
    robotRenderer.syncWithPhysics(engine.robot);
    missionManager.update(deltaSeconds);
    interactionTool.syncVisuals();
    const t2 = performance.now();
    profiler.recordSyncTime(t2 - t1);
 
    // Update active mission element score chip in HUD
    const activeElem = missionManager.getActiveElement();
    if (activeElem) {
      hud.updateMissionScore(activeElem.getScore(), activeElem.isSolved());
    }
 
    // Camera follow update and live hit proxy synchronization
    const robotPos = engine.robot.getPosition();
    const robotYaw = engine.robot.getYawDegrees();
    viewport.updateCameraFollow(robotPos.x, robotPos.y, robotPos.z, robotYaw);
    viewport.updateRobotHitProxy(robotPos.x, robotPos.y, robotPos.z);
 
    // Render viewport
    viewport.render();
    const t3 = performance.now();
    profiler.recordRenderTime(t3 - t2);
 
    // Feed real-time render stats to profiler
    profiler.setRenderStats(viewport.getRenderStats());
 
    // Feed physics body counts to profiler
    let dynamicBodies = 0;
    let fixedBodies = 0;
    let totalBodies = 0;
    if (engine.world) {
      engine.world.forEachRigidBody((b) => {
        totalBodies++;
        if (b.isDynamic()) dynamicBodies++;
        else if (b.isFixed()) fixedBodies++;
      });
      profiler.setPhysicsStats({
        totalBodies,
        dynamicBodies,
        fixedBodies,
        colliders: engine.world.colliders.len(),
      });
    }
 
    // Sensors & telemetry
    const driveLeftPort = (engine.robot as any).driveLeftPort || 'A';
    const driveRightPort = (engine.robot as any).driveRightPort || 'B';
    const motorLeft = engine.robot.motors.get(driveLeftPort);
    const motorRight = engine.robot.motors.get(driveRightPort);
    const colorC = sensors.sampleColorSensor('C');
    const colorD = sensors.sampleColorSensor('D');
    const distCm = sensors.sampleDistanceSensor();
    const gyroYaw = sensors.getYaw();
    const t4 = performance.now();
    profiler.recordSensorsTime(t4 - t3);
 
    const allMotorsState: Record<
      string,
      {
        port: MotorPort;
        degrees: number;
        speed: number;
        targetPercent: number;
        status: 'IDLE' | 'RUNNING' | 'BRAKING';
      }
    > = {};
    for (const [port, m] of engine.robot.motors.entries()) {
      const isTargetActive = Math.abs(m.targetSpeedDegPerSec) > 0.1;
      const targetPct = Math.round((m.targetSpeedDegPerSec / m.maxSpeedDegPerSec) * 100);
      const measuredSpeed = Math.round(m.velocityDegPerSec || 0);
      const status: 'IDLE' | 'RUNNING' | 'BRAKING' = isTargetActive
        ? 'RUNNING'
        : Math.abs(measuredSpeed) > 1
        ? 'BRAKING'
        : 'IDLE';
 
      allMotorsState[port] = {
        port,
        degrees: Math.round(m.degrees || 0),
        speed: measuredSpeed,
        targetPercent: targetPct,
        status,
      };
    }
 
    const leftTargetPct = Math.round(((motorLeft?.targetSpeedDegPerSec || 0) / (motorLeft?.maxSpeedDegPerSec || 1000)) * 100);
    const rightTargetPct = Math.round(((motorRight?.targetSpeedDegPerSec || 0) / (motorRight?.maxSpeedDegPerSec || 1000)) * 100);
 
    hud.updateTelemetry({
      timeSeconds: now / 1000,
      matchTimerSeconds: 150,
      fps: profiler.getCurrentFps(),
      physicsHz: 60,
      robot: {
        x: robotPos.x,
        y: robotPos.y,
        z: robotPos.z,
        yawDegrees: robotYaw,
      },
      motors: {
        left: {
          port: driveLeftPort,
          degrees: Math.round(motorLeft?.degrees || 0),
          speed: Math.round(motorLeft?.velocityDegPerSec || 0),
          targetPercent: leftTargetPct,
          status: Math.abs(motorLeft?.targetSpeedDegPerSec || 0) > 0.1 ? 'RUNNING' : (Math.abs(motorLeft?.velocityDegPerSec || 0) > 1 ? 'BRAKING' : 'IDLE'),
        },
        right: {
          port: driveRightPort,
          degrees: Math.round(motorRight?.degrees || 0),
          speed: Math.round(motorRight?.velocityDegPerSec || 0),
          targetPercent: rightTargetPct,
          status: Math.abs(motorRight?.targetSpeedDegPerSec || 0) > 0.1 ? 'RUNNING' : (Math.abs(motorRight?.velocityDegPerSec || 0) > 1 ? 'BRAKING' : 'IDLE'),
        },
        all: allMotorsState,
      },
      sensors: {
        colorC: {
          reflectedLight: colorC.reflectedLight,
          color: colorC.color,
          rgb: colorC.rgb,
        },
        colorD: {
          reflectedLight: colorD.reflectedLight,
          color: colorD.color,
          rgb: colorD.rgb,
        },
        distanceCm: distCm,
        gyroYaw,
      },
    });
  }
 
  requestAnimationFrame(animate);
  hud.logConsole('FLL Simulator ready! Ready to run SPIKE Prime code.');
}
 
bootstrapSimulator().catch((err) => {
  console.error('Fatal initialization error:', err);
});