FGO reader JP server
Not fetchingIdle — 204627 wiki requests so far, 353 failed

Module:Material Usage

Cached copy of the original page · revision 1650446 · refresh

Documentation icon Module documentation

The documentation for this module is missing. Click here to create it.

-- Generates the per-class servant usage table for a material page by
-- parsing each servant page's {{Ascension}} and {{Skillreinforcement}}
-- data. Invoked via Template:Material Usage Table.
local p = {}

local CLASS_ORDER = {
    "Saber", "Archer", "Lancer", "Rider", "Caster", "Assassin",
    "Berserker", "Shielder", "Ruler", "Avenger", "Moon Cancer",
    "Alter Ego", "Foreigner", "Pretender", "Beast",
}

local function escapePattern(s)
    return (s:gsub("[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%1"))
end

-- Find balanced {{TemplateName ...}} blocks in wikitext
local function findTemplateBlocks(content, templateName)
    local blocks = {}
    local pat = "{{%s*" .. escapePattern(templateName) .. "%s*[|}]"
    local searchFrom = 1
    while true do
        local s = content:find(pat, searchFrom)
        if not s then
            break
        end
        local depth, i, len, e = 0, s, #content, nil
        while i <= len do
            local two = content:sub(i, i + 1)
            if two == "{{" then
                depth = depth + 1
                i = i + 2
            elseif two == "}}" then
                depth = depth - 1
                i = i + 2
                if depth == 0 then
                    e = i - 1
                    break
                end
            else
                i = i + 1
            end
        end
        if not e then
            break
        end
        table.insert(blocks, { text = content:sub(s, e), startPos = s })
        searchFrom = e + 1
    end
    return blocks
end

-- Find {{<item>|<amount>}} uses and the "|XY =" key each belongs to
local function findItemUses(blockText, itemPatterns)
    local uses = {}
    for _, ip in ipairs(itemPatterns) do
        local from = 1
        while true do
            local s, e, amount = blockText:find(
                "{{%s*" .. ip .. "%s*|%s*([%d,]+)%s*[|}]", from)
            if not s then
                break
            end
            local prefix = blockText:sub(1, s - 1)
            local key = prefix:match(".*|%s*(%w+)%s*=%s*$")
                or prefix:match(".*|%s*(%w+)%s*=[^|]*$")
            if key then
                table.insert(uses, {
                    key = key,
                    amount = tonumber((amount:gsub(",", ""))) or 0,
                })
            end
            from = e + 1
        end
    end
    return uses
end

-- Ascension block: tiers 1-4 -> ascension total, tiers 5+ -> costumes.
-- Costumes are keyed by the icon's stage token (e.g. "cos1", or "fc1"
-- for Francesca-form costumes), so ReqItem can reuse it verbatim.
local function aggregateAscension(block, itemPatterns)
    local asc = 0
    local costumes = {}
    local tierStage = {}
    for tier, stage in block:gmatch(
        "|%s*(%d+)icon%s*=%s*{{[^{}]-stage%s*=%s*(%w+)") do
        tierStage[tonumber(tier)] = stage
    end
    -- Key is <tier><slot>; the tier may be two digits (Mashu reaches |114 =).
    for _, u in ipairs(findItemUses(block, itemPatterns)) do
        local tier = tonumber(u.key:match("^(%d+)%d$") or "")
        if tier then
            if tier <= 4 then
                asc = asc + u.amount
            else
                local stage = tierStage[tier] or ("cos" .. (tier - 4))
                costumes[stage] = (costumes[stage] or 0) + u.amount
            end
        end
    end
    return asc, costumes
end

-- Sum all "|XY =" uses in one Skillreinforcement block (= cost per skill)
local function aggregateSkill(block, itemPatterns)
    local total = 0
    for _, u in ipairs(findItemUses(block, itemPatterns)) do
        if u.key:match("^%d%d$") then
            total = total + u.amount
        end
    end
    return total
end

-- Whether a Skillreinforcement block sits in the Active or Append tab
local function skillTabLabel(content, startPos, index)
    local prefix = content:sub(math.max(1, startPos - 80), startPos - 1)
    if prefix:match("Append[^{}]*|%s*$") then
        return "append"
    end
    if prefix:match("Active[^{}]*|%s*$") then
        return "active"
    end
    return index == 1 and "active" or "append"
end

local function analyzeServant(title, itemPatterns)
    local t = mw.title.new(title)
    if not t then
        return nil
    end
    local content = t:getContent()
    if not content then
        return nil
    end
    local result = { asc = 0, skill = 0, append = 0, costumes = {} }
    for _, b in ipairs(findTemplateBlocks(content, "Ascension")) do
        local asc, costumes = aggregateAscension(b.text, itemPatterns)
        result.asc = result.asc + asc
        for n, v in pairs(costumes) do
            result.costumes[n] = (result.costumes[n] or 0) + v
        end
    end
    local skillBlocks = findTemplateBlocks(content, "Skillreinforcement")
    for i, b in ipairs(skillBlocks) do
        local label = skillTabLabel(content, b.startPos, i)
        local total = aggregateSkill(b.text, itemPatterns)
        if label == "active" then
            result.skill = result.skill + total
        else
            result.append = result.append + total
        end
    end
    return result
