Example #1
0
        public void SkippingTagsOnFileLoad()
        {
            var loadedFile = new NbtFile();
            loadedFile.LoadFromFile("TestFiles/bigtest.nbt",
                                    NbtCompression.None,
                                    tag => tag.Name != "nested compound test");
            Assert.IsFalse(loadedFile.RootTag.Contains("nested compound test"));
            Assert.IsTrue(loadedFile.RootTag.Contains("listTest (long)"));

            loadedFile.LoadFromFile("TestFiles/bigtest.nbt",
                                    NbtCompression.None,
                                    tag => tag.TagType != NbtTagType.Float || tag.Parent.Name != "Level");
            Assert.IsFalse(loadedFile.RootTag.Contains("floatTest"));
            Assert.AreEqual(0.75f, loadedFile.RootTag["nested compound test"]["ham"]["value"].FloatValue);

            loadedFile.LoadFromFile("TestFiles/bigtest.nbt",
                                    NbtCompression.None,
                                    tag => tag.Name != "listTest (long)");
            Assert.IsFalse(loadedFile.RootTag.Contains("listTest (long)"));
            Assert.IsTrue(loadedFile.RootTag.Contains("byteTest"));

            loadedFile.LoadFromFile("TestFiles/bigtest.nbt",
                                    NbtCompression.None,
                                    tag => false);
            Assert.AreEqual(0, loadedFile.RootTag.Count);
        }
Example #2
0
 public void LoadingBigFileGZip()
 {
     var file = new NbtFile();
     long length = file.LoadFromFile(TestFiles.BigGZip);
     TestFiles.AssertNbtBigFile(file);
     Assert.AreEqual(length, new FileInfo(TestFiles.BigGZip).Length);
 }
Example #3
0
        public void ByteArrayFromStream()
        {
            var data = new byte[64*1024];
            for (int i = 0; i < data.Length; i++) {
                data[i] = unchecked((byte)i);
            }

            using (var ms = new MemoryStream()) {
                var writer = new NbtWriter(ms, "root");
                {
                    byte[] buffer = new byte[1024];
                    using (var dataStream = new NonSeekableStream(new MemoryStream(data))) {
                        writer.WriteByteArray("byteArray1", dataStream, data.Length);
                    }
                    using (var dataStream = new NonSeekableStream(new MemoryStream(data))) {
                        writer.WriteByteArray("byteArray2", dataStream, data.Length, buffer);
                    }
                    using (var dataStream = new NonSeekableStream(new MemoryStream(data))) {
                        writer.WriteByteArray("byteArray3", dataStream, 1);
                    }
                    using (var dataStream = new NonSeekableStream(new MemoryStream(data))) {
                        writer.WriteByteArray("byteArray4", dataStream, 1, buffer);
                    }

                    writer.BeginList("innerLists", NbtTagType.ByteArray, 4);
                    using (var dataStream = new NonSeekableStream(new MemoryStream(data))) {
                        writer.WriteByteArray(dataStream, data.Length);
                    }
                    using (var dataStream = new NonSeekableStream(new MemoryStream(data))) {
                        writer.WriteByteArray(dataStream, data.Length, buffer);
                    }
                    using (var dataStream = new NonSeekableStream(new MemoryStream(data))) {
                        writer.WriteByteArray(dataStream, 1);
                    }
                    using (var dataStream = new NonSeekableStream(new MemoryStream(data))) {
                        writer.WriteByteArray(dataStream, 1, buffer);
                    }
                    writer.EndList();
                }
                writer.EndCompound();
                writer.Finish();

                ms.Position = 0;
                var file = new NbtFile();
                file.LoadFromStream(ms, NbtCompression.None);
                CollectionAssert.AreEqual(data, file.RootTag["byteArray1"].ByteArrayValue);
                CollectionAssert.AreEqual(data, file.RootTag["byteArray2"].ByteArrayValue);
                Assert.AreEqual(1, file.RootTag["byteArray3"].ByteArrayValue.Length);
                Assert.AreEqual(data[0], file.RootTag["byteArray3"].ByteArrayValue[0]);
                Assert.AreEqual(1, file.RootTag["byteArray4"].ByteArrayValue.Length);
                Assert.AreEqual(data[0], file.RootTag["byteArray4"].ByteArrayValue[0]);

                CollectionAssert.AreEqual(data, file.RootTag["innerLists"][0].ByteArrayValue);
                CollectionAssert.AreEqual(data, file.RootTag["innerLists"][1].ByteArrayValue);
                Assert.AreEqual(1, file.RootTag["innerLists"][2].ByteArrayValue.Length);
                Assert.AreEqual(data[0], file.RootTag["innerLists"][2].ByteArrayValue[0]);
                Assert.AreEqual(1, file.RootTag["innerLists"][3].ByteArrayValue.Length);
                Assert.AreEqual(data[0], file.RootTag["innerLists"][3].ByteArrayValue[0]);
            }
        }
Example #4
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 #5
0
 public void SkippingLists()
 {
     {
         var file = new NbtFile(TestFiles.MakeListTest());
         byte[] savedFile = file.SaveToBuffer(NbtCompression.None);
         file.LoadFromBuffer(savedFile, 0, savedFile.Length, NbtCompression.None,
                             tag => tag.TagType != NbtTagType.List);
         Assert.AreEqual(0, file.RootTag.Count);
     }
     {
         // Check list-compound interaction
         NbtCompound comp = new NbtCompound("root") {
             new NbtCompound("compOfLists") {
                 new NbtList("listOfComps") {
                     new NbtCompound {
                         new NbtList("emptyList", NbtTagType.Compound)
                     }
                 }
             }
         };
         var file = new NbtFile(comp);
         byte[] savedFile = file.SaveToBuffer(NbtCompression.None);
         file.LoadFromBuffer(savedFile, 0, savedFile.Length, NbtCompression.None,
                             tag => tag.TagType != NbtTagType.List);
         Assert.AreEqual(1, file.RootTag.Count);
     }
 }
Example #6
0
        public void TestNbtSmallFileLoadingUncompressed()
        {
            var file = new NbtFile();
            file.LoadFile("TestFiles/test.nbt", false);

            AssertNbtSmallFile(file);
        }
Example #7
0
        public void TestNbtSmallFileLoading()
        {
            var file = new NbtFile();
            file.LoadFile("TestFiles/test.nbt.gz");

            AssertNbtSmallFile(file);
        }
Example #8
0
 public void LoadingBigFileZLib()
 {
     var file = new NbtFile();
     int length = file.LoadFromFile(TestFiles.BigZLib);
     TestFiles.AssertNbtBigFile(file);
     Assert.AreEqual(length, new FileInfo(TestFiles.BigZLib).Length);
 }
Example #9
0
 public void SkippingLists()
 {
     var file = new NbtFile(TestFiles.MakeListTest());
     byte[] savedFile = file.SaveToBuffer(NbtCompression.None);
     file.LoadFromBuffer(savedFile, 0, savedFile.Length, NbtCompression.None, tag => false);
     Assert.AreEqual(file.RootTag.Count, 0);
 }
