aorecomp

Anarchy Online classic in the browser

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


server/nano_range_test.go (12979B)


      1 package main
      2 
      3 import (
      4 	"ao/server/gamedata"
      5 	"fmt"
      6 	"reflect"
      7 	"slices"
      8 	"testing"
      9 	"time"
     10 )
     11 
     12 func TestNanoRangeSignedModifiersDoNotInventAMinimumOrSelfBypass(t *testing.T) {
     13 	for _, fixture := range []struct {
     14 		modifier        int32
     15 		inside, outside float32
     16 		accepted        bool
     17 	}{
     18 		{-50, 6, 6.001, true}, {-100, 0, 0.001, true}, {-110, 0, 0, false},
     19 	} {
     20 		for _, inside := range []bool{false, true} {
     21 			t.Run(fmt.Sprintf("%d/%t", fixture.modifier, inside), func(t *testing.T) {
     22 				original := gamedata.NanoTemplates[95448]
     23 				definition := *original
     24 				definition.Sections = slices.Clone(original.Sections)
     25 				for index, section := range definition.Sections {
     26 					if section.Functions != nil {
     27 						functions := slices.Clone(*section.Functions)
     28 						for index := range functions {
     29 							functions[index].Arguments = slices.Clone(functions[index].Arguments)
     30 							functions[index].Arguments[1].Integer = new(fixture.modifier)
     31 						}
     32 						definition.Sections[index].Functions = &functions
     33 					}
     34 				}
     35 				gamedata.NanoTemplates[95448] = &definition
     36 				t.Cleanup(func() { gamedata.NanoTemplates[95448] = original })
     37 				world, _ := newNanoRangeWorld(t)
     38 				player, client, recipient := world.characters[1], world.clients[1], world.characters[2]
     39 				castTestBuff(t, world, 1, 1, 95448)
     40 				player.nanoRechargeUntil = time.Time{}
     41 				recipient.position[0] = fixture.outside
     42 				if inside {
     43 					recipient.position[0] = fixture.inside
     44 				}
     45 				before := player.nano
     46 
     47 				err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 2, 53019, 27169})[20:])
     48 				admitted := client.nanoCast != nil
     49 				if admitted {
     50 					world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond))
     51 				}
     52 
     53 				if err != nil || admitted != (inside && fixture.accepted) || admitted != (len(recipient.activeNanos) == 1) ||
     54 					!admitted && player.nano != before || player.nanoReserved != 0 {
     55 					t.Fatal("signed range was clamped or negative self-distance was bypassed", fixture.modifier, recipient.position, admitted, err)
     56 				}
     57 				if !fixture.accepted {
     58 					if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1, 53019, 27169})[20:]); err != nil || client.nanoCast != nil || player.nano != before {
     59 						t.Fatal("negative range incorrectly bypassed distance validation for the caster", err)
     60 					}
     61 				}
     62 			})
     63 		}
     64 	}
     65 }
     66 
     67 func TestNanoRangeReplacementFailuresKeepBothCompanionsAtomic(t *testing.T) {
     68 	for _, phase := range []string{"admission", "outcome"} {
     69 		for _, failure := range []string{"error", "ignore", "commit"} {
     70 			t.Run(phase+"/"+failure, func(t *testing.T) {
     71 				world, _ := newNanoRangeWorld(t)
     72 				player, client := world.characters[1], world.clients[1]
     73 				player.inventory.LearnedNanos = append(player.inventory.LearnedNanos, 95442)
     74 				castTestBuff(t, world, 1, 1, 95448)
     75 				player.nanoRechargeUntil = time.Time{}
     76 				before := player.nano
     77 				request := characterActionPacket(1, [5]uint32{19, 50000, 1, 53019, 95442})[20:]
     78 				if phase == "outcome" {
     79 					if err := world.handleNanoCast(client, request); err != nil || client.nanoCast == nil {
     80 						t.Fatal(err)
     81 					}
     82 				}
     83 				event, condition := "UPDATE OF nano_reserved ON characters", "NEW.nano_reserved!=0"
     84 				if phase == "outcome" {
     85 					event, condition = "INSERT ON active_nanos", "NEW.program_id=95442"
     86 				}
     87 				statement := "CREATE TRIGGER fail_range BEFORE " + event + " WHEN " + condition + " BEGIN SELECT RAISE(FAIL,'test range'); END"
     88 				if failure == "ignore" {
     89 					statement = "CREATE TRIGGER fail_range BEFORE " + event + " WHEN " + condition + " BEGIN SELECT RAISE(IGNORE); END"
     90 				} else if failure == "commit" {
     91 					statement = "CREATE TABLE pending_range (player_id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_range AFTER " + event + " WHEN " + condition + " BEGIN INSERT INTO pending_range VALUES(999999); END"
     92 				}
     93 				if _, err := world.db.Exec(statement); err != nil {
     94 					t.Fatal(err)
     95 				}
     96 
     97 				if phase == "admission" {
     98 					if err := world.handleNanoCast(client, request); err == nil {
     99 						t.Fatal("failed range reservation returned success")
    100 					}
    101 				} else {
    102 					world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond))
    103 				}
    104 				cold := newTestInventoryServer(t).characters[1]
    105 
    106 				if player.nano != before || cold.nano != before || player.nanoReserved != 0 || cold.nanoReserved != 0 || client.nanoCast != nil ||
    107 					player.nanoBonus(381) != 36 || cold.nanoBonus(381) != 36 || player.nanoBonus(318) != 0 || cold.nanoBonus(318) != 0 ||
    108 					len(player.activeNanos) != 1 || len(cold.activeNanos) != 1 {
    109 					t.Fatal("failed replacement changed its range/cost companions or durable debit")
    110 				}
    111 				if _, err := world.db.Exec("DROP TRIGGER fail_range"); err != nil {
    112 					t.Fatal(err)
    113 				}
    114 				castTestBuff(t, world, 1, 1, 95442)
    115 				cold = newTestInventoryServer(t).characters[1]
    116 				if player.nano != before-248 || cold.nano != player.nano || player.nanoBonus(381) != 86 || cold.nanoBonus(381) != 86 ||
    117 					player.nanoBonus(318) != 2 || cold.nanoBonus(318) != 2 || len(player.activeNanos) != 1 || len(cold.activeNanos) != 1 {
    118 					t.Fatal("retry failed to replace the whole mixed contract exactly once")
    119 				}
    120 			})
    121 		}
    122 	}
    123 }
    124 
    125 func TestNanoRangeProgramsUploadRefreshRestoreAndExpireCompleteEffects(t *testing.T) {
    126 	for _, fixture := range nanoRangeFixtures(t) {
    127 		t.Run(fmt.Sprint(fixture.Program), func(t *testing.T) {
    128 			world, _ := newNanoCostWorld(t, nanoCostFixture{combatNanoFixture: fixture.combatNanoFixture})
    129 			player, client := world.characters[1], world.clients[1]
    130 			trained := player.baseStats()
    131 
    132 			if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]); err != nil {
    133 				t.Fatal(err)
    134 			}
    135 			castTestBuff(t, world, 1, 1, fixture.Program)
    136 			player.nanoRechargeUntil = time.Time{}
    137 			refreshed := castTestBuff(t, world, 1, 1, fixture.Program)
    138 			cold := newTestInventoryServer(t).characters[1]
    139 
    140 			if len(player.activeNanos) != 1 || len(cold.activeNanos) != 1 || player.usedNCU() != fixture.NCU || cold.usedNCU() != fixture.NCU ||
    141 				player.baseStats() != trained || cold.baseStats() != trained || player.nanoReserved != 0 || cold.nano != player.nano ||
    142 				!slices.Equal(cold.inventory.LearnedNanos, []uint32{fixture.Program}) ||
    143 				player.activeNanos[0].expiresAt.Sub(refreshed) != time.Duration(fixture.Duration)*10*time.Millisecond {
    144 				t.Fatal("range refresh stacked, lost its upload, changed training or failed to persist")
    145 			}
    146 			for _, modifier := range fixture.Modifiers {
    147 				if player.nanoBonus(uint32(modifier[0])) != modifier[1] || cold.nanoBonus(uint32(modifier[0])) != modifier[1] {
    148 					t.Fatal("range contract omitted or duplicated its companion", fixture.Program, modifier)
    149 				}
    150 			}
    151 			items := slices.Clone(player.inventory.Items)
    152 			world.advanceNanos(player.activeNanos[0].expiresAt)
    153 			cold = newTestInventoryServer(t).characters[1]
    154 			if len(player.activeNanos) != 0 || len(cold.activeNanos) != 0 || player.usedNCU() != 0 || cold.usedNCU() != 0 ||
    155 				!reflect.DeepEqual(player.inventory.Items, items) || !reflect.DeepEqual(cold.inventory.Items, items) {
    156 				t.Fatal("range expiration retained an effect or changed owned equipment")
    157 			}
    158 			for _, modifier := range fixture.Modifiers {
    159 				if player.nanoBonus(uint32(modifier[0])) != 0 || cold.nanoBonus(uint32(modifier[0])) != 0 {
    160 					t.Fatal("range expiration left a companion", fixture.Program, modifier)
    161 				}
    162 			}
    163 		})
    164 	}
    165 }
    166 
    167 func newNanoRangeWorld(t *testing.T) (*server, *combatTestConn) {
    168 	t.Helper()
    169 	world, conn := newNanoCostWorld(t, nanoCostFixture{combatNanoFixture: combatNanoFixture{Profession: 11}})
    170 	player := world.characters[1]
    171 	player.inventory.LearnedNanos = []uint32{27169, 95407, 95443, 95444, 95448}
    172 	recipient := *player
    173 	recipient.id, recipient.name = 2, "Range recipient"
    174 	recipient.inventory, recipient.activeNanos = playerInventory{}, nil
    175 	world.characters[2], world.nextCharacter = &recipient, 2
    176 	world.clients[2] = &worldClient{id: 2, conn: &combatTestConn{}, ready: true, target: true}
    177 	if err := world.saveUser(&recipient); err != nil {
    178 		t.Fatal(err)
    179 	}
    180 	if err := world.saveInventory(player, player.inventory); err != nil {
    181 		t.Fatal(err)
    182 	}
    183 	return world, conn
    184 }
    185 
    186 func equipNanoRangeDevice(t *testing.T, world *server, template uint32) {
    187 	t.Helper()
    188 	player, client := world.characters[1], world.clients[1]
    189 	for _, fixture := range []struct{ template, slot uint32 }{{204601, 7}, {template, 11}} {
    190 		if granted, err := world.grantItem(player, fixture.template); err != nil || !granted {
    191 			t.Fatal(granted, err)
    192 		}
    193 		item := player.inventory.Items[len(player.inventory.Items)-1]
    194 		if err := world.handleInventory(client, inventoryMovePacket(1, item.Slot, fixture.slot)[20:]); err != nil || client.equipment == nil {
    195 			t.Fatal("range device or its belt could not begin installation", fixture.template, err)
    196 		}
    197 		world.advanceEquipment(client.equipment.readyAt)
    198 	}
    199 }
    200 
    201 func TestNanoRangeUsesCasterModifiersAndCompleteNativeDistanceChecks(t *testing.T) {
    202 	for _, fixture := range []struct {
    203 		name            string
    204 		programs        []uint32
    205 		device          uint32
    206 		inside, outside [3]float32
    207 	}{
    208 		{"base", nil, 0, [3]float32{12, 0, 0}, [3]float32{12.736, 0, 0}},
    209 		{"distance float32 store", nil, 0, [3]float32{0.001, 0, 12}, [3]float32{0.01, 0, 12}},
    210 		{"three dimensions", nil, 0, [3]float32{3, 4, 10}, [3]float32{3, 4, 11}},
    211 		{"range buff", []uint32{95448}, 0, [3]float32{16, 0, 0}, [3]float32{16.001, 0, 0}},
    212 		{"percentage truncation", []uint32{95444}, 0, [3]float32{17, 0, 0}, [3]float32{17.001, 0, 0}},
    213 		{"independent strains", []uint32{95407, 95448}, 0, [3]float32{16, 0, 0}, [3]float32{16.001, 0, 0}},
    214 		{"QL50 device", nil, 95516, [3]float32{25, 0, 0}, [3]float32{25.001, 0, 0}},
    215 		{"QL200 device", nil, 95517, [3]float32{29, 0, 0}, [3]float32{29.001, 0, 0}},
    216 		{"device plus nano", []uint32{95448}, 95516, [3]float32{29, 0, 0}, [3]float32{29.001, 0, 0}},
    217 		{"upper cap", []uint32{95443}, 95517, [3]float32{40, 0, 0}, [3]float32{40.001, 0, 0}},
    218 	} {
    219 		for _, accepted := range []bool{false, true} {
    220 			t.Run(fmt.Sprintf("%s/%t", fixture.name, accepted), func(t *testing.T) {
    221 				world, _ := newNanoRangeWorld(t)
    222 				player, client, recipient := world.characters[1], world.clients[1], world.characters[2]
    223 				if fixture.device != 0 {
    224 					equipNanoRangeDevice(t, world, fixture.device)
    225 				}
    226 				for _, program := range fixture.programs {
    227 					castTestBuff(t, world, 1, 1, program)
    228 					player.nanoRechargeUntil = time.Time{}
    229 				}
    230 				recipient.position = fixture.outside
    231 				if accepted {
    232 					recipient.position = fixture.inside
    233 				}
    234 				before := player.nano
    235 
    236 				err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 2, 53019, 27169})[20:])
    237 				if client.nanoCast != nil {
    238 					world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond))
    239 				}
    240 
    241 				if err != nil || (len(recipient.activeNanos) == 1) != accepted || client.nanoCast != nil || player.nanoReserved != 0 ||
    242 					accepted && player.nano >= before || !accepted && player.nano != before {
    243 					t.Fatal("range ignored caster effects, the complete distance check, signed percentage or cap", err, recipient.position, player.nano, before)
    244 				}
    245 			})
    246 		}
    247 	}
    248 }
    249 
    250 func TestNanoRangeCompletionRechecksCurrentCasterEffectsAndRefundsOnce(t *testing.T) {
    251 	for _, scenario := range []string{"buff removed", "buff expires", "target moves", "recipient range only"} {
    252 		t.Run(scenario, func(t *testing.T) {
    253 			world, _ := newNanoRangeWorld(t)
    254 			player, client, recipient := world.characters[1], world.clients[1], world.characters[2]
    255 			if scenario == "recipient range only" {
    256 				castTestBuff(t, world, 1, 2, 95448)
    257 			} else {
    258 				castTestBuff(t, world, 1, 1, 95448)
    259 			}
    260 			player.nanoRechargeUntil = time.Time{}
    261 			recipient.position = [3]float32{16, 0, 0}
    262 			before := player.nano
    263 
    264 			if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 2, 53019, 27169})[20:]); err != nil {
    265 				t.Fatal(err)
    266 			}
    267 			if scenario != "recipient range only" {
    268 				if client.nanoCast == nil {
    269 					t.Fatal("extended-range cast was rejected")
    270 				}
    271 				deadline := client.nanoCast.readyAt
    272 				switch scenario {
    273 				case "buff removed":
    274 					if err := world.handleNanoRemoval(client, characterActionPacket(1, [5]uint32{65, 0, 0, 53019, 95448})[20:]); err != nil {
    275 						t.Fatal(err)
    276 					}
    277 				case "buff expires":
    278 					player.activeNanos[0].expiresAt = deadline
    279 				case "target moves":
    280 					recipient.position[0] = 17
    281 				}
    282 				world.advanceNanos(deadline.Add(time.Nanosecond))
    283 				world.advanceNanos(deadline.Add(time.Second))
    284 			}
    285 
    286 			if player.nano != before || player.nanoReserved != 0 || client.nanoCast != nil || !player.nanoRechargeUntil.IsZero() ||
    287 				slices.ContainsFunc(recipient.activeNanos, func(effect activeNano) bool { return effect.program == 27169 }) {
    288 				t.Fatal("invalidated range spent a reservation or delivered the program", player.nano, before)
    289 			}
    290 		})
    291 	}
    292 }