From 70d08b0d32830e8e3ae77ccca28ceb697e1f96bf Mon Sep 17 00:00:00 2001 From: dingo Date: Wed, 9 Sep 2026 08:27:21 -0400 Subject: [PATCH] Add biome revisions readable content and visible projectile outcomes --- client/src/content-editor.css | 1 + client/src/content-editor.ts | 56 +++++++--- client/src/generated.ts | 86 +++++++++------ client/src/projectile-presentation.ts | 58 ++++++++++ client/src/world-view.ts | 6 +- docs/ARCHITECTURE.md | 12 +++ docs/CONTENT-PROJECTILE-FEEDBACK.md | 75 +++++++++++++ planning/ENVIRONMENT-BACKLOG.md | 30 ++++++ planning/SYSTEMS-ROADMAP.md | 6 ++ planning/VISION.md | 6 ++ schemas/protocol.json | 39 +++++-- server/content/balance.yaml | 6 +- server/content/combat.go | 33 +++--- server/content/gathering.go | 36 +++++-- server/internal/game/biome_revision_test.go | 52 +++++++++ server/internal/game/biomes.go | 6 +- server/internal/game/combat.go | 33 +++++- server/internal/game/combat_test.go | 29 +++++ server/internal/game/mobs.go | 1 + server/internal/game/world.go | 20 +++- server/internal/protocol/generated.go | 106 +++++++++++-------- server/internal/store/biome_revision_test.go | 78 ++++++++++++++ server/internal/store/catalog.go | 9 ++ server/internal/store/catalog_preview.go | 47 +++++++- 24 files changed, 703 insertions(+), 128 deletions(-) create mode 100644 client/src/projectile-presentation.ts create mode 100644 docs/CONTENT-PROJECTILE-FEEDBACK.md create mode 100644 planning/ENVIRONMENT-BACKLOG.md create mode 100644 server/internal/game/biome_revision_test.go create mode 100644 server/internal/store/biome_revision_test.go diff --git a/client/src/content-editor.css b/client/src/content-editor.css index 6fee8c9..eb18a56 100644 --- a/client/src/content-editor.css +++ b/client/src/content-editor.css @@ -1,3 +1,4 @@ .catalog-editor{padding:20px;min-width:0}.catalog-heading,.catalog-tabs{display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin-bottom:20px}.catalog-heading h2{font-size:20px;margin-right:auto}.catalog-tabs button[aria-pressed=true]{background:#215944;color:white}.catalog-list{display:grid;gap:12px}.catalog-list>.button{justify-self:start}.catalog-definition{padding:14px;border:1px solid var(--line);border-radius:5px;min-width:0;overflow-wrap:anywhere;font-size:12px;line-height:1.7}.catalog-definition summary{cursor:pointer;font-size:13px;font-weight:600}.catalog-definition p{margin-top:10px}.catalog-form{margin-top:24px;padding-top:20px;border-top:1px solid var(--line);max-width:900px}.catalog-form>h3{margin-bottom:12px}.catalog-form label{display:flex;flex-direction:column;gap:8px;font-size:12px;margin:14px 0;min-width:0}.catalog-form input,.catalog-form select,.catalog-form textarea{width:100%;min-width:0}.catalog-fields{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:0 14px}.catalog-fields label:has(textarea){grid-column:1/-1}.catalog-repeatable,.catalog-title-choices{padding:14px;min-width:0;border:1px solid var(--line);margin:20px 0}.catalog-repeatable legend,.catalog-title-choices legend{font-size:13px;padding:0 8px}.catalog-row{display:flex;align-items:center;gap:12px;border-bottom:1px solid var(--line);margin-bottom:12px}.catalog-row>.catalog-fields{flex:1}.catalog-row>.button{font-size:11px;padding:8px}.catalog-title-choices{max-height:260px;overflow:auto}.catalog-title-choices label{flex-direction:row-reverse;justify-content:flex-end;align-items:center}.catalog-title-choices input{width:18px;height:18px}.catalog-form footer{display:flex;justify-content:flex-end;gap:12px;margin-top:20px}.catalog-form>.muted{line-height:1.7}.catalog-form details{margin:14px 0}.catalog-form .error{margin-top:14px}.table-tools[hidden]{display:none}@media(max-width:720px){.control-sidebar nav{grid-template-columns:repeat(4,minmax(0,1fr))}.catalog-editor{padding:12px}.catalog-fields{grid-template-columns:1fr}.catalog-row{align-items:flex-end}.catalog-tabs{gap:6px}.catalog-tabs button{padding:9px;font-size:11px}} .player-content{padding:0 0 20px;border-bottom:1px solid var(--line)}.player-content form{display:grid;gap:12px}.player-content label{display:flex;flex-direction:column;gap:7px;font-size:12px;min-width:0}.player-content input,.player-content select,.player-content textarea{width:100%;min-width:0;max-width:100%}.player-content .muted{font-size:12px;line-height:1.7}.player-content [hidden]{display:none}.player-content .button{justify-self:start} .catalog-preview:not(:empty){margin:18px 0;padding:16px;border:1px solid var(--line);border-radius:5px;line-height:1.7;font-size:13px}.catalog-preview h4{margin-bottom:10px}.catalog-preview pre{overflow:auto;max-height:320px;font-size:12px}.catalog-form footer{flex-wrap:wrap}.catalog-form:focus{outline:none} +.catalog-facts{display:grid;grid-template-columns:minmax(120px,1fr) minmax(0,2fr);gap:8px 18px;margin:14px 0}.catalog-facts dt{color:var(--muted);font-weight:500}.catalog-facts dd{margin:0;min-width:0}.catalog-values{padding-left:18px;display:grid;gap:8px}.catalog-facts .catalog-facts{margin:0}.catalog-definition section{padding:12px 0;border-top:1px solid var(--line)}@media(max-width:600px){.catalog-facts{grid-template-columns:1fr;gap:4px}.catalog-facts dd{margin-bottom:10px}} diff --git a/client/src/content-editor.ts b/client/src/content-editor.ts index c8aa3e8..b230c31 100644 --- a/client/src/content-editor.ts +++ b/client/src/content-editor.ts @@ -15,7 +15,7 @@ function field(label:string,input:HTMLElement){const wrap=node('label',label);wr function text(value='',max=80){const i=node('input');i.value=value;i.maxLength=max;i.required=true;return i;} function number(value:number,min=0,max=1000000,step='any'){const i=text(String(value));i.type='number';i.min=String(min);i.max=String(max);i.step=step;return i;} function select(keys:string[],value=''){const i=node('select');for(const key of keys)i.append(new Option(statLabel(key),key));i.value=keys.includes(value)?value:keys[0];return i;} -function identity(){const group=node('div','','catalog-fields'),name=text(),description=node('textarea');description.maxLength=500;description.rows=3;group.append(field('Name',name),field('Description',description),node('p','A permanent ID is assigned automatically when you publish.','muted'));return {node:group,read:()=>({name:name.value.trim(),description:description.value.trim()})};} +function identity(initial?:{name:string;description:string}){const group=node('div','','catalog-fields'),name=text(initial?.name??''),description=node('textarea');description.value=initial?.description??'';description.maxLength=500;description.rows=3;group.append(field('Name',name),field('Description',description),node('p',initial?'This biome keeps its identity. Publishing creates its next revision.':'A permanent ID is assigned automatically when you publish.','muted'));return {node:group,read:()=>({name:name.value.trim(),description:description.value.trim()})};} function repeat(title:string,addLabel:string,make:(value?:T)=>{node:HTMLElement;read:()=>T},initial:T[]=[],max=64){ const group=node('fieldset','','catalog-repeatable'),rows=node('div'),entries:{node:HTMLElement;read:()=>T}[]=[];group.append(node('legend',title),rows); const add=button(addLabel,()=>append());group.append(add); @@ -44,7 +44,7 @@ function form(title:string,op:string,payload:()=>object){ reason.required=true;reason.minLength=5;reason.maxLength=240;reason.rows=2;error.setAttribute('role','alert'); const focus=registerMenu(form,()=>{editing=false;refresh.disabled=saving;forms.replaceChildren();focus.dispose()}); const save=node('button','Publish changes','button');save.type='submit';const cancel=button('Cancel',()=>focus.close()),check=button('Preview changes',()=>void previewChanges());const footer=node('footer');footer.append(cancel,check,save); - form.append(node('h3',title),node('p',`Based on catalog version ${expectedVersion}. Published definitions and sets cannot be edited or removed.`,'muted'),fields,field('Reason for change',reason),error,preview,footer);forms.replaceChildren(form); + form.append(node('h3',title),node('p',`Based on catalog version ${expectedVersion}. Biome edits publish new revisions; other definitions remain immutable.`,'muted'),fields,field('Reason for change',reason),error,preview,footer);forms.replaceChildren(form); const previous=document.activeElement;queueMicrotask(()=>{if(form.isConnected)focus.opened(previous)}); form.addEventListener('input',()=>preview.replaceChildren());form.addEventListener('change',()=>preview.replaceChildren()); fields.addEventListener('click',event=>{if((event.target as HTMLElement).closest('button'))preview.replaceChildren()}); @@ -64,13 +64,13 @@ function form(title:string,op:string,payload:()=>object){ function previewView(result:ContentPreview){ const root=node('div'),r=result.resolved;root.append(node('h4','Validated publication preview'),node('p',`Version ${result.basedOnVersion} → ${result.proposedVersion}. Nothing has been published.`)); const definition=r.title??r.item??r.requirementSet??r.effectSet??r.gatheringSkill??r.resource??r.biome??r.consumable??r.attack??r.mob??r.loot??r.spawn; - if(definition)root.append(node('strong',definition.name),node('p',definition.description),node('p','Permanent ID assigned on publication.','muted')); + if(definition)root.append(node('strong',definition.name),node('p',definition.description),node('p',r.targetId?`Revision ${r.biome?.revision} of the existing biome`:'Permanent ID assigned on publication.','muted')); const requirements=r.title?.requirements??r.requirementSet?.requirements; if(requirements)root.append(node('p',requirements.map(v=>`${statLabel(v.metric)} ≥ ${v.atLeast}`).join(' / '))); if(r.item)root.append(node('p',`Requires level ${r.item.requirements.level}; ${Object.entries(r.item.requirements.stats??{}).map(([key,n])=>`${statLabel(key)} ≥ ${n}`).join(' / ')}`),node('p',`Required titles: ${(r.item.requirements.titles??[]).join(', ')||'None'}`)); const modifiers=r.title?.effects.modifiers??r.item?.modifiers??r.effectSet?.modifiers;if(modifiers)root.append(modifiersView(modifiers)); - if(r.gatheringSkill||r.resource||r.biome||r.consumable||r.attack||r.mob||r.loot||r.spawn)root.append(node('pre',JSON.stringify(r.gatheringSkill??r.resource??r.biome??r.consumable??r.attack??r.mob??r.loot??r.spawn,null,2))); - if(r.stats){root.append(node('p','Validated base values and primary-to-derived coefficients.'));const details=node('details');details.append(node('summary','Review stat formulas'),node('pre',JSON.stringify(r.stats,null,2)));root.append(details);} + if(r.gatheringSkill||r.resource||r.biome||r.consumable||r.attack||r.mob||r.loot||r.spawn)root.append(readableDefinition(r.gatheringSkill??r.resource??r.biome??r.consumable??r.attack??r.mob??r.loot??r.spawn)); + if(r.stats){root.append(node('p','Validated base values and primary-to-derived coefficients.'));const details=node('details');details.append(node('summary','Review stat formulas'),readableDefinition(r.stats));root.append(details);} return root; } function titleForm(){ @@ -124,9 +124,34 @@ export function hasCatalogDraft(){return editing;} function contentChoice(values:{id:string;name:string}[]) { const input=node('select');input.required=true;for(const v of values)input.append(new Option(v.name,v.id));return input; } -function gatheringForm(kind:string){ + +function readableDefinition(value:unknown, context=''):HTMLElement { + const names = [...catalog.items,...catalog.titles,...(catalog.gathering?.skills??[]),...(catalog.gathering?.resources??[]),...(catalog.gathering?.biomes??[]),...(catalog.gathering?.consumables??[]),...(catalog.combat?.attacks??[]),...(catalog.combat?.mobs??[]),...(catalog.combat?.loot??[])]; + const reference=(v:string)=>names.find(n=>n.id===v)?.name??statLabel(v); + if(Array.isArray(value)) { + const list=node('ul','','catalog-values'); + if(!value.length)list.append(node('li','None')); + for(const entry of value){const row=node('li');row.append(readableDefinition(entry,context));list.append(row)}return list; + } + if(value!==null && typeof value==='object') { + const labels:Record={baseXp:'XP to level 2',xpPerLevel:'Additional XP per level',maxLevel:'Maximum level',skillId:'Gathering profession',requiredLevel:'Required level',amount:'Yield / quantity',seconds:'Duration / interval (seconds)',respawnSeconds:'Respawn (seconds)',density:'Nodes per chunk',biomes:'Biomes',resources:'Resources',color:'Terrain color',weight:'Relative weight',revision:'Revision',speed:'Speed (m/s)',dexteritySpeed:'Extra m/s per Dexterity',strengthSpeed:'Extra m/s per Strength',cooldown:'Cooldown (seconds)',stamina:'Stamina cost',range:'Range (m)',radius:'Radius (m)',duration:'Area duration (seconds)',interval:'Pulse interval (seconds)',attackId:'Attack profile',lootId:'Loot table',mobId:'Mob',hp:'Base health',xp:'XP reward',aggroRange:'Detection range (m)',leashRange:'Pursuit limit (m)',scalePerDay:'World-age scaling per day',minPlayerDistance:'Minimum spawn distance (m)',respawn:'Respawn (seconds)',chance:'Chance (%)',group:'Weighted group',item:'Item',stat:'Power stat',multiplier:'Power multiplier'}; + const fields=node('dl','','catalog-facts'); + const record=value as Record; + for(const [key,raw] of Object.entries(record)) { + if(['id','name','description'].includes(key))continue; + let item=raw; + if(key==='resources'&&item==null&&typeof record.id==='string')item=(catalog.gathering?.resources??[]).filter(r=>r.biomes.includes(record.id as string)).map(r=>r.id); + if(key==='biomes'&&'skillId' in record&&record.id) item=(catalog.gathering?.biomes??[]).filter(b=>b.resources!=null?b.resources.includes(record.id as string):(raw as string[]).includes(b.id)).map(b=>b.id); + const term=node('dt',labels[key]??statLabel(key)),detail=node('dd');detail.append(readableDefinition(item,key));fields.append(term,detail); + }return fields; + } + if(value==null||value==='')return node('span',context==='group'?'Independent':'None'); + if(typeof value==='string')return node('span',context==='color'?value:reference(value)); + return node('span',typeof value==='boolean'?(value?'Yes':'No'):String(value)); +} +function gatheringForm(kind:string,existing?:NonNullable['biomes'][number]){ if(editing||saving){show('Finish or cancel the open draft first.');return;} - const values=identity(),g=catalog.gathering; + const values=identity(existing),g=catalog.gathering; if(kind==='gathering'){ const base=number(20,1,1000000,'1'),step=number(10,0,1000000,'1'),max=number(1000,2,10000,'1'); const fields=form('Create gathering skill','create-gathering-skill',()=>({gatheringSkill:{...values.read(),baseXp:Number(base.value),xpPerLevel:Number(step.value),maxLevel:Number(max.value)}})); @@ -139,9 +164,12 @@ function gatheringForm(kind:string){ const fields=form('Create resource','create-resource',()=>{const biomes=checks.filter(v=>v.input.checked).map(v=>v.id);if(!biomes.length)throw new Error('Choose at least one biome.');return{resource:{...values.read(),skillId:skill.value,model:model.value,output:output.value,requiredLevel:Number(level.value),amount:Number(amount.value),xp:Number(xp.value),seconds:Number(seconds.value),respawnSeconds:Number(respawn.value),density:Number(density.value),biomes}}}); fields.append(values.node,field('Gathering skill',skill),field('Model preset',model),field('Gathered material',output),field('Required effective skill level',level),field('Base amount per success',amount),field('Base profession XP per success',xp),field('Gathering interval (seconds)',seconds),field('Respawn interval (seconds)',respawn),field('Nodes per matching chunk (before forest density bonus)',density),biomeFields,node('p','Players may risk attempts up to 20 levels below this requirement. Failures can destroy the node until respawn and inflict damage/fatigue. New definitions appear in unexplored chunks of new-generation worlds; explored layouts stay fixed. Models use existing placeholders until milestone 4.5.','muted')); }else if(kind==='biomes'){ - const color=text('#426044',7);color.type='color';const weight=number(3,1,100,'1'); - const fields=form('Create biome','create-biome',()=>({biome:{...values.read(),color:color.value,weight:Number(weight.value)}})); - fields.append(values.node,field('Terrain color',color),field('Relative occurrence weight',weight),node('p','Applies to unexplored chunks. Publish resource definitions referencing this biome to populate it. Mob populations arrive in milestone 4.','muted')); + const color=text(existing?.color??'#426044',7);color.type='color';const weight=number(existing?.weight??3,1,100,'1'); + const resources=node('fieldset','','catalog-title-choices');resources.append(node('legend','Resources in this biome')); + const selected=existing?.resources??(g?.resources??[]).filter(r=>existing&&r.biomes.includes(existing.id)).map(r=>r.id); + const checks=(g?.resources??[]).map(r=>{const input=node('input');input.type='checkbox';input.checked=selected.includes(r.id);resources.append(field(`${r.name} · ${statLabel(r.model)} · level ${r.requiredLevel}`,input));return{id:r.id,input}}); + const fields=form(existing?`Edit ${existing.name} · publish revision ${(existing.revision??1)+1}`:'Create biome',existing?'update-biome':'create-biome',()=>({...existing?{targetId:existing.id}:{},biome:{...values.read(),color:color.value,weight:Number(weight.value),resources:checks.filter(c=>c.input.checked).map(c=>c.id)}})); + fields.append(values.node,field('Terrain color',color),field('Relative occurrence weight',weight),resources,node('p','Reuse any existing resource. Published biome revisions affect unexplored chunks; explored layouts remain unchanged. Adding a new resource from the resource editor also versions its selected biomes.','muted')); }else{ const seconds=number(120,1,86400),effects=modifiers(); const fields=form('Create gathering consumable','create-consumable',()=>{const mods=effects.read();if(!mods.length||mods.some(m=>!m.stat.startsWith('gathering')))throw new Error('Choose gathering level, yield, speed, or XP modifiers.');return{consumable:{...values.read(),seconds:Number(seconds.value),modifiers:mods}}}); @@ -152,7 +180,9 @@ function gatheringList(){ const labels:Record={gathering:'gathering skill',resources:'resource',biomes:'biome',consumables:'gathering consumable'}; list.append(button(`Create ${labels[section]}`,()=>gatheringForm(section))); const g=catalog.gathering;const entries=section==='gathering'?g?.skills:section==='resources'?g?.resources:section==='biomes'?g?.biomes:g?.consumables; - for(const v of entries??[]){const d=node('details','','catalog-definition');d.append(node('summary',v.name),node('p',v.description),node('pre',JSON.stringify(v,null,2)));list.append(d);} + for(const v of entries??[]){const d=node('details','','catalog-definition');d.append(node('summary',v.name),node('p',v.description),readableDefinition(v)); + if(section==='biomes') { const b=v as NonNullable['biomes'][number]; d.append(node('p',`Current revision ${b.revision??1}`),button('Edit biome',()=>gatheringForm('biomes',b)));const history=node('details');history.append(node('summary','Previous revisions'));for(const old of g?.biomeHistory??[])if(old.id===b.id){const revision=node('section');revision.append(node('h4',`Revision ${old.revision}`),readableDefinition(old));history.append(revision)}d.append(history); } + list.append(d);} } function combatForm(kind:string){ @@ -160,7 +190,7 @@ function combatForm(kind:string){ const values=identity(),c=catalog.combat; if(kind==='attacks'){ const delivery=select(['melee','projectile']),effect=select(['damage','heal']),stat=select(['meleeDamage','rangedDamage','magicDamage']); - const settings=[['multiplier','Stat multiplier',1,.01,100],['range','Range (m)',6,1,128],['cooldown','Cooldown (seconds)',1,.1,120],['stamina','Player stamina cost',0,0,10000],['speed','Projectile speed (m/s)',35,1,100],['radius','Area radius (0 = single target)',0,0,24],['duration','Area duration (0 = burst)',0,0,60],['interval','Area tick interval (seconds)',1,.2,60]] as const; + const settings=[['multiplier','Stat multiplier',1,.01,100],['range','Range (m)',6,1,128],['cooldown','Cooldown (seconds)',1,.1,120],['stamina','Player stamina cost',0,0,10000],['speed','Weapon base projectile speed (m/s)',35,1,100],['dexteritySpeed','Extra m/s per Dexterity point',.1,0,5],['strengthSpeed','Extra m/s per Strength point',.05,0,5],['radius','Area radius (0 = single target)',0,0,24],['duration','Area duration (0 = burst)',0,0,60],['interval','Area tick interval (seconds)',1,.2,60]] as const; const inputs=settings.map(([key,label,value,min,max])=>({key,label,input:number(value,min,max)})); const fields=form('Create attack profile','create-attack',()=>({attack:{...values.read(),delivery:delivery.value,effect:effect.value,stat:stat.value,...Object.fromEntries(inputs.map(v=>[v.key,Number(v.input.value)]))}})); fields.append(values.node,field('Delivery',delivery),field('Effect',effect),field('Player stat to scale',stat),...inputs.map(v=>field(v.label,v.input)),node('p','Damage targets opponents; healing targets allies. Players currently target mobs and the Harbinger, while player healing targets living players. Projectiles fly toward the selected position and can miss. Areas remain fixed at impact. Damage is sampled at attack time.','muted')); @@ -184,5 +214,5 @@ function combatList(){ const c=catalog.combat,entries=section==='attacks'?c?.attacks:section==='mobs'?c?.mobs:section==='loot'?c?.loot:c?.spawns; const labels:Record={attacks:'attack profile',mobs:'mob',loot:'loot table',spawns:'mob spawn rule'}; list.append(button(`Create ${labels[section]}`,()=>combatForm(section))); - for(const v of entries??[]){const d=node('details','','catalog-definition');d.append(node('summary',v.name),node('p',v.description),node('pre',JSON.stringify(v,null,2)));list.append(d)} + for(const v of entries??[]){const d=node('details','','catalog-definition');d.append(node('summary',v.name),node('p',v.description),readableDefinition(v));list.append(d)} } diff --git a/client/src/generated.ts b/client/src/generated.ts index 2837dac..42e5e88 100644 --- a/client/src/generated.ts +++ b/client/src/generated.ts @@ -27,20 +27,22 @@ export interface CombatContent { } export interface CombatAttack { - cooldown: number; - delivery: string; - description: string; - duration: number; - effect: string; - id: string; - interval: number; - multiplier: number; - name: string; - radius: number; - range: number; - speed: number; - stamina: number; - stat: string; + cooldown: number; + delivery: string; + description: string; + dexteritySpeed?: number; + duration: number; + effect: string; + id: string; + interval: number; + multiplier: number; + name: string; + radius: number; + range: number; + speed: number; + stamina: number; + stat: string; + strengthSpeed?: number; } export interface LootTable { @@ -106,10 +108,11 @@ export interface StatModifier { } export interface GatheringContent { - biomes: BiomeDefinition[]; - consumables: GatheringConsumable[]; - resources: ResourceDefinition[]; - skills: GatheringSkill[]; + biomeHistory?: BiomeDefinition[]; + biomes: BiomeDefinition[]; + consumables: GatheringConsumable[]; + resources: ResourceDefinition[]; + skills: GatheringSkill[]; } export interface BiomeDefinition { @@ -117,6 +120,8 @@ export interface BiomeDefinition { description: string; id: string; name: string; + resources?: string[] | null; + revision?: number; weight: number; } @@ -223,24 +228,27 @@ export interface ContentChange { resource?: ResourceDefinitionDraft; spawn?: MobSpawnDraft; stats?: ContentStatsRules; + targetId?: string; title?: TitleDraft; } export interface CombatAttackDraft { - cooldown: number; - delivery: string; - description: string; - duration: number; - effect: string; - id?: string; - interval: number; - multiplier: number; - name: string; - radius: number; - range: number; - speed: number; - stamina: number; - stat: string; + cooldown: number; + delivery: string; + description: string; + dexteritySpeed?: number; + duration: number; + effect: string; + id?: string; + interval: number; + multiplier: number; + name: string; + radius: number; + range: number; + speed: number; + stamina: number; + stat: string; + strengthSpeed?: number; } export interface BiomeDefinitionDraft { @@ -248,6 +256,8 @@ export interface BiomeDefinitionDraft { description: string; id?: string; name: string; + resources?: string[] | null; + revision?: number; weight: number; } @@ -385,6 +395,7 @@ export interface Snapshot { entities: Entity[]; gatherRisks?: { [key: string]: GatheringRisk }; message: string; + projectileVisuals?: ProjectileVisual[]; self: Character; tick: number; type: string; @@ -435,6 +446,17 @@ export interface GatheringRisk { seconds: number; } +export interface ProjectileVisual { + at: number; + destination: Vec3; + id: string; + outcome: string; + phase: string; + position: Vec3; + projectileId: string; + speed: number; +} + export interface Character { ack: number; allocatedStats: { [key: string]: number }; diff --git a/client/src/projectile-presentation.ts b/client/src/projectile-presentation.ts new file mode 100644 index 0000000..04050dd --- /dev/null +++ b/client/src/projectile-presentation.ts @@ -0,0 +1,58 @@ +import * as T from 'three'; +import type { ProjectileVisual } from './generated'; + +type Flight = { mesh:T.Mesh; start:T.Vector3; end:T.Vector3; speed:number; born:number; impact?:ProjectileVisual }; + +// Animation consumes server outcomes. It never decides whether a target was hit. +// Straight flight is isolated here so future curved/seeking paths can use the +// same launch/authoritative-impact lifecycle without changing combat ownership. +export class ProjectilePresentation { + private flights = new Map(); + private seen = new Map(); + private flashes: {mesh:T.Mesh; until:number}[] = []; + private geometry = new T.SphereGeometry(.28,8,6); + private shotMaterial = new T.MeshBasicMaterial({color:'#fff0ad'}); + private hitMaterial = new T.MeshBasicMaterial({color:'#ff794f',wireframe:true}); + private missMaterial = new T.MeshBasicMaterial({color:'#b9c6ce',wireframe:true}); + constructor(private scene:T.Scene) {} + has(id:string) { return this.flights.has(id); } + receive(events:ProjectileVisual[]) { + const now=performance.now()/1000; + for(const event of events) { + if(this.seen.has(event.id))continue; + this.seen.set(event.id,now); + if(event.phase==='launch') { + if(this.flights.size>=512)continue; + const start=new T.Vector3(event.position.x,event.position.y,event.position.z),end=new T.Vector3(event.destination.x,event.destination.y,event.destination.z); + const mesh=new T.Mesh(this.geometry,this.shotMaterial);mesh.position.copy(start);this.scene.add(mesh); + this.flights.set(event.projectileId,{mesh,start,end,speed:event.speed,born:now}); + } else { + const flight=this.flights.get(event.projectileId); + if(flight) { flight.end.set(event.position.x,event.position.y,event.position.z);flight.impact=event; } + else this.flash(event,now); + } + } + // Event IDs are monotonic per world, and the server retains only two seconds. + // Bound deduplication memory even for long sessions. + while(this.seen.size>4096)this.seen.delete(this.seen.keys().next().value!); + } + private flash(event:ProjectileVisual,now:number) { + if(event.outcome==='cancelled'||this.flashes.length>=256)return; + const mesh=new T.Mesh(this.geometry,event.outcome==='hit'?this.hitMaterial:this.missMaterial); + mesh.position.set(event.position.x,event.position.y,event.position.z);mesh.scale.setScalar(event.outcome==='hit'?4:2); + this.scene.add(mesh);this.flashes.push({mesh,until:now+.4}); + } + update() { + const now=performance.now()/1000; + for(const [id,f] of this.flights) { + const duration=Math.max(.1,f.start.distanceTo(f.end)/Math.max(1,f.speed)); + const t=Math.min(1,(now-f.born)/duration); + f.mesh.position.lerpVectors(f.start,f.end,t); + if(t>=1&&(f.impact||now-f.born>duration+2)) { + if(f.impact)this.flash(f.impact,now); + this.scene.remove(f.mesh);this.flights.delete(id); + } + } + this.flashes=this.flashes.filter(f=>{if(now(); readonly batches = new Map(); @@ -181,12 +183,13 @@ export class WorldView { } update(snapshot: Snapshot) { this.snapshot = snapshot; + this.projectiles.receive(snapshot.projectileVisuals??[]); if (!this.initialized) this.addChunks([], []); this.addChunks(snapshot.chunks, snapshot.chunkKeys); const unavailable = new Set(snapshot.unavailableResources); const resources = [...this.chunks.values()].flatMap(c => c.data.resources).filter(r => !unavailable.has(r.id)); snapshot.entities = [...snapshot.entities, ...resources]; - this.updateEntities(snapshot.entities); + this.updateEntities(snapshot.entities.filter(e=>e.kind!=='projectile'||!this.projectiles.has(e.id))); const p = snapshot.self.entity.position; this.aim.set(p.x, p.y, p.z); if (!this.initialized || this.position.distanceTo(this.aim) > 20) { this.position.copy(this.aim); this.focus.copy(this.aim); this.initialized = true; } @@ -212,6 +215,7 @@ export class WorldView { start() { this.renderer.setAnimationLoop(() => { const dt = Math.min(this.clock.getDelta(), 0.05); + this.projectiles.update(); // Presentation interpolation follows server positions; it never changes authoritative movement. this.position.lerp(this.aim, 1 - Math.exp(-14 * dt)); this.focus.lerp(this.position, 1 - Math.exp(-8 * dt)); diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 67f7419..894e314 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -177,6 +177,18 @@ within a world fail restoration. Materials and consumables remain quantity stack ## Combat and mobs +Biomes now retain a stable ID with server-assigned revisions and archived resource +assignments. Explicit resource ID lists replace reverse resource-to-biome lookup +for revised/new biomes; legacy lists are resolved on first edit. New resource +publication revisions its selected biomes in the same catalog transaction. +Explored layouts remain snapshots and do not regenerate when a biome changes. + +Projectile speed samples weapon settings and final Dexterity/Strength at firing. +A bounded two-second launch/impact journal accompanies snapshots so short flights +are visible even if they complete between publications. Client presentation +deduplicates these events; only the Go collision path determines outcomes. The +journal is presentation history, not an input command or reward queue. + Combat attack definitions are copied into weapon and mob instances. Go resolves straight projectiles with swept target collision and terrain obstruction, and bounded stationary damage/healing areas. Living-source checks preserve death and diff --git a/docs/CONTENT-PROJECTILE-FEEDBACK.md b/docs/CONTENT-PROJECTILE-FEEDBACK.md new file mode 100644 index 0000000..c4ada13 --- /dev/null +++ b/docs/CONTENT-PROJECTILE-FEEDBACK.md @@ -0,0 +1,75 @@ +# Control and projectile feedback slice + +September 9 follow-up to milestone 4, before milestone 4.5 presentation work. + +## Readable Control and versioned biomes + +Content definitions and publication previews use labeled fields, nested lists, +and resolved reference names. Stat formula previews no longer display JSON. + +Create a biome by selecting existing resources, including resources first made +for other biomes. Edit biome publishes the next numbered revision with the same +server-created permanent ID. Previous revisions remain readable in the biome's +history. Replays cannot create extra revisions; stale catalog edits are rejected. +Empty selections are supported. Resources are referenced, never duplicated. + +The resource editor also updates the selected biomes when creating a new resource, +archiving their previous assignments and incrementing their revisions. Legacy +biomes derive initial assignments from existing resource definitions. Explicit +biome resource lists govern new terrain generation afterward. The history is +bounded to 1,024 archived revisions across the catalog; no automatic deletion. + +Explored chunks keep saved resources, biome name/color, geometry, and depletion. +Changes apply to unexplored chunks of the current generator. Legacy generator-1 +worlds retain their legacy node generation. Mob biome references keep their stable +IDs; new biome revisions do not break those references. Other content types +continue to use the existing immutable-definition workflow. + +## Visible projectile launches and outcomes + +The server retains a bounded two-second history of launches and impacts, so a +flight that completes between snapshots can still be presented. The browser +animates a bright projectile toward the last selected target position and displays +an orange hit flash or gray miss/terrain flash from the server's outcome. No client +prediction awards damage. For extremely short flights, animation has a 100ms +minimum so it can be seen; this does not delay authoritative combat resolution. + +Attack authoring now has weapon base speed, Dexterity contribution, and Strength +contribution. Player flight speed is sampled when fired: + +`clamp(base speed + final Dexterity × dexterity coefficient + final Strength × strength coefficient, 1, 100) m/s` + +New default profiles use provisional coefficients 0.1 and 0.05. Existing acquired +weapons and published profiles retain their copied settings; missing coefficients +mean zero. Create a new attack profile and weapon to use the new coefficients. +Changing stats or equipment after firing cannot change that projectile's speed. +Mob projectiles currently use the attack's base speed; mob primary stats are not +implemented. All damage, swept collision, terrain collision, and misses remain Go-owned. + +The launch/impact event lifecycle and presentation module are foundations for +curved and seeking trajectories. Those path types, turn limits, target-loss rules, +and their authoring controls remain future work; current shots stay straight and +can be avoided by moving out of their path. + +## Manual playtest + +1. Browse Gathering, Resources, Biomes, Attacks, Mobs, Loot, and Spawns. Definitions + and previews should read as labeled values with names, including in dark mode. +2. Create a biome selecting an existing Young tree and ore. Check that Resources + still has one copy of each. Edit the biome, deselect ore, and publish. Confirm + the same biome identity, next revision, and original assignment in history. +3. Visit unexplored regions in a current-generation world. New assignments apply; + revisiting previously explored regions after restart keeps existing nodes. +4. Create an attack with slow base speed and nonzero Dexterity/Strength coefficients. + Create and equip a weapon using it. Shoot a moving mob: watch travel, a confirmed + hit flash or miss flash, and corresponding HP. Test a close target as well. +5. Change the character's stats before firing again. New shots use the new speed; + a shot already traveling keeps the sampled speed. Opening a menu stops auto-fire. + +Server checks cover revision preview/publication/replay/conflict, resource reuse, +empty selections, unknown references, saved explored layouts, speed sampling, and +launch/impact events for a flight shorter than a snapshot interval. Routine +Playwright runs remain deferred; the user manually tests this build. + +The environment reference and meaningful obstacle jumping are recorded in +[the environment backlog](../planning/ENVIRONMENT-BACKLOG.md). diff --git a/planning/ENVIRONMENT-BACKLOG.md b/planning/ENVIRONMENT-BACKLOG.md new file mode 100644 index 0000000..111cb48 --- /dev/null +++ b/planning/ENVIRONMENT-BACKLOG.md @@ -0,0 +1,30 @@ +# Environment depth and traversal backlog + +Deferred by the user on September 9 while Control, combat presentation, and the +agreed milestone sequence continue. This is not implemented terrain behavior. + +Visual direction from the supplied reference: a broad, deeply cut forested valley, +layered ridgelines and distant mountains, rocky slopes/cliffs, and large coherent +patches of different tree species/colors. The important change is landform scale +and depth, with vegetation following the terrain rather than disguising a flat plane. + +Plan a versioned terrain pass using combined low-frequency landform noise, +height maps, ridged detail, slope masks, and biome transitions. Review a few fixed +seed vistas before tuning resource density. Preserve existing worlds/layouts or +introduce a new generator version; do not silently alter explored terrain. + +Jumping must enable traversal: jump over fallen trees, rocks, fences, and gaps; +jump onto steps, ledges, and elevated surfaces. Define collision, obstacle height, +slope limits, grounded state, head clearance, and reachable ledge heights together. +Share authoritative collision and terrain queries with mob/projectile movement. +Mobs need a path around obstacles or an authored traversal capability; they must +not pass through scenery that blocks players. Keep collision boundaries continuous +across chunks. Caves, overhangs, and stacked spaces remain a later generator scope. + +Acceptance: recognizable valley/ridge vistas; routes across elevation changes; +jumps that clear low obstacles and fail against tall ones; authoritative landing; +consistent player/mob/projectile collision; no resource or structure displacement +after eviction/restart; measured terrain/vegetation rendering cost on target devices. + +Milestone 4.5 still comes next: rigs, equipment attachments, animations, and sound. +Schedule this terrain/traversal pass explicitly when revisiting the milestone plan. diff --git a/planning/SYSTEMS-ROADMAP.md b/planning/SYSTEMS-ROADMAP.md index 15f7d0a..f183545 100644 --- a/planning/SYSTEMS-ROADMAP.md +++ b/planning/SYSTEMS-ROADMAP.md @@ -532,6 +532,12 @@ Milestone 4 implementation and manual handoff: projectiles, damage/healing areas, cross-chunk pursuit, and live admin spawning are ready for manual testing. Milestone 4.5 has not started. +Milestone 4 follow-up: [readable Control, biome revisions, and projectile visibility](../docs/CONTENT-PROJECTILE-FEEDBACK.md). +Biome edits retain identity and reusable resource references. Projectiles retain +launch/impact presentation events and configurable stat contributions to speed. +Curved/seeking paths remain future extensions. The requested deeper terrain and +obstacle traversal are deferred in [Environment backlog](ENVIRONMENT-BACKLOG.md). + This replaces the earlier proposed order. Each milestone produces a reviewable slice, followed by commit/push and a user testing handoff. These are dependency-based milestones, not time estimates or new tested-capacity claims. diff --git a/planning/VISION.md b/planning/VISION.md index a530b38..82e09f8 100644 --- a/planning/VISION.md +++ b/planning/VISION.md @@ -170,6 +170,12 @@ Tracked across: - Networking: is node size (128x128x128) fixed/final, or a placeholder for tuning? ## Backlog +- September 9: layered valley/ridge/forest terrain and jumping over/onto actual + obstacles are deferred in [Environment backlog](ENVIRONMENT-BACKLOG.md), using + the supplied landscape reference. Continue the agreed presentation milestone. +- Control biome revisions keep stable identity and reuse existing resources. + Projectile launches and confirmed impacts are visible; weapon profiles can + scale speed with Dexterity and Strength. Curved/seeking paths remain planned. - Milestone 4 implements reusable combat/mob/loot/spawn definitions, selected-target projectiles, stationary damage/healing areas, cross-chunk pursuit, and live admin spawning. These use existing model presets and provisional PvE targeting/scaling; diff --git a/schemas/protocol.json b/schemas/protocol.json index 370bcd9..56665a9 100644 --- a/schemas/protocol.json +++ b/schemas/protocol.json @@ -94,7 +94,8 @@ "attack": {"$ref": "#/definitions/CombatAttackDraft"}, "mob": {"$ref": "#/definitions/MobDefinitionDraft"}, "loot": {"$ref": "#/definitions/LootTableDraft"}, - "spawn": {"$ref": "#/definitions/MobSpawnDraft"} + "spawn": {"$ref": "#/definitions/MobSpawnDraft"}, + "targetId": {"type": "string"} }, "required": ["id", "expectedVersion", "op", "reason"] }, @@ -297,7 +298,8 @@ "chunkKeys": {"type": "array", "items": {"type": "string"}}, "unavailableResources": {"type": "array", "items": {"type": "string"}}, "message": {"type": "string"}, - "gatherRisks": {"type": "object", "additionalProperties": {"$ref": "#/definitions/GatheringRisk"}} + "gatherRisks": {"type": "object", "additionalProperties": {"$ref": "#/definitions/GatheringRisk"}}, + "projectileVisuals": {"type": "array", "items": {"$ref": "#/definitions/ProjectileVisual"}} }, "required": ["type", "version", "tick", "world", "self", "entities", "chunks", "chunkKeys", "unavailableResources", "message"] }, @@ -370,7 +372,9 @@ "name": {"type": "string"}, "description": {"type": "string"}, "color": {"type": "string"}, - "weight": {"type": "integer"} + "weight": {"type": "integer"}, + "revision": {"type": "integer"}, + "resources": {"type": ["array", "null"], "items": {"type": "string"}} }, "required": ["id", "name", "description", "color", "weight"] }, @@ -381,7 +385,9 @@ "name": {"type": "string"}, "description": {"type": "string"}, "color": {"type": "string"}, - "weight": {"type": "integer"} + "weight": {"type": "integer"}, + "revision": {"type": "integer"}, + "resources": {"type": ["array", "null"], "items": {"type": "string"}} }, "required": ["name", "description", "color", "weight"] }, @@ -413,7 +419,8 @@ "skills": {"type": "array", "items": {"$ref": "#/definitions/GatheringSkill"}}, "resources": {"type": "array", "items": {"$ref": "#/definitions/ResourceDefinition"}}, "biomes": {"type": "array", "items": {"$ref": "#/definitions/BiomeDefinition"}}, - "consumables": {"type": "array", "items": {"$ref": "#/definitions/GatheringConsumable"}} + "consumables": {"type": "array", "items": {"$ref": "#/definitions/GatheringConsumable"}}, + "biomeHistory": {"type": "array", "items": {"$ref": "#/definitions/BiomeDefinition"}} }, "required": ["skills", "resources", "biomes", "consumables"] }, @@ -470,7 +477,9 @@ "speed": {"type": "number"}, "radius": {"type": "number"}, "duration": {"type": "number"}, - "interval": {"type": "number"} + "interval": {"type": "number"}, + "dexteritySpeed": {"type": "number"}, + "strengthSpeed": {"type": "number"} }, "required": ["id", "name", "description", "delivery", "effect", "stat", "multiplier", "range", "cooldown", "stamina", "speed", "radius", "duration", "interval"] }, @@ -490,7 +499,9 @@ "speed": {"type": "number"}, "radius": {"type": "number"}, "duration": {"type": "number"}, - "interval": {"type": "number"} + "interval": {"type": "number"}, + "dexteritySpeed": {"type": "number"}, + "strengthSpeed": {"type": "number"} }, "required": ["name", "description", "delivery", "effect", "stat", "multiplier", "range", "cooldown", "stamina", "speed", "radius", "duration", "interval"] }, @@ -612,6 +623,20 @@ "spawns": {"type": "array", "items": {"$ref": "#/definitions/MobSpawn"}} }, "required": ["attacks", "mobs", "loot", "spawns"] + }, + "ProjectileVisual": { + "type": "object", "additionalProperties": false, + "properties": { + "id": {"type": "string"}, + "projectileId": {"type": "string"}, + "phase": {"type": "string"}, + "position": {"$ref": "#/definitions/Vec3"}, + "destination": {"$ref": "#/definitions/Vec3"}, + "speed": {"type": "number"}, + "outcome": {"type": "string"}, + "at": {"type": "number"} + }, + "required": ["id", "projectileId", "phase", "position", "destination", "speed", "outcome", "at"] } } } diff --git a/server/content/balance.yaml b/server/content/balance.yaml index 1d54d99..1edda1c 100644 --- a/server/content/balance.yaml +++ b/server/content/balance.yaml @@ -8,9 +8,9 @@ combatRules: hitRadius: 1.2 combat: attacks: - - { id: bow_shot, name: Bow shot, description: A straight projectile that can miss., delivery: projectile, effect: damage, stat: rangedDamage, multiplier: 1, range: 45, cooldown: 1, stamina: 2, speed: 35, radius: 0, duration: 0, interval: 1 } - - { id: blast_shot, name: Blast shot, description: A projectile with a damage burst., delivery: projectile, effect: damage, stat: rangedDamage, multiplier: 1, range: 35, cooldown: 3, stamina: 8, speed: 25, radius: 6, duration: 0, interval: 1 } - - { id: healing_field, name: Healing field, description: A projectile that creates a stationary healing area., delivery: projectile, effect: heal, stat: magicDamage, multiplier: 1, range: 30, cooldown: 8, stamina: 10, speed: 25, radius: 6, duration: 5, interval: 1 } + - { id: bow_shot, name: Bow shot, description: A straight projectile that can miss., delivery: projectile, effect: damage, stat: rangedDamage, multiplier: 1, range: 45, cooldown: 1, stamina: 2, speed: 35, dexteritySpeed: 0.1, strengthSpeed: 0.05, radius: 0, duration: 0, interval: 1 } + - { id: blast_shot, name: Blast shot, description: A projectile with a damage burst., delivery: projectile, effect: damage, stat: rangedDamage, multiplier: 1, range: 35, cooldown: 3, stamina: 8, speed: 25, dexteritySpeed: 0.1, strengthSpeed: 0.05, radius: 6, duration: 0, interval: 1 } + - { id: healing_field, name: Healing field, description: A projectile that creates a stationary healing area., delivery: projectile, effect: heal, stat: magicDamage, multiplier: 1, range: 30, cooldown: 8, stamina: 10, speed: 25, dexteritySpeed: 0.1, strengthSpeed: 0.05, radius: 6, duration: 5, interval: 1 } - { id: sentinel_strike, name: Sentinel strike, description: Close range damage., delivery: melee, effect: damage, stat: meleeDamage, multiplier: 1, range: 3, cooldown: 1.8, stamina: 0, speed: 1, radius: 0, duration: 0, interval: 1 } mobs: - { id: ash_guard, name: Ash guard, description: A territorial guardian., model: sentinel, behavior: aggressive, level: 1, hp: 54, damage: 6, defence: 0, speed: 4, aggroRange: 24, leashRange: 160, scalePerDay: 0.1, xp: 50, attackId: sentinel_strike, lootId: common_mob_loot } diff --git a/server/content/combat.go b/server/content/combat.go index bc0265e..4d7ea0e 100644 --- a/server/content/combat.go +++ b/server/content/combat.go @@ -6,23 +6,28 @@ import ( ) type CombatAttack struct { - ID string `json:"id" yaml:"id"` - Name string `json:"name" yaml:"name"` - Description string `json:"description" yaml:"description"` - Delivery string `json:"delivery" yaml:"delivery"` - Effect string `json:"effect" yaml:"effect"` - Stat string `json:"stat" yaml:"stat"` - Multiplier float64 `json:"multiplier" yaml:"multiplier"` - Range float64 `json:"range" yaml:"range"` - Cooldown float64 `json:"cooldown" yaml:"cooldown"` - Stamina float64 `json:"stamina" yaml:"stamina"` - Speed float64 `json:"speed" yaml:"speed"` - Radius float64 `json:"radius" yaml:"radius"` - Duration float64 `json:"duration" yaml:"duration"` - Interval float64 `json:"interval" yaml:"interval"` + DexteritySpeed float64 `json:"dexteritySpeed,omitempty" yaml:"dexteritySpeed"` + StrengthSpeed float64 `json:"strengthSpeed,omitempty" yaml:"strengthSpeed"` + ID string `json:"id" yaml:"id"` + Name string `json:"name" yaml:"name"` + Description string `json:"description" yaml:"description"` + Delivery string `json:"delivery" yaml:"delivery"` + Effect string `json:"effect" yaml:"effect"` + Stat string `json:"stat" yaml:"stat"` + Multiplier float64 `json:"multiplier" yaml:"multiplier"` + Range float64 `json:"range" yaml:"range"` + Cooldown float64 `json:"cooldown" yaml:"cooldown"` + Stamina float64 `json:"stamina" yaml:"stamina"` + Speed float64 `json:"speed" yaml:"speed"` + Radius float64 `json:"radius" yaml:"radius"` + Duration float64 `json:"duration" yaml:"duration"` + Interval float64 `json:"interval" yaml:"interval"` } func (a CombatAttack) Validate() error { + if !finiteRange(a.DexteritySpeed, 0, 5) || !finiteRange(a.StrengthSpeed, 0, 5) { + return fmt.Errorf("invalid projectile speed coefficients") + } if !validSetIdentity(a.ID, a.Name, a.Description) || !slices.Contains([]string{"melee", "projectile"}, a.Delivery) || !slices.Contains([]string{"damage", "heal"}, a.Effect) || !slices.Contains([]string{"meleeDamage", "rangedDamage", "magicDamage"}, a.Stat) || !finiteRange(a.Multiplier, .01, 100) || !finiteRange(a.Range, 1, 128) || !finiteRange(a.Cooldown, .1, 120) || !finiteRange(a.Stamina, 0, 10000) || !finiteRange(a.Speed, 1, 100) || !finiteRange(a.Radius, 0, 24) || !finiteRange(a.Duration, 0, 60) || !finiteRange(a.Interval, .2, 60) { return fmt.Errorf("invalid attack %q", a.ID) } diff --git a/server/content/gathering.go b/server/content/gathering.go index c3a9a8d..53d3524 100644 --- a/server/content/gathering.go +++ b/server/content/gathering.go @@ -31,11 +31,13 @@ type ResourceDefinition struct { Biomes []string `json:"biomes" yaml:"biomes"` } type BiomeDefinition struct { - ID string `json:"id" yaml:"id"` - Name string `json:"name" yaml:"name"` - Description string `json:"description" yaml:"description"` - Color string `json:"color" yaml:"color"` - Weight int64 `json:"weight" yaml:"weight"` + Revision int64 `json:"revision,omitempty" yaml:"revision"` + Resources []string `json:"resources" yaml:"resources"` + ID string `json:"id" yaml:"id"` + Name string `json:"name" yaml:"name"` + Description string `json:"description" yaml:"description"` + Color string `json:"color" yaml:"color"` + Weight int64 `json:"weight" yaml:"weight"` } type GatheringConsumable struct { ID string `json:"id" yaml:"id"` @@ -45,10 +47,11 @@ type GatheringConsumable struct { Modifiers []StatModifier `json:"modifiers" yaml:"modifiers"` } type GatheringContent struct { - Skills []GatheringSkill `json:"skills" yaml:"skills"` - Resources []ResourceDefinition `json:"resources" yaml:"resources"` - Biomes []BiomeDefinition `json:"biomes" yaml:"biomes"` - Consumables []GatheringConsumable `json:"consumables" yaml:"consumables"` + BiomeHistory []BiomeDefinition `json:"biomeHistory,omitempty" yaml:"biomeHistory"` + Skills []GatheringSkill `json:"skills" yaml:"skills"` + Resources []ResourceDefinition `json:"resources" yaml:"resources"` + Biomes []BiomeDefinition `json:"biomes" yaml:"biomes"` + Consumables []GatheringConsumable `json:"consumables" yaml:"consumables"` } type GatheringRules struct { FailureBase float64 `json:"failureBase" yaml:"failureBase"` @@ -84,6 +87,9 @@ func (r GatheringRules) Validate() error { return nil } func (g GatheringContent) Validate() error { + if len(g.BiomeHistory) > 1024 { + return fmt.Errorf("biome revision history limit reached") + } if len(g.Skills) < 1 || len(g.Skills) > 64 || len(g.Resources) > 256 || len(g.Biomes) < 1 || len(g.Biomes) > 32 || len(g.Consumables) > 256 { return fmt.Errorf("invalid gathering content counts") } @@ -125,6 +131,18 @@ func (g GatheringContent) Validate() error { seen[id] = true } } + for _, b := range append(slices.Clone(g.Biomes), g.BiomeHistory...) { + if b.Revision < 0 || len(b.Resources) > 256 { + return fmt.Errorf("invalid biome revision") + } + seen := map[string]bool{} + for _, id := range b.Resources { + if seen[id] || !slices.ContainsFunc(g.Resources, func(r ResourceDefinition) bool { return r.ID == id }) { + return fmt.Errorf("unknown/duplicate biome resource %q", id) + } + seen[id] = true + } + } for _, c := range g.Consumables { if !identity(c.ID, c.Name, c.Description) || !finiteRange(c.Seconds, 1, 86400) || len(c.Modifiers) < 1 { return fmt.Errorf("invalid consumable %q", c.ID) diff --git a/server/internal/game/biome_revision_test.go b/server/internal/game/biome_revision_test.go new file mode 100644 index 0000000..9cf4ffc --- /dev/null +++ b/server/internal/game/biome_revision_test.go @@ -0,0 +1,52 @@ +package game + +import ( + "aeternalis/server/content" + "encoding/json" + "reflect" + "testing" +) + +func TestBiomeResourceRevisionPreservesExploredChunks(t *testing.T) { + w, _ := fixture(t) + g := w.Balance.Gathering + g.Biomes = []content.BiomeDefinition{{ID: "valley", Name: "Valley", Color: "#445566", Weight: 1, Revision: 1, Resources: []string{"tree"}}} + before := w.chunk(2, 2) + if len(before.Resources) == 0 { + t.Fatal("existing tree could not be reused in a new biome") + } + for _, r := range before.Resources { + if stringValue(r.ResourceID) != "tree" { + t.Fatal("unselected resource generated") + } + } + g.Biomes[0].Revision = 2 + g.Biomes[0].Resources = []string{} + delete(w.chunks, before.Key) + after := w.chunk(2, 2) + if !reflect.DeepEqual(before, after) { + t.Fatal("biome revision rewrote an explored chunk") + } + if len(w.chunk(3, 3).Resources) != 0 { + t.Fatal("new chunk ignored empty resource selection") + } + // Saved geometry/resource identity survives restart independently of the active revision. + raw, err := json.Marshal(w) + if err != nil { + t.Fatal(err) + } + var restored World + if err = json.Unmarshal(raw, &restored); err != nil { + t.Fatal(err) + } + // Restore validates all resource biome references; use the normal default list, + // while keeping the explored layout under test. + b, _ := content.Load() + restored.Balance.Gathering = b.Gathering + if err = restored.Restore(w.now); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(before, restored.chunk(2, 2)) { + t.Fatal("restart rewrote explored layout") + } +} diff --git a/server/internal/game/biomes.go b/server/internal/game/biomes.go index de5bff2..7230fad 100644 --- a/server/internal/game/biomes.go +++ b/server/internal/game/biomes.go @@ -53,7 +53,11 @@ func (t *Terrain) Chunk(x, z int) p.Chunk { } c.Resources = []p.Entity{} for _, r := range t.B.Gathering.Resources { - if !slices.Contains(r.Biomes, biome.ID) { + allowed := slices.Contains(r.Biomes, biome.ID) + if biome.Resources != nil { + allowed = slices.Contains(biome.Resources, r.ID) + } + if !allowed { continue } hash := fnv.New64a() diff --git a/server/internal/game/combat.go b/server/internal/game/combat.go index d266914..2e1ce42 100644 --- a/server/internal/game/combat.go +++ b/server/internal/game/combat.go @@ -27,12 +27,22 @@ type CombatArea struct { } func protocolAttack(a content.CombatAttack) p.CombatAttack { - return p.CombatAttack{ID: a.ID, Name: a.Name, Description: a.Description, Delivery: a.Delivery, Effect: a.Effect, Stat: a.Stat, Multiplier: a.Multiplier, Range: a.Range, Cooldown: a.Cooldown, Stamina: a.Stamina, Speed: a.Speed, Radius: a.Radius, Duration: a.Duration, Interval: a.Interval} + return p.CombatAttack{ID: a.ID, Name: a.Name, Description: a.Description, Delivery: a.Delivery, Effect: a.Effect, Stat: a.Stat, Multiplier: a.Multiplier, Range: a.Range, Cooldown: a.Cooldown, Stamina: a.Stamina, Speed: a.Speed, DexteritySpeed: &a.DexteritySpeed, StrengthSpeed: &a.StrengthSpeed, Radius: a.Radius, Duration: a.Duration, Interval: a.Interval} } func (w *World) playerAttack(c *Character) p.CombatAttack { for _, i := range c.View.Items { if i.ID == c.View.Equipment["weapon"] && i.Attack != nil { - return *i.Attack + a := *i.Attack + if a.Delivery == "projectile" { + if a.DexteritySpeed != nil { + a.Speed += c.View.Stats["dexterity"].Final * *a.DexteritySpeed + } + if a.StrengthSpeed != nil { + a.Speed += c.View.Stats["strength"].Final * *a.StrengthSpeed + } + a.Speed = math.Max(1, math.Min(100, a.Speed)) + } + return a } } return p.CombatAttack{ID: "basic_melee", Name: "Melee attack", Delivery: "melee", Effect: "damage", Stat: "meleeDamage", Multiplier: 1, Range: w.Balance.AttackRange, Cooldown: w.Balance.AttackCooldown, Speed: 1, Interval: 1} @@ -137,6 +147,7 @@ func (w *World) attack(c *Character, target string) error { shot := Projectile{ID: w.combatID("projectile"), Source: c.View.Entity.ID, Player: true, Target: target, Position: from, Destination: to, Attack: a, Power: power} if a.Delivery == "projectile" { w.Projectiles[shot.ID] = &shot + w.projectileVisual(shot, "launch", "") } else { shot.Position = to w.impact(shot, target) @@ -254,6 +265,7 @@ func (w *World) updateCombat(dt float64) { for _, id := range ids { shot := w.Projectiles[id] if !w.sourceActive(shot.Source, shot.Player) { + w.projectileVisual(*shot, "impact", "cancelled") delete(w.Projectiles, id) w.dirty = true continue @@ -302,6 +314,13 @@ func (w *World) updateCombat(dt float64) { copy.Position = hitPoint } delete(w.Projectiles, id) + outcome := "miss" + if hit != "" { + outcome = "hit" + } else if blocked { + outcome = "terrain" + } + w.projectileVisual(copy, "impact", outcome) w.impact(copy, hit) } else { shot.Position = end @@ -326,6 +345,16 @@ func (w *World) updateCombat(dt float64) { } } } + +// Short, bounded event history lets a launch and impact survive between network +// snapshots. This is presentation data; damage is resolved only by updateCombat. +func (w *World) projectileVisual(shot Projectile, phase, outcome string) { + w.ProjectileVisuals = append(w.ProjectileVisuals, p.ProjectileVisual{ID: w.combatID("visual"), ProjectileID: shot.ID, Phase: phase, Position: shot.Position, Destination: shot.Destination, Speed: shot.Attack.Speed, Outcome: outcome, At: w.Age()}) + if len(w.ProjectileVisuals) > 1024 { + w.ProjectileVisuals = w.ProjectileVisuals[len(w.ProjectileVisuals)-1024:] + } + w.dirty = true +} func (w *World) mobKilled(c *Character, m *Mob) { if m.Entity.State == "dead" { return diff --git a/server/internal/game/combat_test.go b/server/internal/game/combat_test.go index 7f8df04..a42e7ed 100644 --- a/server/internal/game/combat_test.go +++ b/server/internal/game/combat_test.go @@ -250,3 +250,32 @@ func TestRegionalSpawnsRespectExploredBiomeAndPlayerDistance(t *testing.T) { t.Fatal("regional slot was missing or duplicated") } } + +func TestProjectileSpeedSampleAndShortFlightEvents(t *testing.T) { + w, c, m := combatFixture(t) + dex, str := float64(2), float64(1) + weapon := &c.View.Items[len(c.View.Items)-1] + weapon.Attack.DexteritySpeed = &dex + weapon.Attack.StrengthSpeed = &str + c.View.Stats["dexterity"] = p.StatValue{Final: 5} + c.View.Stats["strength"] = p.StatValue{Final: 3} + m.Entity.Position = w.terrain.Position(2, 0) + if err := w.attack(c, m.Entity.ID); err != nil { + t.Fatal(err) + } + if len(w.ProjectileVisuals) != 1 || w.ProjectileVisuals[0].Phase != "launch" || w.ProjectileVisuals[0].Speed != 48 { + t.Fatal("wrong launch speed/event") + } + c.View.Stats["dexterity"] = p.StatValue{Final: 100} + w.updateCombat(.1) + if len(w.Projectiles) != 0 || len(w.ProjectileVisuals) != 2 || w.ProjectileVisuals[1].Outcome != "hit" { + t.Fatal("short flight lost its hit") + } + if w.ProjectileVisuals[1].Speed != 48 { + t.Fatal("stat change altered in-flight speed") + } + snapshot := w.Snapshot(c.View.Entity.ID, map[string]bool{}) + if len(snapshot.ProjectileVisuals) != 2 { + t.Fatal("flight between snapshots became invisible") + } +} diff --git a/server/internal/game/mobs.go b/server/internal/game/mobs.go index 23924cc..2695ef0 100644 --- a/server/internal/game/mobs.go +++ b/server/internal/game/mobs.go @@ -312,6 +312,7 @@ func (w *World) updateMobs(active map[string]bool, dt float64) { m.LastAttack = w.Age() if attack.Delivery == "projectile" { w.Projectiles[shot.ID] = &shot + w.projectileVisual(shot, "launch", "") } else { shot.Position = body(aim) w.impact(shot, targetID) diff --git a/server/internal/game/world.go b/server/internal/game/world.go index 5a5602a..2d89d1a 100644 --- a/server/internal/game/world.go +++ b/server/internal/game/world.go @@ -70,9 +70,10 @@ type ResourceLayout struct { Resources []p.Entity `json:"resources"` } type World struct { - Projectiles map[string]*Projectile `json:"projectiles,omitempty"` - Areas map[string]*CombatArea `json:"areas,omitempty"` - CombatSequence uint64 `json:"combatSequence"` + ProjectileVisuals []p.ProjectileVisual `json:"projectileVisuals,omitempty"` + Projectiles map[string]*Projectile `json:"projectiles,omitempty"` + Areas map[string]*CombatArea `json:"areas,omitempty"` + CombatSequence uint64 `json:"combatSequence"` ResourceLayouts map[string]ResourceLayout `json:"resourceLayouts,omitempty"` @@ -636,6 +637,13 @@ func (w *World) Advance(now time.Time, dt float64) { playedDT := math.Max(0, dt) w.now = now w.Tick++ + kept := w.ProjectileVisuals[:0] + for _, v := range w.ProjectileVisuals { + if w.Age()-v.At <= 2 { + kept = append(kept, v) + } + } + w.ProjectileVisuals = kept dt = math.Max(0, math.Min(dt, 0.25)) if w.Phase == "won" || w.Phase == "lost" { return @@ -798,6 +806,12 @@ func (w *World) Snapshot(id string, known map[string]bool) p.Snapshot { visible := func(pos p.Vec3) bool { return allowed[Key(ChunkCoord(pos.X, w.Balance.ChunkSize), ChunkCoord(pos.Z, w.Balance.ChunkSize))] } + s.ProjectileVisuals = []p.ProjectileVisual{} + for _, v := range w.ProjectileVisuals { + if w.Age()-v.At <= 2 && (visible(v.Position) || visible(v.Destination)) { + s.ProjectileVisuals = append(s.ProjectileVisuals, v) + } + } for _, other := range w.Characters { if 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 9d91811..e812b6b 100644 --- a/server/internal/protocol/generated.go +++ b/server/internal/protocol/generated.go @@ -29,20 +29,22 @@ type CombatContent struct { } type CombatAttack struct { - Cooldown float64 `json:"cooldown"` - Delivery string `json:"delivery"` - Description string `json:"description"` - Duration float64 `json:"duration"` - Effect string `json:"effect"` - ID string `json:"id"` - Interval float64 `json:"interval"` - Multiplier float64 `json:"multiplier"` - Name string `json:"name"` - Radius float64 `json:"radius"` - Range float64 `json:"range"` - Speed float64 `json:"speed"` - Stamina float64 `json:"stamina"` - Stat string `json:"stat"` + Cooldown float64 `json:"cooldown"` + Delivery string `json:"delivery"` + Description string `json:"description"` + DexteritySpeed *float64 `json:"dexteritySpeed,omitempty"` + Duration float64 `json:"duration"` + Effect string `json:"effect"` + ID string `json:"id"` + Interval float64 `json:"interval"` + Multiplier float64 `json:"multiplier"` + Name string `json:"name"` + Radius float64 `json:"radius"` + Range float64 `json:"range"` + Speed float64 `json:"speed"` + Stamina float64 `json:"stamina"` + Stat string `json:"stat"` + StrengthSpeed *float64 `json:"strengthSpeed,omitempty"` } type LootTable struct { @@ -108,18 +110,21 @@ type StatModifier struct { } type GatheringContent struct { - Biomes []BiomeDefinition `json:"biomes"` - Consumables []GatheringConsumable `json:"consumables"` - Resources []ResourceDefinition `json:"resources"` - Skills []GatheringSkill `json:"skills"` + BiomeHistory []BiomeDefinition `json:"biomeHistory,omitempty"` + Biomes []BiomeDefinition `json:"biomes"` + Consumables []GatheringConsumable `json:"consumables"` + Resources []ResourceDefinition `json:"resources"` + Skills []GatheringSkill `json:"skills"` } type BiomeDefinition struct { - Color string `json:"color"` - Description string `json:"description"` - ID string `json:"id"` - Name string `json:"name"` - Weight int64 `json:"weight"` + Color string `json:"color"` + Description string `json:"description"` + ID string `json:"id"` + Name string `json:"name"` + Resources []string `json:"resources"` + Revision *int64 `json:"revision,omitempty"` + Weight int64 `json:"weight"` } type GatheringConsumable struct { @@ -225,32 +230,37 @@ type ContentChange struct { Resource *ResourceDefinitionDraft `json:"resource,omitempty"` Spawn *MobSpawnDraft `json:"spawn,omitempty"` Stats *ContentStatsRules `json:"stats,omitempty"` + TargetID *string `json:"targetId,omitempty"` Title *TitleDraft `json:"title,omitempty"` } type CombatAttackDraft struct { - Cooldown float64 `json:"cooldown"` - Delivery string `json:"delivery"` - Description string `json:"description"` - Duration float64 `json:"duration"` - Effect string `json:"effect"` - ID *string `json:"id,omitempty"` - Interval float64 `json:"interval"` - Multiplier float64 `json:"multiplier"` - Name string `json:"name"` - Radius float64 `json:"radius"` - Range float64 `json:"range"` - Speed float64 `json:"speed"` - Stamina float64 `json:"stamina"` - Stat string `json:"stat"` + Cooldown float64 `json:"cooldown"` + Delivery string `json:"delivery"` + Description string `json:"description"` + DexteritySpeed *float64 `json:"dexteritySpeed,omitempty"` + Duration float64 `json:"duration"` + Effect string `json:"effect"` + ID *string `json:"id,omitempty"` + Interval float64 `json:"interval"` + Multiplier float64 `json:"multiplier"` + Name string `json:"name"` + Radius float64 `json:"radius"` + Range float64 `json:"range"` + Speed float64 `json:"speed"` + Stamina float64 `json:"stamina"` + Stat string `json:"stat"` + StrengthSpeed *float64 `json:"strengthSpeed,omitempty"` } type BiomeDefinitionDraft struct { - Color string `json:"color"` - Description string `json:"description"` - ID *string `json:"id,omitempty"` - Name string `json:"name"` - Weight int64 `json:"weight"` + Color string `json:"color"` + Description string `json:"description"` + ID *string `json:"id,omitempty"` + Name string `json:"name"` + Resources []string `json:"resources"` + Revision *int64 `json:"revision,omitempty"` + Weight int64 `json:"weight"` } type GatheringConsumableDraft struct { @@ -387,6 +397,7 @@ type Snapshot struct { Entities []Entity `json:"entities"` GatherRisks map[string]GatheringRisk `json:"gatherRisks,omitempty"` Message string `json:"message"` + ProjectileVisuals []ProjectileVisual `json:"projectileVisuals,omitempty"` Self Character `json:"self"` Tick int64 `json:"tick"` Type string `json:"type"` @@ -437,6 +448,17 @@ type GatheringRisk struct { Seconds float64 `json:"seconds"` } +type ProjectileVisual struct { + At float64 `json:"at"` + Destination Vec3 `json:"destination"` + ID string `json:"id"` + Outcome string `json:"outcome"` + Phase string `json:"phase"` + Position Vec3 `json:"position"` + ProjectileID string `json:"projectileId"` + Speed float64 `json:"speed"` +} + type Character struct { ACK int64 `json:"ack"` AllocatedStats map[string]int64 `json:"allocatedStats"` diff --git a/server/internal/store/biome_revision_test.go b/server/internal/store/biome_revision_test.go new file mode 100644 index 0000000..deb19d8 --- /dev/null +++ b/server/internal/store/biome_revision_test.go @@ -0,0 +1,78 @@ +package store + +import ( + "aeternalis/server/content" + "aeternalis/server/internal/game" + "context" + "errors" + "path/filepath" + "testing" +) + +func TestBiomeRevisionsReuseResourcesAndRejectStaleEdits(t *testing.T) { + ctx := context.Background() + db, err := Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "biomes.db"))) + if err != nil { + t.Fatal(err) + } + defer db.Close() + initial, err := db.Catalog(ctx) + if err != nil { + t.Fatal(err) + } + draft := CatalogChange{ID: game.ID(), ExpectedVersion: initial.Version, Reason: "Reuse existing trees", Op: "create-biome", Biome: &content.BiomeDefinition{Name: "Wooded valley", Color: "#445566", Weight: 2, Resources: []string{"tree"}}} + made, err := db.PublishCatalog(ctx, "admin", draft) + if err != nil { + t.Fatal(err) + } + edit := CatalogChange{ID: game.ID(), ExpectedVersion: made.Version, Reason: "Add existing ore", Op: "update-biome", TargetID: made.ID, Biome: &content.BiomeDefinition{Name: "Wooded valley", Color: "#334455", Weight: 3, Resources: []string{"tree", "ore"}}} + preview, err := db.PreviewCatalog(ctx, edit) + if err != nil { + t.Fatal(err) + } + if preview.Resolved.Biome.ID != made.ID || preview.Resolved.Biome.Revision != 2 { + t.Fatal("preview replaced permanent identity") + } + unchanged, _ := db.Catalog(ctx) + if unchanged.Version != made.Version || len(unchanged.Gathering.BiomeHistory) != 0 { + t.Fatal("preview mutated history") + } + revised, err := db.PublishCatalog(ctx, "admin", edit) + if err != nil { + t.Fatal(err) + } + replay, err := db.PublishCatalog(ctx, "admin", edit) + if err != nil || replay != revised { + t.Fatal("retry changed revision", err) + } + current, err := db.Catalog(ctx) + if err != nil { + t.Fatal(err) + } + if len(current.Gathering.Resources) != len(initial.Gathering.Resources) || len(current.Gathering.Biomes) != len(initial.Gathering.Biomes)+1 { + t.Fatal("revision duplicated resource or biome") + } + if len(current.Gathering.BiomeHistory) != 1 || current.Gathering.BiomeHistory[0].Revision != 1 || len(current.Gathering.BiomeHistory[0].Resources) != 1 { + t.Fatal("old revision not preserved") + } + edit.ID = game.ID() + if _, err = db.PublishCatalog(ctx, "admin", edit); !errors.Is(err, ErrCatalogConflict) { + t.Fatal("stale edit accepted", err) + } + edit.ExpectedVersion = current.Version + edit.Biome.Resources = []string{"missing"} + if _, err = db.PublishCatalog(ctx, "admin", edit); !errors.Is(err, ErrCatalogInvalid) { + t.Fatal("unknown resource accepted", err) + } + edit.ID = game.ID() + edit.Biome.Resources = []string{} + if _, err = db.PublishCatalog(ctx, "admin", edit); err != nil { + t.Fatal("empty biome rejected", err) + } + current, _ = db.Catalog(ctx) + for _, b := range current.Gathering.Biomes { + if b.ID == made.ID && (b.Resources == nil || len(b.Resources) != 0 || b.Revision != 3) { + t.Fatal("empty resource selection lost on save") + } + } +} diff --git a/server/internal/store/catalog.go b/server/internal/store/catalog.go index 4543955..14489dd 100644 --- a/server/internal/store/catalog.go +++ b/server/internal/store/catalog.go @@ -17,6 +17,7 @@ var ErrCatalogInvalid = errors.New("invalid catalog change") var catalogRequestID = regexp.MustCompile(`^[a-f0-9-]{32,36}$`) type CatalogChange struct { + TargetID string `json:"targetId,omitempty"` Attack *content.CombatAttack `json:"attack,omitempty"` Mob *content.MobDefinition `json:"mob,omitempty"` Loot *content.LootTable `json:"loot,omitempty"` @@ -141,6 +142,12 @@ func (d *DB) CatalogAfter(ctx context.Context, after int64) (*content.Catalog, e return &catalog, err } func (c CatalogChange) validate() error { + if (c.Op == "update-biome") != (c.TargetID != "") { + return fmt.Errorf("%w: only biome edits require an existing target", ErrCatalogInvalid) + } + if c.Biome != nil && c.Biome.Revision != 0 { + return fmt.Errorf("%w: revisions are assigned by the server", ErrCatalogInvalid) + } if !catalogRequestID.MatchString(c.ID) || c.ExpectedVersion < 1 || len(c.Reason) < 5 || len(c.Reason) > 240 { return fmt.Errorf("%w: request ID, current version and 5-240 character reason required", ErrCatalogInvalid) } @@ -166,6 +173,8 @@ func (c CatalogChange) validate() error { valid = c.Resource != nil case "create-biome": valid = c.Biome != nil + case "update-biome": + valid = c.Biome != nil && c.Biome.ID == "" case "create-consumable": valid = c.Consumable != nil case "create-title": diff --git a/server/internal/store/catalog_preview.go b/server/internal/store/catalog_preview.go index b85d266..c07d1e7 100644 --- a/server/internal/store/catalog_preview.go +++ b/server/internal/store/catalog_preview.go @@ -53,7 +53,7 @@ func (d *DB) PreviewCatalog(ctx context.Context, change CatalogChange) (CatalogP if resolved.Resource != nil { resolved.Resource.ID = "" } - if resolved.Biome != nil { + if resolved.Biome != nil && change.Op != "update-biome" { resolved.Biome.ID = "" } if resolved.Consumable != nil { @@ -153,16 +153,44 @@ func buildCatalog(c content.Catalog, change CatalogChange) (content.Catalog, str v.ID = "resource_" + game.ID() } resolved.Resource = &v + for i, b := range c.Gathering.Biomes { + if slices.Contains(v.Biomes, b.ID) { + if b.Resources == nil { + b.Resources = []string{} + for _, r := range c.Gathering.Resources { + if slices.Contains(r.Biomes, b.ID) { + b.Resources = append(b.Resources, r.ID) + } + } + } + b.Resources = append(slices.Clone(b.Resources), v.ID) + reviseBiome(c.Gathering, i, b) + } + } c.Gathering.Resources = append(slices.Clone(c.Gathering.Resources), v) target = v.ID case "create-biome": v := *change.Biome + v.Revision = 1 if v.ID == "" { v.ID = "biome_" + game.ID() } resolved.Biome = &v c.Gathering.Biomes = append(slices.Clone(c.Gathering.Biomes), v) target = v.ID + case "update-biome": + i := slices.IndexFunc(c.Gathering.Biomes, func(b content.BiomeDefinition) bool { return b.ID == change.TargetID }) + if i < 0 { + return invalid(fmt.Errorf("biome not found")) + } + v := *change.Biome + if v.Resources == nil { + return invalid(fmt.Errorf("select biome resources, or an empty list")) + } + reviseBiome(c.Gathering, i, v) + v = c.Gathering.Biomes[i] + resolved.Biome = &v + target = v.ID case "create-consumable": v := *change.Consumable if v.ID == "" { @@ -247,3 +275,20 @@ func buildCatalog(c content.Catalog, change CatalogChange) (content.Catalog, str } return c, target, resolved, nil } + +func reviseBiome(g *content.GatheringContent, index int, next content.BiomeDefinition) { + previous := g.Biomes[index] + previous.Revision = max(1, previous.Revision) + if previous.Resources == nil { + previous.Resources = []string{} + for _, r := range g.Resources { + if slices.Contains(r.Biomes, previous.ID) { + previous.Resources = append(previous.Resources, r.ID) + } + } + } + g.BiomeHistory = append(slices.Clone(g.BiomeHistory), previous) + next.ID, next.Revision = previous.ID, previous.Revision+1 + g.Biomes = slices.Clone(g.Biomes) + g.Biomes[index] = next +}