Module:Skills: Difference between revisions

From Melvor Idle
(Move Farming functions to Module:Skills/Gathering)
(Add Archaeology recipe key)
 
(47 intermediate revisions by 5 users not shown)
Line 15: Line 15:


local p = {}
local p = {}
local ItemData = mw.loadData('Module:Items/data')
local SkillData = mw.loadData('Module:Skills/data')


local Shared = require('Module:Shared')
local Shared = require('Module:Shared')
local Constants = require('Module:Constants')
local Constants = require('Module:Constants')
local Common = require('Module:Common')
local GameData = require('Module:GameData')
local SkillData = GameData.skillData
local Modifiers = require('Module:Modifiers')
local Items = require('Module:Items')
local Items = require('Module:Items')
local Icons = require('Module:Icons')
local Icons = require('Module:Icons')
local Num = require('Module:Number')
-- Given a skill ID, returns the key for that skill's recipe data.
-- If the skill has no recipes (e.g. is a combat skill) then the
-- return value is nil
function p.getSkillRecipeKey(skillID)
-- Convert skillID to local ID if not already
local ns, localSkillID = GameData.getLocalID(skillID)
local recipeIDs = {
["Woodcutting"] = 'trees',
["Fishing"] = 'fish',
["Firemaking"] = 'logs',
["Mining"] = 'rockData',
["Thieving"] = 'npcs',
["Agility"] = 'obstacles',
["Cooking"] = 'recipes',
["Smithing"] = 'recipes',
["Farming"] = 'recipes',
["Summoning"] = 'recipes',
["Fletching"] = 'recipes',
["Crafting"] = 'recipes',
["Runecrafting"] = 'recipes',
["Herblore"] = 'recipes',
["Astrology"] = 'recipes',
["Archaeology"] = 'digSites',
["Harvesting"] = 'veinData'
}
return recipeIDs[localSkillID]
end
-- Given a skill ID & recipe, returns the skill level requirement for
-- that recipe and a boolean value indicating whether the level if abyssal or not.
-- If the level could not be determined, then the return value is nil, nil
function p.getRecipeLevelRealm(skillID, recipe)
local level, isAbyssal = nil, nil
-- Convert skillID to local ID if not already
local ns, localSkillID = GameData.getLocalID(skillID)
local realmID = p.getRecipeRealm(recipe)
if localSkillID == 'Agility' then
local course = GameData.getEntityByProperty(SkillData.Agility.courses, 'realm', realmID)
isAbyssal = (realmID == 'melvorItA:Abyssal')
-- For Agility, level is derived from obstacle category
if recipe.category ~= nil then
-- Obstacle
local slot = course.obstacleSlots[recipe.category + 1]
if isAbyssal then
level = slot.abyssalLevel
else
level = slot.level
end
elseif recipe.slot ~= nil then
-- Pillar
level = course.pillarSlots[recipe.slot + 1].level
end
elseif recipe.abyssalLevel ~= nil then
level, isAbyssal = recipe.abyssalLevel, true
else
-- For all other skills, the recipe should have a level property
level, isAbyssal = recipe.level, false
end
return level, isAbyssal
end


local MasteryCheckpoints = {.1, .25, .5, .95}
function p.getRecipeLevel(skillID, recipe)
local level, isAbyssal = p.getRecipeLevelRealm(skillID, recipe)
return level
end


-- Thieving
function p.getRecipeRequirementText(skillName, recipe)
function p.getThievingNPC(npcName)
local reqText = {}
local result = nil
if recipe.abyssalLevel ~= nil and recipe.abyssalLevel > 0 then
for i, npc in Shared.skpairs(SkillData.Thieving.NPCs) do
table.insert(reqText, Icons._SkillReq(skillName, recipe.abyssalLevel, false, 'melvorItA:Abyssal'))
if npc.name == npcName then
elseif recipe.level ~= nil and recipe.level > 0 then
result = Shared.clone(npc)
table.insert(reqText, Icons._SkillReq(skillName, recipe.level, false))
break
end
if recipe.totalMasteryRequired ~= nil then
table.insert(reqText, Num.formatnum(recipe.totalMasteryRequired) .. ' ' .. Icons.Icon({skillName, type='skill', notext=true}) .. ' ' .. Icons.Icon({'Mastery'}))
end
local reqsData = {}
if type(recipe.requirements) == 'table' then
reqsData = Shared.shallowClone(recipe.requirements)
end
if recipe.shopItemPurchased ~= nil then
-- Mining requirements are stored differently than other skills like
-- Woodcutting, standardize here
table.insert(reqsData, {
["type"] = 'ShopPurchase',
["purchaseID"] = recipe.shopItemPurchased,
["count"] = 1
})
end
if not Shared.tableIsEmpty(reqsData) then
local reqs = Common.getRequirementString(reqsData)
if reqs ~= nil then
table.insert(reqText, reqs)
end
end
end
end
return result
return table.concat(reqText, '<br/>')
end
 
function p.standardRecipeSort(skillID, recipeA, recipeB)
local levelA, isAbyssalA = p.getRecipeLevelRealm(skillID, recipeA)
local levelB, isAbyssalB = p.getRecipeLevelRealm(skillID, recipeB)
local isAbyssalNumA, isAbyssalNumB = (isAbyssalA and 1) or 0, (isAbyssalB and 1) or 0
 
return (isAbyssalA == isAbyssalB and levelA < levelB) or isAbyssalNumA < isAbyssalNumB
end
 
 
function p.getRecipeRealm(recipe)
return recipe.realm or 'melvorD:Melvor'
end
 
function p.getRealmFromName(realmName)
local realm = nil
if realmName == nil or realmName == '' then
-- Default realm
realm = GameData.getEntityByID('realms', 'melvorD:Melvor')
else
realm = GameData.getEntityByName('realms', realmName)
end
return realm
end
end


function p.getThievingNPCArea(npc)
function p.getMasteryActionCount(skillID, realmID, levelLimit)
if type(npc) == 'string' then
local actCount = 0
npc = p.getThievingNPC(npc)
local skillNS, skillLocalID = Shared.getLocalID(skillID)
local skillData = SkillData[skillLocalID]
local recipeKey = p.getSkillRecipeKey(skillLocalID)
if recipeKey ~= nil then
local recipeData = skillData[recipeKey]
for i, recipe in ipairs(recipeData) do
if (
p.getRecipeRealm(recipe) == realmID
and (recipe.noMastery == nil or not recipe.noMastery)
and (levelLimit == nil or p.getRecipeLevel(skillLocalID, recipe) <= levelLimit)
) then
actCount = actCount + 1
end
end
end
end
return actCount
end
-- Thieving
function p.getThievingNPCByID(npcID)
return GameData.getEntityByID(SkillData.Thieving.npcs, npcID)
end
function p.getThievingNPC(npcName)
return GameData.getEntityByName(SkillData.Thieving.npcs, npcName)
end


local result = nil
function p.getThievingNPCArea(npc)
for i, area in Shared.skpairs(SkillData.Thieving.Areas) do
for i, area in ipairs(SkillData.Thieving.areas) do
for j, npcID in pairs(area.npcs) do
for j, npcID in ipairs(area.npcIDs) do
if npcID == npc.id then
if npcID == npc.id then
result = area
return area
break
end
end
end
end
end
end
return result
end
end


Line 81: Line 213:
local npc = p.getThievingNPC(npcName)
local npc = p.getThievingNPC(npcName)
if npc == nil then
if npc == nil then
return "ERROR: Invalid Thieving NPC "..npcName.."[[Category:Pages with script errors]]"
return Shared.printError('Invalid Thieving NPC ' .. npcName)
end
end


Line 89: Line 221:
function p.getThievingSourcesForItem(itemID)
function p.getThievingSourcesForItem(itemID)
local resultArray = {}
local resultArray = {}
local areaNPCs = {}
local areaNPCs = {}


