示例#1
0
 protected override void SaveCore()
 {
     using (var str = _regionFile.GetChunkDataOutputStream(X, Z))
     {
         _tree.WriteTo(str);
     }
 }
示例#2
0
 protected override void SaveCore()
 {
     var file = new NBTFile(_path);
     using (var str = file.GetDataOutputStream(_compressionType))
     {
         _tree.WriteTo(str);
     }
 }
示例#3
0
        /// <summary>
        /// Saves a Chunk's underlying NBT_Tree to an output stream.
        /// </summary>
        /// <param name="outStream">An open, writable output stream.</param>
        /// <returns>True if the data is written out to the stream.</returns>
        public bool Save(Stream outStream)
        {
            if (outStream == null || !outStream.CanWrite)
            {
                return(false);
            }

            _tree.WriteTo(outStream);
            outStream.Close();

            return(true);
        }
示例#4
0
        /// <summary>
        /// Saves a raw <see cref="NbtTree"/> representing a map to the given map's file.
        /// </summary>
        /// <param name="id">The id of the map to write data to.</param>
        /// <param name="tree">The map's data as an <see cref="NbtTree"/>.</param>
        /// <exception cref="NbtIOException">Thrown when the manager cannot initialize an NBT data stream for output.</exception>
        public void SetMapTree(int id, NbtTree tree)
        {
            MapFile mf     = GetMapFile(id);
            Stream  zipstr = mf.GetDataOutputStream();

            if (zipstr == null)
            {
                throw new NbtIOException("Failed to initialize NBT data stream for output.");
            }

            tree.WriteTo(zipstr);
            zipstr.Close();
        }
示例#5
0
        /// <summary>
        /// Saves a Chunk's underlying NBT_Tree to an output stream.
        /// </summary>
        /// <param name="outStream">An open, writable output stream.</param>
        /// <returns>True if the data is written out to the stream.</returns>
        public bool Save(Stream outStream)
        {
            if (outStream == null || !outStream.CanWrite)
            {
                return(false);
            }

            BuildConditional();

            _tree.WriteTo(outStream);

            return(true);
        }
示例#6
0
        /// <summary>
        /// Saves a raw <see cref="NbtTree"/> representing a player to the given player's file.
        /// </summary>
        /// <param name="name">The name of the player to write data to.</param>
        /// <param name="tree">The player's data as an <see cref="NbtTree"/>.</param>
        /// <exception cref="NbtIOException">Thrown when the manager cannot initialize an NBT data stream for output.</exception>
        public void SetPlayerTree(string name, NbtTree tree)
        {
            PlayerFile pf     = GetPlayerFile(name);
            Stream     zipstr = pf.GetDataOutputStream();

            if (zipstr == null)
            {
                throw new NbtIOException("Failed to initialize NBT data stream for output.");
            }

            tree.WriteTo(zipstr);
            zipstr.Close();
        }
示例#7
0
        public static byte[] SerializeNode (TagNode node)
        {
            TagNodeCompound root = new TagNodeCompound();
            root.Add("root", node);
            NbtTree tree = new NbtTree(root);

            using (MemoryStream ms = new MemoryStream()) {
                tree.WriteTo(ms);
                byte[] data = new byte[ms.Length];
                Array.Copy(ms.GetBuffer(), data, ms.Length);

                return data;
            }
        }
示例#8
0
        public static byte[] GetEnchantmentNBTData(List <Enchantment> enchantments)
        {
            if (enchantments.Count < 1)
            {
                return(new byte[0]);
            }
            NbtTree nbt = new NbtTree();

            nbt.Root.Add("ench", GetEnchantmentNBT(enchantments));
            using (MemoryStream ms = new MemoryStream())
            {
                nbt.WriteTo(ms);
                return(ms.ToArray().Compress(Ionic.Zlib.CompressionLevel.BestCompression, CompressionType.GZip));
            }
        }
        public static byte[] SerializeNode(TagNode node)
        {
            TagNodeCompound root = new TagNodeCompound();

            root.Add("root", node);
            NbtTree tree = new NbtTree(root);

            using (MemoryStream ms = new MemoryStream()) {
                tree.WriteTo(ms);
                byte[] data = new byte[ms.Length];
                Array.Copy(ms.GetBuffer(), data, ms.Length);

                return(data);
            }
        }
示例#10
0
        private bool SaveChunkTree(int cx, int cz, NbtTree tree)
        {
            ChunkFile cf     = GetChunkFile(cx, cz);
            Stream    zipstr = cf.GetDataOutputStream();

            if (zipstr == null)
            {
                return(false);
            }

            tree.WriteTo(zipstr);
            zipstr.Close();

            return(true);
        }
