-
Notifications
You must be signed in to change notification settings - Fork 1
/
prime-psionics.mjs
447 lines (401 loc) · 13 KB
/
prime-psionics.mjs
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
import PP_CONFIG from "./module/config.mjs";
import PowerData from "./module/powerData.mjs";
import PowerSheet from "./module/powerSheet.mjs";
import {typePower, moduleID, modulePath, ppText} from "./module/utils.mjs";
Hooks.once("init", () => {
foundry.utils.mergeObject(CONFIG, PP_CONFIG);
Object.assign(CONFIG.Item.dataModels, {
[typePower]: PowerData
});
dnd5e.utils.preLocalize("spellcastingTypes.psionics.progression", {
key: "label"
});
Items.registerSheet(moduleID, PowerSheet, {
types: [typePower],
label: "PrimePsionics.Sheets.Power"
});
loadTemplates([modulePath("templates/details-power.hbs")]);
dnd5e.applications.CompendiumBrowser.TABS.splice(7, 0, {
tab: "primePowers",
label: "TYPES.Item.prime-psionics.powerPl",
svg: modulePath("assets/icons/power.svg"),
documentClass: "Item",
types: [typePower]
});
});
/**
*
* LOCALIZING THE CONFIG OBJECT
*
*/
Hooks.once("i18nInit", () => {
_localizeHelper(CONFIG.PSIONICS);
});
function _localizeHelper(object) {
for (const [key, value] of Object.entries(object)) {
switch (typeof value) {
case "string":
if (value.startsWith("PrimePsionics") || value.startsWith("DND5E"))
object[key] = game.i18n.localize(value);
break;
case "object":
_localizeHelper(object[key]);
break;
}
}
}
/**
*
* INLINE POWER DISPLAY
*
*/
Hooks.on("renderActorSheet5e", (app, html, context) => {
const actor = app.actor;
if (!game.user.isGM && actor.limited) return true;
const newCharacterSheet = ["ActorSheet5eCharacter2", "ActorSheet5eNPC2"].includes(app.constructor.name);
if (context.isCharacter || context.isNPC) {
let powers = context.items.filter((i) => i.type === typePower);
powers = app._filterItems(powers, app._filters.spellbook.properties);
if (!powers.length && !hasPowerPoints(actor)) return true;
const spellbook = context.spellbook;
const specialPowerPrepModes = {
innate: -5
};
const specialPowerPrep = {};
const sections = {
atwill: -20,
innate: -10,
pact: 0.5
};
const cantripOffset =
!!spellbook.find((s) => s?.order === sections.atwill) +
!!spellbook.find((s) => s?.order === sections.innate);
const levelOffset =
cantripOffset + !!spellbook.find((s) => s?.order === sections.pact);
const emptyTen = Array.from({length: 10});
if (spellbook.length) {
// Resolving #5 - bad order for mixed psionics + spellcasting if have spells > spell level.
const manifestLevels = emptyTen.map((e, i) =>
spellbook.findIndex((s) => s?.order === i)
);
let inserted = 0;
for (const index in manifestLevels) {
const i = Number(index);
if ((i === 0) && (manifestLevels[i] === -1)) {
inserted += 1;
// Cantrip special case
spellbook.splice(cantripOffset, 0, undefined);
} else if (manifestLevels[i] + inserted !== i + levelOffset) {
inserted += 1;
spellbook.splice(i + levelOffset, 0, undefined);
}
}
}
const registerSection = (
sl,
p,
label,
{preparationMode = "always", override} = {}
) => {
const aeOverride = foundry.utils.hasProperty(
context.actor.overrides,
`system.spells.spell${p}.override`
);
const sectionData = {
order: p,
label: label,
usesSlots: false,
canCreate: actor.isOwner,
canPrepare: false,
spells: [],
uses: "-",
slots: "-",
override: override || 0,
dataset: {
type: typePower,
level: preparationMode in sections ? 1 : p,
preparationMode
},
prop: sl,
editable: context.editable && !aeOverride
};
let i = p;
if (p >= 0) {
i = p ? p + levelOffset : p + cantripOffset;
spellbook[i] = sectionData;
} else {
specialPowerPrep[i] = sectionData;
}
};
powers.forEach((power) => {
if (power.system.usesPP) power.system.labels.pp = ppText(power.system.ppValue);
foundry.utils.mergeObject(power, {
labels: power.system.labels
});
// Activation
const cost = power.system.activation?.value;
const abbr = {
action: "DND5E.ActionAbbr",
bonus: "DND5E.BonusActionAbbr",
reaction: "DND5E.ReactionAbbr",
minute: "DND5E.TimeMinuteAbbr",
hour: "DND5E.TimeHourAbbr",
day: "DND5E.TimeDayAbbr"
}[power.system.activation.type];
const itemContext = newCharacterSheet
? {
activation:
cost && abbr
? `${cost}${game.i18n.localize(abbr)}`
: power.labels.activation,
preparation: {applicable: false}
}
: {
toggleTitle: CONFIG.DND5E.spellPreparationModes.always,
toggleClass: "fixed"
};
if (newCharacterSheet) {
// Range
const units = power.system.range?.units;
if (units && (units !== "none")) {
if (units in CONFIG.DND5E.movementUnits) {
itemContext.range = {
distance: true,
value: power.system.range.value,
unit: game.i18n.localize(`DND5E.Dist${units.capitalize()}Abbr`)
};
} else itemContext.range = {distance: false};
}
// To Hit
const toHit = parseInt(power.labels.modifier);
if (power.hasAttack && !isNaN(toHit)) {
itemContext.toHit = {
sign: Math.sign(toHit) < 0 ? "-" : "+",
abs: Math.abs(toHit)
};
}
}
foundry.utils.mergeObject(context.itemContext[power.id], itemContext);
const mode = power.system.preparation.mode;
const p = power.system.level || 0;
const pl = `spell${p}`;
let index = p ? p + levelOffset : p + cantripOffset;
if (mode in specialPowerPrepModes) {
index = specialPowerPrepModes[mode];
if (!specialPowerPrep[index]) {
registerSection(
mode,
index,
CONFIG.PSIONICS.powerPreparationModes[mode],
{preparationMode: mode}
);
}
specialPowerPrep[index].spells.push(power);
} else {
if (!spellbook[index]) {
registerSection(pl, p, CONFIG.PSIONICS.powerLevels[p], {
preparationMode: power.system.preparation.mode
});
}
// Add the power to the relevant heading
spellbook[index].spells.push(power);
}
});
for (const i in spellbook) {
if (spellbook[i] === undefined) delete spellbook[i];
}
spellbook.push(...Object.values(specialPowerPrep));
spellbook.sort((a, b) => a.order - b.order);
const spellList = newCharacterSheet
? html.find(".spells")
: html.find(".spellbook");
const spellListTemplate = newCharacterSheet
? "systems/dnd5e/templates/actors/tabs/creature-spells.hbs"
: "systems/dnd5e/templates/actors/parts/actor-spellbook.hbs";
renderTemplate(spellListTemplate, context).then((partial) => {
spellList.html(partial);
if (newCharacterSheet) {
const schoolSlots = spellList.find(".item-detail.item-school");
/** @type {Array<string>} */
const disciplines = Object.values(CONFIG.PSIONICS.disciplines).map(
(d) => d.label
);
for (const div of schoolSlots) {
if (disciplines.includes(div.dataset.tooltip)) {
div.innerHTML = `<dnd5e-icon src="modules/prime-psionics/assets/icons/${div.dataset.tooltip.toLowerCase()}.svg"></dnd5e-icon>`;
}
}
}
let pp = app.actor.getFlag(moduleID, "pp");
if (pp) {
const ppContext = {
pp: pp.value,
ppMax: pp.max,
limit: app.actor.getFlag(moduleID, "manifestLimit")
};
const ppTemplate = newCharacterSheet
? "/modules/prime-psionics/templates/pp-partial-2.hbs"
: "/modules/prime-psionics/templates/pp-partial.hbs";
renderTemplate(ppTemplate, ppContext).then((powerHeader) => {
const ppTarget = newCharacterSheet
? "dnd5e-inventory"
: ".inventory-list";
spellList.find(ppTarget).prepend(powerHeader);
});
}
app.activateListeners(spellList);
});
if (app.constructor.name === "ActorSheet5eNPC") {
const features = html.find("dnd5e-inventory").first();
const inventory = features.find("ol").last();
for (const i of inventory.find("li")) {
const item = actor.items.get(i.dataset.itemId);
if (item.type === typePower) i.remove();
}
}
} else return true;
});
/**
* Determines if an actor has exertion points
* @param {object} actor The character
* @returns {boolean} Whether or not the character has an exertion pool
*/
function hasPowerPoints(actor) {
for (const cls of Object.values(actor.classes)) {
if (cls.spellcasting.type === "psionics") return true;
}
return false;
}
/**
*
* CALCULATE MAX PSI POINTS
*
*/
Hooks.on(
"dnd5e.computePsionicsProgression",
(progression, actor, cls, spellcasting, count) => {
if (!("psionics" in progression)) progression.psionics = 0;
const prog =
CONFIG.DND5E.spellcastingTypes.psionics.progression[
spellcasting.progression
];
if (!prog) return;
progression.psionics += Math.floor(spellcasting.levels / (prog.divisor ?? 1));
// Single-classed, non-full progression rounds up, rather than down, except at first level for half manifesters.
if ((count === 1) && (prog.divisor > 1) && progression.psionics) {
progression.psionics = Math.ceil(spellcasting.levels / prog.divisor);
}
updateManifester(actor, progression.psionics);
}
);
Hooks.on("dnd5e.preparePsionicsSlots", (spells, actor, progression) => {
if ((actor.type !== "npc") || !actor.items.some((i) => i.type === typePower))
return;
const level = foundry.utils.getProperty(actor, "system.details.spellLevel");
updateManifester(actor, level);
});
/**
* In-memory update to the manifester
* @param {Actor} actor
* @param {number} manifesterLevel
* @returns
*/
function updateManifester(actor, manifesterLevel) {
const limit = Math.ceil(Math.min(manifesterLevel, 10) / 2) * 2;
const updates = {
manifestLimit: limit,
pp: {
max: CONFIG.PSIONICS.ppProgression[manifesterLevel]
}
};
if (actor === undefined) return;
const pp = actor.getFlag(moduleID, "pp");
if (pp === undefined)
updates.pp.value = CONFIG.PSIONICS.ppProgression[manifesterLevel];
else if (typeof pp === "number") updates.pp.value = pp; // migration
foundry.utils.mergeObject(actor.flags, {
[moduleID]: updates
});
}
/**
*
* POWER POINT RESET ON LR
*
*/
Hooks.on("dnd5e.preRestCompleted", (actor, result) => {
if (!result.longRest) return true;
const pp = actor.getFlag(moduleID, "pp");
if (!pp) return;
result.updateData["flags.prime-psionics.pp.value"] = pp.max;
});
/**
*
* SPELLCASTING TABLE
*
*/
Hooks.on(
"dnd5e.buildPsionicsSpellcastingTable",
(table, item, spellcasting) => {
table.headers = [
[
{content: game.i18n.localize("PrimePsionics.PP")},
{content: game.i18n.localize("PrimePsionics.PsiLimit")}
]
];
table.cols = [{class: "spellcasting", span: 2}];
for (const level of Array.fromRange(CONFIG.DND5E.maxLevel, 1)) {
const progression = {psionics: 0};
spellcasting.levels = level;
globalThis.dnd5e.documents.Actor5e.computeClassProgression(
progression,
item,
{spellcasting}
);
const pp = CONFIG.PSIONICS.ppProgression[progression.psionics] || "—";
const limit =
Math.ceil(Math.min(progression.psionics, 10) / 2) * 2 || "—";
table.rows.push([
{class: "spell-slots", content: `${pp}`},
{class: "spell-slots", content: `${limit}`}
]);
}
}
);
/**
*
* Useful Defaults
*
*/
Hooks.on("preCreateItem", (item, data, context, userId) => {
if (item.type !== typePower) return;
const bookSource = foundry.utils.getProperty(data, "system.source.book");
if (!bookSource) item.updateSource({"system.source": {
book: "Psion's Primer",
license: "DMsGuild CCA"
}});
});
Hooks.on("preUpdateItem", (item, changes, context, userId) => {
if (item.type !== typePower) return;
const activityChanges = foundry.utils.getProperty(changes, "system.activities");
if (!activityChanges) return;
const activities = foundry.utils.getProperty(item, "system.activities");
for (const [key, activityData] of Object.entries(activityChanges)) {
if (!activities.get(key) && !key.startsWith("-=")) {
// make changes to activity
if (item.system.level > 0) {
activityData.consumption.targets.push({
type: "psiPoints",
value: "1",
scaling: {
mode: "amount"
}
});
activityData.consumption.scaling.allowed = true;
activityData.consumption.scaling.max = "1 + @flags.prime-psionics.manifestLimit - @activity.consumption.targets.0.value";
}
else {
// Talents
}
}
}
});