/* -------------------------------------------- */ import { PegasusCombat } from "./pegasus-combat.js"; import { PegasusCommands } from "./pegasus-commands.js"; import { PegasusActorCreate } from "./pegasus-create-char.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 PegasusUtility { /* -------------------------------------------- */ static async init() { Hooks.on('renderChatLog', (log, html, data) => PegasusUtility.chatListeners(html)); Hooks.on("getCombatTrackerEntryContext", (html, options) => { PegasusUtility.pushInitiativeOptions(html, options); }); Hooks.on("dropCanvasData", (canvas, data) => { PegasusUtility.dropItemOnToken(canvas, data) }); this.rollDataStore = {} this.defenderStore = {} this.diceList = []; this.diceFoundryList = []; this.optionsDiceList = ""; this.buildDiceLists(); PegasusCommands.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 pushInitiativeOptions(html, options) { options.push({ name: "Apply -10", condition: true, icon: '', callback: target => { PegasusCombat.decInitBy10(target.data('combatant-id'), -10); } }) } /* -------------------------------------------- */ static getDiceList() { return [{ key: "d4", img: "systems/fvtt-pegasus-rpg/images/dice/d4.webp" }, { key: "d6", img: "systems/fvtt-pegasus-rpg/images/dice/d6.webp" }, { key: "d8", img: "systems/fvtt-pegasus-rpg/images/dice/d8.webp" }, { key: "d10", img: "systems/fvtt-pegasus-rpg/images/dice/d10.webp" }, { key: "d12", img: "systems/fvtt-pegasus-rpg/images/dice/d12.webp" }] } /* -------------------------------------------- */ static updateEffectsBonusDice( rollData) { let newDicePool = rollData.dicePool.filter(dice => dice.name != "effect-bonus-dice") for (let effect of rollData.effectsList) { if (effect && effect.applied && effect.effect.data.bonusdice) { let diceKey = PegasusUtility.getDiceFromLevel(effect.effect.data.effectlevel) let newDice = { name: "effect-bonus-dice", key: diceKey, effect: effect.effect.name, img: `systems/fvtt-pegasus-rpg/images/dice/${diceKey}.webp` } newDicePool.push(newDice) } } rollData.dicePool = newDicePool } /* -------------------------------------------- */ static updateDamageDicePool(rollData) { if (rollData.isDamage) { let newDicePool = rollData.dicePool.filter(dice => dice.name != "damage") if (rollData.damageDiceLevel > 0) { let diceKey = PegasusUtility.getDiceFromLevel(rollData.damageDiceLevel) let diceList = diceKey.split(" ") for(let myDice of diceList) { let newDice = { name: "damage", key: myDice, img: `systems/fvtt-pegasus-rpg/images/dice/${myDice}.webp` } newDicePool.push(newDice) } } rollData.dicePool = newDicePool } } /* -------------------------------------------- */ static updateSpecDicePool(rollData) { let newDicePool = rollData.dicePool.filter(dice => dice.name != "spec") if (rollData.specDicesLevel > 0) { let diceKey = PegasusUtility.getDiceFromLevel(rollData.specDicesLevel) let diceList = diceKey.split(" ") for(let myDice of diceList) { let newDice = { name: "spec", key: myDice, img: `systems/fvtt-pegasus-rpg/images/dice/${myDice}.webp` } newDicePool.push(newDice) } } rollData.dicePool = newDicePool } /* -------------------------------------------- */ static addDicePool(rollData, diceKey) { let newDice = { name: "dice-click", key: diceKey, img: `systems/fvtt-pegasus-rpg/images/dice/${diceKey}.webp` } rollData.dicePool.push(newDice) } /*-------------------------------------------- */ static removeFromDicePool( rollData, diceIdx ) { let toRemove = rollData.dicePool[diceIdx] if (toRemove && toRemove.name != "spec" && toRemove.name != "stat" && toRemove.name != "damage") { let newDicePool = [] for (let i=0; i i.toObject()); } /* -------------------------------------------- */ 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: `
The item ${item.name} has been dropped on the actor ${actor.name}= token.x && x <= (token.x + token.width) && y >= token.y && y <= (token.y + token.height)) { let item = await this.searchItem(data) if (game.user.isGM || token.actor.isOwner) { this.addItemDropToActor(token.actor, item) } else { game.socket.emit("system.fvtt-pegasus-rpg", { name: "msg_gm_item_drop", data: { actorId: token.actor.id, itemId: item.id, isPack: item.pack } }) } return } } } /* -------------------------------------------- */ static async loadCompendiumData(compendium) { const pack = game.packs.get(compendium); return await pack?.getDocuments() ?? []; } /* -------------------------------------------- */ static async loadCompendium(compendium, filter = item => true) { let compendiumData = await PegasusUtility.loadCompendiumData(compendium); return compendiumData.filter(filter); } /* -------------------------------------------- */ static buildDiceLists() { let maxLevel = game.settings.get("fvtt-pegasus-rpg", "dice-max-level"); let diceList = ["0"]; let diceValues = [0]; let diceFoundryList = ["d0"]; let diceLevel = 1; let concat = ""; let concatFoundry = ""; let optionsDiceList = ''; let optionsLevel = ''; for (let i = 1; i <= maxLevel; i++) { let currentDices = concat + __level2Dice[diceLevel]; diceList.push(currentDices); diceFoundryList.push(concatFoundry + __level2Dice[diceLevel] + "x"); if (__level2Dice[diceLevel] == "d12") { concat = concat + "d12 "; concatFoundry = concatFoundry + "d12x, "; diceLevel = 1; } else { diceLevel++; } optionsDiceList += ``; optionsLevel += ``; } this.diceList = diceList; this.diceFoundryList = diceFoundryList; this.optionsDiceList = optionsDiceList; this.optionsLevel = optionsLevel; this.optionsStatusList = ''; } /* -------------------------------------------- */ static getOptionsStatusList() { return this.optionsStatusList; } /* -------------------------------------------- */ static getOptionsDiceList() { return this.optionsDiceList; } /* -------------------------------------------- */ static getOptionsLevel() { return this.optionsLevel; } /* -------------------------------------------- */ static computeAttackDefense(defenseRollId) { let defenseRollData = this.getRollData(defenseRollId); let attackRollData = this.getRollData(defenseRollData.linkedRollId); let defender = game.actors.get(defenseRollData.actorId); defender.processDefenseResult(defenseRollData, attackRollData); } /* -------------------------------------------- */ static applyDamage(defenseRollId) { let defenseRollData = this.getRollData(defenseRollId); let defender = game.actors.get(defenseRollData.actorId); defender.applyDamageLoss(defenseRollData.finalDamage); } /* -------------------------------------------- */ static applyNoDefense(actorId, attackRollId) { let attackRollData = this.getRollData(attackRollId); let defender = game.actors.get(actorId); defender.processNoDefense(attackRollData); } /* -------------------------------------------- */ static async chatListeners(html) { html.on("click", '.chat-create-actor', event => { game.system.pegasus.creator.processChatEvent(event); }) html.on("click", '.view-item-from-chat', event => { game.system.pegasus.creator.openItemView(event) }) html.on("click", '.reroll-level-remaining', event => { let rollId = $(event.currentTarget).data("roll-id") let rollData = this.getRollData(rollId) rollData.reroll = true this.rollPegasus( rollData) }) } /* -------------------------------------------- */ static async preloadHandlebarsTemplates() { const templatePaths = [ 'systems/fvtt-pegasus-rpg/templates/editor-notes-gm.html', 'systems/fvtt-pegasus-rpg/templates/partial-roll-select-effects.html', 'systems/fvtt-pegasus-rpg/templates/partial-options-statistics.html', 'systems/fvtt-pegasus-rpg/templates/partial-options-level.html', 'systems/fvtt-pegasus-rpg/templates/partial-options-range.html', 'systems/fvtt-pegasus-rpg/templates/partial-options-equipment-types.html', 'systems/fvtt-pegasus-rpg/templates/partial-equipment-effects.html', 'systems/fvtt-pegasus-rpg/templates/partial-actor-stat-block.html', 'systems/fvtt-pegasus-rpg/templates/partial-actor-status.html', 'systems/fvtt-pegasus-rpg/templates/partial-item-nav.html', 'systems/fvtt-pegasus-rpg/templates/partial-item-description.html', 'systems/fvtt-pegasus-rpg/templates/partial-actor-equipment.html' ] 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) { let effects = await this.loadCompendium('fvtt-pegasus.effect', item => item.name.toLowerCase() == effectName) 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) { return PegasusUtility.getChatMessageId(PegasusUtility.findChatMessage(current)); } static getChatMessageId(node) { return node?.attributes.getNamedItem('data-message-id')?.value; } static findChatMessage(current) { return PegasusUtility.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 PegasusUtility.findNodeMatching(current.parentElement, predicate); } return undefined; } /* -------------------------------------------- */ static templateData(it) { return PegasusUtility.data(it)?.data ?? {} } /* -------------------------------------------- */ static data(it) { if (it instanceof Actor || it instanceof Item || it instanceof Combatant) { return it.data; } return it; } /* -------------------------------------------- */ static getDiceValue(level = 0) { let diceString = this.diceList[level] if (!diceString) { return __name2DiceValue[level] } let diceTab = diceString.split(" ") let diceValue = 0 for (let dice of diceTab) { diceValue += __name2DiceValue[dice] } return diceValue } /* -------------------------------------------- */ static getDiceFromLevel(level = 0) { level = Number(level) return this.diceList[level]; } /* -------------------------------------------- */ static getFoundryDiceFromLevel(level = 0) { level = Number(level) //console.log(this.diceFoundryList); return this.diceFoundryList[level]; } /* -------------------------------------------- */ 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 += `` } 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 getDefenseState(actorId) { return this.defenderStore[actorId]; } /* -------------------------------------------- */ static async updateDefenseState(defenderId, rollId) { this.defenderStore[defenderId] = rollId if (game.user.character && game.user.character.id == defenderId) { let defender = game.actors.get(defenderId); let chatData = { user: game.user.id, alias: defender.name, rollMode: game.settings.get("core", "rollMode"), whisper: [game.user.id].concat(ChatMessage.getWhisperRecipients('GM')), content: `
${defender.name} is under attack. He must roll a skill/weapon/technique to defend himself or suffer damages (button below). 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 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; } await game.dice3d.showForRoll(roll, game.user, true, whisper, blind); } } } /* -------------------------------------------- */ static removeUsedPerkEffects(rollData) { // De-actived used effects from perks let toRem = [] for (let effect of rollData.effectsList) { if (effect.effect.data.perkId && effect.effect.data.isUsed) { toRem.push(effect.effect._id) } } if (toRem.length > 0) { let actor = game.actors.get(rollData.actorId) actor.deleteEmbeddedDocuments('Item', toRem) } } /* -------------------------------------------- */ static removeOneUseEffects(rollData) { // De-actived used effects from perks let toRem = [] for (let effect of rollData.effectsList) { if (effect.effect.data.isUsed && effect.effect.data.oneuse) { toRem.push(effect.effect._id) } } if (toRem.length > 0) { console.log("Going to remove one use effects", toRem) let actor = game.actors.get(rollData.actorId) actor.deleteEmbeddedDocuments('Item', toRem) } } /* -------------------------------------------- */ static async rollPegasus(rollData) { /* let dicePool = [{ name: "stat", level: 0, statmod: 0 }, { name: "spec", level: 0 }, { name: "bonus", level: 0 }, { name: "hindrance", level: 0 }, { name: "other", level: 0 }]; if (rollData.stat) { dicePool[0].level += Number(rollData.stat.value) dicePool[0].statmod = Number(rollData.stat.mod) } if (rollData.statDicesLevel) { dicePool[0].level = rollData.statDicesLevel } if (rollData.selectedSpec && rollData.selectedSpec != "0") { rollData.spec = rollData.specList.find(item => item._id == rollData.selectedSpec) rollData.spec.data.dice = PegasusUtility.getDiceFromLevel(rollData.spec.data.level) } if (rollData.spec) { dicePool[1].level += Number(rollData.spec.data.level) } if (rollData.specDicesLevel) { dicePool[1].level = rollData.specDicesLevel } if (rollData.traumaState == "none") { if (rollData.bonusDicesLevel) { dicePool[2].level += Number(rollData.bonusDicesLevel) } } if (!rollData.isInit) { // No Hindrance dice for Init if (rollData.hindranceDicesLevel) { dicePool[3].level += Number(rollData.hindranceDicesLevel) } } if (rollData.otherDicesLevel) { dicePool[4].level += Number(rollData.otherDicesLevel) } let diceFormulaTab = []; for (let diceGroup of dicePool) { diceFormulaTab.push(this.getFoundryDiceFromLevel(diceGroup.level)) } let diceFormula = '{' + diceFormulaTab.join(', ') + '}kh'; */ let actor = game.actors.get(rollData.actorId) let diceFormulaTab = [] for (let dice of rollData.dicePool) { diceFormulaTab.push(dice.key) } let diceFormula = '{' + diceFormulaTab.join(', ') + '}kh + ' + (rollData.stat?.mod || 0) // Performs roll let myRoll = rollData.roll if (!myRoll || rollData.reroll) { // New rolls only of no rerolls myRoll = new Roll(diceFormula).roll({ async: false }) await this.showDiceSoNice(myRoll, game.settings.get("core", "rollMode")) rollData.roll = myRoll } if (rollData.reroll) { rollData.levelRemaining = actor.modifyHeroLevelRemaining(-1) } // Final score and keep data rollData.finalScore = myRoll.total if (rollData.damages) { let dmgFormula = this.getFoundryDiceFromLevel(rollData.damages.value) let dmgRoll = new Roll(dmgFormula).roll({ async: false }) await this.showDiceSoNice(dmgRoll, game.settings.get("core", "rollMode")) rollData.dmgResult = dmgRoll.total } this.createChatWithRollMode(rollData.alias, { content: await renderTemplate(`systems/fvtt-pegasus-rpg/templates/chat-generic-result.html`, rollData) }); // Init stuf if (rollData.isInit) { let combat = game.combats.get(rollData.combatId) combat.updateEmbeddedDocuments("Combatant", [{ _id: rollData.combatantId, initiative: rollData.finalScore }]) } // Stun specific -> Suffere a stun level when dmg-res if (rollData.subKey && rollData.subKey == "dmg-res") { actor.modifyStun(-1) } //this.removeUsedPerkEffects( rollData) // Unused for now this.removeOneUseEffects(rollData) // Unused for now // And save the roll this.saveRollData(rollData); } /* -------------------------------------------- */ static getDamageDice(result) { if (result < 0) return 0; return Math.floor(result / 5) + 1; } /* ------------------------- ------------------- */ static async updateRoll(rollData) { let diceResults = rollData.diceResults; let sortedRoll = []; for (let i = 0; i < 10; i++) { sortedRoll[i] = 0; } for (let dice of diceResults) { sortedRoll[dice.result]++; } let index = 0; let bestRoll = 0; for (let i = 0; i < 10; i++) { if (sortedRoll[i] > bestRoll) { bestRoll = sortedRoll[i]; index = i; } } 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) { let actor = game.actors.get(actorId); let rollData = actor.getRollData(); if (diceIndex == -1) { rollData.hasWillpower = actor.decrementWillpower(); rollData.roll = undefined; } else { let myRoll = new Roll("1d6").roll({ async: false }); await this.showDiceSoNice(myRoll, game.settings.get("core", "rollMode")); console.log("Result: ", myRoll); rollData.roll.dice[0].results[diceIndex].result = myRoll.total; // Patch rollData.nbStrongHitUsed++; } this.rollFraggedKingdom(rollData); } /* -------------------------------------------- */ static getUsers(filter) { return game.users.filter(filter).map(user => user.data._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 + "
" + chatOptions.content; 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) } 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) { 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; ChatMessage.create(chatOptions); } /* -------------------------------------------- */ static getBasicRollData() { let rollData = { rollId: randomID(16), rollMode: game.settings.get("core", "rollMode"), bonusDicesLevel: 0, hindranceDicesLevel: 0, otherDicesLevel: 0, statDicesLevel: 0, specDicesLevel: 0, effectsList: [], armorsList: [], weaponsList: [], equipmentsList: [], optionsDiceList: PegasusUtility.getOptionsDiceList() } PegasusUtility.updateWithTarget(rollData) return rollData } /* -------------------------------------------- */ static updateWithTarget(rollData) { let objectDefender let target = PegasusUtility.getTarget(); if (target) { let defenderActor = game.actors.get(target.data.actorId) objectDefender = PegasusUtility.data(defenderActor) objectDefender = mergeObject(objectDefender, target.data.actorData) rollData.defender = objectDefender rollData.attackerId = this.id rollData.defenderId = objectDefender._id defenderActor.addHindrancesList(rollData.effectsList) } } /* -------------------------------------------- */ static createChatWithRollMode(name, chatOptions) { this.createChatMessage(name, game.settings.get("core", "rollMode"), chatOptions); } /* -------------------------------------------- */ static async confirmDelete(actorSheet, li) { let itemId = li.data("item-id"); let msgTxt = "

Are you sure to remove this Item ?"; let buttons = { delete: { icon: '', label: "Yes, remove it", callback: () => { actorSheet.actor.deleteEmbeddedDocuments("Item", [itemId]); li.slideUp(200, () => actorSheet.render(false)); } }, cancel: { icon: '', label: "Cancel" } } msgTxt += "

"; let d = new Dialog({ title: "Confirm removal", content: msgTxt, buttons: buttons, default: "cancel" }); d.render(true); } }