Build playable Aeternalis foundation and GitOps deployment pipeline

This commit is contained in:
dingo
2026-09-05 12:52:51 -04:00
parent 93703b20bc
commit ff87b8a544
66 changed files with 6567 additions and 0 deletions
+69
View File
@@ -0,0 +1,69 @@
package game
import (
"fmt"
"math"
"math/rand/v2"
"aeternalis/server/content"
p "aeternalis/server/internal/protocol"
"github.com/ojrac/opensimplex-go"
)
const GeneratorVersion = 1
type Terrain struct {
Seed int64
B content.Balance
noise opensimplex.Noise
}
func NewTerrain(seed int64, b content.Balance) *Terrain {
return &Terrain{seed, b, opensimplex.New(seed)}
}
func (t *Terrain) rawHeight(x, z float64) float64 {
// A low, flat arrival clearing blends into broad hills and fine detail.
d := math.Min(1, math.Hypot(x, z)/55)
return (t.noise.Eval2(x/220, z/220)*17 + t.noise.Eval2(x/55, z/55)*3) * d
}
func ChunkCoord(v, size float64) int { return int(math.Floor(v / size)) }
func Key(x, z int) string { return fmt.Sprintf("%d:%d", x, z) }
// Height uses the same triangle split as the transmitted terrain mesh.
func (t *Terrain) Height(x, z float64) float64 {
step := t.B.ChunkSize / float64(t.B.TerrainResolution)
ix, iz := math.Floor(x/step), math.Floor(z/step)
fx, fz := x/step-ix, z/step-iz
a, b := t.rawHeight(ix*step, iz*step), t.rawHeight((ix+1)*step, iz*step)
c, d := t.rawHeight(ix*step, (iz+1)*step), t.rawHeight((ix+1)*step, (iz+1)*step)
if fx+fz <= 1 {
return a + (b-a)*fx + (c-a)*fz
}
return d + (c-d)*(1-fx) + (b-d)*(1-fz)
}
func (t *Terrain) Position(x, z float64) p.Vec3 { return p.Vec3{X: x, Y: t.Height(x, z), Z: z} }
func (t *Terrain) Chunk(x, z int) p.Chunk {
c := p.Chunk{Key: Key(x, z), X: int64(x), Z: int64(z), Size: t.B.ChunkSize, Resolution: int64(t.B.TerrainResolution), Biome: "highlands", Heights: []float64{}, Resources: []p.Entity{}}
for iz := 0; iz <= t.B.TerrainResolution; iz++ {
for ix := 0; ix <= t.B.TerrainResolution; ix++ {
c.Heights = append(c.Heights, t.rawHeight(float64(x)*c.Size+float64(ix)*c.Size/float64(c.Resolution), float64(z)*c.Size+float64(iz)*c.Size/float64(c.Resolution)))
}
}
rng := rand.New(rand.NewPCG(uint64(t.Seed)^uint64(int64(x)*73856093), uint64(int64(z)*19349663)^0xa341316c))
kinds := []string{"tree", "ore", "herb"}
for i := 0; i < t.B.ResourcesPerChunk; i++ {
px, pz := (float64(x)+0.08+rng.Float64()*0.84)*c.Size, (float64(z)+0.08+rng.Float64()*0.84)*c.Size
if math.Hypot(px, pz) > t.B.WorldRadius || math.Hypot(px, pz) < 10 {
continue
}
kind := kinds[i%len(kinds)]
c.Resources = append(c.Resources, p.Entity{ID: fmt.Sprintf("r:%d:%d:%d", x, z, i), Kind: kind, Name: kind, Position: t.Position(px, pz), HP: 1, MaxHP: 1, State: "available"})
}
// Arrival resources make the first crafting loop reachable without aimless travel.
if x == 0 && z == 0 {
for i, k := range kinds {
c.Resources = append(c.Resources, p.Entity{ID: "arrival:" + k, Kind: k, Name: k, Position: t.Position(12+float64(i)*5, 12), HP: 1, MaxHP: 1, State: "available"})
}
}
return c
}
+648
View File
@@ -0,0 +1,648 @@
package game
import (
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"math"
"sort"
"time"
"aeternalis/server/content"
p "aeternalis/server/internal/protocol"
)
type Character struct {
View p.Character `json:"view"`
Account string `json:"account"`
Day string `json:"day"`
DailySeconds float64 `json:"dailySeconds"`
ReturnPosition *p.Vec3 `json:"returnPosition,omitempty"`
Sheltered bool `json:"sheltered"`
LastAttack float64 `json:"lastAttack"`
LastGather float64 `json:"lastGather"`
Online bool `json:"-"`
MoveX float64 `json:"-"`
MoveZ float64 `json:"-"`
LastMove time.Time `json:"-"`
Message string `json:"-"`
}
type Corpse struct {
Entity p.Entity `json:"entity"`
Inventory map[string]int64 `json:"inventory"`
}
type Mob struct {
Entity p.Entity `json:"entity"`
HomeX int `json:"homeX"`
HomeZ int `json:"homeZ"`
LastAttack float64 `json:"lastAttack"`
RespawnAt float64 `json:"respawnAt"`
}
type World struct {
Version int `json:"version"`
ID string `json:"id"`
Seed int64 `json:"seed"`
CreatedAt time.Time `json:"createdAt"`
EndedAt *time.Time `json:"endedAt,omitempty"`
Phase string `json:"phase"`
Tick int64 `json:"tick"`
BossHP float64 `json:"bossHp"`
BossLastAttack float64 `json:"bossLastAttack"`
Characters map[string]*Character `json:"characters"`
Corpses map[string]*Corpse `json:"corpses"`
Depleted map[string]float64 `json:"depleted"`
Mobs map[string]*Mob `json:"mobs"`
Balance content.Balance `json:"balance"`
terrain *Terrain
chunks map[string]p.Chunk
now time.Time
dirty bool
}
func ID() string {
var b [16]byte
if _, err := rand.Read(b[:]); err != nil {
panic(err)
}
return hex.EncodeToString(b[:])
}
func New(id string, seed int64, now time.Time, b content.Balance) *World {
w := &World{Version: GeneratorVersion, ID: id, Seed: seed, CreatedAt: now, Phase: "gathering", BossHP: b.BossHp, Characters: map[string]*Character{}, Corpses: map[string]*Corpse{}, Depleted: map[string]float64{}, Mobs: map[string]*Mob{}, Balance: b}
_ = w.Restore(now)
return w
}
func (w *World) Restore(now time.Time) error {
if w.Version != GeneratorVersion {
return errors.New("unsupported persisted generator version")
}
if err := w.Balance.Validate(); err != nil {
return err
}
if w.Characters == nil || w.Mobs == nil || w.Corpses == nil || w.Depleted == nil {
return errors.New("invalid world snapshot")
}
w.terrain = NewTerrain(w.Seed, w.Balance)
w.chunks = map[string]p.Chunk{}
w.now = now
for _, c := range w.Characters {
c.Online = false
c.MoveX = 0
c.MoveZ = 0
c.View.ACK = 0
}
return nil
}
func (w *World) Age() float64 {
now := w.now
if w.EndedAt != nil {
now = *w.EndedAt
}
return math.Max(0, now.Sub(w.CreatedAt).Seconds())
}
func (w *World) Dirty() bool { return w.dirty }
func (w *World) Saved() { w.dirty = false }
func (w *World) SafeRadius() float64 {
if w.Phase == "gathering" {
return w.Balance.WorldRadius
}
if w.Phase == "lost" {
return 0
}
return math.Max(0, w.Balance.WorldRadius*(1-(w.Age()-w.Balance.SeasonSeconds)/w.Balance.CollapseSeconds))
}
func (w *World) Info() p.WorldInfo {
online := int64(0)
for _, c := range w.Characters {
if c.Online {
online++
}
}
return p.WorldInfo{ID: w.ID, Seed: w.Seed, Phase: w.Phase, AgeSeconds: w.Age(), BossInSeconds: math.Max(0, w.Balance.SeasonSeconds-w.Age()), CollapseInSeconds: math.Max(0, w.Balance.SeasonSeconds+w.Balance.CollapseSeconds-w.Age()), SafeRadius: w.SafeRadius(), Radius: w.Balance.WorldRadius, Online: online, Capacity: int64(w.Balance.MaxPlayers), BossHP: w.BossHP, BossMaxHP: w.Balance.BossHp}
}
func (w *World) ForAccount(account string) *Character {
for _, c := range w.Characters {
if c.Account == account {
return c
}
}
return nil
}
func (w *World) spawn(exclude string) (p.Vec3, error) {
for i := 0; i < 4096; i++ {
radius := math.Sqrt(float64(i)) * w.Balance.SpawnSeparation * 0.6
angle := float64(i) * 2.399963229728653
pos := w.terrain.Position(math.Cos(angle)*radius, math.Sin(angle)*radius)
if radius > w.Balance.WorldRadius-32 {
break
}
clear := true
for id, c := range w.Characters {
if id != exclude && c.View.Entity.State != "dead" && distance(pos, c.View.Entity.Position) < w.Balance.SpawnSeparation {
clear = false
break
}
}
if clear {
return pos, nil
}
}
return p.Vec3{}, errors.New("no separated spawn available")
}
func (w *World) Join(account, name string) (*Character, error) {
if c := w.ForAccount(account); c != nil {
return c, nil
}
if w.Phase != "gathering" {
return nil, errors.New("this world is closed to new arrivals")
}
if len(w.Characters) >= w.Balance.MaxPlayers {
return nil, errors.New("world capacity reached")
}
pos, err := w.spawn("")
if err != nil {
return nil, err
}
c := &Character{Account: account, Day: w.now.UTC().Format(time.DateOnly), View: p.Character{Entity: p.Entity{ID: ID(), Kind: "player", Name: name, Position: pos, HP: w.Balance.PlayerHp, MaxHP: w.Balance.PlayerHp, State: "alive"}, Inventory: map[string]int64{}, Skills: map[string]int64{}, RemainingSeconds: w.Balance.DailyPlaySeconds}}
for k, v := range w.Balance.StartingKit {
c.View.Inventory[k] = v
}
w.Characters[c.View.Entity.ID] = c
w.dirty = true
return c, nil
}
func (w *World) Import(c *Character) error {
if w.Phase != "gathering" || w.ForAccount(c.Account) != nil || len(w.Characters) >= w.Balance.MaxPlayers {
return errors.New("destination cannot accept character")
}
if c.View.Entity.State != "eligible" || c.View.Entity.HP <= 0 {
return errors.New("character is not a living survivor")
}
pos, err := w.spawn("")
if err != nil {
return err
}
c.View.Entity.Position = pos
c.View.Entity.State = "alive"
c.Online = false
c.MoveX = 0
c.MoveZ = 0
c.View.ACK = 0
c.LastAttack = 0
c.LastGather = 0
c.ReturnPosition = nil
c.Sheltered = false
c.View.HasKeystone = false
w.resetDay(c)
w.Characters[c.View.Entity.ID] = c
w.dirty = true
return nil
}
func (w *World) resetDay(c *Character) {
day := w.now.UTC().Format(time.DateOnly)
if c.Day != day {
c.Day = day
c.DailySeconds = 0
w.dirty = true
}
c.View.RemainingSeconds = math.Max(0, w.Balance.DailyPlaySeconds-c.DailySeconds)
}
func (w *World) Connect(id string) error {
c := w.Characters[id]
if c == nil {
return errors.New("character not found")
}
w.resetDay(c)
if c.View.Entity.State == "dead" {
return errors.New("this character has died permanently")
}
if c.View.RemainingSeconds <= 0 {
return errors.New("daily play limit reached; resets at 00:00 UTC")
}
if c.Online {
return errors.New("character already connected")
}
c.Online = true
c.View.ACK = 0
c.MoveX = 0
c.MoveZ = 0
return nil
}
func (w *World) Disconnect(id string) {
if c := w.Characters[id]; c != nil {
c.Online = false
c.MoveX = 0
c.MoveZ = 0
}
}
func distance(a, b p.Vec3) float64 { return math.Hypot(a.X-b.X, a.Z-b.Z) }
func (w *World) chunk(x, z int) p.Chunk {
key := Key(x, z)
if c, ok := w.chunks[key]; ok {
return c
}
c := w.terrain.Chunk(x, z)
w.chunks[key] = c
return c
}
func (w *World) neighbors(pos p.Vec3) []p.Chunk {
x, z := ChunkCoord(pos.X, w.Balance.ChunkSize), ChunkCoord(pos.Z, w.Balance.ChunkSize)
chunks := make([]p.Chunk, 0, 9)
for dz := -1; dz <= 1; dz++ {
for dx := -1; dx <= 1; dx++ {
chunks = append(chunks, w.chunk(x+dx, z+dz))
}
}
return chunks
}
func (w *World) Intent(id string, i p.Intent) error {
c := w.Characters[id]
if c == nil || !c.Online || c.View.Entity.State != "alive" || w.Phase == "won" || w.Phase == "lost" {
return errors.New("character cannot act")
}
if i.Seq <= c.View.ACK || i.Seq > c.View.ACK+10000 {
return errors.New("invalid input sequence")
}
if math.IsNaN(i.X) || math.IsNaN(i.Z) || math.IsInf(i.X, 0) || math.IsInf(i.Z, 0) || math.Abs(i.X) > 1 || math.Abs(i.Z) > 1 || len(i.Target) > 100 {
return errors.New("invalid intent")
}
c.View.ACK = i.Seq
if c.Sheltered && ((i.Op == "move" && (i.X != 0 || i.Z != 0)) || (i.Op != "move" && i.Op != "heal")) {
c.Sheltered = false
w.dirty = true
}
switch i.Op {
case "move":
n := math.Max(1, math.Hypot(i.X, i.Z))
c.MoveX = i.X / n
c.MoveZ = i.Z / n
c.LastMove = w.now
return nil
case "gather":
return w.gather(c, i.Target)
case "craft":
return w.craft(c, i.Target)
case "attack":
return w.attack(c, i.Target)
case "heal":
if c.View.Inventory["bandage"] < 1 || c.View.Entity.HP >= c.View.Entity.MaxHP {
return errors.New("no bandage needed or available")
}
c.View.Inventory["bandage"]--
c.View.Entity.HP = math.Min(c.View.Entity.MaxHP, c.View.Entity.HP+w.Balance.BandageHealing)
w.dirty = true
case "return":
if c.ReturnPosition == nil {
return errors.New("no keystone destination")
}
if math.Hypot(c.ReturnPosition.X, c.ReturnPosition.Z) > w.SafeRadius() {
return errors.New("keystone destination has been destroyed")
}
c.View.Entity.Position = *c.ReturnPosition
c.ReturnPosition = nil
c.View.HasKeystone = false
w.dirty = true
case "loot":
corpse := w.Corpses[i.Target]
if corpse == nil || distance(c.View.Entity.Position, corpse.Entity.Position) > w.Balance.GatherRange {
return errors.New("corpse out of reach")
}
for k, v := range corpse.Inventory {
c.View.Inventory[k] += v
}
delete(w.Corpses, i.Target)
w.dirty = true
default:
return errors.New("unknown intent")
}
return nil
}
func (w *World) gather(c *Character, target string) error {
if w.Age()-c.LastGather < w.Balance.GatherCooldown {
return errors.New("gathering cooldown")
}
if until := w.Depleted[target]; until > w.Age() {
return errors.New("resource depleted")
}
for _, chunk := range w.neighbors(c.View.Entity.Position) {
for _, r := range chunk.Resources {
if r.ID != target {
continue
}
if distance(c.View.Entity.Position, r.Position) > w.Balance.GatherRange {
return errors.New("resource out of reach")
}
item := map[string]string{"tree": "wood", "ore": "ore", "herb": "herb"}[r.Kind]
if item == "" {
return errors.New("not gatherable")
}
c.View.Inventory[item]++
c.View.Skills["gathering"] += w.Balance.SkillXpPerAction
c.LastGather = w.Age()
w.Depleted[target] = w.Age() + w.Balance.ResourceRespawnSeconds
w.dirty = true
c.Message = "Gathered " + item
return nil
}
}
return errors.New("unknown resource")
}
func (w *World) craft(c *Character, name string) error {
r, ok := w.Balance.Recipes[name]
if !ok {
return errors.New("unknown recipe")
}
for k, v := range r.Inputs {
if c.View.Inventory[k] < v {
return errors.New("missing crafting materials")
}
}
for k, v := range r.Inputs {
c.View.Inventory[k] -= v
}
for k, v := range r.Outputs {
c.View.Inventory[k] += v
}
c.View.Skills["crafting"] += w.Balance.SkillXpPerAction
c.Message = "Crafted " + name
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 := w.Balance.PlayerDamage
if c.View.Inventory["spear"] > 0 {
damage = w.Balance.SpearDamage
}
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")
}
w.BossHP = math.Max(0, w.BossHP-damage)
if w.BossHP == 0 {
w.Phase = "won"
ended := w.now
w.EndedAt = &ended
for _, survivor := range w.Characters {
if survivor.View.Entity.State == "alive" {
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")
}
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.View.Inventory["herb"]++
}
}
c.LastAttack = w.Age()
c.View.Skills["combat"] += w.Balance.SkillXpPerAction
w.dirty = true
return nil
}
func (w *World) kill(c *Character, reason string) {
if c.View.Entity.State != "alive" {
return
}
e := c.View.Entity
e.ID = "corpse:" + e.ID
e.Kind = "corpse"
e.State = "dead"
e.HP = 0
w.Corpses[e.ID] = &Corpse{Entity: e, Inventory: c.View.Inventory}
c.View.Inventory = map[string]int64{}
c.View.Entity.HP = 0
c.View.Entity.State = "dead"
c.MoveX = 0
c.MoveZ = 0
c.ReturnPosition = nil
c.View.HasKeystone = false
c.Message = reason
w.dirty = true
}
func (w *World) Advance(now time.Time, dt float64) {
playedDT := math.Max(0, dt)
w.now = now
w.Tick++
dt = math.Max(0, math.Min(dt, 0.25))
if w.Phase == "won" || w.Phase == "lost" {
return
}
if w.Phase == "gathering" && w.Age() >= w.Balance.SeasonSeconds {
w.Phase = "cataclysm"
w.dirty = true
}
active := map[string]bool{}
for _, c := range w.Characters {
if c.View.Entity.State != "alive" {
continue
}
w.resetDay(c)
if c.Online {
midnight := time.Date(now.UTC().Year(), now.UTC().Month(), now.UTC().Day(), 0, 0, 0, 0, time.UTC)
c.DailySeconds += math.Min(playedDT, now.Sub(midnight).Seconds())
c.View.PlayedSeconds += playedDT
c.View.RemainingSeconds = math.Max(0, w.Balance.DailyPlaySeconds-c.DailySeconds)
if c.View.RemainingSeconds <= 0 {
pos := c.View.Entity.Position
c.ReturnPosition = &pos
c.Sheltered = true
c.View.HasKeystone = true
c.View.Entity.Position = w.terrain.Position(0, 0)
c.View.Entity.HP = math.Min(c.View.Entity.MaxHP, math.Max(50, c.View.Entity.HP))
c.Online = false
c.MoveX = 0
c.MoveZ = 0
c.Message = "Daily limit reached. Your keystone is ready for tomorrow."
w.dirty = true
}
}
if c.Online {
if now.Sub(c.LastMove) > 250*time.Millisecond {
c.MoveX = 0
c.MoveZ = 0
}
pos := c.View.Entity.Position
nx, nz := pos.X+c.MoveX*w.Balance.PlayerSpeed*dt, pos.Z+c.MoveZ*w.Balance.PlayerSpeed*dt
if math.Hypot(nx, nz) < w.Balance.WorldRadius {
c.View.Entity.Position = w.terrain.Position(nx, nz)
}
for _, ch := range w.neighbors(c.View.Entity.Position) {
active[ch.Key] = true
w.ensureMob(ch)
}
}
if w.Phase == "cataclysm" && math.Hypot(c.View.Entity.Position.X, c.View.Entity.Position.Z) > w.SafeRadius() {
c.View.Entity.HP -= w.Balance.StormDamagePerSecond * dt
w.dirty = true
}
if c.View.Entity.HP <= 0 {
w.kill(c, "The encroaching ruin claimed this character.")
}
}
w.updateMobs(active, dt)
if w.Phase == "cataclysm" {
if w.Age()-w.BossLastAttack >= w.Balance.BossCooldown {
for _, c := range w.Characters {
if c.Online && !c.Sheltered && c.View.Entity.State == "alive" && distance(c.View.Entity.Position, w.terrain.Position(0, 0)) <= w.Balance.BossRange {
c.View.Entity.HP -= w.Balance.BossDamage
w.dirty = true
if c.View.Entity.HP <= 0 {
w.kill(c, "The Harbinger ended this character's journey.")
}
}
}
w.BossLastAttack = w.Age()
}
alive := 0
for _, c := range w.Characters {
if c.View.Entity.State == "alive" {
alive++
}
}
if w.SafeRadius() <= 0 || (len(w.Characters) > 0 && alive == 0) {
for _, c := range w.Characters {
w.kill(c, "The world has been destroyed.")
}
w.Phase = "lost"
ended := w.now
w.EndedAt = &ended
w.dirty = true
}
}
// Keep CPU/GPU working sets bounded to subscribed chunks. Persistent deltas survive eviction.
for key := range w.chunks {
if !active[key] {
delete(w.chunks, key)
}
}
for key, until := range w.Depleted {
if until <= w.Age() {
delete(w.Depleted, key)
}
}
}
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) {
for id, m := range w.Mobs {
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 w.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 {
target.View.Entity.HP -= 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{}}
allowed := map[string]bool{}
for _, ch := range w.neighbors(c.View.Entity.Position) {
allowed[ch.Key] = true
s.ChunkKeys = append(s.ChunkKeys, ch.Key)
if !known[ch.Key] {
s.Chunks = append(s.Chunks, ch)
}
for _, r := range ch.Resources {
if w.Depleted[r.ID] > w.Age() {
s.UnavailableResources = append(s.UnavailableResources, r.ID)
}
}
}
visible := func(pos p.Vec3) bool {
return allowed[Key(ChunkCoord(pos.X, w.Balance.ChunkSize), ChunkCoord(pos.Z, w.Balance.ChunkSize))]
}
for _, other := range w.Characters {
if other.View.Entity.ID != id && other.Online && other.View.Entity.State != "dead" && visible(other.View.Entity.Position) {
s.Entities = append(s.Entities, other.View.Entity)
}
}
for _, m := range w.Mobs {
if m.Entity.HP > 0 && visible(m.Entity.Position) {
s.Entities = append(s.Entities, m.Entity)
}
}
for _, corpse := range w.Corpses {
if visible(corpse.Entity.Position) {
s.Entities = append(s.Entities, corpse.Entity)
}
}
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"})
}
sort.Slice(s.Entities, func(i, j int) bool { return s.Entities[i].ID < s.Entities[j].ID })
return s
}
func (w *World) TriggerBoss() error {
if w.Phase != "gathering" {
return fmt.Errorf("boss event already started")
}
w.CreatedAt = w.now.Add(-time.Duration(w.Balance.SeasonSeconds * float64(time.Second)))
w.Phase = "cataclysm"
w.dirty = true
return nil
}
+305
View File
@@ -0,0 +1,305 @@
package game
import (
"encoding/json"
"math"
"reflect"
"testing"
"time"
"aeternalis/server/content"
p "aeternalis/server/internal/protocol"
)
func fixture(t *testing.T) (*World, *Character) {
t.Helper()
b, err := content.Load()
if err != nil {
t.Fatal(err)
}
w := New("test", 123, time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC), b)
c, err := w.Join("account", "Traveler")
if err != nil {
t.Fatal(err)
}
if err = w.Connect(c.View.Entity.ID); err != nil {
t.Fatal(err)
}
return w, c
}
func TestTerrainDeterministicAndSeamless(t *testing.T) {
b, _ := content.Load()
a := NewTerrain(123, b)
other := NewTerrain(456, b)
if !reflect.DeepEqual(a.Chunk(-1, 0), NewTerrain(123, b).Chunk(-1, 0)) {
t.Fatal("same seed changed")
}
if reflect.DeepEqual(a.Chunk(0, 0), other.Chunk(0, 0)) {
t.Fatal("different seeds identical")
}
left, right := a.Chunk(-1, 0), a.Chunk(0, 0)
n := b.TerrainResolution + 1
for z := 0; z < n; z++ {
if left.Heights[z*n+n-1] != right.Heights[z*n] {
t.Fatal("chunk seam")
}
}
if ChunkCoord(-0.1, 128) != -1 || ChunkCoord(-128, 128) != -1 {
t.Fatal("negative coordinates")
}
for _, r := range left.Resources {
if math.Abs(r.Position.Y-a.Height(r.Position.X, r.Position.Z)) > 1e-8 {
t.Fatal("floating resource")
}
}
}
func TestMovementAuthorityAndInterest(t *testing.T) {
w, c := fixture(t)
id := c.View.Entity.ID
w.now = w.now.Add(time.Second)
for _, intent := range []p.Intent{{Op: "move", Seq: 1, X: 2}, {Op: "move", Seq: 1, X: math.NaN()}, {Op: "move", Seq: 1, Z: math.Inf(1)}} {
if w.Intent(id, intent) == nil {
t.Fatal("invalid movement accepted")
}
}
if err := w.Intent(id, p.Intent{Op: "move", Seq: 1, X: 1, Z: 1}); err != nil {
t.Fatal(err)
}
before := c.View.Entity.Position
w.Advance(w.now.Add(50*time.Millisecond), 0.05)
if got := distance(before, c.View.Entity.Position); math.Abs(got-w.Balance.PlayerSpeed*0.05) > 1e-8 {
t.Fatalf("diagonal speed: %v", got)
}
if w.Intent(id, p.Intent{Op: "move", Seq: 1}) == nil {
t.Fatal("replayed sequence")
}
s := w.Snapshot(id, map[string]bool{})
if len(s.Chunks) != 9 || len(s.ChunkKeys) != 9 {
t.Fatal("interest area not 3x3")
}
known := map[string]bool{}
for _, key := range s.ChunkKeys {
known[key] = true
}
if len(w.Snapshot(id, known).Chunks) != 0 {
t.Fatal("resent known terrain")
}
far, _ := w.Join("far", "Far")
far.View.Entity.Position = w.terrain.Position(700, 700)
far.Online = true
for _, e := range w.Snapshot(id, known).Entities {
if e.ID == far.View.Entity.ID {
t.Fatal("remote entity leaked outside interest")
}
}
w.Advance(w.now.Add(time.Second), 0.05)
if c.MoveX != 0 || c.MoveZ != 0 {
t.Fatal("stale input did not stop")
}
}
func TestGatherCraftAndPermanentDeath(t *testing.T) {
w, c := fixture(t)
id := c.View.Entity.ID
w.now = w.now.Add(2 * time.Second)
if w.Intent(id, p.Intent{Op: "gather", Seq: 1, Target: "arrival:ore"}) == nil {
t.Fatal("remote gather accepted")
}
c.View.Entity.Position = w.terrain.Position(17, 12)
if err := w.Intent(id, p.Intent{Op: "gather", Seq: 2, Target: "arrival:ore"}); err != nil {
t.Fatal(err)
}
if c.View.Inventory["ore"] != 1 {
t.Fatal("gather failed")
}
if w.Intent(id, p.Intent{Op: "gather", Seq: 3, Target: "arrival:ore"}) == nil {
t.Fatal("double gather")
}
if w.Intent(id, p.Intent{Op: "craft", Seq: 4, Target: "spear"}) == nil {
t.Fatal("free craft")
}
c.View.Inventory["wood"] = 3
c.View.Inventory["ore"] = 2
if err := w.Intent(id, p.Intent{Op: "craft", Seq: 5, Target: "spear"}); err != nil {
t.Fatal(err)
}
if c.View.Inventory["spear"] != 1 || c.View.Inventory["wood"] != 0 || c.View.Inventory["ore"] != 0 {
t.Fatal("recipe not atomic")
}
w.kill(c, "test death")
w.Disconnect(id)
if w.Connect(id) == nil {
t.Fatal("dead character reconnected")
}
same, err := w.Join(c.Account, "Replacement")
if err != nil || same.View.Entity.ID != id || same.View.Entity.State != "dead" {
t.Fatal("death bypass by rejoining")
}
if len(c.View.Inventory) != 0 || w.Corpses["corpse:"+id].Inventory["spear"] != 1 {
t.Fatal("corpse inventory")
}
raw, _ := json.Marshal(w)
var restored World
if err = json.Unmarshal(raw, &restored); err != nil {
t.Fatal(err)
}
if err = restored.Restore(w.now); err != nil {
t.Fatal(err)
}
if restored.Connect(id) == nil {
t.Fatal("restart resurrected character")
}
}
func TestStaticResourcesAreNotReplicatedEverySnapshot(t *testing.T) {
w, c := fixture(t)
w.Depleted["arrival:ore"] = w.Age() + 60
s := w.Snapshot(c.View.Entity.ID, map[string]bool{})
if len(s.UnavailableResources) != 1 || s.UnavailableResources[0] != "arrival:ore" {
t.Fatal("missing authoritative resource availability")
}
for _, e := range s.Entities {
if e.Kind == "tree" || e.Kind == "ore" || e.Kind == "herb" {
t.Fatal("static resource repeated in dynamic entity snapshot")
}
}
resources := 0
for _, ch := range s.Chunks {
resources += len(ch.Resources)
}
if resources == 0 {
t.Fatal("initial chunk does not carry resources")
}
}
func TestDailyLimitAndKeystone(t *testing.T) {
w, c := fixture(t)
w.Balance.DailyPlaySeconds = 1
c.DailySeconds = .9
c.View.Entity.HP = 20
c.View.Entity.Position = w.terrain.Position(40, 40)
w.Advance(w.now.Add(200*time.Millisecond), .2)
if c.Online || c.ReturnPosition == nil || !c.View.HasKeystone || c.View.Entity.HP != 50 || distance(c.View.Entity.Position, p.Vec3{}) != 0 {
t.Fatalf("cap not enforced: %+v", c)
}
if w.Connect(c.View.Entity.ID) == nil {
t.Fatal("same-day cap bypass")
}
w.now = w.now.Add(24 * time.Hour)
if err := w.Connect(c.View.Entity.ID); err != nil {
t.Fatal(err)
}
if err := w.Intent(c.View.Entity.ID, p.Intent{Op: "return", Seq: 1}); err != nil {
t.Fatal(err)
}
if c.View.Entity.Position.X != 40 || c.ReturnPosition != nil || c.View.HasKeystone {
t.Fatal("keystone failed")
}
}
func TestDailyBudgetUsesWallTimeDuringLag(t *testing.T) {
w, c := fixture(t)
w.Balance.DailyPlaySeconds = 2
w.Advance(w.now.Add(3*time.Second), 3)
if c.Online || c.View.RemainingSeconds != 0 {
t.Fatal("simulation lag bypassed wall-clock play cap")
}
}
func TestKeystoneCannotGrantRoamingInvulnerability(t *testing.T) {
w, c := fixture(t)
c.Sheltered = true
c.ReturnPosition = &p.Vec3{X: 40, Z: 40}
if err := w.Intent(c.View.Entity.ID, p.Intent{Op: "move", Seq: 1, X: 1}); err != nil {
t.Fatal(err)
}
if c.Sheltered || c.ReturnPosition == nil {
t.Fatal("leaving sanctuary must remove protection while preserving keystone")
}
}
func TestBossVictoryAndCollapse(t *testing.T) {
t.Run("victory includes offline survivors and excludes dead", func(t *testing.T) {
w, c := fixture(t)
dead, _ := w.Join("dead", "Dead")
w.kill(dead, "test")
offline, _ := w.Join("offline", "Offline")
w.now = w.now.Add(time.Second)
_ = w.TriggerBoss()
w.BossHP = 1
if err := w.Intent(c.View.Entity.ID, p.Intent{Op: "attack", Seq: 1, Target: "boss"}); err != nil {
t.Fatal(err)
}
if w.Phase != "won" || c.View.Entity.State != "eligible" || offline.View.Entity.State != "eligible" || dead.View.Entity.State != "dead" {
t.Fatal("incorrect survivor selection")
}
radius := w.SafeRadius()
w.Advance(w.now.Add(20*24*time.Hour), .05)
if w.SafeRadius() != radius {
t.Fatal("world kept collapsing after boss death")
}
if c.View.Entity.State != "eligible" {
t.Fatal("victory not terminal")
}
if w.Intent(c.View.Entity.ID, p.Intent{Op: "move", Seq: 2, X: 1}) == nil {
t.Fatal("survivor mutated frozen world")
}
})
t.Run("collapse kills offline and capped characters", func(t *testing.T) {
w, c := fixture(t)
c.Online = false
c.ReturnPosition = &p.Vec3{X: 40}
w.Advance(w.CreatedAt.Add(time.Duration((w.Balance.SeasonSeconds+w.Balance.CollapseSeconds+1)*float64(time.Second))), .05)
if w.Phase != "lost" || c.View.Entity.State != "dead" {
t.Fatal("world destruction bypass")
}
})
t.Run("boss schedule survives downtime", func(t *testing.T) {
w, _ := fixture(t)
w.Advance(w.CreatedAt.Add(7*24*time.Hour+5*time.Minute), .05)
if w.Phase != "cataclysm" || w.SafeRadius() >= w.Balance.WorldRadius {
t.Fatal("deadline did not advance")
}
})
}
func TestSpawnAndTransferPreserveBudget(t *testing.T) {
w, c := fixture(t)
other, _ := w.Join("other", "Other")
if distance(c.View.Entity.Position, other.View.Entity.Position) < w.Balance.SpawnSeparation {
t.Fatal("spawns overlap")
}
c.View.Entity.State = "eligible"
c.DailySeconds = 123
c.View.PlayedSeconds = 456
c.View.Skills["combat"] = 9
c.View.Inventory["spear"] = 1
next := New("next", 999, w.now, w.Balance)
if err := next.Import(c); err != nil {
t.Fatal(err)
}
if c.DailySeconds != 123 || c.View.PlayedSeconds != 456 || c.View.Skills["combat"] != 9 || c.View.Inventory["spear"] != 1 {
t.Fatal("transfer changed progress or budget")
}
if err := next.Import(c); err == nil {
t.Fatal("duplicate import")
}
}
func BenchmarkSnapshot100Players(b *testing.B) {
balance, _ := content.Load()
w := New("bench", 123, time.Now(), balance)
ids := []string{}
for i := 0; i < 100; i++ {
c, err := w.Join(ID(), "Traveler")
if err != nil {
b.Fatal(err)
}
c.Online = true
ids = append(ids, c.View.Entity.ID)
}
w.Advance(time.Now(), .05)
known := map[string]bool{}
b.ResetTimer()
for i := 0; i < b.N; i++ {
s := w.Snapshot(ids[i%len(ids)], known)
if _, err := json.Marshal(s); err != nil {
b.Fatal(err)
}
}
}