def from_arguments(arg_dict: dict) -> LevelFile: """ Builds an nbt level.dat file from a template with arguments. :param arg_dict: The dictionary containing the values for a data schema. :return: The created nbt file object. """ default_data = get_template_dict() default_data.update(arg_dict) # Why Mojang? default_data["DataVersion"] = default_data["Version"]["Id"] level_file = LevelFile(parse_nbt("{'':{Data:{}}}")) level_file.data = LevelDataSchema(parse_nbt(json.dumps(default_data))) return level_file
async def nbt(self, ctx: Context, nbtstring: str, schemastr: str = None): try: nbtobj = nbtlib.parse_nbt(nbtstring) if schemastr in schemas.entities.MAP: schema = schemas.entities.MAP[schemastr] try: schema(nbtobj) except cogbot.extensions.nbt.errors.SchemaValidationError as e: await self.bot.add_reaction(ctx.message, u'β') await self.bot.send_message(ctx.message.channel, f'Invalid schema: {str(e)}') return elif schemastr: await self.bot.add_reaction(ctx.message, u'β') await self.bot.send_message(ctx.message.channel, f'Unknown schema `{schemastr}`') return await self.bot.add_reaction(ctx.message, u'β ') except ValueError as e: await self.bot.add_reaction(ctx.message, u'β') await self.bot.send_message(ctx.message.channel, f'Invalid NBT: {str(e)}') except: log.exception( 'An unexpected error occurred while parsing NBT: {}'.format( nbtstring)) await self.bot.add_reaction(ctx.message, u'π©')
def set_nbt_list(nbt, name, pattern='', data=None, parse=False): if data is None: data = [] content = [ parse_nbt(pattern.format(*value)) if parse else pattern.format(*value) for value in data[0:] ] nbt[name] = List[Compound if parse else String](content)
def biglist(): return parse_nbt("""[ [{a: [{value: 0}, {value: 1, thing: 42}], flag: 1, first: 99}], [{spam: {egg: [{foo: 0}, {foo: 2}], checked: 1b}}, {spam: {egg: [{foo: 7}]}}], [{a: [{value: 1}, {value: 2, thing: 42}]}, {a: [], flag: 1}], [{a: [{value: 3, thing: 42}], flag: 1}], [{spam: {egg: [{foo: 1}], checked: 1b}}], [{spam: {egg: [{foo: 2}]}}, {spam: {egg: [{foo: 9}, {foo: 5}], checked: 1b}}] ]""")
def compound_literal(literal): try: nbt_data = parse_nbt(literal) except InvalidLiteral as exc: raise ArgumentTypeError(exc) from exc else: if not isinstance(nbt_data, Compound): raise ArgumentTypeError('The root nbt tag must be a compound tag') return nbt_data
def setblock(self, coordinates: tuple, block_id: str, block_state: str = None, tile_entity_nbt: str = None): block_identifier = block_id, block_state if block_identifier not in self._palette: self._palette[block_identifier] = len(self._palette) x, y, z = coordinates block = self._blocks[x][y][z] = nbt.Compound() block["state"] = nbt.Int(self._palette[block_identifier]) if tile_entity_nbt is not None: block["nbt"] = nbt.parse_nbt(tile_entity_nbt)
def summon(self, coordinates: tuple, entity_id: str, entity_nbt: str = None): entity = nbt.Compound() if entity_nbt is None: entity["nbt"] = nbt.Compound() else: entity["nbt"] = nbt.parse_nbt(entity_nbt) entity["nbt"]["id"] = nbt.String(entity_id) entity["blockPos"] = nbt.List[nbt.Int]([int(i) for i in coordinates]) entity["pos"] = nbt.List[nbt.Double](list(coordinates)) self._entities.append(entity)
def __get_palette(self): values = [None] * len(self._palette) for block_identifier, index in self._palette.items(): compound = nbt.Compound() compound["Name"] = nbt.String(block_identifier[0]) if block_identifier[1] is not None: try: compound["Properties"] = nbt.parse_nbt(block_identifier[1]) except Exception as err: raise ValueError( f"The following error occurred when parsing the nbt literal {block_identifier[1]}: {err}" ) values[index] = compound palette = nbt.List[nbt.Compound](values) return palette
# Minecraft 1.12.2 NBT files. import nbtlib import sys if len(sys.argv) != 2: print(f'usage: {sys.argv[0]} <file>') sys.exit(1) palette_1_12_2 = [] with open('palette-1.12.2.txt') as f: for line in f.readlines(): line = line.strip() if len(line) == 0 or line[0] == '#': continue palette_1_12_2.append(nbtlib.parse_nbt(line)) palette_1_16_5 = [] with open('palette-1.16.5.txt') as f: for line in f.readlines(): line = line.strip() if len(line) == 0 or line[0] == '#': continue palette_1_16_5.append(nbtlib.parse_nbt(line)) assert len(palette_1_12_2) == len(palette_1_16_5) with nbtlib.load(sys.argv[1]) as f: palette = f.root['palette'] for i in range(len(palette)): if palette[i] in palette_1_16_5:
def add_tag(self, tag): self.root["structure"]["entities"][0]["Item"]["tag"] = parse_nbt(tag)
def test_literal_parsing(literal, expected_tag): assert parse_nbt(literal) == expected_tag
def readBox(name): return nbtlib.parse_nbt(open(f"{name}.snbt", 'r').read())
def test_parsing_literal_tag_value(nbt_data): assert str(parse_nbt(str(nbt_data))) == str(nbt_data)
def test_parsing_invalid_literal(literal): with pytest.raises(InvalidLiteral): parse_nbt(literal)
def test_tag_literal_value(literal, expected_tag): assert parse_nbt(literal).snbt() == expected_tag.snbt()
def test_tag_literal_value(literal, expected_tag): assert str(parse_nbt(literal)) == str(expected_tag)
def test_path_set(biglist, path, value, select, results): biglist[Path(path)] = parse_nbt(value) assert biglist.get_all(Path(select)) == results
def add_tag(self, tag): self.root["structure"]["entities"][0].update(parse_nbt(tag))
def test_parsing_literal_tag_value(nbt_data): assert parse_nbt(nbt_data.snbt()).snbt() == nbt_data.snbt()
def singlelayer2litematic(weights, layer_name='sample_layer', verbose=False): if isinstance(weights, torch.Tensor): weights = weights.cpu().numpy() if len(weights.shape) == 4: # conv layers c2, c1, h, w = weights.shape weights = np.transpose(weights.reshape( c2, c1, h * w)) # stretch conv filter vertically elif len(weights.shape) == 2: # fully connected layer c2, c1 = weights.shape weights = np.transpose(weights.reshape(c2, c1, 1)) else: raise ValueError( 'Invalid number of dimensions for the weights passed. Expects either 2 or 4 dimensions.' ) sizeY, sizeZ, sizeX = weights.shape sizeLayer = sizeZ * sizeX bits = ['' for _ in range(sizeX * sizeY * sizeZ)] zero = '00' pos = '01' neg = '10' total_blocks = 0 for y in range(sizeY): for z in range(sizeZ): for x in range(sizeX): index = y * sizeLayer + z * sizeX + x if weights[y][z][x] == 0: bits[index] = zero elif weights[y][z][x] > 0: bits[index] = pos total_blocks += 1 else: bits[index] = neg total_blocks += 1 block_states = '[L; ' for i in range(0, len(bits), 32): bit_string = '' for j in range(32): if (i + j) >= len(bits): bit_string = (32 - j) * '00' + bit_string assert len(bit_string) == 64 break else: bit_string = bits[i + j] + bit_string num = string2signedint(bit_string) if verbose: print(num.bit_length(), num) print(len(bit_string), bit_string) print(64 * '-') assert num.bit_length() <= len(bit_string) - 1 block_states += str(num) + 'L, ' block_states = block_states[:-2] + ']' mod_time = int( time.time()) * 1000 # litematica apparently reads nanoseconds litematica_nbt_data = serialized_tag.format(enc_x=sizeX, enc_y=sizeY, enc_z=sizeZ, author=author, time=mod_time, total_volume=sizeX * sizeY * sizeZ, total_blocks=total_blocks, pos_x=0, pos_y=0, pos_z=0, metadata_name=layer_name, size_x=sizeX, size_y=sizeY, size_z=sizeZ, pos_block=pos_block, neg_block=neg_block, block_states=block_states) if verbose: print(litematica_nbt_data) data = parse_nbt(litematica_nbt_data) file_name = global_nn_name + '.' + layer_name save_path = global_save_dict + '/' + file_name + '.litematic' File(data).save(save_path, gzipped=True) print('Litematica scheamtic generated at : {}'.format(save_path))
class Structure(_Structure): def __init__(self): self["palette"]=[] self["blocks"]=[] self["size"]=[1]*3 super().__init__() def add_block(self,id,pos,state={},nbt=None): if (pal:={"Name":id,"Properties":state}) in self["palette"]: ind=self["palette"].index(pal) else: self["palette"].append(pal) ind=len(self["palette"])-1 block_data={"pos":pos,"state":ind} if nbt is not None: block_data["nbt"]=nbtlib.parse_nbt(nbt) self["blocks"].append(block_data) def final(self,filename): return nbtlib.File({"":self},gzipped=True).save(filename=filename) del _Structure #δΈι’ζ―δ½Ώη¨ηι¨εδΊ x=Structure() import math for i in range(-100,100): for j in range(-100,100): x.add_block("stone",[i,50*math.sin(0.1*math.dist((0,0),(i,j))),j])