--First check area unique drops
--First check area unique drops
--If an area drops the item, add all the NPC ids to the list so we can add them later
--If an area drops the item, add all the NPC ids to the list so we can add them later
if not result then
for i, area in pairs(SkillData.Thieving.areas) do
for i, area in pairs(SkillData.Thieving.Areas) do
for j, drop in pairs(area.uniqueDrops) do
for j, drop in pairs(area.uniqueDrops) do
if drop.id == itemID then
if drop.itemID == itemID then
for k, npcID in ipairs(area.npcIDs) do
for k, npcID in pairs(area.npcs) do
areaNPCs[npcID] = { qty = drop.quantity, area = area }
areaNPCs[npcID] = drop.qty
end
break
end
end
break
end
end
end
end
Line 108: Line 237:


--Now go through and get drop chances on each NPC if needed
--Now go through and get drop chances on each NPC if needed
for i, npc in pairs(SkillData.Thieving.NPCs) do
for i, npc in pairs(SkillData.Thieving.npcs) do
local totalWt = 0
local totalWt = 0
local dropWt = 0
local dropWt = 0
local dropQty = 0
local dropQty = { min = 0, max = 0 }
for j, drop in pairs(npc.lootTable) do
for j, drop in ipairs(npc.lootTable) do
totalWt = totalWt + drop[2]
totalWt = totalWt + drop.weight
if drop[1] == itemID then
if drop.itemID == itemID then
dropWt = drop[2]
dropWt = drop.weight
dropQty = drop[3]
dropQty = { min = drop.minQuantity, max = drop.maxQuantity }
end
end
end
end
if dropWt > 0 then
if dropWt > 0 then
table.insert(resultArray, {npc = npc.name, minQty = 1, maxQty = dropQty, wt = dropWt * SkillData.Thieving.ItemChance, totalWt = totalWt * 100, level = npc.level})
table.insert(resultArray, {npc = npc.name, minQty = dropQty.min, maxQty = dropQty.max, wt = dropWt * SkillData.Thieving.itemChance, totalWt = totalWt * 100, level = npc.level, abyssalLevel = npc.abyssalLevel, npcID = npc.id, type = 'npc'})
end
end


--Chance of -1 on unique drops is to indicate variable chance
--Chance of -1 on unique drops is to indicate variable chance
if npc.uniqueDrop ~= nil and npc.uniqueDrop.itemID == itemID then
if npc.uniqueDrop ~= nil and npc.uniqueDrop.id == itemID then
table.insert(resultArray, {npc = npc.name, minQty = npc.uniqueDrop.qty, maxQty = npc.uniqueDrop.qty, wt = -1, totalWt = -1, level = npc.level})
table.insert(resultArray, {npc = npc.name, minQty = npc.uniqueDrop.quantity, maxQty = npc.uniqueDrop.quantity, wt = -1, totalWt = -1, level = npc.level, abyssalLevel = npc.abyssalLevel, npcID = npc.id, type = 'npcUnique'})
end
end


if areaNPCs[npc.id] ~= nil then
local areaNPC = areaNPCs[npc.id]
table.insert(resultArray, {npc = npc.name, minQty = areaNPCs[npc.id], maxQty = areaNPCs[npc.id], wt = SkillData.Thieving.AreaUniqueChance, totalWt = 100, level = npc.level})
if areaNPC ~= nil then
table.insert(resultArray, {npc = npc.name, minQty = areaNPC.qty, maxQty = areaNPC.qty, wt = SkillData.Thieving.baseAreaUniqueChance, totalWt = 100, level = npc.level, abyssalLevel = npc.abyssalLevel, npcID = npc.id, area = areaNPC.area, type = 'areaUnique'})
end
end
end
end


for i, drop in pairs(SkillData.Thieving.RareItems) do
for i, drop in ipairs(SkillData.Thieving.generalRareItems) do
if drop.itemID == itemID then
if drop.itemID == itemID then
table.insert(resultArray, {npc = 'all', minQty = 1, maxQty = 1, wt = 1, totalWt = Shared.round2(1/(drop.chance/100), 0), level = 1})
if drop.npcs == nil then
table.insert(resultArray, {npc = 'all', minQty = 1, maxQty = 1, wt = 1, totalWt = Num.round2(1/(drop.chance/100), 0), level = 1, npcID = itemID, type = 'generalRare'})
else
for j, npcID in ipairs(drop.npcs) do
local npc = p.getThievingNPCByID(npcID)
if npc ~= nil then
table.insert(resultArray, {npc = npc.name, minQty = 1, maxQty = 1, wt = 1, totalWt = Num.round2(1/(drop.chance/100), 0), level = npc.level, abyssalLevel = npc.abyssalLevel, npcID = npc.id, type = 'generalRare'})
end
end
end
end
end
end
end
Line 144: Line 283:
-- Astrology
-- Astrology
function p.getConstellationByID(constID)
function p.getConstellationByID(constID)
return SkillData.Astrology.Constellations[constID]
return GameData.getEntityByID(SkillData.Astrology.recipes, constID)
end
end


function p.getConstellation(constName)
function p.getConstellation(constName)
for i, const in ipairs(SkillData.Astrology.Constellations) do
return GameData.getEntityByName(SkillData.Astrology.recipes, constName)
if const.name == constName then
return const
end
end
return nil
end
end


function p.getConstellations(checkFunc)
function p.getConstellations(checkFunc)
return GameData.getEntities(SkillData.Astrology.recipes, checkFunc)
end
-- Combines Astrology constellation modifiers into an object similar to other entities,
-- and multiplies the values up to their maximum possible amount
function p._getConstellationModifiers(cons)
local result = {}
local result = {}
for i, const in ipairs(SkillData.Astrology.Constellations) do
local modKeys = { 'standardModifiers', 'uniqueModifiers', 'abyssalModifiers' }
if checkFunc(const) then
table.insert(result, const)
end
end
return result
end


-- For a given constellation cons and modifier value modValue, generates and returns
for _, keyID in ipairs(modKeys) do
-- a table of modifiers, much like any other item/object elsewhere in the game.
result[keyID] = {}
-- includeStandard: true|false, determines whether standard modifiers are included
local mods = cons[keyID]
-- includeUnique: true|false, determines whether unique modifiers are included
if mods ~= nil then
-- isDistinct: true|false, if true, the returned list of modifiers is de-duplicated
for _, mod in ipairs(mods) do
-- asKeyValue: true|false, if true, returns key/value pairs like usual modifier objects
local newModObj = {}
function p._buildAstrologyModifierArray(cons, modValue, includeStandard, includeUnique, isDistinct, asKeyValue)
local multValue = mod.maxCount
-- Temporary function to determine if the table already contains a given modifier
local subKeys = { 'modifiers', 'enemyModifiers' }
local containsMod = function(modList, modNew)
for _, subKey in ipairs(subKeys) do
for i, modItem in ipairs(modList) do
local modAdj = Shared.clone(mod[subKey])
-- Check mod names & value data types both equal
if type(modAdj) == 'table' then
if modItem[1] == modNew[1] and type(modItem[2]) == type(modNew[2]) then
for modName, modValueDef in pairs(modAdj) do
if type(modItem[2]) == 'table' then
if type(modValueDef) == 'table' then
if Shared.tablesEqual(modItem[2], modNew[2]) then
if modValueDef[1] ~= nil then
return true
-- Table of multiple values
for i, subValue in ipairs(modValueDef) do
if type(subValue) == 'table' and subValue.value ~= nil then
subValue.value = subValue.value * multValue
elseif type(subValue) == 'number' then
modValueDef[i] = subValue * multValue
end
end
elseif modValueDef.value ~= nil then
-- Table but with a single value
modValueDef.value = modValueDef.value * multValue
end
elseif type(modValueDef) == 'number' then
-- Single value
modAdj[modName] = modValueDef * multValue
end
end
end
elseif modItem[2] == modNew[2] then
newModObj[subKey] = modAdj
return true
end
end
end
end
table.insert(result[keyID], newModObj)
end
end
return false
end
end
local addToArray = function(modArray, modNew)
if not isDistinct or (isDistinct and not containsMod(modArray, modNew)) then
table.insert(modArray, modNew)
end
end
local modTypes = {}
if includeStandard then
table.insert(modTypes, 'standardModifiers')
end
if includeUnique then
table.insert(modTypes, 'uniqueModifiers')
end
local modArray = {}
local isSkillMod = {}
for _, modType in ipairs(modTypes) do
for i, skillMods in ipairs(cons[modType]) do
local skillID = cons.skills[i]
if skillID ~= nil then
for j, modName in ipairs(skillMods) do
local modBaseName, modText, sign, isNegative, unsign, modBase = Constants.getModifierDetails(modName)
-- Check if modifier varies by skill, and amend the modifier value accordingly
local modVal = modValue
if Shared.contains(modText, '{SV0}') then
isSkillMod[modName] = true
modVal = {skillID, modValue}
end
addToArray(modArray, {modName, modVal})
end
end
end
end
if asKeyValue then
local modArrayKV = {}
for i, modDefn in ipairs(modArray) do
local modName, modVal = modDefn[1], modDefn[2]
local isSkill = isSkillMod[modName]
if modArrayKV[modName] == nil then
modArrayKV[modName] = (isSkill and { modVal } or modVal)
elseif isSkill then
table.insert(modArrayKV[modName], modVal)
else
modArrayKV[modName] = modArrayKV[modName] + modVal
end
end
return modArrayKV
else
return modArray
end
end
return result
end
end


