Module:Sandbox/Aurelain/Cargo: Difference between revisions

From Heroes of Might and Magic: Olden Era Official Wiki
No edit summary
No edit summary
 
(71 intermediate revisions by the same user not shown)
Line 1: Line 1:
local p = {}
local p = {}
local FACTION_ORDER = {
local FACTION_ORDER = {
     human = 1,
     human = 1,
Line 9: Line 10:
     neutral = 7,
     neutral = 7,
}
}
local FACTION_IDS_IN_TRANSLATION = {
 
     'human',
local FACTION_MAPPING = {
     'undead',
     Temple = 'human',
     'nature',
     Necropolis = 'undead',
     'demon',
     Grove = 'nature',
     'unfrozen',
     Hive = 'demon',
     'dungeon',
     Schism = 'unfrozen',
     'neutral', -- missing
     Dungeon = 'dungeon',
     Neutral = 'neutral'
}
}
local OTHER_IDS_IN_TRANSLATION = {
 
     'creature',
-- Note: The right side is just a fallback, it will seldom be used.
     'faction',
local TRANSLATION_IDS = {
     'tier',
     wiki_ubox_growth =      'Base growth',
     'cost', -- missing
    creature =              'Creature',
     'hp',
     faction =              'Faction',
     'offence',
    tier =                  'Tier',
     'defence',
     wiki_cost =            'Cost',
     'damage',
     hp =                    'Hp',
     'initiative',
     offence =              'Offence',
     'speed',
     defence =              'Defence',
     'ranged',
     damage =                'Damage',
     initiative =            'Initiative',
     morale =                'Morale',
     luck =                  'Luck',
    speed =                'Speed',
     wiki_units_neutral =    'Neutral',
    wiki_units_attack_type = 'Attack type',
    melee_attack =          'Melee Attack', -- melee_attack = 1
    wiki_units_no_counter = 'Melee,<br>no counter', -- melee_attack_no_counter = 2
    remote_attack        = 'Long Reach', -- remote_attack = 3
    ranged_attack        = 'Ranged Attack', -- ranged_attack = 4
    wiki_units_no_close = 'Ranged,<br>no melee penalty', -- ranged_attack_no_close = 5
    wiki_units_no_range = 'Ranged,<br>no range penalty', -- ranged_attack_no_range = 6
    wiki_units_no_range_close = 'Ranged,<br>no penalties', -- ranged_attack_no_range_close = 7
}
}
local RESOURCE_ICONS = {
local RESOURCE_ICONS = {
     wood_cost    = 'Wood',
     wood_cost    = 'Wood',
Line 39: Line 55:
     gemstone_cost = 'Gemstones'
     gemstone_cost = 'Gemstones'
}
}
local STAT_ICONS = {
local STAT_ICONS = {
     hp          = 'Icon_Stats_Health',
     hp          = 'Icon_Stats_Health',
Line 44: Line 61:
     defence    = 'Icon_Stats_Defence',
     defence    = 'Icon_Stats_Defence',
     damage      = 'Icon_Stats_Damage',
     damage      = 'Icon_Stats_Damage',
    morale      = 'Icon_Stats_Morale',
    luck        = 'Icon_Stats_Luck',
     initiative  = 'Icon_Stats_Initiative',
     initiative  = 'Icon_Stats_Initiative',
     speed      = 'Icon_Stats_Speed',
     speed      = 'Icon_Stats_Speed',
}
}
local ATTACK_RANKS = {
    base_passive_melee_attack_name = 1,                -- Swordsman    100,  0,  0,  0,  0,  0,  0,  0,  0
    base_passive_melee_attack_no_counter_name = 2,      -- Vampire Lord  101,  0,  0,  0,  0,  0,  0,  0,  0
    base_passive_remote_attack_name = 3,                -- Graverobber    0, 100,  0,  0,  0,  0,  0,  0,  0
    base_passive_ranged_attack_name = 4,                -- Onyx Dancer    50, 100, 100,  90,  80,  70,  60,  50,  50
    base_passive_ranged_attack_no_close_name = 5,      -- Apotheosis    100, 100, 100,  90,  80,  70,  60,  50,  50
    base_passive_ranged_attack_no_range_name = 6,      -- Marksman      50, 100, 100, 100, 100, 100, 100, 100, 100
    base_passive_ranged_attack_no_range_close_name = 7, -- Halfling      100, 100, 100, 100, 100, 100, 100, 100, 100
}
local ATTACK_ICONS = {
    base_passive_melee_attack_name = 'Base_passive_melee_attack',
    base_passive_melee_attack_no_counter_name = 'Base_passive_noncounter',
    base_passive_remote_attack_name = 'Base_passive_remote_attack',
    base_passive_ranged_attack_name = 'Base_passive_ranged_attack', -- TODO: clarify icon
    base_passive_ranged_attack_no_close_name = 'Base passive duelist', -- TODO: clarify icon
    base_passive_ranged_attack_no_range_name = 'Base_passive_sharpshooter', -- TODO: clarify icon
    base_passive_ranged_attack_no_range_close_name = 'Arbitrator_passive_1', -- TODO: clarify icon
}
local ATTACK_WORDS = {
    base_passive_melee_attack_name = 'melee_attack',
    base_passive_melee_attack_no_counter_name = 'wiki_units_no_counter',
    base_passive_remote_attack_name = 'remote_attack',
    base_passive_ranged_attack_name = 'ranged_attack',
    base_passive_ranged_attack_no_close_name = 'wiki_units_no_close',
    base_passive_ranged_attack_no_range_name = 'wiki_units_no_range',
    base_passive_ranged_attack_no_range_close_name = 'wiki_units_no_range_close',
}
local ROMAN = { 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII' }
local ROMAN = { 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII' }


------------------------------------------------------------------------------------------------------------------------
local PAGES = {
-- Detects the current language from the URL
     Stinger = 'Stinger_(unit)',
------------------------------------------------------------------------------------------------------------------------
}
local function getCurrentLang()
 
     local title = mw.title.getCurrentTitle()
local MORALE_AND_LUCK = {
    local segments = mw.text.split(title.text, '/')
    '<span class="elevated1">1</span>',
     for i = #segments, 2, -1 do
     '<span class="elevated2">2</span>',
        local segment = mw.ustring.lower(segments[i])
     '<span class="elevated3">3</span>',
        if mw.language.isSupportedLanguage(segment) then
}
            return segment
        end
    end
     return 'en'
end


------------------------------------------------------------------------------------------------------------------------
-- Awards a number from 0 to 3 for a unit, based on how upgraded it is
-- Awards a number from 0 to 3 for a unit, based on how upgraded it is
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
Line 82: Line 125:
end
end


-- Returns one of the ATTACK_RANKS keys (e.g. 'base_passive_melee_attack_name') or an empty string
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
-- Returns 0, 1 or 2 depending on the ai_archetype value
local function computeAttackType(row)
------------------------------------------------------------------------------------------------------------------------
     local abilities = row['shared_abilities']
local function computeRange(row)
     if type(abilities) ~= "string" then
     local v = row['ai_archetype']
         return ""
     if v == 'reach_type' then
     end
         return 1
    for key, _ in pairs(ATTACK_RANKS) do
     elseif v == 'range_type' or v == 'range_type_melee_shooters' or v == 'range_type_eater' then
        local pattern = "%f[%w]" .. key .. "%f[%W]"
        return 2
        if string.match(abilities, pattern) then
    else
            return key
         return 0
         end
     end
     end
    return ""
end
end


------------------------------------------------------------------------------------------------------------------------
-- Returns a rich wikitext with numbers and icons
-- Returns a rich wikitext with numbers and icons
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
Line 111: Line 155:
end
end


-- Parses and runs a Cargo query from wiki-like syntax
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
local function runQuery(query, ...)
    query = string.gsub(query, "%-%-.-\n", "") -- remove "comments"
    query = select('#', ...) > 0 and mw.ustring.format(query, ...) or query
    query = mw.text.trim(query)
    local tables = ''
    local fields = ''
    local options = {}
    for part in query:gmatch('[^|]+') do
        local key, val = part:match('^%s*([^=]+)%s*=%s*(.-)%s*$')
        if key and val then
            key = mw.text.trim(key):lower()
            val = mw.text.trim(val)
            val = val:gsub('%s', ' ')
            if key == 'tables' then
                tables = val
            elseif key == 'fields' then
                fields = val
            elseif key == 'limit' then
                options[key] = tonumber(val) or val
            elseif key == 'join on' then
                options['join'] = val
            else
                options[key] = val
            end
        end
    end
    local success, result = pcall(function()
        return mw.ext.cargo.query(tables, fields, options)
    end)
    return success and result or {}
end
-- Retrieves the data from Cargo
-- Retrieves the data from Cargo
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
local function query(lang)
local function query(lang, forcedFaction)
     local tables = 'Unit, Translation'
     local tables = 'Unit, Translation'
     local fields = '' ..
     local fields = '' ..
Line 125: Line 202:
         'Unit.damage_min=damage_min, ' ..
         'Unit.damage_min=damage_min, ' ..
         'Unit.damage_max=damage_max, ' ..
         'Unit.damage_max=damage_max, ' ..
        'Unit.morale=morale, ' ..
        'Unit.luck=luck, ' ..
         'Unit.initiative=initiative, ' ..
         'Unit.initiative=initiative, ' ..
         'Unit.speed=speed, ' ..
         'Unit.speed=speed, ' ..
         'Unit.ai_archetype=ai_archetype, ' .. -- we use it for range detection
         'Unit.shared_abilities=shared_abilities, ' .. -- we use it for range detection
         -- costs
         -- costs
         'Unit.gold_cost=gold_cost, ' ..
         'Unit.gold_cost=gold_cost, ' ..
Line 142: Line 221:
         'Translation.language=language, ' ..
         'Translation.language=language, ' ..
         'Translation.name=transName'
         'Translation.name=transName'
    -- where:
    local where = {}
    if forcedFaction then
        table.insert(where, 'Unit.faction="' .. forcedFaction .. '"')
    end
    table.insert(where, '(Translation.language = "en" OR Translation.language = "' .. lang .. '")')


     -- Get BOTH the English row AND the target language row
     -- Get BOTH the English row AND the target language row
     local cargoArgs = {
     local cargoArgs = {
         join = 'Unit.id = Translation.target_id',
         join = 'Unit.id = Translation.target_id',
         where = 'Translation.language = "en" OR Translation.language = "' .. lang .. '"',
         where = table.concat(where, ' AND '),
         orderBy = 'Unit.id ASC',
         orderBy = 'Unit.id ASC',
         limit = 1000 -- Increased limit since each unit will return 2 rows
         limit = 1000 -- Increased limit since each unit will return 2 rows
Line 154: Line 240:
end
end


-- Gets the weekly increment for all units from the MapObject table
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
local function queryGrowths()
    return runQuery([[
      tables =
          MapObject = M
      | where =
          M.units_weekly > 0
      | fields =
          M.units_hire_sid = units_hire_sid,
          M.units_weekly = units_weekly
      | limit =
          100
  ]]);
end
-- Scans the Cargo results and folds the EN and lang rows into a single row
-- Scans the Cargo results and folds the EN and lang rows into a single row
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
Line 166: Line 267:
             units[id] = mw.clone(row)
             units[id] = mw.clone(row)
             units[id].upgradeRank = computeUpgradeRank(row)
             units[id].upgradeRank = computeUpgradeRank(row)
             units[id].ranged = computeRange(row)
             units[id].attackType = computeAttackType(row)
             units[id].cost = computeCost(row)
             units[id].cost = computeCost(row)
         end
         end
Line 188: Line 289:
end
end


------------------------------------------------------------------------------------------------------------------------
-- Decides the order between two units, for sorting purposes.
-- Decides the order between two units, for sorting purposes.
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
Line 210: Line 310:
end
end


------------------------------------------------------------------------------------------------------------------------
-- Retrieves the text for some specific ids from Cargo Translations.
-- Retrieves the text for some specific ids from Cargo Translations.
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
local function translateIds(ids, lang, where)
local function translateIds(ids, lang, extra)
     -- Initialize
     -- Key list
     local dictionary = {}
     local list = {}
     for _, id in ipairs(ids) do
     for key, _ in pairs(ids) do
         dictionary[id] = id:gsub("^%l", string.upper)
         list[#list + 1] = key
     end
     end
    local idListString = '"' .. table.concat(list, '", "') .. '"'


     -- Cargo
     -- Cargo
     local idListString = '"' .. table.concat(ids, '", "') .. '"'
     local where = {}
     local tables = 'Translation'
    table.insert(where, 'target_id IN (' .. idListString .. ')')
    local fields = 'target_id, name'
    table.insert(where, 'language = "' .. lang .. '"')
    where = where or ''
    if extra then
    local cargoArgs = {
        table.insert(where, extra)
         where = 'target_id IN (' .. idListString .. ') AND language = "' .. lang .. '"' .. where,
    end
     local results = mw.ext.cargo.query('Translation', 'target_id, name', {
         where = table.concat(where, ' AND '),
         limit = 100
         limit = 100
     }
     })
    local results = mw.ext.cargo.query(tables, fields, cargoArgs)


     -- Update dictionary
     -- Dictionary
     if results then
    local dictionary = mw.clone(ids)
         for _, row in ipairs(results) do
     for key, value in pairs(dictionary) do
             dictionary[row['target_id']] = row['name']
        --dictionary[key] = value .. '[[Data:WikiTranslations/' .. lang .. '#' .. key .. '|💬]]'
         dictionary[key] = value .. '💬'
    end
    for _, row in ipairs(results) do
        local name = row['name']
        if name and name ~= '' and not name:find('💬') then
             dictionary[row['target_id']] = name
         end
         end
     end
     end
Line 240: Line 347:
end
end


------------------------------------------------------------------------------------------------------------------------
-- Displays a variable
-- Displays a variable
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
Line 247: Line 353:
end
end


------------------------------------------------------------------------------------------------------------------------
-- Builds an icon+text combo for the unit's name
-- Builds an icon+text combo for the unit's name
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
local function renderUnitName(u, suffix)
local function renderUnitName(u, suffix)
     local page = u.nameEn .. suffix
     local stem = PAGES[u.nameEn] or u.nameEn
     local img = '[[File:' .. u.nameEn .. ' icon.png|40px|link=' .. page .. ']]'
    local page = stem .. suffix
     local img = '[[File:' .. u.nameEn .. ' icon.png|64px|link=' .. page .. ']]'
     local text = '[[' .. page .. '|' .. u.nameX .. ']]'
     local text = '[[' .. page .. '|' .. u.nameX .. ']]'
     return img .. ' ' .. text
     return img .. ' ' .. text
end
end


------------------------------------------------------------------------------------------------------------------------
-- Boilerplate for the header cells
-- Boilerplate for the header cells
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
local function createTh(tr, text)
local function addTh(tr, text)
     tr:tag('th'):wikitext(text):done()
     tr:tag('th'):wikitext(text):done()
end
end


------------------------------------------------------------------------------------------------------------------------
-- Boilerplate for stat tds
-- Boilerplate for stat tds
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
local function createStat(tr, value, pngName)
local function createStat(tr, value, pngName)
     tr:tag('td'):wikitext(value .. '[[File:' .. pngName .. '.png|16px|link=]]'):done()
     tr:tag('td'):wikitext(value .. '[[File:' .. pngName .. '.png|link=]]'):done()
end
end


-- Boilerplate for the separator
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
-- Main public function
local function addSeparator(htmlTable, className, content)
    htmlTable:tag('tr')
        :addClass('separator')
        :addClass(className)
        :tag('td'):attr('data-sort-value', ''):attr('colspan', 100):wikitext(content):done()
end
 
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
function p.display(frame)
local function addFactionWords(words, lang, frame)
     local lang = getCurrentLang()
     for key, _ in pairs(FACTION_ORDER) do
    local suffix = lang ~= 'en' and '/' .. lang or ''
        words[key] = frame:preprocess('{{F|' .. key .. '|' .. lang .. '}}')
    local wordsEn = translateIds(OTHER_IDS_IN_TRANSLATION, 'en')
     end
     local wordsX = lang == 'en' and wordsEn or translateIds(OTHER_IDS_IN_TRANSLATION, lang)
end
    local factionEn = translateIds(FACTION_IDS_IN_TRANSLATION, 'en', ' AND type="faction"')
    local factionX = lang == 'en' and factionEn or translateIds(FACTION_IDS_IN_TRANSLATION, lang, ' AND type="faction"')


    -- Cargo
------------------------------------------------------------------------------------------------------------------------
    local results = query(lang)
local function renderIconWithHint(fileName, text, frame)
     local units = consolidateResults(results, lang)
     local file = '[[File:' .. fileName .. '.png|32px|link=]]';
     table.sort(units, sortUnits)
     return frame:preprocess('{{Hint|' .. file .. '|' .. text .. '}}')
end


    -- Table
------------------------------------------------------------------------------------------------------------------------
    local htmlTable = mw.html.create('table')
local function createHeader(htmlTable, words, frame)
    htmlTable:addClass('wikitable sortable')
    htmlTable:css('white-space', 'nowrap')
 
    -- Header
     local header = htmlTable:tag('tr')
     local header = htmlTable:tag('tr')
     createTh(header, wordsX['creature'])
     -- 1 to 4 (general)
     createTh(header, wordsX['faction'])
    addTh(header, words.creature)
     createTh(header, wordsX['tier'])
     addTh(header, words.faction)
     createTh(header, wordsX['cost'])
     addTh(header, words.tier)
     -- main stats
     addTh(header, words.wiki_cost)
     createTh(header, wordsX.hp)
     -- 5 to 12 (main stats)
     createTh(header, wordsX.offence)
     addTh(header, renderIconWithHint(STAT_ICONS.hp, words.hp, frame))
     createTh(header, '[[File:Icon_Stats_Defence.png|24px|' .. wordsX['defence'] .. ']]')
     addTh(header, renderIconWithHint(STAT_ICONS.offence, words.offence, frame))
     createTh(header, '[[File:Icon_Stats_Damage.png|24px|' .. wordsX['damage'] .. ']]')
     addTh(header, renderIconWithHint(STAT_ICONS.defence, words.defence, frame))
     createTh(header, '[[File:Icon_Stats_Initiative.png|24px|' .. wordsX['initiative'] .. ']]')
     addTh(header, renderIconWithHint(STAT_ICONS.damage, words.damage, frame))
     createTh(header, '[[File:Icon_Stats_Speed.png|24px|' .. wordsX['speed'] .. ']]')
    addTh(header, renderIconWithHint(STAT_ICONS.morale, words.morale, frame))
     -- others
     addTh(header, renderIconWithHint(STAT_ICONS.luck, words.luck, frame))
     createTh(header, '[[File:Base_passive_ranged_attack.png|24px|' .. wordsX['ranged'] .. ']]')
    addTh(header, renderIconWithHint(STAT_ICONS.initiative, words.initiative, frame))
     addTh(header, renderIconWithHint(STAT_ICONS.speed, words.speed, frame))
     -- 13 (others)
     addTh(header, renderIconWithHint('Sunlight_cavalry_passive_3', words.wiki_units_attack_type, frame))
end


    -- Body
------------------------------------------------------------------------------------------------------------------------
local function createBody(htmlTable, units, words, suffix, frame)
    local currentTier = units[1].tier
    local currentFaction = units[1].faction
     for _, u in ipairs(units) do
     for _, u in ipairs(units) do
         local factionPage = factionEn[u.faction] .. '_Units' .. suffix
 
         local tr = htmlTable:tag('tr')
        -- separators
         if u.faction ~= currentFaction then
            currentFaction = u.faction
            currentTier = u.tier
            addSeparator(htmlTable, 'separator-large', words[currentFaction])
        elseif u.tier ~= currentTier then
            currentTier = u.tier
            addSeparator(htmlTable, 'separator-tiny', '')
        end
 
         local tr = htmlTable:tag('tr'):addClass('unit')
        if u.upgradeRank == 2 or u.upgradeRank == 3 then
            tr:addClass('upgraded')
        end
        -- 1 to 4 (general)
         tr:tag('td'):wikitext(renderUnitName(u, suffix)):done()
         tr:tag('td'):wikitext(renderUnitName(u, suffix)):done()
         tr:tag('td'):wikitext('[[' .. factionPage .. '|' .. factionX[u.faction] .. ']]'):done()
         tr:tag('td'):wikitext(words[currentFaction]):done()
         tr:tag('td'):wikitext(ROMAN[tonumber(u.tier)]):done()
         tr:tag('td'):wikitext(ROMAN[tonumber(u.tier)]):done()
        -- cost
         tr:tag('td'):attr('data-sort-value', string.match(u.cost, "^%d+")):wikitext(u.cost):done()
         tr:tag('td'):attr('data-sort-value', string.match(u.cost, "^%d+")):wikitext(u.cost):done()
         -- main stats
         -- 5 to 12 (main stats)
         createStat(tr, u.hp, STAT_ICONS.hp)
         createStat(tr, u.hp, STAT_ICONS.hp)
         createStat(tr, u.offence, STAT_ICONS.offence)
         createStat(tr, u.offence, STAT_ICONS.offence)
         createStat(tr, u.defence, STAT_ICONS.offence)
         createStat(tr, u.defence, STAT_ICONS.defence)
         createStat(tr, u.damage_min .. '-' .. u.damage_max, STAT_ICONS.damage)
         createStat(tr, u.damage_min .. '-' .. u.damage_max, STAT_ICONS.damage)
        createStat(tr, MORALE_AND_LUCK[tonumber(u.morale)] or u.morale, STAT_ICONS.morale)
        createStat(tr, MORALE_AND_LUCK[tonumber(u.luck)] or u.luck, STAT_ICONS.luck)
         createStat(tr, u.initiative, STAT_ICONS.initiative)
         createStat(tr, u.initiative, STAT_ICONS.initiative)
         createStat(tr, u.speed, STAT_ICONS.speed)
         createStat(tr, u.speed, STAT_ICONS.speed)
         -- others
         -- 13 (others)
         tr:tag('td'):wikitext(u.ranged):done()
        local wording = ATTACK_WORDS[u.attackType]
        local icon =  renderIconWithHint(ATTACK_ICONS[u.attackType], words[wording], frame)
         tr:tag('td'):attr('data-sort-value', ATTACK_RANKS[u.attackType]):wikitext(icon):done()
    end
end
 
-- Main public function
------------------------------------------------------------------------------------------------------------------------
function p.display(frame)
    --do return dump(frame) end
    local growths = queryGrowths()
    do return dump(growths) end
 
    -- Args
    local args = frame.args
    local lang = args.lang ~= '' and args.lang or 'en'
    --lang = 'ru'
    local forcedFaction = FACTION_MAPPING[args.faction] or nil
    --forcedFaction = 'human'
 
    -- Language
    local suffix = lang ~= 'en' and '/' .. lang or ''
    local words = translateIds(TRANSLATION_IDS, lang)
    addFactionWords(words, lang, frame)
 
    -- Cargo
    local results = query(lang, forcedFaction)
 
    local units = consolidateResults(results, lang)
    table.sort(units, sortUnits)
 
    -- Table
    local htmlTable = mw.html.create('table')
    htmlTable:addClass('wikitable sortable')
    if forcedFaction then
        htmlTable:addClass('forced-faction')
     end
     end
    createHeader(htmlTable, words, frame)
    createBody(htmlTable, units, words, suffix, frame)


     local styleTag = frame:extensionTag('templatestyles', '', { src = 'Module:Sandbox/Aurelain/Cargo/styles.css' })
    -- Output
     return styleTag .. tostring(htmlTable)
     local styleTag = frame:extensionTag('templatestyles', '', { src = frame:getTitle() .. '/styles.css' })
     return '<div class="units-overview">' .. styleTag .. tostring(htmlTable) .. '</div>'
end
end


return p
return p

Latest revision as of 09:41, 20 July 2026

Documentation for this module may be created at Module:Sandbox/Aurelain/Cargo/doc

local p = {}

local FACTION_ORDER = {
    human = 1,
    undead = 2,
    nature = 3,
    demon = 4,
    unfrozen = 5,
    dungeon = 6,
    neutral = 7,
}

local FACTION_MAPPING = {
    Temple = 'human',
    Necropolis = 'undead',
    Grove = 'nature',
    Hive = 'demon',
    Schism = 'unfrozen',
    Dungeon = 'dungeon',
    Neutral = 'neutral'
}

-- Note: The right side is just a fallback, it will seldom be used.
local TRANSLATION_IDS = {
    wiki_ubox_growth =      'Base growth',
    creature =              'Creature',
    faction =               'Faction',
    tier =                  'Tier',
    wiki_cost =             'Cost',
    hp =                    'Hp',
    offence =               'Offence',
    defence =               'Defence',
    damage =                'Damage',
    initiative =            'Initiative',
    morale =                'Morale',
    luck =                  'Luck',
    speed =                 'Speed',
    wiki_units_neutral =    'Neutral',
    wiki_units_attack_type = 'Attack type',
    melee_attack =          'Melee Attack', -- melee_attack = 1
    wiki_units_no_counter = 'Melee,<br>no counter', -- melee_attack_no_counter = 2
    remote_attack         = 'Long Reach', -- remote_attack = 3
    ranged_attack         = 'Ranged Attack', -- ranged_attack = 4
    wiki_units_no_close = 'Ranged,<br>no melee penalty', -- ranged_attack_no_close = 5
    wiki_units_no_range = 'Ranged,<br>no range penalty', -- ranged_attack_no_range = 6
    wiki_units_no_range_close = 'Ranged,<br>no penalties', -- ranged_attack_no_range_close = 7
}

local RESOURCE_ICONS = {
    wood_cost     = 'Wood',
    ore_cost      = 'Ore',
    mercury_cost  = 'Mercury',
    dust_cost     = 'Dust',
    crystal_cost  = 'Crystal',
    gemstone_cost = 'Gemstones'
}

local STAT_ICONS = {
    hp          = 'Icon_Stats_Health',
    offence     = 'Icon_Stats_Attack',
    defence     = 'Icon_Stats_Defence',
    damage      = 'Icon_Stats_Damage',
    morale      = 'Icon_Stats_Morale',
    luck        = 'Icon_Stats_Luck',
    initiative  = 'Icon_Stats_Initiative',
    speed       = 'Icon_Stats_Speed',
}

local ATTACK_RANKS = {
    base_passive_melee_attack_name = 1,                 -- Swordsman     100,   0,   0,   0,   0,   0,   0,   0,   0
    base_passive_melee_attack_no_counter_name = 2,      -- Vampire Lord  101,   0,   0,   0,   0,   0,   0,   0,   0
    base_passive_remote_attack_name = 3,                -- Graverobber     0, 100,   0,   0,   0,   0,   0,   0,   0
    base_passive_ranged_attack_name = 4,                -- Onyx Dancer    50, 100, 100,  90,  80,  70,  60,  50,  50
    base_passive_ranged_attack_no_close_name = 5,       -- Apotheosis    100, 100, 100,  90,  80,  70,  60,  50,  50
    base_passive_ranged_attack_no_range_name = 6,       -- Marksman       50, 100, 100, 100, 100, 100, 100, 100, 100
    base_passive_ranged_attack_no_range_close_name = 7, -- Halfling      100, 100, 100, 100, 100, 100, 100, 100, 100
}

local ATTACK_ICONS = {
    base_passive_melee_attack_name = 'Base_passive_melee_attack',
    base_passive_melee_attack_no_counter_name = 'Base_passive_noncounter',
    base_passive_remote_attack_name = 'Base_passive_remote_attack',
    base_passive_ranged_attack_name = 'Base_passive_ranged_attack', -- TODO: clarify icon
    base_passive_ranged_attack_no_close_name = 'Base passive duelist', -- TODO: clarify icon
    base_passive_ranged_attack_no_range_name = 'Base_passive_sharpshooter', -- TODO: clarify icon
    base_passive_ranged_attack_no_range_close_name = 'Arbitrator_passive_1', -- TODO: clarify icon
}
local ATTACK_WORDS = {
    base_passive_melee_attack_name = 'melee_attack',
    base_passive_melee_attack_no_counter_name = 'wiki_units_no_counter',
    base_passive_remote_attack_name = 'remote_attack',
    base_passive_ranged_attack_name = 'ranged_attack',
    base_passive_ranged_attack_no_close_name = 'wiki_units_no_close',
    base_passive_ranged_attack_no_range_name = 'wiki_units_no_range',
    base_passive_ranged_attack_no_range_close_name = 'wiki_units_no_range_close',
}

local ROMAN = { 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII' }

local PAGES = {
    Stinger = 'Stinger_(unit)',
}

local MORALE_AND_LUCK = {
    '<span class="elevated1">1</span>',
    '<span class="elevated2">2</span>',
    '<span class="elevated3">3</span>',
}

-- Awards a number from 0 to 3 for a unit, based on how upgraded it is
------------------------------------------------------------------------------------------------------------------------
local function computeUpgradeRank(row)
    local base = (row['base'] and row['base'] ~= "") and 1 or 0
    local upgrade = (row['upgrade'] and row['upgrade'] ~= "") and 10 or 0
    local sum = base + upgrade
    if sum == 1 then
        return 3
    elseif sum == 10 then
        return 1
    elseif sum == 0 then
        return 0
    else
        return 2
    end
end

-- Returns one of the ATTACK_RANKS keys (e.g. 'base_passive_melee_attack_name') or an empty string
------------------------------------------------------------------------------------------------------------------------
local function computeAttackType(row)
    local abilities = row['shared_abilities']
    if type(abilities) ~= "string" then
        return ""
    end
    for key, _ in pairs(ATTACK_RANKS) do
        local pattern = "%f[%w]" .. key .. "%f[%W]"
        if string.match(abilities, pattern) then
            return key
        end
    end
    return ""
end

-- Returns a rich wikitext with numbers and icons
------------------------------------------------------------------------------------------------------------------------
local function computeCost(row)
    local gold = row['gold_cost']
    local cost = gold .. '[[File:Icon_Resource_Gold.png|24px|link=]]'
    for key, icon in pairs(RESOURCE_ICONS) do
        local val = row[key]
        if val and val ~= '' and val ~= 0 then
            cost = cost .. ' ' .. val .. '[[File:Icon_Resource_' .. icon .. '.png|24px|link=]]'
        end
    end
    return cost
end

-- Parses and runs a Cargo query from wiki-like syntax
------------------------------------------------------------------------------------------------------------------------
local function runQuery(query, ...)
    query = string.gsub(query, "%-%-.-\n", "") -- remove "comments"
    query = select('#', ...) > 0 and mw.ustring.format(query, ...) or query
    query = mw.text.trim(query)
    local tables = ''
    local fields = ''
    local options = {}
    for part in query:gmatch('[^|]+') do
        local key, val = part:match('^%s*([^=]+)%s*=%s*(.-)%s*$')
        if key and val then
            key = mw.text.trim(key):lower()
            val = mw.text.trim(val)
            val = val:gsub('%s', ' ')
            if key == 'tables' then
                tables = val
            elseif key == 'fields' then
                fields = val
            elseif key == 'limit' then
                options[key] = tonumber(val) or val
            elseif key == 'join on' then
                options['join'] = val
            else
                options[key] = val
            end
        end
    end
    local success, result = pcall(function()
        return mw.ext.cargo.query(tables, fields, options)
    end)
    return success and result or {}
end

-- Retrieves the data from Cargo
------------------------------------------------------------------------------------------------------------------------
local function query(lang, forcedFaction)
    local tables = 'Unit, Translation'
    local fields = '' ..
        'Unit.id=id, ' ..
        'Unit.faction=faction, ' ..
        'Unit.tier=tier, ' ..
        'Unit.hp=hp, ' ..
        'Unit.offence=offence, ' ..
        'Unit.defence=defence, ' ..
        'Unit.damage_min=damage_min, ' ..
        'Unit.damage_max=damage_max, ' ..
        'Unit.morale=morale, ' ..
        'Unit.luck=luck, ' ..
        'Unit.initiative=initiative, ' ..
        'Unit.speed=speed, ' ..
        'Unit.shared_abilities=shared_abilities, ' .. -- we use it for range detection
        -- costs
        'Unit.gold_cost=gold_cost, ' ..
        'Unit.wood_cost=wood_cost, ' ..
        'Unit.ore_cost=ore_cost, ' ..
        'Unit.mercury_cost=mercury_cost, ' ..
        'Unit.dust_cost=dust_cost, ' ..
        'Unit.crystal_cost=crystal_cost, ' ..
        'Unit.gemstone_cost=gemstone_cost, ' ..
        -- upgrade
        'Unit.base_sid=base, ' ..
        'Unit.upgrade_sid=upgrade, ' ..
        -- Translation
        'Translation.language=language, ' ..
        'Translation.name=transName'

    -- where:
    local where = {}
    if forcedFaction then
        table.insert(where, 'Unit.faction="' .. forcedFaction .. '"')
    end
    table.insert(where, '(Translation.language = "en" OR Translation.language = "' .. lang .. '")')

    -- Get BOTH the English row AND the target language row
    local cargoArgs = {
        join = 'Unit.id = Translation.target_id',
        where = table.concat(where, ' AND '),
        orderBy = 'Unit.id ASC',
        limit = 1000 -- Increased limit since each unit will return 2 rows
    }

    return mw.ext.cargo.query(tables, fields, cargoArgs)
end

-- Gets the weekly increment for all units from the MapObject table
------------------------------------------------------------------------------------------------------------------------
local function queryGrowths()
    return runQuery([[
       tables =
           MapObject = M
       | where =
           M.units_weekly > 0
       | fields =
           M.units_hire_sid = units_hire_sid,
           M.units_weekly = units_weekly
       | limit =
           100
   ]]);
end

-- Scans the Cargo results and folds the EN and lang rows into a single row
------------------------------------------------------------------------------------------------------------------------
local function consolidateResults(results, lang)
    local units = {}
    for _, row in ipairs(results) do
        local id = row['id']

        -- If this is the first time seeing this id, set up its basic stats
        if not units[id] then
            units[id] = mw.clone(row)
            units[id].upgradeRank = computeUpgradeRank(row)
            units[id].attackType = computeAttackType(row)
            units[id].cost = computeCost(row)
        end

        -- Save the names based on which language row we are currently looping over
        if row['language'] == 'en' then
            units[id].nameEn = row['transName']
        end
        if row['language'] == lang then
            units[id].nameX = row['transName']
        end
    end

    -- Convert the Dictionary into an Array
    local unitsArray = {}
    for _, unitData in pairs(units) do
        table.insert(unitsArray, unitData)
    end

    return unitsArray
end

-- Decides the order between two units, for sorting purposes.
------------------------------------------------------------------------------------------------------------------------
local function sortUnits(unitA, unitB)
    local rankA = FACTION_ORDER[unitA.faction] or 99
    local rankB = FACTION_ORDER[unitB.faction] or 99

    if rankA ~= rankB then
        return rankA < rankB
    end

    if unitA.tier ~= unitB.tier then
        return unitA.tier < unitB.tier
    end

    if unitA.upgradeRank ~= unitB.upgradeRank then
        return unitA.upgradeRank < unitB.upgradeRank
    end

    return unitA.hp < unitB.hp
end

-- Retrieves the text for some specific ids from Cargo Translations.
------------------------------------------------------------------------------------------------------------------------
local function translateIds(ids, lang, extra)
    -- Key list
    local list = {}
    for key, _ in pairs(ids) do
        list[#list + 1] = key
    end
    local idListString = '"' .. table.concat(list, '", "') .. '"'

    -- Cargo
    local where = {}
    table.insert(where, 'target_id IN (' .. idListString .. ')')
    table.insert(where, 'language = "' .. lang .. '"')
    if extra then
        table.insert(where, extra)
    end
    local results = mw.ext.cargo.query('Translation', 'target_id, name', {
        where = table.concat(where, ' AND '),
        limit = 100
    })

    -- Dictionary
    local dictionary = mw.clone(ids)
    for key, value in pairs(dictionary) do
        --dictionary[key] = value .. '[[Data:WikiTranslations/' .. lang .. '#' .. key .. '|💬]]'
        dictionary[key] = value .. '💬'
    end
    for _, row in ipairs(results) do
        local name = row['name']
        if name and name ~= '' and not name:find('💬') then
            dictionary[row['target_id']] = name
        end
    end
    return dictionary
end

-- Displays a variable
------------------------------------------------------------------------------------------------------------------------
local function dump(target)
    return '<pre>' .. mw.dumpObject(target) .. '</pre>'
end

-- Builds an icon+text combo for the unit's name
------------------------------------------------------------------------------------------------------------------------
local function renderUnitName(u, suffix)
    local stem = PAGES[u.nameEn] or u.nameEn
    local page = stem .. suffix
    local img = '[[File:' .. u.nameEn .. ' icon.png|64px|link=' .. page .. ']]'
    local text = '[[' .. page .. '|' .. u.nameX .. ']]'
    return img .. ' ' .. text
end

-- Boilerplate for the header cells
------------------------------------------------------------------------------------------------------------------------
local function addTh(tr, text)
    tr:tag('th'):wikitext(text):done()
end

-- Boilerplate for stat tds
------------------------------------------------------------------------------------------------------------------------
local function createStat(tr, value, pngName)
    tr:tag('td'):wikitext(value .. '[[File:' .. pngName .. '.png|link=]]'):done()
end

-- Boilerplate for the separator
------------------------------------------------------------------------------------------------------------------------
local function addSeparator(htmlTable, className, content)
    htmlTable:tag('tr')
        :addClass('separator')
        :addClass(className)
        :tag('td'):attr('data-sort-value', ''):attr('colspan', 100):wikitext(content):done()
end

------------------------------------------------------------------------------------------------------------------------
local function addFactionWords(words, lang, frame)
    for key, _ in pairs(FACTION_ORDER) do
        words[key] = frame:preprocess('{{F|' .. key .. '|' .. lang .. '}}')
    end
end

------------------------------------------------------------------------------------------------------------------------
local function renderIconWithHint(fileName, text, frame)
    local file = '[[File:' .. fileName .. '.png|32px|link=]]';
    return frame:preprocess('{{Hint|' .. file .. '|' .. text .. '}}')
end

------------------------------------------------------------------------------------------------------------------------
local function createHeader(htmlTable, words, frame)
    local header = htmlTable:tag('tr')
    -- 1 to 4 (general)
    addTh(header, words.creature)
    addTh(header, words.faction)
    addTh(header, words.tier)
    addTh(header, words.wiki_cost)
    -- 5 to 12 (main stats)
    addTh(header, renderIconWithHint(STAT_ICONS.hp, words.hp, frame))
    addTh(header, renderIconWithHint(STAT_ICONS.offence, words.offence, frame))
    addTh(header, renderIconWithHint(STAT_ICONS.defence, words.defence, frame))
    addTh(header, renderIconWithHint(STAT_ICONS.damage, words.damage, frame))
    addTh(header, renderIconWithHint(STAT_ICONS.morale, words.morale, frame))
    addTh(header, renderIconWithHint(STAT_ICONS.luck, words.luck, frame))
    addTh(header, renderIconWithHint(STAT_ICONS.initiative, words.initiative, frame))
    addTh(header, renderIconWithHint(STAT_ICONS.speed, words.speed, frame))
    -- 13 (others)
    addTh(header, renderIconWithHint('Sunlight_cavalry_passive_3', words.wiki_units_attack_type, frame))
end

------------------------------------------------------------------------------------------------------------------------
local function createBody(htmlTable, units, words, suffix, frame)
    local currentTier = units[1].tier
    local currentFaction = units[1].faction
    for _, u in ipairs(units) do

        -- separators
        if u.faction ~= currentFaction then
            currentFaction = u.faction
            currentTier = u.tier
            addSeparator(htmlTable, 'separator-large', words[currentFaction])
        elseif u.tier ~= currentTier then
            currentTier = u.tier
            addSeparator(htmlTable, 'separator-tiny', '')
        end

        local tr = htmlTable:tag('tr'):addClass('unit')
        if u.upgradeRank == 2 or u.upgradeRank == 3 then
            tr:addClass('upgraded')
        end
        -- 1 to 4 (general)
        tr:tag('td'):wikitext(renderUnitName(u, suffix)):done()
        tr:tag('td'):wikitext(words[currentFaction]):done()
        tr:tag('td'):wikitext(ROMAN[tonumber(u.tier)]):done()
        tr:tag('td'):attr('data-sort-value', string.match(u.cost, "^%d+")):wikitext(u.cost):done()
        -- 5 to 12 (main stats)
        createStat(tr, u.hp, STAT_ICONS.hp)
        createStat(tr, u.offence, STAT_ICONS.offence)
        createStat(tr, u.defence, STAT_ICONS.defence)
        createStat(tr, u.damage_min .. '-' .. u.damage_max, STAT_ICONS.damage)
        createStat(tr, MORALE_AND_LUCK[tonumber(u.morale)] or u.morale, STAT_ICONS.morale)
        createStat(tr, MORALE_AND_LUCK[tonumber(u.luck)] or u.luck, STAT_ICONS.luck)
        createStat(tr, u.initiative, STAT_ICONS.initiative)
        createStat(tr, u.speed, STAT_ICONS.speed)
        -- 13 (others)
        local wording = ATTACK_WORDS[u.attackType]
        local icon =  renderIconWithHint(ATTACK_ICONS[u.attackType], words[wording], frame)
        tr:tag('td'):attr('data-sort-value', ATTACK_RANKS[u.attackType]):wikitext(icon):done()
    end
end

-- Main public function
------------------------------------------------------------------------------------------------------------------------
function p.display(frame)
    --do return dump(frame) end
    local growths = queryGrowths()
    do return dump(growths) end

    -- Args
    local args = frame.args
    local lang = args.lang ~= '' and args.lang or 'en'
    --lang = 'ru'
    local forcedFaction = FACTION_MAPPING[args.faction] or nil
    --forcedFaction = 'human'

    -- Language
    local suffix = lang ~= 'en' and '/' .. lang or ''
    local words = translateIds(TRANSLATION_IDS, lang)
    addFactionWords(words, lang, frame)

    -- Cargo
    local results = query(lang, forcedFaction)

    local units = consolidateResults(results, lang)
    table.sort(units, sortUnits)

    -- Table
    local htmlTable = mw.html.create('table')
    htmlTable:addClass('wikitable sortable')
    if forcedFaction then
        htmlTable:addClass('forced-faction')
    end
    createHeader(htmlTable, words, frame)
    createBody(htmlTable, units, words, suffix, frame)

    -- Output
    local styleTag = frame:extensionTag('templatestyles', '', { src = frame:getTitle() .. '/styles.css' })
    return '<div class="units-overview">' .. styleTag .. tostring(htmlTable) .. '</div>'
end

return p