996 lines
31 KiB
Go
996 lines
31 KiB
Go
package game
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"math"
|
|
"sort"
|
|
"time"
|
|
|
|
"aeternalis/server/content"
|
|
p "aeternalis/server/internal/protocol"
|
|
)
|
|
|
|
type Character struct {
|
|
ItemReadyAt float64 `json:"itemReadyAt"`
|
|
HouseRoom *p.HouseScene `json:"-"`
|
|
XPCurveVersion int `json:"xpCurveVersion"`
|
|
PendingCast *PendingCast `json:"pendingCast,omitempty"`
|
|
RevivalCorpse string `json:"revivalCorpse,omitempty"`
|
|
RevivalAllowed bool `json:"revivalAllowed"`
|
|
DeathCount int64 `json:"deathCount"`
|
|
CraftReadyAt float64 `json:"craftReadyAt"`
|
|
AttackReadyAt float64 `json:"attackReadyAt"`
|
|
JumpVelocity float64 `json:"jumpVelocity"`
|
|
GatherReadyAt float64 `json:"gatherReadyAt"`
|
|
|
|
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:"-"`
|
|
BornAt time.Time `json:"bornAt"`
|
|
DiedAt *time.Time `json:"diedAt,omitempty"`
|
|
DeathReason string `json:"deathReason,omitempty"`
|
|
Progression *content.Progression `json:"progression,omitempty"`
|
|
WorldKills int64 `json:"worldKills"`
|
|
BossKills int64 `json:"bossKills"`
|
|
WorldsSurvived int64 `json:"worldsSurvived"`
|
|
StatsVersion int `json:"statsVersion"`
|
|
}
|
|
type Corpse struct {
|
|
CharacterID string `json:"characterId,omitempty"`
|
|
CraftedStacks []p.CraftedStack `json:"craftedStacks,omitempty"`
|
|
Entity p.Entity `json:"entity"`
|
|
Inventory map[string]int64 `json:"inventory"`
|
|
Items []p.ItemInstance `json:"items"`
|
|
}
|
|
type Mob struct {
|
|
Definition *content.MobDefinition `json:"definition,omitempty"`
|
|
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"`
|
|
LastAttack float64 `json:"lastAttack"`
|
|
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 {
|
|
Structures map[string]*Structure `json:"structures,omitempty"`
|
|
Kind string `json:"kind,omitempty"`
|
|
ProjectileVisuals []p.ProjectileVisual `json:"projectileVisuals,omitempty"`
|
|
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"`
|
|
ID string `json:"id"`
|
|
Seed int64 `json:"seed"`
|
|
CreatedAt time.Time `json:"createdAt"`
|
|
EndedAt *time.Time `json:"endedAt,omitempty"`
|
|
Phase string `json:"phase"`
|
|
AdmissionsClosed bool `json:"admissionsClosed"`
|
|
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"`
|
|
PendingTitles []TitleCandidate `json:"-"`
|
|
CatalogVersion int64 `json:"catalogVersion"`
|
|
RandomCounter uint64 `json:"randomCounter"`
|
|
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.Balance.Entrances == nil {
|
|
defaults, err := content.Load()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
w.Balance.Entrances = defaults.Entrances
|
|
w.dirty = true
|
|
}
|
|
if err := w.Balance.Entrances.Validate(); err != nil {
|
|
return err
|
|
}
|
|
if w.Balance.Inventory == nil {
|
|
defaults, err := content.Load()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
w.Balance.Inventory = defaults.Inventory
|
|
w.dirty = true
|
|
}
|
|
if err := w.Balance.Inventory.Validate(); err != nil {
|
|
return err
|
|
}
|
|
if w.Kind == "" {
|
|
w.Kind = "survival"
|
|
}
|
|
if w.Kind != "" && w.Kind != "survival" && w.Kind != "hub" {
|
|
return errors.New("unknown instance kind")
|
|
}
|
|
if w.IsHub() {
|
|
w.Phase = "hub"
|
|
}
|
|
if w.Version != 1 && w.Version != GeneratorVersion {
|
|
return errors.New("unsupported persisted generator version")
|
|
}
|
|
// Snapshots predating progression receive the YAML defaults once. Existing
|
|
// world tuning and character lives remain intact; old actions grant no backfill XP.
|
|
if w.Balance.Progression == nil {
|
|
defaults, err := content.Load()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
w.Balance.Progression = defaults.Progression
|
|
if w.Balance.Titles == nil {
|
|
w.Balance.Titles = defaults.Titles
|
|
}
|
|
w.dirty = true
|
|
}
|
|
if w.Balance.Stats == nil {
|
|
defaults, err := content.Load()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
w.Balance.Stats = defaults.Stats
|
|
w.Balance.Items = defaults.Items
|
|
rules := *w.Balance.Progression
|
|
rules.StatPointsPerLevel = defaults.Progression.StatPointsPerLevel
|
|
rules.StaminaPerLevel = defaults.Progression.StaminaPerLevel
|
|
rules.VitalPointsPerChoice = defaults.Progression.VitalPointsPerChoice
|
|
w.Balance.Progression = &rules
|
|
w.dirty = true
|
|
}
|
|
if w.Balance.CriticalMultiplier == 0 {
|
|
defaults, err := content.Load()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
w.Balance.CriticalMultiplier = defaults.CriticalMultiplier
|
|
w.dirty = true
|
|
}
|
|
if w.Balance.MaxYieldPerAction == 0 {
|
|
defaults, err := content.Load()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
w.Balance.MaxYieldPerAction = defaults.MaxYieldPerAction
|
|
w.dirty = true
|
|
}
|
|
if w.Balance.Gathering == nil || w.Balance.GatheringRules == nil {
|
|
b, err := content.Load()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if w.Balance.Gathering == nil {
|
|
w.Balance.Gathering = b.Gathering
|
|
}
|
|
if w.Balance.GatheringRules == nil {
|
|
w.Balance.GatheringRules = b.GatheringRules
|
|
}
|
|
w.dirty = true
|
|
}
|
|
if e := w.restoreHousing(); e != nil {
|
|
return e
|
|
}
|
|
if e := w.restoreBuilding(); e != nil {
|
|
return e
|
|
}
|
|
if w.ResourceLayouts == nil {
|
|
w.ResourceLayouts = map[string]ResourceLayout{}
|
|
}
|
|
if w.Balance.Powers == nil {
|
|
b, e := content.Load()
|
|
if e != nil {
|
|
return e
|
|
}
|
|
cat := content.Catalog{Items: w.Balance.Items, Combat: w.Balance.Combat}
|
|
cat.RestorePowers(b)
|
|
w.Balance.Powers = cat.Powers
|
|
w.Balance.Combat = cat.Combat
|
|
w.Balance.Items = cat.Items
|
|
}
|
|
if w.Balance.Crafting == nil {
|
|
b, e := content.Load()
|
|
if e != nil {
|
|
return e
|
|
}
|
|
cat := content.Catalog{Items: w.Balance.Items}
|
|
cat.RestoreCrafting(b)
|
|
w.Balance.Crafting = cat.Crafting
|
|
w.Balance.Items = cat.Items
|
|
}
|
|
if w.Balance.Combat == nil || w.Balance.CombatRules == nil {
|
|
b, e := content.Load()
|
|
if e != nil {
|
|
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
|
|
}
|
|
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.terrain.Version = w.Version
|
|
w.chunks = map[string]p.Chunk{}
|
|
w.now = now
|
|
w.PendingTitles = nil
|
|
for _, c := range w.Characters {
|
|
if err := w.restoreProgression(c); err != nil {
|
|
return err
|
|
}
|
|
if err := w.restoreEquipment(c); err != nil {
|
|
return err
|
|
}
|
|
if err := w.restorePowers(c); err != nil {
|
|
return err
|
|
}
|
|
if err := w.restoreCrafting(c); err != nil {
|
|
return err
|
|
}
|
|
if err := w.restoreGathering(c); err != nil {
|
|
return err
|
|
}
|
|
if err := w.initializeStats(c); err != nil {
|
|
return err
|
|
}
|
|
c.Online = false
|
|
c.MoveX = 0
|
|
c.MoveZ = 0
|
|
c.View.ACK = 0
|
|
}
|
|
if err := w.restoreCombat(); err != nil {
|
|
return err
|
|
}
|
|
return w.restoreCorpseEquipment()
|
|
}
|
|
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.IsHub() {
|
|
return w.Balance.WorldRadius
|
|
}
|
|
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{Kind: stringPtr(w.Kind), 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 && c.View.Entity.State != "dead" {
|
|
return c
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
func (w *World) LivingCount() int {
|
|
n := 0
|
|
for _, c := range w.Characters {
|
|
if c.View.Entity.State != "dead" {
|
|
n++
|
|
}
|
|
}
|
|
return n
|
|
}
|
|
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 > math.Max(0, math.Min(w.Balance.WorldRadius-32, w.SafeRadius()-8)) {
|
|
break
|
|
}
|
|
clear := !w.structureBlocked(pos, pos)
|
|
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 w.IsHub() {
|
|
return nil, errors.New("new characters must begin in a survival world")
|
|
}
|
|
if c := w.ForAccount(account); c != nil {
|
|
return c, nil
|
|
}
|
|
if (w.Phase != "gathering" && w.Phase != "cataclysm") || w.AdmissionsClosed {
|
|
return nil, errors.New("this world is closed to new arrivals")
|
|
}
|
|
if w.LivingCount() >= w.Balance.MaxPlayers {
|
|
return nil, errors.New("world capacity reached")
|
|
}
|
|
pos, err := w.spawn("")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
c := &Character{XPCurveVersion: 1, 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}}
|
|
if err := w.restoreProgression(c); err != nil {
|
|
return nil, err
|
|
}
|
|
for k, v := range w.Balance.StartingKit {
|
|
c.View.Inventory[k] = v
|
|
}
|
|
if err := w.restoreEquipment(c); err != nil {
|
|
return nil, err
|
|
}
|
|
if err := w.restorePowers(c); err != nil {
|
|
return nil, err
|
|
}
|
|
if err := w.restoreCrafting(c); err != nil {
|
|
return nil, err
|
|
}
|
|
if err := w.restoreGathering(c); err != nil {
|
|
return nil, err
|
|
}
|
|
if err := w.initializeStats(c); err != nil {
|
|
return nil, err
|
|
}
|
|
w.Characters[c.View.Entity.ID] = c
|
|
c.BornAt = w.now
|
|
w.evaluateTitles(c)
|
|
w.dirty = true
|
|
return c, nil
|
|
}
|
|
func (w *World) Import(c *Character) error {
|
|
if (w.Phase != "gathering" && w.Phase != "cataclysm" && !w.IsHub()) || w.AdmissionsClosed || w.ForAccount(c.Account) != nil || w.Characters[c.View.Entity.ID] != nil || w.LivingCount() >= 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")
|
|
}
|
|
if err := w.restoreProgression(c); err != nil {
|
|
return err
|
|
}
|
|
if err := w.restoreEquipment(c); err != nil {
|
|
return err
|
|
}
|
|
if err := w.checkImportedEquipment(c); err != nil {
|
|
return err
|
|
}
|
|
if err := w.restorePowers(c); err != nil {
|
|
return err
|
|
}
|
|
if err := w.restoreCrafting(c); err != nil {
|
|
return err
|
|
}
|
|
if err := w.restoreGathering(c); err != nil {
|
|
return err
|
|
}
|
|
if err := w.initializeStats(c); err != nil {
|
|
return err
|
|
}
|
|
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.AttackReadyAt = 0
|
|
c.LastGather = 0
|
|
c.GatherReadyAt = 0
|
|
c.JumpVelocity = 0
|
|
c.ReturnPosition = nil
|
|
c.Sheltered = false
|
|
c.PendingCast = nil
|
|
c.View.HasKeystone = false
|
|
c.WorldKills = 0
|
|
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 is dead; corpse revival is required before reconnecting")
|
|
}
|
|
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.View.DestroyKey = nil
|
|
LeaveHouse(c)
|
|
}
|
|
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)
|
|
if w.IsHub() {
|
|
c.Resources = []p.Entity{}
|
|
c.Biome = "Survivor haven"
|
|
w.chunks[key] = c
|
|
return c
|
|
}
|
|
if layout, ok := w.ResourceLayouts[key]; ok {
|
|
c.Biome, c.Color, c.Resources = layout.Biome, layout.Color, layout.Resources
|
|
} else {
|
|
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
|
|
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" && c.View.Entity.State != "eligible") || 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 || len(i.Slot) > 64 {
|
|
return errors.New("invalid intent")
|
|
}
|
|
c.View.ACK = i.Seq
|
|
if HouseID(c) != "" {
|
|
return w.houseIntent(c, i)
|
|
}
|
|
if c.Sheltered && ((i.Op == "move" && (i.X != 0 || i.Z != 0)) || (i.Op != "move" && i.Op != "heal" && i.Op != "allocate-stat" && i.Op != "choose-vital" && i.Op != "equip" && i.Op != "unequip" && i.Op != "drop")) {
|
|
c.Sheltered = false
|
|
w.dirty = true
|
|
}
|
|
if w.Phase == "won" && i.Op != "move" && i.Op != "jump" && i.Op != "return" && i.Op != "learn" && i.Op != "drop" {
|
|
return errors.New("use the victory portal to continue")
|
|
}
|
|
if w.IsHub() && (i.Op == "attack" || i.Op == "gather") {
|
|
return errors.New("combat and gathering are unavailable in the hub")
|
|
}
|
|
switch i.Op {
|
|
case "allocate-stat":
|
|
return w.allocateStat(c, i.Target)
|
|
case "choose-vital":
|
|
return w.chooseVital(c, i.Target)
|
|
case "equip":
|
|
return w.equip(c, i.Target, i.Slot)
|
|
case "unequip":
|
|
return w.unequip(c, i.Target)
|
|
case "drop":
|
|
return w.dropItem(c, i.Target)
|
|
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 "jump":
|
|
return w.jump(c)
|
|
case "consume":
|
|
return w.consumeGathering(c, i.Target)
|
|
case "gather":
|
|
return w.gather(c, i.Target)
|
|
case "build":
|
|
return w.Build(c, i.Target, i.X, i.Z, i.Slot)
|
|
case "learn":
|
|
return w.LearnPower(c, i.Target)
|
|
case "cast":
|
|
return w.CastPower(c, i.Slot, i.Target)
|
|
case "cancel-cast":
|
|
c.PendingCast = nil
|
|
w.refreshPowers(c)
|
|
w.dirty = true
|
|
return nil
|
|
case "craft":
|
|
return errors.New("use the crafting workbench to offer ingredients")
|
|
case "attack":
|
|
return w.attack(c, i.Target)
|
|
case "heal":
|
|
if c.View.Inventory["bandage"] < 1 || c.View.Entity.HP >= c.View.Entity.MaxHP {
|
|
return errors.New("no bandage needed or available")
|
|
}
|
|
TakeStack(c, "bandage", 1)
|
|
w.RefreshStats(c)
|
|
c.View.Entity.HP = math.Min(c.View.Entity.MaxHP, c.View.Entity.HP+w.Balance.BandageHealing)
|
|
w.dirty = true
|
|
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.JumpVelocity = 0
|
|
c.View.Entity.Position = *c.ReturnPosition
|
|
c.ReturnPosition = nil
|
|
c.View.HasKeystone = false
|
|
w.dirty = true
|
|
case "loot":
|
|
return w.lootCorpse(c, i.Target)
|
|
default:
|
|
return errors.New("unknown intent")
|
|
}
|
|
return nil
|
|
}
|
|
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."
|
|
}
|
|
}
|
|
}
|
|
}
|
|
func (w *World) kill(c *Character, reason string) {
|
|
if c.View.Entity.State != "alive" {
|
|
return
|
|
}
|
|
e := c.View.Entity
|
|
e.Position = w.terrain.Position(e.Position.X, e.Position.Z)
|
|
c.View.Entity.Position = e.Position
|
|
c.DeathCount++
|
|
c.View.DestroyKey = nil
|
|
LeaveHouse(c)
|
|
c.PendingCast = nil
|
|
c.RevivalAllowed = false
|
|
e.ID = "corpse:" + e.ID + ":" + ID()
|
|
c.RevivalCorpse = e.ID
|
|
e.Kind = "corpse"
|
|
e.State = "dead"
|
|
e.HP = 0
|
|
w.Corpses[e.ID] = &Corpse{CharacterID: c.View.Entity.ID, Entity: e, Inventory: c.View.Inventory, Items: c.View.Items, CraftedStacks: c.View.CraftedStacks}
|
|
c.View.CraftedStacks = nil
|
|
c.View.Inventory = map[string]int64{}
|
|
c.View.Items = []p.ItemInstance{}
|
|
c.View.Equipment = map[string]string{}
|
|
c.View.CarryWeight = 0
|
|
c.View.Entity.HP = 0
|
|
c.JumpVelocity = 0
|
|
c.View.Entity.State = "dead"
|
|
c.MoveX = 0
|
|
c.MoveZ = 0
|
|
c.ReturnPosition = nil
|
|
c.View.HasKeystone = false
|
|
c.Message = reason
|
|
died := w.now
|
|
c.DiedAt = &died
|
|
c.DeathReason = reason
|
|
w.evaluateTitles(c)
|
|
w.dirty = true
|
|
}
|
|
|
|
// Operator changes use the same simulation and persistence path as gameplay.
|
|
func (w *World) Control(op, target, value, reason string) error {
|
|
if w.IsHub() && (op == "end-world" || op == "awaken-boss" || op == "spawn-mobs") {
|
|
return errors.New("hubs cannot be destroyed or host combat")
|
|
}
|
|
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")
|
|
}
|
|
w.AdmissionsClosed = op == "close-admissions"
|
|
case "awaken-boss":
|
|
return w.TriggerBoss()
|
|
case "end-world":
|
|
if w.Phase == "won" || w.Phase == "lost" {
|
|
return errors.New("world has already ended")
|
|
}
|
|
for _, c := range w.orderedCharacters() {
|
|
w.kill(c, "World ended by an operator: "+reason)
|
|
}
|
|
w.Phase = "lost"
|
|
ended := w.now
|
|
w.EndedAt = &ended
|
|
default:
|
|
c := w.Characters[target]
|
|
if c == nil {
|
|
return errors.New("character not found")
|
|
}
|
|
if c.View.Entity.State != "alive" {
|
|
return errors.New("only living characters in an active world may be changed")
|
|
}
|
|
switch op {
|
|
case "rename":
|
|
c.View.Entity.Name = value
|
|
case "heal":
|
|
c.View.Entity.HP = c.View.Entity.MaxHP
|
|
case "unstuck":
|
|
c.JumpVelocity = 0
|
|
c.View.Entity.Position = w.terrain.Position(0, 0)
|
|
c.MoveX, c.MoveZ = 0, 0
|
|
case "retire":
|
|
w.kill(c, "Character retired by an operator: "+reason)
|
|
default:
|
|
return errors.New("unknown control operation")
|
|
}
|
|
}
|
|
w.dirty = true
|
|
return nil
|
|
}
|
|
func (w *World) Advance(now time.Time, dt float64) {
|
|
playedDT := math.Max(0, dt)
|
|
w.now = now
|
|
w.Tick++
|
|
kept := w.ProjectileVisuals[:0]
|
|
for _, v := range w.ProjectileVisuals {
|
|
if w.Age()-v.At <= 2 {
|
|
kept = append(kept, v)
|
|
}
|
|
}
|
|
w.ProjectileVisuals = kept
|
|
dt = math.Max(0, math.Min(dt, 0.25))
|
|
if w.Phase == "lost" {
|
|
return
|
|
}
|
|
if w.Phase == "won" || w.IsHub() {
|
|
clear(w.Projectiles)
|
|
clear(w.Areas)
|
|
}
|
|
if w.Phase == "gathering" && w.Age() >= w.Balance.SeasonSeconds {
|
|
w.Phase = "cataclysm"
|
|
w.dirty = true
|
|
}
|
|
active := map[string]bool{}
|
|
characters := w.orderedCharacters()
|
|
for _, c := range characters {
|
|
if c.View.Entity.State != "alive" && c.View.Entity.State != "eligible" {
|
|
continue
|
|
}
|
|
w.resetDay(c)
|
|
nowSeconds := float64(w.now.UnixMilli()) / 1000
|
|
effects := c.View.GatheringEffects[:0]
|
|
for _, e := range c.View.GatheringEffects {
|
|
if e.ExpiresAt > nowSeconds {
|
|
effects = append(effects, e)
|
|
}
|
|
}
|
|
if len(effects) != len(c.View.GatheringEffects) {
|
|
c.View.GatheringEffects = effects
|
|
w.RefreshStats(c)
|
|
w.dirty = true
|
|
}
|
|
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.JumpVelocity = 0
|
|
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 c.View.Entity.HP > 0 {
|
|
c.View.Entity.HP = math.Min(c.View.Entity.MaxHP, c.View.Entity.HP+c.View.Stats["healthRecovery"].Final*dt)
|
|
}
|
|
c.View.Mana = math.Min(c.View.Stats["manaPoints"].Final, c.View.Mana+c.View.Stats["manaRecovery"].Final*dt)
|
|
c.View.Stamina = math.Min(c.View.Stats["stamina"].Final, c.View.Stamina+c.View.Stats["staminaRecovery"].Final*dt)
|
|
// A generous window: the client resends its move intent well under this on every
|
|
// rendered frame, but a slow/throttled frame (e.g. software-rendered CI) shouldn't
|
|
// zero out in-flight movement and strand a walk-to-target action mid-course.
|
|
if now.Sub(c.LastMove) > 800*time.Millisecond {
|
|
c.MoveX = 0
|
|
c.MoveZ = 0
|
|
}
|
|
if HouseID(c) == "" {
|
|
w.moveCharacter(c, dt)
|
|
} else {
|
|
w.moveHouse(c, dt)
|
|
}
|
|
for _, ch := range w.neighbors(c.View.Entity.Position) {
|
|
active[ch.Key] = true
|
|
if !w.IsHub() && w.Phase != "won" {
|
|
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.")
|
|
}
|
|
}
|
|
if !w.IsHub() && w.Phase != "won" {
|
|
w.updateMobs(active, dt)
|
|
}
|
|
w.updateHousingActions()
|
|
w.updatePowers()
|
|
if w.Phase != "won" {
|
|
w.updateCombat(dt)
|
|
}
|
|
if w.Phase == "cataclysm" {
|
|
if w.Age()-w.BossLastAttack >= w.Balance.BossCooldown {
|
|
for _, c := range characters {
|
|
if c.Online && !c.Sheltered && c.View.Entity.State == "alive" && distance(c.View.Entity.Position, w.terrain.Position(0, 0)) <= w.Balance.BossRange {
|
|
w.damageCharacter(c, 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 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) 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{}}
|
|
s.House = w.HouseSnapshot(c)
|
|
s.GatherRisks = map[string]p.GatheringRisk{}
|
|
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] {
|
|
ch.Resources = append([]p.Entity{}, ch.Resources...)
|
|
for index := range ch.Resources {
|
|
e := &ch.Resources[index]
|
|
id := stringValue(e.ResourceID)
|
|
if id == "" {
|
|
id = e.Kind
|
|
}
|
|
if r := w.resource(id); r != nil {
|
|
e.ResourceID = stringPtr(r.ID)
|
|
e.SkillID = stringPtr(r.SkillID)
|
|
e.RequiredLevel = &r.RequiredLevel
|
|
e.Name = r.Name
|
|
}
|
|
}
|
|
s.Chunks = append(s.Chunks, ch)
|
|
}
|
|
for _, r := range ch.Resources {
|
|
if w.Depleted[r.ID] <= w.Age() {
|
|
id := stringValue(r.ResourceID)
|
|
if id == "" {
|
|
id = r.Kind
|
|
}
|
|
if def := w.resource(id); def != nil {
|
|
if _, ok := s.GatherRisks[def.ID]; !ok {
|
|
s.GatherRisks[def.ID] = w.gatherRisk(c, *def)
|
|
}
|
|
}
|
|
}
|
|
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))]
|
|
}
|
|
s.ProjectileVisuals = []p.ProjectileVisual{}
|
|
for _, v := range w.ProjectileVisuals {
|
|
if w.Age()-v.At <= 2 && (visible(v.Position) || visible(v.Destination)) {
|
|
s.ProjectileVisuals = append(s.ProjectileVisuals, v)
|
|
}
|
|
}
|
|
for _, other := range w.Characters {
|
|
if HouseID(other) == "" && 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 !w.IsHub() && w.Phase != "won" && m.Entity.HP > 0 && visible(m.Entity.Position) {
|
|
s.Entities = append(s.Entities, m.Entity)
|
|
}
|
|
}
|
|
for _, structure := range w.Structures {
|
|
if visible(structure.Entity.Position) {
|
|
s.Entities = append(s.Entities, structure.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"})
|
|
}
|
|
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})
|
|
}
|
|
}
|
|
if HouseID(c) == "" && (w.Phase == "won" || w.IsHub()) && visible(w.PortalPosition()) {
|
|
name := "Portal to the hub"
|
|
if w.IsHub() {
|
|
name = "World portal"
|
|
}
|
|
s.Entities = append(s.Entities, p.Entity{ID: "hub-portal", Kind: "portal", Name: name, Position: w.PortalPosition(), HP: 1, MaxHP: 1, State: "open"})
|
|
}
|
|
if HouseID(c) == "" && w.IsHub() && visible(w.HousingEntrancePosition()) {
|
|
s.Entities = append(s.Entities, p.Entity{ID: "housing-entrance", Kind: "house-door", Name: "Housing entrance", Position: w.HousingEntrancePosition(), HP: 1, MaxHP: 1, State: "open"})
|
|
}
|
|
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.IsHub() {
|
|
return errors.New("hubs have no Harbinger")
|
|
}
|
|
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
|
|
}
|