Пример #1
0
 def add_data_to_tag(self, tag):
     tag.tags.append(TAG_String(name='id', value=self.i_id))
     tag.tags.append(TAG_Short(name='Damage', value=int(self.damage)))
     tag.tags.append(TAG_Byte(name='Count', value=1))
     subtag = TAG_Compound()
     subtag.name = 'tag'
     did_append = False
     if len(self.enchants) > 0:
         enchant = TAG_List(name='ench', type=TAG_Compound)
         for ench in self.enchants:
             enchant.tags.append(ench.getNBTTag())
         subtag.tags.append(enchant)
         did_append = True
     if len(self.attributes) > 0:
         attributes = TAG_List(name='AttributeModifiers', type=TAG_Compound)
         for attribute in self.attributes:
             attributes.tags.append(attribute.getNBTTag())
         subtag.tags.append(attributes)
         did_append = True
     if self.name is not None or len(self.lore) > 0:
         display = TAG_Compound()
         display.name = 'display'
         if self.name is not None:
             display.tags.append(TAG_String(name='Name', value=self.name))
         if len(self.lore) > 0:
             lore_tag = TAG_List(name='Lore', type=TAG_String)
             for lore in self.lore:
                 lore_tag.tags.append(TAG_String(value=lore))
             display.tags.append(lore_tag)
         subtag.tags.append(display)
         did_append = True
     if did_append:
         tag.tags.append(subtag)
Пример #2
0
def generate_level():
    level = NBTFile() # Blank NBT
    level.name = "Data"
    level.tags.extend([
        TAG_Long(name="Time", value=1),
        TAG_Long(name="LastPlayed", value=int(time.time())),
        TAG_Int(name="SpawnX", value=0),
        TAG_Int(name="SpawnY", value=2),
        TAG_Int(name="SpawnZ", value=0),
        TAG_Long(name="SizeOnDisk", value=0),
        TAG_Long(name="RandomSeed", value=random.randrange(1,9999999999)),
        TAG_Int(name="version", value=19132),
        TAG_String(name="LevelName", value="Testing")
    ])
    
    player = TAG_Compound()
    player.name = "Player"
    player.tags.extend([
        TAG_Int(name="Score", value=0),
        TAG_Int(name="Dimension", value=0)
    ])
    inventory = TAG_Compound()
    inventory.name = "Inventory"
    player.tags.append(inventory)
    level.tags.append(player)
    
    return level
Пример #3
0
def pack_nbt(s):
    """
    Pack a native Python data structure into an NBT tag. Only the following
    structures and types are supported:

     * int
     * float
     * str
     * unicode
     * dict

    Additionally, arbitrary iterables are supported.

    Packing is not lossless. In order to avoid data loss, TAG_Long and
    TAG_Double are preferred over the less precise numerical formats.

    Lists and tuples may become dicts on unpacking if they were not homogenous
    during packing, as a side-effect of NBT's format. Nothing can be done
    about this.

    Only strings are supported as keys for dicts and other mapping types. If
    your keys are not strings, they will be coerced. (Resistance is futile.)
    """

    if isinstance(s, int):
        return TAG_Long(s)
    elif isinstance(s, float):
        return TAG_Double(s)
    elif isinstance(s, (str, unicode)):
        return TAG_String(s)
    elif isinstance(s, dict):
        tag = TAG_Compound()
        for k, v in s:
            v = pack_nbt(v)
            v.name = str(k)
            tag.tags.append(v)
        return tag
    elif hasattr(s, "__iter__"):
        # We arrive at a slight quandry. NBT lists must be homogenous, unlike
        # Python lists. NBT compounds work, but require unique names for every
        # entry. On the plus side, this technique should work for arbitrary
        # iterables as well.
        tags = [pack_nbt(i) for i in s]
        t = type(tags[0])
        # If we're homogenous...
        if all(t == type(i) for i in tags):
            tag = TAG_List(type=t)
            tag.tags = tags
        else:
            tag = TAG_Compound()
            for i, item in enumerate(tags):
                item.name = str(i)
            tag.tags = tags
        return tag
    else:
        raise ValueError("Couldn't serialise type %s!" % type(s))
