Example #1
0
        public void ReadAsTagTest1()
        {
            // read various lists/compounds as tags
            var reader = new NbtReader(TestFiles.MakeReaderTest());

            reader.ReadToFollowing(); // skip root
            while (!reader.IsAtStreamEnd)
            {
                reader.ReadAsTag();
            }
            Assert.Throws <EndOfStreamException>(() => reader.ReadAsTag());
        }
Example #2
0
        public void ErrorTest()
        {
            var root = new NbtCompound("root");

            byte[] testData = new NbtFile(root).SaveToBuffer(NbtCompression.None);

            // creating NbtReader without a stream, or with a non-readable stream
            Assert.Throws <ArgumentNullException>(() => new NbtReader(null));
            Assert.Throws <ArgumentException>(() => new NbtReader(new NonReadableStream()));

            // corrupt the data
            testData[0] = 123;
            var reader = new NbtReader(new MemoryStream(testData));

            // attempt to use ReadValue when not at value
            Assert.Throws <InvalidOperationException>(() => reader.ReadValue());
            reader.CacheTagValues = true;
            Assert.Throws <InvalidOperationException>(() => reader.ReadValue());

            // attempt to read a corrupt stream
            Assert.Throws <NbtFormatException>(() => reader.ReadToFollowing());

            // make sure we've properly entered the error state
            Assert.IsTrue(reader.IsInErrorState);
            Assert.IsFalse(reader.HasName);
            Assert.Throws <InvalidReaderStateException>(() => reader.ReadToFollowing());
            Assert.Throws <InvalidReaderStateException>(() => reader.ReadListAsArray <int>());
            Assert.Throws <InvalidReaderStateException>(() => reader.ReadToNextSibling());
            Assert.Throws <InvalidReaderStateException>(() => reader.ReadToDescendant("derp"));
            Assert.Throws <InvalidReaderStateException>(() => reader.ReadAsTag());
            Assert.Throws <InvalidReaderStateException>(() => reader.Skip());
        }
Example #3
0
        public void EndTagTest()
        {
            using (MemoryStream ms = new MemoryStream()) {
                var root = new NbtCompound("root")
                {
                    new NbtInt("test", 0)
                };
                new NbtFile(root).SaveToStream(ms, NbtCompression.None);
                ms.Position = 0;

                NbtReader reader = new NbtReader(ms)
                {
                    SkipEndTags = false
                };
                reader.ReadToDescendant("test");
                Assert.AreEqual(NbtTagType.Int, reader.TagType);
                Assert.IsTrue(reader.ReadToNextSibling());

                // should be at root's End tag now
                Assert.AreEqual(NbtTagType.End, reader.TagType);
                Assert.IsFalse(reader.IsInErrorState);
                Assert.IsFalse(reader.IsAtStreamEnd);
                Assert.IsFalse(reader.IsCompound);
                Assert.IsFalse(reader.IsList);
                Assert.IsFalse(reader.IsListElement);
                Assert.IsFalse(reader.HasValue);
                Assert.IsFalse(reader.HasName);
                Assert.IsFalse(reader.HasLength);
                Assert.Throws <InvalidOperationException>(() => reader.ReadAsTag()); // Cannot create NbtTag from TAG_END

                // We done now
                Assert.IsFalse(reader.ReadToFollowing());
                Assert.IsTrue(reader.IsAtStreamEnd);
            }
        }
Example #4
0
        public void ReadAsTagTest4()
        {
            // read a bunch of lists as tags
            byte[] testData = new NbtFile(TestFiles.MakeListTest()).SaveToBuffer(NbtCompression.None);

            // first, read everything all-at-once
            {
                var reader = new NbtReader(new MemoryStream(testData));
                while (!reader.IsAtStreamEnd)
                {
                    Console.WriteLine(reader.ReadAsTag());
                }
            }

            // next, read each list individually
            {
                var reader = new NbtReader(new MemoryStream(testData));
                reader.ReadToFollowing(); // read to root
                reader.ReadToFollowing(); // read to first list tag
                while (!reader.IsAtStreamEnd)
                {
                    Console.WriteLine(reader.ReadAsTag());
                }
            }
        }
