aorecomp

Anarchy Online classic in the browser

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


server/nano_cost_implant_test.go (17110B)


      1 package main
      2 
      3 import (
      4 	"ao/server/gamedata"
      5 	_ "embed"
      6 	"encoding/json"
      7 	"fmt"
      8 	"reflect"
      9 	"slices"
     10 	"testing"
     11 	"time"
     12 )
     13 
     14 //go:embed testdata/nano-cost-implants.json
     15 var nanoCostImplantData []byte
     16 
     17 type nanoCostImplantFixture struct {
     18 	Template, Quality, Mask, Slot, Delay, Debit uint32
     19 	Modifiers                                   [][2]int32
     20 	Actions                                     []gamedata.ItemAction
     21 	Admitted                                    bool
     22 	PayloadSHA256                               string `json:"payload_sha256"`
     23 }
     24 
     25 func nanoCostImplantFixtures(t *testing.T) []nanoCostImplantFixture {
     26 	t.Helper()
     27 	var fixtures []nanoCostImplantFixture
     28 	if err := json.Unmarshal(nanoCostImplantData, &fixtures); err != nil {
     29 		t.Fatal(err)
     30 	}
     31 	return fixtures
     32 }
     33 
     34 func TestNanoCostImplantCatalogMatchesCompleteOriginalContracts(t *testing.T) {
     35 	fixtures := nanoCostImplantFixtures(t)
     36 	var admitted, expected []uint32
     37 
     38 	for template, definition := range gamedata.ItemTemplates {
     39 		if definition.HeaderWords[0] != 51022 || itemStat(definition, 76) != 3 {
     40 			continue
     41 		}
     42 		item := ownedItem{ID: 1, Type: definition.HeaderWords[0], Template: template, Quality: *definition.Quality,
     43 			Slot: 32 + itemStat(definition, 88), Count: 1}
     44 		if item.isImplant() && item.equipmentBonus(318, 0) != 0 {
     45 			admitted = append(admitted, template)
     46 		}
     47 	}
     48 	for _, fixture := range fixtures {
     49 		if fixture.Admitted {
     50 			expected = append(expected, fixture.Template)
     51 		}
     52 	}
     53 	slices.Sort(admitted)
     54 	slices.Sort(expected)
     55 
     56 	if len(fixtures) != 816 || len(expected) != 816 || !slices.Equal(admitted, expected) {
     57 		t.Fatal("cost implant admission differs from the independent original-record census", len(fixtures), len(admitted), len(expected))
     58 	}
     59 	for _, fixture := range fixtures {
     60 		definition := gamedata.ItemTemplates[fixture.Template]
     61 		if *definition.Quality != fixture.Quality || definition.PayloadSHA256 != fixture.PayloadSHA256 ||
     62 			itemStat(definition, 298) != fixture.Mask || 32+itemStat(definition, 88) != fixture.Slot {
     63 			t.Fatal("original implant identity, quality or anatomical mask changed", fixture.Template)
     64 		}
     65 		var actions []gamedata.ItemAction
     66 		var modifiers [][2]int32
     67 		for _, section := range definition.Sections {
     68 			if section.Actions != nil {
     69 				actions = append(actions, *section.Actions...)
     70 			}
     71 			if section.Functions != nil {
     72 				for _, function := range *section.Functions {
     73 					if section.Type != 2 || section.Subtype != 14 || function.ID != 53045 || function.Target != 2 ||
     74 						function.HeaderWords != [2]uint32{0, 4} || function.ArgumentHeader != 9 || len(function.Requirements) != 0 ||
     75 						function.TickCount != 1 || function.TickInterval != 0 || len(function.Arguments) != 2 {
     76 						t.Fatal("original complete OnWear contract changed", fixture.Template)
     77 					}
     78 					modifiers = append(modifiers, [2]int32{*function.Arguments[0].Integer, *function.Arguments[1].Integer})
     79 				}
     80 			}
     81 		}
     82 		if !slices.Equal(modifiers, fixture.Modifiers) || !reflect.DeepEqual(actions, fixture.Actions) {
     83 			t.Fatal("original companion modifiers or strict wear criteria changed", fixture.Template)
     84 		}
     85 	}
     86 }
     87 
     88 func newNanoCostImplantWorld(t *testing.T, template uint32) (*server, *combatTestConn) {
     89 	t.Helper()
     90 	world, conn := newCatalogImplantWorld(t, template)
     91 	player := world.characters[1]
     92 	player.level, player.profession = 200, 12
     93 	for _, field := range player.stats.trainingStats() {
     94 		*field.value = 5000
     95 	}
     96 	player.stats.Abilities = characterAbilitiesStats{1500, 1500, 1500, 1500, 1500, 1500}
     97 	player.stats.Body.NanoPool, player.stats.Speed.NanoInitiative = 30000, 5
     98 	player.nano = 50000
     99 	player.inventory.LearnedNanos = []uint32{27169}
    100 	if err := world.saveUser(player); err != nil {
    101 		t.Fatal(err)
    102 	}
    103 	if err := world.saveInventory(player, player.inventory); err != nil {
    104 		t.Fatal(err)
    105 	}
    106 	conn.packets = nil
    107 	return world, conn
    108 }
    109 
    110 func TestNanoCostImplantsInstallCastRemoveAndRestoreCompleteEffects(t *testing.T) {
    111 	for _, fixture := range nanoCostImplantFixtures(t) {
    112 		if !fixture.Admitted {
    113 			continue
    114 		}
    115 		t.Run(fmt.Sprint(fixture.Template), func(t *testing.T) {
    116 			world, conn := newNanoCostImplantWorld(t, fixture.Template)
    117 			player, client := world.characters[1], world.clients[1]
    118 			before, trained := slices.Clone(player.inventory.Items), player.baseStats()
    119 			clinicDeadline := player.skillLocks[124]
    120 
    121 			started := time.Now()
    122 			if err := world.handleInventory(client, inventoryMovePacket(1, 66, fixture.Slot)[20:]); err != nil {
    123 				t.Fatal(err)
    124 			}
    125 			delay := time.Duration(fixture.Delay) * 10 * time.Millisecond
    126 			if client.equipment == nil || client.equipment.readyAt.Before(started.Add(delay)) || client.equipment.readyAt.After(time.Now().Add(delay)) {
    127 				t.Fatal("original cost implant did not start its authored delay", fixture.Template)
    128 			}
    129 			deadline := client.equipment.readyAt
    130 			world.advanceEquipment(deadline.Add(-time.Nanosecond))
    131 			if !reflect.DeepEqual(player.inventory.Items, before) || len(conn.packets) != 0 {
    132 				t.Fatal("cost implant changed placement/effects before its deadline")
    133 			}
    134 			world.advanceEquipment(deadline)
    135 			cold := newTestInventoryServer(t).characters[1]
    136 			castTestBuff(t, world, 1, 1, 27169)
    137 
    138 			if player.inventory.Items[2].Slot != fixture.Slot || cold.inventory.Items[2].Slot != fixture.Slot ||
    139 				player.inventory.Items[2].ID != 3 || cold.inventory.Items[2].ID != 3 || cold.inventory.Items[2].Quality != fixture.Quality ||
    140 				player.nano != 50000-fixture.Debit || player.nanoReserved != 0 || player.baseStats() != trained || cold.baseStats() != trained ||
    141 				!player.skillLocks[124].Equal(clinicDeadline) || !cold.skillLocks[124].Equal(clinicDeadline) {
    142 				t.Fatal("implant lost placement, quality, base state or its cast cost", fixture.Template, player.nano, fixture.Debit)
    143 			}
    144 			for _, modifier := range fixture.Modifiers {
    145 				if player.equipmentBonus(uint32(modifier[0])) != modifier[1] || cold.equipmentBonus(uint32(modifier[0])) != modifier[1] {
    146 					t.Fatal("cost implant lost or duplicated an authored companion", fixture.Template, modifier)
    147 				}
    148 			}
    149 			if err := world.handleInventory(client, itemMovePacket(1, fixture.Slot, 111)[20:]); err != nil || client.equipment == nil {
    150 				t.Fatal("valid cost implant removal was rejected", err)
    151 			}
    152 			world.advanceEquipment(client.equipment.readyAt)
    153 			player.nanoRechargeUntil = time.Time{}
    154 			castTestBuff(t, world, 1, 1, 27169)
    155 			removed := newTestInventoryServer(t).characters[1]
    156 			if !reflect.DeepEqual(player.inventory.Items, before) || !reflect.DeepEqual(removed.inventory.Items, before) ||
    157 				player.nano != 50000-fixture.Debit-44 || removed.nano != player.nano || player.equipmentBonus(318) != 0 || removed.equipmentBonus(318) != 0 {
    158 				t.Fatal("implant removal lost an instance or retained its cost contribution", fixture.Template, player.nano)
    159 			}
    160 			for _, modifier := range fixture.Modifiers {
    161 				if player.equipmentBonus(uint32(modifier[0])) != 0 || removed.equipmentBonus(uint32(modifier[0])) != 0 {
    162 					t.Fatal("removed implant retained a companion modifier", fixture.Template, modifier)
    163 				}
    164 			}
    165 		})
    166 	}
    167 }
    168 
    169 func TestNanoCostImplantsEnforceEveryAuthoredRequirement(t *testing.T) {
    170 	for _, fixture := range nanoCostImplantFixtures(t) {
    171 		if !fixture.Admitted || len(fixture.Modifiers) != 1 {
    172 			continue
    173 		}
    174 		for _, requirement := range fixture.Actions[0].Requirements {
    175 			if requirement.Operator != 2 {
    176 				continue
    177 			}
    178 			for _, passed := range []bool{false, true} {
    179 				t.Run(fmt.Sprintf("%d/%d/%t", fixture.Template, requirement.Stat, passed), func(t *testing.T) {
    180 					world, _ := newNanoCostImplantWorld(t, fixture.Template)
    181 					player, client := world.characters[1], world.clients[1]
    182 					player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1}
    183 					for _, condition := range fixture.Actions[0].Requirements {
    184 						if condition.Stat >= 16 && condition.Stat <= 21 {
    185 							for _, field := range player.stats.trainingStats() {
    186 								if field.stat == uint32(condition.Stat) {
    187 									*field.value = uint16(condition.Value + 1)
    188 								}
    189 							}
    190 						}
    191 					}
    192 					if requirement.Stat == 37 {
    193 						player.level = map[int32]uint16{2: 50, 3: 100, 4: 150, 5: 190}[requirement.Value]
    194 						if !passed {
    195 							player.level--
    196 						}
    197 					} else {
    198 						value := requirement.Value
    199 						if requirement.Stat == 124 {
    200 							// Set up the exact threshold independently of ability trickle.
    201 							player.stats.NanoAiding.Treatment = 0
    202 							trickle, _ := player.effectiveStat(124)
    203 							value -= trickle
    204 						}
    205 						if passed {
    206 							value++
    207 						}
    208 						for _, field := range player.stats.trainingStats() {
    209 							if field.stat == uint32(requirement.Stat) {
    210 								*field.value = uint16(value)
    211 							}
    212 						}
    213 					}
    214 					before := slices.Clone(player.inventory.Items)
    215 
    216 					err := world.handleInventory(client, inventoryMovePacket(1, 66, fixture.Slot)[20:])
    217 					if client.equipment != nil {
    218 						world.advanceEquipment(client.equipment.readyAt)
    219 					}
    220 
    221 					if err != nil || (player.inventory.Items[2].Slot == fixture.Slot) != passed ||
    222 						!passed && (!reflect.DeepEqual(player.inventory.Items, before) || player.equipmentBonus(318) != 0) ||
    223 						passed && player.equipmentBonus(318) != fixture.Modifiers[0][1] {
    224 						t.Fatal("cost implant ignored a strict skill/ability/title boundary", requirement, passed, err)
    225 					}
    226 				})
    227 			}
    228 		}
    229 	}
    230 }
    231 
    232 func TestNanoCostImplantPendingMoveRevalidatesSurgeryAndRequirements(t *testing.T) {
    233 	for _, scenario := range []string{"no access", "access expires", "Treatment drops", "ability drops"} {
    234 		t.Run(scenario, func(t *testing.T) {
    235 			world, _ := newNanoCostImplantWorld(t, 179305)
    236 			player, client := world.characters[1], world.clients[1]
    237 			if scenario == "no access" {
    238 				player.implantChangesUntil = time.Time{}
    239 			}
    240 			before := slices.Clone(player.inventory.Items)
    241 
    242 			if err := world.handleInventory(client, inventoryMovePacket(1, 66, 40)[20:]); err != nil {
    243 				t.Fatal(err)
    244 			}
    245 			if scenario != "no access" {
    246 				if client.equipment == nil {
    247 					t.Fatal("valid cost implant did not begin installation")
    248 				}
    249 				switch scenario {
    250 				case "access expires":
    251 					player.implantChangesUntil = client.equipment.readyAt
    252 				case "Treatment drops":
    253 					player.stats.NanoAiding.Treatment = 0
    254 				case "ability drops":
    255 					player.stats.Abilities.Agility = 1
    256 				}
    257 				world.advanceEquipment(client.equipment.readyAt)
    258 			}
    259 			cold := newTestInventoryServer(t).characters[1]
    260 
    261 			if client.equipment != nil || !reflect.DeepEqual(player.inventory.Items, before) || !reflect.DeepEqual(cold.inventory.Items, before) ||
    262 				player.equipmentBonus(318) != 0 || cold.equipmentBonus(318) != 0 || player.nano != 50000 || cold.nano != 50000 {
    263 				t.Fatal("failed delayed surgery moved the item or granted a cost modifier")
    264 			}
    265 		})
    266 	}
    267 }
    268 
    269 func TestNanoCostImplantSaveFailuresPreserveEveryEffectAndInstance(t *testing.T) {
    270 	for _, removal := range []bool{false, true} {
    271 		for _, failure := range []string{"error", "ignore", "commit"} {
    272 			t.Run(fmt.Sprintf("remove=%t/%s", removal, failure), func(t *testing.T) {
    273 				world, _ := newNanoCostImplantWorld(t, 179201)
    274 				player, client := world.characters[1], world.clients[1]
    275 				request := inventoryMovePacket(1, 66, 38)
    276 				cost, heal := int32(0), int32(0)
    277 				if removal {
    278 					if err := world.handleInventory(client, request[20:]); err != nil || client.equipment == nil {
    279 						t.Fatal(err)
    280 					}
    281 					world.advanceEquipment(client.equipment.readyAt)
    282 					request, cost, heal = itemMovePacket(1, 38, 111), 2, 5
    283 				}
    284 				before := slices.Clone(player.inventory.Items)
    285 				stored, err := readTestItemStore(world)
    286 				if err != nil {
    287 					t.Fatal(err)
    288 				}
    289 				statement := "CREATE TRIGGER fail_cost_implant BEFORE INSERT ON item_locations BEGIN SELECT RAISE(FAIL,'test implant'); END"
    290 				if failure == "ignore" {
    291 					statement = "CREATE TRIGGER fail_cost_implant BEFORE INSERT ON item_locations BEGIN SELECT RAISE(IGNORE); END"
    292 				} else if failure == "commit" {
    293 					statement = "CREATE TABLE pending_cost_implant (player_id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_cost_implant AFTER INSERT ON item_locations BEGIN INSERT INTO pending_cost_implant VALUES(999999); END"
    294 				}
    295 				if _, err := world.db.Exec(statement); err != nil {
    296 					t.Fatal(err)
    297 				}
    298 
    299 				if err := world.handleInventory(client, request[20:]); err != nil || client.equipment == nil {
    300 					t.Fatal(err)
    301 				}
    302 				world.advanceEquipment(client.equipment.readyAt)
    303 				after, readErr := readTestItemStore(world)
    304 
    305 				if readErr != nil || !slices.Equal(stored, after) || !reflect.DeepEqual(player.inventory.Items, before) ||
    306 					player.equipmentBonus(318) != cost || player.equipmentBonus(343) != heal || player.nano != 50000 {
    307 					t.Fatal("failed cost implant save published partial effects or lost an instance", failure, readErr)
    308 				}
    309 				if _, err := world.db.Exec("DROP TRIGGER fail_cost_implant"); err != nil {
    310 					t.Fatal(err)
    311 				}
    312 				if err := world.handleInventory(client, request[20:]); err != nil || client.equipment == nil {
    313 					t.Fatal(err)
    314 				}
    315 				world.advanceEquipment(client.equipment.readyAt)
    316 				cold := newTestInventoryServer(t).characters[1]
    317 				if player.equipmentBonus(318) != 2-cost || cold.equipmentBonus(318) != 2-cost ||
    318 					player.equipmentBonus(343) != 5-heal || cold.equipmentBonus(343) != 5-heal || len(cold.inventory.Items) != 3 || cold.inventory.Items[2].ID != 3 {
    319 					t.Fatal("retry failed to publish exactly the complete cost/delta contract")
    320 				}
    321 			})
    322 		}
    323 	}
    324 }
    325 
    326 func TestNanoCostImplantsStackWithDevicesAndNanosBelowInstallRequirements(t *testing.T) {
    327 	for _, fixture := range []struct {
    328 		name                string
    329 		templates           [3]uint32
    330 		total               int32
    331 		debit, afterRemoval uint32
    332 	}{
    333 		{"positive", [3]uint32{173249, 179184, 179302}, 10, 39, 38},
    334 		{"negative", [3]uint32{173252, 179187, 179305}, -10, 30, 31},
    335 		{"mixed", [3]uint32{173249, 179187, 179302}, 6, 37, 38},
    336 	} {
    337 		t.Run(fixture.name, func(t *testing.T) {
    338 			world, _ := newNanoCostImplantWorld(t, fixture.templates[0])
    339 			player, client := world.characters[1], world.clients[1]
    340 			for index, template := range fixture.templates {
    341 				if index != 0 {
    342 					if granted, err := world.grantItem(player, template); err != nil || !granted {
    343 						t.Fatal(granted, err)
    344 					}
    345 				}
    346 				if err := world.handleInventory(client, inventoryMovePacket(1, 66, []uint32{35, 38, 40}[index])[20:]); err != nil || client.equipment == nil {
    347 					t.Fatal("stacked cost implant could not be installed", err)
    348 				}
    349 				world.advanceEquipment(client.equipment.readyAt)
    350 			}
    351 			for _, item := range []struct{ template, slot uint32 }{{204601, 7}, {95513, 13}} {
    352 				if granted, err := world.grantItem(player, item.template); err != nil || !granted {
    353 					t.Fatal(granted, err)
    354 				}
    355 				if err := world.handleInventory(client, inventoryMovePacket(1, 66, item.slot)[20:]); err != nil || client.equipment == nil {
    356 					t.Fatal("cost device or its required belt was rejected", err)
    357 				}
    358 				world.advanceEquipment(client.equipment.readyAt)
    359 			}
    360 			if granted, err := world.grantItem(player, 95418); err != nil || !granted {
    361 				t.Fatal(granted, err)
    362 			}
    363 			if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 66, 2)[20:]); err != nil {
    364 				t.Fatal(err)
    365 			}
    366 			if !slices.Equal(player.inventory.LearnedNanos, []uint32{27169, 95410}) {
    367 				t.Fatal("cost nano uploader did not consume its own item-use sequence")
    368 			}
    369 			castTestBuff(t, world, 1, 1, 95410)
    370 			player.nanoRechargeUntil = time.Time{}
    371 			player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1}
    372 			player.stats.NanoAiding.Treatment = 0
    373 			if err := world.saveUser(player); err != nil {
    374 				t.Fatal(err)
    375 			}
    376 			before := player.nano
    377 
    378 			castTestBuff(t, world, 1, 1, 27169)
    379 			cold := newTestInventoryServer(t).characters[1]
    380 
    381 			if player.nano != before-fixture.debit || cold.nano != player.nano || player.equipmentBonus(318) != fixture.total-15 ||
    382 				cold.equipmentBonus(318) != fixture.total-15 || player.nanoBonus(318) != -7 || cold.nanoBonus(318) != -7 ||
    383 				player.stats.NanoAiding.Treatment != 0 || cold.stats.NanoAiding.Treatment != 0 {
    384 				t.Fatal("cost sources multiplied, failed to stack or became overequipped", player.nano, before, fixture.debit)
    385 			}
    386 			if err := world.handleInventory(client, itemMovePacket(1, 38, 111)[20:]); err != nil || client.equipment == nil {
    387 				t.Fatal("removal incorrectly rechecked the implant's installation requirements", err)
    388 			}
    389 			world.advanceEquipment(client.equipment.readyAt)
    390 			player.nanoRechargeUntil = time.Time{}
    391 			castTestBuff(t, world, 1, 1, 27169)
    392 			removed := newTestInventoryServer(t).characters[1]
    393 			if player.nano != before-fixture.debit-fixture.afterRemoval || removed.nano != player.nano ||
    394 				len(removed.inventory.Items) != 7 || removed.inventory.Items[3].ID != 4 || removed.inventory.Items[3].Slot != 66 ||
    395 				removed.inventory.Items[2].Slot != 35 || removed.inventory.Items[4].Slot != 40 {
    396 				t.Fatal("removing one cost implant changed another contribution or lost an item", player.nano, removed.inventory.Items)
    397 			}
    398 		})
    399 	}
    400 }