aorecomp

Anarchy Online classic in the browser

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


commit 3cd5037e9a323ba771a128db79a3462d342c8011
parent eaa77d7420f5fb16b447abe12659654da8903a75
Author: anon <anon@example.com>
Date:   Fri,  6 Nov 2026 20:19:28 +0000

Add read-only item sources, admin icons and rotating shop stock

Diffstat:
MTODO.md | 5++++-
Mdocs/shop-stock-expansion.md | 34++++++++++++++++++++++++++++++++++
Mserver/admin_pages.go | 2+-
Mserver/assets/map.js | 55++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mserver/browser_creation.go | 10+++++++---
Mserver/control_data_test.go | 2+-
Mserver/control_inventory.go | 3++-
Mserver/http.go | 3+++
Aserver/item_icons.go | 67+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/item_pages.go | 30+++++++++++++++++++++++-------
Aserver/item_source_pages.go | 178+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/item_sources.go | 184+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/item_sources_test.go | 79+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/map_test.js | 19+++++++++++++++++++
Aserver/shop_catalog.go | 45+++++++++++++++++++++++++++++++++++++++++++++
Mserver/shop_quality_test.go | 13++++++++++++-
Aserver/shop_rotation_test.go | 59+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/shops.go | 2+-
18 files changed, 773 insertions(+), 17 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -138,7 +138,10 @@ research separately. More screenshots and test cases do not count as new gamepla functional basic shop is a failure. Completion: visit each listed shop, browse and buy/use its applicable stock, sell loot, cancel/retry and reconnect, with atomic credits/items and prices affordable under the alpha's reward rules. - Exact random stock rotation and the full historical catalog are deferred. + Exact historical stock rotation and the full historical catalog are deferred. + November 6: read-only acquisition browsing, original item icons and provisional + 30-minute restocking are documented in [shop stock](docs/shop-stock-expansion.md). + Shop changes remain embedded YAML plus a rebuild. November 5: [the finite terminal inventory](docs/early-shop-stock.md) lists all 190 placements in training grounds 950/952/954 and basic shops 1180/1183/1186. The four empty training terminals now carry seven original QL1 diff --git a/docs/shop-stock-expansion.md b/docs/shop-stock-expansion.md @@ -133,3 +133,37 @@ outside the implemented alpha paths. Importing their original definitions does not claim that all can yet be used successfully. Historical stock rotation, rarity and exact per-NPC sale membership remain uncertain. The existing temporary pickup-box visual while an NPC catalog is open also remains unchanged. + +## Read-only acquisition browsing and provisional restocking + +The admin item catalog shows family-level acquisition sources and filters for +items sold in shops, items not sold in shops, and items without a known source. +Opening a template shows offered QLs, shop restrictions, monster drop chances +and supported spawn levels, recipes, mission rewards/objectives, starting +items and world pickups. Its map marks seller and monster spawn positions; +interior sources use the corresponding playfield view. Shop links show the +embedded stock pool and its locations. These are read-only views: stock and +merchant bindings are still maintained in embedded YAML and require a rebuild. +An absent mapping is not proof that an item is impossible to obtain, and a +family source does not establish availability at every quality level. + +Original item icons are read directly from resource type 1010008 in the shipped +archive. The catalog, template and instance pages, inventory/equipment, bank, +reclaim, containers, recipes and shop stock share the same icon rendering. +Their original green transparency key is converted to alpha. Missing original +icons have a placeholder. + +Stock selection is shared per shop instance in 30-minute UTC periods. Supplies, +fixed-QL goods and equipment at QL10 or lower stay available. Higher-QL weapon +and armor families have a 75% inclusion chance per authored row and vary by up +to 10% QL, bounded by their supported original family. Identical results are +collapsed; a specialty shop never becomes empty. This is a provisional gameplay +policy, not recovered historical restock behavior. Each open trade retains its +stock snapshot, so a period boundary cannot change its rows, prices or delivery. +The admin pool lists possible stock, not a guarantee of what is currently on sale. + +Verification for these views and restocking: focused shop, source, icon, catalog +and starting-inventory Go tests passed, along with the map JavaScript tests and +`go vet ./server/...`. A small admin browser check covered catalog filtering, +item and shop maps, original icons, monster drops and an existing item instance. +Test-owned browsers and temporary servers were closed afterward. diff --git a/server/admin_pages.go b/server/admin_pages.go @@ -17,7 +17,7 @@ import ( func (server *server) adminPageStart(w http.ResponseWriter, title, section string) { w.Header().Set("Content-Type", "text/html; charset=utf-8") fmt.Fprintf(w, `<!doctype html><html lang='en'><head><meta charset='utf-8'><meta name='viewport' content='width=device-width,initial-scale=1'><base href='%s'><title>%s - AO Admin</title><style> - *{box-sizing:border-box}body{margin:0;background:#f4f6f8;color:#182634;font:15px system-ui,sans-serif}a{color:#175d8d;text-underline-offset:3px}header{background:#142c3e;color:white;padding:12px 24px;display:flex;align-items:center;gap:24px;flex-wrap:wrap}header strong{font-size:18px}nav{display:flex;gap:6px;flex-wrap:wrap}nav a{color:#d7e4ed;text-decoration:none;padding:10px 14px;border-radius:6px}nav a[aria-current=page],nav a:hover{background:#2b4d65;color:white}header form{margin-left:auto}main{padding:24px;max-width:1600px;margin:auto;overflow-x:auto}h1{font-size:26px;margin:0 0 20px}h2{font-size:19px;margin-top:26px}section,.cards>div{background:white;border:1px solid #d9e1e7;border-radius:8px;padding:20px;margin-bottom:20px}.cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:12px}.cards strong{display:block;font-size:28px;margin-top:8px}label{display:inline-flex;gap:8px;align-items:center;flex-wrap:wrap;margin:5px 10px 5px 0}input,select,textarea,button{font:inherit;border:1px solid #a7b8c5;border-radius:5px;padding:10px;max-width:100%%}input[type=checkbox]{width:20px;height:20px}button{background:#175d8d;color:white;border-color:#175d8d;cursor:pointer;min-height:44px}button:disabled{opacity:.5;cursor:default}input:focus-visible,select:focus-visible,textarea:focus-visible,button:focus-visible,a:focus-visible{outline:3px solid #e0a22a;outline-offset:2px}textarea{display:block;width:100%%;font:14px ui-monospace,monospace;line-height:1.5;background:white}table{border-collapse:collapse;background:white;width:100%%;margin:16px 0}th,td{text-align:left;padding:10px 12px;border-bottom:1px solid #dce3e9;vertical-align:top}th{background:#e7edf2;position:sticky;top:0}tr:hover td{background:#f0f6fa}.login{max-width:430px;margin:8vh auto}.login label{display:flex;align-items:stretch;flex-direction:column;margin:16px 0}.login input{width:100%%}.muted{color:#526777}.error{color:#a02121;white-space:pre-wrap}pre{white-space:pre-wrap;overflow-wrap:anywhere}canvas[data-map-canvas]{width:100%%;height:calc(100dvh - 310px);min-height:320px;display:block;touch-action:none;border-radius:8px}body:has(.map-page){height:100dvh;display:flex;flex-direction:column}body:has(.map-page) header{flex-shrink:0}body:has(.map-page) main{flex:1;min-height:0;margin:0;width:100%%;max-width:none;display:flex;flex-direction:column}.map-page,.map-page [data-world-map]{flex:1;min-height:0;display:flex;flex-direction:column}.map-page h1{font-size:22px;margin:0}.map-page [hidden]{display:none}.map-page form{margin-bottom:8px}.map-page p{margin:6px 0}.map-page canvas{flex:1;min-height:200px;height:0}details{margin:16px 0}summary{cursor:pointer;padding:10px 0}@media(max-width:600px){header{padding:12px;gap:10px}nav a{padding:10px}main{padding:14px}header form{margin-left:0}th,td{padding:8px}canvas[data-map-canvas]{height:60dvh}} + *{box-sizing:border-box}body{margin:0;background:#f4f6f8;color:#182634;font:15px system-ui,sans-serif}a{color:#175d8d;text-underline-offset:3px}header{background:#142c3e;color:white;padding:12px 24px;display:flex;align-items:center;gap:24px;flex-wrap:wrap}header strong{font-size:18px}nav{display:flex;gap:6px;flex-wrap:wrap}nav a{color:#d7e4ed;text-decoration:none;padding:10px 14px;border-radius:6px}nav a[aria-current=page],nav a:hover{background:#2b4d65;color:white}header form{margin-left:auto}main{padding:24px;max-width:1600px;margin:auto;overflow-x:auto}h1{font-size:26px;margin:0 0 20px}h2{font-size:19px;margin-top:26px}section,.cards>div{background:white;border:1px solid #d9e1e7;border-radius:8px;padding:20px;margin-bottom:20px}.cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:12px}.cards strong{display:block;font-size:28px;margin-top:8px}label{display:inline-flex;gap:8px;align-items:center;flex-wrap:wrap;margin:5px 10px 5px 0}input,select,textarea,button{font:inherit;border:1px solid #a7b8c5;border-radius:5px;padding:10px;max-width:100%%}input[type=checkbox]{width:20px;height:20px}button{background:#175d8d;color:white;border-color:#175d8d;cursor:pointer;min-height:44px}button:disabled{opacity:.5;cursor:default}input:focus-visible,select:focus-visible,textarea:focus-visible,button:focus-visible,a:focus-visible{outline:3px solid #e0a22a;outline-offset:2px}textarea{display:block;width:100%%;font:14px ui-monospace,monospace;line-height:1.5;background:white}table{border-collapse:collapse;background:white;width:100%%;margin:16px 0}th,td{text-align:left;padding:10px 12px;border-bottom:1px solid #dce3e9;vertical-align:top}th{background:#e7edf2;position:sticky;top:0}tr:hover td{background:#f0f6fa}.login{max-width:430px;margin:8vh auto}.login label{display:flex;align-items:stretch;flex-direction:column;margin:16px 0}.login input{width:100%%}.muted{color:#526777}.error{color:#a02121;white-space:pre-wrap}pre{white-space:pre-wrap;overflow-wrap:anywhere}canvas[data-map-canvas]{width:100%%;height:calc(100dvh - 310px);min-height:320px;display:block;touch-action:none;border-radius:8px}body:has(.map-page){height:100dvh;display:flex;flex-direction:column}body:has(.map-page) header{flex-shrink:0}body:has(.map-page) main{flex:1;min-height:0;margin:0;width:100%%;max-width:none;display:flex;flex-direction:column}.map-page,.map-page [data-world-map]{flex:1;min-height:0;display:flex;flex-direction:column}.map-page h1{font-size:22px;margin:0}.map-page [hidden]{display:none}.map-page form{margin-bottom:8px}.map-page p{margin:6px 0}.map-page canvas{flex:1;min-height:200px;height:0}details{margin:16px 0}.item-icon{display:inline-block;width:32px;height:32px;object-fit:contain;vertical-align:middle;margin-right:8px;border-radius:3px;background:#e7edf2}summary{cursor:pointer;padding:10px 0}@media(max-width:600px){header{padding:12px;gap:10px}nav a{padding:10px}main{padding:14px}header form{margin-left:0}th,td{padding:8px}canvas[data-map-canvas]{height:60dvh}} </style></head><body>`, html.EscapeString(server.baseURL), html.EscapeString(title)) if section != "" { fmt.Fprint(w, "<header><strong>AO Admin</strong><nav aria-label='Main navigation'>") diff --git a/server/assets/map.js b/server/assets/map.js @@ -11,6 +11,7 @@ class AOMap { this.form = element.querySelector("[data-map-teleport]"); this.character = Number(element.dataset.character); this.players = []; + this.sources = []; this.entities = {npcs: [], warps: []}; this.pointers = new Map(); this.tiles = new Map(); @@ -32,7 +33,9 @@ class AOMap { } this.manifest = await response.json(); this.zones = new Map(this.manifest.zones.map(zone => [zone.id, zone])); - for (const zone of this.manifest.zones.filter(zone => !zone.origin && zone.levels.length).sort((a, b) => a.name.localeCompare(b.name))) { + const sourceData = this.element.parentElement.querySelector("[data-item-sources]"); + if (sourceData) this.sources = JSON.parse(sourceData.textContent); + for (const zone of this.manifest.zones.filter(zone => !zone.origin).sort((a, b) => a.name.localeCompare(b.name))) { const option = document.createElement("option"); option.value = zone.id; option.textContent = `${zone.name} (${zone.id})`; @@ -80,6 +83,16 @@ class AOMap { new ResizeObserver(() => this.resize()).observe(this.canvas); this.resize(); this.fit(this.bounds()); + const sourceChoice = this.element.parentElement.querySelector("[data-map-source]"); + if (sourceChoice) { + sourceChoice.addEventListener("change", () => this.focusSource(this.sources[Number(sourceChoice.value)])); + this.focusSource(this.sources[0]); + } + const query = new URLSearchParams(window.location.search); + if (query.has("playfield") && query.has("x") && query.has("z")) { + this.sources = [{playfield: Number(query.get("playfield")), position: [Number(query.get("x")), 0, Number(query.get("z"))], name: "Source location"}]; + this.focusSource(this.sources[0]); + } await this.poll(); } @@ -180,7 +193,26 @@ class AOMap { zone.origin[1] + Math.max(...boundary.map(point => point[1]))]); } + focusSource(source) { + const zone = this.zones.get(source.playfield); + if (!zone) { + this.location.textContent = `${source.name}: playfield ${source.playfield} has no map.`; + return; + } + this.initialized = true; + this.view.value = zone.origin ? "world" : String(zone.id); + this.center = this.playerPoint(source); + this.scale = 1; + this.location.textContent = `${source.name}: ${zone.name} (${zone.id}), X ${source.position[0].toFixed(1)}, Z ${source.position[2].toFixed(1)}.`; + this.renderSoon(); + } + centerPlayer() { + if (this.sources.length) { + const sourceChoice = this.element.parentElement.querySelector("[data-map-source]"); + this.focusSource(this.sources[Number(sourceChoice?.value || 0)]); + return; + } this.element.querySelector("[data-map-find]").value = ""; const player = this.players.find(player => player.id === this.character); const zone = player && this.zones.get(player.playfield); @@ -359,6 +391,15 @@ class AOMap { } pick(x, y) { + for (const source of this.sources) { + const point = this.playerPoint(source); + if (!point) continue; + const screen = this.toScreen(...point); + if (Math.hypot(x - screen[0], y - screen[1]) < 10) { + this.location.textContent = `${source.name}: playfield ${source.playfield}, X ${source.position[0].toFixed(1)}, Z ${source.position[2].toFixed(1)}.`; + return; + } + } for (const marker of this.entities.warps) { if (!this.detailVisible() || !this.element.querySelector("[data-map-warps]").checked) break; const screen = this.toScreen(...marker.point); @@ -493,6 +534,18 @@ class AOMap { } } + // Acquisition markers remain visible at every zoom, independently of live NPCs. + for (const source of this.sources) { + const point = this.playerPoint(source); + if (!point) continue; + const [x, y] = this.toScreen(...point); + ctx.fillStyle = "#21db87"; + ctx.strokeStyle = "#102b20"; + ctx.lineWidth = 2; + ctx.beginPath(); ctx.arc(x, y, 6, 0, Math.PI * 2); ctx.fill(); ctx.stroke(); + if (this.scale >= 0.6) ctx.fillText(source.name, x + 9, y - 9); + } + // Draw player markers above imagery; offline markers have an empty centre. ctx.font = "12px sans-serif"; for (const player of this.players) { diff --git a/server/browser_creation.go b/server/browser_creation.go @@ -90,21 +90,25 @@ func insertRow(tx *sql.Tx, table, columns string, fields []any) error { return nil } -func (server *server) browserStartingItems_locked(player *character) error { +func startingItemTemplates(profession uint16, side uint16) []uint32 { // Original startup weapons/crystals and sided gifts; provenance is in character-creation.md. professions := [][]uint32{ {121569, 29092}, {117610, 43382}, {121567, 43329, 29194, 43328}, {121571, 43380}, {121568, 43383, 29191}, {121567, 28742}, {121570, 43378, 78417}, {121567, 43381, 29625}, {121564, 43379}, {121567, 28778, 43384}, {121567, 28815, 42111}, {121566, 43330, 29193}, } - side := unpackAppearance(player.appearance).Side templates := []uint32{116628, 116629, []uint32{116697, 116696, 116693}[side]} - templates = append(templates, professions[player.profession-1]...) + templates = append(templates, professions[profession-1]...) if side == 1 { templates = append(templates, 96358) } else if side == 2 { templates = append(templates, 99719, 29426) } + return templates +} + +func (server *server) browserStartingItems_locked(player *character) error { + templates := startingItemTemplates(player.profession, uint16(unpackAppearance(player.appearance).Side)) if uint64(server.nextItem)+uint64(len(templates)) > uint64(^uint32(0)) { return fmt.Errorf("item identities exhausted") } diff --git a/server/control_data_test.go b/server/control_data_test.go @@ -40,7 +40,7 @@ func TestControlItemCatalogPaginatesAndFilters(t *testing.T) { } } if filtered.Code != http.StatusOK || strings.Count(filtered.Body.String(), "<button name='template' value='") != 1 || - !strings.Contains(filtered.Body.String(), "<td>Solar-Powered Pistol</td>") || !strings.Contains(filtered.Body.String(), "value='121567'>Create</button>") { + !strings.Contains(filtered.Body.String(), "Solar-Powered Pistol</a></td>") || !strings.Contains(filtered.Body.String(), "value='121567'>Create</button>") { t.Fatal("catalog filter did not select the exact template") } } diff --git a/server/control_inventory.go b/server/control_inventory.go @@ -18,6 +18,7 @@ func (server *server) itemTableRow_locked(w io.Writer, slot string, id *uint32) record := server.items[*id] if definition := (ownedItem{Type: record.Type, Template: record.Template, Quality: record.Quality}).templateDefinition(); definition != nil { name = definition.Name + fmt.Fprint(w, itemIcon(definition)) } fmt.Fprintf(w, "<a href='admin/items/%d'>%s (ID %d)</a>", *id, html.EscapeString(name), *id) } @@ -63,7 +64,7 @@ func (server *server) inventoryTables_locked(w io.Writer, inventory playerInvent continue } fmt.Fprintf(w, "<h2>Container <a href='admin/items/%d'>%s (ID %d)</a></h2>", item.ID, - html.EscapeString(gamedata.ItemTemplates[item.Template].Name), item.ID) + itemIcon(item.templateDefinition())+html.EscapeString(gamedata.ItemTemplates[item.Template].Name), item.ID) server.backpackTable_locked(w, server.items[item.ID]) } } diff --git a/server/http.go b/server/http.go @@ -73,6 +73,9 @@ func (server *server) adminHandler() http.Handler { admin.HandleFunc("POST /admin/players/{character}/password", server.changePlayerPassword) admin.HandleFunc("GET /admin/items", server.itemsPage) admin.HandleFunc("GET /admin/items/catalog", server.itemCatalogPage) + admin.HandleFunc("GET /admin/items/catalog/{template}", server.itemTemplatePage) + admin.HandleFunc("GET /admin/item-icons/{icon}", server.itemIconPage) + admin.HandleFunc("GET /admin/shops/{template}", server.shopCatalogPage) admin.HandleFunc("POST /admin/items", server.createItem) admin.HandleFunc("GET /admin/items/{item}", server.itemPage) admin.HandleFunc("POST /admin/items/{item}", server.editItem) diff --git a/server/item_icons.go b/server/item_icons.go @@ -0,0 +1,67 @@ +package main + +import ( + "ao/server/gamedata" + "bytes" + "fmt" + "html" + "image" + "image/draw" + "image/png" + "net/http" + "strconv" + "time" +) + +func itemIcon(definition *gamedata.Item) string { + if definition == nil || itemStat(definition, 79) == 0 { + return "<span class='item-icon' title='No item icon available'></span>" + } + return fmt.Sprintf("<img class='item-icon' src='admin/item-icons/%d' width='32' height='32' alt='' loading='lazy'>", itemStat(definition, 79)) +} + +func catalogItemLink(template uint32) string { + definition := gamedata.ItemTemplates[template] + return fmt.Sprintf("<a href='admin/items/catalog/%d'>%s%s</a>", template, itemIcon(definition), html.EscapeString(definition.Name)) +} + +func (server *server) itemIconPage(w http.ResponseWriter, r *http.Request) { + icon, err := strconv.ParseUint(r.PathValue("icon"), 10, 32) + if err != nil { + http.NotFound(w, r) + return + } + database := server.geometry.database + // A few original records reference missing icons. Keep their layout without a broken image. + if _, exists := database.positions[[2]uint32{1010008, uint32(icon)}]; !exists { + w.Header().Set("Content-Type", "image/svg+xml") + fmt.Fprint(w, `<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48"><rect x="1" y="1" width="46" height="46" rx="4" fill="#e7edf2" stroke="#a7b8c5"/><text x="24" y="31" text-anchor="middle" font-size="24" fill="#526777">?</text></svg>`) + return + } + data, _, err := database.read(1010008, uint32(icon)) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + // Original icons use pure green as a transparency key. + decoded, err := png.Decode(bytes.NewReader(data)) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + iconImage := image.NewNRGBA(decoded.Bounds()) + draw.Draw(iconImage, iconImage.Bounds(), decoded, decoded.Bounds().Min, draw.Src) + for offset := 0; offset < len(iconImage.Pix); offset += 4 { + if iconImage.Pix[offset] == 0 && iconImage.Pix[offset+1] == 255 && iconImage.Pix[offset+2] == 0 { + iconImage.Pix[offset+3] = 0 + } + } + var encoded bytes.Buffer + if err := png.Encode(&encoded, iconImage); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "image/png") + w.Header().Set("Cache-Control", "private, max-age=31536000, immutable") + http.ServeContent(w, r, "icon.png", time.Time{}, bytes.NewReader(encoded.Bytes())) +} diff --git a/server/item_pages.go b/server/item_pages.go @@ -123,7 +123,7 @@ func (server *server) itemsPage(w http.ResponseWriter, r *http.Request) { if location.owner != 0 { owner = names[location.owner] } - fmt.Fprintf(w, "<tr><td><a href='admin/items/%d'>%d</a></td><td><a href='admin/items/%d'>%s</a></td><td>%d</td><td>%d</td><td>", id, id, id, html.EscapeString(name), record.Quality, record.Count) + fmt.Fprintf(w, "<tr><td><a href='admin/items/%d'>%d</a></td><td><a href='admin/items/%d'>%s</a></td><td>%d</td><td>%d</td><td>", id, id, id, itemIcon(definition)+html.EscapeString(name), record.Quality, record.Count) if location.owner == 0 { fmt.Fprint(w, owner) } else { @@ -138,9 +138,16 @@ func (server *server) itemsPage(w http.ResponseWriter, r *http.Request) { func (server *server) itemCatalogPage(w http.ResponseWriter, r *http.Request) { catalog := strings.ToLower(strings.TrimSpace(r.FormValue("catalog"))) + sources := itemSources() + sourceFilter := r.FormValue("source") var matches []*gamedata.Item for _, definition := range gamedata.ItemTemplates { if definition.Quality != nil && (catalog == "" || strings.Contains(strings.ToLower(definition.Name), catalog) || strconv.FormatUint(uint64(definition.ID), 10) == catalog) { + available := sources[itemFamily(definition.ID)] + buyable := slices.ContainsFunc(available, func(source itemSource) bool { return source.kind == "Shop" }) + if sourceFilter == "shops" && !buyable || sourceFilter == "no-shops" && buyable || sourceFilter == "unknown" && len(available) != 0 { + continue + } matches = append(matches, definition) } } @@ -153,12 +160,21 @@ func (server *server) itemCatalogPage(w http.ResponseWriter, r *http.Request) { // Filter before paging so every page refers to the same ordered result set. w.Header().Set("Content-Type", "text/html; charset=utf-8") - server.adminPageStart(w, "Create item", "Items") - fmt.Fprintf(w, "<h1>Create item</h1><form method='get' action='admin/items/catalog'><label>Filter by name or template ID <input name='catalog' value='%s'></label> <button>Filter</button> <a href='admin/items/catalog'>Clear filter</a></form>", html.EscapeString(r.FormValue("catalog"))) + server.adminPageStart(w, "Item catalog", "Items") + fmt.Fprintf(w, "<h1>Item catalog</h1><form method='get' action='admin/items/catalog'><label>Filter by name or template ID <input name='catalog' value='%s'></label>", html.EscapeString(r.FormValue("catalog"))) + fmt.Fprint(w, "<label>Sources <select name='source'>") + for _, option := range []struct{ value, label string }{{"", "All"}, {"shops", "Buyable in shops"}, {"no-shops", "Not sold in shops"}, {"unknown", "No known acquisition source"}} { + selected := "" + if sourceFilter == option.value { + selected = " selected" + } + fmt.Fprintf(w, "<option value='%s'%s>%s</option>", option.value, selected, option.label) + } + fmt.Fprint(w, "</select></label> <button>Filter</button> <a href='admin/items/catalog'>Clear filter</a></form><p>Sources cover the item's quality-level family. Open an item to see available qualities and locations. No known source means no mapped acquisition path in the current server data.</p>") start, end := itemPagination(w, r, len(matches)) - fmt.Fprint(w, "<form method='post' action='admin/items'><table><tr><th>Name</th><th>Template</th><th>QL</th><th></th></tr>") + fmt.Fprint(w, "<form method='post' action='admin/items'><table><tr><th>Name</th><th>Template</th><th>QL</th><th>Sources (family)</th><th></th></tr>") for _, definition := range matches[start:end] { - fmt.Fprintf(w, "<tr><td>%s</td><td>%d</td><td>%d</td><td><button name='template' value='%d'>Create</button></td></tr>", html.EscapeString(definition.Name), definition.ID, *definition.Quality, definition.ID) + fmt.Fprintf(w, "<tr><td>%s</td><td>%d</td><td>%d</td><td>%s</td><td><button name='template' value='%d'>Create</button></td></tr>", catalogItemLink(definition.ID), definition.ID, *definition.Quality, html.EscapeString(itemSourceSummary(sources[itemFamily(definition.ID)])), definition.ID) } fmt.Fprint(w, "</table></form>") itemPagination(w, r, len(matches)) @@ -238,7 +254,7 @@ func (server *server) itemPage(w http.ResponseWriter, r *http.Request) { server.adminPageStart(w, fmt.Sprintf("Item %d", id), "Items") fmt.Fprintf(w, "<h1>Item %d</h1>", id) if definition != nil { - fmt.Fprintf(w, "<h2>%s</h2><p><strong>Description:</strong> %s</p>", html.EscapeString(definition.Name), html.EscapeString(definition.Description)) + fmt.Fprintf(w, "<h2>%s</h2><p><strong>Description:</strong> %s</p>", itemIcon(definition)+html.EscapeString(definition.Name), html.EscapeString(definition.Description)) } if location.owner != 0 { fmt.Fprintf(w, "<p>Owner: <a href='admin/players/%d'>%s (%d)</a>. ", location.owner, html.EscapeString(ownerName), location.owner) @@ -250,7 +266,7 @@ func (server *server) itemPage(w http.ResponseWriter, r *http.Request) { } else { fmt.Fprint(w, html.EscapeString(location.label)) } - fmt.Fprint(w, "</p>") + fmt.Fprintf(w, "</p><p><a href='admin/items/catalog/%d'>View catalog and acquisition sources</a></p>", record.Template) if location.label == "" { fmt.Fprintf(w, "<h2>Assign item</h2><form method='get' action='admin/items/%d'><label>Player <select name='owner' required>", id) for _, user := range users { diff --git a/server/item_source_pages.go b/server/item_source_pages.go @@ -0,0 +1,178 @@ +package main + +import ( + "ao/server/gamedata" + "encoding/json" + "fmt" + "html" + "maps" + "net/http" + "slices" + "strconv" + "strings" +) + +type sourceMapLocation struct { + Name string `json:"name"` + Playfield uint32 `json:"playfield"` + Position [3]float32 `json:"position"` +} + +func sourceMap(w http.ResponseWriter, sources []itemSource) { + locations := make([]sourceMapLocation, 0) + seen := make(map[sourceMapLocation]bool) + for _, source := range sources { + for _, location := range source.locations { + marker := sourceMapLocation{source.kind + ": " + location.name, location.playfield, location.position} + if !seen[marker] { + locations = append(locations, marker) + seen[marker] = true + } + } + } + if len(locations) == 0 { + return + } + data, err := json.Marshal(locations) + if err != nil { + panic(err) + } + fmt.Fprint(w, "<section><h2>Acquisition locations</h2><p>Green markers show possible sources. NPC markers use their spawn positions. Interior locations appear in their own playfield view.</p><label>Source location <select data-map-source>") + for index, location := range locations { + fmt.Fprintf(w, "<option value='%d'>%s - %s (%d), X %.1f Z %.1f</option>", index, html.EscapeString(location.Name), html.EscapeString(gamedata.Playfields[location.Playfield].Name), location.Playfield, location.Position[0], location.Position[2]) + } + fmt.Fprintf(w, "</select></label><script type='application/json' data-item-sources>%s</script>", data) + controlMap(w, 0) + fmt.Fprint(w, "</section>") +} + +func (server *server) itemTemplatePage(w http.ResponseWriter, r *http.Request) { + template, err := strconv.ParseUint(r.PathValue("template"), 10, 32) + definition := gamedata.ItemTemplates[uint32(template)] + if err != nil || definition == nil || definition.Quality == nil { + http.NotFound(w, r) + return + } + sources := itemSources()[itemFamily(definition.ID)] + server.adminPageStart(w, definition.Name, "Items") + fmt.Fprintf(w, "<p><a href='admin/items/catalog'>Item catalog</a></p><h1>%s%s</h1><p>%s</p><p>Template %d, QL %d. %s.</p>", itemIcon(definition), html.EscapeString(definition.Name), html.EscapeString(definition.Description), definition.ID, *definition.Quality, html.EscapeString(itemSourceSummary(sources))) + fmt.Fprint(w, "<p>Sources below cover this item's quality-level family; only the listed QLs are offered. Shop rows describe possible stock, not guaranteed current availability. No known source is a gap in the current server mappings, not proof that the item is impossible to obtain.</p>") + sourceMap(w, sources) + fmt.Fprint(w, "<h2>Sources</h2><table><tr><th>Type</th><th>Source</th><th>QL</th><th>Details</th></tr>") + for _, source := range sources { + name := html.EscapeString(source.name) + if source.shop != 0 { + name = fmt.Sprintf("<a href='admin/shops/%d'>%s</a>", source.shop, itemIcon(gamedata.ItemTemplates[source.shop])+name) + } + if source.ingredients[0] != 0 { + name = catalogItemLink(source.ingredients[0]) + " + " + catalogItemLink(source.ingredients[1]) + } + quality := fmt.Sprintf("%d", source.quality[0]) + if source.quality[0] != source.quality[1] { + quality = fmt.Sprintf("%d-%d", source.quality[0], source.quality[1]) + } + if source.quality[0] == 0 { + quality = "Mission level" + } + fmt.Fprintf(w, "<tr><td>%s</td><td>%s</td><td>%s</td><td>", source.kind, name, quality) + if source.kind == "Loot" { + fmt.Fprintf(w, "%d%% per roll, NPC levels %d-%d. ", source.chance, source.level[0], source.level[1]) + } + if source.shop != 0 { + fmt.Fprint(w, html.EscapeString(shopAccess(gamedata.ItemTemplates[source.shop])), ". ") + } + if len(source.locations) != 0 { + fmt.Fprintf(w, "<details><summary>%d locations</summary><ul>", len(source.locations)) + for _, location := range source.locations { + fmt.Fprintf(w, "<li><a href='admin/map?playfield=%d&amp;x=%g&amp;z=%g'>%s - %s (%d), X %.1f Z %.1f</a></li>", location.playfield, location.position[0], location.position[2], html.EscapeString(location.name), html.EscapeString(gamedata.Playfields[location.playfield].Name), location.playfield, location.position[0], location.position[2]) + } + fmt.Fprint(w, "</ul></details>") + } + fmt.Fprint(w, "</td></tr>") + } + fmt.Fprint(w, "</table>") + itemCatalogProperties(w, ownedItem{Type: definition.HeaderWords[0], Template: definition.ID, Quality: *definition.Quality}, definition) + fmt.Fprint(w, "</main></body></html>") +} + +func shopAccess(definition *gamedata.Item) string { + var conditions []string + for _, section := range definition.Sections { + if section.Actions == nil { + continue + } + for _, action := range *section.Actions { + if action.Type != 3 { + continue + } + var stack []string + for _, requirement := range action.Requirements { + if (requirement.Operator == 3 || requirement.Operator == 4) && len(stack) >= 2 { + operator := " OR " + if requirement.Operator == 4 { + operator = " AND " + } + stack[len(stack)-2] = "(" + stack[len(stack)-2] + operator + stack[len(stack)-1] + ")" + stack = stack[:len(stack)-1] + } else if requirement.Operator == 42 && len(stack) > 0 { + stack[len(stack)-1] = "NOT (" + stack[len(stack)-1] + ")" + } else { + operator := map[int32]string{0: "=", 1: "<", 2: ">", 24: "!="}[requirement.Operator] + if operator == "" { + operator = fmt.Sprintf("operator %d", requirement.Operator) + } + value := fmt.Sprint(requirement.Value) + if requirement.Stat == 33 { + value = map[int32]string{0: "Neutral", 1: "Clan", 2: "Omni"}[requirement.Value] + } + stack = append(stack, fmt.Sprintf("%s %s %s", gamedata.ItemStatNames[uint32(requirement.Stat)], operator, value)) + } + } + if len(stack) > 0 { + conditions = append(conditions, stack[len(stack)-1]) + } + } + } + if len(conditions) == 0 { + return "No faction or profession restriction" + } + return strings.Join(conditions, " AND ") +} + +func (server *server) shopCatalogPage(w http.ResponseWriter, r *http.Request) { + template, err := strconv.ParseUint(r.PathValue("template"), 10, 32) + stock, exists := gamedata.ShopStock[uint32(template)] + if err != nil || !exists { + http.NotFound(w, r) + return + } + definition := gamedata.ItemTemplates[uint32(template)] + server.adminPageStart(w, definition.Name, "Items") + fmt.Fprintf(w, "<p><a href='admin/items/catalog'>Item catalog</a></p><h1>%s</h1><p>Shop template %d. %s.</p>", itemIcon(definition)+html.EscapeString(definition.Name), template, html.EscapeString(shopAccess(definition))) + fmt.Fprint(w, "<p>This is the possible stock pool from embedded YAML. Supplies and QL 1-10 equipment stay available. Higher-QL weapon and armor families rotate every 30 minutes, with a 75% inclusion chance per row and QL varying by up to 10% within the supported range. Open trades keep their original stock and prices. Editing stock requires changing the YAML and recompiling.</p>") + // Each catalog repeats its placements per item; one source supplies the map. + sources := itemSources() + for _, family := range slices.Sorted(maps.Keys(sources)) { + found := false + for _, source := range sources[family] { + if source.shop == uint32(template) { + sourceMap(w, []itemSource{source}) + found = true + break + } + } + if found { + break + } + } + fmt.Fprint(w, "<table><tr><th>Item</th><th>Template</th><th>Base QL</th><th>Possible QL</th><th>Availability</th></tr>") + for _, entry := range stock { + low, high := shopQualityRange(entry) + availability := "Always stocked" + if low != high { + availability = "Rotating" + } + fmt.Fprintf(w, "<tr><td>%s</td><td>%d</td><td>%d</td><td>%d-%d</td><td>%s</td></tr>", catalogItemLink(entry.Template), entry.Template, entry.Quality, low, high, availability) + } + fmt.Fprint(w, "</table></main></body></html>") +} diff --git a/server/item_sources.go b/server/item_sources.go @@ -0,0 +1,184 @@ +package main + +import ( + "ao/server/gamedata" + "cmp" + "fmt" + "maps" + "slices" + "strconv" + "strings" +) + +type itemSource struct { + kind string + name string + shop uint32 + ingredients [2]uint32 + quality [2]uint32 + chance uint32 + level [2]uint16 + locations []itemSourceLocation +} + +type itemSourceLocation struct { + name string + playfield uint32 + position [3]float32 +} + +func itemFamily(template uint32) uint32 { + if pair, exists := gamedata.ItemFamilies[template]; exists { + return pair[0] + } + return template +} + +func npcSourcePlayfield(id string) uint32 { + zone, _, _ := strings.Cut(id, "/") + value, _ := strconv.ParseUint(zone, 10, 32) + return uint32(value) +} + +// Build one family index per page, never scan all sources separately for each catalog row. +func itemSources() map[uint32][]itemSource { + sources := make(map[uint32][]itemSource) + sellers := make(map[uint32][]itemSourceLocation) + for _, id := range slices.Sorted(maps.Keys(gamedata.ShopMachines)) { + machine := gamedata.ShopMachines[id] + if itemStat(gamedata.ItemTemplates[machine.Template], 30)&8 == 0 { + continue + } + sellers[machine.Template] = append(sellers[machine.Template], itemSourceLocation{ + fmt.Sprintf("%s (machine %d)", gamedata.ItemTemplates[machine.Template].Name, id), machine.Playfield, machine.Position}) + } + for _, id := range slices.Sorted(maps.Keys(gamedata.NPCGroups)) { + group := gamedata.NPCGroups[id] + if group.ShopTemplate != 0 { + for _, position := range group.Positions { + sellers[group.ShopTemplate] = append(sellers[group.ShopTemplate], itemSourceLocation{group.Name, npcSourcePlayfield(id), position}) + } + } + // Use only profiles admitted for this group at levels it can actually spawn at. + drops := make(map[[2]uint32]itemSource) + for _, level := range slices.Sorted(maps.Keys(gamedata.NPCCombatProfiles[group.MonsterData])) { + profile := gamedata.NPCCombatProfiles[group.MonsterData][level] + if level < group.Levels[0] || level > group.Levels[1] || !group.SupportsCombatProfile(group.MonsterData, profile) { + continue + } + for _, drop := range profile.Loot { + if drop.Chance == 0 { + continue + } + family := itemFamily(drop.Template) + // Keep distinct probabilities separate rather than inventing an aggregate drop rate. + key := [2]uint32{family, drop.Chance} + source, exists := drops[key] + if !exists { + source = itemSource{kind: "Loot", name: group.Name + " (" + id + ")", quality: drop.Quality, chance: drop.Chance, level: [2]uint16{level, level}} + for _, position := range group.Positions { + source.locations = append(source.locations, itemSourceLocation{group.Name, npcSourcePlayfield(id), position}) + } + } else { + source.quality[0] = min(source.quality[0], drop.Quality[0]) + source.quality[1] = max(source.quality[1], drop.Quality[1]) + source.level[1] = level + } + drops[key] = source + } + } + keys := slices.Collect(maps.Keys(drops)) + slices.SortFunc(keys, func(a, b [2]uint32) int { + if a[0] != b[0] { + return cmp.Compare(a[0], b[0]) + } + return cmp.Compare(a[1], b[1]) + }) + for _, key := range keys { + sources[key[0]] = append(sources[key[0]], drops[key]) + } + if group.StaticMesh != 0 && len(group.Positions) > 0 { + template := gamedata.NPCNames.Templates[group.TemplateCode].ItemTemplate + source := itemSource{kind: "World pickup", name: group.Name, quality: [2]uint32{uint32(group.Levels[0]), min(uint32(group.Levels[1]), uint32(group.Levels[0])+uint32(len(group.Positions))-1)}} + for _, position := range group.Positions { + source.locations = append(source.locations, itemSourceLocation{group.Name, npcSourcePlayfield(id), position}) + } + sources[itemFamily(template)] = append(sources[itemFamily(template)], source) + } + } + for _, template := range slices.Sorted(maps.Keys(sellers)) { + for _, entry := range gamedata.ShopStock[template] { + low, high := shopQualityRange(entry) + family := itemFamily(entry.Template) + sources[family] = append(sources[family], itemSource{kind: "Shop", name: gamedata.ItemTemplates[template].Name, shop: template, quality: [2]uint32{low, high}, locations: sellers[template]}) + } + } + // Recipes, mission rewards/objectives and issued equipment are also acquisition paths. + for _, tool := range slices.Sorted(maps.Keys(gamedata.ItemCombinations)) { + for _, material := range slices.Sorted(maps.Keys(gamedata.ItemCombinations[tool])) { + recipe := gamedata.ItemCombinations[tool][material] + result := gamedata.ItemTemplates[recipe.Result] + sources[itemFamily(recipe.Result)] = append(sources[itemFamily(recipe.Result)], itemSource{kind: "Crafted", name: "Combine", ingredients: [2]uint32{tool, material}, quality: [2]uint32{*result.Quality, *result.Quality}}) + } + } + for _, template := range slices.Sorted(maps.Keys(gamedata.MissionTemplates)) { + mission := gamedata.MissionTemplates[template] + for _, item := range append(slices.Clone(mission.RewardItems), mission.ObjectiveItem) { + if item == 0 { + continue + } + quality := mission.RewardQuality + kind := "Mission reward" + if item == mission.ObjectiveItem { + kind = "Mission objective" + quality = *gamedata.ItemTemplates[item].Quality + } + sources[itemFamily(item)] = append(sources[itemFamily(item)], itemSource{kind: kind, name: mission.Description, quality: [2]uint32{quality, quality}, locations: []itemSourceLocation{{"Mission booth", gamedata.MissionBooths[template].Playfield, gamedata.MissionBooths[template].Position}}}) + } + } + issued := make(map[uint32]bool) + for profession := uint16(1); profession <= 12; profession++ { + for side := uint16(0); side <= 2; side++ { + for _, template := range startingItemTemplates(profession, side) { + if issued[template] { + continue + } + issued[template] = true + item := gamedata.ItemTemplates[template] + sources[itemFamily(template)] = append(sources[itemFamily(template)], itemSource{kind: "Starter equipment", name: "Issued during character creation", quality: [2]uint32{*item.Quality, *item.Quality}}) + } + } + } + return sources +} + +func itemSourceSummary(sources []itemSource) string { + shops := make(map[uint32]int) + loot := make(map[string]bool) + other := make(map[string]bool) + for _, source := range sources { + if source.kind == "Shop" { + shops[source.shop] = len(source.locations) + } else if source.kind == "Loot" { + loot[source.name] = true + } else { + other[source.kind] = true + } + } + var parts []string + count := 0 + for _, n := range shops { + count += n + } + if count != 0 { + parts = append(parts, fmt.Sprintf("Shops: %d", count)) + } + if len(loot) != 0 { + parts = append(parts, fmt.Sprintf("Loot: %d", len(loot))) + } + parts = append(parts, slices.Sorted(maps.Keys(other))...) + if len(parts) == 0 { + return "No known acquisition source" + } + return strings.Join(parts, "; ") +} diff --git a/server/item_sources_test.go b/server/item_sources_test.go @@ -0,0 +1,79 @@ +package main + +import ( + "ao/server/gamedata" + "bytes" + "image/png" + "net/http/httptest" + "slices" + "strconv" + "strings" + "testing" +) + +func TestItemSourcesIncludeShopsLootCraftingAndStarterFamilies(t *testing.T) { + sources := itemSources() + armor := sources[itemFamily(85595)] + if !slices.ContainsFunc(armor, func(source itemSource) bool { + return source.kind == "Shop" && source.quality == [2]uint32{5, 5} && len(source.locations) > 0 + }) { + t.Fatal("high endpoint did not find the QL5 armor sellers") + } + if !slices.ContainsFunc(sources[itemFamily(42640)], func(source itemSource) bool { + return source.kind == "Loot" && source.chance == 50 && len(source.locations) > 0 + }) { + t.Fatal("Monster Parts lost its mapped 50% monster drops") + } + if !slices.ContainsFunc(sources[itemFamily(158416)], func(source itemSource) bool { return source.kind == "Crafted" }) { + t.Fatal("NCU Hacker Interface lost its recipe") + } + if !slices.ContainsFunc(sources[itemFamily(121567)], func(source itemSource) bool { return source.kind == "Starter equipment" }) { + t.Fatal("starter pistol lost its issuance source") + } +} + +func TestItemSourcePagesAreReadOnlyAndFilterFamilies(t *testing.T) { + world := newTestServer(t) + handler := adminTestHandler(world) + for _, path := range []string{"/admin/items/catalog/85595", "/admin/shops/99491"} { + page := httptest.NewRecorder() + handler.ServeHTTP(page, httptest.NewRequest("GET", path, nil)) + if page.Code != 200 || !strings.Contains(page.Body.String(), "data-item-sources") || !strings.Contains(page.Body.String(), "class='item-icon'") || strings.Contains(page.Body.String(), "method='post'") && strings.Contains(page.Body.String(), "name='data'") { + t.Fatal(path, "lost read-only source data or icons") + } + post := httptest.NewRecorder() + handler.ServeHTTP(post, httptest.NewRequest("POST", path, strings.NewReader(""))) + if post.Code != 405 { + t.Fatal(path, "allows mutations", post.Code) + } + } + for _, filter := range []string{"shops", "no-shops", "unknown"} { + page := httptest.NewRecorder() + handler.ServeHTTP(page, httptest.NewRequest("GET", "/admin/items/catalog?catalog=85595&source="+filter, nil)) + found := strings.Contains(page.Body.String(), "value='85595'>Create") + if page.Code != 200 || found != (filter == "shops") { + t.Fatal("family source filter failed", filter, page.Code) + } + } +} + +func TestAdminItemIconUsesOriginalPNG(t *testing.T) { + world := newTestServer(t) + response := httptest.NewRecorder() + // Use the shipped armor icon and its original green transparency key. + icon := itemStat(gamedata.ItemTemplates[85595], 79) + request := httptest.NewRequest("GET", "/admin/item-icons/"+strconv.FormatUint(uint64(icon), 10), nil) + request.SetPathValue("icon", strconv.FormatUint(uint64(icon), 10)) + world.itemIconPage(response, request) + decoded, err := png.Decode(bytes.NewReader(response.Body.Bytes())) + if response.Code != 200 || response.Header().Get("Content-Type") != "image/png" || err != nil { + t.Fatal("original icon was not served", response.Code, err) + } + if decoded.Bounds().Dx() != 48 || decoded.Bounds().Dy() != 48 { + t.Fatal("unexpected original icon dimensions", decoded.Bounds()) + } + _, _, _, alpha := decoded.At(0, 0).RGBA() + if alpha != 0 { + t.Fatal("original green background is not transparent") + } +} diff --git a/server/map_test.js b/server/map_test.js @@ -242,3 +242,22 @@ test('cancelled touch releases the gesture without selecting a destination', () assert.equal(map.drag, null); assert.equal(map.pointers.size, 0); }); + +test('acquisition locations focus outdoor and interior coordinates and label taps', () => { + const map = mapWithTiles(1000, 1, () => {}); + map.zones.set(705, {id: 705, name: 'Trade', origin: [1000, 2000]}); + map.zones.set(1183, {id: 1183, name: 'Shop', width: 500, height: 500, levels: []}); + map.sources = [{name: 'Shop: Supplies', playfield: 705, position: [100, 0, 200]}]; + + map.focusSource(map.sources[0]); + assert.equal(map.view.value, 'world'); + assert.deepEqual(Array.from(map.center), [1100, 2200]); + map.pick(500, 500); + assert.match(map.location.textContent, /Shop: Supplies/); + assert.equal(map.selection, null); + + map.focusSource({name: 'Shop: Armor', playfield: 1183, position: [180, 5, 135]}); + assert.equal(map.view.value, '1183'); + assert.deepEqual(Array.from(map.center), [180, 135]); + assert.equal(map.initialized, true); +}); diff --git a/server/shop_catalog.go b/server/shop_catalog.go @@ -0,0 +1,45 @@ +package main + +import ( + "ao/server/gamedata" + "math/rand/v2" + "time" +) + +func shopQualityRange(entry gamedata.ShopItem) (uint32, uint32) { + definition := gamedata.ItemTemplates[entry.Template] + pair, exists := gamedata.ItemFamilies[entry.Template] + class := itemStat(definition, 76) + // Keep supplies, fixed-QL goods and the starter equipment core continuously available. + if !exists || entry.Quality <= 10 || (class != 1 && class != 2) { + return entry.Quality, entry.Quality + } + spread := max(uint32(1), entry.Quality/10) + return max(*gamedata.ItemTemplates[pair[0]].Quality, entry.Quality-spread), min(*gamedata.ItemTemplates[pair[1]].Quality, entry.Quality+spread) +} + +func (server *server) shopCatalog_locked(machine, template uint32, now time.Time) []gamedata.ShopItem { + // A shop shares one selection across players for each half-hour, without a background timer. + roll := rand.New(rand.NewPCG(uint64(machine), uint64(now.Unix()/1800))) + stock := gamedata.ShopStock[template] + result := make([]gamedata.ShopItem, 0, len(stock)) + seen := make(map[gamedata.ShopItem]bool) + for _, entry := range stock { + low, high := shopQualityRange(entry) + if low != high { + if roll.IntN(4) == 0 { + continue + } + entry.Quality = low + uint32(roll.IntN(int(high-low+1))) + } + if !seen[entry] { + result = append(result, entry) + seen[entry] = true + } + } + // Even a one-item specialty assortment remains a usable shop. + if len(result) == 0 && len(stock) != 0 { + result = append(result, stock[0]) + } + return result +} diff --git a/server/shop_quality_test.go b/server/shop_quality_test.go @@ -71,11 +71,22 @@ func TestShopQualityCatalogResolvesBothStoredAnchors(t *testing.T) { t.Fatal("quality catalog failed", err, len(conn.packets)) } catalog := conn.packets[3] - for index, expected := range []uint32{4036, 85596, 85596, 1, 85596, 85595, 5, 85595, 85595, 200} { + for index, expected := range []uint32{uint32(len(world.clients[1].shop.stock)+1) * 1009, 85596, 85596, 1, 85596, 85595, 5} { if binary.BigEndian.Uint32(catalog[29+4*index:]) != expected { t.Fatalf("anchor %d catalog field %d changed", anchor, index) } } + // The highest row may rotate out or vary within the original endpoint range. + if len(world.clients[1].shop.stock) == 3 { + quality := world.clients[1].shop.stock[2].Quality + low := uint32(85596) + if quality == 200 { + low = 85595 + } + if quality < 180 || quality > 200 || binary.BigEndian.Uint32(catalog[57:61]) != low || binary.BigEndian.Uint32(catalog[61:65]) != 85595 || binary.BigEndian.Uint32(catalog[65:69]) != quality { + t.Fatal("rotated catalog lost its selected quality or original endpoints") + } + } }) { return } diff --git a/server/shop_rotation_test.go b/server/shop_rotation_test.go @@ -0,0 +1,59 @@ +package main + +import ( + "ao/server/gamedata" + "slices" + "testing" + "time" +) + +func TestShopRotationKeepsSuppliesAndStarterStockStable(t *testing.T) { + original := gamedata.ShopStock[99491] + gamedata.ShopStock[99491] = []gamedata.ShopItem{{Template: 21605, Quality: 1}, {Template: 85596, Quality: 5}, {Template: 85596, Quality: 100}} + t.Cleanup(func() { gamedata.ShopStock[99491] = original }) + world := &server{} + first := world.shopCatalog_locked(3221488799, 99491, time.Unix(0, 0)) + same := world.shopCatalog_locked(3221488799, 99491, time.Unix(1799, 0)) + if !slices.Equal(first, same) { + t.Fatal("stock changed within a restock period") + } + changed := false + for period := int64(1); period <= 8; period++ { + stock := world.shopCatalog_locked(3221488799, 99491, time.Unix(period*1800, 0)) + if !slices.Equal(stock, first) { + changed = true + } + if len(stock) < 2 || stock[0] != (gamedata.ShopItem{Template: 21605, Quality: 1}) || stock[1] != (gamedata.ShopItem{Template: 85596, Quality: 5}) { + t.Fatal("stable supplies or starter armor rotated out") + } + if len(stock) == 3 && (stock[2].Quality < 90 || stock[2].Quality > 110 || !gamedata.ItemQualitySupported(stock[2].Template, stock[2].Quality)) { + t.Fatal("rotation invented an unsupported QL", stock) + } + } + if !changed { + t.Fatal("stock never rotated") + } + if gamedata.ShopStock[99491][2].Quality != 100 { + t.Fatal("rotation modified embedded source stock") + } +} + +func TestShopRotationDoesNotChangeOpenTrade(t *testing.T) { + world, _ := newPurchaseWorld(t) + client := world.clients[1] + before := slices.Clone(client.shop.stock) + world.shopCatalog_locked(client.shop.machine, 99491, time.Now().Add(30*time.Minute)) + if !slices.Equal(client.shop.stock, before) { + t.Fatal("refresh changed an open trade") + } + if err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{51035, client.shop.machine}, [2]uint32{111, 0})[20:]); err != nil { + t.Fatal(err) + } + if err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:]); err != nil { + t.Fatal(err) + } + purchased := world.characters[1].inventory.Items[1] + if purchased.Template != 95577 || purchased.Quality != 1 { + t.Fatal("open trade delivered changed stock", purchased) + } +} diff --git a/server/shops.go b/server/shops.go @@ -115,7 +115,7 @@ func (server *server) startShop_locked(client *worldClient, machineID uint32, ma return err } } - client.shop = &shopTrade{machine: machineID, items: make(map[uint32]ownedItem), stock: gamedata.ShopStock[machine.Template], purchases: make(map[uint32]uint16)} + client.shop = &shopTrade{machine: machineID, items: make(map[uint32]ownedItem), stock: server.shopCatalog_locked(machineID, machine.Template, time.Now()), purchases: make(map[uint32]uint16)} // Explain missing purchase stock while keeping the terminal available for sales. if len(client.shop.stock) == 0 { text := gamedata.ItemTemplates[machine.Template].Name + ": Purchases are not yet supported in this alpha. You can still sell items here."