Editing Module:Sandbox/LVL

Warning: You are not logged in. Once you make an edit, a temporary account will be created for you. Learn more. Log in or create an account to continue receiving notifications after this account expires, and to access other features.
The edit can be undone. Please check the comparison below to verify that this is what you want to do, and then publish the changes below to finish undoing the edit.
Latest revision Your text
Line 1: Line 1:
-- ====================================================================
-- Dependencies and Initial Setup
-- ====================================================================
local lang = require "Module:Lang"
local commonutils = require "Module:Utilities"
local utils = require "Module:Abilities/utils"
local p = {}
local p = {}
local data = mw.loadJsonData("Data:AbilityCards.json")


local heroes_data      = mw.loadJsonData("Data:HeroData.json")
-- (ATTR_TYPE_ICON_MAP and helper functions remain the same)
local attributes_data  = mw.loadJsonData("Data:AttributeData.json")
local ATTR_TYPE_ICON_MAP = {
local attribute_orders  = mw.loadJsonData("Data:StatInfoboxOrder.json")
bullet_armor_up = {img='Bullet_Armor.png', link='Damage_Resistance', color = 'NoColor'},
local util_module      = require('Module:Utilities')
bullet_armor_down = {img='Bullet_Armor.png', link='Damage_Resistance', color = 'NoColor'},
local lang_module      = require('Module:Lang')
cast = {img='AttributeIconMaxChargesIncrease.png', link=''},
local dictionary_module = require('Module:Dictionary')
charges = {img='AttributeIconMaxChargesIncrease.png', link='', color = 'Purple'},
local attribute_module  = require('Module:AttributeData')
damage = {img='Damage_heart.png', link='', color = 'NoColor'},
local hero_data_module  = require('Module:HeroData')
bullet_damage = {img='Bullet_damage.png', link='Bullet_Damage', color = 'NoColor'},
fire_rate = {img='Fire Rate.png', link='Fire_Rate', color = 'Brown'},
healing = {img='Healing.png', link='Healing', color = 'Green'},
health = {img='Health.png', link='Health', color = 'Green'},
move_speed = {img='Move speed.png', link='Move Speed', color = 'Green'},
range = {img='CastRange.png', link='Ability_Range', color = 'Purple'},
tech_armor_up = {img='Spirit_Armor.png', link='Damage_Resistance', color = 'NoColor'},
tech_damage = {img='AttributeIconTechShieldHealth.png', link='Spirit_Damage', color = 'NoColor',size = '12px'},
distance = {img='AttributeIconTechRange.png', link='Ability_Range', color = 'Purple'},
duration = {img='AttributeIconTechDuration.png', link='Ability Duration', color = 'Purple'},
slow = {img='MoveSlow.png', link='', color = 'Purple'},
melee_damage = {img='Melee damage.png', link='Melee Damage'},
cooldown = {img='Cooldown Icon.png', link='Ability Cooldown', color = 'Purple'},
combat_barrier = {img='Barrier.png', link='Barrier', color = 'Green'},
time = {img='AttributeIconTechDuration.png', link='Ability Duration', color = 'Purple'},
}


local function get_nested_stat_value(hero_data, stat_key)
function get_hero_key(hero_name) -- Unchanged
    if hero_data[stat_key] ~= nil then
for i, hero in pairs(data) do
        return hero_data[stat_key]
if hero["Name"] == hero_name then return i end
    elseif hero_data.Weapon and hero_data.Weapon[stat_key] ~= nil then
end
        return hero_data.Weapon[stat_key]
return nil
    elseif hero_data.Weapon and hero_data.Weapon.AltFire and hero_data.Weapon.AltFire[stat_key] ~= nil then
        return hero_data.Weapon.AltFire[stat_key]
    end
    return 0
end
end


local function localize(key, fallback)
function get_icon(attr_type) -- Unchanged
    local result = lang_module.get_string(key)
local mappedAttr = ATTR_TYPE_ICON_MAP[attr_type]
    if result == "" or result == nil then
local img = 'GenericProperty.png'
        result = util_module.add_space_before_cap(fallback) ..
local link = ''
                mw.getCurrentFrame():expandTemplate{title = "MissingValveTranslationTooltip"}
local size = ''
    end
local color = 'Grey'
    return result
if mappedAttr then
img = mappedAttr.img
link = mappedAttr.link
size = mappedAttr.size
color = mappedAttr.color or color
end
return {img=img, link=link, color=color, size=size}
end
end


-- =========================================================================
function get_attr_ss(attr) -- Unchanged
--  DPS calculation helpers
if not attr then return nil end
-- =========================================================================
local scale = attr.Scale
if not scale or scale.Type ~= 'spirit' or scale.Value == 0 then return nil end
return commonutils.round_to_sig_fig(scale.Value, 3)
end


local function calculate_dps(stats, dps_type)
-- ====================================================================
    local rps = stats.RoundsPerSecond or 0
-- HTML Builder Functions (With Final Fixes)
    if rps == 0 then return 0 end
-- ====================================================================


    local bullets_per_shot = (stats.HitOnceAcrossAllBullets and 1) or (stats.BulletsPerShot or 1)
local function buildMultiplierHtml(type, value, icon_size) -- Unchanged from last version
    local burst_count = stats.BulletsPerBurst or 1
