/// <summary> /// Creates terrain data from heights. /// </summary> /// <param name="heightPercents">Terrain height percentages ranging from 0 to 1.</param> /// <param name="maxHeight">The maximum height of the terrain, corresponding to a height percentage of 1.</param> /// <param name="heightSampleDistance">The horizontal/vertical distance between height samples.</param> /// <param name="splatPrototypes">The textures used by the terrain.</param> /// <param name="alphaMap">Texture blending information.</param> /// <returns>A TerrainData instance.</returns> public static TerrainData CreateTerrainData(float[,] heightPercents, float maxHeight, float heightSampleDistance, SplatPrototype[] splatPrototypes, float[,,] alphaMap) { Debug.Assert((heightPercents.GetLength(0) == heightPercents.GetLength(1)) && (maxHeight >= 0) && (heightSampleDistance >= 0)); // Create the TerrainData. var terrainData = new TerrainData(); terrainData.heightmapResolution = heightPercents.GetLength(0); var terrainWidth = (terrainData.heightmapResolution - 1) * heightSampleDistance; // If maxHeight is 0, leave all the heights in terrainData at 0 and make the vertical size of the terrain 1 to ensure valid AABBs. if(!Mathf.Approximately(maxHeight, 0)) { terrainData.size = new Vector3(terrainWidth, maxHeight, terrainWidth); terrainData.SetHeights(0, 0, heightPercents); } else { terrainData.size = new Vector3(terrainWidth, 1, terrainWidth); } // Texture the terrain. if((splatPrototypes != null) && (alphaMap != null)) { Debug.Assert(alphaMap.GetLength(0) == alphaMap.GetLength(1)); terrainData.alphamapResolution = alphaMap.GetLength(0); terrainData.splatPrototypes = splatPrototypes; terrainData.SetAlphamaps(0, 0, alphaMap); } return terrainData; }
UnityEngine.TerrainData GenerateTerrain(UnityEngine.TerrainData terrainData) { terrainData.heightmapResolution = width + 1; terrainData.size = new Vector3(width, depth, height); terrainData.SetHeights(0, 0, GenerateHeights()); return(terrainData); }
public static void Smooth(TerrainData terrain) { int heightmapWidth = terrain.heightmapWidth; int heightmapHeight = terrain.heightmapHeight; float[,] heights = terrain.GetHeights(0, 0, heightmapWidth, heightmapHeight); Smooth(heights, terrain); terrain.SetHeights(0, 0, heights); }
public static void Flatten(TerrainData terrain, float height) { int heightmapWidth = terrain.heightmapWidth; float[,] heights = new float[terrain.heightmapHeight, heightmapWidth]; for (int index1 = 0; index1 < heights.GetLength(0); ++index1) { for (int index2 = 0; index2 < heights.GetLength(1); ++index2) heights[index1, index2] = height; } terrain.SetHeights(0, 0, heights); }
public static void Flatten(TerrainData terrain, float height) { int heightmapWidth = terrain.heightmapWidth; float[,] heights = new float[terrain.heightmapHeight, heightmapWidth]; for (int i = 0; i < heights.GetLength(0); i++) { for (int j = 0; j < heights.GetLength(1); j++) { heights[i, j] = height; } } terrain.SetHeights(0, 0, heights); }
public static void Flatten(TerrainData terrain, float height) { int heightmapWidth = terrain.heightmapWidth; int heightmapHeight = terrain.heightmapHeight; float[,] array = new float[heightmapHeight, heightmapWidth]; for (int i = 0; i < array.GetLength(0); i++) { for (int j = 0; j < array.GetLength(1); j++) { array[i, j] = height; } } terrain.SetHeights(0, 0, array); }
public void CreateTerrain() { //Het maken van een nieuw terrein met daarbijbehorende resolutie. TerrainData terrainData = new TerrainData(); terrainData.heightmapResolution = Settings.HeightmapResolution; terrainData.alphamapResolution = Settings.AlphamapResolution; //Het maken van het terrein hoogte / lengte. var heightmap = GetHeightMap(); terrainData.SetHeights(0, 0, heightmap); terrainData.size = new Vector3(Settings.Length, Settings.Height, Settings.Length); var newTerrainGameObject = Terrain.CreateTerrainGameObject(terrainData); newTerrainGameObject.transform.position = new Vector3(X * Settings.Length, 0, Z * Settings.Length); Terrain = newTerrainGameObject.GetComponent<Terrain>(); Terrain.Flush(); }
/// <summary> /// This method allows to load the terrain data (details, heightmaps). /// </summary> public void LoadTerrainData() { if (!IsInitialized) { return; } if (ActiveTerrain == null) { return; } for (int Layer = 0; Layer < Data.detailPrototypes.Length; Layer++) { Data.SetDetailLayer(0, 0, Layer, TerrainDetails[Layer]); } Data.SetHeights(0, 0, TerrainHeights); }
public void CreateTerrain() { Data = new TerrainData(); Data.heightmapResolution = Settings.HeightmapResolution; Data.alphamapResolution = Settings.AlphamapResolution; Data.SetHeights(0, 0, Heightmap); ApplyTextures(Data); Data.size = new Vector3(Settings.Length, Settings.Height, Settings.Length); var newTerrainGameObject = Terrain.CreateTerrainGameObject(Data); newTerrainGameObject.transform.position = new Vector3(Position.X * Settings.Length, 0, Position.Z * Settings.Length); Terrain = newTerrainGameObject.GetComponent<Terrain>(); Terrain.heightmapPixelError = 8; Terrain.materialType = UnityEngine.Terrain.MaterialType.Custom; Terrain.materialTemplate = Settings.TerrainMaterial; Terrain.reflectionProbeUsage = UnityEngine.Rendering.ReflectionProbeUsage.Off; Terrain.Flush(); }
/// <summary> /// Clone TerrainData object /// </summary> /// <param name="source"> /// A <see cref="TerrainData"/> /// </param> /// <param name="detailResolutionPerPatch"> /// A <see cref="System.Int32"/> /// </param> /// <returns> /// A <see cref="TerrainData"/> /// </returns> public static TerrainData Clone(TerrainData source, int detailResolutionPerPatch) { TerrainData dest = new TerrainData(); dest.alphamapResolution = source.alphamapResolution; dest.baseMapResolution = source.baseMapResolution; dest.SetDetailResolution(source.detailResolution, detailResolutionPerPatch); DetailPrototype[] dp = new DetailPrototype[source.detailPrototypes.Length]; for (int i=0; i<dp.Length; i++) dp[i] = new DetailPrototype(); dest.detailPrototypes = dp; for (int i=0; i<dp.Length; i++) { dest.detailPrototypes[i].bendFactor = source.detailPrototypes[i].bendFactor; dest.detailPrototypes[i].dryColor = source.detailPrototypes[i].dryColor; dest.detailPrototypes[i].healthyColor = source.detailPrototypes[i].healthyColor; dest.detailPrototypes[i].maxHeight = source.detailPrototypes[i].maxHeight; dest.detailPrototypes[i].maxWidth = source.detailPrototypes[i].maxWidth; dest.detailPrototypes[i].minHeight = source.detailPrototypes[i].minHeight; dest.detailPrototypes[i].minWidth = source.detailPrototypes[i].minWidth; dest.detailPrototypes[i].noiseSpread = source.detailPrototypes[i].noiseSpread; dest.detailPrototypes[i].prototype = source.detailPrototypes[i].prototype; dest.detailPrototypes[i].prototypeTexture = source.detailPrototypes[i].prototypeTexture; dest.detailPrototypes[i].renderMode = source.detailPrototypes[i].renderMode; dest.detailPrototypes[i].usePrototypeMesh = source.detailPrototypes[i].usePrototypeMesh; dest.SetDetailLayer(0,0,i,source.GetDetailLayer(0,0,source.detailWidth,source.detailHeight,i)); } dest.RefreshPrototypes(); dest.heightmapResolution = source.heightmapResolution; dest.SetHeights(0,0,source.GetHeights(0,0,source.heightmapWidth,source.heightmapHeight)); dest.hideFlags = source.hideFlags; dest.name = source.name+" (Clone)"; dest.size = source.size; dest.splatPrototypes = source.splatPrototypes; dest.treeInstances = source.treeInstances; dest.treePrototypes = source.treePrototypes; dest.wavingGrassAmount = source.wavingGrassAmount; dest.wavingGrassSpeed = source.wavingGrassSpeed; dest.wavingGrassStrength = source.wavingGrassStrength; dest.wavingGrassTint = source.wavingGrassTint; return dest; }
public void CreateTerrain() { var data = new TerrainData(); data.alphamapResolution = Settings.AlphaMapResolution; data.heightmapResolution = Settings.HeightMapResolution; var heightmap = GetHeightmap(); data.SetHeights(0, 0, heightmap); ApplyTextures(data); data.size = new Vector3(Settings.Length, Settings.Height, Settings.Length); var terrain = Terrain.CreateTerrainGameObject(data); terrain.transform.position = new Vector3(-0.5f * Settings.Length, 0, -0.5f * Settings.Length); _terrain = terrain.GetComponent<Terrain>(); _terrain.heightmapPixelError = 8; _terrain.materialType = Terrain.MaterialType.Custom; _terrain.materialTemplate = Settings.TerrainMaterial; _terrain.reflectionProbeUsage = UnityEngine.Rendering.ReflectionProbeUsage.Off; _terrain.Flush(); }
// Method runs on program launch void Start() { // Fetch terrain data of current playing field TD = transform.GetComponent<Terrain> ().terrainData; printTerrainSize(); // Creates 2-dimensional array of floats that is the size of the width and height of the heightmap and contains the current height values float[,] heightMap = TD.GetHeights (0, 0, TD.heightmapWidth, TD.heightmapHeight); for (int x = 0; x < TD.heightmapWidth; x++) { for (int y = 0; y < TD.heightmapHeight; y++) { // Standard formula to apply perlin noise to 3D terrain from http://wiki.unity3d.com/index.php/TerrainPerlinNoise // By using the width and height on each position we ensure that adjacent positions are adjusted smoothly heightMap [x, y] = Mathf.PerlinNoise (((float)x / (float)TD.heightmapWidth) * hillVariance, ((float)y / (float)TD.heightmapHeight) * hillVariance) / 10.0f; } } // Pushes the new height map to the terrain data TD.SetHeights (0, 0, heightMap); }
void stitchTerrain(TerrainData tData, ChunkCoord c) { TerrainData left = (TerrainData)chunks[new ChunkCoord(c.x - 1, c.z)]; TerrainData right = (TerrainData)chunks[new ChunkCoord(c.x + 1, c.z)]; TerrainData top = (TerrainData)chunks[new ChunkCoord(c.x, c.z - 1)]; TerrainData bottom = (TerrainData)chunks[new ChunkCoord(c.x, c.z + 1)]; if (left != null) { var seam = left.GetHeights(chunkResolution - 1, 0, 1, chunkResolution); tData.SetHeights(0, 0, seam); } if (right != null) { var seam = right.GetHeights(0, 0, 1, chunkResolution); tData.SetHeights(chunkResolution - 1, 0, seam); } if (top != null) { var seam = top.GetHeights(0, chunkResolution-1, chunkResolution, 1); tData.SetHeights(0, 0, seam); } if (bottom != null) { var seam = bottom.GetHeights(0, 0, chunkResolution, 1); tData.SetHeights(0, chunkResolution - 1, seam); } }
void finalizeHeightmap(RenderedHeightmap rh) { TerrainData tData = new TerrainData(); tData.heightmapResolution = chunkResolution; tData.alphamapResolution = chunkResolution; tData.size = new Vector3(chunkWidth, terrainHeight, chunkWidth); tData.splatPrototypes = splats; tData.RefreshPrototypes(); /* Create and position the terrain */ GameObject terrain = Terrain.CreateTerrainGameObject(tData); terrain.transform.position = new Vector3( chunkWidth * rh.coord.x, 0.0f, chunkWidth * rh.coord.z); /* Set the heightmap data from the background thread. */ tData.SetHeights(0, 0, rh.heightmap); stitchTerrain(tData, rh.coord); chunks[rh.coord] = tData; // texturing tData.SetAlphamaps(0, 0, rh.splatmap); }
public override void OnInspectorGUI() { DrawDefaultInspector(); if (GUILayout.Button("Generuj")) { var terrainData = new TerrainData { heightmapResolution = 65, size = new Vector3(50f, 20f, 50f) }; int xSize = terrainData.heightmapHeight; int zSize = terrainData.heightmapWidth; const float noiseScale = 1.5f; var heights = terrainData.GetHeights(0, 0, xSize, zSize); float[][] noise = PerlinTools.GeneratePerlinNoise(xSize, zSize, 8); for (var x = 0; x < terrainData.heightmapHeight; x++) { for (var z = 0; z < terrainData.heightmapWidth; z++) { heights[x, z] = noise[x][z] * noiseScale; } } terrainData.SetHeights(0, 0, heights); var tekstura = Resources.Load<Texture2D>( "prototype_textures/Textures/proto_blue"); if (tekstura != null) { var sp = new SplatPrototype[1]; sp[0] = new SplatPrototype{texture = tekstura}; terrainData.splatPrototypes = sp; var alphamaps = new float[xSize, zSize, sp.Length]; for(int ax = 0; ax < xSize; ++ax) for(int az = 0; az < zSize; ++az) for (int tex = 0; tex < sp.Length; ++tex) alphamaps[ax, az, tex] = Math.Abs(Mathf.Sin(ax*1.2f + az*1.3f)); terrainData.SetAlphamaps(0, 0, alphamaps); } GameObject terrain = Terrain.CreateTerrainGameObject(terrainData); } /* _Terrain.terr = Terrain.activeTerrain; hmWidth = terr.terrainData.heightmapWidth; hmHeight = terr.terrainData.heightmapHeight; Terrain.activeTerrain.heightmapMaximumLOD = 0; // get the heights of the terrain under this game object float[,] heights = terr.terrainData.GetHeights(0, 0, hmWidth, hmHeight); // we set each sample of the terrain in the size to the desired height //for (int i=0; i<hmWidth; i++) //for (int j=0; j<hmHeight; j++){ //heights[i,j] = (Mathf.Sin(i/10f)/100f + Mathf.Cos((i+j)/10f) / 100f) + 0.5f; float[][] mapa = PerlinTools.GeneratePerlinNoise(hmWidth, hmHeight, 4); for (int x = 0; x < hmWidth; ++x) for (int z = 0; z < hmHeight; ++z) { heights[x, z] = mapa[x][z] / 1000f; } //print(heights[i,j]); //} // set the new height terr.terrainData.SetHeights(0, 0, heights); */ }
public void Perform(TerrainData data) { data.SetHeights(x,z,heights); if (splats!=null) data.SetAlphamaps(x,z,splats); }
void DrawSelectedNodeDetails(NodeBase node) { if (previewNeedsUpdate || lastSelected != node) { preview = new Texture2D(230, 230); if (node.Module != null && previewCalculation == null) previewCalculation = new NoiseCalculation(node.Module, 230, 230); previewNeedsUpdate = false; lastSelected = node; } if (previewCalculation != null && previewCalculation.Done) { preview = previewCalculation.Noise.GetTexture(); previewCalculation = null; } var state = mainEditorState as NoiseDesignerState; EditorGUILayout.Space(); EditorGUILayout.LabelField("Selected Node:"); GUILayout.Box(preview); EditorGUILayout.Space(); EditorGUILayout.Separator(); EditorGUILayout.LabelField("Apply to terrain:"); terrain = EditorGUILayout.ObjectField("TerrainData", terrain, typeof(TerrainData), false) as TerrainData; if (GUILayout.Button("Apply")) { Noise2D noise = new Noise2D(terrain.heightmapWidth, terrain.heightmapHeight, node.Module); noise.GeneratePlanar(4.0f, 10.0f, 1.0f, 5.0f); terrain.SetHeights(0, 0, noise.GetNormalizedData()); } EditorGUILayout.Space(); EditorGUILayout.Separator(); EditorGUILayout.LabelField("Export as texture:"); state.textureSize = EditorGUILayout.Vector2Field("Texture Size", state.textureSize); if (GUILayout.Button("Save as PNG")) { var path = EditorUtility.SaveFilePanelInProject("Save as PNG", "noise", "png", ""); if (!string.IsNullOrEmpty(path)) { Noise2D noise = new Noise2D((int)state.textureSize.x, (int)state.textureSize.y, node.Module); noise.GeneratePlanar(4.0f, 10.0f, 1.0f, 5.0f); var texture = noise.GetTexture(); File.WriteAllBytes(path, texture.EncodeToPNG()); AssetDatabase.Refresh(); } } }
void CreateTerrain() { //fire up the progress bar ShowProgressBar(1, 100); TerrainData terrain = new TerrainData(); terrain.heightmapResolution = resolution; GameObject terrainObject = Terrain.CreateTerrainGameObject(terrain); Undo.RegisterCreatedObjectUndo(terrainObject, "Object to Terrain"); MeshCollider collider = Selection.activeGameObject.GetComponent<MeshCollider>(); CleanUp cleanUp = null; //Add a collider to our source object if it does not exist. //Otherwise raycasting doesn't work. if(!collider){ collider = Selection.activeGameObject.AddComponent<MeshCollider>(); cleanUp = () => DestroyImmediate(collider); } Bounds bounds = collider.bounds; float sizeFactor = collider.bounds.size.y / (collider.bounds.size.y + addTerrain.y); terrain.size = collider.bounds.size + addTerrain; bounds.size = new Vector3(terrain.size.x, collider.bounds.size.y, terrain.size.z); // Do raycasting samples over the object to see what terrain heights should be float[,] heights = new float[terrain.heightmapWidth, terrain.heightmapHeight]; Ray ray = new Ray(new Vector3(bounds.min.x, bounds.max.y + bounds.size.y, bounds.min.z), -Vector3.up); RaycastHit hit = new RaycastHit(); float meshHeightInverse = 1 / bounds.size.y; Vector3 rayOrigin = ray.origin; int maxHeight = heights.GetLength(0); int maxLength = heights.GetLength(1); Vector2 stepXZ = new Vector2(bounds.size.x / maxLength, bounds.size.z / maxHeight); for(int zCount = 0; zCount < maxHeight; zCount++){ ShowProgressBar(zCount, maxHeight); for(int xCount = 0; xCount < maxLength; xCount++){ float height = 0.0f; if(collider.Raycast(ray, out hit, bounds.size.y * 3)){ height = (hit.point.y - bounds.min.y) * meshHeightInverse; height += shiftHeight; //bottom up if(bottomTopRadioSelected == 0){ height *= sizeFactor; } //clamp if(height < 0){ height = 0; } } heights[zCount, xCount] = height; rayOrigin.x += stepXZ[0]; ray.origin = rayOrigin; } rayOrigin.z += stepXZ[1]; rayOrigin.x = bounds.min.x; ray.origin = rayOrigin; } terrain.SetHeights(0, 0, heights); EditorUtility.ClearProgressBar(); if(cleanUp != null){ cleanUp(); } }
void Start() { m_groundNoise = new PerlinNoise(m_groundSeed); m_mountainNoise = new PerlinNoise(m_mountainSeed); m_treeNoise = new PerlinNoise(m_treeSeed); m_detailNoise = new PerlinNoise(m_detailSeed); if(!Mathf.IsPowerOfTwo(m_heightMapSize-1)) { Debug.Log("TerrianGenerator::Start - height map size must be pow2+1 number"); m_heightMapSize = Mathf.ClosestPowerOfTwo(m_heightMapSize)+1; } if(!Mathf.IsPowerOfTwo(m_alphaMapSize)) { Debug.Log("TerrianGenerator::Start - Alpha map size must be pow2 number"); m_alphaMapSize = Mathf.ClosestPowerOfTwo(m_alphaMapSize); } if(!Mathf.IsPowerOfTwo(m_detailMapSize)) { Debug.Log("TerrianGenerator::Start - Detail map size must be pow2 number"); m_detailMapSize = Mathf.ClosestPowerOfTwo(m_detailMapSize); } if(m_detailResolutionPerPatch < 8) { Debug.Log("TerrianGenerator::Start - Detail resolution per patch must be >= 8, changing to 8"); m_detailResolutionPerPatch = 8; } float[,] htmap = new float[m_heightMapSize,m_heightMapSize]; m_terrain = new Terrain[m_tilesX,m_tilesZ]; //this will center terrain at origin m_offset = new Vector2(-m_terrainSize*m_tilesX*0.5f, -m_terrainSize*m_tilesZ*0.5f); CreateProtoTypes(); for(int x = 0; x < m_tilesX; x++) { for(int z = 0; z < m_tilesZ; z++) { FillHeights(htmap, x, z); TerrainData terrainData = new TerrainData(); terrainData.heightmapResolution = m_heightMapSize; terrainData.SetHeights(0, 0, htmap); terrainData.size = new Vector3(m_terrainSize, m_terrainHeight, m_terrainSize); terrainData.splatPrototypes = m_splatPrototypes; terrainData.treePrototypes = m_treeProtoTypes; terrainData.detailPrototypes = m_detailProtoTypes; FillAlphaMap(terrainData); m_terrain[x,z] = Terrain.CreateTerrainGameObject(terrainData).GetComponent<Terrain>(); m_terrain[x,z].transform.position = new Vector3(m_terrainSize*x + m_offset.x, 0, m_terrainSize*z + m_offset.y); m_terrain[x,z].heightmapPixelError = m_pixelMapError; m_terrain[x,z].basemapDistance = m_baseMapDist; //disable this for better frame rate m_terrain[x,z].castShadows = false; FillTreeInstances(m_terrain[x,z], x, z); FillDetailMap(m_terrain[x,z], x, z); } } //Set the neighbours of terrain to remove seams. for(int x = 0; x < m_tilesX; x++) { for(int z = 0; z < m_tilesZ; z++) { Terrain right = null; Terrain left = null; Terrain bottom = null; Terrain top = null; if(x > 0) left = m_terrain[(x-1),z]; if(x < m_tilesX-1) right = m_terrain[(x+1),z]; if(z > 0) bottom = m_terrain[x,(z-1)]; if(z < m_tilesZ-1) top = m_terrain[x,(z+1)]; m_terrain[x,z].SetNeighbors(left, top, right, bottom); } } }
void finalizeHeightmap(RenderedHeightmap rh) { TerrainData tData = new TerrainData(); tData.heightmapResolution = chunkResolution; tData.alphamapResolution = chunkResolution; tData.SetDetailResolution(chunkResolution*2, 1); tData.size = new Vector3(chunkWidth, terrainHeight, chunkWidth); tData.splatPrototypes = splats; tData.detailPrototypes = grassProto; tData.treePrototypes = treeProto; tData.RefreshPrototypes(); // tree placement tData.treeInstances = rh.treeInstances.ToArray(); /* Create and position the terrain */ GameObject terrain = Terrain.CreateTerrainGameObject(tData); terrain.transform.position = new Vector3 ( chunkWidth * rh.coord.x, 0.0f, chunkWidth * rh.coord.z); /* Set the heightmap data from the background thread. */ tData.SetHeights(0, 0, rh.heightmap); stitchTerrain(tData, rh.coord); chunks[rh.coord] = tData; // texturing tData.SetAlphamaps(0, 0, rh.splatmap); // grass placement /*if (texturesToAffect.Length != 0) { var detailedLayer = grassPlacement (tData.detailResolution, tData.GetAlphamaps (0, 0, tData.alphamapWidth, tData.alphamapHeight)); tData.SetDetailLayer (0, 0, grassType, detailedLayer); }*/ }
public void GenerateTerrain(TerrainData terrainData, float tileSize) { if(disableProceduralTerrain) return; _heightMap = new float[terrainData.heightmapWidth, terrainData.heightmapHeight]; float width_2 = terrainData.heightmapWidth*0.5f; float height_2 = terrainData.heightmapHeight*0.5f; float aW = MathHelpers.RandomFromVec2(aWMinMax); float bW = MathHelpers.RandomFromVec2(bWMinMax); float cW = MathHelpers.RandomFromVec2(cWMinMax); float dW = MathHelpers.RandomFromVec2(dWMinMax); float bH = MathHelpers.RandomFromVec2(bHMinMax); float cH = MathHelpers.RandomFromVec2(cHMinMax); for (int i = 0; i < terrainData.heightmapWidth; i++) { for (int k = 0; k < terrainData.heightmapHeight; k++) { float xW = (float)(i - width_2); float xH = (float)(k - height_2); float heightAdjustW = aW*Mathf.Exp(- (Mathf.Pow((xW -bW),2)/(2*Mathf.Pow(cW,2)) + Mathf.Pow((xH-bH),2)/(2*Mathf.Pow(cH,2)))) + dW; _heightMap[i, k] = heightAdjustW + MathHelpers.RandomFromVec2( perlinNoiseAmpMinMax )*Mathf.PerlinNoise(((float)i / (float)terrainData.heightmapWidth) * tileSize, ((float)k / (float)terrainData.heightmapHeight) * tileSize); } } terrainData.SetHeights(0, 0, _heightMap); SplatPrototype groundProto = new SplatPrototype(); groundProto.texture = terrainTexture; groundProto.tileOffset = new Vector2(0f,0f); groundProto.tileSize = new Vector2(10f,10f); SplatPrototype snowProto = new SplatPrototype(); snowProto.texture = snowTexture; snowProto.tileOffset = new Vector2(0f,0f); snowProto.tileSize = new Vector2(10f,10f); SplatPrototype[] prototypes = new SplatPrototype[2]; prototypes[0] = groundProto; prototypes[1] = snowProto; terrainData.splatPrototypes = prototypes; _terrainTransform.localPosition = new Vector3( -0.5f*terrainData.size.x,0f,-0.5f*terrainData.size.z ); }
public void Perform(TerrainData data) { data.SetHeights(heightsOffsetX,heightsOffsetZ,heights); if (splats!=null) data.SetAlphamaps(splatsOffsetX,splatsOffsetZ,splats); }
public Terrain GenerateTerrains(int x, int z, Terrain t) { float[,] htmap = new float[heightMapSize,heightMapSize]; CreateBasicTerrain(htmap, x, z); TerrainData terrainData = new TerrainData(); terrainData.heightmapResolution = heightMapSize; terrainData.SetHeights(0, 0, htmap); terrainData.size = new Vector3(terrainSize, terrainHeight, terrainSize); terrainData.splatPrototypes = splatPrototypes; terrainData.treePrototypes = treePrototypes; terrainData.detailPrototypes = detailPrototypes; AddAlphaMap(terrainData); t = Terrain.CreateTerrainGameObject(terrainData).GetComponent<Terrain>(); t.transform.position = new Vector3(terrainSize*x -(terrainSize*0.5f), 0, terrainSize*z - (terrainSize*0.5f)); t.heightmapPixelError = pixelMapError; t.basemapDistance = baseMapDist; AddTrees(t, x, z); AddDetailMap(t, x, z); return t; }
void CopyTerrainDataFromTo(TerrainData tDataFrom, ref TerrainData tDataTo) { //TerrainCollider tc = terrainBlock.gameObject.GetComponent<TerrainCollider>(); //tc.terrainData = terrainBlock.terrainData; tDataTo.SetDetailResolution(tDataFrom.detailResolution, 8); tDataTo.heightmapResolution = tDataFrom.heightmapResolution; tDataTo.alphamapResolution = tDataFrom.alphamapResolution; tDataTo.baseMapResolution = tDataFrom.baseMapResolution; tDataTo.size = tDataFrom.size; tDataTo.splatPrototypes = tDataFrom.splatPrototypes; tDataTo.treePrototypes = tDataFrom.treePrototypes; tDataTo.treeInstances = tDataFrom.treeInstances; float[,] heights = tDataFrom.GetHeights(0, 0, tileWidth, tileHeight); tDataTo.SetHeights(0,0, heights); }
// Use this for initialization void Start() { t = terrain.GetComponent<Terrain>(); td = t.terrainData; float[,] heights = new float[(int)td.size.x, (int)td.size.z]; System.Random rand = new System.Random(); for(int i = 0 ; i < td.size.x; i++) { for(int j = 0 ; j < td.size.z; j++) { // heights[i, j] += ((float) SimplexNoise.noise(i, j))>0?(float) SimplexNoise.noise(i, j):0; } } normalizePerlin(ref heights, new Vector2(td.size.x - 1, td.size.z - 1)); td.SetHeights(0, 0, heights); td.RefreshPrototypes(); t.Flush(); }
TerrainData InitializeTerrain(float[,] noise) { TerrainData t = new TerrainData(); t.heightmapResolution = terrainSizePOT; t.alphamapResolution = textureRes; t.SetDetailResolution(textureRes, 16); t.baseMapResolution = textureRes; t.size = new Vector3(terrainSizePOT, terrainHeight, terrainSizePOT); t.SetHeights(0,0,noise); t.splatPrototypes = splatProto; return t; }
public void WriteHeightmap (TerrainData data, float[,] array=null, float brushFallof=0.5f) { CoordRect intersection = CoordRect.Intersect(rect, new CoordRect(0,0,data.heightmapResolution, data.heightmapResolution)); //checking ref array if (array == null || array.Length != intersection.size.x*intersection.size.z) array = new float[intersection.size.z,intersection.size.x]; //x and z swapped //write to 2d array Coord min = intersection.Min; Coord max = intersection.Max; for (int x=min.x; x<max.x; x++) for (int z=min.z; z<max.z; z++) { float fallofFactor = Fallof(x,z,brushFallof); if (Mathf.Approximately(fallofFactor,0)) continue; array[z-min.z, x-min.x] = this[x,z]*fallofFactor + array[z-min.z, x-min.x]*(1-fallofFactor); //array[z-min.z, x-min.x] += this[x,z]; } data.SetHeights(intersection.offset.x, intersection.offset.z, array); }
IEnumerator LoadTerrain(Options options) { Progress ("Chargement du terrain", (1.0f / 5.0f) * 4.0f); // Load height map. WWW www = new WWW("file://" + heightMapPath); yield return www; Texture2D texture = www.texture; // Create height map. int resolution = options.preset.population; float distance = options.preset.distance; float[,] heightMap = new float[resolution, resolution]; for (int y = 0; y < resolution; ++y) { for(int x = 0; x < resolution; ++x) { heightMap[x, y] = texture.GetPixel(x, y).r; } } yield return null; // Set height map. terrain = (GameObject) Instantiate (terrainPrefab); TerrainData data = new TerrainData (); data.heightmapResolution = resolution; terrain.GetComponent<Terrain>().terrainData = data; data.size = new Vector3( resolution * distance, 256, resolution * distance ); data.SetHeights(0, 0, heightMap); terrainMat.SetTexture ("type_texture", vegetationMap.mainTexture); terrain.GetComponent<Terrain> ().materialTemplate = terrainMat; terrain.GetComponent<Terrain> ().basemapDistance = 2000; yield return null; // Center terrain. Vector3 size = data.size; Debug.Log (size.x + " " + size.y + " " + size.z); Vector3 sizeN = size.normalized; terrain.transform.localScale = sizeN; terrain.transform.position = new Vector3(-size.x / 2.0f, 0, -size.z / 2.0f); // Water. water.transform.position = new Vector3(water.transform.position.x, options.seaLevel, water.transform.position.z); // Camera. mainCamera.transform.position = new Vector3(1, 1, 1); mainCamera.transform.LookAt (Vector3.zero); mainCamera.transform.position = mainCamera.transform.position * size.z; mainCamera.farClipPlane = size.x * 4; light.transform.position = mainCamera.transform.position; light.transform.rotation = mainCamera.transform.rotation; // Vegetation. Vegetation vegetation = terrain.GetComponent<Vegetation> (); vegetation.terrain = terrain.GetComponent<Terrain>(); vegetation.tex_vegetation = (Texture2D) vegetationMap.mainTexture; yield return StartCoroutine(vegetation.Init ()); yield return null; }
public static void BlendData(TerrainData terrain1, TerrainData terrain2, Direction thisDirection, bool singleTerrain) { float[,] heightmapData = terrain1.GetHeights(0, 0, terrainRes, terrainRes); float[,] heightmapData2 = terrain2.GetHeights(0, 0, terrainRes, terrainRes); int pos = terrainRes - 1; if (thisDirection == Direction.Across) { for (int i = 0; i < terrainRes; i++) { for (int j = 1; j < stitchWidth; j++) { float mix = Mathf.Lerp(heightmapData[i, pos - j], heightmapData2[i, j], 0.5f); if (j == 1) { heightmapData[i, pos] = mix; heightmapData2[i, 0] = mix; } float t = Mathf.SmoothStep(0.0f, 1.0f, Mathf.InverseLerp(1, stitchWidth - 1, j)); heightmapData[i, pos - j] = Mathf.Lerp(mix, heightmapData[i, pos - j], t); if (!singleTerrain) { heightmapData2[i, j] = Mathf.Lerp(mix, heightmapData2[i, j], t); } else { heightmapData[i, j] = Mathf.Lerp(mix, heightmapData2[i, j], t); } } } if (singleTerrain) { for (int i = 0; i < terrainRes; i++) { heightmapData[i, 0] = heightmapData[i, pos]; } } } else { for (int i = 0; i < terrainRes; i++) { for (int j = 1; j < stitchWidth; j++) { float mix = Mathf.Lerp(heightmapData2[pos - j, i], heightmapData[j, i], 0.5f); if (j == 1) { heightmapData2[pos, i] = mix; heightmapData[0, i] = mix; } float t = Mathf.SmoothStep(0.0f, 1.0f, Mathf.InverseLerp(1, stitchWidth - 1, j)); if (!singleTerrain) { heightmapData2[pos - j, i] = Mathf.Lerp(mix, heightmapData2[pos - j, i], t); } else { heightmapData[pos - j, i] = Mathf.Lerp(mix, heightmapData2[pos - j, i], t); } heightmapData[j, i] = Mathf.Lerp(mix, heightmapData[j, i], t); } } if (singleTerrain) { for (int i = 0; i < terrainRes; i++) { heightmapData[pos, i] = heightmapData[0, i]; } } } terrain1.SetHeights(0, 0, heightmapData); if (!singleTerrain) { terrain2.SetHeights(0, 0, heightmapData2); } }
//************************************************** void Start() { //Constructores de ruidos ruidosuelo = new PerlinNoise(TipoDeTerreno); ruidomontaña = new PerlinNoise(TipoDeMontaña); ruidoarbol = new PerlinNoise(TipoDeArboleda); ruidodetalle = new PerlinNoise(TipoDeDetallado); //*********************************************** mi_terrain = new Terrain[CuadrantesEnX, CuadrantesEnZ]; float[,] alturas = new float[TamañoDelHeightmap, TamañoDelHeightmap]; map_offset = new Vector2(-TamañoDelTerreno * CuadrantesEnX * 0.5f, -TamañoDelTerreno * CuadrantesEnZ * 0.5f);//Centrado del terreno CreateProtoTypes(); float max_altura = 0; for (int x = 0; x < CuadrantesEnX; x++) { for (int z = 0; z < CuadrantesEnZ; z++) { editTerrain(alturas, x, z); TerrainData terrainData = new TerrainData(); terrainData.heightmapResolution = TamañoDelHeightmap; terrainData.SetHeights(0, 0, alturas); terrainData.size = new Vector3(TamañoDelTerreno, AlturaMaxima, TamañoDelTerreno); terrainData.splatPrototypes = splatArray; terrainData.treePrototypes = treeArray; terrainData.detailPrototypes = detailArray; max_altura = maxHeight(terrainData, max_altura); texturizeTerrain(terrainData, max_altura); mi_terrain[x, z] = Terrain.CreateTerrainGameObject(terrainData).GetComponent<Terrain>(); mi_terrain[x, z].transform.position = new Vector3(TamañoDelTerreno * x + map_offset.x, 0, TamañoDelTerreno * z + map_offset.y); mi_terrain[x, z].basemapDistance = DibujadoLowRes; TreeGenerator(mi_terrain[x, z], x, z); DetailGenerator(mi_terrain[x, z], x, z); } } //Eliminar bordes extraños for (int x = 0; x < CuadrantesEnX; x++) { for (int z = 0; z < CuadrantesEnZ; z++) { Terrain right = null; Terrain left = null; Terrain bottom = null; Terrain top = null; if (x > 0) left = mi_terrain[(x - 1), z]; if (x < CuadrantesEnX - 1) right = mi_terrain[(x + 1), z]; if (z > 0) bottom = mi_terrain[x, (z - 1)]; if (z < CuadrantesEnZ - 1) top = mi_terrain[x, (z + 1)]; mi_terrain[x, z].SetNeighbors(left, top, right, bottom); } }//****************************************************** }
/// <summary> /// Read the data into the specified value. /// </summary> /// <param name="value">Value.</param> /// <param name="reader">Reader.</param> public override void ReadInto(object value, ISaveGameReader reader) { UnityEngine.TerrainData terrainData = (UnityEngine.TerrainData)value; foreach (string property in reader.Properties) { switch (property) { case "alphamaps": terrainData.SetAlphamaps(0, 0, reader.ReadProperty <float [, , ]> ()); break; case "heights": terrainData.SetHeights(0, 0, reader.ReadProperty <float [, ]> ()); break; case "heightmapResolution": terrainData.heightmapResolution = reader.ReadProperty <System.Int32> (); break; case "size": terrainData.size = reader.ReadProperty <UnityEngine.Vector3> (); break; case "thickness": terrainData.thickness = reader.ReadProperty <System.Single> (); break; case "wavingGrassStrength": terrainData.wavingGrassStrength = reader.ReadProperty <System.Single> (); break; case "wavingGrassAmount": terrainData.wavingGrassAmount = reader.ReadProperty <System.Single> (); break; case "wavingGrassSpeed": terrainData.wavingGrassSpeed = reader.ReadProperty <System.Single> (); break; case "wavingGrassTint": terrainData.wavingGrassTint = reader.ReadProperty <UnityEngine.Color> (); break; case "detailPrototypes": terrainData.detailPrototypes = reader.ReadProperty <UnityEngine.DetailPrototype []> (); break; case "treeInstances": terrainData.treeInstances = reader.ReadProperty <UnityEngine.TreeInstance []> (); break; case "treePrototypes": terrainData.treePrototypes = reader.ReadProperty <UnityEngine.TreePrototype []> (); break; case "alphamapResolution": terrainData.alphamapResolution = reader.ReadProperty <System.Int32> (); break; case "baseMapResolution": terrainData.baseMapResolution = reader.ReadProperty <System.Int32> (); break; case "splatPrototypes": terrainData.splatPrototypes = reader.ReadProperty <UnityEngine.SplatPrototype []> (); break; case "name": terrainData.name = reader.ReadProperty <System.String> (); break; case "hideFlags": terrainData.hideFlags = reader.ReadProperty <UnityEngine.HideFlags> (); break; } } }
static Terrain ImportTerrain(string planet, string map, Revise.Files.ZON.ZoneFile zon, int x, int y) { var blockName = x.ToString() + "_" + y.ToString(); var basePath = rootPath + "3DDATA/MAPS/" + planet + "/" + map + "/" + blockName; float blockX = (x - 32) * 160; float blockY = (32 - y) * 160; Object.DestroyImmediate(GameObject.Find(blockName)); var ifo = new Revise.Files.IFO.MapDataFile(); ifo.Load(basePath + ".IFO"); for (int i = 0; i < ifo.Objects.Count; ++i) { var obj = ifo.Objects[i]; ImportObject("JUNON_JDT_DECO", x, y, "DECO", i, obj); } for (int i = 0; i < ifo.Buildings.Count; ++i) { var obj = ifo.Buildings[i]; ImportObject("JUNON_JDT_CNST", x, y, "CNST", i, obj); } for (int i = 0; i < ifo.Animations.Count; ++i) { //var obj = ifo.Animations[i]; Debug.LogWarning("Got unexpected animation object."); } for (int i = 0; i < ifo.Sounds.Count; ++i) { var snd = ifo.Sounds[i]; var sndName = "SND_" + snd.ObjectID.ToString() + " (" + blockName + "_" + i.ToString() + ")"; var a = new GameObject(); //var s = a.AddComponent<AudioSource>(); //TODO: Need to link to audio after copy in prestage a.transform.localPosition = ifotruPosition(snd.Position); a.transform.localRotation = rtuRotation(snd.Rotation); a.transform.localScale = rtuScale(snd.Scale); a.name = sndName; a.isStatic = true; } var tex = ImportPlanMap(planet, map, x, y); var him = new Revise.Files.HIM.HeightmapFile(); him.Load(basePath + ".HIM"); float[,] heights = new float[65,65]; float heightMin = him.Heights[0, 0]; float heightMax = him.Heights[0, 0]; for (int ix = 0; ix < 65; ++ix) { for (int iy = 0; iy < 65; ++iy) { if (him.Heights[ix, iy] < heightMin) { heightMin = him.Heights[ix, iy]; } if (him.Heights[ix, iy] > heightMax) { heightMax = him.Heights[ix, iy]; } } } float heightBase = heightMin; float heightDelta = heightMax - heightMin; for (int ix = 0; ix < 65; ++ix) { for (int iy = 0; iy < 65; ++iy) { heights[ix, iy] = (him.Heights[64 - ix, iy] - heightBase) / heightDelta; } } var til = new Revise.Files.TIL.TileFile(); til.Load(basePath + ".TIL"); /* for (int ix = 0; ix < til.Width; ++ix) { for (int iy = 0; iy < til.Height; ++iy) { var t = til[ix, iy].Tile; Debug.Log( til[ix, iy].Brush.ToString() + "," + til[ix, iy].TileSet.ToString() + "," + til[ix, iy].TileIndex.ToString() + "," + til[ix, iy].Tile.ToString()); Debug.Log( zon.Tiles[t].Layer1.ToString() + "," + zon.Tiles[t].Offset1.ToString() + "," + zon.Tiles[t].Layer2.ToString() + "," + zon.Tiles[t].Offset2.ToString() + "," + zon.Tiles[t].TileType.ToString() + "," + zon.Tiles[t].TileType.ToString() + "," + zon.Tiles[t].Rotation.ToString()); Debug.Log(zon.Textures[zon.Tiles[t].Layer1 + zon.Tiles[t].Offset1]); Debug.Log(zon.Textures[zon.Tiles[t].Layer2 + zon.Tiles[t].Offset2]); } } */ var td = new TerrainData(); td.size = new Vector3(80, heightDelta/100, 80); td.heightmapResolution = 65; td.SetHeights(0, 0, heights); var ts = new SplatPrototype[1]; ts[0] = new SplatPrototype(); ts[0].texture = tex; ts[0].tileSize = new Vector2(160, 160); td.splatPrototypes = ts; var ter = Terrain.CreateTerrainGameObject(td).GetComponent<Terrain>(); ter.name = blockName; ter.transform.localPosition = new Vector3(blockX, heightBase/100, blockY); return ter; }
public void GenerateTerrain() { terraindata = terrain.terrainData; float [] positionsx = new float[aantalHeuvels]; float[] positionsz = new float[aantalHeuvels]; int heightmapwidth = terraindata.heightmapWidth-1; int heightmapheigth = terraindata.heightmapHeight - 1; float beginhoogte = 0.003f; float[,] heights = new float[heightmapwidth + 1, heightmapheigth + 1]; for (int x = 0; x < heightmapwidth; x++) { for(int z = 0; z < heightmapheigth; z++){ heights[x,z] = beginhoogte; } } terraindata.SetHeights(0,0,heights); // heuvels genereren for (int i = 0; i < aantalHeuvels; i++) { int beginx = (int) (Random.value*heightmapwidth); int beginz = (int) (Random.value*heightmapheigth); positionsx[i] = beginx; positionsz[i] = beginz; int heuvelradius = (int) (Random.Range(70,100)); float top = 0.03f; float helling = (float)(top*(0.002f/0.03f)); for(int r = 1; r < heuvelradius; r++){ for(int d = 0; d < 360; d++){ int xx = beginx + (int)(r*Mathf.Cos(d*Mathf.PI/180)); int x = Mathf.Min(xx,heightmapwidth); int zz = beginz + (int)(r*Mathf.Sin(d*Mathf.PI/180)); int z = Mathf.Min(zz,heightmapheigth); float hoogte = Mathf.Max ((float)(top-(Mathf.Pow((r*helling),2))),(float)(beginhoogte*1.1)); if(heights[Mathf.Max(x,0),Mathf.Max(z,0)]<hoogte){ heights[Mathf.Max(x,0),Mathf.Max(z,0)] = hoogte; } } } } // sloten genereren for (int i = 0; i < aantalSloten; i++) { float randomx = Random.value; float randomz = Random.value; int beginx = (int) (randomx*(float)heightmapwidth); int beginz = (int) (randomz*(float)heightmapheigth); float realx = ((float)beginx/(float)heightmapwidth)*terraindata.size.x; float realz = ((float)beginz/(float)heightmapheigth)*terraindata.size.z; int slootbreedte = (int)(Random.Range(50,70)); int slootlengte = (int)(Random.Range(300,400)); GameObject gras = Resources.Load ("FernMesh") as GameObject; float lengteGras = gras.GetComponent<Renderer>().bounds.size.x; if(Random.value>0){ for(int x = 0; x < slootlengte; x++){ for(int z = 0; z < slootbreedte; z++){ int xx = Mathf.Min((beginx + x),heightmapwidth); int zz = Mathf.Min((beginz + z),heightmapheigth); if(positioncheck(xx, zz, positionsx, positionsz)){ heights[Mathf.Max(xx,0), Mathf.Max (zz,0)] = 0; } } } //STAAT UIT for(int k = 0; k < 10; k++){ if(false){ GameObject nieuwgras = Instantiate (gras); nieuwgras.transform.position = new Vector3(realz, 2, realx + Random.value*k*lengteGras); nieuwgras.transform.localScale = new Vector3(500,500,500); nieuwgras.transform.eulerAngles = new Vector3(0,Random.value*Mathf.PI,0); } } } else{ for(int x = 0; x < slootbreedte; x++){ for(int z = 0; z < slootlengte; z++){ int xx = Mathf.Min((beginx + x),heightmapwidth); int zz = Mathf.Min((beginz + z),heightmapheigth); if(positioncheck(xx, zz, positionsx, positionsz)){ heights[Mathf.Max(xx,0), Mathf.Max (zz,0)] = 0; } } } } } // vijvers genereren for (int i = 0; i < aantalVijvers; i++) { int beginx = (int) (Random.value*heightmapwidth); int beginz = (int) (Random.value*heightmapheigth); int vijverradius = (int) (Random.Range(30,70)); for(int r = 1; r < vijverradius; r++){ for(int d = 0; d < 360; d++){ int xx = beginx + (int)(r*Mathf.Cos(d*Mathf.PI/180)); int x = Mathf.Min(xx,heightmapwidth); int zz = beginz + (int)(r*Mathf.Sin(d*Mathf.PI/180)); int z = Mathf.Min(zz,heightmapheigth); if(positioncheck(x,z,positionsx, positionsz)){ heights[Mathf.Max(x,0),Mathf.Max(z,0)] = 0; } } } } terraindata.SetHeights (0, 0, heights); for (int i = 0; i < 5; i++) { Smooth(); } }