-
Notifications
You must be signed in to change notification settings - Fork 319
Expand file tree
/
Copy pathactor.mjs
More file actions
3754 lines (3271 loc) · 154 KB
/
actor.mjs
File metadata and controls
3754 lines (3271 loc) · 154 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
import BaseRestDialog from "../../applications/actor/rest/base-rest-dialog.mjs";
import CreateDocumentDialog from "../../applications/create-document-dialog.mjs";
import SkillToolRollConfigurationDialog from "../../applications/dice/skill-tool-configuration-dialog.mjs";
import PropertyAttribution from "../../applications/property-attribution.mjs";
import TravelField from "../../data/actor/fields/travel-field.mjs";
import ActivationsField from "../../data/chat-message/fields/activations-field.mjs";
import { ActorDeltasField } from "../../data/chat-message/fields/deltas-field.mjs";
import AdvantageModeField from "../../data/fields/advantage-mode-field.mjs";
import TransformationSetting from "../../data/settings/transformation-setting.mjs";
import { createRollLabel } from "../../enrichers.mjs";
import {
convertTime, defaultUnits, formatLength, formatNumber, formatTime, simplifyBonus, staticID
} from "../../utils.mjs";
import ActiveEffect5e from "../active-effect.mjs";
import Item5e from "../item.mjs";
import SystemDocumentMixin from "../mixins/document.mjs";
import Proficiency from "./proficiency.mjs";
import SelectChoices from "./select-choices.mjs";
import * as Trait from "./trait.mjs";
/**
* @import { RequestOptions5e } from "../../_types.mjs";
* @import { AttributionDescription } from "../../applications/_types.mjs";
* @import { TravelPace5e } from "../../data/actor/fields/_types.mjs";
* @import { SkillData } from "../../data/actor/templates/_types.mjs";
* @import {
* AbilityRollProcessConfiguration,
* BasicRollDialogConfiguration, BasicRollMessageConfiguration,
* HitDieRollProcessConfiguration, InitiativeRollOptions,
* SkillToolRollDialogConfiguration, SkillToolRollProcessConfiguration
* } from "../../dice/_types.mjs";
* @import {
* ActorRollData, DamageAffectCategory, DamageApplicationOptions, DamageDescription, DamageSummary,
* RestConfiguration, RestResult, RollDataOptions, SpellcastingDescription
* } from "../_types.mjs";
*/
/**
* Extend the base Actor class to implement additional system-specific logic.
*/
export default class Actor5e extends SystemDocumentMixin(Actor) {
/** @override */
static DEFAULT_ICON = "systems/dnd5e/icons/svg/documents/actor.svg";
/* -------------------------------------------- */
/**
* Lazily computed store of classes, subclasses, background, and species.
* @type {Record<string, Record<string, Item5e|Item5e[]>>}
*/
_lazy = {};
/* -------------------------------------------- */
/**
* Cached copy of the preferred artwork.
* @type {{ src: string, isToken: boolean, isRandom: boolean, isVideo: boolean }|null}
*/
_preferredArtwork = this._preferredArtwork;
/* -------------------------------------------- */
/**
* Mapping of item identifiers to the items.
* @type {IdentifiedItemsMap<string, Set<Item5e>>}
*/
identifiedItems = this.identifiedItems;
/* -------------------------------------------- */
/**
* Mapping of item compendium source UUIDs to the items.
* @type {SourcedItemsMap<string, Set<Item5e>>}
*/
sourcedItems = this.sourcedItems;
/* -------------------------------------------- */
/**
* Types that can be selected within the compendium browser.
* @param {object} [options={}]
* @param {Set<string>} [options.chosen] Types that have been selected.
* @returns {SelectChoices}
*/
static compendiumBrowserTypes({ chosen=new Set() }={}) {
return new SelectChoices(Actor.TYPES.filter(t => t !== CONST.BASE_DOCUMENT_TYPE).reduce((obj, type) => {
obj[type] = {
label: CONFIG.Actor.typeLabels[type],
chosen: chosen.has(type)
};
return obj;
}, {}));
}
/* -------------------------------------------- */
/* Properties */
/* -------------------------------------------- */
/**
* A mapping of classes belonging to this Actor.
* @type {Record<string, Item5e>}
*/
get classes() {
if ( this._lazy?.classes !== undefined ) return this._lazy.classes;
return this._lazy.classes = Object.fromEntries(this.itemTypes.class.map(cls => [cls.identifier, cls]));
}
/* -------------------------------------------- */
/**
* Calculate the bonus from any cover the actor is affected by.
* @type {number} The cover bonus to AC and dexterity saving throws.
*/
get coverBonus() {
const { coverHalf, coverThreeQuarters } = CONFIG.DND5E.statusEffects;
if ( this.statuses.has("coverThreeQuarters") ) return coverThreeQuarters?.coverBonus;
else if ( this.statuses.has("coverHalf") ) return coverHalf?.coverBonus;
return 0;
}
/* -------------------------------------------- */
/**
* Get all classes which have spellcasting ability.
* @type {Record<string, Item5e>}
*/
get spellcastingClasses() {
if ( this._lazy.spellcastingClasses !== undefined ) return this._lazy.spellcastingClasses;
return this._lazy.spellcastingClasses = Object.entries(this.classes).reduce((obj, [identifier, cls]) => {
if ( cls.spellcasting && (cls.spellcasting.progression !== "none") ) obj[identifier] = cls;
return obj;
}, {});
}
/* -------------------------------------------- */
/**
* A mapping of subclasses belonging to this Actor.
* @type {Record<string, Item5e>}
*/
get subclasses() {
if ( this._lazy?.subclasses !== undefined ) return this._lazy.subclasses;
return this._lazy.subclasses = Object.fromEntries(this.itemTypes.subclass.map(i => [i.identifier, i]));
}
/* -------------------------------------------- */
/**
* Is this Actor currently polymorphed into some other creature?
* @type {boolean}
*/
get isPolymorphed() {
return this.getFlag("dnd5e", "isPolymorphed") || false;
}
/* -------------------------------------------- */
/**
* The Actor's currently equipped armor, if any.
* @type {Item5e|null}
*/
get armor() {
return this.system.attributes?.ac?.equippedArmor ?? null;
}
/* -------------------------------------------- */
/**
* The Actor's currently equipped shield, if any.
* @type {Item5e|null}
*/
get shield() {
return this.system.attributes?.ac?.equippedShield ?? null;
}
/* -------------------------------------------- */
/**
* The items this actor is concentrating on, and the relevant effects.
* @type {{items: Set<Item5e>, effects: Set<ActiveEffect5e>}}
*/
get concentration() {
const concentration = {
items: new Set(),
effects: new Set()
};
const limit = this.system.attributes?.concentration?.limit ?? 0;
if ( !limit ) return concentration;
for ( const effect of this.effects ) {
if ( !effect.statuses.has(CONFIG.specialStatusEffects.CONCENTRATING) ) continue;
const data = effect.getFlag("dnd5e", "item");
concentration.effects.add(effect);
if ( data ) {
let item = this.items.get(data.id);
if ( !item && (foundry.utils.getType(data.data) === "Object") ) {
item = new Item.implementation(data.data, { keepId: true, parent: this });
}
if ( item ) concentration.items.add(item);
}
}
return concentration;
}
/* -------------------------------------------- */
/**
* Creatures summoned by this actor.
* @type {Actor5e[]}
*/
get summonedCreatures() {
return dnd5e.registry.summons.creatures(this);
}
/* -------------------------------------------- */
/* Data Migration */
/* -------------------------------------------- */
/** @inheritDoc */
_initializeSource(source, options={}) {
if ( source instanceof foundry.abstract.DataModel ) source = source.toObject();
/**
* A hook event that fires before source data is initialized for an Actor in a compendium.
* @function dnd5e.initializeActorSource
* @memberof hookEvents
* @param {Actor5e} actor Actor for which the data is being initialized.
* @param {object} source Source data being initialized.
* @param {object} options Additional data initialization options.
*/
if ( options.pack ) Hooks.callAll("dnd5e.initializeActorSource", this, source, options);
// Migrate encounter groups to their own Actor type.
if ( (source.type === "group") && (source.system?.type?.value === "encounter") ) {
source.type = "encounter";
foundry.utils.setProperty(source, "flags.dnd5e.persistSourceMigration", true);
}
source = super._initializeSource(source, options);
const pack = game.packs.get(options.pack);
if ( !source._id || !pack || !game.compendiumArt.enabled ) return source;
const uuid = pack.getUuid(source._id);
const art = game.dnd5e.moduleArt.map.get(uuid);
if ( art?.actor || art?.token ) {
if ( art.actor ) source.img = art.actor;
if ( typeof art.token === "string" ) source.prototypeToken.texture.src = art.token;
else if ( art.token ) foundry.utils.mergeObject(source.prototypeToken, art.token);
Actor5e.applyCompendiumArt(source, pack, art);
}
return source;
}
/* -------------------------------------------- */
/* Methods */
/* -------------------------------------------- */
/**
* Apply package-provided art to a compendium Document.
* @param {object} source The Document's source data.
* @param {CompendiumCollection} pack The Document's compendium.
* @param {CompendiumArtInfo} art The art being applied.
*/
static applyCompendiumArt(source, pack, art) {
const biography = source.system.details?.biography;
if ( art.credit && biography ) {
if ( typeof biography.value !== "string" ) biography.value = "";
biography.value += `<p>${art.credit}</p>`;
}
}
/* -------------------------------------------- */
/**
* Format a type object into a string.
* @param {object} typeData The type data to convert to a string.
* @returns {string}
*/
static formatCreatureType(typeData) {
if ( typeof typeData === "string" ) return typeData; // Backwards compatibility
let localizedType;
if ( typeData.value === "custom" ) localizedType = typeData.custom;
else if ( typeData.value in CONFIG.DND5E.creatureTypes ) {
const code = CONFIG.DND5E.creatureTypes[typeData.value];
localizedType = game.i18n.localize(typeData.swarm ? code.plural : code.label);
}
let type = localizedType;
if ( typeData.swarm ) {
type = game.i18n.format("DND5E.CreatureSwarmPhrase", {
size: game.i18n.localize(CONFIG.DND5E.actorSizes[typeData.swarm].label),
type: localizedType
});
}
if ( typeData.subtype ) type = `${type} (${typeData.subtype})`;
return type;
}
/* -------------------------------------------- */
/** @inheritDoc */
prepareData() {
if ( this.system.modelProvider !== dnd5e ) return super.prepareData();
this._clearCachedValues();
this._preparationWarnings = [];
this.labels = {};
super.prepareData();
this.items.forEach(item => item.prepareFinalAttributes());
this._prepareSpellcasting();
}
/* --------------------------------------------- */
/**
* Clear cached class collections.
* @internal
*/
_clearCachedValues() {
this._lazy = {};
this._preferredArtwork = null;
this.identifiedItems = new IdentifiedItemsMap();
this.sourcedItems = new SourcedItemsMap();
}
/* --------------------------------------------- */
/** @inheritDoc */
prepareEmbeddedDocuments() {
this._embeddedPreparation = true;
super.prepareEmbeddedDocuments();
delete this._embeddedPreparation;
}
/* -------------------------------------------- */
/**
* Prepares data for a specific skill.
* @param {string} skillId The id of the skill to prepare data for.
* @param {object} [options] Additional options passed to {@link CreatureTemplate#prepareSkill}.
* @returns {SkillData}
* @internal
*/
_prepareSkill(skillId, options) {
return this.system.prepareSkill?.(skillId, options) ?? {};
}
/* --------------------------------------------- */
/** @inheritDoc */
applyActiveEffects(phase) {
if ( game.release.generation < 14 ) phase ??= "initial";
if ( (this.system?.prepareEmbeddedData instanceof Function) && (phase === "initial") ) {
this.system.prepareEmbeddedData();
}
return super.applyActiveEffects(phase);
}
/* -------------------------------------------- */
/** @inheritDoc */
*allApplicableEffects() {
for ( const effect of super.allApplicableEffects() ) {
if ( effect.type === "enchantment" ) continue;
if ( effect.parent?.getFlag("dnd5e", "riders.effect")?.includes(effect.id) ) continue;
yield effect;
}
}
/* -------------------------------------------- */
/**
* Fetch an Actor by UUID and obtain a version of it in the World. If the Actor is inside a compendium, check if a
* version has already been imported before importing it again.
* @param {string} uuid The Actor's UUID.
* @param {object} [options]
* @param {object} [options.origin] Optionally check if the Actor has a specific origin. If not supplied, any
* Actor that matches the criteria will be returned.
* @param {string} [options.origin.key] The origin property.
* @param {any} [options.origin.value] The origin value.
* @returns {Promise<Actor5e>}
* @throws {Error} If the Actor cannot be found, or cannot be imported.
*/
static async fetchExisting(uuid, options={}) {
const { origin } = options;
const actor = await fromUuid(uuid);
if ( !actor ) throw new Error(game.i18n.format("DND5E.ACTOR.Warning.NoActor", { uuid }));
const { actorLink } = actor.prototypeToken;
const matchesOrigin = !origin || (foundry.utils.getProperty(actor, origin.key) === origin.value);
if ( !actor.pack && (!actorLink || matchesOrigin) ) return actor;
// Search world actors to see if any had been previously imported for this purpose.
// Linked actors must match the origin to be considered.
const localActor = game.actors.find(a => {
const matchesOrigin = !origin || (foundry.utils.getProperty(a, origin.key) === origin.value);
// Has been auto-imported by this process.
return (a.getFlag("dnd5e", "isAutoImported") || a.getFlag("dnd5e", "summonedCopy")) // Back-compat
// User has ownership of existing actor
&& a.isOwner
// Sourced from the desired actor UUID.
&& ((a._stats?.compendiumSource === uuid) || (a._stats?.duplicateSource === uuid))
// Unlinked or created from a specific source.
&& (!a.prototypeToken.actorLink || matchesOrigin);
});
if ( localActor ) return localActor;
// Check permissions to create actors.
if ( !game.user.can("ACTOR_CREATE") ) throw new Error(game.i18n.localize("DND5E.ACTOR.Warning.CreateActor"));
// No suitable world actor was found, create one.
if ( actor.pack ) {
// Template actor resides only in a compendium, import the actor into the world.
return game.actors.importFromCompendium(game.packs.get(actor.pack), actor.id, {
"flags.dnd5e.isAutoImported": true
});
} else {
// A linked world actor was found. Create a copy to avoid affecting the original.
return actor.clone({
"flags.dnd5e.isAutoImported": true,
"_stats.compendiumSource": actor._stats.compendiumSource,
"_stats.duplicateSource": actor.uuid
}, { save: true });
}
}
/* -------------------------------------------- */
/**
* Select appropriate artwork to display on sheet & chat cards based on `showTokenPortrait` flag.
* @returns {Promise<{ src: string, token: boolean, isRandom: boolean, isVideo: boolean }>}
*/
async getPreferredArtwork() {
if ( !this._preferredArtwork ) {
const showTokenPortrait = this.getFlag("dnd5e", "showTokenPortrait") === true;
const token = this.isToken ? this.token : this.prototypeToken;
const defaultArtwork = Actor.implementation.getDefaultArtwork(this._source)?.img;
let texture = token?.texture.src;
if ( showTokenPortrait && token?.randomImg ) {
const images = await this.getTokenImages();
texture = images[Math.floor(Math.random() * images.length)];
}
const src = (showTokenPortrait ? texture : this.img) ?? defaultArtwork;
this._preferredArtwork = {
src,
isRandom: showTokenPortrait && token?.randomImg,
isToken: showTokenPortrait,
isVideo: foundry.helpers.media.VideoHelper.hasVideoExtension(src)
};
}
return this._preferredArtwork;
}
/* -------------------------------------------- */
/** @inheritDoc */
prepareDerivedData() {
const origin = this.getFlag("dnd5e", "summon.origin");
if ( origin && this.token?.id ) {
const { collection, primaryId } = foundry.utils.parseUuid(origin);
dnd5e.registry.summons.track(collection?.get?.(primaryId)?.uuid, this.uuid);
}
}
/* -------------------------------------------- */
/**
* Calculate the DC of a concentration save required for a given amount of damage.
* @param {number} damage Amount of damage taken.
* @returns {number} DC of the required concentration save.
*/
getConcentrationDC(damage) {
return Math.clamp(
Math.floor(damage / 2), 10, dnd5e.settings.rulesVersion === "modern" ? 30 : Infinity
);
}
/* -------------------------------------------- */
/**
* Return the amount of experience required to gain a certain character level.
* @param {number} level The desired level.
* @returns {number} The XP required.
*/
getLevelExp(level) {
const levels = CONFIG.DND5E.CHARACTER_EXP_LEVELS;
return levels[Math.min(level, levels.length - 1)];
}
/* -------------------------------------------- */
/**
* Return the amount of experience granted by killing a creature of a certain CR.
* @param {number|null} cr The creature's challenge rating.
* @returns {number|null} The amount of experience granted per kill.
*/
getCRExp(cr) {
if ( cr === null ) return null;
if ( cr < 1.0 ) return Math.max(200 * cr, 10);
return CONFIG.DND5E.CR_EXP_LEVELS[cr] ?? Object.values(CONFIG.DND5E.CR_EXP_LEVELS).pop();
}
/* -------------------------------------------- */
/**
* @inheritdoc
* @param {RollDataOptions} [options]
* @returns {ActorRollData}
*/
getRollData({ deterministic=false }={}) {
let data;
if ( this.system.getRollData ) data = this.system.getRollData({ deterministic });
else data = {...super.getRollData()};
data.flags = {...this.flags};
data.name = this.name;
data.statuses = {};
for ( const status of this.statuses ) {
data.statuses[status] = status === "exhaustion"
? this.system.attributes?.exhaustion ?? 1
: status === "concentrating" ? this.concentration.effects.size : 1;
}
return data;
}
/* -------------------------------------------- */
/**
* Is this actor under the effect of this property from some status or due to its level of exhaustion?
* @param {string} key A key in `DND5E.conditionEffects`.
* @returns {boolean} Whether the actor is affected.
*/
hasConditionEffect(key) {
const props = CONFIG.DND5E.conditionEffects[key] ?? new Set();
const level = this.system.attributes?.exhaustion ?? null;
const imms = this.system.traits?.ci?.value ?? new Set();
const applyExhaustion = (level !== null) && !imms.has("exhaustion")
&& (dnd5e.settings.rulesVersion === "legacy");
const statuses = this.statuses;
return props.some(k => {
const l = Number(k.split("-").pop());
return (statuses.has(k) && !imms.has(k)) || (applyExhaustion && Number.isInteger(l) && (level >= l));
});
}
/* -------------------------------------------- */
/* Spellcasting Preparation */
/* -------------------------------------------- */
/**
* Prepare data related to the spell-casting capabilities of the Actor.
* Mutates the value of the system.spells object. Must be called after final item preparation.
* @protected
*/
_prepareSpellcasting() {
if ( !this.system.spells ) return;
// Translate the list of classes into spellcasting progression
const progression = Object.values(CONFIG.DND5E.spellcasting).reduce((acc, model) => {
if ( model.slots ) acc[model.key] = 0;
return acc;
}, {});
const types = {};
// Grab all classes with spellcasting
const classes = this.itemTypes.class.filter(cls => {
const type = cls.spellcasting.type;
if ( !type ) return false;
types[type] = (types[type] ?? 0) + 1;
return true;
});
for ( const cls of classes ) {
this.constructor.computeClassProgression(progression, cls, { actor: this, count: types[cls.spellcasting.type] });
}
if ( this.system.isNPC && ("spell" in (this.system.attributes ?? {})) ) {
const level = Object.values(progression).find(_ => _);
if ( level ) this.system.attributes.spell.level = level;
else if ( this.system.attributes.spell.level > 0 ) {
const methods = this.itemTypes.spell.reduce((m, s) => {
if ( s.system.level && CONFIG.DND5E.spellcasting[s.system.method]?.slots ) m.add(s.system.method);
return m;
}, new Set());
if ( methods.size ) methods.forEach(k => progression[k] = this.system.attributes.spell.level);
else progression.spell = this.system.attributes.spell.level;
}
}
for ( const [type, model] of Object.entries(CONFIG.DND5E.spellcasting) ) {
if ( !model.slots ) continue;
// Assume spellcasting methods without progression are based on character level rather than class level.
if ( foundry.utils.isEmpty(model.progression) ) model.computeProgression(progression, this);
this.constructor.prepareSpellcastingSlots(this.system.spells, type, progression, { actor: this });
}
}
/* -------------------------------------------- */
/**
* Contribute to the actor's spellcasting progression.
* @param {object} progression Spellcasting progression data. *Will be mutated.*
* @param {Item5e} cls Class for whom this progression is being computed.
* @param {object} [config={}]
* @param {Actor5e} [config.actor] Actor for whom the data is being prepared.
* @param {SpellcastingDescription} [config.spellcasting] Spellcasting descriptive object.
* @param {number} [config.count=1] Number of classes with this type of spellcasting.
*/
static computeClassProgression(progression, cls, {actor, spellcasting, count=1}={}) {
const type = cls.spellcasting.type;
spellcasting ??= cls.spellcasting;
/**
* A hook event that fires while computing the spellcasting progression for each class on each actor.
* The actual hook names include the spellcasting type (e.g. `dnd5e.computeLeveledProgression`).
* @param {object} progression Spellcasting progression data. *Will be mutated.*
* @param {Actor5e|void} actor Actor for whom the data is being prepared.
* @param {Item5e} cls Class for whom this progression is being computed.
* @param {SpellcastingDescription} spellcasting Spellcasting descriptive object.
* @param {number} count Number of classes with this type of spellcasting.
* @returns {boolean} Explicitly return false to prevent default progression from being calculated.
* @function dnd5e.computeSpellcastingProgression
* @memberof hookEvents
*/
const allowed = Hooks.call(
`dnd5e.compute${type.capitalize()}Progression`, progression, actor, cls, spellcasting, count
);
const model = CONFIG.DND5E.spellcasting[type];
if ( (allowed === false) || !model.slots ) return;
// Check for deprecated overrides.
if ( model.isSingleLevel ) {
if ( foundry.utils.getDefiningClass(this, "computePactProgression") !== Actor5e ) {
foundry.utils.logCompatibilityWarning("Actor5e.computePactProgression is deprecated. Please use "
+ "SpellcastingModel#computeProgression instead.", { since: "DnD5e 5.1", until: "DnD5e 6.0" });
this.computePactProgression(progression, actor, cls, spellcasting, count);
return;
}
} else if ( foundry.utils.getDefiningClass(this, "computeLeveledProgression") !== Actor5e ) {
foundry.utils.logCompatibilityWarning("Actor5e.computeLeveledProgression is deprecated. Please use "
+ "SpellcastingModel#computeProgression instead.", { since: "DnD5e 5.1", until: "DnD5e 6.0" });
this.computeLeveledProgression(progression, actor, cls, spellcasting, count);
return;
}
// Otherwise proceed with calculation.
model.computeProgression(progression, actor, cls, spellcasting, count);
}
/* -------------------------------------------- */
/**
* Prepare actor's spell slots using progression data.
* @param {object} spells The `data.spells` object within actor's data. *Will be mutated.*
* @param {string} type Type of spellcasting slots being prepared.
* @param {object} progression Spellcasting progression data.
* @param {object} [config]
* @param {Actor5e} [config.actor] Actor for whom the data is being prepared.
*/
static prepareSpellcastingSlots(spells, type, progression, {actor}={}) {
/**
* A hook event that fires to convert the provided spellcasting progression into spell slots.
* The actual hook names include the spellcasting type (e.g. `dnd5e.prepareLeveledSlots`).
* @param {object} spells The `data.spells` object within actor's data. *Will be mutated.*
* @param {Actor5e|void} actor Actor for whom the data is being prepared, if any.
* @param {object} progression Spellcasting progression data.
* @returns {boolean} Explicitly return false to prevent default preparation from being performed.
* @function dnd5e.prepareSpellcastingSlots
* @memberof hookEvents
*/
const allowed = Hooks.call(`dnd5e.prepare${type.capitalize()}Slots`, spells, actor, progression);
if ( allowed === false ) return;
const model = CONFIG.DND5E.spellcasting[type];
// Check for deprecated overrides.
if ( model.isSingleLevel ) {
if ( foundry.utils.getDefiningClass(this, "preparePactSlots") !== Actor5e ) {
foundry.utils.logCompatibilityWarning("Actor5e.preparePactSlots is deprecated. Please use "
+ "SpellcastingModel#prepareSlots instead.", { since: "DnD5e 5.1", until: "DnD5e 6.0" });
this.preparePactSlots(spells, actor, progression);
return;
}
} else if ( foundry.utils.getDefiningClass(this, "prepareLeveledSlots") !== Actor5e ) {
foundry.utils.logCompatibilityWarning("Actor5e.prepareLeveledSlots is deprecated. Please use "
+ "SpellcastingModel#prepareSlots instead.", { since: "DnD5e 5.1", until: "DnD5e 6.0" });
this.prepareLeveledSlots(spells, actor, progression);
return;
}
// Otherwise proceed with calculation.
model.prepareSlots(spells, actor, progression);
}
/* -------------------------------------------- */
/* Gameplay Mechanics */
/* -------------------------------------------- */
/** @override */
async modifyTokenAttribute(attribute, value, isDelta, isBar) {
if ( attribute === "attributes.hp" ) {
const hp = this.system.attributes.hp;
const delta = isDelta ? (-1 * value) : (hp.value + hp.temp) - value;
return this.applyDamage(delta, { isDelta });
} else if ( attribute.startsWith(".") ) {
const item = fromUuidSync(attribute, { relative: this });
let newValue = item?.system.uses?.value ?? 0;
if ( isDelta ) newValue += value;
else newValue = value;
return item?.update({ "system.uses.spent": item.system.uses.max - newValue });
}
return super.modifyTokenAttribute(attribute, value, isDelta, isBar);
}
/* -------------------------------------------- */
/**
* Apply a certain amount of damage or healing to the health pool for Actor
* @param {DamageDescription[]|number} damages Damages to apply.
* @param {DamageApplicationOptions} [options={}] Damage application options.
* @returns {Promise<Actor5e>} A Promise which resolves once the damage has been applied.
*/
async applyDamage(damages, options={}) {
const hp = this.system.attributes.hp;
if ( !hp ) return this; // Group actors don't have HP at the moment
if ( Number.isNumeric(damages) ) {
damages = [{ value: damages }];
options.ignore ??= true;
}
damages = this.calculateDamage(damages, options);
if ( !damages ) return this;
const { amount, temp, tempMax } = damages;
const deltaTemp = amount > 0 ? Math.min(hp.temp, amount) : 0;
const deltaHP = Math.clamp(amount - deltaTemp, -hp.damage + tempMax, hp.value - tempMax);
const updates = {
"system.attributes.hp.temp": hp.temp - deltaTemp,
"system.attributes.hp.tempmax": hp.tempmax - tempMax,
"system.attributes.hp.value": hp.value - deltaHP
};
if ( temp > updates["system.attributes.hp.temp"] ) updates["system.attributes.hp.temp"] = temp;
/**
* A hook event that fires before damage is applied to an actor.
* @param {Actor5e} actor Actor the damage will be applied to.
* @param {number} amount Amount of damage that will be applied.
* @param {object} updates Distinct updates to be performed on the actor.
* @param {DamageApplicationOptions} options Additional damage application options.
* @returns {boolean} Explicitly return `false` to prevent damage application.
* @function dnd5e.preApplyDamage
* @memberof hookEvents
*/
if ( Hooks.call("dnd5e.preApplyDamage", this, amount, updates, options) === false ) return this;
// Delegate damage application to a hook
// TODO: Replace this in the future with a better modifyTokenAttribute function in the core
if ( Hooks.call("modifyTokenAttribute", {
attribute: "attributes.hp",
value: amount,
isDelta: false,
isBar: true
}, updates) === false ) return this;
await this.update(updates);
/**
* A hook event that fires after damage has been applied to an actor.
* @param {Actor5e} actor Actor that has been damaged.
* @param {number} amount Amount of damage that has been applied.
* @param {DamageApplicationOptions} options Additional damage application options.
* @function dnd5e.applyDamage
* @memberof hookEvents
*/
Hooks.callAll("dnd5e.applyDamage", this, amount, options);
return this;
}
/* -------------------------------------------- */
/**
* Calculate the damage that will be applied to this actor.
* @param {DamageDescription[]} damages Damages to calculate.
* @param {DamageApplicationOptions} [options={}] Damage calculation options.
* @returns {DamageSummary|false} New damage descriptions with changes applied, or `false` if the
* calculation was canceled.
*/
calculateDamage(damages, options={}) {
damages = foundry.utils.deepClone(damages);
damages.amount = 0;
damages.temp = 0;
damages.tempMax = 0;
/**
* A hook event that fires before damage amount is calculated for an actor.
* @param {Actor5e} actor The actor being damaged.
* @param {DamageDescription[]} damages Damage descriptions.
* @param {DamageApplicationOptions} options Additional damage application options.
* @returns {boolean} Explicitly return `false` to prevent damage application.
* @function dnd5e.preCalculateDamage
* @memberof hookEvents
*/
if ( Hooks.call("dnd5e.preCalculateDamage", this, damages, options) === false ) return false;
const multiplier = options.multiplier ?? 1;
const treatAs = options.originatingMessage?.flags?.dnd5e?.roll?.type
? options.originatingMessage.flags.dnd5e.roll.type === "healing" ? "healing" : "damage"
: options.only ?? "damage";
const skipped = type => {
if ( type === "maximum" ) return options.only ? options.only !== treatAs : false;
if ( options.only === "damage" ) return type in CONFIG.DND5E.healingTypes;
if ( options.only === "healing" ) return type in CONFIG.DND5E.damageTypes;
return false;
};
const dm = this.system.traits?.dm ?? {};
const rollData = this.getRollData({ deterministic: true });
const modifications = Object.entries(dm.amount ?? {}).reduce((obj, [type, formula]) => {
obj[type] = simplifyBonus(formula, rollData);
return obj;
}, {});
const applyModification = (d, type=d.type) => {
if ( !modifications[type] || this.#changeIsIgnored("modification", type, { options }) ) return;
const originalValue = d.value;
if ( Math.sign(d.value) !== Math.sign(d.value + modifications[type]) ) d.value = 0;
else d.value += modifications[type];
(d.active[type === "ALL" ? "all" : "type"] ??= {}).modification = true;
modifications[type] += originalValue - d.value;
};
damages.forEach(d => {
d.active ??= {};
// Skip damage types with immunity
if ( skipped(d.type) || this.#changeHasEffect("immunity", d, { options }) ) {
d.value = 0;
d.active.multiplier = 0;
return;
}
// Apply damage modification
if ( !CONFIG.DND5E.damageTypes[d.type]?.isPhysical || !d.properties?.size
|| !dm.bypasses?.intersection(d.properties).size ) {
applyModification(d);
if ( !(d.type in CONFIG.DND5E.healingTypes) ) applyModification(d, "ALL");
}
let damageMultiplier = multiplier;
let appliedDamage = d.value * multiplier;
// Apply damage resistance
if ( this.#changeHasEffect("resistance", d, { options }) ) {
damageMultiplier /= 2;
appliedDamage = Math.trunc(appliedDamage / 2);
}
// Apply damage vulnerability
if ( this.#changeHasEffect("vulnerability", d, { options }) ) {
damageMultiplier *= 2;
appliedDamage *= 2;
}
// Negate healing types
if ( (options.invertHealing !== false) && ((d.type === "healing")
|| ((d.type === "maximum") && (treatAs === "healing"))) ) {
damageMultiplier *= -1;
appliedDamage *= -1;
}
d.value = appliedDamage;
d.active.multiplier = (d.active.multiplier ?? 1) * damageMultiplier;
if ( d.type === "temphp" ) damages.temp += d.value;
else if ( d.type === "maximum" ) damages.tempMax += d.value;
else damages.amount += d.value;
});
if ( damages.tempMax < 0 ) damages.amount += damages.tempMax;
damages.amount = Math.trunc(damages.amount);
// Apply damage threshold
if ( ((damages.amount > 0) && (damages.amount < (this.system.attributes?.hp?.dt ?? -Infinity)))
&& !((options.ignore === true) || options.ignore?.threshold) ) {
damages.amount = 0;
damages.forEach(d => {
d.value = 0;
d.active.multiplier = 0;
d.active.threshold = true;
});
}
/**
* A hook event that fires after damage values are calculated for an actor.
* @param {Actor5e} actor The actor being damaged.
* @param {DamageSummary} damages Damage descriptions.
* @param {DamageApplicationOptions} options Additional damage application options.
* @returns {boolean} Explicitly return `false` to prevent damage application.
* @function dnd5e.calculateDamage
* @memberof hookEvents
*/
if ( Hooks.call("dnd5e.calculateDamage", this, damages, options) === false ) return false;
return damages;
}
/* -------------------------------------------- */
/**
* Determine whether a specific type of change to a damage value will have an effect.
* @param {DamageAffectCategory} category Type of change that should be considered.
* @param {DamageDescription|string} damage Damage description to consider or a specific type.
* @param {object} [options={}]
* @param {DamageApplicationOptions} [options.options={}] Damage application options.
* @param {boolean} [options.skipDowngrade=false] Should downgrades be skipped?
* @returns {boolean}
*/
#changeHasEffect(category, damage, { options={}, skipDowngrade=false }={}) {
const config = this.system.traits?.[`d${category.slice(0, 1)}`];
const downgrade = type => options.downgrade === true || options.downgrade?.has?.(type);
const setActive = type => {
if ( damage.active ) {
damage.active[type] ??= {};
damage.active[type][category] = true;
}
return true;
};
const type = typeof damage === "string" ? damage : damage.type;
const isHealingType = type in CONFIG.DND5E.healingTypes;
// If category is resistance, check for downgraded immunities
if ( category === "resistance" ) {
if ( !isHealingType && downgrade("ALL") && this.#changeHasEffect("immunity", "ALL", { skipDowngrade: true }) ) {
return setActive("all");
}
if ( downgrade(type) && this.#changeHasEffect("immunity", type, { skipDowngrade: true }) ) {
return setActive("type");
}
}
// If damage type is physical and bypass present in properties, skip further checks
if ( CONFIG.DND5E.damageTypes[type]?.isPhysical && damage.properties?.size
&& config?.bypasses?.intersection(damage.properties)?.size ) return false;
// If all damage resistance is present and not ignored (healing types are excluded from "All Damage")
if ( !isHealingType
&& !this.#changeIsIgnored(category, "ALL", { options, skipDowngrade })
&& config?.value.has("ALL") ) {
return setActive("all");
}
// If specific type damage resistance is present and not ignored
if ( !this.#changeIsIgnored(category, type, { options, skipDowngrade }) && config?.value.has(type) ) {
return setActive("type");
}
return false;
}
/* -------------------------------------------- */
/**
* Determine whether a specific damage change type should be ignored.
* @param {DamageAffectCategory} category Type of change that should be considered.
* @param {string} type Specific damage type to consider.
* @param {object} [options={}]
* @param {DamageApplicationOptions} [options.options={}] Damage application options.
* @param {boolean} [options.skipDowngrade=false] Should downgrades not be taken into account?
* @returns {boolean}
*/
#changeIsIgnored(category, type, { options={}, skipDowngrade=false }={}) {
const downgrade = type => options.downgrade === true || options.downgrade?.has?.(type);
// All categories are ignored
if ( options.ignore === true ) return true;
// Specific category is ignored, or specific category has this type in its ignore list
if ( (options.ignore?.[category] === true) || (options.ignore?.[category]?.has?.(type)) ) return true;
// When downgrading, always ignore immunities unless `skipDowngrade` option is set
if ( (category === "immunity") && downgrade(type) && !skipDowngrade ) return true;
// When downgrading, resistances should be decided by whether immunity is applied
if ( (category === "resistance") && downgrade(type) && !this.#changeHasEffect("immunity", type) ) return true;
return false;
}
/* -------------------------------------------- */
/**
* Apply a certain amount of temporary hit point, but only if it's more than the actor currently has.
* @param {number} amount An amount of temporary hit points to set
* @returns {Promise<Actor5e>} A Promise which resolves once the temp HP has been applied
*/
async applyTempHP(amount=0) {
amount = parseInt(amount);
const hp = this.system.attributes.hp;
// Update the actor if the new amount is greater than the current
const tmp = parseInt(hp.temp) || 0;