Ejemplo n.º 1
0
        public static void PositionRails(AnvilWorld worldDest, BlockManager bm)
        {
            // todo low: different elevations
            int intReplaced = 0;

            for (int x = 0; x < City.mapLength; x++)
            {
                for (int z = -City.farmLength; z < City.mapLength; z++)
                {
                    for (int y = 0; y < 128; y++)
                    {
                        switch (bm.GetID(x, y, z))
                        {
                        case BlockType.POWERED_RAIL:
                        case BlockType.DETECTOR_RAIL:
                        case BlockType.RAILS:
                            BlockHelper.MakeRail(x, y, z);
                            if (++intReplaced > 100)
                            {
                                worldDest.Save();
                                intReplaced = 0;
                            }
                            break;
                        }
                    }
                }
            }
        }
Ejemplo n.º 2
0
        public static void CropMaceWorld(frmMace frmLogForm)
        {
            // thank you to Surrogard <*****@*****.**> for providing a linux friendly version of this code:
            Directory.CreateDirectory("macecopy".ToMinecraftSaveDirectory());
            AnvilWorld         awCopy = AnvilWorld.Create("macecopy".ToMinecraftSaveDirectory());
            RegionChunkManager cmCopy = awCopy.GetChunkManager();
            AnvilWorld         awCrop = AnvilWorld.Open("mace".ToMinecraftSaveDirectory());
            RegionChunkManager cmCrop = awCrop.GetChunkManager();

            foreach (ChunkRef chunk in cmCrop)
            {
                if (chunk.X >= -7 && chunk.X <= 11 && chunk.Z >= 0 && chunk.Z <= 11)
                {
                    Debug.WriteLine("Copying chunk " + chunk.X + "," + chunk.Z);
                    cmCopy.SetChunk(chunk.X, chunk.Z, chunk.GetChunkRef());
                }
                cmCopy.Save();
            }
            awCopy.Level.GameType = GameType.CREATIVE;
            cmCopy.Save();
            awCopy.Save();
            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                Process.Start("explorer.exe", @"/select," + "macecopy".ToMinecraftSaveDirectory() + "\\level.dat");
            }
        }
Ejemplo n.º 3
0
        public static void MakeMineshaft(AnvilWorld world, BlockManager bm, Buildings.structPoint spMineshaftEntrance, frmMace frmLogForm)
        {
            _intBlockStartBuildings = City.edgeLength + 13;
            int intMineshaftSize = (1 + City.mapLength) - (_intBlockStartBuildings * 2);

            if (intMineshaftSize % 5 > 0)
            {
                intMineshaftSize += 5 - (intMineshaftSize % 5);
            }
            _intBlockStartBuildings -= 2;
            for (int intLevel = 1; intLevel <= 7; intLevel++)
            {
                if (Utils.ValueFromXMLElement(Path.Combine("Resources", "Mineshaft.xml"), "active", "level" + intLevel.ToString()).IsAffirmative())
                {
                    MakeLevel(world, bm, intLevel, intMineshaftSize, spMineshaftEntrance, frmLogForm);
                }
            }
            int intBlockToReplace = bm.GetID(spMineshaftEntrance.x, 63, spMineshaftEntrance.z + 1);

            BlockShapes.MakeSolidBox(spMineshaftEntrance.x, spMineshaftEntrance.x,
                                     3, 63, spMineshaftEntrance.z + 1, spMineshaftEntrance.z + 1, BlockInfo.Wood.ID, 0);
            BlockHelper.MakeLadder(spMineshaftEntrance.x, 4, 63, spMineshaftEntrance.z, 0, BlockInfo.Wood.ID);
            BlockShapes.MakeSolidBox(spMineshaftEntrance.x, spMineshaftEntrance.x, 3, 63, spMineshaftEntrance.z + 1,
                                     spMineshaftEntrance.z + 1, BlockInfo.Stone.ID, 0);
            bm.SetID(spMineshaftEntrance.x, 63, spMineshaftEntrance.z + 1, intBlockToReplace);
        }
Ejemplo n.º 4
0
        public Spawner(Coordinate coordinate, AnvilWorld world)
        {
            var block = world.Dimensions[Dimension.TheEnd].Blocks.GetBlock(coordinate.X, coordinate.Y, coordinate.Z);
            var id    = block.Block.Id;

            IsBroken = id != 50;
        }
Ejemplo n.º 5
0
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("You must specify a target directory");
                return;
            }
            string dest = args[0];

            /*
             * NbtVerifier.InvalidTagType += (e) => {
             *  throw new Exception("Invalid Tag Type: " + e.TagName + " [" + e.Tag + "]");
             * };
             * NbtVerifier.InvalidTagValue += (e) => {
             *  throw new Exception("Invalid Tag Value: " + e.TagName + " [" + e.Tag + "]");
             * };
             * NbtVerifier.MissingTag += (e) => {
             *  throw new Exception("Missing Tag: " + e.TagName);
             * };
             */

            // Opening an NbtWorld will try to autodetect if a world is Alpha-style or Beta-style
            Console.WriteLine("AnvilWorld.Open(dest)");
            AnvilWorld world = AnvilWorld.Open(dest);

            // Grab a generic chunk manager reference
            Console.WriteLine("world.GetChunkManager()");
            IChunkManager cm = world.GetChunkManager();

            // Iterate through all the chunks
            foreach (ChunkRef chunk in cm)
            {
                // Check if Ocean chunk
                bool foundocean = false;
                for (int x = 0; x < 16; x++)
                {
                    for (int z = 0; z < 16; z++)
                    {
                        if (chunk.Biomes.GetBiome(x, z) == BiomeType.Ocean || chunk.Biomes.GetBiome(x, z) == BiomeType.DeepOcean || chunk.Biomes.GetBiome(x, z) == BiomeType.FrozenOcean)
                        {
                            foundocean = true;
                        }
                    }
                }
                // Or if old unpopulated chunk
                //set status as liquid_carved (or similar)
                if (foundocean == true)
                {
                    Console.WriteLine("Found ocean in chunk {0},{1}, setting status to liquid_carved", chunk.X, chunk.Z);
                    chunk.Status = "liquid_carved";
                }

                cm.Save();

                //Console.WriteLine("Repopulated Chunk {0},{1}", chunk.X, chunk.Z);
            }
        }
Ejemplo n.º 6
0
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("You must specify a target directory");
                return;
            }
            string dest = args[0];

            AnvilWorld   world = AnvilWorld.Open("F:\\Minecraft\\test");
            BlockManager bm    = world.GetBlockManager();

            bm.AutoLight = false;

            Grid grid = new Grid();

            grid.BuildInit(bm);

            Generator             gen   = new Generator();
            List <Generator.Edge> edges = gen.Generate();

            foreach (Generator.Edge e in edges)
            {
                int x1;
                int y1;
                int z1;
                gen.UnIndex(e.node1, out x1, out y1, out z1);

                int x2;
                int y2;
                int z2;
                gen.UnIndex(e.node2, out x2, out y2, out z2);

                grid.LinkRooms(bm, x1, y1, z1, x2, y2, z2);
            }

            // Entrance Room
            grid.BuildRoom(bm, 2, 5, 2);
            grid.LinkRooms(bm, 2, 5, 2, 1, 5, 2);
            grid.LinkRooms(bm, 2, 5, 2, 3, 5, 2);
            grid.LinkRooms(bm, 2, 5, 2, 2, 5, 1);
            grid.LinkRooms(bm, 2, 5, 2, 2, 5, 3);
            grid.LinkRooms(bm, 2, 4, 2, 2, 5, 2);

            // Exit Room
            grid.BuildRoom(bm, 2, -1, 2);
            grid.LinkRooms(bm, 2, -1, 2, 2, 0, 2);
            grid.AddPrize(bm, 2, -1, 2);

            Console.WriteLine("Relight Chunks");

            RegionChunkManager cm = world.GetChunkManager();

            cm.RelightDirtyChunks();

            world.Save();
        }
