From 897c5745bc3290c3f559acb12780355b3e3316ed Mon Sep 17 00:00:00 2001 From: dingo Date: Wed, 9 Sep 2026 18:15:17 -0400 Subject: [PATCH] Add spells, weapon abilities, and durable corpse resurrection --- client/src/character-stats.ts | 4 +- client/src/content-editor.ts | 42 ++- client/src/generated.ts | 81 +++++ client/src/input-actions.ts | 39 +-- client/src/input-controls.ts | 46 +++ client/src/main.ts | 22 +- client/src/menu-focus.ts | 6 + client/src/player-content.ts | 3 +- client/src/power-panel.ts | 28 ++ client/src/style.css | 2 + docs/ARCHITECTURE.md | 21 +- docs/MILESTONE-7.md | 138 +++++++++ planning/PLAYWRIGHT-TODO.md | 3 + planning/SYSTEMS-ROADMAP.md | 32 +- planning/VISION.md | 10 +- schemas/protocol.json | 108 ++++++- server/content/balance.yaml | 9 + server/content/combat.go | 3 + server/content/content.go | 8 +- server/content/crafting.go | 3 + server/content/powers.go | 182 +++++++++++ server/content/powers_test.go | 34 +++ server/content/stats.go | 7 +- server/internal/game/admin_content.go | 6 + server/internal/game/combat.go | 21 +- server/internal/game/crafting_test.go | 2 +- server/internal/game/equipment.go | 10 +- server/internal/game/equipment_test.go | 2 +- server/internal/game/powers.go | 370 +++++++++++++++++++++++ server/internal/game/powers_test.go | 208 +++++++++++++ server/internal/game/revival.go | 91 ++++++ server/internal/game/stats.go | 12 +- server/internal/game/world.go | 60 +++- server/internal/game/world_test.go | 2 +- server/internal/protocol/generated.go | 145 +++++++-- server/internal/store/catalog.go | 17 +- server/internal/store/catalog_preview.go | 31 ++ server/internal/store/crafting.go | 2 +- server/internal/store/life_migration.go | 46 +++ server/internal/store/portal.go | 11 + server/internal/store/revival.go | 154 ++++++++++ server/internal/store/revival_test.go | 216 +++++++++++++ server/internal/store/store.go | 9 +- server/internal/store/titles.go | 2 + server/internal/store/travel.go | 2 + server/internal/store/travel_test.go | 14 +- server/internal/transport/http.go | 1 + server/internal/transport/http_test.go | 12 + server/internal/transport/powers.go | 137 +++++++++ 49 files changed, 2277 insertions(+), 137 deletions(-) create mode 100644 client/src/input-controls.ts create mode 100644 client/src/power-panel.ts create mode 100644 docs/MILESTONE-7.md create mode 100644 server/content/powers.go create mode 100644 server/content/powers_test.go create mode 100644 server/internal/game/powers.go create mode 100644 server/internal/game/powers_test.go create mode 100644 server/internal/game/revival.go create mode 100644 server/internal/store/life_migration.go create mode 100644 server/internal/store/revival.go create mode 100644 server/internal/store/revival_test.go create mode 100644 server/internal/transport/powers.go diff --git a/client/src/character-stats.ts b/client/src/character-stats.ts index e81569f..1034412 100644 --- a/client/src/character-stats.ts +++ b/client/src/character-stats.ts @@ -26,7 +26,9 @@ export function statsBreakdown(c:Character) { for(const [name,v] of [['Level',g.levelValue],['Yield %',g.yield],['Speed %',g.speed],['XP %',g.experience]] as const){const row=body.insertRow();row.append(node('th',name));for(const text of [numberText(v.base),signed(v.flat),`${signed(v.percent)}%`,numberText(v.final)])row.insertCell().textContent=text;} } for(const p of Object.values(c.crafting??{})){const row=body.insertRow();const th=node('th',`${p.name}: level ${p.level} · ${p.xp} XP · ${p.xpToNextLevel} to next`);th.colSpan=5;row.append(th);} - wrapper.append(table);for(const effect of c.gatheringEffects??[]){wrapper.append(node('p',`${effect.name} · expires ${new Date(effect.expiresAt*1000).toLocaleTimeString()}`),modifiersView(effect.modifiers));}return wrapper; + for(const v of Object.values(c.weapons??{})){const row=body.insertRow();const th=node('th',`${v.name}: level ${v.level} · ${v.xp} XP`);th.colSpan=5;row.append(th)} + for(const v of Object.values(c.powers??{})){const row=body.insertRow();const th=node('th',`${v.definition.name}: rank ${v.level} · ${v.xp} XP`);th.colSpan=5;row.append(th)} + wrapper.append(table);for(const effect of c.gatheringEffects??[]){wrapper.append(node('p',`${effect.name} · expires ${new Date(effect.expiresAt*1000).toLocaleTimeString()}`),modifiersView(effect.modifiers));}return wrapper; } export function itemDetails(item:ItemInstance,c:Character) { const card=node('article','','gear-card'); diff --git a/client/src/content-editor.ts b/client/src/content-editor.ts index 0c9248a..3ed7219 100644 --- a/client/src/content-editor.ts +++ b/client/src/content-editor.ts @@ -9,7 +9,7 @@ function craftPool(){return repeat('Available crafted stats','Add pos const group=node('div','','catalog-fields'),stat=select(statKeys,value?.stat),min=number(value?.min??1,-1000000),max=number(value?.max??5,-1000000),weight=number(value?.weight??1,.01,1000),percent=node('input');percent.type='checkbox';percent.checked=value?.percent??false; group.append(field('Stat',stat),field('Minimum roll',min),field('Maximum roll',max),field('Selection weight',weight),field('Percentage modifier',percent)); return {node:group,read:()=>({stat:stat.value,min:Number(min.value),max:Number(max.value),weight:Number(weight.value),percent:percent.checked})};},[],32);} -function craftMaterials(){return [...['axe','flint_and_steel','fishing_pole','wood','ore','herb','bandage','escape_stone'].map(id=>({id,name:statLabel(id)})),...(catalog.gathering?.resources??[]).filter(r=>r.output==='self'),...(catalog.gathering?.consumables??[]),...(catalog.crafting?.materials??[])];} +function craftMaterials(){return [...['axe','flint_and_steel','fishing_pole','wood','ore','herb','bandage','escape_stone'].map(id=>({id,name:statLabel(id)})),...(catalog.gathering?.resources??[]).filter(r=>r.output==='self'),...(catalog.gathering?.consumables??[]),...(catalog.crafting?.materials??[]),{id:'revival_stone',name:'Revival stone'},...(catalog.powers?.powers??[]).filter(p=>p.book).map(p=>({id:'book_'+p.id,name:p.name+' spell book'}))];} function recipeForm(initial?:CraftRecipe){ if(editing||saving){show('Finish or cancel the open draft first.');return;} const values=identity(initial),profession=contentChoice(catalog.crafting?.professions??[],initial?.profession),level=number(initial?.level??1,1,1000,'1'),xp=number(initial?.xp??20,1,1000000,'1'); @@ -41,7 +41,7 @@ const statKeys=[...primaryStats,...derivedStats],metrics=['level','kills','world const root=node('section','','catalog-editor'),header=node('div','','catalog-heading'),version=node('p'),tabs=node('div','','catalog-tabs'),list=node('div','','catalog-list'),forms=node('div'),message=node('p','','message'); const refresh=button('Refresh catalog',()=>void load());header.append(node('h2','Game content'),version,refresh);message.hidden=true;message.setAttribute('role','status');root.append(header,message,tabs,list,forms); let catalog:Catalog,changes:Audit[]=[],section='titles',editing=false,loading=false,saving=false; -for(const [key,label] of [['titles','Titles'],['items','Equipment'],['requirements','Requirement sets'],['effects','Effect sets'],['gathering','Gathering'],['resources','Resources'],['biomes','Biomes'],['consumables','Consumables'],['attacks','Attacks'],['mobs','Mobs'],['loot','Loot tables'],['spawns','Mob spawns'],['craft-recipes','Recipes'],['craft-professions','Crafting professions'],['craft-materials','Crafting materials'],['craft-rules','Crafting tuning'],['stats','Stat formulas'],['audit','Content audit']]){const b=button(label,()=>{if(editing||saving){show('Finish or cancel the open draft first.');return;}section=key;render()});b.dataset.section=key;tabs.append(b);} +for(const [key,label] of [['titles','Titles'],['items','Equipment'],['requirements','Requirement sets'],['effects','Effect sets'],['gathering','Gathering'],['resources','Resources'],['biomes','Biomes'],['consumables','Consumables'],['attacks','Attacks'],['mobs','Mobs'],['loot','Loot tables'],['spawns','Mob spawns'],['powers','Spells and abilities'],['weapons','Weapon types'],['craft-recipes','Recipes'],['craft-professions','Crafting professions'],['craft-materials','Crafting materials'],['craft-rules','Crafting tuning'],['stats','Stat formulas'],['audit','Content audit']]){const b=button(label,()=>{if(editing||saving){show('Finish or cancel the open draft first.');return;}section=key;render()});b.dataset.section=key;tabs.append(b);} function button(text:string,fn:()=>void){const b=node('button',text,'button secondary');b.type='button';b.onclick=fn;return b;} function show(text:string){message.textContent=text;message.hidden=false;} function field(label:string,input:HTMLElement){const wrap=node('label',label);wrap.append(input);return wrap;} @@ -96,7 +96,7 @@ function form(title:string,op:string,payload:()=>object){ } function previewView(result:ContentPreview){ const root=node('div'),r=result.resolved;root.append(node('h4','Validated publication preview'),node('p',`Version ${result.basedOnVersion} → ${result.proposedVersion}. Nothing has been published.`)); - const definition=r.craftRecipe??r.craftProfession??r.craftMaterial??r.title??r.item??r.requirementSet??r.effectSet??r.gatheringSkill??r.resource??r.biome??r.consumable??r.attack??r.mob??r.loot??r.spawn; + const definition=r.power??r.weapon??r.craftRecipe??r.craftProfession??r.craftMaterial??r.title??r.item??r.requirementSet??r.effectSet??r.gatheringSkill??r.resource??r.biome??r.consumable??r.attack??r.mob??r.loot??r.spawn; if(definition)root.append(node('strong',definition.name),node('p',definition.description),node('p',r.targetId?`Revision ${r.biome?.revision??r.craftRecipe?.revision} of the existing definition`:'Permanent ID assigned on publication.','muted')); const requirements=r.title?.requirements??r.requirementSet?.requirements; if(requirements)root.append(node('p',requirements.map(v=>`${statLabel(v.metric)} ≥ ${v.atLeast}`).join(' / '))); @@ -104,7 +104,8 @@ function previewView(result:ContentPreview){ const modifiers=r.title?.effects.modifiers??r.item?.modifiers??r.effectSet?.modifiers;if(modifiers)root.append(modifiersView(modifiers)); if(r.item?.craftPool?.length)root.append(node('p',`${r.item.craftRolls??0} random stat rolls per crafted item`),readableDefinition(r.item.craftPool)); if(r.gatheringSkill||r.resource||r.biome||r.consumable||r.attack||r.mob||r.loot||r.spawn)root.append(readableDefinition(r.gatheringSkill??r.resource??r.biome??r.consumable??r.attack??r.mob??r.loot??r.spawn)); - if(r.craftRecipe||r.craftProfession||r.craftMaterial||r.craftRules)root.append(readableDefinition(r.craftRecipe??r.craftProfession??r.craftMaterial??r.craftRules)); + if(r.power||r.weapon)root.append(readableDefinition(r.power??r.weapon)); + if(r.craftRecipe||r.craftProfession||r.craftMaterial||r.craftRules)root.append(readableDefinition(r.craftRecipe??r.craftProfession??r.craftMaterial??r.craftRules)); if(r.stats){root.append(node('p','Validated base values and primary-to-derived coefficients.'));const details=node('details');details.append(node('summary','Review stat formulas'),readableDefinition(r.stats));root.append(details);} return root; } @@ -119,13 +120,14 @@ function titleForm(){ function itemForm(){ if(editing||saving){show('Finish or cancel the open draft first.');return;} const pool=craftPool(),rolls=number(0,0,8,'1'); + const weaponType=contentChoice([{id:'',name:'No proficiency'},...(catalog.powers?.weapons??[])]);weaponType.required=false; const values=identity(),slot=select(itemSlots,'weapon'),weight=number(1,0,10000),drop=number(0,0,100),level=number(1,1,10000,'1'),effects=modifiers(); const requirements=repeat<{stat:string;value:number}>('Required stats','Add required stat',value=>{const group=node('div','','catalog-fields'),stat=select([...statKeys,'gatheringLevel','gatheringYield','gatheringSpeed','gatheringXP'],value?.stat),minimum=number(value?.value??1);group.append(field('Stat',stat),field('Minimum value',minimum));return {node:group,read:()=>({stat:stat.value,value:Number(minimum.value)})}},[],statKeys.length); const titles=node('fieldset','','catalog-title-choices');titles.append(node('legend','Required titles'));const checks=(catalog.titles??[]).map(t=>{const input=node('input');input.type='checkbox';titles.append(field(t.name,input));return {id:t.id,input}}); const sets=setChoices(true); const attack=contentChoice([{id:'',name:'Basic melee / none'},...(catalog.combat?.attacks??[])]);attack.required=false; - const fields=form('Create equipment','create-item',()=>{const req=requirements.read();if(new Set(req.map(r=>r.stat)).size!==req.length)throw new Error('Each required stat can appear once.');return {...sets.read(),item:{...values.read(),craftPool:pool.read(),craftRolls:Number(rolls.value),slot:slot.value,...(slot.value==='weapon'&&attack.value?{attackId:attack.value}:{}),weight:Number(weight.value),dropChance:Number(drop.value),requirements:{level:Number(level.value),stats:Object.fromEntries(req.map(r=>[r.stat,r.value])),titles:checks.filter(c=>c.input.checked).map(c=>c.id)},modifiers:effects.read()}}}); - fields.append(values.node,field('Equipment slot',slot),field('Weapon attack profile',attack),field('Weight',weight),field('Sentinel drop chance (%)',drop),node('p','Zero disables sentinel drops. Drop-rate bonuses apply. Requirements are checked without equipment bonuses.','muted'),sets.node,field('Required level',level),requirements.node,titles,effects.node,field('Stats rolled when crafted',rolls),pool.node); + const fields=form('Create equipment','create-item',()=>{const req=requirements.read();if(new Set(req.map(r=>r.stat)).size!==req.length)throw new Error('Each required stat can appear once.');return {...sets.read(),item:{...values.read(),weaponType:weaponType.value,craftPool:pool.read(),craftRolls:Number(rolls.value),slot:slot.value,...(slot.value==='weapon'&&attack.value?{attackId:attack.value}:{}),weight:Number(weight.value),dropChance:Number(drop.value),requirements:{level:Number(level.value),stats:Object.fromEntries(req.map(r=>[r.stat,r.value])),titles:checks.filter(c=>c.input.checked).map(c=>c.id)},modifiers:effects.read()}}}); + fields.append(values.node,field('Equipment slot',slot),field('Weapon attack profile',attack),field('Weapon proficiency',weaponType),field('Weight',weight),field('Sentinel drop chance (%)',drop),node('p','Zero disables sentinel drops. Drop-rate bonuses apply. Requirements are checked without equipment bonuses.','muted'),sets.node,field('Required level',level),requirements.node,titles,effects.node,field('Stats rolled when crafted',rolls),pool.node); } function statsForm(){ if(editing||saving){show('Finish or cancel the open draft first.');return;} @@ -136,7 +138,8 @@ function statsForm(){ } function render(){ version.textContent=`Catalog version ${catalog.version}`;for(const b of tabs.querySelectorAll('button'))b.setAttribute('aria-pressed',String(b.dataset.section===section));list.replaceChildren(); - if(section.startsWith('craft-')){craftingList(); + if(section==='powers'||section==='weapons'){powerList(); + }else if(section.startsWith('craft-')){craftingList(); }else if(['attacks','mobs','loot','spawns'].includes(section)){combatList(); }else if(['gathering','resources','biomes','consumables'].includes(section)){gatheringList(); }else if(section==='titles'){ @@ -163,7 +166,7 @@ function contentChoice(values:{id:string;name:string}[],initial?:string) { } function readableDefinition(value:unknown, context=''):HTMLElement { - const names = [...catalog.items,...catalog.titles,...(catalog.gathering?.skills??[]),...(catalog.gathering?.resources??[]),...(catalog.gathering?.biomes??[]),...(catalog.gathering?.consumables??[]),...(catalog.combat?.attacks??[]),...(catalog.combat?.mobs??[]),...(catalog.combat?.loot??[]),...(catalog.crafting?.professions??[]),...(catalog.crafting?.materials??[])]; + const names = [...catalog.items,...catalog.titles,...(catalog.gathering?.skills??[]),...(catalog.gathering?.resources??[]),...(catalog.gathering?.biomes??[]),...(catalog.gathering?.consumables??[]),...(catalog.combat?.attacks??[]),...(catalog.combat?.mobs??[]),...(catalog.combat?.loot??[]),...(catalog.crafting?.professions??[]),...(catalog.crafting?.materials??[]),...(catalog.powers?.weapons??[]),...(catalog.powers?.powers??[])]; const reference=(v:string)=>names.find(n=>n.id===v)?.name??statLabel(v); if(Array.isArray(value)) { const list=node('ul','','catalog-values'); @@ -238,7 +241,7 @@ function combatForm(kind:string){ const fields=form('Create mob','create-mob',()=>({mob:{...values.read(),model:model.value,behavior:behavior.value,attackId:attack.value,lootId:loot.value,...Object.fromEntries(inputs.map(v=>[v.key,Number(v.input.value)]))}})); fields.append(values.node,field('Model preset',model),field('Behavior',behavior),field('Attack profile',attack),field('Loot table',loot),...inputs.map(v=>field(v.label,v.input)),node('p','Health/power = base × level × (1 + world age in days × scaling). Defence is flat. Aggressive creatures pursue within the leash; guards defend their detection radius; passive creatures retaliate only when attacked. Models remain placeholders until milestone 4.5.','muted')); }else if(kind==='loot'){ - const items=[...catalog.items,...(catalog.crafting?.materials??[]),...(catalog.gathering?.consumables??[]),...(catalog.gathering?.resources??[]).filter(r=>r.output==='self'),...['wood','ore','herb','bandage','escape_stone','axe','flint_and_steel','fishing_pole'].map(id=>({id,name:statLabel(id)}))]; + const items=[...catalog.items,...craftMaterials()]; const entries=repeat('Loot entries','Add loot entry',()=>{const group=node('div','','catalog-fields'),item=contentChoice(items),amount=number(1,1,100,'1'),chance=number(100,0,100),pool=text('',40),weight=number(1,1,10000,'1');pool.required=false;group.append(field('Item',item),field('Quantity',amount),field('Drop chance (%)',chance),field('Weighted group (blank = independent)',pool),field('Group weight',weight));return{node:group,read:()=>({item:item.value,amount:Number(amount.value),chance:Number(chance.value),group:pool.value.trim(),weight:Number(weight.value)})}},[],32); const fields=form('Create loot table','create-loot',()=>({loot:{...values.read(),entries:entries.read()}}));fields.append(values.node,entries.node,node('p','Blank groups roll independently; 100% is guaranteed. Each named group selects one entry by weight, then rolls that entry’s chance. Finisher luck affects non-guaranteed chances. New mobs leave a lootable corpse; the corpse is shared and may be looted by nearby players.','muted')); }else{ @@ -253,3 +256,24 @@ function combatList(){ list.append(button(`Create ${labels[section]}`,()=>combatForm(section))); for(const v of entries??[]){const d=node('details','','catalog-definition');d.append(node('summary',v.name),node('p',v.description),readableDefinition(v));list.append(d)} } + +function powerList(){ + const p=catalog.powers;if(!p)return; + if(section==='weapons'){ + list.append(button('Create weapon type',()=>{if(editing||saving)return;const values=identity(),base=number(100,1,1000000,'1'),per=number(50,1,1000000,'1'),max=number(1000,1,1000,'1');form('Create weapon type','create-weapon',()=>({weapon:{...values.read(),baseXp:Number(base.value),xpPerLevel:Number(per.value),maxLevel:Number(max.value)}})).append(values.node,field('XP to level 2',base),field('Additional XP per level',per),field('Maximum level',max));})); + for(const w of p.weapons){const d=node('details','','catalog-definition');d.append(node('summary',w.name),readableDefinition(w));list.append(d)}return; + } + list.append(button('Create spell or ability',powerForm)); + for(const v of p.powers){const d=node('details','','catalog-definition');d.append(node('summary',v.name+' · '+v.kind),node('p',v.description),readableDefinition(v));if(v.book)d.append(node('p','Teach using '+v.name+' spell book, available in player item controls and loot tables.'));list.append(d)} +} +function powerForm(){ + if(editing||saving)return; + const values=identity(),kind=select(['spell','ability']),attack=contentChoice(catalog.combat?.attacks??[]),targeting=select(['target','self','aura']),weapon=contentChoice([{id:'',name:'None'},...(catalog.powers?.weapons??[])]);weapon.required=false; + const resurrection=node('input'),book=node('input');resurrection.type=book.type='checkbox';book.checked=true; + const basePower=number(10,0,100000),weaponLevel=number(1,1,1000,'1'),level=number(1,1,1000,'1'),mana=number(5,0,10000),cast=number(0,0,30),cooldown=number(2,.1,120),scaling=number(.03,0,1),base=number(100,1,1000000,'1'),per=number(50,1,1000000,'1'),max=number(1000,1,1000,'1'); + const stats=repeat<{stat:string;minimum:number}>('Required stats without equipment','Add requirement',v=>{const group=node('div','','catalog-fields'),stat=select(statKeys,v?.stat),minimum=number(v?.minimum??1,0,1000000);group.append(field('Stat',stat),field('Minimum',minimum));return {node:group,read:()=>({stat:stat.value,minimum:Number(minimum.value)})}},[],32); + const parents=repeat<{id:string;rank:number}>('Predecessor spells (all required)','Add predecessor',v=>{const group=node('div','','catalog-fields'),id=contentChoice((catalog.powers?.powers??[]).filter(p=>p.kind==='spell'),v?.id),rank=number(v?.rank??2,1,1000,'1');group.append(field('Spell',id),field('Required rank',rank));return {node:group,read:()=>({id:id.value,rank:Number(rank.value)})}},[],16); + const titles=node('fieldset','','catalog-title-choices');titles.append(node('legend','Required titles'));const checks=catalog.titles.map(t=>{const input=node('input');input.type='checkbox';titles.append(field(t.name,input));return {id:t.id,input}}); + const fields=form('Create spell or ability','create-power',()=>{const r=stats.read(),pre=parents.read();if(new Set(r.map(v=>v.stat)).size!==r.length||new Set(pre.map(v=>v.id)).size!==pre.length)throw new Error('Requirements must not repeat.');return {power:{...values.read(),kind:kind.value,attackId:resurrection.checked?'':attack.value,targeting:resurrection.checked?'target':targeting.value,resurrection:resurrection.checked,weapon:kind.value==='ability'?weapon.value:'',weaponLevel:Number(weaponLevel.value),requirements:{level:Number(level.value),stats:Object.fromEntries(r.map(v=>[v.stat,v.minimum])),titles:checks.filter(v=>v.input.checked).map(v=>v.id)},parents:kind.value==='ability'?{}:Object.fromEntries(pre.map(v=>[v.id,v.rank])),book:kind.value==='spell'&&book.checked,mana:Number(mana.value),castSeconds:resurrection.checked?0:Number(cast.value),cooldown:Number(cooldown.value),basePower:Number(basePower.value),rankScaling:Number(scaling.value),baseXp:Number(base.value),xpPerLevel:Number(per.value),maxLevel:kind.value==='ability'?1:Number(max.value)}}}); + fields.append(values.node,field('Kind',kind),field('Combat effect profile',attack),field('Targeting',targeting),field('Corpse resurrection (instant, adjacent, consent required)',resurrection),field('Learn from a consumable spell book',book),field('Weapon type for ability',weapon),field('Weapon level required',weaponLevel),field('Character level required',level),stats.node,titles,parents.node,field('Base effect power',basePower),field('Mana cost',mana),field('Cast time (seconds)',cast),field('Cooldown (seconds)',cooldown),field('Power increase per rank (0.03 = 3%)',scaling),field('XP to rank 2',base),field('Additional XP per rank',per),field('Maximum spell rank',max),node('p','A spell without a book automatically unlocks from its predecessor requirements. Abilities require the matching equipped weapon. Existing learned powers retain their definition. Aura profiles require a melee delivery, radius, and duration.','muted')); +} diff --git a/client/src/generated.ts b/client/src/generated.ts index d5007c3..2d43ddc 100644 --- a/client/src/generated.ts +++ b/client/src/generated.ts @@ -16,6 +16,7 @@ export interface ContentCatalog { effectSets?: EffectSet[]; gathering?: GatheringContent; items: ItemDefinition[]; + powers?: PowerContent; requirementSets?: RequirementSet[]; stats: ContentStatsRules; titles: TitleDefinition[]; @@ -213,6 +214,7 @@ export interface ItemDefinition { name: string; requirements: ItemRequirements; slot: string; + weaponType?: string; weight: number; } @@ -230,6 +232,38 @@ export interface ItemRequirements { titles: string[]; } +export interface PowerContent { + powers: PowerDefinition[]; + revivalHealth: number; + revivalRange: number; + spellXp: number; + weaponXp: number; + weapons: GatheringSkill[]; +} + +export interface PowerDefinition { + attackId: string; + basePower: number; + baseXp: number; + book: boolean; + castSeconds: number; + cooldown: number; + description: string; + id: string; + kind: string; + mana: number; + maxLevel: number; + name: string; + parents: { [key: string]: number }; + rankScaling: number; + requirements: ItemRequirements; + resurrection: boolean; + targeting: string; + weapon: string; + weaponLevel: number; + xpPerLevel: number; +} + export interface RequirementSet { description: string; id: string; @@ -280,6 +314,7 @@ export interface ContentChange { loot?: LootTableDraft; mob?: MobDefinitionDraft; op: string; + power?: PowerDraft; reason: string; requirementSet?: RequirementSetDraft; requirementSetIds?: string[]; @@ -288,6 +323,7 @@ export interface ContentChange { stats?: ContentStatsRules; targetId?: string; title?: TitleDraft; + weapon?: GatheringSkillDraft; } export interface CombatAttackDraft { @@ -374,6 +410,7 @@ export interface ItemDraft { name: string; requirements: ItemRequirements; slot: string; + weaponType?: string; weight: number; } @@ -403,6 +440,29 @@ export interface MobDefinitionDraft { xp: number; } +export interface PowerDraft { + attackId: string; + basePower: number; + baseXp: number; + book: boolean; + castSeconds: number; + cooldown: number; + description: string; + id?: string; + kind: string; + mana: number; + maxLevel: number; + name: string; + parents: { [key: string]: number }; + rankScaling: number; + requirements: ItemRequirements; + resurrection: boolean; + targeting: string; + weapon: string; + weaponLevel: number; + xpPerLevel: number; +} + export interface RequirementSetDraft { description: string; id?: string; @@ -564,6 +624,7 @@ export interface Character { allocatedStats: { [key: string]: number }; attack?: CombatAttack; carryWeight: number; + casting?: string; consumables?: GatheringConsumable[]; craftedStacks?: CraftedStack[]; crafting?: { [key: string]: CraftProgress }; @@ -585,6 +646,7 @@ export interface Character { manaChoices: number; pendingVitalChoices: number; playedSeconds: number; + powers?: { [key: string]: LearnedPower }; remainingSeconds: number; skills: { [key: string]: number }; stackNames?: { [key: string]: string }; @@ -592,6 +654,7 @@ export interface Character { statPoints: number; stats: { [key: string]: StatValue }; titles: TitleAward[]; + weapons?: { [key: string]: WeaponProgress }; } export interface CraftedStack { @@ -659,9 +722,19 @@ export interface ItemInstance { requirementMessage: string; requirements: ItemRequirements; slot: string; + weaponType?: string; weight: number; } +export interface LearnedPower { + attack: CombatAttack; + definition: PowerDefinition; + level: number; + readyAt: number; + xp: number; + xpToNextLevel: number; +} + export interface TitleAward { description: string; earnedAt: string; @@ -672,6 +745,14 @@ export interface TitleAward { worldId: string; } +export interface WeaponProgress { + id: string; + level: number; + name: string; + xp: number; + xpToNextLevel: number; +} + export interface WorldInfo { ageSeconds: number; bossHp: number; diff --git a/client/src/input-actions.ts b/client/src/input-actions.ts index f75ea80..9233c3c 100644 --- a/client/src/input-actions.ts +++ b/client/src/input-actions.ts @@ -1,37 +1,2 @@ -export type InputAction = 'north' | 'south' | 'west' | 'east' | 'attack' | 'gather' | 'inventory' | 'heal' | 'return' | 'jump'; -const bindings: Readonly> = { - KeyW:'north', ArrowUp:'north', KeyS:'south', ArrowDown:'south', KeyA:'west', ArrowLeft:'west', - KeyD:'east', ArrowRight:'east', Space:'jump', KeyF:'attack', KeyE:'gather', KeyI:'inventory' -}; -export function isEditing(target: EventTarget | null) { - return target instanceof HTMLElement && !!target.closest('input,select,textarea,[contenteditable]:not([contenteditable="false"])'); -} - -// Physical input is separate from gameplay intents. Rebinding/controller mapping -// can feed these same actions later without changing authoritative game commands. -export class InputActions { - private held = new Map(); - constructor(private blocked: () => boolean, private onAction: (action: InputAction) => void) { - window.addEventListener('keydown', event => { - const action = bindings[event.code]; - if (!action || event.defaultPrevented || event.ctrlKey || event.metaKey || event.altKey || isEditing(event.target) || blocked()) return; - event.preventDefault(); - if (['north','south','west','east'].includes(action)) this.held.set(event.code, action); - else if (!event.repeat) this.trigger(action); - }); - window.addEventListener('keyup', event => this.held.delete(event.code)); - window.addEventListener('blur', () => this.clear()); - document.addEventListener('visibilitychange', () => { if (document.hidden) this.clear(); }); - document.addEventListener('focusin', event => { if (isEditing(event.target) || blocked()) this.clear(); }); - } - trigger(action: InputAction) { if (!this.blocked()) this.onAction(action); } - press(source: string, action: InputAction) { if (!this.blocked()) this.held.set(source, action); } - release(source: string) { this.held.delete(source); } - clear() { this.held.clear(); } - get keys() { return [...this.held.keys()]; } - get movement() { - if (this.blocked()) { this.clear(); return {x:0,z:0}; } - const actions = new Set(this.held.values()); - return {x:Number(actions.has('east'))-Number(actions.has('west')), z:Number(actions.has('south'))-Number(actions.has('north'))}; - } -} +export { InputActions, isEditing, actionNames } from './input-controls'; +export type { InputAction } from './input-controls'; diff --git a/client/src/input-controls.ts b/client/src/input-controls.ts new file mode 100644 index 0000000..10713a0 --- /dev/null +++ b/client/src/input-controls.ts @@ -0,0 +1,46 @@ +export type InputAction = 'north'|'south'|'west'|'east'|'attack'|'gather'|'inventory'|'heal'|'return'|'jump'|'next-target'|'previous-target'|'cancel-cast'|'slot1'|'slot2'|'slot3'|'slot4'|'slot5'|'slot6'|'slot7'|'slot8'; +export const actionNames:InputAction[]=['north','south','west','east','attack','gather','inventory','heal','return','jump','next-target','previous-target','cancel-cast','slot1','slot2','slot3','slot4','slot5','slot6','slot7','slot8']; +const defaults:Record={KeyW:'north',ArrowUp:'north',KeyS:'south',ArrowDown:'south',KeyA:'west',ArrowLeft:'west',KeyD:'east',ArrowRight:'east',Space:'jump',KeyF:'attack',KeyE:'gather',KeyI:'inventory',KeyQ:'previous-target',KeyR:'next-target',KeyX:'cancel-cast',Digit1:'slot1',Digit2:'slot2',Digit3:'slot3',Digit4:'slot4',Digit5:'slot5',Digit6:'slot6',Digit7:'slot7',Digit8:'slot8'}; +const padDefaults:Record={'0':'jump','1':'gather','2':'attack','3':'heal','4':'previous-target','5':'next-target','6':'slot1','7':'slot2','9':'inventory','12':'slot3','13':'slot4','14':'slot5','15':'slot6'}; +export function isEditing(target:EventTarget|null){return target instanceof HTMLElement&&!!target.closest('input,select,textarea,[contenteditable]:not([contenteditable="false"])');} +const valid=(a:unknown):a is InputAction=>typeof a==='string'&&actionNames.includes(a as InputAction); +import { closeFocusedMenu } from './menu-focus'; +export class InputActions { + private held=new Map(); + private bindings={...defaults};private padBindings={...padDefaults};private padPressed=new Set(); + private padX=0;private padZ=0; + constructor(private blocked:()=>boolean,private onAction:(action:InputAction)=>void){ + try{const data=JSON.parse(localStorage.getItem('aeternalis.controls.v1')??'null');if(data){this.bindings={};this.padBindings={};for(const [code,a] of Object.entries(data.keyboard??{}))if(valid(a)&&code!=='Escape')this.bindings[code]=a;for(const [code,a] of Object.entries(data.gamepad??{}))if(valid(a)&&/^\d+$/.test(code)&&Number(code)<32)this.padBindings[code]=a;}}catch{/* Defaults remain usable when storage is unavailable. */} + window.addEventListener('keydown',e=>{const a=this.bindings[e.code];if(!a||e.defaultPrevented||e.ctrlKey||e.metaKey||e.altKey||isEditing(e.target)||blocked())return;e.preventDefault();if(['north','south','west','east'].includes(a))this.held.set(e.code,a);else if(!e.repeat)this.trigger(a);}); + window.addEventListener('keyup',e=>this.held.delete(e.code));window.addEventListener('blur',()=>this.clear()); + document.addEventListener('visibilitychange',()=>{if(document.hidden)this.clear()});document.addEventListener('focusin',e=>{if(isEditing(e.target)||blocked())this.clear()}); + } + trigger(action:InputAction){if(!this.blocked()&&!document.hidden)this.onAction(action)} + press(source:string,action:InputAction){if(!this.blocked())this.held.set(source,action)} + release(source:string){this.held.delete(source)} + clear(){this.held.clear();this.padX=this.padZ=0} + get keys(){return [...this.held.keys()]} + pollController(){ + this.padX=this.padZ=0;const pressed=new Set();const pad=navigator.getGamepads?.().find(p=>p?.connected);if(!pad){this.padPressed=pressed;return} + const blocked=this.blocked()||document.hidden||!document.hasFocus(); + if(!blocked){this.padX=Math.abs(pad.axes[0]??0)>.2?pad.axes[0]:0;this.padZ=Math.abs(pad.axes[1]??0)>.2?pad.axes[1]:0} + pad.buttons.forEach((b,i)=>{if(!b.pressed)return;const key=String(i);pressed.add(key);const action=this.padBindings[key];if(blocked&&!document.hidden&&document.hasFocus()&&!this.padPressed.has(key))this.menuButton(i);if(action&&!blocked){if(action==='east')this.padX=1;else if(action==='west')this.padX=-1;else if(action==='north')this.padZ=-1;else if(action==='south')this.padZ=1;else if(!this.padPressed.has(key))this.trigger(action)}});this.padPressed=pressed; + } + get movement(){if(this.blocked()){this.clear();return{x:0,z:0}};const a=new Set(this.held.values());return{x:Math.max(-1,Math.min(1,Number(a.has('east'))-Number(a.has('west'))+this.padX)),z:Math.max(-1,Math.min(1,Number(a.has('south'))-Number(a.has('north'))+this.padZ))}} + private menuButton(i:number){ + if(i===1||i===9){closeFocusedMenu();return} + const focused=document.activeElement as HTMLElement|null,menu=focused?.closest('.panel,dialog,form');if(!menu)return; + const options=[...menu.querySelectorAll('button:not([disabled]),input:not([disabled]),select:not([disabled]),summary,a[href]')].filter(e=>e.getClientRects().length>0); + if(i===12||i===13){const at=options.indexOf(focused!);options[(at+(i===13?1:options.length-1)+options.length)%options.length]?.focus();return} + if((i===14||i===15)&&focused instanceof HTMLSelectElement){focused.selectedIndex=Math.max(0,Math.min(focused.options.length-1,focused.selectedIndex+(i===15?1:-1)));focused.dispatchEvent(new Event('change',{bubbles:true}));return} + if(i===0&&focused&&!['INPUT','SELECT'].includes(focused.tagName))focused.click(); + } + settings(){ + const root=document.createElement('details');const title=document.createElement('summary');title.textContent='Keyboard and controller bindings';root.append(title); + const note=document.createElement('p');note.textContent='Left stick moves. Button numbers use the browser gamepad mapping. Esc always closes the focused menu. Bindings are saved on this browser.';root.append(note); + const render=()=>{root.querySelectorAll('label').forEach(e=>e.remove());for(const a of actionNames){const label=document.createElement('label');label.textContent=a.replaceAll('-',' ');const keyboard=document.createElement('select'),pad=document.createElement('select');keyboard.setAttribute('aria-label',a+' keyboard');pad.setAttribute('aria-label',a+' gamepad');for(const code of ['',...'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('').map(k=>'Key'+k),...Array.from({length:10},(_,i)=>'Digit'+i),'Space','ArrowUp','ArrowDown','ArrowLeft','ArrowRight'])keyboard.append(new Option(code||'Unbound',code));for(let i=-1;i<32;i++)pad.append(new Option(i<0?'Unbound':'Button '+i,i<0?'':String(i)));keyboard.value=Object.keys(this.bindings).find(k=>this.bindings[k]===a)??'';pad.value=Object.keys(this.padBindings).find(k=>this.padBindings[k]===a)??''; + const change=(map:Record,code:string)=>{for(const k of Object.keys(map))if(map[k]===a)delete map[k];if(code)map[code]=a;this.clear();this.save();render();root.querySelector(`select[aria-label="${a} ${map===this.bindings?'keyboard':'gamepad'}"]`)?.focus()};keyboard.onchange=()=>change(this.bindings,keyboard.value);pad.onchange=()=>change(this.padBindings,pad.value);label.append(keyboard,pad);root.append(label); + }};render();const reset=document.createElement('button');reset.type='button';reset.textContent='Reset bindings';reset.onclick=()=>{this.bindings={...defaults};this.padBindings={...padDefaults};this.clear();this.save();render()};root.append(reset);return root; + } + private save(){try{localStorage.setItem('aeternalis.controls.v1',JSON.stringify({keyboard:this.bindings,gamepad:this.padBindings}))}catch{/* Session bindings still work. */}} +} diff --git a/client/src/main.ts b/client/src/main.ts index 6b40225..92b46a6 100644 --- a/client/src/main.ts +++ b/client/src/main.ts @@ -1,6 +1,7 @@ import './style.css'; import { showTravel } from './travel'; import { craftingPanel } from './crafting-panel'; +import { createPowerPanel, revivalPanel } from './power-panel'; import { createIcons, Crosshair, Settings2, X, Flame, LogOut, Hourglass, Swords, Pickaxe, HeartPulse, Gem, Backpack, ChevronUp, ChevronDown, ChevronLeft, ChevronRight, ArrowRight, RefreshCw } from 'lucide'; import { WorldView } from './world-view'; import type { Character, Chunk, Entity, Intent, Snapshot } from './generated'; @@ -49,6 +50,7 @@ function progressSignature(): number | undefined { const avoidUntil = new Map(); let requestedClose = false; let input: InputActions; +let powers:ReturnType; let view: WorldView; const selectedWorld = new URLSearchParams(location.search).get('world'); const worldPrefix = selectedWorld && /^[a-z][a-z0-9-]{0,30}$/.test(selectedWorld) ? `/worlds/${selectedWorld}` : ''; @@ -101,11 +103,15 @@ function connect() { if (value.type !== 'snapshot' || value.version !== 1) { ws?.close(); notice('Client and server versions do not match.'); return; } if(pendingAction?.op==='gather' && snapshot && value.self.gatherAttempt!==snapshot.self.gatherAttempt){pendingAction=undefined;walkTo=undefined;gatherSent=0;} if(gatherSent && value.self.ack>=gatherSent)gatherSent=0; + const previousState = snapshot?.self.entity.state; snapshot = value; view.update(value); updateHUD(value); $('connection-status').textContent = 'Connected'; $('connection-dot').parentElement!.classList.remove('offline'); const state = value.self.entity.state; - if (state === 'dead') showEnding('A life, remembered.', 'This character is permanently dead. Their belongings remain in this world.', false); - else if (value.self.remainingSeconds <= 0) showEnding('Rest until tomorrow.', 'Your daily play time is complete. Your keystone will return you to your previous location after 00:00 UTC.', false); + const ending = $('ending'); + if (previousState === 'dead' && state !== 'dead') ending.close(); + if (state === 'dead') { + if (!ending.open) showEnding('A life, remembered.', 'Your belongings remain on your corpse. Revival requires another player and your consent; replacement makes this death final.', false); + } else if (value.self.remainingSeconds <= 0 && !ending.open) showEnding('Rest until tomorrow.', 'Your daily play time is complete. Your keystone will return you to your previous location after 00:00 UTC.', false); }; ws.onclose = async () => { $('connection-status').textContent = 'Disconnected'; $('connection-dot').parentElement!.classList.add('offline'); input.clear(); walkTo = undefined; @@ -127,7 +133,8 @@ function showEnding(title: string, detail: string, survivor: boolean) { if (survivor && destinations.children.length === 0) { const p = document.createElement('p'); p.textContent = 'Your passage is saved. No destination world is open yet.'; destinations.append(p); } visible('reconnect', false); visible('new-character', snapshot?.self.entity.state === 'dead' && ['gathering','cataclysm'].includes(snapshot.world.phase)); - $('ending').show(); + $('ending').querySelector('.revival-panel')?.remove();if(snapshot?.self.entity.state==='dead')$('ending').append(revivalPanel(worldPrefix)); + $('ending').show(); } function inventory(c: Character) { $('earned-titles').replaceChildren(permanentTitles(c.titles)); @@ -152,6 +159,7 @@ function minimap(s: Snapshot) { } function updateHUD(s: Snapshot) { const c = s.self, w = s.world; + powers?.update(c); visible('game-controls', true); visible('movement', ['alive','eligible'].includes(c.entity.state) && $('inventory').hidden && $('settings').hidden); $('character-name').textContent = c.entity.name; $('character-level').textContent = `Level ${c.level || 1}`; @@ -191,6 +199,9 @@ async function boot() { input = new InputActions(() => hasOpenMenu() || isEditing(document.activeElement) || $('arrival').open || $('ending').open, key => { if(key==='attack'||key==='gather')action(key); else if(key==='inventory')$('inventory-toggle').click(); + else if(key.startsWith('slot'))powers.useSlot(Number(key.slice(4))-1); + else if(key==='cancel-cast')send('cancel-cast'); + else if(key==='next-target'||key==='previous-target'){if(!snapshot)return;const p=snapshot.self.entity.position,targets=[snapshot.self.entity,...snapshot.entities].filter(e=>['mob','sentinel','boss','player','corpse'].includes(e.kind)).sort((a,b)=>Math.hypot(a.position.x-p.x,a.position.z-p.z)-Math.hypot(b.position.x-p.x,b.position.z-p.z)||a.id.localeCompare(b.id));if(targets.length){const i=targets.findIndex(e=>e.id===view.selected?.id);selection(targets[(i+(key==='next-target'?1:targets.length-1)+targets.length)%targets.length])}} else if(key==='heal'||key==='return'||key==='jump')send(key); }); view.start(); @@ -201,6 +212,7 @@ async function boot() { const now = performance.now(), dt = (now - lastInputAt) / 1000; lastInputAt = now; inputElapsed += dt; + input.pollController(); if (!snapshot || ws?.readyState !== WebSocket.OPEN || $('ending').open) return; if(document.hidden||hasOpenMenu()||isEditing(document.activeElement)){ input.clear();walkTo=undefined;pendingAction=undefined;view.moving=false; @@ -250,6 +262,7 @@ async function boot() { }, 50); const [loadedConfig, chunks] = await Promise.all([api('/api/config'), api('/api/preview'), view.load()]); config = loadedConfig; + powers=createPowerPanel((op,target,x,z,slot)=>{if(op==='cast'){input.clear();walkTo=undefined;pendingAction=undefined;send('move')}send(op,target,x,z,slot)},()=>view.selected,notice,worldPrefix);$('recipes').after(powers.root);$('hud').append(powers.hotbar);$('settings').append(input.settings()); const travelButton=document.createElement('button');travelButton.id='travel';travelButton.textContent='Travel';travelButton.title='World travel';$('inventory-toggle').before(travelButton); travelButton.onclick=()=>{if(!snapshot)return;input.clear();walkTo=undefined;pendingAction=undefined;send('move');void showTravel({worldId:config.worldId,route:config.kind==='hub'?'hub':snapshot.world.phase==='won'?'portal':'escape',beforeTravel:()=>{requestedClose=true;},afterTravel:departed=>{requestedClose=departed;}});}; $('zoom').value = String(view.distance); @@ -264,7 +277,8 @@ async function boot() { if (me.character.entity.state === 'dead') showEnding('A life, remembered.', 'This character is permanently dead. A fresh world is a new beginning.', false); else connect(); } else { - if (me?.active) { + if(me&&!me.active)$('passages').append(revivalPanel(worldPrefix)); + if (me?.active) { visible('join-form', false); const link = document.createElement('a'); link.href = me.active.state==='transit'?'/':`/game?world=${encodeURIComponent(me.active.worldId)}`; link.className = 'command'; link.textContent = me.active.state==='transit'?'Resume travel from your account':`Continue ${me.active.name} in ${me.active.worldId}`; $('passages').append(link); } diff --git a/client/src/menu-focus.ts b/client/src/menu-focus.ts index 42458be..7255551 100644 --- a/client/src/menu-focus.ts +++ b/client/src/menu-focus.ts @@ -6,6 +6,12 @@ function visible(menu: Menu) { !menu.element.matches('dialog:not([open])') && menu.element.getClientRects().length > 0; } export function hasOpenMenu() { return [...menus].some(visible); } +export function closeFocusedMenu() { + const open=[...menus].filter(visible).sort((a,b)=>b.order-a.order); + const focused=open.filter(m=>m.element.contains(document.activeElement)); + const menu=focused.find(m=>!focused.some(other=>other!==m&&m.element.contains(other.element)))??open[0]; + if(!menu)return false;menu.close();return true; +} // Menus use their own close operation, including inline editors and native dialogs. // Capture Escape before input fields or gameplay; close one focused layer only. diff --git a/client/src/player-content.ts b/client/src/player-content.ts index 896d236..927347d 100644 --- a/client/src/player-content.ts +++ b/client/src/player-content.ts @@ -1,7 +1,7 @@ import { api, el, type RecordCharacter } from './portal-shared'; import { statLabel } from './character-stats'; -type Catalog={crafting?:{materials:{id:string;name:string}[]};gathering?:{resources:{id:string;name:string;output:string}[];consumables:{id:string;name:string}[]};items:{id:string;name:string}[];titles:{id:string;name:string}[]}; +type Catalog={powers?:{powers:{id:string;name:string;book:boolean}[]};crafting?:{materials:{id:string;name:string}[]};gathering?:{resources:{id:string;name:string;output:string}[];consumables:{id:string;name:string}[]};items:{id:string;name:string}[];titles:{id:string;name:string}[]}; export function playerContent(record:RecordCharacter,enabled:boolean,onQueued:()=>void){ const root=el('section','','player-content');root.append(el('h3','Manage items and titles')); if(!enabled){root.append(el('p','A living character or survivor with an available world owner is required.','muted'));return root;} @@ -18,6 +18,7 @@ export function playerContent(record:RecordCharacter,enabled:boolean,onQueued:() const v=record.character.view;choice.replaceChildren(); switch(operation.value){ case 'grant-item': + choice.append(new Option('Revival stone','revival_stone'));for(const p of catalog.powers?.powers??[])if(p.book)choice.append(new Option(p.name+' spell book','book_'+p.id)); for(const i of catalog.items)choice.append(new Option(`${i.name} (${i.id})`,i.id)); for(const r of catalog.gathering?.resources??[])if(r.output==='self')choice.append(new Option(r.name,r.id)); for(const i of catalog.gathering?.consumables??[])choice.append(new Option(i.name,i.id)); diff --git a/client/src/power-panel.ts b/client/src/power-panel.ts new file mode 100644 index 0000000..8e48c7d --- /dev/null +++ b/client/src/power-panel.ts @@ -0,0 +1,28 @@ +import type {Character,Entity} from './generated'; +import {node,statLabel} from './character-stats'; +import {api} from './portal-shared'; + +export function createPowerPanel(send:(op:string,target?:string,x?:number,z?:number,slot?:string)=>void,target:()=>Entity|undefined,notice:(s:string)=>void,prefix:string){ + const root=node('section','','power-panel'),hotbar=node('div','','power-hotbar'),bookList=node('div'),known=node('div'),casting=node('p');root.append(node('h3','Spells and abilities'),casting,bookList,known); + let latest:Character,signature='',slots:string[]=[],character='',busy=false; + const use=async(id:string)=>{if(!latest||busy)return;const power=latest.powers?.[id];if(!power&&id!=='item')return;const selected=target();if(id==='item'||power?.definition.resurrection){if(selected?.kind!=='corpse'){notice('Select a player corpse and stand next to it.');return}busy=true;try{await api(prefix+'/api/revive',{corpse:selected.id,power:id});notice('Player revived.')}catch(e){notice((e as Error).message)}finally{busy=false}}else {const aim=power!.definition.targeting;if(aim==='target'&&!selected){notice('Select a target first.');return}send('cast',aim==='target'?selected!.id:latest.entity.id,0,0,id)}}; + const buttons=Array.from({length:8},(_,i)=>{const b=node('button',String(i+1));b.type='button';b.onclick=()=>void use(slots[i]);hotbar.append(b);return b}); + function refreshSlots(){buttons.forEach((b,i)=>{const p=latest.powers?.[slots[i]];b.textContent=p?`${i+1} · ${p.definition.name}`:`${i+1} · Empty`;b.disabled=!p||!['alive','eligible'].includes(latest.entity.state);b.title=p?`${p.definition.mana} mana · ${p.definition.cooldown}s cooldown`:'Assign a learned power in Inventory';})} + const save=()=>{try{localStorage.setItem('aeternalis.slots.'+character,JSON.stringify(slots))}catch{};refreshSlots()}; + function update(c:Character){latest=c;if(character!==c.entity.id){character=c.entity.id;signature='';slots=[];try{slots=JSON.parse(localStorage.getItem('aeternalis.slots.'+character)??'[]');if(!Array.isArray(slots))slots=[]}catch{slots=[]}} + casting.textContent=`Mana ${Math.floor(c.mana??0)} / ${Math.floor(c.stats?.manaPoints?.final??0)} · Stamina ${Math.floor(c.stamina??0)}${c.casting?' · '+c.casting:''}`;refreshSlots();const sig=JSON.stringify([c.powers,c.weapons,c.inventory]);if(sig===signature)return;signature=sig;known.replaceChildren();bookList.replaceChildren(); + for(const [id,n] of Object.entries(c.inventory)){if(n<1)continue;if(id.startsWith('book_')){const b=node('button',`Learn from ${c.stackNames?.[id]??statLabel(id)} (${n})`);b.type='button';b.onclick=()=>send('learn',id);bookList.append(b)}if(id==='revival_stone'){const b=node('button',`Use revival stone (${n})`);b.type='button';b.onclick=()=>void use('item');bookList.append(b)}} + for(const v of Object.values(c.weapons??{}))known.append(node('p',`${v.name} · Level ${v.level} · ${v.xp} XP · ${v.xpToNextLevel} to next`)); + for(const v of Object.values(c.powers??{})){const d=v.definition,detail=node('details'),assign=node('select'),activate=node('button','Use '+d.name);assign.setAttribute('aria-label','Action slot for '+d.name);assign.append(new Option('Not assigned',''));for(let i=0;i<8;i++)assign.append(new Option('Slot '+(i+1),String(i)));const at=slots.indexOf(d.id);assign.value=at<0?'':String(at);assign.onchange=()=>{slots=slots.map(id=>id===d.id?'':id);if(assign.value!=='')slots[Number(assign.value)]=d.id;save()};activate.type='button';activate.onclick=()=>void use(d.id);detail.append(node('summary',`${d.name} · ${d.kind==='spell'?'Rank '+v.level:'Ability'}`),node('p',`${v.xp} XP · ${v.xpToNextLevel} to next · ${d.mana} mana · ${d.castSeconds}s cast · ${d.cooldown}s cooldown`),node('p',`${d.targeting}${d.resurrection?' · corpse revival':` · ${v.attack.effect} · ${v.attack.range}m range`}`),assign,activate);known.append(detail)} + if(!Object.keys(c.powers??{}).length)known.append(node('p','Use a spell book or train a weapon to unlock powers.')); + } + return {root,hotbar,update,useSlot:(i:number)=>void use(slots[i])}; +} + +export function revivalPanel(prefix:string){ + const root=node('section','','revival-panel'),status=node('p'),button=node('button','Check revival status');button.type='button';root.append(status,button); + let current:{available:boolean;characterId?:string;allowed?:boolean;active?:string},busy=false; + async function refresh(){if(busy)return;busy=true;try{current=await api(prefix+'/api/revival');if(current.active){status.textContent='Your character is active. Continue to reconnect.';button.textContent='Continue character'}else if(current.available){status.textContent='Another player can revive you at your corpse. Creating a replacement permanently ends this option.';button.textContent=current.allowed?'Disable revival consent':'Allow revival'}else{status.textContent='No recoverable corpse is available in this world.';button.textContent='Check revival status'}}catch(e){status.textContent=(e as Error).message}finally{busy=false}} + button.onclick=async()=>{if(busy)return;if(current?.active){location.href='/game?world='+encodeURIComponent(current.active);return}if(current?.available){busy=true;try{await api(prefix+'/api/revival/consent',{characterId:current.characterId,allowed:!current.allowed})}catch(e){status.textContent=(e as Error).message}finally{busy=false}}await refresh()}; + const check=node('button','Refresh revival status');check.type='button';check.onclick=()=>void refresh();root.append(check);void refresh();return root; +} diff --git a/client/src/style.css b/client/src/style.css index 4a9e3a9..bae1b7b 100644 --- a/client/src/style.css +++ b/client/src/style.css @@ -12,3 +12,5 @@ #target-health{white-space:normal;line-height:1.5;max-width:min(550px,80vw)} .crafting-workbench{display:grid;gap:12px;font-size:12px;line-height:1.5}.crafting-workbench h3{margin:8px 0 0}.crafting-workbench form{display:grid;gap:8px}.crafting-workbench .recipe{display:grid;grid-template-columns:minmax(0,1fr) 68px;gap:6px}.crafting-workbench .recipe button{grid-column:1/-1;justify-self:end}.crafting-workbench details{border-top:1px solid var(--progression-border);padding:10px 0;overflow-wrap:anywhere}.crafting-workbench summary{cursor:pointer}.crafting-workbench details p{margin:8px 0}.crafting-workbench [role=status]{color:#d6e4b6} + +.power-panel{display:grid;gap:10px;font-size:12px;line-height:1.5}.power-panel details{padding:8px 0;border-top:1px solid var(--progression-border)}.power-panel select,.power-panel button{margin-top:8px}.power-hotbar{pointer-events:auto;position:absolute;bottom:110px;left:50%;transform:translateX(-50%);display:flex;gap:4px;max-width:85vw;flex-wrap:wrap;justify-content:center}.power-hotbar button{font-size:11px;padding:6px;min-height:32px}.revival-panel{display:grid;gap:8px;margin-top:15px}.revival-panel p{margin:0}.settings details p{margin:10px 0;font-size:12px}@media(max-width:800px){.power-hotbar{bottom:205px;max-width:72vw}.power-hotbar button{font-size:10px;min-height:28px}} diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 5393eb7..4055114 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -35,9 +35,9 @@ The highest-risk requirements are: Planning update: the vision now includes corpse-based item/spell resurrection, key-owned hub housing, crafting rolls/provenance, and portal dungeon instances. -These are design requirements, not implemented behavior. This document's terminal -death and current-world boundaries describe the running implementation; see -`planning/SYSTEMS-ROADMAP.md` for the future lifecycle rules and unresolved details. +Milestone 7 now implements corpse resurrection for new deaths. Key-owned housing +and portal dungeon instances remain design requirements. See +`planning/SYSTEMS-ROADMAP.md` for future lifecycle rules and unresolved details. The milestone 1 [lifecycle and ownership contract](LIFECYCLE-OWNERSHIP.md) maps the current code to proposed states, transaction boundaries, and migration steps. Its later lifecycle systems remain specifications. [Milestone 5](MILESTONE-5.md) @@ -89,6 +89,21 @@ versioned title/equipment/stat catalog that world owners apply and checkpoint. ## Durability and ownership +Milestone 7 adds copied character-owned spells/ranks/cooldowns and weapon XP, +preserved by travel and revival and absent from replacement characters. Go owns +learning, unlocks, cast release, useful-hit XP, and moving aura effects. Pending +casts cancel across restart/travel. See [milestone 7](MILESTONE-7.md) for scope. + +Resurrection stages consent-checked corpse revival and resource costs before an +owner/revision-fenced transaction. `account_lives` records the latest character +ever created, including after death; replacement permanently invalidates older +revival eligibility. `character_deaths` archives distinct death occurrences and +atomically claims revival once. A new-life insert trigger maintains the pointer +for older writers during deployment. Corpse loot, restored character, costs, and +death claim commit together. Old deaths without a revival identity remain final; +world destruction still prevents revival. Daily limits and transfer ownership +continue to apply. + Development uses SQLite WAL. Production requires PostgreSQL with TLS certificate verification. Both use the same storage tests and transaction behavior. diff --git a/docs/MILESTONE-7.md b/docs/MILESTONE-7.md new file mode 100644 index 0000000..82d9667 --- /dev/null +++ b/docs/MILESTONE-7.md @@ -0,0 +1,138 @@ +# Milestone 7: spells, weapon abilities, and corpse revival + +This build adds playable character-owned spell learning/ranks, weapon proficiency, +automatic ability unlocks, eight assignable action slots, controller controls, and +durable corpse resurrection. Control has readable **Spells and abilities** and +**Weapon types** editors; equipment can reference a weapon type. IDs are generated +by the server. Publish/preview uses the existing catalog version and audit path. + +## Learning and combat + +- Inventory contains **Spells and abilities**, owned spell books, weapon levels, + learned powers, and slot assignment. Consuming a book learns its spell at rank 1. + Duplicate books and books with unmet requirements are retained. +- Control can grant books and revival stones, put them in loot tables, and use + them in recipes. Existing mob loot is unchanged; grant books for this playtest + or author their drop sources. Spell books are normal loot until consumed. +- Each learned power copies its definition and combat profile. Later catalog + publications do not rewrite learned spells or acquired weapon metadata. +- Useful spell casts and weapon hits award 10 XP, at most once per action, even + for multiple area targets or aura pulses. Misses, zero damage, and healing a + full-health target give none. Hub actions never award XP. Spell and weapon XP + are separate from existing generic combat XP; no historical XP is converted. +- Requirements include character level, stats, titles, and predecessor spell + ranks. Abilities additionally require weapon proficiency and the matching + equipped main-hand weapon when used. Equipment bonuses do not satisfy power + stat prerequisites. Weapon proficiency is sampled when the attack is released. +- Spells can have cast times, mana/stamina costs, cooldowns, and rank scaling. + Costs are consumed on release after rechecking requirements and targets. + Movement, incoming combat damage, death, disconnect, shelter, travel, and + explicit cancellation interrupt pending casts. Pending casts do not resume + after restart. Cooldowns and learned progression remain saved. +- Supported effects reuse authoritative damage/healing, straight projectiles, + burst and persistent areas, and moving auras. Auras follow their caster; one + cast can earn XP only once. Terrain, range, target eligibility, and effect + capacity limits are checked by Go. + +Initial tuning lives in `server/content/balance.yaml` and is provisional: + +| Power | Access | Initial behavior | +| --- | --- | --- | +| Arc bolt | Spell book | 5 mana, 0.5s cast, 2s cooldown, visible projectile | +| Mend | Spell book | 5 mana, instant targeted heal, 2s cooldown | +| Renewal | Mend rank 2 | 10 mana, 10s cooldown, 6m healing aura lasting 8s | +| Revive | Spell book | 20 mana, instant corpse revival, 30s cooldown | +| Cleave | Blades level 2 and Strength 2 | Equipped blade, 5 stamina, nearby damage | + +Initial spell/weapon levels require 100 XP, then 50 more XP per subsequent level, +with a maximum of 1,000. Ordinary seed spells use base power 10 plus the combat +profile's stat contribution, increasing by 3% of that amount per spell rank. +The seed knife trains Blades and the spear trains Polearms. + +## Controls + +Eight HUD slots default to keys **1–8**. Assign learned powers in Inventory. +**Q/R** cycle nearby targets, including players and corpses; **X** cancels a cast. +Settings contains keyboard and gamepad bindings. Esc remains reserved for closing +the focused menu. Bindings persist on this browser; slot assignments are also +scoped to the character. Text entry still requires a keyboard. + +The first connected controller uses its left stick for movement. Defaults: +buttons 0/1/2/3 jump/gather/attack/heal, 4/5 cycle targets, 6/7 use slots 1/2, +9 opens Inventory, and buttons 12–15 use slots 3–6. Rebind any action as needed. +With a menu focused, up/down navigate controls, left/right change select values, +button 0 activates buttons, and 1/9 close the focused menu. Button numbers follow +the browser's controller mapping. Opening a menu stops gameplay movement. + +## Resurrection and finality + +The dead player enables **Allow revival** for that death in the death/arrival +panel. Another active player stands within 3m of the corpse with terrain line of +sight, selects it, and uses a revival stone or learned resurrection spell. The +stone is consumed once; the spell spends mana and starts its cooldown once. +This first build uses instant revival. Consent can be disabled, and an offline +player can be revived if they previously enabled it. These consent, cost, and +restored-pool defaults are provisional choices for playtesting. + +Revival returns the same character with only belongings still on the corpse. +Remaining equipment goes into the bag. Completely looted player corpses stay +targetable and revive with no items; stolen items and starting gear are never +recreated. Progression and daily usage are preserved. Revival restores 25% maximum +health, zero mana, and zero stamina. A character at the daily cap stays offline +and uses the normal safe-zone/keystone protection with no additional play time. + +Creating a replacement permanently blocks older-character revival, even if the +replacement later dies. World destruction also blocks revival. There is no added +short corpse expiry timer. After Harbinger victory, revival yields an eligible +survivor who can use the portal, without replaying survival rewards or XP. +Each subsequent death has a new corpse identity and requires new consent. + +Storage stages revival and commits corpse removal, remaining loot, resource +costs, character state, and death history in one owner/revision-fenced transaction. +The account's latest-ever character pointer arbitrates replacement versus revival. +A database trigger also maintains that pointer for older writers during deployment. +Historical death snapshots remain in `character_deaths`; current registry state +can return to alive only through the recorded revival transaction. Pre-milestone-7 +deaths have no revival identity and remain final. + +## Manual playtest + +1. In Control, grant Arc bolt, Mend, and Revive books plus revival stones to test + characters. Learn and assign powers in Inventory; try a duplicate book. +2. Cast Arc bolt at a mob. Move during casting, try an out-of-range target, and + check a moving-target miss. Successful hits train spells; canceled casts cost + nothing and misses earn no spell XP. +3. Heal an injured player with Mend and compare full-health casts. Train Mend to + rank 2, verify Renewal unlocks, and move with its healing aura. +4. Equip a knife, train Blades to level 2, and meet Strength 2. Verify Cleave unlocks + and rejects use with a different weapon type. +5. Preview/publish a new weapon type and power in Control, including stat, title, + and predecessor requirements. Confirm invalid references are rejected. +6. With two accounts, kill one character, enable consent, loot part/all of the + corpse, and revive by item and spell on separate deaths. Confirm only remaining + loot returns. Check rejected duplicate attempts do not spend costs. +7. Create a replacement and confirm older revival stays blocked after that new + character dies. Check world destruction also blocks revival. +8. Travel with learned progression and verify it persists; heal in a hub and + confirm no XP. Rebind slots, use controller targeting/menu navigation, and + verify Esc closes the focused menu without a gameplay action. + +Deploy updated world owners and client before testing travel with new progression; +older binaries cannot preserve fields they do not understand. Legacy account-owned +titles still require the separately planned character-ownership migration. + +## Limits and verification + +Timed stat buffs/debuffs, crowd control, ground aiming, curved/seeking projectiles, +PvP/friendly-fire policy, advanced aura stacking, spell-point/skill-point spending, +resurrection channels, and dungeon corpse closure/reset rules remain future work. +Housing, building, and cosmetics are later milestones. This build makes no new +tested capacity claim. + +Required verification: TypeScript check, production build, generated-contract +check, and the full Go suite. New tests cover learning/rank unlocks, useful-action +XP, auras, interrupted casts, daily caps, remaining-corpse loot, replacement +finality, restart, stale-owner rollback, competing replacement/revival, travel +progression, and mutation authentication/origin checks. PostgreSQL integration +tests require `TEST_DATABASE_URL`; without it, those cases are skipped. Browser +Playwright work stays in the deferred todo list; the user manually tests this build. diff --git a/planning/PLAYWRIGHT-TODO.md b/planning/PLAYWRIGHT-TODO.md index 67b724b..8c26de0 100644 --- a/planning/PLAYWRIGHT-TODO.md +++ b/planning/PLAYWRIGHT-TODO.md @@ -24,6 +24,9 @@ automation. These are future tasks, not completion gates for the current milesto - [ ] Hub crafting records discoveries and consumes resources with every XP track unchanged. - [ ] Spell books/ranks/unlocks, weapon abilities, rebinding, and controller flows. - [ ] Corpse resurrection after looting; rejection after replacement/world destruction. +- [ ] Milestone 7: learned-power slots, keyboard/controller rebinding and target + cycling, cast interruption, useful-heal XP, moving auras, consent after reload, + and empty-corpse item/spell revival with preserved progression. - [ ] Structures and house placement, keys/guest permissions, storage, and recovery UI. - [ ] Last-key three-second deletion and recovery before the death-world deadline. - [ ] Cosmetics: ordinary drops, house placement, push/pull, and entitled/unentitled pickup. diff --git a/planning/SYSTEMS-ROADMAP.md b/planning/SYSTEMS-ROADMAP.md index b90b4ae..202cc82 100644 --- a/planning/SYSTEMS-ROADMAP.md +++ b/planning/SYSTEMS-ROADMAP.md @@ -320,7 +320,7 @@ abilities remain usable after a weapon swap, and whether temporary stat bonuses can satisfy learning or activation requirements. Keep unlock rules distinct from activation rules. Legacy generic combat XP needs an agreed migration policy. -### Resurrection: confirmed design, not implemented +### Resurrection: milestone 7 implemented Resurrection requires a resurrection item used on the corpse or another player casting a resurrection spell at the corpse. The spell caster must be next to it. @@ -335,17 +335,17 @@ resurrection itself grants neither a replacement key nor house access. If the corpse's world has been destroyed, resurrection is impossible. World destruction is a hard boundary; no additional short resurrection window has been -agreed. Item consumption/activation details, any extra deadline, spell costs, -consent/offline targets, restored health/mana/stamina, casting interruption, repeat -limits, and corpse relocation remain open. +agreed. Milestone 7 uses explicit per-death consent, another player's item/spell +activation, and provisional costs and restored pools. See the +[milestone 7 handoff](../docs/MILESTONE-7.md) for playable behavior and defaults. +Additional repeat limits, corpse relocation, and dungeon closure rules remain open. -Before implementation specify a durable dead-but-resurrectable state and terminal -conditions without changing the running game's current terminal-death behavior. -Account replacement creation, looting, resurrection, and world destruction must -resolve atomically against character/corpse ownership. Concurrent casts cannot -revive twice; concurrent looting cannot copy items. Preserve daily usage, character -progress, and unique passage ownership. Agree behavior at daily cap and world -victory, and how dungeon corpse locations interact with instance closure/reset. +New deaths retain a unique revival corpse identity and immutable death history. +Account replacement and revival arbitrate through a durable latest-life pointer; +loot, costs, and revival commit together under the owning world's lease/revision. +Daily usage, character progress, and unique passage ownership remain preserved. +Pre-milestone-7 deaths remain final. Dungeon instance closure/reset still needs its +own corpse policy before that system is implemented. ## 8. Building, housing, hub, and later social systems @@ -551,7 +551,7 @@ milestones, not time estimates or new tested-capacity claims. | 4.5. Models and action presentation | Model rigs, equipment attachments, animations, sound hooks | Compatible rigs/slots, locomotion/attack/gather animation, action/outcome sounds | | 5. Playable hub travel | Hub instances/switching, survival-world entry, escape items, Harbinger victory portal | Implemented; [manual handoff](../docs/MILESTONE-5.md): admission, escape restrictions, single character/item ownership, hub XP restrictions | | 6. Crafting and item quality | Recipe discovery, nine professions, failure/refund curves, random stats, crafter provenance, hub crafting | Implemented; [manual handoff](../docs/MILESTONE-6.md): valid-recipe feedback, resource use, quality/provenance, discoveries without hub XP | -| 7. Spells, abilities, resurrection | Spell books/ranks/unlocks, weapon proficiency, corpse revival, full bindings/controller targeting | Use-based progression, effects, resurrection constraints, input usability | +| 7. Spells, abilities, resurrection | Spell books/ranks/unlocks, weapon proficiency, corpse revival, bindings/controller targeting | Implemented; [manual handoff](../docs/MILESTONE-7.md): useful-action XP, healing/auras, revival finality, costs, and controls | | 8. Building and housing | Destructible world structures, house instances, keys, permissions, storage, timed deletion/recovery | Persistence, ownership, navigation changes, guest access, three-second deletion and recovery | | 9. Cosmetics and customization | Simple character creator, account cosmetic application, furniture exceptions, presentation polish | Entitlements, appearance compatibility, drop versus placement/push/pickup | | 10. Dungeons and social expansion | Portal instances and lifecycle; separately scoped communication, trade, parties, guilds | Instance population/reset/exit rules, item exchange, membership and permissions | @@ -571,8 +571,8 @@ Milestone 1 defines ownership boundaries; it does not implement every later syst Milestone 3 terrain informs milestone 4 navigation. Combat exposes the obstacle hooks that milestone 8 structures use. Cosmetic account boundaries are designed in milestone 1, while player/furniture application follows the rig and housing work. -Resurrection and housing require their remaining lifecycle details to be settled -before their respective implementation milestones. +Resurrection's first playable defaults are recorded in milestone 7. Housing still +requires its remaining lifecycle details before implementation. At the end of **every milestone**: @@ -594,8 +594,8 @@ First discussion, because these affect the architecture: 1. Housing: countdown access/cancellation, original-creator recovery identity, exceptional death-world cases, eligibility, and the permission matrix? Three-second deletion with recovery until death-world destruction is settled. -2. Resurrection: item activation, consent, costs/pools, any extra limits, and - corpse handling during dungeon closure/reset? Corpse/world conditions are settled. +2. Resurrection: playtest milestone 7's provisional consent, costs/pools, and instant + activation. Extra limits and corpse handling during dungeon closure/reset remain open. 3. Combat: action aiming model, controller targeting, friendly fire, ranged projectiles? 4. Title migration: active awards become character-owned while historical first claims remain reserved. Decide treatment of titles already inherited under the diff --git a/planning/VISION.md b/planning/VISION.md index 9f226d5..1ceabcc 100644 --- a/planning/VISION.md +++ b/planning/VISION.md @@ -18,15 +18,16 @@ - New players always start some distance N away from existing players — **exact distance TBD**. ## Permadeath -- No automatic respawn. The current implementation makes death terminal; the - following confirmed resurrection exception is planned, not implemented. +- No automatic respawn. Milestone 7 implements the following corpse resurrection + exception for new deaths; earlier deaths remain final. - Resurrection requires an item used on the player's corpse or another player casting a resurrection spell next to that corpse. The account must not have created a replacement character since the death. - Revival returns the same character with only the items remaining on the corpse. A completely looted corpse revives with no items; stolen items are not recreated. - A character cannot be resurrected after the corpse's world is destroyed. - Item details, resource costs, and any additional limits remain to be scoped. + Provisional consent, costs, and restored pools are in `docs/MILESTONE-7.md`; + further constraints remain open for playtesting. - Loot: dead character's loot stays on the corpse. - Initial loot priority goes to whoever dealt the most damage to the character. - Once that person closes the loot interface, the corpse becomes lootable by anyone. @@ -170,6 +171,9 @@ Tracked across: - Networking: is node size (128x128x128) fixed/final, or a placeholder for tuning? ## Backlog +- Milestone 7 implements spell books/ranks/unlocks, weapon proficiency and abilities, + healing/auras, bindable keyboard/controller slots, and durable corpse revival. + See `docs/MILESTONE-7.md` for defaults, effect limits, and the manual handoff. - Milestone 6 implements character-owned crafting professions/discoveries, authored recipes and stat pools, durable attempts, and maker/world provenance. Hub crafting consumes resources without XP. See `docs/MILESTONE-6.md` for diff --git a/schemas/protocol.json b/schemas/protocol.json index 29f82ae..d4e8b21 100644 --- a/schemas/protocol.json +++ b/schemas/protocol.json @@ -70,7 +70,8 @@ "modifiers": {"type": "array", "items": {"$ref": "#/definitions/StatModifier"}}, "attackId": {"type": "string"}, "craftPool": {"type": "array", "items": {"$ref": "#/definitions/CraftStat"}}, - "craftRolls": {"type": "integer"} + "craftRolls": {"type": "integer"}, + "weaponType": {"type": "string"} }, "required": ["id", "name", "description", "slot", "weight", "dropChance", "requirements", "modifiers"] }, @@ -93,7 +94,8 @@ "effectSets": {"type": "array", "items": {"$ref": "#/definitions/EffectSet"}}, "gathering": {"$ref": "#/definitions/GatheringContent"}, "combat": {"$ref": "#/definitions/CombatContent"}, - "crafting": {"$ref": "#/definitions/CraftingContent"} + "crafting": {"$ref": "#/definitions/CraftingContent"}, + "powers": {"$ref": "#/definitions/PowerContent"} }, "required": ["version", "titles", "items", "stats"] }, @@ -123,7 +125,9 @@ "craftRecipe": {"$ref": "#/definitions/CraftRecipeDraft"}, "craftProfession": {"$ref": "#/definitions/GatheringSkillDraft"}, "craftMaterial": {"$ref": "#/definitions/CraftMaterialDraft"}, - "craftRules": {"$ref": "#/definitions/CraftRules"} + "craftRules": {"$ref": "#/definitions/CraftRules"}, + "power": {"$ref": "#/definitions/PowerDraft"}, + "weapon": {"$ref": "#/definitions/GatheringSkillDraft"} }, "required": ["id", "expectedVersion", "op", "reason"] }, @@ -153,7 +157,8 @@ "modifiers": {"type": "array", "items": {"$ref": "#/definitions/StatModifier"}}, "attackId": {"type": "string"}, "craftPool": {"type": "array", "items": {"$ref": "#/definitions/CraftStat"}}, - "craftRolls": {"type": "integer"} + "craftRolls": {"type": "integer"}, + "weaponType": {"type": "string"} }, "required": ["name", "description", "slot", "weight", "dropChance", "requirements", "modifiers"] }, @@ -237,7 +242,10 @@ "attack": {"$ref": "#/definitions/CombatAttack"}, "crafting": {"type": "object", "additionalProperties": {"$ref": "#/definitions/CraftProgress"}}, "discoveredRecipes": {"type": "object", "additionalProperties": {"$ref": "#/definitions/KnownRecipe"}}, - "craftedStacks": {"type": "array", "items": {"$ref": "#/definitions/CraftedStack"}} + "craftedStacks": {"type": "array", "items": {"$ref": "#/definitions/CraftedStack"}}, + "powers": {"type": "object", "additionalProperties": {"$ref": "#/definitions/LearnedPower"}}, + "weapons": {"type": "object", "additionalProperties": {"$ref": "#/definitions/WeaponProgress"}}, + "casting": {"type": "string"} }, "required": ["entity", "inventory", "skills", "level", "experience", "experienceToNextLevel", "statPoints", "titles", "allocatedStats", "stats", "mana", "stamina", "carryWeight", "pendingVitalChoices", "healthChoices", "manaChoices", "items", "equipment", "playedSeconds", "remainingSeconds", "kills", "ack", "hasKeystone", "gatherAttempt"] }, @@ -280,7 +288,8 @@ "equippable": {"type": "boolean"}, "requirementMessage": {"type": "string"}, "attack": {"$ref": "#/definitions/CombatAttack"}, - "provenance": {"$ref": "#/definitions/CraftProvenance"} + "provenance": {"$ref": "#/definitions/CraftProvenance"}, + "weaponType": {"type": "string"} }, "required": ["id", "definitionId", "name", "description", "slot", "weight", "requirements", "modifiers", "equippable", "requirementMessage"] }, @@ -836,6 +845,93 @@ "recipe": {"$ref": "#/definitions/KnownRecipe"} }, "required": ["id", "valid", "success", "message", "consumed", "created"] + }, + "PowerDefinition": { + "type": "object", "additionalProperties": false, + "properties": { + "id": {"type": "string"}, + "name": {"type": "string"}, + "description": {"type": "string"}, + "kind": {"type": "string"}, + "attackId": {"type": "string"}, + "targeting": {"type": "string"}, + "resurrection": {"type": "boolean"}, + "weapon": {"type": "string"}, + "weaponLevel": {"type": "integer"}, + "requirements": {"$ref": "#/definitions/ItemRequirements"}, + "parents": {"type": "object", "additionalProperties": {"type": "integer"}}, + "book": {"type": "boolean"}, + "mana": {"type": "number"}, + "castSeconds": {"type": "number"}, + "cooldown": {"type": "number"}, + "rankScaling": {"type": "number"}, + "baseXp": {"type": "integer"}, + "xpPerLevel": {"type": "integer"}, + "maxLevel": {"type": "integer"}, + "basePower": {"type": "number"} + }, + "required": ["id", "name", "description", "kind", "attackId", "targeting", "resurrection", "weapon", "weaponLevel", "requirements", "parents", "book", "mana", "castSeconds", "cooldown", "rankScaling", "baseXp", "xpPerLevel", "maxLevel", "basePower"] + }, + "PowerDraft": { + "type": "object", "additionalProperties": false, + "properties": { + "id": {"type": "string"}, + "name": {"type": "string"}, + "description": {"type": "string"}, + "kind": {"type": "string"}, + "attackId": {"type": "string"}, + "targeting": {"type": "string"}, + "resurrection": {"type": "boolean"}, + "weapon": {"type": "string"}, + "weaponLevel": {"type": "integer"}, + "requirements": {"$ref": "#/definitions/ItemRequirements"}, + "parents": {"type": "object", "additionalProperties": {"type": "integer"}}, + "book": {"type": "boolean"}, + "mana": {"type": "number"}, + "castSeconds": {"type": "number"}, + "cooldown": {"type": "number"}, + "rankScaling": {"type": "number"}, + "baseXp": {"type": "integer"}, + "xpPerLevel": {"type": "integer"}, + "maxLevel": {"type": "integer"}, + "basePower": {"type": "number"} + }, + "required": ["name", "description", "kind", "attackId", "targeting", "resurrection", "weapon", "weaponLevel", "requirements", "parents", "book", "mana", "castSeconds", "cooldown", "rankScaling", "baseXp", "xpPerLevel", "maxLevel", "basePower"] + }, + "PowerContent": { + "type": "object", "additionalProperties": false, + "properties": { + "weapons": {"type": "array", "items": {"$ref": "#/definitions/GatheringSkill"}}, + "powers": {"type": "array", "items": {"$ref": "#/definitions/PowerDefinition"}}, + "weaponXp": {"type": "integer"}, + "spellXp": {"type": "integer"}, + "revivalRange": {"type": "number"}, + "revivalHealth": {"type": "number"} + }, + "required": ["weapons", "powers", "weaponXp", "spellXp", "revivalRange", "revivalHealth"] + }, + "LearnedPower": { + "type": "object", "additionalProperties": false, + "properties": { + "definition": {"$ref": "#/definitions/PowerDefinition"}, + "attack": {"$ref": "#/definitions/CombatAttack"}, + "xp": {"type": "integer"}, + "level": {"type": "integer"}, + "xpToNextLevel": {"type": "integer"}, + "readyAt": {"type": "number"} + }, + "required": ["definition", "attack", "xp", "level", "xpToNextLevel", "readyAt"] + }, + "WeaponProgress": { + "type": "object", "additionalProperties": false, + "properties": { + "id": {"type": "string"}, + "name": {"type": "string"}, + "xp": {"type": "integer"}, + "level": {"type": "integer"}, + "xpToNextLevel": {"type": "integer"} + }, + "required": ["id", "name", "xp", "level", "xpToNextLevel"] } } } diff --git a/server/content/balance.yaml b/server/content/balance.yaml index a5e77da..f5ccff2 100644 --- a/server/content/balance.yaml +++ b/server/content/balance.yaml @@ -12,6 +12,10 @@ combat: - { id: blast_shot, name: Blast shot, description: A projectile with a damage burst., delivery: projectile, effect: damage, stat: rangedDamage, multiplier: 1, range: 35, cooldown: 3, stamina: 8, speed: 25, dexteritySpeed: 0.1, strengthSpeed: 0.05, radius: 6, duration: 0, interval: 1 } - { id: healing_field, name: Healing field, description: A projectile that creates a stationary healing area., delivery: projectile, effect: heal, stat: magicDamage, multiplier: 1, range: 30, cooldown: 8, stamina: 10, speed: 25, dexteritySpeed: 0.1, strengthSpeed: 0.05, radius: 6, duration: 5, interval: 1 } - { id: sentinel_strike, name: Sentinel strike, description: Close range damage., delivery: melee, effect: damage, stat: meleeDamage, multiplier: 1, range: 3, cooldown: 1.8, stamina: 0, speed: 1, radius: 0, duration: 0, interval: 1 } + - {"id": "arc_bolt", "name": "Arc bolt", "description": "Arc bolt", "delivery": "projectile", "effect": "damage", "stat": "magicDamage", "multiplier": 1, "range": 30, "cooldown": 2, "stamina": 0, "speed": 25, "radius": 0, "duration": 0, "interval": 1} + - {"id": "mend", "name": "Mend", "description": "Mend", "delivery": "melee", "effect": "heal", "stat": "magicDamage", "multiplier": 1, "range": 30, "cooldown": 2, "stamina": 0, "speed": 25, "radius": 0, "duration": 0, "interval": 1} + - {"id": "renewal_aura", "name": "Renewal aura", "description": "Renewal aura", "delivery": "melee", "effect": "heal", "stat": "magicDamage", "multiplier": 1, "range": 30, "cooldown": 2, "stamina": 0, "speed": 25, "radius": 6, "duration": 8, "interval": 1} + - {"id": "cleave", "name": "Cleave", "description": "Cleave", "delivery": "melee", "effect": "damage", "stat": "meleeDamage", "multiplier": 1, "range": 3, "cooldown": 2, "stamina": 5, "speed": 25, "radius": 3, "duration": 0, "interval": 1} mobs: - { id: ash_guard, name: Ash guard, description: A territorial guardian., model: sentinel, behavior: aggressive, level: 1, hp: 54, damage: 6, defence: 0, speed: 4, aggroRange: 24, leashRange: 160, scalePerDay: 0.1, xp: 50, attackId: sentinel_strike, lootId: common_mob_loot } loot: @@ -188,6 +192,7 @@ stats: luck: { criticalChance: 0.1, dropRate: 1, gatherRate: 1, dodgeChance: 0.1 } items: - id: knife + weaponType: blades name: Knife description: A starting close-combat weapon. slot: weapon @@ -195,6 +200,7 @@ items: requirements: { level: 1, stats: {}, titles: [] } modifiers: [] - id: spear + weaponType: polearms craftRolls: 1 craftPool: - { stat: meleeDamage, min: 1, max: 6, percent: false, weight: 2 } @@ -238,3 +244,6 @@ crafting: - {"id": "recipe_trap", "revision": 1, "name": "Trap parts", "description": "Starter trap parts recipe.", "profession": "trap_master", "level": 1, "xp": 20, "inputs": {"wood": 2, "ore": 1}, "outputs": {"trap_parts": 1}, "stats": {}, "titles": []} - {"id": "recipe_ration", "revision": 1, "name": "Ration", "description": "Starter ration recipe.", "profession": "cook", "level": 1, "xp": 20, "inputs": {"herb": 3}, "outputs": {"ration": 1}, "stats": {}, "titles": []} - {"id": "recipe_component", "revision": 1, "name": "Building component", "description": "Starter building component recipe.", "profession": "builder", "level": 1, "xp": 20, "inputs": {"wood": 4, "ore": 1}, "outputs": {"building_component": 1}, "stats": {}, "titles": []} + +# Milestone 7 provisional progression and resurrection tuning. +powers: {"weapons": [{"id": "blades", "name": "Blades", "description": "Blades proficiency", "baseXp": 100, "xpPerLevel": 50, "maxLevel": 1000}, {"id": "polearms", "name": "Polearms", "description": "Polearms proficiency", "baseXp": 100, "xpPerLevel": 50, "maxLevel": 1000}], "powers": [{"id": "arc_bolt", "name": "Arc bolt", "description": "Arc bolt", "kind": "spell", "attackId": "arc_bolt", "targeting": "target", "resurrection": false, "weapon": "", "weaponLevel": 1, "requirements": {"level": 1, "stats": {}, "titles": []}, "parents": {}, "book": true, "mana": 5, "castSeconds": 0.5, "cooldown": 2, "rankScaling": 0.03, "baseXp": 100, "xpPerLevel": 50, "maxLevel": 1000, "basePower": 10}, {"id": "mend", "name": "Mend", "description": "Mend", "kind": "spell", "attackId": "mend", "targeting": "target", "resurrection": false, "weapon": "", "weaponLevel": 1, "requirements": {"level": 1, "stats": {}, "titles": []}, "parents": {}, "book": true, "mana": 5, "castSeconds": 0, "cooldown": 2, "rankScaling": 0.03, "baseXp": 100, "xpPerLevel": 50, "maxLevel": 1000, "basePower": 10}, {"id": "renewal", "name": "Renewal aura", "description": "Renewal aura", "kind": "spell", "attackId": "renewal_aura", "targeting": "aura", "resurrection": false, "weapon": "", "weaponLevel": 1, "requirements": {"level": 1, "stats": {}, "titles": []}, "parents": {"mend": 2}, "book": false, "mana": 10, "castSeconds": 0, "cooldown": 10, "rankScaling": 0.03, "baseXp": 100, "xpPerLevel": 50, "maxLevel": 1000, "basePower": 10}, {"id": "revive", "name": "Resurrection", "description": "Resurrection", "kind": "spell", "attackId": "", "targeting": "target", "resurrection": true, "weapon": "", "weaponLevel": 1, "requirements": {"level": 1, "stats": {}, "titles": []}, "parents": {}, "book": true, "mana": 20, "castSeconds": 0, "cooldown": 30, "rankScaling": 0.03, "baseXp": 100, "xpPerLevel": 50, "maxLevel": 1000, "basePower": 0}, {"id": "cleave", "name": "Cleave", "description": "Cleave", "kind": "ability", "attackId": "cleave", "targeting": "target", "resurrection": false, "weapon": "blades", "weaponLevel": 2, "requirements": {"level": 1, "stats": {"strength": 2}, "titles": []}, "parents": {}, "book": false, "mana": 0, "castSeconds": 0, "cooldown": 2, "rankScaling": 0.03, "baseXp": 100, "xpPerLevel": 50, "maxLevel": 1, "basePower": 0}], "weaponXp": 10, "spellXp": 10, "revivalRange": 3, "revivalHealth": 0.25} diff --git a/server/content/combat.go b/server/content/combat.go index 3d35868..1645e49 100644 --- a/server/content/combat.go +++ b/server/content/combat.go @@ -129,6 +129,9 @@ func (c Catalog) validateCombat() error { attacks[a.ID] = true } items := map[string]bool{} + for id := range c.PowerItems() { + items[id] = true + } if c.Crafting != nil { for _, m := range c.Crafting.Materials { items[m.ID] = true diff --git a/server/content/content.go b/server/content/content.go index 84aa958..961450f 100644 --- a/server/content/content.go +++ b/server/content/content.go @@ -19,6 +19,7 @@ type Recipe struct { } type Balance struct { + Powers *PowerContent `yaml:"powers"` Crafting *CraftingContent `yaml:"crafting"` Combat *CombatContent `yaml:"combat"` CombatRules *CombatRules `yaml:"combatRules"` @@ -81,7 +82,10 @@ func Parse(data []byte) (Balance, error) { return b, b.Validate() } func (b Balance) Validate() error { - if err := (Catalog{Crafting: b.Crafting, Items: b.Items, Titles: b.Titles, Gathering: b.Gathering}).validateCrafting(); err != nil { + if err := (Catalog{Powers: b.Powers, Combat: b.Combat, Items: b.Items, Titles: b.Titles}).validatePowers(); err != nil { + return err + } + if err := (Catalog{Powers: b.Powers, Crafting: b.Crafting, Items: b.Items, Titles: b.Titles, Gathering: b.Gathering}).validateCrafting(); err != nil { return err } if b.CombatRules != nil { @@ -89,7 +93,7 @@ func (b Balance) Validate() error { return err } } - if err := (Catalog{Crafting: b.Crafting, Combat: b.Combat, Items: b.Items, Gathering: b.Gathering}).validateCombat(); err != nil { + if err := (Catalog{Powers: b.Powers, Crafting: b.Crafting, Combat: b.Combat, Items: b.Items, Gathering: b.Gathering}).validateCombat(); err != nil { return err } if b.Gathering != nil { diff --git a/server/content/crafting.go b/server/content/crafting.go index 1dba333..b72cd19 100644 --- a/server/content/crafting.go +++ b/server/content/crafting.go @@ -83,6 +83,9 @@ func SkillLevel(s GatheringSkill, xp int64) (int64, int64) { } func (c Catalog) StackIDs() map[string]bool { ids := map[string]bool{} + for id := range c.PowerItems() { + ids[id] = true + } for _, id := range []string{"axe", "flint_and_steel", "fishing_pole", "wood", "ore", "herb", "bandage", "escape_stone"} { ids[id] = true } diff --git a/server/content/powers.go b/server/content/powers.go new file mode 100644 index 0000000..0a2c42d --- /dev/null +++ b/server/content/powers.go @@ -0,0 +1,182 @@ +package content + +import ( + "fmt" + "slices" +) + +// Powers reuse combat attacks. Knowledge is copied on acquisition; later catalog +// publications cannot rewrite a learned spell or weapon ability. +type PowerDefinition struct { + BasePower float64 `json:"basePower" yaml:"basePower"` + ID string `json:"id" yaml:"id"` + Name string `json:"name" yaml:"name"` + Description string `json:"description" yaml:"description"` + Kind string `json:"kind" yaml:"kind"` + AttackID string `json:"attackId" yaml:"attackId"` + Targeting string `json:"targeting" yaml:"targeting"` + Resurrection bool `json:"resurrection" yaml:"resurrection"` + Weapon string `json:"weapon" yaml:"weapon"` + WeaponLevel int64 `json:"weaponLevel" yaml:"weaponLevel"` + Requirements ItemRequirements `json:"requirements" yaml:"requirements"` + Parents map[string]int64 `json:"parents" yaml:"parents"` + Book bool `json:"book" yaml:"book"` + Mana float64 `json:"mana" yaml:"mana"` + CastSeconds float64 `json:"castSeconds" yaml:"castSeconds"` + Cooldown float64 `json:"cooldown" yaml:"cooldown"` + RankScaling float64 `json:"rankScaling" yaml:"rankScaling"` + BaseXP int64 `json:"baseXp" yaml:"baseXp"` + XPPerLevel int64 `json:"xpPerLevel" yaml:"xpPerLevel"` + MaxLevel int64 `json:"maxLevel" yaml:"maxLevel"` +} +type PowerContent struct { + Weapons []GatheringSkill `json:"weapons" yaml:"weapons"` + Powers []PowerDefinition `json:"powers" yaml:"powers"` + WeaponXP int64 `json:"weaponXp" yaml:"weaponXp"` + SpellXP int64 `json:"spellXp" yaml:"spellXp"` + RevivalRange float64 `json:"revivalRange" yaml:"revivalRange"` + RevivalHealth float64 `json:"revivalHealth" yaml:"revivalHealth"` +} + +func (c Catalog) PowerItems() map[string]string { + out := map[string]string{"revival_stone": "Revival stone"} + if c.Powers != nil { + for _, p := range c.Powers.Powers { + if p.Book { + out["book_"+p.ID] = p.Name + " spell book" + } + } + } + return out +} +func (c Catalog) validatePowers() error { + v := c.Powers + if v == nil { + return nil + } + if len(v.Powers) > 256 || len(v.Weapons) > 64 || v.WeaponXP < 1 || v.WeaponXP > 1000 || v.SpellXP < 1 || v.SpellXP > 1000 || !finiteRange(v.RevivalRange, 1, 5) || !finiteRange(v.RevivalHealth, .01, 1) { + return fmt.Errorf("invalid power content limits") + } + weapons := map[string]bool{} + for _, s := range v.Weapons { + if !validSetIdentity(s.ID, s.Name, s.Description) || weapons[s.ID] || s.BaseXP < 1 || s.BaseXP > 1000000 || s.XPPerLevel < 1 || s.XPPerLevel > 1000000 || s.MaxLevel < 1 || s.MaxLevel > 1000 { + return fmt.Errorf("invalid weapon profession") + } + weapons[s.ID] = true + } + attacks := map[string]CombatAttack{} + if c.Combat != nil { + for _, a := range c.Combat.Attacks { + attacks[a.ID] = a + } + } + powers := map[string]PowerDefinition{} + titles := map[string]bool{} + for _, t := range c.Titles { + titles[t.ID] = true + } + for _, p := range v.Powers { + if !validSetIdentity(p.ID, p.Name, p.Description) || powers[p.ID].ID != "" || !slices.Contains([]string{"spell", "ability"}, p.Kind) || !slices.Contains([]string{"target", "self", "aura"}, p.Targeting) || !finiteRange(p.BasePower, 0, 100000) || !finiteRange(p.Mana, 0, 10000) || !finiteRange(p.CastSeconds, 0, 30) || !finiteRange(p.Cooldown, .1, 120) || !finiteRange(p.RankScaling, 0, 1) || p.BaseXP < 1 || p.BaseXP > 1000000 || p.XPPerLevel < 1 || p.XPPerLevel > 1000000 || p.MaxLevel < 1 || p.MaxLevel > 1000 || len(p.Parents) > 16 { + return fmt.Errorf("invalid spell/ability %q", p.Name) + } + if p.Resurrection { + if p.Kind != "spell" || p.Targeting != "target" || p.AttackID != "" || p.CastSeconds != 0 { + return fmt.Errorf("resurrection requires an instant corpse-targeted spell") + } + } else { + a, ok := attacks[p.AttackID] + if !ok || (p.Targeting == "aura" && (a.Radius <= 0 || a.Duration <= 0 || a.Delivery != "melee")) || (p.Targeting == "self" && a.Effect != "heal") { + return fmt.Errorf("invalid power attack/targeting") + } + } + if p.Kind == "ability" { + if !weapons[p.Weapon] || p.WeaponLevel < 1 || p.WeaponLevel > 1000 || p.Book || len(p.Parents) > 0 { + return fmt.Errorf("ability requires a weapon proficiency") + } + } else if p.Weapon != "" || (!p.Book && len(p.Parents) == 0) { + return fmt.Errorf("spell requires a book or predecessor") + } + r := p.Requirements + if r.Level < 1 || r.Level > 1000 || len(r.Stats) > 32 || len(r.Titles) > 16 { + return fmt.Errorf("invalid power requirements") + } + for stat, n := range r.Stats { + if !KnownStat(stat) || !finiteRange(n, 0, 1000000) { + return fmt.Errorf("invalid power stat requirement") + } + } + for _, id := range r.Titles { + if !titles[id] { + return fmt.Errorf("unknown power title") + } + } + powers[p.ID] = p + } + for _, p := range v.Powers { + for id, rank := range p.Parents { + parent, ok := powers[id] + if !ok || parent.Kind != "spell" || rank < 1 || rank > parent.MaxLevel { + return fmt.Errorf("invalid spell unlock predecessor") + } + } + } + visiting, done := map[string]bool{}, map[string]bool{} + var visit func(string) bool + visit = func(id string) bool { + if visiting[id] { + return false + } + if done[id] { + return true + } + visiting[id] = true + for parent := range powers[id].Parents { + if !visit(parent) { + return false + } + } + visiting[id] = false + done[id] = true + return true + } + for id := range powers { + if !visit(id) { + return fmt.Errorf("spell unlock graph contains a cycle") + } + } + for _, i := range c.Items { + if i.WeaponType != "" && !weapons[i.WeaponType] { + return fmt.Errorf("unknown equipment weapon type") + } + if _, ok := c.PowerItems()[i.ID]; ok { + return fmt.Errorf("equipment conflicts with power item") + } + } + return nil +} +func (c *Catalog) RestorePowers(b Balance) { + if c.Powers != nil { + return + } + c.Powers = b.Powers + if c.Combat == nil { + c.Combat = b.Combat + } else { + combat := *c.Combat + combat.Attacks = slices.Clone(combat.Attacks) + for _, seed := range b.Combat.Attacks { + if !slices.ContainsFunc(combat.Attacks, func(a CombatAttack) bool { return a.ID == seed.ID }) { + combat.Attacks = append(combat.Attacks, seed) + } + } + c.Combat = &combat + } + c.Items = slices.Clone(c.Items) + for i := range c.Items { + for _, seed := range b.Items { + if c.Items[i].ID == seed.ID { + c.Items[i].WeaponType = seed.WeaponType + } + } + } +} diff --git a/server/content/powers_test.go b/server/content/powers_test.go new file mode 100644 index 0000000..5ebcaf2 --- /dev/null +++ b/server/content/powers_test.go @@ -0,0 +1,34 @@ +package content + +import "testing" + +func TestPowerCatalogValidation(t *testing.T) { + for _, mutate := range []func(*Catalog){ + func(c *Catalog) { c.Powers.Powers[0].Parents = map[string]int64{"arc_bolt": 1} }, + func(c *Catalog) { c.Powers.Powers[0].AttackID = "missing" }, + func(c *Catalog) { c.Powers.Powers[0].Requirements.Stats = map[string]float64{"unknown": 1} }, + func(c *Catalog) { c.Powers.Powers[4].Weapon = "missing" }, + func(c *Catalog) { c.Powers.Powers[3].CastSeconds = 1 }, + func(c *Catalog) { c.Powers.Powers[2].Parents = map[string]int64{"mend": 1001} }, + } { + c, e := DefaultCatalog() + if e != nil { + t.Fatal(e) + } + mutate(&c) + if c.Validate() == nil { + t.Fatal("invalid power catalog accepted") + } + } + c, e := DefaultCatalog() + if e != nil { + t.Fatal(e) + } + c.Powers = nil + c.Combat.Attacks = c.Combat.Attacks[:4] + b, _ := Load() + c.RestorePowers(b) + if e = c.Validate(); e != nil { + t.Fatal("legacy catalog power upgrade failed", e) + } +} diff --git a/server/content/stats.go b/server/content/stats.go index 706c746..b8a8f4b 100644 --- a/server/content/stats.go +++ b/server/content/stats.go @@ -35,6 +35,7 @@ type ItemRequirements struct { Titles []string `json:"titles" yaml:"titles"` } type ItemDefinition struct { + WeaponType string `json:"weaponType,omitempty" yaml:"weaponType"` CraftPool []CraftStat `json:"craftPool,omitempty" yaml:"craftPool"` CraftRolls int64 `json:"craftRolls,omitempty" yaml:"craftRolls"` AttackID string `json:"attackId,omitempty" yaml:"attackId"` @@ -48,6 +49,7 @@ type ItemDefinition struct { Modifiers []StatModifier `json:"modifiers" yaml:"modifiers"` } type Catalog struct { + Powers *PowerContent `json:"powers,omitempty"` Crafting *CraftingContent `json:"crafting,omitempty"` Combat *CombatContent `json:"combat,omitempty"` Gathering *GatheringContent `json:"gathering,omitempty"` @@ -132,6 +134,9 @@ func (item ItemDefinition) Validate() error { return ValidateModifiers(item.Modifiers) } func (c Catalog) Validate() error { + if err := c.validatePowers(); err != nil { + return err + } if err := c.validateCrafting(); err != nil { return err } @@ -210,5 +215,5 @@ func DefaultCatalog() (Catalog, error) { if err != nil { return Catalog{}, err } - return Catalog{Crafting: b.Crafting, Combat: b.Combat, Gathering: b.Gathering, Version: 1, Titles: b.Titles, Items: b.Items, Stats: *b.Stats}, nil + return Catalog{Powers: b.Powers, Crafting: b.Crafting, Combat: b.Combat, Gathering: b.Gathering, Version: 1, Titles: b.Titles, Items: b.Items, Stats: *b.Stats}, nil } diff --git a/server/internal/game/admin_content.go b/server/internal/game/admin_content.go index d2516c6..445d2a3 100644 --- a/server/internal/game/admin_content.go +++ b/server/internal/game/admin_content.go @@ -1,6 +1,7 @@ package game import ( + "aeternalis/server/content" p "aeternalis/server/internal/protocol" "errors" "strconv" @@ -30,6 +31,11 @@ func (w *World) AdminItems(c *Character, op, value string) error { } if op == "grant-item" { known := false + for key := range (content.Catalog{Powers: w.Balance.Powers}).PowerItems() { + if key == id { + known = true + } + } if w.Balance.Gathering != nil { for _, r := range w.Balance.Gathering.Resources { if r.Output == "self" && r.ID == id { diff --git a/server/internal/game/combat.go b/server/internal/game/combat.go index 5af7fe5..58e8f7f 100644 --- a/server/internal/game/combat.go +++ b/server/internal/game/combat.go @@ -11,6 +11,8 @@ import ( ) type Projectile struct { + Credit *CombatCredit `json:"credit,omitempty"` + MovingAura bool `json:"movingAura"` Target string `json:"target"` ID string `json:"id"` Source string `json:"source"` @@ -101,6 +103,9 @@ func (w *World) terrainHit(a, b p.Vec3) (p.Vec3, bool) { return b, false } func (w *World) attack(c *Character, target string) error { + if c.PendingCast != nil { + return errors.New("finish or cancel the current cast") + } if !w.AllowsXP() { return errors.New("combat is unavailable here") } @@ -147,7 +152,7 @@ func (w *World) attack(c *Character, target string) error { c.AttackReadyAt = w.Age() + a.Cooldown c.View.Stamina -= a.Stamina w.dirty = true - shot := Projectile{ID: w.combatID("projectile"), Source: c.View.Entity.ID, Player: true, Target: target, Position: from, Destination: to, Attack: a, Power: power} + shot := Projectile{Credit: &CombatCredit{Weapon: w.weaponType(c)}, ID: w.combatID("projectile"), Source: c.View.Entity.ID, Player: true, Target: target, Position: from, Destination: to, Attack: a, Power: power} if a.Delivery == "projectile" { w.Projectiles[shot.ID] = &shot w.projectileVisual(shot, "launch", "") @@ -218,6 +223,9 @@ func (w *World) combatHit(shot Projectile, target string) { return } if healing && shot.Player { + if shot.Power > 0 && c.View.Entity.HP < c.View.Entity.MaxHP { + w.awardCombatCredit(shot) + } c.View.Entity.HP = math.Min(c.View.Entity.MaxHP, c.View.Entity.HP+shot.Power) } else if !healing && !shot.Player { w.damageCharacter(c, shot.Power) @@ -235,6 +243,9 @@ func (w *World) combatHit(shot Projectile, target string) { if healing && !shot.Player { w.BossHP = math.Min(w.Balance.BossHp, w.BossHP+shot.Power) } else if !healing && shot.Player { + if shot.Power > 0 { + w.awardCombatCredit(shot) + } w.damageBoss(w.Characters[shot.Source], shot.Power) } w.dirty = true @@ -251,6 +262,9 @@ func (w *World) combatHit(shot Projectile, target string) { if m.Definition != nil { defence = m.Definition.Defence } + if shot.Power > defence { + w.awardCombatCredit(shot) + } m.Entity.HP = math.Max(0, m.Entity.HP-math.Max(0, shot.Power-defence)) m.Target = shot.Source if m.Entity.HP == 0 { @@ -341,6 +355,11 @@ func (w *World) updateCombat(dt float64) { w.dirty = true continue } + if area.MovingAura { + if c := w.Characters[area.Source]; c != nil { + area.Position = body(c.View.Entity.Position) + } + } if w.Age() >= area.NextAt { w.areaPulse(area.Projectile) area.NextAt = w.Age() + area.Attack.Interval diff --git a/server/internal/game/crafting_test.go b/server/internal/game/crafting_test.go index 4905988..c77ad54 100644 --- a/server/internal/game/crafting_test.go +++ b/server/internal/game/crafting_test.go @@ -135,7 +135,7 @@ func TestCraftedStackSplitDeathLootAndReplacement(t *testing.T) { t.Fatal("pickup changed crafter") } w.kill(c, "test") - corpse := w.Corpses["corpse:"+c.View.Entity.ID] + corpse := w.Corpses[c.RevivalCorpse] if len(c.View.CraftedStacks) != 0 || len(corpse.CraftedStacks) != 1 { t.Fatal("death duplicated crafted stock") } diff --git a/server/internal/game/equipment.go b/server/internal/game/equipment.go index 183c7cd..341396d 100644 --- a/server/internal/game/equipment.go +++ b/server/internal/game/equipment.go @@ -57,7 +57,7 @@ func (w *World) addInventoryItems(inventory *map[string]int64, items *[]p.ItemIn created := make([]p.ItemInstance, 0, int(quantity)) for n := int64(0); n < quantity; n++ { item := p.ItemInstance{ID: ID(), DefinitionID: definition.ID, Name: definition.Name, Description: definition.Description, Slot: definition.Slot, Weight: definition.Weight, - Requirements: p.ItemRequirements{Level: definition.Requirements.Level, Stats: map[string]float64{}, Titles: append([]string{}, definition.Requirements.Titles...)}, Modifiers: []p.StatModifier{}} + WeaponType: stringPtr(definition.WeaponType), Requirements: p.ItemRequirements{Level: definition.Requirements.Level, Stats: map[string]float64{}, Titles: append([]string{}, definition.Requirements.Titles...)}, Modifiers: []p.StatModifier{}} for stat, value := range definition.Requirements.Stats { item.Requirements.Stats[stat] = value } @@ -352,7 +352,13 @@ func (w *World) lootCorpse(c *Character, target string) error { c.View.Inventory[name] += quantity } c.View.Items = append(c.View.Items, corpse.Items...) - delete(w.Corpses, target) + if corpse.CharacterID != "" { + corpse.Inventory = map[string]int64{} + corpse.Items = []p.ItemInstance{} + corpse.CraftedStacks = nil + } else { + delete(w.Corpses, target) + } w.RefreshStats(c) w.dirty = true return nil diff --git a/server/internal/game/equipment_test.go b/server/internal/game/equipment_test.go index 85c5fb4..9bda7c5 100644 --- a/server/internal/game/equipment_test.go +++ b/server/internal/game/equipment_test.go @@ -125,7 +125,7 @@ func TestEquipmentDeathDropLootAndRestart(t *testing.T) { } count := len(survivor.View.Items) next.kill(survivor, "test death") - corpse := next.Corpses["corpse:"+survivor.View.Entity.ID] + corpse := next.Corpses[survivor.RevivalCorpse] if len(corpse.Items) != count || len(survivor.View.Items) != 0 || len(survivor.View.Equipment) != 0 { t.Fatal("death duplicated/lost items") } diff --git a/server/internal/game/powers.go b/server/internal/game/powers.go new file mode 100644 index 0000000..7e5258d --- /dev/null +++ b/server/internal/game/powers.go @@ -0,0 +1,370 @@ +package game + +import ( + "aeternalis/server/content" + p "aeternalis/server/internal/protocol" + "encoding/json" + "errors" + "math" + "slices" +) + +type PendingCast struct { + Power string `json:"power"` + Target string `json:"target"` + Origin p.Vec3 `json:"origin"` + Finish float64 `json:"finish"` +} +type CombatCredit struct { + Power string `json:"power"` + Weapon string `json:"weapon"` + Rewarded bool `json:"rewarded"` +} + +func (w *World) refreshPowers(c *Character) { + if c.View.Powers == nil { + c.View.Powers = map[string]p.LearnedPower{} + } + if c.View.Weapons == nil { + c.View.Weapons = map[string]p.WeaponProgress{} + } + if w.Balance.Powers == nil { + return + } + for _, s := range w.Balance.Powers.Weapons { + v := c.View.Weapons[s.ID] + v.ID = s.ID + v.Name = s.Name + v.Level, v.XPToNextLevel = content.SkillLevel(s, v.XP) + c.View.Weapons[s.ID] = v + } + for id, v := range c.View.Powers { + d := v.Definition + v.Level, v.XPToNextLevel = content.SkillLevel(content.GatheringSkill{BaseXP: d.BaseXP, XPPerLevel: d.XPPerLevel, MaxLevel: d.MaxLevel}, v.XP) + c.View.Powers[id] = v + } + for id, name := range (content.Catalog{Powers: w.Balance.Powers}).PowerItems() { + if c.View.Inventory[id] > 0 { + c.View.StackNames[id] = name + } + } + c.View.Casting = nil + if c.PendingCast != nil { + message := "Casting " + c.View.Powers[c.PendingCast.Power].Definition.Name + c.View.Casting = &message + } +} +func (w *World) restorePowers(c *Character) error { + if len(c.View.Powers) > 256 || len(c.View.Weapons) > 64 { + return errors.New("invalid learned power history") + } + for id, v := range c.View.Powers { + if id != v.Definition.ID || v.XP < 0 || v.XP > 1000000000000 || !finiteCraft(v.ReadyAt) || v.Definition.BaseXP < 1 || v.Definition.XPPerLevel < 1 || v.Definition.MaxLevel < 1 || v.Definition.MaxLevel > 1000 { + return errors.New("invalid learned spell") + } + d := v.Definition + if len(id) > 64 || !finiteCraft(d.Mana) || d.Mana > 10000 || !finiteCraft(d.BasePower) || d.BasePower > 100000 || !finiteCraft(d.RankScaling) || d.RankScaling > 1 || !finiteCraft(d.Cooldown) || d.Cooldown < .1 || d.Cooldown > 120 || !finiteCraft(d.CastSeconds) || d.CastSeconds > 30 || len(d.Parents) > 16 || len(d.Requirements.Stats) > 32 || len(d.Requirements.Titles) > 16 { + return errors.New("invalid saved power definition") + } + if !d.Resurrection { + raw, _ := json.Marshal(v.Attack) + var attack content.CombatAttack + _ = json.Unmarshal(raw, &attack) + if e := attack.Validate(); e != nil { + return e + } + } + } + for _, v := range c.View.Weapons { + if v.XP < 0 || v.XP > 1000000000000 { + return errors.New("invalid weapon XP") + } + } + // Casts cancel on reconnect/restart/travel; no cast cost is taken until resolution. + c.PendingCast = nil + c.View.Casting = nil + for i := range c.View.Items { + if c.View.Items[i].WeaponType == nil { + for _, d := range w.Balance.Items { + if d.ID == c.View.Items[i].DefinitionID && d.WeaponType != "" { + v := d.WeaponType + c.View.Items[i].WeaponType = &v + } + } + } + } + return nil +} +func (w *World) powerRequirements(c *Character, d p.PowerDefinition) bool { + if c.View.Level < d.Requirements.Level { + return false + } + stats := w.statValues(c, false) + for key, n := range d.Requirements.Stats { + if stats[key].Final < n { + return false + } + } + for _, id := range d.Requirements.Titles { + if !slices.ContainsFunc(c.View.Titles, func(t p.TitleAward) bool { return t.ID == id }) { + return false + } + } + if d.Kind == "ability" && c.View.Weapons[d.Weapon].Level < d.WeaponLevel { + return false + } + return true +} +func (w *World) acquirePower(c *Character, d content.PowerDefinition) { + var definition p.PowerDefinition + raw, _ := json.Marshal(d) + _ = json.Unmarshal(raw, &definition) + v := p.LearnedPower{Definition: definition, Level: 1, XPToNextLevel: d.BaseXP} + for _, a := range w.Balance.Combat.Attacks { + if a.ID == d.AttackID { + v.Attack = protocolAttack(a) + } + } + c.View.Powers[d.ID] = v + w.dirty = true +} +func (w *World) unlockPowers(c *Character) { + w.refreshPowers(c) + if w.Balance.Powers == nil { + return + } + // Topological fixed point is bounded by the validated catalog size. + for pass := 0; pass < len(w.Balance.Powers.Powers); pass++ { + changed := false + for _, d := range w.Balance.Powers.Powers { + if _, ok := c.View.Powers[d.ID]; ok || d.Book { + continue + } + var definition p.PowerDefinition + raw, _ := json.Marshal(d) + _ = json.Unmarshal(raw, &definition) + if !w.powerRequirements(c, definition) { + continue + } + ready := true + for id, rank := range d.Parents { + if c.View.Powers[id].Level < rank { + ready = false + } + } + if ready { + w.acquirePower(c, d) + changed = true + } + } + if !changed { + break + } + } + w.refreshPowers(c) +} +func (w *World) LearnPower(c *Character, book string) error { + if c == nil || !c.Online || c.Sheltered || c.View.RemainingSeconds <= 0 || (c.View.Entity.State != "alive" && c.View.Entity.State != "eligible") || w.Phase == "lost" { + return errors.New("cannot learn a spell now") + } + if c.View.Inventory[book] < 1 { + return errors.New("spell book not owned") + } + for _, d := range w.Balance.Powers.Powers { + if d.Book && "book_"+d.ID == book { + if _, ok := c.View.Powers[d.ID]; ok { + return errors.New("spell already learned; book retained") + } + var definition p.PowerDefinition + raw, _ := json.Marshal(d) + _ = json.Unmarshal(raw, &definition) + if !w.powerRequirements(c, definition) { + return errors.New("spell requirements not met") + } + for id, rank := range d.Parents { + if c.View.Powers[id].Level < rank { + return errors.New("predecessor spell rank required") + } + } + TakeStack(c, book, 1) + w.acquirePower(c, d) + w.unlockPowers(c) + c.Message = "Learned " + d.Name + return nil + } + } + return errors.New("unknown spell book") +} +func (w *World) weaponType(c *Character) string { + for _, i := range c.View.Items { + if i.ID == c.View.Equipment["weapon"] && i.WeaponType != nil { + return *i.WeaponType + } + } + return "" +} +func (w *World) awardCombatCredit(shot Projectile) { + credit := shot.Credit + if credit == nil || credit.Rewarded || !shot.Player || !w.AllowsXP() { + return + } + c := w.Characters[shot.Source] + if c == nil || c.View.Entity.State != "alive" { + return + } + credit.Rewarded = true + if credit.Power != "" { + v, ok := c.View.Powers[credit.Power] + if ok && v.Definition.Kind == "spell" { + v.XP = min(int64(1000000000000), v.XP+w.Balance.Powers.SpellXP) + c.View.Powers[credit.Power] = v + } + } + if credit.Weapon != "" { + v, ok := c.View.Weapons[credit.Weapon] + if ok { + v.XP = min(int64(1000000000000), v.XP+w.Balance.Powers.WeaponXP) + c.View.Weapons[credit.Weapon] = v + } + } + w.unlockPowers(c) + w.dirty = true +} +func (w *World) CastPower(c *Character, id, target string) error { + w.unlockPowers(c) + v, ok := c.View.Powers[id] + if !ok { + return errors.New("power not learned") + } + d := v.Definition + if d.Resurrection { + return errors.New("use corpse resurrection") + } + if c.PendingCast != nil { + return errors.New("already casting") + } + if err := w.checkPower(c, v, target); err != nil { + return err + } + if d.CastSeconds > 0 { + c.PendingCast = &PendingCast{Power: id, Target: target, Origin: c.View.Entity.Position, Finish: float64(w.now.UnixMilli())/1000 + d.CastSeconds} + w.refreshPowers(c) + w.dirty = true + return nil + } + return w.releasePower(c, id, target) +} +func (w *World) checkPower(c *Character, v p.LearnedPower, target string) error { + d := v.Definition + if !c.Online || c.Sheltered || c.View.Entity.State != "alive" || c.View.RemainingSeconds <= 0 || w.Phase == "lost" || w.Phase == "won" { + return errors.New("cannot cast here") + } + if w.IsHub() && v.Attack.Effect != "heal" { + return errors.New("damage powers unavailable in hub") + } + if !w.powerRequirements(c, d) || (d.Kind == "ability" && w.weaponType(c) != d.Weapon) { + return errors.New("power requirements or equipped weapon not met") + } + if c.View.Mana < d.Mana || c.View.Stamina < v.Attack.Stamina { + return errors.New("not enough mana or stamina") + } + if float64(w.now.UnixMilli())/1000 < v.ReadyAt { + return errors.New("power cooldown") + } + if d.Targeting == "self" || d.Targeting == "aura" { + target = c.View.Entity.ID + } + found := false + for _, e := range w.combatTargets(true, v.Attack.Effect) { + if e.ID == target { + if length3(body(c.View.Entity.Position), body(e.Position)) > v.Attack.Range+func() float64 { + if target == "boss" { + return 4 + } + return 0 + }() { + return errors.New("power target out of range") + } + if _, blocked := w.terrainHit(body(c.View.Entity.Position), body(e.Position)); blocked { + return errors.New("terrain blocks power") + } + found = true + } + } + if d.Targeting == "aura" { + found = true + } + if !found { + return errors.New("invalid power target") + } + if v.Attack.Delivery == "projectile" && len(w.Projectiles) >= w.Balance.CombatRules.MaxProjectiles { + return errors.New("projectile limit") + } + if v.Attack.Duration > 0 && len(w.Areas)+w.pendingAreas() >= w.Balance.CombatRules.MaxAreas { + return errors.New("area limit") + } + return nil +} +func (w *World) releasePower(c *Character, id, target string) error { + v := c.View.Powers[id] + if err := w.checkPower(c, v, target); err != nil { + return err + } + d := v.Definition + if d.Targeting == "self" || d.Targeting == "aura" { + target = c.View.Entity.ID + } + to := body(c.View.Entity.Position) + for _, e := range w.combatTargets(true, v.Attack.Effect) { + if e.ID == target { + to = body(e.Position) + } + } + a := v.Attack + if a.Delivery == "projectile" { + if a.DexteritySpeed != nil { + a.Speed += c.View.Stats["dexterity"].Final * *a.DexteritySpeed + } + if a.StrengthSpeed != nil { + a.Speed += c.View.Stats["strength"].Final * *a.StrengthSpeed + } + a.Speed = math.Min(100, math.Max(1, a.Speed)) + } + c.View.Mana -= d.Mana + c.View.Stamina -= a.Stamina + v.ReadyAt = float64(w.now.UnixMilli())/1000 + d.Cooldown + c.View.Powers[id] = v + credit := &CombatCredit{Power: id} + if d.Kind == "ability" { + credit.Weapon = w.weaponType(c) + } + shot := Projectile{ID: w.combatID("projectile"), Source: c.View.Entity.ID, Player: true, Target: target, Position: body(c.View.Entity.Position), Destination: to, Attack: a, Power: (d.BasePower + c.View.Stats[a.Stat].Final*a.Multiplier) * (1 + float64(v.Level-1)*d.RankScaling), Credit: credit, MovingAura: d.Targeting == "aura"} + if a.Delivery == "projectile" { + w.Projectiles[shot.ID] = &shot + w.projectileVisual(shot, "launch", "") + } else { + shot.Position = to + w.impact(shot, target) + } + c.Message = "Used " + d.Name + w.dirty = true + return nil +} +func (w *World) updatePowers() { + for _, c := range w.orderedCharacters() { + if cast := c.PendingCast; cast != nil { + if !c.Online || c.Sheltered || c.View.Entity.State != "alive" || length3(c.View.Entity.Position, cast.Origin) > .1 { + c.PendingCast = nil + c.Message = "Casting interrupted" + w.dirty = true + } else if float64(w.now.UnixMilli())/1000 >= cast.Finish { + c.PendingCast = nil + if e := w.releasePower(c, cast.Power, cast.Target); e != nil { + c.Message = e.Error() + } + w.dirty = true + } + w.refreshPowers(c) + } + } +} diff --git a/server/internal/game/powers_test.go b/server/internal/game/powers_test.go new file mode 100644 index 0000000..21cee39 --- /dev/null +++ b/server/internal/game/powers_test.go @@ -0,0 +1,208 @@ +package game + +import ( + "encoding/json" + "reflect" + "testing" + "time" +) + +func TestSpellBooksRanksAuraAndHubXP(t *testing.T) { + w, c := fixture(t) + c.View.Inventory["book_mend"] = 2 + c.View.Mana = 100 + if e := w.LearnPower(c, "book_mend"); e != nil { + t.Fatal(e) + } + if c.View.Powers["mend"].Level != 1 || c.View.Inventory["book_mend"] != 1 { + t.Fatal("book did not teach rank one exactly once") + } + if w.LearnPower(c, "book_mend") == nil || c.View.Inventory["book_mend"] != 1 { + t.Fatal("duplicate learning consumed book") + } + if e := w.CastPower(c, "mend", c.View.Entity.ID); e != nil { + t.Fatal(e) + } + if c.View.Powers["mend"].XP != 0 { + t.Fatal("full health healing gained XP") + } + for i := 0; i < 10; i++ { + w.now = w.now.Add(3 * time.Second) + c.View.Mana = 100 + c.View.Entity.HP = 10 + if e := w.CastPower(c, "mend", c.View.Entity.ID); e != nil { + t.Fatal(e) + } + } + if c.View.Powers["mend"].Level != 2 || c.View.Powers["renewal"].Level != 1 { + t.Fatal("spell rank did not unlock successor", c.View.Powers) + } + w.now = w.now.Add(10 * time.Second) + c.View.Mana = 100 + c.View.Entity.HP = 10 + if e := w.CastPower(c, "renewal", ""); e != nil { + t.Fatal(e) + } + if c.View.Powers["renewal"].XP != 10 { + t.Fatal("useful aura did not grant one award") + } + c.View.Entity.Position.X += 2 + c.View.Entity.HP = 10 + advanceProjectiles(w, 30) + for _, a := range w.Areas { + if a.MovingAura && a.Position != body(c.View.Entity.Position) { + t.Fatal("aura did not follow caster") + } + } + if c.View.Powers["renewal"].XP != 10 { + t.Fatal("aura tick multiplied XP") + } + raw, _ := json.Marshal(w) + var restored World + if e := json.Unmarshal(raw, &restored); e != nil { + t.Fatal(e) + } + if e := restored.Restore(w.now); e != nil { + t.Fatal(e) + } + rc := restored.Characters[c.View.Entity.ID] + if !reflect.DeepEqual(rc.View.Powers, c.View.Powers) { + t.Fatal("restart changed learned powers") + } + w.Kind = "hub" + w.Phase = "hub" + w.now = w.now.Add(20 * time.Second) + c.View.Mana = 100 + c.View.Entity.HP = 10 + before := c.View.Powers["mend"].XP + if e := w.CastPower(c, "mend", c.View.Entity.ID); e != nil { + t.Fatal(e) + } + if c.View.Powers["mend"].XP != before || c.View.Mana >= 100 { + t.Fatal("hub spell gained XP or bypassed cost") + } +} + +func TestCastingInterruptMissAndWeaponUnlock(t *testing.T) { + w, c, m := combatFixture(t) + c.View.Inventory["book_arc_bolt"] = 1 + c.View.Mana = 100 + if e := w.LearnPower(c, "book_arc_bolt"); e != nil { + t.Fatal(e) + } + if e := w.CastPower(c, "arc_bolt", m.Entity.ID); e != nil { + t.Fatal(e) + } + c.View.Entity.Position.X += 1 + w.updatePowers() + if c.PendingCast != nil || len(w.Projectiles) != 0 || c.View.Mana != 100 { + t.Fatal("movement failed to interrupt cast without cost") + } + if e := w.CastPower(c, "arc_bolt", m.Entity.ID); e != nil { + t.Fatal(e) + } + w.now = w.now.Add(time.Second) + w.updatePowers() + if len(w.Projectiles) != 1 || c.View.Mana != 95 { + t.Fatal("cast did not release after delay") + } + m.Entity.Position.Z += 20 + advanceProjectiles(w, 40) + if c.View.Powers["arc_bolt"].XP != 0 { + t.Fatal("miss gained spell XP") + } + w, c, m = combatFixture(t) + c.View.Equipment = map[string]string{} + for _, i := range c.View.Items { + if i.DefinitionID == "knife" { + c.View.Equipment["weapon"] = i.ID + } + } + w.RefreshStats(c) + m.Entity.Position = c.View.Entity.Position + m.Entity.Position.X += 1 + m.Entity.HP = 10000 + m.Entity.MaxHP = 10000 + c.View.AllocatedStats["strength"] = 2 + w.RefreshStats(c) + for i := 0; i < 10; i++ { + w.now = w.now.Add(3 * time.Second) + if e := w.attack(c, m.Entity.ID); e != nil { + t.Fatal(e) + } + } + if c.View.Weapons["blades"].Level != 2 || c.View.Powers["cleave"].Definition.ID != "cleave" { + t.Fatal("meaningful weapon hits did not unlock ability") + } + if e := w.unequip(c, "weapon"); e != nil { + t.Fatal(e) + } + if w.CastPower(c, "cleave", m.Entity.ID) == nil { + t.Fatal("ability used without matching weapon") + } + w.kill(c, "test") + replacement, e := w.Join(c.Account, "Replacement") + if e != nil { + t.Fatal(e) + } + if len(replacement.View.Powers) != 0 || replacement.View.Weapons["blades"].XP != 0 { + t.Fatal("replacement inherited powers") + } +} + +func TestCorpseRevivalKeepsLootAndDailyBudget(t *testing.T) { + w, c := fixture(t) + rescuer, e := w.Join("rescuer", "Rescuer") + if e != nil { + t.Fatal(e) + } + _ = w.Connect(rescuer.View.Entity.ID) + rescuer.View.Entity.Position = c.View.Entity.Position + rescuer.View.Inventory["revival_stone"] = 2 + c.DailySeconds = 123 + c.View.Inventory["wood"] = 7 + w.kill(c, "test") + corpse := c.RevivalCorpse + if _, e = w.Revive(rescuer, corpse, "item"); e == nil { + t.Fatal("revived without consent") + } + c.RevivalAllowed = true + if e = w.lootCorpse(rescuer, corpse); e != nil { + t.Fatal(e) + } + if w.Corpses[corpse] == nil || len(w.Corpses[corpse].Inventory) != 0 { + t.Fatal("fully looted corpse no longer targetable") + } + if _, e = w.Revive(rescuer, corpse, "item"); e != nil { + t.Fatal(e) + } + if len(c.View.Inventory) != 0 || len(c.View.Items) != 0 || c.DailySeconds != 123 || rescuer.View.Inventory["wood"] != 7 || rescuer.View.Inventory["revival_stone"] != 1 { + t.Fatal("revival recreated loot or daily time") + } + if _, e = w.Revive(rescuer, corpse, "item"); e == nil || rescuer.View.Inventory["revival_stone"] != 1 { + t.Fatal("revived twice") + } + w.kill(c, "again") + if c.RevivalCorpse == corpse { + t.Fatal("death reused corpse identity") + } + c.RevivalAllowed = true + rescuer.View.Inventory["book_revive"] = 1 + rescuer.View.Mana = 100 + if e = w.LearnPower(rescuer, "book_revive"); e != nil { + t.Fatal(e) + } + c.DailySeconds = w.Balance.DailyPlaySeconds + if _, e = w.Revive(rescuer, c.RevivalCorpse, "revive"); e != nil { + t.Fatal(e) + } + if c.View.RemainingSeconds != 0 || !c.Sheltered || !c.View.HasKeystone || c.ReturnPosition == nil || rescuer.View.Mana != 80 || rescuer.View.Powers["revive"].XP != 10 { + t.Fatal("spell revival changed daily budget or costs") + } + w.kill(c, "final") + c.RevivalAllowed = true + w.Phase = "lost" + if _, e = w.Revive(rescuer, c.RevivalCorpse, "item"); e == nil { + t.Fatal("revived after destruction") + } +} diff --git a/server/internal/game/revival.go b/server/internal/game/revival.go new file mode 100644 index 0000000..8347707 --- /dev/null +++ b/server/internal/game/revival.go @@ -0,0 +1,91 @@ +package game + +import ( + "errors" + "math" +) + +// The owning store additionally fences this against account replacement, the +// persisted death occurrence, and world ownership in the same save transaction. +func (w *World) Revive(caster *Character, corpseID, power string) (*Character, error) { + corpse := w.Corpses[corpseID] + if corpse == nil || corpse.CharacterID == "" || w.Phase == "lost" { + return nil, errors.New("corpse cannot be revived") + } + target := w.Characters[corpse.CharacterID] + if caster == nil || target == nil || caster == target || !caster.Online || caster.Sheltered || caster.View.RemainingSeconds <= 0 || (caster.View.Entity.State != "alive" && caster.View.Entity.State != "eligible") || target.View.Entity.State != "dead" || target.RevivalCorpse != corpseID || !target.RevivalAllowed { + return nil, errors.New("revival requires an active rescuer and the dead player's consent") + } + if length3(caster.View.Entity.Position, corpse.Entity.Position) > w.Balance.Powers.RevivalRange { + return nil, errors.New("stand next to the corpse") + } + if _, blocked := w.terrainHit(body(caster.View.Entity.Position), body(corpse.Entity.Position)); blocked { + return nil, errors.New("terrain blocks the corpse") + } + if caster.PendingCast != nil { + return nil, errors.New("finish or cancel the current cast") + } + if power == "item" { + if caster.View.Inventory["revival_stone"] < 1 { + return nil, errors.New("revival stone required") + } + } else { + v, ok := caster.View.Powers[power] + if !ok || !v.Definition.Resurrection || !w.powerRequirements(caster, v.Definition) || caster.View.Mana < v.Definition.Mana || float64(w.now.UnixMilli())/1000 < v.ReadyAt { + return nil, errors.New("resurrection spell unavailable") + } + } + if e := validateOwnedItems(corpse.Items, map[string]bool{}); e != nil { + return nil, e + } + if e := ValidateCraftedStacks(corpse.Inventory, corpse.CraftedStacks, map[string]bool{}); e != nil { + return nil, e + } + if power == "item" { + TakeStack(caster, "revival_stone", 1) + } else { + v := caster.View.Powers[power] + caster.View.Mana -= v.Definition.Mana + v.ReadyAt = float64(w.now.UnixMilli())/1000 + v.Definition.Cooldown + caster.View.Powers[power] = v + w.awardCombatCredit(Projectile{Source: caster.View.Entity.ID, Player: true, Credit: &CombatCredit{Power: power}}) + } + target.View.Inventory = corpse.Inventory + target.View.Items = corpse.Items + target.View.CraftedStacks = corpse.CraftedStacks + target.View.Entity.State = "alive" + if w.Phase == "won" { + target.View.Entity.State = "eligible" + } + target.View.Entity.Position = corpse.Entity.Position + target.RevivalAllowed = false + target.DiedAt = nil + target.DeathReason = "" + target.PendingCast = nil + target.JumpVelocity = 0 + target.MoveX = 0 + target.MoveZ = 0 + target.Sheltered = false + target.ReturnPosition = nil + target.View.HasKeystone = false + w.RefreshStats(target) + target.View.Entity.HP = math.Max(1, target.View.Entity.MaxHP*w.Balance.Powers.RevivalHealth) + target.View.Mana = 0 + target.View.Stamina = 0 + // Daily usage is retained; capped players cannot reconnect or act until reset. + w.resetDay(target) + if target.View.RemainingSeconds <= 0 { + target.Online = false + position := target.View.Entity.Position + target.ReturnPosition = &position + target.Sheltered = true + target.View.HasKeystone = true + target.View.Entity.Position = w.terrain.Position(0, 0) + target.View.Entity.HP = math.Min(target.View.Entity.MaxHP, math.Max(50, target.View.Entity.HP)) + } + delete(w.Corpses, corpseID) + target.Message = "Revived with the belongings left on your corpse" + caster.Message = "Revived " + target.View.Entity.Name + w.dirty = true + return target, nil +} diff --git a/server/internal/game/stats.go b/server/internal/game/stats.go index 9fc1eea..fb9e346 100644 --- a/server/internal/game/stats.go +++ b/server/internal/game/stats.go @@ -90,6 +90,7 @@ func (w *World) RefreshStats(c *Character) { c.View.Stats = w.statValues(c, true) w.refreshGathering(c) w.refreshCrafting(c) + w.unlockPowers(c) attack := w.playerAttack(c) c.View.Attack = &attack c.View.Entity.MaxHP = c.View.Stats["healthPoints"].Final @@ -172,6 +173,9 @@ func (w *World) ApplyCatalog(catalog content.Catalog) error { if catalog.Combat != nil { w.Balance.Combat = catalog.Combat } + if catalog.Powers != nil { + w.Balance.Powers = catalog.Powers + } if catalog.Crafting != nil { w.Balance.Crafting = catalog.Crafting } @@ -211,5 +215,11 @@ func (w *World) damageCharacter(c *Character, amount float64) { if w.roll(c.View.Stats["dodgeChance"].Final) { return } - c.View.Entity.HP -= math.Max(0, amount-c.View.Stats["defence"].Final) + damage := math.Max(0, amount-c.View.Stats["defence"].Final) + if damage > 0 && c.PendingCast != nil { + c.PendingCast = nil + c.View.Casting = nil + c.Message = "Casting interrupted by damage" + } + c.View.Entity.HP -= damage } diff --git a/server/internal/game/world.go b/server/internal/game/world.go index a6bb85a..5009a04 100644 --- a/server/internal/game/world.go +++ b/server/internal/game/world.go @@ -14,10 +14,14 @@ import ( ) type Character struct { - CraftReadyAt float64 `json:"craftReadyAt"` - AttackReadyAt float64 `json:"attackReadyAt"` - JumpVelocity float64 `json:"jumpVelocity"` - GatherReadyAt float64 `json:"gatherReadyAt"` + PendingCast *PendingCast `json:"pendingCast,omitempty"` + RevivalCorpse string `json:"revivalCorpse,omitempty"` + RevivalAllowed bool `json:"revivalAllowed"` + DeathCount int64 `json:"deathCount"` + CraftReadyAt float64 `json:"craftReadyAt"` + AttackReadyAt float64 `json:"attackReadyAt"` + JumpVelocity float64 `json:"jumpVelocity"` + GatherReadyAt float64 `json:"gatherReadyAt"` View p.Character `json:"view"` Account string `json:"account"` @@ -42,6 +46,7 @@ type Character struct { StatsVersion int `json:"statsVersion"` } type Corpse struct { + CharacterID string `json:"characterId,omitempty"` CraftedStacks []p.CraftedStack `json:"craftedStacks,omitempty"` Entity p.Entity `json:"entity"` Inventory map[string]int64 `json:"inventory"` @@ -187,6 +192,17 @@ func (w *World) Restore(now time.Time) error { if w.ResourceLayouts == nil { w.ResourceLayouts = map[string]ResourceLayout{} } + if w.Balance.Powers == nil { + b, e := content.Load() + if e != nil { + return e + } + cat := content.Catalog{Items: w.Balance.Items, Combat: w.Balance.Combat} + cat.RestorePowers(b) + w.Balance.Powers = cat.Powers + w.Balance.Combat = cat.Combat + w.Balance.Items = cat.Items + } if w.Balance.Crafting == nil { b, e := content.Load() if e != nil { @@ -228,6 +244,9 @@ func (w *World) Restore(now time.Time) error { if err := w.restoreEquipment(c); err != nil { return err } + if err := w.restorePowers(c); err != nil { + return err + } if err := w.restoreCrafting(c); err != nil { return err } @@ -342,6 +361,9 @@ func (w *World) Join(account, name string) (*Character, error) { if err := w.restoreEquipment(c); err != nil { return nil, err } + if err := w.restorePowers(c); err != nil { + return nil, err + } if err := w.restoreCrafting(c); err != nil { return nil, err } @@ -373,6 +395,9 @@ func (w *World) Import(c *Character) error { if err := w.checkImportedEquipment(c); err != nil { return err } + if err := w.restorePowers(c); err != nil { + return err + } if err := w.restoreCrafting(c); err != nil { return err } @@ -399,6 +424,7 @@ func (w *World) Import(c *Character) error { c.JumpVelocity = 0 c.ReturnPosition = nil c.Sheltered = false + c.PendingCast = nil c.View.HasKeystone = false c.WorldKills = 0 w.resetDay(c) @@ -422,7 +448,7 @@ func (w *World) Connect(id string) error { } w.resetDay(c) if c.View.Entity.State == "dead" { - return errors.New("this character has died permanently") + return errors.New("this character is dead; corpse revival is required before reconnecting") } if c.View.RemainingSeconds <= 0 { return errors.New("daily play limit reached; resets at 00:00 UTC") @@ -483,7 +509,7 @@ func (w *World) Intent(id string, i p.Intent) error { if i.Seq <= c.View.ACK || i.Seq > c.View.ACK+10000 { return errors.New("invalid input sequence") } - if math.IsNaN(i.X) || math.IsNaN(i.Z) || math.IsInf(i.X, 0) || math.IsInf(i.Z, 0) || math.Abs(i.X) > 1 || math.Abs(i.Z) > 1 || len(i.Target) > 100 || len(i.Slot) > 30 { + if math.IsNaN(i.X) || math.IsNaN(i.Z) || math.IsInf(i.X, 0) || math.IsInf(i.Z, 0) || math.Abs(i.X) > 1 || math.Abs(i.Z) > 1 || len(i.Target) > 100 || len(i.Slot) > 64 { return errors.New("invalid intent") } c.View.ACK = i.Seq @@ -491,7 +517,7 @@ func (w *World) Intent(id string, i p.Intent) error { c.Sheltered = false w.dirty = true } - if w.Phase == "won" && i.Op != "move" && i.Op != "jump" && i.Op != "return" { + if w.Phase == "won" && i.Op != "move" && i.Op != "jump" && i.Op != "return" && i.Op != "learn" { return errors.New("use the victory portal to continue") } if w.IsHub() && (i.Op == "attack" || i.Op == "gather") { @@ -520,6 +546,15 @@ func (w *World) Intent(id string, i p.Intent) error { return w.consumeGathering(c, i.Target) case "gather": return w.gather(c, i.Target) + case "learn": + return w.LearnPower(c, i.Target) + case "cast": + return w.CastPower(c, i.Slot, i.Target) + case "cancel-cast": + c.PendingCast = nil + w.refreshPowers(c) + w.dirty = true + return nil case "craft": return errors.New("use the crafting workbench to offer ingredients") case "attack": @@ -580,11 +615,15 @@ func (w *World) kill(c *Character, reason string) { e := c.View.Entity e.Position = w.terrain.Position(e.Position.X, e.Position.Z) c.View.Entity.Position = e.Position - e.ID = "corpse:" + e.ID + c.DeathCount++ + c.PendingCast = nil + c.RevivalAllowed = false + e.ID = "corpse:" + e.ID + ":" + ID() + c.RevivalCorpse = e.ID e.Kind = "corpse" e.State = "dead" e.HP = 0 - w.Corpses[e.ID] = &Corpse{Entity: e, Inventory: c.View.Inventory, Items: c.View.Items, CraftedStacks: c.View.CraftedStacks} + w.Corpses[e.ID] = &Corpse{CharacterID: c.View.Entity.ID, Entity: e, Inventory: c.View.Inventory, Items: c.View.Items, CraftedStacks: c.View.CraftedStacks} c.View.CraftedStacks = nil c.View.Inventory = map[string]int64{} c.View.Items = []p.ItemInstance{} @@ -749,6 +788,9 @@ func (w *World) Advance(now time.Time, dt float64) { } if !w.IsHub() && w.Phase != "won" { w.updateMobs(active, dt) + } + w.updatePowers() + if w.Phase != "won" { w.updateCombat(dt) } if w.Phase == "cataclysm" { diff --git a/server/internal/game/world_test.go b/server/internal/game/world_test.go index 702abb8..6eec4db 100644 --- a/server/internal/game/world_test.go +++ b/server/internal/game/world_test.go @@ -143,7 +143,7 @@ func TestGatherCraftAndPermanentDeath(t *testing.T) { if c.DiedAt == nil || c.DeathReason != "test death" { t.Fatal("missing durable death record") } - if len(c.View.Inventory) != 0 || gearCount(w.Corpses["corpse:"+id].Items, "spear") != 1 { + if len(c.View.Inventory) != 0 || gearCount(w.Corpses[c.RevivalCorpse].Items, "spear") != 1 { t.Fatal("corpse inventory") } raw, _ := json.Marshal(w) diff --git a/server/internal/protocol/generated.go b/server/internal/protocol/generated.go index e49a95a..c0eaf5b 100644 --- a/server/internal/protocol/generated.go +++ b/server/internal/protocol/generated.go @@ -18,6 +18,7 @@ type ContentCatalog struct { EffectSets []EffectSet `json:"effectSets,omitempty"` Gathering *GatheringContent `json:"gathering,omitempty"` Items []ItemDefinition `json:"items"` + Powers *PowerContent `json:"powers,omitempty"` RequirementSets []RequirementSet `json:"requirementSets,omitempty"` Stats ContentStatsRules `json:"stats"` Titles []TitleDefinition `json:"titles"` @@ -215,6 +216,7 @@ type ItemDefinition struct { Name string `json:"name"` Requirements ItemRequirements `json:"requirements"` Slot string `json:"slot"` + WeaponType *string `json:"weaponType,omitempty"` Weight float64 `json:"weight"` } @@ -232,6 +234,38 @@ type ItemRequirements struct { Titles []string `json:"titles"` } +type PowerContent struct { + Powers []PowerDefinition `json:"powers"` + RevivalHealth float64 `json:"revivalHealth"` + RevivalRange float64 `json:"revivalRange"` + SpellXP int64 `json:"spellXp"` + WeaponXP int64 `json:"weaponXp"` + Weapons []GatheringSkill `json:"weapons"` +} + +type PowerDefinition struct { + AttackID string `json:"attackId"` + BasePower float64 `json:"basePower"` + BaseXP int64 `json:"baseXp"` + Book bool `json:"book"` + CastSeconds float64 `json:"castSeconds"` + Cooldown float64 `json:"cooldown"` + Description string `json:"description"` + ID string `json:"id"` + Kind string `json:"kind"` + Mana float64 `json:"mana"` + MaxLevel int64 `json:"maxLevel"` + Name string `json:"name"` + Parents map[string]int64 `json:"parents"` + RankScaling float64 `json:"rankScaling"` + Requirements ItemRequirements `json:"requirements"` + Resurrection bool `json:"resurrection"` + Targeting string `json:"targeting"` + Weapon string `json:"weapon"` + WeaponLevel int64 `json:"weaponLevel"` + XPPerLevel int64 `json:"xpPerLevel"` +} + type RequirementSet struct { Description string `json:"description"` ID string `json:"id"` @@ -282,6 +316,7 @@ type ContentChange struct { Loot *LootTableDraft `json:"loot,omitempty"` Mob *MobDefinitionDraft `json:"mob,omitempty"` Op string `json:"op"` + Power *PowerDraft `json:"power,omitempty"` Reason string `json:"reason"` RequirementSet *RequirementSetDraft `json:"requirementSet,omitempty"` RequirementSetIDS []string `json:"requirementSetIds,omitempty"` @@ -290,6 +325,7 @@ type ContentChange struct { Stats *ContentStatsRules `json:"stats,omitempty"` TargetID *string `json:"targetId,omitempty"` Title *TitleDraft `json:"title,omitempty"` + Weapon *GatheringSkillDraft `json:"weapon,omitempty"` } type CombatAttackDraft struct { @@ -376,6 +412,7 @@ type ItemDraft struct { Name string `json:"name"` Requirements ItemRequirements `json:"requirements"` Slot string `json:"slot"` + WeaponType *string `json:"weaponType,omitempty"` Weight float64 `json:"weight"` } @@ -405,6 +442,29 @@ type MobDefinitionDraft struct { XP int64 `json:"xp"` } +type PowerDraft struct { + AttackID string `json:"attackId"` + BasePower float64 `json:"basePower"` + BaseXP int64 `json:"baseXp"` + Book bool `json:"book"` + CastSeconds float64 `json:"castSeconds"` + Cooldown float64 `json:"cooldown"` + Description string `json:"description"` + ID *string `json:"id,omitempty"` + Kind string `json:"kind"` + Mana float64 `json:"mana"` + MaxLevel int64 `json:"maxLevel"` + Name string `json:"name"` + Parents map[string]int64 `json:"parents"` + RankScaling float64 `json:"rankScaling"` + Requirements ItemRequirements `json:"requirements"` + Resurrection bool `json:"resurrection"` + Targeting string `json:"targeting"` + Weapon string `json:"weapon"` + WeaponLevel int64 `json:"weaponLevel"` + XPPerLevel int64 `json:"xpPerLevel"` +} + type RequirementSetDraft struct { Description string `json:"description"` ID *string `json:"id,omitempty"` @@ -562,38 +622,41 @@ type ProjectileVisual struct { } type Character struct { - ACK int64 `json:"ack"` - AllocatedStats map[string]int64 `json:"allocatedStats"` - Attack *CombatAttack `json:"attack,omitempty"` - CarryWeight float64 `json:"carryWeight"` - Consumables []GatheringConsumable `json:"consumables,omitempty"` - CraftedStacks []CraftedStack `json:"craftedStacks,omitempty"` - Crafting map[string]CraftProgress `json:"crafting,omitempty"` - DiscoveredRecipes map[string]KnownRecipe `json:"discoveredRecipes,omitempty"` - Entity Entity `json:"entity"` - Equipment map[string]string `json:"equipment"` - Experience int64 `json:"experience"` - ExperienceToNextLevel int64 `json:"experienceToNextLevel"` - GatherAttempt int64 `json:"gatherAttempt"` - Gathering map[string]SkillProgress `json:"gathering,omitempty"` - GatheringEffects []TimedGatheringEffect `json:"gatheringEffects,omitempty"` - HasKeystone bool `json:"hasKeystone"` - HealthChoices int64 `json:"healthChoices"` - Inventory map[string]int64 `json:"inventory"` - Items []ItemInstance `json:"items"` - Kills int64 `json:"kills"` - Level int64 `json:"level"` - Mana float64 `json:"mana"` - ManaChoices int64 `json:"manaChoices"` - PendingVitalChoices int64 `json:"pendingVitalChoices"` - PlayedSeconds float64 `json:"playedSeconds"` - RemainingSeconds float64 `json:"remainingSeconds"` - Skills map[string]int64 `json:"skills"` - StackNames map[string]string `json:"stackNames,omitempty"` - Stamina float64 `json:"stamina"` - StatPoints int64 `json:"statPoints"` - Stats map[string]StatValue `json:"stats"` - Titles []TitleAward `json:"titles"` + ACK int64 `json:"ack"` + AllocatedStats map[string]int64 `json:"allocatedStats"` + Attack *CombatAttack `json:"attack,omitempty"` + CarryWeight float64 `json:"carryWeight"` + Casting *string `json:"casting,omitempty"` + Consumables []GatheringConsumable `json:"consumables,omitempty"` + CraftedStacks []CraftedStack `json:"craftedStacks,omitempty"` + Crafting map[string]CraftProgress `json:"crafting,omitempty"` + DiscoveredRecipes map[string]KnownRecipe `json:"discoveredRecipes,omitempty"` + Entity Entity `json:"entity"` + Equipment map[string]string `json:"equipment"` + Experience int64 `json:"experience"` + ExperienceToNextLevel int64 `json:"experienceToNextLevel"` + GatherAttempt int64 `json:"gatherAttempt"` + Gathering map[string]SkillProgress `json:"gathering,omitempty"` + GatheringEffects []TimedGatheringEffect `json:"gatheringEffects,omitempty"` + HasKeystone bool `json:"hasKeystone"` + HealthChoices int64 `json:"healthChoices"` + Inventory map[string]int64 `json:"inventory"` + Items []ItemInstance `json:"items"` + Kills int64 `json:"kills"` + Level int64 `json:"level"` + Mana float64 `json:"mana"` + ManaChoices int64 `json:"manaChoices"` + PendingVitalChoices int64 `json:"pendingVitalChoices"` + PlayedSeconds float64 `json:"playedSeconds"` + Powers map[string]LearnedPower `json:"powers,omitempty"` + RemainingSeconds float64 `json:"remainingSeconds"` + Skills map[string]int64 `json:"skills"` + StackNames map[string]string `json:"stackNames,omitempty"` + Stamina float64 `json:"stamina"` + StatPoints int64 `json:"statPoints"` + Stats map[string]StatValue `json:"stats"` + Titles []TitleAward `json:"titles"` + Weapons map[string]WeaponProgress `json:"weapons,omitempty"` } type CraftedStack struct { @@ -661,9 +724,19 @@ type ItemInstance struct { RequirementMessage string `json:"requirementMessage"` Requirements ItemRequirements `json:"requirements"` Slot string `json:"slot"` + WeaponType *string `json:"weaponType,omitempty"` Weight float64 `json:"weight"` } +type LearnedPower struct { + Attack CombatAttack `json:"attack"` + Definition PowerDefinition `json:"definition"` + Level int64 `json:"level"` + ReadyAt float64 `json:"readyAt"` + XP int64 `json:"xp"` + XPToNextLevel int64 `json:"xpToNextLevel"` +} + type TitleAward struct { Description string `json:"description"` EarnedAt string `json:"earnedAt"` @@ -674,6 +747,14 @@ type TitleAward struct { WorldID string `json:"worldId"` } +type WeaponProgress struct { + ID string `json:"id"` + Level int64 `json:"level"` + Name string `json:"name"` + XP int64 `json:"xp"` + XPToNextLevel int64 `json:"xpToNextLevel"` +} + type WorldInfo struct { AgeSeconds float64 `json:"ageSeconds"` BossHP float64 `json:"bossHp"` diff --git a/server/internal/store/catalog.go b/server/internal/store/catalog.go index 8a28e90..15485c6 100644 --- a/server/internal/store/catalog.go +++ b/server/internal/store/catalog.go @@ -17,6 +17,8 @@ var ErrCatalogInvalid = errors.New("invalid catalog change") var catalogRequestID = regexp.MustCompile(`^[a-f0-9-]{32,36}$`) type CatalogChange struct { + Power *content.PowerDefinition `json:"power,omitempty"` + Weapon *content.GatheringSkill `json:"weapon,omitempty"` CraftRecipe *content.CraftRecipe `json:"craftRecipe,omitempty"` CraftProfession *content.GatheringSkill `json:"craftProfession,omitempty"` CraftMaterial *content.CraftMaterial `json:"craftMaterial,omitempty"` @@ -51,7 +53,7 @@ type CatalogResult struct { // Explicit definition IDs are reserved for trusted seed/import code. Browser // publications omit them; the server assigns an ID after resolving request replay. func (c CatalogChange) HasDefinitionID() bool { - return (c.CraftRecipe != nil && c.CraftRecipe.ID != "") || (c.CraftProfession != nil && c.CraftProfession.ID != "") || (c.CraftMaterial != nil && c.CraftMaterial.ID != "") || (c.Attack != nil && c.Attack.ID != "") || (c.Mob != nil && c.Mob.ID != "") || (c.Loot != nil && c.Loot.ID != "") || (c.Spawn != nil && c.Spawn.ID != "") || (c.GatheringSkill != nil && c.GatheringSkill.ID != "") || (c.Resource != nil && c.Resource.ID != "") || (c.Biome != nil && c.Biome.ID != "") || (c.Consumable != nil && c.Consumable.ID != "") || (c.Title != nil && c.Title.ID != "") || (c.Item != nil && c.Item.ID != "") || (c.RequirementSet != nil && c.RequirementSet.ID != "") || (c.EffectSet != nil && c.EffectSet.ID != "") + return (c.Power != nil && c.Power.ID != "") || (c.Weapon != nil && c.Weapon.ID != "") || (c.CraftRecipe != nil && c.CraftRecipe.ID != "") || (c.CraftProfession != nil && c.CraftProfession.ID != "") || (c.CraftMaterial != nil && c.CraftMaterial.ID != "") || (c.Attack != nil && c.Attack.ID != "") || (c.Mob != nil && c.Mob.ID != "") || (c.Loot != nil && c.Loot.ID != "") || (c.Spawn != nil && c.Spawn.ID != "") || (c.GatheringSkill != nil && c.GatheringSkill.ID != "") || (c.Resource != nil && c.Resource.ID != "") || (c.Biome != nil && c.Biome.ID != "") || (c.Consumable != nil && c.Consumable.ID != "") || (c.Title != nil && c.Title.ID != "") || (c.Item != nil && c.Item.ID != "") || (c.RequirementSet != nil && c.RequirementSet.ID != "") || (c.EffectSet != nil && c.EffectSet.ID != "") } type CatalogAudit struct { @@ -129,6 +131,13 @@ func decodeCatalog(version int64, raw string) (content.Catalog, error) { } catalog.RestoreCrafting(defaults) } + if catalog.Powers == nil { + b, e := content.Load() + if e != nil { + return catalog, e + } + catalog.RestorePowers(b) + } return catalog, catalog.Validate() } func (d *DB) Catalog(ctx context.Context) (content.Catalog, error) { @@ -164,12 +173,16 @@ func (c CatalogChange) validate() error { } valid := false count := 0 - for _, present := range []bool{c.CraftRecipe != nil, c.CraftProfession != nil, c.CraftMaterial != nil, c.CraftRules != nil, c.Attack != nil, c.Mob != nil, c.Loot != nil, c.Spawn != nil, c.GatheringSkill != nil, c.Resource != nil, c.Biome != nil, c.Consumable != nil, c.Title != nil, c.Item != nil, c.Stats != nil, c.RequirementSet != nil, c.EffectSet != nil} { + for _, present := range []bool{c.Power != nil, c.Weapon != nil, c.CraftRecipe != nil, c.CraftProfession != nil, c.CraftMaterial != nil, c.CraftRules != nil, c.Attack != nil, c.Mob != nil, c.Loot != nil, c.Spawn != nil, c.GatheringSkill != nil, c.Resource != nil, c.Biome != nil, c.Consumable != nil, c.Title != nil, c.Item != nil, c.Stats != nil, c.RequirementSet != nil, c.EffectSet != nil} { if present { count++ } } switch c.Op { + case "create-power": + valid = c.Power != nil + case "create-weapon": + valid = c.Weapon != nil case "create-craft-recipe", "update-craft-recipe": valid = c.CraftRecipe != nil case "create-craft-profession": diff --git a/server/internal/store/catalog_preview.go b/server/internal/store/catalog_preview.go index dbf7bf3..4e53af8 100644 --- a/server/internal/store/catalog_preview.go +++ b/server/internal/store/catalog_preview.go @@ -35,6 +35,12 @@ func (d *DB) PreviewCatalog(ctx context.Context, change CatalogChange) (CatalogP } // Preview validates a provisional identity but does not reserve or expose it. if !change.HasDefinitionID() { + if resolved.Power != nil { + resolved.Power.ID = "" + } + if resolved.Weapon != nil { + resolved.Weapon.ID = "" + } if resolved.CraftRecipe != nil && change.Op != "update-craft-recipe" { resolved.CraftRecipe.ID = "" } @@ -124,7 +130,32 @@ func buildCatalog(c content.Catalog, change CatalogChange) (content.Catalog, str } crafting := *c.Crafting c.Crafting = &crafting + if c.Powers == nil { + b, e := content.Load() + if e != nil { + return invalid(e) + } + c.RestorePowers(b) + } + powers := *c.Powers + c.Powers = &powers switch change.Op { + case "create-power": + v := *change.Power + if v.ID == "" { + v.ID = "power_" + game.ID() + } + c.Powers.Powers = append(slices.Clone(c.Powers.Powers), v) + resolved.Power = &v + target = v.ID + case "create-weapon": + v := *change.Weapon + if v.ID == "" { + v.ID = "weapon_" + game.ID() + } + c.Powers.Weapons = append(slices.Clone(c.Powers.Weapons), v) + resolved.Weapon = &v + target = v.ID case "create-craft-recipe", "update-craft-recipe": v := *change.CraftRecipe v.Revision = 1 diff --git a/server/internal/store/crafting.go b/server/internal/store/crafting.go index 19ce046..a99b9e9 100644 --- a/server/internal/store/crafting.go +++ b/server/internal/store/crafting.go @@ -73,7 +73,7 @@ func (l *Lease) Craft(ctx context.Context, live *game.World, account string, req request, _ := json.Marshal(req) out, _ := json.Marshal(result) receipt := &craftReceipt{req.ID, account, req.CharacterID, string(request), string(out)} - if e = l.save(ctx, staged, "", nil, "", receipt); e != nil { + if e = l.save(ctx, staged, "", nil, "", receipt, nil); e != nil { return p.CraftResult{}, e } // Retain character pointers captured by existing WebSocket handlers. diff --git a/server/internal/store/life_migration.go b/server/internal/store/life_migration.go new file mode 100644 index 0000000..322b230 --- /dev/null +++ b/server/internal/store/life_migration.go @@ -0,0 +1,46 @@ +package store + +import ( + "context" + "database/sql" + "errors" +) + +// During a rolling upgrade an older world owner still inserts replacement lives. +// Enforce the account pointer at the database boundary as well as in new writers, +// so creating and losing a replacement on that owner cannot revive an older life. +func (d *DB) migrateLifeTrigger(ctx context.Context, tx *sql.Tx) error { + var version int + err := tx.QueryRowContext(ctx, `SELECT version FROM schema_migrations WHERE version=7`).Scan(&version) + if err == nil { + return nil + } + if !errors.Is(err, sql.ErrNoRows) { + return err + } + if d.postgres { + if _, e := tx.ExecContext(ctx, `CREATE OR REPLACE FUNCTION aeternalis_current_life() RETURNS trigger AS $$ BEGIN + INSERT INTO account_lives(account_id,character_id) VALUES(NEW.account_id,NEW.character_id) + ON CONFLICT(account_id) DO UPDATE SET character_id=EXCLUDED.character_id; + RETURN NEW; + END; $$ LANGUAGE plpgsql`); e != nil { + return e + } + if _, e := tx.ExecContext(ctx, `DROP TRIGGER IF EXISTS aeternalis_new_life ON character_records`); e != nil { + return e + } + if _, e := tx.ExecContext(ctx, `CREATE TRIGGER aeternalis_new_life AFTER INSERT ON character_records FOR EACH ROW WHEN (NEW.state IN ('alive','eligible','transit')) EXECUTE FUNCTION aeternalis_current_life()`); e != nil { + return e + } + } else { + _, e := tx.ExecContext(ctx, `CREATE TRIGGER IF NOT EXISTS aeternalis_new_life AFTER INSERT ON character_records WHEN NEW.state IN ('alive','eligible','transit') BEGIN + INSERT INTO account_lives(account_id,character_id) VALUES(NEW.account_id,NEW.character_id) + ON CONFLICT(account_id) DO UPDATE SET character_id=excluded.character_id; + END`) + if e != nil { + return e + } + } + _, err = tx.ExecContext(ctx, `INSERT INTO schema_migrations(version) VALUES(7)`) + return err +} diff --git a/server/internal/store/portal.go b/server/internal/store/portal.go index 254190c..c4dbf18 100644 --- a/server/internal/store/portal.go +++ b/server/internal/store/portal.go @@ -65,6 +65,8 @@ func (d *DB) migrate(ctx context.Context) error { } } for _, stmt := range []string{ + `CREATE TABLE IF NOT EXISTS account_lives(account_id TEXT PRIMARY KEY,character_id TEXT NOT NULL)`, + `CREATE TABLE IF NOT EXISTS character_deaths(corpse_id TEXT PRIMARY KEY,character_id TEXT NOT NULL,world_id TEXT NOT NULL,character TEXT NOT NULL,revived INTEGER NOT NULL)`, `CREATE TABLE IF NOT EXISTS craft_receipts(id TEXT NOT NULL,account_id TEXT NOT NULL,character_id TEXT NOT NULL,request_json TEXT NOT NULL,result_json TEXT NOT NULL,PRIMARY KEY(account_id,id))`, `CREATE TABLE IF NOT EXISTS schema_migrations(version INTEGER PRIMARY KEY)`, `CREATE TABLE IF NOT EXISTS title_awards(account_id TEXT NOT NULL, title_id TEXT NOT NULL, scope TEXT NOT NULL, scope_key TEXT NOT NULL, character_id TEXT NOT NULL, award TEXT NOT NULL, PRIMARY KEY(account_id,title_id), UNIQUE(scope,scope_key,title_id))`, @@ -83,7 +85,13 @@ func (d *DB) migrate(ctx context.Context) error { return err } } + if _, err = tx.ExecContext(ctx, `INSERT INTO account_lives(account_id,character_id) SELECT account_id,character_id FROM character_records WHERE state IN ('alive','eligible','transit') ON CONFLICT(account_id) DO NOTHING`); err != nil { + return err + } var version int + if err = d.migrateLifeTrigger(ctx, tx); err != nil { + return err + } err = tx.QueryRowContext(ctx, `SELECT version FROM schema_migrations WHERE version=1`).Scan(&version) if err == nil { return tx.Commit() @@ -136,6 +144,9 @@ func (d *DB) migrate(ctx context.Context) error { return tx.Commit() } func (d *DB) writeCharacter(ctx context.Context, tx *sql.Tx, world string, c *game.Character, claim bool) error { + if err := d.reserveCharacterLife(ctx, tx, world, c); err != nil { + return err + } raw, err := json.Marshal(c) if err != nil { return err diff --git a/server/internal/store/revival.go b/server/internal/store/revival.go new file mode 100644 index 0000000..c8a163d --- /dev/null +++ b/server/internal/store/revival.go @@ -0,0 +1,154 @@ +package store + +import ( + "aeternalis/server/internal/game" + "context" + "database/sql" + "encoding/json" + "errors" + "fmt" + "maps" +) + +var ErrRevival = errors.New("revival rejected") + +type reviveClaim struct{ Account, Character, Corpse, World string } + +// A permanent account pointer records the most recently created life, including +// after its death. Repeated deaths never make an older life current again. +func (d *DB) reserveCharacterLife(ctx context.Context, tx *sql.Tx, world string, c *game.Character) error { + if _, e := tx.ExecContext(ctx, d.q(`INSERT INTO account_lives(account_id,character_id) VALUES(?,?) ON CONFLICT(account_id) DO NOTHING`), c.Account, c.View.Entity.ID); e != nil { + return e + } + if _, e := tx.ExecContext(ctx, d.q(`UPDATE account_lives SET character_id=character_id WHERE account_id=?`), c.Account); e != nil { + return e + } + var current string + if e := tx.QueryRowContext(ctx, d.q(`SELECT character_id FROM account_lives WHERE account_id=?`), c.Account).Scan(¤t); e != nil { + return e + } + var state, oldWorld string + e := tx.QueryRowContext(ctx, d.q(`SELECT state,world_id FROM character_records WHERE character_id=?`), c.View.Entity.ID).Scan(&state, &oldWorld) + if e != nil && !errors.Is(e, sql.ErrNoRows) { + return e + } + if errors.Is(e, sql.ErrNoRows) && c.View.Entity.State != "dead" { + if _, e = tx.ExecContext(ctx, d.q(`UPDATE account_lives SET character_id=? WHERE account_id=?`), c.View.Entity.ID, c.Account); e != nil { + return e + } + } else if e == nil && oldWorld == world && c.View.Entity.State != "dead" { + if current != c.View.Entity.ID { + return ErrLivingCharacter + } + if state == "dead" { + var revived int + if e = tx.QueryRowContext(ctx, d.q(`SELECT revived FROM character_deaths WHERE corpse_id=? AND character_id=?`), c.RevivalCorpse, c.View.Entity.ID).Scan(&revived); e != nil || revived != 1 { + return ErrRevival + } + } + } + if c.View.Entity.State == "dead" && c.RevivalCorpse != "" { + raw, e := json.Marshal(c) + if e != nil { + return e + } + _, e = tx.ExecContext(ctx, d.q(`INSERT INTO character_deaths(corpse_id,character_id,world_id,character,revived) VALUES(?,?,?,?,0) ON CONFLICT(corpse_id) DO NOTHING`), c.RevivalCorpse, c.View.Entity.ID, world, string(raw)) + if e != nil { + return e + } + } + return nil +} +func (d *DB) checkRevival(ctx context.Context, tx *sql.Tx, r *reviveClaim) error { + if _, e := tx.ExecContext(ctx, d.q(`UPDATE account_lives SET character_id=character_id WHERE account_id=?`), r.Account); e != nil { + return e + } + var current string + if e := tx.QueryRowContext(ctx, d.q(`SELECT character_id FROM account_lives WHERE account_id=?`), r.Account).Scan(¤t); e != nil { + return e + } + if current != r.Character { + return fmt.Errorf("%w: a replacement character was created", ErrRevival) + } + var state, world, raw string + if e := tx.QueryRowContext(ctx, d.q(`SELECT state,world_id,character FROM character_records WHERE character_id=? AND account_id=?`), r.Character, r.Account).Scan(&state, &world, &raw); e != nil { + return e + } + var dead game.Character + if e := json.Unmarshal([]byte(raw), &dead); e != nil { + return e + } + if state != "dead" || world != r.World || dead.RevivalCorpse != r.Corpse || !dead.RevivalAllowed { + return ErrRevival + } + result, e := tx.ExecContext(ctx, d.q(`UPDATE character_deaths SET revived=1 WHERE corpse_id=? AND character_id=? AND revived=0`), r.Corpse, r.Character) + if e != nil { + return e + } + n, _ := result.RowsAffected() + if n != 1 { + return ErrRevival + } + return nil +} +func (d *DB) RevivalCurrent(ctx context.Context, account, id string) (bool, error) { + var current string + e := d.sql.QueryRowContext(ctx, d.q(`SELECT character_id FROM account_lives WHERE account_id=?`), account).Scan(¤t) + if errors.Is(e, sql.ErrNoRows) { + return false, nil + } + return current == id, e +} +func (l *Lease) RevivalConsent(ctx context.Context, w *game.World, account, id string, allowed bool) error { + c := w.Characters[id] + if c == nil || c.Account != account || c.View.Entity.State != "dead" || c.RevivalCorpse == "" || w.Corpses[c.RevivalCorpse] == nil || w.Phase == "lost" { + return ErrRevival + } + current, e := l.DB.RevivalCurrent(ctx, account, id) + if e != nil { + return e + } + if !current { + return ErrRevival + } + staged := stageTitleWorld(w) + staged.Characters[id].RevivalAllowed = allowed + if e = l.Save(ctx, staged, ""); e != nil { + return e + } + for id, c := range staged.Characters { + *w.Characters[id] = *c + } + w.Saved() + return nil +} +func (l *Lease) Revive(ctx context.Context, w *game.World, account, corpse, power string) error { + caster := w.ForAccount(account) + if caster == nil { + return ErrRevival + } + active, e := l.DB.ActiveCharacter(ctx, account) + if e != nil { + return e + } + if active == nil || active.ID != caster.View.Entity.ID || active.WorldID != w.ID { + return ErrRevival + } + staged := stageTitleWorld(w) + staged.Corpses = maps.Clone(w.Corpses) + target, e := staged.Revive(staged.Characters[caster.View.Entity.ID], corpse, power) + if e != nil { + return fmt.Errorf("%w: %v", ErrRevival, e) + } + claim := &reviveClaim{target.Account, target.View.Entity.ID, corpse, w.ID} + if e = l.save(ctx, staged, "", nil, "", nil, claim); e != nil { + return e + } + for id, c := range staged.Characters { + *w.Characters[id] = *c + } + w.Corpses = staged.Corpses + w.PendingTitles = nil + w.Saved() + return nil +} diff --git a/server/internal/store/revival_test.go b/server/internal/store/revival_test.go new file mode 100644 index 0000000..b0c5a19 --- /dev/null +++ b/server/internal/store/revival_test.go @@ -0,0 +1,216 @@ +package store + +import ( + "aeternalis/server/content" + "aeternalis/server/internal/game" + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "testing" + "time" +) + +func TestRevivalDurability(t *testing.T) { + testRevivalDurability(t, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "revive.db"))) +} +func TestPostgresRevivalDurability(t *testing.T) { + dsn := os.Getenv("TEST_DATABASE_URL") + if dsn == "" { + t.Skip("TEST_DATABASE_URL not configured") + } + testRevivalDurability(t, dsn) +} +func testRevivalDurability(t *testing.T, dsn string) { + ctx := context.Background() + db, e := Open(ctx, dsn) + if e != nil { + t.Fatal(e) + } + defer db.Close() + b, _ := content.Load() + now := time.Now().UTC() + w := game.New("revive-"+game.ID(), 1, now, b) + l, _, e := db.Acquire(ctx, w) + if e != nil { + t.Fatal(e) + } + c, _ := w.Join("victim-"+game.ID(), "Victim") + rescuer, _ := w.Join("rescuer-"+game.ID(), "Rescuer") + _ = w.Connect(rescuer.View.Entity.ID) + rescuer.View.Entity.Position = c.View.Entity.Position + rescuer.View.Inventory["revival_stone"] = 3 + if e = l.Save(ctx, w, ""); e != nil { + t.Fatal(e) + } + // Create an actual new-system death without ending the world. + c.View.Entity.HP = 0 + w.Advance(now.Add(time.Second), 1) + corpse := c.RevivalCorpse + if corpse == "" { + t.Fatal("death missing corpse identity") + } + if e = l.Save(ctx, w, ""); e != nil { + t.Fatal(e) + } + if e = l.RevivalConsent(ctx, w, c.Account, c.View.Entity.ID, true); e != nil { + t.Fatal(e) + } + if e = l.RevivalConsent(ctx, w, rescuer.Account, c.View.Entity.ID, true); !errors.Is(e, ErrRevival) { + t.Fatal("rescuer set another account's consent", e) + } + before, _ := json.Marshal(w) + stale := *l + stale.Revision-- + if e = stale.Revive(ctx, w, rescuer.Account, corpse, "item"); !errors.Is(e, ErrOwnership) { + t.Fatal("stale revival not fenced", e) + } + after, _ := json.Marshal(w) + if string(before) != string(after) { + t.Fatal("failed revival mutated live world") + } + if e = l.Revive(ctx, w, rescuer.Account, corpse, "item"); e != nil { + t.Fatal(e) + } + if c.View.Entity.State != "alive" || rescuer.View.Inventory["revival_stone"] != 2 { + t.Fatal("revival not applied") + } + if e = l.Revive(ctx, w, rescuer.Account, corpse, "item"); !errors.Is(e, ErrRevival) { + t.Fatal("duplicate revival accepted", e) + } + // Death events survive revival and restart; repeats create distinct corpses. + var count int + if e = db.sql.QueryRowContext(ctx, db.q(`SELECT COUNT(*) FROM character_deaths WHERE character_id=? AND revived=1`), c.View.Entity.ID).Scan(&count); e != nil || count != 1 { + t.Fatal("death history missing", e) + } + c.View.Entity.HP = 0 + w.Advance(now.Add(2*time.Second), 1) + if e = l.Save(ctx, w, ""); e != nil { + t.Fatal(e) + } + if e = l.RevivalConsent(ctx, w, c.Account, c.View.Entity.ID, true); e != nil { + t.Fatal(e) + } + corpse = c.RevivalCorpse + other := game.New("replacement-"+game.ID(), 2, now, b) + ol, _, e := db.Acquire(ctx, other) + if e != nil { + t.Fatal(e) + } + replacement, e := other.Join(c.Account, "Replacement") + if e != nil { + t.Fatal(e) + } + // Simulate an old world binary inserting a replacement during rolling upgrade. + replacementJSON, _ := json.Marshal(replacement) + if _, e = db.sql.ExecContext(ctx, db.q(`INSERT INTO character_records(character_id,account_id,world_id,name,state,character) VALUES(?,?,?,?,?,?)`), replacement.View.Entity.ID, replacement.Account, other.ID, "Replacement", "alive", string(replacementJSON)); e != nil { + t.Fatal(e) + } + // Even killing the replacement cannot restore eligibility for the old life. + replacement.View.Entity.HP = 0 + other.Advance(now.Add(time.Second), 1) + if e = ol.Save(ctx, other, ""); e != nil { + t.Fatal(e) + } + if e = l.Revive(ctx, w, rescuer.Account, corpse, "item"); !errors.Is(e, ErrRevival) { + t.Fatal("replacement death re-enabled old revival", e) + } + if c.View.Entity.State != "dead" || rescuer.View.Inventory["revival_stone"] != 2 || w.Corpses[corpse] == nil { + t.Fatal("rejected old revival spent or moved items") + } + if e = l.Release(ctx); e != nil { + t.Fatal(e) + } + restored := game.New(w.ID, 1, now, b) + var raw []byte + l, raw, e = db.Acquire(ctx, restored) + if e != nil { + t.Fatal(e) + } + if e = json.Unmarshal(raw, restored); e != nil { + t.Fatal(e) + } + if e = restored.Restore(now.Add(3 * time.Second)); e != nil { + t.Fatal(e) + } + _ = restored.Connect(rescuer.View.Entity.ID) + if e = l.Revive(ctx, restored, rescuer.Account, corpse, "item"); !errors.Is(e, ErrRevival) { + t.Fatal("restart lost finality", e) + } + testRevivalRace(t, db) +} + +func testRevivalRace(t *testing.T, db *DB) { + t.Helper() + ctx := context.Background() + b, _ := content.Load() + now := time.Now().UTC() + w := game.New("race-source-"+game.ID(), 1, now, b) + l, _, e := db.Acquire(ctx, w) + if e != nil { + t.Fatal(e) + } + victim, _ := w.Join("race-victim-"+game.ID(), "Victim") + rescuer, _ := w.Join("race-rescuer-"+game.ID(), "Rescuer") + _ = w.Connect(rescuer.View.Entity.ID) + rescuer.View.Entity.Position = victim.View.Entity.Position + rescuer.View.Inventory["revival_stone"] = 1 + if e = l.Save(ctx, w, ""); e != nil { + t.Fatal(e) + } + victim.View.Entity.HP = 0 + w.Advance(now.Add(time.Second), 1) + if e = l.Save(ctx, w, ""); e != nil { + t.Fatal(e) + } + if e = l.RevivalConsent(ctx, w, victim.Account, victim.View.Entity.ID, true); e != nil { + t.Fatal(e) + } + next := game.New("race-next-"+game.ID(), 2, now, b) + nl, _, e := db.Acquire(ctx, next) + if e != nil { + t.Fatal(e) + } + replacement, e := next.Join(victim.Account, "Replacement") + if e != nil { + t.Fatal(e) + } + type outcome struct { + revive bool + err error + } + done := make(chan outcome, 2) + start := make(chan struct{}) + go func() { + <-start + done <- outcome{true, l.Revive(ctx, w, rescuer.Account, victim.RevivalCorpse, "item")} + }() + go func() { <-start; done <- outcome{false, nl.Save(ctx, next, "")} }() + close(start) + wins := 0 + revived := false + for i := 0; i < 2; i++ { + r := <-done + if r.err == nil { + wins++ + revived = r.revive + } else if !errors.Is(r.err, ErrRevival) && !errors.Is(r.err, ErrLivingCharacter) { + t.Fatal("unexpected race failure", r.err) + } + } + if wins != 1 { + t.Fatal("replacement and revival did not produce exactly one winner") + } + active, e := db.ActiveCharacter(ctx, victim.Account) + if e != nil || active == nil { + t.Fatal("race lost active life", e) + } + if revived { + if active.ID != victim.View.Entity.ID || rescuer.View.Inventory["revival_stone"] != 0 { + t.Fatal("revival winner lost identity or cost") + } + } else if active.ID != replacement.View.Entity.ID || rescuer.View.Inventory["revival_stone"] != 1 { + t.Fatal("replacement winner spent revival cost") + } +} diff --git a/server/internal/store/store.go b/server/internal/store/store.go index c14913f..1cf25b5 100644 --- a/server/internal/store/store.go +++ b/server/internal/store/store.go @@ -139,9 +139,9 @@ func (l *Lease) Save(ctx context.Context, w *game.World, claimID string) error { return l.SaveCommand(ctx, w, claimID, nil, "") } func (l *Lease) SaveCommand(ctx context.Context, w *game.World, claimID string, command *Command, outcome string) error { - return l.save(ctx, w, claimID, command, outcome, nil) + return l.save(ctx, w, claimID, command, outcome, nil, nil) } -func (l *Lease) save(ctx context.Context, w *game.World, claimID string, command *Command, outcome string, receipt *craftReceipt) error { +func (l *Lease) save(ctx context.Context, w *game.World, claimID string, command *Command, outcome string, receipt *craftReceipt, revival *reviveClaim) error { live := w w = stageTitleWorld(w) data, err := json.Marshal(w) @@ -162,6 +162,11 @@ func (l *Lease) save(ctx context.Context, w *game.World, claimID string, command if n != 1 { return ErrOwnership } + if revival != nil { + if err = d.checkRevival(ctx, tx, revival); err != nil { + return err + } + } if receipt != nil { if _, err = tx.ExecContext(ctx, d.q(`INSERT INTO craft_receipts(id,account_id,character_id,request_json,result_json) VALUES(?,?,?,?,?)`), receipt.ID, receipt.Account, receipt.CharacterID, receipt.Request, receipt.Result); err != nil { return err diff --git a/server/internal/store/titles.go b/server/internal/store/titles.go index b735fee..c6c0256 100644 --- a/server/internal/store/titles.go +++ b/server/internal/store/titles.go @@ -23,6 +23,8 @@ func stageTitleWorld(w *game.World) *game.World { copy.View.Items = append([]p.ItemInstance{}, c.View.Items...) copy.View.CraftedStacks = append([]p.CraftedStack{}, c.View.CraftedStacks...) copy.View.Crafting = maps.Clone(c.View.Crafting) + copy.View.Powers = maps.Clone(c.View.Powers) + copy.View.Weapons = maps.Clone(c.View.Weapons) copy.View.Inventory = maps.Clone(c.View.Inventory) copy.View.Equipment = maps.Clone(c.View.Equipment) copy.View.AllocatedStats = maps.Clone(c.View.AllocatedStats) diff --git a/server/internal/store/travel.go b/server/internal/store/travel.go index d56fb3f..1b276ba 100644 --- a/server/internal/store/travel.go +++ b/server/internal/store/travel.go @@ -106,6 +106,8 @@ func (l *Lease) PrepareTravel(ctx context.Context, live *game.World, account, re if err = json.Unmarshal(raw, &departing); err != nil { return nil, err } + departing.PendingCast = nil + departing.View.Casting = nil if route == "escape" { game.TakeStack(&departing, "escape_stone", 1) } diff --git a/server/internal/store/travel_test.go b/server/internal/store/travel_test.go index 3d6dcbc..73584ff 100644 --- a/server/internal/store/travel_test.go +++ b/server/internal/store/travel_test.go @@ -71,6 +71,18 @@ func runTravelTests(t *testing.T, dsn string) { if e = source.Connect(id); e != nil { t.Fatal(e) } + c.View.Inventory["book_mend"] = 1 + if e = source.LearnPower(c, "book_mend"); e != nil { + t.Fatal(e) + } + spell := c.View.Powers["mend"] + spell.XP = 25 + spell.ReadyAt = float64(now.Unix() + 30) + c.View.Powers["mend"] = spell + weapon := c.View.Weapons["blades"] + weapon.XP = 29 + c.View.Weapons["blades"] = weapon + source.RefreshStats(c) if e = sl.Save(ctx, source, ""); e != nil { t.Fatal(e) } @@ -171,7 +183,7 @@ func runTravelTests(t *testing.T, dsn string) { if copies != 1 { t.Fatalf("arrival copies: %d", copies) } - if !reflect.DeepEqual(arrived.View.Items, c.View.Items) || !reflect.DeepEqual(arrived.View.Gathering, c.View.Gathering) || !reflect.DeepEqual(arrived.View.AllocatedStats, c.View.AllocatedStats) { + if !reflect.DeepEqual(arrived.View.Powers, c.View.Powers) || !reflect.DeepEqual(arrived.View.Weapons, c.View.Weapons) || !reflect.DeepEqual(arrived.View.Items, c.View.Items) || !reflect.DeepEqual(arrived.View.Gathering, c.View.Gathering) || !reflect.DeepEqual(arrived.View.AllocatedStats, c.View.AllocatedStats) { t.Fatal("item identities or character progression changed during travel") } if arrived.View.Inventory["escape_stone"] != 1 || arrived.View.Inventory["wood"] != 31 || arrived.View.Level != 3 || arrived.View.Experience != 7 || arrived.View.StatPoints != 20 || arrived.View.Skills["combat"] != 29 || arrived.DailySeconds != 123 || arrived.WorldsSurvived != 2 || arrived.View.Entity.ID != id || !reflect.DeepEqual(arrived.View.Titles, c.View.Titles) { diff --git a/server/internal/transport/http.go b/server/internal/transport/http.go index 6f2d093..900dad1 100644 --- a/server/internal/transport/http.go +++ b/server/internal/transport/http.go @@ -99,6 +99,7 @@ func (h *HTTP) Handler() http.Handler { h.portalRoutes(mux) h.travelRoutes(mux) h.craftingRoutes(mux) + h.powerRoutes(mux) h.catalogRoutes(mux) mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { if !h.s.ready.Load() { diff --git a/server/internal/transport/http_test.go b/server/internal/transport/http_test.go index 3382259..6d7e387 100644 --- a/server/internal/transport/http_test.go +++ b/server/internal/transport/http_test.go @@ -142,6 +142,18 @@ func TestHTTPAndSocketSecurity(t *testing.T) { t.Fatal("cross-origin crafting accepted") } } + for _, path := range []string{"/api/revive", "/api/revival/consent"} { + r := request(path, "https://evil.example", "{}", cookie) + r.Body.Close() + if r.StatusCode != 403 { + t.Fatal("cross-origin revival accepted", path) + } + r = request(path, server.URL, "{}", nil) + r.Body.Close() + if r.StatusCode != 401 { + t.Fatal("unauthenticated revival accepted", path) + } + } response = request("/api/craft", server.URL, string(body), cookie) var outcome p.CraftResult if e := json.NewDecoder(response.Body).Decode(&outcome); e != nil { diff --git a/server/internal/transport/powers.go b/server/internal/transport/powers.go new file mode 100644 index 0000000..1e19f9b --- /dev/null +++ b/server/internal/transport/powers.go @@ -0,0 +1,137 @@ +package transport + +import ( + "aeternalis/server/content" + "aeternalis/server/internal/game" + "aeternalis/server/internal/store" + "errors" + "net/http" +) + +func (h *HTTP) powerRoutes(mux *http.ServeMux) { + mux.HandleFunc("GET /api/powers", func(w http.ResponseWriter, r *http.Request) { + account, e := h.auth.account(r) + if e != nil { + fail(w, 401, "sign in required") + return + } + h.s.mu.Lock() + defer h.s.mu.Unlock() + c := h.s.world.ForAccount(account) + if c == nil { + fail(w, 409, "character unavailable") + return + } + books := map[string]string{} + for id, name := range (content.Catalog{Powers: h.s.world.Balance.Powers}).PowerItems() { + if c.View.Inventory[id] > 0 { + books[id] = name + } + } + respond(w, 200, map[string]any{"items": books}) + }) + mux.HandleFunc("GET /api/revival", func(w http.ResponseWriter, r *http.Request) { + account, e := h.auth.account(r) + if e != nil { + fail(w, 401, "sign in required") + return + } + h.s.mu.Lock() + defer h.s.mu.Unlock() + if !h.s.ready.Load() { + fail(w, 503, "world unavailable") + return + } + active, e := h.auth.db.ActiveCharacter(r.Context(), account) + if e != nil { + fail(w, 503, "registry unavailable") + return + } + if active != nil { + respond(w, 200, map[string]any{"active": active.WorldID, "available": false}) + return + } + var dead *game.Character + for _, c := range h.s.world.Characters { + if c.Account == account && c.View.Entity.State == "dead" && c.RevivalCorpse != "" { + current, e := h.auth.db.RevivalCurrent(r.Context(), account, c.View.Entity.ID) + if e != nil { + fail(w, 503, "registry unavailable") + return + } + if current { + dead = c + break + } + } + } + if dead == nil || h.s.world.Phase == "lost" || h.s.world.Corpses[dead.RevivalCorpse] == nil { + respond(w, 200, map[string]bool{"available": false}) + return + } + respond(w, 200, map[string]any{"available": true, "characterId": dead.View.Entity.ID, "name": dead.View.Entity.Name, "corpse": dead.RevivalCorpse, "allowed": dead.RevivalAllowed}) + }) + mux.HandleFunc("POST /api/revival/consent", func(w http.ResponseWriter, r *http.Request) { + account, e := h.auth.account(r) + if e != nil { + fail(w, 401, "sign in required") + return + } + var req struct { + CharacterID string `json:"characterId"` + Allowed bool `json:"allowed"` + } + if decode(w, r, &req) != nil { + fail(w, 400, "invalid consent") + return + } + h.s.mu.Lock() + defer h.s.mu.Unlock() + if !h.s.ready.Load() { + fail(w, 503, "world unavailable") + return + } + if e = h.s.lease.RevivalConsent(r.Context(), h.s.world, account, req.CharacterID, req.Allowed); e != nil { + h.powerFailure(w, e) + return + } + respond(w, 200, map[string]bool{"allowed": req.Allowed}) + }) + mux.HandleFunc("POST /api/revive", func(w http.ResponseWriter, r *http.Request) { + account, e := h.auth.account(r) + if e != nil { + fail(w, 401, "sign in required") + return + } + var req struct { + Corpse string `json:"corpse"` + Power string `json:"power"` + } + if decode(w, r, &req) != nil { + fail(w, 400, "invalid revival") + return + } + h.s.mu.Lock() + defer h.s.mu.Unlock() + if !h.s.ready.Load() { + fail(w, 503, "world unavailable") + return + } + if e = h.s.lease.Revive(r.Context(), h.s.world, account, req.Corpse, req.Power); e != nil { + h.powerFailure(w, e) + return + } + respond(w, 200, map[string]bool{"revived": true}) + }) +} +func (h *HTTP) powerFailure(w http.ResponseWriter, e error) { + if errors.Is(e, store.ErrRevival) || errors.Is(e, store.ErrLivingCharacter) { + fail(w, 409, e.Error()) + return + } + h.s.ready.Store(false) + for _, p := range h.s.peers { + p.close() + } + fail(w, 503, "revival save unavailable; reconnect to check the result") +}