Example #10
0
 public void ReloadUncompressed()
 {
     NbtFile loadedFile = new NbtFile( "TestFiles/bigtest.nbt", NbtCompression.AutoDetect );
     loadedFile.SaveToFile( "TestTemp/bigtest.nbt", NbtCompression.None );
     loadedFile.LoadFromFile( "TestTemp/bigtest.nbt", NbtCompression.AutoDetect );
     AssertNbtBigFile( loadedFile );
 }
Example #11
0
 public void LoadingBigFileZLib()
 {
     var file = new NbtFile();
     int length = file.LoadFromFile( "TestFiles/bigtest.nbt.z" );
     AssertNbtBigFile( file );
     Assert.AreEqual( length, new FileInfo( "TestFiles/bigtest.nbt.z" ).Length );
 }
Example #12
0
 public void LoadingBigFileBuffer()
 {
     byte[] fileBytes = File.ReadAllBytes( "TestFiles/bigtest.nbt" );
     var file = new NbtFile();
     int length = file.LoadFromBuffer( fileBytes, 0, fileBytes.Length, NbtCompression.AutoDetect, null );
     AssertNbtBigFile( file );
     Assert.AreEqual( length, new FileInfo( "TestFiles/bigtest.nbt" ).Length );
 }
Example #13
0
 public void HugeNbtFileTest()
 {
     byte[] val = new byte[1024*1024*1024];
     NbtCompound root = new NbtCompound("root") {
         new NbtByteArray("payload1") {
             Value = val
         }
     };
     NbtFile file = new NbtFile(root);
     file.SaveToStream(Stream.Null, NbtCompression.None);
 }
Example #14
0
        public void SkippingValuesInCompoundTest()
        {
            NbtCompound root = TestFiles.MakeValueTest();
            NbtCompound nestedComp = TestFiles.MakeValueTest();
            nestedComp.Name = "NestedComp";
            root.Add(nestedComp);

            var file = new NbtFile(root);
            byte[] savedFile = file.SaveToBuffer(NbtCompression.None);
            file.LoadFromBuffer(savedFile, 0, savedFile.Length, NbtCompression.None, tag => false);
            Assert.AreEqual(0, file.RootTag.Count);
        }
Example #15
0
 public void LoadingBigFileStream()
 {
     byte[] fileBytes = File.ReadAllBytes(TestFiles.Big);
     using (var ms = new MemoryStream(fileBytes)) {
         using (var nss = new NonSeekableStream(ms)) {
             var file = new NbtFile();
             long length = file.LoadFromStream(nss, NbtCompression.None, null);
             TestFiles.AssertNbtBigFile(file);
             Assert.AreEqual(length, new FileInfo(TestFiles.Big).Length);
         }
     }
 }
Example #16
0
        public void LoadingBigFileBuffer()
        {
            byte[] fileBytes = File.ReadAllBytes(TestFiles.Big);
            var file = new NbtFile();

            Assert.Throws<ArgumentNullException>(
                () => file.LoadFromBuffer(null, 0, fileBytes.Length, NbtCompression.AutoDetect, null));

            long length = file.LoadFromBuffer(fileBytes, 0, fileBytes.Length, NbtCompression.AutoDetect, null);
            TestFiles.AssertNbtBigFile(file);
            Assert.AreEqual(length, new FileInfo(TestFiles.Big).Length);
        }
Example #17
0
 public void LoadingBigFileStream()
 {
     byte[] fileBytes = File.ReadAllBytes( "TestFiles/bigtest.nbt" );
     using( MemoryStream ms = new MemoryStream( fileBytes ) ) {
         using( NonSeekableStream nss = new NonSeekableStream( ms ) ) {
             var file = new NbtFile();
             int length = file.LoadFromStream( nss, NbtCompression.None, null );
             AssertNbtBigFile( file );
             Assert.AreEqual( length, new FileInfo( "TestFiles/bigtest.nbt" ).Length );
         }
     }
 }
Example #18
0
        public void TestNbtSmallFileSavingUncompressed()
        {
            var file = new NbtFile
                           {
                               RootTag = new NbtCompound("hello world", new NbtTag[]
                                                                            {
                                                                                new NbtString("name", "Bananrama")
                                                                            })
                           };

            file.SaveFile("TestTemp/test.nbt", false);

            FileAssert.AreEqual("TestFiles/test.nbt", "TestTemp/test.nbt");
        }
Example #19
0
        public void CacheTagValuesTest()
        {
            byte[] testData = new NbtFile(TestFiles.MakeValueTest()).SaveToBuffer(NbtCompression.None);
            var reader = new NbtReader(new MemoryStream(testData));
            Assert.IsFalse(reader.CacheTagValues);
            reader.CacheTagValues = true;
            Assert.IsTrue(reader.ReadToFollowing()); // root

            Assert.IsTrue(reader.ReadToFollowing()); // byte
            Assert.AreEqual(reader.ReadValue(), 1);
            Assert.AreEqual(reader.ReadValue(), 1);
            Assert.IsTrue(reader.ReadToFollowing()); // short
            Assert.AreEqual(reader.ReadValue(), 2);
            Assert.AreEqual(reader.ReadValue(), 2);
            Assert.IsTrue(reader.ReadToFollowing()); // int
            Assert.AreEqual(reader.ReadValue(), 3);
            Assert.AreEqual(reader.ReadValue(), 3);
            Assert.IsTrue(reader.ReadToFollowing()); // long
            Assert.AreEqual(reader.ReadValue(), 4L);
            Assert.AreEqual(reader.ReadValue(), 4L);
            Assert.IsTrue(reader.ReadToFollowing()); // float
            Assert.AreEqual(reader.ReadValue(), 5f);
            Assert.AreEqual(reader.ReadValue(), 5f);
            Assert.IsTrue(reader.ReadToFollowing()); // double
            Assert.AreEqual(reader.ReadValue(), 6d);
            Assert.AreEqual(reader.ReadValue(), 6d);
            Assert.IsTrue(reader.ReadToFollowing()); // byteArray
            CollectionAssert.AreEqual((byte[])reader.ReadValue(),
                                      new byte[] {
                                          10, 11, 12
                                      });
            CollectionAssert.AreEqual((byte[])reader.ReadValue(),
                                      new byte[] {
                                          10, 11, 12
                                      });
            Assert.IsTrue(reader.ReadToFollowing()); // intArray
            CollectionAssert.AreEqual((int[])reader.ReadValue(),
                                      new[] {
                                          20, 21, 22
                                      });
            CollectionAssert.AreEqual((int[])reader.ReadValue(),
                                      new[] {
                                          20, 21, 22
                                      });
            Assert.IsTrue(reader.ReadToFollowing()); // string
            Assert.AreEqual(reader.ReadValue(), "123");
            Assert.AreEqual(reader.ReadValue(), "123");
        }
