Ejemplo n.º 1
0
        public static void Purge(MapMagic.CoordRect rect, Terrain terrain)
        {
            //skipping if already purged
            if (terrain.terrainData.alphamapResolution <= 16)
            {
                return;                                                         //using 8 will return resolution to 16
            }
            SplatPrototype[] prototypes = new SplatPrototype[1];
            if (prototypes[0] == null)
            {
                prototypes[0] = new SplatPrototype();
            }
            if (prototypes[0].texture == null)
            {
                prototypes[0].texture = defaultTex;
            }
            terrain.terrainData.splatPrototypes = prototypes;

            float[,,] emptySplats = new float[16, 16, 1];
            for (int x = 0; x < 16; x++)
            {
                for (int z = 0; z < 16; z++)
                {
                    emptySplats[z, x, 0] = 1;
                }
            }

            terrain.terrainData.alphamapResolution = 16;
            terrain.terrainData.SetAlphamaps(0, 0, emptySplats);
        }
Ejemplo n.º 2
0
			static public void AddSplatmaps (TerrainData data, Matrix[] matrices, int[] channels, float[] opacity, float[,,] array=null, float brushFallof=0.5f)
			{
				int numChannels = data.alphamapLayers;
				bool[] usedChannels = new bool[numChannels];
				for (int i=0; i<channels.Length; i++) usedChannels[channels[i]] = true;
				float[] slice = new float[numChannels];

				Coord dataSize = new Coord(data.alphamapResolution, data.alphamapResolution);
				CoordRect dataRect = new CoordRect(new Coord(0,0), dataSize);
				CoordRect intersection = CoordRect.Intersect(dataRect, matrices[0].rect);
				
				if (array==null) array = data.GetAlphamaps(intersection.offset.x, intersection.offset.z, intersection.size.x, intersection.size.z);

				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++)
				{
					//calculating fallof and opacity
					float fallofFactor = matrices[0].Fallof(x,z,brushFallof);
					if (Mathf.Approximately(fallofFactor,0)) continue;

					//reading slice
					for (int c=0; c<numChannels; c++) slice[c] = array[z-min.z, x-min.x, c];

					//converting matrices to additive
					for (int i=0; i<matrices.Length; i++) matrices[i][x,z] = Mathf.Max(0, matrices[i][x,z] - slice[channels[i]]);

					//apply fallof
					for (int i=0; i<matrices.Length; i++) matrices[i][x,z] *= fallofFactor * opacity[i];

					//calculating sum of adding values
					float addedSum = 0; //the sum of adding channels
					for (int i=0; i<matrices.Length; i++) addedSum += matrices[i][x,z];
					//if (addedSum < 0.00001f) continue; //no need to do anything

					//if addedsum exceeds 1 - equalizing matrices
					if (addedSum > 1f) 
						{ for (int i=0; i<matrices.Length; i++) matrices[i][x,z] /= addedSum; addedSum=1; }

					//multiplying all values on a remaining amount
					float multiplier = 1-addedSum;
					for (int c=0; c<numChannels; c++) slice[c] *= multiplier;

					//adding matrices
					for (int i=0; i<matrices.Length; i++) slice[channels[i]] += matrices[i][x,z];

					//saving slice
					for (int c=0; c<numChannels; c++) array[z-min.z, x-min.x, c] = slice[c];
				}

				data.SetAlphamaps(intersection.offset.x, intersection.offset.z, array);
			}
Ejemplo n.º 3
0
        public static bool IsIntersecting(CoordRect c1, CoordRect c2)
        {
            if (c2.Contains(c1.offset.x, c1.offset.z) || c2.Contains(c1.offset.x + c1.size.x, c1.offset.z) || c2.Contains(c1.offset.x, c1.offset.z + c1.size.z) || c2.Contains(c1.offset.x + c1.size.x, c1.offset.z + c1.size.z))
            {
                return(true);
            }
            if (c1.Contains(c2.offset.x, c2.offset.z) || c1.Contains(c2.offset.x + c2.size.x, c2.offset.z) || c1.Contains(c2.offset.x, c2.offset.z + c1.size.z) || c1.Contains(c2.offset.x + c2.size.x, c2.offset.z + c2.size.z))
            {
                return(true);
            }

            return(false);
        }
