IEnumerator Shake(bool crit) { float magnitude = crit ? shakeBaseMagnitude * critShakeMultiplier : shakeBaseMagnitude; float elapsed = 0.0f; Vector3 originalCamPos = cam.transform.position; float randomStart = UnityEngine.Random.Range(-1000.0f, 1000.0f); while (elapsed < shakeDuration) { elapsed += Time.deltaTime; float percentComplete = elapsed / shakeDuration; // to reduce the shaking magnitude from full power to 0, beginning from halfway the shaking duration float damper = 1.0f - Mathf.Clamp(2.0f * percentComplete - 1.0f, 0.0f, 1.0f); float alpha = randomStart + shakeSpeed * percentComplete; // map value to [-1, 1], that smoothly change thanks to Perlin noise float x = SimplexNoise.Noise(alpha, 0); float y = SimplexNoise.Noise(0, alpha); //float x = Mathf.PerlinNoise(alpha, 0); //float y = Mathf.PerlinNoise(0, alpha); x *= magnitude * damper; y *= magnitude * damper; cam.transform.position = new Vector3(originalCamPos.x + x, originalCamPos.y + y, originalCamPos.z); yield return(null); } cam.transform.position = originalCamPos; }
public virtual void RegenCloudTileCache(Vec3i tileOffset) { tilesPerRegion = (int)Math.Ceiling((float)api.World.BlockAccessor.RegionSize / ws.CloudTileSize) + 2 * NoisePadding; CloudDensityNoiseCache = new double[tilesPerRegion, tilesPerRegion]; lastTileX = cloudTilebasePosX + tileOffset.X; lastTileZ = cloudTilebasePosZ + tileOffset.Z; double timeAxis = api.World.Calendar.TotalDays / 10.0; if (LocationalCloudThicknessGen == null) { for (int dx = 0; dx < tilesPerRegion; dx++) { for (int dz = 0; dz < tilesPerRegion; dz++) { CloudDensityNoiseCache[dx, dz] = 0; } } } else { for (int dx = 0; dx < tilesPerRegion; dx++) { for (int dz = 0; dz < tilesPerRegion; dz++) { double x = (lastTileX + dx - tilesPerRegion / 2 - NoisePadding) / 20.0; double z = (lastTileZ + dz - tilesPerRegion / 2 - NoisePadding) / 20.0; CloudDensityNoiseCache[dx, dz] = GameMath.Clamp(LocationalCloudThicknessGen.Noise(x, z, timeAxis), 0, 1); } } } }
void CreateTexture() { Debug.Log("Creating Texture"); Texture2D texture = new Texture2D(Width, Height); Color[] col_map = new Color[Width * Height]; for (int y = 0; y < Height; y++) { for (int x = 0; x < Width; x++) { if (SimplexNoise.Noise(x / NoiseScale, y / NoiseScale, Depth / NoiseScale * 8) > SolidThreshold) { col_map[y * Width + x] = LayerColor; } else { col_map[y * Width + x] = Color.clear; } } } texture.SetPixels(col_map); texture.Apply(); Sprite s = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f), 100.0f); textureRenderer.sprite = s; // textureRenderer.transform.localScale = new Vector3(Width, Height, 1); }
public float GetTemporalStability(double x, double y, double z) { if (!temporalStabilityEnabled) { return(2); } float noiseval = (float)GameMath.Clamp(stabilityNoise.Noise(x / 80, y / 80, z / 80) * 1.2f + 0.1f, -1f, 2f); float sealLevelDistance = (float)(TerraGenConfig.seaLevel - y); // The deeper you go, the more the stability varies. Surface 100% to 80%. Deep below down 100% to 0% float surfacenoiseval = GameMath.Clamp(1.6f + noiseval, 0.8f, 1.5f); float l = (float)GameMath.Clamp(Math.Pow(Math.Max(0, (float)y) / TerraGenConfig.seaLevel, 2), 0, 1); noiseval = GameMath.Mix(noiseval, surfacenoiseval, l); // The deeper you go, the lower the stability. Up to -25% stability noiseval -= Math.Max(0, sealLevelDistance / api.World.BlockAccessor.MapSizeY) / 3.5f; noiseval = GameMath.Clamp(noiseval, 0, 1.5f); float extraStr = 1.5f * GetGlitchEffectExtraStrength(); return(GameMath.Clamp(noiseval - extraStr, 0, 1.5f)); }
public void PopulateNoiseMap(bool[,] mazeGrid) { int iMaze = 0; int jMaze = 0; for (int i = 0; i < 300; i++) { for (int j = 0; j < 300; j++) { weight1 = (float)(0.5f + SimplexNoise.Noise(i * xSmoothingCoef * zScale, 0, j * zSmoothingCoef * zScale)); if (mazeGrid[iMaze, jMaze]) { noiseMap[i, j] = weight1 * 0.1f; } else { noiseMap[i, j] = weight1 * 0.9f; } if (j != 0 && j % 10 == 9) { jMaze++; } } jMaze = 0; if (i != 0 && i % 10 == 9) { iMaze++; } } }
double[] GetTerrainNoise3D(double[] octX0, double[] octX1, double[] octX2, double[] octX3, double[] octThX0, double[] octThX1, double[] octThX2, double[] octThX3, int xPos, int yPos, int zPos) { for (int x = 0; x < paddedNoiseWidth; x++) { for (int z = 0; z < paddedNoiseWidth; z++) { for (int i = 0; i < TerraGenConfig.terrainGenOctaves; i++) { lerpedAmps[i] = GameMath.BiLerp(octX0[i], octX1[i], octX2[i], octX3[i], (double)x / paddedNoiseWidth, (double)z / paddedNoiseWidth); lerpedTh[i] = GameMath.BiLerp(octThX0[i], octThX1[i], octThX2[i], octThX3[i], (double)x / paddedNoiseWidth, (double)z / paddedNoiseWidth); } float distx = (float)distort2dx.Noise(xPos + x, zPos + z); float distz = (float)distort2dz.Noise(xPos + x, zPos + z); for (int y = 0; y < paddedNoiseHeight; y++) { noiseTemp[NoiseIndex3d(x, y, z)] = TerrainNoise.Noise( (xPos + x) + (distx > 0 ? Math.Max(0, distx - 10) : Math.Min(0, distx + 10)), (yPos + y) / TerraGenConfig.terrainNoiseVerticalScale, (zPos + z) + (distz > 0 ? Math.Max(0, distz - 10) : Math.Min(0, distz + 10)), lerpedAmps, lerpedTh ); } } } return(noiseTemp); }
private float[] GenerateHeightMap(WorldGenData data, int chunkX, int chunkY, int seedX, int seedY) { float[] heightMap = new float[data.chunkSize * data.chunkSize]; float layerFrequency = data.layerFrequency; float layerWeight = data.layerWeight; for (int octave = 0; octave < data.octaves; octave++) { for (int y = 0; y < data.chunkSize; y++) { for (int x = 0; x < data.chunkSize; x++) { float inputX = chunkX * data.chunkSize + x + seedX; float inputY = chunkY * data.chunkSize + y + seedY; float noise = data.layerWeight * SimplexNoise.Noise(inputX * layerFrequency, inputY * layerFrequency); heightMap[x + y * data.chunkSize] += noise; } } layerFrequency *= 2.0f; layerWeight *= data.roughness; } return(heightMap); }
public virtual void Update(float dt) { if (strengthNoiseGen != null) { double timeAxis = api.World.Calendar.TotalDays / 10.0; Strength = State.BaseStrength + (float)GameMath.Clamp(strengthNoiseGen.Noise(0, timeAxis), 0, 1); } }
float getPrecipNoise(double posX, double posZ, double totalDays, float wgenRain) { return((float)GameMath.Max( precipitationNoise.Noise(posX / 9 / 2 + totalDays * 18, posZ / 9 / 2, totalDays * 4) * 1.6f - GameMath.Clamp(precipitationNoiseSub.Noise(posX / 4 / 2 + totalDays * 24, posZ / 4 / 2, totalDays * 6) * 5 - 1 - wgenRain, 0, 1) + wgenRain, 0 )); }
private static void CalculateNoise(int i) { var simplexNoise = new SimplexNoise(); for (int j = 0; j < NumberOfCalculations; j++) { var noise = simplexNoise.Noise(i, i, i); } }
/// <summary> /// Returns the noise at the given position. /// </summary> /// <returns>The noise at the position.</returns> /// <param name="position">Position.</param> public Vector3 NoiseForPosition(Vector3 position) { Vector3 scaled = Vector3.Scale(position, m_Frequency); Vector3 offset = scaled + m_Phase; // I'm cheating. SimplexNoise returns floats for given positions, so I offset each axis by // an arbitrary value to get asynchronous results. return(new Vector3((float)SimplexNoise.Noise(offset.x, offset.y, offset.z, X_OFFSET), (float)SimplexNoise.Noise(offset.x, offset.y, offset.z, Y_OFFSET), (float)SimplexNoise.Noise(offset.x, offset.y, offset.z, Z_OFFSET))); }
private void updateTemperature(ref ClimateCondition climate, BlockPos pos, double yearRel, double hourOfDay, double totalDays) { // 1. Global average temperature at this location double heretemp = climate.Temperature; // 2. season based temperature // - Near the equator the variation seems to be only 5-10 degrees // - In european cities the per month average temperature seem to vary by about 20 degrees (~ 0 - 20) // - Above the arctic circle it seems to vary by up to 60 degrees (~ -39 - 20) // -1 for south pole, 0 for equater, 1 for north pole double latitude = coreSys.onGetLatitude(pos.Z); double seasonalVariationAmplitude = Math.Abs(latitude) * 65; heretemp -= seasonalVariationAmplitude / 2; // 1 to 0 => january is coldest month // 0 to -1 => july is coldest month if (latitude > 0) { double distanceToJanuary = GameMath.Smootherstep(Math.Abs(GameMath.CyclicValueDistance(0.5f, yearRel * 12, 12) / 6f)); heretemp += seasonalVariationAmplitude * distanceToJanuary; } else { double distanceToJuly = GameMath.Smootherstep(Math.Abs(GameMath.CyclicValueDistance(6.5f, yearRel * 12, 12) / 6f)); heretemp += seasonalVariationAmplitude * distanceToJuly; } // 3. diurnal temperature variation: // https://en.wikipedia.org/wiki/Diurnal_temperature_variation // Lets define the variation strength as 5 + rainFall * 10 double diurnalVariationAmplitude = 20 - climate.Rainfall * 8; // variation is then further reduced by the distance from the equator (because at the equator the day/night cycle is most intense, and thus the warming/cooling effects more pronounced) diurnalVariationAmplitude *= (0.2 + 0.8 * Math.Abs(latitude)); // just before sunrise is the coldest time. We have no time zones in VS // lets just hardcode 6 am for this for now double distanceTo6Am = GameMath.SmoothStep(Math.Abs(GameMath.CyclicValueDistance(6, hourOfDay, 24) / 12f)); heretemp -= diurnalVariationAmplitude / 2; heretemp += distanceTo6Am * diurnalVariationAmplitude; // 4. Yearly random noise heretemp += YearlyTemperatureNoise.Noise(totalDays, 0) * 3; // 5. Daily random noise heretemp += DailyTemperatureNoise.Noise(totalDays, 0); climate.Temperature = (float)heretemp; }
public override int[] GenLayer(int xCoord, int zCoord, int sizeX, int sizeZ) { int[] outData = new int[sizeX * sizeZ]; for (int z = 0; z < sizeZ; ++z) { for (int x = 0; x < sizeX; ++x) { outData[z * sizeX + x] = (int)GameMath.Clamp(noisegen.Noise(xCoord + x, zCoord + z, thresholds), clampMin, clampMax); } } return(outData); }
// Given a world tile x and tile z this generates a Tile object. private Tile GenerateTile(int x, int z) { GameObject plane = (GameObject)Instantiate(terrainPlane, new Vector3(x * planeSize, 0, z * planeSize), Quaternion.identity); plane.SetActive(true); // Fix for tiling float tiling = singlePlaneSize / 20f; plane.GetComponent <Renderer>().material.SetTextureScale("_MainTex", new Vector2(tiling, tiling)); plane.transform.localScale = new Vector3(planeSize * 0.1f, 1, planeSize * 0.1f); plane.transform.parent = transform; // Get the planes vertices Mesh mesh = plane.GetComponent <MeshFilter>().mesh; Vector3[] vertices = mesh.vertices; // alter vertex Y position depending on simplex noise) for (int v = 0; v < vertices.Length; v++) { // generate the height for current vertex Vector3 vertexPosition = plane.transform.position + vertices[v] * planeSize / 10f; float height = SimplexNoise.Noise(vertexPosition.x * detailScale, vertexPosition.z * detailScale); // scale it with the heightScale field vertices[v].y = height * heightScale; } mesh.vertices = vertices; mesh.RecalculateBounds(); mesh.RecalculateNormals(); plane.AddComponent <MeshCollider>(); Tile tile = new Tile(); tile.gameObject = plane; tile.tileX = x; tile.tileZ = z; return(tile); }
static void Main(string[] args) { var noise = new SimplexNoise(); var operationTimer = new OperationTimer(); var elapsedTime = operationTimer.TimeOperation(() => { const int upperLimit = NumberOfCalculations * Iterations; for (int i = 0; i < upperLimit; i++) { var d = noise.Noise(i, i, i); } }); Console.WriteLine(elapsedTime.TotalSeconds); elapsedTime = operationTimer.TimeOperation(() => Parallel.For(0, Iterations, CalculateNoise)); Console.WriteLine(elapsedTime.TotalSeconds); }
private void CreateHeightMap() { heightMap = new int[result.GetXzDimension(), result.GetXzDimension()]; for (int i = 0; i < result.GetXzDimension(); i++) { for (int j = 0; j < result.GetXzDimension(); j++) { float scaledI = (i + 7023) * 4 / 16384.0f; float scaledJ = (j + 4359) * 4 / 16384.0f; float scaledI2 = (i + 4067) * 8 / 8192.0f; float scaledJ2 = (j + 6638) * 8 / 8192.0f; float scaledI3 = (i + 7650) * 16 / 4096.0f; float scaledJ3 = (j + 4014) * 16 / 4096.0f; float scaledI4 = (i + 7648) * 32 / 2048.0f; float scaledJ4 = (j + 3730) * 32 / 2048.0f; float scaledI5 = (i + 7066) * 64 / 1024.0f; float scaledJ5 = (j + 149) * 64 / 1024.0f; float scaledI6 = (i + 1399) * 128 / 512.0f; float scaledJ6 = (j + 9036) * 128 / 512.0f; float normalizedNoise = (float)((SimplexNoise.Noise(scaledI, scaledJ) + 1) * 0.5f); float normalizedNoise2 = (float)((SimplexNoise.Noise(scaledI2, scaledJ2) + 1) * 0.25f); float normalizedNoise3 = (float)((SimplexNoise.Noise(scaledI3, scaledJ3) + 1) * 0.125f); float normalizedNoise4 = (float)((SimplexNoise.Noise(scaledI4, scaledJ4) + 1) * 0.0625f); float normalizedNoise5 = (float)((SimplexNoise.Noise(scaledI5, scaledJ5) + 1) * 0.03125f); float normalizedNoise6 = (float)((SimplexNoise.Noise(scaledI6, scaledJ6) + 1) * 0.015625f); float finalNoise = (normalizedNoise + normalizedNoise2 + normalizedNoise3 + normalizedNoise4 + normalizedNoise5 + normalizedNoise6) / 6.0f; float redistirbutedNoise = Mathf.Pow(finalNoise, 2.0f); heightMap[i, j] = Mathf.CeilToInt(redistirbutedNoise * Island.HEIGHT_IN_BLOCKS); } } }
void ApplyNoiseToHeightmap(int max_iterations, float _length, float _power, float[,] hmHandle, float offset = 0.0f) { float power = _power; float length = _length; for (int i = 0; i < max_iterations; i++) { for (int z = 0; z < caveHMWidthZ; z++) { for (int x = 0; x < caveHMWidthX; x++) { float u = (float)x / (float)caveHMWidthX; float v = (float)z / (float)caveHMWidthZ; float changeFromNoise = (float)myNoise.Noise((u + offset) * length, (v + offset) * length); changeFromNoise *= caveHeightmapSrc[x, z]; hmHandle[x, z] += changeFromNoise * power; } } power /= 2.0f; length *= 2.0f; } }
/// <summary> /// Generates the noise texture. /// </summary> /// <param name="texture">Texture.</param> /// <param name="frequency">Frequency.</param> /// <param name="phase">Phase.</param> private void GenerateNoise(Texture2D texture, Vector3 frequency, Vector3 phase) { Array.Resize(ref s_Pixels, texture.width * texture.height); int index = 0; for (int y = 0; y < texture.height; y++) { for (int x = 0; x < texture.width; x++) { Vector3 scaled = Vector3.Scale(new Vector3(x, y, 1), frequency); Vector3 offset = scaled + phase; float noise = (float)SimplexNoise.Noise(offset.x, offset.y, offset.z); noise = (noise + 1.0f) / 2.0f; s_Pixels[index] = new Color(noise, noise, noise); index++; } } texture.SetPixels(s_Pixels); texture.Apply(); }
public virtual void RegenNoiseCache() { int len = ws.CloudTileLength; CloudDensityNoiseCache = new double[len, len]; CloudOffsetYNoiseCache = new double[len, len]; lastTileX = ws.CloudTileX; lastTileZ = ws.CloudTileZ; double timeAxis = api.World.Calendar.TotalDays / 10.0; for (int dx = 0; dx < len; dx++) { for (int dz = 0; dz < len; dz++) { double x = (lastTileX + dx - len / 2) / 20.0; double z = (lastTileZ + dz - len / 2) / 20.0; CloudDensityNoiseCache[dx, dz] = CloudDensityNoise.Noise(x, z, timeAxis) / 2; CloudOffsetYNoiseCache[dx, dz] = CloudOffsetYNoise.Noise(x, z, timeAxis) / 2; } } }
void LoadNoisePoints(IntVector4 node, int minCount, int maxCount) { int nx = node.x >> VoxelTerrainConstants._shift >> node.w; int nz = node.z >> VoxelTerrainConstants._shift >> node.w; float noise = (float)mNoise.Noise(nx, nz, nx + nz); int randomCount = Mathf.FloorToInt((maxCount - minCount) * noise); int count = Mathf.Clamp(minCount + randomCount, minCount, maxCount); int length = VoxelTerrainConstants._numVoxelsPerAxis << node.w; for (int i = 0; i < count; i++) { float ox = (float)mNoise.Noise(nx, (nx + nz) * i) * 0.5f + 0.5f; float oz = (float)mNoise.Noise(nz, (nx - nz) * i) * 0.5f + 0.5f; Vector3 pos = new Vector3(node.x + ox * length, node.y, node.z + oz * length); Quaternion rot = Quaternion.Euler(0.0f, UnityEngine.Random.Range(0, 360), 0.0f); SPPoint point = SPPoint.InstantiateSPPoint <SPPoint>(pos, rot, nextIndex, transform, 0, 0, true, true, false, true, true, mNoise); point.name = "Noise : " + point.name; RegisterSPPoint(point); //Debug.LogError("Noise normal ai point : " + pos); } }
public void genBlockColumn(IServerChunk[] chunks, int chunkX, int chunkZ, int lx, int lz) { int surfaceY = heightMap[lz * chunksize + lx]; int ylower = 1; int yupper = surfaceY; strataThickness = 0; WeightedIndex[] indices = map[ chunkInRegionX + lx * lerpMapInv, chunkInRegionZ + lz * lerpMapInv ]; rockGroupMaxThickness[0] = rockGroupMaxThickness[1] = rockGroupMaxThickness[2] = rockGroupMaxThickness[3] = 0; rockGroupCurrentThickness[0] = rockGroupCurrentThickness[1] = rockGroupCurrentThickness[2] = rockGroupCurrentThickness[3] = 0; for (int i = 0; i < indices.Length; i++) { float w = indices[i].Weight; GeologicProvinceVariant var = provinces.Variants[indices[i].Index]; rockGroupMaxThickness[0] += var.RockStrataIndexed[0].MaxThickness * w; rockGroupMaxThickness[1] += var.RockStrataIndexed[1].MaxThickness * w; rockGroupMaxThickness[2] += var.RockStrataIndexed[2].MaxThickness * w; rockGroupMaxThickness[3] += var.RockStrataIndexed[3].MaxThickness * w; } float distx = (float)distort2dx.Noise(chunkX * chunksize + lx, chunkZ * chunksize + lz); float distz = (float)distort2dz.Noise(chunkX * chunksize + lx, chunkZ * chunksize + lz); rockStrataId = -1; while (ylower <= yupper) { if (--strataThickness <= 0) { rockStrataId++; if (rockStrataId >= strata.Variants.Length) { break; } stratum = strata.Variants[rockStrataId]; rockMap = mapChunk.MapRegion.RockStrata[rockStrataId]; step = (float)rockMap.InnerSize / regionChunkSize; grp = (int)stratum.RockGroup; float thicknessDistort = GameMath.Clamp((distx + distz) / 30, 0.9f, 1.1f); float allowedThickness = rockGroupMaxThickness[grp] * thicknessDistort - rockGroupCurrentThickness[grp]; strataThickness = Math.Min(allowedThickness, rockMap.GetIntLerpedCorrectly(rdx * step + step * (float)(lx + distx) / chunksize, rdz * step + step * (float)(lz + distz) / chunksize)); strataThickness -= (stratum.RockGroup == EnumRockGroup.Sedimentary) ? Math.Max(0, yupper - TerraGenConfig.seaLevel) * 0.5f : 0; if (strataThickness < 2) { strataThickness = -1; continue; } } rockGroupCurrentThickness[grp]++; if (stratum.GenDir == EnumStratumGenDir.BottomUp) { int chunkY = ylower / chunksize; int lY = ylower - chunkY * chunksize; int localIndex3D = (chunksize * lY + lz) * chunksize + lx; if (chunks[chunkY].Blocks[localIndex3D] == rockBlockId) { chunks[chunkY].Blocks[localIndex3D] = stratum.BlockId; } ylower++; } else { int chunkY = yupper / chunksize; int lY = yupper - chunkY * chunksize; int localIndex3D = (chunksize * lY + lz) * chunksize + lx; if (chunks[chunkY].Blocks[localIndex3D] == rockBlockId) { chunks[chunkY].Blocks[localIndex3D] = stratum.BlockId; } yupper--; } } }
private void OnChunkColumnGeneration(IServerChunk[] chunks, int chunkX, int chunkZ, ITreeAttribute chunkGenParams = null) { rnd.InitPositionSeed(chunkX, chunkZ); IntDataMap2D forestMap = chunks[0].MapChunk.MapRegion.ForestMap; IntDataMap2D climateMap = chunks[0].MapChunk.MapRegion.ClimateMap; IntDataMap2D beachMap = chunks[0].MapChunk.MapRegion.BeachMap; ushort[] heightMap = chunks[0].MapChunk.RainHeightMap; int regionChunkSize = api.WorldManager.RegionSize / chunksize; int rdx = chunkX % regionChunkSize; int rdz = chunkZ % regionChunkSize; // Amount of data points per chunk float climateStep = (float)climateMap.InnerSize / regionChunkSize; float forestStep = (float)forestMap.InnerSize / regionChunkSize; float beachStep = (float)beachMap.InnerSize / regionChunkSize; // Retrieves the map data on the chunk edges int forestUpLeft = forestMap.GetUnpaddedInt((int)(rdx * forestStep), (int)(rdz * forestStep)); int forestUpRight = forestMap.GetUnpaddedInt((int)(rdx * forestStep + forestStep), (int)(rdz * forestStep)); int forestBotLeft = forestMap.GetUnpaddedInt((int)(rdx * forestStep), (int)(rdz * forestStep + forestStep)); int forestBotRight = forestMap.GetUnpaddedInt((int)(rdx * forestStep + forestStep), (int)(rdz * forestStep + forestStep)); int beachUpLeft = beachMap.GetUnpaddedInt((int)(rdx * beachStep), (int)(rdz * beachStep)); int beachUpRight = beachMap.GetUnpaddedInt((int)(rdx * beachStep + beachStep), (int)(rdz * beachStep)); int beachBotLeft = beachMap.GetUnpaddedInt((int)(rdx * beachStep), (int)(rdz * beachStep + beachStep)); int beachBotRight = beachMap.GetUnpaddedInt((int)(rdx * beachStep + beachStep), (int)(rdz * beachStep + beachStep)); // increasing x -> left to right // increasing z -> top to bottom float transitionSize = blockLayerConfig.blockLayerTransitionSize; for (int x = 0; x < chunksize; x++) { for (int z = 0; z < chunksize; z++) { // Some weird randomnes stuff to hide fundamental bugs in the climate transition system :D T_T (maybe not bugs but just fundamental shortcomings of using lerp on a very low resolution map) float distx = (float)distort2dx.Noise(chunkX * chunksize + x, chunkZ * chunksize + z); float distz = (float)distort2dz.Noise(chunkX * chunksize + x, chunkZ * chunksize + z); double posRand = (double)GameMath.MurmurHash3(x + chunkX * chunksize, 1, z + chunkZ * chunksize) / int.MaxValue; double transitionRand = (posRand + 1) * transitionSize; int posY = heightMap[z * chunksize + x]; int climate = climateMap.GetUnpaddedColorLerped( rdx * climateStep + climateStep * (float)(x + distx) / chunksize, rdz * climateStep + climateStep * (float)(z + distz) / chunksize ); int tempUnscaled = (climate >> 16) & 0xff; int rnd = (int)(distx / 5); float temp = TerraGenConfig.GetScaledAdjustedTemperatureFloat(tempUnscaled, posY - TerraGenConfig.seaLevel + rnd); float tempRel = TerraGenConfig.GetAdjustedTemperature(tempUnscaled, posY - TerraGenConfig.seaLevel + rnd) / 255f; float rainRel = TerraGenConfig.GetRainFall((climate >> 8) & 0xff, posY + rnd) / 255f; float forestRel = GameMath.BiLerp(forestUpLeft, forestUpRight, forestBotLeft, forestBotRight, (float)x / chunksize, (float)z / chunksize) / 255f; float beachRel = GameMath.BiLerp(beachUpLeft, beachUpRight, beachBotLeft, beachBotRight, (float)x / chunksize, (float)z / chunksize) / 255f; int prevY = posY; posY = PutLayers(transitionRand, x, posY, z, chunks, rainRel, temp, tempUnscaled, heightMap); int blockID = chunks[0].MapChunk.TopRockIdMap[z * chunksize + x]; GenBeach(x, prevY, z, chunks, rainRel, temp, beachRel, blockID); PlaceTallGrass(x, prevY, z, chunks, rainRel, tempRel, temp, forestRel); // Try again to put layers if above sealevel and we found over 10 air blocks int foundAir = 0; while (posY >= TerraGenConfig.seaLevel - 1) { int chunkY = posY / chunksize; int lY = posY % chunksize; int index3d = (chunksize * lY + z) * chunksize + x; int blockId = chunks[chunkY].Blocks[index3d]; if (blockId == 0) { foundAir++; } else { if (foundAir >= 8) { //temp = TerraGenConfig.GetScaledAdjustedTemperatureFloat(tempUnscaled, posY - TerraGenConfig.seaLevel); //rainRel = TerraGenConfig.GetRainFall((climate >> 8) & 0xff, posY) / 255f; //PutLayers(transitionRand, x, posY, z, chunks, rainRel, temp, tempUnscaled, null); break; } else { foundAir = 0; } } posY--; } } } }
public float GetValueAtPos(float currVal, float x, float y) { float val = 0; switch (_type) { case NOISE_TYPE.SIMPLEX: val = SimplexNoise.Noise((_initialOffset.x + x) * _scale, (_initialOffset.y + y) * _scale, Time.time * _changeSpeed); break; case NOISE_TYPE.PERLIN: val = Perlin.Noise((_initialOffset.x + x) * _scale, (_initialOffset.y + y) * _scale, Time.time * _changeSpeed); break; case NOISE_TYPE.RANDOM: val = Random.value; break; case NOISE_TYPE.NONE: val = 1; break; case NOISE_TYPE.X: val = x / _scale; break; case NOISE_TYPE.Y: val = y / _scale; break; case NOISE_TYPE.SINX: val = Mathf.Sin(x * _scale); break; case NOISE_TYPE.SINY: val = Mathf.Sin(y * _scale); break; case NOISE_TYPE.COSX: val = Mathf.Cos(x * _scale); break; case NOISE_TYPE.COSY: val = Mathf.Cos(y * _scale); break; } if (_curve.keys.Length > 0) { val = _curve.Evaluate(val); } val *= _weighting; switch (_operationType) { case OPERATION_TYPE.ADDITION: currVal += val; break; case OPERATION_TYPE.DIVISION: currVal /= val; break; case OPERATION_TYPE.MULTIPLICATION: currVal *= val; break; case OPERATION_TYPE.SUBTRACTION: currVal -= val; break; } return(currVal); }
private void OnChunkColumnGen(IServerChunk[] chunks, int chunkX, int chunkZ, ITreeAttribute chunkGenParams = null) { landforms = NoiseLandforms.landforms; IMapChunk mapchunk = chunks[0].MapChunk; int climateUpLeft; int climateUpRight; int climateBotLeft; int climateBotRight; IntMap climateMap = chunks[0].MapChunk.MapRegion.ClimateMap; int regionChunkSize = api.WorldManager.RegionSize / chunksize; float fac = (float)climateMap.InnerSize / regionChunkSize; int rlX = chunkX % regionChunkSize; int rlZ = chunkZ % regionChunkSize; climateUpLeft = climateMap.GetUnpaddedInt((int)(rlX * fac), (int)(rlZ * fac)); climateUpRight = climateMap.GetUnpaddedInt((int)(rlX * fac + fac), (int)(rlZ * fac)); climateBotLeft = climateMap.GetUnpaddedInt((int)(rlX * fac), (int)(rlZ * fac + fac)); climateBotRight = climateMap.GetUnpaddedInt((int)(rlX * fac + fac), (int)(rlZ * fac + fac)); int freezingTemp = TerraGenConfig.DescaleTemperature(-17); IntMap landformMap = mapchunk.MapRegion.LandformMap; // Amount of pixels for each chunk (probably 1, 2, or 4) in the land form map float chunkPixelSize = landformMap.InnerSize / regionChunkSize; // Adjusted lerp for the noiseWidth float chunkPixelStep = chunkPixelSize / noiseWidth; // Start coordinates for the chunk in the region map float baseX = (chunkX % regionChunkSize) * chunkPixelSize; float baseZ = (chunkZ % regionChunkSize) * chunkPixelSize; LerpedWeightedIndex2DMap landLerpMap = GetOrLoadLerpedLandformMap(chunks[0].MapChunk, chunkX / regionChunkSize, chunkZ / regionChunkSize); // Terrain octaves double[] octNoiseX0, octNoiseX1, octNoiseX2, octNoiseX3; double[] octThX0, octThX1, octThX2, octThX3; // So it seems we have some kind of off-by-one error here? // When the slope of a mountain goes up (in positive z or x direction), particularly at large word heights (512+) // then the last blocks (again in postive x/z dir) are below of where they should be? // I have no idea why, but this offset seems to greatly mitigate the issue float weirdOffset = 0.25f; chunkPixelSize += weirdOffset; GetInterpolatedOctaves(landLerpMap[baseX, baseZ], out octNoiseX0, out octThX0); GetInterpolatedOctaves(landLerpMap[baseX + chunkPixelSize, baseZ], out octNoiseX1, out octThX1); GetInterpolatedOctaves(landLerpMap[baseX, baseZ + chunkPixelSize], out octNoiseX2, out octThX2); GetInterpolatedOctaves(landLerpMap[baseX + chunkPixelSize, baseZ + chunkPixelSize], out octNoiseX3, out octThX3); double[] terrainNoise3d = GetTerrainNoise3D(octNoiseX0, octNoiseX1, octNoiseX2, octNoiseX3, octThX0, octThX1, octThX2, octThX3, chunkX * noiseWidth, 0, chunkZ * noiseWidth); // Store heightmap in the map chunk ushort[] rainheightmap = chunks[0].MapChunk.RainHeightMap; ushort[] terrainheightmap = chunks[0].MapChunk.WorldGenTerrainHeightMap; // Terrain thresholds double tnoiseY0; double tnoiseY1; double tnoiseY2; double tnoiseY3; double tnoiseGainY0; double tnoiseGainY1; double tnoiseGainY2; double tnoiseGainY3; double thNoiseX0; double thNoiseX1; double thNoiseGainX0; double thNoiseGainX1; double thNoiseGainZ0; double thNoiseZ0; float[] terrainThresholdsX0 = new float[api.WorldManager.MapSizeY]; float[] terrainThresholdsX1 = new float[api.WorldManager.MapSizeY]; float[] terrainThresholdsX2 = new float[api.WorldManager.MapSizeY]; float[] terrainThresholdsX3 = new float[api.WorldManager.MapSizeY]; for (int xN = 0; xN < noiseWidth; xN++) { for (int zN = 0; zN < noiseWidth; zN++) { // Landform thresholds LoadInterpolatedThresholds(landLerpMap[baseX + xN * chunkPixelStep, baseZ + zN * chunkPixelStep], terrainThresholdsX0); LoadInterpolatedThresholds(landLerpMap[baseX + (xN + 1) * chunkPixelStep, baseZ + zN * chunkPixelStep], terrainThresholdsX1); LoadInterpolatedThresholds(landLerpMap[baseX + xN * chunkPixelStep, baseZ + (zN + 1) * chunkPixelStep], terrainThresholdsX2); LoadInterpolatedThresholds(landLerpMap[baseX + (xN + 1) * chunkPixelStep, baseZ + (zN + 1) * chunkPixelStep], terrainThresholdsX3); for (int yN = 0; yN < noiseHeight; yN++) { // Terrain noise tnoiseY0 = terrainNoise3d[NoiseIndex3d(xN, yN, zN)]; tnoiseY1 = terrainNoise3d[NoiseIndex3d(xN, yN, zN + 1)]; tnoiseY2 = terrainNoise3d[NoiseIndex3d(xN + 1, yN, zN)]; tnoiseY3 = terrainNoise3d[NoiseIndex3d(xN + 1, yN, zN + 1)]; tnoiseGainY0 = (terrainNoise3d[NoiseIndex3d(xN, yN + 1, zN)] - tnoiseY0) * lerpDeltaVert; tnoiseGainY1 = (terrainNoise3d[NoiseIndex3d(xN, yN + 1, zN + 1)] - tnoiseY1) * lerpDeltaVert; tnoiseGainY2 = (terrainNoise3d[NoiseIndex3d(xN + 1, yN + 1, zN)] - tnoiseY2) * lerpDeltaVert; tnoiseGainY3 = (terrainNoise3d[NoiseIndex3d(xN + 1, yN + 1, zN + 1)] - tnoiseY3) * lerpDeltaVert; for (int y = 0; y < lerpVer; y++) { int posY = yN * lerpVer + y; int chunkY = posY / chunksize; int localY = posY % chunksize; // For Terrain noise double tnoiseX0 = tnoiseY0; double tnoiseX1 = tnoiseY1; double tnoiseGainX0 = (tnoiseY2 - tnoiseY0) * lerpDeltaHor; double tnoiseGainX1 = (tnoiseY3 - tnoiseY1) * lerpDeltaHor; // Landform thresholds lerp thNoiseX0 = terrainThresholdsX0[posY]; thNoiseX1 = terrainThresholdsX2[posY]; thNoiseGainX0 = (terrainThresholdsX1[posY] - thNoiseX0) * lerpDeltaHor; thNoiseGainX1 = (terrainThresholdsX3[posY] - thNoiseX1) * lerpDeltaHor; for (int x = 0; x < lerpHor; x++) { // For terrain noise double tnoiseZ0 = tnoiseX0; double tnoiseGainZ0 = (tnoiseX1 - tnoiseX0) * lerpDeltaHor; // Landform thNoiseZ0 = thNoiseX0; thNoiseGainZ0 = (thNoiseX1 - thNoiseX0) * lerpDeltaHor; for (int z = 0; z < lerpHor; z++) { int lX = xN * lerpHor + x; int lZ = zN * lerpHor + z; int mapIndex = ChunkIndex2d(lX, lZ); int chunkIndex = ChunkIndex3d(lX, localY, lZ); chunks[chunkY].Blocks[chunkIndex] = 0; if (posY == 0) { chunks[chunkY].Blocks[chunkIndex] = GlobalConfig.mantleBlockId; continue; } if (tnoiseZ0 > thNoiseZ0) { terrainheightmap[mapIndex] = rainheightmap[mapIndex] = (ushort)Math.Max(rainheightmap[mapIndex], posY); chunks[chunkY].Blocks[chunkIndex] = GlobalConfig.defaultRockId; } else { if (posY < TerraGenConfig.seaLevel) { terrainheightmap[mapIndex] = rainheightmap[mapIndex] = (ushort)Math.Max(rainheightmap[mapIndex], posY); if (posY == TerraGenConfig.seaLevel - 1) { int temp = (GameMath.BiLerpRgbColor(((float)lX) / chunksize, ((float)lZ) / chunksize, climateUpLeft, climateUpRight, climateBotLeft, climateBotRight) >> 16) & 0xff; float distort = (float)distort2dx.Noise(chunkX * chunksize + lX, chunkZ * chunksize + lZ) / 20f; float tempf = TerraGenConfig.GetScaledAdjustedTemperatureFloat(temp, 0) + distort; // dominionsmod chunks[chunkY].Blocks[chunkIndex] = (tempf < -17) ? GlobalConfig.lakeIceBlockId : saltWater; } else { // dominionsmod chunks[chunkY].Blocks[chunkIndex] = saltWater; } } else { chunks[chunkY].Blocks[chunkIndex] = 0; } } tnoiseZ0 += tnoiseGainZ0; thNoiseZ0 += thNoiseGainZ0; } tnoiseX0 += tnoiseGainX0; tnoiseX1 += tnoiseGainX1; thNoiseX0 += thNoiseGainX0; thNoiseX1 += thNoiseGainX1; } tnoiseY0 += tnoiseGainY0; tnoiseY1 += tnoiseGainY1; tnoiseY2 += tnoiseGainY2; tnoiseY3 += tnoiseGainY3; } } } } int ymax = 0; for (int i = 0; i < rainheightmap.Length; i++) { ymax = Math.Max(ymax, rainheightmap[i]); } chunks[0].MapChunk.YMax = (ushort)ymax; }
public virtual void Update(float dt) { densityOffset = CloudDensityOffsetNoise.Noise(api.World.Calendar.TotalHours / 10.0, 0) / 2; EnsureNoiseCacheIsFresh(); }
public virtual void Update(float dt) { if (!State.BeginUseExecuted) { int a = 1; } //EnsureNoiseCacheIsFresh(); double timeAxis = api.World.Calendar.TotalDays / 10.0; State.nowPrecIntensity = State.nowBasePrecIntensity + (float)GameMath.Clamp(TimeBasePrecIntenstityGen?.Noise(0, timeAxis) ?? 0, 0, 1); }
//GenNoise, return value in [-1,1] public double GetNoise(int noisePosX, int noisePosZ) { return(myNoise.Noise(noisePosX * noiseScale, noisePosZ * noiseScale)); }
public void CreateData() { float scale = NoiseParameters.Scale; float smoothingCoeficient = NoiseParameters.Smooth; int multiplyer = NoiseParameters.Mult; float minWeight = float.MaxValue; float maxWeight = float.MinValue; PerlinNoise perlin = new PerlinNoise(1); CustomPerlinNoise customPerlin = new CustomPerlinNoise(); for (int x = 0; x < sizeX; x++) { for (int y = 0; y < sizeY; y++) { for (int z = 0; z < sizeZ; z++) { float weight = 0f; double sampleX = (x + Position.x) * scale; double sampleZ = (z + Position.z) * scale; double sampleY; if (NoiseParameters.Use3DNoise) { sampleY = (y + Position.y) * scale; } else { sampleY = 0; } if (NoiseParameters.ClassicNoise) { weight += (float)(y * smoothingCoeficient + ClassicNoise.Noise(sampleX * smoothingCoeficient, sampleY * smoothingCoeficient, sampleZ * smoothingCoeficient) * multiplyer); } if (NoiseParameters.PerlinNoise) { weight += (float)(y * smoothingCoeficient + perlin.Noise(sampleX * smoothingCoeficient, sampleY * smoothingCoeficient, sampleZ * smoothingCoeficient) * multiplyer); } if (NoiseParameters.SimplexNoise) { weight += (float)(y * smoothingCoeficient + SimplexNoise.Noise(sampleX * smoothingCoeficient, sampleY * smoothingCoeficient, sampleZ * smoothingCoeficient) * multiplyer); } if (NoiseParameters.DefaultPerlinNoise) { weight += (y + customPerlin.Noise((float)sampleX, (float)sampleZ, NoiseParameters.Octaves) * multiplyer); } if (weight < minWeight) { minWeight = weight; } if (weight > maxWeight) { maxWeight = weight; } data[x, y, z] = weight; if (y == 0) { data[x, y, z] = -1f; } } } } }
void GenOneTile() { if (idx == xzcount) { w.Seek(0, SeekOrigin.Begin); for (int i = 0; i < xzcount; ++i) { w.Write(offsets[i]); w.Write(lens[i]); } w.Close(); fs.Close(); MonoBehaviour.Destroy(this); return; } offsets[idx] = (int)(fs.Position); RaycastHit rch; SimplexNoise noise = new SimplexNoise(); for (int _x = 0; _x < tile; ++_x) { for (int _z = 0; _z < tile; ++_z) { Vector3 pos = new Vector3(x + _x + 0.5f, 1043, z + _z + 0.5f); float ns = (float)(noise.Noise(pos.x / 64.0f, pos.y / 64.0f, pos.z / 64.0f)); float nst = (float)(noise.Noise(pos.y / 100.0f, pos.z / 100.0f, pos.x / 100.0f)); if (ns < -0.48f) { continue; } float p = Mathf.Clamp01((float)(ns) + 0.5f); if (Physics.Raycast(pos, Vector3.down, out rch, 1000, 1 << Pathea.Layer.VFVoxelTerrain)) { RedGrassInstance vgi = new RedGrassInstance(); vgi.Position = rch.point; vgi.Density = p; vgi.Normal = rch.normal; vgi.ColorF = Color.white; if (Random.value > Mathf.Sqrt(rch.normal.y)) { vgi.Prototype = nst > 0 ? 64 : 65; allGrasses[idx].Add(vgi); } vgi.Prototype = nst > 0 ? 0 : 1; allGrasses[idx].Add(vgi); Debug.DrawRay(rch.point, rch.normal, new Color(rch.normal.x * 0.5f + 0.5f, rch.normal.y * 0.5f + 0.5f, rch.normal.z * 0.5f + 0.5f), 1); } } } lens[idx] = allGrasses[idx].Count; foreach (RedGrassInstance vgi in allGrasses[idx]) { vgi.WriteToStream(w); } allGrasses[idx].Clear(); x += tile; if (x > xend - 1) { z += tile; x = xstart; } idx++; Debug.Log(idx.ToString()); }
public float Noise(float x, float y, float t, float globalGain, float globalExpo) { var v = (globalGain * gain) * (float)SimplexNoise.Noise(x, y, t); return(v); }