-
Notifications
You must be signed in to change notification settings - Fork 62
/
Fog.js
5998 lines (5169 loc) · 215 KB
/
Fog.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
const POLYGON_CLOSE_DISTANCE = 15;
const doorColors = {
0: {
'open': "rgba(255, 100, 255, 0.5)", // door
'closed': "rgba(255, 100, 255, 1)"
},
1: {
'open': "rgba(255, 255, 0, 0.5)", // window
'closed': "rgba(255, 255, 0, 1)"
},
2: {
'open': "rgba(150, 50, 150, 0.5)", // locked door
'closed': "rgba(150, 50, 150, 1)"
},
3: {
'open': "rgba(150, 150, 0, 0.5)", // locked window
'closed': "rgba(150, 150, 0, 1)"
},
4: {
'open': "rgba(100, 0, 255, 0.5)", //secret door
'closed': "rgba(100, 0, 255, 1)"
},
5: {
'open': "rgba(50, 0, 180, 0.5)", // secret locked door
'closed': "rgba(50, 0, 180, 1)"
},
6: {
'open': "rgba(50, 255, 255, 0.5)", // secret window
'closed': "rgba(50, 255, 255, 1)"
},
7: {
'open': "rgba(50, 180, 180, 0.5)", // secret locked window
'closed': "rgba(50, 180, 180, 1)"
},
};
let doorColorsArray = [];
for(let i in doorColors){
for(let j in doorColors[i]){
doorColorsArray.push(doorColors[i][j])
}
}
function sync_fog(){
window.MB.sendMessage("custom/myVTT/fogdata",window.REVEALED);
}
function sync_drawings(newDraw = true){
if(!window.DM && newDraw == true){
if(window.playerDrawUndo == undefined)
window.playerDrawUndo = [];
window.playerDrawUndo.push(window.DRAWINGS[window.DRAWINGS.length-1]);
}
window.MB.sendMessage("custom/myVTT/drawdata",window.DRAWINGS);
}
function roundRect(ctx, x, y, width, height, radius, fill, stroke) {
if (typeof stroke == "undefined" ) {
stroke = true;
}
if (typeof radius === "undefined") {
radius = 5;
}
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
if (stroke) {
ctx.stroke();
}
if (fill) {
ctx.fill();
}
}
/**
* Class to manage measure waypoints
*/
class WaypointManagerClass {
constructor(){
this.canvas=undefined;
this.ctx=undefined;
this.numWaypoints = 0;
/**
* @type {{startX: number, startY: number, endX: number, endY: number, distance: number}[]}
*/
this.coords = [];
this.currentWaypointIndex = 0;
this.mouseDownCoords = { mousex: undefined, mousey: undefined };
this.timeout = undefined;
/**
* @type {number | undefined}
*/
this.fadeoutAnimationId = undefined;
this.drawStyle = {
lineWidth: Math.max(25 * Math.max((1 - window.ZOOM), 0), 5),
color: window.color ? window.color : "#f2f2f2",
outlineColor: "black",
textColor: "black",
backgroundColor: "rgba(255, 255, 255, 0.7)"
}
}
resetDefaultDrawStyle(){
this.drawStyle = {
lineWidth: Math.max(25 * Math.max((1 - window.ZOOM), 0), 5),
color: window.color ? window.color : "#f2f2f2",
outlineColor: "black",
textColor: "black",
backgroundColor: "rgba(255, 255, 255, 0.7)"
}
}
// Set canvas and further set context
setCanvas(canvas) {
this.canvas = canvas;
this.ctx = canvas.getContext("2d");
}
// Are we in the middle of measuring?
isMeasuring() {
return this.numWaypoints != 0;
}
// Store a waypoint in the array
storeWaypoint(index, startX, startY, endX, endY) {
// Check if we have this waypoint in our array, if not then increment how many waypoints we have
if (typeof this.coords[index] === 'undefined') {
this.numWaypoints++;
}
// If this is the first segment we store the values as passed in
if (this.numWaypoints == 1) {
this.coords[index] = { startX: startX, startY: startY, endX: endX, endY: endY, distance: 0 };
}
else {
// If this is NOT the first, then we stitch the segments together by setting the start of this one to the end of the previous one
this.coords[index] = { startX: this.coords[index - 1].endX, startY: this.coords[index - 1].endY, endX: endX, endY: endY, distance: 0 };
}
}
/**
* Draw a nice circle
* @param x {number}
* @param y {number}
* @returns {string} <circle> tag
*/
makeBobble(x, y) {
/*
this.ctx.beginPath();
this.ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
this.ctx.lineWidth = radius
this.ctx.strokeStyle = this.drawStyle.outlineColor
this.ctx.stroke();
this.ctx.fillStyle = this.drawStyle.color
this.ctx.fill();
*/
return `<circle cx='${x}' cy='${y}' fill='${this.drawStyle.color}' stroke='${this.drawStyle.outlineColor}' />`;
}
// Increment the current index into the array of waypoints, and draw a small indicator
checkNewWaypoint(mousex, mousey) {
//console.log("Incrementing waypoint");
this.currentWaypointIndex++;
// Draw an indicator for cosmetic niceness
//let snapCoords = this.getSnapPointCoords(mousex, mousey);
//this.drawBobble(snapCoords.x, snapCoords.y, Math.max(15 * Math.max((1 - window.ZOOM), 0)/window.CURRENT_SCENE_DATA.scale_factor, 3));
}
// Track mouse moving
registerMouseMove(mousex, mousey) {
this.mouseDownCoords.mousex = mousex;
this.mouseDownCoords.mousey = mousey;
}
// On mouse up, clear out the waypoints
clearWaypoints(cancelFadeout=true) {
this.numWaypoints = 0;
this.coords = [];
this.currentWaypointIndex = 0;
this.mouseDownCoords = { mousex: undefined, mousey: undefined };
clearTimeout(this.timeout);
this.timeout = undefined;
this.cancelFadeout()
}
// Helper function to convert mouse coordinates to 'snap' or 'centre of current grid cell' coordinates
getSnapPointCoords(x, y) {
if (!$('#ruler_menu').hasClass('button-enabled')) {
// only snap if the ruler tool is selected.
// The select tool manages the snapping based on ctrl key, scene settings, etc. so let it do it's thing
return { x: x, y: y };
}
x -= window.CURRENT_SCENE_DATA.offsetx;
y -= window.CURRENT_SCENE_DATA.offsety;
let gridSize = window.CURRENT_SCENE_DATA.hpps/window.CURRENT_SCENE_DATA.scale_factor;
let currGridX = Math.floor(x / gridSize);
let currGridY = Math.floor(y / gridSize);
let snapPointXStart = (currGridX * gridSize) + (gridSize/2);
let snapPointYStart = (currGridY * gridSize);
// Add in scene offset
snapPointXStart += window.window.CURRENT_SCENE_DATA.offsetx/window.CURRENT_SCENE_DATA.scale_factor;
snapPointYStart += window.window.CURRENT_SCENE_DATA.offsety/window.CURRENT_SCENE_DATA.scale_factor;
return { x: snapPointXStart, y: snapPointYStart }
}
/**
* Find ruler container for this player or create it
* @param playerId {string | boolean}
*/
getOrCreateDrawingContainer(playerId) {
const rulerContainerId = `ruler-container-${playerId}`;
let rulerContainer = document.getElementById(rulerContainerId)
if (!rulerContainer) {
const rulerContainerDiv = document.createElement("div");
rulerContainerDiv.id = rulerContainerId;
document.getElementById("VTT").append(rulerContainerDiv);
// re-query to get created element
rulerContainer = document.getElementById(rulerContainerId);
}
return rulerContainer;
}
/**
* Empties ruler container for this player
* @param playerId
*/
clearWaypointDrawings(playerId) {
const rulerContainerId = `ruler-container-${playerId}`;
let rulerContainer = document.getElementById(rulerContainerId)
if (!rulerContainer) {
// it's empty then
return;
}
rulerContainer.innerHTML = "";
}
/**
* @returns {{sceneHeight: number, sceneWidth: number}}
*/
getSceneMapSize() {
const sceneMap = document.getElementById("scene_map");
return { sceneHeight: Math.floor(sceneMap.offsetHeight), sceneWidth: Math.floor(sceneMap.offsetWidth) }
}
/**
* Draw the waypoints, note that we sum up the cumulative distance
* @param labelX {number | undefined} if provided, move last text of last waypoint there
* @param labelY {number | undefined} if provided, move last text of last waypoint there
* @param alpha {number | undefined} set alpha of drawings to this, 1 if unset
* @param playerId {string | false | undefined} `window.PLAYER_ID` if unset
*/
draw(labelX = undefined, labelY = undefined, alpha = 1, playerId=window.PLAYER_ID) {
const rulerContainer = this.getOrCreateDrawingContainer(playerId);
// update alpha for the entire container
rulerContainer.style.setProperty("--svg-text-alpha", alpha.toString());
const sceneMapSize = this.getSceneMapSize();
let cumulativeDistance = 0;
this.numberOfDiagonals = 0;
let elementsToDraw = "";
const { sceneWidth, sceneHeight } = sceneMapSize;
const bobbles = $(`<svg viewbox='0 0 ${sceneWidth} ${sceneHeight}' width='${sceneWidth}' height='${sceneHeight}' class='ruler-svg-bobbles' style='top:0px; left:0px;'></svg>`);
const lines = $(`<svg viewbox='0 0 ${sceneWidth} ${sceneHeight}' width='${sceneWidth}' height='${sceneHeight}' class='ruler-svg-line' style='top:0px; left:0px;'></svg>`);
for (let i = 0; i < this.coords.length; i++) {
// We do the beginPath here because otherwise the lines on subsequent waypoints get
// drawn over the labels...
this.ctx.beginPath();
if (i < this.coords.length - 1) {
elementsToDraw += this.makeWaypointSegment(this.coords[i], cumulativeDistance, undefined, undefined, sceneMapSize, bobbles, lines);
} else {
elementsToDraw += this.makeWaypointSegment(this.coords[i], cumulativeDistance, labelX, labelY, sceneMapSize, bobbles, lines);
}
cumulativeDistance += this.coords[i].distance
}
elementsToDraw = `${lines[0].outerHTML}${elementsToDraw}${bobbles[0].outerHTML}`
rulerContainer.innerHTML = elementsToDraw;
}
/**
* Make a waypoint segment SVGs with all the lines and labels etc.
* @param coord {{startX: number, startY: number, endX: number, endY: number, distance: number}}
* @param cumulativeDistance {number}
* @param labelX {number}
* @param labelY {number}
* @param sceneMapSize {{sceneHeight: number, sceneWidth: number}}
* @returns {string} SVG elements for waypoint line and label
*/
makeWaypointSegment(coord, cumulativeDistance, labelX, labelY, sceneMapSize, bobbles, lines) {
// Snap to centre of current grid square
let gridSize = window.CURRENT_SCENE_DATA.hpps/window.CURRENT_SCENE_DATA.scale_factor;
let snapPointXStart = coord.startX;
let snapPointYStart = coord.startY;
this.ctx.moveTo(snapPointXStart, snapPointYStart);
let snapPointXEnd = coord.endX;
let snapPointYEnd = coord.endY;
let unitSymbol;
// Pull the scene data for units, unless it doesn't exist (i.e. older maps)
if (typeof window.CURRENT_SCENE_DATA.upsq !== "undefined")
unitSymbol = window.CURRENT_SCENE_DATA.upsq;
else
unitSymbol = 'ft'
// Calculate the distance and set into the waypoint object
const xAdjustment = window.CURRENT_SCENE_DATA.scaleAdjustment?.x != undefined ? window.CURRENT_SCENE_DATA.scaleAdjustment.x : 1;
const yAdjustment = window.CURRENT_SCENE_DATA.scaleAdjustment?.y != undefined ? window.CURRENT_SCENE_DATA.scaleAdjustment.y : 1;
const xLength = Math.abs(snapPointXStart - snapPointXEnd)/xAdjustment;
const yLength = Math.abs(snapPointYStart - snapPointYEnd)/yAdjustment;
let distance = Math.max(xLength, yLength);
const rulerType = $('#ruler_menu .button-enabled').attr('data-type');
if(window.CURRENT_SCENE_DATA.gridType != undefined){
if((xLength > yLength && window.CURRENT_SCENE_DATA.gridType != 1 && rulerType != 'euclidean') || (window.CURRENT_SCENE_DATA.gridType == 2 && rulerType == 'euclidean')){
gridSize = window.hexGridSize.width/window.CURRENT_SCENE_DATA.scale_factor;
} else if((xLength < yLength && window.CURRENT_SCENE_DATA.gridType != 1 && rulerType != 'euclidean' )|| (window.CURRENT_SCENE_DATA.gridType == 3 && rulerType == 'euclidean')){
gridSize = window.hexGridSize.height/window.CURRENT_SCENE_DATA.scale_factor;
}
}
const eucDistance = Math.sqrt(xLength*xLength+yLength*yLength)/gridSize * window.CURRENT_SCENE_DATA.fpsq;
distance = Math.round(distance / gridSize);
const lineSlope = yLength/xLength;
let addedDistance = 0;
if(rulerType == "fiveten" && lineSlope > 0.6 && lineSlope < 1.4){
this.numberOfDiagonals = (this.numberOfDiagonals%2 == 0) ? distance : distance+1 ;
addedDistance = Math.floor(this.numberOfDiagonals/2);
}
distance = (rulerType == 'euclidean') ? eucDistance : (distance+addedDistance) * window.CURRENT_SCENE_DATA.fpsq;
coord.distance = distance;
let textX = 0;
let textY = 0;
let margin = 2;
let heightOffset = 30;
let slopeModifier = 0;
// Setup text metrics
let fontSize = Math.max(75 * Math.max((1 - window.ZOOM), 0)/window.CURRENT_SCENE_DATA.scale_factor, 26)
const totalDistance = Number.isInteger(distance + cumulativeDistance)
? (distance + cumulativeDistance)
: (distance + cumulativeDistance).toFixed(1)
let text = `${totalDistance}${unitSymbol}`
let textMetrics = this.ctx.measureText(text);
let contrastRect = { x: 0, y: 0, width: 0, height: 0 }
let textRect = { x: 0, y: 0, width: 0, height: 0 }
if (labelX !== undefined && labelY !== undefined) {
// Calculate our coords and dimensions
contrastRect.x = labelX - margin + slopeModifier;
contrastRect.y = labelY - margin + slopeModifier;
contrastRect.width = textMetrics.width + (margin * 4);
contrastRect.height = Math.max(150 * Math.max((1 - window.ZOOM), 0)/window.CURRENT_SCENE_DATA.scale_factor, 30) + (margin * 3);
textRect.x = labelX + slopeModifier;
textRect.y = labelY + slopeModifier;
textRect.width = textMetrics.width + (margin * 3);
textRect.height = Math.max(150 * Math.max((1 - window.ZOOM), 0)/window.CURRENT_SCENE_DATA.scale_factor, 30) + margin;
textRect.x -= (textRect.width / 2);
textX = (labelX + margin + slopeModifier - (textRect.width / 2));
textY = (labelY + (margin * 2) + slopeModifier);
} else {
slopeModifier = margin;
// Calculate our coords and dimensions
contrastRect.x = snapPointXEnd - margin + slopeModifier;
contrastRect.y = snapPointYEnd - margin + slopeModifier;
contrastRect.width = textMetrics.width + (margin * 4);
contrastRect.height = Math.max(150 * Math.max((1 - window.ZOOM), 0)/window.CURRENT_SCENE_DATA.scale_factor, 30) + (margin * 3);
textRect.x = snapPointXEnd + slopeModifier;
textRect.y = snapPointYEnd + slopeModifier;
textRect.width = textMetrics.width + (margin * 3);
textRect.height = Math.max(150 * Math.max((1 - window.ZOOM), 0)/window.CURRENT_SCENE_DATA.scale_factor, 30) + margin;
textX = snapPointXEnd + margin + slopeModifier;
textY = snapPointYEnd + (margin * 2) + slopeModifier;
}
/*
// Draw our 'contrast line'
this.ctx.strokeStyle = this.drawStyle.outlineColor
this.ctx.lineWidth = Math.floor(Math.max(25 * Math.max((1 - window.ZOOM), 0)/window.CURRENT_SCENE_DATA.scale_factor, 3));
this.ctx.lineTo(snapPointXEnd, snapPointYEnd);
this.ctx.stroke();
// Draw our centre line
this.ctx.strokeStyle = this.drawStyle.color
this.ctx.lineWidth = Math.floor(Math.max(15 * Math.max((1 - window.ZOOM), 0)/window.CURRENT_SCENE_DATA.scale_factor, 2));
this.ctx.lineTo(snapPointXEnd, snapPointYEnd);
this.ctx.stroke();
/*this.ctx.strokeStyle = this.drawStyle.outlineColor
this.ctx.fillStyle = this.drawStyle.backgroundColor
this.ctx.lineWidth = Math.floor(Math.max(15 * Math.max((1 - window.ZOOM), 0)/window.CURRENT_SCENE_DATA.scale_factor, 3));
roundRect(this.ctx, Math.floor(textRect.x), Math.floor(textRect.y), Math.floor(textRect.width), Math.floor(textRect.height), 10, true);
// draw the outline of the text box
roundRect(this.ctx, Math.floor(textRect.x), Math.floor(textRect.y), Math.floor(textRect.width), Math.floor(textRect.height), 10, false, true);
// Finally draw our text
this.ctx.fillStyle = this.drawStyle.textColor
this.ctx.textBaseline = 'top';
this.ctx.fillText(text, textX, textY);*/
const { sceneWidth, sceneHeight } = sceneMapSize;
// add ruler line and text
const rulerLineSVG = `
<line x1='${snapPointXStart}' y1='${snapPointYStart}' x2='${snapPointXEnd}' y2='${snapPointYEnd}' stroke="${this.drawStyle.outlineColor}"></line>
<line x1='${snapPointXStart}' y1='${snapPointYStart}' x2='${snapPointXEnd}' y2='${snapPointYEnd}' stroke="${this.drawStyle.color}"></line>
`;
lines.append(rulerLineSVG);
if(bobbles.children().length == 0){
const startBobble = this.makeBobble(snapPointXStart, snapPointYStart);
const endBobble = this.makeBobble(snapPointXEnd, snapPointYEnd)
bobbles.append(startBobble, endBobble);
}
else{
const endBobble = this.makeBobble(snapPointXEnd, snapPointYEnd)
bobbles.append(endBobble);
}
const textSVG = `
<svg class='ruler-svg-text' style='top:${textY*window.CURRENT_SCENE_DATA.scale_factor}px; left:${textX*window.CURRENT_SCENE_DATA.scale_factor}px; width:${textRect.width}px;'>
<text x="1" y="11">
${text}
</text>
</svg>
`;
return `${textSVG}`;
}
/**
* redraws the waypoints using various levels of opacity until completely clear
* then removes all waypoints and resets canvas opacity
*/
fadeoutMeasuring(playerID){
let alpha = 1.0
const self = this
if(self.ctx == undefined){
self.cancelFadeout()
self.clearWaypoints();
clear_temp_canvas(playerID)
return;
}
// only ever allow a single fadeout to occur
// this stops weird flashing behaviour with interacting
// interval function calls
if (this.fadeoutAnimationId) {
return
}
let prevFrameTime, deltaTime;
/**
* This is a function expression to make sure `this` is available.
* @type {FrameRequestCallback}
*/
const fadeout = (time) =>{
if (prevFrameTime === undefined) {
deltaTime = 0;
} else {
deltaTime = time - prevFrameTime;
}
prevFrameTime = time;
self.ctx.clearRect(0,0, self.canvas.width, self.canvas.height);
self.ctx.globalAlpha = alpha;
self.draw(undefined, undefined, alpha, window.PLAYER_ID)
alpha = alpha - (0.08 * deltaTime / 100); // 0.08 per 100 ms
if (alpha <= 0.0) {
self.clearWaypoints();
clear_temp_canvas(playerID)
return;
}
this.fadeoutAnimationId = requestAnimationFrame(fadeout)
};
this.fadeoutAnimationId = requestAnimationFrame(fadeout);
}
/**
*
*/
cancelFadeout(){
if (this.fadeoutAnimationId !== undefined) {
clear_temp_canvas();
cancelAnimationFrame(this.fadeoutAnimationId);
this.ctx.globalAlpha = 1.0
this.fadeoutAnimationId = undefined
}
}
};
function is_token_under_fog(tokenid, fogContext=undefined){
if(window.DM && !window.SelectedTokenVision)
return false;
if(fogContext == undefined){
fogContext = $('#fog_overlay')[0].getContext('2d', {willReadFrequently: true});
}
let left = (parseInt(window.TOKEN_OBJECTS[tokenid].options.left.replace('px', '')) + (window.TOKEN_OBJECTS[tokenid].options.size / 2)) / window.CURRENT_SCENE_DATA.scale_factor;
let top = (parseInt(window.TOKEN_OBJECTS[tokenid].options.top.replace('px', '')) + (window.TOKEN_OBJECTS[tokenid].options.size / 2)) / window.CURRENT_SCENE_DATA.scale_factor;
let pixeldata = fogContext.getImageData(left, top, 1, 1).data;
if (!window.TOKEN_OBJECTS[tokenid].options.revealInFog && pixeldata[3] >= 100)
return true;
else
return false;
}
function is_token_in_raycasting_context(tokenid, rayContext=undefined){
if(rayContext == undefined){
rayContext = $("#raycastingCanvas")[0].getContext('2d');
}
let pixeldata = rayContext.getImageData((parseInt(window.TOKEN_OBJECTS[tokenid].options.left.replace('px', ''))/ window.CURRENT_SCENE_DATA.scale_factor) + (window.TOKEN_OBJECTS[tokenid].sizeWidth()/2/ window.CURRENT_SCENE_DATA.scale_factor),(parseInt(window.TOKEN_OBJECTS[tokenid].options.top.replace('px', ''))/ window.CURRENT_SCENE_DATA.scale_factor)+(window.TOKEN_OBJECTS[tokenid].sizeHeight()/2/ window.CURRENT_SCENE_DATA.scale_factor), 1, 1).data;
for(let i=0; i<pixeldata.length; i+=4){
if(pixeldata[i]>4 || pixeldata[i+1]>4 || pixeldata[i+2]>4){
return true;
}
}
return false;
}
function is_token_under_light_aura(tokenid, lightContext=undefined){
if(lightContext == undefined){
lightContext = window.lightInLos.getContext('2d');
}
let pixeldata = lightContext.getImageData(parseInt(window.TOKEN_OBJECTS[tokenid].options.left.replace('px', ''))/ window.CURRENT_SCENE_DATA.scale_factor, parseInt(window.TOKEN_OBJECTS[tokenid].options.top.replace('px', ''))/ window.CURRENT_SCENE_DATA.scale_factor, window.TOKEN_OBJECTS[tokenid].sizeWidth()/window.CURRENT_SCENE_DATA.scale_factor, window.TOKEN_OBJECTS[tokenid].sizeHeight()/window.CURRENT_SCENE_DATA.scale_factor).data;
for(let i=0; i<pixeldata.length; i+=4){
if(pixeldata[i]>4 || pixeldata[i+1]>4 || pixeldata[i+2]>4){
return true;
}
}
return false;
}
function is_token_under_truesight_aura(tokenid, truesightContext=undefined){
if(truesightContext == undefined){
truesightContext = window.truesightCanvas.getContext('2d', {willReadFrequently: true});
}
let pixeldata = truesightContext.getImageData(parseInt(window.TOKEN_OBJECTS[tokenid].options.left.replace('px', ''))/ window.CURRENT_SCENE_DATA.scale_factor, parseInt(window.TOKEN_OBJECTS[tokenid].options.top.replace('px', ''))/ window.CURRENT_SCENE_DATA.scale_factor, window.TOKEN_OBJECTS[tokenid].sizeWidth()/ window.CURRENT_SCENE_DATA.scale_factor, window.TOKEN_OBJECTS[tokenid].sizeHeight()/ window.CURRENT_SCENE_DATA.scale_factor).data;
for(let i=0; i<pixeldata.length; i+=4){
if(pixeldata[i]>4 || pixeldata[i+1]>4 || pixeldata[i+2]>4)
return true;
}
return false;
}
function is_door_under_fog(door, fogContext=undefined){
if(window.DM)
return false;
if(fogContext == undefined){
fogContext = $('#fog_overlay')[0].getContext('2d', {willReadFrequently: true});
}
let left = parseFloat($(door).css('--mid-x'))/window.CURRENT_SCENE_DATA.scale_factor;
let top = parseFloat($(door).css('--mid-y'))/window.CURRENT_SCENE_DATA.scale_factor;
let pixeldata = fogContext.getImageData(left, top, 1, 1).data;
if (pixeldata[3] >= 253)
return true;
else
return false;
}
function is_door_under_light_aura(door, lightContext=undefined){
if(lightContext == undefined){
lightContext = window.lightInLos.getContext('2d', {willReadFrequently: true});
}
let left = parseFloat($(door).css('--mid-x'))/window.CURRENT_SCENE_DATA.scale_factor;
let top = parseFloat($(door).css('--mid-y'))/window.CURRENT_SCENE_DATA.scale_factor;
let pixeldata = lightContext.getImageData(left-5, top-5, 10, 10).data;
for(let i=0; i<pixeldata.length; i+=4){
if(pixeldata[i]>4 || pixeldata[i+1]>4 || pixeldata[i+2]>4)
return true;
}
return false;
}
function check_single_token_visibility(id){
console.log("check_single_token_visibility");
if (window.DM || $("#fog_overlay").is(":hidden") || window.TOKEN_OBJECTS[id].options.combatGroupToken)
return;
let fogContext = $('#fog_overlay')[0].getContext('2d');
let auraSelectorId = id.replaceAll("/", "").replaceAll('.', '');
let auraSelector = ".aura-element[id='aura_" + auraSelectorId + "']";
let selector = "div.token[data-id='" + id + "']";
let playerTokenId = $(`.token[data-id*='${window.PLAYER_ID}']`).attr("data-id");
let playerHasTruesight = (playerTokenId == undefined) ? false : window.TOKEN_OBJECTS[playerTokenId].options.sight == 'truesight';
let playerTokenHasVision = (playerTokenId == undefined) ? ((window.walls.length > 4 || window.CURRENT_SCENE_DATA.darkness_filter > 0) ? true : false) : window.TOKEN_OBJECTS[playerTokenId].options.auraislight;
const hideThisTokenInFogOrDarkness = (!window.TOKEN_OBJECTS[id].options.revealInFog); //we want to hide this token in fog or darkness
const inFog = playerTokenId != id && is_token_under_fog(id, fogContext); // this token is in fog
const notInLight = (inFog || (window.CURRENT_SCENE_DATA.disableSceneVision != 1 && playerTokenHasVision && !is_token_in_raycasting_context(id)) || (window.CURRENT_SCENE_DATA.disableSceneVision != 1 && playerTokenHasVision && !is_token_under_light_aura(id) )); // this token is not in light, the player is using vision/light and darkness > 0
const dmSelected = window.DM && $(tokenSelector).hasClass('tokenselected');
const showThisPlayerToken = window.TOKEN_OBJECTS[id].options.itemType == 'pc' && !window.DM && playerTokenId == undefined //show this token when logged in as a player without your own token
const hideInvisible = !dmSelected && window.TOKEN_OBJECTS[id].options.conditions.some(d=> d.name == 'Invisible') && playerTokenId != id && window.TOKEN_OBJECTS[id].options.share_vision != true && window.TOKEN_OBJECTS[id].options.share_vision != window.myUser
let inTruesight = false;
if(window.TOKEN_OBJECTS[id].conditions.includes('Invisible') && $(`.aura-element-container-clip.truesight`).length>0 ){
inTruesight = is_token_under_truesight_aura(id);
}
if (!showThisPlayerToken && (hideThisTokenInFogOrDarkness && notInLight || (window.TOKEN_OBJECTS[id].options.hidden && !inTruesight) || (hideInvisible && !inTruesight))) {
$(selector + "," + auraSelector).hide();
}
else if (!window.TOKEN_OBJECTS[id].options.hidden || inTruesight) {
$(selector).css('opacity', 1);
$(selector).show();
if(!window.TOKEN_OBJECTS[id].options.hideaura && id != playerTokenId)
$(auraSelector).show();
//console.log('SHOW '+id);
}
}
// if it was not executed in the last 1 second, execute it immediately and asynchronously
// if it's already scheduled to be executed, return
// otherwise, schedule it to execute in 1 second
async function check_token_visibility(){
if(window.DM)
return;
else if(window.NEXT_CHECK_TOKEN_VISIBILITY && (window.NEXT_CHECK_TOKEN_VISIBILITY - Date.now() > 0)){
return;
}
else if(!window.NEXT_CHECK_TOKEN_VISIBILITY || (window.NEXT_CHECK_TOKEN_VISIBILITY - Date.now() < -1000)){
window.NEXT_CHECK_TOKEN_VISIBILITY = Date.now();
await do_check_token_visibility();
return;
}
else {
window.NEXT_CHECK_TOKEN_VISIBILITY = Date.now() + 1000;
setTimeout(async () => do_check_token_visibility(), 1000);
return;
}
}
function do_check_token_visibility() {
console.log("do_check_token_visibility");
if(window.LOADING)
return;
if((window.DM && !window.SelectedTokenVision) || (window.DM && $('.tokenselected').length == 0)){
$(`.token`).show();
$(`.door-button`).css('visibility', '');
$(`.aura-element`).show();
return;
}
let canvas = document.getElementById("fog_overlay");
if (canvas.style.diplay == "none")
return;
let ctx = canvas.getContext("2d", { willReadFrequently: true });
let promises = [];
let lightContext = window.lightInLos.getContext('2d');
let rayContext = $('#raycastingCanvas')[0].getContext('2d');
const truesightAuraExists = $(`.aura-element-container-clip.truesight`).length>0;
let truesightContext;
if(truesightAuraExists)
truesightContext = window.truesightCanvas.getContext('2d');
let playerTokenId = $(`.token[data-id*='${window.PLAYER_ID}']`).attr("data-id");
let playerTokenHasVision = (playerTokenId == undefined) ? ((window.walls.length > 4 || window.CURRENT_SCENE_DATA.darkness_filter > 0) ? true : false) : window.TOKEN_OBJECTS[playerTokenId].options.auraislight;
let playerHasTruesight = (playerTokenId == undefined) ? false : window.TOKEN_OBJECTS[playerTokenId].options.sight == 'truesight';
for (let id in window.TOKEN_OBJECTS) {
if(window.TOKEN_OBJECTS[id].options.combatGroupToken)
continue;
promises.push(new Promise(function() {
let auraSelectorId = id.replaceAll("/", "").replaceAll('.','');
let auraSelector = ".aura-element[id='aura_" + auraSelectorId + "']";
let tokenSelector = "div.token[data-id='" + id + "']";
//Combining some and filter cut down about 140ms for average sized picture
const hideThisTokenInFogOrDarkness = (!window.TOKEN_OBJECTS[id].options.revealInFog); //we want to hide this token in fog or darkness
const inFog = (playerTokenId != id && is_token_under_fog(id, ctx)); // this token is in fog and not the players token
const notInLight = (inFog || (window.CURRENT_SCENE_DATA.disableSceneVision != 1 && playerTokenHasVision && !is_token_in_raycasting_context(id, rayContext)) || (playerTokenId != id && window.CURRENT_SCENE_DATA.disableSceneVision != 1 && playerTokenHasVision && !is_token_under_light_aura(id, lightContext))); // this token is not in light, the player is using vision/light and darkness > 0
const dmSelected = window.DM && $(tokenSelector).hasClass('tokenselected')
const showThisPlayerToken = window.TOKEN_OBJECTS[id].options.itemType == 'pc' && !window.DM && playerTokenId == undefined //show this token when logged in as a player without your own token
const hideInvisible = !dmSelected && window.TOKEN_OBJECTS[id].options.conditions.some(d=> d.name == 'Invisible') && playerTokenId != id && window.TOKEN_OBJECTS[id].options.share_vision != true && window.TOKEN_OBJECTS[id].options.share_vision != window.myUser
let inTruesight = false;
if(window.TOKEN_OBJECTS[id].conditions.includes('Invisible') && truesightAuraExists){
inTruesight = is_token_under_truesight_aura(id, truesightContext);
}
if (!showThisPlayerToken && (hideThisTokenInFogOrDarkness && notInLight && !dmSelected || (window.TOKEN_OBJECTS[id].options.hidden && !inTruesight && !dmSelected) || (hideInvisible && !inTruesight))) {
$(tokenSelector + "," + auraSelector).hide();
}
else if (!window.TOKEN_OBJECTS[id].options.hidden || inTruesight) {
$(tokenSelector).css({'opacity': 1, 'display': 'flex'});
if(!window.TOKEN_OBJECTS[id].options.hideaura || id == playerTokenId)
$(auraSelector).show();
}else if(dmSelected){
$(tokenSelector).css({'display': 'flex'});
}
}));
}
let doors = $('.door-button');
for(let i=0; i<doors.length; i++){
let door = doors[i];
promises.push(new Promise(function() {
//Combining some and filter cut down about 140ms for average sized picture
const inFog = (is_door_under_fog(door, ctx)); // this token is in fog and not the players token
const notInLight = (inFog || (window.CURRENT_SCENE_DATA.disableSceneVision != 1 && playerTokenHasVision && !is_door_under_light_aura(door, lightContext) && (window.CURRENT_SCENE_DATA.darkness_filter > 0 || window.walls.length>4))); // this token is not in light, the player is using vision/light and darkness > 0
if (notInLight || $(door).hasClass('secret')) {
$(door).css('visibility', 'hidden');
}
else {
$(door).css('visibility', 'visible');
}
}));
}
Promise.all(promises);
console.log("finished");
}
function circle2(a, b) {
let R = a.r,
r = b.r,
dx = b.x - a.x,
dy = b.y - a.y,
d = Math.sqrt(dx * dx + dy * dy),
x = (d * d - r * r + R * R) / (2 * d),
y = Math.sqrt(R * R - x * x);
dx /= d;
dy /= d;
return [
[a.x + dx * x - dy * y, a.y + dy * x + dx * y],
[a.x + dx * x + dy * y, a.y + dy * x - dx * y]
];
}
function circle_intersection(x0, y0, r0, x1, y1, r1) {
let a, dx, dy, d, h, rx, ry;
let x2, y2;
/* dx and dy are the vertical and horizontal distances between
* the circle centers.
*/
dx = x1 - x0;
dy = y1 - y0;
/* Determine the straight-line distance between the centers. */
d = Math.sqrt((dy * dy) + (dx * dx));
/* Check for solvability. */
if (d > (r0 + r1)) {
/* no solution. circles do not intersect. */
return false;
}
if (d < Math.abs(r0 - r1)) {
/* no solution. one circle is contained in the other */
return false;
}
/* 'point 2' is the point where the line through the circle
* intersection points crosses the line between the circle
* centers.
*/
/* Determine the distance from point 0 to point 2. */
a = ((r0 * r0) - (r1 * r1) + (d * d)) / (2.0 * d);
/* Determine the coordinates of point 2. */
x2 = x0 + (dx * a / d);
y2 = y0 + (dy * a / d);
/* Determine the distance from point 2 to either of the
* intersection points.
*/
h = Math.sqrt((r0 * r0) - (a * a));
/* Now determine the offsets of the intersection points from
* point 2.
*/
rx = -dy * (h / d);
ry = dx * (h / d);
/* Determine the absolute intersection points. */
let xi = x2 + rx;
let xi_prime = x2 - rx;
let yi = y2 + ry;
let yi_prime = y2 - ry;
return [xi, xi_prime, yi, yi_prime];
}
function midPointBtw(p1, p2) {
return {
x: p1.x + (p2.x - p1.x) / 2,
y: p1.y + (p2.y - p1.y) / 2
};
}
function clear_grid(){
const gridCanvas = document.getElementById("grid_overlay");
const gridContext = gridCanvas.getContext("2d");
gridContext.clearRect(0, 0, gridCanvas.width, gridCanvas.height);
}
function redraw_hex_grid(hpps=null, vpps=null, offsetX=null, offsetY=null, color=null, lineWidth=null, subdivide=null, dash=[], columns=true, drawGrid = window.CURRENT_SCENE_DATA.grid){
const gridCanvas = document.getElementById("grid_overlay");
gridCanvas.width = $('#scene_map').width() / window.CURRENT_SCENE_DATA.scaleAdjustment.x
gridCanvas.height = $('#scene_map').height() / window.CURRENT_SCENE_DATA.scaleAdjustment.y;
const gridContext = gridCanvas.getContext("2d");
if(window.CURRENT_SCENE_DATA.gridType == 2){
hpps = vpps || window.CURRENT_SCENE_DATA.vpps;
window.CURRENT_SCENE_DATA.hpps = vpps || window.CURRENT_SCENE_DATA.vpps;
}
clear_grid();
gridContext.setLineDash(dash);
let startX = offsetX / window.CURRENT_SCENE_DATA.scale_factor || window.CURRENT_SCENE_DATA.offsetx / window.CURRENT_SCENE_DATA.scale_factor;
let startY = offsetY / window.CURRENT_SCENE_DATA.scale_factor || window.CURRENT_SCENE_DATA.offsety / window.CURRENT_SCENE_DATA.scale_factor;
startX = Math.round(startX)
startY = Math.round(startY)
const hexSize = hpps/1.5 / window.CURRENT_SCENE_DATA.scale_factor || window.CURRENT_SCENE_DATA.hpps/1.5 / window.CURRENT_SCENE_DATA.scale_factor;
gridContext.lineWidth = lineWidth || window.CURRENT_SCENE_DATA.grid_line_width;
gridContext.strokeStyle = color || window.CURRENT_SCENE_DATA.grid_color;
const a = 2 * Math.PI / 6;
if(window.CURRENT_SCENE_DATA.gridType == 2){
if(drawGrid == 1 || window.WIZARDING){
for (let x = startX, j = 0; x + hexSize * Math.sin(a) < gridCanvas.width+hexSize+startX; x += 2 ** ((j + 1) % 2) * hexSize * Math.sin(a), j = 0){
for (let y = startY; y + hexSize * (1 + Math.cos(a)) < gridCanvas.height+hexSize+startY; y += hexSize * (1 + Math.cos(a)), x += (-1) ** j++ * hexSize * Math.sin(a)){
drawHexagon(x, y);
}
}
}
let hexWidth = hexSize * Math.sin(a) * 2 * window.CURRENT_SCENE_DATA.scale_factor;
let hexHeight = hexSize * (1 + Math.cos(a)) * window.CURRENT_SCENE_DATA.scale_factor;
window.hexGridSize = {
width: hexWidth,
height: hexHeight
}
}
else{
if(drawGrid == 1 || window.WIZARDING){
for (let y = startY, j = 0; y + hexSize * Math.sin(a) < gridCanvas.height+startY+hexSize; y += 2 ** ((j + 1) % 2) * hexSize * Math.sin(a), j = 0){
for (let x = startX; x + hexSize * (1 + Math.cos(a)) < gridCanvas.width+startX+hexSize; x += hexSize * (1 + Math.cos(a)), y += (-1) ** j++ * hexSize * Math.sin(a)){
drawHexagon(x, y);
}
}
}
let hexWidth = hexSize * (1 + Math.cos(a)) * window.CURRENT_SCENE_DATA.scale_factor;
let hexHeight = hexSize * Math.sin(a) * 2 * window.CURRENT_SCENE_DATA.scale_factor;
window.hexGridSize = {
width: hexWidth,
height: hexHeight
}
}
function drawHexagon(x, y) {
if(window.CURRENT_SCENE_DATA.gridType == 3){
gridContext.beginPath();
gridContext.moveTo(x + hexSize, y);
for (let i = 1; i <= 6; i++) {
let angle = i * Math.PI / 3;
let dx = hexSize * Math.cos(angle);
let dy = hexSize * Math.sin(angle);
gridContext.lineTo(x + dx, y + dy);
}
gridContext.closePath();
gridContext.stroke();
}
else{
gridContext.beginPath();
gridContext.moveTo(x, y + hexSize);
for (let i = 1; i <= 6; i++) {
let angle = i * Math.PI / 3;
let dx = hexSize * Math.sin(angle);
let dy = hexSize * Math.cos(angle);
gridContext.lineTo(x + dx, y + dy);
}
gridContext.closePath();
gridContext.stroke();
}
}
$('#grid_overlay').css('transform', `scale(calc(var(--scene-scale) * ${window.CURRENT_SCENE_DATA.scaleAdjustment.x}), calc(var(--scene-scale) * ${window.CURRENT_SCENE_DATA.scaleAdjustment.y}))`)
}
function redraw_grid(hpps=null, vpps=null, offsetX=null, offsetY=null, color=null, lineWidth=null, subdivide=null, dash=[]){
if(window.CURRENT_SCENE_DATA.gridType && window.CURRENT_SCENE_DATA.gridType != 1){
let type = (window.CURRENT_SCENE_DATA.gridType == 2) ? false : true;
redraw_hex_grid(hpps, vpps, offsetX, offsetY, color, lineWidth, subdivide, dash, type)
return;
}
if(window.CURRENT_SCENE_DATA.grid != '1' && !window.WIZARDING){
return;
}
const gridCanvas = document.getElementById("grid_overlay");
gridCanvas.width = $('#scene_map').width();
gridCanvas.height = $('#scene_map').height();
const gridContext = gridCanvas.getContext("2d");
clear_grid();
gridContext.setLineDash(dash);
let startX = offsetX / window.CURRENT_SCENE_DATA.scale_factor || window.CURRENT_SCENE_DATA.offsetx / window.CURRENT_SCENE_DATA.scale_factor;
let startY = offsetY / window.CURRENT_SCENE_DATA.scale_factor || window.CURRENT_SCENE_DATA.offsety / window.CURRENT_SCENE_DATA.scale_factor;