From 1bd5d487e209c5a7c95df3a8f239069f36a45dd8 Mon Sep 17 00:00:00 2001 From: dingo Date: Thu, 10 Sep 2026 10:48:26 -0400 Subject: [PATCH] Add walkable housing interiors and cross-hub visitors --- client/src/generated.ts | 21 +++ client/src/house-view.ts | 38 +++++ client/src/housing-panel.ts | 14 +- client/src/housing.css | 1 + client/src/input-controls.ts | 1 + client/src/main.ts | 10 +- client/src/world-view.ts | 5 + docs/ARCHITECTURE.md | 7 +- docs/LIFECYCLE-OWNERSHIP.md | 3 +- docs/MILESTONE-8B.md | 3 + docs/MILESTONE-8C.md | 80 ++++++++++ planning/SYSTEMS-ROADMAP.md | 6 +- planning/VISION.md | 4 +- schemas/protocol.json | 31 +++- server/content/balance.yaml | 2 +- server/content/housing.go | 19 ++- server/internal/game/house_movement.go | 152 +++++++++++++++++++ server/internal/game/house_movement_test.go | 65 ++++++++ server/internal/game/housing.go | 23 ++- server/internal/game/world.go | 24 +-- server/internal/protocol/generated.go | 21 +++ server/internal/store/house_lifecycle.go | 16 +- server/internal/store/house_presence.go | 94 ++++++++++++ server/internal/store/house_presence_test.go | 114 ++++++++++++++ server/internal/store/housing.go | 6 + server/internal/store/housing_test.go | 2 +- server/internal/store/portal.go | 2 + server/internal/store/store.go | 9 ++ 28 files changed, 721 insertions(+), 52 deletions(-) create mode 100644 client/src/house-view.ts create mode 100644 docs/MILESTONE-8C.md create mode 100644 server/internal/game/house_movement.go create mode 100644 server/internal/game/house_movement_test.go create mode 100644 server/internal/store/house_presence.go create mode 100644 server/internal/store/house_presence_test.go diff --git a/client/src/generated.ts b/client/src/generated.ts index ff5c761..e3c2545 100644 --- a/client/src/generated.ts +++ b/client/src/generated.ts @@ -723,6 +723,7 @@ export interface Snapshot { chunks: Chunk[]; entities: Entity[]; gatherRisks?: { [key: string]: GatheringRisk }; + house?: HouseScene; message: string; projectileVisuals?: ProjectileVisual[]; self: Character; @@ -754,6 +755,25 @@ export interface GatheringRisk { seconds: number; } +export interface HouseScene { + furniture: RoomFurniture[]; + id: string; + name: string; + people: Entity[]; + size: number; +} + +export interface RoomFurniture { + container: boolean; + depth: number; + height: number; + id: string; + name: string; + width: number; + x: number; + z: number; +} + export interface ProjectileVisual { at: number; destination: Vec3; @@ -786,6 +806,7 @@ export interface Character { hasKeystone: boolean; healthChoices: number; houseId?: string; + housePosition?: Vec3; inventory: { [key: string]: number }; items: ItemInstance[]; kills: number; diff --git a/client/src/house-view.ts b/client/src/house-view.ts new file mode 100644 index 0000000..b90dd0a --- /dev/null +++ b/client/src/house-view.ts @@ -0,0 +1,38 @@ +import * as T from 'three'; +import type {Entity, HouseScene, Snapshot} from './generated'; + +/** Indoor presentation only. Positions and furniture geometry come from Go. */ +export class HouseView { + readonly scene=new T.Scene(); + readonly camera=new T.OrthographicCamera(-10,10,10,-10,.1,100); + private room=new T.Group();private actors=new Mapvoid}>(); + private signature='';private active=false;private size=12;private ray=new T.Raycaster(); + private disposables:(()=>void)[]=[]; + constructor(){this.scene.background=new T.Color('#172329');this.scene.add(new T.HemisphereLight('#fff5db','#4b3930',2));const sun=new T.DirectionalLight('#ffdfaa',3);sun.position.set(2,9,6);this.scene.add(sun,this.room)} + private box(w:number,h:number,d:number,x:number,y:number,z:number,color:string,parent:T.Object3D=this.room){const geometry=new T.BoxGeometry(w,h,d),material=new T.MeshStandardMaterial({color,roughness:.85});const mesh=new T.Mesh(geometry,material);mesh.position.set(x,y,z);parent.add(mesh);this.disposables.push(()=>{geometry.dispose();material.dispose()});return mesh} + update(snapshot:Snapshot,model?:T.Group){ + const house=snapshot.house;if(!house){if(this.active)this.clear();return}this.active=true;this.size=house.size; + const signature=JSON.stringify([house.id,house.size,house.furniture]);if(this.signature!==signature){this.clear();this.active=true;this.signature=signature;this.build(house)} + const entities=[...house.people.filter(p=>p.id!==snapshot.self.entity.id),{...snapshot.self.entity,position:snapshot.self.housePosition??{x:0,y:0,z:0}}]; + const ids=new Set(entities.map(p=>p.id));for(const [id,v] of this.actors)if(!ids.has(id)){this.scene.remove(v.root);v.dispose();this.actors.delete(id)} + for(const e of entities){let actor=this.actors.get(e.id);if(!actor){const firstDisposable=this.disposables.length,root=new T.Group();if(model)root.add(model.clone(true));else{this.box(.55,1.25,.45,0,.8,0,e.id===snapshot.self.entity.id?'#bdd1ad':'#88a9c6',root);this.box(.4,.4,.4,0,1.65,0,'#d6b49a',root)} + const canvas=document.createElement('canvas');canvas.width=256;canvas.height=48;const ctx=canvas.getContext('2d')!;ctx.fillStyle='#13201ee6';ctx.fillRect(0,0,256,48);ctx.fillStyle='#fff5df';ctx.textAlign='center';ctx.font='24px sans-serif';ctx.fillText(e.name,128,32,248);const texture=new T.CanvasTexture(canvas),material=new T.SpriteMaterial({map:texture,depthTest:false}),name=new T.Sprite(material);name.position.y=2.2;name.scale.set(2.5,.47,1);root.add(name);this.disposables.push(()=>{texture.dispose();material.dispose()});root.position.set(e.position.x,e.position.y,e.position.z);const cleanup=this.disposables.splice(firstDisposable);actor={root,target:root.position.clone(),dispose:()=>cleanup.forEach(f=>f())};this.actors.set(e.id,actor);this.scene.add(root) + }actor.target.set(e.position.x,e.position.y,e.position.z) + } + } + private build(h:HouseScene){ + this.box(h.size,.18,h.size,0,-.09,0,'#907451');this.box(h.size,2.8,.2,0,1.4,-h.size/2,'#bab297');this.box(.2,2.8,h.size,-h.size/2,1.4,0,'#9e9986'); + for(let x=-h.size/2;x.002)a.root.rotation.y=Math.atan2(-delta.x,-delta.z);a.root.position.lerp(a.target,1-Math.exp(-14*dt))}renderer.render(this.scene,this.camera); + } + pick(canvas:HTMLCanvasElement,x:number,y:number):{entity?:Entity;point?:T.Vector3}{const r=canvas.getBoundingClientRect();this.ray.setFromCamera(new T.Vector2((x-r.left)/r.width*2-1,-(y-r.top)/r.height*2+1),this.camera);for(const hit of this.ray.intersectObject(this.room,true)){let o:T.Object3D|null=hit.object;while(o){if(o.userData.entity)return{entity:o.userData.entity as Entity};o=o.parent}if(Math.abs(hit.point.y)<.02)return{point:hit.point}}return{}} + clear(){for(const dispose of this.disposables)dispose();this.disposables=[];this.room.clear();for(const a of this.actors.values()){this.scene.remove(a.root);a.dispose()}this.actors.clear();this.signature='';this.active=false} +} diff --git a/client/src/housing-panel.ts b/client/src/housing-panel.ts index 45273df..6722e58 100644 --- a/client/src/housing-panel.ts +++ b/client/src/housing-panel.ts @@ -12,13 +12,15 @@ const number=(value:number,min:number,max:number)=>{const n=node('input');n.type 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){ +export function createHousingPanel(character:()=>Character|undefined,prefix:string,isHub:()=>boolean,onEnter:()=>void){ 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 dialog=node('dialog','','housing-dialog'),title=node('h2','Housing'),status=node('p'),body=node('div'),close=button('Close controls',()=>dialog.close()); + const toolbar=node('div','','house-toolbar');toolbar.hidden=true;toolbar.append(button('House controls',()=>show()),button('Return to hub',()=>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()}); + const menu=registerMenu(dialog,()=>dialog.close());dialog.addEventListener('cancel',e=>{e.preventDefault();dialog.close()}); + function show(id=''){selected=id;if(!dialog.open)dialog.showModal();menu.opened();void refresh(true)} 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…'; @@ -35,7 +37,7 @@ export function createHousingPanel(character:()=>Character|undefined,prefix:stri } 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'; + title.textContent=h?h.name+' · '+s.role:'Housing & keys';close.textContent=h?'Walk around':'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); @@ -46,7 +48,7 @@ export function createHousingPanel(character:()=>Character|undefined,prefix:stri } 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); + const x=number(h.furniture[selected]?.x??0,-h.size/2,h.size/2),z=number(h.furniture[selected]?.z??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); @@ -76,5 +78,5 @@ export function createHousingPanel(character:()=>Character|undefined,prefix:stri } } 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)}}}; + return {root,toolbar,open:show,leave,update(c:Character){latest=c;toolbar.hidden=!c.houseId;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){onEnter();dialog.close()}if(dialog.open)void refresh(true)}}}; } diff --git a/client/src/housing.css b/client/src/housing.css index 6f4b3ab..4ab351a 100644 --- a/client/src/housing.css +++ b/client/src/housing.css @@ -8,3 +8,4 @@ .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} +.house-toolbar{pointer-events:auto;position:absolute;top:90px;right:24px;display:flex;gap:8px;z-index:4}.house-toolbar[hidden]{display:none}.house-toolbar button{background:#21372eef;color:#f2ecd5;padding:10px;border:1px solid #a9b994;border-radius:5px} diff --git a/client/src/input-controls.ts b/client/src/input-controls.ts index 10713a0..d659035 100644 --- a/client/src/input-controls.ts +++ b/client/src/input-controls.ts @@ -32,6 +32,7 @@ export class InputActions { const focused=document.activeElement as HTMLElement|null,menu=focused?.closest('.panel,dialog,form');if(!menu)return; const options=[...menu.querySelectorAll('button:not([disabled]),input:not([disabled]),select:not([disabled]),summary,a[href]')].filter(e=>e.getClientRects().length>0); if(i===12||i===13){const at=options.indexOf(focused!);options[(at+(i===13?1:options.length-1)+options.length)%options.length]?.focus();return} + if((i===14||i===15)&&focused instanceof HTMLInputElement&&focused.type==='number'){if(i===15)focused.stepUp();else focused.stepDown();focused.dispatchEvent(new Event('change',{bubbles:true}));return} if((i===14||i===15)&&focused instanceof HTMLSelectElement){focused.selectedIndex=Math.max(0,Math.min(focused.options.length-1,focused.selectedIndex+(i===15?1:-1)));focused.dispatchEvent(new Event('change',{bubbles:true}));return} if(i===0&&focused&&!['INPUT','SELECT'].includes(focused.tagName))focused.click(); } diff --git a/client/src/main.ts b/client/src/main.ts index 12ad58a..f9f80f9 100644 --- a/client/src/main.ts +++ b/client/src/main.ts @@ -141,7 +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); @@ -164,6 +164,7 @@ function minimap(s: Snapshot) { } function updateHUD(s: Snapshot) { const c = s.self, w = s.world; + housing?.update(c); powers?.update(c); visible('game-controls', true); visible('movement', ['alive','eligible'].includes(c.entity.state) && $('inventory').hidden && $('settings').hidden); $('character-name').textContent = c.entity.name; @@ -194,6 +195,7 @@ function updateHUD(s: Snapshot) { visible('target-boss',w.kind!=='hub');$('target-boss').textContent=w.phase==='won'?'Find victory portal':'Target Harbinger';$('target-boss').setAttribute('aria-label',w.phase==='won'?'Find victory portal':'Target Harbinger'); visible('dev-boss',config.development&&w.kind!=='hub'); $('attack').disabled=w.kind==='hub'||w.phase==='won';$('gather').disabled=w.kind==='hub'||w.phase==='won'; + if(c.houseId){$('phase-label').textContent=s.house?.name??'HOUSE';$('season-detail').textContent='WASD / stick to walk · Jump onto furniture · I for house controls';$('coordinates').textContent=`${c.housePosition?.x.toFixed(1)??0}, ${c.housePosition?.z.toFixed(1)??0}`;} selection(view.selected); minimap(s); if (s.message && s.message !== lastNotice) { notice(s.message); lastNotice = s.message; } } @@ -202,6 +204,7 @@ async function boot() { createIcons({ icons: { Crosshair, Settings2, X, Flame, LogOut, Hourglass, Swords, Pickaxe, HeartPulse, Gem, Backpack, ChevronUp, ChevronDown, ChevronLeft, ChevronRight, ArrowRight, RefreshCw } }); view = new WorldView($('world')); input = new InputActions(() => hasOpenMenu() || isEditing(document.activeElement) || $('arrival').open || $('ending').open, key => { + if(snapshot?.self.houseId){if(key==='inventory'||key==='gather'){housing.open();return}if(key==='jump'){send('jump');return}return} if(key==='attack'||key==='gather')action(key); else if(key==='inventory')$('inventory-toggle').click(); else if(key.startsWith('slot'))powers.useSlot(Number(key.slice(4))-1); @@ -219,11 +222,11 @@ 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; } + if(snapshot.self.houseId){let {x,z}=input.movement;if(x||z)walkTo=undefined;const p=snapshot.self.housePosition;if(walkTo&&p){const dx=walkTo.x-p.x,dz=walkTo.z-p.z,n=Math.hypot(dx,dz);if(n>.25){x=dx/n;z=dz/n}else walkTo=undefined}if(inputElapsed>=.05){send('move','',x,z);inputElapsed=0}return} let {x,z} = input.movement; if (x || z) { walkTo = undefined; pendingAction = undefined; } const actionTarget = pendingAction?.target === snapshot.self.entity.id ? snapshot.self.entity : snapshot.entities.find(e => e.id === pendingAction?.target); @@ -268,7 +271,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); + housing=createHousingPanel(()=>snapshot?.self,worldPrefix,()=>config.kind==='hub',()=>{input.clear();walkTo=undefined;pendingAction=undefined;placement=undefined;visible('inventory',false);selection()});$('recipes').after(housing.root);$('hud').append(housing.toolbar); 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;}});}; @@ -326,6 +329,7 @@ async function boot() { view.canvas.addEventListener('pointerdown', event => { if (!snapshot || hasOpenMenu() || $('arrival').open || $('ending').open || event.button !== 0) return; const hit = view.pick(event.clientX, event.clientY); + if(snapshot.self.houseId){if(hit.entity?.kind==='house-exit')void housing.leave();else if(hit.entity)housing.open(hit.entity.id);else if(hit.point)walkTo=hit.point;return} if(placement){if(!hit.point||hit.entity){notice('Choose unoccupied ground. Esc cancels.');return}const p=snapshot.self.entity.position,x=(hit.point.x-p.x)/placement.range,z=(hit.point.z-p.z)/placement.range;if(Math.hypot(x,z)>1){notice('Choose ground within '+placement.range+'m.');return}send('build',placement.id,x,z,placement.rotation);placement=undefined;return;} if (hit.entity) { if(hit.entity.kind==='portal'){$('travel').click();return;} selection(hit.entity); action(['boss', 'sentinel','mob','player','structure'].includes(hit.entity.kind) ? 'attack' : 'gather'); } diff --git a/client/src/world-view.ts b/client/src/world-view.ts index 93615ea..155295b 100644 --- a/client/src/world-view.ts +++ b/client/src/world-view.ts @@ -1,4 +1,5 @@ import * as T from 'three'; +import {HouseView} from './house-view'; import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'; import { ProjectilePresentation } from './projectile-presentation'; import type { Chunk, Entity, Snapshot, Vec3 } from './generated'; @@ -7,6 +8,7 @@ type Batch = { parts: T.InstancedMesh[]; entities: Entity[] }; export class WorldView { readonly renderer: T.WebGLRenderer; readonly scene = new T.Scene(); + readonly houseView=new HouseView(); readonly projectiles = new ProjectilePresentation(this.scene); readonly camera = new T.OrthographicCamera(-60, 60, 40, -40, 0.1, 1400); readonly chunks = new Map(); @@ -186,6 +188,7 @@ export class WorldView { } update(snapshot: Snapshot) { this.snapshot = snapshot; + this.houseView.update(snapshot,this.models.get('player')); this.projectiles.receive(snapshot.projectileVisuals??[]); if (!this.initialized) this.addChunks([], []); this.addChunks(snapshot.chunks, snapshot.chunkKeys); @@ -204,6 +207,7 @@ export class WorldView { if (this.selected) this.selected = this.selected.id === snapshot.self.entity.id ? snapshot.self.entity : snapshot.entities.find(e => e.id === this.selected!.id); } pick(clientX: number, clientY: number): { entity?: Entity; point?: T.Vector3 } { + if(this.snapshot?.house)return this.houseView.pick(this.canvas,clientX,clientY); const rect = this.canvas.getBoundingClientRect(); this.ray.setFromCamera(new T.Vector2((clientX - rect.left) / rect.width * 2 - 1, -(clientY - rect.top) / rect.height * 2 + 1), this.camera); const objects: T.Object3D[] = []; @@ -218,6 +222,7 @@ export class WorldView { start() { this.renderer.setAnimationLoop(() => { const dt = Math.min(this.clock.getDelta(), 0.05); + if(this.snapshot?.house){this.houseView.render(this.renderer,dt);this.frames++;return} this.projectiles.update(); // Presentation interpolation follows server positions; it never changes authoritative movement. this.position.lerp(this.aim, 1 - Math.exp(-14 * dt)); diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 9493be1..f3ff4fa 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -36,8 +36,8 @@ 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. Milestone 8b adds -key-owned housing documents and floor-plan controls; walkable interiors and portal -dungeon instances remain. See +key-owned housing documents and floor-plan controls; 8c adds walkable interiors +and leased cross-hub visitor presence. 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. @@ -52,7 +52,8 @@ 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. +See [milestone 8b](MILESTONE-8B.md) for the lifecycle and [8c](MILESTONE-8C.md) for +indoor movement, rendering, visitor consistency, bounds, and manual tests. 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 9ed3665..20589b7 100644 --- a/docs/LIFECYCLE-OWNERSHIP.md +++ b/docs/LIFECYCLE-OWNERSHIP.md @@ -139,7 +139,8 @@ neither an escape item nor a hub switch supplies a fresh allowance. 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 +for playtesting. [Milestone 8c](MILESTONE-8C.md) adds walkable interiors and visitor +presence while preserving these ownership boundaries. The stored state name for `archived_recoverable` is `archived`. Proposed house states: `active -> archived_recoverable -> purged`. diff --git a/docs/MILESTONE-8B.md b/docs/MILESTONE-8B.md index e94071d..f87ad77 100644 --- a/docs/MILESTONE-8B.md +++ b/docs/MILESTONE-8B.md @@ -1,5 +1,8 @@ # Milestone 8b: housing controls and lifecycle checkpoint +Follow-up: [8c](MILESTONE-8C.md) adds walkable interiors and updates Escape to close +the controls while staying inside. Use Return to hub or the door to leave. + 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, diff --git a/docs/MILESTONE-8C.md b/docs/MILESTONE-8C.md new file mode 100644 index 0000000..abde8d6 --- /dev/null +++ b/docs/MILESTONE-8C.md @@ -0,0 +1,80 @@ +# Milestone 8c: walkable house interiors + +This wraps the first playable building/housing milestone with a 3D indoor view, +authoritative indoor movement, furniture collision, jumping, visible visitors, +and controller-accessible placement controls. The [8b ownership, storage, key, +permission and recovery rules](MILESTONE-8B.md) continue to apply. The separate +[shared XP curve update](XP-CURVE.md) is already committed and pushed. + +## Controls + +Enter through Inventory → Housing & keys. Entry closes the controls and shows +the house interior. **WASD, the left stick, or touch movement buttons** walk; +Space/controller jump uses the existing binding. Clicking the floor walks toward +that point. Walls and furniture block movement; jump onto tables and chests. +Click furniture to open its controls. **I**, the controller inventory/gather +binding, or **House controls** opens the floor plan, storage, and permissions. + +**Escape now closes the focused controls while you stay in the house.** Choose +**Return to hub**, or click the green exit door, to leave. These have no distance +requirement in this first build. Disconnect/restart and daily-cap eviction still +return you to your saved hub position. No house action grants experience. + +Furniture placement/movement uses the floor-plan controls. On a controller, +D-pad up/down changes focus; left/right changes selected choices and numeric +coordinates; the primary button activates buttons. Cancel closes the menu. +Coordinates move in half-metre increments. This is controller form placement, +not a free-moving 3D placement preview. Text naming still uses text input. + +## Authoritative room and visitors + +Go retains a separate indoor position; the character's hub position is preserved +for exit. Clients send bounded movement/jump intents, never indoor coordinates. +Simulation substeps prevent tunneling through narrow furniture on delayed ticks. +The saved indoor position is checked against the latest committed furniture +layout. If a furniture edit encloses a player, they move to a clear floor position; +if no position exists they return to the hub. A completely blocked room rejects +new entry. Characters do not collide with other characters in this slice. + +House geometry and visitor snapshots contain no storage inventories or account +identities. Current local positions are emitted each snapshot. Visitors entering +the same house from different hub processes are visible through a leased database +presence heartbeat, normally refreshed within about one second and expired after +five seconds without updates. Each original world remains the sole owner and +simulator of its characters. No cloned living characters are created. Cross-hub +presence is eventually consistent; it is not a new shared simulation process. + +House mutations, membership, presence and world snapshots commit under the existing +world revision fence. Permissions and last-key archive are rechecked before +publishing membership. Furniture geometry is refreshed on save; updates from a +different hub can take a save interval to affect movement collision. Storage and +permission actions continue to read current database state transactionally. + +The room uses simple procedural table/chest meshes and the existing player model, +with a cutaway camera and name labels. New production art, advanced animation, +custom room shells, avatar cosmetic/gear presentation polish, and freeform +placement previews are later work. Generated room meshes, labels and textures are +disposed on changes/exit; departed visitors release their labels immediately. +No tested player-capacity claim is increased by adding the visitor view. + +## Manual test handoff + +1. Enter a house and walk using keyboard/controller. Test walls, table collision, + jumps onto furniture, landing, and click-to-walk. Close a menu with Escape and + verify you remain inside. Use the exit button/door to return to your hub spot. +2. Click a chest, deposit/withdraw items, and move it with floor-plan controls. + Verify stored contents persist and guests remain bound by the six permissions. +3. Enter the same house with an invited player from another hub instance. Check + names and movement appear. Remove the guest invitation and confirm eviction; + disconnect a visitor and confirm their presence disappears. +4. Move furniture into an occupied spot and verify the occupant is relocated + safely. Reconnect or reach the daily cap and verify the hub return. +5. Repeat 8b's non-last/last-key destruction and interrupted-death tests. Ensure + archived houses remove their visitors and never restore previously withdrawn + items on recovery. + +Local checks cover indoor collision/jumping, invalid action rejection, saved hub +position, daily limits, cross-hub visitor ownership, revoked access, stale lease +rollback, existing key/recovery lifecycle, TypeScript, production build, and +generated protocol consistency. PostgreSQL integration checks require a configured +test database; browser Playwright remains deferred for manual testing. diff --git a/planning/SYSTEMS-ROADMAP.md b/planning/SYSTEMS-ROADMAP.md index 88d9eb4..69a8957 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](../docs/MILESTONE-8A.md) and [8b housing controls/lifecycle](../docs/MILESTONE-8B.md); walkable interiors and controller placement remain | +| 8. Building and housing | Destructible world structures, house instances, keys, permissions, storage, timed deletion/recovery | First playable build implemented: [8a building](../docs/MILESTONE-8A.md), [8b lifecycle](../docs/MILESTONE-8B.md), [8c interiors and manual handoff](../docs/MILESTONE-8C.md); art and placement-preview polish 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 | @@ -604,8 +604,8 @@ First discussion, because these affect the architecture: 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 + Unknown death worlds retain data; retiring inaccessible keys and custom room + shells 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. diff --git a/planning/VISION.md b/planning/VISION.md index 0035231..a6e396c 100644 --- a/planning/VISION.md +++ b/planning/VISION.md @@ -179,8 +179,8 @@ Tracked across: ## Backlog - Milestone 8a adds persistent destructible world structures, craftable kits, 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. + floor-plan controls, keys, permissions, storage, and recovery. Milestone 8c adds + walkable interiors and visitors; see `docs/MILESTONE-8C.md` for 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 8224285..ef49b21 100644 --- a/schemas/protocol.json +++ b/schemas/protocol.json @@ -261,7 +261,8 @@ "weapons": {"type": "object", "additionalProperties": {"$ref": "#/definitions/WeaponProgress"}}, "casting": {"type": "string"}, "houseId": {"type": "string"}, - "destroyKey": {"$ref": "#/definitions/KeyDestruction"} + "destroyKey": {"$ref": "#/definitions/KeyDestruction"}, + "housePosition": {"$ref": "#/definitions/Vec3"} }, "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"] }, @@ -368,7 +369,8 @@ "unavailableResources": {"type": "array", "items": {"type": "string"}}, "message": {"type": "string"}, "gatherRisks": {"type": "object", "additionalProperties": {"$ref": "#/definitions/GatheringRisk"}}, - "projectileVisuals": {"type": "array", "items": {"$ref": "#/definitions/ProjectileVisual"}} + "projectileVisuals": {"type": "array", "items": {"$ref": "#/definitions/ProjectileVisual"}}, + "house": {"$ref": "#/definitions/HouseScene"} }, "required": ["type", "version", "tick", "world", "self", "entities", "chunks", "chunkKeys", "unavailableResources", "message"] }, @@ -1088,6 +1090,31 @@ "people": {"type": "array", "items": {"$ref": "#/definitions/Entity"}} }, "required": ["houses", "role", "effective", "people"] + }, + "HouseScene": { + "type": "object", "additionalProperties": false, + "properties": { + "id": {"type": "string"}, + "name": {"type": "string"}, + "size": {"type": "number"}, + "furniture": {"type": "array", "items": {"$ref": "#/definitions/RoomFurniture"}}, + "people": {"type": "array", "items": {"$ref": "#/definitions/Entity"}} + }, + "required": ["id", "name", "size", "furniture", "people"] + }, + "RoomFurniture": { + "type": "object", "additionalProperties": false, + "properties": { + "id": {"type": "string"}, + "name": {"type": "string"}, + "x": {"type": "number"}, + "z": {"type": "number"}, + "width": {"type": "number"}, + "depth": {"type": "number"}, + "height": {"type": "number"}, + "container": {"type": "boolean"} + }, + "required": ["id", "name", "x", "z", "width", "depth", "height", "container"] } } } diff --git a/server/content/balance.yaml b/server/content/balance.yaml index 0df02e2..b3c3cca 100644 --- a/server/content/balance.yaml +++ b/server/content/balance.yaml @@ -262,4 +262,4 @@ building: - {"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 } +housing: { walkSpeed: 4, playerRadius: 0.35, jumpSpeed: 6, gravity: 18, tableHeight: 0.8, storageHeight: 0.9, roomSize: 12, maxFurniture: 64, maxItems: 256, maxGuests: 64, keySeconds: 3 } diff --git a/server/content/housing.go b/server/content/housing.go index 999f1ba..4d03bc7 100644 --- a/server/content/housing.go +++ b/server/content/housing.go @@ -16,14 +16,23 @@ func (f FurnitureProfile) Validate() error { } type HousingRules struct { - RoomSize float64 `yaml:"roomSize"` - MaxFurniture int `yaml:"maxFurniture"` - MaxItems int `yaml:"maxItems"` - MaxGuests int `yaml:"maxGuests"` - KeySeconds float64 `yaml:"keySeconds"` + WalkSpeed float64 `yaml:"walkSpeed"` + PlayerRadius float64 `yaml:"playerRadius"` + JumpSpeed float64 `yaml:"jumpSpeed"` + Gravity float64 `yaml:"gravity"` + TableHeight float64 `yaml:"tableHeight"` + StorageHeight float64 `yaml:"storageHeight"` + 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 r.WalkSpeed != 0 && (!finiteRange(r.WalkSpeed, 1, 8) || !finiteRange(r.PlayerRadius, .2, .6) || !finiteRange(r.JumpSpeed, 1, 8) || !finiteRange(r.Gravity, 10, 30) || !finiteRange(r.TableHeight, .5, 2) || !finiteRange(r.StorageHeight, .5, 2)) { + return fmt.Errorf("invalid indoor movement tuning") + } 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") } diff --git a/server/internal/game/house_movement.go b/server/internal/game/house_movement.go new file mode 100644 index 0000000..ac5855c --- /dev/null +++ b/server/internal/game/house_movement.go @@ -0,0 +1,152 @@ +package game + +import ( + p "aeternalis/server/internal/protocol" + "errors" + "math" + "slices" +) + +// House geometry contains no storage contents, permissions, or account identities. +func (w *World) HouseScene(h p.House) *p.HouseScene { + out := &p.HouseScene{ID: h.ID, Name: h.Name, Size: h.Size, Furniture: []p.RoomFurniture{}, People: []p.Entity{}} + for id, f := range h.Furniture { + if f.Item.Furniture == nil { + continue + } + profile := f.Item.Furniture + height := w.Balance.Housing.TableHeight + if profile.Container { + height = w.Balance.Housing.StorageHeight + } + out.Furniture = append(out.Furniture, p.RoomFurniture{ID: id, Name: f.Item.Name, X: f.X, Z: f.Z, Width: profile.Width, Depth: profile.Depth, Height: height, Container: profile.Container}) + } + slices.SortFunc(out.Furniture, func(a, b p.RoomFurniture) int { + if a.ID < b.ID { + return -1 + } + if a.ID > b.ID { + return 1 + } + return 0 + }) + return out +} +func roomGround(room *p.HouseScene, pos p.Vec3) float64 { + ground := 0. + for _, f := range room.Furniture { + if math.Abs(pos.X-f.X) < f.Width/2 && math.Abs(pos.Z-f.Z) < f.Depth/2 { + ground = math.Max(ground, f.Height) + } + } + return ground +} +func (w *World) HousePositionValid(room *p.HouseScene, pos p.Vec3) bool { + radius := w.Balance.Housing.PlayerRadius + if math.IsNaN(pos.X) || math.IsNaN(pos.Y) || math.IsNaN(pos.Z) || math.IsInf(pos.X, 0) || math.IsInf(pos.Y, 0) || math.IsInf(pos.Z, 0) || math.Abs(pos.X)+radius > room.Size/2 || math.Abs(pos.Z)+radius > room.Size/2 || pos.Y < 0 || pos.Y > 3 { + return false + } + for _, f := range room.Furniture { + if math.Abs(pos.X-f.X) < f.Width/2+radius && math.Abs(pos.Z-f.Z) < f.Depth/2+radius && pos.Y < f.Height-.001 { + return false + } + } + return true +} +func (w *World) HouseSpawn(room *p.HouseScene) (p.Vec3, bool) { + for z := room.Size/2 - 1.; z >= -room.Size/2+1; z -= .5 { + for x := -room.Size/2 + 1; x <= room.Size/2-1; x += .5 { + pos := p.Vec3{X: x, Z: z} + if w.HousePositionValid(room, pos) { + return pos, true + } + } + } + return p.Vec3{}, false +} +func (w *World) houseIntent(c *Character, i p.Intent) error { + if !w.IsHub() || c.HouseRoom == nil || c.View.HousePosition == nil { + return errors.New("house is synchronizing") + } + switch i.Op { + case "move": + n := math.Max(1, math.Hypot(i.X, i.Z)) + c.MoveX = i.X / n + c.MoveZ = i.Z / n + c.LastMove = w.now + return nil + case "jump": + if math.Abs(c.View.HousePosition.Y-roomGround(c.HouseRoom, *c.View.HousePosition)) > .02 || c.JumpVelocity != 0 { + return errors.New("already jumping") + } + c.JumpVelocity = w.Balance.Housing.JumpSpeed + w.dirty = true + return nil + default: + return errors.New("use house controls or leave to use world actions") + } +} +func (w *World) moveHouse(c *Character, dt float64) { + room := c.HouseRoom + if room == nil || c.View.HousePosition == nil || room.ID != HouseID(c) { + return + } + old := *c.View.HousePosition + pos := old + r := w.Balance.Housing + // Small substeps prevent tunneling through narrow furniture on a delayed tick. + steps := max(1, int(math.Ceil(dt*r.WalkSpeed/.1))) + step := dt / float64(steps) + for range steps { + if c.JumpVelocity != 0 || pos.Y > roomGround(room, pos) { + c.JumpVelocity -= r.Gravity * step + pos.Y += c.JumpVelocity * step + } + pos.Y = math.Max(pos.Y, roomGround(room, pos)) + if pos.Y >= 3 { + pos.Y = 3 + c.JumpVelocity = math.Min(0, c.JumpVelocity) + } + next := pos + next.X += c.MoveX * r.WalkSpeed * step + if w.HousePositionValid(room, next) { + pos.X = next.X + } + next = pos + next.Z += c.MoveZ * r.WalkSpeed * step + if w.HousePositionValid(room, next) { + pos.Z = next.Z + } + ground := roomGround(room, pos) + if pos.Y <= ground { + pos.Y = ground + c.JumpVelocity = 0 + } + } + if pos != old { + c.View.HousePosition = &pos + w.dirty = true + } +} +func (w *World) HouseSnapshot(c *Character) *p.HouseScene { + if HouseID(c) == "" || c.HouseRoom == nil { + return nil + } + out := *c.HouseRoom + out.People = []p.Entity{} + // Local movement is current to this simulation tick. Foreign visitors are read + // from their owning world's leased presence heartbeat, never simulated here. + for _, v := range c.HouseRoom.People { + if _, local := w.Characters[v.ID]; !local { + out.People = append(out.People, v) + } + } + for _, other := range w.orderedCharacters() { + if HouseID(other) == out.ID && other.Online && other.View.HousePosition != nil { + v := other.View.Entity + v.Position = *other.View.HousePosition + out.People = append(out.People, v) + } + } + return &out +} diff --git a/server/internal/game/house_movement_test.go b/server/internal/game/house_movement_test.go new file mode 100644 index 0000000..4f73f70 --- /dev/null +++ b/server/internal/game/house_movement_test.go @@ -0,0 +1,65 @@ +package game + +import ( + p "aeternalis/server/internal/protocol" + "math" + "testing" + "time" +) + +func TestIndoorMovementCollisionJumpAndReturn(t *testing.T) { + w, c := fixture(t) + w.Kind = "hub" + w.Phase = "hub" + house := ID() + c.View.HouseID = &house + c.HouseRoom = &p.HouseScene{ID: house, Size: 12, Furniture: []p.RoomFurniture{{ID: ID(), Width: 2, Depth: 2, Height: .8}}} + pos := p.Vec3{X: -3} + c.View.HousePosition = &pos + hub := c.View.Entity.Position + xp := c.View.Experience + if e := w.Intent(c.View.Entity.ID, p.Intent{Seq: 1, Op: "move", X: 1}); e != nil { + t.Fatal(e) + } + for range 40 { + w.moveHouse(c, .05) + } + if c.View.HousePosition.X > -1.34 || c.View.HousePosition.X < -1.5 { + t.Fatal("walked through table", *c.View.HousePosition) + } + if e := w.Intent(c.View.Entity.ID, p.Intent{Seq: 2, Op: "jump"}); e != nil { + t.Fatal(e) + } + if e := w.Intent(c.View.Entity.ID, p.Intent{Seq: 3, Op: "jump"}); e == nil { + t.Fatal("air jump accepted") + } + top := 0. + for range 12 { + w.moveHouse(c, .05) + top = math.Max(top, c.View.HousePosition.Y) + } + if top < .8 || c.View.HousePosition.X < -.8 { + t.Fatal("could not jump onto furniture", top, *c.View.HousePosition) + } + for range 100 { + w.moveHouse(c, .05) + } + if c.View.HousePosition.X > 6-w.Balance.Housing.PlayerRadius || c.View.HousePosition.Y != 0 { + t.Fatal("room boundary or landing failed", *c.View.HousePosition) + } + if e := w.Intent(c.View.Entity.ID, p.Intent{Seq: 4, Op: "attack"}); e == nil { + t.Fatal("house combat accepted") + } + if c.View.Entity.Position != hub || c.View.Experience != xp { + t.Fatal("indoor movement changed hub position or XP") + } + c.LastMove = w.now.Add(-time.Second) + w.Advance(w.now, .05) + if c.MoveX != 0 { + t.Fatal("stale indoor move did not stop") + } + LeaveHouse(c) + if c.View.HousePosition != nil || c.HouseRoom != nil || c.View.Entity.Position != hub || c.JumpVelocity != 0 { + t.Fatal("exit did not clear room state") + } +} diff --git a/server/internal/game/housing.go b/server/internal/game/housing.go index 36e455a..f509b06 100644 --- a/server/internal/game/housing.go +++ b/server/internal/game/housing.go @@ -16,7 +16,14 @@ func HouseID(c *Character) string { } return *c.View.HouseID } -func LeaveHouse(c *Character) { c.View.HouseID = nil; c.MoveX = 0; c.MoveZ = 0 } +func LeaveHouse(c *Character) { + c.View.HouseID = nil + c.View.HousePosition = nil + c.HouseRoom = nil + c.JumpVelocity = 0 + c.MoveX = 0 + c.MoveZ = 0 +} func (w *World) restoreHousing() error { if w.Balance.Housing == nil { b, e := content.Load() @@ -28,6 +35,20 @@ func (w *World) restoreHousing() error { cat.RestoreFurniture(b) w.Balance.Items = cat.Items } + if w.Balance.Housing.WalkSpeed == 0 { + b, e := content.Load() + if e != nil { + return e + } + r := *w.Balance.Housing + r.WalkSpeed = b.Housing.WalkSpeed + r.PlayerRadius = b.Housing.PlayerRadius + r.JumpSpeed = b.Housing.JumpSpeed + r.Gravity = b.Housing.Gravity + r.TableHeight = b.Housing.TableHeight + r.StorageHeight = b.Housing.StorageHeight + w.Balance.Housing = &r + } for _, c := range w.Characters { LeaveHouse(c) c.View.DestroyKey = nil diff --git a/server/internal/game/world.go b/server/internal/game/world.go index 87af7cd..3c36d68 100644 --- a/server/internal/game/world.go +++ b/server/internal/game/world.go @@ -14,15 +14,16 @@ import ( ) type Character struct { - XPCurveVersion int `json:"xpCurveVersion"` - PendingCast *PendingCast `json:"pendingCast,omitempty"` - RevivalCorpse string `json:"revivalCorpse,omitempty"` - RevivalAllowed bool `json:"revivalAllowed"` - DeathCount int64 `json:"deathCount"` - CraftReadyAt float64 `json:"craftReadyAt"` - AttackReadyAt float64 `json:"attackReadyAt"` - JumpVelocity float64 `json:"jumpVelocity"` - GatherReadyAt float64 `json:"gatherReadyAt"` + HouseRoom *p.HouseScene `json:"-"` + XPCurveVersion int `json:"xpCurveVersion"` + PendingCast *PendingCast `json:"pendingCast,omitempty"` + RevivalCorpse string `json:"revivalCorpse,omitempty"` + RevivalAllowed bool `json:"revivalAllowed"` + DeathCount int64 `json:"deathCount"` + CraftReadyAt float64 `json:"craftReadyAt"` + AttackReadyAt float64 `json:"attackReadyAt"` + JumpVelocity float64 `json:"jumpVelocity"` + GatherReadyAt float64 `json:"gatherReadyAt"` View p.Character `json:"view"` Account string `json:"account"` @@ -526,7 +527,7 @@ func (w *World) Intent(id string, i p.Intent) error { } c.View.ACK = i.Seq if HouseID(c) != "" { - return errors.New("leave the house to use world actions") + return w.houseIntent(c, i) } 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 @@ -791,6 +792,8 @@ func (w *World) Advance(now time.Time, dt float64) { } if HouseID(c) == "" { w.moveCharacter(c, dt) + } else { + w.moveHouse(c, dt) } for _, ch := range w.neighbors(c.View.Entity.Position) { active[ch.Key] = true @@ -859,6 +862,7 @@ func (w *World) Advance(now time.Time, dt float64) { func (w *World) Snapshot(id string, known map[string]bool) p.Snapshot { c := w.Characters[id] s := p.Snapshot{Type: "snapshot", Version: 1, Tick: w.Tick, World: w.Info(), Self: c.View, Message: c.Message, Entities: []p.Entity{}, Chunks: []p.Chunk{}, ChunkKeys: []string{}, UnavailableResources: []string{}} + s.House = w.HouseSnapshot(c) s.GatherRisks = map[string]p.GatheringRisk{} allowed := map[string]bool{} for _, ch := range w.neighbors(c.View.Entity.Position) { diff --git a/server/internal/protocol/generated.go b/server/internal/protocol/generated.go index 160e93f..81cb30b 100644 --- a/server/internal/protocol/generated.go +++ b/server/internal/protocol/generated.go @@ -725,6 +725,7 @@ type Snapshot struct { Chunks []Chunk `json:"chunks"` Entities []Entity `json:"entities"` GatherRisks map[string]GatheringRisk `json:"gatherRisks,omitempty"` + House *HouseScene `json:"house,omitempty"` Message string `json:"message"` ProjectileVisuals []ProjectileVisual `json:"projectileVisuals,omitempty"` Self Character `json:"self"` @@ -756,6 +757,25 @@ type GatheringRisk struct { Seconds float64 `json:"seconds"` } +type HouseScene struct { + Furniture []RoomFurniture `json:"furniture"` + ID string `json:"id"` + Name string `json:"name"` + People []Entity `json:"people"` + Size float64 `json:"size"` +} + +type RoomFurniture struct { + Container bool `json:"container"` + Depth float64 `json:"depth"` + Height float64 `json:"height"` + ID string `json:"id"` + Name string `json:"name"` + Width float64 `json:"width"` + X float64 `json:"x"` + Z float64 `json:"z"` +} + type ProjectileVisual struct { At float64 `json:"at"` Destination Vec3 `json:"destination"` @@ -788,6 +808,7 @@ type Character struct { HasKeystone bool `json:"hasKeystone"` HealthChoices int64 `json:"healthChoices"` HouseID *string `json:"houseId,omitempty"` + HousePosition *Vec3 `json:"housePosition,omitempty"` Inventory map[string]int64 `json:"inventory"` Items []ItemInstance `json:"items"` Kills int64 `json:"kills"` diff --git a/server/internal/store/house_lifecycle.go b/server/internal/store/house_lifecycle.go index 29bd1da..29c8009 100644 --- a/server/internal/store/house_lifecycle.go +++ b/server/internal/store/house_lifecycle.go @@ -104,19 +104,7 @@ func (d *DB) syncHousing(ctx context.Context, tx *sql.Tx, w *game.World) error { } } } - 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) @@ -149,5 +137,5 @@ func (d *DB) syncHousing(ctx context.Context, tx *sql.Tx, w *game.World) error { } } } - return nil + return d.syncHouseRooms(ctx, tx, w) } diff --git a/server/internal/store/house_presence.go b/server/internal/store/house_presence.go new file mode 100644 index 0000000..ea49986 --- /dev/null +++ b/server/internal/store/house_presence.go @@ -0,0 +1,94 @@ +package store + +import ( + "aeternalis/server/internal/game" + p "aeternalis/server/internal/protocol" + "context" + "database/sql" + "encoding/json" +) + +func (d *DB) syncHouseRooms(ctx context.Context, tx *sql.Tx, w *game.World) error { + for id, c := range w.Characters { + var world, state string + if e := tx.QueryRowContext(ctx, d.q(`SELECT world_id,state FROM character_records WHERE character_id=?`), id).Scan(&world, &state); e != nil { + return e + } + if world != w.ID || state == "transit" { + continue + } + 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.Sheltered || c.View.Entity.State == "dead" || c.View.RemainingSeconds <= 0 || !w.IsHub() { + game.LeaveHouse(c) + } else { + c.HouseRoom = w.HouseScene(h.View) + if c.View.HousePosition == nil || !w.HousePositionValid(c.HouseRoom, *c.View.HousePosition) { + pos, ok := w.HouseSpawn(c.HouseRoom) + if !ok { + game.LeaveHouse(c) + } else { + c.View.HousePosition = &pos + c.JumpVelocity = 0 + } + } + } + } + if game.HouseID(c) == "" { + if _, e := tx.ExecContext(ctx, d.q(`DELETE FROM house_visitors WHERE character_id=? AND world_id=?`), id, w.ID); e != nil { + return e + } + continue + } + v := c.View.Entity + v.Position = *c.View.HousePosition + raw, e := json.Marshal(v) + if e != nil { + return e + } + if _, e = tx.ExecContext(ctx, d.q(`INSERT INTO house_visitors(character_id,house_id,world_id,updated_at,entity) VALUES(?,?,?,`+d.now()+`,?) ON CONFLICT(character_id) DO UPDATE SET house_id=excluded.house_id,world_id=excluded.world_id,updated_at=excluded.updated_at,entity=excluded.entity`), id, game.HouseID(c), w.ID, string(raw)); e != nil { + return e + } + } + rooms := map[string][]p.Entity{} + for _, c := range w.Characters { + house := game.HouseID(c) + if house == "" || c.HouseRoom == nil { + continue + } + if _, ok := rooms[house]; !ok { + rooms[house] = []p.Entity{} + rows, e := tx.QueryContext(ctx, d.q(`SELECT v.entity FROM house_visitors v JOIN worlds w ON w.id=v.world_id WHERE v.house_id=? AND v.updated_at>=`+d.now()+`-5 AND w.owner<>'' AND w.lease_until>=`+d.now()+` ORDER BY v.character_id LIMIT 256`), house) + if e != nil { + return e + } + for rows.Next() { + var raw string + var v p.Entity + if e = rows.Scan(&raw); e != nil { + rows.Close() + return e + } + if e = json.Unmarshal([]byte(raw), &v); e != nil { + rows.Close() + return e + } + rooms[house] = append(rooms[house], v) + } + e = rows.Err() + rows.Close() + if e != nil { + return e + } + } + c.HouseRoom.People = rooms[house] + } + return nil +} diff --git a/server/internal/store/house_presence_test.go b/server/internal/store/house_presence_test.go new file mode 100644 index 0000000..ee20fad --- /dev/null +++ b/server/internal/store/house_presence_test.go @@ -0,0 +1,114 @@ +package store + +import ( + "aeternalis/server/content" + "aeternalis/server/internal/game" + p "aeternalis/server/internal/protocol" + "context" + "errors" + "path/filepath" + "testing" + "time" +) + +func TestHouseVisitorsAcrossHubOwners(t *testing.T) { + ctx := context.Background() + db, e := Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "visitors.db"))) + if e != nil { + t.Fatal(e) + } + defer db.Close() + b, _ := content.Load() + now := time.Now() + makeHub := func(id string) (*game.World, *Lease, *game.Character) { + t.Helper() + w := game.New(id, 1, now, b) + c, e := w.Join(id, id) + if e != nil { + t.Fatal(e) + } + 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) + } + return w, l, c + } + a, al, owner := makeHub("hub-a") + bworld, bl, guest := makeHub("hub-b") + act := func(w *game.World, l *Lease, 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) + } + } + save := func(w *game.World, l *Lease) { + t.Helper() + if e := l.Save(ctx, w, ""); e != nil { + t.Fatal(e) + } + } + act(a, al, owner, HouseRequest{Op: "create", Name: "Shared room"}) + directory, e := db.HouseState(ctx, a, owner.Account) + if e != nil { + t.Fatal(e) + } + house := directory.Houses[0].ID + act(a, al, owner, HouseRequest{Op: "enter", HouseID: house}) + act(a, al, owner, HouseRequest{Op: "invite", HouseID: house, Target: guest.View.Entity.ID, Role: "guest"}) + act(bworld, bl, guest, HouseRequest{Op: "enter", HouseID: house}) + if e := bworld.Intent(guest.View.Entity.ID, p.Intent{Seq: 1, Op: "move", X: 1}); e != nil { + t.Fatal(e) + } + bworld.Advance(now.Add(100*time.Millisecond), .1) + save(bworld, bl) + save(a, al) + scene := a.HouseSnapshot(owner) + if scene == nil || len(scene.People) != 2 { + t.Fatal("cross-hub visitor missing", scene) + } + found := false + for _, v := range scene.People { + if v.ID == guest.View.Entity.ID { + found = true + if v.Position != *guest.View.HousePosition { + t.Fatal("visitor used hub coordinates") + } + } + } + if !found { + t.Fatal("guest missing") + } + if _, exists := a.Characters[guest.View.Entity.ID]; exists { + t.Fatal("replicated visitor into another simulation owner") + } + stale := *bl + stale.Revision-- + if e := stale.HouseAction(ctx, bworld, guest.Account, HouseRequest{RequestID: game.ID(), Op: "leave"}); !errors.Is(e, ErrOwnership) { + t.Fatal("unfenced visitor change", e) + } + if game.HouseID(guest) != house { + t.Fatal("rollback published eviction") + } + act(a, al, owner, HouseRequest{Op: "invite", HouseID: house, Target: guest.View.Entity.ID, Role: "remove"}) + save(bworld, bl) + save(a, al) + if guest.View.HousePosition != nil || game.HouseID(guest) != "" || len(a.HouseSnapshot(owner).People) != 1 { + t.Fatal("revoked guest retained room presence") + } + act(a, al, owner, HouseRequest{Op: "leave"}) + if owner.HouseRoom != nil || owner.View.HousePosition != nil { + t.Fatal("exit retained cached room") + } + var n int + if e = db.sql.QueryRow(`SELECT COUNT(*) FROM house_visitors`).Scan(&n); e != nil || n != 0 { + t.Fatal("stale presence retained", n, e) + } +} diff --git a/server/internal/store/housing.go b/server/internal/store/housing.go index 63eee64..754c9fa 100644 --- a/server/internal/store/housing.go +++ b/server/internal/store/housing.go @@ -308,7 +308,13 @@ func (d *DB) mutateHouse(ctx context.Context, tx *sql.Tx, w *game.World, c *game return houseError("leave the current house first") } id := h.View.ID + pos, ok := w.HouseSpawn(w.HouseScene(h.View)) + if !ok { + return houseError("no clear space to enter this house") + } c.View.HouseID = &id + c.View.HousePosition = &pos + c.JumpVelocity = 0 c.View.DestroyKey = nil c.View.Casting = nil return nil diff --git a/server/internal/store/housing_test.go b/server/internal/store/housing_test.go index 0cf60f9..542d1fd 100644 --- a/server/internal/store/housing_test.go +++ b/server/internal/store/housing_test.go @@ -110,7 +110,7 @@ func testHousingLifecycle(t *testing.T, dsn string) { 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 { + if e := w.Intent(owner.View.Entity.ID, p.Intent{Seq: 1, Op: "attack"}); 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 { diff --git a/server/internal/store/portal.go b/server/internal/store/portal.go index 9918255..45a99d2 100644 --- a/server/internal/store/portal.go +++ b/server/internal/store/portal.go @@ -67,6 +67,8 @@ 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_visitors(character_id TEXT PRIMARY KEY,house_id TEXT NOT NULL,world_id TEXT NOT NULL,updated_at BIGINT NOT NULL,entity TEXT NOT NULL)`, + `CREATE INDEX IF NOT EXISTS visitors_house ON house_visitors(house_id)`, `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))`, diff --git a/server/internal/store/store.go b/server/internal/store/store.go index d329c8a..a824dc5 100644 --- a/server/internal/store/store.go +++ b/server/internal/store/store.go @@ -205,6 +205,9 @@ func (l *Lease) save(ctx context.Context, w *game.World, claimID string, command if err = d.applyHouse(ctx, tx, w, housing); err != nil { return err } + if err = d.syncHouseRooms(ctx, tx, w); err != nil { + return err + } } if err = d.syncTitles(ctx, tx, w); err != nil { return err @@ -259,7 +262,13 @@ func (l *Lease) save(ctx context.Context, w *game.World, claimID string, command } l.Revision++ for id, c := range w.Characters { + if game.HouseID(live.Characters[id]) != game.HouseID(c) { + live.Characters[id].MoveX = 0 + live.Characters[id].MoveZ = 0 + live.Characters[id].JumpVelocity = 0 + } live.Characters[id].View = c.View + live.Characters[id].HouseRoom = c.HouseRoom } live.PendingTitles = nil live.Saved()