local config = {
    local cycle_time = 1 / rps
spirit = { color = "#E3BDFA", bgColor = "#533669", icon = "Spirit scaling.png", link = "Spirit Power#Spirit Power Scaling", size = icon_size or "40px" },
    local total_cycle_time = cycle_time * burst_count
melee = { color = "#cdb89e", bgColor = "#80550f", icon = "Melee scaling.png", link = "Melee Damage#Abilities", size = icon_size or "40px" },
boon = { color = "#bec1ac", bgColor = "#217a68", icon = "Boon scaling.png", link = "Level#Boons from Patron", size = icon_size or "25px" },
weapon_damage_increase = { color = "#cdb89e", bgColor = "#80550f", icon = "Weapon scaling.png", link = "Weapon Damage", size = icon_size or "40px" }
}
local c = config[type]
if not c or not value then return '' end
local icon = string.format('[[File:%s|link=%s|%s]]', c.icon, c.link, c.size)
return string.format(
'<span style="font-size: 0.8em; color: %s; white-space: nowrap;">%s<span style="background-color: %s; font-family: \'Retail Demo Regular\', \'PT Serif\', \'Palatino\'; font-weight:bold; width: auto; border-radius: 5px; padding: 2px 2px 0px 2px; margin-left: -2px;"><i>x</i>%s</span></span>',
c.color, icon, c.bgColor, value
)
end


    if total_cycle_time == 0 then return 0 end
--- FIXED: Replicates the original HeaderAttr template exactly.
local function buildHeaderAttrHtml(value, uom, ss, icon, style)
if not value or value == '' then return '' end
local frame = mw.getCurrentFrame()
-- The original template used {{Icon/Grey}}, which we can replicate with a span and filter for simplicity,
-- or just output the icon directly if the filter isn't critical. Let's keep it simple.
local mainBox = string.format('%s %s',
icon,
frame:expandTemplate{ title = "ValueAndUom", args = {
"'''" .. value .. "'''",
uom,
uom_style = "font-size: calc(1em - 2px); color: #B2B2B2"
}}
)


    local base_damage = stats.BulletDamage or 0
local spiritScale = ''
    if dps_type == 'burst' then
if ss and ss ~= '' then
        return base_damage * bullets_per_shot * burst_count / total_cycle_time
spiritScale = string.format(
    end
'<div style="position: relative;"><div style="position: absolute; top: -24px; right: -14px">%s</div></div>',
 
buildMultiplierHtml('spirit', ss, '28px')
    local clip_size = stats.ClipSize or 0
)
    if clip_size <= 0 then
end
        return base_damage * bullets_per_shot * burst_count / total_cycle_time
    end
return string.format(
 
'<div style="background-color: #2C2C2C; padding: 10px 6px 10px 6px; margin-right: 20px; white-space: nowrap; %s">%s</div>%s',
    local reload_time
style or '', mainBox, spiritScale
    if stats.ReloadSingle then
)
        reload_time = (stats.ReloadTime or 0) * clip_size
    else
        reload_time = stats.ReloadTime or 0
    end
    reload_time = reload_time + (stats.ReloadDelay or 0)
 
    local time_to_empty_clip = (clip_size / burst_count) * total_cycle_time
    local damage_from_clip = base_damage * bullets_per_shot * clip_size
    local total_time = time_to_empty_clip + reload_time
    if total_time == 0 then return 0 end
    return damage_from_clip / total_time
end
end


-- Compute how much DPS changes when all relevant component scalings are applied.
--- FIXED: Removed "overflow: hidden;" to prevent clipping.
-- Used for alt-fire rows where explicit DPS/SustainedDPS scaling keys are missing.
local function buildMainBoxHtml(prop, hero_key)
local function compute_dps_scaling(hero_data, base_stats, dps_type, scaling_type)
local frame = mw.getCurrentFrame()
    local scaling_source = hero_data[scaling_type .. "Scaling"] or {}
local scale_type = prop.Scale and prop.Scale.Type
 
local scale_value = prop.Scale and commonutils.round_to_sig_fig(prop.Scale.Value, 3)
    local component_scalings = {}
    local possible_keys = {
local scale_styles = {
        "BulletDamage", "RoundsPerSecond", "ClipSize", "ReloadTime",
melee = { grad = "radial-gradient(circle, rgba(36,37,36,1) 0%%, rgba(66,55,47,1) 100%%)", border = "#5b412b", shadow = "#3d2c4d" },
        "ReloadDelay", "BulletsPerShot", "BulletsPerBurst"
spirit = { grad = "radial-gradient(circle, rgba(42,41,43,1) 0%%, rgba(59,49,69,1) 100%%)", border = "#583D6F", shadow = "#3d2c4d" },
    }
power_increase = { grad = "radial-gradient(circle, rgba(42,41,43,1) 0%%, rgba(61,78,70,1) 100%%)", border = "#48675a", shadow = "#3d2c4d" }
    for _, key in ipairs(possible_keys) do
}
        local alt_key = key .. "AltFire"
local current_style = scale_styles[scale_type] or { grad = "#2A2A2A", border = "#2A2A2A", shadow = "#2A2A2A" }
        if scaling_source[alt_key] then
            component_scalings[key] = scaling_source[alt_key]
local multiplierHtml = buildMultiplierHtml(scale_type, scale_value)
        end
    end
 
    -- ClipSize is shared between fire modes; fall back to primary scaling
    if base_stats.ClipSize and not component_scalings.ClipSize then
        local primary_clip_scale = scaling_source["ClipSize"]
        if primary_clip_scale then
            component_scalings.ClipSize = primary_clip_scale
        end
    end


    if next(component_scalings) == nil then