示例#11
0
        public bool Save(Stream outStream)
        {
            if (outStream == null || !outStream.CanWrite)
            {
                return(false);
            }

            BuildConditional();

            NbtTree tree = new NbtTree();

            tree.Root["Level"] = BuildTree();

            tree.WriteTo(outStream);

            return(true);
        }
示例#12
0
        // XXX: Exceptions
        /// <summary>
        /// Saves an <see cref="NbtTree"/> for a chunk back to the region's data store at the given local coordinates.
        /// </summary>
        /// <param name="lcx">The local X-coordinate of the chunk within the region.</param>
        /// <param name="lcz">The local Z-coordinate of the chunk within the region.</param>
        /// <param name="tree">The <see cref="NbtTree"/> of a chunk to write back to the region.</param>
        /// <returns>True if the save succeeded.</returns>
        /// <remarks>It is up to the programmer to ensure that the global coordinates defined within the chunk's tree
        /// are consistent with the local coordinates of the region being written into.</remarks>
        public bool SaveChunkTree (int lcx, int lcz, NbtTree tree)
        {
            if (!LocalBoundsCheck(lcx, lcz)) {
                Region alt = GetForeignRegion(lcx, lcz);
                return (alt == null) ? false : alt.SaveChunkTree(ForeignX(lcx), ForeignZ(lcz), tree);
            }

            RegionFile rf = GetRegionFile();
            Stream zipstr = rf.GetChunkDataOutputStream(lcx, lcz);
            if (zipstr == null) {
                return false;
            }

            tree.WriteTo(zipstr);
            zipstr.Close();

            return true;
        }
示例#13
0
        static void Main(string[] args)
        {
            if (!File.Exists("level.dat")) {
                Console.WriteLine("Could not find level.dat");
                return;
            }

            NBTFile nf = new NBTFile("level.dat");
            NbtTree tree;

            using (Stream nbtstr = nf.GetDataInputStream()) {
                if (nbtstr == null) {
                    Console.WriteLine("Could not open level.dat");
                    return;
                }

                tree = new NbtTree(nbtstr);
            }

            TagNodeList list = tree.Root["FML"].ToTagCompound()["ItemData"].ToTagList();
            foreach (TagNodeCompound tag in list) {
                TagNodeString modid = tag["K"].ToTagString();
                if (modid.Data.Contains("modularpots:modularpots:")) {
                    modid.Data = modid.Data.Replace("modularpots:modularpots:", "modularpots:");
                    Console.WriteLine("Updating entry " + tag["V"].ToTagInt().Data + ": " + modid.Data);
                }
            }

            using (Stream zipstr = nf.GetDataOutputStream()) {
                if (zipstr == null) {
                    Console.WriteLine("Could not write back to level.dat");
                    return;
                }

                tree.WriteTo(zipstr);
            }

            Console.WriteLine("Update complete");
        }
示例#14
0
        private bool SaveChunkTree(int lcx, int lcz, NbtTree tree, int?timestamp)
        {
            if (!LocalBoundsCheck(lcx, lcz))
            {
                Region alt = GetForeignRegion(lcx, lcz);
                return((alt == null) ? false : alt.SaveChunkTree(ForeignX(lcx), ForeignZ(lcz), tree));
            }

            RegionFile rf     = GetRegionFile();
            Stream     zipstr = (timestamp == null)
                ? rf.GetChunkDataOutputStream(lcx, lcz)
                : rf.GetChunkDataOutputStream(lcx, lcz, (int)timestamp);

            if (zipstr == null)
            {
                return(false);
            }

            tree.WriteTo(zipstr);
            zipstr.Close();

            return(true);
        }
        /// <summary>
        /// 保存所有修改到 Region 文件
        /// </summary>
        internal void saveAll()
        {
            // 缓存变量
            RegionFile  lastRegion       = null;
            NbtTree     lastTree         = null;
            TagNodeList lastTileEntities = null;
            int         lastChunkX       = -1;
            int         lastChunkZ       = -1;

            // 遍历命令方块列表
            foreach (var commandBlock in this.CommandBlocks)
            {
                // 如果需要保存
                if (commandBlock.edit)
                {
                    // 读取目标区块的 TileEntities
                    if (lastRegion == commandBlock.region && commandBlock.chunkX == lastChunkX && commandBlock.chunkZ == lastChunkZ)
                    {
                        // 如果 region chunk 都没变 则触发缓存 继续用上次的 TileEntities
                    }
                    else
                    {
                        if (lastRegion != null)
                        {
                            // 保存之前的修改到文件
                            using (var stream = lastRegion.GetChunkDataOutputStream(lastChunkX, lastChunkZ)) {
                                lastTree.WriteTo(stream);
                            }
                        }

                        // 打开 Region 文件
                        lastRegion = commandBlock.region;
                        // 打开目标 Chunk
                        lastTree = new NbtTree();
                        lastTree.ReadFrom(lastRegion.GetChunkDataInputStream(commandBlock.chunkX, commandBlock.chunkZ));

                        // Level
                        var level = lastTree.Root["Level"] as TagNodeCompound;
                        // TileEntities
                        lastTileEntities = level["TileEntities"] as TagNodeList;

                        // 保存区块位置
                        lastChunkX = commandBlock.chunkX;
                        lastChunkZ = commandBlock.chunkZ;
                    }

                    // 遍历 TileEntity 列表
                    foreach (TagNodeCompound tileEntity in lastTileEntities)
                    {
                        // 当前 TileEntity 的坐标
                        int x = int.Parse(tileEntity["x"].ToString());
                        int y = int.Parse(tileEntity["y"].ToString());
                        int z = int.Parse(tileEntity["z"].ToString());

                        // 如果坐标一致
                        if (x == commandBlock.x && y == commandBlock.y && z == commandBlock.z)
                        {
                            // 修改 Command
                            tileEntity["Command"] = new TagNodeString(commandBlock.command);

                            // 输出调试信息
                            // System.Diagnostics.Debug.WriteLine("Save" + commandBlock);

                            // 设置 CommandBlock 的保存标记
                            commandBlock.edit = false;
                            break;
                        }
                    }
                }
            }

            if (lastRegion != null)
            {
                // 保存之前的修改到文件
                using (var str = lastRegion.GetChunkDataOutputStream(lastChunkX, lastChunkZ)) {
                    lastTree.WriteTo(str);
                }
            }
        }