Example #20
0
        public void GlobalsTest()
        {
            Assert.AreEqual(NbtFile.DefaultBufferSize, new NbtFile(new NbtCompound("Foo")).BufferSize);
            Assert.Throws<ArgumentOutOfRangeException>(() => NbtFile.DefaultBufferSize = -1);
            NbtFile.DefaultBufferSize = 12345;
            Assert.AreEqual(12345, NbtFile.DefaultBufferSize);

            // Newly-created NbtFiles should use default buffer size
            NbtFile tempFile = new NbtFile(new NbtCompound("Foo"));
            Assert.AreEqual(NbtFile.DefaultBufferSize, tempFile.BufferSize);
            Assert.Throws<ArgumentOutOfRangeException>(() => tempFile.BufferSize = -1);
            tempFile.BufferSize = 54321;
            Assert.AreEqual(54321, tempFile.BufferSize);

            // Changing default buffer size should not retroactively change already-existing NbtFiles' buffer size.
            NbtFile.DefaultBufferSize = 8192;
            Assert.AreEqual(54321, tempFile.BufferSize);
        }
        private void UpdateMinecraftWorlds()
        {
            List <WorldItem> worlds = new List <WorldItem>();

            string minecraftSavesPath = Path.Join(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "\\.minecraft\\saves");

            string[] paths = Directory.GetDirectories(minecraftSavesPath);

            foreach (string dir in paths)
            {
                //check if leveldata and levelname can be determined
                try {
                    NbtFile level = new NbtFile(Path.Join(dir, "/level.dat"));
                    string  name  = level.RootTag.Get <NbtCompound>("Data").Get <NbtString>("LevelName").Value.ToString();
                    worlds.Add(new WorldItem {
                        name = name, path = dir
                    });
                } catch { }
            }

            WorldSelection.DataSource = worlds;
        }
Example #22
0
        protected bool Equals(Item other)
        {
            if (Id != other.Id || Metadata != other.Metadata)
            {
                return(false);
            }
            if (ExtraData == null ^ other.ExtraData == null)
            {
                return(false);
            }

            byte[] saveToBuffer = null;
            if (other.ExtraData != null)
            {
                other.ExtraData.Name = string.Empty;
                saveToBuffer         = new NbtFile(other.ExtraData).SaveToBuffer(NbtCompression.None);
            }

            byte[] saveToBuffer2 = null;
            if (ExtraData != null)
            {
                ExtraData.Name = string.Empty;
                saveToBuffer2  = new NbtFile(ExtraData).SaveToBuffer(NbtCompression.None);
            }
            var nbtCheck = !(saveToBuffer == null ^ saveToBuffer2 == null);

            if (nbtCheck)
            {
                if (saveToBuffer == null)
                {
                    nbtCheck = true;
                }
                else
                {
                    nbtCheck = saveToBuffer.SequenceEqual(saveToBuffer2);
                }
            }
            return(nbtCheck);
        }
Example #23
0
        public void TestNbtListType()
        {
            var file = new NbtFile();
            file.RootTag = new NbtCompound("ListTypeTest");

            NbtTagType mytype = NbtTagType.TAG_Compound;

            NbtList list = new NbtList("Entities", null, mytype);
            file.RootTag.Tags.Add(list);

            file.SaveFile("TestFiles/NbtListType.nbt");

            NbtFile read = new NbtFile();
            read.LoadFile("TestFiles/NbtListType.nbt");
            Assert.NotNull(read);
            Console.WriteLine(read.RootTag.ToString());

            NbtList readlist = (NbtList)read.RootTag.Tags.ToArray()[0];
            Assert.NotNull(readlist);

            Assert.AreEqual(mytype, readlist.ListType);
        }
        public void SaveLevelInfo(LevelInfo level)
        {
            if (!Directory.Exists(BasePath))
            {
                Directory.CreateDirectory(BasePath);
            }
            else
            {
                return;
            }

            if (LevelInfo.SpawnY <= 0)
            {
                LevelInfo.SpawnY = 256;
            }

            NbtFile file    = new NbtFile();
            NbtTag  dataTag = file.RootTag["Data"] = new NbtCompound("Data");

            level.SaveToNbt(dataTag);
            file.SaveToFile(Path.Combine(BasePath, "level.dat"), NbtCompression.ZLib);
        }
Example #25
0
    public void WriteTagTest()
    {
        using var ms = new MemoryStream();

        var writer = new NbtWriter(ms, "root");

        {
            foreach (NbtTag tag in TestFiles.MakeValueTest().Tags)
            {
                writer.WriteTag(tag);
            }
            writer.EndCompound();
            Assert.True(writer.IsDone);
            writer.Finish();
        }
        ms.Position = 0;
        var  file      = new NbtFile();
        long bytesRead = file.LoadFromBuffer(ms.ToArray(), 0, (int)ms.Length, NbtCompression.None);

        Assert.Equal(bytesRead, ms.Length);
        TestFiles.AssertValueTest(file);
    }
Example #26
0
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string filename1 = "";

            //DDS test;
            openFileDialog.Filter           = "Schematic Files .schematic | *.schematic";
            openFileDialog.Title            = "Select a Schematic";
            openFileDialog.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.Personal);

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                NbtFile test = new NbtFile(openFileDialog.FileName, true);
                test.LoadFile();
                AssertNbtBigFile(test);
                paintIt     = true;
                this.Width  = rXmax * 20;
                this.Height = rYmax * 20;
                this.Refresh();

                Console.WriteLine("CLICK!");
            }
        }
Example #27
0
        public void SkippingTagsOnFileLoad()
        {
            NbtFile loadedFile = new NbtFile();

            loadedFile.LoadFromFile("TestFiles/bigtest.nbt",
                                    NbtCompression.None,
                                    tag => tag.Name != "nested compound test");
            Assert.IsFalse(loadedFile.RootTag.Contains("nested compound test"));
            Assert.IsTrue(loadedFile.RootTag.Contains("listTest (long)"));

            loadedFile.LoadFromFile("TestFiles/bigtest.nbt",
                                    NbtCompression.None,
                                    tag => tag.TagType != NbtTagType.Float || tag.Parent.Name != "Level");
            Assert.IsFalse(loadedFile.RootTag.Contains("floatTest"));
            Assert.AreEqual(loadedFile.RootTag["nested compound test"]["ham"]["value"].FloatValue, 0.75);

            loadedFile.LoadFromFile("TestFiles/bigtest.nbt",
                                    NbtCompression.None,
                                    tag => tag.Name != "listTest (long)");
            Assert.IsFalse(loadedFile.RootTag.Contains("listTest (long)"));
            Assert.IsTrue(loadedFile.RootTag.Contains("byteTest"));
        }
Example #28
0
        public void NullParameterTest()
        {
            Assert.Throws <ArgumentNullException>(() => new NbtFile((NbtCompound)null));
            Assert.Throws <ArgumentNullException>(() => new NbtFile((string)null));

            NbtFile file = new NbtFile();

            Assert.Throws <ArgumentNullException>(() => file.LoadFromBuffer(null, 0, 1, NbtCompression.None));
            Assert.Throws <ArgumentNullException>(() => file.LoadFromBuffer(null, 0, 1, NbtCompression.None, tag => true));
            Assert.Throws <ArgumentNullException>(() => file.LoadFromFile(null));
            Assert.Throws <ArgumentNullException>(() => file.LoadFromFile(null, NbtCompression.None, tag => true));
            Assert.Throws <ArgumentNullException>(() => file.LoadFromStream(null, NbtCompression.AutoDetect));
            Assert.Throws <ArgumentNullException>(() => file.LoadFromStream(null, NbtCompression.AutoDetect, tag => true));

            Assert.Throws <ArgumentNullException>(() => file.SaveToBuffer(null, 0, NbtCompression.None));
            Assert.Throws <ArgumentNullException>(() => file.SaveToFile(null, NbtCompression.None));
            Assert.Throws <ArgumentNullException>(() => file.SaveToStream(null, NbtCompression.None));

            Assert.Throws <ArgumentNullException>(() => NbtFile.ReadRootTagName(null));
            Assert.Throws <ArgumentNullException>(
                () => NbtFile.ReadRootTagName((Stream)null, NbtCompression.None, true, 0));
        }
