From 6903d5ece868b06d280188c87674cac0a6ac2b6f Mon Sep 17 00:00:00 2001 From: dingo Date: Thu, 10 Sep 2026 05:44:45 -0400 Subject: [PATCH] Add housing storage, guest permissions, and timed key destruction --- client/src/content-editor.ts | 7 +- client/src/generated.ts | 196 +++++++--- client/src/housing-panel.ts | 80 ++++ client/src/housing.css | 10 + client/src/main.ts | 5 + docs/ARCHITECTURE.md | 11 +- docs/LIFECYCLE-OWNERSHIP.md | 6 + docs/MILESTONE-8A.md | 3 +- docs/MILESTONE-8B.md | 116 ++++++ planning/SYSTEMS-ROADMAP.md | 16 +- planning/VISION.md | 5 +- schemas/protocol.json | 118 +++++- server/content/balance.yaml | 4 + server/content/content.go | 6 + server/content/housing.go | 52 +++ server/content/stats.go | 36 +- server/internal/game/admin_content.go | 3 + server/internal/game/combat.go | 4 +- server/internal/game/crafting.go | 2 +- server/internal/game/equipment.go | 22 ++ server/internal/game/housing.go | 132 +++++++ server/internal/game/housing_test.go | 72 ++++ server/internal/game/travel.go | 3 + server/internal/game/world.go | 19 +- server/internal/protocol/generated.go | 244 ++++++++---- server/internal/store/catalog.go | 7 + server/internal/store/crafting.go | 2 +- server/internal/store/house_items.go | 123 ++++++ server/internal/store/house_lifecycle.go | 153 ++++++++ server/internal/store/house_recovery_test.go | 174 +++++++++ server/internal/store/house_view.go | 123 ++++++ server/internal/store/housing.go | 386 +++++++++++++++++++ server/internal/store/housing_test.go | 256 ++++++++++++ server/internal/store/portal.go | 6 + server/internal/store/revival.go | 4 +- server/internal/store/store.go | 12 +- server/internal/store/titles.go | 1 + server/internal/store/travel.go | 2 + server/internal/transport/housing.go | 67 ++++ server/internal/transport/housing_test.go | 80 ++++ server/internal/transport/http.go | 1 + 41 files changed, 2386 insertions(+), 183 deletions(-) create mode 100644 client/src/housing-panel.ts create mode 100644 client/src/housing.css create mode 100644 docs/MILESTONE-8B.md create mode 100644 server/content/housing.go create mode 100644 server/internal/game/housing.go create mode 100644 server/internal/game/housing_test.go create mode 100644 server/internal/store/house_items.go create mode 100644 server/internal/store/house_lifecycle.go create mode 100644 server/internal/store/house_recovery_test.go create mode 100644 server/internal/store/house_view.go create mode 100644 server/internal/store/housing.go create mode 100644 server/internal/store/housing_test.go create mode 100644 server/internal/transport/housing.go create mode 100644 server/internal/transport/housing_test.go diff --git a/client/src/content-editor.ts b/client/src/content-editor.ts index 419d053..0703088 100644 --- a/client/src/content-editor.ts +++ b/client/src/content-editor.ts @@ -120,6 +120,7 @@ function titleForm(){ } function itemForm(){ if(editing||saving){show('Finish or cancel the open draft first.');return;} + const furniture=node('input'),container=node('input'),width=number(2,.5,4),depth=number(1,.5,4);furniture.type='checkbox';container.type='checkbox'; const pool=craftPool(),rolls=number(0,0,8,'1'); const weaponType=contentChoice([{id:'',name:'No proficiency'},...(catalog.powers?.weapons??[])]);weaponType.required=false; const values=identity(),slot=select(itemSlots,'weapon'),weight=number(1,0,10000),drop=number(0,0,100),level=number(1,1,10000,'1'),effects=modifiers(); @@ -127,8 +128,8 @@ function itemForm(){ 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(),weaponType:weaponType.value,craftPool:pool.read(),craftRolls:Number(rolls.value),slot:slot.value,...(slot.value==='weapon'&&attack.value?{attackId:attack.value}:{}),weight:Number(weight.value),dropChance:Number(drop.value),requirements:{level:Number(level.value),stats:Object.fromEntries(req.map(r=>[r.stat,r.value])),titles:checks.filter(c=>c.input.checked).map(c=>c.id)},modifiers:effects.read()}}}); - fields.append(values.node,field('Equipment slot',slot),field('Weapon attack profile',attack),field('Weapon proficiency',weaponType),field('Weight',weight),field('Sentinel drop chance (%)',drop),node('p','Zero disables sentinel drops. Drop-rate bonuses apply. Requirements are checked without equipment bonuses.','muted'),sets.node,field('Required level',level),requirements.node,titles,effects.node,field('Stats rolled when crafted',rolls),pool.node); + const fields=form('Create equipment','create-item',()=>{const req=requirements.read();if(new Set(req.map(r=>r.stat)).size!==req.length)throw new Error('Each required stat can appear once.');return {...sets.read(),item:{...values.read(),weaponType:weaponType.value,craftPool:pool.read(),craftRolls:Number(rolls.value),slot:furniture.checked?'bag':slot.value,...(furniture.checked?{furniture:{width:Number(width.value),depth:Number(depth.value),container:container.checked}}:{}),...(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(field('House furniture (carried in bag)',furniture),field('Storage container',container),field('Furniture width (metres)',width),field('Furniture depth (metres)',depth),values.node,field('Equipment slot',slot),field('Weapon attack profile',attack),field('Weapon proficiency',weaponType),field('Weight',weight),field('Sentinel drop chance (%)',drop),node('p','Zero disables sentinel drops. Drop-rate bonuses apply. Requirements are checked without equipment bonuses.','muted'),sets.node,field('Required level',level),requirements.node,titles,effects.node,field('Stats rolled when crafted',rolls),pool.node); } function statsForm(){ if(editing||saving){show('Finish or cancel the open draft first.');return;} @@ -147,7 +148,7 @@ function render(){ }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),node('p',`${i.craftRolls??0} crafted stat rolls`),readableDefinition(i.craftPool??[]));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??[]));if(i.furniture)d.append(node('p',`House furniture · ${i.furniture.width} × ${i.furniture.depth}m · ${i.furniture.container?'Storage container':'Decoration'}`));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);} diff --git a/client/src/generated.ts b/client/src/generated.ts index f562268..ff5c761 100644 --- a/client/src/generated.ts +++ b/client/src/generated.ts @@ -6,6 +6,8 @@ export interface Protocol { catalogResult?: ContentResult; craftRequest?: CraftRequest; craftResult?: CraftResult; + houseRequest?: HouseRequest; + houseState?: HouseState; intent: Intent; snapshot: Snapshot; } @@ -16,6 +18,7 @@ export interface ContentCatalog { crafting?: CraftingContent; effectSets?: EffectSet[]; gathering?: GatheringContent; + housingVersion?: number; items: ItemDefinition[]; powers?: PowerContent; requirementSets?: RequirementSet[]; @@ -231,6 +234,7 @@ export interface ItemDefinition { craftRolls?: number; description: string; dropChance: number; + furniture?: FurnitureProfile; id: string; modifiers: StatModifier[]; name: string; @@ -248,6 +252,12 @@ export interface CraftStat { weight: number; } +export interface FurnitureProfile { + container: boolean; + depth: number; + width: number; +} + export interface ItemRequirements { level: number; stats: { [key: string]: number }; @@ -441,6 +451,7 @@ export interface ItemDraft { craftRolls?: number; description: string; dropChance: number; + furniture?: FurnitureProfile; id?: string; modifiers: StatModifier[]; name: string; @@ -578,6 +589,126 @@ export interface KnownRecipe { recipe: CraftRecipe; } +export interface HouseRequest { + houseId?: string; + item?: string; + name?: string; + op: string; + permissions?: { [key: string]: boolean }; + quantity?: number; + requestId: string; + revision?: number; + role?: string; + target?: string; + x?: number; + z?: number; +} + +export interface HouseState { + effective: { [key: string]: boolean }; + houses: HouseSummary[]; + people: Entity[]; + role: string; + room?: House; +} + +export interface HouseSummary { + creator: boolean; + id: string; + keys: number; + name: string; + recoveryWorld: string; + role: string; + state: string; +} + +export interface Entity { + depth?: number; + height?: number; + hp: number; + id: string; + kind: string; + maxHp: number; + model?: string; + name: string; + position: Vec3; + radius?: number; + requiredLevel?: number; + resourceId?: string; + skillId?: string; + state: string; + width?: number; +} + +export interface Vec3 { + x: number; + y: number; + z: number; +} + +export interface House { + floor: HouseInventory; + furniture: { [key: string]: HouseFurniture }; + id: string; + name: string; + overrides: { [key: string]: { [key: string]: boolean } }; + permissions: { [key: string]: boolean }; + revision: number; + roles: { [key: string]: string }; + size: number; + state: string; +} + +export interface HouseInventory { + craftedStacks: CraftedStack[]; + inventory: { [key: string]: number }; + items: ItemInstance[]; + stackNames: { [key: string]: string }; +} + +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 ItemInstance { + attack?: CombatAttack; + definitionId: string; + description: string; + equippable: boolean; + furniture?: FurnitureProfile; + houseId?: string; + id: string; + modifiers: StatModifier[]; + name: string; + provenance?: CraftProvenance; + requirementMessage: string; + requirements: ItemRequirements; + slot: string; + weaponType?: string; + weight: number; +} + +export interface HouseFurniture { + contents: HouseInventory; + item: ItemInstance; + x: number; + z: number; +} + export interface Intent { op: string; seq: number; @@ -614,30 +745,6 @@ export interface Chunk { z: number; } -export interface Entity { - depth?: number; - height?: number; - hp: number; - id: string; - kind: string; - maxHp: number; - model?: string; - name: string; - position: Vec3; - radius?: number; - requiredLevel?: number; - resourceId?: string; - skillId?: string; - state: string; - width?: number; -} - -export interface Vec3 { - x: number; - y: number; - z: number; -} - export interface GatheringRisk { allowed: boolean; damage: number; @@ -667,6 +774,7 @@ export interface Character { consumables?: GatheringConsumable[]; craftedStacks?: CraftedStack[]; crafting?: { [key: string]: CraftProgress }; + destroyKey?: KeyDestruction; discoveredRecipes?: { [key: string]: KnownRecipe }; entity: Entity; equipment: { [key: string]: string }; @@ -677,6 +785,7 @@ export interface Character { gatheringEffects?: TimedGatheringEffect[]; hasKeystone: boolean; healthChoices: number; + houseId?: string; inventory: { [key: string]: number }; items: ItemInstance[]; kills: number; @@ -696,24 +805,6 @@ export interface Character { weapons?: { [key: string]: WeaponProgress }; } -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; @@ -723,6 +814,11 @@ export interface CraftProgress { xpToNextLevel: number; } +export interface KeyDestruction { + finishesAt: number; + keyId: string; +} + export interface SkillProgress { effectiveLevel: number; experience: StatValue; @@ -749,22 +845,6 @@ export interface TimedGatheringEffect { source: string; } -export interface ItemInstance { - attack?: CombatAttack; - definitionId: string; - description: string; - equippable: boolean; - id: string; - modifiers: StatModifier[]; - name: string; - provenance?: CraftProvenance; - requirementMessage: string; - requirements: ItemRequirements; - slot: string; - weaponType?: string; - weight: number; -} - export interface LearnedPower { attack: CombatAttack; definition: PowerDefinition; diff --git a/client/src/housing-panel.ts b/client/src/housing-panel.ts new file mode 100644 index 0000000..45273df --- /dev/null +++ b/client/src/housing-panel.ts @@ -0,0 +1,80 @@ +import type {Character, HouseInventory, HouseRequest, HouseState} from './generated'; +import {api, APIError} from './portal-shared'; +import {node} from './character-stats'; +import {registerMenu} from './menu-focus'; +import './housing.css'; + +const permissions:Record={moveFurniture:'Move furniture',openFurniture:'Open furniture',placeFurniture:'Place furniture',depositItems:'Put items in furniture',pickupItems:'Pick up items in the house',dropItems:'Drop items in the house'}; +const label=(text:string,control:HTMLElement)=>{const el=node('label',text);el.append(control);return el}; +const button=(text:string,action:()=>void)=>{const b=node('button',text);b.type='button';b.onclick=action;return b}; +const select=(rows:[string,string][])=>{const s=node('select');for(const [id,name] of rows)s.append(new Option(name,id));return s}; +const number=(value:number,min:number,max:number)=>{const n=node('input');n.type='number';n.value=String(value);n.min=String(min);n.max=String(max);n.step='0.5';return n}; +type InventoryView=Pick & {stackNames?:Record}; +function choices(v:InventoryView):[string,string][]{return [...v.items.map(i=>[i.id,i.name] as [string,string]),...Object.entries(v.inventory).filter(([,n])=>n>0).map(([id,n])=>[id,`${v.stackNames?.[id]??id} × ${n}`] as [string,string])];} + +export function createHousingPanel(character:()=>Character|undefined,prefix:string,isHub:()=>boolean){ + const root=node('section'),open=button('Housing & keys',()=>{dialog.showModal();menu.opened();void refresh(true)}); + const dialog=node('dialog','','housing-dialog'),title=node('h2','Housing'),status=node('p'),body=node('div'),close=button('Close',()=>void leave()); + const retry=button('Retry pending action',()=>{if(pending)void action(pending,true)});retry.hidden=true; + status.setAttribute('role','status');root.append(open);dialog.append(title,close,status,retry,body);document.body.append(dialog); + let pending:HouseRequest|undefined,state:HouseState|undefined,busy=false,loading=false,signature='',lastHouse='',selected='',latest:Character|undefined; + const menu=registerMenu(dialog,()=>void leave());dialog.addEventListener('cancel',e=>{e.preventDefault();void leave()}); + async function leave(){if(busy)return;if(character()?.houseId||state?.room)await action({op:'leave'});dialog.close();signature=''} + async function action(r:Omit,retrying=false){ + if(busy)return;if(pending&&!retrying){status.textContent='Resolve the pending action before making another change.';return}busy=true;dialog.classList.add('housing-busy');status.textContent='Saving…'; + pending??={...r,houseId:r.houseId??state?.room?.id,revision:r.revision??state?.room?.revision,requestId:crypto.randomUUID()}; + try{await api(prefix+'/api/housing',pending);pending=undefined;status.textContent=r.op==='destroy-key'?'Destroying key. It remains lootable until the three seconds finish.':'Saved.';signature='';await refresh(true)} + catch(e){if(e instanceof APIError&&e.status<500)pending=undefined;status.textContent=(e as Error).message+(pending?' Retry the pending action to resolve its result safely.':'');await refresh(true)} + finally{busy=false;retry.hidden=!pending;dialog.classList.remove('housing-busy')} + } + async function refresh(force=false){ + if(loading||!dialog.open)return;loading=true; + try{state=await api(prefix+'/api/housing');const c=character();if(!c)return;latest=c; + const next=JSON.stringify([state,c.items,c.inventory]);if(force||signature!==next){signature=next;render()} + }catch(e){status.textContent=(e as Error).message}finally{loading=false} + } + function render(){ + const c=latest,s=state;if(!c||!s)return;body.replaceChildren();const h=s.room; + title.textContent=h?h.name+' · '+s.role:'Housing & keys';close.textContent=h?'Leave house':'Close'; + const keys=node('section');keys.append(node('h3','Carried keys'),node('p','Destroying a key takes three seconds. Death, dropping the key, leaving the world, or disconnecting cancels the action.')); + for(const key of c.items.filter(i=>i.houseId)){const row=node('p',key.name+' ');row.append(button('Destroy key',()=>void action({op:'destroy-key',item:key.id})));keys.append(row)} + const progress=node('p');progress.dataset.keyProgress='';keys.append(progress,button('Cancel key destruction',()=>void action({op:'cancel-key'})));body.append(keys); + if(!h){ + body.append(node('p',isHub()?'Create or enter a house after surviving your first world. A carried key grants owner rights.':'Return to a hub to enter housing. Keys can be destroyed here.')); + if(isHub()){const name=node('input');name.maxLength=80;name.placeholder='House name';body.append(label('New house name',name),button('Create house',()=>void action({op:'create',name:name.value})))} + for(const entry of s.houses){const row=node('section');row.append(node('h3',entry.name),node('p',`${entry.state} · ${entry.role||'no access'} · ${entry.keys} valid keys`));if(isHub()&&entry.state==='active'&&entry.role)row.append(button('Enter',()=>void action({op:'enter',houseId:entry.id})));if(isHub()&&entry.creator&&entry.recoveryWorld&&entry.state!=='purged')row.append(button('Recover creator key',()=>void action({op:'recover',houseId:entry.id})));body.append(row)}return; + } + body.prepend(node('p','Private house room · click the floor to choose a position, or furniture to select it. No experience is earned here.')); + const layout=node('div','','house-layout');layout.setAttribute('aria-label','House floor plan'); + const x=number(0,-h.size/2,h.size/2),z=number(0,-h.size/2,h.size/2); + layout.onclick=e=>{if(e.target!==layout)return;const b=layout.getBoundingClientRect();x.value=String(Math.round(((e.clientX-b.left)/b.width*h.size-h.size/2)*2)/2);z.value=String(Math.round(((e.clientY-b.top)/b.height*h.size-h.size/2)*2)/2)}; + const furniture=select([['','Choose furniture'],...Object.values(h.furniture).map(f=>[f.item.id,f.item.name] as [string,string])]);furniture.value=selected; + const choose=(id:string)=>{selected=id;furniture.value=id;const f=h.furniture[id];if(f){x.value=String(f.x);z.value=String(f.z)}showStorage()};furniture.onchange=()=>choose(furniture.value); + for(const [id,f] of Object.entries(h.furniture)){const b=button(f.item.name,()=>choose(id)),p=f.item.furniture!;b.className='house-piece';b.style.left=(f.x+h.size/2)/h.size*100+'%';b.style.top=(f.z+h.size/2)/h.size*100+'%';b.style.width=p.width/h.size*100+'%';b.style.height=p.depth/h.size*100+'%';layout.append(b)} + body.append(layout,label('Selected furniture',furniture),label('East / west',x),label('North / south',z)); + const held=select(c.items.filter(i=>i.furniture).map(i=>[i.id,i.name])); + if(s.effective.placeFurniture)body.append(label('Furniture in inventory',held),button('Place furniture',()=>void action({op:'place',item:held.value,x:Number(x.value),z:Number(z.value)}))); + if(s.effective.moveFurniture)body.append(button('Move selected furniture',()=>void action({op:'move',target:furniture.value,x:Number(x.value),z:Number(z.value)}))); + if(s.effective.pickupItems)body.append(button('Pick up selected furniture',()=>void action({op:'pickup-furniture',target:furniture.value}))); + const storage=node('section');body.append(storage);showStorage(); + function transfer(parent:HTMLElement,inventory:InventoryView,text:string,op:string,target=''){ + const rows=choices(inventory);if(!rows.length){parent.append(node('p',text+': no items'));return}const item=select(rows),qty=number(1,1,1000);qty.step='1';parent.append(label(text,item),label('Quantity',qty),button(text,()=>void action({op,item:item.value,quantity:Number(qty.value),target}))); + } + function showStorage(){if(!s||!h||!c)return;storage.replaceChildren();const f=h.furniture[furniture.value]; + if(f?.item.furniture?.container){storage.append(node('h3',f.item.name));if(s.effective.openFurniture){const rows=choices(f.contents);storage.append(node('p',rows.map(([,name])=>name).join(', ')||'Empty'));if(s.effective.pickupItems)transfer(storage,f.contents,'Take from furniture','withdraw',f.item.id)}else storage.append(node('p','You cannot open this furniture.'));if(s.effective.depositItems)transfer(storage,c,'Put in furniture','deposit',f.item.id)} + } + const floor=node('section');floor.append(node('h3','Floor items'),node('p',choices(h.floor).map(([,name])=>name).join(', ')||'Nothing on the floor.'));if(s.effective.pickupItems)transfer(floor,h.floor,'Pick up floor item','pickup');if(s.effective.dropItems)transfer(floor,c,'Drop on floor','drop');body.append(floor); + if(s.role==='owner'||s.role==='co-owner'){ + const management=node('details');management.append(node('summary','Guests & permissions'));body.append(management); + const names=new Map(s.people.map(p=>[p.id,p.name]));const people=select(s.people.filter(p=>p.id!==c.entity.id).map(p=>[p.id,p.name]));const role=select(s.role==='owner'?[['guest','Guest'],['co-owner','Co-owner']]:[['guest','Guest']]);management.append(label('Player in this hub',people),label('Invitation role',role),button('Invite',()=>void action({op:'invite',target:people.value,role:role.value}))); + for(const [id,roleName] of Object.entries(h.roles)){const row=node('p',(names.get(id)??'Invited character')+' · '+roleName+' ');if(s.role==='owner'||roleName!=='co-owner')row.append(button('Remove invitation',()=>void action({op:'invite',target:id,role:'remove'})));management.append(row)} + if(s.role==='owner')management.append(button('Create additional owner key',()=>void action({op:'issue-key'}))); + management.append(node('p','Every valid key grants owner rights. Removing an invitation cannot revoke a key. Co-owners can manage guests.')); + const target=select([['','Baseline for all guests'],...Object.keys(h.roles).map(id=>[id,names.get(id)??'Invited character'] as [string,string])]),fields=node('div');management.append(label('Permission settings for',target),fields);let values:Record={}; + const show=()=>{fields.replaceChildren();values={};for(const [key,text] of Object.entries(permissions)){const field=select(target.value?[['inherit','Use baseline'],['allow','Allow'],['deny','Deny']]:[['allow','Allow'],['deny','Deny']]);const v=target.value?h.overrides[target.value]?.[key]:h.permissions[key]??false;field.value=v===undefined?'inherit':v?'allow':'deny';values[key]=field;fields.append(label(text,field))}};target.onchange=show;show(); + management.append(button('Save guest permissions',()=>{const permissions:Record={};for(const [key,field] of Object.entries(values))if(field.value!=='inherit')permissions[key]=field.value==='allow';void action({op:'permissions',target:target.value,permissions})})); + } + } + setInterval(()=>{if(dialog.open&&!busy)void refresh();const a=character()?.destroyKey;const p=dialog.querySelector('[data-key-progress]');if(p)p.textContent=a?`Key destruction in progress · ${Math.max(0,a.finishesAt-Date.now()/1000).toFixed(1)}s remaining (server confirmed on completion)`:'No key destruction in progress.'},1000); + return {root,update(c:Character){latest=c;open.textContent=c.houseId?'Return to house controls':'Housing & keys';if(c.entity.state==='dead'||c.remainingSeconds<=0){dialog.close();return}if((c.houseId??'')!==lastHouse){lastHouse=c.houseId??'';signature='';if(c.houseId&&!dialog.open){dialog.showModal();menu.opened()}if(dialog.open)void refresh(true)}}}; +} diff --git a/client/src/housing.css b/client/src/housing.css new file mode 100644 index 0000000..6f4b3ab --- /dev/null +++ b/client/src/housing.css @@ -0,0 +1,10 @@ +.housing-dialog{width:min(900px,94vw);max-height:92dvh;overflow:auto;background:#17212b;color:#ecf0ed;border:1px solid #617565;border-radius:14px;padding:24px} +.housing-dialog::backdrop{background:#081019cf} +.housing-dialog section{border-top:1px solid #46544c;margin-top:20px;padding-top:10px} +.housing-dialog label{display:inline-flex;flex-direction:column;gap:5px;margin:8px;max-width:95%} +.housing-dialog button{margin:5px;padding:9px;cursor:pointer} +.housing-dialog select,.housing-dialog input{background:#25333b;color:#fff;padding:8px;border:1px solid #66786c;max-width:100%} +.housing-busy button,.housing-busy input,.housing-busy select{pointer-events:none;opacity:.6} +.house-layout{position:relative;width:min(100%,540px);aspect-ratio:1;margin:16px auto;background-color:#76664b;background-image:linear-gradient(#b2a48344 1px,transparent 1px),linear-gradient(90deg,#b2a48344 1px,transparent 1px);background-size:8.333% 8.333%;border:8px solid #403c36;cursor:crosshair} +.housing-dialog .house-piece{position:absolute;transform:translate(-50%,-50%);margin:0;padding:1px;background:#b48b54;color:#171c1b;overflow:hidden;font-size:11px;border:2px solid #463421;border-radius:3px} +.housing-dialog .house-piece:focus{outline:3px solid #b7e2bb} diff --git a/client/src/main.ts b/client/src/main.ts index 661f19b..12ad58a 100644 --- a/client/src/main.ts +++ b/client/src/main.ts @@ -1,5 +1,6 @@ import './style.css'; import { showTravel } from './travel'; +import { createHousingPanel } from './housing-panel'; import { buildingPanel } from './building-panel'; import { craftingPanel } from './crafting-panel'; import { createPowerPanel, revivalPanel } from './power-panel'; @@ -52,6 +53,7 @@ const avoidUntil = new Map(); let requestedClose = false; let input: InputActions; let powers:ReturnType; +let housing:ReturnType; let placement:{id:string;rotation:string;range:number}|undefined; let view: WorldView; const selectedWorld = new URLSearchParams(location.search).get('world'); @@ -139,6 +141,7 @@ function showEnding(title: string, detail: string, survivor: boolean) { $('ending').show(); } function inventory(c: Character) { + housing?.update(c); $('earned-titles').replaceChildren(permanentTitles(c.titles)); const parent = $('inventory-items'), panel = characterPanel(c, send); if (panel.parentElement !== parent) parent.replaceChildren(panel); @@ -216,6 +219,7 @@ async function boot() { inputElapsed += dt; input.pollController(); if (!snapshot || ws?.readyState !== WebSocket.OPEN || $('ending').open) return; + if(snapshot.self.houseId){input.clear();walkTo=undefined;pendingAction=undefined;return} if(document.hidden||hasOpenMenu()||isEditing(document.activeElement)){ input.clear();walkTo=undefined;pendingAction=undefined;view.moving=false; if(inputElapsed>=0.05){send('move');inputElapsed=0;}return; @@ -264,6 +268,7 @@ async function boot() { }, 50); const [loadedConfig, chunks] = await Promise.all([api('/api/config'), api('/api/preview'), view.load()]); config = loadedConfig; + housing=createHousingPanel(()=>snapshot?.self,worldPrefix,()=>config.kind==='hub');$('recipes').after(housing.root); powers=createPowerPanel((op,target,x,z,slot)=>{if(op==='cast'){input.clear();walkTo=undefined;pendingAction=undefined;send('move')}send(op,target,x,z,slot)},()=>view.selected,notice,worldPrefix);$('recipes').after(powers.root);$('hud').append(powers.hotbar);$('settings').append(input.settings());$('recipes').after(buildingPanel(()=>snapshot?.self,(id,rotation,range)=>{placement={id,rotation,range};input.clear();walkTo=undefined;pendingAction=undefined;send('move');$('inventory-toggle').click();notice('Click clear ground to build. Esc cancels.');},worldPrefix)); const travelButton=document.createElement('button');travelButton.id='travel';travelButton.textContent='Travel';travelButton.title='World travel';$('inventory-toggle').before(travelButton); travelButton.onclick=()=>{if(!snapshot)return;input.clear();walkTo=undefined;pendingAction=undefined;send('move');void showTravel({worldId:config.worldId,route:config.kind==='hub'?'hub':snapshot.world.phase==='won'?'portal':'escape',beforeTravel:()=>{requestedClose=true;},afterTravel:departed=>{requestedClose=departed;}});}; diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 4f18d07..9493be1 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -35,8 +35,9 @@ The highest-risk requirements are: Planning update: the vision now includes corpse-based item/spell resurrection, key-owned hub housing, crafting rolls/provenance, and portal dungeon instances. -Milestone 7 now implements corpse resurrection for new deaths. Key-owned housing -and portal dungeon instances remain design requirements. See +Milestone 7 now implements corpse resurrection for new deaths. Milestone 8b adds +key-owned housing documents and floor-plan controls; walkable interiors and portal +dungeon instances remain. See `planning/SYSTEMS-ROADMAP.md` for future lifecycle rules and unresolved details. The milestone 1 [lifecycle and ownership contract](LIFECYCLE-OWNERSHIP.md) maps the current code to proposed states, transaction boundaries, and migration steps. @@ -46,6 +47,12 @@ destination acceptance each commit under their own owner lease, with the account reserved throughout transit. Hub crafting suppresses XP and retains daily usage. One Go process owns one world, with a serial simulation protected by one lock. +Housing membership stays with the current hub's character owner. Separate shared +house documents and key ledgers serialize storage/permission/key changes with +the fenced character snapshot, so all hubs access the same retained contents. +The three-second action destroys a key; only completion removing the last valid +key archives a house. Recovery and purge follow the recorded creator death world. +See [milestone 8b](MILESTONE-8B.md) for the concrete interface, bounds, and defaults. Clients submit bounded intents. The server determines speed, terrain height, range, cooldown, inventory changes, damage, death, play-time, and passage eligibility. Movement is interpolated on the client; full prediction/reconciliation is deferred. diff --git a/docs/LIFECYCLE-OWNERSHIP.md b/docs/LIFECYCLE-OWNERSHIP.md index ded1c49..9ed3665 100644 --- a/docs/LIFECYCLE-OWNERSHIP.md +++ b/docs/LIFECYCLE-OWNERSHIP.md @@ -136,6 +136,12 @@ neither an escape item nor a hub switch supplies a fresh allowance. ## House permissions, three-second key destruction, and recovery +Implementation checkpoint: [milestone 8b](MILESTONE-8B.md) now implements these +transactions and permission rules with floor-plan controls. Its provisional rules +resolve the open interruption, eligibility, invitation, and occupant choices below +for playtesting. Walkable interiors remain outstanding. The stored state name for +`archived_recoverable` is `archived`. + Proposed house states: `active -> archived_recoverable -> purged`. Eligible recovery returns archived state to the same active house. `purged` has no recoverable contents. A record of the purge may remain for audit/history. diff --git a/docs/MILESTONE-8A.md b/docs/MILESTONE-8A.md index ef6502d..d563d6f 100644 --- a/docs/MILESTONE-8A.md +++ b/docs/MILESTONE-8A.md @@ -1,6 +1,7 @@ # Milestone 8a: world building checkpoint -Milestone 8 is **in progress**. This checkpoint implements the independent world +Milestone 8 is **in progress**. The later [8b checkpoint](MILESTONE-8B.md) implements +housing controls and lifecycle. This checkpoint implements the independent world building work. House instances, keys, invitations, storage, deletion, and recovery are not implemented here. Their access and recovery decisions remain pending. diff --git a/docs/MILESTONE-8B.md b/docs/MILESTONE-8B.md new file mode 100644 index 0000000..e94071d --- /dev/null +++ b/docs/MILESTONE-8B.md @@ -0,0 +1,116 @@ +# Milestone 8b: housing controls and lifecycle checkpoint + +This checkpoint adds usable housing ownership, storage, permissions, and recovery +alongside [8a's world building](MILESTONE-8A.md). Housing is presented as an +interactive floor plan. Walkable 3D interiors, furniture models, in-room avatars, +and controller placement remain milestone 8 work; this is not the final interior +presentation. No milestone 9 cosmetics are implemented by this checkpoint. + +## Player controls + +Open Inventory → **Housing & keys**. In a hub, a character who survived a world +can create a named house, enter using a carried key or invitation, and recover a +creator key when eligible. IDs are generated by Go. Escape closes the focused +house controls and requests exit; if the request fails, the server keeps the +character inside until exit is confirmed. Reopen **Return to house controls** to +retry. Daily play time continues inside; reaching the limit exits the room. + +Click the floor plan to choose a position or select placed furniture. Furniture +can be placed, moved without pickup, or picked up when empty. The floor and each +storage container have independent item inventories. Unique equipment and crafted +stack provenance retain their identities when moved. Furniture placement uses +its copied footprint; Go rejects overlap and out-of-room placement. Furniture +does not grant equipped stat bonuses. Exit to use the hub crafting workbench. + +Control → Content → Equipment includes furniture and storage-container fields. +The additive catalog migration supplies **Storage chest** and **House table** for +manual testing. Admins can grant these through the player item controls; equipment +recipes can output furniture through the existing crafting system. Definitions +remain immutable, with each instance retaining its copied furniture profile. + +## Permissions and keys + +Owners and co-owners manage invitations and all six guest permissions: move, +open, place furniture; deposit into furniture; pick up house items; drop house +items. Baselines default to deny. Each invited character can inherit, allow, or +deny each permission independently. Opening a container does not grant withdrawal +or deposit rights. Withdrawal requires both open and pickup rights. Container +contents are hidden from guests without open permission. + +Every carried valid key grants owner rights, regardless of invitation settings. +Keys are unique, transferable inventory items and ordinary corpse loot. Owners +can issue additional keys and assign co-owners; co-owners can invite/remove guests +and change guest permissions. Removing an invitation never invalidates a key. +These invitation/issuance distinctions are provisional first-build rules. + +**Destroy key** is available in survival worlds as well as hubs. It starts a +three-second server action. The key remains valid and lootable until completion. +Movement and incoming damage do not cancel it. Death, dropping/depositing that +key, departure, disconnect/restart, daily cap, or explicit cancellation do. +Completion rechecks the exact living holder and key under the world lease. +The key registry counts other players' keys, corpse keys, and stored keys. +Admins cannot bypass the action by directly removing a key from inventory. + +Destroying a non-last key leaves the house active. Destroying the last key +immediately archives the final house contents and removes access; there is no +additional three-second house timer. Occupants return to their existing hub +position when their membership is reconciled, and every action checks access +again before committing. Keys on inaccessible corpses remain valid; automatic +retirement of those keys requires a separate product decision. + +## Recovery and provisional bounds + +The original creator account may recover a key to the same house before the +recorded original creator's death world is destroyed. A replacement character +must first survive a world. Recovery does not recreate withdrawn items or revoke +other keys. Ordinary replacement progression, equipment, invitations, and titles +are not inherited through this mechanism. The older account-title migration +remains a separate backlog item. + +Archived data is purged when the recorded death world is destroyed; an active +house with valid keys survives. Missing death/world records retain data rather +than inventing a purge deadline, and recovery requires a known, unlost world. +Purging stored keys also updates their house registries. No recovery is possible +after purge. One unpurged created house per account, 128 keys, a 12m room, 64 +furniture pieces, 64 invitations, and 256 unique items per inventory/container are +provisional bounds. A house's own key cannot be left inside that same house, +preventing its only access item from becoming locked inside. Other house keys can +be stored. Creation and entry require survival credit; escape alone grants none. + +## Persistence and validation + +The current hub process continues to own the character. Houses are separate shared +database documents, so hub-instance changes access the same room and contents. +Authenticated `/api/housing` requests are intents. House row locking, inventory +changes, key issuance/destruction, request receipts, and the fenced world snapshot +commit together. Guest changes are enforced on every action; revision checks +protect UI edits. An old source-world character copy cannot complete a transferred +key action. Startup clears room membership and pending actions, preserving keys +and house data. Upgrade all world owners before testing new item metadata across +worlds; older binaries are not compatible with the new housing fields. + +Tests cover baseline/individual permissions, container privacy, forbidden actions, +key looting, last-key timing, death/drop/disconnect/restart cancellation, creator +recovery, world-loss purge, travel, stale-world fencing, daily limits, provenance, +and HTTP authentication/origin checks. SQLite runs locally; the PostgreSQL housing +lifecycle test requires `TEST_DATABASE_URL`. Browser Playwright tests remain +deferred to the existing testing backlog, with manual playtesting for this build. + +## Manual handoff + +1. Survive a world and reach a hub. Create a house in **Housing & keys**, enter, + and verify Escape returns you to the hub. +2. Grant a chest and table in Control. Place/move both; check overlaps are rejected. + Deposit and withdraw resources and crafted gear; refresh/reconnect and verify + the exact items and their provenance remain. +3. Invite a second survivor as a guest. Test each baseline permission, then a + per-person override. Verify open, deposit, and pickup work independently. +4. Create an extra key. Drop it outside the house for another player to loot; + verify they have owner rights even after their invitation is removed. +5. Destroy one of two keys. Verify three seconds elapse and the house remains. + Destroy the last key and verify access ends with contents retained. +6. In a survival world, start destroying a key and die before completion. Verify + it remains on the corpse. Repeat with drop, disconnect, and world travel. +7. Test creator recovery before death-world destruction, including the replacement + survival gate. Confirm archived data is purged after destruction, and active + houses with another valid key remain accessible across hub switches. diff --git a/planning/SYSTEMS-ROADMAP.md b/planning/SYSTEMS-ROADMAP.md index b383055..88d9eb4 100644 --- a/planning/SYSTEMS-ROADMAP.md +++ b/planning/SYSTEMS-ROADMAP.md @@ -562,7 +562,7 @@ milestones, not time estimates or new tested-capacity claims. | 5. Playable hub travel | Hub instances/switching, survival-world entry, escape items, Harbinger victory portal | Implemented; [manual handoff](../docs/MILESTONE-5.md): admission, escape restrictions, single character/item ownership, hub XP restrictions | | 6. Crafting and item quality | Recipe discovery, nine professions, failure/refund curves, random stats, crafter provenance, hub crafting | Implemented; [manual handoff](../docs/MILESTONE-6.md): valid-recipe feedback, resource use, quality/provenance, discoveries without hub XP | | 7. Spells, abilities, resurrection | Spell books/ranks/unlocks, weapon proficiency, corpse revival, bindings/controller targeting | Implemented; [manual handoff](../docs/MILESTONE-7.md): useful-action XP, healing/auras, revival finality, costs, and controls | -| 8. Building and housing | Destructible world structures, house instances, keys, permissions, storage, timed deletion/recovery | In progress: [8a building checkpoint](../docs/MILESTONE-8A.md); housing access/recovery decisions and implementation remain | +| 8. Building and housing | Destructible world structures, house instances, keys, permissions, storage, timed deletion/recovery | In progress: [8a building](../docs/MILESTONE-8A.md) and [8b housing controls/lifecycle](../docs/MILESTONE-8B.md); walkable interiors and controller placement remain | | 9. Cosmetics and customization | Simple character creator, account cosmetic application, furniture exceptions, presentation polish | Entitlements, appearance compatibility, drop versus placement/push/pickup | | 10. Dungeons and social expansion | Portal instances and lifecycle; separately scoped communication, trade, parties, guilds | Instance population/reset/exit rules, item exchange, membership and permissions | @@ -581,8 +581,9 @@ Milestone 1 defines ownership boundaries; it does not implement every later syst Milestone 3 terrain informs milestone 4 navigation. Combat exposes the obstacle hooks that milestone 8 structures use. Cosmetic account boundaries are designed in milestone 1, while player/furniture application follows the rig and housing work. -Resurrection's first playable defaults are recorded in milestone 7. Housing still -requires its remaining lifecycle details before implementation. +Resurrection's first playable defaults are recorded in milestone 7. Housing's +provisional recovery, invitation, and interruption rules are recorded in milestone +8b, with the user's three-second key action and six guest permissions implemented. At the end of **every milestone**: @@ -601,10 +602,11 @@ planning update itself does not start milestone implementation. First discussion, because these affect the architecture: -1. Housing: key-action interruption, original-creator recovery identity, exceptional - death-world cases, eligibility, and occupant handling after deletion remain open. - Key destruction takes three seconds. Guest permissions have owner/co-owner-managed - baseline settings and per-person overrides; recovery retention remains settled. +1. Housing: playtest milestone 8b's provisional invitation/issuance distinctions, + replacement survival gate, interruption behavior, and hub return on eviction. + Unknown death worlds retain data; retiring inaccessible keys and walkable + interiors remain to scope. The three-second key action, baseline guest + permissions, per-person overrides, and recovery retention are implemented. 2. Resurrection: playtest milestone 7's provisional consent, costs/pools, and instant activation. Extra limits and corpse handling during dungeon closure/reset remain open. 3. Combat: action aiming model, controller targeting, friendly fire, ranged projectiles? diff --git a/planning/VISION.md b/planning/VISION.md index 0971701..0035231 100644 --- a/planning/VISION.md +++ b/planning/VISION.md @@ -178,8 +178,9 @@ Tracked across: ## Backlog - Milestone 8a adds persistent destructible world structures, craftable kits, - Control definitions, placement checks, and collision. Housing/key lifecycle work - remains pending; see `docs/MILESTONE-8A.md` for the checkpoint and open decisions. + Control definitions, placement checks, and collision. Milestone 8b adds housing + floor-plan controls, keys, permissions, storage, and recovery; walkable interiors + remain. See `docs/MILESTONE-8B.md` for provisional rules and manual tests. - Milestone 7 implements spell books/ranks/unlocks, weapon proficiency and abilities, healing/auras, bindable keyboard/controller slots, and durable corpse revival. See `docs/MILESTONE-7.md` for defaults, effect limits, and the manual handoff. diff --git a/schemas/protocol.json b/schemas/protocol.json index 05134fe..8224285 100644 --- a/schemas/protocol.json +++ b/schemas/protocol.json @@ -27,6 +27,12 @@ }, "craftResult": { "$ref": "#/definitions/CraftResult" + }, + "houseState": { + "$ref": "#/definitions/HouseState" + }, + "houseRequest": { + "$ref": "#/definitions/HouseRequest" } }, "required": [ @@ -71,7 +77,8 @@ "attackId": {"type": "string"}, "craftPool": {"type": "array", "items": {"$ref": "#/definitions/CraftStat"}}, "craftRolls": {"type": "integer"}, - "weaponType": {"type": "string"} + "weaponType": {"type": "string"}, + "furniture": {"$ref": "#/definitions/FurnitureProfile"} }, "required": ["id", "name", "description", "slot", "weight", "dropChance", "requirements", "modifiers"] }, @@ -96,7 +103,8 @@ "combat": {"$ref": "#/definitions/CombatContent"}, "crafting": {"$ref": "#/definitions/CraftingContent"}, "powers": {"$ref": "#/definitions/PowerContent"}, - "building": {"$ref": "#/definitions/BuildingContent"} + "building": {"$ref": "#/definitions/BuildingContent"}, + "housingVersion": {"type": "integer"} }, "required": ["version", "titles", "items", "stats"] }, @@ -160,7 +168,8 @@ "attackId": {"type": "string"}, "craftPool": {"type": "array", "items": {"$ref": "#/definitions/CraftStat"}}, "craftRolls": {"type": "integer"}, - "weaponType": {"type": "string"} + "weaponType": {"type": "string"}, + "furniture": {"$ref": "#/definitions/FurnitureProfile"} }, "required": ["name", "description", "slot", "weight", "dropChance", "requirements", "modifiers"] }, @@ -250,7 +259,9 @@ "craftedStacks": {"type": "array", "items": {"$ref": "#/definitions/CraftedStack"}}, "powers": {"type": "object", "additionalProperties": {"$ref": "#/definitions/LearnedPower"}}, "weapons": {"type": "object", "additionalProperties": {"$ref": "#/definitions/WeaponProgress"}}, - "casting": {"type": "string"} + "casting": {"type": "string"}, + "houseId": {"type": "string"}, + "destroyKey": {"$ref": "#/definitions/KeyDestruction"} }, "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"] }, @@ -294,7 +305,9 @@ "requirementMessage": {"type": "string"}, "attack": {"$ref": "#/definitions/CombatAttack"}, "provenance": {"$ref": "#/definitions/CraftProvenance"}, - "weaponType": {"type": "string"} + "weaponType": {"type": "string"}, + "furniture": {"$ref": "#/definitions/FurnitureProfile"}, + "houseId": {"type": "string"} }, "required": ["id", "definitionId", "name", "description", "slot", "weight", "requirements", "modifiers", "equippable", "requirementMessage"] }, @@ -980,6 +993,101 @@ "maxSlope": {"type": "number"} }, "required": ["definitions", "maxStructures", "range", "protectedRadius", "maxSlope"] + }, + "FurnitureProfile": { + "type": "object", "additionalProperties": false, + "properties": { + "width": {"type": "number"}, + "depth": {"type": "number"}, + "container": {"type": "boolean"} + }, + "required": ["width", "depth", "container"] + }, + "KeyDestruction": { + "type": "object", "additionalProperties": false, + "properties": { + "keyId": {"type": "string"}, + "finishesAt": {"type": "number"} + }, + "required": ["keyId", "finishesAt"] + }, + "HouseInventory": { + "type": "object", "additionalProperties": false, + "properties": { + "inventory": {"type": "object", "additionalProperties": {"type": "integer"}}, + "items": {"type": "array", "items": {"$ref": "#/definitions/ItemInstance"}}, + "craftedStacks": {"type": "array", "items": {"$ref": "#/definitions/CraftedStack"}}, + "stackNames": {"type": "object", "additionalProperties": {"type": "string"}} + }, + "required": ["inventory", "items", "craftedStacks", "stackNames"] + }, + "HouseFurniture": { + "type": "object", "additionalProperties": false, + "properties": { + "item": {"$ref": "#/definitions/ItemInstance"}, + "x": {"type": "number"}, + "z": {"type": "number"}, + "contents": {"$ref": "#/definitions/HouseInventory"} + }, + "required": ["item", "x", "z", "contents"] + }, + "House": { + "type": "object", "additionalProperties": false, + "properties": { + "id": {"type": "string"}, + "name": {"type": "string"}, + "state": {"type": "string"}, + "revision": {"type": "integer"}, + "size": {"type": "number"}, + "permissions": {"type": "object", "additionalProperties": {"type": "boolean"}}, + "overrides": {"type": "object", "additionalProperties": {"type": "object", "additionalProperties": {"type": "boolean"}}}, + "roles": {"type": "object", "additionalProperties": {"type": "string"}}, + "furniture": {"type": "object", "additionalProperties": {"$ref": "#/definitions/HouseFurniture"}}, + "floor": {"$ref": "#/definitions/HouseInventory"} + }, + "required": ["id", "name", "state", "revision", "size", "permissions", "overrides", "roles", "furniture", "floor"] + }, + "HouseSummary": { + "type": "object", "additionalProperties": false, + "properties": { + "id": {"type": "string"}, + "name": {"type": "string"}, + "state": {"type": "string"}, + "role": {"type": "string"}, + "creator": {"type": "boolean"}, + "recoveryWorld": {"type": "string"}, + "keys": {"type": "integer"} + }, + "required": ["id", "name", "state", "role", "creator", "recoveryWorld", "keys"] + }, + "HouseRequest": { + "type": "object", "additionalProperties": false, + "properties": { + "requestId": {"type": "string"}, + "op": {"type": "string"}, + "houseId": {"type": "string"}, + "target": {"type": "string"}, + "item": {"type": "string"}, + "quantity": {"type": "integer"}, + "x": {"type": "number"}, + "z": {"type": "number"}, + "role": {"type": "string"}, + "name": {"type": "string"}, + "permissions": {"type": "object", "additionalProperties": {"type": "boolean"}}, + "revision": {"type": "integer"} + }, + "required": ["requestId", "op"] + }, + "HouseState": { + "type": "object", "additionalProperties": false, + "properties": { + "houses": {"type": "array", "items": {"$ref": "#/definitions/HouseSummary"}}, + "room": {"$ref": "#/definitions/House"}, + "role": {"type": "string"}, + "effective": {"type": "object", "additionalProperties": {"type": "boolean"}}, + "people": {"type": "array", "items": {"$ref": "#/definitions/Entity"}} + }, + "required": ["houses", "role", "effective", "people"] } } } diff --git a/server/content/balance.yaml b/server/content/balance.yaml index 4f61f01..0243b74 100644 --- a/server/content/balance.yaml +++ b/server/content/balance.yaml @@ -214,6 +214,8 @@ items: modifiers: [{ stat: meleeDamage, flat: 14, percent: 0 }] # Milestone 6 provisional crafting tuning. Percentages use 0-100. + - {"id": "storage_chest", "name": "Storage chest", "description": "Furniture for a house.", "slot": "bag", "weight": 5, "dropChance": 0, "requirements": {"level": 1, "stats": {}, "titles": []}, "modifiers": [], "furniture": {"width": 2, "depth": 1, "container": true}} + - {"id": "house_table", "name": "House table", "description": "Furniture for a house.", "slot": "bag", "weight": 5, "dropChance": 0, "requirements": {"level": 1, "stats": {}, "titles": []}, "modifiers": [], "furniture": {"width": 2, "depth": 2, "container": false}} 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: @@ -258,3 +260,5 @@ building: - {"id": "timber_wall", "name": "Timber wall", "description": "A persistent, destructible timber wall.", "model": "wall", "width": 4, "depth": 1, "height": 2, "hp": 250, "profession": "builder", "level": 1} - {"id": "camp_platform", "name": "Camp platform", "description": "A persistent, destructible camp platform.", "model": "camp", "width": 4, "depth": 4, "height": 0.75, "hp": 300, "profession": "builder", "level": 1} - {"id": "fort_block", "name": "Fort block", "description": "A persistent, destructible fort block.", "model": "fort", "width": 6, "depth": 3, "height": 3, "hp": 800, "profession": "builder", "level": 5} + +housing: { roomSize: 12, maxFurniture: 64, maxItems: 256, maxGuests: 64, keySeconds: 3 } diff --git a/server/content/content.go b/server/content/content.go index 389d70d..0a20546 100644 --- a/server/content/content.go +++ b/server/content/content.go @@ -19,6 +19,7 @@ type Recipe struct { } type Balance struct { + Housing *HousingRules `yaml:"housing"` Building *BuildingContent `yaml:"building"` Powers *PowerContent `yaml:"powers"` Crafting *CraftingContent `yaml:"crafting"` @@ -83,6 +84,11 @@ func Parse(data []byte) (Balance, error) { return b, b.Validate() } func (b Balance) Validate() error { + if b.Housing != nil { + if e := b.Housing.Validate(); e != nil { + return e + } + } if e := (Catalog{Building: b.Building, Crafting: b.Crafting, Items: b.Items}).validateBuilding(); e != nil { return e } diff --git a/server/content/housing.go b/server/content/housing.go new file mode 100644 index 0000000..999f1ba --- /dev/null +++ b/server/content/housing.go @@ -0,0 +1,52 @@ +package content + +import "fmt" + +type FurnitureProfile struct { + Width float64 `json:"width" yaml:"width"` + Depth float64 `json:"depth" yaml:"depth"` + Container bool `json:"container" yaml:"container"` +} + +func (f FurnitureProfile) Validate() error { + if !finiteRange(f.Width, .5, 4) || !finiteRange(f.Depth, .5, 4) { + return fmt.Errorf("invalid furniture footprint") + } + return nil +} + +type HousingRules struct { + RoomSize float64 `yaml:"roomSize"` + MaxFurniture int `yaml:"maxFurniture"` + MaxItems int `yaml:"maxItems"` + MaxGuests int `yaml:"maxGuests"` + KeySeconds float64 `yaml:"keySeconds"` +} + +func (r HousingRules) Validate() error { + if !finiteRange(r.RoomSize, 8, 32) || r.MaxFurniture < 1 || r.MaxFurniture > 128 || r.MaxItems < 1 || r.MaxItems > 512 || r.MaxGuests < 1 || r.MaxGuests > 128 || r.KeySeconds != 3 { + return fmt.Errorf("invalid housing rules") + } + return nil +} +func (c *Catalog) RestoreFurniture(b Balance) { + if c.HousingVersion != 0 { + return + } + c.Items = append([]ItemDefinition{}, c.Items...) + for _, v := range b.Items { + if v.Furniture == nil { + continue + } + found := false + for _, i := range c.Items { + if i.ID == v.ID { + found = true + } + } + if !found { + c.Items = append(c.Items, v) + } + } + c.HousingVersion = 1 +} diff --git a/server/content/stats.go b/server/content/stats.go index 450371d..954c133 100644 --- a/server/content/stats.go +++ b/server/content/stats.go @@ -35,20 +35,22 @@ type ItemRequirements struct { Titles []string `json:"titles" yaml:"titles"` } type ItemDefinition struct { - WeaponType string `json:"weaponType,omitempty" yaml:"weaponType"` - CraftPool []CraftStat `json:"craftPool,omitempty" yaml:"craftPool"` - CraftRolls int64 `json:"craftRolls,omitempty" yaml:"craftRolls"` - AttackID string `json:"attackId,omitempty" yaml:"attackId"` - ID string `json:"id" yaml:"id"` - Name string `json:"name" yaml:"name"` - Description string `json:"description" yaml:"description"` - Slot string `json:"slot" yaml:"slot"` - Weight float64 `json:"weight" yaml:"weight"` - DropChance float64 `json:"dropChance" yaml:"dropChance"` - Requirements ItemRequirements `json:"requirements" yaml:"requirements"` - Modifiers []StatModifier `json:"modifiers" yaml:"modifiers"` + Furniture *FurnitureProfile `json:"furniture,omitempty" yaml:"furniture"` + WeaponType string `json:"weaponType,omitempty" yaml:"weaponType"` + CraftPool []CraftStat `json:"craftPool,omitempty" yaml:"craftPool"` + CraftRolls int64 `json:"craftRolls,omitempty" yaml:"craftRolls"` + AttackID string `json:"attackId,omitempty" yaml:"attackId"` + ID string `json:"id" yaml:"id"` + Name string `json:"name" yaml:"name"` + Description string `json:"description" yaml:"description"` + Slot string `json:"slot" yaml:"slot"` + Weight float64 `json:"weight" yaml:"weight"` + DropChance float64 `json:"dropChance" yaml:"dropChance"` + Requirements ItemRequirements `json:"requirements" yaml:"requirements"` + Modifiers []StatModifier `json:"modifiers" yaml:"modifiers"` } type Catalog struct { + HousingVersion int `json:"housingVersion,omitempty"` Building *BuildingContent `json:"building,omitempty"` Powers *PowerContent `json:"powers,omitempty"` Crafting *CraftingContent `json:"crafting,omitempty"` @@ -105,6 +107,14 @@ 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 item.Furniture != nil { + if item.Slot != "bag" { + return fmt.Errorf("furniture must use bag slot") + } + if e := item.Furniture.Validate(); e != nil { + return e + } + } if err := ValidateCraftPool(item); err != nil { return err } @@ -219,5 +229,5 @@ func DefaultCatalog() (Catalog, error) { if err != nil { return Catalog{}, err } - return Catalog{Building: b.Building, Powers: b.Powers, Crafting: b.Crafting, Combat: b.Combat, Gathering: b.Gathering, Version: 1, Titles: b.Titles, Items: b.Items, Stats: *b.Stats}, nil + return Catalog{HousingVersion: 1, Building: b.Building, Powers: b.Powers, Crafting: b.Crafting, Combat: b.Combat, Gathering: b.Gathering, Version: 1, Titles: b.Titles, Items: b.Items, Stats: *b.Stats}, nil } diff --git a/server/internal/game/admin_content.go b/server/internal/game/admin_content.go index ad47da0..9659c0d 100644 --- a/server/internal/game/admin_content.go +++ b/server/internal/game/admin_content.go @@ -75,6 +75,9 @@ func (w *World) AdminItems(c *Character, op, value string) error { } return w.grantItems(c, id, n) } + if item := ownedItem(c, id); item != nil && item.HouseID != nil { + return errors.New("house keys require the holder's three-second destruction action") + } if op != "remove-item" { return errors.New("unknown item operation") } diff --git a/server/internal/game/combat.go b/server/internal/game/combat.go index cf2856d..7c74755 100644 --- a/server/internal/game/combat.go +++ b/server/internal/game/combat.go @@ -66,7 +66,7 @@ func (w *World) sourceActive(source string, player bool) bool { } if player { c := w.Characters[source] - return c != nil && c.View.Entity.State == "alive" && !c.Sheltered + return c != nil && HouseID(c) == "" && c.View.Entity.State == "alive" && !c.Sheltered } m := w.Mobs[source] return m != nil && m.Entity.HP > 0 @@ -75,7 +75,7 @@ func (w *World) combatTargets(player bool, effect string) []p.Entity { out := []p.Entity{} if (player && effect == "heal") || (!player && effect == "damage") { for _, c := range w.orderedCharacters() { - if c.Online && c.View.Entity.State == "alive" && !c.Sheltered { + if HouseID(c) == "" && c.Online && c.View.Entity.State == "alive" && !c.Sheltered { out = append(out, c.View.Entity) } } diff --git a/server/internal/game/crafting.go b/server/internal/game/crafting.go index 3573632..f253a6c 100644 --- a/server/internal/game/crafting.go +++ b/server/internal/game/crafting.go @@ -145,7 +145,7 @@ func (w *World) CraftProfessions(c *Character) []p.CraftProgress { // 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") { + if c == nil || HouseID(c) != "" || !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 diff --git a/server/internal/game/equipment.go b/server/internal/game/equipment.go index 470d442..f1a409b 100644 --- a/server/internal/game/equipment.go +++ b/server/internal/game/equipment.go @@ -19,6 +19,9 @@ func validEquipmentSlot(slot string) bool { return false } func itemFitsSlot(item p.ItemInstance, slot string) bool { + if item.HouseID != nil || item.Furniture != nil { + return false + } if !validEquipmentSlot(slot) { return false } @@ -58,6 +61,10 @@ func (w *World) addInventoryItems(inventory *map[string]int64, items *[]p.ItemIn for n := int64(0); n < quantity; n++ { item := p.ItemInstance{ID: ID(), DefinitionID: definition.ID, Name: definition.Name, Description: definition.Description, Slot: definition.Slot, Weight: definition.Weight, WeaponType: stringPtr(definition.WeaponType), Requirements: p.ItemRequirements{Level: definition.Requirements.Level, Stats: map[string]float64{}, Titles: append([]string{}, definition.Requirements.Titles...)}, Modifiers: []p.StatModifier{}} + if definition.Furniture != nil { + f := definition.Furniture + item.Furniture = &p.FurnitureProfile{Width: f.Width, Depth: f.Depth, Container: f.Container} + } for stat, value := range definition.Requirements.Stats { item.Requirements.Stats[stat] = value } @@ -133,6 +140,15 @@ func validateOwnedItems(items []p.ItemInstance, seen map[string]bool) error { return errors.New("invalid or duplicate persisted equipment") } seen[item.ID] = true + if item.Furniture != nil { + f := item.Furniture + if math.IsNaN(f.Width) || math.IsNaN(f.Depth) || f.Width < .5 || f.Width > 4 || f.Depth < .5 || f.Depth > 4 { + return errors.New("invalid saved furniture") + } + } + if item.HouseID != nil && (len(*item.HouseID) != 32 || item.DefinitionID != "house_key") { + return errors.New("invalid saved house key") + } for _, value := range item.Requirements.Stats { if math.IsNaN(value) || math.IsInf(value, 0) || value < 0 { return errors.New("invalid equipment requirement") @@ -198,6 +214,9 @@ func (w *World) restoreCorpseEquipment() error { return nil } func equipmentRequirementError(c *Character, item p.ItemInstance, stats map[string]p.StatValue) error { + if item.HouseID != nil || item.Furniture != nil { + return errors.New("house items cannot be equipped") + } if c.View.Level < item.Requirements.Level { return fmt.Errorf("requires level %d", item.Requirements.Level) } @@ -291,6 +310,9 @@ func (w *World) dropItem(c *Character, target string) error { index := -1 for i, item := range c.View.Items { if item.ID == target { + if c.View.DestroyKey != nil && c.View.DestroyKey.KeyID == target { + c.View.DestroyKey = nil + } index = i name = item.Name break diff --git a/server/internal/game/housing.go b/server/internal/game/housing.go new file mode 100644 index 0000000..36e455a --- /dev/null +++ b/server/internal/game/housing.go @@ -0,0 +1,132 @@ +package game + +import ( + "aeternalis/server/content" + p "aeternalis/server/internal/protocol" + "errors" + "math" +) + +var HousePermissions = []string{"moveFurniture", "openFurniture", "placeFurniture", "depositItems", "pickupItems", "dropItems"} + +func (w *World) NowSeconds() float64 { return float64(w.now.UnixMilli()) / 1000 } +func HouseID(c *Character) string { + if c == nil || c.View.HouseID == nil { + return "" + } + return *c.View.HouseID +} +func LeaveHouse(c *Character) { c.View.HouseID = nil; c.MoveX = 0; c.MoveZ = 0 } +func (w *World) restoreHousing() error { + if w.Balance.Housing == nil { + b, e := content.Load() + if e != nil { + return e + } + w.Balance.Housing = b.Housing + cat := content.Catalog{Items: w.Balance.Items} + cat.RestoreFurniture(b) + w.Balance.Items = cat.Items + } + for _, c := range w.Characters { + LeaveHouse(c) + c.View.DestroyKey = nil + } + return nil +} +func (w *World) updateHousingActions() { + for _, c := range w.Characters { + if c.View.DestroyKey != nil { + key := ownedItem(c, c.View.DestroyKey.KeyID) + if !c.Online || c.View.RemainingSeconds <= 0 || c.Sheltered || c.View.Entity.State == "dead" || key == nil || key.HouseID == nil { + c.View.DestroyKey = nil + w.dirty = true + } else if w.NowSeconds() >= c.View.DestroyKey.FinishesAt { + w.dirty = true + } + } + if HouseID(c) != "" && (!c.Online || c.View.Entity.State == "dead" || c.View.RemainingSeconds <= 0) { + LeaveHouse(c) + w.dirty = true + } + } +} +func EmptyHouseInventory() p.HouseInventory { + return p.HouseInventory{Inventory: map[string]int64{}, Items: []p.ItemInstance{}, CraftedStacks: []p.CraftedStack{}, StackNames: map[string]string{}} +} +func ValidateHouseInventory(v p.HouseInventory, seen map[string]bool) error { + if len(v.Inventory) > 512 || len(v.Items) > 512 || len(v.StackNames) > 1024 { + return errors.New("house inventory limit") + } + for _, n := range v.Inventory { + if n < 0 || n > 1000000000000 { + return errors.New("invalid stored quantity") + } + } + if e := validateOwnedItems(v.Items, seen); e != nil { + return e + } + return ValidateCraftedStacks(v.Inventory, v.CraftedStacks, seen) +} +func HouseInventoryOf(c *Character) p.HouseInventory { + return p.HouseInventory{Inventory: c.View.Inventory, Items: c.View.Items, CraftedStacks: c.View.CraftedStacks, StackNames: c.View.StackNames} +} +func SetHouseInventory(c *Character, v p.HouseInventory) { + c.View.Inventory = v.Inventory + c.View.Items = v.Items + c.View.CraftedStacks = v.CraftedStacks + c.View.StackNames = v.StackNames +} + +// Move one unique instance or a bounded stack quantity; provenance travels with it. +// Call on staged/transaction-owned inventories and validate before publishing. +func MoveHouseItem(from, to *p.HouseInventory, id string, quantity int64) error { + if quantity < 1 || quantity > 1000 || len(to.Items) >= 512 || len(to.Inventory) >= 512 { + return errors.New("invalid quantity or destination full") + } + for i, item := range from.Items { + if item.ID == id { + if quantity != 1 { + return errors.New("unique item quantity must be one") + } + to.Items = append(to.Items, item) + from.Items = append(from.Items[:i:i], from.Items[i+1:]...) + return nil + } + } + if from.Inventory[id] < quantity || to.Inventory[id] > 1000000000000-quantity { + return errors.New("item quantity unavailable") + } + temp := &Character{} + SetHouseInventory(temp, *from) + batches := TakeStack(temp, id, quantity) + *from = HouseInventoryOf(temp) + if to.Inventory == nil { + to.Inventory = map[string]int64{} + } + if to.StackNames == nil { + to.StackNames = map[string]string{} + } + to.Inventory[id] += quantity + to.CraftedStacks = append(to.CraftedStacks, batches...) + if name := from.StackNames[id]; name != "" { + to.StackNames[id] = name + } + return nil +} +func FurnitureFits(h p.House, id string, item p.ItemInstance, x, z float64) bool { + f := item.Furniture + if f == nil || math.IsNaN(x) || math.IsNaN(z) || math.IsInf(x, 0) || math.IsInf(z, 0) || math.Abs(x)+f.Width/2 > h.Size/2 || math.Abs(z)+f.Depth/2 > h.Size/2 { + return false + } + for other, v := range h.Furniture { + if other == id { + continue + } + g := v.Item.Furniture + if g != nil && math.Abs(x-v.X) < (g.Width+f.Width)/2 && math.Abs(z-v.Z) < (g.Depth+f.Depth)/2 { + return false + } + } + return true +} diff --git a/server/internal/game/housing_test.go b/server/internal/game/housing_test.go new file mode 100644 index 0000000..b78ff79 --- /dev/null +++ b/server/internal/game/housing_test.go @@ -0,0 +1,72 @@ +package game + +import ( + "aeternalis/server/content" + p "aeternalis/server/internal/protocol" + "encoding/json" + "math" + "testing" + "time" +) + +func TestHouseInventoryPreservesCraftedProvenance(t *testing.T) { + b, _ := content.Load() + w := New("craft-origin", 1, time.Now(), b) + c, _ := w.Join("crafter", "Crafter") + c.View.Inventory["bandage"] = 5 + provenance := p.CraftProvenance{At: 1, CharacterID: c.View.Entity.ID, CrafterName: "Crafter", Level: 1, Profession: "alchemist", RecipeID: "recipe_bandage", RecipeRevision: 1, WorldID: w.ID} + c.View.CraftedStacks = []p.CraftedStack{{ID: ID(), Item: "bandage", Quantity: 5, Provenance: provenance}} + from, to := HouseInventoryOf(c), EmptyHouseInventory() + if e := MoveHouseItem(&from, &to, "bandage", 2); e != nil { + t.Fatal(e) + } + if from.Inventory["bandage"] != 3 || to.Inventory["bandage"] != 2 || to.CraftedStacks[0].Provenance != provenance || from.CraftedStacks[0].ID == to.CraftedStacks[0].ID { + t.Fatal("split damaged provenance or duplicated batch ID") + } + seen := map[string]bool{} + if e := ValidateHouseInventory(from, seen); e != nil { + t.Fatal(e) + } + if e := ValidateHouseInventory(to, seen); e != nil { + t.Fatal(e) + } + if e := w.AdminItems(c, "grant-item", "storage_chest:1"); e != nil { + t.Fatal(e) + } + item := c.View.Items[len(c.View.Items)-1] + h := p.House{Size: 12, Furniture: map[string]p.HouseFurniture{item.ID: {Item: item, X: 0, Z: 0}}} + if FurnitureFits(h, "", item, 0, 0) || FurnitureFits(h, "", item, 6, 0) || FurnitureFits(h, "", item, math.NaN(), 0) || !FurnitureFits(h, item.ID, item, 3, 0) { + t.Fatal("furniture collision validation") + } + before, _ := json.Marshal(to) + if e := MoveHouseItem(&from, &to, "bandage", 999); e == nil { + t.Fatal("overdraw accepted") + } + after, _ := json.Marshal(to) + if string(before) != string(after) { + t.Fatal("overdraw changed destination") + } +} +func TestHousingDailyLimitAndNoMovement(t *testing.T) { + b, _ := content.Load() + now := time.Date(2026, 9, 10, 12, 0, 0, 0, time.UTC) + w := New("daily-house", 1, now, b) + c, _ := w.Join("owner", "Owner") + _ = w.Connect(c.View.Entity.ID) + w.Kind = "hub" + w.Phase = "hub" + id := ID() + c.View.HouseID = &id + before := c.View.Entity.Position + c.MoveX = 1 + c.LastMove = now + c.DailySeconds = b.DailyPlaySeconds - 1 + w.Advance(now.Add(500*time.Millisecond), .5) + if c.View.Entity.Position != before || c.DailySeconds != b.DailyPlaySeconds-.5 { + t.Fatal("housing moved avatar or stopped daily budget") + } + w.Advance(now.Add(2*time.Second), 1.5) + if c.Online || c.View.HouseID != nil || c.View.RemainingSeconds != 0 { + t.Fatal("daily cap did not exit housing") + } +} diff --git a/server/internal/game/travel.go b/server/internal/game/travel.go index 9827440..a21cc58 100644 --- a/server/internal/game/travel.go +++ b/server/internal/game/travel.go @@ -13,6 +13,9 @@ func (w *World) PortalPosition() p.Vec3 { return w.terrain.Position(0, 0) } // Escape is an explicit one-item action. It grants no victory/survival credit. func (w *World) Departure(c *Character, route string) error { + if HouseID(c) != "" { + return errors.New("leave the house before traveling") + } if c == nil || !c.Online || c.Sheltered || c.View.RemainingSeconds <= 0 || (c.View.Entity.State != "alive" && c.View.Entity.State != "eligible") { return errors.New("character cannot travel") } diff --git a/server/internal/game/world.go b/server/internal/game/world.go index e052423..c0af356 100644 --- a/server/internal/game/world.go +++ b/server/internal/game/world.go @@ -190,6 +190,9 @@ func (w *World) Restore(now time.Time) error { } w.dirty = true } + if e := w.restoreHousing(); e != nil { + return e + } if e := w.restoreBuilding(); e != nil { return e } @@ -467,6 +470,10 @@ func (w *World) Connect(id string) error { return nil } func (w *World) Disconnect(id string) { + if c := w.Characters[id]; c != nil { + c.View.DestroyKey = nil + LeaveHouse(c) + } if c := w.Characters[id]; c != nil { c.Online = false c.MoveX = 0 @@ -517,6 +524,9 @@ func (w *World) Intent(id string, i p.Intent) error { return errors.New("invalid intent") } c.View.ACK = i.Seq + if HouseID(c) != "" { + return errors.New("leave the house to use world actions") + } if c.Sheltered && ((i.Op == "move" && (i.X != 0 || i.Z != 0)) || (i.Op != "move" && i.Op != "heal" && i.Op != "allocate-stat" && i.Op != "choose-vital" && i.Op != "equip" && i.Op != "unequip" && i.Op != "drop")) { c.Sheltered = false w.dirty = true @@ -622,6 +632,8 @@ func (w *World) kill(c *Character, reason string) { e.Position = w.terrain.Position(e.Position.X, e.Position.Z) c.View.Entity.Position = e.Position c.DeathCount++ + c.View.DestroyKey = nil + LeaveHouse(c) c.PendingCast = nil c.RevivalAllowed = false e.ID = "corpse:" + e.ID + ":" + ID() @@ -776,7 +788,9 @@ func (w *World) Advance(now time.Time, dt float64) { c.MoveX = 0 c.MoveZ = 0 } - w.moveCharacter(c, dt) + if HouseID(c) == "" { + w.moveCharacter(c, dt) + } for _, ch := range w.neighbors(c.View.Entity.Position) { active[ch.Key] = true if !w.IsHub() && w.Phase != "won" { @@ -795,6 +809,7 @@ func (w *World) Advance(now time.Time, dt float64) { if !w.IsHub() && w.Phase != "won" { w.updateMobs(active, dt) } + w.updateHousingActions() w.updatePowers() if w.Phase != "won" { w.updateCombat(dt) @@ -892,7 +907,7 @@ func (w *World) Snapshot(id string, known map[string]bool) p.Snapshot { } } for _, other := range w.Characters { - if other.View.Entity.ID != id && other.Online && other.View.Entity.State != "dead" && visible(other.View.Entity.Position) { + if HouseID(other) == "" && other.View.Entity.ID != id && other.Online && other.View.Entity.State != "dead" && visible(other.View.Entity.Position) { s.Entities = append(s.Entities, other.View.Entity) } } diff --git a/server/internal/protocol/generated.go b/server/internal/protocol/generated.go index 0b875cf..160e93f 100644 --- a/server/internal/protocol/generated.go +++ b/server/internal/protocol/generated.go @@ -8,6 +8,8 @@ type Protocol struct { CatalogResult *ContentResult `json:"catalogResult,omitempty"` CraftRequest *CraftRequest `json:"craftRequest,omitempty"` CraftResult *CraftResult `json:"craftResult,omitempty"` + HouseRequest *HouseRequest `json:"houseRequest,omitempty"` + HouseState *HouseState `json:"houseState,omitempty"` Intent Intent `json:"intent"` Snapshot Snapshot `json:"snapshot"` } @@ -18,6 +20,7 @@ type ContentCatalog struct { Crafting *CraftingContent `json:"crafting,omitempty"` EffectSets []EffectSet `json:"effectSets,omitempty"` Gathering *GatheringContent `json:"gathering,omitempty"` + HousingVersion *int64 `json:"housingVersion,omitempty"` Items []ItemDefinition `json:"items"` Powers *PowerContent `json:"powers,omitempty"` RequirementSets []RequirementSet `json:"requirementSets,omitempty"` @@ -228,18 +231,19 @@ type ResourceDefinition struct { } 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"` - Modifiers []StatModifier `json:"modifiers"` - Name string `json:"name"` - Requirements ItemRequirements `json:"requirements"` - Slot string `json:"slot"` - WeaponType *string `json:"weaponType,omitempty"` - Weight float64 `json:"weight"` + AttackID *string `json:"attackId,omitempty"` + CraftPool []CraftStat `json:"craftPool,omitempty"` + CraftRolls *int64 `json:"craftRolls,omitempty"` + Description string `json:"description"` + DropChance float64 `json:"dropChance"` + Furniture *FurnitureProfile `json:"furniture,omitempty"` + ID string `json:"id"` + Modifiers []StatModifier `json:"modifiers"` + Name string `json:"name"` + Requirements ItemRequirements `json:"requirements"` + Slot string `json:"slot"` + WeaponType *string `json:"weaponType,omitempty"` + Weight float64 `json:"weight"` } type CraftStat struct { @@ -250,6 +254,12 @@ type CraftStat struct { Weight float64 `json:"weight"` } +type FurnitureProfile struct { + Container bool `json:"container"` + Depth float64 `json:"depth"` + Width float64 `json:"width"` +} + type ItemRequirements struct { Level int64 `json:"level"` Stats map[string]float64 `json:"stats"` @@ -438,18 +448,19 @@ type EffectSetDraft struct { } 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"` - Modifiers []StatModifier `json:"modifiers"` - Name string `json:"name"` - Requirements ItemRequirements `json:"requirements"` - Slot string `json:"slot"` - WeaponType *string `json:"weaponType,omitempty"` - Weight float64 `json:"weight"` + AttackID *string `json:"attackId,omitempty"` + CraftPool []CraftStat `json:"craftPool,omitempty"` + CraftRolls *int64 `json:"craftRolls,omitempty"` + Description string `json:"description"` + DropChance float64 `json:"dropChance"` + Furniture *FurnitureProfile `json:"furniture,omitempty"` + ID *string `json:"id,omitempty"` + Modifiers []StatModifier `json:"modifiers"` + Name string `json:"name"` + Requirements ItemRequirements `json:"requirements"` + Slot string `json:"slot"` + WeaponType *string `json:"weaponType,omitempty"` + Weight float64 `json:"weight"` } type LootTableDraft struct { @@ -580,6 +591,126 @@ type KnownRecipe struct { Recipe CraftRecipe `json:"recipe"` } +type HouseRequest struct { + HouseID *string `json:"houseId,omitempty"` + Item *string `json:"item,omitempty"` + Name *string `json:"name,omitempty"` + Op string `json:"op"` + Permissions map[string]bool `json:"permissions,omitempty"` + Quantity *int64 `json:"quantity,omitempty"` + RequestID string `json:"requestId"` + Revision *int64 `json:"revision,omitempty"` + Role *string `json:"role,omitempty"` + Target *string `json:"target,omitempty"` + X *float64 `json:"x,omitempty"` + Z *float64 `json:"z,omitempty"` +} + +type HouseState struct { + Effective map[string]bool `json:"effective"` + Houses []HouseSummary `json:"houses"` + People []Entity `json:"people"` + Role string `json:"role"` + Room *House `json:"room,omitempty"` +} + +type HouseSummary struct { + Creator bool `json:"creator"` + ID string `json:"id"` + Keys int64 `json:"keys"` + Name string `json:"name"` + RecoveryWorld string `json:"recoveryWorld"` + Role string `json:"role"` + State string `json:"state"` +} + +type Entity struct { + Depth *float64 `json:"depth,omitempty"` + HP float64 `json:"hp"` + Height *float64 `json:"height,omitempty"` + ID string `json:"id"` + Kind string `json:"kind"` + MaxHP float64 `json:"maxHp"` + Model *string `json:"model,omitempty"` + Name string `json:"name"` + Position Vec3 `json:"position"` + Radius *float64 `json:"radius,omitempty"` + RequiredLevel *int64 `json:"requiredLevel,omitempty"` + ResourceID *string `json:"resourceId,omitempty"` + SkillID *string `json:"skillId,omitempty"` + State string `json:"state"` + Width *float64 `json:"width,omitempty"` +} + +type Vec3 struct { + X float64 `json:"x"` + Y float64 `json:"y"` + Z float64 `json:"z"` +} + +type House struct { + Floor HouseInventory `json:"floor"` + Furniture map[string]HouseFurniture `json:"furniture"` + ID string `json:"id"` + Name string `json:"name"` + Overrides map[string]map[string]bool `json:"overrides"` + Permissions map[string]bool `json:"permissions"` + Revision int64 `json:"revision"` + Roles map[string]string `json:"roles"` + Size float64 `json:"size"` + State string `json:"state"` +} + +type HouseInventory struct { + CraftedStacks []CraftedStack `json:"craftedStacks"` + Inventory map[string]int64 `json:"inventory"` + Items []ItemInstance `json:"items"` + StackNames map[string]string `json:"stackNames"` +} + +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 ItemInstance struct { + Attack *CombatAttack `json:"attack,omitempty"` + DefinitionID string `json:"definitionId"` + Description string `json:"description"` + Equippable bool `json:"equippable"` + Furniture *FurnitureProfile `json:"furniture,omitempty"` + HouseID *string `json:"houseId,omitempty"` + 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"` + WeaponType *string `json:"weaponType,omitempty"` + Weight float64 `json:"weight"` +} + +type HouseFurniture struct { + Contents HouseInventory `json:"contents"` + Item ItemInstance `json:"item"` + X float64 `json:"x"` + Z float64 `json:"z"` +} + type Intent struct { Op string `json:"op"` Seq int64 `json:"seq"` @@ -616,30 +747,6 @@ type Chunk struct { Z int64 `json:"z"` } -type Entity struct { - Depth *float64 `json:"depth,omitempty"` - HP float64 `json:"hp"` - Height *float64 `json:"height,omitempty"` - ID string `json:"id"` - Kind string `json:"kind"` - MaxHP float64 `json:"maxHp"` - Model *string `json:"model,omitempty"` - Name string `json:"name"` - Position Vec3 `json:"position"` - Radius *float64 `json:"radius,omitempty"` - RequiredLevel *int64 `json:"requiredLevel,omitempty"` - ResourceID *string `json:"resourceId,omitempty"` - SkillID *string `json:"skillId,omitempty"` - State string `json:"state"` - Width *float64 `json:"width,omitempty"` -} - -type Vec3 struct { - X float64 `json:"x"` - Y float64 `json:"y"` - Z float64 `json:"z"` -} - type GatheringRisk struct { Allowed bool `json:"allowed"` Damage float64 `json:"damage"` @@ -669,6 +776,7 @@ type Character struct { Consumables []GatheringConsumable `json:"consumables,omitempty"` CraftedStacks []CraftedStack `json:"craftedStacks,omitempty"` Crafting map[string]CraftProgress `json:"crafting,omitempty"` + DestroyKey *KeyDestruction `json:"destroyKey,omitempty"` DiscoveredRecipes map[string]KnownRecipe `json:"discoveredRecipes,omitempty"` Entity Entity `json:"entity"` Equipment map[string]string `json:"equipment"` @@ -679,6 +787,7 @@ type Character struct { GatheringEffects []TimedGatheringEffect `json:"gatheringEffects,omitempty"` HasKeystone bool `json:"hasKeystone"` HealthChoices int64 `json:"healthChoices"` + HouseID *string `json:"houseId,omitempty"` Inventory map[string]int64 `json:"inventory"` Items []ItemInstance `json:"items"` Kills int64 `json:"kills"` @@ -698,24 +807,6 @@ type Character struct { Weapons map[string]WeaponProgress `json:"weapons,omitempty"` } -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"` @@ -725,6 +816,11 @@ type CraftProgress struct { XPToNextLevel int64 `json:"xpToNextLevel"` } +type KeyDestruction struct { + FinishesAt float64 `json:"finishesAt"` + KeyID string `json:"keyId"` +} + type SkillProgress struct { EffectiveLevel int64 `json:"effectiveLevel"` Experience StatValue `json:"experience"` @@ -751,22 +847,6 @@ type TimedGatheringEffect struct { Source string `json:"source"` } -type ItemInstance struct { - Attack *CombatAttack `json:"attack,omitempty"` - DefinitionID string `json:"definitionId"` - Description string `json:"description"` - Equippable bool `json:"equippable"` - 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"` - WeaponType *string `json:"weaponType,omitempty"` - Weight float64 `json:"weight"` -} - type LearnedPower struct { Attack CombatAttack `json:"attack"` Definition PowerDefinition `json:"definition"` diff --git a/server/internal/store/catalog.go b/server/internal/store/catalog.go index ef8388b..aad124b 100644 --- a/server/internal/store/catalog.go +++ b/server/internal/store/catalog.go @@ -146,6 +146,13 @@ func decodeCatalog(version int64, raw string) (content.Catalog, error) { } catalog.RestoreBuilding(b) } + if catalog.HousingVersion == 0 { + b, e := content.Load() + if e != nil { + return catalog, e + } + catalog.RestoreFurniture(b) + } return catalog, catalog.Validate() } func (d *DB) Catalog(ctx context.Context) (content.Catalog, error) { diff --git a/server/internal/store/crafting.go b/server/internal/store/crafting.go index a99b9e9..c3aabff 100644 --- a/server/internal/store/crafting.go +++ b/server/internal/store/crafting.go @@ -73,7 +73,7 @@ func (l *Lease) Craft(ctx context.Context, live *game.World, account string, req request, _ := json.Marshal(req) out, _ := json.Marshal(result) receipt := &craftReceipt{req.ID, account, req.CharacterID, string(request), string(out)} - if e = l.save(ctx, staged, "", nil, "", receipt, nil); e != nil { + if e = l.save(ctx, staged, "", nil, "", receipt, nil, nil); e != nil { return p.CraftResult{}, e } // Retain character pointers captured by existing WebSocket handlers. diff --git a/server/internal/store/house_items.go b/server/internal/store/house_items.go new file mode 100644 index 0000000..eb79949 --- /dev/null +++ b/server/internal/store/house_items.go @@ -0,0 +1,123 @@ +package store + +import ( + "aeternalis/server/internal/game" + p "aeternalis/server/internal/protocol" + "slices" +) + +func houseItemAction(w *game.World, c *game.Character, h *houseRecord, r HouseRequest, allowed map[string]bool) error { + rules := w.Balance.Housing + switch r.Op { + case "place": + if !allowed["placeFurniture"] { + return houseError("placing furniture is not permitted") + } + if len(h.View.Furniture) >= rules.MaxFurniture { + return houseError("furniture limit") + } + for i, item := range c.View.Items { + if item.ID == r.Item { + if !game.FurnitureFits(h.View, "", item, r.X, r.Z) { + return houseError("furniture overlaps or leaves the room") + } + h.View.Furniture[item.ID] = p.HouseFurniture{Item: item, X: r.X, Z: r.Z, Contents: game.EmptyHouseInventory()} + c.View.Items = append(c.View.Items[:i:i], c.View.Items[i+1:]...) + return nil + } + } + return houseError("carried furniture required") + case "move": + if !allowed["moveFurniture"] { + return houseError("moving furniture is not permitted") + } + f, ok := h.View.Furniture[r.Target] + if !ok || !game.FurnitureFits(h.View, r.Target, f.Item, r.X, r.Z) { + return houseError("invalid furniture position") + } + f.X = r.X + f.Z = r.Z + h.View.Furniture[r.Target] = f + return nil + case "pickup-furniture": + if !allowed["pickupItems"] { + return houseError("picking up items is not permitted") + } + f, ok := h.View.Furniture[r.Target] + if !ok || len(c.View.Items) >= rules.MaxItems { + return houseError("furniture unavailable or inventory full") + } + if len(f.Contents.Items) > 0 { + return houseError("empty the furniture first") + } + for _, n := range f.Contents.Inventory { + if n > 0 { + return houseError("empty the furniture first") + } + } + c.View.Items = append(c.View.Items, f.Item) + delete(h.View.Furniture, r.Target) + return nil + case "deposit", "withdraw", "drop", "pickup": + permission := map[string]string{"deposit": "depositItems", "withdraw": "pickupItems", "drop": "dropItems", "pickup": "pickupItems"}[r.Op] + if !allowed[permission] || r.Op == "withdraw" && !allowed["openFurniture"] { + return houseError("item movement is not permitted") + } + player := game.HouseInventoryOf(c) + contents := h.View.Floor + f := p.HouseFurniture{} + if r.Op == "deposit" || r.Op == "withdraw" { + var ok bool + f, ok = h.View.Furniture[r.Target] + if !ok || f.Item.Furniture == nil || !f.Item.Furniture.Container { + return houseError("choose storage furniture") + } + contents = f.Contents + } + if r.Op == "deposit" || r.Op == "drop" { + // Do not permit the house's access keys to become locked inside that same house. + for _, i := range player.Items { + if i.ID == r.Item && i.HouseID != nil && *i.HouseID == h.View.ID { + return houseError("keep this house's key outside its own storage and floor") + } + } + if len(contents.Items) >= rules.MaxItems { + return houseError("storage full") + } + if e := game.MoveHouseItem(&player, &contents, r.Item, r.Quantity); e != nil { + return houseError(e.Error()) + } + if c.View.DestroyKey != nil && c.View.DestroyKey.KeyID == r.Item { + c.View.DestroyKey = nil + } + } else { + if len(player.Items) >= rules.MaxItems { + return houseError("inventory full") + } + if e := game.MoveHouseItem(&contents, &player, r.Item, r.Quantity); e != nil { + return houseError(e.Error()) + } + } + seen := map[string]bool{} + if e := game.ValidateHouseInventory(player, seen); e != nil { + return houseError(e.Error()) + } + if e := game.ValidateHouseInventory(contents, seen); e != nil { + return houseError(e.Error()) + } + game.SetHouseInventory(c, player) + for slot, id := range c.View.Equipment { + if !slices.ContainsFunc(c.View.Items, func(i p.ItemInstance) bool { return i.ID == id }) { + delete(c.View.Equipment, slot) + } + } + if r.Op == "deposit" || r.Op == "withdraw" { + f.Contents = contents + h.View.Furniture[r.Target] = f + } else { + h.View.Floor = contents + } + return nil + } + return houseError("unknown house action") +} diff --git a/server/internal/store/house_lifecycle.go b/server/internal/store/house_lifecycle.go new file mode 100644 index 0000000..29bd1da --- /dev/null +++ b/server/internal/store/house_lifecycle.go @@ -0,0 +1,153 @@ +package store + +import ( + "aeternalis/server/internal/game" + p "aeternalis/server/internal/protocol" + "context" + "database/sql" + "slices" +) + +func (d *DB) destroyHouseKey(ctx context.Context, tx *sql.Tx, key, house string, visited map[string]bool) error { + h, e := d.readHouse(ctx, tx, house, true) + if e != nil { + return e + } + if _, e = tx.ExecContext(ctx, d.q(`UPDATE house_keys SET state='destroyed' WHERE id=? AND house_id=? AND state='active'`), key, house); e != nil { + return e + } + count, e := d.keyCount(ctx, tx, house) + if e != nil { + return e + } + if count != 0 { + return nil + } + return d.archiveHouse(ctx, tx, h, visited) +} +func (d *DB) archiveHouse(ctx context.Context, tx *sql.Tx, h *houseRecord, visited map[string]bool) error { + if visited[h.View.ID] { + return nil + } + visited[h.View.ID] = true + h.View.State = "archived" + ended, e := d.recoveryEnded(ctx, tx, h) + if e != nil { + return e + } + if ended { + // Purging stored keys also updates their houses; registry counts never retain + // keys whose containing inventory has been permanently removed. + keys := []p.ItemInstance{} + keys = append(keys, h.View.Floor.Items...) + for _, f := range h.View.Furniture { + keys = append(keys, f.Contents.Items...) + } + slices.SortFunc(keys, func(a, b p.ItemInstance) int { + if a.ID < b.ID { + return -1 + } + if a.ID > b.ID { + return 1 + } + return 0 + }) + purgeHouse(h) + if e = d.writeHouse(ctx, tx, h); e != nil { + return e + } + for _, key := range keys { + if key.HouseID != nil { + if e = d.destroyHouseKey(ctx, tx, key.ID, *key.HouseID, visited); e != nil { + return e + } + } + } + return nil + } + return d.writeHouse(ctx, tx, h) +} +func (d *DB) syncHousing(ctx context.Context, tx *sql.Tx, w *game.World) error { + ids := make([]string, 0, len(w.Characters)) + for id := range w.Characters { + ids = append(ids, id) + } + slices.Sort(ids) + for _, id := range ids { + c := w.Characters[id] + var ownerWorld, state string + if e := tx.QueryRowContext(ctx, d.q(`SELECT world_id,state FROM character_records WHERE character_id=?`), id).Scan(&ownerWorld, &state); e != nil { + return e + } + // An old source copy may checkpoint, but cannot touch a transferred key. + if ownerWorld != w.ID || state == "transit" { + continue + } + if c.View.Entity.State == "dead" && c.DiedAt != nil && c.RevivalCorpse != "" { + // Compare death time so an old source-world copy cannot replace a later death. + if _, e := tx.ExecContext(ctx, d.q(`UPDATE houses SET death_world=?,death_id=?,death_at=? WHERE creator_character=? AND death_at= a.FinishesAt { + c.View.DestroyKey = nil + if c.Online && !c.Sheltered && c.View.RemainingSeconds > 0 && (c.View.Entity.State == "alive" || c.View.Entity.State == "eligible") { + for i, key := range c.View.Items { + if key.ID == a.KeyID && key.HouseID != nil { + if e := d.destroyHouseKey(ctx, tx, key.ID, *key.HouseID, map[string]bool{}); e != nil { + return e + } + c.View.Items = append(c.View.Items[:i:i], c.View.Items[i+1:]...) + w.RefreshStats(c) + break + } + } + } + } + if house := game.HouseID(c); house != "" { + h, e := d.readHouse(ctx, tx, house, false) + if e != nil { + return e + } + role, e := d.houseRole(ctx, tx, h, c) + if e != nil { + return e + } + if h.View.State != "active" || role == "" || !c.Online || c.View.Entity.State == "dead" || c.View.RemainingSeconds <= 0 { + game.LeaveHouse(c) + } + } + } + if w.Phase == "lost" { + rows, e := tx.QueryContext(ctx, d.q(`SELECT id FROM houses WHERE death_world=? AND state='archived' ORDER BY id`), w.ID) + if e != nil { + return e + } + houses := []string{} + for rows.Next() { + var id string + if e = rows.Scan(&id); e != nil { + rows.Close() + return e + } + houses = append(houses, id) + } + e = rows.Err() + rows.Close() + if e != nil { + return e + } + for _, id := range houses { + h, e := d.readHouse(ctx, tx, id, true) + if e != nil { + return e + } + if h.View.State == "archived" { + if e = d.archiveHouse(ctx, tx, h, map[string]bool{}); e != nil { + return e + } + } + } + } + return nil +} diff --git a/server/internal/store/house_recovery_test.go b/server/internal/store/house_recovery_test.go new file mode 100644 index 0000000..d418071 --- /dev/null +++ b/server/internal/store/house_recovery_test.go @@ -0,0 +1,174 @@ +package store + +import ( + "aeternalis/server/content" + "aeternalis/server/internal/game" + p "aeternalis/server/internal/protocol" + "context" + "encoding/json" + "errors" + "path/filepath" + "testing" + "time" +) + +func TestHouseDeathTravelAndRecovery(t *testing.T) { + ctx := context.Background() + db, e := Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "recovery.db"))) + if e != nil { + t.Fatal(e) + } + defer db.Close() + b, _ := content.Load() + now := time.Now().UTC() + hub := game.New("home", 1, now, b) + c, _ := hub.Join("creator", "Creator") + c.WorldsSurvived = 1 + _ = hub.Connect(c.View.Entity.ID) + hub.Kind = "hub" + hub.Phase = "hub" + hl, _, e := db.Acquire(ctx, hub) + if e != nil { + t.Fatal(e) + } + if e = hl.Save(ctx, hub, ""); e != nil { + t.Fatal(e) + } + act := func(l *Lease, w *game.World, c *game.Character, r HouseRequest) { + t.Helper() + r.RequestID = game.ID() + if e = l.HouseAction(ctx, w, c.Account, r); e != nil { + t.Fatal(r.Op, e) + } + } + state := func(w *game.World, c *game.Character) p.HouseState { + t.Helper() + v, e := db.HouseState(ctx, w, c.Account) + if e != nil { + t.Fatal(e) + } + return v + } + act(hl, hub, c, HouseRequest{Op: "create", Name: "Recovery home"}) + house := state(hub, c).Houses[0].ID + key := c.View.Items[len(c.View.Items)-1].ID + act(hl, hub, c, HouseRequest{Op: "enter", HouseID: house}) + c.View.Inventory["wood"] = 12 + act(hl, hub, c, HouseRequest{Op: "drop", HouseID: house, Item: "wood", Quantity: 7}) + act(hl, hub, c, HouseRequest{Op: "leave"}) + next := game.New("doomed", 2, now, b) + nl, _, e := db.Acquire(ctx, next) + if e != nil { + t.Fatal(e) + } + // Traveling cancels the action, retains the exact key, and never creates another owner copy. + act(hl, hub, c, HouseRequest{Op: "destroy-key", Item: key}) + oldWorld := *hub + oldWorld.Characters = map[string]*game.Character{c.View.Entity.ID: c} + tr, e := hl.PrepareTravel(ctx, hub, c.Account, game.ID(), next.ID, "hub") + if e != nil { + t.Fatal(e) + } + _, e = nl.AcceptTravel(ctx, next, c.Account, tr.ID) + if e != nil { + t.Fatal(e) + } + c = next.ForAccount(c.Account) + _ = next.Connect(c.View.Entity.ID) + if c.View.DestroyKey != nil || c.View.Items[len(c.View.Items)-1].ID != key { + t.Fatal("travel lost key or retained pending destruction") + } + // Saving an old source-world copy cannot complete its now-expired key action. + oldWorld.Advance(now.Add(4*time.Second), 4) + if e = hl.Save(ctx, &oldWorld, ""); e != nil { + t.Fatal(e) + } + var keys int + if e = db.sql.QueryRow(`SELECT COUNT(*) FROM house_keys WHERE state='active'`).Scan(&keys); e != nil || keys != 1 { + t.Fatal("stale source destroyed traveling key", e) + } + act(nl, next, c, HouseRequest{Op: "destroy-key", Item: key}) + c.View.Entity.HP = 0 + next.Advance(now.Add(time.Second), 1) + if e = nl.Save(ctx, next, ""); e != nil { + t.Fatal(e) + } + corpse := next.Corpses[c.RevivalCorpse] + if corpse == nil || c.View.DestroyKey != nil { + t.Fatal("death failed to interrupt") + } + found := false + for _, i := range corpse.Items { + if i.ID == key { + found = true + } + } + if !found { + t.Fatal("interrupted key missing from corpse") + } + // Replacement inherits no key. Recovery remains gated on that replacement's survival. + replacement, e := next.Join(c.Account, "Replacement") + if e != nil { + t.Fatal(e) + } + _ = next.Connect(replacement.View.Entity.ID) + replacement.View.Inventory["escape_stone"] = 1 + if e = nl.Save(ctx, next, ""); e != nil { + t.Fatal(e) + } + // Remove the deliberately stale fixture copy from the hub before arrival. + delete(hub.Characters, c.View.Entity.ID) + tr, e = nl.PrepareTravel(ctx, next, replacement.Account, game.ID(), hub.ID, "escape") + if e != nil { + t.Fatal(e) + } + _, e = hl.AcceptTravel(ctx, hub, replacement.Account, tr.ID) + if e != nil { + t.Fatal(e) + } + replacement = hub.ForAccount(replacement.Account) + _ = hub.Connect(replacement.View.Entity.ID) + if len(replacement.View.Items) != 1 { + t.Fatal("replacement unexpectedly inherited items", replacement.View.Items) + } // Starting knife only. + e = hl.HouseAction(ctx, hub, replacement.Account, HouseRequest{RequestID: game.ID(), Op: "recover", HouseID: house}) + if !errors.Is(e, ErrHousing) { + t.Fatal("unproven replacement recovered", e) + } + replacement.WorldsSurvived = 1 + act(hl, hub, replacement, HouseRequest{Op: "recover", HouseID: house}) + if v := state(hub, replacement); v.Houses[0].Keys != 2 { + t.Fatal("creator recovery invalidated corpse key") + } + act(hl, hub, replacement, HouseRequest{Op: "enter", HouseID: house}) + if state(hub, replacement).Room.Floor.Inventory["wood"] != 7 { + t.Fatal("recovery recreated or lost contents") + } + // Restart exits the room and cancels an unfinished destruction, retaining its key and contents. + key2 := replacement.View.Items[len(replacement.View.Items)-1].ID + act(hl, hub, replacement, HouseRequest{Op: "destroy-key", Item: key2}) + raw, _ := json.Marshal(hub) + var restored game.World + if e = json.Unmarshal(raw, &restored); e != nil { + t.Fatal(e) + } + if e = restored.Restore(now.Add(10 * time.Second)); e != nil { + t.Fatal(e) + } + rc := restored.ForAccount(replacement.Account) + if rc == nil || rc.View.DestroyKey != nil || game.HouseID(rc) != "" { + t.Fatal("restart preserved pending room/action") + } + next.Phase = "lost" + if e = nl.Save(ctx, next, ""); e != nil { + t.Fatal(e) + } + // An active house remains owned by valid keys when the recovery world is destroyed. + if state(hub, replacement).Houses[0].State != "active" { + t.Fatal("death-world loss deleted key-owned house") + } + e = hl.HouseAction(ctx, hub, replacement.Account, HouseRequest{RequestID: game.ID(), Op: "recover", HouseID: house}) + if !errors.Is(e, ErrHousing) { + t.Fatal("recovery after world destruction", e) + } +} diff --git a/server/internal/store/house_view.go b/server/internal/store/house_view.go new file mode 100644 index 0000000..cb92f6b --- /dev/null +++ b/server/internal/store/house_view.go @@ -0,0 +1,123 @@ +package store + +import ( + "aeternalis/server/internal/game" + p "aeternalis/server/internal/protocol" + "context" + "database/sql" + "errors" + "slices" +) + +func (d *DB) HouseState(ctx context.Context, w *game.World, account string) (p.HouseState, error) { + out := p.HouseState{Houses: []p.HouseSummary{}, People: []p.Entity{}, Effective: map[string]bool{}} + c := w.ForAccount(account) + if c == nil { + return out, houseError("living character required") + } + tx, e := d.sql.BeginTx(ctx, nil) + if e != nil { + return out, e + } + defer tx.Rollback() + var world string + e = tx.QueryRowContext(ctx, d.q(`SELECT world_id FROM character_records WHERE character_id=? AND state IN ('alive','eligible')`), c.View.Entity.ID).Scan(&world) + if errors.Is(e, sql.ErrNoRows) || e == nil && world != w.ID { + return out, houseError("character is in another world") + } + if e != nil { + return out, e + } + ids := map[string]bool{} + rows, e := tx.QueryContext(ctx, d.q(`SELECT id FROM houses WHERE creator_account=? UNION SELECT house_id FROM house_invites WHERE character_id=?`), account, c.View.Entity.ID) + if e != nil { + return out, e + } + for rows.Next() { + var id string + if e = rows.Scan(&id); e != nil { + rows.Close() + return out, e + } + ids[id] = true + } + e = rows.Err() + rows.Close() + if e != nil { + return out, e + } + for _, i := range c.View.Items { + if i.HouseID != nil { + ids[*i.HouseID] = true + } + } + sorted := make([]string, 0, len(ids)) + for id := range ids { + sorted = append(sorted, id) + } + slices.Sort(sorted) + for _, id := range sorted { + h, e := d.readHouse(ctx, tx, id, false) + if e != nil { + return out, e + } + role, e := d.houseRole(ctx, tx, h, c) + if e != nil { + return out, e + } + n, e := d.keyCount(ctx, tx, id) + if e != nil { + return out, e + } + out.Houses = append(out.Houses, p.HouseSummary{ID: id, Name: h.View.Name, State: h.View.State, Role: role, Creator: h.CreatorAccount == account, RecoveryWorld: h.DeathWorld, Keys: n}) + if game.HouseID(c) == id && h.View.State == "active" && role != "" { + out.Role = role + out.Effective = housePermissions(h, c, role) + if !out.Effective["openFurniture"] { + for key, f := range h.View.Furniture { + f.Contents = game.EmptyHouseInventory() + h.View.Furniture[key] = f + } + } + if role != "owner" && role != "co-owner" { + h.View.Roles = map[string]string{} + h.View.Overrides = map[string]map[string]bool{} + h.View.Permissions = map[string]bool{} + } + out.Room = &h.View + } + } + for _, other := range w.Characters { + if other.View.Entity.State == "alive" || other.View.Entity.State == "eligible" { + v := p.Entity{ID: other.View.Entity.ID, Name: other.View.Entity.Name, Kind: "player"} + out.People = append(out.People, v) + } + } + // Keep invitations understandable after guests switch hubs or disconnect. + if out.Room != nil && (out.Role == "owner" || out.Role == "co-owner") { + for id := range out.Room.Roles { + if slices.ContainsFunc(out.People, func(v p.Entity) bool { return v.ID == id }) { + continue + } + var name string + e := tx.QueryRowContext(ctx, d.q(`SELECT name FROM character_records WHERE character_id=?`), id).Scan(&name) + if errors.Is(e, sql.ErrNoRows) { + continue + } + if e != nil { + return out, e + } + out.People = append(out.People, p.Entity{ID: id, Name: name, Kind: "player"}) + } + } + slices.SortFunc(out.People, func(a, b p.Entity) int { + if a.Name < b.Name { + return -1 + } + if a.Name > b.Name { + return 1 + } + return 0 + }) + return out, tx.Commit() +} diff --git a/server/internal/store/housing.go b/server/internal/store/housing.go new file mode 100644 index 0000000..63eee64 --- /dev/null +++ b/server/internal/store/housing.go @@ -0,0 +1,386 @@ +package store + +import ( + "aeternalis/server/internal/game" + p "aeternalis/server/internal/protocol" + "context" + "database/sql" + "encoding/json" + "errors" + "fmt" + "slices" + "strings" +) + +var ErrHousing = errors.New("housing action rejected") + +func houseError(s string) error { return fmt.Errorf("%w: %s", ErrHousing, s) } + +type HouseRequest struct { + RequestID string `json:"requestId"` + Op string `json:"op"` + HouseID string `json:"houseId"` + Target string `json:"target"` + Item string `json:"item"` + Quantity int64 `json:"quantity"` + X float64 `json:"x"` + Z float64 `json:"z"` + Role string `json:"role"` + Name string `json:"name"` + Permissions map[string]bool `json:"permissions"` + Revision int64 `json:"revision"` +} +type houseMutation struct { + Account string + Request HouseRequest +} +type houseRecord struct { + View p.House + CreatorAccount, CreatorCharacter, DeathWorld, DeathID string +} + +func (d *DB) readHouse(ctx context.Context, tx *sql.Tx, id string, lock bool) (*houseRecord, error) { + if lock { + if _, e := tx.ExecContext(ctx, d.q(`UPDATE houses SET state=state WHERE id=?`), id); e != nil { + return nil, e + } + } + var raw string + h := &houseRecord{} + e := tx.QueryRowContext(ctx, d.q(`SELECT creator_account,creator_character,death_world,death_id,document FROM houses WHERE id=?`), id).Scan(&h.CreatorAccount, &h.CreatorCharacter, &h.DeathWorld, &h.DeathID, &raw) + if errors.Is(e, sql.ErrNoRows) { + return nil, houseError("house not found") + } + if e != nil { + return nil, e + } + if e = json.Unmarshal([]byte(raw), &h.View); e != nil { + return nil, e + } + return h, nil +} +func (d *DB) writeHouse(ctx context.Context, tx *sql.Tx, h *houseRecord) error { + seen := map[string]bool{} + if e := game.ValidateHouseInventory(h.View.Floor, seen); e != nil { + return houseError(e.Error()) + } + for id, f := range h.View.Furniture { + if id != f.Item.ID || seen[id] || f.Item.Furniture == nil { + return houseError("invalid furniture identity") + } + seen[id] = true + if e := game.ValidateHouseInventory(f.Contents, seen); e != nil { + return houseError(e.Error()) + } + } + h.View.Revision++ + raw, e := json.Marshal(h.View) + if e != nil { + return e + } + _, e = tx.ExecContext(ctx, d.q(`UPDATE houses SET state=?,document=? WHERE id=?`), h.View.State, string(raw), h.View.ID) + return e +} +func (d *DB) houseRole(ctx context.Context, tx *sql.Tx, h *houseRecord, c *game.Character) (string, error) { + for _, i := range c.View.Items { + if i.HouseID == nil || *i.HouseID != h.View.ID { + continue + } + var n int + if e := tx.QueryRowContext(ctx, d.q(`SELECT COUNT(*) FROM house_keys WHERE id=? AND house_id=? AND state='active'`), i.ID, h.View.ID).Scan(&n); e != nil { + return "", e + } + if n == 1 { + return "owner", nil + } + } + return h.View.Roles[c.View.Entity.ID], nil +} +func housePermissions(h *houseRecord, c *game.Character, role string) map[string]bool { + out := map[string]bool{} + for _, key := range game.HousePermissions { + out[key] = role == "owner" || role == "co-owner" || h.View.Permissions[key] + if role != "owner" && role != "co-owner" { + if v, ok := h.View.Overrides[c.View.Entity.ID][key]; ok { + out[key] = v + } + } + } + return out +} +func (d *DB) keyCount(ctx context.Context, tx *sql.Tx, id string) (int64, error) { + var n int64 + e := tx.QueryRowContext(ctx, d.q(`SELECT COUNT(*) FROM house_keys WHERE house_id=? AND state='active'`), id).Scan(&n) + return n, e +} +func (d *DB) issueKey(ctx context.Context, tx *sql.Tx, h *houseRecord, c *game.Character, max int) error { + if len(c.View.Items) >= max { + return houseError("inventory full") + } + count, e := d.keyCount(ctx, tx, h.View.ID) + if e != nil { + return e + } + if count >= 128 { + return houseError("house key limit reached") + } + id := game.ID() + _, e = tx.ExecContext(ctx, d.q(`INSERT INTO house_keys(id,house_id,state) VALUES(?,?,'active')`), id, h.View.ID) + if e != nil { + return e + } + houseID := h.View.ID + c.View.Items = append(c.View.Items, p.ItemInstance{ID: id, DefinitionID: "house_key", Name: h.View.Name + " key", Description: "A bearer key granting owner rights. Destroying it takes three seconds.", Slot: "bag", Weight: .1, HouseID: &houseID, Requirements: p.ItemRequirements{Level: 1, Stats: map[string]float64{}, Titles: []string{}}, Modifiers: []p.StatModifier{}}) + return nil +} +func (d *DB) recoveryEnded(ctx context.Context, tx *sql.Tx, h *houseRecord) (bool, error) { + if h.DeathWorld == "" { + return false, nil + } + var raw string + e := tx.QueryRowContext(ctx, d.q(`SELECT snapshot FROM worlds WHERE id=?`), h.DeathWorld).Scan(&raw) + if errors.Is(e, sql.ErrNoRows) { + return false, nil + } + if e != nil { + return false, e + } + var w struct{ Phase string } + if e = json.Unmarshal([]byte(raw), &w); e != nil { + return false, e + } + return w.Phase == "lost", nil +} +func purgeHouse(h *houseRecord) { + h.View.State = "purged" + h.View.Floor = game.EmptyHouseInventory() + h.View.Furniture = map[string]p.HouseFurniture{} + h.View.Roles = map[string]string{} + h.View.Overrides = map[string]map[string]bool{} +} +func (l *Lease) HouseAction(ctx context.Context, w *game.World, account string, r HouseRequest) error { + if !catalogRequestID.MatchString(r.RequestID) || len(r.HouseID) > 64 || len(r.Item) > 100 || len(r.Target) > 100 || len(r.Name) > 80 || len(r.Permissions) > 6 { + return houseError("invalid request") + } + if e := l.save(ctx, w, "", nil, "", nil, nil, &houseMutation{account, r}); e != nil { + return e + } + if c := w.ForAccount(account); c != nil && game.HouseID(c) != "" { + c.MoveX = 0 + c.MoveZ = 0 + c.PendingCast = nil + } + return nil +} +func (d *DB) applyHouse(ctx context.Context, tx *sql.Tx, w *game.World, m *houseMutation) error { + r := m.Request + c := w.ForAccount(m.Account) + if c == nil || !c.Online || c.Sheltered || c.View.RemainingSeconds <= 0 || w.Phase == "lost" { + return houseError("active character required") + } + var current, world, state string + if e := tx.QueryRowContext(ctx, d.q(`SELECT character_id,world_id,state FROM character_records WHERE account_id=? AND state IN ('alive','eligible','transit')`), m.Account).Scan(¤t, &world, &state); e != nil { + return e + } + if current != c.View.Entity.ID || world != w.ID || state == "transit" { + return houseError("character has moved") + } + raw, _ := json.Marshal(r) + var previous string + e := tx.QueryRowContext(ctx, d.q(`SELECT request FROM house_receipts WHERE account_id=? AND id=?`), m.Account, r.RequestID).Scan(&previous) + if e == nil { + if previous != string(raw) { + return houseError("request already used") + } + return nil + } + if !errors.Is(e, sql.ErrNoRows) { + return e + } + if e = d.mutateHouse(ctx, tx, w, c, r); e != nil { + return e + } + w.RefreshStats(c) + _, e = tx.ExecContext(ctx, d.q(`INSERT INTO house_receipts(account_id,id,request) VALUES(?,?,?)`), m.Account, r.RequestID, string(raw)) + return e +} +func (d *DB) mutateHouse(ctx context.Context, tx *sql.Tx, w *game.World, c *game.Character, r HouseRequest) error { + rules := w.Balance.Housing + if r.Op == "cancel-key" { + c.View.DestroyKey = nil + return nil + } + if r.Op == "destroy-key" { + if c.View.DestroyKey != nil { + return houseError("already destroying a key") + } + for _, i := range c.View.Items { + if i.ID == r.Item && i.HouseID != nil { + h, e := d.readHouse(ctx, tx, *i.HouseID, true) + if e != nil { + return e + } + var n int + if e = tx.QueryRowContext(ctx, d.q(`SELECT COUNT(*) FROM house_keys WHERE id=? AND house_id=? AND state='active'`), i.ID, h.View.ID).Scan(&n); e != nil { + return e + } + if n != 1 { + return houseError("key is invalid") + } + c.View.DestroyKey = &p.KeyDestruction{KeyID: i.ID, FinishesAt: w.NowSeconds() + rules.KeySeconds} + return nil + } + } + return houseError("carried key required") + } + if !w.IsHub() { + return houseError("housing is accessed from a hub") + } + if r.Op == "leave" { + game.LeaveHouse(c) + return nil + } + if r.Op == "create" { + if c.WorldsSurvived < 1 || game.HouseID(c) != "" { + return houseError("survive a world and return to the hub before creating a house") + } + var count int + if e := tx.QueryRowContext(ctx, d.q(`SELECT COUNT(*) FROM houses WHERE creator_account=? AND state<>'purged'`), c.Account).Scan(&count); e != nil { + return e + } + if count > 0 { + return houseError("you already created a recoverable house") + } + name := strings.TrimSpace(r.Name) + if name == "" { + return houseError("house name required") + } + h := &houseRecord{CreatorAccount: c.Account, CreatorCharacter: c.View.Entity.ID, View: p.House{ID: game.ID(), Name: name, State: "active", Size: rules.RoomSize, Permissions: map[string]bool{}, Overrides: map[string]map[string]bool{}, Roles: map[string]string{}, Furniture: map[string]p.HouseFurniture{}, Floor: game.EmptyHouseInventory()}} + raw, _ := json.Marshal(h.View) + if _, e := tx.ExecContext(ctx, d.q(`INSERT INTO houses(id,creator_account,creator_character,death_world,death_id,state,document) VALUES(?,?,?,'','','active',?)`), h.View.ID, c.Account, c.View.Entity.ID, string(raw)); e != nil { + return e + } + if e := d.issueKey(ctx, tx, h, c, rules.MaxItems); e != nil { + return e + } + return d.writeHouse(ctx, tx, h) + } + h, e := d.readHouse(ctx, tx, r.HouseID, true) + if e != nil { + return e + } + ended, e := d.recoveryEnded(ctx, tx, h) + if e != nil { + return e + } + if r.Op == "recover" { + if h.CreatorAccount != c.Account || c.WorldsSurvived < 1 || h.DeathID == "" || h.DeathWorld == "" || ended || h.View.State == "purged" { + return houseError("creator recovery unavailable") + } + var known int + if e = tx.QueryRowContext(ctx, d.q(`SELECT COUNT(*) FROM worlds WHERE id=?`), h.DeathWorld).Scan(&known); e != nil { + return e + } + if known != 1 { + return houseError("recovery world unavailable") + } + if e = d.issueKey(ctx, tx, h, c, rules.MaxItems); e != nil { + return e + } + h.View.State = "active" + return d.writeHouse(ctx, tx, h) + } + if h.View.State != "active" { + return houseError("house is unavailable") + } + role, e := d.houseRole(ctx, tx, h, c) + if e != nil { + return e + } + if role == "" { + return houseError("a carried key or invitation is required") + } + if r.Op == "enter" { + if c.WorldsSurvived < 1 { + return houseError("survive a world before entering housing") + } + if game.HouseID(c) != "" { + return houseError("leave the current house first") + } + id := h.View.ID + c.View.HouseID = &id + c.View.DestroyKey = nil + c.View.Casting = nil + return nil + } + if game.HouseID(c) != h.View.ID { + return houseError("enter this house first") + } + if r.Revision > 0 && r.Revision != h.View.Revision { + return houseError("house changed; refresh before editing") + } + allowed := housePermissions(h, c, role) + manager := role == "owner" || role == "co-owner" + switch r.Op { + case "issue-key": + if role != "owner" { + return houseError("only key holders issue keys") + } + if e = d.issueKey(ctx, tx, h, c, rules.MaxItems); e != nil { + return e + } + case "invite": + if !manager || (!slices.Contains([]string{"guest", "co-owner", "remove"}, r.Role)) || (role != "owner" && (r.Role == "co-owner" || h.View.Roles[r.Target] == "co-owner")) { + return houseError("invitation role not allowed") + } + if r.Target == c.View.Entity.ID { + return houseError("cannot change your own invitation") + } + if r.Role == "remove" { + delete(h.View.Roles, r.Target) + delete(h.View.Overrides, r.Target) + if _, e = tx.ExecContext(ctx, d.q(`DELETE FROM house_invites WHERE house_id=? AND character_id=?`), h.View.ID, r.Target); e != nil { + return e + } + } else { + var n int + if e = tx.QueryRowContext(ctx, d.q(`SELECT COUNT(*) FROM character_records WHERE character_id=? AND state IN ('alive','eligible')`), r.Target).Scan(&n); e != nil { + return e + } + if n != 1 { + return houseError("living guest not found") + } + if h.View.Roles[r.Target] == "" && len(h.View.Roles) >= rules.MaxGuests { + return houseError("guest limit") + } + h.View.Roles[r.Target] = r.Role + if _, e = tx.ExecContext(ctx, d.q(`INSERT INTO house_invites(house_id,character_id) VALUES(?,?) ON CONFLICT(house_id,character_id) DO NOTHING`), h.View.ID, r.Target); e != nil { + return e + } + } + case "permissions": + if !manager { + return houseError("only owners and co-owners manage guest permissions") + } + for key := range r.Permissions { + if !slices.Contains(game.HousePermissions, key) { + return houseError("unknown guest permission") + } + } + if r.Target == "" { + for k, v := range r.Permissions { + h.View.Permissions[k] = v + } + } else { + if h.View.Roles[r.Target] == "" { + return houseError("invite this person first") + } + h.View.Overrides[r.Target] = r.Permissions + } + default: + if e = houseItemAction(w, c, h, r, allowed); e != nil { + return e + } + } + return d.writeHouse(ctx, tx, h) +} diff --git a/server/internal/store/housing_test.go b/server/internal/store/housing_test.go new file mode 100644 index 0000000..0cf60f9 --- /dev/null +++ b/server/internal/store/housing_test.go @@ -0,0 +1,256 @@ +package store + +import ( + "aeternalis/server/content" + "aeternalis/server/internal/game" + p "aeternalis/server/internal/protocol" + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "testing" + "time" +) + +func TestHousingLifecycle(t *testing.T) { + testHousingLifecycle(t, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "housing.db"))) +} +func TestPostgresHousingLifecycle(t *testing.T) { + dsn := os.Getenv("TEST_DATABASE_URL") + if dsn == "" { + t.Skip("TEST_DATABASE_URL not configured") + } + testHousingLifecycle(t, dsn) +} +func testHousingLifecycle(t *testing.T, dsn string) { + ctx := context.Background() + db, e := Open(ctx, dsn) + if e != nil { + t.Fatal(e) + } + defer db.Close() + b, _ := content.Load() + now := time.Now().UTC() + w := game.New("housing-"+game.ID(), 1, now, b) + l, _, e := db.Acquire(ctx, w) + if e != nil { + t.Fatal(e) + } + join := func(name string) *game.Character { + c, e := w.Join(name+game.ID(), name) + if e != nil { + t.Fatal(e) + } + if e = w.Connect(c.View.Entity.ID); e != nil { + t.Fatal(e) + } + return c + } + owner, guest, coowner := join("Owner"), join("Guest"), join("Co-owner") + // Seed arrivals before making this fixture a hub; travel itself has separate coverage. + w.Kind = "hub" + w.Phase = "hub" + save := func() { + t.Helper() + if e := l.Save(ctx, w, ""); e != nil { + t.Fatal(e) + } + } + save() + act := func(c *game.Character, r HouseRequest) { + t.Helper() + if r.RequestID == "" { + r.RequestID = game.ID() + } + if e := l.HouseAction(ctx, w, c.Account, r); e != nil { + t.Fatal(r.Op, e) + } + } + reject := func(c *game.Character, r HouseRequest) { + t.Helper() + r.RequestID = game.ID() + before, _ := json.Marshal(w) + e := l.HouseAction(ctx, w, c.Account, r) + if !errors.Is(e, ErrHousing) { + t.Fatal("expected housing rejection", r.Op, e) + } + after, _ := json.Marshal(w) + if string(before) != string(after) { + t.Fatal("rejected action mutated world", r.Op) + } + } + view := func(c *game.Character) p.HouseState { + t.Helper() + s, e := db.HouseState(ctx, w, c.Account) + if e != nil { + t.Fatal(e) + } + return s + } + tick := func(seconds float64) { + now = now.Add(time.Duration(seconds * float64(time.Second))) + w.Advance(now, seconds) + save() + } + reject(owner, HouseRequest{Op: "create", Name: "Home"}) + owner.WorldsSurvived = 1 + guest.WorldsSurvived = 1 + coowner.WorldsSurvived = 1 + save() + create := HouseRequest{RequestID: game.ID(), Op: "create", Name: "Home"} + act(owner, create) + act(owner, create) + s := view(owner) + if len(s.Houses) != 1 || s.Houses[0].Keys != 1 { + t.Fatal("create replay duplicated house or key", s) + } + house := s.Houses[0].ID + key := owner.View.Items[len(owner.View.Items)-1].ID + reject(owner, HouseRequest{Op: "create", Name: "Duplicate"}) + reject(guest, HouseRequest{Op: "enter", HouseID: house}) + act(owner, HouseRequest{Op: "enter", HouseID: house}) + if e := w.Intent(owner.View.Entity.ID, p.Intent{Seq: 1, Op: "jump"}); e == nil { + t.Fatal("world action inside house") + } + if _, e := w.AttemptCraft(owner, p.CraftRequest{Profession: "carver", Ingredients: map[string]int64{"wood": 1}}); e == nil { + t.Fatal("house craft accepted") + } + stale := *l + stale.Revision-- + if e := stale.HouseAction(ctx, w, owner.Account, HouseRequest{RequestID: game.ID(), Op: "issue-key", HouseID: house}); !errors.Is(e, ErrOwnership) { + t.Fatal("stale owner mutation", e) + } + if view(owner).Houses[0].Keys != 1 { + t.Fatal("stale lease issued key") + } + act(owner, HouseRequest{Op: "invite", HouseID: house, Target: guest.View.Entity.ID, Role: "guest"}) + act(owner, HouseRequest{Op: "invite", HouseID: house, Target: coowner.View.Entity.ID, Role: "co-owner"}) + act(guest, HouseRequest{Op: "enter", HouseID: house}) + act(coowner, HouseRequest{Op: "enter", HouseID: house}) + reject(guest, HouseRequest{Op: "permissions", HouseID: house, Permissions: map[string]bool{"pickupItems": true}}) + reject(coowner, HouseRequest{Op: "issue-key", HouseID: house}) + act(coowner, HouseRequest{Op: "permissions", HouseID: house, Permissions: map[string]bool{"moveFurniture": true, "openFurniture": true, "depositItems": true}}) + act(coowner, HouseRequest{Op: "permissions", HouseID: house, Target: guest.View.Entity.ID, Permissions: map[string]bool{"moveFurniture": false}}) + if v := view(guest); v.Effective["moveFurniture"] || !v.Effective["depositItems"] { + t.Fatal("baseline/override not enforced") + } + if e = w.AdminItems(owner, "grant-item", "storage_chest:1"); e != nil { + t.Fatal(e) + } + chest := owner.View.Items[len(owner.View.Items)-1].ID + owner.View.Inventory["wood"] = 20 + save() + act(owner, HouseRequest{Op: "place", HouseID: house, Item: chest, X: 0, Z: 0}) + reject(owner, HouseRequest{Op: "move", HouseID: house, Target: chest, X: 100, Z: 0}) + reject(guest, HouseRequest{Op: "move", HouseID: house, Target: chest, X: 3, Z: 0}) + act(owner, HouseRequest{Op: "deposit", HouseID: house, Target: chest, Item: "wood", Quantity: 10}) + reject(guest, HouseRequest{Op: "withdraw", HouseID: house, Target: chest, Item: "wood", Quantity: 1}) + reject(owner, HouseRequest{Op: "pickup-furniture", HouseID: house, Target: chest}) + reject(owner, HouseRequest{Op: "deposit", HouseID: house, Target: chest, Item: key, Quantity: 1}) + act(coowner, HouseRequest{Op: "permissions", HouseID: house, Target: guest.View.Entity.ID, Permissions: map[string]bool{"pickupItems": true, "openFurniture": false}}) + if len(view(guest).Room.Furniture[chest].Contents.Inventory) != 0 { + t.Fatal("closed container contents leaked") + } + reject(guest, HouseRequest{Op: "withdraw", HouseID: house, Target: chest, Item: "wood", Quantity: 1}) + act(coowner, HouseRequest{Op: "permissions", HouseID: house, Target: guest.View.Entity.ID, Permissions: map[string]bool{"pickupItems": true}}) + act(guest, HouseRequest{Op: "withdraw", HouseID: house, Target: chest, Item: "wood", Quantity: 2}) + if view(owner).Room.Furniture[chest].Contents.Inventory["wood"] != 8 || guest.View.Inventory["wood"] != 2 { + t.Fatal("stored inventory transfer") + } + // Furniture movement preserves exact instance and contents. + act(guest, HouseRequest{Op: "move", HouseID: house, Target: chest, X: 3, Z: 0}) + if f := view(owner).Room.Furniture[chest]; f.Item.ID != chest || f.Contents.Inventory["wood"] != 8 { + t.Fatal("move lost furniture or contents") + } + act(owner, HouseRequest{Op: "issue-key", HouseID: house}) + if view(owner).Houses[0].Keys != 2 { + t.Fatal("extra key missing") + } + act(owner, HouseRequest{Op: "destroy-key", Item: key}) + tick(2.9) + if view(owner).Houses[0].Keys != 2 || owner.View.DestroyKey == nil { + t.Fatal("key destroyed early") + } + tick(.11) + if view(owner).Houses[0].Keys != 1 || view(owner).Houses[0].State != "active" { + t.Fatal("non-last key archived house") + } + key = owner.View.Items[len(owner.View.Items)-1].ID + act(owner, HouseRequest{Op: "leave"}) + act(owner, HouseRequest{Op: "destroy-key", Item: key}) + w.Disconnect(owner.View.Entity.ID) + save() + tick(4) + if view(owner).Houses[0].Keys != 1 || owner.View.DestroyKey != nil { + t.Fatal("disconnect failed to cancel key action") + } + _ = w.Connect(owner.View.Entity.ID) + act(owner, HouseRequest{Op: "destroy-key", Item: key}) + if e = w.Intent(owner.View.Entity.ID, p.Intent{Seq: 2, Op: "drop", Target: key}); e != nil { + t.Fatal(e) + } + if owner.View.DestroyKey != nil { + t.Fatal("drop failed to cancel") + } + save() + var pile string + for id, c := range w.Corpses { + for _, i := range c.Items { + if i.ID == key { + pile = id + } + } + } + if pile == "" { + t.Fatal("key not dropped") + } + act(guest, HouseRequest{Op: "leave"}) + guest.View.Entity.Position = owner.View.Entity.Position + if e = w.Intent(guest.View.Entity.ID, p.Intent{Seq: 1, Op: "loot", Target: pile}); e != nil { + t.Fatal(e) + } + save() + act(guest, HouseRequest{Op: "enter", HouseID: house}) + if view(guest).Role != "owner" { + t.Fatal("looted key did not grant ownership") + } + act(coowner, HouseRequest{Op: "invite", HouseID: house, Target: guest.View.Entity.ID, Role: "remove"}) + if view(guest).Role != "owner" { + t.Fatal("invitation removal stripped key owner") + } + // Last-key destruction archives contents immediately on completion; no invented purge deadline. + act(guest, HouseRequest{Op: "destroy-key", Item: key}) + tick(3.01) + if v := view(owner); v.Houses[0].State != "archived" || v.Houses[0].Keys != 0 { + t.Fatal("last-key archive", v) + } + tx, _ := db.sql.BeginTx(ctx, nil) + stored, e := db.readHouse(ctx, tx, house, false) + tx.Rollback() + if e != nil || stored.View.Furniture[chest].Contents.Inventory["wood"] != 8 { + t.Fatal("archive lost recoverable contents", e) + } + reject(owner, HouseRequest{Op: "recover", HouseID: house}) + reject(coowner, HouseRequest{Op: "enter", HouseID: house}) + // Creator death establishes the recovery world. World loss finally purges archived data. + owner.View.Entity.HP = 0 + tick(.1) + if owner.DiedAt == nil { + t.Fatal("creator death absent") + } + tx, _ = db.sql.BeginTx(ctx, nil) + stored, e = db.readHouse(ctx, tx, house, false) + tx.Rollback() + if e != nil || stored.DeathWorld != w.ID { + t.Fatal("recovery world not captured", e) + } + w.Phase = "lost" + save() + tx, _ = db.sql.BeginTx(ctx, nil) + stored, e = db.readHouse(ctx, tx, house, false) + tx.Rollback() + if e != nil || stored.View.State != "purged" || len(stored.View.Furniture) != 0 { + t.Fatal("world loss did not purge archived house", e) + } +} diff --git a/server/internal/store/portal.go b/server/internal/store/portal.go index c4dbf18..9918255 100644 --- a/server/internal/store/portal.go +++ b/server/internal/store/portal.go @@ -65,6 +65,12 @@ func (d *DB) migrate(ctx context.Context) error { } } for _, stmt := range []string{ + `CREATE TABLE IF NOT EXISTS houses(id TEXT PRIMARY KEY,creator_account TEXT NOT NULL,creator_character TEXT NOT NULL,death_world TEXT NOT NULL,death_id TEXT NOT NULL,death_at BIGINT NOT NULL DEFAULT 0,state TEXT NOT NULL,document TEXT NOT NULL)`, + `CREATE UNIQUE INDEX IF NOT EXISTS one_created_house ON houses(creator_account) WHERE state<>'purged'`, + `CREATE TABLE IF NOT EXISTS house_keys(id TEXT PRIMARY KEY,house_id TEXT NOT NULL,state TEXT NOT NULL)`, + `CREATE INDEX IF NOT EXISTS keys_house ON house_keys(house_id,state)`, + `CREATE TABLE IF NOT EXISTS house_invites(house_id TEXT NOT NULL,character_id TEXT NOT NULL,PRIMARY KEY(house_id,character_id))`, + `CREATE TABLE IF NOT EXISTS house_receipts(account_id TEXT NOT NULL,id TEXT NOT NULL,request TEXT NOT NULL,PRIMARY KEY(account_id,id))`, `CREATE TABLE IF NOT EXISTS account_lives(account_id TEXT PRIMARY KEY,character_id TEXT NOT NULL)`, `CREATE TABLE IF NOT EXISTS character_deaths(corpse_id TEXT PRIMARY KEY,character_id TEXT NOT NULL,world_id TEXT NOT NULL,character TEXT NOT NULL,revived INTEGER NOT NULL)`, `CREATE TABLE IF NOT EXISTS craft_receipts(id TEXT NOT NULL,account_id TEXT NOT NULL,character_id TEXT NOT NULL,request_json TEXT NOT NULL,result_json TEXT NOT NULL,PRIMARY KEY(account_id,id))`, diff --git a/server/internal/store/revival.go b/server/internal/store/revival.go index c8a163d..5933d8f 100644 --- a/server/internal/store/revival.go +++ b/server/internal/store/revival.go @@ -124,7 +124,7 @@ func (l *Lease) RevivalConsent(ctx context.Context, w *game.World, account, id s } func (l *Lease) Revive(ctx context.Context, w *game.World, account, corpse, power string) error { caster := w.ForAccount(account) - if caster == nil { + if caster == nil || game.HouseID(caster) != "" { return ErrRevival } active, e := l.DB.ActiveCharacter(ctx, account) @@ -141,7 +141,7 @@ func (l *Lease) Revive(ctx context.Context, w *game.World, account, corpse, powe return fmt.Errorf("%w: %v", ErrRevival, e) } claim := &reviveClaim{target.Account, target.View.Entity.ID, corpse, w.ID} - if e = l.save(ctx, staged, "", nil, "", nil, claim); e != nil { + if e = l.save(ctx, staged, "", nil, "", nil, claim, nil); e != nil { return e } for id, c := range staged.Characters { diff --git a/server/internal/store/store.go b/server/internal/store/store.go index 1cf25b5..d329c8a 100644 --- a/server/internal/store/store.go +++ b/server/internal/store/store.go @@ -139,9 +139,9 @@ func (l *Lease) Save(ctx context.Context, w *game.World, claimID string) error { return l.SaveCommand(ctx, w, claimID, nil, "") } func (l *Lease) SaveCommand(ctx context.Context, w *game.World, claimID string, command *Command, outcome string) error { - return l.save(ctx, w, claimID, command, outcome, nil, nil) + return l.save(ctx, w, claimID, command, outcome, nil, nil, nil) } -func (l *Lease) save(ctx context.Context, w *game.World, claimID string, command *Command, outcome string, receipt *craftReceipt, revival *reviveClaim) error { +func (l *Lease) save(ctx context.Context, w *game.World, claimID string, command *Command, outcome string, receipt *craftReceipt, revival *reviveClaim, housing *houseMutation) error { live := w w = stageTitleWorld(w) data, err := json.Marshal(w) @@ -198,6 +198,14 @@ func (l *Lease) save(ctx context.Context, w *game.World, claimID string, command return err } } + if err = d.syncHousing(ctx, tx, w); err != nil { + return err + } + if housing != nil { + if err = d.applyHouse(ctx, tx, w, housing); err != nil { + return err + } + } if err = d.syncTitles(ctx, tx, w); err != nil { return err } diff --git a/server/internal/store/titles.go b/server/internal/store/titles.go index c6c0256..848d49d 100644 --- a/server/internal/store/titles.go +++ b/server/internal/store/titles.go @@ -26,6 +26,7 @@ func stageTitleWorld(w *game.World) *game.World { copy.View.Powers = maps.Clone(c.View.Powers) copy.View.Weapons = maps.Clone(c.View.Weapons) copy.View.Inventory = maps.Clone(c.View.Inventory) + copy.View.StackNames = maps.Clone(c.View.StackNames) copy.View.Equipment = maps.Clone(c.View.Equipment) copy.View.AllocatedStats = maps.Clone(c.View.AllocatedStats) copy.View.Stats = maps.Clone(c.View.Stats) diff --git a/server/internal/store/travel.go b/server/internal/store/travel.go index 1b276ba..fa5a34e 100644 --- a/server/internal/store/travel.go +++ b/server/internal/store/travel.go @@ -107,6 +107,8 @@ func (l *Lease) PrepareTravel(ctx context.Context, live *game.World, account, re return nil, err } departing.PendingCast = nil + departing.View.DestroyKey = nil + game.LeaveHouse(&departing) departing.View.Casting = nil if route == "escape" { game.TakeStack(&departing, "escape_stone", 1) diff --git a/server/internal/transport/housing.go b/server/internal/transport/housing.go new file mode 100644 index 0000000..d48ddc2 --- /dev/null +++ b/server/internal/transport/housing.go @@ -0,0 +1,67 @@ +package transport + +import ( + "aeternalis/server/internal/store" + "errors" + "net/http" +) + +func (h *HTTP) housingRoutes(mux *http.ServeMux) { + mux.HandleFunc("GET /api/housing", 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 + } + state, e := h.auth.db.HouseState(r.Context(), h.s.world, account) + if e != nil { + h.housingFailure(w, e) + return + } + respond(w, 200, state) + }) + mux.HandleFunc("POST /api/housing", 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 store.HouseRequest + if decode(w, r, &req) != nil { + fail(w, 400, "invalid housing 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.persist(r.Context(), ""); e != nil { + fail(w, 503, "save unavailable") + return + } + if e = h.s.lease.HouseAction(r.Context(), h.s.world, account, req); e != nil { + h.housingFailure(w, e) + return + } + respond(w, 200, map[string]bool{"saved": true}) + }) +} +func (h *HTTP) housingFailure(w http.ResponseWriter, e error) { + if errors.Is(e, store.ErrHousing) || errors.Is(e, store.ErrLivingCharacter) { + fail(w, 409, e.Error()) + return + } + h.s.ready.Store(false) + for _, p := range h.s.peers { + p.close() + } + fail(w, 503, "housing save unavailable; reconnect to check the result") +} diff --git a/server/internal/transport/housing_test.go b/server/internal/transport/housing_test.go new file mode 100644 index 0000000..75105e3 --- /dev/null +++ b/server/internal/transport/housing_test.go @@ -0,0 +1,80 @@ +package transport + +import ( + "aeternalis/server/content" + "aeternalis/server/internal/game" + "aeternalis/server/internal/store" + "context" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestHousingHTTPAuthorization(t *testing.T) { + ctx := context.Background() + db, e := store.Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "house.db"))) + if e != nil { + t.Fatal(e) + } + defer db.Close() + b, _ := content.Load() + w := game.New("house-auth", 1, time.Now(), b) + c, _ := w.Join("owner", "Owner") + c.WorldsSurvived = 1 + _ = w.Connect(c.View.Entity.ID) + w.Kind = "hub" + w.Phase = "hub" + l, _, e := db.Acquire(ctx, w) + if e != nil { + t.Fatal(e) + } + if e = l.Save(ctx, w, ""); e != nil { + t.Fatal(e) + } + auth, _ := NewAuth(ctx, db, true, "http://127.0.0.1", "", "", "") + out := httptest.NewRecorder() + if e = auth.session(out, httptest.NewRequest("POST", auth.base+"/auth/dev", nil), "owner"); e != nil { + t.Fatal(e) + } + cookie := out.Result().Cookies()[0] + s := NewService(w, l) + h := NewHTTP(s, auth, t.TempDir(), nil).Handler() + request := func(method, origin, body string, cookie *http.Cookie) int { + r := httptest.NewRequest(method, auth.base+"/api/housing", strings.NewReader(body)) + r.RemoteAddr = "127.0.0.1:1234" + if origin != "" { + r.Header.Set("Origin", origin) + } + if cookie != nil { + r.AddCookie(cookie) + } + out := httptest.NewRecorder() + h.ServeHTTP(out, r) + return out.Code + } + body := `{"requestId":"` + game.ID() + `","op":"create","name":"Home"}` + if code := request("GET", "", "", nil); code != 401 { + t.Fatal("anonymous directory", code) + } + if code := request("POST", auth.base, body, nil); code != 401 { + t.Fatal("anonymous mutation", code) + } + if code := request("POST", "https://evil.example", body, cookie); code != 403 { + t.Fatal("cross-origin mutation", code) + } + if code := request("POST", auth.base, body, cookie); code != 200 { + t.Fatal("authorized create", code) + } + if code := request("GET", "", "", cookie); code != 200 { + t.Fatal("authorized directory", code) + } + if code := request("POST", auth.base, `{"requestId":"`+game.ID()+`","op":"create","account":"other"}`, cookie); code != 400 { + t.Fatal("actor spoofing", code) + } + if !s.ready.Load() { + t.Fatal("ordinary rejection froze world") + } +} diff --git a/server/internal/transport/http.go b/server/internal/transport/http.go index 900dad1..4d83217 100644 --- a/server/internal/transport/http.go +++ b/server/internal/transport/http.go @@ -100,6 +100,7 @@ func (h *HTTP) Handler() http.Handler { h.travelRoutes(mux) h.craftingRoutes(mux) h.powerRoutes(mux) + h.housingRoutes(mux) h.catalogRoutes(mux) mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { if !h.s.ready.Load() {