| <!DOCTYPE html> |
| <html lang="en"> |
| <head> |
| <meta charset="UTF-8"> |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> |
| <title>webXOS MIRROR IDE</title> |
| <meta name="theme-color" content="#000"> |
| <link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@400;500;700&family=Press+Start+2P&display=swap" rel="stylesheet"> |
| <script src="https://cdn.jsdelivr.net/npm/three@0.158.0/build/three.min.js"></script> |
| <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script> |
| <script src="https://cdn.jsdelivr.net/npm/pako@2.1.0/dist/pako.min.js"></script> |
| <style> |
| * { |
| margin: 0; |
| padding: 0; |
| box-sizing: border-box; |
| font-family: 'Orbitron', monospace; |
| image-rendering: pixelated; |
| } |
| |
| body { |
| background: #000; |
| color: #0f0; |
| overflow: hidden; |
| height: 100vh; |
| user-select: none; |
| } |
| |
| |
| #crt { |
| position: fixed; |
| inset: 0; |
| pointer-events: none; |
| z-index: 9999; |
| background: repeating-linear-gradient( |
| 0deg, |
| rgba(0, 40, 0, 0.03) 0px, |
| rgba(0, 40, 0, 0.03) 1px, |
| transparent 1px, |
| transparent 2px |
| ); |
| animation: scan 8s linear infinite; |
| } |
| |
| @keyframes scan { |
| 0% { background-position: 0 0; } |
| 100% { background-position: 0 100%; } |
| } |
| |
| |
| #banner { |
| position: absolute; |
| top: 0; |
| left: 0; |
| width: 100%; |
| height: 30px; |
| background: linear-gradient(90deg, rgba(255,0,255,0.9) 0%, rgba(0,255,255,0.9) 100%); |
| color: #000; |
| display: flex; |
| align-items: center; |
| justify-content: center; |
| font-size: 11px; |
| letter-spacing: 1px; |
| border-bottom: 2px solid #0ff; |
| z-index: 1000; |
| animation: glitch 4s infinite; |
| font-family: 'Press Start 2P', cursive; |
| } |
| |
| @keyframes glitch { |
| 0%, 100% { transform: translateX(0); } |
| 4% { transform: translateX(-1.5px); } |
| 8% { transform: translateX(1.5px); } |
| 95% { transform: translateX(0); } |
| } |
| |
| |
| #container { |
| position: relative; |
| width: 100vw; |
| height: 100vh; |
| overflow: hidden; |
| } |
| |
| |
| #threeContainer { |
| position: absolute; |
| top: 40px; |
| left: 0; |
| width: 100%; |
| height: calc(100% - 120px); |
| z-index: 1; |
| } |
| |
| canvas { |
| display: block; |
| } |
| |
| |
| #header { |
| position: absolute; |
| top: 30px; |
| left: 0; |
| width: 100%; |
| height: 40px; |
| background: linear-gradient(90deg, #000 0%, #0a0a0a 50%, #000 100%); |
| border-bottom: 1px solid #0f0; |
| display: flex; |
| align-items: center; |
| justify-content: space-between; |
| padding: 0 20px; |
| z-index: 100; |
| box-shadow: 0 0 20px rgba(0, 255, 0, 0.1); |
| } |
| |
| .logo { |
| font-size: 14px; |
| font-weight: 700; |
| letter-spacing: 1px; |
| color: #0f0; |
| text-shadow: 0 0 10px #0f0; |
| font-family: 'Press Start 2P', cursive; |
| } |
| |
| .status-indicator { |
| display: flex; |
| align-items: center; |
| gap: 10px; |
| } |
| |
| .status-dot { |
| width: 8px; |
| height: 8px; |
| border-radius: 50%; |
| background: #f00; |
| animation: pulse 2s infinite; |
| } |
| |
| .status-dot.active { |
| background: #0f0; |
| } |
| |
| @keyframes pulse { |
| 0%, 100% { opacity: 1; } |
| 50% { opacity: 0.5; } |
| } |
| |
| .status-text { |
| font-size: 12px; |
| color: #0f0; |
| } |
| |
| |
| #controlPanel { |
| position: absolute; |
| bottom: 0; |
| left: 0; |
| width: 100%; |
| height: 80px; |
| background: rgba(0, 10, 0, 0.95); |
| border-top: 2px solid #0f0; |
| display: flex; |
| align-items: center; |
| padding: 0 20px; |
| gap: 15px; |
| z-index: 100; |
| backdrop-filter: blur(5px); |
| } |
| |
| |
| .mirror-btn { |
| width: 52px; |
| height: 52px; |
| background: #000; |
| border: 2px solid #0f0; |
| color: #0f0; |
| font-size: 7px; |
| display: flex; |
| align-items: center; |
| justify-content: center; |
| cursor: pointer; |
| box-shadow: 2px 2px 0 #000; |
| transform: skew(-2deg); |
| transition: all 0.1s; |
| text-align: center; |
| line-height: 1.1; |
| flex-direction: column; |
| padding: 4px; |
| font-family: 'Press Start 2P', cursive; |
| } |
| |
| .mirror-btn:hover { |
| background: #0f0; |
| color: #000; |
| } |
| |
| .mirror-btn.active { |
| background: #0f0; |
| color: #000; |
| } |
| |
| .mirror-btn.danger { |
| border-color: #f00; |
| color: #f00; |
| } |
| |
| .mirror-btn.danger:hover { |
| background: #f00; |
| color: #fff; |
| } |
| |
| .btn-icon { |
| font-size: 16px; |
| margin-bottom: 2px; |
| } |
| |
| |
| .data-panel { |
| position: absolute; |
| background: rgba(0, 10, 0, 0.9); |
| border: 1px solid #0f0; |
| padding: 10px; |
| border-radius: 6px; |
| z-index: 10; |
| backdrop-filter: blur(5px); |
| } |
| |
| #telemetryPanel { |
| top: 80px; |
| right: 10px; |
| width: 250px; |
| } |
| |
| #progressPanel { |
| top: 80px; |
| left: 10px; |
| width: 220px; |
| } |
| |
| #patternPanel { |
| top: 220px; |
| left: 10px; |
| width: 220px; |
| border-color: #0ff; |
| } |
| |
| #fsdPanel { |
| top: 220px; |
| right: 10px; |
| width: 250px; |
| border-color: #ff00ff; |
| } |
| |
| #rewardPanel { |
| top: 360px; |
| right: 10px; |
| width: 250px; |
| border-color: #ffaa00; |
| } |
| |
| .panel-title { |
| font-size: 11px; |
| color: #0f0; |
| margin-bottom: 8px; |
| text-align: center; |
| font-family: 'Press Start 2P', cursive; |
| } |
| |
| .pattern-title { |
| color: #0ff; |
| } |
| |
| .fsd-title { |
| color: #ff00ff; |
| } |
| |
| .reward-title { |
| color: #ffaa00; |
| } |
| |
| .data-row { |
| display: flex; |
| justify-content: space-between; |
| margin: 4px 0; |
| font-size: 10px; |
| } |
| |
| .data-label { |
| color: #0a0; |
| } |
| |
| .data-value { |
| color: #0f0; |
| font-family: 'Courier New', monospace; |
| font-size: 10px; |
| } |
| |
| .pattern-value { |
| color: #0ff; |
| } |
| |
| .fsd-value { |
| color: #ff00ff; |
| } |
| |
| .reward-value { |
| color: #ffaa00; |
| } |
| |
| |
| .progress-bar-container { |
| width: 100%; |
| height: 6px; |
| background: #050; |
| border-radius: 3px; |
| margin: 8px 0; |
| overflow: hidden; |
| } |
| |
| .progress-bar { |
| height: 100%; |
| background: #0f0; |
| width: 0%; |
| transition: width 0.3s; |
| } |
| |
| |
| #waveVisualizer { |
| position: absolute; |
| bottom: 90px; |
| right: 10px; |
| width: 250px; |
| height: 80px; |
| background: rgba(0, 10, 0, 0.8); |
| border: 1px solid #0f0; |
| border-radius: 6px; |
| overflow: hidden; |
| z-index: 10; |
| backdrop-filter: blur(5px); |
| } |
| |
| |
| #pathVisualizer { |
| position: absolute; |
| bottom: 180px; |
| right: 10px; |
| width: 250px; |
| height: 150px; |
| background: rgba(0, 10, 0, 0.8); |
| border: 1px solid #0ff; |
| border-radius: 6px; |
| overflow: hidden; |
| z-index: 10; |
| backdrop-filter: blur(5px); |
| } |
| |
| |
| .toggle-btn { |
| position: absolute; |
| top: 10px; |
| z-index: 10; |
| width: 52px; |
| height: 52px; |
| } |
| |
| #viewToggle { |
| right: 150px; |
| top: 40px; |
| } |
| |
| #fullscreenBtn { |
| right: 210px; |
| top: 40px; |
| } |
| |
| #emergencyStop { |
| right: 10px; |
| top: 40px; |
| } |
| |
| |
| #messageOverlay { |
| position: fixed; |
| top: 50%; |
| left: 50%; |
| transform: translate(-50%, -50%); |
| background: rgba(0, 0, 0, 0.9); |
| border: 3px solid #0ff; |
| padding: 20px; |
| text-align: center; |
| display: none; |
| z-index: 2000; |
| pointer-events: none; |
| } |
| |
| .message-text { |
| color: #0ff; |
| font-size: 16px; |
| margin-bottom: 10px; |
| } |
| |
| .message-detail { |
| color: #0aa; |
| font-size: 12px; |
| } |
| |
| |
| #nnVisualizer { |
| position: absolute; |
| top: 360px; |
| left: 10px; |
| width: 220px; |
| height: 200px; |
| background: rgba(0, 10, 0, 0.8); |
| border: 1px solid #ff00ff; |
| border-radius: 6px; |
| overflow: hidden; |
| z-index: 10; |
| backdrop-filter: blur(5px); |
| } |
| |
| |
| @media (max-width: 768px) { |
| #controlPanel { |
| gap: 8px; |
| padding: 0 10px; |
| } |
| |
| .mirror-btn { |
| width: 45px; |
| height: 45px; |
| font-size: 6px; |
| } |
| |
| .data-panel { |
| transform: scale(0.9); |
| } |
| } |
| </style> |
| </head> |
| <body> |
| |
| <div id="banner">webXOS MIRROR IDE • DRONE DATASETS</div> |
| |
| |
| <div id="crt"></div> |
| |
| |
| <div id="messageOverlay"> |
| <div class="message-text" id="messageTitle">FSD TRAINING INITIALIZED</div> |
| <div class="message-detail" id="messageDetail">Neural Network: 256-128-64-32 • Learning Rate: 0.001</div> |
| </div> |
| |
| <div id="container"> |
| |
| <div id="threeContainer"></div> |
| |
| |
| <div id="header"> |
| <div class="logo">FSD TRAINER v3.0</div> |
| <div class="status-indicator"> |
| <div class="status-dot" id="statusDot"></div> |
| <div class="status-text" id="statusText">INITIALIZING ENHANCED FSD...</div> |
| </div> |
| </div> |
| |
| |
| <div id="telemetryPanel" class="data-panel"> |
| <div class="panel-title">DRONE TELEMETRY</div> |
| <div class="data-row"> |
| <span class="data-label">ALTITUDE:</span> |
| <span class="data-value" id="altitude">0.0m</span> |
| </div> |
| <div class="data-row"> |
| <span class="data-label">SPEED:</span> |
| <span class="data-value" id="speed">0.0m/s</span> |
| </div> |
| <div class="data-row"> |
| <span class="data-label">VEL X/Y/Z:</span> |
| <span class="data-value" id="velocity">0.0/0.0/0.0</span> |
| </div> |
| <div class="data-row"> |
| <span class="data-label">DIST TO TARGET:</span> |
| <span class="data-value" id="distanceToTarget">0.0m</span> |
| </div> |
| <div class="data-row"> |
| <span class="data-label">NEXT PORTAL:</span> |
| <span class="data-value" id="nextPortal">NW</span> |
| </div> |
| <div class="data-row"> |
| <span class="data-label">PATTERN STEP:</span> |
| <span class="data-value" id="patternStep">1/5</span> |
| </div> |
| <div class="data-row"> |
| <span class="data-label">COLLISIONS:</span> |
| <span class="data-value" id="collisionCount">0</span> |
| </div> |
| <div class="data-row"> |
| <span class="data-label">PATH LENGTH:</span> |
| <span class="data-value" id="pathLength">0.0m</span> |
| </div> |
| <div class="data-row"> |
| <span class="data-label">EFFICIENCY:</span> |
| <span class="data-value" id="efficiency">0%</span> |
| </div> |
| </div> |
| |
| |
| <div id="progressPanel" class="data-panel"> |
| <div class="panel-title">FSD TRAINING PROGRESS</div> |
| <div class="data-row"> |
| <span class="data-label">EPOCH:</span> |
| <span class="data-value" id="epochNumber">1</span> |
| </div> |
| <div class="data-row"> |
| <span class="data-label">ITERATION:</span> |
| <span class="data-value" id="iterationNumber">1</span> |
| </div> |
| <div class="data-row"> |
| <span class="data-label">TRAINING STEP:</span> |
| <span class="data-value" id="trainingStep">0</span> |
| </div> |
| <div class="progress-bar-container"> |
| <div class="progress-bar" id="patternProgressBar"></div> |
| </div> |
| <div class="data-row"> |
| <span class="data-label">EPOCH TIME:</span> |
| <span class="data-value" id="patternTime">0.0s</span> |
| </div> |
| <div class="data-row"> |
| <span class="data-label">BEST TIME:</span> |
| <span class="data-value" id="bestTime">∞</span> |
| </div> |
| <div class="data-row"> |
| <span class="data-label">EPOCH SCORE:</span> |
| <span class="data-value" id="epochScore">0.00</span> |
| </div> |
| </div> |
| |
| |
| <div id="patternPanel" class="data-panel"> |
| <div class="panel-title pattern-title">CRISS-CROSS PATTERN</div> |
| <div class="data-row"> |
| <span class="data-label">PATTERN:</span> |
| <span class="data-value pattern-value" id="patternSequence">NW→SE→NE→SW→CENTER</span> |
| </div> |
| <div class="data-row"> |
| <span class="data-label">CROSSINGS:</span> |
| <span class="data-value pattern-value" id="crossingCount">0</span> |
| </div> |
| <div class="data-row"> |
| <span class="data-label">OBSTACLE AVOID:</span> |
| <span class="data-value pattern-value" id="avoidanceScore">0.0</span> |
| </div> |
| <div class="data-row"> |
| <span class="data-label">SUCCESS RATE:</span> |
| <span class="data-value pattern-value" id="successRate">0%</span> |
| </div> |
| <div class="data-row"> |
| <span class="data-label">ENV DIFFICULTY:</span> |
| <span class="data-value pattern-value" id="difficultyLevel">1.0</span> |
| </div> |
| </div> |
| |
| |
| <div id="fsdPanel" class="data-panel"> |
| <div class="panel-title fsd-title">ENHANCED NEURAL NETWORK</div> |
| <div class="data-row"> |
| <span class="data-label">NETWORK:</span> |
| <span class="data-value fsd-value" id="networkArch">256-128-64-32</span> |
| </div> |
| <div class="data-row"> |
| <span class="data-label">LEARNING RATE:</span> |
| <span class="data-value fsd-value" id="learningRate">0.001</span> |
| </div> |
| <div class="data-row"> |
| <span class="data-label">EXPLORATION:</span> |
| <span class="data-value fsd-value" id="explorationRate">0.9</span> |
| </div> |
| <div class="data-row"> |
| <span class="data-label">Q-VALUE:</span> |
| <span class="data-value fsd-value" id="qValue">0.00</span> |
| </div> |
| <div class="data-row"> |
| <span class="data-label">TD-ERROR:</span> |
| <span class="data-value fsd-value" id="tdError">0.00</span> |
| </div> |
| <div class="data-row"> |
| <span class="data-label">MEMORY SIZE:</span> |
| <span class="data-value fsd-value" id="memorySize">0</span> |
| </div> |
| <div class="data-row"> |
| <span class="data-label">BATCH SIZE:</span> |
| <span class="data-value fsd-value" id="batchSize">32</span> |
| </div> |
| </div> |
| |
| |
| <div id="rewardPanel" class="data-panel"> |
| <div class="panel-title reward-title">REINFORCEMENT LEARNING</div> |
| <div class="data-row"> |
| <span class="data-label">CUM. REWARD:</span> |
| <span class="data-value reward-value" id="cumulativeReward">0.0</span> |
| </div> |
| <div class="data-row"> |
| <span class="data-label">AVG REWARD:</span> |
| <span class="data-value reward-value" id="avgReward">0.0</span> |
| </div> |
| <div class="data-row"> |
| <span class="data-label">REWARD/EPOCH:</span> |
| <span class="data-value reward-value" id="rewardPerEpoch">0.0</span> |
| </div> |
| <div class="data-row"> |
| <span class="data-label">POLICY LOSS:</span> |
| <span class="data-value reward-value" id="policyLoss">0.00</span> |
| </div> |
| <div class="data-row"> |
| <span class="data-label">VALUE LOSS:</span> |
| <span class="data-value reward-value" id="valueLoss">0.00</span> |
| </div> |
| <div class="data-row"> |
| <span class="data-label">TRAIN STEPS:</span> |
| <span class="data-value reward-value" id="trainSteps">0</span> |
| </div> |
| </div> |
| |
| |
| <canvas id="waveVisualizer"></canvas> |
| |
| |
| <canvas id="pathVisualizer"></canvas> |
| |
| |
| <canvas id="nnVisualizer"></canvas> |
| |
| |
| <div id="viewToggle" class="mirror-btn toggle-btn" title="Toggle FPV/3PV"> |
| <div class="btn-icon">👁️</div> |
| <div>VIEW</div> |
| </div> |
| |
| <div id="fullscreenBtn" class="mirror-btn toggle-btn" title="Toggle Fullscreen"> |
| <div class="btn-icon">⛶</div> |
| <div>FULL</div> |
| </div> |
| |
| <div id="emergencyStop" class="mirror-btn danger toggle-btn" title="Emergency Stop"> |
| <div class="btn-icon">⏹️</div> |
| <div>STOP</div> |
| </div> |
| |
| |
| <div id="controlPanel"> |
| <div class="mirror-btn" id="startBtn"> |
| <div class="btn-icon">⚡</div> |
| <div>START FSD</div> |
| </div> |
| |
| <div class="mirror-btn" id="pauseBtn"> |
| <div class="btn-icon">⏸️</div> |
| <div>PAUSE</div> |
| </div> |
| |
| <div class="mirror-btn" id="stopBtn"> |
| <div class="btn-icon">⏹️</div> |
| <div>RESET</div> |
| </div> |
| |
| <div class="mirror-btn" id="newEpochBtn"> |
| <div class="btn-icon">🔄</div> |
| <div>NEW EPOCH</div> |
| </div> |
| |
| <div class="mirror-btn" id="exportBtn"> |
| <div class="btn-icon">💾</div> |
| <div>EXPORT</div> |
| </div> |
| |
| <div style="margin-left: auto; display: flex; gap: 10px;"> |
| <div class="mirror-btn" id="trainingBtn" title="Training Settings"> |
| <div class="btn-icon">🧠</div> |
| <div>TRAIN</div> |
| </div> |
| |
| <div class="mirror-btn" id="speedBtn" title="Increase Learning Rate"> |
| <div class="btn-icon">🚀</div> |
| <div>LEARN+</div> |
| </div> |
| |
| <div class="mirror-btn" id="difficultyBtn" title="Increase Difficulty"> |
| <div class="btn-icon">🔥</div> |
| <div>HARD+</div> |
| </div> |
| </div> |
| </div> |
| </div> |
|
|
| <script> |
| |
| const FSD_CONFIG = { |
| |
| patternSequence: ['NW', 'SE', 'NE', 'SW', 'CENTER'], |
| currentStep: 0, |
| patternCompleted: false, |
| |
| |
| portalPositions: { |
| 'NW': new THREE.Vector3(-22, 5, 22), |
| 'NE': new THREE.Vector3(22, 5, 22), |
| 'SW': new THREE.Vector3(-22, 5, -22), |
| 'SE': new THREE.Vector3(22, 5, -22), |
| 'CENTER': new THREE.Vector3(0, 4, 0) |
| }, |
| |
| portals: {}, |
| activePortal: null, |
| |
| obstacles: [], |
| floatingObstacles: [], |
| |
| |
| dronePosition: new THREE.Vector3(0, 4, 0), |
| droneVelocity: new THREE.Vector3(0, 0, 0), |
| droneAcceleration: new THREE.Vector3(0, 0, 0), |
| droneRotation: new THREE.Euler(0, 0, 0), |
| droneTargetPosition: new THREE.Vector3(0, 4, 0), |
| |
| |
| pidController: { |
| kp: 0.8, |
| ki: 0.05, |
| kd: 0.2, |
| integral: new THREE.Vector3(0, 0, 0), |
| lastError: new THREE.Vector3(0, 0, 0) |
| }, |
| |
| |
| isTraining: false, |
| isPaused: false, |
| cameraMode: 'third', |
| epoch: 1, |
| iteration: 1, |
| trainingStep: 0, |
| stuckTimer: 0, |
| stuckThreshold: 3.0, |
| lastProgressTime: 0, |
| lastDistanceToTarget: 0, |
| |
| |
| networkArchitecture: [256, 128, 64, 32], |
| learningRate: 0.001, |
| explorationRate: 0.9, |
| discountFactor: 0.99, |
| tdError: 0, |
| policyLoss: 0, |
| valueLoss: 0, |
| |
| |
| memoryBuffer: [], |
| maxMemorySize: 50000, |
| batchSize: 32, |
| trainSteps: 0, |
| |
| |
| collisionCount: 0, |
| patternStartTime: 0, |
| patternBestTime: Infinity, |
| totalPathLength: 0, |
| lastPosition: new THREE.Vector3(0, 4, 0), |
| crossingCount: 0, |
| efficiencyScore: 0, |
| epochScore: 0, |
| successHistory: [], |
| |
| |
| environment: { |
| roomSize: 60, |
| obstacleCount: 15, |
| floatingCount: 12, |
| floatingMinSpeed: 0.2, |
| floatingMaxSpeed: 0.5, |
| bounceEnergy: 0.8, |
| obstacleRepulsion: 2.0, |
| difficultyLevel: 1.0 |
| }, |
| |
| |
| avoidanceMemory: [], |
| successfulPaths: [], |
| failedPaths: [], |
| actionHistory: [], |
| |
| |
| telemetryBuffer: [], |
| rewardBuffer: [], |
| maxBufferSize: 100000, |
| cumulativeReward: 0, |
| avgReward: 0, |
| rewardPerEpoch: [], |
| |
| |
| actionSpace: [ |
| |
| {type: 'forward', vector: new THREE.Vector3(0, 0, -1), weight: 1.0}, |
| {type: 'backward', vector: new THREE.Vector3(0, 0, 1), weight: 0.8}, |
| {type: 'left', vector: new THREE.Vector3(-1, 0, 0), weight: 0.8}, |
| {type: 'right', vector: new THREE.Vector3(1, 0, 0), weight: 0.8}, |
| {type: 'up', vector: new THREE.Vector3(0, 1, 0), weight: 0.6}, |
| {type: 'down', vector: new THREE.Vector3(0, -1, 0), weight: 0.6}, |
| |
| |
| {type: 'forward_left', vector: new THREE.Vector3(-0.7, 0, -0.7), weight: 0.9}, |
| {type: 'forward_right', vector: new THREE.Vector3(0.7, 0, -0.7), weight: 0.9}, |
| {type: 'backward_left', vector: new THREE.Vector3(-0.7, 0, 0.7), weight: 0.7}, |
| {type: 'backward_right', vector: new THREE.Vector3(0.7, 0, 0.7), weight: 0.7}, |
| |
| |
| {type: 'up_forward', vector: new THREE.Vector3(0, 0.5, -0.8), weight: 0.7}, |
| {type: 'up_left', vector: new THREE.Vector3(-0.5, 0.5, 0), weight: 0.7}, |
| {type: 'up_right', vector: new THREE.Vector3(0.5, 0.5, 0), weight: 0.7}, |
| {type: 'hover', vector: new THREE.Vector3(0, 0.1, 0), weight: 0.5} |
| ], |
| |
| |
| stateNormalization: { |
| positionScale: 30, |
| velocityScale: 20, |
| targetScale: 30, |
| distanceScale: 50 |
| } |
| }; |
| |
| |
| class EnhancedFSDNetwork { |
| constructor() { |
| this.layers = [256, 128, 64, 32]; |
| this.weights = []; |
| this.biases = []; |
| this.targetWeights = []; |
| this.targetBiases = []; |
| this.initializeWeights(); |
| this.copyToTarget(); |
| |
| |
| this.learningRate = 0.001; |
| this.clipEpsilon = 0.2; |
| this.valueCoeff = 0.5; |
| this.entropyCoeff = 0.01; |
| } |
| |
| initializeWeights() { |
| for (let i = 0; i < this.layers.length - 1; i++) { |
| const rows = this.layers[i + 1]; |
| const cols = this.layers[i]; |
| |
| |
| const scale = Math.sqrt(2.0 / cols); |
| const weightMatrix = []; |
| for (let r = 0; r < rows; r++) { |
| const row = []; |
| for (let c = 0; c < cols; c++) { |
| row.push((Math.random() * 2 - 1) * scale); |
| } |
| weightMatrix.push(row); |
| } |
| |
| this.weights.push(weightMatrix); |
| this.biases.push(new Array(rows).fill(0.01)); |
| } |
| } |
| |
| copyToTarget() { |
| this.targetWeights = JSON.parse(JSON.stringify(this.weights)); |
| this.targetBiases = JSON.parse(JSON.stringify(this.biases)); |
| } |
| |
| softUpdateTarget(tau = 0.01) { |
| for (let i = 0; i < this.weights.length; i++) { |
| for (let r = 0; r < this.weights[i].length; r++) { |
| for (let c = 0; c < this.weights[i][r].length; c++) { |
| this.targetWeights[i][r][c] = |
| tau * this.weights[i][r][c] + (1 - tau) * this.targetWeights[i][r][c]; |
| } |
| } |
| for (let j = 0; j < this.biases[i].length; j++) { |
| this.targetBiases[i][j] = |
| tau * this.biases[i][j] + (1 - tau) * this.targetBiases[i][j]; |
| } |
| } |
| } |
| |
| forward(input, useTarget = false) { |
| let current = input; |
| const weights = useTarget ? this.targetWeights : this.weights; |
| const biases = useTarget ? this.targetBiases : this.biases; |
| |
| const activations = [input]; |
| |
| for (let i = 0; i < weights.length; i++) { |
| const next = new Array(weights[i].length).fill(0); |
| |
| |
| for (let r = 0; r < weights[i].length; r++) { |
| let sum = biases[i][r]; |
| for (let c = 0; c < weights[i][r].length; c++) { |
| sum += weights[i][r][c] * current[c]; |
| } |
| |
| next[r] = Math.max(0.01 * sum, sum); |
| } |
| |
| activations.push(next); |
| current = next; |
| } |
| |
| return { |
| output: current, |
| activations: activations |
| }; |
| } |
| |
| |
| getPolicy(state) { |
| const input = this.stateToInput(state); |
| const result = this.forward(input); |
| |
| |
| const logits = result.output.slice(0, FSD_CONFIG.actionSpace.length); |
| const maxLogit = Math.max(...logits); |
| const expLogits = logits.map(l => Math.exp(l - maxLogit)); |
| const sumExp = expLogits.reduce((a, b) => a + b, 0); |
| |
| return expLogits.map(exp => exp / sumExp); |
| } |
| |
| |
| getValue(state) { |
| const input = this.stateToInput(state); |
| const result = this.forward(input); |
| return result.output[FSD_CONFIG.actionSpace.length]; |
| } |
| |
| |
| trainBatch(batch) { |
| if (batch.length === 0) return { policyLoss: 0, valueLoss: 0, tdError: 0 }; |
| |
| let totalPolicyLoss = 0; |
| let totalValueLoss = 0; |
| let totalTdError = 0; |
| |
| for (const experience of batch) { |
| const { state, action, reward, nextState, oldProbability, done } = experience; |
| |
| |
| const currentValue = this.getValue(state); |
| const nextValue = done ? 0 : this.getValue(nextState); |
| const targetValue = reward + FSD_CONFIG.discountFactor * nextValue; |
| const advantage = targetValue - currentValue; |
| |
| |
| const policy = this.getPolicy(state); |
| const newProbability = policy[action]; |
| |
| |
| const ratio = newProbability / (oldProbability + 1e-8); |
| const clippedRatio = Math.max(1 - this.clipEpsilon, Math.min(ratio, 1 + this.clipEpsilon)); |
| const policyLoss = -Math.min(ratio * advantage, clippedRatio * advantage); |
| |
| |
| const valueLoss = Math.pow(targetValue - currentValue, 2); |
| |
| |
| totalPolicyLoss += policyLoss; |
| totalValueLoss += valueLoss; |
| totalTdError += Math.abs(advantage); |
| |
| |
| this.applyUpdate(state, action, policyLoss, valueLoss); |
| } |
| |
| |
| this.softUpdateTarget(0.01); |
| |
| return { |
| policyLoss: totalPolicyLoss / batch.length, |
| valueLoss: totalValueLoss / batch.length, |
| tdError: totalTdError / batch.length |
| }; |
| } |
| |
| applyUpdate(state, action, policyLoss, valueLoss) { |
| |
| const input = this.stateToInput(state); |
| const result = this.forward(input); |
| |
| |
| const lastLayerIndex = this.weights.length - 1; |
| const actionIndex = action; |
| |
| |
| const policyGradient = policyLoss * this.learningRate; |
| for (let i = 0; i < this.weights[lastLayerIndex][actionIndex].length; i++) { |
| this.weights[lastLayerIndex][actionIndex][i] -= |
| policyGradient * result.activations[lastLayerIndex][i]; |
| } |
| this.biases[lastLayerIndex][actionIndex] -= policyGradient; |
| |
| |
| const valueIndex = this.weights[lastLayerIndex].length - 1; |
| const valueGradient = valueLoss * this.learningRate * this.valueCoeff; |
| for (let i = 0; i < this.weights[lastLayerIndex][valueIndex].length; i++) { |
| this.weights[lastLayerIndex][valueIndex][i] -= |
| valueGradient * result.activations[lastLayerIndex][i]; |
| } |
| this.biases[lastLayerIndex][valueIndex] -= valueGradient; |
| } |
| |
| stateToInput(state) { |
| const input = []; |
| const norm = FSD_CONFIG.stateNormalization; |
| |
| |
| input.push(state.dronePosition.x / norm.positionScale); |
| input.push(state.dronePosition.y / norm.positionScale); |
| input.push(state.dronePosition.z / norm.positionScale); |
| |
| |
| input.push(state.droneVelocity.x / norm.velocityScale); |
| input.push(state.droneVelocity.y / norm.velocityScale); |
| input.push(state.droneVelocity.z / norm.velocityScale); |
| |
| |
| const target = FSD_CONFIG.portalPositions[state.target]; |
| if (target) { |
| input.push(target.x / norm.targetScale); |
| input.push(target.y / norm.targetScale); |
| input.push(target.z / norm.targetScale); |
| } else { |
| input.push(0, 0, 0); |
| } |
| |
| |
| const toTarget = target.clone().sub(state.dronePosition); |
| input.push(toTarget.x / norm.distanceScale); |
| input.push(toTarget.y / norm.distanceScale); |
| input.push(toTarget.z / norm.distanceScale); |
| |
| |
| input.push(state.distanceToTarget / norm.distanceScale); |
| |
| |
| const obstacleProximity = this.calculateObstacleProximity(state.dronePosition); |
| input.push(...obstacleProximity); |
| |
| |
| input.push(state.patternStep / 5); |
| |
| |
| input.push(FSD_CONFIG.explorationRate); |
| |
| |
| while (input.length < 256) input.push(0); |
| |
| return input.slice(0, 256); |
| } |
| |
| calculateObstacleProximity(position) { |
| const directions = [ |
| new THREE.Vector3(1, 0, 0), |
| new THREE.Vector3(-1, 0, 0), |
| new THREE.Vector3(0, 0, 1), |
| new THREE.Vector3(0, 0, -1), |
| new THREE.Vector3(0, 1, 0), |
| new THREE.Vector3(0, -1, 0) |
| ]; |
| |
| const proximities = []; |
| const maxRange = 15; |
| |
| for (const dir of directions) { |
| let minDistance = maxRange; |
| |
| for (const obstacle of FSD_CONFIG.obstacles) { |
| if (!obstacle || !obstacle.position) continue; |
| |
| |
| const toObstacle = obstacle.position.clone().sub(position); |
| const dot = toObstacle.dot(dir); |
| |
| if (dot > 0) { |
| const distance = toObstacle.length(); |
| if (distance < minDistance) { |
| minDistance = distance; |
| } |
| } |
| } |
| |
| |
| proximities.push(1 - (minDistance / maxRange)); |
| } |
| |
| return proximities; |
| } |
| } |
| |
| |
| const enhancedNetwork = new EnhancedFSDNetwork(); |
| |
| |
| let scene, camera, renderer, clock; |
| let droneGroup = new THREE.Group(); |
| let frameCount = 0; |
| |
| function setupThreeJS() { |
| scene = new THREE.Scene(); |
| scene.background = new THREE.Color(0x000000); |
| scene.fog = new THREE.Fog(0x000000, 10, 100); |
| |
| camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); |
| camera.position.set(0, 20, 35); |
| |
| renderer = new THREE.WebGLRenderer({ antialias: true }); |
| renderer.setSize(window.innerWidth, window.innerHeight); |
| renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); |
| renderer.shadowMap.enabled = true; |
| renderer.shadowMap.type = THREE.PCFSoftShadowMap; |
| document.getElementById('threeContainer').appendChild(renderer.domElement); |
| |
| clock = new THREE.Clock(); |
| } |
| |
| |
| function setupScene() { |
| |
| while(scene.children.length > 0) { |
| const child = scene.children[0]; |
| if (child.geometry) child.geometry.dispose(); |
| if (child.material) child.material.dispose(); |
| scene.remove(child); |
| } |
| |
| scene.add(droneGroup); |
| setupDrone(); |
| |
| |
| const grid = new THREE.GridHelper(60, 60, 0x002200, 0x001100); |
| grid.position.y = 0.1; |
| scene.add(grid); |
| |
| |
| const centerGeo = new THREE.SphereGeometry(1.0, 16, 16); |
| const centerMat = new THREE.MeshBasicMaterial({ |
| color: 0x00ff00, |
| emissive: 0x003000, |
| transparent: true, |
| opacity: 0.5 |
| }); |
| const centerMarker = new THREE.Mesh(centerGeo, centerMat); |
| centerMarker.position.set(0, 0.5, 0); |
| scene.add(centerMarker); |
| |
| |
| for (const [name, pos] of Object.entries(FSD_CONFIG.portalPositions)) { |
| if (name === 'CENTER') continue; |
| |
| const markerGeo = new THREE.SphereGeometry(0.5, 12, 12); |
| const markerMat = new THREE.MeshBasicMaterial({ |
| color: 0xff0000, |
| emissive: 0x300000 |
| }); |
| const marker = new THREE.Mesh(markerGeo, markerMat); |
| marker.position.set(pos.x, 0.5, pos.z); |
| marker.userData = { name: name, type: 'portal' }; |
| scene.add(marker); |
| } |
| |
| |
| scene.add(new THREE.AmbientLight(0x003300)); |
| |
| const topLight = new THREE.DirectionalLight(0x00ff00, 0.7); |
| topLight.position.set(0, 40, 0); |
| topLight.castShadow = true; |
| scene.add(topLight); |
| |
| |
| for (const [name, pos] of Object.entries(FSD_CONFIG.portalPositions)) { |
| if (name === 'CENTER') continue; |
| |
| const cornerLight = new THREE.PointLight(0xff0000, 0.5, 30); |
| cornerLight.position.set(pos.x, 10, pos.z); |
| scene.add(cornerLight); |
| } |
| } |
| |
| |
| function setupDrone() { |
| droneGroup.clear(); |
| |
| |
| const bodyGeo = new THREE.BoxGeometry(0.8, 0.15, 0.8); |
| const bodyMat = new THREE.MeshBasicMaterial({ |
| color: 0x00ff00, |
| wireframe: true |
| }); |
| const body = new THREE.Mesh(bodyGeo, bodyMat); |
| droneGroup.add(body); |
| |
| |
| const armGeo = new THREE.BoxGeometry(1.4, 0.05, 0.05); |
| const armMat = new THREE.MeshBasicMaterial({ color: 0x00ff00 }); |
| |
| for (let i = 0; i < 4; i++) { |
| const angle = (i * Math.PI) / 2; |
| const arm = new THREE.Mesh(armGeo, armMat); |
| arm.position.set(Math.cos(angle) * 0.7, 0, Math.sin(angle) * 0.7); |
| droneGroup.add(arm); |
| |
| |
| const propGeo = new THREE.CylinderGeometry(0.2, 0.2, 0.03, 12); |
| const propMat = new THREE.MeshBasicMaterial({ |
| color: 0xff0000, |
| emissive: 0x330000 |
| }); |
| const prop = new THREE.Mesh(propGeo, propMat); |
| prop.position.set(Math.cos(angle) * 0.7, 0.08, Math.sin(angle) * 0.7); |
| prop.userData = { rotationSpeed: 15 + Math.random() * 5 }; |
| droneGroup.add(prop); |
| } |
| |
| |
| const frontGeo = new THREE.ConeGeometry(0.1, 0.3, 8); |
| const frontMat = new THREE.MeshBasicMaterial({ |
| color: 0x00ffff, |
| emissive: 0x003333 |
| }); |
| const frontIndicator = new THREE.Mesh(frontGeo, frontMat); |
| frontIndicator.position.set(0.5, 0, 0); |
| frontIndicator.rotation.z = Math.PI / 2; |
| droneGroup.add(frontIndicator); |
| |
| |
| const orientationGeo = new THREE.SphereGeometry(0.05, 4, 4); |
| const orientationMat = new THREE.MeshBasicMaterial({ color: 0xffff00 }); |
| |
| for (let i = 0; i < 3; i++) { |
| const indicator = new THREE.Mesh(orientationGeo, orientationMat); |
| indicator.position.set(0, i * 0.1 - 0.1, 0); |
| droneGroup.add(indicator); |
| } |
| |
| droneGroup.position.copy(FSD_CONFIG.dronePosition); |
| } |
| |
| |
| function generateBouncingObstacles() { |
| |
| FSD_CONFIG.obstacles.forEach(obstacle => { |
| if (obstacle.parent) obstacle.parent.remove(obstacle); |
| if (obstacle.geometry) obstacle.geometry.dispose(); |
| if (obstacle.material) obstacle.material.dispose(); |
| }); |
| |
| FSD_CONFIG.obstacles = []; |
| FSD_CONFIG.floatingObstacles = []; |
| |
| const difficulty = FSD_CONFIG.environment.difficultyLevel; |
| const roomHalf = FSD_CONFIG.environment.roomSize / 2; |
| |
| |
| const totalObstacles = Math.floor(15 + (difficulty - 1) * 5); |
| const floatingCount = Math.floor(12 + (difficulty - 1) * 3); |
| |
| for (let i = 0; i < totalObstacles - floatingCount; i++) { |
| const type = Math.random() > 0.5 ? 'pillar' : 'wall'; |
| let geo, mat; |
| |
| if (type === 'pillar') { |
| const radius = 0.6 + Math.random() * 1.2 * difficulty; |
| const height = 4 + Math.random() * 8 * difficulty; |
| geo = new THREE.CylinderGeometry(radius, radius, height, 12); |
| mat = new THREE.MeshBasicMaterial({ |
| color: 0x00ff00, |
| wireframe: true, |
| transparent: true, |
| opacity: 0.6 |
| }); |
| |
| const obstacle = new THREE.Mesh(geo, mat); |
| |
| |
| let x, z; |
| if (i < 4) { |
| |
| const portalNames = ['NW', 'NE', 'SW', 'SE']; |
| const portal = FSD_CONFIG.portalPositions[portalNames[i]]; |
| x = portal.x + (Math.random() - 0.5) * 8; |
| z = portal.z + (Math.random() - 0.5) * 8; |
| } else { |
| |
| x = (Math.random() - 0.5) * 50; |
| z = (Math.random() - 0.5) * 50; |
| } |
| |
| obstacle.position.set(x, height / 2, z); |
| obstacle.userData = { |
| type: 'pillar', |
| height: height, |
| radius: radius, |
| isFloating: false, |
| velocity: new THREE.Vector3(0, 0, 0) |
| }; |
| |
| scene.add(obstacle); |
| FSD_CONFIG.obstacles.push(obstacle); |
| } else { |
| const width = 2 + Math.random() * 4 * difficulty; |
| const height = 3 + Math.random() * 6 * difficulty; |
| const depth = 0.5 + Math.random() * 1.5 * difficulty; |
| geo = new THREE.BoxGeometry(width, height, depth); |
| mat = new THREE.MeshBasicMaterial({ |
| color: 0x00ff00, |
| wireframe: true, |
| transparent: true, |
| opacity: 0.6 |
| }); |
| |
| const obstacle = new THREE.Mesh(geo, mat); |
| |
| |
| const angle = Math.random() * Math.PI * 2; |
| const distance = 12 + Math.random() * 18; |
| const x = Math.cos(angle) * distance; |
| const z = Math.sin(angle) * distance; |
| |
| obstacle.position.set(x, height / 2, z); |
| obstacle.rotation.y = angle; |
| |
| obstacle.userData = { |
| type: 'wall', |
| height: height, |
| width: width, |
| depth: depth, |
| isFloating: false, |
| velocity: new THREE.Vector3(0, 0, 0) |
| }; |
| |
| scene.add(obstacle); |
| FSD_CONFIG.obstacles.push(obstacle); |
| } |
| } |
| |
| |
| for (let i = 0; i < floatingCount; i++) { |
| const size = 1.2 + Math.random() * 2.5 * difficulty; |
| const geo = new THREE.IcosahedronGeometry(size, 1); |
| const mat = new THREE.MeshBasicMaterial({ |
| color: 0xff00ff, |
| wireframe: true, |
| transparent: true, |
| opacity: 0.7 |
| }); |
| |
| const obstacle = new THREE.Mesh(geo, mat); |
| |
| |
| const bias = Math.random(); |
| const x = (Math.random() - 0.5) * 40 * (bias > 0.7 ? 0.5 : 1); |
| const z = (Math.random() - 0.5) * 40 * (bias > 0.7 ? 0.5 : 1); |
| const y = 6 + Math.random() * 12; |
| |
| obstacle.position.set(x, y, z); |
| |
| const speed = FSD_CONFIG.environment.floatingMinSpeed + |
| Math.random() * (FSD_CONFIG.environment.floatingMaxSpeed * difficulty - FSD_CONFIG.environment.floatingMinSpeed); |
| const angle = Math.random() * Math.PI * 2; |
| const velocity = new THREE.Vector3( |
| Math.cos(angle) * speed, |
| (Math.random() - 0.5) * speed * 0.5, |
| Math.sin(angle) * speed |
| ); |
| |
| obstacle.userData = { |
| type: 'floating', |
| size: size, |
| isFloating: true, |
| velocity: velocity, |
| angularVelocity: new THREE.Vector3( |
| (Math.random() - 0.5) * 0.1, |
| (Math.random() - 0.5) * 0.1, |
| (Math.random() - 0.5) * 0.1 |
| ), |
| bounceEnergy: FSD_CONFIG.environment.bounceEnergy, |
| originalColor: 0xff00ff |
| }; |
| |
| scene.add(obstacle); |
| FSD_CONFIG.obstacles.push(obstacle); |
| FSD_CONFIG.floatingObstacles.push(obstacle); |
| } |
| } |
| |
| |
| function updateBouncingObstacles(delta) { |
| const roomHalf = FSD_CONFIG.environment.roomSize / 2; |
| |
| for (const obstacle of FSD_CONFIG.floatingObstacles) { |
| if (!obstacle || !obstacle.userData) continue; |
| |
| const data = obstacle.userData; |
| |
| |
| obstacle.position.x += data.velocity.x * delta * 60; |
| obstacle.position.y += data.velocity.y * delta * 60; |
| obstacle.position.z += data.velocity.z * delta * 60; |
| |
| |
| obstacle.rotation.x += data.angularVelocity.x; |
| obstacle.rotation.y += data.angularVelocity.y; |
| obstacle.rotation.z += data.angularVelocity.z; |
| |
| |
| const halfSize = data.size / 2; |
| const bounceEnergy = data.bounceEnergy; |
| |
| |
| if (obstacle.position.x - halfSize < -roomHalf || obstacle.position.x + halfSize > roomHalf) { |
| data.velocity.x = -data.velocity.x * bounceEnergy; |
| |
| data.velocity.x += (Math.random() - 0.5) * 0.1; |
| obstacle.position.x = THREE.MathUtils.clamp( |
| obstacle.position.x, |
| -roomHalf + halfSize, |
| roomHalf - halfSize |
| ); |
| } |
| |
| |
| if (obstacle.position.y - halfSize < 2 || obstacle.position.y + halfSize > roomHalf - 5) { |
| data.velocity.y = -data.velocity.y * bounceEnergy; |
| data.velocity.y += (Math.random() - 0.5) * 0.05; |
| obstacle.position.y = THREE.MathUtils.clamp( |
| obstacle.position.y, |
| 2 + halfSize, |
| roomHalf - 5 - halfSize |
| ); |
| } |
| |
| |
| if (obstacle.position.z - halfSize < -roomHalf || obstacle.position.z + halfSize > roomHalf) { |
| data.velocity.z = -data.velocity.z * bounceEnergy; |
| data.velocity.z += (Math.random() - 0.5) * 0.1; |
| obstacle.position.z = THREE.MathUtils.clamp( |
| obstacle.position.z, |
| -roomHalf + halfSize, |
| roomHalf - halfSize |
| ); |
| } |
| |
| |
| data.velocity.y -= 0.1 * delta; |
| |
| |
| for (const otherObstacle of FSD_CONFIG.floatingObstacles) { |
| if (obstacle === otherObstacle || !otherObstacle.userData) continue; |
| |
| const otherData = otherObstacle.userData; |
| const distance = obstacle.position.distanceTo(otherObstacle.position); |
| const minDistance = (data.size + otherData.size) / 2; |
| |
| if (distance < minDistance) { |
| |
| const normal = new THREE.Vector3() |
| .subVectors(obstacle.position, otherObstacle.position) |
| .normalize(); |
| |
| |
| const relativeVelocity = data.velocity.clone().sub(otherData.velocity); |
| const normalVelocity = relativeVelocity.dot(normal); |
| |
| |
| if (normalVelocity < 0) { |
| const impulse = -(1 + bounceEnergy) * normalVelocity / |
| (1/data.size + 1/otherData.size); |
| |
| data.velocity.add(normal.clone().multiplyScalar(impulse / data.size)); |
| otherData.velocity.sub(normal.clone().multiplyScalar(impulse / otherData.size)); |
| |
| |
| const overlap = minDistance - distance; |
| const separation = normal.multiplyScalar(overlap * 0.5); |
| obstacle.position.add(separation); |
| otherObstacle.position.sub(separation); |
| } |
| } |
| } |
| } |
| } |
| |
| |
| function createPortals() { |
| |
| Object.values(FSD_CONFIG.portals).forEach(portal => { |
| if (portal && portal.parent === scene) { |
| scene.remove(portal); |
| } |
| }); |
| FSD_CONFIG.portals = {}; |
| |
| for (const [name, position] of Object.entries(FSD_CONFIG.portalPositions)) { |
| if (name === 'CENTER') continue; |
| |
| |
| const outerGeo = new THREE.TorusGeometry(2.5, 0.3, 16, 32); |
| const outerMat = new THREE.MeshBasicMaterial({ |
| color: 0x00ff00, |
| wireframe: true, |
| emissive: 0x003300 |
| }); |
| const outerRing = new THREE.Mesh(outerGeo, outerMat); |
| outerRing.position.copy(position); |
| outerRing.rotation.x = Math.PI / 2; |
| |
| |
| const innerGeo = new THREE.SphereGeometry(1.5, 16, 16); |
| const innerMat = new THREE.MeshBasicMaterial({ |
| color: 0xff0000, |
| wireframe: true, |
| transparent: true, |
| opacity: 0.7, |
| emissive: 0x330000 |
| }); |
| const innerSphere = new THREE.Mesh(innerGeo, innerMat); |
| innerSphere.position.copy(position); |
| |
| |
| const portalGroup = new THREE.Group(); |
| portalGroup.add(outerRing); |
| portalGroup.add(innerSphere); |
| portalGroup.position.copy(position); |
| |
| portalGroup.userData = { |
| name: name, |
| collected: false, |
| position: position.clone(), |
| rotationSpeed: 0.03, |
| pulsePhase: Math.random() * Math.PI * 2 |
| }; |
| |
| scene.add(portalGroup); |
| FSD_CONFIG.portals[name] = portalGroup; |
| } |
| |
| |
| FSD_CONFIG.currentStep = 0; |
| const firstPortalName = FSD_CONFIG.patternSequence[0]; |
| FSD_CONFIG.activePortal = FSD_CONFIG.portals[firstPortalName]; |
| } |
| |
| |
| function enhancedFSDAutoPilot(delta) { |
| if (!FSD_CONFIG.isTraining || FSD_CONFIG.isPaused || FSD_CONFIG.patternCompleted) return; |
| |
| try { |
| FSD_CONFIG.trainingStep++; |
| const currentTime = Date.now(); |
| const currentTargetName = FSD_CONFIG.patternSequence[FSD_CONFIG.currentStep]; |
| |
| |
| let targetPosition; |
| if (currentTargetName === 'CENTER') { |
| targetPosition = FSD_CONFIG.portalPositions['CENTER'].clone(); |
| } else { |
| targetPosition = FSD_CONFIG.portalPositions[currentTargetName].clone(); |
| } |
| |
| FSD_CONFIG.droneTargetPosition.copy(targetPosition); |
| |
| |
| const currentState = getCurrentState(); |
| |
| |
| let actionIndex; |
| let actionProbability = 0; |
| |
| if (Math.random() < FSD_CONFIG.explorationRate && FSD_CONFIG.trainingStep < 200) { |
| |
| actionIndex = Math.floor(Math.random() * FSD_CONFIG.actionSpace.length); |
| actionProbability = 1 / FSD_CONFIG.actionSpace.length; |
| } else { |
| |
| const policy = enhancedNetwork.getPolicy(currentState); |
| actionIndex = sampleFromDistribution(policy); |
| actionProbability = policy[actionIndex]; |
| } |
| |
| |
| const action = FSD_CONFIG.actionSpace[actionIndex]; |
| |
| |
| const moveVector = calculateEnhancedMovement(targetPosition, action.vector, delta); |
| |
| |
| FSD_CONFIG.dronePosition.add(moveVector); |
| |
| |
| const roomHalf = FSD_CONFIG.environment.roomSize / 2; |
| const margin = 3; |
| FSD_CONFIG.dronePosition.x = THREE.MathUtils.clamp( |
| FSD_CONFIG.dronePosition.x, |
| -roomHalf + margin, |
| roomHalf - margin |
| ); |
| FSD_CONFIG.dronePosition.y = THREE.MathUtils.clamp( |
| FSD_CONFIG.dronePosition.y, |
| 2, |
| roomHalf - 8 |
| ); |
| FSD_CONFIG.dronePosition.z = THREE.MathUtils.clamp( |
| FSD_CONFIG.dronePosition.z, |
| -roomHalf + margin, |
| roomHalf - margin |
| ); |
| |
| |
| droneGroup.position.copy(FSD_CONFIG.dronePosition); |
| |
| |
| if (moveVector.length() > 0.1) { |
| const targetQuat = new THREE.Quaternion().setFromUnitVectors( |
| new THREE.Vector3(0, 0, 1), |
| moveVector.clone().normalize() |
| ); |
| droneGroup.quaternion.slerp(targetQuat, 0.15); |
| } |
| |
| |
| const newVelocity = moveVector.divideScalar(delta); |
| FSD_CONFIG.droneVelocity.lerp(newVelocity, 0.2); |
| |
| |
| const stepDistance = FSD_CONFIG.dronePosition.distanceTo(FSD_CONFIG.lastPosition); |
| FSD_CONFIG.totalPathLength += stepDistance; |
| FSD_CONFIG.lastPosition.copy(FSD_CONFIG.dronePosition); |
| |
| |
| const distanceToTarget = FSD_CONFIG.dronePosition.distanceTo(targetPosition); |
| |
| |
| if (distanceToTarget < FSD_CONFIG.lastDistanceToTarget * 0.99) { |
| FSD_CONFIG.stuckTimer = Math.max(0, FSD_CONFIG.stuckTimer - delta * 2); |
| FSD_CONFIG.lastProgressTime = currentTime; |
| } else { |
| FSD_CONFIG.stuckTimer += delta; |
| } |
| |
| FSD_CONFIG.lastDistanceToTarget = distanceToTarget; |
| |
| |
| if (FSD_CONFIG.stuckTimer > FSD_CONFIG.stuckThreshold) { |
| handleEnhancedStuckRecovery(); |
| } |
| |
| |
| if (distanceToTarget < 3.0) { |
| handleTargetReached(currentTargetName); |
| } |
| |
| |
| if (Math.abs(FSD_CONFIG.dronePosition.x) < 6 && Math.abs(FSD_CONFIG.dronePosition.z) < 6) { |
| if (Math.abs(FSD_CONFIG.lastPosition.x) > 6 || Math.abs(FSD_CONFIG.lastPosition.z) > 6) { |
| FSD_CONFIG.crossingCount++; |
| addEnhancedReward(8, 'center_crossing'); |
| } |
| } |
| |
| |
| if (checkEnhancedCollisions()) { |
| addEnhancedReward(-15, 'collision'); |
| } |
| |
| |
| const immediateReward = calculateImmediateReward(distanceToTarget, stepDistance, delta); |
| addEnhancedReward(immediateReward, 'movement'); |
| |
| |
| recordEnhancedExperience(currentState, actionIndex, actionProbability); |
| |
| |
| if (FSD_CONFIG.trainingStep % 50 === 0 && FSD_CONFIG.memoryBuffer.length >= FSD_CONFIG.batchSize) { |
| trainEnhancedNetwork(); |
| } |
| |
| |
| logEnhancedTelemetry(actionIndex, distanceToTarget); |
| |
| |
| updateAvoidanceMemory(); |
| |
| } catch (error) { |
| console.error('Enhanced FSD Auto-pilot error:', error); |
| } |
| } |
| |
| function calculateEnhancedMovement(targetPosition, actionVector, delta) { |
| |
| const pidOutput = calculatePIDOutput(targetPosition); |
| const avoidanceForce = calculateEnhancedAvoidance(); |
| |
| |
| const blendFactor = 0.6; |
| const neuralForce = actionVector.clone().multiplyScalar(blendFactor); |
| const pidForce = pidOutput.multiplyScalar(1 - blendFactor); |
| |
| let finalForce = neuralForce.add(pidForce); |
| |
| |
| const avoidanceWeight = Math.min(2.0, FSD_CONFIG.avoidanceMemory.length / 10); |
| finalForce.add(avoidanceForce.multiplyScalar(avoidanceWeight)); |
| |
| |
| finalForce.normalize(); |
| |
| |
| const baseSpeed = 10 + (FSD_CONFIG.successfulPaths.length * 0.3); |
| const distance = FSD_CONFIG.dronePosition.distanceTo(targetPosition); |
| const adaptiveSpeed = Math.min(baseSpeed, distance * 0.7); |
| const speedBoost = 1 + (FSD_CONFIG.learningRate * 5); |
| |
| return finalForce.multiplyScalar(adaptiveSpeed * speedBoost * delta); |
| } |
| |
| function calculatePIDOutput(targetPosition) { |
| const pid = FSD_CONFIG.pidController; |
| const error = targetPosition.clone().sub(FSD_CONFIG.dronePosition); |
| |
| |
| pid.integral.add(error.clone().multiplyScalar(pid.ki)); |
| |
| |
| const maxIntegral = 5; |
| pid.integral.x = THREE.MathUtils.clamp(pid.integral.x, -maxIntegral, maxIntegral); |
| pid.integral.y = THREE.MathUtils.clamp(pid.integral.y, -maxIntegral, maxIntegral); |
| pid.integral.z = THREE.MathUtils.clamp(pid.integral.z, -maxIntegral, maxIntegral); |
| |
| |
| const derivative = error.clone().sub(pid.lastError); |
| |
| |
| const output = new THREE.Vector3() |
| .add(error.clone().multiplyScalar(pid.kp)) |
| .add(pid.integral) |
| .add(derivative.multiplyScalar(pid.kd)); |
| |
| |
| pid.lastError.copy(error); |
| |
| return output; |
| } |
| |
| function calculateEnhancedAvoidance() { |
| const avoidance = new THREE.Vector3(0, 0, 0); |
| const dronePos = FSD_CONFIG.dronePosition; |
| |
| for (const obstacle of FSD_CONFIG.obstacles) { |
| if (!obstacle || !obstacle.position) continue; |
| |
| const data = obstacle.userData; |
| const obstaclePos = obstacle.position.clone(); |
| |
| |
| if (data.isFloating && data.velocity) { |
| const predictionTime = 0.8; |
| obstaclePos.add(data.velocity.clone().multiplyScalar(predictionTime)); |
| } |
| |
| const toDrone = dronePos.clone().sub(obstaclePos); |
| const distance = toDrone.length(); |
| |
| |
| let safeDistance; |
| if (data.isFloating) { |
| safeDistance = data.size + 4; |
| } else if (data.type === 'pillar') { |
| safeDistance = data.radius + 3; |
| } else { |
| safeDistance = Math.max(data.width, data.depth) / 2 + 3; |
| } |
| |
| if (distance < safeDistance * 2) { |
| |
| const repulsionForce = toDrone.normalize().multiplyScalar( |
| Math.pow(safeDistance * 2 / distance, 3) |
| ); |
| |
| |
| let weight = 1.0; |
| if (data.isFloating && data.velocity) { |
| const approachSpeed = -data.velocity.dot(toDrone.normalize()); |
| weight += Math.max(0, approachSpeed) * 0.5; |
| } |
| |
| avoidance.add(repulsionForce.multiplyScalar(weight)); |
| } |
| } |
| |
| return avoidance.length() > 0 ? avoidance.normalize() : avoidance; |
| } |
| |
| function getCurrentState() { |
| const currentTarget = FSD_CONFIG.patternSequence[FSD_CONFIG.currentStep]; |
| return { |
| dronePosition: FSD_CONFIG.dronePosition.clone(), |
| droneVelocity: FSD_CONFIG.droneVelocity.clone(), |
| target: currentTarget, |
| distanceToTarget: FSD_CONFIG.dronePosition.distanceTo( |
| currentTarget === 'CENTER' ? |
| FSD_CONFIG.portalPositions['CENTER'] : |
| FSD_CONFIG.portalPositions[currentTarget] |
| ), |
| patternStep: FSD_CONFIG.currentStep |
| }; |
| } |
| |
| function sampleFromDistribution(probabilities) { |
| const rand = Math.random(); |
| let cumulative = 0; |
| for (let i = 0; i < probabilities.length; i++) { |
| cumulative += probabilities[i]; |
| if (rand <= cumulative) { |
| return i; |
| } |
| } |
| return probabilities.length - 1; |
| } |
| |
| function calculateImmediateReward(distanceToTarget, stepDistance, delta) { |
| let reward = 0; |
| |
| |
| const distanceImprovement = FSD_CONFIG.lastDistanceToTarget - distanceToTarget; |
| reward += distanceImprovement * 0.5; |
| |
| |
| const speed = stepDistance / delta; |
| const optimalSpeed = 8; |
| const speedReward = Math.exp(-Math.pow(speed - optimalSpeed, 2) / 50); |
| reward += speedReward * 0.1; |
| |
| |
| reward -= 0.01; |
| |
| return reward; |
| } |
| |
| function addEnhancedReward(reward, source) { |
| FSD_CONFIG.cumulativeReward += reward; |
| |
| |
| FSD_CONFIG.rewardBuffer.push({ |
| reward: reward, |
| source: source, |
| timestamp: Date.now(), |
| step: FSD_CONFIG.trainingStep |
| }); |
| |
| |
| if (FSD_CONFIG.rewardBuffer.length > 1000) { |
| FSD_CONFIG.rewardBuffer.shift(); |
| } |
| |
| |
| const recentRewards = FSD_CONFIG.rewardBuffer.slice(-100); |
| FSD_CONFIG.avgReward = recentRewards.reduce((sum, r) => sum + r.reward, 0) / recentRewards.length; |
| } |
| |
| function recordEnhancedExperience(state, actionIndex, actionProbability) { |
| const experience = { |
| state: state, |
| action: actionIndex, |
| oldProbability: actionProbability, |
| reward: FSD_CONFIG.cumulativeReward, |
| timestamp: Date.now(), |
| step: FSD_CONFIG.trainingStep, |
| epoch: FSD_CONFIG.epoch, |
| iteration: FSD_CONFIG.iteration |
| }; |
| |
| FSD_CONFIG.memoryBuffer.push(experience); |
| FSD_CONFIG.actionHistory.push(actionIndex); |
| |
| |
| if (FSD_CONFIG.memoryBuffer.length > FSD_CONFIG.maxMemorySize) { |
| FSD_CONFIG.memoryBuffer.shift(); |
| } |
| if (FSD_CONFIG.actionHistory.length > 100) { |
| FSD_CONFIG.actionHistory.shift(); |
| } |
| } |
| |
| function trainEnhancedNetwork() { |
| if (FSD_CONFIG.memoryBuffer.length < FSD_CONFIG.batchSize) return; |
| |
| |
| const batch = []; |
| for (let i = 0; i < FSD_CONFIG.batchSize; i++) { |
| const randomIndex = Math.floor(Math.random() * FSD_CONFIG.memoryBuffer.length); |
| batch.push(FSD_CONFIG.memoryBuffer[randomIndex]); |
| } |
| |
| |
| for (const exp of batch) { |
| exp.nextState = getCurrentState(); |
| exp.done = FSD_CONFIG.patternCompleted; |
| } |
| |
| |
| const losses = enhancedNetwork.trainBatch(batch); |
| |
| |
| FSD_CONFIG.policyLoss = losses.policyLoss; |
| FSD_CONFIG.valueLoss = losses.valueLoss; |
| FSD_CONFIG.tdError = losses.tdError; |
| FSD_CONFIG.trainSteps++; |
| |
| |
| updateLearningParameters(); |
| } |
| |
| function updateLearningParameters() { |
| |
| FSD_CONFIG.explorationRate = Math.max(0.05, FSD_CONFIG.explorationRate * 0.999); |
| |
| |
| const successRate = FSD_CONFIG.successHistory.length > 0 ? |
| FSD_CONFIG.successHistory.filter(s => s).length / FSD_CONFIG.successHistory.length : 0; |
| |
| if (successRate > 0.7) { |
| FSD_CONFIG.learningRate = Math.min(0.005, FSD_CONFIG.learningRate * 1.01); |
| } else if (successRate < 0.3) { |
| FSD_CONFIG.learningRate = Math.max(0.0001, FSD_CONFIG.learningRate * 0.99); |
| } |
| |
| |
| enhancedNetwork.learningRate = FSD_CONFIG.learningRate; |
| } |
| |
| function handleEnhancedStuckRecovery() { |
| FSD_CONFIG.stuckTimer = 0; |
| |
| |
| const recoveryAngle = Math.random() * Math.PI * 2; |
| const recoveryDistance = 8; |
| |
| FSD_CONFIG.dronePosition.add(new THREE.Vector3( |
| Math.cos(recoveryAngle) * recoveryDistance, |
| 3, |
| Math.sin(recoveryAngle) * recoveryDistance |
| )); |
| |
| |
| FSD_CONFIG.explorationRate = Math.min(0.5, FSD_CONFIG.explorationRate * 1.2); |
| |
| showMessage('ENHANCED RECOVERY', 'Drone repositioned and exploration increased'); |
| } |
| |
| function checkEnhancedCollisions() { |
| for (const obstacle of FSD_CONFIG.obstacles) { |
| if (!obstacle || !obstacle.position) continue; |
| |
| const data = obstacle.userData; |
| const distance = FSD_CONFIG.dronePosition.distanceTo(obstacle.position); |
| |
| let collisionDistance; |
| if (data.isFloating) { |
| collisionDistance = data.size + 0.8; |
| } else if (data.type === 'pillar') { |
| collisionDistance = data.radius + 0.8; |
| } else { |
| collisionDistance = Math.max(data.width, data.depth) / 2 + 0.8; |
| } |
| |
| if (distance < collisionDistance) { |
| handleEnhancedCollision(obstacle); |
| return true; |
| } |
| } |
| return false; |
| } |
| |
| function handleEnhancedCollision(obstacle) { |
| if (!FSD_CONFIG.isTraining) return; |
| |
| FSD_CONFIG.collisionCount++; |
| |
| const data = obstacle.userData; |
| |
| |
| const originalColor = obstacle.material.color.getHex(); |
| obstacle.material.color.setHex(0xff0000); |
| if (obstacle.material.emissive) { |
| obstacle.material.emissive.setHex(0x330000); |
| } |
| |
| setTimeout(() => { |
| try { |
| obstacle.material.color.setHex(data.originalColor || originalColor); |
| if (obstacle.material.emissive) { |
| obstacle.material.emissive.setHex(0x000000); |
| } |
| } catch (e) {} |
| }, 500); |
| |
| |
| const normal = FSD_CONFIG.dronePosition.clone().sub(obstacle.position).normalize(); |
| const bounceStrength = 3.0; |
| FSD_CONFIG.dronePosition.add(normal.multiplyScalar(bounceStrength)); |
| |
| |
| FSD_CONFIG.droneVelocity.multiplyScalar(0.2); |
| |
| |
| FSD_CONFIG.avoidanceMemory.push({ |
| position: obstacle.position.clone(), |
| type: data.type, |
| size: data.size || data.radius || 2, |
| velocity: data.velocity ? data.velocity.clone() : new THREE.Vector3(0, 0, 0), |
| timestamp: Date.now(), |
| severity: 1.0 |
| }); |
| |
| |
| if (FSD_CONFIG.avoidanceMemory.length > 50) { |
| FSD_CONFIG.avoidanceMemory.shift(); |
| } |
| } |
| |
| function updateAvoidanceMemory() { |
| |
| const currentTime = Date.now(); |
| FSD_CONFIG.avoidanceMemory = FSD_CONFIG.avoidanceMemory.filter(memory => { |
| const age = currentTime - memory.timestamp; |
| return age < 10000; |
| }); |
| } |
| |
| function logEnhancedTelemetry(actionIndex, distanceToTarget) { |
| try { |
| if (!FSD_CONFIG.isTraining || FSD_CONFIG.isPaused) return; |
| |
| const currentTarget = FSD_CONFIG.patternSequence[FSD_CONFIG.currentStep]; |
| const targetPos = currentTarget === 'CENTER' ? |
| FSD_CONFIG.portalPositions['CENTER'] : |
| FSD_CONFIG.portalPositions[currentTarget]; |
| |
| const telemetry = { |
| timestamp: Date.now(), |
| frame: frameCount++, |
| epoch: FSD_CONFIG.epoch, |
| iteration: FSD_CONFIG.iteration, |
| trainingStep: FSD_CONFIG.trainingStep, |
| |
| pattern_step: FSD_CONFIG.currentStep, |
| pattern_target: currentTarget, |
| |
| position: [FSD_CONFIG.dronePosition.x, FSD_CONFIG.dronePosition.y, FSD_CONFIG.dronePosition.z], |
| velocity: [FSD_CONFIG.droneVelocity.x, FSD_CONFIG.droneVelocity.y, FSD_CONFIG.droneVelocity.z], |
| rotation: [droneGroup.rotation.x, droneGroup.rotation.y, droneGroup.rotation.z], |
| |
| target_position: [targetPos.x, targetPos.y, targetPos.z], |
| distance_to_target: distanceToTarget, |
| |
| |
| q_value: enhancedNetwork.getValue(getCurrentState()), |
| cumulative_reward: FSD_CONFIG.cumulativeReward, |
| exploration_rate: FSD_CONFIG.explorationRate, |
| learning_rate: FSD_CONFIG.learningRate, |
| td_error: FSD_CONFIG.tdError, |
| policy_loss: FSD_CONFIG.policyLoss, |
| value_loss: FSD_CONFIG.valueLoss, |
| |
| |
| collisions: FSD_CONFIG.collisionCount, |
| path_length: FSD_CONFIG.totalPathLength, |
| crossing_count: FSD_CONFIG.crossingCount, |
| stuck_timer: FSD_CONFIG.stuckTimer, |
| avoidance_memory: FSD_CONFIG.avoidanceMemory.length, |
| |
| |
| obstacle_count: FSD_CONFIG.obstacles.length, |
| floating_obstacle_count: FSD_CONFIG.floatingObstacles.length, |
| difficulty_level: FSD_CONFIG.environment.difficultyLevel, |
| |
| |
| pattern_time: (Date.now() - FSD_CONFIG.patternStartTime) / 1000, |
| pattern_completed: FSD_CONFIG.patternCompleted, |
| |
| |
| memory_buffer_size: FSD_CONFIG.memoryBuffer.length, |
| successful_paths_count: FSD_CONFIG.successfulPaths.length, |
| train_steps: FSD_CONFIG.trainSteps, |
| avg_reward: FSD_CONFIG.avgReward |
| }; |
| |
| FSD_CONFIG.telemetryBuffer.push(telemetry); |
| |
| if (FSD_CONFIG.telemetryBuffer.length > FSD_CONFIG.maxBufferSize) { |
| FSD_CONFIG.telemetryBuffer = FSD_CONFIG.telemetryBuffer.slice(-FSD_CONFIG.maxBufferSize); |
| } |
| |
| } catch (error) { |
| console.error('Enhanced telemetry error:', error); |
| } |
| } |
| |
| |
| function handleTargetReached(targetName) { |
| if (targetName === 'CENTER') { |
| completeEnhancedPattern(); |
| return; |
| } |
| |
| const portal = FSD_CONFIG.portals[targetName]; |
| if (portal && !portal.userData.collected) { |
| portal.userData.collected = true; |
| |
| |
| portal.children.forEach(child => { |
| if (child.material) { |
| child.material.color.setHex(0x00aa00); |
| if (child.material.emissive) { |
| child.material.emissive.setHex(0x003300); |
| } |
| } |
| }); |
| |
| addEnhancedReward(25, 'portal_reached'); |
| } |
| |
| FSD_CONFIG.currentStep++; |
| |
| if (FSD_CONFIG.currentStep < FSD_CONFIG.patternSequence.length) { |
| const nextTargetName = FSD_CONFIG.patternSequence[FSD_CONFIG.currentStep]; |
| |
| if (nextTargetName === 'CENTER') { |
| FSD_CONFIG.activePortal = null; |
| showMessage('RETURN TO CENTER', 'Complete pattern by returning to center'); |
| } else { |
| FSD_CONFIG.activePortal = FSD_CONFIG.portals[nextTargetName]; |
| showMessage('NEXT TARGET', `${targetName} → ${nextTargetName}`); |
| } |
| |
| addEnhancedReward(10, 'pattern_progress'); |
| updateUI(); |
| } |
| } |
| |
| function completeEnhancedPattern() { |
| FSD_CONFIG.patternCompleted = true; |
| const elapsedTime = (Date.now() - FSD_CONFIG.patternStartTime) / 1000; |
| |
| |
| const idealPath = calculateIdealPathLength(); |
| const efficiency = FSD_CONFIG.totalPathLength > 0 ? |
| (idealPath / FSD_CONFIG.totalPathLength) * 100 : 0; |
| FSD_CONFIG.efficiencyScore = efficiency; |
| |
| |
| const timeBonus = Math.max(0, 45 - elapsedTime) * 0.8; |
| |
| |
| const collisionPenalty = FSD_CONFIG.collisionCount * 3; |
| |
| |
| const efficiencyBonus = efficiency > 85 ? 20 : |
| efficiency > 70 ? 10 : 0; |
| |
| |
| FSD_CONFIG.epochScore = efficiency - collisionPenalty + timeBonus + efficiencyBonus; |
| |
| |
| if (elapsedTime < FSD_CONFIG.patternBestTime) { |
| FSD_CONFIG.patternBestTime = elapsedTime; |
| } |
| |
| |
| const success = FSD_CONFIG.collisionCount === 0 && efficiency > 80; |
| FSD_CONFIG.successHistory.push(success); |
| if (FSD_CONFIG.successHistory.length > 20) FSD_CONFIG.successHistory.shift(); |
| |
| |
| addEnhancedReward(100 + timeBonus + efficiencyBonus - collisionPenalty, 'pattern_complete'); |
| |
| |
| const successfulPath = { |
| epoch: FSD_CONFIG.epoch, |
| iteration: FSD_CONFIG.iteration, |
| time: elapsedTime, |
| collisions: FSD_CONFIG.collisionCount, |
| pathLength: FSD_CONFIG.totalPathLength, |
| efficiency: efficiency, |
| score: FSD_CONFIG.epochScore, |
| cumulativeReward: FSD_CONFIG.cumulativeReward, |
| explorationRate: FSD_CONFIG.explorationRate, |
| timestamp: Date.now() |
| }; |
| |
| FSD_CONFIG.successfulPaths.push(successfulPath); |
| |
| |
| if (FSD_CONFIG.successfulPaths.length > 30) { |
| FSD_CONFIG.successfulPaths.shift(); |
| } |
| |
| |
| FSD_CONFIG.rewardPerEpoch.push(FSD_CONFIG.cumulativeReward); |
| if (FSD_CONFIG.rewardPerEpoch.length > 10) { |
| FSD_CONFIG.rewardPerEpoch.shift(); |
| } |
| |
| showMessage('ENHANCED PATTERN COMPLETE!', |
| `Time: ${elapsedTime.toFixed(2)}s | Score: ${FSD_CONFIG.epochScore.toFixed(2)} | Efficiency: ${efficiency.toFixed(1)}%`); |
| |
| |
| updateEnhancedLearningParameters(success, efficiency, elapsedTime); |
| |
| updateUI(); |
| |
| |
| setTimeout(() => { |
| if (FSD_CONFIG.isTraining && !FSD_CONFIG.isPaused) { |
| FSD_CONFIG.iteration++; |
| startPattern(); |
| } |
| }, 2500); |
| } |
| |
| function updateEnhancedLearningParameters(success, efficiency, elapsedTime) { |
| |
| FSD_CONFIG.explorationRate = Math.max(0.05, FSD_CONFIG.explorationRate * 0.97); |
| |
| |
| if (success && efficiency > 75 && elapsedTime < FSD_CONFIG.patternBestTime * 1.3) { |
| FSD_CONFIG.learningRate = Math.min(0.005, FSD_CONFIG.learningRate * 1.05); |
| } else if (!success || efficiency < 60) { |
| FSD_CONFIG.learningRate = Math.max(0.0001, FSD_CONFIG.learningRate * 0.95); |
| } |
| |
| |
| enhancedNetwork.learningRate = FSD_CONFIG.learningRate; |
| } |
| |
| function calculateIdealPathLength() { |
| let totalDistance = 0; |
| let lastPosition = FSD_CONFIG.portalPositions['CENTER']; |
| |
| for (const portalName of FSD_CONFIG.patternSequence) { |
| const position = FSD_CONFIG.portalPositions[portalName]; |
| totalDistance += lastPosition.distanceTo(position); |
| lastPosition = position; |
| } |
| |
| return totalDistance; |
| } |
| |
| |
| function updateUI() { |
| try { |
| |
| document.getElementById('altitude').textContent = FSD_CONFIG.dronePosition.y.toFixed(1) + 'm'; |
| document.getElementById('speed').textContent = FSD_CONFIG.droneVelocity.length().toFixed(1) + 'm/s'; |
| document.getElementById('velocity').textContent = |
| `${FSD_CONFIG.droneVelocity.x.toFixed(1)}/${FSD_CONFIG.droneVelocity.y.toFixed(1)}/${FSD_CONFIG.droneVelocity.z.toFixed(1)}`; |
| |
| |
| const currentTarget = FSD_CONFIG.patternSequence[FSD_CONFIG.currentStep]; |
| const targetPos = currentTarget === 'CENTER' ? |
| FSD_CONFIG.portalPositions['CENTER'] : |
| FSD_CONFIG.portalPositions[currentTarget]; |
| const distance = FSD_CONFIG.dronePosition.distanceTo(targetPos); |
| document.getElementById('distanceToTarget').textContent = distance.toFixed(1) + 'm'; |
| |
| document.getElementById('collisionCount').textContent = FSD_CONFIG.collisionCount; |
| document.getElementById('pathLength').textContent = FSD_CONFIG.totalPathLength.toFixed(1) + 'm'; |
| document.getElementById('crossingCount').textContent = FSD_CONFIG.crossingCount; |
| |
| |
| document.getElementById('epochNumber').textContent = FSD_CONFIG.epoch; |
| document.getElementById('iterationNumber').textContent = FSD_CONFIG.iteration; |
| document.getElementById('trainingStep').textContent = FSD_CONFIG.trainingStep; |
| document.getElementById('patternStep').textContent = `${FSD_CONFIG.currentStep + 1}/${FSD_CONFIG.patternSequence.length}`; |
| |
| const nextPortal = FSD_CONFIG.currentStep < FSD_CONFIG.patternSequence.length ? |
| FSD_CONFIG.patternSequence[FSD_CONFIG.currentStep] : 'COMPLETE'; |
| document.getElementById('nextPortal').textContent = nextPortal; |
| |
| |
| const progress = (FSD_CONFIG.currentStep / FSD_CONFIG.patternSequence.length) * 100; |
| document.getElementById('patternProgressBar').style.width = `${progress}%`; |
| |
| |
| const elapsedTime = FSD_CONFIG.patternStartTime > 0 ? |
| ((Date.now() - FSD_CONFIG.patternStartTime) / 1000).toFixed(1) : '0.0'; |
| document.getElementById('patternTime').textContent = elapsedTime + 's'; |
| document.getElementById('bestTime').textContent = |
| FSD_CONFIG.patternBestTime === Infinity ? '∞' : FSD_CONFIG.patternBestTime.toFixed(2) + 's'; |
| document.getElementById('epochScore').textContent = FSD_CONFIG.epochScore.toFixed(2); |
| |
| |
| const idealPath = calculateIdealPathLength(); |
| const efficiency = FSD_CONFIG.totalPathLength > 0 ? |
| (idealPath / FSD_CONFIG.totalPathLength * 100).toFixed(1) : '0.0'; |
| document.getElementById('efficiency').textContent = efficiency + '%'; |
| |
| |
| document.getElementById('patternSequence').textContent = |
| FSD_CONFIG.patternSequence.join('→'); |
| document.getElementById('avoidanceScore').textContent = |
| FSD_CONFIG.avoidanceMemory.length > 0 ? |
| (FSD_CONFIG.avoidanceMemory.length / 50).toFixed(2) : '0.00'; |
| |
| |
| const successRate = FSD_CONFIG.successHistory.length > 0 ? |
| (FSD_CONFIG.successHistory.filter(s => s).length / FSD_CONFIG.successHistory.length * 100).toFixed(0) : '0'; |
| document.getElementById('successRate').textContent = successRate + '%'; |
| |
| document.getElementById('difficultyLevel').textContent = FSD_CONFIG.environment.difficultyLevel.toFixed(1); |
| |
| |
| document.getElementById('networkArch').textContent = enhancedNetwork.layers.join('-'); |
| document.getElementById('learningRate').textContent = FSD_CONFIG.learningRate.toFixed(4); |
| document.getElementById('explorationRate').textContent = FSD_CONFIG.explorationRate.toFixed(3); |
| document.getElementById('qValue').textContent = enhancedNetwork.getValue(getCurrentState()).toFixed(3); |
| document.getElementById('tdError').textContent = FSD_CONFIG.tdError.toFixed(4); |
| document.getElementById('memorySize').textContent = FSD_CONFIG.memoryBuffer.length; |
| document.getElementById('batchSize').textContent = FSD_CONFIG.batchSize; |
| |
| |
| document.getElementById('cumulativeReward').textContent = FSD_CONFIG.cumulativeReward.toFixed(1); |
| document.getElementById('avgReward').textContent = FSD_CONFIG.avgReward.toFixed(2); |
| |
| const recentRewards = FSD_CONFIG.rewardPerEpoch.slice(-5); |
| const avgRewardPerEpoch = recentRewards.length > 0 ? |
| recentRewards.reduce((a, b) => a + b, 0) / recentRewards.length : 0; |
| document.getElementById('rewardPerEpoch').textContent = avgRewardPerEpoch.toFixed(1); |
| |
| document.getElementById('policyLoss').textContent = FSD_CONFIG.policyLoss.toFixed(4); |
| document.getElementById('valueLoss').textContent = FSD_CONFIG.valueLoss.toFixed(4); |
| document.getElementById('trainSteps').textContent = FSD_CONFIG.trainSteps; |
| |
| |
| const statusDot = document.getElementById('statusDot'); |
| const statusText = document.getElementById('statusText'); |
| |
| if (FSD_CONFIG.isPaused) { |
| statusDot.style.background = '#ff0'; |
| statusText.textContent = 'PAUSED'; |
| } else if (FSD_CONFIG.isTraining) { |
| statusDot.style.background = '#0f0'; |
| statusText.textContent = `EPOCH ${FSD_CONFIG.epoch} | ITER ${FSD_CONFIG.iteration} | STEP ${FSD_CONFIG.trainingStep}`; |
| } else { |
| statusDot.style.background = '#f00'; |
| statusText.textContent = 'ENHANCED FSD READY'; |
| } |
| |
| |
| drawEnhancedWave(); |
| drawEnhancedPath(); |
| drawNeuralNetwork(); |
| |
| } catch (error) { |
| console.error('Enhanced UI update error:', error); |
| } |
| } |
| |
| |
| const waveCanvas = document.getElementById('waveVisualizer'); |
| const waveCtx = waveCanvas.getContext('2d'); |
| const pathCanvas = document.getElementById('pathVisualizer'); |
| const pathCtx = pathCanvas.getContext('2d'); |
| const nnCanvas = document.getElementById('nnVisualizer'); |
| const nnCtx = nnCanvas.getContext('2d'); |
| |
| let waveData = []; |
| let pathData = []; |
| |
| function drawEnhancedWave() { |
| if (!waveCanvas || !waveCtx) return; |
| |
| waveCanvas.width = waveCanvas.offsetWidth; |
| waveCanvas.height = waveCanvas.offsetHeight; |
| |
| |
| const gradient = waveCtx.createLinearGradient(0, 0, waveCanvas.width, 0); |
| gradient.addColorStop(0, 'rgba(0, 10, 0, 0.8)'); |
| gradient.addColorStop(1, 'rgba(0, 20, 0, 0.6)'); |
| waveCtx.fillStyle = gradient; |
| waveCtx.fillRect(0, 0, waveCanvas.width, waveCanvas.height); |
| |
| |
| waveCtx.strokeStyle = 'rgba(0, 255, 0, 0.15)'; |
| waveCtx.lineWidth = 1; |
| |
| for (let x = 0; x < waveCanvas.width; x += 25) { |
| waveCtx.beginPath(); |
| waveCtx.moveTo(x, 0); |
| waveCtx.lineTo(x, waveCanvas.height); |
| waveCtx.stroke(); |
| } |
| |
| for (let y = 0; y < waveCanvas.height; y += 25) { |
| waveCtx.beginPath(); |
| waveCtx.moveTo(0, y); |
| waveCtx.lineTo(waveCanvas.width, y); |
| waveCtx.stroke(); |
| } |
| |
| |
| waveData.push({ |
| altitude: FSD_CONFIG.dronePosition.y, |
| speed: FSD_CONFIG.droneVelocity.length(), |
| reward: FSD_CONFIG.cumulativeReward, |
| qValue: enhancedNetwork.getValue(getCurrentState()), |
| time: Date.now() |
| }); |
| |
| if (waveData.length > 120) waveData.shift(); |
| |
| |
| if (waveData.length > 1) { |
| |
| waveCtx.strokeStyle = '#0f0'; |
| waveCtx.lineWidth = 2; |
| waveCtx.beginPath(); |
| |
| waveData.forEach((point, i) => { |
| const x = (i / waveData.length) * waveCanvas.width; |
| const y = waveCanvas.height - (point.speed / 25 * waveCanvas.height); |
| |
| if (i === 0) waveCtx.moveTo(x, y); |
| else waveCtx.lineTo(x, y); |
| }); |
| waveCtx.stroke(); |
| |
| |
| waveCtx.strokeStyle = '#ff00ff'; |
| waveCtx.lineWidth = 1.5; |
| waveCtx.beginPath(); |
| |
| const rewards = waveData.map(p => p.reward); |
| const minReward = Math.min(...rewards); |
| const maxReward = Math.max(...rewards); |
| const rewardRange = Math.max(1, maxReward - minReward); |
| |
| waveData.forEach((point, i) => { |
| const x = (i / waveData.length) * waveCanvas.width; |
| const normalizedReward = (point.reward - minReward) / rewardRange; |
| const y = waveCanvas.height - (normalizedReward * waveCanvas.height * 0.7); |
| |
| if (i === 0) waveCtx.moveTo(x, y); |
| else waveCtx.lineTo(x, y); |
| }); |
| waveCtx.stroke(); |
| |
| |
| waveCtx.strokeStyle = '#0ff'; |
| waveCtx.lineWidth = 1.2; |
| waveCtx.beginPath(); |
| |
| const qValues = waveData.map(p => p.qValue); |
| const minQ = Math.min(...qValues); |
| const maxQ = Math.max(...qValues); |
| const qRange = Math.max(0.1, maxQ - minQ); |
| |
| waveData.forEach((point, i) => { |
| const x = (i / waveData.length) * waveCanvas.width; |
| const normalizedQ = (point.qValue - minQ) / qRange; |
| const y = waveCanvas.height - (normalizedQ * waveCanvas.height * 0.6); |
| |
| if (i === 0) waveCtx.moveTo(x, y); |
| else waveCtx.lineTo(x, y); |
| }); |
| waveCtx.stroke(); |
| |
| |
| const current = waveData[waveData.length - 1]; |
| waveCtx.fillStyle = '#0f0'; |
| waveCtx.font = '8px monospace'; |
| waveCtx.fillText(`Speed: ${current.speed.toFixed(1)}`, 5, 12); |
| waveCtx.fillStyle = '#ff00ff'; |
| waveCtx.fillText(`Reward: ${current.reward.toFixed(1)}`, 5, 24); |
| waveCtx.fillStyle = '#0ff'; |
| waveCtx.fillText(`Q: ${current.qValue.toFixed(3)}`, 5, 36); |
| } |
| } |
| |
| function drawEnhancedPath() { |
| if (!pathCanvas || !pathCtx) return; |
| |
| pathCanvas.width = pathCanvas.offsetWidth; |
| pathCanvas.height = pathCanvas.offsetHeight; |
| |
| |
| const gradient = pathCtx.createRadialGradient( |
| pathCanvas.width/2, pathCanvas.height/2, 0, |
| pathCanvas.width/2, pathCanvas.height/2, pathCanvas.width/2 |
| ); |
| gradient.addColorStop(0, 'rgba(0, 20, 20, 0.7)'); |
| gradient.addColorStop(1, 'rgba(0, 10, 10, 0.9)'); |
| pathCtx.fillStyle = gradient; |
| pathCtx.fillRect(0, 0, pathCanvas.width, pathCanvas.height); |
| |
| |
| const scale = Math.min(pathCanvas.width, pathCanvas.height) / 60; |
| const offsetX = pathCanvas.width / 2; |
| const offsetY = pathCanvas.height / 2; |
| |
| |
| pathCtx.strokeStyle = 'rgba(0, 255, 255, 0.15)'; |
| pathCtx.lineWidth = 0.5; |
| |
| for (let x = -30; x <= 30; x += 5) { |
| const screenX = offsetX + x * scale; |
| pathCtx.beginPath(); |
| pathCtx.moveTo(screenX, 0); |
| pathCtx.lineTo(screenX, pathCanvas.height); |
| pathCtx.stroke(); |
| } |
| |
| for (let y = -30; y <= 30; y += 5) { |
| const screenY = offsetY + y * scale; |
| pathCtx.beginPath(); |
| pathCtx.moveTo(0, screenY); |
| pathCtx.lineTo(pathCanvas.width, screenY); |
| pathCtx.stroke(); |
| } |
| |
| |
| for (const [name, pos] of Object.entries(FSD_CONFIG.portalPositions)) { |
| let color; |
| if (name === 'CENTER') { |
| color = '#ff0'; |
| } else { |
| color = FSD_CONFIG.portals[name]?.userData.collected ? '#0a0' : '#f00'; |
| } |
| |
| const screenX = offsetX + pos.x * scale; |
| const screenY = offsetY - pos.z * scale; |
| |
| |
| pathCtx.shadowColor = color; |
| pathCtx.shadowBlur = 10; |
| pathCtx.fillStyle = color; |
| pathCtx.beginPath(); |
| pathCtx.arc(screenX, screenY, 6, 0, Math.PI * 2); |
| pathCtx.fill(); |
| pathCtx.shadowBlur = 0; |
| |
| |
| pathCtx.strokeStyle = '#fff'; |
| pathCtx.lineWidth = 1; |
| pathCtx.beginPath(); |
| pathCtx.arc(screenX, screenY, 6, 0, Math.PI * 2); |
| pathCtx.stroke(); |
| |
| |
| pathCtx.fillStyle = '#fff'; |
| pathCtx.font = '9px monospace'; |
| pathCtx.textAlign = 'center'; |
| pathCtx.fillText(name, screenX, screenY - 12); |
| } |
| |
| |
| if (pathData.length > 1) { |
| |
| for (let i = 1; i < pathData.length; i++) { |
| const prev = pathData[i - 1]; |
| const current = pathData[i]; |
| |
| const screenX1 = offsetX + prev.x * scale; |
| const screenY1 = offsetY - prev.z * scale; |
| const screenX2 = offsetX + current.x * scale; |
| const screenY2 = offsetY - current.z * scale; |
| |
| |
| const timeDiff = current.time - prev.time; |
| const distance = Math.sqrt(Math.pow(current.x - prev.x, 2) + Math.pow(current.z - prev.z, 2)); |
| const speed = timeDiff > 0 ? distance / timeDiff * 1000 : 0; |
| |
| |
| let r, g, b; |
| if (speed < 5) { |
| r = 0; g = Math.floor(255 * (speed / 5)); b = 255; |
| } else if (speed < 10) { |
| r = Math.floor(255 * ((speed - 5) / 5)); g = 255; b = 0; |
| } else { |
| r = 255; g = Math.floor(255 * (1 - (speed - 10) / 10)); b = 0; |
| } |
| |
| |
| const age = Date.now() - current.time; |
| const width = Math.max(1, 3 * (1 - age / 10000)); |
| |
| pathCtx.strokeStyle = `rgb(${r}, ${g}, ${b})`; |
| pathCtx.lineWidth = width; |
| pathCtx.beginPath(); |
| pathCtx.moveTo(screenX1, screenY1); |
| pathCtx.lineTo(screenX2, screenY2); |
| pathCtx.stroke(); |
| } |
| |
| |
| const currentX = offsetX + FSD_CONFIG.dronePosition.x * scale; |
| const currentY = offsetY - FSD_CONFIG.dronePosition.z * scale; |
| |
| |
| pathCtx.fillStyle = '#0f0'; |
| pathCtx.beginPath(); |
| pathCtx.arc(currentX, currentY, 5, 0, Math.PI * 2); |
| pathCtx.fill(); |
| |
| pathCtx.strokeStyle = '#0f0'; |
| pathCtx.lineWidth = 1; |
| pathCtx.beginPath(); |
| pathCtx.arc(currentX, currentY, 5, 0, Math.PI * 2); |
| pathCtx.stroke(); |
| |
| |
| const forward = new THREE.Vector3(0, 0, -1); |
| forward.applyQuaternion(droneGroup.quaternion); |
| const forwardX = forward.x * 8; |
| const forwardZ = forward.z * 8; |
| |
| pathCtx.strokeStyle = '#0ff'; |
| pathCtx.lineWidth = 2; |
| pathCtx.beginPath(); |
| pathCtx.moveTo(currentX, currentY); |
| pathCtx.lineTo(currentX + forwardX * scale, currentY - forwardZ * scale); |
| pathCtx.stroke(); |
| |
| |
| if (FSD_CONFIG.droneVelocity.length() > 0.1) { |
| const velX = FSD_CONFIG.droneVelocity.x * 2; |
| const velZ = FSD_CONFIG.droneVelocity.z * 2; |
| |
| pathCtx.strokeStyle = '#ff0'; |
| pathCtx.lineWidth = 1.5; |
| pathCtx.beginPath(); |
| pathCtx.moveTo(currentX, currentY); |
| pathCtx.lineTo(currentX + velX * scale, currentY - velZ * scale); |
| pathCtx.stroke(); |
| |
| |
| const speed = FSD_CONFIG.droneVelocity.length(); |
| const speedRadius = Math.min(12, speed * 1.5); |
| pathCtx.strokeStyle = 'rgba(255, 255, 0, 0.5)'; |
| pathCtx.lineWidth = 1; |
| pathCtx.beginPath(); |
| pathCtx.arc(currentX, currentY, speedRadius, 0, Math.PI * 2); |
| pathCtx.stroke(); |
| } |
| } |
| |
| |
| pathData.push({ |
| x: FSD_CONFIG.dronePosition.x, |
| z: FSD_CONFIG.dronePosition.z, |
| time: Date.now() |
| }); |
| |
| |
| if (pathData.length > 800) { |
| pathData = pathData.slice(-800); |
| } |
| } |
| |
| function drawNeuralNetwork() { |
| if (!nnCanvas || !nnCtx) return; |
| |
| nnCanvas.width = nnCanvas.offsetWidth; |
| nnCanvas.height = nnCanvas.offsetHeight; |
| |
| |
| nnCtx.fillStyle = 'rgba(0, 10, 10, 0.8)'; |
| nnCtx.fillRect(0, 0, nnCanvas.width, nnCanvas.height); |
| |
| |
| const layers = enhancedNetwork.layers; |
| const neuronRadius = 3; |
| const layerSpacing = (nnCanvas.width - 40) / (layers.length - 1); |
| const maxNeurons = Math.max(...layers); |
| |
| |
| for (let l = 0; l < layers.length; l++) { |
| const neuronCount = layers[l]; |
| const x = 20 + l * layerSpacing; |
| |
| for (let n = 0; n < neuronCount; n++) { |
| const y = nnCanvas.height / 2 + (n - neuronCount/2) * (nnCanvas.height / (maxNeurons + 2)); |
| |
| |
| const activation = Math.random() * 0.5 + 0.3; |
| |
| |
| const gradient = nnCtx.createRadialGradient(x, y, 0, x, y, neuronRadius * 2); |
| gradient.addColorStop(0, `rgba(255, ${Math.floor(255 * activation)}, 255, 0.8)`); |
| gradient.addColorStop(1, `rgba(128, ${Math.floor(128 * activation)}, 255, 0.3)`); |
| |
| nnCtx.fillStyle = gradient; |
| nnCtx.beginPath(); |
| nnCtx.arc(x, y, neuronRadius, 0, Math.PI * 2); |
| nnCtx.fill(); |
| |
| |
| nnCtx.strokeStyle = `rgba(255, ${Math.floor(255 * activation)}, 255, 0.6)`; |
| nnCtx.lineWidth = 1; |
| nnCtx.beginPath(); |
| nnCtx.arc(x, y, neuronRadius, 0, Math.PI * 2); |
| nnCtx.stroke(); |
| } |
| } |
| |
| |
| nnCtx.fillStyle = '#ff00ff'; |
| nnCtx.font = '8px monospace'; |
| nnCtx.textAlign = 'center'; |
| |
| for (let l = 0; l < layers.length; l++) { |
| const x = 20 + l * layerSpacing; |
| nnCtx.fillText(`L${l+1}: ${layers[l]}`, x, 15); |
| } |
| |
| |
| nnCtx.fillStyle = '#0ff'; |
| nnCtx.font = '7px monospace'; |
| nnCtx.textAlign = 'left'; |
| nnCtx.fillText(`Learning: ${FSD_CONFIG.learningRate.toFixed(4)}`, 5, nnCanvas.height - 25); |
| nnCtx.fillText(`Exploration: ${FSD_CONFIG.explorationRate.toFixed(3)}`, 5, nnCanvas.height - 15); |
| nnCtx.fillText(`Memory: ${FSD_CONFIG.memoryBuffer.length}/${FSD_CONFIG.maxMemorySize}`, 5, nnCanvas.height - 5); |
| } |
| |
| |
| function showMessage(title, detail) { |
| const overlay = document.getElementById('messageOverlay'); |
| const titleEl = document.getElementById('messageTitle'); |
| const detailEl = document.getElementById('messageDetail'); |
| |
| titleEl.textContent = title; |
| detailEl.textContent = detail; |
| |
| overlay.style.display = 'block'; |
| |
| setTimeout(() => { |
| overlay.style.display = 'none'; |
| }, 2000); |
| } |
| |
| |
| function updateCamera() { |
| if (FSD_CONFIG.cameraMode === 'first') { |
| |
| camera.position.copy(droneGroup.position); |
| camera.position.y += 0.3; |
| camera.position.z += 0.8; |
| camera.rotation.copy(droneGroup.rotation); |
| } else { |
| |
| const cameraOffset = new THREE.Vector3(0, 12, 20); |
| const idealCameraPos = droneGroup.position.clone().add(cameraOffset); |
| camera.position.lerp(idealCameraPos, 0.1); |
| camera.lookAt(droneGroup.position); |
| } |
| } |
| |
| |
| function startFSDTraining() { |
| if (FSD_CONFIG.isTraining && !FSD_CONFIG.isPaused) return; |
| |
| if (FSD_CONFIG.isTraining && FSD_CONFIG.isPaused) { |
| FSD_CONFIG.isPaused = false; |
| clock.start(); |
| document.getElementById('pauseBtn').classList.remove('active'); |
| document.getElementById('startBtn').classList.add('active'); |
| } else { |
| FSD_CONFIG.isTraining = true; |
| FSD_CONFIG.isPaused = false; |
| clock.start(); |
| startPattern(); |
| document.getElementById('startBtn').classList.add('active'); |
| document.getElementById('pauseBtn').classList.remove('active'); |
| document.getElementById('stopBtn').classList.remove('active'); |
| } |
| |
| showMessage('ENHANCED FSD TRAINING STARTED', |
| `Epoch ${FSD_CONFIG.epoch} | Network: ${enhancedNetwork.layers.join('-')} | LR: ${FSD_CONFIG.learningRate.toFixed(4)}`); |
| updateUI(); |
| } |
| |
| function pauseTraining() { |
| if (!FSD_CONFIG.isTraining) return; |
| |
| FSD_CONFIG.isPaused = !FSD_CONFIG.isPaused; |
| if (FSD_CONFIG.isPaused) { |
| clock.stop(); |
| document.getElementById('pauseBtn').classList.add('active'); |
| document.getElementById('startBtn').classList.remove('active'); |
| } else { |
| clock.start(); |
| document.getElementById('pauseBtn').classList.remove('active'); |
| document.getElementById('startBtn').classList.add('active'); |
| } |
| |
| showMessage(FSD_CONFIG.isPaused ? 'TRAINING PAUSED' : 'TRAINING RESUMED', |
| `Epoch ${FSD_CONFIG.epoch} | Iteration ${FSD_CONFIG.iteration}`); |
| updateUI(); |
| } |
| |
| function stopTraining() { |
| FSD_CONFIG.isTraining = false; |
| FSD_CONFIG.isPaused = false; |
| clock.stop(); |
| |
| |
| FSD_CONFIG.dronePosition.set(0, 4, 0); |
| FSD_CONFIG.droneVelocity.set(0, 0, 0); |
| droneGroup.position.copy(FSD_CONFIG.dronePosition); |
| droneGroup.rotation.set(0, 0, 0); |
| |
| |
| FSD_CONFIG.pidController.integral.set(0, 0, 0); |
| FSD_CONFIG.pidController.lastError.set(0, 0, 0); |
| |
| document.getElementById('startBtn').classList.remove('active'); |
| document.getElementById('pauseBtn').classList.remove('active'); |
| document.getElementById('stopBtn').classList.add('active'); |
| |
| showMessage('TRAINING STOPPED', 'Enhanced neural network preserved for next session'); |
| updateUI(); |
| } |
| |
| function emergencyStop() { |
| document.body.style.backgroundColor = '#300'; |
| setTimeout(() => { |
| document.body.style.backgroundColor = '#000'; |
| }, 200); |
| |
| stopTraining(); |
| |
| |
| FSD_CONFIG.collisionCount = 0; |
| FSD_CONFIG.totalPathLength = 0; |
| FSD_CONFIG.crossingCount = 0; |
| FSD_CONFIG.patternCompleted = false; |
| FSD_CONFIG.currentStep = 0; |
| FSD_CONFIG.avoidanceMemory = []; |
| FSD_CONFIG.cumulativeReward = 0; |
| |
| document.getElementById('statusText').textContent = 'EMERGENCY STOP'; |
| document.getElementById('statusDot').style.background = '#f00'; |
| |
| setTimeout(() => { |
| generateNewEpoch(); |
| updateUI(); |
| }, 1000); |
| } |
| |
| function startPattern() { |
| FSD_CONFIG.patternStartTime = Date.now(); |
| FSD_CONFIG.patternCompleted = false; |
| FSD_CONFIG.currentStep = 0; |
| FSD_CONFIG.collisionCount = 0; |
| FSD_CONFIG.totalPathLength = 0; |
| FSD_CONFIG.lastPosition.copy(FSD_CONFIG.dronePosition); |
| FSD_CONFIG.crossingCount = 0; |
| FSD_CONFIG.stuckTimer = 0; |
| FSD_CONFIG.trainingStep = 0; |
| FSD_CONFIG.lastProgressTime = Date.now(); |
| FSD_CONFIG.lastDistanceToTarget = 0; |
| FSD_CONFIG.cumulativeReward = 0; |
| FSD_CONFIG.avgReward = 0; |
| |
| |
| FSD_CONFIG.dronePosition.set(0, 4, 0); |
| FSD_CONFIG.droneVelocity.set(0, 0, 0); |
| |
| |
| FSD_CONFIG.pidController.integral.set(0, 0, 0); |
| FSD_CONFIG.pidController.lastError.set(0, 0, 0); |
| |
| const firstPortalName = FSD_CONFIG.patternSequence[0]; |
| FSD_CONFIG.activePortal = FSD_CONFIG.portals[firstPortalName]; |
| |
| |
| Object.values(FSD_CONFIG.portals).forEach(portal => { |
| if (portal && portal.userData) { |
| portal.userData.collected = false; |
| portal.children.forEach(child => { |
| if (child.material) { |
| child.material.color.setHex(child === portal.children[1] ? 0xff0000 : 0x00ff00); |
| if (child.material.emissive) { |
| child.material.emissive.setHex(child === portal.children[1] ? 0x330000 : 0x003300); |
| } |
| } |
| }); |
| } |
| }); |
| |
| showMessage('ENHANCED TRAINING ITERATION', |
| `Epoch ${FSD_CONFIG.epoch} | Iteration ${FSD_CONFIG.iteration} | Target: ${firstPortalName}`); |
| |
| updateUI(); |
| } |
| |
| function generateNewEpoch() { |
| FSD_CONFIG.epoch++; |
| FSD_CONFIG.iteration = 1; |
| |
| |
| if (FSD_CONFIG.epoch % 2 === 0) { |
| FSD_CONFIG.environment.difficultyLevel = Math.min(3.0, FSD_CONFIG.environment.difficultyLevel + 0.2); |
| FSD_CONFIG.environment.floatingCount = Math.min(25, Math.floor(12 + FSD_CONFIG.environment.difficultyLevel * 3)); |
| FSD_CONFIG.environment.floatingMaxSpeed = Math.min(1.5, 0.5 + FSD_CONFIG.environment.difficultyLevel * 0.3); |
| FSD_CONFIG.environment.bounceEnergy = Math.max(0.6, 0.8 - (FSD_CONFIG.environment.difficultyLevel - 1) * 0.1); |
| } |
| |
| |
| FSD_CONFIG.explorationRate = Math.max(0.1, 0.9 * Math.pow(0.95, FSD_CONFIG.epoch - 1)); |
| FSD_CONFIG.learningRate = 0.001 * Math.pow(0.99, FSD_CONFIG.epoch - 1); |
| enhancedNetwork.learningRate = FSD_CONFIG.learningRate; |
| |
| generateBouncingObstacles(); |
| createPortals(); |
| startPattern(); |
| |
| showMessage('ENHANCED EPOCH ' + FSD_CONFIG.epoch, |
| `Difficulty: ${FSD_CONFIG.environment.difficultyLevel.toFixed(1)}x | ` + |
| `Obstacles: ${FSD_CONFIG.obstacles.length} | ` + |
| `Learning Rate: ${FSD_CONFIG.learningRate.toFixed(4)}`); |
| } |
| |
| function increaseLearningRate() { |
| FSD_CONFIG.learningRate = Math.min(0.01, FSD_CONFIG.learningRate * 1.5); |
| enhancedNetwork.learningRate = FSD_CONFIG.learningRate; |
| FSD_CONFIG.explorationRate = Math.max(0.05, FSD_CONFIG.explorationRate * 0.8); |
| |
| showMessage('LEARNING RATE BOOSTED', |
| `LR: ${FSD_CONFIG.learningRate.toFixed(4)} | Exploration: ${(FSD_CONFIG.explorationRate * 100).toFixed(1)}%`); |
| |
| updateUI(); |
| } |
| |
| function increaseDifficulty() { |
| FSD_CONFIG.environment.difficultyLevel = Math.min(4.0, FSD_CONFIG.environment.difficultyLevel + 0.3); |
| FSD_CONFIG.environment.floatingCount = Math.min(30, FSD_CONFIG.environment.floatingCount + 2); |
| FSD_CONFIG.environment.floatingMaxSpeed = Math.min(2.0, FSD_CONFIG.environment.floatingMaxSpeed + 0.2); |
| FSD_CONFIG.environment.obstacleCount = Math.min(30, FSD_CONFIG.environment.obstacleCount + 2); |
| |
| generateBouncingObstacles(); |
| |
| showMessage('DIFFICULTY INCREASED', |
| `Level: ${FSD_CONFIG.environment.difficultyLevel.toFixed(1)}x | ` + |
| `Floating: ${FSD_CONFIG.environment.floatingCount} | ` + |
| `Speed: ${FSD_CONFIG.environment.floatingMaxSpeed.toFixed(1)}`); |
| |
| updateUI(); |
| } |
| |
| function toggleView() { |
| FSD_CONFIG.cameraMode = FSD_CONFIG.cameraMode === 'first' ? 'third' : 'first'; |
| document.getElementById('viewToggle').classList.toggle('active'); |
| } |
| |
| function toggleFullscreen() { |
| if (!document.fullscreenElement) { |
| document.documentElement.requestFullscreen(); |
| } else { |
| document.exitFullscreen(); |
| } |
| |
| document.getElementById('fullscreenBtn').classList.toggle('active'); |
| } |
| |
| async function exportDataset() { |
| if (FSD_CONFIG.telemetryBuffer.length === 0) { |
| showMessage('NO DATA', 'No training data collected yet!'); |
| return; |
| } |
| |
| const metadata = { |
| generator: "enhanced-fsd-trainer-v3", |
| version: "3.0", |
| export_date: new Date().toISOString(), |
| pattern: FSD_CONFIG.patternSequence.join('→'), |
| total_epochs: FSD_CONFIG.epoch, |
| total_iterations: FSD_CONFIG.iteration, |
| total_training_steps: FSD_CONFIG.trainingStep, |
| total_frames: FSD_CONFIG.telemetryBuffer.length, |
| total_collisions: FSD_CONFIG.collisionCount, |
| best_time: FSD_CONFIG.patternBestTime, |
| success_rate: FSD_CONFIG.successHistory.length > 0 ? |
| (FSD_CONFIG.successHistory.filter(s => s).length / FSD_CONFIG.successHistory.length * 100).toFixed(1) + '%' : '0%', |
| |
| |
| network_architecture: enhancedNetwork.layers, |
| final_learning_rate: FSD_CONFIG.learningRate, |
| final_exploration_rate: FSD_CONFIG.explorationRate, |
| total_train_steps: FSD_CONFIG.trainSteps, |
| |
| |
| environment_config: FSD_CONFIG.environment, |
| difficulty_level: FSD_CONFIG.environment.difficultyLevel, |
| |
| |
| average_reward: FSD_CONFIG.avgReward, |
| cumulative_reward: FSD_CONFIG.cumulativeReward, |
| policy_loss: FSD_CONFIG.policyLoss, |
| value_loss: FSD_CONFIG.valueLoss, |
| td_error: FSD_CONFIG.tdError |
| }; |
| |
| const zip = new JSZip(); |
| |
| |
| const telemetryJsonl = FSD_CONFIG.telemetryBuffer.map(t => JSON.stringify(t)).join('\n'); |
| zip.file("enhanced_telemetry.jsonl", telemetryJsonl); |
| |
| |
| const experiencesJsonl = FSD_CONFIG.memoryBuffer.map(e => JSON.stringify(e)).join('\n'); |
| zip.file("training_experiences.jsonl", experiencesJsonl); |
| |
| |
| const headers = [ |
| 'timestamp', 'frame', 'epoch', 'iteration', 'training_step', 'pattern_step', 'pattern_target', |
| 'pos_x', 'pos_y', 'pos_z', 'vel_x', 'vel_y', 'vel_z', |
| 'target_x', 'target_y', 'target_z', 'distance_to_target', |
| 'q_value', 'cumulative_reward', 'exploration_rate', 'learning_rate', |
| 'td_error', 'policy_loss', 'value_loss', |
| 'collisions', 'path_length', 'crossing_count', 'stuck_timer', |
| 'obstacle_count', 'difficulty_level', |
| 'pattern_time', 'pattern_completed', |
| 'memory_buffer_size', 'train_steps', 'avg_reward' |
| ]; |
| |
| const csvRows = FSD_CONFIG.telemetryBuffer.map(t => [ |
| t.timestamp, |
| t.frame, |
| t.epoch, |
| t.iteration, |
| t.training_step, |
| t.pattern_step, |
| t.pattern_target, |
| t.position[0].toFixed(4), |
| t.position[1].toFixed(4), |
| t.position[2].toFixed(4), |
| t.velocity[0].toFixed(4), |
| t.velocity[1].toFixed(4), |
| t.velocity[2].toFixed(4), |
| t.target_position[0].toFixed(4), |
| t.target_position[1].toFixed(4), |
| t.target_position[2].toFixed(4), |
| t.distance_to_target.toFixed(4), |
| t.q_value?.toFixed(4) || '0', |
| t.cumulative_reward.toFixed(4), |
| t.exploration_rate.toFixed(4), |
| t.learning_rate.toFixed(4), |
| t.td_error?.toFixed(4) || '0', |
| t.policy_loss?.toFixed(4) || '0', |
| t.value_loss?.toFixed(4) || '0', |
| t.collisions, |
| t.path_length.toFixed(2), |
| t.crossing_count, |
| t.stuck_timer?.toFixed(2) || '0', |
| t.obstacle_count, |
| t.difficulty_level?.toFixed(2) || '1.0', |
| t.pattern_time.toFixed(4), |
| t.pattern_completed, |
| t.memory_buffer_size, |
| t.train_steps || '0', |
| t.avg_reward?.toFixed(4) || '0' |
| ].join(',')); |
| |
| const csvContent = headers.join(',') + '\n' + csvRows.join('\n'); |
| zip.file("enhanced_telemetry.csv", csvContent); |
| |
| |
| zip.file("metadata.json", JSON.stringify(metadata, null, 2)); |
| |
| |
| if (FSD_CONFIG.successfulPaths.length > 0) { |
| zip.file("successful_paths.json", JSON.stringify(FSD_CONFIG.successfulPaths, null, 2)); |
| } |
| |
| |
| const networkData = { |
| architecture: enhancedNetwork.layers, |
| weights_shape: enhancedNetwork.weights.map(w => [w.length, w[0].length]), |
| biases_shape: enhancedNetwork.biases.map(b => b.length), |
| learning_rate: enhancedNetwork.learningRate, |
| export_timestamp: Date.now() |
| }; |
| zip.file("enhanced_network.json", JSON.stringify(networkData, null, 2)); |
| |
| const content = await zip.generateAsync({type: "blob"}); |
| const url = URL.createObjectURL(content); |
| const a = document.createElement('a'); |
| a.href = url; |
| a.download = `enhanced-fsd-dataset-epoch${FSD_CONFIG.epoch}-v3-${Date.now()}.zip`; |
| document.body.appendChild(a); |
| a.click(); |
| document.body.removeChild(a); |
| URL.revokeObjectURL(url); |
| |
| showMessage('ENHANCED DATASET EXPORTED', |
| `${FSD_CONFIG.telemetryBuffer.length} frames | ` + |
| `${FSD_CONFIG.memoryBuffer.length} experiences | ` + |
| `${FSD_CONFIG.trainSteps} training steps`); |
| } |
| |
| |
| function setupEventListeners() { |
| document.getElementById('startBtn').addEventListener('click', startFSDTraining); |
| document.getElementById('pauseBtn').addEventListener('click', pauseTraining); |
| document.getElementById('stopBtn').addEventListener('click', stopTraining); |
| document.getElementById('exportBtn').addEventListener('click', exportDataset); |
| document.getElementById('emergencyStop').addEventListener('click', emergencyStop); |
| document.getElementById('viewToggle').addEventListener('click', toggleView); |
| document.getElementById('fullscreenBtn').addEventListener('click', toggleFullscreen); |
| document.getElementById('newEpochBtn').addEventListener('click', generateNewEpoch); |
| document.getElementById('speedBtn').addEventListener('click', increaseLearningRate); |
| document.getElementById('difficultyBtn').addEventListener('click', increaseDifficulty); |
| document.getElementById('trainingBtn').addEventListener('click', () => { |
| showMessage('ENHANCED FSD TRAINING STATUS', |
| `Network: ${enhancedNetwork.layers.join('-')}\n` + |
| `Learning Rate: ${FSD_CONFIG.learningRate.toFixed(4)}\n` + |
| `Exploration: ${(FSD_CONFIG.explorationRate * 100).toFixed(1)}%\n` + |
| `Memory: ${FSD_CONFIG.memoryBuffer.length}/${FSD_CONFIG.maxMemorySize}\n` + |
| `Training Steps: ${FSD_CONFIG.trainSteps}`); |
| }); |
| } |
| |
| |
| function init() { |
| setupThreeJS(); |
| setupScene(); |
| generateBouncingObstacles(); |
| createPortals(); |
| setupEventListeners(); |
| updateUI(); |
| |
| document.getElementById('stopBtn').classList.add('active'); |
| document.getElementById('statusText').textContent = 'ENHANCED FSD READY FOR TRAINING'; |
| |
| showMessage('ENHANCED FSD TRAINER v3.0', |
| '256-128-64-32 Neural Network with PPO Training\n' + |
| 'Enhanced Obstacle Avoidance with PID Control\n' + |
| 'Real-time Telemetry and Visualization\n' + |
| 'Adaptive Difficulty and Learning Rate'); |
| |
| function animate() { |
| requestAnimationFrame(animate); |
| |
| const delta = Math.min(clock.getDelta(), 0.05); |
| |
| if (FSD_CONFIG.isTraining && !FSD_CONFIG.isPaused) { |
| |
| enhancedFSDAutoPilot(delta); |
| |
| |
| updateBouncingObstacles(delta); |
| |
| |
| Object.values(FSD_CONFIG.portals).forEach(portal => { |
| if (portal && portal.userData) { |
| if (!portal.userData.collected) { |
| portal.rotation.y += portal.userData.rotationSpeed; |
| |
| portal.userData.pulsePhase += 0.1; |
| const pulse = 0.7 + 0.3 * Math.sin(portal.userData.pulsePhase); |
| portal.children.forEach(child => { |
| if (child.material && child.material.opacity !== undefined) { |
| child.material.opacity = pulse * 0.7; |
| } |
| }); |
| } |
| } |
| }); |
| |
| |
| droneGroup.children.forEach(child => { |
| if (child.userData && child.userData.rotationSpeed) { |
| child.rotation.y += child.userData.rotationSpeed * delta * 10; |
| } |
| }); |
| } |
| |
| |
| updateCamera(); |
| |
| |
| updateUI(); |
| |
| renderer.render(scene, camera); |
| } |
| |
| animate(); |
| } |
| |
| |
| window.addEventListener('resize', () => { |
| if (camera && renderer) { |
| camera.aspect = window.innerWidth / window.innerHeight; |
| camera.updateProjectionMatrix(); |
| renderer.setSize(window.innerWidth, window.innerHeight); |
| |
| [waveCanvas, pathCanvas, nnCanvas].forEach(canvas => { |
| if (canvas) { |
| canvas.width = canvas.offsetWidth; |
| canvas.height = canvas.offsetHeight; |
| } |
| }); |
| } |
| }); |
| |
| |
| window.addEventListener('load', init); |
| </script> |
| </body> |
| </html> |
|
|