server/combat.go (27461B)
1 package main 2 3 import ( 4 "ao/server/gamedata" 5 "encoding/binary" 6 "fmt" 7 "log" 8 "maps" 9 "math" 10 "math/rand/v2" 11 "slices" 12 "sort" 13 "time" 14 ) 15 16 func attackPacket(attacker, target uint32) []byte { 17 body := binary.BigEndian.AppendUint32(nil, 50000) 18 body = binary.BigEndian.AppendUint32(body, target) 19 body = append(body, 1) 20 return n3Packet(0x28494070, 50000, attacker, body) 21 } 22 23 func stopFightPacket(attacker uint32) []byte { 24 return n3Packet(0x4a41203e, 50000, attacker, []byte{0, 0, 0, 1}) 25 } 26 27 func (server *server) handleCombat(client *worldClient, body []byte) error { 28 key := binary.BigEndian.Uint32(body) 29 if key == 0x28494070 && len(body) < 25 || (key == 0x4a41203e || key == 0x76793f0d) && len(body) < 20 { 30 return fmt.Errorf("short combat message") 31 } 32 player := server.characters[client.id] 33 if server.clients[client.id] != client || !client.ready || client.loading || player.health == 0 { 34 return nil 35 } 36 37 updates := make(map[*worldClient][][]byte) 38 if key == 0x76793f0d { 39 // SetAggDefIIR_t carries one signed integer in the range -100..100. 40 value := int32(binary.BigEndian.Uint32(body[16:20])) 41 if value >= -100 && value <= 100 { 42 player.aggDef = value 43 stats := binary.BigEndian.AppendUint32(nil, 51) 44 stats = binary.BigEndian.AppendUint32(stats, uint32(value)) 45 server.queueCombat(updates, player, player, n3Packet(0x2b333d6e, 50000, player.id, stats)) 46 } 47 } else if key == 0x4a41203e || binary.BigEndian.Uint32(body[20:24]) == 0 { 48 server.stopAttack(player, updates) 49 } else { 50 // Admit only visible PvE encounters with the shared targeting policy. 51 target := server.characters[binary.BigEndian.Uint32(body[20:24])] 52 now := time.Now() 53 if !player.driving() && binary.BigEndian.Uint32(body[16:20]) == 50000 && target != nil && target.attackableNPC() && 54 client.npcs[target.id] && target.health > 0 && 55 target.playfield == player.playfield && server.combatInRange(player, target, now) && server.combatVisible(player, target, now) { 56 server.startAttack(player, target, now, updates) 57 } else { 58 if player.fighting == 0 { 59 updates[client] = append(updates[client], stopFightPacket(player.id)) 60 } else { 61 server.stopAttack(player, updates) 62 } 63 } 64 } 65 server.sendCombatUpdates(updates) 66 return nil 67 } 68 69 func weaponDelays(weapon *gamedata.Item, initiative, aggDef int32) (time.Duration, time.Duration) { 70 // kkr.dll FUN_1007ab40/FUN_1007ac10, QL 1 fist ItemDelay/RechargeDelay 125. 71 attackBase, rechargeBase := uint32(125), uint32(125) 72 if weapon != nil { 73 attackBase, rechargeBase = itemStat(weapon, 294), itemStat(weapon, 210) 74 } 75 effective := float64(initiative) * 0.5 76 if initiative > 1200 { 77 effective = 600 + float64(initiative-1200)*float64(float32(1.0/6)) 78 } 79 // Native float stores precede AggDef subtraction and centisecond truncation. 80 attack := float64(float32(float64(attackBase+75)-effective*float64(float32(1.0/3)))) - float64(aggDef) 81 recharge := float64(float32(float64(rechargeBase+75)-effective*float64(float32(2.0/3)))) - float64(aggDef) 82 return time.Duration(max(100, int(attack))) * 10 * time.Millisecond, time.Duration(max(100, int(recharge))) * 10 * time.Millisecond 83 } 84 85 func (character *character) attackDelays() (time.Duration, time.Duration) { 86 if character.npc { 87 if character.combatProfile != nil { 88 weapon := character.attackWeapon() 89 initiative := uint32(119) 90 if weapon != nil && itemStat(weapon, 440) != 0 { 91 initiative = itemStat(weapon, 440) 92 } 93 return weaponDelays(weapon, character.combatProfile.Initiative+character.nanoBonus(initiative), character.combatProfile.AggDef) 94 } 95 return time.Second, time.Second 96 } 97 // Weapon timing requests effective stat51; the slider remains its base value. 98 aggDef := character.aggDef + character.equipmentBonus(51) + character.nanoBonus(51) 99 stats := character.baseStats() 100 weapon := character.attackWeapon() 101 if weapon != nil { 102 // WeaponItem defaults to RangedInit; authored 440 selects the actual skill. 103 initiative := uint32(119) 104 for _, stat := range weapon.Stats { 105 if stat[0] == 440 { 106 initiative = stat[1] 107 } 108 } 109 value, _ := character.effectiveStat(initiative) 110 return weaponDelays(weapon, value, aggDef) 111 } 112 initiative := character.effectiveSkill(120, stats.Speed.PhysicalInitiative, [6]uint32{0, 10, 0, 10, 60, 20}) 113 return weaponDelays(nil, initiative, aggDef) 114 } 115 116 func (character *character) titleLevel() uint32 { 117 title := uint32(1) 118 for _, threshold := range []uint16{15, 50, 100, 150, 190} { 119 if character.level >= threshold { 120 title++ 121 } 122 } 123 return title 124 } 125 126 func (character *character) maximumHealth() uint32 { 127 if character.npc { 128 if character.combatProfile != nil { 129 return character.combatProfile.Health 130 } 131 return 100 132 } 133 // kkr.dll FUN_10075910; breed 1000203 and profession/title 1000200 coefficients. 134 stats := [8][3]uint32{{2, 2, 2}, {10, 6, 3}, {15, 5, 3}, {10, 5, 2}, {25, 6, 4}, {15, 8, 6}, {2, 2, 2}, {2, 2, 2}}[character.appearance>>4&7] 135 base := character.baseStats() 136 bodyDevelopment := character.effectiveSkill(152, base.Body.BodyDevelopment, [6]uint32{0, 0, 100, 0, 0, 0}) 137 return uint32(int32(stats[0]) + int32(character.level)*int32(stats[1]+gamedata.ProfessionTitles[max(1, character.profession)].Health[character.titleLevel()-1]) + bodyDevelopment*int32(stats[2]) + character.equipmentBonus(1) + character.nanoBonus(1)) 138 } 139 140 func (character *character) directHealthBonus() int32 { 141 // Native snapshots separate authored OnWear/Modify bonuses from the foundation. 142 return character.inventory.equipmentBonus(1) + character.nanoBonus(1) 143 } 144 145 func (character *character) maximumNano() uint32 { 146 if character.pet != nil { 147 if character.pet.program == 43325 { 148 return 0 149 } 150 return 25 151 } 152 // kkr.dll FUN_10075910 uses real profession and stored title, as for health. 153 stats := [8][3]uint32{{2, 2, 2}, {10, 4, 3}, {10, 3, 3}, {15, 5, 4}, {8, 2, 2}, {50, 2, 1}, {2, 2, 2}, {2, 2, 2}}[character.appearance>>4&7] 154 base := character.baseStats() 155 nanoPool := character.effectiveSkill(132, base.Body.NanoPool, [6]uint32{0, 0, 10, 10, 10, 70}) 156 return uint32(int32(stats[0]) + int32(character.level)*int32(stats[1]+gamedata.ProfessionTitles[max(1, character.profession)].Nano[character.titleLevel()-1]) + nanoPool*int32(stats[2]) + character.inventory.equipmentBonus(221)) 157 } 158 159 func (character *character) attackRating() int32 { 160 return character.weaponRating(character.attackWeapon(), 12) 161 } 162 163 func (character *character) weaponRating(weapon *gamedata.Item, kind uint32) int32 { 164 // kkr.dll 1008f1f0/1008f2f0 use sections 12/13 and divide each term separately. 165 var rating int32 166 if weapon == nil { 167 // Martial Arts Item43712: attack MA100, defense EvadeClose155, both 100%. 168 stat := uint32(100) 169 if kind == 13 { 170 stat = 155 171 } 172 rating = character.combatSkill(stat) 173 } else { 174 for _, section := range weapon.Sections { 175 if section.Type != 4 || section.Subtype != 4 || section.Entries == nil { 176 continue 177 } 178 for _, entry := range *section.Entries { 179 if entry.Type != nil && *entry.Type == kind { 180 for _, weight := range *entry.Stats { 181 rating += character.combatSkill(weight[0]) * int32(weight[1]) / 100 182 } 183 } 184 } 185 } 186 } 187 if rating > 0 { 188 modifier := uint32(276) 189 if kind == 13 { 190 modifier = 277 191 } 192 rating += character.equipmentBonus(modifier) + character.nanoBonus(modifier) 193 } 194 return rating 195 } 196 197 func (character *character) combatSkill(stat uint32) int32 { 198 if character.npc { 199 // kkr.dll 1006dfb0 mode 2 reads NPC raw skills, without player trickle/modifiers. 200 stats := character.baseStats() 201 for _, field := range stats.trainingStats() { 202 if field.stat == stat { 203 return int32(*field.value) 204 } 205 } 206 return 0 207 } 208 value, _ := character.effectiveStat(stat) 209 return value 210 } 211 212 func (server *server) weaponLands(attacker, target *character) bool { 213 return server.itemAttackLands(attacker, target, attacker.attackWeapon()) 214 } 215 216 func (server *server) itemAttackLands(attacker, target *character, item *gamedata.Item) bool { 217 attack := float64(attacker.weaponRating(item, 12)) 218 defense := float64(max(0, target.weaponRating(item, 13))) 219 aggDef := target.aggDef 220 if target.npc && target.combatProfile != nil { 221 aggDef = target.combatProfile.AggDef 222 } 223 aggDef += target.equipmentBonus(51) + target.nanoBonus(51) 224 225 // Ebag333's later empirical weapon curve is provisional for 14.9.1. 226 chance := float64(0) 227 if attack > 0 { 228 chance = min(1, (3.75+0.0075*float64(min(100, max(-100, aggDef))))*math.Pow(attack/(attack+defense), 2.25)) 229 } 230 roll := server.combatRoll 231 if roll == nil { 232 roll = rand.Uint32N 233 } 234 return roll(10000) < uint32(chance*10000) 235 } 236 237 func (server *server) weaponHit(attacker, target *character) (uint32, bool) { 238 roll := server.combatRoll 239 if roll == nil { 240 roll = rand.Uint32N 241 } 242 // The period 3% baseline is provisional; NPC ratings are not established. 243 chance := min(100, max(0, int64(3)+int64(attacker.equipmentBonus(379))+int64(attacker.nanoBonus(379)))) 244 critical := int64(roll(100)) < chance 245 return min(attacker.weaponDamage(target, critical, roll), target.health), critical 246 } 247 248 func (attacker *character) weaponDamage(target *character, critical bool, roll func(uint32) uint32) uint32 { 249 return attacker.itemDamage(target, attacker.attackWeapon(), critical, roll) 250 } 251 252 func (attacker *character) itemDamage(target *character, weapon *gamedata.Item, critical bool, roll func(uint32) uint32) uint32 { 253 // Exact catalog endpoints and the weapon's native protection type. 254 minimum, maximum, bonus, damageType := uint32(3), uint32(5), uint32(3), uint32(91) 255 if weapon != nil { 256 minimum, maximum = itemStat(weapon, 286), itemStat(weapon, 285) 257 bonus = itemStat(weapon, 284) 258 // kkr.dll 100abb20 seeds omitted DamageType436 with MeleeAC91. 259 for _, stat := range weapon.Stats { 260 if stat[0] == 436 { 261 damageType = stat[1] 262 } 263 } 264 // kkr.dll FUN_100ab7b0 accepts the eight ACs and NanoAC, else ProjectileAC. 265 if (damageType < 90 || damageType > 97) && damageType != 168 { 266 damageType = 90 267 } 268 } else if attacker.npc { 269 minimum, maximum = 5, 5 270 bonus = 0 // Prototype NPCs without a catalog weapon have no critical bonus. 271 } 272 if critical { 273 // The critical AC floor and OE ordering are provisional; see critical-hits.md. 274 minimum += bonus 275 maximum += bonus 276 } 277 278 // Player fists use MA; equipped weapons use their authored attack skills. 279 // NPC attack skills remain unknown. Fractional endpoint truncation is provisional. 280 if !attacker.npc { 281 rating := attacker.weaponRating(weapon, 12) 282 if weapon != nil { 283 tier := attacker.weaponOverequippingTier(weapon) 284 minimum -= minimum * tier / 4 285 maximum -= maximum * tier / 4 286 } 287 minimum = uint32(int64(minimum) + int64(minimum)*int64(rating)/400) 288 maximum = uint32(int64(maximum) + int64(maximum)*int64(rating)/400) 289 } 290 291 // Period AC rule: reduce the rolled hit without crossing the weapon minimum. 292 // Truncating AC/10 before subtraction is provisional integer ordering. 293 damage := maximum 294 if !critical { 295 damage = minimum + roll(maximum-minimum+1) 296 } 297 damage -= min(damage-minimum, uint32(target.equipmentBonus(damageType)+target.nanoBonus(damageType))/10) 298 299 // Add the matching damage modifier after attack rating and the AC floor. 300 modifier := uint32(315) // NanoDamageModifier 301 if damageType >= 90 && damageType <= 97 { 302 modifier = [8]uint32{278, 279, 280, 281, 282, 311, 317, 316}[damageType-90] 303 } 304 return damage + uint32(attacker.equipmentBonus(modifier)+attacker.nanoBonus(modifier)) 305 } 306 307 func (character *character) physicalExtent() float32 { 308 // FUN_1005a790 scales CharRadius421 by Scale360; Kodaik OnWear sets it to 20. 309 scale := int32(character.baseScale()) 310 if character.driving() { 311 scale = 20 312 } 313 scale += character.inventory.equipmentBonus(360) 314 radius := uint32(2) 315 if monster, exists := gamedata.MonsterTemplates[character.monsterData]; exists { 316 if value, exists := monster.Stats[421]; exists { 317 radius = value 318 } 319 } 320 return float32(scale*int32(radius)) * float32(0.01) 321 } 322 323 func (server *server) combatInRange(attacker, target *character, now time.Time) bool { 324 first, second := attacker.position, target.position 325 if !attacker.npc { 326 first = predictedPosition(attacker, now) 327 } 328 if !target.npc { 329 second = predictedPosition(target, now) 330 } 331 x, y, z := first[0]-second[0], first[1]-second[1], first[2]-second[2] 332 itemRange := int32(2) 333 if weapon := attacker.attackWeapon(); weapon != nil { 334 itemRange = int32(itemStat(weapon, 287)) 335 } 336 // client/game/kkr.dll/lifted-0050.c::sub_360AAE10 uses a signed product 337 // and float32 .01, without a float32 store before truncation and the 40 cap. 338 itemRange = min(40, int32(float64(itemRange*attacker.equipmentBonus(380))*float64(float32(0.01))+float64(itemRange))) 339 // FUN_10078cb0 adds the attacker's extent twice and the target's once. 340 distance := float32(itemRange) + 2*attacker.physicalExtent() + target.physicalExtent() 341 return distance >= 0 && x*x+y*y+z*z <= distance*distance 342 } 343 344 func (server *server) startAttack(attacker, target *character, now time.Time, updates map[*worldClient][][]byte) { 345 server.leaveSneak(attacker, now, updates) 346 server.leaveSneak(target, now, updates) 347 // Repeated requests must not restart or accelerate the attack clock. 348 if attacker.fighting == target.id { 349 return 350 } 351 if attacker.motion != nil { 352 server.stopNPCMotion(attacker, updates) 353 attacker.motion.returning = false 354 } 355 // AttackIIR submits stand only from helper8, independently of retained posture430. 356 // Source: client/game/kkr.dll/lifted-0035.c, sub_36078FC0. 357 if !attacker.npc { 358 attacker.movement.prepare(attacker, now) 359 if attacker.movement.components[0] == 8 { 360 attacker.movement.action(attacker, 33) 361 } 362 } 363 server.combatPresence(attacker, target.id) 364 attacker.fighting = target.id 365 attacker.nextAttack = now 366 if attacker.nextAttack.Before(attacker.rechargeUntil) { 367 attacker.nextAttack = attacker.rechargeUntil 368 } 369 if client := server.clients[attacker.id]; client != nil && client.nanoCast != nil && attacker.nextAttack.Before(client.nanoCast.weaponResumeAt) { 370 attacker.nextAttack = client.nanoCast.weaponResumeAt 371 } 372 attack, _ := attacker.attackDelays() 373 attacker.nextAttack = attacker.nextAttack.Add(attack) 374 server.fighting[attacker.id] = attacker 375 server.queueCombat(updates, attacker, target, attackPacket(attacker.id, target.id)) 376 } 377 378 func (server *server) stopAttack(attacker *character, updates map[*worldClient][][]byte) { 379 if attacker.fighting == 0 { 380 delete(server.fighting, attacker.id) 381 return 382 } 383 server.combatPresence(attacker, 0) 384 attacker.fighting = 0 385 attacker.nextAttack = time.Time{} 386 delete(server.fighting, attacker.id) 387 server.queueCombat(updates, attacker, attacker, stopFightPacket(attacker.id)) 388 if attacker.motion != nil && attacker.combatProfile != nil { 389 server.stopNPCMotion(attacker, updates) 390 attacker.motion.returning = attacker.health != 0 && attacker.position != attacker.motion.home 391 } 392 } 393 394 func (server *server) cancelCombat(id uint32, updates map[*worldClient][][]byte) { 395 // Threat belongs to this encounter, independently of lifetime damage credit. 396 for _, npc := range server.characters { 397 if _, exists := npc.threat[id]; exists { 398 delete(npc.threat, id) 399 server.selectNPCTarget(npc, time.Now(), updates) 400 } 401 } 402 // Leaving or dying also releases every opponent targeting this character. 403 for _, attacker := range server.fighting { 404 if attacker.id == id || attacker.fighting == id { 405 server.stopAttack(attacker, updates) 406 } 407 } 408 if client := server.clients[id]; client != nil { 409 server.abortNano(client, time.Now(), updates) 410 } 411 } 412 413 func (server *server) advanceCombat(now time.Time) { 414 updates := make(map[*worldClient][][]byte) 415 416 // An unavailable opponent must not prevent another participant taking over. 417 for _, attacker := range server.fighting { 418 if attacker.npc && len(attacker.threat) != 0 && server.npcActive(attacker, now) { 419 server.selectNPCTarget(attacker, now, updates) 420 } 421 } 422 423 // Resolve simultaneous swings in identity order, without replaying missed ticks. 424 ids := make([]uint32, 0, len(server.fighting)) 425 for id := range server.fighting { 426 ids = append(ids, id) 427 } 428 sort.Slice(ids, func(i, j int) bool { return ids[i] < ids[j] }) 429 for _, id := range ids { 430 attacker := server.fighting[id] 431 if attacker == nil || attacker.npc && !server.npcActive(attacker, now) { 432 continue 433 } 434 target := server.characters[attacker.fighting] 435 if target == nil || attacker.health == 0 || target.health == 0 || attacker.playfield != target.playfield { 436 server.stopAttack(attacker, updates) 437 continue 438 } 439 // Owned pets share their owner's connection and playfield availability. 440 if !server.combatParticipantAvailable(attacker, now) || !server.combatParticipantAvailable(target, now) { 441 server.stopAttack(attacker, updates) 442 continue 443 } 444 if !server.combatInRange(attacker, target, now) || !server.combatVisible(attacker, target, now) { 445 // Engaged creatures wait for a clear path without restarting their swing. 446 if !attacker.npc || attacker.combatProfile == nil { 447 server.stopAttack(attacker, updates) 448 } 449 continue 450 } 451 if attacker.brawlStunned() || now.Before(attacker.nextAttack) { 452 continue 453 } 454 damage, result := uint32(0), uint32(3) 455 if server.weaponLands(attacker, target) { 456 var critical bool 457 damage, critical = server.weaponHit(attacker, target) 458 result = 4 459 if critical { 460 result = 5 461 } 462 } 463 previous := *target 464 fired, award, err := server.applyWeaponDamage(attacker, target, damage, now) 465 if err != nil { 466 log.Printf("Damage: %v", err) 467 server.cancelCombat(target.id, updates) 468 continue 469 } 470 if !fired { 471 server.stopAttack(attacker, updates) 472 continue 473 } 474 attack, recharge := attacker.attackDelays() 475 attacker.rechargeUntil = now.Add(recharge) 476 attacker.nextAttack = attacker.rechargeUntil.Add(attack) 477 server.queueCombat(updates, attacker, target, weaponResultPacket(attacker, target, damage, result)) 478 server.finishDamageEffects(attacker, target, previous, now, updates) 479 server.applyExperienceAward(award, now, updates) 480 } 481 server.sendCombatUpdates(updates) 482 } 483 484 type damageContributor struct { 485 player uint32 486 team uint32 487 } 488 489 func (server *server) applyDamage(attacker, target *character, damage uint32, now time.Time) (*experienceAward, error) { 490 // Death or a control break commits before the new actor state becomes visible. 491 candidate := server.prepareWeaponDamage(attacker, target, damage, now) 492 var award *experienceAward 493 if candidate.health == 0 || len(candidate.activeNanos) != len(target.activeNanos) { 494 var err error 495 award, err = server.saveDamageOutcome(&candidate, now) 496 if err != nil { 497 return nil, err 498 } 499 } 500 *target = candidate 501 return award, nil 502 } 503 504 func (server *server) prepareDamage(attacker, target *character, damage uint32, now time.Time) character { 505 // Work on detached mutable state until the outcome's transaction succeeds. 506 candidate := *target 507 candidate.health -= damage 508 if candidate.health == 0 { 509 candidate.activeNanos = nil 510 } 511 if candidate.health == 0 && !candidate.npc { 512 // Classic insurance cannot remove a level; the shipped scanner protects levels below 20. 513 if candidate.level >= 20 { 514 lower, _ := candidate.experienceBounds() 515 candidate.experience = max(lower, candidate.insuredExperience) - lower 516 } 517 candidate.nano = min(candidate.nano+candidate.nanoReserved, candidate.maximumNano()) 518 candidate.nanoReserved = 0 519 candidate.collectReclaim(now) 520 } 521 candidate.damageContributors = maps.Clone(target.damageContributors) 522 candidate.threat = maps.Clone(target.threat) 523 if target.corpse != nil { 524 corpse := *target.corpse 525 candidate.corpse = &corpse 526 } 527 // Threat follows the attacking actor; reward credit follows its owner/team. 528 owner := attacker 529 if attacker.pet != nil { 530 owner = server.characters[attacker.pet.owner] 531 } 532 if candidate.npc && candidate.pet == nil && !owner.npc && damage != 0 { 533 if candidate.threat == nil { 534 candidate.threat = make(map[uint32]int64) 535 } 536 candidate.threat[attacker.id] += int64(damage) 537 if candidate.damageContributors == nil { 538 candidate.damageContributors = make(map[damageContributor]uint32) 539 } 540 contributor := damageContributor{player: owner.id} 541 if owner.team != nil { 542 contributor = damageContributor{team: owner.team.id} 543 } 544 candidate.damageContributors[contributor] += damage 545 // Equal totals retain the first contributor to reach that total. 546 if candidate.damageContributors[contributor] > candidate.damageContributors[candidate.leadingContributor] { 547 candidate.leadingContributor = contributor 548 } 549 } 550 if candidate.health == 0 { 551 candidate.threat = nil 552 } 553 monster := gamedata.MonsterTemplates[candidate.monsterData] 554 if candidate.health == 0 && candidate.npc && candidate.pet == nil && monster != nil && len(monster.DeathAnimations) != 0 { 555 if candidate.corpse == nil { 556 candidate.corpse = &npcCorpse{} 557 } 558 candidate.corpse.looter = candidate.leadingContributor.player 559 candidate.corpse.team = candidate.leadingContributor.team 560 candidate.damageContributors = nil 561 if candidate.combatProfile != nil && candidate.combatProfile.CorpseSeconds != 0 { 562 candidate.corpse.expiresAt = now.Add(time.Duration(candidate.combatProfile.CorpseSeconds) * time.Second) 563 } else if gamedata.NPCLootTables[candidate.npcDefinitionID] != nil { 564 candidate.corpse.expiresAt = now.Add(180 * time.Second) 565 } 566 server.placeCorpse(&candidate) 567 } 568 return candidate 569 } 570 571 func (server *server) finishDamageEffects(attacker, target *character, previous character, now time.Time, updates map[*worldClient][][]byte) { 572 if target.health == 0 && target.pet != nil { 573 // The committed lethal hit dissolves the summon and frees the owner's slot. 574 server.removePet(target, updates) 575 return 576 } 577 if target.health != 0 { 578 for _, effect := range previous.activeNanos { 579 // Replacement replays its strain through Action177; breaks need explicit removal. 580 if !slices.ContainsFunc(target.activeNanos, func(active activeNano) bool { return nanoStat(active.program, 75) == nanoStat(effect.program, 75) }) { 581 server.queueCombat(updates, target, target, characterActionPacket(target.id, [5]uint32{65, 0, 0, effect.caster, effect.program})) 582 } 583 } 584 } 585 if target.health == 0 { 586 if !target.npc { 587 client := server.clients[target.id] 588 server.cancelPlayerTrade(client) 589 target.position = predictedPosition(&previous, now) 590 target.followTarget = 0 591 target.movement = playerMovement{} 592 client.reclaimItems = nil 593 client.bank = nil 594 client.backpacks = nil 595 } 596 server.cancelCombat(target.id, updates) 597 if target.motion != nil { 598 // A returning creature can die without an entry in the combat map. 599 server.stopNPCMotion(target, updates) 600 target.motion.returning = false 601 } 602 server.queueCombat(updates, target, target, deathPacket(target)) 603 if !target.npc && target.experience != previous.experience { 604 if owner := server.clients[target.id]; owner != nil && owner.ready && !owner.loading { 605 lower, _ := target.experienceBounds() 606 body := binary.BigEndian.AppendUint32(nil, 52) 607 body = binary.BigEndian.AppendUint32(body, lower+target.experience) 608 updates[owner] = append(updates[owner], n3Packet(0x2b333d6e, 50000, target.id, body)) 609 } 610 } 611 if len(previous.activeNanos) != 0 { 612 // StopFight drains queued weapon hits before modifiers and maxima change. 613 for _, effect := range previous.activeNanos { 614 server.queueCombat(updates, target, target, characterActionPacket(target.id, [5]uint32{65, 0, 0, effect.caster, effect.program})) 615 } 616 if !target.npc { 617 previous.position = target.position 618 server.finishResourceChange(updates, target, previous, now) 619 } 620 } 621 monster := gamedata.MonsterTemplates[target.monsterData] 622 if target.npc && monster != nil && len(monster.DeathAnimations) != 0 { 623 if target.corpse != nil && !target.corpse.expiresAt.IsZero() { 624 server.corpseExpiry = append(server.corpseExpiry, target) 625 } 626 if target.position != previous.position { 627 // Activation otherwise copies the nearby living actor's old pose. 628 // Source: client/game/kkr.dll/lifted-0052.c, sub_360AFCB0. 629 server.queueCombat(updates, target, target, n3Packet(0x36510078, 50000, target.id, nil)) 630 } 631 server.queueCombat(updates, target, target, corpsePacket(target)) 632 } 633 if respawn := server.npcRespawnAt(target, now); target.npc && !respawn.IsZero() { 634 server.npcRespawns = append(server.npcRespawns, npcRespawn{ 635 npc: target, at: respawn, 636 }) 637 } 638 } else if target.npc && target.pet == nil && (!attacker.npc || attacker.pet != nil) { 639 // A hostile cast or a zero-damage hit still starts an encounter. 640 if target.threat == nil { 641 target.threat = make(map[uint32]int64) 642 } 643 if _, exists := target.threat[attacker.id]; !exists { 644 target.threat[attacker.id] = 0 645 } 646 server.selectNPCTarget(target, now, updates) 647 } 648 } 649 650 func (server *server) queueCombat(updates map[*worldClient][][]byte, character, target *character, packets ...[]byte) { 651 // Ready means the actor snapshot is queued; keep later updates ordered behind it 652 // even while the observer's own character is still finishing native loading. 653 for id, client := range server.clients { 654 if client.ready && server.characters[id].playfield == character.playfield && 655 client.sees(character) && client.sees(target) { 656 updates[client] = append(updates[client], packets...) 657 } 658 } 659 } 660 661 func (server *server) sendCombatUpdates(updates map[*worldClient][][]byte) { 662 // Queued broadcasts share packet slices. Cache conversion by their first byte's 663 // address for this batch only; sendEncoded copies before stamping each recipient. 664 native := make(map[*byte][]byte) 665 for client, packets := range updates { 666 for _, packet := range packets { 667 encoded := packet 668 if client.target && binary.BigEndian.Uint16(packet[2:4]) == 10 { 669 encoded = native[&packet[0]] 670 if encoded == nil { 671 encoded = targetPacket(append([]byte(nil), packet...)) 672 native[&packet[0]] = encoded 673 } 674 } 675 if err := client.sendEncoded(encoded); err != nil { 676 if client.ready { 677 log.Printf("Combat: %v", err) 678 } 679 client.ready = false 680 client.disconnect(client.conn) 681 break 682 } 683 } 684 } 685 } 686 687 func weaponResultPacket(attacker, target *character, damage, result uint32) []byte { 688 slot := uint32(0) 689 ammo := uint32(0xffffffff) 690 if !attacker.npc && attacker.attackWeapon() != nil { 691 slot = 6 692 } 693 for _, item := range attacker.inventory.Items { 694 if item.Slot == 6 && item.usesAmmo() { 695 ammo = item.Ammo 696 } 697 } 698 if result == 3 { 699 // kkr.dll 100b1460/100b14f0: miss queues zero damage and the same ammo/slot. 700 var body []byte 701 for _, value := range []uint32{ammo, slot, 50000, attacker.id, 50000, target.id} { 702 body = binary.BigEndian.AppendUint32(body, value) 703 } 704 return n3Packet(0x5c654b28, 50000, attacker.id, body) 705 } 706 // kkr.dll 100aec00: damage, ammo, slot, target identity, death reason and result. 707 body := binary.BigEndian.AppendUint32(nil, damage) 708 for _, value := range []uint32{ammo, slot, 50000, target.id, 0, result} { 709 body = binary.BigEndian.AppendUint32(body, value) 710 } 711 if target.health == 0 { 712 binary.BigEndian.PutUint32(body[20:24], 4) 713 } 714 return n3Packet(0x46002f16, 50000, attacker.id, body) 715 } 716 717 func deathPacket(character *character) []byte { 718 // kkr.dll 0x10070327: action 99 sets the corpse visual flag and death animation. 719 animation := uint32(500) 720 if character.npc { 721 animation = 6000 722 } 723 var body []byte 724 for _, value := range []uint32{99, 0, 0, 0, animation} { 725 body = binary.BigEndian.AppendUint32(body, value) 726 } 727 return n3Packet(0x5e477770, 50000, character.id, body) 728 }