local icon_data = get_icon(prop.Type)
        return 0
local value = prop.Value
    end
if scale_type == 'melee' then
local hero_data = mw.loadJsonData("Data:HeroData.json")
local hero = hero_data[hero_key]
if hero and hero.LightMeleeDamage and prop.Scale.Value then
value = prop.Value + hero.LightMeleeDamage * prop.Scale.Value
end
end
local iconHtml = frame:expandTemplate{ title = 'Icon/' .. (icon_data.color or 'Grey'), args = {
string.format('[[File:%s|%s|link=%s]]', icon_data.img, icon_data.size or '18px', icon_data.link),
frame:expandTemplate{ title = 'ValueAndUom', args = {
"'''" .. value .. "'''",
id = prop.Key,
frame:expandTemplate{ title = 'Lang', args = { key = prop.Key .. '_postfix' } },
uom_style = 'font-size: calc(1em - 2px); color: #B2B2B2'
}}
}}


    local base_dps = calculate_dps(base_stats, dps_type)
return string.format(
    local scaled_stats = {}
-- REMOVED "overflow: hidden;" FROM THE FIRST DIV'S STYLE
    for k, v in pairs(base_stats) do scaled_stats[k] = v end
'<div style="display:flex; flex-direction:column; flex-grow: 1; flex-basis: 0; max-height: 100%%; padding: 10px 0px 10px 0px; margin: 3px;">' ..
    for comp_key, scale_val in pairs(component_scalings) do
'  %s' ..
        if scaled_stats[comp_key] ~= nil then
'  <div style="position: relative;"><div style="position: absolute; top: -20px; right: -2px">%s</div></div>' ..
            scaled_stats[comp_key] = scaled_stats[comp_key] + scale_val
'  <div style="display:flex; flex-direction:column; flex-grow: 1; justify-content: space-between; background: %s; text-align: center; border: 3px solid %s; box-shadow: 0 0 10px %s; border-radius: 1px">' ..
        end
'    <div style="font-weight: bold;">%s</div>' ..
    end
'    <div style="font-size: 0.8rem; padding-bottom: 3px">%s</div>' ..
    local scaled_dps = calculate_dps(scaled_stats, dps_type)
'  </div>' ..
    return scaled_dps - base_dps
'</div>',
prop.Title and string.format('<div style="padding-bottom: 2px; font-size: 0.8rem; color: #9C9C9C; font-variant: small-caps;"><b>%s</b></div>', prop.Title) or '',
multiplierHtml,
current_style.grad,
current_style.border,
current_style.shadow,
iconHtml,
frame:expandTemplate{ title = 'Lang', args = { key = prop.Key .. '_label' }}
)
end
end


-- =========================================================================
local buildAltBoxHtml = function(...) end -- Forward declare
--  Main module function
local buildUpgradeBoxHtml = function(...) end -- Forward declare
-- =========================================================================


p.write_hero_comparison_table = function(frame)
-- ====================================================================
    local power_increases = tonumber(frame.args[1]) or 0
-- Main Entry Point (With Final Fixes)
    local spirit_power    = tonumber(frame.args[2]) or 0
-- ====================================================================
    local max_power      = tonumber(frame.args[3]) or 25
    local max_spirit      = tonumber(frame.args[4]) or 500


    local display_scaling_icons = (power_increases == 0 and spirit_power == 0)
function p.get_ability_card(frame_args)
local frame = mw.getCurrentFrame()
local args = frame_args.args


    local body_str = ""
local hero_name = args[1]
local ability_num = args[2]
local add_link = args[3] == 'true'
local notes = args[4]
local hero_key = get_hero_key(hero_name)
if not hero_key then return 'Hero with name "' .. tostring(hero_name) .. '" not found' end
local ability = utils.get_ability_card_data(hero_key, ability_num)
if not ability then return 'Ability data not found for hero ' .. tostring(hero_key) .. ' and num ' .. tostring(ability_num) end
local html = {}
local ability_name_localized = lang.get_string(ability.Key)
local name_link_target = add_link and ability_name_localized or nil
-- Header Section
local header_attrs_left = {}
local cast_time_data = ability.Cast and ability.Cast.AbilityChannelTime
table.insert(header_attrs_left, buildHeaderAttrHtml(cast_time_data and cast_time_data.Value, 's', get_attr_ss(cast_time_data), '[[File:AttributeIconMaxChargesIncrease.png|Channel Time|20px|link=]]'))
table.insert(header_attrs_left, buildHeaderAttrHtml(ability.AbilityCastRange and ability.AbilityCastRange.Value, 'm', get_attr_ss(ability.AbilityCastRange), '[[File:CastRange.png|Cast Range|20px|link=]]'))
table.insert(header_attrs_left, buildHeaderAttrHtml(ability.Radius and ability.Radius.Value, 'm', get_attr_ss(ability.Radius), '[[File:AttributeIconTechRange.png|Radius|20px|link=]]'))
table.insert(header_attrs_left, buildHeaderAttrHtml(ability.AbilityDuration and ability.AbilityDuration.Value, 's', get_attr_ss(ability.AbilityDuration), '[[File:AttributeIconTechDuration.png|Duration|20px|link=]]'))


    local stats_to_include = {
local header_attrs_right_top = {}
        Weapon = {
table.insert(header_attrs_right_top, buildHeaderAttrHtml(ability.AbilityCharges and ability.AbilityCharges.Value, '', nil, '[[File:AttributeIconMaxChargesIncrease.png|Number of Charges|20px|link=]]', 'margin-right: 0;'))
            "DPS", "SustainedDPS", "BulletDamage", "RoundsPerSecond", "FireRate",
table.insert(header_attrs_right_top, buildHeaderAttrHtml(ability.AbilityCooldownBetweenCharge and ability.AbilityCooldownBetweenCharge.Value, 's', get_attr_ss(ability.AbilityCooldownBetweenCharge), '[[File:AttributeIconTechCooldownBetweenChargeUses.png|Charge Cooldown|16px|link=]]', 'margin-left: 1px; margin-right: 0;'))
            "ClipSize", "ReloadTime", "ReloadDelay", "ReloadSingle", "BulletsPerShot", "BulletsPerBurst",
            "BurstInterShotInterval", "LightMeleeDamage", "HeavyMeleeDamage",
local header_attrs_right_bottom = buildHeaderAttrHtml(ability.AbilityCooldown and ability.AbilityCooldown.Value, 's', get_attr_ss(ability.AbilityCooldown), '[[File:AttributeIconTechCooldown.png|Cooldown|20px|link=]]')
            "BulletSpeed", "FalloffStartRange", "FalloffEndRange",
            "CritDamageBonusPercent", "BulletRadius", "RoundsPerSecondAtMaxSpin", "SpinAcceleration", "SpinDeceleration"
        },
        Vitality = {
            "MaxHealth", "BaseHealthRegen", "BulletResist", "TechResist", "MeleeResist",
            "CritDamageReceivedPercent", "DebuffResist", "BulletLifesteal", "MaxMoveSpeed",
            "SprintSpeed", "StaminaCooldown", "Stamina", "GroundDashSpeed", "GravityChange"
        },
        Spirit = { "TechPower" }
    }


    -- Collect and sort heroes alphabetically, excluding disabled/in-development
