aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


server/npc_loot_test.go (15819B)


      1 package main
      2 
      3 import (
      4 	"ao/server/gamedata"
      5 	"encoding/binary"
      6 	"fmt"
      7 	"slices"
      8 	"sync"
      9 	"testing"
     10 	"time"
     11 )
     12 
     13 func TestNPCDeathCommitsGeneratedLootAcrossAttackPaths(t *testing.T) {
     14 	for _, attack := range []string{"unarmed", "axe", "pistol", "fling", "fast", "nano"} {
     15 		t.Run(attack, func(t *testing.T) {
     16 			world, _ := newKillExperienceWorld(t, attack)
     17 			world.combatRoll = func(uint32) uint32 { return 0 }
     18 			before := world.nextItem
     19 
     20 			attackForExperience(t, world, attack)
     21 			world.advanceCombat(time.Now().Add(time.Hour))
     22 			world.advanceNanos(time.Now().Add(time.Hour))
     23 			cold := newTestInventoryServer(t)
     24 
     25 			expected := []ownedItem{{ID: before + 1, Type: 51005, Template: 42640, Quality: 1, Count: 1}}
     26 			for _, current := range []*server{world, cold} {
     27 				corpse := current.characters[1000000].corpse
     28 				if current.characters[1000000].health != 0 || corpse == nil || !slices.Equal(corpse.items, expected) || corpse.credits != 1 || corpse.looter != 1 || current.characters[1].experience != 100 || current.nextItem != before+1 {
     29 					t.Fatal("death, loot, cash, ownership, XP or allocation did not commit together", corpse, current.nextItem)
     30 				}
     31 				if current.items[before+1].Template != 42640 || current.itemPlacements[before+1] != (itemPlacement{Corpse: 1000000}) {
     32 					t.Fatal("generated instance is absent from the shared item/placement cache")
     33 				}
     34 			}
     35 		})
     36 	}
     37 }
     38 
     39 func TestNPCLootChanceAndCashBoundaries(t *testing.T) {
     40 	for _, scenario := range []struct {
     41 		roll, cash uint32
     42 		items      int
     43 	}{{0, 1, 1}, {49, 5, 1}, {50, 5, 0}, {99, 5, 0}} {
     44 		t.Run(fmt.Sprint(scenario.roll), func(t *testing.T) {
     45 			world, _ := newKillExperienceWorld(t, "unarmed")
     46 			world.combatRoll = func(limit uint32) uint32 { return min(scenario.roll, limit-1) }
     47 			before := world.nextItem
     48 
     49 			attackForExperience(t, world, "unarmed")
     50 			cold := newTestInventoryServer(t)
     51 
     52 			for _, current := range []*server{world, cold} {
     53 				corpse := current.characters[1000000].corpse
     54 				if corpse == nil || len(corpse.items) != scenario.items || corpse.credits != scenario.cash || current.nextItem != before+uint32(scenario.items) {
     55 					t.Fatal("chance boundary, inclusive cash range or empty-result allocation", corpse, current.nextItem)
     56 				}
     57 			}
     58 		})
     59 	}
     60 }
     61 
     62 func TestNPCLootFailedDeathPreservesStateAndRetries(t *testing.T) {
     63 	for _, attack := range []string{"unarmed", "axe", "pistol", "fling", "fast", "nano"} {
     64 		for _, failure := range []struct{ name, sql string }{
     65 			{"item", "CREATE TRIGGER fail_loot BEFORE INSERT ON items BEGIN SELECT RAISE(FAIL,'loot item'); END"},
     66 			{"ignored item", "CREATE TRIGGER fail_loot BEFORE INSERT ON items BEGIN SELECT RAISE(IGNORE); END"},
     67 			{"placement", "CREATE TRIGGER fail_loot BEFORE INSERT ON item_locations BEGIN SELECT RAISE(FAIL,'loot placement'); END"},
     68 			{"ignored placement", "CREATE TRIGGER fail_loot BEFORE INSERT ON item_locations BEGIN SELECT RAISE(IGNORE); END"},
     69 			{"allocation", "CREATE TRIGGER fail_loot BEFORE UPDATE OF last_item_id ON world BEGIN SELECT RAISE(FAIL,'loot allocation'); END"},
     70 			{"ignored allocation", "CREATE TRIGGER fail_loot BEFORE UPDATE OF last_item_id ON world BEGIN SELECT RAISE(IGNORE); END"},
     71 			{"commit", "CREATE TABLE pending_loot (player_id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_loot AFTER INSERT ON items BEGIN INSERT INTO pending_loot VALUES(999999); END"},
     72 		} {
     73 			t.Run(attack+"/"+failure.name, func(t *testing.T) {
     74 				world, output := newKillExperienceWorld(t, attack)
     75 				world.combatRoll = func(uint32) uint32 { return 0 }
     76 				before, itemCount, placementCount := world.nextItem, len(world.items), len(world.itemPlacements)
     77 				if _, err := world.db.Exec(failure.sql); err != nil {
     78 					t.Fatal(err)
     79 				}
     80 
     81 				switch attack {
     82 				case "fling":
     83 					if err := world.handleWeaponSpecial(world.clients[1], flingShotRequest(1, 1000000)[20:]); err == nil {
     84 						t.Fatal("failed Fling loot returned success")
     85 					}
     86 				case "fast":
     87 					if err := world.handleWeaponSpecial(world.clients[1], fastAttackRequest(1, 1000000)[20:]); err == nil {
     88 						t.Fatal("failed Fast Attack loot returned success")
     89 					}
     90 				default:
     91 					attackForExperience(t, world, attack)
     92 				}
     93 				cold := newTestInventoryServer(t)
     94 
     95 				for _, current := range []*server{world, cold} {
     96 					if current.characters[1000000].health != 1 || current.characters[1000000].corpse != nil || current.characters[1].experience != 0 || current.nextItem != before || len(current.items) != itemCount || len(current.itemPlacements) != placementCount {
     97 						t.Fatal("failed loot transaction leaked death, reward, allocation or cached item state")
     98 					}
     99 				}
    100 				for _, packet := range output.packets {
    101 					switch binary.BigEndian.Uint32(packet[16:20]) {
    102 					case 0x46002f16, 0x754f1115, 0x4727213e, 0x4f474e05, 0x7f405a16:
    103 						t.Fatal("failed loot outcome published damage, corpse or progression")
    104 					}
    105 				}
    106 
    107 				// Retry the same public attack after removing the fault.
    108 				if _, err := world.db.Exec("DROP TRIGGER fail_loot"); err != nil {
    109 					t.Fatal(err)
    110 				}
    111 				attackForExperience(t, world, attack)
    112 				again := newTestInventoryServer(t)
    113 				if len(again.characters[1000000].corpse.items) != 1 || again.characters[1000000].corpse.credits != 1 || again.characters[1].experience != 100 || again.nextItem != before+2 {
    114 					t.Fatal("retry lost or repeated generated loot/cash/XP")
    115 				}
    116 			})
    117 		}
    118 	}
    119 }
    120 
    121 func TestNPCLootPickupUsesGeneratedInstanceAndDoesNotRepeatCash(t *testing.T) {
    122 	world, _ := newKillExperienceWorld(t, "unarmed")
    123 	world.combatRoll = func(uint32) uint32 { return 0 }
    124 	before := world.nextItem
    125 	attackForExperience(t, world, "unarmed")
    126 
    127 	if err := world.handleLootUse(world.clients[1], lootUseRequest(1)); err != nil {
    128 		t.Fatal(err)
    129 	}
    130 	if err := world.handleInventory(world.clients[1], lootTakeRequest()); err != nil {
    131 		t.Fatal(err)
    132 	}
    133 	if err := world.handleLootUse(world.clients[1], lootUseRequest(2)); err != nil {
    134 		t.Fatal(err)
    135 	}
    136 	cold := newTestInventoryServer(t)
    137 
    138 	expected := []ownedItem{{ID: before + 1, Type: 51005, Template: 42640, Quality: 1, Slot: 64, Count: 1}}
    139 	for _, current := range []*server{world, cold} {
    140 		if !slices.Equal(current.characters[1].inventory.Items, expected) || current.characters[1].inventory.Credits != 1 || len(current.characters[1000000].corpse.items) != 0 || current.characters[1000000].corpse.credits != 0 || current.nextItem != before+1 {
    141 			t.Fatal("generated pickup changed identity, lost ownership or repeated cash", current.characters[1].inventory)
    142 		}
    143 	}
    144 }
    145 
    146 func TestNPCLootDoesNotDependOnSoloExperienceEligibility(t *testing.T) {
    147 	for _, scenario := range []string{"grey", "zero XP"} {
    148 		t.Run(scenario, func(t *testing.T) {
    149 			world, _ := newKillExperienceWorld(t, "unarmed")
    150 			world.combatRoll = func(uint32) uint32 { return 0 }
    151 			if scenario == "grey" {
    152 				world.characters[1].level = 4
    153 				if err := world.saveUser(world.characters[1]); err != nil {
    154 					t.Fatal(err)
    155 				}
    156 			} else {
    157 				profile := *world.characters[1000000].combatProfile
    158 				profile.Experience = 0
    159 				world.characters[1000000].combatProfile = &profile
    160 			}
    161 
    162 			attackForExperience(t, world, "unarmed")
    163 			cold := newTestInventoryServer(t)
    164 
    165 			if cold.characters[1].experience != 0 || len(cold.characters[1000000].corpse.items) != 1 || cold.characters[1000000].corpse.credits != 1 {
    166 				t.Fatal("XP eligibility incorrectly suppressed corpse rewards")
    167 			}
    168 		})
    169 	}
    170 }
    171 
    172 func TestNPCLootUsesSharedTypedItemRecords(t *testing.T) {
    173 	world, _ := newKillExperienceWorld(t, "unarmed")
    174 	profile := *world.characters[1000000].combatProfile
    175 	profile.Loot = []gamedata.NPCLoot{{Template: 42640, Quality: [2]uint32{1, 1}, Chance: 100}, {Template: 123742, Quality: [2]uint32{1, 1}, Chance: 100}, {Template: 143832, Quality: [2]uint32{1, 1}, Chance: 100}}
    176 	world.characters[1000000].combatProfile = &profile
    177 	world.combatRoll = func(uint32) uint32 { return 0 }
    178 	before := world.nextItem
    179 
    180 	attackForExperience(t, world, "unarmed")
    181 	cold := newTestInventoryServer(t)
    182 
    183 	expected := []ownedItem{
    184 		{ID: before + 1, Type: 51005, Template: 42640, Quality: 1, Count: 1},
    185 		{ID: before + 2, Type: 51018, Template: 123742, Quality: 1, Slot: 1, Count: 1},
    186 		{ID: before + 3, Type: 51017, Template: 143832, Quality: 1, Slot: 2, Count: 1},
    187 	}
    188 	if !slices.Equal(cold.characters[1000000].corpse.items, expected) || cold.nextItem != before+3 || len(world.items[before+3].Slots) != 21 {
    189 		t.Fatal("loot generation did not retain catalog types, original qualities and durable instances", cold.characters[1000000].corpse.items)
    190 	}
    191 }
    192 
    193 func TestNPCLootPeriodicKillingTickCommitsOnce(t *testing.T) {
    194 	world, _ := newPeriodicNanoWorld(t)
    195 	world.combatRoll = func(uint32) uint32 { return 0 }
    196 	target := world.characters[1000000]
    197 	target.health, target.monsterData, target.level = 1, 17655, 1
    198 	profile := *gamedata.NPCCombatProfiles[17655][1]
    199 	profile.Loot = []gamedata.NPCLoot{{Template: 85557, Quality: [2]uint32{101, 101}, Chance: 100}}
    200 	target.combatProfile = &profile
    201 	before := world.nextItem
    202 	at := castPeriodicNano(t, world, 43376)
    203 
    204 	world.advanceNanos(at.Add(7500 * time.Millisecond))
    205 	world.advanceNanos(at.Add(7500 * time.Millisecond))
    206 	cold := newTestInventoryServer(t)
    207 
    208 	if cold.characters[1000000].health != 0 || len(cold.characters[1000000].corpse.items) != 1 || cold.characters[1000000].corpse.items[0].Quality != 101 || cold.characters[1000000].corpse.credits != 1 || cold.characters[1].experience != 100 || cold.nextItem != before+1 {
    209 		t.Fatal("periodic killing tick lost or repeated its durable rewards")
    210 	}
    211 }
    212 
    213 func TestNPCLootDoesNotRollOnNonlethalDamage(t *testing.T) {
    214 	world, _ := newKillExperienceWorld(t, "pistol")
    215 	world.combatRoll = func(uint32) uint32 { return 0 }
    216 	target := world.characters[1000000]
    217 	target.health = 100
    218 	before := world.nextItem
    219 
    220 	attackForExperience(t, world, "pistol")
    221 	cold := newTestInventoryServer(t)
    222 
    223 	if target.health == 0 || target.corpse != nil || cold.characters[1000000].corpse != nil || world.nextItem != before || cold.nextItem != before || len(world.items) != 2 || len(cold.items) != 2 || world.characters[1].experience != 0 {
    224 		t.Fatal("nonlethal hit allocated corpse rewards")
    225 	}
    226 }
    227 
    228 func TestNPCLootIdentityExhaustionRejectsOnlyAnActualDrop(t *testing.T) {
    229 	for _, chance := range []uint32{0, 100} {
    230 		t.Run(fmt.Sprint(chance), func(t *testing.T) {
    231 			world, _ := newKillExperienceWorld(t, "unarmed")
    232 			world.combatRoll = func(uint32) uint32 { return 0 }
    233 			profile := *world.characters[1000000].combatProfile
    234 			profile.Loot = []gamedata.NPCLoot{{Template: 42640, Quality: [2]uint32{1, 1}, Chance: chance}}
    235 			world.characters[1000000].combatProfile = &profile
    236 			world.nextItem = 4294967295
    237 			if _, err := world.db.Exec("UPDATE world SET last_item_id=4294967295 WHERE id=1"); err != nil {
    238 				t.Fatal(err)
    239 			}
    240 
    241 			attackForExperience(t, world, "unarmed")
    242 			cold := newTestInventoryServer(t)
    243 
    244 			if world.nextItem != 4294967295 || cold.nextItem != 4294967295 || len(world.items) != 0 || len(cold.items) != 0 {
    245 				t.Fatal("loot allocation wrapped or leaked a partial item")
    246 			}
    247 			if chance == 100 {
    248 				if cold.characters[1000000].health != 1 || cold.characters[1000000].corpse != nil || cold.characters[1].experience != 0 {
    249 					t.Fatal("exhausted item identities committed part of the killing outcome")
    250 				}
    251 			} else if cold.characters[1000000].health != 0 || cold.characters[1000000].corpse.credits != 1 || cold.characters[1].experience != 100 {
    252 				t.Fatal("empty loot roll required an item identity")
    253 			}
    254 		})
    255 	}
    256 }
    257 
    258 func TestNPCLootRespawnAndCheckpointDoNotRegenerateOldRewards(t *testing.T) {
    259 	world, _ := newRespawnWorld(t)
    260 	world.combatRoll = func(uint32) uint32 { return 0 }
    261 	attackForExperience(t, world, "unarmed")
    262 	before := world.nextItem
    263 	deadline := world.npcRespawns[0].at
    264 	if len(world.characters[1000000].corpse.items) != 3 {
    265 		t.Fatal("the first life did not generate its loot")
    266 	}
    267 	items := slices.Clone(world.characters[1000000].corpse.items)
    268 
    269 	world.advanceNPCRespawns(deadline)
    270 	if err := world.checkpointWorld(deadline); err != nil {
    271 		t.Fatal(err)
    272 	}
    273 	cold := newTestInventoryServer(t)
    274 
    275 	if cold.characters[1000001] == nil || cold.characters[1000001].corpse != nil || cold.characters[1000000].corpse.credits != 1 || !slices.Equal(cold.characters[1000000].corpse.items, items) || world.nextItem != before || cold.nextItem != before {
    276 		t.Fatal("respawn/checkpoint regenerated or lost the prior life's loot")
    277 	}
    278 }
    279 
    280 func TestNPCLootFullInventoryRetainsGeneratedItem(t *testing.T) {
    281 	world, _ := newKillExperienceWorld(t, "unarmed")
    282 	profile := *world.characters[1000000].combatProfile
    283 	profile.Loot = []gamedata.NPCLoot{{Template: 85557, Quality: [2]uint32{101, 101}, Chance: 100}}
    284 	world.characters[1000000].combatProfile = &profile
    285 	world.combatRoll = func(uint32) uint32 { return 0 }
    286 	for range 30 {
    287 		if granted, err := world.grantItem(world.characters[1], 42640); err != nil || !granted {
    288 			t.Fatal("fill inventory", granted, err)
    289 		}
    290 	}
    291 	attackForExperience(t, world, "unarmed")
    292 	if len(world.characters[1000000].corpse.items) != 1 {
    293 		t.Fatal("death did not generate the overflow item")
    294 	}
    295 	item := world.characters[1000000].corpse.items[0]
    296 	if err := world.handleLootUse(world.clients[1], lootUseRequest(1)); err != nil {
    297 		t.Fatal(err)
    298 	}
    299 
    300 	if err := world.handleInventory(world.clients[1], lootTakeRequest()); err != nil {
    301 		t.Fatal(err)
    302 	}
    303 	cold := newTestInventoryServer(t)
    304 
    305 	for _, current := range []*server{world, cold} {
    306 		if len(current.characters[1].inventory.Items) != 30 || current.characters[1].inventory.Credits != 1 || !slices.Equal(current.characters[1000000].corpse.items, []ownedItem{item}) || current.itemPlacements[item.ID] != (itemPlacement{Corpse: 1000000}) || current.nextItem != item.ID {
    307 			t.Fatal("full inventory lost, duplicated or transferred the generated drop")
    308 		}
    309 	}
    310 }
    311 
    312 func TestNPCLootConcurrentDeathsReserveDistinctItems(t *testing.T) {
    313 	world, _ := newKillExperienceWorld(t, "unarmed")
    314 	world.combatRoll = func(uint32) uint32 { return 0 }
    315 	second := world.newCharacter()
    316 	second.playfield, second.position = 950, [3]float32{}
    317 	if err := world.saveUser(second); err != nil {
    318 		t.Fatal(err)
    319 	}
    320 	npc := *world.characters[1000000]
    321 	npc.id = 1000001
    322 	world.characters[npc.id], world.nextNPC = &npc, 1000002
    323 	world.clients[2] = &worldClient{id: 2, conn: &combatTestConn{}, target: true, ready: true, npcs: map[uint32]bool{1000001: true}}
    324 	if err := world.flushWorld(); err != nil {
    325 		t.Fatal(err)
    326 	}
    327 	for _, pair := range [][2]uint32{{1, 1000000}, {2, 1000001}} {
    328 		if err := world.handleCombat(world.clients[pair[0]], attackPacket(pair[0], pair[1])[20:]); err != nil {
    329 			t.Fatal(err)
    330 		}
    331 	}
    332 	at := world.characters[1].nextAttack
    333 	if second.nextAttack.After(at) {
    334 		at = second.nextAttack
    335 	}
    336 	before := world.nextItem
    337 	zone, stop := startTestZone(t, world)
    338 	var visitors sync.WaitGroup
    339 
    340 	for range 8 {
    341 		visitors.Go(func() {
    342 			if err := zone.call(zoneTestCommand(func(state *server) error { state.advanceCombat(at); return nil })); err != nil {
    343 				t.Error(err)
    344 			}
    345 		})
    346 	}
    347 	visitors.Wait()
    348 	if err := stop(); err != nil {
    349 		t.Fatal(err)
    350 	}
    351 	cold := newTestInventoryServer(t)
    352 
    353 	for _, current := range []*server{world, cold} {
    354 		first, second := current.characters[1000000].corpse, current.characters[1000001].corpse
    355 		if first == nil || second == nil || len(first.items) != 1 || len(second.items) != 1 || first.items[0].ID == second.items[0].ID || first.looter != 1 || second.looter != 2 || first.credits != 1 || second.credits != 1 || current.nextItem != before+2 || len(current.items) != 2 {
    356 			t.Fatal("concurrent deaths duplicated identities or lost independent rewards")
    357 		}
    358 		if current.characters[1].experience != 100 || current.characters[2].experience != 100 {
    359 			t.Fatal("one victim's XP was repeated or assigned to the other killer")
    360 		}
    361 	}
    362 }