Example #29
0
        public void Save()
        {
            lock (Regions)
            {
                foreach (var region in Regions)
                {
                    region.Value.Save(Path.Combine(BaseDirectory, Region.GetRegionFileName(region.Key)));
                }
            }
            var file = new NbtFile();

            file.RootTag.Add(new NbtCompound("SpawnPoint", new[]
            {
                new NbtInt("X", this.SpawnPoint.X),
                new NbtInt("Y", this.SpawnPoint.Y),
                new NbtInt("Z", this.SpawnPoint.Z)
            }));
            file.RootTag.Add(new NbtInt("Seed", this.Seed));
            file.RootTag.Add(new NbtString("ChunkProvider", this.ChunkProvider.GetType().FullName));
            file.RootTag.Add(new NbtString("Name", Name));
            file.SaveToFile(Path.Combine(this.BaseDirectory, "manifest.nbt"), NbtCompression.ZLib);
        }
Example #30
0
        public static List <WorldData> getSavedWorldData()
        {
            List <WorldData> worlds = new List <WorldData>();

            string[] names = Directory.GetDirectories("saves/");
            foreach (string folderName in names)
            {
                string dataFile = folderName + "/world.nbt";
                if (File.Exists(dataFile))
                {
                    NbtFile file = new NbtFile();
                    file.LoadFromFile(dataFile);
                    WorldData data = new WorldData(folderName.Substring(folderName.LastIndexOf('/') + 1, folderName.Length - 1 - folderName.LastIndexOf('/')));
                    data.readFromNbt(file.RootTag);
                    worlds.Add(data);
                }
            }

            worlds.Sort((i2, i1) => DateTime.Compare(i1.lastLoaded, i2.lastLoaded));

            return(worlds);
        }
Example #31
0
        protected override Dictionary <long, Map> LoadMaps()
        {
            var maps = new Dictionary <long, Map>();

            OpenDB();
            // thank you A Cynodont for help with this section
            const string MapKeyword = "map";
            var          iterator   = BedrockDB.CreateIterator();

            iterator.Seek(MapKeyword);
            while (iterator.IsValid())
            {
                var name = iterator.StringKey();
                if (name.StartsWith(MapKeyword))
                {
                    if (MapString(name, out long number))
                    {
                        NbtFile nbtfile = new NbtFile();
                        nbtfile.BigEndian = false;
                        byte[] data = iterator.Value();
                        nbtfile.LoadFromBuffer(data, 0, data.Length, NbtCompression.AutoDetect);
                        var colors = nbtfile.RootTag["colors"].ByteArrayValue;
                        // skip completely blank maps (bedrock likes generating pointless parents)
                        if (!colors.All(x => x == 0))
                        {
                            maps.Add(number, new BedrockMap(colors));
                        }
                    }
                }
                else
                {
                    break;
                }
                iterator.Next();
            }
            iterator.Dispose();
            CloseDB();
            return(maps);
        }
Example #32
0
        public void ReadValueTest()
        {
            var root = new NbtCompound("root")
            {
                new NbtByte("byte", 1),
                new NbtShort("short", 2),
                new NbtInt("int", 3),
                new NbtLong("long", 4),
                new NbtFloat("float", 5),
                new NbtDouble("double", 6),
                new NbtByteArray("byteArray", new byte[] { 10, 11, 12 }),
                new NbtIntArray("intArray", new[] { 20, 21, 22 }),
                new NbtString("string", "23")
            };
            var testData = new NbtFile(root).SaveToBuffer(NbtCompression.None);
            var reader   = new NbtReader(new MemoryStream(testData));

            Assert.IsTrue(reader.ReadToFollowing());             // root

            Assert.IsTrue(reader.ReadToFollowing());             // byte
            Assert.AreEqual(reader.ReadValue(), 1);
            Assert.IsTrue(reader.ReadToFollowing());             // short
            Assert.AreEqual(reader.ReadValue(), 2);
            Assert.IsTrue(reader.ReadToFollowing());             // int
            Assert.AreEqual(reader.ReadValue(), 3);
            Assert.IsTrue(reader.ReadToFollowing());             // long
            Assert.AreEqual(reader.ReadValue(), 4);
            Assert.IsTrue(reader.ReadToFollowing());             // float
            Assert.AreEqual(reader.ReadValue(), 5f);
            Assert.IsTrue(reader.ReadToFollowing());             // double
            Assert.AreEqual(reader.ReadValue(), 6d);
            Assert.IsTrue(reader.ReadToFollowing());             // byteArray
            CollectionAssert.AreEqual((byte[])reader.ReadValue(), new byte[] { 10, 11, 12 });
            Assert.IsTrue(reader.ReadToFollowing());             // intArray
            CollectionAssert.AreEqual((int[])reader.ReadValue(), new[] { 20, 21, 22 });
            Assert.IsTrue(reader.ReadToFollowing());             // string
            Assert.AreEqual(reader.ReadValue(), "23");
        }
Example #33
0
        public void NestedListAndCompoundTest()
        {
            byte[] data;
            {
                var root          = new NbtCompound("Root");
                var outerList     = new NbtList("OuterList", NbtTagType.Compound);
                var outerCompound = new NbtCompound();
                var innerList     = new NbtList("InnerList", NbtTagType.Compound);
                var innerCompound = new NbtCompound();

                innerList.Add(innerCompound);
                outerCompound.Add(innerList);
                outerList.Add(outerCompound);
                root.Add(outerList);

                var file = new NbtFile(root);
                data = file.SaveToBuffer(NbtCompression.None);
            }
            {
                var  file      = new NbtFile();
                long bytesRead = file.LoadFromBuffer(data, 0, data.Length, NbtCompression.None);
                Assert.AreEqual(bytesRead, data.Length);
                NbtCompound rootTag = (NbtCompound)file.RootTag;
                Assert.AreEqual(1, rootTag.Get <NbtList>("OuterList").Count);
                Assert.AreEqual(null, rootTag.Get <NbtList>("OuterList").Get <NbtCompound>(0).Name);
                Assert.AreEqual(1,
                                rootTag.Get <NbtList>("OuterList")
                                .Get <NbtCompound>(0)
                                .Get <NbtList>("InnerList")
                                .Count);
                Assert.AreEqual(null,
                                rootTag.Get <NbtList>("OuterList")
                                .Get <NbtCompound>(0)
                                .Get <NbtList>("InnerList")
                                .Get <NbtCompound>(0)
                                .Name);
            }
        }
