-
Notifications
You must be signed in to change notification settings - Fork 62
/
Token.js
4769 lines (4141 loc) · 196 KB
/
Token.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 STANDARD_CONDITIONS = ["Blinded", "Charmed", "Deafened", "Exhaustion", "Frightened", "Grappled", "Incapacitated", "Invisible", "Paralyzed", "Petrified", "Poisoned", "Prone", "Restrained", "Stunned", "Unconscious"];
const CUSTOM_CONDITIONS = ["Concentration(Reminder)", 'Reaction Used',"Flying", "Burning", "Rage", "Blessed", "Baned",
"Bloodied", "Advantage", "Disadvantage", "Bardic Inspiration", "Hasted",
"#1A6AFF", "#FF7433", "#FF4D4D", "#FFD433", "#884DFF", "#86FF66"];
/*const TOKEN_COLORS= [
"D1BBD7","882E72","5289C7","4EB265","CAEOAB","F6C141","E8601C","777777","AE76A3","1965BO","7BAFDE","90C987","F7F056","F1932D","DC050C",
"FF0000", "00FF00", "0000FF", "FFFF00", "FF00FF", "00FFFF",
"800000", "008000", "000080", "808000", "800080", "008080", "808080",
"C00000", "00C000", "0000C0", "C0C000", "C000C0", "00C0C0", "C0C0C0",
"400000", "004000", "000040", "404000", "400040", "004040", "404040",
"200000", "002000", "000020", "202000", "200020", "002020", "202020",
"600000", "006000", "000060", "606000", "600060", "006060", "606060",
"A00000", "00A000", "0000A0", "A0A000", "A000A0", "00A0A0", "A0A0A0",
"E00000", "00E000", "0000E0", "E0E000", "E000E0", "00E0E0", "E0E0E0", "000000"];*/
// const TOKEN_COLORS = ["8DB6C7","","D1C6BF","CA9F92","","E3D9BO","B1C27A","B2E289","51COBF","59ADDO","","9FA3E3","099304","DB8DB2","F1C3DO"];
const TOKEN_COLORS = ["1A6AFF", "FF7433", "FFD433", "884DFF", "5F0404", "EC8AFF", "00E5FF",
"000000", "F032E6", "911EB4", //END OF NEW COLORS
"800000", "008000", "000080", "808000", "800080", "008080", "808080", "C00000", "00C000", "0000C0",
"C0C000", "C000C0", "00C0C0", "C0C0C0", "400000", "004000", "000040",
"404000", "400040", "004040", "404040", "200000", "002000", "000020",
"202000", "200020", "002020", "202020", "600000", "006000", "000060",
"606000", "600060", "006060", "606060", "A00000", "00A000", "0000A0",
"A0A000", "A000A0", "00A0A0", "A0A0A0", "E00000", "00E000", "0000E0",
"E0E000", "E000E0", "00E0E0", "E0E0E0"];
const availableToAoe = [
"hidden",
"locked",
"restrictPlayerMove",
"revealname",
"revealInFog",
"lockRestrictDrop",
"underDarkness"
];
let debounceLightChecks = mydebounce(() => {
if(window.DRAGGING)
return;
if(window.walls?.length < 5){
redraw_light_walls();
}
//let promise = [new Promise (_ => setTimeout(redraw_light(), 1000))];
redraw_light();
debounceAudioChecks();
}, 20);
let debounceAudioChecks = mydebounce(() => {
checkAudioVolume();
}, 20)
function random_token_color() {
const randomColorIndex = getRandomInt(0, TOKEN_COLORS.length);
return "#" + TOKEN_COLORS[randomColorIndex];
}
class Token {
// Defines how many token-sizes a token is allowed to be moved outside of the scene.
SCENE_MOVE_GRID_PADDING_MULTIPLIER = 1;
MIN_TOKEN_SIZE = 25;
MAX_TOKEN_SIZE = 1000;
constructor(options) {
this.selected = false;
this.options = options;
this.sync = null;
this.persist= ()=>{};
this.doing_highlight = false;
if (typeof this.options.size == "undefined") {
this.options.size = window.CURRENT_SCENE_DATA.hpps; // one grid square
}
if (typeof options.custom_conditions == "undefined") {
this.options.custom_conditions = [];
}
if (typeof options.conditions == "undefined") {
this.options.conditions = [];
}
}
/** @return {number} the total of this token's HP and temp HP */
get hp() {
return this.baseHp + this.tempHp;
}
set hp(newValue) {
this.baseHp = newValue;
}
/** @return {number} the percentage of this token's base HP divided by it's max hp */
get hpPercentage() {
// If we choose to include tempHp in this calculation, we need to make sure functions like token_health_aura can handle percentages that are greater than 100%
return Math.round((this.baseHp / this.maxHp) * 100)
}
/** @return {number} the value of this token's HP without adding temp HP */
get baseHp() {
if (!isNaN(this.options.hitPointInfo?.current)) {
return parseInt(this.options.hitPointInfo.current);
} else if (!isNaN((this.options.hp))) {
return parseInt(this.options.hp);
}
return 0;
}
set baseHp(newValue) {
let currentHP = this.options.hitPointInfo ? this.options.hitPointInfo.current : this.options.hp
if (this.options.hitPointInfo) {
this.options.hitPointInfo.current = newValue;
} else {
this.options.hitPointInfo = {
maximum: this.maxHp,
current: newValue,
temp: this.tempHp
};
}
if(window.DM && currentHP > newValue && this.hasCondition("Concentration(Reminder)")){
// CONCENTRATION REMINDER
let msgdata = {
player: this.options.name,
img: parse_img(this.options.imgsrc),
text: `<b>Check for concentration! If damage was from a single source DC ${Math.floor((this.options.hp - newValue)/2) > 10 ? Math.floor((this.options.hp - newValue)/2) : 10}</b>`,
};
window.MB.inject_chat(msgdata);
}
this.options.hp = newValue; // backwards compatibility
}
check_concentration(newValue){
}
/** @return {number} the value of this token's temp HP */
get tempHp() {
if (!isNaN(this.options.hitPointInfo?.temp)) {
return parseInt(this.options.hitPointInfo.temp);
} else if (!isNaN(this.options.temp_hp)) {
return parseInt(this.options.temp_hp);
}
return 0;
}
set tempHp(newValue) {
if (this.options.hitPointInfo) {
this.options.hitPointInfo.temp = newValue;
} else {
this.options.hitPointInfo = {
maximum: this.maxHp,
current: this.baseHp,
temp: newValue
};
}
this.options.temp_hp = newValue; // backwards compatibility
}
/** @return {number} the value of this token's max HP */
get maxHp() {
if (!isNaN(this.options.hitPointInfo?.maximum)) {
return parseInt(this.options.hitPointInfo.maximum);
} else if (!isNaN((this.options.max_hp))) {
return parseInt(this.options.max_hp);
}
return 0;
}
set maxHp(newValue) {
if (this.options.hitPointInfo) {
this.options.hitPointInfo.maximum = newValue;
} else {
this.options.hitPointInfo = {
maximum: newValue,
current: this.baseHp,
temp: this.tempHp
};
}
this.options.max_hp = newValue; // backwards compatibility
}
/** @return {number} the value of this token's AC */
get ac() {
if (!isNaN(this.options.armorClass)) {
return parseInt(this.options.armorClass);
} else if (!isNaN(this.options.ac)) {
return parseInt(this.options.ac);
}
return 0;
}
set ac(newValue) {
this.options.armorClass = newValue;
this.options.ac = newValue; // backwards compatibility
}
/** @return {string[]} the names of the conditions currently active on the token */
get conditions() {
return this.options.conditions.map(c => {
if (typeof c === "string") {
return c;
} else if (c.constructor === Object) {
if (c.level) {
return c.level > 0 ? `${c.name} (Level ${c.level})` : undefined; // only return levels greater than 0. This is probably only Exhaustion
}
return c.name;
}
}).filter(c => c); // remove undefined and empty strings
}
stopAnimation(){
const tok = $(`#tokens div[data-id="${this.options.id}"]`);
if (tok.length === 0) {
this.update_opacity(undefined);
return;
}
tok.stop(true, true);
this.doing_highlight = false;
this.update_opacity(tok, false);
$('.token[data-clone-id^="dragging-"]').remove();
debounceLightChecks();
}
isLineAoe() {
// 1 being a single square which is usually 5ft
return (this.options.size === "" || this.options.size === 0) && this.options.gridWidth === 1 && this.options.gridHeight > 0
}
isAoe() {
return this.options.imgsrc?.startsWith("class")
}
isPlayer() {
// player tokens have ids with a structure like "/profile/username/characters/someId" or "characters/someId"
// monster tokens have a uuid for their id
return is_player_id(this.options.id);
}
isCurrentPlayer() {
return this.isPlayer() && this.options.id.endsWith(`characters/${window.PLAYER_ID}`)
}
isMonster() {
if (this.options.monster === undefined) {
return false;
} else if (typeof this.options.monster === "string") {
return this.options.monster.length > 0;
} else if (typeof this.options.monster === "number") {
return this.options.monster > 0;
} else {
return false;
}
}
// number of grid spaces. eg: 0.5 for tiny, 1 for small/medium, 2 for large, etc
numberOfGridSpacesWide() {
try {
let output = 1;
const w = parseFloat(this.options.gridWidth);
if (!isNaN(w)) {
output = w;
} else {
let tokenMultiplierAdjustment = (!window.CURRENT_SCENE_DATA.scaleAdjustment) ? 1 : (window.CURRENT_SCENE_DATA.scaleAdjustment.x > window.CURRENT_SCENE_DATA.scaleAdjustment.y) ? window.CURRENT_SCENE_DATA.scaleAdjustment.x : window.CURRENT_SCENE_DATA.scaleAdjustment.y;
const calculatedFromSize = (parseFloat(this.options.size) / (parseFloat(window.CURRENT_SCENE_DATA.hpps) * tokenMultiplierAdjustment));
if (!isNaN(calculatedFromSize)) {
output = calculatedFromSize;
}
}
output = Math.round(output * 2) / 2; // round to the nearest 0.5; ex: everything between 0.25 and 0.74 round to 0.5; below .025 rounds to 0, and everything above 0.74 rounds to 1
if (output < 0.5) {
return 0.5;
}
return output;
} catch (error) {
console.warn("Failed to parse gridHeight for token", this, error);
return 1;
}
}
// number of grid spaces. eg: 0.5 for tiny, 1 for small/medium, 2 for large, etc
numberOfGridSpacesTall() {
try {
let output = 1;
const h = parseFloat(this.options.gridHeight);
if (!isNaN(h)) {
output = h;
} else {
let tokenMultiplierAdjustment = (!window.CURRENT_SCENE_DATA.scaleAdjustment) ? 1 : (window.CURRENT_SCENE_DATA.scaleAdjustment.x > window.CURRENT_SCENE_DATA.scaleAdjustment.y) ? window.CURRENT_SCENE_DATA.scaleAdjustment.x : window.CURRENT_SCENE_DATA.scaleAdjustment.y;
const calculatedFromSize = (parseFloat(this.options.size) / (parseFloat(window.CURRENT_SCENE_DATA.vpps)*tokenMultiplierAdjustment));
if (!isNaN(calculatedFromSize)) {
output = calculatedFromSize;
}
}
output = Math.round(output * 2) / 2; // round to the nearest 0.5; ex: everything between 0.25 and 0.74 round to 0.5; below .025 rounds to 0, and everything above 0.74 rounds to 1
if (output < 0.5) {
return 0.5;
}
return output;
} catch (error) {
console.warn("Failed to parse gridHeight for token", this, error);
return 1;
}
}
// number of pixels
sizeWidth() {
let w = parseInt(this.options.gridWidth);
if (isNaN(w)) return this.options.size;
return parseInt(window.CURRENT_SCENE_DATA.hpps) * w;
}
// number of pixels
sizeHeight() {
let h = parseInt(this.options.gridHeight);
if (isNaN(h)) return this.options.size;
return parseInt(window.CURRENT_SCENE_DATA.vpps) * h;
}
hasCondition(conditionName) {
return this.conditions.includes(conditionName) || this.options.custom_conditions.some(e => e.name === conditionName);
}
conditionDuration(conditionName) {
let c = this.options.conditions.find(c => c.name == conditionName) || this.options.custom_conditions.find(c => c.name == conditionName);
return c?.duration;
}
addCondition(conditionName, text='') {
if (this.hasCondition(conditionName)) {
// already did
return;
}
if (STANDARD_CONDITIONS.includes(conditionName)) {
if (this.isPlayer()) {
if(this.isCurrentPlayer()){
$('.ct-combat__statuses-group--conditions .ct-combat__summary-label:contains("Conditions"), .ct-combat-tablet__cta-button:contains("Conditions"), .ct-combat-mobile__cta-button:contains("Conditions")').click();
$('.ct-condition-manage-pane').css('visibility', 'hidden');
$(`.ct-sidebar__inner .ct-condition-manage-pane__condition-name:contains('${conditionName}') ~ .ct-condition-manage-pane__condition-toggle>[class*='styles_toggle'][aria-pressed="false"]`).click();
this.options.conditions.push({ name: conditionName });
setTimeout(function(){
$(`#switch_gamelog`).click();
}, 10)
}
else{
window.MB.inject_chat({
player: window.PLAYER_NAME,
img: window.PLAYER_IMG,
text: `<span class="flex-wrap-center-chat-message">${window.PLAYER_NAME} would like you to set<span style="margin-left: 3px; display: inline-block; font-weight: 700;">${conditionName}</span>.<br/><br/><button class="set-conditions-button">Toggle ${conditionName} ON</button></div>`,
whisper: this.options.name
});
}
} else {
this.options.conditions.push({ name: conditionName });
}
} else {
let condition = {
'name': conditionName,
'text': text
}
this.options.custom_conditions.push(condition);
}
}
removeCondition(conditionName) {
if (STANDARD_CONDITIONS.includes(conditionName)) {
if (this.isPlayer()) {
if(this.isCurrentPlayer()){
$('.ct-combat__statuses-group--conditions .ct-combat__summary-label:contains("Conditions"), .ct-combat-tablet__cta-button:contains("Conditions"), .ct-combat-mobile__cta-button:contains("Conditions")').click();
$('.ct-condition-manage-pane').css('visibility', 'hidden');
$(`.ct-sidebar__inner .ct-condition-manage-pane__condition-name:contains('${conditionName}') ~ .ct-condition-manage-pane__condition-toggle>[class*='styles_toggle'][aria-pressed="true"]`).click();
this.options.conditions = this.options.conditions.filter(c => {
if (typeof c === "string") {
return c !== conditionName;
} else {
return c?.name !== conditionName;
}
});
setTimeout(function(){
$(`#switch_gamelog`).click();
}, 10)
}
else{
window.MB.inject_chat({
player: window.PLAYER_NAME,
img: window.PLAYER_IMG,
text: `<span class="flex-wrap-center-chat-message">${window.PLAYER_NAME} would like you to remove <span style="margin-left: 3px; display: inline-block; font-weight: 700;">${conditionName}</span>.<br/><br/><button class="remove-conditions-button">Toggle ${conditionName} OFF</button></div>`,
whisper: this.options.name
});
}
} else {
this.options.conditions = this.options.conditions.filter(c => {
if (typeof c === "string") {
return c !== conditionName;
} else {
return c?.name !== conditionName;
}
});
}
} else {
array_remove_index_by_value(this.options.custom_conditions, conditionName);
}
}
isInCombatTracker() {
return ct_list_tokens().includes(this.options.id);
}
size(newSize) {
this.MAX_TOKEN_SIZE = Math.max(window.CURRENT_SCENE_DATA.width*window.CURRENT_SCENE_DATA.scale_factor, window.CURRENT_SCENE_DATA.height*window.CURRENT_SCENE_DATA.scale_factor);
// Clamp token size to min/max token size
newSize = clamp(newSize, this.MIN_TOKEN_SIZE, this.MAX_TOKEN_SIZE);
this.update_from_page();
if(this.isLineAoe()) {
// token is not proportional such as a line aoe token
this.options.gridHeight = Math.round(newSize / parseFloat(window.CURRENT_SCENE_DATA.hpps));
}
else {
this.options.size = newSize;
this.options.gridSquares = newSize / parseFloat(window.CURRENT_SCENE_DATA.hpps);
}
this.place_sync_persist();
}
imageSize(imageScale) {
this.update_from_page();
this.options.imageSize = imageScale;
this.place_sync_persist()
}
hide() {
this.update_from_page();
this.options.hidden = true;
if(this.options.ct_show !== undefined){//this is required as if it's undefined it's not in the combat tracker and changing it will add it to the combat tracker on next scene swap unintendedly.
this.options.ct_show = false;
}
if(this.options.monster) {
$("#"+this.options.id+"hideCombatTrackerInput ~ button svg.closedEye").css('display', 'block');
$("#"+this.options.id+"hideCombatTrackerInput ~ button svg.openEye").css('display', 'none');
}
this.place_sync_persist()
debounceCombatPersist();
}
show() {
this.update_from_page();
delete this.options.hidden;
if(this.options.ct_show !== undefined){//this is required as if it's undefined it's not in the combat tracker and changing it will add it to the combat tracker on next scene swap unintendedly.
this.options.ct_show = true;
}
if(this.options.monster) {
$("#"+this.options.id+"hideCombatTrackerInput ~ button svg.openEye").css('display', 'block');
$("#"+this.options.id+"hideCombatTrackerInput ~ button svg.closedEye").css('display', 'none');
}
this.place_sync_persist()
debounceCombatPersist();
}
delete(persist=true) {
if (!window.DM && this.options.deleteableByPlayers != true) {
// only allow the DM to delete tokens unless the token specifies deleteableByPlayers == true which is used by AoE tokens and maybe others
return;
}
ct_remove_token(this, false);
let id = this.options.id;
let selector = "#tokens div[data-id='" + id + "']";
$(selector).remove();
delete window.CURRENT_SCENE_DATA.tokens[id];
delete window.TOKEN_OBJECTS[id];
if(!is_player_id(this.options.id)){
delete window.all_token_objects[id];
if (id in window.JOURNAL.notes) {
delete window.JOURNAL.notes[id];
window.JOURNAL.persist();
}
}
$("#aura_" + id.replaceAll("/", "")).remove();
$(`.aura-element-container-clip[id='${id}']`).remove()
$(`[data-darkness='darkness_${id}']`).remove();
$(`[data-notatoken='notatoken_${id}']`).remove()
if (persist == true) {
window.MB.sendMessage("custom/myVTT/delete_token",{id:id});
}
if(this.options?.audioChannel?.audioId != undefined){
window.MIXER.deleteChannel(this.options.audioChannel.audioId)
}
if(this.options.combatGroupToken){
for(let i in window.TOKEN_OBJECTS){
if(i == this.options.combatGroupToken)
continue;
if(window.TOKEN_OBJECTS[i].options.combatGroup == this.options.combatGroupToken){
delete window.TOKEN_OBJECTS[i].options.combatGroup;
delete window.TOKEN_OBJECTS[i].options.ct_show;
if(window.all_token_objects[i] != undefined){
delete window.all_token_objects[i].options.combatGroup;
delete window.all_token_objects[i].options.ct_show;
}
ct_remove_token(window.TOKEN_OBJECTS[i]);
window.TOKEN_OBJECTS[i].update_and_sync();
}
}
}
if(this.options.combatGroup && !this.options.combatGroupToken){
let count = 0;
for(let i in window.TOKEN_OBJECTS){
if(window.TOKEN_OBJECTS[i].options.combatGroup == this.options.combatGroup){
count++;
}
}
if(count == 1){
window.TOKEN_OBJECTS[this.options.combatGroup].delete();
}
}
debounceLightChecks();
update_pc_token_rows();
}
rotate(newRotation) {
if (!window.DM && (this.options.restrictPlayerMove || this.options.locked) && !this.isCurrentPlayer()) return; // don't allow rotating if the token is locked
if (window.DM && this.options.locked && !$('#select_locked .ddbc-tab-options__header-heading').hasClass('ddbc-tab-options__header-heading--is-active')) return; // don't allow rotating if the token is locked
this.update_from_page();
this.options.rotation = newRotation;
// this is copied from the place() function. Rather than calling place() every time the draggable.drag function executes,
// this just rotates locally to help with performance.
// draggable.stop will call place_sync_persist to finalize the rotation.
// If we ever want this to send to all players in real time, simply comment out the rest of this function and call place_sync_persist() instead.
let scale = this.get_token_scale();
if(this.options.imageSize === undefined) {
this.imageSize(1)
}
let imageScale = (this.options.imageSize != undefined) ? this.options.imageSize : 1;
let selector = "div[data-id='" + this.options.id + "']";
let tokenElement = $("#tokens").find(selector).add(`[data-notatoken='notatoken_${this.options.id}']`);
tokenElement.css("--token-rotation", newRotation + "deg");
tokenElement.css("--token-scale", imageScale);
tokenElement.find(".token-image").css("transform", `scale(var(--token-scale)) rotate(var(--token-rotation))`);
$(`.aura-element-container-clip[id='${this.options.id}'] .aura-element, .aura-element[data-id='${this.options.id}']`).css('--rotation', newRotation + "deg");
}
moveUp() {
let tinyToken = (Math.round(parseFloat(this.options.gridSquares)*2)/2 < 1) || this.isAoe();
let addvpps = (window.CURRENT_SCENE_DATA.gridType && window.CURRENT_SCENE_DATA.gridType != 1) ? window.hexGridSize.height * window.CURRENT_SCENE_DATA.scaleAdjustment.y : (!tinyToken || window.CURRENTLY_SELECTED_TOKENS.length > 1) ? parseFloat(window.CURRENT_SCENE_DATA.vpps) : parseFloat(window.CURRENT_SCENE_DATA.vpps)/2;
let newTop = `${parseFloat(this.options.top) - addvpps/2-5}px`;
this.move(newTop, parseFloat(this.options.left)+5)
}
moveDown() {
let tinyToken = (Math.round(parseFloat(this.options.gridSquares)*2)/2 < 1) || this.isAoe();
let addvpps = (window.CURRENT_SCENE_DATA.gridType && window.CURRENT_SCENE_DATA.gridType != 1) ? window.hexGridSize.height * window.CURRENT_SCENE_DATA.scaleAdjustment.y : (!tinyToken || window.CURRENTLY_SELECTED_TOKENS.length > 1) ? parseFloat(window.CURRENT_SCENE_DATA.vpps) : parseFloat(window.CURRENT_SCENE_DATA.vpps)/2;
let newTop = `${parseFloat(this.options.top) + addvpps+5}px`;
this.move(newTop, parseFloat(this.options.left)+5)
}
moveLeft() {
let tinyToken = (Math.round(parseFloat(this.options.gridSquares)*2)/2 < 1) || this.isAoe();
let addhpps = (window.CURRENT_SCENE_DATA.gridType && window.CURRENT_SCENE_DATA.gridType != 1) ? window.hexGridSize.width * window.CURRENT_SCENE_DATA.scaleAdjustment.x : (!tinyToken || window.CURRENTLY_SELECTED_TOKENS.length > 1) ? parseFloat(window.CURRENT_SCENE_DATA.hpps) : parseFloat(window.CURRENT_SCENE_DATA.hpps)/2;
let newLeft = `${parseFloat(this.options.left) - addhpps/2-5}px`;
this.move(parseFloat(this.options.top)+5, newLeft)
}
moveRight() {
let tinyToken = (Math.round(parseFloat(this.options.gridSquares)*2)/2 < 1) || this.isAoe();
let addhpps = (window.CURRENT_SCENE_DATA.gridType && window.CURRENT_SCENE_DATA.gridType != 1) ? window.hexGridSize.width * window.CURRENT_SCENE_DATA.scaleAdjustment.x : (!tinyToken || window.CURRENTLY_SELECTED_TOKENS.length > 1) ? parseFloat(window.CURRENT_SCENE_DATA.hpps) : parseFloat(window.CURRENT_SCENE_DATA.hpps)/2;
let newLeft = `${parseFloat(this.options.left) + addhpps+5}px`;
this.move(parseFloat(this.options.top)+5, newLeft)
}
moveUpRight() {
let tinyToken = (Math.round(parseFloat(this.options.gridSquares)*2)/2 < 1) || this.isAoe();
let addhpps = (window.CURRENT_SCENE_DATA.gridType && window.CURRENT_SCENE_DATA.gridType != 1) ? window.hexGridSize.width * window.CURRENT_SCENE_DATA.scaleAdjustment.x : (!tinyToken || window.CURRENTLY_SELECTED_TOKENS.length > 1) ? parseFloat(window.CURRENT_SCENE_DATA.hpps) : parseFloat(window.CURRENT_SCENE_DATA.hpps)/2;
let newLeft = `${parseFloat(this.options.left) + addhpps+5}px`;
let addvpps = (window.CURRENT_SCENE_DATA.gridType && window.CURRENT_SCENE_DATA.gridType != 1) ? window.hexGridSize.height * window.CURRENT_SCENE_DATA.scaleAdjustment.y : (!tinyToken || window.CURRENTLY_SELECTED_TOKENS.length > 1) ? parseFloat(window.CURRENT_SCENE_DATA.vpps) : parseFloat(window.CURRENT_SCENE_DATA.vpps)/2;
let newTop = `${parseFloat(this.options.top) - addvpps/2-5}px`;
this.move(newTop, newLeft)
}
moveDownRight() {
let tinyToken = (Math.round(parseFloat(this.options.gridSquares)*2)/2 < 1) || this.isAoe();
let addhpps = (window.CURRENT_SCENE_DATA.gridType && window.CURRENT_SCENE_DATA.gridType != 1) ? window.hexGridSize.width * window.CURRENT_SCENE_DATA.scaleAdjustment.x : (!tinyToken || window.CURRENTLY_SELECTED_TOKENS.length > 1) ? parseFloat(window.CURRENT_SCENE_DATA.hpps) : parseFloat(window.CURRENT_SCENE_DATA.hpps)/2;
let newLeft = `${parseFloat(this.options.left) + addhpps+5}px`;
let addvpps = (window.CURRENT_SCENE_DATA.gridType && window.CURRENT_SCENE_DATA.gridType != 1) ? window.hexGridSize.height * window.CURRENT_SCENE_DATA.scaleAdjustment.y : (!tinyToken || window.CURRENTLY_SELECTED_TOKENS.length > 1) ? parseFloat(window.CURRENT_SCENE_DATA.vpps) : parseFloat(window.CURRENT_SCENE_DATA.vpps)/2;
let newTop = `${parseFloat(this.options.top) + addvpps+5}px`;
this.move(newTop, newLeft)
}
moveUpLeft() {
let tinyToken = (Math.round(parseFloat(this.options.gridSquares)*2)/2 < 1) || this.isAoe();
let addhpps = (window.CURRENT_SCENE_DATA.gridType && window.CURRENT_SCENE_DATA.gridType != 1) ? window.hexGridSize.width * window.CURRENT_SCENE_DATA.scaleAdjustment.x : (!tinyToken || window.CURRENTLY_SELECTED_TOKENS.length > 1) ? parseFloat(window.CURRENT_SCENE_DATA.hpps) : parseFloat(window.CURRENT_SCENE_DATA.hpps)/2;
let newLeft = `${parseFloat(this.options.left) - addhpps/2-5}px`;
let addvpps = (window.CURRENT_SCENE_DATA.gridType && window.CURRENT_SCENE_DATA.gridType != 1) ? window.hexGridSize.height * window.CURRENT_SCENE_DATA.scaleAdjustment.y : (!tinyToken || window.CURRENTLY_SELECTED_TOKENS.length > 1) ? parseFloat(window.CURRENT_SCENE_DATA.vpps) : parseFloat(window.CURRENT_SCENE_DATA.vpps)/2;
let newTop = `${parseFloat(this.options.top) - addvpps/2-5}px`;
this.move(newTop, newLeft)
}
moveDownLeft() {
let tinyToken = (Math.round(parseFloat(this.options.gridSquares)*2)/2 < 1) || this.isAoe();
let addhpps = (window.CURRENT_SCENE_DATA.gridType && window.CURRENT_SCENE_DATA.gridType != 1) ? window.hexGridSize.width * window.CURRENT_SCENE_DATA.scaleAdjustment.x : (!tinyToken || window.CURRENTLY_SELECTED_TOKENS.length > 1) ? parseFloat(window.CURRENT_SCENE_DATA.hpps) : parseFloat(window.CURRENT_SCENE_DATA.hpps)/2;
let newLeft = `${parseFloat(this.options.left) - addhpps/2-5}px`;
let addvpps = (window.CURRENT_SCENE_DATA.gridType && window.CURRENT_SCENE_DATA.gridType != 1) ? window.hexGridSize.height * window.CURRENT_SCENE_DATA.scaleAdjustment.y : (!tinyToken || window.CURRENTLY_SELECTED_TOKENS.length > 1) ? parseFloat(window.CURRENT_SCENE_DATA.vpps) : parseFloat(window.CURRENT_SCENE_DATA.vpps)/2;
let newTop = `${parseFloat(this.options.top) + addvpps+5}px`;
this.move(newTop, newLeft)
}
/**
* Move token to new position.
* @param {String|Number} top position from the top
* @param {String|Number} left position from the left
* @returns void
*/
move(top, left) {
if (!window.DM && (this.options.restrictPlayerMove || this.options.locked) && !this.isCurrentPlayer()) return; // don't allow rotating if the token is locked
if (window.DM && this.options.locked && !$('#select_locked .ddbc-tab-options__header-heading').hasClass('ddbc-tab-options__header-heading--is-active')) return; // don't allow rotating if the token is locked
// Save handle params
top = parseFloat(top);
left = parseFloat(left);
this.prepareWalkableArea()
let tinyToken = (Math.round(this.options.gridSquares*2)/2 < 1) || this.isAoe();
let tokenPosition = snap_point_to_grid(left, top, true, tinyToken)
// Stop movement if new position is outside of the scene
if (
top < this.walkableArea.top - this.options.size ||
top > this.walkableArea.bottom + this.options.size ||
left < this.walkableArea.left - this.options.size ||
left > this.walkableArea.right + this.options.size
) { return; }
let halfWidth = parseFloat(this.options.size)/2;
let inLos = this.isAoe() ? true : detectInLos(tokenPosition.x + halfWidth, tokenPosition.y + halfWidth) ;
if(window.CURRENT_SCENE_DATA.disableSceneVision == 1 || !this.options.auraislight || inLos){
this.options.top = tokenPosition.y + 'px';
this.options.left = tokenPosition.x + 'px';
this.place(100)
this.update_and_sync();
}
}
snap_to_closest_square() {
if ((!window.DM && this.options.restrictPlayerMove && !this.isCurrentPlayer()) || this.options.locked) return; // don't allow moving if the token is locked
if (window.DM && this.options.locked) return; // don't allow moving if the token is locked
// shamelessly copied from the draggable code later in this file
// this should be a XOR... (A AND !B) OR (!A AND B)
let shallwesnap = (window.CURRENT_SCENE_DATA.snap == "1" && !(window.toggleSnap)) || ((window.CURRENT_SCENE_DATA.snap != "1") && window.toggleSnap);
if (shallwesnap) {
// calculate offset in real coordinates
const startX = window.CURRENT_SCENE_DATA.offsetx;
const startY = window.CURRENT_SCENE_DATA.offsety;
const selectedOldTop = parseInt(this.options.top);
const selectedOldleft = parseInt(this.options.left);
const selectedNewtop = Math.round(Math.round( (selectedOldTop - startY) / window.CURRENT_SCENE_DATA.vpps)) * window.CURRENT_SCENE_DATA.vpps + startY;
const selectedNewleft = Math.round(Math.round( (selectedOldleft - startX) / window.CURRENT_SCENE_DATA.hpps)) * window.CURRENT_SCENE_DATA.hpps + startX;
console.log("Snapping from "+selectedOldleft+ " "+selectedOldTop + " -> "+selectedNewleft + " "+selectedNewtop);
console.log("params startX " + startX + " startY "+ startY + " vpps "+window.CURRENT_SCENE_DATA.vpps + " hpps "+window.CURRENT_SCENE_DATA.hpps);
this.update_from_page();
this.options.top = `${selectedNewtop}px`;
this.options.left = `${selectedNewleft}px`;
this.place_sync_persist();
}
}
place_sync_persist() {
this.place();
this.sync();
}
highlight(dontscroll=false) {
let self = this;
if (self.doing_highlight)
return;
self.doing_highlight = true;
let selector = "div[data-id='" + this.options.id + "']";
let old = $(`#tokens ${selector}, #token_map_items ${selector}`);
let old_op = old.css('opacity');
if (old.is(":visible") || window.DM) {
let pageX = Math.round(parseInt(this.options.left) * window.ZOOM - ($(window).width() / 2));
let pageY = Math.round(parseInt(this.options.top) * window.ZOOM - ($(window).height() / 2));
console.log(this.options.left + " " + this.options.top + "->" + pageX + " " + pageY);
if(!dontscroll){
if($("#hide_rightpanel").hasClass("point-right")) {
pageX += 190; // 190 = half gamelog + scrollbar
}
$("html,body").animate({
scrollTop: pageY + window.VTTMargin,
scrollLeft: pageX + window.VTTMargin
}, 500);
}
// double blink
old.animate({ opacity: 0 }, 250).animate({ opacity: old_op }, 250).animate({ opacity: 0 }, 250).animate({ opacity: old_op }, 250, function() {
self.doing_highlight = false;
});
}
else {
self.doing_highlight = false;
}
}
notify(text) {
let n = $("<div/>");
n.html(text);
n.css('position', 'absolute');
n.css('top', parseInt(this.options.top)); // anything to do with sizeHeight() here?
n.css('left', parseInt(this.options.left) + (this.sizeWidth() / 2) - 130);
n.css("z-index", "60");
n.css("opacity", 0.9)
$("#tokens").append(n);
n.animate({
opacity: 0.3,
top: parseInt(this.options.top) - 100,
}, 6000, function() {
n.remove();
})
}
/**
* adds a hidden dead cross to tokens
* makes dead cross visible if token has 0 hp
* @param token jquery selected div with the class "token"
*/
update_dead_cross(token){
if(this.maxHp > 0) {
// add a cross if it doesn't exist
if(token.find(".dead").length === 0)
token.prepend(`<div class="dead" hidden></div>`);
// update cross scale
const deadCross = token.find('.dead')
if(token.hasClass('underDarkness')){
deadCross.hide();
const underdarknessToken = $(`[data-notatoken][data-id='${token.attr('data-id')}']`);
const underdarknessDeadCross = underdarknessToken.find('.dead')
underdarknessDeadCross.attr("style", `transform:scale(${this.get_token_scale()});--size: ${parseInt(this.options.size) / window.CURRENT_SCENE_DATA.scale_factor / 10}px;`)
// check token death
if (this.hp > 0) {
underdarknessDeadCross.hide()
} else {
underdarknessDeadCross.show()
}
}
else{
deadCross.attr("style", `transform:scale(${this.get_token_scale()});--size: ${parseInt(this.options.size) / 10}px;`)
// check token death
if (this.hp > 0) {
deadCross.hide()
} else {
deadCross.show()
}
}
}
}
/**
* updates the color of the health aura if enabled
* @param token jquery selected div with the class "token"
*/
update_health_aura(token){
console.group("update_health_aura")
// set token data to the player if this token is a player token, otherwise just use this tokens data
if($(`.token[data-id='${this.options.id}']>.hpvisualbar`).length<1){
let hpvisualbar = $(`<div class='hpvisualbar'></div>`);
$(`.token[data-id='${this.options.id}']`).append(hpvisualbar);
}
if(this.options.healthauratype == undefined){
if(this.options.disableaura){
this.options.healthauratype = "none"
}
if(this.options.enablepercenthpbar){
this.options.healthauratype = "bar"
}
}
else{
if(this.options.healthauratype == "none"){
this.options.disableaura = true;
this.options.enablepercenthpbar = false;
} else if(this.options.healthauratype == "bar"){
this.options.disableaura = true;
this.options.enablepercenthpbar = true;
} else if(this.options.healthauratype == "aura"){
this.options.disableaura = false;
this.options.enablepercenthpbar = false;
} else if(this.options.healthauratype && this.options.healthauratype.startsWith("aura-bloodied-")){
this.options.disableaura = false;
this.options.enablepercenthpbar = false;
}
}
if (this.maxHp > 0) {
token.css('--hp-percentage', `${this.hpPercentage}%`);
}
const tokenHpAuraColor = token_health_aura(this.hpPercentage, this.options.healthauratype);
let tokenWidth = this.sizeWidth();
let tokenHeight = this.sizeHeight();
if(this.options.disableaura || !this.hp || !this.maxHp) {
token.css('--token-hp-aura-color', 'transparent');
token.css('--token-temp-hp', "transparent");
}
else {
if(this.options.tokenStyleSelect === "circle" || this.options.tokenStyleSelect === "square"){
tokenWidth = (this.options.underDarkness == true) ? tokenWidth - (6/window.CURRENT_SCENE_DATA.scale_factor) : tokenWidth - 6;
tokenHeight = (this.options.underDarkness == true) ? tokenHeight - (6/window.CURRENT_SCENE_DATA.scale_factor) : tokenHeight - 6;
}
token.css('--token-hp-aura-color', tokenHpAuraColor);
if(this.tempHp) {
token.css('--token-temp-hp', "#4444ffbd");
}
else {
token.css('--token-temp-hp', "transparent");
}
}
if(this.options.disableborder) {
token.css('--token-border-color', 'transparent');
}
else {
if(this.options.tokenStyleSelect === "circle" || this.options.tokenStyleSelect === "square"){
tokenWidth = (this.options.underDarkness == true) ? tokenWidth - (1/window.CURRENT_SCENE_DATA.scale_factor) : tokenWidth - 1;
tokenHeight = (this.options.underDarkness == true) ? tokenHeight - (1/window.CURRENT_SCENE_DATA.scale_factor) : tokenHeight - 1;
}
token.css('--token-border-color', this.options.color);
$("#combat_area tr[data-target='" + this.options.id + "'] img[class*='Avatar']").css("border-color", this.options.color);
}
if(!this.options.enablepercenthpbar){
token.css('--token-hpbar-display', 'none');
}
else {
if(this.options.tokenStyleSelect === "circle" || this.options.tokenStyleSelect === "square"){
tokenWidth = (this.options.underDarkness == true) ? Math.round(tokenWidth - (6/window.CURRENT_SCENE_DATA.scale_factor)) : Math.round(tokenWidth - 6);
tokenHeight = (this.options.underDarkness == true) ? Math.round(tokenHeight - (6/window.CURRENT_SCENE_DATA.scale_factor)) : Math.round(tokenHeight - 6);
}
token.css('--token-hpbar-aura-color', tokenHpAuraColor);
if(this.tempHp) {
token.css('--token-temp-hpbar', "#4444ffbd");
}
else {
token.css('--token-temp-hpbar', "transparent");
}
token.css('--token-hpbar-display', 'block');
}
token.attr("data-border-color", this.options.color);
if(!this.options.legacyaspectratio) {
if($(`div.token[data-id='${this.options.id}'] .token-image`)[0] !== undefined){
let imageWidth = $(`div.token[data-id='${this.options.id}'] .token-image`)[0].naturalWidth;
let imageHeight = $(`div.token[data-id='${this.options.id}'] .token-image`)[0].naturalHeight;
if(imageWidth != 0 && imageHeight != 0){
if( imageWidth == imageHeight ){
token.children('.token-image').css("--min-width", tokenWidth + 'px');
token.children('.token-image').css("--min-height", tokenHeight + 'px');
}
else if(imageWidth > imageHeight) {
token.children('.token-image').css("--min-width", tokenWidth + 'px');
token.children('.token-image').css("min-height", '');
}
else {
token.children('.token-image').css("--min-height", tokenHeight + 'px');
token.children('.token-image').css("--min-width", '');
}
}
}
}
else {
token.children('.token-image').css("--min-width", "");
token.children('.token-image').css("--min-height", "");
}
token.children('.token-image').css({
'--max-width': tokenWidth + 'px',
'--max-height': tokenHeight + 'px',
});
let underdarknessToken = $(`[data-notatoken][data-id='${this.options.id}']`)
underdarknessToken.css({
'--token-hpbar-display': token.css('--token-hpbar-display'),
'--token-temp-hpbar': token.css('--token-temp-hpbar'),
'--token-hpbar-aura-color': token.css('--token-hpbar-aura-color'),
'--token-border-color': token.css('--token-border-color'),
'--token-hp-aura-color': token.css('--token-hp-aura-color'),
'--hp-percentage': token.css('--hp-percentage'),
'--token-temp-hp': token.css('--token-temp-hp'),
})
underdarknessToken.children('.token-image').css({
'--min-width': token.children('.token-image').css("--min-width"),
'--min-height': token.children('.token-image').css("--min-width"),
'--max-width': tokenWidth + 'px',
'--max-height': tokenHeight + 'px',
})
console.groupEnd()
}
update_condition_timers(){
console.group("update_condition_timers")
function setDurationBadgeText(token, condition){
if(condition.duration == undefined)
return;
const conditionName = (typeof condition === "string" ? condition : condition?.name) || "";
const isExhaustion = conditionName.startsWith("Exhaustion");
const conditionSymbolName = isExhaustion ? 'exhaustion' : conditionName.toLowerCase();
const durationBadge = $(`.token[data-id='${token.options.id}'] .duration-badge[class*='${conditionSymbolName}']`);
durationBadge.toggleClass('expired', condition.duration<1)
durationBadge.find('span').text(condition.duration);
}
for(let i in this.options.conditions){
const condition = this.options.conditions[i]
setDurationBadgeText(this, condition);
}
for(let i in this.options.custom_conditions){
const condition = this.options.custom_conditions[i];
setDurationBadgeText(this, condition);
}
console.groupEnd()
}
update_age(){
const age = $(`.token[data-id='${this.options.id}'] div.age`);
if(this.options.maxAge == undefined || this.options.maxAge === false){
age.remove();
return;
}
age.find('svg circle').attr('fill', parseInt(this.options.age) > 0 ? '#FFFFFF' : "#ff0000");
age.find('text').text(this.options.age);
}
/**
* returns different scales of the token based on options such as aura disabled
* @returns scale of token
*/
get_token_scale(){
if (this.maxHp <= 0 || (this.options.disableaura && !this.options.enablepercenthpbar)) {
return 1;
}
return (((this.options.size - 15) * 100) / this.options.size) / 100;
}
update_from_page() {
console.group("update_from_page")
let selector = "div[data-id='" + this.options.id + "']";
let old = $("#tokens").find(selector);
if(old.is(':animated')){
this.stopAnimation(); // stop the animation and jump to the end.
}
this.options.left = old.css("left");
this.options.top = old.css("top");
this.options.scaleCreated = window.CURRENT_SCENE_DATA.scale_factor;
// one of either
// is a monster?
// is the DM
// not the DM and player controlled
// AND stats aren't disabled and has hp bar
if ( ( (!(this.options.monster > 0)) || window.DM || (!window.DM && this.options.player_owned)) && old.has(".hp").length > 0) {
if (old.find(".hp").val().trim().startsWith("+") || old.find(".hp").val().trim().startsWith("-")) {
old.find(".hp").val(Math.max(0, this.hp + parseInt(old.find(".hp").val())));
}
if (old.find(".max_hp").val().trim().startsWith("+") || old.find(".max_hp").val().trim().startsWith("-")) {
old.find(".max_hp").val(Math.max(0, this.maxHp + parseInt(old.find(".max_hp").val())));
}
this.hp = parseInt(old.find(".hp").val()) - this.tempHp;
this.maxHp = parseInt(old.find(".max_hp").val());