table.insert(html, string.format(
    local sorted_heroes = {}
'<div style="width: 100%%;"><div style="display:flex; flex-direction:row; justify-content: space-between; background: #121212; font-size: calc(1em - 2px); border-radius: 13px 13px 0 0; padding: 0 8px 14px 8px;">' ..
    for hero_key, hero_data in pairs(heroes_data) do
'  <div style="display:flex; flex-direction:column;">' ..
        if not hero_data["InDevelopment"] and not hero_data["IsDisabled"] then
'    <div style="font-size: 1.3rem;"><span style="filter: brightness(0) saturate(100%%) invert(98%%) sepia(19%%) saturate(1458%%) hue-rotate(301deg) brightness(102%%) contrast(109%%); padding: 0 5px 0 7px">[[File:%s.png|45px|link=]]</span><span style="font-family:\'Retail Demo\',\'Open Sans\'; font-weight:bold">%s</span></div>' ..
            table.insert(sorted_heroes, {key = hero_key, data = hero_data})
'    <div style="display:flex; flex-direction:row; margin-left: 10px; height: 40px;">%s</div>' ..
        end
'  </div>' ..
    end
'  <div style="display:flex; flex-direction:column; align-items: end; justify-content: flex-end;">' ..
    table.sort(sorted_heroes, function(a, b)
'    <div style="display:flex; flex-direction:row; justify-content: flex-end; margin-bottom: 5px; margin-right: 20px;">%s</div>' ..
        local function get_sort_name(name)
'    %s' ..
            return (name:gsub("^The ", ""))
'  </div>' ..
        end
'</div></div>',
        return get_sort_name(a.data["Name"] or a.key) < get_sort_name(b.data["Name"] or b.key)
lang.get_string(ability.Key, 'en'),
    end)
name_link_target and string.format('[[%s|%s]]', name_link_target, ability_name_localized) or ability_name_localized,
table.concat(header_attrs_left),
table.concat(header_attrs_right_top),
header_attrs_right_bottom
))
-- Info Sections
table.insert(html, '<div style="margin: 5px 10px 0px 10px; padding: 3px 0 5px 0; width: calc(100%% - 18px); box-sizing: unset;">')
for i = 1, 3 do
local info_section = ability['Info' .. i]
if info_section then
local desc = (info_section.DescKey and lang.get_string(info_section.DescKey)) or ''
local main_boxes, alt_boxes = {}, {}
if info_section.Main and info_section.Main.Props then
for _, prop in ipairs(info_section.Main.Props) do
if prop.Value and prop.Value ~= 0 then
table.insert(main_boxes, buildMainBoxHtml(prop, hero_key))
end
end
end
if info_section.Alt then
for _, prop in ipairs(info_section.Alt) do
if prop.Value and prop.Value ~= 0 then
table.insert(alt_boxes, buildAltBoxHtml(prop))
end
end
end


    -- Build a single stat cell (<td>) with data attributes for JS recalculation
if desc ~= '' or #main_boxes > 0 or #alt_boxes > 0 then
    local function buildStatCell(hero_data, hero_key, attr_key, is_alt_fire, category)
local alt_box_container = ''
        -- Conversion factors for stats that need unit changes (e.g. metres → centimetres)
if #alt_boxes > 0 then
        local unit_conversion = {
-- FIXED: Added the missing wrapper div for alt boxes.
            BulletRadius = 100  -- metres to centimetres
alt_box_container = string.format(
        }
'<div style="display:flex; flex-direction:row; flex-wrap: wrap; justify-content: center; align-items: center; background-color: #2A2A2A; width: calc(97%% - 19px); min-width: 267px; padding: 0 4px 0 4px; column-gap: 15px">%s</div>',
        local conv_factor = unit_conversion[attr_key] or 1
table.concat(alt_boxes)
)
end


        local base_value