Пример #4
0
 def __init__(self, playerName, xpos, ypos, zpos):
         self.filename = "%s.dat" % (playerName)
         self.player = NBTFile()
         motion = TAG_List(name = "Motion", type = TAG_Double)
         motion.insert(0, TAG_Double(value = 0))
         motion.insert(1, TAG_Double(value = 0))
         motion.insert(2, TAG_Double(value = 0))
         pos = TAG_List(name = "Pos", type = TAG_Double)
         pos.insert(0, TAG_Double(value = xpos))
         pos.insert(1, TAG_Double(value = ypos))
         pos.insert(2, TAG_Double(value = zpos))
         rotation = TAG_List(name = "Rotation", type = TAG_Float)
         rotation.insert(0, TAG_Float(value = 0))
         rotation.insert(1, TAG_Float(value = 0))
         abilities = TAG_Compound()
         abilities.name = "abilities"
         abilities.tags.extend([
                 TAG_Byte(name = "flying", value = 0),
                 TAG_Byte(name = "instabuild", value = 0),
                 TAG_Byte(name = "invulnerable", value = 0),
                 TAG_Byte(name = "mayfly", value = 0)
         ])
         self.player.tags.extend([
                 TAG_Byte(name = "OnGround", value = 1),
                 TAG_Byte(name = "Sleeping", value = 0),
                 TAG_Short(name = "Air", value = 300),
                 TAG_Short(name = "AttackTime", value = 0),
                 TAG_Short(name = "DeathTime", value = 0),
                 TAG_Short(name = "Fire", value = -20),
                 TAG_Short(name = "Health", value = 20),
                 TAG_Short(name = "HurtTime", value = 0),
                 TAG_Short(name = "SleepTimer", value = 0),
                 TAG_Int(name = "Dimension", value = 0),
                 TAG_Int(name = "foodLevel", value = 20),
                 TAG_Int(name = "foodTickTimer", value = 0),
                 TAG_Int(name = "playerGameType", value = 0),
                 TAG_Int(name = "SpawnX", value = xpos),
                 TAG_Int(name = "SpawnY", value = ypos),
                 TAG_Int(name = "SpawnZ", value = zpos),
                 TAG_Int(name = "XpLevel", value = 0),
                 TAG_Int(name = "XpTotal", value = 0),
                 TAG_Float(name = "fallDistance", value = 0),
                 TAG_Float(name = "foodExhaustionLevel", value = 0),
                 TAG_Float(name = "foodSaturationLevel", value = 5),
                 TAG_Float(name = "XpP", value = 0),
                 TAG_List(name = "Inventory", type = TAG_Compound),
                 motion,
                 pos,
                 rotation,
                 abilities
         ])
Пример #5
0
def check_version_leveldat(
    root_tag: nbt.TAG_Compound, _min: int = None, _max: int = None
) -> bool:
    """
    Check the Version tag from the provided level.dat NBT structure

    :param root_tag: the root level.dat tag
    :param _min: The lowest acceptable value (optional)
    :param _max: The highest acceptable value (optional)
    :return: Whether the version tag falls in the correct range
    """

    version_found: int = root_tag.get("Data", nbt.TAG_Compound()).get(
        "Version", nbt.TAG_Compound()
    ).get("Id", nbt.TAG_Int(-1)).value

    min_qualifies: bool = True
    if _min is not None:
        min_qualifies = version_found >= _min

    max_qualifies: bool = True
    if _max is not None:
        max_qualifies = version_found <= _max

    if __debug__:
        min_text: str = f"{min} <= " if _min is not None else ""
        max_text: str = f" <= {max}" if _max is not None else ""
        print(f"Checking {min_text}{version_found}{max_text}")

    return min_qualifies and max_qualifies
Пример #6
0
 def add_data_to_tag(self, tag):
     tag.tags.append(
         TAG_Short(name='SpawnCount', value=int(self.spawn_count)))
     tag.tags.append(
         TAG_Short(name='SpawnRange', value=int(self.spawn_range)))
     tag.tags.append(TAG_Short(name='Delay', value=int(self.delay)))
     tag.tags.append(
         TAG_Short(name='MinSpawnDelay', value=int(self.min_spawn_delay)))
     tag.tags.append(
         TAG_Short(name='MaxSpawnDelay', value=int(self.max_spawn_delay)))
     if self.required_player_range is not None:
         tag.tags.append(
             TAG_Short(name='RequiredPlayerRange',
                       value=int(self.required_player_range)))
     if self.max_nearby_entities is not None:
         tag.tags.append(
             TAG_Short(name='MaxNearbyEntities',
                       value=int(self.max_nearby_entities)))
     if len(self.spawn_potentials) > 0:
         potentials_subtag = TAG_List(name="SpawnPotentials",
                                      type=TAG_Compound)
         for spawn_potential in self.spawn_potentials:
             pot_tag = TAG_Compound()
             pot_tag.tags.append(
                 TAG_Int(name="Weight", value=int(spawn_potential.weight)))
             mob_tag = spawn_potential.mob.getNBTTag()
             mob_tag.name = 'Entity'
             pot_tag.tags.append(mob_tag)
             potentials_subtag.tags.append(pot_tag)
         tag.tags.append(potentials_subtag)