Example #5
0
        private static (string, Dictionary <string, Object>) GetNbtVal(MemoryStream ms)
        {
            string name       = "";
            var    nbt        = new NbtReader(ms, false);
            var    dictParams = new Dictionary <string, Object>();

            nbt.ReadToFollowing();
            if (!nbt.IsCompound)
            {
                throw new Exception("Could not read nbt");
            }

            if (nbt.ReadToDescendant("name"))
            {
                name = nbt.ReadValueAs <string>();

                nbt.ReadToNextSibling();
                while (nbt.TagType != NbtTagType.End)
                {
                    fNbt.Tags.NbtTag tag = nbt.ReadAsTag();
                    switch (tag.Name)
                    {
                    case "version":
                        continue;

                    case "states":
                        IEnumerable <fNbt.Tags.NbtTag> enumTag = (IEnumerable <fNbt.Tags.NbtTag>)tag;
                        foreach (var subtag in enumTag)
                        {
                            if ((subtag.Name == "direction") || (subtag.Name == "facing_direction") || (subtag.Name == "open_bit"))
                            {
                                int subtagvalue = GetTagValue(subtag);
                                dictParams.Add(subtag.Name, subtagvalue);
                            }
                            if ((subtag.Name == "color") || (subtag.Name == "lever_direction"))
                            {
                                if (subtag.TagType == NbtTagType.String)
                                {
                                    dictParams.Add(subtag.Name, subtag.StringValue);
                                }
                            }
                        }
                        break;

                    case "val":
                        int value = GetTagValue(tag);
                        dictParams.Add(tag.Name, value);
                        break;
                    }
                }
            }

            while (!nbt.IsAtStreamEnd)
            {
                nbt.ReadToFollowing();
            }

            return(name, dictParams);
        }
Example #6
0
 public static NbtCompound GetNbtCompoundFromBytes(byte[] data)
 {
     using (MemoryStream stream = new MemoryStream(data))
     {
         NbtReader reader = new NbtReader(stream);
         return((NbtCompound)reader.ReadAsTag());
     }
 }
Example #7
0
        static NbtFile PartialReadTestInternal(NbtFile comp)
        {
            byte[] testData = comp.SaveToBuffer(NbtCompression.None);
            var    reader   = new NbtReader(new PartialReadStream(new MemoryStream(testData)));
            var    root     = (NbtCompound)reader.ReadAsTag();

            return(new NbtFile(root));
        }
Example #8
0
        private static (string, Dictionary <string, Object>) GetNbtVal(MemoryStream ms)
        {
            string name       = "";
            var    nbt        = new NbtReader(ms, false);
            var    dictParams = new Dictionary <string, Object>();

            nbt.ReadToFollowing();
            if (!nbt.IsCompound)
            {
                throw new Exception("Could not read nbt");
            }

            if (nbt.ReadToDescendant("name"))
            {
                name = nbt.ReadValueAs <string>();

                nbt.ReadToNextSibling();
                while (nbt.TagType != NbtTagType.End)
                {
                    fNbt.Tags.NbtTag tag = nbt.ReadAsTag();
                    switch (tag.Name)
                    {
                    case "version":
                        continue;

                    case "states":
                        IEnumerable <fNbt.Tags.NbtTag> enumTag = (IEnumerable <fNbt.Tags.NbtTag>)tag;
                        foreach (var subtag in enumTag)
                        {
                            if ((subtag.Name == "direction") || (subtag.Name == "facing_direction") || (subtag.Name == "open_bit") || (subtag.Name == "multi_face_direction_bits") || (subtag.Name == "stripped_bit") || (subtag.Name == "wall_post_bit") || (subtag.Name == "button_pressed_bit") || (subtag.Name == "rail_direction") || (subtag.Name == "rail_data_bit") || (subtag.Name == "bite_counter") || (subtag.Name == "respawn_anchor_charge") || (subtag.Name == "growth") || (subtag.Name == "powered_bit") || (subtag.Name == "upper_block_bit") || (subtag.Name == "hanging") || (subtag.Name == "coral_direction") || (subtag.Name == "coral_hang_type_bit") || (subtag.Name == "dead_bit") || (subtag.Name == "end_portal_eye_bit") || (subtag.Name == "head_piece_bit") || (subtag.Name == "age"))
                            {
                                int subtagvalue = GetTagValue(subtag);
                                dictParams.Add(subtag.Name, subtagvalue);
                            }
                            if ((subtag.Name == "color") || (subtag.Name == "lever_direction") || (subtag.Name == "wall_block_type") || (subtag.Name == "pillar_axis") || (subtag.Name == "wood_type") || (subtag.Name == "old_log_type") || (subtag.Name == "new_log_type") || (subtag.Name == "old_leaf_type") || (subtag.Name == "new_leaf_type") || (subtag.Name == "sapling_type") || subtag.Name.StartsWith("wall_connection_type_") || (subtag.Name == "chisel_type") || subtag.Name.StartsWith("stone_slab_type") || (subtag.Name == "sponge_type") || (subtag.Name == "double_plant_type") || (subtag.Name == "flower_type") || (subtag.Name == "sand_type") || (subtag.Name == "stone_type") || (subtag.Name == "damage") || (subtag.Name == "dripstone_thickness") || (subtag.Name == "coral_color") || (subtag.Name == "monster_egg_stone_type") || (subtag.Name == "stone_brick_type"))
                            {
                                dictParams.Add(subtag.Name, subtag.StringValue);
                            }
                        }
                        break;

                    case "val":
                        int value = GetTagValue(tag);
                        dictParams.Add(tag.Name, value);
                        break;
                    }
                }
            }

            while (!nbt.IsAtStreamEnd)
            {
                nbt.ReadToFollowing();
            }

            return(name, dictParams);
        }
