Модуль:Песочница/Pok: различия между версиями

Материал из Space Station 14 Вики
Нет описания правки
Нет описания правки
Строка 1: Строка 1:
local p = {}
local p = {}
local JsonPaths = require('Module:JsonPaths')


local BASE_USER = "IanComradeBot/"
local function trim(value)
 
     return mw.text.trim(value or "")
local function get_module_name(pagePath)
     return "Module:" .. BASE_USER .. pagePath .. "/data"
end
end


local function load_cached_data(moduleName)
local function deepEqual(t1, t2)
    local ok, loaded = pcall(mw.loadData, moduleName)
     if t1 == t2 then return true end
     if not ok or not loaded then
     if type(t1) ~= "table" or type(t2) ~= "table" then return false end
        return nil
    end
     return loaded
end


local function parse_indexed_part(part)
    local function isArray(t)
    local key, idx = string.match(part, "^(.-)%[(%d+)%]$")
        local count = 0
    if key then
        for k in pairs(t) do
        return key, tonumber(idx)
            if type(k) ~= "number" then return false end
    end
            count = count + 1
    local num = tonumber(part)
        end
    if num then
         return count == #t
         return nil, num
     end
     end
    return part, nil
end


local function get_by_path(tbl, path)
     if isArray(t1) and isArray(t2) then
     if not tbl or path == "" then return nil end
         if #t1 ~= #t2 then return false end
    local cur = tbl
        for i = 1, #t1 do
    for part in string.gmatch(path, "([^%.]+)") do
             if not deepEqual(t1[i], t2[i]) then
        local key, idx = parse_indexed_part(part)
                 return false
         if key and key ~= "" then
            if type(cur) ~= "table" then return nil end
            local nextCur = cur[key]
             if nextCur == nil then
                 nextCur = cur["!type:" .. key]
             end
             end
            cur = nextCur
         end
         end
         if idx then
         return true
            if type(cur) ~= "table" then return nil end
            cur = cur[idx]
        end
        if cur == nil then return nil end
    end
    return cur
end
 
local function format_value(v)
    local okJson, json = pcall(mw.text.jsonEncode, v)
    if okJson and json == "null" then
        return "null"
     end
     end


     if v == nil then return "" end
     for k, v in pairs(t1) do
 
        if t2[k] == nil or not deepEqual(v, t2[k]) then
    local t = type(v)
             return false
    if t == "string" or t == "number" or t == "boolean" then
        return tostring(v)
    elseif t == "table" then
        local ok, json2 = pcall(mw.text.jsonEncode, v)
        if ok and json2 then
             return json2
         end
         end
        return ""
    else
        return tostring(v)
     end
     end
end
local function to_nowiki(v)
    return "<nowiki>" .. v .. "</nowiki>"
end


local function is_array(tbl)
     for k, v in pairs(t2) do
    local max = 0
         if t1[k] == nil or not deepEqual(v, t1[k]) then
    local count = 0
     for k in pairs(tbl) do
         if type(k) ~= "number" then
             return false
             return false
        end
        if k > max then max = k end
        count = count + 1
    end
    return count > 0 and max == count
end
local function deep_copy(src)
    local dst = {}
    for k, v in pairs(src) do
        if type(v) == "table" then
            dst[k] = deep_copy(v)
        else
            dst[k] = v
         end
         end
     end
     end
    return dst
end


local function deep_merge(dst, src)
     return true
     for k, v in pairs(src) do
        if type(v) == "table" and type(dst[k]) == "table" then
            deep_merge(dst[k], v)
        elseif type(v) == "table" then
            dst[k] = deep_copy(v)
        else
            dst[k] = v
        end
    end
end
end


local function resolve_entry(data, id)
local function findFieldInsensitive(tbl, fieldName)
     if type(data) ~= "table" then
     if type(tbl) ~= "table" then
         return nil
         return nil
     end
     end


     if id and id ~= "" then
     for key, value in pairs(tbl) do
        local direct = data[id]
         if type(key) == "string" and mw.ustring.lower(key) == mw.ustring.lower(fieldName) then
        if direct ~= nil then
            return value
            return direct
        end
 
        local idsTable = data.id
         if type(idsTable) == "table" then
            local specific = idsTable[id]
            if type(specific) == "table" then
                local base = data["default"]
                if type(base) == "table" then
                    local merged = deep_copy(base)
                    deep_merge(merged, specific)
                    return merged
                end
                return deep_copy(specific)
            end
         end
         end
    end
    local base = data["default"]
    if type(base) == "table" then
        return deep_copy(base)
     end
     end
     return nil
     return nil
