aorecomp

Anarchy Online classic in the browser

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


commit 0ab91ba55cb85f69f63e88e60ab11a0e96a774d3
parent 44dc978be707d637e1612798a908a8a7de66aa65
Author: anon <anon@example.com>
Date:   Sat, 28 Nov 2026 10:17:11 +0000

Bound admin catalog memory and render only the requested page

Diffstat:
Mdocs/admin.md | 4+++-
Mserver/admin_table.go | 57++++++++++++++++++++++++++++++++++++++-------------------
Mserver/admin_table_test.go | 11++++-------
Mserver/item_pages.go | 122+++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------
Mserver/item_pool_sources.go | 129++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------
Mserver/item_source_pages.go | 21+++++++++++++++------
Mserver/item_sources.go | 80++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------------
Mserver/item_sources_test.go | 36+++++++++++++++++++++++++++++++-----
Mserver/loot_distribution_test.go | 15++++++++-------
Mserver/state.go | 2++
10 files changed, 345 insertions(+), 132 deletions(-)

diff --git a/docs/admin.md b/docs/admin.md @@ -53,7 +53,9 @@ Item details show named catalog attributes at the instance's quality, decoded flags/capabilities and equipment slots. The Price field is a base value before shop modifiers; NoDrop items are identified as unsellable. Expand Source catalog record to inspect the original endpoint, serialized sections and provenance. -Top-level attribute names match the maintained catalog YAML. +Top-level attribute names match the maintained catalog YAML. Catalog detail +pages show up to 1,000 acquisition locations at a time. Previous and Next +change both the location links and the markers on the overview map. Same-zone map teleports and ordinary carried-item edits update connected players without reconnecting. Profile, equipment, backpack and bank changes, or inventory edits during an open shop/trade or equipment transition, reload the player. diff --git a/server/admin_table.go b/server/admin_table.go @@ -36,34 +36,51 @@ func adminFilter(w http.ResponseWriter, r *http.Request) { } func adminTable(w http.ResponseWriter, r *http.Request, columns []string, rows []adminTableRow) { - // Filter and sort the entire result set before selecting the page. query := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("q"))) - rows = slices.DeleteFunc(rows, func(row adminTableRow) bool { - return !strings.Contains(strings.ToLower(strings.Join(row.values, " ")), query) - }) + if query != "" { + rows = slices.DeleteFunc(rows, func(row adminTableRow) bool { + return !strings.Contains(strings.ToLower(strings.Join(row.values, " ")), query) + }) + } + renderAdminTable(w, r, columns, rows, func(row adminTableRow, col int) string { return row.values[col] }, + func(row adminTableRow) { fmt.Fprint(w, row.markup) }) +} + +func renderAdminTable[T any](w http.ResponseWriter, r *http.Request, columns []string, rows []T, value func(T, int) string, render func(T)) { + rowAt := func(i int) T { return rows[i] } column := slices.Index(columns, r.URL.Query().Get("sort")) descending := r.URL.Query().Get("dir") == "desc" if column >= 0 && columns[column] != "" && columns[column] != "Icon" && columns[column] != "Actions" { - // Decide the column type once so mixed text and numbers sort consistently. - numeric := len(rows) > 0 - for _, row := range rows { - if _, err := strconv.ParseFloat(row.values[column], 64); err != nil { - numeric = false - break + // Compute only the requested column, once per result. Sort the keys + // before selecting the page so off-page rows need no HTML. + type sortKey struct { + row T + text string + number float64 + } + keys := make([]sortKey, len(rows)) + numeric := true + for i, row := range rows { + text := value(row, column) + var number float64 + if numeric { + var err error + number, err = strconv.ParseFloat(text, 64) + numeric = err == nil } + keys[i] = sortKey{row, strings.ToLower(text), number} } - slices.SortStableFunc(rows, func(a, b adminTableRow) int { - order := strings.Compare(strings.ToLower(a.values[column]), strings.ToLower(b.values[column])) + slices.SortStableFunc(keys, func(a, b sortKey) int { + order := strings.Compare(a.text, b.text) if numeric { - left, _ := strconv.ParseFloat(a.values[column], 64) - right, _ := strconv.ParseFloat(b.values[column], 64) - order = cmp.Compare(left, right) + order = cmp.Compare(a.number, b.number) } if descending { return -order } return order }) + rowAt = func(i int) T { return keys[i].row } } start, end := adminPagination(w, r, len(rows)) fmt.Fprint(w, "<table><thead><tr>") @@ -88,8 +105,8 @@ func adminTable(w http.ResponseWriter, r *http.Request, columns []string, rows [ fmt.Fprintf(w, "<th aria-sort='%s'><a href='%s?%s'>%s%s</a></th>", state, html.EscapeString(strings.TrimPrefix(r.URL.Path, "/")), html.EscapeString(query.Encode()), html.EscapeString(name), indicator) } fmt.Fprint(w, "</tr></thead><tbody>") - for _, row := range rows[start:end] { - fmt.Fprint(w, row.markup) + for i := start; i < end; i++ { + render(rowAt(i)) } if len(rows) == 0 { fmt.Fprintf(w, "<tr><td colspan='%d'>No matches.</td></tr>", len(columns)) @@ -98,8 +115,10 @@ func adminTable(w http.ResponseWriter, r *http.Request, columns []string, rows [ adminPagination(w, r, len(rows)) } +const adminPageSize = 1000 + func adminPagination(w http.ResponseWriter, r *http.Request, total int) (int, int) { - pages := max(1, (total+999)/1000) + pages := max(1, (total+adminPageSize-1)/adminPageSize) page, _ := strconv.Atoi(r.FormValue("page")) page = max(1, min(page, pages)) fmt.Fprintf(w, "<p>%d matches. Page %d of %d. ", total, page, pages) @@ -114,5 +133,5 @@ func adminPagination(w http.ResponseWriter, r *http.Request, total int) (int, in } } fmt.Fprint(w, "</p>") - return (page - 1) * 1000, min(page*1000, total) + return (page - 1) * adminPageSize, min(page*adminPageSize, total) } diff --git a/server/admin_table_test.go b/server/admin_table_test.go @@ -3,7 +3,6 @@ package main import ( "ao/server/gamedata" "context" - "fmt" "net/http/httptest" "os" "os/exec" @@ -18,16 +17,14 @@ func newAdminListTestServer(t *testing.T) *server { t.Helper() world := newAdminTestServer(t) world.baseURL = "/share/test/" - for id := uint32(1); id <= 1002; id++ { - world.characters[id] = &character{id: id, name: fmt.Sprintf("Player %04d", id), playfield: 705} - } - world.characters[1002].name = "" - world.characters[1001].name = "<Alpha>" quality := uint32(1) gamedata.ItemTemplates[4000000000] = &gamedata.Item{ID: 4000000000, Quality: &quality} t.Cleanup(func() { delete(gamedata.ItemTemplates, 4000000000) }) if _, err := world.db.Exec(`WITH RECURSIVE n(id) AS (SELECT 1 UNION ALL SELECT id+1 FROM n WHERE id<1002) - INSERT INTO items(id,type,template,quality,count) SELECT id,0,4000000000,1,id FROM n`); err != nil { + INSERT INTO items(id,type,template,quality,count) SELECT id,0,4000000000,1,id FROM n; + INSERT INTO characters(id,name,playfield) + SELECT id,CASE id WHEN 1002 THEN '' WHEN 1001 THEN '<Alpha>' ELSE printf('Player %04d',id) END,705 FROM items; + INSERT INTO players(id) SELECT id FROM characters`); err != nil { t.Fatal(err) } return world diff --git a/server/item_pages.go b/server/item_pages.go @@ -115,36 +115,96 @@ func (server *server) itemsPage(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "</main></body></html>") } -func (server *server) itemCatalogPage(w http.ResponseWriter, r *http.Request) { - catalog := strings.ToLower(strings.TrimSpace(r.FormValue("catalog"))) - sources := server.itemSources() - sourceFilter := r.FormValue("source") - categoryFilter := r.FormValue("category") +// Keep the catalog order without copying the underlying item definitions. +func (index *itemCatalogIndex) buildRows() { categories := make(map[uint32]bool) - var matches []*gamedata.Item - for _, definition := range gamedata.ItemTemplates { - if definition.Quality != nil { - categories[itemStat(definition, 76)] = true - } - if definition.Quality != nil && (catalog == "" || strings.Contains(strings.ToLower(adminName(definition.Name)), catalog) || strconv.FormatUint(uint64(definition.ID), 10) == catalog) { - if categoryFilter != "" && categoryFilter != strconv.FormatUint(uint64(itemStat(definition, 76)), 10) { - continue - } - available := sources[itemFamily(definition.ID)] - buyable := slices.ContainsFunc(available, func(source itemSource) bool { return source.kind == "Shop" }) - lootable := slices.ContainsFunc(available, func(source itemSource) bool { return source.kind == "Loot" }) - if sourceFilter == "shops" && !buyable || sourceFilter == "no-shops" && buyable || sourceFilter == "loot" && !lootable || sourceFilter == "unknown" && len(available) != 0 { - continue - } - matches = append(matches, definition) + index.items = make([]*gamedata.Item, 0, len(gamedata.ItemTemplates)) + for _, item := range gamedata.ItemTemplates { + if item.Quality != nil { + categories[itemStat(item, 76)] = true + index.items = append(index.items, item) } } - slices.SortFunc(matches, func(a, b *gamedata.Item) int { + index.categories = slices.Sorted(maps.Keys(categories)) + slices.SortFunc(index.items, func(a, b *gamedata.Item) int { if a.Name != b.Name { return strings.Compare(a.Name, b.Name) } return cmp.Compare(a.ID, b.ID) }) +} + +func (index *itemCatalogIndex) columnValue(item *gamedata.Item, column int) string { + switch column { + case 1: + return adminName(item.Name) + case 2: + return strconv.FormatUint(uint64(item.ID), 10) + case 3: + return strconv.FormatUint(uint64(*item.Quality), 10) + case 4: + return itemSourceSummary(index.families[itemFamily(item.ID)]) + case 5, 6: + chances, basis := itemLootSummary(index.families[itemFamily(item.ID)]) + if column == 5 { + return chances + } + return basis + } + return "" +} + +func (index *itemCatalogIndex) matchingItems(catalog, sourceFilter, categoryFilter, query string) []*gamedata.Item { + if catalog == "" && sourceFilter == "" && categoryFilter == "" && query == "" { + return index.items + } + var matches []*gamedata.Item + for _, item := range index.items { + if catalog != "" && !strings.Contains(strings.ToLower(adminName(item.Name)), catalog) && index.columnValue(item, 2) != catalog { + continue + } + if categoryFilter != "" && categoryFilter != strconv.FormatUint(uint64(itemStat(item, 76)), 10) { + continue + } + if sourceFilter != "" { + sources := index.families[itemFamily(item.ID)] + switch sourceFilter { + case "shops", "no-shops": + shop := slices.ContainsFunc(sources, func(source *itemSource) bool { return source.shop != 0 }) + if shop != (sourceFilter == "shops") { + continue + } + case "loot": + if !slices.ContainsFunc(sources, func(source *itemSource) bool { return source.kind == "Loot" }) { + continue + } + case "unknown": + if len(sources) != 0 { + continue + } + } + } + if query != "" { + var cells [8]string + for col := range cells { + cells[col] = index.columnValue(item, col) + } + if !strings.Contains(strings.ToLower(strings.Join(cells[:], " ")), query) { + continue + } + } + matches = append(matches, item) + } + return matches +} + +func (server *server) itemCatalogPage(w http.ResponseWriter, r *http.Request) { + catalog := strings.ToLower(strings.TrimSpace(r.FormValue("catalog"))) + sourceFilter := r.FormValue("source") + categoryFilter := r.FormValue("category") + query := strings.ToLower(strings.TrimSpace(r.FormValue("q"))) + index := server.itemCatalog() + matches := index.matchingItems(catalog, sourceFilter, categoryFilter, query) // Filter before paging so every page refers to the same ordered result set. w.Header().Set("Content-Type", "text/html; charset=utf-8") @@ -160,7 +220,7 @@ func (server *server) itemCatalogPage(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "<option value='%s'%s>%s</option>", option.value, selected, option.label) } fmt.Fprint(w, "</select></label> <label>Category <select name='category'><option value=''>All</option>") - for _, category := range slices.Sorted(maps.Keys(categories)) { + for _, category := range index.categories { name := itemClassNames[category] if name == "" { name = fmt.Sprintf("Unknown class %d", category) @@ -173,17 +233,13 @@ func (server *server) itemCatalogPage(w http.ResponseWriter, r *http.Request) { } fmt.Fprint(w, "</select></label> <button>Filter</button> <a href='admin/items/catalog'>Clear filter</a></form>") fmt.Fprint(w, "<p>Loot chances are per independent roll at the sources listed on each item page. They apply to the offered QLs, not every QL in the family. No configured drop means no current server rule; it does not establish historical loot eligibility.</p>") - var entries []adminTableRow - for _, definition := range matches { - summary := itemSourceSummary(sources[itemFamily(definition.ID)]) - chances, basis := itemLootSummary(sources[itemFamily(definition.ID)]) - entries = append(entries, adminTableRow{ - values: []string{"", adminName(definition.Name), fmt.Sprint(definition.ID), fmt.Sprint(*definition.Quality), summary, chances, basis, ""}, - markup: fmt.Sprintf("<tr><td>%s</td><td>%s</td><td>%d</td><td>%d</td><td>%s</td><td>%s</td><td>%s</td><td><button name='template' value='%d'>Create</button></td></tr>", itemIcon(definition), catalogItemLink(definition.ID), definition.ID, *definition.Quality, html.EscapeString(summary), html.EscapeString(chances), html.EscapeString(basis), definition.ID), - }) - } fmt.Fprint(w, "<form method='post' action='admin/items'>") - adminTable(w, r, []string{"Icon", "Name", "Template", "QL", "Sources (family)", "Loot chances / roll", "Loot basis", "Actions"}, entries) + renderAdminTable(w, r, []string{"Icon", "Name", "Template", "QL", "Sources (family)", "Loot chances / roll", "Loot basis", "Actions"}, matches, + index.columnValue, func(definition *gamedata.Item) { + sources := index.families[itemFamily(definition.ID)] + chances, basis := itemLootSummary(sources) + fmt.Fprintf(w, "<tr><td>%s</td><td>%s</td><td>%d</td><td>%d</td><td>%s</td><td>%s</td><td>%s</td><td><button name='template' value='%d'>Create</button></td></tr>", itemIcon(definition), catalogItemLink(definition.ID), definition.ID, *definition.Quality, html.EscapeString(itemSourceSummary(sources)), html.EscapeString(chances), html.EscapeString(basis), definition.ID) + }) fmt.Fprint(w, "</form></main></body></html>") } diff --git a/server/item_pool_sources.go b/server/item_pool_sources.go @@ -4,16 +4,24 @@ import ( "ao/server/gamedata" "fmt" "maps" + "math" "slices" "strings" ) -func addTableLootSources(sources map[uint32][]itemSource, entrances map[uint32][]itemSourceLocation) { +func addTableLootSources(sources map[uint32][]*itemSource, entrances map[uint32][]itemSourceLocation) { // Coalesce shared pools across encounters. Per-item copies of every spawn // would make the catalog index much larger than the underlying world data. populations := make(map[gamedata.LootPoolRoll][]string) for _, key := range slices.Sorted(maps.Keys(gamedata.LootTables)) { table := gamedata.LootTables[key] + for _, roll := range table.Pools { + populations[roll] = append(populations[roll], table.Groups...) + } + if len(table.Drops) == 0 { + continue + } + var locations []itemSourceLocation levels := [2]uint16{65535, 0} for _, id := range table.Groups { @@ -24,14 +32,11 @@ func addTableLootSources(sources map[uint32][]itemSource, entrances map[uint32][ } } for _, drop := range table.Drops { - sources[itemFamily(drop.Template)] = append(sources[itemFamily(drop.Template)], itemSource{ + sources[itemFamily(drop.Template)] = append(sources[itemFamily(drop.Template)], &itemSource{ kind: "Loot", name: table.Name, quality: drop.Quality, chance: drop.Chance, evidence: drop.Evidence, inference: drop.Inference, level: levels, locations: locations, }) } - for _, roll := range table.Pools { - populations[roll] = append(populations[roll], table.Groups...) - } } rolls := slices.Collect(maps.Keys(populations)) slices.SortFunc(rolls, func(a, b gamedata.LootPoolRoll) int { @@ -49,38 +54,100 @@ func addTableLootSources(sources map[uint32][]itemSource, entrances map[uint32][ levels[level] = true } } - locations := make(map[[2]uint16][]itemSourceLocation) - for _, template := range pool.Items { - source := itemSource{kind: "Loot", name: fmt.Sprintf("%s pool (%d%% roll)", strings.ReplaceAll(roll.Pool, "_", " "), roll.Chance), - pool: roll.Pool, chance: roll.Chance, evidence: pool.Evidence, inference: pool.Inference, - level: [2]uint16{65535, 0}, quality: [2]uint32{65535, 0}, candidates: [2]int{len(pool.Items), 0}} - for level := range levels { - low, high := pool.Quality(template, level) - if low > high { - continue + // Reuse the eligible templates that gameplay already indexes by NPC level. + type eligibility struct { + level [2]uint16 + candidates [2]int + } + ranges := make(map[uint32]eligibility, len(pool.Items)) + for _, level := range slices.Sorted(maps.Keys(levels)) { + candidates := pool.Candidates[level] + for _, template := range candidates { + r, found := ranges[template] + if !found { + r.level[0], r.candidates[0] = level, len(candidates) } - source.level[0], source.level[1] = min(source.level[0], level), max(source.level[1], level) - source.quality[0], source.quality[1] = min(source.quality[0], low), max(source.quality[1], high) - count := len(pool.Candidates[level]) - source.candidates[0], source.candidates[1] = min(source.candidates[0], count), max(source.candidates[1], count) + r.level[1] = level + r.candidates[0] = min(r.candidates[0], len(candidates)) + r.candidates[1] = max(r.candidates[1], len(candidates)) + ranges[template] = r } - if source.level[0] > source.level[1] { + } + name := fmt.Sprintf("%s pool (%d%% roll)", strings.ReplaceAll(roll.Pool, "_", " "), roll.Chance) + type offer struct { + eligibility + quality [2]uint32 + } + offers := make(map[offer]*itemSource) + for _, template := range pool.Items { + r, found := ranges[template] + if !found { continue } - if _, exists := locations[source.level]; !exists { - for _, id := range populations[roll] { - group := gamedata.NPCGroups[id] - if group.Levels[0] > source.level[1] || group.Levels[1] < source.level[0] { - continue - } - for _, position := range group.Positions { - locations[source.level] = append(locations[source.level], itemSourceLocations(itemSourceLocation{ - fmt.Sprintf("%s (levels %d-%d)", group.Name, max(group.Levels[0], source.level[0]), min(group.Levels[1], source.level[1])), npcSourcePlayfield(id), position}, entrances)...) - } - } + // Both QL bounds are nondecreasing with NPC level. + low, _ := pool.Quality(template, r.level[0]) + _, high := pool.Quality(template, r.level[1]) + key := offer{r, [2]uint32{low, high}} + source := offers[key] + if source == nil { + source = &itemSource{kind: "Loot", name: name, groups: populations[roll], + pool: roll.Pool, chance: roll.Chance, evidence: pool.Evidence, inference: pool.Inference, + level: r.level, quality: key.quality, candidates: r.candidates} + offers[key] = source } - source.locations = locations[source.level] sources[itemFamily(template)] = append(sources[itemFamily(template)], source) } } } + +// Count all source locations, but materialize links and map markers only for +// the requested page. Some single pools cover tens of thousands of spawns. +func (index *itemCatalogIndex) sourcePage(template uint32, page int) ([]*itemSource, int) { + skip := min(max(1, page)-1, math.MaxInt/adminPageSize) * adminPageSize + remaining, total := adminPageSize, 0 + window := func(n int) (int, int) { + total += n + first := min(skip, n) + skip -= first + take := min(remaining, n-first) + remaining -= take + return first, first + take + } + + sources := slices.Clone(index.families[itemFamily(template)]) + for i, shared := range sources { + source := *shared + sources[i] = &source + first, end := window(len(shared.locations)) + source.locations = shared.locations[first:end:end] + for _, id := range source.groups { + group := gamedata.NPCGroups[id] + if group.Levels[0] > source.level[1] || group.Levels[1] < source.level[0] { + continue + } + playfield := npcSourcePlayfield(id) + doors := index.entrances[playfield] + first, end := window(len(group.Positions) * max(1, len(doors))) + if first == end { + continue + } + name := fmt.Sprintf("%s (levels %d-%d)", group.Name, max(group.Levels[0], source.level[0]), min(group.Levels[1], source.level[1])) + if len(doors) > 0 { + name += " - " + gamedata.Playfields[playfield].Name + " entrance" + } + for j := first; j < end; j++ { + if len(doors) == 0 { + source.locations = append(source.locations, itemSourceLocation{name, playfield, group.Positions[j]}) + } else { + door := doors[j%len(doors)] + door.name = name + source.locations = append(source.locations, door) + } + } + } + } + if last := max(1, (total+adminPageSize-1)/adminPageSize); page > last { + return index.sourcePage(template, last) + } + return sources, total +} diff --git a/server/item_source_pages.go b/server/item_source_pages.go @@ -20,7 +20,7 @@ type sourceMapLocation struct { Vending bool `json:"vending,omitempty"` } -func sourceOverview(w http.ResponseWriter, sources []itemSource) { +func sourceOverview(w http.ResponseWriter, sources []*itemSource) { // Plot each known overworld position once, regardless of source name or height. locations := make([]sourceMapLocation, 0) type mapPoint struct { @@ -62,7 +62,7 @@ func sourceOverview(w http.ResponseWriter, sources []itemSource) { fmt.Fprint(w, "<div data-world-map data-map-overview><p data-map-status>Loading maps...</p><p data-map-location></p><canvas data-map-canvas width='1000' height='480' style='height:240px;min-height:0' aria-label='Item source overworld overview'></canvas></div><script src='admin/control-map.js' defer></script></section>") } -func sourceMap(w http.ResponseWriter, sources []itemSource) { +func sourceMap(w http.ResponseWriter, sources []*itemSource) { locations := make([]sourceMapLocation, 0) seen := make(map[sourceMapLocation]bool) for _, source := range sources { @@ -97,9 +97,15 @@ func (server *server) itemTemplatePage(w http.ResponseWriter, r *http.Request) { http.NotFound(w, r) return } - sources := server.itemSources()[itemFamily(definition.ID)] + index := server.itemCatalog() + page, _ := strconv.Atoi(r.FormValue("page")) + sources, count := index.sourcePage(definition.ID, page) server.adminPageStart(w, adminName(definition.Name), "Items") - fmt.Fprintf(w, "<p><a href='admin/items/catalog'>Item catalog</a></p><h1>%s%s</h1><table><tr><th scope='row'>Description</th><td>%s</td></tr><tr><th scope='row'>Mapped sources (QL family)</th><td>%s</td></tr></table>", itemIcon(definition), html.EscapeString(adminName(definition.Name)), html.EscapeString(definition.Description), html.EscapeString(itemSourceSummary(sources))) + fmt.Fprintf(w, "<p><a href='admin/items/catalog'>Item catalog</a></p><h1>%s%s</h1><table><tr><th scope='row'>Description</th><td>%s</td></tr><tr><th scope='row'>Mapped sources (QL family)</th><td>%s</td></tr></table>", itemIcon(definition), html.EscapeString(adminName(definition.Name)), html.EscapeString(definition.Description), html.EscapeString(itemSourceSummary(index.families[itemFamily(definition.ID)]))) + if count > adminPageSize { + fmt.Fprint(w, "<h2>Source locations</h2><p>The map and location links show one page at a time.</p>") + adminPagination(w, r, count) + } sourceOverview(w, sources) fmt.Fprint(w, "<h2>Possible sources (QL family)</h2><table><tr><th>Type</th><th>Icon</th><th>Source</th><th>Offered QL</th><th>Details</th></tr>") for _, source := range sources { @@ -152,6 +158,9 @@ func (server *server) itemTemplatePage(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "</td></tr>") } fmt.Fprint(w, "</table>") + if count > adminPageSize { + adminPagination(w, r, count) + } itemCatalogProperties(w, ownedItem{Type: definition.HeaderWords[0], Template: definition.ID, Quality: *definition.Quality}, definition) fmt.Fprint(w, "</main></body></html>") } @@ -212,12 +221,12 @@ func (server *server) shopCatalogPage(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "<p><a href='admin/items/catalog'>Item catalog</a></p><h1>%s</h1><table><tr><th scope='row'>Shop template</th><td>%d</td></tr><tr><th scope='row'>Access</th><td>%s</td></tr>", itemIcon(definition)+html.EscapeString(adminName(definition.Name)), template, html.EscapeString(shopAccess(definition))) fmt.Fprint(w, "<tr><th scope='row'>Stock pool</th><td>Possible stock</td></tr><tr><th scope='row'>Always stocked</th><td>Supplies and QL 1-10 equipment</td></tr><tr><th scope='row'>Rotating stock</th><td>Higher-QL weapons and armor</td></tr><tr><th scope='row'>Rotation interval</th><td>30 minutes</td></tr><tr><th scope='row'>Inclusion chance per rotating row</th><td>75%</td></tr><tr><th scope='row'>QL variation</th><td>Up to 10% within supported range</td></tr><tr><th scope='row'>Open-trade stock and prices</th><td>Fixed</td></tr></table>") // Each catalog repeats its placements per item; one source supplies the map. - sources := server.itemSources() + sources := server.itemCatalog().families for _, family := range slices.Sorted(maps.Keys(sources)) { found := false for _, source := range sources[family] { if source.shop == uint32(template) { - sourceMap(w, []itemSource{source}) + sourceMap(w, []*itemSource{source}) found = true break } diff --git a/server/item_sources.go b/server/item_sources.go @@ -22,6 +22,7 @@ type itemSource struct { evidence string inference string level [2]uint16 + groups []string locations []itemSourceLocation } @@ -44,12 +45,24 @@ func npcSourcePlayfield(id string) uint32 { return uint32(value) } -// Build one family index per page, never scan all sources separately for each catalog row. -func (server *server) itemSources() map[uint32][]itemSource { - sources := make(map[uint32][]itemSource) +type itemCatalogIndex struct { + families map[uint32][]*itemSource + entrances map[uint32][]itemSourceLocation + items []*gamedata.Item + categories []uint32 +} + +// The embedded catalog, loot rules and zone links are immutable while the server runs. +func (server *server) itemCatalog() *itemCatalogIndex { + server.catalogOnce.Do(server.buildItemCatalog) + return &server.catalog +} + +func (server *server) buildItemCatalog() { + sources := make(map[uint32][]*itemSource) sellers := make(map[uint32][]itemSourceLocation) // Reverse authored doors so shared and nested interiors expose every entrance. - entrances := make(map[uint32][]itemSourceLocation) + incoming := make(map[uint32][]itemSourceLocation) for _, playfield := range slices.Sorted(maps.Keys(server.zoneLinks["target"])) { for _, door := range server.zoneLinks["target"][playfield].Doors { destination := door.Destination @@ -59,10 +72,16 @@ func (server *server) itemSources() map[uint32][]itemSource { destination = 120 } if destination != 0 && !door.Return { - entrances[destination] = append(entrances[destination], itemSourceLocation{"", playfield, door.Position}) + incoming[destination] = append(incoming[destination], itemSourceLocation{"", playfield, door.Position}) } } } + entrances := make(map[uint32][]itemSourceLocation) + for interior := range incoming { + if !gamedata.Playfields[interior].Outdoor { + entrances[interior] = outdoorEntrances(interior, incoming) + } + } addTableLootSources(sources, entrances) for _, id := range slices.Sorted(maps.Keys(gamedata.ShopMachines)) { machine := gamedata.ShopMachines[id] @@ -84,7 +103,7 @@ func (server *server) itemSources() map[uint32][]itemSource { family, chance uint32 evidence, inference string } - drops := make(map[dropKey]itemSource) + drops := make(map[dropKey]*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) { @@ -99,7 +118,7 @@ func (server *server) itemSources() map[uint32][]itemSource { key := dropKey{family, drop.Chance, drop.Evidence, drop.Inference} source, exists := drops[key] if !exists { - source = itemSource{kind: "Loot", name: group.Name + " (" + id + ")", quality: drop.Quality, chance: drop.Chance, evidence: drop.Evidence, inference: drop.Inference, level: [2]uint16{level, level}} + source = &itemSource{kind: "Loot", name: group.Name + " (" + id + ")", quality: drop.Quality, chance: drop.Chance, evidence: drop.Evidence, inference: drop.Inference, level: [2]uint16{level, level}} for _, position := range group.Positions { source.locations = append(source.locations, itemSourceLocations(itemSourceLocation{group.Name, npcSourcePlayfield(id), position}, entrances)...) } @@ -120,7 +139,7 @@ func (server *server) itemSources() map[uint32][]itemSource { } 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)}} + 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, itemSourceLocations(itemSourceLocation{group.Name, npcSourcePlayfield(id), position}, entrances)...) } @@ -128,10 +147,18 @@ func (server *server) itemSources() map[uint32][]itemSource { } } for _, template := range slices.Sorted(maps.Keys(sellers)) { + // A vendor offers many templates at the same QL and locations. + offers := make(map[[2]uint32]*itemSource) for _, entry := range gamedata.ShopStock[template] { low, high := shopQualityRange(entry) + quality := [2]uint32{low, high} + source := offers[quality] + if source == nil { + source = &itemSource{kind: "Shop", name: gamedata.ItemTemplates[template].Name, shop: template, quality: quality, locations: sellers[template]} + offers[quality] = source + } 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]}) + sources[family] = append(sources[family], source) } } // Recipes, mission rewards/objectives and issued equipment are also acquisition paths. @@ -139,7 +166,7 @@ func (server *server) itemSources() map[uint32][]itemSource { 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}}) + 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)) { @@ -154,7 +181,7 @@ func (server *server) itemSources() map[uint32][]itemSource { 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}}}) + 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) @@ -166,21 +193,32 @@ func (server *server) itemSources() map[uint32][]itemSource { } 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}}) + 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 + server.catalog.families = sources + server.catalog.entrances = entrances + server.catalog.buildRows() } func itemSourceLocations(location itemSourceLocation, entrances map[uint32][]itemSourceLocation) []itemSourceLocation { - if gamedata.Playfields[location.playfield].Outdoor { + doors := entrances[location.playfield] + if len(doors) == 0 { return []itemSourceLocation{location} } + locations := slices.Clone(doors) + name := location.name + " - " + gamedata.Playfields[location.playfield].Name + " entrance" + for i := range locations { + locations[i].name = name + } + return locations +} +func outdoorEntrances(interior uint32, incoming map[uint32][]itemSourceLocation) []itemSourceLocation { // Walk outward through nested interiors, stopping at outdoor doors. var locations []itemSourceLocation - pending := []uint32{location.playfield} + pending := []uint32{interior} visited := make(map[uint32]bool) for len(pending) != 0 { playfield := pending[0] @@ -189,22 +227,18 @@ func itemSourceLocations(location itemSourceLocation, entrances map[uint32][]ite continue } visited[playfield] = true - for _, entrance := range entrances[playfield] { + for _, entrance := range incoming[playfield] { if gamedata.Playfields[entrance.playfield].Outdoor { - entrance.name = location.name + " - " + gamedata.Playfields[location.playfield].Name + " entrance" locations = append(locations, entrance) } else { pending = append(pending, entrance.playfield) } } } - if len(locations) == 0 { - return []itemSourceLocation{location} - } return locations } -func itemSourceSummary(sources []itemSource) string { +func itemSourceSummary(sources []*itemSource) string { shops := make(map[uint32]int) loot := make(map[string]bool) other := make(map[string]bool) @@ -235,7 +269,7 @@ func itemSourceSummary(sources []itemSource) string { return strings.Join(parts, "; ") } -func itemLootSummary(sources []itemSource) (string, string) { +func itemLootSummary(sources []*itemSource) (string, string) { chances := make(map[string]bool) basis := make(map[string]bool) for _, source := range sources { @@ -261,7 +295,7 @@ func itemLootSummary(sources []itemSource) (string, string) { return strings.Join(rates, ", "), strings.Join(slices.Sorted(maps.Keys(basis)), ", ") } -func itemLootChance(source itemSource) string { +func itemLootChance(source *itemSource) string { if source.pool == "" { return fmt.Sprintf("%d%%", source.chance) } diff --git a/server/item_sources_test.go b/server/item_sources_test.go @@ -19,22 +19,22 @@ import ( ) func TestItemSourcesIncludeShopsLootCraftingAndStarterFamilies(t *testing.T) { - sources := newTestServer(t).itemSources() + sources := newTestServer(t).itemCatalog().families armor := sources[itemFamily(85595)] - if !slices.ContainsFunc(armor, func(source itemSource) bool { + 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 { + 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" }) { + 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" }) { + if !slices.ContainsFunc(sources[itemFamily(121567)], func(source *itemSource) bool { return source.kind == "Starter equipment" }) { t.Fatal("starter pistol lost its issuance source") } } @@ -256,3 +256,29 @@ func TestItemSourceMapBrowser(t *testing.T) { } t.Log(string(output)) } + +func TestItemSourceLocationsArePagedWithoutChangingTheCachedCatalog(t *testing.T) { + handler := adminTestHandler(newTestServer(t)) + path := "/admin/items/catalog/42640" + first := adminRequest(handler, "GET", path, "", nil) + second := adminRequest(handler, "GET", path+"?page=2", "", nil) + last := adminRequest(handler, "GET", path+"?page=999999", "", nil) + reopened := adminRequest(handler, "GET", path, "", nil) + + const link = "<li><a href='admin/map?playfield=" + for _, response := range []*httptest.ResponseRecorder{first, second} { + if response.Code != 200 || strings.Count(response.Body.String(), link) != 1000 { + t.Fatal("expected one page of acquisition locations", response.Code) + } + } + if !strings.Contains(first.Body.String(), "?page=2'>Next") || !strings.Contains(second.Body.String(), "?page=1'>Previous") || + !strings.Contains(last.Body.String(), ">Previous</a>") || strings.Contains(last.Body.String(), ">Next</a>") { + t.Fatal("source location navigation does not reach the final page") + } + if count := strings.Count(last.Body.String(), link); count == 0 || count > 1000 { + t.Fatal("invalid number of locations on the final page", count) + } + if !bytes.Equal(first.Body.Bytes(), reopened.Body.Bytes()) { + t.Fatal("browsing another page changed the cached source locations") + } +} diff --git a/server/loot_distribution_test.go b/server/loot_distribution_test.go @@ -93,29 +93,30 @@ func TestDistributedLootFailureDoesNotCommitDeath(t *testing.T) { func TestDistributedCatalogShowsItemOddsAndNamedLocations(t *testing.T) { world := newTestServer(t) - sources := world.itemSources() - source := slices.IndexFunc(sources[147073], func(s itemSource) bool { return s.pool == "instruction_discs" && s.chance == 15 }) + sources := world.itemCatalog().families + disc, _ := world.itemCatalog().sourcePage(147073, 1) + source := slices.IndexFunc(disc, func(s *itemSource) bool { return s.pool == "instruction_discs" && s.chance == 15 }) if source < 0 { t.Fatal("CellAO disc is not indexed") } - got := sources[147073][source] + got := disc[source] if got.candidates[0] <= 1 || got.candidates[1] < got.candidates[0] || itemLootChance(got) == "15%" || len(got.locations) == 0 { t.Fatal("pool chance misrepresented as per-item chance", got) } - if itemLootChance(itemSource{chance: 20, pool: "test", candidates: [2]int{4, 10}}) != "2-5%" { + if itemLootChance(&itemSource{chance: 20, pool: "test", candidates: [2]int{4, 10}}) != "2-5%" { t.Fatal("wrong pool probability range") } - if !slices.ContainsFunc(sources[204748], func(s itemSource) bool { + if !slices.ContainsFunc(sources[204748], func(s *itemSource) bool { return strings.Contains(s.name, "Guardian of Tomorrow") && s.chance == 25 && s.locations[0].playfield == 1931 }) { t.Fatal("documented Temple drop lost") } - if !slices.ContainsFunc(sources[157856], func(s itemSource) bool { + if !slices.ContainsFunc(sources[157856], func(s *itemSource) bool { return strings.Contains(s.name, "Tarasque") && s.locations[0].playfield == 505 && strings.Contains(s.locations[0].name, "Camelot entrance") }) { t.Fatal("Tarasque reward does not link to the Camelot entrance") } - if !slices.ContainsFunc(sources[158601], func(s itemSource) bool { + if !slices.ContainsFunc(sources[158601], func(s *itemSource) bool { return strings.Contains(s.name, "Tarasque") && strings.Contains(s.evidence, "item 158601 description") && s.locations[0].playfield == 505 && strings.Contains(s.locations[0].name, "Camelot entrance") }) { t.Fatal("original description's Gall Stone source lost") diff --git a/server/state.go b/server/state.go @@ -143,6 +143,8 @@ type server struct { populationLoaded bool npcOwners map[uint32]uint32 worldServices + catalogOnce sync.Once + catalog itemCatalogIndex browserStreamsOnce sync.Once browserStreamService *browserStreamRegistry