Example #9
0
        public void ReadAsTagTest3()
        {
            // read values as tags
            byte[] testData = new NbtFile(TestFiles.MakeValueTest()).SaveToBuffer(NbtCompression.None);
            var    reader   = new NbtReader(new MemoryStream(testData));
            var    root     = new NbtCompound("root");

            // skip root
            reader.ReadToFollowing();
            reader.ReadToFollowing();

            while (!reader.IsAtStreamEnd)
            {
                root.Add(reader.ReadAsTag());
            }

            TestFiles.AssertValueTest(new NbtFile(root));
        }
Example #10
0
 public void ReadAsTagTest2()
 {
     // read the whole thing as one tag
     byte[] testData = new NbtFile(TestFiles.MakeValueTest()).SaveToBuffer(NbtCompression.None);
     {
         var reader = new NbtReader(new MemoryStream(testData));
         var root   = (NbtCompound)reader.ReadAsTag();
         TestFiles.AssertValueTest(new NbtFile(root));
     }
     {
         // Try the same thing but with end tag skipping disabled
         var reader = new NbtReader(new MemoryStream(testData))
         {
             SkipEndTags = false
         };
         var root = (NbtCompound)reader.ReadAsTag();
         TestFiles.AssertValueTest(new NbtFile(root));
     }
 }
Example #11
0
        public IEnumerable <(Guid Uuid, string Name, int DimensionId, float[] Position)> GetPlayerData()
        {
            var playerKeyIndicator = Encoding.UTF8.GetBytes("player_server");

            // Get all records whose key begins with "player_server"
            var playerData = db
                             .Where(kvp => kvp.Key.Take(playerKeyIndicator.Length).SequenceEqual(playerKeyIndicator))
                             .Select(i => new
            {
                // Parse the UUID from the key
                PlayerUuid = Guid.Parse(Encoding.UTF8.GetString(i.Key.Skip(playerKeyIndicator.Length + 1).ToArray())),
                i.Value
            })
                             .ToList();

            if (!playerData.Any())
            {
                yield break;
            }

            foreach (var playerNbtData in playerData)
            {
                using var memoryStream = new MemoryStream(playerNbtData.Value);

                var nbtReader = new NbtReader(memoryStream, false);

                // Example Player NBT tag contents: https://gist.github.com/barrett777/d7c02000aace08c536f13fb1d3f1cf3b
                var playerTag = nbtReader.ReadAsTag();

                yield return
                    (
                    // This UUID different than the Minecraft Java edition UUID - I haven't been able to find a way to get a player name using this
                    // For now, I'll just rely on users manually entering names into a JSON file on the web server
                    Uuid : playerNbtData.PlayerUuid,
                    Name : $"Player {playerNbtData.PlayerUuid.ToString().Substring(0, 5)}",
                    DimensionId : playerTag["DimensionId"].IntValue,
                    Position : new[] { playerTag["Pos"][0].FloatValue, playerTag["Pos"][1].FloatValue, playerTag["Pos"][2].FloatValue }
                    );
            }
        }
Example #12
0
        public static RegionFile Read(string filename)
        {
            List <Column> columns = new List <Column>();
            FileStream    stream  = File.OpenRead(filename);

            byte[] mcaHeader = new byte[8192];
            stream.Read(mcaHeader, 0, 8192);
            stream.Seek(0, SeekOrigin.Begin);
            List <byte[]> chunkLocs = new List <byte[]>();

            for (int i = 0; i < 4096; i += 4)
            {
                byte[] inp = new byte[4];
                stream.Read(inp, 0, 4);
                chunkLocs.Add(inp);
            }

            foreach (byte[] bytes in chunkLocs)
            {
                if (((bytes[2] & 0xFF) | ((bytes[1] & 0xFF) << 8) | ((bytes[0] & 0x0F) << 16)) != 0)                       // Don't operate on ones which have an offset of 0. These have yet to be generated.
                {
                    int chunkPosition = ((bytes[2] & 0xFF) | ((bytes[1] & 0xFF) << 8) | ((bytes[0] & 0x0F) << 16)) * 4096; // Get the position of the chunk in bytes in the file.

                    int    sectorLength = bytes[3];                                                                        // How many sectors this chunk takes up. 1 sector = 4096 bytes
                    byte[] chunkPayload = new byte[(4096 * sectorLength) - 5];                                             // The contents of the chunk. Zlib compressed
                    stream.Seek(chunkPosition + 5, SeekOrigin.Begin);
                    stream.Read(chunkPayload, 0, (4096 * sectorLength) - 5);

                    MemoryStream memstr = new MemoryStream(chunkPayload);
                    memstr.ReadByte();
                    memstr.ReadByte();
                    NbtReader reader = new NbtReader(new DeflateStream(memstr, CompressionMode.Decompress));
                    columns.Add(new Column(((NbtCompound)reader.ReadAsTag()).Get <NbtCompound>("Level")));
                    //return new RegionFile(columns);
                }
            }
            return(new RegionFile(columns));
        }