Ejemplo n.º 4
0
        public override void Generate(MapMagic.CoordRect rect, Chunk.Results results, Chunk.Size terrainSize, int seed, Func <float, bool> stop = null)
        {
            //loading inputs
            Matrix[] matrices = new Matrix[baseLayers.Length];
            for (int i = 0; i < baseLayers.Length; i++)
            {
                if (baseLayers[i].input != null)
                {
                    matrices[i] = (Matrix)baseLayers[i].input.GetObject(results);
                    if (matrices[i] != null)
                    {
                        matrices[i] = matrices[i].Copy(null);
                    }
                }
                if (matrices[i] == null)
                {
                    matrices[i] = new Matrix(rect);
                }
            }

            //blending layers
            if (obscureLayers)
            {
                Matrix.BlendLayers(matrices);
            }

            //masking layers
            Matrix mask = (Matrix)maskIn.GetObject(results);

            if (mask != null)
            {
                for (int i = 0; i < matrices.Length; i++)
                {
                    matrices[i].Multiply(mask);
                }
            }

            //saving outputs
            for (int i = 0; i < baseLayers.Length; i++)
            {
                if (stop != null && stop(0))
                {
                    return;                                        //do not write object is generating is stopped
                }
                if (baseLayers[i].output == null)
                {
                    baseLayers[i].output = new Output(InoutType.Map);                                               //back compatibility
                }
                baseLayers[i].output.SetObject(results, matrices[i]);
            }
        }
Ejemplo n.º 5
0
		public override void Generate(CoordRect rect, Chunk.Results results, Chunk.Size terrainSize, int seed, Func<float,bool> stop = null)
		{
	 		#if __MEGASPLAT__
			if ((stop!=null && stop(0)) || !enabled || textureList == null)
				return;

			//loading inputs
			Matrix[] matrices = new Matrix[baseLayers.Length];
			for (int i = 0; i < baseLayers.Length; i++)
			{
				if (baseLayers[i] == null)
					baseLayers[i] = new Layer();

				if (baseLayers[i].input != null)
				{
				   matrices[i] = (Matrix)baseLayers[i].input.GetObject(results);
				   if (matrices[i] != null)
				   {
					  matrices[i] = matrices[i].Copy(null);
					  matrices[i].Clamp01();
					}
				}
				if (matrices[i] == null)
				   matrices[i] = new Matrix(rect);
			}
			if (matrices.Length == 0)
				return;

			//background matrix
			//matrices[0] = terrain.defaultMatrix; //already created
			matrices[0].Fill(1);

			//populating opacity array
			float[] opacities = new float[matrices.Length];
			for (int i = 0; i < baseLayers.Length; i++)
				opacities[i] = baseLayers[i].opacity;
			opacities[0] = 1;

			//blending layers
			Matrix.BlendLayers(matrices, opacities);

			//saving changed matrix results
			for (int i = 0; i < baseLayers.Length; i++)
			{
				if (stop!=null && stop(0))
				   return; //do not write object is generating is stopped
				baseLayers[i].output.SetObject(results, matrices[i]);
			}
			#endif
		}
			public Matrix TestResize (CoordRect newRect)
			{
				Matrix result = new Matrix(newRect);

				Coord min = result.rect.Min; Coord max = result.rect.Max;
				for (int x=min.x; x<max.x; x++)
					for (int z=min.z; z<max.z; z++)
				{
					float percentX = 1f*(x-result.rect.offset.x)/result.rect.size.x; float origX = percentX*this.rect.size.x + this.rect.offset.x; 
					float percentZ = 1f*(z-result.rect.offset.z)/result.rect.size.z; float origZ = percentZ*this.rect.size.z + this.rect.offset.z; 
					result[x,z] = this.OutdatedGetInterpolated(origX, origZ);
				}

				return result;
			}
Ejemplo n.º 7
0
        public CoordRect Approximate(int val)
        {
            CoordRect approx = new CoordRect();

            approx.size.x = (size.x / val + 1) * val;
            approx.size.z = (size.z / val + 1) * val;

            approx.offset.x = offset.x - (approx.size.x - size.x) / 2;
            approx.offset.z = offset.z - (approx.size.z - size.z) / 2;

            approx.offset.x = (int)(approx.offset.x / val + 0.5f) * val;
            approx.offset.z = (int)(approx.offset.z / val + 0.5f) * val;

            return(approx);
        }