Line 248: Line 346:
local skillID = Constants.getSkillID(skillName)
local skillID = Constants.getSkillID(skillName)
if skillID == nil then
if skillID == nil then
return "ERROR: Failed to find a skill ID for "..skillName
return Shared.printError('Failed to find a skill ID for ' .. skillName)
end
end


local unlockTable = SkillData.MasteryUnlocks[skillID]
local _, localSkillID = GameData.getLocalID(skillID)
-- Clone so that we can sort by level
local unlockTable = Shared.shallowClone(SkillData[localSkillID].masteryLevelUnlocks)
if unlockTable == nil then
if unlockTable == nil then
return 'ERROR: Failed to find Mastery Unlock data for '..skillName
return Shared.printError('Failed to find Mastery Unlock data for ' .. skillName)
end
end
table.sort(unlockTable, function(a, b) return (a.level == b.level and a.descriptionID < b.descriptionID) or a.level < b.level end)


local result = '{|class="wikitable"\r\n!Level!!Unlock'
local result = '{|class="wikitable"\r\n!Level!!Unlock'
for i, unlock in Shared.skpairs(unlockTable) do
for i, unlock in ipairs(unlockTable) do
result = result..'\r\n|-'
result = result..'\r\n|-'
result = result..'\r\n|'..unlock.level..'||'..unlock.unlock
result = result..'\r\n|'..unlock.level..'||'..unlock.description
end
end
result = result..'\r\n|}'
result = result..'\r\n|}'
Line 266: Line 367:


function p.getMasteryCheckpointTable(frame)
function p.getMasteryCheckpointTable(frame)
local skillName = frame.args ~= nil and frame.args[1] or frame
local args = frame.args ~= nil and frame.args or frame
local skillName = args[1]
local realmName = args.realm
 
local realm = p.getRealmFromName(realmName)
if realm == nil then
return Shared.printError('Failed to find a realm with name ' .. (realmName or 'nil'))
end
local skillID = Constants.getSkillID(skillName)
local skillID = Constants.getSkillID(skillName)
if skillID == nil then
if skillID == nil then
return "ERROR: Failed to find a skill ID for "..skillName
return Shared.printError('Failed to find a skill ID for ' .. skillName)
end
end


if SkillData.MasteryCheckpoints[skillID] == nil then
local _, localSkillID = GameData.getLocalID(skillID)
return 'ERROR: Failed to find Mastery Unlock data for '..skillName
local checkpoints = SkillData[localSkillID].masteryPoolBonuses
if checkpoints == nil then
return Shared.printError('Failed to find Mastery checkpoint data for ' .. skillName)
end
end


local bonuses = SkillData.MasteryCheckpoints[skillID].bonuses
local totalPoolXP = p.getMasteryActionCount(localSkillID, realm.id) * 500000
local totalPoolXP = SkillData.MasteryPoolXP[skillID + 1]
 
local result = '{|class="wikitable"\r\n!Pool %!!style="width:100px"|Pool XP!!Bonus'
local result = '{|class="wikitable"\r\n!Pool %!!style="width:100px"|Pool XP!!Bonus'
for i, bonus in Shared.skpairs(bonuses) do
for i, checkpointData in ipairs(checkpoints) do
result = result..'\r\n|-'
if checkpointData.realm == realm.id then
result = result..'\r\n|'..(MasteryCheckpoints[i] * 100)..'%||'
local chkDesc = Modifiers.getModifiersText(checkpointData.modifiers, false, false)
result = result..Shared.formatnum(totalPoolXP * MasteryCheckpoints[i])..' xp||'..bonus
local chkPercent = checkpointData.percent
result = result..'\r\n|-'
result = result..'\r\n|'..chkPercent..'%||'
result = result..Num.formatnum(math.floor(totalPoolXP * chkPercent / 100))..' xp||'..chkDesc
end
end
end
result = result..'\r\n|-\r\n!colspan="2"|Total Mastery Pool XP'
result = result..'\r\n|-\r\n!colspan="2"|Total Mastery Pool XP'
result = result..'\r\n|'..Shared.formatnum(totalPoolXP)
result = result..'\r\n|'..Num.formatnum(totalPoolXP)
result = result..'\r\n|}'
result = result..'\r\n|}'
return result
return result
Line 292: Line 404:


function p.getMasteryTokenTable()
function p.getMasteryTokenTable()
-- Defines which skill levels should be included within the output
local skillLevels = {
{
["id"] = 'Base',
["level"] = 99,
["description"] = '[[Full Version|Base Game]] (Level 99)'
}, {
["id"] = 'TotH',
["level"] = 120,
["description"] = Icons.TotH() .. ' [[Throne of the Herald Expansion|Throne of the Herald]] (Level 120)'
}
}
local baseTokenChance = 18500
local baseTokenChance = 18500
local masterySkills = {}
local masteryActionCount = {}
local CCI_ID = 'melvorD:Clue_Chasers_Insignia'
local CCI = Items.getItemByID(CCI_ID)
if CCI == nil then
return Shared.printError('Failed to find item with ID ' .. CCI_ID)
end


