Add item actions, targeting, bindings, and encumbrance
This commit is contained in:
@@ -153,6 +153,11 @@ func (w *World) attack(c *Character, target string) error {
|
||||
return errors.New("area effect limit reached")
|
||||
}
|
||||
power := c.View.Stats[a.Stat].Final * a.Multiplier
|
||||
// Coatings add damage to this weapon attack, so they use the same server
|
||||
// collision, defence and credit rules. Spells do not inherit weapon coatings.
|
||||
if i := ownedItem(c, c.View.Equipment["weapon"]); a.Effect == "damage" && i != nil && i.Coating != nil && i.Coating.ExpiresAt > float64(w.now.UnixMilli())/1000 {
|
||||
power += i.Coating.Damage
|
||||
}
|
||||
if a.Effect == "damage" && w.roll(c.View.Stats["criticalChance"].Final) {
|
||||
power *= w.Balance.CriticalMultiplier
|
||||
}
|
||||
|
||||
@@ -42,6 +42,9 @@ func (w *World) refreshCrafting(c *Character) {
|
||||
}
|
||||
}
|
||||
func (w *World) restoreCrafting(c *Character) error {
|
||||
if !finiteCraft(c.ItemReadyAt) {
|
||||
return errors.New("invalid item cooldown")
|
||||
}
|
||||
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")
|
||||
}
|
||||
|
||||
@@ -133,6 +133,11 @@ 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 v := item.Coating; v != nil {
|
||||
if item.Slot != "weapon" || item.HouseID != nil || item.Furniture != nil || v.Name == "" || len(v.Name) > 100 || v.Source == "" || len(v.Source) > 100 || !finiteCraft(v.ExpiresAt) || v.ExpiresAt <= 0 || !finiteCraft(v.Damage) || v.Damage <= 0 || v.Damage > 10000 {
|
||||
return errors.New("invalid weapon coating")
|
||||
}
|
||||
}
|
||||
if item.Provenance != nil && !validProvenance(*item.Provenance) {
|
||||
return errors.New("invalid equipment provenance")
|
||||
}
|
||||
@@ -281,14 +286,16 @@ func (w *World) equip(c *Character, itemID, slot string) error {
|
||||
if c.View.Equipment == nil {
|
||||
c.View.Equipment = map[string]string{}
|
||||
}
|
||||
if c.View.Equipment[slot] != "" {
|
||||
return errors.New("unequip the occupied slot first")
|
||||
}
|
||||
for _, id := range c.View.Equipment {
|
||||
for equippedSlot, id := range c.View.Equipment {
|
||||
if id == itemID {
|
||||
return errors.New("item is already equipped")
|
||||
if equippedSlot == slot {
|
||||
return nil
|
||||
}
|
||||
delete(c.View.Equipment, equippedSlot)
|
||||
}
|
||||
}
|
||||
// Both items remain owned. The displaced item is already in Items and returns
|
||||
// to the bag when its equipment assignment is replaced.
|
||||
c.View.Equipment[slot] = itemID
|
||||
w.RefreshStats(c)
|
||||
w.evaluateTitles(c)
|
||||
|
||||
@@ -46,8 +46,8 @@ func TestEquipmentSlotsAndRequirements(t *testing.T) {
|
||||
if w.equip(c, "missing", "weapon") == nil || w.equip(c, "slot_ring1", "ring9") == nil {
|
||||
t.Fatal("invalid ownership/slot accepted")
|
||||
}
|
||||
if w.equip(c, "slot_ring1", "ring2") == nil {
|
||||
t.Fatal("same instance equipped twice")
|
||||
if w.equip(c, "slot_ring1", "ring2") != nil || c.View.Equipment["ring1"] != "" || c.View.Equipment["ring2"] != "slot_ring1" || ownedItem(c, "slot_ring2") == nil {
|
||||
t.Fatal("ring swap duplicated assignment or lost displaced item")
|
||||
}
|
||||
if err := w.unequip(c, "helmet"); err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -121,7 +121,11 @@ func (w *World) refreshGathering(c *Character) {
|
||||
for _, v := range w.Balance.Gathering.Consumables {
|
||||
if c.View.Inventory[v.ID] > 0 {
|
||||
c.View.StackNames[v.ID] = v.Name
|
||||
c.View.Consumables = append(c.View.Consumables, p.GatheringConsumable{ID: v.ID, Name: v.Name, Description: v.Description, Seconds: v.Seconds, Modifiers: protocolModifiers(v.Modifiers)})
|
||||
var effect *p.ItemUseEffect
|
||||
if v.UseEffect != nil {
|
||||
effect = &p.ItemUseEffect{Kind: v.UseEffect.Kind, Amount: v.UseEffect.Amount}
|
||||
}
|
||||
c.View.Consumables = append(c.View.Consumables, p.GatheringConsumable{ID: v.ID, Name: v.Name, Description: v.Description, Seconds: v.Seconds, Modifiers: protocolModifiers(v.Modifiers), UseEffect: effect})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -247,6 +251,9 @@ func (w *World) consumeGathering(c *Character, id string) error {
|
||||
}
|
||||
for _, v := range w.Balance.Gathering.Consumables {
|
||||
if v.ID == id {
|
||||
if v.UseEffect != nil {
|
||||
return errors.New("use this item through its targeted item action")
|
||||
}
|
||||
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")
|
||||
}
|
||||
@@ -261,6 +268,9 @@ func (w *World) consumeGathering(c *Character, id string) error {
|
||||
return errors.New("unknown gathering consumable")
|
||||
}
|
||||
func (w *World) jump(c *Character) error {
|
||||
if w.EncumbranceFactor(c) == 0 {
|
||||
return errors.New("too encumbered to jump")
|
||||
}
|
||||
ground := w.floorAt(c.View.Entity.Position.X, c.View.Entity.Position.Z, c.View.Entity.Position.Y)
|
||||
if c.JumpVelocity != 0 || c.View.Entity.Position.Y > ground+0.05 {
|
||||
return errors.New("already airborne")
|
||||
|
||||
@@ -76,6 +76,9 @@ func (w *World) houseIntent(c *Character, i p.Intent) error {
|
||||
c.LastMove = w.now
|
||||
return nil
|
||||
case "jump":
|
||||
if w.EncumbranceFactor(c) == 0 {
|
||||
return errors.New("too encumbered to jump")
|
||||
}
|
||||
if math.Abs(c.View.HousePosition.Y-roomGround(c.HouseRoom, *c.View.HousePosition)) > .02 || c.JumpVelocity != 0 {
|
||||
return errors.New("already jumping")
|
||||
}
|
||||
@@ -94,8 +97,9 @@ func (w *World) moveHouse(c *Character, dt float64) {
|
||||
old := *c.View.HousePosition
|
||||
pos := old
|
||||
r := w.Balance.Housing
|
||||
speed := r.WalkSpeed * w.EncumbranceFactor(c)
|
||||
// Small substeps prevent tunneling through narrow furniture on a delayed tick.
|
||||
steps := max(1, int(math.Ceil(dt*r.WalkSpeed/.1)))
|
||||
steps := max(1, int(math.Ceil(dt*speed/.1)))
|
||||
step := dt / float64(steps)
|
||||
for range steps {
|
||||
if c.JumpVelocity != 0 || pos.Y > roomGround(room, pos) {
|
||||
@@ -108,12 +112,12 @@ func (w *World) moveHouse(c *Character, dt float64) {
|
||||
c.JumpVelocity = math.Min(0, c.JumpVelocity)
|
||||
}
|
||||
next := pos
|
||||
next.X += c.MoveX * r.WalkSpeed * step
|
||||
next.X += c.MoveX * speed * step
|
||||
if w.HousePositionValid(room, next) {
|
||||
pos.X = next.X
|
||||
}
|
||||
next = pos
|
||||
next.Z += c.MoveZ * r.WalkSpeed * step
|
||||
next.Z += c.MoveZ * speed * step
|
||||
if w.HousePositionValid(room, next) {
|
||||
pos.Z = next.Z
|
||||
}
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
package game
|
||||
|
||||
import (
|
||||
"aeternalis/server/content"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func ValidItemAction(r p.ItemActionRequest) bool {
|
||||
return len(r.ID) >= 32 && len(r.ID) <= 36 && strings.Trim(r.ID, "0123456789abcdef-") == "" && len(r.CharacterID) == 32 && strings.Trim(r.CharacterID, "0123456789abcdef") == "" && len(r.Item) > 0 && len(r.Item) <= 100 && len(r.Target) <= 100 && len(r.Slot) <= 64 && r.Quantity >= 1 && r.Quantity <= 1000 && slices.Contains([]string{"equip", "destroy", "breakdown", "consume", "use"}, r.Op)
|
||||
}
|
||||
|
||||
// Invoked only on a staged world; the store commits the result and replay receipt
|
||||
// together before returning it to the browser.
|
||||
func (w *World) ItemAction(c *Character, r p.ItemActionRequest) (p.ItemActionResult, error) {
|
||||
out := p.ItemActionResult{ID: r.ID, Returned: map[string]int64{}}
|
||||
if !ValidItemAction(r) || c == nil || c.View.Entity.ID != r.CharacterID || !c.Online || c.Sheltered || HouseID(c) != "" || c.View.Entity.State != "alive" || c.View.RemainingSeconds <= 0 || (!w.IsHub() && w.Phase != "gathering" && w.Phase != "cataclysm") {
|
||||
return out, errors.New("character cannot use items")
|
||||
}
|
||||
now := float64(w.now.UnixMilli()) / 1000
|
||||
if now < c.ItemReadyAt {
|
||||
return out, errors.New("item action cooldown")
|
||||
}
|
||||
item := ownedItem(c, r.Item)
|
||||
if item == nil && c.View.Inventory[r.Item] < r.Quantity {
|
||||
return out, errors.New("item not owned in that quantity")
|
||||
}
|
||||
if item != nil && r.Quantity != 1 {
|
||||
return out, errors.New("equipment actions require one instance")
|
||||
}
|
||||
if r.Op != "use" && r.Target != "" || r.Op != "equip" && r.Slot != "" {
|
||||
return out, errors.New("unexpected item target or slot")
|
||||
}
|
||||
var err error
|
||||
switch r.Op {
|
||||
case "equip":
|
||||
if r.Quantity != 1 {
|
||||
return out, errors.New("equip one item")
|
||||
}
|
||||
err = w.equip(c, r.Item, r.Slot)
|
||||
out.Message = "Equipment updated"
|
||||
case "destroy":
|
||||
if item != nil {
|
||||
if item.HouseID != nil {
|
||||
return out, errors.New("house keys require the three-second key destruction action")
|
||||
}
|
||||
w.removeOwnedItem(c, item.ID)
|
||||
} else {
|
||||
TakeStack(c, r.Item, r.Quantity)
|
||||
}
|
||||
out.Message = "Item destroyed"
|
||||
case "breakdown":
|
||||
if item == nil {
|
||||
return out, errors.New("only equipment can be broken down")
|
||||
}
|
||||
err = w.breakdown(c, *item, &out)
|
||||
case "consume", "use":
|
||||
if r.Quantity != 1 {
|
||||
return out, errors.New("use one item at a time")
|
||||
}
|
||||
err = w.useItem(c, r.Item, r.Target, r.Op == "consume")
|
||||
out.Message = "Item used"
|
||||
}
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
c.ItemReadyAt = now + w.Balance.Inventory.ActionCooldown
|
||||
w.RefreshStats(c)
|
||||
c.Message = out.Message
|
||||
w.dirty = true
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (w *World) removeOwnedItem(c *Character, id string) {
|
||||
c.View.Items = slices.DeleteFunc(c.View.Items, func(i p.ItemInstance) bool { return i.ID == id })
|
||||
for slot, item := range c.View.Equipment {
|
||||
if item == id {
|
||||
delete(c.View.Equipment, slot)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *World) breakdownRecipe(item p.ItemInstance) *content.CraftRecipe {
|
||||
if item.HouseID != nil || item.Furniture != nil || w.Balance.Crafting == nil {
|
||||
return nil
|
||||
}
|
||||
if item.Provenance != nil {
|
||||
for _, list := range [][]content.CraftRecipe{w.Balance.Crafting.Recipes, w.Balance.Crafting.RecipeHistory} {
|
||||
for _, r := range list {
|
||||
if r.ID == item.Provenance.RecipeID && r.Revision == item.Provenance.RecipeRevision && r.Outputs[item.DefinitionID] > 0 {
|
||||
copy := r
|
||||
return ©
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil // Never substitute a later recipe revision for the original.
|
||||
}
|
||||
var found *content.CraftRecipe
|
||||
for _, r := range w.Balance.Crafting.Recipes {
|
||||
if r.Outputs[item.DefinitionID] > 0 {
|
||||
if found != nil {
|
||||
return nil
|
||||
}
|
||||
copy := r
|
||||
found = ©
|
||||
}
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
func (w *World) breakdown(c *Character, item p.ItemInstance, out *p.ItemActionResult) error {
|
||||
r := w.breakdownRecipe(item)
|
||||
if r == nil {
|
||||
return errors.New("no unambiguous original recipe is available for this item")
|
||||
}
|
||||
profession := r.Profession
|
||||
if item.Slot == "weapon" {
|
||||
profession = "weapon_smithing"
|
||||
} else if slices.Contains([]string{"helmet", "mask", "chest", "shoulders", "pants", "boots", "gloves", "cape"}, item.Slot) {
|
||||
profession = "armor_making"
|
||||
}
|
||||
w.refreshCrafting(c)
|
||||
level := c.View.Crafting[profession].Level
|
||||
if level < 1 {
|
||||
return errors.New("breakdown profession unavailable")
|
||||
}
|
||||
rules := w.Balance.Inventory
|
||||
gap := float64(level - max(r.Level, item.Requirements.Level))
|
||||
rate := rules.BreakdownBase
|
||||
if gap < 0 {
|
||||
rate *= math.Exp(gap / rules.BreakdownLevelScale)
|
||||
} else {
|
||||
rate += (rules.BreakdownMax - rate) * (1 - math.Exp(-gap/rules.BreakdownLevelScale))
|
||||
}
|
||||
units := int64(0)
|
||||
for _, n := range r.Outputs {
|
||||
units += n
|
||||
}
|
||||
if units < 1 {
|
||||
return errors.New("invalid original recipe")
|
||||
}
|
||||
for id, n := range r.Inputs {
|
||||
// Divide by the complete output batch: breaking down each output cannot
|
||||
// multiply the batch's inputs. Return material stacks only.
|
||||
if slices.ContainsFunc(w.Balance.Items, func(i content.ItemDefinition) bool { return i.ID == id }) {
|
||||
return errors.New("equipment ingredients cannot be recovered by breakdown")
|
||||
}
|
||||
amount := int64(math.Floor(float64(n) * rate / 100 / float64(units)))
|
||||
if amount > 0 {
|
||||
if c.View.Inventory[id] > math.MaxInt64-amount {
|
||||
return errors.New("inventory overflow")
|
||||
}
|
||||
out.Returned[id] = amount
|
||||
}
|
||||
}
|
||||
if len(c.View.DiscoveredRecipes) >= 512 {
|
||||
if _, ok := c.View.DiscoveredRecipes[r.ID]; !ok {
|
||||
return errors.New("recipe discovery capacity reached")
|
||||
}
|
||||
}
|
||||
w.removeOwnedItem(c, item.ID)
|
||||
for id, n := range out.Returned {
|
||||
c.View.Inventory[id] += n
|
||||
}
|
||||
if w.roll(rules.RecipeChance) {
|
||||
old, known := c.View.DiscoveredRecipes[r.ID]
|
||||
if !known || old.Recipe.Revision < r.Revision {
|
||||
raw, _ := json.Marshal(r)
|
||||
var recipe p.CraftRecipe
|
||||
_ = json.Unmarshal(raw, &recipe)
|
||||
d := p.KnownRecipe{Recipe: recipe, DiscoveredAt: float64(w.now.UnixMilli()) / 1000}
|
||||
c.View.DiscoveredRecipes[r.ID] = d
|
||||
out.Recipe = &d
|
||||
}
|
||||
}
|
||||
out.Message = fmt.Sprintf("Broke down %s (%.1f%% recovery, rounded down)", item.Name, rate)
|
||||
if out.Recipe != nil {
|
||||
out.Message += "; recipe discovered"
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *World) useItem(c *Character, id, target string, consume bool) error {
|
||||
if target == "" || consume {
|
||||
target = c.View.Entity.ID
|
||||
}
|
||||
if c.View.Inventory[id] < 1 {
|
||||
return errors.New("this item has no supported use effect")
|
||||
}
|
||||
healing := float64(0)
|
||||
if id == "bandage" {
|
||||
healing = w.Balance.BandageHealing
|
||||
}
|
||||
for _, definition := range w.Balance.Gathering.Consumables {
|
||||
if definition.ID != id || definition.UseEffect == nil {
|
||||
continue
|
||||
}
|
||||
effect := definition.UseEffect
|
||||
if effect.Kind == "heal" {
|
||||
healing = effect.Amount
|
||||
}
|
||||
if effect.Kind == "weapon-coating" {
|
||||
weapon := ownedItem(c, target)
|
||||
if consume || weapon == nil || weapon.Slot != "weapon" || weapon.Furniture != nil || weapon.HouseID != nil || (weapon.Attack != nil && weapon.Attack.Effect != "damage") {
|
||||
return errors.New("select one of your damage weapons to apply this coating")
|
||||
}
|
||||
TakeStack(c, id, 1)
|
||||
weapon.Coating = &p.WeaponCoating{Source: id, Name: definition.Name, ExpiresAt: float64(w.now.UnixMilli())/1000 + definition.Seconds, Damage: effect.Amount}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if healing > 0 {
|
||||
var entity *p.Entity
|
||||
if other := w.Characters[target]; other != nil && other.Online && !other.Sheltered && HouseID(other) == "" && other.View.Entity.State == "alive" {
|
||||
entity = &other.View.Entity
|
||||
}
|
||||
if mob := w.Mobs[target]; mob != nil && mob.Entity.HP > 0 && !w.IsHub() {
|
||||
entity = &mob.Entity
|
||||
}
|
||||
if entity == nil || entity.HP >= entity.MaxHP {
|
||||
return errors.New("target cannot be healed")
|
||||
}
|
||||
if length3(body(c.View.Entity.Position), body(entity.Position)) > w.Balance.GatherRange {
|
||||
return errors.New("target out of reach")
|
||||
}
|
||||
if _, blocked := w.combatLine(body(c.View.Entity.Position), body(entity.Position), ""); blocked {
|
||||
return errors.New("target obstructed")
|
||||
}
|
||||
TakeStack(c, id, 1)
|
||||
entity.HP = math.Min(entity.MaxHP, entity.HP+healing)
|
||||
return nil
|
||||
}
|
||||
if target != c.View.Entity.ID {
|
||||
return errors.New("this item can only be used on yourself")
|
||||
}
|
||||
return w.consumeGathering(c, id)
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
package game
|
||||
|
||||
import (
|
||||
"aeternalis/server/content"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"encoding/json"
|
||||
"math"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func itemRequest(c *Character, op, item string) p.ItemActionRequest {
|
||||
return p.ItemActionRequest{ID: ID(), CharacterID: c.View.Entity.ID, Op: op, Item: item, Quantity: 1}
|
||||
}
|
||||
|
||||
func TestDestroyConsumesCraftedStackWithoutLosingRemainingProvenance(t *testing.T) {
|
||||
w, c := fixture(t)
|
||||
provenance := p.CraftProvenance{CharacterID: c.View.Entity.ID, CrafterName: c.View.Entity.Name, WorldID: w.ID, RecipeID: "recipe_bandage", RecipeRevision: 1, Profession: "alchemist", Level: 1}
|
||||
c.View.Inventory["bandage"] = 3
|
||||
c.View.CraftedStacks = []p.CraftedStack{{ID: ID(), Item: "bandage", Quantity: 3, Provenance: provenance}}
|
||||
req := itemRequest(c, "destroy", "bandage")
|
||||
req.Quantity = 2
|
||||
for _, mode := range []string{"offline", "sheltered", "dead", "capped"} {
|
||||
c.Online = true
|
||||
c.Sheltered = false
|
||||
c.View.Entity.State = "alive"
|
||||
c.View.RemainingSeconds = 100
|
||||
switch mode {
|
||||
case "offline":
|
||||
c.Online = false
|
||||
case "sheltered":
|
||||
c.Sheltered = true
|
||||
case "dead":
|
||||
c.View.Entity.State = "dead"
|
||||
case "capped":
|
||||
c.View.RemainingSeconds = 0
|
||||
}
|
||||
if _, err := w.ItemAction(c, req); err == nil || c.View.Inventory["bandage"] != 3 {
|
||||
t.Fatalf("accepted %s destruction", mode)
|
||||
}
|
||||
}
|
||||
c.Online = true
|
||||
c.Sheltered = false
|
||||
c.View.Entity.State = "alive"
|
||||
c.View.RemainingSeconds = 100
|
||||
if _, err := w.ItemAction(c, req); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.View.Inventory["bandage"] != 1 || len(c.View.CraftedStacks) != 1 || c.View.CraftedStacks[0].Quantity != 1 || c.View.CraftedStacks[0].Provenance != provenance {
|
||||
t.Fatal("destroy corrupted retained crafted stack")
|
||||
}
|
||||
req = itemRequest(c, "destroy", "bandage")
|
||||
req.Quantity = 2
|
||||
c.ItemReadyAt = 0
|
||||
if _, err := w.ItemAction(c, req); err == nil || c.View.Inventory["bandage"] != 1 {
|
||||
t.Fatal("destroyed more than owned")
|
||||
}
|
||||
w.Balance.Inventory = nil
|
||||
raw, _ := json.Marshal(w)
|
||||
var old World
|
||||
_ = json.Unmarshal(raw, &old)
|
||||
if err := old.Restore(w.now); err != nil || old.Balance.Inventory == nil || old.Balance.Inventory.StopWeightRatio != 2 {
|
||||
t.Fatal("old snapshot missing inventory migration", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEncumbranceMovementRecoveryAndVictory(t *testing.T) {
|
||||
w, c := fixture(t)
|
||||
c.View.Inventory = map[string]int64{}
|
||||
c.View.Items = nil
|
||||
w.RefreshStats(c)
|
||||
capacity := c.View.Stats["carryCapacity"].Final
|
||||
for _, tt := range []struct{ ratio, factor float64 }{{0, 1}, {1, 1}, {1.1, .99}, {1.5, .75}, {2, 0}, {3, 0}} {
|
||||
item := testGear("weight", "helmet")
|
||||
item.Weight = capacity * tt.ratio
|
||||
c.View.Items = []p.ItemInstance{item}
|
||||
w.RefreshStats(c)
|
||||
if math.Abs(w.playerSpeed(c)/c.View.Stats["moveSpeed"].Final-tt.factor) > 1e-8 || math.Abs(*c.View.MovementFactor-tt.factor) > 1e-8 {
|
||||
t.Fatalf("wrong movement at %.1fx capacity", tt.ratio)
|
||||
}
|
||||
}
|
||||
before := c.View.Entity.Position
|
||||
c.MoveX = 1
|
||||
w.moveCharacter(c, .1)
|
||||
if c.View.Entity.Position.X != before.X || w.jump(c) == nil {
|
||||
t.Fatal("immobilized player moved or jumped")
|
||||
}
|
||||
w.Kind = "hub"
|
||||
w.Phase = "hub"
|
||||
house := ID()
|
||||
pos := p.Vec3{}
|
||||
c.View.HouseID = &house
|
||||
c.View.HousePosition = &pos
|
||||
c.HouseRoom = &p.HouseScene{ID: house, Size: 20}
|
||||
c.LastMove = w.now
|
||||
w.moveHouse(c, .1)
|
||||
if c.View.HousePosition.X != 0 || w.houseIntent(c, p.Intent{Op: "jump"}) == nil {
|
||||
t.Fatal("house bypassed encumbrance")
|
||||
}
|
||||
c.View.HouseID = nil
|
||||
c.View.HousePosition = nil
|
||||
c.HouseRoom = nil
|
||||
w.Kind = "survival"
|
||||
w.Phase = "won"
|
||||
c.View.Entity.State = "eligible"
|
||||
if err := w.Intent(c.View.Entity.ID, p.Intent{Seq: 1, Op: "drop", Target: "weight"}); err != nil {
|
||||
t.Fatal("winner cannot shed weight to reach portal", err)
|
||||
}
|
||||
if w.EncumbranceFactor(c) != 1 {
|
||||
t.Fatal("dropping weight did not restore movement")
|
||||
}
|
||||
}
|
||||
|
||||
func TestItemActionsRejectWithoutConsumptionAndHealTargets(t *testing.T) {
|
||||
w, c := fixture(t)
|
||||
c.View.Inventory["bandage"] = 5
|
||||
other, err := w.Join("other", "Other")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = w.Connect(other.View.Entity.ID)
|
||||
other.View.Entity.Position = c.View.Entity.Position
|
||||
other.View.Entity.HP = 1
|
||||
req := itemRequest(c, "use", "bandage")
|
||||
req.Target = other.View.Entity.ID
|
||||
for _, mode := range []string{"far", "dead", "sheltered", "house", "full"} {
|
||||
other.View.Entity.Position = c.View.Entity.Position
|
||||
other.View.Entity.State = "alive"
|
||||
other.Sheltered = false
|
||||
other.View.HouseID = nil
|
||||
other.View.Entity.HP = 1
|
||||
switch mode {
|
||||
case "far":
|
||||
other.View.Entity.Position.X += 100
|
||||
case "dead":
|
||||
other.View.Entity.State = "dead"
|
||||
case "sheltered":
|
||||
other.Sheltered = true
|
||||
case "house":
|
||||
other.View.HouseID = stringPtr(ID())
|
||||
case "full":
|
||||
other.View.Entity.HP = other.View.Entity.MaxHP
|
||||
}
|
||||
if _, err = w.ItemAction(c, req); err == nil || c.View.Inventory["bandage"] != 5 {
|
||||
t.Fatalf("accepted invalid healing target %s", mode)
|
||||
}
|
||||
}
|
||||
other.View.Entity.HP = 1
|
||||
if _, err = w.ItemAction(c, req); err != nil || other.View.Entity.HP != math.Min(other.View.Entity.MaxHP, 1+w.Balance.BandageHealing) || c.View.Inventory["bandage"] != 4 {
|
||||
t.Fatal("targeted healing failed", err)
|
||||
}
|
||||
if _, err = w.ItemAction(c, req); err == nil {
|
||||
t.Fatal("item cooldown bypassed")
|
||||
}
|
||||
w.now = w.now.Add(2 * time.Second)
|
||||
mob := &Mob{Entity: p.Entity{ID: "heal-target", Kind: "mob", State: "alive", HP: 1, MaxHP: 100, Position: c.View.Entity.Position}}
|
||||
w.Mobs[mob.Entity.ID] = mob
|
||||
req.Target = mob.Entity.ID
|
||||
if _, err = w.ItemAction(c, req); err != nil || mob.Entity.HP <= 1 {
|
||||
t.Fatal("mob healing failed", err)
|
||||
}
|
||||
w.now = w.now.Add(2 * time.Second)
|
||||
key := testGear("key", "bag")
|
||||
key.HouseID = stringPtr(ID())
|
||||
c.View.Items = append(c.View.Items, key)
|
||||
if _, err = w.ItemAction(c, itemRequest(c, "destroy", key.ID)); err == nil || ownedItem(c, key.ID) == nil {
|
||||
t.Fatal("generic destruction bypassed key timer")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBreakdownOriginalRecipeBatchAndDiscovery(t *testing.T) {
|
||||
w, c := fixture(t)
|
||||
c.View.Inventory = map[string]int64{}
|
||||
old := content.CraftRecipe{ID: "original", Revision: 1, Name: "Old spear", Profession: "weapon_smithing", Level: 1, XP: 20, Inputs: map[string]int64{"wood": 100, "ore": 20}, Outputs: map[string]int64{"spear": 2}}
|
||||
current := old
|
||||
current.Revision = 2
|
||||
current.Inputs = map[string]int64{"herb": 100}
|
||||
w.Balance.Crafting.RecipeHistory = []content.CraftRecipe{old}
|
||||
w.Balance.Crafting.Recipes = []content.CraftRecipe{current}
|
||||
item := testGear("old-spear", "weapon")
|
||||
item.DefinitionID = "spear"
|
||||
item.Provenance = &p.CraftProvenance{CharacterID: c.View.Entity.ID, CrafterName: c.View.Entity.Name, WorldID: w.ID, Profession: old.Profession, Level: 1, RecipeID: old.ID, RecipeRevision: 1}
|
||||
c.View.Items = []p.ItemInstance{item}
|
||||
c.View.DiscoveredRecipes = map[string]p.KnownRecipe{}
|
||||
// Find a deterministic success for the actual 0.01% boundary, not a modified rule.
|
||||
for w.randomUnit() >= .0001 {
|
||||
}
|
||||
w.RandomCounter--
|
||||
result, err := w.ItemAction(c, itemRequest(c, "breakdown", item.ID))
|
||||
if err != nil || c.View.Inventory["wood"] != 12 || c.View.Inventory["ore"] != 2 || c.View.Inventory["herb"] != 0 || len(c.View.Items) != 0 {
|
||||
t.Fatal("breakdown did not use original recipe divided by output batch", result, err)
|
||||
}
|
||||
if result.Recipe == nil || result.Recipe.Recipe.Revision != 1 || c.View.Crafting["weapon_smithing"].XP != 0 || c.View.Experience != 0 {
|
||||
t.Fatal("wrong discovery or unexpected experience")
|
||||
}
|
||||
w.now = w.now.Add(2 * time.Second)
|
||||
c.View.Items = []p.ItemInstance{item}
|
||||
w.Balance.Crafting.RecipeHistory = nil
|
||||
if _, err = w.ItemAction(c, itemRequest(c, "breakdown", item.ID)); err == nil || len(c.View.Items) != 1 {
|
||||
t.Fatal("missing historical recipe substituted current revision")
|
||||
}
|
||||
// In a hub, high crafting skill raises recovery but never awards XP.
|
||||
w.Kind = "hub"
|
||||
w.Phase = "hub"
|
||||
w.Balance.Crafting.RecipeHistory = []content.CraftRecipe{old}
|
||||
cp := c.View.Crafting["weapon_smithing"]
|
||||
cp.XP = 1000000
|
||||
c.View.Crafting[cp.ID] = cp
|
||||
result, err = w.ItemAction(c, itemRequest(c, "breakdown", item.ID))
|
||||
if err != nil || result.Returned["wood"] <= 12 || result.Returned["wood"] >= 38 || c.View.Crafting[cp.ID].XP != cp.XP {
|
||||
t.Fatal("higher skill recovery or hub XP changed", result, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsumableCoatingOwnershipExpiryAndRestore(t *testing.T) {
|
||||
w, c := fixture(t)
|
||||
definition := content.GatheringConsumable{ID: "poison", Name: "Weapon poison", Seconds: 10, UseEffect: &content.ItemUseEffect{Kind: "weapon-coating", Amount: 7}}
|
||||
w.Balance.Gathering.Consumables = append(w.Balance.Gathering.Consumables, definition)
|
||||
c.View.Inventory[definition.ID] = 2
|
||||
weapon := testGear("coated", "weapon")
|
||||
c.View.Items = append(c.View.Items, weapon)
|
||||
req := itemRequest(c, "use", definition.ID)
|
||||
req.Target = "not-owned"
|
||||
if _, err := w.ItemAction(c, req); err == nil || c.View.Inventory[definition.ID] != 2 {
|
||||
t.Fatal("coated unowned weapon")
|
||||
}
|
||||
req.Target = weapon.ID
|
||||
if _, err := w.ItemAction(c, req); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
coating := ownedItem(c, weapon.ID).Coating
|
||||
if coating == nil || coating.Damage != 7 || c.View.Inventory[definition.ID] != 1 {
|
||||
t.Fatal("coating was not copied onto exact item")
|
||||
}
|
||||
if err := w.consumeGathering(c, definition.ID); err == nil {
|
||||
t.Fatal("legacy consume bypassed target requirement")
|
||||
}
|
||||
raw, _ := json.Marshal(w)
|
||||
var restored World
|
||||
_ = json.Unmarshal(raw, &restored)
|
||||
if err := restored.Restore(w.now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(ownedItem(restored.Characters[c.View.Entity.ID], weapon.ID).Coating, coating) {
|
||||
t.Fatal("restore lost coating")
|
||||
}
|
||||
_ = w.equip(c, weapon.ID, "weapon")
|
||||
w.Balance.CriticalMultiplier = 1
|
||||
mob := &Mob{Entity: p.Entity{ID: "damage-target", Kind: "mob", State: "alive", HP: 1000, MaxHP: 1000, Position: c.View.Entity.Position}}
|
||||
w.Mobs[mob.Entity.ID] = mob
|
||||
w.now = w.now.Add(2 * time.Second)
|
||||
if err := w.attack(c, mob.Entity.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
coatedDamage := 1000 - mob.Entity.HP
|
||||
w.now = w.now.Add(20 * time.Second)
|
||||
mob.Entity.HP = 1000
|
||||
if err := w.attack(c, mob.Entity.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
normalDamage := 1000 - mob.Entity.HP
|
||||
if math.Abs(coatedDamage-normalDamage-7) > 1e-8 {
|
||||
t.Fatal("coating damage did not expire", coatedDamage, normalDamage)
|
||||
}
|
||||
}
|
||||
@@ -198,5 +198,18 @@ func (c *Character) titleEffects() p.TitleEffects {
|
||||
}
|
||||
|
||||
func (w *World) playerSpeed(c *Character) float64 {
|
||||
return c.View.Stats["moveSpeed"].Final
|
||||
return c.View.Stats["moveSpeed"].Final * w.EncumbranceFactor(c)
|
||||
}
|
||||
|
||||
// Apply after all speed/capacity modifiers, so gear cannot override immobilization.
|
||||
func (w *World) EncumbranceFactor(c *Character) float64 {
|
||||
capacity, weight := c.View.Stats["carryCapacity"].Final, c.View.CarryWeight
|
||||
if weight <= capacity {
|
||||
return 1
|
||||
}
|
||||
if capacity <= 0 {
|
||||
return 0
|
||||
}
|
||||
excess := (weight/capacity - 1) / (w.Balance.Inventory.StopWeightRatio - 1)
|
||||
return math.Max(0, 1-math.Pow(excess, w.Balance.Inventory.SlowdownExponent))
|
||||
}
|
||||
|
||||
@@ -105,6 +105,8 @@ func (w *World) RefreshStats(c *Character) {
|
||||
for _, n := range c.View.Inventory {
|
||||
c.View.CarryWeight += float64(n)
|
||||
}
|
||||
factor := w.EncumbranceFactor(c)
|
||||
c.View.MovementFactor = &factor
|
||||
}
|
||||
func (w *World) initializeStats(c *Character) error {
|
||||
newResources := c.View.Stats == nil
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
)
|
||||
|
||||
type Character struct {
|
||||
ItemReadyAt float64 `json:"itemReadyAt"`
|
||||
HouseRoom *p.HouseScene `json:"-"`
|
||||
XPCurveVersion int `json:"xpCurveVersion"`
|
||||
PendingCast *PendingCast `json:"pendingCast,omitempty"`
|
||||
@@ -124,6 +125,17 @@ func New(id string, seed int64, now time.Time, b content.Balance) *World {
|
||||
return w
|
||||
}
|
||||
func (w *World) Restore(now time.Time) error {
|
||||
if w.Balance.Inventory == nil {
|
||||
defaults, err := content.Load()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
w.Balance.Inventory = defaults.Inventory
|
||||
w.dirty = true
|
||||
}
|
||||
if err := w.Balance.Inventory.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
if w.Kind == "" {
|
||||
w.Kind = "survival"
|
||||
}
|
||||
@@ -533,7 +545,7 @@ func (w *World) Intent(id string, i p.Intent) error {
|
||||
c.Sheltered = false
|
||||
w.dirty = true
|
||||
}
|
||||
if w.Phase == "won" && i.Op != "move" && i.Op != "jump" && i.Op != "return" && i.Op != "learn" {
|
||||
if w.Phase == "won" && i.Op != "move" && i.Op != "jump" && i.Op != "return" && i.Op != "learn" && i.Op != "drop" {
|
||||
return errors.New("use the victory portal to continue")
|
||||
}
|
||||
if w.IsHub() && (i.Op == "attack" || i.Op == "gather") {
|
||||
|
||||
@@ -2,16 +2,18 @@
|
||||
package protocol
|
||||
|
||||
type Protocol struct {
|
||||
Catalog *ContentCatalog `json:"catalog,omitempty"`
|
||||
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"`
|
||||
HouseRequest *HouseRequest `json:"houseRequest,omitempty"`
|
||||
HouseState *HouseState `json:"houseState,omitempty"`
|
||||
Intent Intent `json:"intent"`
|
||||
Snapshot Snapshot `json:"snapshot"`
|
||||
Catalog *ContentCatalog `json:"catalog,omitempty"`
|
||||
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"`
|
||||
HouseRequest *HouseRequest `json:"houseRequest,omitempty"`
|
||||
HouseState *HouseState `json:"houseState,omitempty"`
|
||||
Intent Intent `json:"intent"`
|
||||
ItemActionRequest *ItemActionRequest `json:"itemActionRequest,omitempty"`
|
||||
ItemActionResult *ItemActionResult `json:"itemActionResult,omitempty"`
|
||||
Snapshot Snapshot `json:"snapshot"`
|
||||
}
|
||||
|
||||
type ContentCatalog struct {
|
||||
@@ -125,10 +127,11 @@ type MobSpawn struct {
|
||||
}
|
||||
|
||||
type CraftingContent struct {
|
||||
Materials []CraftMaterial `json:"materials"`
|
||||
Professions []GatheringSkill `json:"professions"`
|
||||
Recipes []CraftRecipe `json:"recipes"`
|
||||
Rules CraftRules `json:"rules"`
|
||||
Materials []CraftMaterial `json:"materials"`
|
||||
Professions []GatheringSkill `json:"professions"`
|
||||
RecipeHistory []CraftRecipe `json:"recipeHistory,omitempty"`
|
||||
Recipes []CraftRecipe `json:"recipes"`
|
||||
Rules CraftRules `json:"rules"`
|
||||
}
|
||||
|
||||
type CraftMaterial struct {
|
||||
@@ -212,6 +215,12 @@ type GatheringConsumable struct {
|
||||
Modifiers []StatModifier `json:"modifiers"`
|
||||
Name string `json:"name"`
|
||||
Seconds float64 `json:"seconds"`
|
||||
UseEffect *ItemUseEffect `json:"useEffect,omitempty"`
|
||||
}
|
||||
|
||||
type ItemUseEffect struct {
|
||||
Amount float64 `json:"amount"`
|
||||
Kind string `json:"kind"`
|
||||
}
|
||||
|
||||
type ResourceDefinition struct {
|
||||
@@ -409,6 +418,7 @@ type GatheringConsumableDraft struct {
|
||||
Modifiers []StatModifier `json:"modifiers"`
|
||||
Name string `json:"name"`
|
||||
Seconds float64 `json:"seconds"`
|
||||
UseEffect *ItemUseEffect `json:"useEffect,omitempty"`
|
||||
}
|
||||
|
||||
type CraftMaterialDraft struct {
|
||||
@@ -688,6 +698,7 @@ type CraftProvenance struct {
|
||||
|
||||
type ItemInstance struct {
|
||||
Attack *CombatAttack `json:"attack,omitempty"`
|
||||
Coating *WeaponCoating `json:"coating,omitempty"`
|
||||
DefinitionID string `json:"definitionId"`
|
||||
Description string `json:"description"`
|
||||
Equippable bool `json:"equippable"`
|
||||
@@ -704,6 +715,13 @@ type ItemInstance struct {
|
||||
Weight float64 `json:"weight"`
|
||||
}
|
||||
|
||||
type WeaponCoating struct {
|
||||
Damage float64 `json:"damage"`
|
||||
ExpiresAt float64 `json:"expiresAt"`
|
||||
Name string `json:"name"`
|
||||
Source string `json:"source"`
|
||||
}
|
||||
|
||||
type HouseFurniture struct {
|
||||
Contents HouseInventory `json:"contents"`
|
||||
Item ItemInstance `json:"item"`
|
||||
@@ -720,6 +738,23 @@ type Intent struct {
|
||||
Z float64 `json:"z"`
|
||||
}
|
||||
|
||||
type ItemActionRequest struct {
|
||||
CharacterID string `json:"characterId"`
|
||||
ID string `json:"id"`
|
||||
Item string `json:"item"`
|
||||
Op string `json:"op"`
|
||||
Quantity int64 `json:"quantity"`
|
||||
Slot string `json:"slot"`
|
||||
Target string `json:"target"`
|
||||
}
|
||||
|
||||
type ItemActionResult struct {
|
||||
ID string `json:"id"`
|
||||
Message string `json:"message"`
|
||||
Recipe *KnownRecipe `json:"recipe,omitempty"`
|
||||
Returned map[string]int64 `json:"returned"`
|
||||
}
|
||||
|
||||
type Snapshot struct {
|
||||
ChunkKeys []string `json:"chunkKeys"`
|
||||
Chunks []Chunk `json:"chunks"`
|
||||
@@ -815,6 +850,7 @@ type Character struct {
|
||||
Level int64 `json:"level"`
|
||||
Mana float64 `json:"mana"`
|
||||
ManaChoices int64 `json:"manaChoices"`
|
||||
MovementFactor *float64 `json:"movementFactor,omitempty"`
|
||||
PendingVitalChoices int64 `json:"pendingVitalChoices"`
|
||||
PlayedSeconds float64 `json:"playedSeconds"`
|
||||
Powers map[string]LearnedPower `json:"powers,omitempty"`
|
||||
|
||||
@@ -186,6 +186,7 @@ func buildCatalog(c content.Catalog, change CatalogChange) (content.Catalog, str
|
||||
}
|
||||
v.ID = c.Crafting.Recipes[i].ID
|
||||
v.Revision = c.Crafting.Recipes[i].Revision + 1
|
||||
c.Crafting.RecipeHistory = append(slices.Clone(c.Crafting.RecipeHistory), c.Crafting.Recipes[i])
|
||||
c.Crafting.Recipes = slices.Clone(c.Crafting.Recipes)
|
||||
c.Crafting.Recipes[i] = v
|
||||
} else {
|
||||
|
||||
@@ -208,6 +208,9 @@ func TestCraftRecipeRevision(t *testing.T) {
|
||||
t.Fatal(e)
|
||||
}
|
||||
got := revised.Crafting.Recipes[len(revised.Crafting.Recipes)-1]
|
||||
if len(revised.Crafting.RecipeHistory) != 1 || !reflect.DeepEqual(revised.Crafting.RecipeHistory[0], made) || len(firstCatalog.Crafting.RecipeHistory) != 0 {
|
||||
t.Fatal("recipe publication lost the immutable salvage revision or mutated the old catalog")
|
||||
}
|
||||
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")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"aeternalis/server/internal/game"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
var ErrItemAction = errors.New("item action rejected")
|
||||
|
||||
// Namespaced IDs share the existing durable action receipt transaction without
|
||||
// colliding with crafting attempts. Store full requests to reject changed retries.
|
||||
func (l *Lease) ItemAction(ctx context.Context, live *game.World, account string, req p.ItemActionRequest) (p.ItemActionResult, error) {
|
||||
fail := func(message string) (p.ItemActionResult, error) {
|
||||
return p.ItemActionResult{}, fmt.Errorf("%w: %s", ErrItemAction, message)
|
||||
}
|
||||
if !game.ValidItemAction(req) {
|
||||
return fail("invalid request")
|
||||
}
|
||||
id := "item:" + req.ID
|
||||
request, _ := json.Marshal(req)
|
||||
var previous, resultJSON string
|
||||
err := l.DB.sql.QueryRowContext(ctx, l.DB.q(`SELECT request_json,result_json FROM craft_receipts WHERE account_id=? AND id=?`), account, id).Scan(&previous, &resultJSON)
|
||||
if err == nil {
|
||||
if previous != string(request) {
|
||||
return fail("request ID already used for another action")
|
||||
}
|
||||
var result p.ItemActionResult
|
||||
err = json.Unmarshal([]byte(resultJSON), &result)
|
||||
return result, err
|
||||
}
|
||||
if !errors.Is(err, sql.ErrNoRows) {
|
||||
return p.ItemActionResult{}, err
|
||||
}
|
||||
active, err := l.DB.ActiveCharacter(ctx, account)
|
||||
if err != nil {
|
||||
return p.ItemActionResult{}, err
|
||||
}
|
||||
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)
|
||||
for _, c := range staged.Characters {
|
||||
raw, err := json.Marshal(c.View)
|
||||
if err != nil {
|
||||
return p.ItemActionResult{}, err
|
||||
}
|
||||
var view p.Character
|
||||
if err = json.Unmarshal(raw, &view); err != nil {
|
||||
return p.ItemActionResult{}, err
|
||||
}
|
||||
c.View = view
|
||||
}
|
||||
staged.Mobs = make(map[string]*game.Mob, len(live.Mobs))
|
||||
for id, m := range live.Mobs {
|
||||
copy := *m
|
||||
staged.Mobs[id] = ©
|
||||
}
|
||||
result, err := staged.ItemAction(staged.Characters[req.CharacterID], req)
|
||||
if err != nil {
|
||||
return fail(err.Error())
|
||||
}
|
||||
raw, _ := json.Marshal(result)
|
||||
receipt := &craftReceipt{id, account, req.CharacterID, string(request), string(raw)}
|
||||
if err = l.save(ctx, staged, "", nil, "", receipt, nil, nil); err != nil {
|
||||
return p.ItemActionResult{}, err
|
||||
}
|
||||
for id, c := range staged.Characters {
|
||||
*live.Characters[id] = *c
|
||||
}
|
||||
live.Mobs = staged.Mobs
|
||||
live.RandomCounter = staged.RandomCounter
|
||||
live.PendingTitles = nil
|
||||
live.Saved()
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
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 TestItemActionDurability(t *testing.T) {
|
||||
testItemActionDurability(t, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "items.db")))
|
||||
}
|
||||
func TestPostgresItemActionDurability(t *testing.T) {
|
||||
dsn := os.Getenv("TEST_DATABASE_URL")
|
||||
if dsn == "" {
|
||||
t.Skip("TEST_DATABASE_URL not configured")
|
||||
}
|
||||
testItemActionDurability(t, dsn)
|
||||
}
|
||||
func testItemActionDurability(t *testing.T, dsn string) {
|
||||
ctx := context.Background()
|
||||
db, err := Open(ctx, dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
b, err := content.Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
w := game.New("items-"+game.ID(), 1, now, b)
|
||||
lease, _, err := db.Acquire(ctx, w)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c, err := w.Join("items-"+game.ID(), "Owner")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = w.Connect(c.View.Entity.ID)
|
||||
other, err := w.Join("target-"+game.ID(), "Target")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = w.Connect(other.View.Entity.ID)
|
||||
c.View.Inventory["bandage"] = 5
|
||||
other.View.Entity.HP = 1
|
||||
other.View.Entity.Position = c.View.Entity.Position
|
||||
if err = lease.Save(ctx, w, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := p.ItemActionRequest{ID: game.ID(), CharacterID: c.View.Entity.ID, Op: "use", Item: "bandage", Target: other.View.Entity.ID, Quantity: 1}
|
||||
before, _ := json.Marshal(w)
|
||||
stale := *lease
|
||||
stale.Revision--
|
||||
if _, err = stale.ItemAction(ctx, w, c.Account, req); !errors.Is(err, ErrOwnership) {
|
||||
t.Fatal("stale item action not fenced", err)
|
||||
}
|
||||
after, _ := json.Marshal(w)
|
||||
if string(after) != string(before) {
|
||||
t.Fatal("failed save mutated acting player or healing target")
|
||||
}
|
||||
result, err := lease.ItemAction(ctx, w, c.Account, req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.View.Inventory["bandage"] != 4 || other.View.Entity.HP <= 1 || w.Characters[c.View.Entity.ID] != c {
|
||||
t.Fatal("saved result not published to live pointers")
|
||||
}
|
||||
committed, _ := json.Marshal(w)
|
||||
replay, err := lease.ItemAction(ctx, w, c.Account, req)
|
||||
if err != nil || !reflect.DeepEqual(result, replay) {
|
||||
t.Fatal("retry changed result", err)
|
||||
}
|
||||
after, _ = json.Marshal(w)
|
||||
if string(after) != string(committed) {
|
||||
t.Fatal("retry consumed or healed again")
|
||||
}
|
||||
changed := req
|
||||
changed.Quantity = 2
|
||||
if _, err = lease.ItemAction(ctx, w, c.Account, changed); !errors.Is(err, ErrItemAction) {
|
||||
t.Fatal("changed request reused receipt", err)
|
||||
}
|
||||
if _, err = lease.ItemAction(ctx, w, other.Account, req); !errors.Is(err, ErrItemAction) {
|
||||
t.Fatal("other account recovered receipt", err)
|
||||
}
|
||||
if err = lease.Release(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
restored := game.New(w.ID, 1, now, b)
|
||||
lease, raw, err := db.Acquire(ctx, restored)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = json.Unmarshal(raw, restored); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = restored.Restore(now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c = restored.Characters[c.View.Entity.ID]
|
||||
other = restored.Characters[other.View.Entity.ID]
|
||||
if c.View.Inventory["bandage"] != 4 || other.View.Entity.HP <= 1 {
|
||||
t.Fatal("restart lost committed item action")
|
||||
}
|
||||
replay, err = lease.ItemAction(ctx, restored, c.Account, req)
|
||||
if err != nil || !reflect.DeepEqual(result, replay) {
|
||||
t.Fatal("restart lost receipt", err)
|
||||
}
|
||||
_ = restored.Connect(c.View.Entity.ID)
|
||||
c.ItemReadyAt = 0
|
||||
// A saved result remains a receipt after death; replay never reactivates a life.
|
||||
c.View.Entity.State = "dead"
|
||||
if err = lease.Save(ctx, restored, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
replay, err = lease.ItemAction(ctx, restored, c.Account, req)
|
||||
if err != nil || !reflect.DeepEqual(result, replay) || c.View.Entity.State != "dead" {
|
||||
t.Fatal("replay changed dead life", err)
|
||||
}
|
||||
changed = req
|
||||
changed.ID = game.ID()
|
||||
if _, err = lease.ItemAction(ctx, restored, c.Account, changed); !errors.Is(err, ErrItemAction) {
|
||||
t.Fatal("dead life used new action", err)
|
||||
}
|
||||
}
|
||||
@@ -99,6 +99,7 @@ func (h *HTTP) Handler() http.Handler {
|
||||
h.portalRoutes(mux)
|
||||
h.travelRoutes(mux)
|
||||
h.craftingRoutes(mux)
|
||||
h.itemActionRoutes(mux)
|
||||
h.powerRoutes(mux)
|
||||
h.housingRoutes(mux)
|
||||
h.catalogRoutes(mux)
|
||||
|
||||
@@ -142,7 +142,7 @@ func TestHTTPAndSocketSecurity(t *testing.T) {
|
||||
t.Fatal("cross-origin crafting accepted")
|
||||
}
|
||||
}
|
||||
for _, path := range []string{"/api/revive", "/api/revival/consent"} {
|
||||
for _, path := range []string{"/api/revive", "/api/revival/consent", "/api/item-action"} {
|
||||
r := request(path, "https://evil.example", "{}", cookie)
|
||||
r.Body.Close()
|
||||
if r.StatusCode != 403 {
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"aeternalis/server/internal/store"
|
||||
"errors"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func (h *HTTP) itemActionRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("POST /api/item-action", func(w http.ResponseWriter, r *http.Request) {
|
||||
account, err := h.auth.account(r)
|
||||
if err != nil {
|
||||
fail(w, 401, "sign in required")
|
||||
return
|
||||
}
|
||||
var req p.ItemActionRequest
|
||||
if decode(w, r, &req) != nil {
|
||||
fail(w, 400, "invalid item action")
|
||||
return
|
||||
}
|
||||
h.s.mu.Lock()
|
||||
defer h.s.mu.Unlock()
|
||||
if !h.s.ready.Load() {
|
||||
fail(w, 503, "world unavailable")
|
||||
return
|
||||
}
|
||||
if err = h.s.refreshCatalog(r.Context()); err != nil {
|
||||
fail(w, 503, "item catalog unavailable")
|
||||
return
|
||||
}
|
||||
result, err := h.s.lease.ItemAction(r.Context(), h.s.world, account, req)
|
||||
if errors.Is(err, store.ErrItemAction) {
|
||||
fail(w, 409, err.Error())
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.s.ready.Store(false)
|
||||
for _, peer := range h.s.peers {
|
||||
peer.close()
|
||||
}
|
||||
fail(w, 503, "item save unavailable; retry the same action after reconnecting")
|
||||
return
|
||||
}
|
||||
respond(w, 200, result)
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user