Example #13
0
        public Region(int x, int y)
        {
            Console.WriteLine(Directory.GetCurrentDirectory());
            using (FileStream data = File.Open($"./world/region/r-{x}-{y}.mca", FileMode.Open))
            {
                Console.WriteLine("test");
                BinaryReader      reader = new BinaryReader(data);
                int               compressedChunkLength = (int)reader.ReadUInt32();
                CompressionScheme compressionScheme     = (CompressionScheme)reader.ReadByte();
                Stream            dataStream;
                if (compressionScheme == CompressionScheme.Zlib)
                {
                    dataStream = new ZlibStream(data, CompressionMode.Decompress);
                }
                else
                {
                    throw new NotImplementedException("GZIP not implemented");
                }

                NbtReader nbtReader = new NbtReader(dataStream);
                Console.WriteLine($"Name: {nbtReader.ReadAsTag().Name}");
            }
        }
        public void ReadAsTagTest4()
        {
            // read a bunch of lists as tags
            byte[] testData = new NbtFile(TestFiles.MakeListTest()).SaveToBuffer(NbtCompression.None);

            // first, read everything all-at-once
            {
                var reader = new NbtReader(new MemoryStream(testData));
                while (!reader.IsAtStreamEnd)
                {
                    Console.WriteLine(reader.ReadAsTag());
                }
            }

            // next, read each list individually
            {
                var reader = new NbtReader(new MemoryStream(testData));
                reader.ReadToFollowing(); // read to root
                reader.ReadToFollowing(); // read to first list tag
                while (!reader.IsAtStreamEnd)
                {
                    Console.WriteLine(reader.ReadAsTag());
                }
            }
        }
        public void ReadAsTagTest3()
        {
            // read values as tags
            byte[] testData = new NbtFile(TestFiles.MakeValueTest()).SaveToBuffer(NbtCompression.None);
            var reader = new NbtReader(new MemoryStream(testData));
            var root = new NbtCompound("root");

            // skip root
            reader.ReadToFollowing();
            reader.ReadToFollowing();

            while (!reader.IsAtStreamEnd)
            {
                root.Add(reader.ReadAsTag());
            }

            TestFiles.AssertValueTest(new NbtFile(root));
        }
 public void ReadAsTagTest2()
 {
     // read the whole thing as one tag
     byte[] testData = new NbtFile(TestFiles.MakeValueTest()).SaveToBuffer(NbtCompression.None);
     {
         var reader = new NbtReader(new MemoryStream(testData));
         var root = (NbtCompound) reader.ReadAsTag();
         TestFiles.AssertValueTest(new NbtFile(root));
     }
     {
         // Try the same thing but with end tag skipping disabled
         var reader = new NbtReader(new MemoryStream(testData))
         {
             SkipEndTags = false
         };
         var root = (NbtCompound) reader.ReadAsTag();
         TestFiles.AssertValueTest(new NbtFile(root));
     }
 }
 public void ReadAsTagTest1()
 {
     // read various lists/compounds as tags
     var reader = new NbtReader(TestFiles.MakeReaderTest());
     reader.ReadToFollowing(); // skip root
     while (!reader.IsAtStreamEnd)
     {
         reader.ReadAsTag();
     }
     Assert.Throws<EndOfStreamException>(() => reader.ReadAsTag());
 }
Example #18
0
        public ItemStack ReadSlot()
        {
            var slot = new ItemStack();

            var present = this.ReadBoolean();

            slot.Present = present;

            if (present)
            {
                slot.Id    = this.ReadVarInt();
                slot.Count = this.ReadSignedByte();

                var reader = new NbtReader(this);

                while (reader.ReadToFollowing())
                {
                    slot.Nbt = new ItemNbt();

                    if (reader.IsCompound)
                    {
                        var root = (NbtCompound)reader.ReadAsTag();
                        foreach (var tag in root)
                        {
                            Globals.PacketLogger.LogDebug($"Tag name: {tag.Name} | Type: {tag.TagType}");
                            switch (tag.Name.ToLower())
                            {
                            case "enchantments":
                            {
                                var enchantments = (NbtList)tag;

                                foreach (var enchant in enchantments)
                                {
                                    if (enchant is NbtCompound compound)
                                    {
                                        slot.Nbt.Enchantments.Add(new Enchantment
                                            {
                                                Id    = compound.Get <NbtString>("id").Value,
                                                Level = compound.Get <NbtShort>("lvl").Value
                                            });
                                    }
                                }

                                break;
                            }

                            case "storedenchantments":
                            {
                                var enchantments = (NbtList)tag;

                                Console.WriteLine($"List Type: {enchantments.ListType}");

                                foreach (var enchantment in enchantments)
                                {
                                    if (enchantment is NbtCompound compound)
                                    {
                                        slot.Nbt.StoredEnchantments.Add(new Enchantment
                                            {
                                                Id    = compound.Get <NbtString>("id").Value,
                                                Level = compound.Get <NbtShort>("lvl").Value
                                            });
                                    }
                                }
                                break;
                            }

                            case "slot":
                            {
                                slot.Nbt.Slot = tag.ByteValue;
                                break;
                            }

                            case "damage":
                            {
                                slot.Nbt.Damage = tag.IntValue;
                                break;
                            }

                            default:
                                break;
                            }
                        }
                        //slot.ItemNbt.Slot = compound.Get<NbtByte>("Slot").Value;
                        //slot.ItemNbt.Count = compound.Get<NbtByte>("Count").Value;
                        //slot.ItemNbt.Id = compound.Get<NbtShort>("id").Value;
                        //slot.ItemNbt.Damage = compound.Get<NbtShort>("Damage").Value;
                        //slot.ItemNbt.RepairCost = compound.Get<NbtInt>("RepairCost").Value;
                    }
                    else
                    {
                        Console.WriteLine($"Other Name: {reader.TagName}");
                    }
                }
            }

            return(slot);
        }
Example #19
0
 public void ReadAsTagTest2()
 {
     // read the whole thing as one tag
     byte[] testData = new NbtFile(TestFiles.MakeValueTest()).SaveToBuffer(NbtCompression.None);
     var reader = new NbtReader(new MemoryStream(testData));
     var root = (NbtCompound)reader.ReadAsTag();
     TestFiles.AssertValueTest(new NbtFile(root));
 }
Example #20
0
 public void ReadAsTagTest4()
 {
     // read a bunch of lists as tags
     byte[] testData = new NbtFile(TestFiles.MakeListTest()).SaveToBuffer(NbtCompression.None);
     var reader = new NbtReader(new MemoryStream(testData));
     //reader.ReadToFollowing(); // skip root
     while (!reader.IsAtStreamEnd) {
         Console.WriteLine(reader.ReadAsTag());
     }
 }
Example #21
0
        public ItemStack ReadItemStack()
        {
            var present = ReadBoolean();

            if (present)
            {
                var item = Registry.GetItem((short)ReadVarInt());

                var slot = new ItemStack(item.Type, ReadUnsignedByte())
                {
                    Present = present
                };

                var reader = new NbtReader(this);

                while (reader.ReadToFollowing())
                {
                    var itemMetaBuilder = new ItemMetaBuilder();

                    if (reader.IsCompound)
                    {
                        var root = (NbtCompound)reader.ReadAsTag();

                        foreach (var tag in root)
                        {
                            switch (tag.Name.ToUpperInvariant())
                            {
                            case "ENCHANTMENTS":
                            {
                                var enchantments = (NbtList)tag;

                                foreach (var enchant in enchantments)
                                {
                                    if (enchant is NbtCompound compound)
                                    {
                                        var id = compound.Get <NbtString>("id").Value;

                                        itemMetaBuilder.AddEnchantment(id.ToEnchantType(), compound.Get <NbtShort>("lvl").Value);
                                    }
                                }

                                break;
                            }

                            case "STOREDENCHANTMENTS":
                            {
                                var enchantments = (NbtList)tag;

                                //Globals.PacketLogger.LogDebug($"List Type: {enchantments.ListType}");

                                foreach (var enchantment in enchantments)
                                {
                                    if (enchantment is NbtCompound compound)
                                    {
                                        var id = compound.Get <NbtString>("id").Value;

                                        itemMetaBuilder.AddStoredEnchantment(id.ToEnchantType(), compound.Get <NbtShort>("lvl").Value);
                                    }
                                }
                                break;
                            }

                            case "SLOT":
                            {
                                itemMetaBuilder.WithSlot(tag.ByteValue);
                                //Console.WriteLine($"Setting slot: {itemMetaBuilder.Slot}");
                                break;
                            }

                            case "DAMAGE":
                            {
                                itemMetaBuilder.WithDurability(tag.IntValue);
                                //Globals.PacketLogger.LogDebug($"Setting damage: {tag.IntValue}");
                                break;
                            }

                            case "DISPLAY":
                            {
                                var display = (NbtCompound)tag;

                                foreach (var displayTag in display)
                                {
                                    if (displayTag.Name.EqualsIgnoreCase("name"))
                                    {
                                        itemMetaBuilder.WithName(displayTag.StringValue);
                                    }
                                    else if (displayTag.Name.EqualsIgnoreCase("lore"))
                                    {
                                        var loreTag = (NbtList)displayTag;

                                        foreach (var lore in loreTag)
                                        {
                                            itemMetaBuilder.AddLore(JsonConvert.DeserializeObject <ChatMessage>(lore.StringValue));
                                        }
                                    }
                                }
                                break;
                            }
                            }
                        }
                    }

                    slot.ItemMeta = itemMetaBuilder.Build();
                }

                return(slot);
            }

            return(null);
        }
Example #22
0
 public void ReadAsTagTest()
 {
     NbtReader reader = new NbtReader( MakeTest() );
     Console.WriteLine( reader.ReadAsTag().ToString() );
 }
Example #23
0
        public async Task <ItemStack> ReadSlotAsync()
        {
            var present = await this.ReadBooleanAsync();

            if (present)
            {
                var item = Registry.GetItem((short)await this.ReadVarIntAsync());

                var slot = new ItemStack(item.Type, await this.ReadByteAsync())
                {
                    Present = present
                };

                var reader = new NbtReader(this);

                while (reader.ReadToFollowing())
                {
                    var itemMetaBuilder = new ItemMetaBuilder();

                    if (reader.IsCompound)
                    {
                        var root = (NbtCompound)reader.ReadAsTag();

                        foreach (var tag in root)
                        {
                            switch (tag.Name.ToLower())
                            {
                            case "enchantments":
                            {
                                var enchantments = (NbtList)tag;

                                foreach (var enchant in enchantments)
                                {
                                    if (enchant is NbtCompound compound)
                                    {
                                        var id = compound.Get <NbtString>("id").Value;

                                        itemMetaBuilder.AddEnchantment(id.ToEnchantType(), compound.Get <NbtShort>("lvl").Value);
                                    }
                                }

                                break;
                            }

                            case "storedenchantments":
                            {
                                var enchantments = (NbtList)tag;

                                //Globals.PacketLogger.LogDebug($"List Type: {enchantments.ListType}");

                                foreach (var enchantment in enchantments)
                                {
                                    if (enchantment is NbtCompound compound)
                                    {
                                        var id = compound.Get <NbtString>("id").Value;

                                        itemMetaBuilder.AddStoredEnchantment(id.ToEnchantType(), compound.Get <NbtShort>("lvl").Value);
                                    }
                                }
                                break;
                            }

                            case "slot":
                            {
                                itemMetaBuilder.WithSlot(tag.ByteValue);
                                //Console.WriteLine($"Setting slot: {itemMetaBuilder.Slot}");
                                break;
                            }

                            case "damage":
                            {
                                itemMetaBuilder.WithDurability(tag.IntValue);
                                //Globals.PacketLogger.LogDebug($"Setting damage: {tag.IntValue}");
                                break;
                            }

                            case "display":
                            {
                                var display = (NbtCompound)tag;

                                foreach (var displayTag in display)
                                {
                                    if (displayTag.Name.EqualsIgnoreCase("name"))
                                    {
                                        itemMetaBuilder.WithName(displayTag.StringValue);
                                    }
                                    else if (displayTag.Name.EqualsIgnoreCase("lore"))
                                    {
                                        var loreTag = (NbtList)displayTag;

                                        foreach (var lore in loreTag)
                                        {
                                            itemMetaBuilder.AddLore(JsonConvert.DeserializeObject <ChatMessage>(lore.StringValue));
                                        }
                                    }
                                }
                                break;
                            }

                            default:
                                break;
                            }
                        }
                        //slot.ItemNbt.Slot = compound.Get<NbtByte>("Slot").Value;
                        //slot.ItemNbt.Count = compound.Get<NbtByte>("Count").Value;
                        //slot.ItemNbt.Id = compound.Get<NbtShort>("id").Value;
                        //slot.ItemNbt.Damage = compound.Get<NbtShort>("Damage").Value;
                        //slot.ItemNbt.RepairCost = compound.Get<NbtInt>("RepairCost").Value;
                    }

                    slot.ItemMeta = itemMetaBuilder.Build();
                }

                return(slot);
            }

            return(null);
        }
Example #24
0
        public void ReadAsTagTest()
        {
            NbtReader reader = new NbtReader(MakeTest());

            Console.WriteLine(reader.ReadAsTag().ToString());
        }
        public void ErrorTest()
        {
            var root = new NbtCompound("root");
            byte[] testData = new NbtFile(root).SaveToBuffer(NbtCompression.None);

            // creating NbtReader without a stream, or with a non-readable stream
            Assert.Throws<ArgumentNullException>(() => new NbtReader(null));
            Assert.Throws<ArgumentException>(() => new NbtReader(new NonReadableStream()));

            // corrupt the data
            testData[0] = 123;
            var reader = new NbtReader(new MemoryStream(testData));

            // attempt to use ReadValue when not at value
            Assert.Throws<InvalidOperationException>(() => reader.ReadValue());
            reader.CacheTagValues = true;
            Assert.Throws<InvalidOperationException>(() => reader.ReadValue());

            // attempt to read a corrupt stream
            Assert.Throws<NbtFormatException>(() => reader.ReadToFollowing());

            // make sure we've properly entered the error state
            Assert.True(reader.IsInErrorState);
            Assert.False(reader.HasName);
            Assert.Throws<InvalidReaderStateException>(() => reader.ReadToFollowing());
            Assert.Throws<InvalidReaderStateException>(() => reader.ReadListAsArray<int>());
            Assert.Throws<InvalidReaderStateException>(() => reader.ReadToNextSibling());
            Assert.Throws<InvalidReaderStateException>(() => reader.ReadToDescendant("derp"));
            Assert.Throws<InvalidReaderStateException>(() => reader.ReadAsTag());
            Assert.Throws<InvalidReaderStateException>(() => reader.Skip());
        }
Example #26
0
    public NbtCompound ReadNbtCompound()
    {
        var reader = new NbtReader(this);

        return(reader.IsCompound ? reader.ReadAsTag() as NbtCompound : new NbtCompound());
    }
 static NbtFile PartialReadTestInternal(NbtFile comp)
 {
     byte[] testData = comp.SaveToBuffer(NbtCompression.None);
     var reader = new NbtReader(new PartialReadStream(new MemoryStream(testData)));
     var root = (NbtCompound) reader.ReadAsTag();
     return new NbtFile(root);
 }
Example #28
0
        public void ListTest()
        {
            // write short (1-element) lists of every possible kind
            using (var ms = new MemoryStream()) {
                var writer = new NbtWriter(ms, "Test");
                writer.BeginList("LotsOfLists", NbtTagType.List, 11);
                {
                    writer.BeginList(NbtTagType.Byte, 1);
                    writer.WriteByte(1);
                    writer.EndList();

                    writer.BeginList(NbtTagType.ByteArray, 1);
                    writer.WriteByteArray(new byte[] {
                        1
                    });
                    writer.EndList();

                    writer.BeginList(NbtTagType.Compound, 1);
                    writer.BeginCompound();
                    writer.EndCompound();
                    writer.EndList();

                    writer.BeginList(NbtTagType.Double, 1);
                    writer.WriteDouble(1);
                    writer.EndList();

                    writer.BeginList(NbtTagType.Float, 1);
                    writer.WriteFloat(1);
                    writer.EndList();

                    writer.BeginList(NbtTagType.Int, 1);
                    writer.WriteInt(1);
                    writer.EndList();

                    writer.BeginList(NbtTagType.IntArray, 1);
                    writer.WriteIntArray(new[] {
                        1
                    });
                    writer.EndList();

                    writer.BeginList(NbtTagType.List, 1);
                    writer.BeginList(NbtTagType.List, 0);
                    writer.EndList();
                    writer.EndList();

                    writer.BeginList(NbtTagType.Long, 1);
                    writer.WriteLong(1);
                    writer.EndList();

                    writer.BeginList(NbtTagType.Short, 1);
                    writer.WriteShort(1);
                    writer.EndList();

                    writer.BeginList(NbtTagType.String, 1);
                    writer.WriteString("ponies");
                    writer.EndList();
                }
                writer.EndList();
                writer.EndCompound();
                writer.Finish();

                ms.Position = 0;
                var reader = new NbtReader(ms);
                Assert.DoesNotThrow(() => reader.ReadAsTag());
            }
        }
Example #29
0
        public void BigTest()
        {
            var fs = Assembly.GetExecutingAssembly().GetManifestResourceStream("Obsidian.Tests.Assets.bigtest.nbt");
            var decompressedStream = new MemoryStream();

            GZip.Decompress(fs, decompressedStream, false);

            decompressedStream.Position = 0;
            var reader = new NbtReader(decompressedStream);

            var main = reader.ReadAsTag() as NbtCompound;

            //Writing out the string to read ourselves
            output.WriteLine(main.ToString());

            //Begin reading

            Assert.Equal("Level", main.Name);

            Assert.Equal(NbtTagType.Compound, main.TagType);

            Assert.Equal(11, main.Count);

            var longTest = main.Get <NbtLong>("longTest");

            Assert.Equal(long.MaxValue, longTest.Value);

            var shortTest = main.Get <NbtShort>("shortTest");

            Assert.Equal(short.MaxValue, shortTest.Value);

            var stringTest = main.Get <NbtString>("stringTest");

            Assert.Equal("HELLO WORLD THIS IS A TEST STRING ÅÄÖ!", stringTest.Value);

            var floatTest = main.Get <NbtFloat>("floatTest");

            Assert.Equal(0.49823147058486938, floatTest.Value);

            var intTest = main.Get <NbtInt>("intTest");

            Assert.Equal(int.MaxValue, intTest.Value);

            var byteTest = main.Get <NbtByte>("byteTest");

            Assert.Equal(127, byteTest.Value);

            var doubleTest = main.Get <NbtDouble>("doubleTest");

            Assert.Equal(0.49312871321823148, doubleTest.Value);

            var byteArrayTest = main.Get <NbtByteArray>("byteArrayTest (the first 1000 values of (n*n*255+n*7)%100, starting with n=0 (0, 62, 34, 16, 8, ...))");

            Assert.Equal(1000, byteArrayTest.Value.Length);

            for (int n = 0; n < 1000; n++)
            {
                Assert.Equal((n * n * 255 + n * 7) % 100, byteArrayTest.Value[n]);
            }

            #region nested compounds
            var nestedCompound = main.Get <NbtCompound>("nested compound test");
            Assert.Equal(2, nestedCompound.Count);

            var ham = nestedCompound.Get <NbtCompound>("ham");
            Assert.Equal(2, ham.Count);

            Assert.Equal("Hampus", ham.Get <NbtString>("name").Value);
            Assert.Equal(0.75, ham.Get <NbtFloat>("value").Value);

            var egg = nestedCompound.Get <NbtCompound>("egg");
            Assert.Equal(2, egg.Count);
            Assert.Equal("Eggbert", egg.Get <NbtString>("name").Value);
            Assert.Equal(0.5, egg.Get <NbtFloat>("value").Value);
            #endregion nested compounds

            #region lists
            var listLongTest = main.Get <NbtList>("listTest (long)");
            Assert.Equal(5, listLongTest.Count);

            var count = 11;

            foreach (var item in listLongTest)
            {
                Assert.Equal(count++, item.LongValue);
            }


            var listCompoundTest = main.Get <NbtList>("listTest (compound)");
            Assert.Equal(2, listCompoundTest.Count);

            var compound1 = listCompoundTest[0] as NbtCompound;
            Assert.Equal("Compound tag #0", compound1.Get <NbtString>("name").Value);
            Assert.Equal(1264099775885, compound1.Get <NbtLong>("created-on").Value);


            var compound2 = listCompoundTest[1] as NbtCompound;
            Assert.Equal("Compound tag #1", compound2.Get <NbtString>("name").Value);
            Assert.Equal(1264099775885, compound2.Get <NbtLong>("created-on").Value);
            #endregion lists
        }
Example #30
0
        public void ListTest()
        {
            // write short (1-element) lists of every possible kind
            using (var ms = new MemoryStream()) {
                var writer = new NbtWriter(ms, "Test");
                writer.BeginList("LotsOfLists", NbtTagType.List, 11);
                {
                    writer.BeginList(NbtTagType.Byte, 1);
                    writer.WriteByte(1);
                    writer.EndList();

                    writer.BeginList(NbtTagType.ByteArray, 1);
                    writer.WriteByteArray(new byte[] {
                        1
                    });
                    writer.EndList();

                    writer.BeginList(NbtTagType.Compound, 1);
                    writer.BeginCompound();
                    writer.EndCompound();
                    writer.EndList();

                    writer.BeginList(NbtTagType.Double, 1);
                    writer.WriteDouble(1);
                    writer.EndList();

                    writer.BeginList(NbtTagType.Float, 1);
                    writer.WriteFloat(1);
                    writer.EndList();

                    writer.BeginList(NbtTagType.Int, 1);
                    writer.WriteInt(1);
                    writer.EndList();

                    writer.BeginList(NbtTagType.IntArray, 1);
                    writer.WriteIntArray(new[] {
                        1
                    });
                    writer.EndList();

                    writer.BeginList(NbtTagType.List, 1);
                    writer.BeginList(NbtTagType.List, 0);
                    writer.EndList();
                    writer.EndList();

                    writer.BeginList(NbtTagType.Long, 1);
                    writer.WriteLong(1);
                    writer.EndList();

                    writer.BeginList(NbtTagType.Short, 1);
                    writer.WriteShort(1);
                    writer.EndList();

                    writer.BeginList(NbtTagType.String, 1);
                    writer.WriteString("ponies");
                    writer.EndList();
                }
                writer.EndList();
                Assert.IsFalse(writer.IsDone);
                writer.EndCompound();
                Assert.IsTrue(writer.IsDone);
                writer.Finish();

                ms.Position = 0;
                var reader = new NbtReader(ms);
                Assert.DoesNotThrow(() => reader.ReadAsTag());
            }
        }