Module:Township: Difference between revisions

From Melvor Idle
No edit summary
(Add Soul Storage into list of building modifiers to check for; Removed getSeasonTable (this is now a manual table); Reduced icon size from 50px to 25px)
 
(78 intermediate revisions by 5 users not shown)
Line 1: Line 1:
local Shared = require('Module:Shared')
local Shared = require('Module:Shared')
local Icons = require('Module:Icons')
local Icons = require('Module:Icons')
local Items = require('Module:Items')
local Monsters = require('Module:Monsters')
local Shop = require('Module:Shop')
local GameData = require('Module:GameData')
local GameData = require('Module:GameData')
local Modifiers = require('Module:Modifiers')
local Num = require('Module:Number')


-- Data Module
local p = {}
local DataDemo = require('Module:GauTest/DataDemo')
local DataFull = require('Module:GauTest/DataFull')
local DataTotH = require('Module:GauTest/DataTotH')


local Namespaces = {
local Township = GameData.getSkillData('melvorD:Township')
melvorD = DataDemo,
p.Township = Township
melvorF = DataFull,
melvorTotH = DataTotH
}


local Data = {}
-- Gets a Township building by ID, e.g. melvorF:Hunters_Cabin
function p._getBuildingByID(id)
-- Check for the special statue case
if id == 'melvorF:Statues' then
local building = Shared.clone(GameData.getEntityByID(Township.buildings, id))
building.name = 'Statue of Worship'
return building
else
return GameData.getEntityByID(Township.buildings, id)
end
end


-- Gets a Township building by name, e.g. Hunters Cabin
function p._getBuildingByName(name)
-- Check for the special statue case
if name == 'Statues' then
name = 'Statue of Worship'
end
local STATUE_OF = 'Statue of '
if string.sub(name, 1, string.len(STATUE_OF)) == STATUE_OF then
local building = Shared.clone(GameData.getEntityByID(Township.buildings, 'melvorF:Statues'))
building.name = name
return building
else
return GameData.getEntityByName(Township.buildings, name)
end
end


-- For a table that is indexed but uses a key, use this function to find the correct element
-- Gets a resource from id
function Data.tableMatch(tabl, property, value)
function p._getResourceByID(id)
for _, elem in ipairs(tabl) do
return GameData.getEntityByID(Township.resources, id)
if elem[property] == value then
end
return elem
 
-- Given a building, find the next building upgrade
function p._getBuildingUpgrade(building)
local function checkFunc(entity)
return entity.upgradesFrom ~= nil and entity.upgradesFrom == building.id
end
local upgradesTo = GameData.getEntities(Township.buildings, checkFunc)
if #upgradesTo > 0 then
return upgradesTo[1]
end
return nil
end
 
-- Given a building, find the building's downgrade
function p._getBuildingDowngrade(building)
if building.upgradesFrom ~= nil then
return p._getBuildingByID(building.upgradesFrom)
end
return nil
end
 
-- Given a building and biome ID, returns the cost of constructing the building
-- within that biome as a human readable text string. Returns nil if the building
-- cannot be built within that biome.
function p._getBuildingCostText(building, biomeID, delimiter)
-- Basic validation of inputs
if type(building) == 'table' and building.cost ~= nil and biomeID ~= nil then
local delim = delimiter
if delim == nil then
delim = ', '
end
for i, costDef in ipairs(building.cost) do
if costDef.biomeID == biomeID then
local resultPart = {}
for j, cost in ipairs(costDef.cost) do
local resData = p._getResourceByID(cost.id)
if resData ~= nil then
table.insert(resultPart, Icons.Icon({resData.name, type='resource', notext=true, nolink=true, qty=cost.quantity}))
end
end
return table.concat(resultPart, delim)
end
end
end
end
end
return nil
end
end


-- For a table that is indexed but uses a key, use this function to find the correct element, when there are several duplicates elements
-- Given a building, groups biomes for which that building has a common cost
function Data.tableMatches(tabl, property, value)
function p._getBuildingGroupedCosts(building)
local matches = {}
local biomeGroups = {}
for _, elem in ipairs(tabl) do
for i, biomeID in ipairs(building.biomes) do
if elem[property] == value then
local currentBiomeCost = p._getBuildingCostText(building, biomeID)
table.insert(matches, elem)
local found = false
for j, biomeGroup in ipairs(biomeGroups) do
if biomeGroup.cost == currentBiomeCost then
-- Another biome exists with this cost
table.insert(biomeGroup.biomeIDs, biomeID)
found = true
break
end
end
if not found then
table.insert(biomeGroups, { biomeIDs = { biomeID }, cost = currentBiomeCost})
end
end
end
end
return matches
return biomeGroups
end
end


-- Separates the namespace and id of a string
-- Given a building, returns a text string repesenting the building costs for all biomes
-- e.g. 'melvorD:Coal_Ore' will return {namespace='melvorD', id='Coal_Ore'}
function p._getBuildingGroupedCostText(building)
-- e.g. 'Coal_Ore' will return {namespace=nil, id='Coal_Ore'}
local resultPart = {}
function Data.splitID(text)
local biomeGroups = p._getBuildingGroupedCosts(building)
local split = Shared.splitString(text, ':')
if Shared.tableCount(biomeGroups) == 1 then
local target_namespace = nil
-- If only one entry then simply output the cost
local target_id = nil
table.insert(resultPart, biomeGroups[1].cost)
if #split == 2 then
return {namespace=split[1], id=split[2]}
elseif #split == 1 then
return {id=split[1]}
else
else
return nil
-- Otherwise, split by biome group
for i, biomeGroup in ipairs(biomeGroups) do
local biomeText = {}
for j, biomeID in ipairs(biomeGroup.biomeIDs) do
local biome = GameData.getEntityByID(Township.biomes, biomeID)
table.insert(biomeText, Icons.Icon({biome.name, type='biome', notext=true, nolink=true, alt=biome.name}))
end
table.insert(resultPart, table.concat(biomeText, ', ') .. ': ' .. biomeGroup.cost)
end
end
end
return table.concat(resultPart, '<br/>')
end
end


-- Returns the namespace name (eventually we should use an icon?)
-- Given a building and biome ID, returns a string displaying the building's benefits,
function Data.PLACEHOLDER_NAMESPACE_ICON(namespace)
-- or nil if no benefits
local namespaces = {
function p._getBuildingBenefitText(building, biomeID, includeModifiers, delimiter)
melvorD = 'Demo',
-- Basic validation of inputs
melvorF = 'Full',
if type(building) == 'table' and building.provides ~= nil and biomeID ~= nil then
melvorTotH = 'TotH'
local delim = delimiter
}
if delim == nil then
return namespaces[namespace]
delim = ', '
end
local includeMods = includeModifiers
if includeMods == nil then
includeMods = false
end
 
local providesData = nil
for i, provides in ipairs(building.provides) do
if provides.biomeID == biomeID then
providesData = provides
break
end
end
 
if providesData ~= nil then
local resultPart = {}
local stats = {
population = 'Population',
happiness = 'Happiness',
education = 'Education',
storage = 'Storage',
soulStorage = 'Soul Storage',
worship = 'Worship',
fortification = 'Fortification'
}
local resourceText = function(resName, resType, quantity)
local elemClass = (quantity < 0 and 'text-negative') or 'text-positive'
local resIcon = Icons.Icon({resName, type=resType, notext=true})
return resIcon .. '&nbsp;<span class="' .. elemClass .. '">' .. Num.numStrWithSign(quantity) .. '</span>'
end
 
-- Resources
if providesData.resources ~= nil then
for i, resource in ipairs(providesData.resources) do
local resData = p._getResourceByID(resource.id)
if resData ~= nil and resource.quantity ~= 0 then
table.insert(resultPart, resourceText(resData.name, 'resource', resource.quantity))
end
end
end
 
-- Other stats
for key, stat in pairs(stats) do
local quantity = providesData[key]
if quantity ~= nil and quantity ~= 0 then
table.insert(resultPart, resourceText(stat, 'township', quantity))
end
end
 
-- Modifiers
if includeMods and building.modifiers ~= nil then
table.insert(resultPart, Modifiers.getModifiersText(building.modifiers))
end
 
if not Shared.tableIsEmpty(resultPart) then
return table.concat(resultPart, delim)
end
end
end
end
end


Data.Item = {}
-- Given a building, groups biomes for which that building has a common benefit/provides
function p._getBuildingGroupedBenefits(building, includeModifiers)
if includeModifiers == nil then
includeModifiers = true
end
local biomeGroups = {}
for i, biomeID in ipairs(building.biomes) do
local currentBiomeBenefit = p._getBuildingBenefitText(building, biomeID, includeModifiers)
local found = false
for j, biomeGroup in ipairs(biomeGroups) do
if biomeGroup.benefit == currentBiomeBenefit then
-- Another biome exists with this cost
table.insert(biomeGroup.biomeIDs, biomeID)
found = true
break
end
end
if not found then
table.insert(biomeGroups, { biomeIDs = { biomeID }, cost = currentBiomeBenefit})
end
end
return biomeGroups
end


-- Get all the items with a property equal to value
-- Given a building, returns a text string repesenting the building benefits for all biomes
function Data.Item.Match(property, value)
function p._getBuildingGroupedBenefitText(building, includeModifiers)
local items = {}
if includeModifiers == nil then
for namespace, data in pairs(Namespaces) do
includeModifiers = true
for k, item in pairs(data.data.items) do
end
if item[property] == value then
local resultPart = {}
local itemcopy = Shared.clone(item)
local biomeGroups = p._getBuildingGroupedBenefits(building, includeModifiers)
itemcopy._namespace = namespace
if Shared.tableCount(biomeGroups) == 1 then
table.insert(items, itemcopy)
-- If only one entry then simply output the cost
table.insert(resultPart, biomeGroups[1].cost)
else
-- Otherwise, split by biome group
for i, biomeGroup in ipairs(biomeGroups) do
local biomeText = {}
for j, biomeID in ipairs(biomeGroup.biomeIDs) do
local biome = GameData.getEntityByID(Township.biomes, biomeID)
table.insert(biomeText, Icons.Icon({biome.name, type='biome', notext=true, nolink=true, alt=biome.name}))
end
end
table.insert(resultPart, table.concat(biomeText, ', ') .. ': ' .. biomeGroup.cost)
end
end
return table.concat(resultPart, '<br/>')
end
-- Returns a sorted list of all Township buildings
function p._sortedBuildings(keepUnsorted)
local ku = true
if keepUnsorted ~= nil then
ku = keepUnsorted
end
return GameData.sortByOrderTable(Township.buildings, Township.buildingDisplayOrder, ku)
end
-- Gets the Township level or abyssalLevel, population and fortification requirements for a tier
-- Returns {population=X, level=X} for non-abyssal tiers
-- Returns {population=X, abyssalLevel=X, fortification=X} for abyssal tiers
function p._getTierRequirements(tier, abyssalTier)
local tierData = Township.populationForTier[tier]
if abyssalTier ~= nil then
local abyssalTierData = Shared.clone(Township.abyssalTierRequirements[abyssalTier + 1])
abyssalTierData.population = tierData.population
return abyssalTierData
else
return tierData
end
end
-- Returns a string containing the Township level and population requirements for a tier
function p._getTierText(tier, abyssalTier)
local realmID = (abyssalTier ~= nil and 'melvorItA:Abyssal' or 'melvorD:Melvor')
local tierData = p._getTierRequirements(tier, abyssalTier)
if tierData ~= nil then
local tierText = Icons._SkillReq('Township', tierData.abyssalLevel or tierData.level, false, realmID)
if tierData.population ~= nil and tierData.population > 0 then
tierText = tierText .. '<br/>' .. Icons.Icon({'Population', type='township', notext=true}) .. '&nbsp;' .. Num.formatnum(tierData.population)
end
end
if tierData.fortification ~= nil and tierData.fortification > 0 then
tierText = tierText .. '<br/>' .. Icons.Icon({'Fortification', type='township', notext=true}) .. '&nbsp;' .. Num.formatnum(tierData.fortification) .. '%'
end
return tierText
end
end
return items
end
end