Ejemplo n.º 8
0
        public IEnumerator Apply(MapMagic.CoordRect rect, Terrain terrain, object dataBox, Func <float, bool> stop = null)
        {
            Dictionary <Transform, List <ObjectPool.Transition> > transitions = (Dictionary <Transform, List <ObjectPool.Transition> >)dataBox;
            var wrapper        = terrain.gameObject.GetOrAddComponent <TerrainWrapper>();
            var MMTerrainLayer = wrapper.GetLayer <MMTerrainLayer>(LayerName, false, true);

            MMTerrainLayer.Objects.Clear();

            //float pixelSize = 1f * global::MapMagic.MapMagic.instance.terrainSize / global::MapMagic.MapMagic.instance.resolution;
            //Rect terrainRect = new Rect(rect.offset.x * pixelSize, rect.offset.z * pixelSize, rect.size.x * pixelSize, rect.size.z * pixelSize);
            var terrainSize = terrain.terrainData.size;

            //adding
            foreach (KeyValuePair <Transform, List <ObjectPool.Transition> > kvp in transitions)
            {
                Transform prefab = kvp.Key;
                List <ObjectPool.Transition> transitionsList = kvp.Value;
                foreach (var transition in transitionsList)
                {
                    var terrainSpacePos = transition.pos - terrain.transform.localPosition /*- terrainSize/2*/;
                    var normalisedPos   = new Vector3(terrainSpacePos.x / terrainSize.x, transition.pos.y,
                                                      terrainSpacePos.z / terrainSize.z);

                    var prefabObj = new PrefabObjectData()
                    {
                        AbsoluteHeight    = false,
                        Guid              = System.Guid.NewGuid().ToString(),
                        Prefab            = prefab.gameObject,
                        Rotation          = transition.rotation.eulerAngles,
                        Position          = normalisedPos,
                        Scale             = transition.scale,
                        ContainerMetadata = LayerName,
                    };
                    MMTerrainLayer.Objects.Add(prefabObj);
                }
            }
            global::MapMagic.MapMagic.OnApplyCompleted -= MapMagicIntegrationUtilities.MapMagicOnOnApplyCompleted;
            global::MapMagic.MapMagic.OnApplyCompleted += MapMagicIntegrationUtilities.MapMagicOnOnApplyCompleted;

            wrapper.OnPostFinalise -= ApplyStampsToTerrain;
            if (ApplyStamps)
            {
                wrapper.OnPostFinalise += ApplyStampsToTerrain;
            }

            wrapper.SetDirtyAbove(MMTerrainLayer);
            yield break;
        }
Ejemplo n.º 9
0
 public Matrix2(int x, int z, T[] array = null)
 {
     rect  = new CoordRect(0, 0, x, z);
     count = x * z;
     if (array != null && array.Length < count)
     {
         Debug.Log("Array length: " + array.Length + " is lower then matrix capacity: " + count);
     }
     if (array != null && array.Length >= count)
     {
         this.array = array;
     }
     else
     {
         this.array = new T[count];
     }
 }
Ejemplo n.º 10
0
 public Matrix2(Coord offset, Coord size, T[] array = null)
 {
     rect  = new CoordRect(offset, size);
     count = rect.size.x * rect.size.z;
     if (array != null && array.Length < count)
     {
         Debug.Log("Array length: " + array.Length + " is lower then matrix capacity: " + count);
     }
     if (array != null && array.Length >= count)
     {
         this.array = array;
     }
     else
     {
         this.array = new T[count];
     }
 }
			/*public void FromTexture (Texture2D texture, Coord textureOffset=new Coord(), bool fillBorders=false)
			{
				Coord textureSize = new Coord(texture.width, texture.height);
				CoordRect textureRect = new CoordRect(textureOffset, textureSize);
				CoordRect intersection = CoordRect.Intersect(textureRect, rect);

				Color[] colors = texture.GetPixels(intersection.offset.x - textureOffset.x, intersection.offset.z - textureOffset.z, intersection.size.x, intersection.size.z);

				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++)
				{
					int tx = x-min.x; int tz = z-min.z;
					Color col = colors[tz*(max.x-min.x) + tx];

					this[x,z] = (col.r+col.g+col.b)/3;
				}

				if (fillBorders) RemoveBorders(intersection);
			}*/

			public void FromTexture (Texture2D texture)
			{
				CoordRect textureRect = new CoordRect(0,0, texture.width, texture.height);
				CoordRect intersection = CoordRect.Intersect(textureRect, rect);

				Color[] colors = texture.GetPixels(intersection.offset.x, intersection.offset.z, intersection.size.x, intersection.size.z);

				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++)
				{
					int tx = x-min.x; int tz = z-min.z;
					Color col = colors[tz*(max.x-min.x) + tx];

					this[x,z] = (col.r+col.g+col.b)/3;
				}
			}
