ws-voxel: wip: codecs/model/Minecraft, model/schematic, Types.Voxels blocks / colors

This commit is contained in:
4DBug committed 2026-10-31 14:25:41 -05:00
1 parent 998177e5ab
commit 58d7e08397
11 files changed
+2237

No files matched your search

+12
View File
@@ -360,6 +360,18 @@ export type Voxels = {
data: buffer, -- size x * y * z bytes, cell (x, y, z) at x + sx * (y + sy * z)
palette: { { number } }, -- palette[i] = { r, g, b, a } 0..255 (sRGB) for i = 1 .. 255 (shared between a file's models)
materials: { [number]: VoxelMaterial }?, -- by palette index
-- block grids (Minecraft schematics / regions): the exact block state of every cell, data / palette being its
-- colour view (block colours from a default table)
blocks: VoxelBlocks?,
-- true-colour grids (Qubicle): the exact 32-bit colour of every cell as r, g, b, a bytes (u32 little-endian,
-- a = 0 empty), data / palette being an indexed view of it
colors: buffer?,
}
export type VoxelBlocks = {
palette: { string }, -- block states ("minecraft:oak_stairs[facing=east,half=bottom]"), palette[1] is index 0
data: buffer, -- u16 little-endian per cell (same cell order as Voxels.data): 0-based index into palette
blockEntities: { any }?, -- the format's block entity records (NBT compounds; positions relative to the grid)
entities: { any }?, -- entity records (NBT compounds)
}
local Voxels = {}
-- new(sx, sy, sz, palette?) -> an empty grid (the palette defaults to grey ramps: callers set their own)
@@ -0,0 +1,81 @@
--!strict
-- codecs/model/Minecraft/Colors: the built-in default colour of Minecraft blocks, for showing block grids as coloured
-- voxels. Hand-made for this library (approximate average colours picked by eye; no game assets or wiki tables were
-- copied): exact block names, then families by dye colour and wood type; codecs/model/Minecraft resolves stairs /
-- slabs / walls / ... to their base block and falls back to keywords. Format: name=rrggbb or name=rrggbbaa.
local Colors = {}
Colors.BLOCKS = [[
stone=7d7d7d granite=956756 polished_granite=9a6a59 diorite=bcbcbc polished_diorite=c0c0c2 andesite=888889
polished_andesite=848686 grass_block=6d9a3f dirt=866043 coarse_dirt=77553b podzol=5b3f18 rooted_dirt=90674c
mud=3c3a3d cobblestone=7a7a7a bedrock=555555 sand=dbcf9f red_sand=be6621 gravel=837f7e suspicious_sand=d6c996
suspicious_gravel=817c7b sandstone=d8cb9b chiseled_sandstone=d8ca9b cut_sandstone=d9cd9e smooth_sandstone=dfd5a5
red_sandstone=b5621f cut_red_sandstone=bc6620 chiseled_red_sandstone=b7601e smooth_red_sandstone=b5621f
sponge=c3c04a wet_sponge=aaab3c glass=c0f5fe50 tinted_glass=2c262ec0 lapis_block=1f438c gold_block=f6d03d
iron_block=dcdcdc diamond_block=62ede4 emerald_block=2acb57 redstone_block=af1805 coal_block=101010
netherite_block=433e40 copper_block=c06c50 exposed_copper=a17e68 weathered_copper=6c9a6f oxidized_copper=52a284
cut_copper=bf6b51 raw_iron_block=a6896b raw_gold_block=dda92e raw_copper_block=9a6a4e amethyst_block=8562b8
budding_amethyst=84609f bricks=976253 bookshelf=75603d chiseled_bookshelf=b29159 mossy_cobblestone=6e7660
obsidian=0f0a18 crying_obsidian=200a3c tnt=db4130 spawner=24364a chest=a0742d trapped_chest=a0742d
ender_chest=2a3b3c crafting_table=81633c furnace=6d6d6d snow=f9fefe snow_block=f9fefe powder_snow=f8fdfd
ice=92b8fec8 packed_ice=8db4fa blue_ice=74a7fd frosted_ice=8cb4fac8 clay=a0a6b3 pumpkin=c6761a
carved_pumpkin=c27118 jack_o_lantern=d79a32 netherrack=612626 soul_sand=513e32 soul_soil=4b3a2e basalt=505055
polished_basalt=636367 smooth_basalt=48484e glowstone=ab8354 magma_block=8e3f1f nether_bricks=2c1518
red_nether_bricks=450709 cracked_nether_bricks=281417 chiseled_nether_bricks=2f171c nether_wart_block=720202
warped_wart_block=167879 end_stone=dbdea0 end_stone_bricks=dae0a2 purpur_block=a97ea9 purpur_pillar=ab81ab
prismarine=63a29a prismarine_bricks=63ab9e dark_prismarine=335b4b sea_lantern=acc7be hay_block=a68b0c
terracotta=985e43 quartz_block=ebe5de smooth_quartz=ece6df quartz_bricks=eae5dd quartz_pillar=ebe6e0
chiseled_quartz_block=e7e2da smooth_stone=9e9e9e stone_bricks=7a7979 mossy_stone_bricks=737969
cracked_stone_bricks=767676 chiseled_stone_bricks=777777 deepslate=505053 cobbled_deepslate=4d4d51
polished_deepslate=484849 deepslate_bricks=474747 cracked_deepslate_bricks=414141 deepslate_tiles=373737
cracked_deepslate_tiles=343434 chiseled_deepslate=363637 reinforced_deepslate=505350 tuff=6c6d67
polished_tuff=626a63 tuff_bricks=626660 calcite=dfe0dc dripstone_block=866b5c pointed_dripstone=816757
moss_block=596d2d moss_carpet=596d2d pale_moss_block=6b7069 melon=6f9118 cactus=587f28 sugar_cane=95c165
bamboo=5d8f1e bamboo_block=7f9030 stripped_bamboo_block=c0ad50 water=3f76e4b4 bubble_column=3f76e4b4
lava=cf5b14 short_grass=5b8a32 grass=5b8a32 tall_grass=5b8a32 fern=586e30 large_fern=586e30 dead_bush=6b4f29
vine=3c6e18 glow_lichen=708079 lily_pad=208030 seagrass=307b16 tall_seagrass=307b16 kelp=3b7f22
kelp_plant=3b7f22 dried_kelp_block=323b27 red_mushroom_block=c82e2d brown_mushroom_block=957051
mushroom_stem=cbc4b9 red_mushroom=d84a3e brown_mushroom=9a7759 slime_block=6fc05bc8 honey_block=fba92fc8
honeycomb_block=e5941e bone_block=e1ddc9 shroomlight=f19346 target=e2aa9e respawn_anchor=4b1e86
lodestone=939599 blackstone=2a2328 polished_blackstone=35303b polished_blackstone_bricks=302a32
cracked_polished_blackstone_bricks=2c2629 chiseled_polished_blackstone=35303b gilded_blackstone=382b26
crimson_nylium=831f1f warped_nylium=2b7265 crimson_roots=7e0812 warped_roots=148a7c packed_mud=8e6b50
mud_bricks=89684f sculk=0d1e24 sculk_catalyst=2d3a3b sculk_sensor=074654 sculk_shrieker=c6cdab
redstone_lamp=5f361e note_block=58392a jukebox=5d4030 beacon=75dcd7 observer=626262 piston=9a8d6c
sticky_piston=8b9c66 piston_head=9a8d6c dispenser=7a7a7a dropper=7a7a7a hopper=434343 anvil=444444
chipped_anvil=444444 damaged_anvil=444444 cauldron=4a4a4a rail=7d6c4b powered_rail=8a6d3e detector_rail=7b6853
activator_rail=74574b ladder=7c5f35 scaffolding=aa8449 lantern=6a5b54 soul_lantern=4a6366 campfire=6e5638
soul_campfire=4e5d5d barrel=86643b smoker=5a5853 blast_furnace=6c6b6b cartography_table=685032
fletching_table=c5b485 smithing_table=39394a loom=8e7965 stonecutter=7b7672 grindstone=8e8e8e composter=704a26
beehive=b8945b bee_nest=c5964b farmland=8f6646 dirt_path=94793f mycelium=6f6365 torch=ffd80060
wall_torch=ffd80060 soul_torch=6be1e360 redstone_torch=c0210f60 redstone_wire=9e0b0060 lever=6e6e6e60
cobweb=e4e9ea80 iron_bars=8b8d8b90 chain=3a404e90 end_rod=e0d8d0 chorus_plant=5e395e chorus_flower=977a97
dragon_egg=0c0910 end_portal_frame=5b7860 enchanting_table=813838 brewing_stand=7a654f flower_pot=7d4536
cake=f8dede conduit=9f8b71 lectern=ad8a54 bell=fdd533 decorated_pot=8f4f35 crafter=7a6c64
trial_spawner=3b4a55 vault=46545c heavy_core=4c5056 command_block=b5886c chain_command_block=829f8f
repeating_command_block=8370b0 structure_block=58475b jigsaw=50455a
dandelion=e0c41c poppy=c42b1a blue_orchid=2aa8d0 allium=b878e8 azure_bluet=dfe6d7 red_tulip=c43b1b
orange_tulip=e07e1b white_tulip=e0e8db pink_tulip=e8b8d8 oxeye_daisy=e8e8c8 cornflower=4f76d8
lily_of_the_valley=e8e8e8 wither_rose=2a2c18 sunflower=f0c71d lilac=b88cb8 rose_bush=b02a1e peony=e8b8e0
torchflower=d9b14e pitcher_plant=7a97c8 pink_petals=f0b8d0 spore_blossom=d066a8 azalea=5f7a2c
flowering_azalea=7c6b6e sweet_berry_bush=3f6a2f cocoa=8c5428 wheat=a99c30 carrots=4a9a1e potatoes=4c9a2a
beetroots=5a8a2a nether_wart=8a1818 crimson_fungus=8a2525 warped_fungus=2a7a6e twisting_vines=148a7c
weeping_vines=8a1414 hanging_roots=a17561 big_dripleaf=6b8f34 small_dripleaf=6b8f34 cave_vines=5a6d23
frogspawn=66605ca0 sniffer_egg=8a5045 turtle_egg=dcd8b8 sea_pickle=6a7030 mangrove_roots=4b3c27
muddy_mangrove_roots=46413a ochre_froglight=f6e8a6 verdant_froglight=dcf0d6 pearlescent_froglight=f1e1ea
creaking_heart=5a4a3c resin_block=d9661c resin_bricks=ce5a1a
]]
-- wool-like colour of each dye, then concrete and terracotta (same order as Colors.DYES)
Colors.DYES = { "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan", "purple", "blue", "brown", "green", "red", "black" }
Colors.WOOL = "e9ecec f07613 bd44b3 3aafd9 f8c527 70b919 ed8dac 3e4447 8e8e86 158991 792aac 35399d 724728 546d1b a12722 141519"
Colors.CONCRETE = "cfd5d6 e06100 a9309f 2389c6 f0af15 5ea818 d5658e 36393d 7d7d73 157788 64209c 2c2e8f 603b1f 495b24 8e2020 080a0f"
Colors.TERRACOTTA = "d1b2a1 a15325 95576c 716c89 ba8523 677534 a14e4e 392a23 876a61 575b5b 764656 4a3b5b 4d3323 4c532a 8f3d2e 251610"
-- wood types: planks, bark (log / wood), leaves
Colors.WOODS = { "oak", "spruce", "birch", "jungle", "acacia", "dark_oak", "mangrove", "cherry", "pale_oak", "bamboo", "crimson", "warped" }
Colors.PLANKS = "a2834f 735531 c0af79 a07351 a85a32 432b14 763631 e3b3ad e4d9d3 c1ad50 653147 2b6963"
Colors.BARK = "6d5533 3a2510 d8d7d2 55441a 676157 3e2f17 543a26 371b22 524a46 7f9030 5c1919 3a3a4d"
Colors.LEAVES = "4a7a20 3d5d3d 5f8a3c 3f8a1c 4b7a1e 3c6a18 4b8a28 e5adc2 878d76 5d8f1e 831f1f 2b7265"
return Colors
@@ -0,0 +1,111 @@
--!strict
-- codecs/model/Minecraft/Legacy: numeric block ids of Minecraft before 1.13 (the .schematic format, Anvil chunks with
-- Blocks / Data arrays), from the Minecraft wiki "Java Edition data values/Pre-flattening" page (facts, not code):
-- the 1.12 name of every id, and how the data value picks a variant for the blocks whose colour or wood depends on it
-- (the modern name of that variant: wool 14 -> red_wool, planks 2 -> birch_planks).
local Legacy = {}
local function words(s: string): { string }
local out = {}
for w in string.gmatch(s, "%S+") do
table.insert(out, w)
end
return out
end
-- ids 0 .. 255 (NAMES[id + 1]), "-" = unused
Legacy.NAMES = words([[air stone grass dirt cobblestone planks sapling bedrock flowing_water water flowing_lava
lava sand gravel gold_ore iron_ore coal_ore log leaves sponge glass lapis_ore lapis_block dispenser sandstone noteblock
bed golden_rail detector_rail sticky_piston web tallgrass deadbush piston piston_head wool piston_extension
yellow_flower red_flower brown_mushroom red_mushroom gold_block iron_block double_stone_slab stone_slab brick_block tnt
bookshelf mossy_cobblestone obsidian torch fire mob_spawner oak_stairs chest redstone_wire diamond_ore diamond_block
crafting_table wheat farmland furnace lit_furnace standing_sign wooden_door ladder rail stone_stairs wall_sign lever
stone_pressure_plate iron_door wooden_pressure_plate redstone_ore lit_redstone_ore unlit_redstone_torch redstone_torch
stone_button snow_layer ice snow cactus clay reeds jukebox fence pumpkin netherrack soul_sand glowstone portal
lit_pumpkin cake unpowered_repeater powered_repeater stained_glass trapdoor monster_egg stonebrick
brown_mushroom_block red_mushroom_block iron_bars glass_pane melon_block pumpkin_stem melon_stem vine fence_gate
brick_stairs stone_brick_stairs mycelium waterlily nether_brick nether_brick_fence nether_brick_stairs nether_wart
enchanting_table brewing_stand cauldron end_portal end_portal_frame end_stone dragon_egg redstone_lamp
lit_redstone_lamp double_wooden_slab wooden_slab cocoa sandstone_stairs emerald_ore ender_chest tripwire_hook tripwire
emerald_block spruce_stairs birch_stairs jungle_stairs command_block beacon cobblestone_wall flower_pot carrots
potatoes wooden_button skull anvil trapped_chest light_weighted_pressure_plate heavy_weighted_pressure_plate
unpowered_comparator powered_comparator daylight_detector redstone_block quartz_ore hopper quartz_block quartz_stairs
activator_rail dropper stained_hardened_clay stained_glass_pane leaves2 log2 acacia_stairs dark_oak_stairs slime
barrier iron_trapdoor prismarine sea_lantern hay_block carpet hardened_clay coal_block packed_ice double_plant
standing_banner wall_banner daylight_detector_inverted red_sandstone red_sandstone_stairs double_stone_slab2
stone_slab2 spruce_fence_gate birch_fence_gate jungle_fence_gate dark_oak_fence_gate acacia_fence_gate spruce_fence
birch_fence jungle_fence dark_oak_fence acacia_fence spruce_door birch_door jungle_door acacia_door dark_oak_door
end_rod chorus_plant chorus_flower purpur_block purpur_pillar purpur_stairs purpur_double_slab purpur_slab end_bricks
beetroots grass_path end_gateway repeating_command_block chain_command_block frosted_ice magma nether_wart_block
red_nether_brick bone_block structure_void observer white_shulker_box orange_shulker_box magenta_shulker_box
light_blue_shulker_box yellow_shulker_box lime_shulker_box pink_shulker_box gray_shulker_box silver_shulker_box
cyan_shulker_box purple_shulker_box blue_shulker_box brown_shulker_box green_shulker_box red_shulker_box
black_shulker_box white_glazed_terracotta orange_glazed_terracotta magenta_glazed_terracotta
light_blue_glazed_terracotta yellow_glazed_terracotta lime_glazed_terracotta pink_glazed_terracotta
gray_glazed_terracotta silver_glazed_terracotta cyan_glazed_terracotta purple_glazed_terracotta
blue_glazed_terracotta brown_glazed_terracotta green_glazed_terracotta red_glazed_terracotta black_glazed_terracotta
concrete concrete_powder - - structure_block]])
-- legacy names whose modern name differs (data value not involved; only one-to-one renames, so the way back is exact:
-- lit_furnace, powered_repeater, ... keep their legacy names)
Legacy.RENAMED = {
grass = "grass_block", brick_block = "bricks", stonebrick = "stone_bricks", hardened_clay = "terracotta",
melon_block = "melon", lit_pumpkin = "jack_o_lantern", slime = "slime_block", magma = "magma_block",
red_nether_brick = "red_nether_bricks", nether_brick = "nether_bricks", end_bricks = "end_stone_bricks",
mob_spawner = "spawner", web = "cobweb", snow_layer = "snow", snow = "snow_block", noteblock = "note_block",
quartz_ore = "nether_quartz_ore", reeds = "sugar_cane", waterlily = "lily_pad", flowing_water = "water",
flowing_lava = "lava", tallgrass = "short_grass", grass_path = "dirt_path", double_stone_slab = "smooth_stone",
stone_slab = "smooth_stone_slab", deadbush = "dead_bush", yellow_flower = "dandelion",
fence = "oak_fence", fence_gate = "oak_fence_gate",
wooden_door = "oak_door", trapdoor = "oak_trapdoor", wooden_pressure_plate = "oak_pressure_plate",
wooden_button = "oak_button", stone_stairs = "cobblestone_stairs", standing_sign = "oak_sign",
wall_sign = "oak_wall_sign", golden_rail = "powered_rail", portal = "nether_portal", piston_extension = "moving_piston",
silver_shulker_box = "light_gray_shulker_box", silver_glazed_terracotta = "light_gray_glazed_terracotta",
monster_egg = "infested_stone",
standing_banner = "white_banner", wall_banner = "white_wall_banner", skull = "skeleton_skull",
bed = "red_bed",
}
-- legacy names whose data value selects the variant: the modern names by data value (0-based)
local DYED = "white orange magenta light_blue yellow lime pink gray light_gray cyan purple blue brown green red black"
local function dyed(suffix: string): { string }
local out = {}
for i, d in words(DYED) do
out[i] = d .. "_" .. suffix
end
return out
end
Legacy.VARIANTS = {
stone = { "stone", "granite", "polished_granite", "diorite", "polished_diorite", "andesite", "polished_andesite" },
dirt = { "dirt", "coarse_dirt", "podzol" },
planks = { "oak_planks", "spruce_planks", "birch_planks", "jungle_planks", "acacia_planks", "dark_oak_planks" },
wooden_slab = { "oak_slab", "spruce_slab", "birch_slab", "jungle_slab", "acacia_slab", "dark_oak_slab" },
sapling = { "oak_sapling", "spruce_sapling", "birch_sapling", "jungle_sapling", "acacia_sapling", "dark_oak_sapling" },
sand = { "sand", "red_sand" },
log = { "oak_log", "spruce_log", "birch_log", "jungle_log" }, -- data % 4
log2 = { "acacia_log", "dark_oak_log" },
leaves = { "oak_leaves", "spruce_leaves", "birch_leaves", "jungle_leaves" },
leaves2 = { "acacia_leaves", "dark_oak_leaves" },
sponge = { "sponge", "wet_sponge" },
sandstone = { "sandstone", "chiseled_sandstone", "cut_sandstone" },
red_sandstone = { "red_sandstone", "chiseled_red_sandstone", "cut_red_sandstone" },
stonebrick = { "stone_bricks", "mossy_stone_bricks", "cracked_stone_bricks", "chiseled_stone_bricks" },
quartz_block = { "quartz_block", "chiseled_quartz_block", "quartz_pillar" },
prismarine = { "prismarine", "prismarine_bricks", "dark_prismarine" },
cobblestone_wall = { "cobblestone_wall", "mossy_cobblestone_wall" },
red_flower = { "poppy", "blue_orchid", "allium", "azure_bluet", "red_tulip", "orange_tulip", "white_tulip", "pink_tulip", "oxeye_daisy" },
double_plant = { "sunflower", "lilac", "tall_grass", "large_fern", "rose_bush", "peony" },
wool = dyed("wool"),
carpet = dyed("carpet"),
stained_glass = dyed("stained_glass"),
stained_glass_pane = dyed("stained_glass_pane"),
stained_hardened_clay = dyed("terracotta"),
concrete = dyed("concrete"),
concrete_powder = dyed("concrete_powder"),
}
Legacy.MASK = { log = 4, log2 = 4, leaves = 4, leaves2 = 4, sapling = 8, wooden_slab = 8, quartz_block = 8, double_plant = 8 }
return Legacy
@@ -0,0 +1,220 @@
--!strict
--!native
--!optimize 2
-- codecs/model/Minecraft/Packed: Minecraft's packed index arrays. New code, from the Minecraft wiki "Chunk format" and
-- the Sponge / Litematica schematic specs: long arrays (little-endian int64s as codecs/text/Nbt keeps them) holding
-- bits-wide indices either spanning long boundaries (Litematica, chunks before 1.16) or not (chunks since 1.16:
-- floor(64 / bits) per long, the rest padding), and the varint byte arrays of Sponge schematics. Indices are written
-- to / read from u16 little-endian buffers. Every access is bounds-checked first; never throws.
local Packed = {}
local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32
local writeu8, writeu16 = buffer.writeu8, buffer.writeu16
local extract, band, rshift, lshift, bor = bit32.extract, bit32.band, bit32.rshift, bit32.lshift, bit32.bor
-- longsNeeded(count, bits, spanning) -> the number of longs a packed array of count indices takes
function Packed.longsNeeded(count: number, bits: number, spanning: boolean): number
if spanning then
return (count * bits + 63) // 64
end
local per = 64 // bits
return (count + per - 1) // per
end
-- unpack(longs, bits, count, spanning, out, max) -> true | false, message: count indices into out (u16 LE, from byte
-- 0); an index >= max is an error. bits 1 .. 16.
function Packed.unpack(longs: buffer, bits: number, count: number, spanning: boolean, out: buffer, max: number): (boolean, string?)
if bits < 1 or bits > 16 then
return false, "unsupported: " .. bits .. "-bit packed indices"
end
local need = Packed.longsNeeded(count, bits, spanning)
if buffer.len(longs) < need * 8 then
return false, "packed array too short (" .. buffer.len(longs) // 8 .. " longs, need " .. need .. ")"
end
if buffer.len(out) < count * 2 then
return false, "output too small"
end
-- a copy with 4 bytes of padding, so every 32-bit read stays in range
local n = need * 8
local src = buffer.create(n + 4)
buffer.copy(src, 0, longs, 0, n)
if spanning then
local p = 0
for i = 0, count - 1 do
local v = extract(readu32(src, rshift(p, 3)), band(p, 7), bits)
if v >= max then
return false, "index " .. v .. " past the palette (" .. max .. ")"
end
writeu16(out, i * 2, v)
p += bits
end
else
local per = 64 // bits
local i = 0
local base = 0
while i < count do
local p = 0
for _ = 1, per do
if i >= count then
break
end
local v = extract(readu32(src, base + rshift(p, 3)), band(p, 7), bits)
if v >= max then
return false, "index " .. v .. " past the palette (" .. max .. ")"
end
writeu16(out, i * 2, v)
i += 1
p += bits
end
base += 8
end
end
return true, nil
end
-- pack(indices, count, bits, spanning) -> longs buffer (little-endian int64s): the inverse of unpack
function Packed.pack(indices: buffer, count: number, bits: number, spanning: boolean): buffer
local need = Packed.longsNeeded(count, bits, spanning)
local out = buffer.create(need * 8 + 4)
local per = 64 // bits
for i = 0, count - 1 do
local v = readu16(indices, i * 2)
local p = if spanning then i * bits else (i // per) * 64 + (i % per) * bits
local at = rshift(p, 3)
local sh = band(p, 7)
-- OR the value in byte by byte (up to 3 bytes for 16 bits at a shift of 7)
local x = lshift(v, sh)
for k = 0, 2 do
local bits8 = band(rshift(x, k * 8), 0xff)
if bits8 ~= 0 then
writeu8(out, at + k, bor(readu8(out, at + k), bits8))
end
end
end
local res = buffer.create(need * 8)
buffer.copy(res, 0, out, 0, need * 8)
return res
end
-- bitsFor(n, min) -> bits for indices 0 .. n - 1 (at least min)
function Packed.bitsFor(n: number, min: number): number
local b = min
while lshift(1, b) < n and b < 31 do
b += 1
end
return b
end
-- varints(src, offset, length, count, out, max) -> true | false, message: count unsigned LEB128 varints (Sponge
-- BlockData) into out (u16 LE)
function Packed.varints(src: buffer, offset: number, length: number, count: number, out: buffer, max: number): (boolean, string?)
if buffer.len(out) < count * 2 or offset + length > buffer.len(src) then
return false, "bad varint array arguments"
end
local p, e = offset, offset + length
for i = 0, count - 1 do
local v, sh = 0, 0
while true do
if p >= e then
return false, "truncated: block data ends after " .. i .. " of " .. count .. " entries"
end
local c = readu8(src, p)
p += 1
v += band(c, 0x7f) * 2 ^ sh
if c < 128 then
break
end
sh += 7
if sh > 28 then
return false, "varint too long"
end
end
if v >= max then
return false, "index " .. v .. " past the palette (" .. max .. ")"
end
writeu16(out, i * 2, v)
end
return true, nil
end
-- toVarints(indices, count) -> buffer: count u16 indices as unsigned LEB128 varints
function Packed.toVarints(indices: buffer, count: number): buffer
local out = buffer.create(count * 3)
local p = 0
for i = 0, count - 1 do
local v = readu16(indices, i * 2)
while v >= 128 do
writeu8(out, p, band(v, 0x7f) + 128)
p += 1
v = rshift(v, 7)
end
writeu8(out, p, v)
p += 1
end
local res = buffer.create(p)
buffer.copy(res, 0, out, 0, p)
return res
end
-- nibble(src, offset, i, highFirst) -> the 4-bit value i of a nibble array (Minecraft: low nibble first; WorldEdit's
-- AddBlocks: high nibble first)
function Packed.nibble(src: buffer, offset: number, i: number, highFirst: boolean): number
local b = readu8(src, offset + rshift(i, 1))
local odd = band(i, 1) == 1
if odd == highFirst then
return band(b, 15)
end
return rshift(b, 4)
end
-- setNibble(dst, offset, i, v, highFirst)
function Packed.setNibble(dst: buffer, offset: number, i: number, v: number, highFirst: boolean)
local at = offset + rshift(i, 1)
local b = readu8(dst, at)
local odd = band(i, 1) == 1
if odd == highFirst then
writeu8(dst, at, bor(band(b, 0xf0), band(v, 15)))
else
writeu8(dst, at, bor(band(b, 0x0f), lshift(band(v, 15), 4)))
end
end
-- fromYzx(src, sx, sy, sz, dst?, ox?, oy?, oz?, dsx?, dsy?) -> dst: u16 cells in Minecraft's order (x fastest, then
-- z, then y: schematics, chunk sections) to Types.Voxels order (x, then y, then z), into dst (default a new
-- sx * sy * sz grid) at cell offset (ox, oy, oz) of a dsx * dsy * ... grid. The caller checks the ranges.
function Packed.fromYzx(src: buffer, sx: number, sy: number, sz: number, dst: buffer?, ox: number?, oy: number?, oz: number?, dsx: number?, dsy: number?): buffer
local out = dst or buffer.create(sx * sy * sz * 2)
local bx, by, bz = ox or 0, oy or 0, oz or 0
local wx, wy = dsx or sx, dsy or sy
local i = 0
for y = 0, sy - 1 do
for z = 0, sz - 1 do
local d = (bx + wx * ((by + y) + wy * (bz + z))) * 2
for _ = 0, sx - 1 do
writeu16(out, d, readu16(src, i))
i += 2
d += 2
end
end
end
return out
end
-- toYzx(src, sx, sy, sz) -> buffer: Types.Voxels order to Minecraft's (the inverse of fromYzx)
function Packed.toYzx(src: buffer, sx: number, sy: number, sz: number): buffer
local out = buffer.create(sx * sy * sz * 2)
local i = 0
for y = 0, sy - 1 do
for z = 0, sz - 1 do
local s = (sx * (y + sy * z)) * 2
for _ = 0, sx - 1 do
writeu16(out, i, readu16(src, s))
i += 2
s += 2
end
end
end
return out
end
return Packed
@@ -0,0 +1,500 @@
--!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] = hex(h)
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 = {}
for i, n in names do
table.insert(out, { n, i })
end
table.sort(out, function(a, b)
return #a[1] > #b[1]
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_", "infested_", "lit_", "unlit_", "unpowered_", "powered_", "chipped_", "damaged_" }
local CORAL = { 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
return Minecraft
+202
View File
@@ -0,0 +1,202 @@
--!strict
-- model/schematic/Common: what the three schematic flavours share: the region record they read into and write from,
-- NBT field access with type checks, and block entities in one shape ({ pos = { x, y, z }, id, data }: Sponge v3's,
-- converted from / to MCEdit's and Litematica's flat { x, y, z, id, ... } and Sponge v2's { Pos, Id, ... }).
local Types = require("@formats/Types")
local Nbt = require("@formats/codecs/text/Nbt")
local Common = {}
-- a block region: indices are u16 per cell in Types.Voxels order (x fastest, then y, then z) into states
export type Region = {
name: string?,
size: { number }, -- x, y, z cells
position: { number }, -- the minimum corner relative to the schematic origin
states: { string },
indices: buffer,
blockEntities: { any },
entities: { any },
}
-- int(v) -> the integer value of an NBT number (byte / short / int / long tag or plain number) | nil
function Common.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
-- dims(a, b, c, max) -> sx, sy, sz | nil, message: positive sizes whose product stays under max cells
function Common.dims(a: any, b: any, c: any, max: number): (number?, any, number?)
local x, y, z = Common.int(a), Common.int(b), Common.int(c)
if not x or not y or not z then
return nil, "missing or non-integer size", nil
end
if x < 0 or y < 0 or z < 0 then
return nil, "negative size", nil
end
if x * y * z > max then
return nil, "limit: " .. x .. " x " .. y .. " x " .. z .. " cells is over maxCells", nil
end
return x, y, z
end
-- ints(v) -> the numbers of an intArray tag or a list of numbers | nil
function Common.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[1] ~= nil then
local out = {}
for i, x in v do
out[i] = Nbt.number(x) or 0
end
return out
end
return nil
end
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 Common.blockEntity(c: any, style: string): any
if type(c) ~= "table" or Nbt.isTag(c) then
return nil
end
if style == "flat" then
return { pos = { Common.int(c.x) or 0, Common.int(c.y) or 0, Common.int(c.z) or 0 }, id = if type(c.id) == "string" then c.id else nil, data = rest(c, FLAT_SKIP) }
end
local p = Common.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 Common.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
-- list(v) -> v when it is an NBT list (array), else an empty list
function Common.list(v: any): { any }
if type(v) == "table" and not Nbt.isTag(v) and not Types.isObject(v) then
return v
end
return {}
end
-- compound({ { key, value } }) -> a Types.object with these keys in this order (nil values skipped)
function Common.compound(fields: { { any } }): { [string]: any }
local o, keys = {}, {}
for _, kv in fields do
if kv[2] ~= nil then
o[kv[1]] = kv[2]
table.insert(keys, kv[1])
end
end
return Types.object(o, keys)
end
-- merge(base, fields, drop?) -> a compound of fields ({ { key, value } }, nil values left out) laid out in base's key
-- order (a decoded source compound: its other keys are kept, except those in drop), new keys after
function Common.merge(base: any, fields: { { any } }, drop: { [string]: boolean }?): { [string]: any }
if type(base) ~= "table" or not Types.isObject(base) then
return Common.compound(fields)
end
local mine: { [string]: any } = {}
local present: { [string]: boolean } = {}
for _, kv in fields do
present[kv[1]] = true
mine[kv[1]] = kv[2]
end
local out = {}
for _, k in Types.keys(base) do
if present[k] then
if mine[k] ~= nil then
table.insert(out, { k, mine[k] })
end
elseif not (drop and drop[k]) then
table.insert(out, { k, base[k] })
end
end
local seen: { [string]: boolean } = {}
for _, kv in out do
seen[kv[1]] = true
end
for _, kv in fields do
if not seen[kv[1]] and kv[2] ~= nil then
table.insert(out, kv)
end
end
return Common.compound(out)
end
-- dedupe(states, indices, n) -> states, indices with every state once (indices remapped when needed)
function Common.dedupe(states: { string }, indices: buffer, n: number): ({ string }, buffer)
local first: { [string]: number } = {}
local remap: { number } = {}
local out: { string } = {}
local dup = false
for i, s in states do
local at = first[s]
if at == nil then
table.insert(out, s)
at = #out - 1
first[s] = at
else
dup = true
end
remap[i] = at
end
if not dup then
return states, indices
end
local res = buffer.create(n * 2)
for i = 0, n - 1 do
buffer.writeu16(res, i * 2, remap[buffer.readu16(indices, i * 2) + 1] or 0)
end
return out, res
end
return Common
+215
View File
@@ -0,0 +1,215 @@
--!strict
-- model/schematic/Litematic: Litematica's .litematic, from the mod's sources (LitematicaSchematic,
-- LitematicaBitArray) as documented by the litemapy project: Metadata (name, author, description, enclosing size,
-- counts, times, preview), several named Regions with a Position and a Size that may be negative, a block-state
-- palette (index 0 = air) and BlockStates packed spanning long boundaries (at least 2 bits), TileEntities (relative
-- to the region's minimum corner), Entities and pending ticks (kept as they are).
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 Litematic = {}
local Packed = Mc.Packed
local function xyz(c: any): { number }?
if type(c) ~= "table" then
return nil
end
local x, y, z = Common.int(c.x), Common.int(c.y), Common.int(c.z)
if not x or not y or not z then
return nil
end
return { x, y, z }
end
local function vec(v: { number }): any
return Common.compound({ { "x", v[1] }, { "y", v[2] }, { "z", v[3] } })
end
-- read(root, maxCells) -> { Region }, extra | nil, message
function Litematic.read(root: any, maxCells: number): ({ Common.Region }?, any)
if not Types.isObject(root.Regions) then
return nil, "no Regions"
end
local out: { Common.Region } = {}
local total = 0
local raw: { [string]: any } = {}
for _, name in Types.keys(root.Regions) do
local reg = root.Regions[name]
if type(reg) ~= "table" then
return nil, "region " .. name .. " is not a compound"
end
local pos, size = xyz(reg.Position), xyz(reg.Size)
if not pos or not size then
return nil, "region " .. name .. ": no Position / Size"
end
local ax, ay, az = math.abs(size[1]), math.abs(size[2]), math.abs(size[3])
local sx, sy, sz = Common.dims(ax, ay, az, maxCells - total)
if not sx then
return nil, "region " .. name .. ": " .. tostring(sy)
end
total += ax * ay * az
local states: { string } = {}
for i, c in Common.list(reg.BlockStatePalette) do
local st = Mc.stateFromNbt(c)
if not st then
return nil, "region " .. name .. ": bad palette entry " .. i
end
states[i] = st
end
if #states == 0 then
states[1] = "minecraft:air"
end
local n = ax * ay * az
local yzx = buffer.create(n * 2)
local bs = reg.BlockStates
if n > 0 then
if not (Nbt.isTag(bs) and bs.type == "longArray") then
return nil, "region " .. name .. ": no BlockStates"
end
local bits = Packed.bitsFor(#states, 2)
local ok, e = Packed.unpack(bs.value, bits, n, true, yzx, #states)
if not ok then
return nil, "region " .. name .. ": " .. tostring(e)
end
end
local bes = {}
for _, c in Common.list(reg.TileEntities) do
local be = Common.blockEntity(c, "flat")
if be then
table.insert(bes, be)
end
end
table.insert(out, {
name = name,
size = { ax, ay, az },
position = {
pos[1] + (if size[1] < 0 then size[1] + 1 else 0),
pos[2] + (if size[2] < 0 then size[2] + 1 else 0),
pos[3] + (if size[3] < 0 then size[3] + 1 else 0),
},
states = states,
indices = Packed.fromYzx(yzx, ax, ay, az),
blockEntities = bes,
entities = Common.list(reg.Entities),
})
raw[name] = reg
end
return out, {
version = Common.int(root.Version),
subVersion = Common.int(root.SubVersion),
dataVersion = Common.int(root.MinecraftDataVersion),
metadata = root.Metadata,
regions = raw,
}
end
-- write(regions, version, dataVersion, base?, name?) -> the root compound | nil, message. base: the decoded root
-- (Metadata fields and each region's Position / Size signs and pending ticks are kept)
function Litematic.write(regions: { Common.Region }, version: number, dataVersion: number, base: any, title: string?): (any, string?)
local baseRegions = if type(base) == "table" and Types.isObject(base.Regions) then base.Regions else nil
local regs, order = {}, {}
local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge }
local blocks, volume = 0, 0
for i, r in regions do
local name = r.name or ("Region" .. (if i == 1 then "" else tostring(i)))
while regs[name] ~= nil do
name ..= "_"
end
local sx, sy, sz = r.size[1], r.size[2], r.size[3]
local n = sx * sy * sz
local states, indices = Common.dedupe(r.states, r.indices, n)
if states[1] ~= "minecraft:air" then
-- Litematica keeps air at index 0
local at = table.find(states, "minecraft:air")
local shifted = buffer.create(n * 2)
local nst = table.clone(states)
if at then
nst[1], nst[at] = states[at], states[1]
else
table.insert(nst, 1, "minecraft:air")
end
for c = 0, n - 1 do
local v = buffer.readu16(indices, c * 2)
local w = if at then (if v == 0 then at - 1 elseif v == at - 1 then 0 else v) else v + 1
buffer.writeu16(shifted, c * 2, w)
end
states, indices = nst, shifted
end
local palette = Nbt.list("compound")
for k, st in states do
palette[k] = Mc.stateToNbt(st)
end
local airLike: { [number]: boolean } = {}
for k, st in states do
airLike[k - 1] = Mc.isAir(st)
end
for c = 0, n - 1 do
if not airLike[buffer.readu16(indices, c * 2)] then
blocks += 1
end
end
volume += n
local bits = Packed.bitsFor(#states, 2)
local longs = Packed.pack(Packed.toYzx(indices, sx, sy, sz), n, bits, true)
local tiles = Nbt.list("compound")
for _, be in r.blockEntities do
table.insert(tiles, Common.flatBlockEntity(be, "flat"))
end
local p = r.position
local pos, size = { p[1], p[2], p[3] }, { sx, sy, sz }
local b = if baseRegions then baseRegions[name] else nil
local bsize = if type(b) == "table" then xyz(b.Size) else nil
if bsize and math.abs(bsize[1]) == sx and math.abs(bsize[2]) == sy and math.abs(bsize[3]) == sz then
-- keep the source's corner and signs
for k = 1, 3 do
if bsize[k] < 0 then
size[k] = bsize[k]
pos[k] = p[k] - bsize[k] - 1
end
end
end
for k = 1, 3 do
lo[k] = math.min(lo[k], p[k])
hi[k] = math.max(hi[k], p[k] + r.size[k])
end
regs[name] = Common.merge(b, {
{ "BlockStatePalette", palette },
{ "BlockStates", Nbt.longArray(longs) },
{ "Entities", if #r.entities > 0 then r.entities else Nbt.list("compound") },
{ "PendingBlockTicks", if type(b) == "table" then b.PendingBlockTicks else Nbt.list("compound") },
{ "PendingFluidTicks", if type(b) == "table" then b.PendingFluidTicks else Nbt.list("compound") },
{ "Position", vec(pos) },
{ "Size", vec(size) },
{ "TileEntities", tiles },
})
table.insert(order, name)
end
if #order == 0 then
lo, hi = { 0, 0, 0 }, { 0, 0, 0 }
end
local bm = if type(base) == "table" and type(base.Metadata) == "table" then base.Metadata else nil
local metadata = Common.merge(bm, {
{ "EnclosingSize", vec({ hi[1] - lo[1], hi[2] - lo[2], hi[3] - lo[3] }) },
{ "Author", if bm and bm.Author then bm.Author else "" },
{ "Description", if bm and bm.Description then bm.Description else "" },
{ "Name", title or (if bm and bm.Name then bm.Name else "Unnamed") },
{ "RegionCount", #order },
{ "TimeCreated", if bm and bm.TimeCreated then bm.TimeCreated else Nbt.long(0) },
{ "TimeModified", if bm and bm.TimeModified then bm.TimeModified else Nbt.long(0) },
{ "TotalBlocks", blocks },
{ "TotalVolume", volume },
})
local regions_ = Types.object(regs, order)
return Common.merge(base, {
{ "MinecraftDataVersion", dataVersion },
{ "Version", version },
{ "SubVersion", if type(base) == "table" and base.SubVersion ~= nil then base.SubVersion elseif version >= 6 then 1 else nil },
{ "Metadata", metadata },
{ "Regions", regions_ },
}), nil
end
return Litematic
+213
View File
@@ -0,0 +1,213 @@
--!strict
-- model/schematic/Mcedit: the MCEdit / WorldEdit .schematic layout (Minecraft before 1.13), from the Minecraft wiki
-- "Schematic file format" page: Width / Height / Length, Blocks + Data (+ WorldEdit's AddBlocks high nibbles, high
-- nibble first), Materials = "Alpha", TileEntities, Entities, WEOffset*, and the SchematicaMapping / BlockIDs name
-- tables of Schematica and MCEdit-Unified. Block ids become state strings through codecs/model/Minecraft
-- (legacyState: wool 14 -> minecraft:red_wool) and back (legacyId; blocks unknown before 1.13 become the legacy block
-- nearest in colour).
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 = {}
local Packed = Mc.Packed
-- read(root, maxCells) -> { Region }, extra | nil, message
function Mcedit.read(root: any, maxCells: number): ({ Common.Region }?, any)
local blocks = root.Blocks
if type(blocks) ~= "buffer" then
return nil, "no Blocks byte array"
end
local function u16(v: any): any
local n = Common.int(v)
return if n and n < 0 then n + 65536 else n
end
local sx, sy, sz = Common.dims(u16(root.Width), u16(root.Height), u16(root.Length), maxCells)
if not sx then
return nil, sy
end
local n = sx * sy :: number * (sz :: number)
if buffer.len(blocks) < n then
return nil, "truncated: Blocks has " .. buffer.len(blocks) .. " bytes for " .. n .. " cells"
end
local data = if type(root.Data) == "buffer" and buffer.len(root.Data) >= n then root.Data else nil
local add = if type(root.AddBlocks) == "buffer" and buffer.len(root.AddBlocks) >= (n + 1) // 2 then root.AddBlocks else nil
-- id -> name tables of Schematica (name -> id) and MCEdit-Unified (id text -> name)
local names: { [number]: string } = {}
if Types.isObject(root.SchematicaMapping) then
for _, k in Types.keys(root.SchematicaMapping) do
local id = Common.int(root.SchematicaMapping[k])
if id then
names[id] = k
end
end
end
if Types.isObject(root.BlockIDs) then
for _, k in Types.keys(root.BlockIDs) do
local id = tonumber(k)
if id and type(root.BlockIDs[k]) == "string" then
names[id] = root.BlockIDs[k]
end
end
end
local function state(id: number, d: number): string
local name = names[id]
if name then
local base = string.match(name, "^minecraft:(.*)$") or (if string.find(name, ":", 1, true) then nil else name)
if base then
local std = table.find(Mc.Legacy.NAMES, base)
if std then
return Mc.legacyState(std - 1, d)
end
end
return Mc.stateString(if string.find(name, ":", 1, true) then name else "minecraft:" .. name, if d ~= 0 then { { "data", tostring(d) } } else nil)
end
return Mc.legacyState(id, d)
end
local slots: { [number]: number } = {}
local states: { string } = {}
local yzx = buffer.create(n * 2)
for i = 0, n - 1 do
local id = buffer.readu8(blocks, i)
if add then
id += Packed.nibble(add, 0, i, true) * 256
end
local d = if data then buffer.readu8(data, i) % 16 else 0
local key = id * 16 + d
local s = slots[key]
if not s then
table.insert(states, state(id, d))
s = #states - 1
slots[key] = s
end
buffer.writeu16(yzx, i * 2, s :: number)
end
local bes = {}
for _, c in Common.list(root.TileEntities) do
local be = Common.blockEntity(c, "flat")
if be then
table.insert(bes, be)
end
end
return {
{
name = nil,
size = { sx, sy, sz },
position = { Common.int(root.WEOffsetX) or 0, Common.int(root.WEOffsetY) or 0, Common.int(root.WEOffsetZ) or 0 },
states = states,
indices = Packed.fromYzx(yzx, sx, sy :: number, sz :: number),
blockEntities = bes,
entities = Common.list(root.Entities),
},
},
{ materials = root.Materials }
end
-- the legacy blocks a colour can become (full blocks of distinct colours)
local CANDIDATES: { { any } }? = nil
local function candidates(): { { any } }
if CANDIDATES then
return CANDIDATES
end
local out = {}
local function add(id: number, d: number)
local c = Mc.color(Mc.legacyState(id, d))
if c then
table.insert(out, { id, d, c })
end
end
for d = 0, 15 do
add(35, d) -- wool
add(159, d) -- stained clay
add(251, d) -- concrete
end
for d = 0, 5 do
add(5, d) -- planks
end
for _, id in { 1, 2, 3, 4, 7, 12, 13, 24, 41, 42, 45, 48, 49, 57, 80, 82, 87, 88, 89, 98, 121, 133, 152, 155, 168, 172, 173, 174, 179, 201, 216 } do
add(id, 0)
end
CANDIDATES = out
return out
end
local function nearest(state: string): (number, number)
local c = Mc.color(state)
if not c then
return 0, 0
end
if c[4] < 200 then
return 20, 0 -- glass
end
local bid, bd, best = 1, 0, math.huge
for _, k in candidates() do
local kc = k[3]
local dist = (kc[1] - c[1]) ^ 2 + (kc[2] - c[2]) ^ 2 + (kc[3] - c[3]) ^ 2
if dist < best then
bid, bd, best = k[1], k[2], dist
end
end
return bid, bd
end
-- write(region, base?) -> the root compound (named "Schematic") | nil, message. base: a decoded root whose other
-- fields are kept
function Mcedit.write(r: Common.Region, base: any): (any, string?)
local sx, sy, sz = r.size[1], r.size[2], r.size[3]
if sx > 65535 or sy > 65535 or sz > 65535 then
return nil, "a .schematic is at most 65535 cells on each axis"
end
local n = sx * sy * sz
local ids, datas = table.create(#r.states), table.create(#r.states)
local high = false
for i, s in r.states do
local id, d = Mc.legacyId(s)
if id == nil then
id, d = nearest(s)
end
ids[i], datas[i] = id, d
if (id :: number) > 255 then
high = true
end
end
local yzx = Packed.toYzx(r.indices, sx, sy, sz)
local blocks, data = buffer.create(n), buffer.create(n)
local add = if high then buffer.create((n + 1) // 2) else nil
for i = 0, n - 1 do
local s = buffer.readu16(yzx, i * 2) + 1
local id = ids[s] or 0
buffer.writeu8(blocks, i, id % 256)
buffer.writeu8(data, i, datas[s] or 0)
if add then
Packed.setNibble(add, 0, i, id // 256, true)
end
end
local tiles = Nbt.list("compound")
for _, be in r.blockEntities do
table.insert(tiles, Common.flatBlockEntity(be, "flat"))
end
local ents = if #r.entities > 0 then r.entities else Nbt.list("compound")
local fields = {
{ "Width", Nbt.short(sx) },
{ "Height", Nbt.short(sy) },
{ "Length", Nbt.short(sz) },
{ "Materials", "Alpha" },
{ "Blocks", blocks },
{ "Data", data },
{ "AddBlocks", add },
{ "Entities", ents },
{ "TileEntities", tiles },
}
local p = r.position
if p[1] ~= 0 or p[2] ~= 0 or p[3] ~= 0 or (type(base) == "table" and base.WEOffsetX ~= nil) then
table.insert(fields, { "WEOffsetX", p[1] })
table.insert(fields, { "WEOffsetY", p[2] })
table.insert(fields, { "WEOffsetZ", p[3] })
end
local root = Common.merge(base, fields, { SchematicaMapping = true, BlockIDs = true, Add = true })
return root, nil
end
return Mcedit
+131
View File
@@ -0,0 +1,131 @@
--!strict
-- model/schematic/Sponge: the Sponge schematic format (.schem: WorldEdit 7+, FAWE, Amulet), from the
-- SpongePowered/Schematic-Specification documents for versions 1, 2 and 3: Width / Height / Length, Offset, the
-- block-state Palette with varint BlockData (v1 / v2) or the Blocks container (v3), block entities (TileEntities /
-- BlockEntities, v3 with Data), Entities, Metadata, DataVersion; biomes are kept as they are.
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 Sponge = {}
local Packed = Mc.Packed
-- read(s, maxCells) -> { Region }, extra | nil, message. s: the Schematic compound (v3: the root's Schematic child)
function Sponge.read(s: any, maxCells: number): ({ Common.Region }?, any)
local version = Common.int(s.Version) or 1
local function u16(v: any): any
local n = Common.int(v)
return if n and n < 0 then n + 65536 else n
end
local sx, sy, sz = Common.dims(u16(s.Width), u16(s.Height), u16(s.Length), maxCells)
if not sx then
return nil, sy
end
local container = if version >= 3 then s.Blocks else s
if version >= 3 and type(container) ~= "table" then
return nil, "no Blocks container"
end
local palette = if version >= 3 then container.Palette else s.Palette
local data = if version >= 3 then container.Data else s.BlockData
if not Types.isObject(palette) then
return nil, "no block palette"
end
if type(data) ~= "buffer" then
return nil, "no block data"
end
local states: { string } = {}
local max = -1
for _, k in Types.keys(palette) do
local i = Common.int(palette[k])
if i == nil or i < 0 or i > 65535 then
return nil, "bad palette index for " .. k
end
states[i + 1] = k
if i > max then
max = i
end
end
for i = 1, max + 1 do
if states[i] == nil then
states[i] = "minecraft:air"
end
end
local n = sx * sy :: number * (sz :: number)
local yzx = buffer.create(n * 2)
local ok, e = Packed.varints(data, 0, buffer.len(data), n, yzx, max + 1)
if not ok then
return nil, e
end
local bes = {}
local raw = if version >= 3 then container.BlockEntities elseif version == 2 then s.BlockEntities else s.TileEntities
for _, c in Common.list(raw) do
local be = Common.blockEntity(c, if version >= 3 then "data" else "pos")
if be then
table.insert(bes, be)
end
end
local off = Common.ints(s.Offset) or { 0, 0, 0 }
return {
{
name = nil,
size = { sx, sy, sz },
position = { off[1] or 0, off[2] or 0, off[3] or 0 },
states = states,
indices = Packed.fromYzx(yzx, sx, sy :: number, sz :: number),
blockEntities = bes,
entities = Common.list(s.Entities),
},
},
{ version = version, dataVersion = Common.int(s.DataVersion), metadata = s.Metadata }
end
-- write(region, version, dataVersion, base?) -> the Schematic compound (v3: the caller wraps it in the root) | nil,
-- message. base: the decoded Schematic compound whose other fields (Metadata, Biomes, ...) are kept
function Sponge.write(r: Common.Region, version: number, dataVersion: number, base: any): (any, string?)
local sx, sy, sz = r.size[1], r.size[2], r.size[3]
if sx > 65535 or sy > 65535 or sz > 65535 then
return nil, "a Sponge schematic is at most 65535 cells on each axis"
end
local n = sx * sy * sz
local states, indices = Common.dedupe(r.states, r.indices, n)
local palette, keys = {}, {}
for i, st in states do
palette[st] = i - 1
keys[i] = st
end
local pal = Types.object(palette, keys)
local data = Packed.toVarints(Packed.toYzx(indices, sx, sy, sz), n)
local bes = Nbt.list("compound")
for _, be in r.blockEntities do
table.insert(bes, Common.flatBlockEntity(be, if version >= 3 then "data" else "pos"))
end
local ents = if #r.entities > 0 then r.entities else nil
local off = Nbt.intArray({ r.position[1], r.position[2], r.position[3] })
local fields: { { any } } = {
{ "Version", version },
{ "DataVersion", if version >= 2 then dataVersion else nil },
{ "Width", Nbt.short(sx) },
{ "Height", Nbt.short(sy) },
{ "Length", Nbt.short(sz) },
{ "Offset", off },
}
if version >= 3 then
local blocksBase = if type(base) == "table" then base.Blocks else nil
table.insert(fields, { "Blocks", Common.merge(blocksBase, { { "Palette", pal }, { "Data", data }, { "BlockEntities", bes } }) })
table.insert(fields, { "Entities", ents })
else
table.insert(fields, { "PaletteMax", #states })
table.insert(fields, { "Palette", pal })
table.insert(fields, { "BlockData", data })
table.insert(fields, { if version == 2 then "BlockEntities" else "TileEntities", bes })
table.insert(fields, { "Entities", if version == 2 then ents else nil })
end
-- the other version's block fields never carry over
local drop = if version >= 3 then { PaletteMax = true, Palette = true, BlockData = true, BlockEntities = true, TileEntities = true }
else { Blocks = true, Biomes = true, TileEntities = version ~= 1, BlockEntities = version == 1 }
return Common.merge(base, fields, drop :: any), nil
end
return Sponge
+309
View File
@@ -0,0 +1,309 @@
--!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
}
-- ------------------------------------------------------------------------------------------------ constants
local DEFAULT_DATA_VERSION = 3953
local LITEMATIC_HINTS = { "Regions", "EnclosingSize", "RegionCount", "TotalVolume", "MinecraftDataVersion" }
-- ------------------------------------------------------------------------------------------------ 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)
for _, h in LITEMATIC_HINTS do
if string.find(head, string.char(0, #h) .. h, 1, true) then
return 1
end
end
return 0
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
return nil, Err.from(extra)
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
+243
View File
@@ -0,0 +1,243 @@
# model/schematic fixtures: schematics written by reference code through nix, with every cell's block state, and our
# encoder's output read back by the same reference code.
# .litematic: Python's litemapy (several regions, a negative size, a 40-state palette), a tile entity added with
# nbtlib; .schem v2: litemapy's Region.to_sponge_nbt (+ a block entity); .schem v1 / v3 and the legacy
# MCEdit .schematic (ids + data, WorldEdit AddBlocks, a SchematicaMapping table): nbtlib, by the specs.
# tests/gen/schematic.luau { cases = { { name, data, variant, version, regions = { { name, min = {x,y,z},
# size = {x,y,z}, cells = "state\n..." (Voxels order: x, then y, then z) or legacy =
# { id*16+data per cell } } }, blockEntities = n, ... } } }
# tests/gen/schematic_ours.luau { [name] = { regions = { { name, min, size, cells } } } }: our encodings
# (tools/fixtures/_schematic_encode.luau) read back by litemapy / nbtlib
import importlib.util, os, pickle, subprocess, sys
INPUTS = ["src/Formats/model/schematic", "src/Formats/codecs/model/Minecraft", "src/Formats/codecs/text/Nbt", "tools/fixtures/_schematic_encode.luau"]
_spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_model_ref.py"))
R = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(R)
COMMON = r'''
import nbtlib, pickle, random, struct, sys, io, gzip, os, tempfile
from nbtlib import Byte, Short, Int, Long, Float, Double, String, List, Compound, ByteArray, IntArray, LongArray
import numpy as np
from litemapy import Schematic, Region, BlockState
def state_of(bs):
# a litemapy BlockState as the state string, properties in the NBT order
t = bs.to_nbt()
props = t.get("Properties")
if props:
return str(t["Name"]) + "[" + ",".join("%s=%s" % (k, str(v)) for k, v in props.items()) + "]"
return str(t["Name"])
def region_cells(reg):
xs, ys, zs = list(reg.range_x()), list(reg.range_y()), list(reg.range_z())
out = []
for z in zs:
for y in ys:
for x in xs:
out.append(state_of(reg[x, y, z]))
return out
def region_info(name, reg):
return {"name": name, "min": [reg.min_schem_x(), reg.min_schem_y(), reg.min_schem_z()],
"size": [abs(reg.width), abs(reg.height), abs(reg.length)], "cells": "\n".join(region_cells(reg))}
def sponge_cells(s):
# Sponge v1 / v2 / v3 compound -> min, size, cells
v = int(s.get("Version", 1))
w, h, l = int(s["Width"]) & 0xffff, int(s["Height"]) & 0xffff, int(s["Length"]) & 0xffff
blocks = s["Blocks"] if v >= 3 else s
pal = blocks["Palette"]
data = bytes(np.asarray(blocks["Data"] if v >= 3 else blocks["BlockData"], dtype=np.int8).tobytes())
names = {int(i): k for k, i in pal.items()}
idx, p = [], 0
while len(idx) < w * h * l:
val, sh = 0, 0
while True:
c = data[p]; p += 1
val |= (c & 0x7f) << sh
sh += 7
if c < 128: break
idx.append(val)
cells = []
for z in range(l):
for y in range(h):
for x in range(w):
cells.append(names[idx[x + z * w + y * w * l]])
off = list(s["Offset"]) if "Offset" in s else [0, 0, 0]
return {"name": "", "min": [int(o) for o in off], "size": [w, h, l], "cells": "\n".join(cells)}
'''
BODY = COMMON + r'''
rng = random.Random(11)
STATES = ["minecraft:air", "minecraft:stone", "minecraft:red_wool", "minecraft:glass", "minecraft:oak_planks",
"minecraft:water[level=0]", "minecraft:grass_block[snowy=false]", "minecraft:oak_log[axis=y]",
"minecraft:oak_stairs[facing=east,half=bottom,shape=straight,waterlogged=false]",
"minecraft:chest[facing=north,type=single,waterlogged=false]", "minecraft:spruce_slab[type=top,waterlogged=false]",
"minecraft:lantern[hanging=true,waterlogged=false]"]
COLOURS = ["white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan",
"purple", "blue", "brown", "green", "red", "black"]
BIG = ["minecraft:%s_%s" % (c, k) for c in COLOURS for k in ("wool", "concrete", "terracotta")]
def bs(s):
if "[" in s:
name, rest = s.split("[", 1)
props = dict(kv.split("=") for kv in rest[:-1].split(","))
return BlockState(name, **props)
return BlockState(s)
def fill(reg, states):
for x in reg.range_x():
for y in reg.range_y():
for z in reg.range_z():
reg[x, y, z] = bs(rng.choice(states))
cases = []
tmp = tempfile.mkdtemp()
# 1. litematic: three regions (one with negative sizes, one with a 40-state palette)
main = Region(0, 0, 0, 6, 5, 4); fill(main, STATES)
neg = Region(10, 2, -3, -4, 3, -5); fill(neg, STATES[:6])
big = Region(-20, 0, 0, 7, 3, 5); fill(big, BIG)
sch = Schematic(name="Test", author="formats-luau", description="fixture", regions={"main": main, "neg": neg, "big": big})
path = os.path.join(tmp, "t.litematic")
sch.save(path)
f = nbtlib.load(path)
# a tile entity, as Litematica stores them (relative to the region's minimum corner)
f["Regions"]["main"]["TileEntities"].append(Compound({"x": Int(1), "y": Int(0), "z": Int(2), "id": String("minecraft:chest"), "Items": List[Compound]([])}))
f.save(path)
data = open(path, "rb").read()
cases.append({"name": "litemapy", "variant": "litematic", "version": 6, "data": data, "blockEntities": 1,
"regions": [region_info(n, r) for n, r in Schematic.load(path).regions.items()]})
# 2. schem v2 from litemapy (+ a block entity)
reg = Region(0, 0, 0, 5, 4, 6); fill(reg, STATES)
sp = reg.to_sponge_nbt(mc_version=3465)
sp["BlockEntities"].append(Compound({"Pos": IntArray([1, 2, 3]), "Id": String("minecraft:chest"), "Items": List[Compound]([])}))
path = os.path.join(tmp, "v2.schem")
sp.save(path, gzipped=True)
data = open(path, "rb").read()
cases.append({"name": "sponge2", "variant": "schem", "version": 2, "data": data, "blockEntities": 1, "regions": [sponge_cells(nbtlib.load(path))]})
# 3. schem v3 / v1 by the spec (nbtlib), a palette past 128 states (two-byte varints)
def varints(idx):
out = bytearray()
for v in idx:
while v >= 128:
out.append((v & 0x7f) | 0x80); v >>= 7
out.append(v)
return bytes(out)
def sponge(version, w, h, l, states, offset):
pal = {s: i for i, s in enumerate(states)}
idx = [rng.randrange(len(states)) for _ in range(w * h * l)]
data = ByteArray(np.frombuffer(varints(idx), dtype=np.int8))
palc = Compound({s: Int(i) for s, i in pal.items()})
if version >= 3:
s = Compound({"Version": Int(3), "DataVersion": Int(3953), "Width": Short(w), "Height": Short(h), "Length": Short(l),
"Offset": IntArray(offset), "Metadata": Compound({"Name": String("v3"), "Date": Long(1700000000000)}),
"Blocks": Compound({"Palette": palc, "Data": data, "BlockEntities": List[Compound]([
Compound({"Pos": IntArray([0, 1, 2]), "Id": String("minecraft:chest"), "Data": Compound({"Items": List[Compound]([])})})])}),
"Biomes": Compound({"Palette": Compound({"minecraft:plains": Int(0)}), "Data": ByteArray([0] * (w * h * l))}),
"Entities": List[Compound]([Compound({"Pos": List[Double]([Double(1.5), Double(0.0), Double(2.5)]), "Id": String("minecraft:pig"), "Data": Compound({})})])})
return nbtlib.File({"Schematic": s}, root_name=""), s
s = Compound({"Version": Int(1), "Width": Short(w), "Height": Short(h), "Length": Short(l), "Offset": IntArray(offset),
"PaletteMax": Int(len(states)), "Palette": palc, "BlockData": data,
"TileEntities": List[Compound]([Compound({"Pos": IntArray([0, 0, 0]), "Id": String("minecraft:chest"), "Items": List[Compound]([])})])})
return nbtlib.File(s, root_name="Schematic"), s
stairs = ["minecraft:oak_stairs[facing=%s,half=%s,shape=%s,waterlogged=false]" % (f_, h_, s_)
for f_ in ("north", "south", "east", "west") for h_ in ("top", "bottom")
for s_ in ("straight", "inner_left", "inner_right", "outer_left", "outer_right")]
for name, version, states, size, off in [("sponge3", 3, ["minecraft:air"] + BIG + stairs + STATES[1:], (9, 7, 8), [-4, 1, 7]),
("sponge1", 1, STATES, (4, 3, 5), [0, 0, 0])]:
f, s = sponge(version, size[0], size[1], size[2], states, off)
path = os.path.join(tmp, name + ".schem")
f.save(path, gzipped=True)
data = open(path, "rb").read()
cases.append({"name": name, "variant": "schem", "version": version, "data": data, "blockEntities": 1, "regions": [sponge_cells(s)]})
# 4. MCEdit .schematic: legacy ids and data values (WorldEdit AddBlocks; a Schematica name table)
LEGACY = [(0, 0), (1, 0), (1, 3), (35, 14), (35, 0), (5, 2), (17, 5), (53, 3), (20, 0), (98, 1), (159, 11), (251, 4), (44, 9), (2, 0)]
for name, ids, add, mapping in [("mcedit", LEGACY, False, False), ("worldedit_add", LEGACY + [(300, 2), (4000, 0)], True, False),
("schematica", LEGACY, False, True)]:
w, h, l = 5, 4, 3
n = w * h * l
cells = [rng.choice(ids) for _ in range(n)] # in file order (x + z*w + y*w*l)
blocks = bytes(c[0] & 0xff for c in cells)
datas = bytes(c[1] for c in cells)
root = Compound({"Width": Short(w), "Height": Short(h), "Length": Short(l), "Materials": String("Alpha"),
"Blocks": ByteArray(np.frombuffer(blocks, dtype=np.int8)), "Data": ByteArray(np.frombuffer(datas, dtype=np.int8)),
"Entities": List[Compound]([]),
"TileEntities": List[Compound]([Compound({"x": Int(1), "y": Int(1), "z": Int(1), "id": String("Chest"), "Items": List[Compound]([])})]),
"WEOffsetX": Int(-2), "WEOffsetY": Int(0), "WEOffsetZ": Int(3)})
if add:
nib = bytearray((n + 1) // 2)
for i, c in enumerate(cells):
hi = c[0] >> 8
nib[i >> 1] |= (hi << 4) if i % 2 == 0 else hi # high nibble first (WorldEdit)
root["AddBlocks"] = ByteArray(np.frombuffer(bytes(nib), dtype=np.int8))
if mapping:
root["SchematicaMapping"] = Compound({"minecraft:stone": Short(1), "minecraft:wool": Short(35), "minecraft:planks": Short(5),
"minecraft:log": Short(17), "minecraft:oak_stairs": Short(53), "minecraft:air": Short(0),
"minecraft:glass": Short(20), "minecraft:stonebrick": Short(98),
"minecraft:stained_hardened_clay": Short(159), "minecraft:concrete": Short(251),
"minecraft:stone_slab": Short(44), "minecraft:grass": Short(2)})
path = os.path.join(tmp, name + ".schematic")
nbtlib.File(root, root_name="Schematic").save(path, gzipped=True)
legacy = []
for z in range(l):
for y in range(h):
for x in range(w):
c = cells[x + z * w + y * w * l]
legacy.append(c[0] * 16 + c[1])
cases.append({"name": name, "variant": "schematic", "version": 0, "data": open(path, "rb").read(), "blockEntities": 1,
"regions": [{"name": "", "min": [-2, 0, 3], "size": [w, h, l], "legacy": legacy}]})
sys.stdout.buffer.write(pickle.dumps(cases, protocol=4))
'''
# our encodings read back: litematic by litemapy, schem v2 by litemapy's from_sponge_nbt, every Sponge version and
# the MCEdit layout by nbtlib
READ_BACK = COMMON + r'''
files = pickle.loads(sys.stdin.buffer.read())
tmp = tempfile.mkdtemp()
out = {}
for name, data in files.items():
path = os.path.join(tmp, name)
open(path, "wb").write(data)
f = nbtlib.load(path)
if name.endswith(".litematic"):
s = Schematic.load(path)
out[name] = {"regions": [region_info(n, r) for n, r in s.regions.items()], "author": s.author, "name": s.name}
elif name.endswith(".schem"):
s = f["Schematic"] if "Schematic" in f and "Version" not in f else f
regs = [sponge_cells(s)]
res = {"regions": regs, "version": int(s["Version"])}
if int(s["Version"]) == 2:
reg, mc = Region.from_sponge_nbt(nbtlib.load(path))
cells = region_cells(reg)
res["litemapy"] = "\n".join(cells)
out[name] = res
else:
w, h, l = int(f["Width"]), int(f["Height"]), int(f["Length"])
blocks = np.asarray(f["Blocks"], dtype=np.uint8)
datas = np.asarray(f["Data"], dtype=np.uint8)
add = np.asarray(f["AddBlocks"], dtype=np.uint8) if "AddBlocks" in f else None
legacy = []
for z in range(l):
for y in range(h):
for x in range(w):
i = x + z * w + y * w * l
bid = int(blocks[i])
if add is not None:
bid |= ((int(add[i >> 1]) >> (4 if i % 2 == 0 else 0)) & 15) << 8
legacy.append(bid * 16 + int(datas[i]))
out[name] = {"regions": [{"name": "", "min": [int(f.get("WEOffsetX", 0)), int(f.get("WEOffsetY", 0)), int(f.get("WEOffsetZ", 0))], "size": [w, h, l], "legacy": legacy}]}
sys.stdout.buffer.write(pickle.dumps(out, protocol=4))
'''
def run(ctx, packages, body, input=None):
try:
return ctx.python(packages, body, input=input)
except subprocess.CalledProcessError as e:
raise RuntimeError("fixture python failed:\n" + e.stderr.decode(errors="replace")[-3000:])
def generate(ctx):
cases = pickle.loads(run(ctx, ["nbtlib", "litemapy", "numpy"], BODY))
ctx.emit("schematic", {"cases": cases})
try:
files = R.luau_encode(ctx, "tools/fixtures/_schematic_encode.luau")
except subprocess.CalledProcessError as e:
raise RuntimeError("our encoder failed:\n" + (e.stderr or b"").decode(errors="replace")[-3000:] + (e.stdout or b"").decode(errors="replace")[-2000:])
ours = pickle.loads(run(ctx, ["nbtlib", "litemapy", "numpy"], READ_BACK, input=pickle.dumps(files)))
ctx.emit("schematic_ours", ours)