This repository has been archived by the owner on Jul 22, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
sheetengine-src-1.2.0.js
3622 lines (3200 loc) · 142 KB
/
sheetengine-src-1.2.0.js
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
/*
sheetengine v1.2.0
Isometric HTML5 JavaScript Display Engine
sheetengine.codeplex.com
Licensed under the MIT license.
Copyright (C) 2012 Levente Dobson
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var sheetengine = (function() {
var sheetengine = {
sheets: [],
basesheets: [],
polygons: [],
objects: [],
currentSheet: -1,
hoverSheet: -1,
canvas: null,
context: null,
canvasCenter: {u:250,v:260}, // main canvas center
viewSource: { x: -1, y: -1, z: -Math.SQRT1_2 },
tempCanvasSize: {w:115,h:115}, // 115x115: max extent of a 80x80 sheet. the size of the temp canvas used when background is redrawn
backgroundColor: '#FFF',
drawObjectContour: false,
boundingBoxMaxsheetDistance: 150,
objectsintersect: false,
debug: false
};
var startsheets = [];
var loadedyards = {};
var staticsheets = null;
// ===================================================================================================
// shadows
var shadows = {};
sheetengine.shadows = shadows;
shadows.baseshadowCanvas = null;
shadows.baseshadowContext = null;
shadows.baseShadowCenter = {u:212,v:2*106};
shadows.lightSource = { x: 1, y: -3, z: -10 };
shadows.lightSourcep1 = { x: 1, y: -3, z: 1 }; // perpendicular to lightsource, scalar prod is 0 : 1x -3y -10z = 0
shadows.lightSourcep2 = { x: -33, y: 11, z: 0 }; // perpendicular both to lightsource and p1 (ls x p1 = p2)
shadows.shadowAlpha = 0.3;
shadows.shadeAlpha = 0.3; // should be the same as shadowalpha, since a shaded sheet counts as if it was in shadow
shadows.drawShadows = true;
function calculateSheetBaseShadow(sheet) {
var s = sheet;
// calculate centerp-p0-p1-p2 crossing with baserect
// vector of light source
var l = shadows.lightSource;
var centerp = { x: s.centerp.x, y: s.centerp.y, z: s.centerp.z };
var p0 = { x: centerp.x + s.p0.x, y: centerp.y + s.p0.y, z: centerp.z + s.p0.z };
var p1 = { x: centerp.x + s.p1.x, y: centerp.y + s.p1.y, z: centerp.z + s.p1.z };
var p2 = { x: centerp.x + s.p2.x, y: centerp.y + s.p2.y, z: centerp.z + s.p2.z };
var tc = centerp.z / -l.z;
var t0 = p0.z / -l.z;
var t1 = p1.z / -l.z;
var t2 = p2.z / -l.z;
var centerpsect = { x: centerp.x + l.x*tc, y: centerp.y + l.y*tc, z: centerp.z + l.z*tc };
var p0sect = { x: p0.x + l.x*t0 - centerpsect.x, y: p0.y + l.y*t0 - centerpsect.y, z: p0.z + l.z*t0 - centerpsect.z };
var p1sect = { x: p1.x + l.x*t1 - centerpsect.x, y: p1.y + l.y*t1 - centerpsect.y, z: p1.z + l.z*t1 - centerpsect.z };
var p2sect = { x: p2.x + l.x*t2 - centerpsect.x, y: p2.y + l.y*t2 - centerpsect.y, z: p2.z + l.z*t2 - centerpsect.z };
// calculate transformation for shadow rectangle
s.baseShadoweData = calculateSheetDataSingle(centerpsect, p0sect, p1sect, p2sect, transforms.transformPoint, transforms.transformPointz, shadows.baseShadowCenter, s.corners);
s.baseShadoweData.translatex -= scene.center.u;
s.baseShadoweData.translatey -= scene.center.v;
};
function checkDirtyShadowConstraint(prev, dirtySheets) {
for (var i=0;i<sheetengine.sheets.length;i++) {
var sheet = sheetengine.sheets[i];
// dirty sheets will surely be processed later
if (sheet.dirty)
continue;
if (sheet.hidden)
continue;
// initialize sheet's flag in first phase only
if (prev)
sheet.shadowdirty = false;
else
{
// if sheet has already been marked in the first phase, it's canvas will be redrawn anyway
if (sheet.shadowdirty)
continue;
}
for (var j=0;j<sheet.polygons.length; j++) {
var sheetpoly = sheet.polygons[j];
var shadowconstraints = prev ? sheetpoly.prevshadowconstraints : sheetpoly.shadowconstraints;
if (shadowconstraints == null) {
sheet.shadowdirty = true;
break;
}
for (var k=0;k<shadowconstraints.length;k++) {
var sheetconstraint = sheetengine.polygons[shadowconstraints[k]].sheetindex;
if (dirtySheets.indexOf(sheetconstraint) != -1) {
sheet.shadowdirty = true;
break;
}
}
if (sheet.shadowdirty)
break;
}
}
};
function initBaseRectShadow(ctx, size, rel, viewport) {
if (!shadows.drawShadows)
return;
// clear baserectshadow canvases
ctx.clearRect(0,0,size.w,size.h);
// draw sheet shadows cast on baserect to baserectcanvases
for (var i=0;i<sheetengine.sheets.length;i++) {
var s = sheetengine.sheets[i];
if (s.hidden)
continue;
if (!s.castshadows)
continue;
if (viewport) {
var sheetdata = s.data;
if (sheetdata.centerpuv.u < viewport.minu || sheetdata.centerpuv.u > viewport.maxu || sheetdata.centerpuv.v < viewport.minv || sheetdata.centerpuv.v > viewport.maxv)
continue;
}
s.baseShadoweData.translatex += rel.u;
s.baseShadoweData.translatey += rel.v;
drawing.drawRect(s.baseShadoweData, ctx, drawBaseShadowTexture, s.baseshadowcanvas, false);
s.baseShadoweData.translatex -= rel.u;
s.baseShadoweData.translatey -= rel.v;
}
};
function drawBaseRectShadow() {
// merge baserect and baserectshadow on visible canvases
sheetengine.context.save();
sheetengine.context.globalAlpha = shadows.shadowAlpha;
sheetengine.context.drawImage(shadows.baseshadowCanvas,sheetengine.canvasCenter.u-scene.tilesize.x,sheetengine.canvasCenter.v-2*scene.tilesize.y);
sheetengine.context.restore();
};
function drawSheetShadow(sheet) {
if (sheet.hidden)
return;
// shadow calculations for a shaded sheet can be skipped - we dont draw shadows on shaded sheets
var drawshadows = !sheet.shaded && shadows.drawShadows && sheet.allowshadows;
if (drawshadows) {
sheet.shadowtempcontext.clearRect(0, 0, sheet.width, sheet.height);
sheet.shadowData = [];
// draw all polygon shadow to shadowcanvas with given transformation
for (var j=0;j<sheet.polygons.length; j++) {
var sheetpoly = sheet.polygons[j];
var shadowconstraints = sheetpoly.shadowconstraints;
// go through shadowconstraints of the polygon: these will cast shadows on this polygon
var sheetsconstraints = [];
for (var k=0;k<shadowconstraints.length;k++) {
var shadowcaster = sheetengine.polygons[shadowconstraints[k]].sheetindex;
// more polygonconstraints can point to the same sheet.
// let's check if the current shadowcaster sheet has already been processed
if (sheetsconstraints.indexOf(shadowcaster) != -1)
continue;
sheetsconstraints.push(shadowcaster);
var shadowcastersheet = sheetengine.sheets[shadowcaster];
// only visible sheets cast shadows
if (shadowcastersheet.hidden)
continue;
if (!shadowcastersheet.castshadows)
continue;
// draw shadow on sheet's shadowtempcanvas
sheet.shadowtempcontext.save();
// set clipping area on sheet for current polygon
sheet.shadowtempcontext.beginPath();
for (var pi=0;pi<sheetpoly.points.length;pi++) {
sheet.shadowtempcontext.lineTo(sheetpoly.pointscanvasuv[pi].u, sheetpoly.pointscanvasuv[pi].v);
}
sheet.shadowtempcontext.closePath();
sheet.shadowtempcontext.clip();
// lazy initialize shadowdata for current sheet with respect to shadowcaster
if (sheet.shadowData[shadowcastersheet.index] == null)
sheet.shadowData[shadowcastersheet.index] = calculateShadowData(sheet, shadowcastersheet);
var sheetData = sheet.shadowData[shadowcastersheet.index];
sheet.shadowtempcontext.transform(sheetData.ta,sheetData.tb,sheetData.tc,sheetData.td,sheetData.translatex,sheetData.translatey);
sheet.shadowtempcontext.drawImage(shadowcastersheet.shadowcanvas, 0, 0);
sheet.shadowtempcontext.restore();
}
}
}
// draw original image and then shadows cast by other sheets onto composite context
sheet.compositecontext.save();
sheet.compositecontext.drawImage(sheet.canvas, 0, 0);
// draw own shadow to imitate shading
if (sheet.shaded) {
sheet.compositecontext.globalCompositeOperation = 'source-over';
sheet.compositecontext.globalAlpha = shadows.shadeAlpha;
sheet.compositecontext.drawImage(sheet.shadowcanvas, 0, 0);
} else {
var shadeThresh = 0;
if (sheet.shadealpha > shadeThresh) {
sheet.compositecontext.globalCompositeOperation = 'source-over';
sheet.compositecontext.globalAlpha = sheet.shadealpha;
sheet.compositecontext.drawImage(sheet.shadowcanvas, 0, 0);
} else {
sheet.compositecontext.globalCompositeOperation = 'source-atop';
sheet.compositecontext.globalAlpha = (shadeThresh - sheet.shadealpha * 6);
sheet.compositecontext.fillStyle = '#FFF';
sheet.compositecontext.fillRect(0,0,sheet.width,sheet.height);
}
}
if (drawshadows) {
// draw shadows cast by other sheets
// an alpha layer is already drawn (shade), so shadow alpha should be lessened with shade alpha to avoid sum of alphas
sheet.compositecontext.globalAlpha = shadows.shadowAlpha-sheet.shadealpha;
sheet.compositecontext.globalCompositeOperation = 'source-atop';
sheet.compositecontext.drawImage(sheet.shadowtempcanvas, 0, 0);
}
sheet.compositecontext.restore();
};
function calculateSheetsShadows(calculateAll) {
// determine sheet ordering from lightsource viewpoint
for (var i=0; i<sheetengine.sheets.length; i++) {
var sheet = sheetengine.sheets[i];
if (sheet.shadowdirty || sheet.dirty || calculateAll)
drawSheetShadow(sheet);
}
};
function calculateShadowData(sheet, shadowcaster) {
var s = shadowcaster;
var l = shadows.lightSource;
// calculate centerp-p0-p1-p2 crossing with baserect
// vector of light source
var centerp = { x: s.centerp.x, y: s.centerp.y, z: s.centerp.z };
var p0 = { x: s.centerp.x + s.p0.x, y: s.centerp.y + s.p0.y, z: s.centerp.z + s.p0.z };
var p1 = { x: s.centerp.x + s.p1.x, y: s.centerp.y + s.p1.y, z: s.centerp.z + s.p1.z };
var p2 = { x: s.centerp.x + s.p2.x, y: s.centerp.y + s.p2.y, z: s.centerp.z + s.p2.z };
// n*(r-r0) = 0
// sheet.normalp.x * (X - sheet.centerp.x) + sheet.normalp.y * (Y - sheet.centerp.y) + sheet.normalp.z * (Z - sheet.centerp.z) = 0
// p0 line : p0 + l*t --> X = p0.x + l.x*t
var tc = getTForSheetLineCrossing(sheet.normalp, sheet.centerp, centerp, l);
var t0 = getTForSheetLineCrossing(sheet.normalp, sheet.centerp, p0, l);
var t1 = getTForSheetLineCrossing(sheet.normalp, sheet.centerp, p1, l);
var t2 = getTForSheetLineCrossing(sheet.normalp, sheet.centerp, p2, l);
var centerpsect = { x: centerp.x + l.x*tc, y: centerp.y + l.y*tc, z: centerp.z + l.z*tc };
var p0sect = { x: p0.x + l.x*t0 - centerpsect.x, y: p0.y + l.y*t0 - centerpsect.y, z: p0.z + l.z*t0 - centerpsect.z };
var p1sect = { x: p1.x + l.x*t1 - centerpsect.x, y: p1.y + l.y*t1 - centerpsect.y, z: p1.z + l.z*t1 - centerpsect.z };
var p2sect = { x: p2.x + l.x*t2 - centerpsect.x, y: p2.y + l.y*t2 - centerpsect.y, z: p2.z + l.z*t2 - centerpsect.z };
// calculate transformation for shadow rectangle
var eData = calculateSheetDataSingle(centerpsect, p0sect, p1sect, p2sect, transforms.transformPoint, null, sheetengine.canvasCenter, null);
// sheet.data inverse transform:
var A1 = geometry.getBaseMatrixInverse({x:sheet.data.ta,y:sheet.data.tb,z:0},{x:sheet.data.tc,y:sheet.data.td,z:0},{x:sheet.data.translatex,y:sheet.data.translatey,z:1});
var C = multiplyMatrices(A1.b1,A1.b2,A1.b3, {x:eData.ta,y:eData.tb,z:0},{x:eData.tc,y:eData.td,z:0},{x:eData.translatex,y:eData.translatey,z:1});
var sheetData = { translatex: C.c3.x, translatey: C.c3.y, ta: C.c1.x, tb: C.c1.y, tc: C.c2.x, td: C.c2.y};
return sheetData;
};
function isSheetDark(sheet, viewSource) {
var v = viewSource;
var l = shadows.lightSource;
// check if sheet is back to lightsource and if its back to viewsource
// if its back to both or none: it is light
// if its back to only lihtsource or only viewsource: it is dark
var lightPoint = {x:sheet.centerp.x - (l.x*100), y:sheet.centerp.y - (l.y*100), z:sheet.centerp.z - (l.z*100) };
var viewPoint = {x:sheet.centerp.x - (v.x*100), y:sheet.centerp.y - (v.y*100), z:sheet.centerp.z - (v.z*100) };
// n*(r-r0) > 0 ? check for lightpoint
var nrr0 = sheet.normalp.x * (lightPoint.x - sheet.centerp.x) + sheet.normalp.y * (lightPoint.y - sheet.centerp.y) + sheet.normalp.z * (lightPoint.z - sheet.centerp.z);
// n*(r-r0) > 0 ? check for viewpoint
var nrr02 = -sheet.normalp.x * (viewPoint.x - sheet.centerp.x) - sheet.normalp.y * (viewPoint.y - sheet.centerp.y) - sheet.normalp.z * (viewPoint.z - sheet.centerp.z);
var backToLightSource = nrr0 < 0;
var backToViewSource = nrr02 < 0;
return (backToLightSource && backToViewSource) || (!backToLightSource && !backToViewSource);
};
function calculateSheetShade(sheet) {
if (!sheet.allowshadows) {
sheet.shaded = false;
sheet.shadealpha = 0;
return;
}
var l = shadows.lightSource;
var n = sheet.normalp;
var scale = 3;
// find enclosing angle between sheet normal and lightsource
// AB*sinT = AXB -> T = arcsin ( AXB / AB )
var axb = geometry.vectorMagnitude(crossProduct(l,n));
var ab = geometry.vectorMagnitude(l) * geometry.vectorMagnitude(n);
var t = Math.asin(axb/ab) / (Math.PI*scale);
// check if sheet is away from viewsource
sheet.shaded = isSheetDark(sheet, sheetengine.viewSource);
// set sheet shade: 1 full black, 0 full original color
sheet.shadealpha = t-0.05;
};
function drawBaseRectShadows(context, offset) {
if (!offset)
offset = {u:0,v:0};
context.save();
context.globalAlpha = shadows.shadowAlpha;
context.drawImage(shadows.baseshadowCanvas,offset.u,offset.v);
context.restore();
};
shadows.calculateSheetBaseShadow = calculateSheetBaseShadow;
shadows.initBaseRectShadow = initBaseRectShadow;
shadows.drawBaseRectShadow = drawBaseRectShadow;
shadows.calculateSheetsShadows = calculateSheetsShadows;
shadows.calculateSheetShade = calculateSheetShade;
// ===================================================================================================
// drawing functions
var drawing = {};
sheetengine.drawing = drawing;
// callbacks
drawing.drawBaseRect = null;
drawing.drawBeforeSheets = null;
drawing.drawAfterSheets = null;
drawing.useClipCorrection = false;
drawing.dimmedAlpha = 0.2; // rate at which sheets are dimmed if dimmer sheets get behind them
drawing.allowContourDrawing = true;
drawing.hoveredSheetColor = '#F80';
drawing.selectedSheetColor = '#00F';
drawing.selectrectlinewidth = 2;
function createCanvas(w, h) {
var canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
return canvas;
};
function redraw() {
sheetengine.context.clearRect(0,0, sheetengine.canvas.width, sheetengine.canvas.height);
if (drawing.drawBaseRect)
drawing.drawBaseRect();
if (shadows.drawShadows) {
shadows.initBaseRectShadow(shadows.baseshadowContext, {w:shadows.baseshadowCanvas.width, h:shadows.baseshadowCanvas.height}, {u:0,v:0});
shadows.drawBaseRectShadow();
}
if (drawing.drawBeforeSheets)
drawing.drawBeforeSheets();
drawing.drawSheets(sheetengine.context);
if (drawing.drawAfterSheets)
drawing.drawAfterSheets();
};
function drawRect(sheetdata, context, drawFunction, canvas, allowContourDrawing, poly) {
// if the sheet is not visible from this angle, draw its contour only
var a = round2digits(sheetdata.p1uv.u, 1000);
var b = round2digits(sheetdata.p1uv.v, 1000);
var c = round2digits(sheetdata.p2uv.u, 1000);
var d = round2digits(sheetdata.p2uv.v, 1000);
if ((a == 0 && c == 0) || (c == 0 && d == 0) || (a == 0 && b == 0) || (b == 0 && d == 0) || (a+b == 0 && c+d == 0)) {
if (allowContourDrawing && drawing.allowContourDrawing)
drawSelectRect(sheetdata, context, 0)
return;
}
context.save();
if (poly != null) {
// check if all sheet corners are included in polygon
var allcornersincluded = true;
for (var i=0;i<4;i++) {
var c = sheetdata.cornersuv[i];
var cornerincluded = false;
for (var polyi=0;polyi<poly.points.length;polyi++) {
var p = poly.data.pointsuv[polyi];
if (c.u == p.u && c.v == p.v) {
cornerincluded = true;
break;
}
}
if (!cornerincluded) {
allcornersincluded = false;
break;
}
}
if (!allcornersincluded) {
context.beginPath();
for (var polyi=0;polyi<poly.points.length;polyi++) {
var p = poly.data.pointsuv[polyi];
// use clip correction
if (drawing.useClipCorrection) {
var avg = poly.data.avguv;
var corru = (p.u - avg.u) * 0.03;
var corrv = (p.v - avg.v) * 0.03;
context.lineTo(p.u+corru, p.v+corrv);
} else {
context.lineTo(p.u, p.v);
}
}
context.closePath();
context.clip();
}
}
context.transform(sheetdata.ta,sheetdata.tb,sheetdata.tc,sheetdata.td,sheetdata.translatex,sheetdata.translatey);
drawFunction(context, canvas);
context.beginPath(); // empty paths
context.restore();
};
function drawTexture(context, canvas) {
context.drawImage(canvas, 0, 0);
};
function drawBaseShadowTexture(context, canvas) {
context.drawImage(canvas, 0, 0);
};
function drawSelectRect(sheetdata, context, selected) {
context.save();
context.globalAlpha = 1;
switch (selected) {
case 0: context.strokeStyle = '#000';
break;
case 1: context.strokeStyle = '#00F';
context.globalAlpha = 0.5;
break;
case 2: context.strokeStyle = '#F80';
context.globalAlpha = 0.5;
break;
case 3: context.strokeStyle = '#00F';
break;
}
context.lineWidth = drawing.selectrectlinewidth;
context.beginPath();
context.moveTo(sheetdata.cornersuv[0].u, sheetdata.cornersuv[0].v);
context.lineTo(sheetdata.cornersuv[1].u, sheetdata.cornersuv[1].v);
context.lineTo(sheetdata.cornersuv[2].u, sheetdata.cornersuv[2].v);
context.lineTo(sheetdata.cornersuv[3].u, sheetdata.cornersuv[3].v);
context.lineTo(sheetdata.cornersuv[0].u, sheetdata.cornersuv[0].v);
context.closePath();
context.stroke();
context.restore();
};
function redrawSheetCanvases(sheet) {
// create images of shadows cast by this sheet
// draw image, then paint it black wherever it is not transparent. leave it transparent otherwise.
sheet.baseshadowcontext.save();
sheet.baseshadowcontext.clearRect(0,0,sheet.width,sheet.height);
sheet.baseshadowcontext.drawImage(sheet.canvas,0,0);
sheet.baseshadowcontext.globalCompositeOperation = 'source-in';
sheet.baseshadowcontext.fillStyle = '#000';
sheet.baseshadowcontext.fillRect(0,0,sheet.width,sheet.height);
sheet.baseshadowcontext.restore();
sheet.shadowcontext.save();
sheet.shadowcontext.clearRect(0,0,sheet.width,sheet.height);
sheet.shadowcontext.drawImage(sheet.canvas,0,0);
sheet.shadowcontext.globalCompositeOperation = 'source-in';
sheet.shadowcontext.fillStyle = '#000';
sheet.shadowcontext.fillRect(0,0,sheet.width,sheet.height);
sheet.shadowcontext.restore();
};
function drawSheetSelection(sheet, polygon, sheetData, context) {
var hoverSheet = sheetengine.hoverSheet != -1 ? sheetengine.sheets[sheetengine.hoverSheet] : null;
var hovered = sheetengine.hoverSheet == sheet.index || (hoverSheet != null && sheet.group != null && sheet.group == hoverSheet.group) || (hoverSheet != null && sheet.objectsheet && sheet.object == hoverSheet.object);
var selected = sheetengine.currentSheet == sheet.index;
var inSelection = sheet.inSelection;
if (hovered || selected || inSelection) {
var color = 1; // hovered
if (inSelection || selected)
color = 2;
drawSelectPoly(sheetData, context, color, sheet, polygon);
}
};
function drawSelectPoly(sheetdata, context, color, sheet, poly) {
context.save();
context.globalAlpha = 1;
switch (color) {
case 1: context.strokeStyle = drawing.hoveredSheetColor;
break;
case 2: context.strokeStyle = drawing.selectedSheetColor;
break;
}
context.lineWidth = 2;
context.beginPath();
for (var j=0;j<poly.points.length;j++) {
var next = j == poly.points.length - 1 ? 0 : j + 1;
context.moveTo(poly.data.pointsuv[j].u, poly.data.pointsuv[j].v);
var inframe = pointsInFrame(poly.data.pointsuv[j], poly.data.pointsuv[next], sheetdata.cornersuv);
if (inframe) {
context.lineTo(poly.data.pointsuv[next].u, poly.data.pointsuv[next].v);
}
}
context.closePath();
context.stroke();
context.restore();
};
function pointsInFrame(p1, p2, cornersuv) {
return pointsInFrameLine(p1,p2,cornersuv[0],cornersuv[1]) ||
pointsInFrameLine(p1,p2,cornersuv[1],cornersuv[2]) ||
pointsInFrameLine(p1,p2,cornersuv[2],cornersuv[3]) ||
pointsInFrameLine(p1,p2,cornersuv[3],cornersuv[0]);
};
function pointsInFrameLine(p1, p2, c1,c2) {
var diffu1 = p1.u-c1.u;
var diffu2 = p2.u-c1.u;
var diffu3 = c2.u-c1.u;
var diffv1 = p1.v-c1.v;
var diffv2 = p2.v-c1.v;
var diffv3 = c2.v-c1.v;
var div1 = (diffu1/diffu3);
var div2 = (diffv1/diffv3);
var div3 = (diffu2/diffu3);
var div4 = (diffv2/diffv3);
var thresh1 = 0.1;
var thresh2 = 2;
var inline = (Math.abs(div1 - div2) < thresh1 && Math.abs(div3 - div4) < thresh1) || (Math.abs(diffu3) < thresh2 && Math.abs(diffu2) < thresh2 & Math.abs(diffu1) < thresh2) || (Math.abs(diffv3) < thresh2 && Math.abs(diffv2) < thresh2 && Math.abs(diffv1) < thresh2);
return inline;
};
function drawSheets(context, viewport) {
if (sheetengine.sheets.length == 0)
return;
for (var i=0; i<sheetengine.orderedPolygons.length; i++) {
var polygon = sheetengine.polygons[sheetengine.orderedPolygons[i]];
var sheet = sheetengine.sheets[polygon.sheetindex];
if (viewport) {
var sheetdata = sheet.data;
if (sheetdata.centerpuv.u < viewport.minu || sheetdata.centerpuv.u > viewport.maxu || sheetdata.centerpuv.v < viewport.minv || sheetdata.centerpuv.v > viewport.maxv)
continue;
}
if (sheet.hidden)
continue;
if (sheet.dimmed) {
context.save();
context.globalAlpha = drawing.dimmedAlpha;
}
drawing.drawRect(sheet.data, context, drawTexture, sheet.compositecanvas, true, polygon);
if (sheet.dimmed) {
context.restore();
}
drawSheetSelection(sheet, polygon, sheet.data, context);
}
};
function getPointuv(p) {
var puv = transforms.transformPoint(p);
return {
u:puv.u+sheetengine.canvasCenter.u-scene.center.u,
v:puv.v+sheetengine.canvasCenter.v-scene.center.v};
};
function drawScenePart(options) {
var viewPort = options.viewPort; // {u,v,w,h}
var targetContext = options.targetContext; // this.context
var targetBaseShadowContext = options.targetBaseShadowContext;
var targetBaseShadowCanvas = options.targetBaseShadowCanvas;
if (!targetContext) {
targetContext = sheetengine.temppartcontext;
targetBaseShadowContext = sheetengine.temppartshadowcontext;
targetBaseShadowCanvas = sheetengine.temppartshadowcanvas;
}
// clear canvas
targetContext.fillStyle = sheetengine.backgroundColor;
targetContext.fillRect(0, 0, viewPort.w, viewPort.h);
var u = viewPort.u + sheetengine.canvasCenter.u;
var v = viewPort.v + sheetengine.canvasCenter.v;
// translate canvas
targetContext.save();
targetContext.translate(-u, -v);
// draw baserects
drawBaseRects(targetContext);
// select the region of interest
var distance = sheetengine.boundingBoxMaxsheetDistance;
var minu = viewPort.u - distance;
var minv = viewPort.v - distance;
var maxu = viewPort.u + viewPort.w + distance;
var maxv = viewPort.v + viewPort.h + distance;
// draw baseshadows
var shadowrel = {u:-u+scene.center.u+sheetengine.canvasCenter.u-shadows.baseShadowCenter.u,v:-v+scene.center.v+sheetengine.canvasCenter.v-shadows.baseShadowCenter.v};
initBaseRectShadow(targetBaseShadowContext, {w:viewPort.w, h:viewPort.h}, shadowrel, {minu:minu, maxu:maxu, minv:minv, maxv:maxv});
targetContext.save();
targetContext.globalAlpha = shadows.shadowAlpha;
targetContext.drawImage(targetBaseShadowCanvas,u,v);
targetContext.restore();
// draw sheets
drawSheets(targetContext, {minu:minu, maxu:maxu, minv:minv, maxv:maxv});
targetContext.restore();
};
function drawScene(full) {
if (full) {
if (sheetengine.backgroundcanvas) {
// clear canvas
sheetengine.backgroundcontext.clearRect(0,0, sheetengine.backgroundcanvas.width, sheetengine.backgroundcanvas.height);
// draw baserects
sheetengine.backgroundcontext.save();
sheetengine.backgroundcontext.translate(-sheetengine.canvasCenter.u+shadows.baseShadowCenter.u,-sheetengine.canvasCenter.v+shadows.baseShadowCenter.v);
drawBaseRects(sheetengine.backgroundcontext);
sheetengine.backgroundcontext.restore();
// draw baseshadows
var shadowrel = {u:scene.center.u,v:scene.center.v};
shadows.initBaseRectShadow(shadows.baseshadowContext, {w:shadows.baseshadowCanvas.width, h:shadows.baseshadowCanvas.height}, shadowrel, null);
drawBaseRectShadows(sheetengine.backgroundcontext,{u:sheetengine.backgroundtranslate.u,v:sheetengine.backgroundtranslate.v});
// draw sheets
sheetengine.backgroundcontext.save();
sheetengine.backgroundcontext.translate(-sheetengine.canvasCenter.u+shadows.baseShadowCenter.u,-sheetengine.canvasCenter.v+shadows.baseShadowCenter.v);
drawing.drawSheets(sheetengine.backgroundcontext, null);
sheetengine.backgroundcontext.restore();
} else {
// clear canvas
sheetengine.context.clearRect(0,0, sheetengine.canvas.width, sheetengine.canvas.height);
// draw baserects
drawBaseRects(sheetengine.context);
// draw baseshadows
var shadowrel = {u:scene.center.u,v:scene.center.v};
shadows.initBaseRectShadow(shadows.baseshadowContext, {w:shadows.baseshadowCanvas.width, h:shadows.baseshadowCanvas.height}, shadowrel, null);
drawBaseRectShadows(sheetengine.context);
// draw sheets
drawing.drawSheets(sheetengine.context, null);
}
if (sheetengine.drawObjectContour) {
for (var i=0;i<sheetengine.objects.length;i++) {
var obj = sheetengine.objects[i];
obj.canvasdirty = true;
obj.draw();
}
}
} else {
// update background (if any sheet's dimmed state is changed) - this also applies for not moving objects!
for (var i=0;i<sheetengine.sheets.length;i++) {
var s = sheetengine.sheets[i];
var dimmedChanged = s.dimmed != s.dimmedprev;
s.dimmedprev = s.dimmed;
if (dimmedChanged) {
// redraw background for this sheet
// viewport will be the bounding box of the sheet
var w = Math.ceil(s.data.umax - s.data.umin);
var h = Math.ceil(s.data.vmax - s.data.vmin);
var u = s.data.umin - sheetengine.canvasCenter.u;
var v = s.data.vmin - sheetengine.canvasCenter.v;
drawScenePart({
viewPort: {u:u, v:v, w:w, h:h}
});
var canvas = sheetengine.backgroundcanvas ? sheetengine.backgroundcanvas : sheetengine.canvas;
var context = sheetengine.backgroundcanvas ? sheetengine.backgroundcontext : sheetengine.context;
u += canvas.width/2;
v += canvas.height/2;
w-=1; // fix drawing inaccuracies
h-=1;
context.drawImage(sheetengine.temppartcanvas,0,0,w,h,u,v,w,h);
}
}
// draw objects
for (var i=0;i<sheetengine.objects.length;i++) {
var obj = sheetengine.objects[i];
obj.draw();
}
}
// position background
if (sheetengine.backgroundcanvas) {
sheetengine.context.clearRect(0,0,sheetengine.canvas.width,sheetengine.canvas.height);
var offsetu = -scene.center.u - sheetengine.backgroundcanvas.width/2 + sheetengine.canvas.width/2;
var offsetv = -scene.center.v - sheetengine.backgroundcanvas.height/2 + sheetengine.canvas.height/2;
offsetu += sheetengine.backgroundtranslate.u;
offsetv += sheetengine.backgroundtranslate.v;
sheetengine.context.drawImage(sheetengine.backgroundcanvas,offsetu,offsetv);
}
};
function drawBaseRects(context) {
for (var i=0;i<sheetengine.basesheets.length;i++) {
var basesheet = sheetengine.basesheets[i];
drawing.drawRect(basesheet.data, context, function(ctx, canvas) {
ctx.fillStyle = basesheet.color;
ctx.fillRect(0,0,basesheet.width,basesheet.height);
}, null, false);
}
};
drawing.createCanvas = createCanvas;
drawing.redraw = redraw;
drawing.drawRect = drawRect;
drawing.redrawSheetCanvases = redrawSheetCanvases;
drawing.drawSheets = drawSheets;
drawing.getPointuv = getPointuv;
drawing.drawScene = drawScene;
// ===================================================================================================
// sheet-intersections
var intersections = {};
sheetengine.intersections = intersections;
intersections.intersections = true;
var polygonMidpointsForOverlapCheck = [{dist:50, numpoints:4}, {dist:20, numpoints:3}, {dist:10, numpoints:2}, {dist:0, numpoints:1}];
//var polygonMidpointsForOverlapCheck = [{dist:50, numpoints:0}];
function getIntersection(n,p,c1,c2) {
// two lines: L1=P1+aV1; L2=P2+bV2
// (here v1=n, p1=p, v2=c2-c1, p2=c1)
// aV1=(P2-P1)+bV2; X V2 -> a(V1 X V2) = (P2-P1) X V2
// a=(P2-P1) X V2 / (V1 X V2) - division here is with magnitudes of vectors
var p2 = c1;
var n2 = {x: c2.x - c1.x,
y: c2.y - c1.y,
z: c2.z - c1.z};
var p2p = {x: p.x-p2.x, y:p.y-p2.y, z:p.z-p2.z};
var cp1 = crossProduct(p2p,n);
var cp2 = crossProduct(n2,n);
var t = geometry.vectorMagnitude(cp1) / geometry.vectorMagnitude(cp2);
// check: by taking magnitudes of vectors, we lose information. t might be -t, but when?
// cp1 is t times cp2, so the following sum should be 0. if not, t should be taken as -t
var check = cp2.x * t + cp2.y*t + cp2.z*t - cp1.x - cp1.y - cp1.z;
if (Math.round(check) != 0)
t = -t;
return {p: {x: p2.x+t*n2.x, y: p2.y+t*n2.y, z: p2.z+t*n2.z}, inside: t>=0 && t<=1, t:t };
};
function pointsEqual(p1,p2) {
return Math.round(p1.x)==Math.round(p2.x) && Math.round(p1.y)==Math.round(p2.y) && Math.round(p1.z)==Math.round(p2.z);
//return p1.x==p2.x && p1.y==p2.y && p1.z==p2.z;
};
function bisectCornerList(corners, n, p) {
// algorithm: we will create two polygons from a corner list, in two phases. in the first phase
// we gather all corners including intersection points, and mark intersections. from the gathered corners
// we eliminate x-c and x-c-x patterns where a single line crosses near a corner making 3 corners -> this
// only counts as one. in the second phase we start out from one intersection point (there should be exactly 2)
// to the left and to the right until we reach the second intersection -> the corners we cover will be the
// corners of the first and second polygon.
// gather all corners and intersection points, mark intersections position
var allcorners = [];
var firstintersect = null;
var secondintersect = null;
var inintersection = false; // this is to detect c-x-c
for (var i=0;i<corners.length;i++) {
var j = i == corners.length-1 ? 0 : i + 1;
var corneradded = false;
// add corner if point not yet added. for x-c only x will be in array.
if ((allcorners.length == 0) || (!pointsEqual(allcorners[allcorners.length-1], corners[i]))) {
allcorners[allcorners.length] = corners[i];
corneradded = true;
}
var p1 = getIntersection(n, p, corners[i], corners[j]);
if (p1.inside) {
var pointalreadyadded = pointsEqual(allcorners[allcorners.length-1], p1.p);
// add intersection if point not yet added. for x-x only x will be in array.
// (x-c-x is eliminated in two steps: first x-c is x above, and here x-x is x.
if (!pointalreadyadded) {
if (firstintersect == null)
firstintersect = allcorners.length;
else if (secondintersect == null)
secondintersect = allcorners.length;
allcorners[allcorners.length] = p1.p;
}
// mark previous point as intersection for c-x
if ((pointalreadyadded) && (corneradded)) {
if (firstintersect == null)
firstintersect = allcorners.length - 1;
else if (secondintersect == null)
secondintersect = allcorners.length - 1;
}
}
}
// no intersection or only one intersection: return
if (secondintersect == null)
return null;
// start from first intersection to the left till second intersection, and put all corners in poly 0
// start from first intersection to the right till second intersection, and put all corners in poly 1
var poly = [];
poly[0] = [];
poly[1] = [];
var index = firstintersect;
for (;;) {
poly[0][poly[0].length] = geometry.clonePoint(allcorners[index]);
if (index == secondintersect)
break;
index--;
if (index < 0)
index = allcorners.length - 1;
}
index = firstintersect;
for (;;) {
poly[1][poly[1].length] = geometry.clonePoint(allcorners[index]);
if (index == secondintersect)
break;
index++;
if (index > allcorners.length - 1)
index = 0;
}
return poly;
};
function isInsideCornerList(corners, n, p) {
for (var i=0;i<corners.length;i++) {
var j = i == corners.length-1 ? 0 : i + 1;
var p1 = getIntersection(n, p, corners[i], corners[j]);
if (p1.inside)
return true;
}
return false;
};
function getIntersectionLineofPlanes(a, b) {
// check if planes are far away from each other
var maxdiag = a.maxdiag + b.maxdiag;
var distance = Math.sqrt(
((a.centerp.x-b.centerp.x)*(a.centerp.x-b.centerp.x))+
((a.centerp.y-b.centerp.y)*(a.centerp.y-b.centerp.y))+
((a.centerp.z-b.centerp.z)*(a.centerp.z-b.centerp.z)));
if (distance > maxdiag)
return null;
var n1n2 = a.normalp.x*b.normalp.x+a.normalp.y*b.normalp.y+a.normalp.z*b.normalp.z;
// planes parallel
if (n1n2 == 1)
return null;
var n1n1 = a.normalp.x*a.normalp.x+a.normalp.y*a.normalp.y+a.normalp.z*a.normalp.z;
var n2n2 = b.normalp.x*b.normalp.x+b.normalp.y*b.normalp.y+b.normalp.z*b.normalp.z;
// calculate line vector of section line: cross product of normalvectors
// x-2y+2z=1, 3x-y-z=2 -> (1,-2,2)x(3,-1,-1)->(4,7,5).
var n = crossProduct(a.normalp, b.normalp);
var d1 = (a.normalp.x*a.centerp.x+a.normalp.y*a.centerp.y+a.normalp.z*a.centerp.z);
var d2 = (b.normalp.x*b.centerp.x+b.normalp.y*b.centerp.y+b.normalp.z*b.centerp.z);
var det = n1n1*n2n2-n1n2*n1n2;
var c1 = (d1*n2n2 - d2*n1n2)/det;
var c2 = (d2*n1n1 - d1*n1n2)/det;
// line is c1 N1 + c2 N2 + t N1 * N2
// -> (p) + t(n)
var p = {x: c1*a.normalp.x + c2*b.normalp.x,
y: c1*a.normalp.y + c2*b.normalp.y,
z: c1*a.normalp.z + c2*b.normalp.z};
return {n:n, p:roundVector2digits(p, 10000)};
};
function doSheetsIntersect(s1, s2) {
// calculate section of sheets
var line = getIntersectionLineofPlanes(s1, s2);
// initialize intersectionparams for both sheets - these data will be used later when calculating sheet sections
s1.intersectionParams[s2.index] = { line: line };
s2.intersectionParams[s1.index] = { line: line };
if (line == null)
return false;
// check if line falls inside both sheets
var insideS1 = isInsideCornerList(s1.corners, line.n, line.p);
var insideS2 = isInsideCornerList(s2.corners, line.n, line.p);
// extend intersectionParams with inside-info
s1.intersectionParams[s2.index].insideThis = insideS1;
s1.intersectionParams[s2.index].insideOther = insideS2;
s2.intersectionParams[s1.index].insideThis = insideS2;
s2.intersectionParams[s1.index].insideOther = insideS1;
return insideS1 && insideS2;
};
function calculatePolygonsForSheet(sheet, sheetset) {
if (sheet.hidden)
return;
if (!sheetset)
sheetset = sheetengine.sheets;
for (var s=0;s<sheetset.length;s++) {
var othersheet = sheetset[s];
if (othersheet.index == sheet.index)
continue;
if (othersheet.hidden)
continue;
var intersectionParams = sheet.intersectionParams[othersheet.index];
var line = intersectionParams == null ?
getIntersectionLineofPlanes(sheet, othersheet) :
intersectionParams.line;
if (line == null)
continue;
// check if line falls inside both sheets
var startpolygons1 = null;
var poly1initialized = false;
var startpolygons2 = null;
var poly2initialized = false;
var inside = false;
if (sheet.polygons.length == 1) {
startpolygons1 = bisectCornerList(sheet.corners, line.n, line.p);
inside = !(startpolygons1 == null);
poly1initialized = true;
} else {
inside = intersectionParams == null ?
isInsideCornerList(sheet.corners, line.n, line.p) :
intersectionParams.insideThis;
}
// current sheet falls out of line, next sheet intersection
if (!inside)
continue;
inside = intersectionParams == null ?
isInsideCornerList(othersheet.corners, line.n, line.p) :
intersectionParams.insideOther;
// other sheet falls out of line, next sheet intersection
if (!inside)
continue;
// bisect all polygons of current sheet with s
var newpoly = [];
for (var i=0; i<sheet.polygons.length; i++) {
var polygons = null;
if (poly1initialized) {
polygons = startpolygons1;
poly1initialized = false;
} else {
polygons = bisectCornerList(sheet.polygons[i].points, line.n, line.p);
}
// if current polygon is not intersected, put it in the list intact,
// otherwise put the resulting polygon sections in the list
if (polygons == null)
newpoly[newpoly.length] = sheet.polygons[i];
else {
newpoly[newpoly.length] = { points: polygons[0] };
newpoly[newpoly.length] = { points: polygons[1] };
}
}
sheet.polygons = newpoly;
sheet.intersectors.push(othersheet.index);
}
};