-- Get item by id
function p.getBuildings(checkFunc)
function Data.Item.ByID(id)
local result = {}
local target = Data.splitID(id)
for i, building in pairs(p.Township.buildings) do
for namespace, data in pairs(Namespaces) do
if checkFunc(building) then
if target.namespace == nil or namespace == target.namespace then
table.insert(result, building)
for k, item in pairs(data.data.items) do
end
if item.id == target.id then
end
local itemcopy = Shared.clone(item)
return result
itemcopy._namespace = namespace
end
return itemcopy
 
end
function p.getSeasons(checkFunc)
end
local result = {}
for i, season in pairs(p.Township.seasons) do
if checkFunc(season) then
table.insert(result, season)
end
end
return result
end
 
function p.getWorships(checkFunc)
local result = {}
for i, worship in pairs(p.Township.worships) do
if checkFunc(worship) then
table.insert(result, worship)
end
end
end
end
return nil
return result
end
 
-- Generates a table listing all biomes and their associated requirements
function p.getBiomeTable(frame)
local resultPart = {}
table.insert(resultPart, '{| class="wikitable sortable stickyHeader"')
table.insert(resultPart, '\n|- class="headerRow-0"')
table.insert(resultPart, '\n!rowspan="2" colspan="2"| Biome\n!colspan="3"| Requirements')
table.insert(resultPart, '\n|- class="headerRow-1"')
table.insert(resultPart, '\n! ' .. Icons.Icon({'Township', 'Level', type='skill', nolink=true}))
table.insert(resultPart, '\n! ' .. Icons.Icon({'Township', 'Population', img='Population', type='township', section='Population' }))
table.insert(resultPart, '\n! ' .. Icons.Icon({'Township', 'Forification', img='Fortification', type='township', section='Fortification' }))
 
for i, biome in ipairs(Township.biomes) do
local reqs = p._getTierRequirements(biome.tier, biome.abyssalTier)
local fortification = reqs.fortification or 0
table.insert(resultPart, '\n|-\n|class="table-img"| ' .. Icons.Icon({biome.name, type='biome', nolink=true, notext=true}))
table.insert(resultPart, '\n| ' .. biome.name)
table.insert(resultPart, '\n|style="text-align:right"| ' .. (reqs.abyssalLevel or reqs.level))
table.insert(resultPart, '\n|style="text-align:right" data-sort-value="' .. reqs.population .. '"| ' .. Num.formatnum(reqs.population))
table.insert(resultPart, '\n|style="text-align:right" data-sort-value="' .. fortification .. '"| ' .. Num.formatnum(fortification))
end
table.insert(resultPart, '\n|}')
 
return table.concat(resultPart)
end
end


-- Returns the recipe for the item of a desired skill.
-- Generates a table showing which buildings can be built in which biomes
function Data.Item.FindRecipes(itemid, skill)
-- Skips upgraded buildings
-- the key name for each skill in the json file
function p.getBuildingBiomeTable(frame)
local skill_recipe_keys = {
local tbl = mw.html.create('table')
Woodcutting = {recipes='trees', productID='productId'}, -- lowercase "d"
:addClass('wikitable sortable stickyHeader')
Fishing = {recipes='fish', productID='productId'}, -- lowercase "d"
:css('text-align', 'center')
Cooking = {recipes='recipes', productID='productID'},
 
Mining = {recipes='rockData', productID='productId'}, -- lowercase "d"
local header = mw.html.create('tr'):addClass('headerRow-0')
Smithing = {recipes='recipes', productID='productID'},
local level = mw.html.create('tr'):addClass('sorttop')
Farming = {recipes='recipes', productID='productId'}, -- lowercase "d"
local pop = mw.html.create('tr'):addClass('sorttop')
Summoning = {recipes='recipes', productID='productID'},
local fort = mw.html.create('tr'):addClass('sorttop')
Fletching = {recipes='recipes', productID='productID'},
Crafting = {recipes='recipes', productID='productID'},
Runecrafting = {recipes='recipes', productID='productID'},
Herblore = {recipes='recipes', productID='potionIDs'} -- Special case potions I-IV
--[[ Excluded skills:
Attack, Strength, Defence, Magic, Ranged, Prayer, Slayer
Thieving, Agility, Astrology, Firemaking, Township (not items)]]
}


local item = Data.splitID(itemid)
header:tag('th')
local results = {}
:css('z-index', '2')
:wikitext('Building')
level:tag('th')
:wikitext(Icons.Icon({'Township', 'Level', type='skill', nolink=true}))
pop:tag('th')
:wikitext(Icons.Icon({'Township', 'Population', img='Population', type='township', section='Population' }))
fort:tag('th')
:wikitext(Icons.Icon({'Township', 'Fortification', img='Fortification', type='township', section='Fortification' }))
for _, biome in ipairs(Township.biomes) do
local reqs = p._getTierRequirements(biome.tier, biome.abyssalTier)
header:tag('th')
:wikitext(Icons.Icon({biome.name, type='biome', notext=true, nolink=true}).. '<br/>' .. biome.name)
level:tag('td')
:wikitext(Num.formatnum((reqs.abyssalLevel or reqs.level)))
pop:tag('td')
:wikitext(Num.formatnum(reqs.population))
fort:tag('td')
:wikitext(Num.formatnum((reqs.fortification or 0)))
end
-- Find the recipe at data.data.skillData -> SKILL.data.KEY
tbl:node(header)
for namespace, data in pairs(Namespaces) do
tbl:node(level)
-- We match multiple entries because there's a bug - melvorF -> skillData Farming has two duplicate entries in the array with differing info
tbl:node(pop)
local Skill_matches = Data.tableMatches(data.data.skillData, 'skillID', 'melvorD:'..skill)
tbl:node(fort)
for _, Skill in ipairs(Skill_matches) do
 
local key = skill_recipe_keys[skill]
for _, _building in ipairs(p._sortedBuildings(false)) do
if Skill ~= nil and Skill.data ~= nil and Skill.data[key.recipes] ~= nil then
-- Fix melvorF:Statues
for _, recipe in ipairs(Skill.data[key.recipes]) do
local building = p._getBuildingByID(_building.id)
-- Check if id matches
-- Skip upgraded buildings
if skill == 'Herblore' then
if p._getBuildingDowngrade(building) == nil then
-- Iterate over the 4 potion tiers
-- Populate the biome habitability data
for _, potion in ipairs(recipe[key.productID]) do
local buildingBiomes = {}
-- Same as below
-- Set all valid biomes to true
local recipe_id = Data.splitID(potion)
for _, biomeid in ipairs(building.biomes) do
if item.id == recipe_id.id then
buildingBiomes[biomeid] = true
local recipecopy = Shared.clone(recipe)
end
recipecopy._namespace = namespace
 
table.insert(results, recipecopy)
local trow = tbl:tag('tr')
end
trow:tag('th')
end
:css('text-align', 'left')
else
:attr('data-sort-value', building.name)
-- Same as above
:wikitext(Icons.Icon({building.name, type='building'}))
local recipe_id = Data.splitID(recipe[key.productID])
 
if item.id == recipe_id.id then
for _, biome in ipairs(Township.biomes) do
local recipecopy = Shared.clone(recipe)
if buildingBiomes[biome.id] then
recipecopy._namespace = namespace
trow:tag('td')
table.insert(results, recipecopy)
:addClass('table-positive')
end
:wikitext('✓')
end
else
trow:tag('td')
end
end
end
end
end
end
end
end
return results
 
return tostring(tbl)
end
end


Data.Township = {}
-- Generates a table contaning each building plus their relevant information
-- Returns a list of all the Township resources
function p.getBuildingTable(frame)
function Data.Township.Resources()
local resultPart = {}
 
-- Get a sorted list of all the resources
-- Change structure of biomes data for ease of use later
local Township = GameData.getSkillData('melvorD:Township')
local biomesByID = {}
local resources = GameData.sortByOrderTable(Township.resources, Township.resourceDisplayOrder[1].ids)
for i, biome in ipairs(Township.biomes) do
resources = Shared.clone(resources)
biomesByID[biome.id] = biome
-- Append the icon reference to each resource
-- From https://melvoridle.com/assets/data/melvorFull.json -> data.skillData -> Township.data.resources.media
local resource_icons = {
['melvorF:GP'] = {'Coins'},
['melvorF:Food'] = {'Raw Beef', type='item'},
['melvorF:Wood'] = {'Wood', type='resource'},
['melvorF:Stone'] = {'Stone', type='resource'},
['melvorF:Ore'] = {'Iron Ore', type='rock'},
['melvorF:Coal'] = {'Coal', type='resource'},
['melvorF:Bar'] = {'Iron Bar', type='item'},
['melvorF:Herbs'] = {'Garum Herb', type='item'},
['melvorF:Rune_Essence'] = {'Rune Essence', type='item'},
['melvorF:Leather'] = {'Leather', type='item'},
['melvorF:Potions'] = {'Potion', type='resource'},
['melvorF:Planks'] = {'Planks', type='resource'},
['melvorF:Clothing'] = {'Leather Body', type='item'}
}
for _, resource in ipairs(resources) do
resource._icon = resource_icons[resource.id]
resource._icon.notext = true
resource._icon.nolink = true
end
end


return resources
-- Generate table header
end
table.insert(resultPart, '{| class="wikitable sortable stickyHeader"')
table.insert(resultPart, '\n|- class="headerRow-0"')
table.insert(resultPart, '\n!colspan="2"|Building\n!Requirements\n!Max Built')
table.insert(resultPart, '\n!Biomes\n!Cost\n!Provides')
 
local buildings = p._sortedBuildings(false)


-- Returns a list of all the Township resources along with the Trader's trade ratios
for i, building in ipairs(buildings) do
function Data.Township.Trader()
-- Number of rows per building is dictated by number of biomes
-- Get the list of resources
local buildingName = (building.id == 'melvorF:Statues' and 'Statue of Worship') or building.name
local resources = Data.Township.Resources()
local firstRow = true
local rowCount = Shared.tableCount(building.biomes)
-- Get the list of convertable items, and calculate the exchange rate
local rowSpan = (rowCount > 1 and ' rowspan="' .. rowCount .. '"') or ''
-- Also inserts the resource's assocaited skill
local rowSpanOnly = (rowCount > 1 and '|' .. rowSpan) or ''
-- See TownshipResource.buildResourceItemConversions for the list of valid items
for j, biomeID in ipairs(building.biomes) do
for _, resource in ipairs(resources) do
local biome = biomesByID[biomeID]
resource.itemConversions = {}
if firstRow then
if resource.id == 'melvorF:GP' then
table.insert(resultPart, '\n|-')
-- No conversions
table.insert(resultPart, '\n|class="table-img"' .. rowSpan .. '| ' .. Icons.Icon({buildingName, type='building', notext=true}))
elseif resource.id == 'melvorF:Food' then
table.insert(resultPart, '\n' .. rowSpanOnly .. '| ' .. Icons.getExpansionIcon(building.id) .. Icons.Icon({buildingName, type='building', noicon=true}))
resource._skill = 'Cooking'
table.insert(resultPart, '\n|' .. 'data-sort-value="' .. building.tier .. '"' .. rowSpan .. '| ' .. (p._getTierText(building.tier, building.abyssalTier) or ''))
for _, food in ipairs(Data.Item.Match('type', 'Food')) do
table.insert(resultPart, '\n|style="text-align:right"' .. rowSpan .. '| ' .. building.maxUpgrades)
if (not string.match(food.id, '_Perfect')) and food.category ~= 'Farming' and (not food.ignoreCompletion) then
firstRow = false
table.insert(resource.itemConversions, food)
else
table.insert(resultPart, '\n|-')
end
-- This section generates by biome rows
table.insert(resultPart, '\n| ' .. Icons.Icon({biome.name, type='biome', nolink=true}))
table.insert(resultPart, '\n| ' .. p._getBuildingCostText(building, biomeID))
local providesText = p._getBuildingBenefitText(building, biomeID)
if building.modifiers ~= nil then
local modText = Modifiers.getModifiersText(building.modifiers)
if providesText == nil then
providesText = modText
else
providesText = providesText .. '<br/>' .. modText
end
end
end
end
elseif resource.id == 'melvorF:Wood' or resource.id == 'melvorF:Planks' then
table.insert(resultPart, '\n| ' .. (providesText or ''))
resource._skill = 'Woodcutting'
end
resource.itemConversions = Data.Item.Match('type', 'Logs')
end
elseif resource.id == 'melvorF:Stone' or resource.id == 'melvorF:Ore' then
table.insert(resultPart, '\n|}')
resource._skill = 'Mining'
 