Example #34
0
        private void LoadFromNbt(NbtFile nbtFile)
        {
            NbtTag dataTag = nbtFile.RootTag["Level"];

            //Debug.WriteLine($"Chunk {x},{z}: {nbtFile}");

            biomeId  = dataTag["Biomes"].ByteArrayValue;
            isAllAir = true;

            var sections = dataTag["Sections"] as NbtList;

            foreach (NbtTag sectionTag in sections)
            {
                LoadNbtSection(sectionTag);
            }

            var entities = dataTag["Entities"] as NbtList;

            if (entities != null)
            {
                foreach (NbtTag entityTag in entities)
                {
                    LoadNbtEntity(entityTag);
                }
            }

            var blockEntities = dataTag["TileEntities"] as NbtList;

            if (blockEntities != null)
            {
                foreach (NbtTag blockEntityTag in blockEntities)
                {
                    LoadNbtBlockEntity(blockEntityTag);
                }
            }

            isDirty = false;
        }
Example #35
0
 public void NestedListTest()
 {
     NbtCompound root = new NbtCompound( "root" ) {
         new NbtList( "OuterList" ) {
             new NbtList {
                 new NbtByte()
             },
             new NbtList {
                 new NbtShort()
             },
             new NbtList {
                 new NbtInt()
             }
         }
     };
     byte[] testData = new NbtFile( root ).SaveToBuffer( NbtCompression.None );
     using( MemoryStream ms = new MemoryStream( testData ) ) {
         NbtReader reader = new NbtReader( ms );
         while( reader.ReadToFollowing() ) {
             Console.WriteLine( reader.ToString( true ) );
         }
     }
 }
Example #36
0
        private void IncreaseMapIdCount(int id)
        {
            NbtFile idcounts;
            string  path = Path.Combine(Folder, "data", "idcounts.dat");

            if (File.Exists(path))
            {
                idcounts = new NbtFile(Path.Combine(Folder, "data", "idcounts.dat"));
                int existing = idcounts.RootTag["data"]["map"].IntValue;
                idcounts.RootTag["data"]["map"] = new NbtInt("map", Math.Max(existing, id));
            }
            else
            {
                idcounts = new NbtFile(new NbtCompound("")
                {
                    new NbtCompound("data")
                    {
                        new NbtInt("map", id)
                    }
                });
            }
            idcounts.SaveToFile(path, NbtCompression.GZip);
        }
Example #37
0
        public bool Load()
        {
            var path = Path.Combine(Directory.GetCurrentDirectory(), "players", Username + ".nbt");

            if (!File.Exists(path))
            {
                return(false);
            }
            try
            {
                var nbt = new NbtFile(path);
                Entity.Position = new Vector3(
                    nbt.RootTag["position"][0].DoubleValue,
                    nbt.RootTag["position"][1].DoubleValue,
                    nbt.RootTag["position"][2].DoubleValue);
                Inventory.SetSlots(((NbtList)nbt.RootTag["inventory"]).Select(t => ItemStack.FromNbt(t as NbtCompound)).ToArray());
                (Entity as PlayerEntity).Health = nbt.RootTag["health"].ShortValue;
                Entity.Yaw   = nbt.RootTag["yaw"].FloatValue;
                Entity.Pitch = nbt.RootTag["pitch"].FloatValue;
            }
            catch { /* Who cares */ }
            return(true);
        }
Example #38
0
        public void Palette(string file)
        {
            var myFile = new NbtFile();

            myFile.LoadFromFile(file);
            var     myCompTag = myFile.RootTag;
            NbtList block     = myFile.RootTag.Get <NbtList>("palette");

            for (int i = 0; i < block.Count; i++)
            {
                if (block.Get <NbtCompound>(i).Contains("Properties") == true)
                {
                    BlockStateConstraint bSC = new BlockStateConstraint();
                    palette.Add(bSC.BlockStates(file, i));
                }
                else
                {
                    palette.Add(new List <string> {
                        block.Get <NbtCompound>(i).Get <NbtString>("Name").StringValue, "null", "null", "null", "null", "null", "null"
                    });
                }
            }
        }
Example #39
0
        public void ByteArrayFromStream()
        {
            var data = new byte[64*1024];
            for (int i = 0; i < data.Length; i++) {
                data[i] = unchecked((byte)i);
            }

            using (var ms = new MemoryStream()) {
                var writer = new NbtWriter(ms, "root");
                {
                    using (var dataStream = new NonSeekableStream(new MemoryStream(data))) {
                        writer.WriteByteArray("byteArray", dataStream, data.Length);
                    }
                }
                writer.EndCompound();
                writer.Finish();

                ms.Position = 0;
                var file = new NbtFile();
                file.LoadFromStream(ms, NbtCompression.None);
                CollectionAssert.AreEqual(file.RootTag["byteArray"].ByteArrayValue, data);
            }
        }
Example #40
0
    public static bool GenerateFlat(int x, int y, int z, string path = "./")
    {
        if (ExistChunk(x, y, z, path))
        {
            return(false);
        }
        NbtCompound TileEntities = new NbtCompound("TileEntities");

        if (y > 0)
        {
            NbtCompound Blocks;
            TileEntities.Add(Blocks = new NbtCompound("Blocks"));
            for (int i = 0; i < 4096; i++)
            {
                Blocks.Add(new NbtCompound(i.ToString())
                {
                    new NbtFloat("BlockPos", i),
                    new NbtInt("BlockID", 1),
                });
            }
        }
        NbtCompound compound = new NbtCompound("root")
        {
            new NbtInt("DataVersion", Amane.chunkVersion),
            new NbtCompound("Level")
            {
                new NbtInt("xPos", x),
                new NbtInt("yPos", y),
                new NbtInt("zPos", z),
                TileEntities
            }
        };
        var NBTFile = new NbtFile(compound);

        NBTFile.SaveToFile($"{path}world/awo/{x.ToString()}.{y.ToString()}.{z.ToString()}.nbt.zlib", NbtCompression.ZLib);
        return(true);
    }
Example #41
0
        public static void SaveOfflinePlayerData(this MiNetServer server, string name, NbtCompound nbtTag, bool async = false)
        {
            NbtFile nbt = new NbtFile(nbtTag);

            nbt.BigEndian = true;

            ParameterizedThreadStart threadStart = new ParameterizedThreadStart(obj =>
            {
                try
                {
                    string path = Config.GetProperty("PluginDirectory", ".\\") + "\\PlayerSave\\players\\";
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    ((NbtFile)((object[])obj)[0]).SaveToFile(path + ((object[])obj)[1].ToString().ToLower() + ".dat", NbtCompression.ZLib);
                }
                catch (Exception e)
                {
                    ConsoleColor col        = Console.ForegroundColor;
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(e.Message);
                    Console.WriteLine(e.StackTrace);
                    Console.ForegroundColor = col;
                }
            });
            Thread thread = new Thread(threadStart);

            if (async)
            {
                thread.Start(new object[] { nbt, name });
            }
            else
            {
                threadStart(new object[] { nbt, name });
            }
        }
