fvtt-imperium5/modules/imperium5-utility.js

541 lines
17 KiB
JavaScript
Raw Normal View History

2022-03-13 16:17:04 +01:00
/* -------------------------------------------- */
import { Imperium5Combat } from "./imperium5-combat.js";
import { Imperium5Commands } from "./imperium5-commands.js";
/* -------------------------------------------- */
const __level2Dice = ["d0", "d4", "d6", "d8", "d10", "d12"];
const __name2DiceValue = { "0": 0, "d0": 0, "d4": 4, "d6": 6, "d8": 8, "d10": 10, "d12": 12 }
/* -------------------------------------------- */
export class Imperium5Utility {
/* -------------------------------------------- */
static async init() {
2022-03-19 09:30:00 +01:00
Hooks.on('renderChatLog', (log, html, data) => Imperium5Utility.chatListeners(html));
2022-10-19 17:30:47 +02:00
2022-03-13 16:17:04 +01:00
Hooks.on("getCombatTrackerEntryContext", (html, options) => {
2022-03-19 09:30:00 +01:00
Imperium5Utility.pushInitiativeOptions(html, options);
})
2022-03-13 16:17:04 +01:00
this.rollDataStore = {}
this.defenderStore = {}
2022-03-19 09:30:00 +01:00
this.diceList = []
Imperium5Commands.init();
2022-03-13 16:17:04 +01:00
Handlebars.registerHelper('count', function (list) {
return list.length;
})
Handlebars.registerHelper('includes', function (array, val) {
return array.includes(val);
})
Handlebars.registerHelper('upper', function (text) {
return text.toUpperCase();
})
Handlebars.registerHelper('lower', function (text) {
return text.toLowerCase()
})
Handlebars.registerHelper('upperFirst', function (text) {
if (typeof text !== 'string') return text
return text.charAt(0).toUpperCase() + text.slice(1)
})
Handlebars.registerHelper('notEmpty', function (list) {
return list.length > 0;
})
Handlebars.registerHelper('mul', function (a, b) {
return parseInt(a) * parseInt(b);
})
2022-03-19 09:30:00 +01:00
Handlebars.registerHelper('exists', function (val) {
return val != null && val != undefined;
})
2022-03-13 16:17:04 +01:00
}
/* -------------------------------------------- */
static pushInitiativeOptions(html, options) {
}
/* -------------------------------------------- */
static async ready() {
2022-03-19 09:30:00 +01:00
2022-03-13 16:17:04 +01:00
}
/* -------------------------------------------- */
static async addItemDropToActor(actor, item) {
actor.preprocessItem("none", item, false)
let chatData = {
user: game.user.id,
rollMode: game.settings.get("core", "rollMode"),
whisper: [game.user.id].concat(ChatMessage.getWhisperRecipients('GM')),
content: `<div>The item ${item.name} has been dropped on the actor ${actor.name}</div`
}
ChatMessage.create(chatData);
}
/* -------------------------------------------- */
static async loadCompendiumData(compendium) {
const pack = game.packs.get(compendium);
return await pack?.getDocuments() ?? [];
}
/* -------------------------------------------- */
static async loadCompendium(compendium, filter = item => true) {
2022-03-19 09:30:00 +01:00
let compendiumData = await Imperium5Utility.loadCompendiumData(compendium);
2022-03-13 16:17:04 +01:00
return compendiumData.filter(filter);
}
/* -------------------------------------------- */
static getOptionsStatusList() {
return this.optionsStatusList;
}
/* -------------------------------------------- */
static async chatListeners(html) {
2022-10-20 23:59:31 +02:00
html.on("click", '.button-apply-paradigme', event => {
let paraKey = $(event.currentTarget).data("para-key")
let rollData = this.getRollDataFromMessage(event)
rollData.previousMessageId = Imperium5Utility.findChatMessageId(event.currentTarget)
this.applyParadigme(rollData, paraKey)
2022-03-19 09:30:00 +01:00
})
2022-10-20 23:59:31 +02:00
2022-03-13 16:17:04 +01:00
}
/* -------------------------------------------- */
static async preloadHandlebarsTemplates() {
const templatePaths = [
2022-03-19 09:30:00 +01:00
'systems/fvtt-imperium5/templates/editor-notes-gm.html',
'systems/fvtt-imperium5/templates/actor-partial-ames.html',
'systems/fvtt-imperium5/templates/actor-partial-paradigmes.html',
'systems/fvtt-imperium5/templates/partial-item-description.html',
2022-03-13 16:17:04 +01:00
]
return loadTemplates(templatePaths);
}
/* -------------------------------------------- */
static async getEffectFromCompendium(effectName) {
effectName = effectName.toLowerCase()
let effect = game.items.contents.find(item => item.type == 'effect' && item.name.toLowerCase() == effectName)
if (!effect) {
2022-10-19 17:30:47 +02:00
let effects = await this.loadCompendium('fvtt-imperium5.effect', item => item.name.toLowerCase() == effectName)
2022-03-13 16:17:04 +01:00
let objs = effects.map(i => i.toObject())
effect = objs[0]
} else {
effect = duplicate(effect);
}
console.log("Effect", effect)
return effect
}
/* -------------------------------------------- */
static removeChatMessageId(messageId) {
if (messageId) {
game.messages.get(messageId)?.delete();
}
}
static findChatMessageId(current) {
2022-03-19 09:30:00 +01:00
return Imperium5Utility.getChatMessageId(Imperium5Utility.findChatMessage(current))
2022-03-13 16:17:04 +01:00
}
static getChatMessageId(node) {
2022-03-19 09:30:00 +01:00
return node?.attributes.getNamedItem('data-message-id')?.value
2022-03-13 16:17:04 +01:00
}
static findChatMessage(current) {
2022-03-19 09:30:00 +01:00
return Imperium5Utility.findNodeMatching(current, it => it.classList.contains('chat-message') && it.attributes.getNamedItem('data-message-id'))
2022-03-13 16:17:04 +01:00
}
static findNodeMatching(current, predicate) {
if (current) {
if (predicate(current)) {
return current;
}
2022-03-19 09:30:00 +01:00
return Imperium5Utility.findNodeMatching(current.parentElement, predicate)
2022-03-13 16:17:04 +01:00
}
return undefined;
}
2022-10-20 23:59:31 +02:00
/* -------------------------------------------- */
static getRollDataFromMessage(event) {
let messageId = Imperium5Utility.findChatMessageId(event.currentTarget)
let message = game.messages.get(messageId)
return message.getFlag("world", "imperium5-roll-data")
}
2022-03-13 16:17:04 +01:00
/* -------------------------------------------- */
static createDirectOptionList(min, max) {
let options = {};
for (let i = min; i <= max; i++) {
options[`${i}`] = `${i}`;
}
return options;
}
/* -------------------------------------------- */
static buildListOptions(min, max) {
let options = ""
for (let i = min; i <= max; i++) {
options += `<option value="${i}">${i}</option>`
}
return options;
}
/* -------------------------------------------- */
static getTarget() {
if (game.user.targets && game.user.targets.size == 1) {
for (let target of game.user.targets) {
return target;
}
}
return undefined;
}
/* -------------------------------------------- */
static updateRollData(rollData) {
let id = rollData.rollId;
let oldRollData = this.rollDataStore[id] || {};
let newRollData = mergeObject(oldRollData, rollData);
this.rollDataStore[id] = newRollData;
}
/* -------------------------------------------- */
static saveRollData(rollData) {
2022-10-19 17:30:47 +02:00
game.socket.emit("system.fvtt-imperium5", {
2022-03-13 16:17:04 +01:00
name: "msg_update_roll", data: rollData
}); // Notify all other clients of the roll
this.updateRollData(rollData);
}
/* -------------------------------------------- */
static getRollData(id) {
return this.rollDataStore[id];
}
/* -------------------------------------------- */
static async onSocketMesssage(msg) {
console.log("SOCKET MESSAGE", msg.name)
if (msg.name == "msg_update_roll") {
this.updateRollData(msg.data)
}
}
/* -------------------------------------------- */
static chatDataSetup(content, modeOverride, isRoll = false, forceWhisper) {
let chatData = {
user: game.user.id,
rollMode: modeOverride || game.settings.get("core", "rollMode"),
content: content
};
2022-03-19 09:30:00 +01:00
if (["gmroll", "blindroll"].includes(chatData.rollMode)) chatData["whisper"] = ChatMessage.getWhisperRecipients("GM").map(u => u.id)
if (chatData.rollMode === "blindroll") chatData["blind"] = true
else if (chatData.rollMode === "selfroll") chatData["whisper"] = [game.user]
2022-03-13 16:17:04 +01:00
if (forceWhisper) { // Final force !
2022-03-19 09:30:00 +01:00
chatData["speaker"] = ChatMessage.getSpeaker()
chatData["whisper"] = ChatMessage.getWhisperRecipients(forceWhisper)
2022-03-13 16:17:04 +01:00
}
return chatData;
}
/* -------------------------------------------- */
static async loadCompendiumData(compendium) {
const pack = game.packs.get(compendium);
return await pack?.getDocuments() ?? [];
}
/* -------------------------------------------- */
static async loadCompendium(compendium, filter = item => true) {
let compendiumData = await this.loadCompendiumData(compendium);
//console.log("Compendium", compendiumData);
return compendiumData.filter(filter);
}
/* -------------------------------------------- */
static async showDiceSoNice(roll, rollMode) {
if (game.modules.get("dice-so-nice")?.active) {
if (game.dice3d) {
let whisper = null;
let blind = false;
rollMode = rollMode ?? game.settings.get("core", "rollMode");
switch (rollMode) {
case "blindroll": //GM only
blind = true;
case "gmroll": //GM + rolling player
whisper = this.getUsers(user => user.isGM);
break;
case "roll": //everybody
whisper = this.getUsers(user => user.active);
break;
case "selfroll":
whisper = [game.user.id];
break;
}
2022-03-19 09:30:00 +01:00
await game.dice3d.showForRoll(roll, game.user, true, whisper, blind)
2022-03-13 16:17:04 +01:00
}
}
}
/* -------------------------------------------- */
2022-10-19 17:30:47 +02:00
static computeDiceReserve(rollData) {
let capaDice = 0
if (rollData.usedCapacite != "none") {
let capa = rollData.capacites.find(c => c._id == rollData.usedCapacite)
capaDice = capa.system.aide
2022-03-13 16:17:04 +01:00
}
2022-10-19 17:30:47 +02:00
let val = rollData.ame.value + capaDice + ((rollData.useKarma) ? 1 : 0) + ((rollData.useArchetype) ? 1 : 0) + ((rollData.useAide) ? 1 : 0) + rollData.ameMalus
return Math.max(val, 0)
}
2022-10-20 23:59:31 +02:00
/* -------------------------------------------- */
static computeReussites(rollData) {
let myRoll = rollData.roll
rollData.successPC = myRoll.terms[0].results.filter(res => res.result <= rollData.seuil).length
rollData.successGM = myRoll.terms[4].results.filter(res => res.result <= rollData.seuil).length
rollData.bonPresage = myRoll.terms[2].results[0].result == 1
rollData.mauvaisPresage = myRoll.terms[2].results[0].result == 8
rollData.nbUnitesNarration = Math.max( rollData.successPC-1, 0)
}
2022-10-19 17:30:47 +02:00
/* -------------------------------------------- */
static async rollImperium5(rollData) {
2022-03-13 16:17:04 +01:00
2022-10-19 17:30:47 +02:00
// Karma management
let actor = game.actors.get(rollData.actorId)
rollData.nbKarma = 0
if ( rollData.useKarma ) {
actor.incDecKarma(-1)
rollData.nbKarma++
}
if ( rollData.usedCapacite != "none" ) {
actor.incDecKarma(-1)
rollData.nbKarma++
2022-03-13 16:17:04 +01:00
}
2022-10-19 17:30:47 +02:00
let nbAmeDice = this.computeDiceReserve( rollData )
let diceFormula = `${nbAmeDice}d8[green] + 1d8[blue] + ${rollData.realiteDice}d8[red]`
let humanFormula = `${nbAmeDice}d8, 1d8, ${rollData.realiteDice}d8`
2022-03-13 16:17:04 +01:00
// Performs roll
2022-10-19 17:30:47 +02:00
let myRoll = rollData.roll
2022-03-13 16:17:04 +01:00
if (!myRoll) { // New rolls only of no rerolls
2022-10-19 17:30:47 +02:00
myRoll = new Roll(diceFormula).roll({ async: false })
await this.showDiceSoNice(myRoll, game.settings.get("core", "rollMode"))
2022-03-13 16:17:04 +01:00
rollData.roll = myRoll
2022-10-19 17:30:47 +02:00
rollData.diceFormula = diceFormula
rollData.humanFormula = humanFormula
2022-03-13 16:17:04 +01:00
}
2022-10-19 17:30:47 +02:00
// Calcul réussites
2022-10-20 23:59:31 +02:00
this.computeReussites(rollData)
2022-03-13 16:17:04 +01:00
2022-10-19 17:30:47 +02:00
let msg = await this.createChatWithRollMode(rollData.alias, {
2022-03-19 09:30:00 +01:00
content: await renderTemplate(`systems/fvtt-imperium5/templates/chat-generic-result.html`, rollData)
2022-10-19 17:30:47 +02:00
})
2022-10-20 23:59:31 +02:00
msg.setFlag("world", "imperium5-roll-data", rollData)
}
/* ------------------------- ------------------- */
static async processParadigmeRoll(rollData) {
this.computeReussites(rollData)
rollData.paradigmes = []
let msg = await this.createChatWithRollMode(rollData.alias, {
content: await renderTemplate(`systems/fvtt-imperium5/templates/chat-generic-result.html`, rollData)
})
msg.setFlag("world", "imperium5-roll-data", rollData)
this.removeChatMessageId(rollData.previousMessageId)
2022-03-13 16:17:04 +01:00
}
/* ------------------------- ------------------- */
static async updateRoll(rollData) {
2022-03-19 09:30:00 +01:00
let diceResults = rollData.diceResults
let sortedRoll = []
2022-03-13 16:17:04 +01:00
for (let i = 0; i < 10; i++) {
sortedRoll[i] = 0;
}
for (let dice of diceResults) {
2022-03-19 09:30:00 +01:00
sortedRoll[dice.result]++
2022-03-13 16:17:04 +01:00
}
let index = 0;
let bestRoll = 0;
for (let i = 0; i < 10; i++) {
if (sortedRoll[i] > bestRoll) {
2022-03-19 09:30:00 +01:00
bestRoll = sortedRoll[i]
index = i
2022-03-13 16:17:04 +01:00
}
}
let bestScore = (bestRoll * 10) + index
rollData.bestScore = bestScore
rollData.finalScore = bestScore + rollData.negativeModifier + rollData.positiveModifier
this.saveRollData(rollData)
this.createChatWithRollMode(rollData.alias, {
content: await renderTemplate(`systems/fvtt-weapons-of-the-gods/templates/chat-generic-result.html`, rollData)
});
}
/* ------------------------- ------------------- */
static async rerollDice(actorId, diceIndex = -1) {
2022-03-19 09:30:00 +01:00
let actor = game.actors.get(actorId)
let rollData = actor.getRollData()
2022-03-13 16:17:04 +01:00
}
/* -------------------------------------------- */
static getUsers(filter) {
2022-03-19 09:30:00 +01:00
return game.users.filter(filter).map(user => user.data._id)
2022-03-13 16:17:04 +01:00
}
/* -------------------------------------------- */
static getWhisperRecipients(rollMode, name) {
switch (rollMode) {
2022-03-19 09:30:00 +01:00
case "blindroll": return this.getUsers(user => user.isGM)
case "gmroll": return this.getWhisperRecipientsAndGMs(name)
case "selfroll": return [game.user.id]
2022-03-13 16:17:04 +01:00
}
return undefined;
}
/* -------------------------------------------- */
static getWhisperRecipientsAndGMs(name) {
let recep1 = ChatMessage.getWhisperRecipients(name) || [];
return recep1.concat(ChatMessage.getWhisperRecipients('GM'));
}
/* -------------------------------------------- */
static blindMessageToGM(chatOptions) {
let chatGM = duplicate(chatOptions);
chatGM.whisper = this.getUsers(user => user.isGM);
2022-03-19 09:30:00 +01:00
chatGM.content = "Message en aveugle à " + game.user.name + "<br>" + chatOptions.content;
2022-03-13 16:17:04 +01:00
console.log("blindMessageToGM", chatGM);
game.socket.emit("system.fvtt-pegasus-rgp", { msg: "msg_gm_chat_message", data: chatGM });
}
/* -------------------------------------------- */
static async searchItem(dataItem) {
let item
if (dataItem.pack) {
item = await fromUuid("Compendium." + dataItem.pack + "." + dataItem.id)
} else {
item = game.items.get(dataItem.id)
2022-10-19 17:30:47 +02:00
}
2022-03-13 16:17:04 +01:00
return item
}
/* -------------------------------------------- */
static split3Columns(data) {
let array = [[], [], []];
if (data == undefined) return array;
let col = 0;
for (let key in data) {
let keyword = data[key];
keyword.key = key; // Self-reference
array[col].push(keyword);
col++;
if (col == 3) col = 0;
}
return array;
}
/* -------------------------------------------- */
static createChatMessage(name, rollMode, chatOptions) {
switch (rollMode) {
case "blindroll": // GM only
if (!game.user.isGM) {
2022-03-19 09:30:00 +01:00
this.blindMessageToGM(chatOptions)
2022-03-13 16:17:04 +01:00
chatOptions.whisper = [game.user.id];
2022-03-19 09:30:00 +01:00
chatOptions.content = "Message only to the GM"
2022-03-13 16:17:04 +01:00
}
else {
2022-03-19 09:30:00 +01:00
chatOptions.whisper = this.getUsers(user => user.isGM)
2022-03-13 16:17:04 +01:00
}
break;
default:
2022-03-19 09:30:00 +01:00
chatOptions.whisper = this.getWhisperRecipients(rollMode, name)
2022-03-13 16:17:04 +01:00
break;
}
chatOptions.alias = chatOptions.alias || name;
2022-10-19 17:30:47 +02:00
return ChatMessage.create(chatOptions)
2022-03-13 16:17:04 +01:00
}
/* -------------------------------------------- */
static getBasicRollData() {
let rollData = {
rollId: randomID(16),
rollMode: game.settings.get("core", "rollMode"),
2022-10-19 17:30:47 +02:00
realiteDice: 0,
ameMalus: 0,
useArchetype: false,
useAide: false,
useKarma: false,
2022-10-20 23:59:31 +02:00
usedCapacite: "none",
seuil: 2
2022-03-13 16:17:04 +01:00
}
2022-03-19 09:30:00 +01:00
Imperium5Utility.updateWithTarget(rollData)
2022-03-13 16:17:04 +01:00
return rollData
}
2022-10-20 23:59:31 +02:00
/* -------------------------------------------- */
static applyParadigme(rollData, paraKey) {
let actor = game.actors.get(rollData.actorId)
let para = actor.system.paradigmes[paraKey]
rollData.seuil = para.value
rollData.usedParadigme = para.label
actor.setParadigmeUsed(paraKey)
this.processParadigmeRoll(rollData)
}
2022-03-13 16:17:04 +01:00
/* -------------------------------------------- */
static updateWithTarget(rollData) {
let objectDefender
2022-03-19 09:30:00 +01:00
let target = Imperium5Utility.getTarget()
2022-03-13 16:17:04 +01:00
if (target) {
let defenderActor = game.actors.get(target.data.actorId)
2022-10-19 17:30:47 +02:00
objectDefender = defenderActor
2022-03-13 16:17:04 +01:00
objectDefender = mergeObject(objectDefender, target.data.actorData)
rollData.defender = objectDefender
rollData.attackerId = this.id
2022-10-19 17:30:47 +02:00
rollData.defenderId = objectDefender.id
2022-03-13 16:17:04 +01:00
}
}
/* -------------------------------------------- */
static createChatWithRollMode(name, chatOptions) {
2022-10-19 17:30:47 +02:00
return this.createChatMessage(name, game.settings.get("core", "rollMode"), chatOptions)
2022-03-13 16:17:04 +01:00
}
/* -------------------------------------------- */
static async confirmDelete(actorSheet, li) {
let itemId = li.data("item-id");
2022-03-19 09:30:00 +01:00
let msgTxt = "<p>Etes vous certain de vouloir supprimer cet objet ?";
2022-03-13 16:17:04 +01:00
let buttons = {
delete: {
icon: '<i class="fas fa-check"></i>',
2022-03-19 09:30:00 +01:00
label: "Oui",
2022-03-13 16:17:04 +01:00
callback: () => {
actorSheet.actor.deleteEmbeddedDocuments("Item", [itemId]);
li.slideUp(200, () => actorSheet.render(false));
}
},
cancel: {
icon: '<i class="fas fa-times"></i>',
2022-03-19 09:30:00 +01:00
label: "Annuler"
2022-03-13 16:17:04 +01:00
}
}
msgTxt += "</p>";
let d = new Dialog({
2022-03-19 09:30:00 +01:00
title: "Confirmer la suppression",
2022-03-13 16:17:04 +01:00
content: msgTxt,
buttons: buttons,
default: "cancel"
});
d.render(true);
}
}