示例#16
0
        private bool SaveChunkTree(int lcx, int lcz, NbtTree tree, int? timestamp)
        {
            if (!LocalBoundsCheck(lcx, lcz)) {
                Region alt = GetForeignRegion(lcx, lcz);
                return (alt == null) ? false : alt.SaveChunkTree(ForeignX(lcx), ForeignZ(lcz), tree);
            }

            RegionFile rf = GetRegionFile();
            Stream zipstr = (timestamp == null)
                ? rf.GetChunkDataOutputStream(lcx, lcz)
                : rf.GetChunkDataOutputStream(lcx, lcz, (int)timestamp);

            if (zipstr == null) {
                return false;
            }

            tree.WriteTo(zipstr);
            zipstr.Close();

            return true;
        }
示例#17
0
        public static byte[] GetEnchantmentNBTData(List<Enchantment> enchantments)
        {
            if (enchantments.Count < 1) return new byte[0];

            NbtTree nbt = new NbtTree();
            TagNodeList list = new TagNodeList(TagType.TAG_COMPOUND);

            TagNodeCompound compound;
            foreach (Enchantment ench in enchantments.ToArray())
            {
                compound = new TagNodeCompound();
                compound.Add("id", new TagNodeShort(ench.id));
                compound.Add("lvl", new TagNodeShort(ench.level));
                list.Add(compound);
            }

            nbt.Root.Add("ench", list);

            using (MemoryStream ms = new MemoryStream())
            {
                nbt.WriteTo(ms);
                return ms.ToArray().Compress(Ionic.Zlib.CompressionLevel.BestCompression, CompressionType.GZip);
            }
        }