-- Find all mastery tokens
local tokens = Items.getItems(function(item) return item.itemType == 'MasteryToken' end)
local masteryTokens = Items.getItems(function(item) return item.isToken ~= nil and item.skill ~= nil and item.isToken end)
local tokenItems = {}
for i, item in pairs(masteryTokens) do
for _, item in ipairs(tokens) do
local milestones = SkillData.Milestones[item.skill + 1]
if item.realm == 'melvorD:Melvor' and item.skill ~= nil then
if milestones ~= nil then
local skillNS, skillLocalID = Shared.getLocalID(item.skill)
table.insert(masterySkills, {tokenRef = i, skillID = item.skill, milestoneCount = milestones})
tokenItems[skillLocalID] = item
end
end
end
table.sort(masterySkills, function(a, b)
if a['milestoneCount'] == b['milestoneCount'] then
return a['skillID'] < b['skillID']
else
return a['milestoneCount'] > b['milestoneCount']
end
end)
-- Generate output table
local resultPart = {}
local CCI = Items.getItem('Clue Chasers Insignia')
local CCIIcon = Icons.Icon({'Clue Chasers Insignia', type='item', notext=true})
if CCI == nil then return '' end
table.insert(resultPart, '{| class="wikitable sortable"')
table.insert(resultPart, '\r\n!rowspan="2"|Token!!rowspan="2"|Skill!!colspan="2"|Approximate Mastery Token Chance')
table.insert(resultPart, '\r\n|-\r\n!Without ' .. CCIIcon .. '!!With ' .. CCIIcon)
for i, m in ipairs(masterySkills) do
local token = masteryTokens[m.tokenRef]
local denom = math.floor(baseTokenChance / m['milestoneCount'])
local denomCCI = Shared.round(baseTokenChance / (m['milestoneCount'] * (1 + CCI.increasedItemChance / 100)), 0, 0)
table.insert(resultPart, '\r\n|-')
table.insert(resultPart, '\r\n|style="text-align:center"|' .. Icons.Icon({token.name, type='item', size=50, notext=true}))
table.insert(resultPart, '\r\n|' .. Icons.Icon({Constants.getSkillName(m['skillID']), type='skill'}))
table.insert(resultPart, '\r\n|style="text-align:right" data-sort-value="' .. denom .. '"|1/' .. Shared.formatnum(denom))
table.insert(resultPart, '\r\n|style="text-align:right" data-sort-value="' .. denomCCI .. '"|1/' .. Shared.formatnum(denomCCI))
end
table.insert(resultPart, '\r\n|}')
return table.concat(resultPart)
end
-- Skill unlock costs for Adventure game mode
function p.getSkillUnlockCostTable()
local returnPart = {}
table.insert(returnPart, '{| class="wikitable stickyHeader"\r\n|- class="headerRow-0"\r\n!Unlock!!Cost!!Cumulative Cost')
local accCost = 0
for i, cost in ipairs(SkillData.SkillUnlockCosts) do
accCost = accCost + cost
table.insert(returnPart, '|-')
table.insert(returnPart, '|' .. i .. '||' .. Icons.GP(cost) .. '||' .. Icons.GP(accCost))
end
table.insert(returnPart, '|}')
return table.concat(returnPart, '\r\n')
end
-- Accepts 1 parameter, being either:
--  'Smelting', for which a table of all bars is generated, or
--  A bar or tier name, which if valid generates a table of all smithing recipes using that bar/tier
function p.getSmithingTable(frame)
local tableType = frame.args ~= nil and frame.args[1] or frame
tableType = Shared.splitString(tableType, ' ')[1]
-- Translates Smithing category names to Smithing recipe data categories
local categoryMap = {
['Smelting'] = 0,
['Bronze'] = 1,
['Iron'] = 2,
['Steel'] = 3,
['Mithril'] = 4,
['Adamant'] = 5,
['Adamantite'] = 5,
['Rune'] = 6,
['Runite'] = 6,
['Dragon'] = 7,
['Dragonite'] = 7
}
local categoryID = categoryMap[tableType]
if categoryID == nil then
return 'ERROR: Invalid Smithing category: "' .. tableType .. '"[[Category:Pages with script errors]]'
end
end


-- Build a list of recipes to be included, and a list of bars while we're at it
-- Iterate over each skill with mastery, determining the number of
-- The bar list will be used later for value/bar calculations
-- mastery actions for each
local recipeList, barIDList = {}, {}
for skillLocalID, skill in pairs(SkillData) do
for i, recipe in ipairs(SkillData.Smithing.Recipes) do
if skill.masteryPoolBonuses ~= nil then
if recipe.category == categoryID then
local actCount = { ["skill"] = skill, ["token"] = tokenItems[skillLocalID] }
local recipeItem = Items.getItemByID(recipe.itemID)
for i, levelDef in ipairs(skillLevels) do
if recipeItem ~= nil then
actCount[levelDef.id] = p.getMasteryActionCount(skillLocalID, 'melvorD:Melvor', levelDef.level)
table.insert(recipeList, { id = i, level = recipe.level, itemName = recipeItem.name, itemValue = recipeItem.sellsFor })
end
end
elseif recipe.category == 0 then
table.insert(masteryActionCount, actCount)
barIDList[recipe.itemID] = true
end
end
end
end


local firstID = skillLevels[1].id
table.sort(masteryActionCount,
function(a, b)
if a[firstID] == b[firstID] then
return a.skill.name < b.skill.name
else
return a[firstID] > b[firstID]
end
end)
-- Generate output table
-- Generate output table
local resultPart = {}
local resultPart = {}
table.insert(resultPart, '{|class="wikitable sortable stickyHeader"')
local CCIIcon = Icons.Icon({CCI.name, type='item', notext=true})
table.insert(resultPart, '\r\n|-class="headerRow-0"')
local columnPairs = Shared.tableCount(skillLevels)
table.insert(resultPart, '\r\n!Item!!Name!!'..Icons.Icon({'Smithing', type='skill', notext=true})..' Level!!XP!!Value!!Ingredients')
 
--Adding value/bar for things other than smelting
-- Generate header
if categoryID > 0 then
table.insert(resultPart, '{| class="wikitable sortable"')
table.insert(resultPart, '!!Value/Bar')
table.insert(resultPart, '\n!rowspan="3"|Token!!rowspan="3"|Skill!!colspan="' .. columnPairs * 2 .. '"|Approximate Mastery Token Chance')
table.insert(resultPart, '\n|-')
for i, levelDef in ipairs(skillLevels) do
table.insert(resultPart, '\n!colspan="2"| ' .. levelDef.description)
end
end
table.insert(resultPart, '\n|-' .. string.rep('\n!Without ' .. CCIIcon .. '\n!With ' .. CCIIcon, columnPairs))


table.sort(recipeList, function(a, b)
for i, rowData in ipairs(masteryActionCount) do
if a.level ~= b.level then
local token = rowData.token
return a.level < b.level
table.insert(resultPart, '\n|-')
else
local tokenImg = (token == nil and '?') or Icons.Icon({token.name, type='item', notext=true})
return a.itemName < b.itemName
table.insert(resultPart, '\n|style="text-align:center"|' .. tokenImg)
end
table.insert(resultPart, '\n|' .. Icons.Icon({rowData.skill.name, type='skill'}))
end)


for i, recipeDef in ipairs(recipeList) do
for j, levelDef in ipairs(skillLevels) do
local recipe = SkillData.Smithing.Recipes[recipeDef.id]
local actCount = rowData[levelDef.id]
local totalValue = recipe.baseQuantity * recipeDef.itemValue
local denom, denomCCI = 0, 0
-- Determine the bar quantity & build the recipe cost string
if actCount > 0 then
local barQty, costString = 0, {}
denom = math.floor(baseTokenChance / actCount)
for j, itemCost in ipairs(recipe.itemCosts) do
denomCCI = Num.round(baseTokenChance / (actCount * (1 + CCI.modifiers.offItemChance / 100)), 0, 0)
local costItem = Items.getItemByID(itemCost.id)
if costItem ~= nil then
table.insert(costString, Icons.Icon({costItem.name, type='item', qty=itemCost.qty, notext=true}))
end
if barIDList[itemCost.id] then
barQty = barQty + itemCost.qty
end
end
end
table.insert(resultPart, '\n|style="text-align:right" data-sort-value="' .. denom .. '"|1/' .. Num.formatnum(denom))
 
table.insert(resultPart, '\n|style="text-align:right" data-sort-value="' .. denomCCI .. '"|1/' .. Num.formatnum(denomCCI))
table.insert(resultPart, '\r\n|-')
table.insert(resultPart, '\r\n| ' .. Icons.Icon({recipeDef.itemName, type='item', size=50, notext=true}))
table.insert(resultPart, '\r\n| ')
if recipe.baseQuantity > 1 then
table.insert(resultPart, recipe.baseQuantity .. 'x ')
end
table.insert(resultPart, Icons.Icon({recipeDef.itemName, type='item', noicon=true}))
table.insert(resultPart, '\r\n|data-sort-value="' .. recipe.level .. '"| ' .. Icons._SkillReq('Smithing', recipe.level))
table.insert(resultPart, '\r\n|data-sort-value="' .. recipe.baseXP .. '"| ' .. Shared.formatnum(recipe.baseXP))
table.insert(resultPart, '\r\n|data-sort-value="' .. totalValue .. '"| ' .. Icons.GP(recipeDef.itemValue))
if recipe.baseQuantity > 1 then
table.insert(resultPart, ' (x' .. recipe.baseQuantity .. ')')
end
table.insert(resultPart, '\r\n| ' .. table.concat(costString, ', '))
if categoryID > 0 then
local barVal, barValTxt = 0, 'N/A'
if barQty > 0 then
barVal = totalValue / barQty
barTxt = Icons.GP(Shared.round(barVal, 1, 1))
end
table.insert(resultPart, '\r\n|data-sort-value="' .. barVal .. '"| ' .. barTxt)
end
end
end
end
table.insert(resultPart, '\r\n|}')
table.insert(resultPart, '\n|}')


return table.concat(resultPart)
return table.concat(resultPart)
Line 454: Line 493:


function p.getFiremakingTable(frame)
function p.getFiremakingTable(frame)
local resultPart = {}
    local args = frame.args ~= nil and frame.args or frame
table.insert(resultPart, '{| class="wikitable sortable stickyHeader"')
    local realmName = args.realm
table.insert(resultPart, '\r\n|-class="headerRow-0"')
    local realm = p.getRealmFromName(realmName)
table.insert(resultPart, '\r\n!colspan="2" rowspan="2"|Logs!!rowspan="2"|'..Icons.Icon({'Firemaking', type='skill', notext=true})..' Level')
    if realm == nil then
table.insert(resultPart, '!!rowspan="2"|Burn Time!!colspan="2"|Without Bonfire!!colspan="2"|With Bonfire!!rowspan="2"|Bonfire Bonus!!rowspan="2"|Bonfire Time')
        return Shared.printError('Failed to find a realm with name ' .. (realmName or 'nil'))
table.insert(resultPart, '\r\n|-class="headerRow-1"')
    end
table.insert(resultPart, '\r\n!XP!!XP/s!!XP!!XP/s')
    local skillID = 'Firemaking'
 
    local tableHtml = mw.html.create('table')
        :addClass('wikitable sortable stickyHeader')
   
    local headerRow0 = tableHtml:tag('tr'):addClass('headerRow-0')
    headerRow0:tag('th'):attr('colspan', '2')
                        :attr('rowspan', '2')
                        :wikitext('Logs')
    headerRow0:tag('th'):attr('rowspan', '2')
                        :wikitext(Icons._SkillRealmIcon('Firemaking', realm.id) .. '<br>Level')
    headerRow0:tag('th'):attr('rowspan', '2')
                        :wikitext('[[DLC]]')
    headerRow0:tag('th'):attr('rowspan', '2')
                        :wikitext('Burn<br>Time')
    headerRow0:tag('th'):attr('colspan', '2')
                        :wikitext('Without Bonfire')
    headerRow0:tag('th'):attr('colspan', '2')
                        :wikitext('With Bonfire')
    headerRow0:tag('th'):attr('rowspan', '2')
                        :wikitext('Bonfire<br>Bonus')
    headerRow0:tag('th'):attr('rowspan', '2')
                        :wikitext('Bonfire<br>Time')
 
    local headerRow1 = tableHtml:tag('tr'):addClass('headerRow-1')
    headerRow1:tag('th'):wikitext('XP')
    headerRow1:tag('th'):wikitext('XP/s')
    headerRow1:tag('th'):wikitext('XP')
    headerRow1:tag('th'):wikitext('XP/s')


for i, logData in Shared.skpairs(SkillData.Firemaking) do
    local logsData = GameData.getEntities(SkillData.Firemaking.logs, function(obj)
local logs = Items.getItemByID(logData.logID)
        return p.getRecipeRealm(obj) == realm.id
local name = logs.name
    end)
local burnTime = logData.baseInterval / 1000
    table.sort(logsData, function(a, b) return p.standardRecipeSort(skillID, a, b) end)
local bonfireTime = logData.baseBonfireInterval / 1000
   
local XPS = logData.baseXP / burnTime
    for i, logData in ipairs(logsData) do
local XP_BF = logData.baseXP * (1 + logData.bonfireXPBonus / 100)
        local logs = Items.getItemByID(logData.logID)
local XPS_BF = XP_BF / burnTime
        local name = logs.name
        local level = p.getRecipeLevel(skillID, logData)
        local baseXP = logData.baseAbyssalExperience or logData.baseExperience
        local reqText = p.getRecipeRequirementText(SkillData.Firemaking.name, logData)
        local bonfireBonus = logData.bonfireAXPBonus or logData.bonfireXPBonus
        local burnTime = logData.baseInterval / 1000
        local bonfireTime = logData.baseBonfireInterval / 1000
        local XPS = baseXP / burnTime
        local XP_BF = baseXP * (1 + bonfireBonus / 100)
        local XPS_BF = Num.round(XP_BF / burnTime, 2, 2)
        XP_BF = Num.round(XP_BF, 2, 0)


table.insert(resultPart, '\r\n|-')
        local row = tableHtml:tag('tr')
table.insert(resultPart, '\r\n|data-sort-value="'..name..'"|'..Icons.Icon({name, type='item', size='50', notext=true}))
        row:tag('td'):attr('data-sort-value', name)
table.insert(resultPart, '||[['..name..']]')
                    :wikitext(Icons.Icon({name, type='item', notext=true}))
table.insert(resultPart, '||style ="text-align: right;"|'..logData.level)
        row:tag('td'):wikitext('[[' .. name .. ']]')
table.insert(resultPart, '||style ="text-align: right;" data-sort-value="'..burnTime..'"|'..Shared.timeString(burnTime, true))
        row:tag('td'):css('text-align', 'center')
table.insert(resultPart, '||style ="text-align: right;"|'..logData.baseXP)
                    :wikitext(level)
table.insert(resultPart, '||style ="text-align: right;" data-sort-value="'..XPS..'"|'..Shared.round(XPS, 2, 2))
        row:tag('td'):css('text-align', 'center')
table.insert(resultPart, '||style ="text-align: right;"|'..Shared.round(XP_BF, 2, 0))
            :attr('data-sort-value', Icons.getExpansionID(logData.logID))
table.insert(resultPart, '||style ="text-align: right;" data-sort-value="'..XPS_BF..'"|'..Shared.round(XPS_BF, 2, 2))
            :wikitext(Icons.getDLCColumnIcon(logData.logID))
table.insert(resultPart, '||style ="text-align: right;" data-sort-value="'..logData.bonfireXPBonus..'"|'..logData.bonfireXPBonus..'%')
        row:tag('td'):css('text-align', 'right')
table.insert(resultPart, '||style ="text-align: right;" data-sort-value="'..bonfireTime..'"|'..Shared.timeString(bonfireTime, true))
                    :attr('data-sort-value', burnTime)
end
                    :wikitext(Shared.timeString(burnTime, true))
        row:tag('td'):css('text-align', 'right')
                    :attr('data-sort-value', baseXP)
                    :wikitext(Num.formatnum(baseXP))
        row:tag('td'):css('text-align', 'right')
                    :attr('data-sort-value', XPS)
                    :wikitext(Num.formatnum(Num.round(XPS, 2, 2)))
       
        if bonfireBonus == 0 then
            row:tag('td'):attr('colspan', '4')
                        :addClass('table-na')
                        :wikitext('N/A')
        else
            row:tag('td'):css('text-align', 'right')
                        :attr('data-sort-value', XP_BF)
                        :wikitext(Num.formatnum(XP_BF))
            row:tag('td'):css('text-align', 'right')
                        :attr('data-sort-value', XPS_BF)
                        :wikitext(Num.formatnum(XPS_BF, 2, 2))
            row:tag('td'):css('text-align', 'right')
                        :attr('data-sort-value', bonfireBonus)
                        :wikitext(bonfireBonus .. '%')
            row:tag('td'):css('text-align', 'right')
                        :attr('data-sort-value', bonfireTime)
                        :wikitext(Shared.timeString(bonfireTime, true))
        end
    end


table.insert(resultPart, '\r\n|}')
    return tostring(tableHtml)
return table.concat(resultPart)
end
end


return p
return p

Latest revision as of 22:57, 15 October 2024

Data pulled from Module:GameData

Some skills have their own modules:

Also be aware of:


--This module should avoid including skill specific functions which generate
--output for wiki pages, especially those which require() other modules. For
--these functions, consider using the appropriate module from the below list.

--Some skills have their own modules:
--Module:Magic for Magic
--Module:Prayer for Prayer
--Module:Skills/Agility for Agility
--Module:Skills/Summoning for Summoning
--Module:Skills/Gathering for Mining, Fishing, Woodcutting
--Module:Skills/Artisan for Smithing, Cooking, Herblore, etc.

--Also be aware of:
--Module:Navboxes for navigation boxes appearing near the bottom of pages

local p = {}

local Shared = require('Module:Shared')
local Constants = require('Module:Constants')
local Common = require('Module:Common')
local GameData = require('Module:GameData')
local SkillData = GameData.skillData
local Modifiers = require('Module:Modifiers')
local Items = require('Module:Items')
local Icons = require('Module:Icons')
local Num = require('Module:Number')

-- Given a skill ID, returns the key for that skill's recipe data.
-- If the skill has no recipes (e.g. is a combat skill) then the
-- return value is nil
function p.getSkillRecipeKey(skillID)
	-- Convert skillID to local ID if not already
	local ns, localSkillID = GameData.getLocalID(skillID)
	local recipeIDs = {
		["Woodcutting"] = 'trees',
		["Fishing"] = 'fish',
		["Firemaking"] = 'logs',
		["Mining"] = 'rockData',
		["Thieving"] = 'npcs',
		["Agility"] = 'obstacles',
		["Cooking"] = 'recipes',
		["Smithing"] = 'recipes',
		["Farming"] = 'recipes',
		["Summoning"] = 'recipes',
		["Fletching"] = 'recipes',
		["Crafting"] = 'recipes',
		["Runecrafting"] = 'recipes',
		["Herblore"] = 'recipes',
		["Astrology"] = 'recipes',
		["Archaeology"] = 'digSites',
		["Harvesting"] = 'veinData'
	}
	return recipeIDs[localSkillID]
end

-- Given a skill ID & recipe, returns the skill level requirement for
-- that recipe and a boolean value indicating whether the level if abyssal or not.
-- If the level could not be determined, then the return value is nil, nil
function p.getRecipeLevelRealm(skillID, recipe)
	local level, isAbyssal = nil, nil
	-- Convert skillID to local ID if not already
	local ns, localSkillID = GameData.getLocalID(skillID)
	local realmID = p.getRecipeRealm(recipe)
	if localSkillID == 'Agility' then
		local course = GameData.getEntityByProperty(SkillData.Agility.courses, 'realm', realmID)
		isAbyssal = (realmID == 'melvorItA:Abyssal')
		-- For Agility, level is derived from obstacle category
		if recipe.category ~= nil then
			-- Obstacle
			local slot = course.obstacleSlots[recipe.category + 1]
			if isAbyssal then
				level = slot.abyssalLevel
			else
				level = slot.level
			end
		elseif recipe.slot ~= nil then
			-- Pillar
			level = course.pillarSlots[recipe.slot + 1].level
		end
	elseif recipe.abyssalLevel ~= nil then
		level, isAbyssal = recipe.abyssalLevel, true
	else
		-- For all other skills, the recipe should have a level property
		level, isAbyssal = recipe.level, false
	end
	return level, isAbyssal
end

function p.getRecipeLevel(skillID, recipe)
	local level, isAbyssal = p.getRecipeLevelRealm(skillID, recipe)
	return level
end

function p.getRecipeRequirementText(skillName, recipe)
	local reqText = {}
	if recipe.abyssalLevel ~= nil and recipe.abyssalLevel > 0 then
		table.insert(reqText, Icons._SkillReq(skillName, recipe.abyssalLevel, false, 'melvorItA:Abyssal'))
	elseif recipe.level ~= nil and recipe.level > 0 then
		table.insert(reqText, Icons._SkillReq(skillName, recipe.level, false))
	end
	if recipe.totalMasteryRequired ~= nil then
		table.insert(reqText, Num.formatnum(recipe.totalMasteryRequired) .. ' ' .. Icons.Icon({skillName, type='skill', notext=true}) .. ' ' .. Icons.Icon({'Mastery'}))
	end
	local reqsData = {}
	if type(recipe.requirements) == 'table' then
		reqsData = Shared.shallowClone(recipe.requirements)
	end
	if recipe.shopItemPurchased ~= nil then
		-- Mining requirements are stored differently than other skills like
		-- Woodcutting, standardize here
		table.insert(reqsData, {
			["type"] = 'ShopPurchase',
			["purchaseID"] = recipe.shopItemPurchased,
			["count"] = 1
		})
	end
	if not Shared.tableIsEmpty(reqsData) then
		local reqs = Common.getRequirementString(reqsData)
		if reqs ~= nil then
			table.insert(reqText, reqs)
		end
	end
	return table.concat(reqText, '<br/>')
end

function p.standardRecipeSort(skillID, recipeA, recipeB)
	local levelA, isAbyssalA = p.getRecipeLevelRealm(skillID, recipeA)
	local levelB, isAbyssalB = p.getRecipeLevelRealm(skillID, recipeB)
	local isAbyssalNumA, isAbyssalNumB = (isAbyssalA and 1) or 0, (isAbyssalB and 1) or 0

	return (isAbyssalA == isAbyssalB and levelA < levelB) or isAbyssalNumA < isAbyssalNumB
end


function p.getRecipeRealm(recipe)
	return recipe.realm or 'melvorD:Melvor'
end

function p.getRealmFromName(realmName)
	local realm = nil
	if realmName == nil or realmName == '' then
		-- Default realm
		realm = GameData.getEntityByID('realms', 'melvorD:Melvor')
	else
		realm = GameData.getEntityByName('realms', realmName)
	end
	return realm
end

function p.getMasteryActionCount(skillID, realmID, levelLimit)
	local actCount = 0
	local skillNS, skillLocalID = Shared.getLocalID(skillID)
	local skillData = SkillData[skillLocalID]
	local recipeKey = p.getSkillRecipeKey(skillLocalID)
	if recipeKey ~= nil then
		local recipeData = skillData[recipeKey]
		for i, recipe in ipairs(recipeData) do
			if (
				p.getRecipeRealm(recipe) == realmID
				and (recipe.noMastery == nil or not recipe.noMastery)
				and (levelLimit == nil or p.getRecipeLevel(skillLocalID, recipe) <= levelLimit)
			) then
				actCount = actCount + 1
			end
		end
	end
	return actCount
end

-- Thieving
function p.getThievingNPCByID(npcID)
	return GameData.getEntityByID(SkillData.Thieving.npcs, npcID)
end

function p.getThievingNPC(npcName)
	return GameData.getEntityByName(SkillData.Thieving.npcs, npcName)
end

function p.getThievingNPCArea(npc)
	for i, area in ipairs(SkillData.Thieving.areas) do
		for j, npcID in ipairs(area.npcIDs) do
			if npcID == npc.id then
				return area
			end
		end
	end
end

function p._getThievingNPCStat(npc, statName)
	local result = nil

	if statName == 'level' then
		result = Icons._SkillReq('Thieving', npc.level)
	elseif statName == 'maxHit' then
		result = npc.maxHit * 10
	elseif statName == 'area' then
		local area = p.getThievingNPCArea(npc)
		result = area.name
	else
		result = npc[statName]
	end

	if result == nil then
		result = ''
	end

	return result
end

function p.getThievingNPCStat(frame)
	local npcName = frame.args ~= nil and frame.args[1] or frame[1]
	local statName = frame.args ~= nil and frame.args[2] or frame[2]
	local npc = p.getThievingNPC(npcName)
	if npc == nil then
		return Shared.printError('Invalid Thieving NPC ' .. npcName)
	end

	return p._getThievingNPCStat(npc, statName)
end

function p.getThievingSourcesForItem(itemID)
	local resultArray = {}
	local areaNPCs = {}

	--First check area unique drops
	--If an area drops the item, add all the NPC ids to the list so we can add them later
	for i, area in pairs(SkillData.Thieving.areas) do
		for j, drop in pairs(area.uniqueDrops) do
			if drop.id == itemID then
				for k, npcID in ipairs(area.npcIDs) do
					areaNPCs[npcID] = { qty = drop.quantity, area = area }
				end
				break
			end
		end
	end

	--Now go through and get drop chances on each NPC if needed
	for i, npc in pairs(SkillData.Thieving.npcs) do
		local totalWt = 0
		local dropWt = 0
		local dropQty = { min = 0, max = 0 }
		for j, drop in ipairs(npc.lootTable) do
			totalWt = totalWt + drop.weight
			if drop.itemID == itemID then
				dropWt = drop.weight
				dropQty = { min = drop.minQuantity, max = drop.maxQuantity }
			end
		end
		if dropWt > 0 then
			table.insert(resultArray, {npc = npc.name, minQty = dropQty.min, maxQty = dropQty.max, wt = dropWt * SkillData.Thieving.itemChance, totalWt = totalWt * 100, level = npc.level, abyssalLevel = npc.abyssalLevel, npcID = npc.id, type = 'npc'})
		end

		--Chance of -1 on unique drops is to indicate variable chance
		if npc.uniqueDrop ~= nil and npc.uniqueDrop.id == itemID then
			table.insert(resultArray, {npc = npc.name, minQty = npc.uniqueDrop.quantity, maxQty = npc.uniqueDrop.quantity, wt = -1, totalWt = -1, level = npc.level, abyssalLevel = npc.abyssalLevel, npcID = npc.id, type = 'npcUnique'})
		end

		local areaNPC = areaNPCs[npc.id]
		if areaNPC ~= nil then
			table.insert(resultArray, {npc = npc.name, minQty = areaNPC.qty, maxQty = areaNPC.qty, wt = SkillData.Thieving.baseAreaUniqueChance, totalWt = 100, level = npc.level, abyssalLevel = npc.abyssalLevel, npcID = npc.id, area = areaNPC.area, type = 'areaUnique'})
		end
	end

	for i, drop in ipairs(SkillData.Thieving.generalRareItems) do
		if drop.itemID == itemID then
			if drop.npcs == nil then
				table.insert(resultArray, {npc = 'all', minQty = 1, maxQty = 1, wt = 1, totalWt = Num.round2(1/(drop.chance/100), 0), level = 1, npcID = itemID, type = 'generalRare'})
			else
				for j, npcID in ipairs(drop.npcs) do
					local npc = p.getThievingNPCByID(npcID)
					if npc ~= nil then
						table.insert(resultArray, {npc = npc.name, minQty = 1, maxQty = 1, wt = 1, totalWt = Num.round2(1/(drop.chance/100), 0), level = npc.level, abyssalLevel = npc.abyssalLevel, npcID = npc.id, type = 'generalRare'})
					end
				end
			end
		end
	end

	return resultArray
end

-- Astrology
function p.getConstellationByID(constID)
	return GameData.getEntityByID(SkillData.Astrology.recipes, constID)
end

function p.getConstellation(constName)
	return GameData.getEntityByName(SkillData.Astrology.recipes, constName)
end

function p.getConstellations(checkFunc)
	return GameData.getEntities(SkillData.Astrology.recipes, checkFunc)
end

-- Combines Astrology constellation modifiers into an object similar to other entities,
-- and multiplies the values up to their maximum possible amount
function p._getConstellationModifiers(cons)
	local result = {}
	local modKeys = { 'standardModifiers', 'uniqueModifiers', 'abyssalModifiers' }

	for _, keyID in ipairs(modKeys) do
		result[keyID] = {}
		local mods = cons[keyID]
		if mods ~= nil then
			for _, mod in ipairs(mods) do
				local newModObj = {}
				local multValue = mod.maxCount
				local subKeys = { 'modifiers', 'enemyModifiers' }
				for _, subKey in ipairs(subKeys) do
					local modAdj = Shared.clone(mod[subKey])
					if type(modAdj) == 'table' then
						for modName, modValueDef in pairs(modAdj) do
							if type(modValueDef) == 'table' then
								if modValueDef[1] ~= nil then
									-- Table of multiple values
									for i, subValue in ipairs(modValueDef) do
										if type(subValue) == 'table' and subValue.value ~= nil then
											subValue.value = subValue.value * multValue
										elseif type(subValue) == 'number' then
											modValueDef[i] = subValue * multValue
										end
									end
								elseif modValueDef.value ~= nil then
									-- Table but with a single value
									modValueDef.value = modValueDef.value * multValue
								end
							elseif type(modValueDef) == 'number' then
								-- Single value
								modAdj[modName] = modValueDef * multValue
							end
						end
						newModObj[subKey] = modAdj
					end
				end
				table.insert(result[keyID], newModObj)
			end
		end
	end
	return result
end

-- Mastery
function p.getMasteryUnlockTable(frame)
	local skillName = frame.args ~= nil and frame.args[1] or frame
	local skillID = Constants.getSkillID(skillName)
	if skillID == nil then
		return Shared.printError('Failed to find a skill ID for ' .. skillName)
	end

	local _, localSkillID = GameData.getLocalID(skillID)
	-- Clone so that we can sort by level
	local unlockTable = Shared.shallowClone(SkillData[localSkillID].masteryLevelUnlocks)
	if unlockTable == nil then
		return Shared.printError('Failed to find Mastery Unlock data for ' .. skillName)
	end
	table.sort(unlockTable, function(a, b) return (a.level == b.level and a.descriptionID < b.descriptionID) or a.level < b.level end)

	local result = '{|class="wikitable"\r\n!Level!!Unlock'
	for i, unlock in ipairs(unlockTable) do
		result = result..'\r\n|-'
		result = result..'\r\n|'..unlock.level..'||'..unlock.description
	end
	result = result..'\r\n|}'
	return result
end

function p.getMasteryCheckpointTable(frame)
	local args = frame.args ~= nil and frame.args or frame
	local skillName = args[1]
	local realmName = args.realm

	local realm = p.getRealmFromName(realmName)
	if realm == nil then
		return Shared.printError('Failed to find a realm with name ' .. (realmName or 'nil'))
	end
	local skillID = Constants.getSkillID(skillName)
	if skillID == nil then
		return Shared.printError('Failed to find a skill ID for ' .. skillName)
	end

	local _, localSkillID = GameData.getLocalID(skillID)
	local checkpoints = SkillData[localSkillID].masteryPoolBonuses
	if checkpoints == nil then
		return Shared.printError('Failed to find Mastery checkpoint data for ' .. skillName)
	end

	local totalPoolXP = p.getMasteryActionCount(localSkillID, realm.id) * 500000
	local result = '{|class="wikitable"\r\n!Pool %!!style="width:100px"|Pool XP!!Bonus'
	for i, checkpointData in ipairs(checkpoints) do
		if checkpointData.realm == realm.id then
			local chkDesc = Modifiers.getModifiersText(checkpointData.modifiers, false, false)
			local chkPercent = checkpointData.percent
			result = result..'\r\n|-'
			result = result..'\r\n|'..chkPercent..'%||'
			result = result..Num.formatnum(math.floor(totalPoolXP * chkPercent / 100))..' xp||'..chkDesc
		end
	end
	result = result..'\r\n|-\r\n!colspan="2"|Total Mastery Pool XP'
	result = result..'\r\n|'..Num.formatnum(totalPoolXP)
	result = result..'\r\n|}'
	return result
end

function p.getMasteryTokenTable()
	-- Defines which skill levels should be included within the output
	local skillLevels = {
		{
			["id"] = 'Base',
			["level"] = 99,
			["description"] = '[[Full Version|Base Game]] (Level 99)'
		}, {
			["id"] = 'TotH',
			["level"] = 120,
			["description"] = Icons.TotH() .. ' [[Throne of the Herald Expansion|Throne of the Herald]] (Level 120)'
		}
	}
	local baseTokenChance = 18500
	local masteryActionCount = {}
	local CCI_ID = 'melvorD:Clue_Chasers_Insignia'
	local CCI = Items.getItemByID(CCI_ID)
	if CCI == nil then
		return Shared.printError('Failed to find item with ID ' .. CCI_ID)	
	end

	local tokens = Items.getItems(function(item) return item.itemType == 'MasteryToken' end)
	local tokenItems = {}
	for _, item in ipairs(tokens) do
		if item.realm == 'melvorD:Melvor' and item.skill ~= nil then
			local skillNS, skillLocalID = Shared.getLocalID(item.skill)
			tokenItems[skillLocalID] = item
		end
	end

	-- Iterate over each skill with mastery, determining the number of
	-- mastery actions for each
	for skillLocalID, skill in pairs(SkillData) do
		if skill.masteryPoolBonuses ~= nil then
			local actCount = { ["skill"] = skill, ["token"] = tokenItems[skillLocalID] }
			for i, levelDef in ipairs(skillLevels) do
				actCount[levelDef.id] = p.getMasteryActionCount(skillLocalID, 'melvorD:Melvor', levelDef.level)
			end
			table.insert(masteryActionCount, actCount)
		end
	end

	local firstID = skillLevels[1].id
	table.sort(masteryActionCount,
		function(a, b)
			if a[firstID] == b[firstID] then
				return a.skill.name < b.skill.name
			else
				return a[firstID] > b[firstID]
			end
		end)
	
	-- Generate output table
	local resultPart = {}
	local CCIIcon = Icons.Icon({CCI.name, type='item', notext=true})
	local columnPairs = Shared.tableCount(skillLevels)

	-- Generate header
	table.insert(resultPart, '{| class="wikitable sortable"')
	table.insert(resultPart, '\n!rowspan="3"|Token!!rowspan="3"|Skill!!colspan="' .. columnPairs * 2 .. '"|Approximate Mastery Token Chance')
	table.insert(resultPart, '\n|-')
	for i, levelDef in ipairs(skillLevels) do
		table.insert(resultPart, '\n!colspan="2"| ' .. levelDef.description)
	end
	table.insert(resultPart, '\n|-' .. string.rep('\n!Without ' .. CCIIcon .. '\n!With ' .. CCIIcon, columnPairs))

	for i, rowData in ipairs(masteryActionCount) do
		local token = rowData.token
		table.insert(resultPart, '\n|-')
		local tokenImg = (token == nil and '?') or Icons.Icon({token.name, type='item', notext=true})
		table.insert(resultPart, '\n|style="text-align:center"|' .. tokenImg)
		table.insert(resultPart, '\n|' .. Icons.Icon({rowData.skill.name, type='skill'}))

		for j, levelDef in ipairs(skillLevels) do
			local actCount = rowData[levelDef.id]
			local denom, denomCCI = 0, 0
			if actCount > 0 then
				denom = math.floor(baseTokenChance / actCount)
				denomCCI = Num.round(baseTokenChance / (actCount * (1 + CCI.modifiers.offItemChance / 100)), 0, 0)
			end
			table.insert(resultPart, '\n|style="text-align:right" data-sort-value="' .. denom .. '"|1/' .. Num.formatnum(denom))
			table.insert(resultPart, '\n|style="text-align:right" data-sort-value="' .. denomCCI .. '"|1/' .. Num.formatnum(denomCCI))
		end
	end
	table.insert(resultPart, '\n|}')

	return table.concat(resultPart)
end

function p.getFiremakingTable(frame)
    local args = frame.args ~= nil and frame.args or frame
    local realmName = args.realm
    local realm = p.getRealmFromName(realmName)
    if realm == nil then
        return Shared.printError('Failed to find a realm with name ' .. (realmName or 'nil'))
    end
    local skillID = 'Firemaking'

    local tableHtml = mw.html.create('table')
        :addClass('wikitable sortable stickyHeader')
    
    local headerRow0 = tableHtml:tag('tr'):addClass('headerRow-0')
    headerRow0:tag('th'):attr('colspan', '2')
                        :attr('rowspan', '2')
                        :wikitext('Logs')
    headerRow0:tag('th'):attr('rowspan', '2')
                        :wikitext(Icons._SkillRealmIcon('Firemaking', realm.id) .. '<br>Level')
    headerRow0:tag('th'):attr('rowspan', '2')
                        :wikitext('[[DLC]]')
    headerRow0:tag('th'):attr('rowspan', '2')
                        :wikitext('Burn<br>Time')
    headerRow0:tag('th'):attr('colspan', '2')
                        :wikitext('Without Bonfire')
    headerRow0:tag('th'):attr('colspan', '2')
                        :wikitext('With Bonfire')
    headerRow0:tag('th'):attr('rowspan', '2')
                        :wikitext('Bonfire<br>Bonus')
    headerRow0:tag('th'):attr('rowspan', '2')
                        :wikitext('Bonfire<br>Time')

    local headerRow1 = tableHtml:tag('tr'):addClass('headerRow-1')
    headerRow1:tag('th'):wikitext('XP')
    headerRow1:tag('th'):wikitext('XP/s')
    headerRow1:tag('th'):wikitext('XP')
    headerRow1:tag('th'):wikitext('XP/s')

    local logsData = GameData.getEntities(SkillData.Firemaking.logs, function(obj)
        return p.getRecipeRealm(obj) == realm.id
    end)
    table.sort(logsData, function(a, b) return p.standardRecipeSort(skillID, a, b) end)
    
    for i, logData in ipairs(logsData) do
        local logs = Items.getItemByID(logData.logID)
        local name = logs.name
        local level = p.getRecipeLevel(skillID, logData)
        local baseXP = logData.baseAbyssalExperience or logData.baseExperience
        local reqText = p.getRecipeRequirementText(SkillData.Firemaking.name, logData)
        local bonfireBonus = logData.bonfireAXPBonus or logData.bonfireXPBonus
        local burnTime = logData.baseInterval / 1000
        local bonfireTime = logData.baseBonfireInterval / 1000
        local XPS = baseXP / burnTime
        local XP_BF = baseXP * (1 + bonfireBonus / 100)
        local XPS_BF = Num.round(XP_BF / burnTime, 2, 2)
        XP_BF = Num.round(XP_BF, 2, 0)

        local row = tableHtml:tag('tr')
        row:tag('td'):attr('data-sort-value', name)
                     :wikitext(Icons.Icon({name, type='item', notext=true}))
        row:tag('td'):wikitext('[[' .. name .. ']]')
        row:tag('td'):css('text-align', 'center')
                     :wikitext(level)
        row:tag('td'):css('text-align', 'center')
        		     :attr('data-sort-value', Icons.getExpansionID(logData.logID))
        		     :wikitext(Icons.getDLCColumnIcon(logData.logID))
        row:tag('td'):css('text-align', 'right')
                     :attr('data-sort-value', burnTime)
                     :wikitext(Shared.timeString(burnTime, true))
        row:tag('td'):css('text-align', 'right')
                     :attr('data-sort-value', baseXP)
                     :wikitext(Num.formatnum(baseXP))
        row:tag('td'):css('text-align', 'right')
                     :attr('data-sort-value', XPS)
                     :wikitext(Num.formatnum(Num.round(XPS, 2, 2)))
        
        if bonfireBonus == 0 then
            row:tag('td'):attr('colspan', '4')
                         :addClass('table-na')
                         :wikitext('N/A')
        else
            row:tag('td'):css('text-align', 'right')
                         :attr('data-sort-value', XP_BF)
                         :wikitext(Num.formatnum(XP_BF))
            row:tag('td'):css('text-align', 'right')
                         :attr('data-sort-value', XPS_BF)
                         :wikitext(Num.formatnum(XPS_BF, 2, 2))
            row:tag('td'):css('text-align', 'right')
                         :attr('data-sort-value', bonfireBonus)
                         :wikitext(bonfireBonus .. '%')
            row:tag('td'):css('text-align', 'right')
                         :attr('data-sort-value', bonfireTime)
                         :wikitext(Shared.timeString(bonfireTime, true))
        end
    end

    return tostring(tableHtml)
end

return p