t8rt0t

atlas.lua

Jul 27th, 2024 (edited)
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 8.57 KB | None | 0 0
  1. local png = require("png") --https://github.com/9551-Dev/pngLua/blob/master/png.lua
  2. local expect = require("cc.expect").expect
  3.  
  4. local function packrgba(r,g,b,a)
  5.     return a*0x1000000 + b*0x10000 + g* 0x100 + r
  6. end
  7. local function unpackrgba(rgba)
  8.     local t = {}
  9.     for i=1,4 do
  10.         table.insert(t,rgba%256)
  11.         rgba = math.floor(rgba/256)
  12.     end
  13.     return unpack(t)
  14. end
  15. local function range(argNum,num,min,max)
  16.     assert(type(num) == "number" and num >= min and num <= max,string.format("Bad argument #%d (Expected number between %d and %d, got %s)",argNum,min,max,tostring(num)))
  17. end
  18. --a1 has to be a real alpha, but a2 can be nil (only accept if a1 is 255), or -1 (ignore alpha entirely)
  19. local function compareColors(r1,g1,b1,a1,r2,g2,b2,a2)
  20.     if not a2 then
  21.         if a1 == 255 then
  22.             return compareColors(r1,g1,b1,255,r2,g2,b2,255)
  23.         else
  24.             return math.huge
  25.         end
  26.     end
  27.     local R = (r2+r1)/2
  28.     local sum
  29.     if R >= 128 then
  30.         sum = 3*(r1-r2)^2+4*(g1-g2)^2+2*(b1-b2)^2
  31.     else
  32.         sum = 2*(r1-r2)^2+4*(g1-g2)^2+3*(b1-b2)^2
  33.     end
  34.     if a2 < 0 then return sum
  35.     else
  36.         return sum + 4*(a1-a2)^2
  37.     end
  38. end
  39.    
  40.  
  41. local function loadImg(baseDir,resourceKey,bVerbose)
  42.     if not resourceKey:find(":") then resourceKey = "minecraft:"..resourceKey end
  43.     local path = fs.find(fs.combine(baseDir,"*/assets",resourceKey:match("^[^:]+"),"textures",resourceKey:match(":(.+)")..".png"))[1]
  44.     print(path)
  45.     if not path or not fs.exists(path) then
  46.         if bVerbose then print("path does not exist,",path) end
  47.     return end
  48.     return png(path)
  49. end
  50.  
  51. local function getAverageColor(img)
  52.     local r,g,b,a,cRGB,cA = 0,0,0,0,0,0
  53.     for i=1,img.width do
  54.         for j=1,img.height do
  55.             local p = img:get_pixel(i,j)
  56.             if p then
  57.                 local pR,pG,pB,pA = p:unpack()
  58.                 a = a+pA
  59.                 cA = cA+1
  60.                 if pA ~= 0 then
  61.                     cRGB = cRGB + 1
  62.                     r,g,b = r+pR,g+pG,b+pB
  63.                 end
  64.             end
  65.         end
  66.     end
  67.     -- for k,v in pairs(img.pixels) do
  68.     --     for j,w in pairs(v) do
  69.     --         --if w.A == 0 then return nil end
  70.     --         a = a+w.A
  71.     --         cA = cA + 1
  72.     --         if w.A ~= 0 then
  73.     --             cRGB = cRGB + 1
  74.     --             r,g,b = r+w.R,g+w.G,b+w.B
  75.     --         end
  76.     --     end
  77.     -- end
  78.     return math.floor(255.99*r/cRGB),math.floor(255.99*g/cRGB),math.floor(255.99*b/cRGB),math.floor(255.99*a/cA)
  79. end
  80.  
  81. local function calculateColor(bVerbose,sBaseDir,...)
  82.     local r,g,b,a,cRGB,cA = 0,0,0,0,0,0
  83.     local args = {...}
  84.     for i=1,#args,2 do
  85.         local weight = args[i+1] or 1
  86.         local img = loadImg(sBaseDir,tostring(args[i]),bVerbose)
  87.         if not img then return end
  88.         local nR,nG,nB,nA = getAverageColor(img)
  89.         if not nR then return end
  90.         r,g,b,a = r+weight*nR,g+weight*nG,b+weight*nB,a+weight*nA
  91.         cRGB,cA = cRGB+weight,cA+weight
  92.     end
  93.     return math.floor(r/cRGB),math.floor(g/cRGB),math.floor(b/cRGB),math.floor(a/cA)
  94. end
  95.    
  96. --TODO: fix for the weird uv thing in `https://minecraft.fandom.com/wiki/Tutorials/Models#Examples:_Condensing_multiple_textures_into_one_file`
  97. local function loadModelBasic(sBaseDir,tTextures,tElements,bVerbose)
  98.     local tWeights = {}
  99.     for k,element in pairs(tElements) do
  100.         for _,face in pairs(element.faces) do
  101.             local texture = face.texture:sub(2) --remove the # at the start
  102.             if tTextures[texture] then
  103.                 tWeights[texture] = (tWeights[texture] or 0) + 1
  104.             else
  105.                 return nil --No defined texture means that its a generic template block
  106.             end
  107.         end
  108.     end
  109.     local packedWeights = {bVerbose,sBaseDir}
  110.     for texture,weight in pairs(tWeights) do
  111.         table.insert(packedWeights,tTextures[texture])
  112.         table.insert(packWeights,weight)
  113.     end
  114.     return calculateColor(unpack(packedWeights))
  115. end
  116.  
  117. local serializers = {
  118.     ["minecraft:block/cube_all"] = function(bVerbose,sBaseDir,tTextures) return calculateColor(bVerbose,sBaseDir,tTextures.all) end,
  119.     ["minecraft:block/cube"] = function(bVerbose,sBaseDir,tTextures,tElements)
  120.         if tElements then --deal with elements overrides
  121.             return loadModelBasic(sBaseDir,tTextures,tElements,bVerbose)
  122.         end
  123.         return calculateColor(bVerbose,sBaseDir,
  124.             tTextures.down,1,
  125.             tTextures.up,1,
  126.             tTextures.north,1,
  127.             tTextures.south,1,
  128.             tTextures.east,1,
  129.             tTextures.west,1
  130.         ) end,
  131.     ["minecraft:block/cube_bottom_top"] = function(bVerbose,sBaseDir,tTextures,tElements)
  132.         return calculateColor(bVerbose,sBaseDir,
  133.             tTextures.side,4,
  134.             tTextures.bottom,1,
  135.             tTextures.top,1
  136.         ) end,
  137.     ["minecraft:block/cube_column"] = function(bVerbose,sBaseDir,tTextures,tElements)
  138.         return calculateColor(bVerbose,sBaseDir,
  139.             tTextures["end"],2,
  140.             tTextures.side,4
  141.         ) end,
  142.     --specifically skipping cube_column_horizontal because its only for logs (?) and just causes problems
  143.     ["minecraft:template_glazed_terracotta"] = function(bVerbose,sBaseDir,tTextures) return calculateColor(bVerbose,sBaseDir,tTextures.pattern) end
  144. }
  145. for parent,func in pairs(serializers) do
  146.     if parent:match("^minecraft:") then
  147.         serializers[parent:sub(11)] = func --make a copy for implied `minecraft:`
  148.     end
  149. end
  150.  
  151. local function loadModelJson(baseDir,path,bVerbose)
  152.     if not fs.exists(path) then return end
  153.     local f = fs.open(path,"r")
  154.     local json = textutils.unserialiseJSON(f.readAll())
  155.     f.close()
  156.     if not json then return end
  157.     if json.parent and serializers[json.parent] then
  158.         return serializers[json.parent](bVerbose,baseDir,json.textures,json.elements)
  159.     end
  160. end
  161.  
  162. local atlas = {}
  163. function atlas.create(baseDir,bVerbose)
  164.     expect(1,baseDir,"string")
  165.     assert(fs.exists(baseDir),"Must provide a directory with resource files inside")
  166.     local blocks = fs.find(fs.combine(baseDir,"*/assets/*/blockstates/*.json"))
  167.     --local models = fs.find(fs.combine(baseDir,"*/assets/*/models/block/*.json")) --no recursive searching because that messes with namespace
  168.     if #blocks == 0 then error("Could not find blocks in the directory, make sure the blocks are defined in"..fs.combine(baseDir,"<any>/assets/<mod_id>/blockstates/<item_id>.json")) end
  169.     local atlasTable = {}
  170.     local epochCheck = os.epoch("UTC") + 6
  171.     for _,path in pairs(blocks) do
  172.         local modelPath = path:gsub("blockstates","models/block")
  173.         print(modelPath)
  174.         local r,g,b,a = loadModelJson(baseDir,modelPath,bVerbose)
  175.         if os.epoch("UTC") > epochCheck then os.queueEvent("nosleep");os.pullEvent() end
  176.         if r then
  177.             local modid,itemid = modelPath:match("assets/([%w_]+)/models/block/([%w_]+)%.json$")
  178.             if modid then atlasTable[modid..":"..itemid] = {r,g,b,a} end
  179.         end
  180.     end
  181.     setmetatable(atlasTable,atlas)
  182.     return atlasTable
  183. end
  184. function atlas.save(atlasTable,output)
  185.     expect(1,atlasTable,"table")
  186.     expect(2,output,"string")
  187.     assert(getmetatable(atlasTable) == atlas,"Can only save atlases")
  188.     local str = ""
  189.     for block,rgba in pairs(atlasTable) do
  190.         str = str .. block .. "|" .. string.format("%.8x",packrgba(unpack(rgba))) .. "\n"
  191.     end
  192.     str = str:gsub("\n$","")
  193.     local f = fs.open(output,"w+")
  194.     f.write(str)
  195.     f.close()
  196. end
  197.  
  198. function atlas.load(input)
  199.     expect(1,input,"string")
  200.     if not fs.exists(input) then return false,"path does not exist" end
  201.     local f = fs.open(input,"r")
  202.     local data = f.readAll()
  203.     f.close()
  204.     local atlasTable = {}
  205.     for modid,rgba in data:gmatch("([%w_:]+)|(%x+)") do
  206.         atlasTable[modid] = {unpackrgba(tonumber(rgba,16))}
  207.     end
  208.     setmetatable(atlasTable,atlas)
  209.     return atlasTable
  210. end
  211.  
  212. function atlas.getClosestBlock(atlasTable,r,g,b,a)
  213.     assert(getmetatable(atlasTable) == atlas,"Bad argument #1 (atlas expected, got "..type(atlasTable))
  214.     range(2,r,0,255);range(3,g,0,255);range(4,b,0,255);
  215.     expect(5,a,"number","nil")
  216.     local bestblock,bestscore = "minecraft:air",math.huge
  217.     for block,rgba in pairs(atlasTable) do
  218.        
  219.         local score = compareColors(rgba[1],rgba[2],rgba[3],rgba[4],r,g,b,a)
  220.         if score == 0 then return block
  221.         elseif score < bestscore then
  222.             bestscore,bestblock = score,block
  223.         end
  224.     end
  225.     return bestblock
  226. end
  227. return atlas
Advertisement
Add Comment
Please, Sign In to add comment