-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1222 lines (1103 loc) · 44.2 KB
/
Copy pathscript.js
File metadata and controls
1222 lines (1103 loc) · 44.2 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
"use strict";
// ═══════════════════════════════════════════════════════════════
// CONSTANTS
// ═══════════════════════════════════════════════════════════════
const EPSILON = 1e-12; // numerical stability threshold for Gauss solver
const MIN_ZOOM = 0.04; // minimum view scale
const MAX_ZOOM = 40; // maximum view scale
const DEFAULT_INSET = 0.25; // default quad inset as a fraction of image size
const MIN_REF_SIZE = 20; // minimum reference image dimension in image-space pixels
// ═══════════════════════════════════════════════════════════════
// STATE
// ═══════════════════════════════════════════════════════════════
const S = {
step: 1,
wall: null, // HTMLImageElement – wall photo
iw: 0, ih: 0, // displayed image dimensions in "image space"
quad: [ // 4 corners in image space: TL TR BR BL
{x:0,y:0},{x:0,y:0},{x:0,y:0},{x:0,y:0}
],
dims: {w:0, h:0, unit:'cm'},
H: null, // 3×3 homography: image-space → real-world
ref: null, // HTMLImageElement – reference artwork
rp: {x:0,y:0,w:0,h:0,opacity:0.5}, // ref placement in image space (fallback)
rrp: {rx:0,ry:0,rw:0,rh:0}, // ref placement in real-world units
marker: null, // {ix,iy,rx,ry,dist} – single measurement marker, or null
view: {s:1, ox:0, oy:0},
drag: null, // current drag operation
lastM: {x:0,y:0}, // last mouse position in canvas space
warpMode: false, // perspective-corrected (rectified) view active
_warpVP: null, // cached warp viewport {vx,vy,vw,vh} set by renderWarpedWall()
};
// ═══════════════════════════════════════════════════════════════
// CANVAS
// ═══════════════════════════════════════════════════════════════
const canvas = document.getElementById('mainCanvas');
const ctx = canvas.getContext('2d');
const wrap = document.getElementById('canvas-wrap');
function resizeCanvas() {
canvas.width = wrap.clientWidth;
canvas.height = wrap.clientHeight;
if (S.wall) { fitView(); render(); }
}
window.addEventListener('resize', resizeCanvas);
resizeCanvas();
// ═══════════════════════════════════════════════════════════════
// MATH – Gaussian elimination, Homography, 3×3 inverse
// ═══════════════════════════════════════════════════════════════
/** Solve Ax = b (n×n) with partial-pivot Gauss elimination. */
function gaussSolve(A, b) {
const n = A.length;
const M = A.map((row, i) => [...row, b[i]]);
for (let c = 0; c < n; c++) {
// find pivot row
let maxR = c;
for (let r = c+1; r < n; r++)
if (Math.abs(M[r][c]) > Math.abs(M[maxR][c])) maxR = r;
[M[c], M[maxR]] = [M[maxR], M[c]];
const piv = M[c][c];
if (Math.abs(piv) < EPSILON) continue;
for (let r = c+1; r < n; r++) {
const f = M[r][c] / piv;
for (let k = c; k <= n; k++) M[r][k] -= f * M[c][k];
}
}
const x = new Array(n).fill(0);
for (let i = n-1; i >= 0; i--) {
x[i] = M[i][n];
for (let j = i+1; j < n; j++) x[i] -= M[i][j] * x[j];
x[i] /= M[i][i];
}
return x;
}
/**
* Compute 3×3 homography H from 4 point correspondences.
* src[i] (image-space) → dst[i] (real-world).
* Uses DLT with h[8]=1.
*/
function computeHomography(src, dst) {
const A = [], b = [];
for (let i = 0; i < 4; i++) {
const {x,y} = src[i], {x:X,y:Y} = dst[i];
A.push([x, y, 1, 0, 0, 0, -X*x, -X*y]); b.push(X);
A.push([0, 0, 0, x, y, 1, -Y*x, -Y*y]); b.push(Y);
}
const h = gaussSolve(A, b);
return [[h[0],h[1],h[2]],[h[3],h[4],h[5]],[h[6],h[7],1]];
}
/** Apply 3×3 homography H to point (x,y) → {x,y}. */
function applyH(H, x, y) {
const w = H[2][0]*x + H[2][1]*y + H[2][2];
return { x: (H[0][0]*x + H[0][1]*y + H[0][2]) / w,
y: (H[1][0]*x + H[1][1]*y + H[1][2]) / w };
}
// ═══════════════════════════════════════════════════════════════
// VIEW – zoom / pan
// ═══════════════════════════════════════════════════════════════
function c2i(cx,cy) { return { x:(cx-S.view.ox)/S.view.s, y:(cy-S.view.oy)/S.view.s }; }
function i2c(ix,iy) { return { x:ix*S.view.s+S.view.ox, y:iy*S.view.s+S.view.oy }; }
/** Convert canvas coords to real-world coords using the warp viewport (warp mode only). */
function c2rw(cx, cy) {
const ip = c2i(cx, cy);
const { vx, vy, vw, vh } = S._warpVP;
return { rx: ip.x / S.iw * vw + vx, ry: ip.y / S.ih * vh + vy };
}
function fitView() {
const cw = canvas.width, ch = canvas.height;
const s = Math.min(cw/S.iw, ch/S.ih) * 0.95;
S.view.s = s;
S.view.ox = (cw - S.iw*s) / 2;
S.view.oy = (ch - S.ih*s) / 2;
}
function doZoom(factor, cx, cy) {
cx = cx ?? canvas.width/2;
cy = cy ?? canvas.height/2;
const ns = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, S.view.s * factor));
const r = ns / S.view.s;
S.view.ox = cx - r*(cx - S.view.ox);
S.view.oy = cy - r*(cy - S.view.oy);
S.view.s = ns;
render();
}
function resetView() { fitView(); render(); }
function getPinchDist(e) {
const t = e.touches;
return Math.hypot(t[0].clientX - t[1].clientX, t[0].clientY - t[1].clientY);
}
function getPinchCenter(e) {
const rect = canvas.getBoundingClientRect();
const t = e.touches;
return {
x: (t[0].clientX + t[1].clientX) / 2 - rect.left,
y: (t[0].clientY + t[1].clientY) / 2 - rect.top,
};
}
// ═══════════════════════════════════════════════════════════════
// RENDER
// ═══════════════════════════════════════════════════════════════
function render() {
const cw = canvas.width, ch = canvas.height;
ctx.clearRect(0, 0, cw, ch);
if (!S.wall) return;
ctx.save();
ctx.translate(S.view.ox, S.view.oy);
ctx.scale(S.view.s, S.view.s);
// Wall image (perspective-corrected in warp mode, original otherwise)
if (S.warpMode && S.H) {
if (!renderWarpedWall()) ctx.drawImage(S.wall, 0, 0, S.iw, S.ih); // WebGL fallback
} else {
ctx.drawImage(S.wall, 0, 0, S.iw, S.ih);
}
// Reference artwork (steps 5+)
if (S.ref && S.step >= 5) {
ctx.save();
ctx.globalAlpha = S.rp.opacity;
if (S.warpMode && S.H && S._warpVP) {
drawRefWarp();
} else {
ctx.drawImage(S.ref, S.rp.x, S.rp.y, S.rp.w, S.rp.h);
}
ctx.restore();
// Draw handles at full opacity
if (S.step === 5) {
if (S.warpMode && S.H && S._warpVP) drawRefHandlesWarp();
else drawRefHandles();
}
}
// Quad overlay (steps 2+): rectified rectangle in warp mode, draggable quad otherwise
if (S.step >= 2) {
if (S.warpMode && S.H && S._warpVP) drawCorrectedRect();
else drawQuad();
}
// Work-area origin indicator and markers
if (S.step >= 6) {
if (S.warpMode && S.H && S._warpVP) {
drawOriginWarp();
drawMarkersWarp();
} else {
if (S.H) drawOrigin();
drawMarkers();
}
}
ctx.restore();
}
function drawQuad() {
const q = S.quad;
const lw = 2 / S.view.s;
// Filled region
ctx.beginPath();
ctx.moveTo(q[0].x, q[0].y);
for (let i = 1; i < 4; i++) ctx.lineTo(q[i].x, q[i].y);
ctx.closePath();
ctx.fillStyle = 'rgba(34,211,238,0.06)';
ctx.fill();
ctx.strokeStyle = 'rgba(34,211,238,0.6)';
ctx.lineWidth = lw;
ctx.setLineDash([6/S.view.s, 4/S.view.s]);
ctx.stroke();
ctx.setLineDash([]);
// Handles
const labels = ['TL','TR','BR','BL'];
q.forEach((pt, i) => {
const r = 14 / S.view.s;
ctx.beginPath();
ctx.arc(pt.x, pt.y, r, 0, Math.PI*2);
ctx.fillStyle = '#f0a500';
ctx.fill();
ctx.strokeStyle = '#fff';
ctx.lineWidth = 1.5 / S.view.s;
ctx.stroke();
ctx.fillStyle = '#111';
ctx.font = `bold ${11/S.view.s}px system-ui`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(labels[i], pt.x, pt.y);
});
}
function drawRefHandles() {
const {x,y,w,h} = S.rp;
const r = 7 / S.view.s;
ctx.strokeStyle = '#f0a500';
ctx.lineWidth = 2 / S.view.s;
ctx.strokeRect(x, y, w, h);
[[x,y],[x+w,y],[x+w,y+h],[x,y+h]].forEach(([cx,cy]) => {
ctx.beginPath();
ctx.arc(cx, cy, r, 0, Math.PI*2);
ctx.fillStyle = '#f0a500';
ctx.fill();
ctx.strokeStyle = '#fff';
ctx.lineWidth = 1.5 / S.view.s;
ctx.stroke();
});
}
function drawOrigin() {
// Draw a small star at the TL quad corner (work-area origin)
const {x,y} = S.quad[0];
const r = 10 / S.view.s;
ctx.save();
ctx.translate(x, y);
ctx.strokeStyle = '#22d3ee';
ctx.lineWidth = 2 / S.view.s;
for (let a = 0; a < Math.PI*2; a += Math.PI/3) {
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(Math.cos(a)*r, Math.sin(a)*r);
ctx.stroke();
}
ctx.beginPath();
ctx.arc(0, 0, r*0.35, 0, Math.PI*2);
ctx.fillStyle = '#22d3ee';
ctx.fill();
ctx.restore();
}
/** Draw a measurement label with a dark pill background near a canvas point. */
function _drawMeasureLabel(text, x, y) {
const fs = 10 / S.view.s;
const pad = 2.5 / S.view.s;
ctx.save();
ctx.font = `bold ${fs}px system-ui`;
ctx.textBaseline = 'middle';
ctx.textAlign = 'center';
const tw = ctx.measureText(text).width;
ctx.fillStyle = 'rgba(0,0,0,0.6)';
ctx.fillRect(x - tw / 2 - pad, y - fs / 2 - pad, tw + pad * 2, fs + pad * 2);
ctx.fillStyle = '#facc15';
ctx.fillText(text, x, y);
ctx.restore();
}
function drawMarkers() {
if (!S.marker) return;
const m = S.marker;
const r = 7 / S.view.s;
const lw = 1.5 / S.view.s;
const { unit } = S.dims;
// Compute left-edge and top-edge image-space points via bilinear interpolation on quad
const t = S.dims.h ? m.ry / S.dims.h : 0; // fraction along TL→BL
const s = S.dims.w ? m.rx / S.dims.w : 0; // fraction along TL→TR
const leftPt = {
x: S.quad[0].x + (S.quad[3].x - S.quad[0].x) * t,
y: S.quad[0].y + (S.quad[3].y - S.quad[0].y) * t,
};
const topPt = {
x: S.quad[0].x + (S.quad[1].x - S.quad[0].x) * s,
y: S.quad[0].y + (S.quad[1].y - S.quad[0].y) * s,
};
// Diagonal, horizontal, and vertical dashed lines
ctx.save();
ctx.strokeStyle = 'rgba(250,204,21,0.35)';
ctx.lineWidth = lw;
ctx.setLineDash([4/S.view.s, 3/S.view.s]);
ctx.beginPath();
ctx.moveTo(S.quad[0].x, S.quad[0].y); ctx.lineTo(m.ix, m.iy); // diagonal (origin → marker)
ctx.moveTo(leftPt.x, leftPt.y); ctx.lineTo(m.ix, m.iy); // horizontal (left edge → marker)
ctx.moveTo(topPt.x, topPt.y); ctx.lineTo(m.ix, m.iy); // vertical (top edge → marker)
ctx.stroke();
ctx.setLineDash([]);
ctx.restore();
// Crosshair
ctx.save();
ctx.strokeStyle = '#facc15';
ctx.lineWidth = lw;
ctx.beginPath();
ctx.moveTo(m.ix - r*2, m.iy); ctx.lineTo(m.ix + r*2, m.iy);
ctx.moveTo(m.ix, m.iy - r*2); ctx.lineTo(m.ix, m.iy + r*2);
ctx.stroke();
// Dot
ctx.beginPath();
ctx.arc(m.ix, m.iy, r, 0, Math.PI*2);
ctx.fillStyle = '#facc15';
ctx.fill();
ctx.strokeStyle = '#111';
ctx.stroke();
ctx.restore();
// Labels at short offsets from the marker
const off = 14 / S.view.s;
_drawMeasureLabel(`${m.dist.toFixed(1)} ${unit}`, m.ix + off, m.iy - 2.5 * off); // diagonal
_drawMeasureLabel(`${m.rx.toFixed(1)} ${unit}`, m.ix - 3 * off, m.iy + off); // from left
_drawMeasureLabel(`${m.ry.toFixed(1)} ${unit}`, m.ix + off, m.iy + 2 * off); // from top
}
/** Draw origin marker at real-world (0,0) in warp output space. */
function drawOriginWarp() {
if (!S._warpVP) return;
const { x, y } = rwToOut(0, 0);
const r = 10 / S.view.s;
ctx.save();
ctx.translate(x, y);
ctx.strokeStyle = '#22d3ee';
ctx.lineWidth = 2 / S.view.s;
for (let a = 0; a < Math.PI * 2; a += Math.PI / 3) {
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(Math.cos(a) * r, Math.sin(a) * r);
ctx.stroke();
}
ctx.beginPath();
ctx.arc(0, 0, r * 0.35, 0, Math.PI * 2);
ctx.fillStyle = '#22d3ee';
ctx.fill();
ctx.restore();
}
/** Draw marker mapped to warp output space via its stored real-world coords. */
function drawMarkersWarp() {
if (!S._warpVP || !S.marker) return;
const m = S.marker;
const origin = rwToOut(0, 0);
const { x: mx, y: my } = rwToOut(m.rx, m.ry);
const leftPt = rwToOut(0, m.ry); // left edge at marker's real-world y
const topPt = rwToOut(m.rx, 0); // top edge at marker's real-world x
const r = 7 / S.view.s;
const lw = 1.5 / S.view.s;
const { unit } = S.dims;
// Diagonal, horizontal, and vertical dashed lines
ctx.save();
ctx.strokeStyle = 'rgba(250,204,21,0.35)';
ctx.lineWidth = lw;
ctx.setLineDash([4/S.view.s, 3/S.view.s]);
ctx.beginPath();
ctx.moveTo(origin.x, origin.y); ctx.lineTo(mx, my); // diagonal (origin → marker)
ctx.moveTo(leftPt.x, leftPt.y); ctx.lineTo(mx, my); // horizontal (left edge → marker)
ctx.moveTo(topPt.x, topPt.y); ctx.lineTo(mx, my); // vertical (top edge → marker)
ctx.stroke();
ctx.setLineDash([]);
ctx.restore();
ctx.save();
ctx.strokeStyle = '#facc15';
ctx.lineWidth = lw;
ctx.beginPath();
ctx.moveTo(mx - r*2, my); ctx.lineTo(mx + r*2, my);
ctx.moveTo(mx, my - r*2); ctx.lineTo(mx, my + r*2);
ctx.stroke();
ctx.beginPath();
ctx.arc(mx, my, r, 0, Math.PI * 2);
ctx.fillStyle = '#facc15';
ctx.fill();
ctx.strokeStyle = '#111';
ctx.stroke();
ctx.restore();
// Labels at short offsets from the marker
const off = 14 / S.view.s;
_drawMeasureLabel(`${m.dist.toFixed(1)} ${unit}`, mx + off, my - 2.5 * off); // diagonal
_drawMeasureLabel(`${m.rx.toFixed(1)} ${unit}`, mx - 3 * off, my + off); // from left
_drawMeasureLabel(`${m.ry.toFixed(1)} ${unit}`, mx + off, my + 2 * off); // from top
}
// ═══════════════════════════════════════════════════════════════
// PERSPECTIVE WARP – WebGL-based image rectification
// ═══════════════════════════════════════════════════════════════
const _WARP_VS = `attribute vec2 a_pos; void main(){ gl_Position = vec4(a_pos,0.0,1.0); }`;
const _WARP_FS = `
precision mediump float;
uniform sampler2D u_tex;
uniform vec2 u_res; // output size (S.iw, S.ih)
uniform mat3 u_Hinv; // real-world → image-space (column-major for GLSL)
uniform vec4 u_vp; // viewport: (minX, minY, width, height) in real-world units
uniform vec2 u_img; // image display size: (S.iw, S.ih)
void main() {
// Normalized output coords with (0,0) at top-left
vec2 uv = vec2(gl_FragCoord.x / u_res.x, (u_res.y - gl_FragCoord.y) / u_res.y);
// Map to real-world viewport
float rx = uv.x * u_vp.z + u_vp.x;
float ry = uv.y * u_vp.w + u_vp.y;
// Apply inverse homography → image-space coords
vec3 p = u_Hinv * vec3(rx, ry, 1.0);
vec2 tc = (p.xy / p.z) / u_img;
if (tc.x < 0.0 || tc.x > 1.0 || tc.y < 0.0 || tc.y > 1.0) {
gl_FragColor = vec4(0.11, 0.12, 0.14, 1.0);
} else {
gl_FragColor = texture2D(u_tex, tc);
}
}`;
let _gl = null, _glCanvas = null, _glProg = null, _glTex = null, _glTexImg = null;
// Cached warp parameters – invalidated when quad or dims change
let _warpHinv = null, _warpHinvKey = null;
function _initGL() {
if (_gl) return true;
_glCanvas = document.createElement('canvas');
const gl = _glCanvas.getContext('webgl') || _glCanvas.getContext('experimental-webgl');
if (!gl) return false;
_gl = gl;
function mkShader(type, src) {
const s = gl.createShader(type);
gl.shaderSource(s, src); gl.compileShader(s); return s;
}
_glProg = gl.createProgram();
gl.attachShader(_glProg, mkShader(gl.VERTEX_SHADER, _WARP_VS));
gl.attachShader(_glProg, mkShader(gl.FRAGMENT_SHADER, _WARP_FS));
gl.linkProgram(_glProg);
// Full-screen quad (TRIANGLE_STRIP)
const buf = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buf);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1,-1, 1,-1, -1,1, 1,1]), gl.STATIC_DRAW);
const loc = gl.getAttribLocation(_glProg, 'a_pos');
gl.enableVertexAttribArray(loc);
gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0);
_glTex = gl.createTexture();
return true;
}
function _uploadTex() {
if (_glTexImg === S.wall) return; // already current
// Draw wall at display resolution so texture coords match S.iw/S.ih
const tmp = document.createElement('canvas');
tmp.width = S.iw; tmp.height = S.ih;
tmp.getContext('2d').drawImage(S.wall, 0, 0, S.iw, S.ih);
const gl = _gl;
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); // no flip; shader handles GL y-axis via (u_res.y - gl_FragCoord.y)
gl.bindTexture(gl.TEXTURE_2D, _glTex);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, tmp);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
_glTexImg = S.wall;
}
/**
* Render perspective-corrected (rectified) wall to ctx at (0,0,S.iw,S.ih).
* The inverse homography is applied so the quad region appears rectangular.
* Returns false if WebGL is unavailable (caller should fall back to ctx.drawImage).
*/
function renderWarpedWall() {
if (!S.H || !S.wall || !_initGL()) return false;
_uploadTex();
const { w, h } = S.dims;
// Inverse homography: real-world rectangle → image-space quad
// Cache keyed on dims + quad coords to avoid recomputing during pan/zoom
const hinvKey = `${w},${h},${S.quad.map(p=>`${p.x.toFixed(3)},${p.y.toFixed(3)}`).join(',')}`;
if (hinvKey !== _warpHinvKey || !_warpHinv) {
_warpHinv = computeHomography([{x:0,y:0},{x:w,y:0},{x:w,y:h},{x:0,y:h}], S.quad);
_warpHinvKey = hinvKey;
S._warpVP = null; // invalidate cached viewport
}
const Hinv = _warpHinv;
// Compute real-world bounding box of all four image corners (cached)
if (!S._warpVP) {
const imgPts = [{x:0,y:0},{x:S.iw,y:0},{x:S.iw,y:S.ih},{x:0,y:S.ih}]
.map(p => applyH(S.H, p.x, p.y));
let vx = Math.min(...imgPts.map(p => p.x)), vy = Math.min(...imgPts.map(p => p.y));
let vw = Math.max(...imgPts.map(p => p.x)) - vx;
let vh = Math.max(...imgPts.map(p => p.y)) - vy;
if (vw < 1e-6 || vh < 1e-6) return false;
// Pad viewport to match output aspect ratio to avoid stretching
const asp = S.iw / S.ih;
if (vw / vh > asp) { const d = (vw / asp - vh) / 2; vy -= d; vh += d * 2; }
else { const d = (vh * asp - vw) / 2; vx -= d; vw += d * 2; }
// Cache for overlay helpers (drawCorrectedRect / drawRefWarp) and future renders
S._warpVP = { vx, vy, vw, vh };
}
const { vx, vy, vw, vh } = S._warpVP;
const gl = _gl;
if (_glCanvas.width !== S.iw || _glCanvas.height !== S.ih) {
_glCanvas.width = S.iw; _glCanvas.height = S.ih;
}
gl.viewport(0, 0, S.iw, S.ih);
gl.useProgram(_glProg);
const u = n => gl.getUniformLocation(_glProg, n);
// GLSL mat3 is column-major; our JS H[row][col] must be transposed
const H = Hinv;
gl.uniformMatrix3fv(u('u_Hinv'), false, [
H[0][0],H[1][0],H[2][0], H[0][1],H[1][1],H[2][1], H[0][2],H[1][2],H[2][2]
]);
gl.uniform2f(u('u_res'), S.iw, S.ih);
gl.uniform4f(u('u_vp'), vx, vy, vw, vh);
gl.uniform2f(u('u_img'), S.iw, S.ih);
gl.bindTexture(gl.TEXTURE_2D, _glTex);
gl.uniform1i(u('u_tex'), 0);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
ctx.drawImage(_glCanvas, 0, 0, S.iw, S.ih);
return true;
}
/** Convert real-world coords to image-space output coords using the cached warp viewport. */
function rwToOut(rx, ry) {
const { vx, vy, vw, vh } = S._warpVP;
return { x: (rx - vx) / vw * S.iw, y: (ry - vy) / vh * S.ih };
}
/** Draw a dashed rectangle showing the rectified (flattened) quad boundary. */
function drawCorrectedRect() {
if (!S._warpVP || !S.dims.w) return;
const tl = rwToOut(0, 0 );
const br = rwToOut(S.dims.w, S.dims.h);
const lw = 2 / S.view.s;
ctx.strokeStyle = 'rgba(34,211,238,0.6)';
ctx.lineWidth = lw;
ctx.setLineDash([6/S.view.s, 4/S.view.s]);
ctx.strokeRect(tl.x, tl.y, br.x - tl.x, br.y - tl.y);
ctx.setLineDash([]);
}
/** Draw reference art at its real-world position in the warp view. */
function drawRefWarp() {
if (!S._warpVP || !S.rrp.rw) return;
const cs = [
rwToOut(S.rrp.rx, S.rrp.ry),
rwToOut(S.rrp.rx + S.rrp.rw, S.rrp.ry),
rwToOut(S.rrp.rx + S.rrp.rw, S.rrp.ry + S.rrp.rh),
rwToOut(S.rrp.rx, S.rrp.ry + S.rrp.rh),
];
const bx = Math.min(...cs.map(c => c.x)), by = Math.min(...cs.map(c => c.y));
const bw = Math.max(...cs.map(c => c.x)) - bx, bh = Math.max(...cs.map(c => c.y)) - by;
ctx.drawImage(S.ref, bx, by, bw, bh);
}
/** Draw corner handles for the reference art in warp output space. */
function drawRefHandlesWarp() {
if (!S._warpVP || !S.rrp.rw) return;
const corners = [
rwToOut(S.rrp.rx, S.rrp.ry),
rwToOut(S.rrp.rx + S.rrp.rw, S.rrp.ry),
rwToOut(S.rrp.rx + S.rrp.rw, S.rrp.ry + S.rrp.rh),
rwToOut(S.rrp.rx, S.rrp.ry + S.rrp.rh),
];
const r = 7 / S.view.s;
ctx.strokeStyle = '#f0a500';
ctx.lineWidth = 2 / S.view.s;
ctx.beginPath();
corners.forEach((c, i) => (i === 0 ? ctx.moveTo(c.x, c.y) : ctx.lineTo(c.x, c.y)));
ctx.closePath();
ctx.stroke();
corners.forEach(c => {
ctx.beginPath();
ctx.arc(c.x, c.y, r, 0, Math.PI * 2);
ctx.fillStyle = '#f0a500';
ctx.fill();
ctx.strokeStyle = '#fff';
ctx.lineWidth = 1.5 / S.view.s;
ctx.stroke();
});
}
/** Toggle perspective-correction warp view on/off. */
function toggleWarp() {
S.warpMode = !S.warpMode;
if (!S.warpMode) S._warpVP = null;
document.getElementById('btn-warp').classList.toggle('active', S.warpMode);
render();
}
// ═══════════════════════════════════════════════════════════════
// STEP NAVIGATION
// ═══════════════════════════════════════════════════════════════
function goTo(n) {
S.step = n;
// Auto-enable warp mode when homography is ready (step 4+)
if (n >= 4 && S.H) {
S.warpMode = true;
} else {
S.warpMode = false;
S._warpVP = null;
}
for (let i = 1; i <= 6; i++) {
const si = document.getElementById(`si-${i}`);
const cp = document.getElementById(`cp-${i}`);
si.className = 'step-item' + (i<n?' done':i===n?' active':'');
if (cp) cp.classList.toggle('hidden', i !== n);
}
document.getElementById('btn-quad-ok').style.display = n === 2 ? 'flex' : 'none';
document.getElementById('btn-fix-ref').style.display = n === 5 ? 'flex' : 'none';
document.getElementById('zoom-btns').style.display = n >= 2 ? 'flex' : 'none';
document.getElementById('warp-btn-wrap').style.display = 'none';
if (isMobile()) { n === 3 ? openSidebar() : closeSidebar(); }
updateStatus();
render();
}
const STATUS_MSGS = {
1: 'Upload a wall photo to begin',
2: 'Drag the yellow handles to define the flat work area',
3: 'Enter the real-world dimensions of the work area',
4: 'Upload a reference artwork photo (or skip)',
5: 'Position artwork on the projected wall · drag to move · corner handles to resize',
6: 'Tap to place a marker · drag to pan · scroll to zoom',
};
function updateStatus() {
document.getElementById('status-bar').textContent = STATUS_MSGS[S.step];
}
// ═══════════════════════════════════════════════════════════════
// FILE UPLOAD HELPERS
// ═══════════════════════════════════════════════════════════════
function setupDropZone(zoneId, inputId, onImage) {
const zone = document.getElementById(zoneId);
const input = document.getElementById(inputId);
zone.addEventListener('click', () => input.click());
input.addEventListener('change', e => {
if (e.target.files[0]) readImage(e.target.files[0], onImage);
});
zone.addEventListener('dragover', e => { e.preventDefault(); zone.classList.add('over'); });
zone.addEventListener('dragleave', () => zone.classList.remove('over'));
zone.addEventListener('drop', e => {
e.preventDefault();
zone.classList.remove('over');
if (e.dataTransfer.files[0]) readImage(e.dataTransfer.files[0], onImage);
});
}
function readImage(file, cb) {
if (!file.type.startsWith('image/')) return;
const url = URL.createObjectURL(file);
const img = new Image();
img.onload = () => { cb(img); URL.revokeObjectURL(url); };
img.src = url;
}
// Wall upload
setupDropZone('dz-wall', 'wall-input', img => {
S.wall = img;
// Fit image into canvas, then track its display size
const maxW = wrap.clientWidth * 0.95;
const maxH = wrap.clientHeight * 0.95;
const sc = Math.min(maxW / img.naturalWidth, maxH / img.naturalHeight, 1);
S.iw = img.naturalWidth * sc;
S.ih = img.naturalHeight * sc;
// Default quad: DEFAULT_INSET inset
const p = DEFAULT_INSET;
S.quad[0] = {x: S.iw*p, y: S.ih*p };
S.quad[1] = {x: S.iw*(1-p), y: S.ih*p };
S.quad[2] = {x: S.iw*(1-p), y: S.ih*(1-p)};
S.quad[3] = {x: S.iw*p, y: S.ih*(1-p)};
document.getElementById('drop-wall').classList.add('hidden');
fitView();
goTo(2);
});
// Reference upload
setupDropZone('dz-ref', 'ref-input', img => {
S.ref = img;
if (S.H && S.dims.w && S.dims.h) {
// Initialize ref art centered on the real-world wall area
const wallW = S.dims.w, wallH = S.dims.h;
const imgAspect = img.naturalWidth / img.naturalHeight;
let rw, rh;
if (imgAspect > wallW / wallH) {
rw = wallW * 0.8;
rh = rw / imgAspect;
} else {
rh = wallH * 0.8;
rw = rh * imgAspect;
}
S.rrp.rw = rw;
S.rrp.rh = rh;
S.rrp.rx = (wallW - rw) / 2;
S.rrp.ry = (wallH - rh) / 2;
} else {
// Fallback: center ref image over the quad bounding box (image-space)
const q = S.quad;
const qx = Math.min(...q.map(p=>p.x)), qy = Math.min(...q.map(p=>p.y));
const qw = Math.max(...q.map(p=>p.x)) - qx;
const qh = Math.max(...q.map(p=>p.y)) - qy;
const rs = Math.min(qw / img.naturalWidth, qh / img.naturalHeight);
S.rp.w = img.naturalWidth * rs;
S.rp.h = img.naturalHeight * rs;
S.rp.x = qx + (qw - S.rp.w) / 2;
S.rp.y = qy + (qh - S.rp.h) / 2;
}
S.rp.opacity = 0.5;
syncOpacitySliders();
document.getElementById('drop-ref').classList.add('hidden');
goTo(5);
});
// ═══════════════════════════════════════════════════════════════
// BUTTON HANDLERS
// ═══════════════════════════════════════════════════════════════
document.getElementById('btn-quad-ok').addEventListener('click', () => goTo(3));
document.getElementById('btn-dims-back').addEventListener('click', () => goTo(2));
document.getElementById('btn-dims-ok').addEventListener('click', () => {
const w = parseFloat(document.getElementById('inp-w').value);
const h = parseFloat(document.getElementById('inp-h').value);
if (!w || !h || w <= 0 || h <= 0) {
alert('Please enter valid width and height values.');
return;
}
S.dims = { w, h, unit: document.getElementById('inp-unit').value };
// Compute homography: quad corners → real-world rectangle
const dst = [{x:0,y:0},{x:w,y:0},{x:w,y:h},{x:0,y:h}];
S.H = computeHomography(S.quad, dst);
document.getElementById('drop-ref').classList.remove('hidden');
goTo(4);
});
document.getElementById('btn-skip-ref').addEventListener('click', () => {
S.ref = null;
document.getElementById('drop-ref').classList.add('hidden');
goTo(6);
document.getElementById('sl-6-wrap').style.display = 'none';
});
document.getElementById('btn-fix-ref').addEventListener('click', () => {
document.getElementById('drop-ref').classList.add('hidden');
syncOpacitySliders();
goTo(6);
});
document.getElementById('btn-change-ref').addEventListener('click', () => {
document.getElementById('drop-ref').classList.remove('hidden');
// reset file input so same file can be re-selected
document.getElementById('ref-input').value = '';
});
document.getElementById('btn-back-5').addEventListener('click', () => {
document.getElementById('drop-ref').classList.add('hidden');
goTo(5);
});
document.getElementById('btn-clear-markers').addEventListener('click', () => {
S.marker = null;
renderMarkerList();
render();
});
function syncOpacitySliders() {
const v = Math.round(S.rp.opacity * 100);
document.getElementById('sl-opacity-5').value = v;
document.getElementById('sl-opacity-6').value = v;
document.getElementById('sl-opacity-5-val').textContent = v + '%';
document.getElementById('sl-opacity-6-val').textContent = v + '%';
}
['sl-opacity-5','sl-opacity-6'].forEach(id => {
document.getElementById(id).addEventListener('input', e => {
S.rp.opacity = e.target.value / 100;
document.getElementById(id+'-val').textContent = e.target.value + '%';
// sync the other slider
const other = id === 'sl-opacity-5' ? 'sl-opacity-6' : 'sl-opacity-5';
document.getElementById(other).value = e.target.value;
document.getElementById(other+'-val').textContent = e.target.value + '%';
render();
});
});
// ═══════════════════════════════════════════════════════════════
// MOUSE / TOUCH EVENTS
// ═══════════════════════════════════════════════════════════════
const HIT_R = 20; // hit-test radius in canvas pixels
const TAP_MAX_DIST = 6; // max movement in canvas pixels to count as a tap
function canvasXY(e) {
const rect = canvas.getBoundingClientRect();
const src = e.touches ? e.touches[0] : e;
return { x: src.clientX - rect.left, y: src.clientY - rect.top };
}
function hitQuad(cx, cy) {
for (let i = 0; i < 4; i++) {
const cp = i2c(S.quad[i].x, S.quad[i].y);
const dx = cx-cp.x, dy = cy-cp.y;
if (Math.hypot(dx,dy) < HIT_R) return i;
}
return -1;
}
function hitRefCorner(cx, cy) {
if (!S.ref || S.step !== 5) return -1;
const {x,y,w,h} = S.rp;
const corners = [[x,y],[x+w,y],[x+w,y+h],[x,y+h]];
for (let i = 0; i < 4; i++) {
const cp = i2c(corners[i][0], corners[i][1]);
if (Math.hypot(cx-cp.x, cy-cp.y) < HIT_R) return i;
}
return -1;
}
function hitRefBody(cx, cy) {
if (!S.ref || S.step !== 5) return false;
const ip = c2i(cx, cy);
return ip.x>=S.rp.x && ip.x<=S.rp.x+S.rp.w && ip.y>=S.rp.y && ip.y<=S.rp.y+S.rp.h;
}
/** Hit-test ref art corner handles in warp output space. */
function hitRefCornerWarp(cx, cy) {
if (!S.ref || S.step !== 5 || !S._warpVP || !S.rrp.rw) return -1;
const corners = [
rwToOut(S.rrp.rx, S.rrp.ry),
rwToOut(S.rrp.rx + S.rrp.rw, S.rrp.ry),
rwToOut(S.rrp.rx + S.rrp.rw, S.rrp.ry + S.rrp.rh),
rwToOut(S.rrp.rx, S.rrp.ry + S.rrp.rh),
];
for (let i = 0; i < 4; i++) {
const sc = i2c(corners[i].x, corners[i].y);
if (Math.hypot(cx - sc.x, cy - sc.y) < HIT_R) return i;
}
return -1;
}
/** Hit-test ref art body in warp (real-world) space. */
function hitRefBodyWarp(cx, cy) {
if (!S.ref || S.step !== 5 || !S._warpVP || !S.rrp.rw) return false;
const rw = c2rw(cx, cy);
return rw.rx >= S.rrp.rx && rw.rx <= S.rrp.rx + S.rrp.rw &&
rw.ry >= S.rrp.ry && rw.ry <= S.rrp.ry + S.rrp.rh;
}
canvas.addEventListener('mousedown', onDown);
canvas.addEventListener('mousemove', onMove);
canvas.addEventListener('mouseup', onUp);
canvas.addEventListener('mouseleave', onUp);
canvas.addEventListener('wheel', e => {
e.preventDefault();
if (S.step < 2) return;
const cp = canvasXY(e);
doZoom(e.deltaY < 0 ? 1.1 : 0.9, cp.x, cp.y);
}, { passive: false });
canvas.addEventListener('touchstart', e => { e.preventDefault(); onDown(e); }, { passive: false });
canvas.addEventListener('touchmove', e => { e.preventDefault(); onMove(e); }, { passive: false });
canvas.addEventListener('touchend', e => { e.preventDefault(); onUp(e); }, { passive: false });
function onDown(e) {
// Two-finger pinch zoom
if (e.touches && e.touches.length === 2) {
if (S.step >= 2) S.drag = { type: 'pinch', dist: getPinchDist(e) };
return;
}
const cp = canvasXY(e);
S.lastM = cp;
if (S.step === 2 && !S.warpMode) {
const hi = hitQuad(cp.x, cp.y);
if (hi >= 0) { S.drag = {type:'quad', idx:hi}; return; }
}
if (S.step === 5) {
if (S.warpMode && S._warpVP) {
const ci = hitRefCornerWarp(cp.x, cp.y);
if (ci >= 0) {
S.drag = {type:'ref-corner-warp', idx:ci, snap:{ ...S.rrp }};
return;
}
if (hitRefBodyWarp(cp.x, cp.y)) {
S.drag = {type:'ref-move-warp'};
return;
}
} else {
const ci = hitRefCorner(cp.x, cp.y);
if (ci >= 0) {
S.drag = {type:'ref-corner', idx:ci, snap:{ ...S.rp }};
return;
}
if (hitRefBody(cp.x, cp.y)) {
S.drag = {type:'ref-move'};
return;
}
}
}
// Pan (tap tracking: a tap with minimal movement in step 6 places the marker)
S.drag = {type:'pan', tapStart: cp, moved: false};
}
function onMove(e) {
// Two-finger pinch zoom
if (e.touches && e.touches.length === 2 && S.step >= 2) {
if (!S.drag || S.drag.type !== 'pinch') {
S.drag = { type: 'pinch', dist: getPinchDist(e) };
} else {
const newDist = getPinchDist(e);
const center = getPinchCenter(e);
doZoom(newDist / S.drag.dist, center.x, center.y);
S.drag.dist = newDist;
}
S.lastM = canvasXY(e);
return;
}
const cp = canvasXY(e);
const dx = cp.x - S.lastM.x;
const dy = cp.y - S.lastM.y;
// Update cursor when not dragging
if (!S.drag) {
if (S.step === 2 && !S.warpMode) {
canvas.style.cursor = hitQuad(cp.x,cp.y) >= 0 ? 'grab' : 'default';
} else if (S.step === 5) {
if (S.warpMode && S._warpVP) {
if (hitRefCornerWarp(cp.x,cp.y) >= 0) canvas.style.cursor = 'nwse-resize';
else if (hitRefBodyWarp(cp.x,cp.y)) canvas.style.cursor = 'move';
else canvas.style.cursor = 'default';
} else {
if (hitRefCorner(cp.x,cp.y) >= 0) canvas.style.cursor = 'nwse-resize';
else if (hitRefBody(cp.x,cp.y)) canvas.style.cursor = 'move';
else canvas.style.cursor = 'default';
}
} else if (S.step === 6) {
// Always show live coordinates in step 6 and use crosshair cursor
canvas.style.cursor = 'crosshair';
if (S.warpMode && S._warpVP) {
const rw = c2rw(cp.x, cp.y);
const tip = document.getElementById('coord-tip');
tip.style.display = 'block';
tip.style.left = (cp.x+14)+'px';
tip.style.top = (cp.y-28)+'px';
tip.textContent = `X: ${rw.rx.toFixed(1)} ${S.dims.unit} Y: ${rw.ry.toFixed(1)} ${S.dims.unit}`;
} else if (S.H) {