forked from foundryvtt/pf2e
-
Notifications
You must be signed in to change notification settings - Fork 0
/
base.ts
1831 lines (1599 loc) · 75.7 KB
/
base.ts
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
import {
ActorAlliance,
ActorDimensions,
ActorInstances,
ApplyDamageParams,
AuraData,
EmbeddedItemInstances,
SaveType,
UnaffectedType,
} from "@actor/types.ts";
import type { AbstractEffectPF2e, ArmorPF2e, ConditionPF2e, ContainerPF2e, PhysicalItemPF2e, ShieldPF2e } from "@item";
import { ItemPF2e, ItemProxyPF2e } from "@item";
import type { EffectTrait } from "@item/abstract-effect/types.ts";
import type { AfflictionSource } from "@item/affliction/index.ts";
import type { ItemSourcePF2e, ItemType, PhysicalItemSource } from "@item/base/data/index.ts";
import type { ConditionKey, ConditionSlug, ConditionSource } from "@item/condition/index.ts";
import { PersistentDialog } from "@item/condition/persistent-damage-dialog.ts";
import { CONDITION_SLUGS } from "@item/condition/values.ts";
import { isContainerCycle } from "@item/container/helpers.ts";
import type { EffectFlags, EffectSource } from "@item/effect/data.ts";
import { createDisintegrateEffect } from "@item/effect/helpers.ts";
import { itemIsOfType } from "@item/helpers.ts";
import { MAGIC_TRADITIONS } from "@item/spell/values.ts";
import type { ActiveEffectPF2e } from "@module/active-effect.ts";
import type { TokenPF2e } from "@module/canvas/index.ts";
import { ChatMessagePF2e } from "@module/chat-message/document.ts";
import type { AppliedDamageFlag } from "@module/chat-message/index.ts";
import type { Size } from "@module/data.ts";
import { preImportJSON } from "@module/doc-helpers.ts";
import { CombatantPF2e, EncounterPF2e } from "@module/encounter/index.ts";
import { RollNotePF2e } from "@module/notes.ts";
import {
extractDamageDice,
extractModifiers,
extractNotes,
processPreUpdateActorHooks,
} from "@module/rules/helpers.ts";
import type { RuleElementSynthetics } from "@module/rules/index.ts";
import type { RuleElementPF2e } from "@module/rules/rule-element/base.ts";
import type { RollOptionRuleElement } from "@module/rules/rule-element/roll-option/rule-element.ts";
import type { UserPF2e } from "@module/user/document.ts";
import type { ScenePF2e } from "@scene/document.ts";
import { TokenDocumentPF2e } from "@scene/token-document/document.ts";
import { IWRApplicationData, applyIWR } from "@system/damage/iwr.ts";
import type { DamageType } from "@system/damage/types.ts";
import type {
ArmorStatistic,
PerceptionStatistic,
Statistic,
StatisticDifficultyClass,
} from "@system/statistic/index.ts";
import { EnrichmentOptionsPF2e, TextEditorPF2e } from "@system/text-editor.ts";
import { ErrorPF2e, localizer, objectHasKey, setHasElement, signedInteger, sluggify, tupleHasValue } from "@util";
import * as R from "remeda";
import { v5 as UUIDv5 } from "uuid";
import { ActorConditions } from "./conditions.ts";
import { Abilities, VisionLevel, VisionLevels } from "./creature/data.ts";
import { GetReachParameters, ModeOfBeing } from "./creature/types.ts";
import { ActorFlagsPF2e, ActorSystemData, ActorTraitsData, PrototypeTokenPF2e, RollOptionFlags } from "./data/base.ts";
import type { ActorSourcePF2e } from "./data/index.ts";
import { Immunity, Resistance, Weakness } from "./data/iwr.ts";
import { ActorSizePF2e } from "./data/size.ts";
import {
auraAffectsActor,
checkAreaEffects,
createEncounterRollOptions,
isReallyPC,
migrateActorSource,
} from "./helpers.ts";
import type { ActorInitiative } from "./initiative.ts";
import { ActorInventory } from "./inventory/index.ts";
import { ItemTransfer } from "./item-transfer.ts";
import { applyStackingRules } from "./modifiers.ts";
import type { ActorSheetPF2e } from "./sheet/base.ts";
import type { ActorSpellcasting } from "./spellcasting.ts";
import { TokenEffect } from "./token-effect.ts";
import type { ActorType } from "./types.ts";
import { CREATURE_ACTOR_TYPES, SAVE_TYPES, SIZE_LINKABLE_ACTOR_TYPES, UNAFFECTED_TYPES } from "./values.ts";
/**
* Extend the base Actor class to implement additional logic specialized for PF2e.
* @category Actor
*/
class ActorPF2e<TParent extends TokenDocumentPF2e | null = TokenDocumentPF2e | null> extends Actor<TParent> {
/** Has this document completed `DataModel` initialization? */
declare initialized: boolean;
/** A UUIDv5 hash digest of the foundry UUID */
declare signature: string;
/** Handles rolling initiative for the current actor */
declare initiative: ActorInitiative | null;
/** A separate collection of owned physical items for convenient access */
declare inventory: ActorInventory<this>;
declare armorClass: StatisticDifficultyClass<ArmorStatistic> | null;
/** A separate collection of owned spellcasting entries for convenience */
declare spellcasting: ActorSpellcasting<this> | null;
/** Rule elements drawn from owned items */
declare rules: RuleElementPF2e[];
declare synthetics: RuleElementSynthetics;
/** Saving throw statistics */
declare saves?: { [K in SaveType]?: Statistic };
/** Data from rule elements for auras this actor may be emanating */
declare auras: Map<string, AuraData>;
/** A collection of this actor's conditions */
declare conditions: ActorConditions<this>;
declare perception?: PerceptionStatistic;
/** Skill checks for the actor if supported by the actor type */
declare skills?: Record<string, Statistic<this>>;
/** A cached copy of `Actor#itemTypes`, lazily regenerated every data preparation cycle */
private declare _itemTypes: EmbeddedItemInstances<this> | null;
constructor(data: PreCreate<ActorSourcePF2e>, context: DocumentConstructionContext<TParent> = {}) {
super(data, context);
Object.defineProperties(this, {
// Prevent object-recursing code from getting into `_itemTypes`,
_itemTypes: {
configurable: false,
enumerable: false,
},
// Add debounced checkAreaEffects method
checkAreaEffects: {
value: fu.debounce(checkAreaEffects, 50),
},
});
}
static override getDefaultArtwork(actorData: foundry.documents.ActorSource): {
img: ImageFilePath;
texture: { src: ImageFilePath | VideoFilePath };
} {
const img: ImageFilePath = `systems/pf2e/icons/default-icons/${actorData.type}.svg`;
return { img, texture: { src: img } };
}
/** Cache the return data before passing it to the caller */
override get itemTypes(): EmbeddedItemInstances<this> {
return (this._itemTypes ??= super.itemTypes as EmbeddedItemInstances<this>);
}
get allowedItemTypes(): (ItemType | "physical")[] {
return ["condition", "effect"];
}
/** The compendium source ID of the actor **/
get sourceId(): ActorUUID | null {
return this.flags.core?.sourceId ?? null;
}
/** The recorded schema version of this actor, updated after each data migration */
get schemaVersion(): number | null {
return Number(this.system._migration?.version ?? this.system.schema?.version) || null;
}
/** Get an active GM or, failing that, a player who can update this actor */
get primaryUpdater(): UserPF2e | null {
// 1. The first active GM, sorted by ID
const { activeGM } = game.users;
if (activeGM) return activeGM;
const activeUsers = game.users.filter((u) => u.active);
// 2. The user with this actor assigned
const primaryPlayer = this.isToken ? null : activeUsers.find((u) => u.character?.id === this.id);
if (primaryPlayer) return primaryPlayer;
// 3. Anyone who can update the actor
const firstUpdater = game.users
.filter((u) => this.canUserModify(u, "update"))
.sort((a, b) => (a.id > b.id ? 1 : -1))
.shift();
return firstUpdater ?? null;
}
get abilities(): Abilities | null {
return null;
}
/** Shortcut to system-data attributes */
get attributes(): this["system"]["attributes"] {
return this.system.attributes;
}
get hitPoints(): HitPointsSummary | null {
const { hp } = this.system.attributes;
if (!hp) return null;
return {
value: hp.value,
max: hp.max,
temp: hp.temp,
unrecoverable: hp.unrecoverable,
negativeHealing: hp.negativeHealing,
};
}
get traits(): Set<string> {
return new Set(this.system.traits?.value ?? []);
}
get level(): number {
return this.system.details.level.value;
}
get size(): Size {
return this.system.traits?.size?.value ?? "med";
}
/**
* With the exception of vehicles, actor heights aren't specified. For the purpose of three-dimensional
* token-distance measurement, however, the system will generally treat actors as cubes.
*/
get dimensions(): ActorDimensions {
const size = this.system.traits?.size ?? new ActorSizePF2e({ value: "med" });
return {
length: size.length,
width: size.width,
height: Math.min(size.length, size.width),
};
}
/**
* Whether the actor can see, given its token placement in the current scene.
* A meaningful implementation is found in `CreaturePF2e`.
*/
get canSee(): boolean {
return true;
}
/** Whether this actor can execute actions: meaningful implementations are found in `CreaturePF2e`. */
get canAct(): boolean {
return true;
}
/** Whether this actor can attack: meaningful implementations are found in `CreaturePF2e` and `HazardPF2e`. */
get canAttack(): boolean {
return false;
}
get isDead(): boolean {
const deathIcon = game.settings.get("pf2e", "deathIcon");
if (this.token) return this.token.overlayEffect === deathIcon;
const tokens = this.getActiveTokens(true, true);
return tokens.length > 0 && tokens.every((t) => t.overlayEffect === deathIcon);
}
get modeOfBeing(): ModeOfBeing {
const { traits } = this;
const isPC = isReallyPC(this);
return traits.has("undead") && !traits.has("eidolon") // Undead eidolons aren't undead
? "undead"
: traits.has("construct") && !isPC && !traits.has("eidolon") // Construct eidolons aren't constructs
? "construct"
: "living";
}
get visionLevel(): VisionLevel {
return VisionLevels.NORMAL;
}
/** Does this creature emit sound? False unless a subclass overrides it */
get emitsSound(): boolean {
return false;
}
get rollOptions(): RollOptionFlags {
return this.flags.pf2e.rollOptions;
}
/** Get the actor's held shield. Meaningful implementation in `CreaturePF2e`'s override. */
get heldShield(): ShieldPF2e<this> | null {
return null;
}
/** The actor's hardness: zero with the exception of some hazards and NPCs */
get hardness(): number {
return 0;
}
/** Most actor types can host rule elements */
get canHostRuleElements(): boolean {
return true;
}
get alliance(): ActorAlliance {
return this.system.details.alliance;
}
get combatant(): CombatantPF2e<EncounterPF2e> | null {
return game.combat?.combatants.find((c) => c.actor?.uuid === this.uuid) ?? null;
}
/** Add effect icons from effect items and rule elements */
override get temporaryEffects(): TemporaryEffect[] {
const fromConditions = this.conditions.active.map((c) => new TokenEffect(c));
const fromEffects = this.itemTypes.effect
.filter((e) => e.system.tokenIcon?.show && (e.isIdentified || game.user.isGM))
.map((e) => new TokenEffect(e));
return R.uniqueBy(
[super.temporaryEffects, fromConditions, fromEffects, this.synthetics.tokenEffectIcons].flat(),
(e) => e.icon,
);
}
/** A means of checking this actor's type without risk of circular import references */
isOfType<T extends "creature" | ActorType>(...types: T[]): this is ActorInstances<TParent>[T];
isOfType(...types: string[]): boolean {
return types.some((t) => (t === "creature" ? tupleHasValue(CREATURE_ACTOR_TYPES, this.type) : this.type === t));
}
/** Whether this actor is an ally of the provided actor */
isAllyOf(actor: ActorPF2e): boolean {
return this.alliance !== null && this !== actor && this.alliance === actor.alliance;
}
/** Whether this actor is an enemy of the provided actor */
isEnemyOf(actor: ActorPF2e): boolean {
return this.alliance !== null && actor.alliance !== null && this.alliance !== actor.alliance;
}
/** Whether this actor is immune to an effect of a certain type */
isImmuneTo(effect: AbstractEffectPF2e | ConditionSource | EffectSource | ConditionSlug): boolean {
if (!game.pf2e.settings.iwr) return false;
const item = typeof effect === "string" ? null : "parent" in effect ? effect : new ItemProxyPF2e(effect);
const statements = new Set(item ? item.getRollOptions("item") : ["item:type:condition", `item:slug:${effect}`]);
return this.attributes.immunities.some((i) => i.test(statements));
}
/** Whether this actor is affected by damage of a certain type despite lack of explicit immunity */
isAffectedBy(damage: DamageType | ConditionPF2e): boolean {
const damageType = objectHasKey(CONFIG.PF2E.damageTypes, damage)
? damage
: damage.isOfType("condition")
? damage.system.persistent?.damageType ?? null
: null;
if (!setHasElement(UNAFFECTED_TYPES, damageType)) return true;
const { traits } = this;
const damageIsApplicable: Record<UnaffectedType, boolean> = {
good: traits.has("evil"),
evil: traits.has("good"),
lawful: traits.has("chaotic"),
chaotic: traits.has("lawful"),
vitality: !!this.attributes.hp?.negativeHealing,
void: !(this.modeOfBeing === "construct" || this.attributes.hp?.negativeHealing),
bleed: this.modeOfBeing === "living",
spirit: !this.itemTypes.effect.some((e) => e.traits.has("possession")),
};
return damageIsApplicable[damageType];
}
/** Checks if the item can be added to this actor by checking the valid item types. */
checkItemValidity(source: PreCreate<ItemSourcePF2e>): boolean {
if (!itemIsOfType(source, ...this.allowedItemTypes)) {
ui.notifications.error(
game.i18n.format("PF2E.Item.CannotAddType", {
type: game.i18n.localize(CONFIG.Item.typeLabels[source.type] ?? source.type.titleCase()),
}),
);
return false;
}
return true;
}
/** Get (almost) any statistic by slug: handling expands in `ActorPF2e` subclasses */
getStatistic(slug: string): Statistic<this> | null;
getStatistic(slug: string): Statistic | null {
if (["armor", "ac"].includes(slug)) {
return this.armorClass?.parent ?? null;
}
if (tupleHasValue(SAVE_TYPES, slug)) {
return this.saves?.[slug] ?? null;
}
if (this.skills && objectHasKey(this.skills, slug)) {
return this.skills[slug] ?? null;
}
return this.synthetics.statistics.get(slug) ?? null;
}
/** Get roll options from this actor's effects, traits, and other properties */
getSelfRollOptions(prefix: "self" | "target" | "origin" = "self"): string[] {
const { rollOptions } = this;
return Object.keys(rollOptions.all).flatMap((o) =>
o.startsWith("self:") && rollOptions.all[o] ? o.replace(/^self/, prefix) : [],
);
}
/** The actor's reach: a meaningful implementation is found in `CreaturePF2e` and `HazardPF2e`. */
getReach(_options: GetReachParameters): number {
return 0;
}
/** Create a clone of this actor to recalculate its statistics with ephemeral effects and roll options included */
getContextualClone(rollOptions: string[], ephemeralEffects: (ConditionSource | EffectSource)[] = []): this {
const rollOptionsAll = rollOptions.reduce(
(options: Record<string, boolean>, option) => ({ ...options, [option]: true }),
{},
);
const applicableEffects = ephemeralEffects.filter((e) => !this.isImmuneTo(e));
return this.clone(
{
items: [fu.deepClone(this._source.items), applicableEffects].flat(),
flags: { pf2e: { rollOptions: { all: rollOptionsAll } } },
},
{ keepId: true },
);
}
/** Apply effects from an aura: will later be expanded to handle effects from measured templates */
async applyAreaEffects(aura: AuraData, origin: { actor: ActorPF2e; token: TokenDocumentPF2e }): Promise<void> {
if (
game.user !== this.primaryUpdater ||
this.isOfType("party") ||
!this.allowedItemTypes.includes("effect") ||
origin.token.hidden
) {
return;
}
const toCreate: (AfflictionSource | EffectSource)[] = [];
const rollOptions = aura.effects.some((e) => e.predicate.length > 0)
? new Set([...origin.actor.getRollOptions(), ...this.getSelfRollOptions("target")])
: new Set([]);
for (const data of aura.effects.filter((e) => e.predicate.test(rollOptions))) {
if (this.itemTypes.effect.some((e) => e.sourceId === data.uuid)) {
continue;
}
if (auraAffectsActor(data, origin.actor, this)) {
const effect = await fromUuid(data.uuid);
if (!(effect instanceof ItemPF2e && effect.isOfType("affliction", "effect"))) {
console.warn(`Effect from ${data.uuid} not found`);
continue;
}
const flags: DeepPartial<EffectFlags> = {
core: { sourceId: effect.uuid },
pf2e: {
aura: {
slug: aura.slug,
origin: origin.actor.uuid,
removeOnExit: data.removeOnExit,
},
},
};
const source = fu.mergeObject(effect.toObject(), { flags });
source.system.level.value = aura.level ?? source.system.level.value;
source.system.duration.unit = "unlimited";
source.system.duration.expiry = null;
// Only transfer traits from the aura if the effect lacks its own
if (source.system.traits.value.length === 0) {
source.system.traits.value.push(...aura.traits);
}
source.system.context = {
target: null,
origin: {
actor: origin.actor.uuid,
token: origin.token.uuid,
item: null,
spellcasting: null,
rollOptions: [],
},
roll: null,
};
for (const alteration of data.alterations) {
alteration.applyTo(source);
}
toCreate.push(source);
}
}
if (toCreate.length > 0) {
await this.createEmbeddedDocuments("Item", toCreate);
}
}
/** Don't allow the user to create in development actor types. */
static override createDialog<TDocument extends foundry.abstract.Document>(
this: ConstructorOf<TDocument>,
data?: Record<string, unknown>,
context?: {
parent?: TDocument["parent"];
pack?: Collection<TDocument> | null;
types?: (ActorType | "creature")[];
} & Partial<FormApplicationOptions>,
): Promise<TDocument | null>;
static override async createDialog(
data: { folder?: string | undefined } = {},
context: {
parent?: TokenDocumentPF2e | null;
pack?: Collection<ActorPF2e<null>> | null;
types?: (ActorType | "creature")[];
[key: string]: unknown;
} = {},
): Promise<Actor<TokenDocument<Scene | null> | null> | null> {
const omittedTypes: ActorType[] = [];
if (game.settings.get("pf2e", "campaignType") !== "kingmaker") omittedTypes.push("army");
const original = game.system.documentTypes.Actor;
try {
game.system.documentTypes.Actor = R.difference(original, omittedTypes);
if (context.types) {
const validTypes = context.types ?? [];
if (validTypes.includes("creature")) validTypes.push(...CREATURE_ACTOR_TYPES);
game.system.documentTypes.Actor = game.system.documentTypes.Actor.filter((type) =>
tupleHasValue(validTypes, type),
);
}
return super.createDialog(data, context);
} finally {
game.system.documentTypes.Actor = original;
}
}
/**
* As of Foundry 0.8: All subclasses of ActorPF2e need to use this factory method rather than having their own
* overrides, since Foundry itself will call `ActorPF2e.create` when a new actor is created from the sidebar.
*/
static override async createDocuments<TDocument extends foundry.abstract.Document>(
this: ConstructorOf<TDocument>,
data?: (TDocument | PreCreate<TDocument["_source"]>)[],
context?: DocumentModificationContext<TDocument["parent"]>,
): Promise<TDocument[]>;
static override async createDocuments(
data: (ActorPF2e | PreCreate<ActorSourcePF2e>)[] = [],
context: DocumentModificationContext<TokenDocumentPF2e | null> = {},
): Promise<Actor<TokenDocument<Scene | null> | null>[]> {
// Convert all `ActorPF2e`s to source objects
const sources = data.map((d) => (d instanceof ActorPF2e ? d.toObject() : d));
// Set additional defaults, some according to actor type
for (const source of [...sources]) {
const linkable = SIZE_LINKABLE_ACTOR_TYPES.has(source.type);
const linkToActorSize = linkable && (source.prototypeToken?.flags?.pf2e?.linkToActorSize ?? true);
const autoscale =
linkable &&
(source.prototypeToken?.flags?.pf2e?.autoscale ??
(linkToActorSize && game.settings.get("pf2e", "tokens.autoscale")));
const merged = fu.mergeObject(source, {
ownership: source.ownership ?? { default: CONST.DOCUMENT_OWNERSHIP_LEVELS.NONE },
prototypeToken: {
flags: {
// Sync token dimensions with actor size?
pf2e: { linkToActorSize, autoscale },
},
},
});
// Set default token dimensions for familiars and vehicles
const dimensionMap: { [K in ActorType]?: number } = { familiar: 0.5, vehicle: 2 };
merged.prototypeToken.height ??= dimensionMap[source.type] ?? 1;
merged.prototypeToken.width ??= merged.prototypeToken.height;
switch (merged.type) {
case "character":
case "familiar":
merged.ownership.default = CONST.DOCUMENT_OWNERSHIP_LEVELS.LIMITED;
// Default characters and their minions to having tokens with vision and an actor link
merged.prototypeToken.actorLink = true;
merged.prototypeToken.sight = { enabled: true };
break;
case "hazard":
merged.prototypeToken.sight = { enabled: false };
break;
case "loot":
// Make loot actors linked and interactable
merged.ownership.default = CONST.DOCUMENT_OWNERSHIP_LEVELS.LIMITED;
merged.prototypeToken.actorLink = true;
merged.prototypeToken.sight = { enabled: false };
break;
case "party":
// Party actors are linked and have observer ownership so that players can see during exploration
merged.ownership.default = CONST.DOCUMENT_OWNERSHIP_LEVELS.OBSERVER;
merged.prototypeToken.actorLink = true;
merged.prototypeToken.sight = { enabled: true, range: 1 };
break;
}
const migrated = await migrateActorSource(source);
sources.splice(sources.indexOf(source), 1, migrated);
}
return super.createDocuments(sources, context);
}
static override updateDocuments<TDocument extends foundry.abstract.Document>(
this: ConstructorOf<TDocument>,
updates?: Record<string, unknown>[],
context?: DocumentUpdateContext<TDocument["parent"]>,
): Promise<TDocument[]>;
static override async updateDocuments(
updates: Record<string, unknown>[] = [],
context: DocumentModificationContext<TokenDocumentPF2e | null> = {},
): Promise<Actor<TokenDocument<Scene | null> | null>[]> {
const isFullReplace = !((context?.diff ?? true) && (context?.recursive ?? true));
if (isFullReplace) return super.updateDocuments(updates, context);
// Process rule element hooks for each actor update
for (const changed of updates) {
await processPreUpdateActorHooks(changed, { pack: context.pack ?? null });
}
return super.updateDocuments(updates, context);
}
/** Set module art if available */
protected override _initializeSource(
source: Record<string, unknown>,
options?: DocumentConstructionContext<TParent>,
): this["_source"] {
const initialized = super._initializeSource(source, options);
if (options?.pack && initialized._id) {
const uuid: CompendiumUUID = `Compendium.${options.pack}.${initialized._id}`;
const art = game.pf2e.system.moduleArt.map.get(uuid) ?? {};
return fu.mergeObject(initialized, art);
}
return initialized;
}
protected override _initialize(options?: Record<string, unknown>): void {
this.initialized = false;
this._itemTypes = null;
this.armorClass = null;
this.auras = new Map();
this.conditions = new ActorConditions();
this.initiative = null;
this.rules = [];
this.spellcasting = null;
this.synthetics = {
criticalSpecializations: { standard: [], alternate: [] },
damageAlterations: {},
damageDice: { damage: [] },
degreeOfSuccessAdjustments: {},
dexterityModifierCaps: [],
modifierAdjustments: { all: [], damage: [] },
modifiers: { all: [], damage: [] },
movementTypes: {},
multipleAttackPenalties: {},
ephemeralEffects: {},
rollNotes: {},
rollSubstitutions: {},
rollTwice: {},
senses: [],
statistics: new Map(),
strikeAdjustments: [],
strikes: [],
striking: {},
tokenMarks: new Map(),
toggles: {},
tokenEffectIcons: [],
tokenOverrides: {},
weaponPotency: {},
};
super._initialize(options);
}
/**
* Never prepare data except as part of `DataModel` initialization. If embedded, don't prepare data if the parent is
* not yet initialized. See https://github.com/foundryvtt/foundryvtt/issues/7987
*/
override prepareData(): void {
if (this.initialized) return;
// Set after data model is initialized so that `this.id` will be defined (and `this.uuid` will be complete)
this.signature ??= UUIDv5(this.uuid, "e9fa1461-0edc-4791-826e-08633f1c6ef7"); // magic number as namespace
if (this.parent && !this.parent.initialized) return;
this.initialized = true;
super.prepareData();
// Split spellcasting entry into those that extend a magic tradition and those that don't.
// Those that don't may be extending special statistics and need to run afterwards
// NOTE: Later on special statistics should have support for phases (with class/spell dc defaulting to last)
const spellcasting = this.itemTypes.spellcastingEntry;
const traditionBased = spellcasting.filter((s) => setHasElement(MAGIC_TRADITIONS, s.system.proficiency.slug));
const nonTraditionBased = spellcasting.filter((s) => !traditionBased.includes(s));
for (const entry of traditionBased) {
entry.prepareStatistic();
}
// Call post-derived-preparation `RuleElement` hooks
for (const rule of this.rules) {
rule.afterPrepareData?.();
}
// Run the spellcasting entries that need to run after special statistic
for (const entry of nonTraditionBased) {
entry.prepareStatistic();
}
// IWR rule elements were only just processed: set the actor to not off-guardable if immune to the condition
if (this.attributes.flanking.offGuardable && this.isImmuneTo("off-guard")) {
this.attributes.flanking.offGuardable = false;
}
this.preparePrototypeToken();
if (this.initialized && canvas.ready) {
// Work around `t.actor` potentially being a lazy getter for a synthetic actor (viz. this one)
const thisTokenIsControlled = canvas.tokens.controlled.some(
(t) => t.document === this.parent || (t.document.actorLink && t.actor === this),
);
if (game.user.character === this || thisTokenIsControlled) {
game.pf2e.effectPanel.refresh();
}
}
this.conditions.finalize();
}
/** Prepare baseline ephemeral data applicable to all actor types */
override prepareBaseData(): void {
super.prepareBaseData();
this.system.autoChanges = {};
this.system.attributes.flanking = { canFlank: false, canGangUp: [], flankable: false, offGuardable: false };
const { attributes, details } = this.system;
attributes.hp &&= fu.mergeObject(attributes.hp, { negativeHealing: false, unrecoverable: 0 });
attributes.immunities = attributes.immunities?.map((i) => new Immunity(i)) ?? [];
attributes.weaknesses = attributes.weaknesses?.map((w) => new Weakness(w)) ?? [];
attributes.resistances = attributes.resistances?.map((r) => new Resistance(r)) ?? [];
details.level.value = Math.floor(details.level.value) || 0;
const traits: ActorTraitsData<string> | undefined = this.system.traits;
if (traits?.size) traits.size = new ActorSizePF2e(traits.size);
// Setup the basic structure of pf2e flags with roll options
this.flags.pf2e = fu.mergeObject(this.flags.pf2e ?? {}, {
rollOptions: {
all: {
[`self:type:${this.type}`]: true,
[`self:signature:${this.signature}`]: true,
...createEncounterRollOptions(this),
},
},
trackedItems: {},
});
}
/** Prepare the physical-item collection on this actor, item-sibling data, and rule elements */
override prepareEmbeddedDocuments(): void {
super.prepareEmbeddedDocuments();
const physicalItems = this.items.filter((i): i is PhysicalItemPF2e<this> => i.isOfType("physical"));
this.inventory = new ActorInventory(this, physicalItems);
// Track all effects on this actor
for (const effect of this.itemTypes.effect) {
game.pf2e.effectTracker.register(effect);
}
this.prepareDataFromItems();
}
/** Prepare data among owned items as well as actor-data preparation performed by items */
protected prepareDataFromItems(): void {
for (const condition of this.itemTypes.condition) {
this.conditions.set(condition.id, condition);
}
for (const item of this.items) {
item.prepareSiblingData?.();
item.prepareActorData?.();
}
this.rules = this.prepareRuleElements();
}
protected prepareRuleElements(): RuleElementPF2e[] {
// Ensure certain ABC items go early and common temporary items go last
// These leads to predictability with RE overrides such as auras and CreatureSize
const sortOrder: Partial<Record<ItemType, number>> = {
ancestry: 0,
heritage: 1,
background: 2,
class: 3,
};
return R.sortBy(
this.items.contents,
(i) => sortOrder[i.type as ItemType] ?? Infinity,
(i) => i.isOfType("affliction", "condition", "effect"),
)
.flatMap((item) => item.prepareRuleElements())
.filter((rule) => !rule.ignored)
.sort((elementA, elementB) => elementA.priority - elementB.priority);
}
/** Collect all rule element output */
protected prepareSynthetics(): void {
// Rule elements
for (const rule of this.rules.filter((r) => !r.ignored)) {
try {
rule.beforePrepareData?.();
} catch (error) {
// Ensure that a failing rule element does not block actor initialization
const ruleName = game.i18n.localize(`PF2E.RuleElement.${rule.key}`);
console.error(`PF2e | Failed to execute onBeforePrepareData on rule element ${ruleName}.`, error);
}
}
for (const item of this.items) {
item.onPrepareSynthetics?.();
}
}
/** Set traits as roll options */
override prepareDerivedData(): void {
const rollOptions = this.flags.pf2e.rollOptions;
for (const trait of this.traits) {
rollOptions.all[`self:trait:${trait}`] = true;
}
}
/** Set defaults for this actor's prototype token */
private preparePrototypeToken(): void {
this.prototypeToken.flags = fu.mergeObject(
{ pf2e: { linkToActorSize: SIZE_LINKABLE_ACTOR_TYPES.has(this.type) } },
this.prototypeToken.flags,
);
TokenDocumentPF2e.assignDefaultImage(this.prototypeToken);
TokenDocumentPF2e.prepareSize(this.prototypeToken);
}
/* -------------------------------------------- */
/* Rolls */
/* -------------------------------------------- */
/** Toggle the provided roll option (swapping it from true to false or vice versa). */
async toggleRollOption(domain: string, option: string, value?: boolean): Promise<boolean | null>;
async toggleRollOption(
domain: string,
option: string,
itemId?: string | null,
value?: boolean,
suboption?: string | null,
): Promise<boolean | null>;
async toggleRollOption(
domain: string,
option: string,
itemId: string | boolean | null = null,
value?: boolean,
suboption: string | null = null,
): Promise<boolean | null> {
// Backward compatibility
value = typeof itemId === "boolean" ? itemId : value ?? !this.rollOptions[domain]?.[option];
type MaybeRollOption = { key: string; domain?: unknown; option?: unknown };
if (typeof itemId === "string") {
// An item ID is provided: find the rule on the item
const item = this.items.get(itemId, { strict: true });
const rule = item.rules.find(
(r: MaybeRollOption): r is RollOptionRuleElement =>
r.key === "RollOption" && r.domain === domain && r.option === option,
);
return rule?.toggle(value, suboption) ?? null;
} else {
// Less precise: no item ID is provided, so find the rule on the actor
const rule = this.rules.find(
(r: MaybeRollOption): r is RollOptionRuleElement =>
r.key === "RollOption" && r.domain === domain && r.option === option,
);
return rule?.toggle(value, suboption) ?? null;
}
}
/**
* Handle how changes to a Token attribute bar are applied to the Actor.
*
* If the attribute bar is for hp and the change is in delta form, defer to the applyDamage method. Otherwise, do
* nothing special.
* @param attribute The attribute path
* @param value The target attribute value
* @param isDelta Whether the number represents a relative change (true) or an absolute change (false)
* @param isBar Whether the new value is part of an attribute bar, or just a direct value
*/
override async modifyTokenAttribute(
attribute: string,
value: number,
isDelta = false,
isBar?: boolean,
): Promise<this> {
const token = this.getActiveTokens(true, true).shift();
const { hitPoints } = this;
const isDamage = !!(
attribute === "attributes.hp" &&
hitPoints &&
(isDelta || (value === 0 && token?.combatant))
);
if (isDamage && token) {
const damage = isDelta ? -1 * value : hitPoints.value - value;
return this.applyDamage({ damage, token, final: true });
}
return super.modifyTokenAttribute(attribute, value, isDelta, isBar);
}
/**
* Apply rolled dice damage to the token or tokens which are currently controlled.
* This allows for damage to be scaled by a multiplier to account for healing, critical hits, or resistance
* @param finalDamage The amount of damage inflicted
* @param token The applicable token for this actor
* @param shieldBlockRequest Whether the user has toggled the Shield Block button
*/
async applyDamage({
damage,
token,
item,
rollOptions = new Set(),
skipIWR = false,
shieldBlockRequest = false,
breakdown = [],
notes = [],
outcome = null,
final = false,
}: ApplyDamageParams): Promise<this> {
const hitPoints = this.hitPoints;
if (!hitPoints) return this;
if (final) {
shieldBlockRequest = false;
skipIWR = true;
}
// Round damage and healing (negative values) toward zero
const result: IWRApplicationData =
typeof damage === "number"
? { finalDamage: Math.trunc(damage), applications: [], persistent: [] }
: skipIWR
? { finalDamage: damage.total, applications: [], persistent: [] }
: applyIWR(this, damage, rollOptions);
// Extract Target-specific healing adjustments (unless final)
// Currently only healing modifiers are implemented
const domain = result.finalDamage < 0 ? "healing-received" : "damage-received";
const { modifiers, damageDice } = (() => {
if (final || domain !== "healing-received") {
return { modifiers: [], damageDice: [] };
}
const critical = outcome === "criticalSuccess";
const resolvables = ((): Record<string, unknown> => {
if (item?.isOfType("spell")) return { spell: item };
if (item?.isOfType("weapon")) return { weapon: item };
return {};
})();
const damageDice = extractDamageDice(this.synthetics.damageDice, {
selectors: [domain],
resolvables,
test: rollOptions,
}).filter((d) => (d.critical === null || d.critical === critical) && d.predicate.test(rollOptions));
const modifiers = extractModifiers(this.synthetics, [domain], { resolvables }).filter(
(m) => (m.critical === null || m.critical === critical) && m.predicate.test(rollOptions),
);
return { modifiers, damageDice };
})();
// Roll any dice damage adjustments and produce a total result
const diceAdjustment = (
await Promise.all(
damageDice.map(async (dice) => {
const formula = `${dice.diceNumber}${dice.dieSize}[${dice.label}]`;
const roll = await new Roll(formula).evaluate({ async: true });
roll._formula = `${dice.diceNumber}${dice.dieSize}`; // remove the label from the main formula
await roll.toMessage({