table.insert(html, string.format(
        if is_alt_fire then
'<div style="display:flex; flex-direction:column; align-items: center; width: 100%%; padding-top: 8px;">' ..
            if attr_key == "ClipSize" or attr_key == "ReloadTime" then
'  <div style="padding: 0 10px 10px 10px">%s</div>' ..
                base_value = get_nested_stat_value(hero_data, attr_key)
'  <div style="display:flex; flex-direction:row; flex-wrap: wrap; justify-content: center; width: calc(97%% - 5px); min-width: 280px;">%s</div>' ..
            elseif hero_data.Weapon and hero_data.Weapon.AltFire
'  %s' ..
                and hero_data.Weapon.AltFire[attr_key] ~= nil then
'</div>',
                base_value = hero_data.Weapon.AltFire[attr_key]
frame:preprocess(desc),
            else
table.concat(main_boxes),
                base_value = get_nested_stat_value(hero_data, attr_key)
alt_box_container
            end
))
        else
end
            base_value = get_nested_stat_value(hero_data, attr_key)
end
        end
end
table.insert(html, '</div>')
-- Upgrades Section
local upgrade_boxes = {}
if ability.Upgrades then
for i, prop in ipairs(ability.Upgrades) do
table.insert(upgrade_boxes, buildUpgradeBoxHtml(prop, i))
end
end
table.insert(html, string.format(
'<div style="display:flex; flex-direction:row; flex-wrap: wrap; margin-bottom: 5px; justify-content: center; width: calc(97%% - 16px); min-width: 280px;">%s</div>',
table.concat(upgrade_boxes)
))
-- Notes Section
if notes and notes ~= '' then
table.insert(html, string.format(
'<div style="align-self: flex-start; margin: 10px 0 10px 20px; font-size: 0.8rem;">'..
'<div><span style="font-size:1.15rem;">%s</span></div>' ..
'<div class="mw-collapsible mw-collapsed" style="margin-top: 5px;">' ..
'<div>%s</div>' ..
'</div></div>',
frame:callParserFunction( '#invoke', 'Dictionary', 'translate', 'Notes' ),
frame:preprocess(notes)
))
end


        -- Apply unit conversion to the base value
local final_card = string.format(
        if type(base_value) == "number" then
'{{anchor|%s}}<div style="font-size: 0.9rem; line-height: 1.4; font-family: \'Retail Demo\', \'Open Sans\', \'PT Serif\', serif; color: #FFEFD7; display:flex; flex-direction:column; background: linear-gradient(90deg, rgba(52,52,52,1) 0%%, rgba(66,66,66,1) 14%%, rgba(77,77,77,1) 100%%); align-items: center; width: 100%%; max-width: 500px; border-radius: 13px 13px 4px 4px;">%s</div>',
            base_value = base_value * conv_factor
ability_name_localized,
        end
table.concat(html, '\n')
)
-- FIXED: Preprocess the entire output to render the anchor and other wikitext.
return frame:preprocess(final_card)
end


        local stat_value = base_value
-- We re-paste the remaining builder functions here so the module is complete in one block.
 
buildAltBoxHtml = function(prop)
        -- Scaling lookup
local frame = mw.getCurrentFrame()
        local scaling_data
local scaleHtml = ''
        if is_alt_fire then
if prop.Scale and prop.Scale.Type and prop.Scale.Value then
            if attr_key == "ClipSize" or attr_key == "ReloadTime" then
scaleHtml = '&nbsp;' .. buildMultiplierHtml(prop.Scale.Type, commonutils.round_to_sig_fig(prop.Scale.Value, 3), '35px')
                scaling_data = hero_data_module.get_hero_scaling_data(hero_data, attr_key)
end
            elseif (attr_key == "DPS" or attr_key == "SustainedDPS")
                and hero_data.Weapon and hero_data.Weapon.AltFire then
local icon_data = get_icon(prop.Type)
                -- Alt-fire DPS/SustainedDPS: use explicit key if present, otherwise compute from components
local iconHtml = frame:expandTemplate{ title = 'Icon/' .. (icon_data.color or 'Grey'), args = {
                local direct_scaling = hero_data_module.get_hero_scaling_data(hero_data, attr_key .. "AltFire")
string.format('[[File:%s|%s|link=%s]]', icon_data.img, icon_data.size or '18px', icon_data.link),
                if direct_scaling and next(direct_scaling) ~= nil then
frame:expandTemplate{ title = 'ValueAndUom', args = {
                    scaling_data = direct_scaling
"'''" .. prop.Value .. "'''",
                else
id = prop.Key,
                    local alt_stats = hero_data.Weapon.AltFire
frame:expandTemplate{ title = 'Lang', args = { key = prop.Key .. '_postfix' } },
                    local dps_type = attr_key == "DPS" and 'burst' or 'sustained'
uom_style = 'font-size: 10px; color: #9C9C9C'
                    local level_scale = compute_dps_scaling(hero_data, alt_stats, dps_type, "Level")
}}
                    local spirit_scale = compute_dps_scaling(hero_data, alt_stats, dps_type, "Spirit")
}}
                    level_scale = util_module.round_to_sig_fig(level_scale, 5)
                    spirit_scale = util_module.round_to_sig_fig(spirit_scale, 5)
