Add ranged combat area effects and admin-authored mobs

This commit is contained in:
dingo
2026-09-09 05:26:31 -04:00
parent 7a4c6c9e9b
commit 0b4eaa153c
29 changed files with 2220 additions and 181 deletions
+452
View File
@@ -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 = &copy
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
}
+252
View File
@@ -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")
}
}
+8
View File
@@ -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...)
+324
View File
@@ -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)
}
}
}
+5
View File
@@ -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
View File
@@ -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
}