private void textidTextbox_TextChanged(object sender, EventArgs e) { if (propertiesChangedFromForm == false) { byte result = 0; OverworldMap mapParent = scene.ow.allmaps[scene.ow.allmaps[scene.selectedMap].parent]; if (scene.ow.allmaps[scene.selectedMap].parent == 255) { mapParent = scene.ow.allmaps[scene.selectedMap]; } short msgid = 0; if (short.TryParse(textidTextbox.Text, NumberStyles.HexNumber, null, out msgid)) { mapParent.messageID = msgid; if (msgid < mainForm.textEditor.textListbox.Items.Count) { mainForm.textEditor.textListbox.SelectedIndex = msgid; } mainForm.textEditor.Refresh(); previewTextPicturebox.Size = new Size(340, 102); previewTextPicturebox.Visible = true; previewTextPicturebox.Refresh(); } } }
public static void GenerateOres(VoxelChunk Chunk, ChunkGeneratorSettings Settings) { for (int x = 0; x < VoxelConstants.ChunkSizeX; x++) { for (int z = 0; z < VoxelConstants.ChunkSizeZ; z++) { var overworldPosition = OverworldMap.WorldToOverworld(new Vector2(x + Chunk.Origin.X, z + Chunk.Origin.Z), Settings.Overworld.InstanceSettings.Origin); var normalizedHeight = NormalizeHeight(Settings.Overworld.Map.LinearInterpolate(overworldPosition, OverworldField.Height)); var height = MathFunctions.Clamp(normalizedHeight * Settings.WorldSizeInChunks.Y * VoxelConstants.ChunkSizeY, 0.0f, Settings.WorldSizeInChunks.Y * VoxelConstants.ChunkSizeY - 2); for (int y = 0; y < VoxelConstants.ChunkSizeY; y++) { if (Chunk.Origin.Y + y >= height) { break; } if (Chunk.Origin.Y + y == 0) { continue; } var v = Chunk.Manager.CreateVoxelHandle(new GlobalVoxelCoordinate(Chunk.Origin.X + x, Chunk.Origin.Y + y, Chunk.Origin.Z + z)); if (v.Sunlight) { continue; } foreach (var voxelType in Library.EnumerateVoxelTypes()) { if (voxelType.SpawnClusters) { if (Chunk.Origin.Y + y < voxelType.MinSpawnHeight) { continue; } if (Chunk.Origin.Y + y > voxelType.MaxSpawnHeight) { continue; } var vRand = new Random(voxelType.ID); var noiseVector = new Vector3(Chunk.Origin.X + x, Chunk.Origin.Y + y, Chunk.Origin.Z + z) * Settings.CaveNoiseScale * 2.0f; noiseVector += new Vector3(vRand.Next(0, 64), vRand.Next(0, 64), vRand.Next(0, 64)); var fade = 1.0f - ((Chunk.Origin.Y + y - voxelType.MinSpawnHeight) / voxelType.MaxSpawnHeight); var oreNoise = Settings.CaveNoise.GetValue(noiseVector.X, noiseVector.Y, noiseVector.Z); if (Math.Abs(oreNoise) < voxelType.Rarity * fade) { v.RawSetType(voxelType); } } } } } } }
//What do we need for a tile viewer? //Load Tile8 Gfx //Load Tile16 Data //Load Tile32 Data? private void TilesViewer_Load(object sender, EventArgs e) { Tile16[] tiles16 = TilesLoader.LoadTile16(rom); tiles32 = TilesLoader.LoadTiles32(rom); //Need to load map data map = new OverworldMap(rom, 0, tiles32); //allgfx16Ptr unsafe { byte *newPdata = (byte *)ZGraphics.allgfx16Ptr.ToPointer(); BitmapData bdata = b.LockBits(new Rectangle(0, 0, 128, 256), ImageLockMode.ReadWrite, PixelFormat.Format4bppIndexed); byte * pdata = (byte *)bdata.Scan0; int sheetPos = 0; for (int i = 0; i < 8; i++) { int d = 0; while (d < 2048) { byte mapByte = newPdata[d + (map.blocksets[i] * 2048)]; switch (i) { case 0: case 3: case 4: case 5: mapByte += 0x88; break; } pdata[d + (sheetPos * 2048)] = mapByte; d++; } sheetPos++; } b.UnlockBits(bdata); ColorPalette cp = b.Palette; for (int i = 0; i < 16; i++) { cp.Entries[i] = map.palettes[i + 32]; } b.Palette = cp; } //mainTilesDisplay.Image = b; //mainTilesDisplay.Refresh(); //Need to load Palette Map Data //Need to load Blockset Map Data //-> will be able to draw a tile at this point }
private static void Init() { //ShatteredWorld.Data.World.SetSeed(); var OverWorld = new OverworldMap(width, height); root = new SadConsole.ScrollingConsole(width, height, SadConsole.Global.FontDefault, new Microsoft.Xna.Framework.Rectangle(0, 0, width, height), OverWorld.OverWorld); root.MouseButtonClicked += Root_MouseButtonClicked; SadConsole.Global.CurrentScreen = root; }
public SCMain(List <Map> _maps, OverworldMap _overworldMap, NPCdata _npcdata, OwLocationData locations, FF1Rom _rom) { maps = _maps; overworldMap = _overworldMap; rom = _rom; npcdata = _npcdata; mapTileSets = new MapTileSets(rom); enter = new EnterTeleData(rom); tele = new NormTeleData(rom); exit = new ExitTeleData(rom); mapTileSets.LoadTable(); enter.LoadData(); tele.LoadData(); exit.LoadData(); for (int i = 0; i < 8; i++) { tileSets[i] = new SCTileSet(rom, (byte)i); } owtileset = new SCTileSet(rom, TileSet.OverworldIndex); Stopwatch w = Stopwatch.StartNew(); List <SCMap> tmpscmaps = new List <SCMap>(); //Parallel.ForEach(Enum.GetValues<MapId>(), mapid => ProcessMap(mapid, tmpscmaps)); foreach (var mapid in Enum.GetValues <MapId>()) { ProcessMap(mapid, tmpscmaps); } scmaps = tmpscmaps.ToDictionary(m => m.MapId); ComposeDungeons(); //SCCoords bridge = new SCCoords(0x98, 0x98); //SCCoords canal = new SCCoords(0x66, 0xA4); Overworld = new SCOwMap(overworldMap, SCMapCheckFlags.None, _rom, owtileset, enter, exit, locations.BridgeLocation, locations.CanalLocation); w.Stop(); }
public static void Generate(Overworld Overworld, bool ShowPolitics, Texture2D TerrainTexture, Texture2D FullTexture) { var colorData = new Color[Overworld.Width * Overworld.Height * 4 * 4]; var stride = Overworld.Width * 4; Overworld.Map.CreateTexture(Overworld.Natives, 4, colorData, Overworld.GenerationSettings.SeaLevel); OverworldMap.Smooth(4, Overworld.Width, Overworld.Height, colorData); Overworld.Map.ShadeHeight(4, colorData); TerrainTexture.SetData(colorData); // Draw political boundaries if (ShowPolitics) { for (var x = 0; x < Overworld.Width; ++x) { for (var y = 0; y < Overworld.Height; ++y) { var thisCell = Overworld.ColonyCells.GetCellAt(x, y); var rect = new Rectangle(x * 4, y * 4, 4, 4); if (EnumerateNeighbors(new Point(x, y)).Select(p => Overworld.ColonyCells.GetCellAt(p.X, p.Y)).Any(c => c == null || !Object.ReferenceEquals(c.Faction, thisCell.Faction))) { FillSolidRectangle(rect, colorData, thisCell.Faction.PrimaryColor, stride); } else { FillPoliticalRectangle(rect, colorData, thisCell.Faction.PrimaryColor, stride); } } } } foreach (var cell in Overworld.ColonyCells.EnumerateCells()) { DrawRectangle(new Rectangle(cell.Bounds.X * 4, cell.Bounds.Y * 4, cell.Bounds.Width * 4, cell.Bounds.Height * 4), colorData, Color.Black, stride); } var spawnRect = new Rectangle((int)Overworld.InstanceSettings.Origin.X * 4, (int)Overworld.InstanceSettings.Origin.Y * 4, Overworld.InstanceSettings.Cell.Bounds.Width * 4, Overworld.InstanceSettings.Cell.Bounds.Height * 4); DrawRectangle(spawnRect, colorData, Color.Red, stride); FullTexture.SetData(colorData); }
public static void DrawTiles(OverworldMap map) { GL.UseProgram(MapRenderer.TileShaderProgram); if (myShouldUpdateTilePosition) { GL.Uniform2(myTilePositionLocation, CameraX, CameraY); GL.Uniform1(myTileScaleLocation, CameraScale); myShouldUpdateTilePosition = false; } GL.ActiveTexture(TextureUnit.Texture0); myWorldMapTex.Bind(); map.VertexBuffer.RenderTiles(); ECheck(); }
public WorldMap(Vector2 size, OverworldMap map) : base(size) { myMap = map; Dictionary <UIButton, Dungeon> dungeonDict = new Dictionary <UIButton, Dungeon>(); foreach (Dungeon dungeon in GameClient.Overworld.Dungeons) { UIButton btn = new UIButton(new Vector2(20.0f, 20.0f)) { Position = new Vector2(dungeon.X / map.ChunkWidth * 16.0f + 62.0f, dungeon.Y / map.ChunkHeight * 16.0f - 2.0f), Colour = new Color4(241, 217, 169, 127), DisabledColour = new Color4(99, 46, 14, 127) }; btn.AddChild(new UISprite(dungeon.IconSprite) { Position = new Vector2(-2.0f, -2.0f) }); if (dungeon.DungeonClass.Name != "fort" && dungeon.DungeonClass.Name != "temple") { btn.Disable(); } dungeonDict.Add(btn, dungeon); btn.Click += delegate(object sender, MouseButtonEventArgs e) { if (DungeonSelected != null) { DungeonSelected(this, new DungeonSelectedEventArgs(dungeonDict[btn])); } }; AddChild(btn); } }
public SCOwMap(OverworldMap _map, SCMapCheckFlags cflags, FF1Rom _rom, SCTileSet _tileSet, EnterTeleData _enter, ExitTeleData _exit, SCCoords bridge, SCCoords canal) { CFlags = cflags; map = _map; rom = _rom; tileSet = _tileSet; enter = _enter; exit = _exit; Bridge = bridge; Canal = canal; ProcessTiles(); ProcessTeleporters(); ProcessSpecialPointOfInterests(); DoPathing(); ProcessPointsOfInterest(); FilterAreas(); }
public static void RunStats(MT19337 rng, IItemPlacementFlags flags, IncentiveData incentivesData, ItemShopSlot caravanItemLocation, OverworldMap overworldMap) { Dictionary <MapLocation, Tuple <List <MapChange>, AccessRequirement> > fullLocationRequirements = overworldMap.FullLocationRequirements; var placedItems = new List <IRewardSource>(); var treasurePool = ItemLocations.AllTreasures.Where(x => !x.IsUnused).Select(x => x.Item) .Concat(ItemLists.AllNonTreasureChestItems).ToList(); var requirementChecks = ItemLists.AllQuestItems.ToDictionary(x => x, x => 0); requirementChecks[Item.Ribbon] = 0; var requirementsToCheck = new List <Item> { Item.Crown, Item.Crystal, Item.Herb, Item.Tnt, Item.Adamant, Item.Slab, Item.Ruby, Item.Bottle, Item.Floater, Item.Ship, Item.Bridge, Item.Canal }; const int maxIterations = 255; var forcedIceCount = 0; var itemPlacementStats = ItemLists.AllQuestItems.ToDictionary(x => x, x => new List <int>()); itemPlacementStats[Item.Ribbon] = new List <int>(); var itemPlacementZones = ItemLists.AllQuestItems.ToDictionary(x => x, x => new List <string>()); itemPlacementZones[Item.Ribbon] = new List <string>(); long iterations = 0; var timeElapsed = new Stopwatch(); while (iterations < maxIterations) { iterations++; // When Enemy Status Shuffle is turned on Coneria is reduced to 11% chance with other shops spliting the remaining 89% var shopTownSelected = ItemShops.PickRandom(rng); var itemShopItem = new ItemShopSlot(ItemLocations.CaravanItemShop1.Address, $"{Enum.GetName(typeof(MapLocation), shopTownSelected)}Shop", shopTownSelected, Item.Bottle); timeElapsed.Start(); placedItems = ItemPlacement.PlaceSaneItems(rng, flags, incentivesData, treasurePool, itemShopItem, overworldMap); timeElapsed.Stop(); var outputIndexes = placedItems.ToLookup(x => x.Item, x => x); foreach (Item item in itemPlacementStats.Keys) { itemPlacementStats[item].AddRange(outputIndexes[item].Select(x => x.Address).ToList()); } var outputZones = placedItems .ToLookup(x => x.Item, x => Enum.GetName(typeof(MapLocation), x.MapLocation)); foreach (Item item in itemPlacementZones.Keys) { if (!outputZones[item].Any()) { continue; } itemPlacementZones[item].AddRange(outputZones[item]); } var matoyaShip = placedItems.Any(x => x.Address == ItemLocations.Matoya.Address && x.Item == Item.Ship); var crystalIceCave = placedItems.Any(x => x.Item == Item.Crystal && x.Address >= ItemLocations.IceCave1.Address && x.Address <= ItemLocations.IceCaveMajor.Address); var keyIceCave = placedItems.Any(x => x.Item == Item.Key && x.Address >= ItemLocations.IceCave1.Address && x.Address <= ItemLocations.IceCaveMajor.Address); var keyLockedCrystal = placedItems.Any(x => x.Item == Item.Crystal && x.AccessRequirement.HasFlag(AccessRequirement.Key)); var keyLockedShip = placedItems.Any(x => x.Item == Item.Ship && x.AccessRequirement.HasFlag(AccessRequirement.Key)); if ((keyLockedShip && keyIceCave) || (matoyaShip && crystalIceCave) || (matoyaShip && keyLockedCrystal && keyIceCave)) { forcedIceCount++; } foreach (Item item in requirementsToCheck) { if (!ItemPlacement.CheckSanity(placedItems.Where(x => x.Item != item).ToList(), fullLocationRequirements, new Flags { OnlyRequireGameIsBeatable = true })) { requirementChecks[item]++; } } } if (iterations > 10) { Debug.WriteLine(PrintStats(maxIterations, itemPlacementStats, itemPlacementZones, requirementChecks)); Debug.WriteLine($"Forced Early Ice Cave for Ship: {forcedIceCount} out of {maxIterations}"); Debug.WriteLine($"Time per iteration: {1.0 * timeElapsed.ElapsedMilliseconds / iterations}"); } }
private void gfxTextbox_TextChanged(object sender, EventArgs e) { if (propertiesChangedFromForm == false) { byte result = 0; OverworldMap mapParent = scene.ow.allmaps[scene.ow.allmaps[scene.selectedMap].parent]; if (scene.ow.allmaps[scene.selectedMap].parent == 255) { mapParent = scene.ow.allmaps[scene.selectedMap]; } if (byte.TryParse(paletteTextbox.Text, NumberStyles.HexNumber, null, out result)) { mapParent.palette = result; } if (byte.TryParse(gfxTextbox.Text, NumberStyles.HexNumber, null, out result)) { mapParent.gfx = result; } if (byte.TryParse(sprgfxTextbox.Text, NumberStyles.HexNumber, null, out result)) { if (mapParent.index >= 64) { mapParent.sprgfx[0] = result; } else { scene.ow.allmaps[mapParent.index].sprgfx[scene.ow.gameState] = result; } } if (byte.TryParse(sprpaletteTextbox.Text, NumberStyles.HexNumber, null, out result)) { if (mapParent.index >= 64) { mapParent.sprpalette[0] = result; } else { mapParent.sprpalette[scene.ow.gameState] = result; } } if (mapParent.largeMap) { scene.ow.allmaps[mapParent.index + 1].gfx = mapParent.gfx; scene.ow.allmaps[mapParent.index + 1].sprgfx = mapParent.sprgfx; scene.ow.allmaps[mapParent.index + 1].palette = mapParent.palette; scene.ow.allmaps[mapParent.index + 1].sprpalette = mapParent.sprpalette; scene.ow.allmaps[mapParent.index + 8].gfx = mapParent.gfx; scene.ow.allmaps[mapParent.index + 8].sprgfx = mapParent.sprgfx; scene.ow.allmaps[mapParent.index + 8].palette = mapParent.palette; scene.ow.allmaps[mapParent.index + 8].sprpalette = mapParent.sprpalette; scene.ow.allmaps[mapParent.index + 9].gfx = mapParent.gfx; scene.ow.allmaps[mapParent.index + 9].sprgfx = mapParent.sprgfx; scene.ow.allmaps[mapParent.index + 9].palette = mapParent.palette; scene.ow.allmaps[mapParent.index + 9].sprpalette = mapParent.sprpalette; mapParent.BuildMap(); scene.ow.allmaps[mapParent.index + 1].BuildMap(); scene.ow.allmaps[mapParent.index + 8].BuildMap(); scene.ow.allmaps[mapParent.index + 9].BuildMap(); } else { mapParent.BuildMap(); } //scene.updateMapGfx(); scene.Invalidate(); //scene.Refresh(); } }
private void ReceiveWorldRequest(BinaryReader reader) { myOverworld = new OverworldMap(reader, false); SendPostWorld(); }
private static void MainLoop() { if (mySinglePlayer) { Log("Starting single player server\n"); } else { List <IPAddress> addresses = new List <IPAddress>(); IPHostEntry info = Dns.GetHostEntry(IPAddress.Loopback); foreach (IPAddress add in info.AddressList) { if (add.ToString().StartsWith("5.")) { addresses.Add(add); } else if (add.ToString().StartsWith("192.168.")) { if (myLan) { addresses.Add(add); } } else if (!myLan && add.ToString().Contains('.')) { addresses.Add(add); } } addresses.Add(IPAddress.Loopback); Log("Starting multi player server..." + "\n Host: " + info.HostName + " @ " + String.Join <IPAddress>(", ", addresses.ToArray()) + "\n Port: " + myPort.ToString() + "\n Max clients: " + myMaxClients.ToString() + "\n"); myListeners = new TcpListener[addresses.Count]; for (int i = 0; i < myListeners.Length; ++i) { myListeners[i] = new TcpListener(addresses[i], myPort); } } myClients = new ClientBase[8]; myClientCount = 0; myJoinQueue = new List <ClientBase>(); Log("Loading content..."); ResourceLib.Res.LoadFromOrderFile("Data" + System.IO.Path.DirectorySeparatorChar + "loadorder.txt"); Lewt.Shared.Scripts.Compile(Lewt.Shared.Scripts.Destination.Server); Lewt.Shared.Scripts.Initialise(); Log("Generating world..."); myOverworld = new OverworldMap(32, 32); myOverworld.Generate(); myOverworld.GetOverworldTile(myOverworld.Width / 2 - 1, myOverworld.Height / 2 - 1).LoadChunks(); myOverworld.GetOverworldTile(myOverworld.Width / 2, myOverworld.Height / 2 - 1).LoadChunks(); myOverworld.GetOverworldTile(myOverworld.Width / 2 - 1, myOverworld.Height / 2).LoadChunks(); myOverworld.GetOverworldTile(myOverworld.Width / 2, myOverworld.Height / 2).LoadChunks(); myActiveMaps = new List <Map>(); Log("Complete\n"); if (!mySinglePlayer) { for (int i = 0; i < myListeners.Length; ++i) { myListeners[i].Start(); } } myRunning = true; Log("Server ready to accept clients\n"); myLastThinkTime = DateTime.Now; while (myRunning) { if (!mySinglePlayer) { CheckForConnectionRequests(); } CheckForClientUpdates(); if (myClientCount == 0 && myJoinQueue.Count == 0) { Thread.Sleep(100); } else if ((DateTime.Now - myLastThinkTime).TotalSeconds >= ThinkInterval) { myLastThinkTime = DateTime.Now; foreach (Map map in myActiveMaps) { map.Think(ThinkInterval); } } } }
/// <summary> /// Loads all necessary data. /// </summary> protected override void OnLoadData() { object instance; if (!this.Parameters.TryGetValue("Offset", out instance) || !(instance is int)) { throw new ApplicationException(); } this.offset = (int)instance; // Load the map. if (!this.Parameters.TryGetValue("Data", out instance) || !(instance is byte[])) { throw new ApplicationException(); } this.map = new OverworldMap(instance as byte[]); // Disable the horizontal scroll bar. this.flowLayoutPanelTiles.HorizontalScroll.Enabled = false; this.flowLayoutPanelTiles.HorizontalScroll.Visible = false; // Convert the master image into individual tiles. var tileMaster = global::JonCloud.Ztwedit.Properties.Resources.OverworldTiles; this.tiles = new Bitmap[tileMaster.Width / 16]; for (int i = 0; i < tiles.Length; i++) { var b = this.tiles[i] = new Bitmap(16, 16); using (var g = Graphics.FromImage(b)) { g.DrawImage( tileMaster, new Rectangle(0, 0, 16, 16), new Rectangle(i * 16, 0, 16, 16), GraphicsUnit.Pixel); } // Add the picture box to the available tiles. PictureBox box = new PictureBox { Height = 32, Image = b, Margin = new Padding(0), Padding = new Padding(0), SizeMode = PictureBoxSizeMode.StretchImage, Tag = i, Width = 32 }; box.MouseClick += new MouseEventHandler(ChangeTile); this.flowLayoutPanelTiles.Controls.Add(box); } // Store the first position as the last tile so it can be // changed first if the tile is actually different. this.lastTile = (byte)this.map[0, 0]; // Update the tiles. this.ChangeTile(this, new MouseEventArgs(MouseButtons.Left, 0, 0, 0, 0)); this.ChangeTile(this, new MouseEventArgs(MouseButtons.Right, 0, 0, 0, 0)); // Render the map. this.RenderMap(); }
private void ReceiveMapRequest(BinaryReader reader) { UInt16 id = reader.ReadUInt16(); if (id == 0xFFFF) { CurrentMap = GameServer.Overworld; } else { CurrentMap = GameServer.Overworld.GetMap(id); } if (CurrentMap is Dungeon) { Dungeon dungeon = CurrentMap as Dungeon; if (!dungeon.HasGenerated) { dungeon.Generate(); } } GameServer.ActivateMap(CurrentMap); if (CurrentMap is OverworldMap) { OverworldMap map = CurrentMap as OverworldMap; PlayerEntity.OriginX = map.Width / 2 + 8; PlayerEntity.OriginY = map.Height / 2 + 8; map.AddEntity(PlayerEntity); } else if (CurrentMap is Dungeon) { Dungeon map = CurrentMap as Dungeon; if (map.SpawnList.Count == 0) { Chunk randChunk = map.TileChunks[(int)(Tools.Random() * map.TileChunks.Length)]; PlayerEntity.OriginX = randChunk.X + randChunk.Width / 2; PlayerEntity.OriginY = randChunk.Y + randChunk.Height / 2; } else { Vector2d spawn = map.SpawnList[(int)(Tools.Random() * map.SpawnList.Count)]; PlayerEntity.OriginX = spawn.X; PlayerEntity.OriginY = spawn.Y; } map.AddEntity(PlayerEntity); } State = ClientState.RequestingMap; SendMapRequest(); FindLocalOverworldTiles(); if (CurrentMap is OverworldMap) { SendPostMap(false); } else { Chunk[] chunks = CurrentMap.TileChunks; for (int i = 0; i < chunks.Length; ++i) { SendInteriorChunk((ushort)i, chunks[i]); } } }
public void GenerateWorld() { #if !DEBUG try #endif { CurrentState = GenerationState.Generating; LoadingMessage = "Init.."; OverworldMap.heightNoise.Seed = Overworld.Seed; Overworld.Map.Map = new OverworldCell[Overworld.Width, Overworld.Height]; Progress = 0.01f; LoadingMessage = "Height Map ..."; float[,] heightMapLookup = null; heightMapLookup = OverworldMap.GenerateHeightMapLookup(Overworld.Width, Overworld.Height); Overworld.Map.CreateHeightFromLookup(heightMapLookup); Progress = 0.05f; int numRains = (int)Overworld.GenerationSettings.NumRains; int rainLength = 250; int numRainSamples = 3; for (int x = 0; x < Overworld.Width; x++) { for (int y = 0; y < Overworld.Height; y++) { Overworld.Map.Map[x, y].Erosion = 1.0f; Overworld.Map.Map[x, y].Weathering = 0; Overworld.Map.Map[x, y].Faults = 1.0f; } } LoadingMessage = "Climate"; for (int x = 0; x < Overworld.Width; x++) { for (int y = 0; y < Overworld.Height; y++) { Overworld.Map.Map[x, y].Temperature = ((float)(y) / (float)(Overworld.Height)) * Overworld.GenerationSettings.TemperatureScale; } } OverworldImageOperations.Distort(Overworld.Map.Map, Overworld.Width, Overworld.Height, 30.0f, 0.005f, OverworldField.Temperature); for (int x = 0; x < Overworld.Width; x++) { for (int y = 0; y < Overworld.Height; y++) { Overworld.Map.Map[x, y].Temperature = Math.Max(Math.Min(Overworld.Map.Map[x, y].Temperature, 1.0f), 0.0f); } } int numVoronoiPoints = (int)Overworld.GenerationSettings.NumFaults; Progress = 0.1f; LoadingMessage = "Faults ..."; Voronoi(Overworld.Width, Overworld.Height, numVoronoiPoints); Overworld.Map.CreateHeightFromLookupWithErosion(heightMapLookup); Progress = 0.2f; Overworld.Map.CreateHeightFromLookupWithErosion(heightMapLookup); Progress = 0.25f; LoadingMessage = "Erosion..."; var buffer = new float[Overworld.Width, Overworld.Height]; Erode(Overworld.Width, Overworld.Height, Overworld.GenerationSettings.SeaLevel, Overworld.Map.Map, numRains, rainLength, numRainSamples, buffer); Overworld.Map.CreateHeightFromLookupWithErosion(heightMapLookup); Progress = 0.9f; LoadingMessage = "Blur."; OverworldImageOperations.Blur(Overworld.Map.Map, Overworld.Width, Overworld.Height, OverworldField.Erosion); LoadingMessage = "Generate height."; Overworld.Map.CreateHeightFromLookupWithErosion(heightMapLookup); LoadingMessage = "Rain"; CalculateRain(Overworld.Width, Overworld.Height); LoadingMessage = "Biome"; for (int x = 0; x < Overworld.Width; x++) { for (int y = 0; y < Overworld.Height; y++) { Overworld.Map.Map[x, y].Biome = Library.GetBiomeForConditions(Overworld.Map.Map[x, y].Temperature, Overworld.Map.Map[x, y].Rainfall, Overworld.Map.Map[x, y].Height).Biome; } } LoadingMessage = "Volcanoes"; GenerateVolcanoes(Overworld.Width, Overworld.Height); LoadingMessage = "Factions"; FactionSet library = new FactionSet(); library.Initialize(null, new CompanyInformation()); Overworld.Natives = new List <OverworldFaction>(); foreach (var fact in library.Factions) { Overworld.Natives.Add(fact.Value.ParentFaction); // Todo: Don't create a whole faction just to grab the overworldfactions from them. } for (int i = 0; i < Overworld.GenerationSettings.NumCivilizations; i++) { Overworld.Natives.Add(library.GenerateOverworldFaction(Overworld, i, Overworld.GenerationSettings.NumCivilizations)); } Politics.Initialize(Overworld); Overworld.ColonyCells = new CellSet("World\\colonies"); Overworld.InstanceSettings = new InstanceSettings(Overworld.ColonyCells.GetCellAt(16, 0)); SeedCivs(); GrowCivs(); for (int x = 0; x < Overworld.Width; x++) { Overworld.Map.Map[x, 0] = Overworld.Map.Map[x, 1]; Overworld.Map.Map[x, Overworld.Height - 1] = Overworld.Map.Map[x, Overworld.Height - 2]; } for (int y = 0; y < Overworld.Height; y++) { Overworld.Map.Map[0, y] = Overworld.Map.Map[1, y]; Overworld.Map.Map[Overworld.Width - 1, y] = Overworld.Map.Map[Overworld.Width - 2, y]; } CurrentState = GenerationState.Finished; LoadingMessage = ""; Progress = 1.0f; } #if !DEBUG catch (Exception exception) { ProgramData.WriteExceptionLog(exception); throw; } #endif }
public static void GenerateSurfaceLife(VoxelChunk TopChunk, ChunkGeneratorSettings Settings) { var creatureCounts = new Dictionary <string, Dictionary <string, int> >(); var worldDepth = Settings.WorldSizeInChunks.Y * VoxelConstants.ChunkSizeY; for (var x = TopChunk.Origin.X; x < TopChunk.Origin.X + VoxelConstants.ChunkSizeX; x++) { for (var z = TopChunk.Origin.Z; z < TopChunk.Origin.Z + VoxelConstants.ChunkSizeZ; z++) { var overworldPosition = OverworldMap.WorldToOverworld(new Vector2(x, z), Settings.Overworld.InstanceSettings.Origin); if (Settings.Overworld.Map.GetBiomeAt(new Vector3(x, 0, z), Settings.Overworld.InstanceSettings.Origin).HasValue(out var biome)) { var normalizedHeight = NormalizeHeight(Settings.Overworld.Map.LinearInterpolate(overworldPosition, OverworldField.Height)); var height = (int)MathFunctions.Clamp(normalizedHeight * worldDepth, 0.0f, worldDepth - 2); var voxel = Settings.World.ChunkManager.CreateVoxelHandle(new GlobalVoxelCoordinate(x, height, z)); if (!voxel.IsValid || voxel.Coordinate.Y == 0 || voxel.Coordinate.Y >= worldDepth - Settings.TreeLine) { continue; } if (voxel.LiquidLevel != 0) { continue; } var above = VoxelHelpers.GetVoxelAbove(voxel); if (above.IsValid && (above.LiquidLevel != 0 || !above.IsEmpty)) { continue; } foreach (var animal in biome.Fauna) { if (MathFunctions.RandEvent(animal.SpawnProbability)) { if (!creatureCounts.ContainsKey(biome.Name)) { creatureCounts[biome.Name] = new Dictionary <string, int>(); } var dict = creatureCounts[biome.Name]; if (!dict.ContainsKey(animal.Name)) { dict[animal.Name] = 0; } if (dict[animal.Name] < animal.MaxPopulation) { EntityFactory.CreateEntity <GameComponent>(animal.Name, voxel.WorldPosition + Vector3.Up * 1.5f); } break; } } if (voxel.Type.Name != biome.SoilLayer.VoxelType) { continue; } foreach (VegetationData veg in biome.Vegetation) { if (voxel.GrassType == 0) { continue; } if (MathFunctions.RandEvent(veg.SpawnProbability) && Settings.NoiseGenerator.Noise(voxel.Coordinate.X / veg.ClumpSize, veg.NoiseOffset, voxel.Coordinate.Z / veg.ClumpSize) >= veg.ClumpThreshold) { var treeSize = MathFunctions.Rand() * veg.SizeVariance + veg.MeanSize; EntityFactory.CreateEntity <Plant>(veg.Name, voxel.WorldPosition + new Vector3(0.5f, 1.0f, 0.5f), Blackboard.Create("Scale", treeSize)); break; } } } } } }
public static VoxelChunk GenerateChunk(GlobalChunkCoordinate ID, ChunkGeneratorSettings Settings) { var origin = new GlobalVoxelCoordinate(ID, new LocalVoxelCoordinate(0, 0, 0)); var worldDepth = Settings.WorldSizeInChunks.Y * VoxelConstants.ChunkSizeY; var waterHeight = NormalizeHeight(Settings.Overworld.GenerationSettings.SeaLevel + 1.0f / worldDepth); var c = new VoxelChunk(Settings.World.ChunkManager, ID); if (GameSettings.Current.NoStone) { return(c); } for (int x = 0; x < VoxelConstants.ChunkSizeX; x++) { for (int z = 0; z < VoxelConstants.ChunkSizeZ; z++) { var overworldPosition = OverworldMap.WorldToOverworld(new Vector2(x + origin.X, z + origin.Z), Settings.Overworld.InstanceSettings.Origin); if (Settings.Overworld.Map.GetBiomeAt(new Vector3(x + origin.X, 0, z + origin.Z), Settings.Overworld.InstanceSettings.Origin).HasValue(out var biomeData)) { var normalizedHeight = NormalizeHeight(Settings.Overworld.Map.LinearInterpolate(overworldPosition, OverworldField.Height)); var height = MathFunctions.Clamp(normalizedHeight * worldDepth, 0.0f, worldDepth - 2); var stoneHeight = (int)MathFunctions.Clamp((int)(height - (biomeData.SoilLayer.Depth + (Math.Sin(overworldPosition.X) + Math.Cos(overworldPosition.Y)))), 1, height); for (int y = 0; y < VoxelConstants.ChunkSizeY; y++) { var globalY = origin.Y + y; var voxel = VoxelHandle.UnsafeCreateLocalHandle(c, new LocalVoxelCoordinate(x, y, z)); if (globalY == 0) { voxel.RawSetType(Library.GetVoxelType("Bedrock")); continue; } // Below the stone line, use subsurface layers. if (globalY <= stoneHeight && stoneHeight > 1) { var depth = stoneHeight - globalY - biomeData.SubsurfaceLayers[0].Depth + 1; var subsurfaceLayer = 0; while (depth > 0 && subsurfaceLayer < biomeData.SubsurfaceLayers.Count - 1) { depth -= biomeData.SubsurfaceLayers[subsurfaceLayer].Depth; subsurfaceLayer += 1; } voxel.RawSetType(Library.GetVoxelType(biomeData.SubsurfaceLayers[subsurfaceLayer].VoxelType)); } // Otherwise, on the surface. else if ((globalY == (int)height || globalY == stoneHeight) && normalizedHeight > waterHeight) { voxel.RawSetType(Library.GetVoxelType(biomeData.SoilLayer.VoxelType)); if (!String.IsNullOrEmpty(biomeData.GrassDecal)) { if (!biomeData.ClumpGrass || (biomeData.ClumpGrass && Settings.NoiseGenerator.Noise(overworldPosition.X / biomeData.ClumpSize, 0, overworldPosition.Y / biomeData.ClumpSize) > biomeData.ClumpTreshold)) { voxel.RawSetGrass(Library.GetGrassType(biomeData.GrassDecal).ID); } } } else if (globalY > height && globalY > 0) { voxel.RawSetType(Library.EmptyVoxelType); } else if (normalizedHeight <= waterHeight) { voxel.RawSetType(Library.GetVoxelType(biomeData.ShoreVoxel)); } else { voxel.RawSetType(Library.GetVoxelType(biomeData.SoilLayer.VoxelType)); } } } } } return(c); }