twoolie / NBT

Python Parser/Writer for the NBT file format, and it's container the RegionFile.
MIT License
361 stars 74 forks source link

Save mca nbt #142

Closed Mowstyl closed 4 years ago

Mowstyl commented 4 years ago

I'm trying to read a region file (.mca), edit a certain NBT Tag value and save it, but I can't find a way to save the NBT data back in the .mca file. Is there any way to do it or is it not supported? If the answer is no, do you intend to add it soon? I think it would be useful, I haven't seen any other library that lets you do that. Thanks.

macfreek commented 4 years ago

Use nbt.Region.write_chunk().

Go to the world folder you like to edit, make a backup, and start Python:

cd ~/Library/Application\ Support/minecraft/saves
# backups, backups, backups
cp -rp MyWorld MyWorld-backup
pip install nbt
python

In the Python shell:

>>> import nbt
>>> world = nbt.world.AnvilWorldFolder('MyWorld')
>>> region = world.get_region(0,0)   # Edits r.0.0.mca
>>> chunk = region.get_chunk(12,18)
>>> print(chunk.pretty_tree())
NBTFile: {2 Entries}
{
    TAG_Compound('Level'): {15 Entries}
    {
        TAG_String('Status'): full
        TAG_Int('zPos'): 18
        TAG_Long('LastUpdate'): 2792760
...
...
...
        }
        TAG_List('LiquidTicks'): [0 _TAG_End(s)]
    }
    TAG_Int('DataVersion'): 1976
}
>>> for entity in chunk['Level']['Entities']:
...    print(entity['id'])
...
minecraft:bat
minecraft:bat
minecraft:sheep
>>> # bat-freeze!
>>> chunk['Level']['Entities'][0]['Motion'][0].value
-0.0009232317763660015
>>> chunk['Level']['Entities'][0]['Motion'][0].value = 0.0
>>> chunk['Level']['Entities'][0]['Motion'][1].value = 0.0
>>> chunk['Level']['Entities'][0]['Motion'][2].value = 0.0
>>> # I prefer my sheeps cyan dyed
>>> chunk['Level']['Entities'][2]['Color'].value = 3
>>> # Now, save to file
>>> region.write_chunk(12,18,chunk)

For information about the NBT structure, see e.g. https://minecraft.gamepedia.com/Chunk_format.

Make sure Minecraft is not running (or at least accessing the same file) while you are editing it.

Mowstyl commented 4 years ago

It works, thank you for your quick answer. Great library!