for _, ore in ipairs(Data.Item.Match('type', 'Ore')) do
return table.concat(resultPart)
if not string.match(ore.id, 'Meteorite_Ore') then
end
table.insert(resource.itemConversions, ore)
 
-- Builds the table of trader items
function p.getTraderTable(frame)
local resultPart = {}
 
-- Build table header
table.insert(resultPart, '{| class="wikitable sortable stickyHeader"')
table.insert(resultPart, '\n|- class="headerRow-0"')
table.insert(resultPart, '\n!colspan="2"| Item\n!Description\n!style="min-width:60px"| Cost\n!Requirements')
 
for i, tsResource in ipairs(Township.itemConversions.fromTownship) do
local res = GameData.getEntityByID(Township.resources, tsResource.resourceID)
for j, tradeDef in ipairs(tsResource.items) do
local item = Items.getItemByID(tradeDef.itemID)
local itemDesc = item.customDescription
if itemDesc == nil then
if item.modifiers ~= nil then
itemDesc = Modifiers.getModifiersText(item.modifiers, false, true)
else
itemDesc = ''
end
end
end
end
elseif resource.id == 'melvorF:Coal' then
local resQty = math.max(item.sellsFor, 2)
resource._skill = 'Mining'
local costSort = i * 10000 + resQty
local coal = 'melvorD:Coal_Ore'
 
table.insert(resource.itemConversions, Data.Item.ByID(coal))
table.insert(resultPart, '\n|-\n| ' .. Icons.Icon({item.name, type='item', notext=true}))
elseif resource.id == 'melvorF:Bar' then
table.insert(resultPart, '\n| ' .. Icons.getExpansionIcon(item.id) .. Icons.Icon({item.name, type='item', noicon=true}))
resource._skill = 'Mining'
table.insert(resultPart, '\n| ' .. itemDesc)
for _, bar in ipairs(Data.Item.Match('type', 'Ore')) do
table.insert(resultPart, '\n|data-sort-value="' .. costSort ..'" style="text-align:right"| ' .. Icons.Icon({res.name, type='resource', qty=resQty, notext=true}))
if not string.match(bar.id, 'Meteorite_Bar') then
table.insert(resultPart, '\n| ' .. Shop.getRequirementString(tradeDef.unlockRequirements))
table.insert(resource.itemConversions, bar)
end
end
end
table.insert(resultPart, '\n|}')
 
return table.concat(resultPart)
end
 
-- Generates a table showing all the worship options
function p.getWorshipTable()
local function getCheckpointCell(checkpoint)
return '\n|-\n!' .. checkpoint .. '%<br/>' .. Num.formatnum(checkpoint * Township.maxWorship / 100) .. '/' .. Num.formatnum(Township.maxWorship)
end
 
local worships = GameData.getEntities(Township.worships, function(w) return not w.isHidden end)
local ret = {}
 
table.insert(ret, '{| class="wikitable stickyHeader"')
table.insert(ret, '\n!' .. Icons.Icon({'Worship', type='township', nolink=true}))
-- Names
for _, worship in ipairs(worships) do
table.insert(ret, '\n!' .. Icons.Icon({worship.name, type='monster', size=50}) .. Icons.Icon({'Statue of ' .. worship.name, type='building', size=50, notext=true}))
end
 
-- Requirements
table.insert(ret, '\n|-\n!Requirements')
for _, worship in ipairs(worships) do
local cellStyle = (Shared.tableIsEmpty(worship.unlockRequirements) and 'class="table-na"') or 'style="text-align:center"'
table.insert(ret, '\n|' .. cellStyle ..'| ' .. Shop.getRequirementString(worship.unlockRequirements))
end
 
-- Season multipliers
table.insert(ret, '\n|-\n!Bonus Seasons')
for _, worship in ipairs(worships) do
local bonusPart = {}
local cellStyle = 'style="text-align:center"'
if Shared.tableIsEmpty(worship.seasonMultiplier) then
bonusPart, cellStyle = {'None'}, 'class="table-na"'
end
for i, seasonMult in ipairs(worship.seasonMultiplier) do
local season = GameData.getEntityByID(Township.seasons, seasonMult.seasonID)
if season ~= nil then
table.insert(bonusPart, Icons.Icon({season.name, type='township', nolink=true}) .. ' (' .. seasonMult.multiplier .. 'x)')
end
end
elseif resource.id == 'melvorF:Herbs' then
end
resource._skill = 'Farming'
table.insert(ret, '\n|' .. cellStyle .. '| ' .. table.concat(bonusPart, '<br/>'))
resource.itemConversions = Data.Item.Match('type', 'Herb')
end
elseif resource.id == 'melvorF:Rune_Essence' then
 
resource._skill = 'Mining'
-- Base modifiers
local ressence = 'melvorD:Rune_Essence'
table.insert(ret, getCheckpointCell(0))
local pessence = 'melvorTotH:Pure_Essence'
for _, worship in ipairs(worships) do
table.insert(resource.itemConversions, Data.Item.ByID(ressence))
table.insert(ret, '\n| ' .. Modifiers.getModifiersText(worship.modifiers))
table.insert(resource.itemConversions, Data.Item.ByID(pessence))
end
elseif resource.id == 'melvorF:Leather' then
 
resource._skill = 'Crafting' -- Placeholder - actually no related skill to obtain
-- Checkpoint modifiers
local leather = 'Leather'
for i, checkpoint in ipairs(Township.worshipCheckpoints) do
table.insert(resource.itemConversions, Data.Item.ByID(leather))
table.insert(ret, getCheckpointCell(checkpoint))
elseif resource.id == 'melvorF:Potions' then
for _, worship in ipairs(worships) do
resource._skill = 'Herblore'
table.insert(ret, '\n| ' .. Modifiers.getModifiersText(worship.checkpoints[i]))
for _, potion in ipairs(Data.Item.Match('type', 'Potion')) do
end
if string.match(potion.id, '_IV') then
end
table.insert(resource.itemConversions, potion)
 
-- Total sum
-- TODO Needs fixing, no function currently for aggregating modifiers
--[==[
table.insert(ret, '\n|-\n!Total')
for _, worship in ipairs(worships) do
local modifiers = Shared.clone(worship.modifiers)
for _, checkpoint in ipairs(worship.checkpoints) do
for modifier, magnitude in pairs(checkpoint) do
local swappedModifier = string.sub(modifier, 1, string.len('increased')) == 'increased' and string.gsub(modifier, 'increased', 'decreased') or string.gsub(modifier, 'decreased', 'increased')
-- The modifier already exists, so we add the two modifiers together
if modifiers[modifier] ~= nil then
modifiers[modifier] = modifiers[modifier] + magnitude
-- The inverse modifier already exists, so we subtract the negative value of the new modifier
elseif modifiers[swappedModifier] ~= nil then
modifiers[swappedModifier] = modifiers[swappedModifier] - magnitude
-- The modifier does not exist, so create the modifier
else
modifiers[modifier] = magnitude
end
end
end
end
elseif resource.id == 'melvorF:Clothing' then
end
resource._skill = 'Crafting'
table.insert(ret, '\n|' .. Modifiers.getModifiersText(modifiers))
local matches = {}
end
table.insert(matches, Data.Item.Match('tier', 'Leather'))
--]==]
table.insert(matches, Data.Item.Match('tier', 'Hard Leather'))
table.insert(ret, '\n|}')
table.insert(matches, Data.Item.Match('tier', 'Dragonhide'))
 
table.insert(matches, Data.Item.Match('tier', 'Elderwood'))
return table.concat(ret)
table.insert(matches, Data.Item.Match('tier', 'Revenant'))
end
table.insert(matches, Data.Item.Match('tier', 'Carrion'))
 
for _, match in ipairs(matches) do
-- Gets a building and prepares all the relevant stats for the building, presented as an infobox
for _, v in ipairs(match) do
function p.getBuildingInfoBox(frame)
table.insert(resource.itemConversions, v)
local name = frame.args ~= nil and frame.args[1] or frame
local building = p._getBuildingByName(name)
if building == nil then
return Shared.printError('No building named "' .. name .. '" exists in the data module')
end
 
local ret = {}
-- Header
table.insert(ret, '{| class="wikitable infobox"')
-- Name
table.insert(ret, '\n|-\n! ' .. Icons.getExpansionIcon(building.id) .. building.name)
-- Icon
table.insert(ret, '\n|-\n|style="text-align:center"| ' .. Icons.Icon({building.name, type='building', size='250', notext=true}))
-- ID
table.insert(ret, '\n|-\n| <b>Building ID:</b> ' .. building.id)
-- Tier
local tier = p._getTierText(building.tier, building.abyssalTier)
table.insert(ret, '\n|-\n| <b>Requirements:</b><br/>' .. tier)
 
-- Upgrades From
table.insert(ret, '\n|-\n| <b>Base Cost:</b>')
local upgradesFrom = p._getBuildingDowngrade(building)
if upgradesFrom ~= nil then
table.insert(ret, '<br/>' .. Icons.Icon({upgradesFrom.name, type='building'}))
end
-- Cost
--table.insert(ret, '<br/>' .. p._getBuildingGroupedCostText(building))
local function getGroupedText(building, groupFunc)
local biomeGroups = groupFunc(building)
if Shared.tableCount(biomeGroups) == 1 then
-- If only one entry then simply output the cost
return biomeGroups[1].cost
else
-- Otherwise, split by biome group
local resultPart = {}
table.insert(resultPart, '{| class="wikitable" style="text-align:center; margin: 0.25em 0 0 0"')
for i, biomeGroup in ipairs(biomeGroups) do
local biomeText = {}
for j, biomeID in ipairs(biomeGroup.biomeIDs) do
local biome = GameData.getEntityByID(Township.biomes, biomeID)
table.insert(biomeText, Icons.Icon({biome.name, type='biome', notext=true, nolink=true, alt=biome.name}))
end
end
table.insert(resultPart, '\n|-\n| ' .. table.concat(biomeText, '<br/>'))
table.insert(resultPart, '\n| ' .. biomeGroup.cost)
end
end
table.insert(resultPart, '\n|}')
return table.concat(resultPart)
end
end
end
end
table.insert(ret, '\n' .. getGroupedText(building, p._getBuildingGroupedCosts))
-- Upgrades To
local upgradesTo = p._getBuildingUpgrade(building)
if upgradesTo ~= nil then
table.insert(ret, '\n|-\n| <b>Upgrades To:</b>')
table.insert(ret, '<br/>' .. Icons.Icon({upgradesTo.name, type='building'}))
table.insert(ret, '\n' .. getGroupedText(upgradesTo, p._getBuildingGroupedCosts))
end
-- Maximum built
local biomeCount = Shared.tableCount(building.biomes)
local maxText = Num.formatnum(building.maxUpgrades)
if biomeCount > 1 then
maxText = maxText .. ' per biome, ' .. Num.formatnum(biomeCount * building.maxUpgrades) .. ' total'
end
table.insert(ret, '\n|-\n| <b>Maximum Built:</b><br/>' .. maxText)
-- Calculate the conversion ratios
-- Benefits
-- See TownshipResource.getBaseConvertToTownshipRatio and TownshipResource.getBaseConvertFromTownshipRatio for the conversion prices
local benefits = p._getBuildingGroupedBenefitText(building)
for _, resource in ipairs(resources) do
if benefits ~= nil and benefits ~= '' then
if resource.id == 'Food' then
table.insert(ret, '\n|-\n| <b>Provides:</b><br/>' .. benefits)
for _, item in ipairs(resource.itemConversions) do
end
item.to = math.max(math.floor(1000/(item.healsFor*10)), 2)
 
item.from = item.healsFor*5*6
-- Biomes
table.insert(ret, '\n|-\n| <b>Biomes:</b>')
for _, biomeid in ipairs(building.biomes) do
local biome = GameData.getEntityByID(Township.biomes, biomeid)
table.insert(ret, '<br/>' .. Icons.Icon({biome.name, type='biome', nolink=true}))
end
 
-- End
table.insert(ret, '\n|}')
return table.concat(ret)
end
 
-- Returns an upgrade table of a building
function p.getBuildingUpgradeTable(frame)
local buildingname = frame.args ~= nil and frame.args[1] or frame
local building = p._getBuildingByName(buildingname)
if building == nil then
return Shared.printError('No building named "' .. buildingname .. '" exists in the data module')
end
 
