-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimKresleni.html
More file actions
1723 lines (1518 loc) · 133 KB
/
Copy pathsimKresleni.html
File metadata and controls
1723 lines (1518 loc) · 133 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
<<<<<<< HEAD
<!DOCTYPE html>
<html lang="cs">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"
/>
<title>CNC SmartGrid v19 Lite</title>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"
/>
<style>
:root {
--bg-canvas: #ffffff;
--bg-panel: #1e1e1e;
--bg-btn: #333;
--grid-main: #999;
--grid-sub: #e0e0e0;
--axis: #000;
--accent: #ff6f00;
--text-light: #eee;
--c-draw: #2e7d32;
--c-arc: #1565c0;
--c-circle: #6a1b9a;
--c-meas: #ef6c00;
--c-util: #0097a7;
--c-undo: #757575;
--c-del: #d32f2f;
}
body {
margin: 0;
padding: 0;
background: var(--bg-panel);
color: var(--text-light);
font-family: "Segoe UI", Roboto, sans-serif;
height: 100dvh;
width: 100vw;
overflow: hidden;
user-select: none;
-webkit-user-select: none;
overscroll-behavior: none;
touch-action: none;
}
* {
-webkit-tap-highlight-color: transparent;
box-sizing: border-box;
}
/* --- LAYOUTY --- */
#app-layout {
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
position: absolute;
top: 0; left: 0;
}
/* --- CAD CANVAS --- */
#canvas-area {
flex-grow: 1;
background: var(--bg-canvas);
position: relative;
overflow: hidden;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.5);
z-index: 1;
touch-action: none;
}
svg {
width: 100%;
height: 100%;
display: block;
cursor: crosshair;
}
body.helpers-hidden .point-center,
body.helpers-hidden .helper-full-circle,
body.helpers-hidden .helper-radius-line,
body.helpers-hidden .helper-target-tangent {
display: none !important;
}
#panel-area {
flex-shrink: 0;
background: var(--bg-panel);
padding: 8px 8px calc(8px + env(safe-area-inset-bottom)) 8px;
box-shadow: 0 -4px 10px rgba(0, 0, 0, 0.3);
z-index: 10;
overflow-y: auto;
max-height: 45vh;
touch-action: pan-y;
}
@media (orientation: landscape) {
#app-layout { flex-direction: row; }
#panel-area { width: 280px; max-height: 100%; border-left: 1px solid #444; padding-bottom: 100px; }
.panel-grid { grid-template-columns: repeat(2, 1fr); }
}
/* --- CAD STYLES --- */
.panel-grid { display: grid; grid-template-columns: repeat(5, 1fr); gap: 6px; width: 100%; max-width: 700px; margin: 0 auto; }
.menu-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; }
.icon-btn {
background: var(--bg-btn); border: none; border-radius: 10px; aspect-ratio: 1/0.9;
display: flex; flex-direction: column; justify-content: center; align-items: center;
cursor: pointer; color: #ccc; transition: all 0.1s; position: relative; padding: 4px; min-height: 44px;
}
.icon-btn:active { transform: scale(0.95); background: #444; }
.icon-btn.active-mode { background: var(--c-util); color: #fff; box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.5); border: 2px solid #fff; }
.icon-btn i { font-size: 20px; margin-bottom: 4px; }
.icon-btn span { font-size: 9px; font-weight: 600; line-height: 1.1; text-align: center; }
.btn-draw i { color: #4caf50; } .btn-arc i { color: #2196f3; } .btn-circ i { color: #9c27b0; }
.btn-meas i { color: #ff9800; } .btn-util i { color: #00bcd4; }
.btn-del { background: #3e2723; border: 1px solid #4e342e; } .btn-del i { color: #ff5252; }
.btn-trim i { color: #f44336; } .btn-trim.active-mode { background: #d32f2f; border-color: #ff8a80; }
.btn-chamfer i { color: #ffeb3b; } .btn-chamfer.active-mode { background: #fbc02d; color: #000; border-color: #fff; }
.btn-copy { background: #ff9800; color: white; box-shadow: 0 3px 0 #e65100; }
.btn-disabled { opacity: 0.3; pointer-events: none; }
.btn-menu { background: #424242; border: 1px solid #555; } .btn-menu i { color: #fff; }
.btn-export { background: #2e7d32; color: white; } .btn-import { background: #ef6c00; color: white; }
#btn-home { position: absolute; top: 10px; right: 10px; width: 44px; height: 44px; background: #fff; color: #333; border-radius: 8px; border: 2px solid #888; display: flex; justify-content: center; align-items: center; cursor: pointer; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2); z-index: 10; padding: 2px; }
#btn-snap-toggle { position: absolute; top: 10px; right: 64px; width: 40px; height: 40px; background: #fff; color: #333; border-radius: 50%; border: 2px solid #888; display: flex; justify-content: center; align-items: center; font-size: 20px; cursor: pointer; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2); z-index: 10; }
#btn-snap-toggle.snap-off { color: #aaa; border-color: #ccc; background: #f0f0f0; } #btn-snap-toggle.snap-off i { text-decoration: line-through; }
/* --- HUD STYLES --- */
#hud-container {
position: absolute; top: 10px; left: 10px; z-index: 100;
display: flex; gap: 8px; flex-wrap: wrap; /* Umožní zalomení na malých displejích */
pointer-events: none; /* Kliknutí projde skrz prázdná místa */
max-width: calc(100% - 120px); /* Aby nezasahoval do tlačítek vpravo */
}
.hud-panel {
background: rgba(255, 255, 255, 0.95); border: 2px solid #333; border-radius: 8px;
padding: 4px 8px; font-family: 'Consolas', monospace; color: #333;
box-shadow: 0 4px 10px rgba(0,0,0,0.2); pointer-events: auto; cursor: pointer;
display: flex; align-items: center; gap: 8px; transition: 0.2s;
white-space: nowrap; /* Zabrání rozlomení textu uvnitř panelu */
}
.hud-panel:active { transform: scale(0.95); background: #e3f2fd; }
.hud-lbl { font-size: 10px; font-weight: bold; color: #666; vertical-align: top; margin-right: 2px; }
.hud-val { font-size: 15px; font-weight: 900; color: #000; }
.hud-sep { width: 1px; height: 16px; background: #ccc; }
.hud-icon { color: var(--accent); font-size: 12px; }
#hud-snap-info { background: #ffeb3b; color: #000; font-size: 9px; padding: 2px 6px; border-radius: 4px; font-weight: 800; display: none; margin-left: auto; }
#toast-msg {
position: absolute; bottom: 100px; left: 50%; transform: translateX(-50%);
background: rgba(0, 0, 0, 0.85); color: #fff; padding: 12px 24px;
border-radius: 30px; font-size: 16px; font-weight: bold; pointer-events: none;
opacity: 0; transition: opacity 0.3s, bottom 0.3s; z-index: 200;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.5); white-space: nowrap;
}
#toast-msg.show { opacity: 1; bottom: 120px; }
.modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.85); z-index: 100; justify-content: center; align-items: center; backdrop-filter: blur(5px); }
.modal-content { background: #fff; width: 90%; max-width: 350px; max-height: 90vh; border-radius: 16px; border: 1px solid #999; color: #000; display: flex; flex-direction: column; overflow: hidden; box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5); position: relative; }
.modal-header { padding: 15px 20px 10px; border-bottom: 2px solid #eee; flex-shrink: 0; background: #fff; display: flex; justify-content: space-between; align-items: center; }
.modal-header h3 { margin: 0; font-size: 20px; color: #000; font-weight: 800; }
.close-icon { font-size: 24px; color: #555; cursor: pointer; padding: 0 5px; transition: color 0.2s; } .close-icon:hover { color: #d32f2f; }
.modal-body { padding: 15px 20px; overflow-y: auto; flex-grow: 1; background: #fff; }
.modal-footer { padding: 15px 20px; border-top: 2px solid #eee; background: #f8f8f8; flex-shrink: 0; }
.confirm-content { text-align: center; }
.confirm-msg { font-size: 18px; font-weight: bold; margin-bottom: 20px; color: #333; }
.segmented-control { display: flex; width: 100%; margin-bottom: 15px; border: 2px solid #666; border-radius: 8px; overflow: hidden; background: #fff; }
.seg-opt { flex: 1; padding: 12px; text-align: center; cursor: pointer; background: #fff; color: #333; font-weight: bold; font-size: 14px; transition: 0.1s; border-right: 1px solid #ccc; display: flex; align-items: center; justify-content: center; }
.seg-opt:last-child { border-right: none; } .seg-opt:hover { background: #eee; color: #000; }
.seg-opt.active { background: var(--c-arc); color: #fff; text-shadow: 0 1px 1px rgba(0, 0, 0, 0.5); }
.mode-toggle .seg-opt.active { background: var(--c-util); } .tangent-target-toggle .seg-opt.active { background: var(--c-meas); } .circle-toggle .seg-opt.active { background: var(--c-circle); }
.tangent-type-toggle .seg-opt.active { background: #e65100; }
input { width: 100%; padding: 12px; font-size: 20px; text-align: right; font-weight: bold; font-family: "Consolas", monospace; border: 2px solid #777; border-radius: 6px; margin-bottom: 15px; box-sizing: border-box; background: #fff; color: #000; }
input:focus { border-color: var(--c-arc); outline: none; background: #f0f8ff; }
.joypad-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; aspect-ratio: 1/0.8; margin-top: 5px; }
.joy-btn { background: #f0f0f0; border: 2px solid #ccc; border-radius: 8px; color: #222; display: flex; flex-direction: column; justify-content: center; align-items: center; cursor: pointer; box-shadow: 0 3px 0 #bbb; transition: 0.1s; }
.joy-btn:active:not(.disabled) { transform: translateY(2px); box-shadow: 0 1px 0 #bbb; background: var(--accent); color: #fff; }
.joy-btn.disabled { opacity: 0.4; cursor: default; background: #e0e0e0; border-color: #ddd; box-shadow: none; }
.modal-btn-row { display: flex; gap: 10px; width: 100%; flex-wrap: wrap; }
.m-btn { flex: 1; padding: 14px; border: none; border-radius: 8px; font-weight: bold; cursor: pointer; font-size: 14px; text-transform: uppercase; display: flex; align-items: center; justify-content: center; gap: 5px; color: #fff; }
.m-cancel { background: #ddd; color: #000; border: 1px solid #bbb; }
.btn-primary-arc { background: var(--c-arc); box-shadow: 0 3px 0 #0d47a1; }
.btn-primary-circ { background: var(--c-circle); box-shadow: 0 3px 0 #4a148c; }
.btn-primary-draw { background: var(--c-draw); box-shadow: 0 3px 0 #1b5e20; }
.btn-primary-util { background: var(--c-util); box-shadow: 0 3px 0 #006064; }
.chk-row { display: flex; align-items: center; margin-bottom: 15px; background: #e3f2fd; padding: 12px; border-radius: 8px; border: 2px solid #90caf9; cursor: pointer; }
.chk-row input { width: 24px; height: 24px; margin: 0 15px 0 0; }
.arc-tabs { display: flex; border-bottom: 3px solid #eee; margin-bottom: 20px; }
.arc-tab { flex: 1; text-align: center; padding: 12px; cursor: pointer; font-weight: 800; font-size: 15px; color: #888; border-bottom: 3px solid transparent; margin-bottom: -3px; }
.arc-tab.active { color: var(--c-arc); border-bottom-color: var(--c-arc); }
.choice-btn { width: 100%; padding: 12px; margin-bottom: 8px; background: #fff8e1; border: 2px solid #ffecb3; border-radius: 6px; text-align: left; cursor: pointer; font-family: monospace; font-size: 14px; font-weight: bold; color: #000; }
.section-label { font-size: 13px; color: #111; text-transform: uppercase; font-weight: 900; margin-bottom: 6px; display: block; letter-spacing: 0.5px; }
.separator { width: 100%; height: 2px; background: #ddd; margin: 15px 0; }
/* SVG Styl */
.axis-line { stroke: #000; stroke-width: 3px; opacity: 1; vector-effect: non-scaling-stroke; z-index: 10; }
.axis-line-red { stroke: #d32f2f; stroke-width: 3px; opacity: 1; vector-effect: non-scaling-stroke; z-index: 11; }
.grid-line { stroke: #888; stroke-width: 1.5px; vector-effect: non-scaling-stroke; }
.grid-sub-line { stroke: #e0e0e0; stroke-width: 1px; vector-effect: non-scaling-stroke; }
.path-draw { stroke: #00c853; fill: none; stroke-width: 3px; vector-effect: non-scaling-stroke; stroke-linecap: round; stroke-linejoin: round; }
.point-marker { fill: #fff; stroke: var(--accent); vector-effect: non-scaling-stroke; }
.point-current { fill: var(--accent); }
.point-temp { fill: transparent; stroke: #9c27b0; stroke-width: 2px; vector-effect: non-scaling-stroke; }
.point-center { fill: yellow; stroke: #333; stroke-width: 1px; vector-effect: non-scaling-stroke; }
.origin-marker { fill: none; stroke: #00bcd4; stroke-width: 2px; vector-effect: non-scaling-stroke; pointer-events: none; opacity: 0.8; }
.helper-full-circle { fill: none; stroke: rgba(0, 0, 0, 0.4); stroke-width: 1px; stroke-dasharray: 4, 4; vector-effect: non-scaling-stroke; }
.helper-radius-line { stroke: rgba(33, 150, 243, 0.8); stroke-width: 1px; stroke-dasharray: 2, 2; vector-effect: non-scaling-stroke; }
.intersection-marker { fill: none; stroke: #666; stroke-width: 2px; vector-effect: non-scaling-stroke; opacity: 0.7; }
.snap-highlight { fill: none; stroke: #f00; stroke-width: 3px; vector-effect: non-scaling-stroke; pointer-events: none; }
.ortho-guide { stroke: #9c27b0; stroke-width: 2px; stroke-dasharray: 5, 5; vector-effect: non-scaling-stroke; pointer-events: none; }
.measure-line { stroke: #ff9800; stroke-width: 2.5px; stroke-dasharray: 8, 4; vector-effect: non-scaling-stroke; }
.measure-point { fill: #ff9800; vector-effect: non-scaling-stroke; }
.mobile-cursor-crosshair { stroke: #d32f2f; stroke-width: 2px; vector-effect: non-scaling-stroke; pointer-events: none; }
.mobile-finger-pos { fill: rgba(33, 150, 243, 0.3); stroke: #2196f3; stroke-width: 2px; vector-effect: non-scaling-stroke; pointer-events: none; }
.click-area { fill: rgba(255, 255, 255, 0.01); stroke: transparent; cursor: pointer; }
text { paint-order: stroke; stroke: rgba(255, 255, 255, 0.8); stroke-width: 4px; stroke-linejoin: round; vector-effect: non-scaling-stroke; }
.dim-line { stroke: #5d4037; stroke-width: 1.5px; vector-effect: non-scaling-stroke; }
.dim-arrow { fill: #5d4037; vector-effect: non-scaling-stroke; }
.dim-text { fill: #3e2723; font-weight: 900; font-family: "Segoe UI", Roboto, sans-serif; text-anchor: middle; dominant-baseline: middle; vector-effect: non-scaling-stroke; paint-order: stroke; stroke: rgba(255, 255, 255, 0.9); stroke-width: 4px; stroke-linejoin: round; }
</style>
</head>
<body>
<!-- CAD REŽIM -->
<div id="app-layout">
<div id="canvas-area" oncontextmenu="return false;">
<svg id="svgCanvas" preserveAspectRatio="xMidYMid slice">
<g id="worldGroup" transform="scale(1, -1)">
<g id="gridLines"></g><g id="axisGroup"></g><g id="pathGroup"></g><g id="intersectionGroup"></g><g id="dimGroup"></g><g id="measureLayer"></g><g id="snapCursorGroup"></g>
</g>
<g id="textGroup"></g> <g id="mobileCursorGroup"></g>
</svg>
<div id="hud-container">
<div id="coords-hud" class="hud-panel" onclick="copyHudCoords()" title="Zkopírovat pozici kurzoru">
<div><span id="hud-lbl-1" class="hud-lbl">X</span><span class="hud-val" id="hud-x">0.00</span></div><div class="hud-sep"></div><div><span id="hud-lbl-2" class="hud-lbl">Z</span><span class="hud-val" id="hud-z">0.00</span></div><div id="hud-snap-info">SNAP</div>
</div>
<div id="sel-hud" class="hud-panel" style="display:none;" onclick="centerOnSelection()" title="Vycentrovat na bod">
<i class="fas fa-crosshairs hud-icon"></i>
<div><span id="sel-lbl-1" class="hud-lbl">X</span><span class="hud-val" id="sel-x">0.00</span></div><div class="hud-sep"></div><div><span id="sel-lbl-2" class="hud-lbl">Z</span><span class="hud-val" id="sel-z">0.00</span></div>
</div>
</div>
<!-- Dynamický kříž Home -->
<div id="btn-home" onclick="setHomeView()" title="Reset">
<svg viewBox="0 0 40 40" style="width:100%; height:100%; display:block;">
<!-- X axis (black) -->
<line id="icon-axis-x" x1="5" y1="35" x2="35" y2="35" stroke="#333" stroke-width="2" marker-end="url(#arrowhead)" />
<!-- Z axis (red dashed) -->
<line id="icon-axis-z" x1="5" y1="35" x2="5" y2="5" stroke="#d32f2f" stroke-width="2" stroke-dasharray="4,2" marker-end="url(#arrowhead-red)" />
<!-- Labels -->
<text id="icon-lbl-x" x="32" y="32" font-family="sans-serif" font-size="10" font-weight="bold" fill="#333">Z</text>
<text id="icon-lbl-z" x="8" y="10" font-family="sans-serif" font-size="10" font-weight="bold" fill="#d32f2f">X</text>
</svg>
</div>
<div id="btn-snap-toggle" onclick="toggleManualSnap()" title="Magnet"><i id="icon-snap" class="fas fa-magnet"></i></div>
<div id="toast-msg">Zkopírováno</div>
</div>
<div id="panel-area">
<div class="panel-grid">
<button id="btn-draw" class="icon-btn btn-draw" onclick="openJoypad()"><i class="fas fa-minus" style="transform: rotate(-45deg)"></i><span>Úsečka</span></button>
<button id="btn-arc" class="icon-btn btn-arc" onclick="openArcModal()"><i class="fas fa-bezier-curve"></i><span>Rádius</span></button>
<button id="btn-circ" class="icon-btn btn-circ" onclick="openCircleModal()"><i class="fas fa-circle-notch"></i><span>Kruh</span></button>
<button id="btn-chain" class="icon-btn btn-draw" onclick="toggleChainMode()"><i class="fas fa-project-diagram"></i><span>Řetězec</span></button>
<button id="btn-meas" class="icon-btn btn-meas" onclick="openMeasureModal()"><i class="fas fa-ruler-combined"></i><span>Měřit</span></button>
<button id="btn-start-pick" class="icon-btn btn-util" onclick="setMode('PICK_START')"><i class="fas fa-pen-nib"></i><span>Start Bod</span></button>
<button id="btn-trim" class="icon-btn btn-trim" onclick="toggleTrimMode()"><i class="fas fa-cut"></i><span>Oříznout</span></button>
<button id="btn-chamfer" class="icon-btn btn-chamfer" onclick="setMode('CHAMFER')"><i class="fas fa-vector-square" style="transform: rotate(45deg)"></i><span>Rohy</span></button>
<button id="btn-dim" class="icon-btn btn-util" onclick="setMode('MANUAL_DIMENSION')" style="background: #795548; border-color: #8d6e63"><i class="fas fa-arrows-alt-h"></i><span>Kóta</span></button>
<button id="btn-menu" class="icon-btn btn-menu" onclick="openMainMenu()"><i class="fas fa-bars"></i><span>MENU</span></button>
</div>
<div style="margin-top: 15px; text-align: center; font-size: 10px; color: #555;">v19.4 Fixed</div>
</div>
</div>
<!-- MODALS -->
<!-- CUSTOM CONFIRM (To fix Sandbox issues) -->
<div id="modal-confirm" class="modal" style="z-index: 9999;">
<div class="modal-content" style="max-width: 300px;">
<div class="modal-body confirm-content">
<div class="confirm-msg" id="confirm-msg">Otázka?</div>
<div class="modal-btn-row">
<button class="m-btn m-cancel" onclick="closeConfirm()">Ne</button>
<button class="m-btn btn-primary-util" onclick="confirmYes()">Ano</button>
</div>
</div>
</div>
</div>
<div id="modal-main-menu" class="modal"><div class="modal-content"><div class="modal-header"><h3>Nástroje</h3><span class="close-icon" onclick="closeModals()"><i class="fas fa-times"></i></span></div><div class="modal-body"><label class="section-label" style="margin-top: 0">Editační Nástroje</label><div class="menu-grid"><button class="icon-btn btn-util" onclick="fitToScreen()"><i class="fas fa-compress-arrows-alt"></i><span>Centrovat</span></button><button id="btn-machine-toggle" class="icon-btn btn-util" style="background: #4527a0" onclick="toggleMachineType()"><i class="fas fa-exchange-alt"></i><span>Karusel</span></button><button id="btn-toggle-dia" class="icon-btn btn-util" onclick="toggleDiameterMode()"><i class="fas fa-expand-arrows-alt"></i><span>Ø Průměr</span></button><button id="btn-helpers" class="icon-btn btn-util" onclick="toggleHelpers()"><i class="fas fa-eye-slash"></i><span>Pomocné</span></button><button id="btn-undo" class="icon-btn btn-disabled" onclick="undoLastMove()"><i class="fas fa-undo"></i><span>Zpět</span></button><button id="btn-redo" class="icon-btn btn-disabled" onclick="redoLastMove()"><i class="fas fa-redo"></i><span>Vpřed</span></button><button class="icon-btn btn-del" onclick="confirmClearAll()"><i class="fas fa-trash-alt"></i><span>Smazat</span></button><button class="icon-btn btn-del" style="background: #5d4037" onclick="clearDimensions()"><i class="fas fa-eraser"></i><span>Smazat Kóty</span></button><button class="icon-btn btn-util" style="background: #e65100; border-color: #ff9800" onclick="autoDimensionAll()"><i class="fas fa-ruler-combined"></i><span>Auto Kóty</span></button></div><div class="separator"></div><label class="section-label">Data</label><div class="menu-grid"><button class="icon-btn btn-export" onclick="saveProjectJSON()" style="background: #43a047"><i class="fas fa-save"></i><span>Uložit Projekt</span></button><button class="icon-btn btn-import" onclick="triggerLoadJSON()" style="background: #fb8c00"><i class="fas fa-folder-open"></i><span>Načíst Projekt</span></button><button class="icon-btn btn-util" style="background: #00796b" onclick="setMode('PICK_MOVE_ORIGIN')"><i class="fas fa-arrows-alt"></i><span>Posunout Model</span></button><button class="icon-btn btn-util" style="background: #004d40" onclick="openAlignModal()"><i class="fas fa-sync-alt"></i><span>Srovnat Rotaci</span></button><button class="icon-btn btn-util" style="background: #283593" onclick="openSimDraha()"><i class="fas fa-play-circle"></i><span>CAM / G-Code</span></button><button class="icon-btn btn-util" style="background: #5e35b1" onclick="openSimDxf()"><i class="fas fa-file-import"></i><span>Konvertor DXF</span></button></div></div><div class="modal-footer"><button class="m-btn m-cancel" onclick="closeModals()">Zavřít</button></div></div></div>
<input type="file" id="json-loader" style="display: none" accept=".json" onchange="loadJSON(this)" />
<div id="modal-align" class="modal">
<div class="modal-content">
<div class="modal-header"><h3>Srovnat Model</h3><span class="close-icon" onclick="closeModals()"><i class="fas fa-times"></i></span></div>
<div class="modal-body">
<button class="m-btn btn-primary-util" style="margin-bottom: 10px; background: #004d40" onclick="setMode('PICK_ALIGN_HORIZ')"><i class="fas fa-arrows-alt-h"></i> Srovnat Vodorovně</button>
<p style="font-size: 12px; color: #666; margin-bottom: 20px;">Vyberte 2 body na modelu. Model se natočí tak, aby tyto body ležely v rovině.</p>
<button class="m-btn btn-primary-util" style="background: #006064; margin-bottom: 10px;" onclick="setMode('PICK_MOVE_ORIGIN')"><i class="fas fa-arrows-alt"></i> Přesunout Bod na Bod</button>
<p style="font-size: 12px; color: #666; margin-bottom: 20px;">Vyberte bod na modelu a poté cílové místo v mapě.</p>
<div class="separator"></div>
<button class="m-btn btn-primary-util" style="background: #bf360c" onclick="rotateModel90()"><i class="fas fa-sync-alt"></i> Otočit o 90°</button>
<p style="font-size: 12px; color: #666; margin-top: 10px;">Otočí celý model kolem jeho středu.</p>
</div>
</div>
</div>
<div id="modal-joypad" class="modal"><div class="modal-content"><div class="modal-header"><h3>Vyberte směr</h3><span class="close-icon" onclick="closeModals()"><i class="fas fa-times"></i></span></div><div class="modal-body"><div class="joypad-grid"><div class="joy-btn" onclick="prepMove('UL')"><i class="fas fa-arrow-up" style="transform: rotate(-45deg)"></i><span class="joy-desc">Kužel</span></div><div class="joy-btn" onclick="prepMove('U')"><i class="fas fa-arrow-up"></i><span class="joy-desc">Z+</span></div><div class="joy-btn" onclick="prepMove('UR')"><i class="fas fa-arrow-up" style="transform: rotate(45deg)"></i><span class="joy-desc">Kužel</span></div><div class="joy-btn" onclick="prepMove('L')"><i class="fas fa-arrow-left"></i><span class="joy-desc">X-</span></div><div id="btn-joy-tangent" class="joy-btn" onclick="prepMove('TANGENT')"><i class="fas fa-long-arrow-alt-up" style="transform: rotate(45deg)"></i><span class="joy-desc">TEČNA</span></div><div class="joy-btn" onclick="prepMove('R')"><i class="fas fa-arrow-right"></i><span class="joy-desc">X+</span></div><div class="joy-btn" onclick="prepMove('DL')"><i class="fas fa-arrow-down" style="transform: rotate(45deg)"></i><span class="joy-desc">Kužel</span></div><div class="joy-btn" onclick="prepMove('D')"><i class="fas fa-arrow-down"></i><span class="joy-desc">Z-</span></div><div class="joy-btn" onclick="prepMove('DR')"><i class="fas fa-arrow-down" style="transform: rotate(-45deg)"></i><span class="joy-desc">Kužel</span></div></div><div style="margin-top: 15px"><button class="m-btn btn-primary-util" onclick="setMode('PICK_TARGET_INP')"><i class="fas fa-crosshairs"></i> Vybrat bod na mapě</button><button class="m-btn btn-primary-draw" style="margin-top: 8px" onclick="closeModals(); setMode('CHAIN')"><i class="fas fa-project-diagram"></i> Pokračovat Řetězcem</button></div></div></div></div>
<div id="modal-chamfer" class="modal"><div class="modal-content"><div class="modal-header"><h3>Úprava Rohu</h3><span class="close-icon" onclick="closeModals()"><i class="fas fa-times"></i></span></div><div class="modal-body"><label class="section-label">Typ úpravy:</label><div class="segmented-control"><div class="seg-opt active" id="chamfer-type-c" onclick="setChamferType('C')">Sražení (C)</div><div class="seg-opt" id="chamfer-type-r" onclick="setChamferType('R')">Rádius (R)</div></div><label class="section-label">Velikost (mm):</label><input type="text" id="chamfer-val" placeholder="Velikost C nebo R" inputmode="decimal" /></div><div class="modal-footer"><div class="modal-btn-row"><button class="m-btn m-cancel" onclick="closeModals()">Zrušit</button><button class="m-btn btn-primary-draw" onclick="applyChamfer()">Provést</button></div></div></div></div>
<div id="modal-input" class="modal"><div class="modal-content"><div class="modal-header"><h3 id="input-title">Parametry pohybu</h3><span class="close-icon" onclick="closeModals()"><i class="fas fa-times"></i></span></div><div class="modal-body"><label class="section-label">Délka pohybu (mm):</label><input type="text" id="inp-len" placeholder="Např. 50" inputmode="decimal" /><div class="separator"></div><div id="grp-x"><label id="lbl-inp-x" class="section-label">Cílové X:</label><input type="text" id="inp-x" placeholder="Prázdné = beze změny" inputmode="decimal" /></div><div id="grp-z"><label class="section-label">Cílové Z:</label><input type="text" id="inp-z" placeholder="Prázdné = beze změny" inputmode="decimal" /></div><div id="grp-angle"><div class="separator"></div><label class="section-label">Úhel (°):</label><input type="text" id="inp-angle" placeholder="Úhel sklonu" inputmode="decimal" /><div class="chk-row" onclick="$('chk-rel-angle').click()"><input type="checkbox" id="chk-rel-angle" onclick="event.stopPropagation()" /><label for="chk-rel-angle">Úhel od předchozí čáry</label></div></div><button id="btn-pick-target" class="m-btn btn-primary-util" style="margin-top: 10px; font-size: 12px; padding: 8px;" onclick="setMode('PICK_TARGET_INP')"><i class="fas fa-crosshairs"></i> Vybrat bod na mapě</button></div><div class="modal-footer"><div class="modal-btn-row"><button class="m-btn m-cancel" onclick="openJoypad()">Zpět</button><button id="btn-commit-move" class="m-btn btn-primary-draw" onclick="commitMove()">Vykreslit</button></div></div></div></div>
<div id="modal-arc" class="modal"><div class="modal-content"><div class="modal-header"><h3>Radius</h3><span class="close-icon" onclick="closeModals()"><i class="fas fa-times"></i></span><div class="arc-tabs"><div class="arc-tab active" id="tab-r" onclick="switchArcMethod('R')">Rádius</div><div class="arc-tab" id="tab-ik" onclick="switchArcMethod('IK')">Střed</div></div></div><div class="modal-body"><div class="segmented-control"><div class="seg-opt active" id="seg-g2" onclick="setArcDir(true)">G2</div><div class="seg-opt" id="seg-g3" onclick="setArcDir(false)">G3</div></div><div id="method-r"><div class="segmented-control tangent-type-toggle"><div class="seg-opt active" id="type-norm" onclick="setArcMode('NORM')">Běžný</div><div class="seg-opt" id="type-tan" onclick="setArcMode('TAN')">Tečna</div><div class="seg-opt" id="type-back" onclick="setArcMode('BACK')">Zpátky</div></div><label id="lbl-arc-r" class="section-label">Rádius:</label><input type="text" id="arc-r" inputmode="decimal" placeholder="Auto pokud je Tangenta" /></div><div id="method-ik" style="display: none"><div class="segmented-control mode-toggle"><div class="seg-opt active" id="ik-abs-btn" onclick="toggleIKMode(false)">Absolutní</div><div class="seg-opt" id="ik-inc-btn" onclick="toggleIKMode(true)">Přírůstkové</div></div><label id="lbl-center-x" class="section-label">Střed I:</label><input type="text" id="center-x" inputmode="decimal" /><label class="section-label">Střed K:</label><input type="text" id="center-z" inputmode="decimal" /><button class="m-btn btn-primary-util" style="padding: 8px; margin-top: 5px; font-size: 12px; margin-bottom: 15px;" onclick="setMode('PICK_ARC_CENTER')"><i class="fas fa-crosshairs"></i> Vybrat Střed na mapě</button><div class="separator"></div><label class="section-label">Cíl X:</label><input type="text" id="ik-target-x" inputmode="decimal" /><label class="section-label">Cíl Z:</label><input type="text" id="ik-target-z" inputmode="decimal" /><button class="m-btn btn-primary-util" style="padding: 8px; margin-top: 5px; font-size: 12px; margin-bottom: 5px;" onclick="setMode('PICK_ARC_TARGET_IK')"><i class="fas fa-crosshairs"></i> Vybrat Cíl na mapě</button><label class="section-label">Úhel:</label><input type="text" id="ik-target-angle" inputmode="decimal" /><div class="chk-row"><input type="checkbox" id="chk-ik-long-arc" /><label for="chk-ik-long-arc">Delší oblouk</label></div></div><div id="arc-targets"><div id="tangent-target-selector" style="display: none"><label class="section-label">Cíl definován jako:</label><div class="segmented-control tangent-target-toggle"><div class="seg-opt active" id="target-coord-btn" onclick="setTangentTarget('coord')">X / Z</div><div class="seg-opt" id="target-cone-btn" onclick="setTangentTarget('cone')">Úhel</div></div></div><div id="target-coord-inputs"><label id="lbl-arc-x" class="section-label">Cíl X:</label><input type="text" id="arc-x" inputmode="decimal" /><label class="section-label">Cíl Z:</label><input type="text" id="arc-z" inputmode="decimal" /><button class="m-btn btn-primary-util" style="padding: 8px; margin-top: 5px; font-size: 12px" onclick="setMode('PICK_ARC_TARGET')"><i class="fas fa-crosshairs"></i> Vybrat Cíl na mapě</button></div><div id="target-cone-input" style="display: none"><label class="section-label">Úhel rozevření (°):</label><input type="text" id="arc-cone-angle" inputmode="decimal" /></div></div></div><div class="modal-footer"><div class="modal-btn-row"><button class="m-btn m-cancel" onclick="closeModals()">Zrušit</button><button class="m-btn btn-primary-arc" onclick="commitArc()">Vykreslit</button></div></div></div></div>
<div id="modal-circle" class="modal"><div class="modal-content"><div class="modal-header"><h3>Celá Kružnice</h3><span class="close-icon" onclick="closeModals()"><i class="fas fa-times"></i></span><div class="arc-tabs"><div class="arc-tab active" id="tab-cr" onclick="setCircTab('CR')">Střed+R</div><div class="arc-tab" id="tab-2p" onclick="setCircTab('2P')">2 Body + R</div><div class="arc-tab" id="tab-3p" onclick="setCircTab('3P')">3 Body</div></div></div><div class="modal-body"><div id="circ-cr"><label class="section-label">Velikost zadat jako:</label><div class="segmented-control circle-toggle"><div class="seg-opt active" id="circ-rad-btn" onclick="setCircleMode('R')">Rádius (R)</div><div class="seg-opt" id="circ-dia-btn" onclick="setCircleMode('D')">Průměr (D)</div></div><label id="lbl-circ-val" class="section-label">Hodnota R:</label><input type="text" id="circ-val" placeholder="Zadejte velikost" inputmode="decimal" /><div class="separator"></div><label class="section-label" style="color: #6a1b9a">Souřadnice Středu:</label><label id="lbl-circ-cx" class="section-label">Střed X:</label><input type="text" id="circ-cx" placeholder="Absolutní X" inputmode="decimal" /><label class="section-label">Střed Z:</label><input type="text" id="circ-cz" placeholder="Absolutní Z" inputmode="decimal" /><button class="m-btn btn-primary-util" style="padding: 8px; margin-top: 5px; font-size: 12px" onclick="setMode('PICK_CIRCLE_CENTER')"><i class="fas fa-crosshairs"></i> Vybrat Střed na mapě</button></div><div id="circ-2p" style="display: none"><label class="section-label">Rádius:</label><input type="text" id="circ-2p-r" inputmode="decimal" /><button class="m-btn btn-primary-util" style="margin-bottom: 10px" onclick="setMode('PICK_CIRC_2P')"><i class="fas fa-mouse-pointer"></i> Vybrat 2 Body / Úsečky</button><div class="chk-row" style="margin-top: 10px" onclick="$('chk-circ-alt').click()"><input type="checkbox" id="chk-circ-alt" onclick="event.stopPropagation()" /><label for="chk-circ-alt">Varianta 1 / Varianta 2</label></div><p style="font-size: 12px; color: #555">Vyberte 2 body nebo 2 úsečky. V případě úseček se vypočítá tečná kružnice (Fillet).</p></div><div id="circ-3p" style="display: none"><button class="m-btn btn-primary-util" onclick="setMode('PICK_CIRC_3P')"><i class="fas fa-mouse-pointer"></i> Vybrat 3 Body</button><p style="font-size: 12px; color: #555; margin-top: 10px">Postupně vyberte 3 body v mapě.</p></div></div><div class="modal-footer"><div class="modal-btn-row"><button class="m-btn m-cancel" onclick="closeModals()">Zrušit</button><button class="m-btn btn-primary-circ" onclick="commitCircle()">Vykreslit</button></div></div></div></div>
<div id="modal-start" class="modal"><div class="modal-content"><div class="modal-header"><h3>Nový Bod / Info</h3><span class="close-icon" onclick="closeModals()"><i class="fas fa-times"></i></span></div><div class="modal-body"><label id="lbl-start-x" class="section-label">X:</label><input type="text" id="start-x" inputmode="decimal" /><label class="section-label">Z:</label><input type="text" id="start-z" inputmode="decimal" /><div style="margin-top: 10px; text-align: center"><button class="m-btn btn-copy" onclick="copyFromModal()"><i class="fas fa-copy"></i> KOPÍROVAT X.. Z..</button></div><div class="separator"></div><label class="section-label">Co udělat dál?</label></div><div class="modal-footer"><div class="modal-btn-row" style="flex-wrap: wrap"><button class="m-btn btn-primary-util" style="background: #757575" onclick="actionMoveOnly()"><i class="fas fa-map-marker-alt"></i> Jen Bod</button><button class="m-btn btn-primary-draw" onclick="actionMoveAndLine()"><i class="fas fa-minus" style="transform: rotate(-45deg)"></i> Úsečka</button><button class="m-btn btn-primary-draw" onclick="actionChain()"><i class="fas fa-project-diagram"></i> Řetězec</button><button class="m-btn btn-primary-circ" onclick="actionCircleCenter()"><i class="fas fa-circle-notch"></i> Kruh</button></div></div></div></div>
<div id="modal-measure" class="modal"><div class="modal-content"><div class="modal-header"><h3>Měření</h3><span class="close-icon" onclick="closeModals()"><i class="fas fa-times"></i></span></div><div class="modal-body"><div class="segmented-control" style="border-color: var(--c-meas)"><div class="seg-opt active" id="meas-dist-btn" onclick="selectMeasure('distance')" style="background: var(--c-meas); color: white">2 Body</div><div class="seg-opt" id="meas-line-btn" onclick="selectMeasure('line')" style="background: #795548; color: white">Úsečka</div></div><div class="segmented-control" style="border-color: var(--c-meas); margin-top: -5px;"><div class="seg-opt" id="meas-angle-btn" onclick="selectMeasure('angle')">Úhel</div><div class="seg-opt" id="meas-coord-btn" onclick="selectMeasure('radius')">Rádius</div></div><p id="measure-instructions" style="text-align: center; font-weight: bold">Vyberte nástroj.</p><div id="measure-result" style="display: none; padding: 10px; background: #fff3e0; margin-top: 10px; border-radius: 4px;"><div id="measure-output" style="font-family: monospace; font-size: 14px; font-weight: bold"></div><button class="m-btn btn-primary-util" style="margin-top: 10px; background: #795548" onclick="addDimension()"><i class="fas fa-ruler"></i> Vložit Kótu</button></div></div><div class="modal-footer"><div class="modal-btn-row"><button class="m-btn m-cancel" onclick="stopMeasure()">Ukončit</button></div></div></div></div>
<script>
const $ = (id) => document.getElementById(id);
const safeStorage = {
getItem: (key) => { try { return localStorage.getItem(key); } catch(e) { return null; } },
setItem: (key, val) => { try { localStorage.setItem(key, val); } catch(e) {} }
};
const MAX_HISTORY = 50;
const State = {
mode: "IDLE", measureMode: null, points: [{ x: 0, z: 0, break: false, type: "line", id: 0 }],
history: [], redo: [], vb: { x: -50, y: -600, w: 800, h: 800 },
initialVb: { x: -50, y: -600, w: 800, h: 800 },
isDiameter: safeStorage.getItem("cnc_diameter_mode") === "true", // Default to Radius (false)
machineType: safeStorage.getItem("cnc_machine_type") || 'SOUSTRUH', // Default to Soustruh
activeIntersections: [], measurePoints: [], chamferIdx: -1,
touch: { active: false, x: 0, y: 0, timer: null, pinchDist: 0 },
tempCenter: null, dimensions: [], lastMeasured: null, dimP1: null,
intersectionNoticeShown: false, isDragging: false, tempPickList: [],
manualSnap: true, moveOrigin: null, lastSel: null
};
let pointIdCounter = 1;
let currentDir = "", isG2 = true, arcMethod = "R", isIncIK = false, tanTarget = "coord", circMode = "R", chamferType = "C", circTab = "CR";
let arcMode = 'NORM'; // NORM, TAN, BACK
let lastVirtualSnap = null;
let confirmCallback = null;
const LONG_PRESS = 600, TOUCH_OFFSET_Y = 100, DRAG_THRESHOLD = 5;
const els = { svg: $("svgCanvas"), grid: $("gridLines"), axis: $("axisGroup"), text: $("textGroup"), path: $("pathGroup"), intr: $("intersectionGroup"), dim: $("dimGroup"), meas: $("measureLayer"), snap: $("snapCursorGroup"), mob: $("mobileCursorGroup") };
const cachedControls = { btnUndo: $("btn-undo"), btnRedo: $("btn-redo") };
let updatePathScheduled = false;
function scheduleUpdatePath() { if (updatePathScheduled) return; updatePathScheduled = true; requestAnimationFrame(() => { updatePathScheduled = false; updatePath(); }); }
// --- CUSTOM CONFIRM (To fix Sandbox issues) ---
function openConfirm(msg, cb) {
$("confirm-msg").innerText = msg;
$("modal-confirm").style.display = "flex";
confirmCallback = cb;
}
function closeConfirm() {
$("modal-confirm").style.display = "none";
confirmCallback = null;
}
function confirmYes() {
if(confirmCallback) confirmCallback();
closeConfirm();
}
// --- MACHINE TOGGLE ---
function toggleMachineType() {
State.machineType = State.machineType === 'KARUSEL' ? 'SOUSTRUH' : 'KARUSEL';
safeStorage.setItem("cnc_machine_type", State.machineType);
updateMachineUI();
setHomeView();
showToast(`Režim: ${State.machineType}`);
}
function updateMachineUI() {
const isKarusel = State.machineType === 'KARUSEL';
$("btn-machine-toggle").querySelector("span").innerText = isKarusel ? "Karusel" : "Soustruh";
if (isKarusel) { $("hud-lbl-1").innerText = "X"; $("hud-lbl-2").innerText = "Z"; $("sel-lbl-1").innerText = "X"; $("sel-lbl-2").innerText = "Z"; }
else { $("hud-lbl-1").innerText = "Z"; $("hud-lbl-2").innerText = "X"; $("sel-lbl-1").innerText = "Z"; $("sel-lbl-2").innerText = "X"; }
// Update Home Icon
$("icon-axis-z").setAttribute("x1", isKarusel ? "5" : "35");
$("icon-axis-z").setAttribute("y1", isKarusel ? "35" : "5");
$("icon-axis-z").setAttribute("x2", isKarusel ? "5" : "5");
$("icon-axis-z").setAttribute("y2", isKarusel ? "5" : "5");
$("icon-axis-x").setAttribute("x1", isKarusel ? "5" : "5");
$("icon-axis-x").setAttribute("y1", isKarusel ? "35" : "5");
$("icon-axis-x").setAttribute("x2", isKarusel ? "35" : "35");
$("icon-axis-x").setAttribute("y2", isKarusel ? "35" : "35");
$("icon-lbl-x").textContent = isKarusel ? "X" : "Z";
$("icon-lbl-x").setAttribute("fill", isKarusel ? "#333" : "#d32f2f");
$("icon-lbl-z").textContent = isKarusel ? "Z" : "X";
$("icon-lbl-z").setAttribute("fill", isKarusel ? "#d32f2f" : "#333");
toggleDiameterMode(true); // Call to update labels without toggling
requestRender();
}
// --- COORDINATES ---
function getScreenX(p) { return State.machineType === 'KARUSEL' ? p.x : p.z; }
function getScreenY(p) { return State.machineType === 'KARUSEL' ? p.z : p.x; }
function getWorldFromScreen(sx, sy) {
return State.machineType === 'KARUSEL' ? {x: sx, z: sy} : {x: sy, z: sx};
}
function openSimDraha() {
window.open('SimDraha.html', '_blank');
}
function openSimDxf() {
window.open('SimDxf.html', '_blank');
}
// --- FILES ---
function downloadFile(content, fileName, mimeType) { const a = document.createElement("a"); const blob = new Blob([content], { type: mimeType }); a.href = URL.createObjectURL(blob); a.download = fileName; a.click(); URL.revokeObjectURL(a.href); }
function saveProjectJSON() {
if (State.points.length < 1) { showToast("Žádná data"); return; }
const data = JSON.stringify({
version: "1.0",
timestamp: new Date().toISOString(),
machineType: State.machineType,
isDiameter: State.isDiameter,
points: State.points,
dimensions: State.dimensions
}, null, 2);
downloadFile(data, "projekt_cnc.json", "application/json");
showToast("Projekt uložen");
closeModals();
}
function triggerLoadJSON() { $("json-loader").click(); }
function loadJSON(input) {
const file = input.files[0]; if (!file) return;
const reader = new FileReader();
reader.onload = function(e) {
try {
const data = JSON.parse(e.target.result);
if(data.points && Array.isArray(data.points)) {
saveHistory();
State.points = data.points;
State.dimensions = data.dimensions || [];
if(data.machineType) State.machineType = data.machineType;
if(typeof data.isDiameter === 'boolean') State.isDiameter = data.isDiameter;
safeStorage.setItem("cnc_machine_type", State.machineType);
safeStorage.setItem("cnc_diameter_mode", State.isDiameter);
updateMachineUI();
pointIdCounter = State.points.reduce((max, p) => Math.max(max, p.id || 0), 0) + 1;
fitToScreen();
updatePath();
showToast("Projekt načten");
} else {
alert("Neplatný formát souboru.");
}
} catch(err) {
console.error(err);
alert("Chyba při čtení souboru.");
}
closeModals();
};
reader.readAsText(file);
input.value = "";
}
// --- UTILS ---
function svgEl(tag, attrs) { const el = document.createElementNS("http://www.w3.org/2000/svg", tag); for (let k in attrs) k === "textContent" ? (el.textContent = attrs[k]) : el.setAttribute(k, attrs[k]); return el; }
function dist(p1, p2) { const z1 = p1.z !== undefined ? p1.z : p1.y, z2 = p2.z !== undefined ? p2.z : p2.y; return Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(z2 - z1, 2)); }
function showToast(msg) { const t = $("toast-msg"); t.innerText = msg; t.classList.add("show"); setTimeout(() => t.classList.remove("show"), 2000); }
function getNum(id) { const el = $(id); if (!el) return NaN; return parseFloat(el.value.replace(",", ".")); }
function formatVal(v) { return (State.isDiameter ? v * 2 : v).toFixed(3); }
function copyToClipboard(text) { if (navigator.clipboard && navigator.clipboard.writeText) navigator.clipboard.writeText(text).then(() => showToast("Zkopírováno: " + text)).catch(() => fallbackCopy(text)); else fallbackCopy(text); }
function fallbackCopy(text) { const ta = document.createElement("textarea"); ta.value = text; ta.style.position = "fixed"; document.body.appendChild(ta); ta.focus(); ta.select(); try { document.execCommand("copy"); showToast("Zkopírováno: " + text); } catch (e) {} document.body.removeChild(ta); }
function copyHudCoords() { copyToClipboard(`X${$("hud-x").innerText} Z${$("hud-z").innerText}`); }
function copyFromModal() { copyToClipboard(`X${$("start-x").value} Z${$("start-z").value}`); }
// --- HISTORY ---
function updateHistory() { cachedControls.btnUndo && cachedControls.btnUndo.classList.toggle("btn-disabled", !State.history.length); cachedControls.btnRedo && cachedControls.btnRedo.classList.toggle("btn-disabled", !State.redo.length); }
function saveHistory() {
if (State.points.length) {
if(State.history.length >= MAX_HISTORY) State.history.shift();
State.history.push(JSON.parse(JSON.stringify({ points: State.points, dimensions: State.dimensions })));
State.redo = [];
updateHistory();
}
}
function undoLastMove() { if (!State.history.length) return; State.redo.push(JSON.parse(JSON.stringify({ points: State.points, dimensions: State.dimensions }))); const prev = State.history.pop(); State.points = prev.points; State.dimensions = prev.dimensions || []; pointIdCounter = State.points.reduce((max, p) => Math.max(max, p.id || 0), 0) + 1; updatePath(); if (State.points.length) centerViewOnPoint(State.points[State.points.length - 1]); updateHistory(); State.lastMeasured = null; State.dimP1 = null; stopMeasure(true); }
function redoLastMove() { if (!State.redo.length) return; State.history.push(JSON.parse(JSON.stringify({ points: State.points, dimensions: State.dimensions }))); const next = State.redo.pop(); State.points = next.points; State.dimensions = next.dimensions || []; pointIdCounter = State.points.reduce((max, p) => Math.max(max, p.id || 0), 0) + 1; updatePath(); if (State.points.length) centerViewOnPoint(State.points[State.points.length - 1]); updateHistory(); }
// --- MODES ---
function setMode(mode, keepSelection = false) {
State.mode = mode; State.tempCenter = null; State.dimP1 = null;
if(!keepSelection) State.tempPickList = [];
["btn-trim", "btn-chamfer", "btn-start-pick", "btn-draw", "btn-arc", "btn-circ", "btn-dim", "btn-chain"].forEach((id) => { const el = $(id); if (el) el.classList.remove("active-mode"); });
$("measure-result").style.display = "none";
if (mode === "IDLE") return;
const setActive = (id) => { const el = $(id); if (el) el.classList.add("active-mode"); };
if (mode === "TRIM") { setActive("btn-trim"); showToast("Klikni pro smazání/oříznutí"); }
else if (mode === "CHAMFER") { setActive("btn-chamfer"); showToast("Rohy: Klikněte na vrchol"); }
else if (mode === "PICK_START") { setActive("btn-start-pick"); showToast("Vyberte startovní bod"); }
else if (mode === "PICK_TARGET_INP") { closeModals(); setActive("btn-draw"); showToast("Vyberte cíl"); }
else if (mode === "CHAIN") { setActive("btn-chain"); showToast("Režim Řetězec: Klikejte body"); }
else if (mode === "PICK_ARC_TARGET" || mode === "PICK_ARC_TARGET_IK") { closeModals(); setActive("btn-arc"); showToast("Vyberte cíl oblouku"); }
else if (mode === "PICK_CIRCLE_CENTER") { closeModals(); setActive("btn-circ"); showToast("Vyberte střed"); }
else if (mode === "PICK_CIRC_2P") { closeModals(); setActive("btn-circ"); showToast("Vyberte 2 body nebo úsečky"); }
else if (mode === "PICK_CIRC_3P") { closeModals(); setActive("btn-circ"); showToast("Vyberte 3 body"); }
else if (mode === "PICK_ARC_CENTER") { closeModals(); setActive("btn-arc"); showToast("Vyberte střed oblouku"); }
else if (mode === "MANUAL_DIMENSION") { setActive("btn-dim"); showToast("Klikni na úsečku, rádius nebo 2 body"); }
else if (mode === "PICK_MOVE_ORIGIN") { closeModals(); showToast("Vyberte referenční bod na modelu"); }
else if (mode === "PICK_MOVE_DEST") { closeModals(); $("input-title").innerText = "Cílová poloha"; $("btn-pick-target").style.display = "none"; $("btn-commit-move").onclick = commitShift; $("modal-input").style.display = "flex"; $("grp-angle").style.display = "none"; $("inp-len").style.display = "none"; $("inp-x").value = "0"; $("inp-z").value = "0"; $("inp-x").focus(); }
else if (mode === "PICK_ALIGN_HORIZ") { closeModals(); showToast("Vyberte 2 body pro srovnání do roviny"); }
if (["TRIM", "CHAMFER", "PICK_START", "PICK_MOVE_ORIGIN", "PICK_ALIGN_HORIZ"].includes(mode)) stopMeasure(false);
if (mode === "TRIM") scheduleUpdatePath();
}
function setTangentTarget(val) {
tanTarget = val;
$("target-coord-btn").classList.toggle("active", val === "coord");
$("target-cone-btn").classList.toggle("active", val === "cone");
if (val === "coord") {
$("target-coord-inputs").style.display = "block";
$("target-cone-input").style.display = "none";
$("lbl-arc-r").innerText = "Rádius:";
if(arcMode === 'TAN' || arcMode === 'BACK') {
$("arc-r").disabled = true;
$("arc-r").placeholder = "Dopočítá se";
}
} else {
$("target-coord-inputs").style.display = "none";
$("target-cone-input").style.display = "block";
$("arc-r").disabled = false;
$("arc-r").placeholder = "Zadejte R";
$("lbl-arc-r").innerText = "Rádius (povinné):";
}
}
function setArcMode(mode) {
arcMode = mode;
$("type-norm").classList.toggle("active", mode === 'NORM');
$("type-tan").classList.toggle("active", mode === 'TAN');
$("type-back").classList.toggle("active", mode === 'BACK');
if(mode === 'NORM') {
$("tangent-target-selector").style.display = "none";
$("target-coord-inputs").style.display = "block";
$("target-cone-input").style.display = "none";
$("arc-r").disabled = false;
$("arc-r").placeholder = "";
$("lbl-arc-r").innerText = "Rádius:";
} else {
$("tangent-target-selector").style.display = "block";
setTangentTarget(tanTarget);
}
}
function toggleTrimMode() { if(State.mode === "TRIM") setMode("IDLE"); else setMode("TRIM"); }
function toggleChainMode() { if(State.mode === "CHAIN") setMode("IDLE"); else setMode("CHAIN"); }
function toggleManualSnap() { State.manualSnap = !State.manualSnap; $("btn-snap-toggle").classList.toggle("snap-off", !State.manualSnap); showToast(State.manualSnap ? "Magnet ZAPNUT" : "Magnet VYPNUT"); }
// --- GEOMETRY ---
function calculateIntersection(p1, p2, p3, p4) { const d = (p1.x - p2.x) * (p3.z - p4.z) - (p1.z - p2.z) * (p3.x - p4.x); if (d === 0) return null; const t = ((p1.x - p3.x) * (p3.z - p4.z) - (p1.z - p3.z) * (p3.x - p4.x)) / d; const u = -((p1.x - p2.x) * (p1.z - p3.z) - (p1.z - p2.z) * (p1.x - p3.x)) / d; if (t >= 0 && t <= 1 && u >= 0 && u <= 1) return { x: p1.x + t * (p2.x - p1.x), z: p1.z + t * (p2.z - p1.z) }; return null; }
function getClosestOnSeg(pWorld, p1, p2) {
const pZ = pWorld.z !== undefined ? pWorld.z : pWorld.y;
if (p2.type !== "arc") { const dx = p2.x - p1.x, dz = p2.z - p1.z, l2 = dx * dx + dz * dz; if (l2 === 0) return { x: p1.x, z: p1.z, dist: dist(pWorld, p1) }; let t = Math.max(0, Math.min(1, ((pWorld.x - p1.x) * dx + (pZ - p1.z) * dz) / l2)); return { x: p1.x + t * dx, z: p1.z + t * dz, dist: Math.hypot(pWorld.x - (p1.x + t * dx), pZ - (p1.z + t * dz)) }; }
else { const dx = pWorld.x - p2.cx, dz = pZ - p2.cz, dCenter = Math.sqrt(dx * dx + dz * dz); return { x: p2.cx + (dx / dCenter) * p2.r, z: p2.cz + (dz / dCenter) * p2.r, dist: Math.abs(dCenter - p2.r) }; }
}
function handleMeasureClick(p, isLine) {
const idx = (p.index !== undefined) ? p.index : State.points.indexOf(p);
if (isLine && State.measureMode === "line") {
const pStart = State.points[idx], pEnd = State.points[idx+1];
const dx = pEnd.x - pStart.x, dz = pEnd.z - pStart.z, distVal = Math.sqrt(dx*dx + dz*dz);
State.lastMeasured = { type: "dist", p1: {x: pStart.x, z: pStart.z}, p2: {x: pEnd.x, z: pEnd.z}, val: distVal.toFixed(3) };
showMeasureResult(`Délka úsečky: ${distVal.toFixed(3)}<br>dX: ${formatVal(dx)} dZ: ${dz.toFixed(3)}`);
return;
}
if (State.measureMode === "distance") {
if(State.measurePoints.length === 1 && dist(State.measurePoints[0], p) < 0.001) return;
State.measurePoints.push(p); renderMeasure();
if(State.measurePoints.length === 2) {
const P = State.measurePoints; const dx = P[1].x - P[0].x, dz = P[1].z - P[0].z, distVal = Math.sqrt(dx*dx + dz*dz);
State.lastMeasured = { type: "dist", p1: {x: P[0].x, z: P[0].z}, p2: {x: P[1].x, z: P[1].z}, val: distVal.toFixed(3) };
showMeasureResult(`Délka: ${distVal.toFixed(3)}<br>dX: ${formatVal(dx)} dZ: ${dz.toFixed(3)}`); State.measurePoints = [];
}
} else if (State.measureMode === "angle") {
if(isLine) {
const pStart = State.points[idx], pEnd = State.points[idx+1];
// Store actual points, not just vector
State.measurePoints.push({ x: pStart.x, z: pStart.z, x2: pEnd.x, z2: pEnd.z, type: 'lineSegment' });
showToast(`Vybrána úsečka ${State.measurePoints.length}/2`);
if(State.measurePoints.length === 2) {
const l1 = State.measurePoints[0], l2 = State.measurePoints[1];
// 1. Calculate Intersection (Vertex)
const d1x = l1.x2 - l1.x, d1z = l1.z2 - l1.z;
const d2x = l2.x2 - l2.x, d2z = l2.z2 - l2.z;
const det = d1x * -d2z - d1z * -d2x;
let vertex = { x: l1.x, z: l1.z }; // Default fallback
if (Math.abs(det) > 1e-5) {
const t = ((l2.x - l1.x) * -d2z - (l2.z - l1.z) * -d2x) / det;
vertex = { x: l1.x + t * d1x, z: l1.z + t * d1z };
} else {
// Check touching endpoints for connected lines
if(dist(l1, l2) < 0.001) vertex = {x: l1.x, z: l1.z};
else if(dist(l1, {x:l2.x2, z:l2.z2}) < 0.001) vertex = {x: l1.x, z: l1.z};
else if(dist({x:l1.x2, z:l1.z2}, l2) < 0.001) vertex = {x: l1.x2, z: l1.z2};
else if(dist({x:l1.x2, z:l1.z2}, {x:l2.x2, z:l2.z2}) < 0.001) vertex = {x: l1.x2, z: l1.z2};
}
// 2. Determine vectors pointing OUT from vertex
function getFarPoint(seg, v) {
const dStart = Math.hypot(seg.x - v.x, seg.z - v.z);
const dEnd = Math.hypot(seg.x2 - v.x, seg.z2 - v.z);
return dStart > dEnd ? {x: seg.x, z: seg.z} : {x: seg.x2, z: seg.z2};
}
const p1Out = getFarPoint(l1, vertex);
const p2Out = getFarPoint(l2, vertex);
const v1x = p1Out.x - vertex.x, v1z = p1Out.z - vertex.z;
const v2x = p2Out.x - vertex.x, v2z = p2Out.z - vertex.z;
const mag1 = Math.sqrt(v1x*v1x + v1z*v1z);
const mag2 = Math.sqrt(v2x*v2x + v2z*v2z);
if(mag1 === 0 || mag2 === 0) {
showMeasureResult("Chyba: Nulová délka");
} else {
const dot = v1x * v2x + v1z * v2z;
const ang = Math.acos(Math.max(-1, Math.min(1, dot / (mag1 * mag2)))) * (180 / Math.PI);
State.lastMeasured = {
type: 'angle',
vertex: vertex,
p1: p1Out,
p2: p2Out,
val: ang.toFixed(3)
};
showMeasureResult(`Úhel: ${ang.toFixed(3)}°<br>Doplněk (360°): ${(360-ang).toFixed(3)}°`);
}
State.measurePoints = [];
}
} else {
State.measurePoints.push(p); renderMeasure();
if(State.measurePoints.length === 3) {
const P = State.measurePoints;
const v1 = { x: P[0].x - P[1].x, z: P[0].z - P[1].z }; // 0 to 1
const v2 = { x: P[2].x - P[1].x, z: P[2].z - P[1].z }; // 2 to 1
const mag1 = Math.sqrt(v1.x*v1.x + v1.z*v1.z), mag2 = Math.sqrt(v2.x*v2.x + v2.z*v2.z);
if (mag1 === 0 || mag2 === 0) showMeasureResult("Chyba: Body");
else {
const dot = v1.x * v2.x + v1.z * v2.z;
const ang = Math.acos(Math.max(-1, Math.min(1, dot / (mag1 * mag2)))) * (180 / Math.PI);
State.lastMeasured = {
type: 'angle',
vertex: P[1], // Middle point is vertex
p1: P[0],
p2: P[2],
val: ang.toFixed(3)
};
showMeasureResult(`Úhel (vrchol bod 2): ${ang.toFixed(3)}°<br>Doplněk (360°): ${(360-ang).toFixed(3)}°`);
} State.measurePoints = [];
}
}
}
}
function commitMove() {
const lS = getNum("inp-len"), xS = getNum("inp-x"), zS = getNum("inp-z"), aS = getNum("inp-angle");
if (isNaN(lS) && isNaN(xS) && isNaN(zS) && isNaN(aS)) { alert("Hodnoty?"); return; }
saveHistory(); const l = State.points[State.points.length - 1]; let nx = l.x, nz = l.z;
if (!isNaN(aS)) {
let ang = aS; if ($("chk-rel-angle").checked && State.points.length > 1) { const prev = State.points[State.points.length - 2]; ang += Math.atan2(l.z - prev.z, l.x - prev.x) * (180 / Math.PI); }
const rad = ang * (Math.PI / 180);
if (!isNaN(lS)) { nx += lS * Math.cos(rad); nz += lS * Math.sin(rad); } else if (!isNaN(xS)) { let tx = State.isDiameter ? xS / 2 : xS; nx = tx; nz += ((tx - l.x) / Math.cos(rad)) * Math.sin(rad); } else if (!isNaN(zS)) { nz = zS; nx += ((zS - l.z) / Math.sin(rad)) * Math.cos(rad); }
} else if (!isNaN(xS) || !isNaN(zS)) { if (!isNaN(xS)) nx = State.isDiameter ? xS / 2 : xS; if (!isNaN(zS)) nz = zS; } else if (!isNaN(lS)) {
if (currentDir === "TANGENT") { let a; if (l.type === "arc" && l.cx !== undefined) { a = Math.atan2(l.z - l.cz, l.x - l.cx) + (l.cw ? -Math.PI / 2 : Math.PI / 2); } else if (State.points.length > 1) { const prev = State.points[State.points.length - 2]; a = Math.atan2(l.z - prev.z, l.x - prev.x); } else { a = 0; } nx += lS * Math.cos(a); nz += lS * Math.sin(a); } else { const diag = Math.SQRT1_2; const D = { U: [0, 1], D: [0, -1], L: [-1, 0], R: [1, 0], UL: [-diag, diag], UR: [diag, diag], DL: [-diag, -diag], DR: [diag, -diag] }; if (D[currentDir]) { nx += D[currentDir][0] * lS; nz += D[currentDir][1] * lS; } }
}
State.points.push({ x: nx, z: nz, break: false, type: "line", id: pointIdCounter++ }); centerViewOnPoint({ x: nx, z: nz }); updatePath(); $("inp-len").value = ""; $("inp-x").value = ""; $("inp-z").value = ""; $("inp-angle").value = ""; closeModals();
}
function shiftAllPoints(dx, dz) {
State.points.forEach(p => { p.x += dx; p.z += dz; if(p.type === 'arc') { p.cx += dx; p.cz += dz; } });
State.dimensions = []; // Reset dimensions on transform
updatePath(); setHomeView();
}
function rotateAllPoints(pivot, angleRad) {
const s = Math.sin(angleRad), c = Math.cos(angleRad);
State.points.forEach(p => {
const x = p.x - pivot.x, z = p.z - pivot.z;
p.x = pivot.x + (x * c - z * s);
p.z = pivot.z + (x * s + z * c);
if(p.type === 'arc') {
const cx = p.cx - pivot.x, cz = p.cz - pivot.z;
p.cx = pivot.x + (cx * c - cz * s);
p.cz = pivot.z + (cx * s + cz * c);
}
});
State.dimensions = []; // Reset dimensions
updatePath(); setHomeView();
}
function commitShift() {
if(!State.moveOrigin) return;
const tx = getNum("inp-x"), tz = getNum("inp-z");
if(isNaN(tx) || isNaN(tz)) return;
saveHistory();
const destX = State.isDiameter ? tx/2 : tx;
const dx = destX - State.moveOrigin.x;
const dz = tz - State.moveOrigin.z;
shiftAllPoints(dx, dz);
State.moveOrigin = null;
closeModals(); showToast("Model posunut");
$("btn-pick-target").style.display = "block"; $("btn-commit-move").onclick = commitMove; $("grp-angle").style.display = "block"; $("inp-len").style.display = "block"; $("input-title").innerText = "Parametry pohybu";
}
function commitArc() {
saveHistory(); const l = State.points[State.points.length - 1]; let ex, ez, cx, cz, r, cw;
if (arcMethod === "IK") {
const cX = getNum("center-x"), cZ = getNum("center-z"); if (isNaN(cX)) { alert("Střed?"); return; }
cx = (State.isDiameter ? cX / 2 : cX) + (isIncIK ? l.x : 0); cz = cZ + (isIncIK ? l.z : 0); r = dist(l, { x: cx, z: cz });
const tA = getNum("ik-target-angle");
if (!isNaN(tA)) { const a = Math.atan2(l.z - cz, l.x - cx) + tA * (Math.PI / 180) * (isG2 ? 1 : -1); ex = cx + r * Math.cos(a); ez = cz + r * Math.sin(a); } else { const tx = getNum("ik-target-x"), tz = getNum("ik-target-z"); if (!isNaN(tx) && !isNaN(tz)) { ex = State.isDiameter ? tx/2 : tx; ez = tz; } else { alert("Cíl?"); return; } } cw = isG2;
} else {
// Method R
if (arcMode === 'TAN' || arcMode === 'BACK') {
if(tanTarget === 'cone') {
r = Math.abs(getNum("arc-r")); if(isNaN(r)) { alert("Zadejte R"); return; }
const coneAngle = getNum("arc-cone-angle"); if(isNaN(coneAngle)) { alert("Zadejte úhel"); return; }
let prevAngle = 0;
if (State.points.length > 1) {
const prevPt = State.points[State.points.length - 2];
if (l.type === "arc") {
const angleToCenter = Math.atan2(l.z - l.cz, l.x - l.cx);
prevAngle = l.cw ? angleToCenter - Math.PI/2 : angleToCenter + Math.PI/2;
} else {
prevAngle = Math.atan2(l.z - prevPt.z, l.x - prevPt.x);
}
}
const centerAngle = prevAngle + (isG2 ? -Math.PI/2 : Math.PI/2);
cx = l.x + Math.cos(centerAngle) * r;
cz = l.z + Math.sin(centerAngle) * r;
const sweepRad = coneAngle * (Math.PI/180);
const startAngleFromCenter = Math.atan2(l.z - cz, l.x - cx);
const endAngleFromCenter = startAngleFromCenter + (isG2 ? -sweepRad : sweepRad);
ex = cx + Math.cos(endAngleFromCenter) * r;
ez = cz + Math.sin(endAngleFromCenter) * r;
cw = isG2;
} else if (arcMode === 'BACK') {
r = Math.abs(getNum("arc-r")); if(isNaN(r)) { alert("Zadejte R"); return; }
let tx = getNum("arc-x"), tz = getNum("arc-z"); if (State.isDiameter) tx /= 2; if(isNaN(tx)) { alert("Cíl?"); return; }
ex = tx; ez = tz;
const prev = State.points[State.points.length-2];
const dx = l.x - prev.x, dz = l.z - prev.z, len = Math.hypot(dx, dz);
const ux = dx/len, uz = dz/len;
const nx = -uz, nz = ux;
const side = isG2 ? 1 : -1;
const px = l.x + nx * r * side, pz = l.z + nz * r * side;
const Ox = px - ex, Oz = pz - ez;
const A = 1;
const B = 2 * (Ox * ux + Oz * uz);
const C = (Ox*Ox + Oz*Oz) - r*r;
const det = B*B - 4*A*C;
if(det < 0) { alert("Nelze sestrojit (Rádius nedosáhne)"); return; }
const t1 = (-B + Math.sqrt(det)) / 2;
const t2 = (-B - Math.sqrt(det)) / 2;
const c1 = {x: px + t1*ux, z: pz + t1*uz};
const c2 = {x: px + t2*ux, z: pz + t2*uz};
const T1x = c1.x - nx * r * side, T1z = c1.z - nz * r * side;
const T2x = c2.x - nx * r * side, T2z = c2.z - nz * r * side;
function calcSweep(c, tx, tz) {
const angS = Math.atan2(tz - c.z, tx - c.x);
const angE = Math.atan2(ez - c.z, ex - c.x);
let diff = angE - angS;
if(isG2) { if(diff > 0) diff -= 2*Math.PI; }
else { if(diff < 0) diff += 2*Math.PI; }
return Math.abs(diff);
}
const sweep1 = calcSweep(c1, T1x, T1z);
const sweep2 = calcSweep(c2, T2x, T2z);
let bestC, bestT;
if(sweep1 < sweep2) { bestC = c1; bestT = {x:T1x, z:T1z}; }
else { bestC = c2; bestT = {x:T2x, z:T2z}; }
cx = bestC.x; cz = bestC.z;
State.points[State.points.length-1].x = bestT.x;
State.points[State.points.length-1].z = bestT.z;
cw = isG2;
} else {
let tx = getNum("arc-x"), tz = getNum("arc-z"); if (State.isDiameter) tx /= 2; ex = tx; ez = tz;
let prevAngle = 0; if (State.points.length > 1) { const prevPt = State.points[State.points.length - 2]; if (l.type === "arc") { const angleToCenter = Math.atan2(l.z - l.cz, l.x - l.cx); prevAngle = l.cw ? angleToCenter - Math.PI/2 : angleToCenter + Math.PI/2; } else { prevAngle = Math.atan2(l.z - prevPt.z, l.x - prevPt.x); } }
const midX = (l.x + ex) / 2, midZ = (l.z + ez) / 2, bisectorAngle = Math.atan2(ez - l.z, ex - l.x) + Math.PI / 2, normalAngle = prevAngle + Math.PI / 2;
const D = Math.cos(normalAngle) * Math.sin(bisectorAngle) - Math.sin(normalAngle) * Math.cos(bisectorAngle);
if (Math.abs(D) < 1e-5) { alert("Body v přímce"); return; }
const dx = midX - l.x, dz = midZ - l.z; const t = (dx * Math.sin(bisectorAngle) - dz * Math.cos(bisectorAngle)) / D;
cx = l.x + t * Math.cos(normalAngle); cz = l.z + t * Math.sin(normalAngle); r = Math.hypot(l.x - cx, l.z - cz);
const Tx = Math.cos(prevAngle), Tz = Math.sin(prevAngle), Vx = ex - l.x, Vz = ez - l.z; cw = (Tx * Vz - Tz * Vx) < 0;
}
} else {
r = Math.abs(getNum("arc-r")); let tx = getNum("arc-x"), tz = getNum("arc-z"); if (State.isDiameter) tx /= 2; ex = tx; ez = tz;
const d = dist(l, { x: ex, z: ez }); if (d > 2 * r) { alert("Malé R"); return; }
const h = Math.sqrt(r * r - (d / 2) * (d / 2)), a = Math.atan2(ez - l.z, ex - l.x), mx = (l.x + ex) / 2, mz = (l.z + ez) / 2;
const c1x = mx + h * Math.sin(a), c1z = mz - h * Math.cos(a), c2x = mx - h * Math.sin(a), c2z = mz + h * Math.cos(a);
const cr = (ex - l.x) * (c1z - l.z) - (ez - l.z) * (c1x - l.x); cw = isG2;
if (cw) { cx = cr > 0 ? c1x : c2x; cz = cr > 0 ? c1z : c2z; } else { cx = cr < 0 ? c1x : c2x; cz = cr < 0 ? c1z : c2z; }
}
}
State.points.push({ x: ex, z: ez, type: "arc", r, cw: cw, break: false, cx, cz, id: pointIdCounter++ }); updatePath(); closeModals();
}
function applyChamfer() {
const val = getNum("chamfer-val"); if (!val || val <= 0) { alert("Hodnota?"); return; }
const idx = State.chamferIdx, pCurr = State.points[idx], pPrev = State.points[idx - 1], pNext = State.points[idx + 1];
if (idx <= 0 || idx >= State.points.length - 1 || pCurr.type === "arc" || pNext.type === "arc") { alert("Nelze"); return; }
saveHistory(); const v1 = { x: pPrev.x - pCurr.x, z: pPrev.z - pCurr.z }, v2 = { x: pNext.x - pCurr.x, z: pNext.z - pCurr.z };
const l1 = Math.sqrt(v1.x * v1.x + v1.z * v1.z), l2 = Math.sqrt(v2.x * v2.x + v2.z * v2.z);
const u1 = { x: v1.x / l1, z: v1.z / l1 }, u2 = { x: v2.x / l2, z: v2.z / l2 };
const angle = Math.acos(Math.max(-1, Math.min(1, u1.x * u2.x + u1.z * u2.z)));
if (Math.abs(angle - Math.PI) < 0.01 || Math.abs(angle) < 0.01) { alert("Rovná přímka"); return; }
const distC = chamferType === "C" ? val : val / Math.tan(angle / 2);
if (distC > l1 || distC > l2) { alert("Velké"); return; }
State.points[idx] = { x: pCurr.x + u1.x * distC, z: pCurr.z + u1.z * distC, type: "line", break: false, id: pCurr.id };
if (chamferType === "C") { State.points.splice(idx + 1, 0, { x: pCurr.x + u2.x * distC, z: pCurr.z + u2.z * distC, type: "line", break: false, id: pointIdCounter++ }); }
else { const cross = v1.x * u2.z - v1.z * u2.x, isCW = cross > 0, cx = State.points[idx].x + (isCW ? -u1.z : u1.z) * val, cz = State.points[idx].z + (isCW ? u1.x : -u1.x) * val; State.points.splice(idx + 1, 0, { x: pCurr.x + u2.x * distC, z: pCurr.z + u2.z * distC, type: "arc", r: val, cw: isCW, cx, cz, break: false, id: pointIdCounter++ }); if (State.points[idx + 2]) State.points[idx + 2].type = "line"; }
updatePath(); closeModals(); setMode("IDLE");
}
function performTrim(seg) {
const idx = seg.index;
if (idx === undefined || idx >= State.points.length - 1) return;
saveHistory();
const pStart = State.points[idx];
const pEnd = State.points[idx+1];
const isArc = pEnd.type === 'arc';
let cuts = State.activeIntersections.filter(i => i.s1 === idx || i.s2 === idx);
function getMetric(p) {
if (!isArc) {
return Math.hypot(p.x - pStart.x, p.z - pStart.z);
} else {
const angStart = Math.atan2(pStart.z - pEnd.cz, pStart.x - pEnd.cx);
let angP = Math.atan2(p.z - pEnd.cz, p.x - pEnd.cx);
let diff = angP - angStart;
if (pEnd.cw) {
if(diff > 0) diff -= 2*Math.PI;
return Math.abs(diff);
} else {
if(diff < 0) diff += 2*Math.PI;
return diff;
}
}
}
const clickMetric = getMetric({x: seg.x, z: seg.z});
const lenMetric = getMetric({x: pEnd.x, z: pEnd.z});
let pointsOnSeg = cuts.map(c => ({x: c.x, z: c.z, m: getMetric(c)}));
pointsOnSeg = pointsOnSeg.filter(p => p.m > 0.001 && p.m < lenMetric - 0.001);
pointsOnSeg.sort((a,b) => a.m - b.m);
let bound1 = { x: pStart.x, z: pStart.z, isStart: true };
let bound2 = { x: pEnd.x, z: pEnd.z, isEnd: true };
const loopList = [...pointsOnSeg, {x: pEnd.x, z: pEnd.z, m: lenMetric, isEnd: true}];
let prev = bound1;
for(let pt of loopList) {
if (clickMetric < pt.m) {
bound2 = pt;
break;
}
prev = pt;
}
bound1 = prev;
const newSegments = [];
if (!bound1.isStart) {
newSegments.push({ ...pEnd, x: bound1.x, z: bound1.z, id: pointIdCounter++ });
}
if (!bound2.isEnd) {
newSegments.push({ x: bound2.x, z: bound2.z, break: true, type: 'line', id: pointIdCounter++ });
newSegments.push({ ...pEnd, id: pointIdCounter++ });
} else {
newSegments.push({ x: pEnd.x, z: pEnd.z, break: true, type: 'line', id: pointIdCounter++ });
}
State.points.splice(idx+1, 1, ...newSegments);
updatePath();
showToast("Oříznuto");
}
function openJoypad() { closeModals(); $("modal-joypad").style.display = "flex"; const l = State.points[State.points.length - 1]; $("btn-joy-tangent").classList.toggle("disabled", l.type !== "arc"); }
function prepMove(d) { currentDir = d; closeModals(); $("modal-input").style.display = "flex"; $("input-title").innerText = d === "TANGENT" ? "Tečna" : `Posun ${d}`; $("inp-len").value = ""; $("inp-x").value = ""; $("inp-z").value = ""; $("inp-angle").value = "";
$("grp-x").style.display = (d==="U"||d==="D") ? "none" : "block"; $("grp-z").style.display = (d==="L"||d==="R") ? "none" : "block"; $("grp-angle").style.display = (d.length>1 || d==="TANGENT") ? "block" : "none";
$("btn-pick-target").style.display = "block"; $("btn-commit-move").onclick = commitMove; $("inp-len").style.display = "block";
$("inp-len").focus(); }
function openArcModal() { closeModals(); $("modal-arc").style.display = "flex"; $("arc-r").value = 100; switchArcMethod("R"); setArcDir(true); setArcMode('NORM'); }
function switchArcMethod(m) { arcMethod = m; $("tab-r").classList.toggle("active", m === "R"); $("tab-ik").classList.toggle("active", m === "IK"); $("method-r").style.display = m === "R" ? "block" : "none"; $("method-ik").style.display = m === "IK" ? "block" : "none"; $("arc-targets").style.display = m === "R" ? "block" : "none"; }
function setArcDir(cw) { isG2 = cw; $("seg-g2").classList.toggle("active", cw); $("seg-g3").classList.toggle("active", !cw); }
function toggleIKMode(i) { isIncIK = i; $("ik-abs-btn").classList.toggle("active", !i); $("ik-inc-btn").classList.toggle("active", i); }
function openCircleModal() { closeModals(); $("modal-circle").style.display = "flex"; setCircleMode("R"); setCircTab("CR"); }
function setCircleMode(m) { circMode = m; $("circ-rad-btn").classList.toggle("active", m === "R"); $("circ-dia-btn").classList.toggle("active", m === "D"); $("lbl-circ-val").innerText = m === "R" ? "Poloměr R:" : "Průměr D:"; }
function setCircTab(t) { circTab = t; ["cr","2p","3p"].forEach(x => { $(`tab-${x}`).classList.toggle("active", x.toUpperCase() === t); $(`circ-${x}`).style.display = x.toUpperCase() === t ? "block" : "none"; }); }
function commitCircle() {
if(circTab === "CR") {
const v = getNum("circ-val"), cX = getNum("circ-cx"), cZ = getNum("circ-cz");
if (isNaN(v) || isNaN(cX)) return; saveHistory();
const r = circMode === "R" ? v : v / 2, cx = State.isDiameter ? cX / 2 : cX;
State.points.push({ x: cx + r, z: cZ, break: true, type: "line", id: pointIdCounter++ }, { x: cx - r, z: cZ, type: "arc", r, cw: true, cx, cz: cZ, id: pointIdCounter++ }, { x: cx + r, z: cZ, type: "arc", r, cw: true, cx, cz: cZ, id: pointIdCounter++ });
updatePath(); closeModals();
} else if (circTab === "2P") {
const r = getNum("circ-2p-r");
if(isNaN(r) || State.tempPickList.length !== 2) { alert("Zadejte R a vyberte 2 prvky"); return; }
saveHistory();
const p1 = State.tempPickList[0]; const p2 = State.tempPickList[1];
let success = false;
if(p1.type === 'line' && p2.type === 'line') { success = createTangentCircle2L(p1, p2, r); }
else if ((p1.type === 'line' && p2.type === 'point') || (p1.type === 'point' && p2.type === 'line')) { const lineObj = p1.type === 'line' ? p1 : p2; const pointObj = p1.type === 'point' ? p1 : p2; success = createTangentCircle1L1P(lineObj, pointObj, r); }
else { success = createCircleFrom2P(p1, p2, r); }
if(success) { State.tempPickList = []; updatePath(); closeModals(); } else { State.history.pop(); }
} else if (circTab === "3P") {
if(State.tempPickList.length !== 3) { alert("Vyberte 3 body nebo úsečky"); return; }
saveHistory();
const lst = State.tempPickList;
const lines = lst.filter(x => x.type === 'line'), points = lst.filter(x => x.type === 'point');
let success = false;
if (lines.length === 3) { success = createCircleFrom3L(lines[0], lines[1], lines[2]); }
else if (lines.length === 1 && points.length === 2) { success = createCircleFrom2P1L(points[0], points[1], lines[0]); }
else if (lines.length === 0) { success = createCircleFrom3P(lst[0], lst[1], lst[2]); }
else { alert("Tato kombinace (1 Bod + 2 Úsečky) zatím není podporována."); }
if(success) { State.tempPickList = []; updatePath(); closeModals(); } else { State.history.pop(); }
}
}
function addTangentPoint(x, z) { State.points.push({ x: x, z: z, break: true, type: "line", id: pointIdCounter++ }); }
function getLineDef(seg) { const s = State.points[seg.index], e = State.points[seg.index+1]; return { p: {x: s.x, z: s.z}, v: {x: e.x - s.x, z: e.z - s.z} }; }
// --- CIRCLE ALGORITHMS ---
function createTangentCircle2L(seg1, seg2, r) {
const s1 = State.points[seg1.index], e1 = State.points[seg1.index+1];
const s2 = State.points[seg2.index], e2 = State.points[seg2.index+1];
function getOffsetLine(p1, p2, clickP, radius) {
const dx = p2.x - p1.x, dz = p2.z - p1.z; const len = Math.hypot(dx, dz); if(len === 0) return null;
const nx = -dz/len, nz = dx/len;
return { px: p1.x, pz: p1.z, dx: dx, dz: dz, nx: nx, nz: nz };