Пример #7
0
 def getNBTTag(self):
     tag = TAG_Compound()
     tag.tags.append(TAG_Byte(name="id", value=int(self.effect_id)))
     tag.tags.append(TAG_Byte(name="Amplifier", value=int(self.amplifier)))
     tag.tags.append(TAG_Int(name="Duration", value=int(self.duration)))
     tag.tags.append(TAG_Byte(name="Ambient", value=int(self.ambient)))
     tag.tags.append(
         TAG_Byte(name="ShowParticles", value=int(self.show_particles)))
     return tag
Пример #8
0
def pack_nbt(s):
    """
    Pack a native Python data structure into an NBT tag. Only the following
    structures and types are supported:

     * int
     * float
     * str
     * unicode
     * dict

    Additionally, arbitrary iterables are supported.

    Packing is not lossless. In order to avoid data loss, TAG_Long and
    TAG_Double are preferred over the less precise numerical formats.

    Lists and tuples may become dicts on unpacking if they were not homogenous
    during packing, as a side-effect of NBT's format. Nothing can be done
    about this.

    Only strings are supported as keys for dicts and other mapping types. If
    your keys are not strings, they will be coerced. (Resistance is futile.)
    """

    if isinstance(s, int):
        return TAG_Long(s)
    elif isinstance(s, float):
        return TAG_Double(s)
    elif isinstance(s, (str, unicode)):
        return TAG_String(s)
    elif isinstance(s, dict):
        tag = TAG_Compound()
        for k, v in s:
            v = pack_nbt(v)
            v.name = str(k)
            tag.tags.append(v)
        return tag
    elif hasattr(s, "__iter__"):
        # We arrive at a slight quandry. NBT lists must be homogenous, unlike
        # Python lists. NBT compounds work, but require unique names for every
        # entry. On the plus side, this technique should work for arbitrary
        # iterables as well.
        tags = [pack_nbt(i) for i in s]
        t = type(tags[0])
        # If we're homogenous...
        if all(t == type(i) for i in tags):
            tag = TAG_List(type=t)
            tag.tags = tags
        else:
            tag = TAG_Compound()
            for i, item in enumerate(tags):
                item.name = str(i)
            tag.tags = tags
        return tag
    else:
        raise ValueError("Couldn't serialise type %s!" % type(s))
Пример #9
0
 def getNBTTag(self):
     tag = TAG_Compound()
     tag.tags.append(
         TAG_String(name="AttributeName", value=self.attribute_id))
     tag.tags.append(TAG_String(name="Name", value=self.attribute_id))
     tag.tags.append(TAG_Double(name="Amount", value=self.value))
     tag.tags.append(TAG_Int(name="Operation", value=int(self.op_choice)))
     tag.tags.append(TAG_Long(name="UUIDLeast", value=self.low))
     tag.tags.append(TAG_Long(name="UUIDMost", value=self.high))
     if self.slot is not None:
         tag.tags.append(TAG_String(name="Slot", value=self.slot))
     return tag
Пример #10
0
def generate_level():
    level = NBTFile()  # Blank NBT
    level.name = "Data"
    level.tags.extend([
        TAG_Long(name="Time", value=1),
        TAG_Long(name="LastPlayed", value=int(time.time())),
        TAG_Int(name="SpawnX", value=0),
        TAG_Int(name="SpawnY", value=2),
        TAG_Int(name="SpawnZ", value=0),
        TAG_Long(name="SizeOnDisk", value=0),
        TAG_Long(name="RandomSeed", value=random.randrange(1, 9999999999)),
        TAG_Int(name="version", value=19132),
        TAG_String(name="LevelName", value="Testing")
    ])

    player = TAG_Compound()
    player.name = "Player"
    player.tags.extend(
        [TAG_Int(name="Score", value=0),
         TAG_Int(name="Dimension", value=0)])
    inventory = TAG_Compound()
    inventory.name = "Inventory"
    player.tags.append(inventory)
    level.tags.append(player)

    return level
