Example #1
0
    public void TestNbtSmallFileSavingUncompressedStream()
    {
        NbtFile file      = TestFiles.MakeSmallFile();
        var     nbtStream = new MemoryStream();

        Assert.Throws <ArgumentNullException>(() => file.SaveToStream(null, NbtCompression.None));
        Assert.Throws <ArgumentException>(() => file.SaveToStream(nbtStream, NbtCompression.AutoDetect));
        Assert.Throws <ArgumentOutOfRangeException>(() => file.SaveToStream(nbtStream, (NbtCompression)255));
        file.SaveToStream(nbtStream, NbtCompression.None);
        FileStream testFileStream = File.OpenRead(TestFiles.Small);
        //FileAssert.Equal(testFileStream, nbtStream);
    }
Example #2
0
        public void SavePlayer(PlayerEntity entity)
        {
            // TODO: Generalize to all mobs
            NbtFile file = new NbtFile();
            var     data = new NbtCompound("");

            data.Add(new NbtByte("OnGround", (byte)(entity.OnGround ? 1 : 0)));
            data.Add(new NbtShort("Air", entity.Air));
            data.Add(new NbtShort("Health", entity.Health));
            data.Add(new NbtInt("Dimension", 0)); // TODO
            data.Add(new NbtInt("foodLevel", entity.Food));
            data.Add(new NbtInt("XpLevel", entity.XpLevel));
            data.Add(new NbtInt("XpTotal", entity.XpTotal));
            data.Add(new NbtFloat("foodExhaustionLevel", entity.FoodExhaustion));
            data.Add(new NbtFloat("foodSaturationLevel", entity.FoodSaturation));
            data.Add(new NbtFloat("XpP", entity.XpProgress));
            data.Add(new NbtList("Equipment", NbtTagType.Compound));
            var inventory = new NbtList("Inventory", NbtTagType.Compound);

            for (int index = 0; index < entity.Inventory.Length; index++)
            {
                var slot = entity.Inventory[index];
                if (slot.Empty)
                {
                    continue;
                }
                slot.Index = NetworkSlotToDataSlot(index);
                inventory.Add(slot.ToNbt());
            }
            data.Add(inventory);
            var motion = new NbtList("Motion", NbtTagType.Double);

            motion.Add(new NbtDouble(entity.Velocity.X));
            motion.Add(new NbtDouble(entity.Velocity.Y));
            motion.Add(new NbtDouble(entity.Velocity.Z));
            data.Add(motion);

            var pos = new NbtList("Pos", NbtTagType.Double);

            pos.Add(new NbtDouble(entity.Position.X));
            pos.Add(new NbtDouble(entity.Position.Y));
            pos.Add(new NbtDouble(entity.Position.Z));
            data.Add(pos);

            var rotation = new NbtList("Rotation", NbtTagType.Float);

            rotation.Add(new NbtFloat(entity.Yaw));
            rotation.Add(new NbtFloat(entity.Pitch));
            data.Add(rotation);

            data.Add(new NbtCompound("abilities"));

            file.RootTag = data;
            if (!Directory.Exists(Path.Combine(LevelDirectory, "players")))
            {
                Directory.CreateDirectory(Path.Combine(LevelDirectory, "players"));
            }
            using (Stream stream = File.Open(Path.Combine(LevelDirectory, "players", entity.Username + ".dat"), FileMode.OpenOrCreate))
                file.SaveToStream(stream, NbtCompression.GZip);
        }
