(?:)?@UUID\[Compendium.pf2e.spells-srd\.(?:Item\.)?(?:Lay on Hands \(Vs\. Undead\)|IxyD7YdRbSSucxZp)\](?:<\/em>)?<\/p>\n?/g,""),source.type==="spell"&&source.system.slug==="lay-on-hands"&&(source.system.overlays??={a33QUFoKgoOprovO:{_id:"a33QUFoKgoOprovO",name:"Lay on Hands (Vs. Undead)",overlayType:"override",sort:2,system:{damage:{"37YW4ZGhxx7Y2mdI":{applyMod:!1,category:null,formula:"1d6",kinds:["damage"],materials:[],type:"vitality"}},defense:{save:{basic:!0,statistic:"fortitude"}},heightening:{damage:{"37YW4ZGhxx7Y2mdI":"1d6"},interval:1,type:"interval"}}},uLuOg62dVyxvbW66:{_id:"uLuOg62dVyxvbW66",name:"Lay on Hands (Healing)",overlayType:"override",sort:1,system:{damage:{b39tbePoPlJSzLku:{applyMod:!1,category:null,formula:"6",kinds:["healing"],materials:[],type:"vitality"}},heightening:{damage:{b39tbePoPlJSzLku:"6"},interval:1,type:"interval"}}}},source.system.overlays?.uLuOg62dVyxvbW66?.overlayType==="override"&&source.system.overlays.uLuOg62dVyxvbW66.system?.damage?.b39tbePoPlJSzLku&&(source.system.overlays.uLuOg62dVyxvbW66.system.damage.b39tbePoPlJSzLku.kinds=["healing"]))}}class Migration895FixVariantSpellTraits extends MigrationBase{static{__name(this,"Migration895FixVariantSpellTraits")}static{__name2(this,"Migration895FixVariantSpellTraits")}static version=.895;async updateItem(source){if(source.type==="spell")switch(source.system.slug){case"harm":case"heal":this.#fixHarmHeal(source);break;case"elemental-annihilation-wave":case"horizon-thunder-sphere":this.#removeOverlayTraits(source);break;default:this.#fixOtherVariants(source)}}#fixHarmHeal(source){const damage=source.system.damage[0];isObject$1(damage)&&(damage.kinds=["damage","healing"]),source.system.slug==="heal"?source.system.traits.value=["healing","manipulate","vitality"]:source.system.traits.value=["manipulate","void"];const variants=isObject$1(source.system.overlays)?Object.values(source.system.overlays).filter(o=>isObject$1(o)&&isObject$1(o.system?.traits)&&Array.isArray(o.system?.traits.value)):[];for(const variant of variants){if(!variant.system?.traits)continue;const system=variant.system;system.time?.value==="1"?system["-=traits"]=null:(system.traits=source.system.slug==="heal"?{value:["concentrate","healing","manipulate","vitality"]}:{value:["concentrate","manipulate","void"]},system.damage?.["0"]?.formula?.includes("+")?(system.damage[0].kinds=["healing"],system.defense=null):system.time?.value==="2"&&!system.damage?.["0"]&&(system.damage={0:{kinds:["damage"]}}))}}#removeOverlayTraits(source){source.system.traits.value=uniq([...source.system.traits.value,"concentrate","manipulate"]).sort();for(const overlay of Object.values(source.system.overlays??{})){const overlaySystem=overlay.system??{};overlaySystem["-=traits"]=null}}#fixOtherVariants(source){for(const partial of Object.values(source.system.damage).filter(p=>isObject$1(p)))typeof partial.type=="string"&&(partial.type==="healing"||partial.type,partial.type||="untyped");for(const overlay of Object.values(source.system.overlays??{})){const overlaySystem=overlay.system??{};if(overlaySystem.traits?.value&&Array.isArray(overlaySystem.traits.value)){if(!compact(overlaySystem.traits.value).every(t=>["concentrate","manipulate"].includes(t)))continue;overlaySystem.traits.value=uniq([...overlaySystem.traits.value,...source.system.traits.value].sort()),equals(overlaySystem.traits.value,uniq(source.system.traits.value.sort()))&&(overlaySystem["-=traits"]=null)}}}}class Migration896HealingDomains extends MigrationBase{static{__name(this,"Migration896HealingDomains")}static{__name2(this,"Migration896HealingDomains")}static version=.896;async updateItem(source){if(["effect","feat"].includes(source.type))switch(source.system.slug){case"harming-hands":case"healing-hands":{const rule={key:"DamageDice",override:{dieSize:"d10"},predicate:[source.system.slug==="healing-hands"?"item:slug:heal":"item:slug:harm"],selector:["spell-damage","spell-healing"]};source.system.rules=[rule];break}case"effect-curse-of-outpouring-life":{const rule=source.system.rules.find(r=>r.key==="DamageDice");rule&&(rule.selector="spell-healing")}}}}class Migration897ClearLayOnHandsDamage extends MigrationBase{static{__name(this,"Migration897ClearLayOnHandsDamage")}static{__name2(this,"Migration897ClearLayOnHandsDamage")}static version=.897;async updateItem(source){if(source.type!=="spell"||!["lay-on-hands","touch-of-corruption"].includes(source.system.slug??""))return;if(source.system.defense=null,"heightening"in source.system){const system=source.system;system["-=heightening"]=null}const damage=source.system.damage;if(Object.keys(damage).length>0)for(const[key,partial]of Object.entries(damage))partial&&(damage[`-=${key}`]=null);for(const overlay of Object.values(source.system.overlays??{})){if(!isObject$1(overlay)||!isObject$1(overlay.system?.damage))continue;const damagePartials=Object.values(overlay.system?.damage??{});for(const partial of damagePartials.filter(p=>isObject$1(p)))partial?.formula==="6"?partial.kinds=["healing"]:partial.kinds=["damage"]}source.system.slug==="lay-on-hands"?source.system.overlays??={a33QUFoKgoOprovO:{_id:"a33QUFoKgoOprovO",name:"Lay on Hands (Vs. Undead)",overlayType:"override",sort:2,system:{damage:{"37YW4ZGhxx7Y2mdI":{applyMod:!1,category:null,formula:"1d6",kinds:["damage"],materials:[],type:"vitality"}},defense:{save:{basic:!0,statistic:"fortitude"}},heightening:{damage:{"37YW4ZGhxx7Y2mdI":"1d6"},interval:1,type:"interval"}}},uLuOg62dVyxvbW66:{_id:"uLuOg62dVyxvbW66",name:"Lay on Hands (Healing)",overlayType:"override",sort:1,system:{damage:{b39tbePoPlJSzLku:{applyMod:!1,category:null,formula:"6",kinds:["healing"],materials:[],type:"vitality"}},heightening:{damage:{b39tbePoPlJSzLku:"6"},interval:1,type:"interval"}}}}:source.system.overlays??={"2a6Vm4mIjBgrzlO2":{_id:"2a6Vm4mIjBgrzlO2",name:"Touch of Corruption (Vs. Living)",overlayType:"override",sort:2,system:{damage:{Esn7klJ9WRsIFnrE:{applyMod:!1,category:null,formula:"1d6",kinds:["damage"],materials:[],type:"void"}},defense:{save:{basic:!0,statistic:"fortitude"}},heightening:{damage:{Esn7klJ9WRsIFnrE:"1d6"},interval:1,type:"interval"}}},gHIOzknAtexc6GUE:{_id:"gHIOzknAtexc6GUE",name:"Touch of Corruption (Healing)",overlayType:"override",sort:1,system:{damage:{cM137DAlBX1LcWAX:{applyMod:!1,category:null,formula:"6",kinds:["healing"],materials:[],type:"untyped"}},heightening:{damage:{cM137DAlBX1LcWAX:"6"},interval:1,type:"interval"}}}}}}class Migration898NoHBAgain extends MigrationBase{static{__name(this,"Migration898NoHBAgain")}static{__name2(this,"Migration898NoHBAgain")}static version=.898;async updateActor(source){source.system.attributes&&=recursiveReplaceString(source.system.attributes,s=>s.replace(/\bhb_/g,""))}async updateItem(source){source.system.rules=source.system.rules.filter(r=>isObject$1(r)).map(r=>recursiveReplaceString(r,s=>s.replace(/\bhb_/g,"")))}}class Migration899ArmorShieldToShieldShield extends MigrationBase{static{__name(this,"Migration899ArmorShieldToShieldShield")}static{__name2(this,"Migration899ArmorShieldToShieldShield")}static version=.899;#KEYS_TO_REMOVE=["category","checkPenalty","dexCap","group","potencyRune","propertyRune1","propertyRune2","propertyRune3","propertyRune4","resiliencyRune","strength","unequippedBulk"];#BASE_SHIELD_TYPES=new Set(["buckler","casters-targe","dart-shield","fortress-shield","gauntlet-buckler","harnessed-shield","heavy-rondache","hide-shield","klar","meteor-shield","razor-disc","salvo-shield","steel-shield","swordstealer-shield","tower-shield","wooden-shield"]);#SPECIFIC_BASE_ITEMS={"amaranthine-pavise":"tower-shield","arrow-catching-shield":"wooden-shield","broadleaf-shield-greater":null,"broadleaf-shield-major":null,"broadleaf-shield-true":null,"broadleaf-shield":null,"burr-shield":"wooden-shield","clockwork-shield-greater":"steel-shield","clockwork-shield":"steel-shield","cursebreak-bulwark":"tower-shield","dragonslayers-shield":"steel-shield","duelists-beacon":"buckler","exploding-shield":"wooden-shield","floating-shield-greater":"buckler","floating-shield":"buckler","force-shield":"steel-shield","forge-warden":"steel-shield","glamorous-buckler":"buckler","guardian-shield":"steel-shield","helmsmans-recourse-greater":"meteor-shield","helmsmans-recourse-major":"meteor-shield","helmsmans-recourse":"meteor-shield","highhelm-war-shield-greater":"razor-disc","highhelm-war-shield-lesser":"razor-disc","highhelm-war-shield-moderate":"razor-disc","jawbreaker-shield":null,"krakens-guard":"steel-shield","limestone-shield":"tower-shield","lions-shield":"steel-shield","martyrs-shield":"steel-shield","medusas-scream-greater":"steel-shield","medusas-scream":"steel-shield","nethysian-bulwark":"steel-shield","pillow-shield":"steel-shield","rampart-shield":"tower-shield","reflecting-shield":"buckler","reforging-shield":"steel-shield","sanguine-klar-greater":"klar","sanguine-klar":"klar","sapling-shield-greater":"buckler","sapling-shield-lesser":"buckler","sapling-shield-major":"buckler","sapling-shield-minor":"buckler","sapling-shield-moderate":"buckler","sapling-shield-true":"buckler","scale-of-igroon":null,"shining-shield":"wooden-shield","silkspinners-shield":"buckler","spellguard-shield":"steel-shield","spined-shield":"steel-shield","staff-storing-shield-greater":"wooden-shield","staff-storing-shield-major":"wooden-shield","staff-storing-shield-true":"wooden-shield","staff-storing-shield":"wooden-shield","starfall-shield":"heavy-rondache","sturdy-shield-greater":"steel-shield","sturdy-shield-lesser":"steel-shield","sturdy-shield-major":"steel-shield","sturdy-shield-minor":"steel-shield","sturdy-shield-moderate":"steel-shield","sturdy-shield-supreme":"steel-shield","turnabout-shield":"salvo-shield","warding-escutcheon-greater":"tower-shield","warding-escutcheon":"tower-shield","wovenwood-shield-greater":"wooden-shield","wovenwood-shield-lesser":"wooden-shield","wovenwood-shield-major":"wooden-shield","wovenwood-shield-minor":"wooden-shield","wovenwood-shield-moderate":"wooden-shield","wovenwood-shield-true":"wooden-shield"};async updateItem(source){if(isPhysicalData(source)&&source.type!=="backpack"){const system2=source.system;"negateBulk"in system2&&(system2["-=negateBulk"]=null)}if(this.#migrateRules(source),source.type!=="armor")return;const category=source.system.category;category!=="shield"&&(source.system.checkPenalty||=0,source.system.dexCap||=0),source.system.speedPenalty||=0;const system=source.system;if("potency"in system&&(system["-=potency"]=null),category==="shield"){source.img=source.img.replace(/\barmor\.svg$/,"shield.svg"),system.baseItem=this.#BASE_SHIELD_TYPES.has(source.system.slug??"")?source.system.slug:null,system.traits.value=system.traits.value.map(t=>t==="hefty-14"?"hefty-2":t),system.traits.integrated=system.traits.value.some(t=>t.startsWith("integrated"))?{runes:{potency:0,striking:0,property:[]},versatile:null}:null,system.usage={value:"held-in-one-hand"},system.runes={reinforcing:0},this.#validateOrRemoveMaterial(system),this.#setSpecificShieldData(system),source.type="shield";for(const key of this.#KEYS_TO_REMOVE)key in system&&(system[`-=${key}`]=null)}}#migrateRules(source){const shieldAlterations=source.system.rules.filter(r=>r.key==="ItemAlteration"&&r.itemType==="armor"&&Array.isArray(r.predicate)&&r.predicate.includes("item:category:shield"));for(const rule of shieldAlterations)rule.itemType="shield",rule.predicate=rule.predicate.filter(s=>s!=="item:category:shield")}#validateOrRemoveMaterial(system){if(!system.material.type){system.material.grade=null;return}if(!system.material.grade){system.material.type=null;return}const baseItem=system.baseItem??"",{type}=system.material,BUCKLERS=["buckler","casters-targe","dart-shield","gauntlet-buckler","heavy-rondache","klar"],bucklerMaterials=["abysium","adamantine","cold-iron","darkwood","djezet","inubrix","mithral","noqual","orichalcum","siccatite","silver"],MATERIALS={buckler:bucklerMaterials,towerShield:["darkwood"],shield:[...bucklerMaterials,"keep-stone"]};["tower-shield","fortress-shield"].includes(baseItem)&&!MATERIALS.towerShield.includes(type)||BUCKLERS.includes(baseItem)&&!MATERIALS.buckler.includes(type)?(system.material.type=null,system.material.grade=null):MATERIALS.shield.includes(type)||(system.material.type=null,system.material.grade=null)}#setSpecificShieldData(system){if(system.baseItem||!system.slug)return;const setSpecific=__name2(()=>{system.specific={material:foundry.utils.deepClone(system.material),runes:{reinforcing:0},integrated:system.traits.integrated?foundry.utils.deepClone({runes:system.traits.integrated.runes}):null}},"setSpecific");switch(system.slug){case"indestructible-shield":system.baseItem="steel-shield",system.material={type:"adamantine",grade:"high"},setSpecific();break;case"kizidhars-shield":system.baseItem="wooden-shield",system.material={type:"duskwood",grade:"standard"},setSpecific();break;case"lodestone-shield":system.baseItem="steel-shield",system.material={type:"cold-iron",grade:"standard"},setSpecific();break;default:system.baseItem=this.#SPECIFIC_BASE_ITEMS[system.slug??""]??null,system.slug in this.#SPECIFIC_BASE_ITEMS&&setSpecific()}}}class Migration900ClassSpellcastingProficiency extends MigrationBase{static{__name(this,"Migration900ClassSpellcastingProficiency")}static{__name2(this,"Migration900ClassSpellcastingProficiency")}static version=.9;async updateActor(source){if(source.type==="character"&&source.system.proficiencies){const proficiencies=source.system.proficiencies;"spellcasting"in proficiencies&&(proficiencies["-=spellcasting"]=null)}}async updateItem(source){if(source.type==="class"){const aeLikeIncrease=source.system.rules.find(r=>r.key==="ActiveEffectLike"&&r.path==="system.proficiencies.spellcasting.rank");aeLikeIncrease?(source.system.spellcasting=Math.max(1,source.system.spellcasting??0),source.system.rules.splice(source.system.rules.indexOf(aeLikeIncrease),1)):["sorcerer","summoner","witch"].includes(source.system.slug??"")?source.system.spellcasting=1:source.system.spellcasting=Math.max(0,source.system.spellcasting??0)}if(source.type==="feat"){const baseRule={key:"ActiveEffectLike",mode:"upgrade",path:"system.proficiencies.spellcasting.rank"};switch(source.system.slug){case"bloodline":case"patron":source.system.rules=source.system.rules.filter(r=>r.path!=="system.proficiencies.spellcasting.rank");break;case"expert-spellcaster":source.system.rules=[{...baseRule,value:2}],source.system.publication={...source.system.publication??{},license:"ORC",remaster:!0,title:"Pathfinder Player Core"};break;case"expert-spellcasting":source.system.rules=[{...baseRule,value:2}];break;case"master-spellcaster":source.system.rules=[{...baseRule,value:3}],source.system.publication={...source.system.publication??{},license:"ORC",remaster:!0,title:"Pathfinder Player Core"};break;case"master-spellcasting":source.system.rules=[{...baseRule,value:3}];break;case"legendary-spellcaster":source.system.rules=[{...baseRule,value:4}],source.system.publication={...source.system.publication??{},license:"ORC",remaster:!0,title:"Pathfinder Player Core"};break}}}}class Migration901ReorganizeBulkData extends MigrationBase{static{__name(this,"Migration901ReorganizeBulkData")}static{__name2(this,"Migration901ReorganizeBulkData")}static version=.901;async updateItem(source){if(this.#migrateRules(source),!isPhysicalData(source))return;const system=source.system;if(system.bulk??={value:0},"equippedBulk"in system&&(["armor","backpack"].includes(source.type)&&(system.bulk.value=this.#bulkStringToNumber(system.equippedBulk)),system["-=equippedBulk"]=null,system.slug==="sack"?(system.usage={value:"held-in-one-hand"},system.bulk.value=.1):/bag-of-(?:devouring|holding|weasels)|spacious-pouch/.test(system.slug??"")?system.bulk.value=1:system.slug==="sleeves-of-storage"&&(system.bulk.value=.1)),"weight"in system){if(source.type==="backpack"){const usage=system.usage?.value??"";source.system.bulk.heldOrStowed=["held-in-one-hand","held-in-two-hands"].includes(usage)?Math.max(system.bulk.value,this.#bulkStringToNumber(system.weight)):this.#bulkStringToNumber(system.weight)}else source.type!=="armor"&&(source.system.bulk.value=this.#bulkStringToNumber(system.weight));system["-=weight"]=null}"bulkCapacity"in system&&(source.type==="backpack"&&(source.system.bulk.capacity=isObject$1(system.bulkCapacity)&&Math.floor(Math.abs(Number(system.bulkCapacity.value)))||0),system["-=bulkCapacity"]=null),"negateBulk"in system&&(source.type==="backpack"&&(source.system.bulk.ignored=isObject$1(system.negateBulk)&&Math.floor(Math.abs(Number(system.negateBulk.value)))||0),system["-=negateBulk"]=null)}#migrateRules(source){const itemAlterations=source.system.rules.filter(r=>r.key==="ItemAlteration"&&typeof r.property=="string");for(const rule of itemAlterations)(rule.itemType==="armor"&&rule.property==="bulk-worn"||rule.itemType!=="armor"&&rule.property==="bulk-value")&&(rule.property="bulk");source.system.rules=source.system.rules.filter(r=>r.key==="ItemAlteration"&&typeof r.property=="string"?!["bulk-worn","bulk-value"].includes(r.property):!0)}#bulkStringToNumber(bulkObject){if(!isObject$1(bulkObject))return 0;const bulkString=String(bulkObject.value||"-").toLocaleUpperCase("en");switch(bulkString){case"-":return 0;case"L":return .1;default:{const numericValue=Number(bulkString);return Number.isInteger(numericValue)?Math.abs(numericValue):0}}}}class Migration902DuskwoodDawnsilver extends MigrationBase{static{__name(this,"Migration902DuskwoodDawnsilver")}static{__name2(this,"Migration902DuskwoodDawnsilver")}static version=.902;#replaceStrings(data){return recursiveReplaceString(data,s=>s.replace(/\bdarkwood\b/g,"duskwood").replace(/Darkwood\b/g,"Duskwood").replace(/\bmithral\b/g,"dawnsilver").replace(/Mithral\b/g,"Dawnsilver").replace(/\bdawnsilver(.)tree\b/g,"mithral$1tree").replace(/\bDawnsilver Tree\b/g,"Mithral Tree").replace(/\bdawnsilver(.)golem/g,"mithral$1golem").replace(/\bDawnsilver(.)golem/g,"Mithral$1golem"))}async updateActor(source){source.system=this.#replaceStrings(source.system),source.flags.pf2e&&=this.#replaceStrings(source.flags.pf2e)}async updateItem(source){source.system=this.#replaceStrings(source.system),source.flags.pf2e&&=this.#replaceStrings(source.flags.pf2e)}}class Migration903PhysicalNumericData extends MigrationBase{static{__name(this,"Migration903PhysicalNumericData")}static{__name2(this,"Migration903PhysicalNumericData")}static version=.903;async updateItem(source){if(source.type==="armor")source.system.dexCap||=0,source.system.strength||=source.system.category==="unarmored"?null:0;else if(source.type==="backpack"){const slug=source.system.slug??"";/bag-of-(?:devouring|holding|weasels)|spacious-pouch/.test(slug)&&(source.system.bulk.value||=1)}}}class Migration904UndercommonToSakvroth extends MigrationBase{static{__name(this,"Migration904UndercommonToSakvroth")}static{__name2(this,"Migration904UndercommonToSakvroth")}static version=.904;#replaceStrings(data){return recursiveReplaceString(data,s=>s.replace(/\bundercommon\b/g,"sakvroth").replace(/\bUndercommon\b/g,"Sakvroth"))}async updateActor(source){source.system=this.#replaceStrings(source.system),source.flags.pf2e&&=this.#replaceStrings(source.flags.pf2e)}async updateItem(source){source.system=this.#replaceStrings(source.system),source.flags.pf2e&&=this.#replaceStrings(source.flags.pf2e)}}class Migration905UnpersistUsage extends MigrationBase{static{__name(this,"Migration905UnpersistUsage")}static{__name2(this,"Migration905UnpersistUsage")}static version=.905;async updateItem(source){if(!isPhysicalData(source)){"usage"in source.system&&(source.system["-=usage"]=null);return}itemIsOfType(source,"armor","shield","treasure")&&"usage"in source.system?source.system["-=usage"]=null:source.system.usage?.value===""&&(source.system.usage.value="carried")}}const CONSUMABLE_CATEGORIES=new Set(["ammo","catalyst","drug","elixir","fulu","gadget","mutagen","oil","other","poison","potion","scroll","snare","talisman","toolkit","wand"]),DAMAGE_OR_HEALING_CONSUMABLE_CATEGORIES=new Set(["ammo","elixir","oil","other","poison","potion","snare"]),DAMAGE_ONLY_CONSUMABLE_CATEGORIES=new Set(["ammo","snare"]),AMMO_STACK_GROUPS=new Set(["arrows","blowgunDarts","bolts","rounds5","rounds10","slingBullets","sprayPellets","woodenTaws"]);class Migration906LimitStackGroup extends MigrationBase{static{__name(this,"Migration906LimitStackGroup")}static{__name2(this,"Migration906LimitStackGroup")}static version=.906;async updateItem(source){if((!isPhysicalData(source)||!itemIsOfType(source,"consumable","treasure"))&&"stackGroup"in source.system)source.system["-=stackGroup"]=null;else if(source.type==="consumable"){const category="consumableType"in source.system&&isObject$1(source.system.consumableType)?String(source.system.consumableType.value):source.system.category;source.system.stackGroup=category==="ammo"&&setHasElement(AMMO_STACK_GROUPS,source.system.stackGroup)?source.system.stackGroup:null}else source.type==="treasure"&&(source.system.stackGroup=["coins","gems"].includes(source.system.stackGroup??"")?source.system.stackGroup:null);!("game"in globalThis)&&"stackGroup"in source.system&&!source.system.stackGroup&&(source.system["-=stackGroup"]=null)}}class Migration907RestructureArmorWeaponRunes extends MigrationBase{static{__name(this,"Migration907RestructureArmorWeaponRunes")}static{__name2(this,"Migration907RestructureArmorWeaponRunes")}static version=.907;#RESILIENT_RUNE_CONVERSION=new Map([["resilient",1],["greaterResilient",2],["majorResilient",3]]);#STRIKING_RUNE_CONVERSION=new Map([["striking",1],["greaterStriking",2],["majorStriking",3]]);#RUNE_DELETIONS=["potencyRune","resiliencyRune","strikingRune","propertyRune1","propertyRune2","propertyRune3","propertyRune4"];#cleanupSpecificData(system){const specificData=system.specific;isObject$1(specificData)&&("price"in specificData&&(specificData["-=price"]=null),specificData.value===!0?(specificData["-=value"]=null,specificData.runes=foundry.utils.deepClone(system.runes),isObject$1(specificData.material)&&"precious"in specificData.material?(specificData.material["-=precious"]=null,specificData.material=foundry.utils.mergeObject(specificData.material,foundry.utils.deepClone(system.material))):specificData.material=foundry.utils.deepClone(system.material)):"value"in specificData&&(system.specific=null))}#getRuneValue(system,key){if(!isObject$1(system))throw ErrorPF2e("Unexpected system data");const runeObject=system[key];return isObject$1(runeObject)?runeObject.value:null}async updateItem(source){if(itemIsOfType(source,"armor","weapon")&&(source.type==="armor"?source.system.runes??={potency:0,resilient:0,property:[]}:source.type==="weapon"&&(source.system.runes??={potency:0,striking:0,property:[]}),"potencyRune"in source.system&&isObject$1(source.system.potencyRune))){const potencyRune=Number(source.system.potencyRune.value)||0;source.system.runes.potency=tupleHasValue([1,2,3,4],potencyRune)?potencyRune:0}if(source.type==="armor"){if("resiliencyRune"in source.system&&isObject$1(source.system.resiliencyRune)){const resilientRune=String(source.system.resiliencyRune.value),numericValue=this.#RESILIENT_RUNE_CONVERSION.get(resilientRune)??0;source.system.runes.resilient=numericValue}for(const runeKey of["propertyRune1","propertyRune2","propertyRune3","propertyRune4"]){if(!(runeKey in source.system))continue;const runeValue=this.#getRuneValue(source.system,runeKey);setHasElement(ARMOR_PROPERTY_RUNE_TYPES,runeValue)&&(source.system.runes.property.push(runeValue),source.system.runes.property=uniq(compact(source.system.runes.property)),source.system.runes.property.length=Math.min(source.system.runes.property.length,4))}this.#cleanupSpecificData(source.system)}else if(source.type==="weapon"){if("strikingRune"in source.system&&isObject$1(source.system.strikingRune)){const strikingRune=String(source.system.strikingRune.value),numericValue=this.#STRIKING_RUNE_CONVERSION.get(strikingRune)??0;source.system.runes.striking=numericValue}for(const runeKey of["propertyRune1","propertyRune2","propertyRune3","propertyRune4"]){if(!(runeKey in source.system))continue;const runeValue=this.#getRuneValue(source.system,runeKey);setHasElement(WEAPON_PROPERTY_RUNE_TYPES,runeValue)&&(source.system.runes.property.push(runeValue),source.system.runes.property=uniq(compact(source.system.runes.property)),source.system.runes.property.length=Math.min(source.system.runes.property.length,4))}this.#cleanupSpecificData(source.system)}for(const deletion of this.#RUNE_DELETIONS)deletion in source.system&&(source.system[`-=${deletion}`]=null)}}class Migration908TrueGangUp extends MigrationBase{static{__name(this,"Migration908TrueGangUp")}static{__name2(this,"Migration908TrueGangUp")}static version=.908;async updateItem(source){if((source.system.slug??"")==="gang-up"&&source.type==="feat"){const rule={key:"ActiveEffectLike",mode:"add",path:"system.attributes.flanking.canGangUp",value:!0};source.system.rules=[rule]}}}class Migration909RefineConsumableData extends MigrationBase{static{__name(this,"Migration909RefineConsumableData")}static{__name2(this,"Migration909RefineConsumableData")}static version=.909;async updateItem(source){if(source.type!=="consumable")return;const system=source.system,autoDestroy=isObject$1(system.autoDestroy)?!!system.autoDestroy.value:system.uses?.autoDestroy??!0;if("autoDestroy"in system&&(system["-=autoDestroy"]=null),"charges"in system){if(isObject$1(system.charges)){const value=Math.min(Math.max(Math.floor(Number(system.charges.value)||0),0),9999),max=Math.min(Math.max(Math.floor(Number(system.charges.max)||0),0),9999);system.uses={value,max,autoDestroy},system.uses.max===0&&(system.uses.value=1,system.uses.max=1)}system["-=charges"]=null}if("consumableType"in system){if(isObject$1(system.consumableType)){const category=system.consumableType.value==="tool"?"toolkit":system.consumableType.value;system.category=setHasElement(CONSUMABLE_CATEGORIES,category)?category:"other"}system["-=consumableType"]=null}if(system.slug==="fang-snare"&&(system.category="snare"),"consume"in system){if(isObject$1(system.consume)){const traits=source.system.traits.value,formula=typeof system.consume.value=="string"&&system.consume.value.trim()||null,type=formula?this.#determineDamageType(system.category,traits,system.description.value):null,kind=DAMAGE_ONLY_CONSUMABLE_CATEGORIES.has(system.category)||!["vitality","void","untyped"].includes(type??"")?"damage":"healing";system.damage=formula===null||type===null?null:{formula,kind,type}}system["-=consume"]=null}DAMAGE_OR_HEALING_CONSUMABLE_CATEGORIES.has(system.category)||(system.damage=null)}#determineDamageType(category,traits,description){const damageTypes2=Array.from(DAMAGE_TYPES),fromTraits=damageTypes2.find(t=>traits.includes(t)),fromDescription=!fromTraits&&category==="snare"?damageTypes2.find(t=>new RegExp(String.raw`\b${t}\b`).test(description)):null;return fromTraits??fromDescription??"untyped"}}class Migration910EdictsAnathemaArrays extends MigrationBase{static{__name(this,"Migration910EdictsAnathemaArrays")}static{__name2(this,"Migration910EdictsAnathemaArrays")}static version=.91;async updateActor(source){if(source.type!=="character")return;const biography=source.system.details.biography;biography.edicts=compact(typeof biography.edicts=="string"?[biography.edicts]:biography.edicts??[]),biography.anathema=compact(typeof biography.anathema=="string"?[biography.anathema]:biography.anathema??[])}}class Migration911CoinBulk extends MigrationBase{static{__name(this,"Migration911CoinBulk")}static{__name2(this,"Migration911CoinBulk")}static version=.911;async updateItem(source){source.type==="treasure"&&source.system.stackGroup==="coins"&&(source.system.bulk.value=1)}}const Migrations=Object.freeze(Object.defineProperty({__proto__:null,Migration634PurgeMartialItems,Migration635NumifyACAndQuantity,Migration636NumifyArmorData,Migration637CleanMeleeItems,Migration638SpellComponents,Migration639NormalizeLevelAndPrice,Migration640CantripsAreNotZeroLevel,Migration641SovereignSteelValue,Migration642TrackSchemaVersion,Migration643HazardLevel,Migration644SpellcastingCategory,Migration645TokenImageSize,Migration646UpdateInlineLinks,Migration647FixPCSenses,Migration648RemoveInvestedProperty,Migration649FocusToActor,Migration650StringifyWeaponProperties,Migration651EphemeralFocusPool,Migration652KillHalcyonTradition,Migration653AEstoREs,Migration654ActionTypeAndCount,Migration655CreatureTokenSizes,Migration656OtherFocusPoolSources,Migration657RemoveSetProperty,Migration658MonkUnarmoredProficiency,Migration659MultipleDamageRows,Migration660DerivedSpellTraits,Migration661NumifyVehicleDimensions,Migration662LinkToActorSizeDefaults,Migration663FixSpellDamage,Migration664DeleteCUBConditions,Migration665HandwrapsCorrections,Migration666UsageAndStowingContainers,Migration667HPSubProperties,Migration668ArmorSpeedPenalty,Migration669NPCAttackEffects,Migration670AncestryVision,Migration670NoCustomTrait,Migration671NoPCItemsOnNonPCs,Migration672RemoveNPCBaseProperties,Migration673RemoveBulwarkREs,Migration674StableHomebrewTagIDs,Migration675FlatModifierAEsToREs,Migration676ReplaceItemsWithRELikeAEs,Migration677RuleValueDataRefs,Migration678SeparateNPCAttackTraits,Migration679TowerShieldSpeedPenalty,Migration680SetWeaponHands,Migration681GiantLanguageToJotun,Migration682BiographyFields,Migration683FlavorTextToPublicNotes,Migration684RationsToConsumable,Migration685FixMeleeUsageTraits,Migration686HeroPointsToResources,Migration687FamiliarityAEsToREs,Migration688ClampSpellLevel,Migration689EncumberanceActiveEffects,Migration690InitiativeTiebreakItems,Migration691WeaponRangeAbilityCategoryGroup,Migration692CraftingEntryFeatReplacement,Migration693ArmorCategoryGroup,Migration694RetireSystemTokenSettings,Migration695SummonToSummoned,Migration696FlatAbilityModifiers,Migration697WeaponReachTrait,Migration698RemoveDerivedActorTraits,Migration699ItemDescriptionEmptyString,Migration700SingleClassFeatures,Migration701ModifierNameToSlug,Migration702REFormulasAtInstanceLevel,Migration703SpellDamageStructure,Migration704MartialProficiencyRE,Migration705GunslingerCatchUp,Migration706FormulasAtInstanceLevelEverythingElse,Migration707BracketedFormulasAtInstanceLevel,Migration708SpecificRuleLabel,Migration709REFormulasAtInstanceLevelRedux,Migration710RarityToString,Migration711HeritageItems,Migration712ActorShieldStructure,Migration713FistToStrikeRE,Migration714RangeIncrementREs,Migration715DangerousSorcery,Migration716StrikeDamageSelector,Migration717TakeFeatLimits,Migration718CarryType,Migration719ShrugFlanking,Migration720UpdateSpellDescriptions,Migration721SetReloadValues,Migration722CraftingSystemData,Migration723CumulativeItemBonuses,Migration724CraftingMaxItemLevel,Migration725QuickClimbREs,Migration726JournalSetting,Migration727TrimSelfRollOptions,Migration728FlattenPhysicalProperties,Migration729CumulativeItemBonusCleanup,Migration730DeruneHandwraps,Migration731TogglePropertyToRollOption,Migration732FixDedicationFeatTypes,Migration733ItemBonusFromEquipment,Migration734SpellLocationPropsAndSignature,Migration735FirearmAmmoAlchemical,Migration736RemoveBrokenThreshold,Migration737NormalizeRuleElementKeys,Migration738UpdateLaughingShadow,Migration739RecoveryCheckDC,Migration740MaxTakable,Migration741RollOptionToggleToItem,Migration742RMAbilityBoostLevels,Migration743FixWeaknessStructure,Migration744MigrateSpellHeighten,Migration745EffectTargetToChoiceSet,Migration746StandardizePricing,Migration747FixedHeightening,Migration748BatchConsumablePricing,Migration749AssuranceREs,Migration750FixCorruptedPrice,Migration751ResetRollOptions,Migration752StrikeVsWeaponTraits,Migration753WeaponReloadTimes,Migration754MightyBulwarkAdjustModifiers,Migration755GrantIdsToData,Migration756RMStoredResourceMaxes,Migration757HillockHalfling,Migration758PrunePCAttributes,Migration759CritSpecRE,Migration760SeparateNoteTitle,Migration761ShotRules,Migration762UpdateBackgroundItems,Migration763RestoreAnimalStrikeOptions,Migration764PanacheVivaciousREs,Migration765ChoiceOwnedItemTypes,Migration766WipeURLSources,Migration767ConvertVoluntaryFlaws,Migration768AddNewAuras,Migration769NoUniversalistFocusPool,Migration770REDataToSystem,Migration771SpellVariantsToSystem,Migration772V10EmbeddedSpellData,Migration773ReligiousSymbolUsage,Migration774UnpersistCraftingEntries,Migration775AgileFinesseRanged,Migration776SlugifyConditionOverrides,Migration777HandOfTheApprentice,Migration778RenameRetiredPackRefs,Migration779EliteWeak,Migration780NumifySpeeds,Migration781SuppressNoCrowbar,Migration782UnnestActorTraits,Migration783RemoveClassSkillAELikes,Migration784CompBrowserPackSetting,Migration785ABCKitItemUUIDs,Migration786RemoveIdentifiedData,Migration787ResolvablesToSystem,Migration788UpdateTanglefootBags,Migration789UpdatePreciseStrike,Migration790MultipleClassDCs,Migration791RuffianHands,Migration792RemoveTokenAELikes,Migration793MakePredicatesArrays,Migration794AddWildShapeChoices,Migration795CleanupFlatFootedToggle,Migration796ItemGrantsToObjects,Migration797MetagameSetting,Migration798WeaponToItemStatements,Migration799RMRecallKnowledgeDuplicates,Migration800SelfEffectPanacheRage,Migration801ColorDarkvision,Migration802StripFeatActionCategory,Migration803NormalizeSpellArea,Migration804RemoveConsumableProperties,Migration805InlineDamageRolls,Migration806TorchImprovisedOtherTags,Migration807RMActivatedEffectFields,Migration808CountDamageDice,Migration809AutomatonEnhancements,Migration810LootDescriptionValue,Migration811InlineDamageRollsPersistent,Migration812RestructureIWR,Migration813NormalizeColdIron,Migration814CalculatedExpandedSplash,Migration815ConsumableDataCleanup,Migration816AlchemistResearchFields,Migration817FieldDiscoveryPredicates,Migration818BasicUndeadNegativeHealing,Migration819SpinTaleAdventureSpecific,Migration820RemoveUnusedTraitsData,Migration821InlineDamageRolls,Migration822BladeAllyConsolidation,Migration823HeritageAncestrySlug,Migration824SneakAttackDamageSource,Migration825KhakkharaFengHuoLun,Migration826GutConditionData,Migration827FixTVShieldTraits,Migration828PruneInvalidTraits,Migration829RMRitualEntries,Migration830BarbarianRework,Migration831ClericDoctrines,Migration832ChoiceSetFlags,Migration833AddRogueToysFixPrecision,Migration834FeatCategories,Migration835InitiativeLongform,Migration836EnergizingConsolidation,Migration837MoveHazardBookSources,Migration838StrikeAttackRollSelector,Migration839ActionCategories,Migration840ArrayWrapPredicates,Migration841V11UUIDFormat,Migration842NumifyNumericSettings,Migration843RMArmorCustomModifiers,Migration844DeityDomainUUIDs,Migration845EmptySpellConsumables,Migration846SpellSchoolOptional,Migration847TempHPRuleEvents,Migration848NumericArmorProperties,Migration849DeleteBrokenThreshold,Migration850FlatFootedToOffGuard,Migration851JustInnovationId,Migration852AbilityScoresToModifiers,Migration853RemasterLanguages,Migration854BracketedAbilityScoresToModifiers,Migration855ApexEquipmentSystemData,Migration856NoSystemDotCustom,Migration857WeaponSpecializationRE,Migration858FakeWeaponSpecialization,Migration859MaterialTypeGrade,Migration860RMGroup,Migration861AuraColorsToAppearance,Migration862SpecificMagicArmor,Migration863FixMisspelledOrganaizationsProperty,Migration864RemoveWeaponMAP,Migration865VitalityVoid,Migration866LinkToActorSizeAgain,Migration867DamageRollDomainFix,Migration868StrikeRERange,Migration869RefreshMightyBulwark,Migration870MartialToProficiencies,Migration871MigrateRollActionMacroParams,Migration872MoveSchemaProperty,Migration873RemoveBonusBulkLimit,Migration874MoveStaminaStuff,Migration875SetInnovationIdEarly,Migration876FeatLevelTaken,Migration877PublicationData,Migration878TakeABreather,Migration879DeviseAStratagemAndFriends,Migration880SplitShowDialogsSettings,Migration881NoHBPrefix,Migration882SpellDataReorganization,Migration883BanishAlignment,Migration884UnifiedSpellcasting,Migration885ConvertAlignmentDamage,Migration886CrossbowGroup,Migration887RedirectSpellLinks,Migration888RemasterLanguagesHeritages,Migration889RemoveFocusMaxIncreases,Migration890RMClassItemClassDC,Migration891DruidicToWildsong,Migration892ChoiceSetREAdjustNameValue,Migration893NoHBPrefixSettings,Migration894NoLayOnHandsVsUndead,Migration895FixVariantSpellTraits,Migration896HealingDomains,Migration897ClearLayOnHandsDamage,Migration898NoHBAgain,Migration899ArmorShieldToShieldShield,Migration900ClassSpellcastingProficiency,Migration901ReorganizeBulkData,Migration902DuskwoodDawnsilver,Migration903PhysicalNumericData,Migration904UndercommonToSakvroth,Migration905UnpersistUsage,Migration906LimitStackGroup,Migration907RestructureArmorWeaponRunes,Migration908TrueGangUp,Migration909RefineConsumableData,Migration910EdictsAnathemaArrays,Migration911CoinBulk},Symbol.toStringTag,{value:"Module"}));class MigrationList{static{__name(this,"MigrationList")}static{__name2(this,"MigrationList")}static#list=Object.values(Migrations);static get latestVersion(){return Math.max(...this.#list.map(M=>M.version))}static constructAll(){return this.#list.map(M=>new M)}static constructFromVersion(version){const minVersion=Number(version)||MigrationRunner.RECOMMENDED_SAFE_VERSION;return this.#list.filter(M=>M.version>minVersion).map(M=>new M)}static constructRange(min,max=1/0){return this.#list.filter(M=>M.version>=min&&M.version<=max).map(M=>new M)}}class WeaponDamagePF2e{static{__name(this,"WeaponDamagePF2e")}static{__name2(this,"WeaponDamagePF2e")}static async fromNPCAttack({attack,actor,context}){const{baseDamage}=attack,secondaryInstances=Object.values(attack.system.damageRolls).map(this.npcDamageToWeaponDamage).filter(d=>!equals(d,baseDamage)),damageDice=[],modifiers=[],labelFromCategory={null:"",persistent:"",precision:"PF2E.Damage.Precision",splash:"PF2E.WeaponSplashDamageLabel"};for(const instance of secondaryInstances){const{damageType}=instance;instance.dice>0&&instance.die&&damageDice.push(new DamageDicePF2e({slug:"base",label:labelFromCategory[instance.category??"null"],selector:"damage",diceNumber:instance.dice,dieSize:instance.die,damageType:instance.damageType,category:instance.category})),instance.modifier&&modifiers.push(new ModifierPF2e({label:labelFromCategory[instance.category??"null"],modifier:instance.modifier,damageType,damageCategory:instance.category}))}return WeaponDamagePF2e.calculate({weapon:attack,actor,damageDice,modifiers,context})}static async calculate({weapon,actor,damageDice=[],modifiers=[],weaponPotency=null,context}){const{baseDamage}=weapon,{options}=context,domains=context.domains;if(baseDamage.die===null&&baseDamage.modifier>0)baseDamage.dice=0;else if(!weapon.dealsDamage)return null;const weaponTraits2=weapon.system.traits.value,materialTraits=weapon.isOfType("melee")?weapon.system.traits.value.filter(t=>t in CONFIG.PF2E.materialDamageEffects):[];for(const trait of weaponTraits2)options.add(trait);const isMelee=!!weapon.isMelee;if(options.add(isMelee?"melee":"ranged"),actor.isOfType("character")&&weapon.isOfType("weapon")){const attributeDomains=ATTRIBUTE_ABBREVIATIONS.map(a=>`${a}-damage`),domain=domains.find(d=>attributeDomains.has(d)),strengthModValue=actor.abilities.str.mod,modifierValue=domain==="str-damage"?strengthModValue<0||!weaponTraits2.some(t=>t==="propulsive")?strengthModValue:Math.floor(strengthModValue/2):null;if(typeof modifierValue=="number"){const strModifier=createAttributeModifier({actor,attribute:"str",domains,max:modifierValue});modifiers.push(strModifier)}}for(const rule of actor.rules.filter(r=>!r.ignored))rule.beforeRoll?.(domains,options);const splashDamage=weapon.isOfType("weapon")?Number(weapon.system.splashDamage?.value):0;if(splashDamage>0){const modifier=new ModifierPF2e({slug:"splash",label:"PF2E.WeaponSplashDamageLabel",modifier:splashDamage,damageCategory:"splash",adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,domains,"splash")});modifiers.push(modifier)}if(weapon.isOfType("weapon")){weaponTraits2.includes("kickback")&&modifiers.push(new ModifierPF2e({slug:"kickback",label:CONFIG.PF2E.weaponTraits.kickback,modifier:1,adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,domains,"kickback")}));const handsHeld=weapon.system.equipped.handsHeld??0,baseDieFaces=Number(baseDamage.die?.replace("d","")??"NaN"),twoHandSize=weaponTraits2.find(t=>t.startsWith("two-hand-"))?.replace("two-hand-",""),twoHandFaces=Number(twoHandSize?.replace("d","")??"NaN");if(handsHeld===2&&setHasElement(DAMAGE_DIE_FACES,twoHandSize)&&twoHandFaces>baseDieFaces&&(baseDamage.die=twoHandSize),weaponTraits2.find(t=>t.startsWith("scatter-"))&&baseDamage.die){const modifier=new ModifierPF2e({slug:"scatter",label:"PF2E.Damage.Scatter",modifier:baseDamage.dice,damageCategory:"splash",adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,domains,"scatter")});modifiers.push(modifier)}const bonusDamage=Number(weapon.system.bonusDamage?.value);bonusDamage>0&&modifiers.push(new ModifierPF2e({label:"PF2E.WeaponBonusDamageLabel",modifier:bonusDamage}));const customDamage=weapon.system.property1,normalDice=customDamage.dice??0;if(normalDice>0){const damageType=customDamage.damageType||null;damageDice.push(new DamageDicePF2e({selector:`${weapon.id}-damage`,slug:"custom",label:"PF2E.WeaponCustomDamageLabel",diceNumber:normalDice,dieSize:customDamage.die,damageType}))}const critDice=customDamage.critDice??0;if(critDice>0){const damageType=customDamage.critDamageType||null;damageDice.push(new DamageDicePF2e({selector:`${weapon.id}-damage`,slug:"custom-critical",label:"PF2E.WeaponCustomDamageLabel",diceNumber:critDice,dieSize:customDamage.critDie,damageType,critical:!0}))}}const potency=weaponPotency?.bonus??0,strikingSynthetic=domains.flatMap(key=>actor.synthetics.striking[key]??[]).filter(wp=>wp.predicate.test(options)).reduce((highest,current)=>highest&&highest.bonus>current.bonus?highest:current,null);strikingSynthetic&&baseDamage.die&&(weapon.isOfType("melee")||strikingSynthetic.bonus>weapon.system.runes.striking)&&(damageDice.push(new DamageDicePF2e({selector:`${weapon.id}-damage`,slug:"striking",label:strikingSynthetic.label,diceNumber:strikingSynthetic.bonus})),weapon.isOfType("weapon")&&(weapon.system.damage.dice-=weapon.system.runes.striking,weapon.system.runes.striking=0));const critSpecEffect=(()=>{const critSpecs=actor.synthetics.criticalSpecalizations,standard=critSpecs.standard.reduceRight((result,cs)=>result??cs?.(weapon,options),null),alternate=critSpecs.alternate.reduceRight((result,cs)=>result??cs?.(weapon,options),null);return standard?alternate??standard:[]})();critSpecEffect.length>0&&options.add("critical-specialization"),modifiers.push(...critSpecEffect.filter(e=>e instanceof ModifierPF2e)),damageDice.push(...critSpecEffect.filter(e=>e instanceof DamageDicePF2e));const propertyRunes=weapon.system.runes.property;damageDice.push(...getPropertyRuneDice(propertyRunes,options));const propertyRuneAdjustments=getPropertyRuneModifierAdjustments(propertyRunes),ignoredResistances=propertyRunes.flatMap(r=>RUNE_DATA.weapon.property[r].damage?.ignoredResistances??[]);if(weaponTraits2.some(t=>t==="backstabber")&&options.has("target:condition:off-guard")){const modifier=new ModifierPF2e({label:CONFIG.PF2E.weaponTraits.backstabber,slug:"backstabber",modifier:potency>2?2:1,damageCategory:"precision",adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,domains,"backstabber")});modifiers.push(modifier)}const traitLabels=CONFIG.PF2E.weaponTraits,deadlyTraits=weaponTraits2.filter(t=>t.startsWith("deadly-")),strikingDice=(()=>{if(weapon.isOfType("weapon")){const weaponStrikingDice=weapon.system.damage.dice-weapon._source.system.damage.dice;return strikingSynthetic&&strikingSynthetic.bonus>weaponStrikingDice?strikingSynthetic.bonus:weaponStrikingDice}else return strikingSynthetic?.bonus??0})();for(const slug of deadlyTraits){const diceNumber=(()=>{const baseNumber=Number(/-(\d)d\d{1,2}$/.exec(slug)?.at(1))||1;return strikingDice>1?strikingDice*baseNumber:baseNumber})();damageDice.push(new DamageDicePF2e({selector:`${weapon.id}-damage`,slug,label:traitLabels[slug],damageType:baseDamage.damageType,diceNumber,dieSize:/-\d?(d\d{1,2})$/.exec(slug)?.at(1)??baseDamage.die,critical:!0}))}for(const trait of weaponTraits2.filter(t=>t.startsWith("fatal-d"))){const dieSize=trait.substring(trait.indexOf("-")+1);damageDice.push(new DamageDicePF2e({selector:`${weapon.id}-damage`,slug:trait,label:traitLabels[trait],damageType:baseDamage.damageType,diceNumber:1,dieSize,critical:!0,enabled:!0,override:{dieSize}}))}const runeNotes=propertyRunes.flatMap(r=>(RUNE_DATA.weapon.property[r].damage?.notes??[]).map(d=>new RollNotePF2e({selector:"strike-damage",...d})));context.notes=[runeNotes,critSpecEffect.filter(e=>e instanceof RollNotePF2e)].flat();const material=objectHasKey(CONFIG.PF2E.materialDamageEffects,weapon.system.material.type)?weapon.system.material.type:null,materials=new Set([materialTraits,material??[]].flat());for(const adjustment of actor.synthetics.strikeAdjustments)adjustment.adjustDamageRoll?.(weapon,{materials});for(const option of Array.from(materials).map(m=>`item:material:${m}`))options.add(option);for(const modifier of modifiers){const propRuneAdjustments=propertyRuneAdjustments.filter(a=>a.slug===modifier.slug);modifier.adjustments.push(...propRuneAdjustments)}const baseUncategorized=(()=>{const diceNumber=baseDamage.die?baseDamage.dice:0;return diceNumber>0||baseDamage.modifier>0?{diceNumber,dieSize:baseDamage.die,modifier:baseDamage.modifier,damageType:baseDamage.damageType,category:"category"in baseDamage&&baseDamage.category==="persistent"?"persistent":null,materials:Array.from(materials)}:null})(),basePersistent=(()=>baseDamage.persistent?.faces?{diceNumber:baseDamage.persistent.number,dieSize:`d${baseDamage.persistent.faces}`,damageType:baseDamage.persistent.type,category:"persistent"}:baseDamage.persistent?.number?{modifier:baseDamage.persistent.number,damageType:baseDamage.persistent.type,category:"persistent"}:null)();if(!(baseUncategorized||basePersistent||splashDamage))return null;const base=compact([baseUncategorized,basePersistent]),extractOptions={test:options,resolvables:{weapon,target:context.target?.actor??null},injectables:{weapon}},extracted=processDamageCategoryStacking(base,{modifiers:[modifiers,extractModifiers(actor.synthetics,domains,extractOptions)].flat(),dice:extractDamageDice(actor.synthetics.damageDice,domains,extractOptions),test:options}),testedModifiers=extracted.modifiers;damageDice.push(...extracted.dice);const formulaData={base,dice:damageDice,maxIncreases:1,modifiers:testedModifiers,ignoredResistances};formulaData.base[0].diceNumber||formulaData.base[0].modifier||(formulaData.dice=formulaData.dice.filter(d=>![null,"precision"].includes(d.category)),formulaData.modifiers=formulaData.modifiers.filter(m=>![null,"precision"].includes(m.category)));const excludeFrom=weapon.isOfType("weapon")?weapon:null;if(this.#excludeDamage({actor,weapon:excludeFrom,modifiers:[...testedModifiers,...damageDice],options}),!context.skipDialog&&!await new DamageModifierDialog({formulaData,context}).resolve())return null;const computedFormulas={criticalFailure:null,failure:createDamageFormula(formulaData,DEGREE_OF_SUCCESS.FAILURE),success:createDamageFormula(formulaData,DEGREE_OF_SUCCESS.SUCCESS),criticalSuccess:createDamageFormula(formulaData,DEGREE_OF_SUCCESS.CRITICAL_SUCCESS)};return{name:`${game.i18n.localize("PF2E.DamageRoll")}: ${weapon.name}`,materials:Array.from(materials),modifiers:[...modifiers,...damageDice],damage:{...formulaData,formula:mapValues(computedFormulas,formula=>formula?.formula??null),breakdown:mapValues(computedFormulas,formula=>formula?.breakdown??[])}}}static#excludeDamage({actor,modifiers,weapon,options}){if(!weapon)return;const notIgnored=modifiers.filter(modifier=>!modifier.ignored);for(const rule of actor.rules)rule.applyDamageExclusion?.(weapon,notIgnored);for(const modifier of notIgnored)modifier.ignored=!modifier.predicate.test(options)}static npcDamageToWeaponDamage(instance){const terms=parseTermsFromSimpleFormula(instance.damage),die=terms.find(t=>t.dice)?.dice,modifier=terms.find(t=>t.modifier)?.modifier??0;return{dice:die?.number??0,die:die?.faces?`d${die.faces}`:null,modifier,damageType:instance.damageType,persistent:null,category:instance.category}}}async function resetActors(actors,options={}){actors??=[game.actors.contents,game.scenes.contents.flatMap(s=>s.tokens.contents).flatMap(t=>t.actor??[])].flat(),actors=uniq(Array.from(actors));for(const actor of actors)actor.reset(),options.sheets&&actor.render();if(game.pf2e.effectPanel.refresh(),game.settings.get("pf2e","automation.effectExpiration")&&!game.settings.get("pf2e","automation.removeExpiredEffects")){const scenes=uniq(Array.from(actors).flatMap(a=>a.getActiveTokens(!1,!0)).flatMap(t=>t.scene));for(const scene of scenes)scene.reset(),scene.isView&&canvas.perception.update({initializeVision:!0},!0)}if(options.tokens)for(const token of uniq(Array.from(actors).flatMap(a=>a.getActiveTokens(!0,!0))))token.simulateUpdate()}__name(resetActors,"resetActors"),__name2(resetActors,"resetActors");function userColorForActor(actor){return(game.users.find(u=>u.character===actor)??game.users.players.find(u=>actor.testUserPermission(u,"OWNER"))??actor.primaryUpdater)?.color??"#43dfdf"}__name(userColorForActor,"userColorForActor"),__name2(userColorForActor,"userColorForActor");async function migrateActorSource(source){source.effects=[],["flags","items","system"].some(k=>k in source)||(source.system={_migration:{version:MigrationRunnerBase.LATEST_SCHEMA_VERSION}});const lowestSchemaVersion=Math.min(source.system?._migration?.version??MigrationRunnerBase.LATEST_SCHEMA_VERSION,...(source.items??[]).map(i=>i?.system?._migration?.version??MigrationRunnerBase.LATEST_SCHEMA_VERSION)),tokenDefaults=foundry.utils.deepClone(game.settings.get("core","defaultToken")),actor=new ActorProxyPF2e(foundry.utils.mergeObject({prototypeToken:tokenDefaults},source));return await MigrationRunner.ensureSchemaVersion(actor,MigrationList.constructFromVersion(lowestSchemaVersion)),actor.toObject()}__name(migrateActorSource,"migrateActorSource"),__name2(migrateActorSource,"migrateActorSource");async function checkAreaEffects(){if(!canvas.ready||game.user!==this.primaryUpdater||this.isOfType("party"))return;const thisTokens=this.getActiveTokens(!0,!0),toDelete2=[],toKeep=[];for(const effect of this.itemTypes.effect){const auraData=effect.flags.pf2e.aura;if(!auraData?.removeOnExit)continue;const auraActor=await fromUuid(auraData.origin),aura=(auraActor?.getActiveTokens(!0,!0).shift()??null)?.auras.get(auraData.slug),auraEffectData=auraActor?.auras.get(auraData.slug)?.effects.find(e=>e.uuid===effect.sourceId&&auraAffectsActor(e,auraActor,this));for(const token of thisTokens)auraEffectData&&aura?.containsToken(token)?toKeep.push(effect.id):toDelete2.push(effect.id);thisTokens.length===0&&toDelete2.push(effect.id)}const finalToDelete=toDelete2.filter(id=>!toKeep.includes(id));finalToDelete.length>0&&await this.deleteEmbeddedDocuments("Item",finalToDelete)}__name(checkAreaEffects,"checkAreaEffects"),__name2(checkAreaEffects,"checkAreaEffects");function auraAffectsActor(data,origin,actor){return data.includesSelf&&origin===actor||data.affects==="allies"&&actor.isAllyOf(origin)||data.affects==="enemies"&&actor.isEnemyOf(origin)||data.affects==="all"&&actor!==origin}__name(auraAffectsActor,"auraAffectsActor"),__name2(auraAffectsActor,"auraAffectsActor");function setHitPointsRollOptions(actor){const hp=actor.hitPoints;if(!hp)return;actor.flags.pf2e.rollOptions.all[`hp-remaining:${hp.value}`]=!0;const percentRemaining=Math.floor(hp.value/hp.max*100);actor.flags.pf2e.rollOptions.all[`hp-percent:${percentRemaining}`]=!0}__name(setHitPointsRollOptions,"setHitPointsRollOptions"),__name2(setHitPointsRollOptions,"setHitPointsRollOptions");function calculateMAPs(item,{domains,options}){const slugAndLabel={slug:"multiple-attack-penalty",label:"PF2E.MultipleAttackPenalty"},baseMap=item.isOfType("action","melee","weapon")&&item.traits.has("agile")?{...slugAndLabel,map1:-4,map2:-8}:{...slugAndLabel,map1:-5,map2:-10},optionSet=options instanceof Set?options:new Set(options),maps=item.actor?.synthetics.multipleAttackPenalties??{},fromSynthetics=domains.flatMap(d=>maps[d]??[]).filter(p=>p.predicate?.test(optionSet)??!0).map(p=>({slug:baseMap.slug,label:p.label,map1:p.penalty,map2:p.penalty*2}));return[baseMap,...fromSynthetics].reduce((lowest,p)=>p.map1>lowest.map1?p:lowest)}__name(calculateMAPs,"calculateMAPs"),__name2(calculateMAPs,"calculateMAPs");function createEncounterRollOptions(actor){const encounter=game.ready?game.combat:null;if(!encounter?.started)return{};const participants=encounter.combatants.contents.filter(c=>typeof c.initiative=="number").sort((a,b)=>b.initiative-a.initiative),participant=actor.combatant;if(typeof participant?.initiative!="number"||!participants.includes(participant))return{};const initiativeRoll=Math.trunc(participant.initiative),initiativeRank=participants.indexOf(participant)+1,{initiativeStatistic}=participant.flags.pf2e,threat=encounter.metrics?.threat,numericThreat={trivial:0,low:1,moderate:2,severe:3,extreme:4}[threat??"trivial"],entries=[["encounter",!0],[`encounter:threat:${numericThreat}`,!!threat],[`encounter:threat:${threat}`,!!threat],[`encounter:round:${encounter.round}`,!0],[`encounter:turn:${Number(encounter.turn)+1}`,!0],["self:participant:own-turn",encounter.combatant===participant],[`self:participant:initiative:roll:${initiativeRoll}`,!0],[`self:participant:initiative:rank:${initiativeRank}`,!0],[`self:participant:initiative:stat:${initiativeStatistic}`,!!initiativeStatistic]].filter(([,value])=>!!value);return Object.fromEntries(entries)}__name(createEncounterRollOptions,"createEncounterRollOptions"),__name2(createEncounterRollOptions,"createEncounterRollOptions");function isOffGuardFromFlanking(target,origin,originRollOptions){if(!target.isOfType("creature"))return!1;const{flanking}=target.attributes;return flanking.flankable&&(typeof flanking.offGuardable=="number"?origin.level>flanking.offGuardable:flanking.offGuardable)&&!target.attributes.immunities.some(i=>i.test(["item:type:condition","item:slug:off-guard",...originRollOptions]))}__name(isOffGuardFromFlanking,"isOffGuardFromFlanking"),__name2(isOffGuardFromFlanking,"isOffGuardFromFlanking");function getStrikeAttackDomains(weapon,proficiencyRank,baseRollOptions){const unarmedOrWeapon=weapon.category==="unarmed"?"unarmed":"weapon",meleeOrRanged=weapon.isMelee?"melee":"ranged",weaponSlug=weapon.slug??sluggify(weapon.name),domains=[weapon.baseType?`${weapon.baseType}-base-attack-roll`:[],weapon.group?`${weapon.group}-group-attack-roll`:[],weapon.system.traits.otherTags.map(t=>`${t}-tag-attack-roll`),`${weapon.id}-attack`,`${weaponSlug}-attack`,`${weaponSlug}-attack-roll`,`${unarmedOrWeapon}-attack-roll`,`${meleeOrRanged}-attack-roll`,`${meleeOrRanged}-strike-attack-roll`,"strike-attack-roll","attack-roll","attack","check","all"].flat();if(typeof proficiencyRank=="number"){const proficiencies=["untrained","trained","expert","master","legendary"];domains.push(`${proficiencies[proficiencyRank]}-attack`)}const{actor}=weapon;if(actor.isOfType("character","npc")){const defaultAttributeModifier=createAttributeModifier({actor,attribute:weapon.defaultAttribute,domains}),rollOptions=[...baseRollOptions,actor.getRollOptions(domains),weapon.getRollOptions("item")].flat(),weaponTraits2=weapon.traits,alternativeAttributeModifier=actor.isOfType("character")?weaponTraits2.has("finesse")?createAttributeModifier({actor,attribute:"dex",domains}):weaponTraits2.has("brutal")||weaponTraits2.has("propulsive")?createAttributeModifier({actor,attribute:"str",domains}):null:null,attributeModifier=compact([defaultAttributeModifier,alternativeAttributeModifier,...extractModifiers(weapon.actor.synthetics,domains,{resolvables:{weapon},test:rollOptions})]).filter(m=>m.type==="ability"&&m.enabled).reduce((best,candidate)=>candidate.modifier>best.modifier?candidate:best);domains.push(`${attributeModifier.ability}-attack`,`${attributeModifier.ability}-based`)}return uniq(domains)}__name(getStrikeAttackDomains,"getStrikeAttackDomains"),__name2(getStrikeAttackDomains,"getStrikeAttackDomains");function getStrikeDamageDomains(weapon,proficiencyRank){const meleeOrRanged=weapon.isMelee?"melee":"ranged",slug=weapon.slug??sluggify(weapon.name),{actor,traits}=weapon,unarmedOrWeapon=traits.has("unarmed")?"unarmed":"weapon",domains=[`${weapon.id}-damage`,`${slug}-damage`,`${meleeOrRanged}-strike-damage`,`${meleeOrRanged}-damage`,`${unarmedOrWeapon}-damage`,"attack-damage","strike-damage","damage"];if(weapon.group&&domains.push(`${weapon.group}-weapon-group-damage`),weapon.baseType&&domains.push(`${weapon.baseType}-base-type-damage`),typeof proficiencyRank=="number"){const proficiencies=["untrained","trained","expert","master","legendary"];domains.push(`${proficiencies[proficiencyRank]}-damage`)}const baseType=CONFIG.PF2E.equivalentWeapons[weapon.baseType??""]??weapon.baseType;if(baseType&&!domains.includes(`${baseType}-damage`)&&domains.push(`${baseType}-damage`),actor.isOfType("character","npc")){const attributeModifier=[weapon.isMelee||weapon.isThrown&&!traits.has("splash")||traits.has("propulsive")?createAttributeModifier({actor,attribute:"str",domains}):null,...extractModifiers(actor.synthetics,domains,{resolvables:{weapon},test:[...actor.getRollOptions(domains),...weapon.getRollOptions("item")]}).filter(m=>!m.ignored&&m.type==="ability")].reduce((best,candidate)=>candidate&&best?candidate.value>best.value?candidate:best:candidate??best);attributeModifier&&domains.push(`${attributeModifier.ability}-damage`)}return uniq(domains)}__name(getStrikeDamageDomains,"getStrikeDamageDomains"),__name2(getStrikeDamageDomains,"getStrikeDamageDomains");function strikeFromMeleeItem(item){const{actor,isMelee}=item;if(!actor.isOfType("npc","hazard"))throw ErrorPF2e("Attempted to create melee-item strike statistic for non-NPC/hazard");const meleeOrRanged=isMelee?"melee":"ranged",baseOptions=new Set(compact(["self:action:slug:strike",meleeOrRanged,...item.system.traits.value])),domains=getStrikeAttackDomains(item,actor.isOfType("npc")?1:null,baseOptions),{synthetics}=actor,modifiers=[new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:item.attackModifier,adjustments:extractModifierAdjustments(synthetics.modifierAdjustments,domains,"base")})];modifiers.push(...extractModifiers(synthetics,domains)),modifiers.push(...AttackTraitHelpers.createAttackModifiers({item}));const attackEffects=CONFIG.PF2E.attackEffects,additionalEffects=item.attackEffects.map(tag=>{const items=actor.items.contents,label=attackEffects[tag]??items.find(i=>(i.slug??sluggify(i.name))===tag)?.name??tag;return{tag,label}});for(const adjustment of synthetics.strikeAdjustments)adjustment.adjustWeapon?.(item);const initialRollOptions=new Set([...baseOptions,...actor.getRollOptions(domains),...item.getRollOptions("item")]),attackSlug=item.slug??sluggify(item.name),statistic=new StatisticModifier(attackSlug,modifiers,initialRollOptions),actionTraits2=compact(["attack",item.baseType==="alchemical-bomb"?"manipulate":null]),strikeAdjustments=[actor.synthetics.strikeAdjustments,getPropertyRuneStrikeAdjustments(item.system.runes.property)].flat();for(const adjustment of strikeAdjustments)adjustment.adjustTraits?.(item,actionTraits2);const strike=foundry.utils.mergeObject(statistic,{label:item.name,type:"strike",glyph:getActionGlyph({type:"action",value:1}),description:item.description,sourceId:item.id,attackRollType:item.isRanged?"PF2E.NPCAttackRanged":"PF2E.NPCAttackMelee",additionalEffects,item,weapon:item,options:Array.from(baseOptions),traits:[actionTraits2.map(t=>traitSlugToObject(t,CONFIG.PF2E.actionTraits)),item.system.traits.value.map(t=>traitSlugToObject(t,CONFIG.PF2E.npcAttackTraits))].flat(),variants:[],ready:!0,success:"",criticalSuccess:""});strike.breakdown=strike.modifiers.filter(m=>m.enabled).map(m=>`${m.label} ${signedInteger(m.value)}`).join(", ");const maps=calculateMAPs(item,{domains,options:initialRollOptions}),createMapModifier=__name2(prop=>new ModifierPF2e({slug:maps.slug,label:maps.label,modifier:maps[prop],adjustments:extractModifierAdjustments(synthetics.modifierAdjustments,domains,maps.slug)}),"createMapModifier"),labels=[`${game.i18n.localize("PF2E.WeaponStrikeLabel")} ${signedInteger(strike.totalModifier)}`,...["map1","map2"].map(prop=>{const modifier=createMapModifier(prop);adjustModifiers([modifier],baseOptions);const penalty=modifier.ignored?0:modifier.value;return game.i18n.format("PF2E.MAPAbbreviationValueLabel",{value:signedInteger(strike.totalModifier+penalty),penalty})})];strike.variants=[null,...["map1","map2"].map(createMapModifier)].map((map2,mapIncreases)=>({label:labels[mapIncreases],roll:async(params={})=>{params.options??=[];const context=await actor.getCheckContext({item,viewOnly:params.getFormula??!1,statistic:strike,target:{token:params.target??game.user.targets.first()??null},defense:"armor",domains,options:new Set([...baseOptions,...params.options]),traits:actionTraits2});if(context.self.item.isRanged&&typeof context.target?.distance=="number"){const maxRange=item.range?.max??10;if(context.target.distance>maxRange)return ui.notifications.warn("PF2E.Action.Strike.OutOfRange",{localize:!0}),null}const otherModifiers=[map2??[],context.self.modifiers].flat(),title=game.i18n.format(item.isMelee?"PF2E.Action.Strike.MeleeLabel":"PF2E.Action.Strike.RangedLabel",{weapon:item.name}),notes=[actor.isOfType("npc")?await actor.getAttackEffects(item):[],extractNotes(context.self.actor.synthetics.rollNotes,domains)].flat(),rollTwice=params.rollTwice||extractRollTwice(context.self.actor.synthetics.rollTwice,domains,context.options),substitutions=extractRollSubstitutions(context.self.actor.synthetics.rollSubstitutions,domains,context.options),dosAdjustments=extractDegreeOfSuccessAdjustments(context.self.actor.synthetics,domains),check=new CheckModifier("strike",context.self.statistic??strike,otherModifiers),checkContext={type:"attack-roll",identifier:`${item.id}.${attackSlug}.${meleeOrRanged}`,action:"strike",title,actor:context.self.actor,token:context.self.token,item:context.self.item,target:context.target,damaging:context.self.item.dealsDamage,domains,options:context.options,traits:context.traits,notes,dc:params.dc??context.dc,mapIncreases,rollTwice,substitutions,dosAdjustments},roll=await CheckPF2e.roll(check,checkContext,params.event);if(roll)for(const rule of context.self.actor.rules.filter(r=>!r.ignored))await rule.afterRoll?.({roll,check,context:checkContext,domains,rollOptions:context.options});return roll}})),strike.roll=strike.attack=strike.variants[0].roll;const damageRoll=__name2(outcome=>async(params={})=>{const domains2=getStrikeDamageDomains(item,actor.isOfType("npc")?1:null),targetToken=params.target??game.user.targets.first()??null,context=await actor.getDamageRollContext({item,statistic:strike,target:{token:targetToken},viewOnly:params.getFormula??!1,domains:domains2,checkContext:params.checkContext,outcome,traits:actionTraits2,options:new Set([...baseOptions,...params.options??[]])});if(!context.self.item.dealsDamage&&!params.getFormula)return ui.notifications.warn("PF2E.ErrorMessage.WeaponNoDamage",{localize:!0}),null;const{self,target}=context,damageContext={type:"damage-roll",sourceType:"attack",self,target,outcome,options:context.options,domains:domains2,traits:context.traits,...eventToRollParams(params.event,{type:"damage"})};typeof params.mapIncreases=="number"&&(damageContext.mapIncreases=params.mapIncreases,damageContext.options.add(`map:increases:${params.mapIncreases}`)),params.getFormula&&(damageContext.skipDialog=!0);const damage=await WeaponDamagePF2e.fromNPCAttack({attack:context.self.item,actor:context.self.actor,context:damageContext});if(!damage)return null;if(params.getFormula){const formula=damage.damage.formula[outcome];return formula?new DamageRoll(formula).formula:""}else return DamagePF2e.roll(damage,damageContext,params.callback)},"damageRoll");return strike.damage=damageRoll("success"),strike.critical=damageRoll("criticalSuccess"),strike}__name(strikeFromMeleeItem,"strikeFromMeleeItem"),__name2(strikeFromMeleeItem,"strikeFromMeleeItem");function getRangeIncrement(attackItem,distance){if(!attackItem.isOfType("action","melee","weapon"))return null;const{increment}=attackItem.range??{};return increment&&typeof distance=="number"?Math.max(Math.ceil(distance/increment),1):null}__name(getRangeIncrement,"getRangeIncrement"),__name2(getRangeIncrement,"getRangeIncrement");function calculateRangePenalty(actor,increment,selectors,rollOptions){if(!increment||increment===1)return null;const slug="range-penalty",modifier=new ModifierPF2e({label:"PF2E.RangePenalty",slug,type:"untyped",modifier:Math.max((increment-1)*-2,-12),predicate:[{nor:["ignore-range-penalty",{gte:["ignore-range-penalty",increment]}]}],adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,selectors,slug)});return modifier.test(rollOptions),modifier}__name(calculateRangePenalty,"calculateRangePenalty"),__name2(calculateRangePenalty,"calculateRangePenalty");function isReallyPC(actor){const traits=actor.traits;return actor.isOfType("character")&&!(traits.has("minion")||traits.has("eidolon"))}__name(isReallyPC,"isReallyPC"),__name2(isReallyPC,"isReallyPC");function findMatchingCheckContext(actor,params){if(params.viewOnly||!params.target?.token)return null;const paramsItem=params.item;return paramsItem?.isOfType("melee","weapon")?game.messages.contents.slice(-3).reverse().find(message=>{if(!message.rolls.some(r=>r instanceof CheckRoll)||message.actor?.uuid!==actor.uuid||params.target?.token!==message.target?.token.object)return!1;const messageItem=message.item;if(!messageItem?.isOfType("melee","weapon"))return!1;const paramsItemSlug=paramsItem.slug??sluggify(paramsItem.name),messageItemSlug=messageItem.slug??sluggify(messageItem.name);return paramsItemSlug===messageItemSlug&¶msItem.uuid===messageItem.uuid&¶msItem.isMelee===messageItem.isMelee})?.flags.pf2e.context??null:null}__name(findMatchingCheckContext,"findMatchingCheckContext"),__name2(findMatchingCheckContext,"findMatchingCheckContext");class Statistic extends BaseStatistic{static{__name(this,"Statistic")}static{__name2(this,"Statistic")}attribute=null;rank=null;proficient=!0;base=null;lore;config;#check;#dc;constructor(actor,data,config={}){data.modifiers??=[];const domains=data.domains??=[],attributeModifier=actor.isOfType("character")&&data.attribute?data.modifiers.find(m=>m.type==="ability"&&m.ability===data.attribute)??createAttributeModifier({actor,attribute:data.attribute,domains}):null;data.attribute&&domains.push(`${data.attribute}-based`);const proficiencyModifier=actor.isOfType("character")?typeof data.rank=="number"?createProficiencyModifier({actor,rank:data.rank,domains}):data.rank==="untrained-level"?createProficiencyModifier({actor,rank:0,domains,addLevel:!0}):null:null,baseModifiers=compact([attributeModifier,proficiencyModifier]),activeSlugs=new Set(baseModifiers.map(m=>m.slug));data.modifiers=data.modifiers.filter(m=>!activeSlugs.has(m.slug)),data.modifiers.unshift(...baseModifiers),super(actor,data),this.attribute=data.attribute??null,typeof data.lore=="boolean"&&(this.lore=data.lore),this.rank=data.rank==="untrained-level"?0:data.rank??null,this.config=config,this.proficient=data.proficient===void 0?this.rank===null||this.rank>0:!!data.proficient,data.filter&&(this.modifiers=this.modifiers.filter(data.filter)),this.data.dc??={domains:[`${this.slug}-dc`]}}get attributeModifier(){return this.actor.isOfType("npc")?this.attribute?createAttributeModifier({actor:this.actor,attribute:this.attribute,domains:this.domains}):null:this.modifiers.find(m=>m.type==="ability"&&m.enabled&&m.ability===this.attribute)??null}get check(){return this.#check??=new StatisticCheck(this,this.data,this.config)}get dc(){return this.#dc??=new StatisticDifficultyClass(this,this.data,this.config)}get mod(){return this.check.mod}get ability(){return foundry.utils.logCompatibilityWarning("`Statistic#ability` is deprecated. Use `Statistic#attribute` instead.",{since:"5.5.0",until:"6.0.0"}),this.attribute}createRollOptions(domains=this.domains,args={}){const{item,extraRollOptions,origin,target}=args,rollOptions=[];return domains.length>0&&rollOptions.push(...super.createRollOptions(domains)),typeof this.rank=="number"&&rollOptions.push(PROFICIENCY_RANK_OPTION[this.rank]),this.data.rollOptions&&rollOptions.push(...this.data.rollOptions),item&&(rollOptions.push(...item.getRollOptions("item")),item.actor&&item.actor.uuid!==this.actor.uuid&&rollOptions.push(...item.actor.getSelfRollOptions("origin")),(item.system.traits?.value??[]).includes("attack")&&rollOptions.push("trait:attack")),origin?rollOptions.push(...origin.getSelfRollOptions("origin")):target&&rollOptions.push(...target.getSelfRollOptions("target")),extraRollOptions&&rollOptions.push(...extraRollOptions),new Set(rollOptions)}withRollOptions(options){const newOptions=foundry.utils.mergeObject(this.config??{},options??{},{inplace:!1});return new Statistic(this.actor,foundry.utils.deepClone(this.data),newOptions)}extend(data){function maybeMergeArrays(arr1,arr2){if(!(!arr1&&!arr2))return[...new Set([arr1??[],arr2??[]].flat())]}__name(maybeMergeArrays,"maybeMergeArrays"),__name2(maybeMergeArrays,"maybeMergeArrays");const result=foundry.utils.mergeObject(foundry.utils.deepClone(this.data),data);result.domains=maybeMergeArrays(this.domains,data.domains),result.modifiers=maybeMergeArrays(this.data.modifiers,data.modifiers),result.rollOptions=maybeMergeArrays(this.data.rollOptions,data.rollOptions),result.check&&this.data.check&&(result.check.domains=maybeMergeArrays(this.data.check.domains,data.check?.domains),result.check.modifiers=maybeMergeArrays(this.data.check.modifiers,data.check?.modifiers)),result.dc&&this.data.dc&&(result.dc.domains=maybeMergeArrays(this.data.dc.domains,data.dc?.domains),result.dc.modifiers=maybeMergeArrays(this.data.dc.modifiers,data.dc?.modifiers));const extended=new Statistic(this.actor,result,this.config);return extended.base=this,extended}roll(args={}){return this.check.roll(args)}getChatData(options={}){const{check,dc}=this.withRollOptions(options),{map1,map2}=options.item?calculateMAPs(options.item,{domains:check?.domains??[],options:check?.createRollOptions(options)??[]}):{map1:-5,map2:-10};return{slug:this.slug,label:this.label,rank:this.rank,check:{mod:check.mod,breakdown:check.breakdown,label:check.label,map1,map2},dc:{value:dc.value,breakdown:dc.breakdown}}}getTraceData(options={}){const{check,dc}=this,valueProp=options.value??"mod",[label,value,totalModifier,breakdown,modifiers]=valueProp==="mod"?[this.label,check.mod,check.mod,check.breakdown,check.modifiers]:[dc.label||this.label,dc.value,dc.value-10,dc.breakdown,dc.modifiers];return{slug:this.slug,label,value,totalModifier,dc:dc.value,breakdown,modifiers:modifiers.map(m=>m.toObject())}}}class StatisticCheck{static{__name(this,"StatisticCheck")}static{__name2(this,"StatisticCheck")}parent;type;label;domains;mod;modifiers;constructor(parent,data,config={}){this.parent=parent,this.type=data.check?.type??"check",data.check=foundry.utils.mergeObject(data.check??{},{type:this.type});const checkDomains=new Set(compact(["check",data.check.domains].flat()));this.type==="attack-roll"?(checkDomains.add("attack"),checkDomains.add("attack-roll"),checkDomains.add(`${this.parent.slug}-attack-roll`)):(checkDomains.add(`${this.parent.slug}-check`),this.type==="flat-check"&&(checkDomains.delete("check"),checkDomains.add("flat-check"))),data.check.domains=Array.from(checkDomains),this.domains=uniq(compact([data.domains,data.check.domains].flat())),this.label=this.#determineLabel(data);const{modifierAdjustments}=parent.actor.synthetics,parentModifiers=parent.modifiers.map(modifier=>{const clone=modifier.clone();return clone.adjustments.push(...extractModifierAdjustments(modifierAdjustments,data.check?.domains??[],clone.slug)),clone}),checkOnlyModifiers=[data.check?.modifiers??[],extractModifiers(parent.actor.synthetics,data.check?.domains??[])].flat().map(modifier=>(modifier.adjustments.push(...extractModifierAdjustments(parent.actor.synthetics.modifierAdjustments,parent.domains,this.parent.slug)),modifier)),rollOptions=parent.createRollOptions(this.domains,config);this.modifiers=[...parentModifiers,...checkOnlyModifiers.map(modifier=>modifier.clone({test:rollOptions}))],this.type==="flat-check"&&this.modifiers.length>0&&(console.error(ErrorPF2e("Flat checks cannot have modifiers.").message),this.modifiers=[]),this.mod=new StatisticModifier(this.label,this.modifiers,rollOptions).totalModifier}get actor(){return this.parent.actor}#determineLabel(data){const parentLabel=this.parent.label;if(data.check?.label)return game.i18n.localize(data.check?.label);if(this.domains.includes("spell-attack-roll"))return game.i18n.format("PF2E.SpellAttackWithTradition",{tradition:parentLabel});switch(this.type){case"skill-check":return game.i18n.format("PF2E.SkillCheckWithName",{skillName:parentLabel});case"saving-throw":return game.i18n.format("PF2E.SavingThrowWithName",{saveName:parentLabel});case"perception-check":return game.i18n.format("PF2E.PerceptionCheck");default:return parentLabel}}createRollOptions(args={}){return this.parent.createRollOptions(this.domains,args)}async roll(args={}){args.dc=typeof args.dc=="number"?{value:Math.trunc(args.dc)||0}:args.dc??null;const{rollMode,skipDialog}=(()=>{if(isObject(args)){const event2=args.event?.originalEvent??args.event;if(event2 instanceof MouseEvent){const{rollMode:rollMode2,skipDialog:skipDialog2}=args;return foundry.utils.mergeObject({rollMode:rollMode2,skipDialog:skipDialog2},eventToRollParams(event2,{type:"check"}))}}return args})(),{domains}=this,token=args.token??this.actor.getActiveTokens(!1,!0).shift(),item=args.item??null,{origin}=args,targetToken=origin?null:(args.target?.getActiveTokens()??Array.from(game.user.targets)).find(t=>t.actor?.isOfType("army","creature","hazard"))??null,rollContext=await(()=>{const isValidAttacker=targetToken?.actor?.isOfType("army")?this.actor.isOfType("army"):this.actor.isOfType("creature","hazard"),isTargetedCheck=this.domains.includes("spell-attack-roll")&&item?.isOfType("spell")||!["flat-check","saving-throw"].includes(this.type)&&!!(args.dc?.slug||"statistic"in(args.dc??{}))&&(!item||item.isOfType("action","campaignFeature","feat","weapon"));return isValidAttacker&&isTargetedCheck?this.actor.getCheckContext({item:item?.isOfType("action","melee","spell","weapon")?item:null,domains,statistic:this,target:targetToken,defense:args.dc?.slug??"armor",melee:args.melee,options:new Set(args.extraRollOptions??[])}):null})(),selfActor=rollContext?.self.actor??this.actor,targetActor=origin?null:rollContext?.target?.actor??args.target??null,dc=typeof args.dc?.value=="number"?args.dc:rollContext?.dc??null,extraModifiers=this.type==="flat-check"?[]:compact([args.modifiers,rollContext?.self.modifiers].flat()),extraRollOptions=[...args.extraRollOptions??[],...rollContext?.options??[],`check:statistic:${this.parent.slug}`,`check:type:${this.type.replace(/-check$/,"")}`];this.parent.base&&extraRollOptions.push(`check:statistic:base:${this.parent.base.slug}`);const options=this.createRollOptions({...args,origin,target:targetActor,extraRollOptions}),notes=[...extractNotes(selfActor.synthetics.rollNotes,domains),...args.extraRollNotes??[]];for(const rule of selfActor.rules.filter(r=>!r.ignored))rule.beforeRoll?.(domains,options);const dosAdjustments=dc?extractDegreeOfSuccessAdjustments(selfActor.synthetics,domains):[];if((options.has("incapacitation")||options.has("item:trait:incapacitation"))&&dc){const effectLevel=item?.isOfType("spell")?2*item.rank:item?.isOfType("physical")?item.level:origin?.level??selfActor.level,amount=this.type==="saving-throw"&&selfActor.level>effectLevel?DEGREE_ADJUSTMENT_AMOUNTS.INCREASE:targetActor&&targetActor.level>effectLevel&&["attack-roll","spell-attack-roll","skill-check"].includes(this.type)?DEGREE_ADJUSTMENT_AMOUNTS.LOWER:null;amount&&dosAdjustments.push({adjustments:{all:{label:"PF2E.TraitIncapacitation",amount}}})}const mapIncreases=Math.clamped((args.attackNumber??1)-1,0,2);if(mapIncreases!==0)if(!item)console.warn("Missing item argument while calculating MAP during check");else{const maps=calculateMAPs(item,{domains,options}),penalty=maps[`map${mapIncreases}`];extraModifiers.push(new ModifierPF2e(maps.label,penalty,"untyped"))}const traits=args.traits?.map(t=>typeof t=="string"?t:t.name).filter(t=>t in CONFIG.PF2E.actionTraits)??[];for(const trait of traits)options.add(trait);if(args.action){options.add(`self:action:slug:${sluggify(args.action)}`);for(const trait of traits)options.add(`self:action:trait:${trait}`)}const context={actor:selfActor,token,item,type:this.type,identifier:args.identifier,domains,target:rollContext?.target??null,dc,notes,options,action:args.action,damaging:args.damaging,rollMode,skipDialog,rollTwice:args.rollTwice||extractRollTwice(selfActor.synthetics.rollTwice,domains,options),substitutions:extractRollSubstitutions(selfActor.synthetics.rollSubstitutions,domains,options),dosAdjustments,traits,title:args.title?.trim()||args.label?.trim()||this.label,createMessage:args.createMessage??!0};typeof args.attackNumber=="number"&&(context.mapIncreases=mapIncreases,context.options?.add(`map:increases:${mapIncreases}`));const check=new CheckModifier(this.parent.slug,{modifiers:this.modifiers},extraModifiers),roll=await CheckPF2e.roll(check,context,null,args.callback);if(roll)for(const rule of selfActor.rules.filter(r=>!r.ignored))await rule.afterRoll?.({roll,check,context,domains,rollOptions:options});return roll}get breakdown(){return this.modifiers.filter(m=>m.enabled).map(m=>`${m.label} ${m.modifier<0?"":"+"}${m.modifier}`).join(", ")}}class StatisticDifficultyClass{static{__name(this,"StatisticDifficultyClass")}static{__name2(this,"StatisticDifficultyClass")}parent;domains;label;modifiers;options;constructor(parent,data,options={}){this.parent=parent,this.domains=uniq(compact([data.domains,data.dc?.domains].flat())),this.label=data.dc?.label,this.options=parent.createRollOptions(this.domains,options);const{modifierAdjustments}=parent.actor.synthetics,parentModifiers=parent.modifiers.map(modifier=>{const clone=modifier.clone();return clone.adjustments.push(...extractModifierAdjustments(modifierAdjustments,data.dc?.domains??[],clone.slug)),clone}),dcOnlyModifiers=[data.dc?.modifiers??[],extractModifiers(parent.actor.synthetics,data.dc?.domains??[])].flat().map(modifier=>(modifier.adjustments.push(...extractModifierAdjustments(parent.actor.synthetics.modifierAdjustments,parent.domains,this.parent.slug)),modifier));this.modifiers=[...new StatisticModifier("",[...parentModifiers,...dcOnlyModifiers.map(m=>m.clone())],this.options).modifiers]}get value(){return 10+new StatisticModifier("",this.modifiers.map(m=>m.clone()),this.options).totalModifier}get breakdown(){const enabledMods=this.modifiers.filter(m=>m.enabled);return[game.i18n.localize("PF2E.DCBase")].concat(enabledMods.map(m=>`${m.label} ${signedInteger(m.modifier)}`)).join(", ")}toString(){return String(this.value)}}class ArmorStatistic extends Statistic{static{__name(this,"ArmorStatistic")}static{__name2(this,"ArmorStatistic")}details;get item(){return this.actor.isOfType("character")?this.actor.wornArmor:null}constructor(actor,data={}){data.rank??=1;const attribute=actor.isOfType("creature")?data.attribute??"dex":null,domains=attribute?["all",`${attribute}-based`]:["all"],fullData={...data,label:"TYPES.Item.armor",slug:"armor",attribute,domains,proficient:data.rank>0,dc:{label:"PF2E.ArmorClassLabel",domains:["ac"],modifiers:[]}};super(actor,fullData),this.details=data.details??"";const dcModifiers=[...this.dc.modifiers,...this.#createBonusesAndPenalties()].map(m=>m.clone());this.dc.modifiers=[...new StatisticModifier("",dcModifiers,this.dc.options).modifiers]}#createBonusesAndPenalties(){const{actor}=this,armor=actor.isOfType("character")?actor.wornArmor:null,armorSlug=armor?.baseType??armor?.slug??sluggify(armor?.name??""),itemBonus=armor?new ModifierPF2e({label:armor.name,type:"item",slug:armorSlug,modifier:armor.acBonus,adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,["all","ac"],armorSlug)}):null;return compact([itemBonus,createShoddyPenalty(actor,armor,this.dc.domains),this.#createShieldBonus()])}#createShieldBonus(){const{actor}=this;if(!actor.isOfType("character","npc"))return null;const shieldData=actor.system.attributes.shield,slug="raised-shield";return shieldData.raised&&!shieldData.broken?new ModifierPF2e({label:shieldData.name,slug,adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,["all","dex-based","ac"],slug),type:"circumstance",modifier:shieldData.ac}):null}getTraceData(){return{...super.getTraceData({value:"dc"}),details:this.details,breakdown:this.dc.breakdown}}}class HitPointsStatistic extends BaseStatistic{static{__name(this,"HitPointsStatistic")}static{__name2(this,"HitPointsStatistic")}value;max;#baseMax;temp;negativeHealing;unrecoverable;details;constructor(actor,{baseMax=0}={}){const modifiers=actor.isOfType("character")?[createAttributeModifier({actor,attribute:"con",domains:["hp","con-based"]})]:[];super(actor,{slug:"hp",label:"PF2E.HitPointsHeader",domains:actor.isOfType("character","npc")?["con-based","hp"]:["hp"],modifiers}),this.#baseMax=baseMax,this.max=baseMax+new StatisticModifier("",this.modifiers.map(m=>m.clone())).totalModifier,this.value=Math.clamped(actor.system.attributes.hp.value,0,this.max),this.temp=actor.system.attributes.hp.temp,this.negativeHealing=actor.system.attributes.hp.negativeHealing,this.unrecoverable=actor.system.attributes.hp.unrecoverable,this.details=actor.system.attributes.hp.details||""}get breakdown(){return compact([this.#baseMax>0?game.i18n.format("PF2E.MaxHitPointsBaseLabel",{base:this.#baseMax}):null,...this.modifiers.filter(m=>m.enabled).map(m=>`${m.label} ${signedInteger(m.modifier)}`)]).join(", ")}getTraceData(){return{slug:this.slug,label:this.label,value:this.value,max:this.max,temp:this.temp,breakdown:this.breakdown,negativeHealing:this.negativeHealing,unrecoverable:this.unrecoverable,details:this.details,modifiers:this.modifiers.map(m=>m.toObject())}}}const TRICK_MAGIC_SKILLS=["arcana","nature","occultism","religion"],TrickMagicTradition={arcana:"arcane",nature:"primal",occultism:"occult",religion:"divine"},traditionSkills={arcane:"arcana",divine:"religion",occult:"occultism",primal:"nature"};class TrickMagicItemEntry{static{__name(this,"TrickMagicItemEntry")}static{__name2(this,"TrickMagicItemEntry")}id;actor;skill;statistic;attribute;get ability(){return foundry.utils.logCompatibilityWarning("`TrickMagicItemEntry#ability` is deprecated. Use `TrickMagicItemEntry#attribute` instead.",{since:"5.3.0",until:"6.0.0"}),this.attribute}tradition;constructor(actor,skill){if(!actor.isOfType("character"))throw ErrorPF2e("Trick magic entries may only be constructed with PCs");this.actor=actor,this.skill=skill,this.id=`trick-${this.skill}`;const attributes=actor.abilities,{attribute}=["int","wis","cha"].map(attribute2=>({attribute:attribute2,mod:attributes[attribute2].mod})).reduce((highest,next)=>next.mod>highest.mod?next:highest);this.attribute=attribute;const tradition=this.tradition=TrickMagicTradition[skill],selectors=[`${attribute}-based`,"all","spell-attack-dc"],attackSelectors=[`${tradition}-spell-attack`,"spell-attack","spell-attack-roll","attack","attack-roll"],saveSelectors=[`${tradition}-spell-dc`,"spell-dc"],skillRank=actor.skills[skill].rank,trickRank=skillRank===4?2:skillRank===3?1:0;this.statistic=new Statistic(actor,{slug:`trick-${tradition}`,label:CONFIG.PF2E.magicTraditions[tradition],attribute,rank:trickRank||"untrained-level",modifiers:extractModifiers(actor.synthetics,selectors),domains:selectors,check:{type:"attack-roll",modifiers:extractModifiers(actor.synthetics,attackSelectors),domains:attackSelectors},dc:{modifiers:extractModifiers(actor.synthetics,saveSelectors),domains:saveSelectors}})}get name(){return game.i18n.localize("PF2E.TrickMagicItemPopup.Title")}get sort(){return 0}get category(){return"items"}get spells(){return null}get isFlexible(){return!1}get isFocusPool(){return!1}get isInnate(){return!1}get isPrepared(){return!1}get isRitual(){return!1}get isSpontaneous(){return!1}canCast(){return!0}async cast(spell,options={}){const{rollMode,message}=options,castLevel=spell.computeCastRank(spell.rank);if(message!==!1)try{spell.trickMagicEntry=this,await spell.toMessage(void 0,{rollMode,data:{castLevel}})}finally{spell.trickMagicEntry=null}}async getSheetData(){return{id:this.id,name:this.name,statistic:this.statistic.getChatData(),tradition:this.tradition,category:"items",hasCollection:!1,sort:0,levels:[],usesSpellProficiency:!1,spellPrepList:null}}}const CANTRIP_DECK_ID="tLa4bewBhyqzi6Ow",scrollCompendiumIds={1:"RjuupS9xyXDLgyIr",2:"Y7UD64foDbDMV9sx",3:"ZmefGBXGJF3CFDbn",4:"QSQZJ5BC3DeHv153",5:"tjLvRWklAylFhBHQ",6:"4sGIy77COooxhQuC",7:"fomEZZ4MxVVK3uVu",8:"iPki3yuoucnj7bIt",9:"cFHomF3tty8Wi1e5",10:"o1XIHJ4MJyroAHfF"},SPELL_CONSUMABLE_NAME_TEMPLATES={cantripDeck5:"PF2E.Item.Physical.FromSpell.CantripDeck5",scroll:"PF2E.Item.Physical.FromSpell.Scroll",wand:"PF2E.Item.Physical.FromSpell.Wand"},wandCompendiumIds={1:"UJWiN0K3jqVjxvKk",2:"vJZ49cgi8szuQXAD",3:"wrDmWkGxmwzYtfiA",4:"Sn7v9SsbEDMUIwrO",5:"5BF7zMnrPYzyigCs",6:"kiXh4SUWKr166ZeM",7:"nmXPj9zuMRQBNT60",8:"Qs8RgNH6thRPv2jt",9:"Fgv722039TVM5JTc"};function getIdForSpellConsumable(type,heightenedLevel){switch(type){case"cantripDeck5":return CANTRIP_DECK_ID;case"scroll":return scrollCompendiumIds[heightenedLevel]??null;default:return wandCompendiumIds[heightenedLevel]??null}}__name(getIdForSpellConsumable,"getIdForSpellConsumable"),__name2(getIdForSpellConsumable,"getIdForSpellConsumable");function getNameForSpellConsumable(type,spellName,heightenedLevel){const templateId=SPELL_CONSUMABLE_NAME_TEMPLATES[type]||`${type} of {name} (Level {level})`;return game.i18n.format(templateId,{name:spellName,level:heightenedLevel})}__name(getNameForSpellConsumable,"getNameForSpellConsumable"),__name2(getNameForSpellConsumable,"getNameForSpellConsumable");function isSpellConsumable(itemId){return itemId===CANTRIP_DECK_ID||Object.values(scrollCompendiumIds).includes(itemId)||Object.values(wandCompendiumIds).includes(itemId)}__name(isSpellConsumable,"isSpellConsumable"),__name2(isSpellConsumable,"isSpellConsumable");async function createConsumableFromSpell(spell,{type,heightenedLevel=spell.baseRank,mystified=!1}){const pack=game.packs.find(p=>p.collection==="pf2e.equipment-srd"),itemId=getIdForSpellConsumable(type,heightenedLevel),consumable=await pack?.getDocument(itemId??"");if(!(consumable instanceof ConsumablePF2e))throw ErrorPF2e("Failed to retrieve consumable item");const consumableSource={...consumable.toObject(),_id:null},{traits}=consumableSource.system;traits.value=uniq([...traits.value,...spell.traits]),traits.rarity=spell.rarity,traits.value.includes("magical")&&traits.value.some(t=>setHasElement(MAGIC_TRADITIONS,t))&&traits.value.splice(traits.value.indexOf("magical"),1),traits.value.sort(),consumableSource.name=getNameForSpellConsumable(type,spell.name,heightenedLevel);const description=consumableSource.system.description.value;return consumableSource.system.description.value=(()=>{const paragraphElement=document.createElement("p");paragraphElement.append(spell.sourceId?`@UUID[${spell.sourceId}]{${spell.name}}`:spell.description);const containerElement=document.createElement("div"),hrElement=document.createElement("hr");return containerElement.append(paragraphElement,hrElement),hrElement.insertAdjacentHTML("afterend",description),containerElement.innerHTML})(),type!=="cantripDeck5"&&(consumableSource.system.spell=spell.clone({"system.location.heightenedLevel":heightenedLevel}).toObject()),mystified&&(consumableSource.system.identification.status="unidentified"),consumableSource}__name(createConsumableFromSpell,"createConsumableFromSpell"),__name2(createConsumableFromSpell,"createConsumableFromSpell");function calculateTrickMagicItemCheckDC(item,options={pwol:!1}){const level=Number(item.level),saveDC=calculateDC(level,options),traditions=item.system.spell?.system.traits.traditions??[],skills=[...item.system.traits.value,...traditions].filter(t=>setHasElement(MAGIC_TRADITIONS,t)).map(tradition=>[traditionSkills[tradition],saveDC]);return Object.fromEntries(skills)}__name(calculateTrickMagicItemCheckDC,"calculateTrickMagicItemCheckDC"),__name2(calculateTrickMagicItemCheckDC,"calculateTrickMagicItemCheckDC");async function preImportJSON(document2,json2){const source=JSON.parse(json2);if(!isObject(source)||("data"in source&&("items"in source?ActorPF2e.migrateData(source):ItemPF2e.migrateData(source)),!isObject(source.system)))return null;const sourceSchemaVersion=Number(source.system?._migration?.version)||0,worldSchemaVersion=MigrationRunnerBase.LATEST_SCHEMA_VERSION;if(foundry.utils.isNewerVersion(sourceSchemaVersion,worldSchemaVersion))return ui.notifications.error(game.i18n.format("PF2E.ErrorMessage.CantImportTooHighVersion",{sourceName:game.i18n.localize("DOCUMENT.Actor"),sourceSchemaVersion,worldSchemaVersion})),null;const newDoc=new document2.constructor(source,{parent:document2.parent}),migrations=MigrationList.constructFromVersion(newDoc.schemaVersion);return await MigrationRunner.ensureSchemaVersion(newDoc,migrations),JSON.stringify(newDoc.toObject())}__name(preImportJSON,"preImportJSON"),__name2(preImportJSON,"preImportJSON");function combatantAndTokenDoc(document2){return document2 instanceof CombatantPF2e?{combatant:document2,tokenDoc:document2.token}:{combatant:document2.combatant,tokenDoc:document2}}__name(combatantAndTokenDoc,"combatantAndTokenDoc"),__name2(combatantAndTokenDoc,"combatantAndTokenDoc");async function processGrantDeletions(item,pendingItems){const{actor}=item,granter=actor.items.get(item.flags.pf2e.grantedBy?.id??""),parentGrant=Object.values(granter?.flags.pf2e.itemGrants??{}).find(g=>g.id===item.id),grants=Object.values(item.flags.pf2e.itemGrants);if(granter&&parentGrant?.onDelete==="restrict"&&!pendingItems.includes(granter)){ui.notifications.warn(game.i18n.format("PF2E.Item.RemovalPrevented",{item:item.name,preventer:granter.name})),pendingItems.splice(pendingItems.indexOf(item),1);return}for(const grant of grants){const grantee=actor.items.get(grant.id);if(grantee?.flags.pf2e.grantedBy?.id===item.id&&grantee.flags.pf2e.grantedBy.onDelete==="restrict"&&!pendingItems.includes(grantee)){ui.notifications.warn(game.i18n.format("PF2E.Item.RemovalPrevented",{item:item.name,preventer:grantee.name})),pendingItems.splice(pendingItems.indexOf(item),1);return}}granter&&parentGrant?.onDelete==="cascade"&&!pendingItems.includes(granter)&&(pendingItems.push(granter),await processGrantDeletions(granter,pendingItems));for(const grant of grants){const grantee=actor.items.get(grant.id);grantee?.flags.pf2e.grantedBy?.id===item.id&&grantee.flags.pf2e.grantedBy.onDelete==="cascade"&&!pendingItems.includes(grantee)&&(pendingItems.push(grantee),await processGrantDeletions(grantee,pendingItems))}const[key]=Object.entries(granter?.flags.pf2e.itemGrants??{}).find(([,g])=>g===parentGrant)??[null];granter&&key&&!pendingItems.includes(granter)&&await granter.update({[`flags.pf2e.itemGrants.-=${key}`]:null},{render:!1});for(const grant of grants){const grantee=actor.items.get(grant.id);grantee?.flags.pf2e.grantedBy?.id===item.id&&grantee.flags.pf2e.grantedBy.onDelete==="detach"&&!pendingItems.includes(grantee)&&await grantee.update({"flags.pf2e.-=grantedBy":null},{render:!1})}}__name(processGrantDeletions,"processGrantDeletions"),__name2(processGrantDeletions,"processGrantDeletions");class ItemPF2e extends Item{static{__name(this,"ItemPF2e")}static{__name2(this,"ItemPF2e")}static getDefaultArtwork(itemData){return{img:`systems/pf2e/icons/default-icons/${itemData.type}.svg`}}get slug(){return this.system.slug}get sourceId(){return this.flags.core?.sourceId??null}get schemaVersion(){return Number(this.system._migration?.version??this.system.schema?.version)||null}get description(){return this.system.description.value.trim()}get grantedBy(){return this.actor?.items.get(this.flags.pf2e.grantedBy?.id??"")??null}get inMemoryOnly(){return!this.collection.has(this.id)}static fromDropData(data,options){if("uuid"in data&&UUIDUtils.isItemUUID(data.uuid)){const item=fromUuidSync(data.uuid);item instanceof ItemPF2e&&item.parent&&!item.sourceId&&(item._source.flags=foundry.utils.mergeObject(item._source.flags,{core:{sourceId:item.uuid}}),item.flags=foundry.utils.mergeObject(item.flags,{core:{sourceId:item.uuid}}))}return super.fromDropData(data,options)}isOfType(...types){return types.some(t=>t==="physical"?setHasElement(PHYSICAL_ITEM_TYPES,this.type):this.type===t)}async delete(context={}){return this.actor?(await this.actor.deleteEmbeddedDocuments("Item",[this.id],context),this):super.delete(context)}getRollOptions(prefix=this.type){if(prefix.length===0)throw ErrorPF2e("`prefix` must be at least one character long");const slug=this.slug??sluggify(this.name),{value:traits=[],otherTags}=this.system.traits,traitOptions=(()=>{const damageType=Object.keys(CONFIG.PF2E.damageTypes).join("|"),diceOrNumber=/-(?:[0-9]*d)?[0-9]+(?:-min)?$/,versatile=new RegExp(`-(?:b|p|s|${damageType})$`),deannotated=traits.filter(t=>diceOrNumber.test(t)||versatile.test(t)).map(t=>t.replace(diceOrNumber,"").replace(versatile,""));return[traits,deannotated].flat().map(t=>`trait:${t}`)})(),options=[`${prefix}:id:${this.id}`,`${prefix}:${slug}`,`${prefix}:slug:${slug}`,...traitOptions.map(t=>`${prefix}:${t}`),...otherTags.map(t=>`${prefix}:tag:${t}`)];(this.isOfType("spell")||traits.some(t=>["magical",...MAGIC_TRADITIONS].includes(t)))&&options.push(`${prefix}:magical`);const level=this.isOfType("spell")?this.rank:this.system.level?.value??null;typeof level=="number"&&options.push(`${prefix}:level:${level}`);const itemType=this.isOfType("feat")&&this.isFeature?"feature":this.type;return prefix!==itemType&&options.unshift(`${prefix}:type:${itemType}`),options}getRollData(){return{...this.actor?.getRollData()??{actor:null},item:this}}async toMessage(event2,options={}){if(!this.actor)throw ErrorPF2e(`Cannot create message for unowned item ${this.name}`);const template=`systems/pf2e/templates/chat/${sluggify(this.type)}-card.hbs`,token=this.actor.token,nearestItem=htmlClosest(event2?.target,".item"),rollOptions=options.data??{...nearestItem?.dataset??{}},templateData={actor:this.actor,tokenId:token?`${token.parent?.id}.${token.id}`:null,item:this,data:await this.getChatData(void 0,rollOptions)},originalEvent=event2 instanceof MouseEvent?event2:event2?.originalEvent,rollMode=options.rollMode??eventToRollMode(originalEvent),chatData=ChatMessagePF2e.applyRollMode({type:CONST.CHAT_MESSAGE_TYPES.OTHER,speaker:ChatMessagePF2e.getSpeaker({actor:this.actor,token:this.actor.getActiveTokens(!1,!0).at(0)}),content:await renderTemplate(template,templateData),flags:{pf2e:{origin:this.getOriginData()}}},rollMode);return options.create??!0?ChatMessagePF2e.create(chatData,{rollMode,renderSheet:!1}):new ChatMessagePF2e(chatData,{rollMode})}async toChat(event2){return this.toMessage(event2,{create:!0})}_initialize(options){this.rules=[],super._initialize(options)}prepareData(){this.parent&&!this.parent.flags?.pf2e||super.prepareData()}prepareBaseData(){super.prepareBaseData();const{flags}=this;flags.pf2e=foundry.utils.mergeObject(flags.pf2e??{},{rulesSelections:{}}),this.system.slug||=null,isObject(flags.pf2e.grantedBy)&&(flags.pf2e.grantedBy.onDelete??=this.isOfType("physical")?"detach":"cascade");const grants=flags.pf2e.itemGrants??={};for(const grant of Object.values(grants))isObject(grant)&&(grant.onDelete??="detach")}prepareRuleElements(options={}){if(!this.actor)throw ErrorPF2e("Rule elements may only be prepared from embedded items");return this.rules=this.actor.canHostRuleElements?RuleElements.fromOwnedItem({...options,parent:this}):[]}async refreshFromCompendium(options={name:!0,notify:!0}){if(!this.isOwned)throw ErrorPF2e("This utility may only be used on owned items");if(!this.sourceId?.startsWith("Compendium."))throw ErrorPF2e(`Item "${this.name}" has no compendium source.`);options.name??=!0,options.notify??=!0;const currentSource=this.toObject();if(currentSource.system.rules.some(r=>typeof r.key=="string"&&["ChoiceSet","GrantItem"].includes(r.key))){ui.notifications.warn("PF2E.Item.RefreshFromCompendium.Tooltip.Disabled",{localize:!0});return}const latestSource=(await fromUuid(this.sourceId))?.toObject();if(latestSource){if(latestSource.type!==this.type){ui.notifications.error(`The compendium source for "${this.name}" is of a different type than what is present on this actor.`);return}}else{ui.notifications.warn(game.i18n.format("PF2E.Item.RefreshFromCompendium.SourceNotFound",{item:this.name,sourceId:this.sourceId}));return}const updates={name:options.name?latestSource.name:currentSource.name,img:latestSource.img,system:foundry.utils.deepClone(latestSource.system)};if(updates.system.level&¤tSource.type==="feat"&&(updates.system.level={value:updates.system.level.value,taken:currentSource.system.level.taken}),isPhysicalData(currentSource)){if(foundry.utils.mergeObject(updates,foundry.utils.expandObject({"system.containerId":currentSource.system.containerId,"system.equipped":currentSource.system.equipped,"system.material":currentSource.system.material,"system.quantity":currentSource.system.quantity,"system.size":currentSource.system.size})),itemIsOfType(currentSource,"armor","shield","weapon")&&foundry.utils.mergeObject(updates,foundry.utils.expandObject({"system.runes":currentSource.system.runes})),currentSource.type==="consumable"&¤tSource.system.spell?.system?.traits&&tupleHasValue(["scroll","wand"],currentSource.system.category)&&latestSource.type==="consumable"&&!latestSource.system.spell){const spellSourceId=currentSource.system.spell.flags.core?.sourceId??"",refreshedSpell=await fromUuid(currentSource.system.spell.flags.core?.sourceId??"");if(refreshedSpell instanceof ItemPF2e&&refreshedSpell.isOfType("spell")){const spellConsumableData=await createConsumableFromSpell(refreshedSpell,{type:currentSource.system.category,heightenedLevel:currentSource.system.spell.system.location.heightenedLevel});foundry.utils.mergeObject(updates,{name:spellConsumableData.name,system:{spell:spellConsumableData.system.spell}})}else{ui.notifications.warn(game.i18n.format("PF2E.Item.RefreshFromCompendium.SourceNotFound",{item:currentSource.system.spell.name,sourceId:spellSourceId}));return}}}else itemIsOfType(currentSource,"campaignFeature","feat","spell")&&foundry.utils.mergeObject(updates,foundry.utils.expandObject({"system.location":currentSource.system.location}));currentSource.type==="feat"&¤tSource.system.level.taken&&foundry.utils.mergeObject(updates,foundry.utils.expandObject({"system.level.taken":currentSource.system.level.taken})),await this.update(updates,{diff:!1,recursive:!1}),options.notify&&ui.notifications.info(`Item "${this.name}" has been refreshed.`)}getOriginData(){return{actor:this.actor?.uuid,uuid:this.uuid,type:this.type}}async processChatData(htmlOptions={},data){if(data.properties=data.properties?.filter(property=>property!==null)??[],isItemSystemData(data)){const chatData=foundry.utils.duplicate(data);return htmlOptions.rollData=foundry.utils.mergeObject(this.getRollData(),htmlOptions.rollData??{}),chatData.description.value=await TextEditor.enrichHTML(chatData.description.value,{...htmlOptions,async:!0}),chatData}return data}async getChatData(htmlOptions={},_rollOptions={}){if(!this.actor)throw ErrorPF2e(`Cannot retrieve chat data for unowned item ${this.name}`);const systemData={...this.system,traits:this.traitChatData()};return this.processChatData(htmlOptions,foundry.utils.deepClone(systemData))}traitChatData(dictionary={},traits=this.system.traits.value??[]){return traits.map(trait=>{const label=game.i18n.localize(dictionary[trait]??trait),traitDescriptions2=CONFIG.PF2E.traitsDescriptions;return{value:trait,label,description:traitDescriptions2[trait]}}).sort((a,b)=>a.label.localeCompare(b.label,game.i18n.lang))}static async createDialog(data={},context={}){const omittedTypes=["condition","spellcastingEntry","lore"];omittedTypes.push("affliction","book"),game.settings.get("pf2e","campaignType")!=="kingmaker"&&omittedTypes.push("campaignFeature");const original=game.system.documentTypes.Item;try{return game.system.documentTypes.Item=difference(original,omittedTypes),super.createDialog(data,{...context,classes:[...context.classes??[],"dialog-item-create"]})}finally{game.system.documentTypes.Item=original}}async importFromJSON(json2){const processed=await preImportJSON(this,json2);return processed?super.importFromJSON(processed):this}toDragData(){return{...super.toDragData(),itemType:this.type}}static async createDocuments(data=[],context={}){const sources=data.map(d=>d instanceof ItemPF2e?d.toObject():d);for(const source of[...sources]){if(source.effects=[],!Object.keys(source).some(k=>k.startsWith("flags")||k.startsWith("system"))){source.system={_migration:{version:MigrationRunnerBase.LATEST_SCHEMA_VERSION}};continue}const item=new CONFIG.Item.documentClass(source);await MigrationRunner.ensureSchemaVersion(item,MigrationList.constructFromVersion(item.schemaVersion)),data.splice(data.indexOf(source),1,item.toObject())}const actor=context.parent;if(!actor)return super.createDocuments(sources,context);if(sources.some(s=>!actor.checkItemValidity(s)))return[];const effectSources=sources.filter(s=>["affliction","condition","effect"].includes(s.type));for(const source of effectSources){const effect=new CONFIG.PF2E.Item.documentClasses[source.type](foundry.utils.deepClone(source),{parent:actor}),isUnaffected=effect.isOfType("condition")&&!actor.isAffectedBy(effect),isImmune=actor.isImmuneTo(effect);if((isUnaffected||isImmune)&&(sources.splice(sources.indexOf(source),1),!(effect.isOfType("effect")&&effect.fromAura))){const locKey=isUnaffected?"PF2E.Damage.IWR.ActorIsUnaffected":"PF2E.Damage.IWR.ActorIsImmune",message=game.i18n.format(locKey,{actor:actor.name,effect:effect.name});ui.notifications.info(message)}}const preCreateDeletions=["ancestry","background","class","heritage","deity"].filter(type=>sources.some(s=>s.type===type)).flatMap(type=>actor.itemTypes[type]);if(preCreateDeletions.length){const idsToDelete=preCreateDeletions.map(i=>i.id);await actor.deleteEmbeddedDocuments("Item",idsToDelete,{render:!1})}const items=await(async()=>{async function getSimpleGrants(item){const granted=await item.createGrantedItems?.({size:context.parent?.size})??[];if(!granted.length)return[];const reparented=granted.map(i=>i.parent?i:new CONFIG.Item.documentClass(i._source,{parent:actor}));return[...reparented,...(await Promise.all(reparented.map(getSimpleGrants))).flat()]}__name(getSimpleGrants,"getSimpleGrants"),__name2(getSimpleGrants,"getSimpleGrants");const items2=sources.map(source=>(context.keepId||context.keepEmbeddedIds||(source._id=foundry.utils.randomID()),new CONFIG.Item.documentClass(source,{parent:actor})));for(const item of[...items2]){const grants=await getSimpleGrants(item);grants.length&&(context.keepId=!0,items2.push(...grants))}return items2})(),outputSources=items.map(i=>i._source);for(const item of items){item.prepareActorData?.();const itemSource=item._source,rules=item.prepareRuleElements({suppressWarnings:!0});for(const rule of rules){const ruleSource=itemSource.system.rules[rules.indexOf(rule)];await rule.preCreate?.({itemSource,ruleSource,pendingItems:outputSources,tempItems:items,context})}}if(outputSources.some(i=>i.type==="class")){const classFeatures=outputSources.filter(i=>i.type==="feat"&&typeof i.system?.level?.value=="number"&&i.system.category==="classfeature"&&!i.flags?.pf2e?.grantedBy);for(const feature of classFeatures)feature.sort=classFeatures.indexOf(feature)*100*(feature.system.level?.value??1)}const nonKits=outputSources.filter(source=>source.type!=="kit");return super.createDocuments(nonKits,context)}static async deleteDocuments(ids=[],context={}){ids=Array.from(new Set(ids));const actor=context.parent;if(actor){const items=ids.flatMap(id=>actor.items.get(id)??[]),containers=items.filter(i=>i.isOfType("backpack"));for(const container of containers)await container.ejectContents();for(const item of[...items]){for(const rule of item.rules)await rule.preDelete?.({pendingItems:items,context});await processGrantDeletions(item,items)}ids=Array.from(new Set(items.map(i=>i.id))).filter(id=>actor.items.has(id))}return super.deleteDocuments(ids,context)}async _preCreate(data,options,user){if(this._source.system.traits.value?.sort(),this.actor?.isOfType("character")&&this.isOfType("ancestry","background","class","feat","heritage")){const hpMaxDifference=this.actor.clone({items:[...this.actor.items.toObject(),data]}).hitPoints.max-this.actor.hitPoints.max;if(hpMaxDifference!==0){const newHitPoints=this.actor.hitPoints.value+hpMaxDifference;await this.actor.update({"system.attributes.hp.value":newHitPoints},{render:!1,allowHPOverage:!0})}}return this._source.system.rules=this._source.system.rules.filter(r=>!r.removeUponCreate),super._preCreate(data,options,user)}async _preUpdate(changed,options,user){if(changed.system?.description?.value===null&&(changed.system.description.value=""),changed.system?.level&&"value"in changed.system.level&&(changed.system.level.value=Math.max(0,Math.trunc(Number(changed.system.level.value)||0))),typeof changed.system?.slug=="string"&&(changed.system.slug=sluggify(changed.system.slug)||null),changed.system?.traits&&(Array.isArray(changed.system.traits.value)&&changed.system.traits.value.sort(),Array.isArray(changed.system.traits.otherTags)&&(changed.system.traits.otherTags=changed.system.traits.otherTags.map(t=>sluggify(t)).sort())),this.actor?.isOfType("character")&&this.isOfType("ancestry","background","class","feat","heritage")){const actorClone=this.actor.clone();actorClone.items.get(this.id,{strict:!0}).updateSource(changed,options),actorClone.reset();const hpMaxDifference=actorClone.hitPoints.max-this.actor.hitPoints.max;if(hpMaxDifference!==0){const newHitPoints=this.actor.hitPoints.value+hpMaxDifference;await this.actor.update({"system.attributes.hp.value":newHitPoints},{render:!1,allowHPOverage:!0})}}for(const rule of this.rules)await rule.preUpdate?.(changed);return super._preUpdate(changed,options,user)}_onCreate(data,options,userId){if(super._onCreate(data,options,userId),!(this.actor&&game.user.id===userId))return;this.actor.reset();const actorUpdates={};for(const rule of this.rules)rule.onCreate?.(actorUpdates);const updateKeys=Object.keys(actorUpdates);updateKeys.length>0&&!updateKeys.every(k=>k==="_id")&&this.actor.update(actorUpdates)}_onUpdate(data,options,userId){super._onUpdate(data,options,userId),game.ready&&game.items.get(this.id)===this&&ui.items.render()}_onDelete(options,userId){if(super._onDelete(options,userId),!(this.actor&&game.user.id===userId)||!(this.actor.isOfType("creature")&&this.canUserModify(game.user,"update")))return;const actorUpdates={};for(const rule of this.rules)rule.onDelete?.(actorUpdates);if(this.actor.isOfType("npc")&&["action","consumable"].includes(this.type)){const slug=this.slug??sluggify(this.name);if(this.actor.isToken){const promises=[];for(const item of this.actor.itemTypes.melee){const attackEffects=item.system.attackEffects.value;if(attackEffects.includes(slug)){const updatedEffects=attackEffects.filter(effect=>effect!==slug);promises.push(item.update({"system.attackEffects.value":updatedEffects}))}}promises.length>0&&Promise.allSettled(promises)}else{const itemUpdates=[];for(const attack of this.actor.itemTypes.melee){const attackEffects=attack.system.attackEffects.value;if(attackEffects.includes(slug)){const updatedEffects=attackEffects.filter(effect=>effect!==slug);itemUpdates.push({_id:attack.id,system:{attackEffects:{value:updatedEffects}}})}}itemUpdates.length>0&&foundry.utils.mergeObject(actorUpdates,{items:itemUpdates})}}const updateKeys=Object.keys(actorUpdates);updateKeys.length>0&&!updateKeys.every(k=>k==="_id")&&this.actor.update(actorUpdates)}}const ItemProxyPF2e=new Proxy(ItemPF2e,{construct(_target,args){const type=args[0]?.type==="armor"&&args[0].system?.category==="shield"?"shield":args[0]?.type,ItemClass=CONFIG.PF2E.Item.documentClasses[type]??ItemPF2e;return new ItemClass(...args)}}),DURATION_UNITS={rounds:6,minutes:60,hours:3600,days:86400};function calculateRemainingDuration(effect,durationData){if(durationData.unit==="encounter"){const isExpired=effect.system.expired;return{expired:!!isExpired,remaining:isExpired?0:1/0}}else if(durationData.unit==="unlimited"||!("start"in effect.system))return{expired:!1,remaining:1/0};const start=effect.system.start.value,{combatant}=game.combat??{},{unit,expiry}=durationData,duration=durationData.value*(DURATION_UNITS[durationData.unit]??0),addend=!combatant&&duration===0&&unit==="rounds"&&["turn-end","round-end"].includes(expiry??"")?1:0,remaining=start+duration+addend-game.time.worldTime,result={remaining,expired:remaining<=0};if(remaining===0&&combatant?.actor){const startInitiative=effect.system.start.initiative??0,currentInitiative=combatant.initiative??0,fightyActor=effect.actor?.isOfType("familiar")?effect.actor.master??effect.actor:effect.actor,atTurnStart=__name2(()=>startInitiative===currentInitiative&&combatant.actor===(effect.origin??fightyActor),"atTurnStart");result.expired=expiry==="turn-start"?atTurnStart():expiry==="turn-end"?currentInitiativestart:!1}return result}__name(calculateRemainingDuration,"calculateRemainingDuration"),__name2(calculateRemainingDuration,"calculateRemainingDuration");class AbstractEffectPF2e extends ItemPF2e{static{__name(this,"AbstractEffectPF2e")}static{__name2(this,"AbstractEffectPF2e")}get origin(){const originUUID=this.system.context?.origin.actor;if(!originUUID||originUUID===this.actor?.uuid)return this.actor;if(originUUID.startsWith("Scene.")){const tokenUUID=originUUID.replace(/\.Actor\..+$/,""),tokenDoc=fromUuidSync(tokenUUID);if(!(tokenDoc instanceof TokenDocumentPF2e))return null;const descriptor=Object.getOwnPropertyDescriptor(tokenDoc,"delta");return descriptor?.value instanceof ActorDelta?descriptor.value.syntheticActor??null:null}const actor=fromUuidSync(originUUID);return actor instanceof ActorPF2e?actor:null}get isIdentified(){return!0}get isLocked(){return!1}get fromSpell(){return this.system.fromSpell}get totalDuration(){const{duration}=this.system;return["unlimited","encounter"].includes(duration.unit)?1/0:duration.value*(DURATION_UNITS[duration.unit]??0)}get remainingDuration(){return calculateRemainingDuration(this,this.system.duration)}getRollOptions(prefix=this.type){const{origin}=this,originRollOptions=!!origin?.flags?.pf2e?.rollOptions?origin.getSelfRollOptions("origin").map(o=>`${prefix}:${o}`)??[]:[],{badge}=this,itemOrigin=this.grantedBy?.getRollOptions(`${prefix}:granter`)??[];return[...super.getRollOptions(prefix),...itemOrigin,...Object.entries({[`badge:type:${badge?.type}`]:!!badge,[`badge:value:${badge?.value}`]:!!badge,"from-spell":this.fromSpell}).filter(([,isTrue])=>isTrue).map(([key])=>`${prefix}:${key}`),...originRollOptions]}prepareBaseData(){super.prepareBaseData();const slug=this.slug??sluggify(this.name);this.rollOptionSlug=slug.replace(/^(?:[a-z]+-)?(?:effect|stance)-/,""),this.system.fromSpell??=!1}prepareActorData(){const actor=this.actor;if(!actor)throw ErrorPF2e("prepareActorData called from unembedded item");actor.rollOptions.all[`self:${this.type}:${this.rollOptionSlug}`]=!0;const badge=this.badge;if(typeof badge?.value=="number"){const values=actor.items.filter(i=>i instanceof AbstractEffectPF2e&&i.rollOptionSlug===this.rollOptionSlug).map(effect=>effect.badge?.value).filter(value=>typeof value=="number");badge.value>=Math.max(...values)&&(actor.rollOptions.all[`self:${this.type}:${this.rollOptionSlug}:${badge.value}`]=!0)}}_preCreate(data,options,user){return data.system.fromSpell??=(()=>{if((this.slug??sluggify(this.name)).startsWith("spell-effect-"))return!0;const originItem=fromUuidSync(this.system.context?.origin.item??"");return originItem instanceof ItemPF2e&&(originItem.isOfType("spell")||originItem.isOfType("affliction","condition","effect")&&originItem.fromSpell)})(),super._preCreate(data,options,user)}_onCreate(data,options,userId){super._onCreate(data,options,userId),this.handleChange({create:this})}_onDelete(options,userId){super._onDelete(options,userId),this.handleChange({delete:{name:this._source.name}})}handleChange(change){const skipFloatyText=this.isOfType("condition")&&!game.user.isGM&&!this.actor?.hasPlayerOwner&&game.settings.get("pf2e","metagame_secretCondition"),auraNotInCombat=this.flags.pf2e.aura&&!game.combat?.started,identified=game.user.isGM||this.isIdentified;if(!(skipFloatyText||!identified||auraNotInCombat)){if(this.isLocked||this.actor?.getActiveTokens().shift()?.showFloatyText(change),this.isOfType("condition"))for(const token of this.actor?.getActiveTokens()??[])token._onApplyStatusEffect(this.rollOptionSlug,!1);game.pf2e.StatusEffects.refresh()}}}var define_CONDITION_SOURCES_default=[{_id:"1wQY3JYyhMYeeV2G",img:"systems/pf2e/icons/conditions/observed.webp",name:"Observed",system:{description:{value:"
Anything in plain view is observed by you. If a creature takes measures to avoid detection, such as by using Stealth to @UUID[Compendium.pf2e.actionspf2e.Item.XMcnh4cSI32tljXa]{Hide}, it can become @UUID[Compendium.pf2e.conditionitems.Item.iU0fEDdBp3rXpTMC]{Hidden} or @UUID[Compendium.pf2e.conditionitems.Item.VRSef5y1LmL2Hkjf]{Undetected} instead of observed. If you have another precise sense besides sight, you might be able to observe a creature or object using that sense instead. You can observe a creature with only your precise senses. When @UUID[Compendium.pf2e.actionspf2e.Item.BlAOM2X92SI6HMtJ]{Seeking} a creature using only imprecise senses, it remains hidden, rather than observed.
"},duration:{value:0},group:"detection",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"observed",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.1wQY3JYyhMYeeV2G"}},effects:[]},{_id:"3uh1r86TzbQvosxv",img:"systems/pf2e/icons/conditions/doomed.webp",name:"Doomed",system:{description:{value:`
Your soul has been gripped by a powerful force that calls you closer to death. Doomed always includes a value. The @UUID[Compendium.pf2e.conditionitems.Item.yZRUzMqrMmfLu0V1]{Dying} value at which you die is reduced by your doomed value. If your maximum dying value is reduced to 0, you instantly die. When you die, you're no longer doomed.
Your doomed value decreases by 1 each time you get a full night's rest.
`},duration:{value:0},group:"death",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!0,value:1},slug:"doomed",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.3uh1r86TzbQvosxv"}},effects:[]},{_id:"4D2KBtexWXa6oUMR",img:"systems/pf2e/icons/conditions/drained.webp",name:"Drained",system:{description:{value:`
Your health and vitality have been depleted as you've lost blood, life force, or some other essence. Drained always includes a value. You take a status penalty equal to your drained value on Constitution-based checks, such as Fortitude saves. You also lose a number of Hit Points equal to your level (minimum 1) times the drained value, and your maximum Hit Points are reduced by the same amount. For example, if you become drained 3 and you're a 3rd-level character, you lose 9 Hit Points and reduce your maximum Hit Points by 9. Losing these Hit Points doesn't count as taking damage.
Each time you get a full night's rest, your drained value decreases by 1. This increases your maximum Hit Points, but you don't immediately recover the lost Hit Points.
Broken is a condition that affects only objects. An object is broken when damage has reduced its Hit Points to equal or less than its Broken Threshold. A broken object can't be used for its normal function, nor does it grant bonuses\u2014with the exception of armor. Broken armor still grants its item bonus to AC, but it also imparts a status penalty to AC depending on its category: \u20131 for broken light armor, \u20132 for broken medium armor, or \u20133 for broken heavy armor.
A broken item still imposes penalties and limitations normally incurred by carrying, holding, or wearing it. For example, broken armor would still impose its Dexterity modifier cap, check penalty, and so forth. If an effect makes an item broken automatically and the item has more HP than its Broken Threshold, that effect also reduces the item's current HP to the Broken Threshold.
`},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"broken",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.6dNUvdb1dhToNDj3"}},effects:[]},{_id:"6uEgoh53GbXuHpTF",img:"systems/pf2e/icons/conditions/paralyzed.webp",name:"Paralyzed",system:{description:{value:"
You're frozen in place. You have the @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} condition and can't act except to @UUID[Compendium.pf2e.actionspf2e.Item.1OagaWtBpVXExToo]{Recall Knowledge} and use actions that require only your mind (as determined by the GM). Your senses still function, but only in the areas you can perceive without moving, so you can't @UUID[Compendium.pf2e.actionspf2e.Item.BlAOM2X92SI6HMtJ]{Seek}.
"},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"ActiveEffectLike",mode:"override",path:"system.attributes.flanking.canFlank",value:!1},{inMemoryOnly:!0,key:"GrantItem",uuid:"Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg"}],value:{isValued:!1,value:null},slug:"paralyzed",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.6uEgoh53GbXuHpTF"}},effects:[]},{_id:"9evPzg9E6muFcoSk",img:"systems/pf2e/icons/conditions/unnoticed.webp",name:"Unnoticed",system:{description:{value:"
If you're unnoticed by a creature, that creature has no idea you're present. When you're unnoticed, you're also @UUID[Compendium.pf2e.conditionitems.Item.VRSef5y1LmL2Hkjf]{Undetected}. This matters for abilities that can be used only against targets totally unaware of your presence.
"},duration:{value:0},group:"detection",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"unnoticed",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.9evPzg9E6muFcoSk"}},effects:[]},{_id:"9PR9y0bi4JPKnHPR",img:"systems/pf2e/icons/conditions/deafened.webp",name:"Deafened",system:{description:{value:"
You can't hear. You automatically critically fail Perception checks that require you to be able to hear. You take a \u20132 status penalty to Perception checks for initiative and checks that involve sound but also rely on other senses. If you perform an action that has the auditory trait, you must succeed at a @Check[type:flat|showDC:all|dc:5] or the action is lost; attempt the check after spending the action but before any effects are applied. You are immune to auditory effects while deafened.
"},duration:{value:0},group:"senses",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:"perception-initiative",slug:"deafened",type:"status",value:-2},{key:"Immunity",type:"auditory"}],value:{isValued:!1,value:null},slug:"deafened",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.9PR9y0bi4JPKnHPR"}},effects:[]},{_id:"9qGBRpbX9NEwtAAr",img:"systems/pf2e/icons/conditions/controlled.webp",name:"Controlled",system:{description:{value:"
You have been commanded, magically dominated, or otherwise had your will subverted. The controller dictates how you act and can make you use any of your actions, including attacks, reactions, or even @UUID[Compendium.pf2e.actionspf2e.Item.A72nHGUtNXgY5Ey9]{Delay}. The controller usually doesn't have to spend their own actions when controlling you.
"},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"controlled",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.9qGBRpbX9NEwtAAr"}},effects:[]},{_id:"AdPVz7rbaVSRxHFg",img:"systems/pf2e/icons/conditions/fascinated.webp",name:"Fascinated",system:{description:{value:"
You're compelled to focus your attention on something, distracting you from whatever else is going on around you. You take a \u20132 status penalty to Perception and skill checks, and you can't use concentrate actions unless they (or their intended consequences) are related to the subject of your fascination, as determined by the GM. For instance, you might be able to @UUID[Compendium.pf2e.actionspf2e.Item.BlAOM2X92SI6HMtJ]{Seek} and @UUID[Compendium.pf2e.actionspf2e.Item.1OagaWtBpVXExToo]{Recall Knowledge} about the subject, but you likely couldn't cast a spell targeting a different creature. This condition ends if a creature uses hostile actions against you or any of your allies.
"},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:["perception","skill-check"],slug:"fascinated",type:"status",value:-2}],value:{isValued:!1,value:null},slug:"fascinated",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.AdPVz7rbaVSRxHFg"}},effects:[]},{_id:"AJh5ex99aV6VTggg",img:"systems/pf2e/icons/conditions/off-guard.webp",name:"Off-Guard",system:{active:!1,description:{value:`
You're distracted or otherwise unable to focus your full attention on defense. You take a \u20132 circumstance penalty to AC. Some effects give you the off-guard condition only to certain creatures or against certain attacks. Others\u2014especially conditions\u2014can make you off-guard against everything. If a rule doesn't specify that the condition applies only to certain circumstances, it applies to all of them, such as "The target is off-guard."
`},duration:{expiry:null,perpetual:!1,text:"",unit:"unlimited",value:-1},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},removable:!1,rules:[{key:"FlatModifier",selector:"ac",slug:"off-guard",type:"circumstance",value:-2}],traits:{},value:{isValued:!1,value:null},slug:"off-guard",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg"}},effects:[]},{_id:"D5mg6Tc7Jzrj6ro7",img:"systems/pf2e/icons/conditions/encumbered.webp",name:"Encumbered",system:{description:{value:"
You are carrying more weight than you can manage. While you're encumbered, you're @UUID[Compendium.pf2e.conditionitems.Item.i3OJZU2nk64Df3xm]{Clumsy 1} and take a 10-foot penalty to all your Speeds. As with all penalties to your Speed, this can't reduce your Speed below 5 feet.
"},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:"speed",slug:"encumbered",value:-10},{inMemoryOnly:!0,key:"GrantItem",uuid:"Compendium.pf2e.conditionitems.Item.i3OJZU2nk64Df3xm"}],value:{isValued:!1,value:null},slug:"encumbered",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.D5mg6Tc7Jzrj6ro7"}},effects:[]},{_id:"dfCMdR4wnpbYNTix",img:"systems/pf2e/icons/conditions/stunned.webp",name:"Stunned",system:{description:{value:`
You've become senseless. You can't act. Stunned usually includes a value, which indicates how many total actions you lose, possibly over multiple turns, from being stunned. Each time you regain actions, reduce the number you regain by your stunned value, then reduce your stunned value by the number of actions you lost. For example, if you were stunned 4, you would lose all 3 of your actions on your turn, reducing you to stunned 1; on your next turn, you would lose 1 more action, and then be able to use your remaining 2 actions normally. Stunned might also have a duration instead, such as "stunned for 1 minute," causing you to lose all your actions for the duration.
Stunned overrides @UUID[Compendium.pf2e.conditionitems.Item.xYTAsEpcJE1Ccni3]{Slowed}. If the duration of your stunned condition ends while you are slowed, you count the actions lost to the stunned condition toward those lost to being slowed. So, if you were stunned 1 and slowed 2 at the beginning of your turn, you would lose 1 action from stunned, and then lose only 1 additional action by being slowed, so you would still have 1 action remaining to use that turn.
`},duration:{value:0},group:null,overrides:["slowed"],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!0,value:1},slug:"stunned",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.dfCMdR4wnpbYNTix"}},effects:[]},{_id:"DmAIPqOBomZ7H95W",img:"systems/pf2e/icons/conditions/concealed.webp",name:"Concealed",system:{description:{value:"
You are difficult for one or more creatures to see due to thick fog or some other obscuring feature. You can be concealed to some creatures but not others. While concealed, you can still be @UUID[Compendium.pf2e.conditionitems.Item.1wQY3JYyhMYeeV2G]{Observed}, but you're tougher to target. A creature that you're concealed from must succeed at a @Check[type:flat|showDC:all|dc:5] when targeting you with an attack, spell, or other effect. If the check fails, you aren't affected. Area effects aren't subject to this flat check.
"},duration:{value:0},group:"senses",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"concealed",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.DmAIPqOBomZ7H95W"}},effects:[]},{_id:"dTwPJuKgBQCMxixg",img:"systems/pf2e/icons/conditions/petrified.webp",name:"Petrified",system:{description:{value:"
You have been turned to stone. You can't act, nor can you sense anything. You become an object with a Bulk double your normal Bulk (typically 12 for a petrified Medium creature or 6 for a petrified Small creature), AC 9, Hardness 8, and the same current Hit Points you had when alive. You don't have a Broken Threshold. When the petrified condition ends, you have the same number of Hit Points you had as a statue. If the statue is destroyed, you immediately die. While petrified, your mind and body are in stasis, so you don't age or notice the passing of time.
"},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"petrified",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.dTwPJuKgBQCMxixg"}},effects:[]},{_id:"e1XGnhKNSQIm5IXg",img:"systems/pf2e/icons/conditions/stupefied.webp",name:"Stupefied",system:{active:!1,description:{value:"
Your thoughts and instincts are clouded. Stupefied always includes a value. You take a status penalty equal to this value on Intelligence-, Wisdom-, and Charisma-based checks and DCs, including Will saving throws, spell attack modifiers, spell DCs, and skill checks that use these attribute modifiers. Any time you attempt to @UUID[Compendium.pf2e.actionspf2e.Item.aBQ8ajvEBByv45yz]{Cast a Spell} while stupefied, the spell is disrupted unless you succeed at a @Check[type:flat|showDC:all|dc:resolve(5+@item.badge.value)] with a DC equal to 5 + your stupefied value.
"},duration:{expiry:null,perpetual:!1,text:"",unit:"unlimited",value:-1},group:"abilities",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},removable:!1,rules:[{key:"FlatModifier",selector:["cha-based","int-based","wis-based"],slug:"stupefied",type:"status",value:"-@item.badge.value"}],traits:{},value:{immutable:!1,isValued:!0,value:1},slug:"stupefied",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.e1XGnhKNSQIm5IXg"}},effects:[]},{_id:"eIcWbB5o3pP6OIMe",img:"systems/pf2e/icons/conditions/immobilized.webp",name:"Immobilized",system:{description:{value:"
You are incapable of movement. You can't use any actions that have the move trait. If you're immobilized by something holding you in place and an external force would move you out of your space, the force must succeed at a check against either the DC of the effect holding you in place or the relevant defense (usually Fortitude DC) of the monster holding you in place.
"},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"immobilized",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.eIcWbB5o3pP6OIMe"}},effects:[]},{_id:"fBnFDH2MTzgFijKf",img:"systems/pf2e/icons/conditions/unconscious.webp",name:"Unconscious",system:{description:{value:`
You're sleeping or have been knocked out. You can't act. You take a \u20134 status penalty to AC, Perception, and Reflex saves, and you have the @UUID[Compendium.pf2e.conditionitems.Item.XgEqL1kFApUbl5Z2]{Blinded} and @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} conditions. When you gain this condition, you fall @UUID[Compendium.pf2e.conditionitems.Item.j91X7x0XSomq8d60]{Prone} and drop items you're holding unless the effect states otherwise or the GM determines you're positioned so you wouldn't.
If you're unconscious because you're @UUID[Compendium.pf2e.conditionitems.Item.yZRUzMqrMmfLu0V1]{Dying}, you can't wake up while you have 0 Hit Points. If you are restored to 1 Hit Point or more, you lose the dying and unconscious conditions and can act normally on your next turn.
If you are unconscious and at 0 Hit Points, but not dying, you return to 1 Hit Point and awaken after sufficient time passes. The GM determines how long you remain unconscious, from a minimum of 10 minutes to several hours. If you are healed, you lose the unconscious condition and can act normally on your next turn.
If you're unconscious and have more than 1 Hit Point (typically because you are asleep or unconscious due to an effect), you wake up in one of the following ways.
You take damage, though if the damage reduces you to 0 Hit Points, you remain unconscious and gain the dying condition as normal.
You receive healing, other than the natural healing you get from resting.
Someone shakes you awake with an @UUID[Compendium.pf2e.actionspf2e.Item.pvQ5rY2zrtPI614F]{Interact} action.
Loud noise around you might wake you. At the start of your turn, you automatically attempt a Perception check against the noise's DC (or the lowest DC if there is more than one noise), waking up if you succeed. If creatures are attempting to stay quiet around you, this Perception check uses their Stealth DCs. Some effects make you sleep so deeply that they don't allow you this Perception check.
If you are simply asleep, the GM decides you wake up either because you have had a restful night's sleep or something disrupted that rest.
`},duration:{value:0},group:"death",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:["ac","perception","reflex"],slug:"unconscious",type:"status",value:-4},{key:"GrantItem",onDeleteActions:{grantee:"restrict"},uuid:"Compendium.pf2e.conditionitems.Item.XgEqL1kFApUbl5Z2"},{inMemoryOnly:!0,key:"GrantItem",uuid:"Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg"},{allowDuplicate:!1,key:"GrantItem",onDeleteActions:{grantee:"restrict",granter:"detach"},uuid:"Compendium.pf2e.conditionitems.Item.j91X7x0XSomq8d60"}],value:{isValued:!1,value:null},slug:"unconscious",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.fBnFDH2MTzgFijKf"}},effects:[]},{_id:"fesd1n5eVhpCSS18",img:"systems/pf2e/icons/conditions/sickened.webp",name:"Sickened",system:{description:{value:`
You feel ill. Sickened always includes a value. You take a status penalty equal to this value on all your checks and DCs. You can't willingly ingest anything\u2014including elixirs and potions\u2014while sickened.
You can spend a single action retching in an attempt to recover, which lets you immediately attempt a Fortitude save against the DC of the effect that made you sickened. On a success, you reduce your sickened value by 1 (or by 2 on a critical success).
`},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:"all",slug:"sickened",type:"status",value:"-@item.badge.value"}],value:{isValued:!0,value:1},slug:"sickened",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.fesd1n5eVhpCSS18"}},effects:[]},{_id:"fuG8dgthlDWfWjIA",img:"systems/pf2e/icons/conditions/indifferent.webp",name:"Indifferent",system:{description:{value:"
This condition reflects a creature's disposition toward a particular character, and only supernatural effects (like a spell) can impose this condition on a PC. A creature that is indifferent to a character doesn't really care one way or the other about that character. Assume a creature's attitude to a given character is indifferent unless specified otherwise.
"},duration:{value:0},group:"attitudes",overrides:["helpful","friendly","unfriendly","hostile"],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"indifferent",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.fuG8dgthlDWfWjIA"}},effects:[]},{_id:"HL2l2VRSaQHu9lUw",img:"systems/pf2e/icons/conditions/fatigued.webp",name:"Fatigued",system:{description:{value:`
You're tired and can't summon much energy. You take a \u20131 status penalty to AC and saving throws. You can't use exploration activities performed while traveling.
You recover from fatigue after a full night's rest.
`},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:["ac","saving-throw"],slug:"fatigued",type:"status",value:-1}],value:{isValued:!1,value:null},slug:"fatigued",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.HL2l2VRSaQHu9lUw"}},effects:[]},{_id:"I1ffBVISxLr2gC4u",img:"systems/pf2e/icons/conditions/unfriendly.webp",name:"Unfriendly",system:{description:{value:"
This condition reflects a creature's disposition toward a particular character, and only supernatural effects (like a spell) can impose this condition on a PC. A creature that is unfriendly to a character dislikes and distrusts that character. The unfriendly creature won't accept @UUID[Compendium.pf2e.actionspf2e.Item.DCb62iCBrJXy0Ik6]{Requests} from the character.
"},duration:{value:0},group:"attitudes",overrides:["helpful","friendly","indifferent","hostile"],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"unfriendly",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.I1ffBVISxLr2gC4u"}},effects:[]},{_id:"i3OJZU2nk64Df3xm",img:"systems/pf2e/icons/conditions/clumsy.webp",name:"Clumsy",system:{description:{value:"
Your movements become clumsy and inexact. Clumsy always includes a value. You take a status penalty equal to the condition value to Dexterity-based checks and DCs, including AC, Reflex saves, ranged attack rolls, and skill checks using Acrobatics, Stealth, and Thievery.
"},duration:{value:0},group:"abilities",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:"dex-based",slug:"clumsy",type:"status",value:"-@item.badge.value"}],value:{isValued:!0,value:1},slug:"clumsy",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.i3OJZU2nk64Df3xm"}},effects:[]},{_id:"iU0fEDdBp3rXpTMC",img:"systems/pf2e/icons/conditions/hidden.webp",name:"Hidden",system:{description:{value:`
While you're hidden from a creature, that creature knows the space you're in but can't tell precisely where you are. You typically become hidden by using Stealth to @UUID[Compendium.pf2e.actionspf2e.Item.XMcnh4cSI32tljXa]{Hide}. When @UUID[Compendium.pf2e.actionspf2e.Item.BlAOM2X92SI6HMtJ]{Seeking} a creature using only imprecise senses, it remains hidden, rather than @UUID[Compendium.pf2e.conditionitems.Item.1wQY3JYyhMYeeV2G]{Observed}. A creature you're hidden from is @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} to you, and it must succeed at a @Check[type:flat|showDC:all|dc:11] when targeting you with an attack, spell, or other effect or it fails to affect you. Area effects aren't subject to this flat check.
A creature might be able to use the seek action to try to observe you.
`},duration:{value:0},group:"detection",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"hidden",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.iU0fEDdBp3rXpTMC"}},effects:[]},{_id:"j91X7x0XSomq8d60",img:"systems/pf2e/icons/conditions/prone.webp",name:"Prone",system:{description:{value:`
You're lying on the ground. You are @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} and take a \u20132 circumstance penalty to attack rolls. The only move actions you can use while you're prone are @UUID[Compendium.pf2e.actionspf2e.Item.Tj055UcNm6UEgtCg]{Crawl} and @UUID[Compendium.pf2e.actionspf2e.Item.OdIUybJ3ddfL7wzj]{Stand}. Standing up ends the prone condition. You can @UUID[Compendium.pf2e.actionspf2e.Item.ust1jJSCZQUhBZIz]{Take Cover} while prone to hunker down and gain greater cover against ranged attacks, even if you don't have an object to get behind, which grants you a +4 circumstance bonus to AC against ranged attacks (but you remain off-guard).
If you would be knocked prone while you're @UUID[Compendium.pf2e.actionspf2e.Item.pprgrYQ1QnIDGZiy]{Climbing} or @UUID[Compendium.pf2e.actionspf2e.Item.cS9nfDRGD83bNU1p]{Flying}, you fall. You can't be knocked prone when @UUID[Compendium.pf2e.actionspf2e.Item.c8TGiZ48ygoSPofx]{Swimming}.
`},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:"attack-roll",slug:"prone",type:"circumstance",value:-2},{inMemoryOnly:!0,key:"GrantItem",uuid:"Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg"}],value:{isValued:!1,value:null},slug:"prone",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.j91X7x0XSomq8d60"}},effects:[]},{_id:"kWc1fhmv9LBiTuei",img:"systems/pf2e/icons/conditions/grabbed.webp",name:"Grabbed",system:{description:{value:"
You're held in place by another creature, giving you the @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} and @UUID[Compendium.pf2e.conditionitems.Item.eIcWbB5o3pP6OIMe]{Immobilized} conditions. If you attempt a manipulate action while grabbed, you must succeed at a @Check[type:flat|showDC:all|dc:5] or it is lost; roll the check after spending the action, but before any effects are applied.
"},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{inMemoryOnly:!0,key:"GrantItem",uuid:"Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg"},{inMemoryOnly:!0,key:"GrantItem",uuid:"Compendium.pf2e.conditionitems.Item.eIcWbB5o3pP6OIMe"}],value:{isValued:!1,value:null},slug:"grabbed",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.kWc1fhmv9LBiTuei"}},effects:[]},{_id:"lDVqvLKA6eF3Df60",img:"systems/pf2e/icons/conditions/persistent-damage.webp",name:"Persistent Damage",system:{description:{value:'
You are taking damage from an ongoing effect, such as from being lit on fire. This appears as "X persistent [type] damage," where "X" is the amount of damage dealt and "[type]" is the damage type. Like normal damage, it can be doubled or halved based on the results of an attack roll or saving throw. Instead of taking persistent damage immediately, you take it at the end of each of your turns as long as you have the condition, rolling any damage dice anew each time. After you take persistent damage, roll a @Check[type:flat|showDC:all|dc:15] to see if you recover from the persistent damage. If you succeed, the condition ends.
'},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"persistent-damage",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.lDVqvLKA6eF3Df60"}},effects:[]},{_id:"MIRkyAjyBeXivMa7",img:"systems/pf2e/icons/conditions/enfeebled.webp",name:"Enfeebled",system:{active:!1,description:{value:"
You're physically weakened. Enfeebled always includes a value. When you are enfeebled, you take a status penalty equal to the condition value to Strength-based rolls and DCs, including Strength-based melee attack rolls, Strength-based damage rolls, and Athletics checks.
"},duration:{expiry:null,perpetual:!1,text:"",unit:"unlimited",value:-1},group:"abilities",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},removable:!1,rules:[{key:"FlatModifier",selector:["str-based","str-damage"],slug:"enfeebled",type:"status",value:"-@item.badge.value"}],traits:{},value:{immutable:!1,isValued:!0,value:1},slug:"enfeebled",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.MIRkyAjyBeXivMa7"}},effects:[]},{_id:"nlCjDvLMf2EkV2dl",img:"systems/pf2e/icons/conditions/quickened.webp",name:"Quickened",system:{description:{value:"
You're able to act more quickly. You gain 1 additional action at the start of your turn each round. Many effects that make you quickened require you use this extra action only in certain ways. If you become quickened from multiple sources, you can use the extra action you've been granted for any single action allowed by any of the effects that made you quickened. Because quickened has its effect at the start of your turn, you don't immediately gain actions if you become quickened during your turn.
"},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"quickened",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.nlCjDvLMf2EkV2dl"}},effects:[]},{_id:"sDPxOjQ9kx2RZE8D",img:"systems/pf2e/icons/conditions/fleeing.webp",name:"Fleeing",system:{active:!1,description:{value:"
You're forced to run away due to fear or some other compulsion. On your turn, you must spend each of your actions trying to escape the source of the fleeing condition as expediently as possible (such as by using move actions to flee, or opening doors barring your escape). The source is usually the effect or creature that gave you the condition, though some effects might define something else as the source. You can't @UUID[Compendium.pf2e.actionspf2e.Item.A72nHGUtNXgY5Ey9]{Delay} or @UUID[Compendium.pf2e.actionspf2e.Item.dLgAMt3TbkmLkUqE]{Ready} while fleeing.
"},duration:{expiry:null,perpetual:!1,text:"",unit:"unlimited",value:-1},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},removable:!1,rules:[],traits:{},value:{isValued:!1,value:null},slug:"fleeing",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.sDPxOjQ9kx2RZE8D"}},effects:[]},{_id:"TBSHQspnbcqxsmjL",img:"systems/pf2e/icons/conditions/frightened.webp",name:"Frightened",system:{active:!1,description:{value:"
You're gripped by fear and struggle to control your nerves. The frightened condition always includes a value. You take a status penalty equal to this value to all your checks and DCs. Unless specified otherwise, at the end of each of your turns, the value of your frightened condition decreases by 1.
"},duration:{expiry:null,perpetual:!1,text:"",unit:"unlimited",value:-1},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},removable:!1,rules:[{key:"FlatModifier",selector:"all",slug:"frightened",type:"status",value:"-@item.badge.value"}],traits:{},value:{immutable:!1,isValued:!0,value:1},slug:"frightened",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.TBSHQspnbcqxsmjL"}},effects:[]},{_id:"TkIyaNPgTZFBCCuh",img:"systems/pf2e/icons/conditions/dazzled.webp",name:"Dazzled",system:{active:!1,description:{value:"
Your eyes are overstimulated or your vision is swimming. If vision is your only precise sense, all creatures and objects are @UUID[Compendium.pf2e.conditionitems.Item.DmAIPqOBomZ7H95W]{Concealed} from you.
"},duration:{expiry:null,perpetual:!1,text:"",unit:"unlimited",value:-1},group:"senses",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},removable:!1,rules:[],traits:{},value:{isValued:!1,value:null},slug:"dazzled",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.TkIyaNPgTZFBCCuh"}},effects:[]},{_id:"ud7gTLwPeklzYSXG",img:"systems/pf2e/icons/conditions/hostile.webp",name:"Hostile",system:{description:{value:"
This condition reflects a creature's disposition toward a particular character, and only supernatural effects (like a spell) can impose on a PC. A creature hostile to a character actively seeks to harm that character. It doesn't necessarily attack, but it won't accept @UUID[Compendium.pf2e.actionspf2e.Item.DCb62iCBrJXy0Ik6]{Requests} from the character.
"},duration:{value:0},group:"attitudes",overrides:["helpful","friendly","indifferent","unfriendly"],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"hostile",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.ud7gTLwPeklzYSXG"}},effects:[]},{_id:"v44P3WUcU1j0115l",img:"systems/pf2e/icons/conditions/helpful.webp",name:"Helpful",system:{description:{value:"
This condition reflects a creature's disposition toward a particular character, and only supernatural effects (like a spell) can impose this condition on a PC. A creature that is helpful to a character wishes to actively aid that character. It will accept reasonable @UUID[Compendium.pf2e.actionspf2e.Item.DCb62iCBrJXy0Ik6]{Requests} from that character, as long as such requests aren't at the expense of the helpful creature's goals or quality of life. If the character (or one of their allies) uses a hostile action against the creature, the creature gains a worse attitude condition depending on the severity of the hostile action, as determined by the GM.
"},duration:{value:0},group:"attitudes",overrides:["friendly","indifferent","unfriendly","hostile"],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"helpful",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.v44P3WUcU1j0115l"}},effects:[]},{_id:"v66R7FdOf11l94im",img:"systems/pf2e/icons/conditions/friendly.webp",name:"Friendly",system:{description:{value:"
This condition reflects a creature's disposition toward a particular character, and only supernatural effects (like a spell) can impose this condition on a PC. A creature that is friendly to a character likes that character. It is likely to agree to @UUID[Compendium.pf2e.actionspf2e.Item.DCb62iCBrJXy0Ik6]{Requests} from that character as long as they are simple, safe, and don't cost too much to fulfill. If the character (or one of their allies) uses hostile actions against the creature, the creature gains a worse attitude condition depending on the severity of the hostile action, as determined by the GM.
"},duration:{value:0},group:"attitudes",overrides:["helpful","indifferent","unfriendly","hostile"],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"friendly",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.v66R7FdOf11l94im"}},effects:[]},{_id:"VcDeM8A5oI6VqhbM",img:"systems/pf2e/icons/conditions/restrained.webp",name:"Restrained",system:{description:{value:"
You're tied up and can barely move, or a creature has you pinned. You have the @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} and @UUID[Compendium.pf2e.conditionitems.Item.eIcWbB5o3pP6OIMe]{Immobilized} conditions, and you can't use any attack or manipulate actions except to attempt to @UUID[Compendium.pf2e.actionspf2e.Item.SkZAQRkLLkmBQNB9]{Escape} or @UUID[Compendium.pf2e.actionspf2e.Item.SjmKHgI7a5Z9JzBx]{Force Open} your bonds. Restrained overrides @UUID[Compendium.pf2e.conditionitems.Item.kWc1fhmv9LBiTuei]{Grabbed}.
"},duration:{value:0},group:null,overrides:["grabbed"],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"ActiveEffectLike",mode:"override",path:"system.attributes.flanking.canFlank",value:!1},{inMemoryOnly:!0,key:"GrantItem",uuid:"Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg"},{inMemoryOnly:!0,key:"GrantItem",uuid:"Compendium.pf2e.conditionitems.Item.eIcWbB5o3pP6OIMe"}],value:{isValued:!1,value:null},slug:"restrained",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.VcDeM8A5oI6VqhbM"}},effects:[]},{_id:"VRSef5y1LmL2Hkjf",img:"systems/pf2e/icons/conditions/undetected.webp",name:"Undetected",system:{description:{value:`
When you are undetected by a creature, that creature can't see you at all, has no idea what space you occupy, and can't target you, though you still can be affected by abilities that target an area. When you're undetected by a creature, that creature is @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} to you.
A creature you're undetected by can guess which square you're in to try targeting you. It must pick a square and attempt an attack. This works like targeting a @UUID[Compendium.pf2e.conditionitems.Item.iU0fEDdBp3rXpTMC]{Hidden} creature (requiring a @Check[type:flat|showDC:all|dc:11|traits:secret]), but the flat check and attack roll are rolled in secret by the GM, who doesn't reveal whether the attack missed due to failing the flat check, failing the attack roll, or choosing the wrong square. They can @UUID[Compendium.pf2e.actionspf2e.Item.BlAOM2X92SI6HMtJ]{Seek} to try to find you.
`},duration:{value:0},group:"detection",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"undetected",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.VRSef5y1LmL2Hkjf"}},effects:[]},{_id:"XgEqL1kFApUbl5Z2",img:"systems/pf2e/icons/conditions/blinded.webp",name:"Blinded",system:{description:{value:"
You can't see. All normal terrain is difficult terrain to you. You can't detect anything using vision. You automatically critically fail Perception checks that require you to be able to see, and if vision is your only precise sense, you take a \u20134 status penalty to Perception checks. You are immune to visual effects. Blinded overrides @UUID[Compendium.pf2e.conditionitems.Item.TkIyaNPgTZFBCCuh]{Dazzled}.
"},duration:{value:0},group:"senses",overrides:["dazzled"],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:"perception",slug:"blinded",type:"status",value:-4},{key:"Immunity",type:"visual"}],value:{isValued:!1,value:null},slug:"blinded",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.XgEqL1kFApUbl5Z2"}},effects:[]},{_id:"xYTAsEpcJE1Ccni3",img:"systems/pf2e/icons/conditions/slowed.webp",name:"Slowed",system:{description:{value:"
You have fewer actions. Slowed always includes a value. When you regain your actions, reduce the number of actions regained by your slowed value. Because you regain actions at the start of your turn, you don't immediately lose actions if you become slowed during your turn.
"},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!0,value:1},slug:"slowed",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.xYTAsEpcJE1Ccni3"}},effects:[]},{_id:"yblD8fOR1J8rDwEQ",img:"systems/pf2e/icons/conditions/confused.webp",name:"Confused",system:{description:{value:`
You don't have your wits about you, and you attack wildly. You are @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard}, you don't treat anyone as your ally (though they might still treat you as theirs), and you can't Delay, Ready, or use reactions.
You use all your actions to Strike or cast offensive cantrips, though the GM can have you use other actions to facilitate attack, such as draw a weapon, move so target is in reach, and so forth. Your targets are determined randomly by the GM. If you have no other viable targets, you target yourself, automatically hitting but not scoring a critical hit. If it's impossible for you to attack or cast spells, you babble incoherently, wasting your actions.
Each time you take damage from an attack or spell, you can attempt a @Check[type:flat|showDC:all|dc:11] to recover from your confusion and end the condition.
`},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"ActiveEffectLike",mode:"override",path:"system.attributes.flanking.canFlank",value:!1},{inMemoryOnly:!0,key:"GrantItem",uuid:"Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg"}],value:{isValued:!1,value:null},slug:"confused",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.yblD8fOR1J8rDwEQ"}},effects:[]},{_id:"Yl48xTdMh3aeQYL2",img:"systems/pf2e/icons/conditions/wounded.webp",name:"Wounded",system:{active:!1,description:{value:`
You have been seriously injured. If you lose the @UUID[Compendium.pf2e.conditionitems.Item.yZRUzMqrMmfLu0V1]{Dying} condition and do not already have the wounded condition, you become wounded 1. If you already have the wounded condition when you lose the dying condition, your wounded condition value increases by 1. If you gain the dying condition while wounded, increase your dying condition value by your wounded value.
The wounded condition ends if someone successfully restores Hit Points to you using @UUID[Compendium.pf2e.actionspf2e.Item.1kGNdIIhuglAjIp9]{Treat Wounds}, or if you are restored to full Hit Points by any means and rest for 10 minutes.
`},duration:{expiry:null,perpetual:!1,text:"",unit:"unlimited",value:-1},group:"death",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},removable:!1,rules:[],traits:{},value:{immutable:!1,isValued:!0,value:1},slug:"wounded",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.Yl48xTdMh3aeQYL2"}},effects:[]},{_id:"yZRUzMqrMmfLu0V1",img:"systems/pf2e/icons/conditions/dying.webp",name:"Dying",system:{description:{value:`
You are bleeding out or otherwise at death's door. While you have this condition, you are @UUID[Compendium.pf2e.conditionitems.Item.fBnFDH2MTzgFijKf]{Unconscious}. Dying always includes a value, and if it ever reaches dying 4, you die. When you're dying, you must attempt a recovery check at the start of your turn each round to determine whether you get better or worse. Your dying condition increases by 1 if you take damage while dying, or by 2 if you take damage from an enemy's critical hit or a critical failure on your save.
If you lose the dying condition by succeeding at a recovery check and are still at 0 Hit Points, you remain unconscious, but you can wake up as described in that condition. You lose the dying condition automatically and wake up if you ever have 1 Hit Point or more. Any time you lose the dying condition, you gain the @UUID[Compendium.pf2e.conditionitems.Item.Yl48xTdMh3aeQYL2]{Wounded 1} condition, or increase your wounded condition value by 1 if you already have that condition.
`},duration:{value:0},group:"death",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"GrantItem",onDeleteActions:{grantee:"restrict"},uuid:"Compendium.pf2e.conditionitems.Item.fBnFDH2MTzgFijKf"}],value:{isValued:!0,value:1},slug:"dying",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.yZRUzMqrMmfLu0V1"}},effects:[]},{_id:"zJxUflt9np0q4yML",img:"systems/pf2e/icons/conditions/invisible.webp",name:"Invisible",system:{active:!1,description:{value:"
You can't be seen. You're @UUID[Compendium.pf2e.conditionitems.Item.VRSef5y1LmL2Hkjf]{Undetected} to everyone. Creatures can @UUID[Compendium.pf2e.actionspf2e.Item.BlAOM2X92SI6HMtJ]{Seek} to detect you; if a creature succeeds at its Perception check against your Stealth DC, you become @UUID[Compendium.pf2e.conditionitems.Item.iU0fEDdBp3rXpTMC]{Hidden} to that creature until you @UUID[Compendium.pf2e.actionspf2e.Item.VMozDqMMuK5kpoX4]{Sneak} to become undetected again. If you become invisible while someone can already see you, you start out hidden to them (instead of undetected) until you successfully Sneak. You can't become @UUID[Compendium.pf2e.conditionitems.Item.1wQY3JYyhMYeeV2G]{Observed} while invisible except via special abilities or magic.
"},duration:{expiry:null,perpetual:!1,text:"",unit:"unlimited",value:-1},group:"senses",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},removable:!1,rules:[],traits:{},value:{isValued:!1,value:null},slug:"invisible",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.zJxUflt9np0q4yML"}},effects:[]},{_id:"axtAzam8kiKbTD2c",img:"systems/pf2e/icons/conditions/malevolence.webp",name:"Malevolence",system:{active:!1,description:{value:`
As the malevolence begins to take its hold on creatures, their body, minds, and souls become increasingly haunted by the supernatural force infesting Xarwin Manor. Malevolence is a special condition that can affect PCs who play in this adventure. The malevolence condition always includes a value. You take a status penalty equal to this value to all saving throws against effects generated by haunts and against all curse and possession effects. The malevolence condition can be reduced by restoration.
The malevolence can never increase above a value of 4. If an effect would increase a creature's malevolence value higher than 4, the creature is instead @UUID[Compendium.pf2e.conditionitems.Item.e1XGnhKNSQIm5IXg]{Stupefied 1} for 24 hours as the malevolence consumes a few of their random, short-term memories. A creature that has a malevolence 4 won't voluntarily leave the Xarwin Manor grounds.
Each time you get a full night's rest in a region not influenced by the malevolence condition, the value of your malevolence decreases by 1.
`},duration:{perpetual:!1,text:"",value:0},group:null,overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Adventure: Malevolence"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},removable:!1,rules:[{key:"FlatModifier",predicate:[{or:["origin:trait:haunt","curse","possession"]}],selector:"saving-throw",slug:"malevolence",type:"status",value:"-@item.badge.value"}],value:{immutable:!1,isValued:!0,value:1},slug:"malevolence",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.campaign-effects.Item.axtAzam8kiKbTD2c"}},effects:[]}];class ConditionManager{static{__name(this,"ConditionManager")}static{__name2(this,"ConditionManager")}static#initialized=!1;static conditions=new Map;static CONDITION_SOURCES=define_CONDITION_SOURCES_default;static get conditionsSlugs(){return[...this.conditions.keys()].filter(k=>!k.startsWith("Compendium."))}static async initialize(force=!1){if(this.#initialized||(this.conditions=new Map(this.CONDITION_SOURCES?.flatMap(source=>{const condition=new ConditionPF2e(source,{pack:"pf2e.conditionitems"});return[[condition.slug,condition],[condition.uuid,condition]]})??[]),delete this.CONDITION_SOURCES),(!this.#initialized||force)&&game.i18n.lang!=="en"&&game.modules.get("babele")?.active){const localize=localizer("PF2E.condition");for(const condition of this.conditions.values())condition.name=condition._source.name=localize(`${condition.slug}.name`),condition.system.description.value=condition._source.system.description.value=localize(`${condition.slug}.rules`)}this.#initialized=!0}static getCondition(slug,modifications={}){if(slug=sluggify(slug),!setHasElement(CONDITION_SLUGS,slug))return null;const condition=ConditionManager.conditions.get(slug)?.clone(modifications);if(!condition)throw ErrorPF2e("Unexpected failure looking up condition");return condition}static async updateConditionValue(itemId,actorOrToken,value){const actor=actorOrToken instanceof ActorPF2e?actorOrToken:actorOrToken.actor,condition=actor?.items.get(itemId);condition?.isOfType("condition")&&(value===0?await condition.delete():actor?.isOfType("creature")&&(tupleHasValue(["dying","wounded","doomed"],condition.slug)&&(value=Math.min(value,actor.attributes[condition.slug].max)),await condition.update({"system.value.value":value})))}}const EXPIRING_CONDITIONS=new Set(["frightened","sickened","drained","doomed","stunned","unconscious"]);class AfflictionPF2e extends AbstractEffectPF2e{static{__name(this,"AfflictionPF2e")}static{__name2(this,"AfflictionPF2e")}constructor(source,context){throw super(source,context),ErrorPF2e("Affliction items are not available in production builds")}get badge(){return{type:"counter",value:this.stage,min:1,max:this.maxStage,label:this.onset?game.i18n.localize("PF2E.Item.Affliction.OnsetLabel"):game.i18n.format("PF2E.Item.Affliction.Stage",{stage:this.stage})}}get stage(){return this.system.stage}get stageData(){return Object.values(this.system.stages).at(this.stage-1)??null}get maxStage(){return Object.keys(this.system.stages).length||1}async increase(){if(this.onset)await this.update({system:{"-=onset":null}});else if(this.stage!==this.maxStage){const stage=Math.min(this.maxStage,this.system.stage+1);await this.update({system:{stage}})}}async decrease(){const stage=this.system.stage-1;if(stage===0){await this.delete();return}await this.update({system:{stage}})}get onset(){return!!this.system.onset?.active}get onsetDuration(){return this.system.onset?this.system.onset.value*(DURATION_UNITS[this.system.onset.unit]??0):0}get remainingStageDuration(){const stageDuration=this.stageData?.duration??{unit:"unlimited"};return calculateRemainingDuration(this,{...stageDuration,expiry:"turn-end"})}prepareBaseData(){super.prepareBaseData(),this.system.stage=Math.clamped(this.system.stage,this.badge.min,this.maxStage);for(const stage of Object.values(this.system.stages))for(const condition of Object.values(stage.conditions))condition.linked??=!0}getStageDamage(stage){const stageData=Object.values(this.system.stages).at(stage-1),base=[];for(const data of Object.values(stageData?.damage??{})){const{formula,type:damageType,category}=data,terms=parseTermsFromSimpleFormula(formula);base.push({terms,damageType,category:category??null})}if(!base.length)return null;try{const{formula,breakdown}=createDamageFormula({base,modifiers:[],dice:[],ignoredResistances:[]}),roll=new DamageRoll(formula),stageLabel=game.i18n.format("PF2E.Item.Affliction.Stage",{stage:this.stage}),template={name:`${this.name} - ${stageLabel}`,damage:{roll,breakdown},materials:[],modifiers:[]},context={type:"damage-roll",sourceType:"save",outcome:"failure",domains:[],options:new Set,self:null,traits:this.system.traits.value};return{template,context}}catch(err){console.error(err)}return null}async handleStageChange(){const actor=this.actor;if(!actor)return;const itemsToDelete=this.getLinkedItems().map(i=>i.id);await actor.deleteEmbeddedDocuments("Item",itemsToDelete);const currentStage=this.stageData;if(!currentStage)return;const conditionsToAdd=[],conditionsToUpdate={};for(const data of Object.values(currentStage.conditions??{})){const value=data.value??1,existing=(()=>{const allExisting=actor.conditions.bySlug(data.slug,{temporary:!1}),byAffliction=allExisting.find(i=>i.appliedBy===this);return byAffliction||(data.linked?null:maxBy(allExisting.filter(i=>!i.appliedBy&&!i.isLocked),c=>c.active?1/0:c.value??0))})();if(existing){existing.system.value.isValued&&(conditionsToUpdate[existing.id]={value,linked:!!data.linked});continue}const condition=ConditionManager.getCondition(data.slug);condition.updateSource({"flags.pf2e.grantedBy.id":this.id}),data.linked&&condition.updateSource({"system.references.parent.id":this.id}),condition.system.value.isValued&&value>1&&condition.updateSource({"system.value.value":data.value}),conditionsToAdd.push(condition)}const additions=conditionsToAdd.map(c=>c.toObject());await actor.createEmbeddedDocuments("Item",additions),await actor.updateEmbeddedDocuments("Item",Object.entries(conditionsToUpdate).map(([_id,data])=>({_id,"system.value.value":data.value,"flags.pf2e.grantedBy.id":this.id,...data.linked?{"system.references.parent.id":this.id}:{}}))),this.system.onset||await this.createStageMessage()}getLinkedItems(){return this.actor?this.actor.items.filter(i=>i.isOfType("condition")&&!EXPIRING_CONDITIONS.has(i.slug)&&i.flags.pf2e.grantedBy?.id===this.id&&i.system.references.parent?.id===this.id):[]}async createStageMessage(){if(!this.actor)return;const damage=this.getStageDamage(this.stage);if(damage){const{template,context}=damage;await DamagePF2e.roll(template,context)}}async _preCreate(data,options,user){if(this.isOwned){const initiative=this.origin?.combatant?.initiative??game.combat?.combatant?.initiative??null;this._source.system.start={value:game.time.worldTime+this.onsetDuration,initiative}}else data.system.stage=1,data.system.onset&&(data.system.onset.active=!0);return super._preCreate(data,options,user)}async _preUpdate(changed,options,user){const duration=changed.system?.duration;return typeof duration?.unit=="string"&&!["unlimited","encounter"].includes(duration.unit)&&duration.value===-1&&(duration.value=1),super._preUpdate(changed,options,user)}_onCreate(data,options,userId){super._onCreate(data,options,userId),game.user===this.actor?.primaryUpdater&&this.handleStageChange()}_onUpdate(changed,options,userId){super._onUpdate(changed,options,userId),changed.system?.stage&&game.user===this.actor?.primaryUpdater&&this.handleStageChange()}async rollRecovery(){if(!this.actor)return;const save=this.actor.saves?.[this.system.save.type];save&&(((await save.roll({dc:{value:this.system.save.value},extraRollOptions:this.getRollOptions("item")}))?.degreeOfSuccess??0)>=DegreeOfSuccess.SUCCESS?this.decrease():this.increase())}prepareActorData(){super.prepareActorData();const actor=this.actor;if(!actor)throw ErrorPF2e("prepareActorData called from unembedded item");this.onset&&(actor.rollOptions.all[`self:${this.type}:${this.rollOptionSlug}:onset`]=!0)}}class ConditionPF2e extends AbstractEffectPF2e{static{__name(this,"ConditionPF2e")}static{__name2(this,"ConditionPF2e")}get badge(){return this.system.persistent?{type:"formula",value:this.system.persistent.formula,label:null}:typeof this.system.value.value=="number"?{type:"counter",min:0,max:1/0,label:null,value:this.system.value.value}:null}get origin(){const grantingItem=this.actor?.items.get(this.flags.pf2e.grantedBy?.id??"");return grantingItem?.isOfType("affliction","effect")?grantingItem.origin:null}get key(){return this.system.persistent?`persistent-damage-${this.system.persistent.damageType}`:this.slug}get appliedBy(){const appliedById=this.system.references.parent?.id??this.flags.pf2e.grantedBy?.id??"";return this.actor?.items.get(appliedById)??this.actor?.conditions.get(appliedById)??null}get value(){return this.system.value.value}get isLocked(){const parentId=this.system.references.parent?.id??"";if(this.actor?.items.has(parentId)||this.actor?.conditions.has(parentId)||super.isLocked)return!0;const granterId=this.flags.pf2e.grantedBy?.id??"",granter=this.actor?.items.get(granterId)??this.actor?.conditions.get(granterId);return Object.values(granter?.flags.pf2e.itemGrants??{}).find(g=>g.id===this.id)?.onDelete==="restrict"}get isInHUD(){return this.slug in CONFIG.PF2E.statusEffects.conditions}get breakdown(){if(!this.active)return null;const list=uniq(compact(this.actor?.conditions.bySlug(this.slug).map(condition=>{const{appliedBy}=condition;return!appliedBy?.isOfType("condition")||appliedBy?.active?appliedBy:null})??[])).map(p=>reduceItemName(p.name)).sort((a,b)=>a.localeCompare(b,game.i18n.lang)).join(", ");return list?game.i18n.format("PF2E.EffectPanel.AppliedBy",{"condition-list":list}):null}get readonly(){return this.actor&&this.id?!this.actor.items.has(this.id):!1}getRollOptions(prefix=this.type){const options=super.getRollOptions(prefix);if(this.system.persistent){const{damageType}=this.system.persistent;options.push(`damage:type:${damageType}`,`${prefix}:damage:type:${damageType}`);const category=DamageCategorization.fromDamageType(damageType);category&&options.push(`damage:category:${category}`,`${prefix}:damage:category:${category}`)}return options}async increase(){await this.actor?.increaseCondition(this)}async decrease(){await this.actor?.decreaseCondition(this)}async onEndTurn(options={}){const{actor}=this,token=options?.token??actor?.token;!this.active||!actor||this.system.persistent&&await this.system.persistent.damage.clone().toMessage({speaker:ChatMessagePF2e.getSpeaker({actor,token}),flavor:`${this.name}`},{rollMode:"roll"})}async rollRecovery(){if(this.actor&&this.system.persistent){const{dc,damageType}=this.system.persistent;((await new Statistic(this.actor,{slug:"pd-recovery",label:game.i18n.format("PF2E.Item.Condition.PersistentDamage.Chat.RecoverLabel",{name:this.name}),check:{type:"flat-check"},domains:[]}).roll({dc:{value:dc},extraRollOptions:this.getRollOptions("item"),skipDialog:!0}))?.degreeOfSuccess??0)>=DegreeOfSuccess.SUCCESS&&this.actor.decreaseCondition(`persistent-damage-${damageType}`)}}prepareBaseData(){super.prepareBaseData(),this.active=!0;const systemData=this.system;systemData.value.value=systemData.value.isValued?Number(systemData.value.value)||1:null,systemData.duration=foundry.utils.mergeObject(systemData.duration,{value:-1,unit:"unlimited",expiry:null}),typeof this.badge?.value=="number"&&(this.name=`${this.name} ${this.badge.value}`);const folder=CONFIG.PF2E.statusEffects.iconDir;if(this.img=`${folder}${this.slug}.webp`,systemData.persistent){const{formula,damageType}=systemData.persistent,fullFormula=`(${formula})[persistent,${damageType}]`,critRule=game.settings.get("pf2e","critRule")==="doubledamage"?"double-damage":"double-dice",roll=new DamageRoll(fullFormula,{},{evaluatePersistent:!0,critRule}),dc=game.user.isGM&&systemData.persistent.dc!==15?systemData.persistent.dc:null,localizationKey=`PF2E.Item.Condition.PersistentDamage.${dc!==null?"NameWithDC":"Name"}`;this.name=game.i18n.format(localizationKey,{formula,damageType:game.i18n.localize(CONFIG.PF2E.damageRollFlavors[damageType]??damageType),dc}),systemData.persistent.damage=roll,systemData.persistent.expectedValue=roll.expectedValue,this.img=PERSISTENT_DAMAGE_IMAGES[damageType]??this.img}}prepareSiblingData(){if(!this.actor)throw ErrorPF2e("prepareSiblingData may only be called from an embedded item");if(!this.active)return;const deactivate=__name2(condition=>{condition.active=!1,condition.system.references.overriddenBy.push({id:this.id,type:"condition"})},"deactivate"),conditions=this.actor.conditions.active;if(this.system.overrides.length>0){const overridden=conditions.filter(c=>this.system.overrides.includes(c.key));for(const condition of overridden)deactivate(condition)}const ofSameType=conditions.filter(c=>c!==this&&c.key===this.key);for(const condition of ofSameType)if(condition.slug==="persistent-damage"){const thisValue=this.system.persistent?.expectedValue??0,otherValue=condition.system.persistent?.expectedValue??0;thisValue>=otherValue&&deactivate(condition)}else(this.value===condition.value&&(!this.isLocked||condition.isLocked)||this.value&&condition.value&&this.value>condition.value)&&deactivate(condition)}prepareActorData(){if(super.prepareActorData(),this.active&&this.system.persistent){const{damageType}=this.system.persistent;this.actor.rollOptions.all[`self:condition:persistent-damage:${damageType}`]=!0}}prepareRuleElements(options){return this.active?super.prepareRuleElements(options):[]}async _preUpdate(changed,options,user){return options.conditionValue=this.value,super._preUpdate(changed,options,user)}_onUpdate(changed,options,userId){if(super._onUpdate(changed,options,userId),!game.user.isGM&&!this.actor?.hasPlayerOwner&&game.settings.get("pf2e","metagame_secretCondition"))return;const[priorValue,newValue]=[options.conditionValue,this.value];if(!!priorValue&&!!newValue&&priorValue!==newValue&&!this.system.references.parent?.id){const change=newValue>priorValue?{create:this}:{delete:this};this.actor?.getActiveTokens().shift()?.showFloatyText(change)}game.pf2e.StatusEffects.refresh()}}class EffectPF2e extends AbstractEffectPF2e{static{__name(this,"EffectPF2e")}static{__name2(this,"EffectPF2e")}get badge(){return this.system.badge}get level(){return this.system.level.value}get traits(){return new Set(this.system.traits.value)}get isExpired(){return this.system.expired}get isAura(){return this.rules.some(r=>r.key==="Aura"&&!r.ignored)}get isIdentified(){return!this.system.unidentified}get fromAura(){return!!this.flags.pf2e.aura}prepareBaseData(){super.prepareBaseData();const{system}=this;["unlimited","encounter"].includes(system.duration.unit)?system.duration.expiry=null:system.duration.expiry||="turn-start",system.expired=this.remainingDuration.expired;const{badge}=this.system;badge&&(badge.type==="formula"?badge.label=null:(badge.min=badge.labels?1:badge.min??1,badge.max=badge.labels?.length??badge.max??1/0,badge.value=Math.clamped(badge.value,badge.min,badge.max),badge.label=badge.labels?.at(badge.value-1)?.trim()||null))}prepareRuleElements(options){if(game.settings.get("pf2e","automation.effectExpiration")&&this.isExpired&&this.actor?.items.has(this.id))for(const rule of this.system.rules)rule.ignored=!0;return super.prepareRuleElements(options)}async increase(){const badge=this.system.badge;if(badge?.type==="counter"&&!this.isExpired){const value=badge.value+1;await this.update({system:{badge:{value}}})}}async decrease(){if(this.system.badge?.type!=="counter"||this.isExpired){await this.delete();return}const value=this.system.badge.value-1;await this.update({system:{badge:{value}}})}getRollOptions(prefix=this.type){const slug=this.slug??sluggify(this.name),trimmedSlug=slug.replace(/^(?:spell-)?(?:effect|stance)-/,""),options=super.getRollOptions(prefix);return options.findSplice(o=>o===`${prefix}:${slug}`,`${prefix}:${trimmedSlug}`),options}async evaluateFormulaBadge(badge){const{actor}=this;if(!actor)throw ErrorPF2e("A formula badge can only be evaluated if part of an embedded effect");const roll=await new Roll(badge.value,this.getRollData()).evaluate({async:!0}),reevaluate=badge.reevaluate?{formula:badge.value,event:badge.reevaluate}:null,token=actor.getActiveTokens(!1,!0).shift(),speaker=ChatMessagePF2e.getSpeaker({actor,token});return roll.toMessage({flavor:reduceItemName(this.name),speaker}),{type:"value",value:roll.total,labels:badge.labels,reevaluate}}async _preCreate(data,options,user){if(this.isOwned){const initiative=this.origin?.combatant?.initiative??game.combat?.combatant?.initiative??null;this._source.system.start={value:game.time.worldTime,initiative}}const badge=data.system.badge;return this.actor&&badge?.type==="formula"&&badge.evaluate&&(this._source.system.badge=await this.evaluateFormulaBadge(badge)),super._preCreate(data,options,user)}async _preUpdate(changed,options,user){const duration=changed.system?.duration;duration?.unit==="unlimited"?duration.expiry=null:typeof duration?.unit=="string"&&!["unlimited","encounter"].includes(duration.unit)&&(duration.expiry||="turn-start",duration.value===-1&&(duration.value=1));const currentBadge=this.system.badge,badgeChange=changed.system?.badge??null;if(badgeChange){const badgeTypeChanged=badgeChange?.type&&badgeChange.type!==currentBadge?.type,labels="labels"in badgeChange&&Array.isArray(badgeChange.labels)?badgeChange.labels:currentBadge?.labels;if(badgeTypeChanged)badgeChange.value=1;else if(currentBadge?.type==="counter"){const[minValue,maxValue]=(()=>{const configuredMin=Number(badgeChange.min??currentBadge.min),configuredMax=Number(badgeChange.max??currentBadge.max);return labels?[1,Math.min(labels.length,configuredMax)]:[configuredMin,configuredMax]})();if(typeof badgeChange.value=="number"&&badgeChange.value0}get handsHeld(){return this.system.equipped.carryType==="held"?this.system.equipped.handsHeld??1:0}get isWorn(){return this.system.equipped.carryType==="worn"}get price(){return this.system.price}get assetValue(){return CoinsPF2e.fromPrice(this.price,this.quantity)}get identificationStatus(){return this.system.identification.status}get isIdentified(){return this.system.identification.status==="identified"}get isAlchemical(){return this.traits.has("alchemical")}get isMagical(){const traits=this.traits;return["magical","arcane","primal","divine","occult"].some(t=>traits.has(t))}get isInvested(){return this.traits.has("invested")?this.isEquipped&&this.isIdentified&&this.system.equipped.invested===!0:null}get isCursed(){return this.traits.has("cursed")}get isTemporary(){return this.system.temporary}get isShoddy(){return this.system.traits.otherTags.includes("shoddy")}get isDamaged(){return this.system.hp.value>0&&this.system.hp.value0&&!this.isDestroyed&&hitPoints.value<=hitPoints.brokenThreshold}get isDestroyed(){const{hitPoints}=this;return hitPoints.max>0&&hitPoints.value===0}get material(){return foundry.utils.deepClone(this.system.material)}get isSpecific(){return!1}get isInContainer(){return!!this.container}get isStowed(){return!!this.container?.system.stowing}get container(){return this.system.containerId===null?this._container=null:this._container??=this.actor?.itemTypes.backpack.find(c=>c.id===this.system.containerId)??null}get bulk(){const{per}=this.system.bulk,bulkRelevantQuantity=Math.floor(this.quantity/per),actorSize=this.actor?.isOfType("creature")?this.actor.size:null;return new Bulk(this.system.bulk.value).convertToSize(this.size,actorSize??this.size).times(bulkRelevantQuantity)}get activations(){return Object.values(this.system.activations??{}).map(action2=>{const components=[];return action2.components.cast&&components.push(game.i18n.localize("PF2E.Item.Activation.Cast")),action2.components.command&&components.push(game.i18n.localize("PF2E.Item.Activation.Command")),action2.components.envision&&components.push(game.i18n.localize("PF2E.Item.Activation.Envision")),action2.components.interact&&components.push(game.i18n.localize("PF2E.Item.Activation.Interact")),{componentsLabel:components.join(", "),...action2}})}getRollOptions(prefix=this.type){const rollOptions=super.getRollOptions(prefix),{material}=this.system;return rollOptions.push(...Object.entries({equipped:this.isEquipped,[`hands-held:${this.handsHeld}`]:this.handsHeld>0,[`rarity:${this.rarity}`]:!0,uninvested:this.isInvested===!1,[`material:${material.type}`]:!!material.type}).filter(e=>!!e[1]).map(e=>`${prefix}:${e[0]}`)),rollOptions}_initialize(options){this._container=null,super._initialize(options)}prepareBaseData(){super.prepareBaseData(),this.system.containerId||=null,this.system.material.type||=null,this.system.material.grade||=null,this.system.material.effects??=[],this.system.stackGroup??=null,this.system.hp.brokenThreshold=Math.floor(this.system.hp.max/2),typeof this.system.price.value=="string"&&(this.system.price.value=CoinsPF2e.fromString(this.system.price.value)),this.system.traits.value.includes("infused")&&(this.system.temporary=!0),this.system.price.value=new CoinsPF2e(this.system.temporary?{}:this.system.price.value),this.system.price.per=Math.max(1,this.system.price.per??1),this.system.usage=getUsageDetails(this.system.usage?.value??"carried");const{equipped,usage}=this.system;equipped.handsHeld??=0,equipped.carryType??="worn",usage.type==="worn"&&usage.where&&(equipped.inSlot??=!1),this.actor?.isOfType("loot")&&(equipped.carryType="worn",equipped.inSlot=!1),this.system.bulk=prepareBulkData(this),this._container?.id!==this.system.containerId&&(this._container=null)}prepareDerivedData(){super.prepareDerivedData(),this.name=game.pf2e.system.generateItemName(this),this.system.identification.identified??={name:this.name,img:this.img,data:{description:{value:this.description}}};const{level,rarity,price}=computeLevelRarityPrice(this);this.system.level.value=level,this.system.traits.rarity=rarity,this.system.price.value=price;const mystifiedData=this.getMystifiedData(this.identificationStatus);this.name=mystifiedData.name,this.img=mystifiedData.img,this.system.description.value=mystifiedData.data.description.value,this.system.identification.unidentified=this.getMystifiedData("unidentified"),this.isEmbedded||(this.system.hp.value=Math.clamped(this.system.hp.value,0,this.system.hp.max))}prepareSiblingData(){this.actor&&(this.isStowed&&(this.system.equipped.carryType="stowed",delete this.system.equipped.inSlot),this._container&&!this.actor.items.has(this._container.id)&&(this._container=this.system.containerId=null))}onPrepareSynthetics(){this.system.hp.value=Math.clamped(this.system.hp.value,0,this.system.hp.max)}isStackableWith(item){if(!(this!==item&&this.type===item.type&&this.name===item.name&&this.isIdentified===item.isIdentified&&![this,item].some(i=>i.isHeld||i.isOfType("backpack"))))return!1;const thisData=this.toObject().system,otherData=item.toObject().system;return thisData.quantity=otherData.quantity,thisData.equipped=otherData.equipped,thisData.containerId=otherData.containerId,thisData._migration=otherData._migration,thisData.identification=otherData.identification,equals(thisData,otherData)}async stackWith(targetItem){if(this.isStackableWith(targetItem)){const stackQuantity=this.quantity+targetItem.quantity;await this.delete({render:!1})&&await targetItem.update({"system.quantity":stackQuantity})}}async move({relativeTo,sortBefore,toContainer,toStack,render=!0}){if(!this.actor)throw ErrorPF2e("Tried to move an unonwned item!");if(toStack)return this.stackWith(toStack);const containerResolved=toContainer??relativeTo?.container,mainContainerUpdate=(()=>{if(containerResolved&&!isCycle(this,containerResolved)){const equipped={carryType:containerResolved.stowsItems?"stowed":"worn",handsHeld:0,inSlot:!1};return{system:{containerId:containerResolved?.id,equipped}}}return!containerResolved&&this.isInContainer?{system:{containerId:null,equipped:{carryType:"worn",handsHeld:0,inSlot:!1}}}:null})(),inventory=this.actor.inventory,siblings=(containerResolved?.contents.contents??inventory.contents).sort((a,b)=>a.sort-b.sort);if(!sortBefore&&!siblings.length&&mainContainerUpdate){await this.update(mainContainerUpdate);return}const updates=SortingHelpers.performIntegerSort(this,{target:relativeTo,siblings,sortBefore}).map(s=>{const baseUpdate={_id:s.target.id,...s.update};return mainContainerUpdate&&s.target.id===this.id?foundry.utils.mergeObject(baseUpdate,mainContainerUpdate):baseUpdate}),stowedOrUnstowed=!this.container&&!!containerResolved||this.container&&!containerResolved;await this.actor.updateEmbeddedDocuments("Item",updates,{render:stowedOrUnstowed||render})}getMystifiedData(status,_options){const mystifiedData=this.system.identification[status],name2=mystifiedData.name||this.generateUnidentifiedName(),img=mystifiedData.img||getUnidentifiedPlaceholderImage(this),description=mystifiedData.data.description.value||(()=>{if(status==="identified")return this.description;const itemType=this.generateUnidentifiedName({typeOnly:!0}),caseCorrect=__name2(noun=>game.i18n.lang.toLowerCase()==="de"?noun:noun.toLowerCase(),"caseCorrect");return game.i18n.format("PF2E.identification.UnidentifiedDescription",{item:caseCorrect(itemType)})})();return{name:name2,img,data:{description:{value:description}}}}async getChatData(){const{type,grade}=this.system.material,material=type&&grade?game.i18n.format("PF2E.Item.Weapon.MaterialAndRunes.MaterialOption",{type:game.i18n.localize(CONFIG.PF2E.preciousMaterials[type]),grade:game.i18n.localize(CONFIG.PF2E.preciousMaterialGrades[grade])}):null;return{rarity:{name:this.rarity,label:CONFIG.PF2E.rarityTraits[this.rarity],description:CONFIG.PF2E.traitsDescriptions[this.rarity]},description:{value:this.description},material}}async setIdentificationStatus(status){this.identificationStatus!==status&&await this.update({"system.identification.status":status,"system.identification.unidentified":this.getMystifiedData("unidentified")})}generateUnidentifiedName({typeOnly=!1}={}){const itemType=game.i18n.localize(`TYPES.Item.${this.type}`);return typeOnly?itemType:game.i18n.format("PF2E.identification.UnidentifiedItem",{item:itemType})}traitChatData(dictionary){const traitData=super.traitChatData(dictionary);for(const trait of traitData)if(trait.mystified=!this.isIdentified&&MystifiedTraits.has(trait.value),trait.excluded=trait.mystified&&!game.user.isGM,trait.excluded)delete trait.description;else if(trait.mystified){const gmNote=game.i18n.localize("PF2E.identification.TraitGMNote");trait.description=trait.description?`${gmNote}
${game.i18n.localize(trait.description)}`:gmNote}return traitData}async _preCreate(data,options,user){return this._source.system.equipped={carryType:"worn"},this.system.usage.type==="worn"&&!!this.system.usage.where&&this.actor?.isOfType("character")&&(this._source.system.equipped.inSlot=!1),super._preCreate(data,options,user)}async _preUpdate(changed,options,user){if(!changed.system)return super._preUpdate(changed,options,user);for(const property of["quantity","hardness"])if(changed.system[property]!==void 0){const max=property==="quantity"?999999:999;changed.system[property]=Math.clamped(Math.trunc(Number(changed.system[property])),0,max)||0}if(handleHPChange(this,changed),isObject(changed.system.price)){const price=changed.system.price;if(isObject(price.value)){const coins=price.value;for(const denomination of DENOMINATIONS)coins[denomination]===0&&(coins[`-=${denomination}`]=null)}"per"in price&&(!price.per||Number(price.per)<=1)&&(price["-=per"]=null)}const equipped=changed.system.equipped??{};equipped.carryType==="dropped"&&this.system.equipped.invested&&(equipped.invested=!1),String(equipped.carryType??this.system.equipped.carryType).startsWith("held")||(equipped.handsHeld=0);const newUsage=getUsageDetails(String(changed.system.usage?.value??this.system.usage.value)),hasSlot=newUsage.type==="worn"&&newUsage.where,isSlotted=!!(equipped.inSlot??this.system.equipped.inSlot);return hasSlot?equipped.inSlot=isSlotted:"inSlot"in this._source.system.equipped&&(equipped["-=inSlot"]=null),super._preUpdate(changed,options,user)}}class PhysicalItemSheetPF2e extends ItemSheetPF2e{static{__name(this,"PhysicalItemSheetPF2e")}static{__name2(this,"PhysicalItemSheetPF2e")}static get defaultOptions(){const options=super.defaultOptions;return options.classes.push("physical"),{...options,hasSidebar:!0}}async getData(options){const sheetData=await super.getData(options),{item}=this,bulkAdjustment=getAdjustment(item.system.bulk.value,item._source.system.bulk.value,{better:"lower"}),basePrice=new CoinsPF2e(item._source.system.price.value),priceAdjustment=getAdjustment(item.system.price.value.copperValue,basePrice.copperValue),{actionTraits:actionTraits2}=CONFIG.PF2E,rollData={...item.getRollData(),...this.actor?.getRollData()};sheetData.enrichedContent.unidentifiedDescription=await TextEditor.enrichHTML(sheetData.item.system.identification.unidentified.data.description.value,{rollData,async:!0});const activations=[];for(const action2 of item.activations){const description=await TextEditor.enrichHTML(action2.description.value,{rollData,async:!0});activations.push({action:action2,id:action2.id,base:`system.activations.${action2.id}`,description,traits:createSheetTags(actionTraits2,action2.traits??{value:[]})})}const adjustedLevelHint=(()=>{const hintText=AutomaticBonusProgression.isEnabled(this.actor)?"PF2E.Item.Weapon.FromABP":"PF2E.Item.Weapon.FromMaterialAndRunes",levelLabel=game.i18n.lang==="de"?game.i18n.localize("PF2E.LevelLabel"):game.i18n.localize("PF2E.LevelLabel").toLocaleLowerCase(game.i18n.lang);return item.level!==item._source.system.level.value?game.i18n.format(hintText,{property:levelLabel,value:item.level}):null})(),adjustedPriceHint=(()=>{if(!priceAdjustment)return null;const baseData=item._source,basePrice2=new CoinsPF2e(baseData.system.price.value).scale(baseData.system.quantity).copperValue,derivedPrice=item.assetValue.copperValue,priceLabel=game.i18n.lang==="de"?game.i18n.localize("PF2E.PriceLabel"):game.i18n.localize("PF2E.PriceLabel").toLocaleLowerCase(game.i18n.lang);return basePrice2!==derivedPrice?game.i18n.format(game.i18n.localize("PF2E.Item.Weapon.FromMaterialAndRunes"),{property:priceLabel,value:item.price.value.toString()}):null})(),localizeBulk=localizer("PF2E.Item.Physical.Bulk"),bulks=[0,.1,...Array.fromRange(50,1)].map(value=>value===0?{value,label:localizeBulk("Negligible.Label")}:value===.1?{value,label:localizeBulk("Light.Label")}:{value,label:value.toString()});return{...sheetData,itemType:game.i18n.localize("PF2E.ItemTitle"),sidebarTemplate:"systems/pf2e/templates/items/physical-sidebar.hbs",bulkAdjustment,adjustedLevelHint,basePrice,priceAdjustment,adjustedPriceHint,actionTypes:CONFIG.PF2E.actionTypes,bulks,actionsNumber:CONFIG.PF2E.actionsNumber,frequencies:CONFIG.PF2E.frequencies,sizes:omit(CONFIG.PF2E.actorSizes,["sm"]),usages:CONFIG.PF2E.usages,isPhysical:!0,activations,bulkDisabled:!!sheetData.data?.stackGroup?.trim()}}render(force,options){return!this.item.isIdentified&&!game.user.isGM?(ui.notifications.warn(this.item.description),this):super.render(force,options)}getMaterialSheetData(item,valuationData){const preciousMaterials2=CONFIG.PF2E.preciousMaterials,isSpecificMagicItem=item.isSpecific,materials=Object.entries(valuationData).reduce((result,[materialKey,materialData])=>{const validGrades=[...PRECIOUS_MATERIAL_GRADES].filter(grade=>!!materialData[grade]&&(!isSpecificMagicItem||item.system.material.type===materialKey));return validGrades.length&&(result[materialKey]={label:game.i18n.localize(preciousMaterials2[materialKey]),grades:Object.fromEntries(validGrades.map(grade=>[grade,{value:JSON.stringify({type:materialKey,grade}),label:game.i18n.localize(CONFIG.PF2E.preciousMaterialGrades[grade])}]))}),result},{});return{value:JSON.stringify(pick(this.item.material,["type","grade"])),materials}}activateListeners($html){super.activateListeners($html),$html.find("[data-action=activation-add]").on("click",event2=>{event2.preventDefault();const id=foundry.utils.randomID(16),action2={id,actionCost:{value:1,type:"action"},components:{command:!1,envision:!1,interact:!1,cast:!1},description:{value:""},traits:{value:[],custom:""}};this.item.update({[`system.activations.${id}`]:action2})}),$html.find("[data-action=activation-delete]").on("click",event2=>{event2.preventDefault();const id=$(event2.target).closest("[data-activation-id]").attr("data-activation-id");Object.values(this.item.system.activations??[]).length===1&&id&&id in(this.item.system.activations??{})?this.item.update({"system.-=activations":null}):this.item.update({[`system.activations.-=${id}`]:null})}),$html.find("[data-action=activation-frequency-add]").on("click",event2=>{const id=$(event2.target).closest("[data-activation-id]").attr("data-activation-id");if(id&&id in(this.item.system.activations??{})){const per=CONFIG.PF2E.frequencies.day;this.item.update({[`system.activations.${id}.frequency`]:{value:1,max:1,per}})}}),$html.find("[data-action=activation-frequency-delete]").on("click",event2=>{const id=$(event2.target).closest("[data-activation-id]").attr("data-activation-id");id&&id in(this.item.system.activations??{})&&this.item.update({[`system.activations.${id}.-=frequency`]:null})})}async _updateObject(event2,formData){formData["system.quantity"]===null&&(formData["system.quantity"]=0);const[materialType,materialGrade]=[formData["system.material.type"],formData["system.material.grade"]],typeIsValid=materialType===void 0||typeof materialType=="string"&&materialType in CONFIG.PF2E.preciousMaterials,gradeIsValid=materialGrade===void 0||typeof materialGrade=="string"&&materialGrade in CONFIG.PF2E.preciousMaterialGrades;(!typeIsValid||!gradeIsValid)&&(formData["system.material.type"]=null,formData["system.material.grade"]=null),formData["system.baseItem"]===""&&(formData["system.baseItem"]=null),"system.price.value"in formData&&(formData["system.price.value"]=CoinsPF2e.fromString(String(formData["system.price.value"])));const expanded=foundry.utils.expandObject(formData);for(const action2 of Object.values(expanded.system?.activations??[])){const actionCost=action2.actionCost;if(actionCost){const isAction=actionCost.type==="action";actionCost.value||(actionCost.value=isAction?actionCost.value||1:null)}}return super._updateObject(event2,foundry.utils.flattenObject(expanded))}}class ArmorPF2e extends PhysicalItemPF2e{static{__name(this,"ArmorPF2e")}static{__name2(this,"ArmorPF2e")}isStackableWith(item){return this.isEquipped||item.isEquipped?!1:super.isStackableWith(item)}get isBarding(){return["light-barding","heavy-barding"].includes(this.category)}get baseType(){return this.system.baseItem??null}get group(){return this.system.group||null}get category(){return this.system.category}get dexCap(){return this.system.dexCap}get strength(){return this.system.strength}get checkPenalty(){return this.system.checkPenalty||0}get speedPenalty(){return this.system.speedPenalty||0}get acBonus(){return this.system.acBonus}get isSpecific(){return!!this.system.specific}getRollOptions(prefix="armor"){const rollOptions=super.getRollOptions(prefix);return rollOptions.push(...Object.entries({[`category:${this.category}`]:!0,[`group:${this.group??"none"}`]:!0,[`base:${this.baseType}`]:!!this.baseType,"rune:potency":this.system.runes.potency>0,"rune:resilient":this.system.runes.resilient>0}).filter(e=>!!e[1]).map(e=>`${prefix}:${e[0]}`),...this.system.runes.property.map(r=>`${prefix}:rune:property:${sluggify(r)}`)),rollOptions}prepareBaseData(){const systemUsage=this.system;systemUsage.usage={value:"wornarmor"},super.prepareBaseData(),AutomaticBonusProgression.cleanupRunes(this);const maxPropertySlots=getPropertyRuneSlots(this);this.system.runes.property.length=Math.min(this.system.runes.property.length,maxPropertySlots);const abpEnabled=AutomaticBonusProgression.isEnabled(this.actor),baseTraits=this.system.traits.value,investedTrait=this.system.runes.potency||this.system.runes.resilient||abpEnabled&&this.system.runes.property.length>0?"invested":null,hasTraditionTraits=baseTraits.some(t=>setHasElement(MAGIC_TRADITIONS,t)),magicTrait=investedTrait&&!hasTraditionTraits?"magical":null;this.system.traits.value=uniq(compact([...baseTraits,investedTrait,magicTrait]).sort())}prepareDerivedData(){super.prepareDerivedData();const potencyRune=this.isInvested&&!AutomaticBonusProgression.isEnabled(this.actor)?this.system.runes.potency:0,baseArmor=Number(this.system.acBonus)||0;this.system.acBonus=baseArmor+potencyRune}prepareActorData(){const{actor}=this;if(!actor)throw ErrorPF2e("This method may only be called from embedded items");if(this.isEquipped)for(const rollOption of this.getRollOptions("armor"))actor.rollOptions.all[rollOption]=!0}async getChatData(htmlOptions={}){const properties=[CONFIG.PF2E.armorCategories[this.category],`${signedInteger(this.acBonus)} ${game.i18n.localize("PF2E.ArmorArmorLabel")}`,`${this.system.dexCap||0} ${game.i18n.localize("PF2E.ArmorDexLabel")}`,`${this.system.checkPenalty||0} ${game.i18n.localize("PF2E.ArmorCheckLabel")}`,this.speedPenalty?`${this.system.speedPenalty} ${game.i18n.localize("PF2E.ArmorSpeedLabel")}`:null];return this.processChatData(htmlOptions,{...await super.getChatData(),traits:this.traitChatData(CONFIG.PF2E.armorTraits),properties})}generateUnidentifiedName({typeOnly=!1}={typeOnly:!1}){const base=this.baseType?CONFIG.PF2E.baseArmorTypes[this.baseType]:null,group=this.group?CONFIG.PF2E.armorGroups[this.group]:null,fallback="TYPES.Item.armor",itemType=game.i18n.localize(base??group??fallback);return typeOnly?itemType:game.i18n.format("PF2E.identification.UnidentifiedItem",{item:itemType})}async _preUpdate(changed,options,user){if(!changed.system)return super._preUpdate(changed,options,user);if(changed.system.acBonus!==void 0){const integerValue=Math.floor(Number(changed.system.acBonus))||0;changed.system.acBonus=Math.max(0,integerValue)}if(changed.system.group!==void 0&&(changed.system.group||=null),changed.system.dexCap!==void 0){const integerValue=Math.floor(Number(changed.system.dexCap))||0;changed.system.dexCap=Math.max(0,integerValue)}if(changed.system.checkPenalty!==void 0){const integerValue=Math.floor(Number(changed.system.checkPenalty))||0;changed.system.checkPenalty=Math.min(0,integerValue)}if(changed.system.speedPenalty!==void 0){const integerValue=Math.floor(Number(changed.system.speedPenalty))||0;changed.system.speedPenalty=Math.min(0,integerValue)}return super._preUpdate(changed,options,user)}}class BookPF2e extends PhysicalItemPF2e{static{__name(this,"BookPF2e")}static{__name2(this,"BookPF2e")}}class InventoryBulk{static{__name(this,"InventoryBulk")}static{__name2(this,"InventoryBulk")}actor;#value=null;encumberedAfterAddend=0;maxAddend=0;constructor(actor){this.actor=actor}get#actorStrength(){return this.actor.isOfType("character","npc")?this.actor.abilities.str.mod:1/0}get encumberedAfter(){return Math.floor(this.#actorStrength+5+this.encumberedAfterAddend)}get encumberedAfterBreakdown(){const addend=this.encumberedAfterAddend,stat=game.i18n.localize(CONFIG.PF2E.abilities.str);return`5 + ${this.#actorStrength} (${stat})`+(addend?` + ${addend}`:"")}get max(){return Math.floor(this.#actorStrength+10+this.maxAddend)}get maxBreakdown(){const addend=this.maxAddend,stat=game.i18n.localize(CONFIG.PF2E.abilities.str);return`10 + ${this.#actorStrength} (${stat})`+(addend?` + ${addend}`:"")}get value(){return this.#value?this.#value:(this.#value=InventoryBulk.computeTotalBulk(this.actor.inventory.filter(i=>!i.isInContainer),this.actor.size),this.#value)}get encumberedPercentage(){const totalTimes10=this.value.toLightUnits(),encumberedAtTimes10=this.encumberedAfter*10+10;return Math.floor(totalTimes10/encumberedAtTimes10*100)}get maxPercentage(){const totalTimes10=this.value.toLightUnits(),limitTimes10=this.max*10+10;return Math.floor(totalTimes10/limitTimes10*100)}get maxPercentageInteger(){return this.maxPercentage>100?100:this.maxPercentage}get isEncumbered(){return this.value.normal>this.encumberedAfter}get isOverMax(){return this.value.normal>this.max}get bulk(){return this.value.normal}static computeTotalBulk(items,actorSize){items=this.#flattenNonStowing(items);const nonStackingItems=items.filter(i=>i.isOfType("backpack")||i.system.bulk.per===1&&i.system.baseItem),nonStackingIds=new Set(nonStackingItems.map(i=>i.id)),stackingItems=items.filter(i=>!nonStackingIds.has(i.id)),baseBulk=nonStackingItems.map(i=>i.bulk).reduce((first,second)=>first.plus(second),new Bulk),stackingBehaviors=stackingItems.map(item=>({per:item.system.bulk.per,item,group:item.system.baseItem,bulk:new Bulk(item.system.bulk.value).convertToSize(item.size,actorSize)})),bulks=[...groupBy(stackingBehaviors,d=>`${d.group}-${d.per}-${d.bulk.toLightUnits()}`).values()].map(dataEntries=>{const{bulk,per}=dataEntries[0],quantity=dataEntries.map(entry=>entry.item.quantity).reduce((sum,value)=>sum+value,0),bulkRelevantQuantity=Math.floor(quantity/per);return bulk.times(bulkRelevantQuantity)});return baseBulk.plus(bulks.reduce((first,second)=>first.plus(second),new Bulk))}static#flattenNonStowing(items){return items.map(item=>item.isOfType("backpack")&&!item.stowsItems?this.#flattenNonStowing(item.contents.contents):item).flat()}}class ActorInventory extends DelegatedCollection{static{__name(this,"ActorInventory")}static{__name2(this,"ActorInventory")}actor;bulk;constructor(actor,entries){super(entries?.map(entry=>[entry.id,entry])),this.actor=actor,this.bulk=new InventoryBulk(this.actor)}get coins(){return this.filter(i=>i.isOfType("treasure")&&i.isCoinage).map(item=>item.assetValue).reduce((first,second)=>first.add(second),new CoinsPF2e)}get totalWealth(){return this.filter(item=>game.user.isGM||item.isIdentified).map(item=>item.assetValue).reduce((first,second)=>first.add(second),new CoinsPF2e)}get invested(){return this.actor.isOfType("character")?{value:this.filter(item=>!!item.isInvested).length,max:this.actor.system.resources.investiture.max}:null}findStackableItem(item){const testItem=item instanceof PhysicalItemPF2e?item.clone():new ItemProxyPF2e(foundry.utils.deepClone(item));if(!testItem.isOfType("physical"))return null;const stackCandidates=this.filter(i=>!i.isInContainer&&i.isStackableWith(testItem));if(stackCandidates.length===0)return null;if(stackCandidates.length>1){const notEquipped=stackCandidates.filter(item2=>!item2.isEquipped);return notEquipped.length>0?notEquipped[0]:stackCandidates[0]}else return stackCandidates[0]}async addCoins(coins,{combineStacks=!0}={}){const topLevelCoins=this.actor.itemTypes.treasure.filter(item=>combineStacks&&item.isCoinage),coinsByDenomination=groupBy(topLevelCoins,item=>item.denomination);for(const denomination of DENOMINATIONS){const quantity=coins[denomination]??0;if(quantity>0){const item=coinsByDenomination.get(denomination)?.at(0);if(item)await item.update({"system.quantity":item.quantity+quantity});else{const compendiumId=coinCompendiumIds[denomination],pack=game.packs.find(p=>p.collection==="pf2e.equipment-srd");if(!pack)throw ErrorPF2e("Unexpected error retrieving equipment compendium");const item2=(await pack.getDocument(compendiumId))?.clone();item2?.isOfType("treasure")&&(item2.updateSource({"system.quantity":quantity}),await this.actor.createEmbeddedDocuments("Item",[item2.toObject()]))}}}}async removeCoins(coins,{byValue=!0}={}){const coinsToRemove=new CoinsPF2e(coins),actorCoins=this.coins,coinsToAdd=new CoinsPF2e;if(byValue){let valueToRemoveInCopper=coinsToRemove.copperValue;if(valueToRemoveInCopper>actorCoins.copperValue)return!1;if(valueToRemoveInCopper%10>actorCoins.cp)coinsToAdd.cp=10,coinsToRemove.cp=valueToRemoveInCopper%10,valueToRemoveInCopper+=10-coinsToRemove.cp;else{coinsToRemove.cp=valueToRemoveInCopper%10,valueToRemoveInCopper-=coinsToRemove.cp;const newCopper=actorCoins.cp-coinsToRemove.cp,extraCopper=Math.min(valueToRemoveInCopper/10,Math.trunc(newCopper/10))*10;coinsToRemove.cp+=extraCopper,valueToRemoveInCopper-=extraCopper}if(valueToRemoveInCopper/10%10>actorCoins.sp)coinsToAdd.sp=10,coinsToRemove.sp=valueToRemoveInCopper/10%10,valueToRemoveInCopper+=100-coinsToRemove.sp*10;else{coinsToRemove.sp=valueToRemoveInCopper/10%10,valueToRemoveInCopper-=coinsToRemove.sp*10;const newSilver=actorCoins.sp-coinsToRemove.sp,extraSilver=Math.min(valueToRemoveInCopper/100,Math.trunc(newSilver/10))*10;coinsToRemove.sp+=extraSilver,valueToRemoveInCopper-=extraSilver*10}if(valueToRemoveInCopper/100%10>actorCoins.gp)coinsToAdd.gp=10,coinsToRemove.gp=valueToRemoveInCopper/100%10,valueToRemoveInCopper+=1e3-coinsToRemove.gp*100;else{coinsToRemove.gp=valueToRemoveInCopper/100%10,valueToRemoveInCopper-=coinsToRemove.gp*100;const newGold=actorCoins.gp-coinsToRemove.gp,extraGold=Math.min(valueToRemoveInCopper/1e3,Math.trunc(newGold/10))*10;coinsToRemove.gp+=extraGold,valueToRemoveInCopper-=extraGold*100}coinsToRemove.pp=valueToRemoveInCopper/1e3}const coinsToPull=actorCoins.add(coinsToAdd);if(!(coinsToRemove.pp<=coinsToPull.pp&&coinsToRemove.gp<=coinsToPull.gp&&coinsToRemove.sp<=coinsToPull.sp&&coinsToRemove.cp<=coinsToPull.cp))return!1;Object.values(coinsToAdd).some(value=>value!==0)&&await this.addCoins(coinsToAdd);const topLevelCoins=this.actor.itemTypes.treasure.filter(item=>item.isCoinage),coinsByDenomination=groupBy(topLevelCoins,item=>item.denomination);for(const denomination of DENOMINATIONS){let quantityToRemove=coinsToRemove[denomination];const coinItems=coinsByDenomination.get(denomination);if(quantityToRemove&&coinItems){const itemsToUpdate=[],itemsToDelete=[];for(const item of coinItems){if(quantityToRemove===0)break;if(item.quantity>quantityToRemove){itemsToUpdate.push({_id:item.id,"system.quantity":item.quantity-quantityToRemove}),quantityToRemove=0;break}else quantityToRemove-=item.quantity,itemsToDelete.push(item.id)}itemsToUpdate.length>0&&await this.actor.updateEmbeddedDocuments("Item",itemsToUpdate),itemsToDelete.length>0&&await this.actor.deleteEmbeddedDocuments("Item",itemsToDelete),quantityToRemove>0&&console.warn("Attempted to remove more coinage than exists")}}return!0}async sellAllTreasure(){const treasures=this.actor.itemTypes.treasure.filter(item=>!item.isCoinage),treasureIds=treasures.map(item=>item.id),coins=treasures.map(item=>item.assetValue).reduce((first,second)=>first.add(second),new CoinsPF2e);await this.actor.deleteEmbeddedDocuments("Item",treasureIds),await this.actor.inventory.addCoins(coins)}async add(item,options={}){if(options.stack&&item.isOfType("physical")){const stackableItem=this.findStackableItem(item._source);if(stackableItem){await stackableItem.update({"system.quantity":stackableItem.quantity+item.quantity});return}}await this.actor.createEmbeddedDocuments("Item",[item.toObject()])}}class ContainerPF2e extends PhysicalItemPF2e{static{__name(this,"ContainerPF2e")}static{__name2(this,"ContainerPF2e")}contents=new Collection;get stowsItems(){return this.system.stowing}get isCollapsed(){return this.system.collapsed}get capacity(){return{value:InventoryBulk.computeTotalBulk(this.contents.contents,this.actor?.size??"med"),max:new Bulk(this.system.bulk.capacity)}}get percentFull(){const{value,max}=this.capacity,realPercent=Math.floor(value.toLightUnits()/max.toLightUnits()*100);return realPercent>100?Math.floor(value.normal/max.normal*100):realPercent}get bulkIgnored(){const isOverfilled=this.percentFull>100,extradimensionalParadox=this.traits.has("extradimensional")&&hasExtraDimensionalParent(this);return!isOverfilled&&!extradimensionalParadox?new Bulk(this.system.bulk.ignored):new Bulk}get bulk(){return super.bulk.plus(this.capacity.value.minus(this.bulkIgnored))}prepareSiblingData(){super.prepareSiblingData(),this.contents=new Collection(this.actor.inventory.filter(i=>i.container?.id===this.id).map(item=>[item.id,item]))}async ejectContents(){if(!this.actor)return;const updates=this.contents.map(i=>({_id:i.id,"system.containerId":this.container?.id??null}));await this.actor.updateEmbeddedDocuments("Item",updates,{render:!1})}async getChatData(htmlOptions={}){return this.processChatData(htmlOptions,{...await super.getChatData(),traits:this.traitChatData(CONFIG.PF2E.equipmentTraits)})}_preUpdate(changed,options,user){if(!changed.system?.bulk)return super._preUpdate(changed,options,user);changed.system.bulk.heldOrStowed!==void 0&&(changed.system.bulk.heldOrStowed=Math.clamped(Number(changed.system.bulk.heldOrStowed),0,999)||0,Number.isInteger(changed.system.bulk.heldOrStowed)||(changed.system.bulk.heldOrStowed=.1));for(const property of["capacity","ignored"])changed.system.bulk[property]!==void 0&&(changed.system.bulk[property]=Math.clamped(Math.trunc(Number(changed.system.bulk[property])),0,999)||0);return super._preUpdate(changed,options,user)}}class EquipmentPF2e extends PhysicalItemPF2e{static{__name(this,"EquipmentPF2e")}static{__name2(this,"EquipmentPF2e")}get otherTags(){return new Set(this.system.traits.otherTags)}prepareBaseData(){super.prepareBaseData(),this.system.apex&&(this.traits.has("apex")?this.isInvested||(this.system.apex.selected=!1):delete this.system.apex)}prepareSiblingData(){if(super.prepareSiblingData(),!this.system.apex)return;const otherApexData=this.actor.itemTypes.equipment.flatMap(e=>e===this?[]:e.system.apex??[]);if(this.system.apex.selected||this.isInvested&&otherApexData.every(d=>!d.selected)){this.system.apex.selected=!0;for(const data of otherApexData)data.selected=!1}}prepareActorData(){const{actor}=this;actor?.isOfType("character")&&this.system.apex?.selected&&(actor.system.build.attributes.apex?this.system.apex.selected=!1:actor.system.build.attributes.apex=this.system.apex.attribute)}async getChatData(htmlOptions={}){return this.processChatData(htmlOptions,{...await super.getChatData(),traits:this.traitChatData(CONFIG.PF2E.equipmentTraits)})}generateUnidentifiedName({typeOnly=!1}={typeOnly:!1}){const identificationConfig=CONFIG.PF2E.identification,slotType=/book\b/.test(this.slug??"")?"Book":/\bring\b/.test(this.slug??"")?"Ring":this.system.usage.value?.replace(/^worn/,"").capitalize()??"",itemType=objectHasKey(identificationConfig.UnidentifiedType,slotType)?game.i18n.localize(identificationConfig.UnidentifiedType[slotType]):game.i18n.localize(identificationConfig.UnidentifiedType.Object);return typeOnly?itemType:game.i18n.format(identificationConfig.UnidentifiedItem,{item:itemType})}async _preCreate(data,options,user){return delete this._source.system.apex?.selected,super._preCreate(data,options,user)}async _preUpdate(changed,options,user){const changedTraits=changed.system?.traits?.value;return!(this._source.system.traits.value.includes("apex")&&(!Array.isArray(changedTraits)||changedTraits.includes("apex")))&&this._source.system.apex&&(delete changed.system?.apex,changed.system??={},changed.system=foundry.utils.mergeObject(changed.system,{"-=apex":null})),super._preUpdate(changed,options,user)}}class TreasurePF2e extends PhysicalItemPF2e{static{__name(this,"TreasurePF2e")}static{__name2(this,"TreasurePF2e")}get isCoinage(){return this.system.stackGroup==="coins"}get denomination(){if(!this.isCoinage)return null;const options=DENOMINATIONS.filter(denomination=>!!this.price.value[denomination]);return options.length===1?options[0]:null}prepareBaseData(){super.prepareBaseData(),this.isCoinage&&(this.system.size="med")}async getChatData(htmlOptions={}){const systemData=this.system,traits=this.traitChatData({});return this.processChatData(htmlOptions,{...systemData,traits})}}class WeaponPF2e extends PhysicalItemPF2e{static{__name(this,"WeaponPF2e")}static{__name2(this,"WeaponPF2e")}constructor(data,context={}){super(data,context),context.shield&&(this.shield=context.shield)}altUsageType=null;get isEquipped(){const{category,slug,traits}=this.system;return category==="unarmed"&&slug!=="handwraps-of-mighty-blows"?!0:super.isEquipped||this.handsHeld===1&&traits.value.some(t=>/^jousting-d\d{1,2}$/.test(t))}isStackableWith(item){if(this.category==="unarmed"||!item.isOfType("weapon")||item.category==="unarmed")return!1;const equippedButStackable=["bomb","dart"].includes(this.group??"");return(this.isEquipped||item.isEquipped)&&!equippedButStackable?!1:super.isStackableWith(item)}get baseType(){return this.system.baseItem}get group(){return this.system.group}get category(){return this.system.category}get defaultAttribute(){return this.system.attribute??(this.isRanged?"dex":"str")}get hands(){return{worngloves:"0","held-in-one-hand":"1","held-in-one-plus-hands":"1+","held-in-two-hands":"2"}[this.system.usage.value]??"1"}get maxRange(){return this.system.maxRange??(this.system.range?this.system.range*6:null)}get range(){const rangeIncrement=this.system.range,maxRange=this.system.maxRange;return maxRange?{increment:null,max:maxRange}:rangeIncrement?{increment:rangeIncrement,max:rangeIncrement*6}:null}get reload(){return this.system.reload.value||null}get isSpecific(){return!!this.system.specific}get isMelee(){return!this.isRanged}get isRanged(){return!!this.system.range}get isThrown(){return this.isRanged&&(this.baseType==="alchemical-bomb"||this.system.traits.value.includes("thrown"))}get isThrowable(){return this.isThrown||this.system.traits.value.some(t=>t.startsWith("thrown"))||!!this.system.meleeUsage?.traits.some(t=>t.startsWith("thrown"))}get isOversized(){return this.category!=="unarmed"&&!!this.parent?.system.traits?.size.isSmallerThan(this.size,{smallIsMedium:!0})}get baseDamage(){return{...foundry.utils.deepClone(this.system.damage),damageType:this.system.traits.toggles.versatile.selection??this.system.traits.toggles.modular.selection??this.system.damage.damageType}}get dealsDamage(){const{baseDamage}=this;return baseDamage.dice>0||baseDamage.modifier>0||this.system.splashDamage.value>0||!!baseDamage.persistent?.number}get requiresAmmo(){return this.isRanged&&!this.isThrown&&![null,"-"].includes(this.reload)}get ammo(){const ammo=this.actor?.items.get(this.system.selectedAmmoId??"");return ammo?.isOfType("consumable","weapon")?ammo:null}get otherTags(){return new Set(this.system.traits.otherTags)}isAmmoFor(weapon){return this.system.usage.canBeAmmo&&!weapon.system.traits.value.includes("repeating")}getRollOptions(prefix=this.type){const{baseDamage}=this,damage={category:DamageCategorization.fromDamageType(baseDamage.damageType),type:baseDamage.damageType,dice:{number:baseDamage.die?baseDamage.dice:0,faces:Number(baseDamage.die?.replace(/^d/,""))}},{actor}=this,isDeityFavored=!!(this.baseType&&actor?.isOfType("character")&&actor.deity?.favoredWeapons.includes(this.baseType)),thrownMelee=this.isThrown&&this.altUsageType==="thrown",baseTypeRollOptions=(()=>{const equivalentBases=CONFIG.PF2E.equivalentWeapons;return[this.baseType??[],equivalentBases[this.baseType??""]??[]].flat().reduce((types,t)=>({...types,[`base:${t}`]:!0}),{})})(),{persistent}=this.system.damage,propertyRunes=mapToObj(this.system.runes.property,p=>[`rune:property:${sluggify(p)}`,!0]),ammunitionRollOptions=(ammunition=>{const rollOptions2={};if(ammunition){rollOptions2[`ammo:id:${ammunition.id}`]=!0,rollOptions2[`ammo:slug:${ammunition.slug}`]=!0,rollOptions2[`ammo:level:${ammunition.level}`]=!0,rollOptions2[`ammo:material:type:${ammunition.material.type}`]=!!ammunition.material.type,rollOptions2[`ammo:material:grade:${ammunition.material.grade}`]=!!ammunition.material.grade;for(const trait of ammunition.traits)rollOptions2[`ammo:trait:${trait}`]=!0}return rollOptions2})(this.ammo),bulk=(()=>{const unitBulk=this.bulk.times(1/this.quantity);return unitBulk.isNegligible?"negligible":unitBulk.isLight?"light":unitBulk.toString()})(),rangeIncrement=this.range?.increment,rollOptions=super.getRollOptions(prefix);return rollOptions.push(...Object.entries({[`category:${this.category}`]:!0,[`group:${this.group??"none"}`]:!0,...baseTypeRollOptions,[`base:${this.baseType}`]:!!this.baseType,[`bulk:${bulk}`]:!0,[`usage:hands:${this.hands}`]:this.hands!=="0",[`range-increment:${rangeIncrement}`]:!!rangeIncrement,[`reload:${this.reload}`]:!!this.reload,[`damage:type:${damage.type}`]:!0,[`damage:category:${damage.category}`]:!!damage.category,[`damage:die:number:${damage.dice.number}`]:!!damage.dice.faces,[`damage:die:faces:${damage.dice.faces}`]:!!damage.dice.faces,[`damage-dice:${damage.dice.number}`]:!!damage.dice.faces,[`damage:persistent:${persistent?.type}`]:!!persistent,"deity-favored":isDeityFavored,oversized:this.isOversized,melee:this.isMelee,ranged:this.isRanged,thrown:this.isThrown,"thrown-melee":thrownMelee,...propertyRunes,...ammunitionRollOptions}).filter(e=>!!e[1]).map(e=>`${prefix}:${e[0]}`)),rollOptions}prepareBaseData(){super.prepareBaseData(),this.system.category||="simple",this.system.group||=null,this.system.baseItem||=null,this.system.bonusDamage.value||=0,this.system.splashDamage.value||=0,this.system.graspingAppendage=["fist","claw"].includes(this.baseType??"")?!0:this.category==="unarmed"?!!this.system.graspingAppendage:!1,setHasElement(ATTRIBUTE_ABBREVIATIONS,this.system.attribute)||(this.system.attribute=null);const reloadValue=this.system.reload.value||=null;this.system.reload.label=reloadValue?game.i18n.format("PF2E.Item.Weapon.Reload.LabelN",{value:CONFIG.PF2E.weaponReload[reloadValue]}):null,this.system.selectedAmmoId||=null,this.system.damage.die||=null,this.system.damage.modifier??=0,!this.system.damage.die&&this.system.damage.dice>0&&(this.system.damage.modifier||=this.system.damage.dice),this.isThrown&&!tupleHasValue(["-","0"],this.system.reload.value)&&(this.system.reload.value="-"),this.system.category==="unarmed"&&!this.system.traits.value.includes("unarmed")&&this.system.traits.value.push("unarmed"),this.system.traits.value=this.system.traits.value.filter(t=>t in CONFIG.PF2E.npcAttackTraits);const traitSet=this.traits,mandatoryRanged=setHasElement(MANDATORY_RANGED_GROUPS,this.system.group)||traitSet.has("thrown");mandatoryRanged&&(this.system.range??=10),this.system.meleeUsage&&(this.system.meleeUsage.traits??=[],this.system.meleeUsage.traitToggles??={modular:null,versatile:null}),this.system.traits.toggles=new WeaponTraitToggles(this);const traitsArray=this.system.traits.value;this.system.category==="unarmed"&&!traitsArray.includes("unarmed")&&this.system.traits.value.push("unarmed"),!mandatoryRanged&&traitsArray.some(t=>/^thrown-\d+$/.test(t))&&(this.system.range=null),this.system.reload.consume=this.isMelee?null:this.reload!==null,this.system.usage.canBeAmmo=this._source.system.usage.canBeAmmo??!1,this.flags.pf2e.comboMeleeUsage??=!1,AutomaticBonusProgression.cleanupRunes(this);const{runes}=this.system;runes.effects=[],runes.property.length=Math.min(runes.property.length,getPropertyRuneSlots(this));const{actor}=this,inherentDiceNumber=this.system.damage.die?this._source.system.damage.dice:0,strikingDice=AutomaticBonusProgression.isEnabled(actor)?AutomaticBonusProgression.getStrikingDice(actor?.level??0):this.system.runes.striking;this.system.damage.dice=inherentDiceNumber===1&&!this.flags.pf2e.battleForm?inherentDiceNumber+strikingDice:this.system.damage.dice;const baseTraits=this.system.traits.value,magicTrait=(runes.potency>0||runes.striking>0||runes.property.length>0)&&!baseTraits.some(t=>setHasElement(MAGIC_TRADITIONS,t))?"magical":null;this.system.traits.value=uniq(compact([...baseTraits,magicTrait]).sort()),this.flags.pf2e.attackItemBonus=this.system.runes.potency||this.system.bonus.value||0}prepareDerivedData(){super.prepareDerivedData(),this.system.usage.canBeAmmo&&!this.isThrowable&&(this.system.usage.canBeAmmo=!1)}prepareSiblingData(){super.prepareSiblingData();const ammoRules=this.ammo?.system.rules.map(r=>({label:this.ammo?.name,...foundry.utils.deepClone(r)}))??[];this.system.rules.push(...ammoRules)}async getChatData(htmlOptions={}){const traits=this.traitChatData(CONFIG.PF2E.weaponTraits),chatData=await super.getChatData(),rangeLabel=createActionRangeLabel(this.range),properties=compact([CONFIG.PF2E.weaponCategories[this.category],this.system.reload.label,rangeLabel]);return this.processChatData(htmlOptions,{...chatData,traits,properties})}getMystifiedData(status,{source=!1}={}){const mystifiedData=super.getMystifiedData(status);return source&&(mystifiedData.name=this._source.name),mystifiedData}generateUnidentifiedName({typeOnly=!1}={typeOnly:!1}){const baseWeaponTypes2=CONFIG.PF2E.baseWeaponTypes,baseShieldTypes2=CONFIG.PF2E.baseShieldTypes,base=this.baseType?baseWeaponTypes2[this.baseType]??baseShieldTypes2[this.baseType]??null:null,group=this.group?CONFIG.PF2E.weaponGroups[this.group]:null,itemType=game.i18n.localize(base??group??"TYPES.Item.weapon");return typeOnly?itemType:game.i18n.format("PF2E.identification.UnidentifiedItem",{item:itemType})}getAltUsages({recurse=!0}={}){const meleeUsage=this.toMeleeUsage();return[this.toThrownUsage()??[],meleeUsage??[],recurse?meleeUsage?.toThrownUsage()??[]:[]].flat()}clone(data,context){const clone=super.clone(data,context);return context?.altUsage&&clone instanceof WeaponPF2e&&(clone.altUsageType=context.altUsage),clone}toThrownUsage(){const traits=this._source.system.traits.value,thrownTrait=traits.find(t=>/^thrown-\d{1,3}$/.test(t));if(this.isRanged||!thrownTrait)return null;const range2=Number(/(\d{1,3})$/.exec(thrownTrait)?.at(1)),newTraits=foundry.utils.deepClone(traits);newTraits.splice(newTraits.indexOf(thrownTrait),1,"thrown");const overlay={system:{range:range2,traits:{value:newTraits}}};return this.clone(overlay,{keepId:!0,altUsage:"thrown"})}toMeleeUsage(){const{meleeUsage}=this.system;if(!meleeUsage||this.flags.pf2e.comboMeleeUsage)return null;const traitToggles={module:{selection:meleeUsage.traitToggles.modular},versatile:{selection:meleeUsage.traitToggles.versatile}},overlay={system:{damage:{damageType:meleeUsage.damage.type,dice:1,die:meleeUsage.damage.die},group:meleeUsage.group,range:null,reload:{value:null},traits:{value:meleeUsage.traits.concat("combination"),toggles:traitToggles},selectedAmmoId:null},flags:{pf2e:{comboMeleeUsage:!0}}};return this.clone(overlay,{keepId:!0,altUsage:"melee"})}toNPCAttacks({keepId=!1}={}){const{actor}=this;if(!actor.isOfType("npc"))throw ErrorPF2e("Melee items can only be generated for NPCs");const baseDamage=(()=>{const weaponDamage=this.baseDamage,ability=this.range?.increment&&!this.isThrown?"dex":"str",actorLevel=actor.system.details.level.base,dice=this.flags.pf2e.fixedAttack?weaponDamage.dice:[1,2,3,4].reduce((closest,dice2)=>Math.abs(dice2-Math.round((actorLevel+2)/4)){const fromAbility=actor.abilities[ability].mod,totalModifier=this.flags.pf2e.fixedAttack?weaponDamage.modifier:fromAbility+(actor.level>1?dice:0),sign=totalModifier<0?"-":"+";return totalModifier===0?"":[sign,Math.abs(totalModifier)].join("")})();return{damage:weaponDamage.die?`${dice}${weaponDamage.die}${constant}`:dice.toString(),damageType:weaponDamage.damageType,category:null}})(),fromPropertyRunes=this.system.runes.property.flatMap(r=>RUNE_DATA.weapon.property[r].damage?.dice??[]).map(d=>({damage:`${d.diceNumber}${d.dieSize}`,damageType:d.damageType??baseDamage.damageType,category:d.category??null})),reachTraitToNPCReach={tiny:null,sm:"reach-10",med:"reach-10",lg:"reach-15",huge:"reach-20",grg:"reach-25"},toAttackTraits=__name2(traits=>{const{increment:rangeIncrement,max:maxRange}=this.range??{},newTraits=traits.flatMap(t=>t==="reach"?reachTraitToNPCReach[this.size]??[]:t==="thrown"&&setHasElement(THROWN_RANGES,rangeIncrement)?`thrown-${rangeIncrement}`:t).filter(t=>(["holy","unholy"].includes(t)||!(t in CONFIG.PF2E.creatureTraits))&&!(t.startsWith("thrown")&&!this.isThrown)&&!(["grapple","finesse","shove","trip"].includes(t)&&this.isRanged)&&!(t==="brutal"&&this.isMelee)&&!(t==="combination"&&(this.isMelee||this.isThrown))&&!(t==="critical-fusion"&&this.isThrown)&&!["artifact","cursed"].includes(t));if(traits.some(t=>setHasElement(MAGIC_TRADITIONS,t))&&newTraits.push("magical"),rangeIncrement&&!this.isThrown){const prefix=maxRange===rangeIncrement*6?"range-increment":"range";newTraits.push(`${prefix}-${rangeIncrement}`)}const sizeToReach=SIZE_TO_REACH[actor.size];this.isMelee&&sizeToReach!==5&&!newTraits.some(t=>t.startsWith("reach"))&&newTraits.push(`reach-${sizeToReach}`);const reloadTrait=`reload-${this.reload}`;return objectHasKey(CONFIG.PF2E.npcAttackTraits,reloadTrait)&&newTraits.push(reloadTrait),uniq(newTraits).sort()},"toAttackTraits"),persistentDamage=(()=>{const{persistent}=this.system.damage;return persistent?{damage:persistent.faces?`${persistent.number}d${persistent.faces}`:persistent.number.toString(),damageType:persistent.type,category:"persistent"}:[]})(),splashDamage=this.system.splashDamage.value?{damage:this.system.splashDamage.value.toString(),damageType:this.system.damage.damageType,category:"splash"}:[],source={_id:keepId?this.id:null,name:this._source.name,type:"melee",system:{slug:this.slug??sluggify(this._source.name),weaponType:{value:this.isMelee?"melee":"ranged"},bonus:{value:this.flags.pf2e.fixedAttack||Math.round(1.5*this.actor.level+7)},damageRolls:[baseDamage,splashDamage,fromPropertyRunes,persistentDamage].flat().reduce((rolls,roll)=>foundry.utils.mergeObject(rolls,{[foundry.utils.randomID()]:roll}),{}),traits:{value:toAttackTraits(this.system.traits.value)},rules:foundry.utils.deepClone(this._source.system.rules)},flags:{pf2e:{linkedWeapon:this.id}}},attack=new MeleePF2e(source,{parent:this.actor});return attack.category=this.category,attack.group=this.group,attack.baseType=this.baseType,[attack,...this.getAltUsages({recurse:!1}).flatMap(u=>u.toNPCAttacks())]}async consumeAmmo(){const{ammo}=this;if(ammo?.isOfType("consumable"))return ammo.consume();if(ammo?.isOfType("weapon")){if(!ammo.system.usage.canBeAmmo)throw ErrorPF2e("attempted to consume weapon not usable as ammunition");await ammo.update({"system.quantity":Math.max(ammo.quantity-1,0)})}}_preUpdate(changed,options,user){if(!changed.system)return super._preUpdate(changed,options,user);const traits=changed.system.traits??{};return"value"in traits&&Array.isArray(traits.value)&&(traits.value=traits.value.filter(t=>t in CONFIG.PF2E.weaponTraits)),changed.system.group!==void 0&&(changed.system.group||=null),super._preUpdate(changed,options,user)}_onDelete(options,userId){if(super._onDelete(options,userId),game.user.id===userId){const updates=this.actor?.itemTypes.melee.filter(a=>a.flags.pf2e.linkedWeapon===this.id).map(a=>({_id:a.id,"flags.pf2e.-=linkedWeapon":null}))??[];this.actor?.updateEmbeddedDocuments("Item",updates)}}}class ABCItemPF2e extends ItemPF2e{static{__name(this,"ABCItemPF2e")}static{__name2(this,"ABCItemPF2e")}get rarity(){return this.system.traits.rarity}getLinkedItems(){if(!this.actor||!objectHasKey(this.actor.itemTypes,this.type))return[];const existingABCIds=this.actor.itemTypes[this.type].map(i=>i.id);return this.actor.itemTypes.feat.filter(f=>existingABCIds.includes(f.system.location??""))}async createGrantedItems(options={}){const entries=Object.values(this.system.items);if(!entries.filter(entry=>!!entry.uuid).length)return[];const items=(await UUIDUtils.fromUUIDs(entries.map(e=>e.uuid))).map(i=>i.clone()),level=options.level??this.parent?.level;return items.flatMap(item=>{if(item instanceof FeatPF2e){if(item.category==="classfeature"){const level2=entries.find(e=>item.sourceId===e.uuid)?.level??item.level;item.updateSource({"system.level.value":level2})}return level!==void 0&&levelboost.value.length===1).map(boost=>boost.selected).filter(boost=>!!boost)}get lockedFlaws(){return Object.values(this.system.flaws).map(flaw=>flaw.selected).filter(flaw=>!!flaw)}getLinkedItems(){return this.actor?Array.from(new Set([...super.getLinkedItems(),...this.actor.itemTypes.feat.filter(f=>f.category==="ancestryfeature")])):[]}prepareBaseData(){super.prepareBaseData();for(const boost of Object.values(this.system.boosts))boost.value.length===1&&(boost.selected=boost.value[0]);for(const flaw of Object.values(this.system.flaws))flaw.value.length===1&&(flaw.selected=flaw.value[0])}prepareActorData(){const{actor}=this;if(!actor.isOfType("character")){console.error("PF2e System | Only a character can have an ancestry");return}actor.ancestry=this,actor.system.attributes.ancestryhp=this.hitPoints,this.logAutoChange("system.attributes.ancestryhp",this.hitPoints),actor.system.traits.size.value=this.size,this.logAutoChange("system.traits.size.value",this.size);const reach=SIZE_TO_REACH[this.size];actor.system.attributes.reach={base:reach,manipulate:reach},actor.system.attributes.speed.value=this.speed;const{build}=actor.system;if(this.system.alternateAncestryBoosts)build.attributes.boosts.ancestry.push(...this.system.alternateAncestryBoosts);else for(const target of["boosts","flaws"])for(const ability of Object.values(this.system[target]))ability.selected&&build.attributes[target].ancestry.push(ability.selected);if(this.system.voluntary){const{boost,flaws}=this.system.voluntary;boost&&build.attributes.boosts.ancestry.push(boost),build.attributes.flaws.ancestry.push(...flaws)}const innateLanguages=this.system.languages.value;for(const language of innateLanguages)language in CONFIG.PF2E.languages&&!actor.system.traits.languages.value.includes(language)&&actor.system.traits.languages.value.push(language);const{senses:senses2}=actor.system.traits,{vision}=this.system;if(!(vision==="normal"||senses2.some(sense=>sense.type===vision))){senses2.push(new CreatureSensePF2e({type:vision,value:"",source:this.name}));const senseRollOptions=actor.rollOptions.sense??={};senseRollOptions[`self:${sluggify(vision)}:from-ancestry`]=!0}actor.system.traits.value.push(...this.traits);const slug=this.slug??sluggify(this.name);actor.system.details.ancestry={name:this.name,trait:slug,adopted:null,versatile:null,countsAs:[slug]},actor.rollOptions.all[`self:ancestry:${slug}`]=!0;for(const trait of this.traits)actor.rollOptions.all[`self:trait:${trait}`]=!0}getRollOptions(prefix=this.type){return[...super.getRollOptions(prefix),`${prefix}:rarity:${this.rarity}`]}}class BackgroundPF2e extends ABCItemPF2e{static{__name(this,"BackgroundPF2e")}static{__name2(this,"BackgroundPF2e")}get traits(){return new Set(this.system.traits.value)}prepareSiblingData(){if(Object.keys(this.system.items).length>0)return;const grantedSkillFeat=Object.values(this.flags.pf2e.itemGrants).flatMap(g=>this.actor.items.get(g.id)??[]).find(i=>i.isOfType("feat")&&i.category==="skill");grantedSkillFeat&&(this.system.items.GRANT={uuid:grantedSkillFeat.sourceId??grantedSkillFeat.uuid,img:grantedSkillFeat.img,name:grantedSkillFeat.name,level:1},grantedSkillFeat.system.level.taken=1,grantedSkillFeat.system.location=this.id)}prepareActorData(){if(!this.actor.isOfType("character")){console.error("Only a character can have a background");return}this.actor.background=this;const{build}=this.actor.system,boosts=Object.values(this.system.boosts);for(const boost of boosts)boost.selected&&build.attributes.boosts.background.push(boost.selected);const{trainedSkills}=this.system;if(trainedSkills.value.length===1){const key=trainedSkills.value[0],skill=this.actor.system.skills[key];skill.rank=Math.max(skill.rank,1)}}}class ClassPF2e extends ABCItemPF2e{static{__name(this,"ClassPF2e")}static{__name2(this,"ClassPF2e")}get attacks(){return this.system.attacks}get defenses(){return this.system.defenses}get hpPerLevel(){return this.system.hp}get perception(){return this.system.perception}get savingThrows(){return this.system.savingThrows}get grantedFeatSlots(){const system=this.system;return{ancestry:foundry.utils.deepClone(system.ancestryFeatLevels.value),class:[...system.classFeatLevels.value],skill:[...system.skillFeatLevels.value],general:[...system.generalFeatLevels.value]}}getLinkedItems(){const{actor}=this;return actor?Array.from(new Set([...super.getLinkedItems(),...actor.itemTypes.feat.filter(f=>f.category==="classfeature"&&!(f.flags.pf2e.grantedBy&&actor.items.has(f.flags.pf2e.grantedBy.id)))])):[]}async createGrantedItems(options={}){return(await super.createGrantedItems(options)).sort((a,b)=>a.system.level.value-b.system.level.value)}prepareBaseData(){super.prepareBaseData();const{keyAbility}=this.system;keyAbility.selected??=keyAbility.value.length===1?keyAbility.value[0]:null}prepareActorData(){if(!this.actor?.isOfType("character")){console.error("Only a character can have a class");return}this.actor.class=this;const{attributes,build,details,proficiencies,saves,skills}=this.actor.system,slug=this.slug??sluggify(this.name);build.attributes.keyOptions=[...this.system.keyAbility.value],build.attributes.boosts.class=this.system.keyAbility.selected,attributes.classhp=this.hpPerLevel,attributes.perception.rank=Math.max(attributes.perception.rank,this.perception),this.logAutoChange("system.attributes.perception.rank",this.perception),details.keyability.value=(build.attributes.manual?details.keyability.value:build.attributes.boosts.class)??"str";const classDCs=proficiencies.classDCs;classDCs[slug]={label:this.name,rank:1,ability:details.keyability.value,primary:!0},this.logAutoChange(`system.proficiencies.classDCs.${slug}.rank`,1);const{attacks,defenses}=proficiencies;for(const category of WEAPON_CATEGORIES)attacks[category].rank=Math.max(attacks[category].rank,this.attacks[category]),this.logAutoChange(`system.proficiencies.attacks.${category}.rank`,this.attacks[category]);const nonBarding=Array.from(ARMOR_CATEGORIES).filter(c=>!["light-barding","heavy-barding"].includes(c));for(const category of nonBarding)defenses[category].rank=Math.max(defenses[category].rank,this.defenses[category]),this.logAutoChange(`system.proficiencies.defenses.${category}.rank`,this.defenses[category]);for(const saveType of SAVE_TYPES)saves[saveType].rank=Math.max(saves[saveType].rank,this.savingThrows[saveType]),this.logAutoChange(`system.saves.${saveType}.rank`,this.savingThrows[saveType]);for(const trainedSkill of this.system.trainedSkills.value)setHasElement(SKILL_ABBREVIATIONS,trainedSkill)&&(skills[trainedSkill].rank=Math.max(skills[trainedSkill].rank,1));proficiencies.spellcasting.rank=Math.max(proficiencies.spellcasting.rank,this.system.spellcasting),this.logAutoChange("system.proficiencies.spellcasting.rank",this.system.spellcasting),details.class={name:this.name,trait:slug},this.actor.rollOptions.all[`class:${slug}`]=!0}}class AbilityItemPF2e extends ItemPF2e{static{__name(this,"AbilityItemPF2e")}static{__name2(this,"AbilityItemPF2e")}range=null;get traits(){return new Set(this.system.traits.value)}get actionCost(){const actionType=this.system.actionType.value||"passive";return actionType==="passive"?null:{type:actionType,value:this.system.actions.value}}get frequency(){return this.system.frequency??null}prepareBaseData(){super.prepareBaseData(),this.actor&&this.system.frequency&&(this.system.frequency.value??=this.system.frequency.max),this.system.selfEffect??=null,this.system.actionType.value==="passive"&&(this.system.selfEffect=null),this.system.traits.value=this.system.traits.value.filter(t=>t in CONFIG.PF2E.actionTraits)}onPrepareSynthetics(){processSanctification(this)}getRollOptions(prefix=this.type){const options=super.getRollOptions(prefix);return(this.frequency||this.system.deathNote)&&options.push(`${prefix}:frequency:limited`),options}async getChatData(htmlOptions={}){return this.processChatData(htmlOptions,{...this.system,traits:this.traitChatData(CONFIG.PF2E.featTraits)})}async _preCreate(data,options,user){return this.parent||this._source.system.frequency&&this.updateSource({"system.frequency.-=value":null}),super._preCreate(data,options,user)}async _preUpdate(changed,options,user){return typeof changed.system?.category=="string"&&(changed.system.category||=null),normalizeActionChangeData(this,changed),super._preUpdate(changed,options,user)}}const KINGDOM_CATEGORY_DATA={"army-tactic":{behavior:"feat",levelLabel:"PF2E.Kingmaker.Feature.Tactic"},"army-war-action":{behavior:"activity"},"kingdom-feat":{behavior:"feat"},"kingdom-feature":{behavior:"feature"},"kingdom-activity":{behavior:"activity"}},KINGMAKER_CATEGORY_TYPES=Object.keys(KINGDOM_CATEGORY_DATA),KINGMAKER_CATEGORIES=mapToObj(KINGMAKER_CATEGORY_TYPES,type=>[type,`PF2E.Kingmaker.Feature.Categories.${type}`]);class CampaignFeaturePF2e extends ItemPF2e{static{__name(this,"CampaignFeaturePF2e")}static{__name2(this,"CampaignFeaturePF2e")}granter=null;get category(){return this.system.category}get level(){return this.behavior!=="activity"?this.system.level?.value??0:null}get traits(){return new Set(this.system.traits.value)}get actionCost(){const actionType=this.system.actionType.value||"passive";return actionType==="passive"?null:{type:actionType,value:this.system.actions.value}}get frequency(){return this.system.frequency??null}get isAction(){return this.behavior==="activity"}get isFeature(){return this.behavior==="feature"}get isFeat(){return this.behavior==="feat"}prepareBaseData(){super.prepareBaseData();const categoryData=KINGDOM_CATEGORY_DATA[this.category]??Object.values(KINGDOM_CATEGORY_DATA)[0];this.behavior=categoryData.behavior,this.group=null,this.levelLabel=categoryData.levelLabel??(this.isFeat?"PF2E.Item.Feat.LevelLabel":"PF2E.LevelLabel"),this.actor&&this.system.frequency&&(this.system.frequency.value??=this.system.frequency.max)}prepareActorData(){const prefix=this.isFeature?"feature":this.isFeat?"feat":null;if(prefix){const slug=this.slug??sluggify(this.name);this.actor.rollOptions.all[`${prefix}:${slug}`]=!0}}prepareSiblingData(){const itemGrants=this.flags.pf2e.itemGrants;this.grants=Object.values(itemGrants).flatMap(grant=>{const item=this.actor?.items.get(grant.id);return item?.isOfType("campaignFeature")?(item.granter=this,[item]):[]})}getRollOptions(prefix=null){return prefix??=this.isFeature?"feature":this.isFeat?"feat":"action",compact([...super.getRollOptions(prefix).filter(o=>!o.endsWith("level:0")),`${prefix}:category:${this.category}`,this.isAction?`action:${this.slug}`:null])}async _preCreate(data,options,user){return this.parent||(this.updateSource({"system.location":null}),this._source.system.frequency&&this.updateSource({"system.frequency.-=value":null})),super._preCreate(data,options,user)}async _preUpdate(changed,options,user){if(typeof changed.system?.location=="string"&&(changed.system.location||=null),normalizeActionChangeData(this,changed),changed.system&&changed.system.category){const system=changed.system,category=tupleHasValue(KINGMAKER_CATEGORY_TYPES,changed.system.category)?changed.system.category:KINGMAKER_CATEGORY_TYPES[0];if(KINGDOM_CATEGORY_DATA[category].behavior==="activity")"level"in this.system&&(system["-=level"]=null);else{const level=system.level?.value??this.system.level?.value??0;system.level={value:level}}}await super._preUpdate(changed,options,user)}}class TrickMagicItemPopup{static{__name(this,"TrickMagicItemPopup")}static{__name2(this,"TrickMagicItemPopup")}item;checkDC;#localize=localizer("PF2E.TrickMagicItemPopup");constructor(item){if(!item.isOfType("consumable"))throw ErrorPF2e("Unexpected item used for Trick Magic Item");if(!item.actor?.isOfType("character"))throw ErrorPF2e(this.#localize("InvalidActor"));this.item=item,this.actor=item.actor,this.checkDC=calculateTrickMagicItemCheckDC(item),this.#initialize()}async#initialize(){const buttons=TRICK_MAGIC_SKILLS.filter(skill=>skill in this.checkDC).map(value=>({value,label:game.i18n.localize(`PF2E.Skill${value.capitalize()}`),modifier:this.actor.skills[value].check.mod})).reduce((accumulated,skill)=>{const button={icon:fontAwesomeIcon("dice-d20").outerHTML,label:`${skill.label} (${skill.modifier<0?"":"+"}${skill.modifier})`,callback:()=>this.#handleTrickItem(skill.value)};return{...accumulated,[skill.value]:button}},{});new Dialog({title:this.#localize("Title"),content:`
${this.#localize("Label")}
`,buttons},{classes:["dialog","trick-magic-item"],width:"auto"}).render(!0)}#handleTrickItem(skill){this.actor.skills[skill].check.roll({extraRollOptions:["action:trick-magic-item"],dc:{value:this.checkDC[skill]??0},item:this.item});const trick=new TrickMagicItemEntry(this.actor,skill);this.item.castEmbeddedSpell(trick)}}class ConsumablePF2e extends PhysicalItemPF2e{static{__name(this,"ConsumablePF2e")}static{__name2(this,"ConsumablePF2e")}get otherTags(){return new Set(this.system.traits.otherTags)}get category(){return this.system.category}get isAmmo(){return this.category==="ammo"}get uses(){return pick(this.system.uses,["value","max"])}get embeddedSpell(){if(!this.actor)throw ErrorPF2e(`No owning actor found for "${this.name}" (${this.id})`);return this.system.spell?new SpellPF2e(foundry.utils.deepClone(this.system.spell),{parent:this.actor,fromConsumable:!0}):null}prepareBaseData(){if(super.prepareBaseData(),this.system.uses.max||=1,!!this.isAmmo){for(const rule of this.system.rules)if(rule.key==="RollOption"&&"toggleable"in rule&&rule.toggleable){console.warn("Toggleable RollOption rule elements may not be added to ammunition"),this.system.rules=[];break}else if(["GrantItem","ChoiceSet"].includes(String(rule.key))){console.warn(`${rule.key} rule elements may not be added to ammunition`),this.system.rules=[];break}}}prepareRuleElements(){const rules=super.prepareRuleElements();for(const rule of rules)rule.ignored=!0;return rules}async getChatData(htmlOptions={},rollOptions={}){const traits=this.traitChatData(CONFIG.PF2E.consumableTraits),[category,isUsable]=this.isIdentified?[game.i18n.localize(CONFIG.PF2E.consumableCategories[this.category]),!0]:[this.generateUnidentifiedName({typeOnly:!0}),!["other","scroll","talisman","toolkit","wand"].includes(this.category)],usesLabel=game.i18n.localize("PF2E.Item.Consumable.Uses.Label"),fromFormula=!!rollOptions.fromFormula;return this.processChatData(htmlOptions,{...await super.getChatData(),traits,properties:this.isIdentified&&this.uses.max>1?[`${this.uses.value}/${this.uses.max} ${usesLabel}`]:[],category,isUsable:fromFormula?!1:isUsable})}generateUnidentifiedName({typeOnly=!1}={typeOnly:!1}){const liquidOrSubstance=__name2(()=>this.traits.has("inhaled")||this.traits.has("contact")?"PF2E.identification.UnidentifiedType.Substance":"PF2E.identification.UnidentifiedType.Liquid","liquidOrSubstance"),itemType=game.i18n.localize(["drug","elixir","mutagen","oil","poison","potion"].includes(this.category)?liquidOrSubstance():["scroll","snare","ammo"].includes(this.category)?CONFIG.PF2E.consumableCategories[this.category]:"PF2E.identification.UnidentifiedType.Object");return typeOnly?itemType:game.i18n.format("PF2E.identification.UnidentifiedItem",{item:itemType})}getRollOptions(prefix=this.type){return[...super.getRollOptions(prefix),...Object.entries({[`category:${this.category}`]:!0}).filter(([,isTrue])=>isTrue).map(([key])=>`${prefix}:${key}`)]}isAmmoFor(weapon){if(!this.isAmmo)return!1;if(!weapon.isOfType("weapon"))return console.warn("Cannot load a consumable into a non-weapon"),!1;const{max}=this.uses;return weapon.system.traits.value.includes("repeating")?max>1:max<=1}async consume(){const{actor}=this;if(!actor)return;const{value,max}=this.uses;if(["scroll","wand"].includes(this.category)&&this.system.spell)if(actor.spellcasting.canCastConsumable(this))this.castEmbeddedSpell();else if(actor.itemTypes.feat.some(feat=>feat.slug==="trick-magic-item"))new TrickMagicItemPopup(this);else{const formatParams={actor:actor.name,spell:this.name},message=game.i18n.format("PF2E.LackCastConsumableCapability",formatParams);ui.notifications.warn(message);return}else if(this.category!=="ammo"){const key=max>1&&value===1?"UseExhausted":max>1?"UseMulti":"UseSingle",content=game.i18n.format(`PF2E.ConsumableMessage.${key}`,{name:this.name,current:value-1}),flags={pf2e:{origin:{sourceId:this.flags.core?.sourceId,uuid:this.uuid,type:this.type}}},speaker=ChatMessage.getSpeaker({actor});if(this.system.damage){const{formula,type,kind}=this.system.damage;new DamageRoll(`(${formula})[${type},${kind}]`).toMessage({speaker,flavor:content,flags})}else ChatMessage.create({speaker,content,flags})}if(this.system.uses.autoDestroy&&value<=1){const{quantity}=this,isPreservedAmmo=this.category==="ammo"&&this.system.rules.length>0;quantity<=1&&!isPreservedAmmo?await this.delete():await this.update({"system.quantity":Math.max(quantity-1,0),"system.uses.value":max})}else await this.update({"system.uses.value":Math.max(value-1,0)})}async castEmbeddedSpell(trickMagicItemData){const{actor}=this,spell=this.embeddedSpell;if(!actor||!spell)return;const entry=(()=>trickMagicItemData||actor.spellcasting.filter(e=>e instanceof SpellcastingEntryPF2e&&e.canCast(spell,{origin:this})).reduce((previous,current)=>{const previousDC=previous.statistic.dc.value;return current.statistic.dc.value>previousDC?current:previous}))();if(entry){const systemData=spell.system;entry instanceof SpellcastingEntryPF2e&&(systemData.location.value=entry.id),entry.cast(spell,{consume:!1})}}_preUpdate(changed,options,user){if(!changed.system)return super._preUpdate(changed,options,user);if(typeof changed.system.damage?.type=="string"){const category=changed.system.category??this.system.category;setHasElement(DAMAGE_OR_HEALING_CONSUMABLE_CATEGORIES,category)?(setHasElement(DAMAGE_ONLY_CONSUMABLE_CATEGORIES,category)||!["vitality","void","untyped"].includes(changed.system.damage.type))&&(changed.system.damage.kind="damage"):changed.system.damage=null}if(changed.system.uses){if("value"in changed.system.uses){const minimum=this.system.uses.autoDestroy?1:0;changed.system.uses.value=Math.clamped(Math.floor(Number(changed.system.uses.value))||minimum,minimum,9999)}"max"in changed.system.uses&&(changed.system.uses.max=Math.clamped(Math.floor(Number(changed.system.uses.max))||1,1,9999)),typeof changed.system.uses.value=="number"&&typeof changed.system.uses.max=="number"&&(changed.system.uses.value=Math.min(changed.system.uses.value,changed.system.uses.max))}return changed.system.price?.per!==void 0&&(changed.system.price.per=Math.clamped(Math.floor(Number(changed.system.price.per))||1,1,999)),super._preUpdate(changed,options,user)}}class DeityPF2e extends ItemPF2e{static{__name(this,"DeityPF2e")}static{__name2(this,"DeityPF2e")}get category(){return this.system.category}get favoredWeapons(){return[...this.system.weapons]}prepareBaseData(){super.prepareBaseData(),this.system.sanctification?.modal||(this.system.sanctification=null),this.category==="philosophy"&&(this.system.attribute=[],this.system.domains={primary:[],alternate:[]},this.system.font=[],this.system.sanctification=null,this.system.skill=null,this.system.spells={},this.system.weapons=[])}prepareActorData(){if(!this.actor.isOfType("character")){this.delete({render:!1});return}this.actor.deity=this;const{deities}=this.actor.system.details,systemData=this.system;deities.primary={skill:foundry.utils.deepClone(systemData.skill),weapons:foundry.utils.deepClone(systemData.weapons)};for(const domain of this.system.domains.primary){const label=CONFIG.PF2E.deityDomains[domain]?.label;deities.domains[domain]=label??domain;const apocryphaKey=`${domain}-apocryphal`;if(objectHasKey(CONFIG.PF2E.deityDomains,apocryphaKey)){const apocrypha=CONFIG.PF2E.deityDomains[apocryphaKey];deities.domains[apocryphaKey]=apocrypha.label}}const slug=this.slug??sluggify(this.name),prefix="deity:primary",actorRollOptions=this.actor.rollOptions;actorRollOptions.all.deity=!0,actorRollOptions.all[`${prefix}:${slug}`]=!0;const sanctifications=this.getSanctificationRollOptions().map(o=>`${prefix}:${o}`);for(const option of sanctifications)actorRollOptions.all[option]=!0;for(const baseType of this.favoredWeapons)actorRollOptions.all[`${prefix}:favored-weapon:${baseType}`]=!0;actorRollOptions.all[`self:deity:slug:${slug}`]=!0}setFavoredWeaponRank(){if(!this.actor.isOfType("character"))return;const favoredWeaponRank=this.actor.flags.pf2e.favoredWeaponRank;if(favoredWeaponRank>0){const attacks=this.actor.system.proficiencies.attacks,baseWeaponTypes2=CONFIG.PF2E.baseWeaponTypes,baseShieldTypes2=CONFIG.PF2E.baseShieldTypes;for(const baseType of this.favoredWeapons)attacks[`weapon-base-${baseType}`]={label:baseWeaponTypes2[baseType]??baseShieldTypes2[baseType]??baseType,rank:Math.max(Number(attacks[`weapon-base-${baseType}`]?.rank)||0,favoredWeaponRank)}}}getRollOptions(prefix=this.type){const baseOptions=super.getRollOptions(prefix),sanctifications=this.getSanctificationRollOptions().map(o=>`${prefix}:${o}`);return[...baseOptions,`${prefix}:category:${this.category}`,...sanctifications].sort()}getSanctificationRollOptions(){const{sanctification}=this.system,modal=sanctification?.modal;return sanctification?.modal&&sanctification.what.length>0?sanctification.what.map(s=>`sanctification:${modal}:${s}`):["sanctification:none"]}}function featCanHaveKeyOptions(feat){if(feat.category!=="classfeature"||feat.level!==1||feat.traits.size>1)return!1;const{grantedBy}=feat;return!grantedBy||grantedBy.isOfType("feat")&&grantedBy.category==="classfeature"}__name(featCanHaveKeyOptions,"featCanHaveKeyOptions"),__name2(featCanHaveKeyOptions,"featCanHaveKeyOptions");class FeatPF2e extends ItemPF2e{static{__name(this,"FeatPF2e")}static{__name2(this,"FeatPF2e")}get category(){return this.system.category}get level(){return this.system.level.value}get traits(){return new Set(this.system.traits.value)}get rarity(){return this.system.traits.rarity}get actionCost(){const actionType=this.system.actionType.value||"passive";return actionType==="passive"?null:{type:actionType,value:this.system.actions.value}}get frequency(){return this.system.frequency??null}get isFeature(){return setHasElement(FEATURE_CATEGORIES,this.category)}get isFeat(){return setHasElement(FEAT_CATEGORIES,this.category)}get onlyLevel1(){return this.system.onlyLevel1}get maxTakable(){return this.system.maxTakable}prepareBaseData(){super.prepareBaseData(),this.group=null,this.system.level.taken??=null,this.system.location||=null;const traits=this.system.traits.value;this.category==="general"&&!traits.includes("general")&&traits.push("general"),this.category==="skill"&&(traits.includes("skill")||traits.push("skill"),!traits.includes("general")&&!traits.includes("archetype")&&traits.push("general")),traits.includes("dedication")&&(this.system.category="class",traits.includes("archetype")||traits.push("archetype")),this.system.traits.value.includes("lineage")&&(this.system.onlyLevel1=!0),this.system.maxTakable??=1/0,this.system.onlyLevel1&&(this.system.maxTakable=1),this.actor&&this.system.frequency&&(this.system.frequency.value??=this.system.frequency.max),this.system.subfeatures=foundry.utils.mergeObject({keyOptions:[]},this.system.subfeatures??{}),this.system.selfEffect??=null,this.system.actionType.value==="passive"&&(this.system.selfEffect=null)}prepareActorData(){const{actor}=this,prefix=this.isFeature?"feature":"feat",slug=this.slug??sluggify(this.name);actor.rollOptions.all[`${prefix}:${slug}`]=!0;const{subfeatures}=this.system;featCanHaveKeyOptions(this)||(subfeatures.keyOptions=[]),actor.isOfType("character")&&subfeatures.keyOptions.length>0&&(actor.system.build.attributes.keyOptions=uniq([...actor.system.build.attributes.keyOptions,...subfeatures.keyOptions]))}prepareSiblingData(){this.grants=Object.values(this.flags.pf2e.itemGrants).flatMap(grant=>{const item=this.actor?.items.get(grant.id);return item?.isOfType("feat")&&!item.system.location||item?.isOfType("heritage")?[item]:[]});for(const grant of this.grants.filter(g=>g.isOfType("feat")))grant.system.level.taken=this.system.level.taken}onPrepareSynthetics(){processSanctification(this)}async getChatData(htmlOptions={}){const levelLabel=game.i18n.format("PF2E.LevelN",{level:this.level}),actionTypeLabel=getActionTypeLabel(this.actionCost?.type,this.actionCost?.value),properties=actionTypeLabel?[levelLabel,actionTypeLabel]:[levelLabel],traits=this.traitChatData(CONFIG.PF2E.featTraits);return this.processChatData(htmlOptions,{...this.system,properties,traits})}getRollOptions(prefix="feat"){return prefix=prefix==="feat"&&this.isFeature?"feature":prefix,compact([...super.getRollOptions(prefix).filter(o=>!o.endsWith("level:0")),`${prefix}:category:${this.category}`,this.isFeat?`${prefix}:rarity:${this.rarity}`:null,this.frequency?`${prefix}:frequency:limited`:null])}async _preCreate(data,options,user){return this.parent||(this._source.system.location=null,delete this._source.system.level.taken,this._source.system.frequency&&delete this._source.system.frequency.value),super._preCreate(data,options,user)}async _preUpdate(changed,options,user){if(!changed.system)return super._preUpdate(changed,options,user);"location"in changed.system&&(changed.system.location||=null),typeof changed.system.level?.value=="number"&&changed.system.level.value!==1&&(changed.system.onlyLevel1=!1),normalizeActionChangeData(this,changed);const traits=changed.system.traits?.value;return setHasElement(FEATURE_CATEGORIES,changed.system.category??this.category)?(changed.system.onlyLevel1=!1,changed.system.maxTakable=1,this.category!=="ancestry"&&Array.isArray(traits)&&traits.findSplice(t=>t==="lineage")):(Array.isArray(traits)&&traits.includes("lineage")||changed.system?.onlyLevel1)&&foundry.utils.mergeObject(changed,{system:{maxTakable:1}}),super._preUpdate(changed,options,user)}_onCreate(data,options,userId){if(super._onCreate(data,options,userId),!(this.isOwner&&this.actor?.isOfType("character")&&this.isFeat))return;const actorItemNames={actor:this.actor.name,item:this.name};if(this.onlyLevel1&&this.actor.level>1){const formatParams={...actorItemNames,actorLevel:this.actor.level},warning=game.i18n.format("PF2E.Item.Feat.Warning.TakenAfterLevel1",formatParams);ui.notifications.warn(warning)}if(this.flags.pf2e.grantedBy)return;const slug=this.slug??sluggify(this.name),timesTaken=this.actor.itemTypes.feat.filter(f=>f.slug===slug).length,{maxTakable}=this;if(maxTakable===1&×Taken>1)ui.notifications.warn(game.i18n.format("PF2E.Item.Feat.Warning.TakenMoreThanOnce",actorItemNames));else if(timesTaken>maxTakable){const formatParams={...actorItemNames,maxTakable,timesTaken};ui.notifications.warn(game.i18n.format("PF2E.Item.Feat.Warning.TakenMoreThanMax",formatParams))}}}class HeritagePF2e extends ItemPF2e{static{__name(this,"HeritagePF2e")}static{__name2(this,"HeritagePF2e")}get traits(){return new Set(this.system.traits.value)}get rarity(){return this.system.traits.rarity}get isVersatile(){return!this.system.ancestry}prepareActorData(){if(!this.actor.isOfType("character"))throw ErrorPF2e("heritage embedded on non-character");const slug=this.slug??sluggify(this.name);(this.actor.itemTypes.heritage.length===1||!this.grantedBy)&&(this.actor.heritage=this,this.actor.system.details.heritage={name:this.name,trait:slug in CONFIG.PF2E.ancestryTraits?slug:null}),this.actor.system.traits.value.push(...this.traits),this.isVersatile&&this.actor.system.details.ancestry?.countsAs.push(slug),this.actor.rollOptions.all[`heritage:${slug}`]=!0,this.actor.rollOptions.all[`self:heritage:${slug}`]=!0}getRollOptions(prefix=this.type){const ancestryOrVersatile=this.system.ancestry?`ancestry:${this.system.ancestry.slug}`:"versatile";return[...super.getRollOptions(prefix),`${prefix}:${ancestryOrVersatile}`]}}class KitPF2e extends ItemPF2e{static{__name(this,"KitPF2e")}static{__name2(this,"KitPF2e")}get entries(){return Object.values(this.system.items)}get price(){return{value:new CoinsPF2e(this.system.price.value),per:this.system.price.per??1}}async createGrantedItems(options={}){const size=new ActorSizePF2e({value:options.size??"med",smallIsMedium:!0}).value,entries=options.entries??this.entries,itemUUIDs=entries.map(e=>e.uuid),items=await UUIDUtils.fromUUIDs(itemUUIDs);if(entries.length!==items.length)throw ErrorPF2e(`Some items from ${this.name} were not found`);return items.every(i=>i instanceof ItemPF2e&&!i.parent)?items.reduce(async(promise,item,index)=>{const prepared=await promise,clone=item.clone({_id:foundry.utils.randomID(),system:{size}},{keepId:!0}),entry=entries[index];if(clone.isOfType("physical")&&clone.updateSource({"system.quantity":entry.quantity,"system.containerId":options.containerId}),clone.isOfType("backpack")&&entry.items){const contents=await this.createGrantedItems({entries:Object.values(entry.items),containerId:clone.id,size});prepared.push(clone,...contents)}else if(clone instanceof KitPF2e){const inflatedKit=await clone.createGrantedItems({containerId:options.containerId,size});prepared.push(...inflatedKit)}else clone instanceof PhysicalItemPF2e&&prepared.push(clone);return prepared},[]):[]}async _preUpdate(changed,options,user){if(!changed.system)return await super._preUpdate(changed,options,user);if(isObject(changed.system.price)){const price=changed.system.price;for(const denomination of DENOMINATIONS)price[denomination]===0&&(price["-=denomination"]=null)}return super._preUpdate(changed,options,user)}}class LorePF2e extends ItemPF2e{static{__name(this,"LorePF2e")}static{__name2(this,"LorePF2e")}}class LoreSheetPF2e extends ItemSheetPF2e{static{__name(this,"LoreSheetPF2e")}static{__name2(this,"LoreSheetPF2e")}}class DicePF2e{static{__name(this,"DicePF2e")}static{__name2(this,"DicePF2e")}_rolled;terms;static async d20Roll({event:event2,item=null,parts,data,template,title,speaker,flavor,onClose,dialogOptions,rollMode=game.settings.get("core","rollMode"),rollType=""}){const userSettingQuickD20Roll=!game.user.settings.showCheckDialogs,_roll=__name2(async(rollParts,adv,$form)=>{let flav=flavor instanceof Function?flavor(rollParts,data):title;adv===1?(rollParts[0]=["2d20kh"],flav=game.i18n.format("PF2E.Roll.FortuneTitle",{title})):adv===-1&&(rollParts[0]=["2d20kl"],flav=game.i18n.format("PF2E.Roll.MisfortuneTitle",{title})),$form&&(data.itemBonus=$form.find("[name=itemBonus]").val()),(!data.itemBonus||data.itemBonus===0)&&rollParts.indexOf("@itemBonus")!==-1&&rollParts.splice(rollParts.indexOf("@itemBonus"),1),$form&&(data.statusBonus=$form.find("[name=statusBonus]").val()),(!data.statusBonus||data.statusBonus===0)&&rollParts.indexOf("@statusBonus")!==-1&&rollParts.splice(rollParts.indexOf("@statusBonus"),1),$form&&(data.circumstanceBonus=$form.find("[name=circumstanceBonus]").val()),(!data.circumstanceBonus||data.circumstanceBonus===0)&&rollParts.indexOf("@circumstanceBonus")!==-1&&rollParts.splice(rollParts.indexOf("@circumstanceBonus"),1);const roll=await new Roll(rollParts.join("+"),data).roll({async:!0}),origin=item?{uuid:item.uuid,type:item.type}:null;return roll.toMessage({speaker,flavor:flav,flags:{pf2e:{context:{type:rollType},origin}}},{rollMode:$form?$form.find("[name=rollMode]").val():rollMode}),roll},"_roll");if(parts.unshift("1d20"),userSettingQuickD20Roll&&!event2.altKey&&!(event2.ctrlKey||event2.metaKey)&&!event2.shiftKey||!userSettingQuickD20Roll&&event2.shiftKey)return _roll(parts,0);if(event2.ctrlKey||event2.metaKey)return rollMode="blindroll",_roll(parts,0);if(event2.shiftKey||!userSettingQuickD20Roll){parts.indexOf("@circumstanceBonus")===-1&&(parts=parts.concat(["@circumstanceBonus"])),parts.indexOf("@itemBonus")===-1&&(parts=parts.concat(["@itemBonus"])),parts.indexOf("@statusBonus")===-1&&(parts=parts.concat(["@statusBonus"])),template=template||"systems/pf2e/templates/chat/roll-dialog.hbs";const dialogData={data,rollMode,formula:parts.join(" + "),rollModes:CONFIG.Dice.rollModes},content=await renderTemplate(template,dialogData);let roll;return new Promise(resolve=>{new Dialog({title,content,buttons:{advantage:{label:game.i18n.localize("PF2E.Roll.Fortune"),callback:async html=>{roll=await _roll(parts,1,html)}},normal:{label:game.i18n.localize("PF2E.Roll.Normal"),callback:async html=>{roll=await _roll(parts,0,html)}},disadvantage:{label:game.i18n.localize("PF2E.Roll.Misfortune"),callback:async html=>{roll=await _roll(parts,-1,html)}}},default:game.i18n.localize("PF2E.Roll.Normal"),close:html=>{onClose&&onClose(html,parts,data),resolve(roll)}},dialogOptions).render(!0)})}else return _roll(parts,0)}alter(add2,multiply){const rgx=new RegExp(DiceTerm.REGEXP,"g");if(this._rolled)throw ErrorPF2e("You may not alter a Roll which has already been rolled");return this.terms=this.terms?.map(t=>t.replace(rgx,(_match,nd,d,mods)=>(nd=nd*(multiply||1)+(add2||0),mods=mods||"",`${nd}d${d}${mods}`))),this}}function simplifyFormula(formula){if(formula==="0")return formula;const fixedFormula=formula.replace(/^\s*-\s+/,"-").replace(/\s*\+\s*-\s*/g," - "),roll=new Roll(fixedFormula);if(!roll.terms.every(t=>[" - "," + "].includes(t.expression)||t instanceof Die||t instanceof NumericTerm))return fixedFormula;const terms=parseTermsFromSimpleFormula(roll);return createSimpleFormula(terms)}__name(simplifyFormula,"simplifyFormula"),__name2(simplifyFormula,"simplifyFormula");class MeleePF2e extends ItemPF2e{static{__name(this,"MeleePF2e")}static{__name2(this,"MeleePF2e")}get traits(){return new Set(this.system.traits.value)}get isMelee(){return this.system.weaponType.value==="melee"}get isRanged(){return this.system.weaponType.value==="ranged"}get isThrown(){return this.isRanged&&this.system.traits.value.some(t=>t.startsWith("thrown"))}get defaultAttribute(){const{traits}=this;return this.isMelee?traits.has("finesse")?"dex":"str":traits.has("brutal")?"str":"dex"}get attackModifier(){return Number(this.system.bonus.value)||0}get reach(){if(this.isRanged)return null;const reachTrait=this.system.traits.value.find(t=>/^reach-\d+$/.test(t));return reachTrait?Number(reachTrait.replace("reach-","")):SIZE_TO_REACH[this.actor?.size??"med"]}get range(){if(this.isMelee)return null;const specifiedMaxRange=(()=>{const rangeTrait=this.system.traits.value.find(t=>/^range-\d+$/.test(t)),range2=Number(rangeTrait?.replace(/\D/g,"")||"NaN");return Number.isInteger(range2)?range2:null})(),rangeIncrement=(()=>{if(specifiedMaxRange)return null;const incrementTrait=this.system.traits.value.find(t=>/^(?:range-increment|thrown)-\d+$/.test(t));return Number(incrementTrait?.replace(/\D/g,""))||10})();return specifiedMaxRange?{increment:null,max:specifiedMaxRange}:rangeIncrement?{increment:rangeIncrement,max:rangeIncrement*6}:null}get baseDamage(){const partials=Object.values(this.system.damageRolls),instance=partials.find(p=>!p.category)??partials.at(0);return instance?WeaponDamagePF2e.npcDamageToWeaponDamage(instance):{dice:0,die:null,modifier:0,damageType:"untyped",persistent:null,category:null}}get dealsDamage(){const{baseDamage}=this;return baseDamage.dice>0||baseDamage.modifier>0||!!baseDamage.persistent?.number||Object.values(this.system.damageRolls).some(d=>d.category==="splash")}get attackEffects(){return this.system.attackEffects.value}get isMagical(){const{traits}=this;return["magical","arcane","primal","divine","occult"].some(t=>traits.has(t))}get linkedWeapon(){const item=this.actor?.items.get(this.flags.pf2e.linkedWeapon??"");return item?.isOfType("weapon")?item:null}_initialize(options){this.category=this.group=this.baseType=null,super._initialize(options)}prepareBaseData(){super.prepareBaseData(),this.system.traits.value=this.system.traits.value.filter(t=>t in CONFIG.PF2E.npcAttackTraits),this.system.material={type:null,grade:null,effects:[]},this.system.runes={property:[]};for(const attackDamage of Object.values(this.system.damageRolls))attackDamage.category||=null,attackDamage.damageType==="bleed"&&(attackDamage.category="persistent")}prepareSiblingData(){const{linkedWeapon}=this,isUnarmed=this.traits.has("unarmed");this.category=isUnarmed?"unarmed":linkedWeapon?.category??null,this.group=isUnarmed?"brawling":this.linkedWeapon?.group??null,this.baseType=tupleHasValue(["claw","fist","jaws"],this.slug)?this.slug:this.linkedWeapon?.baseType??null}prepareActorData(){if(!this.actor?.isOfType("npc"))return;const damageInstances=Object.values(this.system.damageRolls);for(const instance of Object.values(this.system.damageRolls)){try{instance.damage=new Roll(instance.damage)._formula}catch{const message=`Unable to parse damage formula on NPC attack ${this.name}`;console.warn(`PF2e System | ${message}`),instance.damage="1d4"}const{isElite,isWeak}=this.actor;if((isElite||isWeak)&&damageInstances.indexOf(instance)===0){const adjustment=isElite?2:-2;instance.damage=simplifyFormula(`${instance.damage} + ${adjustment}`)}else instance.damage=new Roll(instance.damage)._formula}}getRollOptions(prefix=this.type){const baseOptions=super.getRollOptions(prefix),{damageType}=this.baseDamage,damageCategory=DamageCategorization.fromDamageType(damageType),rangeIncrement=this.range?.increment,propertyRunes=mapToObj(this.system.runes.property,p=>[`rune:property:${sluggify(p)}`,!0]),otherOptions=Object.entries({equipped:!0,melee:this.isMelee,ranged:this.isRanged,thrown:this.isThrown,[`category:${this.category}`]:!!this.category,[`group:${this.group}`]:!!this.group,[`base:${this.baseType}`]:!!this.baseType,[`range-increment:${rangeIncrement}`]:!!rangeIncrement,[`damage:type:${damageType}`]:!0,[`damage:category:${damageCategory}`]:!!damageCategory,...propertyRunes}).filter(([,isTrue])=>isTrue).map(([key])=>`${prefix}:${key}`);return[baseOptions,otherOptions].flat().sort()}async toMessage(_event,{create=!0}={}){if(!create)return;const strike=this.actor?.system.actions?.find(s=>s.item===this);return strike?game.pf2e.rollActionMacro({itemId:this.id,slug:strike.slug}):void 0}}function setActorShieldData(shield){const{actor}=shield;if(!(shield.isEquipped&&actor.heldShield===shield)||!actor.isOfType("character","npc"))return;const{attributes}=actor.system;if(![shield.id,null].includes(attributes.shield.itemId))return;const{hitPoints}=shield;attributes.shield={itemId:shield.id,name:shield.name,ac:shield.acBonus,hp:hitPoints,hardness:shield.hardness,brokenThreshold:hitPoints.brokenThreshold,raised:shield.isRaised,broken:shield.isBroken,destroyed:shield.isDestroyed,icon:shield.img},actor.rollOptions.all["self:shield:equipped"]=!0,shield.isDestroyed?actor.rollOptions.all["self:shield:destroyed"]=!0:shield.isBroken&&(actor.rollOptions.all["self:shield:broken"]=!0)}__name(setActorShieldData,"setActorShieldData"),__name2(setActorShieldData,"setActorShieldData");class ShieldPF2e extends PhysicalItemPF2e{static{__name(this,"ShieldPF2e")}static{__name2(this,"ShieldPF2e")}isStackableWith(item){return this.isEquipped||item.isEquipped?!1:super.isStackableWith(item)}get baseType(){return this.system.baseItem??null}get isBuckler(){return["buckler","casters-targe","dart-shield","gauntlet-buckler","heavy-rondache","klar"].includes(this.system.baseItem??"")}get isTowerShield(){return["fortress-shield","tower-shield"].includes(this.system.baseItem??"")}get speedPenalty(){return this.system.speedPenalty||0}get acBonus(){return this.system.acBonus}get isSpecific(){return!!this.system.specific}get isRaised(){return!!this.actor?.isOfType("character","npc")&&this.id===this.actor.attributes.shield.itemId&&this.actor.attributes.shield.raised}getRollOptions(prefix="armor"){const reinforcingRune=this.system.runes.reinforcing,reinforcingSlug=[null,"minor","lesser","moderate","greater","major","supreme"][reinforcingRune],reinforcingOptions={[`rune:reinforcing:${reinforcingRune}`]:!!reinforcingRune,[`rune:reinforcing:${reinforcingSlug}`]:!!reinforcingRune},rollOptions=super.getRollOptions(prefix);return rollOptions.push(...Object.entries({[`base:${this.baseType}`]:!!this.baseType,...reinforcingOptions}).filter(e=>!!e[1]).map(e=>`${prefix}:${e[0]}`)),rollOptions}prepareBaseData(){const systemUsage=this.system;systemUsage.usage={value:"held-in-one-hand"},super.prepareBaseData(),"category"in this.system&&(this.type="shield",this.system.runes={reinforcing:0}),this.system.traits.integrated&&(this.system.traits.integrated.runes=foundry.utils.mergeObject({potency:0,striking:0,property:[]},this.system.traits.integrated.runes));const materialData=getMaterialValuationData(this),reinforcingRune=this.system.runes.reinforcing,adjustFromMaterialAndRune=__name2((property,base)=>{const fromMaterial=this.isSpecific?Math.max(base,materialData?.[property]??base):materialData?.[property]??base,additionalFromRune=reinforcingRune?RUNE_DATA.shield.reinforcing[reinforcingRune]?.[property]:null,sumFromRune=fromMaterial+(additionalFromRune?.increase??0);return additionalFromRune&&sumFromRune>additionalFromRune.max?Math.max(fromMaterial,additionalFromRune.max):sumFromRune},"adjustFromMaterialAndRune");this.system.hardness=adjustFromMaterialAndRune("hardness",this.system.hardness),this.system.hp.max=adjustFromMaterialAndRune("maxHP",this.system.hp.max),this.system.hp.brokenThreshold=Math.floor(this.system.hp.max/2);const baseTraits=this.system.traits.value,hasTraditionTraits=baseTraits.some(t=>setHasElement(MAGIC_TRADITIONS,t)),magicTrait=this.system.runes.reinforcing>0&&!hasTraditionTraits?"magical":null;this.system.traits.value=uniq(compact([...baseTraits,magicTrait]).sort()).filter(t=>t in CONFIG.PF2E.shieldTraits);const integratedTrait=this.system.traits.value.find(t=>t.startsWith("integrated"));if(integratedTrait){const isVersatileWeapon=integratedTrait.includes("versatile"),traitParts=integratedTrait.split("-"),damageTypeMap={b:"bludgeoning",p:"piercing",s:"slashing"},mainDamageType=damageTypeMap[traitParts.at(2)??""]??"slashing",versatileDamageType=isVersatileWeapon?damageTypeMap[traitParts.at(-1)??""]:null;this.system.traits.integrated&&versatileDamageType?(this.system.traits.integrated.versatile=foundry.utils.mergeObject({options:[mainDamageType,versatileDamageType],selection:mainDamageType},this.system.traits.integrated.versatile??{}),this.system.traits.integrated.versatile.options):this.system.traits.integrated&&(this.system.traits.integrated.versatile=null),this.system.traits.integrated=foundry.utils.mergeObject({damageType:mainDamageType,runes:{potency:0,striking:0,property:[]},versatile:null},this.system.traits.integrated??{})}else this.system.traits.integrated=null}prepareDerivedData(){super.prepareDerivedData(),this.system.acBonus=this.isBroken||this.isDestroyed?0:this.acBonus}prepareActorData(){const{actor}=this;if(!actor)throw ErrorPF2e("This method may only be called from embedded items");setActorShieldData(this)}onPrepareSynthetics(){super.onPrepareSynthetics(),setActorShieldData(this)}async getChatData(htmlOptions={}){const properties=[`${signedInteger(this.acBonus)} ${game.i18n.localize("PF2E.ArmorArmorLabel")}`,this.speedPenalty?`${this.system.speedPenalty} ${game.i18n.localize("PF2E.ArmorSpeedLabel")}`:null];return this.processChatData(htmlOptions,{...await super.getChatData(),traits:this.traitChatData(CONFIG.PF2E.shieldTraits),properties})}generateUnidentifiedName({typeOnly=!1}={typeOnly:!1}){const base=this.baseType?CONFIG.PF2E.baseShieldTypes[this.baseType]:null,fallback="TYPES.Item.shield",itemType=game.i18n.localize(base??fallback);return typeOnly?itemType:game.i18n.format("PF2E.identification.UnidentifiedItem",{item:itemType})}generateWeapon(){if(this.isStowed)return null;const shieldThrowTrait=this.system.traits.value.find(t=>t.startsWith("shield-throw-")),baseData=foundry.utils.deepClone({...pick(this,["_id","name","img"]),type:"weapon",system:{category:"martial",group:"shield",baseItem:this.baseType,equipped:{...this._source.system.equipped,invested:null},hp:pick(this.system.hp,["value","max"]),material:omit(this.material,["effects"]),traits:{rarity:this.rarity,value:shieldThrowTrait?[`thrown-${shieldThrowTrait.slice(-2)}`]:[],otherTags:[]},damage:{dice:1,die:"d4",damageType:"bludgeoning",modifier:0,persistent:null}}});if(this.system.traits.integrated){const damageType=this.system.traits.integrated.damageType,versatileTrait=this.system.traits.value.find(t=>t.includes("versatile")),versatileWeaponTrait=versatileTrait?.slice(versatileTrait.indexOf("versatile"))??null;objectHasKey(CONFIG.PF2E.weaponTraits,versatileWeaponTrait)&&(baseData.system.traits.value.push(versatileWeaponTrait),baseData.system.traits.toggles={versatile:{selection:this.system.traits.integrated.versatile?.selection??damageType}});const integratedWeaponRunes=this.system.traits.integrated?.runes,additionalData={system:{damage:{dice:1,die:"d6",damageType,modifier:0,persistent:null},runes:integratedWeaponRunes}};(integratedWeaponRunes?.potency||integratedWeaponRunes?.striking)&&(additionalData.name=this._source.name);const combinedData=foundry.utils.mergeObject(baseData,additionalData);return new ItemProxyPF2e(combinedData,{parent:this.parent,shield:this})}return new ItemProxyPF2e(baseData,{parent:this.parent,shield:this})}_preUpdate(changed,options,user){if(!changed.system)return super._preUpdate(changed,options,user);if(changed.system.acBonus!==void 0){const integerValue=Math.floor(Number(changed.system.acBonus))||0;changed.system.acBonus=Math.max(0,integerValue)}if(changed.system.speedPenalty!==void 0){const integerValue=Math.floor(Number(changed.system.speedPenalty))||0;changed.system.speedPenalty=Math.min(0,integerValue)}return this._source.system.traits.value.some(t=>t.startsWith("integrated-"))&&!!changed.system.traits?.value&&Array.isArray(changed.system.traits.value)&&!changed.system.traits.value.some(t=>t.startsWith("integrated-"))&&changed.system?.traits&&(changed.system.traits.integrated=null),super._preUpdate(changed,options,user)}}function createSpellRankLabel(spell,castRank){const typeLabel=spell.isCantrip?game.i18n.localize("PF2E.TraitCantrip"):spell.isFocusSpell?game.i18n.localize("PF2E.TraitFocus"):spell.isRitual?game.i18n.localize("PF2E.Item.Spell.Ritual.Label"):game.i18n.localize("TYPES.Item.spell");return castRank?game.i18n.format("PF2E.ItemLevel",{type:typeLabel,level:castRank}):typeLabel}__name(createSpellRankLabel,"createSpellRankLabel"),__name2(createSpellRankLabel,"createSpellRankLabel");async function createDescriptionPrepend(spell,{includeTraditions}){const traditions=includeTraditions?spell.system.traits.traditions.map(t=>game.i18n.localize(CONFIG.PF2E.magicTraditions[t]).toLocaleLowerCase(game.i18n.lang)).sort((a,b)=>a.localeCompare(b,game.i18n.lang)).join(", "):null,templatePath="systems/pf2e/templates/items/partials/spell-description-prepend.hbs",rendered=(await renderTemplate(templatePath,{spell,traditions})).trim();return rendered?`${rendered}
`:""}__name(createDescriptionPrepend,"createDescriptionPrepend"),__name2(createDescriptionPrepend,"createDescriptionPrepend");class SpellOverlayCollection extends Collection{static{__name(this,"SpellOverlayCollection")}static{__name2(this,"SpellOverlayCollection")}constructor(spell,entries){super(Object.entries(entries??{})),this.spell=spell}get overrideVariants(){return[...this.entries()].reduce((result,[overlayId,data])=>{if(data.overlayType==="override"){const spell=this.spell.loadVariant({overlayIds:[overlayId]});if(spell)return[...result,spell]}return result},[])}getType(overlayId){return this.get(overlayId,{strict:!0}).overlayType}async create(overlayType,options={renderSheet:!1}){const id=foundry.utils.randomID();switch(overlayType){case"override":if(await this.spell.update({[`system.overlays.${id}`]:{_id:id,sort:this.overrideVariants.length+1,overlayType:"override",system:{}}}),options.renderSheet){const variantSpell=this.spell.loadVariant({overlayIds:[id]});variantSpell&&variantSpell.sheet.render(!0)}break}}async updateOverride(variantSpell,data,options){const variantId=variantSpell.variantId;if(!variantId)return null;variantSpell.updateSource(data,options);const variantSource=variantSpell.toObject(),originSource=this.spell.toObject(),difference2=foundry.utils.diffObject(originSource,variantSource);return Object.keys(difference2).length===0||(delete difference2.system?.description,difference2.overlayType="override",await this.spell.update({[`system.overlays.-=${variantId}`]:null},{render:!1}),await this.spell.update({[`system.overlays.${variantId}`]:difference2}),variantSpell.sheet.rendered&&variantSpell.sheet.render(!0)),variantSpell}async deleteOverlay(overlayId){this.verifyOverlayId(overlayId),await this.spell.update({[`system.overlays.-=${overlayId}`]:null}),this.delete(overlayId)}verifyOverlayId(overlayId){if(!this.has(overlayId))throw ErrorPF2e(`Spell ${this.spell.name} (${this.spell.uuid}) does not have an overlay with id: ${overlayId}`)}}class SpellPF2e extends ItemPF2e{static{__name(this,"SpellPF2e")}static{__name2(this,"SpellPF2e")}isFromConsumable;trickMagicEntry=null;constructor(data,context={}){super(data,context),this.isFromConsumable=!!context.fromConsumable}get variantId(){return this.original?this.appliedOverlays?.get("override")??null:null}get baseRank(){return this.system.level.value}get baseLevel(){return this.baseRank}get rank(){if(!this.actor)return this.baseRank;const isAutoHeightened=this.isCantrip||this.isFocusSpell,fixedHeightenedRank=this.system.location.autoHeightenLevel||this.spellcasting?.system?.autoHeightenLevel.value||null;return(isAutoHeightened?fixedHeightenedRank||Math.ceil(this.actor.level/2)||null:this.system.location.heightenedLevel||null)||this.baseRank}get level(){return this.rank}get traits(){return new Set(this.system.traits.value)}get rarity(){return this.system.traits.rarity}get traditions(){return new Set(this.system.traits.traditions)}get actionGlyph(){return this.isRitual?null:getActionGlyph(this.system.time.value)||null}get spellcasting(){const spellcastingId=this.system.location.value;return this.trickMagicEntry?this.trickMagicEntry:this.actor?.spellcasting.get(spellcastingId??"")??null}get isAttack(){return this.traits.has("attack")}get isCantrip(){return this.traits.has("cantrip")&&!this.isRitual}get isFocusSpell(){return this.traits.has("focus")}get isRitual(){return!!this.system.ritual}get attribute(){return this.spellcasting?.attribute??"cha"}get ability(){return foundry.utils.logCompatibilityWarning("`SpellPF2e#ability` is deprecated. Use `SpellPF2e#attribute` instead.",{since:"5.3.0",until:"6.0.0"}),this.attribute}get unlimited(){return this.isCantrip}get isVariant(){return!!this.original}get hasVariants(){return this.overlays.size>0}get area(){if(!this.system.area)return null;const size=Number(this.system.area.value),unit=game.i18n.localize("PF2E.Foot"),shape=game.i18n.localize(CONFIG.PF2E.areaTypes[this.system.area.type]),label=game.i18n.format("PF2E.Item.Spell.Area",{size,unit,shape});return{...this.system.area,label}}get range(){return null}get damageKinds(){return new Set(Object.values(this.system.damage).flatMap(d=>Array.from(d.kinds)))}get uuid(){return this.isVariant?this.original?.uuid??super.uuid:super.uuid}computeCastRank(slotRank){return(this.isCantrip||this.isFocusSpell)&&this.actor?this.rank:Math.max(this.baseRank,slotRank??this.rank)}getRollData(rollOptions={}){const spellLevel=Number(rollOptions?.castLevel)||null,castLevel=Math.max(this.baseRank,spellLevel||this.rank);if(spellLevel&&castLevel!==this.rank)return this.clone({"system.location.heightenedLevel":castLevel}).getRollData();const rollData=super.getRollData();return this.actor?.isOfType("character","npc")&&(rollData.mod=this.actor.abilities[this.attribute].mod),rollData.castLevel=castLevel,rollData.heighten=Math.max(0,castLevel-this.baseRank),rollData}async getDamage(params={skipDialog:!0}){const{spellcasting}=this;if(!Object.keys(this.system.damage).length||!this.actor||!spellcasting?.statistic)return null;const castLevel=this.rank,rollData=this.getRollData({castLevel}),base=[];for(const[id,damage]of Object.entries(this.system.damage??{})){if(!DamageRoll.validate(damage.formula))return console.error(`Failed to parse damage formula "${damage.formula}"`),null;const terms=parseTermsFromSimpleFormula(damage.formula,{rollData}),heightening=this.system.heightening;if(heightening?.type==="interval"&&heightening.interval){const scalingFormula=heightening.damage[id],partCount=Math.floor((castLevel-this.baseRank)/heightening.interval);if(scalingFormula&&partCount>0){const scalingTerms=parseTermsFromSimpleFormula(scalingFormula,{rollData});for(let i=0;i0&&!base.length&&this.actor.isOfType("npc")&&this.actor.attributes.adjustment){const value=this.unlimited?2:4;terms.push({dice:null,modifier:this.actor.isElite?value:-value})}const damageType=damage.type,category=damage.category||null,materials=damage.materials;base.push({terms:combinePartialTerms(terms),damageType,category,materials})}if(!base.length)return null;const{attribute,isAttack}=this,checkStatistic=spellcasting.statistic,spellTraits2=uniq(compact([...this.traits,spellcasting.tradition])),damageKinds=Array.from(this.damageKinds),domains=compact([damageKinds,damageKinds.map(k=>`spell-${k}`),damageKinds.map(k=>`${this.id}-${k}`),isAttack?["attack-damage","attack-spell-damage"]:null,checkStatistic.base?damageKinds.map(k=>`${checkStatistic.base?.slug}-${k}`):null].flat()),contextData=await this.actor.getDamageRollContext({target:isAttack?params.target:null,item:this,statistic:checkStatistic.check,domains,options:new Set(["action:cast-a-spell","self:action:slug:cast-a-spell",...spellTraits2]),checkContext:null,outcome:null,traits:spellTraits2,viewOnly:!isAttack||!params.target}),context={type:"damage-roll",sourceType:isAttack?"attack":"save",outcome:isAttack?"success":null,domains,options:contextData.options,self:contextData.self,target:contextData.target??null,rollMode:params.rollMode,traits:contextData.traits},modifiers=[],damageDice=[],{actor}=contextData.self;if(actor.system.abilities){const attributes=actor.system.abilities,attributeModifiers=Object.entries(this.system.damage).filter(([,d])=>d.applyMod).map(([k,d])=>new ModifierPF2e({label:CONFIG.PF2E.abilities[attribute],slug:`ability-${k}`,type:"untyped",modifier:attributes[attribute].mod,damageType:d.type,damageCategory:d.category||null,adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,domains,`ability-${k}`)})),extractOptions={resolvables:{spell:this,target:contextData.target?.actor??null},test:contextData.options},extracted=processDamageCategoryStacking(base,{modifiers:[attributeModifiers,extractModifiers(actor.synthetics,domains,extractOptions)].flat(),dice:extractDamageDice(actor.synthetics.damageDice,domains,extractOptions),test:contextData.options});modifiers.push(...extracted.modifiers),damageDice.push(...extracted.dice)}const formulaData={base,modifiers,dice:damageDice,ignoredResistances:[],kinds:this.damageKinds};if(!params.skipDialog&&!await new DamageModifierDialog({formulaData,context}).resolve())return null;const{formula,breakdown}=createDamageFormula(formulaData),roll=new DamageRoll(formula);return{template:{name:this.name,damage:{roll,breakdown},materials:Array.from(roll.materials),modifiers},context}}loadVariant(options={}){if(this.original)return this.original.loadVariant(options);const{castLevel,overlayIds}=options,appliedOverlays=new Map,heightenEntries=this.getHeightenLayers(castLevel),overlays=overlayIds?.map(id=>({id,data:this.overlays.get(id,{strict:!0})}))??[],overrides=(()=>{if(!heightenEntries.length&&!overlays.length)return castLevel!==this.rank?foundry.utils.mergeObject(this.toObject(),{system:{location:{heightenedLevel:castLevel}}}):null;let source=this.toObject();if(overlays.map(overlay=>overlay.data.overlayType).filter(type=>type==="override").length>1)throw ErrorPF2e(`Error loading variant of Spell ${this.name} (${this.uuid}). Cannot apply multiple override overlays.`);for(const{id,data}of overlays){switch(data.overlayType){case"override":{delete source.system.overlays,source.system.rules=[],source=foundry.utils.mergeObject(source,data,{overwrite:!0});break}}appliedOverlays.set(data.overlayType,id)}for(const overlay of heightenEntries)foundry.utils.mergeObject(source.system,overlay.system);const currentRank=source.system.location.heightenedLevel??source.system.level.value;return castLevel&&castLevel!==currentRank&&(source.system.location.heightenedLevel=castLevel),source._id=this.id,source})();if(!overrides)return null;const variant=new SpellPF2e(overrides,{parent:this.actor,fromConsumable:this.isFromConsumable});return variant.original=this,variant.appliedOverlays=appliedOverlays,variant.trickMagicEntry=this.trickMagicEntry,variant.system.traits.value=Array.from(variant.traits),processSanctification(variant),variant}getHeightenLayers(rank){const heightening=this.system.heightening;return heightening?.type!=="fixed"?[]:Object.entries(heightening.levels).map(([rank2,system])=>({level:Number(rank2),system})).filter(system=>!rank||rank>=system.level).sort((first,second)=>first.level-second.level)}placeTemplate(message){const templateConversion={burst:"circle",cone:"cone",cube:"rect",emanation:"circle",line:"ray",rect:"rect",square:"rect"},{area}=this.system;if(!area)throw ErrorPF2e("Attempted to create template with non-area spell");const templateType=templateConversion[area.type],templateData={t:templateType,distance:Number(area.value)/5*(canvas.dimensions?.distance??0),fillColor:game.user.color,flags:{pf2e:{messageId:message?.id,origin:{name:this.name,slug:this.slug,traits:foundry.utils.deepClone(this.system.traits.value),...this.getOriginData()},areaType:this.system.area?.type??null}}};switch(templateType){case"ray":templateData.width=CONFIG.MeasuredTemplate.defaults.width*(canvas.dimensions?.distance??1);break;case"cone":templateData.angle=CONFIG.MeasuredTemplate.defaults.angle;break;case"rect":{const distance=templateData.distance??0;templateData.distance=Math.hypot(distance,distance),templateData.width=distance,templateData.direction=45;break}}return canvas.templates.createPreview(templateData)}prepareBaseData(){super.prepareBaseData(),this.system.location.value||=null,this.system.level.value=Math.clamped(this.system.level.value,1,10)||1,this.system.area?.value?(this.system.area.value=Number(this.system.area.value)||5,this.system.area.type||="burst"):this.system.area=null,this.isRitual&&(this.system.damage={},this.system.defense=null,this.system.traits.value=this.system.traits.value.filter(t=>!["attack","cantrip","focus"].includes(t)),this.system.traits.traditions=[],this.system.location.value="rituals"),this.system.traits.value=this.system.traits.value.filter(t=>t in CONFIG.PF2E.spellTraits),this.system.traits.value.includes("attack")&&(this.system.defense=foundry.utils.mergeObject(this.system.defense??{},{passive:{statistic:"ac"},save:this.system.defense?.save??null}));const castTime=this.system.time.value=this.system.time.value.trim();!["","2 to 2 rounds"].includes(castTime)&&!this.isRitual&&!getActionGlyph(castTime)&&(this.system.traits.value.push("exploration"),this.system.traits.value.sort());for(const damage of Object.values(this.system.damage)){if(!isObject$1(damage)||typeof damage.formula!="string"){this.system.damage={},delete this.system.heightening,delete this.system.overlays;break}damage.formula=damage.formula?.trim()||"0",damage.kinds=new Set(damage.kinds??["damage"]),(damage.kinds.size===0||this.system.defense?.save?.statistic)&&damage.kinds.add("damage")}if(this.system.heightening?.type==="fixed")for(const heighten of Object.values(this.system.heightening.levels))for(const partial of compact(Object.values(heighten.damage??{})))partial.formula=partial.formula?.trim()||"0";else if(this.system.heightening?.type==="interval")for(const key of Object.keys(this.system.heightening.damage??{}))this.system.heightening.damage[key]=this.system.heightening.damage[key]?.trim()||"0";this.overlays=new SpellOverlayCollection(this,this.system.overlays)}prepareSiblingData(){this.spellcasting?.isInnate&&foundry.utils.mergeObject(this.system.location,{uses:{value:1,max:1}},{overwrite:!1})}prepareActorData(){if(!this.actor?.isOfType("character"))return;const{traits}=this;traits.has("focus")&&!traits.has("cantrip")&&(this.actor.system.resources.focus.max+=1)}onPrepareSynthetics(){processSanctification(this)}getRollOptions(prefix=this.type){const{spellcasting}=this,spellOptions=new Set(["magical",`${prefix}:rank:${this.rank}`,...this.traits]);spellcasting?.tradition&&spellOptions.add(`${prefix}:trait:${spellcasting.tradition}`),!!(spellcasting?.isPrepared||spellcasting?.isSpontaneous)&&!this.isCantrip&&!this.isFromConsumable&&spellOptions.add(`${prefix}:spell-slot`),this.system.duration.value||spellOptions.add(`${prefix}:duration:0`),this.unlimited||spellOptions.add(`${prefix}:frequency:limited`);for(const damage of Object.values(this.system.damage)){damage.type&&(spellOptions.add(`${prefix}:damage:${damage.type}`),spellOptions.add(`${prefix}:damage:type:${damage.type}`));const category=DamageCategorization.fromDamageType(damage.type);category&&spellOptions.add(`${prefix}:damage:category:${category}`),damage.category==="persistent"&&spellOptions.add(`${prefix}:damage:persistent:${damage.type}`)}const isAreaEffect=!!this.system.area?.value;isAreaEffect&&spellOptions.add("area-effect"),this.damageKinds.has("damage")&&(spellOptions.add("damaging-effect"),isAreaEffect&&spellOptions.add("area-damage"));for(const option of spellcasting?.getRollOptions?.("spellcasting")??[])spellOptions.add(option);const rollOptions=super.getRollOptions(prefix);return rollOptions.push(...spellOptions),rollOptions}async toMessage(event2,{create=!0,data,rollMode}={}){const domData=htmlClosest(event2?.currentTarget,".item")?.dataset,castData=foundry.utils.mergeObject(data??{},domData??{}),castLevel=Number(castData.castLevel??"");if(castLevel&&castLevel!==this.rank)return this.loadVariant({castLevel})?.toMessage(event2,{create,data,rollMode});const message=await super.toMessage(event2,{create:!1,data:castData,rollMode});if(!message)return;const messageSource=message.toObject(),flags=messageSource.flags.pf2e,spellcasting=this.spellcasting;if(spellcasting?.statistic){const tradition=spellcasting.tradition??this.traditions.first()??"arcane";if(flags.casting={id:spellcasting.id,tradition},this.isFromConsumable&&(flags.casting.embeddedSpell=this.toObject()),this.system.defense){const dc=spellcasting.statistic.withRollOptions({item:this}).dc;flags.context={type:"spell-cast",domains:dc.domains,options:[...dc.options],rollMode}}}return create?ChatMessagePF2e.create(messageSource,{renderSheet:!1}):(message.updateSource(messageSource),message)}async getChatData(htmlOptions={},rollOptions={}){if(!this.actor)throw ErrorPF2e(`Cannot retrieve chat data for unowned spell ${this.name}`);const slotRank=Number(rollOptions.slotLevel)||this.rank,castLevel=Number(rollOptions.castLevel)||this.computeCastRank(slotRank);if(!this.isVariant){const variant=this.loadVariant({castLevel});if(variant)return variant.getChatData(htmlOptions,rollOptions)}const variants=this.overlays.overrideVariants.map(variant=>({...pick(variant,["name","actionGlyph","sort"]),overlayIds:[...variant.appliedOverlays.values()]})).sort((a,b)=>a.sort-b.sort),rollData=htmlOptions.rollData??this.getRollData({castLevel});rollData.item??=this;const systemData=this.system,description=await(async()=>{const options={...htmlOptions,rollData},prepend=await createDescriptionPrepend(this,{includeTraditions:!1}),description2=await TextEditor.enrichHTML(this.description,{...options,async:!0});return`${prepend}
${description2}`})(),spellcasting=this.spellcasting;if(!spellcasting)return console.warn(`PF2e System | Orphaned spell ${this.name} (${this.id}) on actor ${this.actor.name} (${this.actor.id})`),{...systemData};const statistic=spellcasting?.statistic;if(!statistic&&!this.isRitual)return console.warn(`PF2e System | Spell ${this.name} is missing a statistic to cast with (${this.id}) on actor ${this.actor.name} (${this.actor.id})`),{...systemData};const statisticChatData=statistic?.getChatData({item:this}),spellDC=statisticChatData?.dc.value,damage=await this.getDamage(),hasDamage=!!damage,saveType=systemData.defense?.save&&tupleHasValue(SAVE_TYPES,systemData.defense.save.statistic)?systemData.defense.save.statistic:null,isSave=!!saveType,saveKey=systemData.defense?.save?.basic?"PF2E.SaveDCLabelBasic":"PF2E.SaveDCLabel",saveLabel=(()=>{if(!(spellDC&&saveType))return null;const localized=game.i18n.format(saveKey,{dc:spellDC,type:game.i18n.localize(CONFIG.PF2E.saves[saveType])}),tempElement=createHTMLElement("div",{innerHTML:localized}),visibility=game.settings.get("pf2e","metagame_showDC")?"all":"owner";return TextEditorPF2e.convertXMLNode(tempElement,"dc",{visibility,whose:null}),tempElement.innerHTML})(),{damageKinds}=this,damageLabel=damageKinds.has("damage")?damageKinds.has("healing")?"PF2E.Damage.Kind.Both.Roll.Verb":"PF2E.Damage.Kind.Damage.Roll.Verb":"PF2E.Damage.Kind.Healing.Roll.Verb",{baseRank}=this,heightened=castLevel-baseRank,rankLabel=createSpellRankLabel(this,castLevel),area=this.area,properties=compact([heightened?game.i18n.format("PF2E.SpellLevelBase",{level:ordinalString(baseRank)}):null,heightened?game.i18n.format("PF2E.SpellLevelHeightened",{heightened}):null]),spellTraits2=this.traitChatData(CONFIG.PF2E.spellTraits,uniq(compact([...this.traits,spellcasting.tradition])));return{...systemData,description:{value:description},isAttack:this.isAttack,isSave,check:this.isAttack&&statisticChatData?statisticChatData.check:void 0,save:{...statisticChatData?.dc??{},type:saveType,label:saveLabel},hasDamage,castLevel,rankLabel,damageLabel,formula:damage?.template.damage.roll.formula,properties,traits:spellTraits2,area,variants,isAura:this.traits.has("aura")}}async rollAttack(event2,attackNumber=1,context={}){const{spellcasting}=this,statistic=spellcasting?.statistic;if(statistic)context.extraRollOptions=uniq(compact(["action:cast-a-spell","self:action:slug:cast-a-spell",context.extraRollOptions].flat())),await statistic.check.roll({...eventToRollParams(event2,{type:"check"}),...context,action:"cast-a-spell",item:this,traits:uniq(compact([...this.traits,spellcasting.tradition])),attackNumber});else throw ErrorPF2e("Spell points to location that is not a spellcasting type")}async rollDamage(event2,mapIncreases){const element=htmlClosest(event2.currentTarget,"*[data-cast-level]"),castLevel=Number(element?.dataset.castLevel)||this.rank;if(!this.isVariant){const variant=this.loadVariant({castLevel});if(variant)return variant.rollDamage(event2)}const targetToken=Array.from(game.user.targets).find(t=>t.actor?.isOfType("creature","hazard","vehicle"))?.document??null,spellDamage=await this.getDamage({target:targetToken,...eventToRollParams(event2,{type:"damage"})});if(!spellDamage)return null;const{template,context}=spellDamage;return typeof mapIncreases=="number"&&(context.mapIncreases=mapIncreases,context.options.add(`map:increases:${mapIncreases}`)),DamagePF2e.roll(template,context)}async rollCounteract(event2){if(event2=event2 instanceof Event?event2:event2?.originalEvent,!this.actor?.isOfType("character","npc"))return null;if(!this.spellcasting?.statistic?.attribute)return console.warn(ErrorPF2e(`Spell ${this.name} (${this.uuid}) is missing a statistic with which to counteract.`).message),null;const localize=localizer("PF2E.Item.Spell.Counteract"),statistic=new Statistic(this.actor,{slug:"counteract",label:localize("Label"),attribute:this.spellcasting.attribute,rank:this.spellcasting.statistic.rank??0}),domain="counteract-check",notes=[new RollNotePF2e({selector:domain,text:localize("Hint")}),...DEGREE_OF_SUCCESS_STRINGS.map(degreeString=>{const counteractRank={criticalFailure:0,failure:this.rank,success:this.rank+1,criticalSuccess:this.rank+3}[degreeString];return new RollNotePF2e({selector:domain,title:`PF2E.Check.Result.Degree.Check.${degreeString}`,text:localize(degreeString,{rank:counteractRank}),outcome:[degreeString]})})],traits=uniq(compact([...this.traits,this.spellcasting.tradition])),{check}=statistic.extend({domains:[domain],rollOptions:traits});return check.roll({...eventToRollParams(event2,{type:"check"}),label:game.i18n.localize("PF2E.Check.Specific.Counteract"),extraRollNotes:notes,traits})}getOriginData(){const flag=super.getOriginData();return flag.castLevel=this.rank,this.isVariant&&this.appliedOverlays&&(flag.variant={overlays:[...this.appliedOverlays.values()]}),flag}async update(data,options={}){return this.original&&this.appliedOverlays.has("override")&&this.sheet.rendered?this.original.overlays.updateOverride(this,data,options):super.update(data,options)}async _preCreate(data,options,user){return this._source.system.location.value||=null,this._source.system.ritual&&(this._source.system.damage={},this._source.system.defense=null,this._source.system.location.value=null,this._source.system.traits.value=this._source.system.traits.value.filter(t=>!["attack","cantrip","focus"].includes(t)),this._source.system.traits.traditions=[]),super._preCreate(data,options,user)}async _preUpdate(changed,options,user){if(!changed.system)return super._preUpdate(changed,options,user);const diff=options.diff??=!0,newLocation=changed.system.location?.value,locationChanged=typeof newLocation=="string"&&newLocation!==this._source.system.location.value;if(diff&&(!this.actor||locationChanged)){const system=changed.system,locationUpdates=system.location=this.actor?system.location??{}:{value:""},keys2=Object.keys(this._source.system.location).filter(k=>k!=="value"&&!(k in locationUpdates));for(const key of keys2)locationUpdates[`-=${key}`]=null}if(changed.system.level){const{level}=changed.system;level.value=Math.clamped(Math.trunc(Number(level.value)||1),1,10)}const systemChanges=compact([changed.system,...Object.values(changed.system.overlays??{}).map(o=>o?.system)]);for(const system of systemChanges){(system.defense?.save??{}).statistic===""&&(system.defense=null);for(const partial of compact(Object.values(system.damage??{})))typeof partial.category=="string"&&(partial.category||=null),(partial.category||partial?.type&&!["vitality","void","untyped"].includes(partial.type))&&(partial.kinds=["damage"]);if(system.heightening&&"levels"in system.heightening)for(const rank of compact(Object.values(system.heightening.levels??{})))for(const partial of Object.values(rank.damage??{}))typeof partial?.category=="string"&&(partial.category||=null);const uses=system?.location?.uses;if(uses){const currentUses=uses.value??this.system.location.uses?.value??1,currentMax=uses.max??this.system.location.uses?.max??1;uses.value=Math.clamped(Number(currentUses),0,Number(currentMax))}}return super._preUpdate(changed,options,user)}}class RitualSpellcasting{static{__name(this,"RitualSpellcasting")}static{__name2(this,"RitualSpellcasting")}actor;spells;constructor(actor,rituals){this.actor=actor,this.spells=new SpellCollection(this);for(const ritual of rituals)this.spells.set(ritual.id,ritual)}get id(){return"rituals"}get name(){return game.i18n.localize("PF2E.Actor.Creature.Spellcasting.Rituals")}get sort(){return Math.max(0,...this.actor.itemTypes.spellcastingEntry.map(e=>e.sort))+10}get category(){return"ritual"}get tradition(){return null}get isFlexible(){return!1}get isFocusPool(){return!1}get isInnate(){return!1}get isPrepared(){return!1}get isRitual(){return!0}get isSpontaneous(){return!1}canCast(spell){return spell.isRitual}async cast(spell,options={}){if(!spell.isRitual)throw ErrorPF2e("Attempted to cast non-ritual from `RitualSpellcasting`");await spell.toMessage(void 0,{rollMode:options.rollMode})}async getSheetData(){return{id:this.id,name:this.name,statistic:null,tradition:null,category:this.category,isRitual:!0,hasCollection:!0,sort:this.sort,usesSpellProficiency:!1,...await this.spells.getSpellData()}}}class SpellCollection extends Collection{static{__name(this,"SpellCollection")}static{__name2(this,"SpellCollection")}entry;actor;constructor(entry){if(!entry.actor)throw ErrorPF2e("a spell collection must have an associated actor");super(),this.entry=entry,this.actor=entry.actor}get id(){return this.entry.id}get highestRank(){const highestSpell=Math.max(...this.map(s=>s.rank)),actorSpellRank=Math.ceil((this.actor?.level??0)/2);return Math.min(10,Math.max(highestSpell,actorSpellRank))}#assertEntryIsDocument(entry){if(!(entry instanceof ItemPF2e))throw ErrorPF2e("`this#entry` is not a `SpellcastingEntryPF2e`")}async addSpell(spell,options={}){const{actor}=this;if(!actor.isOfType("creature"))throw ErrorPF2e("Spellcasting entries can only exist on creatures");const canHeighten=!(spell.isCantrip||spell.isFocusSpell||spell.isRitual)&&(this.entry.isSpontaneous||this.entry.isInnate),heightenedRank=canHeighten?options.slotLevel??spell.rank:spell.baseRank;if(spell.system.location.value===this.id&&spell.rank===heightenedRank)return null;if(spell.isFocusSpell&&!this.entry.isFocusPool){const focusTypeLabel=game.i18n.format("PF2E.SpellFocusLabel");return ui.notifications.warn(game.i18n.format("PF2E.Item.Spell.Warning.WrongSpellType",{spellType:focusTypeLabel})),null}if(spell.baseRank>heightenedRank&&this.id===spell.system.location?.value){const targetRankLabel=game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(heightenedRank)}),baseLabel=game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(spell.baseRank)});ui.notifications.warn(game.i18n.format("PF2E.Item.Spell.Warning.InvalidLevel",{name:spell.name,targetLevel:targetRankLabel,baseLevel:baseLabel}))}const heightenedUpdate=canHeighten&&heightenedRank>=spell.baseRank?{"system.location.heightenedLevel":heightenedRank}:{};if(spell.actor===actor)return spell.update({"system.location.value":this.id,...heightenedUpdate});{const source=spell.clone({"system.location.value":this.id,...heightenedUpdate}).toObject(),created=(await actor.createEmbeddedDocuments("Item",[source])).shift();return created instanceof SpellPF2e?created:null}}async prepareSpell(spell,slotRank,spellSlot){if(this.#assertEntryIsDocument(this.entry),spell.baseRank>slotRank&&!(slotRank===0&&spell.isCantrip)){const targetRankLabel=game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(slotRank)}),baseLabel=game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(spell.baseRank)});return ui.notifications.warn(game.i18n.format("PF2E.Item.Spell.Warning.InvalidLevel",{name:spell.name,targetLevel:targetRankLabel,baseLevel:baseLabel})),this.entry}CONFIG.debug.hooks&&console.debug(`PF2e System | Updating location for spell ${spell.name} to match spellcasting entry ${this.id}`);const key=`system.slots.slot${slotRank}.prepared.${spellSlot}`,updates={[key]:{id:spell.id}},slot=this.entry.system.slots[`slot${slotRank}`].prepared[spellSlot];return slot&&(slot.prepared!==void 0&&(updates[`${key}.-=prepared`]=null),slot.name!==void 0&&(updates[`${key}.-=name`]=null)),this.entry.update(updates)}unprepareSpell(slotRank,spellSlot){this.#assertEntryIsDocument(this.entry),CONFIG.debug.hooks===!0&&console.debug(`PF2e System | Updating spellcasting entry ${this.id} to remove spellslot ${spellSlot} for spell rank ${slotRank}`);const key=`system.slots.slot${slotRank}.prepared.${spellSlot}`;return this.entry.update({[key]:{name:game.i18n.localize("PF2E.SpellSlotEmpty"),id:null,prepared:!1,expended:!1}})}setSlotExpendedState(slotRank,spellSlot,isExpended){this.#assertEntryIsDocument(this.entry);const key=`system.slots.slot${slotRank}.prepared.${spellSlot}.expended`;return this.entry.update({[key]:isExpended})}async getSpellData(){const{actor}=this;if(!actor.isOfType("character","npc"))throw ErrorPF2e("Spellcasting entries can only exist on characters and npcs");if(this.entry instanceof RitualSpellcasting)return this.#getRitualData();this.#assertEntryIsDocument(this.entry);const results=[],spells=this.contents.sort((s1,s2)=>(s1.sort||0)-(s2.sort||0)),signatureSpells=spells.filter(s=>s.system.location.signature),isFlexible=this.entry.isFlexible;if(this.entry.isPrepared&&this.entry instanceof SpellcastingEntryPF2e)for(let rank=0;rank<=this.highestRank;rank++){const data=this.entry.system.slots[`slot${rank}`],active=[];if((this.entry.system.showSlotlessLevels.value||data.max>0)&&(rank===0||!isFlexible)){const maxPrepared=Math.max(data.max,0);active.push(...Array(maxPrepared).fill(null));for(const[key,value]of Object.entries(data.prepared)){const spell=value.id?this.get(value.id):null;spell&&(active[Number(key)]={castLevel:spell.computeCastRank(rank),spell,expended:!!value.expended})}}results.push({label:rank===0?"PF2E.Actor.Creature.Spellcasting.Cantrips":game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(rank)}),level:rank,uses:{value:rank>0&&isFlexible?data.value||0:void 0,max:data.max},isCantrip:rank===0,active})}else if(this.entry.isFocusPool){const cantrips=spells.filter(spell=>spell.isCantrip),leveled=spells.filter(spell=>!spell.isCantrip);if(cantrips.length){const active=cantrips.map(spell=>({spell}));results.push({label:"PF2E.Actor.Creature.Spellcasting.Cantrips",level:0,isCantrip:!0,active})}if(leveled.length){const active=leveled.map(spell=>({spell}));results.push({label:actor.type==="character"?"PF2E.Focus.Spells":"PF2E.Focus.Pool",level:Math.max(1,Math.ceil(actor.level/2)),isCantrip:!1,uses:actor.system.resources.focus??{value:0,max:0},active})}}else{const alwaysShowHeader=!this.entry.isRitual,spellsByLevel=groupBy(spells,spell=>spell.isCantrip?0:spell.rank);for(let rank=0;rank<=this.highestRank;rank++){const data=this.entry.system.slots[`slot${rank}`],spells2=spellsByLevel.get(rank)??[];if(alwaysShowHeader||spells2.length){const uses=this.entry.isSpontaneous&&rank!==0?{value:data.value,max:data.max}:void 0,active=spells2.map(spell=>({spell,expended:this.entry.isInnate&&!spell.system.location.uses?.value,uses:this.entry.isInnate&&!spell.unlimited?spell.system.location.uses:void 0})),hideForSpontaneous=this.entry.isSpontaneous&&uses?.max===0&&active.length===0,hideForInnate=this.entry.isInnate&&active.length===0;if(!this.entry.system.showSlotlessLevels.value&&(hideForSpontaneous||hideForInnate))continue;results.push({label:rank===0?"PF2E.Actor.Creature.Spellcasting.Cantrips":game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(rank)}),level:rank,isCantrip:rank===0,uses,active})}}}if(this.entry.isSpontaneous||isFlexible){for(const spell of signatureSpells)for(const result of results){if(spell.baseRank>result.level||!this.entry.system.showSlotlessLevels.value&&result.uses?.max===0)continue;const existing=result.active.find(a=>a?.spell.id===spell.id);if(existing)existing.signature=!0;else if(result.uses?.max){const castLevel=result.level;result.active.push({spell,castLevel,signature:!0,virtual:!0})}}for(const result of results)if(result.level>0&&result.uses?.value===0&&result.uses.max>0)for(const slot of result.active)slot&&(slot.expended=!0)}const flexibleAvailable=(()=>{if(!isFlexible)return null;const totalSlots=results.filter(result=>!result.isCantrip).map(rank=>rank.uses?.max||0).reduce((first,second)=>first+second,0);return{value:signatureSpells.length,max:totalSlots}})();return{levels:results,flexibleAvailable,spellPrepList:this.getSpellPrepList(spells)}}async#getRitualData(){const groupedByRank=groupBy(Array.from(this.values()),s=>s.rank);return{levels:Array.from(groupedByRank.entries()).sort(([a],[b])=>a-b).map(([rank,spells])=>({label:game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(rank)}),level:rank,isCantrip:!1,active:spells.map(spell=>({spell}))})),spellPrepList:null}}getSpellPrepList(spells){if(!this.entry.isPrepared)return{};const spellPrepList={},spellsByRank=groupBy(spells,spell=>spell.isCantrip?0:spell.baseRank);for(let rank=0;rank<=this.highestRank;rank++)spellPrepList[rank]=spellsByRank.get(rank)?.map(spell=>({spell,signature:this.entry.isFlexible&&spell.system.location.signature}))??[];return Object.values(spellPrepList).some(s=>!!s.length)?spellPrepList:null}}class SpellcastingEntryPF2e extends ItemPF2e{static{__name(this,"SpellcastingEntryPF2e")}static{__name2(this,"SpellcastingEntryPF2e")}get attribute(){return this.system.ability.value||"cha"}get ability(){return foundry.utils.logCompatibilityWarning("`SpellcastingEntryPF2e#ability` is deprecated. Use `SpellcastingEntryPF2e#attribute` instead.",{since:"5.3.0",until:"6.0.0"}),this.attribute}get tradition(){const defaultTradition=this.system.prepared.value==="items"?null:"arcane",tradition=this.system.tradition.value;return setHasElement(MAGIC_TRADITIONS,tradition)?tradition:defaultTradition}get category(){return this.system.prepared.value}get rank(){return this.system.proficiency.value??0}get isPrepared(){return this.system.prepared.value==="prepared"}get isFlexible(){return this.isPrepared&&!!this.system.prepared.flexible}get isSpontaneous(){return this.system.prepared.value==="spontaneous"}get isInnate(){return this.system.prepared.value==="innate"}get isFocusPool(){return this.system.prepared.value==="focus"}get isRitual(){return!1}get highestLevel(){return this.spells?.highestRank??0}get showSlotlessLevels(){return this.system.showSlotlessLevels.value}prepareBaseData(){super.prepareBaseData(),this.system.proficiency.value=Math.max(1,this.system.proficiency.value),this.system.prepared.flexible??=!1,this.system.prepared.validItems||=null,this.actor&&(this.statistic=new Statistic(this.actor,{slug:this.slug??sluggify(this.name),label:"PF2E.Actor.Creature.Spellcasting.InvalidProficiency",check:{type:"check"}}))}prepareSiblingData(){if(!this.actor||this.system.prepared.value==="items")this.spells=null;else{this.spells=new SpellCollection(this);const spells=this.actor.itemTypes.spell.filter(i=>i.system.location.value===this.id);for(const spell of spells)this.spells.set(spell.id,spell);this.actor.spellcasting.collections.set(this.spells.id,this.spells)}}prepareActorData(){const actor=this.parent;if(!this.system.proficiency.slug&&!this.isInnate&&actor.isOfType("character")){const spellProficiency=actor.system.proficiencies.spellcasting;spellProficiency.rank=Math.clamped(Math.max(spellProficiency.rank,this.system.proficiency.value),1,4)}}prepareStatistic(){const actor=this.actor;if(!actor)return;const{attribute,tradition}=this,slug=this.slug??sluggify(`${this.name}-spellcasting`),baseDomains=["all",`${attribute}-based`,"spell-attack-dc"],checkDomains=[`${tradition}-spell-attack`,"spell-attack","spell-attack-roll","attack","attack-roll"],dcDomains=[`${tradition}-spell-dc`,"spell-dc"];if(actor.isOfType("character")){const baseStat=actor.getStatistic(this.system.proficiency.slug||"base-spellcasting");if(!baseStat)return;this.system.ability.value=baseStat.attribute??this.system.ability.value,this.system.proficiency.value=Math.max(this.rank,baseStat.rank??0),this.statistic=baseStat.extend({slug,label:baseStat.slug==="base-spellcasting"&&tradition?CONFIG.PF2E.magicTraditions[tradition]:baseStat.label,attribute:this.attribute,rank:this.rank,rollOptions:this.getRollOptions("spellcasting"),domains:baseDomains,check:{type:"attack-roll",domains:checkDomains},dc:{domains:dcDomains}})}else if(actor.isOfType("npc")){const adjustment=actor.isElite?2:actor.isWeak?-2:0,baseMod=Number(this.system?.spelldc?.value??0)+adjustment,baseDC=Number(this.system?.spelldc?.dc??0)+adjustment;this.statistic=new Statistic(actor,{slug,attribute:this.attribute,label:CONFIG.PF2E.magicTraditions[tradition??"arcane"],domains:baseDomains,rollOptions:this.getRollOptions("spellcasting"),check:{type:"attack-roll",domains:checkDomains,modifiers:[new ModifierPF2e("PF2E.ModifierTitle",baseMod,"untyped")]},dc:{domains:dcDomains,modifiers:[new ModifierPF2e("PF2E.ModifierTitle",baseDC-10,"untyped")]}})}else throw ErrorPF2e(`Actor type ${actor.type} does not support spellcasting entries`);const stat=actor.isOfType("npc")?{value:this.statistic.dc.value}:{value:this.statistic.dc.value,rank:this.statistic.rank??0},attributes=actor.system.attributes;stat.value>attributes.classOrSpellDC.value&&(attributes.classOrSpellDC=stat),(!attributes.spellDC||stat.value>attributes.spellDC.value)&&(attributes.spellDC=stat)}getLinkedItems(){return this.actor?.itemTypes.spell.filter(i=>i.system.location.value===this.id)??[]}canCast(spell,{origin}={}){if(this.system.prepared.value==="items")return origin?this.system.prepared.validItems==="scroll"?origin.traits.has("scroll"):!0:!1;const isSpellcastingFeature=this.isPrepared||this.isSpontaneous;if(origin&&!isSpellcastingFeature||!this.spells)return!1;const matchesTradition=this.tradition&&spell.traditions.has(this.tradition),isInSpellList=this.spells.some(s=>s.slug===spell.slug);return matchesTradition||isInSpellList}async cast(spell,options={}){const consume=options.consume??!0,message=options.message??!0,slotRank=options.level??spell.rank,valid=!consume||spell.isCantrip||await this.consume(spell,slotRank,options.slot);if(message&&valid){const castRank=spell.computeCastRank(slotRank);await spell.toMessage(void 0,{rollMode:options.rollMode,data:{castLevel:castRank}})}}async consume(spell,rank,slot){const actor=this.actor;if(!actor?.isOfType("character","npc"))throw ErrorPF2e("Spellcasting entries require an actor");if(this.isRitual)return!0;if(spell.isVariant&&(spell=spell.original),this.isFocusPool&&actor.isOfType("character","npc")){const currentPoints=actor.system.resources.focus?.value??0;return currentPoints>0?(await actor.update({"system.resources.focus.value":currentPoints-1}),!0):(ui.notifications.warn(game.i18n.localize("PF2E.Focus.NotEnoughFocusPointsError")),!1)}const rankLabel=game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(rank)}),slotKey=goesToEleven(rank)?`slot${rank}`:"slot0";if(this.system.slots===null||!this.spells)return!1;if(this.isPrepared&&!this.isFlexible){const preparedData=this.system.slots[slotKey].prepared;if(slot??=Number(Object.entries(preparedData).filter(([_,slot2])=>slot2.id===spell.id&&!slot2.expended).at(0)?.[0]),!Number.isInteger(slot))throw ErrorPF2e("Slot not given for prepared spell, and no alternative slot was found");return preparedData[slot].expended??!1?(ui.notifications.warn(game.i18n.format("PF2E.SpellSlotExpendedError",{name:spell.name})),!1):(await this.spells.setSlotExpendedState(rank,slot,!0),!0)}if(this.isInnate){const remainingUses=spell.system.location.uses?.value||0;return remainingUses<=0?(ui.notifications.warn(game.i18n.format("PF2E.SpellSlotExpendedError",{name:spell.name})),!1):(await spell.update({"system.location.uses.value":remainingUses-1}),!0)}const slots=this.system.slots[slotKey];return slots.value>0?(await this.update({[`system.slots.${slotKey}.value`]:slots.value-1}),!0):(ui.notifications.warn(game.i18n.format("PF2E.SpellSlotNotEnoughError",{name:spell.name,level:rankLabel})),!1)}async addSpell(spell,options){return this.spells?.addSpell(spell,options)??null}async prepareSpell(spell,slotRank,spellSlot){return this.spells?.prepareSpell(spell,slotRank,spellSlot)??null}async unprepareSpell(spellLevel,slotRank){return this.spells?.unprepareSpell(spellLevel,slotRank)??null}async setSlotExpendedState(slotRank,spellSlot,isExpended){return this.spells?.setSlotExpendedState(slotRank,spellSlot,isExpended)??null}async getSheetData(){if(!this.actor?.isOfType("character","npc"))throw ErrorPF2e("Spellcasting entries can only exist on characters and npcs");const spellCollectionData=await this.spells?.getSpellData()??{levels:[],spellPrepList:null};return{id:this.id,name:this.name,sort:this.sort,attribute:this.attribute,statistic:this.statistic.getChatData(),tradition:this.tradition,category:this.system.prepared.value,isPrepared:this.isPrepared,isSpontaneous:this.isSpontaneous,isFlexible:this.isFlexible,isInnate:this.isInnate,isFocusPool:this.isFocusPool,isRitual:this.isRitual,hasCollection:!!this.spells,usesSpellProficiency:!this.system.proficiency.slug,showSlotlessLevels:this.showSlotlessLevels,...spellCollectionData}}getRollOptions(prefix="spellcasting"){return[`${prefix}:${this.attribute}`,`${prefix}:${this.tradition}`,`${prefix}:${this.system.prepared.value}`]}async _preUpdate(changed,options,user){if(changed.system?.slots)for(const key of[0,1,2,3,4,5,6,7,8,9,10]){const slotKey=`slot${key}`,slotData=changed.system.slots[slotKey];if(slotData&&("max"in slotData&&(slotData.max=Math.max(Number(slotData.max)||0,0)),"value"in slotData)){const max="max"in slotData?Number(slotData?.max)||0:this.system.slots[slotKey].max;slotData.value=Math.clamped(Number(slotData.value),0,max)}}return super._preUpdate(changed,options,user)}getSpellData(){return this.getSheetData()}}const createDisintegrateEffect=__name2(()=>({_id:null,type:"effect",name:game.i18n.localize("PF2E.Item.Effect.Disintegrated.Name"),img:"systems/pf2e/icons/effects/fine-powder.svg",system:{slug:"effect-fine-powder",description:{value:game.i18n.localize("PF2E.Item.Effect.Disintegrated.Description")},rules:[{key:"TokenImage",value:"systems/pf2e/icons/effects/fine-powder.svg"}],tokenIcon:{show:!1}}}),"createDisintegrateEffect");function applyIWR(actor,roll,rollOptions){if(actor.isDead)return{finalDamage:0,applications:[],persistent:[]};if(!game.pf2e.settings.iwr)return{finalDamage:roll.total,applications:[],persistent:roll.instances.filter(i=>i.persistent&&!i.options.evaluatePersistent)};const{immunities,weaknesses,resistances}=actor.attributes,instances=roll.instances,persistent=[],ignoredResistances=(roll.options.ignoredResistances??[]).map(ir=>new Resistance({type:ir.type,value:ir.max??1/0})),nonDamageWeaknesses=weaknesses.filter(w=>NON_DAMAGE_WEAKNESSES.has(w.type)&&instances.some(i=>w.test([...i.formalDescription,...rollOptions]))),damageWeaknesses=weaknesses.filter(w=>!nonDamageWeaknesses.includes(w)),applications=instances.flatMap(instance=>{const formalDescription=new Set([...instance.formalDescription,...rollOptions]),wasIncreased=instance.total<=0&&typeof roll.options.increasedFrom=="number",isFirst=instances.indexOf(instance)===0,instanceTotal=wasIncreased&&isFirst?1:Math.max(instance.total,0);if(!actor.isAffectedBy(instance.type))return[{category:"unaffected",type:instance.type,adjustment:-1*instanceTotal}];const immunity=immunities.find(i=>i.test(formalDescription));if(immunity)return[{category:"immunity",type:immunity.label,adjustment:-1*instanceTotal}];const critImmunity=immunities.find(i=>i.type==="critical-hits"),critImmuneTotal=roll.options.degreeOfSuccess===DEGREE_OF_SUCCESS.CRITICAL_SUCCESS?instance.critImmuneTotal:instanceTotal,instanceApplications=[],critImmunityApplies=critImmunity&&critImmuneTotali.type==="precision"),precisionDamage=Math.min(instance.componentTotal("precision"),critImmuneTotal);if(precisionDamage>0&&precisionImmunity?.test([...formalDescription,"damage:component:precision"])){const adjustedPrecisionDamage=critImmunityApplies?Math.floor(precisionDamage/2):precisionDamage,adjustment2=-1*Math.min(critImmuneTotal,adjustedPrecisionDamage);instanceApplications.push({category:"immunity",type:precisionImmunity.applicationLabel,adjustment:adjustment2})}const afterImmunities=Math.max(instanceTotal+instanceApplications.reduce((sum,a)=>sum+a.adjustment,0),0);if(instance.persistent&&!instance.options.evaluatePersistent&&persistent.push(instance),afterImmunities===0)return instanceApplications;const mainWeaknesses=damageWeaknesses.filter(w=>w.test(formalDescription)),splashWeakness=instance.componentTotal("splash")?weaknesses.find(w=>w.type==="splash-damage")??null:null,precisionWeakness=precisionDamage>0?weaknesses.find(r=>r.type==="precision"):null,highestWeakness=compact([...mainWeaknesses,precisionWeakness,splashWeakness]).reduce((highest,w)=>w&&!highest||w&&highest&&w.value>highest.value?w:highest,null);highestWeakness&&instanceApplications.push({category:"weakness",type:highestWeakness.applicationLabel,adjustment:highestWeakness.value});const afterWeaknesses=afterImmunities+(highestWeakness?.value??0),applicableResistances=resistances.filter(r=>r.test(formalDescription)).map(r=>({label:r.applicationLabel,value:r.getDoubledValue(formalDescription),ignored:ignoredResistances.some(ir=>ir.test(formalDescription))})),criticalResistance=resistances.find(r=>r.type==="critical-hits");criticalResistance&&critImmuneTotalir.test(formalDescription))});const precisionResistance=(()=>{const resistance=precisionDamage>0?resistances.find(r=>r.type==="precision"):null;return resistance?{label:resistance.applicationLabel,value:Math.min(resistance.value,precisionDamage),ignored:!1}:null})();precisionResistance&&applicableResistances.push(precisionResistance);const highestResistance=applicableResistances.filter(r=>!r.ignored).reduce((highest,r)=>r&&!highest||r&&highest&&r.value>highest.value?r:highest,null),highestIgnored=applicableResistances.filter(r=>r.ignored).reduce((highest,r)=>r&&!highest||r&&highest&&r.value>highest.value?r:highest,null);return highestResistance?.value?instanceApplications.push({category:"resistance",type:highestResistance.label,adjustment:-1*Math.min(afterWeaknesses,highestResistance.value),ignored:!1}):highestIgnored&&instanceApplications.push({category:"resistance",type:ignoredResistances.find(ir=>ir.test(formalDescription))?.typeLabel??"???",adjustment:0,ignored:!0}),instanceApplications}).concat(...nonDamageWeaknesses.map(w=>({category:"weakness",type:w.typeLabel,adjustment:w.value}))).sort((a,b)=>{if(a.category===b.category)return 0;switch(a.category){case"unaffected":return-1;case"immunity":return b.type==="unaffected"?1:-1;case"weakness":return["unaffected","immunity"].includes(b.category)?1:-1;default:return 1}}),adjustment=applications.reduce((sum,a)=>sum+a.adjustment,0);return{finalDamage:Math.max(roll.total+adjustment,0),applications,persistent}}__name(applyIWR,"applyIWR"),__name2(applyIWR,"applyIWR");class ActorConditions extends DelegatedCollection{static{__name(this,"ActorConditions")}static{__name2(this,"ActorConditions")}#slugMap=new Collection;get active(){return this.filter(c=>c.active)}get stored(){return this.filter(c=>!c.inMemoryOnly)}get clumsy(){return this.bySlug("clumsy",{active:!0}).shift()??null}get doomed(){return this.bySlug("doomed",{active:!0}).shift()??null}get drained(){return this.bySlug("drained",{active:!0}).shift()??null}get dying(){return this.bySlug("dying",{active:!0}).shift()??null}get enfeebled(){return this.bySlug("enfeebled",{active:!0}).shift()??null}get frightened(){return this.bySlug("frightened",{active:!0}).shift()??null}get sickened(){return this.bySlug("sickened",{active:!0}).shift()??null}get slowed(){return this.bySlug("slowed",{active:!0}).shift()??null}get stunned(){return this.bySlug("stunned",{active:!0}).shift()??null}get stupefied(){return this.bySlug("stupefied",{active:!0}).shift()??null}get wounded(){return this.bySlug("wounded",{active:!0}).shift()??null}get(key,{strict=!1,active=null,temporary=null}={}){const condition=super.get(key,{strict});if(!(active===!0&&!condition?.active)&&!(active===!1&&condition?.active)&&!(temporary===!0&&condition?.actor.items.has(key))&&!(temporary===!1&&!condition?.actor.items.has(key)))return condition}set(id,condition){super.set(id,condition);const listBySlug=this.#slugMap.get(condition.slug)??[];return listBySlug.push(condition),this.#slugMap.set(condition.slug,listBySlug),this}every(condition){return this.contents.every(condition)}flatMap(transformer){return this.contents.flatMap(transformer)}delete(){return!1}bySlug(slug,{active=null,temporary=null}={}){return(this.#slugMap.get(slug)??[]).filter(condition=>{const activeFilterSatisfied=active===!0?condition.active:active===!1?!condition.active:!0,temporaryFilterSatisfied=temporary===!0?!condition.actor.items.has(condition.id):temporary===!1?condition.actor.items.has(condition.id):!0;return activeFilterSatisfied&&temporaryFilterSatisfied})}}var VisionLevels=(VisionLevels2=>(VisionLevels2[VisionLevels2.BLINDED=0]="BLINDED",VisionLevels2[VisionLevels2.NORMAL=1]="NORMAL",VisionLevels2[VisionLevels2.LOWLIGHT=2]="LOWLIGHT",VisionLevels2[VisionLevels2.DARKVISION=3]="DARKVISION",VisionLevels2))(VisionLevels||{});class ItemTransfer{static{__name(this,"ItemTransfer")}static{__name2(this,"ItemTransfer")}constructor(source,target,quantity,containerId){this.source=source,this.target=target,this.quantity=quantity,this.containerId=containerId}#templatePaths={flavor:"./systems/pf2e/templates/chat/action/flavor.hbs",content:"./systems/pf2e/templates/chat/action/content.hbs"};async request(){const gamemaster=game.users.find(u=>u.isGM&&u.active);if(!gamemaster){const source=this.#getSource(),target=this.#getTarget(),loot=[source,target].find(a=>a?.isLootableBy(game.user)&&!a.isOwner);if(!loot)throw ErrorPF2e("Unexpected missing actor");ui.notifications.error(game.i18n.format("PF2E.loot.GMSupervisionError",{loot:ItemTransfer.#tokenName(loot)}));return}console.debug(`PF2e System | Requesting item transfer from GM ${gamemaster.name}`),game.socket.emit("system.pf2e",{request:"itemTransfer",data:this})}async enact(requester){if(!game.user.isGM)throw ErrorPF2e("Unauthorized item transfer");console.debug("PF2e System | Enacting item transfer");const sourceActor=this.#getSource(),sourceItem=sourceActor?.inventory.find(i=>i.id===this.source.itemId),targetActor=this.#getTarget();if(!(sourceActor?.isLootableBy(game.user)&&sourceItem&&targetActor?.isLootableBy(game.user)))throw ErrorPF2e("Failed sanity check during item transfer");const targetItem=await sourceActor.transferItemToActor(targetActor,sourceItem,this.quantity,this.containerId),sourceIsLoot=sourceActor.isOfType("loot")&&sourceActor.system.lootSheetType==="Loot";!sourceItem&&sourceIsLoot||this.#sendMessage(requester,sourceActor,targetActor,targetItem)}#getActor(tokenId,actorId){return typeof tokenId=="string"?canvas.tokens.placeables.find(t=>t.id===tokenId)?.actor??null:game.actors.get(actorId)??null}#getSource(){return this.#getActor(this.source.tokenId,this.source.actorId)}#getTarget(){return this.#getActor(this.target.tokenId,this.target.actorId)}static#tokenName(document2){return"items"in document2?document2.isOfType("party")?game.i18n.localize("PF2E.loot.PartyStash"):document2.token?document2.token.name:document2.prototypeToken?.name??document2.name:document2.character?canvas.tokens.placeables.find(t=>t.actor?.id===document2.id)?.name??document2.character?.name:document2.name}async#sendMessage(requester,sourceActor,targetActor,item){const localize=localizer("PF2E.loot");if(!item)if(sourceActor.isOfType("loot")&&sourceActor.system.lootSheetType==="Merchant"){const message=localize("InsufficientFundsMessage"),content2=await renderTemplate(this.#templatePaths.content,{imgPath:targetActor.img,message:game.i18n.format(message,{buyer:targetActor.name})}),flavor2=await this.#messageFlavor(sourceActor,targetActor,localize("BuySubtitle"));await ChatMessage.create({user:requester.id,speaker:{alias:ItemTransfer.#tokenName(targetActor)},type:CONST.CHAT_MESSAGE_TYPES.EMOTE,flavor:flavor2,content:content2});return}else throw ErrorPF2e("Unexpected item-transfer failure");const[speaker,subtitle,formatArgs]=(()=>{const isMerchant=__name2(actor=>actor.isOfType("loot")&&actor.isMerchant,"isMerchant"),isWhat=__name2(actor=>({isCharacter:actor.testUserPermission(requester,"OWNER")&&actor.isOfType("character"),isMerchant:isMerchant(actor),isNPC:actor.isOfType("npc")&&actor.isLootableBy(requester)&&!actor.testUserPermission(requester,"OWNER"),isLoot:(actor.isOfType("party")||actor.isOfType("loot"))&&actor.isLootableBy(requester)&&!actor.testUserPermission(requester,"OWNER")&&!isMerchant(actor)}),"isWhat"),source=isWhat(sourceActor),target=isWhat(targetActor);if(source.isCharacter&&target.isLoot)return[ItemTransfer.#tokenName(sourceActor),localize("DepositSubtitle"),[localize("DepositMessage"),{depositor:ItemTransfer.#tokenName(sourceActor),container:ItemTransfer.#tokenName(targetActor)}]];if(source.isCharacter&&target.isMerchant)return[ItemTransfer.#tokenName(sourceActor),localize("GiveSubtitle"),[localize("GiveMessage"),{giver:ItemTransfer.#tokenName(sourceActor),recipient:ItemTransfer.#tokenName(targetActor)}]];if(source.isCharacter&&target.isNPC)return[ItemTransfer.#tokenName(sourceActor),localize("PlantSubtitle"),[localize("PlantMessage"),{planter:ItemTransfer.#tokenName(sourceActor),corpse:ItemTransfer.#tokenName(targetActor)}]];if(source.isLoot&&target.isCharacter)return[ItemTransfer.#tokenName(targetActor),localize("TakeSubtitle"),[localize("TakeMessage"),{taker:ItemTransfer.#tokenName(targetActor),container:ItemTransfer.#tokenName(sourceActor)}]];if(source.isNPC&&target.isCharacter)return[ItemTransfer.#tokenName(targetActor),localize("LootSubtitle"),[localize("LootMessage"),{looter:ItemTransfer.#tokenName(targetActor),corpse:ItemTransfer.#tokenName(sourceActor)}]];if([source,target].every(actor=>actor.isLoot||actor.isNPC))return[requester.character?.name??requester.name,localize("TransferSubtitle"),[localize("TransferMessage"),{transferrer:requester.character?.name??requester.name,fromContainer:ItemTransfer.#tokenName(sourceActor),toContainer:ItemTransfer.#tokenName(targetActor)}]];if(source.isLoot&&target.isMerchant)return[requester.character?.name??requester.name,localize("GiveSubtitle"),[localize("GiveMessage"),{seller:requester.character?.name??requester.name,buyer:ItemTransfer.#tokenName(targetActor)}]];if(source.isMerchant&&target.isCharacter)return[ItemTransfer.#tokenName(sourceActor),localize("SellSubtitle"),[localize("SellMessage"),{seller:ItemTransfer.#tokenName(sourceActor),buyer:ItemTransfer.#tokenName(targetActor)}]];if(source.isMerchant&&target.isLoot)return[requester.character?.name??requester.name,localize("SellSubtitle"),[localize("SellMessage"),{seller:ItemTransfer.#tokenName(sourceActor),buyer:requester.character?.name??requester.name}]];throw ErrorPF2e("Unexpected item-transfer failure")})(),formatProperties=formatArgs[1];if(!formatProperties)throw ErrorPF2e("Unexpected item-transfer failure");formatProperties.quantity=this.quantity,formatProperties.item=item.name;const content=await renderTemplate(this.#templatePaths.content,{imgPath:item.img,message:game.i18n.format(...formatArgs).replace(/\b1 × /,"")}),flavor=await this.#messageFlavor(sourceActor,targetActor,subtitle);await ChatMessage.create({user:requester.id,speaker:{alias:speaker},type:CONST.CHAT_MESSAGE_TYPES.EMOTE,flavor,content})}async#messageFlavor(sourceActor,targetActor,subtitle){const glyph=getActionGlyph(sourceActor.isOfType("loot")&&targetActor.isOfType("loot")?2:1),action2={title:"PF2E.Actions.Interact.Title",subtitle,glyph},traits=[{name:"manipulate",label:CONFIG.PF2E.featTraits.manipulate,description:CONFIG.PF2E.traitsDescriptions.manipulate}];return await renderTemplate(this.#templatePaths.flavor,{action:action2,traits})}}class ActorSpellcasting extends DelegatedCollection{static{__name(this,"ActorSpellcasting")}static{__name2(this,"ActorSpellcasting")}constructor(actor,entries){super(entries.map(entry=>[entry.id,entry])),this.actor=actor;for(const entry of entries)entry.spells&&this.collections.set(entry.spells.id,entry.spells)}collections=new Collection;get regular(){return this.filter(e=>e instanceof SpellcastingEntryPF2e)}get ritual(){const ritualCasting=this.collections.get("rituals")?.entry;return ritualCasting instanceof RitualSpellcasting?ritualCasting:null}get spellcastingFeatures(){return this.regular.filter(e=>e.isPrepared||e.isSpontaneous)}canCastConsumable(item){const spell=item.embeddedSpell;return!!spell&&this.some(e=>e.canCast(spell,{origin:item}))}refocus(options={}){if(!options.all)throw ErrorPF2e("Actors do not currently support regular refocusing");if(this.actor.isOfType("character","npc")){const focus=this.actor.system.resources.focus,rechargeFocus=focus?.max&&focus.value{if(!(entry instanceof SpellcastingEntryPF2e))return[];if(entry.isFocusPool||!entry.spells)return[];if(entry.isInnate)return entry.spells.map(spell=>{const value=spell.system.location.uses?.max??1;return{_id:spell.id,"system.location.uses.value":value}});const slots=entry.system.slots;let updated=!1;for(const slot of Object.values(slots))if(entry.isPrepared&&!entry.isFlexible)for(const preparedSpell of Object.values(slot.prepared))preparedSpell.expended&&(preparedSpell.expended=!1,updated=!0);else slot.valueu.active),primaryPlayer=this.isToken?null:activeUsers.find(u=>u.character?.id===this.id);return primaryPlayer||(game.users.filter(u=>this.canUserModify(u,"update")).sort((a,b)=>a.id>b.id?1:-1).shift()??null)}get abilities(){return null}get attributes(){return this.system.attributes}get hitPoints(){const{hp}=this.system.attributes;return hp?{value:hp.value,max:hp.max,temp:hp.temp,unrecoverable:hp.unrecoverable,negativeHealing:hp.negativeHealing}:null}get traits(){return new Set(this.system.traits?.value??[])}get level(){return this.system.details.level.value}get size(){return this.system.traits?.size.value??"med"}get dimensions(){const size=this.system.traits?.size??new ActorSizePF2e({value:"med"});return{length:size.length,width:size.width,height:Math.min(size.length,size.width)}}get canSee(){return!0}get canAct(){return!0}get canAttack(){return!1}get isDead(){const deathIcon=game.settings.get("pf2e","deathIcon");if(this.token)return this.token.overlayEffect===deathIcon;const tokens=this.getActiveTokens(!0,!0);return tokens.length>0&&tokens.every(t=>t.overlayEffect===deathIcon)}get modeOfBeing(){const{traits}=this,isPC=isReallyPC(this);return traits.has("undead")&&!traits.has("eidolon")?"undead":traits.has("construct")&&!isPC&&!traits.has("eidolon")?"construct":"living"}get visionLevel(){return VisionLevels.NORMAL}get emitsSound(){return!1}get rollOptions(){return this.flags.pf2e.rollOptions}get heldShield(){return null}get hardness(){return 0}get canHostRuleElements(){return!0}get alliance(){return this.system.details.alliance}get combatant(){return game.combat?.combatants.find(c=>c.actor?.uuid===this.uuid)??null}get temporaryEffects(){const fromConditions=this.conditions.active.map(c=>new TokenEffect(c)),fromEffects=this.itemTypes.effect.filter(e=>e.system.tokenIcon?.show&&(e.isIdentified||game.user.isGM)).map(e=>new TokenEffect(e));return[super.temporaryEffects,fromConditions,fromEffects,this.synthetics.tokenEffectIcons].flat()}isOfType(...types){return types.some(t=>t==="creature"?tupleHasValue(CREATURE_ACTOR_TYPES,this.type):this.type===t)}isAllyOf(actor){return this.alliance!==null&&this!==actor&&this.alliance===actor.alliance}isEnemyOf(actor){return this.alliance!==null&&actor.alliance!==null&&this.alliance!==actor.alliance}isImmuneTo(effect){if(!game.pf2e.settings.iwr)return!1;const item=typeof effect=="string"?null:"parent"in effect?effect:new ItemProxyPF2e(effect),statements=new Set(item?item.getRollOptions("item"):["item:type:condition",`item:slug:${effect}`]);return this.attributes.immunities.some(i=>i.test(statements))}isAffectedBy(damage){const damageType=objectHasKey(CONFIG.PF2E.damageTypes,damage)?damage:damage.isOfType("condition")?damage.system.persistent?.damageType??null:null;if(!setHasElement(UNAFFECTED_TYPES,damageType))return!0;const{traits}=this;return{good:traits.has("evil"),evil:traits.has("good"),lawful:traits.has("chaotic"),chaotic:traits.has("lawful"),vitality:!!this.attributes.hp?.negativeHealing,void:!(this.modeOfBeing==="construct"||this.attributes.hp?.negativeHealing),bleed:this.modeOfBeing==="living",spirit:!this.itemTypes.effect.some(e=>e.traits.has("possession"))}[damageType]}checkItemValidity(source){return itemIsOfType(source,...this.allowedItemTypes)?!0:(ui.notifications.error(game.i18n.format("PF2E.Item.CannotAddType",{type:game.i18n.localize(CONFIG.Item.typeLabels[source.type]??source.type.titleCase())})),!1)}getStatistic(slug){return["armor","ac"].includes(slug)?this.armorClass?.parent??null:tupleHasValue(SAVE_TYPES,slug)?this.saves?.[slug]??null:this.skills&&objectHasKey(this.skills,slug)?this.skills[slug]??null:this.synthetics.statistics.get(slug)??null}getSelfRollOptions(prefix="self"){const{rollOptions}=this;return Object.keys(rollOptions.all).flatMap(o=>o.startsWith("self:")&&rollOptions.all[o]?o.replace(/^self/,prefix):[])}getReach(_options){return 0}getContextualClone(rollOptions,ephemeralEffects=[]){const rollOptionsAll=rollOptions.reduce((options,option)=>({...options,[option]:!0}),{}),applicableEffects=ephemeralEffects.filter(e=>!this.isImmuneTo(e));return this.clone({items:[foundry.utils.deepClone(this._source.items),applicableEffects].flat(),flags:{pf2e:{rollOptions:{all:rollOptionsAll}}}},{keepId:!0})}async applyAreaEffects(aura,origin){if(game.user!==this.primaryUpdater||this.isOfType("party")||!this.allowedItemTypes.includes("effect")||origin.token.hidden)return;const toCreate=[],rollOptions=aura.effects.some(e=>e.predicate.length>0)?new Set([...origin.actor.getRollOptions(),...this.getSelfRollOptions("target")]):new Set([]);for(const data of aura.effects.filter(e=>e.predicate.test(rollOptions)))if(!this.itemTypes.effect.some(e=>e.sourceId===data.uuid)&&auraAffectsActor(data,origin.actor,this)){const effect=await fromUuid(data.uuid);if(!(effect instanceof ItemPF2e&&effect.isOfType("affliction","effect"))){console.warn(`Effect from ${data.uuid} not found`);continue}const flags={core:{sourceId:effect.uuid},pf2e:{aura:{slug:aura.slug,origin:origin.actor.uuid,removeOnExit:data.removeOnExit}}},source=foundry.utils.mergeObject(effect.toObject(),{flags});source.system.level.value=aura.level??source.system.level.value,source.system.duration.unit="unlimited",source.system.duration.expiry=null,source.system.traits.value.length===0&&source.system.traits.value.push(...aura.traits),source.system.context={target:null,origin:{actor:origin.actor.uuid,token:origin.token.uuid,item:null,spellcasting:null},roll:null};for(const alteration of data.alterations)alteration.applyTo(source);toCreate.push(source)}toCreate.length>0&&await this.createEmbeddedDocuments("Item",toCreate)}static async createDialog(data={},context={}){const omittedTypes=[];game.settings.get("pf2e","campaignType")!=="kingmaker"&&omittedTypes.push("army");const original=game.system.documentTypes.Actor;try{if(game.system.documentTypes.Actor=difference(original,omittedTypes),context.types){const validTypes=context.types??[];validTypes.includes("creature")&&validTypes.push(...CREATURE_ACTOR_TYPES),game.system.documentTypes.Actor=game.system.documentTypes.Actor.filter(type=>tupleHasValue(validTypes,type))}return super.createDialog(data,context)}finally{game.system.documentTypes.Actor=original}}static async createDocuments(data=[],context={}){const sources=data.map(d=>d instanceof ActorPF2e?d.toObject():d);for(const source of[...sources]){const linkable=SIZE_LINKABLE_ACTOR_TYPES.has(source.type),linkToActorSize=linkable&&(source.prototypeToken?.flags?.pf2e?.linkToActorSize??!0),autoscale=linkable&&(source.prototypeToken?.flags?.pf2e?.autoscale??(linkToActorSize&&game.settings.get("pf2e","tokens.autoscale"))),merged=foundry.utils.mergeObject(source,{ownership:source.ownership??{default:CONST.DOCUMENT_OWNERSHIP_LEVELS.NONE},prototypeToken:{flags:{pf2e:{linkToActorSize,autoscale}}}}),dimensionMap={familiar:.5,vehicle:2};switch(merged.prototypeToken.height??=dimensionMap[source.type]??1,merged.prototypeToken.width??=merged.prototypeToken.height,merged.type){case"character":case"familiar":merged.ownership.default=CONST.DOCUMENT_OWNERSHIP_LEVELS.LIMITED,merged.prototypeToken.actorLink=!0,merged.prototypeToken.sight={enabled:!0};break;case"loot":merged.ownership.default=CONST.DOCUMENT_OWNERSHIP_LEVELS.LIMITED,merged.prototypeToken.actorLink=!0,merged.prototypeToken.sight={enabled:!1};break;case"party":merged.ownership.default=CONST.DOCUMENT_OWNERSHIP_LEVELS.OBSERVER,merged.prototypeToken.actorLink=!0,merged.prototypeToken.sight={enabled:!0,range:1};break}const migrated=await migrateActorSource(source);sources.splice(sources.indexOf(source),1,migrated)}return super.createDocuments(sources,context)}static async updateDocuments(updates=[],context={}){for(const changed of updates)await processPreUpdateActorHooks(changed,{pack:context.pack??null});return super.updateDocuments(updates,context)}_initialize(options){this.constructed??=!1,this._itemTypes=null,this.rules=[],this.initiative=null,this.armorClass=null,this.conditions=new ActorConditions,this.auras=new Map;const preparationWarnings=new Set;this.synthetics={criticalSpecalizations:{standard:[],alternate:[]},damageDice:{damage:[]},degreeOfSuccessAdjustments:{},dexterityModifierCaps:[],modifierAdjustments:{all:[],damage:[]},modifiers:{all:[],damage:[]},movementTypes:{},multipleAttackPenalties:{},ephemeralEffects:{},rollNotes:{},rollSubstitutions:{},rollTwice:{},senses:[],statistics:new Map,strikeAdjustments:[],strikes:new Map,striking:{},tokenMarks:new Map,toggles:[],tokenEffectIcons:[],tokenOverrides:{},weaponPotency:{},preparationWarnings:{add:warning=>preparationWarnings.add(warning),flush:foundry.utils.debounce(()=>{for(const warning of preparationWarnings)console.warn(warning);preparationWarnings.clear()},10)}},super._initialize(options),game._documentsReady&&this.synthetics.preparationWarnings.flush()}_initializeSource(source,options){const initialized=super._initializeSource(source,options);if(options?.pack&&initialized._id){const uuid=`Compendium.${options.pack}.${initialized._id}`,art=game.pf2e.system.moduleArt.map.get(uuid)??{};return foundry.utils.mergeObject(initialized,art)}return initialized}prepareData(){this.signature??=UUIDv5(this.uuid,"e9fa1461-0edc-4791-826e-08633f1c6ef7"),super.prepareData();const spellcasting=this.itemTypes.spellcastingEntry,traditionBased=spellcasting.filter(s=>setHasElement(MAGIC_TRADITIONS,s.system.proficiency.slug)),nonTraditionBased=spellcasting.filter(s=>!traditionBased.includes(s));for(const entry of traditionBased)entry.prepareStatistic();for(const rule of this.rules)rule.afterPrepareData?.();for(const entry of nonTraditionBased)entry.prepareStatistic();if(this.attributes.flanking.offGuardable&&this.isImmuneTo("off-guard")&&(this.attributes.flanking.offGuardable=!1),this.preparePrototypeToken(),this.constructed&&canvas.ready){const thisTokenIsControlled=canvas.tokens.controlled.some(t=>t.document===this.parent||t.document.actorLink&&t.actor===this);(game.user.character===this||thisTokenIsControlled)&&game.pf2e.effectPanel.refresh()}}prepareBaseData(){super.prepareBaseData(),this.system.autoChanges={},this.system.attributes.flanking={canFlank:!1,canGangUp:[],flankable:!1,offGuardable:!1};const{attributes,details}=this.system;attributes.hp&&=foundry.utils.mergeObject(attributes.hp,{negativeHealing:!1,unrecoverable:0}),attributes.immunities=attributes.immunities?.map(i=>new Immunity(i))??[],attributes.weaknesses=attributes.weaknesses?.map(w=>new Weakness(w))??[],attributes.resistances=attributes.resistances?.map(r=>new Resistance(r))??[],details.level.value=Math.floor(details.level.value)||0;const traits=this.system.traits;traits?.size&&(traits.size=new ActorSizePF2e(traits.size)),this.flags.pf2e=foundry.utils.mergeObject(this.flags.pf2e??{},{rollOptions:{all:{[`self:type:${this.type}`]:!0,[`self:signature:${this.signature}`]:!0,...createEncounterRollOptions(this)}},trackedItems:{}})}prepareEmbeddedDocuments(){for(const item of this.items)item.reset();const physicalItems=this.items.filter(i=>i.isOfType("physical"));this.inventory=new ActorInventory(this,physicalItems),this.spellcasting=(()=>{const rituals=this.itemTypes.spell.filter(s=>s.isRitual).sort((a,b)=>a.sort-b.sort),spellcastingEntries=[this.itemTypes.spellcastingEntry,rituals.length>0?new RitualSpellcasting(this,rituals):[]].flat();return new ActorSpellcasting(this,spellcastingEntries)})();for(const effect of this.itemTypes.effect)game.pf2e.effectTracker.register(effect);this.prepareDataFromItems()}prepareDataFromItems(){for(const condition of this.itemTypes.condition)this.conditions.set(condition.id,condition);for(const item of this.items)item.prepareSiblingData?.(),item.prepareActorData?.();this.rules=this.prepareRuleElements()}prepareRuleElements(){return sortBy(this.items.contents,i=>i instanceof AbstractEffectPF2e).flatMap(item=>item.prepareRuleElements()).filter(rule=>!rule.ignored).sort((elementA,elementB)=>elementA.priority-elementB.priority)}prepareSynthetics(){for(const rule of this.rules.filter(r=>!r.ignored))try{rule.beforePrepareData?.()}catch(error){const ruleName=game.i18n.localize(`PF2E.RuleElement.${rule.key}`);console.error(`PF2e | Failed to execute onBeforePrepareData on rule element ${ruleName}.`,error)}for(const item of this.items)item.onPrepareSynthetics?.()}prepareDerivedData(){const{rollOptions}=this;for(const trait of this.traits)rollOptions.all[`self:trait:${trait}`]=!0;this.spellcasting.base=new Statistic(this,{slug:"base-spellcasting",label:"PF2E.Actor.Creature.Spellcasting.Label",rank:this.isOfType("character")?this.system.proficiencies.spellcasting.rank:0,domains:["all","spell-attack-dc"],check:{type:"attack-roll"}})}preparePrototypeToken(){this.prototypeToken.flags=foundry.utils.mergeObject({pf2e:{linkToActorSize:SIZE_LINKABLE_ACTOR_TYPES.has(this.type)}},this.prototypeToken.flags),TokenDocumentPF2e.assignDefaultImage(this.prototypeToken),TokenDocumentPF2e.prepareSize(this.prototypeToken)}async getRollContext(params){const[selfToken,targetToken]=canvas.ready&&!params.viewOnly?[canvas.tokens.controlled.find(t=>t.actor===this)??this.getActiveTokens().shift()??null,params.target?.token??params.target?.actor?.getActiveTokens().shift()??null]:[null,null],isAttackAction=["attack","attack-roll","attack-damage"].some(d=>params.domains.includes(d)),isMelee=!!(params.melee||params.item?.isOfType("weapon","melee")&¶ms.item.isMelee),reach=isMelee&¶ms.item?.isOfType("action","weapon","melee")?this.getReach({action:"attack",weapon:params.item}):this.getReach({action:"attack"}),isFlankingAttack=!!(isAttackAction&&isMelee&&typeof reach=="number"&&targetToken?.actor&&selfToken?.isFlanking(targetToken,{reach})),originEphemeralEffects=await extractEphemeralEffects({affects:"origin",origin:this,target:params.target?.actor??targetToken?.actor??null,item:params.item??null,domains:params.domains,options:[...params.options,...params.item?.getRollOptions("item")??[]]}),targetMarkOption=(()=>{const tokenMark=targetToken?this.synthetics.tokenMarks.get(targetToken.document.uuid):null;return tokenMark?`target:mark:${tokenMark}`:null})(),initialActionOptions=params.traits?.map(t=>`self:action:trait:${t}`)??[],selfActor=params.viewOnly||!targetToken?.actor?this:this.getContextualClone(compact([...Array.from(params.options),...targetToken.actor.getSelfRollOptions("target"),targetMarkOption,...initialActionOptions,isFlankingAttack?"self:flanking":null]),originEphemeralEffects),isStrike=params.statistic instanceof StatisticModifier,strikeActions=isStrike?selfActor.system.actions?.flatMap(a=>[a,a.altUsages??[]].flat())??[]:[],statistic=params.viewOnly?params.statistic:isStrike?strikeActions.find(action2=>params.item?.id!==action2.item.id||params?.item.name!==action2.item.name?!1:params.item.isOfType("melee")&&action2.item.isOfType("melee")?!0:params.item.isOfType("weapon")&&action2.item.isOfType("weapon")&¶ms.item.isMelee===action2.item.isMelee)??params.statistic:params.statistic,selfItem=(()=>{if(selfActor===this)return params.item??null;if(statistic&&"item"in statistic&&statistic.item instanceof ItemPF2e&&statistic.item.isOfType("action","melee","spell","weapon"))return statistic.item;const itemClone=selfActor.items.get(params.item?.id??"");return itemClone?.isOfType("melee","weapon")?itemClone:params.item??null})(),itemOptions=selfItem?.getRollOptions("item")??[],actionTraits2=(()=>{const traits=compact([params.traits].flat());if(selfItem?.isOfType("weapon","melee")){const strikeAdjustments=[selfActor.synthetics.strikeAdjustments,getPropertyRuneStrikeAdjustments(selfItem.system.runes.property)].flat();for(const adjustment of strikeAdjustments)adjustment.adjustTraits?.(selfItem,traits)}return uniq(traits).sort()})(),distance=selfToken&&targetToken?selfToken.distanceTo(targetToken):null,[originDistance,targetDistance]=typeof distance=="number"?[`origin:distance:${distance}`,`target:distance:${distance}`]:[null,null],originMarkOption=(()=>{const tokenMark=selfToken?targetToken?.actor?.synthetics.tokenMarks.get(selfToken.document.uuid):null;return tokenMark?`origin:mark:${tokenMark}`:null})(),originRollOptions=selfToken&&targetToken?compact(uniq([...selfActor.getSelfRollOptions("origin"),...actionTraits2.map(t=>`origin:action:trait${t}`),...originDistance?[originDistance]:[],originMarkOption])):[],getTargetRollOptions=__name2(actor=>{const targetOptions=actor?.getSelfRollOptions("target")??[];return targetToken&&(targetOptions.push("target"),targetMarkOption&&targetOptions.push(targetMarkOption)),targetOptions.sort()},"getTargetRollOptions"),targetRollOptions=getTargetRollOptions(targetToken?.actor),targetEphemeralEffects=await extractEphemeralEffects({affects:"target",origin:selfActor,target:targetToken?.actor??null,item:selfItem,domains:params.domains,options:[...params.options,...itemOptions,...targetRollOptions]});if(isFlankingAttack&&isOffGuardFromFlanking(targetToken.actor,selfActor,originRollOptions)){const name2=game.i18n.localize("PF2E.Item.Condition.Flanked"),condition=game.pf2e.ConditionManager.getCondition("off-guard",{name:name2});targetEphemeralEffects.push(condition.toObject())}const targetActor=params.viewOnly?null:(params.target?.actor??targetToken?.actor)?.getContextualClone(compact([...params.options,...itemOptions,...originRollOptions]),targetEphemeralEffects)??null,rollOptions=new Set(compact([...params.options,...selfActor.getRollOptions(params.domains),...targetActor?getTargetRollOptions(targetActor):targetRollOptions,...actionTraits2.map(t=>`self:action:trait:${t}`),...itemOptions,isAttackAction?"attack":null]).sort());targetDistance&&rollOptions.add(targetDistance);const rangeIncrement=selfItem?getRangeIncrement(selfItem,distance):null;rangeIncrement&&rollOptions.add(`target:range-increment:${rangeIncrement}`);const self={actor:selfActor,token:selfToken?.document??null,statistic,item:selfItem,modifiers:[]},target=targetActor&&targetToken&&distance!==null?{actor:targetActor,token:targetToken.document,distance,rangeIncrement}:null;return{options:rollOptions,self,target,traits:actionTraits2}}async getCheckContext(params){const context=await this.getRollContext(params),targetActor=context.target?.actor,rangeIncrement=context.target?.rangeIncrement??null,rangePenalty=calculateRangePenalty(this,rangeIncrement,params.domains,context.options);rangePenalty&&context.self.modifiers.push(rangePenalty);const dcData=(()=>{const{domains,defense}=params,scope=domains.includes("attack")?"attack":"check",statistic=targetActor?.getStatistic(defense)?.dc;return statistic?{scope,statistic,slug:defense,value:statistic.value}:null})();return{...context,dc:dcData}}async getDamageRollContext(params){params.checkContext??=findMatchingCheckContext(this,params),params.outcome&¶ms.options.add(`check:outcome:${sluggify(params.outcome)}`);const substitution=params.checkContext?.substitutions.find(s=>s.selected);return substitution&¶ms.options.add(`check:substitution:${substitution.slug}`),this.getRollContext(params)}async toggleRollOption(domain,option,itemId=null,value,suboption=null){return value=typeof itemId=="boolean"?itemId:value??!this.rollOptions[domain]?.[option],typeof itemId=="string"?this.items.get(itemId,{strict:!0}).rules.find(r=>r instanceof RollOptionRuleElement&&r.domain===domain&&r.option===option)?.toggle(value,suboption)??null:this.rules.find(r=>r instanceof RollOptionRuleElement&&r.domain===domain&&r.option===option)?.toggle(value,suboption)??null}async modifyTokenAttribute(attribute,value,isDelta=!1,isBar){const token=this.getActiveTokens(!0,!0).shift(),{hitPoints}=this;if(!!(attribute==="attributes.hp"&&hitPoints&&(isDelta||value===0&&token?.combatant))&&token){const damage=isDelta?-1*value:hitPoints.value-value;return this.applyDamage({damage,token})}return super.modifyTokenAttribute(attribute,value,isDelta,isBar)}async applyDamage({damage,token,item,rollOptions=new Set,skipIWR=!1,shieldBlockRequest=!1,breakdown=[],notes=[]}){const{hitPoints}=this;if(!hitPoints)return this;const result=typeof damage=="number"?{finalDamage:Math.trunc(damage),applications:[],persistent:[]}:skipIWR?{finalDamage:damage.total,applications:[],persistent:[]}:applyIWR(this,damage,rollOptions),{finalDamage}=result,localize=localizer("PF2E.Actor.ApplyDamage"),actorShield=this.isOfType("character","npc")?this.attributes.shield:null,shieldBlock=actorShield&&shieldBlockRequest?(()=>actorShield.broken?(ui.notifications.warn(game.i18n.format("PF2E.Actions.RaiseAShield.ShieldIsBroken",{actor:token.name,shield:actorShield.name})),!1):actorShield.destroyed?(ui.notifications.warn(game.i18n.format("PF2E.Actions.RaiseAShield.ShieldIsDestroyed",{actor:token.name,shield:actorShield.name})),!1):actorShield.raised?!0:(ui.notifications.warn(localize("ShieldNotRaised",{actor:token.name})),!1))():!1,shieldHardness=shieldBlock?actorShield?.hardness??0:0,damageAbsorbedByShield=finalDamage>0?Math.min(shieldHardness,finalDamage):0,{heldShield}=this,blockingShield=heldShield?.id===actorShield?.itemId?heldShield:null,currentShieldHP=blockingShield?blockingShield._source.system.hp.value:actorShield?.hp.value??0,shieldDamage=shieldBlock?Math.min(currentShieldHP,Math.abs(finalDamage)-damageAbsorbedByShield):0,baseActorHardness=this.hardness,effectiveActorHardness=(()=>{const damageHasAdamantine=typeof damage=="number"?!1:damage.materials.has("adamantine"),materialGrade=item?.isOfType("weapon")&&item.system.material.type==="adamantine"?item.system.material.grade??"standard":"standard",itemHardness={low:0,standard:10,high:13}[materialGrade];return damageHasAdamantine&&itemHardness>=baseActorHardness?Math.floor(baseActorHardness/2):baseActorHardness})(),damageAbsorbedByActor=finalDamage>0?Math.min(finalDamage-damageAbsorbedByShield,effectiveActorHardness):0;if(damageAbsorbedByActor>0){const typeLabel=effectiveActorHardness===baseActorHardness?"PF2E.Damage.Hardness.Full":"PF2E.Damage.Hardness.Half";result.applications.push({category:"reduction",type:game.i18n.localize(typeLabel),adjustment:-1*damageAbsorbedByActor})}const damageResult=this.calculateHealthDelta({hp:hitPoints,sp:this.isOfType("character")?this.attributes.hp.sp:null,delta:finalDamage-damageAbsorbedByShield-damageAbsorbedByActor}),preUpdateSource=this.toObject();blockingShield&&shieldDamage>0&&await blockingShield.update({"system.hp.value":Math.max(blockingShield._source.system.hp.value-shieldDamage,0)},{render:damageResult.totalApplied===0});const staminaMax=this.isOfType("character")?this.attributes.hp.sp?.max??0:0,instantDeath=(()=>damageResult.totalApplied<=0||damageResult.updates["system.attributes.hp.value"]!==0?null:rollOptions.has("item:trait:death")&&!this.attributes.immunities.some(i=>i.type==="death-effects")?"death-effect":rollOptions.has("item:type:spell")&&rollOptions.has("item:slug:disintegrate")?"fine-powder":this.isOfType("npc")&&this.modeOfBeing==="undead"?"destroyed":damageResult.totalApplied>=(hitPoints.max+staminaMax)*2?"massive-damage":null)(),finePowder=instantDeath==="fine-powder";if(damageResult.totalApplied!==0){const updated=await this.update(damageResult.updates,{damageTaken:damageResult.totalApplied,finePowder}),setting=game.settings.get("pf2e","automation.actorsDeadAtZero"),deadAtZero=this.isOfType("npc")&&["npcsOnly","both"].includes(setting)||this.isOfType("character")&&setting==="both"&&!!instantDeath;updated?.isDead&&deadAtZero&&(damageResult.totalApplied>=0&&!token.combatant?.isDefeated||damageResult.totalApplied<0&&token.combatant?.isDefeated)&&token.combatant?.toggleDefeated({overlayIcon:!finePowder}).then(()=>{finePowder&&this.createEmbeddedDocuments("Item",[createDisintegrateEffect()])})}const hpStatement=(()=>hitPoints.max===0||finalDamage-damageAbsorbedByActor===0?localize("TakesNoDamage"):finalDamage>0?damageAbsorbedByShield>0?damageResult.totalApplied>0?localize("DamagedForNShield"):localize("ShieldAbsorbsAll"):localize("DamagedForN"):damageResult.totalApplied<0?localize("HealedForN"):localize("AtFullHealth"))(),updatedShield=this.isOfType("character","npc")?this.attributes.shield:null,shieldStatement=updatedShield&&shieldDamage>0?updatedShield.broken?localize("ShieldDamagedForNBroken"):updatedShield.destroyed?localize("ShieldDamagedForNDestroyed"):localize("ShieldDamagedForN"):null,statements=(()=>{const deathMessage=instantDeath&&localize(`InstantDeath.${sluggify(instantDeath,{camel:"bactrian"})}`),concatenated=compact([hpStatement,shieldStatement,deathMessage]).map(s=>game.i18n.format(s,{actor:token.name.replace(/[<>]/g,""),hpDamage:Math.abs(damageResult.totalApplied),absorbedDamage:damageAbsorbedByShield,shieldDamage})).join(" "),tempElem=document.createElement("div");return tempElem.innerHTML=concatenated,TextEditorPF2e.convertXMLNode(tempElem,"actor",{whose:null,classes:["target-name"]}),tempElem.innerHTML})(),deparenthesize=__name2(formula=>formula.replace(/^\(([^)]+)\)$/,"$1"),"deparenthesize"),persistentDamage=result.persistent.map(instance=>{const condition=game.pf2e.ConditionManager.getCondition("persistent-damage").toObject();return condition.system.persistent={formula:deparenthesize(instance.head.expression),damageType:instance.type,dc:15},condition}),persistentCreated=persistentDamage.length>0?await this.createEmbeddedDocuments("Item",persistentDamage):[],canUndoDamage=!!(damageResult.totalApplied||shieldDamage||persistentCreated.length),content=await renderTemplate("systems/pf2e/templates/chat/damage/damage-taken.hbs",{breakdown,notes,statements,persistent:compact(persistentCreated.map(p=>p.system.persistent?.damage.formula)),iwr:{applications:result.applications,visibility:this.hasPlayerOwner?"all":"gm"},canUndoDamage}),flavor=await(async()=>{if(breakdown.length||notes.length)return renderTemplate("systems/pf2e/templates/chat/damage/damage-taken-flavor.hbs",{breakdown,notes})})(),appliedDamage=canUndoDamage?{uuid:this.uuid,isHealing:damageResult.totalApplied<0,shield:shieldDamage!==0?{id:actorShield?.itemId??"",damage:shieldDamage}:null,persistent:persistentCreated.map(c=>c.id),updates:Object.entries(damageResult.updates).map(([path,newValue])=>{const preUpdateValue=foundry.utils.getProperty(preUpdateSource,path);if(typeof preUpdateValue=="number"){const difference2=preUpdateValue-newValue;return difference2===0?[]:{path,value:difference2}}return[]}).flat()}:null;return await ChatMessagePF2e.create({speaker:ChatMessagePF2e.getSpeaker({token}),flags:{pf2e:{appliedDamage}},flavor,content,type:CONST.CHAT_MESSAGE_TYPES.OTHER,whisper:game.settings.get("pf2e","metagame_secretDamage")&&!token.actor?.hasPlayerOwner?ChatMessagePF2e.getWhisperRecipients("GM").map(u=>u.id):[]}),this}async undoDamage(appliedDamage){const{updates,shield,persistent}=appliedDamage,actorUpdates={};for(const update of updates){const currentValue=foundry.utils.getProperty(this,update.path);typeof currentValue=="number"&&(actorUpdates[update.path]=currentValue+update.value)}if(shield){const item=this.inventory.get(shield.id);item&&(actorUpdates.items=[{_id:shield.id,"system.hp.value":item.hitPoints.value+shield.damage}])}const updateCount=Object.keys(actorUpdates).length;if(persistent.length&&await this.deleteEmbeddedDocuments("Item",persistent,{render:updateCount===0}),updateCount){const{hitPoints}=this,damageTaken=hitPoints&&typeof actorUpdates["system.attributes.hp.value"]=="number"?hitPoints.value-actorUpdates["system.attributes.hp.value"]:0;this.update(actorUpdates,{damageTaken,damageUndo:!0})}}isLootableBy(user){return this.canUserModify(user,"update")}async transferItemToActor(targetActor,item,quantity,containerId,newStack=!1){if(!(item instanceof PhysicalItemPF2e))throw ErrorPF2e("Only physical items (with quantities) can be transfered between actors");const container=targetActor.inventory.get(containerId??"");if(!(!container||container instanceof ContainerPF2e))throw ErrorPF2e("containerId refers to a non-container");if(__name2((source,target)=>{const bothAreOwned=source.isOwner&&target.isOwner,sourceIsOwnedOrLoot=source.isLootableBy(game.user),targetIsOwnedOrLoot=target.isLootableBy(game.user);return!bothAreOwned&&sourceIsOwnedOrLoot&&targetIsOwnedOrLoot},"gmMustTransfer")(this,targetActor)){const source={tokenId:this.token?.id,actorId:this.id,itemId:item.id},target={tokenId:targetActor.token?.id,actorId:targetActor.id};return await new ItemTransfer(source,target,quantity,container?.id).request(),null}if(!this.canUserModify(game.user,"update"))return ui.notifications.error(game.i18n.localize("PF2E.ErrorMessage.CantMoveItemSource")),null;if(!targetActor.canUserModify(game.user,"update"))return ui.notifications.error(game.i18n.localize("PF2E.ErrorMessage.CantMoveItemDestination")),null;quantity=Math.min(quantity,item.quantity);const newQuantity=item.quantity-quantity;newQuantity<1?await item.delete():await item.update({"system.quantity":newQuantity});const newItemData=item.toObject();return newItemData.system.quantity=quantity,newItemData.system.equipped.carryType="worn",hasInvestedProperty(newItemData)&&(newItemData.system.equipped.invested=item.traits.has("invested")?!1:null),targetActor.addToInventory(newItemData,container,newStack)}async addToInventory(itemSource,container,newStack){const stackItem=this.inventory.findStackableItem(itemSource);if(!newStack&&stackItem&&stackItem.type!=="backpack"){const stackQuantity=stackItem.quantity+itemSource.system.quantity;return await stackItem.update({"system.quantity":stackQuantity}),stackItem}const result=await ItemPF2e.create(itemSource,{parent:this});if(!result)return null;const movedItem=this.inventory.get(result.id);return movedItem?(await this.stowOrUnstow(movedItem,container),movedItem):null}async stowOrUnstow(item,container){if(!container)await item.update({"system.containerId":null,"system.equipped.carryType":"worn","system.equipped.handsHeld":0,"system.equipped.inSlot":!1});else if(!isCycle(item,container)){const carryType=container.stowsItems?"stowed":"worn";await item.update({"system.containerId":container.id,"system.equipped.carryType":carryType,"system.equipped.handsHeld":0,"system.equipped.inSlot":!1})}}calculateHealthDelta(args){const updates={},{hp,sp,delta}=args;if(hp.max===0)return{updates,totalApplied:0};const appliedToTemp=(()=>{if(!hp.temp||delta<=0)return 0;const applied=Math.min(hp.temp,delta);return updates["system.attributes.hp.temp"]=Math.max(hp.temp-applied,0),applied})(),appliedToSP=(()=>{if(!(!!sp&&game.pf2e.settings.variants.stamina)||delta<=0)return 0;const remaining=delta-appliedToTemp,applied=Math.min(sp.value,remaining);return updates["system.attributes.hp.sp.value"]=Math.max(sp.value-applied,0),applied})(),appliedToHP=(()=>{const remaining=delta-appliedToTemp-appliedToSP;return updates["system.attributes.hp.value"]=Math.clamped(hp.value-remaining,0,hp.max),remaining})(),totalApplied=appliedToTemp+appliedToSP+appliedToHP;return{updates,totalApplied}}getRollOptions(domains=[]){const withAll=Array.from(new Set(["all",...domains])),{rollOptions}=this,toReturn=new Set;for(const domain of withAll)for(const[option,value]of Object.entries(rollOptions[domain]??{}))value&&toReturn.add(option);return Array.from(toReturn)}getRollData(){const rollData={actor:this};for(const prop of["abilities","attributes","details","skills","saves"])Object.defineProperty(rollData,prop,{get:()=>(foundry.utils.logCompatibilityWarning(`@${prop} is deprecated`,{since:"5.0.1",until:"6"}),objectHasKey(this.system,prop)?foundry.utils.deepClone(this.system[prop]):null)});return rollData}getCondition(slugOrKey,{all=!1}={}){const conditions=this.conditions.filter(c=>c.key===slugOrKey||c.slug===slugOrKey);return all?conditions.sort((conditionA,conditionB)=>{const[valueA,valueB]=[conditionA.value??0,conditionB.value??0];return valueA>valueB?-1:valueAc.active)??null}hasCondition(...slugs){return slugs.some(s=>this.conditions.bySlug(s,{active:!0}).length>0)}async decreaseCondition(conditionSlug,{forceRemove}={forceRemove:!1}){const condition=typeof conditionSlug=="string"?this.getCondition(conditionSlug):conditionSlug;if(!condition)return;if(condition.slug==="persistent-damage"){const matching=this.conditions.stored.filter(c=>c.key===condition.key).map(c=>c.id);await this.deleteEmbeddedDocuments("Item",matching);return}const currentValue=condition._source.system.value.value,newValue=typeof currentValue=="number"?Math.max(currentValue-1,0):null;newValue!==null&&!forceRemove?await game.pf2e.ConditionManager.updateConditionValue(condition.id,this,newValue):await this.deleteEmbeddedDocuments("Item",[condition.id])}async increaseCondition(conditionSlug,{max=Number.MAX_SAFE_INTEGER,value}={}){if(conditionSlug==="persistent-damage")return await new PersistentDamageDialog(this).render(!0),null;const existing=(()=>{if(typeof conditionSlug!="string")return conditionSlug;const conditions=this.itemTypes.condition;return value?conditions.find(c=>c.slug===conditionSlug&&!c.isLocked):conditions.find(c=>c.slug===conditionSlug&&c.active)})();if(existing){const newValue=(()=>{const currentValue=existing._source.system.value.value;if(currentValue===null)return null;const addend=value??1;return Math.clamped(currentValue+addend,1,max)})();return newValue?(await game.pf2e.ConditionManager.updateConditionValue(existing.id,this,newValue),existing):null}else if(typeof conditionSlug=="string"){const conditionSource=game.pf2e.ConditionManager.getCondition(conditionSlug).toObject(),conditionValue=typeof conditionSource.system.value.value=="number"&&max?Math.clamped(conditionSource.system.value.value,value??1,max):null;return conditionSource.system.value.value=conditionValue,(await this.createEmbeddedDocuments("Item",[conditionSource])).shift()??null}return null}async toggleCondition(conditionSlug){if(!setHasElement(CONDITION_SLUGS,conditionSlug))throw ErrorPF2e(`Unrecognized condition: ${conditionSlug}`);this.hasCondition(conditionSlug)?await this.decreaseCondition(conditionSlug,{forceRemove:!0}):await this.increaseCondition(conditionSlug)}async importFromJSON(json2){const processed=await preImportJSON(this,json2);return processed?super.importFromJSON(processed):this}_applyDefaultTokenSettings(data,options){const diff=super._applyDefaultTokenSettings(data,options);return this._source.prototypeToken.texture.src===CONST.DEFAULT_TOKEN&&(this._source.prototypeToken.texture.src=ActorPF2e.getDefaultArtwork(data).texture.src),diff}async _preUpdate(changed,options,user){const changedHP=changed.system?.attributes?.hp,currentHP=this.hitPoints;if(!options.damageTaken&&this.hasPlayerOwner&&typeof changedHP?.value=="number"&¤tHP){const damageTaken=-1*(changedHP.value-currentHP.value),levelChanged=!!changed.system?.details&&"level"in changed.system.details;damageTaken&&!levelChanged&&(options.damageTaken=damageTaken)}return super._preUpdate(changed,options,user)}_onUpdate(changed,options,userId){super._onUpdate(changed,options,userId);const hideFromUser=!this.hasPlayerOwner&&!game.user.isGM&&game.settings.get("pf2e","metagame_secretDamage");if(options.damageTaken&&!hideFromUser){const tokens=this.getActiveTokens();for(const token of tokens)token.showFloatyText(-1*options.damageTaken)}if(canvas.ready&&changed.system?.details&&"alliance"in changed.system.details)for(const token of this.getActiveTokens(!0,!0))token.reset();const currentHP=this.hitPoints?.value??0,hpChange=Number(changed.system?.attributes?.hp?.value)||0;if(currentHP>0&&hpChange>0&&this.isDead){const{combatant}=this;if(combatant)combatant.toggleDefeated({to:!1});else for(const tokenDoc of this.getActiveTokens(!1,!0))tokenDoc.update({overlayEffect:""})}}_onDelete(options,userId){for(const effect of this.itemTypes.effect)game.pf2e.effectTracker.unregister(effect);super._onDelete(options,userId)}_onEmbeddedDocumentChange(){super._onEmbeddedDocumentChange(),this.synthetics.preparationWarnings.flush()}}const ActorProxyPF2e=new Proxy(ActorPF2e,{construct(_target,args){return new CONFIG.PF2E.Actor.documentClasses[args[0].type](...args)}});class CreaturePF2e extends ActorPF2e{static{__name(this,"CreaturePF2e")}static{__name2(this,"CreaturePF2e")}get allowedItemTypes(){return[...super.allowedItemTypes,"affliction"]}get creatureTypes(){return this.system.traits.value.filter(t=>t in CONFIG.PF2E.creatureTypes).sort()}get rarity(){return this.system.traits.rarity}get hardness(){return Math.floor(Math.abs(this.system.attributes.hardness.value))||0}getReach({action:action2="interact",weapon=null}={}){const baseReach=this.attributes.reach.base,weaponReach=weapon?.isOfType("melee")?weapon.reach:null;if(action2==="interact"||this.type==="familiar")return baseReach;if(typeof weaponReach=="number")return weaponReach;{const traitsFromItems=(weapon?[{item:weapon,ready:!0}]:this.system.actions??[]).filter(a=>a.ready).map(a=>new Set(a.item.system.traits?.value??[]));if(traitsFromItems.length===0)return baseReach;const reaches=traitsFromItems.map(traits=>{if(setHasElement(traits,"reach"))return baseReach+5;const reachNPattern=/^reach-\d{1,3}$/;return Number([...traits].find(t=>reachNPattern.test(t))?.replace("reach-",""))||baseReach});return Math.max(...reaches)}}get visionLevel(){const{senses:senses2}=this.system.traits;if(!(Array.isArray(senses2)&&senses2.every(s=>isObject(s)&&"type"in s&&typeof s.type=="string")))return VisionLevels.NORMAL;const senseTypes=new Set(senses2.map(sense=>sense.type));return this.getCondition("blinded")?VisionLevels.BLINDED:senseTypes.has("darkvision")||senseTypes.has("greaterDarkvision")?VisionLevels.DARKVISION:senseTypes.has("lowLightVision")?VisionLevels.LOWLIGHT:VisionLevels.NORMAL}get hasDarkvision(){return this.visionLevel===VisionLevels.DARKVISION&&!this.hasCondition("blinded")}get hasLowLightVision(){return this.visionLevel>=VisionLevels.LOWLIGHT&&!this.hasCondition("blinded")}get canSee(){return canvas.scene?this.visionLevel===VisionLevels.BLINDED?!1:canvas.scene.lightLevel>LightLevels.DARKNESS||this.hasDarkvision:!0}get canAct(){const traits=this.system.traits.value;return(!this.isDead||traits.some(t=>t==="eidolon"))&&!this.hasCondition("paralyzed","stunned","unconscious")}get canAttack(){return this.type!=="familiar"&&this.canAct}get isDead(){const{hitPoints}=this;return hitPoints.max>0&&hitPoints.value===0&&!this.hasCondition("dying","unconscious")?!0:!!(this.token??this.getActiveTokens(!1,!0).shift())?.hasStatusEffect("dead")}get emitsSound(){return this.system.attributes.emitsSound}get isSpellcaster(){const{itemTypes}=this;return itemTypes.spellcastingEntry.length>0&&itemTypes.spell.length>0}get wornArmor(){return this.itemTypes.armor.find(a=>a.isEquipped)??null}get heldShield(){const heldShields=this.itemTypes.shield.filter(s=>s.isEquipped);return heldShields.length===0?null:heldShields.slice(0,-1).reduce((bestShield,shield)=>{if(bestShield===shield)return bestShield;const withBetterAC=bestShield.acBonus>shield.acBonus?bestShield:shield.acBonus>bestShield.acBonus?shield:null,withMoreHP=bestShield.hitPoints.value>shield.hitPoints.value?bestShield:shield.hitPoints.value>bestShield.hitPoints.value?shield:null,withBetterHardness=bestShield.hardness>shield.hardness?bestShield:shield.hardness>bestShield.hardness?shield:null;return withBetterAC??withMoreHP??withBetterHardness??bestShield},heldShields.slice(-1)[0])}getStatistic(slug){switch(slug){case"perception":return this.perception;case"spell":case"spell-attack":return this.spellcasting.contents.flatMap(sc=>sc.statistic??[]).sort((a,b)=>b.mod-a.mod).shift()??null;case"spell-dc":return this.spellcasting.contents.flatMap(sc=>sc.statistic??[]).sort((a,b)=>b.dc.value-a.dc.value).shift()??null}return this.spellcasting.contents.flatMap(sc=>sc.statistic??[]).find(s=>s.slug===slug)??super.getStatistic(slug)}_initialize(options){this.parties??=new Set,super._initialize(options)}prepareData(){super.prepareData();for(const party of this.parties)party.reset({actor:!0})}prepareBaseData(){super.prepareBaseData(),this.flags.pf2e.rollOptions.all["self:creature"]=!0;const attributes=this.system.attributes;attributes.hardness??={value:0},attributes.flanking.canFlank=!0,attributes.flanking.flankable=!0,attributes.flanking.offGuardable=!0,attributes.reach={base:0,manipulate:0},attributes.speed=foundry.utils.mergeObject({total:0,value:0},attributes.speed??{}),attributes.initiative&&(attributes.initiative.tiebreakPriority=this.hasPlayerOwner?2:1);const customModifiers=this.system.customModifiers??={};for(const selector of Object.keys(customModifiers))customModifiers[selector]=customModifiers[selector].map(rawModifier=>new ModifierPF2e(rawModifier));this.isOfType("character","npc")&&(this.system.attributes.shield={itemId:null,name:game.i18n.localize("PF2E.ArmorTypeShield"),ac:0,hp:{value:0,max:0},brokenThreshold:0,hardness:0,raised:!1,broken:!1,destroyed:!1,icon:"systems/pf2e/icons/actions/raise-a-shield.webp"}),attributes.doomed={value:0,max:3},attributes.dying={value:0,max:4,recoveryDC:10},attributes.wounded={value:0,max:3},setImmunitiesFromTraits(this)}prepareEmbeddedDocuments(){super.prepareEmbeddedDocuments();for(const rule of this.rules)rule.onApplyActiveEffects?.();for(const changeEntries of Object.values(this.system.autoChanges))changeEntries?.sort((a,b)=>Number(a.level)>Number(b.level)?1:-1);this.rollOptions.all[`self:mode:${this.modeOfBeing}`]=!0}prepareDerivedData(){super.prepareDerivedData();const{attributes}=this,reachFromSize=SIZE_TO_REACH[this.size];attributes.reach.base=Math.max(attributes.reach.base,reachFromSize),attributes.reach.manipulate=Math.max(attributes.reach.manipulate,attributes.reach.base,reachFromSize);const{rollOptions}=this;this.isSpellcaster&&(rollOptions.all["self:caster"]=!0),this.hitPoints.negativeHealing&&(rollOptions.all["self:negative-healing"]=!0),rollOptions.all["self:armored"]=!!this.wornArmor&&this.wornArmor.category!=="unarmored",attributes.shield?.raised&&!attributes.shield.broken&&!attributes.shield.destroyed&&(this.rollOptions.all["self:shield:raised"]=!0),this.system.attributes.emitsSound=!this.isDead,this.prepareSynthetics();const sizeIndex=SIZES.indexOf(this.size),sizeSlug=SIZE_SLUGS[sizeIndex];rollOptions.all[`self:size:${sizeIndex}`]=!0,rollOptions.all[`self:size:${sizeSlug}`]=!0,attributes.wounded.max=Math.max(0,attributes.dying.max-1),attributes.doomed.max=attributes.dying.max;for(const conditionSlug of["doomed","wounded","dying"]){const condition=this.conditions.bySlug(conditionSlug,{active:!0}).at(0),status=attributes[conditionSlug];conditionSlug==="dying"&&(status.max-=attributes.doomed.value),status.value=Math.min(condition?.value??0,status.max)}if(this.system.resources?.focus){const{focus}=this.system.resources;focus.max=Math.clamped(Math.floor(focus.max),0,focus.cap)||0,focus.value=Math.clamped(Math.floor(focus.value),0,focus.max)||0}imposeEncumberedCondition(this)}prepareSynthetics(){super.prepareSynthetics();for(const[selector,modifiers]of Object.entries(this.system.customModifiers))(this.synthetics.modifiers[selector]??=[]).push(...modifiers.map(m=>()=>m))}async adjustCarryType(item,{carryType,handsHeld=0,inSlot=!1}){const{usage}=item.system;if(carryType==="stowed"){const container=item.actor.itemTypes.backpack.find(c=>c!==item.container&&!isCycle(item,c));container&&await item.actor.stowOrUnstow(item,container)}else{const equipped={carryType,handsHeld:carryType==="held"?handsHeld:0,inSlot:usage.type==="worn"&&usage.where?inSlot:void 0},updates=[];if(isEquipped(usage,equipped)&&item.isOfType("armor")){const wornArmors=this.itemTypes.armor.filter(a=>a!==item&&a.isEquipped);for(const armor of wornArmors)updates.push({_id:armor.id,system:{equipped:{inSlot:!1}}})}else if(equipped.carryType!=="held"&&item.isOfType("weapon")&&item.shield?.isRaised){const effectIds=item.actor.itemTypes.effect.filter(e=>e.slug==="effect-raise-a-shield"||e.slug==="effect-cover"&&e.system.traits.otherTags.includes("tower-shield")&&item.shield?.isTowerShield).map(e=>e.id);await this.deleteEmbeddedDocuments("Item",effectIds)}updates.push({_id:item.id,system:{containerId:null,equipped}}),await this.updateEmbeddedDocuments("Item",updates)}}async addCustomModifier(stat,label,value,type){if(stat=stat==="armor"?"ac":stat,!this.isOfType("character","npc"))return;if(stat.length===0)throw ErrorPF2e("A custom modifier's statistic must be a non-empty string");if(label.length===0)throw ErrorPF2e("A custom modifier's label must be a non-empty string");const modifiers=(this.toObject().system.customModifiers??{})[stat]??[];if(!modifiers.some(m=>m.label===label)){const modifierType=setHasElement(MODIFIER_TYPES,type)?type:"untyped",modifier=new ModifierPF2e({label,modifier:value,type:modifierType,custom:!0}).toObject();await this.update({[`system.customModifiers.${stat}`]:[...modifiers,modifier]})}}async removeCustomModifier(stat,slug){if(stat=stat==="armor"?"ac":stat,stat.length===0)throw ErrorPF2e("A custom modifier's statistic must be a non-empty string");const modifiers=(this.toObject().system.customModifiers??{})[stat]??[];if(modifiers.length!==0)if(typeof slug=="string"){const withRemoved=modifiers.filter(m=>m.slug!==slug);await this.update({[`system.customModifiers.${stat}`]:withRemoved})}else throw ErrorPF2e("Custom modifiers can only be removed by slug (string) or index (number)")}async rollRecovery(event2){const{dying}=this.attributes;if(!dying?.value)return null;const localize=localizer("PF2E.Recovery"),recoveryDC=dying.recoveryDC,dc={label:localize("rollingDescription",{dying:dying.value,dc:"{dc}"}),value:recoveryDC+dying.value,visible:!0},notes=[new RollNotePF2e({selector:"all",text:localize("critSuccess"),outcome:["criticalSuccess"]}),new RollNotePF2e({selector:"all",text:localize("success"),outcome:["success"]}),new RollNotePF2e({selector:"all",text:localize("failure"),outcome:["failure"]}),new RollNotePF2e({selector:"all",text:localize("critFailure"),outcome:["criticalFailure"]})];return new Statistic(this,{slug:"dying-recovery",label:"PF2E.Check.Specific.Recovery",check:{type:"flat-check"}}).roll({...eventToRollParams(event2,{type:"check"}),dc,extraRollNotes:notes})}prepareSenses(data,synthetics){const preparedSenses=data.map(datum=>new CreatureSensePF2e(datum));for(const{sense,predicate,force}of synthetics.senses){if(predicate&&!predicate.test(this.getRollOptions(["all","sense"])))continue;const existing=preparedSenses.find(oldSense=>oldSense.type===sense.type);existing?force?preparedSenses.findSplice(oldSense=>oldSense===existing,sense):(sense.isMoreAcuteThan(existing)&&(existing.acuity=sense.acuity),sense.hasLongerRangeThan(existing)&&(existing.value=sense.value)):preparedSenses.push(sense)}return preparedSenses}prepareSpeed(movementType){const systemData=this.system;if(movementType==="land"){const domains=["speed","all-speeds",`${movementType}-speed`],rollOptions=this.getRollOptions(domains),landSpeed=systemData.attributes.speed;landSpeed.value=Number(landSpeed.value)||0;const fromSynthetics=(this.synthetics.movementTypes[movementType]??[]).flatMap(d=>d()??[]);landSpeed.value=Math.max(landSpeed.value,...fromSynthetics.map(s=>s.value));const modifiers=extractModifiers(this.synthetics,domains),stat=foundry.utils.mergeObject(new StatisticModifier(`${movementType}-speed`,modifiers,rollOptions),landSpeed,{overwrite:!1}),typeLabel=game.i18n.localize("PF2E.SpeedTypesLand"),otherData={type:"land",label:game.i18n.format("PF2E.SpeedLabel",{type:typeLabel})};this.rollOptions.all["speed:land"]=!0;const merged=foundry.utils.mergeObject(stat,otherData);return Object.defineProperties(merged,{total:{get(){return stat.value+stat.totalModifier}},breakdown:{get(){return[`${game.i18n.format("PF2E.SpeedBaseLabel",{type:typeLabel})} ${stat.value}`,...stat.modifiers.filter(m=>m.enabled).map(m=>`${m.label} ${m.signedValue}`)].join(", ")}}}),merged}else{const fastest=(()=>{const{otherSpeeds}=systemData.attributes.speed,existing=otherSpeeds.filter(s=>s.type===movementType),fromSynthetics=(this.synthetics.movementTypes[movementType]??[]).map(d=>d()??[]).flat();return[...existing,...fromSynthetics]})().reduce((best,speed2)=>best?speed2?.value>best.value?speed2:best:speed2,null);if(!fastest)return null;const domains=fastest.derivedFromLand?[`${movementType}-speed`]:["speed","all-speeds",`${movementType}-speed`],rollOptions=this.getRollOptions(domains),label=game.i18n.localize(CONFIG.PF2E.speedTypes[movementType]),speed={type:movementType,label,value:fastest.value};fastest.source&&(speed.source=fastest.source),this.rollOptions.all[`speed:${movementType}`]=!0;const modifiers=extractModifiers(this.synthetics,domains),stat=new StatisticModifier(`${movementType}-speed`,modifiers,rollOptions),merged=foundry.utils.mergeObject(stat,speed,{overwrite:!1});return Object.defineProperties(merged,{total:{get(){return speed.value+stat.totalModifier}},breakdown:{get(){return[`${game.i18n.format("PF2E.SpeedBaseLabel",{type:speed.label})} ${speed.value}`].concat(stat.modifiers.filter(m=>m.enabled).map(m=>`${m.label} ${m.modifier<0?"":"+"}${m.modifier}`)).join(", ")}}}),merged}}deleteEmbeddedDocuments(embeddedName,ids,context){if(embeddedName==="Item"){const linked=ids.map(id=>this.items.get(id)).flatMap(item=>item?.getLinkedItems?.()??[]);ids.push(...linked.map(item=>item.id))}return super.deleteEmbeddedDocuments(embeddedName,[...new Set(ids)],context)}async _preUpdate(changed,options,user){if(!changed.system)return super._preUpdate(changed,options,user);const currentHP=this.hitPoints,changedHP=changed.system.attributes?.hp;typeof changedHP?.value=="number"&&(changedHP.value=options.allowHPOverage?Math.max(0,changedHP.value):Math.clamped(changedHP.value,0,Math.max(currentHP.max-currentHP.unrecoverable,0)));const focusUpdate=changed.system.resources?.focus;if(focusUpdate&&this.system.resources){typeof focusUpdate.max=="number"&&(focusUpdate.max=Math.clamped(focusUpdate.max,0,3));const updatedPoints=Number(focusUpdate.value??this.system.resources.focus?.value)||0,enforcedMax=(Number(focusUpdate.max)||this.system.resources.focus?.max)??0;focusUpdate.value=Math.clamped(updatedPoints,0,enforcedMax)}const traitChanges=changed.system.traits;if(isObject$1(traitChanges)&&Array.isArray(traitChanges.value)){const sourceAlignmentTraits=this._source.system.traits?.value.filter(t=>["good","evil","lawful","chaotic"].includes(t)&&!(t in CONFIG.PF2E.creatureTraits));traitChanges.value=uniq(compact([traitChanges.value,sourceAlignmentTraits].flat()).sort())}return super._preUpdate(changed,options,user)}_onDelete(options,userId){super._onDelete(options,userId);for(const party of this.parties){const updater=party.primaryUpdater;game.user===updater?party.removeMembers(this.uuid):updater||(party.reset(),ui.actors.render())}}}class CharacterFeats extends Collection{static{__name(this,"CharacterFeats")}static{__name2(this,"CharacterFeats")}constructor(actor){super(),this.actor=actor;const classFeatSlots=actor.class?.grantedFeatSlots;this.bonus=new FeatGroup(actor,{id:"bonus",label:"PF2E.FeatBonusHeader"}),this.createGroup({id:"ancestryfeature",label:"PF2E.FeaturesAncestryHeader",supported:["ancestryfeature"]}),this.createGroup({id:"classfeature",label:"PF2E.FeaturesClassHeader",supported:["classfeature"]});const ancestryTraitsFilter=actor.system.details.ancestry?.countsAs.flatMap(t=>t in CONFIG.PF2E.featTraits?`traits-${t}`:[])??[];this.createGroup({id:"ancestry",label:"PF2E.FeatAncestryHeader",featFilter:ancestryTraitsFilter,supported:["ancestry"],slots:classFeatSlots?.ancestry??[]});const classTrait=(()=>{const slug=actor.class?actor.class.slug??sluggify(actor.class.name):null;return slug&&slug in CONFIG.PF2E.featTraits?slug:null})(),classFeatFilter=classTrait?this.actor.level<2?[`traits-${classTrait}`]:this.actor.itemTypes.feat.some(f=>f.traits.has("dedication"))?[`traits-${classTrait}`,"traits-archetype"]:[`traits-${classTrait}`,"traits-dedication"]:[];this.createGroup({id:"class",label:"PF2E.FeatClassHeader",featFilter:classFeatFilter,supported:["class"],slots:classFeatSlots?.class??[]});const evenLevels=new Array(actor.level).fill(0).map((_,idx)=>idx+1).filter(idx=>idx%2===0);game.pf2e.settings.variants.fa&&this.createGroup({id:"archetype",label:"PF2E.FeatArchetypeHeader",supported:["class"],slots:evenLevels,featFilter:this.actor.itemTypes.feat.some(f=>f.traits.has("dedication"))?["traits-archetype"]:["traits-dedication"]});const backgroundSkillFeats=actor.background&&Object.keys(actor.background.system.items??{}).length>0?{id:actor.background.id,level:1,label:game.i18n.localize("PF2E.FeatBackgroundShort")}:null;this.createGroup({id:"skill",label:"PF2E.FeatSkillHeader",supported:["skill"],slots:compact([backgroundSkillFeats,classFeatSlots?.skill].flat())}),this.createGroup({id:"general",label:"PF2E.FeatGeneralHeader",supported:["general","skill"],slots:classFeatSlots?.general??[]}),game.pf2e.settings.campaign.enabled&&this.createGroup({id:"campaign",label:"PF2E.FeatCampaignHeader"})}bonus;createGroup(options){return this.set(options.id,new FeatGroup(this.actor,options))}async insertFeat(feat,slotData){const alreadyHasFeat=this.actor.items.has(feat.id);if(isBoonOrCurse(feat))return alreadyHasFeat?[]:this.actor.createEmbeddedDocuments("Item",[feat.toObject()]);const groupId=slotData?.groupId??"",{group,slotId}=this.get(groupId)?.isFeatValid(feat)?{group:this.get(groupId),slotId:slotData?.slotId??null}:this.#findBestLocation(feat,{requested:groupId}),isFeatValidInSlot=!!group?.isFeatValid(feat);if(groupId!=="bonus"&&!group){const badGroup=this.get(groupId);if(badGroup)return ui.notifications.warn(game.i18n.format("PF2E.Item.Feat.Warning.InvalidCategory",{item:feat.name,category:game.i18n.format(badGroup.label)})),[]}return alreadyHasFeat&&feat.system.location&&!isFeatValidInSlot?this.actor.updateEmbeddedDocuments("Item",[{_id:feat.id,"system.location":null}]):group?.insertFeat(feat,slotId)??this.bonus.insertFeat(feat)}#findBestLocation(feat,{requested}){if(feat.isFeature)return{group:this.get(feat.category)??null,slotId:null};if(requested==="bonus")return{group:null,slotId:null};const validGroups=this.filter(c=>c.isFeatValid(feat)&&!c.isFull),group=validGroups.at(0);if(validGroups.length===1&&group){const slotId=group.slotted?Object.values(group.slots).find(slot=>!slot?.feat)?.id??null:null;return{group,slotId}}return{group:null,slotId:null}}assignToSlots(){const groupsBySlot=this.contents.filter(g=>g.slotted).reduce((previous,current)=>{for(const slot of Object.keys(current.slots))previous[slot]=current;return previous},{}),feats=this.actor.itemTypes.feat.sort((f1,f2)=>f1.sort-f2.sort);for(const feat of feats.filter(f=>!isBoonOrCurse(f))){if(feat.flags.pf2e.grantedBy&&!feat.system.location){const granter=this.actor.items.get(feat.flags.pf2e.grantedBy.id);if(granter?.isOfType("feat")&&granter.grants.includes(feat))continue}const location=feat.system.location??"";(groupsBySlot[location]??this.get(location)??this.get(feat.category))?.assignFeat(feat)||this.bonus.assignFeat(feat)}this.get("classfeature").feats.sort((a,b)=>(a.feat?.level||0)-(b.feat?.level||0))}}class FeatGroup{static{__name(this,"FeatGroup")}static{__name2(this,"FeatGroup")}actor;id;label;feats=[];slotted=!1;featFilter;supported=[];slots={};constructor(actor,options){this.actor=actor;const maxLevel=options.level??actor.level;if(this.id=options.id,this.label=options.label,this.supported=options.supported??[],this.featFilter=Array.from(new Set([this.supported.map(s=>`category-${s}`),options.featFilter??[]].flat())),options.slots){this.slotted=!0;for(const slotOption of options.slots){const slotData=typeof slotOption=="number"?{id:`${this.id}-${slotOption}`,level:slotOption,label:slotOption.toString()}:typeof slotOption=="string"?{id:`${this.id}-${sluggify(slotOption)}`,level:null,label:slotOption}:slotOption;if(typeof slotData.level=="number"&&slotData.level>maxLevel)continue;const slot={...slotData,level:slotData.level??null,children:[]};this.feats.push(slot),this.slots[slot.id]=slot}}}get isFull(){return this.slotted&&Object.values(this.slots).every(s=>!!s?.feat)}assignFeat(feat){const slotId=feat.isOfType("feat")&&feat.system.location===this.id?feat.system.level.taken?.toString()??"":feat.system.location??"",slot=this.slots[slotId];if(!slot&&this.slotted)return!1;if(slot?.feat)return console.debug(`PF2e System | Multiple feats with same index: ${feat.name}, ${slot.feat.name}`),!1;const childSlots=this.#getChildSlots(feat);if(slot)slot.feat=feat,slot.children=childSlots;else{const label=feat.category==="classfeature"?feat.system.level?.value.toString()??null:null;this.feats.push({feat,label,children:childSlots})}return feat.group=this,!0}#getChildSlots(feat){return feat?.isOfType("feat")?feat.grants.map(grant=>({id:grant.id,label:null,level:grant.system.level?.taken??null,feat:grant,children:this.#getChildSlots(grant)})):[]}isFeatValid(feat){return this.supported.length===0||tupleHasValue(this.supported,feat.category)}async insertFeat(feat,slotId=null){const slot=this.slots[slotId??""],location=this.slotted||this.id==="bonus"?slot?.id??null:this.id,existing=this.actor.items.filter(i=>isFeatLike(i)&&i.system.location===location),isFeatValidInSlot=this.isFeatValid(feat),alreadyHasFeat=this.actor.items.has(feat.id),changed=[];if(!alreadyHasFeat&&(isFeatValidInSlot||!location)){const source=foundry.utils.mergeObject(feat.toObject(),{system:{location}});changed.push(...await this.actor.createEmbeddedDocuments("Item",[source]));const label=game.i18n.localize(this.label);ui.notifications.info(game.i18n.format("PF2E.Item.Feat.Info.Added",{item:feat.name,category:label}))}const locationUpdates=this.slotted?existing.map(f=>({_id:f.id,"system.location":null,..."taken"in(feat._source.system.level??{})?{"system.level.-=taken":null}:{}})):[];return alreadyHasFeat&&isFeatValidInSlot&&locationUpdates.push({_id:feat.id,"system.location":location,...slot?.level&&feat.isOfType("feat")?{"system.level.taken":slot.level}:{}}),locationUpdates.length>0&&changed.push(...await this.actor.updateEmbeddedDocuments("Item",locationUpdates)),changed}}function isBoonOrCurse(feat){return["pfsboon","deityboon","curse"].includes(feat.category)}__name(isBoonOrCurse,"isBoonOrCurse"),__name2(isBoonOrCurse,"isBoonOrCurse");function isFeatLike(item){return"category"in item&&"location"in item.system&&"isFeat"in item&&"isFeature"in item}__name(isFeatLike,"isFeatLike"),__name2(isFeatLike,"isFeatLike");const CHARACTER_SHEET_TABS=["character","actions","inventory","spellcasting","crafting","proficiencies","feats","effects","biography","pfs"];class CharacterPF2e extends CreaturePF2e{static{__name(this,"CharacterPF2e")}static{__name2(this,"CharacterPF2e")}get allowedItemTypes(){const buildItems=["ancestry","heritage","background","class","deity","feat"];return[...super.allowedItemTypes,...buildItems,"physical","spellcastingEntry","spell","action","lore","kit"]}get keyAttribute(){return this.system.details.keyability.value||"str"}get keyAbility(){return foundry.utils.logCompatibilityWarning("`CharacterPF2e#keyAbility` is deprecated. Use `CharacterPF2e#keyAttribute` instead.",{since:"5.2.0",until:"6.0.0"}),this.keyAttribute}get abilities(){return foundry.utils.deepClone(this.system.abilities)}get handsFree(){const heldItems=this.inventory.filter(i=>i.isHeld);return Math.clamped(2-sumBy(heldItems,i=>i.traits.has("free-hand")?0:i.handsHeld),0,2)}get handsReallyFree(){const heldItems=this.inventory.filter(i=>i.isHeld);return Math.clamped(2-sumBy(heldItems,i=>i.handsHeld),0,2)}get hitPoints(){return{...super.hitPoints,recoveryMultiplier:this.system.attributes.hp.recoveryMultiplier,recoveryAddend:this.system.attributes.hp.recoveryAddend}}get heroPoints(){return foundry.utils.deepClone(this.system.resources.heroPoints)}getStatistic(slug){switch(slug){case"class":case"class-dc":case"classDC":return this.classDC;case"class-spell":{const highestClass=Object.values(this.classDCs).sort((a,b)=>b.mod-a.mod).shift(),highestSpell=this.spellcasting.contents.flatMap(s=>s.statistic??[]).sort((a,b)=>b.mod-a.mod).shift();return compact([highestClass,highestSpell]).sort((a,b)=>b.mod-a.mod).shift()??null}case"base-spellcasting":return this.spellcasting.base}return this.classDCs[slug]??super.getStatistic(slug)}async getCraftingFormulas(){const{formulas}=this.system.crafting;formulas.sort((a,b)=>(a.sort??0)-(b.sort??0));const formulaMap=new Map(formulas.map(data=>[data.uuid,data]));return(await UUIDUtils.fromUUIDs(formulas.map(f=>f.uuid))).filter(i=>i instanceof ItemPF2e&&i.isOfType("physical")).map(item=>{const{dc,batchSize,deletable}=formulaMap.get(item.uuid)??{deletable:!1};return new CraftingFormula(item,{dc,batchSize,deletable})})}async getCraftingEntries(formulas){const craftingFormulas=formulas??await this.getCraftingFormulas();return Object.values(this.system.crafting.entries).filter(entry=>CraftingEntry.isValid(entry)).map(entry=>new CraftingEntry(this,craftingFormulas,entry))}async getCraftingEntry(selector){const craftingFormulas=await this.getCraftingFormulas(),craftingEntryData=this.system.crafting.entries[selector];return CraftingEntry.isValid(craftingEntryData)?new CraftingEntry(this,craftingFormulas,craftingEntryData):null}async performDailyCrafting(){const entries=(await this.getCraftingEntries()).filter(e=>e.isDailyPrep),reagentCost=entries.filter(e=>e.isAlchemical).reduce((sum,entry)=>sum+entry.reagentCost,0),reagentValue=(this.system.resources.crafting.infusedReagents.value||0)-reagentCost;if(reagentValue<0){ui.notifications.warn(game.i18n.localize("PF2E.CraftingTab.Alerts.MissingReagents"));return}else await this.update({"system.resources.crafting.infusedReagents.value":reagentValue});for(const item of this.inventory)item.system.temporary&&await item.delete();for(const entry of entries)for(const formula of entry.preparedCraftingFormulas){const itemSource=formula.item.toObject();itemSource.system.quantity=formula.quantity,itemSource.system.temporary=!0,itemSource.system.size=this.ancestry?.size==="tiny"?"tiny":"med",entry.isAlchemical&&(itemSource.type==="consumable"||itemSource.type==="weapon"||itemSource.type==="equipment")&&itemSource.system.traits.value.push("infused"),await this.addToInventory(itemSource)}}_initialize(options){this.familiar??=null,super._initialize(options)}prepareData(){super.prepareData(),game.ready&&this.familiar&&game.actors.has(this.familiar.id)&&this.familiar.reset({fromMaster:!0})}prepareBaseData(){super.prepareBaseData(),this.parties.size||(this.system.exploration=[]);const{flags}=this;flags.pf2e.favoredWeaponRank=0,flags.pf2e.freeCrafting??=!1,flags.pf2e.quickAlchemy??=!1,flags.pf2e.sheetTabs=foundry.utils.mergeObject(CHARACTER_SHEET_TABS.reduce((tabs,tab)=>({...tabs,[tab]:!0}),{}),flags.pf2e.sheetTabs??{}),flags.pf2e.showBasicUnarmed??=!0;const isGradual=game.pf2e.settings.variants.gab,allowedBoosts=[1,5,10,15,20].reduce((result,level)=>{const allowed=(()=>this.level===0&&level===1?4:isGradual?4-Math.clamped(level-this.level,0,4):this.level>=level?4:0)();return result[level]=allowed,result},{}),manualAttributes=Object.keys(this.system.abilities??{}).length>0;this.system.abilities=mapToObj(Array.from(ATTRIBUTE_ABBREVIATIONS),a=>[a,foundry.utils.mergeObject({mod:0},this.system.abilities?.[a]??{})]);const systemData=this.system,existingBoosts=systemData.build?.attributes?.boosts,isABP=game.pf2e.variantRules.AutomaticBonusProgression.isEnabled(this);systemData.build={attributes:{manual:manualAttributes,keyOptions:[],boosts:{ancestry:[],background:[],class:null,1:existingBoosts?.[1]?.slice(0,allowedBoosts[1])??[],5:existingBoosts?.[5]?.slice(0,allowedBoosts[5])??[],10:existingBoosts?.[10]?.slice(0,allowedBoosts[10])??[],15:existingBoosts?.[15]?.slice(0,allowedBoosts[15])??[],20:existingBoosts?.[20]?.slice(0,allowedBoosts[20])??[]},allowedBoosts,flaws:{ancestry:[]},apex:isABP?systemData.build?.attributes?.apex??null:null}},systemData.saves=foundry.utils.mergeObject(mapToObj(SAVE_TYPES,t=>[t,{rank:0,ability:SAVING_THROW_DEFAULT_ATTRIBUTES[t]}]),systemData.saves??{});const{details}=this.system;for(const property of["ancestry","heritage","background","class","deity"])this[property]=null,property==="deity"?details.deities={primary:null,secondary:null,domains:{}}:property!=="background"&&(details[property]=null);details.alliance=ALLIANCES.has(details.alliance)?details.alliance:this.hasPlayerOwner?"party":"opposition";const attributes=this.system.attributes;attributes.ac={},attributes.polymorphed=!1,attributes.battleForm=!1,attributes.classDC=null,attributes.spellDC=null,attributes.classOrSpellDC={rank:0,value:0};const perception=attributes.perception??={ability:"wis",rank:0};perception.ability="wis",perception.rank??=0;const hitPoints=this.system.attributes.hp;hitPoints.recoveryMultiplier=1,hitPoints.recoveryAddend=0,attributes.ancestryhp=0,attributes.classhp=0;const{skills}=this.system;for(const key of SKILL_ABBREVIATIONS){const skill=skills[key];skill.ability=SKILL_EXPANDED[SKILL_DICTIONARY[key]].attribute,skill.armor=["dex","str"].includes(skill.ability)}attributes.familiarAbilities={value:0},systemData.proficiencies={...systemData.proficiencies,classDCs:{}},systemData.proficiencies.spellcasting??={rank:0};const{resources}=this.system;resources.heroPoints.max=3,resources.investiture={value:0,max:10},resources.focus={value:resources.focus?.value||0,max:0,cap:3},resources.crafting=foundry.utils.mergeObject({infusedReagents:{value:0,max:0}},resources.crafting??{}),resources.crafting.infusedReagents.max=0,this.system.traits.size=new ActorSizePF2e({value:"med"});const attacks=systemData.proficiencies.attacks??={};for(const category of keys.strict(CONFIG.PF2E.weaponCategories))attacks[category]={rank:attacks[category]?.rank??0,custom:!!attacks[category]?.custom,immutable:!!attacks[category]?.custom};const defenses=systemData.proficiencies.defenses??={};for(const category of ARMOR_CATEGORIES)defenses[category]={rank:defenses[category]?.rank??0,immutable:["light-barding","heavy-barding"].includes(category)};systemData.crafting=foundry.utils.mergeObject({formulas:[],entries:{}},systemData.crafting??{});for(const formula of this.system.crafting.formulas)formula.deletable=!0;this.rollOptions.all[`self:level:${this.level}`]=!0}prepareEmbeddedDocuments(){super.prepareEmbeddedDocuments();for(const attribute of Object.values(this.system.abilities))attribute.mod=Math.trunc(attribute.mod)||0;if(this.setNumericRollOptions(),this.deity?.setFavoredWeaponRank(),this.spellcasting.some(e=>e.isInnate)){const spellcasting=this.system.proficiencies.spellcasting;spellcasting.rank=Math.max(spellcasting.rank,this.level>=12?2:1)}}prepareDataFromItems(){super.prepareDataFromItems(),this.setAttributeModifiers()}prepareDerivedData(){super.prepareDerivedData(),imposeOversizedWeaponCondition(this);const systemData=this.system,{synthetics}=this;if(game.pf2e.variantRules.AutomaticBonusProgression.concatModifiers(this),systemData.details.xp.pct=Math.min(Math.round(systemData.details.xp.value*100/systemData.details.xp.max),99.5),systemData.pfs.levelBump){const params={slug:"level-bump",label:"PF2E.PFS.LevelBump",modifier:1};this.synthetics.modifiers.all.push(()=>new ModifierPF2e(params)),this.synthetics.modifiers.damage.push(()=>new ModifierPF2e(params))}{const ancestryHP=systemData.attributes.ancestryhp,classHP=systemData.attributes.classhp,hitPoints=systemData.attributes.hp,modifiers=[new ModifierPF2e("PF2E.AncestryHP",ancestryHP,"untyped")];if(game.pf2e.settings.variants.stamina){const halfClassHp=Math.floor(classHP/2);systemData.attributes.hp.sp={value:systemData.attributes.hp.sp?.value??0,max:(halfClassHp+systemData.abilities.con.mod)*this.level},systemData.resources.resolve={value:systemData.resources.resolve?.value??0,max:systemData.abilities[systemData.details.keyability.value].mod},modifiers.push(new ModifierPF2e("PF2E.ClassHP",halfClassHp*this.level,"untyped"))}else{modifiers.push(new ModifierPF2e("PF2E.ClassHP",classHP*this.level,"untyped")),delete systemData.resources.resolve;const conHP=systemData.abilities.con.mod*Math.max(this.level,1);modifiers.push(new ModifierPF2e({slug:"hp-con",label:"PF2E.AbilityCon",ability:"con",type:"ability",modifier:conHP,adjustments:extractModifierAdjustments(synthetics.modifierAdjustments,["con-based"],"hp-con")}))}const hpRollOptions=this.getRollOptions(["hp"]);modifiers.push(...extractModifiers(synthetics,["hp"],{test:hpRollOptions}));const perLevelRollOptions=this.getRollOptions(["hp-per-level"]);modifiers.push(...extractModifiers(synthetics,["hp-per-level"],{test:perLevelRollOptions}).map(clone=>(clone.modifier*=this.level,clone)));const stat=foundry.utils.mergeObject(new StatisticModifier("hp",modifiers),hitPoints,{overwrite:!1});if(systemData.pfs.levelBump){const hitPointsBump=Math.max(10,stat.totalModifier*.1);stat.push(new ModifierPF2e("PF2E.PFS.LevelBump",hitPointsBump,"untyped"))}stat.max=stat.totalModifier,stat.value=Math.min(stat.value,stat.max),stat.breakdown=stat.modifiers.filter(m=>m.enabled).map(m=>`${m.label} ${m.modifier<0?"":"+"}${m.modifier}`).join(", "),systemData.attributes.hp=stat,setHitPointsRollOptions(this)}this.prepareFeats(),this.prepareSaves(),this.prepareMartialProficiencies(),this.perception=new Statistic(this,{slug:"perception",label:"PF2E.PerceptionLabel",attribute:"wis",rank:systemData.attributes.perception.rank,domains:["perception","all"],check:{type:"perception-check"}}),systemData.attributes.perception=foundry.utils.mergeObject(systemData.attributes.perception,this.perception.getTraceData({value:"mod"})),this.skills=this.prepareSkills(),this.system.traits.senses=this.prepareSenses(this.system.traits.senses,synthetics),this.classDC=null,this.classDCs={};for(const[slug,classDC]of Object.entries(systemData.proficiencies.classDCs)){const statistic=this.prepareClassDC(slug,classDC);systemData.proficiencies.classDCs[slug]=foundry.utils.mergeObject(classDC,statistic.getTraceData({value:"dc"})),this.classDCs[slug]=statistic,classDC.primary&&(this.classDC=statistic)}systemData.attributes.classDC=Object.values(systemData.proficiencies.classDCs).find(c=>c.primary)??null,systemData.attributes.classDC&&(systemData.attributes.classOrSpellDC=pick(systemData.attributes.classDC,["rank","value"]));const armorStatistic=this.createArmorStatistic();this.armorClass=armorStatistic.dc,systemData.attributes.ac=armorStatistic.getTraceData();const{heldShield}=this;if(heldShield?.speedPenalty){const speedPenalty=new ModifierPF2e(heldShield.name,heldShield.speedPenalty,"untyped");speedPenalty.predicate.push({not:"self:shield:ignore-speed-penalty"}),this.synthetics.modifiers.speed??=[],this.synthetics.modifiers.speed.push(()=>speedPenalty)}const speeds=systemData.attributes.speed=this.prepareSpeed("land");speeds.otherSpeeds=["burrow","climb","fly","swim"].flatMap(m=>this.prepareSpeed(m)??[]),systemData.actions=this.prepareStrikes(),this.flags.pf2e.highestWeaponDamageDice=Math.max(...systemData.actions.filter(s=>s.ready).map(s=>s.item.system.damage.dice),0);const initiativeSkill=systemData.attributes.initiative?.statistic||"perception";this.initiative=new ActorInitiative(this,{statistic:initiativeSkill}),this.system.attributes.initiative=this.initiative.getTraceData();const{crafting}=this.system.resources;crafting.infusedReagents.max=Math.floor(crafting.infusedReagents.max)||0,crafting.infusedReagents.value=Math.clamped(crafting.infusedReagents.value,0,crafting.infusedReagents.max),systemData.attributes.familiarAbilities.value>0&&(this.rollOptions.all["self:has-familiar"]=!0)}setAttributeModifiers(){const{build}=this.system;if(!build.attributes.manual){for(const section of["ancestry","background","class",1,5,10,15,20]){const boosts=build.attributes.boosts[section];if(typeof boosts=="string"){const ability=this.system.abilities[boosts];ability.mod+=ability.mod>=4?.5:1}else if(Array.isArray(boosts))for(const abbrev of boosts){const ability=this.system.abilities[abbrev];ability.mod+=ability.mod>=4?.5:1}const flaws=section==="ancestry"?build.attributes.flaws[section]:[];for(const abbrev of flaws){const ability=this.system.abilities[abbrev];ability.mod-=1}}const isABP=game.pf2e.variantRules.AutomaticBonusProgression.isEnabled(this);if(build.attributes.apex&&(!isABP||this.level>=17)){const attribute=this.system.abilities[build.attributes.apex];attribute.mod=Math.max(attribute.mod+1,4)}}for(const ability of Object.values(this.system.abilities))ability.mod=Math.clamped(ability.mod,-5,10),ability.base=Math.trunc(ability.mod)}setNumericRollOptions(){const rollOptionsAll=this.rollOptions.all,perceptionRank=this.system.attributes.perception.rank;rollOptionsAll[`perception:rank:${perceptionRank}`]=!0;for(const key of ATTRIBUTE_ABBREVIATIONS){const mod=this.abilities[key].mod;rollOptionsAll[`attribute:${key}:mod:${mod}`]=!0}for(const key of SKILL_ABBREVIATIONS){const rank=this.system.skills[key].rank;rollOptionsAll[`skill:${key}:rank:${rank}`]=!0}for(const key of keys.strict(CONFIG.PF2E.weaponCategories)){const rank=this.system.proficiencies.attacks[key].rank;rollOptionsAll[`attack:${key}:rank:${rank}`]=!0}for(const key of ARMOR_CATEGORIES){const rank=this.system.proficiencies.defenses[key].rank;rollOptionsAll[`defense:${key}:rank:${rank}`]=!0}for(const key of SAVE_TYPES){const rank=this.system.saves[key].rank;rollOptionsAll[`save:${key}:rank:${rank}`]=!0}const{handsFree,handsReallyFree}=this;this.attributes.handsFree=handsFree,rollOptionsAll[`hands-free:${handsFree}`]=!0,rollOptionsAll[`hands-free:but-really:${handsReallyFree}`]=!0}createArmorStatistic(){const{synthetics,wornArmor}=this;this.system.proficiencies.defenses["light-barding"].rank||=this.traits.has("animal")&&!isReallyPC(this)?Math.max(this.system.proficiencies.defenses["light-barding"].rank,1):0;const modifiers=[],dexCapSources=[{value:1/0,source:""},...synthetics.dexterityModifierCaps];wornArmor&&dexCapSources.push({value:Number(wornArmor.dexCap??0),source:wornArmor.name});const dexCap=dexCapSources.reduce((lowest,candidate)=>lowest.value>candidate.value?candidate:lowest),dexModifier=createAttributeModifier({actor:this,attribute:"dex",domains:["all","ac","dex-based"],max:dexCap.value}),attributeModifier=modifiers.filter(m=>m.type==="ability"&&!!m.ability).reduce((best,modifier)=>modifier.modifier>best.modifier?modifier:best,dexModifier),proficiency=Object.entries(this.system.proficiencies.defenses).filter(([key,proficiency2])=>wornArmor?wornArmor.category===key?!0:proficiency2.definition?.test(wornArmor.getRollOptions("item"))??!1:key==="unarmored").map(([_k,v])=>v).reduce((best,p)=>p.rank>best.rank?p:best,{rank:0});return new ArmorStatistic(this,{rank:proficiency.rank,attribute:attributeModifier.ability,modifiers:[attributeModifier]})}prepareSaves(){const systemData=this.system,{wornArmor}=this,saves={};for(const saveType of SAVE_TYPES){const save=systemData.saves[saveType],saveName=game.i18n.localize(CONFIG.PF2E.saves[saveType]),modifiers=[],selectors=[saveType,`${save.ability}-based`,"saving-throw","all"];if(wornArmor?.system.runes.resilient&&wornArmor.isInvested){const value=wornArmor.system.runes.resilient;modifiers.push(new ModifierPF2e({slug:"resilient",label:wornArmor.name,type:"item",modifier:value}))}if(saveType==="reflex"&&wornArmor?.traits.has("bulwark")){const slug="bulwark",bulwarkModifier=new ModifierPF2e({slug,type:"untyped",label:CONFIG.PF2E.armorTraits.bulwark,modifier:3,predicate:["damaging-effect"],adjustments:extractModifierAdjustments(this.synthetics.modifierAdjustments,selectors,slug)});modifiers.push(bulwarkModifier),(this.synthetics.modifierAdjustments[saveType]??=[]).push({slug:"dex",test:options=>new PredicatePF2e("damaging-effect").test(options),suppress:!0})}const stat=new Statistic(this,{slug:saveType,label:saveName,attribute:save.ability,rank:save.rank,modifiers,domains:selectors,check:{type:"saving-throw"}});saves[saveType]=stat,this.system.saves[saveType]=foundry.utils.mergeObject(this.system.saves[saveType],stat.getTraceData())}this.saves=saves}prepareSkills(){const systemData=this.system,{synthetics,wornArmor}=this,skills=Array.from(SKILL_ABBREVIATIONS).reduce((builtSkills,shortForm)=>{const skill=systemData.skills[shortForm],longForm=SKILL_DICTIONARY[shortForm],label=CONFIG.PF2E.skillList[longForm]??longForm,domains=[longForm,`${skill.ability}-based`,"skill-check",`${skill.ability}-skill-check`,"all"],modifiers=[],strengthRequirement=wornArmor?.strength;if(typeof strengthRequirement=="number"&&this.system.abilities.str.mod>=strengthRequirement)for(const selector of["skill-check","initiative"]){const rollOptions=this.rollOptions[selector]??={};rollOptions["armor:strength-requirement-met"]=!0}if(skill.armor&&typeof wornArmor?.strength=="number"&&wornArmor.checkPenalty<0){const slug="armor-check-penalty",armorCheckPenalty=new ModifierPF2e({slug,label:"PF2E.ArmorCheckPenalty",modifier:wornArmor.checkPenalty,type:"untyped",adjustments:extractModifierAdjustments(synthetics.modifierAdjustments,domains,slug)});armorCheckPenalty.predicate.push({nor:["attack","armor:ignore-check-penalty"]}),["acrobatics","athletics"].includes(longForm)?armorCheckPenalty.predicate.push({nor:["armor:strength-requirement-met","armor:trait:flexible"]}):longForm==="stealth"&&wornArmor.traits.has("noisy")?armorCheckPenalty.predicate.push({nand:["armor:strength-requirement-met","armor:ignore-noisy-penalty"]}):armorCheckPenalty.predicate.push({not:"armor:strength-requirement-met"}),modifiers.push(armorCheckPenalty)}longForm==="athletics"&&modifiers.push(createForceOpenPenalty(this,domains));const statistic=new Statistic(this,{slug:longForm,label,rank:skill.rank,attribute:skill.ability,domains,modifiers,lore:!1,check:{type:"skill-check"}});return builtSkills[longForm]=statistic,this.system.skills[shortForm]=foundry.utils.mergeObject(this.system.skills[shortForm],statistic.getTraceData()),builtSkills},{});for(const loreItem of this.itemTypes.lore){const longForm=sluggify(loreItem.name),rank=loreItem.system.proficient.value,statistic=new Statistic(this,{slug:longForm,label:loreItem.name,rank,attribute:"int",domains:[longForm,"skill-check","lore-skill-check","int-skill-check","all"],lore:!0,check:{type:"skill-check"}});skills[longForm]=statistic,this.system.skills[longForm]={armor:!1,ability:"int",rank,lore:!0,itemID:loreItem.id,...statistic.getTraceData()}}return skills}prepareSpeed(movementType){const statistic=super.prepareSpeed(movementType);if(!statistic)return null;const{wornArmor}=this,basePenalty=wornArmor?.speedPenalty??0,strength=this.system.abilities.str.mod,requirement=wornArmor?.strength??null,penaltyValue=Math.min(typeof requirement=="number"&&strength>=requirement?Math.min(basePenalty+5,0):basePenalty,0),derivedFromLand=!!("derivedFromLand"in statistic&&statistic.derivedFromLand),modifierName=wornArmor?.name??"PF2E.ArmorSpeedLabel",slug="armor-speed-penalty",armorPenalty=penaltyValue&&!derivedFromLand?new ModifierPF2e({slug,label:modifierName,modifier:penaltyValue,type:"untyped",predicate:new PredicatePF2e({not:"armor:ignore-speed-penalty"}),adjustments:extractModifierAdjustments(this.synthetics.modifierAdjustments,["all-speeds","speed",`${movementType}-speed`],slug)}):null;armorPenalty&&(statistic.push(armorPenalty),statistic.calculateTotal(new Set(this.getRollOptions(["all-speeds","speed",`${movementType}-speed`]))));const hinderingPenalty=createHinderingPenalty(this);return hinderingPenalty&&statistic.push(hinderingPenalty),statistic}prepareFeats(){this.pfsBoons=[],this.deityBoonsCurses=[],this.feats=new CharacterFeats(this);for(const section of game.pf2e.settings.campaign.sections)this.feats.createGroup(section);this.feats.assignToSlots();const feats=this.itemTypes.feat.filter(f=>["pfsboon","deityboon","curse"].includes(f.category)).sort((f1,f2)=>f1.sort-f2.sort);for(const feat of feats)feat.category==="pfsboon"?this.pfsBoons.push(feat):this.deityBoonsCurses.push(feat)}prepareClassDC(slug,classDC){classDC.ability??="str",classDC.rank??=0,classDC.primary??=!1;const classNames=CONFIG.PF2E.classTraits;return classDC.label=classDC.label??classNames[slug]??slug.titleCase(),new Statistic(this,{slug,label:classDC.label,attribute:classDC.ability,rank:classDC.rank,domains:["class",slug,"all"],check:{type:"check"}})}prepareStrikes({includeBasicUnarmed=!0}={}){const{itemTypes,synthetics}=this,handwrapsSlug="handwraps-of-mighty-blows",handwraps=itemTypes.weapon.find(w=>w.slug===handwrapsSlug&&w.category==="unarmed"&&w.isEquipped&&w.isInvested),unarmedRunes=foundry.utils.deepClone(handwraps?._source.system.runes)??{potency:0,striking:0,property:[]},basicUnarmed=includeBasicUnarmed?(()=>{const source={_id:"xxPF2ExUNARMEDxx",name:game.i18n.localize("PF2E.WeaponTypeUnarmed"),type:"weapon",img:"icons/skills/melee/unarmed-punch-fist.webp",system:{slug:"basic-unarmed",category:"unarmed",baseItem:null,bonus:{value:0},damage:{dice:1,die:"d4",damageType:"bludgeoning"},equipped:{carryType:"worn",inSlot:!0,handsHeld:0},group:"brawling",traits:{value:["agile","finesse","nonlethal","unarmed"]},usage:{value:"worngloves"},runes:unarmedRunes}};return new WeaponPF2e(source,{parent:this})})():null;if(handwraps){for(const[slug,weapon]of synthetics.strikes.entries())if(weapon.category==="unarmed"){const clone=weapon.clone({system:{runes:unarmedRunes}},{keepId:!0});synthetics.strikes.set(slug,clone),clone.name=clone._source.name}}const ammos=[...itemTypes.consumable.filter(i=>i.category==="ammo"&&!i.isStowed),...itemTypes.weapon.filter(w=>w.system.usage.canBeAmmo)],offensiveCategories=keys.strict(CONFIG.PF2E.weaponCategories),weapons=compact([itemTypes.weapon.filter(w=>w.slug!==handwrapsSlug),Array.from(synthetics.strikes.values()),basicUnarmed??[],this.itemTypes.shield.filter(s=>!s.isStowed&&!s.isBroken&&!s.isDestroyed).map(s=>s.generateWeapon())].flat()),{handsReallyFree}=this;return weapons.map(w=>this.prepareStrike(w,{categories:offensiveCategories,handsReallyFree,ammos})).sort((a,b)=>a.label.toLocaleLowerCase(game.i18n.lang).replace(/[-0-9\s]/g,"").localeCompare(b.label.toLocaleLowerCase(game.i18n.lang).replace(/[-0-9\s]/gi,""),game.i18n.lang)).sort((a,b)=>a.slug==="basic-unarmed"?1:b.slug==="basic-unarmed"?-1:0).sort((a,b)=>a.item.isHeld===b.item.isHeld?0:a.item.isHeld?-1:1).sort((a,b)=>a.ready===b.ready?0:a.ready?-1:1)}prepareStrike(weapon,{categories,handsReallyFree,ammos=[]}){const{synthetics}=this,modifiers=[],systemData=this.system,strikeAdjustments=[synthetics.strikeAdjustments,getPropertyRuneStrikeAdjustments(weapon.system.runes.property)].flat();for(const adjustment of strikeAdjustments)adjustment.adjustWeapon?.(weapon);const weaponRollOptions=weapon.getRollOptions("item"),weaponTraits2=weapon.traits,{proficiencies}=systemData,categoryRank=proficiencies.attacks[weapon.category]?.rank??0,groupRank=proficiencies.attacks[`weapon-group-${weapon.group}`]?.rank??0,baseWeapon=CONFIG.PF2E.equivalentWeapons[weapon.baseType??""]??weapon.baseType,baseWeaponRank=proficiencies.attacks[`weapon-base-${baseWeapon}`]?.rank??0,equivalentCategories=Object.values(proficiencies.attacks).flatMap(p=>p&&"sameAs"in p&&(p.definition?.test(weaponRollOptions)??!0)?`item:category:${p.sameAs}`:[]),weaponProficiencyOptions=new Set(weaponRollOptions.concat(equivalentCategories)),syntheticRanks=compact(Object.values(proficiencies.attacks)).filter(p=>p.immutable&&(p.definition?.test(weaponProficiencyOptions)??!0)).map(p=>p.rank),proficiencyRank=Math.max(categoryRank,groupRank,baseWeaponRank,...syntheticRanks),meleeOrRanged=weapon.isMelee?"melee":"ranged",baseOptions=new Set(["action:strike","self:action:slug:strike",`item:proficiency:rank:${proficiencyRank}`,PROFICIENCY_RANK_OPTION[proficiencyRank],...weaponTraits2,meleeOrRanged]),attackDomains=getStrikeAttackDomains(weapon,proficiencyRank,baseOptions),{defaultAttribute}=weapon;modifiers.push(createAttributeModifier({actor:this,attribute:defaultAttribute,domains:attackDomains})),weapon.isMelee&&weaponTraits2.has("finesse")&&modifiers.push(createAttributeModifier({actor:this,attribute:"dex",domains:attackDomains})),weapon.isRanged&&weaponTraits2.has("brutal")&&modifiers.push(createAttributeModifier({actor:this,attribute:"str",domains:attackDomains})),modifiers.push(createProficiencyModifier({actor:this,rank:proficiencyRank,domains:attackDomains}));const initialRollOptions=new Set([...baseOptions,...this.getRollOptions(attackDomains),...weaponRollOptions]),ABP=game.pf2e.variantRules.AutomaticBonusProgression;if(weapon.group==="bomb"&&!ABP.isEnabled(this)){const attackBonus=Number(weapon.system.bonus?.value)||0;attackBonus!==0&&modifiers.push(new ModifierPF2e("PF2E.ItemBonusLabel",attackBonus,"item"))}const weaponPotency=(()=>{const potency=attackDomains.flatMap(key=>foundry.utils.deepClone(synthetics.weaponPotency[key]??[])).filter(wp=>wp.predicate.test(initialRollOptions));return weapon.system.runes.potency>0&&potency.push({label:"PF2E.Item.Weapon.Rune.Potency",bonus:weapon.system.runes.potency,type:"item",predicate:new PredicatePF2e}),potency.length>0?potency.reduce((highest,current)=>highest.bonus>current.bonus?highest:current):null})();weaponPotency&&(modifiers.push(new ModifierPF2e(weaponPotency.label,weaponPotency.bonus,weaponPotency.type)),!weapon.isMagical&&(weaponPotency.type==="item"||!ABP.isEnabled(weapon.actor))&&weapon.system.traits.value.push("magical"),weapon.flags.pf2e.attackItemBonus=weaponPotency.bonus);const shoddyPenalty=createShoddyPenalty(this,weapon,attackDomains);shoddyPenalty&&modifiers.push(shoddyPenalty),modifiers.push(...PCAttackTraitHelpers.createAttackModifiers({item:weapon,domains:attackDomains}),...extractModifiers(synthetics,attackDomains,{injectables:{weapon},resolvables:{weapon}}));const auxiliaryActions=[],isRealItem=this.items.has(weapon.id);if(weapon.system.traits.toggles.modular.options.length>0&&auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"interact",annotation:"modular"})),isRealItem&&weapon.category!=="unarmed"){const traitsArray=weapon.system.traits.value,{usage}=weapon.system,weaponAsShield=weapon.shield,canWield2H=usage.hands===2||usage.hands===1&&this.handsFree>0&&!!weaponAsShield||traitsArray.some(t=>t.startsWith("fatal-aim"))||traitsArray.some(t=>t.startsWith("two-hand"));switch(weapon.carryType){case"held":{if(weaponAsShield){const hasShieldRaised=!!this.rollOptions.all["self:effect:raise-a-shield"],hasGreaterCover=!!this.rollOptions.all["self:cover-level:greater"];if(!hasShieldRaised)auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"raise-a-shield"}));else if(weaponAsShield.isTowerShield&&weaponAsShield.isRaised){const action22=hasGreaterCover?"end-cover":"take-cover",annotation="tower-shield";auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:action22,annotation}))}}weapon.handsHeld===2?auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"release",annotation:"grip",hands:1})):weapon.handsHeld===1&&canWield2H&&auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"interact",annotation:"grip",hands:2})),auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"interact",annotation:"sheathe",hands:0})),auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"release",annotation:"drop",hands:0}));break}case"worn":{auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"interact",annotation:"draw",hands:1})),canWield2H&&auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"interact",annotation:"draw",hands:2}));break}case"stowed":{auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"interact",annotation:"retrieve",hands:1}));break}case"dropped":{auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"interact",annotation:"pick-up",hands:1})),canWield2H&&auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"interact",annotation:"pick-up",hands:2}));break}}}const weaponSlug=weapon.slug??sluggify(weapon.name),flavor=this.getStrikeDescription(weapon),rollOptions=[...this.getRollOptions(attackDomains),...weaponRollOptions,...weaponTraits2,meleeOrRanged],strikeStat=new StatisticModifier(weaponSlug,modifiers,rollOptions),altUsages=weapon.getAltUsages().map(w=>this.prepareStrike(w,{categories,handsReallyFree})),versatileLabel=__name2(damageType=>{switch(damageType){case"bludgeoning":return CONFIG.PF2E.weaponTraits["versatile-b"];case"piercing":return CONFIG.PF2E.weaponTraits["versatile-p"];case"slashing":return CONFIG.PF2E.weaponTraits["versatile-s"];default:return CONFIG.PF2E.weaponTraits[`versatile-${damageType}`]??CONFIG.PF2E.damageTypes[damageType]}},"versatileLabel"),handsAvailable=!weapon.system.graspingAppendage||handsReallyFree>0,actionTraits2=["attack",weapon.baseType==="alchemical-bomb"?"manipulate":[]].flat();for(const adjustment of strikeAdjustments)adjustment.adjustTraits?.(weapon,actionTraits2);const ready2=weapon.isEquipped&&handsAvailable||weapon.isThrown&&weapon.reload==="0"&&weapon.isWorn&&handsReallyFree>0,action2=foundry.utils.mergeObject(strikeStat,{label:weapon.name,quantity:weapon.quantity,ready:ready2,domains:attackDomains,visible:weapon.slug!=="basic-unarmed"||this.flags.pf2e.showBasicUnarmed,glyph:"A",item:weapon,type:"strike",...flavor,options:Array.from(baseOptions),traits:actionTraits2.map(t=>traitSlugToObject(t,CONFIG.PF2E.actionTraits)),handsAvailable,weaponTraits:Array.from(weaponTraits2).map(t=>traitSlugToObject(t,CONFIG.PF2E.npcAttackTraits)).sort((a,b)=>a.label.localeCompare(b.label)),variants:[],selectedAmmoId:weapon.system.selectedAmmoId,altUsages,auxiliaryActions,versatileOptions:weapon.system.traits.toggles.versatile.options.map(o=>({value:o,selected:weapon.system.traits.toggles.versatile.selection===o,label:versatileLabel(o),glyph:DAMAGE_TYPE_ICONS[o]}))});if(action2.versatileOptions.length>0&&action2.versatileOptions.unshift({value:weapon.system.damage.damageType,selected:weapon.system.traits.toggles.versatile.selection===null,label:CONFIG.PF2E.damageTypes[weapon.system.damage.damageType],glyph:DAMAGE_TYPE_ICONS[weapon.system.damage.damageType]}),weapon.requiresAmmo){const compatible=ammos.filter(a=>a.isAmmoFor(weapon)),incompatible=ammos.filter(a=>!a.isAmmoFor(weapon)),{ammo}=weapon,selected=ammo?{id:ammo.id,compatible:ammo.isAmmoFor(weapon)}:null;action2.ammunition={compatible,incompatible,selected}}action2.breakdown=action2.modifiers.filter(m=>m.enabled).map(m=>`${m.label} ${m.modifier<0?"":"+"}${m.modifier}`).join(", ");const maps=calculateMAPs(weapon,{domains:attackDomains,options:initialRollOptions}),createMapModifier=__name2(prop=>new ModifierPF2e({slug:maps.slug,label:maps.label,modifier:maps[prop],adjustments:extractModifierAdjustments(synthetics.modifierAdjustments,attackDomains,maps.slug)}),"createMapModifier"),createMapLabel=__name2(prop=>{const modifier=createMapModifier(prop);adjustModifiers([modifier],new Set(rollOptions));const penalty=modifier.ignored?0:modifier.value;return game.i18n.format("PF2E.MAPAbbreviationValueLabel",{value:signedInteger(action2.totalModifier+penalty),penalty})},"createMapLabel"),labels=[()=>signedInteger(action2.totalModifier),()=>createMapLabel("map1"),()=>createMapLabel("map2")],checkModifiers=[(statistic,otherModifiers)=>new CheckModifier("strike",statistic,otherModifiers),(statistic,otherModifiers)=>new CheckModifier("strike-map1",statistic,[...otherModifiers,createMapModifier("map1")]),(statistic,otherModifiers)=>new CheckModifier("strike-map2",statistic,[...otherModifiers,createMapModifier("map2")])];action2.variants=[0,1,2].map(mapIncreases=>({get label(){return labels[mapIncreases]()},roll:async(params={})=>{if(params.options??=[],params.consumeAmmo??=weapon.requiresAmmo,weapon.requiresAmmo&¶ms.consumeAmmo&&!weapon.ammo)return ui.notifications.warn(game.i18n.format("PF2E.Strike.Ranged.NoAmmo",{weapon:weapon.name,actor:this.name})),null;const context=await this.getCheckContext({item:weapon,domains:attackDomains,statistic:action2,target:{token:params.target??game.user.targets.first()??null},defense:"armor",options:new Set([...baseOptions,...params.options]),viewOnly:params.getFormula,traits:actionTraits2});if(action2.traits=context.traits.map(t=>traitSlugToObject(t,CONFIG.PF2E.actionTraits)),context.self.item.isRanged&&typeof context.target?.distance=="number"){const maxRange=context.self.item.range?.max??10;if(context.target.distance>maxRange)return ui.notifications.warn("PF2E.Action.Strike.OutOfRange",{localize:!0}),null}for(const rule of this.rules.filter(r=>!r.ignored))rule.beforeRoll?.(attackDomains,context.options);const dc=params.dc??context.dc,notes=extractNotes(context.self.actor.synthetics.rollNotes,attackDomains),rollTwice=params.rollTwice||extractRollTwice(context.self.actor.synthetics.rollTwice,attackDomains,context.options),substitutions=extractRollSubstitutions(context.self.actor.synthetics.rollSubstitutions,attackDomains,context.options),dosAdjustments=[getPropertyRuneDegreeAdjustments(context.self.item),extractDegreeOfSuccessAdjustments(context.self.actor.synthetics,attackDomains)].flat(),title=game.i18n.format(weapon.isMelee?"PF2E.Action.Strike.MeleeLabel":"PF2E.Action.Strike.RangedLabel",{weapon:weapon.name}),checkContext={type:"attack-roll",identifier:`${weapon.id}.${weaponSlug}.${meleeOrRanged}`,action:"strike",title,actor:context.self.actor,token:context.self.token,target:context.target,item:context.self.item,altUsage:params.altUsage??null,damaging:context.self.item.dealsDamage,domains:attackDomains,options:context.options,notes,dc,traits:context.traits,rollTwice,substitutions,dosAdjustments,mapIncreases};if(params.consumeAmmo&&!this.consumeAmmo(context.self.item,params))return null;const check=checkModifiers[mapIncreases](context.self.statistic??action2,context.self.modifiers),roll=await CheckPF2e.roll(check,checkContext,params.event,params.callback);if(roll)for(const rule of context.self.actor.rules.filter(r=>!r.ignored))await rule.afterRoll?.({roll,check,context:checkContext,domains:attackDomains,rollOptions:context.options});return roll}})),action2.attack=action2.roll=action2.variants[0].roll;for(const method of["damage","critical"])action2[method]=async(params={})=>{const domains=getStrikeDamageDomains(weapon,proficiencyRank);params.options=new Set(params.options??[]);const targetToken=params.target??game.user.targets.first()??null,context=await this.getDamageRollContext({item:weapon,viewOnly:params.getFormula??!1,statistic:action2,target:{token:targetToken},domains,outcome:method==="damage"?"success":"criticalSuccess",options:new Set([...baseOptions,...params.options]),traits:actionTraits2,checkContext:params.checkContext});if(!context.self.item.dealsDamage)return params.getFormula?"":(ui.notifications.warn("PF2E.ErrorMessage.WeaponNoDamage",{localize:!0}),null);const outcome=method==="damage"?"success":"criticalSuccess",{self,target,options}=context,damageContext={type:"damage-roll",sourceType:"attack",self,target,outcome,options,domains,traits:context.traits,...eventToRollParams(params.event,{type:"damage"})};typeof params.mapIncreases=="number"&&(damageContext.mapIncreases=params.mapIncreases,damageContext.options.add(`map:increases:${params.mapIncreases}`)),params.getFormula&&(damageContext.skipDialog=!0);const damage=await WeaponDamagePF2e.calculate({weapon:context.self.item,actor:context.self.actor,weaponPotency,context:damageContext});if(!damage)return null;if(params.getFormula){const formula=damage.damage.formula[outcome];return formula?new DamageRoll(formula).formula:""}else return DamagePF2e.roll(damage,damageContext,params.callback)};return action2}getStrikeDescription(weapon){const flavor={description:"PF2E.Strike.Default.Description",criticalSuccess:"PF2E.Strike.Default.CriticalSuccess",success:"PF2E.Strike.Default.Success"},traits=weapon.traits;return traits.has("unarmed")?(flavor.description="PF2E.Strike.Unarmed.Description",flavor.success="PF2E.Strike.Unarmed.Success"):[...traits].some(trait=>trait.startsWith("thrown-")||trait==="combination")?(flavor.description="PF2E.Strike.Combined.Description",flavor.success="PF2E.Strike.Combined.Success"):weapon.isMelee?(flavor.description="PF2E.Strike.Melee.Description",flavor.success="PF2E.Strike.Melee.Success"):(flavor.description="PF2E.Strike.Ranged.Description",flavor.success="PF2E.Strike.Ranged.Success"),flavor}async getRollContext(params){const context=await super.getRollContext(params);return params.statistic instanceof StatisticModifier&&context.self.item?.isOfType("weapon")&&PCAttackTraitHelpers.adjustWeapon(context.self.item),context}consumeAmmo(weapon,params){const ammo=weapon.ammo;if(ammo){if(ammo.quantity<1)return ui.notifications.warn(game.i18n.localize("PF2E.ErrorMessage.NotEnoughAmmo")),!1;{const existingCallback=params.callback;return params.callback=async roll=>{existingCallback?.(roll),await weapon.consumeAmmo()},!0}}else return!0}prepareMartialProficiencies(){for(const key of["attacks","defenses"]){const proficiencies=this.system.proficiencies[key],linkedProficiencies=Object.values(proficiencies).filter(p=>!!p?.sameAs&&p.sameAs in proficiencies);for(const proficiency of linkedProficiencies){const category=proficiencies[proficiency.sameAs??""];proficiency.rank=(()=>{const maxRankIndex=PROFICIENCY_RANKS.indexOf(proficiency.maxRank??"legendary");return Math.min(category?.rank??0,maxRankIndex)})()}const allProficiencies=Object.entries(proficiencies);for(const[_key,proficiency]of allProficiencies){if(!proficiency)continue;const duplicates=allProficiencies.flatMap(([k,p])=>p&&proficiency!==p&&proficiency.rank>=p.rank&&"definition"in proficiency&&"definition"in p&&proficiency.sameAs===p.sameAs&&equals(p.definition??[],[...proficiency.definition??[]])?k:[]);for(const duplicate of duplicates)delete proficiencies[duplicate];const proficiencyBonus=createProficiencyModifier({actor:this,rank:proficiency.rank,domains:[]});proficiency.value=proficiencyBonus.value,proficiency.breakdown=`${proficiencyBonus.label} ${signedInteger(proficiencyBonus.value)}`}}}async toggleInvested(itemId){const item=this.inventory.get(itemId);if(!item?.traits.has("invested"))throw ErrorPF2e("Unexpected error toggling item investment");const invested=item.isInvested;if(!invested&&!item.isEquipped){const newCarryType=item.system.usage.type==="carried"?"worn":item.system.usage.type;await this.adjustCarryType(item,{carryType:newCarryType,handsHeld:item.system.usage.hands,inSlot:!0})}return!!await item.update({"system.equipped.invested":!invested})}async addAttackProficiency(key){const currentProficiencies=this.system.proficiencies.attacks;if(key in currentProficiencies)return;const newProficiency={rank:1,custom:!0};await this.update({[`system.proficiencies.attacks.${key}`]:newProficiency})}async _preUpdate(changed,options,user){const systemData=this.system;if(typeof changed.system?.resources?.crafting?.infusedReagents?.value=="number"&&(changed.system.resources.crafting.infusedReagents.value=Math.max(0,Math.floor(changed.system.resources.crafting.infusedReagents.value))||0),changed.system?.details?.level||changed.system?.build?.attributes){const level=changed.system?.details?.level;typeof level?.value=="number"&&(level.value=Math.clamped(Number(level.value)||0,0,30)||0);const hpMaxDifference=this.clone(changed).hitPoints.max-this.hitPoints.max;if(hpMaxDifference!==0){options.allowHPOverage=!0;const currentHP=this.hitPoints.value,newHP=Math.max(currentHP+hpMaxDifference,currentHP===0?0:1);changed.system=foundry.utils.mergeObject(changed.system??{},{attributes:{hp:{value:newHP}}})}}game.pf2e.settings.variants.stamina&&(changed.system?.attributes?.hp?.sp&&(changed.system.attributes.hp.sp.value=Math.floor(Math.clamped(changed.system.attributes.hp.sp?.value??0,0,systemData.attributes.hp.sp?.max??0))||0),changed.system?.resources?.resolve&&(changed.system.resources.resolve.value=Math.floor(Math.clamped(changed.system.resources.resolve.value??0,0,systemData.resources.resolve?.max??0))||0));const xp=changed.system?.details?.xp??{};typeof xp.value=="number"&&(xp.value=Math.max(xp.value,0)),typeof xp.max=="number"&&(xp.max=Math.max(xp.max,1));const newLevel=changed.system?.details?.level?.value??this.level,actorClass=this.class;if(actorClass&&newLevel!==this.level){const current=this.itemTypes.feat.filter(feat=>feat.category==="classfeature");if(newLevel>this.level){const classFeaturesToCreate=(await actorClass.createGrantedItems({level:newLevel})).filter(feature=>feature.system.level.value>this.level&&!current.some(currentFeature=>currentFeature.sourceId===feature.flags.core?.sourceId)).map(i=>i.toObject());await this.createEmbeddedDocuments("Item",classFeaturesToCreate,{keepId:!0,render:!1})}else if(newLevelf.level>newLevel&&!f.grantedBy).map(f=>f.id);await this.deleteEmbeddedDocuments("Item",classFeaturestoDelete,{render:!1})}}for(const property of["playerNumber","characterNumber"])if(typeof changed.system?.pfs?.[property]=="number"){const[min,max]=property==="playerNumber"?[1,9999999]:[2001,9999];changed.system.pfs[property]=Math.clamped(changed.system.pfs[property]||0,min,max)}else changed.system?.pfs&&changed.system.pfs[property]!==null&&(changed.system.pfs[property]=this.system.pfs[property]??null);return super._preUpdate(changed,options,user)}}class FamiliarPF2e extends CreaturePF2e{static{__name(this,"FamiliarPF2e")}static{__name2(this,"FamiliarPF2e")}get allowedItemTypes(){return[...super.allowedItemTypes,"action"]}get master(){if(!game.ready||!this.system.master.id)return null;const master=game.actors.get(this.system.master.id??"");return master?.isOfType("character")?(master.familiar??=this,master):null}get masterAttributeModifier(){return this.system.master.ability||="cha",this.master?.system.abilities[this.system.master.ability].mod??0}get masterAbilityModifier(){return this.masterAttributeModifier}get combatant(){return this.master?.combatant??null}reset({fromMaster=!1}={}){super.reset(),fromMaster&&this.sheet.render()}prepareBaseData(){const systemData=this.system;systemData.details.level={value:0},systemData.traits={value:["minion"],senses:[{type:"lowLightVision",label:CONFIG.PF2E.senses.lowLightVision,value:""}],size:new ActorSizePF2e({value:"tiny"})},super.prepareBaseData();const isItemBonus=new PredicatePF2e(["bonus:type:item"]);this.synthetics.modifierAdjustments.all.push({slug:null,test:options=>isItemBonus.test(options),suppress:!0}),systemData.attributes.flanking.canFlank=!1,systemData.attributes.perception={},systemData.attributes.speed={value:25,label:game.i18n.localize("PF2E.SpeedTypesLand"),otherSpeeds:[]},systemData.skills={},systemData.saves={fortitude:{},reflex:{},will:{}},systemData.traits=foundry.utils.mergeObject(systemData.traits,{dv:[],di:[],dr:[]});const{master}=this;systemData.details.level.value=master?.level??0,this.rollOptions.all[`self:level:${this.level}`]=!0,systemData.details.alliance=master?.alliance??"party",master&&(this.flags.pf2e.rollOptions.all=foundry.utils.mergeObject(this.flags.pf2e.rollOptions.all,createEncounterRollOptions(master)))}prepareRuleElements(){return this.master?super.prepareRuleElements():[]}prepareDerivedData(){super.prepareDerivedData();const{master}=this,systemData=this.system,{attributes,traits}=systemData;traits.value=[...this.traits].sort();const{level,masterAttributeModifier}=this,masterLevel=game.pf2e.settings.variants.pwol.enabled?0:level,{synthetics}=this,speeds=attributes.speed=this.prepareSpeed("land");speeds.otherSpeeds=["burrow","climb","fly","swim"].flatMap(m=>this.prepareSpeed(m)??[]);const hitPoints=new HitPointsStatistic(this,{baseMax:level*5});this.system.attributes.hp=hitPoints.getTraceData(),setHitPointsRollOptions(this);const masterModifier=master?new ModifierPF2e({label:"PF2E.Actor.Familiar.Master.ArmorClass",slug:"base",modifier:master.armorClass.modifiers.filter(m=>m.enabled&&!["status","circumstance"].includes(m.type)).reduce((total,modifier)=>total+modifier.value,0)}):null,statistic=new ArmorStatistic(this,{modifiers:compact([masterModifier])});this.armorClass=statistic.dc,systemData.attributes.ac=statistic.getTraceData(),this.saves=SAVE_TYPES.reduce((partialSaves,saveType)=>{const source=master?.saves[saveType]?.modifiers.filter(m=>!["status","circumstance"].includes(m.type))??[],totalMod=applyStackingRules(source),attribute=CONFIG.PF2E.savingThrowDefaultAttributes[saveType],selectors=[saveType,`${attribute}-based`,"saving-throw","all"],stat=new Statistic(this,{slug:saveType,label:game.i18n.localize(CONFIG.PF2E.saves[saveType]),domains:selectors,modifiers:[new ModifierPF2e(`PF2E.MasterSavingThrow.${saveType}`,totalMod,"untyped")],check:{type:"saving-throw"}});return{...partialSaves,[saveType]:stat}},{}),this.system.saves=SAVE_TYPES.reduce((partial,saveType)=>({...partial,[saveType]:this.saves[saveType].getTraceData()}),{}),traits.senses=this.prepareSenses(this.system.traits.senses,synthetics),this.attackStatistic=new Statistic(this,{slug:"attack-roll",label:"PF2E.Familiar.AttackRoll",modifiers:[new ModifierPF2e("PF2E.MasterLevel",masterLevel,"untyped")],check:{type:"attack-roll"}}),this.system.attack=this.attackStatistic.getTraceData();{const domains=["perception","wis-based","all"],modifiers=[new ModifierPF2e("PF2E.MasterLevel",masterLevel,"untyped"),new ModifierPF2e(`PF2E.MasterAbility.${systemData.master.ability}`,masterAttributeModifier,"untyped")];this.perception=new Statistic(this,{slug:"perception",label:"PF2E.PerceptionLabel",domains,modifiers,check:{type:"perception-check"}}),systemData.attributes.perception=foundry.utils.mergeObject(systemData.attributes.perception,this.perception.getTraceData({value:"mod"}))}this.skills=Array.from(SKILL_ABBREVIATIONS).reduce((builtSkills,shortForm)=>{const longForm=SKILL_DICTIONARY[shortForm],modifiers=[new ModifierPF2e("PF2E.MasterLevel",masterLevel,"untyped")];if(["acr","ste"].includes(shortForm)){const label2=`PF2E.MasterAbility.${systemData.master.ability}`;modifiers.push(new ModifierPF2e(label2,masterAttributeModifier,"untyped"))}const attribute=SKILL_EXPANDED[longForm].attribute,domains=[longForm,`${attribute}-based`,"skill-check","all"],label=CONFIG.PF2E.skills[shortForm]??longForm,statistic2=new Statistic(this,{slug:longForm,label,attribute,domains,modifiers,lore:!1,check:{type:"skill-check"}});return builtSkills[longForm]=statistic2,this.system.skills[shortForm]=statistic2.getTraceData(),builtSkills},{})}_onDelete(options,userId){this.master&&(this.master.familiar=null),super._onDelete(options,userId)}}const identifySkills=new Map([["aberration",["occultism"]],["animal",["nature"]],["astral",["occultism"]],["beast",["arcana","nature"]],["celestial",["religion"]],["construct",["arcana","crafting"]],["dragon",["arcana"]],["elemental",["arcana","nature"]],["ethereal",["occultism"]],["fey",["nature"]],["fiend",["religion"]],["fungus",["nature"]],["humanoid",["society"]],["monitor",["religion"]],["ooze",["occultism"]],["plant",["nature"]],["spirit",["occultism"]],["undead",["religion"]]]);function toKnowledgeDC(dc,rarity,loreAdjustment="normal"){const rarityAdjustment=rarityToDCAdjustment(rarity),start=combineDCAdjustments(rarityAdjustment,loreAdjustment),progression=createDifficultyScale(dc,start);return{dc:adjustDC(dc,start),progression,start}}__name(toKnowledgeDC,"toKnowledgeDC"),__name2(toKnowledgeDC,"toKnowledgeDC");function creatureIdentificationDCs(creature,{pwol=!1}={}){const{level,rarity}=creature,dc=calculateDC(level,{pwol}),traits=creature.system.traits.value;return{skills:Array.from(new Set(traits.flatMap(t=>identifySkills.get(t)??[]))),standard:toKnowledgeDC(dc,rarity,"normal"),lore:[toKnowledgeDC(dc,rarity,"easy"),toKnowledgeDC(dc,rarity,"very-easy")]}}__name(creatureIdentificationDCs,"creatureIdentificationDCs"),__name2(creatureIdentificationDCs,"creatureIdentificationDCs");class NPCPF2e extends CreaturePF2e{static{__name(this,"NPCPF2e")}static{__name2(this,"NPCPF2e")}get allowedItemTypes(){return[...super.allowedItemTypes,"physical","spellcastingEntry","spell","action","melee","lore"]}get baseLevel(){return this._source.system.details.level.value}get abilities(){return foundry.utils.deepClone(this.system.abilities)}get description(){return this.system.details.publicNotes}get isElite(){return this.attributes.adjustment==="elite"}get isWeak(){return this.attributes.adjustment==="weak"}get identificationDCs(){const pwol=game.pf2e.settings.variants.pwol.enabled;return creatureIdentificationDCs(this,{pwol})}get isLootable(){const npcsAreLootable=game.settings.get("pf2e","automation.lootableNPCs");return this.isDead&&(npcsAreLootable||this.flags.pf2e.lootable)}get visible(){return super.visible&&this.prototypeToken.actorLink||this.permission>=CONST.DOCUMENT_OWNERSHIP_LEVELS.OBSERVER}canUserModify(user,action2){return super.canUserModify(user,action2)||action2==="update"&&this.isLootable}prepareBaseData(){super.prepareBaseData(),this.flags.pf2e.lootable??=!1;const systemData=this.system;systemData.actions=[];for(const key of SAVE_TYPES)systemData.saves[key].ability=CONFIG.PF2E.savingThrowDefaultAttributes[key];const{attributes,details}=systemData;attributes.perception.ability="wis",attributes.reach={base:SIZE_TO_REACH[this.size],manipulate:SIZE_TO_REACH[this.size]},details.alliance===void 0&&(details.alliance=this.hasPlayerOwner?"party":"opposition"),attributes.hp.negativeHealing=systemData.traits.value.includes("undead"),attributes.flanking.flankable=!systemData.traits.value.includes("troop");const{level}=details;level.base=Math.clamped(level.value,-1,100),level.value=this.isElite?level.base+1:this.isWeak?level.base-1:level.base,this.rollOptions.all[`self:level:${level.value}`]=!0,attributes.spellDC=null,attributes.classDC=(()=>{const pwol=game.pf2e.settings.variants.pwol.enabled,levelBasedDC=calculateDC(level.base,{pwol,rarity:this.rarity});return{value:this.isElite?levelBasedDC+2:this.isWeak?levelBasedDC-2:levelBasedDC}})(),attributes.classOrSpellDC={value:attributes.classDC.value},this.system.spellcasting=foundry.utils.mergeObject({rituals:{dc:0}},this.system.spellcasting),this.system.resources.focus=foundry.utils.mergeObject({value:0,max:0,cap:3},this.system.resources.focus)}prepareDerivedData(){super.prepareDerivedData();const{system}=this,{synthetics}=this,{modifierAdjustments}=synthetics,baseLevel=this.system.details.level.base;this.synthetics.modifiers.hp??=[],this.isElite?(modifierAdjustments.all.push({slug:"base",getNewValue:base=>base+2,test:()=>!0}),this.synthetics.modifiers.hp.push(()=>new ModifierPF2e("PF2E.NPC.Adjustment.EliteLabel",this.getHpAdjustment(baseLevel,"elite"),"untyped"))):this.isWeak&&(modifierAdjustments.all.push({slug:"base",getNewValue:base=>base-2,test:()=>!0}),this.synthetics.modifiers.hp.push(()=>new ModifierPF2e("PF2E.NPC.Adjustment.WeakLabel",this.getHpAdjustment(baseLevel,"weak")*-1,"untyped"))),system.details.level.base=baseLevel;for(const ability of Object.values(this.system.abilities))ability.mod=Math.trunc(Number(ability.mod))||0;{const base=system.attributes.hp.max,modifiers=[extractModifiers(this.synthetics,["hp"],{test:this.getRollOptions(["hp"])}),extractModifiers(this.synthetics,["hp-per-level"],{test:this.getRollOptions(["hp-per-level"])}).map(modifier=>(modifier.modifier*=this.level,modifier))].flat(),hpData=foundry.utils.deepClone(system.attributes.hp),stat=foundry.utils.mergeObject(new StatisticModifier("hp",modifiers),hpData,{overwrite:!1});stat.base=base,stat.max=stat.max+stat.totalModifier,stat.value=Math.min(stat.value,stat.max),stat.breakdown=[game.i18n.format("PF2E.MaxHitPointsBaseLabel",{base}),...stat.modifiers.filter(m=>m.enabled).map(m=>`${m.label} ${signedInteger(m.modifier)}`)].join(", "),system.attributes.hp=stat,setHitPointsRollOptions(this)}const speeds=system.attributes.speed=this.prepareSpeed("land");speeds.otherSpeeds=["burrow","climb","fly","swim"].flatMap(m=>this.prepareSpeed(m)??[]);const armorStatistic=new ArmorStatistic(this,{modifiers:[new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:system.attributes.ac.value-10,adjustments:extractModifierAdjustments(modifierAdjustments,["all","ac","dex-based"],"base")})],details:system.attributes.ac.details});this.armorClass=armorStatistic.dc,this.system.attributes.ac=armorStatistic.getTraceData(),this.prepareSaves();{const domains=["perception","wis-based","all"];this.perception=new Statistic(this,{slug:"perception",label:"PF2E.PerceptionLabel",attribute:"wis",domains,modifiers:[new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:system.attributes.perception.value,adjustments:extractModifierAdjustments(modifierAdjustments,domains,"base")})],check:{type:"perception-check"}}),system.attributes.perception=foundry.utils.mergeObject(system.attributes.perception,this.perception.getTraceData({value:"mod"}))}this.skills=this.prepareSkills();const generatedMelee=Array.from(synthetics.strikes.values()).flatMap(w=>w.toNPCAttacks({keepId:!0}));for(const item of[...this.itemTypes.melee,...generatedMelee])system.actions.push(strikeFromMeleeItem(item));const initiativeSkill=system.attributes.initiative?.statistic||"perception";this.initiative=new ActorInitiative(this,{statistic:initiativeSkill}),this.system.attributes.initiative=this.initiative.getTraceData()}prepareSaves(){const systemData=this.system,{modifierAdjustments}=this.synthetics,saves={};for(const saveType of SAVE_TYPES){const save=systemData.saves[saveType],saveName=game.i18n.localize(CONFIG.PF2E.saves[saveType]),base=save.value,ability=save.ability,domains=[saveType,`${ability}-based`,"saving-throw","all"],stat=new Statistic(this,{slug:saveType,label:saveName,domains,modifiers:[new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:base,adjustments:extractModifierAdjustments(modifierAdjustments,domains,"base")})],check:{type:"saving-throw"}});saves[saveType]=stat,foundry.utils.mergeObject(this.system.saves[saveType],stat.getTraceData()),systemData.saves[saveType].base=base}this.saves=saves}prepareSkills(){const{system}=this,{modifierAdjustments}=this.synthetics;system.skills={};function createTrace(stat,item){const{attribute,shortForm}=objectHasKey(SKILL_EXPANDED,stat.slug)?SKILL_EXPANDED[stat.slug]:{attribute:"int",shortForm:stat.slug};system.skills[shortForm]={...stat.getTraceData(),base:item?.system.mod.value,isLore:!!stat.lore,itemID:item?.id,ability:attribute,visible:stat.proficient,variants:Object.values(item?.system.variants??{})}}__name(createTrace,"createTrace"),__name2(createTrace,"createTrace");const skills={};for(const skill of SKILL_LONG_FORMS){const{attribute,shortForm}=SKILL_EXPANDED[skill],domains=[skill,`${attribute}-based`,"skill-check",`${attribute}-skill-check`,"all"],name2=game.i18n.localize(`PF2E.Skill${SKILL_DICTIONARY[shortForm].capitalize()}`),statistic=new Statistic(this,{slug:skill,label:name2,attribute,domains,modifiers:[new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:system.abilities[attribute].mod,adjustments:extractModifierAdjustments(modifierAdjustments,domains,"base")})],lore:!1,proficient:!1,check:{type:"skill-check"}});skills[skill]=statistic,createTrace(statistic)}for(const item of this.itemTypes.lore){const skill=sluggify(item.name),attribute=objectHasKey(SKILL_EXPANDED,skill)?SKILL_EXPANDED[skill].attribute:"int",label=objectHasKey(CONFIG.PF2E.skillList,skill)?CONFIG.PF2E.skillList[skill]:item.name,base=item.system.mod.value,domains=[skill,`${attribute}-based`,"skill-check","lore-skill-check",`${attribute}-skill-check`,"all"],statistic=new Statistic(this,{slug:skill,label,attribute,lore:!objectHasKey(SKILL_EXPANDED,skill),domains,modifiers:[new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:base,adjustments:extractModifierAdjustments(modifierAdjustments,domains,"base")})],check:{type:"skill-check"}});skills[skill]=statistic,createTrace(statistic,item)}return skills}async getAttackEffects(attack){const notes=[];attack.description&¬es.push(new RollNotePF2e({selector:"all",visibility:"gm",text:attack.description}));const formatItemName=__name2(item=>{if(item.isOfType("consumable")){const button=createHTMLElement("button",{dataset:{action:"consume",item:item.id}});return button.style.width="auto",button.style.lineHeight="14px",button.innerHTML=game.i18n.localize("PF2E.ConsumableUseLabel"),`${item.name} - ${game.i18n.localize("TYPES.Item.consumable")} (${item.quantity}) ${button.outerHTML}`}return item.name},"formatItemName"),formatNoteText=__name2(item=>{const rollData=item.getRollData();return TextEditor.enrichHTML(item.description,{rollData,async:!0})},"formatNoteText");for(const attackEffect of attack.attackEffects){const item=this.items.find(i=>i.type!=="melee"&&(i.slug??sluggify(i.name))===sluggify(attackEffect));if(item){const note=new RollNotePF2e({selector:"all",visibility:"gm",title:formatItemName(item),text:await formatNoteText(item)});notes.push(note)}else{const packItem=(await game.packs.get("pf2e.bestiary-ability-glossary-srd",{strict:!0}).getDocuments({system:{slug:attackEffect}}))[0];if(packItem instanceof ItemPF2e){const note=new RollNotePF2e({selector:"all",visibility:"gm",title:formatItemName(packItem),text:await formatNoteText(packItem)});notes.push(note)}}}return notes}getHpAdjustment(level,adjustment){if(adjustment==="elite"){if(level>=20)return 30;if(level<=19&&level>=5)return 20;if(level<=4&&level>=2)return 15;if(level<=1)return 10}else if(adjustment==="weak"){if(level>=21)return 30;if(level<=20&&level>=6)return 20;if(level<=5&&level>=3)return 15;if(level===1||level===2)return 10}return 0}async applyAdjustment(adjustment){const{isElite,isWeak}=this;if(isElite&&adjustment==="elite"||isWeak&&adjustment==="weak"||!isElite&&!isWeak&&!adjustment)return;const currentHPAdjustment=(()=>isElite?this.getHpAdjustment(this.baseLevel,"elite"):isWeak?this.getHpAdjustment(this.baseLevel,"weak"):0)(),newHPAdjustment=this.getHpAdjustment(this.baseLevel,adjustment),currentHP=this.system.attributes.hp.value,maxHP=this.system.attributes.hp.max,newHP=(()=>{if(isElite){if(adjustment==="weak")return currentHP-currentHPAdjustment-newHPAdjustment;if(!adjustment)return currentHP-currentHPAdjustment}else if(isWeak){if(adjustment==="elite")return this.system.attributes.hp.max=maxHP+currentHPAdjustment+newHPAdjustment,currentHP+currentHPAdjustment+newHPAdjustment;if(!adjustment)return this.system.attributes.hp.max=maxHP+currentHPAdjustment,currentHP+currentHPAdjustment}else{if(adjustment==="elite")return this.system.attributes.hp.max=currentHP+newHPAdjustment,currentHP+newHPAdjustment;if(adjustment==="weak")return currentHP-newHPAdjustment}return currentHP})();await this.update({"system.attributes.hp.value":Math.max(0,newHP),"system.attributes.adjustment":adjustment})}variantClone(params){const source=this._source,changes={name:params.name??this.name,system:{details:{publicNotes:params.description??source.system.details.publicNotes}},img:params.img?.actor??source.img,prototypeToken:{texture:{src:params.img?.token??source.prototypeToken.texture.src}}};return this.clone(changes,{save:params.save,keepId:params.keepId})}}function resolveKingdomBoosts(entry,choices){const notFreeBoosts=entry.boosts.filter(b=>b!=="free");return uniq([notFreeBoosts,choices].flat()).filter(b=>b!==entry.flaw).slice(0,entry.boosts.length)}__name(resolveKingdomBoosts,"resolveKingdomBoosts"),__name2(resolveKingdomBoosts,"resolveKingdomBoosts");function calculateKingdomCollectionData(kingdom){const commodityTypes=["luxuries","lumber","ore","stone"];return{formula:`${kingdom.resources.dice.number}d${kingdom.resources.dice.faces}`,commodities:mapToObj(commodityTypes,type=>{const value=kingdom.resources.workSites[type];return[type,value.value+value.resource*2]})}}__name(calculateKingdomCollectionData,"calculateKingdomCollectionData"),__name2(calculateKingdomCollectionData,"calculateKingdomCollectionData");async function importDocuments(actor,items,skipDialog){const createData=items.filter(d=>!actor.items.some(i=>i.sourceId===d.uuid)).map(d=>d.toObject()),incomingDataByUUID=mapToObj(items,d=>[d.uuid,d.toObject(!0)]),updateData=compact(actor.itemTypes.campaignFeature.map(d=>{const incoming=d.sourceId&&incomingDataByUUID[d.sourceId];if(!incoming)return null;const data=pick(incoming,["name","img","system"]),diff=foundry.utils.diffObject(d.toObject(!0),data);return isEmpty(diff)?null:{_id:d.id,...diff}}));!updateData.length&&!createData.length||!skipDialog&&!await Dialog.confirm({title:game.i18n.localize("PF2E.Kingmaker.Kingdom.ImportDialog.Title"),content:game.i18n.format("PF2E.Kingmaker.Kingdom.ImportDialog.Content",{added:createData.length,updated:updateData.length})})||(await actor.updateEmbeddedDocuments("Item",updateData),await actor.createEmbeddedDocuments("Item",createData))}__name(importDocuments,"importDocuments"),__name2(importDocuments,"importDocuments");const KINGDOM_ABILITIES=["culture","economy","loyalty","stability"],KINGDOM_LEADERSHIP=["ruler","counselor","general","emissary","magister","treasurer","viceroy","warden"],KINGDOM_COMMODITIES=["food","luxuries","lumber","ore","stone"],KINGDOM_SKILLS=["agriculture","arts","boating","defense","engineering","exploration","folklore","industry","intrigue","magic","politics","scholarship","statecraft","trade","warfare","wilderness"],KINGDOM_LEADERSHIP_ABILITIES={ruler:"loyalty",counselor:"culture",general:"stability",emissary:"loyalty",magister:"culture",treasurer:"economy",viceroy:"economy",warden:"stability"},KINGDOM_SKILL_ABILITIES={agriculture:"stability",arts:"culture",boating:"economy",defense:"stability",engineering:"stability",exploration:"economy",folklore:"culture",industry:"economy",intrigue:"loyalty",magic:"culture",politics:"loyalty",scholarship:"culture",statecraft:"loyalty",trade:"economy",warfare:"loyalty",wilderness:"stability"},KINGDOM_ABILITY_LABELS=mapToObj(KINGDOM_ABILITIES,a=>[a,`PF2E.Kingmaker.Abilities.${a}`]),KINGDOM_COMMODITY_LABELS=mapToObj(KINGDOM_COMMODITIES,c=>[c,`PF2E.Kingmaker.Kingdom.Commodity.${c}`]),KINGDOM_RUIN_LABELS={culture:"PF2E.Kingmaker.Kingdom.Ruin.corruption",economy:"PF2E.Kingmaker.Kingdom.Ruin.crime",stability:"PF2E.Kingmaker.Kingdom.Ruin.decay",loyalty:"PF2E.Kingmaker.Kingdom.Ruin.strife"},KINGDOM_SKILL_LABELS=mapToObj(KINGDOM_SKILLS,a=>[a,`PF2E.Kingmaker.Skills.${a}`]),CONTROL_DC_BY_LEVEL=[14,15,16,18,20,22,23,24,26,27,28,30,31,32,34,35,36,38,39,40],KINGDOM_SIZE_DATA={1:{faces:4,type:"territory",controlMod:0,storage:4},10:{faces:6,type:"province",controlMod:1,storage:8},25:{faces:8,type:"state",controlMod:2,storage:12},50:{faces:10,type:"country",controlMod:3,storage:16},100:{faces:12,type:"dominion",controlMod:4,storage:20}},KINGDOM_SETTLEMENT_TYPES=["village","town","city","metropolis"],KINGDOM_SETTLEMENT_TYPE_LABELS=mapToObj(KINGDOM_SETTLEMENT_TYPES,size=>[size,`PF2E.Kingmaker.Settlement.Type.${size}`]),KINGDOM_SETTLEMENT_TYPE_DATA={village:{blocks:1,population:[0,400],level:[1,1],consumption:1,maxItemBonus:1,influence:0},town:{blocks:4,population:[401,2e3],level:[2,4],consumption:2,maxItemBonus:1,influence:1},city:{blocks:9,population:[2001,25e3],level:[5,9],consumption:4,maxItemBonus:2,influence:2},metropolis:{blocks:1/0,population:[25001,1/0],level:[10,1/0],consumption:6,maxItemBonus:3,influence:3}},vacancyLabel=__name2(role=>game.i18n.format("PF2E.Kingmaker.Kingdom.VacantRole",{role:game.i18n.localize(`PF2E.Kingmaker.Kingdom.LeadershipRole.${role}`)}),"vacancyLabel"),VACANCY_PENALTIES={ruler:()=>({modifiers:{"kingdom-check":[{slug:"vacancy-ruler",label:vacancyLabel("ruler"),modifier:-1}],"control-dc":[{slug:"vacancy-ruler",label:vacancyLabel("ruler"),modifier:2}]}}),counselor:()=>({modifiers:{"culture-based":[{slug:"vacancy",label:vacancyLabel("counselor"),modifier:-1}]}}),general:()=>({modifiers:{warfare:[{slug:"vacancy",label:vacancyLabel("general"),modifier:0}]},adjustments:{warfare:[{slug:"vacancy",test:()=>!0,relabel:vacancyLabel("general"),getNewValue:()=>-4}]}}),emissary:()=>({modifiers:{"loyalty-based":[{slug:"vacancy",label:vacancyLabel("emissary"),modifier:-1}]}}),magister:()=>({modifiers:{warfare:[{slug:"vacancy",label:vacancyLabel("magister"),modifier:0}]},adjustments:{warfare:[{slug:"vacancy",test:()=>!0,relabel:vacancyLabel("magister"),getNewValue:()=>-4}]}}),treasurer:()=>({modifiers:{"economy-based":[{slug:"vacancy",label:vacancyLabel("treasurer"),modifier:-1}]}}),viceroy:()=>({modifiers:{"stability-based":[{slug:"vacancy",label:vacancyLabel("viceroy"),modifier:-1}]}}),warden:()=>({modifiers:{"kingdom-check":[{slug:"vacancy",label:vacancyLabel("warden"),modifier:0}]},adjustments:{"kingdom-check":[{slug:"vacancy",test:options=>[...options].includes("region"),relabel:vacancyLabel("warden"),getNewValue:()=>-4}]}})};function getKingdomCHGData(){const localize=localizer("PF2E.Kingmaker");return{charter:{conquest:{name:localize("Charter.conquest.Name"),description:localize("Charter.conquest.Description"),img:"/icons/weapons/swords/sword-guard-steel-green.webp",boosts:["loyalty","free"],flaw:"culture"},expansion:{name:localize("Charter.expansion.Name"),description:localize("Charter.expansion.Description"),img:"/icons/skills/trades/woodcutting-logging-axe-stump.webp",boosts:["culture","free"],flaw:"stability"},exploration:{name:localize("Charter.exploration.Name"),description:localize("Charter.exploration.Description"),img:"/icons/tools/navigation/map-chart-tan.webp",boosts:["stability","free"],flaw:"economy"},grant:{name:localize("Charter.grant.Name"),description:localize("Charter.grant.Description"),img:"/icons/skills/trades/academics-merchant-scribe.webp",boosts:["economy","free"],flaw:"loyalty"},open:{name:localize("Charter.open.Name"),description:localize("Charter.open.Description"),img:"/icons/sundries/documents/document-sealed-brown-red.webp",boosts:["free"],flaw:null}},heartland:{forestOrSwamp:{name:localize("Heartland.forestOrSwamp.Name"),description:localize("Heartland.forestOrSwamp.Description"),img:"/icons/environment/wilderness/tree-oak.webp",boosts:["culture"]},hillOrPlain:{name:localize("Heartland.hillOrPlain.Name"),description:localize("Heartland.hillOrPlain.Description"),img:"/icons/environment/creatures/horses.webp",boosts:["loyalty"]},lakeOrRiver:{name:localize("Heartland.lakeOrRiver.Name"),description:localize("Heartland.lakeOrRiver.Description"),img:"/icons/environment/settlement/bridge-stone.webp",boosts:["economy"]},mountainOrRuins:{name:localize("Heartland.mountainOrRuins.Name"),description:localize("Heartland.mountainOrRuins.Description"),img:"/icons/environment/wilderness/cave-entrance-mountain.webp",boosts:["stability"]}},government:{despotism:{name:localize("Government.despotism.Name"),description:localize("Government.despotism.Description"),img:"/icons/environment/settlement/pyramid.webp",boosts:["stability","economy","free"],skills:["intrigue","warfare"],feat:"Compendium.pf2e.kingmaker-features.Item.WGpkcIChjIk1i0q0"},feudalism:{name:localize("Government.feudalism.Name"),description:localize("Government.feudalism.Description"),img:"/icons/environment/settlement/watchtower-cliff.webp",boosts:["stability","culture","free"],skills:["defense","trade"],feat:"Compendium.pf2e.kingmaker-features.Item.JYY8vQxPe9AIGTvv"},oligarchy:{name:localize("Government.oligarchy.Name"),description:localize("Government.oligarchy.Description"),img:"/icons/environment/settlement/house-manor.webp",boosts:["loyalty","economy","free"],skills:["arts","industry"],feat:"Compendium.pf2e.kingmaker-features.Item.9dkyZ7r1z7loOxI7"},republic:{name:localize("Government.republic.Name"),description:localize("Government.republic.Description"),img:"/icons/environment/settlement/gazebo.webp",boosts:["stability","economy","free"],skills:["engineering","politics"],feat:"Compendium.pf2e.kingmaker-features.Item.BChcBEZpcqMnLISC"},thaumocracy:{name:localize("Government.thaumocracy.Name"),description:localize("Government.thaumocracy.Description"),img:"/icons/environment/settlement/wizard-castle.webp",boosts:["economy","culture","free"],skills:["folklore","magic"],feat:"Compendium.pf2e.kingmaker-features.Item.nDDEbrWj2JouxlRw"},yeomanry:{name:localize("Government.yeomanry.Name"),description:localize("Government.yeomanry.Description"),img:"/icons/environment/settlement/house-farmland-small.webp",boosts:["loyalty","culture","free"],skills:["agriculture","wilderness"],feat:"Compendium.pf2e.kingmaker-features.Item.WFng3pxgEAdpdy1p"}}}}__name(getKingdomCHGData,"getKingdomCHGData"),__name2(getKingdomCHGData,"getKingdomCHGData");const KINGDOM_TRAITS=["commerce","leadership","region","civic","army"];class KingdomSheetPF2e extends ActorSheetPF2e{static{__name(this,"KingdomSheetPF2e")}static{__name2(this,"KingdomSheetPF2e")}selectedFilter=null;focusElement=null;#editingSettlements={};constructor(actor,options){super(actor,options)}get kingdom(){const campaign=this.actor.campaign;if(!(campaign instanceof Kingdom))throw this.close(),ErrorPF2e("Only actors with kingdom data is supported");return campaign}get title(){return this.kingdom.name}static get defaultOptions(){const options=super.defaultOptions;return{...options,classes:[...options.classes,"kingdom"],width:720,height:620,template:"systems/pf2e/templates/actors/party/kingdom/sheet.hbs",scrollY:[...options.scrollY,".tab.active",".tab.active .content",".sidebar"],tabs:[{navSelector:"form > nav",contentSelector:".container",initial:"main"}]}}_getHeaderButtons(){const buttons=super._getHeaderButtons();return game.user.isGM&&buttons.unshift({label:"JOURNAL.ActionShow",class:"show-sheet",icon:"fa-solid fa-eye",onclick:()=>{const users=game.users.filter(u=>!u.isSelf);game.socket.emit("system.pf2e",{request:"showSheet",users:users.map(u=>u.uuid),document:this.actor.uuid,options:{campaign:!0,tab:this._tabs[0].active}})}}),buttons}async getData(options){const data=await super.getData(options),kingdom=this.kingdom,settlementEntries=pipe(Object.entries(this.kingdom.settlements),filter(entry=>!!entry[1]),sortBy(entry=>entry[1].sort));return{...data,actor:this.actor,kingdom:this.kingdom,nationTypeLabel:game.i18n.localize(`PF2E.Kingmaker.Kingdom.NationType.${kingdom.nationType}`),abilities:KINGDOM_ABILITIES.map(slug=>({...this.kingdom.abilities[slug],slug,label:game.i18n.localize(KINGDOM_ABILITY_LABELS[slug]),ruinLabel:game.i18n.localize(KINGDOM_RUIN_LABELS[slug])})),commodities:KINGDOM_COMMODITIES.map(type=>({...kingdom.resources.commodities[type],type,label:game.i18n.localize(KINGDOM_COMMODITY_LABELS[type]),workSites:{label:game.i18n.localize(`PF2E.Kingmaker.WorkSites.${type}.Name`),description:game.i18n.localize(`PF2E.Kingmaker.WorkSites.${type}.Description`),hasResource:["lumber","ore","stone"].includes(type),value:kingdom.resources.workSites[type].value,resource:kingdom.resources.workSites[type].resource}})),resourceDice:{...kingdom.resources.dice,icon:fontAwesomeIcon(`dice-d${kingdom.resources.dice.faces}`).outerHTML,bonusAdjustment:getAdjustment(kingdom.resources.dice.bonus,kingdom._source.resources.dice.bonus),penaltyAdjustment:getAdjustment(kingdom.resources.dice.penalty,kingdom._source.resources.dice.penalty)},leadership:KINGDOM_LEADERSHIP.map(slug=>{const data2=this.kingdom.leadership[slug],document2=fromUuidSync(data2.uuid??""),actor=document2 instanceof ActorPF2e?document2:null;return{...data2,slug,label:game.i18n.localize(`PF2E.Kingmaker.Kingdom.LeadershipRole.${slug}`),actor,img:actor?.prototypeToken.texture.src??actor?.img??ActorPF2e.DEFAULT_ICON,abilityLabel:game.i18n.localize(KINGDOM_ABILITY_LABELS[KINGDOM_LEADERSHIP_ABILITIES[slug]]),penaltyLabel:game.i18n.localize(`PF2E.Kingmaker.Kingdom.VacancyPenalty.${slug}`)}}),actions:sortBy(kingdom.activities,a=>a.name).map(item=>({item,traits:createSheetTags(CONFIG.PF2E.kingmakerTraits,item.system.traits.value.filter(t=>t!=="downtime"))})),skills:sortBy(Object.values(this.kingdom.skills),s=>s.label),feats:[kingdom.features,kingdom.feats,kingdom.bonusFeats],actionFilterChoices:KINGDOM_TRAITS.map(trait=>({label:game.i18n.localize(CONFIG.PF2E.kingmakerTraits[trait]),value:trait,selected:!1})),settlements:await Promise.all(settlementEntries.map(async([id,data2])=>this.#prepareSettlement(id,data2))),eventText:await TextEditor.enrichHTML(kingdom.event.text,{async:!0,rollData:this.actor.getRollData()}),settlementTypes:KINGDOM_SETTLEMENT_TYPE_LABELS,abilityLabels:KINGDOM_ABILITY_LABELS,skillLabels:KINGDOM_SKILL_LABELS}}async#prepareSettlement(id,settlement){const data=KINGDOM_SETTLEMENT_TYPE_DATA[settlement.type],levelRange=data.level[1]===1/0?`${data.level[0]}+`:data.level[0]===data.level[1]?String(data.level[0]):data.level.join("-"),populationRange=data.population[1]===1/0?`${data.population[0]}+`:data.population.join("-");return{...settlement,id,description:await TextEditor.enrichHTML(settlement.description,{async:!0,rollData:this.actor.getRollData()}),editing:this.#editingSettlements[id]??!1,blocks:data.blocks===1/0?"10+":data.blocks,populationRange,levelRange,typeLabel:KINGDOM_SETTLEMENT_TYPE_LABELS[settlement.type],storage:KINGDOM_COMMODITIES.map(type=>({type,value:settlement.storage[type],label:game.i18n.localize(KINGDOM_COMMODITY_LABELS[type])}))}}activateListeners($html){super.activateListeners($html);const html=$html[0];this.focusElement&&(htmlQuery(html,this.focusElement)?.focus(),this.focusElement=null);for(const openSheetLink of htmlQueryAll(html,"[data-action=open-sheet]")){const actorUUID=htmlClosest(openSheetLink,"[data-actor-uuid]")?.dataset.actorUuid,actor=fromUuidSync(actorUUID??"");openSheetLink.addEventListener("click",()=>actor?.sheet.render(!0))}for(const button of htmlQueryAll(html,"[data-action=builder]")){const tab=button.dataset.tab??null;button.addEventListener("click",()=>{new KingdomBuilder(this.kingdom).render(!0,{tab})})}const{fame}=this.kingdom.resources,famePips=htmlQuery(html,"[data-action=adjust-fame]");famePips?.addEventListener("click",async()=>{const newValue=Math.min(fame.value+1,fame.max);await this.kingdom.update({"resources.fame.value":newValue})}),famePips?.addEventListener("contextmenu",async event2=>{event2.preventDefault();const newValue=Math.max(fame.value-1,0);await this.kingdom.update({"resources.fame.value":newValue})});for(const leader of htmlQueryAll(html,".leader[data-role]")){const{role,uuid}=leader.dataset;if(htmlQuery(leader,"[data-action=remove-leader]")?.addEventListener("click",()=>{this.kingdom.update({[`leadership.${role}`]:null})}),uuid)for(const clickable of htmlQueryAll(leader,"[data-action=open-sheet]"))clickable.addEventListener("click",()=>fromUuid(uuid).then(a=>a?.sheet.render(!0)));const vacantEl=htmlQuery(leader,".vacant[title]");if(vacantEl){const lines=vacantEl.title.split(/;\s*/).map(l=>createHTMLElement("li",{children:[l]})),content=createHTMLElement("ul",{children:lines});$(vacantEl).tooltipster({content,contentAsHTML:!0,side:"right",theme:"crb-hover"})}}for(const rollableStat of htmlQueryAll(html,".rollable")){const statSlug=htmlClosest(rollableStat,"[data-statistic]")?.dataset.statistic;statSlug&&rollableStat.addEventListener("click",event2=>{this.actor.getStatistic(statSlug)?.roll(eventToRollParams(event2,{type:"check"}))})}htmlQuery(html,"[data-action=collect]")?.addEventListener("click",async()=>{ChatMessagePF2e.create({speaker:{...ChatMessagePF2e.getSpeaker(this.actor),alias:this.kingdom.name},content:await renderTemplate("systems/pf2e/templates/actors/party/kingdom/collection.hbs",{...calculateKingdomCollectionData(this.kingdom)})})}),this.filterActions(this.selectedFilter,{instant:!0}),htmlQuery(html,".filters")?.addEventListener("click",event2=>{const filterButton=htmlClosest(event2.target,".choice");filterButton&&this.filterActions(filterButton.dataset.slug??null)}),$html.find("[data-tooltip-content]").tooltipster({trigger:"click",arrow:!1,contentAsHTML:!0,debug:!1,interactive:!0,side:["right","bottom"],theme:"crb-hover",minWidth:120});for(const customModifierEl of htmlQueryAll(html,".modifiers-tooltip")){const stat=customModifierEl.dataset.stat;if(!stat)continue;for(const removeButton of htmlQueryAll(customModifierEl,"[data-action=remove-modifier]")){const slug=removeButton.dataset.slug??"";removeButton.addEventListener("click",()=>{this.kingdom.removeCustomModifier(stat,slug)})}const modifierValueEl=htmlQuery(customModifierEl,".add-modifier input[type=number]");htmlQuery(customModifierEl,"[data-action=increment]")?.addEventListener("click",()=>{modifierValueEl?.stepUp()}),htmlQuery(customModifierEl,"[data-action=decrement]")?.addEventListener("click",()=>{modifierValueEl?.stepDown()}),htmlQuery(customModifierEl,"[data-action=create-custom-modifier]")?.addEventListener("click",()=>{const modifier=modifierValueEl?.valueAsNumber||1,type=htmlQuery(customModifierEl,".add-modifier-type")?.value??"",label=htmlQuery(customModifierEl,".add-modifier-name")?.value?.trim()??game.i18n.localize(`PF2E.ModifierType.${type}`);if(!setHasElement(MODIFIER_TYPES,type)){ui.notifications.error("Type is required.");return}this.kingdom.addCustomModifier(stat,{label,modifier,type})})}htmlQuery(html,"[data-action=add-settlement]")?.addEventListener("click",()=>{const id=foundry.utils.randomID();this.#editingSettlements[id]=!0,this.focusElement=`[name="settlements.${id}.name"]`,this.kingdom.update({[`settlements.${id}`]:{}})});for(const settlementElement of htmlQueryAll(html,".settlement"))this.#activateSettlementEvents(settlementElement);for(const link of htmlQueryAll(html,"[data-action=browse-feats]")){const maxLevel=Number(link.dataset.level)||this.kingdom.level;link.addEventListener("click",async()=>{const compendiumTab=game.pf2e.compendiumBrowser.tabs.campaignFeature,filter2=await compendiumTab.getFilterData(),levels=filter2.sliders.level;levels.values.max=Math.min(maxLevel,levels.values.upperLimit),levels.isExpanded=levels.values.max!==levels.values.upperLimit,filter2.checkboxes.category.options["kingdom-feat"].selected=!0,filter2.checkboxes.category.selected.push("kingdom-feat"),filter2.checkboxes.category.isExpanded=!0,compendiumTab.open(filter2)})}htmlQuery(html,"[data-action=random-event]")?.addEventListener("click",()=>{new Statistic(this.actor,{slug:"random-event",label:"Random Kingdom Event",check:{type:"flat-check"}}).roll({dc:this.kingdom.event.dc})}),htmlQuery(html,"[data-action=reset-event-dc]")?.addEventListener("click",()=>{this.kingdom.update({event:{dc:16}})});const settlementList=htmlQuery(html,".settlement-list");settlementList&&Sortable.create(settlementList,{...SORTABLE_BASE_OPTIONS,handle:".drag-handle",onEnd:event2=>{const settlements=this.kingdom.settlements,settlementsWithIds=Object.entries(settlements).map(([id,value])=>({id,...value})),settlement=settlementsWithIds.find(s=>s.id===event2.item.dataset.settlementId),newIndex=event2.newDraggableIndex;if(!settlement||newIndex===void 0){this.render();return}const siblings=sortBy(settlementsWithIds.filter(s=>s!==settlement),s=>s.sort);siblings.splice(newIndex,0,settlement);const updates=mapToObj.indexed(siblings,(s,index)=>[`settlements.${s.id}.sort`,index]);this.kingdom.update(updates)}})}#activateSettlementEvents(settlementElement){const id=settlementElement.dataset.settlementId??null;if(id===null)return;const rerenderSettlement=__name2(async()=>{const settlement=this.kingdom.settlements[id];if(!settlement)return;const newHTML=await renderTemplate("systems/pf2e/templates/actors/party/kingdom/partials/settlement.hbs",{...await this.getData(),settlement:await this.#prepareSettlement(id,settlement)}),newElement=createHTMLElement("div",{innerHTML:newHTML}).firstElementChild;newElement instanceof HTMLElement&&(newElement.classList.toggle("expanded",settlementElement.classList.contains("expanded")),settlementElement.replaceWith(newElement),super.activateListeners($(newElement)),this.#activateSettlementEvents(newElement),this.#editingSettlements[id]&&!newElement.classList.contains("expanded")&&this.itemRenderer.toggleSummary(newElement,{visible:!0}))},"rerenderSettlement");htmlQuery(settlementElement,"[data-action=edit-settlement]")?.addEventListener("click",()=>{this.#editingSettlements[id]=!0,rerenderSettlement()}),htmlQuery(settlementElement,"[data-action=finish-settlement]")?.addEventListener("click",async()=>{this.#editingSettlements[id]=!1,await this.saveEditor(`settlements.${id}.description`),rerenderSettlement()}),htmlQuery(settlementElement,"[data-action=delete-settlement]")?.addEventListener("click",async event2=>{const settlement=this.kingdom.settlements[id];if(!settlement)return;(event2?.ctrlKey||await Dialog.confirm({title:game.i18n.localize("PF2E.DeleteItemTitle"),content:`
`})&&(await this.update({active:"building"}),KingdomBuilder.showToPlayers({uuid:this.actor.uuid}),new KingdomBuilder(this).render(!0));else{const type=this.active===!0?null:"builder";this.renderSheet({type})}}),[icon]}async collect(){const{formula,commodities}=calculateKingdomCollectionData(this),roll=await new Roll(formula).evaluate({async:!0});await roll.toMessage({flavor:game.i18n.localize("PF2E.Kingmaker.Kingdom.Resources.Points"),speaker:{...ChatMessagePF2e.getSpeaker(this.actor),alias:this.name}},{rollMode:"publicroll"}),this.update({resources:{points:roll.total,commodities:mapValues$1(commodities,(incoming,type)=>{const current=this.resources.commodities[type];return{value:Math.min(current.value+incoming,current.max)}})}})}async addCustomModifier(stat,data){if(stat.length===0)throw ErrorPF2e("A custom modifier's statistic must be a non-empty string");if(data.label.length===0)throw ErrorPF2e("A custom modifier's label must be a non-empty string");const modifiers=(this.toObject().customModifiers??{})[stat]??[];if(!modifiers.some(m=>m.label===data.label)){data.type=setHasElement(MODIFIER_TYPES,data.type)?data.type:"untyped";const modifier=new ModifierPF2e({...data,custom:!0}).toObject();await this.update({[`customModifiers.${stat}`]:[...modifiers,modifier]})}}async removeCustomModifier(stat,slug){if(stat.length===0)throw ErrorPF2e("A custom modifier's statistic must be a non-empty string");const modifiers=(this.toObject().customModifiers??{})[stat]??[];if(modifiers.length!==0)if(typeof slug=="string"){const withRemoved=modifiers.filter(m=>m.slug!==slug);await this.update({[`customModifiers.${stat}`]:withRemoved})}else throw ErrorPF2e("Custom modifiers can only be removed by slug (string) or index (number)")}async update(data){const expanded=foundry.utils.expandObject(data),updateData=foundry.utils.mergeObject(expanded,expanded.system?.campaign??{});delete updateData.system,await this.actor.update({"system.campaign":updateData}),updateData.level&&await this.updateFeatures(updateData.level)}prepareBaseData(){const{synthetics}=this.actor,{build}=this;if(!build.manual){for(const ability of KINGDOM_ABILITIES)this.abilities[ability].value=10;for(const category of["charter","heartland","government"]){const data=build[category],chosen=build.boosts[category];if(!data)continue;"flaw"in data&&data.flaw&&(this.abilities[data.flaw].value-=2);const activeBoosts=resolveKingdomBoosts(data,chosen);for(const ability of activeBoosts)this.abilities[ability].value+=this.abilities[ability].value>=18?1:2}const activeLevels=[1,5,10,15,20].filter(l=>this.level>=l);for(const level of activeLevels){const chosen=build.boosts[level].slice(0,2);for(const ability of chosen)this.abilities[ability].value+=this.abilities[ability].value>=18?1:2}}for(const ability of KINGDOM_ABILITIES)this.abilities[ability].mod=(this.abilities[ability].value-10)/2;if(build.government&&build.government.skills.length>0)for(const skill of build.government.skills)build.skills[skill].rank=Math.max(1,build.skills[skill].rank);const customModifiers=this.customModifiers??={};for(const selector of Object.keys(customModifiers)){const modifiers=customModifiers[selector]=customModifiers[selector].map(rawModifier=>new ModifierPF2e(rawModifier));(synthetics.modifiers[selector]??=[]).push(...modifiers.map(m=>()=>m))}const sizeData=Object.entries(KINGDOM_SIZE_DATA).findLast(([size])=>this.size>=Number(size))?.[1]??KINGDOM_SIZE_DATA[1];this.nationType=sizeData.type,this.resources.dice.faces=sizeData.faces,sizeData.controlMod&&(synthetics.modifiers["control-dc"]??=[]).push(()=>new ModifierPF2e({slug:"size",label:"Size Modifier",modifier:sizeData.controlMod}));for(const ability of KINGDOM_ABILITIES){const penalty=this.abilities[ability].penalty;penalty&&(synthetics.modifiers[`${ability}-based`]??=[]).push(()=>new ModifierPF2e({slug:"ruin",type:"item",label:KINGDOM_RUIN_LABELS[ability],modifier:penalty}))}for(const role of KINGDOM_LEADERSHIP){const data=this.leadership[role],actor=fromUuidSync(data.uuid??"");if(actor instanceof ActorPF2e?actor.hasPlayerOwner||(data.vacant=!1):data.vacant=!0,data.vacant){const penalties=VACANCY_PENALTIES[role]();for(const[selector,entries]of Object.entries(penalties.adjustments??{}))(synthetics.modifierAdjustments[selector]??=[]).push(...entries);for(const[selector,entries]of Object.entries(penalties.modifiers??{}))(synthetics.modifiers[selector]??=[]).push(...entries.map(e=>()=>new ModifierPF2e(e)))}if(data.invested){const ability=KINGDOM_LEADERSHIP_ABILITIES[role];(synthetics.modifiers[`${ability}-skill-check`]??=[]).push(()=>new ModifierPF2e({slug:"invested",label:"PF2E.Kingmaker.Kingdom.Invested",type:"status",modifier:1}))}}if(this.unrest.value>0){const modifier=-([1,5,10,15].findLastIndex(t=>this.unrest.value>=t)+1);(synthetics.modifiers["kingdom-check"]??=[]).push(()=>new ModifierPF2e({slug:"unrest",label:"PF2E.Kingmaker.Kingdom.Unrest",type:"status",modifier}))}const settlements=compact(Object.values(this.settlements));for(const settlement of settlements){if(!settlement)continue;const typeData=KINGDOM_SETTLEMENT_TYPE_DATA[settlement.type];settlement.consumption.base=typeData.consumption,settlement.consumption.total=Math.max(0,typeData.consumption-settlement.consumption.reduction)}for(const[type,value]of Object.entries(this.resources.commodities)){const settlementStorage=sumBy(settlements,s=>s.storage[type]);value.max=sizeData.storage+settlementStorage}}prepareDerivedData(){const{synthetics}=this.actor,{consumption,resources}=this;resources.dice.number=Math.max(0,this.level+4+resources.dice.bonus-resources.dice.penalty);const settlements=compact(Object.values(this.settlements));consumption.settlement=sumBy(settlements,s=>s.consumption.total);const computedConsumption=consumption.base+consumption.settlement+consumption.army-this.resources.workSites.food.value;consumption.value=Math.max(0,computedConsumption);const controlMod=CONTROL_DC_BY_LEVEL[Math.clamped(this.level-1,0,19)]-10;this.control=new Statistic(this.actor,{slug:"control",label:"PF2E.Kingmaker.Kingdom.ControlDC",domains:["control-dc"],modifiers:[new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:controlMod})]}),this.skills=mapToObj(KINGDOM_SKILLS,skill=>{const ability=KINGDOM_SKILL_ABILITIES[skill],abilityMod=this.abilities[ability].mod,rank=this.build.skills[skill].rank,domains=["kingdom-check",`${ability}-based`,`${ability}-skill-check`,skill],statistic=new Statistic(this.actor,{slug:skill,rank,label:KINGDOM_SKILL_LABELS[skill],domains,modifiers:[new ModifierPF2e({slug:ability,label:KINGDOM_ABILITY_LABELS[ability],modifier:abilityMod,type:"ability",adjustments:extractModifierAdjustments(synthetics.modifierAdjustments,domains,ability)}),createProficiencyModifier({actor:this.actor,rank,domains,level:this.level})],check:{type:"skill-check"}});return[skill,statistic]});const evenLevels=new Array(this.level).fill(0).map((_,idx)=>idx+1).filter(idx=>idx%2===0);this.features=new FeatGroup(this.actor,{id:"features",label:"Kingdom Features",level:this.level}),this.feats=new FeatGroup(this.actor,{id:"kingdom",label:"Kingdom Feats",slots:[{id:"government",label:"G"},...evenLevels],featFilter:["traits-kingdom"],level:this.level}),this.bonusFeats=new FeatGroup(this.actor,{id:"bonus",label:"PF2E.FeatBonusHeader",featFilter:["traits-kingdom"],level:this.level});const allFeatures=this.actor.itemTypes.campaignFeature,features=sortBy(allFeatures.filter(f=>f.isFeature),f=>f.level??1,f=>f.name),feats=sortBy(allFeatures.filter(f=>f.isFeat),f=>f.sort);for(const feature of features)this.features.assignFeat(feature);for(const feat of feats)this.feats.assignFeat(feat)||this.bonusFeats.assignFeat(feat)}getRollOptions(){const prefix="kingdom";return compact([this.unrest.value?`${prefix}:unrest:${this.unrest.value}`:null])}getRollData(){return{kingdom:this}}async importActivities({skipDialog=!1}={}){const pack=game.packs.get("pf2e.kingmaker-features");if(!pack)throw ErrorPF2e("Could not load kingdom features compendium");await this.updateFeatures(this.level);const documents=(await pack.getDocuments({type:"campaignFeature"})).filter(d=>d instanceof ItemPF2e&&d.isOfType("campaignFeature")).filter(d=>d.system.category==="kingdom-activity");await importDocuments(this.actor,documents,skipDialog)}async updateFeatures(level){const featuresToDelete=this.actor.itemTypes.campaignFeature.filter(f=>f.isFeature).filter(f=>(f.level??0)>level).map(f=>f.id),featuresToAdd=await(async()=>{const pack=game.packs.get("pf2e.kingmaker-features");return pack?(await pack.getDocuments({type:"campaignFeature"})).filter(d=>d instanceof ItemPF2e&&d.isOfType("campaignFeature")).filter(d=>d.system.category==="kingdom-feature").filter(d=>level>=(d.level??0)).filter(d=>!this.actor.items.some(i=>i.sourceId===d.uuid)).map(i=>i.toObject()):(console.error("PF2E System | Could not load kingdom features compendium"),[])})();await this.actor.deleteEmbeddedDocuments("Item",featuresToDelete),await this.actor.createEmbeddedDocuments("Item",featuresToAdd)}getStatistic(slug){return this.skills&&objectHasKey(this.skills,slug)?this.skills[slug]??null:null}renderSheet(options={}){options.type==="builder"?new KingdomBuilder(this).render(!0):new KingdomSheetPF2e(this.actor).render(!0,{tab:options.tab})}_preUpdate(changed){const actor=this.actor,feat=changed.build?.government?.feat;feat&&(console.log("Replacing feat"),fromUuid(feat).then(async f=>{if(!(f instanceof CampaignFeaturePF2e))return;const currentGovernmentFeat=actor.itemTypes.campaignFeature.find(f2=>f2.system.location==="government"),newFeat=f.clone({"system.location":"government"});await currentGovernmentFeat?.delete(),await actor.createEmbeddedDocuments("Item",[newFeat.toObject()])}))}}const BASIC_WAR_ACTIONS_FOLDER="Vqp8b64uH35zkncy",ALIGNMENTS=new Set(["LG","NG","CG","LN","N","CN","LE","NE","CE"]),ARMY_TYPES=["infantry","cavalry","siege","skirmisher"],ARMY_STATS={scouting:[0,7,8,9,11,12,14,15,16,18,19,21,22,23,25,26,28,29,30,32,33],standardDC:[0,15,16,18,19,20,22,23,24,26,27,28,30,31,32,34,35,36,38,39,40],ac:[0,16,18,19,21,22,24,25,27,28,30,31,33,34,36,37,39,40,42,43,45],strongSave:[0,10,11,12,14,15,17,18,19,21,22,24,25,26,28,29,30,32,33,35,36],weakSave:[0,4,5,6,8,9,11,12,13,15,16,18,19,20,22,23,25,26,27,29,30],attack:[0,9,11,12,14,15,17,18,20,21,23,24,26,27,29,30,32,33,35,36,38],maxTactics:[0,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6]};function getArmyGearData(){return{...mapToObj(["melee","ranged"],type=>[`additional-${type}`,{img:type==="melee"?"icons/weapons/axes/axe-battle-black.webp":"icons/weapons/crossbows/crossbow-simple-brown.webp",name:game.i18n.format("PF2E.Kingmaker.Army.Gear.AdditionalWeapon.Name",{type:game.i18n.format(`PF2E.Kingmaker.Army.Strikes.${type}`)}),description:"PF2E.Kingmaker.Army.Gear.AdditionalWeapon.Description",traits:["army"],level:1,price:10}]),...mapToObj(["melee","ranged"],type=>[type,{img:type==="melee"?"icons/weapons/axes/axe-battle-black.webp":"icons/weapons/crossbows/crossbow-simple-brown.webp",name:game.i18n.format("PF2E.Kingmaker.Army.Gear.MagicWeapons.Name",{type:game.i18n.format(`PF2E.Kingmaker.Army.Strikes.${type}`)}),description:"PF2E.Kingmaker.Army.Gear.MagicWeapons.Description",traits:["army","magical"],ranks:[{price:20,level:2},{price:40,level:10},{price:60,level:16}].map((d,idx)=>({...d,name:`PF2E.Kingmaker.Army.Gear.MagicWeapons.rank${idx+1}.Name`,description:`PF2E.Kingmaker.Army.Gear.MagicWeapons.rank${idx+1}.Description`}))}]),potions:{img:"icons/consumables/potions/bottle-round-corked-orante-red.webp",name:"PF2E.Kingmaker.Army.Gear.Potions.Name",description:"PF2E.Kingmaker.Army.Gear.Potions.Description",traits:["army","consumable","healing","magical","potion"],level:1,price:15},armor:{img:"icons/equipment/shield/heater-wooden-brown-axe.webp",name:game.i18n.localize("PF2E.Kingmaker.Army.Gear.Armor.Name"),description:game.i18n.localize("PF2E.Kingmaker.Army.Gear.Armor.Description"),traits:["army","magical"],ranks:[{price:25,level:5},{price:50,level:11},{price:75,level:18}].map((d,idx)=>({...d,name:`PF2E.Kingmaker.Army.Gear.Armor.rank${idx+1}.Name`,description:`PF2E.Kingmaker.Army.Gear.Armor.rank${idx+1}.Description`}))}}}__name(getArmyGearData,"getArmyGearData"),__name2(getArmyGearData,"getArmyGearData");class ArmyPF2e extends ActorPF2e{static{__name(this,"ArmyPF2e")}static{__name2(this,"ArmyPF2e")}get allowedItemTypes(){return["campaignFeature","effect"]}get underRoutThreshold(){return this.hitPoints.value<=this.system.attributes.hp.routThreshold}get kingdom(){if(this.alliance==="party"){const campaign=game.actors.party?.campaign;return campaign instanceof Kingdom?campaign:null}return null}get maxTactics(){return ARMY_STATS.maxTactics[this.level]}prepareBaseData(){super.prepareBaseData(),this.system.ac.value??=this._source.system.ac.value??=ARMY_STATS.ac[this.level],this.system.scouting??=this._source.system.scouting??=ARMY_STATS.scouting[this.level],this.system.details.level.value=Math.clamped(this.system.details.level.value,1,20),this.system.resources.potions.max=3,this.system.saves.strongSave=this.system.saves.maneuver>=this.system.saves.morale?"maneuver":"morale",this.system.traits.senses=[],this.system.details.alliance=this.hasPlayerOwner?"party":"opposition",this.rollOptions.all[`self:trait:${this.system.traits.type}`]=!0,this.rollOptions.all["self:under-rout-threshold"]=this.underRoutThreshold}prepareEmbeddedDocuments(){super.prepareEmbeddedDocuments();for(const rule of this.rules)rule.onApplyActiveEffects?.()}prepareDerivedData(){super.prepareDerivedData(),this.prepareSynthetics(),this.system.consumption=Math.max(0,this.system.consumption),this.itemTypes.campaignFeature.some(f=>f.slug==="darkvision")?this.system.traits.senses.push(new CreatureSensePF2e({type:"darkvision"})):this.itemTypes.campaignFeature.some(f=>f.slug==="low-light-vision")&&this.system.traits.senses.push(new CreatureSensePF2e({type:"lowLightVision"})),this.tactics=new FeatGroup(this,{id:"tactics",label:"PF2E.Kingmaker.Army.Tactics",slots:range(0,this.maxTactics).map(idx=>({id:String(idx),label:""}))}),this.bonusTactics=new FeatGroup(this,{id:"bonus",label:"PF2E.Kingmaker.Army.TacticsFree"});const expectedAC=ARMY_STATS.ac[this.level],acAdjustment=this.system.ac.value-expectedAC;this.armorClass=new ArmorStatistic(this,{modifiers:compact([new ModifierPF2e({slug:"base",label:"PF2E.Kingmaker.Army.Base",modifier:expectedAC-10}),acAdjustment&&new ModifierPF2e({slug:"adjustment",label:"PF2E.Kingmaker.Army.Adjustment",modifier:acAdjustment}),this.system.ac.potency&&new ModifierPF2e({slug:"potency",label:"Potency",modifier:this.system.ac.potency})])}).dc,this.system.ac.value=this.armorClass.value;const baseScouting=ARMY_STATS.scouting[this.level],scoutAdjustment=this.system.scouting-baseScouting;this.scouting=new Statistic(this,{slug:"scouting",label:"PF2E.Kingmaker.Army.Scouting",domains:["scouting"],modifiers:compact([new ModifierPF2e({slug:"base",label:"PF2E.Kingmaker.Army.Base",modifier:baseScouting}),scoutAdjustment?new ModifierPF2e({slug:"adjustment",label:"PF2E.Kingmaker.Army.Adjustment",modifier:scoutAdjustment}):null])}),this.system.scouting=this.scouting.mod;for(const saveType of["maneuver","morale"]){const baseValue=(this.system.saves.strongSave===saveType?ARMY_STATS.strongSave:ARMY_STATS.weakSave)[this.level],adjustment=this.system.saves[saveType]-baseValue;this[saveType]=new Statistic(this,{slug:saveType,label:`PF2E.Kingmaker.Army.Save.${saveType}`,domains:["saving-throw",saveType],modifiers:compact([new ModifierPF2e({slug:"base",label:"PF2E.Kingmaker.Army.Base",modifier:baseValue}),adjustment?new ModifierPF2e({slug:"adjustment",label:"PF2E.Kingmaker.Army.Adjustment",modifier:adjustment}):null])})}this.initiative=new ActorInitiative(this,{statistic:"scouting"}),this.strikes=flatMapToObj(["melee","ranged"],t=>this.system.weapons[t]?[[t,this.prepareArmyStrike(t)]]:[]);for(const tactic of this.itemTypes.campaignFeature.filter(i=>i.category==="army-tactic"))this.tactics.assignFeat(tactic)||this.bonusTactics.assignFeat(tactic)}async usePotion(){const newPotions=Math.max(0,this.system.resources.potions.value-1),newHP=Math.min(this.attributes.hp.value+1,this.attributes.hp.max);await this.update({"system.attributes.hp.value":newHP,"system.resources.potions.value":newPotions}),await ChatMessagePF2e.create({speaker:ChatMessagePF2e.getSpeaker({actor:this,token:this.token}),flavor:createHTMLElement("div",{children:[createHTMLElement("strong",{children:[game.i18n.localize("PF2E.Kingmaker.Army.Potions.UsedPotionHeader")]}),document.createElement("hr")]}).outerHTML,content:createHTMLElement("p",{children:[game.i18n.localize("PF2E.Kingmaker.Army.Potions.UsedPotionContent")]}).outerHTML,type:CONST.CHAT_MESSAGE_TYPES.EMOTE})}prepareArmyStrike(type){const synthetics=this.synthetics,data=this.system.weapons[type];if(data===null)return null;const attackDomains=["attack","attack-roll",`${type}-attack-roll`],maps=(()=>{const baseMap={slug:"multiple-attack-penalty",label:"PF2E.MultipleAttackPenalty",map1:-5,map2:-10},optionSet=new Set(this.getRollOptions(attackDomains)),maps2=this.synthetics.multipleAttackPenalties??{},fromSynthetics=attackDomains.flatMap(d=>maps2[d]??[]).filter(p=>p.predicate?.test(optionSet)??!0).map(p=>({slug:baseMap.slug,label:p.label,map1:p.penalty,map2:p.penalty*2}));return[baseMap,...fromSynthetics].reduce((lowest,p)=>p.map1>lowest.map1?p:lowest)})(),createMapModifier=__name2(prop=>new ModifierPF2e({slug:maps.slug,label:maps.label,modifier:maps[prop],adjustments:extractModifierAdjustments(synthetics.modifierAdjustments,attackDomains,maps.slug)}),"createMapModifier"),statistic=new Statistic(this,{slug:`${type}-strike`,label:data.name,domains:attackDomains,rollOptions:[`item:${type}`],check:{type:"attack-roll"},modifiers:compact([new ModifierPF2e({slug:"base",label:"PF2E.Kingmaker.Army.Base",modifier:ARMY_STATS.attack[this.level]}),data.potency&&new ModifierPF2e({slug:"potency",label:"Potency",modifier:data.potency}),new ModifierPF2e({slug:"concealed",label:"PF2E.Kingmaker.Army.Condition.concealed.name",type:"circumstance",modifier:-2,predicate:["target:effect:concealed"],hideIfDisabled:!0})])}),dealDamage=__name2(async(params={},outcome="success")=>{const targetToken=params.target??game.user.targets.first()??null,domains=["damage","strike-damage",`${type}-damage`],context=await this.getDamageRollContext({viewOnly:params.getFormula??!1,statistic:statistic.check,target:{token:targetToken},domains,outcome,checkContext:params.checkContext,options:new Set}),damageContext={type:"damage-roll",sourceType:"attack",self:context.self,target:context.target,outcome,options:context.options,domains,...eventToRollParams(params.event,{type:"damage"})},{formula,breakdown}=createDamageFormula({base:[{modifier:outcome==="success"?1:2,damageType:"untyped",category:null}],modifiers:extractModifiers(context.self.actor.synthetics,domains,{test:context.options}),dice:extractDamageDice(context.self.actor.synthetics.damageDice,domains,{test:context.options,resolvables:{target:context.target?.actor??null}}),ignoredResistances:[]}),template={name:"Army damage",materials:[],modifiers:[],damage:{roll:new DamageRoll(formula),breakdown}};return DamagePF2e.roll(template,damageContext)},"dealDamage");return{slug:`${type}-strike`,label:data.name,type:"strike",glyph:"A",variants:[0,1,2].map(idx=>{const mapModifier=idx===0?null:createMapModifier(`map${idx}`),penalty=mapModifier?.modifier??0;return{label:idx===0?signedInteger(statistic.mod):game.i18n.format("PF2E.MAPAbbreviationValueLabel",{value:signedInteger(statistic.mod+penalty),penalty}),mod:statistic.mod,roll:async params=>{const targetToken=params.target??game.user.targets.find(t=>!!t.actor?.isOfType("army")),roll=await statistic.roll({identifier:type,action:"army-strike",melee:type==="melee",modifiers:mapModifier?[mapModifier]:[],target:targetToken?.actor,dc:{slug:"ac"},damaging:!0,extraRollOptions:["origin:action:slug:army-strike"],...eventToRollParams(params.event,{type:"check"})});if(roll&&type==="ranged"){const newAmmo=Math.max(0,this.system.resources.ammunition.value-1);this.update({"system.resources.ammunition.value":newAmmo})}return roll}}}),damage:params=>dealDamage(params,"success"),critical:params=>dealDamage(params,"criticalSuccess")}}updateLevel(newLevel){newLevel=Math.clamped(newLevel,1,20);const currentLevel=this.system.details.level.value,strongSave=this.system.saves.strongSave,strongSaveDifference=ARMY_STATS.strongSave[newLevel]-ARMY_STATS.strongSave[currentLevel],weakSaveDifference=ARMY_STATS.weakSave[newLevel]-ARMY_STATS.weakSave[currentLevel];return this.update({system:{ac:{value:this.system.ac.value+(ARMY_STATS.ac[newLevel]-ARMY_STATS.ac[currentLevel])},details:{level:{value:newLevel}},saves:{maneuver:this.system.saves.maneuver+(strongSave==="maneuver"?strongSaveDifference:weakSaveDifference),morale:this.system.saves.morale+(strongSave==="morale"?strongSaveDifference:weakSaveDifference)},scouting:this.system.scouting+(ARMY_STATS.scouting[newLevel]-ARMY_STATS.scouting[currentLevel])}})}checkItemValidity(source){if(source.type==="campaignFeature"&&source.system?.category==="army-tactic"){const validArmyTypes=ARMY_TYPES.filter(t=>source.system?.traits?.value?.includes(t));if(validArmyTypes.length>0&&!validArmyTypes.includes(this.system.traits.type))return ui.notifications.error(game.i18n.format("PF2E.Kingmaker.Army.Error.InvalidTacticType",{name:source.name,type:game.i18n.localize(CONFIG.PF2E.kingmakerTraits[this.system.traits.type])})),!1}return super.checkItemValidity(source)}getStatistic(slug){return tupleHasValue(["scouting","morale","maneuver"],slug)?this[slug]:this.kingdom?.getStatistic(slug)??super.getStatistic(slug)}_preUpdate(changed,options,user){if(typeof changed?.system?.attributes?.hp?.value=="number"){const max=Number(changed.system.attributes.hp.max??this.system.attributes.hp.max);changed.system.attributes.hp.value=Math.clamped(changed.system.attributes.hp.value,0,max)}return super._preUpdate(changed,options,user)}}class HazardPF2e extends ActorPF2e{static{__name(this,"HazardPF2e")}static{__name2(this,"HazardPF2e")}get allowedItemTypes(){return[...super.allowedItemTypes,"action","melee"]}get rarity(){return this.system.traits.rarity}get isComplex(){return this.system.details.isComplex}get hardness(){return Math.abs(this.system.attributes.hardness)}get hasDefenses(){return!!(this.hitPoints?.max||this.attributes.ac.value)}get canAttack(){return this.itemTypes.melee.length>0}get emitsSound(){const{emitsSound}=this.system.attributes;return!this.isDead&&typeof emitsSound=="boolean"?emitsSound:!!game.combats.active?.started&&game.combats.active.combatants.some(c=>c.actor===this)}isAffectedBy(effect){const damageType=objectHasKey(CONFIG.PF2E.damageTypes,effect)?effect:isObject(effect)?effect.system.persistent?.damageType??null:null;if(!this.system.attributes.hasHealth&&damageType)return!1;const{weaknesses,resistances}=this.system.attributes;return damageType&&["vitality","void"].includes(damageType)?weaknesses.some(w=>w.type===damageType)||resistances.some(r=>r.type===damageType):super.isAffectedBy(effect)}prepareBaseData(){super.prepareBaseData();const{attributes,details}=this.system;if(attributes.hp.negativeHealing=!1,attributes.hp.brokenThreshold=Math.floor(attributes.hp.max/2),attributes.hasHealth=attributes.hp.max>0,attributes.immunities.some(i=>i.type==="object-immunities")||attributes.immunities.unshift(new Immunity({type:"object-immunities",source:"TYPES.Actor.hazard"})),this.isComplex){attributes.stealth.value??=0;const partialAttributes=this.system.attributes;partialAttributes.initiative={statistic:"stealth",tiebreakPriority:this.hasPlayerOwner?2:1}}details.alliance=null}prepareDerivedData(){super.prepareDerivedData();const{system}=this;if(this.prepareSynthetics(),setHitPointsRollOptions(this),this.skills={stealth:new Statistic(this,{slug:"stealth",label:CONFIG.PF2E.skillList.stealth,domains:["stealth","dex-based","skill-check","dex-skill-check","all"],modifiers:[new ModifierPF2e({label:"PF2E.ModifierTitle",slug:"base",type:"untyped",modifier:system.attributes.stealth.value??0})],check:{type:"skill-check"}})},system.attributes.initiative&&(this.initiative=new ActorInitiative(this,{statistic:"stealth"}),system.attributes.initiative=this.initiative.getTraceData()),this.hasDefenses){const baseModifier=new ModifierPF2e({slug:"base",label:"PF2E.BaseModifier",modifier:system.attributes.ac.value-10}),statistic=new ArmorStatistic(this,{rank:1,modifiers:[baseModifier]});this.armorClass=statistic.dc,system.attributes.ac=statistic.getTraceData()}this.saves=this.prepareSaves(),this.system.actions=this.itemTypes.melee.map(m=>strikeFromMeleeItem(m))}prepareData(){super.prepareData();const weaknessesAndResistances=new Set([this.system.attributes.weaknesses.map(w=>w.type),this.system.attributes.resistances.map(r=>r.type)].flat()),objectImmunities=this.system.attributes.immunities.find(i=>i.type==="object-immunities");for(const wrType of["bleed","mental","poison","spirit"])weaknessesAndResistances.has(wrType)&&objectImmunities?.exceptions.push(wrType)}prepareSaves(){const{system}=this;return SAVE_TYPES.reduce((saves,saveType)=>{const save=system.saves[saveType],label=game.i18n.localize(CONFIG.PF2E.saves[saveType]),base=save.value;if(!base)return saves;const statistic=new Statistic(this,{slug:saveType,label,attribute:CONFIG.PF2E.savingThrowDefaultAttributes[saveType],domains:[saveType,"saving-throw"],modifiers:[new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:base})],check:{type:"saving-throw"}});return this.system.saves[saveType]=foundry.utils.mergeObject(save,statistic.getTraceData()),saves[saveType]=statistic,saves},{})}}class LootPF2e extends ActorPF2e{static{__name(this,"LootPF2e")}static{__name2(this,"LootPF2e")}armorClass=null;get allowedItemTypes(){return["physical"]}get isLoot(){return this.system.lootSheetType==="Loot"}get isMerchant(){return this.system.lootSheetType==="Merchant"}get hiddenWhenEmpty(){return this.isLoot&&this.system.hiddenWhenEmpty}get canHostRuleElements(){return!1}get canAct(){return!1}isAffectedBy(){return!1}get visible(){return this.permission>=CONST.DOCUMENT_OWNERSHIP_LEVELS.OBSERVER}canUserModify(user,action2){return action2==="update"?this.permission>=CONST.DOCUMENT_OWNERSHIP_LEVELS.LIMITED:super.canUserModify(user,action2)}async transferItemToActor(targetActor,item,quantity,containerId,newStack=!1){if(!(this.isOwner&&targetActor.isOwner))return super.transferItemToActor(targetActor,item,quantity,containerId,newStack);if(this.isMerchant&&item.isOfType("physical")){const itemValue=CoinsPF2e.fromPrice(item.price,quantity);if(await targetActor.inventory.removeCoins(itemValue))return await item.actor.inventory.addCoins(itemValue),super.transferItemToActor(targetActor,item,quantity,containerId,newStack);if(this.isLoot)throw ErrorPF2e("Loot transfer failed");return null}return super.transferItemToActor(targetActor,item,quantity,containerId,newStack)}async toggleTokenHiding(){if(!this.hiddenWhenEmpty||!this.isOwner)return;const hiddenStatus=this.items.size===0,promises=game.scenes.map(s=>[s,s.tokens.filter(t=>t.actor===this)]).map(([scene,tokenDocs])=>scene.updateEmbeddedDocuments("Token",tokenDocs.map(tokenDoc=>({_id:tokenDoc.id,hidden:hiddenStatus}))));await Promise.allSettled(promises)}prepareDerivedData(){this.rules=[],super.prepareDerivedData()}_onCreate(data,options,userId){game.user.id===userId&&this.toggleTokenHiding(),super._onCreate(data,options,userId)}_onUpdate(changed,options,userId){game.user.id===userId&&changed.system?.hiddenWhenEmpty!==void 0&&this.toggleTokenHiding(),super._onUpdate(changed,options,userId)}_onCreateDescendantDocuments(parent,collection,documents,result,options,userId){game.user.id===userId&&this.toggleTokenHiding(),super._onCreateDescendantDocuments(parent,collection,documents,result,options,userId)}_onDeleteDescendantDocuments(parent,collection,documents,ids,options,userId){game.user.id===userId&&this.toggleTokenHiding(),super._onDeleteDescendantDocuments(parent,collection,documents,ids,options,userId)}}const{DataModel}=foundry.abstract;class InvalidCampaign extends DataModel{static{__name(this,"InvalidCampaign")}static{__name2(this,"InvalidCampaign")}type="invalid";actor;options;constructor(actor,options){super(),this.actor=actor,this.options=options}static defineSchema(){return{}}createSidebarButtons(){const icon=createHTMLElement("a",{children:[fontAwesomeIcon("warning",{fixedWidth:!0})]});return icon.title=game.i18n.localize("PF2E.Actor.Party.InvalidCampaign.Hint"),game.user.isGM?icon.addEventListener("click",()=>{new Dialog({title:game.i18n.format("PF2E.Actor.Party.InvalidCampaign.Title",{party:this.actor.name}),content:game.i18n.format(`PF2E.Actor.Party.InvalidCampaign.Message.${this.options.reason}`,{current:this.actor.system.campaign?.type??"",...this.options}),buttons:{yes:{icon:fontAwesomeIcon("trash").outerHTML,label:game.i18n.localize("Yes"),callback:async()=>{await this.actor.update({"system.-=campaign":null}),ui.sidebar.render()}},cancel:{icon:fontAwesomeIcon("times").outerHTML,label:game.i18n.localize("Cancel")}}}).render(!0)}):icon.style.pointerEvents="none",[icon]}}class PartyPF2e extends ActorPF2e{static{__name(this,"PartyPF2e")}static{__name2(this,"PartyPF2e")}armorClass=null;get active(){return game.actors.party===this}get baseAllowedItemTypes(){return["physical"]}get allowedItemTypes(){return[...this.baseAllowedItemTypes,...this.campaign?.extraItemTypes??[]]}get canAct(){return!1}canUserModify(user,action2){return super.canUserModify(user,action2)||action2==="update"&&this.members.some(m=>m.canUserModify(user,action2))}isAffectedBy(){return!1}validate(options){if(!super.validate(options))return!1;const changes=options?.changes??{};return!(changes.system?.campaign&&!this.campaign?.validate({...options,changes:changes.system.campaign}))}updateSource(data,options){if(!this.campaign)return super.updateSource(data,options);const expanded=foundry.utils.expandObject(data??{}),campaignDiff=expanded?.system?.campaign?this.campaign.updateSource(expanded.system.campaign,options):{},diff=super.updateSource(data,options);return isEmpty(campaignDiff)?diff:foundry.utils.mergeObject(diff,campaignDiff)}prepareRuleElements(){return this.items.contents.filter(item=>!item.isOfType("physical")).flatMap(item=>item.prepareRuleElements()).filter(rule=>!rule.ignored).sort((elementA,elementB)=>elementA.priority-elementB.priority)}_initialize(options){super._initialize(options),Object.defineProperty(this.system,"campaign",{writable:!0,enumerable:!1})}prepareBaseData(){this.system.details.level={value:0},super.prepareBaseData(),this.members=this.system.details.members.map(m=>fromUuidSync(m.uuid)).filter(a=>a instanceof ActorPF2e&&a.isOfType("creature")).sort((a,b)=>a.name.localeCompare(b.name,game.i18n.lang));for(const member of this.members)member?.parties.add(this);this.system.details.alliance=this.members.some(m=>m.alliance==="party")?"party":this.members.some(m=>m.alliance==="opposition")?"opposition":null;const campaignType=game.settings.get("pf2e","campaignType");if(campaignType!=="none"){const typeMatches=this.system.campaign?.type===campaignType;if(this.system.campaign&&!typeMatches)this.campaign=new InvalidCampaign(this,{campaignType,reason:"mismatch"});else try{this.campaign?.type!==campaignType?this.campaign=new Kingdom(foundry.utils.deepClone(this._source.system.campaign),{parent:this}):(Kingdom.cleanData(this.campaign._source),this.campaign.reset()),this.campaign.prepareBaseData?.(),this.system.campaign=this.campaign}catch(err){console.error(err),this.campaign=new InvalidCampaign(this,{campaignType,reason:"error"})}}else this.campaign=null;const partyLevel=Math.round(meanBy(this.members.filter(m=>m.isOfType("character")),m=>m.level));this.system.details.level.value=partyLevel}prepareEmbeddedDocuments(){super.prepareEmbeddedDocuments();for(const rule of this.rules)rule.onApplyActiveEffects?.()}prepareDerivedData(){super.prepareDerivedData();const travelSpeed=Math.min(...this.members.map(m=>m.attributes.speed.total));this.attributes.speed={total:travelSpeed},this.prepareSynthetics(),this.campaign?.prepareDerivedData?.()}async addMembers(...membersToAdd){const existing=this.system.details.members.filter(d=>this.members.some(m=>m.uuid===d.uuid)),existingUUIDs=new Set(existing.map(data=>data.uuid)),newMembers=membersToAdd.filter(a=>a.uuid.startsWith("Actor.")&&!existingUUIDs.has(a.uuid));for(const member of newMembers){const allianceUpdate=member.isOfType("character","npc")?{"system.details.alliance":member._source.system.details.alliance??"party"}:{};await member.update({folder:null,...allianceUpdate})}const members=[...existing,...newMembers.map(m=>({uuid:m.uuid}))];await this.update({system:{details:{members}}}),await resetActors(newMembers)}async removeMembers(...remove2){const uuids=remove2.map(d=>typeof d=="string"?d:d.uuid),members=this.system.details.members.filter(d=>this.members.some(m=>m.uuid===d.uuid)).filter(m=>!tupleHasValue(uuids,m.uuid));await this.update({system:{details:{members}}})}async addToCombat(options={}){const promises=this.members.map(a=>CombatantPF2e.fromActor(a,!0,{combat:options.combat}));return(await Promise.all(promises)).filter(c=>!!c)}getRollOptions(domains){return super.getRollOptions(domains).concat(this.campaign?.getRollOptions?.()??[])}getRollData(){return foundry.utils.mergeObject(super.getRollData(),this.campaign?.getRollData?.()??{})}reset({actor=!1}={}){actor?this._resetAndRerenderDebounced():super.reset()}getStatistic(slug){const statistic=super.getStatistic(slug);return statistic||(this.campaign?.getStatistic?.(slug)??null)}_resetAndRerenderDebounced=foundry.utils.debounce(()=>{super.reset(),this.sheet.render(!1,{actor:!0})},50);async _preUpdate(changed,options,user){const members=this.members,newMemberUUIDs=changed?.system?.details?.members?.map(m=>m?.uuid);if(newMemberUUIDs){const deletedMembers=members.filter(m=>m?.uuid&&!newMemberUUIDs.includes(m.uuid));options.removedMembers=deletedMembers.map(m=>m.uuid)}return changed.system?.campaign&&this.campaign&&this.campaign.type!=="invalid"&&(changed.system.campaign.type=this.campaign.type,this.campaign._preUpdate?.(changed.system.campaign)),super._preUpdate(changed,options,user)}_onUpdate(changed,options,userId){super._onUpdate(changed,options,userId);const removedCreatures=(options.removedMembers??[]).map(uuid=>fromUuidSync(uuid)).filter(a=>a instanceof ActorPF2e&&a.isOfType("creature"));for(const actor of removedCreatures)actor.parties.delete(this);if(resetActors(removedCreatures),changed.system?.details?.members&&game.combat)for(const encounter of game.combats)encounter.reset(),ui.combat.render();game.ready&&changed.system?.campaign&&game.actors.get(this.id)===this&&ui.actors.render()}_onDelete(options,userId){super._onDelete(options,userId);for(const member of this.members)member.parties.delete(this);resetActors(this.members),ui.actors.saveActivePartyFolderState()}}class VehiclePF2e extends ActorPF2e{static{__name(this,"VehiclePF2e")}static{__name2(this,"VehiclePF2e")}get allowedItemTypes(){return[...super.allowedItemTypes,"physical","action"]}get dimensions(){return{length:this.system.details.space.long,width:this.system.details.space.wide,height:this.system.details.space.high}}get hardness(){return this.system.attributes.hardness}getTokenDimensions(dimensions=this.dimensions){return{width:Math.max(Math.round(dimensions.width/5),1),height:Math.max(Math.round(dimensions.length/5),1)}}prepareBaseData(){super.prepareBaseData(),this.system.details.alliance=null;const{size}=this.system.traits,{dimensions}=this;if(size.length=dimensions.length,size.width=dimensions.width,this.prototypeToken.flags?.pf2e?.linkToActorSize){const{width,height}=this.getTokenDimensions();this.prototypeToken.width=width,this.prototypeToken.height=height}}prepareEmbeddedDocuments(){super.prepareEmbeddedDocuments();for(const rule of this.rules)rule.onApplyActiveEffects?.()}prepareDerivedData(){if(super.prepareDerivedData(),this.prepareSynthetics(),this.hasCondition("broken"))for(const selector of["ac","saving-throw"]){const modifiers=this.synthetics.modifiers[selector]??=[],brokenModifier=new ModifierPF2e({slug:"broken",label:"PF2E.ConditionTypeBroken",modifier:-2,adjustments:extractModifierAdjustments(this.synthetics.modifierAdjustments,[selector],"broken")});modifiers.push(()=>brokenModifier)}const{attributes}=this,hitPoints=new HitPointsStatistic(this,{baseMax:attributes.hp.max});attributes.hp=foundry.utils.mergeObject(hitPoints.getTraceData(),{brokenThreshold:Math.floor(hitPoints.max/2)}),setHitPointsRollOptions(this);const armorStatistic=new ArmorStatistic(this,{modifiers:[new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:this.system.attributes.ac.value-10,adjustments:extractModifierAdjustments(this.synthetics.modifierAdjustments,["all","ac"],"base")})]});this.armorClass=armorStatistic.dc,this.system.attributes.ac=armorStatistic.getTraceData(),this.prepareSaves()}prepareSaves(){const{synthetics}=this,slug="fortitude",domains=[slug,"saving-throw","all"],modifiers=[new ModifierPF2e({label:"PF2E.ModifierTitle",slug,type:"untyped",modifier:this.system.saves.fortitude.value}),...extractModifiers(synthetics,domains)],fortitude=new Statistic(this,{slug:"fortitude",label:CONFIG.PF2E.saves.fortitude,modifiers,domains,check:{type:"saving-throw"}});this.saves={fortitude},this.system.saves.fortitude=foundry.utils.mergeObject(this.system.saves.fortitude,fortitude.getTraceData())}async _preUpdate(changed,options,user){const result=await super._preUpdate(changed,options,user);if(result===!1)return result;if(this.prototypeToken.flags?.pf2e?.linkToActorSize){const{space}=this.system.details,spaceUpdates={width:changed.system?.details?.space?.wide??space.wide,length:changed.system?.details?.space?.long??space.long},tokenDimensions=this.getTokenDimensions(spaceUpdates);if(changed.prototypeToken=foundry.utils.mergeObject(changed.prototypeToken??{},tokenDimensions),canvas.scene){const updates=this.getActiveTokens().filter(token=>token.document.linkToActorSize).map(token=>({_id:token.id,...tokenDimensions}));await TokenDocumentPF2e.updateDocuments(updates,{parent:canvas.scene})}}}}function extractModifiers(synthetics,selectors,options={}){const{modifierAdjustments,modifiers:syntheticModifiers}=synthetics,modifiers=Array.from(new Set(selectors)).flatMap(s=>syntheticModifiers[s]??[]).flatMap(d=>d(options)??[]);for(const modifier of modifiers)modifier.adjustments=extractModifierAdjustments(modifierAdjustments,selectors,modifier.slug);return modifiers}__name(extractModifiers,"extractModifiers"),__name2(extractModifiers,"extractModifiers");function extractModifierAdjustments(adjustmentsRecord,selectors,slug){return Array.from(new Set(selectors.flatMap(s=>adjustmentsRecord[s]??[]))).filter(a=>[slug,null].includes(a.slug))}__name(extractModifierAdjustments,"extractModifierAdjustments"),__name2(extractModifierAdjustments,"extractModifierAdjustments");function extractNotes(rollNotes,selectors){return selectors.flatMap(s=>(rollNotes[s]??[]).map(n=>n.clone()))}__name(extractNotes,"extractNotes"),__name2(extractNotes,"extractNotes");function extractDamageDice(deferredDice,selectors,options){return selectors.flatMap(s=>deferredDice[s]??[]).flatMap(d=>d(options)??[])}__name(extractDamageDice,"extractDamageDice"),__name2(extractDamageDice,"extractDamageDice");function processDamageCategoryStacking(base,options){const{dice}=options,groupedModifiers=groupBy$1(options.modifiers,m=>m.category==="persistent"?"persistent":"main"),modifiers=[...new StatisticModifier("damage",groupedModifiers.main??[],options.test).modifiers,...new StatisticModifier("persistent",groupedModifiers.persistent??[],options.test).modifiers],allPersistent=base.length>0&&base.every(b=>b.category==="persistent");return{modifiers:allPersistent?modifiers.filter(m=>m.category==="persistent"):modifiers,dice:allPersistent?dice.filter(m=>m.category==="persistent"):dice}}__name(processDamageCategoryStacking,"processDamageCategoryStacking"),__name2(processDamageCategoryStacking,"processDamageCategoryStacking");async function extractEphemeralEffects({affects,origin,target,item,domains,options}){if(!(origin&&target))return[];const[effectsFrom,effectsTo]=affects==="target"?[origin,target]:[target,origin],fullOptions=[...options,effectsFrom.getRollOptions(domains),effectsTo.getSelfRollOptions(affects)].flat(),resolvables=item?item.isOfType("spell")?{spell:item}:{weapon:item}:{};return(await Promise.all(domains.flatMap(s=>effectsFrom.synthetics.ephemeralEffects[s]?.[affects]??[]).map(d=>d({test:fullOptions,resolvables})))).flatMap(e=>e??[])}__name(extractEphemeralEffects,"extractEphemeralEffects"),__name2(extractEphemeralEffects,"extractEphemeralEffects");function extractRollTwice(rollTwices,selectors,options){const twices=selectors.flatMap(s=>rollTwices[s]??[]).filter(rt=>rt.predicate?.test(options)??!0);return twices.length===0||twices.some(rt=>rt.keep==="higher")&&twices.some(rt=>rt.keep==="lower")?!1:twices.at(0)?.keep==="higher"?"keep-higher":"keep-lower"}__name(extractRollTwice,"extractRollTwice"),__name2(extractRollTwice,"extractRollTwice");function extractRollSubstitutions(substitutions,domains,rollOptions){return domains.flatMap(d=>foundry.utils.deepClone(substitutions[d]??[])).filter(s=>s.predicate?.test(rollOptions)??!0)}__name(extractRollSubstitutions,"extractRollSubstitutions"),__name2(extractRollSubstitutions,"extractRollSubstitutions");function extractDegreeOfSuccessAdjustments(synthetics,selectors){return Object.values(pick(synthetics.degreeOfSuccessAdjustments,selectors)).flat()}__name(extractDegreeOfSuccessAdjustments,"extractDegreeOfSuccessAdjustments"),__name2(extractDegreeOfSuccessAdjustments,"extractDegreeOfSuccessAdjustments");function isBracketedValue(value){return isObject$1(value)&&Array.isArray(value.brackets)}__name(isBracketedValue,"isBracketedValue"),__name2(isBracketedValue,"isBracketedValue");async function processPreUpdateActorHooks(changed,{pack}){const actorId=String(changed._id),actor=pack?await game.packs.get(pack)?.getDocument(actorId):game.actors.get(actorId);if(!(actor instanceof ActorPF2e))return;const rules=actor.rules.filter(r=>!!r.preUpdateActor);if(rules.length===0)return;actor.flags.pf2e.rollOptions=actor.clone(changed,{keepId:!0}).flags.pf2e.rollOptions;const createDeletes=(await Promise.all(rules.map(r=>actor.items.has(r.item.id)?r.preUpdateActor():new Promise(()=>({create:[],delete:[]}))))).reduce((combined,cd)=>(combined.create.push(...cd.create),combined.delete.push(...cd.delete),combined),{create:[],delete:[]});createDeletes.delete=uniq(createDeletes.delete).filter(id=>actor.items.has(id)),createDeletes.create.length>0&&await actor.createEmbeddedDocuments("Item",createDeletes.create,{keepId:!0,render:!1}),createDeletes.delete.length>0&&await actor.deleteEmbeddedDocuments("Item",createDeletes.delete,{render:!1})}__name(processPreUpdateActorHooks,"processPreUpdateActorHooks"),__name2(processPreUpdateActorHooks,"processPreUpdateActorHooks");const PROFICIENCY_RANK_OPTION=["proficiency:untrained","proficiency:trained","proficiency:expert","proficiency:master","proficiency:legendary"];function ensureProficiencyOption(options,rank){rank>=0&&options.add(`skill:rank:${rank}`).add(PROFICIENCY_RANK_OPTION[rank])}__name(ensureProficiencyOption,"ensureProficiencyOption"),__name2(ensureProficiencyOption,"ensureProficiencyOption");const MODIFIER_TYPES=new Set(["ability","circumstance","item","potency","proficiency","status","untyped"]);class ModifierPF2e{static{__name(this,"ModifierPF2e")}static{__name2(this,"ModifierPF2e")}slug;label;modifier;#originalValue;type;ability;adjustments;force;enabled;ignored;rule;source;custom;damageType;damageCategory;predicate;critical;traits;hideIfDisabled;kind;constructor(...args){const params=__name2(args2=>typeof args2[0]=="string","isLegacyParams")(args)?{label:args[0],modifier:args[1],type:args[2]??"untyped",enabled:args[3],ignored:args[4],source:args[5]}:args[0];if(this.label=game.i18n.localize(params.label??params.name),this.slug=sluggify(params.slug??this.label),this.#originalValue=this.modifier=params.modifier,this.type=setHasElement(MODIFIER_TYPES,params.type)?params.type:"untyped",this.ability=params.ability??null,this.force=params.force??!1,this.adjustments=foundry.utils.deepClone(params.adjustments??[]),this.enabled=params.enabled??!0,this.ignored=params.ignored??!1,this.custom=params.custom??!1,this.source=params.source??null,this.predicate=new PredicatePF2e(params.predicate??[]),this.traits=foundry.utils.deepClone(params.traits??[]),this.hideIfDisabled=params.hideIfDisabled??!1,this.modifier=params.modifier,this.rule=params.rule??null,Object.defineProperty(this,"rule",{enumerable:!1}),this.damageType=objectHasKey(CONFIG.PF2E.damageTypes,params.damageType)?params.damageType:null,this.damageCategory=this.damageType==="bleed"?"persistent":params.damageCategory??null,this.critical=this.damageCategory==="splash"?!!params.critical:params.critical??null,this.kind=(()=>this.modifier>=0&&!["ability","untyped"].includes(this.type)?"bonus":this.modifier<0&&this.type!=="ability"?"penalty":"modifier")(),this.force&&this.type==="untyped")throw ErrorPF2e("A forced modifier must have a type")}get category(){return this.damageCategory}get value(){return this.kind==="penalty"&&this.modifier===0?-this.modifier:this.modifier}get signedValue(){return this.modifier===0&&this.kind==="penalty"?signedInteger(-this.modifier):signedInteger(this.modifier)}clone(options={}){const clone=this.modifier===this.#originalValue?new ModifierPF2e(this):new ModifierPF2e({...this,modifier:this.#originalValue});return options.test&&clone.test(options.test),clone}getRollOptions(){const options=["slug","type","value"].map(p=>`${this.kind}:${p}:${this[p]}`);return this.type==="ability"&&this.ability&&options.push(`modifier:ability:${this.ability}`),new Set(options)}test(options){if(this.predicate.length===0)return;const rollOptions=this.rule?[...options,...this.rule.item.getRollOptions("parent")]:options;this.ignored=!this.predicate.test(rollOptions)}toObject(){return foundry.utils.deepClone({...this,predicate:[...this.predicate],rule:this.rule?.toObject(),item:void 0})}toString(){return this.label}}function createAttributeModifier({actor,attribute,domains,max}){const withAttributeBased=domains.includes(`${attribute}-based`)?domains:[...domains,`${attribute}-based`],modifierValue=actor.abilities[attribute].mod,cappedValue=Math.min(modifierValue,max??modifierValue);return new ModifierPF2e({slug:attribute,label:CONFIG.PF2E.abilities[attribute],modifier:cappedValue,type:"ability",ability:attribute,adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,withAttributeBased,attribute)})}__name(createAttributeModifier,"createAttributeModifier"),__name2(createAttributeModifier,"createAttributeModifier");function createProficiencyModifier({actor,rank,domains,level,addLevel}){rank=Math.clamped(rank,0,4),addLevel??=rank>0;const pwolVariant=game.pf2e.settings.variants.pwol.enabled,baseBonuses=pwolVariant?game.pf2e.settings.variants.pwol.modifiers:[0,2,4,6,8],addedLevel=addLevel&&!pwolVariant?level??actor.level:0,bonus=baseBonuses[rank]+addedLevel;return new ModifierPF2e({slug:"proficiency",label:`PF2E.ProficiencyLevel${rank}`,modifier:bonus,type:"proficiency",adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,domains,"proficiency")})}__name(createProficiencyModifier,"createProficiencyModifier"),__name2(createProficiencyModifier,"createProficiencyModifier");const HIGHER_BONUS=__name2((a,b)=>a.modifier>=b.modifier,"HIGHER_BONUS"),LOWER_PENALTY=__name2((a,b)=>a.modifier<=b.modifier,"LOWER_PENALTY");function applyStacking(best,modifier,isBetter){const existing=best[modifier.type];return existing===void 0?(modifier.enabled=!0,best[modifier.type]=modifier,modifier.modifier):isBetter(modifier,existing)?(existing.enabled=!1,modifier.enabled=!0,best[modifier.type]=modifier,modifier.modifier-existing.modifier):(modifier.enabled=!1,0)}__name(applyStacking,"applyStacking"),__name2(applyStacking,"applyStacking");function applyStackingRules(modifiers){let total=0;const highestBonus={},lowestPenalty={},abilityModifiers=modifiers.filter(m=>m.type==="ability"&&!m.ignored),bestAbility=abilityModifiers.reduce((best,modifier)=>best===null||modifier.force?modifier:best.force?best:modifier.modifier>best.modifier?modifier:best,null);for(const modifier of abilityModifiers)modifier.ignored=modifier!==bestAbility;for(const modifier of modifiers){if(modifier.ignored){modifier.enabled=!1;continue}if(modifier.type==="untyped"){modifier.enabled=!0,total+=modifier.modifier;continue}modifier.modifier<0?total+=applyStacking(lowestPenalty,modifier,LOWER_PENALTY):total+=applyStacking(highestBonus,modifier,HIGHER_BONUS)}return total}__name(applyStackingRules,"applyStackingRules"),__name2(applyStackingRules,"applyStackingRules");class StatisticModifier{static{__name(this,"StatisticModifier")}static{__name2(this,"StatisticModifier")}slug;_modifiers;breakdown="";notes;constructor(slug,modifiers=[],rollOptions=new Set){rollOptions=rollOptions instanceof Set?rollOptions:new Set(rollOptions),this.slug=slug;const seen=modifiers.reduce((result,modifier)=>((!result[modifier.slug]?.enabled||Math.abs(modifier.modifier)>Math.abs(result[modifier.slug].modifier))&&(result[modifier.slug]=modifier),result),{});this._modifiers=Object.values(seen),this.calculateTotal(rollOptions)}get modifiers(){return[...this._modifiers]}push(modifier){const existingIdx=this._modifiers.findIndex(o=>o.slug===modifier.slug),existing=this._modifiers[existingIdx];return existing?Math.abs(modifier.modifier)>Math.abs(existing.modifier)&&(this._modifiers[existingIdx]=modifier,this.calculateTotal()):(this._modifiers.push(modifier),this.calculateTotal()),this._modifiers.length}unshift(modifier){return this._modifiers.find(o=>o.slug===modifier.slug)===void 0&&(this._modifiers.unshift(modifier),this.calculateTotal()),this._modifiers.length}delete(modifierSlug){const toDelete2=typeof modifierSlug=="object"?modifierSlug:this._modifiers.find(modifier=>modifier.slug===modifierSlug),wasDeleted=toDelete2&&this._modifiers.includes(toDelete2)?!!this._modifiers.findSplice(modifier=>modifier===toDelete2):!1;return wasDeleted&&this.calculateTotal(),wasDeleted}calculateTotal(rollOptions=new Set){if(rollOptions.size>0){for(const modifier of this._modifiers)modifier.test(rollOptions);adjustModifiers(this._modifiers,rollOptions)}applyStackingRules(this._modifiers),this.totalModifier=this._modifiers.filter(m=>m.enabled).reduce((total,m)=>total+m.modifier,0)}}function adjustModifiers(modifiers,rollOptions){for(const modifier of[...modifiers].sort((a,b)=>Math.abs(b.value)-Math.abs(a.value))){const adjustments=modifier.adjustments.filter(a=>a.test([...rollOptions,...modifier.getRollOptions()]));if(adjustments.some(a=>a.suppress)){modifier.ignored=!0;continue}const resolvedAdjustment=adjustments.reduce((resolved,adjustment)=>{const newValue=adjustment.getNewValue?.(resolved.value)??resolved.value;return newValue!==resolved.value&&(resolved.value=newValue,resolved.relabel=adjustment.relabel??null),resolved},{value:modifier.modifier,relabel:null});modifier.modifier=resolvedAdjustment.value,resolvedAdjustment.relabel&&(modifier.label=game.i18n.localize(resolvedAdjustment.relabel)),modifier.damageType=adjustments.reduce((damageType,adjustment)=>adjustment.getDamageType?.(damageType)??damageType,modifier.damageType)}}__name(adjustModifiers,"adjustModifiers"),__name2(adjustModifiers,"adjustModifiers");class CheckModifier extends StatisticModifier{static{__name(this,"CheckModifier")}static{__name2(this,"CheckModifier")}constructor(slug,statistic,modifiers=[],rollOptions=new Set){const baseModifiers=statistic.modifiers.map(m=>"clone"in m?m.clone():new ModifierPF2e(m));super(slug,baseModifiers.concat(modifiers),rollOptions)}}class DamageDicePF2e{static{__name(this,"DamageDicePF2e")}static{__name2(this,"DamageDicePF2e")}selector;slug;label;diceNumber;dieSize;critical;category;damageType;override;ignored;enabled;custom;predicate;constructor(params){if(params.selector)this.selector=params.selector;else throw ErrorPF2e("`selector` is mandatory");if(this.label=game.i18n.localize(params.label??""),this.slug=sluggify(params.slug??this.label),!this.slug)throw ErrorPF2e("A DiceModifier must have a slug");this.diceNumber=params.diceNumber??0,this.dieSize=params.dieSize??null,this.damageType=params.damageType??null,this.category=params.category??null,this.override=params.override??null,this.custom=params.custom??!1,this.category=tupleHasValue(["persistent","precision","splash"],params.category)?params.category:this.damageType==="bleed"?"persistent":null,this.critical=this.category==="splash"?!!params.critical:params.critical??null,this.predicate=params.predicate instanceof PredicatePF2e?params.predicate:new PredicatePF2e(params.predicate??[]),this.enabled=params.enabled??this.predicate.test([]),this.ignored=params.ignored??!this.enabled}test(options){this.enabled=this.predicate.test(options),this.ignored=!this.enabled}clone(){return new DamageDicePF2e(this)}toObject(){return foundry.utils.deepClone({...this,predicate:[...this.predicate]})}}function isCheckContextFlag(flag){return!!flag&&!tupleHasValue(["damage-roll","spell-cast"],flag.type)}__name(isCheckContextFlag,"isCheckContextFlag"),__name2(isCheckContextFlag,"isCheckContextFlag");async function createSelfEffectMessage(item,rollMode="roll"){if(!item.system.selfEffect)throw ErrorPF2e(["Only actions with self-applied effects can be passed to `ActorPF2e#useAction`.","Support will be expanded at a later time."].join(" "));const{actor,actionCost}=item,token=actor.getActiveTokens(!0,!0).shift()??null,speaker=ChatMessagePF2e.getSpeaker({actor,token}),flavor=await renderTemplate("systems/pf2e/templates/chat/action/flavor.hbs",{action:{title:item.name,glyph:getActionGlyph(actionCost)},item,traits:item.system.traits.value.map(t=>traitSlugToObject(t,CONFIG.PF2E.actionTraits))}),previewLength=100,descriptionPreview=(()=>{if(item.actor.pack)return null;const tempDiv=document.createElement("div"),documentTypes=[...CONST.DOCUMENT_LINK_TYPES,"Compendium","UUID"],linkPattern=new RegExp(`@(${documentTypes.join("|")})\\[([^#\\]]+)(?:#([^\\]]+))?](?:{([^}]+)})?`,"g");return tempDiv.innerHTML=item.description.replace(linkPattern,(_match,...args)=>args[3]),tempDiv.innerText.slice(0,previewLength)})(),description={full:descriptionPreview&&descriptionPreview.lengtho.startsWith("self:")).map(o=>o.replace(/^self/,"origin")),messageItem=message.item;for(const token of tokens){if(!token.actor)continue;messageRollOptions.some(o=>o.startsWith("target"))||messageRollOptions.push(...token.actor.getSelfRollOptions("target"));const domain=multiplier>0?"damage-received":"healing-received",ephemeralEffects=multiplier>0?await extractEphemeralEffects({affects:"target",origin:message.actor,target:token.actor,item:message.item,domains:[domain],options:messageRollOptions}):[],contextClone=token.actor.getContextualClone(originRollOptions,ephemeralEffects),applicationRollOptions=new Set([...messageRollOptions.filter(o=>!/^(?:self|target):/.test(o)),...originRollOptions,...contextClone.getSelfRollOptions()]),outcome=message.flags.pf2e.context?.outcome,breakdown=[],rolls=[];if(typeof damage=="number"&&damage<0){const critical=outcome==="criticalSuccess",resolvables=(()=>messageItem?.isOfType("spell")?{spell:messageItem}:messageItem?.isOfType("weapon")?{weapon:messageItem}:{})(),damageDice=extractDamageDice(contextClone.synthetics.damageDice,[domain],{resolvables,test:applicationRollOptions}).filter(d=>(d.critical===null||d.critical===critical)&&d.predicate.test(applicationRollOptions));for(const dice of damageDice){const formula=`${dice.diceNumber}${dice.dieSize}[${dice.label}]`,roll2=await new Roll(formula).evaluate({async:!0});roll2._formula=`${dice.diceNumber}${dice.dieSize}`,await roll2.toMessage({flags:{pf2e:{suppressDamageButtons:!0}},flavor:dice.label,speaker:ChatMessage.getSpeaker({token})}),breakdown.push(`${dice.label} ${dice.diceNumber}${dice.dieSize}`),rolls.push(roll2)}rolls.length&&(damage-=rolls.map(roll2=>roll2.total).reduce((previous,current)=>previous+current));const modifiers=extractModifiers(contextClone.synthetics,[domain],{resolvables}).filter(m=>(m.critical===null||m.critical===critical)&&m.predicate.test(applicationRollOptions));damage-=applyStackingRules(modifiers??[]),breakdown.push(...modifiers.filter(m=>m.enabled).map(m=>`${m.label} ${signedInteger(m.modifier)}`))}const hasDamage=typeof damage=="number"?damage!==0:damage.total!==0,notes=(()=>hasDamage?extractNotes(contextClone.synthetics.rollNotes,[domain]).filter(n=>(!outcome||n.outcome.length===0||n.outcome.includes(outcome))&&n.predicate.test(applicationRollOptions)).map(note=>note.text):[])();await contextClone.applyDamage({damage,token,item:message.item,skipIWR:multiplier<=0,rollOptions:applicationRollOptions,shieldBlockRequest,breakdown,notes})}toggleOffShieldBlock(message.id)}__name(applyDamageFromMessage,"applyDamageFromMessage"),__name2(applyDamageFromMessage,"applyDamageFromMessage");async function shiftAdjustDamage(message,multiplier,rollIndex){const content=await renderTemplate("systems/pf2e/templates/chat/damage/adjustment-dialog.hbs"),AdjustmentDialog=class extends Dialog{static{__name(this,"AdjustmentDialog")}static{__name2(this,"AdjustmentDialog")}activateListeners($html){super.activateListeners($html),$html[0].querySelector("input")?.focus()}},isHealing=multiplier<0;new AdjustmentDialog({title:game.i18n.localize(isHealing?"PF2E.UI.shiftModifyHealingTitle":"PF2E.UI.shiftModifyDamageTitle"),content,buttons:{ok:{label:game.i18n.localize("PF2E.OK"),callback:async $dialog=>{const adjustment=(Number($dialog[0].querySelector("input")?.value)||0)*Math.sign(multiplier);applyDamageFromMessage({message,multiplier,addend:adjustment,promptModifier:!1,rollIndex})}},cancel:{label:"Cancel"}},default:"ok",close:()=>{toggleOffShieldBlock(message.id)}}).render(!0)}__name(shiftAdjustDamage,"shiftAdjustDamage"),__name2(shiftAdjustDamage,"shiftAdjustDamage");function toggleOffShieldBlock(messageId){for(const app of["#chat-log","#chat-popout"]){const selector=`${app} > li.chat-message[data-message-id="${messageId}"] button[data-action=shield-block]`;htmlQuery(document.body,selector)?.classList.remove("shield-activated")}CONFIG.PF2E.chatDamageButtonShieldToggle=!1}__name(toggleOffShieldBlock,"toggleOffShieldBlock"),__name2(toggleOffShieldBlock,"toggleOffShieldBlock");function toggleClearTemplatesButton(message){if(!message||!canvas.ready)return;const selector=`li[data-message-id="${message.id}"] button[data-action=spell-template-clear]`;for(const chatLogDOM of htmlQueryAll(document.body,"#chat-log, #chat-popout")){const clearTemplatesButton=htmlQuery(chatLogDOM,selector);if(!clearTemplatesButton)continue;const hasMeasuredTemplates=!!canvas.scene?.templates.some(t=>t.message===message&&t.isOwner);clearTemplatesButton.classList.toggle("hidden",!hasMeasuredTemplates)}}__name(toggleClearTemplatesButton,"toggleClearTemplatesButton"),__name2(toggleClearTemplatesButton,"toggleClearTemplatesButton");const CanvasReady={listen:()=>{Hooks.once("canvasReady",async()=>{await game.pf2e.ConditionManager.initialize();const tokenActors=canvas.scene?.tokens.contents.flatMap(t=>t.actor??[])??[];for(const actor of tokenActors)for(const effect of actor.itemTypes.effect.filter(e=>e.fromAura))game.pf2e.effectTracker.register(effect)}),Hooks.on("canvasReady",()=>{if(game.pf2e.effectPanel.render(!0),!!canvas.scene){game.ready&&canvas.scene.reset(),CONFIG.MeasuredTemplate.defaults.angle=canvas.scene.hasHexGrid?60:90;for(const token of canvas.tokens.placeables.filter(t=>t.visible))token.renderFlags.set({redrawEffects:!0});for(const message of game.messages.contents.slice(-1*CONFIG.ChatMessage.batchSize/2))toggleClearTemplatesButton(message)}})}},CloseCombatTrackerConfig={listen:()=>{Hooks.on("closeCombatTrackerConfig",async(_app,$html)=>{const newIcon=String($html.find('input[name="deathIcon"]').val()).trim();newIcon&&newIcon!==game.settings.get("pf2e","deathIcon")&&await game.settings.set("pf2e","deathIcon",newIcon);const currentDeadAtZero=game.settings.get("pf2e","automation.actorsDeadAtZero"),newDeadAtZero=String($html.find('select[name="actorsDeadAtZero"]').val());currentDeadAtZero!==newDeadAtZero&&await game.settings.set("pf2e","automation.actorsDeadAtZero",newDeadAtZero)})}},CloseWorldClockSettings={listen:()=>{Hooks.on("closeWorldClockSettings",()=>{game.user.isGM&&game.socket.emit("system.pf2e",{request:"refreshSceneControls",data:{layer:"TokenLayer"}})})}},isDice3D=__name2(obj=>obj instanceof Object&&["addSystem","addDicePreset","addTexture","addColorset"].every(m=>m in obj),"isDice3D"),DiceSoNiceReady={listen:()=>{Hooks.once("diceSoNiceReady",dice3d=>{if(isDice3D(dice3d)){dice3d.addSystem({id:"basic",name:"Dicefinder Basic",colorset:"basic"});for(const faces of[4,6,8,10,12])dice3d.addDicePreset({type:`d${faces}`,labels:[...Array(faces)].map((_value,idx)=>String(idx+1)),system:"basic",colorset:"basic"});dice3d.addDicePreset({type:"d20",labels:["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","systems/pf2e/dice/basic/nat20.webp"],system:"basic",colorset:"basic"}),dice3d.addDicePreset({type:"dc",labels:["systems/pf2e/dice/basic/tail.webp","systems/pf2e/dice/basic/heads.webp"],system:"basic",colorset:"basic"}),dice3d.addDicePreset({type:"d2",labels:["systems/pf2e/dice/basic/tail_bump.webp","systems/pf2e/dice/basic/heads_bump.webp"],system:"basic",colorset:"basic"}),dice3d.addDicePreset({type:"d100",labels:[...Array(10)].map((_value,idx)=>String((idx+1)*10)),system:"basic",colorset:"basic"}),dice3d.addDicePreset({type:"df",labels:["-","","+"],system:"basic",colorset:"basic"}),dice3d.addTexture("PFred",{name:"Pathfinder Red",composite:"source-over",source:"systems/pf2e/dice/texture/texture.webp"}).then(()=>{dice3d.addColorset({name:"basic",description:"Dicefinder Basic",category:"Pathfinder 2e",texture:"PFred",material:"metal",foreground:"#f9b96e",outline:"none",edge:"#f9b96e",visibility:"hidden"})}),dice3d.addSystem({id:"campaign",name:"Dicefinder Campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"dc",labels:["systems/pf2e/dice/basic/tail.webp","systems/pf2e/dice/basic/heads.webp"],system:"campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"d2",labels:["systems/pf2e/dice/basic/tail_bump.webp","systems/pf2e/dice/basic/heads_bump.webp"],system:"campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"d4",labels:["systems/pf2e/dice/campaign/d4/d4-1.webp","systems/pf2e/dice/campaign/d4/d4-2.webp","systems/pf2e/dice/campaign/d4/d4-3.webp","systems/pf2e/dice/campaign/d4/d4-4.webp"],system:"campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"d6",labels:["systems/pf2e/dice/campaign/d6/d6-1.webp","systems/pf2e/dice/campaign/d6/d6-2.webp","systems/pf2e/dice/campaign/d6/d6-3.webp","systems/pf2e/dice/campaign/d6/d6-4.webp","systems/pf2e/dice/campaign/d6/d6-5.webp","systems/pf2e/dice/campaign/d6/d6-6.webp"],system:"campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"df",labels:["systems/pf2e/dice/campaign/df/dfm.webp","systems/pf2e/dice/campaign/df/df.webp","systems/pf2e/dice/campaign/df/dfp.webp"],system:"campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"d8",labels:["systems/pf2e/dice/campaign/d8/d8-1.webp","systems/pf2e/dice/campaign/d8/d8-2.webp","systems/pf2e/dice/campaign/d8/d8-3.webp","systems/pf2e/dice/campaign/d8/d8-4.webp","systems/pf2e/dice/campaign/d8/d8-5.webp","systems/pf2e/dice/campaign/d8/d8-6.webp","systems/pf2e/dice/campaign/d8/d8-7.webp","systems/pf2e/dice/campaign/d8/d8-P.webp"],system:"campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"d10",labels:["systems/pf2e/dice/campaign/d10/d10-1.webp","systems/pf2e/dice/campaign/d10/d10-2.webp","systems/pf2e/dice/campaign/d10/d10-3.webp","systems/pf2e/dice/campaign/d10/d10-4.webp","systems/pf2e/dice/campaign/d10/d10-5.webp","systems/pf2e/dice/campaign/d10/d10-6.webp","systems/pf2e/dice/campaign/d10/d10-7.webp","systems/pf2e/dice/campaign/d10/d10-8.webp","systems/pf2e/dice/campaign/d10/d10-9.webp","systems/pf2e/dice/campaign/d10/d10-10.webp"],system:"campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"d12",labels:["systems/pf2e/dice/campaign/d12/d12-1.webp","systems/pf2e/dice/campaign/d12/d12-2.webp","systems/pf2e/dice/campaign/d12/d12-3.webp","systems/pf2e/dice/campaign/d12/d12-4.webp","systems/pf2e/dice/campaign/d12/d12-5.webp","systems/pf2e/dice/campaign/d12/d12-6.webp","systems/pf2e/dice/campaign/d12/d12-7.webp","systems/pf2e/dice/campaign/d12/d12-8.webp","systems/pf2e/dice/campaign/d12/d12-9.webp","systems/pf2e/dice/campaign/d12/d12-10.webp","systems/pf2e/dice/campaign/d12/d12-11.webp","systems/pf2e/dice/campaign/d12/d12-12.webp"],system:"campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"d100",labels:["systems/pf2e/dice/campaign/d100/d100-10.webp","systems/pf2e/dice/campaign/d100/d100-20.webp","systems/pf2e/dice/campaign/d100/d100-30.webp","systems/pf2e/dice/campaign/d100/d100-40.webp","systems/pf2e/dice/campaign/d100/d100-50.webp","systems/pf2e/dice/campaign/d100/d100-60.webp","systems/pf2e/dice/campaign/d100/d100-70.webp","systems/pf2e/dice/campaign/d100/d100-80.webp","systems/pf2e/dice/campaign/d100/d100-90.webp","systems/pf2e/dice/campaign/d100/d100-100.webp"],system:"campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"d20",labels:["systems/pf2e/dice/campaign/d20/d20-1.webp","systems/pf2e/dice/campaign/d20/d20-2.webp","systems/pf2e/dice/campaign/d20/d20-3.webp","systems/pf2e/dice/campaign/d20/d20-4.webp","systems/pf2e/dice/campaign/d20/d20-5.webp","systems/pf2e/dice/campaign/d20/d20-6.webp","systems/pf2e/dice/campaign/d20/d20-7.webp","systems/pf2e/dice/campaign/d20/d20-8.webp","systems/pf2e/dice/campaign/d20/d20-9.webp","systems/pf2e/dice/campaign/d20/d20-10.webp","systems/pf2e/dice/campaign/d20/d20-11.webp","systems/pf2e/dice/campaign/d20/d20-12.webp","systems/pf2e/dice/campaign/d20/d20-13.webp","systems/pf2e/dice/campaign/d20/d20-14.webp","systems/pf2e/dice/campaign/d20/d20-15.webp","systems/pf2e/dice/campaign/d20/d20-16.webp","systems/pf2e/dice/campaign/d20/d20-17.webp","systems/pf2e/dice/campaign/d20/d20-18.webp","systems/pf2e/dice/campaign/d20/d20-19.webp","systems/pf2e/dice/campaign/d20/d20-20.webp"],system:"campaign",colorset:"campaign"}),dice3d.addTexture("stoneD4",{name:"Pathfinder Stone (D4)",composite:"source-over",source:"systems/pf2e/dice/texture/d4.webp"}).then(()=>{dice3d.addColorset({name:"campaign",description:"Dicefinder Campaign",category:"Pathfinder 2e",texture:"stoneD4",material:"stone",foreground:"#5c2f00",outline:"none",edge:"#f9b96e",visibility:"hidden"})}),dice3d.addSystem({id:"darkmode",name:"Dicefinder Dark Mode",colorset:"darkmode"});for(const faces of[4,6,8,10,12])dice3d.addDicePreset({type:`d${faces}`,labels:[...Array(faces)].map((_value,idx)=>String(idx+1)),system:"darkmode",colorset:"darkmode"});dice3d.addDicePreset({type:"d100",labels:[...Array(10)].map((_value,idx)=>String((idx+1)*10)),system:"darkmode",colorset:"darkmode"}),dice3d.addDicePreset({type:"df",labels:["-","","+"],system:"darkmode",colorset:"darkmode"}),dice3d.addDicePreset({type:"d20",labels:["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","systems/pf2e/dice/basic/nat20.webp"],system:"darkmode",colorset:"darkmode"}),dice3d.addDicePreset({type:"dc",labels:["systems/pf2e/dice/basic/tail.webp","systems/pf2e/dice/basic/heads.webp"],system:"darkmode",colorset:"darkmode"}),dice3d.addDicePreset({type:"d2",labels:["systems/pf2e/dice/basic/tail_bump.webp","systems/pf2e/dice/basic/heads_bump.webp"],system:"darkmode",colorset:"darkmode"}),dice3d.addTexture("darkModeBlack",{name:"Dark Mode Black",composite:"source-over",source:"systems/pf2e/dice/texture/transparent.webp"}).then(()=>{dice3d.addColorset({name:"darkmode",description:"Dicefinder Dark Mode",category:"Pathfinder 2e",texture:"darkModeBlack",material:"metal",foreground:"#f9b96e",outline:"none",edge:"#f9b96e",visibility:"hidden"})})}})}},DropCanvasData={listen:()=>{Hooks.on("dropCanvasData",(_canvas,data)=>{const actor=[...canvas.tokens.placeables].sort((a,b)=>b.document.sort-a.document.sort).find(token=>{const maximumX=token.x+(token.hitArea?.right??0),maximumY=token.y+(token.hitArea?.bottom??0);return data.x>=token.x&&data.y>=token.y&&data.x<=maximumX&&data.y<=maximumY})?.actor;if(actor&&data.type==="Item")return actor.sheet.emulateItemDrop(data),!1;if(actor&&data.type==="PersistentDamage"&&"formula"in data){const instances=new DamageRoll(String(data.formula)).instances.filter(i=>i.persistent),baseConditionSource=game.pf2e.ConditionManager.getCondition("persistent-damage").toObject(),conditions=instances.map(i=>foundry.utils.mergeObject(baseConditionSource,{system:{persistent:{formula:i.head.expression,damageType:i.type,dc:15}}}));return actor.createEmbeddedDocuments("Item",conditions),!1}return!0})}},dayInSeconds=Duration.fromObject({hours:24}).as("seconds");function darknessLevelAtTime(time){const secondsElapsed=time.diff(time.startOf("day")).as("seconds"),radians=2*Math.PI*(secondsElapsed/dayInSeconds),lightnessLevel=-1*Math.cos(radians),rad18degrees=Math.toRadians(18);return 1-(lightnessLevel>0?1:lightnessLevel<-rad18degrees?0:Math.sin((lightnessLevel+rad18degrees)/rad18degrees*Math.PI/2))}__name(darknessLevelAtTime,"darknessLevelAtTime"),__name2(darknessLevelAtTime,"darknessLevelAtTime");function intervalToTransition(interval,compactInterval){const currentDarkness=canvas.darknessLevel,targetDarkness=interval.end?darknessLevelAtTime(interval.end):NaN,darknessDiff=Math.abs((currentDarkness??targetDarkness)-targetDarkness),proportionOfDay=compactInterval.length("seconds")/dayInSeconds,darkTimeMean=(darknessDiff*.5+proportionOfDay)/2;return{target:targetDarkness,duration:darkTimeMean*6e3,interval}}__name(intervalToTransition,"intervalToTransition"),__name2(intervalToTransition,"intervalToTransition");async function runAnimation(transition){if(!canvas.lighting||canvas.darknessLevel===transition.target)return;const duration=Math.min(Math.trunc(100*transition.duration)/100,6e3);await canvas.effects.animateDarkness(transition.target,{duration}),game.user.isGM&&await canvas.scene.update({darkness:transition.target})}__name(runAnimation,"runAnimation"),__name2(runAnimation,"runAnimation");async function animateDarkness(timeDiff){if(!this.syncDarkness)return;const newTime=this.worldTime,oldTime=newTime.minus({seconds:timeDiff}),fullInterval=Interval.fromDateTimes(oldTime,newTime);if(!fullInterval.isValid){await runAnimation({target:darknessLevelAtTime(newTime),duration:100,interval:fullInterval});return}const compactInterval=(()=>{if(fullInterval.length("hours")>24){const adjustedOldTime=newTime.minus({hours:24});return Interval.fromDateTimes(adjustedOldTime,newTime)}return fullInterval})(),transitionTimes=[4.75,18].map(hour=>compactInterval.start.set({hour,minute:0,second:0})).concat([4.75,18].map(hour=>compactInterval.end.set({hour,minute:0,second:0}))).filter(dateTime=>compactInterval.contains(dateTime)).concat([compactInterval.start,compactInterval.end]).sort((dtA,dtB)=>dtAdtB?1:0),transitions=transitionTimes.reduce((pairs,dateTime)=>{const index=transitionTimes.indexOf(dateTime);if(index===0)return[];const before=transitionTimes[index-1];return[...pairs,[before,dateTime]]},[]).map(pair=>Interval.fromDateTimes(pair[0],pair[1])).filter(interval=>interval.length()>0).map(interval=>intervalToTransition(interval,compactInterval));for(const transition of transitions)await runAnimation(transition)}__name(animateDarkness,"animateDarkness"),__name2(animateDarkness,"animateDarkness");var TimeChangeMode=(TimeChangeMode2=>(TimeChangeMode2[TimeChangeMode2.ADVANCE=0]="ADVANCE",TimeChangeMode2[TimeChangeMode2.RETRACT=1]="RETRACT",TimeChangeMode2))(TimeChangeMode||{});class TimeOfDay{static{__name(this,"TimeOfDay")}static{__name2(this,"TimeOfDay")}constructor(hour,minute,second){this.hour=hour,this.minute=minute,this.second=second}static DAWN=new TimeOfDay(4,58,54);static NOON=new TimeOfDay(12,0,0);static DUSK=new TimeOfDay(18,34,6);static MIDNIGHT=new TimeOfDay(0,0,0);diffSeconds(worldTime,mode){const targetTime=worldTime.set(this),targetDayDifference=TimeOfDay.diffDays(worldTime,targetTime,mode);return worldTime.plus({day:targetDayDifference}).set(this).diff(worldTime,"seconds").seconds}static diffDays(currentTime,targetTime,mode){return currentTime>=targetTime&&mode===0?1:currentTime<=targetTime&&mode===1?-1:0}}class WorldClock extends Application{static{__name(this,"WorldClock")}static{__name2(this,"WorldClock")}ctrlKeyDown=!1;animateDarkness=animateDarkness;constructor(){super();const settingValue=game.settings.get("pf2e","worldClock.worldCreatedOn"),defaultValue=game.settings.settings.get("pf2e.worldClock.worldCreatedOn")?.default;typeof settingValue=="string"&&settingValue===defaultValue?game.settings.set("pf2e","worldClock.worldCreatedOn",settingValue):DateTime.fromISO(settingValue).isValid||game.settings.set("pf2e","worldClock.worldCreatedOn",defaultValue)}get dateTheme(){return game.settings.get("pf2e","worldClock.dateTheme")}get timeConvention(){const setting=game.settings.get("pf2e","worldClock.timeConvention");if(setting!==24&&setting!==12)throw Error("PF2e System | Unrecognized time convention");return setting}get syncDarkness(){const sceneSetting=canvas.scene?.flags.pf2e.syncDarkness??"default";return{enabled:!0,disabled:!1,default:game.settings.get("pf2e","worldClock.syncDarkness")}[sceneSetting]}get worldCreatedOn(){const value=game.settings.get("pf2e","worldClock.worldCreatedOn");return DateTime.fromISO(value).toUTC()}get worldTime(){return this.worldCreatedOn.plus({seconds:game.time.worldTime})}static get defaultOptions(){return foundry.utils.mergeObject(super.defaultOptions,{id:"world-clock",width:400,template:"systems/pf2e/templates/system/world-clock.hbs",title:"PF2E.WorldClock.Title"})}get era(){switch(this.dateTheme){case"AR":return game.i18n.localize(CONFIG.PF2E.worldClock.AR.Era);case"AD":return this.worldTime.toFormat("G");default:return""}}get year(){const yearOffset=(()=>{switch(this.dateTheme){case"AR":return CONFIG.PF2E.worldClock.AR.yearOffset;case"AD":return CONFIG.PF2E.worldClock.AD.yearOffset;default:return 0}})();return this.worldTime.year+yearOffset}get month(){switch(this.dateTheme){case"AR":{const months=CONFIG.PF2E.worldClock.AR.Months,month=this.worldTime.setLocale("en-US").monthLong;return game.i18n.localize(months[month])}default:return this.worldTime.monthLong}}get weekday(){switch(this.dateTheme){case"AR":{const weekdays=CONFIG.PF2E.worldClock.AR.Weekdays,weekday=this.worldTime.setLocale("en-US").weekdayLong;return game.i18n.localize(weekdays[weekday])}default:return this.worldTime.weekdayLong}}getData(options){const date=this.dateTheme==="CE"?this.worldTime.toLocaleString(DateTime.DATE_HUGE):game.i18n.format(CONFIG.PF2E.worldClock.Date,{era:this.era,year:this.year,month:this.month,day:ordinalString(this.worldTime.day),weekday:this.weekday}),time=this.timeConvention===24?this.worldTime.toFormat("HH:mm:ss"):this.worldTime.toLocaleString(DateTime.TIME_WITH_SECONDS),sign=this.ctrlKeyDown?"-":"+";return{date,time,options,user:game.user,sign}}_getHeaderButtons(){return(game.user.isGM?[{label:"PF2E.SETTINGS.Settings",class:"configure-settings",icon:"fa-solid fa-cog",onclick:()=>{const menu=game.settings.menus.get("pf2e.worldClock");if(!menu)throw ErrorPF2e("PF2e System | World Clock Settings application not found");new menu.type().render(!0)}}]:[]).concat(...super._getHeaderButtons())}static calculateIncrement(wordTime,interval,intervalMode){const mode=intervalMode==="+"?TimeChangeMode.ADVANCE:TimeChangeMode.RETRACT;switch(interval){case"dawn":return TimeOfDay.DAWN.diffSeconds(wordTime,mode);case"noon":return TimeOfDay.NOON.diffSeconds(wordTime,mode);case"dusk":return TimeOfDay.DUSK.diffSeconds(wordTime,mode);case"midnight":return TimeOfDay.MIDNIGHT.diffSeconds(wordTime,mode);default:{const sign=mode===TimeChangeMode.ADVANCE?1:-1;return Number(interval)*sign}}}activateListeners($html){super.activateListeners($html),$html.find("button[data-advance-time]").on("click",event2=>{const $button=$(event2.currentTarget),advanceTime=$button.data("advanceTime")??"0",advanceMode=$button.data("advanceMode")??"+",increment=WorldClock.calculateIncrement(this.worldTime,advanceTime,advanceMode);increment!==0&&game.time.advance(increment)}),$html.find("button[name=advance], button[name=retract]").on("click",event2=>{const value=$html.find('input[type=number][name="diff-value"]').val(),unit=$html.find('select[name="diff-unit"]').val(),increment=($(event2.currentTarget).attr("name")==="advance"?1:-1)*Number(value)*Number(unit);game.time.advance(increment)});for(const eventName of["keydown.pf2e.world-clock","keyup.pf2e.world-clock"])$(document).off(eventName),$(document).on(eventName,event2=>{const{originalEvent}=event2;if(!(originalEvent instanceof KeyboardEvent))return;const ctrlKeys=KeyboardManager.CONTROL_KEY_STRING==="\u2318"?["Control","Meta"]:["Control"];if(originalEvent.repeat||!ctrlKeys.includes(originalEvent.key)||!(event2.ctrlKey||this.ctrlKeyDown))return;const retractTime=this.ctrlKeyDown=event2.type==="keydown",{Advance,Retract,TimeOfDay:TimeOfDay2}=CONFIG.PF2E.worldClock.Button,advanceButtons=Array.from($html.get(0)?.querySelectorAll("button[data-advance-time]")??[]);for(const button of advanceButtons){const{advanceMode,advanceTime}=button.dataset,nextMode=advanceMode==="+"?"-":"+";button.dataset.advanceMode=nextMode;const sign=button.querySelector(".sign");if(sign&&(sign.innerHTML=nextMode),tupleHasValue(["dawn","noon","dusk","midnight"],advanceTime)){const timeOfDayKeys=nextMode==="+"?TimeOfDay2.Advance:TimeOfDay2.Retract;button.title=timeOfDayKeys[advanceTime.titleCase()]}}$html.find("button[name=advance], button[name=retract]").attr("name",retractTime?"retract":"advance").text(game.i18n.localize(retractTime?Retract:Advance))})}async close(options){$(document).off("keydown.pf2e.world-clock").off("keyup.pf2e.world-clock"),await super.close(options)}static createSyncedMessage(){const managedBy=document.createElement("span");managedBy.classList.add("managed"),managedBy.innerHTML=" ".concat(game.i18n.localize("PF2E.SETTINGS.WorldClock.SyncDarknessScene.ManagedBy"));const anchor=document.createElement("a"),wtLink=managedBy.querySelector("wt");return anchor.innerText=wtLink?.innerHTML??"",anchor.setAttribute("href",""),anchor.addEventListener("click",event2=>{event2.preventDefault(),event2.stopPropagation();const menu=game.settings.menus.get("pf2e.worldClock");if(!menu)throw ErrorPF2e("World Clock Settings application not found");new menu.type().render(!0)}),wtLink?.replaceWith(anchor),managedBy}}class SceneDarknessAdjuster extends Application{static{__name(this,"SceneDarknessAdjuster")}static{__name2(this,"SceneDarknessAdjuster")}static instance=new this;#slider;#noRefreshHook=!1;static get defaultOptions(){return{...super.defaultOptions,id:"darkness-adjuster",title:"CONTROLS.AdjustSceneDarkness",template:"systems/pf2e/templates/system/scene-darkness-adjuster.hbs",width:400,height:45,minimizable:!1}}async getData(options={}){return{...await super.getData(options),darknessSyncedToTime:!!game.scenes.viewed?.darknessSyncedToTime}}async render(force=!1,options={}){if(!game.scenes.viewed)return this;const bounds=ui.controls.element[0]?.querySelector("li[data-tool=darkness-adjuster]")?.getBoundingClientRect();return bounds?(options.left=bounds.right+6,options.top=bounds.top-3,this.rendered?super.render(force,options):(await super.render(force,options),await $("#darkness-adjuster").hide(0).fadeIn().promise(),this)):this}async close(options){return this.rendered?(await $("#darkness-adjuster").fadeOut().promise(),super.close(options)):super.close(options)}activateListeners($html){if(!game.scenes.viewed)return;const slider=$html[0].querySelector(".slider");if(this.#slider=noUiSlider.create(slider,{range:{min:0,max:1},start:[.25,game.scenes.viewed.darkness,.75],connect:[!0,!1,!1,!0],behaviour:"snap-unconstrained-snap",pips:{mode:PipsMode.Range,density:5},step:.05}),game.scenes.viewed?.darknessSyncedToTime){const synchronized=document.createElement("div");synchronized.className="message";const message=WorldClock.createSyncedMessage();synchronized.append(message),slider.append(synchronized)}slider.querySelectorAll(".noUi-origin").forEach((thumb,index)=>{index!==1&&$(thumb).attr({disabled:"disabled"}),game.scenes.viewed?.darknessSyncedToTime&&thumb.setAttribute("disabled","true")}),this.#slider.on("slide",(values,thumbNumber)=>{thumbNumber===1&&canvas.scene&&(this.#noRefreshHook=!0,canvas.colorManager.initialize({darknessLevel:Number(values[1])}),canvas.app.ticker.add(()=>{this.#noRefreshHook=!1}))}),this.#slider.on("change",async(values,thumbNumber)=>{if(canvas.scene&&thumbNumber===1){const newValue=Number(values[1]);await canvas.scene.update({darkness:newValue},{animateDarkness:Math.round(5e3*Math.abs(canvas.scene.darkness-newValue))})}}),slider.querySelectorAll(".noUi-handle").forEach((handle,index)=>{const decoration={0:["threshold_bright-light",fontAwesomeIcon("sun")],1:["darkness-level",null],2:["threshold_darkness",fontAwesomeIcon("moon",{fixedWidth:!0})]},$handle=$(handle),[cssClass,icon]=decoration[index];icon&&$handle.append(icon),$handle.addClass(cssClass)}),slider.querySelectorAll(".noUi-connect").forEach((connect,index)=>{const classes={0:"range_bright-light",1:"range_darkness"};connect.classList.add(classes[index])})}onLightingRefresh(darkness){if(!this.rendered||this.#noRefreshHook)return;const sliderValues=this.#slider?.get();if(this.#slider&&Array.isArray(sliderValues)){const currentValue=sliderValues[1],stepValue=Math.round(darkness*20)/20;stepValue!==currentValue&&(sliderValues[1]=stepValue,this.#slider.set(sliderValues))}}}const GetSceneControlButtons={listen:()=>{Hooks.on("getSceneControlButtons",controls=>{controls.find(c=>c.name==="token")?.tools?.push({name:"worldclock",title:"CONTROLS.WorldClock",icon:"fa-solid fa-clock",button:!0,visible:game.settings.get("pf2e","worldClock.showClockButton")&&(game.user.isGM||game.settings.get("pf2e","worldClock.playersCanView")),onClick:()=>{game.pf2e.worldClock.rendered?game.pf2e.worldClock.close({force:!0}):game.pf2e.worldClock.render(!0)}});const lightingControls=controls.find(c=>c.name==="lighting"),lightingTools=lightingControls?.tools,dayTool=lightingTools?.find(tool=>tool.name==="day");if(!(lightingControls&&lightingTools&&dayTool))return;lightingControls.visible&&SceneDarknessAdjuster.instance.rendered&&SceneDarknessAdjuster.instance.close({force:!0});const adjusterTool={name:"darkness-adjuster",title:"CONTROLS.AdjustSceneDarkness",icon:"fa-solid fa-adjust",visible:game.user.isGM&&game.pf2e.settings.rbv,toggle:!0,active:!1,onClick:()=>{const adjuster=SceneDarknessAdjuster.instance;adjuster.rendered?adjuster.close({force:!0}):adjuster.render(!0)}},gmVisionTool=(()=>{const binding=game.keybindings.actions.get("pf2e.gm-vision")?.editable?.[0];if(!(binding&&game.user.isGM))return null;const gmVisionLabel=game.i18n.localize("PF2E.Keybinding.GMVision.Label"),bindingLabel=KeybindingsConfig._humanizeBinding(binding),gmVisionIcon=__name2((active=game.settings.get("pf2e","gmVision"))=>active?"fa-solid fa-lightbulb-cfl-on":"fa-solid fa-lightbulb-cfl","gmVisionIcon");return{name:"gm-vision",title:`${gmVisionLabel} [${bindingLabel}]`,icon:gmVisionIcon(),visible:game.user.isGM,toggle:!0,active:game.settings.get("pf2e","gmVision"),onClick:()=>{const newStatus=!game.settings.get("pf2e","gmVision");game.settings.set("pf2e","gmVision",newStatus);const toggle=ui.controls.control?.tools.find(t=>t.name==="gm-vision");toggle&&(toggle.active=newStatus,toggle.icon=gmVisionIcon(newStatus),ui.controls.render())}}})(),tools=[adjusterTool,gmVisionTool??[]].flat();lightingTools.splice(lightingTools?.indexOf(dayTool),0,...tools)})}},I18nInit={listen:()=>{Hooks.once("i18nInit",()=>{new HomebrewElements().onInit()})}};class HotbarPF2e extends Hotbar{static{__name(this,"HotbarPF2e")}static{__name2(this,"HotbarPF2e")}async _onDrop(event2){const li=htmlClosest(event2.target,".macro"),slot=Number(li?.dataset.slot)||null;if(!slot)return;const data=TextEditor.getDragEventData(event2);if(!["Item","RollOption","Skill","Action"].includes(data.type??""))return super._onDrop(event2);if(Hooks.call("hotbarDrop",this,data,slot)!==!1)switch(data.type==="Item"&&data.itemType==="melee"&&typeof data.index=="number"&&(data.type="Action"),data.type){case"Item":{const itemId=data.id??(isObject(data.data)?data.data._id:null),uuid=data.uuid,prefix=typeof data.pack=="string"?`Compendium.${data.pack}`:typeof data.actorId=="string"?`Actor.${data.actorId}.Item`:"Item",item=await fromUuid(uuid??`${prefix}.${itemId}`);if(!(item instanceof ItemPF2e))return;if(item.isOfType("condition","effect"))return createToggleEffectMacro(item,slot);if(uuid?.startsWith("Compendium.")){ui.notifications.error("PF2E.Macro.NoCompendiumItem",{localize:!0});return}else return HotbarPF2e.#createItemMacro(item,slot)}case"RollOption":{const item=fromUuidSync(data.uuid??"");if(!(item instanceof ItemPF2e&&item.isEmbedded))throw ErrorPF2e("Unexpected error during macro creation");return this.#hasRollOptionData(data)?HotbarPF2e.#createRollOptionToggleMacro({...data,item},slot):void 0}case"Skill":{if(!(data.actorId&&setHasElement(SKILL_ABBREVIATIONS,data.skill)))return;const skillName=data.skillName??game.i18n.localize(CONFIG.PF2E.skills[data.skill]);return createSkillMacro(data.skill,skillName,data.actorId,slot)}case"Action":return typeof data.index!="number"&&!data.elementTrait?void 0:createActionMacro({actorUUID:data.actorUUID,actionIndex:data.index,slot,elementTrait:data.elementTrait})}}#hasRollOptionData(data){const{label,domain,option}=data;return typeof label=="string"&&label.length>0&&typeof domain=="string"&&domain.length>0&&typeof option=="string"&&option.length>0}static async#createItemMacro(item,slot){const command=`game.pf2e.rollItemMacro("${item.id}");`,macro=game.macros.find(m=>m.name===item.name&&m.command===command)??await MacroPF2e.create({command,name:item.name,type:"script",img:item.img,flags:{pf2e:{itemMacro:!0}}},{renderSheet:!1});game.user.assignHotbarMacro(macro??null,slot)}static async#createRollOptionToggleMacro(data,slot){const name2=game.i18n.format("PF2E.ToggleWithName",{property:data.label}),escapedName=new Handlebars.SafeString(data.label),{item,domain,option}=data,command=`const item = fromUuidSync("${item.uuid}");
if (!(item instanceof Item && item.isEmbedded && item.isOwner)) {
ui.notifications.error("PF2E.MacroActionNoActorError", { localize: true });
}
const result = await item.actor.toggleRollOption("${domain}", "${option}", "${item.id}");
const state = game.i18n.localize(result ? "PF2E.Macro.OptionToggle.On" : "PF2E.Macro.OptionToggle.Off");
const message = game.i18n.format("PF2E.Macro.OptionToggle.Notification", { toggle: "${escapedName}", state });
if (typeof result === "boolean") {
ui.notifications.info(message);
}`,toggleMacro=game.macros.find(m=>m.name===name2&&m.command===command)??await MacroPF2e.create({type:"script",name:name2,img:item.img,command},{renderSheet:!1})??null;await game.user.assignHotbarMacro(toggleMacro,slot)}}class ActorDirectoryPF2e extends ActorDirectory{static{__name(this,"ActorDirectoryPF2e")}static{__name2(this,"ActorDirectoryPF2e")}static entryPartial="systems/pf2e/templates/sidebar/actor-document-partial.hbs";#extraFolders={};#renderedOnce=!1;#draggingParty=!1;static get defaultOptions(){const options=super.defaultOptions;return options.renderUpdateKeys.push("system.details.level.value","system.attributes.adjustment","system.details.members","system.campaign.type"),options}async getData(){const activeParty=game.actors.party;this.#renderedOnce||(activeParty&&game.settings.get("pf2e","activePartyFolderState")&&(this.#extraFolders[activeParty.id]=!0),this.#renderedOnce=!0);const parties=sortBy(this.documents.filter(a=>a.isOfType("party")&&a!==activeParty),p=>p.sort);return{...await super.getData(),activeParty,parties,placePartiesInSubfolder:parties.length>1,extraFolders:this.#extraFolders}}saveActivePartyFolderState(){game.settings.set("pf2e","activePartyFolderState",this.#extraFolders[game.actors.party?.id??""]??!0)}activateListeners($html){super.activateListeners($html);const html=$html[0];for(const element of htmlQueryAll(html,"li.directory-item.actor"))game.actors.get(element.dataset.documentId??"")?.testUserPermission(game.user,"OBSERVER")||element.querySelector("span.actor-level")?.remove();for(const folderLike of htmlQueryAll(html,".folder-like")){const header=htmlQuery(folderLike,":scope > header");if(!header)continue;for(const eventType of["dragenter","dragleave","dragend"])folderLike.addEventListener(eventType,event2=>{this.#onDragHighlightFolderLike(folderLike,event2)});header.addEventListener("click",event2=>{const folderEl=htmlClosest(event2.target,".folder-like"),entryId=htmlClosest(event2.target,"[data-entry-id]")?.dataset.entryId??"";folderEl&&entryId&&(event2.stopPropagation(),this.#extraFolders[entryId]=folderEl.classList.contains("collapsed"),folderEl.classList.toggle("collapsed",!this.#extraFolders[entryId]),this.popOut&&this.setPosition(),this.saveActivePartyFolderState())});const openSheetLink=htmlQuery(header,"a[data-action=open-sheet]");openSheetLink?.addEventListener("click",event2=>{event2.stopPropagation();const documentId=htmlClosest(openSheetLink,"[data-document-id]")?.dataset.documentId;game.actors.get(documentId??"")?.sheet.render(!0)});const createMemberLink=htmlQuery(header,"a[data-action=create-member]");createMemberLink?.addEventListener("click",async event2=>{event2.preventDefault(),event2.stopPropagation();const documentId=htmlClosest(createMemberLink,"[data-document-id]")?.dataset.documentId,party=game.actors.get(documentId??"");if(!party?.isOfType("party"))return;const button=event2.currentTarget,actor=await ActorPF2e.createDialog({},{width:320,left:window.innerWidth-630,top:button?.offsetTop??0,types:["creature"]});actor?.isOfType("creature")&&(this.#extraFolders[party.id]=!0,await party.addMembers(actor))});const createPartyLink=htmlQuery(header,"a[data-action=create-party]");createPartyLink?.addEventListener("click",async event2=>{event2.stopPropagation(),(await ActorPF2e.create({type:"party",name:"New Party"}))?.sheet.render(!0);const entryId=htmlClosest(createPartyLink,".folder-like")?.dataset.entryId;entryId&&(this.#extraFolders[entryId]=!0,this.render())});const activatePartyLink=htmlQuery(header,"a[data-action=activate-party]");activatePartyLink?.addEventListener("click",event2=>{event2.stopPropagation();const documentId=htmlClosest(activatePartyLink,"[data-document-id]")?.dataset.documentId??"";game.actors.has(documentId)&&(game.settings.set("pf2e","activeParty",documentId),this.saveActivePartyFolderState())})}this.#appendBrowseButton(html)}_onSearchFilter(event2,query,rgx,html){super._onSearchFilter(event2,query,rgx,html);const folderLikes=htmlQueryAll(html,".folder-like");for(const folderLike of folderLikes)if(query!==""&&htmlQueryAll(folderLike,".actor").some(li=>li.style.display!=="none")){folderLike.removeAttribute("style"),folderLike.classList.remove("collapsed");const folderLikeHeader=htmlQuery(folderLike,":scope > header");folderLikeHeader&&folderLikeHeader.removeAttribute("style")}else{const entryId=folderLike.dataset.entryId??"";folderLike.classList.toggle("collapsed",!this.#extraFolders[entryId])}}_onDragStart(event2){if(event2.target.dataset.entryId==="otherParties"){event2.preventDefault();return}super._onDragStart(event2);const fromParty=htmlClosest(event2.target,".party")?.dataset.documentId;if(fromParty){const data=JSON.parse(event2.dataTransfer.getData("text/plain"));data.fromParty=fromParty,this.#draggingParty=fromUuidSync(data.uuid)instanceof PartyPF2e,event2.dataTransfer.setData("text/plain",JSON.stringify(data))}else this.#draggingParty=!1}_onDragHighlight(event2){if(event2.type==="dragenter"&&this.#draggingParty)return event2.stopPropagation();super._onDragHighlight(event2)}#onDragHighlightFolderLike(folderLike,event2){event2.stopPropagation(),!this.#draggingParty&&(event2.type==="dragleave"&&document.elementFromPoint(event2.clientX,event2.clientY)?.closest(".folder-like")===folderLike||folderLike?.classList.toggle("droptarget",event2.type==="dragenter"))}async _handleDroppedEntry(target,data){await super._handleDroppedEntry(target,data);const toPartyId=htmlClosest(target,".party")?.dataset.documentId;if(toPartyId!==data.fromParty&&data.uuid){const toParty=game.actors.get(toPartyId??""),fromParty=game.actors.get(data.fromParty??""),actor=fromUuidSync(data.uuid);fromParty instanceof PartyPF2e&&await fromParty.removeMembers(data.uuid),toParty instanceof PartyPF2e&&actor instanceof CreaturePF2e&&await toParty.addMembers(actor)}}async _renderInner(data){const $element=await super._renderInner(data);if(game.actors.some(a=>a.isOfType("party"))){const partyHTML=await renderTemplate("systems/pf2e/templates/sidebar/party-document-partial.hbs",data);$element.find(".directory-list").prepend(partyHTML);for(const header of htmlQueryAll($element.get(0),".party")){const party=game.actors.get(header.dataset.documentId??""),sidebarButtons=party?.isOfType("party")?party.campaign?.createSidebarButtons?.()??[]:[];header.querySelector("header h3")?.after(...sidebarButtons)}}return $element}async _render(force,context={}){return context=foundry.utils.deepClone(context),context.action==="update"&&context.documentType==="Actor"&&context.data&&(context.data=context.data.map(d=>({...d,...foundry.utils.flattenObject(d)}))),super._render(force,context)}_contextMenu($html){super._contextMenu($html),ContextMenu.create(this,$html,".party .party-header",this._getPartyContextOptions())}_getEntryContextOptions(){const options=super._getEntryContextOptions();return options.push({name:"PF2E.Actor.Party.Sidebar.RemoveMember",icon:fontAwesomeIcon("bus").outerHTML,condition:$li=>$li.closest(".party").length>0&&!$li.closest(".party-header").length,callback:$li=>{const actorId=$li.data("document-id"),partyId=$li.closest(".party").data("document-id"),actor=game.actors.get(actorId??""),party=game.actors.get(partyId??"");actor&&party instanceof PartyPF2e&&party.removeMembers(actor.uuid)}}),options}_getPartyContextOptions(){const allOptions=super._getEntryContextOptions(),relevantNames=["SIDEBAR.CharArt","SIDEBAR.TokenArt","OWNERSHIP.Configure","SIDEBAR.Delete"],relevantOptions=allOptions.filter(o=>relevantNames.includes(o.name));return relevantOptions.length!==relevantNames.length&&console.error("PF2E System | Failed to extract all sidebar options from the base options"),relevantOptions}#appendBrowseButton(html){if(!game.user.isGM)return;const browseButton=document.createElement("button");browseButton.type="button",browseButton.append(fontAwesomeIcon("search",{fixedWidth:!0})," ",game.i18n.localize("PF2E.CompendiumBrowser.BestiaryBrowser")),browseButton.addEventListener("click",()=>{game.pf2e.compendiumBrowser.openTab("bestiary")}),htmlQuery(html,"footer.directory-footer")?.append(browseButton)}}class ItemDirectoryPF2e extends ItemDirectory{static{__name(this,"ItemDirectoryPF2e")}static{__name2(this,"ItemDirectoryPF2e")}static entryPartial="systems/pf2e/templates/sidebar/item-document-partial.hbs";static get defaultOptions(){const options=super.defaultOptions;return options.renderUpdateKeys.push("system.level.value"),options}activateListeners($html){super.activateListeners($html);const html=$html[0];for(const element of htmlQueryAll(html,"li.directory-item.item"))game.items.get(element.dataset.documentId??"")?.testUserPermission(game.user,"OBSERVER")||element.querySelector("span.item-level")?.remove();this.#appendBrowseButton(html)}async _render(force,context={}){return context=foundry.utils.deepClone(context),context.action==="update"&&context.documentType==="Item"&&context.data&&(context.data=context.data.map(d=>({...d,...foundry.utils.flattenObject(d)}))),super._render(force,context)}#appendBrowseButton(html){const browseButton=document.createElement("button");browseButton.type="button",browseButton.append(fontAwesomeIcon("search",{fixedWidth:!0})," ",game.i18n.localize("PF2E.CompendiumBrowser.Title")),browseButton.addEventListener("click",()=>{game.pf2e.compendiumBrowser.render(!0,{focus:!0})}),htmlQuery(html,"footer.directory-footer")?.append(browseButton)}}async function handleKingdomChatMessageEvents(options){const{event:event2,message}=options,party=message.actor??game.actors.party;if(!(!party?.isOfType("party")||!(party?.campaign instanceof Kingdom))&&htmlClosest(event2.target,"[data-action=kingdom-collect]")){if(!party.isOwner)return;await party.campaign.collect();const content=createHTMLElement("div",{innerHTML:message.content});htmlQuery(content,"[data-action=kingdom-collect]")?.replaceWith(createHTMLElement("div",{classes:["confirmation"],children:[fontAwesomeIcon("fa-check"),"Resources Collected"]})),message.update({content:content.innerHTML})}}__name(handleKingdomChatMessageEvents,"handleKingdomChatMessageEvents"),__name2(handleKingdomChatMessageEvents,"handleKingdomChatMessageEvents");class ChatLogPF2e extends ChatLog{static{__name(this,"ChatLogPF2e")}static{__name2(this,"ChatLogPF2e")}activateListeners($html){super.activateListeners($html);const html=$html[0],log=htmlQuery(html,"#chat-log");log&&(log.dataset.tooltipDirection="UP"),this.activateClickListener(html),html.addEventListener("dblclick",async event2=>{const{message}=ChatLogPF2e.#messageFromEvent(event2);if((message?htmlClosest(event2.target,".message-sender"):null)&&message)return this.#onClickSender(message,event2)})}activateClickListener(html){html.addEventListener("click",async event2=>{const{message,element:messageEl}=ChatLogPF2e.#messageFromEvent(event2);if(!message)return;if((message?htmlClosest(event2.target,".message-sender"):null)&&message)return this.#onClickSender(message,event2);const button=htmlClosest(event2.target,"button[data-action]");if(button){if(message.isDamageRoll){const button2=htmlClosest(event2.target,"button");if(!button2)return;if(button2.dataset.action==="shield-block")return this.#onClickShieldBlock(button2,messageEl);const actions=["apply-damage","apply-healing","double-damage","half-damage","triple-damage"];for(const action2 of actions)if(button2.dataset.action===action2){const index=htmlClosest(button2,".damage-application")?.dataset.rollIndex;return this.#onClickDamageButton(message,action2,event2.shiftKey,index)}}else if(button.dataset.action==="revert-damage"){const appliedDamageFlag=message?.flags.pf2e.appliedDamage;appliedDamageFlag&&await this.#onClickRevertDamage(appliedDamageFlag)&&(htmlQuery(messageEl,"span.statements")?.classList.add("reverted"),button.remove(),await message.update({"flags.pf2e.appliedDamage.isReverted":!0,content:htmlQuery(messageEl,".message-content")?.innerHTML??message.content}))}message&&messageEl&&handleKingdomChatMessageEvents({event:event2,message,messageEl})}})}_onDiceRollClick(event2){const message=ChatLogPF2e.#messageFromEvent(event2.originalEvent).message;if(message&&htmlClosest(event2.target,"button[data-action=set-as-initiative]"))event2.stopPropagation(),this.#onClickSetAsInitiative(message);else return super._onDiceRollClick(event2)}async _processDiceCommand(command,matches,chatData,createOptions){const rollData=(ChatMessage.getSpeakerActor(chatData.speaker??{})||game.user.character)?.getRollData()??{},rolls=[];for(const match of matches.filter(m=>!!m)){const[formula,flavor]=match.slice(2,4);flavor&&!chatData.flavor&&(chatData.flavor=flavor);const roll=(()=>{try{const damageRoll=new DamageRoll(formula,rollData);return looksLikeDamageRoll(damageRoll)?damageRoll:new Roll(formula,rollData)}catch{return new Roll(formula,rollData)}})();rolls.push(await roll.evaluate({async:!0}))}chatData.type=CONST.CHAT_MESSAGE_TYPES.ROLL,chatData.rolls=rolls.map(r=>r.toJSON()),chatData.sound=CONFIG.sounds.dice,chatData.content=rolls.reduce((t,r)=>t+r.total,0).toString(),createOptions.rollMode=objectHasKey(CONFIG.Dice.rollModes,command)?command:"roll"}static#messageFromEvent(event2){const element=htmlClosest(event2?.target,"li[data-message-id]"),messageId=element?.dataset.messageId??"",message=game.messages.get(messageId);return element&&message?{element,message}:{element:null,message:null}}#onClickDamageButton(message,action2,shiftKey,index){const multiplier=(()=>{switch(action2){case"apply-healing":return-1;case"half-damage":return .5;case"apply-damage":return 1;case"double-damage":return 2;case"triple-damage":return 3}})();applyDamageFromMessage({message,multiplier,addend:0,promptModifier:shiftKey,rollIndex:Number(index)||0})}async#onClickRevertDamage(flag){const actorOrToken=fromUuidSync(flag.uuid),actor=actorOrToken instanceof ActorPF2e?actorOrToken:actorOrToken instanceof TokenDocumentPF2e?actorOrToken.actor:null;return actor?(await actor.undoDamage(flag),ui.notifications.info(game.i18n.format(`PF2E.RevertDamage.${flag.isHealing?"Healing":"Damage"}Message`,{actor:actor.name})),!0):!1}#onClickShieldBlock(shieldButton,messageEl){const getTokens=__name2(()=>{const tokens=game.user.getActiveTokens();return tokens.length||ui.notifications.error("PF2E.ErrorMessage.NoTokenSelected",{localize:!0}),tokens},"getTokens"),getNonBrokenShields=__name2(tokens=>tokens.find(t=>!!t.actor)?.actor?.itemTypes.shield.filter(s=>s.isEquipped&&!s.isBroken&&!s.isDestroyed)??[],"getNonBrokenShields");shieldButton.classList.contains("tooltipstered")||$(shieldButton).tooltipster({animation:"fade",trigger:"click",arrow:!1,content:$(messageEl).find("div.hover-content"),contentAsHTML:!0,contentCloning:!0,debug:!1,interactive:!0,side:["top"],theme:"crb-hover",functionBefore:()=>{const tokens=getTokens();if(!tokens.length)return!1;const nonBrokenShields=getNonBrokenShields(tokens),hasMultipleShields=tokens.length===1&&nonBrokenShields.length>1,shieldActivated=shieldButton.classList.contains("shield-activated");return hasMultipleShields&&!shieldActivated?!0:hasMultipleShields&&shieldButton.dataset.shieldId?(shieldButton.attributes.removeNamedItem("data-shield-id"),shieldButton.classList.remove("shield-activated"),CONFIG.PF2E.chatDamageButtonShieldToggle=!1,!0):(shieldButton.classList.toggle("shield-activated"),CONFIG.PF2E.chatDamageButtonShieldToggle=!CONFIG.PF2E.chatDamageButtonShieldToggle,!1)},functionFormat:(instance,_helper,$content)=>{const tokens=getTokens(),nonBrokenShields=getNonBrokenShields(tokens),multipleShields=tokens.length===1&&nonBrokenShields.length>1,shieldActivated=shieldButton.classList.contains("shield-activated");if(multipleShields&&!shieldActivated){const content=$content[0],listEl=htmlQuery(content,"ul.shield-options");if(!listEl)return $content;const shieldList=[];for(const shield of nonBrokenShields){const input=document.createElement("input");input.classList.add("data"),input.type="radio",input.name="shield-id",input.value=shield.id,input.addEventListener("click",()=>{shieldButton.dataset.shieldId=input.value,shieldButton.classList.add("shield-activated"),CONFIG.PF2E.chatDamageButtonShieldToggle=!0,instance.close()});const shieldName=document.createElement("span");shieldName.classList.add("label"),shieldName.innerHTML=shield.name;const hardness=document.createElement("span");hardness.classList.add("tag");const hardnessLabel=game.i18n.localize("PF2E.HardnessLabel");hardness.innerHTML=`${hardnessLabel}: ${shield.hardness}`;const itemLi=document.createElement("li");itemLi.classList.add("item"),itemLi.append(input,shieldName,hardness),shieldList.push(itemLi)}listEl.replaceChildren(...shieldList)}return $content}}).tooltipster("open")}#onClickSender(message,event2){if(!canvas)return;const token=message.token?.object;if(token?.isVisible&&token.isOwner&&(token.controlled?token.release():token.control({releaseOthers:!event2.shiftKey}),event2.type==="dblclick")){const scale=Math.max(1,canvas.stage.scale.x);canvas.animatePan({...token.center,scale,duration:1e3})}}async#onClickSetAsInitiative(message){const{actor,token}=message;if(!token){ui.notifications.error(game.i18n.format("PF2E.Encounter.NoTokenInScene",{actor:message.actor?.name??message.user?.name??""}));return}if(!actor)return;const combatant=await CombatantPF2e.fromActor(actor);if(!combatant)return;const value=message.rolls.at(0)?.total??0;await combatant.encounter.setInitiative(combatant.id,value),ui.notifications.info(game.i18n.format("PF2E.Encounter.InitiativeSet",{actor:token.name,initiative:value}))}_getEntryContextOptions(){const canApplyDamage=__name2($li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});return canvas.tokens.controlled.length>0&&message.rolls.some(r=>r instanceof DamageRoll)},"canApplyDamage"),canApplyTripleDamage=__name2($li=>canApplyDamage($li)&&game.settings.get("pf2e","critFumbleButtons"),"canApplyTripleDamage"),canApplyInitiative=__name2($li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0}),validActor=message.token?.actor?.type==="npc"&&(message.token.combatant?.initiative??null)===null,validRollType=message.isRoll&&message.isCheckRoll;return validActor&&validRollType},"canApplyInitiative"),canReroll=__name2($li=>game.messages.get($li[0].dataset.messageId,{strict:!0}).isRerollable,"canReroll"),canHeroPointReroll=__name2($li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0}),{actor}=message;return message.isRerollable&&!!actor?.isOfType("character")&&actor.heroPoints.value>0},"canHeroPointReroll"),canShowRollDetails=__name2($li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});return game.user.isGM&&!!message.flags.pf2e.context},"canShowRollDetails"),options=super._getEntryContextOptions();return options.push({name:"PF2E.ChatRollDetails.Select",icon:fontAwesomeIcon("search").outerHTML,condition:canShowRollDetails,callback:$li=>{game.messages.get($li[0].dataset.messageId,{strict:!0}).showDetails()}},{name:"PF2E.DamageButton.FullContext",icon:fontAwesomeIcon("heart-broken").outerHTML,condition:canApplyDamage,callback:$li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});applyDamageFromMessage({message})}},{name:"PF2E.DamageButton.HalfContext",icon:fontAwesomeIcon("heart-broken").outerHTML,condition:canApplyDamage,callback:$li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});applyDamageFromMessage({message,multiplier:.5})}},{name:"PF2E.DamageButton.DoubleContext",icon:fontAwesomeIcon("heart-broken").outerHTML,condition:canApplyDamage,callback:$li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});applyDamageFromMessage({message,multiplier:2})}},{name:"PF2E.DamageButton.TripleContext",icon:fontAwesomeIcon("heart-broken").outerHTML,condition:canApplyTripleDamage,callback:$li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});applyDamageFromMessage({message,multiplier:3})}},{name:"PF2E.DamageButton.HealingContext",icon:fontAwesomeIcon("heart").outerHTML,condition:canApplyDamage,callback:$li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});applyDamageFromMessage({message,multiplier:-1})}},{name:"PF2E.ClickToSetInitiativeContext",icon:fontAwesomeIcon("swords").outerHTML,condition:canApplyInitiative,callback:async $li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0}),{actor,token}=message;if(!token){ui.notifications.error(game.i18n.format("PF2E.Encounter.NoTokenInScene",{actor:message.actor?.name??message.user?.name??""}));return}if(!actor)return;const combatant=await CombatantPF2e.fromActor(actor);if(!combatant)return;const value=message.rolls.at(0)?.total??0;await combatant.encounter.setInitiative(combatant.id,value),ui.notifications.info(game.i18n.format("PF2E.Encounter.InitiativeSet",{actor:actor.name,initiative:value}))}},{name:"PF2E.RerollMenu.HeroPoint",icon:fontAwesomeIcon("hospital-symbol").outerHTML,condition:canHeroPointReroll,callback:$li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});CheckPF2e.rerollFromMessage(message,{heroPoint:!0})}},{name:"PF2E.RerollMenu.KeepNew",icon:fontAwesomeIcon("dice").outerHTML,condition:canReroll,callback:$li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});CheckPF2e.rerollFromMessage(message)}},{name:"PF2E.RerollMenu.KeepLower",icon:fontAwesomeIcon("dice-one").outerHTML,condition:canReroll,callback:$li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});CheckPF2e.rerollFromMessage(message,{keep:"lower"})}},{name:"PF2E.RerollMenu.KeepHigher",icon:fontAwesomeIcon("dice-six").outerHTML,condition:canReroll,callback:$li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});CheckPF2e.rerollFromMessage(message,{keep:"higher"})}}),options}}class CompendiumMigrationStatus extends Application{static{__name(this,"CompendiumMigrationStatus")}static{__name2(this,"CompendiumMigrationStatus")}compendium;static get defaultOptions(){const options=super.defaultOptions;return options.template="systems/pf2e/templates/system/compendium-migration-status.hbs",options.classes=["compendium-migration-status"],options.height="auto",options.title=game.i18n.localize("PF2E.CompendiumMigrationStatus.Title"),options}constructor(compendium){super(),this.compendium=compendium}get id(){return`compendium-info-${this.compendium.metadata.id}`}async getData(options){const index=await this.compendium.getIndex({fields:[foundry.utils.randomID(),"system._migration","system.schema","data.schema"]}),schemaVersion=Math.min(...index.map(d=>{const system=d.system??d.data;return Number(system?._migration?.version??system?.schema?.version)})),foundryVersion=pipe(Object.entries(MigrationRunner.FOUNDRY_SCHEMA_VERSIONS),sortBy(([_,schema])=>schema),findLast(([_,schema])=>schemaVersion>=schema))?.[0]??game.i18n.localize("PF2E.CompendiumMigrationStatus.FoundryOld");return{...await super.getData(options),compendium:this.compendium,schemaVersion:Number.isNaN(schemaVersion)?game.i18n.localize("PF2E.CompendiumMigrationStatus.Invalid"):schemaVersion,foundryVersion,module:game.modules.get(this.compendium.metadata.packageName??""),updated:schemaVersion>=MigrationRunner.LATEST_SCHEMA_VERSION,size:index.contents.length}}activateListeners($html){super.activateListeners($html);const html=$html[0];htmlQuery(html,"[data-action=migrate]")?.addEventListener("click",async()=>{await new MigrationRunner(MigrationList.constructFromVersion(null)).runCompendiumMigration(this.compendium),this.render(!0)})}}class CompendiumDirectoryPF2e extends CompendiumDirectory{static{__name(this,"CompendiumDirectoryPF2e")}static{__name2(this,"CompendiumDirectoryPF2e")}static STOP_WORDS=new Set(["of","th","the"]);static searchEngine=new MiniSearch({fields:["name"],idField:"uuid",processTerm:t=>t.length>1&&!this.STOP_WORDS.has(t)?t.toLocaleLowerCase(game.i18n.lang):null,searchOptions:{combineWith:"AND",prefix:!0},storeFields:["uuid","img","name","type","documentType","packLabel"]});static get defaultOptions(){const options=super.defaultOptions;return options.dragDrop.push({dragSelector:"ol.document-matches > li.match"}),{...options,filters:[{inputSelector:"input[type=search]",contentSelector:"ol.directory-list"}],template:"systems/pf2e/templates/sidebar/compendium-directory.hbs"}}get#dragPreview(){const preview=document.createElement("div");preview.id="pack-search-drag-preview";const thumbnail=document.createElement("img"),title=document.createElement("h4");return preview.append(thumbnail,title),preview}async getData(options){return{...await super.getData(options),searchContents:game.user.settings.searchPackContents}}activateListeners($html){super.activateListeners($html),$html[0].querySelector("footer > button")?.addEventListener("click",()=>{game.pf2e.compendiumBrowser.render(!0)})}_getEntryContextOptions(){const options=super._getEntryContextOptions();return options.push({name:"COMPENDIUM.MigrationStatus",icon:fontAwesomeIcon("info").outerHTML,condition:$li=>{const compendium=game.packs.get($li.data("pack"),{strict:!0}),actorOrItem=compendium.documentClass===CONFIG.Actor.documentClass||compendium.documentClass===CONFIG.Item.documentClass,isSystemCompendium=compendium.metadata.packageType==="system";return game.user.isGM&&actorOrItem&&!isSystemCompendium},callback:async $li=>{const compendium=game.packs.get($li.data("pack"),{strict:!0});new CompendiumMigrationStatus(compendium).render(!0)}}),options}_contextMenu($html){super._contextMenu($html),ContextMenu.create(this,$html,"ol.document-matches > li",[{name:"COMPENDIUM.ImportEntry",icon:fontAwesomeIcon("download").outerHTML,condition:$li=>{const{uuid}=$li.get(0)?.dataset??{};if(!uuid)throw ErrorPF2e("Unexpected missing uuid");return game.packs.get(fromUuidSync(uuid)?.pack??"",{strict:!0}).documentClass.canUserCreate(game.user)},callback:$li=>{const{uuid}=$li.get(0)?.dataset??{};if(!uuid)throw ErrorPF2e("Unexpected missing uuid");const packCollection=game.packs.get(fromUuidSync(uuid)?.pack??"",{strict:!0}),worldCollection=game.collections.get(packCollection.documentName,{strict:!0}),indexData=fromUuidSync(uuid)??{_id:""};if(!("_id"in indexData&&typeof indexData._id=="string"))throw ErrorPF2e("Unexpected missing document _id");return worldCollection.importFromCompendium(packCollection,indexData._id,{},{renderSheet:!0})}}])}_onSearchFilter(event2,query,rgx,listElem){super._onSearchFilter(event2,query,rgx,listElem);const html=this.element[0],docMatches=query.length>0?this.constructor.searchEngine.search(query):[],{activeFilters}=this,filteredMatches=this.activeFilters.length>0?docMatches.filter(m=>activeFilters.includes(m.documentType)):docMatches,matchTemplate=htmlQuery(html,".compendium-search-match");if(!matchTemplate)throw ErrorPF2e("Match template not found");const listElements=filteredMatches.map(match=>{const li=matchTemplate.content.firstElementChild?.cloneNode(!0);li.dataset.uuid=match.uuid,li.dataset.score=match.score.toString();const thumbnail=li.querySelector("img");thumbnail&&(typeof match.img=="string"?thumbnail.src=game.pf2e.system.moduleArt.map.get(match.uuid)?.img??match.img:match.documentType==="JournalEntry"&&(thumbnail.src="icons/svg/book.svg")),li.addEventListener("click",async event22=>{event22.stopPropagation();const doc=await fromUuid(match.uuid);await doc?.sheet?.render(!0,{editable:doc.sheet.isEditable})});const anchor=li.querySelector("a"),details=li.querySelector("span"),systemType=["Actor","Item"].includes(match.documentType)?game.i18n.localize(`TYPES.${match.documentType}.${match.type}`):null;return anchor&&details&&(anchor.innerText=match.name,details.innerText=systemType?`${systemType} (${match.packLabel})`:`(${match.packLabel})`),li}),matchesList=htmlQuery(html,"ol.document-matches");if(matchesList){matchesList.replaceChildren(...listElements);for(const dragDrop of this._dragDrop)dragDrop.bind(matchesList)}}_canDragStart(){return!0}_onDragStart(event2){const dragElement=event2.currentTarget,{uuid}=dragElement.dataset;if(!uuid)return super._onDragStart(event2);const indexEntry=fromUuidSync(uuid);if(!indexEntry)throw ErrorPF2e("Unexpected error retrieving index data");document.querySelector("#pack-search-drag-preview")?.remove();const dragPreview=this.#dragPreview.cloneNode(!0),[img,title]=Array.from(dragPreview.childNodes);title.innerText=indexEntry.name??"",img.src="img"in indexEntry&&indexEntry.img?indexEntry.img:"icons/svg/book.svg",document.body.appendChild(dragPreview);const documentType=(()=>indexEntry instanceof foundry.abstract.Document?indexEntry.documentName:game.packs.get(indexEntry.pack??"")?.documentName??null)();documentType&&(event2.dataTransfer.setDragImage(dragPreview,75,25),event2.dataTransfer.setData("text/plain",JSON.stringify({type:documentType,uuid})))}compileSearchIndex(){console.debug("PF2e System | compiling search index");const packs=game.packs.filter(p=>p.index.size>0&&p.testUserPermission(game.user,"OBSERVER"));this.constructor.searchEngine.removeAll();for(const pack of packs){const contents=pack.index.map(i=>({...i,documentType:pack.metadata.type,packLabel:pack.metadata.label}));this.constructor.searchEngine.addAll(contents)}console.debug("PF2e System | Finished compiling search index")}}class EncounterTrackerPF2e extends CombatTracker{static{__name(this,"EncounterTrackerPF2e")}static{__name2(this,"EncounterTrackerPF2e")}async _renderInner(data,options){const $html=await super._renderInner(data,options);if(!game.user.isGM)return $html;const metrics=this.viewed?.metrics;if(!metrics)return $html;const localize=localizer("PF2E.Encounter.Metrics"),threat=(()=>{const label=game.i18n.localize(`PF2E.Encounter.Budget.Threats.${metrics.threat}`),tooltip=localize("Budget",metrics.budget),tempContainer=createHTMLElement("div",{innerHTML:localize("Threat",{threat:label})});return TextEditorPF2e.convertXMLNode(tempContainer,"threat",{classes:["value",metrics.threat]}),{label:tempContainer.innerHTML,tooltip}})(),award=(()=>{const label=localize("Award.Label",{xp:metrics.award.xp}),numRecipients=metrics.award.recipients.length,tooltip=localize(numRecipients===1?"Award.Tooltip.Singular":numRecipients===4?"Award.Tooltip.Four":"Award.Tooltip.Plural",{xpPerFour:metrics.budget.spent,recipients:numRecipients});return{label,tooltip}})(),threatAward=parseHTML(await renderTemplate("systems/pf2e/templates/sidebar/encounter-tracker/threat-award.hbs",{threat,award})),html=$html[0];return htmlQuery(html,"nav.encounters")?.after(threatAward),$(html)}activateListeners($html){const html=$html[0],tracker=htmlQuery(html,"#combat-tracker");if(!tracker)throw ErrorPF2e("No tracker found");const encounter=this.viewed;if(!encounter)return super.activateListeners($html);const tokenSetsNameVisibility=game.pf2e.settings.tokens.nameVisibility,allyColor=__name2(c=>c.actor?.hasPlayerOwner?CONFIG.Canvas.dispositionColors.PARTY:CONFIG.Canvas.dispositionColors.FRIENDLY,"allyColor"),combatantRows=htmlQueryAll(tracker,"li.combatant");for(const row of combatantRows){const combatantId=row.dataset.combatantId??"",combatant=encounter.combatants.get(combatantId,{strict:!0});if(row.dataset.initiative=String(combatant.initiative),combatant?.actor&&this.viewed?.combatant===combatant){const alliance=combatant.actor.alliance,dispositionColor=new foundry.utils.Color(alliance==="party"?allyColor(combatant):alliance==="opposition"?CONFIG.Canvas.dispositionColors.HOSTILE:CONFIG.Canvas.dispositionColors.NEUTRAL);row.style.background=dispositionColor.toRGBA(.1),row.style.borderColor=dispositionColor.toString()}const nameHeader=htmlQuery(row,".token-name h4");if(nameHeader){nameHeader.innerHTML=[createHTMLElement("span",{classes:["name"],children:[nameHeader.innerText]}).outerHTML,createHTMLElement("span",{classes:["users-targeting"]}).outerHTML].join("");for(const control of htmlQueryAll(row,"a.combatant-control")){const controlIcon=htmlQuery(control,"i");if(controlIcon&&(controlIcon.classList.remove("fas"),controlIcon.classList.add("fa-solid","fa-fw"),control.dataset.control==="pingCombatant"&&(controlIcon.classList.remove("fa-bullseye-arrow"),controlIcon.classList.add("fa-signal-stream"),game.scenes.viewed?.tokens.has(combatant.token?.id??"")))){const targetControl=createHTMLElement("a",{classes:["combatant-control"],dataset:{control:"toggleTarget",tooltip:"COMBAT.ToggleTargeting"},children:[fontAwesomeIcon("location-crosshairs",{style:"duotone",fixedWidth:!0})]});control.before(targetControl)}}if(this.refreshTargetDisplay(combatant),tokenSetsNameVisibility){const nameElement=htmlQuery(nameHeader,"span.name");if(nameElement&&!game.user.isGM&&!combatant.playersCanSeeName&&(nameElement.innerText="",row.querySelector("img.token-image")?.removeAttribute("title")),game.user.isGM&&combatant.actor&&combatant.actor.alliance!=="party"){const toggleNameVisibility=document.createElement("a"),isActive=combatant.playersCanSeeName;toggleNameVisibility.classList.add(...["combatant-control",isActive?"active":[]].flat()),toggleNameVisibility.dataset.control="toggleNameVisibility",toggleNameVisibility.dataset.tooltip=game.i18n.localize(isActive?"PF2E.Encounter.HideName":"PF2E.Encounter.RevealName");const icon=fontAwesomeIcon("signature",{fixedWidth:!0});toggleNameVisibility.append(icon),row.querySelector('.combatant-controls a[data-control="toggleHidden"]')?.after(toggleNameVisibility),isActive||row.classList.add("hidden-name")}}}}if(game.user.isGM&&!game.modules.get("combat-enhancements")?.active){Sortable.create(tracker,{animation:200,dataIdAttr:"data-combatant-id",direction:"vertical",dragClass:"drag-preview",dragoverBubble:!0,easing:"cubic-bezier(1, 0, 0, 1)",ghostClass:"drag-gap",onEnd:event2=>this.adjustFinalOrder(event2),onUpdate:event2=>this.#onDropCombatant(event2)});for(const row of combatantRows)row.classList.add("gm-draggable")}super.activateListeners($html)}refreshTargetDisplay(combatantOrToken){if(!this.viewed||!canvas.ready)return;const{combatant,tokenDoc}=combatantAndTokenDoc(combatantOrToken);if(!(combatant?.encounter!==this.viewed||tokenDoc?.combatant!==combatant))for(const tracker of htmlQueryAll(document,"#combat, #combat-popout")){const combatantRow=htmlQuery(tracker,`li.combatant[data-combatant-id="${combatant?.id??null}"]`);if(!combatantRow)return;const usersTargetting=game.users.filter(u=>Array.from(u.targets).some(t=>t.document===tokenDoc)),userIndicators=usersTargetting.map(user=>{const icon=fontAwesomeIcon("location-crosshairs",{style:"duotone",fixedWidth:!0});return icon.style.color=user.color,icon}),targetingSection=htmlQuery(combatantRow,".users-targeting");targetingSection&&(targetingSection.innerHTML=userIndicators.map(i=>i.outerHTML).join(""),targetingSection.dataset.tooltip=game.i18n.format("COMBAT.TargetedBy",{list:localizeList(usersTargetting.map(u=>u.name),{conjunction:"and"})}));const targetControlIcon=htmlQuery(combatantRow,"a.combatant-control[data-control=toggleTarget]");usersTargetting.includes(game.user)?targetControlIcon?.classList.add("active"):targetControlIcon?.classList.remove("active")}}async _onCombatControl(event2){const control=event2.currentTarget.dataset.control;if((control==="rollNPC"||control==="rollAll")&&this.viewed){event2.stopPropagation();const args=eventToRollParams(event2,{type:"check"});await this.viewed[control]({...args,messageOptions:{rollMode:args.rollMode}})}else await super._onCombatControl(event2)}async _onCombatantControl(event2){if(event2.stopPropagation(),!this.viewed)return;const control=event2.currentTarget.dataset.control,li=event2.currentTarget.closest(".combatant"),combatant=this.viewed.combatants.get(li?.dataset.combatantId??"",{strict:!0});switch(control){case"rollInitiative":{await this.viewed.rollInitiative([combatant.id],eventToRollParams(event2,{type:"check"}));break}case"toggleTarget":return this.#onToggleTarget(combatant.token,event2.originalEvent);case"toggleNameVisibility":return combatant.toggleNameVisibility();default:return super._onCombatantControl(event2)}}_onToggleDefeatedStatus(combatant){return combatant.toggleDefeated()}async#onToggleTarget(tokenDoc,event2){if(!tokenDoc)return;const isTargeted=Array.from(game.user.targets).some(t=>t.document===tokenDoc);if(!tokenDoc.object?.visible){ui.notifications.warn("COMBAT.PingInvisibleToken",{localize:!0});return}tokenDoc.object.setTarget(!isTargeted,{releaseOthers:!event2?.shiftKey})}async#onDropCombatant(event2){this.validateDrop(event2);const encounter=this.viewed;if(!encounter)return;const droppedId=event2.item.getAttribute("data-combatant-id")??"",dropped=encounter.combatants.get(droppedId,{strict:!0});if(typeof dropped.initiative!="number"){ui.notifications.error(game.i18n.format("PF2E.Encounter.HasNoInitiativeScore",{actor:dropped.name}));return}const newOrder=this.getCombatantsFromDOM(),oldOrder=encounter.turns.filter(c=>c.initiative!==null);newOrder.every(c=>newOrder.indexOf(c)===oldOrder.indexOf(c))||(this.setInitiativeFromDrop(newOrder,dropped),await this.saveNewOrder(newOrder))}setInitiativeFromDrop(newOrder,dropped){const aboveDropped=newOrder.find(c=>newOrder.indexOf(c)===newOrder.indexOf(dropped)-1),belowDropped=newOrder.find(c=>newOrder.indexOf(c)===newOrder.indexOf(dropped)+1),hasAboveAndBelow=!!aboveDropped&&!!belowDropped,hasAboveAndNoBelow=!!aboveDropped&&!belowDropped,hasBelowAndNoAbove=!aboveDropped&&!!belowDropped,aboveIsHigherThanBelow=hasAboveAndBelow&&belowDropped.initiativec.initiative===dropped.initiative);if(withSameInitiative.length>1)for(let priority=0;priority({id:c.id,value:c.initiative,overridePriority:c.overridePriority(c.initiative)})))}adjustFinalOrder(event2){const row=event2.item,tracker=this.element[0].querySelector("#combat-tracker");if(!tracker)throw ErrorPF2e("Unexpected failure to retriever tracker DOM element");const rows=Array.from(tracker.querySelectorAll("li.combatant")),[oldIndex,newIndex]=[event2.oldIndex??0,event2.newIndex??0],firstRowWithNoRoll=rows.find(row2=>Number.isNaN(Number(row2.dataset.initiative)));Number.isNaN(Number(row.dataset.initiative))?newIndex>oldIndex?tracker.insertBefore(row,rows[oldIndex]):tracker.insertBefore(row,rows[oldIndex+1]):firstRowWithNoRoll&&rows.indexOf(firstRowWithNoRoll)row.getAttribute("data-combatant-id")??"").map(id=>combat.combatants.get(id,{strict:!0})).filter(c=>typeof c.initiative=="number")}}const darkvision=new VisionMode({id:"darkvision",label:"VISION.ModeDarkvision",canvas:{shader:ColorAdjustmentsSamplerShader,uniforms:{enable:!0,contrast:0,saturation:-1,brightness:0}},lighting:{levels:{},background:{visibility:VisionMode.LIGHTING_VISIBILITY.REQUIRED}},vision:{darkness:{adaptive:!0},defaults:{attenuation:0,contrast:0,saturation:-1,brightness:.75,range:1/0}}});class VisionDetectionMode extends DetectionModeBasicSight{static{__name(this,"VisionDetectionMode")}static{__name2(this,"VisionDetectionMode")}constructor(){super({id:"basicSight",label:"DETECTION.BasicSight",type:DetectionMode.DETECTION_TYPES.SIGHT})}_canDetect(visionSource,target){return target instanceof PlaceableObject&&target.document.hidden||target instanceof TokenPF2e&&target.actor?.hasCondition("hidden","undetected","unnoticed")?!1:super._canDetect(visionSource,target)}_testRange(visionSource,mode,target,test){return mode.range>=canvas.dimensions.maxR||super._testRange(visionSource,mode,target,test)}}class HearingDetectionMode extends DetectionMode{static{__name(this,"HearingDetectionMode")}static{__name2(this,"HearingDetectionMode")}constructor(){super({id:"hearing",label:"PF2E.Actor.Creature.Sense.Type.Hearing",type:DetectionMode.DETECTION_TYPES.SOUND})}static getDetectionFilter(){const filter2=this._detectionFilter??=OutlineOverlayFilter.create({wave:!0,knockout:!1});return filter2.thickness=1,filter2}_canDetect(visionSource,target){return!(target instanceof TokenPF2e)||target.document.hidden||!target.actor?.emitsSound?!1:game.pf2e.settings.rbv?target.actor?.hasCondition("undetected","unnoticed")?!1:!visionSource.object.actor?.hasCondition("deafened"):!0}_testLOS(visionSource,_mode,_target,test){test.loh??=new Map;const hearingSource=visionSource.object.hearing,hasLOH=test.loh.get(hearingSource)??hearingSource.shape.contains(test.point.x,test.point.y);return test.loh.set(hearingSource,hasLOH),hasLOH}_testRange(visionSource,mode,target,test){return mode.range>=canvas.dimensions.maxR||super._testRange(visionSource,mode,target,test)}}class DetectionModeTremorPF2e extends DetectionModeTremor{static{__name(this,"DetectionModeTremorPF2e")}static{__name2(this,"DetectionModeTremorPF2e")}constructor(){super({id:"feelTremor",label:"DETECTION.FeelTremor",walls:!1,type:DetectionMode.DETECTION_TYPES.MOVE})}static getDetectionFilter(){const filter2=super.getDetectionFilter();return filter2.thickness=1,filter2}_canDetect(visionSource,target){return super._canDetect(visionSource,target)&&target instanceof TokenPF2e&&!target.document.hidden&&!target.actor?.isOfType("loot")&&!target.actor?.hasCondition("undetected","unnoticed")}}function setPerceptionModes(){CONFIG.Canvas.visionModes.darkvision=darkvision,CONFIG.Canvas.detectionModes.basicSight=new VisionDetectionMode,CONFIG.Canvas.detectionModes.hearing=new HearingDetectionMode,CONFIG.Canvas.detectionModes.feelTremor=new DetectionModeTremorPF2e}__name(setPerceptionModes,"setPerceptionModes"),__name2(setPerceptionModes,"setPerceptionModes");class JournalSheetPF2e extends JournalSheet{static{__name(this,"JournalSheetPF2e")}static{__name2(this,"JournalSheetPF2e")}static get theme(){return null}static get defaultOptions(){const options=super.defaultOptions,{theme}=this;return theme&&options.classes.push(theme),options}}class JournalTextTinyMCESheetPF2e extends JournalTextTinyMCESheet{static{__name(this,"JournalTextTinyMCESheetPF2e")}static{__name2(this,"JournalTextTinyMCESheetPF2e")}async activateEditor(name2,options={},initialContent=""){const editor=await super.activateEditor(name2,options,initialContent),theme=this.object.parent?.sheet.constructor?.theme;return editor.contentDocument.documentElement.classList.add("journal-entry-page","text"),editor.contentDocument.body.classList.add("journal-page-content"),theme&&editor.contentDocument.documentElement.classList.add(theme),editor}}var define_EN_JSON_default={COMBAT:{Begin:"Begin Encounter",CombatantNotInScene:"The participant {name} is not present in your currently viewed scene.",CombatantRemove:"Remove Participant",CombatantStatus:"Participant Status",CombatantUpdate:"Update Participant",End:"End Encounter",EndConfirmation:"End this encounter and empty the turn tracker?",EndTitle:"End Encounter?",NoneActive:"There is no active Encounter in your currently viewed Scene.",NoneRemaining:"There are no participants remaining in this Encounter that are not defeated.",PingCombatant:"Ping Token",PingInvisibleToken:"You can't see this participant's token.",ResourceHint:"Choose an attribute to track for each participant.",Settings:"Encounter Tracker Settings",SidebarTitle:"Encounter Tracker",SkipDefeatedHint:"Automatically bypass participants marked as defeated?",TargetedBy:"Targeted by {list}",ToggleTargeting:"Toggle Targeting",UnknownCombatant:"Unknown Participant"},COMPENDIUM:{MigrationStatus:"Migration Status"},CONTROLS:{AdjustSceneDarkness:"Adjust Scene Darkness",EffectPanel:"Effects Panel",WorldClock:"World Clock"},DOCUMENT:{Combat:"Encounter",Combats:"Encounters"},PF2E:{AbilityBoost:"Attribute Boost",AbilityBoostLevels:"Attribute Boost Levels",AbilityCha:"Charisma",AbilityCheck:{cha:"Charisma Check",con:"Constitution Check",dex:"Dexterity Check",int:"Intelligence Check",str:"Strength Check",wis:"Wisdom Check"},AbilityCon:"Constitution",AbilityDex:"Dexterity",AbilityFlaw:"Flaw",AbilityFree:"Free",AbilityId:{cha:"Cha",con:"Con",dex:"Dex",int:"Int",str:"Str",wis:"Wis"},AbilityInt:"Intelligence",AbilityModifierLabel:"Attribute Modifier",AbilityStr:"Strength",AbilityTitle:"Attribute",AbilityWis:"Wisdom",AccessoryPropertyRuneCalled:"Called",AccessoryPropertyRuneDragonsBreath:"Dragon's Breath",AccessoryPropertyRuneGreaterPaired:"Greater Paired",AccessoryPropertyRuneGreaterWindCatcher:"Greater Wind-Catcher",AccessoryPropertyRuneMajorPaired:"Major Paired",AccessoryPropertyRunePaired:"Paired",AccessoryPropertyRunePresentable:"Presentable",AccessoryPropertyRuneSnagging:"Snagging",AccessoryPropertyRuneSoftLanding:"Soft-Landing",AccessoryPropertyRuneSpellBastion:"Spell-Bastion",AccessoryPropertyRuneWindCatcher:"Wind-Catcher",Action:{RestForTheNight:{Label:"Rest for the Night",Message:{Awakens:"{actor} awakens well-rested.",ConditionReduced:"{condition} reduced by 1.",ConditionRemoved:"No longer {condition}.",FocusPoints:"Focus points restored.",Frequencies:"Action frequencies refreshed.",HitPoints:"{hitPoints} hit points restored.",HitPointsSingle:"{hitPoints} hit point restored.",InfusedReagents:"Infused reagents restored.",Resolve:"Resolve restored.",SpellSlots:"All spell slots restored.",StaminaPoints:"Stamina points restored.",TemporaryItems:"Temporary items removed.",WandsCharges:"Wands recharged."},Prompt:"Rest for the night?"},Strike:{MeleeLabel:"Melee Strike: {weapon}",OutOfRange:"The target is out of range.",RangedLabel:"Ranged Strike: {weapon}"}},ActionActionTypeLabel:"Action Type",ActionActionsLabel:"Actions",ActionBrowserSearchHint:"You can search for name or custom attributes. Possible searchable attributes are: source, spellType, level, materials, target, range, time, duration, damage, damageType, save, concentration, ritual, ability and classes. Example: 'fire, damage:d6' to show all spells that have fire in their name and a d6 in the damage",ActionDeathNoteLabel:"Death Note",ActionNumber1:"One",ActionNumber2:"Two",ActionNumber3:"Three",ActionSkillRequirementLabel:"Requirement",ActionTypeAction:"Action",ActionTypeFree:"Free Action",ActionTypePassive:"Passive",ActionTypeReaction:"Reaction",ActionTypeSingle:"Single Action",ActionWeaponLabel:"Associated Weapon",ActionsActionsHeader:"Actions",ActionsFreeActionsHeader:"Free Actions",ActionsReactionsHeader:"Reactions",Actor:{ApplyDamage:{AtFullHealth:"{actor} is already at full health.",DamagedForN:"{actor} takes {hpDamage} damage.",DamagedForNShield:"{actor}'s shield absorbs {absorbedDamage} damage, with an additional {hpDamage} making it through.",HealedForN:"{actor} is healed for {hpDamage} damage.",InstantDeath:{DeathEffect:"The death effect immediately kills them.",Destroyed:"They are destroyed.",FinePowder:"They are reduced to a fine powder; their gear remains.",MassiveDamage:"The massive damage immediately kills them."},ShieldAbsorbsAll:"{actor} is unscathed, their shield completely absorbing {absorbedDamage} damage.",ShieldDamagedForN:"Their shield is also damaged for {shieldDamage}.",ShieldDamagedForNBroken:"Their shield also takes {shieldDamage} damage, breaking it.",ShieldDamagedForNDestroyed:"Their shield also takes {shieldDamage} damage, destroying it.",ShieldNotRaised:"{actor} has not raised their shield.",TakesNoDamage:"{actor} takes no damage.",TheTarget:"The target"},Attacks:"Attacks",Character:{Attribute:{Apex:"Apex Attribute",Boosts:"Attribute Boosts",Key:"Key Attribute"},AttributeBuilder:{InputMethod:{Description:"Switching method resets your attribute modifier distribution.",Manual:"Manual Entry",Title:"Input Method"},AncestryMissingHelp:"Choose an ancestry to select boosts.",AlternateBoostsLabel:"Alternate Boosts",BackgroundBoostDescription:"Two boosts: one must be {a} or {b}.",BackgroundMissingHelp:"Choose a background to select boosts.",Boost:"Boost",Boosts:"Boosts",ClassMissingHelp:"Choose a class to select boosts.",Complete:"Complete",Flaw:"Flaw",Flaws:"Flaws",Increase:"Increase",KeyIcon:"Key",LegacyFlaws:"Legacy Flaws",Partial:"Partial",NotSelected:"Not Selected",Title:"Assign your boosts",VoluntaryFlaw:{Description:"You can take one or more additional penalties purely for roleplaying a highly flawed character.",LegacyDescription:"This is the Voluntary Flaws feature that existed until the CRB's 4th printing. It is kept in place for older characters and as a continued option for Pathfinder Society play.",Title:"Voluntary Flaws"}},Active:"Active",ActiveHeader:"Active Activities",Biography:{Anathema:{Add:"Add Anathema",Delete:"Delete Anathema"},ToggleVisibility:"Toggle visibility to other players",Edicts:{Add:"Add Edict",Delete:"Delete Edict"}},Blurb:"Level {level} {ancestry} {class}",ClassDC:{Label:"Class DC",LabelSpecific:"Class DC ({class})",Plural:"Class DCs"},Clear:"Clear",Configure:{ShowBasicUnarmed:{Hint:"A PC always has available an unspecific unarmed attack using any part of their body. The attack may be hidden from view if the player never intends to use it.",Label:"Show Basic Unarmed Attack"},Title:"Configure Character"},Crafting:{Cost:"Cost"},HandsOccupied:"Hands Occupied",Proficiency:{Attack:{Advanced:"Advanced Weapons",Martial:"Martial Weapons",Simple:"Simple Weapons",Title:"Attacks",Unarmed:"Unarmed Attacks"},Defense:{Heavy:"Heavy Armor",HeavyBarding:"Heavy Barding",Light:"Light Armor",LightBarding:"Light Barding",Medium:"Medium Armor",Title:"Defenses",Unarmored:"Unarmored Defense"},HigherUpgrade:"{ability} has upgraded this proficiency's rank to {rank}."},Rest:{Label:"Rest for the Night"}},Creature:{Alliance:{Default:"Ownership Default ({alliance})",Neutral:"Neutral",Opposition:"Opposition",Party:"Party"},AttributeModifiers:"Attribute Modifiers",Configure:{Alliance:{Hint:"A creature can be in opposition to the party, allied with it, or neutral. This impacts some mechanics during an encounter, such as flanking.",Label:"Alliance"}},CriticalSpecialization:"Critical Specialization",Language:{adlet:"Adlet",akitonian:"Akitonian",aklo:"Aklo",alghollthu:"Alghollthu",amurrun:"Amurrun",anadi:"Anadi","ancient-osiriani":"Ancient Osiriani",androffan:"Androffan",anugobu:"Anugobu",arboreal:"Arboreal",arcadian:"Arcadian",azlanti:"Azlanti",boggard:"Boggard",calda:"Calda",caligni:"Caligni",chthonian:"Chthonian",common:"Common",cyclops:"Cyclops",daemonic:"Daemonic",destrachan:"Destrachan",diabolic:"Diabolic",draconic:"Draconic",drooni:"Drooni",dwarven:"Dwarven",dziriak:"D'ziriak",ekujae:"Ekujae shape-script","elder-thing":"Elder Thing",elven:"Elven",empyrean:"Empyrean",erutaki:"Erutaki",fey:"Fey",formian:"Formian",garundi:"Garundi",girtablilu:"Girtablilu",gnomish:"Gnomish",goblin:"Goblin",goloma:"Goloma",grioth:"Grioth",grippli:"Grippli",halfling:"Halfling",hallit:"Hallit",hwan:"Hwan",iblydan:"Iblydan",ikeshti:"Ikeshti",immolis:"Immolis",iruxi:"Iruxi",jistkan:"Jistkan",jotun:"Jotun",jyoti:"Jyoti",kaava:"Kaava",kashrishi:"Kashrishi",kelish:"Kelish",kholo:"Kholo",kibwani:"Kibwani",kitsune:"Kitsune",kovintal:"Kovintal",lirgeni:"Lirgeni",mahwek:"Mahwek",migo:"Mi-Go",minaten:"Minatan",minkaian:"Minkaian",muan:"Muan",munavri:"Munavri",mwangi:"Mwangi",mzunu:"Mzunu",nagaji:"Nagaji",necril:"Necril",ocotan:"Ocotan",okaiyan:"Okaiyan",orcish:"Orcish",orvian:"Orvian",osiriani:"Osiriani",petran:"Petran",protean:"Protean",pyric:"Pyric",rasu:"Rasu",ratajin:"Ratajin",razatlani:"Razatlani",requian:"Requian",russian:"Russian",sakvroth:"Sakvroth",samsaran:"Samsaran",sasquatch:"Sasquatch",senzar:"Senzar",shadowtongue:"Shadowtongue",shae:"Shae",shisk:"Shisk",shoanti:"Shoanti",shobhad:"Shobhad",shoony:"Shoony",shory:"Shory",skald:"Skald",sphinx:"Sphinx",strix:"Strix",sussuran:"Sussuran",taldane:"Taldane",talican:"Talican",tekritanin:"Tekritanin",tengu:"Tengu",thalassic:"Thalassic",thassilonian:"Thassilonian",tien:"Tien",utopian:"Utopian",vanara:"Vanara",varisian:"Varisian",varki:"Varki",vishkanyan:"Vishkanyan",vudrani:"Vudrani",wildsong:"Wildsong",wyrwood:"Wyrwood",xanmba:"Xanmba",yithian:"Yithian",ysoki:"Ysoki"},Sense:{Acuity:{Imprecise:"Imprecise",Label:"Acuity",Precise:"Precise",Vague:"Vague"},Label:"Senses",NoRangeLimit:"No Limit",RangeLabel:"Range",Type:{Darkvision:"Darkvision",Echolocation:"Echolocation",GreaterDarkvision:"Greater Darkvision",Hearing:"Hearing",Heatsight:"Heatsight",Lifesense:"Lifesense",LowLightVision:"Low-Light Vision",Motionsense:"Motionsense",Scent:"Scent",SeeInvisibility:"See Invisibility",Spiritsense:"Spiritsense",Thoughtsense:"Thoughtsense",Tremorsense:"Tremorsense",Wavesense:"Wavesense"},WithAcuity:"{sense} ({acuity})",WithAcuityAndRange:"{sense} ({acuity} {range} Ft)"},Shield:{ACBonus:"Shield AC Bonus (When Raised)",BrokenThreshold:"Shield Broken Threshold",Hardness:{Hint:"Shield Hardness",Label:"H"},HitPoints:{Value:"Shield HP",Max:"Shield Max HP"}},SpellPreparation:{Hint:"To prepare a spell, drag one from this list to a slot on the actor sheet.",HintFlexible:"To prepare a spell, enable it here. To prepare a cantrip, drag one from this list to a slot on the actor sheet.",Search:"Search Spells",Title:"{actor}: Spell Preparation"},Spellcasting:{Cantrips:"Cantrips",DC:"Spell DC",InvalidProficiency:"Invalid",Label:"Spell Attack Modifiers & DCs",MagicItemTypesLabel:"Magic Item Types",Rituals:"Rituals",TraditionSpellcasting:"{tradition} Spellcasting",ValidItemTypes:{All:"All Magic Items",Scroll:"Scrolls Only"}}},Dead:"Dead",Familiar:{Blurb:"Familiar of {master}",Master:{ArmorClass:"Master Armor Class",Perception:"Master Perception"}},Hardness:{ShortLabel:"HRD"},Hazard:{EmitsSound:{Encounter:"During Encounters",False:"Never",Hint:"Whether this hazard emits sound and can be sensed via hearing",Title:"Emits Sound?",True:"Always"},Level:"Hazard {level}",Plural:"Hazards",Simple:"Simple",TitleEdit:"{name} (Edit Mode)"},HitPoints:{Unrecoverable:"{value} hit points are currently unrecoverable."},Inventory:{DistributeCoins:"Distribute Coins",Encumbrance:"Encumbrance",ItemQuantity:{Decrease:{Click:"[Click] Decrease by 1",ShiftClick:"[Shift-Click] Decrease by 5",ControlClick:"[Control-Click] Decrease by 10"},Increase:{Click:"[Click] Increase by 1",ShiftClick:"[Shift-Click] Increase by 5",ControlClick:"[Control-Click] Increase by 10"}},Section:{WeaponsAndShields:"Weapons & Shields"},TotalBulk:"Total Bulk: {bulk}"},IWREditor:{DoubleVs:"Double Vs.",Exceptions:"Exceptions",Title:"{actor}: {category}",Type:"Type"},NPC:{Configure:{Lootable:{DefaultLootable:"Global Default (Lootable)",DefaultNotLootable:"Global Default (Not Lootable)",Hint:"Set whether this NPC becomes lootable by players upon its demise. The global default can be configured in Automation Settings.",Label:"Lootable?",Lootable:"Lootable",NotLootable:"Not Lootable"},Title:"Configure NPC"},GenerateAttack:{Confirm:{Content:"An attack has already been generated for this weapon. Would you like to replace it?",Title:"Regenerate attack"},Label:"Generate Attack",Notification:"Generated NPC attack: {attack}"},Identification:{Skills:{Label:"{skills}: DC {dc} ({adjustment})",Tooltip:`"The skill used to identify a creature usually depends on that creature's trait, as shown on Table 10\u20137, but you have leeway on which skills apply." \u2013 CRB pg. 506`},Lore:{Label:"Applicable Lore: DC {dc1} ({adjustment1}) or DC {dc2} ({adjustment2})",Tooltip:'"Using the applicable Lore usually has an easy or very easy DC (before adjusting for rarity)." \u2013 CRB pg. 506'}},SimpleSheet:"Simple NPC Sheet",SkillsEditor:{LorePlaceholder:"Carpentry Lore",Title:"Skills Editor ({actor})"}},Party:{BlankSlate:"This party doesn't have any members. Drag a creature from the actor sidebar to get started.",CheckPrompt:{AdjustDifficulty:"Adjust Difficulty",ChooseLores:"Choose Lores",ChooseSaves:"Choose Saves",ChooseSkills:"Choose Skills/Perception",LevelDC:"Level-Based DC",Post:"Generate Prompt",PromptTitle:"Prompt Title",SecretCheck:"Secret Check",SetDC:"Set DC",SimpleDC:"Simple DC",SkillsPerception:"Skills/Perception",Title:"Generate Check Prompt",TitleShort:"Check Prompt"},Coin:"Coin",ClearActivities:{Label:"Clear",Complete:"Party exploration activities have been cleared"},ClownCar:{Deposit:"Deposit PC Tokens",Retrieve:"Retrieve PC Tokens"},DefaultName:"The Party",InvalidCampaign:{Hint:"The campaign data is invalid",Title:"Invalid Campaign ({party})",Message:{mismatch:"This party has campaign data of type {current}, but the configured type is {campaignType}. Do you want to delete existing campaign data?",error:"This party's campaign data ({current}) is corrupt and failed data preparation. Do you want to delete existing campaign data?"}},Languages:"Party Languages",MembersLabel:"Members: ",NoMembers:"No Members",NoSpecialSenses:"No Special Senses",RemoveMember:{Title:"Remove Member",Content:"Remove member from party?"},Rest:"Rest",Sidebar:{ActivateParty:"Activate Party",CreateMember:"Create New Member",CreateParty:"Create New Party",RemoveMember:"Remove Member",OpenSheet:"Open Sheet",OtherParties:"Other Parties"},Skills:"Party Skills",SlotAvailable:"Slot Available",Tabs:{Overview:"Overview",Exploration:"Exploration",Orphaned:"Orphaned Items",Stash:"Stash"},Total:"Party Total",TravelHeader:"Party Travel and Hexploration",Visibility:{Restricted:"Restricted",Unrestricted:"Unrestricted"},Wealth:"Wealth"},Plural:"Actors"},ActorSizeGargantuan:"Gargantuan",ActorSizeHuge:"Huge",ActorSizeLarge:"Large",ActorSizeMedium:"Medium",ActorSizeSmall:"Small",ActorSizeTiny:"Tiny",AddCoinsCombineStacksLabel:"Combine Stacks",AddCoinsTitle:"Add Coins",AddCombatProficiency:{Message:"Select a weapon group or base weapon",Title:"Add Combat Proficiency"},AddModifierTitle:"Add Modifier",AddShortLabel:"Add",AddSpellTitle:"Add Spell",AddSpellcastingEntryTitle:"Add Spellcasting Entry",AdditionalLanguagePlusInt:"(plus Intelligence)",AdditionalSkills:"Additional Skills",Age:"Age",AllSavesLabel:"All Saves",AncestryFeatLevels:"Ancestry Feat Levels",AncestryFeatures:"Ancestry Features",AncestryHP:"Ancestry HP",AreaLabel:"Area",AreaSize10:"10 Foot",AreaSize100:"100 Foot",AreaSize1000:"1000 Foot",AreaSize120:"120 Foot",AreaSize15:"15 Foot",AreaSize1Mile:"1 Mile",AreaSize20:"20 Foot",AreaSize25:"25 Foot",AreaSize30:"30 Foot",AreaSize360:"360 Foot",AreaSize40:"40 Foot",AreaSize45:"45 Foot",AreaSize5:"5 Foot",AreaSize50:"50 Foot",AreaSize500:"500 Foot",AreaSize60:"60 Foot",AreaSize65:"65 Foot",AreaSize75:"75 Foot",AreaSize80:"80 Foot",AreaSize90:"90 Foot",AreaSizeQuarterMile:"Quarter Mile",AreaTypeBurst:"Burst",AreaTypeCone:"Cone",AreaTypeCube:"Cube",AreaTypeEmanation:"Emanation",AreaTypeLine:"Line",AreaTypeSquare:"Square",ArmorArmorLabel:"AC Bonus",ArmorCheckLabel:"Check Penalty",ArmorCheckPenalty:"Armor Check Penalty",ArmorClassBase:"Base Armor Class 10",ArmorClassLabel:"Armor Class",ArmorClassShortLabel:"AC",ArmorDexLabel:"Dex Modifier Cap",ArmorGreaterResilientRune:"Greater Resilient",ArmorGroupChain:"Chain",ArmorGroupCloth:"Cloth",ArmorGroupComposite:"Composite",ArmorGroupLabel:"Group",ArmorGroupLeather:"Leather",ArmorGroupPlate:"Plate",ArmorGroupSkeletal:"Skeletal",ArmorGroupWood:"Wood",ArmorMajorResilientRune:"Major Resilient",ArmorPotencyRune1:"Armor Potency (+1)",ArmorPotencyRune2:"Armor Potency (+2)",ArmorPotencyRune3:"Armor Potency (+3)",ArmorPotencyRune4:"Armor Potency (+4)",ArmorPropertyRuneAcidResistant:"Acid-Resistant",ArmorPropertyRuneAdvancing:"Advancing",ArmorPropertyRuneAimAiding:"Aim-Aiding",ArmorPropertyRuneAntimagic:"Antimagic",ArmorPropertyRuneAssisting:"Assisting",ArmorPropertyRuneBitter:"Bitter",ArmorPropertyRuneColdResistant:"Cold-Resistant",ArmorPropertyRuneDeathless:"Deathless",ArmorPropertyRuneElectricityResistant:"Electricity-Resistant",ArmorPropertyRuneEnergyAdaptive:"Energy Adaptive",ArmorPropertyRuneEthereal:"Ethereal",ArmorPropertyRuneFireResistant:"Fire-Resistant",ArmorPropertyRuneFortification:"Fortification",ArmorPropertyRuneGlamered:"Glamered",ArmorPropertyRuneGliding:"Gliding",ArmorPropertyRuneGreaterAcidResistant:"Greater Acid-Resistant",ArmorPropertyRuneGreaterAdvancing:"Greater Advancing",ArmorPropertyRuneGreaterColdResistant:"Greater Cold-Resistant",ArmorPropertyRuneGreaterDread:"Greater Dread",ArmorPropertyRuneGreaterElectricityResistant:"Greater Electricity-Resistant",ArmorPropertyRuneGreaterFireResistant:"Greater Fire-Resistant",ArmorPropertyRuneGreaterFortification:"Greater Fortification",ArmorPropertyRuneGreaterInvisibility:"Greater Invisibility",ArmorPropertyRuneGreaterQuenching:"Greater Quenching",ArmorPropertyRuneGreaterReady:"Greater Ready",ArmorPropertyRuneGreaterShadow:"Greater Shadow",ArmorPropertyRuneGreaterSlick:"Greater Slick",ArmorPropertyRuneGreaterStanching:"Greater Stanching",ArmorPropertyRuneGreaterSwallowSpike:"Greater Swallow-Spike",ArmorPropertyRuneGreaterWinged:"Greater Winged",ArmorPropertyRuneImmovable:"Immovable",ArmorPropertyRuneImplacable:"Implacable",ArmorPropertyRuneInvisibility:"Invisibility",ArmorPropertyRuneLesserDread:"Lesser Dread",ArmorPropertyRuneMagnetizing:"Magnetizing",ArmorPropertyRuneMajorQuenching:"Major Quenching",ArmorPropertyRuneMajorShadow:"Major Shadow",ArmorPropertyRuneMajorSlick:"Major Slick",ArmorPropertyRuneMajorStanching:"Major Stanching",ArmorPropertyRuneMajorSwallowSpike:"Major Swallow-Spike",ArmorPropertyRuneMalleable:"Malleable",ArmorPropertyRuneMisleading:"Misleading",ArmorPropertyRuneModerateDread:"Moderate Dread",ArmorPropertyRunePortable:"Portable",ArmorPropertyRuneQuenching:"Quenching",ArmorPropertyRuneRaiment:"Raiment",ArmorPropertyRuneReady:"Ready",ArmorPropertyRuneRockBraced:"Rock-Braced",ArmorPropertyRuneShadow:"Shadow",ArmorPropertyRuneSinisterKnight:"Sinister Knight",ArmorPropertyRuneSlick:"Slick",ArmorPropertyRuneSoaring:"Soaring",ArmorPropertyRuneStanching:"Stanching",ArmorPropertyRuneSwallowSpike:"Swallow-Spike",ArmorPropertyRuneTrueQuenching:"True Quenching",ArmorPropertyRuneTrueStanching:"True Stanching",ArmorPropertyRuneWinged:"Winged",ArmorResilientRune:"Resilient",ArmorSpeedLabel:"Speed Penalty",ArmorStrengthLabel:"Strength Requirement",ArmorTypeHeavy:"Heavy Armor",ArmorTypeLight:"Light Armor",ArmorTypeMedium:"Medium Armor",ArmorTypeUnarmored:"Unarmored",AttackEffectConstrict:"Constrict",AttackEffectGrab:"Grab",AttackEffectGreaterConstrict:"Improved Constrict",AttackEffectImprovedGrab:"Improved Grab",AttackEffectImprovedKnockdown:"Improved Knockdown",AttackEffectImprovedPush:"Improved Push",AttackEffectKnockdown:"Knockdown",AttackEffectPush:"Push",AttackEffectTrip:"Trip",AttackLabel:"Attack",AttitudeLabel:"Attitude",Attitudes:{Friendly:"Friendly",Helpful:"Helpful",Hostile:"Hostile",Indifferent:"Indifferent",Unfriendly:"Unfriendly"},AutomaticBonusProgression:{attackPotency:"Attack Potency",defensePotency:"Defense Potency",devastatingAttacks:"Devastating Attacks",perceptionPotency:"Perception Potency",savePotency:"Save Potency"},Background:"Background",BackgroundSkillFeats:"Skill Feats",BaseModifier:"Base Modifier",BaseWeapons:"Base Weapons",BestiaryBrowserSearchHint:"You can search for name or custom attributes. Possible searchable attributes are: source, spellType, level, materials, target, range, time, duration, damage, damageType, save, concentration, ritual, ability and classes. Example: 'fire, damage:d6' to show all spells that have fire in their name and a d6 in the damage",Biography:"Biography",BiographyAllies:"Allies",BiographyAppearance:"Appearance",BiographyAnathema:"Anathema",BiographyAttitude:"Attitude",BiographyBackStory:"Backstory",BiographyBeliefs:"Beliefs",BiographyBirthPlace:"Birth Place",BiographyCampaignNotes:"Notes",BiographyCampaignNotesHeader:"Campaign",BiographyCatchphrases:"Catchphrases",BiographyDislikes:"Dislikes",BiographyEdicts:"Edicts",BiographyEnemies:"Enemies",BiographyLikes:"Likes",BiographyOrganizations:"Organizations",BiographyPersonalityHeader:"Personality",Bonus:"Bonus",BonusLabel:{ability:"Attribute Bonus",circumstance:"Circumstance Bonus",item:"Item Bonus",proficiency:"Proficiency Bonus",status:"Status Bonus",untyped:"Untyped Bonus"},BonusSPLabel:"Bonus SP",BonusSPperLevel:"Bonus SP per Level",BrowseLabel:"Browse",BrowserClearFilter:"Clear Filter",BrowserClearFilters:"Clear All Filters",BrowserFilterAlignments:"Alignments",BrowserFilterAncestries:"Ancestries",BrowserFilterArmorFilters:"Armor Filters",BrowserFilterCastingTime:"Casting time",BrowserFilterCategory:"Categories",BrowserFilterClass:"Classes",BrowserFilterComplexity:"Hazard Complexities",BrowserFilterConjunction:{AndLabel:"All of above",OrLabel:"Any of above"},BrowserFilterInventoryTypes:"Inventory Types",BrowserFilterLevels:"Levels",BrowserFilterProficiencyRequirements:"Proficiency Requirements",BrowserFilterRarities:"Rarities",BrowserFilterSizes:"Sizes",BrowserFilterSkills:"Skills",BrowserFilterSource:"Source",BrowserFilterSpellCategories:"Categories",BrowserFilterTraditions:"Traditions",BrowserFilterTraits:"Traits",BrowserFilterWeaponFilters:"Weapon Filters",BrowserSearchPlaceholder:"Search Text",BrowserSearchTitle:"Right click for guide",BrowserSettingsSaved:"Settings have been saved",BrowserSortyByLabel:"Sort by",BrowserWarnPackNotLoaded:'Compendium "{pack}" could not be loaded.',BulkMaxLabel:"Max Bulk",CapacityBarLabel:"Capacity",CarryType:{dropped:"Dropped",held1:"Held 1H",held2:"Held 2H",stowed:"Stowed",worn:"Worn","worn-in-slot":"Worn (In Slot)"},CastLabel:"Cast",CastingItemCreateDialog:{"10thLevelWand":"10th level wands don't exist",cantripDeck5:"Cantrip Deck (5-pack)",itemTypeLabel:"Item type: ",label:"Create a spellcasting item from the dropped spell",scroll:"Scroll",spellLevelLabel:"Heightened Rank: ",submit:"Create item",title:"Create a spellcasting item",wand:"Wand"},Category:"Category",CharacterDetails:"Character Details",CharacterLevelLabel:"Level",CharacterNamePlaceholder:"Character Name",CharacterTraits:"Character Traits",CharacterTraitsHeader:"Traits & Other Details",ChatRollDetails:{FlatCheckNoModifiers:"Flat checks never include any modifiers, bonuses, or penalties.",ModifiersAndDice:"Modifiers and Dice",RollOptions:"Roll Options",Select:"Inspect Roll",Title:"Roll Inspector"},Check:{DC:{Label:{AdjustedTarget:"Target: {target}({dcType} {preadjusted}{adjusted})",NoChangeTarget:"Target: {target}({dcType} {adjusted})",NoTarget:"{dcType} {dc}",WithTarget:"Target: {target}({dcType} {dc})"},Specific:{armor:"AC",athletics:"Athletics DC",deception:"Deception DC",fortitude:"Fortitude DC",perception:"Perception DC",reflex:"Reflex DC",stealth:"Stealth DC",will:"Will DC"},Unspecific:"DC"},Label:"Check",Result:{AdjustedLabel:"Result: {unadjusted}{adjusted}by {offset}",Degree:{Attack:{criticalFailure:"Critical Miss",criticalSuccess:"Critical Hit",failure:"Miss",success:"Hit"},Check:{criticalFailure:"Critical Failure",criticalSuccess:"Critical Success",failure:"Failure",success:"Success"}},Label:"Result: {unadjusted}by {offset}"},SetAsInitiative:"Set as {actor}'s initiative",Specific:{Counteract:"Counteract Check",Perception:{Label:"Perception Check",Secret:"Perception Check (Secret)"},Recovery:"Recovery Check"}},CircumstanceBonusShortLabel:"Circumstance",CircumstanceBonusTitle:"Circumstance Bonus",ClassFeatLevels:"Class Feat Levels",ClassFeatures:"Class Features",ClassHP:"Class HP",ClipboardNotification:'Copied "{clipText}" to the clipboard.',CompendiumBrowser:{AddedItem:"Added {item} to the selected actor(s).",AddedItemToCharacter:"Added {item} to {character}.",BestiaryBrowser:"Bestiary Browser",BoughtItemWithAllCharacters:"Purchased {item} with all selected actor(s).",BoughtItemWithCharacter:"Purchased {item} with {character}.",BuyLabel:"Buy Item",FailedToBuyItemWithCharacter:"Could not purchase {item} with {character}.",FailedToBuyItemWithSomeCharacters:"Could not purchase {item} with some of the selected actor(s).",Hint:"Use the tabs above to select a compendium",RollTable:{AddDialogText:"Add {count} result(s) to Roll Table?",AddLabel:"Add to Roll Table",CreateDialogText:"Create Roll Table with {count} result(s)?",CreateLabel:"Create Roll Table",SelectTableTitle:"Select Roll Table",WeightLabel:"Weight"},Settings:{PacksLabel:"Packs",SourcesLabel:"Sources"},TabAction:"Actions",TabBestiary:"Bestiaries",TabCampaign:"Campaign",TabFeat:"Feats/Features",TakeLabel:"Take Item",Title:"Compendium Browser"},CompendiumMigrationStatus:{Document:"Document",Foundry:"Foundry",FoundryOld:"0.7 or older",Invalid:"Invalid",LockedTooltip:"Unable to migrate - compendium is locked",MigrateCompendium:"Migrate Compendium",Schema:"Schema",Size:"Size",Title:"Migration Status",UpToDate:"Up to Date"},Condition:{ActiveLabel:"Active",DurationNumberLabel:"Rounds",DurationTextLabel:"Duration",HasValueLabel:"Has Value",ImmutableLabel:"Immutable",ImmutableTitle:"Value cannot be reduced.",PerpetualLabel:"Perpetual Condition",RemovableLabel:"Removable",ValueLabel:"Value"},ConditionTypeBlinded:"Blinded",ConditionTypeBroken:"Broken",ConditionTypeClumsy:"Clumsy",ConditionTypeConcealed:"Concealed",ConditionTypeConfused:"Confused",ConditionTypeControlled:"Controlled",ConditionTypeDazzled:"Dazzled",ConditionTypeDeafened:"Deafened",ConditionTypeDoomed:"Doomed",ConditionTypeDrained:"Drained",ConditionTypeDying:"Dying",ConditionTypeEncumbered:"Encumbered",ConditionTypeEnfeebled:"Enfeebled",ConditionTypeFascinated:"Fascinated",ConditionTypeFatigued:"Fatigued",ConditionTypeFlatFooted:"Off-Guard",ConditionTypeFleeing:"Fleeing",ConditionTypeFriendly:"Friendly",ConditionTypeFrightened:"Frightened",ConditionTypeGrabbed:"Grabbed",ConditionTypeHelpful:"Helpful",ConditionTypeHidden:"Hidden",ConditionTypeHostile:"Hostile",ConditionTypeImmobilized:"Immobilized",ConditionTypeIndifferent:"Indifferent",ConditionTypeInvisible:"Invisible",ConditionTypeMalevolence:"Malevolence",ConditionTypeObserved:"Observed",ConditionTypeOffGuard:"Off-Guard",ConditionTypeParalyzed:"Paralyzed",ConditionTypePersistent:"Persistent Damage",ConditionTypePersistentShort:"Persistent",ConditionTypePetrified:"Petrified",ConditionTypeProne:"Prone",ConditionTypeQuickened:"Quickened",ConditionTypeRestrained:"Restrained",ConditionTypeSickened:"Sickened",ConditionTypeSlowed:"Slowed",ConditionTypeStunned:"Stunned",ConditionTypeStupefied:"Stupefied",ConditionTypeUnconscious:"Unconscious",ConditionTypeUndetected:"Undetected",ConditionTypeUnfriendly:"Unfriendly",ConditionTypeUnnoticed:"Unnoticed",ConditionTypeWounded:"Wounded",ConditionsLabel:"Conditions",ConsumableMessage:{UseExhausted:"Exhausted {name}",UseMulti:"Uses {name}, {current} remain",UseSingle:"Uses {name}"},CoreSkillsHeader:"Core Skills",Counteractable:"Counteractable",CraftDCTitle:"DC",CraftItemTitle:"Craft",CraftingTab:{Alchemical:{AdvancedAlchemy:"Advanced Alchemy",AdvancedAlchemyLevel:"Advanced Alchemy Level",InfusedReagents:"Infused Reagents",ReagentCost:"Reagent Cost",ToggleSignatureItem:"Toggle Signature Item",TotalCost:"Total Cost"},Alerts:{CharacterLevel:"Item level exceeds character level.",FormulaExpended:"Prepared formula has already been crafted.",ItemMissingTraits:"Item is not compatible with crafting entry item requirements.",MaxItemLevel:"Item level exceeds maximum item level for entry.",MaxSlots:"Crafting entry's allowed slots are full.",MissingReagents:"Insufficient infused reagents to complete crafting."},CraftQuantityTitle:"Quantity",ExpendFormula:"Expend Formula",NoEligibleEntry:"No eligible crafting entry was found.",QuickAddTitle:"Add this formula to one or more crafting entries",RemoveFormulaDialogQuestion:"Are you sure you want to remove the formula for {name}?",RemoveFormulaDialogTitle:"Remove Formula",ToggleFreeCrafting:"Toggle Free Crafting",ToggleQuickAlchemy:"Quick Alchemy",UndeletableTooltip:"This crafting formula is part of another item and cannot be individually deleted.",UnprepareFormulaDialogQuestion:"Are you sure you want to unprepare the formula for {name}?",UnprepareFormulaDialogTitle:"Unprepare Formula"},CreateActionTitle:"Create Action",CreateAttackTitle:"Create Attack",CreateFeatTitle:"Create Feat",CreateFormulaTitle:"Create Formula",CreateItemTitle:"Create Item",CreateLabelUniversal:"Create",CreateSkillTitle:"Create Skill",CreateSpellTitle:"Create Spell",CritFailure:"Critical Failure",CritSuccess:"Critical Success",CriticalDamageLabel:"Critical",CriticalFumbleCardButtonTitle:"Draw a Critical Fumble Card",CriticalHitCardButtonTitle:"Draw a Critical Hit Card",CurrencyAbbreviations:{cp:"cp",gp:"gp",pp:"pp",sp:"sp"},CurrencyCP:"Copper",CurrencyGP:"Gold",CurrencyPP:"Platinum",CurrencySP:"Silver",CurrentHitPointsShortLabel:"Current HP",CurrentStaminaPointsShortLabel:"Current SP",DCAdjustmentEasy:"easy",DCAdjustmentHard:"hard",DCAdjustmentIncrediblyEasy:"incredibly easy",DCAdjustmentIncrediblyHard:"incredibly hard",DCAdjustmentNormal:"baseline",DCAdjustmentVeryEasy:"very easy",DCAdjustmentVeryHard:"very hard",DCBase:"Base DC 10",DCWithValue:"DC {dc} {text}",DCWithValueAndVisibility:'DC {dc} {text}',Damage:{Base:"Base",IWR:{ActorIsImmune:"{actor} is immune to {effect}.",ActorIsUnaffected:"{actor} is unaffected by {effect}.",ApplicationBreakdown:{ignored:"Resistance to {type} ignored!",immunity:"Immune to {type}: {adjustment}",resistance:"Resistant to {type}: {adjustment}",unaffected:"Unaffected by {type}: {adjustment}",weakness:"Weak to {type}: {adjustment}",reduction:"Reduced by {type}: {adjustment}"},CompositeLabel:{Exceptions0DoubleVs0:"{type} {value}",Exceptions0DoubleVs1:"{type} {value} (double resistance vs. {doubleVs1})",Exceptions0DoubleVs2:"{type} {value} (double resistance vs. {doubleVs1} or {doubleVs2})",Exceptions0DoubleVs3:"{type} {value} (double resistance vs. {doubleVs1}, {doubleVs2}, or {doubleVs3})",Exceptions0DoubleVs4:"{type} {value} (double resistance vs. {doubleVs1}, {doubleVs2}, {doubleVs3}, or {doubleVs4})",Exceptions1DoubleVs0:"{type} {value} (except {exception1})",Exceptions1DoubleVs1:"{type} {value} (except {exception1}; double resistance vs. {doubleVs1})",Exceptions1DoubleVs2:"{type} {value} (except {exception1}; double resistance vs. {doubleVs1} or {doubleVs2})",Exceptions1DoubleVs3:"{type} {value} (except {exception1}; double resistance vs. {doubleVs1}, {doubleVs2}, or {doubleVs3})",Exceptions1DoubleVs4:"{type} {value} (except {exception1}; double resistance vs. {doubleVs1}, {doubleVs2}, {doubleVs3}, or {doubleVs4})",Exceptions2DoubleVs0:"{type} {value} (except {exception1} or {exception2})",Exceptions2DoubleVs1:"{type} {value} (except {exception1} or {exception2}; double resistance vs. {doubleVs1})",Exceptions2DoubleVs2:"{type} {value} (except {exception1} or {exception2}; double resistance vs. {doubleVs1} or {doubleVs2})",Exceptions2DoubleVs3:"{type} {value} (except {exception1} or {exception2}; double resistance vs. {doubleVs1}, {doubleVs2}, or {doubleVs3})",Exceptions2DoubleVs4:"{type} {value} (except {exception1} or {exception2}; double resistance vs. {doubleVs1}, {doubleVs2}, {doubleVs3}, or {doubleVs4})",Exceptions3DoubleVs0:"{type} {value} (except {exception1}, {exception2}, or {exception3})",Exceptions3DoubleVs1:"{type} {value} (except {exception1}, {exception2}, or {exception3}; double resistance vs. {doubleVs1})",Exceptions3DoubleVs2:"{type} {value} (except {exception1}, {exception2}, or {exception3}; double resistance vs. {doubleVs1} or {doubleVs2})",Exceptions3DoubleVs3:"{type} {value} (except {exception1}, {exception2}, or {exception3}; double resistance vs. {doubleVs1}, {doubleVs2}, or {doubleVs3})",Exceptions3DoubleVs4:"{type} {value} (except {exception1}, {exception2}, or {exception3}; double resistance vs. {doubleVs1}, {doubleVs2}, {doubleVs3}, or {doubleVs4})",Exceptions4DoubleVs0:"{type} {value} (except {exception1}, {exception2}, {exception3}, or {exception4})",Exceptions4DoubleVs1:"{type} {value} (except {exception1}, {exception2}, {exception3}, or {exception4}; double resistance vs. {doubleVs1})",Exceptions4DoubleVs2:"{type} {value} (except {exception1}, {exception2}, {exception3}, or {exception4}; double resistance vs. {doubleVs1} or {doubleVs2})",Exceptions4DoubleVs3:"{type} {value} (except {exception1}, {exception2}, {exception3}, or {exception4}; double resistance vs. {doubleVs1}, {doubleVs2}, or {doubleVs3})",Exceptions4DoubleVs4:"{type} {value} (except {exception1}, {exception2}, {exception3}, or {exception4}; double resistance vs. {doubleVs1}, {doubleVs2}, {doubleVs3}, or {doubleVs4})"},Type:{abysium:"abysium",adamantine:"adamantine","all-damage":"all damage","area-damage":"area damage","arrow-vulnerability":"arrow vulnerability",auditory:"auditory","axe-vulnerability":"axe vulnerability",blinded:"blinded",broken:"broken",clumsy:"clumsy","cold-iron":"cold iron",confused:"confused",controlled:"controlled","critical-hits":"critical hits",curse:"curse","damage-from-spells":"damage from spells",dawnsilver:"dawnsilver",dazzled:"dazzled",deafened:"deafened","death-effects":"death effects",disease:"disease",djezet:"djezet",doomed:"doomed",drained:"drained",duskwood:"duskwood",emotion:"emotion",energy:"energy",enfeebled:"enfeebled",fascinated:"fascinated",fatigued:"fatigued","fear-effects":"fear effects",fleeing:"fleeing",frightened:"frightened","ghost-touch":"ghost touch",glass:"glass",grabbed:"grabbed",healing:"healing",hidden:"hidden",holy:"holy",illusion:"illusion",immobilized:"immobilized",inhaled:"inhaled",inubrix:"inubrix",light:"light",magic:"magic",magical:"magical",metal:"metal","misfortune-effects":"misfortune effects","non-magical":"non-magical",nonlethal:"nonlethal","nonlethal-attacks":"nonlethal attacks",noqual:"noqual","object-immunities":"object immunities","off-guard":"off-guard",olfactory:"olfactory",orichalcum:"orichalcum",paralyzed:"paralyzed","persistent-damage":"persistent damage",petrified:"petrified",physical:"physical",plant:"plant",polymorph:"polymorph",possession:"possession",prone:"prone","protean-anatomy":"protean anatomy",radiation:"radiation",restrained:"restrained",salt:"salt","salt-water":"salt water",scrying:"scrying",siccatite:"siccatite",sickened:"sickened",silver:"silver",sleep:"sleep",slowed:"slowed","spell-deflection":"spell deflection",spells:"spells","splash-damage":"splash damage",stunned:"stunned",stupefied:"stupefied","swarm-attacks":"swarm attacks","swarm-mind":"swarm mind",trip:"trip","unarmed-attacks":"unarmed attacks",unconscious:"unconscious",unholy:"unholy","vampire-weaknesses":"vampire weaknesses",visual:"visual",vorpal:"vorpal","vorpal-adamantine":"vorpal adamantine","vorpal-fear":"vorpal fear","vulnerable-to-sunlight":"vulnerable to sunlight",water:"water",weapons:"weapons","weapons-shedding-bright-light":"weapons shedding bright light",wood:"wood",wounded:"wounded"}},Hardness:{Full:"hardness",Half:"half hardness"},IncreasedFrom:"Increased from {original} to minimum of 1",Kind:{Both:{Label:"Both",Roll:{Noun:"Damage/Healing Roll",Verb:"Roll Damage/Healing"}},Damage:{Roll:{Noun:"Damage Roll",Verb:"Roll Damage"}},Healing:{Apply:{Label:"Apply Healing"},Roll:{Noun:"Healing Roll",Verb:"Roll Healing"}}},NoDamageFormulaLabel:"No damage",PersistentTooltip:"Persistent {damageType}",Precision:"Precision",RollFlavor:{acid:"acid",air:"air",bleed:"bleed",bludgeoning:"bludgeoning",cold:"cold",earth:"earth",electricity:"electricity",fire:"fire",force:"force",mental:"mental",metal:"metal",persistent:"persistent {damageType}",piercing:"piercing",poison:"poison",precision:"precision",slashing:"slashing",sonic:"sonic",spirit:"spirit",splash:"splash",vitality:"vitality",void:"void",untyped:"untyped"},Scatter:"Scatter Damage"},DamageButton:{Adjust:"[Shift-Click] Adjust value before applying.",Double:"[Click] Apply double damage to selected tokens.",DoubleContext:"Double Damage",DoubleShort:"Double",Full:"[Click] Apply full damage to selected tokens.",FullContext:"Apply Damage",FullShort:"Damage",Half:"[Click] Apply half damage to selected tokens.",HalfContext:"Half Damage",HalfShort:"Half",Healing:"[Click] Apply full healing to selected tokens.",HealingContext:"Apply Healing",HealingShort:"Heal",ShieldBlock:"[Click] Toggle the shield block status of the selected tokens before applying damage.",ShieldBlockContext:"Shield Block",ShieldBlockShort:"Block",Triple:"[Click] Apply triple damage to selected tokens.",TripleContext:"Apply Triple Damage",TripleShort:"Triple"},DamageCategoriesLabel:"Damage Categories",DamageDieD10:"d10",DamageDieD12:"d12",DamageDieD4:"d4",DamageDieD6:"d6",DamageDieD8:"d8",DamageLabel:"Damage",DamageRoll:"Damage Roll",DecrementEffectTitle:"Decrease Effect Level",DefensesLabel:"Defenses",Deity:"Deity",DeleteQuestion:"Are you sure you want to delete {name}?",DeleteConditionTitle:"Delete Condition",DeleteItemTitle:"Delete Item",DeleteShortLabel:"Delete",DeleteSpellcastEntryQuestion:"Are you sure you want to delete this spellcasting entry?",DeleteSpellcastEntryTitle:"Delete Spellcasting",DeleteSpellcastEntryWarning:"WARNING: All spells in this spellcasting entry will also be deleted.",DenominationLabel:"Denomination",DetailsHeading:"Details",DragDropFeats:"Drag & Drop feats to add",Duration:{P1M:"month",P1W:"week",P1Y:"year",PT10M:"10 minutes",PT1H:"hour",PT1M:"minute",PT24H:"24 hours",day:"day",round:"round",turn:"turn"},Edit:"Edit",EditHazardLabel:"Edit Hazard",EditItemTitle:"Edit Item",EditLabel:"Edit?",EffectPanel:{AppliedBy:"Applied by: {condition-list}",DecrementToolTip:"[Right Click] Decrease value",Expired:"Expired",IncrementToolTip:"[Left Click] Increase value",RemainingDuration:{MultipleDays:"{days} days remaining",MultipleHours:"{hours} hours remaining",MultipleMinutes:"{minutes} minutes remaining",MultipleRounds:"{rounds} rounds remaining",MultipleSeconds:"{seconds} seconds remaining",MultipleWeeks:"{weeks} weeks remaining",MultipleYears:"{years} years remaining",SingleRound:"1 round remaining",SingleSecond:"1 second remaining",SingleWeek:"1 week remaining",SingleYear:"1 year remaining",ZeroRoundsExpireTurnEnd:"0 rounds remaining, expires end of initiative {initiative}",ZeroRoundsExpireTurnStart:"0 rounds remaining, expires start of initiative {initiative}"},RemoveToolTip:"[Right Click] Remove effect",RollDamageToolTip:"[Left Click] Roll damage",Sustained:"Sustained?",Unidentified:"Unidentified",UnlimitedDuration:"Unlimited duration",UntilEncounterEnds:"Until encounter ends"},EffectsLabel:"Effects",EmptySlot:"Empty Slot",Encounter:{AlreadyRolled:"{actor} has already rolled initiative.",Broadcast:{FastHealing:{DeactivatedBy:"Deactivated by {types}","fast-healing":{Name:"Fast Healing",ReceivedMessage:"Received fast healing"},regeneration:{Name:"Regeneration",ReceivedMessage:"Received regeneration"}},TempHP:{PluralNew:"{actor} now has {newQuantity} temporary hit points{wasAt} from {item}.",SingleNew:"{actor} now has {newQuantity} temporary hit point{wasAt} from {item}.",WasAt:" (was at {oldQuantity})"}},Budget:{EncounterBudget:"Encounter Budget",PartyLevel:"Party Level",PartySize:"Party Size",Reward:"Reward",Threat:"Threat",Threats:{extreme:"Extreme",low:"Low",moderate:"Moderate",severe:"Severe",trivial:"Trivial"},XPBudget:"XP Budget",XPNeeded:"XP Needed"},CreatureXPAndRole:{CreatureLevel:"Creature Level",CreatureLevels:{0:"Any standard creature or low-threat boss",1:"Low- or moderate-threat boss",2:"Moderate- or severe-threat boss",3:"Severe- or extreme-threat boss",4:"Extreme-threat solo boss","-1":"Any standard creature","-2":"Any lackey or standard creature","-3":"Low- or moderate-threat lackey","-4":"Low-threat lackey"},CreatureXPAndRole:"Creature XP and Role",SuggestedRole:"Suggested Role"},ExcludingFromInitiative:"Excluding {type} {actor} from initiative.",HasNoInitiativeScore:"{actor} has no initiative score.",HideName:"Hide Name",InitiativeSet:"Initiative of {actor} was set to {initiative}.",Metrics:{Award:{Label:"Award: {xp} XP",Tooltip:{Four:"4 Party Members",Plural:"{xpPerFour} \xD7 4 / {recipients} Party Members",Singular:"1 Party Member"}},Budget:"Budget: {spent}/{max} XP (Party Level {partyLevel})",Threat:"Threat: {threat}"},NoActiveEncounter:"There is no active encounter.",NoTokenInScene:"{actor} has no token in the scene.",RevealName:"Reveal Name",XP:"XP"},ErrorMessage:{CantCreateEffectMacro:"An effect for a toggle macro must come from a compendium or world item.",CantImportTooHighVersion:"Unable to import {sourceName}: its schema version ({sourceSchemaVersion}) is higher than this world's ({worldSchemaVersion}).",CantMoveItemDestination:"You are not allowed to move items to this character.",CantMoveItemSource:"You are not allowed to move items from this character.",ItemNotFoundByUUID:'Item with UUID of "{uuid}" not found.',MinimumProfLevelSetByFeatures:"The selected proficiency is below proficiency set by features.",NoCreatureTokenSelected:"Select at least one token associated with a creature.",NoPCTokenSelected:"Select at least one token associated with a PC.",NoTokenSelected:"Select at least one token.",NoUpdatePermission:"You lack permission to update this actor.",NotEnoughAmmo:"You don't have enough ammo to make this strike.",NotEnoughCoins:"Insufficient Coins",RuleElementSyntax:"Syntax error in rule element definition: {message}",SubV9Module:"{module} is unmaintained and may introduce stability issues to your game.",WeaponNoDamage:"This weapon deals no damage.",WeaponQuantityZero:"You have no more of these weapons equipped."},Ethnicity:"Ethnicity",ExpendSpellTitle:"Expend Spell",Failure:"Failure",Familiar:{AbilitiesLabel:"Abilities",ArmorClass:"Armor Class",AttackRoll:"Attack Roll",Creature:"Creature",CreatureType:"Creature Type",Defenses:"Defense",Familiar:"Familiar",Master:"Master",MasterActor:"Master Actor",MasterLevel:"Master Level",MasterSpellcastingAbility:"Master Attribute",Offenses:"Offenses",Perception:"Perception",SelectMaster:"Select a master...",Skills:"Skills",TotalNumberFamiliarAbilities:"Total # of Familiar Abilities"},FeatActionTypeLabel:"Action Type",FeatActionsLabel:"Number of Actions",FeatAncestryHeader:"Ancestry Feats",FeatArchetypeHeader:"Archetype Feats",FeatBackgroundShort:"BG",FeatBonusHeader:"Bonus Feats",FeatBrowserSearchHint:"You can search for name or custom attributes. Possible searchable attributes are: source, spellType, level, materials, target, range, time, duration, damage, damageType, save, concentration, ritual, ability and classes. Example: 'fire, damage:d6' to show all spells that have fire in their name and a d6 in the damage",FeatCampaignHeader:"Campaign Feats",FeatClassHeader:"Class Feats",FeatDeityBoonCursesHeader:"Divine Intercessions",FeatGeneralHeader:"General Feats",FeatLevelLabel:"Level",FeatPFSBoonHeader:"Society Boons",FeatPrereqLabel:"Prerequisites",FeatSkillHeader:"Skill Feats",FeatTypeAncestry:"Ancestry Feat",FeatTypeAncestryfeature:"Ancestry Feature",FeatTypeBonus:"Bonus Feat",FeatTypeClass:"Class Feat",FeatTypeClassfeature:"Class Feature",FeatTypeCurse:"Deity Curse",FeatTypeDeityboon:"Deity Boon",FeatTypeGeneral:"General Feat",FeatTypePfsboon:"Society Boon",FeatTypeSkill:"Skill Feat",FeaturesAncestryHeader:"Ancestry Features",FeaturesClassHeader:"Class Features",Feet:"feet",FlatCheck:"Flat Check",Focus:{NotEnoughFocusPointsError:"You do not have enough focus points to cast this spell.",Outdated:"Old value of the focus pool as a reminder. Click to delete.",Pool:"Focus Pool",Previous:"Previous",Spells:"Focus Spells",label:"Focus Points",pointLabel:"Points"},Foot:"Foot",FormulaKnownTitle:"Known Formulas",FormulaListEmpty:"Empty (drag formula/item here)",Formula:"Formula",FormulaSheet:{DescriptionUnknown:"This formula is completely filled with drawings of small stick men, stains from some unknown liquid, nonsensical rhymes written in children's letters, and other seemingly random markings. It must have been made by goblins, and makes no sense to you.Note This formula is referencing a missing or invalid item.",NameEmpty:"Empty Formula",NamePrefix:"Formula of {name}",NameUnknown:"Unknown Formula"},Frequency:{AtWill:"At-Will",Label:"Frequency",per:"per"},GenderPronoun:"Gender/Pronouns",GeneralFeatLevels:"General Feat Levels",GreaterWeaponSpecialization:"Greater Weapon Specialization",HardnessLabel:"Hardness",HazardDescriptionLabel:"Description",HazardDisableLabel:"Disable",HazardResetLabel:"Reset",HazardRoutineLabel:"Routine",HealingTypeTemporaryHealing:"Healing (Temporary)",Height:"Height",Heritage:"Heritage",HeroPointRatio:{Many:"{value}/{max} Hero Points",One:"1/{max} Hero Point"},HeroPointsLabel:"Hero Points",HitPointsDetailsLabel:"HP Details",HitPointsDetailsTitle:"Additional information related to Hit Points such as Fast Healing or Regeneration",HitPointsHeader:"Hit Points",HitPointsShortLabel:"HP",ImageLabel:"Image",ImmunitiesLabel:"Immunities",IncrementEffectTitle:"Increase Effect Level",InitiativeIsNow:"{name}'s Initiative is now {value}!",InitiativeHeader:"Initiative bonus",InitiativeLabel:"Initiative",InitiativeWithSkill:"Initiative: {skillName}",InlineCheck:{BasicWithSave:"Basic {save}",DCWithName:"{name} DC",Invalid:"Invalid @Check expression: {message}",Errors:{AdjustmentLengthMismatch:"mismatch between number of type and adjustment parameters",DCAndDefense:"cannot have both dc and defense arguments",NonIntegerAdjustment:"adjustments must be integers",TypeMissing:"type argument is mandatory",InvalidDomains:"{type} domains must be sluggified and end with -damage"}},InlineDamage:{Base:"Base: {formula}"},InlineTemplateErrors:{DistanceMissing:"Error in @Template: distance parameter is mandatory",DistanceNoNumber:"Error in @Template: dimension {distance} is not a number",TypeMissing:"Error in @Template: type parameter is mandatory",TypeUnsupported:"Error in @Template: type {type} is not supported",WidthNoNumber:"Error in @Template: width {width} is not a number"},InventroyBrowserSearchHint:"You can search for name or custom attributes. Possible searchable attributes are: source, spellType, level, materials, target, range, time, duration, damage, damageType, save, concentration, ritual, ability and classes. Example: 'fire, damage:d6' to show all spells that have fire in their name and a d6 in the damage",InvestedLabel:"Invested",Item:{ABC:{InvalidDrop:"{badType} cannot be dropped here (must be {goodType})"},Action:{Category:{None:"None",Defensive:"Defensive",Interaction:"Interaction",Offensive:"Offensive",Familiar:"Familiar Ability"},Plural:"Abilities",SelfAppliedEffect:{Applied:"{effect} was applied.",Delete:"Delete Reference",Drop:"Drop Effect",Label:"Self-Applied Effect",Hint:"A single effect item to be applied to the actor that uses this action"},Type:{Activity:"Activity",Free:"Free Action",Single:"Single Action",Reaction:"Reaction"}},Activation:{Add:"Add Activation",Cast:"Cast a Spell",Command:"command",CommandSheetLabel:"Command",Envision:"envision",EnvisionSheetLabel:"Envision",Interact:"Interact",Label:"Activation"},Affliction:{AddStage:"Add Stage",Error:{RestrictedStageItem:"Only effect items can be directly added to afflictions"},Linked:{Title:"If set, prevents the condition from being removed while the affliction lasts"},OnsetLabel:"Onset",OnsetActive:"Onset Active",SaveLabel:"Save DC",Stage:"Stage {stage}",StageLabel:"Stage"},Ancestry:{Vision:{Label:"Vision",Normal:"Normal Vision"}},Armor:{Base:{"armored-cloak":"Armored Cloak","armored-coat":"Armored Coat","bastion-plate":"Bastion Plate",breastplate:"Breastplate","buckle-armor":"Buckle Armor","ceramic-plate":"Ceramic Plate","chain-mail":"Chain Mail","chain-shirt":"Chain Shirt","coral-armor":"Coral Armor","explorers-clothing":"Explorer's Clothing","fortress-plate":"Fortress Plate","full-plate":"Full Plate",gi:"Gi","half-plate":"Half Plate","hellknight-breastplate":"Hellknight Breastplate","hellknight-half-plate":"Hellknight Half Plate","hellknight-plate":"Hellknight Plate","hide-armor":"Hide Armor","lamellar-breastplate":"Lamellar Breastplate","lattice-armor":"Lattice Armor","leaf-weave":"Leaf Weave","leather-armor":"Leather Armor","leather-lamellar":"Leather Lamellar","mantis-shell":"Mantis Shell",niyahaat:"Niyah\xE1at","o-yoroi":"O-Yoroi","padded-armor":"Padded Armor","power-suit":"Power Suit","quilted-armor":"Quilted Armor",sankeit:"Sankeit","scale-mail":"Scale Mail","scroll-robes":"Scroll Robes","splint-mail":"Splint Mail","studded-leather-armor":"Studded Leather Armor","subterfuge-suit":"Subterfuge Suit","wooden-breastplate":"Wooden Breastplate"},Category:{"heavy-barding":"Heavy Barding","light-barding":"Light Barding"},Rune:{Resilient:{Label:"Resilient Rune"}},Specific:{Hint:"Marking this armor as specific magic armor indicates that it does more than what its material composition and runes allow. The name, level, rarity, and price will no longer be overridden from precious material or runes at the time of marking. Those material and runes will, however, serve as a baseline for level, rarity, and price adjustments from later upgrades.",Label:"Specific Magic Armor"},UnequippedHint:"This armor is bulkier due to not being equipped."},CampaignFeature:{CampaignLabel:"Campaign"},CannotAddType:"{type} items cannot be added to this actor.",Condition:{Flanked:"Off-Guard (Flanked)",PersistentDamage:{AssistedRecovery:"Roll Assisted Recovery",Chat:{Recover:"Roll Recovery Check",RecoverLabel:"Recovery: {name}"},Dialog:{Add:"Add Persistent Damage",Invalid:"Formula is invalid.",Remove:"Remove Persistent Damage",Title:"Persistent Damage ({actor})"},Error:{DoesNotExist:"No persistent {damageType} damage exists on the actor"},Name:"Persistent Damage ({formula} {damageType})",NameWithDC:"Persistent Damage ({formula} DC{dc})",RollDamage:"Roll Damage"}},Consumable:{Damage:{Add:"Add Damage/Healing",Label:"Damage/Healing",Remove:"Remove Damage/Healing"},Category:{ammo:"Ammunition",catalyst:"Catalyst",drug:"Drug",elixir:"Elixir",fulu:"Fulu",gadget:"Gadget",mutagen:"Mutagen",oil:"Oil",other:"Other",poison:"Poison",potion:"Potion",scroll:"Scroll",snare:"Snare",talisman:"Talisman",toolkit:"Toolkit",wand:"Wand"},Plural:"Consumables",Uses:{AutoDestroy:"Destroy on Use",Label:"Uses",None:"No Uses Remain",Use:"Use"}},Container:{Bulk:{Capacity:"Bulk Capacity",Ignored:"Bulk Ignored"},Plural:"Containers",Stowing:"Is Stowing Container?"},CreationDialog:{Categories:{Character:"Character Building",Other:"Other",Physical:"Physical Items"}},Deity:{Alignment:"Alignment",Category:{Hint:"Pantheons of deities and philosophies not associated with any deity can be followed instead of a particular deity. Clerics and Champions must follow a deity or pantheon.",Pantheon:"Pantheon",Philosophy:"Philosophy"},ClericSpells:{DropError:"A deity's cleric spells may not include cantrips, focus spells, or rituals.",Hint:"To add a spell, drag and drop one onto this sheet.",Label:"Cleric Spells"},DivineAttribute:{Hint:"If choosing the Raised by Belief background, its attribute boost options come from a deity.",Label:"Divine Attribute"},DivineFont:{Harm:"Harm",Heal:"Heal",Label:"Divine Font"},DivineSkill:"Divine Skill",Domain:{Abomination:{Description:"You seek to instill abhorrence and horror in those around you.",Label:"Abomination"},Air:{Description:"You can control winds and the weather.",Label:"Air"},AirApocryphal:{Description:"You can control winds and the weather. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Air (apocryphal)"},Ambition:{Description:"You strive to keep up with and outpace the competition.",Label:"Ambition"},AmbitionApocryphal:{Description:"You strive to keep up with and outpace the competition. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Ambition (apocryphal)"},Change:{Description:"You can restructure the physical and metaphysical.",Label:"Change"},Cities:{Description:"You have powers over urban environments and denizens.",Label:"Cities"},Cold:{Description:"You control ice, snow, and freezing temperatures.",Label:"Cold"},Confidence:{Description:"You overcome your fear and project pride.",Label:"Confidence"},ConfidenceApocryphal:{Description:"You overcome your fear and project pride. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Confidence (apocryphal)"},Creation:{Description:"You have divine abilities related to crafting and art.",Label:"Creation"},Darkness:{Description:"You operate in the darkness and take away the light.",Label:"Darkness"},DarknessApocryphal:{Description:"You operate in the darkness and take away the light. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Darkness (apocryphal)"},Death:{Description:"You have the power to end lives and destroy undead.",Label:"Death"},DeathApocryphal:{Description:"You have the power to end lives and destroy undead. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Death (apocryphal)"},Decay:{Description:"You have the power to spoil and deteriorate matter.",Label:"Decay"},Delirium:{Description:"You can bring about hallucinations and restlessness.",Label:"Delirium"},Destruction:{Description:"You are a conduit for divine devastation.",Label:"Destruction"},Dreams:{Description:"You have the power to enter and manipulate dreams.",Label:"Dreams"},Dust:{Description:"You have the power to dry and crumble what opposes you.",Label:"Dust"},Duty:{Description:"You defend oaths and carry out your divine missions with great dedication.",Label:"Duty"},Earth:{Description:"You control soil and stone.",Label:"Earth"},Family:{Description:"You aid and protect your family and community more effectively.",Label:"Family"},Fate:{Description:"You see and understand hidden inevitabilities.",Label:"Fate"},FateApocryphal:{Description:"You see and understand hidden inevitabilities. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Fate (apocryphal)"},Fire:{Description:"You control flame.",Label:"Fire"},FireApocryphal:{Description:"You control flame. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Fire (apocryphal)"},Freedom:{Description:"You liberate yourself and others from shackles and constraints.",Label:"Freedom"},Glyph:{Description:"You wield power over written words and symbols.",Label:"Glyph"},Healing:{Description:"Your healing magic is particularly potent.",Label:"Healing"},Indulgence:{Description:"You feast mightily and can shake off the effects of overindulging.",Label:"Indulgence"},IndulgenceApocryphal:{Description:"You feast mightily and can shake off the effects of overindulging. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Indulgence (apocryphal)"},Introspection:{Description:"You guide others in examining their lives, emotions, and motivations to ultimately become a truer version of themselves\u2014a difficult and often painful process.",Label:"Introspection"},Knowledge:{Description:"You receive divine insights.",Label:"Knowledge"},KnowledgeApocryphal:{Description:"You receive divine insights. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Knowledge (apocryphal)"},Lightning:{Description:"You control electricity, thunder, and storms.",Label:"Lightning"},Luck:{Description:"You're unnaturally lucky and keep out of harm's way.",Label:"Luck"},Magic:{Description:"You perform the unexpected and inexplicable.",Label:"Magic"},Metal:{Description:"You manipulate flexible, mutable metal.",Label:"Metal"},Might:{Description:"Your physical power is bolstered by divine strength.",Label:"Might"},MightApocryphal:{Description:"Your physical power is bolstered by divine strength. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Might (apocryphal)"},Moon:{Description:"You command powers associated with the moon.",Label:"Moon"},Naga:{Description:"Like the serpentine nagas, you're in tune with cosmic forces that Ravithra once controlled.",Label:"Naga"},Nature:{Description:"You hold power over animals and plants.",Label:"Nature"},Nightmares:{Description:"You fill minds with horror and dread.",Label:"Nightmares"},Pain:{Description:"You punish those who displease you with the sharp sting of pain.",Label:"Pain"},Passion:{Description:"You evoke passion, whether as love or lust.",Label:"Passion"},Perfection:{Description:"You strive to perfect your mind, body, and spirit.",Label:"Perfection"},Plague:{Description:"You wield disease and pestilence like a weapon.",Label:"Plague"},Protection:{Description:"You ward yourself and others.",Label:"Protection"},Repose:{Description:"You ease mental burdens.",Label:"Repose"},Secrecy:{Description:"You protect secrets and keep them hidden.",Label:"Secrecy"},SecrecyApocryphal:{Description:"You protect secrets and keep them hidden. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Secrecy (apocryphal)"},Sorrow:{Description:"You have a painful connection to melancholy and sadness.",Label:"Sorrow"},Soul:{Description:"You wield power over the spiritual.",Label:"Soul"},Star:{Description:"You command the power of the stars.",Label:"Star"},Sun:{Description:"You harness the power of the sun and other light sources, and punish undead.",Label:"Sun"},Swarm:{Description:"You exert control over masses of creatures.",Label:"Swarm"},Time:{Description:"You reign over the flow of time.",Label:"Time"},Toil:{Description:"You work constantly and refuse to let anything stand in your way.",Label:"Toil"},Travel:{Description:"You have power over movement and journeys.",Label:"Travel"},TravelApocryphal:{Description:"You have power over movement and journeys. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Travel (apocryphal)"},Trickery:{Description:"You deceive others and cause mischief.",Label:"Trickery"},Truth:{Description:"You pierce lies and discover the truth.",Label:"Truth"},Tyranny:{Description:"You wield power to rule and enslave others.",Label:"Tyranny"},Undeath:{Description:"Your magic carries close ties to the undead.",Label:"Undeath"},Vigil:{Description:"You watch over those long passed and guard their secrets.",Label:"Vigil"},Void:{Description:"You draw power from emptiness.",Label:"Void"},Water:{Description:"You control water and bodies of water.",Label:"Water"},WaterApocryphal:{Description:"You control water and bodies of water. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Water (apocryphal)"},Wealth:{Description:"You hold power over wealth, trade, and treasure.",Label:"Wealth"},Wood:{Description:"You command the indomitable power of wood.",Label:"Wood"},Wyrmkin:{Description:"You draw on the power of dragons, linnorms, and other powerful reptilian creatures.",Label:"Wyrmkin"},Zeal:{Description:"Your inner fire increases your combat prowess.",Label:"Zeal"}},Domains:{Alternate:{Hint:"A cleric can take the Expanded Domain Initiate feat to gain access to one of their deity's alternate domains.",Label:"Alternate Domains"},Primary:"Primary Domains"},FavoredWeapons:{Hint:"Almost all deities have a single favored weapon, but a few have both a favored weapon and unarmed attack.",Label:"Favored Weapon(s)"},Sanctification:{Can:{Holy:"can choose holy",HolyUnholy:"can choose holy or unholy",Unholy:"can choose unholy"},Label:"Divine Sanctification",Must:{Holy:"must choose holy",Unholy:"must choose unholy"},None:"none"},Spellcasting:"Spellcasting"},Effect:{Expiry:{EndOfRound:"End of Round",EndOfTurn:"End of Turn",ExpiresOn:"Expires On",StartOfTurn:"Start of Turn"},Badge:{Add:"Add Badge",Labels:{Add:"Add Label",Label:"Labels",Hint:"The values of a badge can be given descriptive labels. They should be short enough to fit in the effects panel. Labels also serve as a natural maximum value for a badge.",Placeholder:"New Label"},Range:"Range",ReevaluateFormula:{Label:"Reevaluate?",Never:"Never",TurnEnd:"On Turn End",TurnStart:"On Turn Start"},Type:{counter:"Counter",formula:"Formula",value:"Fixed Value"}},Disintegrated:{Description:"Maybe it's a treatable condition.",Name:"Disintegrated"},Plural:"Effects",ShowTokenIcon:"Show token icon?",Sustained:"Sustained",Unidentified:"Unidentified?"},Feat:{Info:{Added:"{item} was added to {category}."},KeyAbilityOptions:{Label:"Key Attribute Options",Hint:"Key attribute options in addition to this provided by a class"},LevelLabel:"Feat",LevelN:"Feat {level}",OnlyLevel1:"Must be taken at level 1",Plural:"Feats",TakeMultiple:{Five:"Up to 5\xD7",Four:"Up to 4\xD7",Label:"Can be taken multiple times",NoLimit:"No limit",Three:"Up to 3\xD7",Two:"Up to 2\xD7"},Warning:{InvalidCategory:'Cannot add feat "{item}" to {category}: feat type is invalid.',TakenAfterLevel1:"{item} must be taken at level 1, but {actor} is at level {actorLevel}.",TakenMoreThanMax:"{item} may only be taken {maxTakable} times, but {actor} has selected it {timesTaken} times.",TakenMoreThanOnce:"{item} may only be taken once, but {actor} has selected it an additional time."}},GMNotes:{Add:"Add GM Notes",Title:"GM Notes"},Heritage:{AncestryNotFound:"The referenced ancestry item was not found.",DragAncestryHere:"Drag an ancestry item here to set this heritage's prerequisite ancestry.",NoneVersatile:"None (Versatile)",RemoveAncestry:"Remove prerequisite ancestry"},IconLabel:"Icon",MaterialEffects:{Hint:"Precious-material damage effects that can trigger or bypass some creatures' immunities, weaknesses, and resistances (applied to inline damage rolls)",Label:"Material Damage Effects"},NameLabel:"Name",OtherTags:{Label:"Other Tags",Hint:"Additional tags beyond traits to help classify an item"},Physical:{Base:"Base",Broken:"Broken",BrokenThreshold:{Label:"Broken Threshold",ShortLabel:"BT"},Bulk:{HeldOrStowed:"Bulk (held/stowed)",Label:"Bulk",Light:{Label:"Light",ShortLabel:"L"},Negligible:{Label:"Negligible",ShortLabel:"\u2014"},NLight:"{light}L",WithLight:"{bulk}, {light}L"},Destroyed:"Destroyed",FromSpell:{CantripDeck5:"Cantrip Deck of {name} (5-pack)",Scroll:"Scroll of {name} (Rank {level})",Wand:"Wand of {name} (Rank {level})"},GeneratedName:{FourProperties:"{property1} {property2} {property3} {property4} {base}",FourPropertiesMaterial:"{property1} {property2} {property3} {property4} {material} {base}",Fundamental2:"{fundamental2} {base}",Fundamental2Material:"{fundamental2} {material} {base}",Hint:'This is the name of the base weapon. For most weapons, the base is used to generate a fuller name, taking into account the material composition and/or runes. Giving this weapon a custom name or marking it as "specific" will prevent the generated name from appearing.',Material:"{material} {base}",OneProperty:"{property1} {base}",OnePropertyMaterial:"{property1} {material} {base}",Potency:"+{potency} {base}",PotencyFourProperties:"+{potency} {property1} {property2} {property3} {property4} {base}",PotencyFourPropertiesMaterial:"+{potency} {property1} {property2} {property3} {property4} {material} {base}",PotencyFundamental2:"+{potency} {fundamental2} {base}",PotencyFundamental2FourProperties:"+{potency} {fundamental2} {property1} {property2} {property3} {property4} {base}",PotencyFundamental2FourPropertiesMaterial:"+{potency} {fundamental2} {property1} {property2} {property3} {property4} {material} {base}",PotencyFundamental2Material:"+{potency} {fundamental2} {material} {base}",PotencyFundamental2OneProperty:"+{potency} {fundamental2} {property1} {base}",PotencyFundamental2OnePropertyMaterial:"+{potency} {fundamental2} {property1} {material} {base}",PotencyFundamental2ThreeProperties:"+{potency} {fundamental2} {property1} {property2} {property3} {base}",PotencyFundamental2ThreePropertiesMaterial:"+{potency} {fundamental2} {property1} {property2} {property3} {material} {base}",PotencyFundamental2TwoProperties:"+{potency} {fundamental2} {property1} {property2} {base}",PotencyFundamental2TwoPropertiesMaterial:"+{potency} {fundamental2} {property1} {property2} {material} {base}",PotencyMaterial:"+{potency} {material} {base}",PotencyOneProperty:"+{potency} {property1} {base}",PotencyOnePropertyMaterial:"+{potency} {property1} {material} {base}",PotencyThreeProperties:"+{potency} {property1} {property2} {property3} {base}",PotencyThreePropertiesMaterial:"+{potency} {property1} {property2} {property3} {material} {base}",PotencyTwoProperties:"+{potency} {property1} {property2} {base}",PotencyTwoPropertiesMaterial:"+{potency} {property1} {property2} {material} {base}",Reinforcing:"{reinforcing} {base}",ReinforcingMaterial:"{reinforcing} {material} {base}",ThreeProperties:"{property1} {property2} {property3} {base}",ThreePropertiesMaterial:"{property1} {property2} {property3} {material} {base}",TwoProperties:"{property1} {property2} {base}",TwoPropertiesMaterial:"{property1} {property2} {material} {base}"},LevelLabel:"Item {level}",OtherTag:{Herbal:"Herbal",Improvised:"Improvised",Shoddy:"Shoddy"},OtherTags:{Hint:"These are tags indicating classifications in Second Edition rules that lack explicit status/definition but are still yet heavily relied upon. Some may be automatically added when other properties are present.",Label:"Other Tags"},MaterialRunes:{Label:"Precious Material and Runes"},PriceLabel:"Price: {price}",Usage:{WornParenthetical:"Worn ({where})",WornSlot:{amulet:"Amulet",anklets:"Anklets",armbands:"Armbands",armor:"Armor",backpack:"Backpack",barding:"Barding",belt:"Belt",beltpouch:"Belt Pouch",bracelet:"Bracelet",bracers:"Bracers",circlet:"Circlet",cloak:"Cloak",clothing:"Clothing",collar:"Collar",crown:"Crown",epaulet:"Epaulet",eyepiece:"Eyepiece",footwear:"Footwear",garment:"Garment",gloves:"Gloves",headwear:"Headwear",horseshoes:"Horseshoes",mask:"Mask",necklace:"Necklace",onbelt:"On Belt",ring:"Ring",saddle:"Saddle",shoes:"Shoes",wrist:"On Wrists"}}},Plural:"Items",RefreshFromCompendium:{Label:"Refresh",SourceNotFound:'The compendium source for "{item}" (source ID: {sourceId}) was not found.',Tooltip:{Disabled:"Item cannot be refreshed: contains data stored at time of adding to actor",Enabled:"Refresh this item's data with the latest from its originating compendium."}},RemovalPrevented:"Removal of {item} is prevented by {preventer}.",Rules:{Apply:"Apply",Close:"Close",Edit:"Edit JSON",Hint:{Slug:"A stable, human-readable identifier: if set, it will remain in place even if the item is renamed.",SourceId:"The UUID of the original compendium item",UUID:"A universally unique identifier for this item"},New:"New Rule Element",RegenerateSlug:"(Re)generate Slug",Remove:"Remove Rule Element",Tab:"Rules"},Shield:{Base:{buckler:"Buckler","casters-targe":"Caster's Targe","dart-shield":"Dart Shield","fortress-shield":"Fortress Shield","gauntlet-buckler":"Gauntlet Buckler","harnessed-shield":"Harnessed Shield","heavy-rondache":"Heavy Rondache","hide-shield":"Hide Shield",klar:"Klar","meteor-shield":"Meteor Shield","razor-disc":"Razor Disc","salvo-shield":"Salvo Shield","steel-shield":"Steel Shield","swordstealer-shield":"Swordstealer Shield","tower-shield":"Tower Shield","wooden-shield":"Wooden Shield"},Rune:{Reinforcing:{Greater:"Greater Reinforcing",Label:"Reinforcing Rune",Lesser:"Lesser Reinforcing",Major:"Major Reinforcing",Minor:"Minor Reinforcing",Moderate:"Moderate Reinforcing",Supreme:"Supreme Reinforcing"}},Specific:{Hint:"Marking this shield as a specific magic shield indicates that it does more than what its material composition and runes allow. The name, level, rarity, and price will no longer be overridden from precious material or runes at the time of marking. Those material and runes will, however, serve as a baseline for level, rarity, and price adjustments from later upgrades.",Label:"Specific Magic Shield"}},SidebarSummary:"{type} Summary",Spell:{Area:"{size}-{unit} {shape}",Cast:"Cast",Cost:"Cost",Counteract:{Hint:"If you're counteracting an affliction, the DC is in the affliction's stat block. If it's a spell, use the caster's DC. The GM can also calculate a DC based on the target effect's level.",Label:"Counteract",criticalFailure:"You fail to counteract the target.",criticalSuccess:"Counteract the target if its counteract rank is {rank} or less.",failure:"Counteract the target if its counteract rank is less than {rank}.",success:"Counteract the target if its counteract rank is {rank} or less."},Defense:{BasicSave:"Basic",Label:"Defense"},LevelN:"Spell {level}",MeasuredTemplate:{Clear:"Clear Placed Templates",Place:"Place {area}"},Plural:"Spells",Rank:{Label:"Rank",Ordinal:"{rank} Rank",Plural:"Ranks"},Ritual:{Label:"Ritual",PrimaryCheck:"Primary Check",SecondaryChecks:"Secondary Checks",SecondaryCasters:"Secondary Casters"},Variants:{DeleteDialogText:"Are you sure you want to delete '{variantName}'?",DeleteDialogTitle:"Delete Spell Variant",LabelPlural:"Spell Variants",SelectOtherVariantLabel:"Select Other Variant",SelectVariantLabel:"Select Variant",SheetTitle:"{originalName} (Variant)"},Warning:{InvalidLevel:"Attempted to add spell {name} at {targetLevel}, but spell is {baseLevel}.",WrongSpellType:"Cannot add {spellType} spell to this casting entry."}},Weapon:{CanBeAmmo:{Label:"Usable as Ammo",Hint:"Indicate that this weapon can be loaded into another weapon as ammunition."},CriticalSpecialization:{axe:"Choose one creature adjacent to the initial target and within reach. If its AC is lower than your attack roll result for the critical hit, you deal damage to that creature equal to the result of the weapon damage die you rolled (including extra dice for its potency rune, if any). This amount isn't doubled, and no bonuses or other additional dice apply to this damage.",bomb:"Increase the radius of the bomb's splash damage (if any) to 10 feet.",bow:"If the target of the critical hit is adjacent to a surface, it gets stuck to that surface by the missile. The target is @UUID[Compendium.pf2e.conditionitems.Item.eIcWbB5o3pP6OIMe]{Immobilized} and must spend an Interact action to attempt a @Check[type:athletics|dc:10|name:Pull the Missile Free|showDC:all] check to pull the missile free; it can't move from its space until it succeeds. The creature doesn't become stuck if it is incorporeal, is liquid (like a water elemental or some oozes), or could otherwise escape without effort",brawling:"The target must succeed at a @Check[type:fortitude|dc:resolve(@actor.attributes.classDC.value)|name:Brawling Critical Specialization] save or be @UUID[Compendium.pf2e.conditionitems.Item.xYTAsEpcJE1Ccni3]{Slowed 1} until the end of your next turn.",club:"You knock the target away from you up to 10 feet (you choose the distance). This is forced movement.",firearm:"The target must succeed at a @Check[type:fortitude|dc:resolve(@actor.attributes.classDC.value)|name:Firearm Critical Specialization] save or be @UUID[Compendium.pf2e.conditionitems.Item.dfCMdR4wnpbYNTix]{Stunned 1}.",flail:"The target is knocked @UUID[Compendium.pf2e.conditionitems.Item.j91X7x0XSomq8d60]{Prone} unless they success at a @Check[type:reflex|dc:resolve(@actor.attributes.classDC.value)|name:Flail Critical Specialization] save against your class DC.",hammer:"The target is knocked @UUID[Compendium.pf2e.conditionitems.Item.j91X7x0XSomq8d60]{Prone} unless they succeed at a @Check[type:fortitude|dc:resolve(@actor.attributes.classDC.value)|name:Hammer Critical Specialization] save against your class DC.",polearm:"The target is moved 5 feet in a direction of your choice. This is forced movement.",shield:"You knock the target back from you 5 feet. This is forced movement.",sling:"The target must succeed at a @Check[type:fortitude|dc:resolve(@actor.attributes.classDC.value)|name:Sling Critical Specialization] save or be @UUID[Compendium.pf2e.conditionitems.Item.dfCMdR4wnpbYNTix]{Stunned 1}.",spear:"The weapon pierces the target, weakening its attacks. The target is @UUID[Compendium.pf2e.conditionitems.Item.i3OJZU2nk64Df3xm]{Clumsy 1} until the start of your next turn.",sword:"The target is made off-balance by your attack, becoming @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} until the start of your next turn."},Damage:{DiceNumber:"Dice Number"},FromABP:"Automatic bonus progression has adjusted this weapon's {property} to {value}.",FromMaterialAndRunes:"Precious materials and runes on this item have adjusted its {property} to {value}.",HandsLabel:"Hands",MandatoryMelee:"This weapon has a trait that can only be used with melee weapons.",MaterialAndRunes:{MaterialOption:"{type} ({grade})",Title:"Material Composition and Runes"},MeleeUsage:{Hint:"A combination weapon has a firearm form or usage and a melee weapon form or usage. Switching between the melee weapon usage and the firearm usage requires an Interact action. However, if your last action was a successful melee Strike against a foe using a combination weapon, you can make a firearm Strike with the combination weapon against that foe without fully switching to the firearm usage, firing the firearm just as you hit with the melee attack. In this case, the combination weapon returns to its melee usage after the firearm Strike.",Label:"Melee Usage"},NoRangeMelee:"None (Melee)",RangeIncrementN:{Hint:"Ranged and thrown weapons have a range increment. Attacks with these weapons work normally up to that distance. Attack rolls beyond a weapon's range increment take a -2 penalty for each additional multiple of that increment between you and the target. Attacks beyond the sixth range increment are impossible.",Label:"Range Increment {range} ft."},Reload:{LabelN:"Reload {value}",OneMinute:"1 min"},Rune:{Potency:"Weapon Potency",Striking:{Greater:"Greater Striking",Major:"Major Striking",Striking:"Striking"}},SpecificMagicWeapon:{Hint:"Marking this weapon as a specific magic weapon indicates that it does more than what its material composition and runes allow. The name, level, rarity, and price will no longer be overridden from precious material or runes at the time of marking. Those material and runes will, however, serve as a baseline for level, rarity, and price adjustments from later upgrades.",Label:"Specific Magic Weapon"},ThrownUsage:{Label:"Thrown Usage"}},WorldItemWarning:"This is a World Item and will not work if saved in a compendium"},ItemBonus0:"0",ItemBonus1:"+1 Weapon Potency",ItemBonus2:"+2 Weapon Potency",ItemBonus3:"+3 Weapon Potency",ItemBonusLabel:"Item Bonus",ItemBonusMinus2:"Shoddy (-2)",ItemBonusShortLabel:"Item",ItemDescription:"Description",ItemDescriptionHeader:"Description",ItemDetails:"Details",ItemLevel:"{type} {level}",ItemMystification:"Mystification",ItemMystified:"Mystified",ItemNamePlaceholder:"Name",ItemNewSkillVariant:"New Skill Variant",ItemNotSupportedOnActor:"Item not supported on actor",ItemRemoveRuleElement:"Remove Rule Element",ItemTitle:"Item",ItemsLabel:"Items",Keybinding:{CycleTokenStack:{Hint:"Cycle the Z indices of a mouse-hovered stack of tokens, pushing the top to the bottom.",Label:"Cycle Token Stack"},GMVision:{Hint:"Brighten dark scenes for easier viewing.",Label:"GM Vision"},TogglePartySheet:{Hint:"Open or close the sheet of the active or (if a player) assigned party.",Label:"Toggle Party Sheet"}},KitItems:"Items",KitWorldItem:"This item is not found in a Compendium and will not work in other worlds",LackCastConsumableCapability:"{actor} lacks the proficiency to use {spell} and does not have the Trick Magic Item feat.",Languages:"Languages",LanguagesAdditional:"Additional Languages",Level1:"Level 1",Level10:"Level 10",Level11:"Level 11",Level12:"Level 12",Level13:"Level 13",Level14:"Level 14",Level15:"Level 15",Level16:"Level 16",Level17:"Level 17",Level18:"Level 18",Level19:"Level 19",Level2:"Level 2",Level20:"Level 20",Level3:"Level 3",Level4:"Level 4",Level5:"Level 5",Level6:"Level 6",Level7:"Level 7",Level8:"Level 8",Level9:"Level 9",LevelLabel:"Level",LevelN:"Level {level}",LevelRange:"Levels {minLevel} - {level}",LicenseViewer:{Label:"Legal Notice",LandingPageText:"Use the tabs above to read the legal information"},ListPartsAnd:{end:"{first}, and {second}",middle:"{first}, {second}",start:"{first}, {second}",two:"{first} and {second}"},ListPartsOr:{end:"{first}, or {second}",middle:"{first}, {second}",start:"{first}, {second}",two:"{first} or {second}"},Lore:"Lore",LoreProficiencyDisclaimer:"Informational only. Will not change the skill modifier.",LoreSkillsHeader:"Lore Skills",MAPAbbreviationLabel:"MAP {penalty}",MAPAbbreviationValueLabel:"{value} (MAP {penalty})",Macro:{OptionToggle:{Notification:"{toggle} has been toggled {state}.",Off:"OFF",On:"ON"},Plural:"Macros",NoCompendiumItem:"A macro cannot be created from a compendium item that isn't an effect or condition."},MacroActionNoActionError:"This action no longer exists!",MacroActionNoActorError:"This actor no longer exists!",MagicTraditionLabel:"Magic Tradition",MagicTraditionUseSpellLabel:"Use Spell Tradition",MasterAbility:{cha:"Master Charisma",con:"Master Constitution",dex:"Master Dexterity",int:"Master Intelligence",str:"Master Strength",wis:"Master Wisdom"},MasterArmorClass:"Master Armor Class {base}",MasterLevel:"Master Level",MasterSavingThrow:{fortitude:"Master Fortitude",reflex:"Master Reflex",will:"Master Will"},MaxHitPointsBaseLabel:"Base Max HP {base}",MaxHitPointsShortLabel:"Max HP",MaxStaminaPointsShortLabel:"Max SP",Migrations:{Finished:"PF2E System Migration to version {version} completed!",OnlyGMCanUse:"Only a gamemaster can use this tool.",OutsideSchemaRange:"The specified range is outside the system's schema version range (between {minimum} and {maximum}).",Running:"Running system migration ...",Starting:"Applying PF2E System Migration to version {version}. Please be patient and do not close your game or shut down your server.",Summary:{Documents:"Documents",HelpResources:'An unexpected error was encountered while migrating some actors or items. If you would like further assistance, feel free to report an issue at the system repository or visit us on Discord for community support.',Migrated:"Migrated",Remigrate:"Remigrate",Title:"Migration Summary",Total:"Total",Troubleshoot:{Hint:"Here you can run a remigration, which will attempt to automatically fix issues with actors and items.",Title:"System Troubleshooting"}},Troubleshooting:"Troubleshooting",WorldNotReady:"Game world not ready: try again in a few seconds."},ModifierNamePlaceholder:"Name",ModifierTitle:"Modifier",ModifierType:{ability:"Attribute",circumstance:"Circumstance",item:"Item",potency:"Potency",proficiency:"Proficiency",status:"Status",untyped:"Untyped"},ModifierTypeTitle:"[Type]",ModifiersTitle:"Modifiers",MultipleAttackPenalty:"Multiple Attack Penalty",MysticStrikes:"Mystical Strikes",NPC:{Abilities:{Glossary:{AllAroundVision:"
This monster can see in all directions simultaneously, and therefore can't be flanked.
",AquaticAmbush:`
Requirements The monster is hiding in water and a creature that hasn't detected it is within the listed number of feet.
Effect The monster moves up to its swim Speed + 10 feet toward the triggering creature, traveling on water and on land. Once the creature is in reach, the monster makes a Strike against it. The creature is @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} against this Strike.
`,AtWillSpells:"
The monster can cast its at-will spells any number of times without using up spell slots.
",AttackOfOpportunity:`
Trigger A creature within the monster's reach uses a manipulate action or a move action, makes a ranged attack, or leaves a square during a move action it's using.
Effect The monster attempts a melee Strike against the triggering creature. If the attack is a critical hit and the trigger was a manipulate action, the monster disrupts that action. This Strike doesn't count toward the monster's multiple attack penalty, and its multiple attack penalty doesn't apply to this Strike.
`,Aura:`
A monster's aura automatically affects everything within a specified emanation around that monster. The monster doesn't need to spend actions on the aura; rather, the aura's effects are applied at specific times, such as when a creature ends its turn in the aura or when creatures enter the aura.
If an aura does nothing but deal damage, its entry lists only the radius, damage, and saving throw. Such auras deal this damage to a creature when the creature enters the aura and when a creature starts its turn in the aura. A creature can take damage from the aura only once per round.
The GM might determine that a monster's aura doesn't affect its own allies. For example, a creature might be immune to a monster's frightful presence if they have been around each other for a long time.
`,Buck:`
Most monsters that serve as mounts can attempt to buck off unwanted or annoying riders, but most mounts will not use this reaction against a trusted creature unless the mounts are spooked or mistreated.
Trigger A creature @UUID[Compendium.pf2e.actionspf2e.Item.PM5jvValFkbFH3TV]{Mounts} or uses the @UUID[Compendium.pf2e.actionspf2e.Item.q9nbyIF0PEBqMtYe]{Command an Animal} action while riding the monster.
Effect The triggering creature must succeed at a Reflex saving throw against the listed DC or fall off the creature and land @UUID[Compendium.pf2e.conditionitems.Item.j91X7x0XSomq8d60]{Prone}. If the save is a critical failure, the triggering creature also takes [[/roll 1d6[bludgeoning]]]{1d6 bludgeoning damage} in addition to the normal damage for the fall.
`,CatchRock:`
Requirements The monster must have a free hand but can @UUID[Compendium.pf2e.actionspf2e.Item.wQYmDStjdjn0I26t]{Release} anything it's holding as part of this reaction.
Trigger The monster is targeted with a thrown rock Strike or a rock would fall on the monster.
Effect The monster gains a +4 circumstance bonus to its AC against the triggering attack or to any defense against the falling rock. If the attack misses or the monster successfully defends against the falling rock, the monster catches the rock, takes no damage, and is now holding the rock.
`,ChangeShape:"
The monster changes its shape indefinitely. It can use this action again to return to its natural shape or adopt a new shape. Unless otherwise noted, a monster cannot use Change Shape to appear as a specific individual. Using Change Shape counts as creating a disguise for the @UUID[Compendium.pf2e.actionspf2e.Item.AJstokjdG6iDjVjE]{Impersonate} use of Deception. The monster's transformation automatically defeats Perception DCs to determine whether the creature is a member of the ancestry or creature type into which it transformed, and it gains a +4 status bonus to its Deception DC to prevent others from seeing through its disguise. Change Shape abilities specify what shapes the monster can adopt. The monster doesn't gain any special abilities of the new shape, only its physical form. For example, in each shape, it replaces its normal Speeds and Strikes, and might potentially change its senses or size. Any changes are listed in its stat block.
",ConstantSpells:"
A constant spell affects the monster without the monster needing to cast it, and its duration is unlimited. If a constant spell gets counteracted, the monster can reactivate it by spending the normal spellcasting actions the spell requires.
",Constrict:"
The monster deals the listed amount of damage to any number of creatures @UUID[Compendium.pf2e.conditionitems.Item.kWc1fhmv9LBiTuei]{Grabbed} or @UUID[Compendium.pf2e.conditionitems.Item.VcDeM8A5oI6VqhbM]{Restrained} by it. Each of those creatures can attempt a basic Fortitude save with the listed DC.
",Coven:`
This monster can form a coven with two or more other creatures who also have the coven ability. This involves performing an 8-hour ceremony with all prospective coven members. After the coven is formed, each of its members gains elite adjustments, adjusting their levels accordingly. Coven members can sense other members' locations and conditions by spending a single action, which has the concentrate trait, and can sense what another coven member is sensing as a two-action activity, which has the concentrate trait as well.
Covens also grant spells and rituals to their members, but these can be cast only in cooperation between three coven members who are all within 30 feet of one another. A coven member can contribute to a coven spell with a single-action spellcasting activity that has a single verbal component. If two coven members have contributed these actions within the last round, a third member can cast a coven spell on her turn by spending the normal spellcasting actions. A coven can cast its coven spells an unlimited number of times but can cast only one coven spell each round. All covens grant the 8th-rank @UUID[Compendium.pf2e.spells-srd.Item.dN8QBNuTiaBHCKUe]{Baleful Polymorph} spell and all the following spells, which the coven can cast at any rank up to 5th: @UUID[Compendium.pf2e.spells-srd.Item.41TZEjhO6D1nWw2X]{Augury}, @UUID[Compendium.pf2e.spells-srd.Item.vLA0q0WOK2YPuJs6]{Charm}, @UUID[Compendium.pf2e.spells-srd.Item.HXhWYJviWalN5tQ2]{Clairaudience}, @UUID[Compendium.pf2e.spells-srd.Item.zvKWclOZ7A53DObE]{Clairvoyance}, @UUID[Compendium.pf2e.spells-srd.Item.yM3KTTSAIHhyuP14]{Dream Message}, @UUID[Compendium.pf2e.spells-srd.Item.i35dpZFI7jZcRoBo]{Illusory Disguise}, @UUID[Compendium.pf2e.spells-srd.Item.Ucf8eynbZMfUucjE]{Illusory Scene}, @UUID[Compendium.pf2e.spells-srd.Item.Ek5XI0aEdZhBgm21]{Prying Eye}, and @UUID[Compendium.pf2e.spells-srd.Item.FM3SmEW8N1FCRjqt]{Talking Corpse}. Individual creatures with the coven ability also grant additional spells to any coven they join. A coven can also cast the @UUID[Compendium.pf2e.spells-srd.Item.XkDCzMIyc0YOjw05]{Control Weather} ritual, with a DC of 23 instead of the standard DC.
If a coven member leaving the coven or the death of a coven member brings the coven below three members, the remaining members keep their elite adjustments for 24 hours, but without enough members to contribute the necessary actions, they can't cast coven spells.
`,Darkvision:"
A monster with darkvision can see perfectly well in areas of darkness and dim light, though such vision is in black and white only. Some forms of magical darkness, such as a 4th-rank @UUID[Compendium.pf2e.spells-srd.Item.4GE2ZdODgIQtg51c]{Darkness} spell, block normal darkvision. A monster with @UUID[Compendium.pf2e.bestiary-ability-glossary-srd.Item.4Ho2xMPEC05aSxzr]{Greater Darkvision}, however, can see through even these forms of magical darkness.
",Disease:"
When a creature is exposed to a monster's disease, it attempts a Fortitude save or succumbs to the disease. The level of a disease is the level of the monster inflicting the disease. The disease follows the rules for afflictions.
",Engulf:`
The monster Strides up to double its Speed and can move through the spaces of any creatures in its path. Any creature of the monster's size or smaller whose space the monster moves through can attempt a Reflex save with the listed DC to avoid being engulfed. A creature unable to act automatically critically fails this save. If a creature succeeds at its save, it can choose to be either pushed aside (out of the monster's path) or pushed in front of the monster to the end of the monster's movement. The monster can attempt to Engulf the same creature only once in a single use of Engulf. The monster can contain as many creatures as can fit in its space.
A creature that fails its save is pulled into the monster's body. It is @UUID[Compendium.pf2e.conditionitems.Item.kWc1fhmv9LBiTuei]{Grabbed}, is @UUID[Compendium.pf2e.conditionitems.Item.xYTAsEpcJE1Ccni3]{Slowed 1}, and has to hold its breath or start suffocating. The creature takes the listed amount of damage when first engulfed and at the end of each of its turns while it's engulfed. An engulfed creature can get free by @UUID[Compendium.pf2e.actionspf2e.Item.SkZAQRkLLkmBQNB9]{Escaping} against the listed escape DC. An engulfed creature can attack the monster engulfing it, but only with unarmed attacks or with weapons of light Bulk or less. The engulfing creature is @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} against the attack. If the monster takes piercing or slashing damage equaling or exceeding the listed Rupture value from a single attack or spell, the engulfed creature cuts itself free. A creature that gets free by either method can immediately breathe and exits the swallowing monster's space.
If the monster dies, all creatures it has engulfed are automatically released as the monster's form loses cohesion.
`,FastHealing:"
A monster with this ability regains the given number of Hit Points each round at the beginning of its turn.
",Ferocity:`
Trigger The monster is reduced to 0 HP.
Effect The monster avoids being knocked out and remains at 1 HP, but its @UUID[Compendium.pf2e.conditionitems.Item.Yl48xTdMh3aeQYL2]{Wounded} value increases by 1. When it is Wounded 3, it can no longer use this ability
`,FormUp:"
The troop chooses one of the squares it currently occupies and redistributes its squares to any configuration in which all squares are contiguous and within 15 feet of the chosen square. The troop can't share its space with other creatures.
",FrightfulPresence:`
A creature that first enters the area must attempt a Will save.
Regardless of the result of the saving throw, the creature is temporarily immune to this monster's Frightful Presence for 1 minute.
Critical Success The creature is unaffected by the presence.
Success The creature is @UUID[Compendium.pf2e.conditionitems.Item.TBSHQspnbcqxsmjL]{Frightened 1}.
Failure The creature is @UUID[Compendium.pf2e.conditionitems.Item.TBSHQspnbcqxsmjL]{Frightened 2}.
Critical Failure The creature is @UUID[Compendium.pf2e.conditionitems.Item.TBSHQspnbcqxsmjL]{Frightened 4}.
`,Grab:"
Requirements The monster's last action was a successful Strike that lists Grab in its damage entry, or the monster has a creature @UUID[Compendium.pf2e.conditionitems.Item.kWc1fhmv9LBiTuei]{Grabbed} or @UUID[Compendium.pf2e.conditionitems.Item.VcDeM8A5oI6VqhbM]{Restrained}
Effect If used after a Strike, the monster attempts to @UUID[Compendium.pf2e.actionspf2e.Item.PMbdMWc2QroouFGD]{Grapple} the creature using the body part it attacked with. This attempt neither applies nor counts toward the creature's multiple attack penalty.
The monster can instead use Grab and choose one creature it's grabbing or restraining with an appendage that has Grab to automatically extend that condition to the end of the monster's next turn.
",GreaterConstrict:"
The monster deals the listed amount of damage to any number of creatures @UUID[Compendium.pf2e.conditionitems.Item.kWc1fhmv9LBiTuei]{Grabbed} or @UUID[Compendium.pf2e.conditionitems.Item.VcDeM8A5oI6VqhbM]{Restrained} by it. Each of those creatures can attempt a basic Fortitude save with the listed DC. A creature that fails this save falls @UUID[Compendium.pf2e.conditionitems.Item.fBnFDH2MTzgFijKf]{Unconscious}, and a creature that succeeds is then temporarily immune to falling unconscious from Greater Constrict for 1 minute.
",GreaterDarkvision:"
A creature with greater darkvision can see perfectly well in areas of darkness and dim light, though such vision is in black and white only. Some forms of magical darkness, such as a 4th-rank @UUID[Compendium.pf2e.spells-srd.Item.4GE2ZdODgIQtg51c]{Darkness} spell, block normal @UUID[Compendium.pf2e.bestiary-ability-glossary-srd.Item.qCCLZhnp2HhP3Ex6]{Darkvision}. A creature with greater darkvision, however, can see through even these forms of magical darkness.
",ImprovedGrab:"
The monster can use @UUID[Compendium.pf2e.bestiary-ability-glossary-srd.Item.Tkd8sH4pwFIPzqTr]{Grab} as a free action triggered by a hit with its initial attack. A monster with Improved Grab still needs to spend an action to extend the duration for creatures it already has @UUID[Compendium.pf2e.conditionitems.Item.kWc1fhmv9LBiTuei]{Grabbed}.
",ImprovedKnockdown:"
The monster can use @UUID[Compendium.pf2e.bestiary-ability-glossary-srd.Item.BCLvAx4Pz4MLa2pu]{Knockdown} as a free action triggered by a hit with its initial attack.
",ImprovedPush:"
The monster can use @UUID[Compendium.pf2e.bestiary-ability-glossary-srd.Item.t6cx9FOODmeZQNYl]{Push} as a free action triggered by a hit with its initial attack.
",Knockdown:"
Requirements The monster's last action was a successful Strike that lists Knockdown in its damage entry
Effect The monster attempts to @UUID[Compendium.pf2e.actionspf2e.Item.ge56Lu1xXVFYUnLP]{Trip} the creature. This attempt neither applies nor counts toward the monster's multiple attack penalty.
",Lifesense:"
Lifesense allows a monster to sense the vital essence of living and undead creatures within the listed range. The sense can distinguish between the vitality energy animating living creatures and the void energy animating undead creatures, much as sight distinguishes colors.
",LightBlindness:"
When first exposed to bright light, the monster is @UUID[Compendium.pf2e.conditionitems.Item.XgEqL1kFApUbl5Z2]{Blinded} until the end of its next turn. After this exposure, light doesn't blind the monster again until after it spends 1 hour in darkness. However, as long as the monster is in an area of bright light, it's @UUID[Compendium.pf2e.conditionitems.Item.TkIyaNPgTZFBCCuh]{Dazzled}.
",LowLightVision:"
The monster can see in dim light as though it were bright light, so it ignores the @UUID[Compendium.pf2e.conditionitems.Item.DmAIPqOBomZ7H95W]{Concealed} condition due to dim light.
",NegativeHealing:"
A creature with void healing draws health from void energy rather than vitality energy. It is damaged by vitality damage and is not healed by vitality healing effects. It does not take void damage, and it is healed by void effects that heal undead.
",Poison:"
When a creature is exposed to a monster's poison, it attempts a Fortitude save to avoid becoming poisoned. The level of a poison is the level of the monster inflicting the poison. The poison follows the rules for afflictions.
",PowerAttack:`
Frequency once per round
Effect The monster makes a melee Strike. This counts as two attacks when calculating the monster's multiple attack penalty. If this Strike hits, the monster deals an extra die of weapon damage.
`,Push:"
Requirements The monster's last action was a successful Strike that lists Push in its damage entry
Effect The monster attempts to @UUID[Compendium.pf2e.actionspf2e.Item.7blmbDrQFNfdT731]{Shove} the creature. This attempt neither applies nor counts toward the monster's multiple attack penalty. If Push lists a distance, change the distance the creature is pushed on a success to that distance.
",Regeneration:"
This monster regains the listed number of Hit Points each round at the beginning of its turn. Its @UUID[Compendium.pf2e.conditionitems.Item.yZRUzMqrMmfLu0V1]{Dying} condition never increases beyond Dying 3 as long as its regeneration is active. However, if it takes damage of a type listed in the regeneration entry, its regeneration deactivates until the end of its next turn. Deactivate the regeneration before applying any damage of a listed type, since that damage might kill the monster by bringing it to Dying 4.
",Rend:`
A Rend entry lists a Strike the monster has.
Requirements The monster hit the same enemy with two consecutive Strikes of the listed type in the same round.
Effect The monster automatically deals that Strike's damage again to the enemy.
`,RetributiveStrike:`
Trigger An enemy damages the monster's ally, and both are within 15 feet of the monster.
Effect The ally gains resistance to all damage against the triggering damage equal to 2 + the monster's level. If the foe is within reach, the monster makes a melee Strike against it.
`,Scent:`
Scent involves sensing creatures or objects by smell, and is usually a vague sense. The range is listed in the ability, and it functions only if the creature or object being detected emits an aroma (for instance, incorporeal creatures usually do not exude an aroma).
If a creature emits a heavy aroma or is upwind, the GM can double or even triple the range of scent abilities used to detect that creature, and the GM can reduce the range if a creature is downwind.
`,ShieldBlock:`
Trigger The monster has its shield raised and takes damage from a physical attack.
Effect The monster snaps its shield into place to deflect a blow. The shield prevents the monster from taking an amount of damage up to the shield's Hardness. The monster and the shield each take any remaining damage, possibly breaking or destroying the shield.
`,SneakAttack:"
When the monster Strikes a creature that has the @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} condition with an agile or finesse melee weapon, an agile or finesse unarmed attack, or a ranged weapon attack, it also deals the listed precision damage. For a ranged attack with a thrown weapon, that weapon must also be an agile or finesse weapon.
",SwallowWhole:`
The monster attempts to swallow a creature of the listed size or smaller that it has grabbed in its jaws or mouth. If a swallowed creature is of the maximum size listed, the monster can't use Swallow Whole again. If the creature is smaller than the maximum, the monster can usually swallow more creatures; the GM determines the maximum. The monster attempts an @Check[type:athletics|defense:reflex] check opposed by the grabbed creature's Reflex DC. If it succeeds, it swallows the creature. The monster's mouth or jaws no longer grab a creature it has swallowed, so the monster is free to use them to Strike or Grab once again. The monster can't attack creatures it has swallowed.
A swallowed creature is @UUID[Compendium.pf2e.conditionitems.Item.kWc1fhmv9LBiTuei]{Grabbed}, is @UUID[Compendium.pf2e.conditionitems.Item.xYTAsEpcJE1Ccni3]{Slowed 1}, and has to hold its breath or start suffocating. The swallowed creature takes the listed amount of damage when first swallowed and at the end of each of its turns while it's swallowed. If the victim @UUID[Compendium.pf2e.actionspf2e.Item.SkZAQRkLLkmBQNB9]{Escapes} this ability's grabbed condition, it exits through the monster's mouth. This frees any other creature grabbed in the monster's mouth or jaws. A swallowed creature can attack the monster that has swallowed it, but only with unarmed attacks or with weapons of light Bulk or less. The swallowing creature is @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} against the attack. If the monster takes piercing or slashing damage equaling or exceeding the listed Rupture value from a single attack or spell, the swallowed creature cuts itself free. A creature that gets free by either Escaping or cutting itself free can immediately breathe and exits the swallowing monster's space.
If the monster dies, a swallowed creature can be freed by creatures adjacent to the corpse if they spend a combined total of 3 actions cutting the monster open with a weapon or unarmed attack that deals piercing or slashing damage.
`,SwarmMind:"
This monster doesn't have a single mind (typically because it's a swarm of smaller creatures), and is immune to mental effects that target only a specific number of creatures. It is still subject to mental effects that affect all creatures in an area.
",Telepathy:"
A monster with telepathy can communicate mentally with any creatures within the listed radius, as long as they share a language. This doesn't give any special access to their thoughts, and communicates no more information than normal speech would.
",Thoughtsense:"
Thoughtsense allows a monster to sense all non-mindless creatures at the listed range.
",ThrowRock:"
The monster picks up a rock within reach or retrieves a stowed rock and throws it, making a ranged Strike.
",Trample:"
The monster Strides up to double its Speed and can move through the spaces of creatures of the listed size, Trampling each creature whose space it enters. The monster can attempt to Trample the same creature only once in a single use of Trample. The monster deals the damage of the listed Strike, but trampled creatures can attempt a basic Reflex save at the listed DC (no damage on a critical success, half damage on a success, double damage on a critical failure).
",Tremorsense:"
Tremorsense allows a monster to feel the vibrations through a solid surface caused by movement. It is an imprecise sense with a limited range (listed in the ability). Tremorsense functions only if the monster is on the same surface as the subject, and only if the subject is moving along (or burrowing through) the surface.
",TroopDefenses:`
Troops are composed of many individuals, and over the course of enough attacks and downed comrades, troops shrink in size. Most troops start with 16 squares (4 by 4), and their Hit Points have two listed thresholds, typically the first is at 2/3 their maximum Hit Points and the second is at 1/3 their maximum Hit Points. Once the troop drops below the first threshold, it loses 4 squares, leaving 12 squares remaining, and the first threshold becomes the troop's new maximum Hit Points. Once the troop falls below the second threshold, it loses another 4 squares, leaving 8 squares remaining, and the second threshold becomes the troop's new maximum Hit Points. In order to restore its size and maximum Hit Points, a troop needs to spend downtime to use long-term treatment on casualties or recruit new members to replace the fallen. At 0 Hit Points, the troop is reduced down to 4 squares, which is too few to sustain the troop, so it disperses entirely, with the few remaining members surrendering, fleeing, or easily dispatched, depending on their nature.
A damaging single-target effect, such as a Strike, can't force a troop to pass through more than one threshold at once. For instance, if a troop had 60 Hit Points, with thresholds at 40 and 20, a Strike for 50 damage would leave the troop at 21 Hit Points, just above the second threshold. A damaging area effect or multi-target effect can cross multiple thresholds at once and could potentially destroy the entire troop in one shot.
Non-damaging effects with an area or that target all creatures in a certain proximity affect a troop normally if they affect the entire area occupied by the troop. If an effect has a smaller area or numbers of targets, it typically has no effect on the troop. However, if the effect can target at least four creatures or cover at least four squares in the troop, and if it would prevent its targets from acting, cause them to flee, or otherwise make them unable to function as part of the troop for a round or more, the troop loses loses a number of Hit Points equal to the amount required to bring it to the next threshold, removing 4 squares. If an effect would both deal damage and automatically cross a threshold due to incapacitating some of the creatures in the troop, apply the damage first. If the damage wasn't enough to cross a threshold on its own, then reduce the Hit Points to cross the threshold for the incapacitating effect.
`,Wavesense:"
This sense allows a monster to feel vibrations caused by movement through a liquid. It's an imprecise sense with a limited range (listed in the ability). Wavesense functions only if monster and the subject are in the same body of liquid, and only if the subject is moving through the liquid.
"}},ActionsList:{ActionName:"Name",Cost:"Cost",Traits:"Traits",Type:"Type"},AddAction:"Add Action",AddArmor:"Armor",AddConsumable:"Consumable",AddEquipment:"Equipment",AddItem:"Add Item",AddPassive:"Add Passive",AddSkill:"Add Skill",AddTrait:"Add Trait",AddTreasure:"Treasure",AddWeapon:"Weapon",Adjustment:{EliteLabel:"Elite",EliteNameFormat:"Elite {name}",NormalLabel:"Normal",WeakLabel:"Weak",WeakNameFormat:"Weak {name}"},ArmorExtraInfoLabelPlaceholder:"AC details...",AttackType:{Melee:"NPC Melee Attack",Ranged:"NPC Ranged Attack",Weapon:"Compendium Weapon"},Attacks:"Attacks",Creature:"Creature",Dead:"Dead",Edit:"Edit",EditImmunities:"Edit Immunities",EditLanguages:"Edit Languages",EditResistances:"Edit Resistances",EditSenses:"Edit Senses",EditSkills:"Edit Skills",EditSpeed:"Edit Speed",EditTraits:"Edit Traits",EditWeaknesses:"Edit Weaknesses",EffectsTab:"Effects",HPExtraInfoLabelPlaceholder:"HP details...",Inventory:{Header:{NameLabel:"Name",QuantityLabel:"Quantity",ValueLabel:"Value"}},InventoryTab:"Inventory",MainTab:"Main",NotesTab:"Notes",PassivesLabel:"Passives",PrivateNotes:"Private Notes",PublicNotes:"Description",Remove:"Remove",SavesExtraInfoLabelPlaceholder:"Bonus to all saves...",SendToChat:"Send to chat",SensesLabel:"Senses",SkillRollFlavor:"{skillName} Skill Check ({rank})",SpeedExtraInfoLabelPlaceholder:"Speed details...",SpeedLabel:"Speed",Spells:{AttackLabel:"Attack",DCLabel:"DC",PreparedLabel:"Prepared",PreparedShortLabel:"Prep."},SpellsTab:"Spells"},NPCAttackMelee:"Melee",NPCAttackRanged:"Ranged",NPCNotesLabel:"Notes/Conditions",NPCNotesTitle:"Write any notes for this NPC here.",NPCWeaponAddDamage:"Add Damage Partial",NPCWeaponAttackEffect:"Additional Attack Effects",NPCWeaponAttackLabel:"Attack Modifier",NPCWeaponDamageLabel:"Damage Formula",Nationality:"Nationality",NewLabel:"New",NewLoreSkill:"New skill",NewPlaceholders:{Action:"New Action",Ancestry:"New Ancestry",Armor:"New Armor",Background:"New Background",Backpack:"New Container",Condition:"New Condition",Consumable:"New Consumable",Equipment:"New Equipment",Feat:"New Feat",Kit:"New Kit",Lore:"New Lore",Melee:"New Attack",Skill:"New Skill",Spell:"New Spell",SpellcastingEntry:"New Spellcasting Entry",Treasure:"New Treasure",Weapon:"New Weapon"},NoAmmoLabel:"No Ammo",NoneOption:"None",OK:"OK",OpenActionBrowserTitle:"Open Action Browser",OpenInventoryBrowser:"Open Inventory Browser",OpenItemTitle:"Toggle Container Contents",OpenSpellBrowserTitle:"Open Spell Browser",OrdinalNumber:"{value}{suffix}",OrdinalSuffixes:{few:"rd",many:"th",one:"st",other:"th",two:"nd",zero:"th"},OrphanedSpellsHeader:"Orphaned Spells (move to spellcasting entry above)",OverridesTitle:"Overrides",Pathfinder:"Pathfinder",PFS:{CharacterNumber:"Character #",CurrentFaction:"Current Faction",Factions:{EA:"Envoy's Alliance",GA:"Grand Archive",HH:"Horizon Hunters",RO:"Radiant Oath",VS:"Vigilant Seal",VW:"Verdant Wheel"},LevelBump:"Level Bump",OrganizedPlayNumber:"Organized Play #",Reputation:"Reputation",School:{None:"Field-Commissioned Agent",Scrolls:"Scrolls",Spells:"Spells",Swords:"Swords"}},PenaltyLabel:{ability:"Attribute Penalty",circumstance:"Circumstance Penalty",item:"Item Penalty",proficiency:"Proficiency Penalty",status:"Status Penalty",untyped:"Untyped Penalty"},PerceptionCheck:"Perception Check",PerceptionHeader:"Perception",PerceptionLabel:"Perception",PotencyRuneLabel:"Potency Rune",PreciousMaterialAbysium:"Abysium",PreciousMaterialAbysiumDescription:"A blue-green metal with an eerie green luminescence, abysium radiates power that's inimical to life. Careless exposure to the material can lead to long-term damage to the immune system; as such, mining abysium is hazardous, as large quantities of the metal in an area cause all nearby creatures to become sick. A creature carrying an abysium object is sickened 1 for a standard-grade object of light Bulk, sickened 2 for a standard-grade object of 1 Bulk or more or a high-grade object of light Bulk, or sickened 3 for a high-grade object of 1 Bulk or more. This and all other sickening effects of abysium are poison effects. Crafters can use 1 abysium chunk to create up to 6 doses of poisonous abysium powder. Unscrupulous smiths have harnessed abysium's toxic properties to create noxious weapons and deadly substances. All objects crafted from abysium shed dim light in a 10-foot radius.",PreciousMaterialAdamantine:"Adamantine",PreciousMaterialAdamantineDescription:"Mined from rocks that fell from the heavens, adamantine is one of the hardest metals known. It has a shiny, black appearance, and it is prized for its amazing resiliency and ability to hold an incredibly sharp edge.",PreciousMaterialColdIron:"Cold Iron",PreciousMaterialColdIronDescription:"Weapons made from cold iron are deadly to demons and fey alike. Cold iron looks like normal iron but is mined from particularly pure sources and shaped with little or no heat. This process is extremely difficult, especially for high-grade cold iron items.",PreciousMaterialDawnsilver:"Dawnsilver",PreciousMaterialDawnsilverDescription:"Dawnsilver is renowned for its lightness, durability, and effectiveness against a range of creatures including devils and lycanthropes. It has the same sheen as silver but a slightly lighter hue. Dawnsilver weapons and armor are treated as if they were silver for the purpose of damaging creatures with weakness to silver. A metal item made of dawnsilver is lighter than one made of iron or steel: the item's Bulk is reduced by 1 (reduced to light Bulk if its normal Bulk is 1, with no effect on an item that normally has light Bulk). The Price of an item made of this material is based on the item's normal Bulk, not its reduced Bulk for being made of dawnsilver, but reduce the Bulk before making any further Bulk adjustments for the size of the item.",PreciousMaterialDjezet:"Djezet",PreciousMaterialDjezetDescription:'This rust red metal is liquid at room temperature, making it challenging for all but the most skilled metallurgists to craft with and earning it the name "quickiron" in some places. Djezet is also extremely reactive to magic, even in its solid, workable alloyed form. It glows when targeted by magic, and objects crafted with djezet alloys glow with scarlet striations, which lead some smiths to nickname it "tiger iron." When targeted by spells, objects crafted from djezet alloys exhibit these glowing red markings that last for 1 round or the duration of the spell, whichever is longer. A djezet mass contains enough djezet to refine into up to two djezet doses.',PreciousMaterialDragonhide:"Dragonhide",PreciousMaterialDragonhideDescription:"The hide and scales of a dragon can be used to Craft any item normally made of ordinary leather or hide. Dragonhide varies in color from blue to glittering gold, depending on the dragon it came from. Due to the scales' resiliency, it can also be used to Craft armor usually made out of metal plates (such as a breastplate, half plate, and full plate), allowing such armor to be made without metal. Dragonhide objects are immune to one damage type, depending on the type of dragon.",PreciousMaterialDuskwood:"Duskwood",PreciousMaterialDuskwoodDescription:"Duskwood is a very lightweight wood found primarily in old- growth forests in south-central Avistan; it is dark as ebony but has a slight purple tint. A duskwood item's Bulk is reduced by 1 (or to light Bulk if its normal Bulk is 1, with no effect on an item that normally has light Bulk). The Price of an item made of duskwood is based on the item's normal Bulk, not its reduced Bulk for being made of duskwood, but reduce the Bulk before making any further Bulk adjustments for the size of the item.",PreciousMaterialGradeLabel:"Precious Material Grade",PreciousMaterialGrisantianPelt:"Grisantian Pelt",PreciousMaterialGrisantianPeltDescription:"This supernaturally tough animal skin is gold and shines in sunlight. It can be used to make any item usually made of cloth, leather, or hide. This material is immune to fire, and its Hardness is doubled against piercing or slashing damage. Up to 4 Bulk of grisantian pelt can be harvested from a single creature (this is usually more than enough for 4 suits of standard grade armor or 2 suit of high-grade armor).",PreciousMaterialHighGrade:"High-Grade",PreciousMaterialInubrix:"Inubrix",PreciousMaterialInubrixDescription:"This pale, malleable metal's unusual molecular structure allows it to partially pass through iron and steel without touching them. While this property is useful for making weapons that bypass metal armor, inubrix is barely sturdier than lead. Even in an alloyed state, this skymetal is so fragile that it's difficult to use in crafting reliable shields and less than ideal for crafting armor.",PreciousMaterialLabel:"Precious Material",PreciousMaterialLowGrade:"Low-Grade",PreciousMaterialKeepStone:"Keep Stone",PreciousMaterialKeepStoneDescription:"The crowning achievement of Highhelm's millennia of metallurgical advancements and engineering is the beautiful alloy called keep stone. Despite its name, no stone is used in the production of keep stone. Through the use of a highly guarded process that smelts together adamantine and lead, Highhelm's greatest crafters were able to develop a material with an appearance that more closely resembles marble than metal. Keep stone is only slightly weaker than adamantine alone, but with the incredible ability to disrupt magic. Any spell or magical effect targeting raw keep stone must succeed at a DC 5 flat check or the effect is lost.",PreciousMaterialNoqual:"Noqual",PreciousMaterialNoqualDescription:"Light and strong, noqual also demonstrates a powerful resistance to magic. A side effect of this resistance is that making magical weapons out of noqual requires complex and expensive alchemical treatments. Kevoth-Kul, the Black Sovereign of Numeria, has developed an alloy of noqual and cold iron known as sovereign steel to help mitigate this property. The metal's crystalline appearance might suggest that it's fragile, but the pale-green material can be worked similarly to iron. Objects made of noqual have a +4 circumstance bonus on saves against magic that the item attempts and grant their bonus to saves the owner makes specifically to protect the item from magic (such as against the rusting grasp spell).",PreciousMaterialOrichalcum:"Orichalcum",PreciousMaterialOrichalcumDescription:"The most rare and valuable skymetal, orichalcum is coveted for its incredible time-related magical properties. This dull, coppery metal isn't as physically sturdy as adamantine, but orichalcum's time-bending properties protect it, granting it greater Hardness and Hit Points. If an orichalcum item takes damage but isn't destroyed, it repairs itself completely 24 hours later.",PreciousMaterialPeachwood:"Peachwood",PreciousMaterialPeachwoodDescription:"Peachwood weapons have a particularly auburn tinge to them when under direct sunlight. Peachwood is treated as duskwood for any undead creatures' resistances or weaknesses related to duskwood (allowing a peachwood weapon to bypass a jiang-shi's resistance, for example). In addition, peachwood weapons bypass a small portion of the resistances of any undead creature. Strikes with a peachwood weapon treat an undead's resistances against physical damage as 2 lower for standard-grade peachwood, and 4 lower for high-grade.",PreciousMaterialSiccatite:"Siccatite",PreciousMaterialSiccatiteDescription:"In its raw state, this silvery ore is either scalding hot or freezing cold. Metallurgists disagree over whether siccatite is two related substances or one substance that determines its temperature output via some unknown process. Whatever the reason, the extreme temperature of the material means it must be handled carefully. Hot siccatite can easily ignite flammables such as paper and dry brush, and cold siccatite left in moist areas quickly surrounds itself with a thick layer of ice. A creature that comes into physical contact with a significant amount of siccatite takes 1 energy Damage for each round of continued contact (either fire or cold damage, for hot and cold siccatite respectively).",PreciousMaterialSilver:"Silver",PreciousMaterialSilverDescription:"Silver weapons are a bane to creatures ranging from devils to werewolves. Silver items are less durable than steel items, and low-grade silver items are usually merely silver-plated.",PreciousMaterialSisterstone:"Sisterstone",PreciousMaterialSisterstoneDescription:"Sisterstone is a term used for two closely related ores infused by the spiritual runoff in the Field of Maidens, dusk sisterstone and scarlet sisterstone. They have the same physical properties except for color-dusk sisterstone is a pale orange while scarlet sisterstone is orange-red. When near an object made of the other type of sisterstone, they both begin exuding spiritual energy that repels undead.",PreciousMaterialSisterstoneDusk:"Sisterstone (Dusk)",PreciousMaterialSisterstoneScarlet:"Sisterstone (Scarlet)",PreciousMaterialSovereignSteel:"Sovereign Steel",PreciousMaterialSovereignSteelDescription:"Created by Black Sovereign Kevoth-Kul, this unique alloy of cold iron and the skymetal noqual can provide protection from magical assault. The process of cold-forging the two materials together is quite complicated and precise. Characters in search of sovereign steel weapons and armor will almost assuredly have to travel to Starfall to procure gear made from this rare alloy. While some believe it possible to craft shields of sovereign steel as well, in one of his fits, Kevoth-Kul yelled that he had no use for them and banned anyone from making such a thing. So far, his smiths have been too afraid to confirm whether or not it was a joke. All sovereign steel items (including weapon and armor below) have a +4 circumstance bonus on saves against magic that the item makes, and grant their bonus to saves the owner makes specifically to protect the item from magic (such as against the rusting grasp spell).",PreciousMaterialStandardGrade:"Standard-Grade",PreciousMaterialWarpglass:"Warpglass",PreciousMaterialWarpglassDescription:"This bizarre substance is fashioned from the raw, chaotic quintessence of the Maelstrom. It can be fashioned into weapons and items, but is too unstable to make into useful armor or shields. Raw warpglass is an opalescent glassy material with surprising strength. When worked, it changes its appearance-though not its properties-to appear as random striations of other metals and types of stone.",PreparationTypeInnate:"Innate",PreparationTypeItems:"Items Only",PreparationTypePrepared:"Prepared",PreparationTypeSpontaneous:"Spontaneous",Prerequisite1:"Prerequisite 1",Prerequisite2:"Prerequisite 2",Prerequisite3:"Prerequisite 3",Prerequisite4:"Prerequisite 4",Prerequisite5:"Prerequisite 5",PriceLabel:"Price",ProficiencyLabel:"Proficiency",ProficiencyLevel0:"Untrained",ProficiencyLevel1:"Trained",ProficiencyLevel2:"Expert",ProficiencyLevel3:"Master",ProficiencyLevel4:"Legendary",ProficiencyRankLabel:"Prof",ProgressBar:{LoadingComplete:"Loading complete",LoadingPack:"Loading {pack}"},PropertyRuneLabel1:"Property Rune (1st)",PropertyRuneLabel2:"Property Rune (2nd)",PropertyRuneLabel3:"Property Rune (3rd)",PropertyRuneLabel4:"Property Rune (4th)",Publication:{Authors:"Author(s)",Label:"Publication",License:{Label:"License",OGL:"OGL",ORC:"ORC"},Remaster:"Remaster?",Title:"Title"},QuantityLabel:"Quantity",QuantityShortLabel:"Qty.",RangePenalty:"Range Penalty",Rarity:"Rarity",Reach:"Reach (feet)",RecallKnowledge:{Breakdown:"Attempts",BreakdownTitle:"Identify Creature Attempts",FifthAttempt:"5th DC",FirstAttempt:"1st DC",FourthAttempt:"4th DC",Help:"You can attempt repeated Recall Knowledge actions to recall more information about a creature. These checks increase in difficulty as shown in the chart below. However, if you fail, or if no DC is listed, you can not attempt further Recall Knowledge checks against this creature.",Label:"Recall Knowledge",LoreEasy:"Applicable Lore (Easy)",LoreVeryEasy:"Applicable Lore (Very Easy)",SecondAttempt:"2nd DC",SixthAttempt:"6th DC",Skill:"Skill",ThirdAttempt:"3rd DC"},Recovery:{critFailure:"Increase your dying value by 2.",critSuccess:"Reduce your dying value by 2.",failure:"Increase your dying value by 1.",rollingDescription:"DC {dc} (Dying {dying})",success:"Reduce your dying value by 1."},RemoveCoinsByValueLabel:"Remove value, not specific type",RemoveCoinsTitle:"Remove Coins",RemoveCombatProficiency:{Message:"Remove {proficiency} proficiency?",Title:"Remove Combat Proficiency"},RemoveModifierTitle:"Remove Modifier",RemoveSpellcastingEntryTitle:"Remove Spellcasting Entry",RepairItemTitle:"Attempt to Repair Item",Repost:"Post prompt to chat",RerollMenu:{ErrorCantDelete:"You are unable to delete the original roll.",ErrorNoActor:"No actor is associated to the roll",HeroPoint:"Reroll using a Hero Point",KeepHigher:"Reroll and keep the higher result",KeepNew:"Reroll and keep the new result",KeepLower:"Reroll and keep the lower result",MessageHeroPoint:"Rerolled using a Hero Point",MessageKeep:{higher:"Rerolled and kept the higher result",new:"Rerolled and kept the new result",lower:"Rerolled and kept the lower result"},WarnNoHeroPoint:"{name} has no Hero Points"},ResistancesLabel:"Resistances",ResolvePointsShortLabel:"Resolve",RestoreSpellTitle:"Restore Spell",RevertDamage:{ButtonTooltip:"Undo",DamageMessage:"Damage applied to {actor} was reverted.",HealingMessage:"Healing applied to {actor} was reverted."},Roll:{Add:"Add",CriticalHit:"Critical Hit",Dialog:{Check:{Substitution:"Substitution",Utilize:"Utilize?"},Damage:{BaseDamage:"Base Damage",Dice:"{dice} Dice",DiceHeader:"Dice",DieSizeUpgrade:"Upgrade Die Size",ExtraDice:"Extra {dice}",Label:"Label",None:"None",Override:"Override {value}",Splash:"{damageType} Splash",TitleCritical:"Critical Damage Roll",Title:"Damage Roll"},ShowDefault:"Always Show Dialog",ShowDefaultHint:"If enabled, this dialog is always shown unless you hold Shift. If disabled, you can open this dialog by holding Shift."},Fortune:"Fortune",FortuneTitle:"{title} Fortune",KeepHigher:"Keep Higher",KeepLower:"Keep Lower",Misfortune:"Misfortune",MisfortuneTitle:"{title} Misfortune",Modifier:"Modifier",None:"None",Normal:"Normal",Roll:"Roll",Type:"Type",UntypedPenalty:"Untyped (penalty)"},RollBonusPlaceholder:"e.g. +3 or +1d4",RollModeLabel:"Roll Mode",RollTable:{Plural:"Rollable Tables"},SETTINGS:{Automation:{ActorsDeadAtZero:{Both:"Yes",Hint:"Upon reaching zero hit points, actors are marked as dead. For PCs, this only applies to damage that would immediately kill them.",NPCsOnly:"NPCS only",Name:"Actors Dead at 0 HP",Neither:"No"},Encumbrance:{Hint:"Automatically apply the Encumbered condition to creatures carrying more than their respective limits.",Name:"Encumbrance"},EffectExpiration:{Hint:"Effects automatically disable attached rule elements when the duration expires.",Name:"Effects Auto-Expire"},FlankingDetection:{Hint:"Flanking arrangements and abilities that predicate on it are managed by the system.",Name:"Flanking Detection"},Hint:"Decide how much and what kinds of automation should apply to your game world.",IWR:{Hint:"When applying damage to an actor, adjust its value according to the actor's immunities, weaknesses, and resistances.",Name:"Immunities, Weaknesses, & Resistances"},Label:"Manage Automation",LootableNPCs:{Hint:"Upon their demise, NPCs become lootable by players.",Name:"Lootable NPCs"},Name:"Automation",RemoveExpiredEffects:{Hint:"Expired effects are automatically removed from actors (requires a GM to be logged in).",Name:"Remove Expired Effects"},RulesBasedVision:{Hint:"Apply vision mechanics that are a best-effort attempt to capture Pathfinder Second Edition rules. Enabling this setting will remove the ability to configure Unrestricted Global Vision as well as Token Sight radii.",ManagedBy:"Managed by rules-based vision.",Name:"Rules-Based Vision",ViewWorldSetting:"View World Setting"}},CampaignFeats:{Hint:"Adds a section to all player sheets for campaign specific feats.",Name:"Campaign Feats"},CampaignType:{Hint:"Extended campaign rule type for parties",Name:"Campaign Type",Choices:{none:"None",kingmaker:"Kingmaker"}},CompendiumBrowserPacks:{Hint:"Settings to exclude packs from loading",Name:"Compendium Browser Packs"},CompendiumBrowserSources:{DeleteAllInfo:"All compendium documents will become browseable, including those with empty sources.",DeleteAllQuestion:"Are you sure you want to reset all settings for included sources?",DeleteAllTitle:"Reset Settings",Hint:"Settings to display only entries with specified sources in the compendium browser.",IgnoreAsGM:"Let GMs ignore filtering and see all entries.",Name:"Included Sources",ShowEmptySources:"Do not filter entries with empty sources.",ShowUnknownSources:"Do not filter entries with unknown sources.",SourcesListHeader:"Specified Sources"},CritRule:{Choices:{Doubledamage:"Double the damage",Doubledice:"Double the number of dice"},Hint:"Use a different rule for doubling damage on a critical hit",Name:"Critical Damage Rule"},DeathIcon:{Hint:"Set the overlay icon used to mark dead actors.",Name:"Death Icon"},EnabledDisabled:{Enabled:"Enabled",Default:"World Default ({worldDefault})",Disabled:"Disabled"},EnabledRulesUI:{Hint:"When enabled, players are able to see and utilize the rule elements panel on item sheets.",Name:"Player Rule Elements Access"},Homebrew:{BaseWeapons:{Hint:"The bottom level of Pathfinder 2e weapon taxonomy (e.g, Heavy Crossbow, Longsword)",Name:"Base Weapons"},ConfirmDelete:{Message:"Delete Homebrew element {element}?",Title:"Delete Homebrew Element?"},CreatureTraits:{Hint:"Traits that can be applied to any creature and some item types (e.g., Dragon, Gnome)",Name:"Creature Traits"},DamageTypes:{Add:"Add Damage Type",Hint:"Additional damage types for the system to recognize",Icon:"Icon (Font Awesome)",Name:"Custom Damage Types",Label:"Label"},EquipmentTraits:{Hint:"Traits applicable to equipment other than weapons",Name:"Equipment Traits"},FeatTraits:{Hint:"Traits that can be applied to feats (e.g., Lineage, Monk) and actions",Name:"Feat Traits"},Hint:"Add custom traits, languages, and other elements of a homebrew world.",Instructions:"These settings allow GMs to add traits, languages, and other elements to a homebrew world. To add such elements, simply type the desired terms in the appropriate fields, separated by commas or tab keystrokes. They will then appear in the appropriate places on actor and item sheets. To update a term, click it to make the desired changes.",Label:"Manage Homebrew Elements",Languages:{Hint:"Languages for characters to know or learn (e.g., Draconic, Gnomish)",Name:"Languages"},Name:"Homebrew Elements",ReservedTerm:'"{term}" is a reserved term.',SpellTraits:{Hint:"Traits that can be applied to any spell (e.g., Cursebound, Healing)",Name:"Spell Traits"},Tabs:{Damage:"Damage Types",Traits:"Traits and Categories"},WeaponCategories:{Hint:"The top level of Pathfinder 2e weapon taxonomy (e.g., Simple, Martial)",Name:"Weapon Categories"},WeaponGroups:{Hint:"The mid level of Pathfinder 2e weapon taxonomy (e.g, Crossbow, Sword)",Name:"Weapon Groups"},WeaponTraits:{Hint:"Traits applicable to weapons and NPC attacks",Name:"Weapon Traits"}},IdentifyMagicNotMatchingTraditionModifier:{Choices:{0:"0",2:"+2",5:"+5",10:"+10"},Hint:"Modifier to add to Identify Magic Skill DCs if the skill does not match the item's magic tradition",Name:"Identify Magic Skill Modifier"},Metagame:{Hint:"Limit what kinds of metagame information your players have access to.",Label:"Limit Metagame Information",Name:"Metagame Information",PartyVision:{Hint:"If enabled, all players will mutually share token vision, regardless of permissions or token selection.",Name:"Shared Party Vision"},SecretCondition:{Hint:"If enabled, only the GM will see the condition update and reminder messages that are generated for tokens not owned by a player.",Name:"Hide Condition Update Message"},SecretDamage:{Hint:"If enabled, only the GM will see the damage/healing taken messages that are generated by the damage chat cards for tokens not owned by a player.",Name:"Hide Damage-Taken Message"},ShowDC:{Hint:"If enabled, players will see DCs of checks made against NPCs and other non-player-owned sources.",Name:"Show DCs on Attacks and Saves"},ShowResults:{Hint:"If enabled, players will see the degree of success of checks made against NPCs and other non-player-owned sources.",Name:"Show Results on Attacks and Saves"},ShowPartyStats:{Hint:"If enabled, players will see stats for their fellow party members in the party actor sheet",Name:"Show Party-Member Stats"},TokenSetsNameVisibility:{Hint:"If enabled, then for any NPC token whose nameplate isn't visible to players, its name will also be hidden from them in the encounter tracker and chat messages.",Name:"Tokens Determine NPC Name Visibility"}},NathMode:{Hint:"Use better default token icons",Name:"Nath Mode"},ResetChanges:"Reset Changes",Settings:"Settings",Sidebar:{Changelog:"Changelog",Discord:"Discord",Remaster:"Remaster Changes",Wiki:"Wiki"},TOTMToggles:{Hint:"Include additional toggles on actor sheets to facilitate Theater of the Mind play. Such toggles will allow for enabling certain abilities without targeting in Foundry.",Name:"Theater of the Mind Toggles"},Tokens:{Autoscale:{Hint:"If enabled, tokens will be scaled to 1.0 or (if belonging to a small creature) 0.8",Name:"Scale Tokens According to Size"}},User:{EffectPanel:{Hint:"Show the Effects Panel when a token is selected.",Name:"Show Effects Panel"},MonochromeDarkvision:{Hint:"If rules-based vision is enabled, depict areas of darkness in monochrome for tokens with darkvision. Note that some creatures, such as fetchlings, possess full-color darkvision and will not be affected.",Name:"Monochrome Darkvision"}},Variant:{GradualBoosts:{Hint:"Spread out attribute boosts across multiple levels. Players gain a boost every level except 6, 11, and 16.",Name:"Gradual Attribute Boosts"},AutomaticBonus:{Choices:{ABPFundamentalPotency:"ABP: Allow Property Runes",ABPRulesAsWritten:"ABP: Disallow Property Runes",noABP:"Do not use ABP"},Hint:"Enable the Automatic Bonus Progression variant rule. Skill potency must currently be managed manually.",Name:"Automatic Bonus Progression"},FreeArchetype:{Hint:"Grant additional feat slots for the free archetype variant from Gamemastery Guide pg 194",Name:"Free Archetype"},Hint:"Enable and configure variant rules like Proficiency Without Level or the Stamina system.",Label:"Toggle Variant Rules",Name:"Variant Rules",Proficiency:{Hint:"Play with the proficiency without level variant from Gamemastery Guide pg 198.",ModifiersHint:"Set the modifier value for each proficiency rank.",Name:"Proficiency without Level"},Stamina:{Hint:"Play with the stamina variant from Gamemastery Guide pg 200.",Name:"Stamina"},Title:"Variant Rules"},WorldClock:{DateTheme:{AD:"Earth (Gregorian Calendar)",AR:"Golarion (Absalom Reckoning)",CE:"Unthemed (Gregorian Calendar)",Hint:"Set the theme of the World Clock application.",IC:"Golarion (Imperial Calendar)",Name:"Date Theme"},Hint:"Configure the appearance of the World Clock application.",Label:"Configure World Clock",Name:"World Clock",PlayersCanView:{Hint:"Set whether players can view the World Clock.",Name:"Player Access"},ResetWorldTime:{Button:"Reset",Confirm:{Question:"Are you sure you want to reset this world's elapsed time?",Warning1:"Time-dependent game effects may be impacted.",Warning2:"This action cannot be undone."},Hint:"Reset this world's time elapsed time to zero.",Name:"Reset World Date/Time"},ShowClockButton:{Hint:"Set whether to show the clock button at all (requires refresh).",Name:"Show Clock Button"},SyncDarkness:{Hint:"Set whether any scene's Darkness Level will reflect the time of day.",Name:"Synchronize Darkness (World Default)"},SyncDarknessScene:{Hint:"Set whether this scene's Darkness Level will reflect the time of day.",ManagedBy:"Synchronized with world time.",Name:"Synchronize Darkness (Current Scene)"},TimeConvention:{Hint:"Display either a 24-hour or 12-hour clock.",Name:"Time Convention",Twelve:"12-Hour",TwentyFour:"24-Hour"}},WorldSchemaVersion:{Hint:"Records the schema version for documents in the PF2e system (don't modify this unless you know what you are doing).",Name:"World Schema Version"},critFumbleCardButtons:{hint:"Show critical hit and fumble card draw buttons on attack rolls.",name:"Critical Hit & Fumble Card Buttons"},critFumbleCards:{hint:"Automatically draw a critical hit or fumble card on appropriate rolls.",name:"Critical Hit & Fumble Cards"},statusEffectShowCombatMessage:{hint:"Each turn of an encounter, send a chat message containing the conditions of the turn's participant.",name:"Show Conditions during Encounters"},statusEffectType:{blackWhite:"Black & white",default:"Full color",hint:"Determines which icon set is used for condition token effects.",legacy:"Legacy",name:"Condition Icon Set"}},SaveDCLabel:"Save DC {dc} {type}",SaveDCLabelBasic:"Save DC {dc} basic {type}",SavesFortitude:"Fortitude",SavesFortitudeShort:"Fort",SavesHeader:"Saves",SavesReflex:"Reflex",SavesReflexShort:"Ref",SavesWill:"Will",SavesWillShort:"Will",SavingThrow:"Saving Throw",SavingThrowWithName:"{saveName} Saving Throw",Scene:{HearingRange:{Caveat:"*For performance reasons, the radius is a real measurement rather than a grid-based one.",Hint:'Limit the range* creatures can hear in this scene as a representation of "an environment that distorts the sense, such as a noisy room" (CRB pg. 464). Requires rules-based vision to be enabled.',Name:"Hearing Range (ft.)",Unlimited:"Unlimited"}},ScoreTitle:"Score",SelectLabel:"Select",SellAllTreasureQuestion:"Convert all treasure items into coins",SellAllTreasureTitle:"Sell All Treasure",SellItemConfirmHeader:"Sell Confirmation",SellItemQuestion:"Are you sure you want to sell {item}?",Senses:"Senses",SettingsQuickChecksLabel:"Preview D20 Rolls",SettingsQuickChecksNotes:"If disabled, dialogs to preview D20 rolls will appear only when a roll button is shift-clicked.",SettingsQuickDamageLabel:"Preview Damage Rolls",SettingsQuickDamageNotes:"If disabled, dialogs to preview Damage rolls will appear only when a roll button is shift-clicked.",SheetLabel:"{type} Sheet",ShieldLabel:"Shield",SidebarAppearanceLabel:"Appearance",Size:"Size",SizeLabel:"Size",SkillAcr:"Acrobatics",SkillAcrobatics:"Acrobatics",SkillArc:"Arcana",SkillArcana:"Arcana",SkillAth:"Athletics",SkillAthletics:"Athletics",SkillCheckWithName:"Skill Check: {skillName}",SkillCra:"Crafting",SkillCrafting:"Crafting",SkillDec:"Deception",SkillDeception:"Deception",SkillDip:"Diplomacy",SkillDiplomacy:"Diplomacy",SkillFeatLevels:"Skill Feat Levels",SkillIncreaseLevels:"Skill Increase Levels",SkillIntimidation:"Intimidation",SkillItm:"Intimidation",SkillLabel:"Skill",SkillLore:"Lore",SkillMed:"Medicine",SkillMedicine:"Medicine",SkillNat:"Nature",SkillNature:"Nature",SkillOcc:"Occultism",SkillOccultism:"Occultism",SkillPerformance:"Performance",SkillPotencyHeader:"Skill Potencies",SkillPrf:"Performance",SkillRel:"Religion",SkillReligion:"Religion",SkillSoc:"Society",SkillSociety:"Society",SkillSte:"Stealth",SkillStealth:"Stealth",SkillSur:"Survival",SkillSurvival:"Survival",SkillThi:"Thievery",SkillThievery:"Thievery",SkillsLabel:"Skills",Slug:"Slug",SpecialLabel:"Special",SpecialSensesLabel:"Special Senses",Speed:"Speed",SpeedBaseLabel:"Base {type} Speed",SpeedFeet:"Speed (feet)",SpeedLabel:"{type} Speed",SpeedTypes:"Speed Types",SpeedTypesBurrow:"Burrow",SpeedTypesClimb:"Climb",SpeedTypesFly:"Fly",SpeedTypesLand:"Land",SpeedTypesSwim:"Swim",SpellAbilityModLabel:"+ Mod",SpellArea:"Area: {area}",SpellAttackLabel:"Spell Attack",SpellAttackWithTradition:"{tradition} Spell Attack",SpellBrowserSearchHint:"You can search for name or custom attributes. Possible searchable attributes are: source, spellType, level, materials, target, range, time, duration, damage, damageType, save, concentration, ritual, ability and classes. Example: 'fire, damage:d6' to show all spells that have fire in their name and a d6 in the damage",SpellCastingFormat:"{traditionSpells} {preparationType} Spells",SpellCollectionAdd:"Add to Spell Collection",SpellCollectionRemove:"Remove from Spell Collection",SpellDurationLabel:"Duration",SpellFlexibleAvailable:"Flexible: {value} / {max}",SpellFlexibleLabel:"Flexible",SpellFocusLabel:"Focus",SpellLevelBase:"Base: {level}",SpellLevelHeightened:"Heightened: +{heightened}",SpellLevelLabel:"Spell Rank",SpellPreparedLabel:"Prepared",SpellRangeLabel:"Range",SpellRequirementsLabel:"Requirements",SpellScalingInterval:{Add:"Add Heightening (Interval)",Header:"Scaling (Interval)",Label:"Interval",Selection:"Heightened (+{interval})"},SpellScalingLabel:"Scaling",SpellScalingOverlay:{Add:"Add Heightening (Fixed)",Selection:"Heightened ({level})"},SpellSlotEmpty:"Empty Slot (drag spell here)",SpellSlotExpendedError:"Cannot cast {name}: spell is already expended",SpellSlotNotEnoughError:"Cannot cast {name} at the {level}: not enough spell slots",SpellTargetLabel:"Targets",SpellTraditionsLabel:"Traditions",SpellUnlimitedLabel:"Unlimited",SpellUsesLabel:"Uses",SpellcastingSettings:{AutoHeightenDefault:"Default (Use Actor Level)",AutoHeightenLabel:"Auto Heighten Rank",Title:"Spellcasting Settings"},SpellcastingTypeLabel:"Spellcasting Type",SpellsActionHeader:"Action",StackGroupArrows:"Arrows",StackGroupBlowgunDarts:"Blowgun Darts",StackGroupBolts:"Bolts",StackGroupCoins:"Coins",StackGroupGems:"Gems",StackGroupLabel:"Stack Group",StackGroupRounds10:"Rounds (10)",StackGroupRounds5:"Rounds (5)",StackGroupSlingBullets:"Sling Bullets",StackGroupSprayPellets:"Spray Pellets",StackGroupWoodenTaws:"Wooden Taws",StaminaPointsHeader:"Stamina Points",StaminaPointsShortLabel:"Stamina",StatusBonusShortLabel:"Status",StatusBonusTitle:"Status Bonus",StatusEffects:"{name}'s conditions",StealthLabel:"Stealth",Strike:{Combined:{Description:"You attack with a weapon you're wielding, targeting one creature within your reach (for a melee attack) or within range (for a ranged attack). Roll the attack roll for the weapon or unarmed attack you are using, and compare the result to the target creature's AC to determine the effect.",Success:"You deal damage according to the weapon, including any modifiers, bonuses, and penalties you have to damage."},Default:{CriticalSuccess:"As success, but you deal double damage.",Description:"You attack with a weapon you're wielding or with an unarmed attack, targeting one creature within your reach (for a melee attack) or within range (for a ranged attack). Roll the attack roll for the weapon or unarmed attack you are using, and compare the result to the target creature's AC to determine the effect.",Success:"You deal damage according to the weapon or unarmed attack, including any modifiers, bonuses, and penalties you have to damage."},Fist:{Label:"Fist"},Melee:{Description:"You attack with a weapon you're wielding, targeting one creature within your reach. Roll the attack roll for the weapon you are using, and compare the result to the target creature's AC to determine the effect.",Success:"You deal damage according to the weapon, including any modifiers, bonuses, and penalties you have to damage."},Ranged:{Description:"You attack with a weapon you're wielding, targeting one creature within range. Roll the attack roll for the weapon you are using, and compare the result to the target creature's AC to determine the effect.",NoAmmo:"No ammunition is assigned to {weapon}. Check the Actions tab of {actor}'s sheet.",Success:"You deal damage according to the weapon, including any modifiers, bonuses, and penalties you have to damage."},Unarmed:{Description:"You attack with an unarmed attack, targeting one creature within your reach. Roll the attack roll for the unarmed attack you are using, and compare the result to the target creature's AC to determine the effect.",Success:"You deal damage according to the unarmed attack, including any modifiers, bonuses, and penalties you have to damage."}},StrikesLabel:"Strikes",StrikingRuneLabel:"Striking Rune",Success:"Success",TabActionsDowntimeLabel:"Downtime",TabActionsEncounterLabel:"Encounter",TabActionsExplorationLabel:"Exploration",TabActionsLabel:"Actions",TabCharacterLabel:"Character",TabCraftingLabel:"Crafting",TabDescriptionLabel:"Description",TabDetailsLabel:"Details",TabInventoryLabel:"Inventory",TabManageTabsLabel:"Manage Tabs",TabPathfinderSociety:"Pathfinder Society",TabSkillsLabel:"Proficiencies",TabSpellbookLabel:"Spellcasting",TempHitPointsShortLabel:"Temp HP",TemplateLabel:"{size}-{unit} {shape}",TemporaryItemToolTip:"This item is temporary and will expire after a duration or during daily preparations. It has no value and cannot be sold.",Time:{Duration:"Duration",Unit:{Days:"Days",Hours:"Hours",Minutes:"Minutes",Rounds:"Rounds",Seconds:"Seconds",Unlimited:"Unlimited",UntilEncounterEnds:"Until encounter ends",Weeks:"Weeks"}},ToggleEffectUnidentified:"Toggle Whether Effect Is Unidentified",ToggleSignatureSpellTitle:"Toggle Signature Spell",ToggleSlotlessSpellLevelsTitle:"Toggle visibility of spell ranks without slots",ToggleSpellVisibilityTitle:"Spell Preparation",ToggleUnreadyStrikes:"Toggle unequipped weapons",ToggleWithName:"Toggle: {property}",TogglesLabel:"Toggles",Token:{Appearance:"Appearance",Flanking:"Flanking",SecretDisposition:{Label:"Secret Disposition",Hint:'Activate the "secret" disposition, which displays a purple border for owners and no border or cursor change for all others.'},Size:{Dimensions:"Dimensions",Label:"Size",LinkToActorSize:{Link:"Link to Actor Size",Unlink:"Unlink from Actor Size"}}},TotalCoinage:"Total Coinage",TotalTreasure:"Total Treasure",TotalWealth:"Total Wealth",TrainedSkillsLabel:"Trained Skills",TraitAberration:"Aberration",TraitAcid:"Acid",TraitAdditive0:"Additive 0",TraitAdditive1:"Additive 1",TraitAdditive2:"Additive 2",TraitAdditive3:"Additive 3",TraitAdjusted:"Adjusted",TraitAdjustment:"Adjustment",TraitAeon:"Aeon",TraitAesir:"Aesir",TraitAffixedToAMetalWeapon:"Affixed to a Metal Weapon",TraitAffixedToARangedWeapon:"Affixed to a Ranged Weapon",TraitAffixedToAShield:"Affixed to a Shield",TraitAffixedToAShieldOrWeapon:"Affixed to a Shield or Weapon",TraitAffixedToATwoHandedFirearmOrCrossbow:"Affixed to a Two-Handed Firearm or Crossbow",TraitAffixedToArmor:"Affixed to Armor",TraitAffixedToArmorOrAWeapon:"Affixed to Armor or a Weapon",TraitAffixedToArmorOrTravelersClothing:"Affixed to Armor or Travelers Clothing",TraitAffixedToCreature:"Affixed to a Creature",TraitAffixedToCrossbowOrFirearm:"Affixed to Crossbow or Firearm",TraitAffixedToFirearm:"Affixed to Firearm",TraitAffixedToFirearmWithAReloadOf1:"Affixed to a Firearm With a Reload of 1",TraitAffixedToFirearmWithTheKickbackTrait:"Affixed to a Firearm With the Kickback Trait",TraitAffixedToGround:"Affixed to the Ground",TraitAffixedToGroundIn10FtRadius:"Affixed to the Ground in Four Spaces Along a Circle with a 10-foot Radius",TraitAffixedToGroundIn20FtRadius:"Affixed to the Ground in Four Spaces Along a Circle with a 20-foot Radius",TraitAffixedToHarness:"Affixed to Harness",TraitAffixedToHeadgear:"Affixed to Headgear",TraitAffixedToInnovation:"Affixed to an Innovation",TraitAffixedToInstrument:"Affixed to Instrument",TraitAffixedToLoadBearingWallOrPillar:"Affixed to a Load-Bearing Wall or Pillar",TraitAffixedToMagicalStaff:"Affixed to a Magical Staff",TraitAffixedToMediumHeavyArmor:"Affixed to Medium or Heavy Armor",TraitAffixedToMediumHeavyMetalArmor:"Affixed to Medium or Heavy Metal Armor",TraitAffixedToMeleeWeapon:"Affixed to a Melee Weapon",TraitAffixedToMetalWeapon:"Affixed to a Metal Weapon",TraitAffixedToObjectOrStructure:"Affixed to an Object or Structure",TraitAffixedToStructureObjectOrCreature:"Affixed to Structure, Object, or Creature",TraitAffixedToThrownWeapon:"Affixed to a Thrown Weapon",TraitAffixedToUnarmoredItem:"Affixed to Unarmored Defense Item",TraitAffixedToWeapon:"Affixed to a Weapon",TraitAftermath:"Aftermath",TraitAgathion:"Agathion",TraitAgile:"Agile",TraitAir:"Air",TraitAiuvarin:"Aiuvarin",TraitAlchemical:"Alchemical",TraitAlchemist:"Alchemist",TraitAmp:"Amp",TraitAmphibious:"Amphibious",TraitAnadi:"Anadi",TraitAndroid:"Android",TraitAngel:"Angel",TraitAnimal:"Animal",TraitAnugobu:"Anugobu",TraitApex:"Apex",TraitAphorite:"Aphorite",TraitAppliedToANoninjectionMeleePiercingWeapon:"Applied to a non-injection melee weapon that deals piercing damage",TraitAppliedToAWindPoweredVehicle:"Applied to a wind-powered vehicle",TraitAppliedToAWeapon:"Applied to a weapon",TraitAppliedToAnyItemOfLightOrNegligibleBulk:"Applied to any item of light or negligible Bulk",TraitAppliedToAnyVisibleArticleOfClothing:"Applied to any visible article of clothing",TraitAppliedToArmor:"Applied to armor",TraitAppliedToArmorOrUnarmored:"Applied to armor or unarmored defense clothing",TraitAppliedToBasketBagOrContainer:"Applied to a Basket, Bag, or Other Container",TraitAppliedToBeltCapeCloakOrScarf:"Applied to belt, cape, cloak, or scarf",TraitAppliedToBootsCapeCloakOrUmbrella:"Applied to boots, cape, cloak, or umbrella",TraitAppliedToBucklerShield:"Applied to a buckler or a shield",TraitAppliedToDuelingCapeOrShield:"Applied to dueling cape or shield",TraitAppliedToFootwear:"Applied to Footwear",TraitAppliedToMediumHeavyArmor:"Applied to Medium or Heavy Armor",TraitAppliedToShield:"Applied to shield",TraitAquadynamic:"Aquadynamic",TraitAquatic:"Aquatic",TraitArcane:"Arcane",TraitArchetype:"Archetype",TraitArchon:"Archon",TraitArdande:"Ardande",TraitAreaDamage:"Area Damage",TraitArtifact:"Artifact",TraitAstral:"Astral",TraitAsura:"Asura",TraitAttached:"Attached",TraitAttachedToAThrownWeapon:"Attached to a Thrown Weapon",TraitAttachedToCrossbowOrFirearm:"Attached to Crossbow or Firearm",TraitAttachedToCrossbowOrFirearmFiringMechanism:"Attached to Crossbow or Firearm (Firing Mechanism)",TraitAttachedToCrossbowOrFirearmScope:"Attached to Crossbow or Firearm (Scope)",TraitAttachedToFirearm:"Attached To Firearm",TraitAttachedToFirearmFiringMechanism:"Attached To Firearm (Firing Mechanism)",TraitAttachedToFirearmScope:"Attached To Firearm (Scope)",TraitAttachedToShield:"Attached to Shield",TraitAttachedToShipsBow:"Attached to a Ship's Bow",TraitAttack:"Attack",TraitAuditory:"Auditory",TraitAura:"Aura",TraitAutomaton:"Automaton",TraitAzarketi:"Azarketi",TraitAzata:"Azata",TraitBackstabber:"Backstabber",TraitBackswing:"Backswing",TraitBarbarian:"Barbarian",TraitBard:"Bard",TraitBarding:"Barding",TraitBeast:"Beast",TraitBeastkin:"Beastkin",TraitBleed:"Bleed",TraitBludgeoning:"Bludgeoning",TraitBoggard:"Boggard",TraitBomb:"Bomb",TraitBonded:"Bonded",TraitBottledBreath:"Bottled Breath",TraitBrace:"Brace",TraitBrutal:"Brutal",TraitBulwark:"Bulwark",TraitCaligni:"Caligni",TraitCantrip:"Cantrip",TraitCapacity:"Capacity",TraitCapacity2:"Capacity 2",TraitCapacity3:"Capacity 3",TraitCapacity4:"Capacity 4",TraitCapacity5:"Capacity 5",TraitCarried:"Carried",TraitCatalyst:"Catalyst",TraitCatfolk:"Catfolk",TraitCelestial:"Celestial",TraitChampion:"Champion",TraitChangeling:"Changeling",TraitCharauKa:"Charau-ka",TraitCircus:"Circus",TraitCleric:"Cleric",TraitClimbing:"Climbing",TraitClockwork:"Clockwork",TraitCobbled:"Cobbled",TraitCoda:"Coda",TraitCold:"Cold",TraitColdiron:"Cold Iron",TraitCombination:"Combination",TraitComfort:"Comfort",TraitCommon:"Common",TraitCompanion:"Companion",TraitComplex:"Complex",TraitComposite:"Composite",TraitComposition:"Composition",TraitConcealable:"Concealable",TraitConcentrate:"Concentrate",TraitConcussive:"Concussive",TraitConfusion:"Confusion",TraitConrasu:"Conrasu",TraitConsecration:"Consecration",TraitConstruct:"Construct",TraitConsumable:"Consumable",TraitContact:"Contact",TraitContingency:"Contingency",TraitContract:"Contract",TraitCouatl:"Couatl",TraitCriticalFusion:"Critical Fusion",TraitCurse:"Curse",TraitCursebound:"Cursebound",TraitCursed:"Cursed",TraitDaemon:"Daemon",TraitDarkness:"Darkness",TraitDarvakka:"Darvakka",TraitDeadly:"Deadly",TraitDeadly2D10:"Deadly 2d10",TraitDeadly2D12:"Deadly 2d12",TraitDeadly2D8:"Deadly 2d8",TraitDeadly3D10:"Deadly 3d10",TraitDeadly3D12:"Deadly 3d12",TraitDeadly3D8:"Deadly 3d8",TraitDeadly4D10:"Deadly 4d10",TraitDeadly4D12:"Deadly 4d12",TraitDeadly4D8:"Deadly 4d8",TraitDeadlyD10:"Deadly d10",TraitDeadlyD12:"Deadly d12",TraitDeadlyD4:"Deadly d4",TraitDeadlyD6:"Deadly d6",TraitDeadlyD8:"Deadly d8",TraitDeath:"Death",TraitDedication:"Dedication",TraitDeflectingBludgeoning:"Deflecting Bludgeoning",TraitDeflectingPhysicalRanged:"Deflecting Physical Ranged",TraitDeflectingPiercing:"Deflecting Piercing",TraitDeflectingSlashing:"Deflecting Slashing",TraitDemon:"Demon",TraitDero:"Dero",TraitDescriptionAcid:"Effects with this trait deal acid damage. Creatures with this trait have a magical connection to acid.",TraitDescriptionAdditive:"Feats with the additive trait allow you to spend actions to add special substances to bombs or elixirs. You can add only one additive to a single alchemical item, and attempting to add another spoils the item. You can typically use actions with the additive trait only when you're creating an infused alchemical item, and some can be used only with the Quick Alchemy action. The additive trait is always followed by a level, such as additive 2. An additive adds its level to the level of the alchemical item you're modifying; the result is the new level of the mixture. The mixture's item level must be no higher than your advanced alchemy level",TraitDescriptionAdjusted:"The equipment comes with an adjustment described in its entry. This adjustment is built into the equipment permanently, meaning the equipment can't have another adjustment added, nor can it be swapped out for a different adjustment. If the adjustment alters the item's base statistics, such as adding the noisy trait, that's reflected in the equipment's table entry.",TraitDescriptionAdjustment:"Items with this trait are intended to alter existing pieces of equipment, typically armors, shields, and weapons. The given item will note which type of equipment it modifies. A piece of equipment can only be affected by a single adjustment at a time. Unless otherwise noted, adding or removing an adjustment requires using a 10-minute activity and a repair kit.",TraitDescriptionAeon:"These monitors are the self-styled defenders of reality. Traditional aeons have dualistic natures and forms, and they hold a dichotomy of interests, though axiomites and inevitables do not. Aeons other than axiomites and inevitables communicate via a strange telepathic hodgepodge of sensory sending called envisioning.",TraitDescriptionAesir:"Aesir are often-bellicose monitors of the chaotic planes, honing their skill in battle and preparing for a final confrontation at the end of the multiverse.",TraitDescriptionAftermath:"This trait describes feats that represent special abilities gained after exposure to the weird and deadly.",TraitDescriptionAgathion:"This family of animal-featured celestials is native to the plane of Nirvana. Most agathions are neutral good, have darkvision, and have a weakness to evil damage.",TraitDescriptionAgile:"The multiple attack penalty you take with this weapon on the second attack on your turn is -4 instead of -5, and -8 instead of -10 on the third and subsequent attacks in the turn.",TraitDescriptionAir:"Effects with the air trait either manipulate or conjure air. Those that manipulate air have no effect in a vacuum or an area without air. Creatures with this trait consist primarily of air or have a magical connection to that element.",TraitDescriptionAiuvarin:"A creature with this trait has the aiuvarin versatile heritage. Aiuvarins are of mixed ancestry, including elves or other aiuvarins. An ability with this trait can be used or selected only by aiuvarins.",TraitDescriptionAlchemical:"Alchemical items are powered by reactions of alchemical reagents. Alchemical items aren't magical and don't radiate a magical aura.",TraitDescriptionAlchemist:"This indicates abilities from the alchemist class.",TraitDescriptionAmp:"An amp is a special thoughtform that modifies the properties of your psi cantrips. Psi cantrips each have their own amp, and feats with the amp trait provide different amps you can apply to psi cantrips in place of their normal amps.",TraitDescriptionAmphibious:"An amphibious creature can breathe in water and in air, even outside of its preferred environment, usually indefinitely but at least for hours. These creatures often have a swim Speed. Their bludgeoning and slashing unarmed Strikes don't take the usual -2 penalty for being underwater.",TraitDescriptionAnadi:"A reclusive people from Garund who resemble spiders and can assume human forms.",TraitDescriptionAndroid:"A synthetic humanoid ancestry created by artificial means. Most common in Numeria.",TraitDescriptionApex:"When you Invest an Item that has the apex trait, it improves one of your attribute modifiers, either increasing it by 1 or to a total of +4, whichever grants the higher modifier. This gives you all the benefits of the new attribute modifier until the investiture ends. An apex item grants this benefit only the first time it's invested within a 24-hour period, and you can benefit from only one apex item at a time. If you attempt to invest an apex item when you already have one invested, you don't gain the attribute modifier increase, though you do gain any other effects of Investing the Item.",TraitDescriptionAphorite:"A type of planar scion descended from a being from Axis, the Plane of Law.",TraitDescriptionAquadynamic:"This armor is designed for use underwater, with streamlined design and buoyant materials used in strategic places. You don't apply the armor's check penalty to Acrobatics or Athletics checks in water or similar liquids.",TraitDescriptionArcane:"This magic comes from the arcane tradition, which is built on logic and rationality. Anything with this trait is magical.",TraitDescriptionArdande:"Ardandes are planar scions descended from kizidhars and other beings of elemental wood.",TraitDescriptionArchetype:"This feat belongs to an archetype.",TraitDescriptionArtifact:"Items with this trait are artifacts. These magic items can't be crafted by normal means, and they can't be damaged by normal means. Artifacts are always rare or unique.",TraitDescriptionAttached:"An attached weapon must be combined with another piece of gear to be used. The trait lists what type of item the weapon must be attached to. You must be wielding or wearing the item the weapon is attached to in order to attack with it. For example, shield spikes are attached to a shield, allowing you to attack with the spikes instead of a shield bash, but only if you're wielding the shield. An attached weapon is usually bolted onto or built into the item it's attached to, and typically an item can have only one weapon attached to it. An attached weapon can be affixed to an item with 10 minutes of work and a successful @Check[type:crafting|dc:10] check; this includes the time needed to remove the weapon from a previous item, if necessary. If an item is destroyed, its attached weapon can usually be salvaged.",TraitDescriptionAttack:"An ability with this trait involves an attack. For each attack you make beyond the first on your turn, you take a multiple attack penalty.",TraitDescriptionAuditory:"Auditory actions and effects rely on sound. An action with the auditory trait can be successfully performed only if the creature using the action can speak or otherwise produce the required sounds. A spell or effect with the auditory trait has its effect only if the target can hear it. This applies only to sound-based parts of the effect, as determined by the GM. This is different from a sonic effect, which still affects targets who can't hear it (such as deaf targets) as long as the effect itself makes sound.",TraitDescriptionAura:"An aura is an emanation that continually ebbs out from you, affecting creatures within a certain radius. Aura can also refer to the magical signature of an item or a creature with a strong alignment.",TraitDescriptionAutomaton:"A creature with this trait is a member of the automaton ancestry.",TraitDescriptionAzarketi:"Amphibious humanoids who live among the seas of the Inner Sea region, said to have descended from the people of Azlant. Sometimes known as gillmen or Low Azlanti.",TraitDescriptionBackstabber:"When you hit an off-guard creature, this weapon deals 1 precision damage in addition to its normal damage. The precision damage increases to 2 if the weapon is a +3 weapon.",TraitDescriptionBackswing:"You can use the momentum from a missed attack with this weapon to lead into your next attack. After missing with this weapon on your turn, you gain a +1 circumstance bonus to your next attack with this weapon before the end of your turn.",TraitDescriptionBarbarian:"This indicates abilities from the barbarian class.",TraitDescriptionBard:"This indicates abilities from the bard class.",TraitDescriptionBarding:"You can purchase special armor for animals, called barding. All animals have a trained proficiency rank in light barding, and combat-trained animals are trained in heavy barding. Barding uses the same rules as armor except for the following. The Price and Bulk of barding depend on the animal's size. Unlike for a suit of armor, barding's Strength entry is listed as a modifier, not a score. Barding can't be etched with magic runes, though special magical barding might be available.",TraitDescriptionBeastkin:"Humanoids that can partially or fully transform into animal forms.",TraitDescriptionBomb:"An alchemical bomb combines volatile alchemical components that explode when the bomb hits a creature or object. Most alchemical bombs deal damage, though some produce other effects.",TraitDescriptionBottledBreath:"Bottles of breath are enchanted bottles of cloud and mist, first developed by the denizens of the Plane of Air. You can Activate an item with the bottled breath trait as you inhale it or cause another creature to inhale it.",TraitDescriptionBrace:"A brace weapon is effective at damaging moving opponents. When you Ready to Strike an opponent that moves within your reach, until the start of your next turn Strikes with the brace weapon deal an additional 2 precision damage for each weapon damage die it has.",TraitDescriptionBrutal:"A ranged attack with this trait uses its Strength modifier instead of Dexterity on the attack roll.",TraitDescriptionBulwark:"The armor covers you so completely that it provides benefits against some damaging effects. On Reflex saves to avoid a damaging effect, such as a fireball, you add a +3 modifier instead of your Dexterity modifier.",TraitDescriptionCantrip:"A spell you can cast at will that is automatically heightened to half your level rounded up.",TraitDescriptionCapacity:"Weapons that have the capacity trait typically have multiple barrels or chambers capable of containing a round of ammunition. Capacity is always accompanied by a number indicating the number of barrels or chambers. After a capacity weapon is fired, you can select the next loaded barrel or chamber as an Interact action that doesn't require a free hand. Each barrel or chamber can be reloaded after it's fired as a separate Interact action.",TraitDescriptionCatalyst:"Items with the catalyst trait are consumable material spell components that alter or magnify specific spells. Activating a catalyst is part of Casting the Spell. The catalyst might increase the number of actions required to Cast the Spell, as indicated in the catalyst's Activate entry. Additionally, the spell gains material components if it didn't have them already or adds the catalyst to its existing components. Because the catalyst becomes part of the material components, you can draw the catalyst as part of Casting the Spell.",TraitDescriptionCatfolk:"A creature with this trait is a member of the catfolk ancestry.",TraitDescriptionCenser:"Censers are decorative containers, often metal or ceramic, in which incense is burned. An item with the censer trait must be filled with incense to Activate it, which ignites the incense and causes the censer to exude a cloud of smoke.",TraitDescriptionChampion:"This indicates abilities from the champion class.",TraitDescriptionChangeling:"A creature with this trait is a member of the changeling ancestry.",TraitDescriptionClass:"Archetypes with the class trait fundamentally diverge from your class's specialties but still fit within the theme of your class. You can select a class archetype only if your class meets the criteria listed in the archetype's prerequisites. Class archetypes always alter or replace some of a class's static class features in addition to any new feats they offer. It might be possible to take a class archetype at 1st level if it alters or replaces some of the class's initial class features. The 1st-level ability is presented much like a class feature and includes the class archetype's prerequisites and rules on how it changes your class. If you select this ability, you must take that archetype's dedication feat at 2nd level, and you proceed normally afterward. You can never have more than one class archetype.",TraitDescriptionCleric:"This indicates abilities from the cleric class.",TraitDescriptionClimbing:"The hand wielding the weapon is available to Climb.",TraitDescriptionClockwork:"Clockworks are intricate, complex constructs that can be programmed to perform specific functions.",TraitDescriptionCobbled:"This firearm is cobbled together and likely to misfire. No matter how well you upkeep it, on a failed attack roll, the attack misses and you must roll a @Check[type:flat|dc:5]. If you fail this check, the weapon misfires.",TraitDescriptionCoda:"
Instruments with the coda trait work mostly like staves and have the staff trait. There are two differences: Coda instruments are in the form of musical instruments, and they can be prepared only by bards. Because they're not physically staves, you can't attack with a coda instrument, nor can you etch it with weapon runes.
The process of preparing a coda instrument involves playing significant portions of songs related to the spells within the instrument\u2014either old standards or ones of your own creation. This leaves magical reverberations within the instrument that allow you to complete the songs by playing their coda later in the day.
",TraitDescriptionCold:"Effects with this trait deal cold damage. Creatures with this trait have a connection to magical cold.",TraitDescriptionCombination:"This is a trait for weapons that combine the functionality of melee weapons and firearms in unique or unusual ways. A combination weapon has both a firearm form or usage and a melee weapon form or usage.",TraitDescriptionComfort:"The armor is so comfortable that you can rest normally while wearing it.",TraitDescriptionCommon:"Anything that doesn't list another rarity trait (uncommon, rare, or unique) automatically has the common trait. This rarity indicates that an ability, item, or spell is available to all players who meet the prerequisites for it. A creature of this rarity is generally known and can be summoned with the appropriate summon spell.",TraitDescriptionCompanion:"An item with this trait can be worn by an animal companion or similar creature. A companion can have up to two items invested.",TraitDescriptionComplex:"A hazard with this trait takes turns in an encounter.",TraitDescriptionComposite:"A composite impulse combines multiple elements. You can gain an impulse with the composite trait only if your kinetic elements include all the elements listed in the impulse's traits.",TraitDescriptionComposition:"To cast a composition cantrip or focus spell, you usually use a type of Performance. If the spell includes a verbal component, you must use an auditory performance, and if it includes a somatic component, you must use a visual one. The spell gains all the traits of the performance you used. You can cast only one composition spell each turn, and you can have only one active at a time. If you cast a new composition spell, any ongoing effects from your previous composition spell end immediately.",TraitDescriptionConcealable:"This weapon is designed to be inconspicuous or easily concealed. You gain a +2 circumstance bonus to Stealth checks and DCs to hide or conceal a weapon with this trait.",TraitDescriptionConcentrate:"An action with this trait requires a degree of mental concentration and discipline.",TraitDescriptionConcussive:"These weapons smash as much as puncture. When determining a creature's resistance or immunity to damage from this weapon, use the weaker of the target's resistance or immunity to piercing or to bludgeoning. For instance, if the creature were immune to piercing and had no resistance or immunity to bludgeoning damage, it would take full damage from a concussive weapon. Resistance or immunity to all physical damage, or all damage, applies as normal.",TraitDescriptionConrasu:"A people that are made of cosmic force given consciousness and housed within unique exoskeletons.",TraitDescriptionConsecration:"A consecration spell enhances an area for an extended period of time. A given area can have only a single consecration effect at a time. The new effect attempts to counteract any existing one in areas of overlap.",TraitDescriptionConstruct:"A construct is an artificial creature empowered by a force other than necromancy. Constructs are often mindless; they are immune to bleed damage, death effects, disease, healing, necromancy, nonlethal attacks, poison, and the doomed, drained, fatigued, paralyzed, sickened, and unconscious conditions; and they may have Hardness based on the materials used to construct their bodies. Constructs are not living creatures, nor are they undead. When reduced to 0 Hit Points, a construct creature is destroyed.",TraitDescriptionConsumable:"An item with this trait can be used only once. Unless stated otherwise, it's destroyed after activation. Consumable items include alchemical items and magical consumables such as scrolls and talismans. When a character creates consumable items, they can make them in batches of four.",TraitDescriptionContact:"This poison is delivered by contact with the skin.",TraitDescriptionContingency:"Spells with this trait grant you an action during the spell's effects, typically a reaction with a special trigger. They typically have a long duration, such as 24 hours. You can have only one spell with the contingency trait, or one contingency spell, active at a time. If you cast another spell with the contingency trait or contingency, the newer casting supersedes the older.",TraitDescriptionContract:"A contract is a type of item that magically establishes an agreement between multiple parties and typically grants magical benefits.",TraitDescriptionCriticalFusion:"Critical fusion is a new trait for combination weapons that grants you two additional options for the critical specialization effect when using the combination weapon's melee version to make a melee attack while the firearm is loaded. If you choose to use one of them, they replace the melee usage's normal critical specialization effect. First, you can discharge the firearm to create a loud bang and concussion, using the critical specialization effect for firearms instead of the melee weapon group's critical specialization effect. Second, you can choose to discharge the firearm to increase the critical hit's momentum or shoot the foe as you attack them in melee, dealing 2 additional damage per weapon damage die. Both of these options discharge the firearm, which typically means you have to reload it before firing it again.",TraitDescriptionCurse:"A curse is an effect that places some long-term affliction on a creature. Curses are always magical and are typically the result of a spell or trap. Effects with this trait can be removed only by effects that specifically target curses.",TraitDescriptionCursebound:"Spells with this trait increase the severity of your oracular curse when cast. Usually, only revelation spells have this trait. You can't cast a cursebound spell if you don't have an oracular curse.",TraitDescriptionCursed:"An item with this trait is cursed to cause trouble for its owner. A curse isn't detected when the item is identified, though a critical success reveals both the presence and exact nature of the curse. Cursed items can't be discarded once they've been triggered or invested the first time. The item can be removed only if the curse is removed.",TraitDescriptionDarkness:"Darkness effects extinguish non-magical light in the area, and can counteract less powerful magical light. You must usually target light magic with your darkness magic directly to counteract the light, but some darkness spells automatically attempt to counteract light.",TraitDescriptionDarvakka:"Entropic undead creatures twisted by the Netherworld and the Void.",TraitDescriptionDeadly:"On a critical hit, the weapon adds a weapon damage die of the listed size. Roll this after doubling the weapon's damage. This increases to two dice if the weapon has a greater striking rune and three dice if the weapon has a major striking rune. For instance, a rapier with a greater striking rune deals 2d8 extra piercing damage on a critical hit. An ability that changes the size of the weapon's normal damage dice doesn't change the size of its deadly die.",TraitDescriptionDeath:"An effect with the death trait kills you immediately if it reduces you to 0 HP. Some death effects can bring you closer to death or slay you outright without reducing you to 0 HP.",TraitDescriptionDedication:"You must select a feat with this trait to apply an archetype to your character.",TraitDescriptionDeflecting:"This shield is designed to block or divert certain types of attacks or weapons. Increase the shield's Hardness against the listed type of attack by 2.",TraitDescriptionDetection:"Effects with this trait attempt to determine the presence or location of a person, object, or aura.",TraitDescriptionDeviant:"This trait describes strange supernatural or paranormal abilities.",TraitDescriptionDhampir:"A creature with this trait is a member of the dhampir ancestry. These humanoids are the mortal offspring of vampires and members of other ancestries.",TraitDescriptionDisarm:"You can use this weapon to Disarm with the Athletics skill even if you don't have a free hand. This uses the weapon's reach (if different from your own) and adds the weapon's item bonus to attack rolls (if any) as an item bonus to the Athletics check. If you critically fail a check to Disarm using the weapon, you can drop the weapon to take the effects of a failure instead of a critical failure. On a critical success, you still need a free hand if you want to take the item.",TraitDescriptionDisease:"An effect with this trait applies one or more diseases. A disease is typically an affliction.",TraitDescriptionDivine:"This magic comes from the divine tradition, drawing power from deities or similar sources. Anything with this trait is magical.",TraitDescriptionDoubleBarrel:"This weapon has two barrels that are each loaded separately. You can fire both barrels of a double barrel weapon in a single Strike to increase the weapon damage die by one step. If the weapon has the fatal trait, this increases the fatal die by one step.",TraitDescriptionDowntime:"An activity with this trait takes a day or more, and can be used only during downtime.",TraitDescriptionDromaar:"A creature with this trait has the dromaar versatile heritage. Dromaars are of mixed ancestry, including orcs or other dromaars. An ability with this trait can be used or selected only by dromaars.",TraitDescriptionDrug:"An item with this trait is a drug, a poison that conveys short-term benefits in addition to harmful side effects and long-term consequences. Each time a creature uses a given drug it must also attempt a saving throw against addiction to that drug.",TraitDescriptionDruid:"This indicates abilities from the druid class.",TraitDescriptionDuskwalker:"A creature with this trait has the duskwalker versatile heritage. Duskwalkers are planar scions infused with the supernatural energy of psychopomps. An ability with this trait can be used or selected only by duskwalkers.",TraitDescriptionDwarf:"A creature with this trait is a member of the dwarf ancestry. Dwarves are stout folk who often live underground and typically have darkvision. An ability with this trait can be used or selected only by dwarves. An item with this trait is created and used by dwarves.",TraitDescriptionEarth:"Effects with the earth trait either manipulate or conjure earth. Those that manipulate earth have no effect in an area without earth. Creatures with this trait consist primarily of earth or have a magical connection to that element.",TraitDescriptionEidolon:"A creature with this trait is a summoner's eidolon. An item with this trait can be worn by an eidolon. An eidolon can have up to two items invested.",TraitDescriptionElectricity:"Effects with this trait deal electricity damage. A creature with this trait has a magical connection to electricity.",TraitDescriptionElf:"A creature with this trait is a member of the elf ancestry. Elves are mysterious people with rich traditions of magic and scholarship who typically have low-light vision. An ability with this trait can be used or selected only by elves. A weapon with this trait is created and used by elves.",TraitDescriptionElixir:"Elixirs are alchemical liquids that are used by drinking them.",TraitDescriptionEmotion:"This effect alters a creature's emotions. Effects with this trait always have the mental trait as well. Creatures with special training or that have mechanical or artificial intelligence are immune to emotion effects.",TraitDescriptionEntrench:"You can position yourself in the armor or reposition its articulated pieces to better protect against some attacks. If you're trained in this armor, while wearing it you can spend a single action to gain a +1 circumstance bonus to AC against a certain type of attack until the start of your next turn. The entrench trait lists the type of attack this bonus applies against, typically entrench melee or entrench ranged.",TraitDescriptionEnvironment:"A hazard with this trait is something dangerous that's part of the natural world, such as quicksand or harmful mold.",TraitDescriptionEsoterica:"The esoterica trait is present in many thaumaturge feats and class features that incorporate the various talismans, supernatural trinkets, and other objects you carry with you. Abilities that have the esoterica trait require you to be in possession of your esoterica to use them. Normally, you're assumed to always have your esoterica with you, but in some rare circumstances, you might either not have them on hand or have your gear stripped from you.",TraitDescriptionEvolution:"Feats with this trait affect your eidolon instead of you, typically by granting it additional physical capabilities.",TraitDescriptionExpandable:"An item with the expandable trait increases to a specific size when activated. Unless otherwise noted, this space must be adjacent to you and on the ground, and the item needs to have enough open space to expand into or else the activation has no effect. When the effect ends, the expanded item disintegrates if it's a consumable or shrinks back to its normal size if it's not a consumable.",TraitDescriptionExploration:"An activity with this trait takes more than a turn to use, and can usually be used only during exploration mode.",TraitDescriptionExtradimensional:"This effect or item creates an extradimensional space. An extradimensional effect placed inside another extradimensional space ceases to function until it is removed.",TraitDescriptionFatal:"The fatal trait includes a die size. On a critical hit, the weapon's damage die increases to that die size instead of the normal die size, and the weapon adds one additional damage die of the listed size.",TraitDescriptionFatalAim:"It's possible to hold the stock of this weapon under one arm so you can fire it with a single hand as long as the other hand isn't holding a weapon, shield, or anything else you would need to move and position, to ensure the weapon doesn't slip out from under your arm. However, if you use both hands, the weapon can make fatal attacks. When you wield the weapon in two hands, it gains the fatal trait with the listed damage die. Holding the weapon underarm stably enough to fire is significantly more complicated than just releasing one hand from the weapon, so to switch between the two grips, you must do so with an Interact action rather than Releasing or as part of reloading.",TraitDescriptionFear:"Fear effects evoke the emotion of fear. Effects with this trait always have the mental and emotion traits as well.",TraitDescriptionFetchling:"A creature with this trait is a member of the fetchling ancestry. Fetchlings were once human, but generations of life in the Netherworld have transformed them.",TraitDescriptionFey:"Creatures of the First World are called the fey.",TraitDescriptionFighter:"This indicates abilities from the fighter class.",TraitDescriptionFigurehead:"While many ships are adorned with decorative carvings, daring crews sometimes procure magical figureheads for their vessels.",TraitDescriptionFinesse:"You can use your Dexterity modifier instead of your Strength modifier on attack rolls using this melee weapon. You still use your Strength modifier when calculating damage.",TraitDescriptionFinisher:"Finishers are spectacular finishing moves. You can use a finisher only if you have panache, and you lose your panache immediately after performing a finisher. Once you use a finisher, you can't use actions that have the attack trait for the rest of your turn. Some finisher actions also grant an effect on a failure. If your finisher succeeds, you can choose to apply the failure effect instead.",TraitDescriptionFinite:"Planes with this trait consist of a limited amount of space.",TraitDescriptionFire:"Effects with the fire trait deal fire damage or either conjure or manipulate fire. Those that manipulate fire have no effect in an area without fire. Creatures with this trait consist primarily of fire or have a magical connection to that element.",TraitDescriptionFleshwarp:"A humanoid transformed so completely by outside forces that they are now a unique ancestry.",TraitDescriptionFlexible:"The armor is flexible enough that it doesn't hinder most actions. You don't apply its check penalty to Acrobatics or Athletics checks.",TraitDescriptionFlourish:"Flourish actions are actions that require too much exertion to perform a large number in a row. You can use only 1 action with the flourish trait per turn.",TraitDescriptionFocus:"Focus spells are a special type of spell attained directly from a branch of study, from a deity, or from another specific source. You can learn focus spells only through special class features or feats, rather than choosing them from a spell list. Furthermore, you cast focus spells using a special pool of Focus Points\u2014you can't prepare a focus spell in a spell slot or use your spell slots to cast focus spells; similarly, you can't spend your Focus Points to cast spells that aren't focus spells.",TraitDescriptionFocused:"An item with this trait can give you an additional Focus Point. This focus point is separate from your focus pool and doesn't count toward the cap on your focus pool. You can gain this benefit only if you have a focus pool, and there might be restrictions on how the point can be used. You can't gain more than 1 Focus Point per day from focused items.",TraitDescriptionFoldaway:"
This shield can collapse into a smaller form attached to a gauntlet for stability and easy travel. You can use an Interact action to deploy or stow the shield. While it's deployed, you can Raise the Shield as long as you have that hand free or are holding an object of light Bulk that's not a weapon in that hand. The shield impedes the use of your hand while it's deployed. Though you can still hold items in that hand, you can't wield weapons in that hand, operate anything that takes two hands, or attack with the gauntlet.
A foldaway shield must be attached to a gauntlet for stability. It can be affixed to an item with 10 minutes of work and a successful DC 10 Crafting check; this includes the time needed to remove the shield from a previous gauntlet, if necessary. If the gauntlet is destroyed, the foldaway shield can usually be salvaged. The collapsible nature of the shield makes it impossible to affix an attached weapon to it.
",TraitDescriptionForce:"Effects with this trait deal force damage or create objects made of pure magical force.",TraitDescriptionForceful:"This weapon becomes more dangerous as you build momentum. When you attack with it more than once on your turn, the second attack gains a circumstance bonus to damage equal to the number of weapon damage dice, and each subsequent attack gains a circumstance bonus to damage equal to double the number of weapon damage dice.",TraitDescriptionFortune:"A fortune effect beneficially alters how you roll your dice. You can never have more than one fortune effect alter a single roll. If multiple fortune effects would apply, you have to pick which to use. If a fortune effect and a misfortune effect would apply to the same roll, the two cancel each other out, and you roll normally.",TraitDescriptionFreeHand:"This weapon doesn't take up your hand, usually because it is built into your armor. A free-hand weapon can't be Disarmed. You can use the hand covered by your free-hand weapon to wield other items, perform manipulate actions, and so on. You can't attack with a free-hand weapon if you're wielding anything in that hand or otherwise using that hand. When you're not wielding anything and not otherwise using the hand, you can use abilities that require you to have a hand free as well as those that require you to be wielding a weapon in that hand. Each of your hands can have only one free-hand weapon on it.",TraitDescriptionFulu:"Fulus are small paper charms that can be affixed to a suit of armor, a shield, a weapon, a creature, or even a structure. Some fulus are composed of multiple such charms, taking effect only once all have been affixed. Normal fulus have effects immediately once affixed, while fulu talismans have an effect only once activated. Once a fulu has been activated, it lasts for the given duration and then burns out. Unless otherwise noted, fulus expire one year after being created, reverting to mundane paper. All fulus have the fulu and consumable traits. Fulus also have a tradition trait\u2014either arcane, divine, occult or primal\u2014determined by the magical tradition of its creator. For example, a fulu created by a priest would have the divine trait, whereas a witch who dabbles in fate might create a fulu with the occult trait. Some fulus also have the talisman trait, if they work similarly to talismans (such as being affixed to a suit of armor, a shield, or a weapon. Each fulu's stat block indicates the type of item or creature it can be affixed to. Affixing or removing a fulu requires using the Affix a Fulu activity, or the Affix a Talisman action instead if the fulu is also a talisman.",TraitDescriptionGadget:"Gadgets are consumable technological inventions with innovative uses.",TraitDescriptionGanzi:"A planar scion descended from a chaotic being of the Maelstrom, such as a protean.",TraitDescriptionGeneral:"A type of feat that any character can select, regardless of ancestry and class, as long as they meet the prerequisites. You can select a feat with this trait when your class grants a general feat.",TraitDescriptionGenie:"The diverse families of genies hold positions of prominence on the Elemental Planes. They have powerful magical abilities.",TraitDescriptionGeniekin:"An umbrella term for planar scions descended from beings from the Elemental Planes.",TraitDescriptionGhoran:"An intelligent plant ancestry that maintain long lives by rejuvenating themselves from seeds.",TraitDescriptionGhul:"Greedy and gluttonous undead originally formed from genie.",TraitDescriptionGnoll:"Gnolls are humanoids that resemble hyenas.",TraitDescriptionGnome:"A creature with this trait is a member of the gnome ancestry. Gnomes are small people skilled at magic who seek out new experiences and usually have low-light vision. An ability with this trait can be used or selected only by gnomes. A weapon with this trait is created and used by gnomes.",TraitDescriptionGoblin:"A creature with this trait can come from multiple tribes of creatures, including goblins, hobgoblins, and bugbears. Goblins tend to have darkvision. An ability with this trait can be used or chosen only by goblins. A weapon with this trait is created and used by goblins.",TraitDescriptionGoloma:"Insular humanoids that bear countless eyes.",TraitDescriptionGrapple:"You can use this weapon to Grapple with the Athletics skill even if you don't have a free hand. This uses the weapon's reach (if different from your own) and adds the weapon's item bonus to attack rolls as an item bonus to the Athletics check. If you critically fail a check to Grapple using the weapon, you can drop the weapon to take the effects of a failure instead of a critical failure.",TraitDescriptionGrimoire:"Spellbooks are useful tools for any magic user to write down incantations and runes of power, but where most spellbooks are nothing more than ink on parchment, grimoires have absorbed the magic of the spells within\u2014magic that knowledgeable spellcasters can use to augment their spells.",TraitDescriptionGrippli:"Gripplis are a family of frog-like humanoids",TraitDescriptionGunslinger:"This indicates abilities from the gunslinger class.",TraitDescriptionHalfling:"A creature with this trait is a member of the halfling ancestry. These small people are friendly wanderers considered to be lucky. An ability with this trait can be used or selected only by halflings. A weapon with this trait is created and used by halflings.",TraitDescriptionHampering:"A weapon with the hampering trait includes a disruptive limb or flange. You can use an Interact action to thrash the weapon in a square within the weapon's reach. That square becomes difficult terrain until you attack with the weapon, move, would otherwise stop thrashing it, or at the beginning of your next turn.",TraitDescriptionHarnessed:"This shield features a special brace or opening designed to hold jousting weapons.",TraitDescriptionHaunt:"A hazard with this trait is a spiritual echo, often of someone with a tragic death. Putting a haunt to rest often involves resolving the haunt's unfinished business. A haunt that hasn't been properly put to rest always returns after a time.",TraitDescriptionHealing:"A healing effect restores a creature's body, typically by restoring Hit Points, but sometimes by removing diseases or other debilitating effects.",TraitDescriptionHefty:"A hefty shield is so heavy that raising it takes more effort. Raising a Shield with the hefty trait is a 2-action activity unless your Strength score equals or exceeds the number with the trait.",TraitDescriptionHex:"A hex is a type of focus spell a witch can cast.",TraitDescriptionHindering:"This armor is so heavy and bulky it slows you down no matter what. You take a -5 penalty to all your Speeds (to a minimum of a 5-foot Speed). This is separate from and in addition to the armor's Speed penalty, and affects you even if your Strength or an ability lets you reduce or ignore the armor's Speed penalty.",TraitDescriptionHobgolin:"Hobgoblins are a sturdy, clever people with a propensity for militaristic order.",TraitDescriptionHoly:"Effects with the holy trait are tied to powerful magical forces of benevolence and virtue. They often have stronger effects on unholy creatures. Creatures with this trait are strongly devoted to holy causes and often have weakness to unholy. If a creature with weakness to holy uses a holy item or effect, it takes damage from its weaknes",TraitDescriptionHuman:"A creature with this trait is a member of the human ancestry. Humans are a diverse array of people known for their adaptability. An ability with this trait can be used or selected only by humans.",TraitDescriptionHumanoid:"Humanoid creatures reason and act much like humans. They typically stand upright and have two arms and two legs.",TraitDescriptionIfrit:"A type of geniekin descended from a being from the Plane of Fire.",TraitDescriptionIllusion:"Effects and magic items with this trait involve false sensory stimuli.",TraitDescriptionImpulse:"The primary magical actions kineticists use are called impulses. You can use an impulse only if your kinetic aura is active and channeling that element, and only if you have a hand free to shape the elemental flow. The impulse trait means the action has the concentrate trait unless another ability changes this. If an impulse allows you to choose an element, you can choose any element you're channeling, and the impulse gains that element's trait.",TraitDescriptionIncapacitation:"An ability with this trait can take a character completely out of the fight or even kill them, and it's harder to use on a more powerful character. If a spell has the incapacitation trait, any creature of more than twice the spell's rank treats the result of their check to prevent being incapacitated by the spell as one degree of success better, or the result of any check the spellcaster made to incapacitate them as one degree of success worse. If any other effect has the incapacitation trait, a creature of higher level than the item, creature, or hazard generating the effect gains the same benefits.",TraitDescriptionIncarnate:"A spell with the incarnate trait is similar in theme to spells that summon creatures, but it doesn't conjure a minion with the summoned trait. Instead, when summoned, the incarnate creature takes its Arrive action when you finish Casting the Spell. At the end of your next turn, the incarnate creature can either Step, Stride, or take the action for another movement type it has (such as Climb or Burrow), and then takes its Depart action. The spell then ends. The names of specific Arrive and Depart actions are listed in italics after the word \u201CArrive\u201D or \u201CDepart\u201D respectively, along with any traits. A creature summoned by an incarnate spell acts in your interests, directs its effects away from you and your allies as much as possible, and might listen to your requests, but ultimately makes its own decisions. If the spell indicates that the incarnate makes a decision, the GM determines what the incarnate would do. It might even become more inclined to do precisely as you wish over multiple summonings. The incarnate is not fully a creature. It can't take any other actions, nor can it be targeted or harmed by Strikes, spells, or other effects unless they would be able to target or end a spell effect (such as dispel magic). It has a size for the purposes of determining its placement for effects, but it doesn't block movement. If applicable, its effects use your spell DCs and spell attack roll modifier.",TraitDescriptionIncorporeal:"An incorporeal creature or object has no physical form. It can pass through solid objects, including walls. When inside an object, an incorporeal creature can't perceive, attack, or interact with anything outside the object, and if it starts its turn in an object, it is slowed 1. Corporeal creatures can pass through an incorporeal creature, but they can't end their movement in its space. An incorporeal creature can't attempt Strength-based checks against physical creatures or objects-only against incorporeal ones-unless those objects have the ghost touch property rune. Likewise, a corporeal creature can't attempt Strength-based checks against incorporeal creatures or objects. Incorporeal creatures usually have immunity to effects or conditions that require a physical body, like disease, poison, and precision damage. They usually have resistance against all damage (except force damage and damage from Strikes with the ghost touch property rune), with double the resistance against non-magical damage.",TraitDescriptionInfused:"You created an alchemical item with the infused trait using your infused reagents, and it has a limited time before it becomes inert. Any nonpermanent effects from your infused alchemical items, with the exception of afflictions such as slow-acting poisons, end when you make your daily preparations again.",TraitDescriptionInfusion:"Actions with the infusion trait tweak your kineticist impulses. You must use an infusion action directly before the impulse action you want to alter. If you use any action (including free actions and reactions) other than an impulse action directly after, you waste the benefits of the infusion action. Any additional effects added by an infusion action are part of the impulse's effect, not of the infusion action itself.",TraitDescriptionIngested:"This poison is delivered when drunk or eaten.",TraitDescriptionInhaled:"This poison is delivered when breathed in.",TraitDescriptionInjection:"This weapon can be filled with an injury poison. Immediately after a successful attack with the weapon, you can inject the target with the loaded poison with a single Interact action. Refilling the weapon with a new substance requires three Interact actions, and uses both hands.",TraitDescriptionInjury:"This poison is delivered by damaging the recipient.",TraitDescriptionInscribed:"The armor or shield has been treated so it can be inscribed with magical symbols using the same method as Crafting a scroll. Inscribed attire can hold one scroll inscribed on it. You need a free hand to Activate the scroll, but you don't need to Interact to draw it. You can also Activate the magic to erase the scroll the armor currently contains. You can't inscribe a new scroll onto the armor if a scroll is currently inscribed on it or if the armor is broken.",TraitDescriptionIntegrated:"This shield has been created to include a weapon in its construction, which works like an attached weapon but can't be removed from the shield.",TraitDescriptionIntelligent:"An item with this trait is intelligent and has its own will and personality, as well as several statistics that most items don't have. Intelligent items can't be crafted by normal means, and they are always rare or unique.",TraitDescriptionInventor:"This indicates abilities from the inventor class.",TraitDescriptionInvested:"A character can wear only 10 magical items that have the invested trait. None of the magical effects of the item apply if the character hasn't invested it, nor can it be activated, though the character still gains any normal benefits from wearing the physical item (like a hat keeping rain off their head).",TraitDescriptionInvestigator:"This indicates abilities from the investigator class.",TraitDescriptionJousting:"The weapon is suited for mounted combat with a harness or similar means. When mounted, if you moved at least 10 feet on the action before your attack, add a circumstance bonus to damage for that attack equal to the number of damage dice for the weapon. In addition, while mounted, you can wield the weapon in one hand, changing the damage die to the listed value.",TraitDescriptionKashrishi:"A stout ancestry bearing distinctive crystal horns and inherent psychic abilities.",TraitDescriptionKickback:"A kickback weapon is extra powerful and difficult to use due to its high recoil. A kickback weapon deals 1 additional damage with all attacks. Firing a kickback weapon gives a -2 circumstance penalty to the attack roll, but characters with 14 or more Strength ignore the penalty. Attaching a kickback weapon to a deployed bipod, tripod, or other stabilizer can lower or negate this penalty.",TraitDescriptionKineticist:"This indicates abilities from the kineticist class.",TraitDescriptionKitsune:"Shapeshifting humanoids whose true forms resemble foxes.",TraitDescriptionKobold:"A creature with this trait is a member of the kobold ancestry.",TraitDescriptionLaminar:"The armor is made up of layered sections, so when it breaks, it isn't as much of a problem. The status penalty to AC if this armor is broken is \u20131 for broken medium armor, \u20132 for broken heavy armor, or no penalty for broken light armor.",TraitDescriptionLaunching:`A mechanism within this shield can shoot projectiles, causing the shield to also function as a ranged weapon. The trait lists the type of weapon, such as "launching dart." Striking with the launcher requires the same number of hands as normal, except that the hand holding the shield counts toward this total, so a one-handed ranged weapon would require only one hand. Reloading takes the normal number of Interact actions, to a minimum of 1 action, and you can't use the hand holding your shield to reload.`,TraitDescriptionLeshy:"A creature with this trait is a member of the leshy ancestry.",TraitDescriptionLight:"Light effects overcome non-magical darkness in the area, and can counteract magical darkness. You must usually target darkness magic with your light magic directly to counteract the darkness, but some light spells automatically attempt to counteract darkness.",TraitDescriptionLinguistic:"An effect with this trait depends on language comprehension. A linguistic effect that targets a creature works only if the target understands the language you are using.",TraitDescriptionLitany:"Litanies are special devotion spells, typically used by champions and requiring a single action, that usually give temporary immunity to further litanies.",TraitDescriptionLizardfolk:"These reptilian humanoids, also known as iruxi, are extremely adaptable and patient.",TraitDescriptionLozenge:"You Activate an alchemical lozenge by putting it in your mouth. It stays there, slowly dissolving and releasing its ingredients over time. You can bite a lozenge for a secondary effect. The action this takes is noted in the item. As soon as this secondary effect is over, the lozenge is used up and its benefits for you end. You can drink elixirs, potions, and beverages with a lozenge in your mouth, but you can't benefit from more than one lozenge at a time. If you have two lozenges in your mouth at the same time, both become inert. You can also spit out a lozenge as a single action to end its effect and make it inert. A lozenge dissolves due to its alchemical ingredients, so it typically still works even if you don't have saliva.",TraitDescriptionMagical:"Something with the magical trait is imbued with magical energies not tied to a specific tradition of magic. Some items or effects are closely tied to a particular tradition of magic. In these cases, the item has the arcane, divine, occult, or primal trait instead of the magical trait. Any of these traits indicate that the item is magical.",TraitDescriptionMagus:"This indicates abilities from the magus class.",TraitDescriptionManipulate:"You must physically manipulate an item or make gestures to use an action with this trait. Creatures without a suitable appendage can't perform actions with this trait. Manipulate actions often trigger reactions.",TraitDescriptionMechanical:"A hazard with this trait is a constructed physical object.",TraitDescriptionMental:"A mental effect can alter the target's mind. It has no effect on an object or a mindless creature.",TraitDescriptionMetal:"Effects with the metal trait either manipulate or conjure metal. Those that manipulate metal have no effect in an area without metal. Creatures with this trait consist primarily of metal or have a magical connection to that element.",TraitDescriptionMindless:"A mindless creature has either programmed or rudimentary mental attributes. Most, if not all, of their mental attribute modifiers are -5. They are immune to all mental effects.",TraitDescriptionMindshift:"An action with this trait can always be altered to use the raw power of your mind. When you take this action, you can choose to replace any damage it deals with mental damage, give it the mental trait, and replace any save it requires with a Will save. The action loses any traits matching damage types it no longer deals.",TraitDescriptionMinion:"Minions are creatures that directly serve another creature. A creature with this trait can use only 2 actions per turn, doesn't have reactions, and can't act when it's not your turn. Your minion acts on your turn in combat, once per turn, when you spend an action to issue it commands. For an animal companion, you Command an Animal; for a minion that's a spell or magic item effect, like a summoned minion, you Sustain a Spell or Sustain an Activation; if not otherwise specified, you issue a verbal command as a single action with the auditory and concentrate traits. If given no commands, minions use no actions except to defend themselves or to escape obvious harm. If left unattended for long enough, typically 1 minute, mindless minions usually don't act, animals follow their instincts, and sapient minions act how they please. A minion can't control other creatures.",TraitDescriptionMisfortune:"A misfortune effect detrimentally alters how you roll your dice. You can never have more than one misfortune effect alter a single roll. If multiple misfortune effects would apply, the GM decides which is worse and applies it. If a fortune effect and a misfortune effect would apply to the same roll, the two cancel each other out, and you roll normally.",TraitDescriptionMissive:"A missive is a piece of magical stationery that must be crafted and composed before it can be activated. All missives have the missive and consumable traits. Missives are often constructed of paper, parchment, or vellum, but any other thin, portable material that can hold writing or embossing upon it can be crafted into missives. After being crafted, the missive is a blank sheet until a message is composed upon it, completing its magic.",TraitDescriptionModification:"A feat with this trait alters the construction of your innovation. If you have the reconfigure class feature, you can retrain such a feat more easily.",TraitDescriptionModular:`The weapon has multiple configurations that you can switch between using an Interact action. Typically, switching between configurations of a modular weapon allows it to deal different types of damage (listed in the trait, such as "modular B, P, or S"), though it's possible for a modular weapon's description to list more complicated configurations.`,TraitDescriptionMonk:"Abilities with this trait are from the monk class. A weapon with this trait is primarily used by monks.",TraitDescriptionMonkWeapon:"Many monks learn to use these weapons.",TraitDescriptionMorph:"Effects that slightly alter a creature's form have the morph trait. Any Strikes specifically granted by a morph effect are magical. You can be affected by multiple morph spells at once, but if you morph the same body part more than once, the second morph effect attempts to counteract the first (in the same manner as two polymorph effects, described in that trait). Your morph effects might also end if you are polymorphed and the polymorph effect invalidates or overrides your morph effect. The GM determines which morph effects can be used together and which can't.",TraitDescriptionMounted:"Mounted siege weapons take up a certain size and space, and typically have statistics to allow them to be attacked. They're used for large-scale warfare.",TraitDescriptionMove:"An action with this trait involves moving from one space to another.",TraitDescriptionMulticlass:"Archetypes with the multiclass trait represent diversifying your training into another class's specialties. You can't select a multiclass archetype's dedication feat if you are a member of the class of the same name.",TraitDescriptionMutagen:"An elixir with the mutagen trait temporarily transmogrifies the subject's body and alters its mind. A mutagen always conveys one or more beneficial effects paired with one or more detrimental effects. Mutagens are polymorph effects, meaning you can benefit from only one at a time.",TraitDescriptionNagaji:"A traditionalist ancestry with reptilian features and serpentine heads.",TraitDescriptionNephilim:"A creature with this trait has the nephilim versatile heritage. Nephilim are planar scions descended from immortal beings from other planes. An ability with this trait can be used or selected only by nephilim.",TraitDescriptionNindoru:"Nindorus are chaotic evil fiends that rise from corruptions to the cycle of reincarnating souls and live on the Universe. Although they often have elements in their appearance that make them seem undead, they're actually living beings. Most nindorus have darkvision, are immune to death effects, have weakness to silver, and possess the power to manifest objects or creatures from their thoughts.",TraitDescriptionNoisy:"This armor is loud and likely to alert others to your presence when you're using the Avoid Notice exploration activity. The armor's check penalty applies to Stealth checks even if you meet the required Strength score.",TraitDescriptionNone:"This trait has no description.",TraitDescriptionNonlethal:"Attacks with this weapon are nonlethal, and are used to knock creatures unconscious instead of kill them. You can use a nonlethal weapon to make a lethal attack with a -2 circumstance penalty.",TraitDescriptionOath:"Oaths add an additional tenet to your code. You can usually have only one feat with this trait.",TraitDescriptionOccult:"This magic comes from the occult tradition, calling upon bizarre and ephemeral mysteries. Anything with this trait is magical.",TraitDescriptionOil:"Oils are magical gels, ointments, pastes, or salves that are typically applied to an object and are used up in the process.",TraitDescriptionOlfactory:"An olfactory effect can affect only creatures that can smell it. This applies only to olfactory parts of the effect, as determined by the GM.",TraitDescriptionOpen:"These maneuvers work only as the first salvo on your turn. You can use an open only if you haven't used an action with the attack or open trait yet this turn.",TraitDescriptionOracle:"This indicates abilities from the oracle class.",TraitDescriptionOrc:"A creature with this trait is a member of the orc ancestry. A weapon with this trait is a weapon which orcs craft and use.",TraitDescriptionOread:"A type of geniekin descended from a being from the Plane of Earth.",TraitDescriptionOverflow:"Powerful impulses temporarily overdraw the energy of your kinetic gate. When you use an impulse that has the overflow trait, your kinetic aura deactivates until you revitalize it (typically with Channel Elements). Extinguishing your element this severely is taxing, and consequently, you can use only one overflow impulse per round, even if you reactivate your kinetic gate.",TraitDescriptionParry:"This weapon can be used defensively to block attacks. While wielding this weapon, if your proficiency with it is trained or better, you can spend a single action to position your weapon defensively, gaining a +1 circumstance bonus to AC until the start of your next turn.",TraitDescriptionPeachwood:"Peachwood weapons have a particularly auburn tinge to them when under direct sunlight. Peachwood is treated as duskwood for any undead creatures' resistances or weaknesses related to duskwood (allowing a peachwood weapon to bypass a jiang-shi's resistance, for example). In addition, peachwood weapons bypass a small portion of the resistances of any undead creature. Strikes with a peachwood weapon treat an undead's resistances against physical damage as 2 lower for standard-grade peachwood, and 4 lower for high-grade.",TraitDescriptionPlant:"Vegetable creatures have the plant trait. They are distinct from normal plants. Magical effects with this trait manipulate or conjure plants or plant matter in some way. Those that manipulate plants have no effect in an area with no plants.",TraitDescriptionPoison:"An effect with this trait delivers a poison or deals poison damage. An item with this trait is poisonous and might cause an affliction.",TraitDescriptionPolymorph:"These effects transform the target into a new form. A target can't be under the effect of more than one polymorph effect at a time. If it comes under the effect of a second polymorph effect, the second polymorph effect attempts to counteract the first. If it succeeds, it takes effect, and if it fails, the spell has no effect on that target. Any Strikes specifically granted by a polymorph effect are magical. Unless otherwise stated, polymorph spells don't allow the target to take on the appearance of a specific individual creature, but rather just a generic creature of a general type or ancestry. If you take on a battle form with a polymorph spell, the special statistics can be adjusted only by circumstance bonuses, status bonuses, and penalties. Unless otherwise noted, the battle form prevents you from casting spells, speaking, and using most manipulate actions that require hands. (If there's doubt about whether you can use an action, the GM decides.) Your gear is absorbed into you; the constant abilities of your gear still function, but you can't activate any items.",TraitDescriptionPonderous:"The armor has moving parts or other complications that lengthen the wearer's initial reaction time. While wearing the armor, you take a \u20131 penalty to initiative checks. If you don't meet the armor's required Strength score, this penalty increases to be equal to the armor's check penalty if it's worse.",TraitDescriptionPoppet:"A creature with this trait is a member of the poppet ancestry.",TraitDescriptionPortable:"Portable siege weapons, such as battering rams, can be more easily carried and have a role in both warfare and smaller conflicts or exploration.",TraitDescriptionPossession:"Effects with this trait allow a creature to project its mind and spirit into a target. A creature immune to mental effects can't use a possession effect. While possessing a target, a possessor's true body is unconscious (and can't wake up normally), unless the possession effect allows the creature to physically enter the target. Whenever the target takes damage, the possessor takes half that amount of damage as mental damage. A possessor loses the benefits of any of its active spells or abilities that affect its physical body, though it gains the benefits of the target's active spells and abilities that affect their body. A possessor can use any of the target's abilities that are purely physical, and it can't use any of its own abilities except spells and purely mental abilities. The GM decides whether an ability is purely physical or purely mental. A possessor uses the target's attack modifier, AC, Fortitude save, Reflex save, Perception, and physical skills, and its own Will save, mental skills, spell attack roll, and spell DC; benefits of invested items apply where relevant (the possessor's invested items apply when using its own values, and the target's invested items apply when using the target's values). A possessor gains no benefit from casting spells that normally affect only the caster, since it isn't in its own body. The possessor must use its own actions to make the possessed creature act. If a possessor reaches 0 Hit Points through any combination of damage to its true body and mental damage from the possession, it is knocked out as normal and the possession immediately ends. If the target reaches 0 Hit Points first, the possessor can either fall unconscious with the body and continue the possession or end the effect as a free action and return to its body. If the target dies, the possession ends immediately and the possessor is stunned for 1 minute.",TraitDescriptionPotion:"A potion is a magical liquid activated when you drink it.",TraitDescriptionPrecious:"Valuable materials with special properties have the precious trait. They can be substituted for base materials when you Craft items.",TraitDescriptionPrediction:"Effects with this trait determine what is likely to happen in the near future. Most predictions are divinations.",TraitDescriptionPress:"Actions with this trait allow you to follow up earlier attacks. An action with the press trait can be used only if you are currently affected by a multiple attack penalty. You can't use a press action when it's not your turn, even if you use the Ready activity. Some actions with the press trait also grant an effect on a failure. The effects that are added on a failure don't apply on a critical failure. If your press action succeeds, you can choose to apply the failure effect instead. (For example, you may wish to do this when an attack deals no damage due to resistance.)",TraitDescriptionPrimal:"This magic comes from the primal tradition, connecting to the natural world and instinct. Anything with this trait is magical.",TraitDescriptionProcessed:"An alchemical consumable with the processed trait can be created with Quick Alchemy but is too complex to create in a single action.",TraitDescriptionPropulsive:"You add half your Strength modifier (if positive) to damage rolls with a propulsive ranged weapon. If you have a negative Strength modifier, you add your full Strength modifier instead.",TraitDescriptionPsyche:"Your psyche must be unleashed to use abilities that have the psyche trait, and they end automatically when your unleashed psyche subsides.",TraitDescriptionPsychic:"This indicates abilities from the psychic class.",TraitDescriptionRadiation:"A dangerous, typically poisonous emission typically originating from radioactive minerals.",TraitDescriptionRage:"You must be raging to use abilities with the rage trait, and they end automatically when you stop raging.",TraitDescriptionRange:"These attacks will either list a finite range or a range increment, which follows the normal rules for range increments.",TraitDescriptionRangedTrip:"This weapon can be used to Trip with the Athletics skill at a distance up to the weapon's first range increment. The skill check takes a -2 circumstance penalty. You can add the weapon's item bonus to attack rolls as a bonus to the check. As with using a melee weapon to trip, a ranged trip doesn't deal any damage when used to Trip.",TraitDescriptionRanger:"This indicates abilities from the ranger class.",TraitDescriptionRare:"This rarity indicates that a rules element is very difficult to find in the game world. A rare feat, spell, item or the like is available to players only if the GM decides to include it in the game, typically through discovery during play. Creatures with this trait are rare. They typically can't be summoned. The DC of Recall Knowledge checks related to these creatures is increased by 5.",TraitDescriptionRatfolk:"A creature with this trait is a member of the ratfolk ancestry.",TraitDescriptionRazing:"Razing weapons are particularly good at damaging objects, structures, and vehicles. Whenever you deal damage to an object (including shields and animated objects), structure, or vehicle with a razing weapon, the object takes an amount of additional damage equal to double the number of weapon damage dice.",TraitDescriptionReach:"Natural attacks with this trait can be used to attack creatures up to the listed distance away instead of only adjacent creatures. Weapons with this trait are long and can be used to attack creatures up to 10 feet away instead of only adjacent creatures. For creatures that already have reach with the limb or limbs that wield the weapon, the weapon increases their reach by 5 feet.",TraitDescriptionReckless:"Actions with the reckless trait run the risk of the pilot losing control of a vehicle. When performing a reckless action, the pilot must first attempt an appropriate piloting check to keep control of the vehicle.",TraitDescriptionRecovery:"Recovery weapons are thrown weapons designed to return to the thrower when they miss the target. When you make an unsuccessful thrown Strike with this weapon, it flies back to your hand after the Strike is complete, allowing you to try again. If your hands are full when the weapon returns, it falls to the ground in your space.",TraitDescriptionReflection:"A creature with this trait has the reflection versatile heritage. Reflections are beings who are copies of living people, whether through cloning, planar duplication, or another mechanism. An ability with this trait can be used or selected only by reflections.",TraitDescriptionRelic:"An item with the relic trait grows in power with its wielder.",TraitDescriptionReload:"While all weapons need some amount of time to get into position, many ranged weapons also need to be loaded and reloaded. This entry indicates how many Interact actions it takes to reload such weapons. This can be 0 if drawing ammunition and firing the weapon are part of the same action. If an item takes 2 or more actions to reload, the GM determines whether they must be performed together as an activity, or you can spend some of those actions during one turn and the rest during your next turn.",TraitDescriptionRepeating:"A repeating weapon is typically a type of crossbow that has a shorter reload time. These weapons can't be loaded with individual bolts like other crossbows; instead, they require a magazine of specialized ammunition to be loaded into a special slot. Once that magazine is in place, the ammunition is automatically loaded each time the weapon is cocked to fire, reducing its reload to the value in its reload entry (typically 0). When the ammunition runs out, a new magazine must be loaded, which requires a free hand and 3 Interact actions (to remove the old magazine, retrieve the new magazine, and slot the new magazine in place). These actions don't need to be consecutive.",TraitDescriptionResonant:"This weapon can channel energy damage. You gain the Conduct Energy free action while wielding a resonant weapon.",TraitDescriptionRevelation:"Effects with this trait see things as they truly are.",TraitDescriptionRogue:"This indicates abilities from the rogue class.",TraitDescriptionSaggorak:"Ancient dwarven blacksmiths in Saggorak designed a series of spectacularly powerful runes. Only someone with legendary proficiency in Crafting, or a well-versed dwarven crafter from the city of Kovlar, can apply, transfer, or remove a rune with the Saggorak trait. Because of their considerable power, all Saggorak runes take up two property rune slots, and consequently they can be applied only to armor and weapons with at least a +2 potency rune.",TraitDescriptionSanctified:"If you are holy or unholy, your sanctified actions and spells gain the same trait.",TraitDescriptionScatter:"This weapon fires a cluster of pellets in a wide spray. Scatter always has an area listed with it, indicating the radius of the spray. On a hit, the primary target of attacks with a scatter weapon take the listed damage, and the target and all other creatures within the listed radius around it take 1 point of splash damage per weapon damage die.",TraitDescriptionScroll:"A scroll contains a single spell you can cast without a spell slot.",TraitDescriptionScrying:"A scrying effect lets you see, hear, or otherwise get sensory information from a distance using a sensor or apparatus, rather than your own eyes and ears.",TraitDescriptionSecret:"The GM rolls the check for this ability in secret.",TraitDescriptionShadow:"This magic involves shadows or the energy of the Netherworld.",TraitDescriptionShieldThrow:"A shield with this trait is designed to be thrown as a ranged attack.",TraitDescriptionShisk:"Secretive humanoids covered in bony plumage that reside underground.",TraitDescriptionShoony:"A creature with this trait is a member of the shoony ancestry.",TraitDescriptionShove:"You can use this weapon to Shove with the Athletics skill even if you don't have a free hand. This uses the weapon's reach (if different from your own) and adds the weapon's item bonus to attack rolls as an item bonus to the Athletics check. If you critically fail a check to Shove using the weapon, you can drop the weapon to take the effects of a failure instead of a critical failure.",TraitDescriptionSkeleton:"This undead is made by animating a dead creature's skeleton with void energy. An ability with this trait can be used or selected only by skeletons.",TraitDescriptionSkill:"A general feat with the skill trait improves your skills and their actions or gives you new actions for a skill. A feat with this trait can be selected when a class grants a skill feat or general feat. Archetype feats with the skill trait can be selected in place of a skill feat if you have that archetype's dedication feat.",TraitDescriptionSleep:"This effect can cause a creature to fall asleep or get drowsy.",TraitDescriptionSnare:"Traps typically made by rangers, snares follow special rules that allow them to be constructed quickly and used on the battlefield.",TraitDescriptionSocial:"Actions and abilities with the social trait can be used only while a vigilante is in their social identity.",TraitDescriptionSonic:"An effect with the sonic trait functions only if it makes sound, meaning it has no effect in an area of silence or in a vacuum. This is different from an auditory spell, which is effective only if the target can hear it. A sonic effect might deal sonic damage.",TraitDescriptionSorcerer:"This indicates abilities from the sorcerer class.",TraitDescriptionSpellgun:"The spellgun trait appears on items that can generate a magical effect that flies out like a bullet. You can make either a spell attack roll with a spellgun or a ranged attack roll using your proficiency with simple firearms. Spellguns have a range increment, which applies regardless of which type of attack roll you make. Though you can use your modifier for simple firearms, a spellgun isn't actually a firearm. You don't get the damage of a firearm Strike, nor other benefits like critical specialization. Similarly, you can't load or reload a spellgun, affix talismans to one, make a spellgun Strike as part of an action that lets you make a firearm Strike, and so on.",TraitDescriptionSpellheart:"Spellhearts are permanent items that work similarly to talismans. You affix a spellheart using the Affix a Spellheart activity, which is otherwise identical to Affix a Talisman. The limit of one talisman per item remains\u2014an item can have one spellheart or one talisman, not both. When casting a cantrip from a spellheart, you can use your own spell attack roll or spell DC if it's higher. Crafting a spellheart requires the spells the spellheart can cast. For example, a major five-feather wreath requires air walk, gale blast, and wall of wind.",TraitDescriptionSpellshape:"Spellshape actions tweak the properties of your spells. You must use a spellshape action directly before casting the spell you want to alter. If you use any action (including free actions and reactions) other than casting a spell directly after, you waste the benefits of the spellshape action. The benefit is also lost if your turn ends before you cast the spell. Any additional effects added by a spellshape action are part of the spell's effect, not of the spellshape action itself.",TraitDescriptionSplash:"When you use a thrown weapon with the splash trait, you don't add your Strength modifier to the damage roll. If an attack with a splash weapon fails, succeeds, or critically succeeds, all creatures within 5 feet of the target (including the target) take the listed splash damage. On a failure (but not a critical failure), the target of the attack still takes the splash damage. Add splash damage together with the initial damage against the target before applying the target's weaknesses or resistances. You don't multiply splash damage on a critical hit.",TraitDescriptionSplash10:"When you use a thrown weapon with the splash trait, you don't add your Strength modifier to the damage roll. If an attack with a splash weapon fails, succeeds, or critically succeeds, all creatures within 10 feet of the target (including the target) take the listed splash damage. On a failure (but not a critical failure), the target of the attack still takes the splash damage. Add splash damage together with the initial damage against the target before applying the target's weaknesses or resistances. You don't multiply splash damage on a critical hit.",TraitDescriptionSpirit:"Effects with this trait can affect creatures with spiritual essence and might deal spirit damage. A creature with this trait is defined by its spiritual essence. Spirit creatures often lack a material form.",TraitDescriptionSprite:"A family of diminutive winged fey with a strong connection to primal magic.",TraitDescriptionStaff:"This magic item holds spells of a particular theme and allows a spellcaster to cast additional spells by preparing the staff.",TraitDescriptionStance:"A stance is a general combat strategy that you enter by using an action with the stance trait, and that you remain in for some time. A stance lasts until you get knocked out, until its requirements (if any) are violated, until the encounter ends, or until you enter a new stance, whichever comes first. After you use an action with the stance trait, you can't use another one for 1 round. You can enter or be in a stance only in encounter mode.",TraitDescriptionSteam:"Items with this trait are powered by engines that boil water to produce steam and move their components.",TraitDescriptionStrix:"Winged humanoids, most of whom live in and around Cheliax.",TraitDescriptionStructure:"An item with the structure trait creates a magical building or other structure when activated. The item must be activated on a plot of land free of other structures. The structure adapts to the natural terrain, adopting the structural requirements for being built there. The structure adjusts around small features such as ponds or spires of rock, but it can't be created on water or other nonsolid surfaces. If activated on snow, sand dunes, or other soft surfaces with a solid surface underneath, the structure's foundation (if any) reaches the solid ground. If an item with this trait is activated on a solid but unstable surface, such as a swamp or an area plagued by tremors, roll a @Check[type:flat|dc:3] each day; on a failure, the structure begins to sink or collapse. The structure doesn't harm creatures within the area when it appears, and it can't be created within a crowd or in a densely populated area. Any creature inadvertently caught inside the structure when the item is activated ends up unharmed inside the complete structure and always has a clear path of escape. A creature inside the structure when the activation ends isn't harmed, and it lands harmlessly on the ground if it was on an upper level of the structure.",TraitDescriptionSubjectiveGravity:"On planes with this trait, all bodies of mass can be centers of gravity with the same amount of force, but only if a non-mindless creature wills it.",TraitDescriptionSubtle:"A spell with the subtle trait can be cast without incantations and doesn't have obvious manifestations.",TraitDescriptionSuli:"Sulis are planar scions descended from jann.",TraitDescriptionSummon:"Spells with the summon trait can conjure creatures, typically ones with a particular trait. Such creatures can be found in Monster Core and similar books. Unless noted otherwise, the creature must be common, it gains the summoned trait, and it must appear in an unoccupied space in range large enough to contain it. The highest level of creature the spell can summon depends on the rank of the spell, as listed below. The spell can still summon a creature of a lower level if you so choose. These rules apply only to spells that have the summon trait; other spells that call or conjure items or beings but that don't have the trait, like summon instrument, work as explained in the spell.",TraitDescriptionSummoned:"A creature called by a spell or effect gains the summoned trait. A summoned creature can't summon other creatures, create things of value, or cast spells that require a cost. It has the minion trait. If it tries to Cast a Spell of equal or higher rank than the spell that summoned it, it overpowers the summoning magic, causing its own spell to fail and the summon spell to end. Otherwise, the summoned creature uses the standard abilities for a creature of its kind. It generally attacks your enemies to the best of its ability. If you can communicate with it, you can attempt to command it, but the GM determines the degree to which it follows your commands. Immediately when you finish Casting the Spell, the summoned creature uses its 2 actions for that turn. A spawn or other creature generated from a summoned creature returns to its unaltered state (usually a corpse in the case of spawn) once the summoned creature is gone. If it's unclear what this state would be, the GM decides. Summoned creatures can be banished by various spells and effects. They are automatically banished if reduced to 0 Hit Points or if the spell that called them ends.",TraitDescriptionSummoner:"This indicates abilities from the Summoner class.",TraitDescriptionSwashbuckler:"This indicates abilities from the Swashbuckler class.",TraitDescriptionSweep:"This weapon makes wide sweeping or spinning attacks, making it easier to attack multiple enemies. When you attack with this weapon, you gain a +1 circumstance bonus to your attack roll if you already attempted to attack a different target this turn using this weapon.",TraitDescriptionSylph:"A type of geniekin descended from a being from the Plane of Air.",TraitDescriptionTalisman:"A talisman is a small object affixed to armor, a shield, or a weapon (called the affixed item). You must be wielding or wearing an item to activate a talisman attached to it. Once activated, a talisman burns out permanently.",TraitDescriptionTalos:"Taloses are planar scions descended from zuhras.",TraitDescriptionTandem:"Actions with this trait involve you and your eidolon acting in concert. You can't use a tandem action if either you or your eidolon can't act, if you haven't Manifested your Eidolon, or if you've Manifested your Eidolon in a way where it isn't a separate entity (such as with the Meld into Eidolon feat). Tandem actions often let both you and your eidolon take separate actions, but these must be actions taken separately by you and your eidolon; you can't use a tandem action to take another tandem action.",TraitDescriptionTattoo:"A tattoo is a type of item that is drawn or cut into a creature's skin and usually takes the form of images or symbols.",TraitDescriptionTea:"
Magic tea is a type of potion. It activates when you drink it, which uses it up. Magic tea has the potion and tea traits. When you craft a dose of magic tea, the raw materials you supply are in the form of unusual and costly tea leaves. The process of crafting magic tea includes infusing the leaves with magical reagents, purifying the water, and steeping the tea in the water, resulting in what's essentially a particularly delicious-tasting potion. You can activate magic tea with an Interact action as you drink it or feed it to another creature, as if it were a potion. You can also activate magic tea with a 10-minute activity that requires sterling tea ware (these artisan's tools can be shared by up to four people who take this activity simultaneously) to prepare the tea and then consume it or present it to someone during a short tea ceremony, after which the magic tea's effects begin; activating magic tea in this way enhances its effect, as detailed in each entry's Tea Ceremony.
Once you drink a dose of magic tea, you're temporarily immune to that particular type of magic tea for 24 hours.
",TraitDescriptionTech:"Items with this trait are associated with the technology of Numeria.",TraitDescriptionTelepathy:"A creature with telepathy can communicate mentally with creatures. This doesn't give any special access to their thoughts, and communicates no more information than normal speech would.",TraitDescriptionTeleportation:"Teleportation effects allow you to instantaneously move from one point in space to another. Teleportation does not usually trigger reactions based on movement.",TraitDescriptionTengu:"A creature with this trait is a member of the tengu ancestry. Tengus are humanoids who resemble birds. An ability with this trait can be used or selected only by tengus. An item with this trait is created and used by tengus.",TraitDescriptionTethered:"This weapon is attached to a length of rope or chain that allows you to retrieve it after it has left your hand. If you have a free hand while wielding this weapon, you can use an Interact action to pull the weapon back into your grasp after you have thrown it as a ranged attack or after it has been disarmed (unless it is being held by another creature).",TraitDescriptionThaumaturge:"This indicates abilities from the thaumaturge class.",TraitDescriptionThrown:"You can throw this weapon as a ranged attack. A thrown weapon adds your Strength modifier to damage just like a melee weapon does. When this trait appears on a melee weapon, it also includes the range increment.",TraitDescriptionTraining:"A training weapon is designed to be used when training an animal to participate in combat by identifying the target for the animal to attack. Striking a creature with a training weapon gives your animal companion or your bonded animal a +1 circumstance bonus to its next attack roll against that target.",TraitDescriptionTrap:"A hazard or item with this trait is constructed to hinder interlopers.",TraitDescriptionTrip:"You can use this weapon to Trip with the Athletics skill even if you don't have a free hand. This uses the weapon's reach (if different from your own) and adds the weapon's item bonus to attack rolls as an item bonus to the Athletics check. If you critically fail a check to Trip using the weapon, you can drop the weapon to take the effects of a failure instead of a critical failure.",TraitDescriptionTrueName:"Certain spells, feats, and items have the true name trait. This trait means they require you to know a creature's true name to use them.",TraitDescriptionTwin:"These weapons are used as a pair, complementing each other. When you attack with a twin weapon, you add a circumstance bonus to the damage roll equal to the weapon's number of damage dice if you have previously attacked with a different weapon of the same type this turn. The weapons must be of the same type to benefit from this trait, but they don't need to have the same runes.",TraitDescriptionTwoHand:"This weapon can be wielded with two hands. Doing so changes its weapon damage die to the indicated value. This change applies to all the weapon's damage dice, such as those from striking runes.",TraitDescriptionUnarmed:"An unarmed attack uses your body rather than a manufactured weapon. An unarmed attack isn't a weapon, though it's categorized with weapons for weapon groups, and it might have weapon traits. Since it's part of your body, an unarmed attack can't be Disarmed. It also doesn't take up a hand, though a fist or other grasping appendage follows the same rules as a free-hand weapon.",TraitDescriptionUncommon:"Something of uncommon rarity requires special training or comes from a particular culture or part of the world. Some character choices give access to uncommon options, and the GM can choose to allow access for anyone. Less is known about uncommon creatures than common creatures. They typically can't be summoned. The DC of Recall Knowledge checks related to these creature is increased by 2.",TraitDescriptionUndead:"Once living, these creatures were infused after death with void energy and soul-corrupting unholy magic. When reduced to 0 Hit Points, an undead creature is destroyed. Undead creatures are damaged by vitality energy and are healed by void energy, and don't benefit from healing vitality effects.",TraitDescriptionUndine:"A type of geniekin descended from a being from the Plane of Water.",TraitDescriptionUnholy:"Effects with the unholy trait are tied to powerful magical forces of cruelty and sin. They often have stronger effects on holy creatures. Creatures with this trait are strongly devoted to unholy causes, and often have weakness to holy. If a creature with weakness to unholy uses an unholy item or effect, it takes damage from its weakness.",TraitDescriptionUnique:"A rules element with this trait is one-of-a-kind. The DC of Recall Knowledge checks related to creatures with this trait is increased by 10.",TraitDescriptionUnstable:"Unstable actions rely on experimental functions of your innovation that even you can't fully predict. After an unstable action is used on an innovation, using another one is dangerous.",TraitDescriptionVanara:"An inquisitive ancestry with primate-like features and prehensile tails.",TraitDescriptionVehicular:"A vehicular weapon is attached to a vehicle or worn by a mount and can typically only be wielded by the driver of the vehicle or the mount's primary rider. The driver or rider can control a vehicular weapon with the same hands they use to steer the vehicle or guide the mount. A vehicular weapon can be Disarmed by knocking the controls (typically reins for a mount or a steering device for a vehicle) out of the wielder's hands.",TraitDescriptionVersatile:"A versatile weapon can be used to deal a different type of damage than that listed in the Damage entry. This trait indicates the alternate damage type. For instance, a piercing weapon that is versatile S can be used to deal piercing or slashing damage. You choose the damage type each time you make an attack.",TraitDescriptionVirulent:"Afflictions with the virulent trait are harder to remove. You must succeed at two consecutive saves to reduce a virulent affliction's stage by 1. A critical success reduces a virulent affliction's stage by only 1 instead of by 2.",TraitDescriptionVishkanya:"An ancestry with snake-like features and powerful venom.",TraitDescriptionVisual:"A visual effect can affect only creatures that can see it. This applies only to visible parts of the effect, as determined by the GM.",TraitDescriptionVitality:"Effects with this trait heal living creatures with energy from the Forge of Creation, deal vitality energy damage to undead, or manipulate vitality energy.",TraitDescriptionVoid:"Effects with this trait heal undead creatures with void energy, deal void damage to living creatures, or manipulate void energy.",TraitDescriptionVolley:"This ranged weapon is less effective at close distances. Your attacks against targets that are at a distance within the range listed take a -2 penalty.",TraitDescriptionWand:"A wand contains a single spell which you can cast once per day.",TraitDescriptionWater:"Effects with the water trait either manipulate or conjure water. Those that manipulate water have no effect in an area without water. Creatures with this trait consist primarily of water or have a magical connection to the element.",TraitDescriptionWildHunt:"Creatures with the wild hunt trait are never below 14th level. They possess greater darkvision, greensight, planar acclimation, wild gaze, instinctive cooperation, weakness to cold iron, the ability to speak with plants and animals, and their own specific wild hunt link.",TraitDescriptionWitch:"This indicates abilities from the witch class.",TraitDescriptionWizard:"This indicates abilities from the wizard class.",TraitDescriptionWood:"Effects with the wood trait conjure or manipulate wood. Those that manipulate wood have no effect in an area without wood. Creatures with this trait consist primarily of wood or have a connection to magical wood.",TraitCenser:"Censer",TraitDetection:"Detection",TraitDeviant:"Deviant",TraitDevil:"Devil",TraitDhampir:"Dhampir",TraitDinosaur:"Dinosaur",TraitDisarm:"Disarm",TraitDisease:"Disease",TraitDiv:"Div",TraitDivine:"Divine",TraitDoubleBarrel:"Double Barrel",TraitDowntime:"Downtime",TraitDragon:"Dragon",TraitDream:"Dream",TraitDromaar:"Dromaar",TraitDrow:"Drow",TraitDrug:"Drug",TraitDruid:"Druid",TraitDuergar:"Duergar",TraitDuskwalker:"Duskwalker",TraitDwarf:"Dwarf",TraitEachRuneAppliedToASeparateItemThatHasPockets:"Each rune applied to a separate item that has pockets",TraitEarth:"Earth",TraitEidolon:"Eidolon",TraitElectricity:"Electricity",TraitElemental:"Elemental",TraitElf:"Elf",TraitElixir:"Elixir",TraitEmotion:"Emotion",TraitEnergy:"Energy",TraitEntrenchMelee:"Entrench Melee",TraitEntrenchRanged:"Entrench Ranged",TraitEnvironmental:"Environmental",TraitEsoterica:"Esoterica",TraitEtchedOntoABludgeoningWeapon:"Etched on Bludgeoning Weapon",TraitEtchedOntoAClanDagger:"Etched on Clan Dagger",TraitEtchedOntoAMeleeWeapon:"Etched on Melee Weapon",TraitEtchedOntoAMeleeWeaponMonk:"Etched onto a melee weapon with the monk trait",TraitEtchedOntoAPiercingOrSlashingMeleeWeapon:"Etched on Piercing/Slashing Melee Weapon",TraitEtchedOntoAPiercingOrSlashingWeapon:"Etched on Piercing/Slashing Weapon",TraitEtchedOntoAShield:"Etched onto a Shield",TraitEtchedOntoASlashingMeleeWeapon:"Etched on Slashing Melee Weapon",TraitEtchedOntoAThrownWeapon:"Etched on Thrown Weapon",TraitEtchedOntoAWeapon:"Etched onto a Weapon",TraitEtchedOntoAWeaponWOAnarchicRune:"Etched on Weapon w/o Anarchic Rune",TraitEtchedOntoAWeaponWOAxiomaticRune:"Etched on Weapon w/o Axiomatic Rune",TraitEtchedOntoAWeaponWOHolyRune:"Etched on Weapon that isn't Holy",TraitEtchedOntoAWeaponWOUnholyRune:"Etched on Weapon that isn't Unholy",TraitEtchedOntoArmor:"Etched onto Armor",TraitEtchedOntoHeavyArmor:"Etched onto Heavy Armor",TraitEtchedOntoLightArmor:"Etched onto Light Armor",TraitEtchedOntoLightMedNMArmor:"Etched on L/M Nonmetal Armor",TraitEtchedOntoMedHeavyArmor:"Etched onto Medium or Heavy Armor",TraitEtchedOntoMediumHeavyMetalArmor:"Etched onto Medium or Heavy Metal Armor",TraitEtchedOntoMetalArmor:"Etched onto Metal Armor",TraitEthereal:"Ethereal",TraitEvolution:"Evolution",TraitExpandable:"Expandable",TraitExploration:"Exploration",TraitExtradimensional:"Extradimensional",TraitFatal:"Fatal",TraitFatalAim:"Fatal Aim",TraitFatalAimD10:"Fatal Aim d10",TraitFatalAimD12:"Fatal Aim d12",TraitFatalD10:"Fatal d10",TraitFatalD12:"Fatal d12",TraitFatalD8:"Fatal d8",TraitFear:"Fear",TraitFetchling:"Fetchling",TraitFey:"Fey",TraitFiend:"Fiend",TraitFighter:"Fighter",TraitFigurehead:"Figurehead",TraitFinesse:"Finesse",TraitFinisher:"Finisher",TraitFinite:"Finite",TraitFire:"Fire",TraitFleshwarp:"Fleshwarp",TraitFlexible:"Flexible",TraitFlourish:"Flourish",TraitFocus:"Focus",TraitFocused:"Focused",TraitFoldaway:"Foldaway",TraitForce:"Force",TraitForceful:"Forceful",TraitFormian:"Formian",TraitFortune:"Fortune",TraitFreeHand:"Free-Hand",TraitFulu:"Fulu",TraitFungus:"Fungus",TraitGadget:"Gadget",TraitGanzi:"Ganzi",TraitGeneral:"General",TraitGenie:"Genie",TraitGeniekin:"Geniekin",TraitGhoran:"Ghoran",TraitGhost:"Ghost",TraitGhoul:"Ghoul",TraitGhul:"Ghul",TraitGiant:"Giant",TraitGnoll:"Gnoll",TraitGnome:"Gnome",TraitGoblin:"Goblin",TraitGolem:"Golem",TraitGoloma:"Goloma",TraitGrapple:"Grapple",TraitGremlin:"Gremlin",TraitGrimoire:"Grimoire",TraitGrioth:"Grioth",TraitGrippli:"Grippli",TraitGunslinger:"Gunslinger",TraitHag:"Hag",TraitHalcyon:"Halcyon",TraitHalfling:"Halfling",TraitHampering:"Hampering",TraitHantu:"Hantu",TraitHarnessed:"Harnessed",TraitHarrowCourt:"Harrow Court",TraitHaunt:"Haunt",TraitHealing:"Healing",TraitHefty2:"Hefty 2",TraitHeldOneHand:"Held in 1 hand",TraitHeldOneHandFreeStanding:"Held in 1 hand or free-standing",TraitHeldOneTwoHands:"Held in 1 or 2 hands",TraitHeldTwoHands:"Held in 2 hands",TraitHerald:"Herald",TraitHeritage:"Heritage",TraitHex:"Hex",TraitHindering:"Hindering",TraitHobgoblin:"Hobgoblin",TraitHoly:"Holy",TraitHryngar:"Hryngar",TraitHuman:"Human",TraitHumanoid:"Humanoid",TraitIfrit:"Ifrit",TraitIkeshti:"Ikeshti",TraitIllusion:"Illusion",TraitImpulse:"Impulse",TraitIncapacitation:"Incapacitation",TraitIncarnate:"Incarnate",TraitIncorporeal:"Incorporeal",TraitInevitable:"Inevitable",TraitInfused:"Infused",TraitInfusion:"Infusion",TraitIngested:"Ingested",TraitInhaled:"Inhaled",TraitInjection:"Injection",TraitInjury:"Injury",TraitInscribed:"Inscribed",TraitIntegrated1d6B:"Integrated 1d6 B",TraitIntegrated1d6P:"Integrated 1d6 P",TraitIntegrated1d6S:"Integrated 1d6 S",TraitIntegrated1d6SVersatileP:"Integrated 1d6 S (Versatile P)",TraitIntelligent:"Intelligent",TraitInteract:"Interact",TraitInventor:"Inventor",TraitInvested:"Invested",TraitInvestigator:"Investigator",TraitJousting:"Jousting",TraitJoustingD6:"Jousting d6",TraitKaiju:"Kaiju",TraitKami:"Kami",TraitKashrishi:"Kashrishi",TraitKickback:"Kickback",TraitKineticist:"Kineticist",TraitKingdom:"Kingdom",TraitKitsune:"Kitsune",TraitKobold:"Kobold",TraitKovintus:"Kovintus",TraitLaminar:"Laminar",TraitLaunching:"Launching",TraitLeshy:"Leshy",TraitLight:"Light",TraitLilu:"Lilu",TraitLineage:"Lineage",TraitLinguistic:"Linguistic",TraitLitany:"Litany",TraitLizardfolk:"Lizardfolk",TraitLocathah:"Locathah",TraitLozenge:"Lozenge",TraitMagic:"Magic",TraitMagical:"Magical",TraitMagus:"Magus",TraitManipulate:"Manipulate",TraitMechanical:"Mechanical",TraitMental:"Mental",TraitMerfolk:"Merfolk",TraitMetal:"Metal",TraitMindless:"Mindless",TraitMindshift:"Mindshift",TraitMinion:"Minion",TraitMisfortune:"Misfortune",TraitMisfortuneEffects:"Misfortune Effects",TraitMissive:"Missive",TraitModification:"Modification",TraitModular:"Modular B, P, or S",TraitMonitor:"Monitor",TraitMonk:"Monk",TraitMorlock:"Morlock",TraitMorph:"Morph",TraitMortic:"Mortic",TraitMounted:"Mounted",TraitMove:"Move",TraitMulticlass:"Multiclass",TraitMummy:"Mummy",TraitMunavri:"Munavri",TraitMutagen:"Mutagen",TraitMutant:"Mutant",TraitNaari:"Naari",TraitNagaji:"Nagaji",TraitNephilim:"Nephilim",TraitNindoru:"Nindoru",TraitNoisy:"Noisy",TraitNonlethal:"Nonlethal",TraitNymph:"Nymph",TraitOath:"Oath",TraitOccult:"Occult",TraitOil:"Oil",TraitOlfactory:"Olfactory",TraitOni:"Oni",TraitOoze:"Ooze",TraitOpen:"Open",TraitOracle:"Oracle",TraitOrc:"Orc",TraitOread:"Oread",TraitOverflow:"Overflow",TraitPaaridar:"Paaridar",TraitParry:"Parry",TraitPervasiveMagic:"Pervasive Magic",TraitPetitioner:"Petitioner",TraitPhantom:"Phantom",TraitPhysical:"Physical",TraitPiercing:"Piercing",TraitPlant:"Plant",TraitPoison:"Poison",TraitPolymorph:"Polymorph",TraitPonderous:"Ponderous",TraitPoppet:"Poppet",TraitPortable:"Portable",TraitPossession:"Possession",TraitPotion:"Potion",TraitPrecious:"Precious",TraitPrediction:"Prediction",TraitPress:"Press",TraitPrimal:"Primal",TraitProcessed:"Processed",TraitPropulsive:"Propulsive",TraitProtean:"Protean",TraitPsyche:"Psyche",TraitPsychic:"Psychic",TraitPsychopomp:"Psychopomp",TraitQlippoth:"Qlippoth",TraitRadiation:"Radiation",TraitRage:"Rage",TraitRakshasa:"Rakshasa",TraitRange:"Range",TraitRange10:"Range 10 feet",TraitRange100:"Range 100 feet",TraitRange110:"Range 110 feet",TraitRange120:"Range 120 feet",TraitRange130:"Range 130 feet",TraitRange140:"Range 140 feet",TraitRange15:"Range 15 feet",TraitRange150:"Range 150 feet",TraitRange160:"Range 160 feet",TraitRange170:"Range 170 feet",TraitRange180:"Range 180 feet",TraitRange190:"Range 190 feet",TraitRange20:"Range 20 feet",TraitRange200:"Range 200 feet",TraitRange210:"Range 210 feet",TraitRange220:"Range 220 feet",TraitRange230:"Range 230 feet",TraitRange240:"Range 240 feet",TraitRange25:"Range 25 feet",TraitRange250:"Range 250 feet",TraitRange260:"Range 260 feet",TraitRange270:"Range 270 feet",TraitRange280:"Range 280 feet",TraitRange290:"Range 290 feet",TraitRange30:"Range 30 feet",TraitRange300:"Range 300 feet",TraitRange310:"Range 310 feet",TraitRange320:"Range 320 feet",TraitRange40:"Range 40 feet",TraitRange5:"Range 5 feet",TraitRange50:"Range 50 feet",TraitRange500:"Range 500 feet",TraitRange60:"Range 60 feet",TraitRange70:"Range 70 feet",TraitRange80:"Range 80 feet",TraitRange90:"Range 90 feet",TraitRangeIncrement10:"Range Increment 10 feet",TraitRangeIncrement100:"Range Increment 100 feet",TraitRangeIncrement110:"Range Increment 110 feet",TraitRangeIncrement120:"Range Increment 120 feet",TraitRangeIncrement130:"Range Increment 130 feet",TraitRangeIncrement140:"Range Increment 140 feet",TraitRangeIncrement15:"Range Increment 15 feet",TraitRangeIncrement150:"Range Increment 150 feet",TraitRangeIncrement160:"Range Increment 160 feet",TraitRangeIncrement170:"Range Increment 170 feet",TraitRangeIncrement180:"Range Increment 180 feet",TraitRangeIncrement190:"Range Increment 190 feet",TraitRangeIncrement20:"Range Increment 20 feet",TraitRangeIncrement200:"Range Increment 200 feet",TraitRangeIncrement210:"Range Increment 210 feet",TraitRangeIncrement220:"Range Increment 220 feet",TraitRangeIncrement230:"Range Increment 230 feet",TraitRangeIncrement240:"Range Increment 240 feet",TraitRangeIncrement25:"Range Increment 25 feet",TraitRangeIncrement250:"Range Increment 250 feet",TraitRangeIncrement260:"Range Increment 260 feet",TraitRangeIncrement270:"Range Increment 270 feet",TraitRangeIncrement280:"Range Increment 280 feet",TraitRangeIncrement290:"Range Increment 290 feet",TraitRangeIncrement30:"Range Increment 30 feet",TraitRangeIncrement300:"Range Increment 300 feet",TraitRangeIncrement310:"Range Increment 310 feet",TraitRangeIncrement320:"Range Increment 320 feet",TraitRangeIncrement40:"Range Increment 40 feet",TraitRangeIncrement5:"Range Increment 5 feet",TraitRangeIncrement50:"Range Increment 50 feet",TraitRangeIncrement60:"Range Increment 60 feet",TraitRangeIncrement70:"Range Increment 70 feet",TraitRangeIncrement75:"Range Increment 75 feet",TraitRangeIncrement80:"Range Increment 80 feet",TraitRangeIncrement90:"Range Increment 90 feet",TraitRangedTrip:"Ranged Trip",TraitRanger:"Ranger",TraitRare:"Rare",TraitRatajin:"Ratajin",TraitRatfolk:"Ratfolk",TraitRazing:"Razing",TraitReach:"Reach",TraitReach0:"Reach 0 feet",TraitReach10:"Reach 10 feet",TraitReach100:"Reach 100 feet",TraitReach120:"Reach 120 feet",TraitReach1000:"Reach 1,000 feet",TraitReach15:"Reach 15 feet",TraitReach20:"Reach 20 feet",TraitReach200:"Reach 200 feet",TraitReach25:"Reach 25 feet",TraitReach30:"Reach 30 feet",TraitReach40:"Reach 40 feet",TraitReach50:"Reach 50 feet",TraitReach60:"Reach 60 feet",TraitReckless:"Reckless",TraitRecovery:"Recovery",TraitReflection:"Reflection",TraitRelic:"Relic",TraitReload:"Reload",TraitReload0:"Reload 0",TraitReload1:"Reload 1",TraitReload1Min:"Reload 1 min",TraitReload2:"Reload 2",TraitRepeating:"Repeating",TraitResonant:"Resonant",TraitRevelation:"Revelation",TraitRogue:"Rogue",TraitSaggorak:"Saggorak",TraitSahkil:"Sahkil",TraitSamsaran:"Samsaran",TraitSanctified:"Sanctified",TraitScatter:"Scatter",TraitScatter10:"Scatter 10",TraitScatter15:"Scatter 15",TraitScatter20:"Scatter 20",TraitScatter5:"Scatter 5",TraitScroll:"Scroll",TraitScrying:"Scrying",TraitSeaDevil:"Sea Devil",TraitSecret:"Secret",TraitSerpentfolk:"Serpentfolk",TraitSeugathi:"Seugathi",TraitSewnIntoClothing:"Sewn Into Clothing",TraitShabti:"Shabti",TraitShadow:"Shadow",TraitShieldThrow20:"Shield Throw 20 ft",TraitShieldThrow30:"Shield Throw 30 ft",TraitShisk:"Shisk",TraitShobhad:"Shobhad",TraitShoony:"Shoony",TraitShove:"Shove",TraitSiktempora:"Siktempora",TraitSkeleton:"Skeleton",TraitSkelm:"Skelm",TraitSkill:"Skill",TraitSkulk:"Skulk",TraitSlashing:"Slashing",TraitSleep:"Sleep",TraitSnare:"Snare",TraitSocial:"Social",TraitSonic:"Sonic",TraitSorcerer:"Sorcerer",TraitSoulbound:"Soulbound",TraitSpellDeflection:"Spell Deflection",TraitSpellgun:"Spellgun",TraitSpellheart:"Spellheart",TraitSpellshape:"Spellshape",TraitSpellshot:"Spellshot",TraitSpirit:"Spirit",TraitSplash:"Splash",TraitSplash10:"Splash 10 ft",TraitSporeborn:"Sporeborn",TraitSpriggan:"Spriggan",TraitSprite:"Sprite",TraitStaff:"Staff",TraitStamina:"Stamina",TraitStance:"Stance",TraitSteam:"Steam",TraitStheno:"Stheno",TraitStrix:"Strix",TraitStructure:"Structure",TraitSubjectiveGravity:"Subjective Gravity",TraitSubtle:"Subtle",TraitSuli:"Suli",TraitSummon:"Summon",TraitSummoned:"Summoned",TraitSummoner:"Summoner",TraitSwarm:"Swarm",TraitSwashbuckler:"Swashbuckler",TraitSweep:"Sweep",TraitSylph:"Sylph",TraitTalisman:"Talisman",TraitTalos:"Talos",TraitTandem:"Tandem",TraitTane:"Tane",TraitTanggal:"Tanggal",TraitTattoo:"Tattoo",TraitTattooedOnTheBody:"Tattooed on the Body",TraitTea:"Tea",TraitTech:"Tech",TraitTechnological:"Technological",TraitTelepathy:"Telepathy",TraitTeleportation:"Teleportation",TraitTengu:"Tengu",TraitTethered:"Tethered",TraitThaumaturge:"Thaumaturge",TraitThrown:"Thrown",TraitThrown10:"Thrown 10 ft.",TraitThrown100:"Thrown 100 ft.",TraitThrown15:"Thrown 15 ft.",TraitThrown20:"Thrown 20 ft.",TraitThrown200:"Thrown 200 ft.",TraitThrown30:"Thrown 30 ft.",TraitThrown40:"Thrown 40 ft.",TraitThrown60:"Thrown 60 ft.",TraitThrown80:"Thrown 80 ft.",TraitTime:"Time",TraitTitan:"Titan",TraitTouched:"Touched",TraitTraining:"Training",TraitTrap:"Trap",TraitTrip:"Trip",TraitTroll:"Troll",TraitTroop:"Troop",TraitTrueName:"True Name",TraitTwin:"Twin",TraitTwoHand:"Two-Hand",TraitTwoHandD10:"Two-Hand d10",TraitTwoHandD12:"Two-Hand d12",TraitTwoHandD6:"Two-Hand d6",TraitTwoHandD8:"Two-Hand d8",TraitUnarmed:"Unarmed",TraitUncommon:"Uncommon",TraitUndead:"Undead",TraitUndine:"Undine",TraitUnholy:"Unholy",TraitUnique:"Unique",TraitUnstable:"Unstable",TraitUntyped:"Untyped",TraitUrdefhan:"Urdefhan",TraitVampire:"Vampire",TraitVanara:"Vanara",TraitVehicular:"Vehicular",TraitVelstrac:"Velstrac",TraitVersatile:"Versatile",TraitVersatileAcid:"Versatile Acid",TraitVersatileB:"Versatile B",TraitVersatileCold:"Versatile Cold",TraitVersatileElectricity:"Versatile Electricity",TraitVersatileFire:"Versatile Fire",TraitVersatileForce:"Versatile Force",TraitVersatileP:"Versatile P",TraitVersatilePoison:"Versatile Poison",TraitVersatileS:"Versatile S",TraitVersatileSonic:"Versatile Sonic",TraitVersatileSpirit:"Versatile Spirit",TraitVersatileVitality:"Versatile Vitality",TraitVersatileVoid:"Versatile Void",TraitVersatileX:"Versatile {x}",TraitVigilante:"Vigilante",TraitVirulent:"Virulent",TraitVishkanya:"Vishkanya",TraitVisual:"Visual",TraitVitality:"Vitality",TraitVoid:"Void",TraitVolley:"Volley",TraitVolley20:"Volley 20 ft.",TraitVolley30:"Volley 30 ft.",TraitVolley50:"Volley 50 ft.",TraitVorpalFear:"Vorpal Fear",TraitWand:"Wand",TraitWater:"Water",TraitWayang:"Wayang",TraitWeapons:"Weapons",TraitWerecreature:"Werecreature",TraitWight:"Wight",TraitWildHunt:"Wild Hunt",TraitWitch:"Witch",TraitWizard:"Wizard",TraitWood:"Wood",TraitWorn:"Worn",TraitWornAmulet:"Worn Amulet",TraitWornAndAttachedToTwoWeapons:"Worn and Attached to Two Weapons",TraitWornAnklets:"Worn Anklets",TraitWornArmbands:"Worn Armbands",TraitWornBackpack:"Worn Backpack",TraitWornBarding:"Worn Barding",TraitWornBelt:"Worn Belt",TraitWornBeltPouch:"Worn Belt Pouch",TraitWornBoots:"Worn Boots",TraitWornBracelet:"Worn Bracelet",TraitWornBracers:"Worn Bracers",TraitWornCap:"Worn Cap",TraitWornCape:"Worn Cape",TraitWornCirclet:"Worn Circlet",TraitWornCloak:"Worn Cloak",TraitWornClothing:"Worn Clothing",TraitWornCollar:"Worn Collar",TraitWornCrown:"Worn Crown",TraitWornEpaulet:"Worn Epaulets",TraitWornEyeglasses:"Worn Eyeglasses",TraitWornEyepiece:"Worn Eyepiece",TraitWornFootwear:"Worn Footwear",TraitWornGarment:"Worn Garment",TraitWornGloves:"Worn Gloves",TraitWornHeadwear:"Worn Headwear",TraitWornHorseshoes:"Worn Horseshoes",TraitWornMask:"Worn Mask",TraitWornNecklace:"Worn Necklace",TraitWornOnBelt:"Worn on Belt",TraitWornOnWrists:"Worn on Wrists",TraitWornOrOneHand:"Worn or Held in One Hand",TraitWornRing:"Worn Ring",TraitWornSaddle:"Worn Saddle",TraitWornSandles:"Worn Sandles",TraitWornShoes:"Worn Shoes",TraitWornUnderArmor:"Worn Under Light Armor or Clothes",TraitWraith:"Wraith",TraitWyrwood:"Wyrwood",TraitXulgath:"Xulgath",TraitZombie:"Zombie",Traits:"Traits",TraitsLabel:"Traits",Trap:"Trap",TravelSpeed:{Days:"Days",DetectBeforeRunningIntoIt:"Notice Everything in Advance",DetectEverything:"Notice Everything",DetectionMode:"Detection Mode",DifficultTerrain:"Difficult Terrain Speed",Distance:"Distance",ExplorationActivities:{AvoidNotice:"Avoid Notice",CoverTracks:"Cover Tracks",Defend:"Defend",DetectMagic:"Detect Magic",HalfSpeed:"Other (Half Speed)",Investigate:"Investigate",None:"None (Full Speed)",RepeatASpell:"Repeat a Spell",Scout:"Scout",Search:"Search",Track:"Track"},ExplorationActivity:"Exploration Activity",ExplorationSpeed:"Exploration Speed",Feet:"Feet",FeetAcronym:"ft",GreaterDifficultTerrain:"Greater Difficult Terrain Speed",HexplorationActivities:"Hexploration Activities",Hours:"Hours",HoursPerDay:"Hours Spent Traveling Per Day",HustleMinutes:"Minutes Spent Hustling Per Day",Journey:"Journey",Label:"Travel Speed",Miles:"Miles",Name:"Name",None:"Full Speed",NormalTerrain:"Normal Terrain Speed",PartySpeed:"Party Speed",Speed:"Speed",TerrainSlowdown:"Terrain Speed",Title:"Travel Duration Calculator (Alpha)",TravelDuration:"Travel Duration",Weeks:"Weeks"},TrickMagicItemPopup:{InvalidActor:"Only a character or NPC can use Trick Magic Item.",Label:"Select a skill to use with Trick Magic Item.",Title:"Trick Magic Item"},UI:{applyDamage:{by:"by",damaged:"damaged for ",healed:"healed for ",shieldActive:"and their {shield} gets ",shieldInActive:"gets"},noDamageInfoForOutcome:"No damage information for outcome {outcome}.",shiftModifyDamageLabel:"Amount",shiftModifyDamageTitle:"Adjust Damage",shiftModifyHealingTitle:"Adjust Healing"},UUID:{Label:"UUID",SourceId:"Source ID"},UnitPriceLabel:"Unit price",UnitedPaizoWorkers:{PFSNote:'Note for Pathfinder Society players: In support of UPW, merchandise purchased from the union store will count in the Online PFS region for the Promotional Vestments boon.',ReleaseIntro:"Redmond, WA (October 14th, 2021) \u2014 Today, the workers at Paizo, Inc - publisher of the Pathfinder and Starfinder roleplaying games - are announcing their formation of the United Paizo Workers union (UPW), with the Communication Workers of America's CODE-CWA project. This union is the first of its kind in the tabletop roleplaying games industry.",Title:"Announcement: United Paizo Workers"},UnprepareItemTitle:"Unprepare Item",UpdateLabelUniversal:"Update",Usage:"Usage",UserSettings:{DarkvisionFilter:{Hint:"Add a (usually monochrome) filter when viewing a scene through the sight of a creature with darkvision",Label:"Darkvision Filter"}},ValueLabel:"Value",WeaknessesLabel:"Weaknesses",Weapon:{Base:{adze:"Adze","air-repeater":"Air Repeater",aklys:"Aklys","alchemical-bomb":"Alchemical Bomb","alchemical-crossbow":"Alchemical Crossbow","aldori-dueling-sword":"Aldori Dueling Sword",arbalest:"Arbalest",arquebus:"Arquebus","asp-coil":"Asp Coil",atlatl:"Atlatl","axe-musket":"Axe Musket","barricade-buster":"Barricade Buster","bastard-sword":"Bastard Sword","battle-axe":"Battle Axe","battle-lute":"Battle Lute","battle-saddle":"Battle Saddle","bec-de-corbin":"Bec de Corbin","big-boom-gun":"Big Boom Gun","black-powder-knuckle-dusters":"Black Powder Knuckle Dusters","bladed-diabolo":"Bladed Diabolo","bladed-gauntlet":"Bladed Gauntlet","bladed-hoop":"Bladed Hoop","bladed-scarf":"Bladed Scarf",blowgun:"Blowgun","blowgun-darts":"Blowgun Darts",blunderbuss:"Blunderbuss","bo-staff":"Bo Staff","boarding-axe":"Boarding Axe","boarding-pike":"Boarding Pike",bola:"Bola",boomerang:"Boomerang","bow-staff":"Bow Staff","breaching-pike":"Breaching Pike",broadspear:"Broadspear","butchering-axe":"Butchering Axe","butterfly-sword":"Butterfly Sword",buugeng:"Buugeng","cane-pistol":"Cane Pistol","chain-sword":"Chain Sword",chakram:"Chakram",chakri:"Chakri","clan-dagger":"Clan Dagger","clan-pistol":"Clan Pistol",claw:"Claw","claw-blade":"Claw Blade",club:"Club","coat-pistol":"Coat Pistol","combat-grapnel":"Combat Grapnel","combat-lure":"Combat Lure","composite-longbow":"Composite Longbow","composite-shortbow":"Composite Shortbow","corset-knife":"Corset Knife","crescent-cross":"Crescent Cross",crossbow:"Crossbow",dagger:"Dagger","dagger-pistol":"Dagger Pistol",daikyu:"Daikyu","dancers-spear":"Dancer's Spear",dandpatta:"Dandpatta",dart:"Dart",dogslicer:"Dogslicer",donchak:"Donchak","double-barreled-musket":"Double-Barreled Musket","double-barreled-pistol":"Double-Barreled Pistol","dragon-mouth-pistol":"Dragon Mouth Pistol","dueling-pistol":"Dueling Pistol","dueling-spear":"Dueling Spear","dwarven-dorn-dergar":"Dwarven Dorn-Dergar","dwarven-scattergun":"Dwarven Scattergun","dwarven-war-axe":"Dwarven War Axe",earthbreaker:"Earthbreaker","elven-branched-spear":"Elven Branched Spear","elven-curve-blade":"Elven Curve Blade","explosive-dogslicer":"Explosive Dogslicer","exquisite-sword-cane":"Exquisite Sword Cane","exquisite-sword-cane-sheath":"Exquisite Sword Cane Sheath",falcata:"Falcata",falchion:"Falchion",fangwire:"Fangwire",fauchard:"Fauchard","feng-huo-lun":"Feng Huo Lun","fighting-fan":"Fighting Fan","fighting-stick":"Fighting Stick","filchers-fork":"Filcher's Fork","fire-lance":"Fire Lance","fire-poi":"Fire Poi",fist:"Fist",flail:"Flail",flingflenser:"Flingflenser","flintlock-musket":"Flintlock Musket","flintlock-pistol":"Flintlock Pistol","flying-talon":"Flying Talon",flyssa:"Flyssa","forked-bipod":"Forked Bipod","frying-pan":"Frying Pan",gada:"Gada",gaff:"Gaff",gakgung:"Gakgung",gauntlet:"Gauntlet","gauntlet-bow":"Gauntlet Bow","gill-hook":"Gill Hook",glaive:"Glaive","gnome-amalgam-musket":"Gnome Amalgam Musket","gnome-flickmace":"Gnome Flickmace","gnome-hooked-hammer":"Gnome Hooked Hammer",greataxe:"Greataxe",greatclub:"Greatclub",greatpick:"Greatpick",greatsword:"Greatsword","griffon-cane":"Griffon Cane",guisarme:"Guisarme","gun-sword":"Gun Sword",halberd:"Halberd","halfling-sling-staff":"Halfling Sling Staff","hammer-gun":"Hammer Gun","hand-adze":"Hand Adze","hand-cannon":"Hand Cannon","hand-crossbow":"Hand Crossbow","harmona-gun":"Harmona Gun",harpoon:"Harpoon",hatchet:"Hatchet","heavy-crossbow":"Heavy Crossbow","hongali-hornbow":"Hongali Hornbow","hook-sword":"Hook Sword",horsechopper:"Horsechopper","injection-spear":"Injection Spear",javelin:"Javelin",jaws:"Jaws",jezail:"Jezail","jiu-huan-dao":"Jiu Huan Dao","juggling-club":"Juggling Club",kalis:"Kalis",kama:"Kama",karambit:"Karambit",katana:"Katana",katar:"Katar",khakkhara:"Khakkhara",khopesh:"Khopesh","knuckle-duster":"Knuckle Duster",kris:"Kris",kukri:"Kukri",kusarigama:"Kusarigama",lance:"Lance",lancer:"Lancer",leiomano:"Leiomano","light-hammer":"Light Hammer","light-mace":"Light Mace","light-pick":"Light Pick","lion-scythe":"Lion Scythe","long-air-repeater":"Long Air Repeater","long-hammer":"Long Hammer",longbow:"Longbow",longspear:"Longspear",longsword:"Longsword",mace:"Mace","mace-multipistol":"Mace Multipistol",machete:"Machete","main-gauche":"Main-Gauche",mambele:"Mambele",maul:"Maul","meteor-hammer":"Meteor Hammer",mikazuki:"Mikazuki","mithral-tree":"Mithral Tree","monkeys-fist":"Monkey's Fist",morningstar:"Morningstar",naginata:"Naginata",nightstick:"Nightstick","nine-ring-sword":"Nine-Ring Sword",nodachi:"Nodachi",nunchaku:"Nunchaku","ogre-hook":"Ogre Hook","orc-knuckle-dagger":"Orc Knuckle Dagger","orc-necksplitter":"Orc Necksplitter",panabas:"Panabas",pepperbox:"Pepperbox","phalanx-piercer":"Phalanx Piercer",pick:"Pick","piercing-wind":"Piercing Wind","piranha-kiss":"Piranha Kiss",poi:"Poi",polytool:"Polytool","probing-cane":"Probing Cane",ranseur:"Ranseur",rapier:"Rapier","rapier-pistol":"Rapier Pistol","reinforced-wheels":"Reinforced Wheels","repeating-crossbow":"Repeating Crossbow","repeating-hand-crossbow":"Repeating Hand Crossbow","repeating-heavy-crossbow":"Repeating Heavy Crossbow","rhoka-sword":"Rhoka Sword","rope-dart":"Rope Dart","rotary-bow":"Rotary Bow",rungu:"Rungu",sai:"Sai",sansetsukon:"Sansetsukon",sap:"Sap","sawtooth-saber":"Sawtooth Saber",scimitar:"Scimitar",scizore:"Scizore","scorpion-whip":"Scorpion Whip",scourge:"Scourge",scythe:"Scythe","shauth-lash":"Shauth Lash",shears:"Shears","shield-bash":"Shield Bash","shield-boss":"Shield Boss","shield-bow":"Shield Bow","shield-pistol":"Shield Pistol","shield-spikes":"Shield Spikes","shobhad-longrifle":"Shobhad Longrifle",shortbow:"Shortbow",shortsword:"Shortsword",shuriken:"Shuriken",sickle:"Sickle","sickle-saber":"Sickle-saber","slide-pistol":"Slide Pistol",sling:"Sling","sling-bullets":"Sling Bullets",spear:"Spear","spiked-chain":"Spiked Chain","spiked-gauntlet":"Spiked Gauntlet","spiral-rapier":"Spiral Rapier","spoon-gun":"Spoon Gun",spraysling:"Spraysling",staff:"Staff",starknife:"Starknife","stiletto-pen":"Stiletto Pen",sukgung:"Sukgung","sun-sling":"Sun Sling",switchscythe:"Switchscythe","sword-cane":"Sword Cane",talwar:"Talwar","tamchal-chakram":"Tamchal Chakram","taw-launcher":"Taw Launcher","tekko-kagi":"Tekko-kagi","temple-sword":"Temple Sword","tengu-gale-blade":"Tengu Gale Blade","thorn-whip":"Thorn whip","three-peaked-tree":"Three Peaked Tree","three-section-naginata":"Three-Section Naginata","throwing-knife":"Throwing Knife","thunder-sling":"Thunder Sling",thundermace:"Thundermace",tonfa:"Tonfa","tri-bladed-katar":"Tri-bladed Katar","tricky-pick":"Tricky Pick",trident:"Trident",triggerbrand:"Triggerbrand",urumi:"Urumi",visap:"Visap",wakizashi:"Wakizashi","war-flail":"War Flail","war-lance":"War Lance","war-razor":"War Razor",warhammer:"Warhammer","wheel-blades":"Wheel Blades","wheel-spikes":"Wheel Spikes",whip:"Whip","whip-claw":"Whip Claw","whip-staff":"Whip Staff","wish-blade":"Wish Blade","wish-knife":"Wish Knife","wooden-taws":"Wooden Taws",wrecker:"Wrecker","wrist-launcher":"Wrist Launcher",zulfikar:"Zulfikar"}},WeaponAbilityLabel:"Weapon Ability",WeaponBaseDamageTitle:"This section configures the base damage for the weapon. Additional die from Striking runes should not be added here and instead configured in the Weapon Runes section above.",WeaponBaseLabel:"Base",WeaponBonusAttackLabel:"Bonus Attack",WeaponBonusDamageLabel:"Bonus Damage",WeaponCustomDamageLabel:"Additional Custom Damage",WeaponCustomDamageTitle:"This section adds any custom damage that is not covered by the Rune system. The Strike Effect and Critical Effect attributes are not currently used in the system and are informational only.",WeaponDamageLabel:"Base Damage",WeaponGroupAxe:"Axe",WeaponGroupBomb:"Bomb",WeaponGroupBow:"Bow",WeaponGroupBrawling:"Brawling",WeaponGroupClub:"Club",WeaponGroupCrossbow:"Crossbow",WeaponGroupDart:"Dart",WeaponGroupFirearm:"Firearm",WeaponGroupFlail:"Flail",WeaponGroupHammer:"Hammer",WeaponGroupKnife:"Knife",WeaponGroupLabel:"Group",WeaponGroupPick:"Pick",WeaponGroupPolearm:"Polearm",WeaponGroupShield:"Shield",WeaponGroupSling:"Sling",WeaponGroupSpear:"Spear",WeaponGroupSword:"Sword",WeaponGroups:"Weapon Groups",WeaponHands1:"One",WeaponHands1Plus:"One Plus",WeaponHands2:"Two",WeaponMAPDefaultOption:"Default (uses Agile trait if present)",WeaponMAPLabel:"Multiple Attack Penalty",WeaponPotencyRune1:"Weapon Potency (+1)",WeaponPotencyRune2:"Weapon Potency (+2)",WeaponPotencyRune3:"Weapon Potency (+3)",WeaponPotencyRune4:"Weapon Potency (+4)",WeaponPropertyCriticalDamageLabel:"Critical Damage",WeaponPropertyCriticalEffectLabel:"Critical Effect",WeaponPropertyRune:{ancestralEchoing:{Name:"Ancestral Echoing"},anchoring:{Name:"Anchoring",Note:{criticalSuccess:"If you critically hit a target with an anchoring weapon, the weapon casts @UUID[Compendium.pf2e.spells-srd.Item.ksLCg62cLOojw3gN]{Dimensional Anchor} on the target (@Check[type:will|dc:27|name:Anchoring Rune], counteract modifier [[/r 1d20+17 # Anchoring Rune Counteract Check]]{+17})."}},ashen:{Name:"Ashen",Note:{success:"This ash clouds the senses, causing the creature to become confused for 1 round unless it succeeds at a @Check[type:will|dc:25] save."}},astral:{Name:"Astral",Note:{criticalSuccess:"On a critical hit against a creature possessing another creature, the possessing creature must succeed at a @Check[type:will|dc:26] save or be expelled and unable to possess a creature for [[/br 1d4 #rounds]]{1d4 rounds}.",Note:"The weapon can harm creatures without physical form. An astral weapon is particularly effective against incorporeal creatures, which almost always have a specific vulnerability to astral weapons. Incorporeal creatures can touch, hold, and wield astral weapons (unlike most physical objects)."}},authorized:{Name:"Authorized"},bane:{Name:"Bane"},bloodbane:{Name:"Bloodbane"},bloodthirsty:{Name:"Bloodthirsty",Note:{criticalSuccess:"When you critically hit a target that's taking @UUID[Compendium.pf2e.conditionitems.Item.lDVqvLKA6eF3Df60]{Persistent Bleed Damage}, your target becomes @UUID[Compendium.pf2e.conditionitems.Item.4D2KBtexWXa6oUMR]{Drained 1}."}},brilliant:{Name:"Brilliant",Note:{criticalSuccess:"On a critical hit, the target must succeed at a @Check[type:fortitude|dc:29|name:Brilliant Rune] save or be @UUID[Compendium.pf2e.conditionitems.Item.XgEqL1kFApUbl5Z2]{Blinded} for 1 round."}},called:{Name:"Called"},coating:{Name:"Coating"},conducting:{Name:"Conducting"},corrosive:{Name:"Corrosive",Note:{criticalSuccess:"On a critical hit, the target's armor (if any) takes [[/r 3d6[acid] #Corrosive Rune]]{3d6 acid} damage (before applying Hardness); if the target has a shield raised, the shield takes this damage instead."}},crushing:{Name:"Crushing",Note:{criticalSuccess:"When you critically hit a target with this weapon, your target becomes @UUID[Compendium.pf2e.conditionitems.Item.i3OJZU2nk64Df3xm]{Clumsy 1} and @UUID[Compendium.pf2e.conditionitems.Item.MIRkyAjyBeXivMa7]{Enfeebled 1} until the end of your next turn. @UUID[Compendium.pf2e.equipment-effects.Item.zNHvhwHsC8ckhKVp]{Effect: Crushing}"}},cunning:{Name:"Cunning"},dancing:{Name:"Dancing"},decaying:{Name:"Decaying"},deathdrinking:{Name:"Deathdrinking"},demolishing:{Name:"Demolishing"},disrupting:{Name:"Vitalizing",Note:{criticalSuccess:"On a critical hit, the undead is also @UUID[Compendium.pf2e.conditionitems.Item.MIRkyAjyBeXivMa7]{Enfeebled 1} until the end of your next turn."}},earthbinding:{Name:"Earthbinding"},energizing:{Name:"Energizing"},extending:{Name:"Extending"},fanged:{Name:"Fanged"},fearsome:{Name:"Fearsome",Note:{criticalSuccess:"When you critically hit with this weapon, the target becomes @UUID[Compendium.pf2e.conditionitems.Item.TBSHQspnbcqxsmjL]{Frightened 1}."}},flaming:{Name:"Flaming",Note:{criticalSuccess:"On a critical hit, you deal an additional [[/r 1d10[persistent,fire]]]."}},flurrying:{Name:"Flurrying"},frost:{Name:"Frost",Note:{criticalSuccess:"On a critical hit, the target is also @UUID[Compendium.pf2e.conditionitems.Item.xYTAsEpcJE1Ccni3]{Slowed 1} until the end of your next turn unless it succeeds at a @Check[type:fortitude|dc:24|name:Frost Rune] save."}},ghostTouch:{Name:"Ghost Touch",Note:"The weapon can harm creatures without physical form. A ghost touch weapon is particularly effective against incorporeal creatures, which almost always have a specific vulnerability to ghost touch weapons. Incorporeal creatures can touch, hold, and wield ghost touch weapons (unlike most physical objects)."},giantKilling:{Name:"Giant-Killing",Note:{criticalSuccess:"On a critical hit with this weapon, the giant is also @UUID[Compendium.pf2e.conditionitems.Item.MIRkyAjyBeXivMa7]{Enfeebled 1} until the end of your next turn."}},greaterAnchoring:{Name:"Greater Anchoring",Note:{criticalSuccess:"When you critically hit a target with a weapon with the anchoring rune, the weapon casts 8th-rank @UUID[Compendium.pf2e.spells-srd.Item.ksLCg62cLOojw3gN]{Dimensional Anchor} on the target (@Check[type:will|dc:38|name:Greater Anchoring Rune], counteract modifier [[/r 1d20+28 #Greater Anchoring Rune Counteract Check]]{+28}), except that if the target critically succeeds at its Will save, instead of having no effect, the dimensional anchor lasts for 1 round.",success:"When you hit a target with the weapon but don't critically hit, the target is affected by 4th-rank @UUID[Compendium.pf2e.spells-srd.Item.ksLCg62cLOojw3gN]{Dimensional Anchor} for 1 round without a save (counteract modifier [[/r 1d20+28 #Greater Anchoring Rune Counteract Check]]{+28})."}},greaterAshen:{Name:"Greater Ashen",Note:{success:"This ash clouds the senses, causing the creature to become confused for 1 round unless it succeeds at a @Check[type:will|dc:35] save. On a critical failure, the effect lasts for 1 minute."}},greaterAstral:{Name:"Greater Astral",Note:{criticalSuccess:"On a critical hit against a creature possessing another creature, the possessing creature must succeed at a @Check[type:will|dc:36] save or be expelled and unable to possess a creature for [[/br 1d4 #rounds]]{1d4 rounds}.",Note:"The weapon can harm creatures without physical form. A greater astral weapon is particularly effective against incorporeal creatures, which almost always have a specific vulnerability to greater astral weapons. Incorporeal creatures can touch, hold, and wield greater astral weapons (unlike most physical objects). The spirit damage granted by a greater astral weapon ignores any spirit resistance the target has."}},greaterBloodbane:{Name:"Greater Bloodbane"},greaterBrilliant:{Name:"Greater Brilliant",Note:{criticalSuccess:"Damage dealt by this weapon ignores the target's fire, good, or vitality resistance. On a critical hit, the target must succeed at a @Check[type:fortitude|dc:41|name:Greater Brilliant Rune] save or be @UUID[Compendium.pf2e.conditionitems.Item.XgEqL1kFApUbl5Z2]{Blinded} for 1 round.",success:"Damage dealt by this weapon ignores the target's fire, good, or vitality resistance."}},greaterCorrosive:{Name:"Greater Corrosive",Note:{criticalSuccess:"The acid damage dealt by this weapon ignores the target's acid resistance. On a critical hit, the target's armor (if any) takes [[/r 6d6[acid]]]{6d6 acid} damage (before applying Hardness); if the target has a shield raised, the shield takes this damage instead.",success:"The acid damage dealt by this weapon ignores the target's acid resistance."}},greaterCrushing:{Name:"Greater Crushing",Note:{criticalSuccess:"Your critical hits leave the target @UUID[Compendium.pf2e.conditionitems.Item.i3OJZU2nk64Df3xm]{Clumsy 2} and @UUID[Compendium.pf2e.conditionitems.Item.MIRkyAjyBeXivMa7]{Enfeebled 2} until the end of your next turn. @UUID[Compendium.pf2e.equipment-effects.Item.czdEHtLsrUcZxSDx]{Effect: Crushing (Greater)}"}},greaterDecaying:{Name:"Greater Decaying"},greaterDisrupting:{Name:"Greater Vitalizing",Note:{criticalSuccess:"On a critical hit, the undead creature is @UUID[Compendium.pf2e.conditionitems.Item.MIRkyAjyBeXivMa7]{Enfeebled 1} and @UUID[Compendium.pf2e.conditionitems.Item.e1XGnhKNSQIm5IXg]{Stupefied 1} as long as it has the persistent damage from this rune."}},greaterExtending:{Name:"Greater Extending"},greaterFanged:{Name:"Greater Fanged"},greaterFearsome:{Name:"Greater Fearsome",Note:{criticalSuccess:"When you critically hit with this weapon, the target becomes @UUID[Compendium.pf2e.conditionitems.Item.TBSHQspnbcqxsmjL]{Frightened 2}."}},greaterFlaming:{Name:"Greater Flaming",Note:{criticalSuccess:"Fire damage dealt by this weapon (including the persistent fire damage) ignores the target's fire resistance.",success:"Fire damage dealt by this weapon ignores the target's fire resistance."}},greaterFrost:{Name:"Greater Frost",Note:{criticalSuccess:"Cold damage dealt by this weapon ignores the target's cold resistance. On a critical hit, the target is also @UUID[Compendium.pf2e.conditionitems.Item.xYTAsEpcJE1Ccni3]{Slowed 1} until the end of your next turn unless it succeeds at a @Check[type:fortitude|dc:34|name:Greater Frost Rune] save.",success:"Cold damage dealt by this weapon ignores the target's cold resistance."}},greaterGiantKilling:{Name:"Greater Giant-Killing",Note:{success:"Mental damage dealt by this weapon ignores the target's mental resistance.",criticalSuccess:"On a critical hit with this weapon, the giant must attempt a @Check[type:fortitude|dc:34] with the following effects. Critical Success The giant is @UUID[Compendium.pf2e.conditionitems.Item.MIRkyAjyBeXivMa7]{Enfeebled 1} until the end of your next turn. Success The giant is @UUID[Compendium.pf2e.conditionitems.Item.MIRkyAjyBeXivMa7]{Enfeebled 2} until the end of your next turn and takes @Damage[1d10[mental]]. Failure The giant is @UUID[Compendium.pf2e.conditionitems.Item.MIRkyAjyBeXivMa7]{Enfeebled 2} for the next minute and takes @Damage[2d10[mental]]. Critical Failure The giant is @UUID[Compendium.pf2e.conditionitems.Item.MIRkyAjyBeXivMa7]{Enfeebled 4} for the next minute and takes @Damage[4d10[mental]]."}},greaterHauling:{Name:"Greater Hauling"},greaterImpactful:{Name:"Greater Impactful",Note:{criticalSuccess:"On a critical hit, you can choose to force the target to succeed at a @Check[type:fortitude|dc:37|name:Greater Impactful Rune] save or be pushed 10 feet away from you."}},greaterRooting:{Name:"Greater Rooting",Note:{criticalSuccess:`When you critically hit a target with this weapon, roots grow from the target. It's @UUID[Compendium.pf2e.conditionitems.Item.eIcWbB5o3pP6OIMe]{immobilized} for 1 round (Escape DC 28) and @UUID[Compendium.pf2e.conditionitems.Item.i3OJZU2nk64Df3xm]{Clumsy 1} for as long as the immobilization lasts.`}},greaterShock:{Name:"Greater Shock",Note:{criticalSuccess:"Electricity damage dealt by this weapon ignores the targets electricity resistance (and the other creatures' on a critical hit). On a critical hit, electricity arcs out to deal an equal amount of electricity damage to up to two other creatures of your choice within 10 feet of the target.",success:"Electricity damage dealt by this weapon ignores the target's electricity resistance."}},greaterThundering:{Name:"Greater Thundering",Note:{criticalSuccess:"Sonic damage dealt by this weapon ignores the target's sonic resistance. On a critical hit, the target has to succeed at a @Check[type:fortitude|dc:34|name:Greater Thundering Rune] save or be @UUID[Compendium.pf2e.conditionitems.Item.9PR9y0bi4JPKnHPR]{Deafened} permanently.",success:"Sonic damage dealt by this weapon ignores the target's sonic resistance."}},grievous:{Name:"Grievous",Note:{Axe:"You can damage a third creature, with the same restrictions.",Bow:"The Athletics check to pull the missile free is DC 20.",Brawling:"The target takes a -4 circumstance penalty to its save.",Club:"You can knock the target up to 15 feet away.",Dart:"The base persistent bleed damage increases to [[/r 2d6[bleed]]].",Flail:"You move the target 5 feet. You can't move it away from you, but you can move it in another direction of your choice.",Hammer:"You can also knock the target 5 feet away from you.",Knife:"The target takes a -5-foot status penalty to its Speed while it has the @UUID[Compendium.pf2e.conditionitems.Item.lDVqvLKA6eF3Df60]{Persistent Bleed Damage}.",Pick:"The extra damage from the critical specialization effect increases to 4 per weapon damage die.",Polearm:"You can move the target up to 10 feet.",Shield:"You can knock the target up to 10 feet away.",Sling:"The target also takes a -10-foot status penalty to its Speed for 1 round if it fails the save.",Spear:"The clumsy condition lasts for 2 rounds.",Sword:"The target is off-guard until the end of your next turn."}},hauling:{Name:"Hauling"},holy:{Name:"Holy",Note:{criticalSuccess:`(R command; once per day) Trigger You critically succeed at an attack roll against an evil creature with the weapon Effect You regain HP equal to double the evil creature's level. This is a good, vitality, healing effect.`}},hopeful:{Name:"Hopeful",Note:{criticalSuccess:"On a critical hit with this weapon, you inspire your comrades, pushing them to fight harder and stand for your shared convictions. Allies within 30 feet that share at least one alignment component with you gain a +1 status bonus to attack rolls until the end of your next turn."}},hooked:{Name:"Hooked",Note:{criticalSuccess:"If a hooked weapon normally has the trip trait, you can attempt to Trip a foe as a reaction when you critically hit it with the hooked weapon."}},impactful:{Name:"Impactful",Note:{criticalSuccess:"On a critical hit, you can choose to force the target to succeed at a @Check[type:fortitude|dc:27|name:Impactful Rune] save or be pushed 5 feet away from you."}},impossible:{Name:"Impossible"},keen:{Name:"Keen"},kinWarding:{Name:"Kin-Warding"},majorRooting:{Name:"Major Rooting",Note:{criticalSuccess:`When you critically hit a target with this weapon, roots grow from the target. It's @UUID[Compendium.pf2e.conditionitems.Item.eIcWbB5o3pP6OIMe]{immobilized} for 1 round (Escape DC 34) and @UUID[Compendium.pf2e.conditionitems.Item.i3OJZU2nk64Df3xm]{Clumsy 1} for as long as the immobilization lasts.`}},merciful:{Name:"Merciful"},majorFanged:{Name:"Major Fanged"},pacifying:{Name:"Pacifying"},returning:{Name:"Returning",Note:"When you make a thrown Strike with this weapon, it flies back to your hand after the Strike is complete. If your hands are full when the weapon returns, it falls to the ground in your space."},rooting:{Name:"Rooting",Note:{criticalSuccess:`When you critically hit a target with this weapon, roots grow from the target. It's @UUID[Compendium.pf2e.conditionitems.Item.eIcWbB5o3pP6OIMe]{immobilized} for 1 round (Escape DC 23) and @UUID[Compendium.pf2e.conditionitems.Item.i3OJZU2nk64Df3xm]{Clumsy 1} for as long as the immobilization lasts.`}},serrating:{Name:"Serrating"},shifting:{Name:"Shifting"},shock:{Name:"Shock",Note:{criticalSuccess:"On a critical hit, electricity arcs out to deal an equal amount of electricity damage to up to two other creatures of your choice within 10 feet of the target."}},speed:{Name:"Speed"},spellStoring:{Name:"Spell-Storing"},swarming:{Name:"Swarming"},thundering:{Name:"Thundering",Note:{criticalSuccess:"On a critical hit, the target has to succeed at a @Check[type:fortitude|dc:24|name:Thundering Rune] save or be @UUID[Compendium.pf2e.conditionitems.Item.9PR9y0bi4JPKnHPR]{Deafened} for 1 minute (or 1 hour on a critical failure)."}},trueRooting:{Name:"True Rooting",Note:{criticalSuccess:`When you critically hit a target with this weapon, roots grow from the target. It's @UUID[Compendium.pf2e.conditionitems.Item.eIcWbB5o3pP6OIMe]{immobilized} for 1 round (Escape DC 41) and @UUID[Compendium.pf2e.conditionitems.Item.i3OJZU2nk64Df3xm]{Clumsy 1} for as long as the immobilization lasts.`}},underwater:{Name:"Underwater"},unholy:{Name:"Unholy",Note:{criticalSuccess:'(R command; once per day) Trigger You critically succeed at an attack roll against a good creature with the weapon Effect The target takes @UUID[Compendium.pf2e.conditionitems.Item.lDVqvLKA6eF3Df60]{Persistent Bleed Damage} equal to 1d8 per weapon damage die of the etched weapon.'}},vorpal:{Name:"Vorpal",Note:{criticalSuccess:`(R envision (death, incapacitation)) Trigger You roll a natural 20 on a Strike with the weapon, critically succeed, and deal slashing damage. The target must have a head Effect The target must succeed at a @Check[type:fortitude|dc:37|traits:death,incapacitation|name:Vorpal Rune] save or be decapitated. This kills any creature except ones that don't require a head to live. For creatures with multiple heads, this usually kills the creature only if you sever its last head.`}},wounding:{Name:"Wounding"}},WeaponPropertyStrikeDamageLabel:"Strike Damage",WeaponPropertyStrikeEffectLabel:"Strike Effect",WeaponRange10:"10 ft.",WeaponRange100:"100 ft.",WeaponRange120:"120 ft.",WeaponRange140:"140 ft.",WeaponRange150:"150 ft.",WeaponRange180:"180 ft.",WeaponRange20:"20 ft.",WeaponRange200:"200 ft",WeaponRange240:"240 ft.",WeaponRange30:"30 ft.",WeaponRange300:"300 ft.",WeaponRange40:"40 ft.",WeaponRange50:"50 ft.",WeaponRange60:"60 ft.",WeaponRange70:"70 ft.",WeaponRange80:"80 ft.",WeaponRange90:"90 ft.",WeaponRangeMelee:"Melee",WeaponRangeN:"{range} ft.",WeaponRangeReach:"Reach",WeaponReloadLabel:"Reload Time",WeaponSpecialization:"Weapon Specialization",WeaponSplashDamageLabel:"Splash Damage",WeaponStrikeLabel:"Strike",WeaponTypeAdvanced:"Advanced Weapon",WeaponTypeMartial:"Martial Weapon",WeaponTypeSimple:"Simple Weapon",WeaponTypeSpecial:"Other Weapons",WeaponTypeUnarmed:"Unarmed Attack",Weight:"Weight",WorldClock:{AD:{Era:"AD"},AR:{Era:"AR",Months:{April:"Gozran",August:"Arodus",December:"Kuthona",February:"Calistril",January:"Abadius",July:"Erastus",June:"Sarenith",March:"Pharast",May:"Desnus",November:"Neth",October:"Lamashan",September:"Rova"},Weekdays:{Friday:"Fireday",Monday:"Moonday",Saturday:"Starday",Sunday:"Sunday",Thursday:"Oathday",Tuesday:"Toilday",Wednesday:"Wealday"}},Button:{AddOneDay:"1 Day",AddOneHour:"1 Hour",AddOneMinute:"1 Minute",AddOneRound:"1 Round",AddOneWeek:"1 Week",AddTenMinutes:"10 Minutes",Advance:"Advance",Retract:"Retract",TimeOfDay:{Advance:{Dawn:"Advance to Dawn",Dusk:"Advance to Dusk",Midnight:"Advance to Midnight",Noon:"Advance to Noon"},Retract:{Dawn:"Retract to Dawn",Dusk:"Retract to Dusk",Midnight:"Retract to Midnight",Noon:"Retract to Noon"}}},CE:{Era:"CE"},Date:"{weekday}, {day} of {month}, {year} {era}",IC:{Era:"IC"},Placeholder:"Number",Title:"World Clock"},condition:{blinded:{name:"Blinded",rules:"
You can't see. All normal terrain is difficult terrain to you. You can't detect anything using vision. You automatically critically fail Perception checks that require you to be able to see, and if vision is your only precise sense, you take a -4 status penalty to Perception checks. You are immune to visual effects. Blinded overrides dazzled.
",summary:"You're unable to see."},broken:{name:"Broken",rules:`
Broken is a condition that affects objects. An object is broken when damage has reduced its Hit Points to equal or less than its Broken Threshold. A broken object can't be used for its normal function, nor does it grant bonuses-with the exception of armor. Broken armor still grants its item bonus to AC, but it also imparts a status penalty to AC depending on its category: -1 for broken light armor, -2 for broken medium armor, or -3 for broken heavy armor.
A broken item still imposes penalties and limitations normally incurred by carrying, holding, or wearing it. For example, broken armor would still impose its Dexterity modifier cap, check penalty, and so forth.
If an effect makes an item broken automatically and the item has more HP than its Broken Threshold, that effect also reduces the item's current HP to the Broken Threshold.
`,summary:"This item can't be used for its normal function until repaired."},clumsy:{name:"Clumsy",rules:"
Your movements become clumsy and inexact. Clumsy always includes a value. You take a status penalty equal to the condition value to Dexterity-based checks and DCs, including AC, Reflex saves, ranged attack rolls, and skill checks using Acrobatics, Stealth, and Thievery.
",summary:"You can't move as easily or gracefully as usual."},concealed:{name:"Concealed",rules:`
While you are concealed from a creature, such as in a thick fog, you are difficult for that creature to see. You can still be observed, but you're tougher to target. A creature that you're concealed from must succeed at a @Check[type:flat|dc:5] when targeting you with an attack, spell, or other effect.
Area effects aren't subject to this flat check. If the check fails, the attack, spell, or effect doesn't affect you.
`,summary:"Fog or similar obscuration makes you difficult to see and target."},confused:{name:"Confused",rules:`
You don't have your wits about you, and you attack wildly. You are off-guard, you don't treat anyone as your ally (though they might still treat you as theirs), and you can't Delay, Ready, or use reactions.
You use all your actions to Strike or cast offensive cantrips, though the GM can have you use other actions to facilitate attack, such as draw a weapon, move so that a target is in reach, and so forth. Your targets are determined randomly by the GM. If you have no other viable targets, you target yourself, automatically hitting but not scoring a critical hit. If it's impossible for you to attack or cast spells, you babble incoherently, wasting your actions.
Each time you take damage from an attack or spell, you can attempt a @Check[type:flat|dc:11] to recover from your confusion and end the condition.
Someone else is making your decisions for you, usually because you're being commanded or magically dominated. The controller dictates how you act and can make you use any of your actions, including attacks, reactions, or even Delay. The controller usually does not have to spend their own actions when controlling you.
",summary:"Another creature determines your actions."},dazzled:{name:"Dazzled",rules:"
Your eyes are overstimulated. If vision is your only precise sense, all creatures and objects are concealed from you.
",summary:"Everything is concealed to you."},deafened:{name:"Deafened",rules:"
You can't hear. You automatically critically fail Perception checks that require you to be able to hear. You take a -2 status penalty to Perception checks for initiative and checks that involve sound but also rely on other senses. If you perform an action with the auditory trait, you must succeed at a @Check[type:flat|dc:5] or the action is lost; attempt the check after spending the action but before any effects are applied. You are immune to auditory effects.
",summary:"You're unable to hear."},doomed:{name:"Doomed",rules:`
Your life is ebbing away, bringing you ever closer to death. Some powerful spells and evil creatures can inflict the doomed condition on you. Doomed always includes a value. The maximum dying value at which you die is reduced by your doomed value. For example, if you were doomed 1, you would die upon reaching dying 3 instead of dying 4. If your maximum dying value is ever reduced to 0, you instantly die. When you die, you're no longer doomed.
Your doomed value decreases by 1 each time you get a full night's rest.
`,summary:"With your soul in peril, you are now closer to death."},drained:{name:"Drained",rules:`
When a creature successfully drains you of blood or life force, you become less healthy. Drained always includes a value. You take a status penalty equal to your drained value on Constitution-based checks, such as Fortitude saves. You also lose a number of Hit Points equal to your level (minimum 1) times the drained value, and your maximum Hit Points are reduced by the same amount. For example, if you're hit by an effect that inflicts drained 3 and you're a 3rd-level character, you lose 9 Hit Points and reduce your maximum Hit Points by 9. Losing these Hit Points doesn't count as taking damage.
Each time you get a full night's rest, your drained value decreases by 1. This increases your maximum Hit Points, but you don't immediately recover the lost Hit Points.
`,summary:"Blood loss or something similar has leached your vitality."},dying:{name:"Dying",rules:`
You are bleeding out or otherwise at death's door. While you have this condition, you are unconscious. Dying always includes a value, and if it ever reaches dying 4, you die. If you're dying, you must attempt a recovery check at the start of your turn each round to determine whether you get better or worse. Your dying condition increases by 1 if you take damage while dying, or by 2 if you take damage from an enemy's critical hit or a critical failure on your save.
If you lose the dying condition by succeeding at a recovery check and are still at 0 Hit Points, you remain unconscious, but you can wake up as described in that condition. You lose the dying condition automatically and wake up if you ever have 1 Hit Point or more. Any time you lose the dying condition, you gain the wounded 1 condition, or increase your wounded condition value by 1 if you already have that condition.
`,summary:"You're slipping closer to death."},encumbered:{name:"Encumbered",rules:"
You are carrying more weight than you can manage. While you're encumbered, you're clumsy 1 and take a 10-foot penalty to all your Speeds. As with all penalties to your Speed, this can't reduce your Speed below 5 feet.
",summary:"You're carrying more weight than you can manage."},enfeebled:{name:"Enfeebled",rules:"
You're physically weakened. Enfeebled always includes a value. When you are enfeebled, you take a status penalty equal to the condition value to Strength-based rolls and DCs, including Strength-based melee attack rolls, Strength-based damage rolls, and Athletics checks.
",summary:"Your strength has been sapped away."},fascinated:{name:"Fascinated",rules:"
You are compelled to focus your attention on something, distracting you from whatever else is going on around you. You take a -2 status penalty to Perception and skill checks, and you can't use actions with the concentrate trait unless they or their intended consequences are related to the subject of your fascination (as determined by the GM). For instance, you might be able to Seek and Recall Knowledge about the subject, but you likely couldn't cast a spell targeting a different creature. This condition ends if a creature uses hostile actions against you or any of your allies.
",summary:"You are compelled to focus your attention on something."},fatigued:{name:"Fatigued",rules:`
You're tired and can't summon much energy. You take a -1 status penalty to AC and saving throws. While exploring, you can't choose an exploration activity.
You recover from fatigue after a full night's rest.
`,summary:"Your defenses are lower and you can't focus while exploring."},"off-guard":{name:"Off-Guard",rules:`
You're distracted or otherwise unable to focus your full attention on defense. You take a -2 circumstance penalty to AC. Some effects give you the off-guard condition only to certain creatures or against certain attacks. Others\u2014especially conditions\u2014can make you universally off-guard against everything. If a rule doesn't specify that the condition applies only to certain circumstances, it applies to all of them; for example, many effects simply say "The target is off-guard."
`,summary:"You're unable to defend yourself to your full capability."},fleeing:{name:"Fleeing",rules:"
You're forced to run away due to fear or some other compulsion. On your turn, you must spend each of your actions trying to escape the source of the fleeing condition as expediently as possible (such as by using move actions to flee, or opening doors barring your escape). The source is usually the effect or caster that gave you the condition, though some effects might define something else as the source. You can't Delay or Ready while fleeing.
",summary:"You must run away."},friendly:{name:"Friendly",rules:"
This condition reflects a creature's disposition toward a particular character, and only supernatural effects (like a spell) can impose these conditions on player characters. A creature that is friendly to a character likes that character. The character can attempt to make a Request of a friendly creature, and the friendly creature is likely to agree to a simple and safe request that doesn't cost it much to fulfill. If the character or one of their allies uses hostile actions against the creature, the creature gains a worse attitude condition depending on the severity of the hostile action, as determined by the GM.
",summary:"An NPC with this condition has a good attitude toward you."},frightened:{name:"Frightened",rules:"
You're gripped by fear and struggle to control your nerves. The frightened condition always includes a value. You take a status penalty equal to this value to all your checks and DCs. Unless specified otherwise, at the end of each of your turns, the value of your frightened condition decreases by 1.
",summary:"Fear makes you less capable of attacking and defending."},grabbed:{name:"Grabbed",rules:"
You're held in place by another creature, giving you the off-guard and immobilized conditions. If you attempt a manipulate action while grabbed, you must succeed at a @Check[type:flat|dc:5] or it is lost; roll the check after spending the action, but before any effects are applied.
",summary:"A creature, object, or magic holds you in place."},group:{attitudes:"Attitudes",death:"Death and Dying",detection:"Degrees of Detection",senses:"Senses"},helpful:{name:"Helpful",rules:"
This condition reflects a creature's disposition toward a particular character, and only supernatural effects (like a spell) can impose these conditions on player characters. A creature that is helpful to a character wishes to actively aid that character. It will accept reasonable Requests from that character, as long as such requests aren't at the expense of the helpful creature's goals or quality of life. If the character or one of their allies uses a hostile action against the creature, the creature gains a worse attitude condition depending on the severity of the hostile action, as determined by the GM.
",summary:"An NPC with this condition wants to assist you."},hidden:{name:"Hidden",rules:`
While you're hidden from a creature, that creature knows the space you're in but can't tell precisely where you are. You typically become hidden by using Stealth to Hide. When Seeking a creature using only imprecise senses, it remains hidden, rather than observed. A creature you're hidden from is off-guard to you, and it must succeed at a @Check[type:flat|dc:11] when targeting you with an attack, spell, or other effect or it fails affect you. Area effects aren't subject to this flat check.
A creature might be able to use the Seek action to try to observe you.
`,summary:"A creature you're hidden from knows your location but can't see you."},hostile:{name:"Hostile",rules:"
This condition reflects a creature's disposition toward a particular character, and only supernatural effects (like a spell) can impose these conditions on player characters. A creature that is hostile to a character actively seeks to harm that character. It doesn't necessarily attack, but it won't accept Requests from the character.
",summary:"An NPC with this condition wants to harm you."},immobilized:{name:"Immobilized",rules:"
You can't use any action with the move trait. If you're immobilized by something holding you in place and an external force would move you out of your space, the force must succeed at a check against either the DC of the effect holding you in place or the relevant defense (usually Fortitude DC) of the monster holding you in place.
This condition reflects a creature's disposition toward a particular character, and only supernatural effects (like a spell) can impose these conditions on player characters. A creature that is indifferent to a character doesn't really care one way or the other about that character. Assume a creature's attitude to a given character is indifferent unless specified otherwise.
",summary:"An NPC with this condition doesn't have a strong opinion about you."},invisible:{name:"Invisible",rules:"
While invisible, you can't be seen. You're undetected to everyone. Creatures can Seek to attempt to detect you; if a creature succeeds at its Perception check against your Stealth DC, you become hidden to that creature until you Sneak to become undetected again. If you become invisible while someone can already see you, you start out hidden to the observer (instead of undetected) until you successfully Sneak. You can't become observed while invisible except via special abilities or magic.
",summary:"Creatures can't see you."},observed:{name:"Observed",rules:"
Anything in plain view is observed by you. If a creature takes measures to avoid detection, such as by using Stealth to Hide, it can become hidden or undetected instead of observed. If you have another precise sense instead of or in addition to sight, you might be able to observe a creature or object using that sense instead. You can observe a creature only with precise senses. When Seeking a creature using only imprecise senses, it remains hidden, rather than observed.
",summary:"You're in plain view."},paralyzed:{name:"Paralyzed",rules:"
Your body is frozen in place. You have the off-guard condition and can't act except to Recall Knowledge and use actions that require only the use of your mind (as determined by the GM). Your senses still function, but only in the areas you can perceive without moving your body, so you can't Seek while paralyzed.
",summary:"Your body is frozen in place."},"persistent-damage":{name:"Persistent Damage",rules:'
Persistent damage comes from effects like acid, being on fire, or many other situations. It appears as "X persistent [type] damage," where "X" is the amount of damage dealt and "[type]" is the damage type. Instead of taking persistent damage immediately, you take it at the end of each of your turns as long as you have the condition, rolling any damage dice anew each time. After you take persistent damage, roll a @Check[type:flat|dc:15] to see if you recover from the persistent damage. If you succeed, the condition ends.
',summary:"You keep taking damage every round."},petrified:{name:"Petrified",rules:"
You have been turned to stone. You can't act, nor can you sense anything. You become an object with a Bulk double your normal Bulk (typically 12 for a petrified Medium creature or 6 for a petrified Small creature), AC 9, Hardness 8, and the same current Hit Points you had when alive. You don't have a Broken Threshold. When you're turned back into flesh, you have the same number of Hit Points you had as a statue. If the statue is destroyed, you immediately die. While petrified, your mind and body are in stasis, so you don't age or notice the passing of time.
",summary:"You've been turned to stone."},prone:{name:"Prone",rules:`
You're lying on the ground. You are off-guard and take a -2 circumstance penalty to attack rolls. The only move actions you can use while you're prone are Crawl and Stand. Standing up ends the prone condition. You can Take Cover while prone to hunker down and gain cover against ranged attacks, even if you don't have an object to get behind, gaining a +4 circumstance bonus to AC against ranged attacks (but you remain off-guard).
If you would be knocked prone while you're Climbing or Flying, you fall. You can't be knocked prone when Swimming.
`,summary:"You're lying on the ground and are easier to attack."},quickened:{name:"Quickened",rules:"
You gain 1 additional action at the start of your turn each round. Many effects that make you quickened specify the types of actions you can use with this additional action. If you become quickened from multiple sources, you can use the extra action you've been granted for any single action allowed by any of the effects that made you quickened. Because quickened has its effect at the start of your turn, you don't immediately gain actions if you become quickened during your turn.
",summary:"You get an extra action each turn."},restrained:{name:"Restrained",rules:"
You're tied up and can barely move, or a creature has you pinned. You have the off-guard and immobilized conditions, and you can't use any actions with the attack or manipulate traits except to attempt to Escape or Force Open your bonds. Restrained overrides grabbed.
",summary:"You're tied up and can't move, or a grappling creature has you pinned."},sickened:{name:"Sickened",rules:`
You feel ill. Sickened always includes a value. You take a status penalty equal to this value on all your checks and DCs. You can't willingly ingest anything-including elixirs and potions-while sickened.
You can spend a single action retching in an attempt to recover, which lets you immediately attempt a Fortitude save against the DC of the effect that made you sickened. On a success, you reduce your sickened value by 1 (or by 2 on a critical success).
`,summary:"You're sick to your stomach."},slowed:{name:"Slowed",rules:"
You have fewer actions. Slowed always includes a value. When you regain your actions at the start of your turn, reduce the number of actions you regain by your slowed value. Because slowed has its effect at the start of your turn, you don't immediately lose actions if you become slowed during your turn.
",summary:"You lose actions each turn."},stunned:{name:"Stunned",rules:`
You've become senseless. You can't act while stunned. Stunned usually includes a value, which indicates how many total actions you lose, possibly over multiple turns, from being stunned. Each time you regain actions (such as at the start of your turn), reduce the number you regain by your stunned value, then reduce your stunned value by the number of actions you lost. For example, if you were stunned 4, you would lose all 3 of your actions on your turn, reducing you to stunned 1; on your next turn, you would lose 1 more action, and then be able to use your remaining 2 actions normally. Stunned might also have a duration instead of a value, such as "stunned for 1 minute." In this case, you lose all your actions for the listed duration.
Stunned overrides slowed. If the duration of your stunned condition ends while you are slowed, you count the actions lost to the stunned condition toward those lost to being slowed. So, if you were stunned 1 and slowed 2 at the beginning of your turn, you would lose 1 action from stunned, and then lose only 1 additional action by being slowed, so you would still have 1 action remaining to use that turn.
`,summary:"You can't use actions."},stupefied:{name:"Stupefied",rules:"
Your thoughts and instincts are clouded. Stupefied always includes a value. You take a status penalty equal to this value on Intelligence-, Wisdom-, and Charisma-based checks and DCs, including Will saving throws, spell attack rolls, spell DCs, and skill checks that use these attribute modifiers. Any time you attempt to Cast a Spell while stupefied, the spell is disrupted unless you succeed at a flat check with a DC equal to 5 + your stupefied value.
",summary:"You can't access your full mental faculties, and you have trouble casting spells."},unconscious:{name:"Unconscious",rules:`
You're sleeping, or you've been knocked out. You can't act. You take a -4 status penalty to AC, Perception, and Reflex saves, and you have the blinded and off-guard conditions. When you gain this condition, you fall prone and drop items you are wielding or holding unless the effect states otherwise or the GM determines you're in a position in which you wouldn't.
If you're unconscious because you're dying, you can't wake up while you have 0 Hit Points. If you are restored to 1 Hit Point or more via healing, you lose the dying and unconscious conditions and can act normally on your next turn.
If you are unconscious and at 0 Hit Points, but not dying, you naturally return to 1 Hit Point and awaken after sufficient time passes. The GM determines how long you remain unconscious, from a minimum of 10 minutes to several hours. If you receive healing during this time, you lose the unconscious condition and can act normally on your next turn.
If you're unconscious and have more than 1 Hit Point (typically because you are asleep or unconscious due to an effect), you wake up in one of the following ways. Each causes you to lose the unconscious condition.
You take damage, provided the damage doesn't reduce you to 0 Hit Points. If the damage reduces you to 0 Hit Points, you remain unconscious and gain the dying condition as normal.
You receive healing, other than the natural healing you get from resting.
Someone shakes you awake with an Interact action.
There's loud noise going on around you-though this isn't automatic. At the start of your turn, you automatically attempt a Perception check against the noise's DC (or the lowest DC if there is more than one noise), waking up if you succeed. If creatures are attempting to stay quiet around you, this Perception check uses their Stealth DCs. Some magical effects make you sleep so deeply that they don't allow you to attempt this Perception check.
If you are simply asleep, the GM decides you wake up either because you have had a restful night's sleep or something disrupted that rest.
`,summary:"You're asleep or knocked out."},undetected:{name:"Undetected",rules:`
When you are undetected by a creature, that creature cannot see you at all, has no idea what space you occupy, and can't target you, though you still can be affected by abilities that target an area. When you're undetected by a creature, that creature is off-guard to you.
A creature you're undetected by can guess which square you're in to try targeting you. It must pick a square and attempt an attack. This works like targeting a hidden creature (requiring a @Check[type:flat|dc:11]), but the flat check and attack roll are rolled in secret by the GM, who doesn't reveal whether the attack missed due to failing the flat check, failing the attack roll, or choosing the wrong square.
A creature can use the Seek action to try to find you.
`,summary:"A creature you're undetected by doesn't know where you are."},unfriendly:{name:"Unfriendly",rules:"
This condition reflects a creature's disposition toward a particular character, and only supernatural effects (like a spell) can impose these conditions on player characters. A creature that is unfriendly to a character dislikes and specifically distrusts that character. The unfriendly creature won't accept Requests from the character.
",summary:"An NPC with this condition doesn't like you."},unnoticed:{name:"Unnoticed",rules:"
If you are unnoticed by a creature, that creature has no idea you are present at all. When you're unnoticed, you're also undetected by the creature. This condition matters for abilities that can be used only against targets totally unaware of your presence.
",summary:"A creature is entirely unaware you're present."},wounded:{name:"Wounded",rules:`
You have been seriously injured. If you lose the dying condition and do not already have the wounded condition, you become wounded 1. If you already have the wounded condition when you lose the dying condition, your wounded condition value increases by 1. If you gain the dying condition while wounded, increase your dying condition value by your wounded value.
The wounded condition ends if someone successfully restores Hit Points to you with Treat Wounds, or if you are restored to full Hit Points and rest for 10 minutes.
`,summary:"You've been brought back from the brink of death but haven't fully recovered."}},identification:{DisplayDetails:"Display Details",Identified:"Identified",Identify:"Identify Item",IdentifyAlchemyDCs:"Identify Alchemy DCs",IdentifyGenericDCs:"Identify Generic DCs",IdentifyMagicDCs:"Identify Magic DCs",IsIdentified:"Identified?",MisidentifiedItem:"Misidentified {item}",Misidentify:"Misidentify Item",MystificationStatus:"Mystification status",Mystify:"Mystify Item",PostSkillsToChat:"Post skill checks to chat",PostSkillsToChatText:"Identify item: Skill checks",TraitGMNote:"Note: this trait is hidden from players.",Unidentified:"Unidentified",UnidentifiedDescription:"The nature of this {item} is unclear.",UnidentifiedHint:"Change the basic details seen by players when this item is unidentified.",UnidentifiedItem:"Unusual {item}",UnidentifiedType:{Amulet:"Amulet",Anklets:"Anklets",Armbands:"Armbands",Backpack:"Backpack",Belt:"Belt",Book:"Book",Bracers:"Bracers",Circlet:"Circlet",Cloak:"Cloak",Collar:"Collar",Epaulets:"Epaulets",Eyepiece:"Eyepiece",Garment:"Garment",Gloves:"Gloves",Headwear:"Headwear",Horseshoes:"Horseshoes",Liquid:"Liquid",Mask:"Mask",Necklace:"Necklace",Object:"Object",Ring:"Ring",Saddle:"Saddle",Shoes:"Shoes",Substance:"Substance",Tool:"Tool"}},loot:{BuySubtitle:"Buy item",DepositMessage:"{depositor} deposits {quantity} \xD7 {item} in {container}.",DepositSubtitle:"Deposit item",EditLootLabel:"Configure Loot?",GMSupervisionError:"A GM must be online in order to interact with {loot}.",GiveMessage:"{giver} gives {quantity} \xD7 {item} to {recipient}.",GiveSubtitle:"Give item",HiddenWhenEmpty:{Hint:"Hide this actor's token(s) when its inventory is empty.",Label:"Hidden When Empty"},InsufficientCurrencyError:"Insufficient currency for purchase by {buyer}",InsufficientFundsMessage:"{buyer} reaches for their coins but comes up short!",LootDescription:"Allows for distribution of coins across players",LootLabel:"Loot",LootMessage:"{looter} loots {quantity} \xD7 {item} off {corpse}.",LootNPCsLabel:"Loot Selected Tokens",LootNPCsPopupHeader:"Choose tokens to loot from",LootNamePlaceholder:"Loot",LootSubtitle:"Loot item",MerchantDescription:"Allows players to purchase items directly from the sheet",MerchantLabel:"Merchant",MoveLoot:"Move Items",MoveLootMessage:"How many items do you wish to move?",MoveLootPopupTitle:"Item Quantity",PartyStash:"the party stash",PermissionError:"A GM must be online in order to loot or stow an item.",PlantMessage:"{planter} plants {quantity} \xD7 {item} on {corpse}.",PlantSubtitle:"Plant Item",PurchaseLoot:"Purchase Items",PurchaseLootMessage:"How many items do you wish to purchase?",Quantity:"Quantity",SellMessage:"{seller} sells {quantity} \xD7 {item} to {buyer}.",SellSubtitle:"Sell item",SheetType:"Sheet Type",SplitCoinsLabel:"Distribute Coins",SplitCoinsPopupHeader:"Choose actors to receive a share",Stack:"Create new stack?",TakeMessage:"{taker} takes {quantity} \xD7 {item} from {container}.",TakeSubtitle:"Take item",TransferMessage:"{transferrer} moves {quantity} \xD7 {item} from {fromContainer} to {toContainer}.",TransferSubtitle:"Transfer item"},ui:{armorEquipped:"Toggle wearing your equipment",equipmentInvested:"Toggle Investment",sell:"Sell",weaponEquipped:"Toggle holding your weapon"},vehicle:{BrokenThresholdShortLabel:"BT",CrewLabel:"Crew",CurrentHPTitle:"Current Hitpoints",DescriptionHeading:"Description",HardnessLabel:"Hardness",HardnessShortLabel:"Hard.",LevelN:"Vehicle {level}",MaxHPTitle:"Maximum Hitpoints",NamePlaceholder:"Vehicle",PassengersLabel:"Passengers",PilotingCheckLabel:"Piloting Check",PropertyDescriptionCollisionDC:"The vehicle's DC for saving throws to mitigate damage.",PropertyDescriptionCollisionDamage:"The vehicle's collision damage. Unless otherwise stated, collisions deal bludgeoning damage.",PropertyDescriptionCrew:"The crew members required to operate the vehicle.",PropertyDescriptionPassengers:"The number of passengers the vehicle is typically configured to carry, if any.",PropertyDescriptionPilotingCheck:"This entry lists the skills that can be used for piloting checks while operating the vehicle. Some skills may increase the DC; these list the DC adjustment in parentheses following the skill name.",PropertyDescriptionPrice:"Vehicle's Price. This does not include creatures for pulling a vehicle, materials needed to power the vehicle, or the cost of rowers.",PropertyDescriptionSpace:"Vehicle's dimensions, not including any creatures pulling the vehicle.",PropertyDescriptionSpeed:"The vehicle's Speeds, each followed by the propulsion type for that Speed in parentheses. A pulled vehicle indicates the number and size of the pulling creatures.",SpaceHighLabel:"Height",SpaceLongLabel:"Length",SpaceWideLabel:"Width",VehicleLevelLabel:"Vehicle",VehicleString:"Vehicle",collisionDCLabel:"Collision DC",collisionDamageLabel:"Collision Damage"}},SIDEBAR:{TabCombat:"Encounter Tracker"},TYPES:{Actor:{army:"Army",character:"Player Character",eidolon:"Eidolon",familiar:"Familiar",hazard:"Hazard",loot:"Loot",npc:"NPC",party:"Party",vehicle:"Vehicle"},Item:{action:"Ability",affliction:"Affliction",ancestry:"Ancestry",armor:"Armor",background:"Background",backpack:"Container",book:"Book",campaignFeature:"Campaign Feature",class:"Class",condition:"Condition",consumable:"Consumable",deity:"Deity",effect:"Effect",equipment:"Equipment",feat:"Feat/Feature",heritage:"Heritage",kit:"Kit",lore:"Lore Skill",melee:"NPC Attack",shield:"Shield",spell:"Spell",spellcastingEntry:"Spellcasting Entry",treasure:"Treasure",weapon:"Weapon"}}};const actorTypes={army:"TYPES.Actor.army",character:"TYPES.Actor.character",familiar:"TYPES.Actor.familiar",hazard:"TYPES.Actor.hazard",loot:"TYPES.Actor.loot",npc:"TYPES.Actor.npc",party:"TYPES.Actor.party",vehicle:"TYPES.Actor.vehicle"},abilities={str:"PF2E.AbilityStr",dex:"PF2E.AbilityDex",con:"PF2E.AbilityCon",int:"PF2E.AbilityInt",wis:"PF2E.AbilityWis",cha:"PF2E.AbilityCha"},senses={darkvision:"PF2E.Actor.Creature.Sense.Type.Darkvision",echolocation:"PF2E.Actor.Creature.Sense.Type.Echolocation",greaterDarkvision:"PF2E.Actor.Creature.Sense.Type.GreaterDarkvision",heatsight:"PF2E.Actor.Creature.Sense.Type.Heatsight",lifesense:"PF2E.Actor.Creature.Sense.Type.Lifesense",lowLightVision:"PF2E.Actor.Creature.Sense.Type.LowLightVision",motionsense:"PF2E.Actor.Creature.Sense.Type.Motionsense",scent:"PF2E.Actor.Creature.Sense.Type.Scent",seeInvisibility:"PF2E.Actor.Creature.Sense.Type.SeeInvisibility",spiritsense:"PF2E.Actor.Creature.Sense.Type.Spiritsense",thoughtsense:"PF2E.Actor.Creature.Sense.Type.Thoughtsense",tremorsense:"PF2E.Actor.Creature.Sense.Type.Tremorsense",wavesense:"PF2E.Actor.Creature.Sense.Type.Wavesense"},senseAcuity={imprecise:"PF2E.Actor.Creature.Sense.Acuity.Imprecise",precise:"PF2E.Actor.Creature.Sense.Acuity.Precise",vague:"PF2E.Actor.Creature.Sense.Acuity.Vague"},tokenHUDConditions={blinded:"PF2E.ConditionTypeBlinded",broken:"PF2E.ConditionTypeBroken",clumsy:"PF2E.ConditionTypeClumsy",concealed:"PF2E.ConditionTypeConcealed",confused:"PF2E.ConditionTypeConfused",controlled:"PF2E.ConditionTypeControlled",dazzled:"PF2E.ConditionTypeDazzled",deafened:"PF2E.ConditionTypeDeafened",doomed:"PF2E.ConditionTypeDoomed",drained:"PF2E.ConditionTypeDrained",dying:"PF2E.ConditionTypeDying",encumbered:"PF2E.ConditionTypeEncumbered",enfeebled:"PF2E.ConditionTypeEnfeebled",fascinated:"PF2E.ConditionTypeFascinated",fatigued:"PF2E.ConditionTypeFatigued",fleeing:"PF2E.ConditionTypeFleeing",frightened:"PF2E.ConditionTypeFrightened",grabbed:"PF2E.ConditionTypeGrabbed",hidden:"PF2E.ConditionTypeHidden",immobilized:"PF2E.ConditionTypeImmobilized",invisible:"PF2E.ConditionTypeInvisible","off-guard":"PF2E.ConditionTypeOffGuard",paralyzed:"PF2E.ConditionTypeParalyzed","persistent-damage":"PF2E.ConditionTypePersistent",petrified:"PF2E.ConditionTypePetrified",prone:"PF2E.ConditionTypeProne",quickened:"PF2E.ConditionTypeQuickened",restrained:"PF2E.ConditionTypeRestrained",sickened:"PF2E.ConditionTypeSickened",slowed:"PF2E.ConditionTypeSlowed",stunned:"PF2E.ConditionTypeStunned",stupefied:"PF2E.ConditionTypeStupefied",unconscious:"PF2E.ConditionTypeUnconscious",undetected:"PF2E.ConditionTypeUndetected",wounded:"PF2E.ConditionTypeWounded"},conditionTypes={...tokenHUDConditions,friendly:"PF2E.ConditionTypeFriendly",helpful:"PF2E.ConditionTypeHelpful",hostile:"PF2E.ConditionTypeHostile",indifferent:"PF2E.ConditionTypeIndifferent",malevolence:"PF2E.ConditionTypeMalevolence",observed:"PF2E.ConditionTypeObserved",unfriendly:"PF2E.ConditionTypeUnfriendly",unnoticed:"PF2E.ConditionTypeUnnoticed"},weaponCategories={simple:"PF2E.WeaponTypeSimple",martial:"PF2E.WeaponTypeMartial",advanced:"PF2E.WeaponTypeAdvanced",unarmed:"PF2E.WeaponTypeUnarmed"},baseArmorTypes=mapValues$1(define_EN_JSON_default.PF2E.Item.Armor.Base,(_v,slug)=>`PF2E.Item.Armor.Base.${slug}`),baseShieldTypes=mapValues$1(define_EN_JSON_default.PF2E.Item.Shield.Base,(_v,slug)=>`PF2E.Item.Shield.Base.${slug}`),baseWeaponTypes=mapValues$1(define_EN_JSON_default.PF2E.Weapon.Base,(_v,slug)=>`PF2E.Weapon.Base.${slug}`),equivalentWeapons={"composite-longbow":"longbow","composite-shortbow":"shortbow","big-boom-gun":"hand-cannon","spoon-gun":"hand-cannon"},preciousMaterialGrades={low:"PF2E.PreciousMaterialLowGrade",standard:"PF2E.PreciousMaterialStandardGrade",high:"PF2E.PreciousMaterialHighGrade"},meleeWeaponGroups={axe:"PF2E.WeaponGroupAxe",brawling:"PF2E.WeaponGroupBrawling",club:"PF2E.WeaponGroupClub",dart:"PF2E.WeaponGroupDart",flail:"PF2E.WeaponGroupFlail",hammer:"PF2E.WeaponGroupHammer",knife:"PF2E.WeaponGroupKnife",pick:"PF2E.WeaponGroupPick",polearm:"PF2E.WeaponGroupPolearm",shield:"PF2E.WeaponGroupShield",spear:"PF2E.WeaponGroupSpear",sword:"PF2E.WeaponGroupSword"},weaponGroups={...meleeWeaponGroups,bomb:"PF2E.WeaponGroupBomb",bow:"PF2E.WeaponGroupBow",crossbow:"PF2E.WeaponGroupCrossbow",firearm:"PF2E.WeaponGroupFirearm",sling:"PF2E.WeaponGroupSling"},sizeTypes={tiny:"PF2E.ActorSizeTiny",sm:"PF2E.ActorSizeSmall",med:"PF2E.ActorSizeMedium",lg:"PF2E.ActorSizeLarge",huge:"PF2E.ActorSizeHuge",grg:"PF2E.ActorSizeGargantuan"},featCategories={ancestry:"PF2E.FeatTypeAncestry",ancestryfeature:"PF2E.FeatTypeAncestryfeature",class:"PF2E.FeatTypeClass",classfeature:"PF2E.FeatTypeClassfeature",skill:"PF2E.FeatTypeSkill",general:"PF2E.FeatTypeGeneral",bonus:"PF2E.FeatTypeBonus",pfsboon:"PF2E.FeatTypePfsboon",deityboon:"PF2E.FeatTypeDeityboon",curse:"PF2E.FeatTypeCurse"},creatureTypes=pick(creatureTraits,["aberration","animal","astral","beast","celestial","construct","dragon","dream","elemental","ethereal","fey","fiend","fungus","giant","humanoid","monitor","ooze","petitioner","plant","shadow","spirit","time","vitality","void","undead"]),consumableCategories=mapToObj(Array.from(CONSUMABLE_CATEGORIES),c=>[c,`PF2E.Item.Consumable.Category.${c}`]),deityDomains=mapToObj(Object.keys(define_EN_JSON_default.PF2E.Item.Deity.Domain),key=>{const label=`PF2E.Item.Deity.Domain.${key}.Label`,description=`PF2E.Item.Deity.Domain.${key}.Description`;return[sluggify(key),{label,description}]}),weaponReload={"-":"\u2014",0:"0",1:"1",2:"2",3:"3",10:"PF2E.Item.Weapon.Reload.OneMinute"};function notifyDeprecatedPath(configPath,locPath){foundry.utils.logCompatibilityWarning(`CONFIG.PF2E.${configPath} is deprecated. Use localization path ${locPath} directly instead.`,{since:"5.2.0",until:"6.0.0"})}__name(notifyDeprecatedPath,"notifyDeprecatedPath"),__name2(notifyDeprecatedPath,"notifyDeprecatedPath");const PF2ECONFIG={defaultPartyId:"xxxPF2ExPARTYxxx",chatDamageButtonShieldToggle:!1,statusEffects:{lastIconTheme:"default",iconDir:"systems/pf2e/icons/conditions/",conditions:tokenHUDConditions},levels:{1:"PF2E.Level1",2:"PF2E.Level2",3:"PF2E.Level3",4:"PF2E.Level4",5:"PF2E.Level5",6:"PF2E.Level6",7:"PF2E.Level7",8:"PF2E.Level8",9:"PF2E.Level9",10:"PF2E.Level10",11:"PF2E.Level11",12:"PF2E.Level12",13:"PF2E.Level13",14:"PF2E.Level14",15:"PF2E.Level15",16:"PF2E.Level16",17:"PF2E.Level17",18:"PF2E.Level18",19:"PF2E.Level19",20:"PF2E.Level20"},abilities,attributes:{get perception(){const locPath="PF2E.PerceptionLabel";return notifyDeprecatedPath("attributes.perception",locPath),locPath},get stealth(){const locPath="PF2E.StealthLabel";return notifyDeprecatedPath("attributes.stealth",locPath),locPath},get initiative(){const locPath="PF2E.InitiativeLabel";return notifyDeprecatedPath("attributes.initiative",locPath),locPath}},dcAdjustments:{"incredibly-easy":"PF2E.DCAdjustmentIncrediblyEasy","very-easy":"PF2E.DCAdjustmentVeryEasy",easy:"PF2E.DCAdjustmentEasy",normal:"PF2E.DCAdjustmentNormal",hard:"PF2E.DCAdjustmentHard","very-hard":"PF2E.DCAdjustmentVeryHard","incredibly-hard":"PF2E.DCAdjustmentIncrediblyHard"},checkDCs:configFromLocalization(define_EN_JSON_default.PF2E.Check.DC,"PF2E.Check.DC"),skills:{acr:"PF2E.SkillAcr",arc:"PF2E.SkillArc",ath:"PF2E.SkillAth",cra:"PF2E.SkillCra",dec:"PF2E.SkillDec",dip:"PF2E.SkillDip",itm:"PF2E.SkillItm",med:"PF2E.SkillMed",nat:"PF2E.SkillNat",occ:"PF2E.SkillOcc",prf:"PF2E.SkillPrf",rel:"PF2E.SkillRel",soc:"PF2E.SkillSoc",ste:"PF2E.SkillSte",sur:"PF2E.SkillSur",thi:"PF2E.SkillThi"},saves:{fortitude:"PF2E.SavesFortitude",reflex:"PF2E.SavesReflex",will:"PF2E.SavesWill"},savingThrowDefaultAttributes:{fortitude:"con",reflex:"dex",will:"wis"},currencies:{pp:"PF2E.CurrencyPP",gp:"PF2E.CurrencyGP",sp:"PF2E.CurrencySP",cp:"PF2E.CurrencyCP"},preciousMaterialGrades,preciousMaterials,accessoryPropertyRunes:{called:"PF2E.AccessoryPropertyRuneCalled",dragonsBreath:"PF2E.AccessoryPropertyRuneDragonsBreath",paired:"PF2E.AccessoryPropertyRunePaired",greaterPaired:"PF2E.AccessoryPropertyRuneGreaterPaired",majorPaired:"PF2E.AccessoryPropertyRuneMajorPaired",presentable:"PF2E.AccessoryPropertyRunePresentable",snagging:"PF2E.AccessoryPropertyRuneSnagging",softLanding:"PF2E.AccessoryPropertyRuneSoftLanding",spellBastion:"PF2E.AccessoryPropertyRuneSpellBastion",windCatcher:"PF2E.AccessoryPropertyRuneWindCatcher",greaterWindCatcher:"PF2E.AccessoryPropertyRuneGreaterWindCatcher"},damageTraits,damageTypes,damageRollFlavors,damageCategories,elementTraits,materialDamageEffects,resistanceTypes,stackGroups:{arrows:"PF2E.StackGroupArrows",blowgunDarts:"PF2E.StackGroupBlowgunDarts",bolts:"PF2E.StackGroupBolts",coins:"PF2E.StackGroupCoins",gems:"PF2E.StackGroupGems",rounds5:"PF2E.StackGroupRounds5",rounds10:"PF2E.StackGroupRounds10",slingBullets:"PF2E.StackGroupSlingBullets",sprayPellets:"PF2E.StackGroupSprayPellets",woodenTaws:"PF2E.StackGroupWoodenTaws"},weaknessTypes,weaponCategories,weaponGroups,meleeWeaponGroups,baseArmorTypes,baseShieldTypes,baseWeaponTypes,equivalentWeapons,weaponDescriptions:{club:"PF2E.WeaponDescriptionClub",knife:"PF2E.WeaponDescriptionKnife",brawling:"PF2E.WeaponDescriptionBrawling",spear:"PF2E.WeaponDescriptionSpear",sword:"PF2E.WeaponDescriptionSword",axe:"PF2E.WeaponDescriptionAxe",flail:"PF2E.WeaponDescriptionFlail",polearm:"PF2E.WeaponDescriptionPolearm",pick:"PF2E.WeaponDescriptionPick",hammer:"PF2E.WeaponDescriptionHammer",shield:"PF2E.WeaponDescriptionShield",dart:"PF2E.WeaponDescriptionDart",bow:"PF2E.WeaponDescriptionBow",sling:"PF2E.WeaponDescriptionSling",bomb:"PF2E.WeaponDescriptionBomb"},usages:{"affixed-to-a-creature":"PF2E.TraitAffixedToCreature","affixed-to-a-magical-staff":"PF2E.TraitAffixedToMagicalStaff","affixed-to-a-metal-weapon":"PF2E.TraitAffixedToAMetalWeapon","affixed-to-a-ranged-weapon":"PF2E.TraitAffixedToARangedWeapon","affixed-to-a-shield":"PF2E.TraitAffixedToAShield","affixed-to-a-shield-or-weapon":"PF2E.TraitAffixedToAShieldOrWeapon","affixed-to-a-thrown-weapon":"PF2E.TraitAffixedToThrownWeapon","affixed-to-a-two-handed-firearm-or-crossbow":"PF2E.TraitAffixedToATwoHandedFirearmOrCrossbow","affixed-to-an-innovation":"PF2E.TraitAffixedToInnovation","affixed-to-an-object-or-structure":"PF2E.TraitAffixedToObjectOrStructure","affixed-to-armor":"PF2E.TraitAffixedToArmor","affixed-to-medium-heavy-armor":"PF2E.TraitAffixedToMediumHeavyArmor","affixed-to-medium-heavy-metal-armor":"PF2E.TraitAffixedToMediumHeavyMetalArmor","affixed-to-armor-or-a-weapon":"PF2E.TraitAffixedToArmorOrAWeapon","affixed-to-armor-or-travelers-clothing":"PF2E.TraitAffixedToArmorOrTravelersClothing","affixed-to-crossbow-or-firearm":"PF2E.TraitAffixedToCrossbowOrFirearm","affixed-to-firearm":"PF2E.TraitAffixedToFirearm","affixed-to-firearm-with-a-reload-of-1":"PF2E.TraitAffixedToFirearmWithAReloadOf1","affixed-to-firearm-with-the-kickback-trait":"PF2E.TraitAffixedToFirearmWithTheKickbackTrait","affixed-to-ground-in-10-foot-radius":"PF2E.TraitAffixedToGroundIn10FtRadius","affixed-to-ground-in-20-foot-radius":"PF2E.TraitAffixedToGroundIn20FtRadius","affixed-to-harness":"PF2E.TraitAffixedToHarness","affixed-to-headgear":"PF2E.TraitAffixedToHeadgear","affixed-to-instrument":"PF2E.TraitAffixedToInstrument","affixed-to-load-bearing-wall-or-pillar":"PF2E.TraitAffixedToLoadBearingWallOrPillar","affixed-to-melee-weapon":"PF2E.TraitAffixedToMeleeWeapon","affixed-to-metal-weapon":"PF2E.TraitAffixedToMetalWeapon","affixed-to-object-structure-or-creature":"PF2E.TraitAffixedToStructureObjectOrCreature","affixed-to-the-ground":"PF2E.TraitAffixedToGround","affixed-to-unarmored-defense-item":"PF2E.TraitAffixedToUnarmoredItem","affixed-to-weapon":"PF2E.TraitAffixedToWeapon","applied-to-a-basket-bag-or-other-container":"PF2E.TraitAppliedToBasketBagOrContainer","applied-to-a-weapon":"PF2E.TraitAppliedToAWeapon","applied-to-a-wind-powered-vehicle":"PF2E.TraitAppliedToAWindPoweredVehicle","applied-to-a-non-injection-melee-weapon-piercing-damage":"PF2E.TraitAppliedToANoninjectionMeleePiercingWeapon","applied-to-any-item-of-light-or-negligible-bulk":"PF2E.TraitAppliedToAnyItemOfLightOrNegligibleBulk","applied-to-any-visible-article-of-clothing":"PF2E.TraitAppliedToAnyVisibleArticleOfClothing","applied-to-armor":"PF2E.TraitAppliedToArmor","applied-to-armor-or-unarmored-defense-clothing":"PF2E.TraitAppliedToArmorOrUnarmored","applied-to-belt-cape-cloak-or-scarf":"PF2E.TraitAppliedToBeltCapeCloakOrScarf","applied-to-boots-cape-cloak-or-umbrella":"PF2E.TraitAppliedToBootsCapeCloakOrUmbrella","applied-to-buckler-shield":"PF2E.TraitAppliedToBucklerShield","applied-to-dueling-cape-or-shield":"PF2E.TraitAppliedToDuelingCapeOrShield","applied-to-footwear":"PF2E.TraitAppliedToFootwear","applied-to-medium-heavy-armor":"PF2E.TraitAppliedToMediumHeavyArmor","applied-to-shield":"PF2E.TraitAppliedToShield","attached-to-a-thrown-weapon":"PF2E.TraitAttachedToAThrownWeapon","attached-to-crossbow-or-firearm":"PF2E.TraitAttachedToCrossbowOrFirearm","attached-to-crossbow-or-firearm-firing-mechanism":"PF2E.TraitAttachedToCrossbowOrFirearmFiringMechanism","attached-to-crossbow-or-firearm-scope":"PF2E.TraitAttachedToCrossbowOrFirearmScope","attached-to-firearm":"PF2E.TraitAttachedToFirearm","attached-to-firearm-scope":"PF2E.TraitAttachedToFirearmScope","attached-to-ships-bow":"PF2E.TraitAttachedToShipsBow",bonded:"PF2E.TraitBonded",carried:"PF2E.TraitCarried","each-rune-applied-to-a-separate-item-that-has-pockets":"PF2E.TraitEachRuneAppliedToASeparateItemThatHasPockets","etched-onto-a-weapon":"PF2E.TraitEtchedOntoAWeapon","etched-onto-a-shield":"PF2E.TraitEtchedOntoAShield","etched-onto-armor":"PF2E.TraitEtchedOntoArmor","etched-onto-heavy-armor":"PF2E.TraitEtchedOntoHeavyArmor","etched-onto-light-armor":"PF2E.TraitEtchedOntoLightArmor","etched-onto-metal-armor":"PF2E.TraitEtchedOntoMetalArmor","etched-onto-clan-dagger":"PF2E.TraitEtchedOntoAClanDagger","etched-onto-lm-nonmetal-armor":"PF2E.TraitEtchedOntoLightMedNMArmor","etched-onto-med-heavy-armor":"PF2E.TraitEtchedOntoMedHeavyArmor","etched-onto-medium-heavy-metal-armor":"PF2E.TraitEtchedOntoMediumHeavyMetalArmor","etched-onto-bludgeoning-weapon":"PF2E.TraitEtchedOntoABludgeoningWeapon","etched-onto-melee-weapon":"PF2E.TraitEtchedOntoAMeleeWeapon","etched-onto-slashing-melee-weapon":"PF2E.TraitEtchedOntoASlashingMeleeWeapon","etched-onto-piercing-or-slashing-melee-weapon":"PF2E.TraitEtchedOntoAPiercingOrSlashingMeleeWeapon","etched-onto-piercing-or-slashing-weapon":"PF2E.TraitEtchedOntoAPiercingOrSlashingWeapon","etched-onto-weapon-wo-anarchic-rune":"PF2E.TraitEtchedOntoAWeaponWOAxiomaticRune","etched-onto-weapon-wo-axiomatic-rune":"PF2E.TraitEtchedOntoAWeaponWOAnarchicRune","etched-onto-weapon-wo-unholy-rune":"PF2E.TraitEtchedOntoAWeaponWOHolyRune","etched-onto-weapon-wo-holy-rune":"PF2E.TraitEtchedOntoAWeaponWOUnholyRune","etched-onto-melee-weapon-monk":"PF2E.TraitEtchedOntoAMeleeWeaponMonk","etched-onto-thrown-weapon":"PF2E.TraitEtchedOntoAThrownWeapon","held-in-one-hand":"PF2E.TraitHeldOneHand","held-in-one-hand-or-free-standing":"PF2E.TraitHeldOneHandFreeStanding","held-in-one-or-two-hands":"PF2E.TraitHeldOneTwoHands","held-in-two-hands":"PF2E.TraitHeldTwoHands",other:"Other","sewn-into-clothing":"PF2E.TraitSewnIntoClothing","tattooed-on-the-body":"PF2E.TraitTattooedOnTheBody",touched:"PF2E.TraitTouched",worn:"PF2E.TraitWorn",wornamulet:"PF2E.TraitWornAmulet",wornanklets:"PF2E.TraitWornAnklets",wornarmbands:"PF2E.TraitWornArmbands",wornbackpack:"PF2E.TraitWornBackpack",wornbarding:"PF2E.TraitWornBarding",wornbelt:"PF2E.TraitWornBelt",wornbeltpouch:"PF2E.TraitWornBeltPouch",wornboots:"PF2E.TraitWornBoots",wornbracelet:"PF2E.TraitWornBracelet",wornbracers:"PF2E.TraitWornBracers",worncap:"PF2E.TraitWornCap",worncape:"PF2E.TraitWornCape",worncirclet:"PF2E.TraitWornCirclet",worncloak:"PF2E.TraitWornCloak",wornclothing:"PF2E.TraitWornClothing",worncollar:"PF2E.TraitWornCollar",worncrown:"PF2E.TraitWornCrown",wornepaulet:"PF2E.TraitWornEpaulet",worneyeglasses:"PF2E.TraitWornEyeglasses",worneyepiece:"PF2E.TraitWornEyepiece",wornfootwear:"PF2E.TraitWornFootwear",worngarment:"PF2E.TraitWornGarment",worngloves:"PF2E.TraitWornGloves",wornheadwear:"PF2E.TraitWornHeadwear",wornhorseshoes:"PF2E.TraitWornHorseshoes",wornmask:"PF2E.TraitWornMask",wornnecklace:"PF2E.TraitWornNecklace",wornonbelt:"PF2E.TraitWornOnBelt",wornoronehand:"PF2E.TraitWornOrOneHand",wornring:"PF2E.TraitWornRing",wornsaddle:"PF2E.TraitWornSaddle",wornsandles:"PF2E.TraitWornSandles",wornshoes:"PF2E.TraitWornShoes",wornwrist:"PF2E.TraitWornOnWrists","worn-and-attached-to-two-weapons":"PF2E.TraitWornAndAttachedToTwoWeapons","worn-under-armor":"PF2E.TraitWornUnderArmor"},rarityTraits:{common:"PF2E.TraitCommon",uncommon:"PF2E.TraitUncommon",rare:"PF2E.TraitRare",unique:"PF2E.TraitUnique"},magicTraditions,classTraits,ancestryTraits,deityDomains,weaponTraits,otherWeaponTags,armorTraits,otherArmorTags,equipmentTraits,consumableTraits,otherConsumableTags,actionTraits,shieldTraits,spellTraits,featTraits,creatureTraits,kingmakerTraits,npcAttackTraits,hazardTraits,vehicleTraits,traitsDescriptions:traitDescriptions,creatureTypes,weaponHands:{1:"PF2E.WeaponHands1","1+":"PF2E.WeaponHands1Plus",2:"PF2E.WeaponHands2"},itemBonuses:{"-2":"PF2E.ItemBonusMinus2",0:"PF2E.ItemBonus0",1:"PF2E.ItemBonus1",2:"PF2E.ItemBonus2",3:"PF2E.ItemBonus3"},damageDice:{0:"0",1:"1",2:"2",3:"3",4:"4"},damageDie:{d4:"PF2E.DamageDieD4",d6:"PF2E.DamageDieD6",d8:"PF2E.DamageDieD8",d10:"PF2E.DamageDieD10",d12:"PF2E.DamageDieD12"},weaponMAP:{1:"-1/-2",2:"-2/-4",3:"-3/-6",4:"-4/-8",5:"-5/-10"},weaponReload,armorCategories:{unarmored:"PF2E.ArmorTypeUnarmored",light:"PF2E.ArmorTypeLight",medium:"PF2E.ArmorTypeMedium",heavy:"PF2E.ArmorTypeHeavy","light-barding":"PF2E.Item.Armor.Category.light-barding","heavy-barding":"PF2E.Item.Armor.Category.heavy-barding"},armorGroups:{composite:"PF2E.ArmorGroupComposite",chain:"PF2E.ArmorGroupChain",cloth:"PF2E.ArmorGroupCloth",leather:"PF2E.ArmorGroupLeather",plate:"PF2E.ArmorGroupPlate",skeletal:"PF2E.ArmorGroupSkeletal",wood:"PF2E.ArmorGroupWood"},consumableCategories,identification:configFromLocalization(define_EN_JSON_default.PF2E.identification,"PF2E.identification"),preparationType:{prepared:"PF2E.PreparationTypePrepared",spontaneous:"PF2E.PreparationTypeSpontaneous",innate:"PF2E.PreparationTypeInnate",focus:"PF2E.TraitFocus",items:"PF2E.PreparationTypeItems",ritual:"PF2E.Item.Spell.Ritual.Label"},areaTypes:{burst:"PF2E.AreaTypeBurst",cone:"PF2E.AreaTypeCone",cube:"PF2E.AreaTypeCube",emanation:"PF2E.AreaTypeEmanation",line:"PF2E.AreaTypeLine",square:"PF2E.AreaTypeSquare"},areaSizes:{5:"PF2E.AreaSize5",10:"PF2E.AreaSize10",15:"PF2E.AreaSize15",20:"PF2E.AreaSize20",25:"PF2E.AreaSize25",30:"PF2E.AreaSize30",40:"PF2E.AreaSize40",45:"PF2E.AreaSize45",50:"PF2E.AreaSize50",60:"PF2E.AreaSize60",65:"PF2E.AreaSize65",75:"PF2E.AreaSize75",80:"PF2E.AreaSize80",90:"PF2E.AreaSize90",100:"PF2E.AreaSize100",120:"PF2E.AreaSize120",360:"PF2E.AreaSize360",500:"PF2E.AreaSize500",1e3:"PF2E.AreaSize1000",1320:"PF2E.AreaSizeQuarterMile",5280:"PF2E.AreaSize1Mile"},attitude:{hostile:"PF2E.Attitudes.Hostile",unfriendly:"PF2E.Attitudes.Unfriendly",indifferent:"PF2E.Attitudes.Indifferent",friendly:"PF2E.Attitudes.Friendly",helpful:"PF2E.Attitudes.Helpful"},skillList:{acrobatics:"PF2E.SkillAcrobatics",arcana:"PF2E.SkillArcana",athletics:"PF2E.SkillAthletics",crafting:"PF2E.SkillCrafting",deception:"PF2E.SkillDeception",diplomacy:"PF2E.SkillDiplomacy",intimidation:"PF2E.SkillIntimidation",medicine:"PF2E.SkillMedicine",nature:"PF2E.SkillNature",occultism:"PF2E.SkillOccultism",performance:"PF2E.SkillPerformance",religion:"PF2E.SkillReligion",society:"PF2E.SkillSociety",stealth:"PF2E.SkillStealth",survival:"PF2E.SkillSurvival",thievery:"PF2E.SkillThievery",lore:"PF2E.SkillLore"},spellComponents:{V:"PF2E.SpellComponentV",S:"PF2E.SpellComponentS",M:"PF2E.SpellComponentM",F:"PF2E.SpellComponentF"},featCategories,actionTypes:{action:"PF2E.ActionTypeAction",reaction:"PF2E.ActionTypeReaction",free:"PF2E.ActionTypeFree",passive:"PF2E.ActionTypePassive"},actionsNumber:{1:"PF2E.ActionNumber1",2:"PF2E.ActionNumber2",3:"PF2E.ActionNumber3"},actionCategories:{interaction:"PF2E.Item.Action.Category.Interaction",defensive:"PF2E.Item.Action.Category.Defensive",offensive:"PF2E.Item.Action.Category.Offensive",familiar:"PF2E.Item.Action.Category.Familiar"},frequencies:{turn:"PF2E.Duration.turn",round:"PF2E.Duration.round",PT1M:"PF2E.Duration.PT1M",PT10M:"PF2E.Duration.PT10M",PT1H:"PF2E.Duration.PT1H",PT24H:"PF2E.Duration.PT24H",day:"PF2E.Duration.day",P1W:"PF2E.Duration.P1W",P1M:"PF2E.Duration.P1M",P1Y:"PF2E.Duration.P1Y"},timeUnits:{rounds:"PF2E.Time.Unit.Rounds",minutes:"PF2E.Time.Unit.Minutes",hours:"PF2E.Time.Unit.Hours",days:"PF2E.Time.Unit.Days",unlimited:"PF2E.Time.Unit.Unlimited",encounter:"PF2E.Time.Unit.UntilEncounterEnds"},proficiencyLevels:["PF2E.ProficiencyLevel0","PF2E.ProficiencyLevel1","PF2E.ProficiencyLevel2","PF2E.ProficiencyLevel3","PF2E.ProficiencyLevel4"],actorSizes:sizeTypes,actorTypes,speedTypes:{swim:"PF2E.SpeedTypesSwim",climb:"PF2E.SpeedTypesClimb",fly:"PF2E.SpeedTypesFly",burrow:"PF2E.SpeedTypesBurrow"},prerequisitePlaceholders:{prerequisite1:"PF2E.Prerequisite1",prerequisite2:"PF2E.Prerequisite2",prerequisite3:"PF2E.Prerequisite3",prerequisite4:"PF2E.Prerequisite4",prerequisite5:"PF2E.Prerequisite5"},senses,senseAcuity,conditionTypes,pfsFactions:{EA:"PF2E.PFS.Factions.EA",GA:"PF2E.PFS.Factions.GA",HH:"PF2E.PFS.Factions.HH",VS:"PF2E.PFS.Factions.VS",RO:"PF2E.PFS.Factions.RO",VW:"PF2E.PFS.Factions.VW"},pfsSchools:{none:"PF2E.PFS.School.None",scrolls:"PF2E.PFS.School.Scrolls",spells:"PF2E.PFS.School.Spells",swords:"PF2E.PFS.School.Swords"},immunityTypes,languages:mapToObj(LANGUAGES,l=>[l,`PF2E.Actor.Creature.Language.${l}`]),attackEffects:{grab:"PF2E.AttackEffectGrab","improved-grab":"PF2E.AttackEffectImprovedGrab",constrict:"PF2E.AttackEffectConstrict","greater-constrict":"PF2E.AttackEffectGreaterConstrict",knockdown:"PF2E.AttackEffectKnockdown","improved-knockdown":"PF2E.AttackEffectImprovedKnockdown",push:"PF2E.AttackEffectPush","improved-push":"PF2E.AttackEffectImprovedPush",trip:"PF2E.AttackEffectTrip"},worldClock:foundry.utils.mergeObject(configFromLocalization(define_EN_JSON_default.PF2E.WorldClock,"PF2E.WorldClock"),{AR:{yearOffset:2700},IC:{yearOffset:5200},AD:{yearOffset:-95},CE:{yearOffset:0}}),hexplorationActivities:{10:.5,25:1,40:2,55:3,Infinity:4},SETTINGS:{automation:{rulesBasedVision:{name:"PF2E.SETTINGS.Automation.RulesBasedVision.Name",hint:"PF2E.SETTINGS.Automation.RulesBasedVision.Hint"},iwr:{name:"PF2E.SETTINGS.Automation.IWR.Name",hint:"PF2E.SETTINGS.Automation.IWR.Hint"},effectExpiration:{name:"PF2E.SETTINGS.Automation.EffectExpiration.Name",hint:"PF2E.SETTINGS.Automation.EffectExpiration.Hint"},removeExpiredEffects:{name:"PF2E.SETTINGS.Automation.RemoveExpiredEffects.Name",hint:"PF2E.SETTINGS.Automation.RemoveExpiredEffects.Hint"},flankingDetection:{name:"PF2E.SETTINGS.Automation.FlankingDetection.Name",hint:"PF2E.SETTINGS.Automation.FlankingDetection.Hint"},actorsDeadAtZero:{name:"PF2E.SETTINGS.Automation.ActorsDeadAtZero.Name",hint:"PF2E.SETTINGS.Automation.ActorsDeadAtZero.Hint",neither:"PF2E.SETTINGS.Automation.ActorsDeadAtZero.Neither",npcsOnly:"PF2E.SETTINGS.Automation.ActorsDeadAtZero.NPCsOnly",both:"PF2E.SETTINGS.Automation.ActorsDeadAtZero.Both"},lootableNPCs:{name:"PF2E.SETTINGS.Automation.LootableNPCs.Name",hint:"PF2E.SETTINGS.Automation.LootableNPCs.Hint"}},homebrew:{creatureTraits:{name:"PF2E.SETTINGS.Homebrew.CreatureTraits.Name",hint:"PF2E.SETTINGS.Homebrew.CreatureTraits.Hint"},featTraits:{name:"PF2E.SETTINGS.Homebrew.FeatTraits.Name",hint:"PF2E.SETTINGS.Homebrew.FeatTraits.Hint"},languages:{name:"PF2E.SETTINGS.Homebrew.Languages.Name",hint:"PF2E.SETTINGS.Homebrew.Languages.Hint"},spellTraits:{name:"PF2E.SETTINGS.Homebrew.SpellTraits.Name",hint:"PF2E.SETTINGS.Homebrew.SpellTraits.Hint"},weaponCategories:{name:"PF2E.SETTINGS.Homebrew.WeaponCategories.Name",hint:"PF2E.SETTINGS.Homebrew.WeaponCategories.Hint"},weaponGroups:{name:"PF2E.SETTINGS.Homebrew.WeaponGroups.Name",hint:"PF2E.SETTINGS.Homebrew.WeaponGroups.Hint"},baseWeapons:{name:"PF2E.SETTINGS.Homebrew.BaseWeapons.Name",hint:"PF2E.SETTINGS.Homebrew.BaseWeapons.Hint"},weaponTraits:{name:"PF2E.SETTINGS.Homebrew.WeaponTraits.Name",hint:"PF2E.SETTINGS.Homebrew.WeaponTraits.Hint"},equipmentTraits:{name:"PF2E.SETTINGS.Homebrew.EquipmentTraits.Name",hint:"PF2E.SETTINGS.Homebrew.EquipmentTraits.Hint"}},worldClock:{name:"PF2E.SETTINGS.WorldClock.Name",label:"PF2E.SETTINGS.WorldClock.Label",hint:"PF2E.SETTINGS.WorldClock.Hint",dateTheme:{name:"PF2E.SETTINGS.WorldClock.DateTheme.Name",hint:"PF2E.SETTINGS.WorldClock.DateTheme.Hint",AR:"PF2E.SETTINGS.WorldClock.DateTheme.AR",AD:"PF2E.SETTINGS.WorldClock.DateTheme.AD",CE:"PF2E.SETTINGS.WorldClock.DateTheme.CE"},timeConvention:{name:"PF2E.SETTINGS.WorldClock.TimeConvention.Name",hint:"PF2E.SETTINGS.WorldClock.TimeConvention.Hint",twentyFour:"PF2E.SETTINGS.WorldClock.TimeConvention.TwentyFour",twelve:"PF2E.SETTINGS.WorldClock.TimeConvention.Twelve"},showClockButton:{name:"PF2E.SETTINGS.WorldClock.ShowClockButton.Name",hint:"PF2E.SETTINGS.WorldClock.ShowClockButton.Hint"},playersCanView:{name:"PF2E.SETTINGS.WorldClock.PlayersCanView.Name",hint:"PF2E.SETTINGS.WorldClock.PlayersCanView.Hint"},syncDarkness:{name:"PF2E.SETTINGS.WorldClock.SyncDarkness.Name",hint:"PF2E.SETTINGS.WorldClock.SyncDarkness.Hint"},syncDarknessScene:{name:"PF2E.SETTINGS.WorldClock.SyncDarknessScene.Name",hint:"PF2E.SETTINGS.WorldClock.SyncDarknessScene.Hint",enabled:"PF2E.SETTINGS.EnabledDisabled.Enabled",default:"PF2E.SETTINGS.EnabledDisabled.Default",disabled:"PF2E.SETTINGS.EnabledDisabled.Disabled"},worldCreatedOn:{name:"PF2E.SETTINGS.WorldClock.WorldCreatedOn.Name",hint:"PF2E.SETTINGS.WorldClock.WorldCreatedOn.Hint"}},CampaignFeats:{name:"PF2E.SETTINGS.CampaignFeats.Name",hint:"PF2E.SETTINGS.CampaignFeats.Hint"}},Actor:{documentClasses:{army:ArmyPF2e,character:CharacterPF2e,npc:NPCPF2e,hazard:HazardPF2e,loot:LootPF2e,familiar:FamiliarPF2e,party:PartyPF2e,vehicle:VehiclePF2e}},Item:{documentClasses:{action:AbilityItemPF2e,affliction:AfflictionPF2e,ancestry:AncestryPF2e,armor:ArmorPF2e,background:BackgroundPF2e,backpack:ContainerPF2e,book:BookPF2e,campaignFeature:CampaignFeaturePF2e,class:ClassPF2e,condition:ConditionPF2e,consumable:ConsumablePF2e,deity:DeityPF2e,effect:EffectPF2e,equipment:EquipmentPF2e,feat:FeatPF2e,heritage:HeritagePF2e,kit:KitPF2e,lore:LorePF2e,melee:MeleePF2e,shield:ShieldPF2e,spell:SpellPF2e,spellcastingEntry:SpellcastingEntryPF2e,treasure:TreasurePF2e,weapon:WeaponPF2e},traits:{action:actionTraits,affliction:actionTraits,armor:armorTraits,ancestry:creatureTraits,background:backgroundTraits,backpack:equipmentTraits,book:equipmentTraits,campaignFeature:kingmakerTraits,consumable:consumableTraits,equipment:equipmentTraits,feat:featTraits,heritage:featTraits,kit:classTraits,melee:npcAttackTraits,shield:shieldTraits,spell:spellTraits,weapon:weaponTraits}},JournalEntry:{sheetClass:JournalSheetPF2e},Canvas:{darkness:{default:CONFIG.Canvas.darknessColor,gmVision:9473209}}};function registerHandlebarsHelpers(){Handlebars.registerHelper("pad",(value,length,character)=>`${value}`.padStart(length,character)),Handlebars.registerHelper("add",(a,b)=>Number(a)+Number(b)),Handlebars.registerHelper("nor",(...args)=>!args.slice(0,-1).some(a=>!!a)),Handlebars.registerHelper("any",(...args)=>args.slice(0,-1).some(a=>!!a)),Handlebars.registerHelper("disabled",condition=>condition?"disabled":""),Handlebars.registerHelper("coalesce",(...args)=>args.find(a=>a!=null)??null),Handlebars.registerHelper("lower",str=>String(str).toLowerCase()),Handlebars.registerHelper("capitalize",str=>String(str).capitalize()),Handlebars.registerHelper("multiply",(a,b)=>Number(a)*Number(b)),Handlebars.registerHelper("percentage",(value,max)=>Number(value)*100/Number(max)),Handlebars.registerHelper("ordinal",value=>{const numericValue=Number(value);return isNaN(numericValue)?null:ordinalString(numericValue)}),Handlebars.registerHelper("sluggify",text=>sluggify(String(text))),Handlebars.registerHelper("json",data=>JSON.stringify(data)),Handlebars.registerHelper("actionGlyph",(value,options)=>{const glyph=getActionGlyph(value??"");return glyph?`${glyph}`:options?.hash.fallback?Handlebars.escapeExpression(value):null}),Handlebars.registerHelper("times",(count,options)=>[...Array(Number(count)||0).keys()].map(i=>options.fn(i,{data:options.data,blockParams:[i]})).join("")),Handlebars.registerHelper("concat",(...params)=>params.slice(0,-1).join("")),Handlebars.registerHelper("developMode",function(options){return""}),Handlebars.registerHelper("isNumber",value=>typeof value=="number"),Handlebars.registerHelper("isNullish",value=>value==null),Handlebars.registerHelper("signedInteger",(value,options)=>{const number=Number(value)||0,emptyStringZero=!!options.hash.emptyStringZero,zeroIsNegative=!!options.hash.zeroIsNegative;return signedInteger(number,{emptyStringZero,zeroIsNegative})}),Handlebars.registerHelper("coinLabel",value=>value?"value"in value?new CoinsPF2e(value.value):new CoinsPF2e(value):null),Handlebars.registerHelper("includes",(arr,element)=>Array.isArray(arr)?arr.includes(element):arr instanceof Set?arr.has(element):arr&&typeof arr=="object"?(typeof element=="number"||typeof element=="string")&&element in arr:!1),Handlebars.registerHelper("raw",function(options){return options.fn(this)})}__name(registerHandlebarsHelpers,"registerHandlebarsHelpers"),__name2(registerHandlebarsHelpers,"registerHandlebarsHelpers");function registerFonts(){CONFIG.fontDefinitions.Eczar={editor:!0,fonts:[{urls:["systems/pf2e/fonts/eczar-v16-latin-ext_latin-regular.woff2"],style:"normal",weight:"400"},{urls:["systems/pf2e/fonts/eczar-v16-latin-ext_latin-500.woff2"],style:"normal",weight:"500"},{urls:["systems/pf2e/fonts/eczar-v16-latin-ext_latin-600.woff2"],style:"normal",weight:"600"},{urls:["systems/pf2e/fonts/eczar-v16-latin-ext_latin-700.woff2"],style:"normal",weight:"700"},{urls:["systems/pf2e/fonts/eczar-v16-latin-ext_latin-800.woff2"],style:"normal",weight:"800"}]},CONFIG.fontDefinitions.Gelasio={editor:!1,fonts:[{urls:["systems/pf2e/fonts/gelasio-v9-latin-ext_latin-regular.woff2"],style:"normal",weight:"400"},{urls:["systems/pf2e/fonts/gelasio-v9-latin-ext_latin-italic.woff2"],style:"italic",weight:"400"},{urls:["systems/pf2e/fonts/gelasio-v9-latin-ext_latin-500.woff2"],style:"normal",weight:"500"},{urls:["systems/pf2e/fonts/gelasio-v9-latin-ext_latin-500italic.woff2"],style:"italic",weight:"500"},{urls:["systems/pf2e/fonts/gelasio-v9-latin-ext_latin-600.woff2"],style:"normal",weight:"600"},{urls:["systems/pf2e/fonts/gelasio-v9-latin-ext_latin-600italic.woff2"],style:"italic",weight:"600"},{urls:["systems/pf2e/fonts/gelasio-v9-latin-ext_latin-700.woff2"],style:"normal",weight:"700"},{urls:["systems/pf2e/fonts/gelasio-v9-latin-ext_latin-700italic.woff2"],style:"italic",weight:"700"}]},CONFIG.fontDefinitions["La Belle Aurore"]={editor:!0,fonts:[{urls:["systems/pf2e/fonts/la-belle-aurore-v16-latin-regular.woff2"],style:"normal",weight:"400"}]},CONFIG.fontDefinitions.Pathfinder2eActions={editor:!1,fonts:[{urls:["systems/pf2e/fonts/pathfinder-2e-actions.woff2"]}]},CONFIG.fontDefinitions.Roboto={editor:!0,fonts:[{urls:["systems/pf2e/fonts/roboto-v30-latin-ext_latin_cyrillic-regular.woff2"],style:"normal",weight:"400"},{urls:["systems/pf2e/fonts/roboto-v30-latin-ext_latin_cyrillic-italic.woff2"],style:"italic",weight:"400"},{urls:["systems/pf2e/fonts/roboto-v30-latin-ext_latin_cyrillic-500.woff2"],style:"normal",weight:"500"},{urls:["systems/pf2e/fonts/roboto-v30-latin-ext_latin_cyrillic-500italic.woff2"],style:"italic",weight:"500"},{urls:["systems/pf2e/fonts/roboto-v30-latin-ext_latin_cyrillic-700.woff2"],style:"normal",weight:"700"},{urls:["systems/pf2e/fonts/roboto-v30-latin-ext_latin_cyrillic-700italic.woff2"],style:"italic",weight:"700"},{urls:["systems/pf2e/fonts/roboto-v30-latin-ext_latin_cyrillic-900.woff2"],style:"normal",weight:"900"},{urls:["systems/pf2e/fonts/roboto-v30-latin-ext_latin_cyrillic-900italic.woff2"],style:"italic",weight:"900"}]},CONFIG.fontDefinitions["Roboto Condensed"]={editor:!1,fonts:[{urls:["systems/pf2e/fonts/roboto-condensed-v24-latin-ext_latin_cyrillic-regular.woff2"],style:"normal",weight:"400"},{urls:["systems/pf2e/fonts/roboto-condensed-v24-latin-ext_latin_cyrillic-italic.woff2"],style:"italic",weight:"400"},{urls:["systems/pf2e/fonts/roboto-condensed-v24-latin-ext_latin_cyrillic-700.woff2"],style:"normal",weight:"700"},{urls:["systems/pf2e/fonts/roboto-condensed-v24-latin-ext_latin_cyrillic-700italic.woff2"],style:"italic",weight:"700"}]},CONFIG.fontDefinitions["Roboto Mono"]={editor:!1,fonts:[{urls:["systems/pf2e/fonts/roboto-mono-v21-latin-ext_latin_cyrillic-regular.woff2"],style:"normal",weight:"400"},{urls:["systems/pf2e/fonts/roboto-mono-v21-latin-ext_latin_cyrillic-500.woff2"],style:"normal",weight:"500"},{urls:["systems/pf2e/fonts/roboto-mono-v21-latin-ext_latin_cyrillic-700.woff2"],style:"italic",weight:"700"}]},CONFIG.fontDefinitions.Signika={editor:!0,fonts:[{urls:["systems/pf2e/fonts/signika-v19-latin-ext_latin-regular.woff2"],style:"normal",weight:"400"},{urls:["systems/pf2e/fonts/signika-v19-latin-ext_latin-500.woff2"],style:"normal",weight:"500"},{urls:["systems/pf2e/fonts/signika-v19-latin-ext_latin-600.woff2"],style:"normal",weight:"600"},{urls:["systems/pf2e/fonts/signika-v19-latin-ext_latin-700.woff2"],style:"normal",weight:"700"}]},CONFIG.fontDefinitions.Vollkorn={editor:!0,fonts:[{urls:["systems/pf2e/fonts/vollkorn-v20-latin-ext_latin_cyrillic-regular.woff2"],style:"normal",weight:"400"},{urls:["systems/pf2e/fonts/vollkorn-v20-latin-ext_latin_cyrillic-500.woff2"],style:"normal",weight:"500"},{urls:["systems/pf2e/fonts/vollkorn-v20-latin-ext_latin_cyrillic-700.woff2"],style:"normal",weight:"600"},{urls:["systems/pf2e/fonts/vollkorn-v20-latin-ext_latin_cyrillic-900.woff2"],style:"normal",weight:"700"}]},delete CONFIG.fontDefinitions.Courier,delete CONFIG.fontDefinitions.Times,CONFIG._fontFamilies=[]}__name(registerFonts,"registerFonts"),__name2(registerFonts,"registerFonts");function registerKeybindings(){game.keybindings.register("pf2e","cycle-token-stack",{name:"PF2E.Keybinding.CycleTokenStack.Label",hint:"PF2E.Keybinding.CycleTokenStack.Hint",editable:[{key:"KeyZ",modifiers:[]}],onUp:()=>canvas.tokens.cycleStack()}),game.keybindings.register("pf2e","toggle-party-sheet",{name:"PF2E.Keybinding.TogglePartySheet.Label",hint:"PF2E.Keybinding.TogglePartySheet.Hint",editable:[{key:"KeyP",modifiers:[]}],onDown:()=>{const party=(()=>{if(game.user.isGM){const token=canvas.ready&&canvas.tokens.controlled.length===1?canvas.tokens.controlled[0]:null;return token?.actor?.isOfType("party")?token.actor:game.actors.party}else if(game.user.character?.isOfType("character")){const pcParties=Array.from(game.user.character.parties);return pcParties.find(p=>p.active)??pcParties.at(0)??null}return null})();if(!party)return!1;const{sheet}=party;return sheet.rendered?sheet._minimized?sheet.maximize():sheet.close():sheet.render(!0),!0}}),!game.modules.get("gm-vision")?.active&&!game.modules.get("perfect-vision")?.active&&game.keybindings.register("pf2e","gm-vision",{name:"PF2E.Keybinding.GMVision.Label",hint:"PF2E.Keybinding.GMVision.Hint",editable:[{key:"KeyG",modifiers:["Control"]}],restricted:!0,onDown:context=>(context.event.preventDefault(),!0),onUp:()=>(ui.controls.control?.name==="lighting"?ui.controls.control.tools.find(t=>t.name==="gm-vision")?.onClick?.():game.settings.set("pf2e","gmVision",!game.settings.get("pf2e","gmVision")),!0)})}__name(registerKeybindings,"registerKeybindings"),__name2(registerKeybindings,"registerKeybindings");function registerTemplates(){const templatePaths=["systems/pf2e/templates/chat/check/roll.hbs","systems/pf2e/templates/chat/check/target-dc-result.hbs","systems/pf2e/templates/chat/damage/damage-taken.hbs","systems/pf2e/templates/dice/damage-roll.hbs","systems/pf2e/templates/dice/damage-tooltip.hbs","systems/pf2e/templates/actors/character/partials/elemental-blast.hbs","systems/pf2e/templates/actors/character/partials/feat-slot.hbs","systems/pf2e/templates/actors/character/partials/header.hbs","systems/pf2e/templates/actors/character/partials/sidebar.hbs","systems/pf2e/templates/actors/character/partials/strike.hbs","systems/pf2e/templates/actors/character/tabs/general.hbs","systems/pf2e/templates/actors/character/tabs/actions.hbs","systems/pf2e/templates/actors/character/tabs/biography.hbs","systems/pf2e/templates/actors/character/tabs/effects.hbs","systems/pf2e/templates/actors/character/tabs/feats.hbs","systems/pf2e/templates/actors/character/tabs/inventory.hbs","systems/pf2e/templates/actors/character/tabs/pfs.hbs","systems/pf2e/templates/actors/character/tabs/proficiencies.hbs","systems/pf2e/templates/actors/character/tabs/spellcasting.hbs","systems/pf2e/templates/actors/character/tabs/crafting.hbs","systems/pf2e/templates/actors/hazard/partials/header.hbs","systems/pf2e/templates/actors/hazard/partials/sidebar.hbs","systems/pf2e/templates/actors/party/kingdom/tabs/main.hbs","systems/pf2e/templates/actors/party/kingdom/tabs/activities.hbs","systems/pf2e/templates/actors/party/kingdom/tabs/world.hbs","systems/pf2e/templates/actors/party/kingdom/tabs/features.hbs","systems/pf2e/templates/actors/party/kingdom/tabs/ongoing.hbs","systems/pf2e/templates/actors/party/kingdom/partials/build-entry-boosts.hbs","systems/pf2e/templates/actors/party/kingdom/partials/settlement.hbs","systems/pf2e/templates/actors/partials/action.hbs","systems/pf2e/templates/actors/partials/carry-type.hbs","systems/pf2e/templates/actors/partials/coinage.hbs","systems/pf2e/templates/actors/partials/dying-pips.hbs","systems/pf2e/templates/actors/partials/effects.hbs","systems/pf2e/templates/actors/partials/encumbrance.hbs","systems/pf2e/templates/actors/partials/inventory.hbs","systems/pf2e/templates/actors/partials/item-line.hbs","systems/pf2e/templates/actors/partials/modifiers-tooltip.hbs","systems/pf2e/templates/actors/partials/spell-collection.hbs","systems/pf2e/templates/actors/partials/toggles.hbs","systems/pf2e/templates/actors/partials/total-bulk.hbs","systems/pf2e/templates/actors/crafting-entry-alchemical.hbs","systems/pf2e/templates/actors/crafting-entry-list.hbs","systems/pf2e/templates/actors/character/partials/proficiencylevels-dropdown.hbs","systems/pf2e/templates/actors/character/icons/d20.hbs","systems/pf2e/templates/actors/character/icons/pfs.hbs","systems/pf2e/templates/actors/character/icons/plus.hbs","systems/pf2e/templates/actors/npc/tabs/main.hbs","systems/pf2e/templates/actors/npc/tabs/inventory.hbs","systems/pf2e/templates/actors/npc/tabs/effects.hbs","systems/pf2e/templates/actors/npc/tabs/spells.hbs","systems/pf2e/templates/actors/npc/tabs/notes.hbs","systems/pf2e/templates/actors/npc/partials/header.hbs","systems/pf2e/templates/actors/npc/partials/sidebar.hbs","systems/pf2e/templates/actors/npc/partials/action.hbs","systems/pf2e/templates/actors/npc/partials/attack.hbs","systems/pf2e/templates/items/action-details.hbs","systems/pf2e/templates/items/action-sidebar.hbs","systems/pf2e/templates/items/activation-panel.hbs","systems/pf2e/templates/items/affliction-details.hbs","systems/pf2e/templates/items/affliction-sidebar.hbs","systems/pf2e/templates/items/ancestry-details.hbs","systems/pf2e/templates/items/ancestry-sidebar.hbs","systems/pf2e/templates/items/armor-details.hbs","systems/pf2e/templates/items/background-details.hbs","systems/pf2e/templates/items/backpack-details.hbs","systems/pf2e/templates/items/book-details.hbs","systems/pf2e/templates/items/campaign-feature-details.hbs","systems/pf2e/templates/items/campaign-feature-sidebar.hbs","systems/pf2e/templates/items/class-details.hbs","systems/pf2e/templates/items/condition-details.hbs","systems/pf2e/templates/items/condition-sidebar.hbs","systems/pf2e/templates/items/consumable-details.hbs","systems/pf2e/templates/items/deity-details.hbs","systems/pf2e/templates/items/effect-details.hbs","systems/pf2e/templates/items/effect-sidebar.hbs","systems/pf2e/templates/items/equipment-details.hbs","systems/pf2e/templates/items/feat-details.hbs","systems/pf2e/templates/items/feat-sidebar.hbs","systems/pf2e/templates/items/heritage-details.hbs","systems/pf2e/templates/items/heritage-sidebar.hbs","systems/pf2e/templates/items/kit-details.hbs","systems/pf2e/templates/items/lore-details.hbs","systems/pf2e/templates/items/melee-details.hbs","systems/pf2e/templates/items/mystify-panel.hbs","systems/pf2e/templates/items/physical-sidebar.hbs","systems/pf2e/templates/items/rules-panel.hbs","systems/pf2e/templates/items/shield-details.hbs","systems/pf2e/templates/items/spell-details.hbs","systems/pf2e/templates/items/spell-overlay.hbs","systems/pf2e/templates/items/treasure-details.hbs","systems/pf2e/templates/items/weapon-details.hbs","systems/pf2e/templates/items/partials/ability-activation.hbs","systems/pf2e/templates/items/partials/duration.hbs","systems/pf2e/templates/items/partials/other-tags.hbs","systems/pf2e/templates/items/partials/self-applied-effect.hbs","systems/pf2e/templates/actors/loot/inventory.hbs","systems/pf2e/templates/actors/loot/sidebar.hbs","systems/pf2e/templates/actors/vehicle/vehicle-header.hbs","systems/pf2e/templates/actors/vehicle/sidebar.hbs","systems/pf2e/templates/actors/vehicle/tabs/details.hbs","systems/pf2e/templates/actors/vehicle/tabs/actions.hbs","systems/pf2e/templates/actors/vehicle/tabs/inventory.hbs","systems/pf2e/templates/actors/vehicle/tabs/description.hbs","systems/pf2e/templates/actors/vehicle/tabs/effects.hbs","systems/pf2e/templates/compendium-browser/settings/settings.hbs","systems/pf2e/templates/compendium-browser/settings/pack-settings.hbs","systems/pf2e/templates/compendium-browser/settings/source-settings.hbs","systems/pf2e/templates/compendium-browser/filters.hbs","systems/pf2e/templates/chat/action/header.hbs","systems/pf2e/templates/system/actions/repair/chat-button-partial.hbs","systems/pf2e/templates/system/actions/repair/repair-result-partial.hbs","systems/pf2e/templates/system/actions/repair/item-heading-partial.hbs","systems/pf2e/templates/scene/token/partials/appearance.hbs","systems/pf2e/templates/scene/token/partials/identity.hbs","systems/pf2e/templates/scene/token/partials/lighting.hbs","systems/pf2e/templates/partials/publication-data.hbs"];loadTemplates(templatePaths)}__name(registerTemplates,"registerTemplates"),__name2(registerTemplates,"registerTemplates");class PackLoader{static{__name(this,"PackLoader")}static{__name2(this,"PackLoader")}loadedSources=[];sourcesSettings;constructor(){this.sourcesSettings=game.settings.get("pf2e","compendiumBrowserSources")}async*loadPacks(documentType,packs,indexFields){const localize=localizer("PF2E.ProgressBar"),sources=this.#getSources(),progress=new Progress({max:packs.length});for(const packId of packs){const pack=game.packs.get(packId);if(!pack){progress.advance();continue}if(progress.advance({label:localize("LoadingPack",{pack:pack.metadata.label})}),pack.documentName===documentType){const index=await pack.getIndex({fields:indexFields});if((index.contents.at(0)??{}).system){const filteredIndex=this.#createFilteredIndex(index,sources);this.#setModuleArt(packId,filteredIndex),yield{pack,index:filteredIndex}}else ui.notifications.warn(game.i18n.format("PF2E.BrowserWarnPackNotLoaded",{pack:pack.collection}))}}progress.close({label:localize("LoadingComplete")})}#setModuleArt(packName,index){if(packName.startsWith("pf2e."))for(const record of index){const uuid=`Compendium.${packName}.${record._id}`,actorArt=game.pf2e.system.moduleArt.map.get(uuid)?.img;record.img=actorArt??record.img}}#getSources(){const sources=new Set;for(const source of Object.values(this.sourcesSettings.sources))source?.load&&sources.add(source.name);return sources}#createFilteredIndex(index,sources){if(sources.size===0||game.user.isGM&&this.sourcesSettings.ignoreAsGM)return index;const filteredIndex=new Collection,knownSources=Object.values(this.sourcesSettings.sources).map(value=>value?.name);for(const data of index){const source=this.#getSourceFromDocument(data);(!source&&this.sourcesSettings.showEmptySources||sources.has(source)||this.sourcesSettings.showUnknownSources&&source&&!knownSources.includes(source))&&filteredIndex.set(data._id,foundry.utils.deepClone(data))}return filteredIndex}async updateSources(packs){await this.#loadSources(packs);for(const source of this.loadedSources){const slug=sluggify(source);this.sourcesSettings.sources[slug]===void 0&&(this.sourcesSettings.sources[slug]={load:this.sourcesSettings.showUnknownSources,name:source})}this.sourcesSettings.sources=Object.fromEntries(Object.entries(this.sourcesSettings.sources).sort((a,b)=>a[0].localeCompare(b[0],game.i18n.lang)))}async#loadSources(packs){const localize=localizer("PF2E.ProgressBar"),progress=new Progress({max:packs.length}),loadedSources=new Set,indexFields=["system.publication.title","system.source.value"],knownDocumentTypes=["Actor","Item"];for(const packId of packs){const pack=game.packs.get(packId);if(!pack||!knownDocumentTypes.includes(pack.documentName)){progress.advance();continue}progress.advance({label:localize("LoadingPack",{pack:pack?.metadata.label??""})});const index=await pack.getIndex({fields:indexFields});for(const element of index){const source=this.#getSourceFromDocument(element);source&&source!==""&&loadedSources.add(source)}}progress.close({label:localize("LoadingComplete")});const loadedSourcesArray=Array.from(loadedSources).sort();this.loadedSources=loadedSourcesArray}#getSourceFromDocument(document2){const{system}=document2;return isObject$1(system)?system.publication?.title??system.details?.publication?.title??system.source?.value??system.details?.source?.value??"":""}reset(){this.loadedSources=[]}async hardReset(packs){this.reset(),this.sourcesSettings={ignoreAsGM:!0,showEmptySources:!0,showUnknownSources:!0,sources:{}},await this.updateSources(packs)}}class CompendiumBrowserTab{static{__name(this,"CompendiumBrowserTab")}static{__name2(this,"CompendiumBrowserTab")}browser;indexData=[];currentIndex=[];isInitialized=!1;totalItemCount=0;scrollLimit=100;#domParser=new DOMParser;searchFields=[];storeFields=[];constructor(browser){this.browser=browser}async init(){await this.loadData(),this.searchEngine=new MiniSearch({fields:this.searchFields,idField:"uuid",processTerm:t=>t.length>1&&!CompendiumDirectoryPF2e.STOP_WORDS.has(t)?t.toLocaleLowerCase(game.i18n.lang):null,storeFields:this.storeFields,searchOptions:{combineWith:"AND",prefix:!0}}),this.searchEngine.addAll(this.indexData),this.defaultFilterData=foundry.utils.deepClone(this.filterData),this.isInitialized=!0}async open(filter2){if(filter2){if(!this.isInitialized)throw ErrorPF2e(`Tried to pass an initial filter to uninitialized tab "${this.tabName}"`);this.filterData=filter2}return this.browser.loadTab(this.tabName)}getIndexData(start){if(!this.isInitialized)throw ErrorPF2e(`Compendium Browser Tab "${this.tabName}" is not initialized!`);return this.currentIndex=(()=>{const searchText=this.filterData.search.text;if(searchText){const searchResult=this.searchEngine.search(searchText);return this.sortResult(searchResult.filter(this.filterIndexData.bind(this)))}return this.sortResult(this.indexData.filter(this.filterIndexData.bind(this)))})(),this.totalItemCount=this.currentIndex.length,this.currentIndex.slice(start,this.scrollLimit)}async getFilterData(){return this.isInitialized||await this.init(),foundry.utils.deepClone(this.defaultFilterData)}resetFilters(){this.filterData=foundry.utils.deepClone(this.defaultFilterData)}isOfType(...types){return types.some(t=>this.tabName===t)}filterTraits(traits,selected,condition){const selectedTraits=selected.filter(s=>!s.not).map(s=>s.value),notTraits=selected.filter(t=>t.not).map(s=>s.value);return!((selectedTraits.length||notTraits.length)&&(notTraits.some(t=>traits.includes(t))||!(condition==="and"?selectedTraits.every(t=>traits.includes(t)):selectedTraits.some(t=>traits.includes(t)))))}async renderResults(start){if(!this.templatePath)throw ErrorPF2e(`Tab "${this.tabName}" has no valid template path.`);const indexData=this.getIndexData(start),liElements=[];for(const entry of indexData){const htmlString=await renderTemplate(this.templatePath,{entry,filterData:this.filterData}),html=this.#domParser.parseFromString(htmlString,"text/html");liElements.push(html.body.firstElementChild)}return liElements}sortResult(result){const{order}=this.filterData,lang=game.i18n.lang,sorted=result.sort((entryA,entryB)=>{switch(order.by){case"name":return entryA.name.localeCompare(entryB.name,lang);case"level":return entryA.level-entryB.level||entryA.name.localeCompare(entryB.name,lang);case"price":return entryA.priceInCopper-entryB.priceInCopper||entryA.name.localeCompare(entryB.name,lang);case"rank":return entryA.rank-entryB.rank||entryA.name.localeCompare(entryB.name,lang);default:return 0}});return order.direction==="asc"?sorted:sorted.reverse()}parseRangeFilterInput(_name,lower,upper){return{min:Number(lower)||0,max:Number(upper)||0,inputMin:lower,inputMax:upper}}arrayIncludes(array,other){return other.some(value=>array.includes(value))}generateCheckboxOptions(configData,sort=!0){const localized=Object.entries(configData).reduce((result,[key,label])=>({...result,[key]:game.i18n.localize(label)}),{});return Object.entries(sort?this.sortedConfig(localized):localized).reduce((result,[key,label])=>({...result,[key]:{label,selected:!1}}),{})}generateMultiselectOptions(optionsRecord,sort=!0){const options=Object.entries(optionsRecord).map(([value,label])=>({value,label:game.i18n.localize(label)}));return sort&&options.sort((a,b)=>a.label.localeCompare(b.label,game.i18n.lang)),options}generateSourceCheckboxOptions(sources){return[...sources].sort().reduce((result,source)=>({...result,[sluggify(source)]:{label:source,selected:!1}}),{})}sortedConfig(obj){return Object.fromEntries([...Object.entries(obj)].sort((entryA,entryB)=>entryA[1].localeCompare(entryB[1],game.i18n.lang)))}hasAllIndexFields(data,indexFields){for(const field of indexFields)if(foundry.utils.getProperty(data,field)===void 0&&!/\.(?:source|publication)/.test(field))return!1;return!0}#getRollTableResults({initial=0,weight=1}){return this.currentIndex.flatMap((e,i)=>{const data=fromUuidSync(e.uuid);if(!data?.pack||!data._id||!("name"in data))return[];const rangeMinMax=initial+i+1;return{text:data.name,type:CONST.TABLE_RESULT_TYPES.COMPENDIUM,collection:data.pack,resultId:data._id,img:e.img,weight,range:[rangeMinMax,rangeMinMax],drawn:!1}})}async createRollTable(){if(!this.isInitialized)throw ErrorPF2e(`Compendium Browser Tab "${this.tabName}" is not initialized!`);const content=await renderTemplate("systems/pf2e/templates/compendium-browser/roll-table-dialog.hbs",{count:this.currentIndex.length});Dialog.confirm({content,title:game.i18n.localize("PF2E.CompendiumBrowser.RollTable.CreateLabel"),yes:async $html=>{const html=$html[0],name2=htmlQuery(html,"input[name=name]")?.value||game.i18n.localize("PF2E.CompendiumBrowser.Title"),weight=Number(htmlQuery(html,"input[name=weight]")?.value)||1,results=this.#getRollTableResults({weight});(await RollTable.create({name:name2,results,formula:`1d${results.length}`}))?.sheet.render(!0)}})}async addToRollTable(){if(!this.isInitialized)throw ErrorPF2e(`Compendium Browser Tab "${this.tabName}" is not initialized!`);const content=await renderTemplate("systems/pf2e/templates/compendium-browser/roll-table-dialog.hbs",{count:this.currentIndex.length,rollTables:game.tables.contents});Dialog.confirm({title:game.i18n.localize("PF2E.CompendiumBrowser.RollTable.SelectTableTitle"),content,yes:async $html=>{const html=$html[0],option=htmlQuery(html,"select[name=roll-table]")?.selectedOptions[0];if(!option)return;const weight=Number(htmlQuery(html,"input[name=weight]")?.value)||1,table=game.tables.get(option.value,{strict:!0});await table.createEmbeddedDocuments("TableResult",this.#getRollTableResults({initial:table.results.size,weight})),table?.sheet.render(!0)}})}}class CompendiumBrowserActionTab extends CompendiumBrowserTab{static{__name(this,"CompendiumBrowserActionTab")}static{__name2(this,"CompendiumBrowserActionTab")}tabName="action";filterData;templatePath="systems/pf2e/templates/compendium-browser/partials/action.hbs";searchFields=["name"];storeFields=["type","name","img","uuid","traits","source","category","actionType"];constructor(browser){super(browser),this.filterData=this.prepareFilterData()}async loadData(){console.debug("PF2e System | Compendium Browser | Started loading actions");const actions=[],indexFields=["img","system.actionType.value","system.category","system.traits.value","system.actionType.value","system.publication","system.source"],publications=new Set;for await(const{pack,index}of this.browser.packLoader.loadPacks("Item",this.browser.loadedPacks("action"),indexFields)){console.debug(`PF2e System | Compendium Browser | ${pack.metadata.label} - Loading`);for(const actionData of index)if(actionData.type==="action"){if(!this.hasAllIndexFields(actionData,indexFields)){console.warn(`Action '${actionData.name}' does not have all required data fields. Consider unselecting pack '${pack.metadata.label}' in the compendium browser settings.`);continue}actionData.system.actionType.value==="passive"&&(actionData.img=getActionIcon("passive"));const{system}=actionData,pubSource=String(system.publication?.title??system.source?.value??"").trim(),sourceSlug=sluggify(pubSource);pubSource&&publications.add(pubSource),actions.push({type:actionData.type,name:actionData.name,img:actionData.img,uuid:`Compendium.${pack.collection}.${actionData._id}`,traits:actionData.system.traits.value.map(t=>t.replace(/^hb_/,"")),actionType:actionData.system.actionType.value,category:actionData.system.category,source:sourceSlug})}}this.indexData=actions,this.filterData.multiselects.traits.options=this.generateMultiselectOptions(CONFIG.PF2E.actionTraits),this.filterData.checkboxes.types.options=this.generateCheckboxOptions(CONFIG.PF2E.actionTypes),this.filterData.checkboxes.category.options=this.generateCheckboxOptions(pick(CONFIG.PF2E.actionCategories,["familiar"])),this.filterData.checkboxes.source.options=this.generateSourceCheckboxOptions(publications),console.debug("PF2e System | Compendium Browser | Finished loading actions")}filterIndexData(entry){const{checkboxes,multiselects}=this.filterData;return!(checkboxes.types.selected.length&&!checkboxes.types.selected.includes(entry.actionType)||checkboxes.category.selected.length&&!checkboxes.category.selected.includes(entry.category)||!this.filterTraits(entry.traits,multiselects.traits.selected,multiselects.traits.conjunction)||checkboxes.source.selected.length&&!checkboxes.source.selected.includes(entry.source))}prepareFilterData(){return{checkboxes:{types:{isExpanded:!0,label:"PF2E.ActionActionTypeLabel",options:{},selected:[]},category:{isExpanded:!0,label:"PF2E.BrowserFilterCategory",options:{},selected:[]},source:{isExpanded:!1,label:"PF2E.BrowserFilterSource",options:{},selected:[]}},multiselects:{traits:{conjunction:"and",label:"PF2E.BrowserFilterTraits",options:[],selected:[]}},order:{by:"name",direction:"asc",options:{name:"Name"}},search:{text:""}}}}class CompendiumBrowserBestiaryTab extends CompendiumBrowserTab{static{__name(this,"CompendiumBrowserBestiaryTab")}static{__name2(this,"CompendiumBrowserBestiaryTab")}tabName="bestiary";filterData;templatePath="systems/pf2e/templates/compendium-browser/partials/bestiary.hbs";index=["img","system.details.level.value","system.details.publication.title","system.details.source.value","system.traits"];searchFields=["name"];storeFields=["type","name","img","uuid","level","actorSize","traits","rarity","source"];constructor(browser){super(browser),this.filterData=this.prepareFilterData()}async loadData(){const bestiaryActors=[],publications=new Set,indexFields=[...this.index];for await(const{pack,index}of this.browser.packLoader.loadPacks("Actor",this.browser.loadedPacks("bestiary"),indexFields)){console.debug(`PF2e System | Compendium Browser | ${pack.metadata.label} - ${index.size} entries found`);for(const actorData of index.filter(d=>d.type==="npc")){if(!this.hasAllIndexFields(actorData,this.index)){console.warn(`Actor '${actorData.name}' does not have all required data fields. Consider unselecting pack '${pack.metadata.label}' in the compendium browser settings.`);continue}const{details}=actorData.system,pubSource=String(details.publication?.title??details.source?.value??"").trim(),sourceSlug=sluggify(pubSource);pubSource&&publications.add(pubSource),bestiaryActors.push({type:actorData.type,name:actorData.name,img:actorData.img,uuid:`Compendium.${pack.collection}.${actorData._id}`,level:actorData.system.details.level.value,actorSize:actorData.system.traits.size.value,traits:actorData.system.traits.value.map(t=>t.replace(/^hb_/,"")),rarity:actorData.system.traits.rarity,source:sourceSlug})}console.debug(`PF2e System | Compendium Browser | ${pack.metadata.label} - Loaded`)}this.indexData=bestiaryActors,this.filterData.checkboxes.sizes.options=this.generateCheckboxOptions(CONFIG.PF2E.actorSizes),this.filterData.multiselects.traits.options=this.generateMultiselectOptions(CONFIG.PF2E.creatureTraits),this.filterData.checkboxes.rarity.options=this.generateCheckboxOptions(CONFIG.PF2E.rarityTraits,!1),this.filterData.checkboxes.source.options=this.generateSourceCheckboxOptions(publications),console.debug("PF2e System | Compendium Browser | Finished loading Bestiary actors")}filterIndexData(entry){const{checkboxes,multiselects,sliders}=this.filterData;return!(!(entry.level>=sliders.level.values.min&&entry.level<=sliders.level.values.max)||checkboxes.sizes.selected.length&&!checkboxes.sizes.selected.includes(entry.actorSize)||!this.filterTraits(entry.traits,multiselects.traits.selected,multiselects.traits.conjunction)||checkboxes.source.selected.length&&!checkboxes.source.selected.includes(entry.source)||checkboxes.rarity.selected.length&&!checkboxes.rarity.selected.includes(entry.rarity))}prepareFilterData(){return{checkboxes:{sizes:{isExpanded:!0,label:"PF2E.BrowserFilterSizes",options:{},selected:[]},rarity:{isExpanded:!1,label:"PF2E.BrowserFilterRarities",options:{},selected:[]},source:{isExpanded:!1,label:"PF2E.BrowserFilterSource",options:{},selected:[]}},multiselects:{traits:{conjunction:"and",label:"PF2E.BrowserFilterTraits",options:[],selected:[]}},order:{by:"level",direction:"asc",options:{name:"Name",level:"PF2E.LevelLabel"}},sliders:{level:{isExpanded:!1,label:"PF2E.BrowserFilterLevels",values:{lowerLimit:-1,upperLimit:25,min:-1,max:25,step:1}}},search:{text:""}}}}class CompendiumBrowserCampaignFeaturesTab extends CompendiumBrowserTab{static{__name(this,"CompendiumBrowserCampaignFeaturesTab")}static{__name2(this,"CompendiumBrowserCampaignFeaturesTab")}tabName="campaignFeature";filterData;templatePath="systems/pf2e/templates/compendium-browser/partials/feat.hbs";searchFields=["name"];storeFields=["type","name","img","uuid","level","category","traits","source"];constructor(browser){super(browser),this.filterData=this.prepareFilterData()}async loadData(){console.debug("PF2e System | Compendium Browser | Started loading feats");const feats=[],publications=new Set,indexFields=["img","system.actionType.value","system.actions.value","system.category","system.level.value","system.prerequisites.value","system.traits","system.publication","system.source"];for await(const{pack,index}of this.browser.packLoader.loadPacks("Item",this.browser.loadedPacks("campaignFeature"),indexFields)){console.debug(`PF2e System | Compendium Browser | ${pack.metadata.label} - ${index.size} entries found`);for(const featData of index.filter(i=>i.type==="campaignFeature")){featData.filters={};const{system}=featData,pubSource=String(system.publication?.title??system.source?.value??"").trim(),sourceSlug=sluggify(pubSource);pubSource&&publications.add(pubSource),feats.push({type:featData.type,name:featData.name,img:featData.img,uuid:`Compendium.${pack.collection}.${featData._id}`,level:featData.system.level?.value,category:featData.system.category,traits:featData.system.traits.value.map(t=>t.replace(/^hb_/,"")),rarity:featData.system.traits.rarity,source:sourceSlug})}}this.indexData=feats,this.filterData.checkboxes.category.options=this.generateCheckboxOptions(KINGMAKER_CATEGORIES),this.filterData.checkboxes.rarity.options=this.generateCheckboxOptions(CONFIG.PF2E.rarityTraits),this.filterData.checkboxes.source.options=this.generateSourceCheckboxOptions(publications),this.filterData.multiselects.traits.options=this.generateMultiselectOptions(CONFIG.PF2E.kingmakerTraits),console.debug("PF2e System | Compendium Browser | Finished loading feats")}filterIndexData(entry){const{checkboxes,multiselects,sliders}=this.filterData,entryLevel=entry.level??0;return!(!(entryLevel>=sliders.level.values.min&&entryLevel<=sliders.level.values.max)||checkboxes.category.selected.length&&!checkboxes.category.selected.includes(entry.category)||!this.filterTraits(entry.traits,multiselects.traits.selected,multiselects.traits.conjunction)||checkboxes.source.selected.length&&!checkboxes.source.selected.includes(entry.source)||checkboxes.rarity.selected.length&&!checkboxes.rarity.selected.includes(entry.rarity))}prepareFilterData(){return{checkboxes:{category:{isExpanded:!1,label:"PF2E.BrowserFilterCategory",options:{},selected:[]},rarity:{isExpanded:!1,label:"PF2E.BrowserFilterRarities",options:{},selected:[]},source:{isExpanded:!1,label:"PF2E.BrowserFilterSource",options:{},selected:[]}},multiselects:{traits:{conjunction:"and",label:"PF2E.BrowserFilterTraits",options:[],selected:[]}},order:{by:"level",direction:"asc",options:{name:"Name",level:"PF2E.LevelLabel"}},sliders:{level:{isExpanded:!1,label:"PF2E.BrowserFilterLevels",values:{lowerLimit:0,upperLimit:20,min:0,max:20,step:1}}},search:{text:""}}}}class CompendiumBrowserEquipmentTab extends CompendiumBrowserTab{static{__name(this,"CompendiumBrowserEquipmentTab")}static{__name2(this,"CompendiumBrowserEquipmentTab")}tabName="equipment";filterData;templatePath="systems/pf2e/templates/compendium-browser/partials/equipment.hbs";searchFields=["name"];storeFields=["type","name","img","uuid","level","category","group","price","priceInCopper","traits","rarity","source"];#localizeCoins=localizer("PF2E.CurrencyAbbreviations");constructor(browser){super(browser),this.filterData=this.prepareFilterData()}async loadData(){console.debug("PF2e System | Compendium Browser | Started loading inventory items");const inventoryItems=[],itemTypes=["weapon","shield","armor","equipment","consumable","treasure","backpack","kit"],baseFields=["img","system.price","system.traits","system.publication","system.source"],physicalItemFields=[...baseFields,"system.level.value"],runedItemFields=[...physicalItemFields,"system.runes"],armorAndWeaponFields=[...runedItemFields,"system.category","system.group"],indexFields=uniq([...armorAndWeaponFields]).sort(),publications=new Set;for await(const{pack,index}of this.browser.packLoader.loadPacks("Item",this.browser.loadedPacks("equipment"),indexFields)){console.debug(`PF2e System | Compendium Browser | ${pack.metadata.label} - ${index.size} entries found`);for(const itemData of index)if(!(itemData.type==="treasure"&&itemData.system.stackGroup==="coins")&&itemTypes.includes(itemData.type)){if((()=>{switch(itemData.type){case"armor":case"weapon":return!this.hasAllIndexFields(itemData,armorAndWeaponFields);case"kit":return!this.hasAllIndexFields(itemData,baseFields);case"shield":return!this.hasAllIndexFields(itemData,runedItemFields);default:return!this.hasAllIndexFields(itemData,physicalItemFields)}})()){console.warn(`Item '${itemData.name}' does not have all required data fields. Consider unselecting pack '${pack.metadata.label}' in the compendium browser settings.`);continue}const priceValue=itemData.system.price.value,priceCoins=typeof priceValue=="string"?CoinsPF2e.fromString(priceValue):new CoinsPF2e(priceValue),coinValue=priceCoins.copperValue,{system}=itemData,pubSource=String(system.publication?.title??system.source?.value??"").trim(),sourceSlug=sluggify(pubSource);pubSource&&publications.add(pubSource);const traits=itemData.system.traits.value??[],runes=itemData.system.runes,traditionTraits=MAGIC_TRADITIONS;!traits.some(t=>traditionTraits.has(t))&&["armor","shield","weapon"].includes(itemData.type)&&(runes.potency||runes.reinforcing||runes.resilient||runes.striking)&&traits.push("magical"),inventoryItems.push({type:itemData.type,name:itemData.name,img:itemData.img,uuid:`Compendium.${pack.collection}.${itemData._id}`,level:itemData.system.level?.value??0,category:itemData.system.category??"",group:itemData.system.group??"",price:priceCoins,priceInCopper:coinValue,traits:uniq(itemData.system.traits.value),rarity:itemData.system.traits.rarity,source:sourceSlug})}}this.indexData=inventoryItems,this.filterData.checkboxes.armorTypes.options=this.generateCheckboxOptions(CONFIG.PF2E.armorCategories),foundry.utils.mergeObject(this.filterData.checkboxes.armorTypes.options,this.generateCheckboxOptions(CONFIG.PF2E.armorGroups)),this.filterData.checkboxes.weaponTypes.options=this.generateCheckboxOptions(CONFIG.PF2E.weaponCategories),foundry.utils.mergeObject(this.filterData.checkboxes.weaponTypes.options,this.generateCheckboxOptions(CONFIG.PF2E.weaponGroups)),this.filterData.multiselects.traits.options=this.generateMultiselectOptions({...CONFIG.PF2E.armorTraits,...CONFIG.PF2E.consumableTraits,...CONFIG.PF2E.equipmentTraits,...CONFIG.PF2E.shieldTraits,...CONFIG.PF2E.weaponTraits}),this.filterData.checkboxes.itemTypes.options=this.generateCheckboxOptions({weapon:"TYPES.Item.weapon",shield:"TYPES.Item.shield",armor:"TYPES.Item.armor",equipment:"TYPES.Item.equipment",consumable:"TYPES.Item.consumable",treasure:"TYPES.Item.treasure",backpack:"TYPES.Item.backpack",kit:"TYPES.Item.kit"}),this.filterData.checkboxes.rarity.options=this.generateCheckboxOptions(CONFIG.PF2E.rarityTraits,!1),this.filterData.checkboxes.source.options=this.generateSourceCheckboxOptions(publications),console.debug("PF2e System | Compendium Browser | Finished loading inventory items")}filterIndexData(entry){const{checkboxes,multiselects,ranges,sliders}=this.filterData;return!(!(entry.level>=sliders.level.values.min&&entry.level<=sliders.level.values.max)||!(entry.priceInCopper>=ranges.price.values.min&&entry.priceInCopper<=ranges.price.values.max)||checkboxes.itemTypes.selected.length>0&&!checkboxes.itemTypes.selected.includes(entry.type)||checkboxes.armorTypes.selected.length>0&&!this.arrayIncludes(checkboxes.armorTypes.selected,[entry.category,entry.group])||checkboxes.weaponTypes.selected.length>0&&!this.arrayIncludes(checkboxes.weaponTypes.selected,[entry.category,entry.group])||!this.filterTraits(entry.traits,multiselects.traits.selected,multiselects.traits.conjunction)||checkboxes.source.selected.length>0&&!checkboxes.source.selected.includes(entry.source)||checkboxes.rarity.selected.length>0&&!checkboxes.rarity.selected.includes(entry.rarity))}parseRangeFilterInput(name2,lower,upper){if(name2==="price"){const coins={cp:this.#localizeCoins("cp"),sp:this.#localizeCoins("sp"),gp:this.#localizeCoins("gp"),pp:this.#localizeCoins("pp")};for(const[english,translated]of Object.entries(coins))lower=lower.replaceAll(translated,english),upper=upper.replaceAll(translated,english);return{min:CoinsPF2e.fromString(lower).copperValue,max:CoinsPF2e.fromString(upper).copperValue,inputMin:lower,inputMax:upper}}return super.parseRangeFilterInput(name2,lower,upper)}prepareFilterData(){return{checkboxes:{itemTypes:{isExpanded:!0,label:"PF2E.BrowserFilterInventoryTypes",options:{},selected:[]},rarity:{isExpanded:!1,label:"PF2E.BrowserFilterRarities",options:{},selected:[]},armorTypes:{isExpanded:!1,label:"PF2E.BrowserFilterArmorFilters",options:{},selected:[]},weaponTypes:{isExpanded:!1,label:"PF2E.BrowserFilterWeaponFilters",options:{},selected:[]},source:{isExpanded:!1,label:"PF2E.BrowserFilterSource",options:{},selected:[]}},multiselects:{traits:{conjunction:"and",label:"PF2E.BrowserFilterTraits",options:[],selected:[]}},order:{by:"level",direction:"asc",options:{name:"Name",level:"PF2E.LevelLabel",price:"PF2E.PriceLabel"}},ranges:{price:{changed:!1,isExpanded:!1,label:"PF2E.PriceLabel",values:{min:0,max:2e7,inputMin:`0${this.#localizeCoins("cp")}`,inputMax:`200,000${this.#localizeCoins("gp")}`}}},sliders:{level:{isExpanded:!1,label:"PF2E.BrowserFilterLevels",values:{lowerLimit:0,upperLimit:30,min:0,max:30,step:1}}},search:{text:""}}}}class CompendiumBrowserFeatTab extends CompendiumBrowserTab{static{__name(this,"CompendiumBrowserFeatTab")}static{__name2(this,"CompendiumBrowserFeatTab")}tabName="feat";filterData;templatePath="systems/pf2e/templates/compendium-browser/partials/feat.hbs";searchFields=["name"];storeFields=["type","name","img","uuid","level","category","skills","traits","rarity","source"];#creatureTraits=CONFIG.PF2E.creatureTraits;constructor(browser){super(browser),this.filterData=this.prepareFilterData()}async loadData(){console.debug("PF2e System | Compendium Browser | Started loading feats");const feats=[],publications=new Set,indexFields=["img","system.actionType.value","system.actions.value","system.category","system.level.value","system.prerequisites.value","system.traits","system.publication","system.source"],translatedSkills=Object.entries(CONFIG.PF2E.skillList).reduce((result,[key,value])=>({...result,[key]:game.i18n.localize(value).toLocaleLowerCase(game.i18n.lang)}),{}),skillList=Object.entries(translatedSkills);for await(const{pack,index}of this.browser.packLoader.loadPacks("Item",this.browser.loadedPacks("feat"),indexFields)){console.debug(`PF2e System | Compendium Browser | ${pack.metadata.label} - ${index.size} entries found`);for(const featData of index)if(featData.type==="feat"){featData.filters={};const categoryPaths=["system.category","system.featType.value"],nonCategoryPaths=indexFields.filter(f=>!categoryPaths.includes(f)),categoryPathFound=categoryPaths.some(p=>foundry.utils.hasProperty(featData,p));if(!this.hasAllIndexFields(featData,nonCategoryPaths)||!categoryPathFound){console.warn(`Feat "${featData.name}" does not have all required data fields.`,`Consider unselecting pack "${pack.metadata.label}" in the compendium browser settings.`);continue}const featType=featData.system.featType;isObject(featType)&&"value"in featType&&typeof featType.value=="string"&&(featData.system.category=featType.value,delete featData.system.featType);const prerequisitesArr=featData.system.prerequisites.value.map(prerequisite=>prerequisite?.value?prerequisite.value.toLowerCase():""),skills=new Set;for(const prereq of prerequisitesArr)for(const[key,value]of skillList)(prereq.includes(key)||prereq.includes(value))&&skills.add(key);const pubSource=featData.system.publication?.title??featData.system.source?.value??"",sourceSlug=sluggify(pubSource);pubSource&&publications.add(pubSource),feats.push({type:featData.type,name:featData.name,img:featData.img,uuid:`Compendium.${pack.collection}.Item.${featData._id}`,level:featData.system.level.value,category:featData.system.category,skills:[...skills],traits:featData.system.traits.value.map(t=>t.replace(/^hb_/,"")),rarity:featData.system.traits.rarity,source:sourceSlug})}}this.indexData=feats,this.filterData.checkboxes.category.options=this.generateCheckboxOptions(CONFIG.PF2E.featCategories),this.filterData.checkboxes.skills.options=this.generateCheckboxOptions(CONFIG.PF2E.skillList),this.filterData.checkboxes.rarity.options=this.generateCheckboxOptions(CONFIG.PF2E.rarityTraits),this.filterData.checkboxes.source.options=this.generateSourceCheckboxOptions(publications),this.filterData.multiselects.traits.options=this.generateMultiselectOptions(CONFIG.PF2E.featTraits),console.debug("PF2e System | Compendium Browser | Finished loading feats")}filterTraits(traits,selected,condition){if(this.filterData.checkboxes.category.selected.includes("ancestry")&&!traits.some(t=>t in this.#creatureTraits)){const withoutAncestryTraits=selected.filter(t=>!(t.value in this.#creatureTraits));return super.filterTraits(traits,withoutAncestryTraits,condition)}return super.filterTraits(traits,selected,condition)}filterIndexData(entry){const{checkboxes,multiselects,sliders}=this.filterData;return!(!(entry.level>=sliders.level.values.min&&entry.level<=sliders.level.values.max)||checkboxes.category.selected.length&&!checkboxes.category.selected.includes(entry.category)||checkboxes.skills.selected.length&&!this.arrayIncludes(checkboxes.skills.selected,entry.skills)||!this.filterTraits(entry.traits,multiselects.traits.selected,multiselects.traits.conjunction)||checkboxes.source.selected.length&&!checkboxes.source.selected.includes(entry.source)||checkboxes.rarity.selected.length&&!checkboxes.rarity.selected.includes(entry.rarity))}prepareFilterData(){return{checkboxes:{category:{isExpanded:!1,label:"PF2E.BrowserFilterCategory",options:{},selected:[]},skills:{isExpanded:!1,label:"PF2E.BrowserFilterSkills",options:{},selected:[]},rarity:{isExpanded:!1,label:"PF2E.BrowserFilterRarities",options:{},selected:[]},source:{isExpanded:!1,label:"PF2E.BrowserFilterSource",options:{},selected:[]}},multiselects:{traits:{conjunction:"and",label:"PF2E.BrowserFilterTraits",options:[],selected:[]}},order:{by:"level",direction:"asc",options:{name:"Name",level:"PF2E.LevelLabel"}},sliders:{level:{isExpanded:!1,label:"PF2E.BrowserFilterLevels",values:{lowerLimit:0,upperLimit:20,min:0,max:20,step:1}}},search:{text:""}}}}class CompendiumBrowserHazardTab extends CompendiumBrowserTab{static{__name(this,"CompendiumBrowserHazardTab")}static{__name2(this,"CompendiumBrowserHazardTab")}tabName="hazard";filterData;templatePath="systems/pf2e/templates/compendium-browser/partials/hazard.hbs";searchFields=["name"];storeFields=["type","name","img","uuid","level","complexity","traits","rarity","source"];index=["img","system.details.level.value","system.details.isComplex","system.traits"];constructor(browser){super(browser),this.filterData=this.prepareFilterData()}async loadData(){console.debug("PF2e System | Compendium Browser | Started loading Hazard actors");const hazardActors=[],publications=new Set,indexFields=[...this.index,"system.details.alignment.value","system.details.publication","system.details.source"];for await(const{pack,index}of this.browser.packLoader.loadPacks("Actor",this.browser.loadedPacks("hazard"),indexFields)){console.debug(`PF2e System | Compendium Browser | ${pack.metadata.label} - ${index.size} entries found`);for(const actorData of index.filter(d=>d.type==="hazard")){if(!this.hasAllIndexFields(actorData,this.index)){console.warn(`Hazard '${actorData.name}' does not have all required data fields. Consider unselecting pack '${pack.metadata.label}' in the compendium browser settings.`);continue}const{details}=actorData.system,pubSource=String(details.publication?.title??details.source?.value??"").trim(),sourceSlug=sluggify(pubSource);pubSource&&publications.add(pubSource),hazardActors.push({type:actorData.type,name:actorData.name,img:actorData.img,uuid:`Compendium.${pack.collection}.${actorData._id}`,level:actorData.system.details.level.value,complexity:actorData.system.details.isComplex?"complex":"simple",traits:actorData.system.traits.value,rarity:actorData.system.traits.rarity,source:sourceSlug})}console.debug(`PF2e System | Compendium Browser | ${pack.metadata.label} - Loaded`)}this.indexData=hazardActors,this.filterData.checkboxes.complexity.options=this.generateCheckboxOptions({simple:"PF2E.Actor.Hazard.Simple",complex:"PF2E.TraitComplex"},!1),this.filterData.multiselects.traits.options=this.generateMultiselectOptions(CONFIG.PF2E.hazardTraits),this.filterData.checkboxes.rarity.options=this.generateCheckboxOptions(CONFIG.PF2E.rarityTraits,!1),this.filterData.checkboxes.source.options=this.generateSourceCheckboxOptions(publications),console.debug("PF2e System | Compendium Browser | Finished loading Hazard actors")}filterIndexData(entry){const{checkboxes,multiselects,sliders}=this.filterData;return!(!(entry.level>=sliders.level.values.min&&entry.level<=sliders.level.values.max)||checkboxes.complexity.selected.length&&!checkboxes.complexity.selected.includes(entry.complexity)||!this.filterTraits(entry.traits,multiselects.traits.selected,multiselects.traits.conjunction)||checkboxes.source.selected.length&&!checkboxes.source.selected.includes(entry.source)||checkboxes.rarity.selected.length&&!checkboxes.rarity.selected.includes(entry.rarity))}prepareFilterData(){return{checkboxes:{complexity:{isExpanded:!0,label:"PF2E.BrowserFilterComplexity",options:{},selected:[]},rarity:{isExpanded:!1,label:"PF2E.BrowserFilterRarities",options:{},selected:[]},source:{isExpanded:!1,label:"PF2E.BrowserFilterSource",options:{},selected:[]}},multiselects:{traits:{conjunction:"and",label:"PF2E.BrowserFilterTraits",options:[],selected:[]}},order:{by:"level",direction:"asc",options:{name:"Name",level:"PF2E.LevelLabel"}},sliders:{level:{isExpanded:!1,label:"PF2E.BrowserFilterLevels",values:{lowerLimit:-1,upperLimit:25,min:-1,max:25,step:1}}},search:{text:""}}}}class CompendiumBrowserSpellTab extends CompendiumBrowserTab{static{__name(this,"CompendiumBrowserSpellTab")}static{__name2(this,"CompendiumBrowserSpellTab")}tabName="spell";filterData;templatePath="systems/pf2e/templates/compendium-browser/partials/spell.hbs";searchFields=["name"];storeFields=["type","name","img","uuid","rank","time","traditions","traits","categories","rarity","source"];constructor(browser){super(browser),this.filterData=this.prepareFilterData()}async loadData(){console.debug("PF2e System | Compendium Browser | Started loading spells");const spells=[],times=new Set,publications=new Set,indexFields=["img","system.level.value","system.time","system.traits","system.publication","system.ritual","system.source"],data=this.browser.packLoader.loadPacks("Item",this.browser.loadedPacks("spell"),indexFields);for await(const{pack,index}of data){console.debug(`PF2e System | Compendium Browser | ${pack.metadata.label} - ${index.size} entries found`);for(const spellData of index)if(spellData.filters={},spellData.type==="spell"){if("system"in spellData&&isObject$1(spellData.system)&&(spellData.system.ritual??=null),!this.hasAllIndexFields(spellData,indexFields)){console.warn(`Item '${spellData.name}' does not have all required data fields. Consider unselecting pack '${pack.metadata.label}' in the compendium browser settings.`);continue}const isCantrip=spellData.system.traits.value.includes("cantrip"),isFocusSpell=spellData.system.traits.value.includes("focus"),isRitual=!!spellData.system.ritual,categories=compact([!isCantrip&&!isFocusSpell&&!isRitual?"spell":null,isCantrip?"cantrip":null,isFocusSpell?"focus":null,isRitual?"ritual":null]),time=spellData.system.time.value;if(time&&typeof time=="string"){const normalizedTime=time.toLocaleLowerCase("en").includes("reaction")?"reaction":sluggify(time);times.add(normalizedTime),spellData.system.time.value=normalizedTime}const actionGlyph=getActionGlyph(spellData.system.time.value),{system}=spellData,pubSource=String(system.publication?.title??system.source?.value??"").trim(),sourceSlug=sluggify(pubSource);pubSource&&publications.add(pubSource),spells.push({type:spellData.type,name:spellData.name,img:spellData.img,uuid:`Compendium.${pack.collection}.${spellData._id}`,rank:spellData.system.level.value,categories,time:spellData.system.time,actionGlyph,traditions:spellData.system.traits.traditions,traits:spellData.system.traits.value.map(t=>t.replace(/^hb_/,"")),rarity:spellData.system.traits.rarity,source:sourceSlug})}}this.indexData=spells,this.filterData.checkboxes.traditions.options=this.generateCheckboxOptions(CONFIG.PF2E.magicTraditions);for(let rank=1;rank<=10;rank++)this.filterData.checkboxes.rank.options[rank]={label:game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(rank)}),selected:!1};this.filterData.checkboxes.rarity.options=this.generateCheckboxOptions(CONFIG.PF2E.rarityTraits,!1),this.filterData.multiselects.traits.options=this.generateMultiselectOptions(omit(CONFIG.PF2E.spellTraits,Array.from(MAGIC_TRADITIONS))),this.filterData.checkboxes.source.options=this.generateSourceCheckboxOptions(publications),this.filterData.checkboxes.category.options=this.generateCheckboxOptions({spell:"TYPES.Item.spell",cantrip:"PF2E.TraitCantrip",focus:"PF2E.TraitFocus",ritual:"PF2E.Item.Spell.Ritual.Label"},!1),this.filterData.selects.timefilter.options=[...times].sort().reduce((result,time)=>({...result,[sluggify(time)]:time}),{}),console.debug("PF2e System | Compendium Browser | Finished loading spells")}filterIndexData(indexData){const{checkboxes,multiselects,selects}=this.filterData;return!(checkboxes.rank.selected.length>0&&!checkboxes.rank.selected.map(r=>Number(r)).includes(indexData.rank)||checkboxes.category.selected.length>0&&!equals(checkboxes.category.selected.sort(),indexData.categories.sort())||selects.timefilter.selected&&selects.timefilter.selected!==indexData.time.value||checkboxes.traditions.selected.length>0&&intersection(checkboxes.traditions.selected,indexData.traditions).length===0||!this.filterTraits(indexData.traits,multiselects.traits.selected,multiselects.traits.conjunction)||checkboxes.rarity.selected.length>0&&!checkboxes.rarity.selected.includes(indexData.rarity)||checkboxes.source.selected.length>0&&!checkboxes.source.selected.includes(indexData.source))}prepareFilterData(){return{checkboxes:{category:{isExpanded:!0,label:"PF2E.BrowserFilterSpellCategories",options:{},selected:[]},traditions:{isExpanded:!0,label:"PF2E.BrowserFilterTraditions",options:{},selected:[]},rank:{isExpanded:!0,label:"PF2E.Item.Spell.Rank.Plural",options:{},selected:[]},rarity:{isExpanded:!1,label:"PF2E.BrowserFilterRarities",options:{},selected:[]},source:{isExpanded:!1,label:"PF2E.BrowserFilterSource",options:{},selected:[]}},multiselects:{traits:{conjunction:"and",label:"PF2E.BrowserFilterTraits",options:[],selected:[]}},selects:{timefilter:{label:"PF2E.BrowserFilterCastingTime",options:{},selected:""}},order:{by:"rank",direction:"asc",options:{name:"Name",rank:"PF2E.Item.Spell.Rank.Label"}},search:{text:""}}}}class CompendiumBrowser extends Application{static{__name(this,"CompendiumBrowser")}static{__name2(this,"CompendiumBrowser")}settings;dataTabsList=["action","bestiary","campaignFeature","equipment","feat","hazard","spell"];navigationTab;tabs;packLoader=new PackLoader;constructor(options={}){super(options),this.settings=game.settings.get("pf2e","compendiumBrowserPacks"),this.navigationTab=this.hookTab(),this.tabs={action:new CompendiumBrowserActionTab(this),bestiary:new CompendiumBrowserBestiaryTab(this),campaignFeature:new CompendiumBrowserCampaignFeaturesTab(this),equipment:new CompendiumBrowserEquipmentTab(this),feat:new CompendiumBrowserFeatTab(this),hazard:new CompendiumBrowserHazardTab(this),spell:new CompendiumBrowserSpellTab(this)},this.initCompendiumList()}get title(){return game.i18n.localize("PF2E.CompendiumBrowser.Title")}static get defaultOptions(){return{...super.defaultOptions,id:"compendium-browser",classes:[],template:"systems/pf2e/templates/compendium-browser/compendium-browser.hbs",width:800,height:700,resizable:!0,dragDrop:[{dragSelector:"ul.item-list > li.item"}],tabs:[{navSelector:"nav",contentSelector:"section.content",initial:"landing-page"},{navSelector:"nav[data-group=settings]",contentSelector:".settings-container",initial:"packs"}],scrollY:[".control-area",".item-list",".settings-container"]}}async close(options){for(const tab of Object.values(this.tabs))tab.filterData.search.text="";await super.close(options)}hookTab(){const navigationTab=this._tabs[0],tabCallback=navigationTab.callback;return navigationTab.callback=async(event2,tabs,active)=>{tabCallback?.(event2,tabs,active),await this.loadTab(active)},navigationTab}initCompendiumList(){const settings={action:{},bestiary:{},campaignFeature:{},hazard:{},equipment:{},feat:{},spell:{}},loadDefault={bestiary:!0,hazard:!0,"pf2e.actionspf2e":!0,"pf2e.familiar-abilities":!0,"pf2e.equipment-srd":!0,"pf2e.ancestryfeatures":!0,"pf2e.classfeatures":!0,"pf2e.feats-srd":!0,"pf2e.spells-srd":!0,"pf2e.kingmaker-features":!0},browsableTypes=new Set(["action","campaignFeature","feat","kit","hazard","npc","spell",...PHYSICAL_ITEM_TYPES]),typeToTab=new Map([["action","action"],["campaignFeature","campaignFeature"],["feat","feat"],["kit","equipment"],["hazard","hazard"],["npc","bestiary"],["spell","spell"],...Array.from(PHYSICAL_ITEM_TYPES).map(t=>[t,"equipment"])]);for(const pack of game.packs){const tabNames=uniq(uniq(pack.index.map(entry=>entry.type)).filter(t=>setHasElement(browsableTypes,t)).flatMap(t=>typeToTab.get(t)??[]));for(const tabName of tabNames){const load=this.settings[tabName]?.[pack.collection]?.load??loadDefault[tabName]??!!loadDefault[pack.collection];settings[tabName][pack.collection]={load,name:pack.metadata.label,package:pack.metadata.packageName}}}for(const tab of this.dataTabsList)settings[tab]=Object.fromEntries(Object.entries(settings[tab]).sort(([_collectionA,dataA],[_collectionB,dataB])=>(dataA?.name??"")>(dataB?.name??"")?1:-1));this.settings=settings}async openTab(tabName,filter2){return this.activeTab=tabName,tabName!=="settings"&&filter2?this.tabs[tabName].open(filter2):this.loadTab(tabName)}async openActionTab(options){const actionTab=this.tabs.action,filter2=await actionTab.getFilterData(),{types}=filter2.checkboxes,{traits}=filter2.multiselects;types.selected=[];for(const type in types.options)options.types?.includes(type)&&(types.options[type].selected=!0,types.selected.push(type));const traitFilters=options.traits??[];if(traits.selected=traitFilters.length?traits.options.filter(trait=>traitFilters.includes(trait.value)):[],options.categories?.length){const optionsToSwitch=pick(filter2.checkboxes.category.options,options.categories);Object.values(optionsToSwitch).forEach(o=>o.selected=!0),filter2.checkboxes.category.selected=Object.keys(optionsToSwitch)}actionTab.open(filter2)}async openSpellTab(entry,maxRank=10,category=null){const spellTab=this.tabs.spell,filter2=await spellTab.getFilterData(),{traditions}=filter2.checkboxes;if(category&&filter2.checkboxes.category.options[category]&&(filter2.checkboxes.category.options[category].selected=!0,filter2.checkboxes.category.selected.push(category)),(entry.isRitual||entry.isFocusPool)&&(filter2.checkboxes.category.options[entry.category].selected=!0,filter2.checkboxes.category.selected.push(entry.category)),maxRank){const ranks=Array.from(Array(maxRank).keys()).map(l=>String(l+1));for(const rank of ranks)filter2.checkboxes.rank.options[rank].selected=!0,filter2.checkboxes.rank.selected.push(rank);(entry.isPrepared||entry.isSpontaneous||entry.isInnate)&&!category&&(filter2.checkboxes.category.options.spell.selected=!0,filter2.checkboxes.category.selected.push("spell"))}entry.tradition&&!entry.isFocusPool&&!entry.isRitual&&(traditions.options[entry.tradition].selected=!0,traditions.selected.push(entry.tradition)),spellTab.open(filter2)}async loadTab(tabName){if(this.activeTab=tabName,tabName==="settings"){await this.packLoader.updateSources(this.loadedPacksAll()),await this.render(!0);return}if(!this.dataTabsList.includes(tabName))throw ErrorPF2e(`Unknown tab "${tabName}"`);const currentTab=this.tabs[tabName];currentTab.isInitialized||await currentTab.init(),await this.render(!0,{focus:!0})}loadedPacks(tab){return tab==="settings"?[]:Object.entries(this.settings[tab]??[]).flatMap(([collection,info])=>info?.load?[collection]:[])}loadedPacksAll(){return uniq(this.dataTabsList.flatMap(t=>this.loadedPacks(t))).sort()}activateListeners($html){super.activateListeners($html);const html=$html[0],activeTabName=this.activeTab;if(this.navigationTab.active!==activeTabName&&this.navigationTab.activate(activeTabName),activeTabName==="settings"){const settings=htmlQuery(html,".compendium-browser-settings"),form=settings?.querySelector("form");if(!form)return;htmlQuery(settings,"button[data-action=save-settings]")?.addEventListener("click",async()=>{const formData=new FormData(form);for(const[t,packs]of Object.entries(this.settings))for(const[key,pack]of Object.entries(packs))pack.load=formData.has(`${t}-${key}`);await game.settings.set("pf2e","compendiumBrowserPacks",this.settings);for(const[key,source]of Object.entries(this.packLoader.sourcesSettings.sources)){if(!source?.name){delete this.packLoader.sourcesSettings.sources[key];continue}source.load=formData.has(`source-${key}`)}this.packLoader.sourcesSettings.showEmptySources=formData.has("show-empty-sources"),this.packLoader.sourcesSettings.showUnknownSources=formData.has("show-unknown-sources"),this.packLoader.sourcesSettings.ignoreAsGM=formData.has("ignore-as-gm"),await game.settings.set("pf2e","compendiumBrowserSources",this.packLoader.sourcesSettings),await this.#resetInitializedTabs(),this.render(!0),ui.notifications.info("PF2E.BrowserSettingsSaved",{localize:!0})});const sourceSearch=htmlQuery(form,"input[data-element=setting-sources-search]"),sourceToggle=htmlQuery(form,"input[data-action=setting-sources-toggle-visible]"),sourceSettings=htmlQueryAll(form,"label[data-element=setting-source]");sourceSearch?.addEventListener("input",()=>{const value=sourceSearch.value?.trim().toLocaleLowerCase(game.i18n.lang);for(const element of sourceSettings){const name2=element.dataset.name?.toLocaleLowerCase(game.i18n.lang),shouldBeHidden=!!value&&!!name2&&!name2.includes(value);element.classList.toggle("hidden",shouldBeHidden)}sourceToggle&&(sourceToggle.checked=!1)}),sourceToggle?.addEventListener("click",()=>{for(const element of sourceSettings){const checkbox=htmlQuery(element,"input[type=checkbox]");!element.classList.contains("hidden")&&checkbox&&(checkbox.checked=sourceToggle.checked)}}),htmlQuery(form,"button[data-action=settings-sources-delete]")?.addEventListener("click",async()=>{const localize=localizer("PF2E.SETTINGS.CompendiumBrowserSources");await Dialog.confirm({title:localize("DeleteAllTitle"),content:`