end
end


local function collect_id_keys(data)
local function shallowMerge(base, extra)
    if type(data) ~= "table" then
     local result = {}
        return {}
    end
 
    local idsTable = data.id
     local ids = {}


     if type(idsTable) == "table" then
     if type(base) == "table" then
         for k in pairs(idsTable) do
         for k, v in pairs(base) do
             ids[#ids + 1] = k
             result[k] = v
        end
        return ids
    end
 
    for k in pairs(data) do
        if k ~= "default" and k ~= "id" then
            ids[#ids + 1] = k
         end
         end
     end
     end
    return ids
end
local function contains_target(v, target)
    if type(v) == "table" then
        if is_array(v) then
            for _, item in ipairs(v) do
                if tostring(item) == target then
                    return true
                end
            end
            return false
        end


         for _, item in pairs(v) do
    if type(extra) == "table" then
             if tostring(item) == target then
         for k, v in pairs(extra) do
                return true
             result[k] = v
            end
         end
         end
        return false
     end
     end


     return tostring(v) == target
     return result
end
end


local function is_nonempty_value(v)
local function normalizeEntry(id, entry, defaultEntry)
     if v == nil then return false end
     local merged = shallowMerge(defaultEntry, entry)
    if type(v) == "table" then
     merged.id = id
        return next(v) ~= nil
     return merged
     end
     return true
end
end


local function find_matching_ids(idsTable, keyPath, searchValue)
local function collectEntries(spriteData)
     local target = tostring(searchValue)
     local result = {}
     local matches = {}
     local defaultEntry = spriteData.default


     for idKey, entry in pairs(idsTable) do
    local entries = spriteData.id or {}
     for id, entry in pairs(entries) do
         if type(entry) == "table" then
         if type(entry) == "table" then
             local v = get_by_path(entry, keyPath)
             table.insert(result, normalizeEntry(id, entry, defaultEntry))
            if v ~= nil and contains_target(v, target) then
                matches[#matches + 1] = idKey
            end
         end
         end
     end
     end


     return matches
     return result
end
end


local function preprocess_or_return(frame, text)
local function getSpritePath(entry)
     if type(frame.preprocess) == "function" then
     if type(entry) ~= "table" then
        return frame:preprocess(text)
         return nil
    end
    return text
end
 
local function get_field_loose(entry, fieldId)
    local value = entry[fieldId]
    if value ~= nil then return value end
    if fieldId == "" then return nil end
 
    local first = string.sub(fieldId, 1, 1)
    local tail = string.sub(fieldId, 2)
    value = entry[string.lower(first) .. tail]
    if value ~= nil then return value end
 
    return entry[string.upper(first) .. tail]
end
 
local function apply_pattern(s, pattern, repl)
    if not pattern or pattern == "" or not s then
         return s
    end
 
    local text = tostring(s)
    local replacement
    if repl and repl ~= "" then
        replacement = tostring(repl)
        replacement = replacement:gsub("\\(%d)", "%%%1")
    else
        replacement = "%1"
     end
     end


    local patt = pattern
     if entry.sprite then
     if not patt:find("%^") and not patt:find("%$") then
         return entry.sprite
         patt = "^" .. patt .. "$"
     end
     end


     return (text:gsub(patt, replacement))
     local iconField = findFieldInsensitive(entry, "Icon")
end
     local spriteField = findFieldInsensitive(entry, "Sprite")
 
local function flatten_parts(entry)
    if type(entry) ~= "table" then return {} end
 
     local parts = {}
    local function append_table_json(key, value)
        local ok, json = pcall(mw.text.jsonEncode, value)
        if ok and json then
            parts[#parts + 1] = key .. "=" .. to_nowiki(json)
        end
    end


     local function walk(tbl, prefix)
     if iconField and iconField.sprite then
         local keys = {}
         return iconField.sprite
         for k in pairs(tbl) do keys[#keys + 1] = k end
    elseif spriteField and spriteField.sprite then
        table.sort(keys, function(a, b) return tostring(a) < tostring(b) end)
         return spriteField.sprite
         for _, k in ipairs(keys) do
    elseif spriteField and spriteField.layers then
             local v = tbl[k]
         for _, layer in pairs(spriteField.layers) do
            local kStr = tostring(k)
             if layer.sprite then
            local key = (prefix == "" and kStr or prefix .. "." .. kStr)
                 return layer.sprite
            if type(v) == "table" then
                 if next(v) == nil then
                else
                    append_table_json(key, v)
                    if is_array(v) then
                        local first = v[1]
                        if type(first) == "table" then
                            walk(first, key)
                        end
                    else
                        walk(v, key)
                    end
                end
            else
                parts[#parts + 1] = key .. "=" .. tostring(v)
             end
             end
         end
         end
     end
     end


    walk(entry, "")
     return nil
 
     return parts
end
 
local function flatten_entry(entry)
    local parts = flatten_parts(entry)
    if #parts == 0 then
        return ""
    end
    return table.concat(parts, "|")
end
 
function p.findInGenerator(frame)
    local args = frame.args or {}
    local searchId = args[1] or ""
    local kind = (args[2] or ""):lower()
    local fieldId = args[3] or ""
 
    if searchId == "" or fieldId == "" then
        return ""
    end
    if kind ~= "prototype" and kind ~= "component" then
        return ""
    end
 
    local storeName = (kind == "prototype") and "prototype_store.json" or "component_store.json"
    local moduleName = get_module_name(storeName)
    local data = load_cached_data(moduleName)
    if not data then
        return ""
    end
 
    local entry = data[searchId]
    if type(entry) ~= "table" then
        return ""
    end
 
    local value = get_field_loose(entry, fieldId)
    if value == nil then
        return ""
    end
 
    local out = {}
    local t = type(value)
    if t == "table" then
        for _, v in ipairs(value) do
            out[#out + 1] = v
        end
    else
        out[1] = value
    end
 
    return mw.text.jsonEncode(out)
end
 
function p.flattenField(frame)
    local args = frame.args or {}
    local id = args[1] or ""
    local pagePath = args[2] or ""
    if id == "" or pagePath == "" then return "" end
 
    local moduleName = get_module_name(pagePath)
    local data = load_cached_data(moduleName)
    if not data then return "" end
 
    local entry = resolve_entry(data, id) or {}
    return flatten_entry(entry)
end
 
function p.get(frame)
    local args = frame.args or {}
    local id = args[1] or ""
    local pagePath = args[2] or ""
    local keyPath = args[3] or ""
 
    if pagePath == "" then return "" end
 
    local moduleName = get_module_name(pagePath)
    local data = load_cached_data(moduleName)
    if not data then return "" end
 
    local entry = resolve_entry(data, id)
    if entry == nil then return "" end
 
    if keyPath == "" then
        return format_value(entry)
    end
 
    local value = get_by_path(entry, keyPath)
    return format_value(value)
end
end


function p.getId(frame)
local function getSpriteStates(entry)
     local args = frame.args or {}
     local result = {}
    local searchValue = args[1] or ""
    local pagePath = args[2] or ""
    local keyPath = args[3] or ""
    local searchType = (args.searchType or ""):lower()


     if searchValue == "" or pagePath == "" or keyPath == "" then
     local function addState(state, sprite)
        return ""
        table.insert(result, { state = state, sprite = sprite })
     end
     end
    if searchType == "" then
        searchType = "value"
    end
    local moduleName = get_module_name(pagePath)
    local data = load_cached_data(moduleName)
    if not data then return "[]" end


     local ids = collect_id_keys(data)
     local spritePath = getSpritePath(entry)
     if #ids == 0 then
     local iconBlock = findFieldInsensitive(entry, "Icon")
        return ""
     local spriteBlock = findFieldInsensitive(entry, "Sprite")
     end


    local matches
     if entry.state then
     if searchType == "key" then
         addState(entry.state, entry.sprite or spritePath)
         local target = tostring(searchValue)
    elseif iconBlock and iconBlock.state then
        matches = {}
        addState(iconBlock.state, iconBlock.sprite or spritePath)
        for _, idKey in ipairs(ids) do
            local entry = resolve_entry(data, idKey)
            if type(entry) == "table" then
                local v = get_by_path(entry, keyPath)
                if type(v) == "table" and v[target] ~= nil then
                    matches[#matches + 1] = idKey
                end
            end
        end
     else
     else
         local target = tostring(searchValue)
         if spriteBlock and spriteBlock.layers then
        matches = {}
            for _, layer in ipairs(spriteBlock.layers) do
        for _, idKey in ipairs(ids) do
                if layer.visible ~= false then
            local entry = resolve_entry(data, idKey)
                    local stateName = layer.state or (iconBlock and iconBlock.state) or "icon"
            if type(entry) == "table" then
                    local s = layer.sprite or (iconBlock and iconBlock.sprite) or spritePath
                local v = get_by_path(entry, keyPath)
                    addState(stateName, s)
                if v ~= nil and contains_target(v, target) then
                     break
                     matches[#matches + 1] = idKey
                 end
                 end
             end
             end
        elseif spriteBlock and spriteBlock.state then
            addState(spriteBlock.state, spriteBlock.sprite or spritePath)
         end
         end
     end
     end


     if #matches == 0 then
     if spriteBlock and spriteBlock.layers then
         return ""
         for _, layer in ipairs(spriteBlock.layers) do
    end
            local alreadyAdded = false
 
            for _, r in ipairs(result) do
    local ok, json = pcall(mw.text.jsonEncode, matches)
                local layerState = layer.state or "icon"
    if ok and json then
                if r.state == layerState then
        return json
                    alreadyAdded = true
    end
                    break
 
                end
    return ""
            end
end
 
function p.getTplId(frame)
    local args = frame.args or {}
    local searchValue = args[1] or ""
    local pagePath = args[2] or ""
    local keyPath = args[3] or ""
    local tplPath = mw.text.unstripNoWiki(args[4] or "")
    local searchType = (args.searchType or ""):lower()
 
    if searchType == "" then
        searchType = "value"
    end
    if searchType == "path" then
        searchValue = ""
        pagePath = args[1] or ""
        keyPath = args[2] or ""
        tplPath = mw.text.unstripNoWiki(args[3] or "")
    end
    if pagePath == "" or keyPath == "" or tplPath == "" then
        return ""
    end
    if searchType ~= "path" and searchValue == "" then
        return ""
    end
 
    local moduleName = get_module_name(pagePath)
    local data = load_cached_data(moduleName)
    if not data then return "" end


    local ids = collect_id_keys(data)
            if not alreadyAdded and layer.visible ~= false then
    if #ids == 0 then
                local stateName = layer.state or "icon"
        return ""
                local s = layer.sprite or (iconBlock and iconBlock.sprite) or spritePath
    end


    local matches
                 if s then
    if searchType == "path" then
                     addState(stateName, s)
        matches = {}
        for _, idKey in ipairs(ids) do
            local entry = resolve_entry(data, idKey)
            if type(entry) == "table" then
                local v = get_by_path(entry, keyPath)
                if is_nonempty_value(v) then
                    matches[#matches + 1] = idKey
                end
            end
        end
    elseif searchType == "key" then
        local target = tostring(searchValue)
        matches = {}
        for _, idKey in ipairs(ids) do
            local entry = resolve_entry(data, idKey)
            if type(entry) == "table" then
                local v = get_by_path(entry, keyPath)
                 if type(v) == "table" and v[target] ~= nil then
                     matches[#matches + 1] = idKey
                end
            end
        end
    else
        local target = tostring(searchValue)
        matches = {}
        for _, idKey in ipairs(ids) do
            local entry = resolve_entry(data, idKey)
            if type(entry) == "table" then
                local v = get_by_path(entry, keyPath)
                if v ~= nil and contains_target(v, target) then
                    matches[#matches + 1] = idKey
                 end
                 end
             end
             end
Строка 520: Строка 174:
     end
     end


     if #matches == 0 then
     if #result == 0 and ((iconBlock and (iconBlock.sprite or iconBlock.state)) or spritePath or entry.sprite) then
         return ""
         local s = (iconBlock and iconBlock.sprite) or entry.sprite or spritePath
    end
         addState(entry.state or "icon", s)
 
    local out = {}
    for _, idKey in ipairs(matches) do
         local tpl = p.getTpl({ args = { idKey, pagePath, tplPath }, data = data })
        if tpl ~= "" then
            out[#out + 1] = tpl
        end
    end
 
    if #out == 0 then
        return ""
     end
     end


    local result = table.concat(out, " ")
     return (#result > 0) and result or nil
     return preprocess_or_return(frame, result)
end
end


function p.getTpl(frame)
local function getBaseUrl(project)
    local args = frame.args or {}
     if project == "Goob" then
    local id = args[1] or ""
         return "https://github.com/space-syndicate/Goob-Station/blob/master/Resources/Textures/"
    local pagePath = args[2] or ""
    local tplPath = mw.text.unstripNoWiki(args[3] or "")
 
     if id == "" or pagePath == "" or tplPath == "" then
         return ""
    end
 
    local moduleName = get_module_name(pagePath)
    local data = frame.data
    if not data then
        data = load_cached_data(moduleName)
    end
    if not data then
        return ""
    end
 
    local entry = resolve_entry(data, id)
    local extra = flatten_entry(entry)
    local tplStr = "{{" .. tostring(tplPath) .. "|id=" .. tostring(id)
    if extra ~= "" then
        tplStr = tplStr .. "|" .. extra
     end
     end
    tplStr = tplStr .. "}}"


     return preprocess_or_return(frame, tplStr)
     return "https://github.com/space-syndicate/space-station-14/blob/master/Resources/Textures/"
end
end


function p.getTplGenerator(frame)
local function generateRepeatTemplate(data)
     local args = frame.args or {}
     local spriteGroups = {}
    local searchId = args[1] or ""
    local kind = (args[2] or ""):lower()
    local generatorId = args[3] or ""
    local tplPath = mw.text.unstripNoWiki(args[4] or "")


     if searchId == "" or generatorId == "" or tplPath == "" then
     for _, entry in pairs(data) do
         return ""
        local found = false
    end
         for _, group in pairs(spriteGroups) do
    if kind ~= "prototype" and kind ~= "component" then
            if deepEqual(findFieldInsensitive(entry, "Sprite"), findFieldInsensitive(group[1], "Sprite")) and
        return ""
              deepEqual(entry.EntityStorageVisuals, group[1].EntityStorageVisuals) and
    end
              deepEqual(findFieldInsensitive(entry, "Icon"), findFieldInsensitive(group[1], "Icon")) and
 
              deepEqual(entry.sprite, group[1].sprite) and
    local dir = (kind == "prototype") and "prototype/" or "component/"
              deepEqual(entry.state, group[1].state) then
    local pagePath = dir .. generatorId .. ".json"
                table.insert(group, entry)
 
                found = true
    local idsJson = p.findInGenerator({ args = { searchId, kind, generatorId } })
                break
    local ok, ids = pcall(mw.text.jsonDecode, idsJson or "")
            end
    if not ok or type(ids) ~= "table" or #ids == 0 then
         end
        return ""
    end
 
    local moduleName = get_module_name(pagePath)
    local data = load_cached_data(moduleName)
    if not data then
         return ""
    end


    local out = {}
        if not found then
    for _, id in ipairs(ids) do
            table.insert(spriteGroups, { entry })
        local tpl = p.getTpl({ args = { id, pagePath, tplPath }, data = data })
        if tpl ~= "" then
            out[#out + 1] = tpl
         end
         end
     end
     end


     local result = table.concat(out, " ")
     local result = {}
    return preprocess_or_return(frame, result)
     for _, group in pairs(spriteGroups) do
end
         if #group > 1 then
 
            local idLinks = {}
function p.flattenParams(entry)
            for _, entry in pairs(group) do
    return flatten_parts(entry)
                table.insert(idLinks, "[[:Файл:" .. entry.id .. ".png]]")
end
            end
 
            table.insert(result, mw.getCurrentFrame():preprocess(
function p.getGenerator(frame)
                "{{Entity Sprite/Repeat|" .. table.concat(idLinks, " ") .. "|" .. group[1].id .. "}}"
    local args = frame.args or {}
            ))
     local searchId = args[1] or ""
    local kind = (args[2] or ""):lower()
    local generatorId = args[3] or ""
 
    if searchId == "" or generatorId == "" then
         return ""
    end
    if kind ~= "prototype" and kind ~= "component" then
        return ""
    end
 
    local idsJson = p.findInGenerator({ args = { searchId, kind, generatorId } })
    local ok, ids = pcall(mw.text.jsonDecode, idsJson or "")
    if not ok or type(ids) ~= "table" or #ids == 0 then
        return ""
    end
 
    local okOut, outJson = pcall(mw.text.jsonEncode, ids)
    if okOut and outJson then
        return outJson
    end
 
    return ""
end
 
function p.hasComp(frame)
    local args = frame.args or {}
    local entityId = args[1] or ""
    local compName = args[2] or ""
 
    if entityId == "" or compName == "" then
        return "false"
    end
 
    local moduleName = get_module_name("component.json")
    local data = load_cached_data(moduleName)
    if not data then
        return "false"
    end
 
    if type(data) ~= "table" then
        return "false"
    end
 
    local entry = data[entityId]
    if type(entry) ~= "table" then
        return "false"
    end
 
    local target = tostring(compName)
    for _, v in ipairs(entry) do
        if tostring(v) == target then
            return "true"
         end
         end
     end
     end


     return "false"
     return table.concat(result, "\n")
end
end


function p.GeneratorId(frame)
local function generateTemplate(entry, param, project)
    local args = frame.args or {}
     local spritePath = getSpritePath(entry)
    local pagePath = args[1] or ""
     if not entry.id or not spritePath then
    local replace = mw.text.unstripNoWiki(args.replace or "")
         return nil
    local pattern = mw.text.unstripNoWiki(args.pattern or "(.*)")
 
    if pagePath == "" then
        return ""
    end
 
    local moduleName = get_module_name(pagePath)
     local data = load_cached_data(moduleName)
     if not data then
        return ""
    end
 
    local idsTable = data.id
    if type(idsTable) ~= "table" then
         return ""
    end
 
    local ids = {}
    for k in pairs(idsTable) do
        ids[#ids + 1] = k
     end
     end


     table.sort(ids)
     if param == "image" then
 
        local states = getSpriteStates(entry)
    if replace ~= "" then
        local stateStr = ""
        local out = {}
        if states then
        for _, id in ipairs(ids) do
            local baseUrl = getBaseUrl(project)
            local text = apply_pattern(id, pattern, replace)
            local links = {}
            if text ~= "" then
            for _, item in ipairs(states) do
                 out[#out + 1] = text
                local path = item.sprite or spritePath
                local stateName = item.state
                local url = baseUrl .. path .. "/" .. stateName .. ".png"
                 table.insert(links, "[" .. url .. " " .. stateName .. "]")
             end
             end
            stateStr = table.concat(links, ", ")
         end
         end
        if #out == 0 then
            return ""
        end
        return preprocess_or_return(frame, table.concat(out, "\n"))
    end


    local ok, json = pcall(mw.text.jsonEncode, ids)
        return mw.getCurrentFrame():preprocess(
    if ok and json then
            "{{Entity Sprite/Image|" .. entry.id ..
         return json
            "|" .. getBaseUrl(project) .. spritePath ..
            "|" .. stateStr .. "}}"
         )
     end
     end


     return ""
     return nil
end
end


function p.GeneratorTplId(frame)
function p.main(frame)
     local args = frame.args or {}
     local action = frame.args[1]
    local pagePath = args[1] or ""
     local mode = frame.args[2]
     local tplPath = args[2] or ""


     if pagePath == "" or tplPath == "" then
     local dataPage = JsonPaths.get("prototype/sprite.json")
        return ""
     local spriteData = mw.loadData(dataPage)
     end


     local moduleName = get_module_name(pagePath)
     if not spriteData or type(spriteData) ~= "table" then
    local data = load_cached_data(moduleName)
         return "Ошибка: Невозможно загрузить данные из JSON (" .. dataPage .. ")."
    if not data then
         return ""
     end
     end


     local idsTable = data.id
     local project = JsonPaths.project()
    if type(idsTable) ~= "table" then
        return ""
    end


     local out = {}
     local entries = collectEntries(spriteData)


     for idKey in pairs(idsTable) do
     if action == "repeat" then
        local tpl = p.getTpl({ args = { idKey, pagePath, tplPath }, data = data })
        return generateRepeatTemplate(entries)
        if tpl ~= "" then
    elseif action == "image" then
             out[#out + 1] = tpl
        local result = {}
        for _, entry in pairs(entries) do
            local template = generateTemplate(entry, action, project)
            if template then
                table.insert(result, template)
             end
         end
         end
        return table.concat(result, "\n")
    else
        return nil
     end
     end
    table.sort(out)
    local result = table.concat(out, " ")
    return preprocess_or_return(frame, result)
end
end


return p
return p

Версия от 21:35, 21 марта 2026

Для документации этого модуля может быть создана страница Модуль:Песочница/Pok/doc

local p = {}
local JsonPaths = require('Module:JsonPaths')

local function trim(value)
    return mw.text.trim(value or "")
end

local function deepEqual(t1, t2)
    if t1 == t2 then return true end
    if type(t1) ~= "table" or type(t2) ~= "table" then return false end

    local function isArray(t)
        local count = 0
        for k in pairs(t) do
            if type(k) ~= "number" then return false end
            count = count + 1
        end
        return count == #t
    end

    if isArray(t1) and isArray(t2) then
        if #t1 ~= #t2 then return false end
        for i = 1, #t1 do
            if not deepEqual(t1[i], t2[i]) then
                return false
            end
        end
        return true
    end

    for k, v in pairs(t1) do
        if t2[k] == nil or not deepEqual(v, t2[k]) then
            return false
        end
    end

    for k, v in pairs(t2) do
        if t1[k] == nil or not deepEqual(v, t1[k]) then
            return false
        end
    end

    return true
end

local function findFieldInsensitive(tbl, fieldName)
    if type(tbl) ~= "table" then
        return nil
    end

    for key, value in pairs(tbl) do
        if type(key) == "string" and mw.ustring.lower(key) == mw.ustring.lower(fieldName) then
            return value
        end
    end
    return nil
end

local function shallowMerge(base, extra)
    local result = {}

    if type(base) == "table" then
        for k, v in pairs(base) do
            result[k] = v
        end
    end

    if type(extra) == "table" then
        for k, v in pairs(extra) do
            result[k] = v
        end
    end

    return result
end

local function normalizeEntry(id, entry, defaultEntry)
    local merged = shallowMerge(defaultEntry, entry)
    merged.id = id
    return merged
end

local function collectEntries(spriteData)
    local result = {}
    local defaultEntry = spriteData.default

    local entries = spriteData.id or {}
    for id, entry in pairs(entries) do
        if type(entry) == "table" then
            table.insert(result, normalizeEntry(id, entry, defaultEntry))
        end
    end

    return result
end

local function getSpritePath(entry)
    if type(entry) ~= "table" then
        return nil
    end

    if entry.sprite then
        return entry.sprite
    end

    local iconField = findFieldInsensitive(entry, "Icon")
    local spriteField = findFieldInsensitive(entry, "Sprite")

    if iconField and iconField.sprite then
        return iconField.sprite
    elseif spriteField and spriteField.sprite then
        return spriteField.sprite
    elseif spriteField and spriteField.layers then
        for _, layer in pairs(spriteField.layers) do
            if layer.sprite then
                return layer.sprite
            end
        end
    end

    return nil
end

local function getSpriteStates(entry)
    local result = {}

    local function addState(state, sprite)
        table.insert(result, { state = state, sprite = sprite })
    end

    local spritePath = getSpritePath(entry)
    local iconBlock = findFieldInsensitive(entry, "Icon")
    local spriteBlock = findFieldInsensitive(entry, "Sprite")

    if entry.state then
        addState(entry.state, entry.sprite or spritePath)
    elseif iconBlock and iconBlock.state then
        addState(iconBlock.state, iconBlock.sprite or spritePath)
    else
        if spriteBlock and spriteBlock.layers then
            for _, layer in ipairs(spriteBlock.layers) do
                if layer.visible ~= false then
                    local stateName = layer.state or (iconBlock and iconBlock.state) or "icon"
                    local s = layer.sprite or (iconBlock and iconBlock.sprite) or spritePath
                    addState(stateName, s)
                    break
                end
            end
        elseif spriteBlock and spriteBlock.state then
            addState(spriteBlock.state, spriteBlock.sprite or spritePath)
        end
    end

    if spriteBlock and spriteBlock.layers then
        for _, layer in ipairs(spriteBlock.layers) do
            local alreadyAdded = false
            for _, r in ipairs(result) do
                local layerState = layer.state or "icon"
                if r.state == layerState then
                    alreadyAdded = true
                    break
                end
            end

            if not alreadyAdded and layer.visible ~= false then
                local stateName = layer.state or "icon"
                local s = layer.sprite or (iconBlock and iconBlock.sprite) or spritePath

                if s then
                    addState(stateName, s)
                end
            end
        end
    end

    if #result == 0 and ((iconBlock and (iconBlock.sprite or iconBlock.state)) or spritePath or entry.sprite) then
        local s = (iconBlock and iconBlock.sprite) or entry.sprite or spritePath
        addState(entry.state or "icon", s)
    end

    return (#result > 0) and result or nil
end

local function getBaseUrl(project)
    if project == "Goob" then
        return "https://github.com/space-syndicate/Goob-Station/blob/master/Resources/Textures/"
    end

    return "https://github.com/space-syndicate/space-station-14/blob/master/Resources/Textures/"
end

local function generateRepeatTemplate(data)
    local spriteGroups = {}

    for _, entry in pairs(data) do
        local found = false
        for _, group in pairs(spriteGroups) do
            if deepEqual(findFieldInsensitive(entry, "Sprite"), findFieldInsensitive(group[1], "Sprite")) and
               deepEqual(entry.EntityStorageVisuals, group[1].EntityStorageVisuals) and
               deepEqual(findFieldInsensitive(entry, "Icon"), findFieldInsensitive(group[1], "Icon")) and
               deepEqual(entry.sprite, group[1].sprite) and
               deepEqual(entry.state, group[1].state) then
                table.insert(group, entry)
                found = true
                break
            end
        end

        if not found then
            table.insert(spriteGroups, { entry })
        end
    end

    local result = {}
    for _, group in pairs(spriteGroups) do
        if #group > 1 then
            local idLinks = {}
            for _, entry in pairs(group) do
                table.insert(idLinks, "[[:Файл:" .. entry.id .. ".png]]")
            end
            table.insert(result, mw.getCurrentFrame():preprocess(
                "{{Entity Sprite/Repeat|" .. table.concat(idLinks, " ") .. "|" .. group[1].id .. "}}"
            ))
        end
    end

    return table.concat(result, "\n")
end

local function generateTemplate(entry, param, project)
    local spritePath = getSpritePath(entry)
    if not entry.id or not spritePath then
        return nil
    end

    if param == "image" then
        local states = getSpriteStates(entry)
        local stateStr = ""
        if states then
            local baseUrl = getBaseUrl(project)
            local links = {}
            for _, item in ipairs(states) do
                local path = item.sprite or spritePath
                local stateName = item.state
                local url = baseUrl .. path .. "/" .. stateName .. ".png"
                table.insert(links, "[" .. url .. " " .. stateName .. "]")
            end
            stateStr = table.concat(links, ", ")
        end

        return mw.getCurrentFrame():preprocess(
            "{{Entity Sprite/Image|" .. entry.id ..
            "|" .. getBaseUrl(project) .. spritePath ..
            "|" .. stateStr .. "}}"
        )
    end

    return nil
end

function p.main(frame)
    local action = frame.args[1]
    local mode = frame.args[2]

    local dataPage = JsonPaths.get("prototype/sprite.json")
    local spriteData = mw.loadData(dataPage)

    if not spriteData or type(spriteData) ~= "table" then
        return "Ошибка: Невозможно загрузить данные из JSON (" .. dataPage .. ")."
    end

    local project = JsonPaths.project()

    local entries = collectEntries(spriteData)

    if action == "repeat" then
        return generateRepeatTemplate(entries)
    elseif action == "image" then
        local result = {}
        for _, entry in pairs(entries) do
            local template = generateTemplate(entry, action, project)
            if template then
                table.insert(result, template)
            end
        end
        return table.concat(result, "\n")
    else
        return nil
    end
end

return p