示例#18
0
        public void Save(World w)
        {
            try
            {
                string path = CreatePath(w, x, z, true);
                string file = CreatePath(w, x, z);
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                NbtTree nbt = new NbtTree();
                nbt.Root.Add("Generated", new TagNodeByte((byte)(generated ? 1 : 0)));
                nbt.Root.Add("Populated", new TagNodeByte((byte)(populated ? 1 : 0)));
                nbt.Root.Add("Blocks", new TagNodeByteArray(blocks));
                nbt.Root.Add("Meta", new TagNodeByteArray(meta));
                nbt.Root.Add("BlockLight", new TagNodeByteArray(Light));
                nbt.Root.Add("SkyLight", new TagNodeByteArray(SkyL));
                nbt.Root.Add("HeightMap", new TagNodeByteArray(heightMap));
                nbt.Root.Add("HeightMapPrec", new TagNodeByteArray(precipitationHeightMap.ToByteArray()));
                TagNodeList     nbtList = new TagNodeList(TagType.TAG_COMPOUND);
                TagNodeCompound nbtCompound;
                lock (extra)
                    foreach (KeyValuePair <int, ushort> kvp in extra)
                    {
                        nbtCompound = new TagNodeCompound();
                        nbtCompound.Add("Pos", new TagNodeInt(kvp.Key));
                        nbtCompound.Add("Value", new TagNodeShort((short)kvp.Value));
                        nbtList.Add(nbtCompound);
                    }
                nbt.Root.Add("Extra", nbtList);
                nbtList = new TagNodeList(TagType.TAG_COMPOUND);
                List <Physics.Check> physChecks = w.physics.GetChunkChecks(x, z);
                foreach (Physics.Check check in physChecks)
                {
                    nbtCompound = new TagNodeCompound();
                    nbtCompound.Add("Pos", new TagNodeList(TagType.TAG_INT)
                    {
                        new TagNodeInt(check.x), new TagNodeInt(check.y), new TagNodeInt(check.z)
                    });
                    nbtCompound.Add("Meta", new TagNodeByte(check.meta));
                    nbtCompound.Add("Time", new TagNodeShort(check.time));
                    nbtList.Add(nbtCompound);
                }
                nbt.Root.Add("Physics", nbtList);
                nbtList = new TagNodeList(TagType.TAG_COMPOUND);
                List <Entity> entities = Entities; TagNodeCompound nbtCompound2;
                foreach (Entity e in entities)
                {
                    if (e.isPlayer)
                    {
                        continue;
                    }
                    nbtCompound = new TagNodeCompound();
                    nbtCompound.Add("Motion", new TagNodeList(TagType.TAG_DOUBLE)
                    {
                        new TagNodeDouble(e.velocity[0]), new TagNodeDouble(e.velocity[1]), new TagNodeDouble(e.velocity[2])
                    });
                    nbtCompound.Add("Pos", new TagNodeList(TagType.TAG_DOUBLE)
                    {
                        new TagNodeDouble(e.pos.x), new TagNodeDouble(e.pos.y), new TagNodeDouble(e.pos.z)
                    });
                    nbtCompound.Add("Rotation", new TagNodeList(TagType.TAG_FLOAT)
                    {
                        new TagNodeFloat(e.rot[0]), new TagNodeFloat(e.rot[1])
                    });
                    nbtCompound.Add("Type", new TagNodeByte((byte)e.Type));
                    nbtCompound.Add("Age", new TagNodeInt(e.age));
                    nbtCompound.Add("OnGround", new TagNodeByte(e.onground));
                    nbtCompound.Add("Health", new TagNodeShort(e.Health));
                    nbtCompound2 = new TagNodeCompound();
                    switch (e.Type)
                    {
                    case EntityType.AI:
                        nbtCompound2.Add("Type", new TagNodeByte(e.ai.type));
                        break;

                    case EntityType.Object:
                        nbtCompound2.Add("Type", new TagNodeByte(e.obj.type));
                        break;

                    case EntityType.Item:
                        nbtCompound2.Add("ID", new TagNodeShort(e.I.id));
                        nbtCompound2.Add("Count", new TagNodeByte(e.I.count));
                        nbtCompound2.Add("Meta", new TagNodeShort(e.I.meta));
                        break;
                    }
                    nbtCompound.Add("Data", nbtCompound2);
                    nbtList.Add(nbtCompound);
                }
                nbt.Root.Add("Entities", nbtList);
                nbtList = new TagNodeList(TagType.TAG_COMPOUND);
                foreach (Container c in GetContainers(w))
                {
                    nbtCompound = new TagNodeCompound();
                    nbtCompound.Add("Type", new TagNodeByte((byte)c.Type));
                    nbtCompound.Add("Pos", new TagNodeList(TagType.TAG_INT)
                    {
                        new TagNodeInt((int)c.Pos.x), new TagNodeInt((int)c.Pos.y), new TagNodeInt((int)c.Pos.z)
                    });
                    nbtCompound.Add("Items", c.GetNBTData());
                    nbtList.Add(nbtCompound);
                    //Console.WriteLine("SAVED CONTAINER @ " + (int)c.Pos.x + "," + (int)c.Pos.y + "," + (int)c.Pos.z + " @ " + x + "," + z);
                }
                nbt.Root.Add("Containers", nbtList);

                try
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        nbt.WriteTo(ms);
                        byte[] bytes = ms.ToArray().Compress(CompressionLevel.BestCompression, CompressionType.GZip);
                        using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
                            fs.Write(bytes, 0, bytes.Length);
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogToFile("Error saving chunk at " + x + "," + z + "!");
                    Logger.LogErrorToFile(ex);
                }

                this._dirty = false;
                //Console.WriteLine("SAVED " + x + " " + z);
            }
            catch (Exception ex) { Logger.LogError(ex); }
        }
