Files
rosetta/src/Formats/model/schematic/init.luau
T
4DBug fea56f4391 ws-voxel: model/schematic (.schem v1-3, .schematic, .litematic read + write), codecs/model/Minecraft (block states, default colours, legacy ids, packed arrays)
Types change (backward compatible): Types.Voxels gains optional blocks (VoxelBlocks: exact block states as
u16 indices into a state palette, block entities, entities) and colors (exact u32 RGBA per cell).
2026-10-31 14:37:43 -05:00

335 lines
14 KiB
Luau

--!strict
-- model/schematic: Minecraft schematics: MCEdit / WorldEdit .schematic (before 1.13), Sponge .schem (versions 1, 2, 3:
-- WorldEdit 7+) and Litematica .litematic, read and write. New code over codecs/text/Nbt (gzip NBT) and
-- codecs/model/Minecraft (block states, colours, legacy ids, packed arrays); the layouts: model/schematic/Mcedit,
-- Sponge, Litematic.
-- decode -> a Scene (meta.up = "y", one unit = one block): scene.voxels holds one Types.Voxels per region (a .litematic
-- has several), each with voxels.blocks (the exact block states, u16 per cell, plus block entities and entities as
-- NBT) and data / palette coloured from the default block colour table; a node per region places it (translation =
-- the region's minimum corner: Sponge Offset, WorldEdit WEOffset, Litematica Position). meta.source keeps the
-- variant, version, DataVersion, Metadata and the whole root NBT (source.nbt).
-- encode <- a Scene with voxels or one Types.Voxels: opts.variant (or the file name's extension, or the source's)
-- "schem" (default, version 3) / "schematic" / "litematic". Grids without blocks (a .vox) get, per palette colour,
-- the block nearest in colour. Several regions are merged into one grid for .schem / .schematic. Fields of the
-- source that are not blocks (Metadata, biomes, pending ticks, ...) are written back when the variant is the same.
-- Not supported: converting block properties to pre-1.13 data values (legacy writes keep the data a state came with
-- or 0), Sponge biome conversion between versions, rotated nodes (only translations place a grid).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Nbt = require("@formats/codecs/text/Nbt")
local Mc = require("@formats/codecs/model/Minecraft")
local Common = require("@formats/model/schematic/Common")
local Mcedit = require("@formats/model/schematic/Mcedit")
local Sponge = require("@formats/model/schematic/Sponge")
local Litematic = require("@formats/model/schematic/Litematic")
-- ------------------------------------------------------------------------------------------------ contract
local Schematic = {
name = "schematic",
category = "model",
extensions = { "schem", "schematic", "litematic" },
mime = { "application/x-minecraft-schematic" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Nbt", "codecs/model/Minecraft" },
caps = { decode = true, encode = true, voxels = true, blocks = true, variants = { "schem", "schematic", "litematic" } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxCells: number?, -- refuse schematics with more cells in total (default 2^26)
maxBytes: number?, -- refuse NBT that inflates past this (default 2^28)
}
export type EncodeOptions = {
variant: ("schem" | "schematic" | "litematic")?, -- default: the extension of opts.name, the source's, else "schem"
version: number?, -- Sponge 1 / 2 / 3 (default 3, or the source's), Litematica version (default 6, or the source's)
dataVersion: number?, -- Minecraft's DataVersion (default the source's, else 3953 = 1.21)
name: string?, -- the file name (its extension picks the variant); for .litematic also the default Metadata.Name
title: string?, -- .litematic Metadata.Name
compression: ("gzip" | "zlib" | "none")?, -- default gzip, as every tool writes them
level: number?, -- deflate level
format: string?, -- set by the api: the format key the encoder was picked by ("schem", "litematic", ...)
}
-- ------------------------------------------------------------------------------------------------ constants
local DEFAULT_DATA_VERSION = 3953
local LITEMATIC_HINTS = { "Regions", "EnclosingSize", "RegionCount", "TotalVolume", "MinecraftDataVersion" }
local SPONGE_HINTS = { "BlockData", "PaletteMax" } -- v1 / v2 fields (some writers leave the root unnamed)
local function hinted(head: string, hints: { string }): boolean
for _, h in hints do
if string.find(head, string.char(0, #h) .. h, 1, true) then
return true
end
end
return false
end
-- ------------------------------------------------------------------------------------------------ sniff
function Schematic.sniff(r: Bytes.Reader): number
local p = Nbt.peek(r.buf, r.base, r.limit - r.base)
if not p or p.rootType ~= "compound" or p.endian ~= "big" then
return 0
end
if p.name == "Schematic" or (p.firstName == "Schematic" and p.firstType == "compound") then
return 1
end
local head = buffer.tostring(p.head)
return if hinted(head, LITEMATIC_HINTS) or hinted(head, SPONGE_HINTS) then 1 else 0
end
-- variant(r) -> "schem" | "litematic" | "schematic" | nil: the flavour, for F.detect (from the first inflated bytes)
function Schematic.variant(r: Bytes.Reader): string?
local p = Nbt.peek(r.buf, r.base, r.limit - r.base)
if not p then
return nil
end
if p.firstName == "Schematic" then
return "schem"
end
local head = buffer.tostring(p.head)
if hinted(head, LITEMATIC_HINTS) then
return "litematic"
elseif hinted(head, SPONGE_HINTS) or (p.name == "Schematic" and hinted(head, { "Palette", "Version" })) then
return "schem"
end
return if p.name == "Schematic" then "schematic" else nil
end
-- ------------------------------------------------------------------------------------------------ decode
-- variantOf(root, name) -> "schem" | "schematic" | "litematic", the compound holding the Sponge fields | nil
local function variantOf(root: any): (string?, any)
if type(root) ~= "table" or not Types.isObject(root) then
return nil, nil
end
if Types.isObject(root.Regions) then
return "litematic", root
end
if Types.isObject(root.Schematic) and (Common.int(root.Schematic.Version) or 0) >= 3 then
return "schem", root.Schematic
end
if root.Version ~= nil and (root.Palette ~= nil or root.BlockData ~= nil) then
return "schem", root
end
if type(root.Blocks) == "buffer" then
return "schematic", root
end
return nil, nil
end
function Schematic.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local o: DecodeOptions = opts or {}
local root, info = Nbt.decode(r.buf, { maxBytes = o.maxBytes, endian = "big" }, r.base, r.limit - r.base)
if root == nil then
return nil, info
end
local variant, s = variantOf(root)
if not variant then
return nil, Err.new(Err.CORRUPT, "not a schematic (no Regions, Schematic / Palette or Blocks)")
end
local maxCells = o.maxCells or 2 ^ 26
local regions, extra
if variant == "litematic" then
regions, extra = Litematic.read(s, maxCells)
elseif variant == "schem" then
regions, extra = Sponge.read(s, maxCells)
else
regions, extra = Mcedit.read(s, maxCells)
end
if not regions then
local msg = tostring(extra)
return nil, Err.from(msg, nil, if string.find(msg, "limit: ", 1, true) then "limit" else nil)
end
local scene = Types.Scene.new()
scene.voxels = {}
for i, reg in regions do
local v = Mc.voxels(reg.size[1], reg.size[2], reg.size[3], reg.states, reg.indices)
v.name = reg.name
local b = v.blocks :: Types.VoxelBlocks
b.blockEntities = reg.blockEntities
b.entities = reg.entities
table.insert(scene.voxels :: { Types.Voxels }, v)
table.insert(scene.nodes, { name = reg.name, children = {}, voxels = i, translation = { reg.position[1], reg.position[2], reg.position[3] } })
table.insert(scene.roots, #scene.nodes)
end
scene.meta.up = "y"
scene.meta.unit = 1
local src: { [string]: any } = { format = "schematic", variant = variant, nbt = root, rootName = info.name, compression = info.compression }
for k, v in extra do
src[k] = v
end
scene.meta.source = src :: any
return scene, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local function regionsOf(value: any): ({ Common.Region }?, string?)
local out: { Common.Region } = {}
local function add(v: Types.Voxels, pos: { number }, name: string?): string?
if type(v) ~= "table" or type(v.size) ~= "table" or type(v.data) ~= "buffer" then
return "expected Types.Voxels grids"
end
local states, indices = Mc.blocksOf(v)
if not states then
return indices
end
local b = v.blocks
table.insert(out, {
name = name or v.name,
size = { v.size[1], v.size[2], v.size[3] },
position = { math.floor(pos[1] + 0.5), math.floor(pos[2] + 0.5), math.floor(pos[3] + 0.5) },
states = states,
indices = indices,
blockEntities = if b and b.blockEntities then b.blockEntities else {},
entities = if b and b.entities then b.entities else {},
})
return nil
end
if type(value) == "table" and value.kind == "voxels" then
local e = add(value, { 0, 0, 0 }, nil)
return if e then nil else out, e
end
if type(value) ~= "table" or value.kind ~= "scene" or type(value.voxels) ~= "table" or #value.voxels == 0 then
return nil, "expected a Scene with voxels or a Types.Voxels"
end
local placed = false
local function walk(i: number, base: { number }, depth: number): string?
local node = value.nodes[i]
if type(node) ~= "table" or depth > 64 then
return nil
end
local t = node.translation or { 0, 0, 0 }
local p = { base[1] + (t[1] or 0), base[2] + (t[2] or 0), base[3] + (t[3] or 0) }
if node.voxels and value.voxels[node.voxels] then
placed = true
local e = add(value.voxels[node.voxels], p, node.name)
if e then
return e
end
end
for _, c in node.children or {} do
local e = walk(c, p, depth + 1)
if e then
return e
end
end
return nil
end
for _, root in value.roots or {} do
local e = walk(root, { 0, 0, 0 }, 0)
if e then
return nil, e
end
end
if not placed then
for _, v in value.voxels do
local e = add(v, { 0, 0, 0 }, nil)
if e then
return nil, e
end
end
end
return out, nil
end
-- merge(regions) -> one region covering them all (air where none is)
local function merge(regions: { Common.Region }): Common.Region
if #regions == 1 then
return regions[1]
end
local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge }
for _, r in regions do
for k = 1, 3 do
lo[k] = math.min(lo[k], r.position[k])
hi[k] = math.max(hi[k], r.position[k] + r.size[k])
end
end
local sx, sy, sz = hi[1] - lo[1], hi[2] - lo[2], hi[3] - lo[3]
local states = { "minecraft:air" }
local out = buffer.create(sx * sy * sz * 2)
local bes, ents = {}, {}
for _, r in regions do
local base = #states
for _, st in r.states do
table.insert(states, st)
end
local rx, ry, rz = r.size[1], r.size[2], r.size[3]
local ox, oy, oz = r.position[1] - lo[1], r.position[2] - lo[2], r.position[3] - lo[3]
for z = 0, rz - 1 do
for y = 0, ry - 1 do
local s = (rx * (y + ry * z)) * 2
local d = (ox + sx * ((oy + y) + sy * (oz + z))) * 2
for _ = 0, rx - 1 do
buffer.writeu16(out, d, buffer.readu16(r.indices, s) + base)
s += 2
d += 2
end
end
end
for _, be in r.blockEntities do
table.insert(bes, { pos = { be.pos[1] + ox, be.pos[2] + oy, be.pos[3] + oz }, id = be.id, data = be.data })
end
for _, e in r.entities do
table.insert(ents, e)
end
end
local st, idx = Common.dedupe(states, out, sx * sy * sz)
return { name = regions[1].name, size = { sx, sy, sz }, position = lo, states = st, indices = idx, blockEntities = bes, entities = ents }
end
function Schematic.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local o: EncodeOptions = opts or {}
local regions, rerr = regionsOf(value)
if not regions then
return nil, Err.new(Err.ARG, tostring(rerr))
end
local src = if type(value) == "table" and type(value.meta) == "table" and type(value.meta.source) == "table" and value.meta.source.format == "schematic" then value.meta.source else nil
local ext = if o.name then string.lower(string.match(o.name, "%.([%w]+)$") or "") else nil
local key = o.format and string.lower(o.format)
local variant = o.variant
or (if ext == "schem" or ext == "schematic" or ext == "litematic" then ext else nil)
or (if key == "schem" or key == "litematic" then key else nil)
or (src and src.variant)
or "schem"
if variant ~= "schem" and variant ~= "schematic" and variant ~= "litematic" then
return nil, Err.new(Err.ARG, "unknown variant " .. tostring(variant))
end
local same = src ~= nil and src.variant == variant
local base = if same then (src :: any).nbt else nil
local dataVersion = o.dataVersion or (src and src.dataVersion) or DEFAULT_DATA_VERSION
local root, rootName, e
if variant == "litematic" then
local version = o.version or (if same then (src :: any).version else nil) or 6
local title = o.title or (if o.name then string.match(o.name, "([^/\\]-)%.[%w]+$") else nil)
root, e = Litematic.write(regions, version, dataVersion, base, title)
rootName = ""
elseif variant == "schem" then
local version = o.version or (if same then (src :: any).version else nil) or 3
if version ~= 1 and version ~= 2 and version ~= 3 then
return nil, Err.new(Err.ARG, "Sponge schematic version must be 1, 2 or 3")
end
local sameVersion = same and (src :: any).version == version
local inner = if sameVersion and base then (if version >= 3 then base.Schematic else base) else nil
local sch
sch, e = Sponge.write(merge(regions), version, dataVersion, inner)
if sch and version >= 3 then
root, rootName = Common.merge(if sameVersion then base else nil, { { "Schematic", sch } }), ""
else
root, rootName = sch, "Schematic"
end
else
root, e = Mcedit.write(merge(regions), base)
rootName = "Schematic"
end
if not root then
return nil, Err.new(Err.ARG, tostring(e))
end
if same and (src :: any).rootName ~= nil then
rootName = (src :: any).rootName
end
return Nbt.encode(root, { name = rootName, endian = "big", compression = o.compression or "gzip", level = o.level })
end
return Schematic