-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathindex.html
1164 lines (1052 loc) · 43 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
function p3( x, y, z ) { return { x:x, y:y, z:z }; }
function p2( x, y ) { return { x:x, y:y }; }
function origin() { return p3(0,0,0); }
function xaxis() { return p3(1,0,0); }
function yaxis() { return p3(0,1,0); }
function zaxis() { return p3(0,0,0); }
function add( a, b ) { return p3( a.x + b.x, a.y + b.y, a.z + b.z ); }
function sub( a, b ) { return p3( a.x - b.x, a.y - b.y, a.z - b.z ); }
function mul( a, f ) { return p3( a.x * f, a.y * f, a.z * f ); }
function dot( a, b ) { return a.x * b.x + a.y * b.y + a.z * b.z; }
function len2( a ) { return dot(a,a); }
function dist( a, b ) { return Math.sqrt( len2( sub( a, b ) ) ); }
function assign( a, b ) { a.x = b.x; a.y = b.y; a.z = b.z; }
function normalize( a ) { return mul( a, 1 / Math.sqrt( len2( a ) ) ); }
function cross( a, b ) { return p3( a.y * b.z - a.z * b.y, a.z*b.x - a.x * b.z, a.x * b.y - a.y * b.x ); }
function fuzz( a ) { var f = 0.01; return add( a, p3( Math.random()*2*f-f,Math.random()*2*f-f,Math.random()*2*f-f) ) }
function mid( a, b ) { return mul( add( a, b ), 0.5 ); }
var theta;
var view_height;
var camera;
var isSpinning = true;
var canvas;
var ctx;
var verts = [];
var vel = []; // velocity of each vert
var edges = []; // pairs of vert indices
var neighbors = [];
var faces = []; // list of vert indices
var pending_commands = [];
var current_pattern = "";
var verts2d = [];
var box_verts = [ p3(-10,-10,-10), p3(-10,10,-10), p3(10,10,-10), p3(10,-10,-10), p3(-10,-10,10), p3(-10,10,10), p3(10,10,10), p3(10,-10,10) ];
var box_verts2d = [];
var box_edges = [ [0,1], [1,2], [2,3], [3,0], [4,5], [5,6], [6,7], [7,4], [0,4], [1,5], [2,6], [3,7] ];
var target_mesh = {
verts: [], // each: { p3: p3, p2: p3, edges: [] } N.B. here edges is a sparse array (contains undefined)
edges: [], // each: { verts: [], faces: [] }
faces: [], // each: { verts: [], edges: [], visited: bool }
};
var stitch_path = [];
var animationRequestID = undefined;
var target_edge_length = 1.0;
var inflate = false;
var draw_target_mesh = true;
function clear() {
// clear the existing pattern
verts = [];
verts2d = [];
vel = [];
edges = [];
neighbors = [];
faces = [];
pending_commands = [];
current_pattern = "";
target_mesh = {
verts: [], // each: { p3: p3, p2: p3, edges: [], faces: [] } N.B. here edges is a sparse array (contains undefined)
edges: [], // each: { verts: [], faces: [] }
faces: [], // each: { verts: [], edges: [], visited: bool }
};
stitch_path = [];
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return p2( evt.clientX - rect.left, evt.clientY - rect.top );
}
function onMouseMove( evt ) {
var pos = getMousePos( canvas, evt );
view_height = ( canvas.height / 2.0 - pos.y ) / canvas.height;
repositionCamera();
}
function onMouseDown( evt ) {
var pos = getMousePos( canvas, evt );
isSpinning = !isSpinning;
if( animationRequestID && isSpinning ) animate();
}
function onMouseUp( evt ) {
redraw();
}
function repositionCamera() {
var look_at = p3(0,0,0);
var d = 40;
var vd = d * view_height;
var hd = Math.sqrt( d*d - vd*vd );
camera.p = p3( hd*Math.cos(theta), hd*Math.sin(theta), vd );
camera.z = normalize( sub( look_at, camera.p ) );
var up = p3(0,0,1);
camera.x = normalize( cross( camera.z, up ) );
camera.y = normalize( cross( camera.x, camera.z ) );
}
function pointInRect( p, rect ) {
return p.x > rect.x && p.x < ( rect.x + rect.width ) &&
p.y > rect.y && p.y < ( rect.y + rect.height );
}
function add_stitch( p) {
verts.push( fuzz( p ) );
vel.push( p3(0,0,0) );
neighbors.push( [] );
}
function make_edge(i,j) {
edges.push( [i,j] );
neighbors[i].push( j );
neighbors[j].push( i );
}
function make_face3(i,j,k) {
faces.push( [i,j,k] );
}
function make_face4(i,j,k,m) {
faces.push( [i,j,k,m] );
}
function add_possible_face( i, j, k ) {
// verts i,j,k have been joined by two edges ij and jk. does this make a face?
if( neighbors[i].indexOf(k) > -1 )
// i and k are already joined, so we have a triangle
make_face3(i,j,k);
else {
// is there a fourth vertex connected to both i and k that make a quad? (there may be more than one)
for( var m = 0; m < verts.length; ++m ) {
if( m==i || m==j || m==k ) continue;
if( neighbors[i].indexOf(m) > -1 && neighbors[k].indexOf(m) > -1 )
make_face4(i,j,k,m);
}
}
}
// make a chain stitch into empty space
function chain( same_location ) {
if( verts.length < 1 ) {
add_stitch( p3(0,0,0) );
}
else if( verts.length < 2 ) {
add_stitch( p3(target_edge_length,0,0) );
make_edge( 0, 1 );
}
else
{
// keep going in the same direction
var iParent = verts.length-1;
var iGrandparent = verts.length-2;
if( same_location )
add_stitch( verts[iParent] );
else
add_stitch( add( verts[iParent], normalize( sub( verts[iParent], verts[iGrandparent] ) ) ) );
make_edge( iParent, iParent+1 );
}
}
// use a slip stitch to join with the stitch of index i
function join( i ) {
make_edge( verts.length-1, i );
}
function join_relative( ir ) {
join( verts.length + ir );
}
function single_crochet_with( i ) {
// try to put it somewhere sensible:
// at midpoint between joined stitch and natural extension:
add_stitch( mid( mid( verts[ verts.length-1 ], verts[ i ] ), add( verts[verts.length-1], normalize( sub( verts[verts.length-1], verts[verts.length-2] ) ) ) ) );
make_edge( verts.length-1, i );
make_edge( verts.length-1, verts.length-2 );
add_possible_face( i, verts.length-1, verts.length-2 );
}
function single_crochet_with_relative( ir ) {
single_crochet_with( verts.length + ir - 1 );
}
function single_crochet_with_two_relative( ir1, ir2 ) {
var i1 = verts.length - 1 + ir1;
var i2 = verts.length - 1 + ir2;
single_crochet_with( i1 );
make_edge( verts.length-1, i2 );
make_edge( i1, i2 ); // this stitch adds an extra edge pulling the two joined ones together
make_face3( verts.length-1, i1, i2 );
add_possible_face( i1, verts.length-1, verts.length-2 );
add_possible_face( i2, verts.length-1, verts.length-2 );
}
function doNextStitch( same_location ) {
if( !pending_commands || pending_commands.length == 0 ) return;
var command = pending_commands.shift();
if( !command || command.length == 0 ) return;
var tokens = command.match( /(c)|(sc)(-\d+)(-\d+)|(sc)(-\d+)/ );
if( !tokens ) { alert( 'Unknown command: ' + command ); pending_commands = []; }
if( tokens[1]=='c') {
chain( same_location );
}
else if( tokens[2]=='sc' ) {
single_crochet_with_two_relative( parseInt( tokens[3] ), parseInt( tokens[4] ) );
}
else if( tokens[5]=='sc' ) {
single_crochet_with_relative( parseInt( tokens[6] ) );
}
else {
alert( 'Unknown command: ' + command );
pending_commands = [];
}
}
// too close = repulsion, too far = attraction
function get_connection_force_on_a( a, b ) {
var x = sub( a, b );
var ab2 = len2( x );
var ab = Math.sqrt( ab2 );
var k = 0.3;
var d = target_edge_length;
return mul( x, k * ( d - ab ) / ab );
}
// too close = weak repulsion
function get_weak_repulsion_force_on_a( a, b ) {
var x = sub( a, b );
var ab2 = len2( x );
var d = 8 * target_edge_length;
if( ab2 < d*d ) {
var k = 0.001;
var ab = Math.sqrt( ab2 );
return mul( x, k * ( d - ab ) / ab );
}
return p3(0,0,0);
}
// move the verts a little in the direction of sum of the forces acting on them
function relax() {
// damp the speed
for( var a = 0; a < verts.length; ++a )
vel[a] = mul( vel[a], 0.97 );
// add a spring force along edges
for( var i = 0; i < edges.length; ++i ) {
a = edges[i][0];
b = edges[i][1];
// add the spring forces from this edge
var m = get_connection_force_on_a( verts[a], verts[b] );
vel[a] = add( vel[a], m );
vel[b] = sub( vel[b], m );
}
if( inflate ) {
// I... I stumbled across this by a coding error. Adding an inflationary term seems to make all the difference.
var k = 0.001;
for( var i = 0; i < verts.length; ++i ) {
vel[i] = add( vel[i], mul( normalize( verts[i] ), k ) );
}
}
// add a weak repulsion from every second-neighbor
for( var a = 0; a < verts.length; ++a ) {
for( var iN = 0; iN < neighbors[a].length; ++iN ) {
var n = neighbors[a][iN];
for( var iNN = 0; iNN < neighbors[n].length; ++iNN ) {
var nn = neighbors[n][iNN];
if( nn == a ) continue;
var m = get_weak_repulsion_force_on_a( verts[a], verts[nn] );
vel[a] = add( vel[a], m );
}
}
}
// apply the movement
var max_speed = 0;
for( var a = 0; a < verts.length; ++a )
{
var speed = Math.sqrt( len2( vel[a] ) );
if( speed > 0.2 )
vel[a] = mul( vel[a], 0.2 / speed );
verts[a] = add( verts[a], vel[a] );
max_speed = Math.max( speed, max_speed );
}
recenter();
return max_speed < 0.1; // have we relaxed enough?
}
function recenter() {
var c = p3(0,0,0);
for( var i = 0; i < verts.length; ++i )
c = add( c, verts[i] );
c = mul( c, 1/verts.length );
for( var i = 0; i < verts.length; ++i )
verts[i] = sub( verts[i], c );
}
function loadPattern( pattern ) {
current_pattern += pattern;
// remove optional characters
pattern.replace( /,\n\r/g, '' );
// expand out repeating sections
while(1) {
var end = pattern.indexOf(')');
if( end==-1) break;
var start = pattern.lastIndexOf('(',end);
if( start==-1) break;
var inside = pattern.substring(start+1,end);
var after = pattern.substr(end+1);
var digits_tokens = after.match(/\d+/);
if( !digits_tokens ) break;
var digits = digits_tokens[0];
var pre = pattern.substring(-1,start);
var post = pattern.substr( end+1+digits.length );
pattern = pre + new Array( parseInt(digits)+1 ).join( inside ) + post;
}
pending_commands = pending_commands.concat( pattern.match( /c|sc-\d+-\d+|sc-\d+/g ) );
}
function init() {
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
theta = Math.PI / 2;
view_height = 0.5;
camera = { p:p3(0,3,-6),
x:p3(1,0,0),
y:p3(0,1,0),
z:p3(0,0,1),
f:canvas.height,
pp:p2(canvas.width/2,canvas.height/2)
};
repositionCamera();
var pattern = "";
if( window.location.search.length > 0 ) {
pattern = window.location.search.replace( /\?/g, '' );
}
else {
var cylinder = "(c)21(sc-20)100";
pattern = cylinder;
}
loadPattern( pattern );
updateShareLink();
redraw();
canvas.addEventListener( 'mousemove', onMouseMove, false );
canvas.addEventListener( 'touchmove', onMouseMove, false );
canvas.addEventListener( 'touchstart', onMouseDown, false );
canvas.addEventListener( 'mousedown', onMouseDown, false );
canvas.addEventListener( 'touchend', onMouseUp, false );
canvas.addEventListener( 'mouseup', onMouseUp, false );
canvas.addEventListener( 'mouseout', onMouseUp, false );
animate();
}
function camera_projection( p, camera ) {
var ray = sub( p, camera.p ); // the ray from camera center to point
var cp = p3( dot( camera.x, ray ), dot( camera.y, ray ), dot( camera.z, ray ) ); // into camera space
return p3( cp.x * camera.f / cp.z + camera.pp.x,
canvas.height - ( cp.y * camera.f / cp.z + camera.pp.y ),
cp.z );
}
function redraw() {
drawMesh();
drawUI();
}
function point( p ) {
ctx.beginPath();
ctx.arc( p.x, p.y, 2, 0, 2.0 * Math.PI );
ctx.fill();
}
function drawMesh() {
// project the box onto the screen
for( var iVert = 0; iVert < box_verts.length; ++iVert ) {
box_verts2d[ iVert ] = camera_projection( box_verts[ iVert ], camera );
}
// project the stitch mesh onto the screen
for( var iVert = 0; iVert < verts.length; ++iVert ) {
verts2d[ iVert ] = camera_projection( verts[ iVert ], camera );
}
// project the target mesh onto the screen
if( draw_target_mesh ) {
for( var iVert = 0; iVert < target_mesh.verts.length; ++iVert ) {
target_mesh.verts[ iVert ].p2 = camera_projection( target_mesh.verts[ iVert ].p3, camera );
}
}
ctx.strokeStyle = "rgb(200,200,200)";
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.strokeRect(0, 0, canvas.width, canvas.height);
// draw the box edges
ctx.strokeStyle = "rgb(230,230,230)";
ctx.beginPath();
for( var i = 0; i < box_edges.length; ++i )
{
var a = box_verts2d[ box_edges[i][0] ];
var b = box_verts2d[ box_edges[i][1] ];
ctx.moveTo( a.x, a.y );
ctx.lineTo( b.x, b.y );
}
ctx.stroke();
// draw the stitch faces
ctx.fillStyle = "rgba(200,210,255,0.2)";
for( var iFace = 0; iFace < faces.length; ++iFace ) {
var a = verts2d[ faces[iFace][0] ];
ctx.beginPath();
ctx.moveTo( a.x, a.y );
for( var i = 1; i < faces[iFace].length; ++i ) {
a = verts2d[ faces[iFace][i] ];
ctx.lineTo( a.x, a.y );
}
ctx.fill();
}
if( draw_target_mesh ) {
// draw the target_mesh faces
ctx.fillStyle = "rgba(200,210,255,0.4)";
for( var iFace = 0; iFace < target_mesh.faces.length; ++iFace ) {
if( !target_mesh.faces[ iFace ].visited ) continue;
var a = target_mesh.verts[ target_mesh.faces[iFace].verts[0] ].p2;
ctx.beginPath();
ctx.moveTo( a.x, a.y );
for( var i = 1; i < target_mesh.faces[iFace].verts.length; ++i ) {
a = target_mesh.verts[ target_mesh.faces[iFace].verts[i] ].p2;
ctx.lineTo( a.x, a.y );
}
ctx.fill();
}
// draw the target mesh edges
ctx.strokeStyle = "rgba(0,0,0,0.2)";
ctx.beginPath();
for( var iEdge = 0; iEdge < target_mesh.edges.length; ++iEdge ) {
var a = target_mesh.verts[ target_mesh.edges[ iEdge ].verts[ 0 ] ].p2;
var b = target_mesh.verts[ target_mesh.edges[ iEdge ].verts[ 1 ] ].p2;
ctx.moveTo( a.x, a.y );
ctx.lineTo( b.x, b.y );
}
ctx.stroke();
}
// draw the stitch mesh edges
ctx.strokeStyle = "rgb(200,200,200)";
ctx.beginPath();
for( var i = 0; i < edges.length; ++i ) {
var a = verts2d[ edges[i][0] ];
var b = verts2d[ edges[i][1] ];
ctx.moveTo( a.x, a.y );
ctx.lineTo( b.x, b.y );
}
ctx.stroke();
if( draw_target_mesh ) {
// draw the stitch path
ctx.strokeStyle = "rgb(255,100,100)";
ctx.beginPath();
for( var i = 0; i < Math.min( verts.length, stitch_path.length-1); ++i ) {
var f1 = stitch_path[i];
var f2 = stitch_path[i+1];
var a = p3(0,0,0);
for( var j = 0; j < target_mesh.faces[f1].verts.length; ++j )
a = add( a, target_mesh.verts[ target_mesh.faces[f1].verts[j] ].p2 );
a = mul( a, 1.0 / target_mesh.faces[f1].verts.length );
var b = p3(0,0,0);
for( var j = 0; j < target_mesh.faces[f2].verts.length; ++j )
b = add( b, target_mesh.verts[ target_mesh.faces[f2].verts[j] ].p2 );
b = mul( b, 1.0 / target_mesh.faces[f2].verts.length );
ctx.moveTo( a.x, a.y );
ctx.lineTo( b.x, b.y );
}
ctx.stroke();
}
// draw the verts
ctx.fillStyle = "rgb(0,0,0)";
for( var i = 0; i < verts2d.length; ++i )
point( verts2d[i], "" );
}
function drawRect( x, y, w, h ) {
ctx.beginPath();
ctx.rect( x, y, w, h );
ctx.fill();
ctx.stroke();
}
function drawUI() {
if( pending_commands.length > 0 ) {
ctx.fillStyle = "rgba(0,0,0,0.2)";
ctx.font = "20px Arial";
ctx.fillText( 'Adding stitches (' + verts.length + " of " + (verts.length+pending_commands.length) + ") ...", 20, 30 );
}
}
function animate() {
if( isSpinning ) {
// rotate round
theta += 0.005;
repositionCamera();
}
var is_relaxed = relax();
if( is_relaxed )
doNextStitch( true );
redraw();
animationRequestID = requestAnimationFrame( animate );
}
function updateShareLink() {
var new_url = window.location.protocol + '//' + window.location.host + window.location.pathname + "?" + current_pattern;
document.getElementById('link').innerHTML = "Share this pattern: <a href=\""+new_url+"\">"+current_pattern+"</a>";
document.getElementById('current_stitches').value = current_pattern;
window.history.pushState( {}, "", new_url );
}
function addInputStitches() {
var new_stitches = document.getElementById('input_stitches').value;
if( new_stitches.length == 0 ) return;
loadPattern( new_stitches );
updateShareLink();
document.getElementById('input_stitches').value = "";
}
function setPattern() {
clear();
var new_pattern = document.getElementById('current_stitches').value;
loadPattern( new_pattern );
updateShareLink();
}
function setRowLengths() {
clear();
var lengths = document.getElementById('row_lengths').value.split(',').map(Number);
var pattern = makePatternFromRowLengths( lengths );
loadPattern( pattern );
updateShareLink();
}
function makePatternFromRowLengths( lengths ) {
// first row: make a loop by chaining and a single crochet at the end
var n = lengths[0];
var pattern = "(c)" + (n-1).toFixed(0) + "sc-" + (n-2).toFixed(0);
var pending_stitch = "";
var n_pending = 0;
// other rows: spiral round, increasing and decreasing as necessary
for( iRow = 1; iRow < lengths.length; ++iRow ) {
var x1 = lengths[ iRow-1 ];
var x2 = lengths[ iRow ];
var dy = x2 - x1;
var prev_ri = 0;
for( var i = 0; i < x2; ++i ) {
var ri = -x1 - Math.round( i * dy / x2 ) + 1;
var new_stitch = "";
if( ri == prev_ri + 1 )
new_stitch = "sc" + prev_ri.toFixed(0) + ri.toFixed(0); // invisible decrease
else
new_stitch += "sc" + ri.toFixed(0);
if( new_stitch == pending_stitch )
n_pending++;
else {
// flush the pending buffer
if( n_pending > 1 )
pattern += "(" + pending_stitch + ")" + n_pending.toFixed(0);
else
pattern += pending_stitch;
// push the new stitch onto the buffer
n_pending = 1;
pending_stitch = new_stitch;
}
prev_ri = ri;
}
}
if( n_pending > 1 )
pattern += "(" + pending_stitch + ")" + n_pending.toFixed(0);
else
pattern += pending_stitch;
return pattern;
}
function setTargetMesh() {
clear();
if( animationRequestID ) {
cancelAnimationFrame( animationRequestID );
animationRequestID = undefined;
}
// parse the lines of the OBJ
var mesh_text = document.getElementById('target_mesh').value.split('\n');
for( var iLine = 0; iLine < mesh_text.length; ++iLine ) {
var entries = mesh_text[ iLine ].split(' ');
if( entries[0] == 'v' ) {
target_mesh.verts.push( { p3: p3( parseFloat( entries[1] ), parseFloat( entries[2] ), parseFloat( entries[3] ) ), edges: [], faces: [] } );
}
else if( entries[0] == 'f' ) {
var ids = [];
for( var iEntry = 1; iEntry < entries.length; ++iEntry ) {
var iVert = parseInt( entries[ iEntry ] ) - 1; // (OBJ indices are 1-based)
ids.push( iVert );
}
target_mesh.faces.push( { verts: ids, edges: [], visited: false } );
var iFace = target_mesh.faces.length - 1;
for( var i = 0; i < ids.length; ++i ) {
var iVert1 = ids[ i ];
target_mesh.verts[ iVert1 ].faces.push( iFace );
var iVert2 = ids[ (i+1)%ids.length ];
// does this edge already exist?
if( typeof target_mesh.verts[ iVert1 ].edges[ iVert2 ] != 'undefined' ) {
var iEdge = target_mesh.verts[ iVert1 ].edges[ iVert2 ];
target_mesh.edges[ iEdge ].faces.push( iFace );
target_mesh.faces[ iFace ].edges.push( iEdge );
}
else {
// make a new edge
target_mesh.edges.push( { verts: [ iVert1, iVert2 ], faces: [ iFace ] } );
var iEdge = target_mesh.edges.length - 1;
target_mesh.verts[ iVert1 ].edges[ iVert2 ] = iEdge;
target_mesh.verts[ iVert2 ].edges[ iVert1 ] = iEdge;
target_mesh.faces[ iFace ].edges.push( iEdge );
}
}
}
}
// recenter
var c = p3(0,0,0);
for( var iVert = 0; iVert < target_mesh.verts.length; ++iVert ) {
c = add( c, target_mesh.verts[iVert].p3 );
}
c = mul( c, 1.0 / target_mesh.verts.length );
for( var iVert = 0; iVert < target_mesh.verts.length; ++iVert )
target_mesh.verts[iVert].p3 = sub( target_mesh.verts[iVert].p3, c );
// scale
var mr = 0;
for( var iVert = 0; iVert < target_mesh.verts.length; ++iVert ) {
mr = Math.max( mr, Math.sqrt( len2( target_mesh.verts[iVert].p3 ) ) );
}
for( var iVert = 0; iVert < target_mesh.verts.length; ++iVert )
target_mesh.verts[iVert].p3 = mul( target_mesh.verts[iVert].p3, 12 / mr );
// check
if( !checkTargetMeshIntegrity() ) {
clear();
return;
}
// make stitch path
makeStitchPathForTargetMesh();
// make crochet pattern and display it
var pattern = makePatternFromStitchPath();
loadPattern( pattern );
document.getElementById('link').innerHTML = "";
document.getElementById('current_stitches').value = "";
var new_url = window.location.protocol + '//' + window.location.host + window.location.pathname;
window.history.pushState( {}, "", new_url );
// for larger patterns is better to connect the whole mesh and then relax it
while( pending_commands.length > 0 )
doNextStitch( true );
// also put each vert into the right position on the target mesh before relaxing
var mean_stitch_length = 0.0;
var mean_stitch_length_count = 0;
for( var iVert = 0; iVert < verts.length; ++iVert ) {
verts[ iVert ] = getFaceCenter( stitch_path[ iVert ] );
if( iVert > 0 ) {
mean_stitch_length += dist( verts[ iVert ], verts[ iVert-1 ] );
mean_stitch_length_count++;
}
}
target_edge_length = mean_stitch_length / mean_stitch_length_count;
document.getElementById('current_stitches').value = current_pattern;
animate();
}
function checkTargetMeshIntegrity() {
// for each vert: same number of edges and faces? and >2?
for( var iVert = 0; iVert < target_mesh.verts.length; ++iVert ) {
if( getDefinedCount( target_mesh.verts[ iVert ].edges ) != target_mesh.verts[ iVert ].faces.length ) {
alert( 'Mesh has mismatch edge:face count around a vertex.' );
return false;
}
if( target_mesh.verts[ iVert ].faces.length <= 2 ) {
alert( 'Mesh has < 3 faces around vertex ' + iVert.toFixed() );
return false;
}
}
// for edges: does each edge join exactly two faces?
for( var iEdge = 0; iEdge < target_mesh.edges.length; ++iEdge ) {
if( typeof target_mesh.edges[ iEdge ] == 'undefined' )
continue; // (edges is a sparse array)
if( target_mesh.edges[ iEdge ].verts.length != 2 ) {
alert( 'Internal error loading mesh.' );
return false;
}
if( target_mesh.edges[ iEdge ].faces.length != 2 ) {
alert( 'Mesh has a non-manifold edge.' );
return false;
}
}
// for faces: number of edges and verts == 3?
for( var iFace = 0; iFace < target_mesh.faces.length; ++iFace ) {
if( target_mesh.faces[ iFace ].edges.length != 3 ) {
alert( 'Mesh has a non-triangular face.' );
return false;
}
if( target_mesh.faces[ iFace ].verts.length != 3 ) {
alert( 'Mesh has a non-triangular face.' );
return false;
}
}
return true;
}
function makeStitchPathForTargetMesh() {
// start the stitch path with something
var iEnd = Math.floor( Math.random() * target_mesh.faces.length );
stitch_path = [ iEnd ];
target_mesh.faces[ iEnd ].visited = true;
growStitchPathEnd();
while( true ) {
growStitchPathMiddle();
var flipped = flipAnUnvisitedTriangle();
if( !flipped )
break;
}
// any left unvisited?
var num_unvisited = 0;
for( var iFace = 0; iFace < target_mesh.faces.length; ++iFace )
if( !target_mesh.faces[ iFace ].visited )
++num_unvisited;
if( num_unvisited > 0 )
alert( 'Num unvisited faces: ' + num_unvisited.toFixed() );
}
function growStitchPathEnd() {
var iEnd = stitch_path[ stitch_path.length - 1 ];
while( true ) {
// find candidates: neighbors of this face that we haven't visited yet
var candidates = [];
for( var iiEdge = 0; iiEdge < target_mesh.faces[ iEnd ].edges.length; ++iiEdge ) {
var iEdge = target_mesh.faces[ iEnd ].edges[ iiEdge ];
for( var iiFace = 0; iiFace < target_mesh.edges[ iEdge ].faces.length; ++iiFace ) {
var iFace = target_mesh.edges[ iEdge ].faces[ iiFace ];
if( iFace != iEnd && !target_mesh.faces[ iFace ].visited ) {
candidates.push( { face: iFace, edge: iEdge } );
}
}
}
if( candidates.length == 0 )
break;
// pick the best candidate
var iBest = 0;
var most_visited_neighbors = 0;
for( var iCandidate = 0; iCandidate < candidates.length; ++iCandidate ) {
var num_visited_neighbors = getNumberOfVisitedIndirectFaceNeighbors( candidates[ iCandidate ].face );
if( num_visited_neighbors > most_visited_neighbors ) {
most_visited_neighbors = num_visited_neighbors;
iBest = iCandidate;
}
}
// extend
iEnd = candidates[ iBest ].face;
var crossed_edge = candidates[ iBest ].edge;
stitch_path.push( iEnd );
target_mesh.faces[ iEnd ].visited = true;
}
}
function growStitchPathMiddle() {
while( true ) {
var extended = false;
for( var iiStitch = 0; iiStitch < stitch_path.length - 1; ++iiStitch ) {
// can we grow this stitch by extending sideways around a vert?
var iFace1 = stitch_path[ iiStitch ];
var iFace2 = stitch_path[ iiStitch+1 ];
var iEdge = getSharedEdge( iFace1, iFace2 );
if( iEdge == -1 )
break; // this shouldn't happen
// find the two vertices in the target mesh at the end of the edge that this stitch crosses
var iVert1 = target_mesh.edges[ iEdge ].verts[0];
var iVert2 = target_mesh.edges[ iEdge ].verts[1];
var num_vert_neighbors1 = getNumberOfVisitedVertNeighbors( iVert1 );
if( num_vert_neighbors1 == 2 && target_mesh.verts[ iVert1 ].faces.length > 2 ) {
extendStitchAroundVert( iiStitch, iVert1 );
extended = true;
break;
}
var num_vert_neighbors2 = getNumberOfVisitedVertNeighbors( iVert2 );
if( num_vert_neighbors2 == 2 && target_mesh.verts[ iVert2 ].faces.length > 2 ) {
extendStitchAroundVert( iiStitch, iVert2 );
extended = true;
break;
}
}
if( !extended )
break;
}
}
function flipAnUnvisitedTriangle() {
// TODO: prefer longer edges (better shape when split)
for( var iUnvisitedFace = 0; iUnvisitedFace < target_mesh.faces.length; ++iUnvisitedFace ) {
var unvisited_face = target_mesh.faces[ iUnvisitedFace ];
if( unvisited_face.visited ) continue;
// find an edge that joins us to a visited face
for( var iiEdge = 0; iiEdge < unvisited_face.edges.length; ++iiEdge ) {
var iEdge = unvisited_face.edges[ iiEdge ];
var edge_faces = target_mesh.edges[ iEdge ].faces;
var iOtherFace = ( edge_faces[0] == iUnvisitedFace ) ? edge_faces[1] : edge_faces[0];
if( target_mesh.faces[ iOtherFace].visited ) {
// found a visited/unvisited pair of neighboring faces
return flipUnvisitedTriangle( iUnvisitedFace, iOtherFace, iEdge );
}
}
}
return false; // no unvisited face found
}
function flipUnvisitedTriangle( iUnvisitedFace, iVisitedFace, iEdge ) {
// view the two neighboring triangles as left and right halves of a diamond,
// with stitch path entering top left and exiting bottom left, then:
// edges are iEdgeA, iEdgeB, iEdgeC, iEdgeD (clockwise from top-left)
// verts are iVert1, iVert2, iVert3, iVert4 (clockwise from top)
// will rotate vertical iEdge in the middle to be horizontal, with the stitch path passing through both triangles
var iStitch = stitch_path.indexOf( iVisitedFace );
if( iStitch == 0 || iStitch == stitch_path.length-1 ) throw "unhandled flip case";
var iEdgeA = getSharedEdge( iVisitedFace, stitch_path[ iStitch - 1 ] );
var iEdgeD = getSharedEdge( iVisitedFace, stitch_path[ iStitch + 1 ] );
var iTempVert1 = target_mesh.edges[ iEdge ].verts[ 0 ];
var iTempVert2 = target_mesh.edges[ iEdge ].verts[ 1 ];
var iVert1,iVert2,iVert3,iVert4;
if( target_mesh.edges[ iEdgeA ].verts.indexOf( iTempVert1 ) > -1 ) {
iVert1 = iTempVert1;
iVert3 = iTempVert2;
}
else {
iVert1 = iTempVert2;
iVert3 = iTempVert1;
}
iVert4 = getOtherVert( iVisitedFace, iVert1, iVert3 );
iVert2 = getOtherVert( iUnvisitedFace, iVert1, iVert3 );
var iEdgeB = target_mesh.verts[ iVert1 ].edges[ iVert2 ];
var iEdgeC = target_mesh.verts[ iVert2 ].edges[ iVert3 ];
if( typeof iEdgeB == 'undefined' || typeof iEdgeC == 'undefined' )
throw "flipUnvisitedTriangle internal error retrieving edge index";
// now perform surgery on the mesh:
// vert faces:
i = target_mesh.verts[ iVert1 ].faces.indexOf( iUnvisitedFace );
if( i < 0 )
throw "flipUnvisitedTriangle internal error retrieving index";
target_mesh.verts[ iVert1 ].faces.splice( i, 1 );
target_mesh.verts[ iVert2 ].faces.push( iVisitedFace );
i = target_mesh.verts[ iVert3 ].faces.indexOf( iVisitedFace );
if( i < 0 )
throw "flipUnvisitedTriangle internal error retrieving index";
target_mesh.verts[ iVert3 ].faces.splice( i, 1 );
target_mesh.verts[ iVert4 ].faces.push( iUnvisitedFace );
// vert edges: (indexed by vert)
delete target_mesh.verts[ iVert1 ].edges[ iVert3 ];
target_mesh.verts[ iVert2 ].edges[ iVert4 ] = iEdge;
delete target_mesh.verts[ iVert3 ].edges[ iVert1 ];
target_mesh.verts[ iVert4 ].edges[ iVert2 ] = iEdge;
// edge verts:
target_mesh.edges[ iEdge ].verts = [ iVert2, iVert4 ];
// edge faces:
i = target_mesh.edges[ iEdgeB ].faces.indexOf( iUnvisitedFace );
if( i < 0 )
throw "flipUnvisitedTriangle internal error retrieving index";
target_mesh.edges[ iEdgeB ].faces.splice( i, 1, iVisitedFace );
i = target_mesh.edges[ iEdgeD ].faces.indexOf( iVisitedFace );
if( i < 0 )
throw "flipUnvisitedTriangle internal error retrieving index";
target_mesh.edges[ iEdgeD ].faces.splice( i, 1, iUnvisitedFace );
// face verts:
target_mesh.faces[ iVisitedFace ].verts = [ iVert1, iVert2, iVert4 ];
target_mesh.faces[ iUnvisitedFace ].verts = [ iVert2, iVert3, iVert4 ];
// face edges:
target_mesh.faces[ iVisitedFace ].edges = [ iEdgeA, iEdgeB, iEdge ];
target_mesh.faces[ iUnvisitedFace ].edges = [ iEdge, iEdgeC, iEdgeD ];
// insert the new face into the stitch path
stitch_path.splice( iStitch+1, 0, iUnvisitedFace );
target_mesh.faces[ iUnvisitedFace ].visited = true;
return true;
}
function getOtherVert( iFace, iVert1, iVert2 ) {
for( var iiVert = 0; iiVert < target_mesh.faces[ iFace ].verts.length; ++iiVert ) {
var iVert = target_mesh.faces[ iFace ].verts[ iiVert ];
if( iVert != iVert1 && iVert != iVert2 )
return iVert;
}
throw "getOtherVert fail";
}
function extendStitchAroundVert( iStartStitch, iVert ) {
// re-route the stitch path around the other side of iVert
var iStartFace = stitch_path[ iStartStitch ];
var iEndFace = stitch_path[ iStartStitch + 1 ];
// insert an unvisited face that is a neighbor of iEndFace and has iVert as a vert, while one exists
var added = false;
while( true ) {
added = false;
for( var iiFace = 0; iiFace < target_mesh.verts[ iVert ].faces.length; ++iiFace ) {
var iFace = target_mesh.verts[ iVert ].faces[ iiFace ];
var iEdge = getSharedEdge( iFace, iEndFace );
if( !target_mesh.faces[ iFace ].visited && iEdge > -1 )
{
// insert the new stitch into the path
stitch_path.splice( iStartStitch + 1, 0, iFace ); // (insert just before iStartStitch+1)
target_mesh.faces[ iFace ].visited = true;
iEndFace = iFace;
added = true;
break;
}
}
if( !added ) break;
}
}
function stitchPathIsValid() {
for( var iiStitch2 = 0; iiStitch2 < stitch_path.length - 1; ++iiStitch2 ) {
// can we grow this stitch by extending sideways around a vert?
var iFace1 = stitch_path[ iiStitch2 ];
var iFace2 = stitch_path[ iiStitch2 + 1 ];
var iEdge = getSharedEdge( iFace1, iFace2 );
if( iEdge == -1 )
return false;
}
return true;
}
function getSharedEdge( iFace1, iFace2 ) {
for( var iiEdge = 0; iiEdge < target_mesh.faces[ iFace1 ].edges.length; ++iiEdge ) {
var iEdge = target_mesh.faces[ iFace1 ].edges[ iiEdge ];
if( target_mesh.edges[ iEdge ].faces.indexOf( iFace2 ) > -1 )
return iEdge;
}
return -1;
}
function getNumberOfVisitedIndirectFaceNeighbors( iCenterFace ) {
var num_visited_neighbors = 0;
for( var iiVert = 0; iiVert < target_mesh.faces[ iCenterFace ].verts.length; ++iiVert ) {
var iVert = target_mesh.faces[ iCenterFace ].verts[ iiVert ];
for( var iiFace = 0; iiFace < target_mesh.verts[ iVert ].faces.length; ++iiFace ) {
var iFace = target_mesh.verts[ iVert ].faces[ iiFace ];
if( target_mesh.faces[ iFace ].visited )
num_visited_neighbors++; // double+-counting but we don't mind too much for now
}
}
return num_visited_neighbors;
}
function getNumberOfVisitedVertNeighbors( iVert ) {
var num_visited_faces = 0;
for( var iiFace = 0; iiFace < target_mesh.verts[ iVert ].faces.length; ++iiFace ) {
var iFace = target_mesh.verts[ iVert ].faces[ iiFace ];
if( target_mesh.faces[ iFace ].visited )
num_visited_faces++;
}
return num_visited_faces;
}
function getDefinedCount( arr ) {
var n = 0;
for( var i = 0; i < arr.length; ++i ) {
if( typeof arr[i] != 'undefined' )
n++;
}
return n;
}
function makePatternFromStitchPath() {
var pattern = "(c)2"; // chain for first two stitches
var pending_stitch = "";
var n_pending = 0;
var new_stitch = "";
for( var iStitch = 2; iStitch < stitch_path.length-1; ++iStitch ) {
var faces = getFaceNeighbors( stitch_path[ iStitch ] );
faces.splice( faces.indexOf( stitch_path[ iStitch - 1 ] ), 1 ); // remove the previous face in the stitch path
faces.splice( faces.indexOf( stitch_path[ iStitch + 1 ] ), 1 ); // remove the next face in the stitch path
var iOtherFace = faces[0];
var iOtherStitch = stitch_path.indexOf( iOtherFace );
if( iOtherStitch < iStitch ) {