-- Let's find the base building
local baseBuilding = building
while true do
local previousBuilding = p._getBuildingDowngrade(baseBuilding)
if previousBuilding ~= nil then
baseBuilding = previousBuilding
else
break
end
end
 
-- Let's make a list of all the buildings
-- Return empty string if there is only 1 building in the upgrade chain (i.e. no upgrades/downgrades)
local buildingList = {}
local _curBuilding = baseBuilding
while true do
table.insert(buildingList, _curBuilding)
_curBuilding = p._getBuildingUpgrade(_curBuilding)
if _curBuilding == nil then
break
end
end
if #buildingList == 1 then
return ''
end
 
local ret = {}
table.insert(ret, '\n== Upgrade Chart ==')
table.insert(ret, '\n{| class="wikitable" style="text-align:center"')
 
-- Name
table.insert(ret, '\n|-\n!colspan="2"| Name')
for _, building in ipairs(buildingList) do
table.insert(ret, '\n!' .. Icons.getExpansionIcon(building.id) .. Icons.Icon({building.name, type='building'}))
end
 
-- Tier
table.insert(ret, '\n|-\n!colspan="2"| Requirements')
for _, building in ipairs(buildingList) do
table.insert(ret, '\n|' .. p._getTierText(building.tier, building.abyssalTier))
end
 
-- Cost
local biomeCount = Shared.tableCount(baseBuilding.biomes)
table.insert(ret, '\n|-\n!rowspan="' .. biomeCount .. '"| Cost')
local firstBiome = true
for _, biomeID in ipairs(baseBuilding.biomes) do
local biome = GameData.getEntityByID(Township.biomes, biomeID)
table.insert(ret, (firstBiome and '' or '\n|-') .. '\n! ' .. Icons.Icon({biome.name, type='biome', nolink=true}))
for _, building in ipairs(buildingList) do
local cost = p._getBuildingCostText(building, biomeID)
table.insert(ret, '\n| ' .. cost)
end
firstBiome = false
end
 
-- Benefits
local benefitText = {}
table.insert(benefitText, '\n|-\n!rowspan="' .. biomeCount .. '"| Benefits')
firstBiome = true
local hasText = false
for _, biomeID in ipairs(baseBuilding.biomes) do
local biome = GameData.getEntityByID(Township.biomes, biomeID)
table.insert(benefitText, (firstBiome and '' or '\n|-') .. '\n! ' .. Icons.Icon({biome.name, type='biome', nolink=true}))
for _, building in ipairs(buildingList) do
local benefit = p._getBuildingBenefitText(building, biomeID, true) or ''
if not hasText and benefit ~= '' then
hasText = true
end
end
elseif resource.id == 'Planks' then
table.insert(benefitText, '\n| ' .. benefit)
for _, item in ipairs(resource.itemConversions) do
end
item.to = math.max(math.floor(3000/math.max(item.sellsFor, 1)), 2)
firstBiome = false
item.from = math.max(math.ceil(item.sellsFor/2)*6, 1);
end
if hasText then
-- Only add benefits rows if the building has benefits to display
table.insert(ret, table.concat(benefitText))
end
 
-- End
table.insert(ret, '\n|}')
 
return table.concat(ret)
end
 
-- Returns a row containing a task given a title and a task table
function p._getTaskRow(title, task, isDailyTask)
local ret = {}
 
-- If has description, we will need to rowspan the title by 2, and insert a description with colspan 2
local hasDescription = false
if task.description ~= nil then
hasDescription = true
end
local titlespan = hasDescription == true and 'rowspan="2"|' or ''
 
-- Title
table.insert(ret, '\n|-')
table.insert(ret, '\n!' .. titlespan .. title)
-- Description
if hasDescription then
table.insert(ret, '\n|colspan="2"|' .. task.description)
table.insert(ret, '\n|-')
end
-- Requirements
table.insert(ret, '\n|')
-- Determines order of requirements output
local reqOrder = {
["items"] = 10,
["monsters"] = 20,
["monsterWithItems"] = 30,
["skillXP"] = 40,
["buildings"] = 50,
["numPOIs"] = 60,
["numRefinements"] = 70
}
local reqTextPart = {}
 
local function getItemText(itemID)
local item = Items.getItemByID(itemID)
if item == nil then
return Shared.printError('Unknown item: ' .. (itemID or 'nil'))
else
return Icons.Icon({item.name, type='item'})
end
end
local function getMonsterText(monsterID)
local monster = Monsters.getMonsterByID(monsterID)
if monster == nil then
return Shared.printError('Unknown monster: ' .. (monsterID or 'nil'))
else
return Icons.Icon({Monsters.getMonsterName(monster), type='monster'})
end
end
 
for goalType, goalData in pairs(task.goals) do
local typeOrder = reqOrder[goalType] or 0
local goalText = nil
if type(goalData) == 'table' then
-- Goal data is a table
for goalIdx, goalObj in ipairs(goalData) do
if goalType == 'items' then
goalText = Num.formatnum(goalObj.quantity) .. ' ' .. getItemText(goalObj.id)
elseif goalType == 'monsters' then
goalText = Num.formatnum(goalObj.quantity) .. ' ' .. getMonsterText(goalObj.id)
elseif goalType == 'monsterWithItems' then
local itemsText = {}
for i, itemID in ipairs(goalObj.itemIDs) do
table.insert(itemsText, getItemText(itemID))
end
goalText = Num.formatnum(goalObj.quantity) .. ' ' .. getMonsterText(goalObj.monsterID) .. ' with ' .. table.concat(itemsText, ', ') .. ' equipped'
elseif goalType == 'skillXP' then
local skillName = GameData.getSkillData(goalObj.id).name
goalText = Num.formatnum(goalObj.quantity) .. ' ' .. Icons.Icon({skillName, type='skill'}) .. ' XP'
elseif goalType == 'buildings' then
local buildingName = p._GetBuildingByID(goalObj.id).name
goalText = Num.formatnum(goalObj.quantity) .. ' ' .. Icons.Icon({buildingName, type='building'})
elseif goalType == 'numPOIs' then
local mapName = GameData.getEntityByID(GameData.skillData.Cartography.worldMaps, goalObj.worldMapID).name
goalText = 'Discover ' .. Num.formatnum(goalObj.quantity) .. ' Points of Interest in ' .. Icons.Icon({'Cartography', type='skill'}) .. ' world map of ' .. mapName
else
goalText = Shared.printError('Unknown goal type: ' .. (goalType or 'nil'))
end
table.insert(reqTextPart, {
["goalOrder"] = typeOrder,
["subOrder"] = goalIdx,
["text"] = goalText
})
end
end
elseif resource.id == 'Rune_Essence' then
else
for _, item in ipairs(resource.itemConversions) do
-- Goal data is another value of some type
item.to = 5
if goalType == 'numRefinements' then
item.from = (item.sellsFor+1)*10*6
goalText = 'Refine dig site maps in ' .. Icons.Icon({'Cartography', type='skill'}) .. ' ' .. Num.formatnum(goalData) .. ' times'
else
goalText = Shared.printError('Unknown goal type: ' .. (goalType or 'nil'))
end
end
elseif resource.id == 'Leather' then
table.insert(reqTextPart, {
for _, item in ipairs(resource.itemConversions) do
["goalOrder"] = typeOrder,
item.to = 20
["subOrder"] = 0,
item.from = 20*6
["text"] = goalText
})
end
end
 
table.sort(reqTextPart,
function(a, b)
if a.goalOrder == b.goalOrder then
return a.subOrder < b.subOrder
else
return a.goalOrder < b.goalOrder
end
end
else
end
for _, item in ipairs(resource.itemConversions) do
)
        item.to = math.max(math.floor(1000/math.max(item.sellsFor, 1)), 2)
 
    item.from = math.max(item.sellsFor * 6, 1)
local requirements = {}
for i, req in ipairs(reqTextPart) do
table.insert(requirements, req.text)
end
-- We don't check tasks.requirements (so far it's only used to enumerate the Tutorial tasks so you only see 1 at a time)
table.insert(ret, table.concat(requirements, '<br/>'))
-- Rewards
table.insert(ret, '\n|')
local rewards = {}
local rewardsVariableQty = {}
if task.rewards.currencies ~= nil then
for _, currReward in ipairs(task.rewards.currencies) do
if isDailyTask and currReward.id ~= 'melvorD:GP' then
table.insert(rewardsVariableQty, Icons._Currency(currReward.id))
elseif not isDailyTask then
table.insert(rewards, Icons._Currency(currReward.id, currReward.quantity))
end
end
end
end
end
end
return resources
for _, item in ipairs(task.rewards.items) do
local itemname = GameData.getEntityByID('items', item.id).name
table.insert(rewards, Num.formatnum(item.quantity)..' '..Icons.Icon({itemname, type='item'}))
end
for _, skill in ipairs(task.rewards.skillXP) do
if not (isDailyTask and skill.id == 'melvorD:Township') then
local skillname = GameData.getSkillData(skill.id).name
table.insert(rewards, Num.formatnum(skill.quantity)..' '..Icons.Icon({skillname, type='skill'})..' XP')
end
end
for _, townshipResource in ipairs(task.rewards.townshipResources) do
local resourcename = p._getResourceByID(townshipResource.id).name
table.insert(rewards, Num.formatnum(townshipResource.quantity)..' '..Icons.Icon({resourcename, type='resource'}))
end
if not Shared.tableIsEmpty(rewardsVariableQty) then
table.insert(ret, '[[Township#Casual Tasks|Variable]] ' .. table.concat(rewardsVariableQty, ', ') .. '<br/>')
end
table.insert(ret, table.concat(rewards, '<br/>'))
 
-- Unlock requirements, daily task specific
if isDailyTask then
table.insert(ret, '\n|' .. Shop.getRequirementString(task.requirements))
end
return table.concat(ret)
end
end


-- Builds the table of trader items
-- Returns all the tasks of a given category
function Data.Township.getTraderTable(frame)
-- TODO: Support casual tasks
local resources = Data.Township.Trader()
function p.getTaskTable(frame)
local category = frame.args ~= nil and frame.args[1] or frame
local categoryData = GameData.getEntityByName(Township.taskCategories, category)
local taskData, categoryName, isDailyTask = nil, nil, false
if category == 'Daily' then
isDailyTask = true
taskData = Township.casualTasks
categoryName = 'Casual'
elseif categoryData ~= nil then
taskData = Township.tasks
categoryName = categoryData.name
else
return Shared.printError('Invalid task category specified: ' .. (tostring(category) or 'nil'))
end
 
local taskcount = 0
local ret = {}
table.insert(ret, '{| class="wikitable lighttable stickyHeader mw-collapsible" style="text-align:left"')
table.insert(ret, '\n|- class="headerRow-0"')
table.insert(ret, '\n!Task')
table.insert(ret, '\n!Requirements')
table.insert(ret, '\n!Rewards')
if isDailyTask then
table.insert(ret, '<br/>(In addition to [[Township#Casual Tasks|Variable]] ' .. Icons._Currency('melvorD:GP') .. ' & ' .. Icons.Icon({'Township', type='skill', notext=true}) .. ' XP)')
end
if isDailyTask then
table.insert(ret, '\n!Unlock Requirements')
end
local ret = {}
for _, task in ipairs(taskData) do
for _, resource in ipairs(resources) do
-- Filter out other categories
if #resource.itemConversions ~= 0 then -- Skips GP
local categoryID, categoryNS, categoryLocalID = '', '', ''
local ret_resource = {}
if categoryData ~= nil then
table.insert(ret_resource, '\r\n==='..resource.name..'===')
categoryID = categoryData.id
table.insert(ret_resource, '\r\n{| class="wikitable sortable stickyHeader"')
categoryNS, categoryLocalID = Shared.getLocalID(categoryID)
table.insert(ret_resource, '\r\n|- class="headerRow-0"')
end
table.insert(ret_resource, '\r\n!Item')
if isDailyTask or task.category == categoryID or task.category == categoryLocalID then
table.insert(ret_resource, '\r\n!Name')
taskcount = taskcount + 1
table.insert(ret_resource, '\r\n!DLC')
local title = categoryName .. ' ' .. taskcount
table.insert(ret_resource, '\r\n!Level')
table.insert(ret, p._getTaskRow(title, task, isDailyTask))
table.insert(ret_resource, '\r\n!Give To')
end
table.insert(ret_resource, '\r\n!Take From')
end
table.insert(ret_resource, '\r\n!Value')
table.insert(ret, '\n|}')
table.insert(ret_resource, '\r\n!Value/Resource')
return table.concat(ret)
if resource.id =='Food' then
end
table.insert(ret_resource, '\r\n!Heals')
 
