summaryrefslogtreecommitdiff
path: root/web_interface.go
blob: 47cc04edfa9e9a07eb8dc33306baaa92099f9c22 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
package main

import (
	"encoding/json"
	"fmt"
	"html/template"
	"log"
	"net/http"
	"sync"
	"time"

	"github.com/gorilla/websocket"
)

var currentParams = TorusParams{
	MajorRadius:    2.0,
	MinorRadius:    0.5,
	MajorSegments:  50,
	MinorSegments:  30,
	RotationSpeedX: 0.3,
	RotationSpeedY: 0.5,
}

var currentAsteroidParams = AsteroidParams{
	SpawnRate:     1.0,
	MaxAsteroids:  500,
	MinSize:       0.05,
	MaxSize:       0.3,
	MinSpeed:      0.5,
	MaxSpeed:      3.0,
	RotationSpeed: 1.0,
}

var currentScene = "donut" // "donut" or "asteroids"

// Global CUDA status for WebSocket broadcasting
var globalCudaEnabled *bool

// Status WebSocket broadcaster
type StatusBroadcaster struct {
	clients    map[*websocket.Conn]bool
	register   chan *websocket.Conn
	unregister chan *websocket.Conn
	broadcast  chan StatusData
	mutex      sync.RWMutex
}

type StatusData struct {
	CudaEnabled    bool           `json:"cudaEnabled"`
	Params         TorusParams    `json:"params"`
	AsteroidParams AsteroidParams `json:"asteroidParams"`
	CurrentScene   string         `json:"currentScene"`
	FPS            float64        `json:"fps"`
	WindowWidth    int            `json:"windowWidth"`
	WindowHeight   int            `json:"windowHeight"`
}

var statusBroadcaster *StatusBroadcaster
var statusUpgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		origin := r.Header.Get("Origin")
		return origin == "" || origin == "http://localhost:8080" || origin == "http://127.0.0.1:8080"
	},
}

func newStatusBroadcaster() *StatusBroadcaster {
	return &StatusBroadcaster{
		clients:    make(map[*websocket.Conn]bool),
		register:   make(chan *websocket.Conn),
		unregister: make(chan *websocket.Conn),
		broadcast:  make(chan StatusData),
	}
}

func (sb *StatusBroadcaster) run() {
	ticker := time.NewTicker(100 * time.Millisecond) // Update 10 times per second
	defer ticker.Stop()

	for {
		select {
		case client := <-sb.register:
			sb.mutex.Lock()
			sb.clients[client] = true
			sb.mutex.Unlock()
			LogInfo("StatusWS", "New client connected to status stream")

			// Send initial status to new client
			sb.sendStatusToClient(client)

		case client := <-sb.unregister:
			sb.mutex.Lock()
			if _, ok := sb.clients[client]; ok {
				delete(sb.clients, client)
				client.Close()
			}
			sb.mutex.Unlock()
			LogInfo("StatusWS", "Client disconnected from status stream")

		case <-ticker.C:
			// Broadcast status updates to all clients
			sb.broadcastStatus()
		}
	}
}

func (sb *StatusBroadcaster) sendStatusToClient(client *websocket.Conn) {
	status := StatusData{
		CudaEnabled:    globalCudaEnabled != nil && *globalCudaEnabled,
		Params:         currentParams,
		AsteroidParams: currentAsteroidParams,
		CurrentScene:   currentScene,
		FPS:            GetCurrentFPS(),
		WindowWidth:    func() int { w, _ := GetWindowSize(); return w }(),
		WindowHeight:   func() int { _, h := GetWindowSize(); return h }(),
	}

	if err := client.WriteJSON(status); err != nil {
		sb.unregister <- client
	}
}