Example #3
0
        private byte[] GetBytes()
        {
            if (_cache != null)
            {
                return(_cache);
            }

            MemoryStream stream = new MemoryStream();
            {
                NbtBinaryWriter writer = new NbtBinaryWriter(stream, true);

                writer.Write(blocks);
                writer.Write(metadata.Data);
                writer.Write(skylight.Data);
                writer.Write(blocklight.Data);

                //RecalcHeight();
                writer.Write(height);

                for (int i = 0; i < biomeColor.Length; i++)
                {
                    writer.Write(biomeColor[i]);
                }

                int extraSize = 0;
                writer.Write(extraSize);                 // No extra data

                if (BlockEntities.Count == 0)
                {
                    NbtFile file = new NbtFile(new NbtCompound(string.Empty))
                    {
                        BigEndian = false
                    };
                    file.SaveToStream(writer.BaseStream, NbtCompression.None);
                }
                else
                {
                    foreach (NbtCompound blockEntity in BlockEntities.Values.ToArray())
                    {
                        NbtFile file = new NbtFile(blockEntity)
                        {
                            BigEndian = false
                        };
                        file.SaveToStream(writer.BaseStream, NbtCompression.None);
                    }
                }

                writer.Flush();
                writer.Close();
            }

            var bytes = stream.ToArray();

            stream.Close();

            _cache = bytes;

            return(bytes);
        }
Example #4
0
        public void WriteNbtFile(NbtFile nbt)
        {
            if (nbt == null)
            {
                throw new ArgumentNullException(nameof(nbt));
            }

            nbt.SaveToStream(this, NbtCompression.None);
        }
Example #5
0
        public byte[] GetBytes()
        {
            if (_cache != null)
            {
                return(_cache);
            }

            using (MemoryStream stream = MiNetServer.MemoryStreamManager.GetStream())
            {
                NbtBinaryWriter writer = new NbtBinaryWriter(stream, true);

                writer.Write(blocks);
                writer.Write(metadata.Data);
                writer.Write(skylight.Data);
                writer.Write(blocklight.Data);

                //RecalcHeight();
                writer.Write(height);

                BiomeUtils utils = new BiomeUtils();
                utils.PrecomputeBiomeColors();

                InterpolateBiomes();

                for (int i = 0; i < biomeId.Length; i++)
                {
                    var biome = biomeId[i];
                    int color = biomeColor[i];
                    writer.Write((color & 0x00ffffff) | biome << 24);
                }

                short extraSize = 0;
                writer.Write(extraSize);                 // No extra data

                if (BlockEntities.Count == 0)
                {
                    //NbtFile file = new NbtFile(new NbtCompound(string.Empty)) {BigEndian = false, UseVarInt = true};
                    //file.SaveToStream(writer.BaseStream, NbtCompression.None);
                }
                else
                {
                    foreach (NbtCompound blockEntity in BlockEntities.Values.ToArray())
                    {
                        NbtFile file = new NbtFile(blockEntity)
                        {
                            BigEndian = false, UseVarInt = true
                        };
                        file.SaveToStream(writer.BaseStream, NbtCompression.None);
                    }
                }

                _cache = stream.ToArray();
            }

            return(_cache);
        }
Example #6
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 #7
0
        public void SerializingWithoutListType()
        {
            var root = new NbtCompound("root")
            {
                new NbtList("list")
            };
            var file = new NbtFile(root);

            using (var ms = new MemoryStream())             // list should throw NbtFormatException, because its ListType is Unknown
                Assert.Throws <NbtFormatException>(() => file.SaveToStream(ms, NbtCompression.None));
        }
Example #8
0
        public void WriteNbtCompound(NbtCompound compound)
        {
            NbtFile f = new NbtFile(compound)
            {
                BigEndian = true, UseVarInt = false
            };

            f.SaveToStream(this, NbtCompression.None);

            //WriteByte(0);
        }
Example #9
0
        public static byte[] GetBytesFromNBTCompound(NbtCompound nbt)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                NbtFile file = new NbtFile(nbt);

                file.SaveToStream(stream, NbtCompression.GZip);

                return(stream.ToArray());
            }
        }