Ejemplo n.º 7
0
        void WriteMetricsFile(AnvilWorld World)
        {
            XmlWriter Writer = XmlWriter.Create(_Configuration.MetricsFilename);

            Writer.WriteStartElement("Metrics");
            Writer.WriteAttributeString("Dimension", _Metrics.Dimension);
            Writer.WriteAttributeString("Name", World.Level.LevelName);

            {
                Writer.WriteStartElement("World");
                {
                    Writer.WriteElementString("Filesize", World.Level.SizeOnDisk.ToString());
                    Writer.WriteElementString("Seed", World.Level.RandomSeed.ToString());
                    Writer.WriteElementString("LastPlayed", World.Level.LastPlayed.ToString());
                    Writer.WriteElementString("IsHardcore", World.Level.Hardcore.ToString());
                    Writer.WriteElementString("GameType", World.Level.GameType.ToString());
                    Writer.WriteElementString("GenerateStructures", World.Level.UseMapFeatures.ToString());
                    Writer.WriteElementString("VersionNumber", World.Level.Version.ToString());

                    Writer.WriteStartElement("SpawnPoint");
                    {
                        Writer.WriteElementString("X", World.Level.Spawn.X.ToString());
                        Writer.WriteElementString("Y", World.Level.Spawn.Y.ToString());
                        Writer.WriteElementString("Z", World.Level.Spawn.Z.ToString());
                    }
                    Writer.WriteEndElement();
                }
                Writer.WriteEndElement();

                Writer.WriteStartElement("Size");
                {
                    Writer.WriteElementString("WidthChunks", (_Metrics.MaxX - _Metrics.MinX + 1).ToString());
                    Writer.WriteElementString("HeightChunks", (_Metrics.MaxZ - _Metrics.MinZ + 1).ToString());
                }
                Writer.WriteEndElement();

                Writer.WriteStartElement("Extents");
                {
                    Writer.WriteElementString("X1", _Metrics.MinX.ToString());
                    Writer.WriteElementString("Y1", _Metrics.MinZ.ToString());

                    Writer.WriteElementString("X2", _Metrics.MaxX.ToString());
                    Writer.WriteElementString("Y2", _Metrics.MaxZ.ToString());
                }
                Writer.WriteEndElement();

                Writer.WriteElementString("ChunkCount", _Metrics.NumberOfChunks.ToString());
            }

            Writer.WriteEndElement();

            Writer.Flush();
            Writer.Close();

            Console.WriteLine("Wrote metrics file to " + Path.GetFileName(_Configuration.MetricsFilename));
        }
Ejemplo n.º 8
0
 private static bool CheckCancelled(AnvilWorld worldDest, frmMace frmLogForm)
 {
     if (City.stop)
     {
         worldDest.Level.LevelName = "Generation cancelled. Please delete me.";
         worldDest.Save();
         return(true);
     }
     return(false);
 }
Ejemplo n.º 9
0
        public void initializeMinecraftWorld()
        {
            currentWorld = AnvilWorld.Create(Settings.Default.outputPath);

            // We can set different world parameters
            currentWorld.Level.LevelName     = Settings.Default.levelName;
            currentWorld.Level.Spawn         = new SpawnPoint(20, 255, 20);
            currentWorld.Level.GameType      = GameType.CREATIVE;
            currentWorld.Level.AllowCommands = true;
        }
        public void ExportMap(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            string           path   = e.Argument as string;

            worker.ReportProgress(0, "Exporting map to " + path);

            AnvilWorld world = AnvilWorld.Create(path);

            world.Level.LevelName = "Dwarf Fortress World";
            world.Level.GameType  = GameType.CREATIVE;
            world.Level.Spawn     = new SpawnPoint(36, 255, 36);
            world.Save();
            var chunkManager = world.GetChunkManager();
            int total        = (Tiles[0].Height * tileWidth / 16) * (Tiles[0].Width * tileWidth / 16);
            int done         = 0;

            for (int chunkZ = 0; chunkZ < Tiles[0].Height * tileWidth / 16; chunkZ++)
            {
                for (int chunkX = 0; chunkX < Tiles[0].Width * tileWidth / 16; chunkX++)
                {
                    var chunk  = chunkManager.CreateChunk(chunkX, chunkZ);
                    var blocks = chunk.Blocks;
                    blocks.AutoLight         = false;
                    chunk.IsTerrainPopulated = true;
                    int chunkY = 0;
                    foreach (var level in Tiles)
                    {
                        if (!level.Enabled)
                        {
                            continue;
                        }
                        for (int y = 0; y < tileHeight; y++)
                        {
                            for (int z = 0; z < 16; z++)
                            {
                                for (int x = 0; x < 16; x++)
                                {
                                    blocks.SetBlock(x, y + (chunkY * tileHeight), z,
                                                    level.GetBlock(x + (chunkX * 16), y, z + (chunkZ * 16)));
                                }
                            }
                        }
                        chunkY++;
                    }
                    blocks.RebuildSkyLight();
                    blocks.RebuildBlockLight();
                    blocks.RebuildHeightMap();
                    chunkManager.Save();
                    done++;
                    worker.ReportProgress(done * 100 / total, "Generating Chunks");
                }
            }
            worker.ReportProgress(100, "Finished exporting map");
        }
Ejemplo n.º 11
0
        public Island(IslandType type, AnvilWorld world)
        {
            IslandType = type;

            var block    = world.Dimensions[(int)type.GetDimension()].Blocks.GetBlock(type.GetCoordinate().X, type.GetCoordinate().Y, type.GetCoordinate().Z);
            var id       = block.Block.Id;
            var metadata = block.Metadata;

            // ブロックIDが121(エンドポータルフレームは120のはずだけどなぜか121)
            // 且つメタデータが4以上7以下(向きが4方向あるため)
            IsComplete = id == 121 && (4 <= metadata && metadata <= 7);
        }
Ejemplo n.º 12
0
        public static void ReplaceValuableBlocks(AnvilWorld worldDest, BlockManager bm)
        {
            int intReplaced = 0;

            for (int x = 0; x < City.mapLength; x++)
            {
                for (int z = -City.farmLength; z < City.mapLength; z++)
                {
                    for (int y = 40; y < 128; y++)
                    {
                        if (bm.GetID(x, y, z) != City.wallMaterialID ||
                            bm.GetData(x, y, z) != City.wallMaterialData)
                        {
                            switch ((int)bm.GetID(x, y, z))
                            {
                            case BlockType.GOLD_BLOCK:
                                BlockShapes.MakeBlock(x, y, z, BlockInfo.Wool.ID, (int)WoolColor.YELLOW);
                                intReplaced++;
                                break;

                            case BlockType.IRON_BLOCK:
                                BlockShapes.MakeBlock(x, y, z, BlockInfo.Wool.ID, (int)WoolColor.LIGHT_GRAY);
                                intReplaced++;
                                break;

                            case BlockType.OBSIDIAN:
                                BlockShapes.MakeBlock(x, y, z, BlockInfo.Wool.ID, (int)WoolColor.BLACK);
                                intReplaced++;
                                break;

                            case BlockType.DIAMOND_BLOCK:
                                BlockShapes.MakeBlock(x, y, z, BlockInfo.Wool.ID, (int)WoolColor.LIGHT_BLUE);
                                intReplaced++;
                                break;

                            case BlockType.LAPIS_BLOCK:
                                BlockShapes.MakeBlock(x, y, z, BlockInfo.Wool.ID, (int)WoolColor.BLUE);
                                intReplaced++;
                                break;
                                // no need for a default, because we purposefully want to skip all the other blocks
                            }
                            if (intReplaced > 25)
                            {
                                worldDest.Save();
                                intReplaced = 0;
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 13
0
        static void Main(string[] args)
        {
            if (args.Length != 3)
            {
                Console.WriteLine("Usage: Convert <world> <dest> <alpha|beta|anvil>");
                return;
            }

            string src     = args[0];
            string dst     = args[1];
            string srctype = args[2];

            if (!Directory.Exists(dst))
            {
                Directory.CreateDirectory(dst);
            }

            // Open source and destrination worlds depending on conversion type
            NbtWorld srcWorld = NbtWorld.Open(src);
            NbtWorld dstWorld;

            switch (srctype)
            {
            case "alpha": dstWorld = AlphaWorld.Create(dst); break;

            case "beta": dstWorld = BetaWorld.Create(dst); break;

            case "anvil": dstWorld = AnvilWorld.Create(dst); break;

            default: throw new Exception("Invalid conversion type");
            }

            // Grab chunk managers to copy chunks
            IChunkManager cmsrc = srcWorld.GetChunkManager();
            IChunkManager cmdst = dstWorld.GetChunkManager();

            // Copy each chunk from source to dest
            foreach (ChunkRef chunk in cmsrc)
            {
                cmdst.SetChunk(chunk.X, chunk.Z, chunk.GetChunkRef());
                Console.WriteLine("Copying chunk: {0}, {1}", chunk.X, chunk.Z);
            }

            // Copy level data from source to dest
            dstWorld.Level.LoadTreeSafe(srcWorld.Level.BuildTree());

            // Save level.dat
            dstWorld.Level.Save();
        }
Ejemplo n.º 14
0
 public static void MoveChunks(AnvilWorld world, RegionChunkManager cm, int CityX, int CityZ)
 {
     cm.Save();
     world.Save();
     for (int x = 0; x < City.mapLength / 16; x++)
     {
         for (int z = -City.farmLength / 16; z < City.mapLength / 16; z++)
         {
             cm.CopyChunk(x, z, CityX + x + CITY_RELOCATION_CHUNKS, CityZ + z + CITY_RELOCATION_CHUNKS);
             ChunkRef chunkActive = cm.GetChunkRef(CityX + x + CITY_RELOCATION_CHUNKS, CityZ + z + CITY_RELOCATION_CHUNKS);
             chunkActive.IsTerrainPopulated = true;
             chunkActive.Blocks.AutoLight   = true;
             biomes.Add(chunkActive.X + "." + chunkActive.Z, City.biome);
             cm.DeleteChunk(x, z);
             cm.Save();
             world.Save();
         }
     }
 }
Ejemplo n.º 15
0
        /// <summary>
        /// ワールド読み込み
        /// </summary>
        /// <param name="path">ワールドパス</param>
        public static void Load(string path)
        {
            if (IsLoading.Value)
            {
                return;
            }

            IslandsData.Reset();
            SpawnersData.Reset();
            ScoreData.Reset();

            FolderName.Value      = System.IO.Path.GetFileName(path);
            IsLoading.Value       = true;
            LoadingProgress.Value = 0;
            Path.Value            = path;

            var count = 0;

            Task.Run(() =>
            {
                try
                {
                    WorldData = AnvilWorld.Load(path);

                    IslandsData.Load(ref count);
                    SpawnersData.Load(ref count);
                    ScoreData.Load();

                    // 100%を見せたいからという理由だけで0.3秒遅延させる
                    System.Threading.Thread.Sleep(300);
                }
                catch
                {
                    Path.Value    = null;
                    IsError.Value = true;
                }
                finally
                {
                    IsLoading.Value = false;
                }
            });
        }
Ejemplo n.º 16
0
 public static structPoint MakeInsideCity(BlockManager bm, AnvilWorld worldDest, int[,] intArea, frmMace frmLogForm)
 {
     int intBlockStart = City.edgeLength + 13;
     structPoint spMineshaftEntrance = MakeBuildings(bm, intArea, intBlockStart, worldDest);
     worldDest.Save();
     if (City.hasPaths)
     {
         JoinPathsToRoad(bm);
     }
     else
     {
         RemovePaths(bm, intArea, intBlockStart);
     }
     if (City.hasMainStreets)
     {
         frmLogForm.UpdateLog("Creating street lights: " + City.streetLightType, true, true);
         MakeStreetLights(bm);
     }
     return spMineshaftEntrance;
 }
Ejemplo n.º 17
0
        // this is a simplified version of the MakeBuildings method from Buildings.cs
        private static void MakeBuildings(BlockManager bm, int[,] intArea, AnvilWorld world)
        {
            int intBuildings = 0;

            for (int x = 0; x < intArea.GetLength(0); x++)
            {
                for (int z = 0; z < intArea.GetLength(1); z++)
                {
                    // hack low: this 100 to 500 stuff is all a bit hackish really, need to find a proper solution
                    if (intArea[x, z] >= 100 && intArea[x, z] <= 500)
                    {
                        SourceWorld.Building CurrentBuilding = SourceWorld.GetBuilding(intArea[x, z] - 100);

                        if (CurrentBuilding.intSizeX >= 10 && RNG.NextDouble() > 0.8)
                        {
                            if (RNG.NextDouble() > 0.5)
                            {
                                MakePond(bm, 6 + x, CurrentBuilding.intSizeX, (6 - City.farmLength) + z, CurrentBuilding.intSizeZ);
                            }
                            else
                            {
                                MakeHill(bm, 6 + x, CurrentBuilding.intSizeX, (6 - City.farmLength) + z, CurrentBuilding.intSizeZ);
                            }
                        }
                        else
                        {
                            SourceWorld.InsertBuilding(bm, intArea, 0, 6 + x, (6 - City.farmLength) + z, CurrentBuilding, 0, -1);
                        }

                        intArea[x + CurrentBuilding.intSizeX - 2, z + CurrentBuilding.intSizeZ - 2] = 0;
                        if (++intBuildings == NumberOfBuildingsBetweenSaves)
                        {
                            world.Save();
                            intBuildings = 0;
                        }
                    }
                }
            }
        }
Ejemplo n.º 18
0
        public static void MakeFlowers(AnvilWorld worldDest, BlockManager bm)
        {
            string[] strFlowers  = Utils.ArrayFromXMLElement(Path.Combine("Resources", "Themes", City.themeName + ".xml"), "options", "flowers");
            int      FlowerCount = 0;

            for (int x = 0; x <= City.mapLength; x++)
            {
                for (int z = -City.farmLength; z <= City.mapLength; z++)
                {
                    if (bm.GetID(x, 63, z) == City.groundBlockID &&
                        bm.GetID(x, 64, z) == BlockInfo.Air.ID)
                    {
                        int FreeNeighbours = 0;
                        for (int xCheck = x - 1; xCheck <= x + 1; xCheck++)
                        {
                            for (int zCheck = z - 1; zCheck <= z + 1; zCheck++)
                            {
                                if (bm.GetID(xCheck, 63, zCheck) == City.groundBlockID &&
                                    bm.GetID(xCheck, 64, zCheck) == BlockInfo.Air.ID)
                                {
                                    FreeNeighbours++;
                                }
                            }
                        }
                        if (FreeNeighbours >= MinimumFreeNeighboursNeededForFlowers && RNG.NextDouble() * 100 <= City.flowerSpawnPercent)
                        {
                            AddFlowersToBlock(bm, x, z, FreeNeighbours, RNG.RandomItemFromArray(strFlowers));
                            if (++FlowerCount >= NumberOfFlowersBetweenSaves)
                            {
                                worldDest.Save();
                                FlowerCount = 0;
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 19
0
        static void Main(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine("Usage: flatmap <type> <target_dir>");
                Console.WriteLine("Available Types: alpha, beta, anvil");
                return;
            }

            string dest = args[1];
            int    xmin = -20;
            int    xmax = 20;
            int    zmin = -20;
            int    zmaz = 20;

            NbtVerifier.InvalidTagType += (e) =>
            {
                throw new Exception("Invalid Tag Type: " + e.TagName + " [" + e.Tag + "]");
            };
            NbtVerifier.InvalidTagValue += (e) =>
            {
                throw new Exception("Invalid Tag Value: " + e.TagName + " [" + e.Tag + "]");
            };
            NbtVerifier.MissingTag += (e) =>
            {
                throw new Exception("Missing Tag: " + e.TagName);
            };

            if (!Directory.Exists(dest))
            {
                Directory.CreateDirectory(dest);
            }

            // This will instantly create any necessary directory structure
            NbtWorld world;

            switch (args[0])
            {
            case "alpha": world = AlphaWorld.Create(dest); break;

            case "beta": world = BetaWorld.Create(dest); break;

            case "anvil": world = AnvilWorld.Create(dest); break;

            default: throw new Exception("Invalid world type specified.");
            }

            IChunkManager cm = world.GetChunkManager();

            // We can set different world parameters
            world.Level.LevelName = "Flatlands";
            world.Level.Spawn     = new SpawnPoint(20, 70, 20);

            // world.Level.SetDefaultPlayer();
            // We'll let MC create the player for us, but you could use the above
            // line to create the SSP player entry in level.dat.

            // We'll create chunks at chunk coordinates xmin,zmin to xmax,zmax
            for (int xi = xmin; xi < xmax; xi++)
            {
                for (int zi = zmin; zi < zmaz; zi++)
                {
                    // This line will create a default empty chunk, and create a
                    // backing region file if necessary (which will immediately be
                    // written to disk)
                    ChunkRef chunk = cm.CreateChunk(xi, zi);

                    // This will suppress generating caves, ores, and all those
                    // other goodies.
                    chunk.IsTerrainPopulated = true;

                    // Auto light recalculation is horrifically bad for creating
                    // chunks from scratch, because we're placing thousands
                    // of blocks.  Turn it off.
                    chunk.Blocks.AutoLight = false;

                    // Set the blocks
                    FlatChunk(chunk, 64);

                    // Reset and rebuild the lighting for the entire chunk at once
                    chunk.Blocks.RebuildHeightMap();
                    chunk.Blocks.RebuildBlockLight();
                    chunk.Blocks.RebuildSkyLight();

                    Console.WriteLine("Built Chunk {0},{1}", chunk.X, chunk.Z);

                    // Save the chunk to disk so it doesn't hang around in RAM
                    cm.Save();
                }
            }

            // Save all remaining data (including a default level.dat)
            // If we didn't save chunks earlier, they would be saved here
            world.Save();
        }
Ejemplo n.º 20
0
        static public void Generate(frmMace frmLogForm, string UserWorldName, string strWorldSeed,
                                    string strWorldType, bool booWorldMapFeatures, int TotalCities, string[] strCheckedThemes,
                                    int ChunksBetweenCities, string strSpawnPoint, bool booExportSchematics,
                                    string strSelectedNPCs, string strUndergroundOres)
        {
            frmLogForm.UpdateLog("Started at " + DateTime.Now.ToLocalTime(), false, true);

            worldCities = new WorldCity[TotalCities];
            lstCityNames.Clear();
            Chunks.biomes.Clear();

            RNG.SetRandomSeed();

            #region create minecraft world directory from a random unused world name
            string strFolder = String.Empty, strWorldName = String.Empty;

            UserWorldName = UserWorldName.ToSafeFilename();
            if (UserWorldName.Trim().Length == 0)
            {
                UserWorldName = "random";
            }

            if (UserWorldName.ToLower().Trim() != "random")
            {
                if (Directory.Exists(UserWorldName.ToMinecraftSaveDirectory()))
                {
                    if (MessageBox.Show("A world called \"" + UserWorldName + "\" already exists. " +
                                        "Would you like to use a random name instead?", "World already exists",
                                        MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
                    {
                        frmLogForm.UpdateLog("Cancelled, because a world with this name already exists.", false, false);
                        return;
                    }
                }
                else
                {
                    strWorldName = UserWorldName;
                    strFolder    = strWorldName.ToMinecraftSaveDirectory();
                }
            }
            if (strWorldName.Length == 0)
            {
                strWorldName = Utils.GenerateWorldName();
                strFolder    = strWorldName.ToMinecraftSaveDirectory();
            }
            Directory.CreateDirectory(strFolder);
            frmLogForm.btnSaveLogNormal.Tag  = Path.Combine(strFolder, "LogNormal.txt");
            frmLogForm.btnSaveLogVerbose.Tag = Path.Combine(strFolder, "LogVerbose.txt");
            frmLogForm.UpdateLog("World name: " + strWorldName, false, true);
            #endregion

            #region get handles to world, chunk manager and block manager
            AnvilWorld worldDest = AnvilWorld.Create(@strFolder);
            worldDest.Level.LevelName = "Creating. Don't open until Mace is finished.";
            RegionChunkManager cmDest = worldDest.GetChunkManager();
            BlockManager       bmDest = worldDest.GetBlockManager();
            bmDest.AutoLight = false;
            #endregion

            #region Determine themes
            // "how does this work, robson?"
            // well, I'm glad you asked!
            // we keep selecting a random unused checked theme, until they've all been used once.
            // after that, all other cities will have a random checked theme

            int maxFarmSize = 0;

            strCheckedThemes = RNG.ShuffleArray(strCheckedThemes);
            for (int CurrentCityID = 0; CurrentCityID < TotalCities; CurrentCityID++)
            {
                if (CurrentCityID <= strCheckedThemes.GetUpperBound(0))
                {
                    worldCities[CurrentCityID].ThemeName = strCheckedThemes[CurrentCityID];
                }
                else
                {
                    worldCities[CurrentCityID].ThemeName = RNG.RandomItem(strCheckedThemes);
                }
                City.themeName = worldCities[CurrentCityID].ThemeName;
                worldCities[CurrentCityID].ChunkLength = GetThemeRandomXMLElementNumber("options", "city_size");
                int farmSize = GetThemeLastXMLElementNumber("options", "farm_size");
                maxFarmSize = Math.Max(maxFarmSize, farmSize);
            }
            #endregion

            GenerateCityLocations(TotalCities, ChunksBetweenCities + maxFarmSize);

            int intRandomCity = RNG.Next(TotalCities);

            for (int CurrentCityID = 0; CurrentCityID < TotalCities; CurrentCityID++)
            {
                MakeCitySettings(frmLogForm, worldCities[CurrentCityID].ThemeName, CurrentCityID, strSelectedNPCs);
                if (!GenerateCity.Generate(frmLogForm, worldDest, cmDest, bmDest, worldCities[CurrentCityID].x, worldCities[CurrentCityID].z, booExportSchematics, strUndergroundOres))
                {
                    frmLogForm.UpdateLog("World generation failed/cancelled.", false, false);
                    return;
                }
                #region set spawn point
                if (City.id == intRandomCity)
                {
                    switch (strSpawnPoint)
                    {
                    case "Away from the cities":
                        worldDest.Level.Spawn = new SpawnPoint(0, 65, 0);
                        break;

                    case "Inside a random city":
                        worldDest.Level.Spawn = new SpawnPoint(((worldCities[intRandomCity].x + Chunks.CITY_RELOCATION_CHUNKS) * 16) + (City.mapLength / 2),
                                                               65,
                                                               ((worldCities[intRandomCity].z + Chunks.CITY_RELOCATION_CHUNKS) * 16) + (City.mapLength / 2));
                        break;

                    case "Outside a random city":
                        worldDest.Level.Spawn = new SpawnPoint(((worldCities[intRandomCity].x + Chunks.CITY_RELOCATION_CHUNKS) * 16) + (City.mapLength / 2),
                                                               65,
                                                               ((worldCities[intRandomCity].z + Chunks.CITY_RELOCATION_CHUNKS) * 16) + 2);
                        break;

                    default:
                        Debug.Fail("invalid spawn point");
                        break;
                    }
                    frmLogForm.UpdateLog("Spawn point set to " + worldDest.Level.Spawn.X + "," + worldDest.Level.Spawn.Y + "," + worldDest.Level.Spawn.Z, false, true);
                }
                #endregion
            }

            #region weather
            frmLogForm.UpdateLog("Setting weather", false, true);
            worldDest.Level.Time = RNG.Next(24000);
            if (RNG.NextDouble() < 0.15)
            {
                frmLogForm.UpdateLog("Rain", false, true);
                worldDest.Level.IsRaining = true;
                // one-quarter to three-quarters of a day
                worldDest.Level.RainTime = RNG.Next(6000, 18000);
                if (RNG.NextDouble() < 0.25)
                {
                    frmLogForm.UpdateLog("Thunder", false, true);
                    worldDest.Level.IsThundering = true;
                    worldDest.Level.ThunderTime  = worldDest.Level.RainTime;
                }
            }
            #endregion

            #region world details
            worldDest.Level.LevelName = strWorldName;
            frmLogForm.UpdateLog("Setting world type: " + strWorldType, false, true);
            switch (strWorldType.ToLower())
            {
            case "creative":
                worldDest.Level.GameType = GameType.CREATIVE;
                break;

            case "survival":
                worldDest.Level.GameType = GameType.SURVIVAL;
                break;

            case "hardcore":
                worldDest.Level.GameType = GameType.SURVIVAL;
                worldDest.Level.Hardcore = true;
                break;

            default:
                Debug.Fail("Invalidate world type selected.");
                break;
            }
            frmLogForm.UpdateLog("World map features: " + booWorldMapFeatures.ToString(), false, true);
            worldDest.Level.UseMapFeatures = booWorldMapFeatures;
            if (strWorldSeed != String.Empty)
            {
                long seed = 0;
                if (long.TryParse(strWorldSeed, out seed))
                {
                    worldDest.Level.RandomSeed = seed;
                    frmLogForm.UpdateLog("Specified world seed: " + worldDest.Level.RandomSeed, false, true);
                }
                else
                {
                    worldDest.Level.RandomSeed = strWorldSeed.ToJavaHashCode();
                    frmLogForm.UpdateLog("Specified world seed: " + strWorldSeed, false, true);
                    frmLogForm.UpdateLog("Specified world seed converted to a number: " + worldDest.Level.RandomSeed, false, true);
                }
            }
            else
            {
                worldDest.Level.RandomSeed = RNG.Next();
                frmLogForm.UpdateLog("Random world seed: " + worldDest.Level.RandomSeed, false, true);
            }
            worldDest.Level.LastPlayed = (DateTime.UtcNow.Ticks - DateTime.Parse("01/01/1970 00:00:00").Ticks) / 10000;
            frmLogForm.UpdateLog("World time: " + worldDest.Level.LastPlayed, false, true);
            #endregion

            cmDest.Save();
            worldDest.Save();

            Chunks.SetBiomeData(@strFolder);

            frmLogForm.UpdateLog("\nCreated the " + strWorldName + "!", false, false);
            frmLogForm.UpdateLog("It'll be at the top of your MineCraft world list.", false, false);

            frmLogForm.UpdateLog("Finished at " + DateTime.Now.ToLocalTime(), false, true);
        }
Ejemplo n.º 21
0
        public static void openFile(Form plcType,
                                    Form main,
                                    ComboBox height,
                                    ToolStripProgressBar mLoad,
                                    ToolStripStatusLabel mStatus)
        {
            bool           noFile = true, cancel = false;
            OpenFileDialog openDiag;
            DialogResult   res;
            String         filename;

            mnuHeight = height;
            mnuLoad   = mLoad;
            mnuStatus = mStatus;
            init      = true;

            plcType.Hide();

            while (noFile ^ cancel)
            {
                openDiag              = new OpenFileDialog();
                openDiag.Multiselect  = false;
                openDiag.AddExtension = true;
                openDiag.DefaultExt   = "dat";
                openDiag.Filter       = "Minecraft Levels (*.dat)|*.dat|" +
                                        "All Files (*.*)|*.*";

                res = openDiag.ShowDialog();

                plcType.Show();

                if (res == DialogResult.Cancel)
                {
                    cancel = true;
                }

                else
                {
                    filename = openDiag.FileName;

                    noFile = false;
                    openDiag.Dispose();

                    lvl = AnvilWorld.Open(filename);

                    if (lvl == null)
                    {
                        MessageBox.Show("That file was not a compatible Minecraft level.",
                                        "Open File Error",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                    }

                    else
                    {
                        regDiag = new SelectRegion(lvl.GetRegionManager(), main);
                        loadLimits();
                        selectRegion(true);
                    }
                }
            }
        }
Ejemplo n.º 22
0
        public static void MakeWalls(AnvilWorld world, frmMace frmLogForm)
        {
            // walls
            for (int a = City.edgeLength + 6; a <= City.edgeLength + 10; a++)
            {
                BlockShapes.MakeHollowLayers(a, City.mapLength - a, 1, 72, a, City.mapLength - a,
                                             City.wallMaterialID, 0, City.wallMaterialData);
                world.Save();
            }
            // outside and inside edges at the top
            BlockShapes.MakeHollowLayers(City.edgeLength + 5, City.mapLength - (City.edgeLength + 5), 72, 73,
                                         City.edgeLength + 5, City.mapLength - (City.edgeLength + 5),
                                         City.wallMaterialID, 0, City.wallMaterialData);
            BlockShapes.MakeHollowLayers(City.edgeLength + 11, City.mapLength - (City.edgeLength + 11), 72, 73,
                                         City.edgeLength + 11, City.mapLength - (City.edgeLength + 11),
                                         City.wallMaterialID, 0, City.wallMaterialData);
            // alternating blocks on top of the edges
            for (int a = City.edgeLength + 6; a <= City.mapLength - (City.edgeLength + 6); a += 2)
            {
                BlockShapes.MakeBlock(a, 74, City.edgeLength + 5, City.wallMaterialID, 2, 100, City.wallMaterialData);
            }
            for (int a = City.edgeLength + 12; a <= City.mapLength - (City.edgeLength + 12); a += 2)
            {
                BlockShapes.MakeBlock(a, 74, City.edgeLength + 11, City.wallMaterialID, 2, 100, City.wallMaterialData);
            }
            // ladder
            BlockHelper.MakeLadder((City.mapLength / 2) - 5, 64, 72, City.edgeLength + 11, 2, City.wallMaterialID);

            BlockShapes.MakeSolidBox((City.mapLength / 2) - 5, (City.mapLength / 2) + 5,
                                     65, 74,
                                     City.edgeLength + 11, City.edgeLength + 11,
                                     BlockInfo.Air.ID, 2);

            // decorations at the gates
            frmLogForm.UpdateLog("Creating wall lights: " + City.outsideLightType, true, true);
            switch (City.outsideLightType)
            {
            case "Fire":
                // fire above the entrances
                BlockShapes.MakeBlock((City.mapLength / 2) - 1, 69, City.edgeLength + 5, BlockInfo.Netherrack.ID, 2, 100, -1);
                BlockShapes.MakeBlock((City.mapLength / 2), 69, City.edgeLength + 5, BlockInfo.Netherrack.ID, 2, 100, -1);
                BlockShapes.MakeBlock((City.mapLength / 2) - 1, 70, City.edgeLength + 5, BlockInfo.Fire.ID, 2, 100, -1);
                BlockShapes.MakeBlock((City.mapLength / 2), 70, City.edgeLength + 5, BlockInfo.Fire.ID, 2, 100, -1);
                // fire on the outside walls
                for (int a = City.edgeLength + 8; a < (City.mapLength / 2) - 9; a += 4)
                {
                    BlockShapes.MakeBlock(a, 69, City.edgeLength + 5, BlockInfo.Netherrack.ID, 2, 100, -1);
                    BlockShapes.MakeBlock(a, 70, City.edgeLength + 5, BlockInfo.Fire.ID, 2, 100, -1);
                }
                break;

            case "Torches":
                // torches above the entrances
                BlockHelper.MakeTorch((City.mapLength / 2), 70, City.edgeLength + 5, City.wallMaterialID, 2);
                BlockHelper.MakeTorch((City.mapLength / 2) - 1, 70, City.edgeLength + 5, City.wallMaterialID, 2);
                // torches on the outside walls
                for (int a = City.edgeLength + 8; a < (City.mapLength / 2) - 9; a += 4)
                {
                    BlockHelper.MakeTorch(a, 70, City.edgeLength + 5, City.wallMaterialID, 2);
                }
                break;

            case "None":
            case "":
                break;

            default:
                Debug.Fail("Invalid switch result");
                break;
            }
            if (City.hasTorchesOnWalkways)
            {
                // torches on the inside walls
                for (int a = City.edgeLength + 16; a < (City.mapLength / 2); a += 4)
                {
                    BlockHelper.MakeTorch(a, 69, City.edgeLength + 11, City.wallMaterialID, 2);
                }
                // torches on the wall roofs
                for (int a = City.edgeLength + 16; a < (City.mapLength / 2); a += 4)
                {
                    BlockShapes.MakeBlock(a, 73, City.edgeLength + 8, BlockInfo.Torch.ID, 2, 100, -1);
                }
            }


            for (int a = City.edgeLength + 16; a < (City.mapLength / 2); a += 24)
            {
                switch (City.npcs)
                {
                case "Ghostdancer's NPCs":
                    EntityVillager eVillager;
                    eVillager        = new EntityVillager(new TypedEntity("GKnight"));
                    eVillager.Health = 20;
                    BlockShapes.MakeEntity(a, 73, City.edgeLength + 8, eVillager, 2);
                    break;

                case "Minecraft Villagers":
                    EntityMob eMob;
                    eMob        = new EntityMob(new TypedEntity("VillagerGolem"));
                    eMob.Health = 100;
                    BlockShapes.MakeEntity(a, 73, City.edgeLength + 8, eMob, 2);
                    break;
                }
            }

            frmLogForm.UpdateLog("Creating wall emblems: " + City.cityEmblemType, true, true);
            MakeEmblem();
        }
Ejemplo n.º 23
0
 private void Measure(AnvilWorld World)
 {
     Measure(World.GetChunkManager(Dimension));
 }
Ejemplo n.º 24
0
        static void Main(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine("Usage: eina_to_nbt <source> <dest>");
                return;
            }

            String dest = args[1];

            System.Console.WriteLine("Creating EINA map...");

            if (!Directory.Exists(dest))
            {
                Directory.CreateDirectory(dest);
            }


            NbtWorld world = AnvilWorld.Create(dest);

            world.Level.LevelName   = "EINA";
            world.Level.Spawn       = new SpawnPoint(292, 70, 270);
            world.Level.GameType    = GameType.CREATIVE;
            world.Level.Initialized = true;


            Player p = new Player();

            p.Position.X = 292;
            p.Position.Y = 130;
            p.Position.Z = 292;



            IPlayerManager pm = world.GetPlayerManager();

            pm.SetPlayer("Player", p);


            IChunkManager cm = world.GetChunkManager();


            string[] lines = System.IO.File.ReadAllLines(args[0]);

            string[] words;



            ChunkRef chunk;


            words = lines[0].Split(' ');
            int minx = Int32.Parse(words[0]);
            int maxx = Int32.Parse(words[0]);
            int miny = Int32.Parse(words[0]);
            int maxy = Int32.Parse(words[0]);

            for (int i = 0; i < lines.Length; i++)
            {
                words = lines[i].Split(' ');
                //System.Console.WriteLine(lines[i]);
                int x     = Int32.Parse(words[0]);
                int y     = Int32.Parse(words[1]);
                int z     = Int32.Parse(words[2]);
                int color = Int32.Parse(words[3]);

                string text = "";



                if (words.Length > 4)
                {
                    text = words[4];
                    for (int j = 5; j < words.Length; j++)
                    {
                        text += ' ' + words[j];
                    }
                }
                else
                {
                    text = "";
                }


                int xLocal = x / 16;
                int yLocal = y / 16;

                if (xLocal < minx)
                {
                    minx = xLocal;
                }
                if (xLocal > maxx)
                {
                    maxx = xLocal;
                }
                if (yLocal < miny)
                {
                    miny = yLocal;
                }
                if (yLocal > maxy)
                {
                    maxy = yLocal;
                }

                if (!cm.ChunkExists(xLocal, yLocal))
                {
                    //System.Console.WriteLine(xLocal+"  "+yLocal);
                    cm.CreateChunk(xLocal, yLocal);
                }
                chunk = cm.GetChunkRef(xLocal, yLocal);
                //System.Console.WriteLine(x+"  "+y+"   "+z);
                //System.Console.WriteLine(xLocal+"  "+yLocal);

                if (!chunk.IsDirty)
                {
                    chunk.IsTerrainPopulated = true;
                    chunk.Blocks.AutoLight   = false;
                    //FlatChunk(chunk, 64);
                    chunk.Blocks.RebuildHeightMap();
                    chunk.Blocks.RebuildBlockLight();
                    chunk.Blocks.RebuildSkyLight();
                    //System.Console.WriteLine(chunk.IsDirty);

                    for (int i2 = 0; i2 < 16; i2++)
                    {
                        for (int j = 0; j < 16; j++)
                        {
                            setBlock(chunk, i2, 64, j, 16, "");
                        }
                    }
                    if (((xLocal % 8) == 0) & ((yLocal % 8) == 0))
                    {
                        cm.Save();
                    }

                    setBlock(chunk, x % 16, z + 64, y % 16, color, text);
                }
                else
                {
                    setBlock(chunk, x % 16, z + 64, y % 16, color, text);
                    //System.Console.WriteLine("hola");
                }
                if ((i + 1) % 500000 == 0)
                {
                    System.Console.WriteLine("Guardando");
                    world.Save();
                    //System.Console.WriteLine("Hecho");
                }
            }



            world.Save();
        }
Ejemplo n.º 25
0
        static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine("Usage: BlockReplace <world> <jsonFile>");
                return;
            }

            StreamReader streamReader = new StreamReader(args [1]);
            string       json         = streamReader.ReadToEnd();

            streamReader.Close();

            JObject o = JObject.Parse(json);


            IList <int> elevations = o.SelectToken("elevation-flat").Select(s => (int)s).ToList();

            Console.WriteLine("Load Elevations...");
            string dest = args [0];

            AnvilWorld   world = AnvilWorld.Open(dest);
            BlockManager bm    = world.GetBlockManager();

            bm.AutoLight = true;


            // Set Elevations
            int i = 0;

            while (i < elevations.Count)
            {
                if (i % 100 == 0)
                {
                    //RegionChunkManager cm = world.GetChunkManager();
                    //cm.RelightDirtyChunks();
                }
                int el = elevations[i];
                int x  = i / 1001 | 0;
                int y  = i % 1001;
                x  = 1001 - x; // Symetry
                x -= 500;
                y -= 500;

                bm.SetID(x, el, y, (int)BlockType.GRASS);

                if (el > 1)
                {
                    bm.SetID(x, el - 1, y, (int)BlockType.DIRT);
                }
                if (el > 2)
                {
                    bm.SetID(x, el - 2, y, (int)BlockType.DIRT);
                }
                if (el > 3)
                {
                    bm.SetID(x, el - 3, y, (int)BlockType.DIRT);
                }
                if (el > 4)
                {
                    bm.SetID(x, el - 4, y, (int)BlockType.DIRT);
                }
                ++i;
            }

            Console.WriteLine("Load Mods...");
            IList <int> mods = o.SelectToken("mods").Select(s => (int)s).ToList();

            Console.WriteLine(mods.Count);
            i = 0;
            while (i < mods.Count - 4)
            {
                int x = (int)mods [i++];
                int y = (int)mods [i++];
                int z = (int)mods [i++];
                int t = (int)mods [i++];

                if (t > 126)
                {
                    Console.WriteLine("Failed");
                    Console.WriteLine(t);
                    Console.WriteLine(x);
                    Console.WriteLine(y);
                    Console.WriteLine(z);
                    continue;
                }

                x = 1001 - x; // Symetry

                x -= 500;
                y -= 500;
                // Check if valid block
                if (t < 256 && z > 0 && z <= 255)
                {
                    bm.SetID(x, z, y, t);
                }
            }
            Console.WriteLine("over generation");

            world.Save();
        }
        public World ConvertWorld(String mcDirectory)
        {
            String segmentDirectory = Path.Combine(FCEDirectory, "Segments");

            if (!Directory.Exists(FCEDirectory))
            {
                Directory.CreateDirectory(FCEDirectory);
            }
            if (!Directory.Exists(Path.Combine(FCEDirectory, segmentDirectory)))
            {
                Directory.CreateDirectory(segmentDirectory);
            }

            Boolean anvil = true;

            NbtWorld      nbtWorld     = AnvilWorld.Open(mcDirectory);
            String        worldName    = nbtWorld.Level.LevelName;
            IChunkManager chunkManager = nbtWorld.GetChunkManager();

            try
            {
                // Try to test for mc world type
                // Don't know how this is supposed to work, but it presumably throws an exception
                // on a non-Anvil world.
                chunkManager.Count();
            }
            catch
            {
                anvil        = false;
                nbtWorld     = BetaWorld.Open(mcDirectory);
                worldName    = nbtWorld.Level.LevelName;
                chunkManager = nbtWorld.GetChunkManager();
            }
            Int32 spawnChunkX = nbtWorld.Level.Spawn.X >> 4;
            Int32 spawnChunkZ = nbtWorld.Level.Spawn.Z >> 4;

            WorldSettings settings = new WorldSettings();

            settings.Name = worldName;
            var fceWorld       = World.Create(FCEDirectory, settings);
            var segmentManager = fceWorld.SegmentManager;

            _totalSegments = chunkManager.LongCount() * (anvil ? 16 : 8);
            _segmentsLeft  = _totalSegments;
            StartSaveThread(fceWorld);
            foreach (ChunkRef chunk in chunkManager)
            {
                // If the save thread is too slow, wait until it has caught up before adding to it to prevent high ram usage
                while (_saveQueue.Count > 5000)
                {
                    Thread.Sleep(500);
                }

                if (chunk.Blocks == null)
                {
                    _segmentsLeft -= (anvil ? 16 : 8);
                    continue;
                }

                Int32 spawnOffsetX = UseSpawnAsOrigin ? spawnChunkX - chunk.X : -chunk.X;
                Int32 spawnOffsetZ = UseSpawnAsOrigin ? spawnChunkZ - chunk.Z : -chunk.Z;

                // Minecraft has different x/y directions so we must reverse z so the world isn't mirrored
                var chunkCoords = new SegmentCoords(spawnOffsetX, 0, -spawnOffsetZ) + SegmentCoords.WorldCenter;
                for (Int32 i = 0; i < (anvil ? 16 : 8); i++)
                {
                    SegmentCoords segCoords = chunkCoords + SegmentCoords.Above * i;
                    var           segment   = new Segment(segmentManager, segCoords);
                    var           array     = new Cube[16, 16, 16];
                    for (Byte x = 0; x < 16; x++)
                    {
                        for (Byte y = 0; y < 16; y++)
                        {
                            for (Byte z = 0; z < 16; z++)
                            {
                                // Minecraft has different x/y directions so we must reverse z so the world isn't mirrored
                                AlphaBlock block    = chunk.Blocks.GetBlock(15 - z, y + i * 16, x);
                                UInt32     mcIdData = (UInt32)block.ID << 16 | (UInt16)block.Data;

                                Cube cube;
                                if (!_mcIdDataToFCECube.TryGetValue(mcIdData, out cube))
                                {
                                    cube = new Cube(1, 0, 0, 0);
                                    if (!UnknownBlocks.ContainsKey((UInt16)block.ID))
                                    {
                                        UnknownBlocks.Add((UInt16)block.ID, block.Info.Name);
                                    }
                                }
                                array[z, y, x] = cube;
                            }
                        }
                    }

                    segment.CubeData = array;
                    _segmentsLeft--;
                    _saveQueue.Enqueue(segment);
                }
                // Pad the area above the converted world with 11 blank segments to prevent world gen from occuring
                // Possibly replace this in the future with simply shifting the world up
                for (Int32 i = (anvil ? 16 : 8); i < 27; i++)
                {
                    var padding = new Segment(segmentManager, chunkCoords + SegmentCoords.Above * i);
                    padding.CubeData = Segment.GetBlankSegment().CubeData;
                    padding.IsEmpty  = true;
                    _saveQueue.Enqueue(padding);
                }
            }
            Task.WaitAll(_saveTask);

            return(fceWorld);
        }
Ejemplo n.º 27
0
        public int HandleCli(string[] Args)
        {
            _Configuration = new RenderConfiguration(_ColourPalette, _Metrics);

            // *** Function returns TRUE if the command line is invalid and the program should NOT proceed.
            if (HandleCommandLineArguments(Args))
            {
                return(0);
            }


            // *** World path is mandatory.
            if (_Configuration.WorldPath == "")
            {
                Console.WriteLine("A world must be specified.");
                ShowHelp();
                return(0);
            }

            // *** Load the world
            Console.WriteLine("Opening world file:");
            Console.WriteLine("    " + _Configuration.WorldPath + "...");
            AnvilWorld World;


            // *** Try and open the world.  If it fails, handle it gracefully
            try
            {
                World = AnvilWorld.Open(_Configuration.WorldPath);
            }
            catch (Exception Ex)
            {
                Console.WriteLine("World could not be opened for reading:");
                Console.WriteLine(Ex.ToString());
                Console.WriteLine("Please check that the world exists and is valid.");
                return(0);
            }


            // *** Read world and compute metrics (size, chunk count, more?)
            Console.WriteLine("Determining world boundaries");
            _StepTimer.Reset();
            _StepTimer.Start();
            _Metrics.Measure(World.GetChunkManager(_Configuration.Dimension));
            _StepTimer.Stop();
            Console.WriteLine("Took " + _StepTimer.Elapsed.ToString("m\\ms\\sff"));
            Console.WriteLine("Boundaries: (" + _Metrics.MinX.ToString() + ", " + _Metrics.MinZ.ToString() + ") to (" + _Metrics.MaxX.ToString() + ", " + _Metrics.MaxZ.ToString() + ")");


            // *** Render dimension, if applicable
            if (_Configuration.SaveFilename != "")
            {
                _StepTimer.Reset();
                _StepTimer.Start();

                // *** Load palettes.  Start with palettes in EXE directory, then append all palettes in the force-load list.
                Console.WriteLine("Loading Palettes...");
                // ReSharper disable once AssignNullToNotNullAttribute
                // *** It's probably safe to assume our EXE is gonna be in a folder.
                foreach (String PalFile in Directory.EnumerateFiles(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "*.pal").Concat(_LoadAdditionalPalettes))
                {
                    string PaletteFile = PalFile;

                    if (!PaletteFile.EndsWith(".pal") && !File.Exists(PaletteFile)) //Append ".pal" to filename if it's been accidentally omitted
                    {
                        PaletteFile += ".pal";
                    }

                    if (File.Exists(PaletteFile))
                    {
                        try
                        {
                            _ColourPalette.LoadPalette(PaletteFile);
                        }
                        catch (BlockPalette.PaletteExecutionException Ex)
                        {
                            Console.WriteLine(Ex.Message);
                        }
                        catch (Exception Ex)
                        {
                            Console.WriteLine("Failed to load palette " + Path.GetFileNameWithoutExtension(PaletteFile) + ":");
                            if (Ex is BlockPalette.PaletteExecutionException)
                            {
                                Console.WriteLine(Ex.Message);
                            }
                            else
                            {
                                Console.WriteLine("Internal Error");
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("Skipped missing file " + PaletteFile);
                    }
                }

                _ColourPalette.AssembleLookupTables();

                Console.WriteLine("Palettes loaded.  Took " + _StepTimer.Elapsed.ToString("m\\ms\\sff"));
                _StepTimer.Reset();

                _StepTimer.Start();
                _Renderer = new StandardRenderer();

                // *** Set up the progress indicator
                Console.WriteLine("Using " + (_Configuration.EnableMultithreading ? "multi-threaded" : "single-threaded") + " " + _Renderer.RendererFriendlyName);


                _Renderer.ProgressUpdate += OnRenderProgressUpdate;
                _Renderer.RenderError    += OnRenderError;

                _Configuration.Chunks = World.GetChunkManager(_Metrics.Dimension);
                if (!_Configuration.RenderSubregion)
                {
                    _Configuration.SubregionChunks = new Rectangle(_Metrics.MinX, _Metrics.MinZ, (_Metrics.MaxX - _Metrics.MinX), (_Metrics.MaxZ - _Metrics.MinZ));
                }
                _Renderer.Configure(_Configuration);
                _Renderer.Initialize();

                if (!_Renderer.IsAborting)
                {
                    _Renderer.Render();
                }

                _StepTimer.Stop();

                if (_Renderer.IsAborting)
                {
                    Console.WriteLine("\r\nMap export failed.");
                }
                else
                {
                    Console.WriteLine("\r\nMap export complete.  Took " + _StepTimer.Elapsed.ToString("m\\ms\\sff"));
                }
            }


            // *** Produce sign information file, if applicable
            if (_Configuration.ScanFilename != "")
            {
                _StepTimer.Reset();
                _StepTimer.Start();

                SignExporter Exporter = new SignExporter();
                Exporter.Process(World.GetChunkManager(_Metrics.Dimension), _Metrics, _Configuration.ScanFilename);

                _StepTimer.Stop();
                Console.WriteLine("Took " + _StepTimer.Elapsed.ToString("m\\ms\\sff"));
            }


            // *** Write world metrics, if applicable
            if (_Configuration.MetricsFilename != "")
            {
                WriteMetricsFile(World);
            }

#if DEBUG
            System.Threading.Thread.Sleep(5500); // *** If debug mode, pause at the end to give me time to read any messages
#endif
            return(0);
        }
Ejemplo n.º 28
0
        private static void GenerateScrf(GenerateOptions opts)
        {
            var world      = AnvilWorld.Open(opts.WorldPath);
            var donorWorld = AnvilWorld.Open(opts.OriginalPath);

            var dim          = opts.WorldDim;
            var manager      = world.GetChunkManager(dim).ToList();
            var donorManager = donorWorld.GetChunkManager(dim);

            var inputMap  = NbtMap.Load(Path.Combine(opts.OriginalPath, "cdfidmap.nbt"));
            var outputMap = NbtMap.Load(Path.Combine(opts.WorldPath, "cdfidmap.nbt"));

            var chunkBounds = new ChunkBounds(opts.ChunkBounds);

            if (!chunkBounds.BoundsExist)
            {
                Console.WriteLine("Input bounds not in the correct format");
                return;
            }

            var diff = new ScarifStructure(outputMap);

            Console.Clear();
            var cgui = new ConsoleGui();

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

            var lChunksTotal     = new ConsoleGuiLabel(0, 1, "Total Chunks    : {0}");
            var lChunksRemaining = new ConsoleGuiLabel(0, 2, "Remaining Chunks: {0}");
            var lStatus          = new ConsoleGuiLabel(0, 3, "Status          : {0}");

            var lChunksProcessed = new ConsoleGuiLabel(Console.WindowWidth / 2, 1, "Processed Chunks : {0}");
            var lChunksSkipped   = new ConsoleGuiLabel(Console.WindowWidth / 2, 2, "Skipped Chunks   : {0}");
            var lChunksDiffed    = new ConsoleGuiLabel(Console.WindowWidth / 2, 3, "Diffed Chunks    : {0}");
            var lBlocksDiffed    = new ConsoleGuiLabel(Console.WindowWidth / 2, 4, "Diffed Blocks    : {0}");
            var lTilesDiffed     = new ConsoleGuiLabel(Console.WindowWidth / 2, 5, "Diffed TEs       : {0}");

            cgui.Add(pbChunks);

            cgui.Add(lChunksTotal);
            cgui.Add(lChunksRemaining);
            cgui.Add(lStatus);

            cgui.Add(lChunksProcessed);
            cgui.Add(lChunksSkipped);
            cgui.Add(lChunksDiffed);
            cgui.Add(lBlocksDiffed);
            cgui.Add(lTilesDiffed);

            var processedChunks = 0;
            var diffedChunks    = 0;
            var diffedBlocks    = 0;
            var diffedTiles     = 0;
            var skipped         = 0;

            lStatus.Value = "Processing...";

            for (var i = 1; i <= manager.Count; i++)
            {
                var chunk = manager[i - 1];

                if (i > 1)
                {
                    manager[i - 2] = null;
                }

                pbChunks.Value = (float)i / manager.Count;

                if (!donorManager.ChunkExists(chunk.X, chunk.Z) || !chunkBounds.CoarseContains(chunk))
                {
                    skipped++;
                    continue;
                }

                processedChunks++;

                var pos        = new ChunkPosition(chunk.X, chunk.Z);
                var otherChunk = donorManager.GetChunk(chunk.X, chunk.Z);

                var numBlocksBefore = diffedBlocks;
                for (var y = 0; y < 256; y++)
                {
                    for (var x = 0; x < 16; x++)
                    {
                        for (var z = 0; z < 16; z++)
                        {
                            if (!chunkBounds.Contains(chunk.X * 16 + x, y, chunk.Z * 16 + z))
                            {
                                continue;
                            }

                            var     blockId   = (short)chunk.Blocks.GetID(x, y, z);
                            var     blockData = chunk.Blocks.GetData(x, y, z);
                            NbtTree nbt       = null;
                            var     te        = chunk.Blocks.GetTileEntity(x, y, z);
                            if (te != null)
                            {
                                nbt = new NbtTree(te.Source, "tile");
                            }

                            var     blockIdOriginal   = (short)otherChunk.Blocks.GetID(x, y, z);
                            var     blockDataOriginal = otherChunk.Blocks.GetData(x, y, z);
                            NbtTree nbtOriginal       = null;
                            var     teOriginal        = otherChunk.Blocks.GetTileEntity(x, y, z);
                            if (teOriginal != null)
                            {
                                nbtOriginal = new NbtTree(teOriginal.Source, "tile");
                            }

                            if (!inputMap.ContainsKey(blockIdOriginal) || !outputMap.ContainsKey(blockId))
                            {
                                continue;
                            }

                            if (inputMap[blockIdOriginal] == outputMap[blockId] && blockDataOriginal == blockData && nbtOriginal == nbt)
                            {
                                continue;
                            }

                            if (nbtOriginal != nbt)
                            {
                                diffedTiles++;
                            }

                            diffedBlocks++;
                            diff.Add(pos, new BlockPosition(x, y, z), new ScarifBlock(blockId, blockData, nbt));
                        }
                    }
                }

                if (diffedBlocks != numBlocksBefore)
                {
                    diffedChunks++;
                }

                lChunksTotal.Value     = i.ToString("N0");
                lChunksRemaining.Value = (manager.Count - i).ToString("N0");

                lChunksProcessed.Value = processedChunks.ToString("N0");
                lBlocksDiffed.Value    = diffedBlocks.ToString("N0");
                lTilesDiffed.Value     = diffedTiles.ToString("N0");
                lChunksDiffed.Value    = diffedChunks.ToString("N0");
                lChunksSkipped.Value   = skipped.ToString("N0");

                cgui.Render();
            }

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

            diff.Save(opts.DiffOutput);

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

            Console.ReadKey();
        }
Ejemplo n.º 29
0
        public static void ResetLighting(AnvilWorld world, RegionChunkManager cm, frmMace frmLogForm)
        {
            int intChunksProcessed = 0, intTotalChunks = 0;

            //this code is based on a Substrate example
            //http://code.google.com/p/substrate-minecraft/source/browse/trunk/Substrate/SubstrateCS/Examples/Relight/Program.cs
            //see the <License Substrate.txt> file for copyright information
            foreach (ChunkRef chunk in cm)
            {
                if (chunk.IsTerrainPopulated)
                {
                    if (chunk.X * 16 >= 0 &&
                        chunk.X * 16 <= City.mapLength &&
                        chunk.Z * 16 >= -City.farmLength &&
                        chunk.Z * 16 <= City.mapLength)
                    {
                        // we process each chunk twice, hence this:
                        intTotalChunks += 2;
                    }
                }
            }
            foreach (ChunkRef chunk in cm)
            {
                if (chunk.IsTerrainPopulated)
                {
                    if (chunk.X * 16 >= 0 &&
                        chunk.X * 16 <= City.mapLength &&
                        chunk.Z * 16 >= -City.farmLength &&
                        chunk.Z * 16 <= City.mapLength)
                    {
                        try
                        {
                            chunk.Blocks.RebuildHeightMap();
                            chunk.Blocks.ResetBlockLight();
                            chunk.Blocks.ResetSkyLight();
                        }
                        catch (Exception)
                        {
                            Debug.WriteLine("Chunk reset light fail");
                        }
                        if (++intChunksProcessed % 10 == 0)
                        {
                            cm.Save();
                            frmLogForm.UpdateProgress(0.5 + (intChunksProcessed * 0.45 / intTotalChunks));
                        }
                    }
                }
            }
            foreach (ChunkRef chunk in cm)
            {
                if (chunk.IsTerrainPopulated)
                {
                    if (chunk.X * 16 >= 0 &&
                        chunk.X * 16 <= City.mapLength &&
                        chunk.Z * 16 >= -City.farmLength &&
                        chunk.Z * 16 <= City.mapLength)
                    {
                        try
                        {
                            chunk.Blocks.RebuildBlockLight();
                            chunk.Blocks.RebuildSkyLight();
                        }
                        catch (Exception)
                        {
                            Debug.WriteLine("Chunk rebuild light fail");
                        }
                        if (++intChunksProcessed % 10 == 0)
                        {
                            cm.Save();
                            frmLogForm.UpdateProgress(0.5 + (intChunksProcessed * 0.45 / intTotalChunks));
                        }
                    }
                }
            }
            world.Save();
        }
Ejemplo n.º 30
0
        private void ExecuteOpenWorld(object Sender, EventArgs E)
        {
            DialogResult Result = fbOpenFolder.ShowDialog();

            // *** Open world, or at least try
            if (Result != DialogResult.OK)
            {
                return;
            }

            ToggleControls(false, false, false);

            _World = null;

            try
            {
                _World = AnvilWorld.Open(fbOpenFolder.SelectedPath);

                // *** Load Dimension list

                Regex ValidDimNames = new Regex(@"(?<Path>(?:DIM[^\-\d]*)?(?<Name>-?\d{1,}|region))$");

                cbDimension.Items.Clear();
                cbDimension.BeginUpdate();

                int UseIndex = -1;

                foreach (String S in Directory.GetDirectories(_World.Path))
                {
                    Match Match = ValidDimNames.Match(S);

                    if (!Match.Success)
                    {
                        continue;
                    }

                    DimensionListEntry Entry = new DimensionListEntry("Dimension " + Match.Groups["Name"].Value, Match.Groups["Path"].Value);

                    if (Match.Groups["Name"].Value == "region")
                    {
                        Entry.Name  = "Overworld";
                        Entry.Value = "";
                        UseIndex    = cbDimension.Items.Count;
                    }
                    else if (Match.Groups["Name"].Value == "-1")
                    {
                        Entry.Name = "The Nether";
                    }
                    else if (Match.Groups["Name"].Value == "1")
                    {
                        Entry.Name = "The End";
                    }
                    else if (Match.Groups["Path"].Value.Contains("_MYST"))
                    {
                        Entry.Name = "Mystcraft " + Entry.Name;
                    }
                    cbDimension.Items.Add(Entry);
                }
                cbDimension.SelectedIndex = UseIndex;
                cbDimension.EndUpdate();
                SetStatus(String.Format("Loaded {0}", _World.Level.LevelName));

                ToggleControls(false, true, false);

                return;
            }
            catch (FileNotFoundException)
            {
                MessageBox.Show(string.Format("The folder {0} does not appear to contain a valid Minecraft world", fbOpenFolder.SelectedPath), "Error Loading World", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
#if !DEBUG
            catch (Exception Ex)
            {
                MessageBox.Show(string.Format("Error - Could not load world:\r\n{1}\r\n({0})", Ex.Message, Ex.GetType().Name), "Error Loading World", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
#endif
            SetStatus("World load failed");
        }