From b65f3e8562b0b99dfd33c5d2ee12cade5fb173b8 Mon Sep 17 00:00:00 2001 From: dingo Date: Wed, 9 Sep 2026 13:27:58 -0400 Subject: [PATCH] Add durable recipe discovery and profession crafting --- client/src/character-panel.ts | 4 +- client/src/character-stats.ts | 2 + client/src/content-editor.ts | 65 +++-- client/src/crafting-panel.ts | 45 ++++ client/src/generated.ts | 155 +++++++++++- client/src/main.ts | 13 +- client/src/player-content.ts | 3 +- client/src/style.css | 1 + docs/ARCHITECTURE.md | 9 + docs/MILESTONE-6.md | 111 ++++++++ planning/PLAYWRIGHT-TODO.md | 3 + planning/SYSTEMS-ROADMAP.md | 9 +- planning/VISION.md | 4 + schemas/protocol.json | 217 +++++++++++++++- server/content/balance.yaml | 37 +++ server/content/combat.go | 5 + server/content/content.go | 6 +- server/content/crafting.go | 218 ++++++++++++++++ server/content/crafting_test.go | 43 ++++ server/content/stats.go | 13 +- server/internal/game/admin_content.go | 9 +- server/internal/game/crafting.go | 307 +++++++++++++++++++++++ server/internal/game/crafting_test.go | 199 +++++++++++++++ server/internal/game/equipment.go | 30 ++- server/internal/game/equipment_test.go | 2 +- server/internal/game/gathering.go | 2 +- server/internal/game/progression_test.go | 2 +- server/internal/game/stats.go | 9 +- server/internal/game/world.go | 66 +++-- server/internal/game/world_test.go | 2 +- server/internal/protocol/generated.go | 161 ++++++++++-- server/internal/store/catalog.go | 47 ++-- server/internal/store/catalog_preview.go | 57 +++++ server/internal/store/crafting.go | 87 +++++++ server/internal/store/crafting_test.go | 218 ++++++++++++++++ server/internal/store/portal.go | 1 + server/internal/store/store.go | 8 + server/internal/store/titles.go | 2 + server/internal/store/travel.go | 5 +- server/internal/transport/crafting.go | 86 +++++++ server/internal/transport/http.go | 3 +- server/internal/transport/http_test.go | 53 ++++ 42 files changed, 2183 insertions(+), 136 deletions(-) create mode 100644 client/src/crafting-panel.ts create mode 100644 docs/MILESTONE-6.md create mode 100644 server/content/crafting.go create mode 100644 server/content/crafting_test.go create mode 100644 server/internal/game/crafting.go create mode 100644 server/internal/game/crafting_test.go create mode 100644 server/internal/store/crafting.go create mode 100644 server/internal/store/crafting_test.go create mode 100644 server/internal/transport/crafting.go diff --git a/client/src/character-panel.ts b/client/src/character-panel.ts index c41e736..45a4fdc 100644 --- a/client/src/character-panel.ts +++ b/client/src/character-panel.ts @@ -11,7 +11,7 @@ function button(label:string,key:string,fn:()=>void,disabled=false){const b=node function request(op:string,target:string,slot=''){sendIntent(op,target,0,0,slot);} function render(){ for(const b of nav.querySelectorAll('button'))b.setAttribute('aria-pressed',String(b.dataset.section===selected)); - const next=JSON.stringify([selected,latest.entity.state,latest.remainingSeconds>0,latest.statPoints,latest.pendingVitalChoices,latest.allocatedStats,latest.stats,latest.items,latest.equipment,latest.inventory,latest.carryWeight,latest.gathering,latest.gatheringEffects,latest.consumables]); + const next=JSON.stringify([selected,latest.entity.state,latest.remainingSeconds>0,latest.statPoints,latest.pendingVitalChoices,latest.allocatedStats,latest.stats,latest.items,latest.equipment,latest.inventory,latest.craftedStacks,latest.carryWeight,latest.gathering,latest.gatheringEffects,latest.consumables]); if(next===signature)return;signature=next; const focus=root.contains(document.activeElement)?(document.activeElement as HTMLElement).dataset.focusKey:undefined; const opened=new Set(Array.from(body.querySelectorAll('details[open]')).map(d=>d.dataset.key));body.replaceChildren(); @@ -32,7 +32,7 @@ function render(){ if(slot==='ring'){const label=node('label','Ring slot'),select=node('select');select.dataset.focusKey=`ring-${item.id}`;select.setAttribute('aria-label',`Ring slot for ${item.name}`);for(let n=1;n<=8;n++)select.append(new Option(`Ring ${n}${c.equipment?.[`ring${n}`]?' · Occupied':' · Empty'}`,`ring${n}`));select.value=rings.get(item.id)??equipmentSlots.find(s=>s.startsWith('ring')&&!c.equipment?.[s])??'ring1';slot=select.value;select.onchange=()=>{slot=select.value;rings.set(item.id,slot)};label.append(select);actions.append(label);} actions.append(button('Equip',`equip-${item.id}`,()=>request('equip',item.id,slot),!active()||!item.equippable),button('Drop',`drop-${item.id}`,()=>request('drop',item.id),!active()));card.append(actions);grid.append(card); } - for(const [key,count] of Object.entries(c.inventory??{}))if(count>0){const card=node('article','','stack-card');card.append(node('span',`${c.stackNames?.[key]??statLabel(key)} × ${count}`),button('Drop one',`drop-stack-${key}`,()=>request('drop',key),!active()));const consumable=c.consumables?.find(v=>v.id===key);if(consumable)card.append(node('p',`${consumable.description} · ${consumable.seconds}s`),modifiersView(consumable.modifiers),button('Use',`consume-${key}`,()=>request('consume',key),!active()));grid.append(card);} + for(const [key,count] of Object.entries(c.inventory??{}))if(count>0){const card=node('article','','stack-card');card.append(node('span',`${c.stackNames?.[key]??statLabel(key)} × ${count}`),button('Drop one',`drop-stack-${key}`,()=>request('drop',key),!active()));const consumable=c.consumables?.find(v=>v.id===key);if(consumable)card.append(node('p',`${consumable.description} · ${consumable.seconds}s`),modifiersView(consumable.modifiers),button('Use',`consume-${key}`,()=>request('consume',key),!active()));for(const batch of c.craftedStacks??[])if(batch.item===key)card.append(node('small',`${batch.quantity} crafted by ${batch.provenance.crafterName} in ${batch.provenance.worldId}`));grid.append(card);} if(!grid.children.length)grid.append(node('p','Your bag is empty.'));body.append(grid); } for(const d of body.querySelectorAll('details'))d.open=opened.has(d.dataset.key); diff --git a/client/src/character-stats.ts b/client/src/character-stats.ts index 363fd1c..e81569f 100644 --- a/client/src/character-stats.ts +++ b/client/src/character-stats.ts @@ -25,12 +25,14 @@ export function statsBreakdown(c:Character) { const row=body.insertRow();const th=node('th',`${g.name}: level ${g.level}, effective ${g.effectiveLevel} · ${g.xp} XP · ${g.xpToNextLevel} to next`);th.colSpan=5;row.append(th); 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; } export function itemDetails(item:ItemInstance,c:Character) { const card=node('article','','gear-card'); const requirements=[`Level ${item.requirements.level}`,...Object.entries(item.requirements.stats??{}).map(([s,v])=>`${statLabel(s)} ${numberText(v)}`),...(item.requirements.titles??[]).map(id=>`Title: ${c.titles?.find(t=>t.id===id)?.name??id}`)]; card.append(node('strong',item.name),node('p',item.description,'progression-note'),node('p',`${statLabel(item.slot)} · Weight ${numberText(item.weight)}`,'progression-note'),node('p',`Requires ${requirements.join(' / ')}`,'gear-requirements'),modifiersView(item.modifiers)); + if(item.provenance)card.append(node('p',`Crafted by ${item.provenance.crafterName} in ${item.provenance.worldId} · ${statLabel(item.provenance.profession)} level ${item.provenance.level}`,'progression-note')); if(item.attack)card.append(node('p',`${item.attack.name} · ${item.attack.delivery} · ${item.attack.effect} · ${item.attack.range}m range · ${item.attack.cooldown}s cooldown · ${item.attack.stamina} stamina · ${item.attack.radius}m area · ${item.attack.duration}s duration`,'progression-note')); if(item.requirementMessage)card.append(node('p',item.requirementMessage,'gear-requirements')); return card; diff --git a/client/src/content-editor.ts b/client/src/content-editor.ts index 643e4ae..0c9248a 100644 --- a/client/src/content-editor.ts +++ b/client/src/content-editor.ts @@ -3,19 +3,52 @@ import { api } from './portal-shared'; import { derivedStats, itemSlots, modifiersView, node, primaryStats, statLabel } from './character-stats'; import type { ContentCatalog as Catalog, ContentRequirement as Requirement, ContentPreview, StatModifier } from './generated'; import { registerMenu } from './menu-focus'; +import type { CraftRecipe, CraftStat, CraftRules } from './generated'; + +function craftPool(){return repeat('Available crafted stats','Add possible stat',value=>{ + 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 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'); + const quantities=(title:string,choices:{id:string;name:string}[],initial:Record,limit:number,max:number)=>repeat<{item:string;quantity:number}>(title,'Add item',value=>{const group=node('div','','catalog-fields'),item=contentChoice(choices,value?.item),amount=number(value?.quantity??1,1,max,'1');group.append(field('Item',item),field('Quantity',amount));return {node:group,read:()=>({item:item.value,quantity:Number(amount.value)})};},Object.entries(initial).map(([item,quantity])=>({item,quantity})),limit); + const inputs=quantities('Exact ingredients',craftMaterials(),initial?.inputs??{},16,1000),outputs=quantities('Outputs',[...craftMaterials(),...catalog.items],initial?.outputs??{},8,100); + const stats=repeat<{stat:string;minimum:number}>('Required stats (without equipment bonuses)','Add required stat',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('At least',minimum));return {node:group,read:()=>({stat:stat.value,minimum:Number(minimum.value)})};},Object.entries(initial?.stats??{}).map(([stat,minimum])=>({stat,minimum})),32); + const titles=node('fieldset');titles.append(node('legend','Required titles'));const choices=catalog.titles.map(t=>{const input=node('input');input.type='checkbox';input.checked=(initial?.titles??[]).includes(t.id);titles.append(field(t.name,input));return {id:t.id,input};}); + const readAmounts=(rows:{item:string;quantity:number}[])=>{if(!rows.length||new Set(rows.map(r=>r.item)).size!==rows.length)throw new Error('Choose each ingredient/output once, with at least one of each.');return Object.fromEntries(rows.map(r=>[r.item,r.quantity]));}; + const fields=form(initial?'Revise recipe':'Create recipe',initial?'update-craft-recipe':'create-craft-recipe',()=>{const required=stats.read();if(new Set(required.map(r=>r.stat)).size!==required.length)throw new Error('Each required stat may appear once.');return {...(initial?{targetId:initial.id}:{}),craftRecipe:{...values.read(),profession:profession.value,level:Number(level.value),xp:Number(xp.value),inputs:readAmounts(inputs.read()),outputs:readAmounts(outputs.read()),stats:Object.fromEntries(required.map(r=>[r.stat,r.minimum])),titles:choices.filter(c=>c.input.checked).map(c=>c.id)}};}); + fields.append(values.node,field('Crafting profession',profession),field('Difficulty level (under-level attempts allowed)',level),field('Profession XP on success',xp),node('p','Ingredients must match exactly. Players discover this recipe through attempts; publishing does not reveal it. Equipment rolls come from its available crafted stat pool.','muted'),inputs.node,outputs.node,stats.node,titles); +} +function craftingList(){ + const c=catalog.crafting;if(!c){list.append(node('p','Crafting content is not available.'));return;} + if(section==='craft-recipes'){ + list.append(button('Create recipe',()=>recipeForm())); + for(const r of c.recipes){const d=node('details','','catalog-definition');d.append(node('summary',`${r.name} · revision ${r.revision}`),node('p',`${c.professions.find(p=>p.id===r.profession)?.name??r.profession} · difficulty ${r.level} · ${r.xp} XP on success`),readableDefinition(r),button('Edit recipe',()=>recipeForm(r)));list.append(d);} + }else if(section==='craft-professions'){ + list.append(button('Create crafting profession',()=>{if(editing||saving)return;const identityFields=identity(),base=number(100,1,1000000,'1'),per=number(50,1,1000000,'1'),max=number(1000,1,1000,'1');const fields=form('Create crafting profession','create-craft-profession',()=>({craftProfession:{...identityFields.read(),baseXp:Number(base.value),xpPerLevel:Number(per.value),maxLevel:Number(max.value)}}));fields.append(identityFields.node,field('First level XP',base),field('Additional XP per level',per),field('Maximum level',max));})); + for(const p of c.professions){const d=node('details','','catalog-definition');d.append(node('summary',p.name),readableDefinition(p));list.append(d);} + }else if(section==='craft-materials'){ + list.append(node('p','Stackable components for recipes. Food, traps, and building components do not gain action effects from their name alone.','muted'),button('Create crafting material',()=>{if(editing||saving)return;const values=identity();form('Create crafting material','create-craft-material',()=>({craftMaterial:values.read()})).append(values.node);})); + for(const m of c.materials){const d=node('details','','catalog-definition');d.append(node('summary',m.name),node('p',m.description));list.append(d);} + }else{ + list.append(readableDefinition(c.rules),button('Edit crafting tuning',()=>{if(editing||saving)return;const inputs=new Map();const fields=form('Crafting tuning','update-craft-rules',()=>({craftRules:Object.fromEntries([...inputs].map(([key,input])=>[key,Number(input.value)]))}));for(const [key,value] of Object.entries(c.rules)){const input=number(value,0,100);inputs.set(key as keyof CraftRules,input);fields.append(field(statLabel(key),input));}fields.append(node('p','Failure rises exponentially below recipe level and falls above it. Material loss falls with absolute profession level; each ingredient rounds up to at least one unit. Quality bias favors higher rolls. Percent fields use 0–100.','muted'));})); + } +} type Audit={id:string;actor:string;op:string;target:string;reason:string;version:number;createdAt:number}; const statKeys=[...primaryStats,...derivedStats],metrics=['level','kills','worldKills','bossKills','worldsSurvived','gathering','crafting','combat','deaths',...statKeys]; 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'],['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'],['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;} function text(value='',max=80){const i=node('input');i.value=value;i.maxLength=max;i.required=true;return i;} function number(value:number,min=0,max=1000000,step='any'){const i=text(String(value));i.type='number';i.min=String(min);i.max=String(max);i.step=step;return i;} function select(keys:string[],value=''){const i=node('select');for(const key of keys)i.append(new Option(statLabel(key),key));i.value=keys.includes(value)?value:keys[0];return i;} -function identity(initial?:{name:string;description:string}){const group=node('div','','catalog-fields'),name=text(initial?.name??''),description=node('textarea');description.value=initial?.description??'';description.maxLength=500;description.rows=3;group.append(field('Name',name),field('Description',description),node('p',initial?'This biome keeps its identity. Publishing creates its next revision.':'A permanent ID is assigned automatically when you publish.','muted'));return {node:group,read:()=>({name:name.value.trim(),description:description.value.trim()})};} +function identity(initial?:{name:string;description:string}){const group=node('div','','catalog-fields'),name=text(initial?.name??''),description=node('textarea');description.value=initial?.description??'';description.maxLength=500;description.rows=3;group.append(field('Name',name),field('Description',description),node('p',initial?'This definition keeps its identity. Publishing creates its next revision.':'A permanent ID is assigned automatically when you publish.','muted'));return {node:group,read:()=>({name:name.value.trim(),description:description.value.trim()})};} function repeat(title:string,addLabel:string,make:(value?:T)=>{node:HTMLElement;read:()=>T},initial:T[]=[],max=64){ const group=node('fieldset','','catalog-repeatable'),rows=node('div'),entries:{node:HTMLElement;read:()=>T}[]=[];group.append(node('legend',title),rows); const add=button(addLabel,()=>append());group.append(add); @@ -44,7 +77,7 @@ function form(title:string,op:string,payload:()=>object){ reason.required=true;reason.minLength=5;reason.maxLength=240;reason.rows=2;error.setAttribute('role','alert'); const focus=registerMenu(form,()=>{editing=false;refresh.disabled=saving;forms.replaceChildren();focus.dispose()}); const save=node('button','Publish changes','button');save.type='submit';const cancel=button('Cancel',()=>focus.close()),check=button('Preview changes',()=>void previewChanges());const footer=node('footer');footer.append(cancel,check,save); - form.append(node('h3',title),node('p',`Based on catalog version ${expectedVersion}. Biome edits publish new revisions; other definitions remain immutable.`,'muted'),fields,field('Reason for change',reason),error,preview,footer);forms.replaceChildren(form); + form.append(node('h3',title),node('p',`Based on catalog version ${expectedVersion}. Biome and recipe edits publish new revisions; equipment and other definitions retain their published values.`,'muted'),fields,field('Reason for change',reason),error,preview,footer);forms.replaceChildren(form); const previous=document.activeElement;queueMicrotask(()=>{if(form.isConnected)focus.opened(previous)}); form.addEventListener('input',()=>preview.replaceChildren());form.addEventListener('change',()=>preview.replaceChildren()); fields.addEventListener('click',event=>{if((event.target as HTMLElement).closest('button'))preview.replaceChildren()}); @@ -63,13 +96,15 @@ 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.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} of the existing biome`:'Permanent ID assigned on publication.','muted')); + 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; + 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(' / '))); if(r.item)root.append(node('p',`Requires level ${r.item.requirements.level}; ${Object.entries(r.item.requirements.stats??{}).map(([key,n])=>`${statLabel(key)} ≥ ${n}`).join(' / ')}`),node('p',`Required titles: ${(r.item.requirements.titles??[]).join(', ')||'None'}`)); 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.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; } @@ -83,13 +118,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 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(),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); + 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); } function statsForm(){ if(editing||saving){show('Finish or cancel the open draft first.');return;} @@ -100,12 +136,13 @@ 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(['attacks','mobs','loot','spawns'].includes(section)){combatList(); + 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'){ list.append(button('Create title',titleForm));for(const t of catalog.titles??[]){const d=node('details','','catalog-definition');d.append(node('summary',t.name),node('p',`${t.id} · ${t.scope} · ${t.description}`),node('p',(t.requirements??[]).map(r=>`${statLabel(r.metric)} ≥ ${r.atLeast}`).join(' / ')),modifiersView(t.effects.modifiers));if(t.effects.damage||t.effects.moveSpeed)d.append(node('p',`Damage ${t.effects.damage}; movement ${t.effects.moveSpeed}`));list.append(d);} }else if(section==='items'){ - list.append(button('Create equipment',itemForm));for(const i of catalog.items??[]){const d=node('details','','catalog-definition');d.append(node('summary',i.name),node('p',`${i.id} · ${statLabel(i.slot)} · Weight ${i.weight} · Drop chance ${i.dropChance??0}%`),node('p',i.description),node('p',`Requires level ${i.requirements.level}; ${Object.entries(i.requirements.stats??{}).map(([k,v])=>`${statLabel(k)} ${v}`).join(', ')} ${(i.requirements.titles??[]).map(id=>`Title: ${catalog.titles.find(t=>t.id===id)?.name??id}`).join(', ')}`),modifiersView(i.modifiers));list.append(d);} + list.append(button('Create equipment',itemForm));for(const i of catalog.items??[]){const d=node('details','','catalog-definition');d.append(node('summary',i.name),node('p',`${i.id} · ${statLabel(i.slot)} · Weight ${i.weight} · Drop chance ${i.dropChance??0}%`),node('p',i.description),node('p',`Requires level ${i.requirements.level}; ${Object.entries(i.requirements.stats??{}).map(([k,v])=>`${statLabel(k)} ${v}`).join(', ')} ${(i.requirements.titles??[]).map(id=>`Title: ${catalog.titles.find(t=>t.id===id)?.name??id}`).join(', ')}`),modifiersView(i.modifiers),node('p',`${i.craftRolls??0} crafted stat rolls`),readableDefinition(i.craftPool??[]));list.append(d);} }else if(section==='requirements'){ list.append(button('Create requirement set',()=>setForm('requirements')),node('p','Named thresholds reusable in titles and equipment. Equipment supports level/stat thresholds; other metrics are title-only.','muted')); for(const s of catalog.requirementSets??[]){const d=node('details','','catalog-definition');d.append(node('summary',s.name),node('p',`${s.id} · ${s.description}`),node('p',s.requirements.map(r=>`${statLabel(r.metric)} ≥ ${r.atLeast}`).join(' / ')));list.append(d);} @@ -121,12 +158,12 @@ async function load(){if(loading||editing)return;loading=true;refresh.disabled=t export function showCatalog(parent:HTMLElement){if(root.parentElement!==parent)parent.replaceChildren(root);if(!catalog&&!loading)void load();} export function hasCatalogDraft(){return editing;} -function contentChoice(values:{id:string;name:string}[]) { - const input=node('select');input.required=true;for(const v of values)input.append(new Option(v.name,v.id));return input; +function contentChoice(values:{id:string;name:string}[],initial?:string) { + const input=node('select');input.required=true;for(const v of values)input.append(new Option(v.name,v.id));if(initial)input.value=initial;return input; } 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??[])]; + 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 reference=(v:string)=>names.find(n=>n.id===v)?.name??statLabel(v); if(Array.isArray(value)) { const list=node('ul','','catalog-values'); @@ -142,7 +179,7 @@ function readableDefinition(value:unknown, context=''):HTMLElement { let item=raw; if(key==='resources'&&item==null&&typeof record.id==='string')item=(catalog.gathering?.resources??[]).filter(r=>r.biomes.includes(record.id as string)).map(r=>r.id); if(key==='biomes'&&'skillId' in record&&record.id) item=(catalog.gathering?.biomes??[]).filter(b=>b.resources!=null?b.resources.includes(record.id as string):(raw as string[]).includes(b.id)).map(b=>b.id); - const term=node('dt',labels[key]??statLabel(key)),detail=node('dd');detail.append(readableDefinition(item,key));fields.append(term,detail); + const term=node('dt',context==='inputs'||context==='outputs'?reference(key):labels[key]??statLabel(key)),detail=node('dd');detail.append(readableDefinition(item,key));fields.append(term,detail); }return fields; } if(value==null||value==='')return node('span',context==='group'?'Independent':'None'); @@ -201,7 +238,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.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,...(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 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{ diff --git a/client/src/crafting-panel.ts b/client/src/crafting-panel.ts new file mode 100644 index 0000000..935c414 --- /dev/null +++ b/client/src/crafting-panel.ts @@ -0,0 +1,45 @@ +import type { Character, CraftRequest, CraftResult, KnownRecipe } from './generated'; +import { api, APIError } from './portal-shared'; +import { node, statLabel, numberText } from './character-stats'; + +const root=node('section','','crafting-workbench'),form=node('form'),profession=node('select'),rows=node('div'),summary=node('p'),status=node('p'),known=node('div'); +const add=node('button','Add ingredient'),attempt=node('button','Attempt craft'),refresh=node('button','Refresh known recipes'); +add.type=refresh.type='button';attempt.type='submit';status.setAttribute('role','status');profession.setAttribute('aria-label','Crafting profession'); +form.append(profession,summary,rows,add,attempt);root.append(node('h3','Crafting workbench'),node('p','Choose a profession and offer exact ingredient quantities. A valid recipe can fail. Matched recipes are recorded; failed experiments give no XP.'),form,status,refresh,known); +let latest:Character,prefix='',character='',signature='',inventorySignature='',busy=false,pending:CraftRequest|undefined,stale:string[]=[]; +const entries:{item:HTMLSelectElement;amount:HTMLInputElement;row:HTMLElement}[]=[]; +const key=()=>`aeternalis.craft.${character}`; +function quantities(){const result:Record={};for(const e of entries){if(result[e.item.value]!==undefined)throw new Error('Each ingredient can appear once.');result[e.item.value]=Number(e.amount.value);}return result;} +function addRow(item='',quantity=1){if(entries.length>=16)return;const row=node('div','','recipe'),select=node('select'),amount=node('input'),remove=node('button','Remove');select.setAttribute('aria-label','Ingredient');select.required=true;const keys=new Set([...Object.keys(latest.inventory).filter(k=>latest.inventory[k]>0),...(item?[item]:[])]);for(const id of keys)select.append(new Option(`${latest.stackNames?.[id]??statLabel(id)} (${latest.inventory[id]??0})`,id));if(item)select.value=item;amount.type='number';amount.min='1';amount.max='1000';amount.step='1';amount.required=true;amount.value=String(quantity);amount.setAttribute('aria-label','Ingredient quantity');remove.type='button';const e={item:select,amount,row};entries.push(e);remove.onclick=()=>{entries.splice(entries.indexOf(e),1);row.remove()};row.append(select,amount,remove);rows.append(row);} +function clearRows(){entries.length=0;rows.replaceChildren();} +function refreshIngredients(){ + const next=JSON.stringify([latest.inventory,latest.stackNames]);if(next===inventorySignature)return;inventorySignature=next; + for(const e of entries){const selected=e.item.value,keys=new Set([...Object.keys(latest.inventory).filter(id=>latest.inventory[id]>0),...(selected?[selected]:[])]);e.item.replaceChildren();for(const id of keys)e.item.append(new Option(`${latest.stackNames?.[id]??statLabel(id)} (${latest.inventory[id]??0})`,id));if(selected)e.item.value=selected;} +} +function updateSummary(){const p=latest.crafting?.[profession.value];summary.textContent=p?`Level ${p.level} · ${p.xp} XP · ${p.xpToNextLevel} to next. Failure loses ${numberText(p.lossPercent)}% of each ingredient, rounded up (minimum one).`:'';} +function renderKnown(){ + const recipes=Object.values(latest.discoveredRecipes??{});known.replaceChildren(node('h3','Discovered recipes')); + if(!recipes.length)known.append(node('p','No recipes discovered by this character yet.')); + for(const d of recipes){const r=d.recipe,detail=node('details'),load=node('button','Use ingredients');load.type='button';load.disabled=busy||!!pending||stale.includes(r.id);load.onclick=()=>{profession.value=r.profession;clearRows();for(const [id,n] of Object.entries(r.inputs))addRow(id,n);updateSummary();};detail.append(node('summary',`${r.name} · revision ${r.revision}`),node('p',`${latest.crafting?.[r.profession]?.name??statLabel(r.profession)} · difficulty ${r.level} · ${r.xp} XP on success`),node('p',Object.entries(r.inputs).map(([id,n])=>`${latest.stackNames?.[id]??statLabel(id)} × ${n}`).join(' + ')),node('p',stale.includes(r.id)?'This recipe has been revised. Experiment to discover its current version.':r.description),load);known.append(detail);} +} +async function reloadKnown(){try{const data=await api<{known:KnownRecipe[];stale:string[];earnsXP:boolean}>(prefix+'/api/crafting');stale=data.stale;latest={...latest,discoveredRecipes:Object.fromEntries(data.known.map(k=>[k.recipe.id,k]))};status.textContent=data.earnsXP?'Only successful crafting grants XP.':'Crafting here consumes resources and records discoveries, but grants no XP.';renderKnown();}catch(e){status.textContent=(e as Error).message;}} +add.onclick=()=>addRow();profession.onchange=updateSummary;refresh.onclick=()=>void reloadKnown(); +form.onsubmit=async event=>{ + event.preventDefault();if(busy)return; + try{ + if(!pending){if(!entries.length)throw new Error('Add ingredients first.');pending={id:crypto.randomUUID(),characterId:character,profession:profession.value,ingredients:quantities()};sessionStorage.setItem(key(),JSON.stringify(pending));} + busy=true;form.inert=true;refresh.disabled=true; + const result=await api(prefix+'/api/craft',pending); + pending=undefined;sessionStorage.removeItem(key());status.textContent=`${result.message} Spent: ${Object.entries(result.consumed).map(([id,n])=>`${latest.stackNames?.[id]??statLabel(id)} × ${n}`).join(', ')}.`; + if(result.recipe){latest={...latest,discoveredRecipes:{...latest.discoveredRecipes,[result.recipe.recipe.id]:result.recipe}};renderKnown();} + }catch(e){status.textContent=(e as Error).message;if(e instanceof APIError&&e.status<500){pending=undefined;sessionStorage.removeItem(key());}else if(pending){status.textContent+=' Retry this pending attempt to recover its saved result.';}} + finally{busy=false;form.inert=false;refresh.disabled=false;attempt.textContent=pending?'Retry pending attempt':'Attempt craft';profession.disabled=add.disabled=!!pending;rows.inert=!!pending;signature='';} +}; +export function craftingPanel(c:Character,worldPrefix:string){ + latest=c;prefix=worldPrefix; + if(character!==c.entity.id){character=c.entity.id;signature='';clearRows();pending=undefined;try{const saved=sessionStorage.getItem(key());if(saved)pending=JSON.parse(saved) as CraftRequest;}catch{sessionStorage.removeItem(key());}profession.replaceChildren();for(const p of Object.values(c.crafting??{}))profession.append(new Option(p.name,p.id));if(pending){profession.value=pending.profession;for(const [id,n] of Object.entries(pending.ingredients))addRow(id,n);}else addRow();void reloadKnown();} + refreshIngredients(); + const next=JSON.stringify([c.crafting,c.discoveredRecipes,!!pending]);if(next!==signature){signature=next;const selected=profession.value;profession.replaceChildren();for(const p of Object.values(c.crafting??{}))profession.append(new Option(p.name,p.id));if(selected)profession.value=selected;updateSummary();renderKnown();} + attempt.disabled=busy||c.entity.state!=='alive'||c.remainingSeconds<=0;attempt.textContent=pending?'Retry pending attempt':'Attempt craft';profession.disabled=add.disabled=!!pending;rows.inert=!!pending; + return root; +} diff --git a/client/src/generated.ts b/client/src/generated.ts index 4df34d9..d5007c3 100644 --- a/client/src/generated.ts +++ b/client/src/generated.ts @@ -4,12 +4,15 @@ export interface Protocol { catalogChange?: ContentChange; catalogPreview?: ContentPreview; catalogResult?: ContentResult; + craftRequest?: CraftRequest; + craftResult?: CraftResult; intent: Intent; snapshot: Snapshot; } export interface ContentCatalog { combat?: CombatContent; + crafting?: CraftingContent; effectSets?: EffectSet[]; gathering?: GatheringContent; items: ItemDefinition[]; @@ -93,6 +96,56 @@ export interface MobSpawn { z: number; } +export interface CraftingContent { + materials: CraftMaterial[]; + professions: GatheringSkill[]; + recipes: CraftRecipe[]; + rules: CraftRules; +} + +export interface CraftMaterial { + description: string; + id: string; + name: string; +} + +export interface GatheringSkill { + baseXp: number; + description: string; + id: string; + maxLevel: number; + name: string; + xpPerLevel: number; +} + +export interface CraftRecipe { + description: string; + id: string; + inputs: { [key: string]: number }; + level: number; + name: string; + outputs: { [key: string]: number }; + profession: string; + revision: number; + stats: { [key: string]: number }; + titles: string[]; + xp: number; +} + +export interface CraftRules { + baseFailure: number; + baseLoss: number; + cooldown: number; + lossDecay: number; + maxFailure: number; + maxQualityBias: number; + minFailure: number; + minLoss: number; + overLevelDecay: number; + qualityPerLevel: number; + underLevelGrowth: number; +} + export interface EffectSet { description: string; id: string; @@ -149,17 +202,10 @@ export interface ResourceDefinition { xp: number; } -export interface GatheringSkill { - baseXp: number; - description: string; - id: string; - maxLevel: number; - name: string; - xpPerLevel: number; -} - export interface ItemDefinition { attackId?: string; + craftPool?: CraftStat[]; + craftRolls?: number; description: string; dropChance: number; id: string; @@ -170,6 +216,14 @@ export interface ItemDefinition { weight: number; } +export interface CraftStat { + max: number; + min: number; + percent: boolean; + stat: string; + weight: number; +} + export interface ItemRequirements { level: number; stats: { [key: string]: number }; @@ -213,6 +267,10 @@ export interface ContentChange { attack?: CombatAttackDraft; biome?: BiomeDefinitionDraft; consumable?: GatheringConsumableDraft; + craftMaterial?: CraftMaterialDraft; + craftProfession?: GatheringSkillDraft; + craftRecipe?: CraftRecipeDraft; + craftRules?: CraftRules; effectSet?: EffectSetDraft; effectSetIds?: string[]; expectedVersion: number; @@ -269,10 +327,9 @@ export interface GatheringConsumableDraft { seconds: number; } -export interface EffectSetDraft { +export interface CraftMaterialDraft { description: string; id?: string; - modifiers: StatModifier[]; name: string; } @@ -285,8 +342,31 @@ export interface GatheringSkillDraft { xpPerLevel: number; } +export interface CraftRecipeDraft { + description: string; + id?: string; + inputs: { [key: string]: number }; + level: number; + name: string; + outputs: { [key: string]: number }; + profession: string; + revision?: number; + stats: { [key: string]: number }; + titles: string[]; + xp: number; +} + +export interface EffectSetDraft { + description: string; + id?: string; + modifiers: StatModifier[]; + name: string; +} + export interface ItemDraft { attackId?: string; + craftPool?: CraftStat[]; + craftRolls?: number; description: string; dropChance: number; id?: string; @@ -380,6 +460,28 @@ export interface ContentResult { version: number; } +export interface CraftRequest { + characterId: string; + id: string; + ingredients: { [key: string]: number }; + profession: string; +} + +export interface CraftResult { + consumed: { [key: string]: number }; + created: string[]; + id: string; + message: string; + recipe?: KnownRecipe; + success: boolean; + valid: boolean; +} + +export interface KnownRecipe { + discoveredAt: number; + recipe: CraftRecipe; +} + export interface Intent { op: string; seq: number; @@ -463,6 +565,9 @@ export interface Character { attack?: CombatAttack; carryWeight: number; consumables?: GatheringConsumable[]; + craftedStacks?: CraftedStack[]; + crafting?: { [key: string]: CraftProgress }; + discoveredRecipes?: { [key: string]: KnownRecipe }; entity: Entity; equipment: { [key: string]: string }; experience: number; @@ -489,6 +594,33 @@ export interface Character { titles: TitleAward[]; } +export interface CraftedStack { + id: string; + item: string; + provenance: CraftProvenance; + quantity: number; +} + +export interface CraftProvenance { + at: number; + characterId: string; + crafterName: string; + level: number; + profession: string; + recipeId: string; + recipeRevision: number; + worldId: string; +} + +export interface CraftProgress { + id: string; + level: number; + lossPercent: number; + name: string; + xp: number; + xpToNextLevel: number; +} + export interface SkillProgress { effectiveLevel: number; experience: StatValue; @@ -523,6 +655,7 @@ export interface ItemInstance { id: string; modifiers: StatModifier[]; name: string; + provenance?: CraftProvenance; requirementMessage: string; requirements: ItemRequirements; slot: string; diff --git a/client/src/main.ts b/client/src/main.ts index b8ac077..6b40225 100644 --- a/client/src/main.ts +++ b/client/src/main.ts @@ -1,5 +1,6 @@ import './style.css'; import { showTravel } from './travel'; +import { craftingPanel } from './crafting-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'; @@ -8,8 +9,7 @@ import { characterPanel } from './character-panel'; import { InputActions, isEditing, type InputAction } from './input-actions'; import { hasOpenMenu, registerMenu } from './menu-focus'; -type Recipe = { Inputs: Record; Outputs: Record }; -type Config = { worldId: string; kind: string; development: boolean; worlds: { id: string; url: string }[]; recipes: Record; playerSpeed: number; gatherRange: number; attackRange: number }; +type Config = { worldId: string; kind: string; development: boolean; worlds: { id: string; url: string }[]; playerSpeed: number; gatherRange: number; attackRange: number }; const $ = (id: string) => document.getElementById(id) as T; const visible = (id: string, show: boolean) => { $(id).hidden = !show; }; const pretty = (s: string) => s.replaceAll('_', ' ').replace(/^./, c => c.toUpperCase()); @@ -133,14 +133,7 @@ function inventory(c: Character) { $('earned-titles').replaceChildren(permanentTitles(c.titles)); const parent = $('inventory-items'), panel = characterPanel(c, send); if (panel.parentElement !== parent) parent.replaceChildren(panel); - const recipes = $('recipes'); recipes.replaceChildren(); - for (const [name, recipe] of Object.entries(config.recipes)) { - const row = document.createElement('div'); row.className = 'recipe'; - const label = document.createElement('div'), title = document.createElement('strong'), cost = document.createElement('small'); - title.textContent = pretty(name); cost.textContent = Object.entries(recipe.Inputs).map(([k, n]) => `${n} ${pretty(k)}`).join(' + '); label.append(title, cost); - const button = document.createElement('button'); button.textContent = 'Craft'; button.title = `Craft ${name}`; button.disabled = Object.entries(recipe.Inputs).some(([item, count]) => (c.inventory[item] ?? 0) < count); button.onclick = () => send('craft', name); - row.append(label, button); recipes.append(row); - } + const recipes=$('recipes'),workbench=craftingPanel(c,worldPrefix);if(workbench.parentElement!==recipes)recipes.replaceChildren(workbench); const skills = $('skills'); skills.replaceChildren(); for(const g of Object.values(c.gathering??{})){const label=document.createElement('span');label.textContent=`${g.name} · Level ${g.level} (effective ${g.effectiveLevel})`;const amount=document.createElement('b');amount.textContent=`${g.xp} XP · ${g.xpToNextLevel} to next`;label.append(amount);skills.append(label);} for (const skill of ['crafting', 'combat']) { const label = document.createElement('span'); label.textContent = pretty(skill); const amount = document.createElement('b'); amount.textContent = `${c.skills[skill] ?? 0} XP`; label.append(amount); skills.append(label); } diff --git a/client/src/player-content.ts b/client/src/player-content.ts index 441e01e..896d236 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={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={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;} @@ -21,6 +21,7 @@ export function playerContent(record:RecordCharacter,enabled:boolean,onQueued:() 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)); + for(const m of catalog.crafting?.materials??[])choice.append(new Option(m.name,m.id)); for(const id of ['axe','flint_and_steel','fishing_pole','wood','ore','herb','bandage','escape_stone'])choice.append(new Option(statLabel(id),id)); notice.textContent='Items go into the bag. Equipment requirements still apply when equipping.';break; case 'remove-item': diff --git a/client/src/style.css b/client/src/style.css index 9dfe8f1..4a9e3a9 100644 --- a/client/src/style.css +++ b/client/src/style.css @@ -11,3 +11,4 @@ @media(max-height:520px){.movement:not([hidden]){bottom:178px}} #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} diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 2522b36..5393eb7 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -204,6 +204,15 @@ inactive mobs retain state. Region spawn rules use persisted explored biome IDs ## Security scope +Crafting accepts authenticated ingredient offers through `POST /api/craft` under +the world mutex. The server stages the character, resolves the secret recipe and +random result, then saves consumption, discovery, XP, item provenance, and an +account-scoped replay receipt in one lease/revision-fenced transaction. Live state +and success feedback are published only after commit. Recipe definitions are +admin-only; players receive only their own recorded discoveries. Crafted stack +batches accompany aggregate inventory totals through consumption, corpse loot, +and travel. See [milestone 6](MILESTONE-6.md) for bounds and manual checks. + - Production login: OIDC verification (issuer, audience, signature, expiry), PKCE, state and nonce binding, and opaque server-side sessions. - Secure, HttpOnly, SameSite cookies. No client-controlled identity or progression. diff --git a/docs/MILESTONE-6.md b/docs/MILESTONE-6.md new file mode 100644 index 0000000..8bc0b24 --- /dev/null +++ b/docs/MILESTONE-6.md @@ -0,0 +1,111 @@ +# Milestone 6: crafting and item quality + +Implemented for manual testing. Open **Inventory and crafting → Crafting +workbench** in the game. In **Control → Game content**, use Recipes, Crafting +professions, Crafting materials, Crafting tuning, and Equipment. + +## Player behavior + +- Choose a profession and offer exact ingredient quantities. Ingredient order + does not matter. Unknown combinations fail and consume part of the offer. +- Matching a recipe records it on this character even when the craft fails. + Recipes with unmet stat/title requirements report the requirement without + spending materials or recording the recipe. Difficulty level is a probability + penalty, never an entry gate. +- Successful crafts spend all offered ingredients and create the authored outputs. + Only success grants profession and character XP. Hub crafting uses resources, + produces items, and records discoveries with every XP track unchanged. +- Higher profession levels reduce failure and resource loss, and favor higher + random stat rolls. Equipment keeps its fixed modifiers plus the configured + number of distinct weighted pool entries. Rolls are made once on the server. +- Crafted equipment and stacks retain maker character ID, maker name, world of + creation, profession/level, timestamp, and recipe ID/revision. Inventory shows + maker/world labels; equipment shows its actual rolled modifiers. +- Mixed stacks consume unmarked units first, then crafted batches in acquisition + order. Dropping part of a batch preserves provenance under a new batch ID. + Death, looting, restart, and world travel preserve the remaining provenance. +- Profession XP and discovered recipes belong to the character. Replacement + starts them fresh. Previous generic crafting XP remains as historical progress; + it is not copied into nine new professions. + +## Administration + +Recipe forms select a profession, difficulty, XP reward, inputs/outputs, and +optional stat/title requirements. Permanent definition IDs and recipe revisions +are assigned by the server. Edit a recipe to publish its next revision using the +same identity; concurrent stale edits are rejected. Old discoveries retain their +recorded version until the character experiments with the new recipe. Refresh +known recipes in the workbench to identify revised discoveries. + +Crafting professions use the same reusable XP-curve definition as gathering. +Materials are stackable recipe inputs/outputs, and can be granted/removed using +player controls or selected in loot tables. Equipment creation includes a +weighted stat pool, flat/percentage ranges, and roll count. Published equipment +definitions and existing owned rolls remain immutable. + +Recipes stay out of public configuration and the browser bundle. The authenticated +crafting endpoint returns only that character's discoveries. Admin catalog access +still requires the existing admin role. + +## Provisional tuning and limits + +Defaults live in `server/content/balance.yaml`; Control can publish tuning changes: + +- Equal-level failure: 25%. Above-level failure decays exponentially to 1%; below + level failure rises exponentially toward 99.9%. Under-level attempts are allowed. +- Failure loses 80% of each ingredient at level 1, decreasing exponentially to + 10%. Quantities round up, with at least one unit lost per offered ingredient. +- Quality bias grows by 0.03 per profession level beyond 1, capped at 8. +- Each profession starts at level 1: 100 XP for level 2, +50 XP per next level, + maximum level 1000. Starter successes award 20 profession XP. +- One-second attempt cooldown; 1–16 ingredient types, 1–1000 units each; at most + eight output types and 100 output units. Each character can hold 2048 crafted + stack batches. Equipment supports up to eight rolls from 32 possible pool entries. + +Crafting currently works anywhere an alive, online, unsheltered character may act, +with daily time remaining. Stations, craft channels, equipment as ingredients, +food/trap activation, rune application, and structure placement are future work. +Cook, trap master, rune master, builder, and the other professions can produce +components now; components do not gain action effects from their names. + +## Durability + +`craft_receipts` stores an account-scoped attempt ID, exact request, and saved +result. Consumption, discovery, rolls, XP, provenance, and receipt commit in the +same lease/revision-fenced world transaction before publication. Reusing an ID +with different inputs is rejected; repeating the same request returns its result +without another roll or spend, including after restart or travel. The browser +retains an uncertain attempt in session storage and offers a retry. + +Legacy saved catalogs/worlds receive the initial crafting definitions once. +Existing owned items are unchanged. Deployment requires the normal database +migration and a coordinated server/client build. Old clients using recipe-name +craft intents receive a message to use the workbench. + +## Manual checklist + +1. Grant wood, ore, and herbs through Control. In Weapon Smithing, offer wood ×3 + and ore ×2. Confirm valid feedback/discovery on either outcome. On success, + inspect the spear's random bonus, maker, and world. Try wood ×1 for invalid + feedback and resource loss without discovery/XP. +2. Try Alchemist with herbs ×2. Confirm successful bandages carry maker/world + labels; use, drop, and loot them, including a stack mixed with granted bandages. +3. Create a material and recipe in Control, preview and publish. Confirm a player + sees it only after discovering it. Edit it and verify revision increases without + a duplicate recipe; refresh the player's known recipes and rediscover it. +4. Create equipment with a stat pool and recipe. Compare actual rolled modifiers + between crafts. Raise recipe difficulty to exercise under-level failures, then + use low XP thresholds on a test profession to compare higher-level outcomes. +5. Bring ingredients to a hub. Craft successfully and fail a valid recipe; + confirm spending/discovery while character and profession XP stay unchanged. +6. Reload/travel after crafting, inspect provenance, and check known recipes and + profession XP. If a request is interrupted, retry the pending attempt and + confirm inventory does not duplicate. Replacement must reset discoveries/XP. +7. Check the workbench and recipe forms on mobile, keyboard focus, and Esc closing + the focused menu. Report layout or interaction issues before the next milestone. + +Focused Go coverage exercises recipe validation/revisions, failed and successful +crafts, quality distributions, hub XP, death/loot/consumption/replacement, restart, +travel, replay, stale-lease rollback, daily-time rejection, and HTTP auth/secrecy. +PostgreSQL variants require `TEST_DATABASE_URL`. Browser automation stays deferred +in [PLAYWRIGHT-TODO.md](../planning/PLAYWRIGHT-TODO.md). diff --git a/planning/PLAYWRIGHT-TODO.md b/planning/PLAYWRIGHT-TODO.md index 9ca98da..67b724b 100644 --- a/planning/PLAYWRIGHT-TODO.md +++ b/planning/PLAYWRIGHT-TODO.md @@ -18,6 +18,9 @@ automation. These are future tasks, not completion gates for the current milesto - [ ] Equipment attachments, animation transitions, and sound settings/event playback. - [ ] Hub-instance switching, admission limits, escape items, and victory portals. - [ ] Craft discovery/valid failure, materials, quality rolls, and maker/world labels. +- [ ] Milestone 6: recipe revisions and stale discoveries, repeatable ingredient + forms, pending-attempt recovery, new profession/material selectors, and + crafted stack provenance after consumption/drop/loot. - [ ] 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. diff --git a/planning/SYSTEMS-ROADMAP.md b/planning/SYSTEMS-ROADMAP.md index 63772aa..b90b4ae 100644 --- a/planning/SYSTEMS-ROADMAP.md +++ b/planning/SYSTEMS-ROADMAP.md @@ -550,7 +550,7 @@ milestones, not time estimates or new tested-capacity claims. | 4. Combat and mobs | Melee/ranged combat, navigation across chunks, projectiles/AoE, mob/spawn/loot editors | Targeting, damage, chunk crossings, loot, basic Control spawning | | 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 | Valid-recipe feedback, resource use, quality/provenance, discoveries without hub XP | +| 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 | | 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 | @@ -601,9 +601,10 @@ First discussion, because these affect the architecture: claims remain reserved. Decide treatment of titles already inherited under the old account ledger. Progression/discovery reset on replacement is now confirmed; only cosmetic access carries forward. -5. Crafting: exact matching, stations, discovery-recording trigger, probability/refund - tuning, stat pool/quality rules, and provenance-aware stacking? Hub crafting uses - resources and records discoveries without XP; random failure is settled. +5. Crafting: milestone 6 uses exact matching, valid-attempt discovery, weighted + equipment pools, provenance batches, and configurable provisional failure/loss + curves. See its handoff for defaults. Stations, equipment inputs, and further + quality tuning remain open; hub crafting uses resources without XP. 6. Instances: dungeon entry/reset/death rules, escape-item details, travel edge cases, hub daily-time policy, and house damage? Hub-instance switching, survival-world commitment, escape items, and victory portals are confirmed. diff --git a/planning/VISION.md b/planning/VISION.md index 82e09f8..9f226d5 100644 --- a/planning/VISION.md +++ b/planning/VISION.md @@ -170,6 +170,10 @@ Tracked across: - Networking: is node size (128x128x128) fixed/final, or a placeholder for tuning? ## Backlog +- 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 + provisional tuning, limits, and the manual handoff. - September 9: layered valley/ridge/forest terrain and jumping over/onto actual obstacles are deferred in [Environment backlog](ENVIRONMENT-BACKLOG.md), using the supplied landscape reference. Continue the agreed presentation milestone. diff --git a/schemas/protocol.json b/schemas/protocol.json index 4ec412f..29f82ae 100644 --- a/schemas/protocol.json +++ b/schemas/protocol.json @@ -4,14 +4,35 @@ "type": "object", "additionalProperties": false, "properties": { - "intent": {"$ref": "#/definitions/Intent"}, - "snapshot": {"$ref": "#/definitions/Snapshot"}, - "catalog": {"$ref": "#/definitions/ContentCatalog"}, - "catalogChange": {"$ref": "#/definitions/ContentChange"}, - "catalogPreview": {"$ref": "#/definitions/ContentPreview"}, - "catalogResult": {"$ref": "#/definitions/ContentResult"} + "intent": { + "$ref": "#/definitions/Intent" + }, + "snapshot": { + "$ref": "#/definitions/Snapshot" + }, + "catalog": { + "$ref": "#/definitions/ContentCatalog" + }, + "catalogChange": { + "$ref": "#/definitions/ContentChange" + }, + "catalogPreview": { + "$ref": "#/definitions/ContentPreview" + }, + "catalogResult": { + "$ref": "#/definitions/ContentResult" + }, + "craftRequest": { + "$ref": "#/definitions/CraftRequest" + }, + "craftResult": { + "$ref": "#/definitions/CraftResult" + } }, - "required": ["intent", "snapshot"], + "required": [ + "intent", + "snapshot" + ], "definitions": { "ContentRequirement": { "type": "object", "additionalProperties": false, @@ -47,7 +68,9 @@ "dropChance": {"type": "number"}, "requirements": {"$ref": "#/definitions/ItemRequirements"}, "modifiers": {"type": "array", "items": {"$ref": "#/definitions/StatModifier"}}, - "attackId": {"type": "string"} + "attackId": {"type": "string"}, + "craftPool": {"type": "array", "items": {"$ref": "#/definitions/CraftStat"}}, + "craftRolls": {"type": "integer"} }, "required": ["id", "name", "description", "slot", "weight", "dropChance", "requirements", "modifiers"] }, @@ -69,7 +92,8 @@ "requirementSets": {"type": "array", "items": {"$ref": "#/definitions/RequirementSet"}}, "effectSets": {"type": "array", "items": {"$ref": "#/definitions/EffectSet"}}, "gathering": {"$ref": "#/definitions/GatheringContent"}, - "combat": {"$ref": "#/definitions/CombatContent"} + "combat": {"$ref": "#/definitions/CombatContent"}, + "crafting": {"$ref": "#/definitions/CraftingContent"} }, "required": ["version", "titles", "items", "stats"] }, @@ -95,7 +119,11 @@ "mob": {"$ref": "#/definitions/MobDefinitionDraft"}, "loot": {"$ref": "#/definitions/LootTableDraft"}, "spawn": {"$ref": "#/definitions/MobSpawnDraft"}, - "targetId": {"type": "string"} + "targetId": {"type": "string"}, + "craftRecipe": {"$ref": "#/definitions/CraftRecipeDraft"}, + "craftProfession": {"$ref": "#/definitions/GatheringSkillDraft"}, + "craftMaterial": {"$ref": "#/definitions/CraftMaterialDraft"}, + "craftRules": {"$ref": "#/definitions/CraftRules"} }, "required": ["id", "expectedVersion", "op", "reason"] }, @@ -123,7 +151,9 @@ "dropChance": {"type": "number"}, "requirements": {"$ref": "#/definitions/ItemRequirements"}, "modifiers": {"type": "array", "items": {"$ref": "#/definitions/StatModifier"}}, - "attackId": {"type": "string"} + "attackId": {"type": "string"}, + "craftPool": {"type": "array", "items": {"$ref": "#/definitions/CraftStat"}}, + "craftRolls": {"type": "integer"} }, "required": ["name", "description", "slot", "weight", "dropChance", "requirements", "modifiers"] }, @@ -204,7 +234,10 @@ "gatherAttempt": {"type": "integer"}, "consumables": {"type": "array", "items": {"$ref": "#/definitions/GatheringConsumable"}}, "stackNames": {"type": "object", "additionalProperties": {"type": "string"}}, - "attack": {"$ref": "#/definitions/CombatAttack"} + "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"}} }, "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"] }, @@ -246,7 +279,8 @@ "modifiers": {"type": "array", "items": {"$ref": "#/definitions/StatModifier"}}, "equippable": {"type": "boolean"}, "requirementMessage": {"type": "string"}, - "attack": {"$ref": "#/definitions/CombatAttack"} + "attack": {"$ref": "#/definitions/CombatAttack"}, + "provenance": {"$ref": "#/definitions/CraftProvenance"} }, "required": ["id", "definitionId", "name", "description", "slot", "weight", "requirements", "modifiers", "equippable", "requirementMessage"] }, @@ -645,6 +679,163 @@ "at": {"type": "number"} }, "required": ["id", "projectileId", "phase", "position", "destination", "speed", "outcome", "at"] + }, + "CraftStat": { + "type": "object", "additionalProperties": false, + "properties": { + "stat": {"type": "string"}, + "min": {"type": "number"}, + "max": {"type": "number"}, + "percent": {"type": "boolean"}, + "weight": {"type": "number"} + }, + "required": ["stat", "min", "max", "percent", "weight"] + }, + "CraftMaterial": { + "type": "object", "additionalProperties": false, + "properties": { + "id": {"type": "string"}, + "name": {"type": "string"}, + "description": {"type": "string"} + }, + "required": ["id", "name", "description"] + }, + "CraftMaterialDraft": { + "type": "object", "additionalProperties": false, + "properties": { + "id": {"type": "string"}, + "name": {"type": "string"}, + "description": {"type": "string"} + }, + "required": ["name", "description"] + }, + "CraftRecipe": { + "type": "object", "additionalProperties": false, + "properties": { + "id": {"type": "string"}, + "revision": {"type": "integer"}, + "name": {"type": "string"}, + "description": {"type": "string"}, + "profession": {"type": "string"}, + "level": {"type": "integer"}, + "xp": {"type": "integer"}, + "inputs": {"type": "object", "additionalProperties": {"type": "integer"}}, + "outputs": {"type": "object", "additionalProperties": {"type": "integer"}}, + "stats": {"type": "object", "additionalProperties": {"type": "number"}}, + "titles": {"type": "array", "items": {"type": "string"}} + }, + "required": ["id", "revision", "name", "description", "profession", "level", "xp", "inputs", "outputs", "stats", "titles"] + }, + "CraftRecipeDraft": { + "type": "object", "additionalProperties": false, + "properties": { + "id": {"type": "string"}, + "revision": {"type": "integer"}, + "name": {"type": "string"}, + "description": {"type": "string"}, + "profession": {"type": "string"}, + "level": {"type": "integer"}, + "xp": {"type": "integer"}, + "inputs": {"type": "object", "additionalProperties": {"type": "integer"}}, + "outputs": {"type": "object", "additionalProperties": {"type": "integer"}}, + "stats": {"type": "object", "additionalProperties": {"type": "number"}}, + "titles": {"type": "array", "items": {"type": "string"}} + }, + "required": ["name", "description", "profession", "level", "xp", "inputs", "outputs", "stats", "titles"] + }, + "CraftRules": { + "type": "object", "additionalProperties": false, + "properties": { + "baseFailure": {"type": "number"}, + "minFailure": {"type": "number"}, + "maxFailure": {"type": "number"}, + "overLevelDecay": {"type": "number"}, + "underLevelGrowth": {"type": "number"}, + "baseLoss": {"type": "number"}, + "minLoss": {"type": "number"}, + "lossDecay": {"type": "number"}, + "qualityPerLevel": {"type": "number"}, + "maxQualityBias": {"type": "number"}, + "cooldown": {"type": "number"} + }, + "required": ["baseFailure", "minFailure", "maxFailure", "overLevelDecay", "underLevelGrowth", "baseLoss", "minLoss", "lossDecay", "qualityPerLevel", "maxQualityBias", "cooldown"] + }, + "CraftingContent": { + "type": "object", "additionalProperties": false, + "properties": { + "professions": {"type": "array", "items": {"$ref": "#/definitions/GatheringSkill"}}, + "materials": {"type": "array", "items": {"$ref": "#/definitions/CraftMaterial"}}, + "recipes": {"type": "array", "items": {"$ref": "#/definitions/CraftRecipe"}}, + "rules": {"$ref": "#/definitions/CraftRules"} + }, + "required": ["professions", "materials", "recipes", "rules"] + }, + "CraftProvenance": { + "type": "object", "additionalProperties": false, + "properties": { + "characterId": {"type": "string"}, + "crafterName": {"type": "string"}, + "worldId": {"type": "string"}, + "recipeId": {"type": "string"}, + "recipeRevision": {"type": "integer"}, + "profession": {"type": "string"}, + "level": {"type": "integer"}, + "at": {"type": "number"} + }, + "required": ["characterId", "crafterName", "worldId", "recipeId", "recipeRevision", "profession", "level", "at"] + }, + "CraftedStack": { + "type": "object", "additionalProperties": false, + "properties": { + "id": {"type": "string"}, + "item": {"type": "string"}, + "quantity": {"type": "integer"}, + "provenance": {"$ref": "#/definitions/CraftProvenance"} + }, + "required": ["id", "item", "quantity", "provenance"] + }, + "CraftProgress": { + "type": "object", "additionalProperties": false, + "properties": { + "id": {"type": "string"}, + "name": {"type": "string"}, + "level": {"type": "integer"}, + "xp": {"type": "integer"}, + "xpToNextLevel": {"type": "integer"}, + "lossPercent": {"type": "number"} + }, + "required": ["id", "name", "level", "xp", "xpToNextLevel", "lossPercent"] + }, + "KnownRecipe": { + "type": "object", "additionalProperties": false, + "properties": { + "recipe": {"$ref": "#/definitions/CraftRecipe"}, + "discoveredAt": {"type": "number"} + }, + "required": ["recipe", "discoveredAt"] + }, + "CraftRequest": { + "type": "object", "additionalProperties": false, + "properties": { + "id": {"type": "string"}, + "characterId": {"type": "string"}, + "profession": {"type": "string"}, + "ingredients": {"type": "object", "additionalProperties": {"type": "integer"}} + }, + "required": ["id", "characterId", "profession", "ingredients"] + }, + "CraftResult": { + "type": "object", "additionalProperties": false, + "properties": { + "id": {"type": "string"}, + "valid": {"type": "boolean"}, + "success": {"type": "boolean"}, + "message": {"type": "string"}, + "consumed": {"type": "object", "additionalProperties": {"type": "integer"}}, + "created": {"type": "array", "items": {"type": "string"}}, + "recipe": {"$ref": "#/definitions/KnownRecipe"} + }, + "required": ["id", "valid", "success", "message", "consumed", "created"] } } } diff --git a/server/content/balance.yaml b/server/content/balance.yaml index 1edda1c..a5e77da 100644 --- a/server/content/balance.yaml +++ b/server/content/balance.yaml @@ -195,9 +195,46 @@ items: requirements: { level: 1, stats: {}, titles: [] } modifiers: [] - id: spear + craftRolls: 1 + craftPool: + - { stat: meleeDamage, min: 1, max: 6, percent: false, weight: 2 } + - { stat: strength, min: 1, max: 3, percent: false, weight: 1 } + - { stat: criticalChance, min: 1, max: 4, percent: false, weight: 1 } name: Spear description: A crafted close-combat weapon. slot: weapon weight: 3 requirements: { level: 1, stats: {}, titles: [] } modifiers: [{ stat: meleeDamage, flat: 14, percent: 0 }] + +# Milestone 6 provisional crafting tuning. Percentages use 0-100. +crafting: + rules: { baseFailure: 25, minFailure: 1, maxFailure: 99.9, overLevelDecay: 0.12, underLevelGrowth: 0.25, baseLoss: 80, minLoss: 10, lossDecay: 0.025, qualityPerLevel: 0.03, maxQualityBias: 8, cooldown: 1 } + professions: + - { id: weapon_smithing, name: "Weapon Smithing", description: "Weapon Smithing progression", baseXp: 100, xpPerLevel: 50, maxLevel: 1000 } + - { id: armor_making, name: "Armor Making", description: "Armor Making progression", baseXp: 100, xpPerLevel: 50, maxLevel: 1000 } + - { id: jeweler, name: "Jeweler", description: "Jeweler progression", baseXp: 100, xpPerLevel: 50, maxLevel: 1000 } + - { id: carver, name: "Carver", description: "Carver progression", baseXp: 100, xpPerLevel: 50, maxLevel: 1000 } + - { id: rune_master, name: "Rune Master", description: "Rune Master progression", baseXp: 100, xpPerLevel: 50, maxLevel: 1000 } + - { id: alchemist, name: "Alchemist", description: "Alchemist progression", baseXp: 100, xpPerLevel: 50, maxLevel: 1000 } + - { id: trap_master, name: "Trap Master", description: "Trap Master progression", baseXp: 100, xpPerLevel: 50, maxLevel: 1000 } + - { id: cook, name: "Cook", description: "Cook progression", baseXp: 100, xpPerLevel: 50, maxLevel: 1000 } + - { id: builder, name: "Builder", description: "Builder progression", baseXp: 100, xpPerLevel: 50, maxLevel: 1000 } + materials: + - { id: armor_padding, name: "Armor padding", description: "Crafted component; further uses are defined by recipes." } + - { id: polished_gem, name: "Polished gem", description: "Crafted component; further uses are defined by recipes." } + - { id: carved_handle, name: "Carved handle", description: "Crafted component; further uses are defined by recipes." } + - { id: rune_dust, name: "Rune dust", description: "Crafted component; further uses are defined by recipes." } + - { id: trap_parts, name: "Trap parts", description: "Crafted component; further uses are defined by recipes." } + - { id: ration, name: "Ration", description: "Crafted component; further uses are defined by recipes." } + - { id: building_component, name: "Building component", description: "Crafted component; further uses are defined by recipes." } + recipes: + - {"id": "recipe_spear", "revision": 1, "name": "Spear", "description": "Starter spear recipe.", "profession": "weapon_smithing", "level": 1, "xp": 20, "inputs": {"wood": 3, "ore": 2}, "outputs": {"spear": 1}, "stats": {}, "titles": []} + - {"id": "recipe_padding", "revision": 1, "name": "Armor padding", "description": "Starter armor padding recipe.", "profession": "armor_making", "level": 1, "xp": 20, "inputs": {"wood": 2, "herb": 1}, "outputs": {"armor_padding": 1}, "stats": {}, "titles": []} + - {"id": "recipe_gem", "revision": 1, "name": "Polished gem", "description": "Starter polished gem recipe.", "profession": "jeweler", "level": 1, "xp": 20, "inputs": {"ore": 3}, "outputs": {"polished_gem": 1}, "stats": {}, "titles": []} + - {"id": "recipe_handle", "revision": 1, "name": "Carved handle", "description": "Starter carved handle recipe.", "profession": "carver", "level": 1, "xp": 20, "inputs": {"wood": 2}, "outputs": {"carved_handle": 1}, "stats": {}, "titles": []} + - {"id": "recipe_rune", "revision": 1, "name": "Rune dust", "description": "Starter rune dust recipe.", "profession": "rune_master", "level": 1, "xp": 20, "inputs": {"ore": 1, "herb": 2}, "outputs": {"rune_dust": 1}, "stats": {}, "titles": []} + - {"id": "recipe_bandage", "revision": 1, "name": "Bandage", "description": "Starter bandage recipe.", "profession": "alchemist", "level": 1, "xp": 20, "inputs": {"herb": 2}, "outputs": {"bandage": 1}, "stats": {}, "titles": []} + - {"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": []} diff --git a/server/content/combat.go b/server/content/combat.go index 599d0ef..3d35868 100644 --- a/server/content/combat.go +++ b/server/content/combat.go @@ -129,6 +129,11 @@ func (c Catalog) validateCombat() error { attacks[a.ID] = true } items := map[string]bool{} + if c.Crafting != nil { + for _, m := range c.Crafting.Materials { + items[m.ID] = true + } + } for _, id := range []string{"axe", "flint_and_steel", "fishing_pole", "wood", "ore", "herb", "bandage", "escape_stone"} { items[id] = true } diff --git a/server/content/content.go b/server/content/content.go index 7022f81..84aa958 100644 --- a/server/content/content.go +++ b/server/content/content.go @@ -19,6 +19,7 @@ type Recipe struct { } type Balance struct { + Crafting *CraftingContent `yaml:"crafting"` Combat *CombatContent `yaml:"combat"` CombatRules *CombatRules `yaml:"combatRules"` Gathering *GatheringContent `yaml:"gathering"` @@ -80,12 +81,15 @@ 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 { + return err + } if b.CombatRules != nil { if err := b.CombatRules.Validate(); err != nil { return err } } - if err := (Catalog{Combat: b.Combat, Items: b.Items, Gathering: b.Gathering}).validateCombat(); err != nil { + if err := (Catalog{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 new file mode 100644 index 0000000..1dba333 --- /dev/null +++ b/server/content/crafting.go @@ -0,0 +1,218 @@ +package content + +import ( + "encoding/json" + "fmt" + "math" + "slices" +) + +type CraftMaterial struct { + ID string `json:"id" yaml:"id"` + Name string `json:"name" yaml:"name"` + Description string `json:"description" yaml:"description"` +} +type CraftStat struct { + Stat string `json:"stat" yaml:"stat"` + Min float64 `json:"min" yaml:"min"` + Max float64 `json:"max" yaml:"max"` + Percent bool `json:"percent" yaml:"percent"` + Weight float64 `json:"weight" yaml:"weight"` +} +type CraftRecipe struct { + ID string `json:"id" yaml:"id"` + Revision int64 `json:"revision" yaml:"revision"` + Name string `json:"name" yaml:"name"` + Description string `json:"description" yaml:"description"` + Profession string `json:"profession" yaml:"profession"` + Level int64 `json:"level" yaml:"level"` + XP int64 `json:"xp" yaml:"xp"` + Inputs map[string]int64 `json:"inputs" yaml:"inputs"` + Outputs map[string]int64 `json:"outputs" yaml:"outputs"` + Stats map[string]float64 `json:"stats" yaml:"stats"` + Titles []string `json:"titles" yaml:"titles"` +} +type CraftRules struct { + BaseFailure float64 `json:"baseFailure" yaml:"baseFailure"` + MinFailure float64 `json:"minFailure" yaml:"minFailure"` + MaxFailure float64 `json:"maxFailure" yaml:"maxFailure"` + OverLevelDecay float64 `json:"overLevelDecay" yaml:"overLevelDecay"` + UnderLevelGrowth float64 `json:"underLevelGrowth" yaml:"underLevelGrowth"` + BaseLoss float64 `json:"baseLoss" yaml:"baseLoss"` + MinLoss float64 `json:"minLoss" yaml:"minLoss"` + LossDecay float64 `json:"lossDecay" yaml:"lossDecay"` + QualityPerLevel float64 `json:"qualityPerLevel" yaml:"qualityPerLevel"` + MaxQualityBias float64 `json:"maxQualityBias" yaml:"maxQualityBias"` + Cooldown float64 `json:"cooldown" yaml:"cooldown"` +} +type CraftingContent struct { + Professions []GatheringSkill `json:"professions" yaml:"professions"` + Materials []CraftMaterial `json:"materials" yaml:"materials"` + Recipes []CraftRecipe `json:"recipes" yaml:"recipes"` + Rules CraftRules `json:"rules" yaml:"rules"` +} + +func (r CraftRules) Validate() error { + if !finiteRange(r.BaseFailure, 0, 100) || !finiteRange(r.MinFailure, 0, r.BaseFailure) || !finiteRange(r.MaxFailure, r.BaseFailure, 100) || !finiteRange(r.OverLevelDecay, .001, 2) || !finiteRange(r.UnderLevelGrowth, .001, 2) || !finiteRange(r.BaseLoss, 1, 100) || !finiteRange(r.MinLoss, 1, r.BaseLoss) || !finiteRange(r.LossDecay, .001, 2) || !finiteRange(r.QualityPerLevel, 0, 1) || !finiteRange(r.MaxQualityBias, 1, 20) || !finiteRange(r.Cooldown, .1, 60) { + return fmt.Errorf("invalid crafting probability, loss, quality or cooldown tuning") + } + return nil +} +func (r CraftRules) Failure(level, required int64) float64 { + gap := float64(level - required) + chance := r.BaseFailure * math.Exp(-math.Max(0, gap)*r.OverLevelDecay) + if gap < 0 { + chance = 100 - (100-r.BaseFailure)*math.Exp(gap*r.UnderLevelGrowth) + } + return math.Max(r.MinFailure, math.Min(r.MaxFailure, chance)) +} +func (r CraftRules) Loss(level int64) float64 { + return math.Max(r.MinLoss, r.BaseLoss*math.Exp(-float64(max(0, level-1))*r.LossDecay)) +} +func SkillLevel(s GatheringSkill, xp int64) (int64, int64) { + level := int64(1) + for level < s.MaxLevel { + need := s.BaseXP + (level-1)*s.XPPerLevel + if xp < need { + return level, need - xp + } + xp -= need + level++ + } + return level, 0 +} +func (c Catalog) StackIDs() map[string]bool { + ids := map[string]bool{} + for _, id := range []string{"axe", "flint_and_steel", "fishing_pole", "wood", "ore", "herb", "bandage", "escape_stone"} { + ids[id] = true + } + if c.Gathering != nil { + for _, r := range c.Gathering.Resources { + if r.Output == "self" { + ids[r.ID] = true + } + } + for _, v := range c.Gathering.Consumables { + ids[v.ID] = true + } + } + if c.Crafting != nil { + for _, m := range c.Crafting.Materials { + ids[m.ID] = true + } + } + return ids +} +func ValidateCraftPool(item ItemDefinition) error { + if item.CraftRolls < 0 || item.CraftRolls > 8 || item.CraftRolls > int64(len(item.CraftPool)) || len(item.CraftPool) > 32 { + return fmt.Errorf("invalid number of crafted stat rolls") + } + seen := map[string]bool{} + for _, s := range item.CraftPool { + key := fmt.Sprintf("%s:%t", s.Stat, s.Percent) + if seen[key] || !KnownStat(s.Stat) || !finiteRange(s.Weight, .01, 1000) || !finiteRange(s.Min, -1000000, 1000000) || !finiteRange(s.Max, s.Min, 1000000) || (s.Percent && (s.Min < -100 || s.Max > 10000)) { + return fmt.Errorf("invalid or duplicate crafted stat pool entry") + } + seen[key] = true + } + if len(item.Modifiers)+int(item.CraftRolls) > 64 { + return fmt.Errorf("crafted result has too many modifiers") + } + return nil +} +func (c Catalog) validateCrafting() error { + if c.Crafting == nil { + return nil + } + v := c.Crafting + if len(v.Professions) < 1 || len(v.Professions) > 64 || len(v.Materials) > 256 || len(v.Recipes) > 512 { + return fmt.Errorf("invalid crafting content limits") + } + if err := v.Rules.Validate(); err != nil { + return err + } + professions := map[string]bool{} + for _, s := range v.Professions { + if !validSetIdentity(s.ID, s.Name, s.Description) || professions[s.ID] || s.BaseXP < 1 || s.BaseXP > 1000000 || s.XPPerLevel < 1 || s.XPPerLevel > 1000000 || s.MaxLevel < 1 || s.MaxLevel > 1000 { + return fmt.Errorf("invalid crafting profession") + } + professions[s.ID] = true + } + base := c + base.Crafting = nil + stacks := base.StackIDs() + outputs := base.StackIDs() + for _, i := range c.Items { + outputs[i.ID] = true + } + for _, m := range v.Materials { + if !validSetIdentity(m.ID, m.Name, m.Description) || outputs[m.ID] { + return fmt.Errorf("invalid or colliding crafting material") + } + outputs[m.ID] = true + stacks[m.ID] = true + } + titles := map[string]bool{} + for _, t := range c.Titles { + titles[t.ID] = true + } + ids, combinations := map[string]bool{}, map[string]bool{} + for _, r := range v.Recipes { + if !validSetIdentity(r.ID, r.Name, r.Description) || ids[r.ID] || r.Revision < 1 || !professions[r.Profession] || r.Level < 1 || r.Level > 1000 || r.XP < 1 || r.XP > 1000000 || len(r.Inputs) < 1 || len(r.Inputs) > 16 || len(r.Outputs) < 1 || len(r.Outputs) > 8 || len(r.Stats) > 32 || len(r.Titles) > 16 { + return fmt.Errorf("invalid crafting recipe %q", r.Name) + } + ids[r.ID] = true + for id, n := range r.Inputs { + if !stacks[id] || n < 1 || n > 1000 { + return fmt.Errorf("recipe inputs require stack materials and quantities 1-1000") + } + } + count := int64(0) + for id, n := range r.Outputs { + if !outputs[id] || n < 1 || n > 100 { + return fmt.Errorf("invalid recipe output") + } + count += n + } + if count > 100 { + return fmt.Errorf("at most 100 output units per craft") + } + raw, _ := json.Marshal(r.Inputs) + key := r.Profession + ":" + string(raw) + if combinations[key] { + return fmt.Errorf("ambiguous ingredient combination in profession") + } + combinations[key] = true + for stat, n := range r.Stats { + if !KnownStat(stat) || !finiteRange(n, 0, 1000000) { + return fmt.Errorf("invalid crafting stat requirement") + } + } + seen := map[string]bool{} + for _, id := range r.Titles { + if !titles[id] || seen[id] { + return fmt.Errorf("unknown or repeated crafting title requirement") + } + seen[id] = true + } + } + return nil +} + +// Old worlds/catalogs receive the new crafting system once. Owned items keep +// their copied modifiers; only future crafts use the seed stat pools. +func (c *Catalog) RestoreCrafting(defaults Balance) { + if c.Crafting != nil { + return + } + c.Crafting = defaults.Crafting + c.Items = slices.Clone(c.Items) + for i := range c.Items { + for _, seed := range defaults.Items { + if seed.ID == c.Items[i].ID { + c.Items[i].CraftPool = seed.CraftPool + c.Items[i].CraftRolls = seed.CraftRolls + } + } + } +} diff --git a/server/content/crafting_test.go b/server/content/crafting_test.go new file mode 100644 index 0000000..8a8fb91 --- /dev/null +++ b/server/content/crafting_test.go @@ -0,0 +1,43 @@ +package content + +import ( + "math" + "testing" +) + +func TestCraftContentValidationAndCurves(t *testing.T) { + c, e := DefaultCatalog() + if e != nil { + t.Fatal(e) + } + r := c.Crafting.Rules + if !(r.Failure(1, 10) > r.Failure(1, 1) && r.Failure(20, 1) < r.Failure(1, 1) && r.Loss(20) < r.Loss(1)) { + t.Fatal("craft level curves reversed") + } + if r.Failure(1, 1000) != r.MaxFailure || r.Failure(1000, 1) != r.MinFailure || r.Loss(1000) != r.MinLoss { + t.Fatal("curve bounds ignored") + } + for _, change := range []func(*Catalog){ + func(c *Catalog) { + r := c.Crafting.Recipes[0] + r.ID = "duplicate" + c.Crafting.Recipes = append(c.Crafting.Recipes, r) + }, + func(c *Catalog) { c.Crafting.Recipes[0].Profession = "missing" }, + func(c *Catalog) { c.Crafting.Recipes[0].Inputs = map[string]int64{"spear": 1} }, + func(c *Catalog) { c.Crafting.Recipes[0].Outputs = map[string]int64{"missing": 1} }, + func(c *Catalog) { c.Crafting.Materials[0].ID = "spear" }, + func(c *Catalog) { c.Crafting.Rules.BaseFailure = math.NaN() }, + func(c *Catalog) { c.Items[0].CraftRolls = 9 }, + func(c *Catalog) { c.Crafting.Recipes[0].Titles = []string{"missing"} }, + } { + fresh, e := DefaultCatalog() + if e != nil { + t.Fatal(e) + } + change(&fresh) + if fresh.Validate() == nil { + t.Fatal("invalid craft catalog accepted") + } + } +} diff --git a/server/content/stats.go b/server/content/stats.go index 1016434..706c746 100644 --- a/server/content/stats.go +++ b/server/content/stats.go @@ -35,6 +35,8 @@ type ItemRequirements struct { Titles []string `json:"titles" yaml:"titles"` } type ItemDefinition struct { + CraftPool []CraftStat `json:"craftPool,omitempty" yaml:"craftPool"` + CraftRolls int64 `json:"craftRolls,omitempty" yaml:"craftRolls"` AttackID string `json:"attackId,omitempty" yaml:"attackId"` ID string `json:"id" yaml:"id"` Name string `json:"name" yaml:"name"` @@ -46,6 +48,7 @@ type ItemDefinition struct { Modifiers []StatModifier `json:"modifiers" yaml:"modifiers"` } type Catalog struct { + Crafting *CraftingContent `json:"crafting,omitempty"` Combat *CombatContent `json:"combat,omitempty"` Gathering *GatheringContent `json:"gathering,omitempty"` Version int64 `json:"version"` @@ -99,7 +102,10 @@ func ValidItemSlot(slot string) bool { return slices.Contains([]string{"helmet", "mask", "chest", "shoulders", "pants", "boots", "gloves", "earrings", "necklace", "ring", "weapon", "offhand", "cape", "bag"}, slot) } func (item ItemDefinition) Validate() error { - if slices.Contains([]string{"axe", "flint_and_steel", "fishing_pole", "wood", "ore", "herb", "bandage"}, item.ID) { + if err := ValidateCraftPool(item); err != nil { + return err + } + if slices.Contains([]string{"axe", "flint_and_steel", "fishing_pole", "wood", "ore", "herb", "bandage", "escape_stone"}, item.ID) { return fmt.Errorf("equipment ID conflicts with a stackable item") } if math.IsNaN(item.DropChance) || math.IsInf(item.DropChance, 0) || item.DropChance < 0 || item.DropChance > 100 { @@ -126,6 +132,9 @@ func (item ItemDefinition) Validate() error { return ValidateModifiers(item.Modifiers) } func (c Catalog) Validate() error { + if err := c.validateCrafting(); err != nil { + return err + } if err := c.validateCombat(); err != nil { return err } @@ -201,5 +210,5 @@ func DefaultCatalog() (Catalog, error) { if err != nil { return Catalog{}, err } - return Catalog{Combat: b.Combat, Gathering: b.Gathering, Version: 1, Titles: b.Titles, Items: b.Items, Stats: *b.Stats}, nil + return Catalog{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 f0eca62..d2516c6 100644 --- a/server/internal/game/admin_content.go +++ b/server/internal/game/admin_content.go @@ -47,6 +47,13 @@ func (w *World) AdminItems(c *Character, op, value string) error { known = true } } + if w.Balance.Crafting != nil { + for _, m := range w.Balance.Crafting.Materials { + if m.ID == id { + known = true + } + } + } for _, definition := range w.Balance.Items { if definition.ID == id { known = true @@ -79,7 +86,7 @@ func (w *World) AdminItems(c *Character, op, value string) error { if c.View.Inventory[id] < n { return errors.New("player no longer holds that item quantity") } - c.View.Inventory[id] -= n + TakeStack(c, id, n) if c.View.Inventory[id] == 0 { delete(c.View.Inventory, id) } diff --git a/server/internal/game/crafting.go b/server/internal/game/crafting.go new file mode 100644 index 0000000..2e866e8 --- /dev/null +++ b/server/internal/game/crafting.go @@ -0,0 +1,307 @@ +package game + +import ( + "aeternalis/server/content" + p "aeternalis/server/internal/protocol" + "encoding/json" + "errors" + "fmt" + "maps" + "math" + "slices" + "strings" +) + +func (w *World) refreshCrafting(c *Character) { + if c.View.Crafting == nil { + c.View.Crafting = map[string]p.CraftProgress{} + } + if c.View.DiscoveredRecipes == nil { + c.View.DiscoveredRecipes = map[string]p.KnownRecipe{} + } + if w.Balance.Crafting == nil { + return + } + for _, s := range w.Balance.Crafting.Professions { + v := c.View.Crafting[s.ID] + v.ID = s.ID + v.Name = s.Name + v.Level, v.XPToNextLevel = content.SkillLevel(s, v.XP) + v.LossPercent = w.Balance.Crafting.Rules.Loss(v.Level) + c.View.Crafting[s.ID] = v + } + for _, m := range w.Balance.Crafting.Materials { + if c.View.Inventory[m.ID] > 0 { + c.View.StackNames[m.ID] = m.Name + } + } +} +func (w *World) restoreCrafting(c *Character) error { + if len(c.View.Crafting) > 64 || len(c.View.DiscoveredRecipes) > 512 || math.IsNaN(c.CraftReadyAt) || math.IsInf(c.CraftReadyAt, 0) || c.CraftReadyAt < 0 { + return errors.New("invalid crafting history") + } + for _, v := range c.View.Crafting { + if v.XP < 0 || v.XP > 1000000000000 { + return errors.New("invalid crafting experience") + } + } + for id, r := range c.View.DiscoveredRecipes { + if id != r.Recipe.ID || r.Recipe.Revision < 1 || len(r.Recipe.Inputs) > 16 || len(r.Recipe.Outputs) > 8 || len(r.Recipe.Name) > 80 { + return errors.New("invalid discovered recipe") + } + } + return ValidateCraftedStacks(c.View.Inventory, c.View.CraftedStacks, map[string]bool{}) +} + +func ValidateCraftedStacks(inventory map[string]int64, batches []p.CraftedStack, seen map[string]bool) error { + if len(batches) > 2048 { + return errors.New("too many crafted batches") + } + totals := map[string]int64{} + for _, b := range batches { + if b.ID == "" || len(b.ID) > 100 || seen[b.ID] || b.Item == "" || b.Quantity < 1 || b.Quantity > 1000000000000 || !validProvenance(b.Provenance) { + return errors.New("invalid crafted provenance or batch") + } + seen[b.ID] = true + totals[b.Item] += b.Quantity + if totals[b.Item] > inventory[b.Item] { + return errors.New("crafted batches exceed inventory") + } + } + return nil +} +func finiteCraft(n float64) bool { return !math.IsNaN(n) && !math.IsInf(n, 0) && n >= 0 } +func validProvenance(v p.CraftProvenance) bool { + return len(v.CharacterID) == 32 && v.CrafterName != "" && len(v.CrafterName) <= 80 && v.WorldID != "" && len(v.WorldID) <= 128 && v.RecipeID != "" && len(v.RecipeID) <= 64 && v.RecipeRevision >= 1 && v.Profession != "" && len(v.Profession) <= 64 && v.Level >= 1 && v.Level <= 1000 && finiteCraft(v.At) +} + +// Consume unmarked units first, then crafted batches in acquisition order. +// Splits receive a new batch identity; surviving units retain their provenance. +func TakeStack(c *Character, item string, quantity int64) []p.CraftedStack { + crafted := int64(0) + for _, b := range c.View.CraftedStacks { + if b.Item == item { + crafted += b.Quantity + } + } + remaining := quantity - min(quantity, max(0, c.View.Inventory[item]-crafted)) + taken := []p.CraftedStack{} + kept := []p.CraftedStack{} + for _, b := range c.View.CraftedStacks { + if b.Item == item && remaining > 0 { + n := min(remaining, b.Quantity) + part := b + part.Quantity = n + if n < b.Quantity { + part.ID = ID() + } + taken = append(taken, part) + b.Quantity -= n + remaining -= n + } + if b.Quantity > 0 { + kept = append(kept, b) + } + } + c.View.CraftedStacks = kept + c.View.Inventory[item] -= quantity + if c.View.Inventory[item] == 0 { + delete(c.View.Inventory, item) + } + return taken +} +func (w *World) checkCraftedWorld(c *Character) error { + seen := map[string]bool{} + for _, existing := range w.Characters { + if existing.View.Entity.ID == c.View.Entity.ID { + continue + } + if e := ValidateCraftedStacks(existing.View.Inventory, existing.View.CraftedStacks, seen); e != nil { + return e + } + } + for _, corpse := range w.Corpses { + if e := ValidateCraftedStacks(corpse.Inventory, corpse.CraftedStacks, seen); e != nil { + return e + } + } + return ValidateCraftedStacks(c.View.Inventory, c.View.CraftedStacks, seen) +} +func (w *World) CraftProfessions(c *Character) []p.CraftProgress { + w.refreshCrafting(c) + out := []p.CraftProgress{} + for _, s := range w.Balance.Crafting.Professions { + out = append(out, c.View.Crafting[s.ID]) + } + return out +} + +// The browser offers quantities, never a secret recipe ID. Invalid inventory or +// requirement requests do not consume materials or advance the random stream. +func (w *World) AttemptCraft(c *Character, req p.CraftRequest) (p.CraftResult, error) { + result := p.CraftResult{ID: req.ID, Consumed: map[string]int64{}, Created: []string{}} + if c == nil || !c.Online || c.Sheltered || c.View.Entity.State != "alive" || c.View.RemainingSeconds <= 0 || (!w.IsHub() && w.Phase != "gathering" && w.Phase != "cataclysm") { + return result, errors.New("character cannot craft") + } + now := float64(w.now.UnixMilli()) / 1000 + if now < c.CraftReadyAt { + return result, errors.New("crafting cooldown") + } + if len(req.Ingredients) < 1 || len(req.Ingredients) > 16 { + return result, errors.New("offer 1-16 distinct ingredients") + } + v := w.Balance.Crafting + profession := slices.IndexFunc(v.Professions, func(s content.GatheringSkill) bool { return s.ID == req.Profession }) + if profession < 0 { + return result, errors.New("unknown crafting profession") + } + for id, n := range req.Ingredients { + if id == "" || len(id) > 64 || n < 1 || n > 1000 || c.View.Inventory[id] < n { + return result, errors.New("invalid or missing ingredients") + } + } + w.refreshCrafting(c) + progress := c.View.Crafting[req.Profession] + var recipe *content.CraftRecipe + for _, r := range v.Recipes { + if r.Profession == req.Profession && maps.Equal(r.Inputs, req.Ingredients) { + copy := r + recipe = © + break + } + } + if recipe != nil { + stats := w.statValues(c, false) + for key, n := range recipe.Stats { + if stats[key].Final < n { + return result, fmt.Errorf("valid recipe; requires %s %.0f (without equipment bonuses); no ingredients spent", key, n) + } + } + for _, id := range recipe.Titles { + if !slices.ContainsFunc(c.View.Titles, func(t p.TitleAward) bool { return t.ID == id }) { + return result, errors.New("valid recipe; required title missing; no ingredients spent") + } + } + } + // Results are constructed on a staged world; persistence failures never publish + // this random result or partially spend the live player's ingredients. + result.Valid = recipe != nil + if recipe != nil { + result.Success = !w.roll(v.Rules.Failure(progress.Level, recipe.Level)) + } + rate := v.Rules.Loss(progress.Level) + if result.Success { + rate = 100 + } + keys := slices.Sorted(maps.Keys(req.Ingredients)) + for _, id := range keys { + n := int64(math.Ceil(float64(req.Ingredients[id]) * rate / 100)) + n = min(req.Ingredients[id], max(1, n)) + TakeStack(c, id, n) + result.Consumed[id] = n + } + if recipe != nil { + var known p.CraftRecipe + raw, _ := json.Marshal(recipe) + _ = json.Unmarshal(raw, &known) + discovered := p.KnownRecipe{Recipe: known, DiscoveredAt: now} + if old, ok := c.View.DiscoveredRecipes[recipe.ID]; ok && old.Recipe.Revision == recipe.Revision { + discovered.DiscoveredAt = old.DiscoveredAt + } + c.View.DiscoveredRecipes[recipe.ID] = discovered + result.Recipe = &discovered + } + if result.Success { + provenance := p.CraftProvenance{CharacterID: c.View.Entity.ID, CrafterName: c.View.Entity.Name, WorldID: w.ID, RecipeID: recipe.ID, RecipeRevision: recipe.Revision, Profession: req.Profession, Level: progress.Level, At: now} + for _, id := range slices.Sorted(maps.Keys(recipe.Outputs)) { + n := recipe.Outputs[id] + before := len(c.View.Items) + if err := w.addInventoryItems(&c.View.Inventory, &c.View.Items, id, n); err != nil { + return result, err + } + if len(c.View.Items) > before { + var definition content.ItemDefinition + for _, d := range w.Balance.Items { + if d.ID == id { + definition = d + break + } + } + for i := before; i < len(c.View.Items); i++ { + item := &c.View.Items[i] + copy := provenance + item.Provenance = © + item.Modifiers = append(item.Modifiers, w.craftModifiers(definition, progress.Level)...) + result.Created = append(result.Created, item.ID) + } + } else { + batch := p.CraftedStack{ID: ID(), Item: id, Quantity: n, Provenance: provenance} + c.View.CraftedStacks = append(c.View.CraftedStacks, batch) + result.Created = append(result.Created, batch.ID) + } + } + if w.AllowsXP() { + progress.XP = min(int64(1000000000000), progress.XP+recipe.XP) + c.View.Crafting[req.Profession] = progress + c.View.Skills["crafting"] += w.Balance.SkillXpPerAction + w.grantXP(c, w.Balance.Progression.CraftXP) + } + result.Message = "Crafted " + recipe.Name + } else if recipe != nil { + result.Message = "Valid recipe discovered: " + recipe.Name + ". Craft failed; some ingredients were lost." + } else { + result.Message = "No recipe matches this combination. Some ingredients were lost." + } + if err := ValidateCraftedStacks(c.View.Inventory, c.View.CraftedStacks, map[string]bool{}); err != nil { + return result, err + } + c.CraftReadyAt = now + v.Rules.Cooldown + c.Message = result.Message + w.RefreshStats(c) + w.evaluateTitles(c) + w.dirty = true + return result, nil +} +func (w *World) craftModifiers(item content.ItemDefinition, level int64) []p.StatModifier { + pool := slices.Clone(item.CraftPool) + out := []p.StatModifier{} + bias := math.Min(w.Balance.Crafting.Rules.MaxQualityBias, 1+float64(level-1)*w.Balance.Crafting.Rules.QualityPerLevel) + for range item.CraftRolls { + total := float64(0) + for _, s := range pool { + total += s.Weight + } + pick := w.randomUnit() * total + index := len(pool) - 1 + for i, s := range pool { + pick -= s.Weight + if pick < 0 { + index = i + break + } + } + s := pool[index] + pool = append(pool[:index], pool[index+1:]...) + value := math.Round((s.Min+(s.Max-s.Min)*math.Pow(w.randomUnit(), 1/bias))*100) / 100 + m := p.StatModifier{Stat: s.Stat} + if s.Percent { + m.Percent = value + } else { + m.Flat = value + } + out = append(out, m) + } + return out +} + +func ValidCraftRequest(r p.CraftRequest) bool { + if len(r.ID) < 32 || len(r.ID) > 36 || len(r.CharacterID) != 32 || len(r.Profession) > 64 { + return false + } + for _, id := range []string{r.ID, r.CharacterID} { + if strings.Trim(id, "0123456789abcdef-") != "" { + return false + } + } + return true +} diff --git a/server/internal/game/crafting_test.go b/server/internal/game/crafting_test.go new file mode 100644 index 0000000..4905988 --- /dev/null +++ b/server/internal/game/crafting_test.go @@ -0,0 +1,199 @@ +package game + +import ( + p "aeternalis/server/internal/protocol" + "encoding/json" + "fmt" + "maps" + "math" + "reflect" + "testing" + "time" +) + +// Existing action regressions use the new ingredient path with a certain success +// roll. A staged copy also exercises failure rollback without a transport fixture. +func (w *World) craft(c *Character, name string) error { + staged := *w + staged.Characters = maps.Clone(w.Characters) + copy := *c + raw, _ := json.Marshal(c.View) + var view p.Character + _ = json.Unmarshal(raw, &view) + copy.View = view + staged.Characters[c.View.Entity.ID] = © + content := *w.Balance.Crafting + content.Rules.BaseFailure = 0 + content.Rules.MinFailure = 0 + content.Rules.MaxFailure = 0 + staged.Balance.Crafting = &content + for _, r := range content.Recipes { + if r.ID == "recipe_"+name { + _, e := staged.AttemptCraft(©, p.CraftRequest{ID: ID(), CharacterID: c.View.Entity.ID, Profession: r.Profession, Ingredients: r.Inputs}) + if e != nil { + return e + } + *c = copy + w.RandomCounter = staged.RandomCounter + w.PendingTitles = staged.PendingTitles + return nil + } + } + return fmt.Errorf("unknown test recipe %s", name) +} + +func TestCraftFailureDiscoveryAndHubRules(t *testing.T) { + w, c := fixture(t) + v := w.Balance.Crafting + v.Rules.BaseFailure = 100 + v.Rules.MinFailure = 100 + v.Rules.MaxFailure = 100 + c.View.Inventory["wood"] = 20 + c.View.Inventory["ore"] = 20 + req := p.CraftRequest{ID: ID(), CharacterID: c.View.Entity.ID, Profession: "weapon_smithing", Ingredients: map[string]int64{"wood": 3, "ore": 2}} + beforeXP := c.View.Experience + result, e := w.AttemptCraft(c, req) + if e != nil || !result.Valid || result.Success || result.Recipe == nil { + t.Fatal("valid failed craft was not discovered", result, e) + } + if c.View.Crafting["weapon_smithing"].XP != 0 || c.View.Experience != beforeXP || c.View.Inventory["wood"] != 17 || c.View.Inventory["ore"] != 18 { + t.Fatal("failed craft XP/loss mismatch") + } + w.now = w.now.Add(2 * time.Second) + req.Ingredients = map[string]int64{"wood": 1} + result, e = w.AttemptCraft(c, req) + if e != nil || result.Valid || result.Success || len(c.View.DiscoveredRecipes) != 1 { + t.Fatal("unknown recipe gave discovery", e) + } + w.now = w.now.Add(2 * time.Second) + w.Kind = "hub" + w.Phase = "hub" + v.Rules.BaseFailure = 0 + v.Rules.MinFailure = 0 + v.Rules.MaxFailure = 0 + req.Ingredients = map[string]int64{"wood": 3, "ore": 2} + result, e = w.AttemptCraft(c, req) + if e != nil || !result.Success { + t.Fatal(e) + } + if c.View.Experience != beforeXP || c.View.Crafting["weapon_smithing"].XP != 0 || c.View.Skills["crafting"] != 0 { + t.Fatal("hub craft gained XP") + } + var crafted *p.ItemInstance + for i := range c.View.Items { + if c.View.Items[i].DefinitionID == "spear" { + crafted = &c.View.Items[i] + } + } + fixed := 0 + for _, item := range w.Balance.Items { + if item.ID == "spear" { + fixed = len(item.Modifiers) + } + } + if crafted == nil || crafted.Provenance == nil || crafted.Provenance.CrafterName != "Traveler" || crafted.Provenance.WorldID != w.ID || len(crafted.Modifiers) != fixed+1 { + t.Fatal("crafted gear missing provenance or stat roll") + } + before := len(c.View.Items) + if _, e = w.AttemptCraft(c, req); e == nil || len(c.View.Items) != before { + t.Fatal("cooldown bypass") + } +} + +func TestCraftedStackSplitDeathLootAndReplacement(t *testing.T) { + w, c := fixture(t) + w.Balance.Crafting.Rules.BaseFailure = 0 + w.Balance.Crafting.Rules.MinFailure = 0 + w.Balance.Crafting.Rules.MaxFailure = 0 + c.View.Inventory["herb"] = 8 + for i := range w.Balance.Crafting.Recipes { + if w.Balance.Crafting.Recipes[i].ID == "recipe_bandage" { + w.Balance.Crafting.Recipes[i].Outputs["bandage"] = 3 + } + } + if e := w.craft(c, "bandage"); e != nil { + t.Fatal(e) + } + before := c.View.CraftedStacks[0].Provenance + batchID := c.View.CraftedStacks[0].ID + if e := w.dropItem(c, "bandage"); e != nil { + t.Fatal(e) + } + var drop *Corpse + for _, v := range w.Corpses { + drop = v + } + if drop == nil || drop.CraftedStacks[0].ID == batchID || drop.CraftedStacks[0].Quantity != 1 || c.View.CraftedStacks[0].Quantity != 2 || !reflect.DeepEqual(drop.CraftedStacks[0].Provenance, before) { + t.Fatal("partial drop lost/duplicated provenance") + } + other, _ := w.Join("other", "Other") + other.View.Entity.Position = c.View.Entity.Position + if e := w.lootCorpse(other, drop.Entity.ID); e != nil { + t.Fatal(e) + } + if !reflect.DeepEqual(other.View.CraftedStacks[0].Provenance, before) { + t.Fatal("pickup changed crafter") + } + w.kill(c, "test") + corpse := w.Corpses["corpse:"+c.View.Entity.ID] + if len(c.View.CraftedStacks) != 0 || len(corpse.CraftedStacks) != 1 { + t.Fatal("death duplicated crafted stock") + } + if e := w.lootCorpse(other, corpse.Entity.ID); e != nil { + t.Fatal(e) + } + TakeStack(other, "bandage", 2) + if other.View.Inventory["bandage"] != 1 || len(other.View.CraftedStacks) != 1 || other.View.CraftedStacks[0].Quantity != 1 { + t.Fatal("consumption left invalid provenance") + } + 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) + } + replacement, e := restored.Join(c.Account, "Replacement") + if e != nil { + t.Fatal(e) + } + if len(replacement.View.DiscoveredRecipes) != 0 || replacement.View.Crafting["alchemist"].XP != 0 { + t.Fatal("replacement inherited crafting progression") + } +} + +func TestCraftRequirementsAndQuality(t *testing.T) { + w, c := fixture(t) + c.View.Inventory["wood"] = 3 + c.View.Inventory["ore"] = 2 + for i := range w.Balance.Crafting.Recipes { + if w.Balance.Crafting.Recipes[i].ID == "recipe_spear" { + w.Balance.Crafting.Recipes[i].Stats = map[string]float64{"strength": 10000} + } + } + counter := w.RandomCounter + _, e := w.AttemptCraft(c, p.CraftRequest{ID: ID(), CharacterID: c.View.Entity.ID, Profession: "weapon_smithing", Ingredients: map[string]int64{"wood": 3, "ore": 2}}) + if e == nil || w.RandomCounter != counter || c.View.Inventory["wood"] != 3 || len(c.View.DiscoveredRecipes) != 0 { + t.Fatal("unmet requirements consumed materials or rolled") + } + item := w.Balance.Items[1] + sumLow, sumHigh := float64(0), float64(0) + for range 200 { + start := w.RandomCounter + low := w.craftModifiers(item, 1) + w.RandomCounter = start + high := w.craftModifiers(item, 100) + if len(low) != 1 || len(high) != 1 || low[0].Stat != high[0].Stat { + t.Fatal("pool selection not preserved") + } + if high[0].Flat < low[0].Flat || math.IsNaN(high[0].Flat) { + t.Fatal("higher proficiency worsened corresponding roll") + } + sumLow += low[0].Flat + sumHigh += high[0].Flat + } + if sumHigh <= sumLow { + t.Fatal("quality distribution did not improve") + } +} diff --git a/server/internal/game/equipment.go b/server/internal/game/equipment.go index a0cd4e1..183c7cd 100644 --- a/server/internal/game/equipment.go +++ b/server/internal/game/equipment.go @@ -126,6 +126,9 @@ func (w *World) migrateEquipment(inventory *map[string]int64, items *[]p.ItemIns } func validateOwnedItems(items []p.ItemInstance, seen map[string]bool) error { for _, item := range items { + if item.Provenance != nil && !validProvenance(*item.Provenance) { + return errors.New("invalid equipment provenance") + } if item.ID == "" || len(item.ID) > 100 || seen[item.ID] || item.DefinitionID == "" || item.Name == "" || (item.Slot != "ring" && !validEquipmentSlot(item.Slot)) || math.IsNaN(item.Weight) || math.IsInf(item.Weight, 0) || item.Weight < 0 || item.Requirements.Level < 1 { return errors.New("invalid or duplicate persisted equipment") } @@ -167,6 +170,17 @@ func (w *World) restoreEquipment(c *Character) error { return nil } func (w *World) restoreCorpseEquipment() error { + batches := map[string]bool{} + for _, c := range w.Characters { + if e := ValidateCraftedStacks(c.View.Inventory, c.View.CraftedStacks, batches); e != nil { + return e + } + } + for _, c := range w.Corpses { + if e := ValidateCraftedStacks(c.Inventory, c.CraftedStacks, batches); e != nil { + return e + } + } seen := map[string]bool{} for _, c := range w.Characters { if err := validateOwnedItems(c.View.Items, seen); err != nil { @@ -294,7 +308,7 @@ func (w *World) dropItem(c *Character, target string) error { if c.View.Inventory[target] < 1 { return errors.New("item not owned") } - c.View.Inventory[target]-- + dropped.CraftedStacks = TakeStack(c, target, 1) if c.View.Inventory[target] == 0 { delete(c.View.Inventory, target) } @@ -318,11 +332,22 @@ func (w *World) lootCorpse(c *Character, target string) error { if err := validateOwnedItems(corpse.Items, seen); err != nil { return err } + batches := map[string]bool{} + if e := ValidateCraftedStacks(c.View.Inventory, c.View.CraftedStacks, batches); e != nil { + return e + } + if e := ValidateCraftedStacks(corpse.Inventory, corpse.CraftedStacks, batches); e != nil { + return e + } for name, quantity := range corpse.Inventory { if quantity < 0 || c.View.Inventory[name] > math.MaxInt64-quantity { return errors.New("invalid loot quantity") } } + if len(c.View.CraftedStacks)+len(corpse.CraftedStacks) > 2048 { + return errors.New("crafted batch capacity reached") + } + c.View.CraftedStacks = append(c.View.CraftedStacks, corpse.CraftedStacks...) for name, quantity := range corpse.Inventory { c.View.Inventory[name] += quantity } @@ -333,6 +358,9 @@ func (w *World) lootCorpse(c *Character, target string) error { return nil } func (w *World) checkImportedEquipment(c *Character) error { + if e := w.checkCraftedWorld(c); e != nil { + return e + } seen := map[string]bool{} for _, existing := range w.Characters { if err := validateOwnedItems(existing.View.Items, seen); err != nil { diff --git a/server/internal/game/equipment_test.go b/server/internal/game/equipment_test.go index 32d57af..85c5fb4 100644 --- a/server/internal/game/equipment_test.go +++ b/server/internal/game/equipment_test.go @@ -166,7 +166,7 @@ func TestLegacyEquipmentMigrationAndAtomicFailures(t *testing.T) { delete(w.Corpses, "legacy") c.View.Inventory["wood"] = 3 c.View.Inventory["ore"] = 2 - w.Balance.Recipes["spear"] = content.Recipe{Inputs: map[string]int64{"wood": 3, "ore": 2}, Outputs: map[string]int64{"spear": 100001}} + w.Balance.Crafting.Recipes[0].Outputs = map[string]int64{"spear": 100001} if w.craft(c, "spear") == nil || c.View.Inventory["wood"] != 3 || c.View.Inventory["ore"] != 2 { t.Fatal("failed craft consumed materials") } diff --git a/server/internal/game/gathering.go b/server/internal/game/gathering.go index 07fa078..098fa6c 100644 --- a/server/internal/game/gathering.go +++ b/server/internal/game/gathering.go @@ -260,7 +260,7 @@ func (w *World) consumeGathering(c *Character, id string) error { if len(c.View.GatheringEffects) >= 64 && !slices.ContainsFunc(c.View.GatheringEffects, func(e p.TimedGatheringEffect) bool { return e.Source == id }) { return errors.New("too many active gathering effects") } - c.View.Inventory[id]-- + TakeStack(c, id, 1) w.applyGatheringEffect(c, p.TimedGatheringEffect{Source: id, Name: v.Name, ExpiresAt: float64(w.now.UnixMilli())/1000 + v.Seconds, Modifiers: protocolModifiers(v.Modifiers)}) w.RefreshStats(c) c.Message = "Used " + v.Name diff --git a/server/internal/game/progression_test.go b/server/internal/game/progression_test.go index 6da50a6..f94be2a 100644 --- a/server/internal/game/progression_test.go +++ b/server/internal/game/progression_test.go @@ -62,7 +62,7 @@ func TestOnlySuccessfulActionsGrantXP(t *testing.T) { t.Fatal("failed gather gained XP") } c.View.Inventory["herb"] = 2 - if err := w.Intent(id, p.Intent{Op: "craft", Seq: 11, Target: "bandage"}); err != nil { + if err := w.craft(c, "bandage"); err != nil { t.Fatal(err) } before := c.View.Experience diff --git a/server/internal/game/stats.go b/server/internal/game/stats.go index e5d4c93..9fc1eea 100644 --- a/server/internal/game/stats.go +++ b/server/internal/game/stats.go @@ -89,6 +89,7 @@ func (w *World) RefreshStats(c *Character) { w.revalidateEquipment(c) c.View.Stats = w.statValues(c, true) w.refreshGathering(c) + w.refreshCrafting(c) attack := w.playerAttack(c) c.View.Attack = &attack c.View.Entity.MaxHP = c.View.Stats["healthPoints"].Final @@ -171,6 +172,9 @@ func (w *World) ApplyCatalog(catalog content.Catalog) error { if catalog.Combat != nil { w.Balance.Combat = catalog.Combat } + if catalog.Crafting != nil { + w.Balance.Crafting = catalog.Crafting + } w.Balance.Titles = catalog.Titles w.Balance.Items = catalog.Items w.Balance.Stats = &catalog.Stats @@ -188,9 +192,12 @@ func (w *World) roll(chance float64) bool { if chance >= 100 { return true } + return w.randomUnit()*100 < chance +} +func (w *World) randomUnit() float64 { w.RandomCounter++ sum := sha256.Sum256([]byte(fmt.Sprintf("%d:%d", w.Seed, w.RandomCounter))) - return float64(binary.LittleEndian.Uint64(sum[:8])>>11)/float64(uint64(1)<<53)*100 < chance + return float64(binary.LittleEndian.Uint64(sum[:8])>>11) / float64(uint64(1)<<53) } func (w *World) yieldAmount(rate float64) int64 { amount := math.Max(0, math.Min(float64(w.Balance.MaxYieldPerAction), rate/100)) diff --git a/server/internal/game/world.go b/server/internal/game/world.go index de931da..a6bb85a 100644 --- a/server/internal/game/world.go +++ b/server/internal/game/world.go @@ -5,7 +5,6 @@ import ( "encoding/hex" "errors" "fmt" - "maps" "math" "sort" "time" @@ -15,6 +14,7 @@ import ( ) type Character struct { + CraftReadyAt float64 `json:"craftReadyAt"` AttackReadyAt float64 `json:"attackReadyAt"` JumpVelocity float64 `json:"jumpVelocity"` GatherReadyAt float64 `json:"gatherReadyAt"` @@ -42,9 +42,10 @@ type Character struct { StatsVersion int `json:"statsVersion"` } type Corpse struct { - Entity p.Entity `json:"entity"` - Inventory map[string]int64 `json:"inventory"` - Items []p.ItemInstance `json:"items"` + CraftedStacks []p.CraftedStack `json:"craftedStacks,omitempty"` + Entity p.Entity `json:"entity"` + Inventory map[string]int64 `json:"inventory"` + Items []p.ItemInstance `json:"items"` } type Mob struct { Definition *content.MobDefinition `json:"definition,omitempty"` @@ -186,6 +187,16 @@ func (w *World) Restore(now time.Time) error { if w.ResourceLayouts == nil { w.ResourceLayouts = map[string]ResourceLayout{} } + if w.Balance.Crafting == nil { + b, e := content.Load() + if e != nil { + return e + } + cat := content.Catalog{Items: w.Balance.Items} + cat.RestoreCrafting(b) + w.Balance.Crafting = cat.Crafting + w.Balance.Items = cat.Items + } if w.Balance.Combat == nil || w.Balance.CombatRules == nil { b, e := content.Load() if e != nil { @@ -217,6 +228,9 @@ func (w *World) Restore(now time.Time) error { if err := w.restoreEquipment(c); err != nil { return err } + if err := w.restoreCrafting(c); err != nil { + return err + } if err := w.restoreGathering(c); err != nil { return err } @@ -328,6 +342,9 @@ func (w *World) Join(account, name string) (*Character, error) { if err := w.restoreEquipment(c); err != nil { return nil, err } + if err := w.restoreCrafting(c); err != nil { + return nil, err + } if err := w.restoreGathering(c); err != nil { return nil, err } @@ -356,6 +373,9 @@ func (w *World) Import(c *Character) error { if err := w.checkImportedEquipment(c); err != nil { return err } + if err := w.restoreCrafting(c); err != nil { + return err + } if err := w.restoreGathering(c); err != nil { return err } @@ -501,14 +521,14 @@ func (w *World) Intent(id string, i p.Intent) error { case "gather": return w.gather(c, i.Target) case "craft": - return w.craft(c, i.Target) + return errors.New("use the crafting workbench to offer ingredients") case "attack": return w.attack(c, i.Target) case "heal": if c.View.Inventory["bandage"] < 1 || c.View.Entity.HP >= c.View.Entity.MaxHP { return errors.New("no bandage needed or available") } - c.View.Inventory["bandage"]-- + TakeStack(c, "bandage", 1) w.RefreshStats(c) c.View.Entity.HP = math.Min(c.View.Entity.MaxHP, c.View.Entity.HP+w.Balance.BandageHealing) w.dirty = true @@ -531,37 +551,6 @@ func (w *World) Intent(id string, i p.Intent) error { } return nil } -func (w *World) craft(c *Character, name string) error { - r, ok := w.Balance.Recipes[name] - if !ok { - return errors.New("unknown recipe") - } - for k, v := range r.Inputs { - if c.View.Inventory[k] < v { - return errors.New("missing crafting materials") - } - } - inventory := maps.Clone(c.View.Inventory) - items := append([]p.ItemInstance{}, c.View.Items...) - for k, v := range r.Inputs { - inventory[k] -= v - } - for k, v := range r.Outputs { - if err := w.addInventoryItems(&inventory, &items, k, v); err != nil { - return err - } - } - c.View.Inventory, c.View.Items = inventory, items - w.RefreshStats(c) - if w.AllowsXP() { - c.View.Skills["crafting"] += w.Balance.SkillXpPerAction - } - c.Message = "Crafted " + name - w.grantXP(c, w.Balance.Progression.CraftXP) - w.evaluateTitles(c) - w.dirty = true - return nil -} func (w *World) damageBoss(c *Character, damage float64) { w.BossHP = math.Max(0, w.BossHP-damage) if w.BossHP == 0 { @@ -595,7 +584,8 @@ func (w *World) kill(c *Character, reason string) { e.Kind = "corpse" e.State = "dead" e.HP = 0 - w.Corpses[e.ID] = &Corpse{Entity: e, Inventory: c.View.Inventory, Items: c.View.Items} + w.Corpses[e.ID] = &Corpse{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{} c.View.Equipment = map[string]string{} diff --git a/server/internal/game/world_test.go b/server/internal/game/world_test.go index 030b98e..702abb8 100644 --- a/server/internal/game/world_test.go +++ b/server/internal/game/world_test.go @@ -119,7 +119,7 @@ func TestGatherCraftAndPermanentDeath(t *testing.T) { } c.View.Inventory["wood"] = 3 c.View.Inventory["ore"] = 2 - if err := w.Intent(id, p.Intent{Op: "craft", Seq: 5, Target: "spear"}); err != nil { + if err := w.craft(c, "spear"); err != nil { t.Fatal(err) } if gearCount(c.View.Items, "spear") != 1 || c.View.Inventory["wood"] != 0 || c.View.Inventory["ore"] != 0 { diff --git a/server/internal/protocol/generated.go b/server/internal/protocol/generated.go index 3dc6cad..e49a95a 100644 --- a/server/internal/protocol/generated.go +++ b/server/internal/protocol/generated.go @@ -6,12 +6,15 @@ type Protocol struct { CatalogChange *ContentChange `json:"catalogChange,omitempty"` CatalogPreview *ContentPreview `json:"catalogPreview,omitempty"` CatalogResult *ContentResult `json:"catalogResult,omitempty"` + CraftRequest *CraftRequest `json:"craftRequest,omitempty"` + CraftResult *CraftResult `json:"craftResult,omitempty"` Intent Intent `json:"intent"` Snapshot Snapshot `json:"snapshot"` } type ContentCatalog struct { Combat *CombatContent `json:"combat,omitempty"` + Crafting *CraftingContent `json:"crafting,omitempty"` EffectSets []EffectSet `json:"effectSets,omitempty"` Gathering *GatheringContent `json:"gathering,omitempty"` Items []ItemDefinition `json:"items"` @@ -95,6 +98,56 @@ type MobSpawn struct { Z float64 `json:"z"` } +type CraftingContent struct { + Materials []CraftMaterial `json:"materials"` + Professions []GatheringSkill `json:"professions"` + Recipes []CraftRecipe `json:"recipes"` + Rules CraftRules `json:"rules"` +} + +type CraftMaterial struct { + Description string `json:"description"` + ID string `json:"id"` + Name string `json:"name"` +} + +type GatheringSkill struct { + BaseXP int64 `json:"baseXp"` + Description string `json:"description"` + ID string `json:"id"` + MaxLevel int64 `json:"maxLevel"` + Name string `json:"name"` + XPPerLevel int64 `json:"xpPerLevel"` +} + +type CraftRecipe struct { + Description string `json:"description"` + ID string `json:"id"` + Inputs map[string]int64 `json:"inputs"` + Level int64 `json:"level"` + Name string `json:"name"` + Outputs map[string]int64 `json:"outputs"` + Profession string `json:"profession"` + Revision int64 `json:"revision"` + Stats map[string]float64 `json:"stats"` + Titles []string `json:"titles"` + XP int64 `json:"xp"` +} + +type CraftRules struct { + BaseFailure float64 `json:"baseFailure"` + BaseLoss float64 `json:"baseLoss"` + Cooldown float64 `json:"cooldown"` + LossDecay float64 `json:"lossDecay"` + MaxFailure float64 `json:"maxFailure"` + MaxQualityBias float64 `json:"maxQualityBias"` + MinFailure float64 `json:"minFailure"` + MinLoss float64 `json:"minLoss"` + OverLevelDecay float64 `json:"overLevelDecay"` + QualityPerLevel float64 `json:"qualityPerLevel"` + UnderLevelGrowth float64 `json:"underLevelGrowth"` +} + type EffectSet struct { Description string `json:"description"` ID string `json:"id"` @@ -151,17 +204,10 @@ type ResourceDefinition struct { XP int64 `json:"xp"` } -type GatheringSkill struct { - BaseXP int64 `json:"baseXp"` - Description string `json:"description"` - ID string `json:"id"` - MaxLevel int64 `json:"maxLevel"` - Name string `json:"name"` - XPPerLevel int64 `json:"xpPerLevel"` -} - type ItemDefinition struct { AttackID *string `json:"attackId,omitempty"` + CraftPool []CraftStat `json:"craftPool,omitempty"` + CraftRolls *int64 `json:"craftRolls,omitempty"` Description string `json:"description"` DropChance float64 `json:"dropChance"` ID string `json:"id"` @@ -172,6 +218,14 @@ type ItemDefinition struct { Weight float64 `json:"weight"` } +type CraftStat struct { + Max float64 `json:"max"` + Min float64 `json:"min"` + Percent bool `json:"percent"` + Stat string `json:"stat"` + Weight float64 `json:"weight"` +} + type ItemRequirements struct { Level int64 `json:"level"` Stats map[string]float64 `json:"stats"` @@ -215,6 +269,10 @@ type ContentChange struct { Attack *CombatAttackDraft `json:"attack,omitempty"` Biome *BiomeDefinitionDraft `json:"biome,omitempty"` Consumable *GatheringConsumableDraft `json:"consumable,omitempty"` + CraftMaterial *CraftMaterialDraft `json:"craftMaterial,omitempty"` + CraftProfession *GatheringSkillDraft `json:"craftProfession,omitempty"` + CraftRecipe *CraftRecipeDraft `json:"craftRecipe,omitempty"` + CraftRules *CraftRules `json:"craftRules,omitempty"` EffectSet *EffectSetDraft `json:"effectSet,omitempty"` EffectSetIDS []string `json:"effectSetIds,omitempty"` ExpectedVersion int64 `json:"expectedVersion"` @@ -271,11 +329,10 @@ type GatheringConsumableDraft struct { Seconds float64 `json:"seconds"` } -type EffectSetDraft struct { - Description string `json:"description"` - ID *string `json:"id,omitempty"` - Modifiers []StatModifier `json:"modifiers"` - Name string `json:"name"` +type CraftMaterialDraft struct { + Description string `json:"description"` + ID *string `json:"id,omitempty"` + Name string `json:"name"` } type GatheringSkillDraft struct { @@ -287,8 +344,31 @@ type GatheringSkillDraft struct { XPPerLevel int64 `json:"xpPerLevel"` } +type CraftRecipeDraft struct { + Description string `json:"description"` + ID *string `json:"id,omitempty"` + Inputs map[string]int64 `json:"inputs"` + Level int64 `json:"level"` + Name string `json:"name"` + Outputs map[string]int64 `json:"outputs"` + Profession string `json:"profession"` + Revision *int64 `json:"revision,omitempty"` + Stats map[string]float64 `json:"stats"` + Titles []string `json:"titles"` + XP int64 `json:"xp"` +} + +type EffectSetDraft struct { + Description string `json:"description"` + ID *string `json:"id,omitempty"` + Modifiers []StatModifier `json:"modifiers"` + Name string `json:"name"` +} + type ItemDraft struct { AttackID *string `json:"attackId,omitempty"` + CraftPool []CraftStat `json:"craftPool,omitempty"` + CraftRolls *int64 `json:"craftRolls,omitempty"` Description string `json:"description"` DropChance float64 `json:"dropChance"` ID *string `json:"id,omitempty"` @@ -382,6 +462,28 @@ type ContentResult struct { Version int64 `json:"version"` } +type CraftRequest struct { + CharacterID string `json:"characterId"` + ID string `json:"id"` + Ingredients map[string]int64 `json:"ingredients"` + Profession string `json:"profession"` +} + +type CraftResult struct { + Consumed map[string]int64 `json:"consumed"` + Created []string `json:"created"` + ID string `json:"id"` + Message string `json:"message"` + Recipe *KnownRecipe `json:"recipe,omitempty"` + Success bool `json:"success"` + Valid bool `json:"valid"` +} + +type KnownRecipe struct { + DiscoveredAt float64 `json:"discoveredAt"` + Recipe CraftRecipe `json:"recipe"` +} + type Intent struct { Op string `json:"op"` Seq int64 `json:"seq"` @@ -465,6 +567,9 @@ type Character struct { 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"` @@ -491,6 +596,33 @@ type Character struct { Titles []TitleAward `json:"titles"` } +type CraftedStack struct { + ID string `json:"id"` + Item string `json:"item"` + Provenance CraftProvenance `json:"provenance"` + Quantity int64 `json:"quantity"` +} + +type CraftProvenance struct { + At float64 `json:"at"` + CharacterID string `json:"characterId"` + CrafterName string `json:"crafterName"` + Level int64 `json:"level"` + Profession string `json:"profession"` + RecipeID string `json:"recipeId"` + RecipeRevision int64 `json:"recipeRevision"` + WorldID string `json:"worldId"` +} + +type CraftProgress struct { + ID string `json:"id"` + Level int64 `json:"level"` + LossPercent float64 `json:"lossPercent"` + Name string `json:"name"` + XP int64 `json:"xp"` + XPToNextLevel int64 `json:"xpToNextLevel"` +} + type SkillProgress struct { EffectiveLevel int64 `json:"effectiveLevel"` Experience StatValue `json:"experience"` @@ -525,6 +657,7 @@ type ItemInstance struct { ID string `json:"id"` Modifiers []StatModifier `json:"modifiers"` Name string `json:"name"` + Provenance *CraftProvenance `json:"provenance,omitempty"` RequirementMessage string `json:"requirementMessage"` Requirements ItemRequirements `json:"requirements"` Slot string `json:"slot"` diff --git a/server/internal/store/catalog.go b/server/internal/store/catalog.go index 14489dd..8a28e90 100644 --- a/server/internal/store/catalog.go +++ b/server/internal/store/catalog.go @@ -17,15 +17,19 @@ var ErrCatalogInvalid = errors.New("invalid catalog change") var catalogRequestID = regexp.MustCompile(`^[a-f0-9-]{32,36}$`) type CatalogChange struct { - TargetID string `json:"targetId,omitempty"` - Attack *content.CombatAttack `json:"attack,omitempty"` - Mob *content.MobDefinition `json:"mob,omitempty"` - Loot *content.LootTable `json:"loot,omitempty"` - Spawn *content.MobSpawn `json:"spawn,omitempty"` - GatheringSkill *content.GatheringSkill `json:"gatheringSkill,omitempty"` - Resource *content.ResourceDefinition `json:"resource,omitempty"` - Biome *content.BiomeDefinition `json:"biome,omitempty"` - Consumable *content.GatheringConsumable `json:"consumable,omitempty"` + CraftRecipe *content.CraftRecipe `json:"craftRecipe,omitempty"` + CraftProfession *content.GatheringSkill `json:"craftProfession,omitempty"` + CraftMaterial *content.CraftMaterial `json:"craftMaterial,omitempty"` + CraftRules *content.CraftRules `json:"craftRules,omitempty"` + TargetID string `json:"targetId,omitempty"` + Attack *content.CombatAttack `json:"attack,omitempty"` + Mob *content.MobDefinition `json:"mob,omitempty"` + Loot *content.LootTable `json:"loot,omitempty"` + Spawn *content.MobSpawn `json:"spawn,omitempty"` + GatheringSkill *content.GatheringSkill `json:"gatheringSkill,omitempty"` + Resource *content.ResourceDefinition `json:"resource,omitempty"` + Biome *content.BiomeDefinition `json:"biome,omitempty"` + Consumable *content.GatheringConsumable `json:"consumable,omitempty"` ID string `json:"id"` ExpectedVersion int64 `json:"expectedVersion"` @@ -47,7 +51,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.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.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 { @@ -118,6 +122,13 @@ func decodeCatalog(version int64, raw string) (content.Catalog, error) { } catalog.Combat = b.Combat } + if catalog.Crafting == nil { + defaults, e := content.Load() + if e != nil { + return catalog, e + } + catalog.RestoreCrafting(defaults) + } return catalog, catalog.Validate() } func (d *DB) Catalog(ctx context.Context) (content.Catalog, error) { @@ -142,10 +153,10 @@ func (d *DB) CatalogAfter(ctx context.Context, after int64) (*content.Catalog, e return &catalog, err } func (c CatalogChange) validate() error { - if (c.Op == "update-biome") != (c.TargetID != "") { - return fmt.Errorf("%w: only biome edits require an existing target", ErrCatalogInvalid) + if (c.Op == "update-biome" || c.Op == "update-craft-recipe") != (c.TargetID != "") { + return fmt.Errorf("%w: only biome and recipe edits require an existing target", ErrCatalogInvalid) } - if c.Biome != nil && c.Biome.Revision != 0 { + if (c.Biome != nil && c.Biome.Revision != 0) || (c.CraftRecipe != nil && c.CraftRecipe.Revision != 0) { return fmt.Errorf("%w: revisions are assigned by the server", ErrCatalogInvalid) } if !catalogRequestID.MatchString(c.ID) || c.ExpectedVersion < 1 || len(c.Reason) < 5 || len(c.Reason) > 240 { @@ -153,12 +164,20 @@ func (c CatalogChange) validate() error { } valid := false count := 0 - for _, present := range []bool{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.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-craft-recipe", "update-craft-recipe": + valid = c.CraftRecipe != nil + case "create-craft-profession": + valid = c.CraftProfession != nil + case "create-craft-material": + valid = c.CraftMaterial != nil + case "update-craft-rules": + valid = c.CraftRules != nil case "create-attack": valid = c.Attack != nil case "create-mob": diff --git a/server/internal/store/catalog_preview.go b/server/internal/store/catalog_preview.go index c07d1e7..dbf7bf3 100644 --- a/server/internal/store/catalog_preview.go +++ b/server/internal/store/catalog_preview.go @@ -35,6 +35,15 @@ 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.CraftRecipe != nil && change.Op != "update-craft-recipe" { + resolved.CraftRecipe.ID = "" + } + if resolved.CraftProfession != nil { + resolved.CraftProfession.ID = "" + } + if resolved.CraftMaterial != nil { + resolved.CraftMaterial.ID = "" + } if resolved.Attack != nil { resolved.Attack.ID = "" } @@ -106,7 +115,55 @@ func buildCatalog(c content.Catalog, change CatalogChange) (content.Catalog, str } combat := *c.Combat c.Combat = &combat + if c.Crafting == nil { + b, e := content.Load() + if e != nil { + return invalid(e) + } + c.RestoreCrafting(b) + } + crafting := *c.Crafting + c.Crafting = &crafting switch change.Op { + case "create-craft-recipe", "update-craft-recipe": + v := *change.CraftRecipe + v.Revision = 1 + if change.Op == "update-craft-recipe" { + i := slices.IndexFunc(c.Crafting.Recipes, func(r content.CraftRecipe) bool { return r.ID == change.TargetID }) + if i < 0 { + return invalid(fmt.Errorf("recipe not found")) + } + v.ID = c.Crafting.Recipes[i].ID + v.Revision = c.Crafting.Recipes[i].Revision + 1 + c.Crafting.Recipes = slices.Clone(c.Crafting.Recipes) + c.Crafting.Recipes[i] = v + } else { + if v.ID == "" { + v.ID = "recipe_" + game.ID() + } + c.Crafting.Recipes = append(slices.Clone(c.Crafting.Recipes), v) + } + resolved.CraftRecipe = &v + target = v.ID + case "create-craft-profession": + v := *change.CraftProfession + if v.ID == "" { + v.ID = "profession_" + game.ID() + } + c.Crafting.Professions = append(slices.Clone(c.Crafting.Professions), v) + resolved.CraftProfession = &v + target = v.ID + case "create-craft-material": + v := *change.CraftMaterial + if v.ID == "" { + v.ID = "material_" + game.ID() + } + c.Crafting.Materials = append(slices.Clone(c.Crafting.Materials), v) + resolved.CraftMaterial = &v + target = v.ID + case "update-craft-rules": + c.Crafting.Rules = *change.CraftRules + target = "crafting-rules" case "create-attack": v := *change.Attack if v.ID == "" { diff --git a/server/internal/store/crafting.go b/server/internal/store/crafting.go new file mode 100644 index 0000000..19ce046 --- /dev/null +++ b/server/internal/store/crafting.go @@ -0,0 +1,87 @@ +package store + +import ( + "aeternalis/server/internal/game" + p "aeternalis/server/internal/protocol" + "context" + "database/sql" + "encoding/json" + "errors" + "fmt" +) + +var ErrCraft = errors.New("craft rejected") + +type craftReceipt struct{ ID, Account, CharacterID, Request, Result string } + +func (d *DB) CraftReceipt(ctx context.Context, account string, req p.CraftRequest) (*p.CraftResult, error) { + var request, result string + e := d.sql.QueryRowContext(ctx, d.q(`SELECT request_json,result_json FROM craft_receipts WHERE account_id=? AND id=?`), account, req.ID).Scan(&request, &result) + if errors.Is(e, sql.ErrNoRows) { + return nil, nil + } + if e != nil { + return nil, e + } + raw, _ := json.Marshal(req) + if string(raw) != request { + return nil, fmt.Errorf("%w: attempt ID already used with different ingredients", ErrCraft) + } + var out p.CraftResult + e = json.Unmarshal([]byte(result), &out) + return &out, e +} + +// Called under the world service mutex. Consumption, rolls, discovery, XP and +// the replay receipt share the same fenced snapshot transaction. +func (l *Lease) Craft(ctx context.Context, live *game.World, account string, req p.CraftRequest) (p.CraftResult, error) { + fail := func(msg string) (p.CraftResult, error) { return p.CraftResult{}, fmt.Errorf("%w: %s", ErrCraft, msg) } + if !game.ValidCraftRequest(req) { + return fail("invalid crafting request") + } + if old, e := l.DB.CraftReceipt(ctx, account, req); e != nil { + return p.CraftResult{}, e + } else if old != nil { + return *old, nil + } + active, e := l.DB.ActiveCharacter(ctx, account) + if e != nil { + return p.CraftResult{}, e + } + if active == nil || active.ID != req.CharacterID || active.WorldID != live.ID || active.State != "alive" { + return fail("character is not active in this world") + } + original := live.Characters[req.CharacterID] + if original == nil || original.Account != account { + return fail("character unavailable") + } + staged := stageTitleWorld(live) + // Deep-copy only the acting view; leave all other players' live inputs intact. + raw, e := json.Marshal(original.View) + if e != nil { + return p.CraftResult{}, e + } + var view p.Character + if e = json.Unmarshal(raw, &view); e != nil { + return p.CraftResult{}, e + } + staged.Characters[req.CharacterID].View = view + result, e := staged.AttemptCraft(staged.Characters[req.CharacterID], req) + if e != nil { + return fail(e.Error()) + } + 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 { + return p.CraftResult{}, e + } + // Retain character pointers captured by existing WebSocket handlers. + for id, c := range staged.Characters { + *live.Characters[id] = *c + } + live.RandomCounter = staged.RandomCounter + live.PendingTitles = nil + live.Saved() + return result, nil +} diff --git a/server/internal/store/crafting_test.go b/server/internal/store/crafting_test.go new file mode 100644 index 0000000..4ff9b49 --- /dev/null +++ b/server/internal/store/crafting_test.go @@ -0,0 +1,218 @@ +package store + +import ( + "aeternalis/server/content" + "aeternalis/server/internal/game" + p "aeternalis/server/internal/protocol" + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "reflect" + "testing" + "time" +) + +func TestCraftDurability(t *testing.T) { + testCraftDurability(t, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "craft.db"))) +} +func TestPostgresCraftDurability(t *testing.T) { + dsn := os.Getenv("TEST_DATABASE_URL") + if dsn == "" { + t.Skip("TEST_DATABASE_URL not configured") + } + testCraftDurability(t, dsn) +} +func testCraftDurability(t *testing.T, dsn string) { + ctx := context.Background() + db, e := Open(ctx, dsn) + if e != nil { + t.Fatal(e) + } + defer db.Close() + b, e := content.Load() + if e != nil { + t.Fatal(e) + } + b.Crafting.Rules.BaseFailure = 0 + b.Crafting.Rules.MinFailure = 0 + b.Crafting.Rules.MaxFailure = 0 + now := time.Now().UTC() + w := game.New("craft-"+game.ID(), 1, now, b) + l, _, e := db.Acquire(ctx, w) + if e != nil { + t.Fatal(e) + } + c, e := w.Join("crafter-"+game.ID(), "Maker") + if e != nil { + t.Fatal(e) + } + if e = w.Connect(c.View.Entity.ID); e != nil { + t.Fatal(e) + } + c.View.Inventory["wood"] = 20 + c.View.Inventory["ore"] = 20 + c.View.Inventory["escape_stone"] = 1 + if e = l.Save(ctx, w, ""); e != nil { + t.Fatal(e) + } + req := p.CraftRequest{ID: game.ID(), CharacterID: c.View.Entity.ID, Profession: "weapon_smithing", Ingredients: map[string]int64{"wood": 3, "ore": 2}} + before, _ := json.Marshal(c) + random := w.RandomCounter + for _, state := range []string{"offline", "sheltered", "dead", "capped"} { + switch state { + case "offline": + c.Online = false + case "sheltered": + c.Sheltered = true + case "dead": + c.View.Entity.State = "dead" + case "capped": + c.View.RemainingSeconds = 0 + } + if _, e = l.Craft(ctx, w, c.Account, req); !errors.Is(e, ErrCraft) { + t.Fatalf("accepted %s: %v", state, e) + } + var restored game.Character + if e = json.Unmarshal(before, &restored); e != nil { + t.Fatal(e) + } + *c = restored + c.Online = true + } + stale := *l + stale.Revision-- + if _, e = stale.Craft(ctx, w, c.Account, req); !errors.Is(e, ErrOwnership) { + t.Fatal("stale craft was not fenced", e) + } + after, _ := json.Marshal(c) + if string(after) != string(before) || w.RandomCounter != random { + t.Fatal("failed save changed live crafting state") + } + if receipt, e := db.CraftReceipt(ctx, c.Account, req); e != nil || receipt != nil { + t.Fatal("failed save left receipt", e) + } + result, e := l.Craft(ctx, w, c.Account, req) + if e != nil || !result.Success { + t.Fatal(result, e) + } + if w.Characters[c.View.Entity.ID] != c || c.View.Inventory["wood"] != 17 || c.View.Crafting["weapon_smithing"].XP != 20 { + t.Fatal("craft did not publish onto live character") + } + committed, _ := json.Marshal(c) + random = w.RandomCounter + replay, e := l.Craft(ctx, w, c.Account, req) + if e != nil || !reflect.DeepEqual(result, replay) { + t.Fatal("retry changed result", e) + } + after, _ = json.Marshal(c) + if string(after) != string(committed) || w.RandomCounter != random { + t.Fatal("retry spent resources or rerolled") + } + changed := req + changed.Ingredients = map[string]int64{"wood": 4, "ore": 2} + if _, e = l.Craft(ctx, w, c.Account, changed); !errors.Is(e, ErrCraft) { + t.Fatal("reused nonce accepted changed ingredients", e) + } + if _, e = l.Craft(ctx, w, "intruder", req); !errors.Is(e, ErrCraft) { + t.Fatal("other account recovered receipt", e) + } + // Reload from the durable world snapshot, not the live result. + if e = l.Release(ctx); e != nil { + t.Fatal(e) + } + restored := game.New(w.ID, 1, now, b) + var snapshot []byte + l, snapshot, e = db.Acquire(ctx, restored) + if e != nil { + t.Fatal(e) + } + if e = json.Unmarshal(snapshot, restored); e != nil { + t.Fatal(e) + } + if e = restored.Restore(now); e != nil { + t.Fatal(e) + } + w = restored + c = w.ForAccount(c.Account) + if c == nil || len(c.View.DiscoveredRecipes) != 1 || c.View.Crafting["weapon_smithing"].XP != 20 { + t.Fatal("restart lost progression") + } + if e = w.Connect(c.View.Entity.ID); e != nil { + t.Fatal(e) + } + hub := game.New("hub-"+game.ID(), 2, now, b) + hub.Kind = "hub" + hub.Phase = "hub" + hl, _, e := db.Acquire(ctx, hub) + if e != nil { + t.Fatal(e) + } + progression, _ := json.Marshal([]any{c.View.Crafting, c.View.DiscoveredRecipes, c.View.Items, c.View.Experience, c.CraftReadyAt}) + transfer, e := l.PrepareTravel(ctx, w, c.Account, game.ID(), hub.ID, "escape") + if e != nil { + t.Fatal(e) + } + if _, e = hl.AcceptTravel(ctx, hub, c.Account, transfer.ID); e != nil { + t.Fatal(e) + } + arrived := hub.ForAccount(c.Account) + after, _ = json.Marshal([]any{arrived.View.Crafting, arrived.View.DiscoveredRecipes, arrived.View.Items, arrived.View.Experience, arrived.CraftReadyAt}) + if string(progression) != string(after) { + t.Fatal("travel changed crafting progression or provenance") + } + replay, e = hl.Craft(ctx, hub, c.Account, req) + if e != nil || !reflect.DeepEqual(result, replay) { + t.Fatal("travel lost original receipt", e) + } +} + +func TestCraftRecipeRevision(t *testing.T) { + ctx := context.Background() + db, e := Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "recipes.db"))) + if e != nil { + t.Fatal(e) + } + defer db.Close() + initial, e := db.Catalog(ctx) + if e != nil { + t.Fatal(e) + } + recipe := content.CraftRecipe{Name: "Trial spear", Profession: "weapon_smithing", Level: 2, XP: 25, Inputs: map[string]int64{"wood": 5, "ore": 3}, Outputs: map[string]int64{"spear": 1}} + change := CatalogChange{ID: game.ID(), ExpectedVersion: initial.Version, Op: "create-craft-recipe", Reason: "Create a test recipe", CraftRecipe: &recipe} + first, e := db.PublishCatalog(ctx, "operator", change) + if e != nil { + t.Fatal(e) + } + firstCatalog, e := db.Catalog(ctx) + if e != nil { + t.Fatal(e) + } + made := firstCatalog.Crafting.Recipes[len(firstCatalog.Crafting.Recipes)-1] + if made.ID == "" || made.Revision != 1 { + t.Fatal("server did not assign recipe identity") + } + replay, e := db.PublishCatalog(ctx, "operator", change) + if e != nil || replay.Version != first.Version { + t.Fatal("recipe create retry failed", e) + } + recipe.Inputs = map[string]int64{"wood": 6, "ore": 3} + update := CatalogChange{ID: game.ID(), ExpectedVersion: first.Version, Op: "update-craft-recipe", TargetID: made.ID, Reason: "Revise test ingredients", CraftRecipe: &recipe} + _, e = db.PublishCatalog(ctx, "operator", update) + if e != nil { + t.Fatal(e) + } + revised, e := db.Catalog(ctx) + if e != nil { + t.Fatal(e) + } + got := revised.Crafting.Recipes[len(revised.Crafting.Recipes)-1] + if got.ID != made.ID || got.Revision != 2 || len(revised.Crafting.Recipes) != len(firstCatalog.Crafting.Recipes) || made.Inputs["wood"] != 5 { + t.Fatal("revision duplicated identity or mutated prior version") + } + update.ID = game.ID() + if _, e = db.PublishCatalog(ctx, "operator", update); !errors.Is(e, ErrCatalogConflict) { + t.Fatal("stale edit accepted", e) + } +} diff --git a/server/internal/store/portal.go b/server/internal/store/portal.go index 19742d6..254190c 100644 --- a/server/internal/store/portal.go +++ b/server/internal/store/portal.go @@ -65,6 +65,7 @@ func (d *DB) migrate(ctx context.Context) error { } } for _, stmt := range []string{ + `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))`, `CREATE TABLE IF NOT EXISTS title_revocations(account_id TEXT NOT NULL,title_id TEXT NOT NULL,command_id TEXT NOT NULL,PRIMARY KEY(account_id,title_id))`, diff --git a/server/internal/store/store.go b/server/internal/store/store.go index 413b9bf..c14913f 100644 --- a/server/internal/store/store.go +++ b/server/internal/store/store.go @@ -139,6 +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) +} +func (l *Lease) save(ctx context.Context, w *game.World, claimID string, command *Command, outcome string, receipt *craftReceipt) error { live := w w = stageTitleWorld(w) data, err := json.Marshal(w) @@ -159,6 +162,11 @@ func (l *Lease) SaveCommand(ctx context.Context, w *game.World, claimID string, if n != 1 { return ErrOwnership } + 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 + } + } if claimID != "" { c := w.Characters[claimID] if c == nil { diff --git a/server/internal/store/titles.go b/server/internal/store/titles.go index a93ef07..b735fee 100644 --- a/server/internal/store/titles.go +++ b/server/internal/store/titles.go @@ -21,6 +21,8 @@ func stageTitleWorld(w *game.World) *game.World { copy := *c copy.View.Titles = append([]p.TitleAward{}, c.View.Titles...) 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.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 9726294..d56fb3f 100644 --- a/server/internal/store/travel.go +++ b/server/internal/store/travel.go @@ -107,10 +107,7 @@ func (l *Lease) PrepareTravel(ctx context.Context, live *game.World, account, re return nil, err } if route == "escape" { - departing.View.Inventory["escape_stone"]-- - if departing.View.Inventory["escape_stone"] == 0 { - delete(departing.View.Inventory, "escape_stone") - } + game.TakeStack(&departing, "escape_stone", 1) } raw, err = json.Marshal(&departing) if err != nil { diff --git a/server/internal/transport/crafting.go b/server/internal/transport/crafting.go new file mode 100644 index 0000000..afc81d4 --- /dev/null +++ b/server/internal/transport/crafting.go @@ -0,0 +1,86 @@ +package transport + +import ( + p "aeternalis/server/internal/protocol" + "aeternalis/server/internal/store" + "errors" + "net/http" +) + +func (h *HTTP) craftingRoutes(mux *http.ServeMux) { + mux.HandleFunc("GET /api/crafting", 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, "character unavailable") + return + } + c := h.s.world.ForAccount(account) + if c == nil || active == nil || active.ID != c.View.Entity.ID || active.WorldID != h.s.world.ID { + fail(w, 409, "enter your character's world first") + return + } + // Publish profession levels and only recipes this character has discovered. + known := []p.KnownRecipe{} + stale := []string{} + for id, discovery := range c.View.DiscoveredRecipes { + known = append(known, discovery) + current := false + for _, recipe := range h.s.world.Balance.Crafting.Recipes { + if recipe.ID == id && recipe.Revision == discovery.Recipe.Revision { + current = true + } + } + if !current { + stale = append(stale, id) + } + } + respond(w, 200, map[string]any{"professions": h.s.world.CraftProfessions(c), "known": known, "stale": stale, "earnsXP": h.s.world.AllowsXP()}) + }) + mux.HandleFunc("POST /api/craft", 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 p.CraftRequest + if decode(w, r, &req) != nil { + fail(w, 400, "invalid craft request") + 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.refreshCatalog(r.Context()); e != nil { + fail(w, 503, "crafting catalog unavailable") + return + } + result, e := h.s.lease.Craft(r.Context(), h.s.world, account, req) + if errors.Is(e, store.ErrCraft) { + fail(w, 409, e.Error()) + return + } + if e != nil { + h.s.ready.Store(false) + for _, peer := range h.s.peers { + peer.close() + } + fail(w, 503, "craft save unavailable; retry the same attempt after reconnecting") + return + } + respond(w, 200, result) + }) +} diff --git a/server/internal/transport/http.go b/server/internal/transport/http.go index 5885526..6f2d093 100644 --- a/server/internal/transport/http.go +++ b/server/internal/transport/http.go @@ -98,6 +98,7 @@ func (h *HTTP) Handler() http.Handler { mux := http.NewServeMux() h.portalRoutes(mux) h.travelRoutes(mux) + h.craftingRoutes(mux) h.catalogRoutes(mux) mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { if !h.s.ready.Load() { @@ -149,7 +150,7 @@ func (h *HTTP) Handler() http.Handler { h.s.mu.Lock() defer h.s.mu.Unlock() b := h.s.world.Balance - respond(w, 200, map[string]any{"worldId": h.s.world.ID, "kind": h.s.world.Kind, "development": h.auth.dev, "worlds": h.worlds, "chunkSize": b.ChunkSize, "playerSpeed": b.PlayerSpeed, "attackRange": b.AttackRange, "gatherRange": b.GatherRange, "recipes": b.Recipes, "tickHz": b.TickHz}) + respond(w, 200, map[string]any{"worldId": h.s.world.ID, "kind": h.s.world.Kind, "development": h.auth.dev, "worlds": h.worlds, "chunkSize": b.ChunkSize, "playerSpeed": b.PlayerSpeed, "attackRange": b.AttackRange, "gatherRange": b.GatherRange, "tickHz": b.TickHz}) }) mux.HandleFunc("GET /api/preview", func(w http.ResponseWriter, r *http.Request) { h.s.mu.Lock() diff --git a/server/internal/transport/http_test.go b/server/internal/transport/http_test.go index c85c981..3382259 100644 --- a/server/internal/transport/http_test.go +++ b/server/internal/transport/http_test.go @@ -114,6 +114,59 @@ func TestHTTPAndSocketSecurity(t *testing.T) { if bytes.Contains(data, []byte(`"account"`)) { t.Fatal("account identity leaked") } + // Public configuration and unauthenticated routes must never expose recipes. + for _, path := range []string{"/api/config", "/api/crafting", "/api/control/catalog"} { + response, e := server.Client().Get(server.URL + path) + if e != nil { + t.Fatal(e) + } + body, _ := io.ReadAll(response.Body) + response.Body.Close() + if bytes.Contains(body, []byte("recipe_spear")) || bytes.Contains(body, []byte(`"recipes"`)) { + t.Fatal("secret recipes exposed", path) + } + if path != "/api/config" && response.StatusCode == 200 { + t.Fatal("unauthenticated crafting/catalog access", path) + } + } + svc.mu.Lock() + c := svc.world.Characters[character.Entity.ID] + c.View.Inventory["herb"] = 10 + svc.mu.Unlock() + craft := p.CraftRequest{ID: game.ID(), CharacterID: character.Entity.ID, Profession: "alchemist", Ingredients: map[string]int64{"herb": 2}} + body, _ := json.Marshal(craft) + for _, origin := range []string{"", "https://evil.example"} { + response := request("/api/craft", origin, string(body), cookie) + response.Body.Close() + if response.StatusCode != 403 { + t.Fatal("cross-origin crafting accepted") + } + } + response = request("/api/craft", server.URL, string(body), cookie) + var outcome p.CraftResult + if e := json.NewDecoder(response.Body).Decode(&outcome); e != nil { + t.Fatal(e) + } + response.Body.Close() + if response.StatusCode != 200 || !outcome.Valid || outcome.Recipe == nil { + t.Fatal("ingredient craft did not record valid recipe", outcome) + } + get, _ := http.NewRequest("GET", server.URL+"/api/crafting", nil) + get.AddCookie(cookie) + response, err = server.Client().Do(get) + if err != nil { + t.Fatal(err) + } + var known struct { + Known []p.KnownRecipe `json:"known"` + } + if err = json.NewDecoder(response.Body).Decode(&known); err != nil { + t.Fatal(err) + } + response.Body.Close() + if len(known.Known) != 1 || known.Known[0].Recipe.ID != "recipe_bandage" { + t.Fatal("crafting returned undiscovered recipes") + } intent := p.Intent{Op: "move", Seq: 1, X: 1} payload, _ := json.Marshal(intent) if err = conn.Write(socketCtx, websocket.MessageText, payload); err != nil {