Example #10
0
        public void Save()
        {
            NbtFile file = new NbtFile();

            var serializer = new NbtSerializer(typeof(SavedLevel));
            var level      = new SavedLevel
            {
                IsRaining        = Raining,
                GeneratorVersion = 0,
                Time             = Time,
                GameMode         = (int)GameMode,
                MapFeatures      = MapFeatures,
                GeneratorName    = WorldGenerator.GeneratorName,
                Initialized      = true,
                Seed             = Seed,
                SpawnPoint       = SpawnPoint,
                SizeOnDisk       = 0,
                ThunderTime      = ThunderTime,
                RainTime         = RainTime,
                Version          = 19133,
                Thundering       = Thundering,
                LevelName        = Name,
                LastPlayed       = DateTime.UtcNow.Ticks
            };

            if (!string.IsNullOrEmpty(PlayerName))
            {
                if (File.Exists(Path.Combine(LevelDirectory, "players", PlayerName + ".dat")))
                {
                    var player = new NbtFile();
                    using (Stream stream = File.Open(Path.Combine(LevelDirectory, "players", PlayerName + ".dat"), FileMode.Open))
                        player.LoadFromStream(stream, NbtCompression.GZip, null);
                    level.Player      = player.RootTag;
                    level.Player.Name = "Player";
                }
            }
            var data = serializer.Serialize(level);

            file.RootTag = new NbtCompound("");
            file.RootTag.Add(data);
            using (var stream = File.Create(Path.Combine(LevelDirectory, "level.dat")))
                file.SaveToStream(stream, NbtCompression.GZip);
            if (World.Directory == null)
            {
                World.Save(Path.Combine(LevelDirectory, "region"));
            }
            else
            {
                World.Save();
            }
        }
Example #11
0
        public void ReloadNonSeekableStream()
        {
            var loadedFile = new NbtFile("TestFiles/bigtest.nbt");

            using (var ms = new MemoryStream())
                using (var nss = new NonSeekableStream(ms))
                {
                    var bytesWritten = loadedFile.SaveToStream(nss, NbtCompression.None);
                    ms.Position = 0;
                    var bytesRead = loadedFile.LoadFromStream(nss, NbtCompression.None, null);
                    Assert.AreEqual(bytesWritten, bytesRead);
                    AssertNbtBigFile(loadedFile);
                }
        }