end

-- List article-namespace servant pages that use Template:<item>.
-- DPL argument format validated in Module:Material Usage/sandbox:
-- positional "name=value" strings, "\\n" as the item separator.
local function fetchUserTitles(frame, uses)
    local result = frame:callParserFunction("#dpl",
        "namespace=",
        "category=Servant",
        "uses=" .. uses,
        "distinct=true",
        "mode=userformat",
        "format=,%TITLE%\\n,,"
    )
    local titles, seen = {}, {}
    for line in mw.text.gsplit(result or "", "\n") do
        local title = mw.text.trim(line)
        if title ~= "" and not seen[title] then
            seen[title] = true
            table.insert(titles, title)
        end
    end
    return titles
end

local function buildRows(frame, list)
    local cell = {}
    for _, r in ipairs(list) do
        if r.asc > 0 or r.skill > 0 or r.append > 0 then
            table.insert(cell, frame:expandTemplate{
                title = "ReqItem",
                args = { r.name, tostring(r.asc),
                    tostring(r.skill), tostring(r.append) },
            })
        end
        local stages = {}
        for stage in pairs(r.costumes) do
            table.insert(stages, stage)
        end
        table.sort(stages, function(a, b)
            local an = tonumber(a:match("%d+") or "") or 0
            local bn = tonumber(b:match("%d+") or "") or 0
            if an ~= bn then
                return an < bn
            end
            return a < b
        end)
        for _, stage in ipairs(stages) do
            local n = stage:match("%d+")
            table.insert(cell, frame:expandTemplate{
                title = "ReqItem",
                args = {
                    r.name,
                    stage = stage,
                    cos = n and ("Costume " .. n) or "Costume",
                    total = tostring(r.costumes[stage]),
                },
            })
        end
    end
    return cell
end

function p.table(frame)
    local parent = frame:getParent()
    local function arg(name)
        local v = frame.args[name]
        if (not v or v == "") and parent then
            v = parent.args[name]
        end
        if v == "" then
            v = nil
        end
        return v
    end

    -- {{PAGENAME}} HTML-encodes characters such as apostrophes (&#39;);
    -- decode so DPL queries and Lua patterns see the real title.
    local item = mw.text.decode(arg("item")
        or mw.title.getCurrentTitle().text)

    local itemPatterns = { escapePattern(item) }
    local uses = "Template:" .. item
    if arg("aliases") then
        for a in mw.text.gsplit(arg("aliases"), ",") do
            a = mw.text.decode(mw.text.trim(a))
            if a ~= "" then
                table.insert(itemPatterns, escapePattern(a))
                uses = uses .. "|Template:" .. a
            end
        end
    end

    local exclude = {}
    if arg("exclude") then
        for x in mw.text.gsplit(arg("exclude"), ",") do
            exclude[mw.text.decode(mw.text.trim(x))] = true
        end
    end

    local servantData = mw.loadData("Module:Servant Icon/data")
    local byClass = {}
    local found = 0
    for _, title in ipairs(fetchUserTitles(frame, uses)) do
        local sd = servantData[title]
        -- id 9999 = entries without a collection number (e.g. Arcade
        -- variants); existing tables do not list them.
        if sd and (sd.id or 0) ~= 9999 and not exclude[title] then
            local r = analyzeServant(title, itemPatterns)
            if r and (r.asc > 0 or r.skill > 0 or r.append > 0
                or next(r.costumes)) then
                r.name = title
                r.id = sd.id or 0
                byClass[sd.class] = byClass[sd.class] or {}
                table.insert(byClass[sd.class], r)
                found = found + 1
            end
        end
    end

    if found == 0 then
        return '<span class="error">Material Usage: no servant usage found'
            .. ' for "' .. item .. '". Check the item/aliases parameters.'
            .. '</span>[[Category:Material Usage table errors]]'
    end

    local out = {}
    table.insert(out, '{| class="wikitable mw-collapsible" style="width:100%;"')
    table.insert(out, '!style="width:30px;"|'
        .. frame:expandTemplate{ title = "All Class" })
    table.insert(out, "!Servants")
    local rendered = {}
    local function renderClass(cls)
        local list = byClass[cls]
        if not list or rendered[cls] then
            return
        end
        rendered[cls] = true
        table.sort(list, function(a, b)
            return a.id < b.id
        end)
        table.insert(out, "|-")
        table.insert(out, "!" .. frame:expandTemplate{ title = cls })
        table.insert(out, "|" .. table.concat(buildRows(frame, list), "\n"))
    end
    for _, cls in ipairs(CLASS_ORDER) do
        renderClass(cls)
    end
    -- Safety net: render any class name not covered by CLASS_ORDER
    -- instead of silently dropping its servants.
    local leftover = {}
    for cls in pairs(byClass) do
        if not rendered[cls] then
            table.insert(leftover, cls)
        end
    end
    table.sort(leftover)
    for _, cls in ipairs(leftover) do
        renderClass(cls)
    end
    if arg("extra") then
        table.insert(out, arg("extra"))
    end
    table.insert(out, "|}")
    return table.concat(out, "\n")
end

return p