Ejemplo n.º 12
0
        public void Fill(Matrix2 <T> m, bool removeBorders = false)
        {
            CoordRect intersection = CoordRect.Intersect(rect, m.rect);
            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] = m[x, z];
                }
            }
            if (removeBorders)
            {
                RemoveBorders(intersection);
            }
        }
Ejemplo n.º 13
0
        public override void Generate(MapMagic.Chunk chunk)
        {
            Matrix matrix = chunk.defaultMatrix;

            if (!enabled || textureMatrix == null)
            {
                output.SetObject(chunk, matrix); return;
            }
            if (chunk.stop)
            {
                return;
            }

            //matrix = textureMatrix.Resize(matrix.rect);

            CoordRect scaledRect = new CoordRect(
                (int)(offset.x * MapMagic.instance.resolution / MapMagic.instance.terrainSize),
                (int)(offset.y * MapMagic.instance.resolution / MapMagic.instance.terrainSize),
                (int)(matrix.rect.size.x * scale),
                (int)(matrix.rect.size.z * scale));
            Matrix scaledTexture = textureMatrix.Resize(scaledRect);

            matrix.Replicate(scaledTexture, tile: tile);
            matrix.Multiply(intensity);

            if (scale > 1)
            {
                Matrix cpy = matrix.Copy();
                for (int i = 0; i < scale - 1; i++)
                {
                    matrix.Blur();
                }
                Matrix.SafeBorders(cpy, matrix, Mathf.Max(matrix.rect.size.x / 128, 4));
            }

            //if (tile) textureMatrix.FromTextureTiled(texture);
            //else textureMatrix.FromTexture(texture);

            //if (!Mathf.Approximately(scale,1)) textureMatrix = textureMatrix.Resize(matrix.rect, result:matrix);*/
            if (chunk.stop)
            {
                return;
            }
            output.SetObject(chunk, matrix);
        }
			public float[,,] ReadSplatmap (TerrainData data, int channel, float[,,] array=null)
			{
				CoordRect intersection = CoordRect.Intersect(rect, new CoordRect(0,0,data.alphamapResolution, data.alphamapResolution));
				
				//get heights
				if (array==null) array = data.GetAlphamaps(intersection.offset.x, intersection.offset.z, intersection.size.x, intersection.size.z); //returns x and z swapped

				//reading 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, channel];

				//removing borders
				RemoveBorders(intersection);

				return array;
			}
			public Matrix OutdatedResize (CoordRect newRect, float smoothness=1, Matrix result=null)
			{
				//calculating ratio
				int upscaleRatio = newRect.size.x / rect.size.x;
				int downscaleRatio = rect.size.x / newRect.size.x;

				//checking if rect could be rescaled
				if (upscaleRatio > 1 && !newRect.Divisible(upscaleRatio)) Debug.LogError("Matrix rect " + rect + " could not be upscaled to " + newRect + " with factor " + upscaleRatio);
				if (downscaleRatio > 1 && !rect.Divisible(downscaleRatio)) Debug.LogError("Matrix rect " + rect + " could not be downscaled to " + newRect + " with factor " + downscaleRatio);

				//scaling
				if (upscaleRatio > 1) result = OutdatedUpscale(upscaleRatio, result:result);
				if (downscaleRatio > 1) result = OutdatedDownscale(downscaleRatio, smoothness:smoothness, result:result);

				//returning clone if all ratios are 1
				if (upscaleRatio <= 1 && downscaleRatio <= 1) return Copy(result);
				else return result;
			}
			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;
			}
