server/shops.go (18698B)
1 package main 2 3 import ( 4 "ao/server/gamedata" 5 "cmp" 6 "encoding/binary" 7 "fmt" 8 "maps" 9 "slices" 10 "time" 11 ) 12 13 type shopTrade struct { 14 machine uint32 15 items map[uint32]ownedItem 16 stock []gamedata.ShopItem 17 purchases map[uint32]uint16 18 } 19 20 func (server *server) shopMachine(client *worldClient, id uint32) (gamedata.ShopMachine, bool) { 21 if machine, exists := gamedata.ShopMachines[id]; exists { 22 return machine, true 23 } 24 npc := server.characters[id] 25 if npc == nil || !npc.npc || npc.health == 0 || !client.npcs[id] { 26 return gamedata.ShopMachine{}, false 27 } 28 group := gamedata.NPCGroups[npc.npcDefinitionID] 29 if group == nil || group.ShopTemplate == 0 { 30 return gamedata.ShopMachine{}, false 31 } 32 // Native catalog/quote APIs require VendingMachine_t. Keep admission on the 33 // NPC; Mesh12=0 uses the pickup box only for the lifetime of its private catalog. 34 return gamedata.ShopMachine{Template: group.ShopTemplate, Playfield: npc.playfield, Position: npc.position, 35 Rotation: npc.rotation, Stats: [][2]uint32{{12, 0}}}, true 36 } 37 38 func (server *server) canUseShop(client *worldClient, machine gamedata.ShopMachine) bool { 39 player := server.characters[client.id] 40 if !client.target || server.clients[client.id] != client || !client.ready || client.loading || player.health == 0 || 41 client.equipment != nil || client.trade != nil || player.playfield != machine.Playfield { 42 return false 43 } 44 position := predictedPosition(player, time.Now()) 45 x, y, z := position[0]-machine.Position[0], position[1]-machine.Position[1], position[2]-machine.Position[2] 46 if x*x+y*y+z*z > 5*5 { 47 return false 48 } 49 // Native default Use requires Can8; vending criteria select only action3. 50 definition := gamedata.ItemTemplates[machine.Template] 51 return itemStat(definition, 30)&8 != 0 && player.templateUseRequirementsMet(definition) 52 } 53 54 func shopMachinePacket(id uint32, machine gamedata.ShopMachine) []byte { 55 // VendingMachineFullUpdate inherits SimpleItem 11, Lockable 2 and Chest 3. 56 body := simpleItemBody(machine.Template, machine.Playfield, machine.Position, machine.Rotation, machine.Stats) 57 for _, value := range []uint32{2, 0, 1009, 3} { 58 body = binary.BigEndian.AppendUint32(body, value) 59 } 60 return n3Packet(0x7f544905, 51035, id, body) 61 } 62 63 func shopTradePacket(subject [2]uint32, action uint32, first, second [2]uint32) []byte { 64 var body []byte 65 for _, value := range []uint32{1, action, first[0], first[1], second[0], second[1]} { 66 body = binary.BigEndian.AppendUint32(body, value) 67 } 68 return n3Packet(0x36284f6e, subject[0], subject[1], body) 69 } 70 71 func (server *server) handleShopUse(client *worldClient, body []byte) error { 72 if len(body) != 48 { 73 return fmt.Errorf("invalid shop use length") 74 } 75 // E sends character Use with kind 0; a vending machine uses kind 1. 76 targetType, kind := binary.BigEndian.Uint32(body[40:44]), binary.BigEndian.Uint32(body[28:32]) 77 if binary.BigEndian.Uint32(body[4:8]) != 50000 || binary.BigEndian.Uint32(body[8:12]) != client.id || 78 binary.BigEndian.Uint32(body[16:20]) != 0 || binary.BigEndian.Uint32(body[24:28]) != 3 || 79 binary.BigEndian.Uint32(body[32:36]) != 50000 || 80 binary.BigEndian.Uint32(body[36:40]) != client.id || 81 !(targetType == 51035 && kind == 1 || targetType == 50000 && kind == 0) || 82 !client.target || server.clients[client.id] != client || !client.ready || client.loading { 83 return nil 84 } 85 sequence := binary.BigEndian.Uint32(body[20:24]) 86 if sequence <= client.useSequence { 87 return nil 88 } 89 client.useSequence = sequence 90 machineID := binary.BigEndian.Uint32(body[44:48]) 91 machine, exists := server.shopMachine(client, machineID) 92 accepted := exists && server.canUseShop(client, machine) 93 if targetType == 50000 { 94 npc := server.characters[machineID] 95 accepted = accepted && npc != nil && npc.npc 96 } 97 reply := append([]byte(nil), body[16:]...) 98 binary.BigEndian.PutUint32(reply, 2) 99 if accepted { 100 binary.BigEndian.PutUint32(reply, 1) 101 } 102 if err := client.send(n3Packet(0x52526858, 50000, client.id, reply)); err != nil || !accepted { 103 return err 104 } 105 return server.startShop(client, machineID, machine) 106 } 107 108 func (server *server) startShop(client *worldClient, machineID uint32, machine gamedata.ShopMachine) error { 109 if client.shop != nil { 110 if err := server.abortShop(client); err != nil { 111 return err 112 } 113 } 114 client.shop = &shopTrade{machine: machineID, items: make(map[uint32]ownedItem), stock: server.shopCatalog(machineID, machine.Template, time.Now()), purchases: make(map[uint32]uint16)} 115 // Explain missing purchase stock while keeping the terminal available for sales. 116 if len(client.shop.stock) == 0 { 117 text := gamedata.ItemTemplates[machine.Template].Name + ": Purchases are not yet supported in this alpha. You can still sell items here." 118 feedback := binary.BigEndian.AppendUint32(nil, uint32(len(text))) 119 feedback = append(feedback, text...) 120 feedback = append(feedback, 0, 0) 121 if err := client.send(n3Packet(0x5f4b442a, 50000, client.id, feedback)); err != nil { 122 return err 123 } 124 } 125 if err := client.send(shopMachinePacket(machineID, machine)); err != nil { 126 return err 127 } 128 // Unknown categories omit ShopUpdate; an empty update prints a native GM warning. 129 if len(client.shop.stock) != 0 { 130 // Native catalog entries are page111 indices, without owned instance IDs. 131 catalog := binary.BigEndian.AppendUint32(nil, uint32(len(client.shop.stock)+1)*1009) 132 for _, entry := range client.shop.stock { 133 item := ownedItem{Type: gamedata.ItemTemplates[entry.Template].HeaderWords[0], Template: entry.Template, Quality: entry.Quality} 134 low, high := item.templateIDs() 135 for _, value := range []uint32{low, high, entry.Quality} { 136 catalog = binary.BigEndian.AppendUint32(catalog, value) 137 } 138 } 139 if err := client.send(n3Packet(0x58362220, 51035, machineID, catalog)); err != nil { 140 return err 141 } 142 } 143 // Create the machine's per-player trade record before the GUI queries it. 144 if err := client.send(shopTradePacket([2]uint32{51035, machineID}, 0, [2]uint32{50000, client.id}, [2]uint32{})); err != nil { 145 return err 146 } 147 // DDR uses B as the catalog's GUI tag. It must differ from the machine 148 // identity so selected rows reach the purchase grid rather than the catalog. 149 return client.send(shopTradePacket([2]uint32{50000, client.id}, 0, [2]uint32{51035, machineID}, [2]uint32{111, 0})) 150 } 151 152 func (server *server) abortShop(client *worldClient) error { 153 if client.shop != nil { 154 slots := make([]uint32, 0, len(client.shop.items)) 155 for slot := range client.shop.items { 156 slots = append(slots, slot) 157 } 158 slices.Sort(slots) 159 if err := server.restoreTradeItems(client, client.shop.items, slots); err != nil { 160 return err 161 } 162 } 163 return server.finishShop(client, 2) 164 } 165 166 func (server *server) finishShop(client *worldClient, action uint32) error { 167 shop := client.shop 168 client.shop = nil 169 if err := client.send(shopTradePacket([2]uint32{50000, client.id}, action, [2]uint32{}, [2]uint32{})); err != nil { 170 return err 171 } 172 // NPC catalogs are connection-local and must not obstruct the next interaction. 173 if shop != nil { 174 if _, machine := gamedata.ShopMachines[shop.machine]; !machine { 175 return client.send(n3Packet(0x36510078, 51035, shop.machine, nil)) 176 } 177 } 178 return nil 179 } 180 181 func restoredTradeInventory(inventory playerInventory, offers map[uint32]ownedItem, returned []uint32) (playerInventory, map[uint32]ownedItem) { 182 inventory.Items = slices.Clone(inventory.Items) 183 remaining := maps.Clone(offers) 184 for _, slot := range returned { 185 delete(remaining, slot) 186 } 187 188 // Offered roots remain durably owned, but are absent from the native ordinary 189 // inventory. Restore selected rows first, in the same first-free order as KKR. 190 var held []ownedItem 191 inventory.Items = slices.DeleteFunc(inventory.Items, func(item ownedItem) bool { 192 for _, offer := range offers { 193 if item.ID == offer.ID { 194 held = append(held, item) 195 return true 196 } 197 } 198 return false 199 }) 200 order := slices.Clone(returned) 201 for slot := range remaining { 202 order = append(order, slot) 203 } 204 slices.Sort(order[len(returned):]) 205 for _, slot := range order { 206 index := slices.IndexFunc(held, func(item ownedItem) bool { return item.ID == offers[slot].ID }) 207 if index < 0 { 208 continue 209 } 210 item := held[index] 211 item.Slot = 64 212 for slices.ContainsFunc(inventory.Items, func(other ownedItem) bool { return other.Slot == item.Slot }) { 213 item.Slot++ 214 } 215 inventory.Items = append(inventory.Items, item) 216 if _, exists := remaining[slot]; exists { 217 remaining[slot] = item 218 } 219 } 220 slices.SortFunc(inventory.Items, func(a, b ownedItem) int { return cmp.Compare(a.ID, b.ID) }) 221 return inventory, remaining 222 } 223 224 func (server *server) restoreTradeItems(client *worldClient, offers map[uint32]ownedItem, returned []uint32) error { 225 if len(offers) == 0 { 226 return nil 227 } 228 player := server.characters[client.id] 229 inventory, remaining := restoredTradeInventory(player.inventory, offers, returned) 230 // Publish draft reservations only after their durable placement commits. 231 if !slices.Equal(inventory.Items, player.inventory.Items) { 232 if err := server.saveInventory(player, inventory); err != nil { 233 return err 234 } 235 } 236 clear(offers) 237 maps.Copy(offers, remaining) 238 return nil 239 } 240 241 func (item ownedItem) shopPrice() uint32 { 242 return item.templateStat(74) 243 } 244 245 func shopSalePrice(item ownedItem, modifier uint32, computerLiteracy int32) uint64 { 246 // kkr.dll FUN_100a99d0 rounds the charge-normalized unit price to float32. 247 price := float32(item.shopPrice()) 248 if charges := int32(itemStat(item.templateDefinition(), 212)); item.Type != 51018 && charges > 0 { 249 price /= float32(charges) 250 } 251 base := uint64(float64(item.Count) * float64(price) * float64(modifier) * 0.01) 252 // kkr.dll 100a9b33..100a9b5f preserves signed literacy, then floors the line total. 253 markup := int64(float64(computerLiteracy) * float64(float32(0.025))) 254 return uint64(max(0, int64(base)+int64(float64(markup)*float64(float32(0.01))*float64(base)))) 255 } 256 257 func shopBuyPrice(item ownedItem, modifier uint32, computerLiteracy int32) uint64 { 258 // kkr.dll 100a9610 discounts each package, with a ninety-percent cap. 259 base := int64(float64(item.shopPrice()) * float64(modifier) * 0.01) 260 discount := min(int64(float64(computerLiteracy)*float64(float32(0.025))), 90) 261 return uint64(base - int64(float64(discount)*float64(base)*float64(float32(0.01)))) 262 } 263 264 func shopPendingSalePrice(item ownedItem, modifier uint32, computerLiteracy int32) int64 { 265 // kkr.dll 100a9f60 uses one signed price per offered row, without charges/count. 266 price := int32(item.shopPrice()) 267 if price == 1234567890 { 268 price = 0 269 } 270 base := int64(float64(price) * float64(int32(modifier)) * 0.01) 271 markup := int64(float64(computerLiteracy) * float64(float32(0.025))) 272 return base + int64(float64(markup)*float64(base)*float64(float32(0.01))) 273 } 274 275 func (server *server) handleTrade(client *worldClient, body []byte) error { 276 if len(body) != 40 { 277 return fmt.Errorf("invalid trade length") 278 } 279 if !client.target || server.clients[client.id] != client || !client.ready || client.loading || 280 binary.BigEndian.Uint32(body[4:8]) != 50000 || binary.BigEndian.Uint32(body[8:12]) != client.id || binary.BigEndian.Uint32(body[16:20]) != 1 { 281 return nil 282 } 283 action := binary.BigEndian.Uint32(body[20:24]) 284 first := [2]uint32{binary.BigEndian.Uint32(body[24:28]), binary.BigEndian.Uint32(body[28:32])} 285 second := [2]uint32{binary.BigEndian.Uint32(body[32:36]), binary.BigEndian.Uint32(body[36:40])} 286 if action == 0 && first[0] == 50000 && second == [2]uint32{} { 287 if npc := server.characters[first[1]]; npc != nil && npc.npc { 288 machine, exists := server.shopMachine(client, npc.id) 289 if exists && server.canUseShop(client, machine) { 290 return server.startShop(client, npc.id, machine) 291 } 292 return nil 293 } 294 } 295 if action == 0 || client.trade != nil { 296 return server.handlePlayerTrade(client, body) 297 } 298 if client.shop == nil { 299 return nil 300 } 301 machine, exists := server.shopMachine(client, client.shop.machine) 302 if action == 2 || !exists || !server.canUseShop(client, machine) { 303 return server.abortShop(client) 304 } 305 player := server.characters[client.id] 306 if (action == 4 || action == 5) && first == [2]uint32{51035, client.shop.machine} { 307 if second[0] != 111 || second[1] >= uint32(len(client.shop.stock)) { 308 return server.abortShop(client) 309 } 310 // Each native Add/Remove selects one package, using a signed-short count. 311 count := client.shop.purchases[second[1]] 312 if action == 4 { 313 if count == 32767 { 314 return server.abortShop(client) 315 } 316 entry := client.shop.stock[second[1]] 317 definition := gamedata.ItemTemplates[entry.Template] 318 item := ownedItem{Type: definition.HeaderWords[0], Template: entry.Template, Quality: entry.Quality} 319 if itemStat(definition, 0)&0x08000000 != 0 && (count != 0 || player.inventory.carriesUnique(item)) { 320 return server.abortShop(client) 321 } 322 // The native echo receiver ignores unaffordable Adds. Match its pending 323 // calculation before acknowledging so rapid requests cannot hide purchases. 324 literacy := player.effectiveSkill(161, player.stats.TradeRepair.ComputerLiteracy, [6]uint32{0, 0, 0, 100, 0, 0}) 325 vendor := gamedata.ItemTemplates[machine.Template] 326 cost := int64(shopBuyPrice(item, itemStat(vendor, 427), literacy)) 327 for index, packages := range client.shop.purchases { 328 other := client.shop.stock[index] 329 definition := gamedata.ItemTemplates[other.Template] 330 cost += int64(shopBuyPrice(ownedItem{Type: definition.HeaderWords[0], Template: other.Template, Quality: other.Quality}, itemStat(vendor, 427), literacy)) * int64(packages) 331 } 332 for _, offered := range client.shop.items { 333 cost -= shopPendingSalePrice(offered, itemStat(vendor, 426), literacy) 334 } 335 if cost > int64(player.inventory.Credits) { 336 return server.abortShop(client) 337 } 338 client.shop.purchases[second[1]] = count + 1 339 } else { 340 if count == 0 { 341 return server.abortShop(client) 342 } 343 client.shop.purchases[second[1]] = count - 1 344 } 345 return client.send(shopTradePacket([2]uint32{50000, client.id}, action, first, second)) 346 } 347 switch action { 348 case 4: 349 if first != [2]uint32{50000, client.id} || second[0] != 104 || second[1] < 64 || second[1] >= 94 { 350 return server.abortShop(client) 351 } 352 index := slices.IndexFunc(player.inventory.Items, func(item ownedItem) bool { return item.Slot == second[1] }) 353 if index < 0 { 354 if err := server.abortShop(client); err != nil { 355 return err 356 } 357 // Cancellation restores the drag, but not stale stack rows or counts. 358 return server.syncStacks(client) 359 } 360 item := player.inventory.Items[index] 361 definition := item.templateDefinition() 362 if itemStat(definition, 0)&0x04000000 != 0 || item.Type == 51017 { 363 return server.abortShop(client) 364 } 365 for _, stat := range definition.Stats { 366 if item.Type == 51022 && stat[0] == 8 && int32(stat[1]) != -1 { 367 return server.abortShop(client) 368 } 369 } 370 for _, other := range client.shop.items { 371 if other.ID == item.ID { 372 return nil 373 } 374 } 375 // The native trade inventory keeps stable slots when an offer is removed. 376 var slot uint32 377 for { 378 if _, occupied := client.shop.items[slot]; !occupied { 379 break 380 } 381 slot++ 382 } 383 client.shop.items[slot] = item 384 return client.send(shopTradePacket([2]uint32{50000, client.id}, action, first, second)) 385 case 5: 386 if _, exists := client.shop.items[second[1]]; first != [2]uint32{50000, client.id} || second[0] != 108 || !exists { 387 return server.abortShop(client) 388 } 389 if err := server.restoreTradeItems(client, client.shop.items, []uint32{second[1]}); err != nil { 390 return err 391 } 392 return client.send(shopTradePacket([2]uint32{50000, client.id}, action, first, second)) 393 case 1, 6: 394 if first != [2]uint32{} || second != [2]uint32{} { 395 return server.abortShop(client) 396 } 397 // The native shop Accept button clears its cash offer before confirming. 398 if action == 6 { 399 return client.send(shopTradePacket([2]uint32{50000, client.id}, 6, first, second)) 400 } 401 inventory := player.inventory 402 inventory.Items = slices.Clone(inventory.Items) 403 literacy := player.effectiveSkill(161, player.stats.TradeRepair.ComputerLiteracy, [6]uint32{0, 0, 0, 100, 0, 0}) 404 modifier := itemStat(gamedata.ItemTemplates[machine.Template], 426) 405 var credits uint64 406 for _, item := range client.shop.items { 407 index := slices.Index(inventory.Items, item) 408 if index < 0 { 409 return server.abortShop(client) 410 } 411 credits += shopSalePrice(item, modifier, literacy) 412 inventory.Items = slices.Delete(inventory.Items, index, index+1) 413 } 414 // Stage purchases in the prospective inventory; publish only after commit. 415 var cost uint64 416 nextItem := server.nextItem 417 var purchased []ownedItem 418 for index, entry := range client.shop.stock { 419 definition := gamedata.ItemTemplates[entry.Template] 420 item := ownedItem{Type: definition.HeaderWords[0], Template: entry.Template, Quality: entry.Quality, Count: 1} 421 if item.isStackable() { 422 item.Count = uint16(max(1, itemStat(definition, 212))) 423 } 424 count := client.shop.purchases[uint32(index)] 425 cost += shopBuyPrice(item, itemStat(gamedata.ItemTemplates[machine.Template], 427), literacy) * uint64(count) 426 for range count { 427 if itemStat(definition, 0)&0x08000000 != 0 && inventory.carriesUnique(item) { 428 return server.abortShop(client) 429 } 430 item.Slot = 64 431 for item.Slot < 94 && slices.ContainsFunc(inventory.Items, func(other ownedItem) bool { return other.Slot == item.Slot }) { 432 item.Slot++ 433 } 434 if item.Slot == 94 { 435 return server.abortShop(client) 436 } 437 id, err := server.reserveItems(1) 438 if err != nil { 439 return err 440 } 441 nextItem = id 442 item.ID = nextItem 443 inventory.Items = append(inventory.Items, item) 444 purchased = append(purchased, item) 445 } 446 } 447 balance := uint64(inventory.Credits) + credits 448 if cost > balance || balance-cost > 1000000000 { 449 return server.abortShop(client) 450 } 451 inventory.Credits = uint32(balance - cost) 452 if len(purchased) != 0 { 453 inventory.LastID = nextItem 454 } 455 // Sales, purchases and cash share the existing SQLite transaction. 456 if len(client.shop.items) != 0 || len(purchased) != 0 { 457 if err := server.saveInventory(player, inventory); err != nil { 458 return err 459 } 460 server.nextItem = nextItem 461 } 462 if err := server.finishShop(client, 3); err != nil { 463 return err 464 } 465 // Deliver first-free rows in the same order as the durable allocation. 466 for _, item := range purchased { 467 if err := client.send(inventoryAdditionPacket(player, item)); err != nil { 468 return err 469 } 470 } 471 stats := binary.BigEndian.AppendUint32(nil, 61) 472 stats = binary.BigEndian.AppendUint32(stats, inventory.Credits) 473 return client.send(n3Packet(0x2b333d6e, 50000, client.id, stats)) 474 } 475 return server.abortShop(client) 476 }