533 lines
16 KiB
Go
533 lines
16 KiB
Go
package game
|
|
|
|
import (
|
|
"aeternalis/server/content"
|
|
p "aeternalis/server/internal/protocol"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"math"
|
|
"sort"
|
|
)
|
|
|
|
type Projectile struct {
|
|
Credit *CombatCredit `json:"credit,omitempty"`
|
|
MovingAura bool `json:"movingAura"`
|
|
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, DexteritySpeed: &a.DexteritySpeed, StrengthSpeed: &a.StrengthSpeed, 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 {
|
|
a := *i.Attack
|
|
if a.Delivery == "projectile" {
|
|
if a.DexteritySpeed != nil {
|
|
a.Speed += c.View.Stats["dexterity"].Final * *a.DexteritySpeed
|
|
}
|
|
if a.StrengthSpeed != nil {
|
|
a.Speed += c.View.Stats["strength"].Final * *a.StrengthSpeed
|
|
}
|
|
a.Speed = math.Max(1, math.Min(100, a.Speed))
|
|
}
|
|
return a
|
|
}
|
|
}
|
|
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 && HouseID(c) == "" && 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 HouseID(c) == "" && 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})
|
|
}
|
|
}
|
|
if effect == "damage" {
|
|
for _, id := range w.structureIDs() {
|
|
out = append(out, w.Structures[id].Entity)
|
|
}
|
|
}
|
|
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 {
|
|
if c.PendingCast != nil {
|
|
return errors.New("finish or cancel the current cast")
|
|
}
|
|
if !w.AllowsXP() {
|
|
return errors.New("combat is unavailable here")
|
|
}
|
|
a := w.playerAttack(c)
|
|
if w.Age() < c.AttackReadyAt || w.Age()-c.LastAttack < a.Cooldown {
|
|
return errors.New("attack cooldown")
|
|
}
|
|
if c.View.Stamina < a.Stamina {
|
|
return errors.New("not enough stamina")
|
|
}
|
|
var e *p.Entity
|
|
for _, v := range w.combatTargets(true, a.Effect) {
|
|
if v.ID == target {
|
|
copy := v
|
|
e = ©
|
|
break
|
|
}
|
|
}
|
|
if e == nil {
|
|
return errors.New("invalid attack target")
|
|
}
|
|
from, to := body(c.View.Entity.Position), body(e.Position)
|
|
extra := float64(0)
|
|
if e.Kind == "structure" {
|
|
extra = math.Max(*e.Width, *e.Depth) / 2
|
|
}
|
|
if target == "boss" {
|
|
extra = 4
|
|
}
|
|
if length3(from, to) > a.Range+extra {
|
|
return errors.New("target out of reach")
|
|
}
|
|
if _, blocked := w.combatLine(from, to, target); 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
|
|
// Coatings add damage to this weapon attack, so they use the same server
|
|
// collision, defence and credit rules. Spells do not inherit weapon coatings.
|
|
if i := ownedItem(c, c.View.Equipment["weapon"]); a.Effect == "damage" && i != nil && i.Coating != nil && i.Coating.ExpiresAt > float64(w.now.UnixMilli())/1000 {
|
|
power += i.Coating.Damage
|
|
}
|
|
if a.Effect == "damage" && w.roll(c.View.Stats["criticalChance"].Final) {
|
|
power *= w.Balance.CriticalMultiplier
|
|
}
|
|
c.LastAttack = w.Age()
|
|
c.AttackReadyAt = w.Age() + a.Cooldown
|
|
c.View.Stamina -= a.Stamina
|
|
w.dirty = true
|
|
shot := Projectile{Credit: &CombatCredit{Weapon: w.weaponType(c)}, 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
|
|
w.projectileVisual(shot, "launch", "")
|
|
} 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.combatLine(shot.Position, body(e.Position), e.ID); 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 w.Structures[target] != nil {
|
|
if !healing {
|
|
w.damageStructure(target, shot.Power)
|
|
}
|
|
return
|
|
}
|
|
if c := w.Characters[target]; c != nil {
|
|
if c.View.Entity.State != "alive" || !c.Online || c.Sheltered {
|
|
return
|
|
}
|
|
if healing && shot.Player {
|
|
if shot.Power > 0 && c.View.Entity.HP < c.View.Entity.MaxHP {
|
|
w.awardCombatCredit(shot)
|
|
}
|
|
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 {
|
|
if shot.Power > 0 {
|
|
w.awardCombatCredit(shot)
|
|
}
|
|
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
|
|
}
|
|
if shot.Power > defence {
|
|
w.awardCombatCredit(shot)
|
|
}
|
|
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) {
|
|
w.projectileVisual(*shot, "impact", "cancelled")
|
|
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 _, id := range w.structureIDs() {
|
|
if f, ok := boxFraction(shot.Position, end, w.Structures[id].Entity, 0, 0); ok && f*length3(shot.Position, end) < best {
|
|
best = f * length3(shot.Position, end)
|
|
hit = id
|
|
hitPoint = lerp3(shot.Position, end, f)
|
|
}
|
|
}
|
|
for _, e := range w.combatTargets(shot.Player, shot.Attack.Effect) {
|
|
if e.Kind == "structure" {
|
|
continue
|
|
}
|
|
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)
|
|
outcome := "miss"
|
|
if hit != "" {
|
|
outcome = "hit"
|
|
} else if blocked {
|
|
outcome = "terrain"
|
|
}
|
|
w.projectileVisual(copy, "impact", outcome)
|
|
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 area.MovingAura {
|
|
if c := w.Characters[area.Source]; c != nil {
|
|
area.Position = body(c.View.Entity.Position)
|
|
}
|
|
}
|
|
if w.Age() >= area.NextAt {
|
|
w.areaPulse(area.Projectile)
|
|
area.NextAt = w.Age() + area.Attack.Interval
|
|
w.dirty = true
|
|
}
|
|
}
|
|
}
|
|
|
|
// Short, bounded event history lets a launch and impact survive between network
|
|
// snapshots. This is presentation data; damage is resolved only by updateCombat.
|
|
func (w *World) projectileVisual(shot Projectile, phase, outcome string) {
|
|
w.ProjectileVisuals = append(w.ProjectileVisuals, p.ProjectileVisual{ID: w.combatID("visual"), ProjectileID: shot.ID, Phase: phase, Position: shot.Position, Destination: shot.Destination, Speed: shot.Attack.Speed, Outcome: outcome, At: w.Age()})
|
|
if len(w.ProjectileVisuals) > 1024 {
|
|
w.ProjectileVisuals = w.ProjectileVisuals[len(w.ProjectileVisuals)-1024:]
|
|
}
|
|
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
|
|
}
|