Add ranged combat area effects and admin-authored mobs
This commit is contained in:
@@ -1,4 +1,27 @@
|
||||
version: 1
|
||||
combatRules:
|
||||
maxMobs: 512
|
||||
maxProjectiles: 256
|
||||
maxAreas: 64
|
||||
maxTargets: 64
|
||||
maxSlope: 1.2
|
||||
hitRadius: 1.2
|
||||
combat:
|
||||
attacks:
|
||||
- { id: bow_shot, name: Bow shot, description: A straight projectile that can miss., delivery: projectile, effect: damage, stat: rangedDamage, multiplier: 1, range: 45, cooldown: 1, stamina: 2, speed: 35, radius: 0, duration: 0, interval: 1 }
|
||||
- { id: blast_shot, name: Blast shot, description: A projectile with a damage burst., delivery: projectile, effect: damage, stat: rangedDamage, multiplier: 1, range: 35, cooldown: 3, stamina: 8, speed: 25, radius: 6, duration: 0, interval: 1 }
|
||||
- { id: healing_field, name: Healing field, description: A projectile that creates a stationary healing area., delivery: projectile, effect: heal, stat: magicDamage, multiplier: 1, range: 30, cooldown: 8, stamina: 10, speed: 25, radius: 6, duration: 5, interval: 1 }
|
||||
- { id: sentinel_strike, name: Sentinel strike, description: Close range damage., delivery: melee, effect: damage, stat: meleeDamage, multiplier: 1, range: 3, cooldown: 1.8, stamina: 0, speed: 1, radius: 0, duration: 0, interval: 1 }
|
||||
mobs:
|
||||
- { id: ash_guard, name: Ash guard, description: A territorial guardian., model: sentinel, behavior: aggressive, level: 1, hp: 54, damage: 6, defence: 0, speed: 4, aggroRange: 24, leashRange: 160, scalePerDay: 0.1, xp: 50, attackId: sentinel_strike, lootId: common_mob_loot }
|
||||
loot:
|
||||
- id: common_mob_loot
|
||||
name: Common creature loot
|
||||
description: Guaranteed herbs and an independent chance of ore.
|
||||
entries:
|
||||
- { item: herb, amount: 1, chance: 100, group: '', weight: 1 }
|
||||
- { item: ore, amount: 1, chance: 20, group: '', weight: 1 }
|
||||
spawns: []
|
||||
# Provisional milestone 3 tuning. The +20 attempt ceiling is a gameplay rule.
|
||||
gatheringRules:
|
||||
failureBase: 70
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
package content
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
)
|
||||
|
||||
type CombatAttack struct {
|
||||
ID string `json:"id" yaml:"id"`
|
||||
Name string `json:"name" yaml:"name"`
|
||||
Description string `json:"description" yaml:"description"`
|
||||
Delivery string `json:"delivery" yaml:"delivery"`
|
||||
Effect string `json:"effect" yaml:"effect"`
|
||||
Stat string `json:"stat" yaml:"stat"`
|
||||
Multiplier float64 `json:"multiplier" yaml:"multiplier"`
|
||||
Range float64 `json:"range" yaml:"range"`
|
||||
Cooldown float64 `json:"cooldown" yaml:"cooldown"`
|
||||
Stamina float64 `json:"stamina" yaml:"stamina"`
|
||||
Speed float64 `json:"speed" yaml:"speed"`
|
||||
Radius float64 `json:"radius" yaml:"radius"`
|
||||
Duration float64 `json:"duration" yaml:"duration"`
|
||||
Interval float64 `json:"interval" yaml:"interval"`
|
||||
}
|
||||
|
||||
func (a CombatAttack) Validate() error {
|
||||
if !validSetIdentity(a.ID, a.Name, a.Description) || !slices.Contains([]string{"melee", "projectile"}, a.Delivery) || !slices.Contains([]string{"damage", "heal"}, a.Effect) || !slices.Contains([]string{"meleeDamage", "rangedDamage", "magicDamage"}, a.Stat) || !finiteRange(a.Multiplier, .01, 100) || !finiteRange(a.Range, 1, 128) || !finiteRange(a.Cooldown, .1, 120) || !finiteRange(a.Stamina, 0, 10000) || !finiteRange(a.Speed, 1, 100) || !finiteRange(a.Radius, 0, 24) || !finiteRange(a.Duration, 0, 60) || !finiteRange(a.Interval, .2, 60) {
|
||||
return fmt.Errorf("invalid attack %q", a.ID)
|
||||
}
|
||||
if a.Duration > 0 && (a.Radius <= 0 || a.Interval > a.Duration) {
|
||||
return fmt.Errorf("timed areas need radius and interval <= duration")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type LootEntry struct {
|
||||
Item string `json:"item" yaml:"item"`
|
||||
Amount int64 `json:"amount" yaml:"amount"`
|
||||
Chance float64 `json:"chance" yaml:"chance"`
|
||||
Group string `json:"group" yaml:"group"`
|
||||
Weight int64 `json:"weight" yaml:"weight"`
|
||||
}
|
||||
type LootTable struct {
|
||||
ID string `json:"id" yaml:"id"`
|
||||
Name string `json:"name" yaml:"name"`
|
||||
Description string `json:"description" yaml:"description"`
|
||||
Entries []LootEntry `json:"entries" yaml:"entries"`
|
||||
}
|
||||
type MobDefinition struct {
|
||||
ID string `json:"id" yaml:"id"`
|
||||
Name string `json:"name" yaml:"name"`
|
||||
Description string `json:"description" yaml:"description"`
|
||||
Model string `json:"model" yaml:"model"`
|
||||
Behavior string `json:"behavior" yaml:"behavior"`
|
||||
Level int64 `json:"level" yaml:"level"`
|
||||
HP float64 `json:"hp" yaml:"hp"`
|
||||
Damage float64 `json:"damage" yaml:"damage"`
|
||||
Defence float64 `json:"defence" yaml:"defence"`
|
||||
Speed float64 `json:"speed" yaml:"speed"`
|
||||
AggroRange float64 `json:"aggroRange" yaml:"aggroRange"`
|
||||
LeashRange float64 `json:"leashRange" yaml:"leashRange"`
|
||||
ScalePerDay float64 `json:"scalePerDay" yaml:"scalePerDay"`
|
||||
XP int64 `json:"xp" yaml:"xp"`
|
||||
AttackID string `json:"attackId" yaml:"attackId"`
|
||||
LootID string `json:"lootId" yaml:"lootId"`
|
||||
}
|
||||
type MobSpawn struct {
|
||||
ID string `json:"id" yaml:"id"`
|
||||
Name string `json:"name" yaml:"name"`
|
||||
Description string `json:"description" yaml:"description"`
|
||||
MobID string `json:"mobId" yaml:"mobId"`
|
||||
X float64 `json:"x" yaml:"x"`
|
||||
Z float64 `json:"z" yaml:"z"`
|
||||
Radius float64 `json:"radius" yaml:"radius"`
|
||||
Count int64 `json:"count" yaml:"count"`
|
||||
Respawn float64 `json:"respawn" yaml:"respawn"`
|
||||
MinPlayerDistance float64 `json:"minPlayerDistance" yaml:"minPlayerDistance"`
|
||||
Biomes []string `json:"biomes" yaml:"biomes"`
|
||||
}
|
||||
type CombatContent struct {
|
||||
Attacks []CombatAttack `json:"attacks" yaml:"attacks"`
|
||||
Mobs []MobDefinition `json:"mobs" yaml:"mobs"`
|
||||
Loot []LootTable `json:"loot" yaml:"loot"`
|
||||
Spawns []MobSpawn `json:"spawns" yaml:"spawns"`
|
||||
}
|
||||
type CombatRules struct {
|
||||
MaxMobs int `yaml:"maxMobs"`
|
||||
MaxProjectiles int `yaml:"maxProjectiles"`
|
||||
MaxAreas int `yaml:"maxAreas"`
|
||||
MaxTargets int `yaml:"maxTargets"`
|
||||
MaxSlope float64 `yaml:"maxSlope"`
|
||||
HitRadius float64 `yaml:"hitRadius"`
|
||||
}
|
||||
|
||||
func (r CombatRules) Validate() error {
|
||||
if r.MaxMobs < 1 || r.MaxMobs > 2048 || r.MaxProjectiles < 1 || r.MaxProjectiles > 512 || r.MaxAreas < 1 || r.MaxAreas > 128 || r.MaxTargets < 1 || r.MaxTargets > 128 || !finiteRange(r.MaxSlope, .1, 4) || !finiteRange(r.HitRadius, .1, 3) {
|
||||
return fmt.Errorf("invalid combat work limits")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (c Catalog) validateCombat() error {
|
||||
if c.Combat == nil {
|
||||
return nil
|
||||
}
|
||||
v := c.Combat
|
||||
if len(v.Attacks) > 256 || len(v.Mobs) > 256 || len(v.Loot) > 256 || len(v.Spawns) > 256 {
|
||||
return fmt.Errorf("too much combat content")
|
||||
}
|
||||
ids := map[string]bool{}
|
||||
identity := func(id, name, desc string) bool {
|
||||
if ids[id] || !validSetIdentity(id, name, desc) {
|
||||
return false
|
||||
}
|
||||
ids[id] = true
|
||||
return true
|
||||
}
|
||||
attacks, loot, mobs := map[string]bool{}, map[string]bool{}, map[string]bool{}
|
||||
for _, a := range v.Attacks {
|
||||
if !identity(a.ID, a.Name, a.Description) {
|
||||
return fmt.Errorf("duplicate attack")
|
||||
}
|
||||
if err := a.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
attacks[a.ID] = true
|
||||
}
|
||||
items := map[string]bool{}
|
||||
for _, id := range []string{"axe", "flint_and_steel", "fishing_pole", "wood", "ore", "herb", "bandage"} {
|
||||
items[id] = true
|
||||
}
|
||||
for _, i := range c.Items {
|
||||
items[i.ID] = true
|
||||
}
|
||||
if c.Gathering != nil {
|
||||
for _, r := range c.Gathering.Resources {
|
||||
if r.Output == "self" {
|
||||
items[r.ID] = true
|
||||
}
|
||||
}
|
||||
for _, i := range c.Gathering.Consumables {
|
||||
items[i.ID] = true
|
||||
}
|
||||
}
|
||||
for _, l := range v.Loot {
|
||||
if !identity(l.ID, l.Name, l.Description) || len(l.Entries) > 32 {
|
||||
return fmt.Errorf("invalid loot table")
|
||||
}
|
||||
loot[l.ID] = true
|
||||
for _, e := range l.Entries {
|
||||
if !items[e.Item] || e.Amount < 1 || e.Amount > 100 || !finiteRange(e.Chance, 0, 100) || len(e.Group) > 40 || e.Weight < 1 || e.Weight > 10000 {
|
||||
return fmt.Errorf("invalid loot entry")
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, m := range v.Mobs {
|
||||
if !identity(m.ID, m.Name, m.Description) || !slices.Contains([]string{"sentinel", "boss"}, m.Model) || !slices.Contains([]string{"aggressive", "guard", "passive"}, m.Behavior) || m.Level < 1 || m.Level > 10000 || !finiteRange(m.HP, 1, 1000000) || !finiteRange(m.Damage, 0, 100000) || !finiteRange(m.Defence, 0, 100000) || !finiteRange(m.Speed, .1, 30) || !finiteRange(m.AggroRange, 1, 128) || !finiteRange(m.LeashRange, m.AggroRange, 512) || !finiteRange(m.ScalePerDay, 0, 10) || m.XP < 0 || m.XP > 1000000000 || !attacks[m.AttackID] || (m.LootID != "" && !loot[m.LootID]) {
|
||||
return fmt.Errorf("invalid mob %q or missing attack/loot reference", m.ID)
|
||||
}
|
||||
mobs[m.ID] = true
|
||||
}
|
||||
for _, s := range v.Spawns {
|
||||
if !identity(s.ID, s.Name, s.Description) || !mobs[s.MobID] || !finiteRange(s.X, -100000, 100000) || !finiteRange(s.Z, -100000, 100000) || !finiteRange(s.Radius, 0, 512) || s.Count < 1 || s.Count > 32 || !finiteRange(s.Respawn, 1, 604800) || !finiteRange(s.MinPlayerDistance, 0, 128) || len(s.Biomes) > 32 {
|
||||
return fmt.Errorf("invalid spawn")
|
||||
}
|
||||
for _, id := range s.Biomes {
|
||||
if c.Gathering == nil || !slices.ContainsFunc(c.Gathering.Biomes, func(b BiomeDefinition) bool { return b.ID == id }) {
|
||||
return fmt.Errorf("unknown spawn biome")
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, i := range c.Items {
|
||||
if i.AttackID != "" && (!attacks[i.AttackID] || i.Slot != "weapon") {
|
||||
return fmt.Errorf("weapon references unknown attack")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -19,6 +19,8 @@ type Recipe struct {
|
||||
}
|
||||
|
||||
type Balance struct {
|
||||
Combat *CombatContent `yaml:"combat"`
|
||||
CombatRules *CombatRules `yaml:"combatRules"`
|
||||
Gathering *GatheringContent `yaml:"gathering"`
|
||||
GatheringRules *GatheringRules `yaml:"gatheringRules"`
|
||||
Version int `yaml:"version"`
|
||||
@@ -78,6 +80,14 @@ func Parse(data []byte) (Balance, error) {
|
||||
return b, b.Validate()
|
||||
}
|
||||
func (b Balance) Validate() error {
|
||||
if b.CombatRules != nil {
|
||||
if err := b.CombatRules.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := (Catalog{Combat: b.Combat, Items: b.Items, Gathering: b.Gathering}).validateCombat(); err != nil {
|
||||
return err
|
||||
}
|
||||
if b.Gathering != nil {
|
||||
if err := b.Gathering.Validate(); err != nil {
|
||||
return err
|
||||
|
||||
@@ -35,6 +35,7 @@ type ItemRequirements struct {
|
||||
Titles []string `json:"titles" yaml:"titles"`
|
||||
}
|
||||
type ItemDefinition struct {
|
||||
AttackID string `json:"attackId,omitempty" yaml:"attackId"`
|
||||
ID string `json:"id" yaml:"id"`
|
||||
Name string `json:"name" yaml:"name"`
|
||||
Description string `json:"description" yaml:"description"`
|
||||
@@ -45,6 +46,7 @@ type ItemDefinition struct {
|
||||
Modifiers []StatModifier `json:"modifiers" yaml:"modifiers"`
|
||||
}
|
||||
type Catalog struct {
|
||||
Combat *CombatContent `json:"combat,omitempty"`
|
||||
Gathering *GatheringContent `json:"gathering,omitempty"`
|
||||
Version int64 `json:"version"`
|
||||
Titles []Title `json:"titles"`
|
||||
@@ -124,6 +126,9 @@ func (item ItemDefinition) Validate() error {
|
||||
return ValidateModifiers(item.Modifiers)
|
||||
}
|
||||
func (c Catalog) Validate() error {
|
||||
if err := c.validateCombat(); err != nil {
|
||||
return err
|
||||
}
|
||||
if c.Gathering != nil {
|
||||
if err := c.Gathering.Validate(); err != nil {
|
||||
return err
|
||||
@@ -196,5 +201,5 @@ func DefaultCatalog() (Catalog, error) {
|
||||
if err != nil {
|
||||
return Catalog{}, err
|
||||
}
|
||||
return Catalog{Gathering: b.Gathering, Version: 1, Titles: b.Titles, Items: b.Items, Stats: *b.Stats}, nil
|
||||
return Catalog{Combat: b.Combat, Gathering: b.Gathering, Version: 1, Titles: b.Titles, Items: b.Items, Stats: *b.Stats}, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,452 @@
|
||||
package game
|
||||
|
||||
import (
|
||||
"aeternalis/server/content"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"sort"
|
||||
)
|
||||
|
||||
type Projectile struct {
|
||||
Target string `json:"target"`
|
||||
ID string `json:"id"`
|
||||
Source string `json:"source"`
|
||||
Player bool `json:"player"`
|
||||
Position p.Vec3 `json:"position"`
|
||||
Destination p.Vec3 `json:"destination"`
|
||||
Attack p.CombatAttack `json:"attack"`
|
||||
Power float64 `json:"power"`
|
||||
}
|
||||
type CombatArea struct {
|
||||
Projectile
|
||||
NextAt float64 `json:"nextAt"`
|
||||
ExpiresAt float64 `json:"expiresAt"`
|
||||
}
|
||||
|
||||
func protocolAttack(a content.CombatAttack) p.CombatAttack {
|
||||
return p.CombatAttack{ID: a.ID, Name: a.Name, Description: a.Description, Delivery: a.Delivery, Effect: a.Effect, Stat: a.Stat, Multiplier: a.Multiplier, Range: a.Range, Cooldown: a.Cooldown, Stamina: a.Stamina, Speed: a.Speed, Radius: a.Radius, Duration: a.Duration, Interval: a.Interval}
|
||||
}
|
||||
func (w *World) playerAttack(c *Character) p.CombatAttack {
|
||||
for _, i := range c.View.Items {
|
||||
if i.ID == c.View.Equipment["weapon"] && i.Attack != nil {
|
||||
return *i.Attack
|
||||
}
|
||||
}
|
||||
return p.CombatAttack{ID: "basic_melee", Name: "Melee attack", Delivery: "melee", Effect: "damage", Stat: "meleeDamage", Multiplier: 1, Range: w.Balance.AttackRange, Cooldown: w.Balance.AttackCooldown, Speed: 1, Interval: 1}
|
||||
}
|
||||
func length3(a, b p.Vec3) float64 {
|
||||
return math.Sqrt((a.X-b.X)*(a.X-b.X) + (a.Y-b.Y)*(a.Y-b.Y) + (a.Z-b.Z)*(a.Z-b.Z))
|
||||
}
|
||||
func body(pos p.Vec3) p.Vec3 { pos.Y += 1; return pos }
|
||||
func lerp3(a, b p.Vec3, t float64) p.Vec3 {
|
||||
return p.Vec3{X: a.X + (b.X-a.X)*t, Y: a.Y + (b.Y-a.Y)*t, Z: a.Z + (b.Z-a.Z)*t}
|
||||
}
|
||||
func (w *World) combatID(kind string) string {
|
||||
w.CombatSequence++
|
||||
return fmt.Sprintf("%s:%d", kind, w.CombatSequence)
|
||||
}
|
||||
func (w *World) sourceActive(source string, player bool) bool {
|
||||
if w.Phase == "won" || w.Phase == "lost" {
|
||||
return false
|
||||
}
|
||||
if player {
|
||||
c := w.Characters[source]
|
||||
return c != nil && c.View.Entity.State == "alive" && !c.Sheltered
|
||||
}
|
||||
m := w.Mobs[source]
|
||||
return m != nil && m.Entity.HP > 0
|
||||
}
|
||||
func (w *World) combatTargets(player bool, effect string) []p.Entity {
|
||||
out := []p.Entity{}
|
||||
if (player && effect == "heal") || (!player && effect == "damage") {
|
||||
for _, c := range w.orderedCharacters() {
|
||||
if c.Online && c.View.Entity.State == "alive" && !c.Sheltered {
|
||||
out = append(out, c.View.Entity)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for _, id := range w.mobIDs() {
|
||||
m := w.Mobs[id]
|
||||
if m.Entity.HP > 0 {
|
||||
out = append(out, m.Entity)
|
||||
}
|
||||
}
|
||||
if w.Phase == "cataclysm" {
|
||||
out = append(out, p.Entity{ID: "boss", Position: w.terrain.Position(0, 0), HP: w.BossHP})
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
func (w *World) terrainHit(a, b p.Vec3) (p.Vec3, bool) {
|
||||
steps := max(1, int(math.Ceil(length3(a, b)*2)))
|
||||
for i := 1; i <= steps; i++ {
|
||||
v := lerp3(a, b, float64(i)/float64(steps))
|
||||
if v.Y < w.terrain.Height(v.X, v.Z)+.05 {
|
||||
return v, true
|
||||
}
|
||||
}
|
||||
return b, false
|
||||
}
|
||||
func (w *World) attack(c *Character, target string) error {
|
||||
a := w.playerAttack(c)
|
||||
if w.Age() < c.AttackReadyAt || w.Age()-c.LastAttack < a.Cooldown {
|
||||
return errors.New("attack cooldown")
|
||||
}
|
||||
if c.View.Stamina < a.Stamina {
|
||||
return errors.New("not enough stamina")
|
||||
}
|
||||
var e *p.Entity
|
||||
for _, v := range w.combatTargets(true, a.Effect) {
|
||||
if v.ID == target {
|
||||
copy := v
|
||||
e = ©
|
||||
break
|
||||
}
|
||||
}
|
||||
if e == nil {
|
||||
return errors.New("invalid attack target")
|
||||
}
|
||||
from, to := body(c.View.Entity.Position), body(e.Position)
|
||||
extra := float64(0)
|
||||
if target == "boss" {
|
||||
extra = 4
|
||||
}
|
||||
if length3(from, to) > a.Range+extra {
|
||||
return errors.New("target out of reach")
|
||||
}
|
||||
if _, blocked := w.terrainHit(from, to); blocked {
|
||||
return errors.New("terrain blocks the attack")
|
||||
}
|
||||
if a.Delivery == "projectile" && len(w.Projectiles) >= w.Balance.CombatRules.MaxProjectiles {
|
||||
return errors.New("projectile limit reached")
|
||||
}
|
||||
if a.Duration > 0 && len(w.Areas)+w.pendingAreas() >= w.Balance.CombatRules.MaxAreas {
|
||||
return errors.New("area effect limit reached")
|
||||
}
|
||||
power := c.View.Stats[a.Stat].Final * a.Multiplier
|
||||
if a.Effect == "damage" && w.roll(c.View.Stats["criticalChance"].Final) {
|
||||
power *= w.Balance.CriticalMultiplier
|
||||
}
|
||||
c.LastAttack = w.Age()
|
||||
c.AttackReadyAt = w.Age() + a.Cooldown
|
||||
c.View.Stamina -= a.Stamina
|
||||
w.dirty = true
|
||||
shot := Projectile{ID: w.combatID("projectile"), Source: c.View.Entity.ID, Player: true, Target: target, Position: from, Destination: to, Attack: a, Power: power}
|
||||
if a.Delivery == "projectile" {
|
||||
w.Projectiles[shot.ID] = &shot
|
||||
} else {
|
||||
shot.Position = to
|
||||
w.impact(shot, target)
|
||||
}
|
||||
c.View.Skills["combat"] += w.Balance.SkillXpPerAction
|
||||
w.evaluateTitles(c)
|
||||
return nil
|
||||
}
|
||||
func (w *World) pendingAreas() int {
|
||||
n := 0
|
||||
for _, p := range w.Projectiles {
|
||||
if p.Attack.Duration > 0 {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
func (w *World) impact(shot Projectile, target string) {
|
||||
if !w.sourceActive(shot.Source, shot.Player) {
|
||||
return
|
||||
}
|
||||
if shot.Attack.Radius > 0 {
|
||||
w.areaPulse(shot)
|
||||
} else if target != "" {
|
||||
w.combatHit(shot, target)
|
||||
}
|
||||
if shot.Attack.Duration > 0 && w.sourceActive(shot.Source, shot.Player) {
|
||||
id := w.combatID("area")
|
||||
shot.ID = id
|
||||
w.Areas[id] = &CombatArea{Projectile: shot, NextAt: w.Age() + shot.Attack.Interval, ExpiresAt: w.Age() + shot.Attack.Duration}
|
||||
}
|
||||
w.dirty = true
|
||||
}
|
||||
func (w *World) areaPulse(shot Projectile) {
|
||||
targets := w.combatTargets(shot.Player, shot.Attack.Effect)
|
||||
sort.Slice(targets, func(i, j int) bool {
|
||||
a, b := length3(body(targets[i].Position), shot.Position), length3(body(targets[j].Position), shot.Position)
|
||||
if a == b {
|
||||
return targets[i].ID < targets[j].ID
|
||||
}
|
||||
return a < b
|
||||
})
|
||||
n := 0
|
||||
for _, e := range targets {
|
||||
if n >= w.Balance.CombatRules.MaxTargets || !w.sourceActive(shot.Source, shot.Player) {
|
||||
break
|
||||
}
|
||||
if length3(body(e.Position), shot.Position) > shot.Attack.Radius {
|
||||
continue
|
||||
}
|
||||
if _, blocked := w.terrainHit(shot.Position, body(e.Position)); blocked {
|
||||
continue
|
||||
}
|
||||
w.combatHit(shot, e.ID)
|
||||
n++
|
||||
}
|
||||
}
|
||||
func (w *World) combatHit(shot Projectile, target string) {
|
||||
if !w.sourceActive(shot.Source, shot.Player) {
|
||||
return
|
||||
}
|
||||
healing := shot.Attack.Effect == "heal"
|
||||
if c := w.Characters[target]; c != nil {
|
||||
if c.View.Entity.State != "alive" || !c.Online || c.Sheltered {
|
||||
return
|
||||
}
|
||||
if healing && shot.Player {
|
||||
c.View.Entity.HP = math.Min(c.View.Entity.MaxHP, c.View.Entity.HP+shot.Power)
|
||||
} else if !healing && !shot.Player {
|
||||
w.damageCharacter(c, shot.Power)
|
||||
if c.View.Entity.HP <= 0 {
|
||||
w.kill(c, "A creature's attack ended this character's journey.")
|
||||
}
|
||||
}
|
||||
w.dirty = true
|
||||
return
|
||||
}
|
||||
if target == "boss" {
|
||||
if w.Phase != "cataclysm" {
|
||||
return
|
||||
}
|
||||
if healing && !shot.Player {
|
||||
w.BossHP = math.Min(w.Balance.BossHp, w.BossHP+shot.Power)
|
||||
} else if !healing && shot.Player {
|
||||
w.damageBoss(w.Characters[shot.Source], shot.Power)
|
||||
}
|
||||
w.dirty = true
|
||||
return
|
||||
}
|
||||
m := w.Mobs[target]
|
||||
if m == nil || m.Entity.HP <= 0 {
|
||||
return
|
||||
}
|
||||
if healing && !shot.Player {
|
||||
m.Entity.HP = math.Min(m.Entity.MaxHP, m.Entity.HP+shot.Power)
|
||||
} else if !healing && shot.Player {
|
||||
defence := float64(0)
|
||||
if m.Definition != nil {
|
||||
defence = m.Definition.Defence
|
||||
}
|
||||
m.Entity.HP = math.Max(0, m.Entity.HP-math.Max(0, shot.Power-defence))
|
||||
m.Target = shot.Source
|
||||
if m.Entity.HP == 0 {
|
||||
w.mobKilled(w.Characters[shot.Source], m)
|
||||
}
|
||||
}
|
||||
w.dirty = true
|
||||
}
|
||||
func (w *World) updateCombat(dt float64) {
|
||||
ids := make([]string, 0, len(w.Projectiles))
|
||||
for id := range w.Projectiles {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
sort.Strings(ids)
|
||||
for _, id := range ids {
|
||||
shot := w.Projectiles[id]
|
||||
if !w.sourceActive(shot.Source, shot.Player) {
|
||||
delete(w.Projectiles, id)
|
||||
w.dirty = true
|
||||
continue
|
||||
}
|
||||
remaining := length3(shot.Position, shot.Destination)
|
||||
step := math.Min(remaining, shot.Attack.Speed*dt)
|
||||
t := float64(1)
|
||||
if remaining > 0 {
|
||||
t = step / remaining
|
||||
}
|
||||
end := lerp3(shot.Position, shot.Destination, t)
|
||||
obstacle, blocked := w.terrainHit(shot.Position, end)
|
||||
best := math.Inf(1)
|
||||
if blocked {
|
||||
best = length3(shot.Position, obstacle)
|
||||
}
|
||||
hit := ""
|
||||
hitPoint := obstacle
|
||||
for _, e := range w.combatTargets(shot.Player, shot.Attack.Effect) {
|
||||
if e.ID == shot.Source && shot.Target != shot.Source {
|
||||
continue
|
||||
}
|
||||
center := body(e.Position)
|
||||
ab := length3(shot.Position, end)
|
||||
fraction := float64(0)
|
||||
if ab > 0 {
|
||||
fraction = ((center.X-shot.Position.X)*(end.X-shot.Position.X) + (center.Y-shot.Position.Y)*(end.Y-shot.Position.Y) + (center.Z-shot.Position.Z)*(end.Z-shot.Position.Z)) / (ab * ab)
|
||||
}
|
||||
fraction = math.Max(0, math.Min(1, fraction))
|
||||
point := lerp3(shot.Position, end, fraction)
|
||||
radius := w.Balance.CombatRules.HitRadius
|
||||
if e.ID == "boss" {
|
||||
radius += 3
|
||||
}
|
||||
dist := length3(shot.Position, point)
|
||||
if length3(point, center) <= radius && dist < best {
|
||||
best = dist
|
||||
hit = e.ID
|
||||
hitPoint = point
|
||||
}
|
||||
}
|
||||
if hit != "" || blocked || t >= 1 {
|
||||
copy := *shot
|
||||
copy.Position = end
|
||||
if hit != "" || blocked {
|
||||
copy.Position = hitPoint
|
||||
}
|
||||
delete(w.Projectiles, id)
|
||||
w.impact(copy, hit)
|
||||
} else {
|
||||
shot.Position = end
|
||||
}
|
||||
}
|
||||
ids = ids[:0]
|
||||
for id := range w.Areas {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
sort.Strings(ids)
|
||||
for _, id := range ids {
|
||||
area := w.Areas[id]
|
||||
if !w.sourceActive(area.Source, area.Player) || w.Age() > area.ExpiresAt {
|
||||
delete(w.Areas, id)
|
||||
w.dirty = true
|
||||
continue
|
||||
}
|
||||
if w.Age() >= area.NextAt {
|
||||
w.areaPulse(area.Projectile)
|
||||
area.NextAt = w.Age() + area.Attack.Interval
|
||||
w.dirty = true
|
||||
}
|
||||
}
|
||||
}
|
||||
func (w *World) mobKilled(c *Character, m *Mob) {
|
||||
if m.Entity.State == "dead" {
|
||||
return
|
||||
}
|
||||
m.Entity.State = "dead"
|
||||
m.Target = ""
|
||||
m.RespawnAt = w.Age() + m.RespawnDelay
|
||||
c.View.Kills++
|
||||
c.WorldKills++
|
||||
if m.Definition == nil {
|
||||
c.View.Inventory["herb"] += w.yieldAmount(c.View.Stats["dropRate"].Final)
|
||||
for _, item := range w.Balance.Items {
|
||||
if w.roll(item.DropChance * c.View.Stats["dropRate"].Final / 100) {
|
||||
_ = w.grantItems(c, item.ID, 1)
|
||||
}
|
||||
}
|
||||
w.grantXP(c, w.Balance.Progression.MobKillXP)
|
||||
} else {
|
||||
inventory := map[string]int64{}
|
||||
items := []p.ItemInstance{}
|
||||
entries := m.Loot.Entries
|
||||
selected := []content.LootEntry{}
|
||||
groups := map[string][]content.LootEntry{}
|
||||
for _, e := range entries {
|
||||
if e.Group == "" {
|
||||
selected = append(selected, e)
|
||||
} else {
|
||||
groups[e.Group] = append(groups[e.Group], e)
|
||||
}
|
||||
}
|
||||
keys := make([]string, 0, len(groups))
|
||||
for key := range groups {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for _, key := range keys {
|
||||
pool := groups[key]
|
||||
total := int64(0)
|
||||
for _, e := range pool {
|
||||
total += e.Weight
|
||||
}
|
||||
for _, e := range pool {
|
||||
if w.roll(float64(e.Weight) * 100 / float64(total)) {
|
||||
selected = append(selected, e)
|
||||
break
|
||||
}
|
||||
total -= e.Weight
|
||||
}
|
||||
}
|
||||
for _, e := range selected {
|
||||
chance := e.Chance
|
||||
if chance < 100 {
|
||||
chance *= c.View.Stats["dropRate"].Final / 100
|
||||
}
|
||||
if w.roll(chance) {
|
||||
_ = w.addInventoryItems(&inventory, &items, e.Item, e.Amount)
|
||||
}
|
||||
}
|
||||
if len(inventory) > 0 || len(items) > 0 {
|
||||
id := w.combatID("loot")
|
||||
entity := m.Entity
|
||||
entity.ID = id
|
||||
entity.Kind = "corpse"
|
||||
entity.Model = nil
|
||||
w.Corpses[id] = &Corpse{Entity: entity, Inventory: inventory, Items: items}
|
||||
}
|
||||
w.grantXP(c, m.Definition.XP)
|
||||
}
|
||||
w.RefreshStats(c)
|
||||
w.evaluateTitles(c)
|
||||
w.dirty = true
|
||||
}
|
||||
func (w *World) restoreCombat() error {
|
||||
if w.Projectiles == nil {
|
||||
w.Projectiles = map[string]*Projectile{}
|
||||
}
|
||||
if w.Areas == nil {
|
||||
w.Areas = map[string]*CombatArea{}
|
||||
}
|
||||
if len(w.Projectiles) > w.Balance.CombatRules.MaxProjectiles || len(w.Areas) > w.Balance.CombatRules.MaxAreas {
|
||||
return errors.New("persisted combat exceeds work limits")
|
||||
}
|
||||
validate := func(shot Projectile) error {
|
||||
raw, _ := json.Marshal(shot.Attack)
|
||||
var a content.CombatAttack
|
||||
_ = json.Unmarshal(raw, &a)
|
||||
if err := a.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, v := range []float64{shot.Position.X, shot.Position.Y, shot.Position.Z, shot.Destination.X, shot.Destination.Y, shot.Destination.Z, shot.Power} {
|
||||
if math.IsNaN(v) || math.IsInf(v, 0) {
|
||||
return errors.New("invalid persisted projectile")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
for id, v := range w.Projectiles {
|
||||
if v == nil || id != v.ID {
|
||||
return errors.New("invalid projectile identity")
|
||||
}
|
||||
if err := validate(*v); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for id, v := range w.Areas {
|
||||
if v == nil || id != v.ID || math.IsNaN(v.NextAt) || math.IsNaN(v.ExpiresAt) || math.IsInf(v.NextAt, 0) || math.IsInf(v.ExpiresAt, 0) {
|
||||
return errors.New("invalid area identity or deadline")
|
||||
}
|
||||
if err := validate(v.Projectile); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, m := range w.Mobs {
|
||||
if m == nil {
|
||||
return errors.New("invalid persisted mob")
|
||||
}
|
||||
if m.Home == nil {
|
||||
v := w.terrain.Position((float64(m.HomeX)+.55)*w.Balance.ChunkSize, (float64(m.HomeZ)+.55)*w.Balance.ChunkSize)
|
||||
m.Home = &v
|
||||
m.RespawnDelay = w.Balance.MobRespawnSeconds
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
package game
|
||||
|
||||
import (
|
||||
"aeternalis/server/content"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func combatFixture(t *testing.T) (*World, *Character, *Mob) {
|
||||
t.Helper()
|
||||
w, c := fixture(t)
|
||||
w.now = w.CreatedAt.Add(time.Minute)
|
||||
d := *w.mobDefinition("ash_guard")
|
||||
d.Behavior = "passive"
|
||||
d.HP = 200
|
||||
d.ScalePerDay = 0
|
||||
m := w.newMob("combat-target", d, w.terrain.Position(20, 0), 60)
|
||||
w.Mobs[m.Entity.ID] = m
|
||||
a := protocolAttack(w.Balance.Combat.Attacks[0])
|
||||
c.View.Items = append(c.View.Items, p.ItemInstance{ID: "bow", DefinitionID: "bow", Name: "Bow", Slot: "weapon", Requirements: p.ItemRequirements{Level: 1}, Attack: &a})
|
||||
c.View.Equipment["weapon"] = "bow"
|
||||
w.RefreshStats(c)
|
||||
return w, c, m
|
||||
}
|
||||
func advanceProjectiles(w *World, steps int) {
|
||||
for i := 0; i < steps; i++ {
|
||||
w.now = w.now.Add(50 * time.Millisecond)
|
||||
w.updateCombat(.05)
|
||||
}
|
||||
}
|
||||
func TestProjectileHitMissCostsAndWeaponSwap(t *testing.T) {
|
||||
w, c, m := combatFixture(t)
|
||||
stamina := c.View.Stamina
|
||||
if err := w.Intent(c.View.Entity.ID, p.Intent{Op: "attack", Target: m.Entity.ID, Seq: 1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if m.Entity.HP != m.Entity.MaxHP || len(w.Projectiles) != 1 || c.View.Stamina != stamina-2 {
|
||||
t.Fatal("projectile applied instant damage or wrong cost")
|
||||
}
|
||||
if err := w.Intent(c.View.Entity.ID, p.Intent{Op: "attack", Target: m.Entity.ID, Seq: 1}); err == nil {
|
||||
t.Fatal("sequence replay accepted")
|
||||
}
|
||||
if err := w.unequip(c, "weapon"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := w.attack(c, m.Entity.ID); err == nil {
|
||||
t.Fatal("weapon swap bypassed cooldown")
|
||||
}
|
||||
advanceProjectiles(w, 20)
|
||||
if m.Entity.HP >= m.Entity.MaxHP || len(w.Projectiles) != 0 {
|
||||
t.Fatal("projectile failed to hit")
|
||||
}
|
||||
w, c, m = combatFixture(t)
|
||||
if err := w.attack(c, m.Entity.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m.Entity.Position = w.terrain.Position(20, 12)
|
||||
advanceProjectiles(w, 25)
|
||||
if m.Entity.HP != m.Entity.MaxHP {
|
||||
t.Fatal("straight projectile homed on moving target")
|
||||
}
|
||||
w, c, m = combatFixture(t)
|
||||
c.View.Stamina = 0
|
||||
if err := w.attack(c, m.Entity.ID); err == nil || len(w.Projectiles) != 0 {
|
||||
t.Fatal("insufficient stamina spawned projectile")
|
||||
}
|
||||
}
|
||||
func TestCrossChunkPursuitRetainsIdentityAndHealth(t *testing.T) {
|
||||
w, c, m := combatFixture(t)
|
||||
m.Definition.Behavior = "aggressive"
|
||||
m.HomeX = 0
|
||||
m.HomeZ = 0
|
||||
home := w.terrain.Position(125, 10)
|
||||
m.Home = &home
|
||||
m.Entity.Position = home
|
||||
m.Entity.HP = 123
|
||||
c.View.Entity.Position = w.terrain.Position(141, 10)
|
||||
for i := 0; i < 8; i++ {
|
||||
w.updateMobs(map[string]bool{"0:0": true, "1:0": true}, .25)
|
||||
}
|
||||
if m.Entity.Position.X <= 128 || m.Entity.HP != 123 || w.Mobs[m.Entity.ID] != m {
|
||||
t.Fatal("chunk edge blocked/reset pursuit")
|
||||
}
|
||||
x := m.Entity.Position.X
|
||||
w.updateMobs(map[string]bool{"1:0": true}, .25)
|
||||
if m.Entity.Position.X <= x {
|
||||
t.Fatal("mob froze when only destination chunk active")
|
||||
}
|
||||
raw, _ := json.Marshal(w)
|
||||
var restored World
|
||||
_ = json.Unmarshal(raw, &restored)
|
||||
if err := restored.Restore(w.now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if restored.Mobs[m.Entity.ID].Entity.Position.X != m.Entity.Position.X || restored.Mobs[m.Entity.ID].Entity.HP != 123 {
|
||||
t.Fatal("restart reset traveling mob")
|
||||
}
|
||||
}
|
||||
func TestAreaHealingBoundariesAndSourceDeath(t *testing.T) {
|
||||
w, c, m := combatFixture(t)
|
||||
c.View.Entity.Position = w.terrain.Position(127, 10)
|
||||
m.Entity.Position = w.terrain.Position(129, 10)
|
||||
shot := Projectile{Source: c.View.Entity.ID, Player: true, Position: body(c.View.Entity.Position), Power: 10, Attack: p.CombatAttack{ID: "test_area", Name: "Area", Delivery: "melee", Effect: "damage", Stat: "rangedDamage", Multiplier: 1, Range: 6, Cooldown: 1, Speed: 1, Radius: 6, Duration: 4, Interval: 1}}
|
||||
w.impact(shot, "")
|
||||
if m.Entity.HP != 190 || len(w.Areas) != 1 {
|
||||
t.Fatal("AoE clipped chunk boundary")
|
||||
}
|
||||
other, err := w.Join("other", "Other")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
other.Online = true
|
||||
other.View.Entity.Position = w.terrain.Position(128, 10)
|
||||
other.View.Entity.HP = 30
|
||||
c.View.Entity.HP = 40
|
||||
shot.Attack.Effect = "heal"
|
||||
w.impact(shot, "")
|
||||
if other.View.Entity.HP != 40 || c.View.Entity.HP != 50 {
|
||||
t.Fatal("area did not heal living allies")
|
||||
}
|
||||
w.kill(other, "test death")
|
||||
w.areaPulse(shot)
|
||||
if other.View.Entity.HP != 0 || other.View.Entity.State != "dead" {
|
||||
t.Fatal("area resurrected a corpse")
|
||||
}
|
||||
w.kill(c, "source died")
|
||||
hp := m.Entity.HP
|
||||
advanceProjectiles(w, 30)
|
||||
if m.Entity.HP != hp || len(w.Areas) != 0 {
|
||||
t.Fatal("dead source area continued damaging")
|
||||
}
|
||||
}
|
||||
func TestProjectileAndAreaRestartDoesNotRepeatDamage(t *testing.T) {
|
||||
w, c, m := combatFixture(t)
|
||||
a := w.playerAttack(c)
|
||||
a.Radius = 4
|
||||
a.Duration = 2
|
||||
a.Interval = 1
|
||||
c.View.Items[len(c.View.Items)-1].Attack = &a
|
||||
if err := w.attack(c, m.Entity.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
advanceProjectiles(w, 4)
|
||||
raw, _ := json.Marshal(w)
|
||||
var restored World
|
||||
_ = json.Unmarshal(raw, &restored)
|
||||
if err := restored.Restore(w.now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
advanceProjectiles(&restored, 12)
|
||||
rm := restored.Mobs[m.Entity.ID]
|
||||
hp := rm.Entity.HP
|
||||
if hp >= 200 || len(restored.Areas) != 1 {
|
||||
t.Fatal("saved projectile did not complete")
|
||||
}
|
||||
raw, _ = json.Marshal(&restored)
|
||||
var again World
|
||||
_ = json.Unmarshal(raw, &again)
|
||||
if err := again.Restore(restored.now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
again.updateCombat(.01)
|
||||
if again.Mobs[m.Entity.ID].Entity.HP != hp {
|
||||
t.Fatal("restore repeated impact or early area tick")
|
||||
}
|
||||
advanceProjectiles(&again, 60)
|
||||
if len(again.Areas) != 0 || len(again.Projectiles) != 0 {
|
||||
t.Fatal("effects outlived their deadlines")
|
||||
}
|
||||
}
|
||||
func TestMobLootOnceAndRespawn(t *testing.T) {
|
||||
w, c, m := combatFixture(t)
|
||||
m.Loot.Entries = []content.LootEntry{{Item: "herb", Amount: 2, Chance: 100, Weight: 1}, {Item: "wood", Amount: 1, Chance: 100, Weight: 1, Group: "one"}, {Item: "ore", Amount: 1, Chance: 100, Weight: 2, Group: "one"}}
|
||||
shot := Projectile{Source: c.View.Entity.ID, Player: true, Attack: p.CombatAttack{Effect: "damage"}, Power: 1000}
|
||||
w.combatHit(shot, m.Entity.ID)
|
||||
w.combatHit(shot, m.Entity.ID)
|
||||
if len(w.Corpses) != 1 || c.View.Kills != 1 {
|
||||
t.Fatal("duplicate loot or kill credit")
|
||||
}
|
||||
for _, corpse := range w.Corpses {
|
||||
if corpse.Inventory["herb"] != 2 || corpse.Inventory["wood"]+corpse.Inventory["ore"] != 1 {
|
||||
t.Fatal("guaranteed/weighted loot wrong")
|
||||
}
|
||||
}
|
||||
raw, _ := json.Marshal(w)
|
||||
var restored World
|
||||
_ = json.Unmarshal(raw, &restored)
|
||||
if err := restored.Restore(w.now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
restored.now = restored.now.Add(61 * time.Second)
|
||||
restored.updateMobs(map[string]bool{Key(m.HomeX, m.HomeZ): true}, .05)
|
||||
if restored.Mobs[m.Entity.ID].Entity.HP <= 0 || len(restored.Corpses) != 1 {
|
||||
t.Fatal("respawn rerolled old loot")
|
||||
}
|
||||
}
|
||||
func TestTerrainObstructionAndCombatLimits(t *testing.T) {
|
||||
w, c, m := combatFixture(t)
|
||||
if _, blocked := w.terrainHit(p.Vec3{X: 0, Y: -2}, p.Vec3{X: 20, Y: -2}); !blocked {
|
||||
t.Fatal("terrain penetration allowed")
|
||||
}
|
||||
w.Balance.CombatRules.MaxProjectiles = 1
|
||||
if err := w.attack(c, m.Entity.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
w.now = w.now.Add(2 * time.Second)
|
||||
stamina := c.View.Stamina
|
||||
if err := w.attack(c, m.Entity.ID); err == nil || c.View.Stamina != stamina {
|
||||
t.Fatal("work limit spent resources")
|
||||
}
|
||||
w.kill(c, "permanent death")
|
||||
advanceProjectiles(w, 30)
|
||||
if m.Entity.HP != m.Entity.MaxHP {
|
||||
t.Fatal("dead character's projectile hit")
|
||||
}
|
||||
if err := w.SpawnMobs("ash_guard", "33,0,0"); err == nil {
|
||||
t.Fatal("spawn limit ignored")
|
||||
}
|
||||
if _, _, _, err := ParseMobSpawn("1,NaN,0"); err == nil {
|
||||
t.Fatal("nonfinite spawn accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegionalSpawnsRespectExploredBiomeAndPlayerDistance(t *testing.T) {
|
||||
w, c, _ := combatFixture(t)
|
||||
w.Mobs = map[string]*Mob{}
|
||||
w.ResourceLayouts["0:0"] = ResourceLayout{BiomeID: "forest", Biome: "Forest"}
|
||||
w.Balance.Combat.Spawns = []content.MobSpawn{{ID: "test_region", MobID: "ash_guard", X: 20, Z: 0, Count: 1, Respawn: 5, MinPlayerDistance: 10, Biomes: []string{"meadow"}}}
|
||||
active := map[string]bool{"0:0": true}
|
||||
w.updateSpawns(active)
|
||||
if len(w.Mobs) != 0 {
|
||||
t.Fatal("spawn ignored explored biome")
|
||||
}
|
||||
w.Balance.Combat.Spawns[0].Biomes = []string{"forest"}
|
||||
c.View.Entity.Position = w.terrain.Position(20, 0)
|
||||
w.updateSpawns(active)
|
||||
if len(w.Mobs) != 0 {
|
||||
t.Fatal("spawn ignored player distance")
|
||||
}
|
||||
c.View.Entity.Position = w.terrain.Position(0, 0)
|
||||
w.updateSpawns(map[string]bool{})
|
||||
if len(w.Mobs) != 0 {
|
||||
t.Fatal("spawn activated an unsubscribed chunk")
|
||||
}
|
||||
w.updateSpawns(active)
|
||||
w.updateSpawns(active)
|
||||
if len(w.Mobs) != 1 || w.Mobs["spawn:test_region:0"] == nil {
|
||||
t.Fatal("regional slot was missing or duplicated")
|
||||
}
|
||||
}
|
||||
@@ -64,6 +64,14 @@ func (w *World) addInventoryItems(inventory *map[string]int64, items *[]p.ItemIn
|
||||
for _, modifier := range definition.Modifiers {
|
||||
item.Modifiers = append(item.Modifiers, p.StatModifier{Skill: stringPtr(modifier.Skill), Stat: modifier.Stat, Flat: modifier.Flat, Percent: modifier.Percent})
|
||||
}
|
||||
if definition.AttackID != "" {
|
||||
for _, a := range w.Balance.Combat.Attacks {
|
||||
if a.ID == definition.AttackID {
|
||||
v := protocolAttack(a)
|
||||
item.Attack = &v
|
||||
}
|
||||
}
|
||||
}
|
||||
created = append(created, item)
|
||||
}
|
||||
*items = append(*items, created...)
|
||||
|
||||
@@ -0,0 +1,324 @@
|
||||
package game
|
||||
|
||||
import (
|
||||
"aeternalis/server/content"
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"slices"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func (w *World) mobIDs() []string {
|
||||
ids := make([]string, 0, len(w.Mobs))
|
||||
for id := range w.Mobs {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
sort.Strings(ids)
|
||||
return ids
|
||||
}
|
||||
func ParseMobSpawn(value string) (int, float64, float64, error) {
|
||||
parts := strings.Split(value, ",")
|
||||
if len(parts) != 3 {
|
||||
return 0, 0, 0, errors.New("spawn requires count,x,z")
|
||||
}
|
||||
n, e1 := strconv.Atoi(parts[0])
|
||||
x, e2 := strconv.ParseFloat(parts[1], 64)
|
||||
z, e3 := strconv.ParseFloat(parts[2], 64)
|
||||
if e1 != nil || e2 != nil || e3 != nil || n < 1 || n > 32 || math.IsNaN(x) || math.IsNaN(z) || math.IsInf(x, 0) || math.IsInf(z, 0) || math.Abs(x) > 100000 || math.Abs(z) > 100000 {
|
||||
return 0, 0, 0, errors.New("choose 1-32 mobs and finite world coordinates")
|
||||
}
|
||||
return n, x, z, nil
|
||||
}
|
||||
func (w *World) mobDefinition(id string) *content.MobDefinition {
|
||||
for i := range w.Balance.Combat.Mobs {
|
||||
if w.Balance.Combat.Mobs[i].ID == id {
|
||||
return &w.Balance.Combat.Mobs[i]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (w *World) newMob(id string, d content.MobDefinition, pos p.Vec3, respawn float64) *Mob {
|
||||
scale := float64(d.Level) * (1 + w.Age()/86400*d.ScalePerDay)
|
||||
hp := d.HP * scale
|
||||
home := pos
|
||||
m := &Mob{Entity: p.Entity{ID: id, Kind: "mob", Model: stringPtr(d.Model), Name: d.Name, Position: pos, HP: hp, MaxHP: hp, State: "alive"}, Definition: &d, Home: &home, HomeX: ChunkCoord(pos.X, w.Balance.ChunkSize), HomeZ: ChunkCoord(pos.Z, w.Balance.ChunkSize), RespawnDelay: respawn, Power: d.Damage * scale}
|
||||
for _, a := range w.Balance.Combat.Attacks {
|
||||
if a.ID == d.AttackID {
|
||||
m.Attack = protocolAttack(a)
|
||||
}
|
||||
}
|
||||
for _, l := range w.Balance.Combat.Loot {
|
||||
if l.ID == d.LootID {
|
||||
m.Loot = l
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
func (w *World) SpawnMobs(definition, value string) error {
|
||||
if w.Phase == "won" || w.Phase == "lost" {
|
||||
return errors.New("world has ended")
|
||||
}
|
||||
n, x, z, err := ParseMobSpawn(value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d := w.mobDefinition(definition)
|
||||
if d == nil {
|
||||
return errors.New("unknown mob definition")
|
||||
}
|
||||
if len(w.Mobs)+n > w.Balance.CombatRules.MaxMobs {
|
||||
return errors.New("world mob limit reached")
|
||||
}
|
||||
positions := []p.Vec3{}
|
||||
for i := 0; i < n; i++ {
|
||||
px, pz := x+float64(i%6)*2, z+float64(i/6)*2
|
||||
if math.Hypot(px, pz) >= w.SafeRadius() {
|
||||
return errors.New("spawn would leave the surviving world")
|
||||
}
|
||||
positions = append(positions, w.terrain.Position(px, pz))
|
||||
}
|
||||
for _, pos := range positions {
|
||||
id := w.combatID("mob")
|
||||
w.Mobs[id] = w.newMob(id, *d, pos, 0)
|
||||
}
|
||||
w.dirty = true
|
||||
return nil
|
||||
}
|
||||
func (w *World) ensureMob(ch p.Chunk) {
|
||||
id := "m:" + ch.Key
|
||||
if _, ok := w.Mobs[id]; ok || len(w.Mobs) >= w.Balance.CombatRules.MaxMobs {
|
||||
return
|
||||
}
|
||||
x, z := (float64(ch.X)+.55)*ch.Size, (float64(ch.Z)+.55)*ch.Size
|
||||
if math.Hypot(x, z) > w.Balance.WorldRadius {
|
||||
return
|
||||
}
|
||||
hp := w.Balance.MobHp * (1 + w.Age()/86400*w.Balance.MobScalePerDay)
|
||||
home := w.terrain.Position(x, z)
|
||||
w.Mobs[id] = &Mob{Entity: p.Entity{ID: id, Kind: "sentinel", Name: "Ash sentinel", Position: home, HP: hp, MaxHP: hp, State: "alive"}, HomeX: int(ch.X), HomeZ: int(ch.Z), Home: &home, RespawnDelay: w.Balance.MobRespawnSeconds}
|
||||
w.dirty = true
|
||||
}
|
||||
func (w *World) updateSpawns(active map[string]bool) {
|
||||
for _, rule := range w.Balance.Combat.Spawns {
|
||||
d := w.mobDefinition(rule.MobID)
|
||||
if d == nil {
|
||||
continue
|
||||
}
|
||||
for i := int64(0); i < rule.Count; i++ {
|
||||
id := fmt.Sprintf("spawn:%s:%d", rule.ID, i)
|
||||
if _, ok := w.Mobs[id]; ok {
|
||||
continue
|
||||
}
|
||||
if len(w.Mobs) >= w.Balance.CombatRules.MaxMobs {
|
||||
return
|
||||
}
|
||||
angle := float64(i) * 2.399963229728653
|
||||
radius := rule.Radius * math.Sqrt(float64(i+1)/float64(rule.Count))
|
||||
x, z := rule.X+math.Cos(angle)*radius, rule.Z+math.Sin(angle)*radius
|
||||
cx, cz := ChunkCoord(x, w.Balance.ChunkSize), ChunkCoord(z, w.Balance.ChunkSize)
|
||||
if !active[Key(cx, cz)] || math.Hypot(x, z) > w.SafeRadius() {
|
||||
continue
|
||||
}
|
||||
biomeID := w.mobBiome(cx, cz)
|
||||
if len(rule.Biomes) > 0 && !slices.Contains(rule.Biomes, biomeID) {
|
||||
continue
|
||||
}
|
||||
pos := w.terrain.Position(x, z)
|
||||
near := false
|
||||
for _, c := range w.Characters {
|
||||
if c.Online && c.View.Entity.State == "alive" && distance(pos, c.View.Entity.Position) < rule.MinPlayerDistance {
|
||||
near = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if near {
|
||||
continue
|
||||
}
|
||||
w.Mobs[id] = w.newMob(id, *d, pos, rule.Respawn)
|
||||
w.Mobs[id].MinPlayerDistance = rule.MinPlayerDistance
|
||||
w.dirty = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *World) mobBiome(x, z int) string {
|
||||
if layout, ok := w.ResourceLayouts[Key(x, z)]; ok {
|
||||
if layout.BiomeID != "" {
|
||||
return layout.BiomeID
|
||||
}
|
||||
// Older explored layouts persisted only the display name. Keep their
|
||||
// established biome instead of recalculating from new catalog weights.
|
||||
for _, biome := range w.Balance.Gathering.Biomes {
|
||||
if biome.Name == layout.Biome {
|
||||
return biome.ID
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
return w.terrain.biome(x, z).ID
|
||||
}
|
||||
|
||||
// Local slope checks and deterministic side steps cross chunk edges. Future solid
|
||||
// structures can extend this one movement/line-of-sight boundary.
|
||||
func (w *World) mobStep(m *Mob, to p.Vec3, speed, dt float64) {
|
||||
from := m.Entity.Position
|
||||
d := distance(from, to)
|
||||
if d < .01 {
|
||||
return
|
||||
}
|
||||
step := math.Min(d, speed*dt)
|
||||
angle := math.Atan2(to.Z-from.Z, to.X-from.X)
|
||||
for _, offset := range []float64{0, .7, -.7, 1.3, -1.3} {
|
||||
x, z := from.X+math.Cos(angle+offset)*step, from.Z+math.Sin(angle+offset)*step
|
||||
if math.Hypot(x, z) >= w.SafeRadius() {
|
||||
continue
|
||||
}
|
||||
dest := w.terrain.Position(x, z)
|
||||
if math.Abs(dest.Y-from.Y) > w.Balance.CombatRules.MaxSlope*step {
|
||||
continue
|
||||
}
|
||||
m.Entity.Position = dest
|
||||
return
|
||||
}
|
||||
}
|
||||
func (w *World) updateMobs(active map[string]bool, dt float64) {
|
||||
w.updateSpawns(active)
|
||||
for _, id := range w.mobIDs() {
|
||||
m := w.Mobs[id]
|
||||
if m.Home == nil {
|
||||
pos := w.terrain.Position((float64(m.HomeX)+.55)*w.Balance.ChunkSize, (float64(m.HomeZ)+.55)*w.Balance.ChunkSize)
|
||||
m.Home = &pos
|
||||
m.RespawnDelay = w.Balance.MobRespawnSeconds
|
||||
}
|
||||
homeActive := active[Key(m.HomeX, m.HomeZ)]
|
||||
currentActive := active[Key(ChunkCoord(m.Entity.Position.X, w.Balance.ChunkSize), ChunkCoord(m.Entity.Position.Z, w.Balance.ChunkSize))]
|
||||
if m.Entity.HP <= 0 {
|
||||
if m.RespawnDelay == 0 {
|
||||
delete(w.Mobs, id)
|
||||
w.dirty = true
|
||||
continue
|
||||
}
|
||||
if !homeActive || w.Age() < m.RespawnAt {
|
||||
continue
|
||||
}
|
||||
blocked := false
|
||||
for _, c := range w.Characters {
|
||||
if c.Online && c.View.Entity.State == "alive" && distance(c.View.Entity.Position, *m.Home) < m.MinPlayerDistance {
|
||||
blocked = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if blocked {
|
||||
continue
|
||||
}
|
||||
hp := w.Balance.MobHp * (1 + w.Age()/86400*w.Balance.MobScalePerDay)
|
||||
if m.Definition != nil {
|
||||
d := m.Definition
|
||||
scale := float64(d.Level) * (1 + w.Age()/86400*d.ScalePerDay)
|
||||
hp = d.HP * scale
|
||||
m.Power = d.Damage * scale
|
||||
}
|
||||
m.Entity.HP = hp
|
||||
m.Entity.MaxHP = hp
|
||||
m.Entity.State = "alive"
|
||||
m.Entity.Position = *m.Home
|
||||
m.Target = ""
|
||||
w.dirty = true
|
||||
}
|
||||
if !homeActive && !currentActive {
|
||||
continue
|
||||
}
|
||||
speed, aggro, leash := w.Balance.MobSpeed, w.Balance.MobAggroRange, w.Balance.ChunkSize*2
|
||||
behavior := "aggressive"
|
||||
attack := p.CombatAttack{ID: "legacy_mob", Name: "Sentinel strike", Delivery: "melee", Effect: "damage", Stat: "meleeDamage", Range: w.Balance.MobAttackRange, Cooldown: w.Balance.MobCooldown, Multiplier: 1, Speed: 1, Interval: 1}
|
||||
power := w.Balance.MobDamage * (1 + w.Age()/86400*w.Balance.MobScalePerDay)
|
||||
if d := m.Definition; d != nil {
|
||||
speed, aggro, leash, behavior = d.Speed, d.AggroRange, d.LeashRange, d.Behavior
|
||||
attack = m.Attack
|
||||
power = m.Power
|
||||
}
|
||||
if distance(m.Entity.Position, *m.Home) > leash {
|
||||
m.Returning = true
|
||||
m.Target = ""
|
||||
}
|
||||
if m.Returning {
|
||||
if distance(m.Entity.Position, *m.Home) < 1 {
|
||||
m.Returning = false
|
||||
} else {
|
||||
w.mobStep(m, *m.Home, speed, dt)
|
||||
}
|
||||
continue
|
||||
}
|
||||
var target *Character
|
||||
if c := w.Characters[m.Target]; c != nil && c.Online && !c.Sheltered && c.View.Entity.State == "alive" && distance(c.View.Entity.Position, *m.Home) <= leash {
|
||||
target = c
|
||||
}
|
||||
if target == nil {
|
||||
m.Target = ""
|
||||
if behavior != "passive" {
|
||||
nearest := aggro
|
||||
for _, c := range w.orderedCharacters() {
|
||||
if !c.Online || c.Sheltered || c.View.Entity.State != "alive" {
|
||||
continue
|
||||
}
|
||||
d := distance(c.View.Entity.Position, m.Entity.Position)
|
||||
if d < nearest && distance(c.View.Entity.Position, *m.Home) <= leash {
|
||||
if _, blocked := w.terrainHit(body(m.Entity.Position), body(c.View.Entity.Position)); blocked {
|
||||
continue
|
||||
}
|
||||
target = c
|
||||
nearest = d
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if target == nil {
|
||||
if distance(m.Entity.Position, *m.Home) > 1 {
|
||||
w.mobStep(m, *m.Home, speed, dt)
|
||||
}
|
||||
continue
|
||||
}
|
||||
m.Target = target.View.Entity.ID
|
||||
if behavior == "guard" && distance(target.View.Entity.Position, *m.Home) > aggro {
|
||||
m.Target = ""
|
||||
w.mobStep(m, *m.Home, speed, dt)
|
||||
continue
|
||||
}
|
||||
aim := target.View.Entity.Position
|
||||
targetID := target.View.Entity.ID
|
||||
if attack.Effect == "heal" {
|
||||
aim = m.Entity.Position
|
||||
targetID = m.Entity.ID
|
||||
}
|
||||
if length3(body(m.Entity.Position), body(aim)) <= attack.Range {
|
||||
if w.Age()-m.LastAttack < attack.Cooldown {
|
||||
continue
|
||||
}
|
||||
if _, blocked := w.terrainHit(body(m.Entity.Position), body(aim)); blocked {
|
||||
w.mobStep(m, aim, speed, dt)
|
||||
continue
|
||||
}
|
||||
if attack.Delivery == "projectile" && len(w.Projectiles) >= w.Balance.CombatRules.MaxProjectiles {
|
||||
continue
|
||||
}
|
||||
if attack.Duration > 0 && len(w.Areas)+w.pendingAreas() >= w.Balance.CombatRules.MaxAreas {
|
||||
continue
|
||||
}
|
||||
shot := Projectile{ID: w.combatID("projectile"), Source: id, Player: false, Position: body(m.Entity.Position), Destination: body(aim), Attack: attack, Power: power * attack.Multiplier, Target: targetID}
|
||||
m.LastAttack = w.Age()
|
||||
if attack.Delivery == "projectile" {
|
||||
w.Projectiles[shot.ID] = &shot
|
||||
} else {
|
||||
shot.Position = body(aim)
|
||||
w.impact(shot, targetID)
|
||||
}
|
||||
w.dirty = true
|
||||
} else {
|
||||
w.mobStep(m, aim, speed, dt)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -89,6 +89,8 @@ func (w *World) RefreshStats(c *Character) {
|
||||
w.revalidateEquipment(c)
|
||||
c.View.Stats = w.statValues(c, true)
|
||||
w.refreshGathering(c)
|
||||
attack := w.playerAttack(c)
|
||||
c.View.Attack = &attack
|
||||
c.View.Entity.MaxHP = c.View.Stats["healthPoints"].Final
|
||||
c.View.Entity.HP = math.Min(c.View.Entity.HP, c.View.Entity.MaxHP)
|
||||
c.View.Mana = math.Max(0, math.Min(c.View.Mana, c.View.Stats["manaPoints"].Final))
|
||||
@@ -166,6 +168,9 @@ func (w *World) ApplyCatalog(catalog content.Catalog) error {
|
||||
w.Balance.Gathering = catalog.Gathering
|
||||
w.terrain.B.Gathering = catalog.Gathering
|
||||
}
|
||||
if catalog.Combat != nil {
|
||||
w.Balance.Combat = catalog.Combat
|
||||
}
|
||||
w.Balance.Titles = catalog.Titles
|
||||
w.Balance.Items = catalog.Items
|
||||
w.Balance.Stats = &catalog.Stats
|
||||
|
||||
+66
-131
@@ -15,6 +15,7 @@ import (
|
||||
)
|
||||
|
||||
type Character struct {
|
||||
AttackReadyAt float64 `json:"attackReadyAt"`
|
||||
JumpVelocity float64 `json:"jumpVelocity"`
|
||||
GatherReadyAt float64 `json:"gatherReadyAt"`
|
||||
|
||||
@@ -46,6 +47,16 @@ type Corpse struct {
|
||||
Items []p.ItemInstance `json:"items"`
|
||||
}
|
||||
type Mob struct {
|
||||
Definition *content.MobDefinition `json:"definition,omitempty"`
|
||||
Attack p.CombatAttack `json:"attack"`
|
||||
Loot content.LootTable `json:"loot"`
|
||||
Home *p.Vec3 `json:"home,omitempty"`
|
||||
Power float64 `json:"power"`
|
||||
Target string `json:"target"`
|
||||
Returning bool `json:"returning"`
|
||||
RespawnDelay float64 `json:"respawnDelay"`
|
||||
MinPlayerDistance float64 `json:"minPlayerDistance"`
|
||||
|
||||
Entity p.Entity `json:"entity"`
|
||||
HomeX int `json:"homeX"`
|
||||
HomeZ int `json:"homeZ"`
|
||||
@@ -53,11 +64,16 @@ type Mob struct {
|
||||
RespawnAt float64 `json:"respawnAt"`
|
||||
}
|
||||
type ResourceLayout struct {
|
||||
BiomeID string `json:"biomeId,omitempty"`
|
||||
Biome string `json:"biome"`
|
||||
Color *string `json:"color"`
|
||||
Resources []p.Entity `json:"resources"`
|
||||
}
|
||||
type World struct {
|
||||
Projectiles map[string]*Projectile `json:"projectiles,omitempty"`
|
||||
Areas map[string]*CombatArea `json:"areas,omitempty"`
|
||||
CombatSequence uint64 `json:"combatSequence"`
|
||||
|
||||
ResourceLayouts map[string]ResourceLayout `json:"resourceLayouts,omitempty"`
|
||||
|
||||
Version int `json:"version"`
|
||||
@@ -159,6 +175,19 @@ func (w *World) Restore(now time.Time) error {
|
||||
if w.ResourceLayouts == nil {
|
||||
w.ResourceLayouts = map[string]ResourceLayout{}
|
||||
}
|
||||
if w.Balance.Combat == nil || w.Balance.CombatRules == nil {
|
||||
b, e := content.Load()
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if w.Balance.Combat == nil {
|
||||
w.Balance.Combat = b.Combat
|
||||
}
|
||||
if w.Balance.CombatRules == nil {
|
||||
w.Balance.CombatRules = b.CombatRules
|
||||
}
|
||||
w.dirty = true
|
||||
}
|
||||
if err := w.Balance.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -188,6 +217,9 @@ func (w *World) Restore(now time.Time) error {
|
||||
c.MoveZ = 0
|
||||
c.View.ACK = 0
|
||||
}
|
||||
if err := w.restoreCombat(); err != nil {
|
||||
return err
|
||||
}
|
||||
return w.restoreCorpseEquipment()
|
||||
}
|
||||
func (w *World) Age() float64 {
|
||||
@@ -324,6 +356,7 @@ func (w *World) Import(c *Character) error {
|
||||
c.MoveZ = 0
|
||||
c.View.ACK = 0
|
||||
c.LastAttack = 0
|
||||
c.AttackReadyAt = 0
|
||||
c.LastGather = 0
|
||||
c.GatherReadyAt = 0
|
||||
c.JumpVelocity = 0
|
||||
@@ -383,7 +416,7 @@ func (w *World) chunk(x, z int) p.Chunk {
|
||||
if layout, ok := w.ResourceLayouts[key]; ok {
|
||||
c.Biome, c.Color, c.Resources = layout.Biome, layout.Color, layout.Resources
|
||||
} else {
|
||||
w.ResourceLayouts[key] = ResourceLayout{Biome: c.Biome, Color: c.Color, Resources: c.Resources}
|
||||
w.ResourceLayouts[key] = ResourceLayout{BiomeID: w.terrain.biome(x, z).ID, Biome: c.Biome, Color: c.Color, Resources: c.Resources}
|
||||
w.dirty = true
|
||||
}
|
||||
w.chunks[key] = c
|
||||
@@ -498,69 +531,27 @@ func (w *World) craft(c *Character, name string) error {
|
||||
w.dirty = true
|
||||
return nil
|
||||
}
|
||||
func (w *World) attack(c *Character, target string) error {
|
||||
if w.Age()-c.LastAttack < w.Balance.AttackCooldown {
|
||||
return errors.New("attack cooldown")
|
||||
}
|
||||
damage := c.View.Stats["meleeDamage"].Final
|
||||
if target == "boss" {
|
||||
if w.Phase != "cataclysm" || distance(c.View.Entity.Position, w.terrain.Position(0, 0)) > w.Balance.AttackRange+4 {
|
||||
return errors.New("boss out of reach")
|
||||
}
|
||||
if w.roll(c.View.Stats["criticalChance"].Final) {
|
||||
damage *= w.Balance.CriticalMultiplier
|
||||
}
|
||||
w.BossHP = math.Max(0, w.BossHP-damage)
|
||||
if w.BossHP == 0 {
|
||||
c.BossKills++
|
||||
w.grantXP(c, w.Balance.Progression.BossKillXP)
|
||||
w.evaluateTitles(c)
|
||||
w.Phase = "won"
|
||||
ended := w.now
|
||||
w.EndedAt = &ended
|
||||
// Stable order for simultaneous survivor milestone candidates.
|
||||
for _, survivor := range w.orderedCharacters() {
|
||||
if survivor.View.Entity.State == "alive" {
|
||||
survivor.WorldsSurvived++
|
||||
w.evaluateTitles(survivor)
|
||||
survivor.View.Entity.State = "eligible"
|
||||
survivor.MoveX = 0
|
||||
survivor.MoveZ = 0
|
||||
survivor.Message = "The world is saved. Passage is open."
|
||||
}
|
||||
func (w *World) damageBoss(c *Character, damage float64) {
|
||||
w.BossHP = math.Max(0, w.BossHP-damage)
|
||||
if w.BossHP == 0 {
|
||||
c.BossKills++
|
||||
w.grantXP(c, w.Balance.Progression.BossKillXP)
|
||||
w.evaluateTitles(c)
|
||||
w.Phase = "won"
|
||||
ended := w.now
|
||||
w.EndedAt = &ended
|
||||
// Stable order for simultaneous survivor milestone candidates.
|
||||
for _, survivor := range w.orderedCharacters() {
|
||||
if survivor.View.Entity.State == "alive" {
|
||||
survivor.WorldsSurvived++
|
||||
w.evaluateTitles(survivor)
|
||||
survivor.View.Entity.State = "eligible"
|
||||
survivor.MoveX = 0
|
||||
survivor.MoveZ = 0
|
||||
survivor.Message = "The world is saved. Passage is open."
|
||||
}
|
||||
}
|
||||
} else {
|
||||
m := w.Mobs[target]
|
||||
if m == nil || m.Entity.HP <= 0 || distance(c.View.Entity.Position, m.Entity.Position) > w.Balance.AttackRange {
|
||||
return errors.New("target out of reach")
|
||||
}
|
||||
if w.roll(c.View.Stats["criticalChance"].Final) {
|
||||
damage *= w.Balance.CriticalMultiplier
|
||||
}
|
||||
m.Entity.HP = math.Max(0, m.Entity.HP-damage)
|
||||
if m.Entity.HP == 0 {
|
||||
m.Entity.State = "dead"
|
||||
m.RespawnAt = w.Age() + w.Balance.MobRespawnSeconds
|
||||
c.View.Kills++
|
||||
c.WorldKills++
|
||||
c.View.Inventory["herb"] += w.yieldAmount(c.View.Stats["dropRate"].Final)
|
||||
for _, item := range w.Balance.Items {
|
||||
if w.roll(item.DropChance * c.View.Stats["dropRate"].Final / 100) {
|
||||
if err := w.grantItems(c, item.ID, 1); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
w.RefreshStats(c)
|
||||
w.grantXP(c, w.Balance.Progression.MobKillXP)
|
||||
}
|
||||
}
|
||||
c.LastAttack = w.Age()
|
||||
c.View.Skills["combat"] += w.Balance.SkillXpPerAction
|
||||
w.evaluateTitles(c)
|
||||
w.dirty = true
|
||||
return nil
|
||||
}
|
||||
func (w *World) kill(c *Character, reason string) {
|
||||
if c.View.Entity.State != "alive" {
|
||||
@@ -596,6 +587,8 @@ func (w *World) kill(c *Character, reason string) {
|
||||
// Operator changes use the same simulation and persistence path as gameplay.
|
||||
func (w *World) Control(op, target, value, reason string) error {
|
||||
switch op {
|
||||
case "spawn-mobs":
|
||||
return w.SpawnMobs(target, value)
|
||||
case "close-admissions", "open-admissions":
|
||||
if w.Phase == "won" || w.Phase == "lost" {
|
||||
return errors.New("world has ended")
|
||||
@@ -718,6 +711,7 @@ func (w *World) Advance(now time.Time, dt float64) {
|
||||
}
|
||||
}
|
||||
w.updateMobs(active, dt)
|
||||
w.updateCombat(dt)
|
||||
if w.Phase == "cataclysm" {
|
||||
if w.Age()-w.BossLastAttack >= w.Balance.BossCooldown {
|
||||
for _, c := range characters {
|
||||
@@ -759,76 +753,6 @@ func (w *World) Advance(now time.Time, dt float64) {
|
||||
}
|
||||
}
|
||||
}
|
||||
func (w *World) ensureMob(ch p.Chunk) {
|
||||
id := "m:" + ch.Key
|
||||
if _, ok := w.Mobs[id]; ok {
|
||||
return
|
||||
}
|
||||
x, z := (float64(ch.X)+0.55)*ch.Size, (float64(ch.Z)+0.55)*ch.Size
|
||||
if math.Hypot(x, z) > w.Balance.WorldRadius {
|
||||
return
|
||||
}
|
||||
hp := w.Balance.MobHp * (1 + w.Age()/86400*w.Balance.MobScalePerDay)
|
||||
w.Mobs[id] = &Mob{Entity: p.Entity{ID: id, Kind: "sentinel", Name: "Ash sentinel", Position: w.terrain.Position(x, z), HP: hp, MaxHP: hp, State: "alive"}, HomeX: int(ch.X), HomeZ: int(ch.Z)}
|
||||
}
|
||||
func (w *World) updateMobs(active map[string]bool, dt float64) {
|
||||
mobIDs := make([]string, 0, len(w.Mobs))
|
||||
for id := range w.Mobs {
|
||||
mobIDs = append(mobIDs, id)
|
||||
}
|
||||
sort.Strings(mobIDs)
|
||||
characters := w.orderedCharacters()
|
||||
for _, id := range mobIDs {
|
||||
m := w.Mobs[id]
|
||||
key := Key(m.HomeX, m.HomeZ)
|
||||
if !active[key] {
|
||||
if m.Entity.HP == m.Entity.MaxHP || (m.Entity.HP <= 0 && w.Age() >= m.RespawnAt) {
|
||||
delete(w.Mobs, id)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if m.Entity.HP <= 0 {
|
||||
if w.Age() >= m.RespawnAt {
|
||||
m.Entity.HP = w.Balance.MobHp * (1 + w.Age()/86400*w.Balance.MobScalePerDay)
|
||||
m.Entity.MaxHP = m.Entity.HP
|
||||
m.Entity.State = "alive"
|
||||
}
|
||||
continue
|
||||
}
|
||||
var target *Character
|
||||
nearest := w.Balance.MobAggroRange
|
||||
for _, c := range characters {
|
||||
if !c.Online || c.View.Entity.State != "alive" || c.Sheltered {
|
||||
continue
|
||||
}
|
||||
d := distance(c.View.Entity.Position, m.Entity.Position)
|
||||
if d < nearest {
|
||||
nearest = d
|
||||
target = c
|
||||
}
|
||||
}
|
||||
if target == nil {
|
||||
continue
|
||||
}
|
||||
if nearest <= w.Balance.MobAttackRange {
|
||||
if w.Age()-m.LastAttack >= w.Balance.MobCooldown {
|
||||
w.damageCharacter(target, w.Balance.MobDamage*(1+w.Age()/86400*w.Balance.MobScalePerDay))
|
||||
m.LastAttack = w.Age()
|
||||
w.dirty = true
|
||||
if target.View.Entity.HP <= 0 {
|
||||
w.kill(target, "An ash sentinel ended this character's journey.")
|
||||
}
|
||||
}
|
||||
} else {
|
||||
pos, to := m.Entity.Position, target.View.Entity.Position
|
||||
step := math.Min(nearest, w.Balance.MobSpeed*dt)
|
||||
x, z := pos.X+(to.X-pos.X)/nearest*step, pos.Z+(to.Z-pos.Z)/nearest*step
|
||||
if ChunkCoord(x, w.Balance.ChunkSize) == m.HomeX && ChunkCoord(z, w.Balance.ChunkSize) == m.HomeZ {
|
||||
m.Entity.Position = w.terrain.Position(x, z)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
func (w *World) Snapshot(id string, known map[string]bool) p.Snapshot {
|
||||
c := w.Characters[id]
|
||||
s := p.Snapshot{Type: "snapshot", Version: 1, Tick: w.Tick, World: w.Info(), Self: c.View, Message: c.Message, Entities: []p.Entity{}, Chunks: []p.Chunk{}, ChunkKeys: []string{}, UnavailableResources: []string{}}
|
||||
@@ -892,6 +816,17 @@ func (w *World) Snapshot(id string, known map[string]bool) p.Snapshot {
|
||||
if w.Phase == "cataclysm" && visible(w.terrain.Position(0, 0)) {
|
||||
s.Entities = append(s.Entities, p.Entity{ID: "boss", Kind: "boss", Name: "The Harbinger", HP: w.BossHP, MaxHP: w.Balance.BossHp, Position: w.terrain.Position(0, 0), State: "alive"})
|
||||
}
|
||||
for _, shot := range w.Projectiles {
|
||||
if visible(shot.Position) {
|
||||
s.Entities = append(s.Entities, p.Entity{ID: shot.ID, Kind: "projectile", Name: shot.Attack.Name, Position: shot.Position, State: shot.Attack.Effect, HP: 1, MaxHP: 1})
|
||||
}
|
||||
}
|
||||
for _, area := range w.Areas {
|
||||
if visible(area.Position) {
|
||||
radius := area.Attack.Radius
|
||||
s.Entities = append(s.Entities, p.Entity{ID: area.ID, Kind: "area", Name: area.Attack.Name, Position: area.Position, State: area.Attack.Effect, Radius: &radius, HP: 1, MaxHP: 1})
|
||||
}
|
||||
}
|
||||
sort.Slice(s.Entities, func(i, j int) bool { return s.Entities[i].ID < s.Entities[j].ID })
|
||||
return s
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ type Protocol struct {
|
||||
}
|
||||
|
||||
type ContentCatalog struct {
|
||||
Combat *CombatContent `json:"combat,omitempty"`
|
||||
EffectSets []EffectSet `json:"effectSets,omitempty"`
|
||||
Gathering *GatheringContent `json:"gathering,omitempty"`
|
||||
Items []ItemDefinition `json:"items"`
|
||||
@@ -20,6 +21,78 @@ type ContentCatalog struct {
|
||||
Version int64 `json:"version"`
|
||||
}
|
||||
|
||||
type CombatContent struct {
|
||||
Attacks []CombatAttack `json:"attacks"`
|
||||
Loot []LootTable `json:"loot"`
|
||||
Mobs []MobDefinition `json:"mobs"`
|
||||
Spawns []MobSpawn `json:"spawns"`
|
||||
}
|
||||
|
||||
type CombatAttack struct {
|
||||
Cooldown float64 `json:"cooldown"`
|
||||
Delivery string `json:"delivery"`
|
||||
Description string `json:"description"`
|
||||
Duration float64 `json:"duration"`
|
||||
Effect string `json:"effect"`
|
||||
ID string `json:"id"`
|
||||
Interval float64 `json:"interval"`
|
||||
Multiplier float64 `json:"multiplier"`
|
||||
Name string `json:"name"`
|
||||
Radius float64 `json:"radius"`
|
||||
Range float64 `json:"range"`
|
||||
Speed float64 `json:"speed"`
|
||||
Stamina float64 `json:"stamina"`
|
||||
Stat string `json:"stat"`
|
||||
}
|
||||
|
||||
type LootTable struct {
|
||||
Description string `json:"description"`
|
||||
Entries []LootEntry `json:"entries"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type LootEntry struct {
|
||||
Amount int64 `json:"amount"`
|
||||
Chance float64 `json:"chance"`
|
||||
Group string `json:"group"`
|
||||
Item string `json:"item"`
|
||||
Weight int64 `json:"weight"`
|
||||
}
|
||||
|
||||
type MobDefinition struct {
|
||||
AggroRange float64 `json:"aggroRange"`
|
||||
AttackID string `json:"attackId"`
|
||||
Behavior string `json:"behavior"`
|
||||
Damage float64 `json:"damage"`
|
||||
Defence float64 `json:"defence"`
|
||||
Description string `json:"description"`
|
||||
HP float64 `json:"hp"`
|
||||
ID string `json:"id"`
|
||||
LeashRange float64 `json:"leashRange"`
|
||||
Level int64 `json:"level"`
|
||||
LootID string `json:"lootId"`
|
||||
Model string `json:"model"`
|
||||
Name string `json:"name"`
|
||||
ScalePerDay float64 `json:"scalePerDay"`
|
||||
Speed float64 `json:"speed"`
|
||||
XP int64 `json:"xp"`
|
||||
}
|
||||
|
||||
type MobSpawn struct {
|
||||
Biomes []string `json:"biomes"`
|
||||
Count int64 `json:"count"`
|
||||
Description string `json:"description"`
|
||||
ID string `json:"id"`
|
||||
MinPlayerDistance float64 `json:"minPlayerDistance"`
|
||||
MobID string `json:"mobId"`
|
||||
Name string `json:"name"`
|
||||
Radius float64 `json:"radius"`
|
||||
Respawn float64 `json:"respawn"`
|
||||
X float64 `json:"x"`
|
||||
Z float64 `json:"z"`
|
||||
}
|
||||
|
||||
type EffectSet struct {
|
||||
Description string `json:"description"`
|
||||
ID string `json:"id"`
|
||||
@@ -83,6 +156,7 @@ type GatheringSkill struct {
|
||||
}
|
||||
|
||||
type ItemDefinition struct {
|
||||
AttackID *string `json:"attackId,omitempty"`
|
||||
Description string `json:"description"`
|
||||
DropChance float64 `json:"dropChance"`
|
||||
ID string `json:"id"`
|
||||
@@ -133,6 +207,7 @@ type TitleEffects struct {
|
||||
}
|
||||
|
||||
type ContentChange struct {
|
||||
Attack *CombatAttackDraft `json:"attack,omitempty"`
|
||||
Biome *BiomeDefinitionDraft `json:"biome,omitempty"`
|
||||
Consumable *GatheringConsumableDraft `json:"consumable,omitempty"`
|
||||
EffectSet *EffectSetDraft `json:"effectSet,omitempty"`
|
||||
@@ -141,15 +216,35 @@ type ContentChange struct {
|
||||
GatheringSkill *GatheringSkillDraft `json:"gatheringSkill,omitempty"`
|
||||
ID string `json:"id"`
|
||||
Item *ItemDraft `json:"item,omitempty"`
|
||||
Loot *LootTableDraft `json:"loot,omitempty"`
|
||||
Mob *MobDefinitionDraft `json:"mob,omitempty"`
|
||||
Op string `json:"op"`
|
||||
Reason string `json:"reason"`
|
||||
RequirementSet *RequirementSetDraft `json:"requirementSet,omitempty"`
|
||||
RequirementSetIDS []string `json:"requirementSetIds,omitempty"`
|
||||
Resource *ResourceDefinitionDraft `json:"resource,omitempty"`
|
||||
Spawn *MobSpawnDraft `json:"spawn,omitempty"`
|
||||
Stats *ContentStatsRules `json:"stats,omitempty"`
|
||||
Title *TitleDraft `json:"title,omitempty"`
|
||||
}
|
||||
|
||||
type CombatAttackDraft struct {
|
||||
Cooldown float64 `json:"cooldown"`
|
||||
Delivery string `json:"delivery"`
|
||||
Description string `json:"description"`
|
||||
Duration float64 `json:"duration"`
|
||||
Effect string `json:"effect"`
|
||||
ID *string `json:"id,omitempty"`
|
||||
Interval float64 `json:"interval"`
|
||||
Multiplier float64 `json:"multiplier"`
|
||||
Name string `json:"name"`
|
||||
Radius float64 `json:"radius"`
|
||||
Range float64 `json:"range"`
|
||||
Speed float64 `json:"speed"`
|
||||
Stamina float64 `json:"stamina"`
|
||||
Stat string `json:"stat"`
|
||||
}
|
||||
|
||||
type BiomeDefinitionDraft struct {
|
||||
Color string `json:"color"`
|
||||
Description string `json:"description"`
|
||||
@@ -183,6 +278,7 @@ type GatheringSkillDraft struct {
|
||||
}
|
||||
|
||||
type ItemDraft struct {
|
||||
AttackID *string `json:"attackId,omitempty"`
|
||||
Description string `json:"description"`
|
||||
DropChance float64 `json:"dropChance"`
|
||||
ID *string `json:"id,omitempty"`
|
||||
@@ -193,6 +289,32 @@ type ItemDraft struct {
|
||||
Weight float64 `json:"weight"`
|
||||
}
|
||||
|
||||
type LootTableDraft struct {
|
||||
Description string `json:"description"`
|
||||
Entries []LootEntry `json:"entries"`
|
||||
ID *string `json:"id,omitempty"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type MobDefinitionDraft struct {
|
||||
AggroRange float64 `json:"aggroRange"`
|
||||
AttackID string `json:"attackId"`
|
||||
Behavior string `json:"behavior"`
|
||||
Damage float64 `json:"damage"`
|
||||
Defence float64 `json:"defence"`
|
||||
Description string `json:"description"`
|
||||
HP float64 `json:"hp"`
|
||||
ID *string `json:"id,omitempty"`
|
||||
LeashRange float64 `json:"leashRange"`
|
||||
Level int64 `json:"level"`
|
||||
LootID string `json:"lootId"`
|
||||
Model string `json:"model"`
|
||||
Name string `json:"name"`
|
||||
ScalePerDay float64 `json:"scalePerDay"`
|
||||
Speed float64 `json:"speed"`
|
||||
XP int64 `json:"xp"`
|
||||
}
|
||||
|
||||
type RequirementSetDraft struct {
|
||||
Description string `json:"description"`
|
||||
ID *string `json:"id,omitempty"`
|
||||
@@ -216,6 +338,20 @@ type ResourceDefinitionDraft struct {
|
||||
XP int64 `json:"xp"`
|
||||
}
|
||||
|
||||
type MobSpawnDraft struct {
|
||||
Biomes []string `json:"biomes"`
|
||||
Count int64 `json:"count"`
|
||||
Description string `json:"description"`
|
||||
ID *string `json:"id,omitempty"`
|
||||
MinPlayerDistance float64 `json:"minPlayerDistance"`
|
||||
MobID string `json:"mobId"`
|
||||
Name string `json:"name"`
|
||||
Radius float64 `json:"radius"`
|
||||
Respawn float64 `json:"respawn"`
|
||||
X float64 `json:"x"`
|
||||
Z float64 `json:"z"`
|
||||
}
|
||||
|
||||
type TitleDraft struct {
|
||||
Description string `json:"description"`
|
||||
Effects TitleEffects `json:"effects"`
|
||||
@@ -272,16 +408,18 @@ type Chunk struct {
|
||||
}
|
||||
|
||||
type Entity struct {
|
||||
HP float64 `json:"hp"`
|
||||
ID string `json:"id"`
|
||||
Kind string `json:"kind"`
|
||||
MaxHP float64 `json:"maxHp"`
|
||||
Name string `json:"name"`
|
||||
Position Vec3 `json:"position"`
|
||||
RequiredLevel *int64 `json:"requiredLevel,omitempty"`
|
||||
ResourceID *string `json:"resourceId,omitempty"`
|
||||
SkillID *string `json:"skillId,omitempty"`
|
||||
State string `json:"state"`
|
||||
HP float64 `json:"hp"`
|
||||
ID string `json:"id"`
|
||||
Kind string `json:"kind"`
|
||||
MaxHP float64 `json:"maxHp"`
|
||||
Model *string `json:"model,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Position Vec3 `json:"position"`
|
||||
Radius *float64 `json:"radius,omitempty"`
|
||||
RequiredLevel *int64 `json:"requiredLevel,omitempty"`
|
||||
ResourceID *string `json:"resourceId,omitempty"`
|
||||
SkillID *string `json:"skillId,omitempty"`
|
||||
State string `json:"state"`
|
||||
}
|
||||
|
||||
type Vec3 struct {
|
||||
@@ -302,6 +440,7 @@ type GatheringRisk struct {
|
||||
type Character struct {
|
||||
ACK int64 `json:"ack"`
|
||||
AllocatedStats map[string]int64 `json:"allocatedStats"`
|
||||
Attack *CombatAttack `json:"attack,omitempty"`
|
||||
CarryWeight float64 `json:"carryWeight"`
|
||||
Consumables []GatheringConsumable `json:"consumables,omitempty"`
|
||||
Entity Entity `json:"entity"`
|
||||
@@ -357,6 +496,7 @@ type TimedGatheringEffect struct {
|
||||
}
|
||||
|
||||
type ItemInstance struct {
|
||||
Attack *CombatAttack `json:"attack,omitempty"`
|
||||
DefinitionID string `json:"definitionId"`
|
||||
Description string `json:"description"`
|
||||
Equippable bool `json:"equippable"`
|
||||
|
||||
@@ -17,6 +17,10 @@ var ErrCatalogInvalid = errors.New("invalid catalog change")
|
||||
var catalogRequestID = regexp.MustCompile(`^[a-f0-9-]{32,36}$`)
|
||||
|
||||
type CatalogChange struct {
|
||||
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"`
|
||||
@@ -42,7 +46,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.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.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 {
|
||||
@@ -106,6 +110,13 @@ func decodeCatalog(version int64, raw string) (content.Catalog, error) {
|
||||
}
|
||||
catalog.Gathering = b.Gathering
|
||||
}
|
||||
if catalog.Combat == nil {
|
||||
b, e := content.Load()
|
||||
if e != nil {
|
||||
return catalog, e
|
||||
}
|
||||
catalog.Combat = b.Combat
|
||||
}
|
||||
return catalog, catalog.Validate()
|
||||
}
|
||||
func (d *DB) Catalog(ctx context.Context) (content.Catalog, error) {
|
||||
@@ -135,12 +146,20 @@ func (c CatalogChange) validate() error {
|
||||
}
|
||||
valid := false
|
||||
count := 0
|
||||
for _, present := range []bool{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.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-attack":
|
||||
valid = c.Attack != nil
|
||||
case "create-mob":
|
||||
valid = c.Mob != nil
|
||||
case "create-loot":
|
||||
valid = c.Loot != nil
|
||||
case "create-spawn":
|
||||
valid = c.Spawn != nil
|
||||
case "create-gathering-skill":
|
||||
valid = c.GatheringSkill != nil
|
||||
case "create-resource":
|
||||
|
||||
@@ -35,6 +35,18 @@ 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.Attack != nil {
|
||||
resolved.Attack.ID = ""
|
||||
}
|
||||
if resolved.Mob != nil {
|
||||
resolved.Mob.ID = ""
|
||||
}
|
||||
if resolved.Loot != nil {
|
||||
resolved.Loot.ID = ""
|
||||
}
|
||||
if resolved.Spawn != nil {
|
||||
resolved.Spawn.ID = ""
|
||||
}
|
||||
if resolved.GatheringSkill != nil {
|
||||
resolved.GatheringSkill.ID = ""
|
||||
}
|
||||
@@ -85,7 +97,48 @@ func buildCatalog(c content.Catalog, change CatalogChange) (content.Catalog, str
|
||||
}
|
||||
gathering := *c.Gathering
|
||||
c.Gathering = &gathering
|
||||
if c.Combat == nil {
|
||||
b, e := content.Load()
|
||||
if e != nil {
|
||||
return invalid(e)
|
||||
}
|
||||
c.Combat = b.Combat
|
||||
}
|
||||
combat := *c.Combat
|
||||
c.Combat = &combat
|
||||
switch change.Op {
|
||||
case "create-attack":
|
||||
v := *change.Attack
|
||||
if v.ID == "" {
|
||||
v.ID = "attack_" + game.ID()
|
||||
}
|
||||
resolved.Attack = &v
|
||||
c.Combat.Attacks = append(slices.Clone(c.Combat.Attacks), v)
|
||||
target = v.ID
|
||||
case "create-mob":
|
||||
v := *change.Mob
|
||||
if v.ID == "" {
|
||||
v.ID = "mob_" + game.ID()
|
||||
}
|
||||
resolved.Mob = &v
|
||||
c.Combat.Mobs = append(slices.Clone(c.Combat.Mobs), v)
|
||||
target = v.ID
|
||||
case "create-loot":
|
||||
v := *change.Loot
|
||||
if v.ID == "" {
|
||||
v.ID = "loot_" + game.ID()
|
||||
}
|
||||
resolved.Loot = &v
|
||||
c.Combat.Loot = append(slices.Clone(c.Combat.Loot), v)
|
||||
target = v.ID
|
||||
case "create-spawn":
|
||||
v := *change.Spawn
|
||||
if v.ID == "" {
|
||||
v.ID = "spawn_" + game.ID()
|
||||
}
|
||||
resolved.Spawn = &v
|
||||
c.Combat.Spawns = append(slices.Clone(c.Combat.Spawns), v)
|
||||
target = v.ID
|
||||
case "create-gathering-skill":
|
||||
v := *change.GatheringSkill
|
||||
if v.ID == "" {
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"aeternalis/server/content"
|
||||
"aeternalis/server/internal/game"
|
||||
"context"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCombatCatalogReferencesAndReplay(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db, err := Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "combat.db")))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
catalog, _ := db.Catalog(ctx)
|
||||
publish := func(change CatalogChange) string {
|
||||
t.Helper()
|
||||
change.ID = game.ID()
|
||||
change.ExpectedVersion = catalog.Version
|
||||
change.Reason = "Combat content test"
|
||||
if _, err := db.PreviewCatalog(ctx, change); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, err := db.PublishCatalog(ctx, "admin", change)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
again, err := db.PublishCatalog(ctx, "admin", change)
|
||||
if err != nil || r != again {
|
||||
t.Fatal("changed replay", err)
|
||||
}
|
||||
catalog, _ = db.Catalog(ctx)
|
||||
return r.ID
|
||||
}
|
||||
attack := catalog.Combat.Attacks[0]
|
||||
attack.ID = ""
|
||||
attack.Name = "Test shot"
|
||||
id := publish(CatalogChange{Op: "create-attack", Attack: &attack})
|
||||
loot := publish(CatalogChange{Op: "create-loot", Loot: &content.LootTable{Name: "Loot", Entries: []content.LootEntry{{Item: "herb", Amount: 1, Chance: 100, Weight: 1}}}})
|
||||
mob := catalog.Combat.Mobs[0]
|
||||
mob.ID = ""
|
||||
mob.AttackID = id
|
||||
mob.LootID = loot
|
||||
mid := publish(CatalogChange{Op: "create-mob", Mob: &mob})
|
||||
publish(CatalogChange{Op: "create-spawn", Spawn: &content.MobSpawn{Name: "Region", MobID: mid, Count: 2, Respawn: 60, Biomes: []string{"forest"}}})
|
||||
publish(CatalogChange{Op: "create-item", Item: &content.ItemDefinition{Name: "Bow", Slot: "weapon", Requirements: content.ItemRequirements{Level: 1}, AttackID: id}})
|
||||
attack.Duration = 2
|
||||
attack.Radius = 0
|
||||
bad := CatalogChange{ID: game.ID(), ExpectedVersion: catalog.Version, Reason: "Invalid area test", Op: "create-attack", Attack: &attack}
|
||||
if _, err := db.PublishCatalog(ctx, "admin", bad); !errors.Is(err, ErrCatalogInvalid) {
|
||||
t.Fatal("invalid area accepted", err)
|
||||
}
|
||||
mob.AttackID = "missing"
|
||||
bad.Op = "create-mob"
|
||||
bad.Attack = nil
|
||||
bad.Mob = &mob
|
||||
if _, err := db.PublishCatalog(ctx, "admin", bad); !errors.Is(err, ErrCatalogInvalid) {
|
||||
t.Fatal("missing attack reference accepted", err)
|
||||
}
|
||||
}
|
||||
@@ -101,6 +101,11 @@ func (h *HTTP) portalRoutes(mux *http.ServeMux) {
|
||||
return
|
||||
}
|
||||
switch req.Op {
|
||||
case "spawn-mobs":
|
||||
if _, _, _, err := game.ParseMobSpawn(req.Value); err != nil {
|
||||
fail(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
case "grant-item", "remove-item":
|
||||
if _, _, err := game.ParseItemChange(req.Value); err != nil {
|
||||
fail(w, 400, err.Error())
|
||||
|
||||
@@ -119,6 +119,41 @@ func TestControlAuthorizationAndExecution(t *testing.T) {
|
||||
if len(commands) != 1 || commands[0].Status != "completed" {
|
||||
t.Fatal("command not audited")
|
||||
}
|
||||
spawn := `{"id":"` + game.ID() + `","worldId":"control-test","op":"spawn-mobs","target":"ash_guard","value":"2,30,30","reason":"Combat playtest"}`
|
||||
before := len(w.Mobs)
|
||||
for i := 0; i < 2; i++ {
|
||||
if request("POST", "/api/control/commands", spawn, token, server.URL) != 202 {
|
||||
t.Fatal("spawn command/retry not accepted")
|
||||
}
|
||||
if err = svc.controls(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(w.Mobs) != before+2 {
|
||||
t.Fatal("spawn retry duplicated mobs")
|
||||
}
|
||||
}
|
||||
if err = lease.Release(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nextLease, snapshot, err := db.Acquire(ctx, w)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer nextLease.Release(ctx)
|
||||
var restarted game.World
|
||||
if err = json.Unmarshal(snapshot, &restarted); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = restarted.Restore(time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = NewService(&restarted, nextLease).controls(ctx); err != nil || len(restarted.Mobs) != before+2 {
|
||||
t.Fatal("spawn execution was not durable/retry safe", err)
|
||||
}
|
||||
commands, err = db.Commands(ctx, w.ID, false)
|
||||
if err != nil || len(commands) != 2 || commands[0].Status != "completed" || commands[1].Status != "completed" {
|
||||
t.Fatal("spawn audit not committed with world", err)
|
||||
}
|
||||
bad := `{"id":"` + game.ID() + `","worldId":"control-test","op":"end-world","reason":"maintenance window"}`
|
||||
if request("POST", "/api/control/commands", bad, token, server.URL) != 400 {
|
||||
t.Fatal("destructive action without confirmation")
|
||||
|
||||
Reference in New Issue
Block a user