Created
January 31, 2025 22:08
-
-
Save Edouard127/7e42dc715c3cd18b2bebef3211f600cc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun StructureTemplate.readLitematicaOrException( | |
lookup: RegistryEntryLookup<Block>, | |
nbt: NbtCompound, | |
): Throwable? { | |
val version = nbt.getInt("MinecraftDataVersion") | |
val metadata = nbt.getCompound("Metadata") | |
val author = metadata.getString("Author") | |
val size = metadata.getVector("EnclosingSize") | |
val newPalette = NbtList() | |
val newBlocks = NbtList() | |
val regions = nbt.getCompound("Regions") | |
regions.keys.map { regions.getCompound(it) } | |
.forEach { | |
val regionSize = it.getVector("Size") | |
val xSizeAbs = abs(regionSize.x) | |
val zSizeAbs = abs(regionSize.z) | |
// The litematic's block state palette is the same as nbt | |
newPalette.addAll(it.getList("BlockStatePalette", 10)) | |
val palette = it.getLongArray("BlockStates") | |
val bits = max(2.0, ceil(log2(palette.size.toDouble()))).floorToInt() | |
// Convert the long array to byte array | |
val buffer = ByteBuffer.allocate(palette.size * Long.SIZE_BYTES) | |
palette.forEach { states -> buffer.putLong(states) } | |
var blockIndex = 0 | |
VarIntIterator(buffer.array(), bitsPerEntry = bits) | |
.forEach { blockId -> | |
val blockpos = positionFromIndex(xSizeAbs, zSizeAbs, blockIndex++) | |
newBlocks.add(NbtCompound().apply { | |
putIntList("pos", blockpos.x, blockpos.y, blockpos.z) | |
putInt("state", blockId) | |
}) | |
} | |
} | |
// Construct a structure compatible nbt compound | |
nbt.putInt("DataVersion", version) | |
nbt.putIntList("size", size.x, size.y, size.z) | |
nbt.put("palette", newPalette) | |
nbt.put("blocks", newBlocks) | |
nbt.putString("author", author) | |
// Fix the data for future versions | |
DataFixTypes.STRUCTURE.update(mc.dataFixer, nbt, version) | |
// Use the StructureTemplate NBT read utils in order to construct the template | |
return readNbtOrException(lookup, nbt) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment