From 3f58de5744bcedce403a85ff5361af2eb94d7715 Mon Sep 17 00:00:00 2001 From: dingo Date: Mon, 7 Sep 2026 13:44:10 -0400 Subject: [PATCH] pushing current --- client/src/generated.ts | 44 ++++++ server/content/balance.yaml | 63 +++++++- server/content/content.go | 14 ++ server/content/progression.go | 47 +++--- server/content/stats.go | 162 +++++++++++++++++++++ server/content/stats_test.go | 27 ++++ server/internal/game/equipment.go | 87 +++++++++++ server/internal/game/progression.go | 26 +++- server/internal/game/stats.go | 198 ++++++++++++++++++++++++++ server/internal/game/stats_test.go | 83 +++++++++++ server/internal/game/world.go | 95 +++++++++--- server/internal/protocol/generated.go | 74 ++++++++-- server/internal/store/store.go | 2 +- server/internal/store/titles.go | 6 + server/internal/transport/service.go | 4 + 15 files changed, 872 insertions(+), 60 deletions(-) create mode 100644 server/content/stats.go create mode 100644 server/content/stats_test.go create mode 100644 server/internal/game/equipment.go create mode 100644 server/internal/game/stats.go create mode 100644 server/internal/game/stats_test.go diff --git a/client/src/generated.ts b/client/src/generated.ts index 030b3c4..b3e644a 100644 --- a/client/src/generated.ts +++ b/client/src/generated.ts @@ -7,6 +7,7 @@ export interface Protocol { export interface Intent { op: string; seq: number; + slot: string; target: string; x: number; z: number; @@ -54,20 +55,62 @@ export interface Vec3 { export interface Character { ack: number; + allocatedStats: { [key: string]: number }; + carryWeight: number; entity: Entity; + equipment: { [key: string]: string }; experience: number; experienceToNextLevel: number; hasKeystone: boolean; + healthChoices: number; inventory: { [key: string]: number }; + items: ItemInstance[]; kills: number; level: number; + mana: number; + manaChoices: number; + pendingVitalChoices: number; playedSeconds: number; remainingSeconds: number; skills: { [key: string]: number }; + stamina: number; statPoints: number; + stats: { [key: string]: StatValue }; titles: TitleAward[]; } +export interface ItemInstance { + definitionId: string; + description: string; + equippable: boolean; + id: string; + modifiers: StatModifier[]; + name: string; + requirementMessage: string; + requirements: ItemRequirements; + slot: string; + weight: number; +} + +export interface StatModifier { + flat: number; + percent: number; + stat: string; +} + +export interface ItemRequirements { + level: number; + stats: { [key: string]: number }; + titles: string[]; +} + +export interface StatValue { + base: number; + final: number; + flat: number; + percent: number; +} + export interface TitleAward { description: string; earnedAt: string; @@ -80,6 +123,7 @@ export interface TitleAward { export interface TitleEffects { damage: number; + modifiers: StatModifier[]; moveSpeed: number; } diff --git a/server/content/balance.yaml b/server/content/balance.yaml index d8e90e8..ba9fb2a 100644 --- a/server/content/balance.yaml +++ b/server/content/balance.yaml @@ -14,6 +14,7 @@ playerSpeed: 12 attackRange: 6 attackCooldown: 0.7 playerDamage: 18 +criticalMultiplier: 2 spearDamage: 32 gatherRange: 7 gatherCooldown: 0.6 @@ -50,7 +51,9 @@ bandageHealing: 35 progression: baseXp: 100 xpPerLevel: 50 - statPointsPerLevel: 5 + statPointsPerLevel: 10 + staminaPerLevel: 5 + vitalPointsPerChoice: 5 maxLevel: 1000 gatherXp: 10 craftXp: 20 @@ -76,3 +79,61 @@ titles: scope: global requirements: [{ metric: worldKills, atLeast: 1 }] effects: { damage: 3, moveSpeed: -0.5 } +# Provisional coefficients. Control can publish changes to these rules. +stats: + version: 1 + base: + constitution: 0 + intelligence: 0 + dexterity: 0 + strength: 0 + wisdom: 0 + charisma: 0 + luck: 0 + healthPoints: 100 + endurance: 0 + resistance: 0 + healthRecovery: 0 + magicDamage: 0 + knowledge: 0 + spellPoints: 0 + manaPoints: 50 + moveSpeed: 12 + rangedDamage: 18 + criticalChance: 0 + dodgeChance: 0 + staminaRecovery: 1 + meleeDamage: 18 + heavyDamage: 18 + carryCapacity: 100 + defence: 0 + skillPoints: 0 + xpGain: 100 + manaRecovery: 0 + buffEffectiveness: 100 + dropRate: 100 + gatherRate: 100 + stamina: 100 + coefficients: + constitution: { healthPoints: 5, endurance: 1, resistance: 0.5, healthRecovery: 0.02 } + intelligence: { magicDamage: 1, knowledge: 1, spellPoints: 0.5, manaPoints: 5 } + dexterity: { moveSpeed: 0.02, rangedDamage: 1, criticalChance: 0.1, endurance: 0.5, dodgeChance: 0.1, staminaRecovery: 0.05 } + strength: { meleeDamage: 1, heavyDamage: 1.5, carryCapacity: 5, endurance: 0.5, defence: 0.5 } + wisdom: { knowledge: 1, resistance: 0.5, skillPoints: 0.5, xpGain: 0.5, manaRecovery: 0.05 } + charisma: { buffEffectiveness: 1 } + luck: { criticalChance: 0.1, dropRate: 1, gatherRate: 1, dodgeChance: 0.1 } +items: + - id: knife + name: Knife + description: A starting close-combat weapon. + slot: weapon + weight: 1 + requirements: { level: 1, stats: {}, titles: [] } + modifiers: [] + - id: spear + name: Spear + description: A crafted close-combat weapon. + slot: weapon + weight: 3 + requirements: { level: 1, stats: {}, titles: [] } + modifiers: [{ stat: meleeDamage, flat: 14, percent: 0 }] diff --git a/server/content/content.go b/server/content/content.go index 352d0bc..a053481 100644 --- a/server/content/content.go +++ b/server/content/content.go @@ -35,6 +35,7 @@ type Balance struct { AttackRange float64 `yaml:"attackRange"` AttackCooldown float64 `yaml:"attackCooldown"` PlayerDamage float64 `yaml:"playerDamage"` + CriticalMultiplier float64 `yaml:"criticalMultiplier"` SpearDamage float64 `yaml:"spearDamage"` GatherRange float64 `yaml:"gatherRange"` GatherCooldown float64 `yaml:"gatherCooldown"` @@ -59,6 +60,8 @@ type Balance struct { BandageHealing float64 `yaml:"bandageHealing"` Progression *Progression `yaml:"progression"` Titles []Title `yaml:"titles"` + Stats *StatsRules `yaml:"stats"` + Items []ItemDefinition `yaml:"items"` } func Load() (Balance, error) { return Parse(balance) } @@ -72,6 +75,17 @@ func Parse(data []byte) (Balance, error) { return b, b.Validate() } func (b Balance) Validate() error { + if b.Stats == nil { + return fmt.Errorf("stats rules are required") + } + if err := b.Stats.Validate(); err != nil { + return err + } + for _, item := range b.Items { + if err := item.Validate(); err != nil { + return err + } + } if err := b.validateProgression(); err != nil { return err } diff --git a/server/content/progression.go b/server/content/progression.go index c2858a8..5cfed07 100644 --- a/server/content/progression.go +++ b/server/content/progression.go @@ -7,33 +7,36 @@ import ( ) type Progression struct { - BaseXP int64 `yaml:"baseXp"` - XPPerLevel int64 `yaml:"xpPerLevel"` - StatPointsPerLevel int64 `yaml:"statPointsPerLevel"` - MaxLevel int64 `yaml:"maxLevel"` - GatherXP int64 `yaml:"gatherXp"` - CraftXP int64 `yaml:"craftXp"` - MobKillXP int64 `yaml:"mobKillXp"` - BossKillXP int64 `yaml:"bossKillXp"` + BaseXP int64 `yaml:"baseXp"` + XPPerLevel int64 `yaml:"xpPerLevel"` + StatPointsPerLevel int64 `yaml:"statPointsPerLevel"` + StaminaPerLevel int64 `yaml:"staminaPerLevel"` + VitalPointsPerChoice int64 `yaml:"vitalPointsPerChoice"` + MaxLevel int64 `yaml:"maxLevel"` + GatherXP int64 `yaml:"gatherXp"` + CraftXP int64 `yaml:"craftXp"` + MobKillXP int64 `yaml:"mobKillXp"` + BossKillXP int64 `yaml:"bossKillXp"` } type TitleRequirement struct { - Metric string `yaml:"metric"` - AtLeast int64 `yaml:"atLeast"` + Metric string `json:"metric" yaml:"metric"` + AtLeast int64 `json:"atLeast" yaml:"atLeast"` } type TitleEffects struct { - Damage float64 `yaml:"damage"` - MoveSpeed float64 `yaml:"moveSpeed"` + Damage float64 `json:"damage" yaml:"damage"` + MoveSpeed float64 `json:"moveSpeed" yaml:"moveSpeed"` + Modifiers []StatModifier `json:"modifiers" yaml:"modifiers"` } type Title struct { - ID string `yaml:"id"` - Name string `yaml:"name"` - Description string `yaml:"description"` - Scope string `yaml:"scope"` - Requirements []TitleRequirement `yaml:"requirements"` - Effects TitleEffects `yaml:"effects"` + ID string `json:"id" yaml:"id"` + Name string `json:"name" yaml:"name"` + Description string `json:"description" yaml:"description"` + Scope string `json:"scope" yaml:"scope"` + Requirements []TitleRequirement `json:"requirements" yaml:"requirements"` + Effects TitleEffects `json:"effects" yaml:"effects"` } var titleID = regexp.MustCompile(`^[a-z][a-z0-9_-]{0,63}$`) @@ -62,7 +65,7 @@ func (b Balance) validateProgression() error { return fmt.Errorf("title %q needs bounded requirements", title.ID) } for _, r := range title.Requirements { - if !metrics[r.Metric] || r.AtLeast < 1 || r.AtLeast > 1000000000 { + if (!metrics[r.Metric] && !KnownStat(r.Metric)) || r.AtLeast < 1 || r.AtLeast > 1000000000 { return fmt.Errorf("invalid title requirement for %q", title.ID) } } @@ -71,11 +74,17 @@ func (b Balance) validateProgression() error { return fmt.Errorf("invalid title effect for %q", title.ID) } } + if err := ValidateModifiers(title.Effects.Modifiers); err != nil { + return err + } } return nil } func (p Progression) Validate() error { + if p.StaminaPerLevel < 1 || p.StaminaPerLevel > 1000 || p.VitalPointsPerChoice < 1 || p.VitalPointsPerChoice > 1000 { + return fmt.Errorf("invalid stamina or vital level reward") + } if p.BaseXP < 1 || p.BaseXP > 1000000000 || p.XPPerLevel < 0 || p.XPPerLevel > 1000000000 || p.StatPointsPerLevel < 1 || p.StatPointsPerLevel > 1000 || p.MaxLevel < 2 || p.MaxLevel > 10000 { return fmt.Errorf("invalid progression curve or stat point grant") } diff --git a/server/content/stats.go b/server/content/stats.go new file mode 100644 index 0000000..b0284fb --- /dev/null +++ b/server/content/stats.go @@ -0,0 +1,162 @@ +package content + +import ( + "fmt" + "math" + "slices" +) + +var PrimaryStats = []string{"constitution", "intelligence", "dexterity", "strength", "wisdom", "charisma", "luck"} +var DerivedStats = []string{"healthPoints", "endurance", "resistance", "healthRecovery", "magicDamage", "knowledge", "spellPoints", "manaPoints", "moveSpeed", "rangedDamage", "criticalChance", "dodgeChance", "staminaRecovery", "meleeDamage", "heavyDamage", "carryCapacity", "defence", "skillPoints", "xpGain", "manaRecovery", "buffEffectiveness", "dropRate", "gatherRate", "stamina"} +var StatLinks = map[string][]string{ + "constitution": {"healthPoints", "endurance", "resistance", "healthRecovery"}, + "intelligence": {"magicDamage", "knowledge", "spellPoints", "manaPoints"}, + "dexterity": {"moveSpeed", "rangedDamage", "criticalChance", "endurance", "dodgeChance", "staminaRecovery"}, + "strength": {"meleeDamage", "heavyDamage", "carryCapacity", "endurance", "defence"}, + "wisdom": {"knowledge", "resistance", "skillPoints", "xpGain", "manaRecovery"}, + "charisma": {"buffEffectiveness"}, + "luck": {"criticalChance", "dropRate", "gatherRate", "dodgeChance"}, +} + +type StatModifier struct { + Stat string `json:"stat" yaml:"stat"` + Flat float64 `json:"flat" yaml:"flat"` + Percent float64 `json:"percent" yaml:"percent"` +} +type StatsRules struct { + Version int `json:"version" yaml:"version"` + Base map[string]float64 `json:"base" yaml:"base"` + Coefficients map[string]map[string]float64 `json:"coefficients" yaml:"coefficients"` +} +type ItemRequirements struct { + Level int64 `json:"level" yaml:"level"` + Stats map[string]float64 `json:"stats" yaml:"stats"` + Titles []string `json:"titles" yaml:"titles"` +} +type ItemDefinition struct { + ID string `json:"id" yaml:"id"` + Name string `json:"name" yaml:"name"` + Description string `json:"description" yaml:"description"` + Slot string `json:"slot" yaml:"slot"` + Weight float64 `json:"weight" yaml:"weight"` + DropChance float64 `json:"dropChance" yaml:"dropChance"` + Requirements ItemRequirements `json:"requirements" yaml:"requirements"` + Modifiers []StatModifier `json:"modifiers" yaml:"modifiers"` +} +type Catalog struct { + Version int64 `json:"version"` + Titles []Title `json:"titles"` + Items []ItemDefinition `json:"items"` + Stats StatsRules `json:"stats"` +} + +func KnownStat(stat string) bool { + return slices.Contains(PrimaryStats, stat) || slices.Contains(DerivedStats, stat) +} +func (s StatsRules) Validate() error { + if s.Version != 1 || len(s.Base) != len(PrimaryStats)+len(DerivedStats) || len(s.Coefficients) != len(PrimaryStats) { + return fmt.Errorf("invalid stats rule version or missing stat values") + } + for k, v := range s.Base { + if !KnownStat(k) || math.IsNaN(v) || math.IsInf(v, 0) || v < 0 || v > 1000000 { + return fmt.Errorf("invalid stat base %q", k) + } + } + if s.Base["healthPoints"] < 50 || s.Base["stamina"] < 1 { + return fmt.Errorf("base health must be at least 50 and stamina positive") + } + for primary, links := range StatLinks { + coefficients, ok := s.Coefficients[primary] + if !ok || len(coefficients) != len(links) { + return fmt.Errorf("missing coefficients for %s", primary) + } + for derived, v := range coefficients { + if !slices.Contains(links, derived) || math.IsNaN(v) || math.IsInf(v, 0) || v < 0 || v > 1000 { + return fmt.Errorf("invalid coefficient %s -> %s", primary, derived) + } + } + } + return nil +} +func ValidateModifiers(modifiers []StatModifier) error { + if len(modifiers) > 64 { + return fmt.Errorf("too many modifiers") + } + for _, m := range modifiers { + if !KnownStat(m.Stat) || math.IsNaN(m.Flat) || math.IsInf(m.Flat, 0) || math.Abs(m.Flat) > 1000000 || math.IsNaN(m.Percent) || math.IsInf(m.Percent, 0) || m.Percent < -100 || m.Percent > 10000 { + return fmt.Errorf("invalid modifier for %q", m.Stat) + } + } + return nil +} +func ValidItemSlot(slot string) bool { + return slices.Contains([]string{"helmet", "mask", "chest", "shoulders", "pants", "boots", "gloves", "earrings", "necklace", "ring", "weapon", "offhand", "cape", "bag"}, slot) +} +func (item ItemDefinition) Validate() error { + if slices.Contains([]string{"axe","flint_and_steel","fishing_pole","wood","ore","herb","bandage"},item.ID){return fmt.Errorf("equipment ID conflicts with a stackable item")} + if math.IsNaN(item.DropChance) || math.IsInf(item.DropChance, 0) || item.DropChance < 0 || item.DropChance > 100 { + return fmt.Errorf("invalid drop chance") + } + if !titleID.MatchString(item.ID) || len(item.Name) < 1 || len(item.Name) > 80 || len(item.Description) > 500 || !ValidItemSlot(item.Slot) || math.IsNaN(item.Weight) || math.IsInf(item.Weight, 0) || item.Weight < 0 || item.Weight > 10000 { + return fmt.Errorf("invalid equipment definition %q", item.ID) + } + if item.Requirements.Level < 1 || item.Requirements.Level > 10000 || len(item.Requirements.Stats) > len(PrimaryStats)+len(DerivedStats) || len(item.Requirements.Titles) > 64 { + return fmt.Errorf("invalid requirements for %q", item.ID) + } + for key, n := range item.Requirements.Stats { + if !KnownStat(key) || math.IsNaN(n) || math.IsInf(n, 0) || n < 0 || n > 1000000 { + return fmt.Errorf("invalid required stat %q", key) + } + } + seen := map[string]bool{} + for _, id := range item.Requirements.Titles { + if !titleID.MatchString(id) || seen[id] { + return fmt.Errorf("invalid required title %q", id) + } + seen[id] = true + } + return ValidateModifiers(item.Modifiers) +} +func (c Catalog) Validate() error { + if c.Version < 1 || len(c.Items) > 512 { + return fmt.Errorf("invalid catalog version or item count") + } + if err := c.Stats.Validate(); err != nil { + return err + } + defaults, err := Load() + if err != nil { + return err + } + defaults.Titles = c.Titles + if err = defaults.validateProgression(); err != nil { + return err + } + titles := map[string]bool{} + for _, title := range c.Titles { + titles[title.ID] = true + } + seen := map[string]bool{} + for _, item := range c.Items { + if seen[item.ID] { + return fmt.Errorf("duplicate item %q", item.ID) + } + seen[item.ID] = true + if err = item.Validate(); err != nil { + return err + } + for _, id := range item.Requirements.Titles { + if !titles[id] { + return fmt.Errorf("unknown required title %q", id) + } + } + } + return nil +} +func DefaultCatalog() (Catalog, error) { + b, err := Load() + if err != nil { + return Catalog{}, err + } + return Catalog{Version: 1, Titles: b.Titles, Items: b.Items, Stats: *b.Stats}, nil +} diff --git a/server/content/stats_test.go b/server/content/stats_test.go new file mode 100644 index 0000000..6107a3d --- /dev/null +++ b/server/content/stats_test.go @@ -0,0 +1,27 @@ +package content + +import ( + "math" + "testing" +) + +func TestCatalogRejectsInvalidStatsAndItemRequirements(t *testing.T) { + for name, mutate:=range map[string]func(*Catalog){ + "unknown stat":func(c *Catalog){c.Stats.Base["admin"]=1}, + "negative primary":func(c *Catalog){c.Stats.Base["constitution"]=-1}, + "nonfinite coefficient":func(c *Catalog){c.Stats.Coefficients["luck"]["criticalChance"]=math.NaN()}, + "unrelated coefficient":func(c *Catalog){delete(c.Stats.Coefficients["charisma"],"buffEffectiveness");c.Stats.Coefficients["charisma"]["healthPoints"]=1}, + "unknown modifier":func(c *Catalog){c.Titles[0].Effects.Modifiers=[]StatModifier{{Stat:"dailySeconds",Flat:100}}}, + "unsafe percentage":func(c *Catalog){c.Titles[0].Effects.Modifiers=[]StatModifier{{Stat:"strength",Percent:-101}}}, + "invalid slot":func(c *Catalog){c.Items[0].Slot="ring9"}, + "unknown title":func(c *Catalog){c.Items[0].Requirements.Titles=[]string{"missing"}}, + "duplicate item":func(c *Catalog){c.Items=append(c.Items,c.Items[0])}, + "stack collision":func(c *Catalog){c.Items[0].ID="wood"}, + "invalid drop chance":func(c *Catalog){c.Items[0].DropChance=101}, + } { + t.Run(name,func(t *testing.T){c,err:=DefaultCatalog();if err!=nil{t.Fatal(err)};mutate(&c);if err=c.Validate();err==nil{t.Fatal("invalid catalog accepted")}}) + } + c,err:=DefaultCatalog();if err!=nil{t.Fatal(err)} + c.Items=append(c.Items,ItemDefinition{ID:"cursed_ring",Name:"Cursed ring",Slot:"ring",Weight:1,DropChance:2,Requirements:ItemRequirements{Level:2,Stats:map[string]float64{"constitution":3},Titles:[]string{"wayfarer"}},Modifiers:[]StatModifier{{Stat:"constitution",Flat:2,Percent:10},{Stat:"moveSpeed",Percent:-10}}}) + if err=c.Validate();err!=nil{t.Fatal(err)} +} diff --git a/server/internal/game/equipment.go b/server/internal/game/equipment.go new file mode 100644 index 0000000..7878913 --- /dev/null +++ b/server/internal/game/equipment.go @@ -0,0 +1,87 @@ +package game + +import ( + "errors" + "fmt" + "math" + "sort" + p "aeternalis/server/internal/protocol" +) + +var equipmentSlots = []string{"helmet", "mask", "chest", "shoulders", "pants", "boots", "gloves", "earrings", "necklace", "ring1", "ring2", "ring3", "ring4", "ring5", "ring6", "ring7", "ring8", "weapon", "offhand", "cape", "bag"} +func validEquipmentSlot(slot string) bool { + for _, candidate := range equipmentSlots { if slot == candidate { return true } }; return false +} +func itemFitsSlot(item p.ItemInstance, slot string) bool { + if !validEquipmentSlot(slot) { return false } + if item.Slot == "ring" { return len(slot) == 5 && slot[:4] == "ring" }; return item.Slot == slot +} +func ownedItem(c *Character, id string) *p.ItemInstance { + for i := range c.View.Items { if c.View.Items[i].ID == id { return &c.View.Items[i] } }; return nil +} +// Definitions are copied at acquisition; passage cannot replace an owned item. +func (w *World) addInventoryItems(inventory *map[string]int64, items *[]p.ItemInstance, name string, quantity int64) error { + if quantity < 1 { return errors.New("invalid item quantity") } + if *inventory == nil { *inventory = map[string]int64{} }; if *items == nil { *items = []p.ItemInstance{} } + for _, definition := range w.Balance.Items { + if definition.ID != name { continue } + if quantity > 100000 { return errors.New("equipment quantity exceeds migration limit") } + created := make([]p.ItemInstance, 0, int(quantity)) + for n := int64(0); n < quantity; n++ { + item := p.ItemInstance{ID: ID(), DefinitionID: definition.ID, Name: definition.Name, Description: definition.Description, Slot: definition.Slot, Weight: definition.Weight, + Requirements: p.ItemRequirements{Level: definition.Requirements.Level, Stats: map[string]float64{}, Titles: append([]string{}, definition.Requirements.Titles...)}, Modifiers: []p.StatModifier{}} + for stat, value := range definition.Requirements.Stats { item.Requirements.Stats[stat] = value } + for _, modifier := range definition.Modifiers { item.Modifiers = append(item.Modifiers, p.StatModifier{Stat: modifier.Stat, Flat: modifier.Flat, Percent: modifier.Percent}) } + created = append(created, item) + } + *items = append(*items, created...); return nil + } + if (*inventory)[name] > math.MaxInt64-quantity { return errors.New("item quantity overflow") } + (*inventory)[name] += quantity; return nil +} +func (w *World) grantItems(c *Character, name string, quantity int64) error { + if err := w.addInventoryItems(&c.View.Inventory, &c.View.Items, name, quantity); err != nil { return err } + w.RefreshStats(c); w.dirty = true; return nil +} +func (w *World) migrateEquipment(inventory *map[string]int64, items *[]p.ItemInstance) error { + if *inventory == nil { *inventory = map[string]int64{} }; if *items == nil { *items = []p.ItemInstance{} } + names := make([]string, 0, len(*inventory)) + for name, quantity := range *inventory { if quantity < 0 { return errors.New("negative persisted inventory") }; names = append(names, name) }; sort.Strings(names) + for _, name := range names { + quantity := (*inventory)[name] + for _, definition := range w.Balance.Items { + if definition.ID != name { continue } + if quantity > 0 { if err := w.addInventoryItems(inventory, items, name, quantity); err != nil { return err } } + delete(*inventory, name); w.dirty = true; break + } + }; return nil +} +func validateOwnedItems(items []p.ItemInstance, seen map[string]bool) error { + for _, item := range items { + if item.ID == "" || len(item.ID) > 100 || seen[item.ID] || item.DefinitionID == "" || item.Name == "" || (item.Slot != "ring" && !validEquipmentSlot(item.Slot)) || math.IsNaN(item.Weight) || math.IsInf(item.Weight, 0) || item.Weight < 0 || item.Requirements.Level < 1 { + return errors.New("invalid or duplicate persisted equipment") + } + seen[item.ID] = true + for _, value := range item.Requirements.Stats { if math.IsNaN(value) || math.IsInf(value, 0) || value < 0 { return errors.New("invalid equipment requirement") } } + for _, modifier := range item.Modifiers { if modifier.Stat == "" || math.IsNaN(modifier.Flat) || math.IsInf(modifier.Flat, 0) || math.IsNaN(modifier.Percent) || math.IsInf(modifier.Percent, 0) { return errors.New("invalid equipment modifier") } } + }; return nil +} +func (w *World) restoreEquipment(c *Character) error { + if err := w.migrateEquipment(&c.View.Inventory, &c.View.Items); err != nil { return err } + if c.View.Equipment == nil { c.View.Equipment = map[string]string{} } + if err := validateOwnedItems(c.View.Items, map[string]bool{}); err != nil { return err } + seen := map[string]bool{} + for slot, id := range c.View.Equipment { + item := ownedItem(c, id) + if item == nil || !itemFitsSlot(*item, slot) || seen[id] { return errors.New("invalid persisted equipment assignment") }; seen[id] = true + } + if c.View.Entity.State == "dead" && (len(c.View.Items) != 0 || len(c.View.Equipment) != 0) { return errors.New("dead character still owns equipment") }; return nil +} +func (w *World) restoreCorpseEquipment() error { + seen := map[string]bool{} + for _, c := range w.Characters { if err := validateOwnedItems(c.View.Items, seen); err != nil { return err } } + for _, corpse := range w.Corpses { + if err := w.migrateEquipment(&corpse.Inventory, &corpse.Items); err != nil { return err } + if err := validateOwnedItems(corpse.Items, seen); err != nil { return err } + }; return nil +} diff --git a/server/internal/game/progression.go b/server/internal/game/progression.go index 1d4a9dc..7ceaf01 100644 --- a/server/internal/game/progression.go +++ b/server/internal/game/progression.go @@ -31,10 +31,26 @@ func (w *World) orderedCharacters() []*Character { } func (w *World) restoreProgression(c *Character) error { + if c.View.Level == 0 { + c.View.Level = 1 + } if c.Progression == nil { rules := *w.Balance.Progression c.Progression = &rules } + if c.StatsVersion == 0 { + rules := *c.Progression + if rules.StatPointsPerLevel < w.Balance.Progression.StatPointsPerLevel { + c.View.StatPoints += (c.View.Level - 1) * (w.Balance.Progression.StatPointsPerLevel - rules.StatPointsPerLevel) + } + rules.StatPointsPerLevel = w.Balance.Progression.StatPointsPerLevel + rules.StaminaPerLevel = w.Balance.Progression.StaminaPerLevel + rules.VitalPointsPerChoice = w.Balance.Progression.VitalPointsPerChoice + c.Progression = &rules + c.View.PendingVitalChoices = c.View.Level - 1 + c.StatsVersion = 1 + w.dirty = true + } if err := c.Progression.Validate(); err != nil { return err } @@ -65,13 +81,16 @@ func (w *World) grantXP(c *Character, amount int64) { if amount <= 0 || c.View.Entity.State != "alive" || c.View.Level >= c.Progression.MaxLevel { return } + amount = int64(math.Min(1000000000, math.Floor(float64(amount)*c.View.Stats["xpGain"].Final/100))) c.View.Experience += amount before := c.View.Level for c.View.Level < c.Progression.MaxLevel && c.View.Experience >= c.nextLevelXP() { c.View.Experience -= c.nextLevelXP() c.View.Level++ c.View.StatPoints += c.Progression.StatPointsPerLevel + c.View.PendingVitalChoices++ } + w.RefreshStats(c) c.View.ExperienceToNextLevel = c.nextLevelXP() if c.View.ExperienceToNextLevel == 0 { c.View.Experience = 0 @@ -101,6 +120,9 @@ func (w *World) evaluateTitles(c *Character) { } return 0 default: + if value, ok := c.View.Stats[name]; ok { + return int64(math.Floor(value.Final)) + } return c.View.Skills[name] } } @@ -136,7 +158,7 @@ func (w *World) evaluateTitles(c *Character) { } w.PendingTitles = append(w.PendingTitles, TitleCandidate{CharacterID: c.View.Entity.ID, Award: p.TitleAward{ ID: title.ID, Name: title.Name, Description: title.Description, Scope: title.Scope, WorldID: w.ID, - EarnedAt: w.now.UTC().Format(time.RFC3339Nano), Effects: p.TitleEffects{Damage: title.Effects.Damage, MoveSpeed: title.Effects.MoveSpeed}, + EarnedAt: w.now.UTC().Format(time.RFC3339Nano), Effects: p.TitleEffects{Damage: title.Effects.Damage, MoveSpeed: title.Effects.MoveSpeed, Modifiers: protocolModifiers(title.Effects.Modifiers)}, }}) w.dirty = true } @@ -158,5 +180,5 @@ func (c *Character) titleEffects() p.TitleEffects { } func (w *World) playerSpeed(c *Character) float64 { - return math.Max(0, w.Balance.PlayerSpeed+c.titleEffects().MoveSpeed) + return c.View.Stats["moveSpeed"].Final } diff --git a/server/internal/game/stats.go b/server/internal/game/stats.go new file mode 100644 index 0000000..2793a6e --- /dev/null +++ b/server/internal/game/stats.go @@ -0,0 +1,198 @@ +package game + +import ( + "crypto/sha256" + "encoding/binary" + "errors" + "fmt" + "math" + "slices" + + "aeternalis/server/content" + p "aeternalis/server/internal/protocol" +) + +func protocolModifiers(in []content.StatModifier) []p.StatModifier { + out := make([]p.StatModifier, 0, len(in)) + for _, m := range in { + out = append(out, p.StatModifier{Stat: m.Stat, Flat: m.Flat, Percent: m.Percent}) + } + return out +} +func (w *World) statValues(c *Character, equipment bool) map[string]p.StatValue { + modifiers := []p.StatModifier{} + seen := map[string]bool{} + for _, title := range c.View.Titles { + if seen[title.ID] { + continue + } + seen[title.ID] = true + modifiers = append(modifiers, title.Effects.Modifiers...) + modifiers = append(modifiers, p.StatModifier{Stat: "meleeDamage", Flat: title.Effects.Damage}, p.StatModifier{Stat: "moveSpeed", Flat: title.Effects.MoveSpeed}) + } + if equipment { + ids := map[string]bool{} + for _, id := range c.View.Equipment { + ids[id] = true + } + for _, item := range c.View.Items { + if ids[item.ID] { + modifiers = append(modifiers, item.Modifiers...) + } + } + } + values := map[string]p.StatValue{} + finish := func(key string, base float64) { + v := p.StatValue{Base: base} + for _, m := range modifiers { + if m.Stat == key { + v.Flat += m.Flat + v.Percent += m.Percent + } + } + v.Final = math.Max(0, (v.Base+v.Flat)*math.Max(0, 1+v.Percent/100)) + if key == "healthPoints" { + v.Final = math.Max(50, v.Final) + } + if key == "criticalChance" || key == "dodgeChance" { + v.Final = math.Min(100, v.Final) + } + values[key] = v + } + for _, key := range content.PrimaryStats { + finish(key, w.Balance.Stats.Base[key]+float64(c.View.AllocatedStats[key])) + } + for _, key := range content.DerivedStats { + base := w.Balance.Stats.Base[key] + for _, primary := range content.PrimaryStats { + base += values[primary].Final * w.Balance.Stats.Coefficients[primary][key] + } + switch key { + case "healthPoints": + base += float64(c.View.HealthChoices * c.Progression.VitalPointsPerChoice) + case "manaPoints": + base += float64(c.View.ManaChoices * c.Progression.VitalPointsPerChoice) + case "stamina": + base += float64((c.View.Level - 1) * c.Progression.StaminaPerLevel) + } + finish(key, base) + } + return values +} + +// Requirements exclude every equipment bonus to prevent self/cyclic enabling. +func (w *World) RequirementStats(c *Character) map[string]p.StatValue { return w.statValues(c, false) } +func (w *World) RefreshStats(c *Character) { + if c.View.Entity.State == "dead" && len(c.View.Stats) > 0 { + return + } + w.revalidateEquipment(c) + c.View.Stats = w.statValues(c, true) + c.View.Entity.MaxHP = c.View.Stats["healthPoints"].Final + c.View.Entity.HP = math.Min(c.View.Entity.HP, c.View.Entity.MaxHP) + c.View.Mana = math.Max(0, math.Min(c.View.Mana, c.View.Stats["manaPoints"].Final)) + c.View.Stamina = math.Max(0, math.Min(c.View.Stamina, c.View.Stats["stamina"].Final)) + c.View.CarryWeight = 0 + for _, item := range c.View.Items { + c.View.CarryWeight += item.Weight + } + // Stack quantities have unit weight in this first inventory version. + for _, n := range c.View.Inventory { + c.View.CarryWeight += float64(n) + } +} +func (w *World) initializeStats(c *Character) error { + newResources := c.View.Stats == nil + if c.View.AllocatedStats == nil { + c.View.AllocatedStats = map[string]int64{} + } + spent := int64(0) + for key, n := range c.View.AllocatedStats { + if !slices.Contains(content.PrimaryStats, key) || n < 0 || n > 10000000 { + return errors.New("invalid allocated stats") + } + } + for _, n := range c.View.AllocatedStats { + spent += n + } + if spent+c.View.StatPoints != (c.View.Level-1)*c.Progression.StatPointsPerLevel { + return errors.New("allocated and unspent points do not match earned levels") + } + if c.View.PendingVitalChoices < 0 || c.View.HealthChoices < 0 || c.View.ManaChoices < 0 || c.View.PendingVitalChoices+c.View.HealthChoices+c.View.ManaChoices != c.View.Level-1 { + return errors.New("invalid level reward choices") + } + w.RefreshStats(c) + if newResources && c.View.Entity.State != "dead" { + c.View.Mana = c.View.Stats["manaPoints"].Final + c.View.Stamina = c.View.Stats["stamina"].Final + } + return nil +} +func (w *World) allocateStat(c *Character, key string) error { + if !slices.Contains(content.PrimaryStats, key) || c.View.StatPoints < 1 { + return errors.New("choose a primary stat with an available point") + } + c.View.AllocatedStats[key]++ + c.View.StatPoints-- + w.RefreshStats(c) + w.evaluateTitles(c) + w.dirty = true + return nil +} +func (w *World) chooseVital(c *Character, key string) error { + if c.View.PendingVitalChoices < 1 || (key != "health" && key != "mana") { + return errors.New("no pending health or mana choice") + } + if key == "health" { + c.View.HealthChoices++ + } else { + c.View.ManaChoices++ + } + c.View.PendingVitalChoices-- + w.RefreshStats(c) + w.evaluateTitles(c) + w.dirty = true + return nil +} +func (w *World) ApplyCatalog(catalog content.Catalog) error { + if catalog.Version <= w.CatalogVersion { + return nil + } + if err := catalog.Validate(); err != nil { + return err + } + w.Balance.Titles = catalog.Titles + w.Balance.Items = catalog.Items + w.Balance.Stats = &catalog.Stats + w.CatalogVersion = catalog.Version + for _, c := range w.orderedCharacters() { + w.RefreshStats(c) + } + w.dirty = true + return nil +} +func (w *World) roll(chance float64) bool { + if chance <= 0 { + return false + } + if chance >= 100 { + return true + } + w.RandomCounter++ + sum := sha256.Sum256([]byte(fmt.Sprintf("%d:%d", w.Seed, w.RandomCounter))) + return float64(binary.LittleEndian.Uint64(sum[:8])>>11)/float64(uint64(1)<<53)*100 < chance +} +func (w *World) yieldAmount(rate float64) int64 { + amount := math.Max(0, math.Min(100, rate/100)) + n := int64(math.Floor(amount)) + if w.roll((amount - float64(n)) * 100) { + n++ + } + return n +} +func (w *World) damageCharacter(c *Character, amount float64) { + if w.roll(c.View.Stats["dodgeChance"].Final) { + return + } + c.View.Entity.HP -= math.Max(0, amount-c.View.Stats["defence"].Final) +} diff --git a/server/internal/game/stats_test.go b/server/internal/game/stats_test.go new file mode 100644 index 0000000..875a4ea --- /dev/null +++ b/server/internal/game/stats_test.go @@ -0,0 +1,83 @@ +package game + +import ( + "encoding/json" + "math" + "testing" + "time" + + "aeternalis/server/content" + p "aeternalis/server/internal/protocol" +) + +func TestLevelRewardsAndPrimaryAllocation(t *testing.T) { + w,c:=fixture(t) + w.grantXP(c,100) + if c.View.Level!=2||c.View.StatPoints!=10||c.View.PendingVitalChoices!=1||c.View.Stats["stamina"].Final!=105{t.Fatalf("wrong level rewards: %+v",c.View)} + for i:=0;i<3;i++{if err:=w.allocateStat(c,"constitution");err!=nil{t.Fatal(err)}} + if c.View.StatPoints!=7||c.View.Stats["constitution"].Final!=3||c.View.Entity.MaxHP!=115{t.Fatal("constitution did not update derived health")} + if err:=w.chooseVital(c,"health");err!=nil{t.Fatal(err)} + if c.View.Entity.MaxHP!=120||c.View.HealthChoices!=1||c.View.PendingVitalChoices!=0{t.Fatal("health choice not applied")} + if w.chooseVital(c,"mana")==nil||w.allocateStat(c,"healthPoints")==nil{t.Fatal("duplicate vital or direct derived allocation accepted")} + w.grantXP(c,150) + if err:=w.chooseVital(c,"mana");err!=nil{t.Fatal(err)} + if c.View.Stats["manaPoints"].Final!=55||c.View.Stats["stamina"].Final!=110||c.View.StatPoints!=17{t.Fatal("second level rewards incorrect")} + for c.View.StatPoints>0 {if err:=w.allocateStat(c,"dexterity");err!=nil{t.Fatal(err)}} + before:=c.View.Stats["dexterity"].Final + if w.allocateStat(c,"dexterity")==nil||c.View.Stats["dexterity"].Final!=before{t.Fatal("overspent banked points")} +} + +func TestStatBreakdownUsesEffectivePrimaryThenFlatAndPercent(t *testing.T) { + w,c:=fixture(t);w.grantXP(c,100) + for i:=0;i<4;i++{if err:=w.allocateStat(c,"strength");err!=nil{t.Fatal(err)}} + c.View.Titles=[]p.TitleAward{{ID:"mixed",Effects:p.TitleEffects{Modifiers:[]p.StatModifier{{Stat:"strength",Flat:2,Percent:50},{Stat:"meleeDamage",Flat:3,Percent:20},{Stat:"moveSpeed",Percent:-25}}}}} + w.RefreshStats(c) + strength:=c.View.Stats["strength"] + if strength.Base!=4||strength.Flat!=2||strength.Percent!=50||strength.Final!=9{t.Fatalf("bad primary breakdown: %+v",strength)} + damage:=c.View.Stats["meleeDamage"] + if damage.Base!=27||damage.Flat!=3||damage.Percent!=20||math.Abs(damage.Final-36)>1e-8{t.Fatalf("bad derived breakdown: %+v",damage)} + if w.playerSpeed(c)!=9{t.Fatal("negative percentage movement not applied")} + c.View.Titles=append(c.View.Titles,p.TitleAward{ID:"curse",Effects:p.TitleEffects{Modifiers:[]p.StatModifier{{Stat:"healthPoints",Percent:-100},{Stat:"moveSpeed",Percent:-100}}}}) + w.RefreshStats(c) + if c.View.Entity.MaxHP!=50||w.playerSpeed(c)!=0{t.Fatal("vital safety floor or zero speed bound failed")} +} + +func TestStatsMigrationAndTransferPreserveEarnedRewards(t *testing.T) { + w,c:=fixture(t) + c.View.Level=3;c.View.Experience=25;c.View.StatPoints=10;c.StatsVersion=0 + c.View.AllocatedStats=nil;c.View.Stats=nil;c.View.PendingVitalChoices=0 + old:=*c.Progression;old.StatPointsPerLevel=5;old.StaminaPerLevel=0;old.VitalPointsPerChoice=0;c.Progression=&old + w.Balance.Stats=nil + c.DailySeconds=321 + 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)} + if err=restored.Restore(w.now);err!=nil{t.Fatal(err)} + migrated:=restored.Characters[c.View.Entity.ID] + if migrated.View.StatPoints!=20||migrated.View.PendingVitalChoices!=2||migrated.View.Stats["stamina"].Final!=110||migrated.DailySeconds!=321{t.Fatal("legacy level rewards not migrated once")} + if err=restored.Restore(w.now);err!=nil{t.Fatal(err)} + if migrated.View.StatPoints!=20||migrated.View.PendingVitalChoices!=2{t.Fatal("repeated restore duplicated rewards")} + if err=restored.allocateStat(migrated,"wisdom");err!=nil{t.Fatal(err)} + if err=restored.chooseVital(migrated,"mana");err!=nil{t.Fatal(err)} + migrated.View.Entity.State="eligible" + next:=New("stats-next",999,w.now,restored.Balance) + if err=next.Import(migrated);err!=nil{t.Fatal(err)} + if migrated.View.StatPoints!=19||migrated.View.AllocatedStats["wisdom"]!=1||migrated.View.PendingVitalChoices!=1||migrated.View.ManaChoices!=1||migrated.DailySeconds!=321{t.Fatal("transfer altered rewards or daily budget")} + next.kill(migrated,"test") + if next.Connect(migrated.View.Entity.ID)==nil{t.Fatal("stat feature resurrected a life")} + if next.Intent(migrated.View.Entity.ID,p.Intent{Op:"allocate-stat",Target:"strength",Seq:1})==nil{t.Fatal("dead life allocated a point")} +} + +func TestCatalogChangesDoNotHealOrRewriteDeadStats(t *testing.T) { + w,c:=fixture(t) + dead,err:=w.Join("dead-stats","Dead");if err!=nil{t.Fatal(err)} + w.kill(dead,"test") + prior:=dead.View.Stats["healthPoints"].Final + c.View.Entity.HP=20;c.DailySeconds=123 + catalog,err:=content.DefaultCatalog();if err!=nil{t.Fatal(err)} + catalog.Version=2;catalog.Stats.Base["healthPoints"]=200 + if err=w.ApplyCatalog(catalog);err!=nil{t.Fatal(err)} + if c.View.Entity.MaxHP!=200||c.View.Entity.HP!=20||c.DailySeconds!=123||dead.View.Entity.State!="dead"||dead.View.Stats["healthPoints"].Final!=prior{t.Fatal("catalog changed life/budget/history")} + w.Balance.DailyPlaySeconds=124 + w.Advance(w.now.Add(2*time.Second),2) + if c.Online||c.View.RemainingSeconds!=0||c.View.Entity.HP!=50{t.Fatal("expanded stats weakened daily cap")} +} diff --git a/server/internal/game/world.go b/server/internal/game/world.go index d4abce7..a0ee015 100644 --- a/server/internal/game/world.go +++ b/server/internal/game/world.go @@ -34,10 +34,12 @@ type Character struct { WorldKills int64 `json:"worldKills"` BossKills int64 `json:"bossKills"` WorldsSurvived int64 `json:"worldsSurvived"` + StatsVersion int `json:"statsVersion"` } type Corpse struct { Entity p.Entity `json:"entity"` Inventory map[string]int64 `json:"inventory"` + Items []p.ItemInstance `json:"items"` } type Mob struct { Entity p.Entity `json:"entity"` @@ -63,6 +65,8 @@ type World struct { Mobs map[string]*Mob `json:"mobs"` Balance content.Balance `json:"balance"` PendingTitles []TitleCandidate `json:"-"` + CatalogVersion int64 `json:"catalogVersion"` + RandomCounter uint64 `json:"randomCounter"` terrain *Terrain chunks map[string]p.Chunk now time.Time @@ -98,6 +102,26 @@ func (w *World) Restore(now time.Time) error { } w.dirty = true } + if w.Balance.Stats == nil { + defaults, err := content.Load() + if err != nil { + return err + } + w.Balance.Stats = defaults.Stats + w.Balance.Items = defaults.Items + rules := *w.Balance.Progression + rules.StatPointsPerLevel = defaults.Progression.StatPointsPerLevel + rules.StaminaPerLevel = defaults.Progression.StaminaPerLevel + rules.VitalPointsPerChoice = defaults.Progression.VitalPointsPerChoice + w.Balance.Progression = &rules + w.dirty = true + } + if w.Balance.CriticalMultiplier == 0 { + defaults, err := content.Load() + if err != nil { return err } + w.Balance.CriticalMultiplier = defaults.CriticalMultiplier + w.dirty = true + } if err := w.Balance.Validate(); err != nil { return err } @@ -112,6 +136,12 @@ func (w *World) Restore(now time.Time) error { if err := w.restoreProgression(c); err != nil { return err } + if err := w.restoreEquipment(c); err != nil { + return err + } + if err := w.initializeStats(c); err != nil { + return err + } c.Online = false c.MoveX = 0 c.MoveZ = 0 @@ -205,6 +235,8 @@ func (w *World) Join(account, name string) (*Character, error) { for k, v := range w.Balance.StartingKit { c.View.Inventory[k] = v } + if err := w.restoreEquipment(c); err != nil { return nil, err } + if err := w.initializeStats(c); err != nil { return nil, err } w.Characters[c.View.Entity.ID] = c c.BornAt = w.now w.evaluateTitles(c) @@ -221,6 +253,8 @@ func (w *World) Import(c *Character) error { if err := w.restoreProgression(c); err != nil { return err } + if err := w.restoreEquipment(c); err != nil { return err } + if err := w.initializeStats(c); err != nil { return err } pos, err := w.spawn("") if err != nil { return err @@ -307,15 +341,25 @@ func (w *World) Intent(id string, i p.Intent) error { if i.Seq <= c.View.ACK || i.Seq > c.View.ACK+10000 { return errors.New("invalid input sequence") } - if math.IsNaN(i.X) || math.IsNaN(i.Z) || math.IsInf(i.X, 0) || math.IsInf(i.Z, 0) || math.Abs(i.X) > 1 || math.Abs(i.Z) > 1 || len(i.Target) > 100 { + if math.IsNaN(i.X) || math.IsNaN(i.Z) || math.IsInf(i.X, 0) || math.IsInf(i.Z, 0) || math.Abs(i.X) > 1 || math.Abs(i.Z) > 1 || len(i.Target) > 100 || len(i.Slot) > 30 { return errors.New("invalid intent") } c.View.ACK = i.Seq - if c.Sheltered && ((i.Op == "move" && (i.X != 0 || i.Z != 0)) || (i.Op != "move" && i.Op != "heal")) { + if c.Sheltered && ((i.Op == "move" && (i.X != 0 || i.Z != 0)) || (i.Op != "move" && i.Op != "heal" && i.Op != "allocate-stat" && i.Op != "choose-vital" && i.Op != "equip" && i.Op != "unequip" && i.Op != "drop")) { c.Sheltered = false w.dirty = true } switch i.Op { + case "allocate-stat": + return w.allocateStat(c, i.Target) + case "choose-vital": + return w.chooseVital(c, i.Target) + case "equip": + return w.equip(c, i.Target, i.Slot) + case "unequip": + return w.unequip(c, i.Target) + case "drop": + return w.dropItem(c, i.Target) case "move": n := math.Max(1, math.Hypot(i.X, i.Z)) c.MoveX = i.X / n @@ -333,6 +377,7 @@ func (w *World) Intent(id string, i p.Intent) error { return errors.New("no bandage needed or available") } c.View.Inventory["bandage"]-- + w.RefreshStats(c) c.View.Entity.HP = math.Min(c.View.Entity.MaxHP, c.View.Entity.HP+w.Balance.BandageHealing) w.dirty = true case "return": @@ -347,15 +392,7 @@ func (w *World) Intent(id string, i p.Intent) error { c.View.HasKeystone = false w.dirty = true case "loot": - corpse := w.Corpses[i.Target] - if corpse == nil || distance(c.View.Entity.Position, corpse.Entity.Position) > w.Balance.GatherRange { - return errors.New("corpse out of reach") - } - for k, v := range corpse.Inventory { - c.View.Inventory[k] += v - } - delete(w.Corpses, i.Target) - w.dirty = true + return w.lootCorpse(c, i.Target) default: return errors.New("unknown intent") } @@ -380,7 +417,7 @@ func (w *World) gather(c *Character, target string) error { if item == "" { return errors.New("not gatherable") } - c.View.Inventory[item]++ + c.View.Inventory[item] += w.yieldAmount(c.View.Stats["gatherRate"].Final) c.View.Skills["gathering"] += w.Balance.SkillXpPerAction c.LastGather = w.Age() w.Depleted[target] = w.Age() + w.Balance.ResourceRespawnSeconds @@ -407,8 +444,9 @@ func (w *World) craft(c *Character, name string) error { c.View.Inventory[k] -= v } for k, v := range r.Outputs { - c.View.Inventory[k] += v + if err := w.grantItems(c, k, v); err != nil { return err } } + w.RefreshStats(c) c.View.Skills["crafting"] += w.Balance.SkillXpPerAction c.Message = "Crafted " + name w.grantXP(c, w.Balance.Progression.CraftXP) @@ -420,15 +458,14 @@ func (w *World) attack(c *Character, target string) error { if w.Age()-c.LastAttack < w.Balance.AttackCooldown { return errors.New("attack cooldown") } - damage := w.Balance.PlayerDamage - if c.View.Inventory["spear"] > 0 { - damage = w.Balance.SpearDamage - } - damage = math.Max(0, damage+c.titleEffects().Damage) + damage := c.View.Stats["meleeDamage"].Final if target == "boss" { if w.Phase != "cataclysm" || distance(c.View.Entity.Position, w.terrain.Position(0, 0)) > w.Balance.AttackRange+4 { return errors.New("boss out of reach") } + if w.roll(c.View.Stats["criticalChance"].Final) { + damage *= w.Balance.CriticalMultiplier + } w.BossHP = math.Max(0, w.BossHP-damage) if w.BossHP == 0 { c.BossKills++ @@ -454,13 +491,21 @@ func (w *World) attack(c *Character, target string) error { if m == nil || m.Entity.HP <= 0 || distance(c.View.Entity.Position, m.Entity.Position) > w.Balance.AttackRange { return errors.New("target out of reach") } + if w.roll(c.View.Stats["criticalChance"].Final) { + damage *= w.Balance.CriticalMultiplier + } m.Entity.HP = math.Max(0, m.Entity.HP-damage) if m.Entity.HP == 0 { m.Entity.State = "dead" m.RespawnAt = w.Age() + w.Balance.MobRespawnSeconds c.View.Kills++ c.WorldKills++ - c.View.Inventory["herb"]++ + c.View.Inventory["herb"] += w.yieldAmount(c.View.Stats["dropRate"].Final) + for _, item := range w.Balance.Items { + if w.roll(item.DropChance*c.View.Stats["dropRate"].Final/100) { + if err := w.grantItems(c, item.ID, 1); err != nil { return err } + } + } w.grantXP(c, w.Balance.Progression.MobKillXP) } } @@ -479,8 +524,11 @@ func (w *World) kill(c *Character, reason string) { e.Kind = "corpse" e.State = "dead" e.HP = 0 - w.Corpses[e.ID] = &Corpse{Entity: e, Inventory: c.View.Inventory} + w.Corpses[e.ID] = &Corpse{Entity: e, Inventory: c.View.Inventory, Items: c.View.Items} c.View.Inventory = map[string]int64{} + c.View.Items = []p.ItemInstance{} + c.View.Equipment = map[string]string{} + c.View.CarryWeight = 0 c.View.Entity.HP = 0 c.View.Entity.State = "dead" c.MoveX = 0 @@ -579,6 +627,9 @@ func (w *World) Advance(now time.Time, dt float64) { } } if c.Online { + if c.View.Entity.HP > 0 { c.View.Entity.HP = math.Min(c.View.Entity.MaxHP, c.View.Entity.HP+c.View.Stats["healthRecovery"].Final*dt) } + c.View.Mana = math.Min(c.View.Stats["manaPoints"].Final, c.View.Mana+c.View.Stats["manaRecovery"].Final*dt) + c.View.Stamina = math.Min(c.View.Stats["stamina"].Final, c.View.Stamina+c.View.Stats["staminaRecovery"].Final*dt) // A generous window: the client resends its move intent well under this on every // rendered frame, but a slow/throttled frame (e.g. software-rendered CI) shouldn't // zero out in-flight movement and strand a walk-to-target action mid-course. @@ -610,7 +661,7 @@ func (w *World) Advance(now time.Time, dt float64) { if w.Age()-w.BossLastAttack >= w.Balance.BossCooldown { for _, c := range characters { if c.Online && !c.Sheltered && c.View.Entity.State == "alive" && distance(c.View.Entity.Position, w.terrain.Position(0, 0)) <= w.Balance.BossRange { - c.View.Entity.HP -= w.Balance.BossDamage + w.damageCharacter(c, w.Balance.BossDamage) w.dirty = true if c.View.Entity.HP <= 0 { w.kill(c, "The Harbinger ended this character's journey.") @@ -700,7 +751,7 @@ func (w *World) updateMobs(active map[string]bool, dt float64) { } if nearest <= w.Balance.MobAttackRange { if w.Age()-m.LastAttack >= w.Balance.MobCooldown { - target.View.Entity.HP -= w.Balance.MobDamage * (1 + w.Age()/86400*w.Balance.MobScalePerDay) + w.damageCharacter(target, w.Balance.MobDamage*(1+w.Age()/86400*w.Balance.MobScalePerDay)) m.LastAttack = w.Age() w.dirty = true if target.View.Entity.HP <= 0 { diff --git a/server/internal/protocol/generated.go b/server/internal/protocol/generated.go index efd396e..f2d9ead 100644 --- a/server/internal/protocol/generated.go +++ b/server/internal/protocol/generated.go @@ -9,6 +9,7 @@ type Protocol struct { type Intent struct { Op string `json:"op"` Seq int64 `json:"seq"` + Slot string `json:"slot"` Target string `json:"target"` X float64 `json:"x"` Z float64 `json:"z"` @@ -55,19 +56,61 @@ type Vec3 struct { } type Character struct { - ACK int64 `json:"ack"` - Entity Entity `json:"entity"` - Experience int64 `json:"experience"` - ExperienceToNextLevel int64 `json:"experienceToNextLevel"` - HasKeystone bool `json:"hasKeystone"` - Inventory map[string]int64 `json:"inventory"` - Kills int64 `json:"kills"` - Level int64 `json:"level"` - PlayedSeconds float64 `json:"playedSeconds"` - RemainingSeconds float64 `json:"remainingSeconds"` - Skills map[string]int64 `json:"skills"` - StatPoints int64 `json:"statPoints"` - Titles []TitleAward `json:"titles"` + ACK int64 `json:"ack"` + AllocatedStats map[string]int64 `json:"allocatedStats"` + CarryWeight float64 `json:"carryWeight"` + Entity Entity `json:"entity"` + Equipment map[string]string `json:"equipment"` + Experience int64 `json:"experience"` + ExperienceToNextLevel int64 `json:"experienceToNextLevel"` + HasKeystone bool `json:"hasKeystone"` + HealthChoices int64 `json:"healthChoices"` + Inventory map[string]int64 `json:"inventory"` + Items []ItemInstance `json:"items"` + Kills int64 `json:"kills"` + Level int64 `json:"level"` + Mana float64 `json:"mana"` + ManaChoices int64 `json:"manaChoices"` + PendingVitalChoices int64 `json:"pendingVitalChoices"` + PlayedSeconds float64 `json:"playedSeconds"` + RemainingSeconds float64 `json:"remainingSeconds"` + Skills map[string]int64 `json:"skills"` + Stamina float64 `json:"stamina"` + StatPoints int64 `json:"statPoints"` + Stats map[string]StatValue `json:"stats"` + Titles []TitleAward `json:"titles"` +} + +type ItemInstance struct { + DefinitionID string `json:"definitionId"` + Description string `json:"description"` + Equippable bool `json:"equippable"` + ID string `json:"id"` + Modifiers []StatModifier `json:"modifiers"` + Name string `json:"name"` + RequirementMessage string `json:"requirementMessage"` + Requirements ItemRequirements `json:"requirements"` + Slot string `json:"slot"` + Weight float64 `json:"weight"` +} + +type StatModifier struct { + Flat float64 `json:"flat"` + Percent float64 `json:"percent"` + Stat string `json:"stat"` +} + +type ItemRequirements struct { + Level int64 `json:"level"` + Stats map[string]float64 `json:"stats"` + Titles []string `json:"titles"` +} + +type StatValue struct { + Base float64 `json:"base"` + Final float64 `json:"final"` + Flat float64 `json:"flat"` + Percent float64 `json:"percent"` } type TitleAward struct { @@ -81,8 +124,9 @@ type TitleAward struct { } type TitleEffects struct { - Damage float64 `json:"damage"` - MoveSpeed float64 `json:"moveSpeed"` + Damage float64 `json:"damage"` + Modifiers []StatModifier `json:"modifiers"` + MoveSpeed float64 `json:"moveSpeed"` } type WorldInfo struct { diff --git a/server/internal/store/store.go b/server/internal/store/store.go index 73e7476..c484427 100644 --- a/server/internal/store/store.go +++ b/server/internal/store/store.go @@ -217,7 +217,7 @@ func (l *Lease) SaveCommand(ctx context.Context, w *game.World, claimID string, } l.Revision++ for id, c := range w.Characters { - live.Characters[id].View.Titles = c.View.Titles + live.Characters[id].View = c.View } live.PendingTitles = nil live.Saved() diff --git a/server/internal/store/titles.go b/server/internal/store/titles.go index e3a02f5..d8b6779 100644 --- a/server/internal/store/titles.go +++ b/server/internal/store/titles.go @@ -5,6 +5,7 @@ import ( "database/sql" "encoding/json" "errors" + "maps" "sort" "aeternalis/server/internal/game" @@ -19,6 +20,10 @@ func stageTitleWorld(w *game.World) *game.World { for id, c := range w.Characters { copy := *c copy.View.Titles = append([]p.TitleAward{}, c.View.Titles...) + copy.View.Items = append([]p.ItemInstance{}, c.View.Items...) + copy.View.Equipment = maps.Clone(c.View.Equipment) + copy.View.AllocatedStats = maps.Clone(c.View.AllocatedStats) + copy.View.Stats = maps.Clone(c.View.Stats) staged.Characters[id] = © } return &staged @@ -96,6 +101,7 @@ func (d *DB) syncTitles(ctx context.Context, tx *sql.Tx, w *game.World) error { } if c.View.Entity.State != "dead" { c.View.Titles = append([]p.TitleAward{}, awards...) + w.RefreshStats(c) continue } // A historical dead life keeps its own record. Only awards from its death diff --git a/server/internal/transport/service.go b/server/internal/transport/service.go index 4ae9070..a62d930 100644 --- a/server/internal/transport/service.go +++ b/server/internal/transport/service.go @@ -178,6 +178,10 @@ func (s *Service) join(ctx context.Context, account, name, claim string) (p.Char view.Inventory = maps.Clone(view.Inventory) view.Skills = maps.Clone(view.Skills) view.Titles = append([]p.TitleAward{}, view.Titles...) + view.Items = append([]p.ItemInstance{}, view.Items...) + view.Equipment = maps.Clone(view.Equipment) + view.Stats = maps.Clone(view.Stats) + view.AllocatedStats = maps.Clone(view.AllocatedStats) return view, nil }