Example #42
0
        protected bool Equals(Item other)
        {
            if (Id != other.Id || Metadata != other.Metadata)
            {
                return(false);
            }
            if (ExtraData == null ^ other.ExtraData == null)
            {
                return(false);
            }

            //TODO: This doesn't work in  most cases. We need to fix comparison when name == null
            byte[] saveToBuffer = null;
            if (other.ExtraData?.Name != null)
            {
                saveToBuffer = new NbtFile(other.ExtraData).SaveToBuffer(NbtCompression.None);
            }
            byte[] saveToBuffer2 = null;
            if (ExtraData?.Name != null)
            {
                saveToBuffer2 = new NbtFile(ExtraData).SaveToBuffer(NbtCompression.None);
            }
            bool nbtCheck = !(saveToBuffer == null ^ saveToBuffer2 == null);

            if (nbtCheck)
            {
                if (saveToBuffer == null)
                {
                    nbtCheck = true;
                }
                else
                {
                    nbtCheck = saveToBuffer.SequenceEqual(saveToBuffer2);
                }
            }
            return(nbtCheck);
        }
Example #43
0
        // creates a file with lots of compounds and lists, used to test NbtReader compliance
        public static Stream MakeReaderTest()
        {
            var root = new NbtCompound("root")
            {
                new NbtInt("first"),
                new NbtInt("second"),
                new NbtCompound("third-comp")
                {
                    new NbtInt("inComp1"),
                    new NbtInt("inComp2"),
                    new NbtInt("inComp3")
                },
                new NbtList("fourth-list")
                {
                    new NbtList {
                        new NbtCompound {
                            new NbtCompound("inList1")
                        }
                    },
                    new NbtList {
                        new NbtCompound {
                            new NbtCompound("inList2")
                        }
                    },
                    new NbtList {
                        new NbtCompound {
                            new NbtCompound("inList3")
                        }
                    }
                },
                new NbtInt("fifth"),
                new NbtByteArray("hugeArray", new byte[1024 * 1024])
            };

            byte[] testData = new NbtFile(root).SaveToBuffer(NbtCompression.None);
            return(new MemoryStream(testData));
        }
Example #44
0
        public void Test1()
        {
            var nbtFile = new NbtFile();

            nbtFile.RootTag.Add(new NbtInt(1, "23333"));
            nbtFile.RootTag.Add(new NbtCompound("test"));
            var testCompound = nbtFile.RootTag["test"] as NbtCompound;

            Assert.NotNull(testCompound);
            var testList = new NbtList(NbtTagType.Int, "testList");

            testCompound.Add(testList);
            testList.Add(new NbtInt(2));
            testList.Add(new NbtInt(4));
            testCompound.Add(new NbtLong(0x000000FFFFFFFFFF, "testLong"));

            using (var sw = new StringWriter())
            {
                nbtFile.RootTag.Accept(new OutputVisitor(sw));
                var str = sw.ToString();
                Console.WriteLine(str);
            }

            var stream = new FileStream("test.bin", FileMode.OpenOrCreate, FileAccess.ReadWrite);

            stream.SetLength(0);
            nbtFile.WriteTo(stream);

            stream.Seek(0, SeekOrigin.Begin);
            var nbtFile2 = new NbtFile(stream);

            using (var sw = new StringWriter())
            {
                nbtFile2.RootTag.Accept(new OutputVisitor(sw));
                Console.WriteLine(sw.ToString());
            }
        }
Example #45
0
        public void CacheTagValuesTest()
        {
            byte[] testData = new NbtFile(TestFiles.MakeValueTest()).SaveToBuffer(NbtCompression.None);
            var    reader   = new NbtReader(new MemoryStream(testData));

            Assert.IsFalse(reader.CacheTagValues);
            reader.CacheTagValues = true;
            Assert.IsTrue(reader.ReadToFollowing()); // root

            Assert.IsTrue(reader.ReadToFollowing()); // byte
            Assert.AreEqual(1, reader.ReadValue());
            Assert.AreEqual(1, reader.ReadValue());
            Assert.IsTrue(reader.ReadToFollowing()); // short
            Assert.AreEqual(2, reader.ReadValue());
            Assert.AreEqual(2, reader.ReadValue());
            Assert.IsTrue(reader.ReadToFollowing()); // int
            Assert.AreEqual(3, reader.ReadValue());
            Assert.AreEqual(3, reader.ReadValue());
            Assert.IsTrue(reader.ReadToFollowing()); // long
            Assert.AreEqual(4L, reader.ReadValue());
            Assert.AreEqual(4L, reader.ReadValue());
            Assert.IsTrue(reader.ReadToFollowing()); // float
            Assert.AreEqual(5f, reader.ReadValue());
            Assert.AreEqual(5f, reader.ReadValue());
            Assert.IsTrue(reader.ReadToFollowing()); // double
            Assert.AreEqual(6d, reader.ReadValue());
            Assert.AreEqual(6d, reader.ReadValue());
            Assert.IsTrue(reader.ReadToFollowing()); // byteArray
            CollectionAssert.AreEqual(new byte[] { 10, 11, 12 }, (byte[])reader.ReadValue());
            CollectionAssert.AreEqual(new byte[] { 10, 11, 12 }, (byte[])reader.ReadValue());
            Assert.IsTrue(reader.ReadToFollowing()); // intArray
            CollectionAssert.AreEqual(new[] { 20, 21, 22 }, (int[])reader.ReadValue());
            CollectionAssert.AreEqual(new[] { 20, 21, 22 }, (int[])reader.ReadValue());
            Assert.IsTrue(reader.ReadToFollowing()); // string
            Assert.AreEqual("123", reader.ReadValue());
            Assert.AreEqual("123", reader.ReadValue());
        }
        //[Test]
        //public void LevelDbGetValueFromMissingKey()
        //{
        //	using var db = new Database(new DirectoryInfo(@"C:\Development\Other\bedrock-server-1.14.1.4\worlds\BedrockGeneratedLevel\db"));
        //	db.Open();

        //	int x = 15;
        //	int z = 6;

        //	Log.Warn("Looking for version");
        //	var versionKey = BitConverter.GetBytes(x).Concat(BitConverter.GetBytes(z)).Concat(new byte[] {0x76}).ToArray();
        //	var version = db.Get(versionKey);
        //	Assert.AreEqual(15, version.First());

        //	Log.Warn("Looking for key");
        //	Assert.NotNull(db.Get(BitConverter.GetBytes(x).Concat(BitConverter.GetBytes(z)).Concat(new byte[] {0x2f, 0}).ToArray()));
        //	Assert.NotNull(db.Get(BitConverter.GetBytes(x).Concat(BitConverter.GetBytes(z)).Concat(new byte[] {0x2f, 1}).ToArray()));
        //	Assert.NotNull(db.Get(BitConverter.GetBytes(x).Concat(BitConverter.GetBytes(z)).Concat(new byte[] {0x2f, 2}).ToArray()));
        //	Assert.NotNull(db.Get(BitConverter.GetBytes(x).Concat(BitConverter.GetBytes(z)).Concat(new byte[] {0x2f, 3}).ToArray()));
        //	Assert.NotNull(db.Get(BitConverter.GetBytes(x).Concat(BitConverter.GetBytes(z)).Concat(new byte[] {0x2f, 4}).ToArray()));
        //	Assert.NotNull(db.Get(BitConverter.GetBytes(x).Concat(BitConverter.GetBytes(z)).Concat(new byte[] {0x2f, 5}).ToArray()));
        //	Assert.Null(db.Get(BitConverter.GetBytes(x).Concat(BitConverter.GetBytes(z)).Concat(new byte[] {0x2f, 6}).ToArray()));
        //	Assert.Null(db.Get(BitConverter.GetBytes(x).Concat(BitConverter.GetBytes(z)).Concat(new byte[] {0x2f, 7}).ToArray()));
        //	Assert.Null(db.Get(BitConverter.GetBytes(x).Concat(BitConverter.GetBytes(z)).Concat(new byte[] {0x2f, 8}).ToArray())); // Fail??
        //	Assert.Null(db.Get(BitConverter.GetBytes(x).Concat(BitConverter.GetBytes(z)).Concat(new byte[] {0x2f, 9}).ToArray()));
        //	Assert.Null(db.Get(BitConverter.GetBytes(x).Concat(BitConverter.GetBytes(z)).Concat(new byte[] {0x2f, 10}).ToArray()));
        //	Assert.Null(db.Get(BitConverter.GetBytes(x).Concat(BitConverter.GetBytes(z)).Concat(new byte[] {0x2f, 11}).ToArray()));
        //	Assert.Null(db.Get(BitConverter.GetBytes(x).Concat(BitConverter.GetBytes(z)).Concat(new byte[] {0x2f, 12}).ToArray()));
        //	Assert.Null(db.Get(BitConverter.GetBytes(x).Concat(BitConverter.GetBytes(z)).Concat(new byte[] {0x2f, 13}).ToArray()));
        //	Assert.Null(db.Get(BitConverter.GetBytes(x).Concat(BitConverter.GetBytes(z)).Concat(new byte[] {0x2f, 14}).ToArray()));
        //	Assert.Null(db.Get(BitConverter.GetBytes(x).Concat(BitConverter.GetBytes(z)).Concat(new byte[] {0x2f, 15}).ToArray()));
        //}

        private void ParseChunk(ReadOnlySpan <byte> data)
        {
            var reader = new SpanReader(data);

            var version = reader.ReadByte();

            Assert.AreEqual(8, version);             // new palette-based chunk format

            var storageSize = reader.ReadByte();

            for (int i = 0; i < storageSize; i++)
            {
                var bitsPerBlock = reader.ReadByte() >> 1;
                Assert.AreEqual(4, bitsPerBlock);
                int numberOfBytes = 4096 / (32 / bitsPerBlock) * 4;
                var blockData     = reader.Read(numberOfBytes);

                Assert.AreEqual(4096 / 2, blockData.Length);

                int paletteSize = reader.ReadInt32();
                Assert.AreEqual(12, paletteSize);

                for (int j = 0; j < paletteSize; j++)
                {
                    NbtFile file = new NbtFile();
                    file.BigEndian = false;
                    file.UseVarInt = false;
                    var buffer = data.Slice(reader.Position).ToArray();

                    int numberOfBytesRead = (int)file.LoadFromStream(new MemoryStream(buffer), NbtCompression.None);
                    reader.Position += numberOfBytesRead;
                    Console.WriteLine(file.RootTag);
                    Assert.NotZero(numberOfBytesRead);
                }
            }
        }
