def count_leaves_in_overlay_tree(base_name: str) -> float: base = nbt.load('./structure_templates/%s.nbt' % base_name) overlay = nbt.load('./structure_templates/%s_overlay.nbt' % base_name) base_leaves = leaf_ids(base) leaves = set(pos_key(block) for block in base.root['blocks'] if block['state'] in base_leaves) count = len(leaves) for block in overlay.root['blocks']: if block['state'] in base_leaves and pos_key(block) not in leaves: count += 0.5 elif pos_key(block) in leaves: count -= 0.5 return count
def output(self): schem = nbt.load(os.path.join( os.path.dirname(__file__), 'empty_schematic')) out_path = os.path.join(self.output_dir, self.out_schem) os.makedirs(self.output_dir, exist_ok=True) self._packing(schem) self._save_schematic(out_path, schem)
def tree(origin, wood, nameout): f = nbt.load(origin + '.nbt') for block in f.root['palette']: if block['Name'] == 'minecraft:log': block['Name'] = String('tfc:wood/log/' + wood) prop = block['Properties'] block['Properties'] = Compound({ 'small': String('false'), 'placed': String('false'), 'axis': prop['axis'] }) if block['Name'] == 'minecraft:planks': # Planks indicate bark blocks block['Name'] = String('tfc:wood/log/' + wood) block['Properties'] = Compound({ 'small': String('false'), 'placed': String('false'), 'axis': String('none') }) if block['Name'] == 'minecraft:leaves': block['Name'] = String('tfc:wood/leaves/' + wood) block['Properties'] = Compound({'decayable': String('true')}) if not os.path.exists('src/main/resources/assets/tfc/structures/' + wood): os.makedirs('src/main/resources/assets/tfc/structures/' + wood) f.save('src/main/resources/assets/tfc/structures/' + wood + '/' + nameout + '.nbt')
def _update_servers_dat(servers_dat_path, server_name, new_ip): """update IP of server_name in server list with new_ip Args: servers_dat_path (str): File path for MC client's servers.dat. server_name (str): Name of the server within client's server list. new_ip (str): Instance's new IP to update client's server list with. """ servers_dat_nbt = load(servers_dat_path, gzipped=False) for server_list_entry in servers_dat_nbt.root['servers']: if server_name == server_list_entry['name']: server_list_entry['ip'] = String(new_ip) print(f" IP for \"{server_name}\" entry in server list updated.") break # If server_name isn't in client's server list, add it. else: # List type must be "Compound" (defaults to "End" for empty List). if not servers_dat_nbt.root['servers']: servers_dat_nbt.root['servers'] = List[Compound]() servers_dat_nbt.root['servers'].append( Compound({ 'ip': String(new_ip), 'name': String(server_name) })) print(f" \"{server_name}\" entry with instance's IP " "added to server list.") servers_dat_nbt.save(gzipped=False)
def make_tree_structure(template: str, wood: str, dest: Optional[str] = None, wood_dir: Optional[str] = None): if dest is None: dest = template if wood_dir is None: wood_dir = wood f = nbt.load('./structure_templates/%s.nbt' % template) for block in f.root['palette']: if block['Name'] == 'minecraft:oak_log': block['Name'] = StringTag('tfc:wood/log/%s' % wood) block['Properties']['natural'] = StringTag('true') elif block['Name'] == 'minecraft:oak_wood': block['Name'] = StringTag('tfc:wood/wood/%s' % wood) block['Properties']['natural'] = StringTag('true') elif block['Name'] == 'minecraft:oak_leaves': block['Name'] = StringTag('tfc:wood/leaves/%s' % wood) block['Properties']['persistent'] = StringTag('false') else: print('Structure: %s has an invalid block state \'%s\'' % (template, block['Name'])) # Hack the data version, to avoid needing to run DFU on anything f.root['DataVersion'] = IntTag(2730) result_dir = '../src/main/resources/data/tfc/structures/%s/' % wood_dir if not os.path.exists(result_dir): os.makedirs(result_dir) file_name = result_dir + dest + '.nbt' try: if os.path.isfile(file_name): # Load and diff the original file - do not overwrite if source identical to avoid unnecessary git diffs due to gzip inconsistencies. original = nbt.load(file_name) if original == f: Count.SKIPPED += 1 return else: Count.MODIFIED += 1 else: Count.NEW += 1 f.save(result_dir + dest + '.nbt') except: Count.ERRORS += 1
def fruit_tree(ftree): f = nbt.load('structure_templates/fruit_tree_base.nbt') for block in f.root['palette']: if block['Name'] == 'tfc:fruit_trees/branch/peach': block['Name'] = String('tfc:fruit_trees/branch/' + ftree) elif block['Name'] == 'tfc:fruit_trees/leaves/peach': block['Name'] = String('tfc:fruit_trees/leaves/' + ftree) elif block['Name'] == 'tfc:fruit_trees/trunk/peach': block['Name'] = String('tfc:fruit_trees/trunk/' + ftree) if not os.path.exists( 'src/main/resources/assets/tfc/structures/fruit_trees'): os.makedirs('src/main/resources/assets/tfc/structures/fruit_trees') f.save('src/main/resources/assets/tfc/structures/fruit_trees/' + ftree + '.nbt')
def load_level_data(): """Read the `level.dat` file and return the `Data` compound.""" try: level_data = nbt.load(LEVEL_DATA_PATH, gzipped=True).root['Data'] except FileNotFoundError: display_error(f'Couldn\'t find any "{LEVEL_DATA_PATH}" file. Are you ' 'sure that the current directory is a minecraft ' 'world folder?') except Exception: # pylint: disable = broad-except display_error(f'Couldn\'t load level data "{LEVEL_DATA_PATH}".') else: world_version = level_data.get('Version', {'Id': 0, 'Name': 'unknown'}) if MIN_VERSION_ID <= world_version['Id']: return level_data version_name = world_version['Name'] display_error(f'Minecraft version "{version_name}" is not compatible ' 'with endermite.') return None
def verify_center_trunk(prefix: str, count: int): for i in range(1, 1 + count): root = nbt.load('./structure_templates/%s%d.nbt' % (prefix, i)) sx, sy, sz = pos_key(root, 'size') if sx % 2 != 1 or sz % 2 != 1: print('Non-odd dimensions: %d x %d x %d on %s%d' % (sx, sy, sz, prefix, i)) continue center = sx // 2, 0, sz // 2 center_state = None for block in root['blocks']: if pos_key(block) == center: center_state = int(block['state']) break if center_state is None: print('Cannot find center trunk state on %s%d' % (prefix, i)) continue state = str(root['palette'][center_state]['Name']) if state not in ('minecraft:oak_wood', 'minecraft:oak_log'): print('Illegal center state, expected log, got: %s, on %s%d' % (state, prefix, i))
def read(filename, gzipped, byteorder, compact, pretty): nbt_file = nbt.load(filename, gzipped=gzipped, byteorder=byteorder) print( serialize_tag(nbt_file, indent=4 if pretty else None, compact=compact))
def load(cls, path): return cls(nbt.load(path, gzipped=True).root)
def test_file_types(file_path, value): nbt_file = nbt.load(file_path) assert validate_types(nbt_file, value), 'mismatched types'
def test_file_compression(file_path, value): nbt_file = nbt.load(file_path) assert nbt_file.gzipped == value.gzipped
def test_file_loading(file_path, value): nbt_file = nbt.load(file_path) assert nbt_file == value
def count_leaves_in_structure(file_name: str): file = nbt.load('./structure_templates/%s.nbt' % file_name) leaves = leaf_ids(file) return sum(block['state'] in leaves for block in file['blocks'])
def test_tag_bench(benchmark, filename): nbt_tag = nbt.load(f'tests/nbt_files/bench/{filename}').root result = benchmark(write_parse, nbt_tag) assert result == nbt_tag
def structure_file_to_bo3_blocks(structure_file, output_file): structure_nbt = nbt.load(structure_file) bo3_text = '\n'.join(structure_to_bo3_blocks(structure_nbt)) with open(output_file, 'w') as fp: fp.write(bo3_text)
def merge(nbt_data, filename, compressed): nbt_file = nbt.load(filename, gzipped=compressed) nbt_file.merge(nbt_data) nbt_file.save()
def read(filename, compressed): print(nbt.load(filename, gzipped=compressed))
import sys from nbtlib import nbt from nbtlib.tag import * from pprint import pprint spawnPos = [1.0, 73.0, 587.0] spawnDim = 100 levelFileName = sys.argv[1] levelfile = nbt.load(levelFileName) itemdata = levelfile['']['FML']['ItemData'] wands = [] for row, contents in enumerate(itemdata): if ((contents['K'].find('wizardry') >= 0) and (contents['K'].find('wand') >= 0)): wands.append(contents['V']) # # Load the main player data file dataFileName = sys.argv[2] nbtfile = nbt.load(dataFileName) badwandcount = 0 # # Find any wands that have a spell index of -1 and set them to zero for slot, contents in enumerate(nbtfile['']['Inventory']): if ((contents['id'] in wands) and ('selectedSpell' in contents['tag']) and (contents['tag']['selectedSpell'] == -1)): nbtfile['']['Inventory'][slot]['tag']['selectedSpell'] = Int(0) badwandcount += 1
import sys from nbtlib import nbt from nbtlib.tag import * from pprint import pprint spawnPos = [-320.0, 70.0, 448.0] spawnDim = 100 dataFileName = sys.argv[1] # # Load the main player data file nbtfile = nbt.load(dataFileName) # # Set the spawn location and dimensions for i, coord in enumerate(spawnPos): nbtfile['']['Pos'][i] = Double(spawnPos[i]) nbtfile['']['Dimension'] = Int(spawnDim) print("Player successfully moved to spawn.") # # Write the file back out nbtfile.save()
def merge(nbt_data, filename, gzipped, byteorder): nbt_file = nbt.load(filename, gzipped=gzipped, byteorder=byteorder) nbt_file.merge(nbt_data) nbt_file.save()