-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathviewer.html
More file actions
2476 lines (2172 loc) · 102 KB
/
Copy pathviewer.html
File metadata and controls
2476 lines (2172 loc) · 102 KB
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
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>High-Performance Waypoint Editor</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.10.3/sql-wasm.js"></script>
<script type="importmap">
{
"imports": {
"three": "https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js",
"three/addons/": "https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/"
}
}
</script>
<style>
html, body { height:100%; margin:0; background:#0b0e14; font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif; }
#app { position:fixed; inset:0; cursor: default; }
#app.draggable, #app.shape-move { cursor: grab; }
#app.delete-mode { cursor: crosshair; }
#ui {
position: fixed; top: 12px; left: 12px; z-index: 10;
display: flex; gap: 8px; align-items: center; flex-wrap: wrap;
background: rgba(20,24,33,0.7); border: 1px solid rgba(255,255,255,0.08);
border-radius: 10px; padding: 8px 10px; color:#eaeefb; backdrop-filter: blur(6px);
}
button, label, select {
background:#2a2f3a; color:#fff; border:1px solid #3a4150; border-radius:8px;
padding:8px 12px; cursor:pointer; font-size:14px;
}
select {
-webkit-appearance: none; -moz-appearance: none; appearance: none;
background-image: url("data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22292.4%22%20height%3D%22292.4%22%3E%3Cpath%20fill%3D%22%23FFFFFF%22%20d%3D%22M287%2069.4a17.6%2017.6%200%200%200-13-5.4H18.4c-5%200-9.3%201.8-12.9%205.4A17.6%2017.6%200%200%200%200%2082.2c0%205%201.8%209.3%205.4%2012.9l128%20127.9c3.6%203.6%207.8%205.4%2012.8%205.4s9.2-1.8%2012.8-5.4L287%2095c3.5-3.5%205.4-7.8%205.4-12.8%200-5-1.9-9.2-5.5-12.8z%22%2F%3E%3C%2Fsvg%3E");
background-repeat: no-repeat;
background-position: right 12px top 50%;
background-size: .65em auto;
padding-right: 30px;
}
button:hover, label:hover, select:hover { background:#343b49; }
button:disabled { background: #222; color: #555; border-color: #333; cursor: not-allowed; }
.hint-bar {
position: fixed; bottom: 10px; left: 50%; transform: translateX(-50%);
color:#9fb0d0; font-size: 13px; opacity: 0.9; user-select:none;
background: rgba(20,24,33,0.6); padding: 6px 10px; border-radius: 8px;
border: 1px solid rgba(255,255,255,0.08); text-align: center;
}
input[type="file"] { display:none; }
#loader {
position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%);
color: #fff; background: rgba(0,0,0,0.7); padding: 20px; border-radius: 10px;
z-index: 100; display: none;
}
.side-panel {
position: fixed; top: 70px; width: 280px;
background: rgba(20,24,33,0.85); border: 1px solid rgba(255,255,255,0.08);
border-radius: 10px; padding: 15px; color: #eaeefb;
backdrop-filter: blur(8px); transition: transform 0.3s ease-in-out, opacity 0.3s; z-index: 9;
transform: translateX(calc(100% + 24px));
opacity: 0;
pointer-events: none;
}
.side-panel.visible {
transform: translateX(0);
opacity: 1;
pointer-events: auto;
}
#info-panel { right: 12px; }
#interpolation-panel { right: 12px; }
#move-panel { right: 12px; }
#zone-panel { right: 12px; }
#display-panel {
left: 12px;
transform: translateX(calc(-100% - 24px));
}
#display-panel.visible {
transform: translateX(0);
opacity: 1;
pointer-events: auto;
}
.side-panel h3 {
margin-top: 0; margin-bottom: 15px; color: #fff; font-weight: 500;
border-bottom: 1px solid #3a4150; padding-bottom: 10px;
}
.panel-info-text {
font-size: 13px; color: #9fb0d0; margin-top: -10px; margin-bottom: 15px;
background: rgba(0,0,0,0.2); padding: 8px; border-radius: 6px;
}
.control-grid {
display: grid; grid-template-columns: 100px 1fr; gap: 12px; font-size: 14px; align-items: center;
}
.control-grid label {
font-weight: 500; color: #9fb0d0; background: none; border: none; padding: 0;
}
.control-grid span, .control-grid input, .control-grid select {
font-family: monospace; background: #0b0e14; padding: 4px 8px;
border-radius: 4px; color: #c8d3f5; border: 1px solid #3a4150;
}
.control-grid button { width: 100%; justify-content: center; }
#edit-toolbar { display: none; gap: 8px; }
#edit-toolbar button.active { background-color: #5476ff; border-color: #839eff; }
#camera-mode-indicator {
position: fixed; bottom: 45px; left: 50%;
transform: translateX(-50%);
background: rgba(84, 118, 255, 0.8); color: #fff;
padding: 8px 14px; border-radius: 8px; font-size: 14px;
font-weight: 500; z-index: 20; display: none; backdrop-filter: blur(6px);
}
#selection-box {
position: fixed;
background: rgba(84, 118, 255, 0.2);
border: 1px solid rgba(131, 158, 255, 0.8);
pointer-events: none;
display: none;
z-index: 1000;
}
/* --- Drawing Palette Styles (Consolidated) --- */
#drawing-palette {
position: fixed;
top: 70px; /* Moved down to avoid overlap with main toolbar */
right: 12px;
z-index: 11;
display: flex;
gap: 8px;
align-items: center;
flex-wrap: wrap;
background: rgba(20,24,33,0.9);
border: 1px solid rgba(255,255,255,0.15);
border-radius: 10px;
padding: 8px 12px;
color: #eaeffb;
}
#drawing-palette button {
padding: 0;
width: 36px;
height: 36px;
font-size: 14px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
}
#drawing-palette button.active {
background: #557fff;
border-color: #7faaff;
color: white;
}
#drawing-palette button svg {
width: 20px;
height: 20px;
stroke-width: 1.5;
}
#drawing-palette input[type="color"] {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
width: 36px;
height: 36px;
border: none;
border-radius: 8px;
cursor: pointer;
padding: 0;
background-color: transparent;
margin-left: 6px;
}
#drawing-palette input[type="color"]::-webkit-color-swatch {
border-radius: 8px;
border: 1px solid #3a4150;
}
#drawing-palette input[type="color"]::-moz-color-swatch {
border-radius: 8px;
border: 1px solid #3a4150;
}
#drawing-palette input[type="text"] {
width: 140px;
font-size: 14px;
padding: 6px 8px;
border-radius: 6px;
border: 1px solid #3a4150;
background: #0b0e14;
color: #c8dffb;
margin-left: 8px;
}
#zone-list {
margin-top: 15px;
max-height: 200px;
overflow-y: auto;
}
.zone-item {
display: flex;
align-items: center;
justify-content: space-between;
padding: 6px;
background: rgba(0,0,0,0.2);
border-radius: 4px;
margin-bottom: 5px;
font-size: 13px;
}
.zone-color-swatch {
width: 16px;
height: 16px;
border-radius: 4px;
margin-right: 8px;
border: 1px solid rgba(255,255,255,0.2);
}
</style>
</head>
<body>
<div id="app"></div>
<div id="selection-box"></div>
<div id="ui">
<label for="map-file" class="file-label">Open Map (.ply/.pcd)</label>
<input id="map-file" type="file" accept=".ply,.pcd" />
<button id="display-toggle">Display Tools</button>
<span style="border-left: 1px solid #444; margin: 0 4px;"></span>
<label for="waypoint-file" class="file-label">Open Waypoints (.db)</label>
<input id="waypoint-file" type="file" accept=".db,.sqlite" />
<button id="new-waypoints">New Waypoint Set</button>
<button id="save-waypoints" disabled>Save Waypoints (.db)</button>
<span style="border-left: 1px solid #444; margin: 0 4px;"></span>
<button id="add-label-toggle" disabled>Add Label</button>
<button id="generate-path" disabled>Generate Path</button>
<button id="edit" disabled>Toggle Edit Mode</button>
<div id="edit-toolbar">
<button id="edit-add">Add</button>
<button id="edit-select" class="active">Select</button>
<button id="edit-move">Move</button>
<button id="edit-interpolate">Interpolate</button>
<button id="edit-delete">Delete</button>
<button id="edit-zone">Zones</button>
<span style="border-left: 1px solid #444; margin: 0 4px;"></span>
<button id="edit-undo" disabled>Undo</button>
<button id="edit-redo" disabled>Redo</button>
</div>
<select id="view-select">
<option value="perspective">Perspective View</option>
<option value="top">Top-Down View</option>
<option value="front">Front View</option>
<option value="side">Side View</option>
</select>
<button id="lock-rotation">Lock Rotation</button>
</div>
<div id="loader">Loading...</div>
<div id="info-panel" class="side-panel">
<h3>Selected Waypoint</h3>
<div class="control-grid">
<label>X:</label> <span id="info-x">---</span>
<label>Y:</label> <span id="info-y">---</span>
<label>Z:</label> <span id="info-z">---</span>
</div>
<h3 style="margin-top: 15px;">Orientation</h3>
<div class="control-grid">
<label>Roll:</label> <span id="info-roll">---</span>
<label>Pitch:</label> <span id="info-pitch">---</span>
<label>Yaw:</label> <span id="info-yaw">---</span>
</div>
</div>
<div id="interpolation-panel" class="side-panel">
<h3>Interpolation Tools</h3>
<p id="interpolation-info" class="panel-info-text">Click a start and end point on the path to begin.</p>
<div class="control-grid">
<button id="linear-interpolate" style="grid-column: 1 / -1;" disabled>Linear Interpolate</button>
<label style="grid-column: 1 / -1; margin-top: 8px; margin-bottom: -4px; color: #fff; background: none; border: none; padding: 0;">Curve (Radial)</label>
<div style="grid-column: 1 / -1; display: grid; grid-template-columns: 1fr auto; gap: 8px; align-items: center;">
<input type="range" id="radial-strength" min="-15" max="15" step="0.1" value="3" disabled>
<input type="number" id="radial-strength-value" min="-15" max="15" step="0.01" value="3" style="width: 70px; -moz-appearance: textfield;" disabled>
</div>
<small style="grid-column: 1 / -1; font-size: 11px; color: #9fb0d0; margin-top: -8px;">Changes are applied on release.</small>
</div>
</div>
<div id="move-panel" class="side-panel">
<h3>Move Tool</h3>
<p id="move-info" class="panel-info-text">Click and drag a selected point to move. If multiple points are selected, they will all move together.</p>
<h3 style="margin-top:20px; margin-bottom:10px; border:none; padding:0;">Selection Tools</h3>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px;">
<button id="move-select-box">Select Box</button>
<button id="move-select-path">Select Path</button>
</div>
<h3 style="margin-top:20px; margin-bottom:10px; border:none; padding:0;">Path Tools</h3>
<div style="display:flex; flex-direction:column; gap: 4px;">
<button id="generate-connections" style="width:100%;" disabled>Generate Path Connections</button>
<small style="font-size: 11px; color: #9fb0d0;">After moving points, generate a smooth transition to their neighbors.</small>
</div>
</div>
<div id="zone-panel" class="side-panel">
<h3>Zone Tools</h3>
<p id="zone-info" class="panel-info-text">Click a start waypoint to begin defining a new zone.</p>
<div class="control-grid">
<label>Zone Name:</label>
<input type="text" id="zone-name-input" placeholder="e.g., 'parking_area'" disabled>
<button id="create-zone-btn" style="grid-column: 1 / -1;" disabled>Create Zone</button>
<button id="clear-zone-selection-btn" style="grid-column: 1 / -1; display: none;">Clear Selection</button>
</div>
<h3 style="margin-top:20px;">Existing Zones</h3>
<div id="zone-list"></div>
</div>
<div id="display-panel" class="side-panel">
<h3>Display Tools</h3>
<div class="control-grid">
<label>Map Point Size</label>
<input type="range" id="map-point-size" min="0.1" max="10" step="0.1" value="0.5">
<label>Waypoint Size</label>
<input type="range" id="waypoint-size" min="0.01" max="0.5" step="0.005" value="0.05">
<label>Color</label>
<select id="color-mode">
<option value="default">Default</option>
<option value="height">Height (Z)</option>
<option value="range">Range from Origin</option>
</select>
<label>Voxel Size</label>
<input type="range" id="voxel-size" min="0" max="0.5" step="0.01" value="0">
</div>
</div>
<div id="hint" class="hint-bar">
Orbit: Left-drag • Pan: Right-drag • Zoom: Wheel
</div>
<div id="hint-edit" class="hint-bar" style="display:none;">
<span id="edit-mode-hint">Select points by clicking or dragging a box.</span> <b>Hold Ctrl for camera.</b>
</div>
<div id="camera-mode-indicator"></div>
<div id="drawing-palette" style="display:none;">
<button id="tool-rect" title="Draw Rectangle"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect></svg></button>
<button id="tool-oval" title="Draw Oval"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><ellipse cx="12" cy="12" rx="10" ry="7"></ellipse></svg></button>
<button id="tool-triangle" title="Draw Triangle"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M12 2L2 22h20L12 2z"></path></svg></button>
<button id="tool-arrow" title="Draw Arrow"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M12 2v20m-6-8l6-6 6 6"></path></svg></button>
<button id="tool-pentagon" title="Draw Pentagon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M12 1.5l9.51 6.91-3.64 11.59H6.13L2.49 8.41 12 1.5z"></path></svg></button>
<button id="tool-star" title="Draw Star"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"></path></svg></button>
<button id="tool-select" title="Select/Move Shape" class="active"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M12 20l-7-15 15 7-8-2-2 8z"></path></svg></button>
<button id="tool-delete" title="Delete Shape"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg></button>
<label for="fill-color" title="Fill Color">Fill:</label>
<input type="color" id="fill-color" value="#557FFF" />
<label for="shape-text" title="Optional Text">Text:</label>
<input type="text" id="shape-text" placeholder="optional text" />
</div>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { PLYLoader } from 'three/addons/loaders/PLYLoader.js';
import { PCDLoader } from 'three/addons/loaders/PCDLoader.js';
// --- Basic setup ---
const app = document.getElementById('app');
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0b0e14);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
app.appendChild(renderer.domElement);
// --- Global Camera and Controls ---
let camera;
let controls;
scene.add(new THREE.AmbientLight(0xffffff, 0.7));
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(2, 2, 3);
scene.add(directionalLight);
const gridHelper = new THREE.GridHelper(10, 20, 0x3d4a66, 0x202838);
gridHelper.rotation.x = Math.PI / 2;
scene.add(gridHelper);
// --- Hover Indicator ---
const hoverRingGeo = new THREE.RingGeometry(1, 1.2, 32);
const hoverRingMat = new THREE.MeshBasicMaterial({ color: 0x00ffff, side: THREE.DoubleSide, transparent: true, opacity: 0.8, depthTest: false });
const hoverIndicator = new THREE.Mesh(hoverRingGeo, hoverRingMat);
hoverIndicator.visible = false;
scene.add(hoverIndicator);
let hoveredPointIndex = null;
// --- App State ---
const mapOffset = new THREE.Vector3();
let mapObject = null;
let waypointsObject = null;
let originalMapGeometry = null;
let editMode = false;
let editSubMode = 'select'; // Default to select mode
let moveSubMode = 'drag'; // 'drag', 'box-select', 'path-select'
let movePathStartIndex = null;
let selectedIndices = new Set();
let isDraggingPoint = false;
let dragStartIndex = -1;
let dragStartOffset = new THREE.Vector3();
let dragStartPositions = new Map();
let isRotationLocked = false;
let isCameraOverrideActive = false;
let indexToDbId = [];
let dynamicPointSize = 0.05;
let pathSelectionStartIndex = null;
let lastMovedIndices = null;
let transientGhostObject = null;
let persistentGhostObject = null;
let undoStack = [];
let redoStack = [];
const MAX_HISTORY = 50;
const pathGroup = new THREE.Group();
scene.add(pathGroup);
// Zone State
let zoneStartIndex = null;
const zoneColors = {};
// Interpolation State
let interpolationOriginalPositions = new Map();
// Marquee Selection State
let isMarqueeSelecting = false;
const selectionBox = document.getElementById('selection-box');
const marqueeStart = new THREE.Vector2();
const marqueeEnd = new THREE.Vector2();
const raycaster = new THREE.Raycaster();
raycaster.params.Points.threshold = 0.05;
const pointer = new THREE.Vector2();
const raycastPlane = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0);
const infoPanel = document.getElementById('info-panel');
const interpolationPanel = document.getElementById('interpolation-panel');
const movePanel = document.getElementById('move-panel');
const zonePanel = document.getElementById('zone-panel');
const hintMain = document.getElementById('hint');
const displayPanel = document.getElementById('display-panel');
const editToolbar = document.getElementById('edit-toolbar');
const cameraModeIndicator = document.getElementById('camera-mode-indicator');
const drawingPalette = document.getElementById('drawing-palette');
// --- Drawing/Annotation State ---
const shapeGroup = new THREE.Group();
scene.add(shapeGroup);
let currentTool = 'select';
let isDrawingShape = false;
let isMovingShape = false;
let shapeDragOffset = new THREE.Vector3();
let shapeDrawStartPoint = new THREE.Vector3();
let selectedShape = null;
let ghostShape = null;
let shapeCounter = 1;
const shapes = [];
let isDrawingPaletteVisible = false;
// --- Coordinate System Transformations ---
// ROS (x-fwd, y-left, z-up) to Three.js (y-fwd, x-right, z-up)
function rosToThree(v) {
return new THREE.Vector3(-v.y, v.x, v.z);
}
// Three.js to ROS
function threeToRos(v) {
return new THREE.Vector3(v.y, -v.x, v.z);
}
// --- Database Setup ---
let db = null;
let SQL = null;
const WAYPOINT_TABLE_SQL = `
CREATE TABLE IF NOT EXISTS waypoints (
id INTEGER PRIMARY KEY AUTOINCREMENT,
x REAL NOT NULL, y REAL NOT NULL, z REAL NOT NULL,
roll REAL DEFAULT 0, pitch REAL DEFAULT 0, yaw REAL DEFAULT 0,
zone TEXT DEFAULT 'N/A'
);`;
async function initDatabase() {
SQL = await initSqlJs({ locateFile: file => `https://cdnjs.cloudflare.com/ajax/libs/sql.js/1.10.3/${file}` });
}
// --- Undo/Redo and State Management ---
const undoBtn = document.getElementById('edit-undo');
const redoBtn = document.getElementById('edit-redo');
// --- Shape Serialization for Undo/Redo ---
function serializeShapes() {
return shapeGroup.children.map(mesh => {
return {
...mesh.userData.shapeData,
position: mesh.position.clone(),
};
});
}
function deserializeShapes(shapesState) {
// Clear existing shapes cleanly
while (shapeGroup.children.length > 0) {
const shape = shapeGroup.children[0];
shapeGroup.remove(shape);
shape.geometry.dispose();
shape.material.dispose();
if (shape.children.length > 0) {
const labelMesh = shape.children[0];
labelMesh.geometry.dispose();
if (labelMesh.material.map) labelMesh.material.map.dispose();
labelMesh.material.dispose();
}
}
shapes.length = 0; // Clear helper array
// Recreate shapes from the saved state
shapesState.forEach(data => {
const halfWidth = data.width / 2;
const halfHeight = data.height / 2;
const startPos = new THREE.Vector3(data.position.x - halfWidth, data.position.y - halfHeight, 0);
const endPos = new THREE.Vector3(data.position.x + halfWidth, data.position.y + halfHeight, 0);
addShapeMesh(data.type, startPos, endPos, data.fillColor, data.text, false);
});
}
function updateUndoRedoButtons() {
undoBtn.disabled = undoStack.length < 2;
redoBtn.disabled = redoStack.length === 0;
}
function recordState() {
redoStack = [];
const state = {
dbState: db ? db.export() : null,
shapesState: serializeShapes()
};
undoStack.push(state);
if (undoStack.length > MAX_HISTORY) {
undoStack.shift();
}
updateUndoRedoButtons();
}
async function undo() {
if (undoStack.length < 2) return;
const currentState = undoStack.pop();
redoStack.push(currentState);
const prevState = undoStack[undoStack.length - 1];
// Restore DB
if (prevState.dbState) {
if (db) db.close();
db = new SQL.Database(new Uint8Array(prevState.dbState));
await refreshWaypointsFromDB();
}
// Restore Shapes
deserializeShapes(prevState.shapesState);
clearAllGhostPreviews();
updateUndoRedoButtons();
}
async function redo() {
if (redoStack.length === 0) return;
const nextState = redoStack.pop();
undoStack.push(nextState);
// Restore DB
if (nextState.dbState) {
if (db) db.close();
db = new SQL.Database(new Uint8Array(nextState.dbState));
await refreshWaypointsFromDB();
}
// Restore Shapes
deserializeShapes(nextState.shapesState);
clearAllGhostPreviews();
updateUndoRedoButtons();
}
// --- Ghost Preview System ---
function createTransientGhostPreview() {
clearTransientGhostPreview();
const indices = Array.from(selectedIndices);
if (indices.length === 0 || !waypointsObject) return;
const positions = waypointsObject.geometry.attributes.position;
const ghostPositions = [];
for (const index of indices) {
ghostPositions.push(positions.getX(index), positions.getY(index), positions.getZ(index));
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute('position', new THREE.Float32BufferAttribute(ghostPositions, 3));
const material = new THREE.PointsMaterial({
size: camera.isPerspectiveCamera ? dynamicPointSize : (dynamicPointSize / 0.05 * 3.0),
sizeAttenuation: camera.isPerspectiveCamera,
color: 0x8888ff,
transparent: true,
opacity: 0.4
});
transientGhostObject = new THREE.Points(geometry, material);
scene.add(transientGhostObject);
}
function clearTransientGhostPreview() {
if (transientGhostObject) {
scene.remove(transientGhostObject);
transientGhostObject.geometry.dispose();
transientGhostObject.material.dispose();
transientGhostObject = null;
}
}
async function createPersistentGhostPreview() {
clearPersistentGhostPreview();
const indices = Array.from(selectedIndices);
if (indices.length === 0 || undoStack.length === 0) return;
const lastState = undoStack[undoStack.length - 1];
if (!lastState.dbState) return;
const tempDb = new SQL.Database(new Uint8Array(lastState.dbState));
const stmt = tempDb.prepare("SELECT x, y, z FROM waypoints ORDER BY id;");
const allOldPositions = [];
while (stmt.step()) {
const row = stmt.get();
const transformed = rosToThree({x: row[0], y: row[1], z: row[2]});
allOldPositions.push(transformed.x - mapOffset.x, transformed.y - mapOffset.y, transformed.z - mapOffset.z);
}
stmt.free();
tempDb.close();
const ghostPositions = [];
for (const index of indices) {
if (index * 3 < allOldPositions.length) {
ghostPositions.push(allOldPositions[index * 3], allOldPositions[index * 3 + 1], allOldPositions[index * 3 + 2]);
}
}
if (ghostPositions.length === 0) return;
const geometry = new THREE.BufferGeometry();
geometry.setAttribute('position', new THREE.Float32BufferAttribute(ghostPositions, 3));
const material = new THREE.PointsMaterial({
size: camera.isPerspectiveCamera ? dynamicPointSize * 0.8 : (dynamicPointSize / 0.05 * 2.0),
sizeAttenuation: camera.isPerspectiveCamera,
color: 0x3377ff,
transparent: true,
opacity: 0.7
});
persistentGhostObject = new THREE.Points(geometry, material);
scene.add(persistentGhostObject);
}
function clearPersistentGhostPreview() {
if (persistentGhostObject) {
scene.remove(persistentGhostObject);
persistentGhostObject.geometry.dispose();
persistentGhostObject.material.dispose();
persistentGhostObject = null;
}
}
function clearAllGhostPreviews() {
clearTransientGhostPreview();
clearPersistentGhostPreview();
}
// --- Annotation Shape Drawing ---
function createShapeGeometry(type, width, height) {
const halfWidth = width / 2;
const halfHeight = height / 2;
const shape = new THREE.Shape();
switch(type) {
case 'rect':
shape.moveTo(-halfWidth, -halfHeight);
shape.lineTo(halfWidth, -halfHeight);
shape.lineTo(halfWidth, halfHeight);
shape.lineTo(-halfWidth, halfHeight);
shape.closePath();
break;
case 'oval':
shape.absellipse(0, 0, halfWidth, halfHeight, 0, Math.PI * 2, false);
break;
case 'triangle':
shape.moveTo(0, halfHeight);
shape.lineTo(-halfWidth, -halfHeight);
shape.lineTo(halfWidth, -halfHeight);
shape.closePath();
break;
case 'arrow':
const bodyW = halfWidth * 0.4;
const headW = halfWidth;
const headH = halfHeight * 0.4;
shape.moveTo(0, halfHeight);
shape.lineTo(-headW, halfHeight - headH);
shape.lineTo(-bodyW, halfHeight - headH);
shape.lineTo(-bodyW, -halfHeight);
shape.lineTo(bodyW, -halfHeight);
shape.lineTo(bodyW, halfHeight - headH);
shape.lineTo(headW, halfHeight - headH);
shape.closePath();
break;
case 'pentagon':
const pRadius = Math.min(halfWidth, halfHeight);
for (let i = 0; i < 5; i++) {
const angle = (i * 2 * Math.PI) / 5 - Math.PI / 2;
const x = Math.cos(angle) * pRadius;
const y = Math.sin(angle) * pRadius;
if (i===0) shape.moveTo(x,y); else shape.lineTo(x,y);
}
shape.closePath();
break;
case 'star':
const outerRadius = Math.min(halfWidth, halfHeight);
const innerRadius = outerRadius * 0.4;
for (let i = 0; i < 10; i++) {
const angle = (i * Math.PI) / 5 - Math.PI / 2;
const radius = i % 2 === 0 ? outerRadius : innerRadius;
const x = Math.cos(angle) * radius;
const y = Math.sin(angle) * radius;
if (i === 0 ) shape.moveTo(x,y); else shape.lineTo(x,y);
}
shape.closePath();
break;
default:
return null;
}
return new THREE.ShapeGeometry(shape);
}
function addShapeMesh(type, startPos, endPos, fillColor, text, isGhost = false) {
const width = Math.abs(endPos.x - startPos.x);
const height = Math.abs(endPos.y - startPos.y);
if (width < 0.05 && height < 0.05) return null;
const geo = createShapeGeometry(type, width, height);
if (!geo) return null;
const mat = new THREE.MeshBasicMaterial({
color: fillColor || 0x4477ff,
transparent: true,
opacity: isGhost ? 0.3 : 0.6,
side: THREE.DoubleSide,
polygonOffset: true,
polygonOffsetFactor: -shapes.length - 1, // Pulls the polygon towards the camera
polygonOffsetUnits: -1
});
const mesh = new THREE.Mesh(geo, mat);
// A small, constant Z offset to keep shapes slightly above the grid.
mesh.position.set((startPos.x + endPos.x)/2, (startPos.y + endPos.y)/2, 0.01);
if (text && text.trim().length > 0 && !isGhost) {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
const fontSize = 48; // Use higher resolution for sharper text
context.font = `${fontSize}px sans-serif`;
const textWidth = context.measureText(text).width;
canvas.width = THREE.MathUtils.ceilPowerOfTwo(textWidth + 20);
canvas.height = THREE.MathUtils.ceilPowerOfTwo(fontSize * 1.5);
// Re-apply font settings after resize
context.font = `${fontSize}px sans-serif`;
context.fillStyle = 'white';
context.textAlign = 'center';
context.textBaseline = 'middle';
context.fillText(text, canvas.width/2, canvas.height/2);
const tex = new THREE.CanvasTexture(canvas);
tex.minFilter = THREE.LinearFilter;
tex.needsUpdate = true; // Ensures the texture updates reliably
const labelMat = new THREE.MeshBasicMaterial({ map: tex, transparent: true, depthTest: false });
// Scale the label plane relative to the parent shape's width
const labelAspect = canvas.height / canvas.width;
const labelWidth = width * 0.9;
const labelHeight = labelWidth * labelAspect;
const labelGeo = new THREE.PlaneGeometry(labelWidth, labelHeight);
const labelMesh = new THREE.Mesh(labelGeo, labelMat);
labelMesh.position.set(0, 0, 0.001); // Keep label just slightly above its parent shape
mesh.add(labelMesh);
}
if (!isGhost) {
mesh.userData.shapeData = { type, width, height, fillColor, text };
shapes.push(mesh);
}
shapeGroup.add(mesh);
return mesh;
}
function selectShape(mesh) {
if (selectedShape) {
selectedShape.material.emissive?.setHex(0x000000);
}
selectedShape = mesh;
if (selectedShape) {
if (!selectedShape.material.emissive) {
selectedShape.material.emissive = new THREE.Color(0x000000);
}
selectedShape.material.emissive.setHex(0xcccc00); // Highlight color
}
}
function deleteSelectedShape() {
if (!selectedShape) return;
recordState();
shapeGroup.remove(selectedShape);
selectedShape.geometry.dispose();
selectedShape.material.dispose();
if (selectedShape.children.length > 0) {
const labelMesh = selectedShape.children[0];
labelMesh.geometry.dispose();
if (labelMesh.material.map) {
labelMesh.material.map.dispose();
}
labelMesh.material.dispose();
}
const index = shapes.indexOf(selectedShape);
if (index > -1) {
shapes.splice(index, 1);
}
selectShape(null);
}
// --- Path Generation ---
function clearPathMesh() {
while(pathGroup.children.length > 0){
const mesh = pathGroup.children[0];
pathGroup.remove(mesh);
mesh.geometry.dispose();
mesh.material.dispose();
}
}
async function generatePathMesh() {
clearPathMesh();
if (!db) return;
const stmt = db.prepare("SELECT id, x, y, z, zone FROM waypoints ORDER BY id;");
const allWaypoints = [];
while(stmt.step()) {
allWaypoints.push(stmt.getAsObject());
}
stmt.free();
const waypoints = allWaypoints
.filter(wp => !(wp.x === 0 && wp.y === 0 && wp.z === 0))
.map(wp => ({
...wp,
pos: rosToThree({x: wp.x, y: wp.y, z: wp.z}).sub(mapOffset)
}));
if (waypoints.length < 2) return;
let currentSegment = [];
for (let i = 0; i < waypoints.length; i++) {
currentSegment.push(waypoints[i]);
const currentZone = waypoints[i].zone || 'N/A';
const nextZone = (i + 1 < waypoints.length) ? (waypoints[i+1].zone || 'N/A') : null;
if (currentZone !== nextZone || i === waypoints.length - 1) {
if (currentSegment.length >= 2) {
createPathSegmentMesh(currentSegment, currentZone);
}
currentSegment = [waypoints[i]]; // Start new segment with the current point
}
}
updateZoneList();
}
function createPathSegmentMesh(segmentPoints, zoneName) {
const points = segmentPoints.map(p => p.pos);
if (points.length < 2) return;
const leftVerts = [];
const rightVerts = [];
const halfWidth = 0.5; // 50cm
for (let i = 0; i < points.length; i++) {
const p_curr = points[i];
let normal, miterScale = 1.0;
if (i === 0) {
const dir_out = points[i+1].clone().sub(p_curr).normalize();
normal = new THREE.Vector3(-dir_out.y, dir_out.x, 0).normalize();
} else if (i === points.length - 1) {
const dir_in = p_curr.clone().sub(points[i-1]).normalize();
normal = new THREE.Vector3(-dir_in.y, dir_in.x, 0).normalize();
} else {
const dir_in = p_curr.clone().sub(points[i-1]).normalize();
const dir_out = points[i+1].clone().sub(p_curr).normalize();
const normal_in = new THREE.Vector3(-dir_in.y, dir_in.x, 0);
const normal_out = new THREE.Vector3(-dir_out.y, dir_out.x, 0);
normal = normal_in.clone().add(normal_out).normalize();
const dot = normal_in.dot(normal);
if (Math.abs(dot) > 0.0001) miterScale = 1 / dot;
}
leftVerts.push(p_curr.clone().add(normal.clone().multiplyScalar(halfWidth * miterScale)));
rightVerts.push(p_curr.clone().sub(normal.clone().multiplyScalar(halfWidth * miterScale)));
}
const vertices = [];
for (let i = 0; i < points.length; i++) {
vertices.push(leftVerts[i].x, leftVerts[i].y, leftVerts[i].z);
vertices.push(rightVerts[i].x, rightVerts[i].y, rightVerts[i].z);
}
const indices = [];
for (let i = 0; i < points.length - 1; i++) {
const i2 = i * 2;
indices.push(i2, i2 + 1, i2 + 2, i2 + 2, i2 + 1, i2 + 3);
}
if (!zoneColors[zoneName]) {
zoneColors[zoneName] = (zoneName === 'N/A') ? 0x559FFF : new THREE.Color().setHSL(Math.random(), 0.7, 0.6).getHex();
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute('position', new THREE.Float32BufferAttribute(vertices, 3));
geometry.setIndex(indices);
const material = new THREE.MeshBasicMaterial({
color: zoneColors[zoneName],
transparent: true, opacity: 0.4, side: THREE.DoubleSide
});
const mesh = new THREE.Mesh(geometry, material);
mesh.renderOrder = -1;
pathGroup.add(mesh);
}
// --- Waypoint Loading and Management ---
function clearVisualWaypoints() {
if (waypointsObject) {
scene.remove(waypointsObject);
waypointsObject.geometry.dispose();
waypointsObject.material.dispose();
waypointsObject = null;
}
clearSelection();
indexToDbId = [];
}
function updateWaypointVisuals() {
if (!waypointsObject || !camera) return;
const perspectiveSize = dynamicPointSize;
const orthoBaseSize = 3.0;
const defaultDynamicSize = 0.05;
const orthoSize = orthoBaseSize * (dynamicPointSize / defaultDynamicSize);
waypointsObject.material.size = camera.isPerspectiveCamera ? perspectiveSize : orthoSize;
waypointsObject.material.sizeAttenuation = camera.isPerspectiveCamera;
waypointsObject.material.needsUpdate = true;
}
async function refreshWaypointsFromDB() {
const oldSelectionDbIds = new Set(Array.from(selectedIndices).map(i => indexToDbId[i]));
clearVisualWaypoints();
if (!db) return;
const stmt = db.prepare("SELECT id, x, y, z FROM waypoints ORDER BY id;");
const positions = [];
indexToDbId = [];
const dbIdToIndex = new Map();
while (stmt.step()) {
const row = stmt.get();
const currentIndex = indexToDbId.length;
indexToDbId.push(row[0]);
dbIdToIndex.set(row[0], currentIndex);
const transformed = rosToThree({x: row[1], y: row[2], z: row[3]});
positions.push(transformed.x - mapOffset.x, transformed.y - mapOffset.y, transformed.z - mapOffset.z);
}
stmt.free();
if (positions.length === 0) return;
const geometry = new THREE.BufferGeometry();
geometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
const material = new THREE.PointsMaterial({ size: dynamicPointSize, vertexColors: true });
waypointsObject = new THREE.Points(geometry, material);
// Restore selection
selectedIndices.clear();
for (const dbId of oldSelectionDbIds) {
if (dbIdToIndex.has(dbId)) {
selectedIndices.add(dbIdToIndex.get(dbId));
}
}
updateAllColors();
scene.add(waypointsObject);
updateWaypointVisuals();
updateInfoPanel();
}