Пример #11
0
 def add_data_to_tag(self, tag):
     tag.tags.append(TAG_String(name='id', value=self.i_id))
     tag.tags.append(TAG_Short(name='Damage', value=int(self.damage)))
     tag.tags.append(TAG_Byte(name='Count', value=1))
     subtag = TAG_Compound()
     subtag.name = 'tag'
     did_append = False
     if len(self.enchants) > 0:
         enchant = TAG_List(name='ench', type=TAG_Compound)
         for ench in self.enchants:
             enchant.tags.append(ench.getNBTTag())
         subtag.tags.append(enchant)
         did_append = True
     if len(self.attributes) > 0:
         attributes = TAG_List(name='AttributeModifiers', type=TAG_Compound)
         for attribute in self.attributes:
             attributes.tags.append(attribute.getNBTTag())
         subtag.tags.append(attributes)
         did_append = True
     if self.name is not None or len(self.lore) > 0:
         display = TAG_Compound()
         display.name = 'display'
         if self.name is not None:
             display.tags.append(TAG_String(name='Name', value=self.name))
         if len(self.lore) > 0:
             lore_tag = TAG_List(name='Lore', type=TAG_String)
             for lore in self.lore:
                 lore_tag.tags.append(TAG_String(value=lore))
             display.tags.append(lore_tag)
         subtag.tags.append(display)
         did_append = True
     if did_append:
         tag.tags.append(subtag)
Пример #12
0
    def from_palette(cls, tag: nbt.TAG_Compound):
        """
        Creates a new Block from the tag format on Section.Palette

        Parameters
        ----------
        tag
            Raw tag from a section's palette
        """
        name = tag['Name'].value
        properties = tag.get('Properties')
        if properties:
            properties = dict(properties)
        return cls.from_name(name, properties=properties)
Пример #13
0
 def getNBTTag(self):
     tag = TAG_Compound()
     self.add_data_to_tag(tag)
     return tag
Пример #14
0
    def value(self):
        if self.type_ == list:
            tag = TAG_Compound(self.name)
            tag.tags = [x.value for x in self._value]
            return tag

        if self.type_ == NBTFile:
            x = NBTFile()
            x.name = self.name
            x.tags = [x.value for x in self._value]
            return x

        if self.type_ == TAG_Compound:
            tag = TAG_Compound(name=self.name)
            tag.tags = [x.value for x in self._value]
            tag.name = self.name
            return tag

        if self.type_ == TAG_Int_Array:
            tag = TAG_Int_Array(name=self.name)
            tag.value = self._value
            return tag

        if self.type_ == TAG_List:
            tag = TAG_List(type=self.extra, name=self.name)
            tag.tags = [x.value for x in self._value]
            tag.name = self.name
            return tag

        return self.type_(value=self._value, name=self.name)
Пример #15
0
 def process_entity(self, entity, randomitems):
         slot = 0
         updated = False
         items = items_from_nbt(entity["Items"])
         if sum(items.values()) == 0:
                 print("empty chest found")
                 itemlist = TAG_List(type=TAG_Compound)
                 for randomitem in randomitems:
                         if slot < 27:
                                 if random.uniform(0,100) < float(randomitem[3]):
                                         item = TAG_Compound()
                                         try:
                                                 quantity = int(randomitem[2])
                                         except ValueError:
                                                 try:
                                                         lowrand, highrand = randomitem[2].split('-')
                                                         quantity = random.randrange(int(lowrand), int(highrand) + 1)
                                                 except ValueError:
                                                         print("ERROR: Invalid quantity range.  Defaulting to 1.")
                                                         line = ''
                                                         for section in randomitem:
                                                                 line += ' ' + section
                                                         print(line)
                                                         quantity = 1
                                         if quantity > 127:
                                                 quantity = 127
                                         elif quantity < 1:
                                                 quantity = 1
                                         item.tags.extend([
                                                 TAG_Byte(name="Count", value=quantity),
                                                 TAG_Byte(name="Slot", value=slot),
                                                 TAG_Short(name="Damage", value=int(randomitem[1])),
                                                 TAG_Short(name="id", value=int(randomitem[0]))
                                         ])
                                         if len(randomitem) > 4:
                                                 enchants = TAG_List(name="ench", type=TAG_Compound)
                                                 count = 4
                                                 try:
                                                         while len(randomitem) > count:
                                                                 enchant = TAG_Compound()
                                                                 enchant.tags.extend([
                                                                         TAG_Short(name="id", value=int(randomitem[count])),
                                                                         TAG_Short(name="lvl", value=int(randomitem[count+1]))
                                                                 ])
                                                                 enchants.insert((count-4)/2,enchant)
                                                                 count += 2
                                                         tag = TAG_Compound()
                                                         tag.tags.extend([enchants])
                                                         tag.name = "tag"
                                                         item.tags.extend([tag])
                                                 except IndexError:
                                                         print("ERROR: invalid enchant data")
                                                         line = ''
                                                         for section in randomitem:
                                                                 line += ' ' + section
                                                         print(line)
                                         itemlist.insert(slot,item)
                                         slot += 1
                                         updated = True
                 if updated:
                         entity["Items"] = itemlist
         return updated