示例#19
0
        /// <summary>
        /// Exports the <see cref="Schematic"/> object to a schematic file.
        /// </summary>
        /// <param name="path">The path to write out the schematic file to.</param>
        public void Export(string path)
        {
            int xdim = _blockset.XDim;
            int ydim = _blockset.YDim;
            int zdim = _blockset.ZDim;

            byte[] blockData = new byte[xdim * ydim * zdim];
            byte[] dataData  = new byte[xdim * ydim * zdim];

            YZXByteArray schemaBlocks = new YZXByteArray(_blockset.XDim, _blockset.YDim, _blockset.ZDim, blockData);
            YZXByteArray schemaData   = new YZXByteArray(_blockset.XDim, _blockset.YDim, _blockset.ZDim, dataData);

            TagNodeList entities     = new TagNodeList(TagType.TAG_COMPOUND);
            TagNodeList tileEntities = new TagNodeList(TagType.TAG_COMPOUND);

            for (int x = 0; x < xdim; x++)
            {
                for (int z = 0; z < zdim; z++)
                {
                    for (int y = 0; y < ydim; y++)
                    {
                        AlphaBlock block = _blockset.GetBlock(x, y, z);
                        schemaBlocks[x, y, z] = (byte)block.ID;
                        schemaData[x, y, z]   = (byte)block.Data;

                        TileEntity te = block.GetTileEntity();
                        if (te != null)
                        {
                            te.X = x;
                            te.Y = y;
                            te.Z = z;

                            tileEntities.Add(te.BuildTree());
                        }
                    }
                }
            }

            foreach (EntityTyped e in _entityset)
            {
                entities.Add(e.BuildTree());
            }

            TagNodeCompound schematic = new TagNodeCompound();

            schematic["Width"]  = new TagNodeShort((short)xdim);
            schematic["Length"] = new TagNodeShort((short)zdim);
            schematic["Height"] = new TagNodeShort((short)ydim);

            schematic["Entities"]     = entities;
            schematic["TileEntities"] = tileEntities;

            schematic["Materials"] = new TagNodeString("Alpha");

            schematic["Blocks"] = new TagNodeByteArray(blockData);
            schematic["Data"]   = new TagNodeByteArray(dataData);

            NBTFile schematicFile = new NBTFile(path);

            Stream nbtStream = schematicFile.GetDataOutputStream();

            if (nbtStream == null)
            {
                return;
            }

            NbtTree tree = new NbtTree(schematic, "Schematic");

            tree.WriteTo(nbtStream);

            nbtStream.Close();
        }
示例#20
0
        /// <summary>
        /// Exports the <see cref="Schematic"/> object to a schematic file.
        /// </summary>
        /// <param name="path">The path to write out the schematic file to.</param>
        public void Export(string path)
        {
            int xdim = _blockset.XDim;
            int ydim = _blockset.YDim;
            int zdim = _blockset.ZDim;

            byte[] blockData = new byte[xdim * ydim * zdim];
            byte[] dataData = new byte[xdim * ydim * zdim];

            YZXByteArray schemaBlocks = new YZXByteArray(_blockset.XDim, _blockset.YDim, _blockset.ZDim, blockData);
            YZXByteArray schemaData = new YZXByteArray(_blockset.XDim, _blockset.YDim, _blockset.ZDim, dataData);

            TagNodeList entities = new TagNodeList(TagType.TAG_COMPOUND);
            TagNodeList tileEntities = new TagNodeList(TagType.TAG_COMPOUND);

            for (int x = 0; x < xdim; x++) {
                for (int z = 0; z < zdim; z++) {
                    for (int y = 0; y < ydim; y++) {
                        AlphaBlock block = _blockset.GetBlock(x, y, z);
                        schemaBlocks[x, y, z] = (byte)block.ID;
                        schemaData[x, y, z] = (byte)block.Data;

                        TileEntity te = block.GetTileEntity();
                        if (te != null) {
                            te.X = x;
                            te.Y = y;
                            te.Z = z;

                            tileEntities.Add(te.BuildTree());
                        }
                    }
                }
            }

            foreach (TypedEntity e in _entityset) {
                entities.Add(e.BuildTree());
            }

            TagNodeCompound schematic = new TagNodeCompound();
            schematic["Width"] = new TagNodeShort((short)xdim);
            schematic["Length"] = new TagNodeShort((short)zdim);
            schematic["Height"] = new TagNodeShort((short)ydim);

            schematic["Entities"] = entities;
            schematic["TileEntities"] = tileEntities;

            schematic["Materials"] = new TagNodeString("Alpha");

            schematic["Blocks"] = new TagNodeByteArray(blockData);
            schematic["Data"] = new TagNodeByteArray(dataData);

            NBTFile schematicFile = new NBTFile(path);

            Stream nbtStream = schematicFile.GetDataOutputStream();
            if (nbtStream == null) {
                return;
            }

            NbtTree tree = new NbtTree(schematic, "Schematic");
            tree.WriteTo(nbtStream);

            nbtStream.Close();
        }