table.insert(ret_resource, '\r\n!Heals/Resource')
-- Returns a table containing all the tasks that reference an item or monster
-- e.g. p.getTaskReferenceTable({'Chicken Coop', 'dungeon'})
-- name = item or monster name
-- type = 'item' or 'monster' or 'dungeon'
function p.getTaskReferenceTable(frame)
-- Returns a set containing all the desired IDs
local function GetReferenceIDs(referenceName, referenceType)
local IDs = {}
if referenceType == 'dungeon' then
-- We get the tasks associated with all monsters in the dungeon
local area = nil
local areaTypes = {'dungeons', 'abyssDepths', 'strongholds'}
for _, areaType in ipairs(areaTypes) do
area = GameData.getEntityByName(areaType, referenceName)
if area ~= nil then
break
end
end
local monsters = area.monsterIDs
for _, monster in ipairs(monsters) do
IDs[monster] = true
end
end
end
for _, item in ipairs(resource.itemConversions) do
if referenceType == 'item' then
-- Find the recipe to get the required level
IDs[GameData.getEntityByName('items', referenceName).id] = true
local required_level = nil
end
local recipes = nil
if referenceType == 'monster' then
local skill = resource._skill
IDs[Monsters.getMonster(referenceName).id] = true
local lookup_id = item.id
end
-- A few special skill overrides
return IDs
if item.id == 'Raw_Magic_Fish' then
end
skill = 'Fishing'
-- For a task, returns where to search for the desired IDs, given the type
elseif item.id == 'Apple' then
local function GetGetSearchTables(referenceType)
skill = 'Farming'
local function searchItems(task)
elseif string.match(item.id, '_U$') then
return {task.goals.items, task.rewards.items}
-- Upgraded Crafting item. Display the level for the base item
end
-- Converts Black_Dhide_Body_U -> Black_Dhide_Body for the purposes of the lookup
local function searchMonsters(task)
lookup_id = string.sub(item.id, 1, #item.id - 2)
return {task.goals.monsters}
end
end
local recipes = Data.Item.FindRecipes(lookup_id, skill)
-- item -> searchItems; monster or dungeon -> searchMonsters
if #recipes == 1 then
return referenceType == 'item' and searchItems or searchMonsters
required_level = recipes[1].level
end
end
 
table.insert(ret_resource, '\r\n|-')
local args = frame.args ~= nil and frame.args or frame
-- Icon
local referenceName = Shared.fixPagename(args[1])
table.insert(ret_resource, '\r\n|style="text-align:center"|'..Icons.Icon({item.name, type='item', size='50', notext=true}))
local referenceType = args[2]
-- Name
local referenceIDs = GetReferenceIDs(referenceName, referenceType)
table.insert(ret_resource, '\r\n|style="text-align:left"|'..Icons.Icon({item.name, type='item', noicon=true}))
-- GetSearchTables = function searchItems/Monsters(task)
-- DLC
local GetSearchTables = GetGetSearchTables(referenceType)
table.insert(ret_resource, '\r\n|style="text-align:center"|'..Data.PLACEHOLDER_NAMESPACE_ICON(item._namespace))
 
-- Level
local function checkTask(task)
if required_level == nil then
local function checkID(entry)
-- Recipe not found, or multiple recipes found
return referenceIDs[entry.id] ~= nil
table.insert(ret_resource, '\r\n|style="text-align:center" data-sort-value="0"|N/A')
end
else
for _, searchTable in pairs(GetSearchTables(task)) do -- ipairs won't work if first table is nil
table.insert(ret_resource, '\r\n|style="text-align:center" data-sort-value="' .. required_level .. '"|'..Icons.Icon({skill, type="skill", notext=true})..' '..required_level)
-- Check to see if the table contains any of the IDs in referenceIDs
end
if searchTable[1] ~= nil then -- Make sure table is not empty
-- Give To
if #GameData.getEntities(searchTable, checkID) ~= 0 then -- Make sure we have at least 1 match
table.insert(ret_resource, '\r\n|style="text-align:center" data-sort-value="' .. item.to .. '"|'..Icons.Icon({item.name, type='item', notext=true})..' '..Shared.formatnum(item.to))
return true
-- Take From
table.insert(ret_resource, '\r\n|style="text-align:center" data-sort-value="' .. item.from .. '"|'..Icons.Icon(resource._icon)..' '..Shared.formatnum(item.from))
-- Value
table.insert(ret_resource, '\r\n|style="text-align:center" data-sort-value="' .. item.sellsFor .. '"|'..Icons.GP(item.sellsFor))
-- Value/Resource
table.insert(ret_resource, '\r\n|style="text-align:center" data-sort-value="' .. item.sellsFor/item.from .. '"|'..Icons.GP(Shared.round(item.sellsFor/item.from, 2, 2)))
if resource.id =='Food' then
-- Heals
table.insert(ret_resource, '\r\n|style="text-align:center" data-sort-value="' .. item.healsFor*10 .. '"|'..Icons.Icon({"Hitpoints", type="skill", notext=true})..' '..Shared.formatnum(item.healsFor*10))
-- Heals/Resource
table.insert(ret_resource, '\r\n|style="text-align:center" data-sort-value="' .. item.healsFor*10/item.from .. '"|'..Icons.Icon({"Hitpoints", type="skill", notext=true})..' '..Shared.round(item.healsFor*10/item.from, 2, 2))
end
end
end
end
table.insert(ret_resource, '\r\n|}')
table.insert(ret, table.concat(ret_resource))
end
end
return false
end
-- Find all tasks that contain the desired ids
local tasks = GameData.getEntities(Township.tasks, checkTask)
if #tasks == 0 then
return ''
end
-- Build the table
local ret = {}
table.insert(ret, '==Tasks==')
table.insert(ret, '\n{| class="wikitable" style="text-align:left"')
table.insert(ret, '\n!Task')
table.insert(ret, '\n!Requirements')
table.insert(ret, '\n!Rewards')
for _, task in ipairs(tasks) do
-- Some categories have a local ID, resolve this before looking up the task category
local taskNS, taskLocalID = Shared.getLocalID(task.id)
local catID = Shared.getNamespacedID(taskNS,  task.category)
local categoryname = GameData.getEntityByID(Township.taskCategories, catID).name
local title = '[[Township/Tasks#'..categoryname..'|'..categoryname..']]'
table.insert(ret, p._getTaskRow(title, task, false))
end
end
table.insert(ret, '\n|}')
return table.concat(ret)
return table.concat(ret)
end
end
local p = {}
p.getTraderTable = Data.Township.getTraderTable


return p
return p

Latest revision as of 05:33, 8 October 2024

Documentation for this module may be created at Module:Township/doc

local Shared = require('Module:Shared')
local Icons = require('Module:Icons')
local Items = require('Module:Items')
local Monsters = require('Module:Monsters')
local Shop = require('Module:Shop')
local GameData = require('Module:GameData')
local Modifiers = require('Module:Modifiers')
local Num = require('Module:Number')

local p = {}

local Township = GameData.getSkillData('melvorD:Township')
p.Township = Township

-- Gets a Township building by ID, e.g. melvorF:Hunters_Cabin
function p._getBuildingByID(id)
	-- Check for the special statue case
	if id == 'melvorF:Statues' then
		local building = Shared.clone(GameData.getEntityByID(Township.buildings, id))
		building.name = 'Statue of Worship'
		return building
	else
		return GameData.getEntityByID(Township.buildings, id)
	end
end

-- Gets a Township building by name, e.g. Hunters Cabin
function p._getBuildingByName(name)
	-- Check for the special statue case
	if name == 'Statues' then
		name = 'Statue of Worship'
	end
	local STATUE_OF = 'Statue of '
	if string.sub(name, 1, string.len(STATUE_OF)) == STATUE_OF then
		local building = Shared.clone(GameData.getEntityByID(Township.buildings, 'melvorF:Statues'))
		building.name = name
		return building
	else
		return GameData.getEntityByName(Township.buildings, name)
	end
end

-- Gets a resource from id
function p._getResourceByID(id)
	return GameData.getEntityByID(Township.resources, id)
end

-- Given a building, find the next building upgrade
function p._getBuildingUpgrade(building)
	local function checkFunc(entity)
		return entity.upgradesFrom ~= nil and entity.upgradesFrom == building.id
	end
	local upgradesTo = GameData.getEntities(Township.buildings, checkFunc)
	if #upgradesTo > 0 then
		return upgradesTo[1]
	end
	return nil
end

-- Given a building, find the building's downgrade
function p._getBuildingDowngrade(building)
	if building.upgradesFrom ~= nil then
		return p._getBuildingByID(building.upgradesFrom)
	end
	return nil
end

-- Given a building and biome ID, returns the cost of constructing the building
-- within that biome as a human readable text string. Returns nil if the building
-- cannot be built within that biome.
function p._getBuildingCostText(building, biomeID, delimiter)
	-- Basic validation of inputs
	if type(building) == 'table' and building.cost ~= nil and biomeID ~= nil then
		local delim = delimiter
		if delim == nil then
			delim = ', '
		end
		for i, costDef in ipairs(building.cost) do
			if costDef.biomeID == biomeID then
				local resultPart = {}
				for j, cost in ipairs(costDef.cost) do
					local resData = p._getResourceByID(cost.id)
					if resData ~= nil then
						table.insert(resultPart, Icons.Icon({resData.name, type='resource', notext=true, nolink=true, qty=cost.quantity}))
					end
				end
				return table.concat(resultPart, delim)
			end
		end
	end
end

-- Given a building, groups biomes for which that building has a common cost
function p._getBuildingGroupedCosts(building)
	local biomeGroups = {}
	for i, biomeID in ipairs(building.biomes) do
		local currentBiomeCost = p._getBuildingCostText(building, biomeID)
		local found = false
		for j, biomeGroup in ipairs(biomeGroups) do
			if biomeGroup.cost == currentBiomeCost then
				-- Another biome exists with this cost
				table.insert(biomeGroup.biomeIDs, biomeID)
				found = true
				break
			end
		end
		if not found then
			table.insert(biomeGroups, { biomeIDs = { biomeID }, cost = currentBiomeCost})
		end
	end
	return biomeGroups
end

-- Given a building, returns a text string repesenting the building costs for all biomes
function p._getBuildingGroupedCostText(building)
	local resultPart = {}
	local biomeGroups = p._getBuildingGroupedCosts(building)
	if Shared.tableCount(biomeGroups) == 1 then
		-- If only one entry then simply output the cost
		table.insert(resultPart, biomeGroups[1].cost)
	else
		-- Otherwise, split by biome group
		for i, biomeGroup in ipairs(biomeGroups) do
			local biomeText = {}
			for j, biomeID in ipairs(biomeGroup.biomeIDs) do
				local biome = GameData.getEntityByID(Township.biomes, biomeID)
				table.insert(biomeText, Icons.Icon({biome.name, type='biome', notext=true, nolink=true, alt=biome.name}))
			end
			table.insert(resultPart, table.concat(biomeText, ', ') .. ': ' .. biomeGroup.cost)
		end
	end
	return table.concat(resultPart, '<br/>')
end

-- Given a building and biome ID, returns a string displaying the building's benefits,
-- or nil if no benefits
function p._getBuildingBenefitText(building, biomeID, includeModifiers, delimiter)
	-- Basic validation of inputs
	if type(building) == 'table' and building.provides ~= nil and biomeID ~= nil then
		local delim = delimiter
		if delim == nil then
			delim = ', '
		end
		local includeMods = includeModifiers
		if includeMods == nil then
			includeMods = false
		end

		local providesData = nil
		for i, provides in ipairs(building.provides) do
			if provides.biomeID == biomeID then
				providesData = provides
				break
			end
		end

		if providesData ~= nil then
			local resultPart = {}
			local stats = {
				population = 'Population',
				happiness = 'Happiness',
				education = 'Education',
				storage = 'Storage',
				soulStorage = 'Soul Storage',
				worship = 'Worship',
 				fortification = 'Fortification'
			}
			local resourceText = function(resName, resType, quantity)
				local elemClass = (quantity < 0 and 'text-negative') or 'text-positive'
				local resIcon = Icons.Icon({resName, type=resType, notext=true})
				return resIcon .. '&nbsp;<span class="' .. elemClass .. '">' .. Num.numStrWithSign(quantity) .. '</span>'
			end

			-- Resources
			if providesData.resources ~= nil then
				for i, resource in ipairs(providesData.resources) do
					local resData = p._getResourceByID(resource.id)
					if resData ~= nil and resource.quantity ~= 0 then
						table.insert(resultPart, resourceText(resData.name, 'resource', resource.quantity))
					end
				end
			end

			-- Other stats
			for key, stat in pairs(stats) do
				local quantity = providesData[key]
				if quantity ~= nil and quantity ~= 0 then
					table.insert(resultPart, resourceText(stat, 'township', quantity))
				end
			end

			-- Modifiers
			if includeMods and building.modifiers ~= nil then
				table.insert(resultPart, Modifiers.getModifiersText(building.modifiers))
			end

			if not Shared.tableIsEmpty(resultPart) then
				return table.concat(resultPart, delim)
			end
		end
	end
end

-- Given a building, groups biomes for which that building has a common benefit/provides
function p._getBuildingGroupedBenefits(building, includeModifiers)
	if includeModifiers == nil then
		includeModifiers = true
	end
	local biomeGroups = {}
	for i, biomeID in ipairs(building.biomes) do
		local currentBiomeBenefit = p._getBuildingBenefitText(building, biomeID, includeModifiers)
		local found = false
		for j, biomeGroup in ipairs(biomeGroups) do
			if biomeGroup.benefit == currentBiomeBenefit then
				-- Another biome exists with this cost
				table.insert(biomeGroup.biomeIDs, biomeID)
				found = true
				break
			end
		end
		if not found then
			table.insert(biomeGroups, { biomeIDs = { biomeID }, cost = currentBiomeBenefit})
		end
	end
	return biomeGroups
end

-- Given a building, returns a text string repesenting the building benefits for all biomes
function p._getBuildingGroupedBenefitText(building, includeModifiers)
	if includeModifiers == nil then
		includeModifiers = true
	end
	local resultPart = {}
	local biomeGroups = p._getBuildingGroupedBenefits(building, includeModifiers)
	if Shared.tableCount(biomeGroups) == 1 then
		-- If only one entry then simply output the cost
		table.insert(resultPart, biomeGroups[1].cost)
	else
		-- Otherwise, split by biome group
		for i, biomeGroup in ipairs(biomeGroups) do
			local biomeText = {}
			for j, biomeID in ipairs(biomeGroup.biomeIDs) do
				local biome = GameData.getEntityByID(Township.biomes, biomeID)
				table.insert(biomeText, Icons.Icon({biome.name, type='biome', notext=true, nolink=true, alt=biome.name}))
			end
			table.insert(resultPart, table.concat(biomeText, ', ') .. ': ' .. biomeGroup.cost)
		end
	end
	return table.concat(resultPart, '<br/>')
end

-- Returns a sorted list of all Township buildings
function p._sortedBuildings(keepUnsorted)
	local ku = true
	if keepUnsorted ~= nil then
		ku = keepUnsorted
	end
	return GameData.sortByOrderTable(Township.buildings, Township.buildingDisplayOrder, ku)
end

-- Gets the Township level or abyssalLevel, population and fortification requirements for a tier
-- Returns {population=X, level=X} for non-abyssal tiers
-- Returns {population=X, abyssalLevel=X, fortification=X} for abyssal tiers
function p._getTierRequirements(tier, abyssalTier)
	local tierData = Township.populationForTier[tier]
	if abyssalTier ~= nil then
		local abyssalTierData = Shared.clone(Township.abyssalTierRequirements[abyssalTier + 1])
		abyssalTierData.population = tierData.population
		return abyssalTierData
	else
		return tierData
	end
end

-- Returns a string containing the Township level and population requirements for a tier
function p._getTierText(tier, abyssalTier)
	local realmID = (abyssalTier ~= nil and 'melvorItA:Abyssal' or 'melvorD:Melvor')
	local tierData = p._getTierRequirements(tier, abyssalTier)
	if tierData ~= nil then
		local tierText = Icons._SkillReq('Township', tierData.abyssalLevel or tierData.level, false, realmID)
		if tierData.population ~= nil and tierData.population > 0 then
			tierText = tierText .. '<br/>' .. Icons.Icon({'Population', type='township', notext=true}) .. '&nbsp;' .. Num.formatnum(tierData.population)
		end
		if tierData.fortification ~= nil and tierData.fortification > 0 then
			tierText = tierText .. '<br/>' .. Icons.Icon({'Fortification', type='township', notext=true}) .. '&nbsp;' .. Num.formatnum(tierData.fortification) .. '%'
		end
		return tierText
	end
end

function p.getBuildings(checkFunc)
	local result = {}
	for i, building in pairs(p.Township.buildings) do
		if checkFunc(building) then
			table.insert(result, building)
		end
	end
	return result
end

function p.getSeasons(checkFunc)
	local result = {}
	for i, season in pairs(p.Township.seasons) do
		if checkFunc(season) then
			table.insert(result, season)
		end
	end
	return result
end

function p.getWorships(checkFunc)
	local result = {}
	for i, worship in pairs(p.Township.worships) do
		if checkFunc(worship) then
			table.insert(result, worship)
		end
	end
	return result
end

-- Generates a table listing all biomes and their associated requirements
function p.getBiomeTable(frame)
	local resultPart = {}
	table.insert(resultPart, '{| class="wikitable sortable stickyHeader"')
	table.insert(resultPart, '\n|- class="headerRow-0"')
	table.insert(resultPart, '\n!rowspan="2" colspan="2"| Biome\n!colspan="3"| Requirements')
	table.insert(resultPart, '\n|- class="headerRow-1"')
	table.insert(resultPart, '\n! ' .. Icons.Icon({'Township', 'Level', type='skill', nolink=true}))
	table.insert(resultPart, '\n! ' .. Icons.Icon({'Township', 'Population', img='Population', type='township', section='Population' }))
	table.insert(resultPart, '\n! ' .. Icons.Icon({'Township', 'Forification', img='Fortification', type='township', section='Fortification' }))

	for i, biome in ipairs(Township.biomes) do
		local reqs = p._getTierRequirements(biome.tier, biome.abyssalTier)
		local fortification = reqs.fortification or 0
		table.insert(resultPart, '\n|-\n|class="table-img"| ' .. Icons.Icon({biome.name, type='biome', nolink=true, notext=true}))
		table.insert(resultPart, '\n| ' .. biome.name)
		table.insert(resultPart, '\n|style="text-align:right"| ' .. (reqs.abyssalLevel or reqs.level))
		table.insert(resultPart, '\n|style="text-align:right" data-sort-value="' .. reqs.population .. '"| ' .. Num.formatnum(reqs.population))
		table.insert(resultPart, '\n|style="text-align:right" data-sort-value="' .. fortification .. '"| ' .. Num.formatnum(fortification))
	end
	table.insert(resultPart, '\n|}')

	return table.concat(resultPart)
end

-- Generates a table showing which buildings can be built in which biomes
-- Skips upgraded buildings
function p.getBuildingBiomeTable(frame)
	local tbl = mw.html.create('table')
		:addClass('wikitable sortable stickyHeader')
		:css('text-align', 'center')

	local header =	mw.html.create('tr'):addClass('headerRow-0')
	local level =	mw.html.create('tr'):addClass('sorttop')
	local pop = 	mw.html.create('tr'):addClass('sorttop')
	local fort = 	mw.html.create('tr'):addClass('sorttop')

	header:tag('th')
		:css('z-index', '2')
		:wikitext('Building')
	level:tag('th')
		:wikitext(Icons.Icon({'Township', 'Level', type='skill', nolink=true}))
	pop:tag('th')
		:wikitext(Icons.Icon({'Township', 'Population', img='Population', type='township', section='Population' }))
	fort:tag('th')
		:wikitext(Icons.Icon({'Township', 'Fortification', img='Fortification', type='township', section='Fortification' }))
	
	for _, biome in ipairs(Township.biomes) do
		local reqs = p._getTierRequirements(biome.tier, biome.abyssalTier)
		header:tag('th')
			:wikitext(Icons.Icon({biome.name, type='biome', notext=true, nolink=true}).. '<br/>' .. biome.name)
		level:tag('td')
			:wikitext(Num.formatnum((reqs.abyssalLevel or reqs.level)))
		pop:tag('td')
			:wikitext(Num.formatnum(reqs.population))
		fort:tag('td')
			:wikitext(Num.formatnum((reqs.fortification or 0)))
	end
	
	tbl:node(header)
	tbl:node(level)
	tbl:node(pop)
	tbl:node(fort)

	for _, _building in ipairs(p._sortedBuildings(false)) do
		-- Fix melvorF:Statues
		local building = p._getBuildingByID(_building.id)
		-- Skip upgraded buildings
		if p._getBuildingDowngrade(building) == nil then
			-- Populate the biome habitability data
			local buildingBiomes = {}
			-- Set all valid biomes to true
			for _, biomeid in ipairs(building.biomes) do
				buildingBiomes[biomeid] = true
			end

			local trow = tbl:tag('tr')
			trow:tag('th')
				:css('text-align', 'left')
				:attr('data-sort-value', building.name)
				:wikitext(Icons.Icon({building.name, type='building'}))

			for _, biome in ipairs(Township.biomes) do
				if buildingBiomes[biome.id] then
					trow:tag('td')
						:addClass('table-positive')
						:wikitext('✓')
				else
					trow:tag('td')
				end
			end
		end
	end

	return tostring(tbl)
end

-- Generates a table contaning each building plus their relevant information
function p.getBuildingTable(frame)
	local resultPart = {}

	-- Change structure of biomes data for ease of use later
	local biomesByID = {}
	for i, biome in ipairs(Township.biomes) do
		biomesByID[biome.id] = biome
	end

	-- Generate table header
	table.insert(resultPart, '{| class="wikitable sortable stickyHeader"')
	table.insert(resultPart, '\n|- class="headerRow-0"')
	table.insert(resultPart, '\n!colspan="2"|Building\n!Requirements\n!Max Built')
	table.insert(resultPart, '\n!Biomes\n!Cost\n!Provides')

	local buildings = p._sortedBuildings(false)

	for i, building in ipairs(buildings) do
		-- Number of rows per building is dictated by number of biomes
		local buildingName = (building.id == 'melvorF:Statues' and 'Statue of Worship') or building.name
		local firstRow = true
		local rowCount = Shared.tableCount(building.biomes)
		local rowSpan = (rowCount > 1 and ' rowspan="' .. rowCount .. '"') or ''
		local rowSpanOnly = (rowCount > 1 and '|' .. rowSpan) or ''
		for j, biomeID in ipairs(building.biomes) do
			local biome = biomesByID[biomeID]
			if firstRow then
				table.insert(resultPart, '\n|-')
				table.insert(resultPart, '\n|class="table-img"' .. rowSpan .. '| ' .. Icons.Icon({buildingName, type='building', notext=true}))
				table.insert(resultPart, '\n' .. rowSpanOnly .. '| ' .. Icons.getExpansionIcon(building.id) .. Icons.Icon({buildingName, type='building', noicon=true}))
				table.insert(resultPart, '\n|' .. 'data-sort-value="' .. building.tier .. '"' .. rowSpan .. '| ' .. (p._getTierText(building.tier, building.abyssalTier) or ''))
				table.insert(resultPart, '\n|style="text-align:right"' .. rowSpan .. '| ' .. building.maxUpgrades)
				firstRow = false
			else
				table.insert(resultPart, '\n|-')
			end
			-- This section generates by biome rows
			table.insert(resultPart, '\n| ' .. Icons.Icon({biome.name, type='biome', nolink=true}))
			table.insert(resultPart, '\n| ' .. p._getBuildingCostText(building, biomeID))
			local providesText = p._getBuildingBenefitText(building, biomeID)
			if building.modifiers ~= nil then
				local modText = Modifiers.getModifiersText(building.modifiers)
				if providesText == nil then
					providesText = modText
				else
					providesText = providesText .. '<br/>' .. modText
				end
			end
			table.insert(resultPart, '\n| ' .. (providesText or ''))
		end
	end
	table.insert(resultPart, '\n|}')

	return table.concat(resultPart)
end

-- Builds the table of trader items
function p.getTraderTable(frame)
	local resultPart = {}

	-- Build table header
	table.insert(resultPart, '{| class="wikitable sortable stickyHeader"')
	table.insert(resultPart, '\n|- class="headerRow-0"')
	table.insert(resultPart, '\n!colspan="2"| Item\n!Description\n!style="min-width:60px"| Cost\n!Requirements')

	for i, tsResource in ipairs(Township.itemConversions.fromTownship) do
		local res = GameData.getEntityByID(Township.resources, tsResource.resourceID)
		for j, tradeDef in ipairs(tsResource.items) do
			local item = Items.getItemByID(tradeDef.itemID)
			local itemDesc = item.customDescription
			if itemDesc == nil then
				if item.modifiers ~= nil then
					itemDesc = Modifiers.getModifiersText(item.modifiers, false, true)
				else
					itemDesc = ''
				end
			end
			local resQty = math.max(item.sellsFor, 2)
			local costSort = i * 10000 + resQty

			table.insert(resultPart, '\n|-\n| ' .. Icons.Icon({item.name, type='item', notext=true}))
			table.insert(resultPart, '\n| ' .. Icons.getExpansionIcon(item.id) .. Icons.Icon({item.name, type='item', noicon=true}))
			table.insert(resultPart, '\n| ' .. itemDesc)
			table.insert(resultPart, '\n|data-sort-value="' .. costSort ..'" style="text-align:right"| ' .. Icons.Icon({res.name, type='resource', qty=resQty, notext=true}))
			table.insert(resultPart, '\n| ' .. Shop.getRequirementString(tradeDef.unlockRequirements))
		end
	end
	table.insert(resultPart, '\n|}')

	return table.concat(resultPart)
end

-- Generates a table showing all the worship options
function p.getWorshipTable()
	local function getCheckpointCell(checkpoint)
		return '\n|-\n!' .. checkpoint .. '%<br/>' .. Num.formatnum(checkpoint * Township.maxWorship / 100) .. '/' .. Num.formatnum(Township.maxWorship)
	end

	local worships = GameData.getEntities(Township.worships, function(w) return not w.isHidden end)
	local ret = {}

	table.insert(ret, '{| class="wikitable stickyHeader"')
	table.insert(ret, '\n!' .. Icons.Icon({'Worship', type='township', nolink=true}))
	-- Names
	for _, worship in ipairs(worships) do
		table.insert(ret, '\n!' .. Icons.Icon({worship.name, type='monster', size=50}) .. Icons.Icon({'Statue of ' .. worship.name, type='building', size=50, notext=true}))
	end

	-- Requirements
	table.insert(ret, '\n|-\n!Requirements')
	for _, worship in ipairs(worships) do
		local cellStyle = (Shared.tableIsEmpty(worship.unlockRequirements) and 'class="table-na"') or 'style="text-align:center"'
		table.insert(ret, '\n|' .. cellStyle ..'| ' .. Shop.getRequirementString(worship.unlockRequirements))
	end

	-- Season multipliers
	table.insert(ret, '\n|-\n!Bonus Seasons')
	for _, worship in ipairs(worships) do
		local bonusPart = {}
		local cellStyle = 'style="text-align:center"'
		if Shared.tableIsEmpty(worship.seasonMultiplier) then
			bonusPart, cellStyle = {'None'}, 'class="table-na"'
		end
		for i, seasonMult in ipairs(worship.seasonMultiplier) do
			local season = GameData.getEntityByID(Township.seasons, seasonMult.seasonID)
			if season ~= nil then
				table.insert(bonusPart, Icons.Icon({season.name, type='township', nolink=true}) .. ' (' .. seasonMult.multiplier .. 'x)')
			end
		end
		table.insert(ret, '\n|' .. cellStyle .. '| ' .. table.concat(bonusPart, '<br/>'))
	end

	-- Base modifiers
	table.insert(ret, getCheckpointCell(0))
	for _, worship in ipairs(worships) do
		table.insert(ret, '\n| ' .. Modifiers.getModifiersText(worship.modifiers))
	end

	-- Checkpoint modifiers
	for i, checkpoint in ipairs(Township.worshipCheckpoints) do
		table.insert(ret, getCheckpointCell(checkpoint))
		for _, worship in ipairs(worships) do
			table.insert(ret, '\n| ' .. Modifiers.getModifiersText(worship.checkpoints[i]))
		end
	end

	-- Total sum
	-- TODO Needs fixing, no function currently for aggregating modifiers
	--[==[ 
	table.insert(ret, '\n|-\n!Total')
	for _, worship in ipairs(worships) do
		local modifiers = Shared.clone(worship.modifiers)
		for _, checkpoint in ipairs(worship.checkpoints) do
			for modifier, magnitude in pairs(checkpoint) do
				local swappedModifier = string.sub(modifier, 1, string.len('increased')) == 'increased' and string.gsub(modifier, 'increased', 'decreased') or string.gsub(modifier, 'decreased', 'increased')
				-- The modifier already exists, so we add the two modifiers together
				if modifiers[modifier] ~= nil then
					modifiers[modifier] = modifiers[modifier] + magnitude
				-- The inverse modifier already exists, so we subtract the negative value of the new modifier
				elseif modifiers[swappedModifier] ~= nil then
					modifiers[swappedModifier] = modifiers[swappedModifier] - magnitude
				-- The modifier does not exist, so create the modifier
				else
					modifiers[modifier] = magnitude
				end
			end
		end
		table.insert(ret, '\n|' .. Modifiers.getModifiersText(modifiers))
	end
	--]==]
	table.insert(ret, '\n|}')

	return table.concat(ret)
end

-- Gets a building and prepares all the relevant stats for the building, presented as an infobox
function p.getBuildingInfoBox(frame)
	local name = frame.args ~= nil and frame.args[1] or frame
	local building = p._getBuildingByName(name)
	if building == nil then
		return Shared.printError('No building named "' .. name .. '" exists in the data module')
	end

	local ret = {}
	-- Header
	table.insert(ret, '{| class="wikitable infobox"')
	-- Name
	table.insert(ret, '\n|-\n! ' .. Icons.getExpansionIcon(building.id) .. building.name)
	-- Icon
	table.insert(ret, '\n|-\n|style="text-align:center"| ' .. Icons.Icon({building.name, type='building', size='250', notext=true}))
	-- ID
	table.insert(ret, '\n|-\n| <b>Building ID:</b> ' .. building.id)
	-- Tier
	local tier = p._getTierText(building.tier, building.abyssalTier)
	table.insert(ret, '\n|-\n| <b>Requirements:</b><br/>' .. tier)

	-- Upgrades From
	table.insert(ret, '\n|-\n| <b>Base Cost:</b>')
	local upgradesFrom = p._getBuildingDowngrade(building)
	if upgradesFrom ~= nil then
		table.insert(ret, '<br/>' .. Icons.Icon({upgradesFrom.name, type='building'}))
	end
	-- Cost
	--table.insert(ret, '<br/>' .. p._getBuildingGroupedCostText(building))
	local function getGroupedText(building, groupFunc)
		local biomeGroups = groupFunc(building)
		if Shared.tableCount(biomeGroups) == 1 then
			-- If only one entry then simply output the cost
			return biomeGroups[1].cost
		else
			-- Otherwise, split by biome group
			local resultPart = {}
			table.insert(resultPart, '{| class="wikitable" style="text-align:center; margin: 0.25em 0 0 0"')
			for i, biomeGroup in ipairs(biomeGroups) do
				local biomeText = {}
				for j, biomeID in ipairs(biomeGroup.biomeIDs) do
					local biome = GameData.getEntityByID(Township.biomes, biomeID)
					table.insert(biomeText, Icons.Icon({biome.name, type='biome', notext=true, nolink=true, alt=biome.name}))
				end
				table.insert(resultPart, '\n|-\n| ' .. table.concat(biomeText, '<br/>'))
				table.insert(resultPart, '\n| ' .. biomeGroup.cost)
			end
			table.insert(resultPart, '\n|}')
			return table.concat(resultPart)
		end
	end

	table.insert(ret, '\n' .. getGroupedText(building, p._getBuildingGroupedCosts))

	-- Upgrades To
	local upgradesTo = p._getBuildingUpgrade(building)
	if upgradesTo ~= nil then
		table.insert(ret, '\n|-\n| <b>Upgrades To:</b>')
		table.insert(ret, '<br/>' .. Icons.Icon({upgradesTo.name, type='building'}))
		table.insert(ret, '\n' .. getGroupedText(upgradesTo, p._getBuildingGroupedCosts))
	end

	-- Maximum built
	local biomeCount = Shared.tableCount(building.biomes)
	local maxText = Num.formatnum(building.maxUpgrades)
	if biomeCount > 1 then
		maxText = maxText .. ' per biome, ' .. Num.formatnum(biomeCount * building.maxUpgrades) .. ' total'
	end
	table.insert(ret, '\n|-\n| <b>Maximum Built:</b><br/>' .. maxText)
	
	-- Benefits
	local benefits = p._getBuildingGroupedBenefitText(building)
	if benefits ~= nil and benefits ~= '' then
		table.insert(ret, '\n|-\n| <b>Provides:</b><br/>' .. benefits)
	end

	-- Biomes
	table.insert(ret, '\n|-\n| <b>Biomes:</b>')
	for _, biomeid in ipairs(building.biomes) do
		local biome = GameData.getEntityByID(Township.biomes, biomeid)
		table.insert(ret, '<br/>' .. Icons.Icon({biome.name, type='biome', nolink=true}))
	end

	-- End
	table.insert(ret, '\n|}')
	return table.concat(ret)
end

-- Returns an upgrade table of a building
function p.getBuildingUpgradeTable(frame)
	local buildingname = frame.args ~= nil and frame.args[1] or frame
	local building = p._getBuildingByName(buildingname)
	if building == nil then
		return Shared.printError('No building named "' .. buildingname .. '" exists in the data module')
	end

	-- Let's find the base building
	local baseBuilding = building
	while true do
		local previousBuilding = p._getBuildingDowngrade(baseBuilding)
		if previousBuilding ~= nil then
			baseBuilding = previousBuilding
		else
			break
		end
	end

	-- Let's make a list of all the buildings
	-- Return empty string if there is only 1 building in the upgrade chain (i.e. no upgrades/downgrades)
	local buildingList = {}
	local _curBuilding = baseBuilding
	while true do
		table.insert(buildingList, _curBuilding)
		_curBuilding = p._getBuildingUpgrade(_curBuilding)
		if _curBuilding == nil then
			break
		end
	end
	if #buildingList == 1 then
		return ''
	end

	local ret = {}
	table.insert(ret, '\n== Upgrade Chart ==')
	table.insert(ret, '\n{| class="wikitable" style="text-align:center"')

	-- Name
	table.insert(ret, '\n|-\n!colspan="2"| Name')
	for _, building in ipairs(buildingList) do
		table.insert(ret, '\n!' .. Icons.getExpansionIcon(building.id) .. Icons.Icon({building.name, type='building'}))
	end

	-- Tier
	table.insert(ret, '\n|-\n!colspan="2"| Requirements')
	for _, building in ipairs(buildingList) do
		table.insert(ret, '\n|' .. p._getTierText(building.tier, building.abyssalTier))
	end

	-- Cost
	local biomeCount = Shared.tableCount(baseBuilding.biomes)
	table.insert(ret, '\n|-\n!rowspan="' .. biomeCount .. '"| Cost')
	local firstBiome = true
	for _, biomeID in ipairs(baseBuilding.biomes) do
		local biome = GameData.getEntityByID(Township.biomes, biomeID)
		table.insert(ret, (firstBiome and '' or '\n|-') .. '\n! ' .. Icons.Icon({biome.name, type='biome', nolink=true}))
		for _, building in ipairs(buildingList) do
			local cost = p._getBuildingCostText(building, biomeID)
			table.insert(ret, '\n| ' .. cost)
		end
		firstBiome = false
	end

	-- Benefits
	local benefitText = {}
	table.insert(benefitText, '\n|-\n!rowspan="' .. biomeCount .. '"| Benefits')
	firstBiome = true
	local hasText = false
	for _, biomeID in ipairs(baseBuilding.biomes) do
		local biome = GameData.getEntityByID(Township.biomes, biomeID)
		table.insert(benefitText, (firstBiome and '' or '\n|-') .. '\n! ' .. Icons.Icon({biome.name, type='biome', nolink=true}))
		for _, building in ipairs(buildingList) do
			local benefit = p._getBuildingBenefitText(building, biomeID, true) or ''
			if not hasText and benefit ~= '' then
				hasText = true
			end
			table.insert(benefitText, '\n| ' .. benefit)
		end
		firstBiome = false
	end
	if hasText then
		-- Only add benefits rows if the building has benefits to display
		table.insert(ret, table.concat(benefitText))
	end

	-- End
	table.insert(ret, '\n|}')

	return table.concat(ret)
end

-- Returns a row containing a task given a title and a task table
function p._getTaskRow(title, task, isDailyTask)
	local ret = {}

	-- If has description, we will need to rowspan the title by 2, and insert a description with colspan 2
	local hasDescription = false
	if task.description ~= nil then
		hasDescription = true
	end
	local titlespan = hasDescription == true and 'rowspan="2"|' or ''

	-- Title
	table.insert(ret, '\n|-')
	table.insert(ret, '\n!' .. titlespan .. title)
	-- Description
	if hasDescription then
		table.insert(ret, '\n|colspan="2"|' .. task.description)
		table.insert(ret, '\n|-')
	end
	-- Requirements
	table.insert(ret, '\n|')
	-- Determines order of requirements output
	local reqOrder = {
		["items"] = 10,
		["monsters"] = 20,
		["monsterWithItems"] = 30,
		["skillXP"] = 40,
		["buildings"] = 50,
		["numPOIs"] = 60,
		["numRefinements"] = 70
	}
	local reqTextPart = {}

	local function getItemText(itemID)
		local item = Items.getItemByID(itemID)
		if item == nil then
			return Shared.printError('Unknown item: ' .. (itemID or 'nil'))
		else
			return Icons.Icon({item.name, type='item'})
		end
	end
	local function getMonsterText(monsterID)
		local monster = Monsters.getMonsterByID(monsterID)
		if monster == nil then
			return Shared.printError('Unknown monster: ' .. (monsterID or 'nil'))
		else
			return Icons.Icon({Monsters.getMonsterName(monster), type='monster'})
		end
	end

	for goalType, goalData in pairs(task.goals) do
		local typeOrder = reqOrder[goalType] or 0
		local goalText = nil
		if type(goalData) == 'table' then
			-- Goal data is a table
			for goalIdx, goalObj in ipairs(goalData) do
				if goalType == 'items' then
					goalText = Num.formatnum(goalObj.quantity) .. ' ' .. getItemText(goalObj.id)
				elseif goalType == 'monsters' then
					goalText = Num.formatnum(goalObj.quantity) .. ' ' .. getMonsterText(goalObj.id)
				elseif goalType == 'monsterWithItems' then
					local itemsText = {}
					for i, itemID in ipairs(goalObj.itemIDs) do
						table.insert(itemsText, getItemText(itemID))
					end
					goalText = Num.formatnum(goalObj.quantity) .. ' ' .. getMonsterText(goalObj.monsterID) .. ' with ' .. table.concat(itemsText, ', ') .. ' equipped'
				elseif goalType == 'skillXP' then
					local skillName = GameData.getSkillData(goalObj.id).name
					goalText = Num.formatnum(goalObj.quantity) .. ' ' .. Icons.Icon({skillName, type='skill'}) .. ' XP'
				elseif goalType == 'buildings' then
					local buildingName = p._GetBuildingByID(goalObj.id).name
					goalText = Num.formatnum(goalObj.quantity) .. ' ' .. Icons.Icon({buildingName, type='building'})
				elseif goalType == 'numPOIs' then
					local mapName = GameData.getEntityByID(GameData.skillData.Cartography.worldMaps, goalObj.worldMapID).name
					goalText = 'Discover ' .. Num.formatnum(goalObj.quantity) .. ' Points of Interest in ' .. Icons.Icon({'Cartography', type='skill'}) .. ' world map of ' .. mapName
				else
					goalText = Shared.printError('Unknown goal type: ' .. (goalType or 'nil'))
				end
				table.insert(reqTextPart, {
					["goalOrder"] = typeOrder,
					["subOrder"] = goalIdx,
					["text"] = goalText
				})
			end
		else
			-- Goal data is another value of some type
			if goalType == 'numRefinements' then
				goalText = 'Refine dig site maps in ' .. Icons.Icon({'Cartography', type='skill'}) .. ' ' .. Num.formatnum(goalData) .. ' times'
			else
				goalText = Shared.printError('Unknown goal type: ' .. (goalType or 'nil'))
			end
			table.insert(reqTextPart, {
				["goalOrder"] = typeOrder,
				["subOrder"] = 0,
				["text"] = goalText
			})
		end
	end

	table.sort(reqTextPart,
		function(a, b)
			if a.goalOrder == b.goalOrder then
				return a.subOrder < b.subOrder
			else
				return a.goalOrder < b.goalOrder
			end
		end
	)

	local requirements = {}
	for i, req in ipairs(reqTextPart) do
		table.insert(requirements, req.text)
	end
	-- We don't check tasks.requirements (so far it's only used to enumerate the Tutorial tasks so you only see 1 at a time)
	table.insert(ret, table.concat(requirements, '<br/>'))
	-- Rewards
	table.insert(ret, '\n|')
	local rewards = {}
	local rewardsVariableQty = {}
	if task.rewards.currencies ~= nil then
		for _, currReward in ipairs(task.rewards.currencies) do
			if isDailyTask and currReward.id ~= 'melvorD:GP' then
				table.insert(rewardsVariableQty, Icons._Currency(currReward.id))
			elseif not isDailyTask then
				table.insert(rewards, Icons._Currency(currReward.id, currReward.quantity))
			end
		end
	end
	for _, item in ipairs(task.rewards.items) do
		local itemname = GameData.getEntityByID('items', item.id).name
		table.insert(rewards, Num.formatnum(item.quantity)..' '..Icons.Icon({itemname, type='item'}))
	end
	for _, skill in ipairs(task.rewards.skillXP) do
		if not (isDailyTask and skill.id == 'melvorD:Township') then
			local skillname = GameData.getSkillData(skill.id).name
			table.insert(rewards, Num.formatnum(skill.quantity)..' '..Icons.Icon({skillname, type='skill'})..' XP')
		end
	end
	for _, townshipResource in ipairs(task.rewards.townshipResources) do
		local resourcename = p._getResourceByID(townshipResource.id).name
		table.insert(rewards, Num.formatnum(townshipResource.quantity)..' '..Icons.Icon({resourcename, type='resource'}))
	end
	if not Shared.tableIsEmpty(rewardsVariableQty) then
		table.insert(ret, '[[Township#Casual Tasks|Variable]] ' .. table.concat(rewardsVariableQty, ', ') .. '<br/>')
	end
	table.insert(ret, table.concat(rewards, '<br/>'))

	-- Unlock requirements, daily task specific
	if isDailyTask then
		table.insert(ret, '\n|' .. Shop.getRequirementString(task.requirements))
	end
	return table.concat(ret)
