public static NbtMap Load(string filename) { var map = new NbtMap(); var nf = new NBTFile(filename); using (var nbtstr = nf.GetDataInputStream()) { var tree = new NbtTree(nbtstr); var root = tree.Root["map"]; var list = root.ToTagList(); foreach (var tag in list) { var k = tag.ToTagCompound()["k"].ToTagString(); var v = (short)tag.ToTagCompound()["v"].ToTagInt(); if (!map.ContainsKey(v)) { map.Add(v, k); } } return(map); } }
public static Chunk Load(NbtTree tag) { var dataVersion = tag.Root["DataVersion"].ToTagInt().Data; var level = tag.Root["Level"].ToTagCompound(); var sectionsList = level["Sections"].ToTagList(); if (sectionsList.Count == 0) { return(null); } var x = level["xPos"].ToTagInt().Data; var z = level["zPos"].ToTagInt().Data; var pos = new Coord2(x, z); var sections = sectionsList.Select(node => ChunkSection.Load(dataVersion, pos, node.ToTagCompound())).Where(section => section != null).ToArray(); var tiles = level["TileEntities"] .ToTagList() .Select(node => node.ToTagCompound()) .ToDictionary(node => new Coord3(node["x"].ToTagInt().Data, node["y"].ToTagInt().Data, node["z"].ToTagInt().Data), node => node); return(new Chunk(pos, sections, tiles)); }
/// <summary> /// Loads the Chunk from an NBT tree rooted at the given TagValue node. /// </summary> /// <param name="tree">Root node of an NBT tree.</param> /// <returns>A reference to the current Chunk, or null if the tree is unparsable.</returns> public Chunk LoadTree(TagNode tree) { TagNodeCompound ctree = tree as TagNodeCompound; if (ctree == null) { return(null); } _tree = new NbtTree(ctree); TagNodeCompound level = _tree.Root["Level"] as TagNodeCompound; _blocks = new XZYByteArray(XDIM, YDIM, ZDIM, level["Blocks"] as TagNodeByteArray); _data = new XZYNibbleArray(XDIM, YDIM, ZDIM, level["Data"] as TagNodeByteArray); _blockLight = new XZYNibbleArray(XDIM, YDIM, ZDIM, level["BlockLight"] as TagNodeByteArray); _skyLight = new XZYNibbleArray(XDIM, YDIM, ZDIM, level["SkyLight"] as TagNodeByteArray); _heightMap = new ZXByteArray(XDIM, ZDIM, level["HeightMap"] as TagNodeByteArray); _entities = level["Entities"] as TagNodeList; _tileEntities = level["TileEntities"] as TagNodeList; if (level.ContainsKey("TileTicks")) { _tileTicks = level["TileTicks"] as TagNodeList; } else { _tileTicks = new TagNodeList(TagType.TAG_COMPOUND); } // List-type patch up if (_entities.Count == 0) { level["Entities"] = new TagNodeList(TagType.TAG_COMPOUND); _entities = level["Entities"] as TagNodeList; } if (_tileEntities.Count == 0) { level["TileEntities"] = new TagNodeList(TagType.TAG_COMPOUND); _tileEntities = level["TileEntities"] as TagNodeList; } if (_tileTicks.Count == 0) { level["TileTicks"] = new TagNodeList(TagType.TAG_COMPOUND); _tileTicks = level["TileTicks"] as TagNodeList; } _cx = level["xPos"].ToTagInt(); _cz = level["zPos"].ToTagInt(); _blockManager = new AlphaBlockCollection(_blocks, _data, _blockLight, _skyLight, _heightMap, _tileEntities, _tileTicks); _entityManager = new EntityCollection(_entities); return(this); }
public void LoadTreeTest_1_8_3_survival() { NbtTree levelTree = LoadLevelTree(@"..\..\Data\1_8_3-survival\level.dat"); Level level = new Level(null); level = level.LoadTreeSafe(levelTree.Root); Assert.IsNotNull(level); }
public void ReadEnchantmentNBTData(byte[] data) { using (MemoryStream ms = new MemoryStream(data.Decompress(CompressionType.GZip))) { try { NbtTree nbt = new NbtTree(ms); LoadEnchantmentNBT(nbt.Root["ench"].ToTagList()); } catch { Logger.Log("NBT data is invalid."); } } }
public static TagNodeCompound GetLevelDat() { if (levelDat == null) { string path = Path.Combine(savePath, "level.dat"); levelFile = new NBTFile(path); levelTree = new NbtTree(); levelTree.ReadFrom(levelFile.GetDataInputStream()); levelDat = levelTree.Root["Data"] as TagNodeCompound; } return(levelDat); }
public static TagNode DeserializeNode (byte[] data) { NbtTree tree = new NbtTree(); using (MemoryStream ms = new MemoryStream(data)) { tree.ReadFrom(ms); } TagNodeCompound root = tree.Root; if (root == null || !root.ContainsKey("root")) return null; return root["root"]; }
public static World Load(string filename) { var nf = new NBTFile(filename); using var nbtstr = nf.GetDataInputStream(); var tree = new NbtTree(nbtstr); var root = tree.Root["Data"].ToTagCompound(); var dataVersion = root["DataVersion"].ToTagInt().Data; return(new World(filename, dataVersion)); }
/// <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(); }
/// <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(); }
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; } }
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)); } }
private bool LoadLevel () { NBTFile nf = new NBTFile(IO.Path.Combine(Path, _levelFile)); Stream nbtstr = nf.GetDataInputStream(); if (nbtstr == null) { return false; } NbtTree tree = new NbtTree(nbtstr); _level = new Level(this); _level = _level.LoadTreeSafe(tree.Root); return _level != null; }
private static NbtFileDataNode TryCreateFrom (string path, CompressionType compressionType) { try { NBTFile file = new NBTFile(path); NbtTree tree = new NbtTree(); tree.ReadFrom(file.GetDataInputStream(compressionType)); if (tree.Root == null) return null; return new NbtFileDataNode(path, compressionType); } catch { return null; } }
/// <inheritdoc /> public Structure Load(string filename) { var input = new NBTFile(filename); var nbt = new NbtTree(input.GetDataInputStream()).Root; var length = nbt["Length"].ToTagInt().Data; var width = nbt["Width"].ToTagInt().Data; var height = nbt["Height"].ToTagInt().Data; var palette = LoadPalette(nbt); var tiles = LoadTileEntities(nbt); var blocks = LoadBlocks(nbt, palette, length, width, tiles); var entities = LoadEntities(nbt); return(new SchematicStructure(blocks, entities, palette, width, height, length)); }
protected override void ExpandCore () { if (_tree == null) { _tree = new NbtTree(); _tree.ReadFrom(_regionFile.GetChunkDataInputStream(_x, _z)); if (_tree.Root != null) _container = new CompoundTagContainer(_tree.Root); } foreach (TagNode tag in _tree.Root.Values) { TagDataNode node = TagDataNode.CreateFromTag(tag); if (node != null) Nodes.Add(node); } }
public static TagNodeCompound GetPlayerData() { if (playerData == null) { string path = Path.Combine(savePath, "playerdata"); string[] files = Directory.GetFiles(path); if (files.Length == 0) { throw new Exception("no player data"); } playerFile = new PlayerFile(files[0]); playerData = new NbtTree(); playerData.ReadFrom(playerFile.GetDataInputStream()); } return(playerData.Root); }
NbtTree LoadLevelTree(string path) { NBTFile nf = new NBTFile(path); NbtTree tree = null; using (Stream nbtstr = nf.GetDataInputStream()) { if (nbtstr == null) { return(null); } tree = new NbtTree(nbtstr); } return(tree); }
public static FabricRegistry Load(string filename) { var nf = new NBTFile(filename); using var nbtstr = nf.GetDataInputStream(); var tree = new NbtTree(nbtstr); var version = tree.Root["version"].ToTagInt().Data; var registries = tree.Root["registries"].ToTagCompound(); var blockMap = CreateMap(registries["minecraft:block"]); var blockEntityTypeMap = CreateMap(registries["minecraft:block_entity_type"]); var itemMap = CreateMap(registries["minecraft:item"]); return(new FabricRegistry(version, blockMap, blockEntityTypeMap, itemMap)); }
NbtTree LoadLevelTree(string path) { NBTFile nf = new NBTFile(path); NbtTree tree = null; using (Stream nbtstr = nf.GetDataInputStream()) { if (nbtstr == null) { return null; } tree = new NbtTree(nbtstr); } return tree; }
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); }
public WorldData(string WorldPath) { _LoadedMods = new List <string>(); BlockIDs = new Dictionary <string, int>(); NBTFile LevelFile = new NBTFile(Path.Combine(WorldPath, "level.dat")); NbtTree LevelTree; using (Stream nbtstr = LevelFile.GetDataInputStream()) { LevelTree = new NbtTree(nbtstr); } _LoadedMods.Add("minecraft"); if (LevelTree.Root.ContainsKey("FML")) { TagNodeList IDList = (TagNodeList)(((TagNodeCompound)LevelTree.Root["FML"])["ItemData"]); TagNodeList ModList = (TagNodeList)(((TagNodeCompound)LevelTree.Root["FML"])["ModList"]); foreach (TagNodeCompound Entry in IDList) { string Key = ((TagNodeString)Entry["K"]).Data.Trim(' ', '', ''); // Non-visible control characters in those last two entries int Value = ((TagNodeInt)Entry["v"]).Data; BlockIDs.Add(Key, Value); } foreach (TagNodeCompound Entry in ModList) { _LoadedMods.Add(((TagNodeString)Entry["ModId"]).Data); } } else { // Load default vanilla stuff here StreamReader TR = new StreamReader(Properties.Resources.BaseIDs); string[] Line; while (!TR.EndOfStream) { Line = TR.ReadLine().Split(' '); BlockIDs.Add(Line[1], int.Parse(Line[0])); } } }
private static NbtFileDataNode TryCreateFrom(string path, CompressionType compressionType) { try { var file = new NBTFile(path); var tree = new NbtTree(); tree.ReadFrom(file.GetDataInputStream(compressionType)); if (tree.Root == null) return null; return new NbtFileDataNode(path, compressionType); } catch { return null; } }
// 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; }
/// <summary> /// Gets the <see cref="NbtTree"/> for a chunk given local coordinates into the region. /// </summary> /// <param name="lcx">The local X-coordinate of a chunk within the region.</param> /// <param name="lcz">The local Z-coordinate of a chunk within the region.</param> /// <returns>An <see cref="NbtTree"/> for a local chunk, or null if there is no chunk at the given coordinates.</returns> public NbtTree GetChunkTree (int lcx, int lcz) { if (!LocalBoundsCheck(lcx, lcz)) { Region alt = GetForeignRegion(lcx, lcz); return (alt == null) ? null : alt.GetChunkTree(ForeignX(lcx), ForeignZ(lcz)); } RegionFile rf = GetRegionFile(); Stream nbtstr = rf.GetChunkDataInputStream(lcx, lcz); if (nbtstr == null) { return null; } NbtTree tree = new NbtTree(nbtstr); nbtstr.Close(); return tree; }
/// <inheritdoc /> public Structure Load(string filename) { var input = new NBTFile(filename); var nbt = new NbtTree(input.GetDataInputStream()).Root; var dataVersion = nbt["DataVersion"].ToTagInt().Data; var author = nbt.ContainsKey("author") ? nbt["author"].ToTagString().Data : null; var size = nbt["size"].ToTagList().Select(node => node.ToTagInt().Data).ToArray(); var width = size[0]; var height = size[1]; var length = size[2]; var palette = LoadPalette(nbt); var blocks = LoadBlocks(nbt, palette); var entities = LoadEntities(nbt); return(new StructureBlockStructure(author, width, height, length, blocks, entities)); }
/// <summary> /// 通过 Region 文件列表构造命令方块编辑工具类的实例 /// </summary> /// <param name="files">Region 文件列表</param> internal CommandBlockIO(string[] files) { // 遍历文件列表 foreach (var file in files) { // 打开 Region 文件 // TODO 非 Region 文件可能抛异常 var region = new RegionFile(file); // 添加到 Region 列表 this.regions.Add(region); // 遍历 Chunk 列表 for (var chunkX = 0; chunkX < 32; chunkX++) { for (var chunkZ = 0; chunkZ < 32; chunkZ++) { if (region.HasChunk(chunkX, chunkZ)) { var tree = new NbtTree(); tree.ReadFrom(region.GetChunkDataInputStream(chunkX, chunkZ)); // Level var level = tree.Root["Level"] as TagNodeCompound; // TileEntities var tileEntities = level["TileEntities"] as TagNodeList; // 遍历 TileEntity 列表 foreach (TagNodeCompound tileEntity in tileEntities) { // 如果是 CommandBlock if (tileEntity["id"].ToString().Equals("Control")) { // 加入 CommandBlock 列表 this.CommandBlocks.Add(new TileCommandBlock(tileEntity, region, chunkX, chunkZ)); // 输出调试信息 // System.Diagnostics.Debug.WriteLine("Add" + this.commandBlocks[this.commandBlocks.Count - 1]); } } } } } } }
private void BuildNBTTree() { int elements2 = XDIM * ZDIM; int elements3 = elements2 * YDIM; TagNodeByteArray blocks = new TagNodeByteArray(new byte[elements3]); TagNodeByteArray data = new TagNodeByteArray(new byte[elements3 >> 1]); TagNodeByteArray blocklight = new TagNodeByteArray(new byte[elements3 >> 1]); TagNodeByteArray skylight = new TagNodeByteArray(new byte[elements3 >> 1]); TagNodeByteArray heightMap = new TagNodeByteArray(new byte[elements2]); _blocks = new XZYByteArray(XDIM, YDIM, ZDIM, blocks); _data = new XZYNibbleArray(XDIM, YDIM, ZDIM, data); _blockLight = new XZYNibbleArray(XDIM, YDIM, ZDIM, blocklight); _skyLight = new XZYNibbleArray(XDIM, YDIM, ZDIM, skylight); _heightMap = new ZXByteArray(XDIM, ZDIM, heightMap); _entities = new TagNodeList(TagType.TAG_COMPOUND); _tileEntities = new TagNodeList(TagType.TAG_COMPOUND); _tileTicks = new TagNodeList(TagType.TAG_COMPOUND); TagNodeCompound level = new TagNodeCompound(); level.Add("Blocks", blocks); level.Add("Data", data); level.Add("SkyLight", blocklight); level.Add("BlockLight", skylight); level.Add("HeightMap", heightMap); level.Add("Entities", _entities); level.Add("TileEntities", _tileEntities); level.Add("TileTicks", _tileTicks); level.Add("LastUpdate", new TagNodeLong(Timestamp())); level.Add("xPos", new TagNodeInt(_cx)); level.Add("zPos", new TagNodeInt(_cz)); level.Add("TerrainPopulated", new TagNodeByte()); _tree = new NbtTree(); _tree.Root.Add("Level", level); _blockManager = new AlphaBlockCollection(_blocks, _data, _blockLight, _skyLight, _heightMap, _tileEntities); _entityManager = new EntityCollection(_entities); }
private bool LoadLevel() { NBTFile nf = new NBTFile(IO.Path.Combine(Path, _levelFile)); NbtTree tree; using (Stream nbtstr = nf.GetDataInputStream()) { if (nbtstr == null) { return(false); } tree = new NbtTree(nbtstr); } _level = new Level(this); _level = _level.LoadTreeSafe(tree.Root); return(_level != null); }
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"); }
public async static Task <TagNodeCompound> GetChunkNodeAsync(int x, int z) { Vector2Int key = new Vector2Int(x, z); if (!chunkDictNBT.ContainsKey(key)) { int regionX = GetRegionCoordinate(x); int regionZ = GetRegionCoordinate(z); RegionFile region = GetRegion(regionX, regionZ); if (region != null) { int _x = x - regionX * 32; int _z = z - regionZ * 32; if (region.HasChunk(_x, _z)) { NbtTree _tree = new NbtTree(); Stream stream = region.GetChunkDataInputStream(_x, _z); await Task.Run(() => { _tree.ReadFrom(stream); }); chunkDictNBT[key] = _tree; } } else { Debug.LogError("Region does not exist! need generation."); } } if (chunkDictNBT.ContainsKey(key)) { return(chunkDictNBT[key].Root); } return(null); }
internal static void TryLoadFile(TreeNodeCollection parent, string path) { string ext = Path.GetExtension(path); if (ext == ".mcr" || ext == ".mca") { TreeNode node = ServerNode.CreateLazyRegion(path); parent.Add(node); LinkDataNodeParent(node, node.Parent); return; } if (ext == ".dat" || ext == ".nbt" || ext == ".schematic") { try { NBTFile file = new NBTFile(path); NbtTree tree = new NbtTree(); tree.ReadFrom(file.GetDataInputStream()); TreeNode node = ServerNode.CreateLazyNbt(path, CompressionType.GZip); parent.Add(node); LinkDataNodeParent(node, node.Parent); return; } catch { } try { NBTFile file = new NBTFile(path); NbtTree tree = new NbtTree(); tree.ReadFrom(file.GetDataInputStream(CompressionType.None)); TreeNode node = ServerNode.CreateLazyNbt(path, CompressionType.None); parent.Add(node); LinkDataNodeParent(node, node.Parent); return; } catch { } } }
public static Chunk Load(int x, int z, World w, bool thread = true, bool threadLoad = true, bool generate = true, bool dummy = true) { string file = CreatePath(w, x, z); if (File.Exists(file)) { if (threadLoad) { World.chunker.QueueChunkLoad(x, z, false, w); return null; } try { Chunk ch = new Chunk(x, z); using (MemoryStream ms = new MemoryStream()) { using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { byte[] comp; ms.SetLength(fs.Length); fs.Read(ms.GetBuffer(), 0, (int)fs.Length); comp = ms.GetBuffer().Decompress(CompressionType.GZip); ms.Write(comp, 0, comp.Length); } ms.Position = 0; NbtTree nbt = new NbtTree(ms); ch.generated = (nbt.Root["Generated"].ToTagByte().Data > 0); ch.populated = (nbt.Root["Populated"].ToTagByte().Data > 0); Array.Copy(nbt.Root["Blocks"].ToTagByteArray(), ch.blocks, ch.blocks.Length); Array.Copy(nbt.Root["Meta"].ToTagByteArray(), ch.meta, ch.meta.Length); Array.Copy(nbt.Root["BlockLight"].ToTagByteArray(), ch.Light, ch.Light.Length); Array.Copy(nbt.Root["SkyLight"].ToTagByteArray(), ch.SkyL, ch.SkyL.Length); Array.Copy(nbt.Root["HeightMap"].ToTagByteArray(), ch.heightMap, ch.heightMap.Length); Array.Copy(nbt.Root["HeightMapPrec"].ToTagByteArray().Data.ToIntArray(), ch.precipitationHeightMap, ch.precipitationHeightMap.Length); TagNodeCompound nbtCompound; foreach (TagNode tag in nbt.Root["Extra"].ToTagList()) { nbtCompound = tag.ToTagCompound(); ch.extra.Add(nbtCompound["Pos"].ToTagInt(), (ushort)nbtCompound["Value"].ToTagShort()); } TagNodeList nbtList = nbt.Root["Physics"].ToTagList(); int count = nbtList.Count; if (count > 0) { ch.physChecks = new Physics.Check[count]; TagNodeList nbtList2; for (int i = 0; i < count; i++) { nbtCompound = nbtList[i].ToTagCompound(); nbtList2 = nbtCompound["Pos"].ToTagList(); ch.physChecks[i] = new Physics.Check(nbtList2[0].ToTagInt(), nbtList2[1].ToTagInt(), nbtList2[2].ToTagInt(), nbtCompound["Meta"].ToTagByte(), nbtCompound["Time"].ToTagShort()); } } AI ai; McObject obj; Item item; Entity e; TagNodeCompound nbtCompound2; foreach (TagNode tag in nbt.Root["Entities"].ToTagList()) { e = null; nbtCompound = tag.ToTagCompound(); switch ((EntityType)(byte)nbtCompound["Type"].ToTagByte()) { case EntityType.AI: // TODO break; case EntityType.Object: // TODO break; case EntityType.Item: nbtCompound2 = nbtCompound["Data"].ToTagCompound(); item = new Item(true) { id = nbtCompound2["ID"].ToTagShort(), count = nbtCompound2["Count"].ToTagByte(), meta = nbtCompound2["Meta"].ToTagShort() }; item.e = new Entity(w) { isItem = true, I = item }; e = item.e; break; } if (e != null) { nbtList = nbtCompound["Motion"].ToTagList(); e.velocity = new double[] { nbtList[0].ToTagDouble(), nbtList[1].ToTagDouble(), nbtList[2].ToTagDouble() }; nbtList = nbtCompound["Pos"].ToTagList(); e.pos = new Point3(nbtList[0].ToTagDouble(), nbtList[1].ToTagDouble(), nbtList[2].ToTagDouble()); nbtList = nbtCompound["Rotation"].ToTagList(); e.rot = new float[] { nbtList[0].ToTagFloat(), nbtList[1].ToTagFloat() }; e.age = nbtCompound["Age"].ToTagInt(); e.OnGround = (nbtCompound["OnGround"].ToTagByte() > 0); e.health = nbtCompound["Health"].ToTagShort(); ch.entityLoad.Add(e); } } Container c; Point3 point3; foreach (TagNode tag in nbt.Root["Containers"].ToTagList()) { nbtCompound = tag.ToTagCompound(); nbtList = nbtCompound["Pos"].ToTagList(); point3 = new Point3(nbtList[0].ToTagInt(), nbtList[1].ToTagInt(), nbtList[2].ToTagInt()); c = Container.CreateInstance((ContainerType)(byte)nbtCompound["Type"].ToTagByte(), w, point3); c.LoadNBTData(nbtCompound["Items"].ToTagList()); if (!w.containers.ContainsKey(point3)) w.containers.Add(point3, c); } } //Console.WriteLine("LOADED " + x + " " + z); return ch; } catch (Exception ex) { Logger.LogToFile("Error loading chunk at " + x + "," + z + "! A new chunk will be generated in it's place."); Logger.LogErrorToFile(ex); } } //Console.WriteLine("GENERATED " + x + " " + z); if (generate) { if (thread) World.chunker.QueueChunk(x, z, w); else return w.GenerateChunk(x, z); return null; } if (dummy) return new Chunk(x, z); return null; }
public void ReadEnchantmentNBTData(byte[] data) { using (MemoryStream ms = new MemoryStream(data.Decompress(CompressionType.GZip))) { try { NbtTree nbt = new NbtTree(ms); TagNodeList list = nbt.Root["ench"].ToTagList(); TagNodeCompound compound; foreach (TagNode tag in list) { compound = tag.ToTagCompound(); enchantments.Add(new Enchantment(compound["id"].ToTagShort().Data, compound["lvl"].ToTagShort().Data)); } } catch (InvalidCastException) { Server.ServerLogger.Log("NBT data is invalid."); } } }
protected override void ReleaseCore() { _tree = null; Nodes.Clear(); }
/// <summary> /// Saves an <see cref="NbtTree"/> for a chunk back to the region's data store at the given local coordinates and with the given timestamp. /// </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> /// <param name="timestamp">The timestamp to write to the underlying region file for this chunk.</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, int timestamp) { return SaveChunkTree(lcx, lcz, tree, timestamp); }
/// <summary> /// Gets the <see cref="NbtTree"/> for a chunk given local coordinates into the region. /// </summary> /// <param name="lcx">The local X-coordinate of a chunk within the region.</param> /// <param name="lcz">The local Z-coordinate of a chunk within the region.</param> /// <returns>An <see cref="NbtTree"/> for a local chunk, or null if there is no chunk at the given coordinates.</returns> public NbtTree GetChunkTree(int lcx, int lcz) { if (!LocalBoundsCheck(lcx, lcz)) { Region alt = GetForeignRegion(lcx, lcz); return (alt == null) ? null : alt.GetChunkTree(ForeignX(lcx), ForeignZ(lcz)); } RegionFile rf = GetRegionFile(); Stream nbtstr = rf.GetChunkDataInputStream(lcx, lcz); if (nbtstr == null) { return null; } NbtTree tree = new NbtTree(nbtstr); nbtstr.Close(); return tree; }
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); } }
protected override IChunk CreateChunkVerifiedCore(NbtTree tree) { return AlphaChunk.CreateVerified(tree); }
static void LoadNbtStream(TreeNode node, int descriptionIndex, Stream stream) { NbtTree tree = new NbtTree(); tree.ReadFrom(stream); if (node.Tag != null && node.Tag is NbtDataNode) { (node.Tag as NbtDataNode).Tree = tree; } PopulateNodeFromTag(node, descriptionIndex, tree.Root); }
protected abstract IChunk CreateChunkVerifiedCore(NbtTree tree);
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); } }
// 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) { return SaveChunkTree(lcx, lcz, tree, null); }
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); } }
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; }
protected override void ExpandCore() { if (_tree == null) { NBTFile file = new NBTFile(_path); _tree = new NbtTree(); _tree.ReadFrom(file.GetDataInputStream(_compressionType)); if (_tree.Root != null) { _container = new CompoundTagContainer(_tree.Root); } } var list = new SortedList<TagKey, TagNode>(); foreach (var item in _tree.Root) { list.Add(new TagKey(item.Key, item.Value.GetTagType()), item.Value); } foreach (TagNode tag in list.Values) { TagDataNode node = TagDataNode.CreateFromTag(tag); if (node != null) Nodes.Add(node); } }
/// <summary> /// Imports a schematic file at the given path and returns in as a <see cref="Schematic"/> object. /// </summary> /// <param name="path">The path to the schematic file.</param> /// <returns>A <see cref="Schematic"/> object containing the decoded schematic file data.</returns> public static Schematic Import(string path) { NBTFile schematicFile = new NBTFile(path); if (!schematicFile.Exists()) { return null; } Stream nbtStream = schematicFile.GetDataInputStream(); if (nbtStream == null) { return null; } NbtTree tree = new NbtTree(nbtStream); NbtVerifier v = new NbtVerifier(tree.Root, _schema); if (!v.Verify()) { return null; } //TagNodeCompound schematic = tree.Root["Schematic"] as TagNodeCompound; TagNodeCompound schematic = tree.Root; int xdim = schematic["Width"].ToTagShort(); int zdim = schematic["Length"].ToTagShort(); int ydim = schematic["Height"].ToTagShort(); Schematic self = new Schematic(xdim, ydim, zdim); // Damnit, schematic is YZX ordering. YZXByteArray schemaBlocks = new YZXByteArray(xdim, ydim, zdim, schematic["Blocks"].ToTagByteArray()); YZXByteArray schemaData = new YZXByteArray(xdim, ydim, zdim, schematic["Data"].ToTagByteArray()); for (int x = 0; x < xdim; x++) { for (int y = 0; y < ydim; y++) { for (int z = 0; z < zdim; z++) { self._blocks[x, y, z] = schemaBlocks[x, y, z]; self._data[x, y, z] = schemaData[x, y, z]; } } } TagNodeList entities = schematic["Entities"] as TagNodeList; foreach (TagNode e in entities) { self._entities.Add(e); } TagNodeList tileEntities = schematic["TileEntities"] as TagNodeList; foreach (TagNode te in tileEntities) { self._tileEntities.Add(te); } self._blockset.Refresh(); return self; }
//private TagNodeCompound _metaRoot; protected override void ExpandCore() { if (_tree == null) { NBTFile file = new NBTFile(_path); _tree = new NbtTree(); _tree.ReadFrom(file.GetDataInputStream(_compressionType)); //_metaRoot = new TagNodeCompound(); if (_tree.Root != null) { //_metaRoot.Add(_tree.Name, _tree.Root); _container = new CompoundTagContainer(_tree.Root); } } /*foreach (TagNode tag in _metaRoot.Values) { TagDataNode node = TagDataNode.CreateFromTag(tag); if (node != null) Nodes.Add(node); }*/ foreach (TagNode tag in _tree.Root.Values) { TagDataNode node = TagDataNode.CreateFromTag(tag); if (node != null) Nodes.Add(node); } }
/// <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(); }
private bool LoadLevel () { NBTFile nf = new NBTFile(IO.Path.Combine(Path, _levelFile)); NbtTree tree; using (Stream nbtstr = nf.GetDataInputStream()) { if (nbtstr == null) { return false; } tree = new NbtTree(nbtstr); } _level = new Level(this); _level = _level.LoadTreeSafe(tree.Root); return _level != null; }