示例#21
0
文件: Item.cs 项目: Cazzar/ForgeCraft
 public static byte[] GetEnchantmentNBTData(List<Enchantment> enchantments)
 {
     if (enchantments.Count < 1) return new byte[0];
     NbtTree nbt = new NbtTree();
     nbt.Root.Add("ench", GetEnchantmentNBT(enchantments));
     using (MemoryStream ms = new MemoryStream())
     {
         nbt.WriteTo(ms);
         return ms.ToArray().Compress(Ionic.Zlib.CompressionLevel.BestCompression, CompressionType.GZip);
     }
 }
示例#22
0
        /// <summary>
        /// Saves a raw <see cref="NbtTree"/> representing a player to the given player's file.
        /// </summary>
        /// <param name="name">The name of the player to write data to.</param>
        /// <param name="tree">The player's data as an <see cref="NbtTree"/>.</param>
        /// <exception cref="NbtIOException">Thrown when the manager cannot initialize an NBT data stream for output.</exception>
        public void SetPlayerTree(string name, NbtTree tree)
        {
            PlayerFile pf = GetPlayerFile(name);
            Stream zipstr = pf.GetDataOutputStream();
            if (zipstr == null) {
                throw new NbtIOException("Failed to initialize NBT data stream for output.");
            }

            tree.WriteTo(zipstr);
            zipstr.Close();
        }
        private static void RunOptionsAndReturnExitCode(CliOptions opts)
        {
            Console.Clear();
            var cgui = new ConsoleGui();

            var pbBlocks = new ConsoleGuiProgressBar(0, 0, Console.WindowWidth, 0, 1)
            {
                ForegroundColor = ConsoleColor.Green,
                BackgroundColor = ConsoleColor.DarkGray
            };

            var lBlocksTotal     = new ConsoleGuiLabel(0, 1, "Total Blocks    : {0}");
            var lBlocksRemaining = new ConsoleGuiLabel(0, 2, "Remaining Blocks: {0}");
            var lBlocksFailed    = new ConsoleGuiLabel(0, 3, "Failed Blocks   : {0}");
            var lStatus          = new ConsoleGuiLabel(0, 4, "Status          : {0}");

            cgui.Add(pbBlocks);
            cgui.Add(lBlocksTotal);
            cgui.Add(lBlocksRemaining);
            cgui.Add(lBlocksFailed);
            cgui.Add(lStatus);

            var failed = new List <int>();

            var inputMap  = NbtMap.Load(opts.InputMap);
            var outputMap = NbtMap.Load(opts.OutputMap);

            var inputSchematic = new NBTFile(opts.InputSchematic);
            var tag            = new NbtTree(inputSchematic.GetDataInputStream()).Root;

            var bLower    = tag["Blocks"].ToTagByteArray().Data;
            var addBlocks = new byte[(bLower.Length >> 1) + 1];

            if (tag.ContainsKey("AddBlocks"))
            {
                addBlocks = tag["AddBlocks"].ToTagByteArray().Data;
            }

            lStatus.Value = "Processing...";

            for (var index = 0; index < bLower.Length; index++)
            {
                short oldId;
                if ((index & 1) == 1)
                {
                    oldId = (short)(((addBlocks[index >> 1] & 0x0F) << 8) + (bLower[index] & 0xFF));
                }
                else
                {
                    oldId = (short)(((addBlocks[index >> 1] & 0xF0) << 4) + (bLower[index] & 0xFF));
                }

                if (!TranslateId(oldId, inputMap, outputMap, out var newId))
                {
                    failed.Add(oldId);
                }

                bLower[index]         = (byte)(newId & 0xFF);
                addBlocks[index >> 1] = (byte)(((index & 1) == 1) ?
                                               addBlocks[index >> 1] & 0xF0 | (newId >> 8) & 0xF
                    : addBlocks[index >> 1] & 0xF | ((newId >> 8) & 0xF) << 4);

                // Gui
                lBlocksTotal.Value     = index + 1;
                lBlocksRemaining.Value = bLower.Length - index - 1;
                lBlocksFailed.Value    = failed.Count;
                pbBlocks.Value         = (float)index / bLower.Length;

                if (index % 10000 == 0)
                {
                    cgui.Render();
                }
            }

            cgui.Render();

            tag["Blocks"] = new TagNodeByteArray(bLower);

            if (!tag.ContainsKey("AddBlocks"))
            {
                tag.Add("AddBlocks", new TagNodeByteArray(addBlocks));
            }
            else
            {
                tag["AddBlocks"] = new TagNodeByteArray(addBlocks);
            }

            lStatus.Value = "Saving...";
            cgui.Render();

            var schematicFile = new NBTFile(opts.OutputSchematic);

            using (var nbtStream = schematicFile.GetDataOutputStream())
            {
                if (nbtStream == null)
                {
                    return;
                }

                var tree = new NbtTree(tag, "Schematic");
                tree.WriteTo(nbtStream);
            }

            lStatus.Value = "Done. Press Enter.";
            cgui.Render();

            Console.WriteLine();
            foreach (var i in failed)
            {
                Console.WriteLine($"Failed ID: {i}");
            }

            Console.ReadKey();
        }
示例#24
0
        public void Save(World w)
        {
            try
            {
                string path = CreatePath(w, x, z, true);
                string file = CreatePath(w, x, z);
                if (!Directory.Exists(path)) Directory.CreateDirectory(path);

                NbtTree nbt = new NbtTree();
                nbt.Root.Add("Generated", new TagNodeByte((byte)(generated ? 1 : 0)));
                nbt.Root.Add("Populated", new TagNodeByte((byte)(populated ? 1 : 0)));
                nbt.Root.Add("Blocks", new TagNodeByteArray(blocks));
                nbt.Root.Add("Meta", new TagNodeByteArray(meta));
                nbt.Root.Add("BlockLight", new TagNodeByteArray(Light));
                nbt.Root.Add("SkyLight", new TagNodeByteArray(SkyL));
                nbt.Root.Add("HeightMap", new TagNodeByteArray(heightMap));
                nbt.Root.Add("HeightMapPrec", new TagNodeByteArray(precipitationHeightMap.ToByteArray()));
                TagNodeList nbtList = new TagNodeList(TagType.TAG_COMPOUND);
                TagNodeCompound nbtCompound;
                lock (extra)
                    foreach (KeyValuePair<int, ushort> kvp in extra)
                    {
                        nbtCompound = new TagNodeCompound();
                        nbtCompound.Add("Pos", new TagNodeInt(kvp.Key));
                        nbtCompound.Add("Value", new TagNodeShort((short)kvp.Value));
                        nbtList.Add(nbtCompound);
                    }
                nbt.Root.Add("Extra", nbtList);
                nbtList = new TagNodeList(TagType.TAG_COMPOUND);
                List<Physics.Check> physChecks = w.physics.GetChunkChecks(x, z);
                foreach (Physics.Check check in physChecks)
                {
                    nbtCompound = new TagNodeCompound();
                    nbtCompound.Add("Pos", new TagNodeList(TagType.TAG_INT) { new TagNodeInt(check.x), new TagNodeInt(check.y), new TagNodeInt(check.z) });
                    nbtCompound.Add("Meta", new TagNodeByte(check.meta));
                    nbtCompound.Add("Time", new TagNodeShort(check.time));
                    nbtList.Add(nbtCompound);
                }
                nbt.Root.Add("Physics", nbtList);
                nbtList = new TagNodeList(TagType.TAG_COMPOUND);
                List<Entity> entities = Entities; TagNodeCompound nbtCompound2;
                foreach (Entity e in entities)
                {
                    if (e.isPlayer) continue;
                    nbtCompound = new TagNodeCompound();
                    nbtCompound.Add("Motion", new TagNodeList(TagType.TAG_DOUBLE) { new TagNodeDouble(e.velocity[0]), new TagNodeDouble(e.velocity[1]), new TagNodeDouble(e.velocity[2]) });
                    nbtCompound.Add("Pos", new TagNodeList(TagType.TAG_DOUBLE) { new TagNodeDouble(e.pos.x), new TagNodeDouble(e.pos.y), new TagNodeDouble(e.pos.z) });
                    nbtCompound.Add("Rotation", new TagNodeList(TagType.TAG_FLOAT) { new TagNodeFloat(e.rot[0]), new TagNodeFloat(e.rot[1]) });
                    nbtCompound.Add("Type", new TagNodeByte((byte)e.Type));
                    nbtCompound.Add("Age", new TagNodeInt(e.age));
                    nbtCompound.Add("OnGround", new TagNodeByte(e.onground));
                    nbtCompound.Add("Health", new TagNodeShort(e.Health));
                    nbtCompound2 = new TagNodeCompound();
                    switch (e.Type)
                    {
                        case EntityType.AI:
                            nbtCompound2.Add("Type", new TagNodeByte(e.ai.type));
                            break;
                        case EntityType.Object:
                            nbtCompound2.Add("Type", new TagNodeByte(e.obj.type));
                            break;
                        case EntityType.Item:
                            nbtCompound2.Add("ID", new TagNodeShort(e.I.id));
                            nbtCompound2.Add("Count", new TagNodeByte(e.I.count));
                            nbtCompound2.Add("Meta", new TagNodeShort(e.I.meta));
                            break;
                    }
                    nbtCompound.Add("Data", nbtCompound2);
                    nbtList.Add(nbtCompound);
                }
                nbt.Root.Add("Entities", nbtList);
                nbtList = new TagNodeList(TagType.TAG_COMPOUND);
                foreach (Container c in GetContainers(w))
                {
                    nbtCompound = new TagNodeCompound();
                    nbtCompound.Add("Type", new TagNodeByte((byte)c.Type));
                    nbtCompound.Add("Pos", new TagNodeList(TagType.TAG_INT) { new TagNodeInt((int)c.Pos.x), new TagNodeInt((int)c.Pos.y), new TagNodeInt((int)c.Pos.z) });
                    nbtCompound.Add("Items", c.GetNBTData());
                    nbtList.Add(nbtCompound);
                    //Console.WriteLine("SAVED CONTAINER @ " + (int)c.Pos.x + "," + (int)c.Pos.y + "," + (int)c.Pos.z + " @ " + x + "," + z);
                }
                nbt.Root.Add("Containers", nbtList);

                try
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        nbt.WriteTo(ms);
                        byte[] bytes = ms.ToArray().Compress(CompressionLevel.BestCompression, CompressionType.GZip);
                        using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
                            fs.Write(bytes, 0, bytes.Length);
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogToFile("Error saving chunk at " + x + "," + z + "!");
                    Logger.LogErrorToFile(ex);
                }

                this._dirty = false;
                //Console.WriteLine("SAVED " + x + " " + z);
            }
            catch (Exception ex) { Logger.LogError(ex); }
        }