Пример #16
0
    def add_data_to_tag(self, tag):
        tag.tags.append(TAG_String(name='id', value=self.mob_id))
        tag.tags.append(TAG_Float(name='Health', value=self.health))
        tag.tags.append(TAG_Byte(name="Glowing", value=int(self.glowing)))
        tag.tags.append(TAG_Byte(name="Silent", value=int(self.silent)))
        tag.tags.append(
            TAG_Byte(name="LeftHanded", value=int(self.left_handed)))
        tag.tags.append(
            TAG_Byte(name="CanPickUpLoot", value=int(self.can_pickup_loot)))
        tag.tags.append(
            TAG_Byte(name="CustomNameVisible",
                     value=int(self.custom_name_visible)))
        tag.tags.append(
            TAG_Float(name="AbsorptionAmount", value=self.absorbtion_amount))
        tag.tags.append(TAG_Short(name='Fire', value=int(self.fire_ticks)))
        if self.custom_name is not None:
            tag.tags.append(
                TAG_String(name='CustomName', value=self.custom_name))
        if len(self.attributes) > 0:
            attribute_subtag = TAG_List(name="Attributes", type=TAG_Compound)
            for attribute in self.attributes:
                attribute_subtag.tags.append(attribute.getNBTTag())
            tag.tags.append(attribute_subtag)
        if len(self.effects) > 0:
            effects_subtag = TAG_List(name="ActiveEffects", type=TAG_Compound)
            for effect in self.effects:
                effects_subtag.tags.append(effect.getNBTTag())
            tag.tags.append(effects_subtag)
        if len(self.passengers) > 0:
            passenger_subtag = TAG_List(name="Passengers", type=TAG_Compound)
            for passenger in self.passengers:
                passenger_subtag.tags.append(passenger.getNBTTag())
            tag.tags.append(passenger_subtag)
        if has_value_not_none(self.hand_items):
            hand_items_subtag = TAG_List(name='HandItems', type=TAG_Compound)
            if self.hand_items['MainHand'] is not None:
                hand_items_subtag.append(
                    self.hand_items['MainHand'].getNBTTag())
            else:
                hand_items_subtag.append(TAG_Compound())
            if self.hand_items['OffHand'] is not None:
                hand_items_subtag.append(
                    self.hand_items['OffHand'].getNBTTag())
            else:
                hand_items_subtag.append(TAG_Compound())
            hand_drops = TAG_List(name="HandDropChances", type=TAG_Float)
            hand_drops.append(
                TAG_Float(value=self.hand_drop_chances['MainHand']))
            hand_drops.append(
                TAG_Float(value=self.hand_drop_chances['OffHand']))
            tag.tags.append(hand_items_subtag)
            tag.tags.append(hand_drops)

        if has_value_not_none(self.armor_items):
            armor_items_subtag = TAG_List(name='ArmorItems', type=TAG_Compound)
            if self.armor_items['Feet'] is not None:
                armor_items_subtag.append(self.armor_items['Feet'].getNBTTag())
            else:
                armor_items_subtag.append(TAG_Compound())
            if self.armor_items['Legs'] is not None:
                armor_items_subtag.append(self.armor_items['Legs'].getNBTTag())
            else:
                armor_items_subtag.append(TAG_Compound())
            if self.armor_items['Chest'] is not None:
                armor_items_subtag.append(
                    self.armor_items['Chest'].getNBTTag())
            else:
                armor_items_subtag.append(TAG_Compound())
            if self.armor_items['Head'] is not None:
                armor_items_subtag.append(self.armor_items['Head'].getNBTTag())
            else:
                armor_items_subtag.append(TAG_Compound())
            armor_drops = TAG_List(name="ArmorDropChances", type=TAG_Float)
            armor_drops.append(
                TAG_Float(value=self.armor_drop_chances['Feet']))
            armor_drops.append(
                TAG_Float(value=self.armor_drop_chances['Legs']))
            armor_drops.append(
                TAG_Float(value=self.armor_drop_chances['Chest']))
            armor_drops.append(
                TAG_Float(value=self.armor_drop_chances['Head']))
            tag.tags.append(armor_items_subtag)
            tag.tags.append(armor_drops)
        for additional in self.additional_settings:
            option = self.additional_settings[additional]
            tag.tags.append(option.getNBTTag())
Пример #17
0
 def getNBTTag(self):
     tag = TAG_Compound()
     tag.tags.append(TAG_Short(name="id", value=int(self.e_id)))
     tag.tags.append(TAG_Short(name="lvl", value=int(self.level)))
     return tag