fvtt-crucible-rpg/modules/crucible-actor.js

398 lines
13 KiB
JavaScript

/* -------------------------------------------- */
import { CrucibleUtility } from "./crucible-utility.js";
import { CrucibleRollDialog } from "./crucible-roll-dialog.js";
/* -------------------------------------------- */
const coverBonusTable = { "nocover": 0, "lightcover": 2, "heavycover": 4, "entrenchedcover": 6 };
const statThreatLevel = ["agi", "str", "phy", "com", "def", "per"]
const __subkey2title = {
"melee-dmg": "Melee Damage", "melee-atk": "Melee Attack", "ranged-atk": "Ranged Attack",
"ranged-dmg": "Ranged Damage", "dmg-res": "Damare Resistance"
}
/* -------------------------------------------- */
/* -------------------------------------------- */
/**
* Extend the base Actor entity by defining a custom roll data structure which is ideal for the Simple system.
* @extends {Actor}
*/
export class CrucibleActor extends Actor {
/* -------------------------------------------- */
/**
* Override the create() function to provide additional SoS functionality.
*
* This overrided create() function adds initial items
* Namely: Basic skills, money,
*
* @param {Object} data Barebones actor data which this function adds onto.
* @param {Object} options (Unused) Additional options which customize the creation workflow.
*
*/
static async create(data, options) {
// Case of compendium global import
if (data instanceof Array) {
return super.create(data, options);
}
// If the created actor has items (only applicable to duplicated actors) bypass the new actor creation logic
if (data.items) {
let actor = super.create(data, options);
return actor;
}
if (data.type == 'character') {
const skills = await CrucibleUtility.loadCompendium("fvtt-crucible-rpg.skills");
data.items = skills.map(i => i.toObject());
}
if (data.type == 'npc') {
}
return super.create(data, options);
}
/* -------------------------------------------- */
prepareBaseData() {
}
/* -------------------------------------------- */
async prepareData() {
super.prepareData();
}
/* -------------------------------------------- */
prepareDerivedData() {
if (this.type == 'character') {
this.data.data.encCapacity = this.getEncumbranceCapacity()
this.buildContainerTree()
}
super.prepareDerivedData();
}
/* -------------------------------------------- */
_preUpdate(changed, options, user) {
super._preUpdate(changed, options, user);
}
/* -------------------------------------------- */
getEncumbranceCapacity() {
return this.data.data.statistics.str.value * 25
}
/* -------------------------------------------- */
getMoneys() {
let comp = this.data.items.filter(item => item.type == 'money');
return comp;
}
/* -------------------------------------------- */
getArmors() {
let comp = duplicate(this.data.items.filter(item => item.type == 'armor') || []);
return comp;
}
getRace() {
let race = this.data.items.filter(item => item.type == 'race')
return race[0] ?? [];
}
/* -------------------------------------------- */
checkAndPrepareEquipment(item) {
}
/* -------------------------------------------- */
checkAndPrepareEquipments(listItem) {
for (let item of listItem) {
this.checkAndPrepareEquipment(item)
}
return listItem
}
/* -------------------------------------------- */
getWeapons() {
let comp = duplicate(this.data.items.filter(item => item.type == 'weapon') || []);
return comp;
}
/* -------------------------------------------- */
getItemById(id) {
let item = this.data.items.find(item => item.id == id);
if (item) {
item = duplicate(item)
if (item.type == 'specialisation') {
item.data.dice = CrucibleUtility.getDiceFromLevel(item.data.level);
}
}
return item;
}
/* -------------------------------------------- */
getSkills() {
let comp = duplicate(this.data.items.filter(item => item.type == 'skill') || []);
for (let c of comp) {
c.data.dice = CrucibleUtility.getDiceFromLevel(c.data.level);
}
return comp;
}
/* -------------------------------------------- */
getRelevantAbility(statKey) {
let comp = duplicate(this.data.items.filter(item => item.type == 'skill' && item.data.data.ability == ability) || []);
return comp;
}
/* -------------------------------------------- */
async equipItem(itemId) {
let item = this.data.items.find(item => item.id == itemId);
if (item && item.data.data) {
let update = { _id: item.id, "data.equipped": !item.data.data.equipped };
await this.updateEmbeddedDocuments('Item', [update]); // Updates one EmbeddedEntity
}
}
/* -------------------------------------------- */
compareName(a, b) {
if (a.name < b.name) {
return -1;
}
if (a.name > b.name) {
return 1;
}
return 0;
}
/* ------------------------------------------- */
getEquipments() {
return this.data.items.filter(item => item.type == 'shield' || item.type == 'armor' || item.type == "weapon" || item.type == "equipment");
}
/* ------------------------------------------- */
getEquipmentsOnly() {
return duplicate(this.data.items.filter(item => item.type == "equipment") || [])
}
/* ------------------------------------------- */
async buildContainerTree() {
let equipments = duplicate(this.data.items.filter(item => item.type == "equipment") || [])
for (let equip1 of equipments) {
if (equip1.data.iscontainer) {
equip1.data.contents = []
equip1.data.contentsEnc = 0
for (let equip2 of equipments) {
if (equip1._id != equip2._id && equip2.data.containerid == equip1._id) {
equip1.data.contents.push(equip2)
let q = equip2.data.quantity ?? 1
equip1.data.contentsEnc += q * equip2.data.weight
}
}
}
}
// Compute whole enc
let enc = 0
for (let item of equipments) {
item.data.idrDice = CrucibleUtility.getDiceFromLevel(Number(item.data.idr))
if (item.data.equipped) {
if (item.data.iscontainer) {
enc += item.data.contentsEnc
} else if (item.data.containerid == "") {
let q = item.data.quantity ?? 1
enc += q * item.data.weight
}
}
}
for (let item of this.data.items) { // Process items/shields/armors
if ((item.type == "weapon" || item.type == "shield" || item.type == "armor") && item.data.data.equipped) {
let q = item.data.data.quantity ?? 1
enc += q * item.data.data.weight
}
}
// Store local values
this.encCurrent = enc
this.containersTree = equipments.filter(item => item.data.containerid == "") // Returns the root of equipements without container
// Manages slow effect
let overCapacity = Math.floor(this.encCurrent / this.getEncumbranceCapacity())
this.encHindrance = Math.floor(this.encCurrent / this.getEncumbranceCapacity())
//console.log("Capacity", overCapacity, this.encCurrent / this.getEncumbranceCapacity() )
let effect = this.data.items.find(item => item.type == "effect" && item.data.data.slow)
if (overCapacity >= 4) {
if (!effect) {
effect = await CrucibleUtility.getEffectFromCompendium("Slowed")
effect.data.slow = true
this.createEmbeddedDocuments('Item', [effect])
}
} else {
if (effect) {
this.deleteEmbeddedDocuments('Item', [effect.id])
}
}
}
/* -------------------------------------------- */
getAbility(abilKey) {
return this.data.data.abilities[abilKey];
}
/* -------------------------------------------- */
async addObjectToContainer(itemId, containerId) {
let container = this.data.items.find(item => item.id == containerId && item.data.data.iscontainer)
let object = this.data.items.find(item => item.id == itemId)
if (container) {
if (object.data.data.iscontainer) {
ui.notifications.warn("Only 1 level of container allowed")
return
}
let alreadyInside = this.data.items.filter(item => item.data.data.containerid && item.data.data.containerid == containerId);
if (alreadyInside.length >= container.data.data.containercapacity) {
ui.notifications.warn("Container is already full !")
return
} else {
await this.updateEmbeddedDocuments("Item", [{ _id: object.id, 'data.containerid': containerId }])
}
} else if (object && object.data.data.containerid) { // remove from container
console.log("Removeing: ", object)
await this.updateEmbeddedDocuments("Item", [{ _id: object.id, 'data.containerid': "" }]);
}
}
/* -------------------------------------------- */
async preprocessItem(event, item, onDrop = false) {
let dropID = $(event.target).parents(".item").attr("data-item-id") // Only relevant if container drop
let objectID = item.id || item._id
this.addObjectToContainer(objectID, dropID)
return true
}
/* -------------------------------------------- */
async equipGear(equipmentId) {
let item = this.data.items.find(item => item.id == equipmentId);
if (item && item.data.data) {
let update = { _id: item.id, "data.equipped": !item.data.data.equipped };
await this.updateEmbeddedDocuments('Item', [update]); // Updates one EmbeddedEntity
}
}
/* -------------------------------------------- */
getInitiativeScore(combatId, combatantId) {
if (this.type == 'character') {
this.rollMR(true, combatId, combatantId)
}
console.log("Init required !!!!")
return -1;
}
/* -------------------------------------------- */
getSubActors() {
let subActors = [];
for (let id of this.data.data.subactors) {
subActors.push(duplicate(game.actors.get(id)))
}
return subActors;
}
/* -------------------------------------------- */
async addSubActor(subActorId) {
let subActors = duplicate(this.data.data.subactors);
subActors.push(subActorId);
await this.update({ 'data.subactors': subActors });
}
/* -------------------------------------------- */
async delSubActor(subActorId) {
let newArray = [];
for (let id of this.data.data.subactors) {
if (id != subActorId) {
newArray.push(id);
}
}
await this.update({ 'data.subactors': newArray });
}
/* -------------------------------------------- */
syncRoll(rollData) {
let linkedRollId = CrucibleUtility.getDefenseState(this.id);
if (linkedRollId) {
rollData.linkedRollId = linkedRollId;
}
this.lastRollId = rollData.rollId;
CrucibleUtility.saveRollData(rollData);
}
/* -------------------------------------------- */
getOneSkill(skillId) {
let skill = this.data.items.find(item => item.type == 'skill' && item.id == skillId)
if (skill) {
skill = duplicate(skill);
}
return skill;
}
/* -------------------------------------------- */
async deleteAllItemsByType(itemType) {
let items = this.data.items.filter(item => item.type == itemType);
await this.deleteEmbeddedDocuments('Item', items);
}
/* -------------------------------------------- */
async addItemWithoutDuplicate(newItem) {
let item = this.data.items.find(item => item.type == newItem.type && item.name.toLowerCase() == newItem.name.toLowerCase())
if (!item) {
await this.createEmbeddedDocuments('Item', [newItem]);
}
}
/* -------------------------------------------- */
async incDecQuantity(objetId, incDec = 0) {
let objetQ = this.data.items.get(objetId)
if (objetQ) {
let newQ = objetQ.data.data.quantity + incDec
if (newQ >= 0) {
const updated = await this.updateEmbeddedDocuments('Item', [{ _id: objetQ.id, 'data.quantity': newQ }]) // pdates one EmbeddedEntity
}
}
}
/* -------------------------------------------- */
async incDecAmmo(objetId, incDec = 0) {
let objetQ = this.data.items.get(objetId)
if (objetQ) {
let newQ = objetQ.data.data.ammocurrent + incDec;
if (newQ >= 0 && newQ <= objetQ.data.data.ammomax) {
const updated = await this.updateEmbeddedDocuments('Item', [{ _id: objetQ.id, 'data.ammocurrent': newQ }]); // pdates one EmbeddedEntity
}
}
}
/* -------------------------------------------- */
getCommonRollData(abKey = undefined) {
let rollData = CrucibleUtility.getBasicRollData()
rollData.alias = this.name
rollData.actorImg = this.img
rollData.actorId = this.id
rollData.img = this.img
if (abilKey) {
rollData.getRelevantSkill(abKey)
rollData.ability = this.getAbility(abKey)
rollData.skillList = this.getRelevantSkill(abKey)
rollData.selectedKill = "0"
rollData.img = `systems/fvtt-crucible-rpg/images/icons/${rollData.ability.abbrev}.webp`
}
console.log("ROLLDATA", rollData)
return rollData
}
/* -------------------------------------------- */
async startRoll(rollData) {
this.syncRoll(rollData);
//console.log("ROLL DATA", rollData)
let rollDialog = await CrucibleRollDialog.create(this, rollData)
console.log(rollDialog)
rollDialog.render(true);
}
}