wavebender_dataset / generator /webXOS_wavebender_betatest.html
webxos's picture
Rename webXOS_wavebender_betatest.html to generator/webXOS_wavebender_betatest.html
1d23547 verified
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, user-scalable=yes">
<title>WAVE BENDER IDE v5.0 - BETA TEST by webXOS</title>
<meta name="theme-color" content="#000000">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
background: #000;
color: #0f0;
font-family: 'Courier New', monospace;
overflow: hidden;
height: 100vh;
}
/* Cyberpunk CRT Effects */
.crt-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 9999;
}
.crt-scanlines {
position: absolute;
width: 100%;
height: 100%;
background: linear-gradient(
to bottom,
transparent 50%,
rgba(0, 255, 0, 0.03) 50%
);
background-size: 100% 4px;
animation: scanlines 8s linear infinite;
}
.crt-glitch {
position: absolute;
width: 100%;
height: 100%;
background: linear-gradient(
90deg,
rgba(0, 255, 0, 0.02) 1px,
transparent 1px
);
background-size: 3px 100%;
animation: glitch 3s infinite;
}
@keyframes scanlines {
0% { background-position: 0 0; }
100% { background-position: 0 100%; }
}
@keyframes glitch {
0%, 100% { transform: translateX(0); opacity: 1; }
5% { transform: translateX(-2px); opacity: 0.8; }
10% { transform: translateX(2px); opacity: 0.9; }
15% { transform: translateX(-1px); opacity: 0.7; }
95% { transform: translateX(0); opacity: 1; }
}
/* Main Container */
#main-container {
display: flex;
height: 100vh;
padding: 10px;
gap: 10px;
}
/* Control Panel */
#control-panel {
width: 320px;
background: rgba(0, 20, 0, 0.85);
border: 3px solid #0f0;
padding: 20px;
display: flex;
flex-direction: column;
gap: 20px;
overflow-y: auto;
box-shadow: 0 0 30px rgba(0, 255, 0, 0.2);
position: relative;
z-index: 10;
}
/* Title Section */
.title-section {
text-align: center;
padding-bottom: 15px;
border-bottom: 2px solid #0f0;
margin-bottom: 15px;
}
.main-title {
font-size: 28px;
color: #0f0;
text-shadow: 0 0 15px #0f0;
margin-bottom: 5px;
letter-spacing: 2px;
}
.version-badge {
background: #0f0;
color: #000;
padding: 3px 10px;
font-size: 12px;
border-radius: 3px;
display: inline-block;
margin-bottom: 10px;
}
.subtitle {
font-size: 11px;
color: #0a0;
opacity: 0.9;
line-height: 1.4;
}
/* Control Groups */
.control-group {
background: rgba(0, 30, 0, 0.4);
border: 1px solid #0a0;
padding: 15px;
margin-bottom: 15px;
border-radius: 3px;
}
.group-title {
color: #0ff;
font-size: 14px;
margin-bottom: 12px;
text-transform: uppercase;
letter-spacing: 1px;
display: flex;
align-items: center;
gap: 8px;
}
.group-title::before {
content: ">";
color: #0f0;
}
/* Sliders */
.slider-container {
margin-bottom: 12px;
}
.slider-label {
display: flex;
justify-content: space-between;
color: #0a0;
font-size: 12px;
margin-bottom: 6px;
}
.slider-value {
color: #0ff;
font-weight: bold;
}
input[type="range"] {
width: 100%;
height: 6px;
-webkit-appearance: none;
background: #002200;
border: 1px solid #0a0;
border-radius: 3px;
outline: none;
}
input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none;
width: 18px;
height: 18px;
background: #0f0;
border: 2px solid #000;
border-radius: 50%;
cursor: pointer;
box-shadow: 0 0 10px #0f0;
transition: all 0.2s;
}
input[type="range"]::-webkit-slider-thumb:hover {
background: #0ff;
box-shadow: 0 0 15px #0ff;
}
/* Buttons */
.button-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 10px;
margin-top: 15px;
}
.cyber-button {
padding: 12px 15px;
background: #000;
border: 2px solid;
color: inherit;
font-family: 'Courier New', monospace;
font-size: 13px;
font-weight: bold;
cursor: pointer;
text-transform: uppercase;
letter-spacing: 1px;
transition: all 0.3s;
position: relative;
overflow: hidden;
z-index: 1;
}
.cyber-button::before {
content: '';
position: absolute;
top: 0;
left: -100%;
width: 100%;
height: 100%;
background: linear-gradient(90deg, transparent, rgba(255,255,255,0.1), transparent);
transition: left 0.5s;
z-index: -1;
}
.cyber-button:hover::before {
left: 100%;
}
.cyber-button:hover {
transform: translateY(-2px);
box-shadow: 0 5px 15px currentColor;
}
.cyber-button:active {
transform: translateY(0);
}
.cyber-button.primary {
border-color: #0ff;
color: #0ff;
}
.cyber-button.primary:hover {
background: #0ff;
color: #000;
}
.cyber-button.secondary {
border-color: #0f0;
color: #0f0;
}
.cyber-button.secondary:hover {
background: #0f0;
color: #000;
}
.cyber-button.warning {
border-color: #ff0;
color: #ff0;
}
.cyber-button.warning:hover {
background: #ff0;
color: #000;
}
.cyber-button.danger {
border-color: #f00;
color: #f00;
}
.cyber-button.danger:hover {
background: #f00;
color: #fff;
}
/* Toggle Switch */
.toggle-container {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 10px;
}
.toggle-label {
color: #0a0;
font-size: 13px;
}
.toggle-switch {
position: relative;
width: 50px;
height: 24px;
}
.toggle-switch input {
opacity: 0;
width: 0;
height: 0;
}
.toggle-slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #002200;
border: 1px solid #0a0;
transition: .4s;
border-radius: 34px;
}
.toggle-slider:before {
position: absolute;
content: "";
height: 16px;
width: 16px;
left: 4px;
bottom: 3px;
background-color: #0a0;
transition: .4s;
border-radius: 50%;
}
input:checked + .toggle-slider {
background-color: #0f0;
}
input:checked + .toggle-slider:before {
transform: translateX(26px);
background-color: #000;
}
/* Telemetry Display */
.telemetry-panel {
background: rgba(0, 20, 0, 0.6);
border: 1px solid #0a0;
padding: 15px;
border-radius: 3px;
}
.telemetry-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 10px;
margin-top: 10px;
}
.telemetry-card {
background: rgba(0, 40, 0, 0.5);
border: 1px solid #0a0;
padding: 10px;
border-radius: 3px;
}
.telemetry-label {
color: #0a0;
font-size: 10px;
margin-bottom: 5px;
text-transform: uppercase;
}
.telemetry-value {
color: #0f0;
font-size: 18px;
font-weight: bold;
font-family: 'Courier New', monospace;
text-shadow: 0 0 5px #0f0;
}
/* Training Stats */
.training-stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
margin-top: 10px;
}
.stat-card {
text-align: center;
padding: 10px;
background: rgba(0, 30, 0, 0.4);
border: 1px solid #0ff;
border-radius: 3px;
}
.stat-value {
font-size: 20px;
color: #0ff;
font-weight: bold;
margin-bottom: 3px;
}
.stat-label {
font-size: 9px;
color: #0aa;
text-transform: uppercase;
}
/* Visualization Panel */
#viz-panel {
flex: 1;
background: rgba(0, 10, 0, 0.9);
border: 3px solid #0f0;
position: relative;
overflow: hidden;
box-shadow: 0 0 30px rgba(0, 255, 0, 0.2);
}
#renderCanvas {
width: 100%;
height: 100%;
display: block;
}
/* 3D Overlay Controls */
.overlay-controls {
position: absolute;
top: 15px;
right: 15px;
display: flex;
gap: 10px;
z-index: 100;
}
.overlay-button {
width: 40px;
height: 40px;
background: rgba(0, 20, 0, 0.8);
border: 2px solid #0ff;
color: #0ff;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
font-size: 18px;
transition: all 0.3s;
}
.overlay-button:hover {
background: #0ff;
color: #000;
box-shadow: 0 0 15px #0ff;
}
/* Training Info Overlay */
.training-info {
position: absolute;
top: 15px;
left: 15px;
background: rgba(0, 20, 0, 0.85);
border: 2px solid #f0f;
padding: 12px 20px;
font-size: 14px;
color: #f0f;
z-index: 100;
text-transform: uppercase;
letter-spacing: 1px;
box-shadow: 0 0 15px rgba(255, 0, 255, 0.3);
}
.training-progress {
position: absolute;
bottom: 200px;
left: 20px;
right: 20px;
height: 10px;
background: #002200;
border: 1px solid #0a0;
border-radius: 5px;
overflow: hidden;
z-index: 100;
}
.progress-fill {
height: 100%;
background: linear-gradient(90deg, #0f0, #0ff);
width: 0%;
transition: width 0.5s;
box-shadow: 0 0 10px #0f0;
}
/* Graph Panel */
.graph-panel {
position: absolute;
bottom: 15px;
left: 15px;
right: 15px;
height: 170px;
background: rgba(0, 20, 0, 0.95);
border: 2px solid #0f0;
padding: 15px;
z-index: 100;
box-shadow: 0 0 20px rgba(0, 255, 0, 0.3);
}
.graph-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
}
.graph-title {
color: #0ff;
font-size: 14px;
text-transform: uppercase;
letter-spacing: 1px;
}
.graph-controls {
display: flex;
gap: 10px;
}
.graph-canvas-container {
width: 100%;
height: calc(100% - 30px);
background: rgba(0, 10, 0, 0.8);
border: 1px solid #0a0;
position: relative;
}
#graphCanvas {
width: 100%;
height: 100%;
display: block;
}
/* Status Bar */
.status-bar {
position: absolute;
bottom: 0;
left: 0;
right: 0;
background: rgba(0, 30, 0, 0.95);
border-top: 2px solid #0f0;
padding: 10px 20px;
display: flex;
justify-content: space-between;
align-items: center;
z-index: 101;
font-size: 12px;
}
.status-item {
display: flex;
align-items: center;
gap: 10px;
}
.status-led {
width: 10px;
height: 10px;
border-radius: 50%;
background: #0f0;
animation: pulse 2s infinite;
box-shadow: 0 0 10px #0f0;
}
.status-led.active { background: #0f0; animation: pulse 1s infinite; }
.status-led.warning { background: #ff0; animation: pulse 0.5s infinite; }
.status-led.error { background: #f00; animation: pulse 0.3s infinite; }
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.3; }
}
/* Terminal */
.terminal-panel {
background: rgba(0, 10, 0, 0.95);
border: 2px solid #0f0;
padding: 15px;
height: 200px;
overflow-y: auto;
margin-top: 15px;
border-radius: 3px;
}
.terminal-line {
margin-bottom: 4px;
padding: 2px 0;
border-bottom: 1px solid rgba(0, 255, 0, 0.1);
font-size: 11px;
line-height: 1.4;
}
.terminal-time {
color: #0a0;
margin-right: 8px;
}
.terminal-content.system { color: #0ff; }
.terminal-content.info { color: #0f0; }
.terminal-content.warning { color: #ff0; }
.terminal-content.error { color: #f00; }
.terminal-content.success { color: #0f0; font-weight: bold; }
.terminal-content.dataset { color: #f0f; }
.terminal-content.training { color: #0ff; }
/* Modal */
.modal-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.85);
z-index: 1000;
display: none;
align-items: center;
justify-content: center;
}
.modal-overlay.active {
display: flex;
animation: fadeIn 0.3s;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.modal-container {
background: rgba(0, 20, 0, 0.95);
border: 3px solid #0f0;
width: 600px;
max-width: 90%;
max-height: 90%;
overflow-y: auto;
padding: 30px;
box-shadow: 0 0 50px rgba(0, 255, 0, 0.3);
}
.modal-header {
text-align: center;
margin-bottom: 25px;
}
.modal-title {
color: #0ff;
font-size: 22px;
margin-bottom: 10px;
text-transform: uppercase;
letter-spacing: 2px;
}
.modal-subtitle {
color: #0a0;
font-size: 13px;
}
.export-options {
margin: 20px 0;
}
.export-option {
margin-bottom: 15px;
padding: 10px;
background: rgba(0, 30, 0, 0.5);
border: 1px solid #0a0;
border-radius: 3px;
}
.export-option label {
color: #0a0;
font-size: 14px;
display: flex;
align-items: center;
gap: 10px;
cursor: pointer;
}
.export-option input[type="checkbox"] {
width: 20px;
height: 20px;
accent-color: #0f0;
cursor: pointer;
}
.modal-actions {
display: flex;
gap: 15px;
margin-top: 30px;
}
.progress-container {
margin: 20px 0;
background: rgba(0, 30, 0, 0.5);
border: 1px solid #0a0;
padding: 10px;
border-radius: 3px;
}
.progress-bar {
height: 10px;
background: #002200;
border: 1px solid #0a0;
border-radius: 5px;
overflow: hidden;
margin-bottom: 10px;
}
.progress-fill {
height: 100%;
background: linear-gradient(90deg, #0f0, #0ff);
width: 0%;
transition: width 0.3s;
box-shadow: 0 0 10px #0f0;
}
.progress-text {
color: #0ff;
font-size: 12px;
text-align: center;
}
/* Training Mode Badges */
.training-badges {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 10px;
}
.training-badge {
background: rgba(0, 255, 255, 0.1);
border: 1px solid #0ff;
color: #0ff;
padding: 4px 10px;
font-size: 10px;
border-radius: 3px;
text-transform: uppercase;
}
/* Responsive */
@media (max-width: 1200px) {
#main-container {
flex-direction: column;
}
#control-panel {
width: 100%;
height: 400px;
}
#viz-panel {
height: calc(100vh - 430px);
}
}
@media (max-width: 768px) {
.telemetry-grid, .training-stats {
grid-template-columns: 1fr;
}
.button-grid {
grid-template-columns: 1fr;
}
.status-bar {
flex-direction: column;
gap: 10px;
padding: 10px;
}
.graph-panel {
height: 150px;
}
}
/* Loading Screen */
.loading-screen {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: #000;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
z-index: 10000;
}
.loading-logo {
font-size: 48px;
color: #0f0;
text-shadow: 0 0 20px #0f0;
margin-bottom: 20px;
letter-spacing: 5px;
}
.loading-bar {
width: 300px;
height: 4px;
background: #002200;
border: 1px solid #0a0;
border-radius: 2px;
overflow: hidden;
margin-top: 20px;
}
.loading-progress {
height: 100%;
background: #0f0;
width: 0%;
transition: width 0.3s;
}
</style>
</head>
<body>
<!-- Loading Screen -->
<div class="loading-screen" id="loadingScreen">
<div class="loading-logo">WAVE BENDER BETA</div>
<div>IDE BETA v5.0 - Loading Training System</div>
<div class="loading-bar">
<div class="loading-progress" id="loadingProgress"></div>
</div>
</div>
<!-- CRT Effects -->
<div class="crt-overlay">
<div class="crt-scanlines"></div>
<div class="crt-glitch"></div>
</div>
<!-- Main Container -->
<div id="main-container">
<!-- Control Panel -->
<div id="control-panel">
<!-- Title Section -->
<div class="title-section">
<div class="main-title">WAVE BENDER IDE</div>
<div class="version-badge">v5.0 - TRAINING DATASET GENERATOR</div>
<div class="subtitle">
Synthetic Telemetry & SLAM Training System<br>
Generate ML-ready datasets for drone autonomy
</div>
</div>
<!-- Generation Controls -->
<div class="control-group">
<div class="group-title">GENERATION PARAMETERS</div>
<div class="slider-container">
<div class="slider-label">
<span>Dataset Complexity</span>
<span class="slider-value" id="complexityValue">7</span>
</div>
<input type="range" id="complexitySlider" min="1" max="10" value="7" step="1">
</div>
<div class="slider-container">
<div class="slider-label">
<span>Signal Noise Level</span>
<span class="slider-value" id="noiseValue">2.5</span>
</div>
<input type="range" id="noiseSlider" min="0" max="5" value="2.5" step="0.1">
</div>
<div class="slider-container">
<div class="slider-label">
<span>Oscillation Frequency</span>
<span class="slider-value" id="frequencyValue">1.8</span>
</div>
<input type="range" id="frequencySlider" min="0.5" max="3" value="1.8" step="0.1">
</div>
<div class="slider-container">
<div class="slider-label">
<span>Sample Rate (Hz)</span>
<span class="slider-value" id="sampleRateValue">100</span>
</div>
<input type="range" id="sampleRateSlider" min="10" max="200" value="100" step="10">
</div>
</div>
<!-- SLAM Training Controls -->
<div class="control-group">
<div class="group-title">SLAM TRAINING CONFIG</div>
<div class="toggle-container">
<span class="toggle-label">Center Region Obstacles</span>
<label class="toggle-switch">
<input type="checkbox" id="centerObstaclesToggle" checked>
<span class="toggle-slider"></span>
</label>
</div>
<div class="toggle-container">
<span class="toggle-label">Dynamic Obstacle Movement</span>
<label class="toggle-switch">
<input type="checkbox" id="dynamicObstaclesToggle" checked>
<span class="toggle-slider"></span>
</label>
</div>
<div class="toggle-container">
<span class="toggle-label">Collision Avoidance Training</span>
<label class="toggle-switch">
<input type="checkbox" id="avoidanceTrainingToggle" checked>
<span class="toggle-slider"></span>
</label>
</div>
<div class="button-grid">
<button id="addObstacleBtn" class="cyber-button secondary">ADD OBSTACLE</button>
<button id="resetObstaclesBtn" class="cyber-button warning">RESET OBSTACLES</button>
<button id="autoPilotBtn" class="cyber-button primary">AUTO PILOT</button>
<button id="trainingModeBtn" class="cyber-button" style="border-color:#f0f;color:#f0f;">TRAINING MODE</button>
</div>
</div>
<!-- Telemetry Display -->
<div class="telemetry-panel">
<div class="group-title">REAL-TIME TELEMETRY</div>
<div class="telemetry-grid">
<div class="telemetry-card">
<div class="telemetry-label">TIMESTAMP</div>
<div class="telemetry-value" id="telemetryTime">00:00:00</div>
</div>
<div class="telemetry-card">
<div class="telemetry-label">ALTITUDE</div>
<div class="telemetry-value" id="telemetryAlt">10.0m</div>
</div>
<div class="telemetry-card">
<div class="telemetry-label">VELOCITY</div>
<div class="telemetry-value" id="telemetryVel">0.0m/s</div>
</div>
<div class="telemetry-card">
<div class="telemetry-label">BATTERY</div>
<div class="telemetry-value" id="telemetryBat">100%</div>
</div>
</div>
<div class="training-stats">
<div class="stat-card">
<div class="stat-value" id="statObstacles">15</div>
<div class="stat-label">OBSTACLES</div>
</div>
<div class="stat-card">
<div class="stat-value" id="statAvoidances">0</div>
<div class="stat-label">AVOIDANCES</div>
</div>
<div class="stat-card">
<div class="stat-value" id="statPoints">0</div>
<div class="stat-label">DATA POINTS</div>
</div>
</div>
</div>
<!-- Main Controls -->
<div class="button-grid">
<button id="startBtn" class="cyber-button primary">START TRAINING</button>
<button id="stopBtn" class="cyber-button danger" disabled>STOP TRAINING</button>
<button id="exportBtn" class="cyber-button secondary">EXPORT DATASET</button>
<button id="resetBtn" class="cyber-button warning">RESET SYSTEM</button>
</div>
<!-- Training Modes -->
<div class="training-badges">
<div class="training-badge">SLAM TRAINING</div>
<div class="training-badge">OBSTACLE AVOIDANCE</div>
<div class="training-badge">REAL-TIME TELEMETRY</div>
<div class="training-badge">ML DATASET GENERATION</div>
</div>
<!-- Terminal -->
<div class="terminal-panel" id="terminal">
<div class="terminal-line">
<span class="terminal-time">[00:00:00]</span>
<span class="terminal-content system">WAVE BENDER IDE v5.0 INITIALIZED</span>
</div>
<div class="terminal-line">
<span class="terminal-time">[00:00:00]</span>
<span class="terminal-content system">Training Dataset Generator Ready</span>
</div>
<div class="terminal-line">
<span class="terminal-time">[00:00:00]</span>
<span class="terminal-content training">SLAM Training Mode: ACTIVE</span>
</div>
<div class="terminal-line">
<span class="terminal-time">[00:00:00]</span>
<span class="terminal-content dataset">Ready to generate ML training datasets</span>
</div>
</div>
</div>
<!-- Visualization Panel -->
<div id="viz-panel">
<canvas id="renderCanvas"></canvas>
<!-- Training Info -->
<div class="training-info">
CENTER REGION OBSTACLE TRAINING - SLAM DATASET GENERATION
</div>
<!-- Overlay Controls -->
<div class="overlay-controls">
<button class="overlay-button" id="fullscreenBtn" title="Fullscreen"></button>
<button class="overlay-button" id="cameraResetBtn" title="Reset Camera"></button>
<button class="overlay-button" id="gridToggleBtn" title="Toggle Grid">#</button>
</div>
<!-- Training Progress -->
<div class="training-progress">
<div class="progress-fill" id="trainingProgress"></div>
</div>
<!-- Graph Panel -->
<div class="graph-panel">
<div class="graph-header">
<div class="graph-title">REAL-TIME TELEMETRY SIGNALS</div>
<div class="graph-controls">
<button class="cyber-button secondary" style="padding:5px 10px;font-size:11px;" id="clearGraphBtn">CLEAR</button>
<button class="cyber-button secondary" style="padding:5px 10px;font-size:11px;" id="pauseGraphBtn">PAUSE</button>
</div>
</div>
<div class="graph-canvas-container">
<canvas id="graphCanvas"></canvas>
</div>
</div>
<!-- Status Bar -->
<div class="status-bar">
<div class="status-item">
<div class="status-led inactive" id="statusGen"></div>
<span>TRAINING: PAUSED</span>
</div>
<div class="status-item">
<div class="status-led active" id="status3D"></div>
<span>3D VISUALIZATION: ACTIVE</span>
</div>
<div class="status-item">
<div class="status-led active" id="statusSLAM"></div>
<span>SLAM: TRAINING MODE</span>
</div>
<div class="status-item">
<div class="status-led active" id="statusWASM"></div>
<span>COMPUTE: ONLINE</span>
</div>
<div class="status-item">
<span id="statusFPS">FPS: 60</span>
</div>
<div class="status-item">
<span>webXOS | HF DATASET READY</span>
</div>
</div>
</div>
</div>
<!-- Export Modal -->
<div class="modal-overlay" id="exportModal">
<div class="modal-container">
<div class="modal-header">
<div class="modal-title">EXPORT TRAINING DATASET</div>
<div class="modal-subtitle">Generate complete ML-ready dataset package for Hugging Face</div>
</div>
<div class="export-options">
<div class="export-option">
<label>
<input type="checkbox" id="exportTelemetry" checked>
<span>Complete Telemetry Dataset (JSONL/CSV)</span>
</label>
</div>
<div class="export-option">
<label>
<input type="checkbox" id="exportSLAM" checked>
<span>SLAM Training Data (Obstacle Detection & Avoidance)</span>
</label>
</div>
<div class="export-option">
<label>
<input type="checkbox" id="exportGraphs" checked>
<span>Signal Graphs & Visualizations</span>
</label>
</div>
<div class="export-option">
<label>
<input type="checkbox" id="exportMetadata" checked>
<span>Dataset Metadata & Documentation</span>
</label>
</div>
<div class="export-option">
<label>
<input type="checkbox" id="exportTrainingStats" checked>
<span>Training Statistics & Epoch Data</span>
</label>
</div>
</div>
<div class="progress-container">
<div class="progress-bar" id="exportProgressBar">
<div class="progress-fill" id="exportProgressFill"></div>
</div>
<div class="progress-text" id="exportStatus">Ready to export...</div>
</div>
<div class="modal-actions">
<button id="exportCancel" class="cyber-button warning" style="flex:1;">CANCEL</button>
<button id="exportConfirm" class="cyber-button primary" style="flex:2;">GENERATE COMPLETE DATASET .ZIP</button>
</div>
</div>
</div>
<!-- Libraries -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.7.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
<script>
// ============================================
// WAVE BENDER IDE v5.0 - Training Dataset Generator
// ============================================
// Application State
const AppState = {
// Core State
isTraining: false,
isAutoPilot: false,
isPaused: false,
trainingStartTime: 0,
currentTime: 0,
frameCount: 0,
fps: 60,
lastFpsUpdate: 0,
// Training Parameters
params: {
complexity: 7,
noise: 2.5,
frequency: 1.8,
sampleRate: 100
},
// Dataset Storage
dataset: {
telemetry: [],
slamData: [],
trainingEpochs: [],
statistics: {
totalPoints: 0,
obstaclesDetected: 0,
avoidanceManeuvers: 0,
trainingProgress: 0
}
},
// Graph Data
graphs: {
acceleration: [],
altitude: [],
battery: [],
velocity: [],
maxPoints: 300,
isPaused: false
},
// SLAM Training
slam: {
obstacles: [],
centerRegion: true,
dynamicMovement: true,
avoidanceTraining: true,
currentEpoch: 1
}
};
// Three.js Scene
const Scene3D = {
scene: null,
camera: null,
renderer: null,
drone: null,
obstacles: [],
centerGrid: null
};
// Graph Context
let graphCtx = null;
let graphWidth = 0;
let graphHeight = 0;
// Animation & Intervals
let animationFrameId = null;
let trainingInterval = null;
let autoPilotInterval = null;
let obstacleInterval = null;
// ============================================
// INITIALIZATION
// ============================================
async function init() {
try {
// Simulate loading progress
simulateLoading();
// Initialize systems
await initThreeJS();
initGraphCanvas();
initTrainingSystem();
initEventListeners();
// Finalize loading
setTimeout(() => {
document.getElementById('loadingScreen').style.opacity = '0';
setTimeout(() => {
document.getElementById('loadingScreen').style.display = 'none';
}, 300);
logMessage("System initialization complete", "system");
logMessage("Training dataset generator ready", "training");
logMessage("Start training to generate ML datasets", "dataset");
// Start animation loop
animate();
}, 1500);
} catch (error) {
console.error("Initialization error:", error);
logMessage(`Initialization failed: ${error.message}`, "error");
}
}
function simulateLoading() {
const progress = document.getElementById('loadingProgress');
let width = 0;
const steps = [
{ msg: "Loading 3D Visualization Engine", duration: 300 },
{ msg: "Initializing WebAssembly Compute Core", duration: 400 },
{ msg: "Setting Up SLAM Training System", duration: 350 },
{ msg: "Preparing Dataset Generation", duration: 250 },
{ msg: "Finalizing Training Interface", duration: 200 }
];
steps.forEach((step, index) => {
setTimeout(() => {
width = ((index + 1) / steps.length) * 100;
progress.style.width = `${width}%`;
document.querySelector('.loading-screen div:nth-child(2)').textContent = step.msg;
}, step.duration);
});
}
// ============================================
// 3D VISUALIZATION
// ============================================
async function initThreeJS() {
try {
// Create scene
Scene3D.scene = new THREE.Scene();
Scene3D.scene.background = new THREE.Color(0x000000);
Scene3D.scene.fog = new THREE.Fog(0x000000, 50, 300);
// Create camera
const canvas = document.getElementById('renderCanvas');
Scene3D.camera = new THREE.PerspectiveCamera(
60, canvas.clientWidth / canvas.clientHeight, 0.1, 1000
);
Scene3D.camera.position.set(40, 30, 50);
Scene3D.camera.lookAt(0, 0, 0);
// Create renderer
Scene3D.renderer = new THREE.WebGLRenderer({
canvas: canvas,
antialias: true,
alpha: true
});
Scene3D.renderer.setSize(canvas.clientWidth, canvas.clientHeight);
Scene3D.renderer.shadowMap.enabled = true;
Scene3D.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
// Lighting
const ambientLight = new THREE.AmbientLight(0x00ff00, 0.1);
Scene3D.scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0x00ff00, 0.6);
directionalLight.position.set(20, 40, 30);
directionalLight.castShadow = true;
Scene3D.scene.add(directionalLight);
// Grids
const mainGrid = new THREE.GridHelper(100, 20, 0x004400, 0x002200);
Scene3D.scene.add(mainGrid);
Scene3D.centerGrid = new THREE.GridHelper(40, 10, 0xff0000, 0x660000);
Scene3D.centerGrid.position.y = 0.1;
Scene3D.scene.add(Scene3D.centerGrid);
// Axes
const axes = new THREE.AxesHelper(25);
Scene3D.scene.add(axes);
// Create drone
createDrone();
// Create initial obstacles
createTrainingObstacles();
logMessage("3D visualization engine initialized", "success");
} catch (error) {
throw new Error(`3D initialization failed: ${error.message}`);
}
}
function createDrone() {
const droneGroup = new THREE.Group();
// Body
const bodyGeometry = new THREE.BoxGeometry(3, 0.5, 3);
const bodyMaterial = new THREE.MeshPhongMaterial({
color: 0x00ff00,
emissive: 0x004400,
shininess: 100
});
const body = new THREE.Mesh(bodyGeometry, bodyMaterial);
body.castShadow = true;
droneGroup.add(body);
// Arms and Motors
const armGeometry = new THREE.BoxGeometry(6, 0.3, 0.3);
const armMaterial = new THREE.MeshPhongMaterial({ color: 0x008800 });
for (let i = 0; i < 4; i++) {
const arm = new THREE.Mesh(armGeometry, armMaterial);
arm.rotation.y = (Math.PI / 2) * i;
arm.position.y = 0.25;
arm.castShadow = true;
droneGroup.add(arm);
// Motor
const motorGeometry = new THREE.CylinderGeometry(0.8, 0.8, 0.5, 8);
const motorMaterial = new THREE.MeshPhongMaterial({ color: 0x00aa00 });
const motor = new THREE.Mesh(motorGeometry, motorMaterial);
motor.position.set(armGeometry.parameters.width / 2, 0.5, 0);
motor.rotation.x = Math.PI / 2;
arm.add(motor);
// Propeller
const propGeometry = new THREE.BoxGeometry(3, 0.1, 0.3);
const propMaterial = new THREE.MeshPhongMaterial({ color: 0x00ff00 });
const propeller = new THREE.Mesh(propGeometry, propMaterial);
propeller.position.y = 0.8;
motor.add(propeller);
if (!droneGroup.propellers) droneGroup.propellers = [];
droneGroup.propellers.push(propeller);
}
// LEDs
const ledGeometry = new THREE.SphereGeometry(0.2, 8, 8);
const ledPositions = [
{ x: 1.2, y: 0.5, z: 1.2, color: 0xff0000 },
{ x: -1.2, y: 0.5, z: 1.2, color: 0x00ff00 },
{ x: -1.2, y: 0.5, z: -1.2, color: 0x0000ff },
{ x: 1.2, y: 0.5, z: -1.2, color: 0xffff00 }
];
ledPositions.forEach(pos => {
const ledMaterial = new THREE.MeshBasicMaterial({
color: pos.color,
emissive: pos.color,
emissiveIntensity: 0.5
});
const led = new THREE.Mesh(ledGeometry, ledMaterial);
led.position.set(pos.x, pos.y, pos.z);
droneGroup.add(led);
});
droneGroup.position.set(0, 10, 0);
Scene3D.drone = droneGroup;
Scene3D.scene.add(droneGroup);
}
function createTrainingObstacles() {
// Clear existing obstacles
Scene3D.obstacles.forEach(obstacle => Scene3D.scene.remove(obstacle));
Scene3D.obstacles = [];
AppState.slam.obstacles = [];
// Create 15 obstacles in center region
for (let i = 0; i < 15; i++) {
createObstacle(i);
}
updateObstacleCount();
startObstacleAnimation();
}
function createObstacle(id) {
const types = ['sphere', 'cube', 'cylinder', 'cone'];
const colors = [0xff0000, 0xff8800, 0xffff00, 0xff00ff];
const type = types[Math.floor(Math.random() * types.length)];
const color = colors[Math.floor(Math.random() * colors.length)];
const trainingWeight = 1 + Math.random() * 2;
let geometry;
switch(type) {
case 'sphere': geometry = new THREE.SphereGeometry(2 + Math.random() * 3, 8, 8); break;
case 'cube': geometry = new THREE.BoxGeometry(3 + Math.random() * 4, 3 + Math.random() * 4, 3 + Math.random() * 4); break;
case 'cylinder': geometry = new THREE.CylinderGeometry(1.5, 1.5, 4 + Math.random() * 4, 8); break;
case 'cone': geometry = new THREE.ConeGeometry(2, 4 + Math.random() * 4, 8); break;
}
const material = new THREE.MeshPhongMaterial({
color: color,
emissive: color,
emissiveIntensity: 0.3,
transparent: true,
opacity: 0.8
});
const obstacle = new THREE.Mesh(geometry, material);
obstacle.castShadow = true;
// Center region positioning
const x = (Math.random() - 0.5) * 30;
const y = 5 + Math.random() * 20;
const z = (Math.random() - 0.5) * 30;
obstacle.position.set(x, y, z);
// Store training data
obstacle.userData = {
id: id,
type: type,
trainingWeight: trainingWeight,
detected: false,
avoidanceCount: 0,
floatSpeed: 0.2 + Math.random() * 0.8,
floatHeight: y,
floatOffset: Math.random() * Math.PI * 2
};
Scene3D.scene.add(obstacle);
Scene3D.obstacles.push(obstacle);
AppState.slam.obstacles.push({
id: id,
position: { x, y, z },
type: type,
trainingWeight: trainingWeight
});
return obstacle;
}
function startObstacleAnimation() {
if (obstacleInterval) clearInterval(obstacleInterval);
obstacleInterval = setInterval(() => {
if (!AppState.slam.dynamicMovement) return;
const time = Date.now() * 0.001;
Scene3D.obstacles.forEach(obstacle => {
if (obstacle.userData) {
obstacle.position.y = obstacle.userData.floatHeight +
Math.sin(time * obstacle.userData.floatSpeed +
obstacle.userData.floatOffset) * 3;
obstacle.rotation.y += 0.01;
obstacle.rotation.x += 0.005;
}
});
}, 50);
}
// ============================================
// GRAPH SYSTEM
// ============================================
function initGraphCanvas() {
const canvas = document.getElementById('graphCanvas');
graphCtx = canvas.getContext('2d');
graphWidth = canvas.width = canvas.clientWidth;
graphHeight = canvas.height = canvas.clientHeight;
// Initialize graph buffers
AppState.graphs.acceleration = [];
AppState.graphs.altitude = [];
AppState.graphs.battery = [];
AppState.graphs.velocity = [];
drawEmptyGraph();
}
function drawEmptyGraph() {
if (!graphCtx) return;
const ctx = graphCtx;
const width = graphWidth;
const height = graphHeight;
// Clear
ctx.fillStyle = '#001100';
ctx.fillRect(0, 0, width, height);
// Grid
ctx.strokeStyle = '#003300';
ctx.lineWidth = 1;
// Vertical lines
for (let x = 0; x < width; x += 40) {
ctx.beginPath();
ctx.moveTo(x, 0);
ctx.lineTo(x, height);
ctx.stroke();
}
// Horizontal lines
for (let y = 0; y < height; y += 30) {
ctx.beginPath();
ctx.moveTo(0, y);
ctx.lineTo(width, y);
ctx.stroke();
}
// Labels
ctx.fillStyle = '#00ff00';
ctx.font = '10px Courier New';
ctx.fillText('Time →', width - 50, height - 5);
ctx.fillText('↑ Signal Value', 5, 15);
}
function updateGraph() {
if (!graphCtx || AppState.graphs.isPaused) return;
const ctx = graphCtx;
const width = graphWidth;
const height = graphHeight;
// Clear
ctx.fillStyle = '#001100';
ctx.fillRect(0, 0, width, height);
// Grid
ctx.strokeStyle = '#003300';
ctx.lineWidth = 1;
// Vertical lines
for (let x = 0; x < width; x += 40) {
ctx.beginPath();
ctx.moveTo(x, 0);
ctx.lineTo(x, height);
ctx.stroke();
}
// Horizontal lines
for (let y = 0; y < height; y += 30) {
ctx.beginPath();
ctx.moveTo(0, y);
ctx.lineTo(width, y);
ctx.stroke();
}
// Draw signals if we have data
if (AppState.graphs.acceleration.length > 1) {
drawSignal(ctx, AppState.graphs.acceleration, 0xff8c00, -10, 10);
drawSignal(ctx, AppState.graphs.altitude, 0x00ff00, 0, 30);
drawSignal(ctx, AppState.graphs.battery, 0x0088ff, 0, 100);
drawSignal(ctx, AppState.graphs.velocity, 0x00ffff, 0, 20);
}
// Training progress
drawTrainingInfo(ctx);
}
function drawSignal(ctx, data, color, minVal, maxVal) {
if (data.length < 2) return;
const width = graphWidth;
const height = graphHeight;
const range = maxVal - minVal;
// Convert color
const r = (color >> 16) & 255;
const g = (color >> 8) & 255;
const b = color & 255;
// Draw line
ctx.strokeStyle = `rgba(${r}, ${g}, ${b}, 0.8)`;
ctx.lineWidth = 2;
ctx.beginPath();
const xStep = width / (data.length - 1);
for (let i = 0; i < data.length; i++) {
const x = i * xStep;
const normalized = (data[i] - minVal) / range;
const clamped = Math.max(0, Math.min(1, normalized));
const y = height - clamped * height * 0.8 - 10;
if (i === 0) {
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
}
}
ctx.stroke();
}
function drawTrainingInfo(ctx) {
const width = graphWidth;
const height = graphHeight;
const progress = AppState.dataset.statistics.trainingProgress;
// Progress bar
ctx.fillStyle = '#003300';
ctx.fillRect(0, height - 5, width, 5);
ctx.fillStyle = '#0f0';
ctx.fillRect(0, height - 5, width * progress, 5);
// Info text
ctx.fillStyle = '#0ff';
ctx.font = '10px Courier New';
ctx.fillText(
`Training: ${Math.round(progress * 100)}% | ` +
`Epoch: ${AppState.slam.currentEpoch} | ` +
`Avoidances: ${AppState.dataset.statistics.avoidanceManeuvers}`,
10, height - 10
);
}
function addGraphData(accel, alt, bat, vel) {
if (AppState.graphs.isPaused) return;
AppState.graphs.acceleration.push(accel);
AppState.graphs.altitude.push(alt);
AppState.graphs.battery.push(bat);
AppState.graphs.velocity.push(vel);
// Limit buffer size
if (AppState.graphs.acceleration.length > AppState.graphs.maxPoints) {
AppState.graphs.acceleration.shift();
AppState.graphs.altitude.shift();
AppState.graphs.battery.shift();
AppState.graphs.velocity.shift();
}
}
// ============================================
// TRAINING SYSTEM
// ============================================
function initTrainingSystem() {
logMessage("Training system initialized", "training");
document.getElementById('statusSLAM').className = "status-led active";
document.getElementById('statusWASM').className = "status-led active";
}
function startTraining() {
if (AppState.isTraining) return;
AppState.isTraining = true;
AppState.trainingStartTime = Date.now();
AppState.currentTime = 0;
// Reset dataset
AppState.dataset = {
telemetry: [],
slamData: [],
trainingEpochs: [],
statistics: {
totalPoints: 0,
obstaclesDetected: 0,
avoidanceManeuvers: 0,
trainingProgress: 0
}
};
// Update UI
document.getElementById('startBtn').disabled = true;
document.getElementById('stopBtn').disabled = false;
document.getElementById('statusGen').className = "status-led active";
// Clear graphs
AppState.graphs.acceleration = [];
AppState.graphs.altitude = [];
AppState.graphs.battery = [];
AppState.graphs.velocity = [];
// Start training interval
trainingInterval = setInterval(generateTrainingData, 1000 / AppState.params.sampleRate);
logMessage("Training started", "success");
logMessage(`Sample rate: ${AppState.params.sampleRate}Hz`, "info");
logMessage("Generating ML training dataset...", "dataset");
}
function stopTraining() {
if (!AppState.isTraining) return;
AppState.isTraining = false;
clearInterval(trainingInterval);
// Update UI
document.getElementById('startBtn').disabled = false;
document.getElementById('stopBtn').disabled = true;
document.getElementById('statusGen').className = "status-led inactive";
const duration = (Date.now() - AppState.trainingStartTime) / 1000;
const points = AppState.dataset.statistics.totalPoints;
const avoidances = AppState.dataset.statistics.avoidanceManeuvers;
logMessage(`Training stopped after ${duration.toFixed(1)}s`, "warning");
logMessage(`Dataset: ${points.toLocaleString()} data points`, "dataset");
logMessage(`Avoidance maneuvers: ${avoidances}`, "training");
logMessage(`Training progress: ${Math.round(AppState.dataset.statistics.trainingProgress * 100)}%`, "training");
if (points > 0) {
logMessage("Ready to export training dataset", "success");
}
}
function generateTrainingData() {
const params = AppState.params;
const timestamp = AppState.currentTime;
// Generate telemetry signals
const baseFreq = params.frequency;
const noiseLevel = params.noise;
// Acceleration (spiky pattern)
let accelX = Math.sin(timestamp * baseFreq * 2) * 3;
accelX += Math.sin(timestamp * baseFreq * 5) * 1.5;
accelX += (Math.random() - 0.5) * noiseLevel * 2;
if (Math.random() < 0.02 * params.complexity) {
accelX += (Math.random() * 4 - 2);
}
let accelY = Math.sin(timestamp * baseFreq * 1.8) * 2.5;
accelY += Math.cos(timestamp * baseFreq * 3) * 1.2;
accelY += (Math.random() - 0.5) * noiseLevel * 1.8;
let accelZ = Math.sin(timestamp * baseFreq * 2.2) * 2.8;
accelZ += Math.sin(timestamp * baseFreq * 4.5) * 1.3;
accelZ += (Math.random() - 0.5) * noiseLevel * 1.5;
// Gyroscope
let gyroX = Math.sin(timestamp * baseFreq * 3) * 2;
gyroX += (Math.random() - 0.5) * noiseLevel * 3;
let gyroY = Math.cos(timestamp * baseFreq * 2.7) * 2.2;
gyroY += (Math.random() - 0.5) * noiseLevel * 2.5;
let gyroZ = Math.sin(timestamp * baseFreq * 3.3) * 1.8;
gyroZ += (Math.random() - 0.5) * noiseLevel * 2.2;
// Altitude
let altitude = 10 + Math.sin(timestamp * baseFreq * 0.5) * 5;
altitude += Math.sin(timestamp * baseFreq * 0.2) * 8;
altitude += (Math.random() - 0.5) * noiseLevel * 0.5;
// Velocity
let velocity = Math.abs(Math.sin(timestamp * baseFreq * 0.8)) * 15;
velocity += (Math.random() - 0.5) * noiseLevel;
// Battery
let battery = 100 - (timestamp * 0.02);
battery += Math.sin(timestamp * baseFreq * 0.3) * 2;
battery += (Math.random() - 0.5) * noiseLevel * 0.3;
battery = Math.max(0, Math.min(100, battery));
// Temperature
let temperature = 25 + Math.sin(timestamp * baseFreq * 0.4) * 10;
temperature += (Math.random() - 0.5) * noiseLevel * 2;
// GPS
let gpsLat = 40.7128 + Math.sin(timestamp * 0.1) * 0.001;
let gpsLon = -74.0060 + Math.cos(timestamp * 0.1) * 0.001;
// Signal strength
let signalStrength = 80 + Math.sin(timestamp * baseFreq * 0.6) * 15;
signalStrength += (Math.random() - 0.5) * noiseLevel * 5;
signalStrength = Math.max(0, Math.min(100, signalStrength));
// Store telemetry data
const telemetryPoint = {
timestamp: timestamp,
acceleration: { x: accelX, y: accelY, z: accelZ },
gyroscope: { x: gyroX, y: gyroY, z: gyroZ },
altitude: altitude,
velocity: velocity,
battery: battery,
temperature: temperature,
gps: { lat: gpsLat, lon: gpsLon },
signalStrength: signalStrength
};
AppState.dataset.telemetry.push(telemetryPoint);
AppState.dataset.statistics.totalPoints++;
// Update graph data
addGraphData(accelX, altitude, battery, velocity);
// Update 3D visualization
updateDronePosition(altitude, accelX, accelY, accelZ);
// SLAM obstacle detection and avoidance
if (AppState.slam.avoidanceTraining) {
processSLAMTraining(timestamp);
}
// Update displays
updateTelemetryDisplay(timestamp, altitude, velocity, battery, accelX);
updateStatistics();
updateTrainingProgress();
// Update graph
updateGraph();
// Increment time
AppState.currentTime += 1 / AppState.params.sampleRate;
}
function processSLAMTraining(timestamp) {
if (!Scene3D.drone) return;
const dronePos = Scene3D.drone.position;
let nearestDistance = Infinity;
let nearestObstacle = null;
// Check all obstacles
Scene3D.obstacles.forEach(obstacle => {
const distance = dronePos.distanceTo(obstacle.position);
if (distance < nearestDistance) {
nearestDistance = distance;
nearestObstacle = obstacle;
}
// Detect obstacle if within range
if (distance < 8 && !obstacle.userData.detected) {
obstacle.userData.detected = true;
AppState.dataset.statistics.obstaclesDetected++;
// Record detection
const detectionData = {
type: 'detection',
timestamp: timestamp,
obstacleId: obstacle.userData.id,
distance: distance,
position: {
x: obstacle.position.x,
y: obstacle.position.y,
z: obstacle.position.z
},
trainingWeight: obstacle.userData.trainingWeight
};
AppState.dataset.slamData.push(detectionData);
logMessage(`Obstacle #${obstacle.userData.id} detected at ${distance.toFixed(1)}m`, "training");
}
// Avoidance maneuver if too close
if (distance < 5) {
obstacle.userData.avoidanceCount++;
// Perform avoidance
const avoidDirection = new THREE.Vector3()
.subVectors(dronePos, obstacle.position)
.normalize();
const avoidanceForce = 0.2 * (8 - distance);
Scene3D.drone.position.add(avoidDirection.multiplyScalar(avoidanceForce));
Scene3D.drone.position.y += avoidanceForce * 0.15;
// Visual feedback
flashDrone();
// Record avoidance
const avoidanceData = {
type: 'avoidance',
timestamp: timestamp,
obstacleId: obstacle.userData.id,
distance: distance,
maneuver: 'evasive',
success: true,
avoidanceCount: obstacle.userData.avoidanceCount
};
AppState.dataset.slamData.push(avoidanceData);
AppState.dataset.statistics.avoidanceManeuvers++;
document.getElementById('statAvoidances').textContent =
AppState.dataset.statistics.avoidanceManeuvers;
if (obstacle.userData.avoidanceCount === 1) {
logMessage(`Avoidance maneuver for obstacle #${obstacle.userData.id}`, "warning");
}
}
});
// Update training progress
const totalObstacles = Scene3D.obstacles.length;
const detectedObstacles = Scene3D.obstacles.filter(o => o.userData.detected).length;
const detectionProgress = detectedObstacles / totalObstacles;
const avoidanceProgress = Math.min(1, AppState.dataset.statistics.avoidanceManeuvers / (totalObstacles * 2));
AppState.dataset.statistics.trainingProgress = (detectionProgress * 0.6 + avoidanceProgress * 0.4);
// Check for epoch completion
if (detectedObstacles >= totalObstacles * 0.8 &&
AppState.dataset.statistics.avoidanceManeuvers >= totalObstacles) {
completeTrainingEpoch();
}
}
function completeTrainingEpoch() {
AppState.slam.currentEpoch++;
AppState.dataset.trainingEpochs.push({
epoch: AppState.slam.currentEpoch,
timestamp: AppState.currentTime,
obstaclesDetected: AppState.dataset.statistics.obstaclesDetected,
avoidanceManeuvers: AppState.dataset.statistics.avoidanceManeuvers,
trainingProgress: AppState.dataset.statistics.trainingProgress
});
logMessage(`Training Epoch ${AppState.slam.currentEpoch - 1} completed!`, "success");
logMessage(`${AppState.dataset.statistics.obstaclesDetected} obstacles detected`, "training");
logMessage(`${AppState.dataset.statistics.avoidanceManeuvers} avoidance maneuvers`, "training");
// Reset obstacle detection for new epoch
Scene3D.obstacles.forEach(obstacle => {
obstacle.userData.detected = false;
});
AppState.dataset.statistics.obstaclesDetected = 0;
}
function updateDronePosition(altitude, accelX, accelY, accelZ) {
if (!Scene3D.drone) return;
Scene3D.drone.position.y = altitude;
Scene3D.drone.position.x += accelX * 0.01;
Scene3D.drone.position.z += accelZ * 0.01;
Scene3D.drone.rotation.x += accelY * 0.01;
Scene3D.drone.rotation.z += accelX * 0.005;
// Animate propellers
if (Scene3D.drone.propellers) {
Scene3D.drone.propellers.forEach(propeller => {
propeller.rotation.y += 0.5;
});
}
}
function flashDrone() {
if (!Scene3D.drone) return;
const originalColor = 0x00ff00;
Scene3D.drone.children.forEach(child => {
if (child.material && child.material.color) {
child.material.color.setHex(0xff0000);
child.material.emissive.setHex(0xff0000);
}
});
setTimeout(() => {
if (Scene3D.drone) {
Scene3D.drone.children.forEach(child => {
if (child.material && child.material.color) {
child.material.color.setHex(originalColor);
child.material.emissive.setHex(0x004400);
}
});
}
}, 200);
}
// ============================================
// UI UPDATES
// ============================================
function updateTelemetryDisplay(time, alt, vel, bat, accelX) {
document.getElementById('telemetryTime').textContent = formatTime(time);
document.getElementById('telemetryAlt').textContent = alt.toFixed(1) + 'm';
document.getElementById('telemetryVel').textContent = vel.toFixed(1) + 'm/s';
document.getElementById('telemetryBat').textContent = bat.toFixed(0) + '%';
}
function updateStatistics() {
document.getElementById('statPoints').textContent =
AppState.dataset.statistics.totalPoints.toLocaleString();
document.getElementById('statObstacles').textContent =
Scene3D.obstacles.length;
// Update training progress bar
const progress = AppState.dataset.statistics.trainingProgress;
document.getElementById('trainingProgress').style.width = `${progress * 100}%`;
}
function updateTrainingProgress() {
// Update training progress in UI
const progress = AppState.dataset.statistics.trainingProgress;
// Additional UI updates can be added here
}
function updateObstacleCount() {
document.getElementById('statObstacles').textContent = Scene3D.obstacles.length;
}
function formatTime(seconds) {
const hrs = Math.floor(seconds / 3600);
const mins = Math.floor((seconds % 3600) / 60);
const secs = Math.floor(seconds % 60);
return `${hrs.toString().padStart(2, '0')}:${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}
function logMessage(message, type = "info") {
const terminal = document.getElementById('terminal');
const line = document.createElement('div');
line.className = 'terminal-line';
const time = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
line.innerHTML = `<span class="terminal-time">[${time}]</span>
<span class="terminal-content ${type}">${message}</span>`;
terminal.appendChild(line);
terminal.scrollTop = terminal.scrollHeight;
}
// ============================================
// EXPORT SYSTEM - COMPLETELY FIXED FOR HUGGING FACE
// ============================================
function showExportModal() {
if (AppState.dataset.statistics.totalPoints === 0) {
logMessage("No training data to export", "error");
return;
}
document.getElementById('exportModal').classList.add('active');
}
function hideExportModal() {
document.getElementById('exportModal').classList.remove('active');
document.getElementById('exportProgressFill').style.width = "0%";
document.getElementById('exportStatus').textContent = "Ready to export...";
}
async function exportDataset() {
const options = {
telemetry: document.getElementById('exportTelemetry').checked,
slam: document.getElementById('exportSLAM').checked,
graphs: document.getElementById('exportGraphs').checked,
metadata: document.getElementById('exportMetadata').checked,
trainingStats: document.getElementById('exportTrainingStats').checked
};
if (!Object.values(options).some(v => v)) {
logMessage("No export options selected", "error");
return;
}
const zip = new JSZip();
const progressBar = document.getElementById('exportProgressFill');
const statusText = document.getElementById('exportStatus');
let progress = 0;
const totalSteps = Object.values(options).filter(v => v).length;
let currentStep = 0;
function updateProgress(message) {
currentStep++;
progress = (currentStep / totalSteps) * 100;
progressBar.style.width = `${progress}%`;
statusText.textContent = message;
}
try {
// 1. Export telemetry data with consistent schema
if (options.telemetry) {
updateProgress("Exporting telemetry data...");
// Create JSON Lines file - each line is a separate JSON object with consistent schema
let jsonlContent = "";
let csvContent = "timestamp,acceleration_x,acceleration_y,acceleration_z,gyroscope_x,gyroscope_y,gyroscope_z,altitude,velocity,battery,temperature,gps_lat,gps_lon,signal_strength\n";
AppState.dataset.telemetry.forEach((point, index) => {
// JSONL format
const telemetryRecord = {
id: index,
timestamp: point.timestamp || 0.0,
acceleration_x: point.acceleration?.x || 0.0,
acceleration_y: point.acceleration?.y || 0.0,
acceleration_z: point.acceleration?.z || 0.0,
gyroscope_x: point.gyroscope?.x || 0.0,
gyroscope_y: point.gyroscope?.y || 0.0,
gyroscope_z: point.gyroscope?.z || 0.0,
altitude: point.altitude || 0.0,
velocity: point.velocity || 0.0,
battery: point.battery || 0.0,
temperature: point.temperature || 0.0,
gps_lat: point.gps?.lat || 0.0,
gps_lon: point.gps?.lon || 0.0,
signal_strength: point.signalStrength || 0.0
};
jsonlContent += JSON.stringify(telemetryRecord) + "\n";
// CSV format
csvContent += `${point.timestamp || 0},${point.acceleration?.x || 0},${point.acceleration?.y || 0},${point.acceleration?.z || 0},${point.gyroscope?.x || 0},${point.gyroscope?.y || 0},${point.gyroscope?.z || 0},${point.altitude || 0},${point.velocity || 0},${point.battery || 0},${point.temperature || 0},${point.gps?.lat || 0},${point.gps?.lon || 0},${point.signalStrength || 0}\n`;
});
zip.file("telemetry/telemetry.jsonl", jsonlContent);
zip.file("telemetry/telemetry.csv", csvContent);
zip.file("telemetry/telemetry_schema.json", JSON.stringify({
timestamp: "float64",
acceleration_x: "float64",
acceleration_y: "float64",
acceleration_z: "float64",
gyroscope_x: "float64",
gyroscope_y: "float64",
gyroscope_z: "float64",
altitude: "float64",
velocity: "float64",
battery: "float64",
temperature: "float64",
gps_lat: "float64",
gps_lon: "float64",
signal_strength: "float64"
}, null, 2));
await new Promise(r => setTimeout(r, 300));
}
// 2. Export SLAM data with separate, consistent schemas
if (options.slam) {
updateProgress("Exporting SLAM training data...");
// Create SLAM directory
const slamDir = zip.folder("slam");
// Export obstacles - ALWAYS create this file with consistent schema
const obstaclesArray = AppState.slam.obstacles.map(obs => ({
obstacle_id: obs.id || 0,
position_x: obs.position?.x || 0.0,
position_y: obs.position?.y || 0.0,
position_z: obs.position?.z || 0.0,
type: obs.type || 'unknown',
training_weight: obs.trainingWeight || 1.0,
dataset_id: "wave_bender_slam_obstacles"
}));
slamDir.file("obstacles.json", JSON.stringify(obstaclesArray, null, 2));
// Export detections - create empty array if no detections
const detections = AppState.dataset.slamData.filter(d => d.type === 'detection');
const detectionsArray = detections.map(det => ({
detection_id: det.obstacleId || 0,
timestamp: det.timestamp || 0.0,
obstacle_id: det.obstacleId || 0,
distance: det.distance || 0.0,
position_x: det.position?.x || 0.0,
position_y: det.position?.y || 0.0,
position_z: det.position?.z || 0.0,
training_weight: det.trainingWeight || 1.0,
dataset_id: "wave_bender_slam_detections"
}));
slamDir.file("detections.json", JSON.stringify(detectionsArray, null, 2));
// Export avoidances - create empty array if no avoidances
const avoidances = AppState.dataset.slamData.filter(d => d.type === 'avoidance');
const avoidancesArray = avoidances.map(av => ({
avoidance_id: av.obstacleId || 0,
timestamp: av.timestamp || 0.0,
obstacle_id: av.obstacleId || 0,
distance: av.distance || 0.0,
maneuver: av.maneuver || 'evasive',
success: av.success !== undefined ? av.success : true,
avoidance_count: av.avoidanceCount || 0,
dataset_id: "wave_bender_slam_avoidances"
}));
slamDir.file("avoidances.json", JSON.stringify(avoidancesArray, null, 2));
// Export training parameters
const trainingParams = {
complexity: AppState.params.complexity || 0,
noise: AppState.params.noise || 0.0,
frequency: AppState.params.frequency || 0.0,
sample_rate: AppState.params.sampleRate || 0,
center_region_training: AppState.slam.centerRegion || false,
dynamic_obstacles: AppState.slam.dynamicMovement || false,
avoidance_training: AppState.slam.avoidanceTraining || false,
dataset_id: "wave_bender_training_params"
};
slamDir.file("training_params.json", JSON.stringify(trainingParams, null, 2));
await new Promise(r => setTimeout(r, 300));
}
// 3. Export training statistics - SEPARATE from epochs to prevent schema conflicts
if (options.trainingStats) {
updateProgress("Exporting training statistics...");
// Create stats directory
const statsDir = zip.folder("statistics");
// Export epochs as separate dataset - ALWAYS create with consistent schema
let epochsArray = AppState.dataset.trainingEpochs.map(epoch => ({
epoch_number: epoch.epoch || 0,
timestamp: epoch.timestamp || 0.0,
obstacles_detected: epoch.obstaclesDetected || 0,
avoidance_maneuvers: epoch.avoidanceManeuvers || 0,
training_progress: epoch.trainingProgress || 0.0,
dataset_id: "wave_bender_training_epochs"
}));
// If no epochs, create one with zero values
if (epochsArray.length === 0) {
epochsArray = [{
epoch_number: 0,
timestamp: 0.0,
obstacles_detected: 0,
avoidance_maneuvers: 0,
training_progress: 0.0,
dataset_id: "wave_bender_training_epochs"
}];
}
statsDir.file("epochs.json", JSON.stringify(epochsArray, null, 2));
// Export statistics as SEPARATE dataset - different schema, different file
const statisticsData = [{
total_points: AppState.dataset.statistics.totalPoints || 0,
obstacles_detected: AppState.dataset.statistics.obstaclesDetected || 0,
avoidance_maneuvers: AppState.dataset.statistics.avoidanceManeuvers || 0,
training_progress: AppState.dataset.statistics.trainingProgress || 0.0,
total_obstacles: Scene3D.obstacles.length || 0,
total_detections: AppState.dataset.slamData.filter(d => d.type === 'detection').length || 0,
total_avoidances: AppState.dataset.slamData.filter(d => d.type === 'avoidance').length || 0,
current_epoch: AppState.slam.currentEpoch || 1,
generation_time: AppState.currentTime || 0.0,
dataset_id: "wave_bender_statistics_summary"
}];
statsDir.file("summary.json", JSON.stringify(statisticsData, null, 2));
await new Promise(r => setTimeout(r, 300));
}
// 4. Export graph data
if (options.graphs) {
updateProgress("Exporting graph data...");
const graphsDir = zip.folder("graphs");
const graphData = {
acceleration: AppState.graphs.acceleration,
altitude: AppState.graphs.altitude,
battery: AppState.graphs.battery,
velocity: AppState.graphs.velocity,
timestamps: AppState.graphs.acceleration.map((_, i) => i * 0.1),
dataset_id: "wave_bender_graph_data"
};
graphsDir.file("graph_data.json", JSON.stringify(graphData, null, 2));
await new Promise(r => setTimeout(r, 300));
}
// 5. Export metadata and Hugging Face dataset configuration
if (options.metadata) {
updateProgress("Creating Hugging Face dataset configuration...");
const metaDir = zip.folder("metadata");
// Create dataset card for Hugging Face
const datasetCard = {
language: ["en"],
license: "mit",
annotations_creators: ["machine-generated"],
task_categories: ["autonomous-driving", "robot-navigation"],
task_ids: ["obstacle-avoidance", "slam", "drone-telemetry"],
pretty_name: "WAVE BENDER Drone Telemetry & SLAM Dataset",
dataset_info: {
splits: {
telemetry: AppState.dataset.telemetry.length,
slam_obstacles: AppState.slam.obstacles.length,
slam_detections: AppState.dataset.slamData.filter(d => d.type === 'detection').length,
slam_avoidances: AppState.dataset.slamData.filter(d => d.type === 'avoidance').length,
training_epochs: AppState.dataset.trainingEpochs.length,
statistics: 1
}
},
size_categories: ["10K<n<100K"],
tags: [
"drone",
"telemetry",
"slam",
"obstacle-avoidance",
"synthetic-data",
"machine-learning",
"autonomous-systems"
],
dataset_id: "wave_bender_v5.0"
};
metaDir.file("dataset_card.json", JSON.stringify(datasetCard, null, 2));
// Create README with fixed loading instructions
const readme = `# WAVE BENDER IDE - Training Dataset
## Dataset Overview
Generated by WAVE BENDER IDE v5.0 - Web-based Drone Telemetry & SLAM Training Dataset Generator
**📊 Dataset Statistics:**
- **Total Telemetry Points**: ${AppState.dataset.statistics.totalPoints.toLocaleString()}
- **Training Duration**: ${AppState.currentTime.toFixed(1)} seconds
- **Sample Rate**: ${AppState.params.sampleRate} Hz
- **Training Epochs**: ${AppState.slam.currentEpoch - 1}
- **Obstacles Detected**: ${AppState.dataset.statistics.obstaclesDetected}
- **Avoidance Maneuvers**: ${AppState.dataset.statistics.avoidanceManeuvers}
- **Training Progress**: ${Math.round(AppState.dataset.statistics.trainingProgress * 100)}%
## 🚀 Loading the Dataset in Hugging Face
### CORRECT WAY - Load each dataset separately:
\`\`\`python
from datasets import Dataset, DatasetDict
import json
# Load telemetry data (separate dataset)
telemetry_dataset = Dataset.from_json("telemetry/telemetry.jsonl")
# Load SLAM data (separate datasets)
obstacles_dataset = Dataset.from_json("slam/obstacles.json")
detections_dataset = Dataset.from_json("slam/detections.json")
avoidances_dataset = Dataset.from_json("slam/avoidances.json")
# Load training data (separate datasets)
epochs_dataset = Dataset.from_json("statistics/epochs.json")
stats_dataset = Dataset.from_json("statistics/summary.json")
# Create DatasetDict with SEPARATE datasets (no schema conflicts!)
dataset_dict = DatasetDict({
'telemetry': telemetry_dataset,
'slam_obstacles': obstacles_dataset,
'slam_detections': detections_dataset,
'slam_avoidances': avoidances_dataset,
'training_epochs': epochs_dataset,
'statistics': stats_dataset
})
\`\`\`
## ✅ NO ARROWINVALID ERRORS - Why this works:
1. **Separate Files**: Each data type is in its own file with consistent schema
2. **Separate Datasets**: Each file is loaded as a separate Dataset
3. **No Schema Mixing**: Different schemas don't conflict because they're separate
4. **Always Valid**: Empty arrays still have consistent schemas
## 📁 Directory Structure
\`\`\`
wave_bender_dataset.zip/
├── telemetry/
│ ├── telemetry.jsonl # Telemetry data (JSON Lines)
│ ├── telemetry.csv # Telemetry data (CSV)
│ └── telemetry_schema.json
├── slam/
│ ├── obstacles.json # Obstacle definitions
│ ├── detections.json # Detection events
│ ├── avoidances.json # Avoidance maneuvers
│ └── training_params.json
├── statistics/
│ ├── epochs.json # Epoch progression
│ └── summary.json # Statistics summary
├── graphs/
│ └── graph_data.json
├── metadata/
│ ├── dataset_card.json
│ └── README.md
└── huggingface_loader.py
\`\`\`
## 🎯 Training Configuration
- **Complexity**: ${AppState.params.complexity}/10
- **Noise Level**: ${AppState.params.noise}/5
- **Frequency**: ${AppState.params.frequency} Hz
- **Center Region Training**: ${AppState.slam.centerRegion ? 'Yes' : 'No'}
- **Dynamic Obstacles**: ${AppState.slam.dynamicMovement ? 'Yes' : 'No'}
- **Avoidance Training**: ${AppState.slam.avoidanceTraining ? 'Yes' : 'No'}
## 🔧 Fixed ArrowInvalid Errors
This export structure completely eliminates ArrowInvalid errors by:
1. **Separating different schema types** into different directories
2. **Never mixing schemas** in the same file
3. **Always providing consistent schemas**, even for empty data
4. **Using unique dataset_id fields** to prevent confusion
## 📝 Citation
\`\`\`
@dataset{wave_bender_dataset_2024,
title = {WAVE BENDER IDE v5.0 - Drone Telemetry & SLAM Training Dataset},
author = {webXOS},
year = {2024},
url = {https://huggingface.co/datasets/webxos/wave_bender_dataset},
note = {Synthetic dataset for drone autonomy training}
}
\`\`\`
---
**Generated**: ${new Date().toISOString()}
**WAVE BENDER IDE v5.0** | **Hugging Face Compatible** | **ArrowInvalid Fixed**`;
metaDir.file("README.md", readme);
// Add a Python loader script
const loaderScript = `#!/usr/bin/env python3
"""
Hugging Face Dataset Loader for WAVE BENDER IDE v5.0
This script loads the dataset WITHOUT ArrowInvalid errors.
"""
import json
from datasets import Dataset, DatasetDict
import os
def load_wave_bender_dataset(dataset_path):
"""
Load WAVE BENDER dataset from extracted directory.
Args:
dataset_path (str): Path to extracted dataset directory
Returns:
DatasetDict: Dictionary of datasets
"""
datasets = {}
# Load telemetry data
telemetry_file = os.path.join(dataset_path, "telemetry", "telemetry.jsonl")
if os.path.exists(telemetry_file):
datasets['telemetry'] = Dataset.from_json(telemetry_file)
print(f"Loaded telemetry data: {len(datasets['telemetry'])} records")
# Load SLAM data
slam_path = os.path.join(dataset_path, "slam")
obstacles_file = os.path.join(slam_path, "obstacles.json")
if os.path.exists(obstacles_file):
datasets['slam_obstacles'] = Dataset.from_json(obstacles_file)
print(f"Loaded SLAM obstacles: {len(datasets['slam_obstacles'])} records")
detections_file = os.path.join(slam_path, "detections.json")
if os.path.exists(detections_file):
datasets['slam_detections'] = Dataset.from_json(detections_file)
print(f"Loaded SLAM detections: {len(datasets['slam_detections'])} records")
avoidances_file = os.path.join(slam_path, "avoidances.json")
if os.path.exists(avoidances_file):
datasets['slam_avoidances'] = Dataset.from_json(avoidances_file)
print(f"Loaded SLAM avoidances: {len(datasets['slam_avoidances'])} records")
# Load training data
stats_path = os.path.join(dataset_path, "statistics")
epochs_file = os.path.join(stats_path, "epochs.json")
if os.path.exists(epochs_file):
datasets['training_epochs'] = Dataset.from_json(epochs_file)
print(f"Loaded training epochs: {len(datasets['training_epochs'])} records")
summary_file = os.path.join(stats_path, "summary.json")
if os.path.exists(summary_file):
datasets['statistics'] = Dataset.from_json(summary_file)
print("Loaded statistics summary")
# Create DatasetDict
dataset_dict = DatasetDict(datasets)
print(f"\\n✅ Dataset loaded successfully with {len(datasets)} components")
print("✅ No ArrowInvalid errors - all schemas are separate and consistent")
return dataset_dict
if __name__ == "__main__":
# Example usage
dataset = load_wave_bender_dataset("./extracted_dataset")
print(f"\\nDataset structure: {list(dataset.keys())}")`;
zip.file("huggingface_loader.py", loaderScript);
await new Promise(r => setTimeout(r, 300));
}
// Generate ZIP file
updateProgress("Creating final package...");
const content = await zip.generateAsync({ type: "blob" });
// Download
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
saveAs(content, `wave_bender_hf_fixed_v5_${timestamp}.zip`);
updateProgress("Export complete!");
logMessage(`Dataset exported successfully (${formatFileSize(content.size)})`, "success");
logMessage("✅ ARROWINVALID ERRORS FIXED - Separate schemas prevent conflicts", "success");
logMessage("✅ Each data type in separate directory", "dataset");
logMessage("✅ Ready for Hugging Face Datasets", "success");
setTimeout(() => {
hideExportModal();
}, 2000);
} catch (error) {
console.error("Export error:", error);
statusText.textContent = "Export failed!";
logMessage(`Export failed: ${error.message}`, "error");
}
}
function formatFileSize(bytes) {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
}
// ============================================
// EVENT HANDLERS
// ============================================
function initEventListeners() {
// Sliders
document.getElementById('complexitySlider').addEventListener('input', function() {
AppState.params.complexity = parseInt(this.value);
document.getElementById('complexityValue').textContent = this.value;
});
document.getElementById('noiseSlider').addEventListener('input', function() {
AppState.params.noise = parseFloat(this.value);
document.getElementById('noiseValue').textContent = this.value;
});
document.getElementById('frequencySlider').addEventListener('input', function() {
AppState.params.frequency = parseFloat(this.value);
document.getElementById('frequencyValue').textContent = this.value;
});
document.getElementById('sampleRateSlider').addEventListener('input', function() {
AppState.params.sampleRate = parseInt(this.value);
document.getElementById('sampleRateValue').textContent = this.value;
});
// Toggles
document.getElementById('centerObstaclesToggle').addEventListener('change', function() {
AppState.slam.centerRegion = this.checked;
Scene3D.centerGrid.visible = this.checked;
});
document.getElementById('dynamicObstaclesToggle').addEventListener('change', function() {
AppState.slam.dynamicMovement = this.checked;
});
document.getElementById('avoidanceTrainingToggle').addEventListener('change', function() {
AppState.slam.avoidanceTraining = this.checked;
});
// Buttons
document.getElementById('startBtn').addEventListener('click', startTraining);
document.getElementById('stopBtn').addEventListener('click', stopTraining);
document.getElementById('exportBtn').addEventListener('click', showExportModal);
document.getElementById('resetBtn').addEventListener('click', resetSystem);
document.getElementById('fullscreenBtn').addEventListener('click', toggleFullscreen);
document.getElementById('cameraResetBtn').addEventListener('click', resetCamera);
document.getElementById('gridToggleBtn').addEventListener('click', toggleGrid);
document.getElementById('addObstacleBtn').addEventListener('click', addObstacle);
document.getElementById('resetObstaclesBtn').addEventListener('click', createTrainingObstacles);
document.getElementById('autoPilotBtn').addEventListener('click', toggleAutoPilot);
document.getElementById('trainingModeBtn').addEventListener('click', toggleTrainingMode);
document.getElementById('clearGraphBtn').addEventListener('click', clearGraph);
document.getElementById('pauseGraphBtn').addEventListener('click', toggleGraphPause);
// Export modal
document.getElementById('exportCancel').addEventListener('click', hideExportModal);
document.getElementById('exportConfirm').addEventListener('click', exportDataset);
// Window resize
window.addEventListener('resize', onWindowResize);
// Keyboard shortcuts
document.addEventListener('keydown', handleKeyboardShortcuts);
}
function addObstacle() {
const newId = Scene3D.obstacles.length;
createObstacle(newId);
updateObstacleCount();
logMessage(`Added obstacle #${newId + 1} to training environment`, "training");
}
function resetSystem() {
stopTraining();
if (AppState.isAutoPilot) toggleAutoPilot();
// Reset dataset
AppState.dataset = {
telemetry: [],
slamData: [],
trainingEpochs: [],
statistics: {
totalPoints: 0,
obstaclesDetected: 0,
avoidanceManeuvers: 0,
trainingProgress: 0
}
};
AppState.currentTime = 0;
AppState.slam.currentEpoch = 1;
// Reset drone position
if (Scene3D.drone) {
Scene3D.drone.position.set(0, 10, 0);
Scene3D.drone.rotation.set(0, 0, 0);
}
// Reset graphs
AppState.graphs.acceleration = [];
AppState.graphs.altitude = [];
AppState.graphs.battery = [];
AppState.graphs.velocity = [];
drawEmptyGraph();
// Update UI
updateTelemetryDisplay(0, 10, 0, 100, 0);
updateStatistics();
document.getElementById('statAvoidances').textContent = '0';
logMessage("System reset", "system");
logMessage("Ready for new training session", "training");
}
function toggleFullscreen() {
if (!document.fullscreenElement) {
document.documentElement.requestFullscreen();
} else {
document.exitFullscreen();
}
}
function resetCamera() {
if (Scene3D.camera) {
Scene3D.camera.position.set(40, 30, 50);
Scene3D.camera.lookAt(0, 0, 0);
}
}
function toggleGrid() {
if (Scene3D.centerGrid) {
Scene3D.centerGrid.visible = !Scene3D.centerGrid.visible;
}
}
function toggleAutoPilot() {
AppState.isAutoPilot = !AppState.isAutoPilot;
const btn = document.getElementById('autoPilotBtn');
if (AppState.isAutoPilot) {
btn.classList.add('active');
btn.textContent = 'MANUAL CONTROL';
logMessage("Auto-pilot mode activated", "success");
autoPilotInterval = setInterval(() => {
if (Scene3D.drone) {
const time = AppState.currentTime;
const radius = 12;
const speed = 0.08;
const targetX = Math.cos(time * speed) * radius;
const targetZ = Math.sin(time * speed) * radius;
Scene3D.drone.position.x += (targetX - Scene3D.drone.position.x) * 0.05;
Scene3D.drone.position.z += (targetZ - Scene3D.drone.position.z) * 0.05;
}
}, 50);
} else {
btn.classList.remove('active');
btn.textContent = 'AUTO PILOT';
logMessage("Auto-pilot mode deactivated", "warning");
if (autoPilotInterval) {
clearInterval(autoPilotInterval);
autoPilotInterval = null;
}
}
}
function toggleTrainingMode() {
const btn = document.getElementById('trainingModeBtn');
const isActive = btn.classList.contains('active');
if (isActive) {
btn.classList.remove('active');
btn.textContent = 'TRAINING MODE';
AppState.slam.avoidanceTraining = false;
logMessage("Training mode deactivated", "warning");
} else {
btn.classList.add('active');
btn.textContent = 'TRAINING ACTIVE';
AppState.slam.avoidanceTraining = true;
logMessage("Training mode activated", "success");
}
}
function clearGraph() {
AppState.graphs.acceleration = [];
AppState.graphs.altitude = [];
AppState.graphs.battery = [];
AppState.graphs.velocity = [];
drawEmptyGraph();
logMessage("Graphs cleared", "info");
}
function toggleGraphPause() {
AppState.graphs.isPaused = !AppState.graphs.isPaused;
const btn = document.getElementById('pauseGraphBtn');
btn.textContent = AppState.graphs.isPaused ? 'RESUME' : 'PAUSE';
logMessage(`Graph ${AppState.graphs.isPaused ? 'paused' : 'resumed'}`, "info");
}
function onWindowResize() {
if (Scene3D.renderer && Scene3D.camera) {
const canvas = document.getElementById('renderCanvas');
Scene3D.camera.aspect = canvas.clientWidth / canvas.clientHeight;
Scene3D.camera.updateProjectionMatrix();
Scene3D.renderer.setSize(canvas.clientWidth, canvas.clientHeight);
}
// Update graph canvas
const graphCanvas = document.getElementById('graphCanvas');
graphWidth = graphCanvas.width = graphCanvas.clientWidth;
graphHeight = graphCanvas.height = graphCanvas.clientHeight;
if (AppState.isTraining) {
updateGraph();
} else {
drawEmptyGraph();
}
}
function handleKeyboardShortcuts(e) {
// Space to start/stop training
if (e.code === 'Space') {
e.preventDefault();
if (AppState.isTraining) {
stopTraining();
} else {
startTraining();
}
}
// Escape to exit fullscreen
if (e.code === 'Escape' && document.fullscreenElement) {
document.exitFullscreen();
}
// R to reset system
if (e.code === 'KeyR' && e.ctrlKey) {
e.preventDefault();
resetSystem();
}
// E to export
if (e.code === 'KeyE' && e.ctrlKey) {
e.preventDefault();
showExportModal();
}
}
// ============================================
// ANIMATION LOOP
// ============================================
function animate(currentTime) {
animationFrameId = requestAnimationFrame(animate);
// Calculate FPS
AppState.frameCount++;
if (currentTime - AppState.lastFpsUpdate >= 1000) {
AppState.fps = Math.round((AppState.frameCount * 1000) / (currentTime - AppState.lastFpsUpdate));
AppState.frameCount = 0;
AppState.lastFpsUpdate = currentTime;
document.getElementById('statusFPS').textContent = `FPS: ${AppState.fps}`;
}
// Render scene
if (Scene3D.renderer && Scene3D.scene && Scene3D.camera) {
Scene3D.renderer.render(Scene3D.scene, Scene3D.camera);
}
}
// ============================================
// INITIALIZE APPLICATION
// ============================================
window.addEventListener('load', init);
</script>
</body>
</html>