GetHeights() private method

private GetHeights ( int xBase, int yBase, int width, int height ) : ].float[
xBase int
yBase int
width int
height int
return ].float[
Example #1
0
        /// <summary>
        /// This method allows to save the terrain data (details, heightmaps).
        /// </summary>
        public void SaveTerrainData()
        {
            if (!IsInitialized)
            {
                return;
            }

            if (ActiveTerrain == null)
            {
                return;
            }

            TerrainDetails = new Dictionary <int, int[, ]>();

            if (Data == null)
            {
                return;
            }

            for (int Layer = 0; Layer < Data.detailPrototypes.Length; Layer++)
            {
                TerrainDetails.Add(Layer, Data.GetDetailLayer(0, 0, Data.detailWidth, Data.detailHeight, Layer));
            }

            TerrainHeights = Data.GetHeights(0, 0, Data.heightmapWidth, Data.heightmapHeight);
        }
Example #2
0
 void Start()
 {
     tData = myTerrain.terrainData;
     xResolution = tData.heightmapWidth;
     zResolution = tData.heightmapHeight;
     heights = tData.GetHeights(0, 0, xResolution, zResolution);
 }
Example #3
0
    void Awake()
    {
        Debug.Log("Awake WorldMap");
        MapTile tempMapTile;
        BitMapDecoder bmd = new BitMapDecoder(heightmap);
        terrainData = terrain.terrainData;
        int heighMapWidth = terrainData.heightmapWidth;
        int heighMapHeight = terrainData.heightmapHeight;
        float[,] tempFloat = terrainData.GetHeights(0, 0, heighMapWidth, heighMapHeight);
        tilesDictionary = new Dictionary<string, MapTile>();

        for (int z = 0; z < mapSizeZ; z++ ) {
            for (int x = 0; x < mapSizeX; x++) {
                tempMapTile = new MapTile(x,z);
                int height = BitMapDecoder.getHeightPos(x, z);
                tempMapTile.setY(height);
                //tempFloat[x*2+1, z*2+1] = height / 5;
                tempFloat[x * 2, z*2 * 2] = (float)height / 10;
                //tempFloat[x*2, z * 2+1] = height / 5;
                //tempFloat[x * 2 + 1, z * 2] = height / 5;

                tilesDictionary.Add(("x" + x.ToString() + "z" + z.ToString()), tempMapTile);
            }
        }
        terrain.terrainData.SetHeights(0, 0, tempFloat);
    }
 public void Awake()
 {
     waterScript = (WaterToolScript)target as WaterToolScript;
     terComponent = (Terrain) waterScript.GetComponent(typeof(Terrain));
     if(terComponent == null)
         Debug.LogError("This script must be attached to a terrain object - Null reference will be thrown");
     terData = terComponent.terrainData;
     terrainHeights = terData.GetHeights(0, 0, terData.heightmapResolution, terData.heightmapResolution);
 }
    public static Mesh createMesh(TerrainData t, Vector3 terrainPosition)
    {
        Mesh m = new Mesh();

        int w = t.heightmapWidth;
        int h = t.heightmapHeight;
        Vector3 meshScale = t.size;
        int tRes = 2;
        meshScale = new Vector3(meshScale.x / (w - 1) * tRes, meshScale.y, meshScale.z / (h - 1) * tRes);

        float[,] tData = t.GetHeights(0, 0, w, h);

        w = (w - 1) / tRes + 1;
        h = (h - 1) / tRes + 1;

        Vector3[] tVertices = new Vector3[w * h];

        int[] tPolys;

        tPolys = new int[(w - 1) * (h - 1) * 6];

        // Build vertices
        for (int y = 0; y < h; y++)
        {
            for (int x = 0; x < w; x++)
            {
                tVertices[y * w + x] = Vector3.Scale(meshScale, new Vector3(-y, tData[x * tRes, y * tRes], x)) + terrainPosition;
            }
        }

        int index = 0;

        // Build triangle indices: 3 indices into vertex array for each triangle
        for (int y = 0; y < h - 1; y++)
        {
            for (int x = 0; x < w - 1; x++)
            {
                // For each grid cell output two triangles
                tPolys[index++] = (y * w) + x;
                tPolys[index++] = ((y + 1) * w) + x;
                tPolys[index++] = (y * w) + x + 1;

                tPolys[index++] = ((y + 1) * w) + x;
                tPolys[index++] = ((y + 1) * w) + x + 1;
                tPolys[index++] = (y * w) + x + 1;
            }
        }

        m.vertices = tVertices;
        m.triangles = tPolys;
        m.subMeshCount = 1;

        return m;
    }
Example #6
0
    // Use this for initialization
    void Start()
    {
        terrain = GetComponent<Terrain>();
        tData = terrain.terrainData;
        height = tData.heightmapHeight;
        widht = tData.heightmapWidth;

        heights = tData.GetHeights(0, 0, widht, height);

        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < widht; x++)
            {
                heights[x, y] = 1.0f;
            }
        }

        //tData.SetHeights(0, 0, heights);
    }