end

-- Returns all the tasks of a given category
-- TODO: Support casual tasks
function p.getTaskTable(frame)
	local category = frame.args ~= nil and frame.args[1] or frame
	local categoryData = GameData.getEntityByName(Township.taskCategories, category)
	local taskData, categoryName, isDailyTask = nil, nil, false
	if category == 'Daily' then
		isDailyTask = true
		taskData = Township.casualTasks
		categoryName = 'Casual'
	elseif categoryData ~= nil then
		taskData = Township.tasks
		categoryName = categoryData.name
	else
		return Shared.printError('Invalid task category specified: ' .. (tostring(category) or 'nil'))
	end

	local taskcount = 0
	local ret = {}
	table.insert(ret, '{| class="wikitable lighttable stickyHeader mw-collapsible" style="text-align:left"')
	table.insert(ret, '\n|- class="headerRow-0"')
	table.insert(ret, '\n!Task')
	table.insert(ret, '\n!Requirements')
	table.insert(ret, '\n!Rewards')
	if isDailyTask then
		table.insert(ret, '<br/>(In addition to [[Township#Casual Tasks|Variable]] ' .. Icons._Currency('melvorD:GP') .. ' & ' .. Icons.Icon({'Township', type='skill', notext=true}) .. ' XP)')
	end
	if isDailyTask then
		table.insert(ret, '\n!Unlock Requirements')
	end
	
	for _, task in ipairs(taskData) do
		-- Filter out other categories
		local categoryID, categoryNS, categoryLocalID = '', '', ''
		if categoryData ~= nil then
			categoryID = categoryData.id
			categoryNS, categoryLocalID = Shared.getLocalID(categoryID)
		end
		if isDailyTask or task.category == categoryID or task.category == categoryLocalID then
			taskcount = taskcount + 1
			local title = categoryName .. ' ' .. taskcount
			table.insert(ret, p._getTaskRow(title, task, isDailyTask))
		end
	end
	table.insert(ret, '\n|}')
	return table.concat(ret)
