Add durable recipe discovery and profession crafting
This commit is contained in:
@@ -47,6 +47,13 @@ func (w *World) AdminItems(c *Character, op, value string) error {
|
||||
known = true
|
||||
}
|
||||
}
|
||||
if w.Balance.Crafting != nil {
|
||||
for _, m := range w.Balance.Crafting.Materials {
|
||||
if m.ID == id {
|
||||
known = true
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, definition := range w.Balance.Items {
|
||||
if definition.ID == id {
|
||||
known = true
|
||||
@@ -79,7 +86,7 @@ func (w *World) AdminItems(c *Character, op, value string) error {
|
||||
if c.View.Inventory[id] < n {
|
||||
return errors.New("player no longer holds that item quantity")
|
||||
}
|
||||
c.View.Inventory[id] -= n
|
||||
TakeStack(c, id, n)
|
||||
if c.View.Inventory[id] == 0 {
|
||||
delete(c.View.Inventory, id)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,307 @@
|
||||
package game
|
||||
|
||||
import (
|
||||
"aeternalis/server/content"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"math"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func (w *World) refreshCrafting(c *Character) {
|
||||
if c.View.Crafting == nil {
|
||||
c.View.Crafting = map[string]p.CraftProgress{}
|
||||
}
|
||||
if c.View.DiscoveredRecipes == nil {
|
||||
c.View.DiscoveredRecipes = map[string]p.KnownRecipe{}
|
||||
}
|
||||
if w.Balance.Crafting == nil {
|
||||
return
|
||||
}
|
||||
for _, s := range w.Balance.Crafting.Professions {
|
||||
v := c.View.Crafting[s.ID]
|
||||
v.ID = s.ID
|
||||
v.Name = s.Name
|
||||
v.Level, v.XPToNextLevel = content.SkillLevel(s, v.XP)
|
||||
v.LossPercent = w.Balance.Crafting.Rules.Loss(v.Level)
|
||||
c.View.Crafting[s.ID] = v
|
||||
}
|
||||
for _, m := range w.Balance.Crafting.Materials {
|
||||
if c.View.Inventory[m.ID] > 0 {
|
||||
c.View.StackNames[m.ID] = m.Name
|
||||
}
|
||||
}
|
||||
}
|
||||
func (w *World) restoreCrafting(c *Character) error {
|
||||
if len(c.View.Crafting) > 64 || len(c.View.DiscoveredRecipes) > 512 || math.IsNaN(c.CraftReadyAt) || math.IsInf(c.CraftReadyAt, 0) || c.CraftReadyAt < 0 {
|
||||
return errors.New("invalid crafting history")
|
||||
}
|
||||
for _, v := range c.View.Crafting {
|
||||
if v.XP < 0 || v.XP > 1000000000000 {
|
||||
return errors.New("invalid crafting experience")
|
||||
}
|
||||
}
|
||||
for id, r := range c.View.DiscoveredRecipes {
|
||||
if id != r.Recipe.ID || r.Recipe.Revision < 1 || len(r.Recipe.Inputs) > 16 || len(r.Recipe.Outputs) > 8 || len(r.Recipe.Name) > 80 {
|
||||
return errors.New("invalid discovered recipe")
|
||||
}
|
||||
}
|
||||
return ValidateCraftedStacks(c.View.Inventory, c.View.CraftedStacks, map[string]bool{})
|
||||
}
|
||||
|
||||
func ValidateCraftedStacks(inventory map[string]int64, batches []p.CraftedStack, seen map[string]bool) error {
|
||||
if len(batches) > 2048 {
|
||||
return errors.New("too many crafted batches")
|
||||
}
|
||||
totals := map[string]int64{}
|
||||
for _, b := range batches {
|
||||
if b.ID == "" || len(b.ID) > 100 || seen[b.ID] || b.Item == "" || b.Quantity < 1 || b.Quantity > 1000000000000 || !validProvenance(b.Provenance) {
|
||||
return errors.New("invalid crafted provenance or batch")
|
||||
}
|
||||
seen[b.ID] = true
|
||||
totals[b.Item] += b.Quantity
|
||||
if totals[b.Item] > inventory[b.Item] {
|
||||
return errors.New("crafted batches exceed inventory")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func finiteCraft(n float64) bool { return !math.IsNaN(n) && !math.IsInf(n, 0) && n >= 0 }
|
||||
func validProvenance(v p.CraftProvenance) bool {
|
||||
return len(v.CharacterID) == 32 && v.CrafterName != "" && len(v.CrafterName) <= 80 && v.WorldID != "" && len(v.WorldID) <= 128 && v.RecipeID != "" && len(v.RecipeID) <= 64 && v.RecipeRevision >= 1 && v.Profession != "" && len(v.Profession) <= 64 && v.Level >= 1 && v.Level <= 1000 && finiteCraft(v.At)
|
||||
}
|
||||
|
||||
// Consume unmarked units first, then crafted batches in acquisition order.
|
||||
// Splits receive a new batch identity; surviving units retain their provenance.
|
||||
func TakeStack(c *Character, item string, quantity int64) []p.CraftedStack {
|
||||
crafted := int64(0)
|
||||
for _, b := range c.View.CraftedStacks {
|
||||
if b.Item == item {
|
||||
crafted += b.Quantity
|
||||
}
|
||||
}
|
||||
remaining := quantity - min(quantity, max(0, c.View.Inventory[item]-crafted))
|
||||
taken := []p.CraftedStack{}
|
||||
kept := []p.CraftedStack{}
|
||||
for _, b := range c.View.CraftedStacks {
|
||||
if b.Item == item && remaining > 0 {
|
||||
n := min(remaining, b.Quantity)
|
||||
part := b
|
||||
part.Quantity = n
|
||||
if n < b.Quantity {
|
||||
part.ID = ID()
|
||||
}
|
||||
taken = append(taken, part)
|
||||
b.Quantity -= n
|
||||
remaining -= n
|
||||
}
|
||||
if b.Quantity > 0 {
|
||||
kept = append(kept, b)
|
||||
}
|
||||
}
|
||||
c.View.CraftedStacks = kept
|
||||
c.View.Inventory[item] -= quantity
|
||||
if c.View.Inventory[item] == 0 {
|
||||
delete(c.View.Inventory, item)
|
||||
}
|
||||
return taken
|
||||
}
|
||||
func (w *World) checkCraftedWorld(c *Character) error {
|
||||
seen := map[string]bool{}
|
||||
for _, existing := range w.Characters {
|
||||
if existing.View.Entity.ID == c.View.Entity.ID {
|
||||
continue
|
||||
}
|
||||
if e := ValidateCraftedStacks(existing.View.Inventory, existing.View.CraftedStacks, seen); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
for _, corpse := range w.Corpses {
|
||||
if e := ValidateCraftedStacks(corpse.Inventory, corpse.CraftedStacks, seen); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
return ValidateCraftedStacks(c.View.Inventory, c.View.CraftedStacks, seen)
|
||||
}
|
||||
func (w *World) CraftProfessions(c *Character) []p.CraftProgress {
|
||||
w.refreshCrafting(c)
|
||||
out := []p.CraftProgress{}
|
||||
for _, s := range w.Balance.Crafting.Professions {
|
||||
out = append(out, c.View.Crafting[s.ID])
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// The browser offers quantities, never a secret recipe ID. Invalid inventory or
|
||||
// requirement requests do not consume materials or advance the random stream.
|
||||
func (w *World) AttemptCraft(c *Character, req p.CraftRequest) (p.CraftResult, error) {
|
||||
result := p.CraftResult{ID: req.ID, Consumed: map[string]int64{}, Created: []string{}}
|
||||
if c == nil || !c.Online || c.Sheltered || c.View.Entity.State != "alive" || c.View.RemainingSeconds <= 0 || (!w.IsHub() && w.Phase != "gathering" && w.Phase != "cataclysm") {
|
||||
return result, errors.New("character cannot craft")
|
||||
}
|
||||
now := float64(w.now.UnixMilli()) / 1000
|
||||
if now < c.CraftReadyAt {
|
||||
return result, errors.New("crafting cooldown")
|
||||
}
|
||||
if len(req.Ingredients) < 1 || len(req.Ingredients) > 16 {
|
||||
return result, errors.New("offer 1-16 distinct ingredients")
|
||||
}
|
||||
v := w.Balance.Crafting
|
||||
profession := slices.IndexFunc(v.Professions, func(s content.GatheringSkill) bool { return s.ID == req.Profession })
|
||||
if profession < 0 {
|
||||
return result, errors.New("unknown crafting profession")
|
||||
}
|
||||
for id, n := range req.Ingredients {
|
||||
if id == "" || len(id) > 64 || n < 1 || n > 1000 || c.View.Inventory[id] < n {
|
||||
return result, errors.New("invalid or missing ingredients")
|
||||
}
|
||||
}
|
||||
w.refreshCrafting(c)
|
||||
progress := c.View.Crafting[req.Profession]
|
||||
var recipe *content.CraftRecipe
|
||||
for _, r := range v.Recipes {
|
||||
if r.Profession == req.Profession && maps.Equal(r.Inputs, req.Ingredients) {
|
||||
copy := r
|
||||
recipe = ©
|
||||
break
|
||||
}
|
||||
}
|
||||
if recipe != nil {
|
||||
stats := w.statValues(c, false)
|
||||
for key, n := range recipe.Stats {
|
||||
if stats[key].Final < n {
|
||||
return result, fmt.Errorf("valid recipe; requires %s %.0f (without equipment bonuses); no ingredients spent", key, n)
|
||||
}
|
||||
}
|
||||
for _, id := range recipe.Titles {
|
||||
if !slices.ContainsFunc(c.View.Titles, func(t p.TitleAward) bool { return t.ID == id }) {
|
||||
return result, errors.New("valid recipe; required title missing; no ingredients spent")
|
||||
}
|
||||
}
|
||||
}
|
||||
// Results are constructed on a staged world; persistence failures never publish
|
||||
// this random result or partially spend the live player's ingredients.
|
||||
result.Valid = recipe != nil
|
||||
if recipe != nil {
|
||||
result.Success = !w.roll(v.Rules.Failure(progress.Level, recipe.Level))
|
||||
}
|
||||
rate := v.Rules.Loss(progress.Level)
|
||||
if result.Success {
|
||||
rate = 100
|
||||
}
|
||||
keys := slices.Sorted(maps.Keys(req.Ingredients))
|
||||
for _, id := range keys {
|
||||
n := int64(math.Ceil(float64(req.Ingredients[id]) * rate / 100))
|
||||
n = min(req.Ingredients[id], max(1, n))
|
||||
TakeStack(c, id, n)
|
||||
result.Consumed[id] = n
|
||||
}
|
||||
if recipe != nil {
|
||||
var known p.CraftRecipe
|
||||
raw, _ := json.Marshal(recipe)
|
||||
_ = json.Unmarshal(raw, &known)
|
||||
discovered := p.KnownRecipe{Recipe: known, DiscoveredAt: now}
|
||||
if old, ok := c.View.DiscoveredRecipes[recipe.ID]; ok && old.Recipe.Revision == recipe.Revision {
|
||||
discovered.DiscoveredAt = old.DiscoveredAt
|
||||
}
|
||||
c.View.DiscoveredRecipes[recipe.ID] = discovered
|
||||
result.Recipe = &discovered
|
||||
}
|
||||
if result.Success {
|
||||
provenance := p.CraftProvenance{CharacterID: c.View.Entity.ID, CrafterName: c.View.Entity.Name, WorldID: w.ID, RecipeID: recipe.ID, RecipeRevision: recipe.Revision, Profession: req.Profession, Level: progress.Level, At: now}
|
||||
for _, id := range slices.Sorted(maps.Keys(recipe.Outputs)) {
|
||||
n := recipe.Outputs[id]
|
||||
before := len(c.View.Items)
|
||||
if err := w.addInventoryItems(&c.View.Inventory, &c.View.Items, id, n); err != nil {
|
||||
return result, err
|
||||
}
|
||||
if len(c.View.Items) > before {
|
||||
var definition content.ItemDefinition
|
||||
for _, d := range w.Balance.Items {
|
||||
if d.ID == id {
|
||||
definition = d
|
||||
break
|
||||
}
|
||||
}
|
||||
for i := before; i < len(c.View.Items); i++ {
|
||||
item := &c.View.Items[i]
|
||||
copy := provenance
|
||||
item.Provenance = ©
|
||||
item.Modifiers = append(item.Modifiers, w.craftModifiers(definition, progress.Level)...)
|
||||
result.Created = append(result.Created, item.ID)
|
||||
}
|
||||
} else {
|
||||
batch := p.CraftedStack{ID: ID(), Item: id, Quantity: n, Provenance: provenance}
|
||||
c.View.CraftedStacks = append(c.View.CraftedStacks, batch)
|
||||
result.Created = append(result.Created, batch.ID)
|
||||
}
|
||||
}
|
||||
if w.AllowsXP() {
|
||||
progress.XP = min(int64(1000000000000), progress.XP+recipe.XP)
|
||||
c.View.Crafting[req.Profession] = progress
|
||||
c.View.Skills["crafting"] += w.Balance.SkillXpPerAction
|
||||
w.grantXP(c, w.Balance.Progression.CraftXP)
|
||||
}
|
||||
result.Message = "Crafted " + recipe.Name
|
||||
} else if recipe != nil {
|
||||
result.Message = "Valid recipe discovered: " + recipe.Name + ". Craft failed; some ingredients were lost."
|
||||
} else {
|
||||
result.Message = "No recipe matches this combination. Some ingredients were lost."
|
||||
}
|
||||
if err := ValidateCraftedStacks(c.View.Inventory, c.View.CraftedStacks, map[string]bool{}); err != nil {
|
||||
return result, err
|
||||
}
|
||||
c.CraftReadyAt = now + v.Rules.Cooldown
|
||||
c.Message = result.Message
|
||||
w.RefreshStats(c)
|
||||
w.evaluateTitles(c)
|
||||
w.dirty = true
|
||||
return result, nil
|
||||
}
|
||||
func (w *World) craftModifiers(item content.ItemDefinition, level int64) []p.StatModifier {
|
||||
pool := slices.Clone(item.CraftPool)
|
||||
out := []p.StatModifier{}
|
||||
bias := math.Min(w.Balance.Crafting.Rules.MaxQualityBias, 1+float64(level-1)*w.Balance.Crafting.Rules.QualityPerLevel)
|
||||
for range item.CraftRolls {
|
||||
total := float64(0)
|
||||
for _, s := range pool {
|
||||
total += s.Weight
|
||||
}
|
||||
pick := w.randomUnit() * total
|
||||
index := len(pool) - 1
|
||||
for i, s := range pool {
|
||||
pick -= s.Weight
|
||||
if pick < 0 {
|
||||
index = i
|
||||
break
|
||||
}
|
||||
}
|
||||
s := pool[index]
|
||||
pool = append(pool[:index], pool[index+1:]...)
|
||||
value := math.Round((s.Min+(s.Max-s.Min)*math.Pow(w.randomUnit(), 1/bias))*100) / 100
|
||||
m := p.StatModifier{Stat: s.Stat}
|
||||
if s.Percent {
|
||||
m.Percent = value
|
||||
} else {
|
||||
m.Flat = value
|
||||
}
|
||||
out = append(out, m)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func ValidCraftRequest(r p.CraftRequest) bool {
|
||||
if len(r.ID) < 32 || len(r.ID) > 36 || len(r.CharacterID) != 32 || len(r.Profession) > 64 {
|
||||
return false
|
||||
}
|
||||
for _, id := range []string{r.ID, r.CharacterID} {
|
||||
if strings.Trim(id, "0123456789abcdef-") != "" {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
package game
|
||||
|
||||
import (
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"maps"
|
||||
"math"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Existing action regressions use the new ingredient path with a certain success
|
||||
// roll. A staged copy also exercises failure rollback without a transport fixture.
|
||||
func (w *World) craft(c *Character, name string) error {
|
||||
staged := *w
|
||||
staged.Characters = maps.Clone(w.Characters)
|
||||
copy := *c
|
||||
raw, _ := json.Marshal(c.View)
|
||||
var view p.Character
|
||||
_ = json.Unmarshal(raw, &view)
|
||||
copy.View = view
|
||||
staged.Characters[c.View.Entity.ID] = ©
|
||||
content := *w.Balance.Crafting
|
||||
content.Rules.BaseFailure = 0
|
||||
content.Rules.MinFailure = 0
|
||||
content.Rules.MaxFailure = 0
|
||||
staged.Balance.Crafting = &content
|
||||
for _, r := range content.Recipes {
|
||||
if r.ID == "recipe_"+name {
|
||||
_, e := staged.AttemptCraft(©, p.CraftRequest{ID: ID(), CharacterID: c.View.Entity.ID, Profession: r.Profession, Ingredients: r.Inputs})
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
*c = copy
|
||||
w.RandomCounter = staged.RandomCounter
|
||||
w.PendingTitles = staged.PendingTitles
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("unknown test recipe %s", name)
|
||||
}
|
||||
|
||||
func TestCraftFailureDiscoveryAndHubRules(t *testing.T) {
|
||||
w, c := fixture(t)
|
||||
v := w.Balance.Crafting
|
||||
v.Rules.BaseFailure = 100
|
||||
v.Rules.MinFailure = 100
|
||||
v.Rules.MaxFailure = 100
|
||||
c.View.Inventory["wood"] = 20
|
||||
c.View.Inventory["ore"] = 20
|
||||
req := p.CraftRequest{ID: ID(), CharacterID: c.View.Entity.ID, Profession: "weapon_smithing", Ingredients: map[string]int64{"wood": 3, "ore": 2}}
|
||||
beforeXP := c.View.Experience
|
||||
result, e := w.AttemptCraft(c, req)
|
||||
if e != nil || !result.Valid || result.Success || result.Recipe == nil {
|
||||
t.Fatal("valid failed craft was not discovered", result, e)
|
||||
}
|
||||
if c.View.Crafting["weapon_smithing"].XP != 0 || c.View.Experience != beforeXP || c.View.Inventory["wood"] != 17 || c.View.Inventory["ore"] != 18 {
|
||||
t.Fatal("failed craft XP/loss mismatch")
|
||||
}
|
||||
w.now = w.now.Add(2 * time.Second)
|
||||
req.Ingredients = map[string]int64{"wood": 1}
|
||||
result, e = w.AttemptCraft(c, req)
|
||||
if e != nil || result.Valid || result.Success || len(c.View.DiscoveredRecipes) != 1 {
|
||||
t.Fatal("unknown recipe gave discovery", e)
|
||||
}
|
||||
w.now = w.now.Add(2 * time.Second)
|
||||
w.Kind = "hub"
|
||||
w.Phase = "hub"
|
||||
v.Rules.BaseFailure = 0
|
||||
v.Rules.MinFailure = 0
|
||||
v.Rules.MaxFailure = 0
|
||||
req.Ingredients = map[string]int64{"wood": 3, "ore": 2}
|
||||
result, e = w.AttemptCraft(c, req)
|
||||
if e != nil || !result.Success {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if c.View.Experience != beforeXP || c.View.Crafting["weapon_smithing"].XP != 0 || c.View.Skills["crafting"] != 0 {
|
||||
t.Fatal("hub craft gained XP")
|
||||
}
|
||||
var crafted *p.ItemInstance
|
||||
for i := range c.View.Items {
|
||||
if c.View.Items[i].DefinitionID == "spear" {
|
||||
crafted = &c.View.Items[i]
|
||||
}
|
||||
}
|
||||
fixed := 0
|
||||
for _, item := range w.Balance.Items {
|
||||
if item.ID == "spear" {
|
||||
fixed = len(item.Modifiers)
|
||||
}
|
||||
}
|
||||
if crafted == nil || crafted.Provenance == nil || crafted.Provenance.CrafterName != "Traveler" || crafted.Provenance.WorldID != w.ID || len(crafted.Modifiers) != fixed+1 {
|
||||
t.Fatal("crafted gear missing provenance or stat roll")
|
||||
}
|
||||
before := len(c.View.Items)
|
||||
if _, e = w.AttemptCraft(c, req); e == nil || len(c.View.Items) != before {
|
||||
t.Fatal("cooldown bypass")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCraftedStackSplitDeathLootAndReplacement(t *testing.T) {
|
||||
w, c := fixture(t)
|
||||
w.Balance.Crafting.Rules.BaseFailure = 0
|
||||
w.Balance.Crafting.Rules.MinFailure = 0
|
||||
w.Balance.Crafting.Rules.MaxFailure = 0
|
||||
c.View.Inventory["herb"] = 8
|
||||
for i := range w.Balance.Crafting.Recipes {
|
||||
if w.Balance.Crafting.Recipes[i].ID == "recipe_bandage" {
|
||||
w.Balance.Crafting.Recipes[i].Outputs["bandage"] = 3
|
||||
}
|
||||
}
|
||||
if e := w.craft(c, "bandage"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
before := c.View.CraftedStacks[0].Provenance
|
||||
batchID := c.View.CraftedStacks[0].ID
|
||||
if e := w.dropItem(c, "bandage"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
var drop *Corpse
|
||||
for _, v := range w.Corpses {
|
||||
drop = v
|
||||
}
|
||||
if drop == nil || drop.CraftedStacks[0].ID == batchID || drop.CraftedStacks[0].Quantity != 1 || c.View.CraftedStacks[0].Quantity != 2 || !reflect.DeepEqual(drop.CraftedStacks[0].Provenance, before) {
|
||||
t.Fatal("partial drop lost/duplicated provenance")
|
||||
}
|
||||
other, _ := w.Join("other", "Other")
|
||||
other.View.Entity.Position = c.View.Entity.Position
|
||||
if e := w.lootCorpse(other, drop.Entity.ID); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if !reflect.DeepEqual(other.View.CraftedStacks[0].Provenance, before) {
|
||||
t.Fatal("pickup changed crafter")
|
||||
}
|
||||
w.kill(c, "test")
|
||||
corpse := w.Corpses["corpse:"+c.View.Entity.ID]
|
||||
if len(c.View.CraftedStacks) != 0 || len(corpse.CraftedStacks) != 1 {
|
||||
t.Fatal("death duplicated crafted stock")
|
||||
}
|
||||
if e := w.lootCorpse(other, corpse.Entity.ID); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
TakeStack(other, "bandage", 2)
|
||||
if other.View.Inventory["bandage"] != 1 || len(other.View.CraftedStacks) != 1 || other.View.CraftedStacks[0].Quantity != 1 {
|
||||
t.Fatal("consumption left invalid provenance")
|
||||
}
|
||||
raw, _ := json.Marshal(w)
|
||||
var restored World
|
||||
if e := json.Unmarshal(raw, &restored); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e := restored.Restore(w.now); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
replacement, e := restored.Join(c.Account, "Replacement")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if len(replacement.View.DiscoveredRecipes) != 0 || replacement.View.Crafting["alchemist"].XP != 0 {
|
||||
t.Fatal("replacement inherited crafting progression")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCraftRequirementsAndQuality(t *testing.T) {
|
||||
w, c := fixture(t)
|
||||
c.View.Inventory["wood"] = 3
|
||||
c.View.Inventory["ore"] = 2
|
||||
for i := range w.Balance.Crafting.Recipes {
|
||||
if w.Balance.Crafting.Recipes[i].ID == "recipe_spear" {
|
||||
w.Balance.Crafting.Recipes[i].Stats = map[string]float64{"strength": 10000}
|
||||
}
|
||||
}
|
||||
counter := w.RandomCounter
|
||||
_, e := w.AttemptCraft(c, p.CraftRequest{ID: ID(), CharacterID: c.View.Entity.ID, Profession: "weapon_smithing", Ingredients: map[string]int64{"wood": 3, "ore": 2}})
|
||||
if e == nil || w.RandomCounter != counter || c.View.Inventory["wood"] != 3 || len(c.View.DiscoveredRecipes) != 0 {
|
||||
t.Fatal("unmet requirements consumed materials or rolled")
|
||||
}
|
||||
item := w.Balance.Items[1]
|
||||
sumLow, sumHigh := float64(0), float64(0)
|
||||
for range 200 {
|
||||
start := w.RandomCounter
|
||||
low := w.craftModifiers(item, 1)
|
||||
w.RandomCounter = start
|
||||
high := w.craftModifiers(item, 100)
|
||||
if len(low) != 1 || len(high) != 1 || low[0].Stat != high[0].Stat {
|
||||
t.Fatal("pool selection not preserved")
|
||||
}
|
||||
if high[0].Flat < low[0].Flat || math.IsNaN(high[0].Flat) {
|
||||
t.Fatal("higher proficiency worsened corresponding roll")
|
||||
}
|
||||
sumLow += low[0].Flat
|
||||
sumHigh += high[0].Flat
|
||||
}
|
||||
if sumHigh <= sumLow {
|
||||
t.Fatal("quality distribution did not improve")
|
||||
}
|
||||
}
|
||||
@@ -126,6 +126,9 @@ func (w *World) migrateEquipment(inventory *map[string]int64, items *[]p.ItemIns
|
||||
}
|
||||
func validateOwnedItems(items []p.ItemInstance, seen map[string]bool) error {
|
||||
for _, item := range items {
|
||||
if item.Provenance != nil && !validProvenance(*item.Provenance) {
|
||||
return errors.New("invalid equipment provenance")
|
||||
}
|
||||
if item.ID == "" || len(item.ID) > 100 || seen[item.ID] || item.DefinitionID == "" || item.Name == "" || (item.Slot != "ring" && !validEquipmentSlot(item.Slot)) || math.IsNaN(item.Weight) || math.IsInf(item.Weight, 0) || item.Weight < 0 || item.Requirements.Level < 1 {
|
||||
return errors.New("invalid or duplicate persisted equipment")
|
||||
}
|
||||
@@ -167,6 +170,17 @@ func (w *World) restoreEquipment(c *Character) error {
|
||||
return nil
|
||||
}
|
||||
func (w *World) restoreCorpseEquipment() error {
|
||||
batches := map[string]bool{}
|
||||
for _, c := range w.Characters {
|
||||
if e := ValidateCraftedStacks(c.View.Inventory, c.View.CraftedStacks, batches); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
for _, c := range w.Corpses {
|
||||
if e := ValidateCraftedStacks(c.Inventory, c.CraftedStacks, batches); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, c := range w.Characters {
|
||||
if err := validateOwnedItems(c.View.Items, seen); err != nil {
|
||||
@@ -294,7 +308,7 @@ func (w *World) dropItem(c *Character, target string) error {
|
||||
if c.View.Inventory[target] < 1 {
|
||||
return errors.New("item not owned")
|
||||
}
|
||||
c.View.Inventory[target]--
|
||||
dropped.CraftedStacks = TakeStack(c, target, 1)
|
||||
if c.View.Inventory[target] == 0 {
|
||||
delete(c.View.Inventory, target)
|
||||
}
|
||||
@@ -318,11 +332,22 @@ func (w *World) lootCorpse(c *Character, target string) error {
|
||||
if err := validateOwnedItems(corpse.Items, seen); err != nil {
|
||||
return err
|
||||
}
|
||||
batches := map[string]bool{}
|
||||
if e := ValidateCraftedStacks(c.View.Inventory, c.View.CraftedStacks, batches); e != nil {
|
||||
return e
|
||||
}
|
||||
if e := ValidateCraftedStacks(corpse.Inventory, corpse.CraftedStacks, batches); e != nil {
|
||||
return e
|
||||
}
|
||||
for name, quantity := range corpse.Inventory {
|
||||
if quantity < 0 || c.View.Inventory[name] > math.MaxInt64-quantity {
|
||||
return errors.New("invalid loot quantity")
|
||||
}
|
||||
}
|
||||
if len(c.View.CraftedStacks)+len(corpse.CraftedStacks) > 2048 {
|
||||
return errors.New("crafted batch capacity reached")
|
||||
}
|
||||
c.View.CraftedStacks = append(c.View.CraftedStacks, corpse.CraftedStacks...)
|
||||
for name, quantity := range corpse.Inventory {
|
||||
c.View.Inventory[name] += quantity
|
||||
}
|
||||
@@ -333,6 +358,9 @@ func (w *World) lootCorpse(c *Character, target string) error {
|
||||
return nil
|
||||
}
|
||||
func (w *World) checkImportedEquipment(c *Character) error {
|
||||
if e := w.checkCraftedWorld(c); e != nil {
|
||||
return e
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, existing := range w.Characters {
|
||||
if err := validateOwnedItems(existing.View.Items, seen); err != nil {
|
||||
|
||||
@@ -166,7 +166,7 @@ func TestLegacyEquipmentMigrationAndAtomicFailures(t *testing.T) {
|
||||
delete(w.Corpses, "legacy")
|
||||
c.View.Inventory["wood"] = 3
|
||||
c.View.Inventory["ore"] = 2
|
||||
w.Balance.Recipes["spear"] = content.Recipe{Inputs: map[string]int64{"wood": 3, "ore": 2}, Outputs: map[string]int64{"spear": 100001}}
|
||||
w.Balance.Crafting.Recipes[0].Outputs = map[string]int64{"spear": 100001}
|
||||
if w.craft(c, "spear") == nil || c.View.Inventory["wood"] != 3 || c.View.Inventory["ore"] != 2 {
|
||||
t.Fatal("failed craft consumed materials")
|
||||
}
|
||||
|
||||
@@ -260,7 +260,7 @@ func (w *World) consumeGathering(c *Character, id string) error {
|
||||
if len(c.View.GatheringEffects) >= 64 && !slices.ContainsFunc(c.View.GatheringEffects, func(e p.TimedGatheringEffect) bool { return e.Source == id }) {
|
||||
return errors.New("too many active gathering effects")
|
||||
}
|
||||
c.View.Inventory[id]--
|
||||
TakeStack(c, id, 1)
|
||||
w.applyGatheringEffect(c, p.TimedGatheringEffect{Source: id, Name: v.Name, ExpiresAt: float64(w.now.UnixMilli())/1000 + v.Seconds, Modifiers: protocolModifiers(v.Modifiers)})
|
||||
w.RefreshStats(c)
|
||||
c.Message = "Used " + v.Name
|
||||
|
||||
@@ -62,7 +62,7 @@ func TestOnlySuccessfulActionsGrantXP(t *testing.T) {
|
||||
t.Fatal("failed gather gained XP")
|
||||
}
|
||||
c.View.Inventory["herb"] = 2
|
||||
if err := w.Intent(id, p.Intent{Op: "craft", Seq: 11, Target: "bandage"}); err != nil {
|
||||
if err := w.craft(c, "bandage"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before := c.View.Experience
|
||||
|
||||
@@ -89,6 +89,7 @@ func (w *World) RefreshStats(c *Character) {
|
||||
w.revalidateEquipment(c)
|
||||
c.View.Stats = w.statValues(c, true)
|
||||
w.refreshGathering(c)
|
||||
w.refreshCrafting(c)
|
||||
attack := w.playerAttack(c)
|
||||
c.View.Attack = &attack
|
||||
c.View.Entity.MaxHP = c.View.Stats["healthPoints"].Final
|
||||
@@ -171,6 +172,9 @@ func (w *World) ApplyCatalog(catalog content.Catalog) error {
|
||||
if catalog.Combat != nil {
|
||||
w.Balance.Combat = catalog.Combat
|
||||
}
|
||||
if catalog.Crafting != nil {
|
||||
w.Balance.Crafting = catalog.Crafting
|
||||
}
|
||||
w.Balance.Titles = catalog.Titles
|
||||
w.Balance.Items = catalog.Items
|
||||
w.Balance.Stats = &catalog.Stats
|
||||
@@ -188,9 +192,12 @@ func (w *World) roll(chance float64) bool {
|
||||
if chance >= 100 {
|
||||
return true
|
||||
}
|
||||
return w.randomUnit()*100 < chance
|
||||
}
|
||||
func (w *World) randomUnit() float64 {
|
||||
w.RandomCounter++
|
||||
sum := sha256.Sum256([]byte(fmt.Sprintf("%d:%d", w.Seed, w.RandomCounter)))
|
||||
return float64(binary.LittleEndian.Uint64(sum[:8])>>11)/float64(uint64(1)<<53)*100 < chance
|
||||
return float64(binary.LittleEndian.Uint64(sum[:8])>>11) / float64(uint64(1)<<53)
|
||||
}
|
||||
func (w *World) yieldAmount(rate float64) int64 {
|
||||
amount := math.Max(0, math.Min(float64(w.Balance.MaxYieldPerAction), rate/100))
|
||||
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"math"
|
||||
"sort"
|
||||
"time"
|
||||
@@ -15,6 +14,7 @@ import (
|
||||
)
|
||||
|
||||
type Character struct {
|
||||
CraftReadyAt float64 `json:"craftReadyAt"`
|
||||
AttackReadyAt float64 `json:"attackReadyAt"`
|
||||
JumpVelocity float64 `json:"jumpVelocity"`
|
||||
GatherReadyAt float64 `json:"gatherReadyAt"`
|
||||
@@ -42,9 +42,10 @@ type Character struct {
|
||||
StatsVersion int `json:"statsVersion"`
|
||||
}
|
||||
type Corpse struct {
|
||||
Entity p.Entity `json:"entity"`
|
||||
Inventory map[string]int64 `json:"inventory"`
|
||||
Items []p.ItemInstance `json:"items"`
|
||||
CraftedStacks []p.CraftedStack `json:"craftedStacks,omitempty"`
|
||||
Entity p.Entity `json:"entity"`
|
||||
Inventory map[string]int64 `json:"inventory"`
|
||||
Items []p.ItemInstance `json:"items"`
|
||||
}
|
||||
type Mob struct {
|
||||
Definition *content.MobDefinition `json:"definition,omitempty"`
|
||||
@@ -186,6 +187,16 @@ func (w *World) Restore(now time.Time) error {
|
||||
if w.ResourceLayouts == nil {
|
||||
w.ResourceLayouts = map[string]ResourceLayout{}
|
||||
}
|
||||
if w.Balance.Crafting == nil {
|
||||
b, e := content.Load()
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
cat := content.Catalog{Items: w.Balance.Items}
|
||||
cat.RestoreCrafting(b)
|
||||
w.Balance.Crafting = cat.Crafting
|
||||
w.Balance.Items = cat.Items
|
||||
}
|
||||
if w.Balance.Combat == nil || w.Balance.CombatRules == nil {
|
||||
b, e := content.Load()
|
||||
if e != nil {
|
||||
@@ -217,6 +228,9 @@ func (w *World) Restore(now time.Time) error {
|
||||
if err := w.restoreEquipment(c); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.restoreCrafting(c); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.restoreGathering(c); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -328,6 +342,9 @@ func (w *World) Join(account, name string) (*Character, error) {
|
||||
if err := w.restoreEquipment(c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := w.restoreCrafting(c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := w.restoreGathering(c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -356,6 +373,9 @@ func (w *World) Import(c *Character) error {
|
||||
if err := w.checkImportedEquipment(c); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.restoreCrafting(c); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.restoreGathering(c); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -501,14 +521,14 @@ func (w *World) Intent(id string, i p.Intent) error {
|
||||
case "gather":
|
||||
return w.gather(c, i.Target)
|
||||
case "craft":
|
||||
return w.craft(c, i.Target)
|
||||
return errors.New("use the crafting workbench to offer ingredients")
|
||||
case "attack":
|
||||
return w.attack(c, i.Target)
|
||||
case "heal":
|
||||
if c.View.Inventory["bandage"] < 1 || c.View.Entity.HP >= c.View.Entity.MaxHP {
|
||||
return errors.New("no bandage needed or available")
|
||||
}
|
||||
c.View.Inventory["bandage"]--
|
||||
TakeStack(c, "bandage", 1)
|
||||
w.RefreshStats(c)
|
||||
c.View.Entity.HP = math.Min(c.View.Entity.MaxHP, c.View.Entity.HP+w.Balance.BandageHealing)
|
||||
w.dirty = true
|
||||
@@ -531,37 +551,6 @@ func (w *World) Intent(id string, i p.Intent) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (w *World) craft(c *Character, name string) error {
|
||||
r, ok := w.Balance.Recipes[name]
|
||||
if !ok {
|
||||
return errors.New("unknown recipe")
|
||||
}
|
||||
for k, v := range r.Inputs {
|
||||
if c.View.Inventory[k] < v {
|
||||
return errors.New("missing crafting materials")
|
||||
}
|
||||
}
|
||||
inventory := maps.Clone(c.View.Inventory)
|
||||
items := append([]p.ItemInstance{}, c.View.Items...)
|
||||
for k, v := range r.Inputs {
|
||||
inventory[k] -= v
|
||||
}
|
||||
for k, v := range r.Outputs {
|
||||
if err := w.addInventoryItems(&inventory, &items, k, v); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
c.View.Inventory, c.View.Items = inventory, items
|
||||
w.RefreshStats(c)
|
||||
if w.AllowsXP() {
|
||||
c.View.Skills["crafting"] += w.Balance.SkillXpPerAction
|
||||
}
|
||||
c.Message = "Crafted " + name
|
||||
w.grantXP(c, w.Balance.Progression.CraftXP)
|
||||
w.evaluateTitles(c)
|
||||
w.dirty = true
|
||||
return nil
|
||||
}
|
||||
func (w *World) damageBoss(c *Character, damage float64) {
|
||||
w.BossHP = math.Max(0, w.BossHP-damage)
|
||||
if w.BossHP == 0 {
|
||||
@@ -595,7 +584,8 @@ func (w *World) kill(c *Character, reason string) {
|
||||
e.Kind = "corpse"
|
||||
e.State = "dead"
|
||||
e.HP = 0
|
||||
w.Corpses[e.ID] = &Corpse{Entity: e, Inventory: c.View.Inventory, Items: c.View.Items}
|
||||
w.Corpses[e.ID] = &Corpse{Entity: e, Inventory: c.View.Inventory, Items: c.View.Items, CraftedStacks: c.View.CraftedStacks}
|
||||
c.View.CraftedStacks = nil
|
||||
c.View.Inventory = map[string]int64{}
|
||||
c.View.Items = []p.ItemInstance{}
|
||||
c.View.Equipment = map[string]string{}
|
||||
|
||||
@@ -119,7 +119,7 @@ func TestGatherCraftAndPermanentDeath(t *testing.T) {
|
||||
}
|
||||
c.View.Inventory["wood"] = 3
|
||||
c.View.Inventory["ore"] = 2
|
||||
if err := w.Intent(id, p.Intent{Op: "craft", Seq: 5, Target: "spear"}); err != nil {
|
||||
if err := w.craft(c, "spear"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if gearCount(c.View.Items, "spear") != 1 || c.View.Inventory["wood"] != 0 || c.View.Inventory["ore"] != 0 {
|
||||
|
||||
@@ -6,12 +6,15 @@ type Protocol struct {
|
||||
CatalogChange *ContentChange `json:"catalogChange,omitempty"`
|
||||
CatalogPreview *ContentPreview `json:"catalogPreview,omitempty"`
|
||||
CatalogResult *ContentResult `json:"catalogResult,omitempty"`
|
||||
CraftRequest *CraftRequest `json:"craftRequest,omitempty"`
|
||||
CraftResult *CraftResult `json:"craftResult,omitempty"`
|
||||
Intent Intent `json:"intent"`
|
||||
Snapshot Snapshot `json:"snapshot"`
|
||||
}
|
||||
|
||||
type ContentCatalog struct {
|
||||
Combat *CombatContent `json:"combat,omitempty"`
|
||||
Crafting *CraftingContent `json:"crafting,omitempty"`
|
||||
EffectSets []EffectSet `json:"effectSets,omitempty"`
|
||||
Gathering *GatheringContent `json:"gathering,omitempty"`
|
||||
Items []ItemDefinition `json:"items"`
|
||||
@@ -95,6 +98,56 @@ type MobSpawn struct {
|
||||
Z float64 `json:"z"`
|
||||
}
|
||||
|
||||
type CraftingContent struct {
|
||||
Materials []CraftMaterial `json:"materials"`
|
||||
Professions []GatheringSkill `json:"professions"`
|
||||
Recipes []CraftRecipe `json:"recipes"`
|
||||
Rules CraftRules `json:"rules"`
|
||||
}
|
||||
|
||||
type CraftMaterial struct {
|
||||
Description string `json:"description"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type GatheringSkill struct {
|
||||
BaseXP int64 `json:"baseXp"`
|
||||
Description string `json:"description"`
|
||||
ID string `json:"id"`
|
||||
MaxLevel int64 `json:"maxLevel"`
|
||||
Name string `json:"name"`
|
||||
XPPerLevel int64 `json:"xpPerLevel"`
|
||||
}
|
||||
|
||||
type CraftRecipe struct {
|
||||
Description string `json:"description"`
|
||||
ID string `json:"id"`
|
||||
Inputs map[string]int64 `json:"inputs"`
|
||||
Level int64 `json:"level"`
|
||||
Name string `json:"name"`
|
||||
Outputs map[string]int64 `json:"outputs"`
|
||||
Profession string `json:"profession"`
|
||||
Revision int64 `json:"revision"`
|
||||
Stats map[string]float64 `json:"stats"`
|
||||
Titles []string `json:"titles"`
|
||||
XP int64 `json:"xp"`
|
||||
}
|
||||
|
||||
type CraftRules struct {
|
||||
BaseFailure float64 `json:"baseFailure"`
|
||||
BaseLoss float64 `json:"baseLoss"`
|
||||
Cooldown float64 `json:"cooldown"`
|
||||
LossDecay float64 `json:"lossDecay"`
|
||||
MaxFailure float64 `json:"maxFailure"`
|
||||
MaxQualityBias float64 `json:"maxQualityBias"`
|
||||
MinFailure float64 `json:"minFailure"`
|
||||
MinLoss float64 `json:"minLoss"`
|
||||
OverLevelDecay float64 `json:"overLevelDecay"`
|
||||
QualityPerLevel float64 `json:"qualityPerLevel"`
|
||||
UnderLevelGrowth float64 `json:"underLevelGrowth"`
|
||||
}
|
||||
|
||||
type EffectSet struct {
|
||||
Description string `json:"description"`
|
||||
ID string `json:"id"`
|
||||
@@ -151,17 +204,10 @@ type ResourceDefinition struct {
|
||||
XP int64 `json:"xp"`
|
||||
}
|
||||
|
||||
type GatheringSkill struct {
|
||||
BaseXP int64 `json:"baseXp"`
|
||||
Description string `json:"description"`
|
||||
ID string `json:"id"`
|
||||
MaxLevel int64 `json:"maxLevel"`
|
||||
Name string `json:"name"`
|
||||
XPPerLevel int64 `json:"xpPerLevel"`
|
||||
}
|
||||
|
||||
type ItemDefinition struct {
|
||||
AttackID *string `json:"attackId,omitempty"`
|
||||
CraftPool []CraftStat `json:"craftPool,omitempty"`
|
||||
CraftRolls *int64 `json:"craftRolls,omitempty"`
|
||||
Description string `json:"description"`
|
||||
DropChance float64 `json:"dropChance"`
|
||||
ID string `json:"id"`
|
||||
@@ -172,6 +218,14 @@ type ItemDefinition struct {
|
||||
Weight float64 `json:"weight"`
|
||||
}
|
||||
|
||||
type CraftStat struct {
|
||||
Max float64 `json:"max"`
|
||||
Min float64 `json:"min"`
|
||||
Percent bool `json:"percent"`
|
||||
Stat string `json:"stat"`
|
||||
Weight float64 `json:"weight"`
|
||||
}
|
||||
|
||||
type ItemRequirements struct {
|
||||
Level int64 `json:"level"`
|
||||
Stats map[string]float64 `json:"stats"`
|
||||
@@ -215,6 +269,10 @@ type ContentChange struct {
|
||||
Attack *CombatAttackDraft `json:"attack,omitempty"`
|
||||
Biome *BiomeDefinitionDraft `json:"biome,omitempty"`
|
||||
Consumable *GatheringConsumableDraft `json:"consumable,omitempty"`
|
||||
CraftMaterial *CraftMaterialDraft `json:"craftMaterial,omitempty"`
|
||||
CraftProfession *GatheringSkillDraft `json:"craftProfession,omitempty"`
|
||||
CraftRecipe *CraftRecipeDraft `json:"craftRecipe,omitempty"`
|
||||
CraftRules *CraftRules `json:"craftRules,omitempty"`
|
||||
EffectSet *EffectSetDraft `json:"effectSet,omitempty"`
|
||||
EffectSetIDS []string `json:"effectSetIds,omitempty"`
|
||||
ExpectedVersion int64 `json:"expectedVersion"`
|
||||
@@ -271,11 +329,10 @@ type GatheringConsumableDraft struct {
|
||||
Seconds float64 `json:"seconds"`
|
||||
}
|
||||
|
||||
type EffectSetDraft struct {
|
||||
Description string `json:"description"`
|
||||
ID *string `json:"id,omitempty"`
|
||||
Modifiers []StatModifier `json:"modifiers"`
|
||||
Name string `json:"name"`
|
||||
type CraftMaterialDraft struct {
|
||||
Description string `json:"description"`
|
||||
ID *string `json:"id,omitempty"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type GatheringSkillDraft struct {
|
||||
@@ -287,8 +344,31 @@ type GatheringSkillDraft struct {
|
||||
XPPerLevel int64 `json:"xpPerLevel"`
|
||||
}
|
||||
|
||||
type CraftRecipeDraft struct {
|
||||
Description string `json:"description"`
|
||||
ID *string `json:"id,omitempty"`
|
||||
Inputs map[string]int64 `json:"inputs"`
|
||||
Level int64 `json:"level"`
|
||||
Name string `json:"name"`
|
||||
Outputs map[string]int64 `json:"outputs"`
|
||||
Profession string `json:"profession"`
|
||||
Revision *int64 `json:"revision,omitempty"`
|
||||
Stats map[string]float64 `json:"stats"`
|
||||
Titles []string `json:"titles"`
|
||||
XP int64 `json:"xp"`
|
||||
}
|
||||
|
||||
type EffectSetDraft struct {
|
||||
Description string `json:"description"`
|
||||
ID *string `json:"id,omitempty"`
|
||||
Modifiers []StatModifier `json:"modifiers"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type ItemDraft struct {
|
||||
AttackID *string `json:"attackId,omitempty"`
|
||||
CraftPool []CraftStat `json:"craftPool,omitempty"`
|
||||
CraftRolls *int64 `json:"craftRolls,omitempty"`
|
||||
Description string `json:"description"`
|
||||
DropChance float64 `json:"dropChance"`
|
||||
ID *string `json:"id,omitempty"`
|
||||
@@ -382,6 +462,28 @@ type ContentResult struct {
|
||||
Version int64 `json:"version"`
|
||||
}
|
||||
|
||||
type CraftRequest struct {
|
||||
CharacterID string `json:"characterId"`
|
||||
ID string `json:"id"`
|
||||
Ingredients map[string]int64 `json:"ingredients"`
|
||||
Profession string `json:"profession"`
|
||||
}
|
||||
|
||||
type CraftResult struct {
|
||||
Consumed map[string]int64 `json:"consumed"`
|
||||
Created []string `json:"created"`
|
||||
ID string `json:"id"`
|
||||
Message string `json:"message"`
|
||||
Recipe *KnownRecipe `json:"recipe,omitempty"`
|
||||
Success bool `json:"success"`
|
||||
Valid bool `json:"valid"`
|
||||
}
|
||||
|
||||
type KnownRecipe struct {
|
||||
DiscoveredAt float64 `json:"discoveredAt"`
|
||||
Recipe CraftRecipe `json:"recipe"`
|
||||
}
|
||||
|
||||
type Intent struct {
|
||||
Op string `json:"op"`
|
||||
Seq int64 `json:"seq"`
|
||||
@@ -465,6 +567,9 @@ type Character struct {
|
||||
Attack *CombatAttack `json:"attack,omitempty"`
|
||||
CarryWeight float64 `json:"carryWeight"`
|
||||
Consumables []GatheringConsumable `json:"consumables,omitempty"`
|
||||
CraftedStacks []CraftedStack `json:"craftedStacks,omitempty"`
|
||||
Crafting map[string]CraftProgress `json:"crafting,omitempty"`
|
||||
DiscoveredRecipes map[string]KnownRecipe `json:"discoveredRecipes,omitempty"`
|
||||
Entity Entity `json:"entity"`
|
||||
Equipment map[string]string `json:"equipment"`
|
||||
Experience int64 `json:"experience"`
|
||||
@@ -491,6 +596,33 @@ type Character struct {
|
||||
Titles []TitleAward `json:"titles"`
|
||||
}
|
||||
|
||||
type CraftedStack struct {
|
||||
ID string `json:"id"`
|
||||
Item string `json:"item"`
|
||||
Provenance CraftProvenance `json:"provenance"`
|
||||
Quantity int64 `json:"quantity"`
|
||||
}
|
||||
|
||||
type CraftProvenance struct {
|
||||
At float64 `json:"at"`
|
||||
CharacterID string `json:"characterId"`
|
||||
CrafterName string `json:"crafterName"`
|
||||
Level int64 `json:"level"`
|
||||
Profession string `json:"profession"`
|
||||
RecipeID string `json:"recipeId"`
|
||||
RecipeRevision int64 `json:"recipeRevision"`
|
||||
WorldID string `json:"worldId"`
|
||||
}
|
||||
|
||||
type CraftProgress struct {
|
||||
ID string `json:"id"`
|
||||
Level int64 `json:"level"`
|
||||
LossPercent float64 `json:"lossPercent"`
|
||||
Name string `json:"name"`
|
||||
XP int64 `json:"xp"`
|
||||
XPToNextLevel int64 `json:"xpToNextLevel"`
|
||||
}
|
||||
|
||||
type SkillProgress struct {
|
||||
EffectiveLevel int64 `json:"effectiveLevel"`
|
||||
Experience StatValue `json:"experience"`
|
||||
@@ -525,6 +657,7 @@ type ItemInstance struct {
|
||||
ID string `json:"id"`
|
||||
Modifiers []StatModifier `json:"modifiers"`
|
||||
Name string `json:"name"`
|
||||
Provenance *CraftProvenance `json:"provenance,omitempty"`
|
||||
RequirementMessage string `json:"requirementMessage"`
|
||||
Requirements ItemRequirements `json:"requirements"`
|
||||
Slot string `json:"slot"`
|
||||
|
||||
@@ -17,15 +17,19 @@ var ErrCatalogInvalid = errors.New("invalid catalog change")
|
||||
var catalogRequestID = regexp.MustCompile(`^[a-f0-9-]{32,36}$`)
|
||||
|
||||
type CatalogChange struct {
|
||||
TargetID string `json:"targetId,omitempty"`
|
||||
Attack *content.CombatAttack `json:"attack,omitempty"`
|
||||
Mob *content.MobDefinition `json:"mob,omitempty"`
|
||||
Loot *content.LootTable `json:"loot,omitempty"`
|
||||
Spawn *content.MobSpawn `json:"spawn,omitempty"`
|
||||
GatheringSkill *content.GatheringSkill `json:"gatheringSkill,omitempty"`
|
||||
Resource *content.ResourceDefinition `json:"resource,omitempty"`
|
||||
Biome *content.BiomeDefinition `json:"biome,omitempty"`
|
||||
Consumable *content.GatheringConsumable `json:"consumable,omitempty"`
|
||||
CraftRecipe *content.CraftRecipe `json:"craftRecipe,omitempty"`
|
||||
CraftProfession *content.GatheringSkill `json:"craftProfession,omitempty"`
|
||||
CraftMaterial *content.CraftMaterial `json:"craftMaterial,omitempty"`
|
||||
CraftRules *content.CraftRules `json:"craftRules,omitempty"`
|
||||
TargetID string `json:"targetId,omitempty"`
|
||||
Attack *content.CombatAttack `json:"attack,omitempty"`
|
||||
Mob *content.MobDefinition `json:"mob,omitempty"`
|
||||
Loot *content.LootTable `json:"loot,omitempty"`
|
||||
Spawn *content.MobSpawn `json:"spawn,omitempty"`
|
||||
GatheringSkill *content.GatheringSkill `json:"gatheringSkill,omitempty"`
|
||||
Resource *content.ResourceDefinition `json:"resource,omitempty"`
|
||||
Biome *content.BiomeDefinition `json:"biome,omitempty"`
|
||||
Consumable *content.GatheringConsumable `json:"consumable,omitempty"`
|
||||
|
||||
ID string `json:"id"`
|
||||
ExpectedVersion int64 `json:"expectedVersion"`
|
||||
@@ -47,7 +51,7 @@ type CatalogResult struct {
|
||||
// Explicit definition IDs are reserved for trusted seed/import code. Browser
|
||||
// publications omit them; the server assigns an ID after resolving request replay.
|
||||
func (c CatalogChange) HasDefinitionID() bool {
|
||||
return (c.Attack != nil && c.Attack.ID != "") || (c.Mob != nil && c.Mob.ID != "") || (c.Loot != nil && c.Loot.ID != "") || (c.Spawn != nil && c.Spawn.ID != "") || (c.GatheringSkill != nil && c.GatheringSkill.ID != "") || (c.Resource != nil && c.Resource.ID != "") || (c.Biome != nil && c.Biome.ID != "") || (c.Consumable != nil && c.Consumable.ID != "") || (c.Title != nil && c.Title.ID != "") || (c.Item != nil && c.Item.ID != "") || (c.RequirementSet != nil && c.RequirementSet.ID != "") || (c.EffectSet != nil && c.EffectSet.ID != "")
|
||||
return (c.CraftRecipe != nil && c.CraftRecipe.ID != "") || (c.CraftProfession != nil && c.CraftProfession.ID != "") || (c.CraftMaterial != nil && c.CraftMaterial.ID != "") || (c.Attack != nil && c.Attack.ID != "") || (c.Mob != nil && c.Mob.ID != "") || (c.Loot != nil && c.Loot.ID != "") || (c.Spawn != nil && c.Spawn.ID != "") || (c.GatheringSkill != nil && c.GatheringSkill.ID != "") || (c.Resource != nil && c.Resource.ID != "") || (c.Biome != nil && c.Biome.ID != "") || (c.Consumable != nil && c.Consumable.ID != "") || (c.Title != nil && c.Title.ID != "") || (c.Item != nil && c.Item.ID != "") || (c.RequirementSet != nil && c.RequirementSet.ID != "") || (c.EffectSet != nil && c.EffectSet.ID != "")
|
||||
}
|
||||
|
||||
type CatalogAudit struct {
|
||||
@@ -118,6 +122,13 @@ func decodeCatalog(version int64, raw string) (content.Catalog, error) {
|
||||
}
|
||||
catalog.Combat = b.Combat
|
||||
}
|
||||
if catalog.Crafting == nil {
|
||||
defaults, e := content.Load()
|
||||
if e != nil {
|
||||
return catalog, e
|
||||
}
|
||||
catalog.RestoreCrafting(defaults)
|
||||
}
|
||||
return catalog, catalog.Validate()
|
||||
}
|
||||
func (d *DB) Catalog(ctx context.Context) (content.Catalog, error) {
|
||||
@@ -142,10 +153,10 @@ func (d *DB) CatalogAfter(ctx context.Context, after int64) (*content.Catalog, e
|
||||
return &catalog, err
|
||||
}
|
||||
func (c CatalogChange) validate() error {
|
||||
if (c.Op == "update-biome") != (c.TargetID != "") {
|
||||
return fmt.Errorf("%w: only biome edits require an existing target", ErrCatalogInvalid)
|
||||
if (c.Op == "update-biome" || c.Op == "update-craft-recipe") != (c.TargetID != "") {
|
||||
return fmt.Errorf("%w: only biome and recipe edits require an existing target", ErrCatalogInvalid)
|
||||
}
|
||||
if c.Biome != nil && c.Biome.Revision != 0 {
|
||||
if (c.Biome != nil && c.Biome.Revision != 0) || (c.CraftRecipe != nil && c.CraftRecipe.Revision != 0) {
|
||||
return fmt.Errorf("%w: revisions are assigned by the server", ErrCatalogInvalid)
|
||||
}
|
||||
if !catalogRequestID.MatchString(c.ID) || c.ExpectedVersion < 1 || len(c.Reason) < 5 || len(c.Reason) > 240 {
|
||||
@@ -153,12 +164,20 @@ func (c CatalogChange) validate() error {
|
||||
}
|
||||
valid := false
|
||||
count := 0
|
||||
for _, present := range []bool{c.Attack != nil, c.Mob != nil, c.Loot != nil, c.Spawn != nil, c.GatheringSkill != nil, c.Resource != nil, c.Biome != nil, c.Consumable != nil, c.Title != nil, c.Item != nil, c.Stats != nil, c.RequirementSet != nil, c.EffectSet != nil} {
|
||||
for _, present := range []bool{c.CraftRecipe != nil, c.CraftProfession != nil, c.CraftMaterial != nil, c.CraftRules != nil, c.Attack != nil, c.Mob != nil, c.Loot != nil, c.Spawn != nil, c.GatheringSkill != nil, c.Resource != nil, c.Biome != nil, c.Consumable != nil, c.Title != nil, c.Item != nil, c.Stats != nil, c.RequirementSet != nil, c.EffectSet != nil} {
|
||||
if present {
|
||||
count++
|
||||
}
|
||||
}
|
||||
switch c.Op {
|
||||
case "create-craft-recipe", "update-craft-recipe":
|
||||
valid = c.CraftRecipe != nil
|
||||
case "create-craft-profession":
|
||||
valid = c.CraftProfession != nil
|
||||
case "create-craft-material":
|
||||
valid = c.CraftMaterial != nil
|
||||
case "update-craft-rules":
|
||||
valid = c.CraftRules != nil
|
||||
case "create-attack":
|
||||
valid = c.Attack != nil
|
||||
case "create-mob":
|
||||
|
||||
@@ -35,6 +35,15 @@ func (d *DB) PreviewCatalog(ctx context.Context, change CatalogChange) (CatalogP
|
||||
}
|
||||
// Preview validates a provisional identity but does not reserve or expose it.
|
||||
if !change.HasDefinitionID() {
|
||||
if resolved.CraftRecipe != nil && change.Op != "update-craft-recipe" {
|
||||
resolved.CraftRecipe.ID = ""
|
||||
}
|
||||
if resolved.CraftProfession != nil {
|
||||
resolved.CraftProfession.ID = ""
|
||||
}
|
||||
if resolved.CraftMaterial != nil {
|
||||
resolved.CraftMaterial.ID = ""
|
||||
}
|
||||
if resolved.Attack != nil {
|
||||
resolved.Attack.ID = ""
|
||||
}
|
||||
@@ -106,7 +115,55 @@ func buildCatalog(c content.Catalog, change CatalogChange) (content.Catalog, str
|
||||
}
|
||||
combat := *c.Combat
|
||||
c.Combat = &combat
|
||||
if c.Crafting == nil {
|
||||
b, e := content.Load()
|
||||
if e != nil {
|
||||
return invalid(e)
|
||||
}
|
||||
c.RestoreCrafting(b)
|
||||
}
|
||||
crafting := *c.Crafting
|
||||
c.Crafting = &crafting
|
||||
switch change.Op {
|
||||
case "create-craft-recipe", "update-craft-recipe":
|
||||
v := *change.CraftRecipe
|
||||
v.Revision = 1
|
||||
if change.Op == "update-craft-recipe" {
|
||||
i := slices.IndexFunc(c.Crafting.Recipes, func(r content.CraftRecipe) bool { return r.ID == change.TargetID })
|
||||
if i < 0 {
|
||||
return invalid(fmt.Errorf("recipe not found"))
|
||||
}
|
||||
v.ID = c.Crafting.Recipes[i].ID
|
||||
v.Revision = c.Crafting.Recipes[i].Revision + 1
|
||||
c.Crafting.Recipes = slices.Clone(c.Crafting.Recipes)
|
||||
c.Crafting.Recipes[i] = v
|
||||
} else {
|
||||
if v.ID == "" {
|
||||
v.ID = "recipe_" + game.ID()
|
||||
}
|
||||
c.Crafting.Recipes = append(slices.Clone(c.Crafting.Recipes), v)
|
||||
}
|
||||
resolved.CraftRecipe = &v
|
||||
target = v.ID
|
||||
case "create-craft-profession":
|
||||
v := *change.CraftProfession
|
||||
if v.ID == "" {
|
||||
v.ID = "profession_" + game.ID()
|
||||
}
|
||||
c.Crafting.Professions = append(slices.Clone(c.Crafting.Professions), v)
|
||||
resolved.CraftProfession = &v
|
||||
target = v.ID
|
||||
case "create-craft-material":
|
||||
v := *change.CraftMaterial
|
||||
if v.ID == "" {
|
||||
v.ID = "material_" + game.ID()
|
||||
}
|
||||
c.Crafting.Materials = append(slices.Clone(c.Crafting.Materials), v)
|
||||
resolved.CraftMaterial = &v
|
||||
target = v.ID
|
||||
case "update-craft-rules":
|
||||
c.Crafting.Rules = *change.CraftRules
|
||||
target = "crafting-rules"
|
||||
case "create-attack":
|
||||
v := *change.Attack
|
||||
if v.ID == "" {
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"aeternalis/server/internal/game"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
var ErrCraft = errors.New("craft rejected")
|
||||
|
||||
type craftReceipt struct{ ID, Account, CharacterID, Request, Result string }
|
||||
|
||||
func (d *DB) CraftReceipt(ctx context.Context, account string, req p.CraftRequest) (*p.CraftResult, error) {
|
||||
var request, result string
|
||||
e := d.sql.QueryRowContext(ctx, d.q(`SELECT request_json,result_json FROM craft_receipts WHERE account_id=? AND id=?`), account, req.ID).Scan(&request, &result)
|
||||
if errors.Is(e, sql.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
raw, _ := json.Marshal(req)
|
||||
if string(raw) != request {
|
||||
return nil, fmt.Errorf("%w: attempt ID already used with different ingredients", ErrCraft)
|
||||
}
|
||||
var out p.CraftResult
|
||||
e = json.Unmarshal([]byte(result), &out)
|
||||
return &out, e
|
||||
}
|
||||
|
||||
// Called under the world service mutex. Consumption, rolls, discovery, XP and
|
||||
// the replay receipt share the same fenced snapshot transaction.
|
||||
func (l *Lease) Craft(ctx context.Context, live *game.World, account string, req p.CraftRequest) (p.CraftResult, error) {
|
||||
fail := func(msg string) (p.CraftResult, error) { return p.CraftResult{}, fmt.Errorf("%w: %s", ErrCraft, msg) }
|
||||
if !game.ValidCraftRequest(req) {
|
||||
return fail("invalid crafting request")
|
||||
}
|
||||
if old, e := l.DB.CraftReceipt(ctx, account, req); e != nil {
|
||||
return p.CraftResult{}, e
|
||||
} else if old != nil {
|
||||
return *old, nil
|
||||
}
|
||||
active, e := l.DB.ActiveCharacter(ctx, account)
|
||||
if e != nil {
|
||||
return p.CraftResult{}, e
|
||||
}
|
||||
if active == nil || active.ID != req.CharacterID || active.WorldID != live.ID || active.State != "alive" {
|
||||
return fail("character is not active in this world")
|
||||
}
|
||||
original := live.Characters[req.CharacterID]
|
||||
if original == nil || original.Account != account {
|
||||
return fail("character unavailable")
|
||||
}
|
||||
staged := stageTitleWorld(live)
|
||||
// Deep-copy only the acting view; leave all other players' live inputs intact.
|
||||
raw, e := json.Marshal(original.View)
|
||||
if e != nil {
|
||||
return p.CraftResult{}, e
|
||||
}
|
||||
var view p.Character
|
||||
if e = json.Unmarshal(raw, &view); e != nil {
|
||||
return p.CraftResult{}, e
|
||||
}
|
||||
staged.Characters[req.CharacterID].View = view
|
||||
result, e := staged.AttemptCraft(staged.Characters[req.CharacterID], req)
|
||||
if e != nil {
|
||||
return fail(e.Error())
|
||||
}
|
||||
request, _ := json.Marshal(req)
|
||||
out, _ := json.Marshal(result)
|
||||
receipt := &craftReceipt{req.ID, account, req.CharacterID, string(request), string(out)}
|
||||
if e = l.save(ctx, staged, "", nil, "", receipt); e != nil {
|
||||
return p.CraftResult{}, e
|
||||
}
|
||||
// Retain character pointers captured by existing WebSocket handlers.
|
||||
for id, c := range staged.Characters {
|
||||
*live.Characters[id] = *c
|
||||
}
|
||||
live.RandomCounter = staged.RandomCounter
|
||||
live.PendingTitles = nil
|
||||
live.Saved()
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"aeternalis/server/content"
|
||||
"aeternalis/server/internal/game"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestCraftDurability(t *testing.T) {
|
||||
testCraftDurability(t, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "craft.db")))
|
||||
}
|
||||
func TestPostgresCraftDurability(t *testing.T) {
|
||||
dsn := os.Getenv("TEST_DATABASE_URL")
|
||||
if dsn == "" {
|
||||
t.Skip("TEST_DATABASE_URL not configured")
|
||||
}
|
||||
testCraftDurability(t, dsn)
|
||||
}
|
||||
func testCraftDurability(t *testing.T, dsn string) {
|
||||
ctx := context.Background()
|
||||
db, e := Open(ctx, dsn)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer db.Close()
|
||||
b, e := content.Load()
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
b.Crafting.Rules.BaseFailure = 0
|
||||
b.Crafting.Rules.MinFailure = 0
|
||||
b.Crafting.Rules.MaxFailure = 0
|
||||
now := time.Now().UTC()
|
||||
w := game.New("craft-"+game.ID(), 1, now, b)
|
||||
l, _, e := db.Acquire(ctx, w)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
c, e := w.Join("crafter-"+game.ID(), "Maker")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = w.Connect(c.View.Entity.ID); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
c.View.Inventory["wood"] = 20
|
||||
c.View.Inventory["ore"] = 20
|
||||
c.View.Inventory["escape_stone"] = 1
|
||||
if e = l.Save(ctx, w, ""); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
req := p.CraftRequest{ID: game.ID(), CharacterID: c.View.Entity.ID, Profession: "weapon_smithing", Ingredients: map[string]int64{"wood": 3, "ore": 2}}
|
||||
before, _ := json.Marshal(c)
|
||||
random := w.RandomCounter
|
||||
for _, state := range []string{"offline", "sheltered", "dead", "capped"} {
|
||||
switch state {
|
||||
case "offline":
|
||||
c.Online = false
|
||||
case "sheltered":
|
||||
c.Sheltered = true
|
||||
case "dead":
|
||||
c.View.Entity.State = "dead"
|
||||
case "capped":
|
||||
c.View.RemainingSeconds = 0
|
||||
}
|
||||
if _, e = l.Craft(ctx, w, c.Account, req); !errors.Is(e, ErrCraft) {
|
||||
t.Fatalf("accepted %s: %v", state, e)
|
||||
}
|
||||
var restored game.Character
|
||||
if e = json.Unmarshal(before, &restored); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
*c = restored
|
||||
c.Online = true
|
||||
}
|
||||
stale := *l
|
||||
stale.Revision--
|
||||
if _, e = stale.Craft(ctx, w, c.Account, req); !errors.Is(e, ErrOwnership) {
|
||||
t.Fatal("stale craft was not fenced", e)
|
||||
}
|
||||
after, _ := json.Marshal(c)
|
||||
if string(after) != string(before) || w.RandomCounter != random {
|
||||
t.Fatal("failed save changed live crafting state")
|
||||
}
|
||||
if receipt, e := db.CraftReceipt(ctx, c.Account, req); e != nil || receipt != nil {
|
||||
t.Fatal("failed save left receipt", e)
|
||||
}
|
||||
result, e := l.Craft(ctx, w, c.Account, req)
|
||||
if e != nil || !result.Success {
|
||||
t.Fatal(result, e)
|
||||
}
|
||||
if w.Characters[c.View.Entity.ID] != c || c.View.Inventory["wood"] != 17 || c.View.Crafting["weapon_smithing"].XP != 20 {
|
||||
t.Fatal("craft did not publish onto live character")
|
||||
}
|
||||
committed, _ := json.Marshal(c)
|
||||
random = w.RandomCounter
|
||||
replay, e := l.Craft(ctx, w, c.Account, req)
|
||||
if e != nil || !reflect.DeepEqual(result, replay) {
|
||||
t.Fatal("retry changed result", e)
|
||||
}
|
||||
after, _ = json.Marshal(c)
|
||||
if string(after) != string(committed) || w.RandomCounter != random {
|
||||
t.Fatal("retry spent resources or rerolled")
|
||||
}
|
||||
changed := req
|
||||
changed.Ingredients = map[string]int64{"wood": 4, "ore": 2}
|
||||
if _, e = l.Craft(ctx, w, c.Account, changed); !errors.Is(e, ErrCraft) {
|
||||
t.Fatal("reused nonce accepted changed ingredients", e)
|
||||
}
|
||||
if _, e = l.Craft(ctx, w, "intruder", req); !errors.Is(e, ErrCraft) {
|
||||
t.Fatal("other account recovered receipt", e)
|
||||
}
|
||||
// Reload from the durable world snapshot, not the live result.
|
||||
if e = l.Release(ctx); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
restored := game.New(w.ID, 1, now, b)
|
||||
var snapshot []byte
|
||||
l, snapshot, e = db.Acquire(ctx, restored)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = json.Unmarshal(snapshot, restored); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = restored.Restore(now); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
w = restored
|
||||
c = w.ForAccount(c.Account)
|
||||
if c == nil || len(c.View.DiscoveredRecipes) != 1 || c.View.Crafting["weapon_smithing"].XP != 20 {
|
||||
t.Fatal("restart lost progression")
|
||||
}
|
||||
if e = w.Connect(c.View.Entity.ID); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
hub := game.New("hub-"+game.ID(), 2, now, b)
|
||||
hub.Kind = "hub"
|
||||
hub.Phase = "hub"
|
||||
hl, _, e := db.Acquire(ctx, hub)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
progression, _ := json.Marshal([]any{c.View.Crafting, c.View.DiscoveredRecipes, c.View.Items, c.View.Experience, c.CraftReadyAt})
|
||||
transfer, e := l.PrepareTravel(ctx, w, c.Account, game.ID(), hub.ID, "escape")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = hl.AcceptTravel(ctx, hub, c.Account, transfer.ID); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
arrived := hub.ForAccount(c.Account)
|
||||
after, _ = json.Marshal([]any{arrived.View.Crafting, arrived.View.DiscoveredRecipes, arrived.View.Items, arrived.View.Experience, arrived.CraftReadyAt})
|
||||
if string(progression) != string(after) {
|
||||
t.Fatal("travel changed crafting progression or provenance")
|
||||
}
|
||||
replay, e = hl.Craft(ctx, hub, c.Account, req)
|
||||
if e != nil || !reflect.DeepEqual(result, replay) {
|
||||
t.Fatal("travel lost original receipt", e)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCraftRecipeRevision(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db, e := Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "recipes.db")))
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer db.Close()
|
||||
initial, e := db.Catalog(ctx)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
recipe := content.CraftRecipe{Name: "Trial spear", Profession: "weapon_smithing", Level: 2, XP: 25, Inputs: map[string]int64{"wood": 5, "ore": 3}, Outputs: map[string]int64{"spear": 1}}
|
||||
change := CatalogChange{ID: game.ID(), ExpectedVersion: initial.Version, Op: "create-craft-recipe", Reason: "Create a test recipe", CraftRecipe: &recipe}
|
||||
first, e := db.PublishCatalog(ctx, "operator", change)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
firstCatalog, e := db.Catalog(ctx)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
made := firstCatalog.Crafting.Recipes[len(firstCatalog.Crafting.Recipes)-1]
|
||||
if made.ID == "" || made.Revision != 1 {
|
||||
t.Fatal("server did not assign recipe identity")
|
||||
}
|
||||
replay, e := db.PublishCatalog(ctx, "operator", change)
|
||||
if e != nil || replay.Version != first.Version {
|
||||
t.Fatal("recipe create retry failed", e)
|
||||
}
|
||||
recipe.Inputs = map[string]int64{"wood": 6, "ore": 3}
|
||||
update := CatalogChange{ID: game.ID(), ExpectedVersion: first.Version, Op: "update-craft-recipe", TargetID: made.ID, Reason: "Revise test ingredients", CraftRecipe: &recipe}
|
||||
_, e = db.PublishCatalog(ctx, "operator", update)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
revised, e := db.Catalog(ctx)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
got := revised.Crafting.Recipes[len(revised.Crafting.Recipes)-1]
|
||||
if got.ID != made.ID || got.Revision != 2 || len(revised.Crafting.Recipes) != len(firstCatalog.Crafting.Recipes) || made.Inputs["wood"] != 5 {
|
||||
t.Fatal("revision duplicated identity or mutated prior version")
|
||||
}
|
||||
update.ID = game.ID()
|
||||
if _, e = db.PublishCatalog(ctx, "operator", update); !errors.Is(e, ErrCatalogConflict) {
|
||||
t.Fatal("stale edit accepted", e)
|
||||
}
|
||||
}
|
||||
@@ -65,6 +65,7 @@ func (d *DB) migrate(ctx context.Context) error {
|
||||
}
|
||||
}
|
||||
for _, stmt := range []string{
|
||||
`CREATE TABLE IF NOT EXISTS craft_receipts(id TEXT NOT NULL,account_id TEXT NOT NULL,character_id TEXT NOT NULL,request_json TEXT NOT NULL,result_json TEXT NOT NULL,PRIMARY KEY(account_id,id))`,
|
||||
`CREATE TABLE IF NOT EXISTS schema_migrations(version INTEGER PRIMARY KEY)`,
|
||||
`CREATE TABLE IF NOT EXISTS title_awards(account_id TEXT NOT NULL, title_id TEXT NOT NULL, scope TEXT NOT NULL, scope_key TEXT NOT NULL, character_id TEXT NOT NULL, award TEXT NOT NULL, PRIMARY KEY(account_id,title_id), UNIQUE(scope,scope_key,title_id))`,
|
||||
`CREATE TABLE IF NOT EXISTS title_revocations(account_id TEXT NOT NULL,title_id TEXT NOT NULL,command_id TEXT NOT NULL,PRIMARY KEY(account_id,title_id))`,
|
||||
|
||||
@@ -139,6 +139,9 @@ func (l *Lease) Save(ctx context.Context, w *game.World, claimID string) error {
|
||||
return l.SaveCommand(ctx, w, claimID, nil, "")
|
||||
}
|
||||
func (l *Lease) SaveCommand(ctx context.Context, w *game.World, claimID string, command *Command, outcome string) error {
|
||||
return l.save(ctx, w, claimID, command, outcome, nil)
|
||||
}
|
||||
func (l *Lease) save(ctx context.Context, w *game.World, claimID string, command *Command, outcome string, receipt *craftReceipt) error {
|
||||
live := w
|
||||
w = stageTitleWorld(w)
|
||||
data, err := json.Marshal(w)
|
||||
@@ -159,6 +162,11 @@ func (l *Lease) SaveCommand(ctx context.Context, w *game.World, claimID string,
|
||||
if n != 1 {
|
||||
return ErrOwnership
|
||||
}
|
||||
if receipt != nil {
|
||||
if _, err = tx.ExecContext(ctx, d.q(`INSERT INTO craft_receipts(id,account_id,character_id,request_json,result_json) VALUES(?,?,?,?,?)`), receipt.ID, receipt.Account, receipt.CharacterID, receipt.Request, receipt.Result); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if claimID != "" {
|
||||
c := w.Characters[claimID]
|
||||
if c == nil {
|
||||
|
||||
@@ -21,6 +21,8 @@ func stageTitleWorld(w *game.World) *game.World {
|
||||
copy := *c
|
||||
copy.View.Titles = append([]p.TitleAward{}, c.View.Titles...)
|
||||
copy.View.Items = append([]p.ItemInstance{}, c.View.Items...)
|
||||
copy.View.CraftedStacks = append([]p.CraftedStack{}, c.View.CraftedStacks...)
|
||||
copy.View.Crafting = maps.Clone(c.View.Crafting)
|
||||
copy.View.Inventory = maps.Clone(c.View.Inventory)
|
||||
copy.View.Equipment = maps.Clone(c.View.Equipment)
|
||||
copy.View.AllocatedStats = maps.Clone(c.View.AllocatedStats)
|
||||
|
||||
@@ -107,10 +107,7 @@ func (l *Lease) PrepareTravel(ctx context.Context, live *game.World, account, re
|
||||
return nil, err
|
||||
}
|
||||
if route == "escape" {
|
||||
departing.View.Inventory["escape_stone"]--
|
||||
if departing.View.Inventory["escape_stone"] == 0 {
|
||||
delete(departing.View.Inventory, "escape_stone")
|
||||
}
|
||||
game.TakeStack(&departing, "escape_stone", 1)
|
||||
}
|
||||
raw, err = json.Marshal(&departing)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"aeternalis/server/internal/store"
|
||||
"errors"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func (h *HTTP) craftingRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/crafting", func(w http.ResponseWriter, r *http.Request) {
|
||||
account, e := h.auth.account(r)
|
||||
if e != nil {
|
||||
fail(w, 401, "sign in required")
|
||||
return
|
||||
}
|
||||
h.s.mu.Lock()
|
||||
defer h.s.mu.Unlock()
|
||||
if !h.s.ready.Load() {
|
||||
fail(w, 503, "world unavailable")
|
||||
return
|
||||
}
|
||||
active, e := h.auth.db.ActiveCharacter(r.Context(), account)
|
||||
if e != nil {
|
||||
fail(w, 503, "character unavailable")
|
||||
return
|
||||
}
|
||||
c := h.s.world.ForAccount(account)
|
||||
if c == nil || active == nil || active.ID != c.View.Entity.ID || active.WorldID != h.s.world.ID {
|
||||
fail(w, 409, "enter your character's world first")
|
||||
return
|
||||
}
|
||||
// Publish profession levels and only recipes this character has discovered.
|
||||
known := []p.KnownRecipe{}
|
||||
stale := []string{}
|
||||
for id, discovery := range c.View.DiscoveredRecipes {
|
||||
known = append(known, discovery)
|
||||
current := false
|
||||
for _, recipe := range h.s.world.Balance.Crafting.Recipes {
|
||||
if recipe.ID == id && recipe.Revision == discovery.Recipe.Revision {
|
||||
current = true
|
||||
}
|
||||
}
|
||||
if !current {
|
||||
stale = append(stale, id)
|
||||
}
|
||||
}
|
||||
respond(w, 200, map[string]any{"professions": h.s.world.CraftProfessions(c), "known": known, "stale": stale, "earnsXP": h.s.world.AllowsXP()})
|
||||
})
|
||||
mux.HandleFunc("POST /api/craft", func(w http.ResponseWriter, r *http.Request) {
|
||||
account, e := h.auth.account(r)
|
||||
if e != nil {
|
||||
fail(w, 401, "sign in required")
|
||||
return
|
||||
}
|
||||
var req p.CraftRequest
|
||||
if decode(w, r, &req) != nil {
|
||||
fail(w, 400, "invalid craft request")
|
||||
return
|
||||
}
|
||||
h.s.mu.Lock()
|
||||
defer h.s.mu.Unlock()
|
||||
if !h.s.ready.Load() {
|
||||
fail(w, 503, "world unavailable")
|
||||
return
|
||||
}
|
||||
if e = h.s.refreshCatalog(r.Context()); e != nil {
|
||||
fail(w, 503, "crafting catalog unavailable")
|
||||
return
|
||||
}
|
||||
result, e := h.s.lease.Craft(r.Context(), h.s.world, account, req)
|
||||
if errors.Is(e, store.ErrCraft) {
|
||||
fail(w, 409, e.Error())
|
||||
return
|
||||
}
|
||||
if e != nil {
|
||||
h.s.ready.Store(false)
|
||||
for _, peer := range h.s.peers {
|
||||
peer.close()
|
||||
}
|
||||
fail(w, 503, "craft save unavailable; retry the same attempt after reconnecting")
|
||||
return
|
||||
}
|
||||
respond(w, 200, result)
|
||||
})
|
||||
}
|
||||
@@ -98,6 +98,7 @@ func (h *HTTP) Handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
h.portalRoutes(mux)
|
||||
h.travelRoutes(mux)
|
||||
h.craftingRoutes(mux)
|
||||
h.catalogRoutes(mux)
|
||||
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !h.s.ready.Load() {
|
||||
@@ -149,7 +150,7 @@ func (h *HTTP) Handler() http.Handler {
|
||||
h.s.mu.Lock()
|
||||
defer h.s.mu.Unlock()
|
||||
b := h.s.world.Balance
|
||||
respond(w, 200, map[string]any{"worldId": h.s.world.ID, "kind": h.s.world.Kind, "development": h.auth.dev, "worlds": h.worlds, "chunkSize": b.ChunkSize, "playerSpeed": b.PlayerSpeed, "attackRange": b.AttackRange, "gatherRange": b.GatherRange, "recipes": b.Recipes, "tickHz": b.TickHz})
|
||||
respond(w, 200, map[string]any{"worldId": h.s.world.ID, "kind": h.s.world.Kind, "development": h.auth.dev, "worlds": h.worlds, "chunkSize": b.ChunkSize, "playerSpeed": b.PlayerSpeed, "attackRange": b.AttackRange, "gatherRange": b.GatherRange, "tickHz": b.TickHz})
|
||||
})
|
||||
mux.HandleFunc("GET /api/preview", func(w http.ResponseWriter, r *http.Request) {
|
||||
h.s.mu.Lock()
|
||||
|
||||
@@ -114,6 +114,59 @@ func TestHTTPAndSocketSecurity(t *testing.T) {
|
||||
if bytes.Contains(data, []byte(`"account"`)) {
|
||||
t.Fatal("account identity leaked")
|
||||
}
|
||||
// Public configuration and unauthenticated routes must never expose recipes.
|
||||
for _, path := range []string{"/api/config", "/api/crafting", "/api/control/catalog"} {
|
||||
response, e := server.Client().Get(server.URL + path)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
body, _ := io.ReadAll(response.Body)
|
||||
response.Body.Close()
|
||||
if bytes.Contains(body, []byte("recipe_spear")) || bytes.Contains(body, []byte(`"recipes"`)) {
|
||||
t.Fatal("secret recipes exposed", path)
|
||||
}
|
||||
if path != "/api/config" && response.StatusCode == 200 {
|
||||
t.Fatal("unauthenticated crafting/catalog access", path)
|
||||
}
|
||||
}
|
||||
svc.mu.Lock()
|
||||
c := svc.world.Characters[character.Entity.ID]
|
||||
c.View.Inventory["herb"] = 10
|
||||
svc.mu.Unlock()
|
||||
craft := p.CraftRequest{ID: game.ID(), CharacterID: character.Entity.ID, Profession: "alchemist", Ingredients: map[string]int64{"herb": 2}}
|
||||
body, _ := json.Marshal(craft)
|
||||
for _, origin := range []string{"", "https://evil.example"} {
|
||||
response := request("/api/craft", origin, string(body), cookie)
|
||||
response.Body.Close()
|
||||
if response.StatusCode != 403 {
|
||||
t.Fatal("cross-origin crafting accepted")
|
||||
}
|
||||
}
|
||||
response = request("/api/craft", server.URL, string(body), cookie)
|
||||
var outcome p.CraftResult
|
||||
if e := json.NewDecoder(response.Body).Decode(&outcome); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
response.Body.Close()
|
||||
if response.StatusCode != 200 || !outcome.Valid || outcome.Recipe == nil {
|
||||
t.Fatal("ingredient craft did not record valid recipe", outcome)
|
||||
}
|
||||
get, _ := http.NewRequest("GET", server.URL+"/api/crafting", nil)
|
||||
get.AddCookie(cookie)
|
||||
response, err = server.Client().Do(get)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var known struct {
|
||||
Known []p.KnownRecipe `json:"known"`
|
||||
}
|
||||
if err = json.NewDecoder(response.Body).Decode(&known); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
response.Body.Close()
|
||||
if len(known.Known) != 1 || known.Known[0].Recipe.ID != "recipe_bandage" {
|
||||
t.Fatal("crafting returned undiscovered recipes")
|
||||
}
|
||||
intent := p.Intent{Op: "move", Seq: 1, X: 1}
|
||||
payload, _ := json.Marshal(intent)
|
||||
if err = conn.Write(socketCtx, websocket.MessageText, payload); err != nil {
|
||||
|
||||
Reference in New Issue
Block a user