Feature/200 beastform (#255)

* Temp

* Dialog setup

* Fixed basic beastform

* Reworked beastform to hold it's data entirely in the beastformEffect

* UpdateActorTokens fix

* Removed hardcoded tierlimit on beastform

* PR fixes
This commit is contained in:
WBHarry 2025-07-04 02:02:14 +02:00 committed by GitHub
parent c4448226e0
commit d071fadf7d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
41 changed files with 1102 additions and 298 deletions

View file

@ -15,7 +15,8 @@ export { default as DhpChatMessage } from './chatMessage.mjs';
export { default as DhpEnvironment } from './sheets/actors/environment.mjs';
export { default as DhActiveEffectConfig } from './sheets/activeEffectConfig.mjs';
export { default as DhContextMenu } from './contextMenu.mjs';
export { default as DhBeastform } from './sheets/items/beastform.mjs';
export { default as DhTooltipManager } from './tooltipManager.mjs';
export * as api from './sheets/api/_modules.mjs';
export * as ux from "./ux/_module.mjs";
export * as ux from './ux/_module.mjs';

View file

@ -69,6 +69,13 @@ export default class DHActionConfig extends DaggerheartSheet(ApplicationV2) {
context.disableOption = this.disableOption.bind(this);
context.isNPC = this.action.actor && this.action.actor.type !== 'character';
context.hasRoll = this.action.hasRoll;
const settingsTiers = game.settings.get(SYSTEM.id, SYSTEM.SETTINGS.gameSettings.LevelTiers).tiers;
context.tierOptions = [
{ key: 1, label: game.i18n.localize('DAGGERHEART.Tiers.tier1') },
...Object.values(settingsTiers).map(x => ({ key: x.tier, label: x.name }))
];
return context;
}

View file

@ -5,7 +5,7 @@ const { ApplicationV2, HandlebarsApplicationMixin } = foundry.applications.api;
export default class RollSelectionDialog extends HandlebarsApplicationMixin(ApplicationV2) {
constructor(experiences, costs, action, resolve) {
super({}, {});
this.experiences = experiences;
this.costs = costs;
this.action = action;
@ -67,9 +67,9 @@ export default class RollSelectionDialog extends HandlebarsApplicationMixin(Appl
context.fear = this.data.fear;
context.advantage = this.data.advantage;
context.experiences = Object.keys(this.experiences).map(id => ({ id, ...this.experiences[id] }));
if(this.costs?.length) {
if (this.costs?.length) {
const updatedCosts = this.action.calcCosts(this.costs);
context.costs = updatedCosts
context.costs = updatedCosts;
context.canRoll = this.action.getRealCosts(updatedCosts)?.hasCost;
} else context.canRoll = true;

View file

@ -7,6 +7,8 @@ import { abilities } from '../../../config/actorConfig.mjs';
import DhCharacterlevelUp from '../../levelup/characterLevelup.mjs';
import DhCharacterCreation from '../../characterCreation.mjs';
import FilterMenu from '../../ux/filter-menu.mjs';
import { DhBeastformAction } from '../../../data/action/action.mjs';
import DHActionConfig from '../../config/Action.mjs';
const { ActorSheetV2 } = foundry.applications.sheets;
const { TextEditor } = foundry.applications.ux;
@ -306,11 +308,14 @@ export default class CharacterSheet extends DaggerheartSheet(ActorSheetV2) {
getItem(element) {
const listElement = (element.target ?? element).closest('[data-item-id]');
const document = listElement.dataset.companion ? this.document.system.companion : this.document;
const itemId = listElement.dataset.itemId,
item = document.items.get(itemId);
return item;
const itemId = listElement.dataset.itemId;
if (listElement.dataset.type === 'effect') {
return this.document.effects.get(itemId);
} else if (['armor', 'weapon', 'feature', 'consumable', 'miscellaneous'].includes(listElement.dataset.type)) {
return this.document.items.get(itemId);
} else {
return this.document.system[listElement.dataset.type].system.actions.find(x => x.id === itemId);
}
}
static triggerContextMenu(event, button) {
@ -733,7 +738,9 @@ export default class CharacterSheet extends DaggerheartSheet(ActorSheetV2) {
// Should dandle its actions. Or maybe they'll be separate buttons as per an Issue on the board
if (item.type === 'feature') {
item.toChat();
item.use(event);
} else if (item instanceof ActiveEffect) {
item.toChat(this);
} else {
const wasUsed = await item.use(event);
if (wasUsed && item.type === 'weapon') {
@ -746,7 +753,11 @@ export default class CharacterSheet extends DaggerheartSheet(ActorSheetV2) {
const item = this.getItem(event);
if (!item) return;
item.sheet.render(true);
if (item.sheet) {
item.sheet.render(true);
} else {
await new DHActionConfig(item).render(true);
}
}
editItem(event) {

View file

@ -0,0 +1,65 @@
import DHBaseItemSheet from '../api/base-item.mjs';
export default class BeastformSheet extends DHBaseItemSheet {
/**@inheritdoc */
static DEFAULT_OPTIONS = {
classes: ['beastform'],
dragDrop: [{ dragSelector: null, dropSelector: '.drop-section' }],
actions: {
editFeature: this.editFeature,
removeFeature: this.removeFeature
}
};
/**@override */
static PARTS = {
header: { template: 'systems/daggerheart/templates/sheets/items/beastform/header.hbs' },
tabs: { template: 'systems/daggerheart/templates/sheets/global/tabs/tab-navigation.hbs' },
settings: { template: 'systems/daggerheart/templates/sheets/items/beastform/settings.hbs' },
features: {
template: 'systems/daggerheart/templates/sheets/global/tabs/tab-features.hbs',
scrollable: ['.features']
},
effects: {
template: 'systems/daggerheart/templates/sheets/global/tabs/tab-effects.hbs',
scrollable: ['.effects']
}
};
static TABS = {
primary: {
tabs: [{ id: 'settings' }, { id: 'features' }, { id: 'effects' }],
initial: 'settings',
labelPrefix: 'DAGGERHEART.Sheets.TABS'
}
};
/**@inheritdoc */
async _preparePartContext(partId, context) {
await super._preparePartContext(partId, context);
return context;
}
static editFeature(event) {
const target = event.target.closest('[data-action="editFeature"]');
const feature = this.document.system.features[target.dataset.index];
feature.sheet.render({ force: true });
}
static async removeFeature(_, target) {
const current = this.document.system.features.map(x => x.uuid);
await this.document.update({
'system.features': current.filter((_, index) => index !== Number(target.dataset.index))
});
}
async _onDrop(event) {
const data = TextEditor.getDragEventData(event);
const item = await fromUuid(data.uuid);
if (item.type === 'feature') {
const current = this.document.system.features.map(x => x.uuid);
await this.document.update({ 'system.features': [...current, item.uuid] });
}
}
}

View file

@ -38,6 +38,11 @@ export const actionTypes = {
id: 'macro',
name: 'DAGGERHEART.Actions.Types.macro.name',
icon: 'fa-scroll'
},
beastform: {
id: 'beastform',
name: 'DAGGERHEART.Actions.Types.beastform.name',
icon: 'fa-paw'
}
};
@ -119,4 +124,4 @@ export const advandtageState = {
label: 'DAGGERHEART.General.Advantage.Full',
value: 1
}
}
};

View file

@ -245,19 +245,23 @@ export const deathMoves = {
export const tiers = {
tier1: {
id: 'tier1',
label: 'DAGGERHEART.Tiers.tier1'
label: 'DAGGERHEART.Tiers.tier1',
value: 1
},
tier2: {
id: 'tier2',
label: 'DAGGERHEART.Tiers.tier2'
label: 'DAGGERHEART.Tiers.tier2',
value: 2
},
tier3: {
id: 'tier3',
label: 'DAGGERHEART.Tiers.tier3'
label: 'DAGGERHEART.Tiers.tier3',
value: 3
},
tier4: {
id: 'tier4',
label: 'DAGGERHEART.Tiers.tier4'
label: 'DAGGERHEART.Tiers.tier4',
value: 4
}
};

View file

@ -6,3 +6,4 @@ export * as items from './item/_module.mjs';
export { actionsTypes } from './action/_module.mjs';
export * as messages from './chat-message/_modules.mjs';
export * as fields from './fields/_module.mjs';
export * as activeEffects from './activeEffect/_module.mjs';

View file

@ -1,6 +1,7 @@
import {
DHAttackAction,
DHBaseAction,
DhBeastformAction,
DHDamageAction,
DHEffectAction,
DHHealingAction,
@ -19,5 +20,6 @@ export const actionsTypes = {
healing: DHHealingAction,
summon: DHSummonAction,
effect: DHEffectAction,
macro: DHMacroAction
macro: DHMacroAction,
beastform: DhBeastformAction
};

View file

@ -1,6 +1,7 @@
import { DHActionDiceData, DHActionRollData, DHDamageData, DHDamageField } from './actionDice.mjs';
import DhpActor from '../../documents/actor.mjs';
import D20RollDialog from '../../dialogs/d20RollDialog.mjs';
import BeastformDialog from '../../dialogs/beastformDialog.mjs';
const fields = foundry.data.fields;
@ -106,6 +107,11 @@ export class DHBaseAction extends foundry.abstract.DataModel {
}),
value: new fields.EmbeddedDataField(DHActionDiceData),
valueAlt: new fields.EmbeddedDataField(DHActionDiceData)
}),
beastform: new fields.SchemaField({
tierAccess: new fields.SchemaField({
exact: new fields.NumberField({ integer: true, nullable: true, initial: null })
})
})
},
extraSchemas = {};
@ -757,3 +763,50 @@ export class DHMacroAction extends DHBaseAction {
}
}
}
export class DhBeastformAction extends DHBaseAction {
static extraSchemas = ['beastform'];
async use(event, ...args) {
const beastformConfig = this.prepareBeastformConfig();
const abort = await this.handleActiveTransformations();
if (abort) return;
const beastformUuid = await BeastformDialog.configure(beastformConfig);
if (!beastformUuid) return;
await this.transform(beastformUuid);
}
prepareBeastformConfig(config) {
const settingsTiers = game.settings.get(SYSTEM.id, SYSTEM.SETTINGS.gameSettings.LevelTiers).tiers;
const actorLevel = this.actor.system.levelData.level.current;
const actorTier =
Object.values(settingsTiers).find(
tier => actorLevel >= tier.levels.start && actorLevel <= tier.levels.end
) ?? 1;
return {
tierLimit: this.beastform.tierAccess.exact ?? actorTier
};
}
async transform(beastformUuid) {
const beastform = await foundry.utils.fromUuid(beastformUuid);
this.actor.createEmbeddedDocuments('Item', [beastform.toObject()]);
}
async handleActiveTransformations() {
const beastformEffects = this.actor.effects.filter(x => x.type === 'beastform');
if (beastformEffects.length > 0) {
for (let effect of beastformEffects) {
await effect.delete();
}
return true;
}
return false;
}
}

View file

@ -0,0 +1,7 @@
import beastformEffect from './beastformEffect.mjs';
export { beastformEffect };
export const config = {
beastform: beastformEffect
};

View file

@ -0,0 +1,40 @@
import { updateActorTokens } from '../../helpers/utils.mjs';
export default class BeastformEffect extends foundry.abstract.TypeDataModel {
static defineSchema() {
const fields = foundry.data.fields;
return {
characterTokenData: new fields.SchemaField({
tokenImg: new fields.FilePathField({
categories: ['IMAGE'],
base64: false,
nullable: true
}),
tokenSize: new fields.SchemaField({
height: new fields.NumberField({ integer: true, nullable: true }),
width: new fields.NumberField({ integer: true, nullable: true })
})
}),
advantageOn: new fields.ArrayField(new fields.StringField()),
featureIds: new fields.ArrayField(new fields.StringField()),
effectIds: new fields.ArrayField(new fields.StringField())
};
}
async _preDelete() {
if (this.parent.parent.type === 'character') {
const update = {
height: this.characterTokenData.tokenSize.height,
width: this.characterTokenData.tokenSize.width,
texture: {
src: this.characterTokenData.tokenImg
}
};
await updateActorTokens(this.parent.parent, update);
await this.parent.parent.deleteEmbeddedDocuments('Item', this.featureIds);
await this.parent.parent.deleteEmbeddedDocuments('ActiveEffect', this.effectIds);
}
}
}

View file

@ -8,6 +8,7 @@ import DHFeature from './feature.mjs';
import DHMiscellaneous from './miscellaneous.mjs';
import DHSubclass from './subclass.mjs';
import DHWeapon from './weapon.mjs';
import DHBeastform from './beastform.mjs';
export {
DHAncestry,
@ -19,7 +20,8 @@ export {
DHFeature,
DHMiscellaneous,
DHSubclass,
DHWeapon
DHWeapon,
DHBeastform
};
export const config = {
@ -32,5 +34,6 @@ export const config = {
feature: DHFeature,
miscellaneous: DHMiscellaneous,
subclass: DHSubclass,
weapon: DHWeapon
weapon: DHWeapon,
beastform: DHBeastform
};

View file

@ -0,0 +1,98 @@
import { updateActorTokens } from '../../helpers/utils.mjs';
import ForeignDocumentUUIDArrayField from '../fields/foreignDocumentUUIDArrayField.mjs';
import BaseDataItem from './base.mjs';
export default class DHBeastform extends BaseDataItem {
static LOCALIZATION_PREFIXES = ['DAGGERHEART.Sheets.Beastform'];
/** @inheritDoc */
static get metadata() {
return foundry.utils.mergeObject(super.metadata, {
label: 'TYPES.Item.beastform',
type: 'beastform',
hasDescription: false
});
}
/** @inheritDoc */
static defineSchema() {
const fields = foundry.data.fields;
return {
...super.defineSchema(),
tier: new fields.StringField({
required: true,
choices: SYSTEM.GENERAL.tiers,
initial: SYSTEM.GENERAL.tiers.tier1.id
}),
tokenImg: new fields.FilePathField({
initial: 'icons/svg/mystery-man.svg',
categories: ['IMAGE'],
base64: false
}),
tokenSize: new fields.SchemaField({
height: new fields.NumberField({ integer: true, min: 1, initial: null, nullable: true }),
width: new fields.NumberField({ integer: true, min: 1, initial: null, nullable: true })
}),
examples: new fields.StringField(),
advantageOn: new fields.ArrayField(new fields.StringField()),
features: new ForeignDocumentUUIDArrayField({ type: 'Item' })
};
}
async _preCreate(data, options, user) {
const allowed = await super._preCreate(data, options, user);
if (allowed === false) return;
if (!this.actor) return;
if (this.actor.type !== 'character') {
ui.notifications.error(game.i18n.localize('DAGGERHEART.UI.notifications.beastformInapplicable'));
return false;
}
if (this.actor.items.find(x => x.type === 'beastform')) {
ui.notifications.error(game.i18n.localize('DAGGERHEART.UI.notifications.beastformAlreadyApplied'));
return false;
}
const features = await this.parent.parent.createEmbeddedDocuments(
'Item',
this.features.map(x => x.toObject())
);
const effects = await this.parent.parent.createEmbeddedDocuments(
'ActiveEffect',
this.parent.effects.map(x => x.toObject())
);
await this.parent.parent.createEmbeddedDocuments('ActiveEffect', [
{
type: 'beastform',
name: game.i18n.localize('DAGGERHEART.Sheets.Beastform.beastformEffect'),
img: 'icons/creatures/abilities/paw-print-pair-purple.webp',
system: {
isBeastform: true,
characterTokenData: {
tokenImg: this.parent.parent.prototypeToken.texture.src,
tokenSize: {
height: this.parent.parent.prototypeToken.height,
width: this.parent.parent.prototypeToken.width
}
},
advantageOn: this.advantageOn,
featureIds: features.map(x => x.id),
effectIds: effects.map(x => x.id)
}
}
]);
await updateActorTokens(this.parent.parent, {
height: this.tokenSize.height,
width: this.tokenSize.width,
texture: {
src: this.tokenImg
}
});
return false;
}
}

View file

@ -0,0 +1,86 @@
import { tiers } from '../config/generalConfig.mjs';
const { ApplicationV2, HandlebarsApplicationMixin } = foundry.applications.api;
export default class BeastformDialog extends HandlebarsApplicationMixin(ApplicationV2) {
constructor(configData) {
super();
this.configData = configData;
this.selected = null;
}
static DEFAULT_OPTIONS = {
tag: 'form',
classes: ['daggerheart', 'views', 'dh-style', 'beastform-selection'],
position: {
width: 600,
height: 'auto'
},
actions: {
selectBeastform: this.selectBeastform,
submitBeastform: this.submitBeastform
},
form: {
handler: this.updateBeastform,
submitOnChange: true,
submitOnClose: false
}
};
get title() {
return game.i18n.localize('DAGGERHEART.Sheets.Beastform.dialogTitle');
}
/** @override */
static PARTS = {
beastform: {
template: 'systems/daggerheart/templates/views/beastformDialog.hbs'
}
};
async _prepareContext(_options) {
const context = await super._prepareContext(_options);
context.beastformTiers = game.items.reduce((acc, x) => {
const tier = tiers[x.system.tier];
if (x.type !== 'beastform' || tier.value > this.configData.tierLimit) return acc;
if (!acc[tier.value]) acc[tier.value] = { label: game.i18n.localize(tier.label), values: {} };
acc[tier.value].values[x.uuid] = { selected: this.selected == x.uuid, value: x };
return acc;
}, {}); // Also get from compendium when added
context.canSubmit = this.selected;
return context;
}
static updateBeastform(event, _, formData) {
this.selected = foundry.utils.mergeObject(this.selected, formData.object);
this.render();
}
static selectBeastform(_, target) {
this.selected = this.selected === target.dataset.uuid ? null : target.dataset.uuid;
this.render();
}
static async submitBeastform() {
await this.close({ submitted: true });
}
/** @override */
_onClose(options = {}) {
if (!options.submitted) this.config = false;
}
static async configure(configData) {
return new Promise(resolve => {
const app = new this(configData);
app.addEventListener('close', () => resolve(app.selected), { once: true });
app.render({ force: true });
});
}
}

View file

@ -38,7 +38,7 @@ export default class DamageDialog extends HandlebarsApplicationMixin(Application
const context = await super._prepareContext(_options);
context.title = this.config.title;
context.extraFormula = this.config.extraFormula;
context.formula = this.roll.constructFormula(this.config);;
context.formula = this.roll.constructFormula(this.config);
return context;
}

View file

@ -28,4 +28,27 @@ export default class DhActiveEffect extends ActiveEffect {
change.value = Roll.safeEval(Roll.replaceFormulaData(change.value, change.effect.parent));
super.applyField(model, change, field);
}
async toChat(origin) {
const cls = getDocumentClass('ChatMessage');
const systemData = {
title: game.i18n.localize('DAGGERHEART.ActionType.action'),
origin: origin,
img: this.img,
name: this.name,
description: this.description,
actions: []
};
const msg = new cls({
type: 'abilityUse',
user: game.user.id,
system: systemData,
content: await foundry.applications.handlebars.renderTemplate(
'systems/daggerheart/templates/chat/ability-use.hbs',
systemData
)
});
cls.create(msg.toObject());
}
}

View file

@ -97,16 +97,16 @@ export default class DHItem extends foundry.documents.Item {
async use(event) {
const actions = this.system.actions;
let response;
if (actions?.length) {
let action = actions[0];
if (actions.length > 1 && !event?.shiftKey) {
// Actions Choice Dialog
action = await this.selectActionDialog();
}
if (action) response = action.use(event);
if (action) return action.use(event);
}
return response;
return this.toChat();
}
async toChat(origin) {

View file

@ -294,3 +294,15 @@ export const adjustRange = (rangeVal, decrease) => {
const newIndex = decrease ? Math.max(index - 1, 0) : Math.min(index + 1, rangeKeys.length - 1);
return range[rangeKeys[newIndex]];
};
export const updateActorTokens = async (actor, update) => {
await actor.prototypeToken.update(update);
/* Update the tokens in all scenes belonging to Actor */
for (let token of actor.getDependentTokens()) {
const tokenActor = token.baseActor ?? token.actor;
if (tokenActor?.id === actor.id) {
await token.update(update);
}
}
};