Формат NBT (от англ. Named Binary Tag — «именованный двоичный тег») используется Minecraft в различных файлах для хранения данных. Формат описан Нотчем в очень краткой спецификации. Формат разработан для хранения данных в структуре-дереве, состоящей из различных тегов. У каждого тега есть идентификатор и название. Оригинальная известная версия NBT, 19132, была введена в Beta 1.3, и с тех пор была обновлена до 19133 вместе с Anvil; в этом обновлении был добавлен тег для массива целочисленных переменных. Формат NBT был ещё в Indev и использовал теги с 0 по 10.
Содержание
Определение тега [ править | править код ]
Тег — отдельный элемент дерева данных. Первый байт в теге — это тип тега (также называемый идентификатором или ID), затем 2 байта хранят длину названия, затем название в виде строки в формате UTF-8 (следует отметить, что TAG_End не имеет названия и не включает дополнительные 2 байта; предполагается, что название пустое). Названия тегов могут содержать пробелы, хотя сам Minecraft не имеет таких тегов. Наконец, следующие байты — содержимое тега, зависящее от типа тега. Таблица ниже описывает 12 известных тегов в версии NBT 19133:
Списки и составные теги могут быть вложены. Следует отметить, что в списке списков подсписки могут иметь разные типы элементов.
Формат файлов [ править | править код ]
Файл NBT — это сжатый GZip составной тег, включающий название и тип. Некоторые такие файлы, используемые Minecraft, не являются сжатыми GZip, хотя в большинстве случаев спецификация Нотча, предписывающая сжатие, соблюдается. В Xbox 360 издании чанки сжимаются XMemCompress, разновидностью алгоритма сжатия LZX. Заголовка, указывающего версию или какую-либо иную информацию, в файлах нет, версия указана только в файле level.dat.
Использование в Minecraft [ править | править код ]
Использование формата NBT в Minecraft местами является странным. В некоторых случаях пустые списки могут быть представлены списками байтов (или тегов End в более новых версиях Minecraft), а не списками правильного типа. К тому же, каждый корневой тег имеет пустое название и включает только один составной тег с самими данными и названием. Например:
Ещё одна заметная странность — это то, что хотя оригинальная спецификация Нотча допускает пробелы в названиях тегов, и приведённый в ней пример использует это, в Minecraft нет файлов с пробелами в тегах. Также использование прописных букв в названиях тегов непостоянно: где-то с прописной буквы пишется каждое слово, где-то — каждое, кроме первого, а где-то используются только строчные буквы.
Область применения [ править | править код ]
Программное обеспечение [ править | править код ]
Mojang предоставила экземпляры классов Java для работы с NBT, предназначенные для использования разработчиками, как часть исходного кода для преобразователя McRegion → Anvil. Помимо этого, сообщество разработало программы для просмотра и изменения сжатых и несжатых файлов NBT, например, NBTExplorer и NBT2YAML (все вышеприведённые программы поддерживают последние версии NBT).
The player can quickly find data tags (NBT) without the use of external editors by using /data to figure out the data for each entity or block entity. See more about this in the article Commands/data.
See Entity format for the various NBT Tags that are saved for each entity. This page also contains basic information for each NBT Tag.
When None is used in a tag name that means that this tag can be put directly into the start of the dataTag.
Contents
Items [ edit ]
These tags can be used on any item.
NBT Tag
Description
Allowed amount of same NBT Tags
Required tagnames
Syntax
Item
Used for any instance of item(s), it includes the Namespaced ID of the item(s), the number of items in the stack and the NBT data of the item(s). Any item with a Count of less than 1 or more than 127 becomes Air.
1
id, Count
Item NBT data here>>>
Enchantments
Used for the addition of enchantments to items, it includes the id of the enchantment and the level of the enchantment. Can specify one enchantment or multiple enchantments. It is possible specify no enchantment, which still applies the enchantment glint over the item.
Any
All
,]>
display
Used for the addition of custom names, colors (leather armor), and lore to items. Lore may have multiple lines.
Color is a hexadecimal color value, except in decimal. An RGB to hexadecimal converter can be found here and a hexadecimal to decimal converter can be found here. Names and lore must be passed as raw JSON text.
Any
At least one
«, color:#, Lore:[«<\"text\":\"Text for lore line\">«. ]>>
AttributeModifiers
Can be used to add attributes to mobs or items. For more information, see Attribute.
?
All
AttributeModifiers:[0:, 1:]
Unbreakable
Used to make items with durability that never degrades.
1
All
(1b = true, 0b = false)
SkullOwner
Used for getting player heads.
1
All
HideFlags
Used to hide flags (the info in the tool tip) such as enchantments, CanDestroy, CanPlaceOn, etc.
To hide multiple tags, you need to add the value of the tags you want to hide. For example, if you want to hide the «Enchantments» and the «Attributes modifiers» tags, the value you need to put is 3 (1+2).
VALUE ranges from 1 to 127, representing 127 combinations.
When adding to create a unique VALUE: [1]
Adding 1 hides «Enchantments»
Adding 2 hides «AttributeModifiers»
Adding 4 hides «Unbreakable»
Adding 8 hides «CanDestroy»
Adding 16 hides «CanPlaceOn»
Adding 32 hides other information, including potion effects, shield pattern info, «StoredEnchantments», written book «generation» and «author», «Explosion», «Fireworks», and map tooltips
Adding 64 hides «Dyed» on leather armors
Allowed 1 amount of same NBT Tags.
All
generation (Minecraft Java Edition 1.8)
Defines whether a written book is labeled as an «Original», a «Copy of Original», a «Copy of a copy» or «Tattered».
«Original», «Copy of Original», «Copy of a copy», «Tattered»
Unknown amount of allowed same NBT Tags.
The following table provides more details on previous sub-tags.
Tagname
Description
Used In
Value Type
Allowed Values
id
Refers to the id of an enchantment. See Enchanting for details on which id correlates to which enchantment.
Enchantments
String
Enchantment ID
lvl
Determines the level of an enchantment. A level between one and ten displays properly on an item as a roman numeral, however, any value above that displays as enchantment.level.lvl.
Enchantments
Numerical
-2147483648 to 2147483647
Name
The name of an item displayed in game. For blocks such as Chests and Dispensers the name replaces the default ‘Chest’ or ‘Dispenser’ in the upper left hand corner of the GUI. When used on command blocks the name is displayed when executing commands. This can be seen by using the /say command.
display
String
Any character that is available within the Minecraft language files (Most characters on your keyboard)
Lore
The text under the name of the item.
display
String
Any character that is available within the Minecraft language files (Most characters on your keyboard)
Blocks [ edit ]
These tags are put on blocks as items.
Tagname
Description
Value Type
Syntax
CanPlaceOn
This tag is used when making adventure maps to determine which block(s) the player can place a block on. Also used on hoes to make them till dirt and on spawn eggs to place them. If the value is not a valid block or item it displays as » missingno «.
An array of strings, each one saying the id of a block. Uses # for block tags (groups).
BlockEntityTag
This is used for tile entities, and stores their data for when they are placed down
Differs based on the block, see Tutorials/Command NBT tags § Blocks 2 for details. Example: get a white shield by using a command: /give @p shield>
>
BlockStateTag
This tag is used for blocks, and stores the block state when they are placed down.
A compound where each key is a block state key, and the value is the block state value to force place for this block. Differs based on the block, see Block states for details.
>
Entities [ edit ]
These tags are used when using the /summon command to spawn entities or when using the /data to edit the data of entities.
This tag determines only the entity’s velocity, not the direction that it’s facing.
The following table provides information on each tagname that can be added in an NBT Tag. These tagnames are specific to the /summon command.
Villager [ edit ]
These tags are used when summoning villagers. (Can’t be done in 1.14+)
Item Frame [ edit ]
These tags are used when summoning itemframes.
Potion [ edit ]
These tags are used to customize potions
Tagname
Description
Value type
Syntax
Potion
Determines which type of potion be receive in / give
minecraft:(potion effect)
CustomPotionEffects
Customize the effect of potions
Numerical
]>
CustomPotionColor
Determines the Color of Potion Bottle (1.11+)
Decimal color code
Armor Stand [ edit ]
These tags are used when summoning armor stands.
NBT Tag
Description
Value type
Syntax
NoGravity
Toggles gravity
0b or 1b (0b for false, 1b for true)
ShowArms
Determines whether you can see the armor stand’s arms or not.
Byte, 0b or 1b (0b for false, 1b for true)
NoBasePlate
Determines whether the armor stand has a base plate or not.
Byte, 0b or 1b
Small
Determines whether the armor stand is small or not.
Byte, 0b or 1b
Rotation
Changes the rotation of the armor stand
Byte, 0b or 1b
Marker
Small Hit box
Byte, 0b or 1b
Pose
Changes the pose of the armor stand’s body parts. Any subtag can be ommited
Byte, 0b or 1b
>
Invisible
Determines whether the armor stand is invisible or not.
Byte, 0b or 1b
Note: The Equipment tag also works for armor stands.
Turtle [ edit ]
These tags are used when summoning turtles.
Tagname
Description
Value type
Syntax
HomePosX
Determines the X coordinate of a turtle’s home beach.
Numerical
HomePosY
Determines the Y coordinate of a turtle’s home beach.
Numerical
HomePosZ
Determines the Z coordinate of a turtle’s home beach.
Numerical
TravelPosX
Determines the distance a turtle can lay eggs from its home coordinates, on the X axis.
Numerical
TravelPosY
Determines the distance a turtle can lay eggs from its home coordinates, on the Y axis.
Numerical
TravelPosZ
Determines the distance a turtle can lay eggs from its home coordinates, on the Z axis.
Numerical
HasEgg
Determines if the turtle has an egg to lay
0 – 0b – false 1 – 1b – true
Blocks [ edit ]
Tagname
Description
Value Type
Syntax
Command
Used with command blocks. Places command block with command.
A string
Generic [ edit ]
These tags can be used on most tile entitied blocks
Tagname
Description
Value Type
Syntax
CustomName
Displayed in the top left corner of the inventory, instead of the regular name. Works only where such a regular name exists.
A JSON text component
Lock
Says a name needed on a held item to open the inventory.
A string
Beacon [ edit ]
Tagname
Description
Value Type
Syntax
Primary
This determines the first status effect that the beacon creates. It defaults to level 1 of the effect.
An ID of a status effect.
Secondary
This determines the second status effect. If its the same as Primary, then it increases the status effect to level 2. Otherwise it is level 1.
Also an ID of a status effect.
Spawner [ edit ]
These tags are used when using /setblock or /summon (spawner minecarts) to create spawners. Add only those data tags you want to avoid a potential error.
Tagname
Description
Value Type
Syntax
EntityId
Specifies what entity the spawner spawns.
A ID of a Mob
>
SpawnData
Used for spawners that spawn entities with data tags.
An entity NBT tag
>
SpawnCount
How many entities the spawner can spawn at one time.
Integer
SpawnRange
The range of which the entities can spawn.
Integer
RequiredPlayerRange
The range of which a player must be in for the spawner to start spawning entities.
Integer
Delay
The number of ticks before entities spawn when a player is first detected.
Integer
MinSpawnDelay
After the first spawn, this is the minimum amount of ticks before more entities can spawn.
Integer
MaxSpawnDelay
Similar to MinSpawnDelay. After the first spawn, this is the maximum amount of ticks before more entities can spawn.
Integer
MaxNearbyEntities
Checks the number of entities within the spawn range (‘SpawnRange’ tag). If the number of entities it detects is over the set MaxNearbyEntities number, it does not spawn more entities unless the amount of entities within the spawn range is decreased.
Integer
SpawnPotentials
Used when creating spawners that spawn multiple types of entities. A weighted list of entities to be spawned, including NBT tags.
A List
>]>
Weight
Used if spawning multiple entities using SpawnPotentials. If the same as another SpawnPotentials entity, both have an even chance of spawning.
Все блоковые сущности: id: ID блоковой сущности x: Расположение сущности по оси x y: Расположение сущности по оси y z: Расположение сущности по оси z
Сундук: CustomName: Название сундука Items (Массив): Предметы, помещённые в сундук
Печь: CustomName: Название печи BurnTime: Количество тиков до того момента, после которого в печке закончится топливо (Уголь, дерево) CookTime: Количество тиков до того момента, после которого в печке приготовится предмет Items (Массив): Предметы, помещённые в печь
Варочная стойка: CustomName: Название стойки BrewTime: Количество тиков, которые понадобились для текущей варки Items (Массив): Предметы, помещённые в стойку
Воронка: CustomName: Название воронки TransferCooldown: Количество тиков до того момента, после которого будет передан следующий предмет Items (Массив): Предметы, помещённые в воронку
Раздатчик и выбрасыватель: CustomName: Название раздатчика или выбрасывателя Items (Массив): Предметы, помещённые в раздатчик или выбрасыватель
Цветочный горшок: Item: ID предмета, который находится в горшке Data: Дополнительный параметр блока, который находится в горшке
Маяк: Levels: Количество уровней блоков под маяком Primary: Базовый эффект Secondary: Дополнительный эффект
Проигрыватель: Record: Выбранная запись (Пластинка) RecordItem: Предмет в проигрывателе
Компаратор: OutputSignal: Сила сигнала, выдаваемого компаратором
Командный блок: CustomName: Название командного блока Command: Команда, прописанная в командном блоке LastOutput: Строка состояния в командном блоке SuccessCount: Мощность выводимого сигнала TrackOutput: Не используется
Табличка: Text1: Текст, написанный на первой строчке Text2: Текст, написанный на второй строчке Text3: Текст, написанный на третьей строчке Text4: Текст, написанный на четвёртой строчке
Голова: SkullType: Тип головы Rot: Угол поворота ExtraType: Ник игрока, чья голова надета на голов
Спаунер: EntiyId: ID выбранной сущности SpawnCount: Количество мобов, создающихся за раз SpawnRange: Радиус, в котором создаются сущности Delay: Количество тиков до того момента, после которого спавнер сработает вновь MinSpawnDelay: Минимальное количество задержки MaxSpawnDelay: Максимальное количество задержки MaxNearbyEntities: Максимальное количество сущностей, которые могут находиться рядом со спавнером RequiredPlayerRange: Радиус, в котором игрок активирует спавнер SpawnData: Данные, копируемые в следующую сущность SpawnPotentials (Массив): Список возможных сущностей для создания —Type: Замена EntiyId —Weight: Весовой шанс рождения —Properties: Потенциально создаваемый объект