return string.format(
                    scaling_data = {}
'<div style="display:flex; flex-direction:row; flex-grow: 1; flex-basis: 0; justify-content: left; background-color: #2A2A2A; font-size: 0.85em; margin: 3px; text-align: center; box-shadow: 0 0 10px #2A2A2A; border-radius: 1px; white-space: nowrap">' ..
                    if level_scale ~= 0 then scaling_data[level_scale] = "Level" end
' <span style="white-space: nowrap">%s&nbsp;<span style="font-size: 0.75rem; white-space: nowrap">%s%s</span></span>' ..
                    if spirit_scale ~= 0 then scaling_data[spirit_scale] = "Spirit" end
'</div>',
                    if next(scaling_data) == nil then scaling_data = nil end
iconHtml,
                end
frame:expandTemplate{ title = 'Lang', args = { key = prop.Key .. '_label' }},
            elseif hero_data.Weapon and hero_data.Weapon.AltFire
scaleHtml
                and hero_data.Weapon.AltFire[attr_key] ~= nil then
)
                scaling_data = hero_data_module.get_hero_scaling_data(hero_data, attr_key .. "AltFire")
end
            else
                scaling_data = hero_data_module.get_hero_scaling_data(hero_data, attr_key)
            end
        else
            scaling_data = hero_data_module.get_hero_scaling_data(hero_data, attr_key)
        end
 
        local scaling_strs = ""
        local spirit_scale = 0
        local level_scale  = 0
        local spirit_val = 0
        local level_val  = 0
        if scaling_data ~= nil then
            for scaling_val, scaling_type in pairs(scaling_data) do
                if scaling_type == "Spirit" then
                    spirit_val = scaling_val * conv_factor  -- apply unit conversion
                elseif scaling_type == "Level" then
                    level_val = scaling_val * conv_factor  -- apply unit conversion
                end
            end
 
            -- Output Spirit icon before Level icon
            local function append_scaling(val, stype)
                if val ~= 0 then
                    local scaling_str = hero_data_module.write_scalar_str(val, stype, true)
                    if scaling_str ~= "" then
                        scaling_strs = scaling_strs .. " " .. scaling_str
                    end
                end
            end
            append_scaling(spirit_val, "Spirit")
            append_scaling(level_val, "Level")
 
            if type(stat_value) == "number" then
                stat_value = stat_value + (spirit_power * spirit_val)
                stat_value = stat_value + (power_increases * level_val)
            end
 
            spirit_scale = spirit_val
            level_scale  = level_val
        end
 
        if attr_key == "TechPower" and spirit_scale == 0 then
            spirit_scale = 1.0
            if type(stat_value) == "number" then
                stat_value = stat_value + (spirit_power * spirit_scale)
            end
        end
 
        local innate_spirit_scale =
            (hero_data["LevelScaling"] and hero_data["LevelScaling"]["TechPower"]) or 0
 
        if not display_scaling_icons then scaling_strs = "" end
 
        if type(stat_value) == "boolean" then
            stat_value = tostring(stat_value)
        else
            stat_value = util_module.round_to_sig_fig(stat_value, 5)
        end
 
        local cell_inner = string.format(
            '<span class="stat-num">%s</span><span class="stat-scaling">%s</span>',
            stat_value,
            scaling_strs
        )
 
        local weapon_table = hero_data.Weapon
        if is_alt_fire and weapon_table and weapon_table.AltFire then
            weapon_table = weapon_table.AltFire
        end
        local hit_once = "false"
        if (attr_key == "DPS" or attr_key == "SustainedDPS")
            and weapon_table
            and weapon_table.HitOnceAcrossAllBullets
        then
            hit_once = "true"
        end
 
        local data_attrs = string.format(
            'data-stat-name="%s" data-base="%s" data-spirit-scale="%s" data-level-scale="%s" data-innate-spirit-scale="%s" data-sort-value="%s" data-hit-once="%s"',
            attr_key,
            tostring(type(base_value) == "number" and util_module.round_to_sig_fig(base_value, 3) or base_value),
            tonumber(spirit_scale) or 0,
            (attr_key == "TechPower") and "0" or (tonumber(level_scale) or 0),
            innate_spirit_scale or 0,
            stat_value,
            hit_once
        )
 
        return string.format('<td style="white-space: nowrap;" %s>%s</td>', data_attrs, cell_inner)
    end
 
    -- Generate a hero's primary stat row
    local function generatePrimaryRow(hero_data, hero_key, has_alt)
        local row_str = ""
        local hero_name_local = localize(hero_key, hero_key)
        local hero_name_en = hero_data["Name"]
        local template_args = {[1] = hero_name_en, l1 = hero_name_local}
        local hero_icon = mw.getCurrentFrame():expandTemplate{ title = "Template:HeroIcon", args = template_args }
        local hero_cell_content = hero_icon
        if has_alt then
            hero_cell_content = '[[#alt-fire-' .. hero_key .. '|+]] ' .. hero_cell_content
        end
        local sort_name = (hero_data["Name"] or hero_key):gsub("^The ", "")
        row_str = row_str .. '<td style="position: sticky; left: 0; z-index: 10; background-color: var(--background-color-base-2); isolation: isolate; overflow: hidden; min-width: 150px;" data-sort-value="' .. sort_name .. '">' .. hero_cell_content .. '</td>'
        for _, category in ipairs(attribute_orders["category_order"]) do
            if stats_to_include[category] ~= nil then
                for _, attr_key in ipairs(stats_to_include[category]) do
                    row_str = row_str .. buildStatCell(hero_data, hero_key, attr_key, false, category)
                end
            end
        end
        return "<tr>" .. row_str .. "</tr>"
    end
 
    -- Generate an expandable alt-fire sub-row (weapon stats only)
    local function generateAltFireSubRow(hero_data, hero_key)
        local row_str = ""
        local hero_name_local = localize(hero_key, hero_key)
        local hero_name_en = hero_data["Name"]
        local template_args = {[1] = hero_name_en, l1 = hero_name_local}
        local hero_icon = mw.getCurrentFrame():expandTemplate{ title = "Template:HeroIcon", args = template_args }
        local hero_cell_content = hero_icon .. ' <small style="color:#aaa;">(Alt‑fire)</small>'
        local sort_name = (hero_data["Name"] or hero_key):gsub("^The ", "")
        row_str = row_str .. '<td style="position: sticky; left: 0; z-index: 9; background-color: #202122; isolation: isolate; overflow: hidden; min-width: 150px;" data-sort-value="' .. sort_name .. '">' .. hero_cell_content .. '</td>'
        for _, category in ipairs(attribute_orders["category_order"]) do
            if stats_to_include[category] ~= nil then
                for _, attr_key in ipairs(stats_to_include[category]) do
                    if category == "Weapon" then
                        row_str = row_str .. buildStatCell(hero_data, hero_key, attr_key, true, category)
                    else
                        row_str = row_str .. '<td></td>'
                    end
                end
            end
        end
        return '<tr class="alt-fire-sub" data-parent="' .. hero_key .. '">' .. row_str .. '</tr>'
    end
 
    -- Build all body rows
    for _, hero_entry in ipairs(sorted_heroes) do
        local hero_key  = hero_entry.key
        local hero_data = hero_entry.data
        local has_alt = hero_data.Weapon and hero_data.Weapon.AltFire and true or false
        body_str = body_str .. generatePrimaryRow(hero_data, hero_key, has_alt)
        if has_alt then
            body_str = body_str .. generateAltFireSubRow(hero_data, hero_key)
        end
    end
 
    -- Pre-pass: determine which stats have any scaling, and which have both types.
    -- Used to set column widths in the header.
    local stats_with_any_scaling  = {}
    local stats_with_both_scaling = {}
    for _, hero_entry in ipairs(sorted_heroes) do
        local hero_data = hero_entry.data
        for _, category in ipairs(attribute_orders["category_order"]) do
            if stats_to_include[category] ~= nil then
                for _, attr_key in ipairs(stats_to_include[category]) do
                    -- Primary scaling
                    local scaling_data = hero_data_module.get_hero_scaling_data(hero_data, attr_key)
                    if scaling_data ~= nil and next(scaling_data) ~= nil then
                        stats_with_any_scaling[attr_key] = true
                        local has_spirit, has_level = false, false
                        for _, scaling_type in pairs(scaling_data) do
                            if scaling_type == "Spirit" then has_spirit = true
                            elseif scaling_type == "Level" then has_level = true end
                        end
                        if has_spirit and has_level then stats_with_both_scaling[attr_key] = true end
                    end
 
                    -- Alt-fire scaling (only for stats present in the AltFire table)
                    if hero_data.Weapon
                        and hero_data.Weapon.AltFire
                        and hero_data.Weapon.AltFire[attr_key] ~= nil
                    then
                        if attr_key ~= "ClipSize" then
                            local alt_scaling = hero_data_module.get_hero_scaling_data(hero_data, attr_key .. "AltFire")
                            if alt_scaling and next(alt_scaling) ~= nil then
                                stats_with_any_scaling[attr_key] = true
                                local has_spirit_alt, has_level_alt = false, false
                                for _, stype in pairs(alt_scaling) do
                                    if stype == "Spirit" then has_spirit_alt = true
                                    elseif stype == "Level" then has_level_alt = true end
                                end
                                if has_spirit_alt and has_level_alt then stats_with_both_scaling[attr_key] = true end
                            else
                                if attr_key == "DPS" or attr_key == "SustainedDPS" then
                                    local alt_stats = hero_data.Weapon.AltFire
                                    local dps_type = attr_key == "DPS" and 'burst' or 'sustained'
                                    local lv = compute_dps_scaling(hero_data, alt_stats, dps_type, "Level")
                                    local sp = compute_dps_scaling(hero_data, alt_stats, dps_type, "Spirit")
                                    lv = util_module.round_to_sig_fig(lv, 5)
                                    sp = util_module.round_to_sig_fig(sp, 5)
                                    if lv ~= 0 or sp ~= 0 then
                                        stats_with_any_scaling[attr_key] = true
                                        if lv ~= 0 and sp ~= 0 then
                                            stats_with_both_scaling[attr_key] = true
                                        end
                                    end
                                end
                            end
                        end
                    end
                end
            end
        end
    end


    -- Build table header row
