diff --git a/Utilities/MathematicalUtils.cs b/Utilities/MathematicalUtils.cs index 8e3e17d123..d920f3e259 100644 --- a/Utilities/MathematicalUtils.cs +++ b/Utilities/MathematicalUtils.cs @@ -27,7 +27,6 @@ namespace CalamityMod /// The Y position on the map. /// A metric of "instability" of the noise. The higher this is, the more unstable. Lower of bounds of 2-3 are preferable. /// The seed for the noise. - /// public static float PerlinNoise2D(float x, float y, int octaves, int seed) { float SmoothFunction(float n) => 3f * n * n - 2f * n * n * n; diff --git a/Utilities/WorldgenUtils.cs b/Utilities/WorldgenUtils.cs index 55017eec6b..41d5d84caa 100644 --- a/Utilities/WorldgenUtils.cs +++ b/Utilities/WorldgenUtils.cs @@ -1,4 +1,5 @@ using System.Linq; +using Microsoft.Xna.Framework; using Terraria; using Terraria.ID; @@ -31,5 +32,58 @@ namespace CalamityMod } } } + + /// + /// Generates caves via celluar automata in terms of active/inactive states. May also be used to smoothen out areas. + /// + /// The area to perform the algorithm on. + /// The number of times to iterate. The higher this value is, the more smooth the result is. + public static void GenerateCellularAutomataCave(Rectangle area, int gameIterations) + { + bool[,] cellStates = new bool[area.Width, area.Height]; + int width = cellStates.GetLength(0); + int height = cellStates.GetLength(1); + + // Initialize the cell states. + for (int i = area.Left; i < area.Right; i++) + { + for (int j = area.Top; j < area.Bottom; j++) + cellStates[i - area.Left, j - area.Top] = ParanoidTileRetrieval(i, j).HasTile; + } + + for (int i = 0; i < gameIterations; i++) + { + bool[,] newState = cellStates.Clone() as bool[,]; + for (int x = 0; x < width; x++) + { + for (int y = 0; y < height; y++) + { + int nearbyActiveCells = 0; + for (int dx = -1; dx <= 1; dx++) + { + for (int dy = -1; dy <= 1; dy++) + { + if (x + dx < 0 || x + dx >= width || y + dy < 0 || y + dy >= height) + { + nearbyActiveCells++; + continue; + } + + nearbyActiveCells += cellStates[x + dx, y + dy].ToInt(); + } + } + + newState[x, y] = nearbyActiveCells >= 5; + } + } + cellStates = newState; + } + + for (int i = area.Left; i < area.Right; i++) + { + for (int j = area.Top; j < area.Bottom; j++) + Main.tile[i, j].Get().HasTile = cellStates[i - area.Left, j - area.Top]; + } + } } } diff --git a/World/SulphurousSea.cs b/World/SulphurousSea.cs index e2a6f0fa48..6be657f96f 100644 --- a/World/SulphurousSea.cs +++ b/World/SulphurousSea.cs @@ -9,6 +9,7 @@ using System; using System.Collections.Generic; using System.Linq; using Terraria; +using Terraria.GameContent.RGB; using Terraria.ID; using Terraria.ModLoader; using Terraria.WorldBuilding; @@ -18,25 +19,78 @@ namespace CalamityMod.World public class SulphurousSea { #region Fields and Properties + + // Loop variables that are accessed via getter methods should be stored externally in local variables for performance reasons. + public static readonly List SulphSeaTiles = new() + { + ModContent.TileType(), + ModContent.TileType(), + ModContent.TileType() + }; + + public const float SandBlockEdgeDescentSmoothness = 0.24f; + + // What percentage it takes for dither effects to start appearing at the edges. + // As an example, if this value is 0.7 that would mean that tiles that are below 70% of the way down from the top of the ocean would + // start randomly dithering. + public const float DitherStartFactor = 0.9f; + + public const int DepthForWater = 18; + + public const float TopWaterDepthPercentage = 0.125f; + + public const float TopWaterDescentSmoothnessMin = 0.26f; + + public const float TopWaterDescentSmoothnessMax = 0.39f; + + public const int TotalSandTilesBeforeWaterMin = 32; + + public const int TotalSandTilesBeforeWaterMax = 45; + + // 0-1 value of how jagged the small caves should be. The higher this value is, the more variance you can expect for each step when carving out caves. + public const float SmallCavesJaggedness = 0.51f; + + // How much of a tendency the small caves have to be cramped instead of large and open, with values between 0-1 emphasizing larger caves while values greater than 1 + // emphasizing more cramped caves. + public const float SmallCavesBiasTowardsTightness = 2.21f; + + // How much of a magnification is performed when calculating perlin noise for spaghetti caves. The closer to 0 this value is, the more same-y the caves will seem in + // terms of direction, size, etc. + public const float SpaghettiCaveMagnification = 0.00193f; + + // 0-1 value that determines the threshold for spaghetti caves being carved out. At 0, no caves are carved out, at 1, all tiles are carved out. + // This is used in the formula 'abs(noise(x, y)) < r' to determine whether the cave should remove tiles. + public static readonly float[] SpaghettiCaveCarveOutThresholds = new float[] + { + 0.033f, + 0.089f + }; + + public const float CheeseCaveMagnification = 0.00237f; + + public static readonly float[] CheeseCaveCarveOutThresholds = new float[] + { + 0.4f + }; + + // Percentage of how far down a tile has to be for open caverns to appear. + public const float OpenCavernStartDepthPercentage = 0.5f; + public static int BiomeWidth { get { - // Small world - if (Main.maxTilesX == 4200) + return Main.maxTilesX switch { - return 370; - } - // Medium world - else if (Main.maxTilesX == 6400) - { - return 445; - } - // Large world - else - { - return 500; - } + // Small worlds. + 4200 => 370, + + // Medium worlds. + 6400 => 445, + + // Large worlds. This also accounts for worlds of an unknown size, such as extra large worlds. + _ => (int)(Main.maxTilesX / 16.8f), + }; } } @@ -44,31 +98,38 @@ namespace CalamityMod.World { get { - // Small world - if (Main.maxTilesX == 4200) + float depthFactor = Main.maxTilesX switch { - return (int)((Main.rockLayer + 20 - YStart) * 0.8); - } - // Medium world - else if (Main.maxTilesX == 6400) - { - return (int)((Main.rockLayer + 20 - YStart) * 0.85); - } - // Large world - else - { - return (int)((Main.rockLayer + 20 - YStart) * 0.925); - } + // Small worlds. + 4200 => 0.8f, + + // Medium worlds. + 6400 => 0.85f, + + // Large worlds. + _ => 0.925f + }; + return (int)((Main.rockLayer + 112 - YStart) * depthFactor); } } - public static int YStart = 0; - public static readonly List SulphSeaTiles = new() + public static int TotalCavesInShallowWater => (int)Math.Ceiling(Main.maxTilesX / 1300f); + + public static int MaxTopWaterDepth => (int)(BlockDepth * TopWaterDepthPercentage); + + public static int MinCaveWidth => (int)(Main.maxTilesX / 2500f); + + public static int MaxCaveWidth => (int)Math.Ceiling(Main.maxTilesX / 376f); + + public static int MinCaveMovementSteps => (int)Math.Ceiling(Main.maxTilesX / 70f); + + public static int MaxCaveMovementSteps => (int)Math.Ceiling(Main.maxTilesX / 40f); + + public static int YStart { - ModContent.TileType(), - ModContent.TileType(), - ModContent.TileType() - }; + get; + set; + } #endregion #region Placement Methods @@ -76,846 +137,323 @@ namespace CalamityMod.World { Abyss.AtLeftSideOfWorld = Main.dungeonX < Main.maxTilesX / 2; DetermineYStart(); - CreateStartingBlock(); - CreateWater(); - GenerateHardenedSandstone(); + GenerateSandBlock(); RemoveStupidTilesAboveSea(); - GenerateLake(); - SettleWater(); // The island Y spawn position calculations are relative to water. Settling the water before doing these calculations is ideal. - GenerateIslands(); - GenerateVentsAndFossils(); - SmoothenTheEntireSea(); + GenerateShallowTopWater(); + + // Cave generation. Some of these borrow concepts and tricks used by Minecraft's new generation. + GenerateSmallWaterCaverns(); + GenerateSpaghettiWaterCaves(); + GenerateCheeseWaterCaves(); + ClearOutStrayTiles(); + + // Lay down decorations after the caves are generated. + DecideHardSandstoneLine(); } public static void FinishGeneratingSulphurSea() { - PlaceStalactites(); - PlaceColumns(); - CreateBeachNearSea(); - PlaceScrapPiles(); - PlaceRustyChests(); + } #endregion - #region Perlin Noise - public static float NoiseFunction(int seed) + #region Generation Functions + public static void GenerateSandBlock() { - seed = (seed << 13) ^ seed; - return 1.0f - ((seed * (seed * seed * 15731) + 1376312589) & 0x7fffffff) / 1073741824.0f; - } - public static float PerlinNoise2D(float x, float y, int octave, int seed) - { - float frequency = (float)Math.Pow(2, octave); - float xFrequency = x * frequency; - float yFrequency = y * frequency; - int flooredXFrequency = (int)xFrequency; - int flooredYFrequency = (int)yFrequency; - float fractionXFrequency = xFrequency - flooredXFrequency; - float fractionYFrequency = yFrequency - flooredYFrequency; - - float noise1 = NoiseFunction(flooredXFrequency + flooredYFrequency * 54 + seed); - float noise2 = NoiseFunction(flooredXFrequency + 1 + flooredYFrequency * 54 + seed); - float noise3 = NoiseFunction(flooredXFrequency + (1 + flooredYFrequency) * 54 + seed); - float noise4 = NoiseFunction(flooredXFrequency + 1 + (1 + flooredYFrequency) * 54 + seed); - - float lerpStart = MathHelper.Lerp(noise1, noise2, fractionXFrequency); - float lerpEnd = MathHelper.Lerp(noise3, noise4, fractionXFrequency); - return MathHelper.Lerp(lerpStart, lerpEnd, fractionYFrequency); - } - #endregion - - #region Generating Initial Block - public static void CreateStartingBlock() - { - // Set above for general performance. - ushort sandTileType = (ushort)ModContent.TileType(); - ushort sandstoneTileType = (ushort)ModContent.TileType(); - - ushort sandWallType = (ushort)ModContent.WallType(); - ushort sandstoneWallType = (ushort)ModContent.WallType(); - - - float randomValue1 = WorldGen.genRand.NextFloat(-0.4f, 0.4f); - while (Math.Abs(randomValue1) < 0.22f) + int width = BiomeWidth + 1; + int maxDepth = BlockDepth; + ushort blockTileType = (ushort)ModContent.TileType(); + for (int i = 1; i < width; i++) { - randomValue1 = WorldGen.genRand.NextFloat(-0.4f, 0.4f); - } - float randomValue2 = WorldGen.genRand.NextFloat(-0.2f, 0.2f); - while (Math.Abs(randomValue2) < 0.07f) - { - randomValue2 = WorldGen.genRand.NextFloat(-0.2f, 0.2f); - } + int x = GetActualX(i); - float randomValue3 = WorldGen.genRand.NextFloat(0.42f, 0.96f) * WorldGen.genRand.NextBool(2).ToDirectionInt(); - float wallBoundAtPosition(float xRatio) => (float)(Math.Sin(randomValue3 * MathHelper.Pi * xRatio) + Math.Cos(randomValue3 * Math.E / 2f * xRatio)) * 0.5f * 28f; + // Calculate the 0-1 factor that determines how far down a vertical strip of the sea should descend. + float depthFactor = (float)Math.Pow(Math.Sin((1f - i / (float)width) * MathHelper.PiOver2), SandBlockEdgeDescentSmoothness); - for (int x = 1; x < BiomeWidth; x++) - { - float xRatio = x / (float)BiomeWidth; - for (int y = YStart; y <= YStart + BlockDepth; y++) + // Determine the top and botton of the strip. + int top = YStart; + int bottom = top + (int)(maxDepth * depthFactor); + for (int y = top; y < bottom; y++) { - int trueX = Abyss.AtLeftSideOfWorld ? x : Main.maxTilesX - x; - float yRatio = (y - YStart) / (float)BlockDepth; - float xAngleWrap = x / (float)BiomeWidth * MathHelper.TwoPi - MathHelper.Pi; - bool generateSand = yRatio < SandstoneYMinimum(xAngleWrap, randomValue1, randomValue2); - if (WorldGen.InWorld(trueX, y)) - { - if (y - YStart < BlockDepth - (int)(BlockDepth * 0.35f) + (int)(Math.Sin(xRatio * MathHelper.Pi) * (int)(BlockDepth * 0.35f))) - { - Main.tile[trueX, y].ClearEverything(); - Main.tile[trueX, y].WallType = generateSand ? sandWallType : sandstoneWallType; - Main.tile[trueX, y].TileType = generateSand ? sandTileType : sandstoneTileType; - if (y - YStart - 6 < wallBoundAtPosition(xRatio * MathHelper.TwoPi * 4f)) - Main.tile[trueX, y].WallType = WallID.None; + float ditherChance = CalculateDitherChance(width, top, bottom, i, y); + if (WorldGen.genRand.NextFloat() >= ditherChance) + Main.tile[x, y].TileType = blockTileType; - Main.tile[trueX, y].Get().HasTile = true; - } + // Ensure that the sand pops into existence if there is no chance that dithering will occur. + // This doesn't happen if there is dithering to ensure that there aren't stray sand tiles in the middle of open + // caves that have nothing to connect to. + if (ditherChance <= 0f) + { + Main.tile[x, y].Get().Slope = SlopeType.Solid; + Main.tile[x, y].Get().IsHalfBlock = false; + Main.tile[x, y].Get().HasTile = true; } } } } - public static float SandstoneYMinimum(float xAsAngle, float randomValue1, float randomValue2) - { - float sineSquaredRandom1 = randomValue1 * (float)Math.Cos(xAsAngle * randomValue1) * (float)Math.Cos(xAsAngle * randomValue1); - float sineSquaredRandom2 = randomValue1 * (float)Math.Sin(xAsAngle * randomValue1) * (float)Math.Sin(xAsAngle * randomValue1); - float sineSquaredRandom3 = randomValue2 * (float)Math.Sin(xAsAngle * randomValue2); - float sineSquaredRandom4 = (float)Math.Sin(randomValue1 / randomValue2 * xAsAngle) * (float)Math.Cos(randomValue1 * MathHelper.Pi); - return 0.25f * Math.Abs(sineSquaredRandom1 + 0.5f * sineSquaredRandom2 + sineSquaredRandom3 - sineSquaredRandom4) + 0.25f; - } - #endregion - #region Generating Water - public const int PerlinIterations = 1; - public const int PerlinOctaves = 4; - public const int PerlinXEdgeClamp = 20; - public const float PerlinYDelta = 40; - public const float PerlinNoiseMax = 0.05f; - public const float PerlinThreshold = 0.1f; // Be careful with this number - - public static void GenerateLake() - { - int lakeDepthMax = WorldGen.genRand.Next(36, 52 + 1); - float lakeSteepness = WorldGen.genRand.NextFloat(1.2f, 1.5f); - for (int x = 1; x < BiomeWidth; x++) - { - int trueX = Abyss.AtLeftSideOfWorld ? x : Main.maxTilesX - x; - float xRatio = x / (float)BiomeWidth; - int lakeDepth = (int)(Math.Sin(MathHelper.Min((1f - xRatio) * MathHelper.PiOver2 * lakeSteepness * 1.2f, MathHelper.PiOver2)) * lakeDepthMax); - for (int y = YStart; y <= YStart + lakeDepth; y++) - { - ushort oldWall = Main.tile[trueX, y].WallType; - Main.tile[trueX, y].ClearEverything(); - Main.tile[trueX, y].WallType = oldWall; - Main.tile[trueX, y].LiquidAmount = 255; - } - } - } - - public static void CreateWater() - { - int[] seeds = new int[PerlinIterations]; - for (int i = 0; i < seeds.Length; i++) - { - seeds[i] = WorldGen.genRand.Next(); - } - for (int x = 1; x < BiomeWidth; x++) - { - float xRatio = x / (float)BiomeWidth; - for (int y = YStart; y <= YStart + BlockDepth; y++) - { - float yRatio = (y - YStart) / (float)BlockDepth; - int trueX = Abyss.AtLeftSideOfWorld ? x : Main.maxTilesX - x; - if (y - YStart < BlockDepth - (int)(BlockDepth * 0.35f) + (int)(Math.Sin(xRatio * MathHelper.Pi) * (int)(BlockDepth * 0.35f)) - PerlinYDelta) - { - if (x < PerlinXEdgeClamp || x > BiomeWidth - PerlinXEdgeClamp) - continue; - float perlinAverage = 0f; - for (int k = 0; k < seeds.Length; k++) - { - perlinAverage += PerlinNoise2D(xRatio, yRatio, PerlinOctaves, seeds[k]) / PerlinIterations; - } - if (perlinAverage > PerlinThreshold * WorldGen.genRand.NextFloat(1f - PerlinNoiseMax, 1f + PerlinNoiseMax)) - { - ushort oldWall = Main.tile[trueX, y].WallType; - Main.tile[trueX, y].ClearEverything(); - Main.tile[trueX, y].WallType = oldWall; - Main.tile[trueX, y].LiquidAmount = 255; - } - } - } - } - } - #endregion - - #region Generating Edge Sandstone - public const int EdgeCheckMinX = 6; - public const int EdgeCheckMaxX = 8; - public const int EdgeCheckMinY = 4; - public const int EdgeCheckMaxY = 6; - public const int MinimumEdgeScore = 4; - public const int SpotWidth = 4; - public static void GenerateHardenedSandstone() - { - for (int x = 1; x < BiomeWidth; x++) - { - for (int y = YStart; y <= YStart + BlockDepth; y++) - { - int trueX = Abyss.AtLeftSideOfWorld ? x : Main.maxTilesX - x; - int edgeScore = GetEdgeScore(trueX, y); - - if (edgeScore >= MinimumEdgeScore) - { - for (int dx = -SpotWidth / 2; dx <= SpotWidth; dx++) - { - for (int dy = -SpotWidth / 2; dy <= SpotWidth / 2; dy++) - { - if (WorldGen.InWorld(trueX + dx, y + dy)) - { - if (CalamityUtils.ParanoidTileRetrieval(trueX + dx, y + dy).TileType != (ushort)ModContent.TileType() && - SulphSeaTiles.Contains(CalamityUtils.ParanoidTileRetrieval(trueX + dx, y + dy).TileType)) - { - Main.tile[trueX + dx, y + dy].TileType = (ushort)ModContent.TileType(); - } - } - } - } - } - } - } - } - public static int GetEdgeScore(int x, int y) - { - int edgeScore = 0; - for (int dx = x - WorldGen.genRand.Next(EdgeCheckMinX, EdgeCheckMaxX + 1); dx <= x + WorldGen.genRand.Next(EdgeCheckMinX, EdgeCheckMaxX + 1); dx++) - { - if (dx == x) - continue; - if (CalamityUtils.ParanoidTileRetrieval(dx, y).LiquidAmount == 255) - edgeScore++; - } - for (int dy = y - WorldGen.genRand.Next(EdgeCheckMinY, EdgeCheckMaxY + 1); dy <= y + WorldGen.genRand.Next(EdgeCheckMinY, EdgeCheckMaxY + 1); dy++) - { - if (dy == y) - continue; - if (CalamityUtils.ParanoidTileRetrieval(x, dy).LiquidAmount == 255) - edgeScore++; - } - return edgeScore; - } - #endregion - - #region Generating Islands - public const int IslandCount = 4; - public const int IslandXPadding = 20; - - public const int IslandMinWidth = 15; - public const int IslandMaxWidth = 22; - - public const int IslandMinDepth = 5; - public const int IslandMaxDepth = 10; - public static void SettleWater() - { - Liquid.QuickWater(3, -1, -1); - WorldGen.WaterCheck(); - int counter = 0; - Liquid.quickSettle = true; - while (counter < 10) - { - counter++; - while (Liquid.numLiquid > 0) - { - Liquid.UpdateLiquid(); - } - WorldGen.WaterCheck(); - } - Liquid.quickSettle = false; - - // Remove liquid above the biome line, to prevent flooding. - for (int x = 2; x < BiomeWidth - 2; x++) - { - int trueX = x; - if (!Abyss.AtLeftSideOfWorld) - trueX = Main.maxTilesX - x; - for (int y = YStart - 300; y <= YStart; y++) - { - if (CalamityUtils.ParanoidTileRetrieval(trueX, y).LiquidAmount > 0) - Main.tile[trueX, y].LiquidAmount = 0; - } - } - } - public static void GenerateIslands() - { - for (int i = 0; i < IslandCount; i++) - { - int y = YStart - 240; - int x = WorldGen.genRand.Next(IslandMaxWidth + IslandXPadding, BiomeWidth - IslandMaxWidth - IslandXPadding); - if (!Abyss.AtLeftSideOfWorld) - x = Main.maxTilesX - x; - while (CalamityUtils.ParanoidTileRetrieval(x, y).LiquidAmount == 0) - { - y++; - if (y > Main.rockLayer - 35) - { - break; - } - } - if (y > Main.rockLayer - 35) - { - i--; - continue; // Try again - } - int height = 2 * WorldGen.genRand.Next(IslandMinDepth, IslandMaxDepth + 1); - int width = WorldGen.genRand.Next(IslandMinWidth, IslandMaxWidth + 1); - int treePosition = WorldGen.genRand.Next(-width + 4, width - 4); - - for (float theta = 0f; theta <= MathHelper.TwoPi; theta += 0.05f) - { - for (int dx = 0; dx != (int)(height * Math.Cos(theta)); dx += (height * Math.Cos(theta) > 0).ToDirectionInt()) - { - for (int dy = 0; dy != (int)(width * Math.Sin(theta)); dy += (width * Math.Sin(theta) > 0).ToDirectionInt()) - { - if (WorldGen.InWorld(x + dx, y + dy)) - { - if (dy >= -2 - WorldGen.genRand.Next(-2, 3)) - { - int extraHeight = WorldGen.genRand.Next(0, 1 + 1); - for (int y2 = 0; y2 <= extraHeight; y2++) - { - Main.tile[x + dx, y + dy - y2].TileType = (ushort)ModContent.TileType(); - Main.tile[x + dx, y + dy - y2].Get().Slope = SlopeType.Solid; - Main.tile[x + dx, y + dy - y2].Get().IsHalfBlock = false; - Main.tile[x + dx, y + dy - y2].Get().HasTile = true; - } - if (dy == -2 && dx == treePosition) - WorldGen.PlaceTile(x + dx, y + dy - extraHeight - 1, ModContent.TileType()); - } - else - { - Main.tile[x + dx, y + dy].LiquidAmount = 0; - } - } - } - } - } - } - } - #endregion - - #region Smoothening Everything - public static void SmoothenTheEntireSea() - { - for (int x = 2; x < BiomeWidth - 2; x++) - { - int trueX = x; - if (!Abyss.AtLeftSideOfWorld) - trueX = Main.maxTilesX - x; - for (int y = YStart; y <= YStart + BlockDepth; y++) - { - Tile.SmoothSlope(trueX, y); - } - } - } - #endregion - - #region Generating Scenery - public const int ColumnMinDistanceX = 8; - public const int ColumnMinHeight = 10; - public const int ColumnMaxHeight = 27; - public const int StalactitePairMinDistance = 6; - public const int StalactitePairMaxDistance = 44; - public static void GenerateVentsAndFossils() - { - for (int x = 1; x < BiomeWidth; x++) - { - int trueX = Abyss.AtLeftSideOfWorld ? x : Main.maxTilesX - x; - for (int y = YStart; y <= YStart + BlockDepth; y++) - { - // Generate vents in the top 45% - if (y - YStart < BlockDepth * 0.45f) - { - if (WorldGen.SolidTile(trueX, y + 1) && WorldGen.genRand.NextBool(20)) - { - PlaceMiscTile(trueX, y, 1, 2, (ushort)ModContent.TileType()); - } - } - // And fossils in the bottom 55% - else - { - if (WorldGen.SolidTile(trueX, y + 1)) - { - // Generate ribs such that they're all nearby - if (WorldGen.genRand.NextBool(25)) - { - ushort type = (ushort)Utils.SelectRandom(WorldGen.genRand, - ModContent.TileType(), - ModContent.TileType(), - ModContent.TileType(), - ModContent.TileType(), - ModContent.TileType()); - int height; - if (type == ModContent.TileType() || type == ModContent.TileType()) - { - height = 3; - } - else if (type == ModContent.TileType()) - { - height = 2; - } - else if (type == ModContent.TileType()) - { - height = 4; - } - else - { - height = 1; - } - PlaceMiscTile(trueX, y, 1, height, type); - } - else if (WorldGen.genRand.NextBool(16)) - { - PlaceMiscTile(trueX, y, 3, 2, (ushort)Utils.SelectRandom(WorldGen.genRand, ModContent.TileType(), ModContent.TileType(), ModContent.TileType())); - } - } - } - } - } - } - public static void PlaceColumns() - { - int previousX = 0; - int style; - for (int x = 1; x < BiomeWidth; x++) - { - int trueX = Abyss.AtLeftSideOfWorld ? x : Main.maxTilesX - x; - for (int y = YStart; y <= YStart + BlockDepth; y++) - { - if (y - YStart > BlockDepth * 0.5f) - { - if (WorldGen.SolidTile(trueX, y + 1) && - WorldGen.SolidTile(trueX + 1, y + 1) && - SulphSeaTiles.Contains(CalamityUtils.ParanoidTileRetrieval(trueX, y + 1).TileType) && - WorldGen.genRand.NextBool(3) && - Math.Abs(trueX - previousX) >= ColumnMinDistanceX) - { - int top = y; - int height = 0; - while (!(WorldGen.SolidTile(trueX - 1, top) && WorldGen.SolidTile(trueX, top) && WorldGen.SolidTile(trueX + 1, top))) - { - top--; - height++; - if (height > ColumnMaxHeight + 1) - break; - } - if (height <= ColumnMaxHeight && height >= ColumnMinHeight) - { - for (int dy = 0; dy < height; dy++) - { - style = WorldGen.genRand.Next(3); - short yFrame = 18; - if (dy == 0) - yFrame = 36; - if (dy == height - 1) - yFrame = 0; - ushort oldWall = Main.tile[trueX, y - dy].WallType; - Main.tile[trueX, y - dy].ResetToType((ushort)ModContent.TileType()); - Main.tile[trueX, y - dy].TileFrameX = (short)(style * 36); - Main.tile[trueX, y - dy].TileFrameY = yFrame; - Main.tile[trueX, y - dy].LiquidAmount = 255; - Main.tile[trueX, y - dy].WallType = oldWall; - Main.tile[trueX, y - dy].Get().HasTile = true; - - oldWall = Main.tile[trueX + 1, y - dy].WallType; - - Main.tile[trueX + 1, y - dy].ResetToType((ushort)ModContent.TileType()); - Main.tile[trueX + 1, y - dy].TileFrameX = (short)(style * 36 + 18); - Main.tile[trueX + 1, y - dy].TileFrameY = yFrame; - Main.tile[trueX + 1, y - dy].LiquidAmount = 255; - Main.tile[trueX + 1, y - dy].WallType = oldWall; - Main.tile[trueX + 1, y - dy].Get().HasTile = true; - } - previousX = trueX; - } - } - } - } - } - } - public static void PlaceStalactites() - { - int heightFromType(int type) - { - if (type <= 2) - return 2; - else if (type <= 4) - return 3; - else - return 4; - }; - for (int x = 1; x < BiomeWidth; x++) - { - int trueX = Abyss.AtLeftSideOfWorld ? x : Main.maxTilesX - x; - for (int y = YStart; y <= YStart + BlockDepth; y++) - { - if (y - YStart > BlockDepth * 0.25f) - { - if (WorldGen.SolidTile(trueX, y - 1) && WorldGen.genRand.NextBool(10)) - { - int dy = 1; - while (!CalamityUtils.ParanoidTileRetrieval(trueX, y + dy).HasTile) - { - dy++; - if (dy > StalactitePairMaxDistance) - break; - } - if (dy <= StalactitePairMaxDistance && dy >= StalactitePairMinDistance) - { - int type = WorldGen.genRand.Next(6); - type++; - int height = heightFromType(type); - - PlaceStalactite(trueX, y, height, (ushort)CalamityMod.Instance.Find($"SulphurousStalactite{type}").Type); - if (WorldGen.SolidTile(trueX, y + dy + 1)) - PlaceStalacmite(trueX, y + dy, height, (ushort)CalamityMod.Instance.Find($"SulphurousStalacmite{type}").Type); - } - } - } - } - } - } - public static void PlaceMiscTile(int x, int y, int width, int height, ushort type, int style = 0) - { - try - { - bool canGenerate = true; - for (int i = x; i < x + width; i++) - { - for (int j = y - (int)Math.Ceiling(height / 2.0); j < y + (int)Math.Ceiling(height / 2.0); j++) - { - if (Main.tile[i, j].HasTile) - { - canGenerate = false; - } - } - if (!Main.tile[i, y + 1].HasUnactuatedTile || Main.tile[i, y + 1].IsHalfBlock || Main.tile[i, y + 1].Slope != 0 || !Main.tileSolid[Main.tile[i, y + 1].TileType]) - { - canGenerate = false; - } - } - if (canGenerate) - { - WorldGen.PlaceTile(x, y, type, style: style); - } - } - catch - { - return; // This should only ever happen from an index error, and there's really no point in continuing if that happens - } - } - public static void PlaceStalactite(int x, int y, int height, ushort type) - { - for (int dy = 0; dy < height; dy++) - { - ushort oldWall = Main.tile[x, y + dy].WallType; - Main.tile[x, y + dy].ClearEverything(); - Main.tile[x, y + dy].WallType = oldWall; - Main.tile[x, y + dy].TileType = type; - Main.tile[x, y + dy].TileFrameY = (short)(dy * 18); - Main.tile[x, y + dy].Get().HasTile = true; - } - } - public static void PlaceStalacmite(int x, int y, int height, ushort type) - { - for (int dy = height - 1; dy > 0; dy--) - { - ushort oldWall = Main.tile[x, y + dy].WallType; - Main.tile[x, y - dy].ClearEverything(); - Main.tile[x, y - dy].WallType = oldWall; - Main.tile[x, y - dy].TileType = type; - Main.tile[x, y - dy].TileFrameY = (short)(height * 18 - dy * 18); - Main.tile[x, y - dy].Get().HasTile = true; - } - } - #endregion - - #region Generating Chests - public const int CheckCutoffDistance = 15; - public static void PlaceRustyChests() - { - // Ambiguity bullshit. - int[] ItemTypes = { ModContent.ItemType(), - ModContent.ItemType(), - ModContent.ItemType(), - ModContent.ItemType() }; - - for (int i = 0; i < ItemTypes.Length; ++i) - { - Chest chest = null; - int attempts = 0; - - while (chest is null) - { - attempts++; - int x = WorldGen.genRand.Next(CheckCutoffDistance, BiomeWidth - CheckCutoffDistance); - if (!Abyss.AtLeftSideOfWorld) - { - x = Main.maxTilesX - x; - } - int y = WorldGen.genRand.Next(YStart + CheckCutoffDistance, YStart + BlockDepth - CheckCutoffDistance); - if (WorldGen.InWorld(x, y)) - { - if (!CalamityUtils.ParanoidTileRetrieval(x, y).HasTile && - SulphSeaTiles.Contains(CalamityUtils.ParanoidTileRetrieval(x, y + 1).TileType) && - CalamityUtils.ParanoidTileRetrieval(x, y + 1).HasTile) - { - chest = MiscWorldgenRoutines.AddChestWithLoot(x, y, (ushort)ModContent.TileType()); - } - } - - if (attempts >= 5000) - break; - } - - if (attempts >= 5000) - continue; - - // If a chest was placed, force its first item to be the unique item. - if (chest != null) - { - chest.item[0].SetDefaults(ItemTypes[i]); - chest.item[0].Prefix(-1); - } - } - } - #endregion - - #region Removal of stupid Tiles above the Sea - - public static List OtherTilesForSulphSeaToDestroy = new() - { - TileID.PalmTree, - TileID.Sunflower, - TileID.CorruptThorns, - TileID.CrimsonThorns, - TileID.CorruptGrass, - TileID.CorruptPlants, - TileID.Stalactite, - TileID.ImmatureHerbs, - TileID.MatureHerbs, - TileID.Pots, - TileID.Pumpkins, // Happens during Halloween - TileID.FallenLog, - TileID.LilyPad, - TileID.VanityTreeSakura, - TileID.VanityTreeYellowWillow - }; - - public static List WallsForSulphSeaToDestroy = new() - { - WallID.Dirt, - WallID.DirtUnsafe, - WallID.DirtUnsafe1, - WallID.DirtUnsafe2, - WallID.DirtUnsafe3, - WallID.DirtUnsafe4, - WallID.Cave6Unsafe, // Rocky dirt wall - WallID.Grass, - WallID.GrassUnsafe, - WallID.Flower, - WallID.FlowerUnsafe, - WallID.CorruptGrassUnsafe, - WallID.EbonstoneUnsafe, - WallID.CrimstoneUnsafe, - }; public static void RemoveStupidTilesAboveSea() { - for (int x = 0; x < BiomeWidth; x++) + for (int i = 0; i < BiomeWidth; i++) { - int trueX = Abyss.AtLeftSideOfWorld ? x : Main.maxTilesX - x; + int x = GetActualX(i); for (int y = YStart - 140; y < YStart + 80; y++) { - int type = CalamityUtils.ParanoidTileRetrieval(trueX, y).TileType; + int type = CalamityUtils.ParanoidTileRetrieval(x, y).TileType; if (YStartWhitelist.Contains(type) || OtherTilesForSulphSeaToDestroy.Contains(type)) + CalamityUtils.ParanoidTileRetrieval(x, y).Get().HasTile = false; + if (WallsForSulphSeaToDestroy.Contains(CalamityUtils.ParanoidTileRetrieval(x, y).WallType)) + CalamityUtils.ParanoidTileRetrieval(x, y).WallType = 0; + } + } + } + + public static void GenerateShallowTopWater() + { + int maxDepth = MaxTopWaterDepth; + int totalSandTilesBeforeWater = WorldGen.genRand.Next(TotalSandTilesBeforeWaterMin, TotalSandTilesBeforeWaterMax); + int width = (int)((BiomeWidth - totalSandTilesBeforeWater) * 0.42f); + float descentSmoothness = WorldGen.genRand.NextFloat(TopWaterDescentSmoothnessMin, TopWaterDescentSmoothnessMax); + for (int i = 1; i < width; i++) + { + int x = GetActualX(i); + + // Calculate the 0-1 factor that determines how far down a vertical strip of water should descend. + float depthFactor = (float)Math.Pow(Math.Sin((1f - i / (float)width) * MathHelper.PiOver2), descentSmoothness); + + // Determine the top and botton of the water strip. + int top = YStart; + int bottom = top + (int)(maxDepth * depthFactor); + for (int y = top; y < bottom; y++) + { + if (y >= top + DepthForWater) + Main.tile[x, y].LiquidAmount = byte.MaxValue; + Main.tile[x, y].Get().HasTile = false; + } + + // Clear water that's above the level for some reason. + for (int y = top - 150; y < top + DepthForWater; y++) + Main.tile[x, y].LiquidAmount = 0; + } + } + + public static void GenerateSmallWaterCaverns() + { + int width = BiomeWidth; + int depth = BlockDepth; + int shallowWaterCaveCount = TotalCavesInShallowWater; + int minCaveWidth = MinCaveWidth; + int maxCaveWidth = MaxCaveWidth; + ushort wallID = (ushort)ModContent.WallType(); + + for (int i = 0; i < shallowWaterCaveCount; i++) + { + // Initialize variables for the cave. + int caveHorizontalOffset = WorldGen.genRand.Next((int)(width * 0.1f)); + int x = GetActualX((int)MathHelper.Lerp(width * 0.8f, width * 0.24f, i / (float)(shallowWaterCaveCount - 1f)) + caveHorizontalOffset); + int caveWidth = (minCaveWidth + maxCaveWidth) / 3 + WorldGen.genRand.Next(8); + int caveSteps = WorldGen.genRand.Next(MinCaveMovementSteps, MaxCaveMovementSteps); + int caveSeed = WorldGen.genRand.Next(); + Vector2 baseCaveDirection = Vector2.UnitY.RotatedBy(WorldGen.genRand.NextFloatDirection() * 0.54f); + Vector2 cavePosition = new(x, YStart + MaxTopWaterDepth + DepthForWater / 2); + + for (int j = 0; j < caveSteps; j++) + { + // Make the cave direction turn based on perlin noise. + float caveOffsetAngleAtStep = CalamityUtils.PerlinNoise2D(i / 50f, j / 50f, 4, caveSeed) * MathHelper.Pi * 1.9f; + Vector2 caveDirection = baseCaveDirection.RotatedBy(caveOffsetAngleAtStep); + + // Carve out at the current position. + if (cavePosition.X < Main.maxTilesX - 15 && cavePosition.X >= 15) { - CalamityUtils.ParanoidTileRetrieval(trueX, y).Get().HasTile = false; + WorldGen.digTunnel(cavePosition.X, cavePosition.Y, caveDirection.X, caveDirection.Y, 1, (int)(caveWidth * 1.18f), true); + WorldUtils.Gen(cavePosition.ToPoint(), new Shapes.Circle(caveWidth), Actions.Chain(new GenAction[] + { + new Actions.ClearTile(true), + new Actions.PlaceWall(wallID, true), + new Actions.SetLiquid() + })); } - if (WallsForSulphSeaToDestroy.Contains(CalamityUtils.ParanoidTileRetrieval(trueX, y).WallType)) + + // Update the cave position. + cavePosition += caveDirection * caveWidth; + + // Turn back if the cave position is close to leaving the sea. + if (GetActualX((int)cavePosition.X) > width * 0.8f || cavePosition.Y > YStart + depth * 0.7f) { - CalamityUtils.ParanoidTileRetrieval(trueX, y).WallType = 0; + cavePosition.X -= Abyss.AtLeftSideOfWorld.ToDirectionInt() * caveWidth; + cavePosition.Y -= caveWidth; + } + + // Update the cave width for the next update step. + float caveWidthFactorInterpolant = (float)Math.Pow(WorldGen.genRand.NextFloat(), SmallCavesBiasTowardsTightness); + caveWidth = (int)Math.Round(caveWidth * MathHelper.Lerp(1f - SmallCavesJaggedness, 1f + SmallCavesJaggedness, caveWidthFactorInterpolant)); + if (WorldGen.genRand.NextBool(12)) + caveWidth = (int)(caveWidth * 1.4f); + + caveWidth = Utils.Clamp(caveWidth, minCaveWidth, maxCaveWidth); + } + } + } + + public static void GenerateSpaghettiWaterCaves() + { + int width = (int)(BiomeWidth * 0.96f); + int depth = (int)(BlockDepth * 0.9f); + ushort wallID = (ushort)ModContent.WallType(); + + for (int c = 0; c < SpaghettiCaveCarveOutThresholds.Length; c++) + { + int caveSeed = WorldGen.genRand.Next(10000000); + for (int i = 1; i < width; i++) + { + // Initialize variables for the cave. + int x = GetActualX(i); + for (int y = YStart; y < YStart + depth; y++) + { + float noise = FractalBrownianMotion(i * SpaghettiCaveMagnification, y * SpaghettiCaveMagnification, caveSeed, 5); + + // Bias noise away from 0, effectively making caves less likely to appear, based on how close it is to the bottom/horizontal edge. + // This causes caves to naturally stop as the reach ends instead of abruptly stopping like in the old Sulphurous Sea worldgen. + float biasAwayFrom0Interpolant = Utils.GetLerpValue(0.92f, 0.96f, i / (float)width, true) + Utils.GetLerpValue(0.86f, 0.9f, (y - YStart) / (float)depth, true); + + // If the noise is less than 0, bias to -1, if it's greater than 0, bias away to 1. + // This is done instead of biasing to -1 or 1 without exception to ensure that in doing so the noise does not cross into the + // cutout threshold near 0 as it interpolates. + noise = MathHelper.Lerp(noise, Math.Sign(noise), biasAwayFrom0Interpolant); + + if (Math.Abs(noise) < SpaghettiCaveCarveOutThresholds[c]) + { + WorldUtils.Gen(new(x, y), new Shapes.Rectangle(1, 1), Actions.Chain(new GenAction[] + { + new Actions.ClearTile(true), + new Actions.PlaceWall(wallID, true), + new Actions.SetLiquid() + })); + } } } } } - #endregion - #region Nearby Beach - public static readonly List ValidBeachCovertTiles = new() + public static void GenerateCheeseWaterCaves() { - TileID.Dirt, - TileID.Stone, - TileID.Crimstone, - TileID.Ebonstone, - TileID.Sand, - TileID.Ebonsand, - TileID.Crimsand, - TileID.Grass, - TileID.CorruptGrass, - TileID.CrimsonGrass, - TileID.ClayBlock, - TileID.Mud, - }; - public static readonly List ValidBeachDestroyTiles = new() - { - TileID.Coral, - TileID.BeachPiles, - TileID.Plants, - TileID.Plants2, - TileID.SmallPiles, - TileID.LargePiles, - TileID.LargePiles2, - TileID.CorruptThorns, - TileID.CrimsonThorns, - TileID.DyePlants, - TileID.Trees, - TileID.Sunflower, - }; - public static void CreateBeachNearSea() - { - int beachWidth = WorldGen.genRand.Next(150, 190 + 1); + int width = (int)(BiomeWidth * 0.9f); + int depth = (int)(BlockDepth * 0.9f); + ushort wallID = (ushort)ModContent.WallType(); - var searchCondition = Searches.Chain(new Searches.Down(3000), new Conditions.IsSolid()); - WorldUtils.Find(new Point(BiomeWidth + 4, (int)WorldGen.worldSurfaceLow - 20), searchCondition, out Point determinedPoint); - Tile tileAtEdge = CalamityUtils.ParanoidTileRetrieval(determinedPoint.X, determinedPoint.Y); - - // Extend outward to encompass some of the desert, if there is one. - if (tileAtEdge.TileType == TileID.Sand || - tileAtEdge.TileType == TileID.Ebonsand || - tileAtEdge.TileType == TileID.Crimsand) + for (int c = 0; c < CheeseCaveCarveOutThresholds.Length; c++) { - beachWidth += 85; - } - - for (int x = BiomeWidth - 10; x <= BiomeWidth + beachWidth; x++) - { - float xRatio = Utils.GetLerpValue(BiomeWidth - 10, BiomeWidth + beachWidth, x, true); - int trueX = Abyss.AtLeftSideOfWorld ? x : Main.maxTilesX - x; - int depth = (int)(Math.Sin((1f - xRatio) * MathHelper.PiOver2) * 45 + 1); - for (int y = YStart - 40; y < YStart + depth; y++) + int caveSeed = WorldGen.genRand.Next(10000000); + for (int i = 1; i < width; i++) { - Tile tileAtPosition = CalamityUtils.ParanoidTileRetrieval(trueX, y); - if (tileAtPosition.HasTile && ValidBeachDestroyTiles.Contains(tileAtPosition.TileType)) + // Initialize variables for the cave. + int x = GetActualX(i); + for (int y = YStart; y < YStart + depth; y++) { - // Kill trees manually so that no leftover tiles are present. - if (Main.tile[trueX, y].TileType == TileID.Trees) - WorldGen.KillTile(trueX, y); - else - Main.tile[trueX, y].Get().HasTile = false; - } - - else if (tileAtPosition.HasTile && ValidBeachCovertTiles.Contains(tileAtPosition.TileType)) - { - Main.tile[trueX, y].TileType = (ushort)ModContent.TileType(); + float noise = FractalBrownianMotion(i * CheeseCaveMagnification, y * CheeseCaveMagnification, caveSeed, 6); + float biasToNegativeOneInterpolant = Utils.GetLerpValue(0.86f, 0.9f, i / (float)width, true) + Utils.GetLerpValue(0.86f, 0.9f, (y - YStart) / (float)depth, true); + biasToNegativeOneInterpolant += Utils.GetLerpValue(YStart + OpenCavernStartDepthPercentage * depth, YStart + OpenCavernStartDepthPercentage * depth - 25f, y, true); + if (noise - biasToNegativeOneInterpolant * 6f > CheeseCaveCarveOutThresholds[c]) + { + WorldUtils.Gen(new(x, y), new Shapes.Rectangle(1, 1), Actions.Chain(new GenAction[] + { + new Actions.ClearTile(true), + new Actions.PlaceWall(wallID, true), + new Actions.SetLiquid() + })); + } } } } - - // Plant new trees. - for (int x = BiomeWidth - 10; x <= BiomeWidth + beachWidth; x++) - { - int trueX = Abyss.AtLeftSideOfWorld ? x : Main.maxTilesX - x; - if (!WorldGen.genRand.NextBool(10)) - continue; - - int y = YStart - 30; - if (!WorldUtils.Find(new Point(trueX, y), Searches.Chain(new Searches.Down(100), new Conditions.IsTile((ushort)ModContent.TileType())), out Point treePlantPosition)) - continue; - - WorldGen.PlaceTile(treePlantPosition.X, treePlantPosition.Y - 1, ModContent.TileType()); - } } - #endregion - #region Scrap Piles - public static void PlaceScrapPiles() + public static void ClearOutStrayTiles() { - int tries = 0; - List pastPlacementPostiion = new List(); - for (int i = 0; i < 3; i++) + int width = BiomeWidth; + int depth = BlockDepth; + ushort blockTileType = (ushort)ModContent.TileType(); + ushort wallID = (ushort)ModContent.WallType(); + + void recursivelyGetAttachedPoints(int x, int y, List points) { - tries++; - if (tries > 20000) - continue; + Tile t = CalamityUtils.ParanoidTileRetrieval(x, y); + Point p = new(x, y); + if (t.TileType != blockTileType || !t.HasTile || points.Count > 512 || points.Contains(p)) + return; - int x = WorldGen.genRand.Next(75, BiomeWidth - 85); - if (!Abyss.AtLeftSideOfWorld) - x = Main.maxTilesX - x; - int y = WorldGen.genRand.Next(YStart + (int)(BlockDepth * 0.3f), YStart + (int)(BlockDepth * 0.8f)); + points.Add(p); - Point pilePlacementPosition = new Point(x, y); + recursivelyGetAttachedPoints(x + 1, y, points); + recursivelyGetAttachedPoints(x - 1, y, points); + recursivelyGetAttachedPoints(x, y + 1, points); + recursivelyGetAttachedPoints(x, y - 1, points); + } - // If the selected position is sitting inside of a tile, try again. - if (WorldGen.SolidTile(pilePlacementPosition.X, pilePlacementPosition.Y)) + + // Clear out stray chunks created by caverns. + for (int i = 1; i < width; i++) + { + int x = GetActualX(i); + for (int y = YStart; y < YStart + depth; y++) { - i--; - continue; + List chunkPoints = new(); + recursivelyGetAttachedPoints(x, y, chunkPoints); + + int cutoffLimit = y >= YStart + depth * OpenCavernStartDepthPercentage ? 512 : 50; + if (chunkPoints.Count >= 2 && chunkPoints.Count < cutoffLimit) + { + foreach (Point p in chunkPoints) + { + WorldUtils.Gen(p, new Shapes.Rectangle(1, 1), Actions.Chain(new GenAction[] + { + new Actions.ClearTile(true), + new Actions.PlaceWall(wallID, true), + new Actions.SetLiquid() + })); + } + } } - - // If the selected position is close to other piles, try again. - if (pastPlacementPostiion.Any(p => Vector2.Distance(p, pilePlacementPosition.ToVector2()) < 85f)) - { - i--; - continue; - } - - // Otherwise, decide which pile should be created. - int pileVariant = WorldGen.genRand.Next(7); - string schematicName = $"Sulphurous Scrap {pileVariant + 1}"; - Vector2? wrappedSchematicArea = SchematicManager.GetSchematicArea(schematicName); - - // Create a log message if for some reason the schematic in question doesn't exist. - if (!wrappedSchematicArea.HasValue) - { - CalamityMod.Instance.Logger.Warn($"Tried to place a schematic with name \"{schematicName}\". No matching schematic file found."); - continue; - } - - Vector2 schematicArea = wrappedSchematicArea.Value; - - // Decide the placement position by searching downward and looking for the lowest point. - // If the position is quite steep, try again. - Vector2 left = pilePlacementPosition.ToVector2() - Vector2.UnitX * schematicArea.X * 0.5f; - Vector2 right = pilePlacementPosition.ToVector2() + Vector2.UnitX * schematicArea.X * 0.5f; - while (!WorldGen.SolidTile(CalamityUtils.ParanoidTileRetrieval((int)left.X, (int)left.Y))) - left.Y++; - while (!WorldGen.SolidTile(CalamityUtils.ParanoidTileRetrieval((int)right.X, (int)right.Y))) - right.Y++; - - if (Math.Abs(left.Y - right.Y) >= 20f) - { - i--; - continue; - } - - // If the placement position ended up in the abyss, try again. - if (left.Y >= YStart + BlockDepth + 5 || right.Y >= YStart + BlockDepth + 5) - { - i--; - continue; - } - - // Pick the lowest point vertically. - Point bottomCenter = new Point(pilePlacementPosition.X, (int)Math.Max(left.Y, right.Y) + 6); - bool _ = false; - SchematicManager.PlaceSchematic>(schematicName, bottomCenter, SchematicAnchor.BottomCenter, ref _); - - pastPlacementPostiion.Add(bottomCenter.ToVector2()); - tries = 0; } } - #endregion Scrap Piles + + public static void DecideHardSandstoneLine() + { + int width = BiomeWidth; + int depth = BlockDepth; + + int sandstoneSeed = WorldGen.genRand.Next(); + ushort blockTypeToReplace = (ushort)ModContent.TileType(); + ushort blockTypeToPlace = (ushort)ModContent.TileType(); + ushort wallID = (ushort)ModContent.WallType(); + for (int i = 0; i < width; i++) + { + for (int y = YStart; y < YStart + depth; y++) + { + int sandstoneLineOffset = (int)(FractalBrownianMotion(i * 0.004f, y * 0.004f, sandstoneSeed, 7) * 30) + depth / 2; + + // Make the sandstone line descent a little bit the closer it is to the world edge, to make it look like it "warps" towards the abyss. + sandstoneLineOffset -= (int)(Math.Pow(Utils.GetLerpValue(width * 0.1f, width * 0.8f, i, true), 1.72f) * 45f); + + Point p = new(GetActualX(i), y); + Tile t = CalamityUtils.ParanoidTileRetrieval(p.X, p.Y); + if (y >= YStart + sandstoneLineOffset && t.HasTile && t.TileType == blockTypeToReplace) + { + WorldUtils.Gen(p, new Shapes.Rectangle(1, 1), Actions.Chain(new GenAction[] + { + new Actions.SetTile(blockTypeToPlace, true), + new Actions.PlaceWall(wallID, true), + new Actions.SetLiquid() + })); + } + } + } + } + #endregion Generation Functions #region Misc Functions - public static List YStartWhitelist = new() + public static readonly List YStartWhitelist = new() { TileID.Stone, TileID.Dirt, @@ -952,11 +490,60 @@ namespace CalamityMod.World TileID.CrimsonVines, TileID.Containers, TileID.DyePlants, - TileID.JungleGrass // Yes, this can happen on rare occasion + TileID.JungleGrass, // Yes, this can happen on rare occasion. + TileID.SeaOats }; + + public static readonly List OtherTilesForSulphSeaToDestroy = new() + { + TileID.PalmTree, + TileID.Sunflower, + TileID.CorruptThorns, + TileID.CrimsonThorns, + TileID.CorruptGrass, + TileID.CorruptPlants, + TileID.Stalactite, + TileID.ImmatureHerbs, + TileID.MatureHerbs, + TileID.Pots, + TileID.Pumpkins, // Happens during Halloween + TileID.FallenLog, + TileID.LilyPad, + TileID.VanityTreeSakura, + TileID.VanityTreeYellowWillow, + TileID.ShellPile + }; + + public static readonly List WallsForSulphSeaToDestroy = new() + { + WallID.Dirt, + WallID.DirtUnsafe, + WallID.DirtUnsafe1, + WallID.DirtUnsafe2, + WallID.DirtUnsafe3, + WallID.DirtUnsafe4, + WallID.Cave6Unsafe, // Rocky dirt wall + WallID.Grass, + WallID.GrassUnsafe, + WallID.Flower, + WallID.FlowerUnsafe, + WallID.CorruptGrassUnsafe, + WallID.EbonstoneUnsafe, + WallID.CrimstoneUnsafe, + }; + + // This method is an involutory function, meaning that applying it to the same number twice always yields the original number. + public static int GetActualX(int x) + { + if (Abyss.AtLeftSideOfWorld) + return x; + + return Main.maxTilesX - x; + } + public static void DetermineYStart() { - int xCheckPosition = Abyss.AtLeftSideOfWorld ? BiomeWidth + 1 : Main.maxTilesX - BiomeWidth - 1; + int xCheckPosition = GetActualX(BiomeWidth + 1); var searchCondition = Searches.Chain(new Searches.Down(3000), new Conditions.IsSolid()); Point determinedPoint; @@ -968,6 +555,41 @@ namespace CalamityMod.World while (CalamityUtils.ParanoidTileRetrieval(determinedPoint.X, determinedPoint.Y).TileType == TileID.Ebonstone); YStart = determinedPoint.Y; } + + public static float CalculateDitherChance(int width, int top, int bottom, int x, int y) + { + float verticalCompletion = Utils.GetLerpValue(top, bottom, y, true); + float horizontalDitherChance = Utils.GetLerpValue(DitherStartFactor, 1f, x / (float)width, true); + float verticalDitherChance = Utils.GetLerpValue(DitherStartFactor, 1f, verticalCompletion, true); + float ditherChance = horizontalDitherChance + verticalDitherChance; + if (ditherChance > 1f) + ditherChance = 1f; + + // Make the dither chance fizzle out at low vertical completion values. + // This is done so that there isn't dithering on the surface of the sea. + ditherChance -= Utils.GetLerpValue(0.56f, 0.5f, verticalCompletion, true); + if (ditherChance < 0f) + ditherChance = 0f; + return ditherChance; + } + + public static float FractalBrownianMotion(float x, float y, int seed, int octaves, float gain = 0.5f, float lacunarity = 2f) + { + float result = 0f; + float frequency = 1f; + float amplitude = 0.5f; + x += seed * 0.00489937f % 10f; + + for (int i = 0; i < octaves; i++) + { + float noise = NoiseHelper.GetStaticNoise(new Vector2(x, y) * frequency) * 2f - 1f; + result += noise * amplitude; + amplitude *= gain; + frequency *= lacunarity; + } + + return result; + } #endregion } }