fvtt-les-heritiers/modules/heritiers-utility.js

665 lines
22 KiB
JavaScript

/* -------------------------------------------- */
import { HeritiersCombat } from "./heritiers-combat.js";
import { HeritiersCommands } from "./heritiers-commands.js";
/* -------------------------------------------- */
export class HeritiersUtility {
/* -------------------------------------------- */
static async init() {
Hooks.on('renderChatLog', (log, html, data) => HeritiersUtility.chatListeners(html))
Hooks.on("getChatLogEntryContext", (html, options) => HeritiersUtility.chatRollMenu(html, options))
this.rollDataStore = {}
this.defenderStore = {}
HeritiersCommands.init()
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);
})
}
/* -------------------------------------------- */
static sortByName(table) {
return table.sort(function (a, b) {
return a.name.localeCompare(b.name);
})
}
/* -------------------------------------------- */
static sortArrayObjectsByName(myArray) {
myArray.sort((a, b) => {
return a.name.localeCompare(b.name);
})
}
/* -------------------------------------------- */
static getSkills() {
return this.skills
}
/* -------------------------------------------- */
static async ready() {
const skills = await HeritiersUtility.loadCompendium("fvtt-les-heritiers.competences")
this.skills = skills.map(i => i.toObject())
}
/* -------------------------------------------- */
static async loadCompendiumData(compendium) {
const pack = game.packs.get(compendium);
return await pack?.getDocuments() ?? [];
}
/* -------------------------------------------- */
static async loadCompendium(compendium, filter = item => true) {
let compendiumData = await HeritiersUtility.loadCompendiumData(compendium);
return compendiumData.filter(filter);
}
/* -------------------------------------------- */
static getOptionsStatusList() {
return this.optionsStatusList;
}
/* -------------------------------------------- */
static async chatListeners(html) {
html.on("click", '.predilection-reroll', async event => {
let predIdx = $(event.currentTarget).data("predilection-index")
let messageId = HeritiersUtility.findChatMessageId(event.currentTarget)
let message = game.messages.get(messageId)
let rollData = message.getFlag("world", "heritiers-roll")
let actor = this.getActorFromRollData(rollData)
await actor.setPredilectionUsed(rollData.competence._id, predIdx)
rollData.competence = duplicate(actor.getCompetence(rollData.competence._id))
HeritiersUtility.rollHeritiers(rollData)
})
html.on("click", '.roll-chat-degat', async event => {
let messageId = HeritiersUtility.findChatMessageId(event.currentTarget)
let message = game.messages.get(messageId)
let rollData = message.getFlag("world", "heritiers-roll")
let actor = this.getActorFromRollData(rollData)
actor.rollArmeDegats(rollData.arme._id, rollData.targetVigueur)
})
}
/* -------------------------------------------- */
static async preloadHandlebarsTemplates() {
const templatePaths = [
'systems/fvtt-les-heritiers/templates/editor-notes-gm.html',
'systems/fvtt-les-heritiers/templates/partial-item-header.html',
'systems/fvtt-les-heritiers/templates/partial-item-description.html',
'systems/fvtt-les-heritiers/templates/partial-item-nav.html',
'systems/fvtt-les-heritiers/templates/partial-utile-skills.html',
'systems/fvtt-les-heritiers/templates/partial-list-niveau.html'
]
return loadTemplates(templatePaths);
}
/* -------------------------------------------- */
static removeChatMessageId(messageId) {
if (messageId) {
game.messages.get(messageId)?.delete();
}
}
static findChatMessageId(current) {
return HeritiersUtility.getChatMessageId(HeritiersUtility.findChatMessage(current));
}
static getChatMessageId(node) {
return node?.attributes.getNamedItem('data-message-id')?.value;
}
static findChatMessage(current) {
return HeritiersUtility.findNodeMatching(current, it => it.classList.contains('chat-message') && it.attributes.getNamedItem('data-message-id'))
}
static findNodeMatching(current, predicate) {
if (current) {
if (predicate(current)) {
return current;
}
return HeritiersUtility.findNodeMatching(current.parentElement, predicate);
}
return undefined;
}
/* -------------------------------------------- */
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 getActorFromRollData(rollData) {
let actor = game.actors.get(rollData.actorId)
if (rollData.tokenId) {
let token = canvas.tokens.placeables.find(t => t.id == rollData.tokenId)
if (token) {
actor = token.actor
}
}
return actor
}
/* -------------------------------------------- */
static updateRollData(rollData) {
let id = rollData.rollId;
let oldRollData = this.rollDataStore[id] || {};
let newRollData = mergeObject(oldRollData, rollData);
this.rollDataStore[id] = newRollData;
}
/* -------------------------------------------- */
static saveRollData(rollData) {
game.socket.emit("system.fvtt-les-heritiers", {
name: "msg_update_roll", data: rollData
}); // Notify all other clients of the roll
this.updateRollData(rollData);
}
/* -------------------------------------------- */
static getRollData(id) {
return this.rollDataStore[id];
}
/* -------------------------------------------- */
static onSocketMesssage(msg) {
//console.log("SOCKET MESSAGE", msg.name, game.user.character.id, msg.data.defenderId);
if (msg.name == "msg_update_defense_state") {
this.updateDefenseState(msg.data.defenderId, msg.data.rollId);
}
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
};
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];
if (forceWhisper) { // Final force !
chatData["speaker"] = ChatMessage.getSpeaker();
chatData["whisper"] = ChatMessage.getWhisperRecipients(forceWhisper);
}
return chatData;
}
/* -------------------------------------------- */
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;
}
await game.dice3d.showForRoll(roll, game.user, true, whisper, blind);
}
}
}
/* -------------------------------------------- */
static computeMonnaieDetails(valueSC) {
let po = Math.floor(valueSC / 400)
let pa = Math.floor((valueSC - (po * 400)) / 20)
let sc = valueSC - (po * 400) - (pa * 20)
return {
po: po, pa: pa, sc: sc, valueSC: valueSC
}
}
/* -------------------------------------------- */
static incDecHeritage() {
}
/* -------------------------------------------- */
static computeResult(actor, rollData) {
let isTricherieHeritage = rollData.useHeritage || rollData.useTricherie
rollData.marge = 0
if (isTricherieHeritage) {
let resTab = [ rollData.roll.terms[0].results[0].result, rollData.roll.terms[0].results[1].result, rollData.roll.terms[0].results[2].result ]
rollData.diceResult = resTab[0] + "," + resTab[1] + "," + resTab[2]
let subResult = Math.max(Math.max(resTab[0], resTab[1]), resTab[2])
if (resTab[1] == 1) { resTab[1] -= 4 }
if (resTab[2] == 1) { resTab[2] -= 6 }
if (resTab[2] == 2) { resTab[2] -= 7 }
rollData.finalResult = rollData.roll.total - subResult + Math.max(Math.max(resTab[0], resTab[1]), resTab[2])
// Gestion des résultats spéciaux
resTab = resTab.sort()
if ((resTab[0] == resTab[1]) && (resTab[1] == resTab[2])) {
rollData.marge = 7
rollData.isSuccess = true
rollData.isCriticalSuccess = true
rollData.isBrelan = true
}
if ((resTab[0] + 1 == resTab[1]) && (resTab[1] + 1 == resTab[2])) {
rollData.marge = 7
rollData.isSuccess = true
rollData.isCriticalSuccess = true
rollData.isSuite = true
}
if (rollData.useTricherie) {
actor.incDecTricherie(-1)
}
if (rollData.useHeritage) {
this.incDecHeritage()
}
} else {
rollData.finalResult = rollData.roll.total
if (rollData.mainDice.includes("d10")) {
if (rollData.diceResult == 1) {
rollData.finalResult -= 3 + rollData.diceResult // substract 3 and the 1 value that has been added
}
}
if (rollData.mainDice.includes("d12")) {
if (rollData.diceResult == 1 || rollData.diceResult == 2) {
rollData.finalResult -= 5 + rollData.diceResult // Remove also the dice result has it has been added already
}
}
}
//rollData.finalResult = Math.max(rollData.finalResult, 0)
//console.log("Result : ", rollData)
if (rollData.marge == 0 && rollData.sdValue > 0) {
rollData.marge = rollData.finalResult - rollData.sdValue
rollData.isSuccess = (rollData.finalResult >= rollData.sdValue)
rollData.isCriticalSuccess = ((rollData.finalResult - rollData.sdValue) >= 7)
rollData.isCriticalFailure = ((rollData.finalResult - rollData.sdValue) <= -7)
}
}
/* -------------------------------------------- */
static async rollHeritiers(rollData) {
let actor = this.getActorFromRollData(rollData)
if (typeof (rollData.pvMalus) != "number") {
ui.notifications.warn("Votre personnage est Moribond(e). Aucun jet autorisé")
return
}
//rollData.actionImg = "systems/fvtt-les-heritiers/assets/icons/" + actor.system.attributs[rollData.attrKey].labelnorm + ".webp"
rollData.carac = duplicate(actor.system.caracteristiques[rollData.caracKey])
if (rollData.useTricherie || rollData.useHeritage) {
rollData.diceFormula = "{1d8, 1d10, 1d12}"
} else {
rollData.diceFormula = "1" + rollData.mainDice + "kh1"
}
let rangValue = 0
if (rollData.rang) {
rangValue = rollData.rang.value
}
if (rollData.competence) {
let compmod = (rollData.competence.system.niveau == 0) ? -3 : 0
let specBonus = (rollData.useSpecialite) ? 1 : 0
rollData.diceFormula += `+${rollData.carac.value}+${rangValue}+${rollData.competence.system.niveau}+${specBonus}+${rollData.bonusMalusContext}+${compmod}`
} else if (rollData.pouvoirBase) {
rollData.diceFormula += `+${rollData.pouvoirBase.value}+${rangValue}+${rollData.bonusMalusContext}`
} else {
rollData.diceFormula += `+${rollData.carac.value}+${rangValue}+${rollData.bonusMalusContext}`
}
rollData.diceFormula += `+${rollData.pvMalus}`
let myRoll = new Roll(rollData.diceFormula).roll({ async: false })
await this.showDiceSoNice(myRoll, game.settings.get("core", "rollMode"))
rollData.roll = myRoll
console.log(">>>> ", myRoll)
this.computeResult(actor, rollData)
if (rollData.mode == "init") {
actor.setFlag("world", "last-initiative", rollData.finalResult)
}
// Compute damages, cf p 187
if (rollData.arme && rollData.isSuccess) {
rollData.degatsArme = rollData.arme.system.degats + rollData.marge
if (rollData.arme.system.categorie == "lourde") {
rollData.degatsArme += actor.system.caracteristiques.for.value
}
if (rollData.arme.system.categorie == "blanche" || rollData.arme.system.categorie == "improvise") {
rollData.degatsArme += Math.max(0, actor.system.caracteristiques.for.value - 2)
}
}
this.createChatWithRollMode(rollData.alias, {
content: await renderTemplate(`systems/fvtt-les-heritiers/templates/chat-generic-result.html`, rollData)
}, rollData)
}
/* -------------------------------------------- */
static async bonusRollHeritiers(rollData) {
rollData.bonusFormula = rollData.addedBonus
let bonusRoll = new Roll(rollData.bonusFormula).roll({ async: false })
await this.showDiceSoNice(bonusRoll, game.settings.get("core", "rollMode"));
rollData.bonusRoll = bonusRoll
rollData.finalResult += rollData.bonusRoll.total
this.computeResult(rollData)
this.createChatWithRollMode(rollData.alias, {
content: await renderTemplate(`systems/fvtt-les-heritiers/templates/chat-generic-result.html`, rollData)
}, rollData)
}
/* -------------------------------------------- */
static getUsers(filter) {
return game.users.filter(filter).map(user => user._id);
}
/* -------------------------------------------- */
static getWhisperRecipients(rollMode, name) {
switch (rollMode) {
case "blindroll": return this.getUsers(user => user.isGM);
case "gmroll": return this.getWhisperRecipientsAndGMs(name);
case "selfroll": return [game.user.id];
}
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);
chatGM.content = "Blinde message of " + game.user.name + "<br>" + chatOptions.content;
console.log("blindMessageToGM", chatGM);
game.socket.emit("system.fvtt-les-heritiers", { msg: "msg_gm_chat_message", data: chatGM });
}
/* -------------------------------------------- */
static async searchItem(dataItem) {
let item
if (dataItem.pack) {
let id = dataItem.id || dataItem._id
let items = await this.loadCompendium(dataItem.pack, item => item.id == id)
item = items[0] || undefined
} else {
item = game.items.get(dataItem.id)
}
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 async createChatMessage(name, rollMode, chatOptions, rollData = undefined) {
switch (rollMode) {
case "blindroll": // GM only
if (!game.user.isGM) {
this.blindMessageToGM(chatOptions);
chatOptions.whisper = [game.user.id];
chatOptions.content = "Message only to the GM";
}
else {
chatOptions.whisper = this.getUsers(user => user.isGM);
}
break;
default:
chatOptions.whisper = this.getWhisperRecipients(rollMode, name);
break;
}
chatOptions.alias = chatOptions.alias || name
let msg = await ChatMessage.create(chatOptions)
console.log("=======>", rollData)
msg.setFlag("world", "heritiers-roll", rollData)
}
/* -------------------------------------------- */
static getBasicRollData() {
let rollData = {
rollId: randomID(16),
rollMode: game.settings.get("core", "rollMode"),
sdList: game.system.lesheritiers.config.seuilsDifficulte,
sdValue: 0,
bonusMalusContext: 0
}
return rollData
}
/* -------------------------------------------- */
static updateWithTarget(rollData) {
let target = HeritiersUtility.getTarget()
if (target) {
rollData.defenderTokenId = target.id
let defender = game.canvas.tokens.get(rollData.defenderTokenId).actor
rollData.armeDefense = defender.getBestDefenseValue()
rollData.targetVigueur = defender.getVigueur()
if (rollData.armeDefense) {
rollData.difficulte = rollData.armeDefense.system.totalDefensif
} else {
ui.notifications.warn("Aucune arme de défense équipée, difficulté manuelle à positionner.")
}
}
}
/* -------------------------------------------- */
static createChatWithRollMode(name, chatOptions, rollData = undefined) {
this.createChatMessage(name, game.settings.get("core", "rollMode"), chatOptions, rollData)
}
/* -------------------------------------------- */
static applyBonneAventureRoll(li, changed, addedBonus) {
let msgId = li.data("message-id")
let msg = game.messages.get(msgId)
if (msg) {
let rollData = msg.getFlag("world", "heritiers-roll")
let actor = this.getActorFromRollData(rollData)
actor.changeBonneAventure(changed)
rollData.isReroll = true
rollData.textBonus = "Bonus de Points d'Aventure"
if (addedBonus == "reroll") {
HeritiersUtility.rollHeritiers(rollData)
} else {
rollData.addedBonus = addedBonus
HeritiersUtility.bonusRollHeritiers(rollData)
}
}
}
/* -------------------------------------------- */
static applyEclatRoll(li, changed, addedBonus) {
let msgId = li.data("message-id")
let msg = game.messages.get(msgId)
if (msg) {
let rollData = msg.getFlag("world", "heritiers-roll")
let actor = this.getActorFromRollData(rollData)
actor.changeEclat(changed)
rollData.isReroll = true
rollData.textBonus = "Bonus d'Eclat"
if (addedBonus == "reroll") {
HeritiersUtility.rollHeritiers(rollData)
} else {
rollData.addedBonus = addedBonus
HeritiersUtility.bonusRollHeritiers(rollData)
}
}
}
/* -------------------------------------------- */
static chatRollMenu(html, options) {
let canApply = li => canvas.tokens.controlled.length && li.find(".heritiers-roll").length
let canApplyBA = function (li) {
let message = game.messages.get(li.attr("data-message-id"))
let rollData = message.getFlag("world", "heritiers-roll")
let actor = this.getActorFromRollData(rollData)
return (!rollData.isReroll && actor.getBonneAventure() > 0)
}
let canApplyPE = function (li) {
let message = game.messages.get(li.attr("data-message-id"))
let rollData = message.getFlag("world", "heritiers-roll")
let actor = this.getActorFromRollData(rollData)
return (!rollData.isReroll && actor.getEclat() > 0)
}
options.push(
{
name: "Ajouer +3 (1 point de Bonne Aventure)",
icon: "<i class='fas fa-user-plus'></i>",
condition: canApply && canApplyBA,
callback: li => HeritiersUtility.applyBonneAventureRoll(li, -1, "+3")
}
)
options.push(
{
name: "Ajouter +10 (1 Point d'Eclat)",
icon: "<i class='fas fa-user-plus'></i>",
condition: canApply && canApplyPE,
callback: li => HeritiersUtility.applyEclatRoll(li, -1, "+10")
}
)
options.push(
{
name: "Relancer le dé (1 point d'Eclat)",
icon: "<i class='fas fa-user-plus'></i>",
condition: canApply && canApplyPE,
callback: li => HeritiersUtility.applyEclatRoll(li, -3, "reroll")
}
)
return options
}
/* -------------------------------------------- */
static async confirmDelete(actorSheet, li) {
let itemId = li.data("item-id");
let msgTxt = "<p>Are you sure to remove this Item ?";
let buttons = {
delete: {
icon: '<i class="fas fa-check"></i>',
label: "Yes, remove it",
callback: () => {
actorSheet.actor.deleteEmbeddedDocuments("Item", [itemId]);
li.slideUp(200, () => actorSheet.render(false));
}
},
cancel: {
icon: '<i class="fas fa-times"></i>',
label: "Cancel"
}
}
msgTxt += "</p>";
let d = new Dialog({
title: "Confirm removal",
content: msgTxt,
buttons: buttons,
default: "cancel"
});
d.render(true);
}
/************************************************************************************/
static async __create_talents_table() {
let compName = "fvtt-les-heritiers.talents-cellule"
const compData = await HeritiersUtility.loadCompendium(compName)
let talents = compData.map(i => i.toObject())
let htmlTab = "<table border='1'><tbody>";
for (let entryData of talents) {
console.log(entryData)
htmlTab += `<tr><td>@UUID[Compendium.${compName}.${entryData._id}]{${entryData.name}}</td>`
htmlTab += `<td>${entryData.system.description}</td>`;
//htmlTab += `<td>${entryData.system.resumebonus}</td>`;
htmlTab += "</tr>\n";
}
htmlTab += "</table>";
await JournalEntry.create({ name: 'Liste des Talents de Cellule', content: htmlTab });
}
}