Example #7
0
	/// <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;
	}
Example #8
0
 /// <summary>
 /// Write the specified value using the writer.
 /// </summary>
 /// <param name="value">Value.</param>
 /// <param name="writer">Writer.</param>
 public override void Write(object value, ISaveGameWriter writer)
 {
     UnityEngine.TerrainData terrainData = (UnityEngine.TerrainData)value;
     float [,,] alphamaps = terrainData.GetAlphamaps(0, 0, terrainData.alphamapWidth, terrainData.alphamapHeight);
     float [,] heights    = terrainData.GetHeights(0, 0, terrainData.heightmapResolution, terrainData.heightmapResolution);
     writer.WriteProperty("alphamaps", alphamaps);
     writer.WriteProperty("heights", heights);
     writer.WriteProperty("heightmapResolution", terrainData.heightmapResolution);
     writer.WriteProperty("size", terrainData.size);
     writer.WriteProperty("thickness", terrainData.thickness);
     writer.WriteProperty("wavingGrassStrength", terrainData.wavingGrassStrength);
     writer.WriteProperty("wavingGrassAmount", terrainData.wavingGrassAmount);
     writer.WriteProperty("wavingGrassSpeed", terrainData.wavingGrassSpeed);
     writer.WriteProperty("wavingGrassTint", terrainData.wavingGrassTint);
     writer.WriteProperty("detailPrototypes", terrainData.detailPrototypes);
     writer.WriteProperty("treeInstances", terrainData.treeInstances);
     writer.WriteProperty("treePrototypes", terrainData.treePrototypes);
     writer.WriteProperty("alphamapResolution", terrainData.alphamapResolution);
     writer.WriteProperty("baseMapResolution", terrainData.baseMapResolution);
     writer.WriteProperty("splatPrototypes", terrainData.splatPrototypes);
     writer.WriteProperty("name", terrainData.name);
     writer.WriteProperty("hideFlags", terrainData.hideFlags);
 }
Example #9
0
    // 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);
    }
Example #10
0
    public void ConformTerrain()
    {
        if ( tobj )
        {
            if ( restorebefore )
                ResetHeights();

            BuildVerts();
            BuildCollider();

            GameObject lobj = null;
            GameObject robj = null;
            MeshCollider lcol = null;
            MeshCollider rcol = null;

            if ( leftenabled )
                lcol = BuildCollider(vertsl, uvsl, steps, 1, false, ref lobj);

            if ( rightenabled )
                rcol = BuildCollider(vertsr, uvsr, steps, 1, true, ref robj);

            doterraindeform = false;
            if ( terrain == null )
                terrain = tobj.GetComponent<Terrain>();

            Collider col = mcol;

            if ( col && terrain )
            {
                tdata = terrain.terrainData;
                float[,] heights = tdata.GetHeights(0, 0, tdata.heightmapWidth, tdata.heightmapHeight);
                float[,] newheights = new float[tdata.heightmapWidth, tdata.heightmapHeight];

                bool[,] hits = new bool[tdata.heightmapWidth, tdata.heightmapHeight];

                Matrix4x4 tm = terrain.transform.localToWorldMatrix;
                Matrix4x4 wtm = terrain.transform.worldToLocalMatrix;
                Vector3 p = Vector3.zero;
                Ray ray = new Ray();

                for ( int y = 0; y < tdata.heightmapHeight; y++ )
                {
                    p.z = ((float)y / (float)tdata.heightmapHeight) * tdata.size.z;

                    for ( int x = 0; x < tdata.heightmapWidth; x++ )
                    {
                        p.y = heights[y, x];
                        newheights[y, x] = p.y;

                        p.y *= tdata.size.y;
                        p.x = ((float)x / (float)tdata.heightmapWidth) * tdata.size.x;

                        Vector3 wp = tm.MultiplyPoint3x4(p);

                        wp.y += startray;
                        ray.origin = wp;
                        ray.direction = Vector3.down;
                        RaycastHit hit;

                        if ( col.Raycast(ray, out hit, raydist) )
                        {
                            Vector3 lp = wtm.MultiplyPoint3x4(hit.point);

                            float h = sectioncrv.Evaluate(hit.textureCoord.x);

                            float nh = (lp.y - offset + h) / tdata.size.y;
                            newheights[y, x] = nh;

                            hits[y, x] = true;
                        }
                        else
                        {
                            if ( leftenabled && lcol.Raycast(ray, out hit, raydist) )
                            {
                                int face = (hit.triangleIndex / 2);
                                Vector3 lp = wtm.MultiplyPoint3x4(vertsl[face * 2]);
                                Vector3 lp1 = wtm.MultiplyPoint3x4(vertsl[(face + 1) * 2]);

                                float y1 = Mathf.Lerp(lp.y, lp1.y, hit.barycentricCoordinate.x);
                                float nh = (y1 - offset) / tdata.size.y;
                                newheights[y, x] = Mathf.Lerp(nh, newheights[y, x], leftfallcrv.Evaluate(hit.textureCoord.x));	//.0f - hit.textureCoord.x);
                                hits[y, x] = true;
                            }
                            else
                            {
                                if ( rightenabled && rcol.Raycast(ray, out hit, raydist) )
                                {
                                    int face = (hit.triangleIndex / 2);
                                    Vector3 lp = wtm.MultiplyPoint3x4(vertsr[face * 2]);
                                    Vector3 lp1 = wtm.MultiplyPoint3x4(vertsr[(face + 1) * 2]);

                                    float y1 = Mathf.Lerp(lp.y, lp1.y, hit.barycentricCoordinate.x);
                                    float nh = (y1 - offset) / tdata.size.y;
                                    newheights[y, x] = Mathf.Lerp(nh, newheights[y, x], 1.0f - rightfallcrv.Evaluate(1.0f - hit.textureCoord.x));	//.0f - hit.textureCoord.x);
                                    hits[y, x] = true;
                                }
                            }
                        }
                    }
                }

                if ( numpasses > 0 )
                {
                    float[,] smoothed = SmoothTerrain(newheights, numpasses, tdata.heightmapWidth, tdata.heightmapHeight, hits);
                    tdata.SetHeights(0, 0, smoothed);
                }
                else
                    tdata.SetHeights(0, 0, newheights);
            }

            if ( Application.isEditor && !Application.isPlaying )
            {
                if ( colobj )
                    GameObject.DestroyImmediate(colobj);

                if ( lobj )
                    GameObject.DestroyImmediate(lobj);

                if ( robj )
                    GameObject.DestroyImmediate(robj);
            }
            else
            {
                if ( colobj )
                    GameObject.Destroy(colobj);

                if ( lobj )
                    GameObject.Destroy(lobj);

                if ( robj )
                    GameObject.Destroy(robj);
            }
        }
    }
Example #11
0
 void Start()
 {
     craterWidth = crater.width;
     craterHeight = crater.height;
     terrain = GetComponent<Terrain> ();
     data = terrain.terrainData;
     heightRestore = data.GetHeights (0, 0, data.heightmapWidth, data.heightmapHeight);
     alphaRestore = data.GetAlphamaps (0, 0, data.alphamapHeight, data.alphamapWidth);
     template = crater.GetPixels ();
     worker = new Thread (WorkerMethod);
     worker.Start ();
     StartCoroutine (ApplyDamage ());
 }
Example #12
0
    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);
        }
    }
	public void NewPath()
	{
		nodeObjects = new PathNodeObjects[0];
		pathCollider = (MeshCollider)pathMesh.AddComponent(typeof(MeshCollider));
		
		terrainObj = parentTerrain;
		terComponent = (Terrain) terrainObj.GetComponent(typeof(Terrain));
		
		if(terComponent == null)
			Debug.LogError("This script must be attached to a terrain object - Null reference will be thrown");
			
		terData = terComponent.terrainData;
		terrainHeights = terData.GetHeights(0, 0, terData.heightmapResolution, terData.heightmapResolution);
		terrainCollider = (TerrainCollider)terrainObj.GetComponent(typeof(TerrainCollider));
	}
    // Use this for initialization
    void Start()
    {
        r = new System.Random ();
        islandChoice = r.Next () % 2;
        terr = Terrain.activeTerrain;
        td = terr.terrainData;
        float[,] heights;
        int w = td.heightmapWidth;
        int h = td.heightmapHeight;
        heights = td.GetHeights (0, 0, w, h);

        float startx = r.Next (99);
        float starty = r.Next (99);

        for (int i = 0; i < w; i++) {
            for (int j = 0; j < h; j++) {
                heights[i,j] = Mathf.PerlinNoise((float)(i + startx) / 80f, (float)(j + starty) / 80f)/3f ;
            }
        }

        switch (islandChoice)
        {
        case 0:
            //modify the island's edges so they go beneath the water
            Vector2 center, dist;
            float height = minHeight;
            float mag;
            int isleRadius = r.Next(isleMinRadius, isleMaxRadius);
            center = new Vector2(w/2,h/2);
            for (int i = 0; i < w; i++)
            {
                for (int j = 0; j < h; j++)
                {
                    dist = new Vector2(i,j);
                    mag = (dist - center).magnitude;

                    if (mag > isleRadius)
                        height = 0f;
                    else{
                        //Set the outer edge of the circle to be 0 and the center to be 1
                        height = -(mag / ((float)isleRadius) - 1f);

                        //Set up height for
                        height *= Mathf.PI;
                        height -= Mathf.PI / 2;
                        height = (Mathf.Sin(height) + 1) / 2;
                    }
                    heights[i,j] *= height;

                }
            }
            break;
        case 1:
            //reduce the random height of protrusions and dips for deserts
            maxHeight = minHeight + ((maxHeight - minHeight) / 2);
            minProtrusions /= 2;
            maxProtrusions /= 2;
            minDipRadius /= 2;
            maxDipRadius /= 2;
            maxDipHeight = minDipHeight + ((maxDipHeight - minDipHeight) / 2);
            break;
        }

        //Create upward protrusions for mountains
        TerrainProtrusions.createProtrusions((int)transform.position.x,(int)transform.position.y,w+(int)transform.position.x,h+(int)transform.position.y,minRadius,maxRadius,minHeight,maxHeight,minProtrusions,maxProtrusions,true);

        //Create the downward protrusions for rivers and lakes
        TerrainProtrusions.createProtrusions((int)transform.position.x,(int)transform.position.y,w+(int)transform.position.x,h+(int)transform.position.y,minDipRadius,maxDipRadius,minDipHeight,maxDipHeight,minDips,maxDips,false);

        //apply the protrusions to the height map
        TerrainProtrusions.modifyHeightMap (heights, (int)transform.position.x,(int)transform.position.y);

        td.SetHeights (0, 0, heights);

        assignSplatMaps ();
    }
    public void Start()
    {
        terrainObject = parentTerrain;
        waterScript = (WaterToolScript)terrainObject.GetComponent("WaterToolScript");
        terComponent = (Terrain) terrainObject.GetComponent(typeof(Terrain));

        if(terComponent == null)
            Debug.LogError("This script must be attached to a terrain object - Null reference will be thrown");

        terData = terComponent.terrainData;
        terrainHeights = terData.GetHeights(0, 0, terData.heightmapResolution, terData.heightmapResolution);

        riverSmooth = 15;
        riverNodeMode = false;
        finalized = false;
        showHandles = true;
    }
Example #16
0
    public void SaveHeights()
    {
        if ( terrain == null )
            terrain = tobj.GetComponent<Terrain>();

        if ( terrain )
        {
            tdata = terrain.terrainData;
            float[,] heights = tdata.GetHeights(0, 0, tdata.heightmapWidth, tdata.heightmapHeight);
            savedheights = new float[tdata.heightmapWidth * tdata.heightmapHeight];
            Convert(heights, savedheights, tdata.heightmapWidth, tdata.heightmapHeight);
        }
    }
Example #17
0
			public float[,] ReadHeighmap (TerrainData data, float height=1)
			{
				CoordRect intersection = CoordRect.Intersect(rect, new CoordRect(0,0,data.heightmapResolution, data.heightmapResolution));
				
				//get heights
				float[,] array = data.GetHeights(intersection.offset.x, intersection.offset.z, intersection.size.x, intersection.size.z); //returns x and z swapped

				//reading 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++)
						this[x,z] = array[z-min.z, x-min.x] * height;

				//removing borders
				RemoveBorders(intersection);

				return array;
			}
	 void ConvertUTerrain()
	{
		if (terrainName=="")
			terrainName =CurrentSelect.name; 
				
		if (!System.IO.Directory.Exists(T4MPrefabFolder+"Terrains/"))
		{
			System.IO.Directory.CreateDirectory(T4MPrefabFolder+"Terrains/");
		} 
		if (!System.IO.Directory.Exists(T4MPrefabFolder+"Terrains/Material/"))
		{
			System.IO.Directory.CreateDirectory(T4MPrefabFolder+"Terrains/Material/");
		} 
		if (!System.IO.Directory.Exists(T4MPrefabFolder+"Terrains/Texture/"))
		{
			System.IO.Directory.CreateDirectory(T4MPrefabFolder+"Terrains/Texture/");
		} 
		if (!System.IO.Directory.Exists(T4MPrefabFolder+"Terrains/Meshes/"))
		{
			System.IO.Directory.CreateDirectory(T4MPrefabFolder+"Terrains/Meshes/");
		} 
		AssetDatabase.Refresh(); 
		
		terrain = CurrentSelect.GetComponent <Terrain>().terrainData;
        int w = terrain.heightmapWidth;
        int h = terrain.heightmapHeight;
        Vector3 meshScale = terrain.size;
        meshScale = new Vector3(meshScale.x/(h-1)*tRes, meshScale.y, meshScale.z/(w-1)*tRes);
	    Vector2 uvScale =  new Vector2((float)(1.0/(w-1)),(float) (1.0/(h-1)));
		
        float[,] tData = terrain.GetHeights(0, 0, w, h);
        w = (int)((w-1) / tRes + 1);
        h = (int)((h-1) / tRes + 1);
        Vector3[] tVertices = new Vector3[w * h];
        Vector2[] tUV = new Vector2[w * h];
        int[] tPolys = new int[(w-1) * (h-1) * 6];
		int y=0;
		int x  =0;
        for (y = 0; y < h; y++) {
			for ( x = 0; x < w; x++) {
                tVertices[y*w + x] = Vector3.Scale(meshScale, new Vector3(x, tData[(int)(x*tRes),(int)(y*tRes)], y));
                tUV[y*w + x] = Vector2.Scale(new Vector2(y*tRes, x*tRes), uvScale);
            }
        }
		
		y  =0;
		x =0;
        int  index = 0;
        for ( y = 0; y < h-1; y++) {
                for ( x = 0; x < w-1; x++) {
                    tPolys[index++] = (y*w) + x;
                    tPolys[index++] = ((y+1) * w) + x;
                    tPolys[index++] = (y*w) + x + 1;
        
                    tPolys[index++] = ((y+1) * w) + x;
                    tPolys[index++] = ((y+1) * w) + x + 1;
                    tPolys[index++] = (y*w) + x + 1;
                }
            }
		
			bool ExportNameSuccess = false;
			int num =1;
			string Next;
			do { 
				Next=terrainName+num;
				
				if (!System.IO.File.Exists(T4MPrefabFolder+"Terrains/"+terrainName+".prefab"))
				{
					FinalExpName = terrainName;
					ExportNameSuccess = true;
				}
				else if (!System.IO.File.Exists(T4MPrefabFolder+"Terrains/"+Next+".prefab"))
				{
					FinalExpName=Next;
					ExportNameSuccess = true;
				}
				num++;
			}while (!ExportNameSuccess);
	
		 //StreamWriter  sw = new StreamWriter(T4MPrefabFolder+"Terrains/Meshes/"+FinalExpName+".obj");
		StreamWriter  sw = new StreamWriter(FinalExpName+".obj");
        try {
           
            sw.WriteLine("# T4M File");
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
            counter = tCount = 0;
            totalCount = (int) ((tVertices.Length*2 + (tPolys.Length/3)) / progressUpdateInterval);
            for (int i = 0; i < tVertices.Length; i++) {
                UpdateProgress();
                 StringBuilder sb = new StringBuilder("v ", 20);
                sb.Append(tVertices[i].x.ToString()).Append(" ").
                   Append(tVertices[i].y.ToString()).Append(" ").
                   Append(tVertices[i].z.ToString());
                sw.WriteLine(sb);
            }
			
            for (int i = 0; i < tUV.Length; i++) {
                UpdateProgress();
                StringBuilder sb = new StringBuilder("vt ", 22);
                sb.Append(tUV[i].x.ToString()).Append(" ").
                   Append(tUV[i].y.ToString());
                sw.WriteLine(sb);
            }
                for (int i = 0; i < tPolys.Length; i += 3) {
                    UpdateProgress();
                    StringBuilder sb = new StringBuilder("f ", 43);
                    sb.Append(tPolys[i]+1).Append("/").Append(tPolys[i]+1).Append(" ").
                       Append(tPolys[i+1]+1).Append("/").Append(tPolys[i+1]+1).Append(" ").
                       Append(tPolys[i+2]+1).Append("/").Append(tPolys[i+2]+1);
                    sw.WriteLine(sb);
                }
        }
        catch (Exception err) {
            Debug.Log("Error saving file: " + err.Message);
        }
        sw.Close();
		AssetDatabase.SaveAssets(); 
	
		string path = T4MPrefabFolder+"Terrains/Texture/"+FinalExpName+".png";
		
		//Control Texture Creation or Recuperation
		string AssetName = AssetDatabase.GetAssetPath(CurrentSelect.GetComponent <Terrain>().terrainData) as string;
		UnityEngine.Object[] AssetName2 = AssetDatabase.LoadAllAssetsAtPath (AssetName);
		if (AssetName2 !=null && AssetName2.Length>1 && keepTexture){
			for (var b = 0; b < AssetName2.Length; b++) {
				if(AssetName2[b].name == "SplatAlpha 0"){
					Texture2D texture  = AssetName2[b] as Texture2D;
					byte[] bytes = texture.EncodeToPNG();
			  		File.WriteAllBytes(path, bytes);
					AssetDatabase.ImportAsset (path, ImportAssetOptions.ForceUpdate);
				}
			}
		}else{ 
			Texture2D NewMaskText = new Texture2D (512, 512,  TextureFormat.ARGB32, true);
			Color[] ColorBase = new Color[512 * 512];
			for (var t = 0; t < ColorBase.Length; t++) {
					ColorBase[t] = new Color (1, 0, 0, 0);
			}
			NewMaskText.SetPixels (ColorBase);
			byte[] data = NewMaskText.EncodeToPNG ();
			File.WriteAllBytes (path, data);
			AssetDatabase.ImportAsset (path, ImportAssetOptions.ForceUpdate);
		}
		AssetDatabase.ImportAsset (path, ImportAssetOptions.ForceUpdate);
		
		UpdateProgress();
		
		//Modification de la Texture 
		TextureImporter TextureI= AssetImporter.GetAtPath (path) as TextureImporter;
		TextureI.textureFormat = TextureImporterFormat.ARGB32;
		TextureI.isReadable = true;
		TextureI.anisoLevel = 9;
		TextureI.mipmapEnabled = false;
		TextureI.wrapMode = TextureWrapMode.Clamp;
		AssetDatabase.Refresh();
		
		AssetDatabase.ImportAsset (path, ImportAssetOptions.ForceUpdate);
		
		UpdateProgress();
		
		//Creation du Materiel
		Material Tmaterial;
		Tmaterial = new Material (Shader.Find("T4MShaders/ShaderModel2/Diffuse/T4M 4 Textures"));
		AssetDatabase.CreateAsset(Tmaterial, T4MPrefabFolder+"Terrains/Material/"+FinalExpName+".mat");
		AssetDatabase.ImportAsset (T4MPrefabFolder+"Terrains/Material/"+FinalExpName+".mat", ImportAssetOptions.ForceUpdate);
		AssetDatabase.Refresh();
		
		//Recuperation des Texture du terrain
		if (keepTexture){
			SplatPrototype[] texts = CurrentSelect.GetComponent <Terrain>().terrainData.splatPrototypes;
			for (int e = 0 ; e < texts.Length ; e++){
				if (e<4){
					Tmaterial.SetTexture("_Splat"+e, texts[e].texture);
					Tmaterial.SetTextureScale ("_Splat"+e, texts[e].tileSize*8.9f);
				}
			}
		}
		
		//Attribution de la Texture Control sur le materiau
		Texture test =(Texture) Resources.LoadAssetAtPath(path, typeof(Texture));
		Tmaterial.SetTexture ("_Control", test);
		
		
		UpdateProgress();
		
		
		//Deplacement de l'obj dans les repertoire mesh
		FileUtil.CopyFileOrDirectory (FinalExpName+".obj",T4MPrefabFolder+"Terrains/Meshes/"+FinalExpName+".obj");
		FileUtil.DeleteFileOrDirectory(FinalExpName+".obj");
		
		
		
		//Force Update
		AssetDatabase.ImportAsset (T4MPrefabFolder+"Terrains/Meshes/"+FinalExpName+".obj", ImportAssetOptions.ForceUpdate);
		
		UpdateProgress();
		
		//Instance du T4M
		GameObject  prefab = (GameObject)Resources.LoadAssetAtPath(T4MPrefabFolder+"Terrains/Meshes/"+FinalExpName+".obj", typeof(GameObject));
		
		AssetDatabase.Refresh();
		
		
		GameObject forRotate = (GameObject) Instantiate (prefab, CurrentSelect.transform.position, Quaternion.identity) as GameObject;
		Transform childCheck = forRotate.transform.Find("default");
		Child = childCheck.gameObject;
		forRotate.transform.DetachChildren();
		DestroyImmediate(forRotate);
		Child.name = FinalExpName;
		Child.AddComponent("T4MObjSC");
		Child.transform.rotation= Quaternion.Euler(0, 90, 0);
		
		UpdateProgress();
				
		//Application des Parametres sur le Script
		Child.GetComponent <T4MObjSC>().T4MMaterial = Tmaterial;
		Child.GetComponent<T4MObjSC>().ConvertType= "UT";
		
		//Regalges Divers
		vertexInfo = 0;
		partofT4MObj = 0;
		trisInfo = 0; 
		int countchild = Child.transform.childCount;
		if (countchild>0){
			Renderer[] T4MOBJPART = Child.GetComponentsInChildren<Renderer>();
			for (int i = 0; i < T4MOBJPART.Length; i++) 
			{
				if (!T4MOBJPART[i].gameObject.AddComponent("MeshCollider"))
					T4MOBJPART[i].gameObject.AddComponent("MeshCollider");
				T4MOBJPART[i].gameObject.isStatic = true;
				T4MOBJPART[i].material = Tmaterial;
				T4MOBJPART[i].gameObject.layer = 30; 
				T4MOBJPART[i].gameObject.AddComponent("T4MPartSC");
				Child.GetComponent<T4MObjSC>().T4MMesh = T4MOBJPART[0].GetComponent<MeshFilter>();
				partofT4MObj +=1;
				vertexInfo += T4MOBJPART[i].gameObject.GetComponent<MeshFilter>().sharedMesh.vertexCount;
				trisInfo += T4MOBJPART[i].gameObject.GetComponent<MeshFilter>().sharedMesh.triangles.Length / 3;
			}
		}else {
			Child.AddComponent("MeshCollider");
			Child.isStatic = true;
			Child.renderer.material = Tmaterial;
			Child.layer = 30; 
			vertexInfo += Child.GetComponent<MeshFilter>().sharedMesh.vertexCount;
			trisInfo += Child.GetComponent<MeshFilter>().sharedMesh.triangles.Length / 3;
			partofT4MObj +=1;
		}
		
		UpdateProgress();
		
		
		GameObject BasePrefab2 = PrefabUtility.CreatePrefab(T4MPrefabFolder+"Terrains/"+FinalExpName+".prefab", Child);
		AssetDatabase.ImportAsset (T4MPrefabFolder+"Terrains/"+FinalExpName+".prefab", ImportAssetOptions.ForceUpdate);
		GameObject forRotate2 = (GameObject) PrefabUtility.InstantiatePrefab (BasePrefab2) as GameObject;
		
		DestroyImmediate (Child.gameObject);
		
		Child = forRotate2.gameObject;
		
		CurrentSelect.GetComponent<Terrain>().enabled = false;
		
		EditorUtility.SetSelectedWireframeHidden(Child.renderer, true);
		
		UnityTerrain = CurrentSelect.gameObject;
		
		EditorUtility.ClearProgressBar();
		
		AssetDatabase.DeleteAsset(T4MPrefabFolder+"Terrains/Meshes/Materials");
		terrainName="";
		AssetDatabase.StartAssetEditing();
			//Modification des attribut du mesh avant de le préfabriquer
			ModelImporter OBJI= ModelImporter.GetAtPath(T4MPrefabFolder+"Terrains/Meshes/"+FinalExpName+".obj") as ModelImporter;
			OBJI.globalScale = 1;
			OBJI.splitTangentsAcrossSeams = true;
			OBJI.normalImportMode =ModelImporterTangentSpaceMode.Calculate;
			OBJI.tangentImportMode=ModelImporterTangentSpaceMode.Calculate;
			OBJI.generateAnimations = ModelImporterGenerateAnimations.None;
			OBJI.meshCompression=ModelImporterMeshCompression.Off;
			OBJI.normalSmoothingAngle = 180f;
			//AssetDatabase.ImportAsset (T4MPrefabFolder+"Terrains/Meshes/"+FinalExpName+".obj", ImportAssetOptions.TryFastReimportFromMetaData);
			AssetDatabase.ImportAsset (T4MPrefabFolder+"Terrains/Meshes/"+FinalExpName+".obj", ImportAssetOptions.ForceSynchronousImport);
		AssetDatabase.StopAssetEditing();
		PrefabUtility.ResetToPrefabState (Child);
	}
Example #19
0
    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);
    }
Example #20
0
        public BigMesh(TerrainData td, Bounds b)
        {
            int xSamples = td.heightmapWidth;
            int zSamples = td.heightmapHeight;
            Vector3 patchScale = td.size / (float)(td.heightmapResolution-1);
            patchScale.y = td.size.y;
            float[,] heights = td.GetHeights(0, 0, xSamples, zSamples);

            int minX = Mathf.Max(
                0,
                Mathf.FloorToInt((b.center.x - b.extents.x) / patchScale.x));
            int maxX = Mathf.Min(
                xSamples,
                Mathf.CeilToInt((b.center.x + b.extents.x) / patchScale.x) + 1);
            int minZ = Mathf.Max(
                0,
                Mathf.FloorToInt((b.center.z - b.extents.z) / patchScale.z));
            int maxZ = Mathf.Min(
                zSamples,
                Mathf.CeilToInt((b.center.z + b.extents.z) / patchScale.z) + 1);
            int sizeX = maxX - minX;
            int sizeZ = maxZ - minZ;
            this.vertices = new Vector3[sizeX * sizeZ];

            for (int iz = 0; iz < sizeZ; iz++)
            {
                for(int ix = 0; ix < sizeX; ix++)
                {
                    this.vertices[iz * sizeX + ix] = new Vector3(
                        (ix + minX) * patchScale.x,
                        heights[iz+minZ, ix+minX] * patchScale.y,
                        (iz + minZ) * patchScale.z);
                }
            }

            int numQuads = (sizeX-1) * (sizeZ-1);
            int numTriangles = numQuads * 2;
            this.triangles = new int[numTriangles * 3];
            int iind = 0;
            for (int iz = 0; iz < sizeZ-1; iz++)
            {
                for (int ix = 0; ix < sizeX - 1; ix++)
                {
                    int i1 = iz * sizeX + ix;
                    int i2 = i1 + 1;
                    int i3 = i1 + sizeX;
                    int i4 = i3 + 1;
                    this.triangles[iind + 0] = i1;
                    this.triangles[iind + 1] = i3;
                    this.triangles[iind + 2] = i2;
                    this.triangles[iind + 3] = i4;
                    this.triangles[iind + 4] = i2;
                    this.triangles[iind + 5] = i3;
                    iind += 6;
                }
            }
        }
        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);

             */
        }
Example #22
0
    void GetTerrainData()
    {
        if ( !terrain )
        {
           terrain = Terrain.activeTerrain;
        }

        terrainData = terrain.terrainData;

        terrainSize = terrain.terrainData.size;

        heightmapWidth = terrain.terrainData.heightmapWidth;
        heightmapHeight = terrain.terrainData.heightmapHeight;

        heightmapData = terrainData.GetHeights( 0, 0, heightmapWidth, heightmapHeight );
    }
Example #23
0
    void GetTerrainInfos()
    {
        terrain = terrainObj.GetComponent<Terrain>();
        terrainData = terrain.terrainData;

        terrainSize = terrain.terrainData.size;

        heightmapWidth = terrain.terrainData.heightmapWidth;
        heightmapHeight = terrain.terrainData.heightmapHeight;

        heightmapData = terrainData.GetHeights(0, 0, heightmapWidth, heightmapHeight);
    }
Example #24
-1
 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);
 }