Files
rosetta/src/Formats/codecs/model/Minecraft/init.luau
T

588 lines
20 KiB
Luau

--!strict
-- codecs/model/Minecraft: what Minecraft's voxel formats share (model/schematic, model/mca). New code.
-- Block states ("minecraft:oak_stairs[facing=east,half=bottom]": parse / format / NBT compound form), the default
-- block colour table (codecs/model/Minecraft/Colors, hand-made) with fallbacks by family, the pre-1.13 numeric ids
-- (codecs/model/Minecraft/Legacy), packed index arrays (codecs/model/Minecraft/Packed), and the bridge between block
-- grids and Types.Voxels: voxels.blocks holds the exact states (u16 indices into a state palette), voxels.data /
-- palette their colours; writing a grid without blocks picks the block nearest in colour for each palette colour.
--
-- local Mc = require("@formats/codecs/model/Minecraft")
-- local name, props = Mc.parseState("minecraft:oak_log[axis=y]") -- "minecraft:oak_log", { { "axis", "y" } }
-- local rgba = Mc.color("minecraft:red_wool") -- { r, g, b, a } | nil for air
-- local v = Mc.voxels(sx, sy, sz, states, indices) -- a Types.Voxels with .blocks
-- local states, indices = Mc.blocksOf(v) -- back (or chosen by colour)
local Types = require("@formats/Types")
local Nbt = require("@formats/codecs/text/Nbt")
local Colors = require("@formats/codecs/model/Minecraft/Colors")
local Legacy = require("@formats/codecs/model/Minecraft/Legacy")
local Packed = require("@formats/codecs/model/Minecraft/Packed")
local Minecraft = {}
Minecraft.Packed = Packed
Minecraft.Legacy = Legacy
-- ------------------------------------------------------------------------------------------------ block states
-- parseState(s) -> name (namespace added when missing), props { { key, value } } in their order
function Minecraft.parseState(s: string): (string, { { string } })
local name, rest = string.match(s, "^%s*([^%[%s]*)%s*(.*)$")
local n = name or ""
if n ~= "" and not string.find(n, ":", 1, true) then
n = "minecraft:" .. n
end
local props = {}
local body = rest and string.match(rest :: string, "^%[(.*)%]%s*$")
if body then
for pair in string.gmatch(body, "[^,]+") do
local k, v = string.match(pair, "^%s*([^=%s]+)%s*=%s*(.-)%s*$")
if k then
table.insert(props, { k, v :: string })
end
end
end
return n, props
end
-- stateString(name, props?) -> "name[k=v,...]" (props { { k, v } } in order, or a map: keys sorted)
function Minecraft.stateString(name: string, props: { any }?): string
if not props or next(props) == nil then
return name
end
local parts = {}
if props[1] ~= nil then
for _, kv in props do
table.insert(parts, kv[1] .. "=" .. tostring(kv[2]))
end
else
for _, k in Types.keys(props) do
table.insert(parts, tostring(k) .. "=" .. tostring((props :: any)[k]))
end
end
return name .. "[" .. table.concat(parts, ",") .. "]"
end
-- stateFromNbt(compound) -> the state string of a palette entry { Name, Properties? } (litematic, chunk sections)
function Minecraft.stateFromNbt(c: any): string?
if type(c) ~= "table" or type(c.Name) ~= "string" then
return nil
end
local props = {}
if type(c.Properties) == "table" then
for _, k in Types.keys(c.Properties) do
local v = c.Properties[k]
table.insert(props, { k, if type(v) == "string" then v else tostring(Nbt.number(v) or v) })
end
end
return Minecraft.stateString(c.Name, props)
end
-- stateToNbt(state) -> { Name, Properties? } (a Types.object; Properties in the state's order)
function Minecraft.stateToNbt(s: string): { [string]: any }
local name, props = Minecraft.parseState(s)
local c = Types.object({ Name = name }, { "Name" })
if #props > 0 then
local p, keys = {}, {}
for _, kv in props do
p[kv[1]] = kv[2]
table.insert(keys, kv[1])
end
Types.set(c, "Properties", Types.object(p, keys))
end
return c
end
-- baseName(state) -> the name without namespace and properties ("minecraft:oak_log[axis=y]" -> "oak_log")
function Minecraft.baseName(s: string): string
local name = string.match(s, "^%s*([^%[%s]*)") or ""
return string.match(name, ":(.*)$") or name
end
local AIR = { air = true, cave_air = true, void_air = true, structure_void = true, light = true, barrier = true, moving_piston = true }
-- isAir(state) -> true for blocks that are not drawn (air, cave_air, void_air, structure_void, light, barrier)
function Minecraft.isAir(s: string): boolean
return AIR[Minecraft.baseName(s)] == true
end
-- ------------------------------------------------------------------------------------------------ colours
local function hex(h: string): { number }
local c = { tonumber(string.sub(h, 1, 2), 16) or 0, tonumber(string.sub(h, 3, 4), 16) or 0, tonumber(string.sub(h, 5, 6), 16) or 0, 255 }
if #h >= 8 then
c[4] = tonumber(string.sub(h, 7, 8), 16) or 255
end
return c
end
local function list(s: string): { { number } }
local out = {}
for h in string.gmatch(s, "%x+") do
table.insert(out, hex(h))
end
return out
end
local EXACT: { [string]: { number } } = {}
for name, h in string.gmatch(Colors.BLOCKS, "([%w_]+)=(%x+)") do
EXACT[name :: string] = hex(h :: string)
end
local WOOL, CONCRETE, TERRACOTTA = list(Colors.WOOL), list(Colors.CONCRETE), list(Colors.TERRACOTTA)
local PLANKS, BARK, LEAVES = list(Colors.PLANKS), list(Colors.BARK), list(Colors.LEAVES)
-- longest prefixes first, so light_blue wins over blue and dark_oak over oak
local function byLength(names: { string }): { { any } }
local out: { { any } } = {}
for i, n in names do
table.insert(out, { n, i })
end
table.sort(out, function(a: { any }, b: { any }): boolean
return #(a[1] :: string) > #(b[1] :: string)
end)
return out
end
local DYES, WOODS = byLength(Colors.DYES), byLength(Colors.WOODS)
local SUFFIXES = {
"_wall_hanging_sign", "_hanging_sign", "_wall_sign", "_sign", "_fence_gate", "_fence", "_pressure_plate", "_button",
"_trapdoor", "_door", "_stairs", "_slab", "_wall", "_pane", "_carpet", "_wall_banner", "_banner", "_bars",
}
local PREFIXES = { "waxed_", "potted_", "flowing_", "infested_", "lit_", "unlit_", "unpowered_", "powered_", "chipped_", "damaged_" }
local CORAL: { [string]: { number } } = { tube = hex("3157d0"), brain = hex("cf5b9f"), bubble = hex("a118a0"), fire = hex("a6252f"), horn = hex("d8c53e") }
local FALLBACK = hex("909090")
local function mix(c: { number }, w: { number }, t: number): { number }
return { math.floor(c[1] + (w[1] - c[1]) * t + 0.5), math.floor(c[2] + (w[2] - c[2]) * t + 0.5), math.floor(c[3] + (w[3] - c[3]) * t + 0.5), c[4] }
end
local resolve: (string, number) -> { number }?
local function family(n: string): { number }?
for _, d in DYES do
local pre = d[1] .. "_"
if string.sub(n, 1, #pre) == pre then
local rest = string.sub(n, #pre + 1)
local i = d[2]
if rest == "concrete" then
return CONCRETE[i]
elseif rest == "concrete_powder" then
return mix(CONCRETE[i], { 255, 255, 255, 255 }, 0.2)
elseif rest == "terracotta" then
return TERRACOTTA[i]
elseif string.find(rest, "glass", 1, true) then
local c = table.clone(WOOL[i])
c[4] = 0x80
return c
end
return WOOL[i]
end
end
local stripped = string.match(n, "^stripped_(.*)$")
for _, w in WOODS do
local pre = w[1] .. "_"
local m = stripped or n
if string.sub(m, 1, #pre) == pre then
local rest = string.sub(m, #pre + 1)
local i = w[2]
if stripped then
return PLANKS[i]
elseif rest == "log" or rest == "wood" or rest == "stem" or rest == "hyphae" then
return BARK[i]
elseif rest == "leaves" or rest == "sapling" or rest == "propagule" then
return LEAVES[i]
elseif rest == "block" and w[1] == "bamboo" then
return EXACT.bamboo_block
end
return PLANKS[i]
end
end
return nil
end
local function keywords(n: string): { number }?
if string.find(n, "copper", 1, true) then
return if string.find(n, "oxidized", 1, true) then EXACT.oxidized_copper
elseif string.find(n, "weathered", 1, true) then EXACT.weathered_copper
elseif string.find(n, "exposed", 1, true) then EXACT.exposed_copper
else EXACT.copper_block
elseif string.find(n, "coral", 1, true) then
if string.find(n, "dead", 1, true) then
return hex("857e79")
end
for k, c in CORAL do
if string.find(n, k, 1, true) then
return c
end
end
elseif string.find(n, "_ore$") then
return if string.find(n, "deepslate", 1, true) then EXACT.deepslate
elseif string.find(n, "nether", 1, true) then EXACT.netherrack
else EXACT.stone
end
for _, k in { "deepslate", "blackstone", "sandstone", "prismarine", "purpur", "quartz", "glass", "ice", "stone", "brick", "nether", "end", "mushroom", "grass", "candle", "head", "skull", "rail", "sign", "tulip", "orchid" } do
if string.find(n, k, 1, true) then
local alias = ({ glass = "glass", ice = "ice", stone = "stone", brick = "bricks", nether = "nether_bricks", ["end"] = "end_stone", mushroom = "mushroom_stem", grass = "short_grass", candle = "white_wool", head = "polished_andesite", skull = "bone_block", rail = "rail", sign = "oak_planks", tulip = "red_tulip", orchid = "blue_orchid", deepslate = "deepslate", blackstone = "blackstone", sandstone = "sandstone", prismarine = "prismarine", purpur = "purpur_block", quartz = "quartz_block" } :: any)[k]
return EXACT[alias]
end
end
return nil
end
resolve = function(n: string, depth: number): { number }?
if depth > 4 then
return nil
end
local c = EXACT[n]
if c then
return c
end
local renamed = Legacy.RENAMED[n]
if renamed then
return resolve(renamed, depth + 1)
end
for _, p in PREFIXES do
if string.sub(n, 1, #p) == p then
return resolve(string.sub(n, #p + 1), depth + 1)
end
end
c = family(n)
if c then
return c
end
for _, sfx in SUFFIXES do
if #n > #sfx and string.sub(n, -#sfx) == sfx then
local base = string.sub(n, 1, #n - #sfx)
for _, form in { base, base .. "s", base .. "_block", base .. "_planks" } do
local fc = EXACT[form] or family(form)
if fc then
return fc
end
end
return resolve(base, depth + 1)
end
end
return keywords(n)
end
local cache: { [string]: { number } | false } = {}
-- color(state) -> { r, g, b, a } (0..255) | nil for air-like blocks: the default colour table, families, keywords
function Minecraft.color(s: string): { number }?
local hit = cache[s]
if hit ~= nil then
return hit or nil
end
local name, props = Minecraft.parseState(s)
local n = string.match(name, ":(.*)$") or name
local res: { number }? = nil
if not AIR[n] then
-- pre-1.13 names whose data value picks the variant
local variants = Legacy.VARIANTS[n] or (if n == "double_wooden_slab" then Legacy.VARIANTS.planks else nil)
if variants then
local data = 0
for _, kv in props do
if kv[1] == "data" then
data = tonumber(kv[2]) or 0
end
end
local v = variants[data % (Legacy.MASK[n] or 16) + 1] or variants[1]
res = resolve(v, 0)
end
res = res or resolve(n, 0) or FALLBACK
end
cache[s] = res or false
return res
end
-- ------------------------------------------------------------------------------------------------ legacy ids
local REVERSE: { [string]: { number } }? = nil
local function reverse(): { [string]: { number } }
if REVERSE then
return REVERSE
end
local r: { [string]: { number } } = {}
local byName: { [string]: number } = {}
for i, n in Legacy.NAMES do
if n ~= "-" then
byName[n] = i - 1
end
end
for legacy, modern in Legacy.RENAMED do
r[modern] = { byName[legacy], 0 }
end
for legacy, variants in Legacy.VARIANTS do
for d, v in variants do
if r[v] == nil then
r[v] = { byName[legacy], d - 1 }
end
end
end
for n, id in byName do
if r[n] == nil then
r[n] = { id, 0 }
end
end
REVERSE = r
return r
end
-- legacyState(id, data) -> the state string for a pre-1.13 block (variant names where the data value picks one, the
-- rest of the data value kept as [data=N] so legacyId gives it back exactly)
function Minecraft.legacyState(id: number, data: number): string
local n = Legacy.NAMES[id + 1]
if n == nil or n == "-" then
return "minecraft:legacy_" .. id .. (if data ~= 0 then "[data=" .. data .. "]" else "")
end
local variants = Legacy.VARIANTS[n]
if variants then
local idx = data % (Legacy.MASK[n] or 16)
local v = variants[idx + 1]
if v then
return "minecraft:" .. v .. (if data ~= idx then "[data=" .. data .. "]" else "")
end
end
return "minecraft:" .. (Legacy.RENAMED[n] or n) .. (if data ~= 0 then "[data=" .. data .. "]" else "")
end
-- legacyId(state) -> id, data | nil: the inverse of legacyState (modern names that exist before 1.13 too; their
-- properties are not converted to data values)
function Minecraft.legacyId(s: string): (number?, number?)
local name, props = Minecraft.parseState(s)
local n = string.match(name, ":(.*)$") or name
local id: number?, data = nil, 0
local lid = string.match(n, "^legacy_(%d+)$")
if lid then
id = tonumber(lid)
else
local e = reverse()[n]
if e then
id, data = e[1], e[2]
end
end
if id == nil then
return nil, nil
end
for _, kv in props do
if kv[1] == "data" then
data = (tonumber(kv[2]) or data) % 16
end
end
return id, data
end
-- ------------------------------------------------------------------------------------------------ voxels
-- voxels(sx, sy, sz, states, indices, opts?) -> Types.Voxels: indices (u16 LE per cell in Voxels order: x fastest,
-- then y, then z) into states; data / palette from the block colours (air -> 0; up to 255 colours, more merge into
-- the nearest one)
function Minecraft.voxels(sx: number, sy: number, sz: number, states: { string }, indices: buffer): Types.Voxels
local v = Types.Voxels.new(sx, sy, sz)
local lut = buffer.create(#states)
local slots: { [string]: number } = {}
local used = 0
for i, s in states do
local c = Minecraft.color(s)
local slot = 0
if c then
local key = string.format("%d,%d,%d,%d", c[1], c[2], c[3], c[4])
slot = slots[key]
if not slot then
if used < 255 then
used += 1
slot = used
v.palette[slot] = { c[1], c[2], c[3], c[4] }
else
local best, bd = 1, math.huge
for k = 1, 255 do
local p = v.palette[k]
local d = (p[1] - c[1]) ^ 2 + (p[2] - c[2]) ^ 2 + (p[3] - c[3]) ^ 2 + (p[4] - c[4]) ^ 2
if d < bd then
best, bd = k, d
end
end
slot = best
end
slots[key] = slot
end
end
buffer.writeu8(lut, i - 1, slot)
end
local n = sx * sy * sz
local data, nstates = v.data, #states
for i = 0, n - 1 do
local s = buffer.readu16(indices, i * 2)
buffer.writeu8(data, i, if s < nstates then buffer.readu8(lut, s) else 0)
end
v.blocks = { palette = states, data = indices }
return v
end
-- the blocks a colour grid is written with: full blocks of distinct colours (and stained glass for translucent ones)
local CANDIDATES: { { any } }? = nil
local function candidates(): { { any } }
if CANDIDATES then
return CANDIDATES
end
local out = {}
for _, d in Colors.DYES do
for _, kind in { "wool", "concrete", "terracotta" } do
local s = "minecraft:" .. d .. "_" .. kind
table.insert(out, { s, Minecraft.color(s) })
end
end
for _, w in Colors.WOODS do
local s = "minecraft:" .. w .. "_planks"
table.insert(out, { s, Minecraft.color(s) })
end
for _, n in { "stone", "cobblestone", "bricks", "sand", "red_sand", "dirt", "grass_block", "gravel", "deepslate", "sandstone", "quartz_block", "obsidian", "netherrack", "end_stone", "prismarine", "dark_prismarine", "snow_block", "gold_block", "iron_block", "diamond_block", "emerald_block", "lapis_block", "redstone_block", "coal_block", "glowstone", "sponge", "melon", "pumpkin", "hay_block", "bone_block", "clay", "packed_ice", "nether_bricks", "purpur_block", "andesite", "diorite", "granite", "calcite", "tuff", "blackstone", "mud", "moss_block", "amethyst_block", "copper_block", "oxidized_copper" } do
local s = "minecraft:" .. n
table.insert(out, { s, Minecraft.color(s) })
end
CANDIDATES = out
return out
end
-- nearestBlock(rgba) -> the block state whose default colour is nearest (translucent colours -> stained glass)
function Minecraft.nearestBlock(c: { number }): string
local a = c[4] or 255
if a < 200 then
local best, bd = "minecraft:glass", math.huge
for i, d in Colors.DYES do
local w = WOOL[i]
local dist = (w[1] - c[1]) ^ 2 + (w[2] - c[2]) ^ 2 + (w[3] - c[3]) ^ 2
if dist < bd then
best, bd = "minecraft:" .. d .. "_stained_glass", dist
end
end
return best
end
local best, bd = "minecraft:stone", math.huge
for _, cand in candidates() do
local k = cand[2]
local dist = (k[1] - c[1]) ^ 2 + (k[2] - c[2]) ^ 2 + (k[3] - c[3]) ^ 2
if dist < bd then
best, bd = cand[1], dist
end
end
return best
end
-- blocksOf(voxels) -> states, indices (u16 LE per cell): voxels.blocks when present (checked), else a block per
-- palette colour (nearestBlock; cell 0 -> "minecraft:air" at index 0) | nil, message
function Minecraft.blocksOf(v: Types.Voxels): ({ string }?, any)
local n = v.size[1] * v.size[2] * v.size[3]
local b = v.blocks
if b then
if type(b.palette) ~= "table" or type(b.data) ~= "buffer" or buffer.len(b.data) < n * 2 then
return nil, "voxels.blocks must hold a palette and a u16 per cell"
end
if #b.palette == 0 or #b.palette > 65536 then
return nil, "voxels.blocks.palette must have 1 .. 65536 states"
end
return b.palette, b.data
end
local states = { "minecraft:air" }
local slotOf: { [number]: number } = { [0] = 0 }
local byState: { [string]: number } = { ["minecraft:air"] = 0 }
local out = buffer.create(n * 2)
local data = v.data
for i = 0, n - 1 do
local p = buffer.readu8(data, i)
local s = slotOf[p]
if s == nil then
local col = v.palette[p] or { 128, 128, 128, 255 }
local st = Minecraft.nearestBlock(col)
s = byState[st]
if s == nil then
table.insert(states, st)
s = #states - 1
byState[st] = s
end
slotOf[p] = s
end
buffer.writeu16(out, i * 2, s :: number)
end
return states, out
end
-- ------------------------------------------------------------------------------------------------ block entities
-- Block entity records in one shape, { pos = { x, y, z }, id, data } (Sponge v3's), from / to the flat
-- { x, y, z, id, ... } of MCEdit, Litematica and chunks, and Sponge v1 / v2's { Pos, Id, ... }.
local function int(v: any): number?
local n = Nbt.number(v)
if n == nil or n ~= n or n % 1 ~= 0 then
return nil
end
return n
end
local function ints(v: any): { number }?
if Nbt.isTag(v) and v.type == "intArray" then
return v.value
elseif type(v) == "table" and not Nbt.isTag(v) and (v :: any)[1] ~= nil then
local out: { number } = {}
for i, x in v :: { any } do
out[i] = Nbt.number(x) or 0
end
return out
end
return nil
end
Minecraft.int = int -- the integer value of an NBT number | nil
Minecraft.ints = ints -- the numbers of an intArray or a list | nil
local function rest(c: any, skip: { [string]: boolean }): { [string]: any }
local out, keys = {}, {}
for _, k in Types.keys(c) do
if not skip[k] then
out[k] = c[k]
table.insert(keys, k)
end
end
return Types.object(out, keys)
end
local FLAT_SKIP = { x = true, y = true, z = true, id = true }
local POS_SKIP = { Pos = true, Id = true }
-- blockEntity(c, style) -> the common shape of one record: style "flat" (MCEdit, Litematica), "pos" (Sponge v1 / v2),
-- "data" (Sponge v3)
function Minecraft.blockEntity(c: any, style: string): any
if type(c) ~= "table" or Nbt.isTag(c) then
return nil
end
if style == "flat" then
return { pos = { int(c.x) or 0, int(c.y) or 0, int(c.z) or 0 }, id = if type(c.id) == "string" then c.id else nil, data = rest(c, FLAT_SKIP) }
end
local p = ints(c.Pos) or { 0, 0, 0 }
local data = if style == "data" then (if type(c.Data) == "table" then c.Data else Types.object()) else rest(c, POS_SKIP)
return { pos = { p[1] or 0, p[2] or 0, p[3] or 0 }, id = if type(c.Id) == "string" then c.Id else nil, data = data }
end
-- flatBlockEntity(be, style) -> the record in a flavour's shape (the inverse of blockEntity)
function Minecraft.flatBlockEntity(be: any, style: string): any
local o = Types.object()
local data = if type(be.data) == "table" then be.data else Types.object()
if style == "flat" then
Types.set(o, "x", be.pos[1])
Types.set(o, "y", be.pos[2])
Types.set(o, "z", be.pos[3])
if be.id then
Types.set(o, "id", be.id)
end
for _, k in Types.keys(data) do
if not FLAT_SKIP[k] then
Types.set(o, k, data[k])
end
end
return o
end
Types.set(o, "Pos", Nbt.intArray({ be.pos[1], be.pos[2], be.pos[3] }))
if be.id then
Types.set(o, "Id", be.id)
end
if style == "data" then
Types.set(o, "Data", data)
else
for _, k in Types.keys(data) do
if not POS_SKIP[k] then
Types.set(o, k, data[k])
end
end
end
return o
end
return Minecraft