UPGRADE_COST_MAP = {1, 2, 5}
    local headers_str = '<th style="position: sticky; left: 0; top: -1px; z-index: 12; background-color: var(--background-color-base-5); isolation: isolate; min-width: 150px;">Hero</th>'
buildUpgradeBoxHtml = function(prop, index)
    local category_data = attribute_module.get_category_data()
local frame = mw.getCurrentFrame()
    local postfix_key_map = {
local description = lang.get_string(prop.DescKey)
        ["ReloadDelay"] = "StatDesc_ReloadTime_postfix",
        ["BulletsPerShot"] = "",
if (description == nil or description == '') then
        ["BulletsPerBurst"] = "",
local desc_parts = {}
        ["BurstInterShotInterval"] = "StatDesc_ReloadTime_postfix",
local seen = {}
        ["ReloadSingle"] = "",
for k, v in pairs(prop) do
        ["BonusAttackRange"] = "StatDesc_WeaponRangeFalloffMax_postfix",
if type(v) ~= 'table' then
        ["SustainedDPS"] = "DPS_postfix",
local formatted_value = utils.format_value_with_prepost(k, v, frame)
        ["RoundsPerSecondAtMaxSpin"] = "",
local attr_name = lang.get_string(k..'_label')
        ["CritDamageBonusPercent"]  = "StatDesc_CritDamageBonusScale_postfix",
local key = formatted_value .. '|' .. attr_name
["CritDamageReceivedPercent"] = "StatDesc_CritDamageReceivedScale_postfix",
if not seen[key] then
        ["BulletLifesteal"] = "BulletLifestealPercentHero_postfix",
table.insert(desc_parts, string.format('%s %s', formatted_value, attr_name))
        ["GroundDashSpeed"] = "DashSpeed_postfix"
seen[key] = true
    }
