From 2ecac106aca126bc4bd2495a168e6ffeef35be7f Mon Sep 17 00:00:00 2001 From: Justin Aquadro Date: Sat, 8 Oct 2011 00:03:54 -0400 Subject: [PATCH] Dropping NBToolkit from Repo (it will move to its own) --- NBToolkit/BlockFilter.cs | 188 ----- NBToolkit/ChunkFilter.cs | 188 ----- NBToolkit/Dump.cs | 151 ---- NBToolkit/FilteredChunkManager.cs | 245 ------ NBToolkit/GenOres.cs | 193 ----- NBToolkit/License.txt | 19 - NBToolkit/MathHelper.cs | 33 - NBToolkit/NBToolkit.csproj | 128 --- NBToolkit/NDesk/Options.cs | 1105 -------------------------- NBToolkit/Oregen.cs | 299 ------- NBToolkit/Program.cs | 151 ---- NBToolkit/Properties/AssemblyInfo.cs | 36 - NBToolkit/Purge.cs | 86 -- NBToolkit/Relight.cs | 154 ---- NBToolkit/Replace.cs | 377 --------- NBToolkit/TKFilter.cs | 33 - NBToolkit/TKOptions.cs | 89 --- NBToolkit/app.config | 3 - 18 files changed, 3478 deletions(-) delete mode 100644 NBToolkit/BlockFilter.cs delete mode 100644 NBToolkit/ChunkFilter.cs delete mode 100644 NBToolkit/Dump.cs delete mode 100644 NBToolkit/FilteredChunkManager.cs delete mode 100644 NBToolkit/GenOres.cs delete mode 100644 NBToolkit/License.txt delete mode 100644 NBToolkit/MathHelper.cs delete mode 100644 NBToolkit/NBToolkit.csproj delete mode 100644 NBToolkit/NDesk/Options.cs delete mode 100644 NBToolkit/Oregen.cs delete mode 100644 NBToolkit/Program.cs delete mode 100644 NBToolkit/Properties/AssemblyInfo.cs delete mode 100644 NBToolkit/Purge.cs delete mode 100644 NBToolkit/Relight.cs delete mode 100644 NBToolkit/Replace.cs delete mode 100644 NBToolkit/TKFilter.cs delete mode 100644 NBToolkit/TKOptions.cs delete mode 100644 NBToolkit/app.config diff --git a/NBToolkit/BlockFilter.cs b/NBToolkit/BlockFilter.cs deleted file mode 100644 index 808e567..0000000 --- a/NBToolkit/BlockFilter.cs +++ /dev/null @@ -1,188 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using NDesk.Options; - -namespace NBToolkit -{ - public interface IBlockFilterable - { - IBlockFilter GetBlockFilter (); - } - - public interface IBlockFilter - { - int? XAboveEq { get; } - int? XBelowEq { get; } - int? YAboveEq { get; } - int? YBelowEq { get; } - int? ZAboveEq { get; } - int? ZBelowEq { get; } - - bool InvertXYZ { get; } - - IEnumerable IncludedBlocks { get; } // MatchAny - IEnumerable ExcludedBlocks { get; } // MatchAny - - int IncludedBlockCount { get; } - int ExcludedBlockCount { get; } - - double? ProbMatch { get; } - - bool IncludedBlocksContains (int id); - bool ExcludedBlocksContains (int id); - } - - public class BlockFilter : IOptions, IBlockFilter - { - protected int? _xAboveEq = null; - protected int? _xBelowEq = null; - protected int? _yAboveEq = null; - protected int? _yBelowEq = null; - protected int? _zAboveEq = null; - protected int? _zBelowEq = null; - - protected bool _invertXYZ = false; - - protected List _includedBlocks = new List(); - protected List _excludedBlocks = new List(); - - protected double? _prob = null; - - protected OptionSet _options; - - public int? XAboveEq - { - get { return _xAboveEq; } - set { _xAboveEq = value; } - } - - public int? XBelowEq - { - get { return _xBelowEq; } - set { _xBelowEq = value; } - } - - public int? YAboveEq - { - get { return _yAboveEq; } - } - - public int? YBelowEq - { - get { return _yBelowEq; } - } - - public int? ZAboveEq - { - get { return _zAboveEq; } - } - - public int? ZBelowEq - { - get { return _zBelowEq; } - } - - public bool InvertXYZ - { - get { return _invertXYZ; } - } - - public IEnumerable IncludedBlocks - { - get { return _includedBlocks; } - } - - public IEnumerable ExcludedBlocks - { - get { return _excludedBlocks; } - } - - public int IncludedBlockCount - { - get { return _includedBlocks.Count; } - } - - public int ExcludedBlockCount - { - get { return _excludedBlocks.Count; } - } - - public double? ProbMatch - { - get { return _prob; } - } - - public BlockFilter () - { - _options = new OptionSet() { - { "bxr|BlockXRange=", "Include blocks with X-coord between {0:V1} and {1:V2}, inclusive. V1 or V2 may be left blank.", - (v1, v2) => { - try { _xAboveEq = Convert.ToInt32(v1); } catch (FormatException) { } - try { _xBelowEq = Convert.ToInt32(v2); } catch (FormatException) { } - } }, - { "byr|BlockYRange=", "Include blocks with Y-coord between {0:V1} and {1:V2}, inclusive. V1 or V2 may be left blank.", - (v1, v2) => { - try { _yAboveEq = Convert.ToInt32(v1); } catch (FormatException) { } - try { _yBelowEq = Convert.ToInt32(v2); } catch (FormatException) { } - } }, - { "bzr|BlockZRange=", "Include blocks with Z-chunk coord between {0:V1} and {1:V2}, inclusive. V1 or V2 may be left blank.", - (v1, v2) => { - try { _zAboveEq = Convert.ToInt32(v1); } catch (FormatException) { } - try { _zBelowEq = Convert.ToInt32(v2); } catch (FormatException) { } - } }, - { "brv|BlockInvertXYZ", "Inverts the block selection created by --cxr, --cyr and --czr when all three options are used.", - v => _invertXYZ = true }, - { "bi|BlockInclude=", "Match blocks of type {ID}. This option is repeatable.", - v => _includedBlocks.Add(Convert.ToInt32(v) % 256) }, - { "bir|BlockIncludeRange=", "Match blocks of type between {0:V1} and {1:V2}, inclusive. This option is repeatable.", - (v1, v2) => { - int i1 = Math.Max(0, Math.Min(255, Convert.ToInt32(v1))); - int i2 = Math.Max(0, Math.Min(255, Convert.ToInt32(v2))); - for (int i = i1; i <= i2; i++) { - _includedBlocks.Add(i); - } - } }, - { "bx|BlockExclude=", "Match all blocks except blocks of type {ID}. This option is repeatable.", - v => _excludedBlocks.Add(Convert.ToInt32(v) % 256) }, - { "ber|BlockExcludeRange=", "Match all blocks except blocks of type between {0:V1} and {1:V2}, inclusive. This option is repeatable.", - (v1, v2) => { - int i1 = Math.Max(0, Math.Min(255, Convert.ToInt32(v1))); - int i2 = Math.Max(0, Math.Min(255, Convert.ToInt32(v2))); - for (int i = i1; i <= i2; i++) { - _excludedBlocks.Add(i); - } - } }, - { "bp|BlockProbability=", "Selects a matching block with probability {VAL} (0.0-1.0)", - v => _prob = Convert.ToDouble(v) }, - }; - } - - public BlockFilter (string[] args) - : this() - { - Parse(args); - } - - public void Parse (string[] args) - { - _options.Parse(args); - } - - public void PrintUsage () - { - Console.WriteLine("Block Filtering Options:"); - _options.WriteOptionDescriptions(Console.Out); - } - - public bool IncludedBlocksContains (int id) - { - return _includedBlocks.Contains(id); - } - - public bool ExcludedBlocksContains (int id) - { - return _excludedBlocks.Contains(id); - } - } -} diff --git a/NBToolkit/ChunkFilter.cs b/NBToolkit/ChunkFilter.cs deleted file mode 100644 index 4d0bd7d..0000000 --- a/NBToolkit/ChunkFilter.cs +++ /dev/null @@ -1,188 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using NDesk.Options; - -namespace NBToolkit -{ - public interface IChunkFilterable - { - IChunkFilter GetChunkFilter (); - } - - public interface IChunkFilter - { - int? XAboveEq { get; } - int? XBelowEq { get; } - int? ZAboveEq { get; } - int? ZBelowEq { get; } - - bool InvertXZ { get; } - - IEnumerable IncludedBlocks { get; } - IEnumerable ExcludedBlocks { get; } - - int IncludedBlockCount { get; } - int ExcludedBlockCount { get; } - - bool IncludeMatchAny { get; } - bool IncludeMatchAll { get; } - bool ExcludeMatchAny { get; } - bool ExcludeMatchAll { get; } - - double? ProbMatch { get; } - - bool IncludedBlocksContains (int id); - bool ExcludedBlocksContains (int id); - } - - public class ChunkFilter : IOptions, IChunkFilter - { - protected int? _xAboveEq = null; - protected int? _xBelowEq = null; - protected int? _zAboveEq = null; - protected int? _zBelowEq = null; - - protected bool _invertXZ = false; - - protected List _includedBlocks = new List(); - protected List _excludedBlocks = new List(); - - protected bool _includeAny = true; - protected bool _excludeAny = true; - - protected double? _prob = null; - - protected OptionSet _options; - - public int? XAboveEq - { - get { return _xAboveEq; } - set { _xAboveEq = value; } - } - - public int? XBelowEq - { - get { return _xBelowEq; } - set { _xBelowEq = value; } - } - - public int? ZAboveEq - { - get { return _zAboveEq; } - set { _zAboveEq = value; } - } - - public int? ZBelowEq - { - get { return _zBelowEq; } - set { _zBelowEq = value; } - } - - public bool InvertXZ - { - get { return _invertXZ; } - } - - public IEnumerable IncludedBlocks - { - get { return _includedBlocks; } - } - - public IEnumerable ExcludedBlocks - { - get { return _excludedBlocks; } - } - - public int IncludedBlockCount - { - get { return _includedBlocks.Count; } - } - - public int ExcludedBlockCount - { - get { return _excludedBlocks.Count; } - } - - public bool IncludeMatchAny - { - get { return _includeAny; } - } - - public bool IncludeMatchAll - { - get { return !_includeAny; } - } - - public bool ExcludeMatchAny - { - get { return _excludeAny; } - } - - public bool ExcludeMatchAll - { - get { return !_excludeAny; } - } - - public double? ProbMatch - { - get { return _prob; } - } - - public ChunkFilter () - { - _options = new OptionSet () { - { "cxr|ChunkXRange=", "Include chunks with X-chunk coord between {0:V1} and {1:V2}, inclusive. V1 or V2 may be left blank.", - (v1, v2) => { - try { _xAboveEq = Convert.ToInt32(v1); } catch (FormatException) { } - try { _xBelowEq = Convert.ToInt32(v2); } catch (FormatException) { } - } }, - { "czr|ChunkZRange=", "Include chunks with Z-chunk coord between {0:V1} and {1:V2}, inclusive. V1 or V2 may be left blank.", - (v1, v2) => { - try { _zAboveEq = Convert.ToInt32(v1); } catch (FormatException) { } - try { _zBelowEq = Convert.ToInt32(v2); } catch (FormatException) { } - } }, - { "crv|ChunkInvertXZ", "Inverts the chunk selection created by --cxr and --czr when both options are used.", - v => _invertXZ = true }, - { "ci|ChunkInclude=", "Include chunks that contain blocks of type {ID}. This option is repeatable.", - v => _includedBlocks.Add(Convert.ToInt32(v) % 256) }, - { "cx|ChunkExclude=", "Exclude chunks that contain blocks of type {ID}. This option is repeatable.", - v => _excludedBlocks.Add(Convert.ToInt32(v) % 256) }, - { "cia|ChunkIncludeAll", "If multiple --ci options, chunk must match all of them to be included.", - v => _includeAny = false }, - { "ciy|ChunkIncludeAny", "If multiple --ci options, chunk can match any of them to be included. (default)", - v => _includeAny = true }, - { "cxa|ChunkExcludeAll", "If multiple --cx options, chunk must match all of them to be excluded.", - v => _includeAny = false }, - { "cxy|ChunkExcludeAny", "If multiple --cx options, chunk can match any of them to be excluded. (default)", - v => _includeAny = true }, - { "cp|ChunkProbability=", "Selects a matching chunk with probability {VAL} (0.0-1.0)", - v => _prob = Convert.ToDouble(v) }, - }; - } - - public ChunkFilter (string[] args) : this() - { - Parse(args); - } - - public void Parse (string[] args) { - _options.Parse(args); - } - - public void PrintUsage () { - Console.WriteLine("Chunk Filtering Options:"); - _options.WriteOptionDescriptions(Console.Out); - } - - public bool IncludedBlocksContains (int id) - { - return _includedBlocks.Contains(id); - } - - public bool ExcludedBlocksContains (int id) - { - return _excludedBlocks.Contains(id); - } - } -} diff --git a/NBToolkit/Dump.cs b/NBToolkit/Dump.cs deleted file mode 100644 index 1d7f8a1..0000000 --- a/NBToolkit/Dump.cs +++ /dev/null @@ -1,151 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.IO; -using NDesk.Options; -using Substrate; -using Substrate.Nbt; -using Substrate.Core; - -namespace NBToolkit -{ - public class DumpOptions : TKOptions, IChunkFilterable - { - private OptionSet _filterOpt = null; - private ChunkFilter _chunkFilter = null; - - public string _outFile = ""; - - public bool _dumpBlocks = false; - public bool _dumpEntities = false; - public bool _dumpTileEntities = false; - - public DumpOptions () - : base() - { - _filterOpt = new OptionSet() - { - { "out|OutFile=", "Path of file to write JSON data into", - var => _outFile = var }, - { "b|BlockData", "Dump block data (type, data, light arrays)", - var => _dumpBlocks = true }, - { "e|Entities", "Dump complete entity data", - var => _dumpEntities = true }, - { "t|TileEntities", "Dump complete tile entity data", - var => _dumpTileEntities = true }, - }; - - _chunkFilter = new ChunkFilter(); - } - - public DumpOptions (string[] args) - : this() - { - Parse(args); - } - - public override void Parse (string[] args) - { - base.Parse(args); - - _filterOpt.Parse(args); - _chunkFilter.Parse(args); - } - - public override void PrintUsage () - { - Console.WriteLine("Usage: nbtoolkit dump [options]"); - Console.WriteLine(); - Console.WriteLine("Options for command 'dump':"); - - _filterOpt.WriteOptionDescriptions(Console.Out); - - Console.WriteLine(); - _chunkFilter.PrintUsage(); - - Console.WriteLine(); - base.PrintUsage(); - } - - public override void SetDefaults () - { - base.SetDefaults(); - - if (_outFile.Length == 0) { - Console.WriteLine("Error: You must specify an output file"); - Console.WriteLine(); - this.PrintUsage(); - - throw new TKOptionException(); - } - } - - public IChunkFilter GetChunkFilter () - { - return _chunkFilter; - } - } - - class Dump : TKFilter - { - private DumpOptions opt; - - public Dump (DumpOptions o) - { - opt = o; - } - - public override void Run () - { - NbtWorld world = GetWorld(opt); - IChunkManager cm = world.GetChunkManager(opt.OPT_DIM); - FilteredChunkManager fcm = new FilteredChunkManager(cm, opt.GetChunkFilter()); - - StreamWriter fstr; - try { - fstr = new StreamWriter(opt._outFile, false); - } - catch (IOException e) { - Console.WriteLine(e.Message); - return; - } - - fstr.WriteLine("["); - - bool first = true; - foreach (ChunkRef chunk in fcm) { - if (!first) { - fstr.Write(","); - } - - Chunk c = chunk.GetChunkRef(); - - if (!opt._dumpBlocks) { - c.Tree.Root["Level"].ToTagCompound().Remove("Blocks"); - c.Tree.Root["Level"].ToTagCompound().Remove("Data"); - c.Tree.Root["Level"].ToTagCompound().Remove("BlockLight"); - c.Tree.Root["Level"].ToTagCompound().Remove("SkyLight"); - c.Tree.Root["Level"].ToTagCompound().Remove("HeightMap"); - } - - if (!opt._dumpEntities) { - c.Tree.Root["Level"].ToTagCompound().Remove("Entities"); - } - - if (!opt._dumpTileEntities) { - c.Tree.Root["Level"].ToTagCompound().Remove("TileEntities"); - } - - string s = JSONSerializer.Serialize(c.Tree.Root["Level"], 1); - fstr.Write(s); - - first = false; - } - - fstr.WriteLine(); - fstr.WriteLine("]"); - - fstr.Close(); - } - } -} diff --git a/NBToolkit/FilteredChunkManager.cs b/NBToolkit/FilteredChunkManager.cs deleted file mode 100644 index 99ba058..0000000 --- a/NBToolkit/FilteredChunkManager.cs +++ /dev/null @@ -1,245 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Text; -using Substrate; -using Substrate.Core; - -namespace NBToolkit -{ - class FilteredChunkManager : IChunkManager, IEnumerable - { - private IChunkManager _cm; - private IChunkFilter _filter; - - public FilteredChunkManager (IChunkManager cm, IChunkFilter filter) - { - _cm = cm; - _filter = filter; - } - - - #region IEnumerable Members - - public IEnumerator GetEnumerator () - { - return new ChunkEnumerator(_cm, _filter); - } - - #endregion - - - #region IEnumerable Members - - IEnumerator IEnumerable.GetEnumerator () - { - return new ChunkEnumerator(_cm, _filter); - } - - #endregion - - - public class ChunkEnumerator : IEnumerator - { - private IChunkManager _cm; - private IChunkFilter _filter; - - private IEnumerator _enum; - - private static Random _rand = new Random(); - - public ChunkEnumerator (IChunkManager cm, IChunkFilter filter) - { - _cm = cm; - _filter = filter; - _enum = _cm.GetEnumerator(); - } - - - #region IEnumerator Members - - public ChunkRef Current - { - get { return _enum.Current; } - } - - #endregion - - - #region IDisposable Members - - public void Dispose () - { - } - - #endregion - - - #region IEnumerator Members - - object IEnumerator.Current - { - get { return _enum.Current; } - } - - public bool MoveNext () - { - while (true) { - if (_enum.MoveNext() == false) { - return false; - } - - // Filter by coordinates - if (_filter.InvertXZ) { - if (_filter.XAboveEq != null && _filter.XBelowEq != null && - _filter.ZAboveEq != null && _filter.ZBelowEq != null && - Current.X >= _filter.XAboveEq && Current.X <= _filter.XBelowEq && - Current.Z >= _filter.ZAboveEq && Current.Z <= _filter.ZBelowEq) { - continue; - } - } - else { - if (_filter.XAboveEq != null && Current.X < _filter.XAboveEq) { - continue; - } - if (_filter.XBelowEq != null && Current.X > _filter.XBelowEq) { - continue; - } - if (_filter.ZAboveEq != null && Current.Z < _filter.ZAboveEq) { - continue; - } - if (_filter.ZBelowEq != null && Current.Z > _filter.ZBelowEq) { - continue; - } - } - - // Filter out chunks that do not contain required blocks (included list) - if (_filter.IncludedBlockCount > 0) { - int matchCount = 0; - foreach (int block in _filter.IncludedBlocks) { - if (Current.Blocks.CountByID(block) > 0) { - matchCount++; - } - } - - if (_filter.IncludeMatchAny && matchCount == 0) { - continue; - } - if (_filter.IncludeMatchAll && matchCount != _filter.IncludedBlockCount) { - continue; - } - } - - // Filter out chunks that contain forbiddon blocks (excluded list) - if (_filter.ExcludedBlockCount > 0) { - int matchCount = 0; - foreach (int block in _filter.ExcludedBlocks) { - if (Current.Blocks.CountByID(block) > 0) { - matchCount++; - } - } - - if (_filter.ExcludeMatchAny && matchCount > 0) { - continue; - } - if (_filter.ExcludeMatchAll && matchCount == _filter.ExcludedBlockCount) { - continue; - } - } - - // Filter out randomly matching chunks (according to probability value) - if (_filter.ProbMatch != null) { - double r = _rand.NextDouble(); - if (r > _filter.ProbMatch) { - continue; - } - } - - return true; - } - } - - public void Reset () - { - _enum.Reset(); - } - - #endregion - } - - - #region IChunkContainer Members - - public int ChunkGlobalX (int cx) - { - return _cm.ChunkGlobalX(cx); - } - - public int ChunkGlobalZ (int cz) - { - return _cm.ChunkGlobalZ(cz); - } - - public int ChunkLocalX (int cx) - { - return _cm.ChunkLocalX(cx); - } - - public int ChunkLocalZ (int cz) - { - return _cm.ChunkLocalZ(cz); - } - - public Chunk GetChunk (int cx, int cz) - { - return _cm.GetChunk(cx, cz); - } - - public ChunkRef GetChunkRef (int cx, int cz) - { - return _cm.GetChunkRef(cx, cz); - } - - public ChunkRef CreateChunk (int cx, int cz) - { - return _cm.CreateChunk(cx, cz); - } - - public bool ChunkExists (int cx, int cz) - { - return _cm.ChunkExists(cx, cz); - } - - public bool DeleteChunk (int cx, int cz) - { - return _cm.DeleteChunk(cx, cz); - } - - public int Save () - { - return _cm.Save(); - } - - public bool SaveChunk (Chunk chunk) - { - return _cm.SaveChunk(chunk); - } - - public ChunkRef SetChunk (int cx, int cz, Chunk chunk) - { - return _cm.SetChunk(cx, cz, chunk); - } - - #endregion - - #region IChunkContainer Members - - - public bool CanDelegateCoordinates - { - get { return false; } - } - - #endregion - } -} diff --git a/NBToolkit/GenOres.cs b/NBToolkit/GenOres.cs deleted file mode 100644 index 51727d7..0000000 --- a/NBToolkit/GenOres.cs +++ /dev/null @@ -1,193 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using Substrate; -using Substrate.Core; - -namespace NBToolkit -{ - public interface IGenerator - { - bool Generate (IBlockManager blockMan, Random rand, int x, int y, int z); - } - - /** - * This class is derived from Mojang sources, the algorithm in particular - * is subject to Mojang copyright and restrictions. Mathfix patch by - * jaquadro. - */ - - public class NativeGenOre : IGenerator - { - private int _blockId = 0; - private int _blockData = 0; - private int _size = 0; - - private bool _mathFix = false; - - public NativeGenOre (int blockId, int size) - { - _blockId = blockId; - _size = size; - } - - public NativeGenOre (int blockId, int blockData, int size) - { - _blockId = blockId; - _blockData = blockData; - _size = size; - } - - public bool MathFix - { - get - { - return _mathFix; - } - set - { - _mathFix = value; - } - } - - public bool Generate (IBlockManager blockMan, Random rand, int x, int y, int z) - { - float rpi = (float)(rand.NextDouble() * Math.PI); - - double x1 = x + 8 + MathHelper.Sin(rpi) * _size / 8.0F; - double x2 = x + 8 - MathHelper.Sin(rpi) * _size / 8.0F; - double z1 = z + 8 + MathHelper.Cos(rpi) * _size / 8.0F; - double z2 = z + 8 - MathHelper.Cos(rpi) * _size / 8.0F; - - double y1 = y + rand.Next(3) + 2; - double y2 = y + rand.Next(3) + 2; - - for (int i = 0; i <= _size; i++) { - double xPos = x1 + (x2 - x1) * i / _size; - double yPos = y1 + (y2 - y1) * i / _size; - double zPos = z1 + (z2 - z1) * i / _size; - - double fuzz = rand.NextDouble() * _size / 16.0D; - double fuzzXZ = (MathHelper.Sin((float)(i * Math.PI / _size)) + 1.0F) * fuzz + 1.0D; - double fuzzY = (MathHelper.Sin((float)(i * Math.PI / _size)) + 1.0F) * fuzz + 1.0D; - - int xStart, yStart, zStart, xEnd, yEnd, zEnd; - - if (_mathFix) { - xStart = (int)Math.Floor(xPos - fuzzXZ / 2.0D); - yStart = (int)Math.Floor(yPos - fuzzY / 2.0D); - zStart = (int)Math.Floor(zPos - fuzzXZ / 2.0D); - - xEnd = (int)Math.Floor(xPos + fuzzXZ / 2.0D); - yEnd = (int)Math.Floor(yPos + fuzzY / 2.0D); - zEnd = (int)Math.Floor(zPos + fuzzXZ / 2.0D); - } - else { - xStart = (int)(xPos - fuzzXZ / 2.0D); - yStart = (int)(yPos - fuzzY / 2.0D); - zStart = (int)(zPos - fuzzXZ / 2.0D); - - xEnd = (int)(xPos + fuzzXZ / 2.0D); - yEnd = (int)(yPos + fuzzY / 2.0D); - zEnd = (int)(zPos + fuzzXZ / 2.0D); - } - - for (int ix = xStart; ix <= xEnd; ix++) { - double xThresh = (ix + 0.5D - xPos) / (fuzzXZ / 2.0D); - if (xThresh * xThresh < 1.0D) { - for (int iy = yStart; iy <= yEnd; iy++) { - double yThresh = (iy + 0.5D - yPos) / (fuzzY / 2.0D); - if (xThresh * xThresh + yThresh * yThresh < 1.0D) { - for (int iz = zStart; iz <= zEnd; iz++) { - double zThresh = (iz + 0.5D - zPos) / (fuzzXZ / 2.0D); - if (xThresh * xThresh + yThresh * yThresh + zThresh * zThresh < 1.0D) { - AlphaBlockRef block = blockMan.GetBlockRef(ix, iy, iz); - if (block.IsValid) { - block.ID = _blockId; - block.Data = _blockData; - } - } - } - } - } - } - } - } - - return true; - } - } - - /*public class LegacyGenOre { - - public bool Generate (BlockManager blockMan, Random rand, int x, int y, int z) - { - double x_scale = 0.25 + (rand.NextDouble() * 0.75); - double y_scale = 0.25 + (rand.NextDouble() * 0.75); - double z_scale = 0.25 + (rand.NextDouble() * 0.75); - - if (opt.OPT_VV) { - Console.WriteLine("Selected scale: {0}, {1}, {2}", x_scale, y_scale, z_scale); - } - - double x_len = (double)opt.OPT_SIZE / 8.0 * x_scale; - double z_len = (double)opt.OPT_SIZE / 8.0 * z_scale; - double y_len = ((double)opt.OPT_SIZE / 16.0 + 2.0) * y_scale; - - if (opt.OPT_VV) { - Console.WriteLine("Selected length: {0}, {1}, {2}", x_len, y_len, z_len); - } - - double xpos = x; - double ypos = y; - double zpos = z; - - if (opt.OPT_VV) { - Console.WriteLine("Selected initial position: {0}, {1}, {2}", xpos, ypos, zpos); - } - - int sample_size = 2 * (int)opt.OPT_SIZE; - double fuzz = 0.25; - - double x_step = x_len / sample_size; - double y_step = y_len / sample_size; - double z_step = z_len / sample_size; - - for (int i = 0; i < sample_size; i++) { - int tx = (int)Math.Floor(xpos + i * x_step); - int ty = (int)Math.Floor(ypos + i * y_step); - int tz = (int)Math.Floor(zpos + i * z_step); - int txp = (int)Math.Floor(xpos + i * x_step + fuzz); - int typ = (int)Math.Floor(ypos + i * y_step + fuzz); - int tzp = (int)Math.Floor(zpos + i * z_step + fuzz); - - if (tx < 0) tx = 0; - if (ty < 0) ty = 0; - if (tz < 0) tz = 0; - - if (tx >= 16) tx = 15; - if (ty >= 128) ty = 127; - if (tz >= 16) tz = 15; - - if (txp < 0) txp = 0; - if (typ < 0) typ = 0; - if (tzp < 0) tzp = 0; - - if (txp >= 16) txp = 15; - if (typ >= 128) typ = 127; - if (tzp >= 16) tzp = 15; - - - UpdateBlock(world, chunk, tx, ty, tz); - UpdateBlock(world, chunk, txp, ty, tz); - UpdateBlock(world, chunk, tx, typ, tz); - UpdateBlock(world, chunk, tx, ty, tzp); - UpdateBlock(world, chunk, txp, typ, tz); - UpdateBlock(world, chunk, tx, typ, tzp); - UpdateBlock(world, chunk, txp, ty, tzp); - UpdateBlock(world, chunk, txp, typ, tzp); - } - } - - }*/ -} diff --git a/NBToolkit/License.txt b/NBToolkit/License.txt deleted file mode 100644 index b6a61eb..0000000 --- a/NBToolkit/License.txt +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (C) 2011 by Justin Aquadro - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. \ No newline at end of file diff --git a/NBToolkit/MathHelper.cs b/NBToolkit/MathHelper.cs deleted file mode 100644 index 9d64462..0000000 --- a/NBToolkit/MathHelper.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -/** - * The following is adapted directly from Mojang sources and is - * subject to Mojang copyright and restrictions. - */ - -namespace NBToolkit -{ - public class MathHelper - { - private static float[] trigTable = new float[65536]; - - static MathHelper () - { - for (int i = 0; i < 65536; i++) { - trigTable[i] = (float)Math.Sin(i * Math.PI * 2.0D / 65536.0D); - } - } - - public static float Sin (float angle) - { - return trigTable[((int)(angle * 10430.378F) & 0xFFFF)]; - } - - public static float Cos (float angle) - { - return trigTable[((int)(angle * 10430.378F + 16384.0F) & 0xFFFF)]; - } - } -} diff --git a/NBToolkit/NBToolkit.csproj b/NBToolkit/NBToolkit.csproj deleted file mode 100644 index 7ec9529..0000000 --- a/NBToolkit/NBToolkit.csproj +++ /dev/null @@ -1,128 +0,0 @@ - - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {68207314-C080-4823-97F1-A6623145AA00} - Exe - Properties - NBToolkit - NBToolkit - v4.0 - 512 - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - - - 3.5 - - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - False - .NET Framework Client Profile - false - - - False - .NET Framework 2.0 %28x86%29 - false - - - False - .NET Framework 3.0 %28x86%29 - false - - - False - .NET Framework 3.5 - false - - - False - .NET Framework 3.5 SP1 - true - - - False - Windows Installer 3.1 - true - - - - - {AFE30E14-3F2F-4461-9F7D-147AB4DCA4C3} - Substrate - - - - - \ No newline at end of file diff --git a/NBToolkit/NDesk/Options.cs b/NBToolkit/NDesk/Options.cs deleted file mode 100644 index c144e61..0000000 --- a/NBToolkit/NDesk/Options.cs +++ /dev/null @@ -1,1105 +0,0 @@ -// -// Options.cs -// -// Authors: -// Jonathan Pryor -// -// Copyright (C) 2008 Novell (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining -// a copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to -// permit persons to whom the Software is furnished to do so, subject to -// the following conditions: -// -// The above copyright notice and this permission notice shall be -// included in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// - -// Compile With: -// gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll -// gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll -// -// The LINQ version just changes the implementation of -// OptionSet.Parse(IEnumerable), and confers no semantic changes. - -// -// A Getopt::Long-inspired option parsing library for C#. -// -// NDesk.Options.OptionSet is built upon a key/value table, where the -// key is a option format string and the value is a delegate that is -// invoked when the format string is matched. -// -// Option format strings: -// Regex-like BNF Grammar: -// name: .+ -// type: [=:] -// sep: ( [^{}]+ | '{' .+ '}' )? -// aliases: ( name type sep ) ( '|' name type sep )* -// -// Each '|'-delimited name is an alias for the associated action. If the -// format string ends in a '=', it has a required value. If the format -// string ends in a ':', it has an optional value. If neither '=' or ':' -// is present, no value is supported. `=' or `:' need only be defined on one -// alias, but if they are provided on more than one they must be consistent. -// -// Each alias portion may also end with a "key/value separator", which is used -// to split option values if the option accepts > 1 value. If not specified, -// it defaults to '=' and ':'. If specified, it can be any character except -// '{' and '}' OR the *string* between '{' and '}'. If no separator should be -// used (i.e. the separate values should be distinct arguments), then "{}" -// should be used as the separator. -// -// Options are extracted either from the current option by looking for -// the option name followed by an '=' or ':', or is taken from the -// following option IFF: -// - The current option does not contain a '=' or a ':' -// - The current option requires a value (i.e. not a Option type of ':') -// -// The `name' used in the option format string does NOT include any leading -// option indicator, such as '-', '--', or '/'. All three of these are -// permitted/required on any named option. -// -// Option bundling is permitted so long as: -// - '-' is used to start the option group -// - all of the bundled options are a single character -// - at most one of the bundled options accepts a value, and the value -// provided starts from the next character to the end of the string. -// -// This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value' -// as '-Dname=value'. -// -// Option processing is disabled by specifying "--". All options after "--" -// are returned by OptionSet.Parse() unchanged and unprocessed. -// -// Unprocessed options are returned from OptionSet.Parse(). -// -// Examples: -// int verbose = 0; -// OptionSet p = new OptionSet () -// .Add ("v", v => ++verbose) -// .Add ("name=|value=", v => Console.WriteLine (v)); -// p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"}); -// -// The above would parse the argument string array, and would invoke the -// lambda expression three times, setting `verbose' to 3 when complete. -// It would also print out "A" and "B" to standard output. -// The returned array would contain the string "extra". -// -// C# 3.0 collection initializers are supported and encouraged: -// var p = new OptionSet () { -// { "h|?|help", v => ShowHelp () }, -// }; -// -// System.ComponentModel.TypeConverter is also supported, allowing the use of -// custom data types in the callback type; TypeConverter.ConvertFromString() -// is used to convert the value option to an instance of the specified -// type: -// -// var p = new OptionSet () { -// { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) }, -// }; -// -// Random other tidbits: -// - Boolean options (those w/o '=' or ':' in the option format string) -// are explicitly enabled if they are followed with '+', and explicitly -// disabled if they are followed with '-': -// string a = null; -// var p = new OptionSet () { -// { "a", s => a = s }, -// }; -// p.Parse (new string[]{"-a"}); // sets v != null -// p.Parse (new string[]{"-a+"}); // sets v != null -// p.Parse (new string[]{"-a-"}); // sets v == null -// - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.ComponentModel; -using System.Globalization; -using System.IO; -using System.Runtime.Serialization; -using System.Security.Permissions; -using System.Text; -using System.Text.RegularExpressions; - -#if LINQ -using System.Linq; -#endif - -#if TEST -using NDesk.Options; -#endif - -namespace NDesk.Options { - - public class OptionValueCollection : IList, IList { - List values = new List (); - OptionContext c; - - internal OptionValueCollection (OptionContext c) - { - this.c = c; - } - - #region ICollection - void ICollection.CopyTo (Array array, int index) {(values as ICollection).CopyTo (array, index);} - bool ICollection.IsSynchronized {get {return (values as ICollection).IsSynchronized;}} - object ICollection.SyncRoot {get {return (values as ICollection).SyncRoot;}} - #endregion - - #region ICollection - public void Add (string item) {values.Add (item);} - public void Clear () {values.Clear ();} - public bool Contains (string item) {return values.Contains (item);} - public void CopyTo (string[] array, int arrayIndex) {values.CopyTo (array, arrayIndex);} - public bool Remove (string item) {return values.Remove (item);} - public int Count {get {return values.Count;}} - public bool IsReadOnly {get {return false;}} - #endregion - - #region IEnumerable - IEnumerator IEnumerable.GetEnumerator () {return values.GetEnumerator ();} - #endregion - - #region IEnumerable - public IEnumerator GetEnumerator () {return values.GetEnumerator ();} - #endregion - - #region IList - int IList.Add (object value) {return (values as IList).Add (value);} - bool IList.Contains (object value) {return (values as IList).Contains (value);} - int IList.IndexOf (object value) {return (values as IList).IndexOf (value);} - void IList.Insert (int index, object value) {(values as IList).Insert (index, value);} - void IList.Remove (object value) {(values as IList).Remove (value);} - void IList.RemoveAt (int index) {(values as IList).RemoveAt (index);} - bool IList.IsFixedSize {get {return false;}} - object IList.this [int index] {get {return this [index];} set {(values as IList)[index] = value;}} - #endregion - - #region IList - public int IndexOf (string item) {return values.IndexOf (item);} - public void Insert (int index, string item) {values.Insert (index, item);} - public void RemoveAt (int index) {values.RemoveAt (index);} - - private void AssertValid (int index) - { - if (c.Option == null) - throw new InvalidOperationException ("OptionContext.Option is null."); - if (index >= c.Option.MaxValueCount) - throw new ArgumentOutOfRangeException ("index"); - if (c.Option.OptionValueType == OptionValueType.Required && - index >= values.Count) - throw new OptionException (string.Format ( - c.OptionSet.MessageLocalizer ("Missing required value for option '{0}'."), c.OptionName), - c.OptionName); - } - - public string this [int index] { - get { - AssertValid (index); - return index >= values.Count ? null : values [index]; - } - set { - values [index] = value; - } - } - #endregion - - public List ToList () - { - return new List (values); - } - - public string[] ToArray () - { - return values.ToArray (); - } - - public override string ToString () - { - return string.Join (", ", values.ToArray ()); - } - } - - public class OptionContext { - private Option option; - private string name; - private int index; - private OptionSet set; - private OptionValueCollection c; - - public OptionContext (OptionSet set) - { - this.set = set; - this.c = new OptionValueCollection (this); - } - - public Option Option { - get {return option;} - set {option = value;} - } - - public string OptionName { - get {return name;} - set {name = value;} - } - - public int OptionIndex { - get {return index;} - set {index = value;} - } - - public OptionSet OptionSet { - get {return set;} - } - - public OptionValueCollection OptionValues { - get {return c;} - } - } - - public enum OptionValueType { - None, - Optional, - Required, - } - - public abstract class Option { - string prototype, description; - string[] names; - OptionValueType type; - int count; - string[] separators; - - protected Option (string prototype, string description) - : this (prototype, description, 1) - { - } - - protected Option (string prototype, string description, int maxValueCount) - { - if (prototype == null) - throw new ArgumentNullException ("prototype"); - if (prototype.Length == 0) - throw new ArgumentException ("Cannot be the empty string.", "prototype"); - if (maxValueCount < 0) - throw new ArgumentOutOfRangeException ("maxValueCount"); - - this.prototype = prototype; - this.names = prototype.Split ('|'); - this.description = description; - this.count = maxValueCount; - this.type = ParsePrototype (); - - if (this.count == 0 && type != OptionValueType.None) - throw new ArgumentException ( - "Cannot provide maxValueCount of 0 for OptionValueType.Required or " + - "OptionValueType.Optional.", - "maxValueCount"); - if (this.type == OptionValueType.None && maxValueCount > 1) - throw new ArgumentException ( - string.Format ("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount), - "maxValueCount"); - if (Array.IndexOf (names, "<>") >= 0 && - ((names.Length == 1 && this.type != OptionValueType.None) || - (names.Length > 1 && this.MaxValueCount > 1))) - throw new ArgumentException ( - "The default option handler '<>' cannot require values.", - "prototype"); - - for (int i = 0; i < names.Length; i++) - names[i] = names[i].ToLower(); - } - - public string Prototype { get { return prototype; } } - public string Description {get {return description;}} - public OptionValueType OptionValueType {get {return type;}} - public int MaxValueCount {get {return count;}} - - public string[] GetNames () - { - return (string[]) names.Clone (); - } - - public string[] GetValueSeparators () - { - if (separators == null) - return new string [0]; - return (string[]) separators.Clone (); - } - - protected static T Parse (string value, OptionContext c) - { - TypeConverter conv = TypeDescriptor.GetConverter (typeof (T)); - T t = default (T); - try { - if (value != null) - t = (T) conv.ConvertFromString (value); - } - catch (Exception e) { - throw new OptionException ( - string.Format ( - c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."), - value, typeof (T).Name, c.OptionName), - c.OptionName, e); - } - return t; - } - - internal string[] Names {get {return names;}} - internal string[] ValueSeparators {get {return separators;}} - - static readonly char[] NameTerminator = new char[]{'=', ':'}; - - private OptionValueType ParsePrototype () - { - char type = '\0'; - List seps = new List (); - for (int i = 0; i < names.Length; ++i) { - string name = names [i]; - if (name.Length == 0) - throw new ArgumentException ("Empty option names are not supported.", "prototype"); - - int end = name.IndexOfAny (NameTerminator); - if (end == -1) - continue; - names [i] = name.Substring (0, end); - if (type == '\0' || type == name [end]) - type = name [end]; - else - throw new ArgumentException ( - string.Format ("Conflicting option types: '{0}' vs. '{1}'.", type, name [end]), - "prototype"); - AddSeparators (name, end, seps); - } - - if (type == '\0') - return OptionValueType.None; - - if (count <= 1 && seps.Count != 0) - throw new ArgumentException ( - string.Format ("Cannot provide key/value separators for Options taking {0} value(s).", count), - "prototype"); - if (count > 1) { - if (seps.Count == 0) - this.separators = new string[]{":", "="}; - else if (seps.Count == 1 && seps [0].Length == 0) - this.separators = null; - else - this.separators = seps.ToArray (); - } - - return type == '=' ? OptionValueType.Required : OptionValueType.Optional; - } - - private static void AddSeparators (string name, int end, ICollection seps) - { - int start = -1; - for (int i = end+1; i < name.Length; ++i) { - switch (name [i]) { - case '{': - if (start != -1) - throw new ArgumentException ( - string.Format ("Ill-formed name/value separator found in \"{0}\".", name), - "prototype"); - start = i+1; - break; - case '}': - if (start == -1) - throw new ArgumentException ( - string.Format ("Ill-formed name/value separator found in \"{0}\".", name), - "prototype"); - seps.Add (name.Substring (start, i-start)); - start = -1; - break; - default: - if (start == -1) - seps.Add (name [i].ToString ()); - break; - } - } - if (start != -1) - throw new ArgumentException ( - string.Format ("Ill-formed name/value separator found in \"{0}\".", name), - "prototype"); - } - - public void Invoke (OptionContext c) - { - OnParseComplete (c); - c.OptionName = null; - c.Option = null; - c.OptionValues.Clear (); - } - - protected abstract void OnParseComplete (OptionContext c); - - public override string ToString () - { - return Prototype; - } - } - - [Serializable] - public class OptionException : Exception { - private string option; - - public OptionException () - { - } - - public OptionException (string message, string optionName) - : base (message) - { - this.option = optionName; - } - - public OptionException (string message, string optionName, Exception innerException) - : base (message, innerException) - { - this.option = optionName; - } - - protected OptionException (SerializationInfo info, StreamingContext context) - : base (info, context) - { - this.option = info.GetString ("OptionName"); - } - - public string OptionName { - get {return this.option;} - } - - [SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)] - public override void GetObjectData (SerializationInfo info, StreamingContext context) - { - base.GetObjectData (info, context); - info.AddValue ("OptionName", option); - } - } - - public delegate void OptionAction (TKey key, TValue value); - - public class OptionSet : KeyedCollection - { - public OptionSet () - : this (delegate (string f) {return f;}) - { - } - - public OptionSet (Converter localizer) - { - this.localizer = localizer; - } - - Converter localizer; - - public Converter MessageLocalizer { - get {return localizer;} - } - - protected override string GetKeyForItem (Option item) - { - if (item == null) - throw new ArgumentNullException ("option"); - if (item.Names != null && item.Names.Length > 0) - return item.Names [0]; - // This should never happen, as it's invalid for Option to be - // constructed w/o any names. - throw new InvalidOperationException ("Option has no names!"); - } - - [Obsolete ("Use KeyedCollection.this[string]")] - protected Option GetOptionForName (string option) - { - if (option == null) - throw new ArgumentNullException ("option"); - try { - return base [option]; - } - catch (KeyNotFoundException) { - return null; - } - } - - protected override void InsertItem (int index, Option item) - { - base.InsertItem (index, item); - AddImpl (item); - } - - protected override void RemoveItem (int index) - { - base.RemoveItem (index); - Option p = Items [index]; - // KeyedCollection.RemoveItem() handles the 0th item - for (int i = 1; i < p.Names.Length; ++i) { - Dictionary.Remove (p.Names [i]); - } - } - - protected override void SetItem (int index, Option item) - { - base.SetItem (index, item); - RemoveItem (index); - AddImpl (item); - } - - private void AddImpl (Option option) - { - if (option == null) - throw new ArgumentNullException ("option"); - List added = new List (option.Names.Length); - try { - // KeyedCollection.InsertItem/SetItem handle the 0th name. - for (int i = 1; i < option.Names.Length; ++i) { - Dictionary.Add (option.Names [i], option); - added.Add (option.Names [i]); - } - } - catch (Exception) { - foreach (string name in added) - Dictionary.Remove (name); - throw; - } - } - - public new OptionSet Add (Option option) - { - base.Add (option); - return this; - } - - sealed class ActionOption : Option { - Action action; - - public ActionOption (string prototype, string description, int count, Action action) - : base (prototype, description, count) - { - if (action == null) - throw new ArgumentNullException ("action"); - this.action = action; - } - - protected override void OnParseComplete (OptionContext c) - { - action (c.OptionValues); - } - } - - public OptionSet Add (string prototype, Action action) - { - return Add (prototype, null, action); - } - - public OptionSet Add (string prototype, string description, Action action) - { - if (action == null) - throw new ArgumentNullException ("action"); - Option p = new ActionOption (prototype, description, 1, - delegate (OptionValueCollection v) { action (v [0]); }); - base.Add (p); - return this; - } - - public OptionSet Add (string prototype, OptionAction action) - { - return Add (prototype, null, action); - } - - public OptionSet Add (string prototype, string description, OptionAction action) - { - if (action == null) - throw new ArgumentNullException ("action"); - Option p = new ActionOption (prototype, description, 2, - delegate (OptionValueCollection v) {action (v [0], v [1]);}); - base.Add (p); - return this; - } - - sealed class ActionOption : Option { - Action action; - - public ActionOption (string prototype, string description, Action action) - : base (prototype, description, 1) - { - if (action == null) - throw new ArgumentNullException ("action"); - this.action = action; - } - - protected override void OnParseComplete (OptionContext c) - { - action (Parse (c.OptionValues [0], c)); - } - } - - sealed class ActionOption : Option { - OptionAction action; - - public ActionOption (string prototype, string description, OptionAction action) - : base (prototype, description, 2) - { - if (action == null) - throw new ArgumentNullException ("action"); - this.action = action; - } - - protected override void OnParseComplete (OptionContext c) - { - action ( - Parse (c.OptionValues [0], c), - Parse (c.OptionValues [1], c)); - } - } - - public OptionSet Add (string prototype, Action action) - { - return Add (prototype, null, action); - } - - public OptionSet Add (string prototype, string description, Action action) - { - return Add (new ActionOption (prototype, description, action)); - } - - public OptionSet Add (string prototype, OptionAction action) - { - return Add (prototype, null, action); - } - - public OptionSet Add (string prototype, string description, OptionAction action) - { - return Add (new ActionOption (prototype, description, action)); - } - - protected virtual OptionContext CreateOptionContext () - { - return new OptionContext (this); - } - -#if LINQ - public List Parse (IEnumerable arguments) - { - bool process = true; - OptionContext c = CreateOptionContext (); - c.OptionIndex = -1; - var def = GetOptionForName ("<>"); - var unprocessed = - from argument in arguments - where ++c.OptionIndex >= 0 && (process || def != null) - ? process - ? argument == "--" - ? (process = false) - : !Parse (argument, c) - ? def != null - ? Unprocessed (null, def, c, argument) - : true - : false - : def != null - ? Unprocessed (null, def, c, argument) - : true - : true - select argument; - List r = unprocessed.ToList (); - if (c.Option != null) - c.Option.Invoke (c); - return r; - } -#else - public List Parse (IEnumerable arguments) - { - OptionContext c = CreateOptionContext (); - c.OptionIndex = -1; - bool process = true; - List unprocessed = new List (); - Option def = Contains ("<>") ? this ["<>"] : null; - foreach (string argument in arguments) { - ++c.OptionIndex; - if (argument == "--") { - process = false; - continue; - } - if (!process) { - Unprocessed (unprocessed, def, c, argument); - continue; - } - if (!Parse (argument.ToLower(), c)) - Unprocessed (unprocessed, def, c, argument); - } - if (c.Option != null) - c.Option.Invoke (c); - return unprocessed; - } -#endif - - private static bool Unprocessed (ICollection extra, Option def, OptionContext c, string argument) - { - if (def == null) { - extra.Add (argument); - return false; - } - c.OptionValues.Add (argument); - c.Option = def; - c.Option.Invoke (c); - return false; - } - - private readonly Regex ValueOption = new Regex ( - @"^(?--|-|/)(?[^:=]+)((?[:=])(?.*))?$"); - - protected bool GetOptionParts (string argument, out string flag, out string name, out string sep, out string value) - { - if (argument == null) - throw new ArgumentNullException ("argument"); - - flag = name = sep = value = null; - Match m = ValueOption.Match (argument); - if (!m.Success) { - return false; - } - flag = m.Groups ["flag"].Value; - name = m.Groups ["name"].Value; - if (m.Groups ["sep"].Success && m.Groups ["value"].Success) { - sep = m.Groups ["sep"].Value; - value = m.Groups ["value"].Value; - } - return true; - } - - protected virtual bool Parse (string argument, OptionContext c) - { - if (c.Option != null) { - ParseValue (argument, c); - return true; - } - - string f, n, s, v; - if (!GetOptionParts (argument, out f, out n, out s, out v)) - return false; - - Option p; - if (Contains (n)) { - p = this [n]; - c.OptionName = f + n; - c.Option = p; - switch (p.OptionValueType) { - case OptionValueType.None: - c.OptionValues.Add (n); - c.Option.Invoke (c); - break; - case OptionValueType.Optional: - case OptionValueType.Required: - ParseValue (v, c); - break; - } - return true; - } - // no match; is it a bool option? - if (ParseBool (argument, n, c)) - return true; - // is it a bundled option? - if (ParseBundledValue (f, string.Concat (n + s + v), c)) - return true; - - return false; - } - - private void ParseValue (string option, OptionContext c) - { - if (option != null) - foreach (string o in c.Option.ValueSeparators != null - ? option.Split (c.Option.ValueSeparators, StringSplitOptions.None) - : new string[]{option}) { - c.OptionValues.Add (o); - } - if (c.OptionValues.Count == c.Option.MaxValueCount || - c.Option.OptionValueType == OptionValueType.Optional) - c.Option.Invoke (c); - else if (c.OptionValues.Count > c.Option.MaxValueCount) { - throw new OptionException (localizer (string.Format ( - "Error: Found {0} option values when expecting {1}.", - c.OptionValues.Count, c.Option.MaxValueCount)), - c.OptionName); - } - } - - private bool ParseBool (string option, string n, OptionContext c) - { - Option p; - string rn; - if (n.Length >= 1 && (n [n.Length-1] == '+' || n [n.Length-1] == '-') && - Contains ((rn = n.Substring (0, n.Length-1)))) { - p = this [rn]; - string v = n [n.Length-1] == '+' ? option : null; - c.OptionName = option; - c.Option = p; - c.OptionValues.Add (v); - p.Invoke (c); - return true; - } - return false; - } - - private bool ParseBundledValue (string f, string n, OptionContext c) - { - if (f != "-") - return false; - for (int i = 0; i < n.Length; ++i) { - Option p; - string opt = f + n [i].ToString (); - string rn = n [i].ToString (); - if (!Contains (rn)) { - if (i == 0) - return false; - throw new OptionException (string.Format (localizer ( - "Cannot bundle unregistered option '{0}'."), opt), opt); - } - p = this [rn]; - switch (p.OptionValueType) { - case OptionValueType.None: - Invoke (c, opt, n, p); - break; - case OptionValueType.Optional: - case OptionValueType.Required: { - string v = n.Substring (i+1); - c.Option = p; - c.OptionName = opt; - ParseValue (v.Length != 0 ? v : null, c); - return true; - } - default: - throw new InvalidOperationException ("Unknown OptionValueType: " + p.OptionValueType); - } - } - return true; - } - - private static void Invoke (OptionContext c, string name, string value, Option option) - { - c.OptionName = name; - c.Option = option; - c.OptionValues.Add (value); - option.Invoke (c); - } - - private const int OptionWidth = 29; - - public void WriteOptionDescriptions (TextWriter o) - { - foreach (Option p in this) { - int written = 0; - if (!WriteOptionPrototype (o, p, ref written)) - continue; - - if (written < OptionWidth) - o.Write (new string (' ', OptionWidth - written)); - else { - o.WriteLine (); - o.Write (new string (' ', OptionWidth)); - } - - List lines = GetLines (localizer (GetDescription (p.Description))); - o.WriteLine (lines [0]); - string prefix = new string (' ', OptionWidth+2); - for (int i = 1; i < lines.Count; ++i) { - o.Write (prefix); - o.WriteLine (lines [i]); - } - } - } - - bool WriteOptionPrototype (TextWriter o, Option p, ref int written) - { - string[] names = p.Names; - - int i = GetNextOptionIndex (names, 0); - if (i == names.Length) - return false; - - if (names [i].Length == 1) { - Write (o, ref written, " -"); - Write (o, ref written, names [0]); - } - else { - Write (o, ref written, " --"); - Write (o, ref written, names [0]); - } - - for ( i = GetNextOptionIndex (names, i+1); - i < names.Length; i = GetNextOptionIndex (names, i+1)) { - Write (o, ref written, ", "); - Write (o, ref written, names [i].Length == 1 ? "-" : "--"); - Write (o, ref written, names [i]); - } - - if (p.OptionValueType == OptionValueType.Optional || - p.OptionValueType == OptionValueType.Required) { - if (p.OptionValueType == OptionValueType.Optional) { - Write (o, ref written, localizer ("[")); - } - Write (o, ref written, localizer ("=" + GetArgumentName (0, p.MaxValueCount, p.Description))); - string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0 - ? p.ValueSeparators [0] - : " "; - for (int c = 1; c < p.MaxValueCount; ++c) { - Write (o, ref written, localizer (sep + GetArgumentName (c, p.MaxValueCount, p.Description))); - } - if (p.OptionValueType == OptionValueType.Optional) { - Write (o, ref written, localizer ("]")); - } - } - return true; - } - - static int GetNextOptionIndex (string[] names, int i) - { - while (i < names.Length && names [i] == "<>") { - ++i; - } - return i; - } - - static void Write (TextWriter o, ref int n, string s) - { - n += s.Length; - o.Write (s); - } - - private static string GetArgumentName (int index, int maxIndex, string description) - { - if (description == null) - return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); - string[] nameStart; - if (maxIndex == 1) - nameStart = new string[]{"{0:", "{"}; - else - nameStart = new string[]{"{" + index + ":"}; - for (int i = 0; i < nameStart.Length; ++i) { - int start, j = 0; - do { - start = description.IndexOf (nameStart [i], j); - } while (start >= 0 && j != 0 ? description [j++ - 1] == '{' : false); - if (start == -1) - continue; - int end = description.IndexOf ("}", start); - if (end == -1) - continue; - return description.Substring (start + nameStart [i].Length, end - start - nameStart [i].Length); - } - return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); - } - - private static string GetDescription (string description) - { - if (description == null) - return string.Empty; - StringBuilder sb = new StringBuilder (description.Length); - int start = -1; - for (int i = 0; i < description.Length; ++i) { - switch (description [i]) { - case '{': - if (i == start) { - sb.Append ('{'); - start = -1; - } - else if (start < 0) - start = i + 1; - break; - case '}': - if (start < 0) { - if ((i+1) == description.Length || description [i+1] != '}') - throw new InvalidOperationException ("Invalid option description: " + description); - ++i; - sb.Append ("}"); - } - else { - sb.Append (description.Substring (start, i - start)); - start = -1; - } - break; - case ':': - if (start < 0) - goto default; - start = i + 1; - break; - default: - if (start < 0) - sb.Append (description [i]); - break; - } - } - return sb.ToString (); - } - - private static List GetLines (string description) - { - List lines = new List (); - if (string.IsNullOrEmpty (description)) { - lines.Add (string.Empty); - return lines; - } - int length = 80 - OptionWidth - 2; - int start = 0, end; - do { - end = GetLineEnd (start, length, description); - bool cont = false; - if (end < description.Length) { - char c = description [end]; - if (c == '-' || (char.IsWhiteSpace (c) && c != '\n')) - ++end; - else if (c != '\n') { - cont = true; - --end; - } - } - lines.Add (description.Substring (start, end - start)); - if (cont) { - lines [lines.Count-1] += "-"; - } - start = end; - if (start < description.Length && description [start] == '\n') - ++start; - } while (end < description.Length); - return lines; - } - - private static int GetLineEnd (int start, int length, string description) - { - int end = Math.Min (start + length, description.Length); - int sep = -1; - for (int i = start; i < end; ++i) { - switch (description [i]) { - case ' ': - case '\t': - case '\v': - case '-': - case ',': - case '.': - case ';': - sep = i; - break; - case '\n': - return i; - } - } - if (sep == -1 || end == description.Length) - return end; - return sep; - } - } -} - diff --git a/NBToolkit/Oregen.cs b/NBToolkit/Oregen.cs deleted file mode 100644 index 56b91a8..0000000 --- a/NBToolkit/Oregen.cs +++ /dev/null @@ -1,299 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using NDesk.Options; -using Substrate; -using Substrate.Core; - -namespace NBToolkit -{ - public class OregenOptions : TKOptions, IChunkFilterable - { - private OptionSet _filterOpt = null; - private ChunkFilter _chunkFilter = null; - - public int? OPT_ID = null; - - public int? OPT_DATA = null; - - public int? OPT_ROUNDS = null; - public int? OPT_SIZE = null; - public int? OPT_MIN = null; - public int? OPT_MAX = null; - - public bool OPT_OO = false; - public bool OPT_OA = false; - - public bool OPT_MATHFIX = true; - - public List OPT_OB_INCLUDE = new List(); - public List OPT_OB_EXCLUDE = new List(); - - private class OreType - { - public int id; - public string name; - public int rounds; - public int min; - public int max; - public int size; - }; - - private OreType[] oreList = new OreType[] { - new OreType() { id = 16, name = "Coal", rounds = 20, min = 0, max = 127, size = 16 }, - new OreType() { id = 15, name = "Iron", rounds = 20, min = 0, max = 63, size = 8 }, - new OreType() { id = 14, name = "Gold", rounds = 2, min = 0, max = 31, size = 8 }, - new OreType() { id = 73, name = "Redstone", rounds = 8, min = 0, max = 15, size = 7 }, - new OreType() { id = 56, name = "Diamond", rounds = 1, min = 0, max = 15, size = 7 }, - new OreType() { id = 21, name = "Lapis", rounds = 1, min = 0, max = 31, size = 7 }, - }; - - public OregenOptions () - : base() - { - _filterOpt = new OptionSet() - { - { "b|Block=", "Generate blocks of type {ID} (0-255)", - v => OPT_ID = Convert.ToByte(v) % 256 }, - { "d|Data=", "Set the block's data value to {VAL} (0-15)", - v => OPT_DATA = Convert.ToInt32(v) % 16 }, - { "r|Rounds=", "Geneate {NUM} deposits per chunk", - v => OPT_ROUNDS = Convert.ToInt32(v) }, - { "min|MinDepth=", "Generates deposits no lower than depth {VAL} (0-127)", - v => OPT_MIN = Convert.ToInt32(v) % 128 }, - { "max|MaxDepth=", "Generates deposits no higher than depth {VAL} (0-127)", - v => OPT_MAX = Convert.ToInt32(v) % 128 }, - { "s|Size=", "Generates deposits containing roughly up to {VAL} blocks", - v => OPT_SIZE = Convert.ToInt32(v) % 128 }, - { "oo|OverrideOres", "Generated deposits can replace other existing ores", - v => OPT_OO = true }, - { "oa|OverrideAll", "Generated deposits can replace any existing block", - v => OPT_OA = true }, - { "oi|OverrideInclude=", "Generated deposits can replace the specified block type {ID} [repeatable]", - v => OPT_OB_INCLUDE.Add(Convert.ToInt32(v) % 256) }, - { "ox|OverrideExclude=", "Generated deposits can never replace the specified block type {ID} [repeatable]", - v => OPT_OB_EXCLUDE.Add(Convert.ToInt32(v) % 256) }, - { "nu|NativeUnpatched", "Use MC native ore generation algorithm without distribution evenness patch", - v => OPT_MATHFIX = false }, - }; - - _chunkFilter = new ChunkFilter(); - } - - public OregenOptions (string[] args) - : this() - { - Parse(args); - } - - public override void Parse (string[] args) - { - base.Parse(args); - - _filterOpt.Parse(args); - _chunkFilter.Parse(args); - } - - public override void PrintUsage () - { - Console.WriteLine("Usage: nbtoolkit oregen -b -w [options]"); - Console.WriteLine(); - Console.WriteLine("Options for command 'oregen':"); - - _filterOpt.WriteOptionDescriptions(Console.Out); - - Console.WriteLine(); - _chunkFilter.PrintUsage(); - - Console.WriteLine(); - base.PrintUsage(); - } - - public override void SetDefaults () - { - base.SetDefaults(); - - foreach (OreType ore in oreList) { - if (OPT_ID != ore.id) { - continue; - } - - if (OPT_ROUNDS == null) { - OPT_ROUNDS = ore.rounds; - } - if (OPT_MIN == null) { - OPT_MIN = ore.min; - } - if (OPT_MAX == null) { - OPT_MAX = ore.max; - } - if (OPT_SIZE == null) { - OPT_SIZE = ore.size; - } - } - - // Check for required parameters - if (OPT_ID == null) { - Console.WriteLine("Error: You must specify a Block ID"); - Console.WriteLine(); - PrintUsage(); - - throw new TKOptionException(); - } - - if (OPT_ROUNDS == null) { - OPT_ROUNDS = 1; - } - - if (OPT_MIN == null || OPT_MAX == null || OPT_SIZE == null) { - if (OPT_MIN == null) { - Console.WriteLine("Error: You must specify the minimum depth for non-ore blocks"); - } - if (OPT_MAX == null) { - Console.WriteLine("Error: You must specify the maximum depth for non-ore blocks"); - } - if (OPT_SIZE == null) { - Console.WriteLine("Error: You must specify the deposit size for non-ore blocks"); - } - - Console.WriteLine(); - PrintUsage(); - - throw new TKOptionException(); - } - } - - public IChunkFilter GetChunkFilter () - { - return _chunkFilter; - } - } - - public class Oregen : TKFilter - { - private OregenOptions opt; - - private static Random rand = new Random(); - - public Oregen (OregenOptions o) - { - opt = o; - } - - public override void Run () - { - NbtWorld world = GetWorld(opt); - IChunkManager cm = world.GetChunkManager(opt.OPT_DIM); - FilteredChunkManager fcm = new FilteredChunkManager(cm, opt.GetChunkFilter()); - - int affectedChunks = 0; - foreach (ChunkRef chunk in fcm) { - if (chunk == null || !chunk.IsTerrainPopulated) { - continue; - } - - if (opt.OPT_V) { - Console.WriteLine("Processing Chunk (" + chunk.X + "," + chunk.Z + ")"); - } - - affectedChunks++; - - ApplyChunk(world, chunk); - - fcm.Save(); - } - - Console.WriteLine("Affected Chunks: " + affectedChunks); - } - - public void ApplyChunk (NbtWorld world, ChunkRef chunk) - { - if (opt.OPT_V) { - Console.WriteLine("Generating {0} size {1} deposits of {2} between {3} and {4}", - opt.OPT_ROUNDS, opt.OPT_SIZE, opt.OPT_ID, opt.OPT_MIN, opt.OPT_MAX); - } - - IGenerator generator; - if (opt.OPT_DATA == null) { - generator = new NativeGenOre((int)opt.OPT_ID, (int)opt.OPT_SIZE); - ((NativeGenOre)generator).MathFix = opt.OPT_MATHFIX; - } - else { - generator = new NativeGenOre((int)opt.OPT_ID, (int)opt.OPT_DATA, (int)opt.OPT_SIZE); - ((NativeGenOre)generator).MathFix = opt.OPT_MATHFIX; - } - - IChunkManager cm = world.GetChunkManager(opt.OPT_DIM); - IBlockManager bm = new GenOreBlockManager(cm, opt); - - for (int i = 0; i < opt.OPT_ROUNDS; i++) { - if (opt.OPT_VV) { - Console.WriteLine("Generating round {0}...", i); - } - - int x = chunk.X * chunk.Blocks.XDim + rand.Next(chunk.Blocks.XDim); - int y = (int)opt.OPT_MIN + rand.Next((int)opt.OPT_MAX - (int)opt.OPT_MIN); - int z = chunk.Z * chunk.Blocks.ZDim + rand.Next(chunk.Blocks.ZDim); - - generator.Generate(bm, rand, x, y, z); - } - } - } - - public class GenOreBlockManager : BlockManager - { - public const int BLOCK_STONE = 1; - public const int BLOCK_DIRT = 3; - public const int BLOCK_GRAVEL = 13; - public const int BLOCK_GOLD = 14; - public const int BLOCK_IRON = 15; - public const int BLOCK_COAL = 16; - public const int BLOCK_LAPIS = 21; - public const int BLOCK_DIAMOND = 56; - public const int BLOCK_REDSTONE = 73; - - protected OregenOptions opt; - - public GenOreBlockManager (IChunkManager bm, OregenOptions o) - : base(bm) - { - opt = o; - } - - protected override bool Check (int x, int y, int z) - { - if (!base.Check(x, y, z)) { - return false; - } - - int blockID = cache.Blocks.GetID(x & chunkXMask, y & chunkYMask, z & chunkZMask); - - if ( - ((opt.OPT_OA) && (blockID != opt.OPT_ID)) || - ((opt.OPT_OO) && ( - blockID == BLOCK_COAL || blockID == BLOCK_IRON || - blockID == BLOCK_GOLD || blockID == BLOCK_REDSTONE || - blockID == BLOCK_DIAMOND || blockID == BLOCK_LAPIS || - blockID == BLOCK_DIRT || blockID == BLOCK_GRAVEL) && (blockID != opt.OPT_ID)) || - (opt.OPT_OB_INCLUDE.Count > 0) || - (blockID == BLOCK_STONE) - ) { - // If overriding list of ores, check membership - if (opt.OPT_OB_INCLUDE.Count > 0 && !opt.OPT_OB_INCLUDE.Contains(blockID)) { - return false; - } - - // Check for any excluded block - if (opt.OPT_OB_EXCLUDE.Contains(blockID)) { - return false; - } - - // We're allowed to update the block - return true; - } - - return false; - } - - } -} diff --git a/NBToolkit/Program.cs b/NBToolkit/Program.cs deleted file mode 100644 index 5e12711..0000000 --- a/NBToolkit/Program.cs +++ /dev/null @@ -1,151 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using Substrate; - -namespace NBToolkit -{ - class Program - { - static void Main (string[] args) - { - //Harness harness = new Harness(); - - if (args.Length < 1) { - args = new string[1] { "" }; - } - - try { - if (args[0] == "oregen") { - OregenOptions options = new OregenOptions(args); - Oregen filter = new Oregen(options); - options.SetDefaults(); - filter.Run(); - } - else if (args[0] == "replace") { - ReplaceOptions options = new ReplaceOptions(args); - Replace filter = new Replace(options); - options.SetDefaults(); - filter.Run(); - } - else if (args[0] == "purge") { - PurgeOptions options = new PurgeOptions(args); - Purge filter = new Purge(options); - options.SetDefaults(); - filter.Run(); - } - else if (args[0] == "dump") { - DumpOptions options = new DumpOptions(args); - Dump filter = new Dump(options); - options.SetDefaults(); - filter.Run(); - } - else if (args[0] == "relight") { - RelightOptions options = new RelightOptions(args); - Relight filter = new Relight(options); - options.SetDefaults(); - filter.Run(); - } - else if (args[0] == "help") { - if (args.Length < 2) { - args = new string[2] { "help", "help" }; - } - - Console.WriteLine("Command: " + args[1]); - Console.WriteLine(); - - TKOptions options = null; - - if (args[1] == "oregen") { - options = new OregenOptions(args); - - WriteBlock("Generates one or more structured deposits of a single block type randomly within each chunk selected for update. The deposits are similar to natural ore deposits that appear in the world. Default values for depth, size, and number of rounds are provided for the true ores (coal, iron, gold, etc,). Other block types can be used as long as these values are specified in the command."); - Console.WriteLine(); - options.PrintUsage(); - } - else if (args[1] == "replace") { - options = new ReplaceOptions(args); - - WriteBlock("Replaces one block type with another. By default all matching blocks in the world will be replaced, but updates can be restricted by the available options. This command can be used to set a new data value on blocks by replacing a block with itself."); - Console.WriteLine(); - options.PrintUsage(); - } - else if (args[1] == "purge") { - options = new PurgeOptions(args); - - WriteBlock("Deletes all chunks matching the chunk filtering options. If no options are specified, all world chunks will be deleted. Region files that have all of their chunks purged will also be deleted from the world directory."); - Console.WriteLine(); - options.PrintUsage(); - } - else if (args[1] == "dump") { - options = new DumpOptions(args); - - WriteBlock("Dumps out chunk data in a readable JSON file. Block data, which are byte arrays, are printed as Bas64-encoded strings."); - Console.WriteLine(); - options.PrintUsage(); - } - else if (args[1] == "relight") { - options = new RelightOptions(args); - - WriteBlock("Recalculates the blocklight and/or skylight values for selected chunks. This completely resets the lighting in a chunk, recalculates it from existing light sources, then stiches the lighting seamlessly back into neighboring chunks."); - Console.WriteLine(); - options.PrintUsage(); - } - else { - WriteBlock("Prints help and usage information for another command. Available commands are 'oregen', 'replace', 'purge', 'dump', 'relight'."); - Console.WriteLine(); - Console.WriteLine("Usage: nbtoolkit help "); - } - - return; - } - else { - TKOptions options = null; - try { - options = new TKOptions(args); - } - catch (TKOptionException) { } - - Console.WriteLine("Usage: nbtoolkit [options]"); - Console.WriteLine(); - Console.WriteLine("Available commands:"); - Console.WriteLine(" help Get help and usage info for another command"); - Console.WriteLine(" oregen Generate structured deposits of a single block type"); - Console.WriteLine(" replace Replace one block type with another"); - Console.WriteLine(" purge Delete chunks"); - Console.WriteLine(" dump Dump parsed chunk data to a readable JSON file"); - Console.WriteLine(" relight Recalculate lighting on chunks"); - Console.WriteLine(); - options.PrintUsage(); - return; - } - } - catch (TKOptionException) { - return; - } - - Console.WriteLine("Done"); - } - - public static void WriteBlock (string str) - { - string buf = ""; - - while (str.Length > 78) { - for (int i = 78; i >= 0; i--) { - if (str[i] == ' ') { - if (buf.Length > 0) { - buf += " "; - } - buf += str.Substring(0, i) + "\n"; - str = str.Substring(i + 1); - break; - } - } - } - - buf += " " + str; - Console.WriteLine(buf); - } - } -} diff --git a/NBToolkit/Properties/AssemblyInfo.cs b/NBToolkit/Properties/AssemblyInfo.cs deleted file mode 100644 index 497ab97..0000000 --- a/NBToolkit/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("NBToolkit")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("NBToolkit")] -[assembly: AssemblyCopyright("Copyright © Justin Aquadro 2011")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("7eece4a1-8471-43dc-b3b8-fb6b2dc3773e")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/NBToolkit/Purge.cs b/NBToolkit/Purge.cs deleted file mode 100644 index f73a3c9..0000000 --- a/NBToolkit/Purge.cs +++ /dev/null @@ -1,86 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using NDesk.Options; -using Substrate; -using Substrate.Core; - -namespace NBToolkit -{ - public class PurgeOptions : TKOptions, IChunkFilterable - { - private OptionSet _filterOpt = null; - private ChunkFilter _chunkFilter = null; - - public PurgeOptions () - : base() - { - _filterOpt = new OptionSet(); - _chunkFilter = new ChunkFilter(); - } - - public PurgeOptions (string[] args) - : this() - { - Parse(args); - } - - public override void Parse (string[] args) - { - base.Parse(args); - - _filterOpt.Parse(args); - _chunkFilter.Parse(args); - } - - public override void PrintUsage () - { - Console.WriteLine("Usage: nbtoolkit purge [options]"); - Console.WriteLine(); - Console.WriteLine("Options for command 'purge':"); - - _filterOpt.WriteOptionDescriptions(Console.Out); - - Console.WriteLine(); - _chunkFilter.PrintUsage(); - - Console.WriteLine(); - base.PrintUsage(); - } - - public override void SetDefaults () - { - base.SetDefaults(); - } - - public IChunkFilter GetChunkFilter () - { - return _chunkFilter; - } - } - - public class Purge : TKFilter - { - private PurgeOptions opt; - - public Purge (PurgeOptions o) - { - opt = o; - } - - public override void Run () - { - NbtWorld world = GetWorld(opt); - IChunkManager cm = world.GetChunkManager(opt.OPT_DIM); - FilteredChunkManager fcm = new FilteredChunkManager(cm, opt.GetChunkFilter()); - - int affectedChunks = 0; - foreach (ChunkRef chunk in fcm) { - affectedChunks++; - fcm.DeleteChunk(chunk.X, chunk.Z); - } - - Console.WriteLine("Purged Chunks: " + affectedChunks); - } - } -} diff --git a/NBToolkit/Relight.cs b/NBToolkit/Relight.cs deleted file mode 100644 index c4835c3..0000000 --- a/NBToolkit/Relight.cs +++ /dev/null @@ -1,154 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using NDesk.Options; -using Substrate; -using Substrate.Core; - -namespace NBToolkit -{ - public class RelightOptions : TKOptions, IChunkFilterable - { - private OptionSet _filterOpt = null; - private ChunkFilter _chunkFilter = null; - - public bool BlockLight = false; - public bool SkyLight = false; - public bool HeightMap = false; - - public RelightOptions () - : base() - { - _filterOpt = new OptionSet() - { - { "b|BlockLight", "Recalculate the block light values (block light sources) of selected chunks", - v => BlockLight = true }, - { "s|SkyLight", "Recalculate the skylight values (natural sunlight) of selected chunks", - v => SkyLight = true }, - { "m|HeightMap", "Recalculate the height map of selected chunks", - v => HeightMap = true }, - }; - - _chunkFilter = new ChunkFilter(); - } - - public RelightOptions (string[] args) - : this() - { - Parse(args); - } - - public override void Parse (string[] args) - { - base.Parse(args); - - _filterOpt.Parse(args); - _chunkFilter.Parse(args); - } - - public override void PrintUsage () - { - Console.WriteLine("Usage: nbtoolkit relight [options]"); - Console.WriteLine(); - Console.WriteLine("Options for command 'relight':"); - - _filterOpt.WriteOptionDescriptions(Console.Out); - - Console.WriteLine(); - _chunkFilter.PrintUsage(); - - Console.WriteLine(); - base.PrintUsage(); - } - - public override void SetDefaults () - { - base.SetDefaults(); - } - - public IChunkFilter GetChunkFilter () - { - return _chunkFilter; - } - } - - public class Relight : TKFilter - { - private RelightOptions opt; - - public Relight (RelightOptions o) - { - opt = o; - } - - public override void Run () - { - NbtWorld world = GetWorld(opt); - IChunkManager cm = world.GetChunkManager(opt.OPT_DIM); - FilteredChunkManager fcm = new FilteredChunkManager(cm, opt.GetChunkFilter()); - - if (opt.OPT_V) { - Console.WriteLine("Clearing existing chunk lighting..."); - } - - int affectedChunks = 0; - - foreach (ChunkRef chunk in fcm) { - if (opt.OPT_VV) { - Console.WriteLine("Resetting chunk {0},{1}...", chunk.X, chunk.Z); - } - - if (opt.HeightMap) { - chunk.Blocks.RebuildHeightMap(); - } - if (opt.BlockLight) { - chunk.Blocks.ResetBlockLight(); - } - if (opt.SkyLight) { - chunk.Blocks.ResetSkyLight(); - } - fcm.Save(); - - affectedChunks++; - } - - if (opt.OPT_V) { - Console.WriteLine("Rebuilding chunk lighting..."); - } - - foreach (ChunkRef chunk in fcm) { - if (opt.OPT_VV) { - Console.WriteLine("Lighting chunk {0},{1}...", chunk.X, chunk.Z); - } - - if (opt.BlockLight) { - chunk.Blocks.RebuildBlockLight(); - } - if (opt.SkyLight) { - chunk.Blocks.RebuildSkyLight(); - } - fcm.Save(); - } - - if (opt.OPT_V) { - Console.WriteLine("Reconciling chunk edges..."); - } - - foreach (ChunkRef chunk in fcm) { - if (opt.OPT_VV) { - Console.WriteLine("Stitching chunk {0},{1}...", chunk.X, chunk.Z); - } - - if (opt.BlockLight) { - chunk.Blocks.StitchBlockLight(); - } - if (opt.SkyLight) { - chunk.Blocks.StitchSkyLight(); - } - fcm.Save(); - } - - Console.WriteLine("Relit Chunks: " + affectedChunks); - } - } -} diff --git a/NBToolkit/Replace.cs b/NBToolkit/Replace.cs deleted file mode 100644 index dc1aa85..0000000 --- a/NBToolkit/Replace.cs +++ /dev/null @@ -1,377 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Globalization; -using NDesk.Options; -using Substrate; -using Substrate.Core; - -namespace NBToolkit -{ - public class ReplaceOptions : TKOptions, IChunkFilterable, IBlockFilterable - { - private OptionSet _filterOpt = null; - private ChunkFilter _chunkFilter = null; - private BlockFilter _blockFilter = null; - - public int? OPT_BEFORE = null; - public int? OPT_AFTER = null; - - public int? OPT_DATA = null; - public double? OPT_PROB = null; - - // Block coordinate conditions - public int? BL_X_GE = null; - public int? BL_X_LE = null; - public int? BL_Y_GE = null; - public int? BL_Y_LE = null; - public int? BL_Z_GE = null; - public int? BL_Z_LE = null; - - // Neighbor conditions - public int? OPT_NEIGHBOR = null; - public int? OPT_NEIGHBOR_SIDE = null; - public int? OPT_NEIGHBOR_E = null; - public int? OPT_NEIGHBOR_W = null; - public int? OPT_NEIGHBOR_N = null; - public int? OPT_NEIGHBOR_S = null; - public int? OPT_NEIGHBOR_T = null; - public int? OPT_NEIGHBOR_B = null; - - public ReplaceOptions () - : base() - { - _filterOpt = new OptionSet() - { - /*{ "b|before=", "Replace instances of block type {ID} with another block type. This option is repeatable.", - v => _includedBlocks.Add(Convert.ToInt32(v) % 256) },*/ - { "a|after=", "Replace the selected blocks with block type {ID}", - v => OPT_AFTER = Convert.ToInt32(v) % 256 }, - { "d|data=", "Set the new block's data value to {VAL} (0-15)", - v => OPT_DATA = Convert.ToInt32(v) % 16 }, - /*{ "p|prob=", "Replace any matching block with probability {VAL} (0.0-1.0)", - v => { OPT_PROB = Convert.ToDouble(v, new CultureInfo("en-US")); - OPT_PROB = Math.Max((double)OPT_PROB, 0.0); - OPT_PROB = Math.Min((double)OPT_PROB, 1.0); } }, - { "bxr|BlockXRange=", "Update blocks with X-coord between {0:V1} and {1:V2}, inclusive. V1 or V2 may be left blank.", - (v1, v2) => { - try { BL_X_GE = Convert.ToInt32(v1); } catch (FormatException) { } - try { BL_X_LE = Convert.ToInt32(v2); } catch (FormatException) { } - } }, - { "byr|BlockYRange=", "Update blocks with Y-coord between {0:V1} and {1:V2}, inclusive. V1 or V2 may be left blank", - (v1, v2) => { - try { BL_Y_GE = Convert.ToInt32(v1); } catch (FormatException) { } - try { BL_Y_LE = Convert.ToInt32(v2); } catch (FormatException) { } - } }, - { "bzr|BlockZRange=", "Update blocks with Z-coord between {0:V1} and {1:V2}, inclusive. V1 or V2 may be left blank", - (v1, v2) => { - try { BL_Z_GE = Convert.ToInt32(v1); } catch (FormatException) { } - try { BL_Z_LE = Convert.ToInt32(v2); } catch (FormatException) { } - } },*/ - /*{ "nb=", "Update blocks that have block type {ID} as any neighbor", - v => OPT_NEIGHBOR = Convert.ToInt32(v) % 256 }, - { "nbs=", "Update blocks that have block type {ID} as any x/z neighbor", - v => OPT_NEIGHBOR_SIDE = Convert.ToInt32(v) % 256 }, - { "nbxa=", "Update blocks that have block type {ID} as their south neighbor", - v => OPT_NEIGHBOR_S = Convert.ToInt32(v) % 256 }, - { "nbxb=", "Update blocks that have block type {ID} as their north neighbor", - v => OPT_NEIGHBOR_N = Convert.ToInt32(v) % 256 }, - { "nbya=", "Update blocks that have block type {ID} as their top neighbor", - v => OPT_NEIGHBOR_T = Convert.ToInt32(v) % 256 }, - { "nbyb=", "Update blocks that have block type {ID} as their bottom neighbor", - v => OPT_NEIGHBOR_B = Convert.ToInt32(v) % 256 }, - { "nbza=", "Update blocks that have block type {ID} as their west neighbor", - v => OPT_NEIGHBOR_W = Convert.ToInt32(v) % 256 }, - { "nbzb=", "Update blocks that have block type {ID} as their east neighbor", - v => OPT_NEIGHBOR_E = Convert.ToInt32(v) % 256 },*/ - }; - - _chunkFilter = new ChunkFilter(); - _blockFilter = new BlockFilter(); - } - - public ReplaceOptions (string[] args) - : this() - { - Parse(args); - } - - public override void Parse (string[] args) - { - base.Parse(args); - - _filterOpt.Parse(args); - _chunkFilter.Parse(args); - _blockFilter.Parse(args); - } - - public override void PrintUsage () - { - Console.WriteLine("Usage: nbtoolkit replace -a [options]"); - Console.WriteLine(); - Console.WriteLine("Options for command 'replace':"); - - _filterOpt.WriteOptionDescriptions(Console.Out); - - Console.WriteLine(); - _chunkFilter.PrintUsage(); - - Console.WriteLine(); - _blockFilter.PrintUsage(); - - Console.WriteLine(); - base.PrintUsage(); - } - - public override void SetDefaults () - { - base.SetDefaults(); - - // Check for required parameters - if (OPT_AFTER == null) { - Console.WriteLine("Error: You must specify a replacement Block ID"); - Console.WriteLine(); - PrintUsage(); - - throw new TKOptionException(); - } - - if (_blockFilter.XAboveEq != null) { - int cx = (int)_blockFilter.XAboveEq >> 5; - _chunkFilter.XAboveEq = Math.Max(_chunkFilter.XAboveEq ?? cx, cx); - } - if (_blockFilter.XBelowEq != null) { - int cx = (int)_blockFilter.XBelowEq >> 5; - _chunkFilter.XBelowEq = Math.Min(_chunkFilter.XBelowEq ?? cx, cx); - } - if (_blockFilter.ZAboveEq != null) { - int cx = (int)_blockFilter.ZAboveEq >> 5; - _chunkFilter.ZAboveEq = Math.Max(_chunkFilter.ZAboveEq ?? cx, cx); - } - if (_blockFilter.ZBelowEq != null) { - int cx = (int)_blockFilter.ZBelowEq >> 5; - _chunkFilter.ZBelowEq = Math.Min(_chunkFilter.ZBelowEq ?? cx, cx); - } - } - - public IChunkFilter GetChunkFilter () - { - return _chunkFilter; - } - - public IBlockFilter GetBlockFilter () - { - return _blockFilter; - } - } - - public class Replace : TKFilter - { - private ReplaceOptions opt; - - private static Random rand = new Random(); - - private List[] _sort = new List[256]; - - public Replace (ReplaceOptions o) - { - opt = o; - - for (int i = 0; i < 256; i++) { - _sort[i] = new List(); - } - } - - public override void Run () - { - NbtWorld world = GetWorld(opt); - IChunkManager cm = world.GetChunkManager(opt.OPT_DIM); - FilteredChunkManager fcm = new FilteredChunkManager(cm, opt.GetChunkFilter()); - - int affectedChunks = 0; - foreach (ChunkRef chunk in fcm) { - if (opt.OPT_V) { - Console.WriteLine("Processing chunk {0},{1}...", chunk.X, chunk.Z); - } - - ApplyChunk(world, chunk); - - affectedChunks += fcm.Save() > 0 ? 1 : 0; - } - - Console.WriteLine("Affected Chunks: " + affectedChunks); - } - - public void ApplyChunk (NbtWorld world, ChunkRef chunk) - { - IBlockFilter opt_b = opt.GetBlockFilter(); - - int xBase = chunk.X * chunk.Blocks.XDim; - int zBase = chunk.Z * chunk.Blocks.ZDim; - - // Determine X range - int xmin = 0; - int xmax = 15; - - if (opt_b.XAboveEq != null) { - xmin = (int)opt_b.XAboveEq - xBase; - } - if (opt_b.XBelowEq != null) { - xmax = (int)opt_b.XBelowEq - xBase; - } - - xmin = (xmin < 0) ? 0 : xmin; - xmax = (xmax > 15) ? 15 : xmax; - - if (xmin > 15 || xmax < 0 || xmin > xmax) { - return; - } - - // Determine Y range - int ymin = 0; - int ymax = 127; - - if (opt_b.YAboveEq != null) { - ymin = (int)opt_b.YAboveEq; - } - if (opt_b.YBelowEq != null) { - ymax = (int)opt_b.YBelowEq; - } - - if (ymin > ymax) { - return; - } - - // Determine X range - int zmin = 0; - int zmax = 15; - - if (opt_b.ZAboveEq != null) { - zmin = (int)opt_b.ZAboveEq - zBase; - } - if (opt_b.ZBelowEq != null) { - zmax = (int)opt_b.ZBelowEq - zBase; - } - - zmin = (zmin < 0) ? 0 : zmin; - zmax = (zmax > 15) ? 15 : zmax; - - if (zmin > 15 || zmax < 0 || zmin > zmax) { - return; - } - - int xdim = chunk.Blocks.XDim; - int ydim = chunk.Blocks.YDim; - int zdim = chunk.Blocks.ZDim; - - // Bin blocks - for (int y = ymin; y <= ymax; y++) { - for (int x = xmin; x <= xmax; x++) { - for (int z = zmin; z <= zmax; z++) { - int id = chunk.Blocks.GetID(x, y, z); - _sort[id].Add(new BlockKey(x, y, z)); - } - } - } - - // Process bins - for (int i = 0; i < 256; i++) { - if (_sort[i].Count == 0) { - continue; - } - - if (opt_b.IncludedBlockCount > 0 & !opt_b.IncludedBlocksContains(i)) { - continue; - } - - if (opt_b.ExcludedBlockCount > 0 & opt_b.ExcludedBlocksContains(i)) { - continue; - } - - foreach (BlockKey key in _sort[i]) { - chunk.Blocks.SetID(key.x, key.y, key.z, (int)opt.OPT_AFTER); - - if (opt.OPT_VV) { - int gx = chunk.X * xdim + key.x; - int gz = chunk.Z * zdim + key.z; - Console.WriteLine("Replaced block {0} at {1},{2},{3}", i, gx, key.y, gz); - } - - if (opt.OPT_DATA != null) { - chunk.Blocks.SetData(key.x, key.y, key.z, (int)opt.OPT_DATA); - } - } - } - - // Reset bins - for (int i = 0; i < 256; i++) { - _sort[i].Clear(); - } - - // Process Chunk - /*for (int y = ymin; y <= ymax; y++) { - for (int x = xmin; x <= xmax; x++) { - for (int z = zmin; z <= zmax; z++) { - // Probability test - if (opt_b.ProbMatch != null) { - double c = rand.NextDouble(); - if (c > opt_b.ProbMatch) { - continue; - } - } - - int lx = x % xdim; - int ly = y % ydim; - int lz = z % zdim; - - // Get the old block - int oldBlock = chunk.Blocks.GetID(lx , ly, lz); - - // Skip block if it doesn't match the inclusion list - if (opt_b.IncludedBlockCount > 0) { - bool match = false; - foreach (int ib in opt_b.IncludedBlocks) { - if (oldBlock == ib) { - match = true; - break; - } - } - - if (!match) { - continue; - } - } - - // Skip block if it does match the exclusion list - if (opt_b.ExcludedBlockCount > 0) { - bool match = false; - foreach (int xb in opt_b.ExcludedBlocks) { - if (oldBlock == xb) { - match = true; - break; - } - } - - if (match) { - continue; - } - } - - // Replace the block - chunk.Blocks.SetID(lx, ly, lz, (int)opt.OPT_AFTER); - - if (opt.OPT_VV) { - int gx = chunk.X * xdim + lx; - int gz = chunk.Z * zdim + lz; - Console.WriteLine("Replaced block at {0},{1},{2}", gx, ly, gz); - } - - if (opt.OPT_DATA != null) { - chunk.Blocks.SetData(lx, ly, lz, (int)opt.OPT_DATA); - } - } - } - }*/ - } - } -} diff --git a/NBToolkit/TKFilter.cs b/NBToolkit/TKFilter.cs deleted file mode 100644 index 2de1a21..0000000 --- a/NBToolkit/TKFilter.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; -using Substrate; - -namespace NBToolkit -{ - - - public abstract class TKFilter - { - //public abstract void ApplyChunk (NBT_Tree root); - - public abstract void Run (); - - public NbtWorld GetWorld (TKOptions opt) - { - NbtWorld world = null; - try { - if (opt.OPT_ALPHA) { - world = AlphaWorld.Open(opt.OPT_WORLD); - } - else { - world = BetaWorld.Open(opt.OPT_WORLD); - } - } - catch (Exception ex) { - Console.WriteLine("Error: " + ex.Message); - Environment.Exit(1); - } - - return world; - } - } -} diff --git a/NBToolkit/TKOptions.cs b/NBToolkit/TKOptions.cs deleted file mode 100644 index a2f495e..0000000 --- a/NBToolkit/TKOptions.cs +++ /dev/null @@ -1,89 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using NDesk.Options; -using System.IO; - -namespace NBToolkit -{ - public interface IOptions - { - void Parse (string[] args); - void PrintUsage (); - } - - public class TKOptions : IOptions - { - private OptionSet commonOpt = null; - - public string OPT_WORLD = ""; - public int OPT_DIM = 0; - - // Verbosity - public bool OPT_V = false; - public bool OPT_VV = false; - public bool OPT_HELP = false; - public bool OPT_ALPHA = false; - - public TKOptions () - { - commonOpt = new OptionSet() - { - { "w|world=", "World directory", - v => OPT_WORLD = v }, - { "h|help", "Print this help message", - v => OPT_HELP = true }, - { "alpha", "Specify that the world is stored as individual chunk files", - v => OPT_ALPHA = true }, - { "nether", "Update the Nether instead of the main region", - v => OPT_DIM = -1 }, - { "v", "Verbose output", - v => OPT_V = true }, - { "vv", "Very verbose output", - v => { OPT_V = true; OPT_VV = true; } }, - }; - } - - public TKOptions (string[] args) - : this() - { - Parse(args); - } - - public virtual void Parse (string[] args) - { - commonOpt.Parse(args); - } - - public virtual void PrintUsage () - { - Console.WriteLine("Common Options:"); - commonOpt.WriteOptionDescriptions(Console.Out); - } - - public virtual void SetDefaults () - { - if (OPT_HELP) { - this.PrintUsage(); - throw new TKOptionException(); - } - - if (OPT_WORLD.Length == 0) { - Console.WriteLine("Error: You must specify a World path"); - Console.WriteLine(); - this.PrintUsage(); - - throw new TKOptionException(); - } - } - } - - public class TKOptionException : Exception - { - public TKOptionException () { } - - public TKOptionException (String msg) : base(msg) { } - - public TKOptionException (String msg, Exception innerException) : base(msg, innerException) { } - } -} diff --git a/NBToolkit/app.config b/NBToolkit/app.config deleted file mode 100644 index 73859b0..0000000 --- a/NBToolkit/app.config +++ /dev/null @@ -1,3 +0,0 @@ - - -