Ejemplo n.º 17
0
        public IEnumerable <Coord> DistanceArea(CoordRect rect)         //same as distance are, but clamped by rect
        {
            int maxDist = Mathf.Max(x - rect.offset.x, rect.Max.x - x, z - rect.offset.z, rect.Max.z - z) + 1;

            if (rect.CheckInRange(this))
            {
                yield return(this);
            }
            for (int i = 0; i < maxDist; i++)
            {
                foreach (Coord c in DistancePerimeter(i))
                {
                    if (rect.CheckInRange(c))
                    {
                        yield return(c);
                    }
                }
            }
        }
				public Stacker (CoordRect smallRect, CoordRect bigRect)
				{
					this.smallRect = smallRect; this.bigRect = bigRect;
					isDownscaled = false;

					//do not create additional matrices if rect sizes are the same
					if (bigRect==smallRect)
					{
						upscaled = downscaled = new Matrix(bigRect);
					}

					else
					{
						downscaled = new Matrix(smallRect);
						upscaled = new Matrix(bigRect);
						difference = new Matrix(bigRect);
						//once arrays created they should not be resized
					}
				}
Ejemplo n.º 19
0
        public void Purge(MapMagic.CoordRect rect, Terrain terrain)
        {
            var wrapper = terrain.GetComponent <TerrainWrapper>();

            if (wrapper == null)
            {
                return;
            }
            var MMTerrainLayer = wrapper.GetLayer <MMTerrainLayer>(LayerName);

            if (MMTerrainLayer == null || MMTerrainLayer.Heights == null)
            {
                return;
            }
            MMTerrainLayer.Heights.Clear();
            wrapper.Dirty = true;

            Debug.Log("Heights Purged");
        }
Ejemplo n.º 20
0
 public void ClampByRect(CoordRect rect)
 {
     if (x < rect.offset.x)
     {
         x = rect.offset.x;
     }
     if (x >= rect.offset.x + rect.size.x)
     {
         x = rect.offset.x + rect.size.x - 1;
     }
     if (z < rect.offset.z)
     {
         z = rect.offset.z;
     }
     if (z >= rect.offset.z + rect.size.z)
     {
         z = rect.offset.z + rect.size.z - 1;
     }
 }
Ejemplo n.º 21
0
        public void Deploy(Vector3[] poses, float createRange, float removeRange)
        {
            bool reDeploy = false;

            //number of cams changed
            if (prevCreateRects == null || prevCreateRects.Length != poses.Length || prevRemoveRects.Length != poses.Length)
            {
                reDeploy        = true;
                prevCreateRects = new CoordRect[poses.Length];
                prevRemoveRects = new CoordRect[poses.Length];
                prevCenters     = new Coord[poses.Length];
            }

            //checking guard arrays
            for (int p = 0; p < poses.Length; p++)
            {
                Vector3 pos = poses[p];

                //finding rect and center
                CoordRect currCreateRect = pos.ToCoordRect(createRange, objectSize.x);
                CoordRect currRemoveRect = pos.ToCoordRect(removeRange, objectSize.x);
                Coord     currCenter     = pos.RoundToCoord(objectSize.x);

                //checking a need to re-deploy
                if (currCreateRect != prevCreateRects[p])
                {
                    reDeploy = true;
                }
                //if (currRemoveRect != prevRemoveRects[p]) reDeploy = true;

                prevCreateRects[p] = currCreateRect;
                prevRemoveRects[p] = currRemoveRect;
                prevCenters[p]     = currCenter;
            }

            //deploy
            if (!reDeploy)
            {
                return;
            }
            base.Deploy(prevCreateRects, prevRemoveRects, prevCenters, allowMove: true);
        }
			public void ToTexture (Texture2D texture=null, Color[] colors=null, float rangeMin=0, float rangeMax=1, bool resizeTexture=false)
			{
				//creating or resizing texture
				if (texture == null) texture = new Texture2D(rect.size.x, rect.size.z);
				if (resizeTexture) texture.Resize(rect.size.x, rect.size.z);
				
				//finding matrix-texture intersection
				Coord textureSize = new Coord(texture.width, texture.height);
				CoordRect textureRect = new CoordRect(new Coord(0,0), textureSize);
				CoordRect intersection = CoordRect.Intersect(textureRect, rect);
				
				//checking ref color array
				if (colors == null || colors.Length != intersection.size.x*intersection.size.z) colors = new Color[intersection.size.x*intersection.size.z];

				//filling texture
				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 val = this[x,z];

					//adjusting value to range
					val -= rangeMin;
					val /= rangeMax-rangeMin;

					//making color gradient
					float byteVal = val * 256;
					int flooredByteVal = (int)byteVal;
					float remainder = byteVal - flooredByteVal;

					float flooredVal = flooredByteVal/256f;
					float ceiledVal = (flooredByteVal+1)/256f;
					
					//saving to colors
					int tx = x-min.x; int tz = z-min.z;
					colors[tz*(max.x-min.x) + tx] = new Color(flooredVal, remainder>0.333f ? ceiledVal : flooredVal, remainder>0.666f ? ceiledVal : flooredVal);
				}
			
				texture.SetPixels(intersection.offset.x, intersection.offset.z, intersection.size.x, intersection.size.z, colors);
				texture.Apply();
			}
Ejemplo n.º 23
0
        public IEnumerator Apply(MapMagic.CoordRect rect, Terrain terrain, object dataBox, Func <float, bool> stop = null)
        {
            var wrapper        = terrain.gameObject.GetOrAddComponent <TerrainWrapper>();
            var MMTerrainLayer = wrapper.GetLayer <MMTerrainLayer>(LayerName, false, true);

            MMTerrainLayer.Trees.Clear();

            TupleSet <TreeInstance[], TreePrototype[]> treesTuple = (TupleSet <TreeInstance[], TreePrototype[]>)dataBox;
            var prototypeList = treesTuple.item2.ToList();

            for (int i = 0; i < treesTuple.item1.Length; i++)
            {
                var treeInstance = treesTuple.item1[i];
                var newTree      = new MadMapsTreeInstance(treeInstance, prototypeList);
                MMTerrainLayer.Trees.Add(newTree);
            }
            global::MapMagic.MapMagic.OnApplyCompleted -= MapMagicIntegrationUtilities.MapMagicOnOnApplyCompleted;
            global::MapMagic.MapMagic.OnApplyCompleted += MapMagicIntegrationUtilities.MapMagicOnOnApplyCompleted;
            wrapper.SetDirtyAbove(MMTerrainLayer);
            yield return(null);
        }
			public void WriteHeightmap (TerrainData data, float[,] array=null, float brushFallof=0.5f, bool delayLod=false)
			{
				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];
				}

				if (delayLod) data.SetHeightsDelayLOD(intersection.offset.x, intersection.offset.z, array);
				else data.SetHeights(intersection.offset.x, intersection.offset.z, array);
			}
Ejemplo n.º 25
0
		public static void Purge(CoordRect rect, Terrain terrain)
		{
			//switch back to standard material to purge
			//TODO: it's wrong, got to be filled with background layer

			// destroy created textures, etc..
			/*var mat = terrain.materialTemplate;
			if (mat != null)
			{
				Texture controlTex = mat.GetTexture("_SplatControl");
				Texture paramTex = mat.GetTexture("_SplatParams");
				if (controlTex != null)
				{
				   GameObject.Destroy(controlTex);
				}
				if (paramTex != null)
				{
				   GameObject.Destroy(paramTex);
				}
				GameObject.Destroy(mat);
			}*/
		}
Ejemplo n.º 26
0
		/*public void OverBlur (int iterations=20)
		{
			Matrix blurred = this.Clone(null);

			for (int i=1; i<=iterations; i++)
			{
				if (i==1 || i==2) blurred.Blur(step:1);
				else if (i==3) { blurred.Blur(step:1); blurred.Blur(step:1); }
				else blurred.Blur(step:i-2); //i:4, step:2

				for (int p=0; p<count; p++) 
				{
					float b = blurred.array[p] * i;
					float a = array[p];

					array[p] = a + b + a*b;
				}
			}
		}*/

		/*public void LossBlur (System.Func<float,float,float,float> blurFn=null, //prev, curr, next = output
			float intensity=0.666f, int step=1, Matrix reference=null, bool horizontal=true, bool vertical=true)
		{
			Coord min = rect.Min; Coord max = rect.Max;

			if (reference==null) reference = this;
			int lastX = max.x-1;
			int lastZ = max.z-1;

			if (horizontal)
			for (int z=min.z; z<=lastZ; z++)
			{
				float next = reference[min.x,z];
				float curr = next;
				float prev = next;

				float blurred = next;
				float lastBlurred = next;

				for (int x=min.x+step; x<=lastX; x+=step) 
				{
					//blurring
					if (blurFn==null) blurred = (prev+next)/2f;
					else blurred = blurFn(prev, curr, next);
					blurred = curr*(1-intensity) + blurred*intensity;

					//shifting values
					prev = curr; //this[x,z];
					curr = next; //this[x+step,z];
					try { next = reference[x+step*2,z]; } //this[x+step*2,z];
					catch { next = reference[lastX,z]; }

					//filling between-steps distance
					if (step==1) this[x,z] = blurred;
					else for (int i=0; i<step; i++) 
					{
						float percent = 1f * i / step;
						this[x-step+i,z] = blurred*percent + lastBlurred*(1-percent);
					}
					lastBlurred = blurred;
				}
			}

			if (vertical)
			for (int x=min.x; x<=lastX; x++)
			{
				float next = reference[x,min.z];
				float curr = next;
				float prev = next;

				float blurred = next;
				float lastBlurred = next;

				for (int z=min.z+step; z<=lastZ; z+=step) 
				{
					//blurring
					if (blurFn==null) blurred = (prev+next)/2f;
					else blurred = blurFn(prev, curr, next);
					blurred = curr*(1-intensity) + blurred*intensity;

					//shifting values
					prev = curr;
					curr = next;
					try { next = reference[x,z+step*2]; }
					catch { next = reference[x,lastZ]; }

					//filling between-steps distance
					if (step==1) this[x,z] = blurred;
					else for (int i=0; i<step; i++) 
					{
						float percent = 1f * i / step;
						this[x,z-step+i] = blurred*percent + lastBlurred*(1-percent);
					}
					lastBlurred = blurred;
				}
			}
		}*/
		#endregion

		#endregion

		#region Other

		/*public float GetOnWorldRect (Vector2 worldPos, Rect worldRect)
			{
				float relativeX = (worldPos.x - worldRect.x) / worldRect.width;
				float relativeZ = (worldPos.y - worldRect.y) / worldRect.height;
				int posX = Mathf.RoundToInt( relativeX*rect.size.x + rect.offset.x );
				int posZ = Mathf.RoundToInt( relativeZ*rect.size.z + rect.offset.z );
				posX = Mathf.Clamp(posX,rect.Min.x+1,rect.Max.x-1); posZ = Mathf.Clamp(posZ,rect.Min.z+1,rect.Max.z-1);

				return this[posX,posZ];
			}*/

			static public void BlendLayers (Matrix[] matrices, float[] opacity=null) //changes splatmaps in photoshop layered style so their summary value does not exceed 1
			{
				//finding any existing matrix
				int anyMatrixNum = -1;
				for (int i=0; i<matrices.Length; i++)
					if (matrices[i]!=null) { anyMatrixNum = i; break; }
				if (anyMatrixNum == -1) { Debug.LogError("No matrices were found to blend " + matrices.Length); return; }

				//finding rect
				CoordRect rect = matrices[anyMatrixNum].rect;

				//checking rect size
				#if WDEBUG
				for (int i=0; i<matrices.Length; i++)
					if (matrices[i]!=null && matrices[i].rect!=rect) { Debug.LogError("Matrix rect mismatch " + rect + " " + matrices[i].rect); return; }
				#endif

				int rectCount = rect.Count;
				for (int pos=0; pos<rectCount; pos++)
				{
					float sum = 0;
					for (int i=matrices.Length-1; i>=0; i--) //layer 0 is background, layer Length-1 is the top one
					{
						if (matrices[i] == null) continue;
						
						float val = matrices[i].array[pos];

						if (opacity != null) val *= opacity[i];
						
						float overly = sum + val - 1; 
						if (overly < 0) overly = 0; //faster then calling Math.Clamp
						if (overly > 1) overly = 1;

						matrices[i].array[pos] = val - overly;
						sum += val - overly;
					}
				}
			}
        public static IEnumerator Apply(CoordRect rect, Terrain terrain, object dataBox, Func <float, bool> stop = null)
        {
            Profiler.BeginSample("VS Apply");

                        #if VEGETATION_STUDIO
            //clear cache
            VegetationSystem vetSys = terrain.gameObject.GetComponentInChildren <VegetationSystem>();
            for (int i = 0; i < vetSys.VegetationCellList.Count; i++)
            {
                vetSys.VegetationCellList[i].ClearCache();
            }

            vetSys.UnityTerrainData = new UnityTerrainData(terrain, false, false);

            //refresh billboards
            BillboardSystem billboardSystem = vetSys.GetComponent <BillboardSystem>();
            billboardSystem.RefreshBillboards();

            Profiler.EndSample();
                        #endif

            yield return(null);
        }