end
    for _, category in ipairs(attribute_orders["category_order"]) do
end
        local category_attrs = attributes_data[category]
end
        local category_rgb  = category_data[category]["rgb"]
description = table.concat(desc_parts, '<br>')
        if stats_to_include[category] ~= nil then
end
            for _, attr_key in ipairs(stats_to_include[category]) do
                local attr_data = category_attrs[attr_key]
               
                -- Fallback: if the stat is missing from this category, check all other categories
                if attr_data == nil then
                    for _, fallback_cat_data in pairs(attributes_data) do
                        if fallback_cat_data[attr_key] ~= nil then
                            attr_data = fallback_cat_data[attr_key]
                            break
                        end
                    end
                end


                local attr_localized, postfix
local d_len = mw.ustring.len(description)
                if attr_data ~= nil then
local fontsize = '1em'
                    attr_localized = lang_module.get_string(attr_data["label"])
if d_len > 60 and d_len < 71 then fontsize = '0.95rem'
                    if attr_localized == nil or attr_localized == "" then
elseif d_len > 70 and d_len < 91 then fontsize = '0.875rem'
                        attr_localized = util_module.add_space_before_cap(attr_key)
elseif d_len > 90 then fontsize = '0.8rem'
                    end
end
                    postfix = lang_module.get_string(attr_data["postfix"])
                    if postfix == nil or postfix == "" then postfix = ""
                    else postfix = " (" .. postfix .. ")" end
                    if attr_key == "BulletRadius" then postfix = " (cm)" end
                else
                    attr_localized = dictionary_module.translate(attr_key)
                    postfix = lang_module.get_string(postfix_key_map[attr_key])
                    if postfix == nil then return "attr_key " .. attr_key .. " must be added to postfix_key_map" end
                    if postfix ~= "" then postfix = " (" .. postfix .. ")" end
                end
                local th_style = 'position: sticky; top: -1px; z-index: 3; background-color: rgb(' .. category_rgb .. ');'
                if stats_with_both_scaling[attr_key] then
                    th_style = th_style .. ' min-width: 130px;'
                elseif stats_with_any_scaling[attr_key] then
                    th_style = th_style .. ' min-width: 75px;'
                end
                headers_str = headers_str .. '<th style="' .. th_style .. '">' .. attr_localized .. postfix .. "</th>"
            end
        end
    end
    headers_str = "<tr>" .. headers_str .. "</tr>"


    return string.format(
local scaleHtml = ''
        '<div id="hero-comparison-container" data-max-power="%s" data-max-spirit="%s">' ..
if prop.Scale and prop.Scale.Type and prop.Scale.Value then
        '<div style="overflow: auto; max-height: 70vh; width: 100%%;">' ..
scaleHtml = buildMultiplierHtml(prop.Scale.Type, commonutils.round_to_sig_fig(prop.Scale.Value, 3))
        '<table class="wikitable sortable" style="table-layout: auto; width: 100%%;" id="hero-comparison-table">%s%s</table>' ..
end
        '</div></div>',
        max_power, max_spirit, headers_str, body_str
return string.format(
    )
'<div style="display:flex; flex-direction:column; flex-grow: 1; flex-basis: 0; justify-content: flex-start; max-height: 140px; background-color: #555555; padding: 0 0 20px 0px; margin: 6px; text-align: center; box-shadow: 0 0 10px #2A2A2A; border-radius: 5px">' ..
' <div style="padding: 2px 0 0 2px; font-family:Retail Demo bold; font-size: clamp(0.70em, 2vw, 1em); background-color: #121212; border-radius: 5px 5px 0 0; ">%s</div>' ..
' <div style="padding: 10px 4px 4px 4px; font-size: clamp(0.70em, 2vw, %s);">%s</div>' ..
' <div>%s</div>' ..
'</div>',
frame:expandTemplate{ title = 'Ap', args = { UPGRADE_COST_MAP[index], icon_size = '15px' } },
fontsize,
frame:preprocess(description),
scaleHtml
)
end
end


return p
return p
Please note that all contributions to The Deadlock Wiki are considered to be released under the Creative Commons Attribution-NonCommercial-ShareAlike (see Deadlock:Copyrights for details). If you do not want your writing to be edited mercilessly and redistributed at will, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource. Do not submit copyrighted work without permission!
Cancel Editing help (opens in new window)
Preview page with this template

Page included on this page: