Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
1966 lines (1690 loc) · 73.9 KB
/
Copy pathscript.js
File metadata and controls
1966 lines (1690 loc) · 73.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Vision Plus for Foundry VTT */
(() => {
"use strict";
const MODULE_ID = "vision-plus";
const REQUIRED_OWNERSHIP = CONST.DOCUMENT_OWNERSHIP_LEVELS?.OBSERVER ?? 2;
const VISION_MODE_TOKEN_ONLY = "tokenOnly";
const VISION_MODE_FULL = "fullVision";
const OTHER_PLAYERS_DISABLED = "disabled";
const OTHER_PLAYERS_SAME_AS_OWN = "sameAsOwn";
const GM_VISION_SELECTED_ONLY = "selectedOnly";
const GM_VISION_POSITIONS = "selectedAndPositions";
const GM_VISION_PLAYER_SOURCES = "selectedPositionsAndPlayerOwnedVision";
const GM_VISION_ALL_SOURCES = "allTokenVision";
const GM_VISION_MODES = [GM_VISION_SELECTED_ONLY, GM_VISION_POSITIONS, GM_VISION_PLAYER_SOURCES, GM_VISION_ALL_SOURCES];
const SOCKET_CHANNEL = `module.${MODULE_ID}`;
const playerOptInResponses = new Map();
let activePlayerStatusRequestId = null;
class VisionPlusDetectionFilter extends foundry.canvas.rendering.filters.AbstractBaseFilter {
static _createVertexShader() {
return `\
attribute vec2 aVertexPosition;
uniform vec4 inputSize;
uniform vec4 outputFrame;
uniform mat3 projectionMatrix;
uniform vec2 origin;
uniform mediump float thickness;
varying vec2 vTextureCoord;
varying float vOffset;
void main() {
vTextureCoord = (aVertexPosition * outputFrame.zw) * inputSize.zw;
vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.0)) + outputFrame.xy;
vec2 offset = position - origin;
vOffset = (offset.x + offset.y) / (1.414213562373095 * 2.0 * thickness);
gl_Position = vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);
}
`;
}
static _createFragmentShader() {
return `\
varying vec2 vTextureCoord;
varying float vOffset;
uniform sampler2D uSampler;
uniform mediump float thickness;
void main() {
float x = abs(vOffset - floor(vOffset + 0.5)) * 2.0;
float y0 = clamp((x + 0.5) * thickness + 0.5, 0.0, 1.0);
float y1 = clamp((x - 0.5) * thickness + 0.5, 0.0, 1.0);
float y = y0 - y1;
vec4 texel = texture2D(uSampler, vTextureCoord);
float luminance = dot(texel.rgb, vec3(0.299, 0.587, 0.114));
float alpha = texel.a * 0.25;
gl_FragColor = vec4(vec3(luminance) * y, 1.0) * alpha;
}
`;
}
static defaultUniforms = {
origin: { x: 0.0, y: 0.0 },
thickness: 1.0,
};
apply(filterManager, input, output, clearMode, currentState) {
const uniforms = this.uniforms;
const worldTransform = currentState.target.worldTransform;
uniforms.origin.x = worldTransform.tx;
uniforms.origin.y = worldTransform.ty;
uniforms.thickness = 4 * canvas.dimensions.uiScale * canvas.stage.scale.x;
super.apply(filterManager, input, output, clearMode, currentState);
}
}
let detectionFilter;
let patched = false;
let tokenVisibilityPatched = false;
let originalTokenIsVisibleGetter = null;
let levelAccessPatched = false;
let noVisionNotificationPatched = false;
const secondaryDetectedTokenIds = new Set();
let refreshQueued = false;
const tokenPositionCache = new Map();
const refreshTokenPositionCache = new Map();
let viewedLevelCache = null;
const nativeVisionProbeTokenIds = new Set();
let nativeVisionBatchInProgress = false;
let nativeRefreshDirty = true;
let lastNativeRefreshSignature = null;
function setting(key) {
return game.settings.get(MODULE_ID, key);
}
/**
* Resolve the current user's GM status during the init hook. In Foundry v14
* game.user may not yet be assigned when settings are registered, while the
* raw user collection and current user id are already available.
*/
function currentUserIsGM() {
if (typeof game.user?.isGM === "boolean") return game.user.isGM;
const userId = game.userId ?? game.data?.userId ?? game.data?.user?._id;
const collectionUser = userId ? game.users?.get?.(userId) : null;
if (typeof collectionUser?.isGM === "boolean") return collectionUser.isGM;
const rawUsers = game.data?.users ?? game.data?.users?.contents ?? [];
const rawUser = Array.from(rawUsers ?? []).find((user) =>
(user?._id ?? user?.id) === userId
);
if (typeof rawUser?.isGM === "boolean") return rawUser.isGM;
const role = Number(rawUser?.role ?? game.data?.user?.role);
const gmRole = Number(CONST?.USER_ROLES?.GAMEMASTER ?? 4);
return Number.isFinite(role) && role >= gmRole;
}
function isEnabledForThisClient() {
// World setting is the GM-controlled maximum. The user's client setting is
// their personal opt-in. Vision Plus is active only when both are on.
try {
return Boolean(game.settings.get(MODULE_ID, "worldEnabled"))
&& Boolean(game.settings.get(MODULE_ID, "enabled"));
} catch (_) {
return false;
}
}
function gmVisionMode() {
try {
const mode = setting("gmVisionMode");
return GM_VISION_MODES.includes(mode) ? mode : GM_VISION_SELECTED_ONLY;
} catch (_) {
return GM_VISION_SELECTED_ONLY;
}
}
function gmHasSelectedToken() {
return (canvas.tokens?.controlled?.length ?? 0) > 0;
}
function gmShowsOtherTokenPositions() {
// Every GM mode is intentionally passive while no Token is selected.
// In that state Foundry's ordinary GM map view must remain untouched.
return game.user?.isGM && gmHasSelectedToken() && gmVisionMode() !== GM_VISION_SELECTED_ONLY;
}
function actorObservedByAnyPlayer(actor) {
if (!actor) return false;
return game.users?.some?.((user) => !user.isGM && actor.testUserPermission?.(user, "OBSERVER")) ?? false;
}
function gmShouldForceVisionSource(token) {
if (!game.user?.isGM || !gmHasSelectedToken() || !token?.document || token.document.hidden) return false;
if (!hasSight(token) || !isTokenOnViewedLevel(token)) return false;
const mode = gmVisionMode();
if (mode === GM_VISION_ALL_SOURCES) return true;
if (mode === GM_VISION_PLAYER_SOURCES) return actorObservedByAnyPlayer(token.actor);
return false;
}
function ownVisionMode() {
return setting("ownVisionMode") || VISION_MODE_TOKEN_ONLY;
}
function otherPlayersVisionMode() {
return setting("otherPlayersVisionMode") || OTHER_PLAYERS_DISABLED;
}
function isOtherPlayersVisionEnabled() {
return otherPlayersVisionMode() !== OTHER_PLAYERS_DISABLED;
}
function effectiveOtherPlayersVisionMode() {
const mode = otherPlayersVisionMode();
if (mode === OTHER_PLAYERS_DISABLED) return null;
if (mode === OTHER_PLAYERS_SAME_AS_OWN) return ownVisionMode();
return VISION_MODE_TOKEN_ONLY;
}
function modeForSecondaryToken(token) {
if (isOwnedByCurrentUser(token)) return ownVisionMode();
if (isOwnedByAnotherPlayer(token)) return effectiveOtherPlayersVisionMode();
return null;
}
function renderMode() {
return {
own: ownVisionMode(),
otherPlayers: otherPlayersVisionMode(),
effectiveOtherPlayers: effectiveOtherPlayersVisionMode() ?? OTHER_PLAYERS_DISABLED
};
}
function isTokenOnlyMode(token = null) {
return token ? modeForSecondaryToken(token) === VISION_MODE_TOKEN_ONLY : true;
}
function isFullVisionMode(token) {
return modeForSecondaryToken(token) === VISION_MODE_FULL;
}
function isNoCanvas() {
return game.settings.get("core", "noCanvas");
}
function registerSettings() {
// Registration order controls the order in Foundry's standard Module Settings.
// Keep the release settings grouped into GM Vision, Player Vision, and Appearance.
game.settings.register(MODULE_ID, "gmVisionMode", {
name: "VPLUS.settings.gmVisionMode.name",
hint: "VPLUS.settings.gmVisionMode.hint",
scope: "client",
config: currentUserIsGM(),
type: String,
choices: {
[GM_VISION_SELECTED_ONLY]: "VPLUS.gmVisionMode.selectedOnly",
[GM_VISION_POSITIONS]: "VPLUS.gmVisionMode.selectedAndPositions",
[GM_VISION_PLAYER_SOURCES]: "VPLUS.gmVisionMode.selectedPositionsAndPlayerOwnedVision",
[GM_VISION_ALL_SOURCES]: "VPLUS.gmVisionMode.allTokenVision"
},
default: GM_VISION_SELECTED_ONLY,
restricted: true,
onChange: onLocalVisionSettingChange
});
game.settings.register(MODULE_ID, "worldEnabled", {
name: "VPLUS.settings.worldEnabled.name",
hint: "VPLUS.settings.worldEnabled.hint",
scope: "world",
config: true,
type: Boolean,
default: true,
restricted: true,
onChange: onWorldVisionSettingChange
});
game.settings.register(MODULE_ID, "ownVisionMode", {
name: "VPLUS.settings.ownVisionMode.name",
hint: "VPLUS.settings.ownVisionMode.hint",
scope: "world",
config: true,
type: String,
choices: {
[VISION_MODE_TOKEN_ONLY]: "VPLUS.visionMode.tokenOnly",
[VISION_MODE_FULL]: "VPLUS.visionMode.fullVision"
},
default: VISION_MODE_TOKEN_ONLY,
restricted: true,
onChange: onWorldVisionSettingChange
});
game.settings.register(MODULE_ID, "otherPlayersVisionMode", {
name: "VPLUS.settings.otherPlayersVisionMode.name",
hint: "VPLUS.settings.otherPlayersVisionMode.hint",
scope: "world",
config: true,
type: String,
choices: {
[OTHER_PLAYERS_DISABLED]: "VPLUS.otherPlayersVisionMode.disabled",
[OTHER_PLAYERS_SAME_AS_OWN]: "VPLUS.otherPlayersVisionMode.sameAsOwn",
[VISION_MODE_TOKEN_ONLY]: "VPLUS.otherPlayersVisionMode.tokenOnly"
},
default: OTHER_PLAYERS_DISABLED,
restricted: true,
onChange: onWorldVisionSettingChange
});
game.settings.register(MODULE_ID, "enabled", {
name: "VPLUS.settings.enabled.name",
hint: "VPLUS.settings.enabled.hint",
scope: "client",
config: !currentUserIsGM(),
type: Boolean,
default: true,
restricted: false,
onChange: onLocalVisionSettingChange
});
}
function findSettingRow(root, key) {
const full = `${MODULE_ID}.${key}`;
const selectors = [
`[data-setting-id="${full}"]`,
`[data-key="${full}"]`,
`[data-setting="${full}"]`,
`[name="${full}"]`
];
for (const selector of selectors) {
const found = root.querySelector?.(selector);
if (!found) continue;
return found.closest?.(".form-group, .setting, li") ?? found;
}
return null;
}
function localizedVisionModeLabel(mode) {
if (mode === VISION_MODE_FULL) return game.i18n.localize("VPLUS.visionMode.fullVision");
if (mode === VISION_MODE_TOKEN_ONLY) return game.i18n.localize("VPLUS.visionMode.tokenOnly");
return game.i18n.localize("VPLUS.otherPlayersVisionMode.disabled");
}
function currentEffectivePlayerStatus() {
let worldEnabled = false;
let optedIn = false;
let own = OTHER_PLAYERS_DISABLED;
let otherPlayers = OTHER_PLAYERS_DISABLED;
try {
worldEnabled = Boolean(setting("worldEnabled"));
optedIn = Boolean(setting("enabled"));
if (worldEnabled && optedIn) {
own = ownVisionMode();
otherPlayers = effectiveOtherPlayersVisionMode() ?? OTHER_PLAYERS_DISABLED;
}
} catch (_) {}
return { worldEnabled, optedIn, own, otherPlayers };
}
function currentConfiguredPlayerVisionStatus() {
let worldEnabled = false;
let own = OTHER_PLAYERS_DISABLED;
let otherPlayers = OTHER_PLAYERS_DISABLED;
try {
worldEnabled = Boolean(setting("worldEnabled"));
if (worldEnabled) {
own = ownVisionMode();
otherPlayers = effectiveOtherPlayersVisionMode() ?? OTHER_PLAYERS_DISABLED;
}
} catch (_) {}
return { worldEnabled, own, otherPlayers };
}
function createPlayerVisionInfoPanel() {
// This panel reports the world configuration chosen by the GM. It is
// intentionally independent of the current player's personal opt-in.
const status = currentConfiguredPlayerVisionStatus();
const panel = document.createElement("div");
panel.className = "vision-plus-player-info";
panel.dataset.visionPlusPlayerInfo = "true";
const title = document.createElement("strong");
title.textContent = game.i18n.localize("VPLUS.playerInfo.title");
panel.appendChild(title);
const rows = [
["VPLUS.playerInfo.ownTokens", localizedVisionModeLabel(status.own)],
["VPLUS.playerInfo.otherPlayers", localizedVisionModeLabel(status.otherPlayers)]
];
for (const [labelKey, value] of rows) {
const row = document.createElement("div");
row.className = "vision-plus-player-info-row";
const label = document.createElement("span");
label.textContent = game.i18n.localize(labelKey);
const strong = document.createElement("strong");
strong.textContent = value;
row.append(label, strong);
panel.appendChild(row);
}
if (!status.worldEnabled) {
const note = document.createElement("p");
note.className = "hint";
note.textContent = game.i18n.localize("VPLUS.playerInfo.worldDisabled");
panel.appendChild(note);
}
return panel;
}
function playerStatusRequestId() {
return globalThis.crypto?.randomUUID?.()
?? foundry?.utils?.randomID?.()
?? `${Date.now()}-${Math.random().toString(36).slice(2)}`;
}
function emitPlayerStatusRequest() {
if (!game.user?.isGM) return null;
const requestId = playerStatusRequestId();
activePlayerStatusRequestId = requestId;
playerOptInResponses.clear();
game.socket?.emit?.(SOCKET_CHANNEL, {
type: "player-status-request",
requestId,
requesterId: game.user.id
});
return requestId;
}
function playerStatusRowsHtml() {
const onlinePlayers = Array.from(game.users ?? [])
.filter((user) => !user.isGM && user.active)
.sort((a, b) => String(a.name).localeCompare(String(b.name)));
if (!onlinePlayers.length) {
return `<p class="hint">${game.i18n.localize("VPLUS.playerStatus.noneOnline")}</p>`;
}
const escape = foundry?.utils?.escapeHTML ?? ((value) => String(value)
.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">")
.replaceAll('"', """).replaceAll("'", "'"));
return `<table class="vision-plus-player-status-table">
<thead><tr>
<th>${game.i18n.localize("VPLUS.playerStatus.player")}</th>
<th>${game.i18n.localize("VPLUS.playerStatus.optIn")}</th>
<th>${game.i18n.localize("VPLUS.playerInfo.ownTokens")}</th>
<th>${game.i18n.localize("VPLUS.playerInfo.otherPlayers")}</th>
</tr></thead>
<tbody>${onlinePlayers.map((user) => {
const response = playerOptInResponses.get(user.id);
const waiting = game.i18n.localize("VPLUS.playerStatus.waiting");
const optedIn = response
? game.i18n.localize(response.optedIn ? "VPLUS.playerStatus.yes" : "VPLUS.playerStatus.no")
: waiting;
const own = response ? localizedVisionModeLabel(response.own) : waiting;
const otherPlayers = response ? localizedVisionModeLabel(response.otherPlayers) : waiting;
return `<tr>
<td>${escape(user.name)}</td>
<td>${escape(optedIn)}</td>
<td>${escape(own)}</td>
<td>${escape(otherPlayers)}</td>
</tr>`;
}).join("")}</tbody>
</table>`;
}
function refreshOpenPlayerStatusPanel() {
const container = document.querySelector("[data-vision-plus-player-status-content]");
if (container && !container.hidden) container.innerHTML = playerStatusRowsHtml();
}
function createPlayerStatusButton() {
const wrapper = document.createElement("div");
wrapper.className = "vision-plus-player-status-action";
wrapper.dataset.visionPlusPlayerStatusAction = "true";
const button = document.createElement("button");
button.type = "button";
button.innerHTML = `<i class="fa-solid fa-users-viewfinder"></i> ${game.i18n.localize("VPLUS.playerStatus.button")}`;
wrapper.appendChild(button);
const hint = document.createElement("p");
hint.className = "hint";
hint.textContent = game.i18n.localize("VPLUS.playerStatus.hint");
wrapper.appendChild(hint);
const panel = document.createElement("div");
panel.className = "vision-plus-player-status-panel";
panel.dataset.visionPlusPlayerStatusContent = "true";
panel.hidden = true;
wrapper.appendChild(panel);
button.addEventListener("click", () => {
panel.hidden = !panel.hidden;
if (panel.hidden) return;
panel.innerHTML = playerStatusRowsHtml();
emitPlayerStatusRequest();
});
return wrapper;
}
function configureMainSettingsLayout(app, html) {
const root = unwrapSettingsRoot(app, html);
if (!root) return false;
const gmRow = findSettingRow(root, "gmVisionMode");
const playerOptInRow = findSettingRow(root, "enabled");
if (!game.user?.isGM) {
if (gmRow) gmRow.remove();
// Player-side: keep the normal Foundry setting row unboxed and add only
// a compact read-only summary of the effective GM/world configuration.
if (!root.querySelector("[data-vision-plus-player-info]") && playerOptInRow) {
playerOptInRow.after(createPlayerVisionInfoPanel());
}
return Boolean(playerOptInRow);
}
if (playerOptInRow) playerOptInRow.remove();
// GM-side: preserve the two clear sections which already worked well.
if (!root.querySelector('[data-vision-plus-settings-group="gm"]') && gmRow) {
const fieldset = document.createElement("fieldset");
fieldset.className = "vision-plus-settings-group";
fieldset.dataset.visionPlusSettingsGroup = "gm";
const legend = document.createElement("legend");
legend.textContent = game.i18n.localize("VPLUS.settings.section.gmVision");
fieldset.appendChild(legend);
gmRow.before(fieldset);
fieldset.appendChild(gmRow);
}
const worldEnabledRow = findSettingRow(root, "worldEnabled");
const ownVisionRow = findSettingRow(root, "ownVisionMode");
const otherPlayersRow = findSettingRow(root, "otherPlayersVisionMode");
if (!root.querySelector('[data-vision-plus-settings-group="player"]') && worldEnabledRow) {
const fieldset = document.createElement("fieldset");
fieldset.className = "vision-plus-settings-group";
fieldset.dataset.visionPlusSettingsGroup = "player";
const legend = document.createElement("legend");
legend.textContent = game.i18n.localize("VPLUS.settings.section.playerVision");
fieldset.appendChild(legend);
worldEnabledRow.before(fieldset);
for (const row of [worldEnabledRow, ownVisionRow, otherPlayersRow].filter(Boolean)) {
fieldset.appendChild(row);
}
fieldset.appendChild(createPlayerStatusButton());
}
return true;
}
function unwrapSettingsRoot(app, html) {
const candidates = [html, html?.[0], app?.element, app?.element?.[0]];
for (const candidate of candidates) {
if (candidate?.querySelector) return candidate;
}
return null;
}
function groupMainSettings(app, html) {
const attempt = () => {
const root = unwrapSettingsRoot(app, html);
if (!root) return false;
// The generic ApplicationV2 hook also fires for unrelated applications.
// Only touch a window which actually contains a Vision Plus setting.
if (!findSettingRow(root, "worldEnabled") && !findSettingRow(root, "gmVisionMode")
&& !findSettingRow(root, "enabled")) return false;
return configureMainSettingsLayout(app, root);
};
if (attempt()) return;
const raf = globalThis.requestAnimationFrame ?? ((fn) => setTimeout(fn, 0));
raf(attempt);
setTimeout(attempt, 100);
setTimeout(attempt, 300);
}
function markNativeRefreshDirty() {
nativeRefreshDirty = true;
}
function scheduleSecondaryVisionRefresh() {
if (!nativeRefreshDirty || refreshQueued) return;
refreshQueued = true;
const raf = globalThis.requestAnimationFrame ?? ((fn) => window.setTimeout(fn, 16));
raf(() => {
refreshQueued = false;
if (nativeRefreshDirty) refreshSecondaryVision();
});
}
function tokenPositionSignature(token) {
if (!token) return "";
const doc = token.document ?? {};
const center = token.center ?? {};
return [
token.id,
Math.round(Number(doc.x ?? token.x ?? center.x ?? 0) * 100) / 100,
Math.round(Number(doc.y ?? token.y ?? center.y ?? 0) * 100) / 100,
Math.round(Number(token.x ?? doc.x ?? center.x ?? 0) * 100) / 100,
Math.round(Number(token.y ?? doc.y ?? center.y ?? 0) * 100) / 100,
Math.round(Number(center.x ?? 0) * 100) / 100,
Math.round(Number(center.y ?? 0) * 100) / 100,
getTokenLevelId(token) ?? "no-level"
].join("|");
}
function watchTokenMovementFrame() {
if (!canvas?.ready || game.user?.isGM || isNoCanvas()) return;
let changed = false;
const viewedLevelId = getViewedLevelId();
if (viewedLevelCache !== viewedLevelId) {
viewedLevelCache = viewedLevelId;
changed = true;
}
for (const token of canvas.tokens?.placeables ?? []) {
const signature = tokenPositionSignature(token);
if (tokenPositionCache.get(token.id) !== signature) {
tokenPositionCache.set(token.id, signature);
changed = true;
}
}
for (const id of Array.from(tokenPositionCache.keys())) {
if (!(canvas.tokens?.placeables ?? []).some((t) => t.id === id)) {
tokenPositionCache.delete(id);
refreshTokenPositionCache.delete(id);
changed = true;
}
}
if (changed && isTokenOnlyMode()) {
markNativeRefreshDirty();
scheduleSecondaryVisionRefresh();
}
}
function refreshCanvasVision() {
markNativeRefreshDirty();
if (!canvas?.ready || isNoCanvas()) return;
canvas.perception?.update?.({ refreshVision: true, refreshLighting: true, refreshSounds: false }, true);
window.setTimeout(scheduleSecondaryVisionRefresh, 0);
}
function reinitializeVisionPlusTokenSources() {
for (const token of canvas.tokens?.placeables ?? []) {
try {
if (typeof token.initializeVisionSource === "function") token.initializeVisionSource();
else if (typeof token._initializeVisionSource === "function") token._initializeVisionSource();
} catch (_) {}
}
}
function forceVisionSettingRefresh() {
markNativeRefreshDirty();
if (!canvas?.ready || isNoCanvas()) return;
// Re-evaluate each token's VisionSource eligibility immediately. This is the
// native step which otherwise happens when token control changes.
reinitializeVisionPlusTokenSources();
canvas.perception?.update?.({
initializeVision: true,
refreshVision: true,
refreshLighting: true,
refreshSounds: false
}, true);
canvas.tokens?.placeables?.forEach?.((token) => {
token.renderFlags?.set?.({ refreshVisibility: true });
});
window.setTimeout(() => {
reinitializeVisionPlusTokenSources();
markNativeRefreshDirty();
scheduleSecondaryVisionRefresh();
canvas.perception?.update?.({
refreshVision: true,
refreshLighting: true,
refreshSounds: false
}, true);
canvas.tokens?.placeables?.forEach?.((token) => {
token.renderFlags?.set?.({ refreshVisibility: true });
});
}, 0);
}
function broadcastVisionSettingRefresh() {
if (!game.user?.isGM) return;
game.socket?.emit?.(SOCKET_CHANNEL, {
type: "vision-settings-refresh",
senderId: game.user.id
});
}
function onLocalVisionSettingChange() {
forceVisionSettingRefresh();
}
function onWorldVisionSettingChange() {
forceVisionSettingRefresh();
broadcastVisionSettingRefresh();
}
function getOwnershipLevel(actor, userId) {
const ownership = actor?.ownership ?? actor?.data?.ownership ?? {};
return ownership[userId] ?? ownership.default ?? 0;
}
function hasObserverPermission(actor, user) {
if (!actor || !user) return false;
try {
return Boolean(actor.testUserPermission?.(user, "OBSERVER"));
} catch (_) {
return getOwnershipLevel(actor, user.id) >= REQUIRED_OWNERSHIP;
}
}
function isOwnedByCurrentUser(token) {
return Boolean(token?.isOwner || hasObserverPermission(token?.actor, game.user));
}
function isOwnedByAnyPlayer(token) {
const actor = token?.actor;
if (!actor) return false;
for (const user of game.users ?? []) {
if (user.isGM) continue;
if (hasObserverPermission(actor, user)) return true;
}
return false;
}
function isOwnedByAnotherPlayer(token) {
const actor = token?.actor;
if (!actor) return false;
for (const user of game.users ?? []) {
if (user.isGM || user.id === game.user.id) continue;
if (hasObserverPermission(actor, user)) return true;
}
return false;
}
function hasSight(token) {
return Boolean(token?.document?.sight?.enabled || token?.hasSight);
}
function normalizeLevelId(level) {
if (level == null || level === "") return null;
if (typeof level === "string") return level;
return level.id ?? level._id ?? null;
}
function getViewedLevelId() {
const scene = canvas?.scene;
return normalizeLevelId(
scene?._view
?? scene?.viewedLevel
?? canvas?.sceneManager?.level
?? canvas?.sceneManager?.viewedLevel
);
}
function getTokenLevelId(token) {
const document = token?.document ?? token;
return normalizeLevelId(document?.level ?? document?._source?.level);
}
function isTokenOnViewedLevel(token) {
const viewedLevelId = getViewedLevelId();
const tokenLevelId = getTokenLevelId(token);
// Scenes without configured Levels do not need any additional filtering.
// In a multi-level Scene, Foundry assigns level IDs to level-bound Tokens and
// stores the locally viewed Level on Scene#_view. Only matching Tokens may
// participate in secondary vision or receive its detection filter.
if (!viewedLevelId || !tokenLevelId) return true;
return viewedLevelId === tokenLevelId;
}
function isSecondaryTokenEligible(token) {
if (!canvas?.ready || game.user.isGM || isNoCanvas()) return false;
if (!isEnabledForThisClient()) return false;
if (!canvas.visibility?.tokenVision) return false;
if (!token?.document || token.destroyed || token.document.hidden) return false;
if (!hasSight(token)) return false;
if (token.controlled) return false;
const hasControlledToken = (canvas.tokens?.controlled?.length ?? 0) > 0;
// Own additional tokens are only secondary while another owned token is focused.
if (isOwnedByCurrentUser(token)) return hasControlledToken;
// Tokens owned by another player are eligible while party sharing is enabled.
if (isOtherPlayersVisionEnabled() && isOwnedByAnotherPlayer(token)) return true;
return false;
}
function isSecondaryTokenForCurrentView(token) {
// Eligibility grants access to an allied token's Level. Its actual vision and
// detected tokens only participate after the player switches to that Level.
return isSecondaryTokenEligible(token) && isTokenOnViewedLevel(token);
}
function isSecondaryTokenForLevelAccess(token) {
if (!isSecondaryTokenEligible(token)) return false;
if (!isOtherPlayersVisionEnabled() || !isOwnedByAnotherPlayer(token)) return false;
const viewedLevelId = getViewedLevelId();
const tokenLevelId = getTokenLevelId(token);
if (!tokenLevelId) return false;
// Register only off-Level allied tokens as native sources. Foundry can then expose
// their Level just as it does for an observed Token, without rendering their vision
// on the Level currently being viewed. Once that Level is selected, token-only mode
// takes over and this native-source exception switches off again.
return Boolean(viewedLevelId && tokenLevelId !== viewedLevelId);
}
function shouldForceSecondaryVisionSource(token) {
// Token-only mode must never create a real Foundry vision source for an allied
// token. Doing so reveals that token's full native vision. Level availability is
// extended separately through Scene.availableLevels / SceneManager.
return isSecondaryTokenForCurrentView(token) && isFullVisionMode(token);
}
function getLevelDocument(scene, token) {
const direct = token?.level ?? token?.document?.level;
if (direct && typeof direct === "object" && (direct.id ?? direct._id)) return direct;
const levelId = getTokenLevelId(token);
if (!scene || !levelId) return null;
return scene.levels?.get?.(levelId)
?? Array.from(scene.levels ?? []).find((level) => normalizeLevelId(level) === levelId)
?? null;
}
function addAlliedAvailableLevels(levels, scene = canvas?.scene) {
const available = levels instanceof Set ? new Set(levels) : new Set(levels ?? []);
if (!scene || game.user?.isGM || !isEnabledForThisClient() || !isOtherPlayersVisionEnabled()) return available;
for (const token of scene.tokens ?? []) {
if (token?.hidden) continue;
if (!isOwnedByAnotherPlayer(token)) continue;
const level = getLevelDocument(scene, token);
if (level) available.add(level);
}
return available;
}
function patchLevelAvailability() {
if (levelAccessPatched) return;
let patchedAny = false;
// Preferred V14 integration point. SceneManager may override Scene.availableLevels.
const manager = canvas?.sceneManager;
const managerPrototype = manager && Object.getPrototypeOf(manager);
if (managerPrototype && typeof managerPrototype._getAvailableLevels === "function"
&& !managerPrototype._visionPlusAvailableLevelsPatched) {
const original = managerPrototype._getAvailableLevels;
managerPrototype._getAvailableLevels = function visionPlusGetAvailableLevels(...args) {
const result = original.apply(this, args);
if (result && typeof result.then === "function") {
return result.then((levels) => addAlliedAvailableLevels(levels, this.scene ?? canvas?.scene));
}
return addAlliedAvailableLevels(result, this.scene ?? canvas?.scene);
};
Object.defineProperty(managerPrototype, "_visionPlusAvailableLevelsPatched", { value: true });
patchedAny = true;
}
// Fallback for SceneManagers which use the core Scene getter directly.
const SceneClass = CONFIG?.Scene?.documentClass ?? foundry?.documents?.Scene;
const scenePrototype = SceneClass?.prototype;
const descriptor = scenePrototype && Object.getOwnPropertyDescriptor(scenePrototype, "availableLevels");
if (descriptor?.get && !scenePrototype._visionPlusAvailableLevelsPatched) {
const originalGetter = descriptor.get;
Object.defineProperty(scenePrototype, "availableLevels", {
configurable: descriptor.configurable,
enumerable: descriptor.enumerable,
get: function visionPlusAvailableLevels() {
return addAlliedAvailableLevels(originalGetter.call(this), this);
}
});
Object.defineProperty(scenePrototype, "_visionPlusAvailableLevelsPatched", { value: true });
patchedAny = true;
}
levelAccessPatched = patchedAny;
if (!patchedAny) console.warn(`${MODULE_ID} | Could not patch native Level availability.`);
}
function hasSecondaryVisionForCurrentView() {
if (game.user?.isGM || !canvas?.ready || !isEnabledForThisClient()) return false;
if (secondaryDetectedTokenIds.size > 0) return true;
return (canvas.tokens?.placeables ?? []).some((token) => isSecondaryTokenForCurrentView(token));
}
/**
* The core no-vision warning is emitted while Canvas#draw is still initializing,
* before canvas.ready becomes true. At that moment the normal secondary-vision
* predicate intentionally returns false. Use a narrow initialization-safe check
* which only asks whether an eligible allied Token exists on the viewed Level.
*/
function hasSecondaryVisionForNotification() {
if (game.user?.isGM || !isEnabledForThisClient()) return false;
if (secondaryDetectedTokenIds.size > 0) return true;
const tokens = canvas?.tokens?.placeables ?? [];
const hasControlledToken = (canvas?.tokens?.controlled?.length ?? 0) > 0;
return tokens.some((token) => {
if (!token?.document || token.destroyed || token.document.hidden) return false;
if (!hasSight(token) || token.controlled || !isTokenOnViewedLevel(token)) return false;
if (isOwnedByCurrentUser(token)) return hasControlledToken;
return isOtherPlayersVisionEnabled() && isOwnedByAnotherPlayer(token);
});
}
/**
* Vision Plus deliberately does not add a real PointVisionSource: doing so
* would make Foundry render the allied Token's full map vision. Instead, expose a
* non-rendering capability flag which represents the module's token-only virtual
* vision. This is the source of truth used when Foundry emits its no-vision notice.
*/
function installVirtualVisionAvailability() {
if (!canvas?.visibility || canvas.visibility.visionPlusVirtualVisionInstalled) return;
Object.defineProperties(canvas.visibility, {
visionPlusVirtualVisionInstalled: {
configurable: true,
value: true
},
visionPlusHasVirtualVisionSource: {
configurable: true,
get: hasSecondaryVisionForCurrentView
}
});
globalThis.VisionPlus = globalThis.VisionPlus ?? {};
Object.defineProperty(globalThis.VisionPlus, "hasVirtualVisionSource", {
configurable: true,
get: hasSecondaryVisionForCurrentView
});
}
function normalizeNotificationText(value) {
return String(value ?? "")
.replace(/<[^>]*>/g, " ")
.replace(/\s+/g, " ")
.trim()
.toLowerCase();
}
function isNoVisionNotification(message) {
const raw = normalizeNotificationText(message);
let localized = raw;
// Foundry often passes a localization key to ui.notifications.warn and only
// resolves it inside the Notifications implementation. Resolve it before
// comparing so the wrapper can recognize the actual displayed message.
try {
localized = normalizeNotificationText(game?.i18n?.localize?.(String(message ?? "")) ?? message);
} catch (_error) {
localized = raw;
}
const matches = (text) => text.includes("there is no token in this scene which gives you visibility of the area")
|| text.includes("you have no token granting you vision for this scene")
|| (text.includes("kein token") && text.includes("sicht") && text.includes("szene"));
return matches(raw) || matches(localized);
}
function patchNoVisionNotification() {
if (noVisionNotificationPatched || !ui?.notifications) return;
for (const method of ["warn", "info"]) {
const original = ui.notifications[method];
if (typeof original !== "function") continue;
ui.notifications[method] = function visionPlusNotification(message, ...args) {
const virtualSource = Boolean(canvas?.visibility?.visionPlusHasVirtualVisionSource)
|| hasSecondaryVisionForCurrentView()
|| hasSecondaryVisionForNotification();
if (isNoVisionNotification(message) && virtualSource) {
return null;
}
return original.call(this, message, ...args);
};
}
noVisionNotificationPatched = true;
}
function getDetectionFilter() {
if (!detectionFilter) detectionFilter = VisionPlusDetectionFilter.create();
return detectionFilter;
}
function isVisionPlusDetectionFilter(filter) {
return filter === detectionFilter;
}
function tokenNeedsSecondaryDetectionFilter(token) {
if (!canvas?.ready || game.user.isGM || isNoCanvas()) return false;
if (!isEnabledForThisClient()) return false;
if (!canvas.visibility?.tokenVision) return false;
if (!token?.document || token.destroyed || token.document.hidden) return false;
if (!isTokenOnViewedLevel(token)) return false;
if (token.controlled) return false;
// In token-only mode, use the explicit target cache built during sight refresh.
// This avoids repeatedly creating secondary vision sources from inside Token#isVisible,
// which can cause Foundry to draw dark secondary vision circles.
if (isTokenOnlyMode()) return secondaryDetectedTokenIds.has(token.id);
const secondaryEntries = getSecondaryVisionEntries();
if (!secondaryEntries.length) return false;
const primaryShapes = getControlledVisionShapes();
return isTokenOnlyInSecondaryVision(token, secondaryEntries, primaryShapes);
}
function patchTokenVisibilityFilter() {
if (tokenVisibilityPatched) return;
const TokenClass = foundry?.canvas?.placeables?.Token ?? CONFIG?.Token?.objectClass;
const descriptor = TokenClass && Object.getOwnPropertyDescriptor(TokenClass.prototype, "isVisible");
if (!TokenClass || typeof descriptor?.get !== "function") {