Ejemplo n.º 28
0
        public void Purge(MapMagic.CoordRect rect, Terrain terrain)
        {
            //skipping if already purged
            if (terrain.terrainData.treeInstances.Length == 0)
            {
                return;
            }

            var wrapper = terrain.GetComponent <TerrainWrapper>();

            if (wrapper == null)
            {
                return;
            }
            var MMTerrainLayer = wrapper.GetLayer <MMTerrainLayer>(LayerName);

            if (MMTerrainLayer == null || MMTerrainLayer.Trees == null)
            {
                return;
            }
            MMTerrainLayer.Trees.Clear();
            wrapper.Dirty = true;
        }
Ejemplo n.º 29
0
			public void Deploy (Vector3[] poses, bool allowMove=true)
			{
				bool reDeploy = false;

				//number of cams changed
				if (prevCreateRects == null || prevCreateRects.Length != poses.Length || prevRemoveRects.Length != poses.Length) 
				{ 
					reDeploy = true; 
					prevCreateRects = new CoordRect[poses.Length];
					prevRemoveRects = new CoordRect[poses.Length];
					prevCenters = new Coord[poses.Length];
				}

				//checking guard arrays
				for (int p=0; p<poses.Length; p++)
				{
					Vector3 pos = poses[p];

					//finding rect and center
					CoordRect currCreateRect = pos.ToCoordRect(MapMagic.instance.generateRange, MapMagic.instance.terrainSize);
					CoordRect currRemoveRect = pos.ToCoordRect(MapMagic.instance.removeRange, MapMagic.instance.terrainSize);
					Coord currCenter = pos.RoundToCoord(MapMagic.instance.terrainSize);

					//checking a need to re-deploy
					if (currCreateRect != prevCreateRects[p]) reDeploy = true;
					//if (currRemoveRect != prevRemoveRects[p]) reDeploy = true;
					
					prevCreateRects[p] = currCreateRect;
					prevRemoveRects[p] = currRemoveRect;
					prevCenters[p] = currCenter;
				}

				//deploy
				if (!reDeploy) return;
				base.Deploy(prevCreateRects, prevRemoveRects, prevCenters, allowMove:allowMove);
			}
Ejemplo n.º 30
0
        public static void Purge(CoordRect rect, Terrain terrain)
        {
            //Purge is not used, output is purged derectly in GeneratorsAsset when turned off

            /*#if VOXELAND
             * //finding instance
             * foreach (Voxeland5.Voxeland v in Voxeland5.Voxeland.instances)
             * {
             *      if (v.data==null || v.data.generator==null || v.data.generator.mapMagicGens==null) continue;
             *
             *      int numGens = 0;
             *      foreach (VoxelandOutput gen in v.data.generator.mapMagicGens.GeneratorsOfType<VoxelandOutput>()) numGens++;
             *
             *      if (numGens==0)
             *      {
             *              //finding area by rect offset
             *              Coord areaCoord = Coord.PickCell(rect.offset.x, rect.offset.z, v.data.areaSize);
             *              Voxeland5.Data.Area area = v.data.areas[areaCoord.x, areaCoord.z];
             *
             *              area.ClearLand();
             *      }
             * }
             #endif*/
        }