Example #47
0
        public void Save(Map mapToSave, string path)
        {
            NbtCompound rootTag = new NbtCompound("Schematic")
            {
                new NbtShort("Width", (short)mapToSave.Width),
                new NbtShort("Height", (short)mapToSave.Height),
                new NbtShort("Length", (short)mapToSave.Length),
                new NbtString("Materials", "Classic"),
                new NbtByteArray("Blocks", mapToSave.Blocks),

                // set to 0 unless converted in overloaded DoConversion
                new NbtByteArray("Data", new byte[mapToSave.Volume]),

                // these two lists are empty, but required for compatibility
                new NbtList("Entities", NbtTagType.Compound),
                new NbtList("TileEntities", NbtTagType.Compound),
            };

            DoConversion(rootTag);
            NbtFile file = new NbtFile(rootTag);

            file.SaveToFile(path, NbtCompression.GZip);
            File.WriteAllText("debug.txt", file.RootTag.ToString("    "));
        }
Example #48
0
        static Stream MakeTest()
        {
            NbtCompound root = new NbtCompound("root")
            {
                new NbtInt("first"),
                new NbtInt("second"),
                new NbtCompound("third-comp")
                {
                    new NbtInt("inComp1"),
                    new NbtInt("inComp2"),
                    new NbtInt("inComp3")
                },
                new NbtList("fourth-list")
                {
                    new NbtList {
                        new NbtCompound {
                            new NbtCompound("inList1")
                        }
                    },
                    new NbtList {
                        new NbtCompound {
                            new NbtCompound("inList2")
                        }
                    },
                    new NbtList {
                        new NbtCompound {
                            new NbtCompound("inList3")
                        }
                    }
                },
                new NbtInt("fifth")
            };

            byte[] testData = new NbtFile(root).SaveToBuffer(NbtCompression.None);
            return(new MemoryStream(testData));
        }
Example #49
0
        public void Initialize()
        {
            if (_isInitialized)
            {
                return;                 // Quick exit
            }

            lock (_initializeSync)
            {
                if (_isInitialized)
                {
                    return;
                }

                var file = new NbtFile();
                file.LoadFromFile(Path.Combine(BasePath, "level.dat"));
                NbtTag dataTag = file.RootTag["Data"];
                LevelInfo = new LevelInfo(dataTag);

                LoadAvailableRegions();

                _isInitialized = true;
            }
        }
        public override Level Read(Stream src, string name, bool metadata)
        {
            NbtFile file = new NbtFile();

            file.LoadFromStream(src);
            NbtCompound root = file.RootTag;

            byte[] raw    = root["Blocks"].ByteArrayValue;
            byte[] meta   = root["Data"].ByteArrayValue;
            int    width  = root["Width"].ShortValue;
            int    height = root["Height"].ShortValue;
            int    length = root["Length"].ShortValue;

            Level lvl = new Level(name, (ushort)width, (ushort)height, (ushort)length);

            byte[] blocks = lvl.blocks;
            for (int i = 0; i < blocks.Length; i++)
            {
                blocks[i] = (byte)mcConv[raw[i], meta[i] & 0x0F];
            }

            for (int i = 0; i < blocks.Length; i++)
            {
                byte block = blocks[i];
                if (block < Block.CPE_COUNT)
                {
                    continue;
                }
                blocks[i] = Block.custom_block;

                ushort x, y, z;
                lvl.IntToPos(i, out x, out y, out z);
                lvl.FastSetExtTile(x, y, z, block);
            }
            return(lvl);
        }
Example #51
0
        public override void Save(string Folder)
        {
            string  f  = Path.Combine(Folder, "DefaultMapGenerator.dat");
            NbtFile nf = new NbtFile(f);

            nf.RootTag = new NbtCompound("__ROOT__");
            NbtCompound c = new NbtCompound("DefaultMapGenerator");

            c.Add(new NbtByte("GenerateCaves", (byte)(GenerateCaves ? 1 : 0)));
            c.Add(new NbtByte("GenerateDungeons", (byte)(GenerateDungeons ? 1 : 0)));
            c.Add(new NbtByte("GenerateOres", (byte)(GenerateOres ? 1 : 0)));
            c.Add(new NbtByte("GenerateWater", (byte)(GenerateWater ? 1 : 0)));
            c.Add(new NbtByte("HellMode", (byte)(HellMode ? 1 : 0)));
            c.Add(new NbtByte("GenerateTrees", (byte)(GenerateTrees ? 1 : 0)));
            c.Add(new NbtDouble("Frequency", Frequency));
            c.Add(new NbtByte("NoiseQuality", (byte)NoiseQuality));
            c.Add(new NbtInt("OctaveCount", OctaveCount));
            c.Add(new NbtDouble("Lacunarity", Lacunarity));
            c.Add(new NbtDouble("Persistance", Persistance));
            c.Add(new NbtDouble("ContinentNoiseFrequency", ContinentNoiseFrequency));
            c.Add(new NbtDouble("CaveThreshold", CaveThreshold));
            nf.RootTag.Add(c);
            nf.SaveFile(f);
        }
