-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrr-robot-c-space.html
More file actions
935 lines (804 loc) · 33.8 KB
/
rr-robot-c-space.html
File metadata and controls
935 lines (804 loc) · 33.8 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>RR Robot C-Space Visualizer</title>
<!-- Tailwind CSS for Responsive Design -->
<script src="https://cdn.tailwindcss.com"></script>
<style>
/* Custom styles for specific interaction needs */
body, html {
height: 100%;
overflow-x: hidden;
touch-action: none; /* Prevent default touch scrolling on canvas/svg areas */
}
/* Ensures the container tries to fit but maintains aspect ratio logic via JS/Flex centering */
.viz-wrapper {
display: flex;
justify-content: center;
align-items: center;
background-color: #f1f5f9;
border-radius: 0.5rem;
overflow: hidden;
position: relative;
}
.canvas-container {
background-color: #ffffff;
border: 2px solid #e5e7eb;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
touch-action: none;
/* Enforce Square Aspect Ratio */
aspect-ratio: 1 / 1;
height: 100%;
/* Constraints to prevent it from becoming too tall */
/* max-width: 600px; */
/* max-height: 70vh; */
margin: auto;
}
#workspace-svg {
cursor: crosshair;
width: 100%;
height: 100%;
display: block;
}
#cspace-canvas {
width: 100%;
height: 100%;
/* Removed pixelated rendering to allow smooth lines at high res */
cursor: crosshair;
}
#cspace-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
/* pointer-events: none; REMOVED to allow interaction */
cursor: crosshair;
}
.highlighted {
stroke: #ef4444 !important; /* Red stroke */
stroke-width: 3px !important;
filter: drop-shadow(0 0 4px rgba(239, 68, 68, 0.5));
}
.collision-state {
background-color: #fee2e2 !important; /* Light red bg */
border-color: #ef4444 !important;
}
.noselect {
user-select: none;
-webkit-user-select: none;
}
</style>
</head>
<body class="bg-slate-50 text-slate-800 flex flex-col h-screen">
<!-- Header / Toolbar -->
<header class="bg-white shadow-sm border-b p-3 z-10 flex-none">
<div class="max-w-7xl mx-auto flex flex-wrap gap-3 items-center justify-between">
<h1 class="text-xl font-bold text-slate-700">RR Robot C-Space</h1>
<div class="flex gap-2">
<button onclick="app.reset()" class="px-3 py-1.5 bg-gray-200 hover:bg-gray-300 rounded text-sm font-medium transition">Reset</button>
<button onclick="app.share()" class="px-3 py-1.5 bg-blue-600 hover:bg-blue-700 text-white rounded text-sm font-medium transition flex items-center gap-1">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"/><polyline points="16 6 12 2 8 6"/><line x1="12" y1="2" x2="12" y2="15"/></svg>
Share
</button>
</div>
</div>
</header>
<!-- Main Content Area -->
<main class="flex-grow flex flex-col lg:flex-row p-2 gap-2 h-full overflow-hidden">
<!-- Workspace (Left/Top) -->
<div class="flex-1 flex flex-col min-h-[300px] lg:h-full relative overflow-hidden">
<div class="flex justify-between items-center mb-1 px-1 flex-none">
<h2 class="text-sm font-bold uppercase tracking-wider text-slate-500">Workspace (Physical)</h2>
<!-- Added truncate class to handle long text gracefully -->
<div class="text-xs text-slate-400 truncate max-w-[200px] sm:max-w-none" id="workspace-status">Double-click background to draw</div>
</div>
<!-- Wrapper to center the square container -->
<div class="viz-wrapper flex-grow w-full h-full p-2">
<div class="canvas-container relative" id="workspace-container">
<svg id="workspace-svg" preserveAspectRatio="none" viewBox="0 0 600 600">
<!-- Grid Lines -->
<defs>
<pattern id="grid" width="50" height="50" patternUnits="userSpaceOnUse">
<path d="M 50 0 L 0 0 0 50" fill="none" stroke="#f1f5f9" stroke-width="1"/>
</pattern>
</defs>
<rect width="100%" height="100%" fill="url(#grid)" />
<!-- Obstacles Group -->
<g id="obstacles-layer"></g>
<!-- Robot Group -->
<g id="robot-layer">
<!-- Link 1 -->
<g id="link1-group">
<rect id="link1-visual" x="0" y="-10" width="100" height="20" rx="5" fill="#94a3b8" stroke="black" stroke-width="2" />
<circle cx="0" cy="0" r="8" fill="#475569" /> <!-- Base Joint -->
</g>
<!-- Link 2 -->
<g id="link2-group">
<rect id="link2-visual" x="0" y="-8" width="80" height="16" rx="4" fill="#cbd5e1" stroke="black" stroke-width="2" />
<circle cx="0" cy="0" r="6" fill="#475569" /> <!-- Elbow Joint -->
<!-- End Effector (Gripper) -->
<g id="ee-group" transform="translate(80, 0)">
<line x1="0" y1="-10" x2="0" y2="10" stroke="black" stroke-width="2" />
<rect x="0" y="-12" width="15" height="4" fill="#475569" />
<rect x="0" y="8" width="15" height="4" fill="#475569" />
<circle id="ee-handle" cx="5" cy="0" r="15" fill="rgba(0,0,0,0)" cursor="pointer" />
</g>
</g>
</g>
<!-- Interaction Layer (for drawing) -->
<g id="drawing-layer"></g>
</svg>
</div>
</div>
</div>
<!-- C-Space (Right/Bottom) -->
<div class="flex-1 flex flex-col min-h-[300px] lg:h-full overflow-hidden">
<div class="flex justify-between items-center mb-1 px-1 flex-none">
<h2 class="text-sm font-bold uppercase tracking-wider text-slate-500">C-Space (Config)</h2>
<div class="text-xs text-slate-400">X: θ1 (0-360°), Y: θ2 (0-360°)</div>
</div>
<!-- Wrapper to center the square container -->
<div class="viz-wrapper flex-grow w-full h-full p-2">
<div class="canvas-container relative" id="cspace-container">
<!-- Base Canvas for static C-Obstacles -->
<canvas id="cspace-canvas" width="360" height="360"></canvas>
<!-- Overlay Canvas for crosshair and dynamic elements -->
<canvas id="cspace-overlay" width="360" height="360"></canvas>
</div>
</div>
</div>
</main>
<!-- Info / Tutorial Footer -->
<footer class="bg-white border-t p-4 text-sm text-slate-600 overflow-y-auto max-h-[30vh] flex-none">
<div class="max-w-5xl mx-auto grid md:grid-cols-2 gap-6">
<div>
<h3 class="font-bold mb-2 text-slate-800">Controls</h3>
<ul class="list-disc pl-4 space-y-1">
<li><strong>Drag Links:</strong> Rotate specific joints (FK).</li>
<li><strong>Drag Gripper:</strong> Move end-effector (IK).</li>
<li><strong>Double-Click Drag Joints:</strong> Resize link lengths.</li>
<li><strong>Draw Obstacle:</strong> Double-click background to start. Click to add points. Click near start to close.</li>
<li><strong>Obstacles:</strong> Click to select. Drag to move. 'Delete' key to remove.</li>
<li><strong>C-Space:</strong> Click/Drag right panel to jump to configuration.</li>
</ul>
</div>
<div>
<h3 class="font-bold mb-2 text-slate-800">Concept: C-Space</h3>
<p>
The <strong>Configuration Space (C-Space)</strong> represents all possible states of the robot.
For this 2-link (RR) robot, the state is defined by two angles: $\theta_1$ (Base) and $\theta_2$ (Elbow).
</p>
<p class="mt-2">
<strong>C-Obstacles</strong> (colored regions on the right) represent configurations where the robot collides with physical obstacles.
</p>
</div>
</div>
</footer>
<!-- Toast Notification -->
<div id="toast" class="fixed bottom-20 left-1/2 transform -translate-x-1/2 bg-slate-800 text-white px-4 py-2 rounded shadow-lg opacity-0 transition-opacity duration-300 pointer-events-none z-50">
Notification
</div>
<script>
/**
* RR Robot C-Space Visualizer
* Core Logic Module
*/
// --- Constants & Config ---
const COLORS = [
'#F87171', '#FBBF24', '#34D399', '#60A5FA', '#818CF8',
'#A78BFA', '#F472B6', '#FB923C', '#A3E635', '#22D3EE'
];
const COLOR_COLLISION = '#EF4444';
const WORKSPACE_SIZE = 600;
const BASE_X = 300;
const BASE_Y = 300;
// Note: CANVAS_RES is now dynamic based on element size
// --- Math Helpers ---
const degToRad = d => d * (Math.PI / 180);
const radToDeg = r => r * (180 / Math.PI);
// Line Segment Intersection
function getSegmentIntersection(p0, p1, p2, p3) {
const s1_x = p1.x - p0.x;
const s1_y = p1.y - p0.y;
const s2_x = p3.x - p2.x;
const s2_y = p3.y - p2.y;
const s = (-s1_y * (p0.x - p2.x) + s1_x * (p0.y - p2.y)) / (-s2_x * s1_y + s1_x * s2_y);
const t = ( s2_x * (p0.y - p2.y) - s2_y * (p0.x - p2.x)) / (-s2_x * s1_y + s1_x * s2_y);
return (s >= 0 && s <= 1 && t >= 0 && t <= 1);
}
// Point in Polygon (Ray casting)
function isPointInPolygon(p, polygon) {
let inside = false;
for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
const xi = polygon[i].x, yi = polygon[i].y;
const xj = polygon[j].x, yj = polygon[j].y;
const intersect = ((yi > p.y) !== (yj > p.y)) && (p.x < (xj - xi) * (p.y - yi) / (yj - yi) + xi);
if (intersect) inside = !inside;
}
return inside;
}
// Polygon Bounding Box
function getBoundingBox(points) {
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
points.forEach(p => {
if(p.x < minX) minX = p.x; if(p.y < minY) minY = p.y;
if(p.x > maxX) maxX = p.x; if(p.y > maxY) maxY = p.y;
});
return { minX, minY, maxX, maxY };
}
// --- Application State ---
const app = {
// Robot State
robot: {
theta1: 45, // Degrees
theta2: 45, // Degrees
l1: 120,
l2: 100
},
// Environment
obstacles: [],
nextObsId: 1,
// Interaction State
selection: null,
interactionMode: 'IDLE',
drawingPoints: [],
drawingStartTime: 0,
dragOffset: {x:0, y:0},
// UI State
isColliding: false,
dirtyCSpace: true,
// Double click detection
lastClickTime: 0,
// DOM Elements
elements: {}
};
// --- Initialization ---
window.onload = function() {
app.elements = {
svg: document.getElementById('workspace-svg'),
obsLayer: document.getElementById('obstacles-layer'),
link1Group: document.getElementById('link1-group'),
link2Group: document.getElementById('link2-group'),
link1Visual: document.getElementById('link1-visual'),
link2Visual: document.getElementById('link2-visual'),
cContainer: document.getElementById('cspace-container'),
cCanvas: document.getElementById('cspace-canvas'),
cCtx: document.getElementById('cspace-canvas').getContext('2d', { willReadFrequently: true }),
cOverlay: document.getElementById('cspace-overlay'),
cOverlayCtx: document.getElementById('cspace-overlay').getContext('2d'),
wsStatus: document.getElementById('workspace-status'),
toast: document.getElementById('toast'),
workspaceContainer: document.getElementById('workspace-container'),
eeHandle: document.getElementById('ee-handle')
};
// Initialize Canvas Size based on CSS/Screen pixels
resizeCanvases();
window.addEventListener('resize', () => {
resizeCanvases();
});
setupEvents();
loadStateFromHash();
app.dirtyCSpace = true;
requestAnimationFrame(gameLoop);
};
function resizeCanvases() {
const container = app.elements.cContainer;
const canvas = app.elements.cCanvas;
const overlay = app.elements.cOverlay;
// Get actual display size
const rect = container.getBoundingClientRect();
const dpr = window.devicePixelRatio || 1;
// Set internal resolution to match physical pixels
const targetW = Math.floor(rect.width * dpr);
const targetH = Math.floor(rect.height * dpr);
// Only update if changed to avoid clearing on mobile scrolls
if (canvas.width !== targetW || canvas.height !== targetH) {
canvas.width = targetW;
canvas.height = targetH;
overlay.width = targetW;
overlay.height = targetH;
app.dirtyCSpace = true;
}
}
// --- Core Logic ---
// Forward Kinematics
function getJointPositions(t1, t2, len1, len2) {
const r1 = degToRad(t1);
const r2 = degToRad(t2); // t2 is relative to link 1
const p0 = { x: BASE_X, y: BASE_Y };
const p1 = {
x: p0.x + len1 * Math.cos(r1),
y: p0.y + len1 * Math.sin(r1)
};
const globalT2 = r1 + r2;
const p2 = {
x: p1.x + len2 * Math.cos(globalT2),
y: p1.y + len2 * Math.sin(globalT2)
};
return { p0, p1, p2 };
}
// Inverse Kinematics (Analytical)
function solveIK(targetX, targetY) {
const x = targetX - BASE_X;
const y = targetY - BASE_Y;
const distSq = x*x + y*y;
const l1 = app.robot.l1;
const l2 = app.robot.l2;
const dist = Math.sqrt(distSq);
if (dist > l1 + l2 || dist < Math.abs(l1 - l2)) return null;
let cosT2 = (distSq - l1*l1 - l2*l2) / (2 * l1 * l2);
cosT2 = Math.max(-1, Math.min(1, cosT2));
const theta2_rad_abs = Math.acos(cosT2);
// Choose solution closer to current
const currentT2Rad = degToRad(app.robot.theta2);
const normCurrT2 = Math.atan2(Math.sin(currentT2Rad), Math.cos(currentT2Rad));
let theta2_sol = theta2_rad_abs;
if (Math.abs(normCurrT2 - (-theta2_rad_abs)) < Math.abs(normCurrT2 - theta2_rad_abs)) {
theta2_sol = -theta2_rad_abs;
}
const phi = Math.atan2(y, x);
const beta = Math.atan2(l2 * Math.sin(theta2_sol), l1 + l2 * Math.cos(theta2_sol));
const theta1_sol = phi - beta;
return {
t1: (radToDeg(theta1_sol) + 360) % 360,
t2: (radToDeg(theta2_sol) + 360) % 360
};
}
// Collision Detection
function checkCollision(t1, t2) {
const pos = getJointPositions(t1, t2, app.robot.l1, app.robot.l2);
const link1Seg = [pos.p0, pos.p1];
const link2Seg = [pos.p1, pos.p2];
for (let obs of app.obstacles) {
if (obs.bounds.minX > (BASE_X + app.robot.l1 + app.robot.l2) || obs.bounds.maxX < 0) continue;
for (let i=0; i<obs.points.length; i++) {
const pA = obs.points[i];
const pB = obs.points[(i+1)%obs.points.length];
if (getSegmentIntersection(link1Seg[0], link1Seg[1], pA, pB)) return obs.id;
if (getSegmentIntersection(link2Seg[0], link2Seg[1], pA, pB)) return obs.id;
}
if (isPointInPolygon(pos.p1, obs.points)) return obs.id;
if (isPointInPolygon(pos.p2, obs.points)) return obs.id;
}
return null;
}
// --- Main Loop & Rendering ---
function gameLoop() {
updateVisuals();
if (app.dirtyCSpace) {
renderCSpaceMap();
app.dirtyCSpace = false;
updateHash();
}
renderCSpaceOverlay();
requestAnimationFrame(gameLoop);
}
function updateVisuals() {
const { p0, p1, p2 } = getJointPositions(app.robot.theta1, app.robot.theta2, app.robot.l1, app.robot.l2);
app.elements.link1Group.setAttribute('transform', `translate(${p0.x}, ${p0.y}) rotate(${app.robot.theta1})`);
app.elements.link2Group.setAttribute('transform', `translate(${p1.x}, ${p1.y}) rotate(${app.robot.theta1 + app.robot.theta2})`);
app.elements.link1Visual.setAttribute('width', app.robot.l1);
app.elements.link2Visual.setAttribute('width', app.robot.l2);
app.elements.link2Group.querySelector('#ee-group').setAttribute('transform', `translate(${app.robot.l2}, 0)`);
const collidingId = checkCollision(app.robot.theta1, app.robot.theta2);
app.isColliding = !!collidingId;
const stroke = app.isColliding ? COLOR_COLLISION : 'black';
app.elements.link1Visual.setAttribute('stroke', stroke);
app.elements.link2Visual.setAttribute('stroke', stroke);
Array.from(app.elements.obsLayer.children).forEach(el => {
const id = parseInt(el.getAttribute('data-id'));
const obs = app.obstacles.find(o => o.id === id);
if (!obs) return;
let isSelected = app.selection && app.selection.type === 'obstacle' && app.selection.id === id;
let isHit = id === collidingId;
if (isHit || isSelected) el.classList.add('highlighted');
else el.classList.remove('highlighted');
});
if (app.isColliding) app.elements.workspaceContainer.classList.add('collision-state');
else app.elements.workspaceContainer.classList.remove('collision-state');
}
function renderCSpaceMap() {
const ctx = app.elements.cCtx;
const width = ctx.canvas.width;
const height = ctx.canvas.height;
ctx.clearRect(0, 0, width, height);
const imgData = ctx.createImageData(width, height);
const data = imgData.data;
if (app.obstacles.length === 0) {
ctx.putImageData(imgData, 0, 0);
return;
}
// Optimization: If canvas is huge (retina), we might want to skip pixels?
// For now, let's go brute force but it might be slow on big screens.
// 600x600 = 360k pixels -> fast enough.
// 1200x1200 = 1.44M pixels -> approx 200-500ms. Acceptable for "dirty" updates only.
for (let x = 0; x < width; x++) {
const t1 = (x / width) * 360; // Map x to 0-360
for (let y = 0; y < height; y++) {
// Map y to 0-360, but inverted (canvas 0 is top, we want 0 at bottom)
const t2 = ((height - 1 - y) / height) * 360;
const colId = checkCollision(t1, t2);
const idx = (y * width + x) * 4;
if (colId) {
const obs = app.obstacles.find(o => o.id === colId);
const hex = COLORS[obs.colorIdx % COLORS.length];
const rgb = hexToRgb(hex);
data[idx] = rgb.r;
data[idx + 1] = rgb.g;
data[idx + 2] = rgb.b;
data[idx + 3] = 255;
} else {
data[idx + 3] = 0;
}
}
}
ctx.putImageData(imgData, 0, 0);
}
function renderCSpaceOverlay() {
const ctx = app.elements.cOverlayCtx;
const width = ctx.canvas.width;
const height = ctx.canvas.height;
ctx.clearRect(0, 0, width, height);
// Map current robot angles to canvas coordinates
const x = (app.robot.theta1 / 360) * width;
const y = height - (app.robot.theta2 / 360) * height;
ctx.strokeStyle = app.isColliding ? '#EF4444' : '#334155';
ctx.lineWidth = 2 * (window.devicePixelRatio || 1); // Scale line width
ctx.beginPath();
ctx.moveTo(x, 0);
ctx.lineTo(x, height);
ctx.moveTo(0, y);
ctx.lineTo(width, y);
ctx.stroke();
ctx.fillStyle = 'white';
ctx.beginPath();
ctx.arc(x, y, 4 * (window.devicePixelRatio || 1), 0, Math.PI * 2);
ctx.fill();
ctx.stroke();
}
function hexToRgb(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : {r:0,g:0,b:0};
}
// --- Interaction Handling ---
function setupEvents() {
const getCoords = (e, el, logicalSize) => {
const rect = el.getBoundingClientRect();
const clientX = e.touches ? e.touches[0].clientX : e.clientX;
const clientY = e.touches ? e.touches[0].clientY : e.clientY;
// Offset relative to element
const x_dom = clientX - rect.left;
const y_dom = clientY - rect.top;
// Scale Factor (Logical Units / Pixel Units)
const scaleX = logicalSize / rect.width;
const scaleY = logicalSize / rect.height;
return {
x: x_dom * scaleX,
y: y_dom * scaleY
};
};
// --- Workspace Events (Logical Size: 600) ---
const ws = app.elements.svg;
const wsPointerDown = (e) => {
e.preventDefault();
const { x, y } = getCoords(e, ws, 600);
const now = Date.now();
const isDoubleClick = (now - app.lastClickTime) < 300;
app.lastClickTime = now;
// --- DRAWING MODE STATE PROTECTION ---
if (app.interactionMode === 'DRAWING') {
const start = app.drawingPoints[0];
const distToStart = dist(x, y, start.x, start.y);
if (app.drawingPoints.length > 2 && distToStart < 20) {
finishDrawing();
return;
}
const lastCommitted = app.drawingPoints[app.drawingPoints.length - 2];
if (!lastCommitted || dist(x, y, lastCommitted.x, lastCommitted.y) > 10) {
app.drawingPoints.push({x, y});
renderDrawing();
}
return;
}
const { p0, p1, p2 } = getJointPositions(app.robot.theta1, app.robot.theta2, app.robot.l1, app.robot.l2);
if (dist(x,y, p2.x, p2.y) < 25) {
if (isDoubleClick) app.interactionMode = 'RESIZING_L2';
else app.interactionMode = 'DRAGGING_EE';
return;
}
if (dist(x,y, p1.x, p1.y) < 20) {
if (isDoubleClick) { app.interactionMode = 'RESIZING_L1'; return; }
}
if (isPointNearLine(x,y, p1.x, p1.y, p2.x, p2.y, 15)) {
app.interactionMode = 'DRAGGING_LINK2';
return;
}
if (isPointNearLine(x,y, p0.x, p0.y, p1.x, p1.y, 15)) {
app.interactionMode = 'DRAGGING_LINK1';
return;
}
for (let i = app.obstacles.length - 1; i >= 0; i--) {
if (isPointInPolygon({x,y}, app.obstacles[i].points)) {
app.selection = { type: 'obstacle', id: app.obstacles[i].id };
app.interactionMode = 'MOVING_OBSTACLE';
app.dragOffset = { x, y };
updateVisuals();
return;
}
}
if (isDoubleClick) {
app.interactionMode = 'DRAWING';
app.drawingStartTime = Date.now();
app.drawingPoints = [{x,y}, {x,y}];
renderDrawing();
app.elements.wsStatus.innerText = "DRAW: Click adds point. Dbl-click closes.";
app.elements.wsStatus.style.color = 'blue';
app.elements.wsStatus.style.fontWeight = 'bold';
} else {
app.selection = null;
updateVisuals();
}
};
const wsPointerMove = (e) => {
const { x, y } = getCoords(e, ws, 600);
if (app.interactionMode === 'DRAGGING_LINK1') {
const angle = radToDeg(Math.atan2(y - BASE_Y, x - BASE_X));
app.robot.theta1 = (angle + 360) % 360;
} else if (app.interactionMode === 'DRAGGING_LINK2') {
const { p1 } = getJointPositions(app.robot.theta1, app.robot.theta2, app.robot.l1, app.robot.l2);
const angle = radToDeg(Math.atan2(y - p1.y, x - p1.x));
const relative = angle - app.robot.theta1;
app.robot.theta2 = (relative + 360) % 360;
} else if (app.interactionMode === 'DRAGGING_EE') {
const sol = solveIK(x, y);
if (sol) {
app.robot.theta1 = sol.t1;
app.robot.theta2 = sol.t2;
}
} else if (app.interactionMode === 'MOVING_OBSTACLE' && app.selection) {
const dx = x - app.dragOffset.x;
const dy = y - app.dragOffset.y;
const obs = app.obstacles.find(o => o.id === app.selection.id);
if (obs) {
obs.points.forEach(p => { p.x += dx; p.y += dy; });
obs.bounds = getBoundingBox(obs.points);
app.dirtyCSpace = true;
// Update SVG in real-time
const el = app.elements.obsLayer.querySelector(`[data-id="${obs.id}"]`);
if (el) {
el.setAttribute("points", obs.points.map(p => `${p.x},${p.y}`).join(" "));
}
}
app.dragOffset = { x, y };
} else if (app.interactionMode === 'DRAWING') {
app.drawingPoints[app.drawingPoints.length-1] = {x, y};
renderDrawing();
} else if (app.interactionMode === 'RESIZING_L1') {
const d = dist(x,y, BASE_X, BASE_Y);
app.robot.l1 = Math.max(20, Math.min(250, d));
app.dirtyCSpace = true;
} else if (app.interactionMode === 'RESIZING_L2') {
const { p1 } = getJointPositions(app.robot.theta1, app.robot.theta2, app.robot.l1, app.robot.l2);
const d = dist(x,y, p1.x, p1.y);
app.robot.l2 = Math.max(20, Math.min(250, d));
app.dirtyCSpace = true;
}
};
const wsPointerUp = (e) => {
if (app.interactionMode === 'DRAWING') {
const { x, y } = getCoords(e, ws, 600);
const lastCommitted = app.drawingPoints[app.drawingPoints.length - 2];
if (lastCommitted && dist(x, y, lastCommitted.x, lastCommitted.y) > 20) {
app.drawingPoints.push({x, y});
renderDrawing();
}
} else {
app.interactionMode = 'IDLE';
updateHash();
}
};
ws.addEventListener('dblclick', (e) => {
if (app.interactionMode === 'DRAWING') {
if (Date.now() - app.drawingStartTime < 500) return;
finishDrawing();
}
});
ws.addEventListener('pointerdown', wsPointerDown);
ws.addEventListener('pointermove', wsPointerMove);
ws.addEventListener('pointerup', wsPointerUp);
ws.addEventListener('pointerleave', wsPointerUp);
// --- C-Space Events ---
const cs = app.elements.cOverlay;
// Logic for C-Space Interaction (Independent of Pixel Size)
const csPointerHandler = (e) => {
if (e.type === 'pointerdown' || e.buttons === 1) {
e.preventDefault();
const rect = cs.getBoundingClientRect();
const clientX = e.touches ? e.touches[0].clientX : e.clientX;
const clientY = e.touches ? e.touches[0].clientY : e.clientY;
// Get percentage of width/height
const pctX = (clientX - rect.left) / rect.width;
const pctY = (clientY - rect.top) / rect.height;
// Map 0-1 to 0-360 (Inverting Y)
const t1 = Math.max(0, Math.min(360, pctX * 360));
const t2 = Math.max(0, Math.min(360, (1 - pctY) * 360));
app.robot.theta1 = t1;
app.robot.theta2 = t2;
updateHash();
}
};
cs.addEventListener('pointerdown', csPointerHandler);
cs.addEventListener('pointermove', csPointerHandler);
document.addEventListener('keydown', (e) => {
if ((e.key === 'Delete' || e.key === 'Backspace') && app.selection && app.selection.type === 'obstacle') {
app.obstacles = app.obstacles.filter(o => o.id !== app.selection.id);
app.selection = null;
app.dirtyCSpace = true;
updateVisuals();
renderObstacles();
}
});
}
function dist(x1, y1, x2, y2) {
return Math.sqrt((x2-x1)**2 + (y2-y1)**2);
}
function isPointNearLine(px, py, x1, y1, x2, y2, tolerance) {
const A = px - x1;
const B = py - y1;
const C = x2 - x1;
const D = y2 - y1;
const dot = A * C + B * D;
const lenSq = C * C + D * D;
let param = -1;
if (lenSq !== 0) param = dot / lenSq;
let xx, yy;
if (param < 0) {
xx = x1; yy = y1;
} else if (param > 1) {
xx = x2; yy = y2;
} else {
xx = x1 + param * C;
yy = y1 + param * D;
}
const dx = px - xx;
const dy = py - yy;
return (dx * dx + dy * dy) < (tolerance * tolerance);
}
function renderObstacles() {
app.elements.obsLayer.innerHTML = '';
app.obstacles.forEach(obs => {
const poly = document.createElementNS("http://www.w3.org/2000/svg", "polygon");
const pointsStr = obs.points.map(p => `${p.x},${p.y}`).join(" ");
poly.setAttribute("points", pointsStr);
poly.setAttribute("fill", COLORS[obs.colorIdx % COLORS.length]);
poly.setAttribute("stroke", "black");
poly.setAttribute("stroke-width", "2");
poly.setAttribute("opacity", "0.8");
poly.setAttribute("data-id", obs.id);
poly.style.cursor = "move";
app.elements.obsLayer.appendChild(poly);
});
}
function renderDrawing() {
const layer = document.getElementById('drawing-layer');
layer.innerHTML = '';
if (app.interactionMode !== 'DRAWING') return;
// Draw the polyline so far
const polyLine = document.createElementNS("http://www.w3.org/2000/svg", "polyline");
const pointsStr = app.drawingPoints.map(p => `${p.x},${p.y}`).join(" ");
polyLine.setAttribute("points", pointsStr);
polyLine.setAttribute("fill", "none");
polyLine.setAttribute("stroke", "blue");
polyLine.setAttribute("stroke-width", "2");
polyLine.setAttribute("stroke-dasharray", "5,5");
layer.appendChild(polyLine);
// Draw points
app.drawingPoints.forEach(p => {
const c = document.createElementNS("http://www.w3.org/2000/svg", "circle");
c.setAttribute("cx", p.x);
c.setAttribute("cy", p.y);
c.setAttribute("r", 4);
c.setAttribute("fill", "blue");
layer.appendChild(c);
});
// Highlight start point
const start = app.drawingPoints[0];
if (start) {
const s = document.createElementNS("http://www.w3.org/2000/svg", "circle");
s.setAttribute("cx", start.x);
s.setAttribute("cy", start.y);
s.setAttribute("r", 6);
s.setAttribute("fill", "none");
s.setAttribute("stroke", "blue");
s.setAttribute("stroke-width", "2");
layer.appendChild(s);
}
}
function finishDrawing() {
if (app.drawingPoints.length < 4) {
// Need at least 3 points + 1 cursor point
app.interactionMode = 'IDLE';
renderDrawing(); // clears layer
app.elements.wsStatus.innerText = "Double-click background to draw";
app.elements.wsStatus.style.color = '';
app.elements.wsStatus.style.fontWeight = '';
return;
}
app.drawingPoints.pop(); // Remove cursor point
const newObs = {
id: app.nextObsId++,
points: [...app.drawingPoints],
colorIdx: app.obstacles.length,
bounds: getBoundingBox(app.drawingPoints)
};
app.obstacles.push(newObs);
renderObstacles();
app.dirtyCSpace = true;
app.interactionMode = 'IDLE';
app.drawingPoints = [];
renderDrawing();
app.elements.wsStatus.innerText = "Double-click background to draw";
app.elements.wsStatus.style.color = '';
app.elements.wsStatus.style.fontWeight = '';
}
app.reset = function() {
app.obstacles = [];
app.robot = { theta1: 45, theta2: 45, l1: 120, l2: 100 };
app.dirtyCSpace = true;
app.selection = null;
app.interactionMode = 'IDLE';
renderObstacles();
updateVisuals();
updateHash();
};
app.share = function() {
const url = window.location.href;
navigator.clipboard.writeText(url).then(() => {
const t = app.elements.toast;
t.innerText = "URL copied to clipboard!";
t.style.opacity = '1';
setTimeout(() => t.style.opacity = '0', 2000);
});
};
function updateHash() {
if (app.hashTimer) clearTimeout(app.hashTimer);
app.hashTimer = setTimeout(() => {
const state = {
r: app.robot,
o: app.obstacles.map(o => ({...o, points: o.points.map(p=>({x:Math.round(p.x), y:Math.round(p.y)}))}))
};
const str = JSON.stringify(state);
window.location.hash = btoa(str);
}, 200);
}
function loadStateFromHash() {
try {
if (window.location.hash) {
const str = atob(window.location.hash.substring(1));
const state = JSON.parse(str);
if (state.r && state.o) {
app.robot = state.r;
app.obstacles = state.o.map(o => ({
...o,
bounds: getBoundingBox(o.points)
}));
if (app.obstacles.length > 0) {
app.nextObsId = Math.max(...app.obstacles.map(o => o.id)) + 1;
}
renderObstacles();
}
}
} catch (e) {
console.warn("Failed to load state", e);
}
}
</script>
</body>
</html>