/// <summary> /// Serializes the given object into a <see cref="NbtCompound"/>. /// </summary> /// <typeparam name="TObject">Object type to serialize.</typeparam> /// <param name="object">Object to serialize.</param> /// <param name="compoundName">Optionnal compound name.</param> /// <returns>Given object serialized as a <see cref="NbtCompound"/>.</returns> public static NbtCompound SerializeCompound <TObject>(TObject @object, string compoundName = null) where TObject : class, new() { IEnumerable <NbtObjectDescriptor> nbtProperties = LoadObjectMetadata(@object); var nbtCompound = new NbtCompound(compoundName); foreach (NbtObjectDescriptor nbtProperty in nbtProperties) { NbtTag tag = null; object propertyValue = nbtProperty.Property.GetValue(@object); if (nbtProperty.Type == NbtTagType.Compound) { tag = SerializeCompound(propertyValue, nbtProperty.Name); } else if (nbtProperty.Type == NbtTagType.List) { // TODO } else { tag = CreateTag(nbtProperty, propertyValue); } if (tag is not null) { nbtCompound.Add(tag); } } return(nbtCompound); }
public void Export(string path, NbtTag root) { if (Snbt) { File.WriteAllText(path, root.ToSnbt(CreateOptions())); } else { var file = new fNbt.NbtFile(); file.BigEndian = BigEndian; file.RootTag = root; using (var writer = File.Create(path)) { if (BedrockHeader) { writer.Seek(8, SeekOrigin.Begin); } long size = file.SaveToStream(writer, Compression); if (BedrockHeader) { // bedrock level.dat files start with a header containing a magic number and then the little-endian size of the data writer.Seek(0, SeekOrigin.Begin); writer.Write(new byte[] { 8, 0, 0, 0 }, 0, 4); writer.Write(DataUtils.GetBytes((int)size, little_endian: !BigEndian), 0, 4); } } } }
public static IByteTransformer GetByteProvider(NbtTag tag) { if (tag is NbtByteArray ba) { return(new ByteArrayByteProvider(ba)); } if (tag is NbtIntArray ia) { return(new IntArrayByteProvider(ia)); } if (tag is NbtLongArray la) { return(new LongArrayByteProvider(la)); } if (tag is NbtList list) { if (list.ListType == NbtTagType.Byte) { return(new ByteListByteProvider(list)); } if (list.ListType == NbtTagType.Short) { return(new ShortListByteProvider(list)); } if (list.ListType == NbtTagType.Int) { return(new IntListByteProvider(list)); } if (list.ListType == NbtTagType.Long) { return(new LongListByteProvider(list)); } } throw new ArgumentException($"Can't get a byte provider from {tag.TagType}"); }
private static object DeserializeTag(NbtTag tag, Type type) { switch (tag.Type) { case NbtTagType.Byte: case NbtTagType.Double: case NbtTagType.Float: case NbtTagType.Int: case NbtTagType.Long: case NbtTagType.Short: case NbtTagType.String: return(Convert.ChangeType(tag.GetValue(), type)); case NbtTagType.ByteArray: break; case NbtTagType.Compound: return(DeserializeCompound(tag as NbtCompound, type)); case NbtTagType.IntArray: break; case NbtTagType.List: return(DeserializeList(tag as NbtList, type)); default: throw new ArgumentOutOfRangeException(); } throw new NotImplementedException(); }
public static World LoadWorld(string FilePath) { NbtFile file = LoadFile(FilePath); //var levelFileName = Path.Combine(FilePath, "level.dat"); if (file is NbtFile) { NbtTag dataTag = file.RootTag["Data"]; if (dataTag == null || !(dataTag is NbtCompound)) { /*Log.Info*/ Debug.WriteLine($"Invalid root tag!"); return(null); } World world = new World((NbtCompound)dataTag) { BasePath = Path.GetFullPath(FilePath) }; /*Log.Info*/ Debug.WriteLine($"Found valid data file at {FilePath}, loading"); /*Log.Info*/ Debug.WriteLine($"World: {world}"); return(world); } else { /*Log.Warn*/ Debug.WriteLine($"No valid data found at {FilePath}"); return(null); } }
void BoxNameTextChanged(object sender, EventArgs e) { var tag = (slot.Item.tag.Contains("tag") ? slot.Item.tag["tag"] : null); var display = ((tag != null && tag.Contains("display")) ? tag["display"] : null); var name = boxName.Text; if (name != "") { if (tag == null) { tag = NbtTag.CreateCompound(); slot.Item.tag.Add("tag", tag); } if (display == null) { display = NbtTag.CreateCompound(); tag.Add("display", display); } if (display.Contains("Name")) { display["Name"].Value = name; } else { display.Add("Name", name); } } else { display["Name"].Remove(); } slot.CallChanged(); }
public void Deserialize(NbtTag value) { var tag = (NbtCompound)value; X = tag["X"].IntValue; Z = tag["Z"].IntValue; if (tag.Contains("TerrainPopulated")) { TerrainPopulated = tag["TerrainPopulated"].ByteValue > 0; } if (tag.Contains("LightPopulated")) { LightPopulated = tag["LightPopulated"].ByteValue > 0; } Blocks = tag["Blocks"].ByteArrayValue; Metadata = new NibbleArray(); Metadata.Data = tag["Data"].ByteArrayValue; BlockLight = new NibbleArray(); BlockLight.Data = tag["BlockLight"].ByteArrayValue; SkyLight = new NibbleArray(); SkyLight.Data = tag["SkyLight"].ByteArrayValue; if (tag.Contains("TileEntities")) { foreach (var entity in tag["TileEntities"] as NbtList) { TileEntities[new Coordinates3D(entity["coordinates"][0].IntValue, entity["coordinates"][1].IntValue, entity["coordinates"][2].IntValue)] = entity["value"][0] as NbtCompound; } } UpdateHeightMap(); // TODO: Entities }
public static DatFile LoadNBT(string FilePath) { try { NbtFile file = LoadFile(FilePath); if (file is NbtFile) { NbtTag dataTag = file.RootTag; if (dataTag == null || !(dataTag is NbtCompound)) { /*Log.Info*/ Debug.WriteLine($"Invalid root tag!"); return(null); } DatFile datFile = new DatFile((NbtCompound)dataTag) { BasePath = Path.GetFullPath(FilePath) }; /*Log.Info*/ Debug.WriteLine($"Found valid data file at {FilePath}, loading"); /*Log.Info*/ Debug.WriteLine($"DatFile: {datFile}"); return(datFile); } } catch (Exception e) { if (e is InvalidDataException) { Debug.WriteLine($"No valid data found at {FilePath}"); } } return(null); }
void BoxPlayerTextChanged(object sender, EventArgs e) { var tag = (slot.Item.tag.Contains("tag") ? slot.Item.tag["tag"] : null); var player = boxPlayer.Text; if (player != "") { if (tag == null) { tag = NbtTag.CreateCompound(); slot.Item.tag.Add("tag", tag); } if (tag.Contains("SkullOwner")) { tag["SkullOwner"].Value = player; } else { tag.Add("SkullOwner", player); } } else { tag["SkullOwner"].Remove(); } slot.CallChanged(); }
void BoxLoreTextChanged(object sender, EventArgs e) { var tag = (slot.Item.tag.Contains("tag") ? slot.Item.tag["tag"] : null); var display = ((tag != null && tag.Contains("display")) ? tag["display"] : null); if (boxLore.Text != "") { if (tag == null) { tag = NbtTag.CreateCompound(); slot.Item.tag.Add("tag", tag); } if (display == null) { display = NbtTag.CreateCompound(); tag.Add("display", display); } var lore = (display.Contains("Lore") ? display["Lore"] : null); if (lore == null) { lore = NbtTag.CreateList(NbtTagType.String); display.Add("Lore", lore); } else { lore.Clear(); } lore.Add(boxLore.Lines); } else { display["Lore"].Remove(); } slot.CallChanged(); }
public static void Load(NbtTag inventory, Dictionary <byte, ItemSlot> slots) { try { foreach (ItemSlot slot in slots.Values) { slot.Item = null; } foreach (NbtTag tag in inventory) { byte slot = (byte)tag["Slot"]; byte count = (byte)tag["Count"]; if (count == 0) { continue; } if (!slots.ContainsKey(slot)) { MessageBox.Show("Unknown slot '" + slot + "', discarded item.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); continue; } ItemSlot itemSlot = slots[slot]; itemSlot.Item = new Item(tag); } } finally { foreach (ItemSlot slot in slots.Values) { slot.Refresh(); } } }
public static void AssertValueTest(NbtFile file) { Assert.IsInstanceOf <NbtCompound>(file.RootTag); NbtCompound root = file.RootTag; Assert.AreEqual("root", root.Name); Assert.AreEqual(10, root.Count); Assert.IsInstanceOf <NbtByte>(root["byte"]); NbtTag node = root["byte"]; Assert.AreEqual("byte", node.Name); Assert.AreEqual(1, node.ByteValue); Assert.IsInstanceOf <NbtShort>(root["short"]); node = root["short"]; Assert.AreEqual("short", node.Name); Assert.AreEqual(2, node.ShortValue); Assert.IsInstanceOf <NbtInt>(root["int"]); node = root["int"]; Assert.AreEqual("int", node.Name); Assert.AreEqual(3, node.IntValue); Assert.IsInstanceOf <NbtLong>(root["long"]); node = root["long"]; Assert.AreEqual("long", node.Name); Assert.AreEqual(4L, node.LongValue); Assert.IsInstanceOf <NbtFloat>(root["float"]); node = root["float"]; Assert.AreEqual("float", node.Name); Assert.AreEqual(5f, node.FloatValue); Assert.IsInstanceOf <NbtDouble>(root["double"]); node = root["double"]; Assert.AreEqual("double", node.Name); Assert.AreEqual(6d, node.DoubleValue); Assert.IsInstanceOf <NbtByteArray>(root["byteArray"]); node = root["byteArray"]; Assert.AreEqual("byteArray", node.Name); CollectionAssert.AreEqual(new byte[] { 10, 11, 12 }, node.ByteArrayValue); Assert.IsInstanceOf <NbtIntArray>(root["intArray"]); node = root["intArray"]; Assert.AreEqual("intArray", node.Name); CollectionAssert.AreEqual(new[] { 20, 21, 22 }, node.IntArrayValue); Assert.IsInstanceOf <NbtLongArray>(root["longArray"]); node = root["longArray"]; Assert.AreEqual("longArray", node.Name); CollectionAssert.AreEqual(new long[] { 200, 210, 220 }, node.LongArrayValue); Assert.IsInstanceOf <NbtString>(root["string"]); node = root["string"]; Assert.AreEqual("string", node.Name); Assert.AreEqual("123", node.StringValue); }
private static object DeserializeTag(NbtTag tag, Type type) { switch (tag.Type) { case NbtTagType.Byte: case NbtTagType.Double: case NbtTagType.Float: case NbtTagType.Int: case NbtTagType.Long: case NbtTagType.Short: case NbtTagType.String: return Convert.ChangeType(tag.GetValue(), type); case NbtTagType.ByteArray: break; case NbtTagType.Compound: return DeserializeCompound(tag as NbtCompound, type); case NbtTagType.IntArray: break; case NbtTagType.List: return DeserializeList(tag as NbtList, type); default: throw new ArgumentOutOfRangeException(); } throw new NotImplementedException(); }
public void Initialize() { if (_isInitialized) { return; // Quick exit } lock (_initializeSync) { if (_isInitialized) { return; } BasePath = BasePath ?? Config.GetProperty("PCWorldFolder", "World").Trim(); NbtFile file = new NbtFile(); file.LoadFromFile(Path.Combine(BasePath, "level.dat")); NbtTag dataTag = file.RootTag["Data"]; LevelInfo = new LevelInfo(dataTag); WaterOffsetY = WaterOffsetY == 0 ? (byte)Config.GetProperty("PCWaterOffset", 0) : WaterOffsetY; _isInitialized = true; } }
internal void LoadSection(NbtTag section) { // Make sure we're passed a TAG_Compound named "Environment" if (section is NbtCompound && section.Name == "Environment") { NbtCompound compound = (NbtCompound) section; SurroundingGroundHeight = compound["SurroundingGroundHeight"] != null ? ((NbtShort) compound["SurroundingGroundHeight"]).Value : (short) 0; SurroundingGroundType = compound["SurroundingGroundType"] != null ? (McBlock) ((NbtByte) compound["SurroundingGroundType"]).Value : 0x00; SurroundingWaterHeight = compound["SurroundingWaterHeight"] != null ? ((NbtShort) compound["SurroundingWaterHeight"]).Value : (short) 0; SurroundingWaterType = compound["SurroundingWaterType"] != null ? (McBlock) ((NbtByte) compound["SurroundingWaterType"]).Value : 0x00; CloudHeight = compound["CloudHeight"] != null ? ((NbtShort) compound["CloudHeight"]).Value : (short) 0; CloudColor = compound["CloudColor"] != null ? Color.FromArgb(((NbtInt) compound["CloudColor"]).Value) : Color.Black; SkyColor = compound["SkyColor"] != null ? Color.FromArgb(((NbtInt) compound["SkyColor"]).Value) : Color.Black; FogColor = compound["FogColor"] != null ? Color.FromArgb(((NbtInt) compound["FogColor"]).Value) : Color.Black; SkyBrightness = compound["SkyBrightness"] != null ? ((NbtByte) compound["SkyBrightness"]).Value : (byte) 0x00; } }
public static NbtTag[] FindTagsNamed(NbtTag haystack, string needleName) { List <NbtTag> l = new List <NbtTag>(); if (!haystack.HasValue) { ICollection <NbtTag> tags = ((ICollection <NbtTag>)haystack); //I DON'T CARE WHETHER ITS A LIST OR A COMPOUND. foreach (NbtTag tag in tags) { if (!tag.HasValue) { if (tag.Name == needleName) { l.Add(tag); } else { l.AddRange(FindTagsNamed(tag, needleName)); //GETTIN RECURSIVE UP IN THIS MOFO. BETTER WATCH OUT. } } } } return(l.ToArray()); }
private void AssertIdentical(NbtTag c1, NbtTag c2) { var snbt1 = c1.ToString(); var snbt2 = c2.ToString(); Assert.AreEqual(snbt1, snbt2); }
void ReadData(NbtCompound root, string name, out Level lvl) { if (root["FormatVersion"].ByteValue > 1) { throw new NotSupportedException("Only version 1 of ClassicWorld format is supported."); } short x = root["X"].ShortValue, y = root["Y"].ShortValue, z = root["Z"].ShortValue; if (x <= 0 || y <= 0 || z <= 0) { throw new InvalidDataException("Level dimensions must be > 0."); } lvl = new Level(name, (ushort)x, (ushort)y, (ushort)z); lvl.blocks = root["BlockArray"].ByteArrayValue; ConvertCustom(lvl); if (!root.Contains("Spawn")) { return; } NbtTag spawn = root["Spawn"]; lvl.spawnx = (ushort)spawn["X"].ShortValue; lvl.spawny = (ushort)spawn["Y"].ShortValue; lvl.spawnz = (ushort)spawn["Z"].ShortValue; lvl.rotx = spawn["H"].ByteValue; lvl.roty = spawn["P"].ByteValue; }
void BoxTextTextChanged(object sender, EventArgs e) { string text = boxText.Text.Replace("\r\n", "\n"); NbtTag pages = slot.Item.tag["tag"]["pages"]; if (text == "") { pages[page].Value = text; if (page == pages.Count - 1) { for (int p = page; p > 1; p--) { if ((string)pages[p].Value == "") { pages[p].Remove(); } else { break; } } } } else { while (pages.Count < page + 1) { pages.Add(""); } pages[page].Value = text; } slot.CallChanged(); }
public void LoadFromNbt(NbtTag dataTag) { GetPropertyValue(dataTag, () => DataVersion); GetPropertyValue(dataTag, () => Version); GetPropertyValue(dataTag, () => Initialized); GetPropertyValue(dataTag, () => LevelName); GetPropertyValue(dataTag, () => GeneratorName); GetPropertyValue(dataTag, () => GeneratorVersion); GetPropertyValue(dataTag, () => GeneratorOptions); GetPropertyValue(dataTag, () => RandomSeed); GetPropertyValue(dataTag, () => MapFeatures); GetPropertyValue(dataTag, () => LastPlayed); GetPropertyValue(dataTag, () => AllowCommands); GetPropertyValue(dataTag, () => Hardcore); GetPropertyValue(dataTag, () => GameType); GetPropertyValue(dataTag, () => Time); GetPropertyValue(dataTag, () => DayTime); GetPropertyValue(dataTag, () => SpawnX); GetPropertyValue(dataTag, () => SpawnY); GetPropertyValue(dataTag, () => SpawnZ); GetPropertyValue(dataTag, () => Raining); GetPropertyValue(dataTag, () => RainTime); GetPropertyValue(dataTag, () => Thundering); GetPropertyValue(dataTag, () => ThunderTime); }
public void Initialize() { BasePath = BasePath ?? Config.GetProperty("LevelDBWorldFolder", "World").Trim(); var directory = new DirectoryInfo(Path.Combine(BasePath, "db")); var levelFileName = Path.Combine(BasePath, "level.dat"); Log.Debug($"Loading level.dat from {levelFileName}"); if (File.Exists(levelFileName)) { var file = new NbtFile { BigEndian = false, UseVarInt = false }; var levelStream = File.OpenRead(levelFileName); levelStream.Seek(8, SeekOrigin.Begin); file.LoadFromStream(levelStream, NbtCompression.None); Log.Debug($"Level DAT\n{file.RootTag}"); NbtTag dataTag = file.RootTag["Data"]; //LevelInfo = new LevelInfoBedrock(dataTag); } else { Log.Warn($"No level.dat found at {levelFileName}. Creating empty."); LevelInfo = new LevelInfoBedrock(); } var db = new Database(directory); db.Open(); _db = db; MissingChunkProvider?.Initialize(); }
private static object DeserializeChild(Type type, NbtTag tag) { if (typeof(NbtTag).IsAssignableFrom(type)) { tag = (NbtTag)tag.Clone(); tag.Name = null; return(tag); } var value = GetValueFromTag(tag, type); if (value != null) { return(value); } if (typeof(IList).IsAssignableFrom(type)) { return(GetList(type, (NbtList)tag)); } else if (typeof(IDictionary).IsAssignableFrom(type)) { return(GetDictionary(type, (NbtCompound)tag)); } value = Activator.CreateInstance(type); DeserializeBase(value, type, tag); return(value); }
public void PrimitiveTest() { NbtTag intTag = NbtConvert.MakeTag("derp", 1); Assert.IsInstanceOf <NbtInt>(intTag); Assert.Equals(intTag.IntValue, 1); }
public override byte[] Load(Stream stream, Game game, out int width, out int height, out int length) { using (GZipStream wrapper = new GZipStream(stream, CompressionMode.Decompress)) { reader = new BinaryReader(wrapper); if (reader.ReadByte() != (byte)NbtTagType.Compound) { throw new InvalidDataException("Nbt file must start with Tag_Compound"); } this.game = game; map = game.Map; invalid.TagId = NbtTagType.Invalid; NbtTag root = ReadTag((byte)NbtTagType.Compound, true); Dictionary <string, NbtTag> children = (Dictionary <string, NbtTag>)root.Value; if (children.ContainsKey("Metadata")) { ParseMetadata(children); } Dictionary <string, NbtTag> spawn = (Dictionary <string, NbtTag>)children["Spawn"].Value; LocalPlayer p = game.LocalPlayer; p.SpawnPoint.X = (short)spawn["X"].Value / 32f; p.SpawnPoint.Y = (short)spawn["Y"].Value / 32f; p.SpawnPoint.Z = (short)spawn["Z"].Value / 32f; map.Uuid = new Guid((byte[])children["UUID"].Value); width = (short)children["X"].Value; height = (short)children["Y"].Value; length = (short)children["Z"].Value; return((byte[])children["BlockArray"].Value); } }
public NbtTag FillTag(object obj, NbtTag tag) { if (!contractType.IsInstanceOfType(obj)) { throw new ArgumentException("Invalid type! Expected an object of type " + contractType); } throw new NotImplementedException(); }
private static List <TileEntity> GetTileEntities(NbtTag tileEntitiesList) { List <TileEntity> list = new List <TileEntity>(); NbtList TileEntities = tileEntitiesList as NbtList; if (TileEntities != null) { foreach (NbtCompound compTag in TileEntities) { NbtTag xTag = compTag["x"]; NbtTag yTag = compTag["y"]; NbtTag zTag = compTag["z"]; NbtTag idTag = compTag["id"]; TileEntity entity = new TileEntity(xTag.IntValue, yTag.IntValue, zTag.IntValue, idTag.StringValue); if (entity.ID == "Sign") { NbtTag Text1Tag = compTag["Text1"]; NbtTag Text2Tag = compTag["Text2"]; NbtTag Text3Tag = compTag["Text3"]; NbtTag Text4Tag = compTag["Text4"]; Sign sign = new Sign(xTag.IntValue, yTag.IntValue, zTag.IntValue, Text1Tag.StringValue, Text2Tag.StringValue, Text3Tag.StringValue, Text4Tag.StringValue); list.Add(sign); continue; } list.Add(entity); } } return(list); }
public void InitializingListFromCollection() { var sameTags = new NbtTag[] { new NbtInt(1), new NbtInt(2), new NbtInt(3) }; var mixedTags = new NbtTag[] { new NbtFloat(1), new NbtByte(2), new NbtInt(3) }; // auto-detecting list type Assert.DoesNotThrow(() => new NbtList("Test1", sameTags)); Assert.AreEqual(new NbtList("Test1", sameTags).ListType, NbtTagType.Int); // correct explicitly-given list type Assert.DoesNotThrow(() => new NbtList("Test2", sameTags, NbtTagType.Int)); // wrong explicitly-given list type Assert.Throws <ArgumentException>(() => new NbtList("Test3", sameTags, NbtTagType.Float)); // auto-detecting mixed list given Assert.Throws <ArgumentException>(() => new NbtList("Test4", mixedTags)); }
public void Deserialize(NbtTag value) { var chunk = new Chunk(); var tag = (NbtCompound)value; Biomes = chunk.Biomes; HeightMap = chunk.HeightMap; LastUpdate = chunk.LastUpdate; TerrainPopulated = chunk.TerrainPopulated; X = tag["X"].IntValue; Z = tag["Z"].IntValue; Blocks = tag["Blocks"].ByteArrayValue; Metadata = new NibbleArray(); Metadata.Data = tag["Data"].ByteArrayValue; BlockLight = new NibbleArray(); BlockLight.Data = tag["BlockLight"].ByteArrayValue; SkyLight = new NibbleArray(); SkyLight.Data = tag["SkyLight"].ByteArrayValue; if (tag.Contains("TileEntities")) { foreach (var entity in tag["TileEntities"] as NbtList) { TileEntities[new Coordinates3D(entity["coordinates"][0].IntValue, entity["coordinates"][1].IntValue, entity["coordinates"][2].IntValue)] = entity["value"][0] as NbtCompound; } } // TODO: Entities }
static NbtList GetNbtInventory(this Player player) { NbtTag[] tags = new NbtTag[104]; for (int i = 0; i < player.Inventory.Slots.Count; i++) { tags[i] = player.Inventory.Slots[i].NbtSerialize(i); } for (int i = player.Inventory.Slots.Count; i < 100; i++) { tags[i] = new ItemAir().NbtSerialize(i); } tags[100] = player.Inventory.Helmet.NbtSerialize(100); tags[101] = player.Inventory.Chest.NbtSerialize(101); tags[102] = player.Inventory.Leggings.NbtSerialize(102); tags[103] = player.Inventory.Boots.NbtSerialize(103); NbtList nbt = new NbtList("Inventory", tags, NbtTagType.Compound); //@TODO EnderChest return(nbt); }
public void LoadAnvilLevelLoadTest() { NbtFile file = new NbtFile(); file.LoadFromFile(@"D:\Downloads\KingsLanding1\KingsLanding1\level.dat"); NbtTag dataTag = file.RootTag["Data"]; Assert.NotNull(dataTag); Assert.NotNull(dataTag["version"]); Assert.AreEqual(19133, dataTag["version"].IntValue); Assert.NotNull(dataTag["initialized"]); var level = new LevelInfo(); level.GetPropertyValue(dataTag, () => level.Version); Assert.AreEqual(19133, level.Version); Assert.AreEqual(19133, level.GetPropertyValue(dataTag, () => level.Version)); Assert.AreEqual(true, level.GetPropertyValue(dataTag, () => level.Initialized)); Assert.AreEqual("WesterosCraft", level.GetPropertyValue(dataTag, () => level.LevelName)); var levelFromNbt = new LevelInfo(dataTag); Assert.AreEqual(19133, levelFromNbt.Version); Assert.AreEqual(true, levelFromNbt.Initialized); Assert.AreEqual("WesterosCraft", levelFromNbt.LevelName); }
public void InitializingListFromCollection() { var sameTags = new NbtTag[] { new NbtInt( 1 ), new NbtInt( 2 ), new NbtInt( 3 ) }; var mixedTags = new NbtTag[] { new NbtFloat( 1 ), new NbtByte( 2 ), new NbtInt( 3 ) }; // auto-detecting list type Assert.DoesNotThrow( () => new NbtList( "Test1", sameTags ) ); Assert.AreEqual( new NbtList( "Test1", sameTags ).ListType, NbtTagType.Int ); // correct explicitly-given list type Assert.DoesNotThrow( () => new NbtList( "Test2", sameTags, NbtTagType.Int ) ); // wrong explicitly-given list type Assert.Throws<ArgumentException>( () => new NbtList( "Test3", sameTags, NbtTagType.Float ) ); // auto-detecting mixed list given Assert.Throws<ArgumentException>( () => new NbtList( "Test4", mixedTags ) ); }
internal void LoadSection(NbtTag section) { // Make sure we're passed a TAG_List named "TileEntities" if (section is NbtList && section.Name == "TileEntities") { //NbtList list = (NbtList) section; } }
public Item(short id, byte count = 1, byte slot = 0, short damage = 0) { tag = NbtTag.CreateCompound( "id", id, "Count", count, "Slot", slot, "Damage", damage); }
private static string GetNameBeforeValue(NbtTag tag, SnbtOptions options) { if (tag.Name == null) { return(String.Empty); } return(GetName(tag, options) + NAME_VALUE_SEPARATOR + (options.Minified ? String.Empty : VALUE_SPACING)); }
public static void Save(NbtTag parent, Dictionary<byte, ItemSlot> slots) { if (parent.Contains("Inventory")) parent["Inventory"].Remove(); NbtTag inventory = parent.Add("Inventory", NbtTag.CreateList(NbtTagType.Compound)); foreach (ItemSlot slot in slots.Values) { if (slot.Item == null) continue; inventory.Add(slot.Item.tag); } }
public void Write(string name, NbtTag tag) { if (name == null) throw new ArgumentNullException("name"); if (tag == null) throw new ArgumentNullException("tag"); Write((byte)tag.Type); Write(name); Write(tag, false); }
public override NbtTag Add(NbtTag item) { if (item == null) throw new ArgumentNullException("item"); if (item.Parent != null) item = item.Clone(); _list.Add(item); item.Parent = this; return item; }
public override NbtTag Add(string key, NbtTag item) { if (key == null) throw new ArgumentNullException("key"); if (item == null) throw new ArgumentNullException("item"); if (item.Parent != null) item = item.Clone(); _dict.Add(key, item); item._name = key; item.Parent = this; return item; }
void Write(NbtTag tag, bool writeType) { if (tag == null) throw new ArgumentNullException("tag"); if (writeType) Write((byte)tag.Type); switch (tag.Type) { case NbtTagType.Byte: Write((byte)tag.Value); break; case NbtTagType.Short: Write((short)tag.Value); break; case NbtTagType.Int: Write((int)tag.Value); break; case NbtTagType.Long: Write((long)tag.Value); break; case NbtTagType.Float: Write((float)tag.Value); break; case NbtTagType.Double: Write((double)tag.Value); break; case NbtTagType.ByteArray: Write((byte[])tag.Value); break; case NbtTagType.String: Write((string)tag.Value); break; case NbtTagType.List: Write((byte)tag.ListType); Write(tag.Count); foreach (NbtTag item in tag) Write(item, false); break; case NbtTagType.Compound: foreach(NbtTag item in tag) Write(item.Name, item); Write((byte)NbtTagType.End); break; case NbtTagType.IntArray: Write((int[])tag.Value); break; default: throw new FormatException("Unknown TagType '"+(int)tag.Type+"'."); } }
public static void Load(NbtTag inventory, Dictionary<byte, ItemSlot> slots) { try { foreach (ItemSlot slot in slots.Values) slot.Item = null; foreach (NbtTag tag in inventory) { byte slot = (byte)tag["Slot"]; byte count = (byte)tag["Count"]; if (count == 0) continue; if (!slots.ContainsKey(slot)) { MessageBox.Show("Unknown slot '"+slot+"', discarded item.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); continue; } ItemSlot itemSlot = slots[slot]; itemSlot.Item = new Item(tag); } } finally { foreach (ItemSlot slot in slots.Values) slot.Refresh(); } }
internal void LoadSection(NbtTag section) { // Make sure we're passed a TAG_List named "Entities" if (section is NbtList && section.Name == "Entities") { NbtList list = (NbtList) section; foreach (NbtTag tag in list.Tags) { if (tag is NbtCompound) { McEntity entity = McEntityLoader.LoadEntity((NbtCompound) tag); if (entity != null) { Entities.Add(entity); } } } } }
internal void LoadSection(NbtTag section) { // Make sure we're passed a TAG_Compound named "Map" if (section is NbtCompound && section.Name == "Map") { NbtCompound compound = (NbtCompound) section; Width = compound["Width"] != null ? ((NbtShort) compound["Width"]).Value : (short) 0; Height = compound["Height"] != null ? ((NbtShort) compound["Height"]).Value : (short) 0; Length = compound["Length"] != null ? ((NbtShort) compound["Length"]).Value : (short) 0; if (compound["Blocks"] != null) { NbtByteArray blocks = (NbtByteArray) compound["Blocks"]; Blocks.Data = new byte[blocks.Value.Length]; Buffer.BlockCopy(blocks.Value, 0, Blocks.Data, 0, blocks.Value.Length); } else { Blocks.Data = new byte[0]; } if (compound["Data"] != null) { NbtByteArray data = (NbtByteArray) compound["Data"]; Data.Data = new byte[data.Value.Length]; Buffer.BlockCopy(data.Value, 0, Data.Data, 0, data.Value.Length); } else { Data.Data = new byte[0]; } if (compound["Spawn"] != null && compound["Spawn"] is NbtList) { NbtList list = (NbtList) compound["Spawn"]; Spawn.X = list.Tags.Count > 0 ? ((NbtShort) list.Tags[0]).Value : (short) 0; Spawn.Y = list.Tags.Count > 1 ? ((NbtShort) list.Tags[1]).Value : (short) 0; Spawn.Z = list.Tags.Count > 2 ? ((NbtShort) list.Tags[2]).Value : (short) 0; } } }
public void UtilityMethods() { NbtTag[] testThings = new NbtTag[] { new NbtShort( "Name1", 1 ), new NbtInt( "Name2", 2 ), new NbtLong( "Name3", 3 ) }; NbtCompound compound = new NbtCompound(); // add range compound.AddRange( testThings ); // add range with duplicates Assert.Throws<ArgumentException>( () => compound.AddRange( testThings ) ); }
public void InitializingCompoundFromCollectionTest() { NbtTag[] allNamed = new NbtTag[] { new NbtShort( "allNamed1", 1 ), new NbtLong( "allNamed2", 2 ), new NbtInt( "allNamed3", 3 ) }; NbtTag[] someUnnamed = new NbtTag[] { new NbtInt( "someUnnamed1", 1 ), new NbtInt( 2 ), new NbtInt( "someUnnamed3", 3 ) }; NbtTag[] someNull = new NbtTag[] { new NbtInt( "someNull1", 1 ), null, new NbtInt( "someNull3", 3 ) }; NbtTag[] dupeNames = new NbtTag[] { new NbtInt( "dupeNames1", 1 ), new NbtInt( "dupeNames2", 2 ), new NbtInt( "dupeNames1", 3 ) }; // null collection, should throw Assert.Throws<ArgumentNullException>( () => new NbtCompound( "nullTest", null ) ); // proper initialization Assert.DoesNotThrow( () => new NbtCompound( "allNamedTest", allNamed ) ); CollectionAssert.AreEquivalent( allNamed, new NbtCompound( "allNamedTest", allNamed ) ); // some tags are unnamed, should throw Assert.Throws<ArgumentException>( () => new NbtCompound( "someUnnamedTest", someUnnamed ) ); // some tags are null, should throw Assert.Throws<ArgumentNullException>( () => new NbtCompound( "someNullTest", someNull ) ); // some tags have same names, should throw Assert.Throws<ArgumentException>( () => new NbtCompound( "dupeNamesTest", dupeNames ) ); }
public object Deserialize(NbtTag value) { if (value is NbtByte) return ((NbtByte)value).Value; else if (value is NbtByteArray) return ((NbtByteArray)value).Value; else if (value is NbtDouble) return ((NbtDouble)value).Value; else if (value is NbtFloat) return ((NbtFloat)value).Value; else if (value is NbtInt) return ((NbtInt)value).Value; else if (value is NbtIntArray) return ((NbtIntArray)value).Value; else if (value is NbtLong) return ((NbtLong)value).Value; else if (value is NbtShort) return ((NbtShort)value).Value; else if (value is NbtString) return ((NbtString)value).Value; else if(value is NbtCompound) { var compound = value as NbtCompound; var properties = Type.GetProperties().Where(p => !Attribute.GetCustomAttributes(p, typeof(NbtIgnoreAttribute)).Any()); var resultObject = Activator.CreateInstance(Type); foreach (var property in properties) { if (!property.CanWrite) continue; string name = property.Name; var nameAttributes = Attribute.GetCustomAttributes(property, typeof(TagNameAttribute)); if (nameAttributes.Length != 0) name = ((TagNameAttribute)nameAttributes[0]).Name; var node = compound.Tags.SingleOrDefault(a => a.Name == name); if (node == null) continue; var data = new NbtSerializer(property.PropertyType).Deserialize(node); if (property.PropertyType == typeof(bool) && data is byte) data = (byte)data == 1; property.SetValue(resultObject, data, null); } return resultObject; } throw new NotSupportedException("The node type '" + value.GetType() + "' is not supported."); }
private static string GetNativeType(NbtTag t) { switch (t.GetType().Name) { case "NbtByte": return "byte"; case "NbtByteArray": return "byte[]"; case "NbtCompound": return "NbtCompound"; // Note to myself to fix shit case "NbtDouble": return "double"; case "NbtFloat": return "float"; case "NbtInt": return "int"; case "NbtList": return "NbtList"; // Note to myself again case "NbtLong": return "long"; case "NbtShort": return "short"; case "NbtString": return "string"; default: return t.GetType().Name; } }
public void Write(NbtTag tag) { Write(tag, true); }
public Item(NbtTag tag) { this.tag = tag.Clone(); }
protected override void Remove(NbtTag item) { _list.Remove(item); item.Parent = null; }
public override NbtTag Insert(int index, NbtTag item) { if (item == null) throw new ArgumentNullException("item"); if (item.Parent != null) item = item.Clone(); _list.Insert(index, item); item.Parent = this; return item; }
public object MakeObject(NbtTag tag) { throw new NotImplementedException(); }
protected override void Remove(NbtTag item) { _dict.Remove(item.Name); item._name = null; item.Parent = null; }
public void ManipulatingList() { var sameTags = new NbtTag[] { new NbtInt( 0 ), new NbtInt( 1 ), new NbtInt( 2 ) }; NbtList list = new NbtList( "Test1", sameTags ); // testing enumerator int j = 0; foreach( NbtTag tag in list ) { Assert.AreEqual( tag, sameTags[j++] ); } // adding an item of correct type list.Add( new NbtInt( 3 ) ); list.Insert( 3, new NbtInt( 4 ) ); // adding an item of wrong type Assert.Throws<ArgumentException>( () => list.Add( new NbtString() ) ); Assert.Throws<ArgumentException>( () => list.Insert( 3, new NbtString() ) ); // testing array contents for( int i = 0; i < sameTags.Length; i++ ) { Assert.AreSame( sameTags[i], list[i] ); Assert.AreEqual( ( (NbtInt)list[i] ).Value, i ); } // test removal Assert.IsFalse( list.Remove( new NbtInt( 5 ) ) ); Assert.IsTrue( list.Remove( sameTags[0] ) ); list.RemoveAt( 0 ); Assert.Throws<ArgumentOutOfRangeException>( () => list.RemoveAt( 10 ) ); }
public void InterfaceImplementations() { NbtTag[] tagList = { new NbtByte("First", 1), new NbtShort("Second", 2), new NbtInt("Third", 3), new NbtLong("Fourth", 4L) }; // test NbtCompound(IEnumerable<NbtTag>) constructor var comp = new NbtCompound(tagList); // test .Names and .Tags collections CollectionAssert.AreEquivalent(new[] { "First", "Second", "Third", "Fourth" }, comp.Names); CollectionAssert.AreEquivalent(tagList, comp.Tags); // test ICollection and ICollection<NbtTag> boilerplate properties ICollection<NbtTag> iGenCollection = comp; Assert.IsFalse(iGenCollection.IsReadOnly); ICollection iCollection = comp; Assert.NotNull(iCollection.SyncRoot); Assert.IsFalse(iCollection.IsSynchronized); // test CopyTo() var tags = new NbtTag[iCollection.Count]; iCollection.CopyTo(tags, 0); CollectionAssert.AreEquivalent(comp, tags); // test non-generic GetEnumerator() var enumeratedTags = comp.ToList(); CollectionAssert.AreEquivalent(tagList, enumeratedTags); // test generic GetEnumerator() List<NbtTag> enumeratedTags2 = new List<NbtTag>(); var enumerator = comp.GetEnumerator(); while (enumerator.MoveNext()) { enumeratedTags2.Add(enumerator.Current); } CollectionAssert.AreEquivalent(tagList, enumeratedTags2); }
public object FillObject(object obj, NbtTag tag) { throw new NotImplementedException(); }
public void InterfaceImplementations() { NbtTag[] tagList = { new NbtByte("First", 1), new NbtShort("Second", 2), new NbtInt("Third", 3), new NbtLong("Fourth", 4L) }; // test NbtCompound(IEnumerable<NbtTag>) constructor var comp = new NbtCompound(tagList); // test .Names and .Tags collections CollectionAssert.AreEquivalent(comp.Names, new[] { "First", "Second", "Third", "Fourth" }); CollectionAssert.AreEquivalent(comp.Tags, tagList); // test ICollection and ICollection<NbtTag> boilerplate properties ICollection<NbtTag> iGenCollection = comp; Assert.IsFalse(iGenCollection.IsReadOnly); ICollection iCollection = comp; Assert.NotNull(iCollection.SyncRoot); Assert.IsFalse(iCollection.IsSynchronized); // test CopyTo() var tags = new NbtTag[iCollection.Count]; iCollection.CopyTo(tags, 0); CollectionAssert.AreEquivalent(tags, comp); // test GetEnumerator() var enumeratedTags = new List<NbtTag>(); foreach (NbtTag tag in comp) { enumeratedTags.Add(tag); } CollectionAssert.AreEquivalent(enumeratedTags, tagList); }
public void ManipulatingList() { var sameTags = new NbtTag[] { new NbtInt(0), new NbtInt(1), new NbtInt(2) }; var list = new NbtList("Test1", sameTags); // testing enumerator, indexer, Contains, and IndexOf int j = 0; foreach (NbtTag tag in list) { Assert.IsTrue(list.Contains(sameTags[j])); Assert.AreEqual(sameTags[j], tag); Assert.AreEqual(j, list.IndexOf(tag)); j++; } // adding an item of correct type list.Add(new NbtInt(3)); list.Insert(3, new NbtInt(4)); // adding an item of wrong type Assert.Throws<ArgumentException>(() => list.Add(new NbtString())); Assert.Throws<ArgumentException>(() => list.Insert(3, new NbtString())); Assert.Throws<ArgumentNullException>(() => list.Insert(3, null)); // testing array contents for (int i = 0; i < sameTags.Length; i++) { Assert.AreSame(sameTags[i], list[i]); Assert.AreEqual(i, ((NbtInt)list[i]).Value); } // test removal Assert.IsFalse(list.Remove(new NbtInt(5))); Assert.IsTrue(list.Remove(sameTags[0])); Assert.Throws<ArgumentNullException>(() => list.Remove(null)); list.RemoveAt(0); Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(10)); // Test some failure scenarios for Add: // adding a list to itself var loopList = new NbtList(); Assert.AreEqual(NbtTagType.Unknown, loopList.ListType); Assert.Throws<ArgumentException>(() => loopList.Add(loopList)); // adding same tag to multiple lists Assert.Throws<ArgumentException>(() => loopList.Add(list[0])); Assert.Throws<ArgumentException>(() => loopList.Insert(0, list[0])); // adding null tag Assert.Throws<ArgumentNullException>(() => loopList.Add(null)); // make sure that all those failed adds didn't affect the tag Assert.AreEqual(0, loopList.Count); Assert.AreEqual(NbtTagType.Unknown, loopList.ListType); // try creating a list with invalid tag type Assert.Throws<ArgumentOutOfRangeException>(() => new NbtList((NbtTagType)200)); }
public Coord(NbtTag x, NbtTag y, NbtTag z) { mX = (int)Math.Floor(((NbtDouble)x).Value); mY = (int)Math.Floor(((NbtDouble)y).Value); mZ = (int)Math.Floor(((NbtDouble)z).Value); }