server/nano_cost_test.go (20015B)
1 package main 2 3 import ( 4 "ao/server/gamedata" 5 _ "embed" 6 "encoding/binary" 7 "encoding/json" 8 "fmt" 9 "reflect" 10 "slices" 11 "testing" 12 "time" 13 ) 14 15 //go:embed testdata/nano-cost-nanos.json 16 var nanoCostData []byte 17 18 type nanoCostFixture struct { 19 combatNanoFixture 20 Getter [][2]uint32 21 } 22 23 func nanoCostFixtures(t *testing.T) []nanoCostFixture { 24 t.Helper() 25 var fixtures []nanoCostFixture 26 if err := json.Unmarshal(nanoCostData, &fixtures); err != nil { 27 t.Fatal(err) 28 } 29 return fixtures 30 } 31 32 func newNanoCostWorld(t *testing.T, fixture nanoCostFixture) (*server, *combatTestConn) { 33 t.Helper() 34 world, conn := newCombatNanoWorld(t, fixture.combatNanoFixture) 35 if fixture.NCU > 49 { 36 // The largest program and a follow-up Boost exceed the fixture's 52 NCU. 37 player := world.characters[1] 38 if granted, err := world.grantItem(player, 204601); err != nil || !granted { 39 t.Fatal(granted, err) 40 } 41 inventory := player.inventory 42 inventory.Items = slices.Clone(inventory.Items) 43 inventory.Items[len(inventory.Items)-1].Slot = 7 44 if err := world.saveInventory(player, inventory); err != nil { 45 t.Fatal(err) 46 } 47 conn.packets = nil 48 } 49 return world, conn 50 } 51 52 func TestNanoCostCatalogMatchesCompleteOriginalContracts(t *testing.T) { 53 fixtures := nanoCostFixtures(t) 54 var programs, crystals []uint32 55 var expectedPrograms, expectedCrystals []uint32 56 57 for program := range gamedata.NanoTemplates { 58 if statBuffNano(program) && nanoProgramBonus(program, 318) != 0 { 59 programs = append(programs, program) 60 } 61 } 62 for crystal := range gamedata.ItemTemplates { 63 if slices.Contains(programs, nanoCrystalProgram(crystal)) { 64 crystals = append(crystals, crystal) 65 } 66 } 67 for _, fixture := range fixtures { 68 expectedPrograms = append(expectedPrograms, fixture.Program) 69 expectedCrystals = append(expectedCrystals, fixture.Crystal) 70 } 71 for _, values := range [][]uint32{programs, crystals, expectedPrograms, expectedCrystals} { 72 slices.Sort(values) 73 } 74 75 if len(programs) != 14 || len(crystals) != 14 || !slices.Equal(programs, expectedPrograms) || !slices.Equal(crystals, expectedCrystals) { 76 t.Fatal("cost admission differs from the independent whole-contract census", programs, crystals) 77 } 78 for _, fixture := range fixtures { 79 for _, field := range [][2]uint32{{0, fixture.Flags}, {30, fixture.Can}, {8, fixture.Duration}, {54, fixture.NCU}, {75, fixture.Strain}, 80 {210, fixture.RechargeDelay}, {287, fixture.Range}, {294, fixture.AttackDelay}, {407, fixture.NanoCost}} { 81 if nanoStat(fixture.Program, field[0]) != field[1] { 82 t.Fatal("authored casting metadata changed", fixture.Program, field) 83 } 84 } 85 var actions []gamedata.ItemAction 86 var weights []gamedata.ItemEntry 87 var getter [][2]uint32 88 var modifiers [][2]int32 89 for _, section := range gamedata.NanoTemplates[fixture.Program].Sections { 90 if section.Actions != nil { 91 actions = append(actions, *section.Actions...) 92 } 93 if section.Entries != nil { 94 weights = append(weights, *section.Entries...) 95 } 96 if section.Stats != nil { 97 getter = append(getter, *section.Stats...) 98 } 99 if section.Functions != nil { 100 for _, function := range *section.Functions { 101 if function.ID != 53012 || function.Target != fixture.Target || function.HeaderWords != [2]uint32{0, 4} || 102 function.ArgumentHeader != 9 || function.TickCount != 1 || function.TickInterval != 0 || len(function.Requirements) != 0 || 103 len(function.Arguments) != 3 || function.Arguments[2].BytesHex == nil || *function.Arguments[2].BytesHex != "00000000" { 104 t.Fatal("complete original Skill effect changed", fixture.Program) 105 } 106 modifiers = append(modifiers, [2]int32{*function.Arguments[0].Integer, *function.Arguments[1].Integer}) 107 } 108 } 109 } 110 if !slices.Equal(modifiers, fixture.Modifiers) || !reflect.DeepEqual(actions, fixture.Actions) || 111 !reflect.DeepEqual(weights, fixture.Weights) || !slices.Equal(getter, fixture.Getter) { 112 t.Fatal("original effect or casting dictionaries changed", fixture.Program) 113 } 114 var crystalActions []gamedata.ItemAction 115 for _, section := range gamedata.ItemTemplates[fixture.Crystal].Sections { 116 if section.Actions != nil { 117 crystalActions = append(crystalActions, *section.Actions...) 118 } 119 } 120 if *gamedata.ItemTemplates[fixture.Crystal].Quality != fixture.Quality || !reflect.DeepEqual(crystalActions, fixture.CrystalActions) { 121 t.Fatal("original uploader quality or criteria changed", fixture.Crystal) 122 } 123 } 124 } 125 126 func TestNanoCostProgramsUploadCastRestoreAndRemoveTheirContribution(t *testing.T) { 127 for _, fixture := range nanoCostFixtures(t) { 128 t.Run(fmt.Sprint(fixture.Program), func(t *testing.T) { 129 world, _ := newNanoCostWorld(t, fixture) 130 player, client := world.characters[1], world.clients[1] 131 trained := player.baseStats() 132 133 if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]); err != nil { 134 t.Fatal(err) 135 } 136 completed := castTestBuff(t, world, 1, 1, fixture.Program) 137 cold := newTestInventoryServer(t).characters[1] 138 var costBonus int32 139 for _, modifier := range fixture.Modifiers { 140 if modifier[0] == 318 { 141 costBonus = modifier[1] 142 } 143 } 144 145 if player.nano != 50000-fixture.Debit || cold.nano != player.nano || player.nanoReserved != 0 || 146 player.nanoBonus(318) != costBonus || cold.nanoBonus(318) != costBonus || 147 player.usedNCU() != fixture.NCU || cold.usedNCU() != fixture.NCU || player.baseStats() != trained || cold.baseStats() != trained || 148 !slices.Equal(cold.inventory.LearnedNanos, []uint32{fixture.Program}) || slices.ContainsFunc(cold.inventory.Items, func(item ownedItem) bool { return item.Template == fixture.Crystal }) || 149 player.activeNanos[0].expiresAt.Sub(completed) != time.Duration(fixture.Duration)*10*time.Millisecond { 150 t.Fatal("complete cost program lost its upload, debit, duration or restored contribution", player.nano, cold.nano) 151 } 152 if err := world.handleNanoRemoval(client, characterActionPacket(1, [5]uint32{65, 0, 0, 53019, fixture.Program})[20:]); err != nil { 153 t.Fatal(err) 154 } 155 cold = newTestInventoryServer(t).characters[1] 156 if player.nanoBonus(318) != 0 || cold.nanoBonus(318) != 0 || player.usedNCU() != 0 || cold.usedNCU() != 0 || 157 len(player.activeNanos) != 0 || len(cold.activeNanos) != 0 { 158 t.Fatal("cost program cancellation retained a modifier or NCU") 159 } 160 }) 161 } 162 } 163 164 func TestNanoCostAffordabilityUsesTheCompleteActiveProgram(t *testing.T) { 165 for _, fixture := range nanoCostFixtures(t) { 166 for _, enough := range []bool{false, true} { 167 t.Run(fmt.Sprintf("%d/%t", fixture.Program, enough), func(t *testing.T) { 168 world, conn := newNanoCostWorld(t, fixture) 169 player, client := world.characters[1], world.clients[1] 170 player.inventory.LearnedNanos = []uint32{fixture.Program, 27169} 171 castTestBuff(t, world, 1, 1, fixture.Program) 172 player.nanoRechargeUntil = time.Time{} 173 debit := map[uint32]uint32{29307: 36, 95407: 42, 95408: 39, 95409: 34, 95410: 41, 95411: 38, 95412: 36, 95413: 35, 95414: 39, 95415: 40, 95416: 40, 95417: 32, 95442: 45, 95443: 46}[fixture.Program] 174 player.nano = debit 175 if !enough { 176 player.nano-- 177 } 178 if err := world.saveNanoBalance(player); err != nil { 179 t.Fatal(err) 180 } 181 conn.packets = nil 182 183 err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1, 53019, 27169})[20:]) 184 var nano, reserved uint32 185 if queryErr := world.db.QueryRow("SELECT nano,nano_reserved FROM characters WHERE id=1").Scan(&nano, &reserved); queryErr != nil { 186 t.Fatal(queryErr) 187 } 188 189 if err != nil { 190 t.Fatal(err) 191 } 192 if enough { 193 if client.nanoCast == nil || player.nano != 0 || nano != 0 || player.nanoReserved != debit || reserved != debit || len(conn.packets) != 2 { 194 t.Fatal("exactly affordable discounted cast did not reserve once", player.nano, player.nanoReserved) 195 } 196 } else if client.nanoCast != nil || player.nano != debit-1 || nano != debit-1 || player.nanoReserved != 0 || reserved != 0 || 197 len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 108 { 198 t.Fatal("unaffordable discounted cast changed resources or started", player.nano, player.nanoReserved, nano, reserved) 199 } 200 }) 201 } 202 } 203 } 204 205 func TestNanoCostCombinesWornPenaltiesReductionsAndActivePrograms(t *testing.T) { 206 for _, fixture := range []struct { 207 name string 208 templates []uint32 209 buff bool 210 debit uint32 211 }{ 212 {"default", nil, false, 44}, {"tank", []uint32{85480}, false, 51}, 213 {"CPU", []uint32{95513}, false, 38}, {"opposing equipment", []uint32{85480, 95513}, false, 44}, 214 {"tank and nano", []uint32{85480}, true, 48}, {"CPU and nano", []uint32{95513}, true, 35}, 215 } { 216 t.Run(fixture.name, func(t *testing.T) { 217 world, _ := newCombatNanoWorld(t, combatNanoFixture{Profession: 12}) 218 player, client := world.characters[1], world.clients[1] 219 player.stats.Abilities = characterAbilitiesStats{80, 80, 80, 80, 80, 80} 220 player.inventory.LearnedNanos = []uint32{95410, 27169} 221 if err := world.saveUser(player); err != nil { 222 t.Fatal(err) 223 } 224 // The original belt enables the CPU's authored fifth deck position. 225 for _, template := range append([]uint32{204601}, fixture.templates...) { 226 if granted, err := world.grantItem(player, template); err != nil || !granted { 227 t.Fatal(granted, err) 228 } 229 slot := map[uint32]uint32{204601: 7, 85480: 19, 95513: 13}[template] 230 if err := world.handleInventory(client, inventoryMovePacket(1, 64, slot)[20:]); err != nil { 231 t.Fatal(err) 232 } 233 if client.equipment == nil { 234 t.Fatal("original cost equipment was rejected", template) 235 } 236 world.advanceEquipment(client.equipment.readyAt) 237 } 238 if fixture.buff { 239 castTestBuff(t, world, 1, 1, 95410) 240 player.nanoRechargeUntil = time.Time{} 241 } 242 before := player.nano 243 244 castTestBuff(t, world, 1, 1, 27169) 245 cold := newTestInventoryServer(t).characters[1] 246 247 if player.nano != before-fixture.debit || cold.nano != player.nano || player.nanoReserved != 0 || cold.nanoReserved != 0 || 248 player.effectiveAbility(16) != 92 || cold.effectiveAbility(16) != 92 { 249 t.Fatal("cast omitted a signed worn or active cost contribution", before, player.nano, cold.nano) 250 } 251 }) 252 } 253 } 254 255 func TestNanoCostReservationSurvivesModifierChanges(t *testing.T) { 256 for _, operation := range []string{"remove and cancel", "expire and cancel", "remove and complete", "restart"} { 257 t.Run(operation, func(t *testing.T) { 258 world, _ := newCombatNanoWorld(t, combatNanoFixture{Profession: 12}) 259 player, client := world.characters[1], world.clients[1] 260 player.inventory.LearnedNanos = []uint32{95410, 27169} 261 castTestBuff(t, world, 1, 1, 95410) 262 player.nanoRechargeUntil = time.Time{} 263 before := player.nano 264 if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1, 53019, 27169})[20:]); err != nil { 265 t.Fatal(err) 266 } 267 if client.nanoCast == nil || player.nanoReserved != 41 || player.nano != before-41 { 268 t.Fatal("discounted cast did not reserve its admission cost") 269 } 270 deadline := client.nanoCast.readyAt 271 272 if operation == "expire and cancel" { 273 player.activeNanos[0].expiresAt = deadline.Add(-time.Nanosecond) 274 world.advanceNanos(deadline.Add(-time.Nanosecond)) 275 } else if operation != "restart" { 276 if err := world.handleNanoRemoval(client, characterActionPacket(1, [5]uint32{65, 0, 0, 53019, 95410})[20:]); err != nil { 277 t.Fatal(err) 278 } 279 } 280 if operation == "remove and complete" { 281 world.advanceNanos(deadline.Add(time.Nanosecond)) 282 } else if operation != "restart" { 283 if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{108})[20:]); err != nil { 284 t.Fatal(err) 285 } 286 world.advanceNanos(deadline.Add(time.Hour)) 287 } 288 cold := newTestInventoryServer(t).characters[1] 289 again := newTestInventoryServer(t).characters[1] 290 291 want := before 292 if operation == "remove and complete" { 293 want -= 41 294 } 295 if cold.nano != want || again.nano != want || cold.nanoReserved != 0 || again.nanoReserved != 0 || 296 operation != "restart" && (player.nano != want || player.nanoReserved != 0 || client.nanoCast != nil) { 297 t.Fatal("modifier change recomputed, lost or duplicated an admitted charge/refund", before, player.nano, cold.nano) 298 } 299 if operation != "restart" && (player.nanoBonus(318) != 0 || cold.nanoBonus(318) != 0) { 300 t.Fatal("removed cost modifier remained active") 301 } 302 }) 303 } 304 } 305 306 func TestNanoCostProgramsEnforceEachUploadAndCastRequirement(t *testing.T) { 307 for _, fixture := range nanoCostFixtures(t) { 308 for _, requirement := range fixture.Actions[0].Requirements { 309 if requirement.Operator != 2 && requirement.Stat != 368 { 310 continue 311 } 312 for _, passed := range []bool{false, true} { 313 t.Run(fmt.Sprintf("%d/%d/%t", fixture.Program, requirement.Stat, passed), func(t *testing.T) { 314 world, _ := newNanoCostWorld(t, fixture) 315 player, client := world.characters[1], world.clients[1] 316 player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1} 317 if requirement.Stat == 368 { 318 if !passed { 319 player.profession = 1 320 } 321 } else { 322 for _, field := range player.stats.trainingStats() { 323 if field.stat == uint32(requirement.Stat) { 324 *field.value = uint16(requirement.Value) 325 if passed { 326 *field.value++ 327 } 328 } 329 } 330 } 331 332 if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]); err != nil { 333 t.Fatal(err) 334 } 335 learned := len(player.inventory.LearnedNanos) == 1 336 player.inventory.LearnedNanos = []uint32{fixture.Program} 337 err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1, 53019, fixture.Program})[20:]) 338 339 if err != nil || learned != passed || (client.nanoCast != nil) != passed || 340 !passed && (player.nano != 50000 || player.nanoReserved != 0) || len(player.activeNanos) != 0 { 341 t.Fatal("cost uploader or cast bypassed an authored strict skill/profession requirement", err) 342 } 343 }) 344 } 345 } 346 } 347 } 348 349 func TestNanoCostZeroAndNegativeDebits(t *testing.T) { 350 for _, fixture := range []struct { 351 modifier int32 352 raw uint32 353 accepted bool 354 }{ 355 {-7, 1, true}, {-100, 45, true}, {-120, 45, false}, 356 } { 357 t.Run(fmt.Sprintf("%d/%d", fixture.modifier, fixture.raw), func(t *testing.T) { 358 // Exercise arithmetic boundaries with otherwise complete template contracts. 359 original, originalBoost := gamedata.NanoTemplates[95410], gamedata.NanoTemplates[27169] 360 definition, boost := *original, *originalBoost 361 definition.Sections = slices.Clone(original.Sections) 362 functions := slices.Clone(*definition.Sections[2].Functions) 363 functions[0].Arguments = slices.Clone(functions[0].Arguments) 364 functions[0].Arguments[1].Integer = new(fixture.modifier) 365 definition.Sections[2].Functions = &functions 366 boost.Stats = slices.Clone(originalBoost.Stats) 367 for index, stat := range boost.Stats { 368 if stat[0] == 407 { 369 boost.Stats[index][1] = fixture.raw 370 } 371 } 372 gamedata.NanoTemplates[95410], gamedata.NanoTemplates[27169] = &definition, &boost 373 t.Cleanup(func() { gamedata.NanoTemplates[95410], gamedata.NanoTemplates[27169] = original, originalBoost }) 374 world, _ := newCombatNanoWorld(t, combatNanoFixture{Profession: 12}) 375 player, client := world.characters[1], world.clients[1] 376 player.inventory.LearnedNanos = []uint32{95410, 27169} 377 castTestBuff(t, world, 1, 1, 95410) 378 player.nano, player.nanoRechargeUntil = 0, time.Time{} 379 if err := world.saveNanoBalance(player); err != nil { 380 t.Fatal(err) 381 } 382 strength := player.effectiveAbility(16) 383 384 err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1, 53019, 27169})[20:]) 385 admitted := client.nanoCast != nil 386 if admitted { 387 world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond)) 388 } 389 cold := newTestInventoryServer(t).characters[1] 390 391 if err != nil || admitted != fixture.accepted || player.nano != 0 || cold.nano != 0 || 392 player.nanoReserved != 0 || cold.nanoReserved != 0 || (player.effectiveAbility(16) == strength+12) != fixture.accepted { 393 t.Fatal("zero cost was rejected or negative cost created points/effects", err, admitted, player.nano, cold.nano) 394 } 395 }) 396 } 397 } 398 399 func TestNanoCostFailuresPublishNeitherChargeNorEffect(t *testing.T) { 400 for _, phase := range []string{"admission", "outcome"} { 401 for _, failure := range []string{"error", "ignore", "commit"} { 402 t.Run(phase+"/"+failure, func(t *testing.T) { 403 world, conn := newCombatNanoWorld(t, combatNanoFixture{Profession: 12}) 404 player, client := world.characters[1], world.clients[1] 405 player.inventory.LearnedNanos = []uint32{95410, 27169} 406 castTestBuff(t, world, 1, 1, 95410) 407 player.nanoRechargeUntil = time.Time{} 408 before := player.nano 409 request := characterActionPacket(1, [5]uint32{19, 50000, 1, 53019, 27169})[20:] 410 if phase == "outcome" { 411 if err := world.handleNanoCast(client, request); err != nil || client.nanoCast == nil || player.nanoReserved != 41 { 412 t.Fatal("discounted cast did not reserve before outcome fault", err) 413 } 414 } 415 event, condition := "UPDATE OF nano_reserved ON characters", "NEW.nano_reserved!=0" 416 if phase == "outcome" { 417 event, condition = "INSERT ON active_nanos", "NEW.program_id=27169" 418 } 419 statement := "CREATE TRIGGER fail_cost BEFORE " + event + " WHEN " + condition + " BEGIN SELECT RAISE(FAIL,'test cost'); END" 420 if failure == "ignore" { 421 statement = "CREATE TRIGGER fail_cost BEFORE " + event + " WHEN " + condition + " BEGIN SELECT RAISE(IGNORE); END" 422 } else if failure == "commit" { 423 statement = "CREATE TABLE pending_cost (player_id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_cost AFTER " + event + " WHEN " + condition + " BEGIN INSERT INTO pending_cost VALUES(999999); END" 424 } 425 if _, err := world.db.Exec(statement); err != nil { 426 t.Fatal(err) 427 } 428 conn.packets = nil 429 430 if phase == "admission" { 431 if err := world.handleNanoCast(client, request); err == nil { 432 t.Fatal("failed reservation returned success") 433 } 434 } else { 435 world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond)) 436 } 437 cold := newTestInventoryServer(t).characters[1] 438 439 if player.nano != before || cold.nano != before || player.nanoReserved != 0 || cold.nanoReserved != 0 || client.nanoCast != nil || 440 !player.nanoRechargeUntil.IsZero() || len(player.activeNanos) != 1 || len(cold.activeNanos) != 1 || 441 player.nanoBonus(318) != -7 || player.nanoBonus(16) != 0 { 442 t.Fatal("failed discounted cast published partial resources, recharge or effects", player.nano, before) 443 } 444 if phase == "admission" && len(conn.packets) != 0 || phase == "outcome" && 445 (len(conn.packets) != 2 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 108) { 446 t.Fatal("failed discounted cast published success", conn.packets) 447 } 448 if _, err := world.db.Exec("DROP TRIGGER fail_cost"); err != nil { 449 t.Fatal(err) 450 } 451 castTestBuff(t, world, 1, 1, 27169) 452 if player.nano != before-41 || player.nanoBonus(16) != 12 || len(player.activeNanos) != 2 { 453 t.Fatal("retry lost the cost contribution or repeated the charge") 454 } 455 }) 456 } 457 } 458 } 459 460 func TestNanoCostUnknownProgramsRejectWithoutMutation(t *testing.T) { 461 for _, program := range []uint32{0, 0xffffffff} { 462 t.Run(fmt.Sprint(program), func(t *testing.T) { 463 world, conn := newNanoCastingWorld(t) 464 player, client := world.characters[1], world.clients[1] 465 466 err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1000000, 53019, program})[20:]) 467 468 if err != nil || client.nanoCast != nil || player.nano != 30 || player.nanoReserved != 0 || world.characters[1000000].health != 100 || 469 len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 108 { 470 t.Fatal("unknown program changed resources, effects or cast state", program, err) 471 } 472 }) 473 } 474 }