示例#25
0
 private void Apply(string path, List <LanguageItem> items, List <LanguageItem> signs, List <LanguageItem> containers, List <LanguageItem> Entities, List <LanguageItem> MobSpawners)
 {
     //try
     //{
     string[] files = Directory.GetFiles(path + "\\region");
     for (int i = 0; i < files.Length; i++)
     {
         Dispatcher.BeginInvoke(new Action(delegate { totalProgress.Value += 1; progress.Value = 0; }));
         RegionFile region = new RegionFile(files[i]);
         for (int I = 0; I < 32; I++)
         {
             for (int J = 0; J < 32; J++)
             {
                 Dispatcher.BeginInvoke(new Action(delegate { progress.Value += 1; }));
                 if (region.HasChunk(I, J))
                 {
                     try
                     {
                         NbtTree nbtTree = new NbtTree();
                         nbtTree.ReadFrom(region.GetChunkDataInputStream(I, J));
                         TagNodeList tagNodeList = nbtTree.Root["Level"].ToTagCompound()["TileEntities"].ToTagList();
                         TagNodeList entityList  = nbtTree.Root["Level"].ToTagCompound()["Entities"].ToTagList();
                         bool        flag        = false;
                         if (entityList != null)
                         {
                             foreach (TagNodeCompound tagNodeCompound in entityList)
                             {
                                 if (LangTranslator.EntityTranslator(tagNodeCompound, Entities))
                                 {
                                     flag = true;
                                 }
                             }
                         }
                         if (tagNodeList != null)
                         {
                             foreach (TagNodeCompound tagNodeCompound in tagNodeList)
                             {
                                 string data = tagNodeCompound["id"].ToTagString().Data;
                                 if (data == CMDBLOCK)
                                 {
                                     if (LangTranslator.CommandBlockTranslator(tagNodeCompound, items))
                                     {
                                         flag = true;
                                     }
                                 }
                                 else if (data == SIGN)
                                 {
                                     if (LangTranslator.SignTranslator(tagNodeCompound, signs))
                                     {
                                         flag = true;
                                     }
                                 }
                                 else if (tagNodeCompound.ContainsKey("Items") || tagNodeCompound.ContainsKey("RecordItem"))
                                 {
                                     if (LangTranslator.ContainerTranslator(tagNodeCompound, containers))
                                     {
                                         flag = true;
                                     }
                                 }
                                 else if (tagNodeCompound.ContainsKey("SpawnData"))
                                 {
                                     if (LangTranslator.EntityTranslator(tagNodeCompound["SpawnData"].ToTagCompound(), MobSpawners))
                                     {
                                         flag = true;
                                     }
                                 }
                             }
                         }
                         if (flag)
                         {
                             using (Stream chunkDataOutputStream = region.GetChunkDataOutputStream(I, J))
                             {
                                 nbtTree.WriteTo(chunkDataOutputStream);
                             }
                         }
                     }
                     catch { }
                 }
             }
         }
     }
     Dispatcher.BeginInvoke(new Action(delegate { progress.Value = 0; totalProgress.Value = 0; progress.IsIndeterminate = true; totalProgress.IsIndeterminate = true; }));
     //}
     //catch
     //{
     //    Dispatcher.BeginInvoke(new Action(delegate { (System.Windows.Application.Current.MainWindow as MetroWindow).ShowMessageAsync("无法完成操作", "存档可能已经损坏", MessageDialogStyle.Affirmative, new MetroDialogSettings() { AffirmativeButtonText = "确定" }); }));
     //}
 }