Example #12
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 #13
0
        public void HugeNbtFileTest()
        {
            // Tests writing byte arrays that exceed the max NbtBinaryWriter chunk size
            byte[]      val  = new byte[5 * 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 TestNbtSmallFileSavingUncompressedStream()
        {
            var file = new NbtFile(
                new NbtCompound("hello world", new NbtTag[] {
                new NbtString("name", "Bananrama")
            })
                );

            var nbtStream = new MemoryStream();

            file.SaveToStream(nbtStream, NbtCompression.None);

            FileStream testFileStream = File.OpenRead("TestFiles/test.nbt");

            FileAssert.AreEqual(testFileStream, nbtStream);
        }
Example #15
0
        public void ReloadNonSeekableStream()
        {
            var loadedFile = new NbtFile(TestFiles.Big);

            using (var ms = new MemoryStream()) {
                using (var nss = new NonSeekableStream(ms)) {
                    long bytesWritten = loadedFile.SaveToStream(nss, NbtCompression.None);
                    ms.Position = 0;
                    Assert.Throws <NotSupportedException>(() => loadedFile.LoadFromStream(nss, NbtCompression.AutoDetect));
                    ms.Position = 0;
                    Assert.Throws <InvalidDataException>(() => loadedFile.LoadFromStream(nss, NbtCompression.ZLib, NbtVersion.Legacy));
                    ms.Position = 0;
                    long bytesRead = loadedFile.LoadFromStream(nss, NbtCompression.None, NbtVersion.Legacy);
                    Assert.AreEqual(bytesWritten, bytesRead);
                    TestFiles.AssertNbtBigFile(loadedFile);
                }
            }
        }
Example #16
0
        public void WriteMixedCodec(MixedCodec value)
        {
            var dimensions = new NbtCompound(value.Dimensions.Name)
            {
                new NbtString("type", value.Dimensions.Name)
            };

            var list = new NbtList("value", NbtTagType.Compound);

            foreach (var(_, codec) in value.Dimensions)
            {
                codec.Write(list);
            }

            dimensions.Add(list);

            #region biomes
            var biomeCompound = new NbtCompound(value.Biomes.Name)
            {
                new NbtString("type", value.Biomes.Name)
            };

            var biomes = new NbtList("value", NbtTagType.Compound);

            foreach (var(_, biome) in value.Biomes)
            {
                biome.Write(biomes);
            }

            biomeCompound.Add(biomes);
            #endregion

            var compound = new NbtCompound(string.Empty)
            {
                dimensions,
                biomeCompound
            };
            var nbt = new NbtFile(compound);

            nbt.SaveToStream(this, NbtCompression.None);
        }
Example #17
0
        /// <summary>
        /// Writes this item stack to a Minecraft stream.
        /// </summary>
        /// <param name="stream">The stream to write to.</param>
        public void WriteTo(IMinecraftStream stream)
        {
            stream.WriteInt16(ID);
            if (Empty)
            {
                return;
            }
            stream.WriteInt8(Count);
            stream.WriteInt16(Metadata);
            if (Nbt == null)
            {
                stream.WriteInt16(-1);
                return;
            }
            var mStream = new MemoryStream();
            var file    = new NbtFile(Nbt);

            file.SaveToStream(mStream, NbtCompression.GZip);
            stream.WriteInt16((short)mStream.Position);
            stream.WriteUInt8Array(mStream.GetBuffer());
        }
Example #18
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 #19
0
        public async Task WriteAsync(DataType type, FieldAttribute attribute, object value, int length = 32767)
        {
            switch (type)
            {
            case DataType.Auto:
            {
                if (value is Player player)
                {
                    await this.WriteUnsignedByteAsync(0xff);
                }
                else
                {
                    await this.WriteAutoAsync(value);
                }

                break;
            }

            case DataType.Angle:
            {
                await this.WriteAngleAsync((Angle)value);

                break;
            }

            case DataType.Boolean:
            {
                await this.WriteBooleanAsync((bool)value);

                break;
            }

            case DataType.Byte:
            {
                await this.WriteByteAsync((sbyte)value);

                break;
            }

            case DataType.UnsignedByte:
            {
                await this.WriteUnsignedByteAsync((byte)value);

                break;
            }

            case DataType.Short:
            {
                await this.WriteShortAsync((short)value);

                break;
            }

            case DataType.UnsignedShort:
            {
                await this.WriteUnsignedShortAsync((ushort)value);

                break;
            }

            case DataType.Int:
            {
                await this.WriteIntAsync((int)value);

                break;
            }

            case DataType.Long:
            {
                await this.WriteLongAsync((long)value);

                break;
            }

            case DataType.Float:
            {
                await this.WriteFloatAsync((float)value);

                break;
            }

            case DataType.Double:
            {
                await this.WriteDoubleAsync((double)value);

                break;
            }

            case DataType.String:
            {
                // TODO: add casing options on Field attribute and support custom naming enums.
                var val = value.GetType().IsEnum ? value.ToString().ToCamelCase() : value.ToString();
                await this.WriteStringAsync(val, length);

                break;
            }

            case DataType.Chat:
            {
                await this.WriteChatAsync((ChatMessage)value);

                break;
            }

            case DataType.VarInt:
            {
                await this.WriteVarIntAsync((int)value);

                break;
            }

            case DataType.VarLong:
            {
                await this.WriteVarLongAsync((long)value);

                break;
            }

            case DataType.Position:
            {
                if (value is Position position)
                {
                    if (attribute.Absolute)
                    {
                        await this.WriteDoubleAsync(position.X);

                        await this.WriteDoubleAsync(position.Y);

                        await this.WriteDoubleAsync(position.Z);

                        break;
                    }

                    await this.WritePositionAsync(position);
                }
                else if (value is SoundPosition soundPosition)
                {
                    await this.WriteIntAsync(soundPosition.X);

                    await this.WriteIntAsync(soundPosition.Y);

                    await this.WriteIntAsync(soundPosition.Z);
                }

                break;
            }

            case DataType.Velocity:
            {
                var velocity = (Velocity)value;

                await this.WriteShortAsync(velocity.X);

                await this.WriteShortAsync(velocity.Y);

                await this.WriteShortAsync(velocity.Z);

                break;
            }

            case DataType.UUID:
            {
                await this.WriteUuidAsync((Guid)value);

                break;
            }

            case DataType.Array:
            {
                if (value is List <CommandNode> nodes)
                {
                    foreach (var node in nodes)
                    {
                        await node.CopyToAsync(this);
                    }
                }
                else if (value is List <PlayerInfoAction> actions)
                {
                    await this.WriteVarIntAsync(actions.Count);

                    foreach (var action in actions)
                    {
                        await action.WriteAsync(this);
                    }
                }
                else if (value is List <int> ids)
                {
                    foreach (var id in ids)
                    {
                        await this.WriteVarIntAsync(id);
                    }
                }
                else if (value is List <string> values)
                {
                    foreach (var vals in values)
                    {
                        await this.WriteStringAsync(vals);
                    }
                }
                else if (value is List <long> vals)
                {
                    foreach (var val in vals)
                    {
                        await this.WriteLongAsync(val);
                    }
                }
                else if (value is List <Tag> tags)
                {
                    await this.WriteVarIntAsync(tags.Count);

                    foreach (var tag in tags)
                    {
                        await this.WriteStringAsync(tag.Name);

                        await this.WriteVarIntAsync(tag.Count);

                        foreach (var entry in tag.Entries)
                        {
                            await this.WriteVarIntAsync(entry);
                        }
                    }
                }
                break;
            }

            case DataType.ByteArray:
            {
                var array = (byte[])value;
                if (attribute.CountLength)
                {
                    await this.WriteVarIntAsync(array.Length);

                    await this.WriteAsync(array);
                }
                else
                {
                    await this.WriteAsync(array);
                }
                break;
            }

            case DataType.Slot:
            {
                await this.WriteSlotAsync((ItemStack)value);

                break;
            }

            case DataType.EntityMetadata:
            {
                var ent = (Entity)value;
                await ent.WriteAsync(this);

                await this.WriteUnsignedByteAsync(0xff);

                break;
            }

            case DataType.NbtTag:
            {
                if (value is MixedCodec codecs)
                {
                    var dimensions = new NbtCompound(codecs.Dimensions.Name)
                    {
                        new NbtString("type", codecs.Dimensions.Name)
                    };

                    var list = new NbtList("value", NbtTagType.Compound);

                    foreach (var(_, codec) in codecs.Dimensions)
                    {
                        codec.Write(list);
                    }

                    dimensions.Add(list);

                    #region biomes
                    var biomeCompound = new NbtCompound(codecs.Biomes.Name)
                    {
                        new NbtString("type", codecs.Biomes.Name)
                    };

                    var biomes = new NbtList("value", NbtTagType.Compound);

                    foreach (var(_, biome) in codecs.Biomes)
                    {
                        biome.Write(biomes);
                    }

                    biomeCompound.Add(biomes);
                    #endregion
                    var compound = new NbtCompound("")
                    {
                        dimensions,
                        biomeCompound
                    };
                    var nbt = new NbtFile(compound);

                    nbt.SaveToStream(this, NbtCompression.None);
                }
                else if (value is DimensionCodec codec)
                {
                    var nbt = new NbtFile(codec.ToNbt());

                    nbt.SaveToStream(this, NbtCompression.None);
                }
                break;
            }

            default:
                throw new ArgumentOutOfRangeException(nameof(type));
            }
        }
Example #20
0
        public void WriteDimensionCodec(DimensionCodec value)
        {
            var nbt = new NbtFile(value.ToNbt());

            nbt.SaveToStream(this, NbtCompression.None);
        }
Example #21
0
        public byte[] GetBytes()
        {
            if (_cache != null)
            {
                return(_cache);
            }

            using (MemoryStream stream = MiNetServer.MemoryStreamManager.GetStream())
            {
                NbtBinaryWriter writer = new NbtBinaryWriter(stream, true);

                int topEmpty = 0;
                for (int ci = 15; ci > 0; ci--)
                {
                    if (chunks[ci].IsAllAir())
                    {
                        topEmpty = ci + 1;
                    }
                    else
                    {
                        break;
                    }
                }

                writer.Write((byte)topEmpty);
                Log.Debug($"Saved sending {16 - topEmpty} chunks");

                for (int ci = 0; ci < topEmpty; ci++)
                {
                    writer.Write((byte)0);
                    writer.Write(chunks[ci].GetBytes());
                }

                //RecalcHeight();
                writer.Write(height);

                //BiomeUtils utils = new BiomeUtils();
                //utils.PrecomputeBiomeColors();

                //InterpolateBiomes();

                writer.Write(biomeId);

                //for (int i = 0; i < biomeId.Length; i++)
                //{
                //	//var biome = biomeId[i];
                //	int color = biomeColor[i];
                //	writer.Write((int) (color & 0x00ffffff) /*| biome << 24*/);
                //}

                short extraSize = 0;
                writer.Write(extraSize);                 // No extra data

                if (BlockEntities.Count == 0)
                {
                    //NbtFile file = new NbtFile(new NbtCompound(string.Empty)) {BigEndian = false, UseVarInt = true};
                    //file.SaveToStream(writer.BaseStream, NbtCompression.None);
                }
                else
                {
                    foreach (NbtCompound blockEntity in BlockEntities.Values.ToArray())
                    {
                        NbtFile file = new NbtFile(blockEntity)
                        {
                            BigEndian = false, UseVarInt = true
                        };
                        file.SaveToStream(writer.BaseStream, NbtCompression.None);
                    }
                }

                _cache = stream.ToArray();
            }

            return(_cache);
        }
Example #22
0
        public void SerializingWithoutListType()
        {
            var root = new NbtCompound("root") {
                new NbtList("list")
            };
            var file = new NbtFile(root);

            using (var ms = new MemoryStream()) {
                // list should throw NbtFormatException, because its ListType is Unknown
                Assert.Throws<NbtFormatException>(() => file.SaveToStream(ms, NbtCompression.None));
            }
        }
Example #23
0
 public void ReloadNonSeekableStream()
 {
     var loadedFile = new NbtFile(TestFiles.Big);
     using (var ms = new MemoryStream()) {
         using (var nss = new NonSeekableStream(ms)) {
             long bytesWritten = loadedFile.SaveToStream(nss, NbtCompression.None);
             ms.Position = 0;
             Assert.Throws<NotSupportedException>(() => loadedFile.LoadFromStream(nss, NbtCompression.AutoDetect));
             ms.Position = 0;
             Assert.Throws<InvalidDataException>(() => loadedFile.LoadFromStream(nss, NbtCompression.ZLib));
             ms.Position = 0;
             long bytesRead = loadedFile.LoadFromStream(nss, NbtCompression.None);
             Assert.AreEqual(bytesWritten, bytesRead);
             TestFiles.AssertNbtBigFile(loadedFile);
         }
     }
 }
Example #24
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 #25
0
 public void ReloadNonSeekableStream()
 {
     NbtFile loadedFile = new NbtFile( "TestFiles/bigtest.nbt" );
     using( MemoryStream ms = new MemoryStream() ) {
         using( NonSeekableStream nss = new NonSeekableStream( ms ) ) {
             int bytesWritten = loadedFile.SaveToStream( nss, NbtCompression.None );
             ms.Position = 0;
             int bytesRead = loadedFile.LoadFromStream( nss, NbtCompression.None, null );
             Assert.AreEqual( bytesWritten, bytesRead );
             AssertNbtBigFile( loadedFile );
         }
     }
 }
Example #26
0
        public byte[] GetBytes()
        {
            if (_cache != null)
            {
                return(_cache);
            }

            using (MemoryStream stream = MiNetServer.MemoryStreamManager.GetStream())
            {
                NbtBinaryWriter writer = new NbtBinaryWriter(stream, true);

                int topEmpty = 16;
                for (int ci = 15; ci >= 0; ci--)
                {
                    if (chunks[ci].IsAllAir())
                    {
                        topEmpty = ci;
                    }
                    else
                    {
                        break;
                    }
                }

                writer.Write((byte)topEmpty);

                int sent = 0;
                for (int ci = 0; ci < topEmpty; ci++)
                {
                    writer.Write((byte)0);
                    writer.Write(chunks[ci].GetBytes());
                    sent++;
                }

                //Log.Debug($"Saved sending {16 - sent} chunks");

                //RecalcHeight();

                byte[] ba = new byte[512];
                Buffer.BlockCopy(height, 0, ba, 0, 512);
                writer.Write(ba);
                //Log.Debug($"Heights:\n{Package.HexDump(ba)}");

                //BiomeUtils utils = new BiomeUtils();
                //utils.PrecomputeBiomeColors();

                //InterpolateBiomes();

                writer.Write(biomeId);

                //for (int i = 0; i < biomeId.Length; i++)
                //{
                //	//var biome = biomeId[i];
                //	int color = biomeColor[i];
                //	writer.Write((int) (color & 0x00ffffff) /*| biome << 24*/);
                //}

                //short extraSize = 0;
                //writer.Write(extraSize); // No extra data

                // Count = SignedVarInt (zigzag)
                // Each entry
                // - Hash SignedVarint x << 12, z << 8, y
                // - Block data short

                writer.Write((byte)0);                 // Border blocks - nope

                VarInt.WriteSInt32(stream, 0);         // Block extradata count
                //VarInt.WriteSInt32(stream, 2);
                //VarInt.WriteSInt32(stream, 1 << 12 | 1 << 8 | 4);
                //writer.Write((byte)31);
                //writer.Write((byte)0);

                if (BlockEntities.Count == 0)
                {
                    //NbtFile file = new NbtFile(new NbtCompound(string.Empty)) {BigEndian = false, UseVarInt = true};
                    //file.SaveToStream(writer.BaseStream, NbtCompression.None);
                }
                else
                {
                    foreach (NbtCompound blockEntity in BlockEntities.Values.ToArray())
                    {
                        NbtFile file = new NbtFile(blockEntity)
                        {
                            BigEndian = false, UseVarInt = true
                        };
                        file.SaveToStream(writer.BaseStream, NbtCompression.None);
                    }
                }

                _cache = stream.ToArray();
            }

            return(_cache);
        }
Example #27
0
        public void TestNbtSmallFileSavingUncompressedStream()
        {
            var file = new NbtFile (
                new NbtCompound( "hello world", new NbtTag[] {
                    new NbtString( "name", "Bananrama" )
                } )
            );

            var nbtStream = new MemoryStream();
            file.SaveToStream( nbtStream, NbtCompression.None );

            FileStream testFileStream = File.OpenRead( "TestFiles/test.nbt" );

            FileAssert.AreEqual( testFileStream, nbtStream );
        }
Example #28
0
        public override void Write(NbtCompound value)
        {
            var serverFile = new NbtFile(value);

            serverFile.SaveToStream(Stream, NbtCompression.None);
        }