end

-- Returns a table containing all the tasks that reference an item or monster
-- e.g. p.getTaskReferenceTable({'Chicken Coop', 'dungeon'})
-- name = item or monster name
-- type = 'item' or 'monster' or 'dungeon'
function p.getTaskReferenceTable(frame)
	-- Returns a set containing all the desired IDs
	local function GetReferenceIDs(referenceName, referenceType)
		local IDs = {}
		if referenceType == 'dungeon' then
			-- We get the tasks associated with all monsters in the dungeon
			local area = nil
			local areaTypes = {'dungeons', 'abyssDepths', 'strongholds'}
			for _, areaType in ipairs(areaTypes) do
				area = GameData.getEntityByName(areaType, referenceName)
				if area ~= nil then
					break
				end
			end
			local monsters = area.monsterIDs
			for _, monster in ipairs(monsters) do
				IDs[monster] = true
			end
		end
		if referenceType == 'item' then
			IDs[GameData.getEntityByName('items', referenceName).id] = true
		end
		if referenceType == 'monster' then
			IDs[Monsters.getMonster(referenceName).id] = true
		end
		return IDs
	end
	-- For a task, returns where to search for the desired IDs, given the type
	local function GetGetSearchTables(referenceType)
		local function searchItems(task)
			return {task.goals.items, task.rewards.items}
		end
		local function searchMonsters(task)
			return {task.goals.monsters}
		end
		-- item -> searchItems; monster or dungeon -> searchMonsters
		return referenceType == 'item' and searchItems or searchMonsters
	end

	local args = frame.args ~= nil and frame.args or frame
	local referenceName = Shared.fixPagename(args[1])
	local referenceType = args[2]
	local referenceIDs = GetReferenceIDs(referenceName, referenceType)
	-- GetSearchTables = function searchItems/Monsters(task)
	local GetSearchTables = GetGetSearchTables(referenceType)

	local function checkTask(task)
		local function checkID(entry)
			return referenceIDs[entry.id] ~= nil
		end
		for _, searchTable in pairs(GetSearchTables(task)) do -- ipairs won't work if first table is nil
			-- Check to see if the table contains any of the IDs in referenceIDs
			if searchTable[1] ~= nil then -- Make sure table is not empty
				if #GameData.getEntities(searchTable, checkID) ~= 0 then -- Make sure we have at least 1 match
					return true
				end
			end
		end
		return false
	end
	-- Find all tasks that contain the desired ids
	local tasks = GameData.getEntities(Township.tasks, checkTask)
	if #tasks == 0 then
		return ''
	end

	-- Build the table
	local ret = {}
	table.insert(ret, '==Tasks==')
	table.insert(ret, '\n{| class="wikitable" style="text-align:left"')
	table.insert(ret, '\n!Task')
	table.insert(ret, '\n!Requirements')
	table.insert(ret, '\n!Rewards')
	for _, task in ipairs(tasks) do
		-- Some categories have a local ID, resolve this before looking up the task category
		local taskNS, taskLocalID = Shared.getLocalID(task.id)
		local catID = Shared.getNamespacedID(taskNS,  task.category)
		local categoryname = GameData.getEntityByID(Township.taskCategories, catID).name
		local title = '[[Township/Tasks#'..categoryname..'|'..categoryname..']]'
		table.insert(ret, p._getTaskRow(title, task, false))
	end
	table.insert(ret, '\n|}')
	return table.concat(ret)
end

return p