Example #52
0
        public Zakaznici(Form1 form)
        {
            this.form  = form;
            ZakazniciS = new SortedDictionary <string, byte>();
            if (File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Ticketnik\\zakaznici"))
            {
                Zak        = zak = new NbtFile(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Ticketnik\\zakaznici");
                form.verze = zak.RootTag.Get <NbtInt>("verze").Value;
                foreach (NbtTag c in zak.RootTag)
                {
                    if (c.TagType == NbtTagType.Compound)
                    {
                        ZakazniciS.Add(((NbtCompound)c).Get <NbtString>("Jmeno").Value, ((NbtCompound)c).Get <NbtByte>("Velikost").Value);
                    }
                }

                if (zak.RootTag.Get <NbtInt>("verze").Value >= 17)
                {
                    if (zak.RootTag.Get <NbtList>("Terpy") != null)
                    {
                        Terpy = (NbtCompound)zak.RootTag.Get <NbtList>("Terpy")[0];
                    }
                    else
                    {
                        form.Aktualizace(true);
                    }
                }
            }
            else
            {
                zak = new NbtFile();
                Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Ticketnik");
                zak.RootTag.Add(new NbtInt("verze", 1));
                zak.SaveToFile(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Ticketnik\\zakaznici", NbtCompression.GZip);
            }
        }
Example #53
0
        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();
        }
        public void CacheTagValuesTest()
        {
            byte[] testData = new NbtFile(TestFiles.MakeValueTest()).SaveToBuffer(NbtCompression.None);
            var reader = new NbtReader(new MemoryStream(testData));
            Assert.False(reader.CacheTagValues);
            reader.CacheTagValues = true;
            Assert.True(reader.ReadToFollowing()); // root

            Assert.True(reader.ReadToFollowing()); // byte
            Assert.Equal((byte) 1, reader.ReadValue());
            Assert.Equal((byte) 1, reader.ReadValue());
            Assert.True(reader.ReadToFollowing()); // short
            Assert.Equal((Int16) 2, reader.ReadValue());
            Assert.Equal((Int16) 2, reader.ReadValue());
            Assert.True(reader.ReadToFollowing()); // int
            Assert.Equal(3, reader.ReadValue());
            Assert.Equal(3, reader.ReadValue());
            Assert.True(reader.ReadToFollowing()); // long
            Assert.Equal(4L, reader.ReadValue());
            Assert.Equal(4L, reader.ReadValue());
            Assert.True(reader.ReadToFollowing()); // float
            Assert.Equal(5f, reader.ReadValue());
            Assert.Equal(5f, reader.ReadValue());
            Assert.True(reader.ReadToFollowing()); // double
            Assert.Equal(6d, reader.ReadValue());
            Assert.Equal(6d, reader.ReadValue());
            Assert.True(reader.ReadToFollowing()); // byteArray
            Assert.Equal(new byte[] {10, 11, 12}, (byte[]) reader.ReadValue());
            Assert.Equal(new byte[] {10, 11, 12}, (byte[]) reader.ReadValue());
            Assert.True(reader.ReadToFollowing()); // intArray
            Assert.Equal(new[] {20, 21, 22}, (int[]) reader.ReadValue());
            Assert.Equal(new[] {20, 21, 22}, (int[]) reader.ReadValue());
            Assert.True(reader.ReadToFollowing()); // string
            Assert.Equal("123", reader.ReadValue());
            Assert.Equal("123", reader.ReadValue());
        }
 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);
 }
        public void ReadValueAsTest()
        {
            byte[] testData = new NbtFile(TestFiles.MakeValueTest()).SaveToBuffer(NbtCompression.None);
            var reader = new NbtReader(new MemoryStream(testData));

            Assert.True(reader.ReadToFollowing()); // root

            Assert.True(reader.ReadToFollowing()); // byte
            Assert.Equal(1, reader.ReadValueAs<byte>());
            Assert.True(reader.ReadToFollowing()); // short
            Assert.Equal(2, reader.ReadValueAs<short>());
            Assert.True(reader.ReadToFollowing()); // int
            Assert.Equal(3, reader.ReadValueAs<int>());
            Assert.True(reader.ReadToFollowing()); // long
            Assert.Equal(4L, reader.ReadValueAs<long>());
            Assert.True(reader.ReadToFollowing()); // float
            Assert.Equal(5f, reader.ReadValueAs<float>());
            Assert.True(reader.ReadToFollowing()); // double
            Assert.Equal(6d, reader.ReadValueAs<double>());
            Assert.True(reader.ReadToFollowing()); // byteArray
            Assert.Equal(new byte[] {10, 11, 12}, reader.ReadValueAs<byte[]>());
            Assert.True(reader.ReadToFollowing()); // intArray
            Assert.Equal(new[] {20, 21, 22}, reader.ReadValueAs<int[]>());
            Assert.True(reader.ReadToFollowing()); // string
            Assert.Equal("123", reader.ReadValueAs<string>());
        }
        public void ReadValueTest()
        {
            byte[] testData = new NbtFile(TestFiles.MakeValueTest()).SaveToBuffer(NbtCompression.None);
            var reader = new NbtReader(new MemoryStream(testData));

            Assert.True(reader.ReadToFollowing()); // root

            Assert.True(reader.ReadToFollowing()); // byte
            Assert.Equal((byte) 1, reader.ReadValue());
            Assert.True(reader.ReadToFollowing()); // short
            Assert.Equal((Int16) 2, reader.ReadValue());
            Assert.True(reader.ReadToFollowing()); // int
            Assert.Equal(3, reader.ReadValue());
            Assert.True(reader.ReadToFollowing()); // long
            Assert.Equal(4L, reader.ReadValue());
            Assert.True(reader.ReadToFollowing()); // float
            Assert.Equal(5f, reader.ReadValue());
            Assert.True(reader.ReadToFollowing()); // double
            Assert.Equal(6d, reader.ReadValue());
            Assert.True(reader.ReadToFollowing()); // byteArray
            Assert.Equal(new byte[] {10, 11, 12}, (byte[]) reader.ReadValue());
            Assert.True(reader.ReadToFollowing()); // intArray
            Assert.Equal(new[] {20, 21, 22}, (int[]) reader.ReadValue());
            Assert.True(reader.ReadToFollowing()); // string
            Assert.Equal("123", reader.ReadValue());

            // Skip to the very end and make sure that we can't read any more values
            reader.ReadToFollowing();
            Assert.Throws<EndOfStreamException>(() => reader.ReadValue());
        }
        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));
     }
 }