func (sb *StatusBroadcaster) broadcastStatus() {
	status := StatusData{
		CudaEnabled:    globalCudaEnabled != nil && *globalCudaEnabled,
		Params:         currentParams,
		AsteroidParams: currentAsteroidParams,
		CurrentScene:   currentScene,
		FPS:            GetCurrentFPS(),
		WindowWidth:    func() int { w, _ := GetWindowSize(); return w }(),
		WindowHeight:   func() int { _, h := GetWindowSize(); return h }(),
	}

	sb.mutex.RLock()
	defer sb.mutex.RUnlock()

	for client := range sb.clients {
		if err := client.WriteJSON(status); err != nil {
			go func(c *websocket.Conn) {
				sb.unregister <- c
			}(client)
		}
	}
}

const htmlTemplate = `
<!DOCTYPE html>
<html>
<head>
    <title>CUDA-Accelerated 3D Visualization Control Panel</title>
    <style>
        body { 
            font-family: Arial, sans-serif; 
            margin: 0; 
            padding: 20px;
            background: #f0f0f0; 
            display: flex;
            gap: 20px;
            height: 100vh;
            box-sizing: border-box;
        }
        .main-panel { 
            flex: 1; 
            max-width: 500px;
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow-y: auto;
        }
        .logs-panel {
            flex: 1;
            background: white;
            border-radius: 8px;
            padding: 0;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            display: flex;
            flex-direction: column;
            min-height: 0;
        }
        .logs-header {
            padding: 15px 20px;
            border-bottom: 1px solid #ddd;
            background: #f8f9fa;
            border-radius: 8px 8px 0 0;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .scene-switcher {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }
        .scene-button {
            flex: 1;
            padding: 12px;
            border: 2px solid #007bff;
            background: white;
            color: #007bff;
            border-radius: 6px;
            cursor: pointer;
            font-weight: bold;
            transition: all 0.3s;
        }
        .scene-button.active {
            background: #007bff;
            color: white;
        }
        .scene-button:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(0,123,255,0.3);
        }
        .scene-panel {
            display: none;
        }
        .scene-panel.active {
            display: block;
        }
        .status-indicator {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background: #dc3545;
            display: inline-block;
        }
        .status-indicator.connected {
            background: #28a745;
        }
        .log-console {
            flex: 1;
            padding: 10px;
            overflow-y: auto;
            background: #1e1e1e;
            color: #fff;
            font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
            font-size: 12px;
            line-height: 1.4;
            min-height: 0;
        }
        .log-entry {
            margin: 2px 0;
            padding: 2px 0;
            white-space: pre-wrap;
            word-wrap: break-word;
        }
        .log-timestamp {
            color: #888;
            margin-right: 8px;
        }
        .log-source {
            color: #ffeb3b;
            margin-right: 8px;
            font-weight: bold;
        }
        .log-level-info { color: #17a2b8; }
        .log-level-success { color: #28a745; }
        .log-level-warning { color: #ffc107; }
        .log-level-error { color: #dc3545; }
        .log-level-debug { color: #6c757d; }
        .log-level-cuda { color: #76b900; }
        
        h1 { color: #333; text-align: center; margin-bottom: 30px; }
        .param-group { margin-bottom: 20px; }
        label { display: block; margin-bottom: 5px; font-weight: bold; color: #555; }
        input[type="range"] { width: 100%; margin: 10px 0; }
        .value-display { 
            font-family: monospace; 
            background: #f8f8f8; 
            padding: 5px; 
            border-radius: 3px;
            color: #333;
            font-weight: normal;
        }
        button { 
            background: #007bff; 
            color: white; 
            border: none; 
            padding: 10px 20px; 
            border-radius: 5px; 
            cursor: pointer; 
            margin: 5px;
            font-size: 14px;
            transition: background 0.3s;
        }
        button:hover { 
            background: #0056b3; 
            transform: translateY(-1px);
        }
        .info { 
            background: #e9ecef; 
            padding: 15px; 
            border-radius: 5px; 
            margin: 20px 0; 
            border-left: 4px solid #007bff;
        }
    </style>
</head>
<body>
    <div class="main-panel">
        <h1>🎮 3D Visualization Control Panel</h1>
        
        <!-- Scene Switcher -->
        <div class="scene-switcher">
            <button class="scene-button active" id="donutBtn" onclick="switchScene('donut')">🍩 Torus Scene</button>
            <button class="scene-button" id="asteroidsBtn" onclick="switchScene('asteroids')">🌌 Asteroid Field</button>
        </div>

        <!-- Torus Scene Controls -->
        <div class="scene-panel active" id="donutPanel">
            <h3>🍩 Torus Parameters</h3>
            
            <div class="param-group">
                <label for="majorRadius">Major Radius (Torus Size): <span class="value-display" id="majorRadiusValue">{{.MajorRadius}}</span></label>
                <input type="range" id="majorRadius" min="0.5" max="5.0" step="0.1" value="{{.MajorRadius}}" oninput="updateTorusParam('majorRadius', this.value)">
            </div>

            <div class="param-group">
                <label for="minorRadius">Minor Radius (Tube Size): <span class="value-display" id="minorRadiusValue">{{.MinorRadius}}</span></label>
                <input type="range" id="minorRadius" min="0.1" max="2.0" step="0.05" value="{{.MinorRadius}}" oninput="updateTorusParam('minorRadius', this.value)">
            </div>

            <div class="param-group">
                <label for="majorSegments">Major Segments (Detail): <span class="value-display" id="majorSegmentsValue">{{.MajorSegments}}</span></label>
                <input type="range" id="majorSegments" min="10" max="100" step="5" value="{{.MajorSegments}}" oninput="updateTorusParam('majorSegments', this.value)">
            </div>

            <div class="param-group">
                <label for="minorSegments">Minor Segments (Smoothness): <span class="value-display" id="minorSegmentsValue">{{.MinorSegments}}</span></label>
                <input type="range" id="minorSegments" min="10" max="50" step="5" value="{{.MinorSegments}}" oninput="updateTorusParam('minorSegments', this.value)">
            </div>

            <div class="param-group">
                <label for="rotationSpeedX">X Rotation Speed: <span class="value-display" id="rotationSpeedXValue">{{.RotationSpeedX}}</span></label>
                <input type="range" id="rotationSpeedX" min="-2.0" max="2.0" step="0.1" value="{{.RotationSpeedX}}" oninput="updateTorusParam('rotationSpeedX', this.value)">
            </div>

            <div class="param-group">
                <label for="rotationSpeedY">Y Rotation Speed: <span class="value-display" id="rotationSpeedYValue">{{.RotationSpeedY}}</span></label>
                <input type="range" id="rotationSpeedY" min="-2.0" max="2.0" step="0.1" value="{{.RotationSpeedY}}" oninput="updateTorusParam('rotationSpeedY', this.value)">
            </div>

            <div style="text-align: center; margin: 20px 0;">
                <button onclick="resetTorusDefaults()">Reset to Defaults</button>
                <button onclick="randomizeTorus()">Randomize</button>
            </div>
        </div>

        <!-- Asteroid Field Controls -->
        <div class="scene-panel" id="asteroidsPanel">
            <h3>🌌 Asteroid Field Parameters</h3>
            
            <div class="param-group">
                <label for="spawnRate">Spawn Rate (asteroids/sec): <span class="value-display" id="spawnRateValue">{{.SpawnRate}}</span></label>
                <input type="range" id="spawnRate" min="0.1" max="5.0" step="0.1" value="{{.SpawnRate}}" oninput="updateAsteroidParam('spawnRate', this.value)">
            </div>

            <div class="param-group">
                <label for="maxAsteroids">Max Asteroids: <span class="value-display" id="maxAsteroidsValue">{{.MaxAsteroids}}</span></label>
                <input type="range" id="maxAsteroids" min="50" max="1000" step="50" value="{{.MaxAsteroids}}" oninput="updateAsteroidParam('maxAsteroids', this.value)">
            </div>

            <div class="param-group">
                <label for="minSize">Min Size: <span class="value-display" id="minSizeValue">{{.MinSize}}</span></label>
                <input type="range" id="minSize" min="0.01" max="0.5" step="0.01" value="{{.MinSize}}" oninput="updateAsteroidParam('minSize', this.value)">
            </div>

            <div class="param-group">
                <label for="maxSize">Max Size: <span class="value-display" id="maxSizeValue">{{.MaxSize}}</span></label>
                <input type="range" id="maxSize" min="0.1" max="1.0" step="0.05" value="{{.MaxSize}}" oninput="updateAsteroidParam('maxSize', this.value)">
            </div>

            <div class="param-group">
                <label for="minSpeed">Min Speed: <span class="value-display" id="minSpeedValue">{{.MinSpeed}}</span></label>
                <input type="range" id="minSpeed" min="0.1" max="5.0" step="0.1" value="{{.MinSpeed}}" oninput="updateAsteroidParam('minSpeed', this.value)">
            </div>

            <div class="param-group">
                <label for="maxSpeed">Max Speed: <span class="value-display" id="maxSpeedValue">{{.MaxSpeed}}</span></label>
                <input type="range" id="maxSpeed" min="1.0" max="10.0" step="0.5" value="{{.MaxSpeed}}" oninput="updateAsteroidParam('maxSpeed', this.value)">
            </div>

            <div class="param-group">
                <label for="rotationSpeed">Rotation Speed: <span class="value-display" id="rotationSpeedValue">{{.RotationSpeed}}</span></label>
                <input type="range" id="rotationSpeed" min="0.1" max="5.0" step="0.1" value="{{.RotationSpeed}}" oninput="updateAsteroidParam('rotationSpeed', this.value)">
            </div>

            <div style="text-align: center; margin: 20px 0;">
                <button onclick="resetAsteroidDefaults()">Reset to Defaults</button>
                <button onclick="clearAsteroids()">Clear All Asteroids</button>
            </div>
        </div>        <div class="info">
            <strong>Info:</strong> This control panel adjusts the 3D visualization in real-time. 
            Switch between the torus scene and asteroid field using the buttons above or press 1/2 in the 3D viewport.
            <br><br>
            <strong>Current Mode:</strong> <span id="renderMode">{{if .CudaEnabled}}CUDA Accelerated{{else}}CPU Fallback{{end}}</span>
            <br>
            <strong>Current Scene:</strong> <span id="currentSceneDisplay">{{.CurrentScene}}</span>
            <br>
            <strong>Performance:</strong> <span id="fpsDisplay">-- FPS</span>
            <br>
            <strong>Viewport:</strong> <span id="windowSize">800 x 600</span> (resizable)
        </div>
    </div>
    
    <div class="logs-panel">
        <div class="logs-header">
            <h3 style="margin: 0;">📋 System Logs</h3>
            <div class="status-indicator" id="wsStatus"></div>
            <span id="wsStatusText">Connecting...</span>
        </div>
        <div class="log-console" id="logConsole">
            <div class="log-entry log-level-info">
                <span class="log-timestamp">[Starting]</span>
                <span class="log-source">WebUI</span>
                <span>Control panel loaded, connecting to log stream...</span>
            </div>
        </div>
    </div>

    <script>
        let ws;
        let isConnected = false;

        function connectWebSocket() {
            const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
            const wsUrl = protocol + '//' + window.location.host + '/ws';
            
            ws = new WebSocket(wsUrl);
            
            ws.onopen = function() {
                isConnected = true;
                document.getElementById('wsStatus').classList.add('connected');
                document.getElementById('wsStatusText').textContent = 'Connected';
                addLogEntry('WebSocket', 'info', 'Connected to log stream');
            };
            
            ws.onmessage = function(event) {
                try {
                    const logData = JSON.parse(event.data);
                    addLogEntry(logData.source, logData.level, logData.message);
                } catch (e) {
                    addLogEntry('WebSocket', 'error', 'Failed to parse log message: ' + event.data);
                }
            };
            
            ws.onclose = function() {
                isConnected = false;
                document.getElementById('wsStatus').classList.remove('connected');
                document.getElementById('wsStatusText').textContent = 'Disconnected';
                addLogEntry('WebSocket', 'warning', 'Disconnected from log stream, attempting to reconnect...');
                setTimeout(connectWebSocket, 3000);
            };
            
            ws.onerror = function(error) {
                addLogEntry('WebSocket', 'error', 'Connection error: ' + error);
            };
        }

        function addLogEntry(source, level, message) {
            const logConsole = document.getElementById('logConsole');
            const timestamp = new Date().toLocaleTimeString();
            
            const logEntry = document.createElement('div');
            logEntry.className = 'log-entry log-level-' + level;
            logEntry.innerHTML = 
                '<span class="log-timestamp">[' + timestamp + ']</span>' +
                '<span class="log-source">' + source + '</span>' +
                '<span>' + message + '</span>';
            
            logConsole.appendChild(logEntry);
            logConsole.scrollTop = logConsole.scrollHeight;
            
            // Keep only last 100 log entries
            while (logConsole.children.length > 100) {
                logConsole.removeChild(logConsole.firstChild);
            }
        }

        function switchScene(scene) {
            // Update UI
            document.querySelectorAll('.scene-button').forEach(btn => btn.classList.remove('active'));
            document.querySelectorAll('.scene-panel').forEach(panel => panel.classList.remove('active'));
            
            if (scene === 'donut') {
                document.getElementById('donutBtn').classList.add('active');
                document.getElementById('donutPanel').classList.add('active');
            } else {
                document.getElementById('asteroidsBtn').classList.add('active');
                document.getElementById('asteroidsPanel').classList.add('active');
            }
            
            // Send scene change to server
            fetch('/api/scene', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({scene: scene})
            });
        }

        function updateTorusParam(param, value) {
            document.getElementById(param + 'Value').textContent = value;
            
            fetch('/api/params', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    [param]: parseFloat(value) || parseInt(value)
                })
            });
        }

        function updateAsteroidParam(param, value) {
            document.getElementById(param + 'Value').textContent = value;
            
            fetch('/api/asteroid-params', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    [param]: parseFloat(value) || parseInt(value)
                })
            });
        }

        function resetTorusDefaults() {
            const defaults = {
                majorRadius: 2.0,
                minorRadius: 0.5,
                majorSegments: 50,
                minorSegments: 30,
                rotationSpeedX: 0.3,
                rotationSpeedY: 0.5
            };
            
            for (const [param, value] of Object.entries(defaults)) {
                document.getElementById(param).value = value;
                document.getElementById(param + 'Value').textContent = value;
            }
            
            fetch('/api/params', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(defaults)
            });
        }

        function resetAsteroidDefaults() {
            const defaults = {
                spawnRate: 1.0,
                maxAsteroids: 500,
                minSize: 0.05,
                maxSize: 0.3,
                minSpeed: 0.5,
                maxSpeed: 3.0,
                rotationSpeed: 1.0
            };
            
            for (const [param, value] of Object.entries(defaults)) {
                document.getElementById(param).value = value;
                document.getElementById(param + 'Value').textContent = value;
            }
            
            fetch('/api/asteroid-params', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(defaults)
            });
        }

        function randomizeTorus() {
            const params = {
                majorRadius: (Math.random() * 4 + 1).toFixed(1),
                minorRadius: (Math.random() * 1.5 + 0.2).toFixed(2),
                majorSegments: Math.floor(Math.random() * 60 + 20),
                minorSegments: Math.floor(Math.random() * 40 + 10),
                rotationSpeedX: (Math.random() * 2 - 1).toFixed(1),
                rotationSpeedY: (Math.random() * 2 - 1).toFixed(1)
            };
            
            for (const [param, value] of Object.entries(params)) {
                document.getElementById(param).value = value;
                document.getElementById(param + 'Value').textContent = value;
            }
            
            fetch('/api/params', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(params)
            });
        }

        function clearAsteroids() {
            fetch('/api/clear-asteroids', {
                method: 'POST'
            });
        }        // Initialize WebSocket connections
        connectWebSocket();  // For logs
        connectStatusWebSocket();  // For status updates
        
        // WebSocket connection for real-time status updates
        let statusWs;
        let statusConnected = false;
        
        function connectStatusWebSocket() {
            const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
            const statusWsUrl = protocol + '//' + window.location.host + '/ws-status';
            
            statusWs = new WebSocket(statusWsUrl);
            
            statusWs.onopen = function() {
                statusConnected = true;
                addLogEntry('StatusWS', 'info', 'Connected to status stream');
            };
            
            statusWs.onmessage = function(event) {
                try {
                    const statusData = JSON.parse(event.data);
                    
                    // Update render mode
                    document.getElementById('renderMode').textContent = 
                        statusData.cudaEnabled ? 'CUDA Accelerated' : 'CPU Fallback';
                    
                    // Update FPS display
                    const fps = statusData.fps ? statusData.fps.toFixed(1) : '--';
                    document.getElementById('fpsDisplay').textContent = fps + ' FPS';
                    
                    // Update window size display
                    if (statusData.windowWidth && statusData.windowHeight) {
                        document.getElementById('windowSize').textContent = 
                            statusData.windowWidth + ' x ' + statusData.windowHeight;
                    }
                } catch (e) {
                    addLogEntry('StatusWS', 'error', 'Failed to parse status message: ' + event.data);
                }
            };
            
            statusWs.onclose = function() {
                statusConnected = false;
                addLogEntry('StatusWS', 'warning', 'Disconnected from status stream, attempting to reconnect...');
                setTimeout(connectStatusWebSocket, 3000);
            };
            
            statusWs.onerror = function(error) {
                addLogEntry('StatusWS', 'error', 'Status connection error: ' + error);
            };
        }
    </script>
</body>
</html>
`

// StartWebServer starts the web interface server
func StartWebServer(params *TorusParams, cudaEnabled *bool) {
	// Set global CUDA status for WebSocket broadcasting
	globalCudaEnabled = cudaEnabled

	// Initialize and start status broadcaster
	statusBroadcaster = newStatusBroadcaster()
	go statusBroadcaster.run()

	// Serve static files for the web interface
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		tmpl := template.Must(template.New("index").Parse(htmlTemplate))
		data := struct {
			TorusParams
			AsteroidParams
			CudaEnabled  bool
			CurrentScene string
		}{
			TorusParams:    currentParams,
			AsteroidParams: currentAsteroidParams,
			CudaEnabled:    cudaEnabled != nil && *cudaEnabled,
			CurrentScene:   currentScene,
		}
		tmpl.Execute(w, data)
	})
	// WebSocket endpoint for real-time logging
	http.HandleFunc("/ws", wsLogHandler)

	// WebSocket endpoint for real-time status updates
	http.HandleFunc("/ws-status", func(w http.ResponseWriter, r *http.Request) {
		conn, err := statusUpgrader.Upgrade(w, r, nil)
		if err != nil {
			log.Println("Status WebSocket upgrade error:", err)
			return
		}

		statusBroadcaster.register <- conn

		// Keep connection alive and handle disconnection
		defer func() {
			statusBroadcaster.unregister <- conn
			conn.Close()
		}()

		// Read messages from client (ping/pong)
		for {
			_, _, err := conn.ReadMessage()
			if err != nil {
				break
			}
		}
	})

	// API endpoint for scene switching
	http.HandleFunc("/api/scene", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodPost {
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
			return
		}

		r.Body = http.MaxBytesReader(w, r.Body, 1048576) // 1MB limit
		var sceneData map[string]string
		if err := json.NewDecoder(r.Body).Decode(&sceneData); err != nil {
			http.Error(w, "Invalid JSON", http.StatusBadRequest)
			return
		}

		if scene, ok := sceneData["scene"]; ok {
			currentScene = scene
			// Update the actual scene in main.go
			SetCurrentScene(scene)
			LogSuccess("Scene", fmt.Sprintf("Scene switched to: %s", scene))
		}

		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(map[string]string{"status": "scene changed"})
	})

	// API endpoint to update torus parameters
	http.HandleFunc("/api/params", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodPost {
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
			return
		}

		r.Body = http.MaxBytesReader(w, r.Body, 1048576) // 1MB limit
		var updates map[string]interface{}
		if err := json.NewDecoder(r.Body).Decode(&updates); err != nil {
			http.Error(w, "Invalid JSON", http.StatusBadRequest)
			return
		}

		// Log parameter changes
		for key, value := range updates {
			LogInfo("UI", fmt.Sprintf("Torus parameter changed: %s = %v", key, value))
		}

		// Update parameters
		for key, value := range updates {
			switch key {
			case "majorRadius":
				if v, ok := value.(float64); ok {
					oldValue := currentParams.MajorRadius
					currentParams.MajorRadius = float32(v)
					LogSuccess("Parameters", fmt.Sprintf("Major Radius: %.2f → %.2f", oldValue, float32(v)))
				}
			case "minorRadius":
				if v, ok := value.(float64); ok {
					oldValue := currentParams.MinorRadius
					currentParams.MinorRadius = float32(v)
					LogSuccess("Parameters", fmt.Sprintf("Minor Radius: %.3f → %.3f", oldValue, float32(v)))
				}
			case "majorSegments":
				if v, ok := value.(float64); ok {
					oldValue := currentParams.MajorSegments
					currentParams.MajorSegments = int(v)
					LogSuccess("Parameters", fmt.Sprintf("Major Segments: %d → %d", oldValue, int(v)))
				}
			case "minorSegments":
				if v, ok := value.(float64); ok {
					oldValue := currentParams.MinorSegments
					currentParams.MinorSegments = int(v)
					LogSuccess("Parameters", fmt.Sprintf("Minor Segments: %d → %d", oldValue, int(v)))
				}
			case "rotationSpeedX":
				if v, ok := value.(float64); ok {
					oldValue := currentParams.RotationSpeedX
					currentParams.RotationSpeedX = float32(v)
					LogSuccess("Parameters", fmt.Sprintf("X Rotation Speed: %.1f → %.1f", oldValue, float32(v)))
				}
			case "rotationSpeedY":
				if v, ok := value.(float64); ok {
					oldValue := currentParams.RotationSpeedY
					currentParams.RotationSpeedY = float32(v)
					LogSuccess("Parameters", fmt.Sprintf("Y Rotation Speed: %.1f → %.1f", oldValue, float32(v)))
				}
			}
		}

		// Copy back to the main params if provided
		if params != nil {
			*params = currentParams
		}

		LogInfo("System", "Torus parameters updated successfully")

		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(map[string]string{"status": "updated"})
	})

	// API endpoint to update asteroid parameters
	http.HandleFunc("/api/asteroid-params", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodPost {
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
			return
		}

		r.Body = http.MaxBytesReader(w, r.Body, 1048576) // 1MB limit
		var updates map[string]interface{}
		if err := json.NewDecoder(r.Body).Decode(&updates); err != nil {
			http.Error(w, "Invalid JSON", http.StatusBadRequest)
			return
		}

		// Log parameter changes
		for key, value := range updates {
			LogInfo("UI", fmt.Sprintf("Asteroid parameter changed: %s = %v", key, value))
		}

		// Update parameters
		for key, value := range updates {
			switch key {
			case "spawnRate":
				if v, ok := value.(float64); ok {
					oldValue := currentAsteroidParams.SpawnRate
					currentAsteroidParams.SpawnRate = float32(v)
					LogSuccess("Asteroids", fmt.Sprintf("Spawn Rate: %.1f → %.1f", oldValue, float32(v)))
				}
			case "maxAsteroids":
				if v, ok := value.(float64); ok {
					oldValue := currentAsteroidParams.MaxAsteroids
					currentAsteroidParams.MaxAsteroids = int(v)
					LogSuccess("Asteroids", fmt.Sprintf("Max Asteroids: %d → %d", oldValue, int(v)))
				}
			case "minSize":
				if v, ok := value.(float64); ok {
					oldValue := currentAsteroidParams.MinSize
					currentAsteroidParams.MinSize = float32(v)
					LogSuccess("Asteroids", fmt.Sprintf("Min Size: %.3f → %.3f", oldValue, float32(v)))
				}
			case "maxSize":
				if v, ok := value.(float64); ok {
					oldValue := currentAsteroidParams.MaxSize
					currentAsteroidParams.MaxSize = float32(v)
					LogSuccess("Asteroids", fmt.Sprintf("Max Size: %.3f → %.3f", oldValue, float32(v)))
				}
			case "minSpeed":
				if v, ok := value.(float64); ok {
					oldValue := currentAsteroidParams.MinSpeed
					currentAsteroidParams.MinSpeed = float32(v)
					LogSuccess("Asteroids", fmt.Sprintf("Min Speed: %.1f → %.1f", oldValue, float32(v)))
				}
			case "maxSpeed":
				if v, ok := value.(float64); ok {
					oldValue := currentAsteroidParams.MaxSpeed
					currentAsteroidParams.MaxSpeed = float32(v)
					LogSuccess("Asteroids", fmt.Sprintf("Max Speed: %.1f → %.1f", oldValue, float32(v)))
				}
			case "rotationSpeed":
				if v, ok := value.(float64); ok {
					oldValue := currentAsteroidParams.RotationSpeed
					currentAsteroidParams.RotationSpeed = float32(v)
					LogSuccess("Asteroids", fmt.Sprintf("Rotation Speed: %.1f → %.1f", oldValue, float32(v)))
				}
			}
		}

		// Update the actual asteroid config in main.go
		UpdateAsteroidConfig(currentAsteroidParams)

		LogInfo("System", "Asteroid parameters updated successfully")

		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(map[string]string{"status": "updated"})
	})

	// API endpoint to clear asteroids
	http.HandleFunc("/api/clear-asteroids", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodPost {
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
			return
		}

		// Call the actual clear function in main.go
		ClearAllAsteroids()
		LogInfo("Asteroids", "Clearing all asteroids from field")

		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(map[string]string{"status": "asteroids cleared"})
	})
	// API endpoint for status
	http.HandleFunc("/api/status", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(map[string]interface{}{
			"cudaEnabled":    cudaEnabled != nil && *cudaEnabled,
			"params":         currentParams,
			"asteroidParams": currentAsteroidParams,
			"currentScene":   currentScene,
			"fps":            GetCurrentFPS(),
			"windowWidth":    func() int { w, _ := GetWindowSize(); return w }(),
			"windowHeight":   func() int { _, h := GetWindowSize(); return h }(),
		})
	})

	LogInfo("WebServer", "Starting web interface on http://localhost:8080")
	LogInfo("WebServer", "Access the control panel and logs in your browser")
	log.Fatal(http.ListenAndServe(":8080", nil))
}

// GetCurrentParams returns the current torus parameters
func GetCurrentParams() TorusParams {
	return currentParams
}

// GetCurrentAsteroidParams returns the current asteroid parameters
func GetCurrentAsteroidParams() AsteroidParams {
	return currentAsteroidParams
}

// GetCurrentScene returns the current scene name
func GetCurrentScene() string {
	return currentScene
}